]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Serial.pm
Place holds on issuances from the OPAC. Not backporting yet as it might be too
[working/Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / Serial.pm
1 #!/usr/bin/perl
2
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
16
17 =head1 NAME
18
19 OpenILS::Application::Serial - Performs serials-related tasks such as receiving issues and generating predictions
20
21 =head1 SYNOPSIS
22
23 TBD
24
25 =head1 DESCRIPTION
26
27 TBD
28
29 =head1 AUTHOR
30
31 Dan Wells, dbw2@calvin.edu
32
33 =cut
34
35 package OpenILS::Application::Serial;
36
37 use strict;
38 use warnings;
39
40
41 use OpenILS::Application;
42 use base qw/OpenILS::Application/;
43 use OpenILS::Application::AppUtils;
44 use OpenILS::Event;
45 use OpenSRF::AppSession;
46 use OpenSRF::Utils qw/:datetime/;
47 use OpenSRF::Utils::Logger qw/:logger/;
48 use OpenILS::Utils::CStoreEditor q/:funcs/;
49 use OpenILS::Utils::Fieldmapper;
50 use OpenILS::Utils::MFHD;
51 use MARC::File::XML (BinaryEncoding => 'utf8');
52 my $U = 'OpenILS::Application::AppUtils';
53 my @MFHD_NAMES = ('basic','supplement','index');
54 my %MFHD_NAMES_BY_TAG = (  '853' => $MFHD_NAMES[0],
55                         '863' => $MFHD_NAMES[0],
56                         '854' => $MFHD_NAMES[1],
57                         '864' => $MFHD_NAMES[1],
58                         '855' => $MFHD_NAMES[2],
59                         '865' => $MFHD_NAMES[2] );
60 my %MFHD_TAGS_BY_NAME = (  $MFHD_NAMES[0] => '853',
61                         $MFHD_NAMES[1] => '854',
62                         $MFHD_NAMES[2] => '855');
63 my $_strp_date = new DateTime::Format::Strptime(pattern => '%F');
64
65 # helper method for conforming dates to ISO8601
66 sub _cleanse_dates {
67     my $item = shift;
68     my $fields = shift;
69
70     foreach my $field (@$fields) {
71         $item->$field(OpenSRF::Utils::clense_ISO8601($item->$field)) if $item->$field;
72     }
73     return 0;
74 }
75
76 sub _get_mvr {
77     $U->simplereq(
78         "open-ils.search",
79         "open-ils.search.biblio.record.mods_slim.retrieve",
80         @_
81     );
82 }
83
84
85 ##########################################################################
86 # item methods
87 #
88 __PACKAGE__->register_method(
89     method    => 'fleshed_item_alter',
90     api_name  => 'open-ils.serial.item.fleshed.batch.update',
91     api_level => 1,
92     argc      => 2,
93     signature => {
94         desc     => 'Receives an array of one or more items and updates the database as needed',
95         'params' => [ {
96                  name => 'authtoken',
97                  desc => 'Authtoken for current user session',
98                  type => 'string'
99             },
100             {
101                  name => 'items',
102                  desc => 'Array of fleshed items',
103                  type => 'array'
104             }
105
106         ],
107         'return' => {
108             desc => 'Returns 1 if successful, event if failed',
109             type => 'mixed'
110         }
111     }
112 );
113
114 sub fleshed_item_alter {
115     my( $self, $conn, $auth, $items ) = @_;
116     return 1 unless ref $items;
117     my( $reqr, $evt ) = $U->checkses($auth);
118     return $evt if $evt;
119     my $editor = new_editor(requestor => $reqr, xact => 1);
120     my $override = $self->api_name =~ /override/;
121
122 # TODO: permission check
123 #        return $editor->event unless
124 #            $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
125
126     for my $item (@$items) {
127
128         my $itemid = $item->id;
129         $item->editor($editor->requestor->id);
130         $item->edit_date('now');
131
132         if( $item->isdeleted ) {
133             $evt = _delete_sitem( $editor, $override, $item);
134         } elsif( $item->isnew ) {
135             # TODO: reconsider this
136             # if the item has a new issuance, create the issuance first
137             if (ref $item->issuance eq 'Fieldmapper::serial::issuance' and $item->issuance->isnew) {
138                 fleshed_issuance_alter($self, $conn, $auth, [$item->issuance]);
139             }
140             _cleanse_dates($item, ['date_expected','date_received']);
141             $evt = _create_sitem( $editor, $item );
142         } else {
143             _cleanse_dates($item, ['date_expected','date_received']);
144             $evt = _update_sitem( $editor, $override, $item );
145         }
146     }
147
148     if( $evt ) {
149         $logger->info("fleshed item-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
150         $editor->rollback;
151         return $evt;
152     }
153     $logger->debug("item-alter: done updating item batch");
154     $editor->commit;
155     $logger->info("fleshed item-alter successfully updated ".scalar(@$items)." items");
156     return 1;
157 }
158
159 sub _delete_sitem {
160     my ($editor, $override, $item) = @_;
161     $logger->info("item-alter: delete item ".OpenSRF::Utils::JSON->perl2JSON($item));
162     return $editor->event unless $editor->delete_serial_item($item);
163     return 0;
164 }
165
166 sub _create_sitem {
167     my ($editor, $item) = @_;
168
169     $item->creator($editor->requestor->id);
170     $item->create_date('now');
171
172     $logger->info("item-alter: new item ".OpenSRF::Utils::JSON->perl2JSON($item));
173     return $editor->event unless $editor->create_serial_item($item);
174     return 0;
175 }
176
177 sub _update_sitem {
178     my ($editor, $override, $item) = @_;
179
180     $logger->info("item-alter: retrieving item ".$item->id);
181     my $orig_item = $editor->retrieve_serial_item($item->id);
182
183     $logger->info("item-alter: original item ".OpenSRF::Utils::JSON->perl2JSON($orig_item));
184     $logger->info("item-alter: updated item ".OpenSRF::Utils::JSON->perl2JSON($item));
185     return $editor->event unless $editor->update_serial_item($item);
186     return 0;
187 }
188
189 __PACKAGE__->register_method(
190     method  => "fleshed_serial_item_retrieve_batch",
191     authoritative => 1,
192     api_name    => "open-ils.serial.item.fleshed.batch.retrieve"
193 );
194
195 sub fleshed_serial_item_retrieve_batch {
196     my( $self, $client, $ids ) = @_;
197 # FIXME: permissions?
198     $logger->info("Fetching fleshed serial items @$ids");
199     return $U->cstorereq(
200         "open-ils.cstore.direct.serial.item.search.atomic",
201         { id => $ids },
202         { flesh => 2,
203           flesh_fields => {sitem => [ qw/issuance creator editor stream unit notes/ ], sstr => ["distribution"], sunit => ["call_number"], siss => [qw/creator editor subscription/]}
204         });
205 }
206
207
208 ##########################################################################
209 # issuance methods
210 #
211 __PACKAGE__->register_method(
212     method    => 'fleshed_issuance_alter',
213     api_name  => 'open-ils.serial.issuance.fleshed.batch.update',
214     api_level => 1,
215     argc      => 2,
216     signature => {
217         desc     => 'Receives an array of one or more issuances and updates the database as needed',
218         'params' => [ {
219                  name => 'authtoken',
220                  desc => 'Authtoken for current user session',
221                  type => 'string'
222             },
223             {
224                  name => 'issuances',
225                  desc => 'Array of fleshed issuances',
226                  type => 'array'
227             }
228
229         ],
230         'return' => {
231             desc => 'Returns 1 if successful, event if failed',
232             type => 'mixed'
233         }
234     }
235 );
236
237 sub fleshed_issuance_alter {
238     my( $self, $conn, $auth, $issuances ) = @_;
239     return 1 unless ref $issuances;
240     my( $reqr, $evt ) = $U->checkses($auth);
241     return $evt if $evt;
242     my $editor = new_editor(requestor => $reqr, xact => 1);
243     my $override = $self->api_name =~ /override/;
244
245 # TODO: permission support
246 #        return $editor->event unless
247 #            $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
248
249     for my $issuance (@$issuances) {
250         my $issuanceid = $issuance->id;
251         $issuance->editor($editor->requestor->id);
252         $issuance->edit_date('now');
253
254         if( $issuance->isdeleted ) {
255             $evt = _delete_siss( $editor, $override, $issuance);
256         } elsif( $issuance->isnew ) {
257             _cleanse_dates($issuance, ['date_published']);
258             $evt = _create_siss( $editor, $issuance );
259         } else {
260             _cleanse_dates($issuance, ['date_published']);
261             $evt = _update_siss( $editor, $override, $issuance );
262         }
263     }
264
265     if( $evt ) {
266         $logger->info("fleshed issuance-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
267         $editor->rollback;
268         return $evt;
269     }
270     $logger->debug("issuance-alter: done updating issuance batch");
271     $editor->commit;
272     $logger->info("fleshed issuance-alter successfully updated ".scalar(@$issuances)." issuances");
273     return 1;
274 }
275
276 sub _delete_siss {
277     my ($editor, $override, $issuance) = @_;
278     $logger->info("issuance-alter: delete issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
279     return $editor->event unless $editor->delete_serial_issuance($issuance);
280     return 0;
281 }
282
283 sub _create_siss {
284     my ($editor, $issuance) = @_;
285
286     $issuance->creator($editor->requestor->id);
287     $issuance->create_date('now');
288
289     $logger->info("issuance-alter: new issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
290     return $editor->event unless $editor->create_serial_issuance($issuance);
291     return 0;
292 }
293
294 sub _update_siss {
295     my ($editor, $override, $issuance) = @_;
296
297     $logger->info("issuance-alter: retrieving issuance ".$issuance->id);
298     my $orig_issuance = $editor->retrieve_serial_issuance($issuance->id);
299
300     $logger->info("issuance-alter: original issuance ".OpenSRF::Utils::JSON->perl2JSON($orig_issuance));
301     $logger->info("issuance-alter: updated issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
302     return $editor->event unless $editor->update_serial_issuance($issuance);
303     return 0;
304 }
305
306 __PACKAGE__->register_method(
307     method  => "fleshed_serial_issuance_retrieve_batch",
308     authoritative => 1,
309     api_name    => "open-ils.serial.issuance.fleshed.batch.retrieve"
310 );
311
312 sub fleshed_serial_issuance_retrieve_batch {
313     my( $self, $client, $ids ) = @_;
314 # FIXME: permissions?
315     $logger->info("Fetching fleshed serial issuances @$ids");
316     return $U->cstorereq(
317         "open-ils.cstore.direct.serial.issuance.search.atomic",
318         { id => $ids },
319         { flesh => 1,
320           flesh_fields => {siss => [ qw/creator editor subscription/ ]}
321         });
322 }
323
324 __PACKAGE__->register_method(
325     method  => "pub_fleshed_serial_issuance_retrieve_batch",
326     api_name    => "open-ils.serial.issuance.pub_fleshed.batch.retrieve",
327     signature => {
328         desc => q/
329             Public (i.e. OPAC) call for getting at the sub and 
330             ultimately the record entry from an issuance
331         /,
332         params => [{name => 'ids', desc => 'Array of IDs', type => 'array'}],
333         return => {
334             desc => q/
335                 issuance objects, fleshed with subscriptions
336             /,
337             class => 'siss'
338         }
339     }
340 );
341 sub pub_fleshed_serial_issuance_retrieve_batch {
342     my( $self, $client, $ids ) = @_;
343     return [] unless $ids and @$ids;
344     return new_editor()->search_serial_issuance([
345         { id => $ids },
346         { 
347             flesh => 1,
348             flesh_fields => {siss => [ qw/subscription/ ]}
349         }
350     ]);
351 }
352
353 sub received_siss_by_bib {
354     my $self = shift;
355     my $client = shift;
356     my $bib = shift;
357
358     my $args = shift || {};
359     $$args{order} ||= 'asc';
360
361     my $global = $$args{global} == 0 ? 0 : 1;
362
363     my $e = new_editor();
364     my $issuances = $e->json_query({
365         select  => {
366             siss => [
367                 $global ? { transform => "min", column => "id", aggregate => 1 } : "id",
368                 "label",
369                 "date_published"
370         ]},
371         from => {
372             ssub => {
373                 siss => {
374                     field => 'subscription',
375                     fkey  => 'id',
376                     join  => {
377                         sitem => {
378                             field  => 'issuance',
379                             fkey   => 'id',
380                             $$args{ou} ? ( join  => {
381                                 sstr => {
382                                     field => 'id',
383                                     fkey  => 'stream',
384                                     join  => {
385                                         sdist => {
386                                             field  => 'id',
387                                             fkey   => 'distribution'
388                                         }
389                                     }
390                                 }
391                             }) : ()
392                         }
393                     }
394                 }
395             }
396         },
397         where => {
398             '+ssub'  => { record_entry => $bib },
399             $$args{type} ? ( '+siss' => { 'holding_type' => $$args{type} } ) : (),
400             '+sitem' => {
401                 # XXX should we also take specific item statuses into account?
402                 date_received => { '!=' => undef },
403                 $$args{status} ? ( 'status' => $$args{status} ) : ()
404             },
405             $$args{ou} ? ( '+sdist' => {
406                 holding_lib => {
407                     'in' => $U->get_org_descendants($$args{ou}, $$args{depth})
408                 }
409             }) : ()
410         },
411         $$args{limit}  ? ( limit  => $$args{limit}  ) : (),
412         $$args{offset} ? ( offset => $$args{offset} ) : (),
413         order_by => [{ class => 'siss', field => 'date_published', direction => $$args{order} }],
414         distinct => 1
415     });
416
417     $client->respond($e->retrieve_serial_issuance($_->{id})) for @$issuances;
418     return undef;
419 }
420 __PACKAGE__->register_method(
421     method    => 'received_siss_by_bib',
422     api_name  => 'open-ils.serial.received_siss.retrieve.by_bib',
423     api_level => 1,
424     argc      => 1,
425     stream    => 1,
426     signature => {
427         desc   => 'Receives a Bib ID and other optional params and returns "siss" (issuance) objects',
428         params => [
429             {   name => 'bibid',
430                 desc => 'id of the bre to which the issuances belong',
431                 type => 'number'
432             },
433             {   name => 'args',
434                 desc =>
435 q/A hash of optional arguments.  Valid keys and their meanings:
436     global := If true, return only one representative version of a conceptual issuance regardless of the number of subscriptions, otherwise return all issuance objects meeting the requested criteria, including conceptual duplicates. Valid values are 0 (false) and 1 (true, default).
437     order  := date_published sort direction, either "asc" (chronological, default) or "desc" (reverse chronological)
438     limit  := Number of issuances to return.  Useful for paging results, or finding the oldest or newest
439     offset := Number of issuance to skip before returning results.  Useful for paging.
440     orgid  := OU id used to scope retrieval, based on distribution.holding_lib
441     depth  := OU depth used to range the scope of orgid
442     type   := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
443     status := Item status filter. Valid values are "Bindery", "Bound", "Claimed", "Discarded", "Expected", "Not Held", "Not Published" and "Received". Can be a scalar (one) or arrayref (one or more).
444 /
445             }
446         ]
447     }
448 );
449
450
451 sub scoped_bib_holdings_summary {
452     my $self = shift;
453     my $client = shift;
454     my $bibid = shift;
455     my $args = shift || {};
456
457     $args->{order} = 'asc';
458
459     my ($issuances) = $self->method_lookup('open-ils.serial.received_siss.retrieve.by_bib.atomic')->run( $bibid => $args );
460
461     # split into issuance type sets
462     my %type_blob = (basic => [], supplement => [], index => []);
463     push @{ $type_blob{ $_->holding_type } }, $_ for (@$issuances);
464
465     # generate a statement list for each type
466     my %statement_blob;
467     for my $type ( keys %type_blob ) {
468         my ($mfhd,$list) = _summarize_contents(new_editor(), $type_blob{$type});
469         $statement_blob{$type} = $list;
470     }
471
472     return \%statement_blob;
473 }
474 __PACKAGE__->register_method(
475     method    => 'scoped_bib_holdings_summary',
476     api_name  => 'open-ils.serial.bib.summary_statements',
477     api_level => 1,
478     argc      => 1,
479     signature => {
480         desc   => 'Receives a Bib ID and other optional params and returns set of holdings statements',
481         params => [
482             {   name => 'bibid',
483                 desc => 'id of the bre to which the issuances belong',
484                 type => 'number'
485             },
486             {   name => 'args',
487                 desc =>
488 q/A hash of optional arguments.  Valid keys and their meanings:
489     orgid  := OU id used to scope retrieval, based on distribution.holding_lib
490     depth  := OU depth used to range the scope of orgid
491     type   := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
492     status := Item status filter. Valid values are "Bindery", "Bound", "Claimed", "Discarded", "Expected", "Not Held", "Not Published" and "Received". Can be a scalar (one) or arrayref (one or more).
493 /
494             }
495         ]
496     }
497 );
498
499
500 ##########################################################################
501 # unit methods
502 #
503 __PACKAGE__->register_method(
504     method    => 'fleshed_sunit_alter',
505     api_name  => 'open-ils.serial.sunit.fleshed.batch.update',
506     api_level => 1,
507     argc      => 2,
508     signature => {
509         desc     => 'Receives an array of one or more Units and updates the database as needed',
510         'params' => [ {
511                  name => 'authtoken',
512                  desc => 'Authtoken for current user session',
513                  type => 'string'
514             },
515             {
516                  name => 'sunits',
517                  desc => 'Array of fleshed Units',
518                  type => 'array'
519             }
520
521         ],
522         'return' => {
523             desc => 'Returns 1 if successful, event if failed',
524             type => 'mixed'
525         }
526     }
527 );
528
529 sub fleshed_sunit_alter {
530     my( $self, $conn, $auth, $sunits ) = @_;
531     return 1 unless ref $sunits;
532     my( $reqr, $evt ) = $U->checkses($auth);
533     return $evt if $evt;
534     my $editor = new_editor(requestor => $reqr, xact => 1);
535     my $override = $self->api_name =~ /override/;
536
537 # TODO: permission support
538 #        return $editor->event unless
539 #            $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
540
541     for my $sunit (@$sunits) {
542         if( $sunit->isdeleted ) {
543             $evt = _delete_sunit( $editor, $override, $sunit );
544         } else {
545             $sunit->default_location( $sunit->default_location->id ) if ref $sunit->default_location;
546
547             if( $sunit->isnew ) {
548                 $evt = _create_sunit( $editor, $sunit );
549             } else {
550                 $evt = _update_sunit( $editor, $override, $sunit );
551             }
552         }
553     }
554
555     if( $evt ) {
556         $logger->info("fleshed sunit-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
557         $editor->rollback;
558         return $evt;
559     }
560     $logger->debug("sunit-alter: done updating sunit batch");
561     $editor->commit;
562     $logger->info("fleshed sunit-alter successfully updated ".scalar(@$sunits)." Units");
563     return 1;
564 }
565
566 sub _delete_sunit {
567     my ($editor, $override, $sunit) = @_;
568     $logger->info("sunit-alter: delete sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
569     return $editor->event unless $editor->delete_serial_unit($sunit);
570     return 0;
571 }
572
573 sub _create_sunit {
574     my ($editor, $sunit) = @_;
575
576     $logger->info("sunit-alter: new Unit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
577     return $editor->event unless $editor->create_serial_unit($sunit);
578     return 0;
579 }
580
581 sub _update_sunit {
582     my ($editor, $override, $sunit) = @_;
583
584     $logger->info("sunit-alter: retrieving sunit ".$sunit->id);
585     my $orig_sunit = $editor->retrieve_serial_unit($sunit->id);
586
587     $logger->info("sunit-alter: original sunit ".OpenSRF::Utils::JSON->perl2JSON($orig_sunit));
588     $logger->info("sunit-alter: updated sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
589     return $editor->event unless $editor->update_serial_unit($sunit);
590     return 0;
591 }
592
593 __PACKAGE__->register_method(
594         method  => "retrieve_unit_list",
595     authoritative => 1,
596         api_name        => "open-ils.serial.unit_list.retrieve"
597 );
598
599 sub retrieve_unit_list {
600
601         my( $self, $client, @sdist_ids ) = @_;
602
603         if(ref($sdist_ids[0])) { @sdist_ids = @{$sdist_ids[0]}; }
604
605         my $e = new_editor();
606
607     my $query = {
608         'select' => 
609             { 'sunit' => [ 'id', 'summary_contents', 'sort_key' ],
610               'sitem' => ['stream'],
611               'sstr' => ['distribution'],
612               'sdist' => [{'column' => 'label', 'alias' => 'sdist_label'}]
613             },
614         'from' =>
615             { 'sdist' =>
616                 { 'sstr' =>
617                     { 'join' =>
618                         { 'sitem' =>
619                             { 'join' => { 'sunit' => {} } }
620                         }
621                     }
622                 }
623             },
624         'distinct' => 'true',
625         'where' => { '+sdist' => {'id' => \@sdist_ids} },
626         'order_by' => [{'class' => 'sunit', 'field' => 'sort_key'}]
627     };
628
629     my $unit_list_entries = $e->json_query($query);
630     
631     my @entries;
632     foreach my $entry (@$unit_list_entries) {
633         my $value = {'sunit' => $entry->{id}, 'sstr' => $entry->{stream}, 'sdist' => $entry->{distribution}};
634         my $label = $entry->{summary_contents};
635         if (length($label) > 100) {
636             $label = substr($label, 0, 100) . '...'; # limited space in dropdown / menu
637         }
638         $label = "[$entry->{sdist_label}/$entry->{stream} #$entry->{id}] " . $label;
639         push (@entries, [$label, OpenSRF::Utils::JSON->perl2JSON($value)]);
640     }
641
642     return \@entries;
643 }
644
645
646
647 ##########################################################################
648 # predict and receive methods
649 #
650 __PACKAGE__->register_method(
651     method    => 'make_predictions',
652     api_name  => 'open-ils.serial.make_predictions',
653     api_level => 1,
654     argc      => 1,
655     signature => {
656         desc     => 'Receives an ssub id and populates the issuance and item tables',
657         'params' => [ {
658                  name => 'ssub_id',
659                  desc => 'Serial Subscription ID',
660                  type => 'int'
661             }
662         ]
663     }
664 );
665
666 sub make_predictions {
667     my ($self, $conn, $authtoken, $args) = @_;
668
669     my $editor = OpenILS::Utils::CStoreEditor->new();
670     my $ssub_id = $args->{ssub_id};
671     my $mfhd = MFHD->new(MARC::Record->new());
672
673     my $ssub = $editor->retrieve_serial_subscription([$ssub_id]);
674     my $scaps = $editor->search_serial_caption_and_pattern({ subscription => $ssub_id, active => 't'});
675     my $sdists = $editor->search_serial_distribution( [{ subscription => $ssub->id }, { flesh => 1, flesh_fields => {sdist => [ qw/ streams / ]} }] ); #TODO: 'deleted' support?
676
677     my $total_streams = 0;
678     foreach (@$sdists) {
679         $total_streams += scalar(@{$_->streams});
680     }
681     if ($total_streams < 1) {
682         $editor->disconnect;
683         # XXX TODO new event type
684         return new OpenILS::Event(
685             "BAD_PARAMS", note =>
686                 "There are no streams to direct items. Can't predict."
687         );
688     }
689
690     unless (@$scaps) {
691         $editor->disconnect;
692         # XXX TODO new event type
693         return new OpenILS::Event(
694             "BAD_PARAMS", note =>
695                 "There are no active caption-and-pattern objects associated " .
696                 "with this subscription. Can't predict."
697         );
698     }
699
700     my @predictions;
701     my $link_id = 1;
702     foreach my $scap (@$scaps) {
703         my $caption_field = _revive_caption($scap);
704         $caption_field->update('8' => $link_id);
705         $mfhd->append_fields($caption_field);
706         my $options = {
707                 'caption' => $caption_field,
708                 'scap_id' => $scap->id,
709                 'num_to_predict' => $args->{num_to_predict},
710                 'end_date' => defined $args->{end_date} ?
711                     $_strp_date->parse_datetime($args->{end_date}) : undef
712                 };
713         if ($args->{base_issuance}) { # predict from a given issuance
714             $options->{predict_from} = _revive_holding($args->{base_issuance}->holding_code, $caption_field, 1); # fresh MFHD Record, so we simply default to 1 for seqno
715         } else { # default to predicting from last published
716             my $last_published = $editor->search_serial_issuance([
717                     {'caption_and_pattern' => $scap->id,
718                     'subscription' => $ssub_id},
719                 {limit => 1, order_by => { siss => "date_published DESC" }}]
720                 );
721             if ($last_published->[0]) {
722                 my $last_siss = $last_published->[0];
723                 unless ($last_siss->holding_code) {
724                     $editor->disconnect;
725                     # XXX TODO new event type
726                     return new OpenILS::Event(
727                         "BAD_PARAMS", note =>
728                             "Last issuance has no holding code. Can't predict."
729                     );
730                 }
731                 $options->{predict_from} = _revive_holding($last_siss->holding_code, $caption_field, 1);
732             } else {
733                 $editor->disconnect;
734                 # XXX TODO make a new event type instead of hijacking this one
735                 return new OpenILS::Event(
736                     "BAD_PARAMS", note => "No issuance from which to predict!"
737                 );
738             }
739         }
740         push( @predictions, _generate_issuance_values($mfhd, $options) );
741         $link_id++;
742     }
743
744     my @issuances;
745     foreach my $prediction (@predictions) {
746         my $issuance = new Fieldmapper::serial::issuance;
747         $issuance->isnew(1);
748         $issuance->label($prediction->{label});
749         $issuance->date_published($prediction->{date_published}->strftime('%F'));
750         $issuance->holding_code(OpenSRF::Utils::JSON->perl2JSON($prediction->{holding_code}));
751         $issuance->holding_type($prediction->{holding_type});
752         $issuance->caption_and_pattern($prediction->{caption_and_pattern});
753         $issuance->subscription($ssub->id);
754         push (@issuances, $issuance);
755     }
756
757     fleshed_issuance_alter($self, $conn, $authtoken, \@issuances); # FIXME: catch events
758
759     my @items;
760     for (my $i = 0; $i < @issuances; $i++) {
761         my $date_expected = $predictions[$i]->{date_published}->add(seconds => interval_to_seconds($ssub->expected_date_offset))->strftime('%F');
762         my $issuance = $issuances[$i];
763         #$issuance->label(interval_to_seconds($ssub->expected_date_offset));
764         foreach my $sdist (@$sdists) {
765             my $streams = $sdist->streams;
766             foreach my $stream (@$streams) {
767                 my $item = new Fieldmapper::serial::item;
768                 $item->isnew(1);
769                 $item->stream($stream->id);
770                 $item->date_expected($date_expected);
771                 $item->issuance($issuance->id);
772                 push (@items, $item);
773             }
774         }
775     }
776     fleshed_item_alter($self, $conn, $authtoken, \@items); # FIXME: catch events
777     return \@items;
778 }
779
780 #
781 # _generate_issuance_values() is an initial attempt at a function which can be used
782 # to populate an issuance table with a list of predicted issues.  It accepts
783 # a hash ref of options initially defined as:
784 # caption : the caption field to predict on
785 # num_to_predict : the number of issues you wish to predict
786 # last_rec_date : the date of the last received issue, to be used as an offset
787 #                 for predicting future issues
788 #
789 # The basic method is to first convert to a single holding if compressed, then
790 # increment the holding and save the resulting values to @issuances.
791
792 # returns @issuance_values, an array of hashrefs containing (formatted
793 # label, formatted chronology date, formatted estimated arrival date, and an
794 # array ref of holding subfields as (key, value, key, value ...)) (not a hash
795 # to protect order and possible duplicate keys), and a holding type.
796 #
797 sub _generate_issuance_values {
798     my ($mfhd, $options) = @_;
799     my $caption = $options->{caption};
800     my $scap_id = $options->{scap_id};
801     my $num_to_predict = $options->{num_to_predict};
802     my $end_date = $options->{end_date};
803     my $predict_from = $options->{predict_from};   # issuance to predict from
804     #my $last_rec_date = $options->{last_rec_date};   # expected or actual
805
806     # TODO: add support for predicting serials with no chronology by passing in
807     # a last_pub_date option?
808
809
810 # Only needed for 'real' MFHD records, not our temp records
811 #    my $link_id = $caption->link_id;
812 #    if(!$predict_from) {
813 #        my $htag = $caption->tag;
814 #        $htag =~ s/^85/86/;
815 #        my @holdings = $mfhd->holdings($htag, $link_id);
816 #        my $last_holding = $holdings[-1];
817 #
818 #        #if ($last_holding->is_compressed) {
819 #        #    $last_holding->compressed_to_last; # convert to last in range
820 #        #}
821 #        $predict_from = $last_holding;
822 #    }
823 #
824
825     $predict_from->notes('public',  []);
826 # add a note marker for system use (?)
827     $predict_from->notes('private', ['AUTOGEN']);
828
829     my $pub_date;
830     my @issuance_values;
831     my @predictions = $mfhd->generate_predictions({'base_holding' => $predict_from, 'num_to_predict' => $num_to_predict, 'end_date' => $end_date});
832     foreach my $prediction (@predictions) {
833         $pub_date = $_strp_date->parse_datetime($prediction->chron_to_date);
834         push(
835                 @issuance_values,
836                 {
837                     #$link_id,
838                     label => $prediction->format,
839                     date_published => $pub_date,
840                     #date_expected => $date_expected->strftime('%F'),
841                     holding_code => [$prediction->indicator(1),$prediction->indicator(2),$prediction->subfields_list],
842                     holding_type => $MFHD_NAMES_BY_TAG{$caption->tag},
843                     caption_and_pattern => $scap_id
844                 }
845             );
846     }
847
848     return @issuance_values;
849 }
850
851 sub _revive_caption {
852     my $scap = shift;
853
854     my $pattern_code = $scap->pattern_code;
855
856     # build MARC::Field
857     my $pattern_parts = OpenSRF::Utils::JSON->JSON2perl($pattern_code);
858     unshift(@$pattern_parts, $MFHD_TAGS_BY_NAME{$scap->type});
859     my $pattern_field = new MARC::Field(@$pattern_parts);
860
861     # build MFHD::Caption
862     return new MFHD::Caption($pattern_field);
863 }
864
865 sub _revive_holding {
866     my $holding_code = shift;
867     my $caption_field = shift;
868     my $seqno = shift;
869
870     # build MARC::Field
871     my $holding_parts = OpenSRF::Utils::JSON->JSON2perl($holding_code);
872     my $captag = $caption_field->tag;
873     $captag =~ s/^85/86/;
874     unshift(@$holding_parts, $captag);
875     my $holding_field = new MARC::Field(@$holding_parts);
876
877     # build MFHD::Holding
878     return new MFHD::Holding($seqno, $holding_field, $caption_field);
879 }
880
881 __PACKAGE__->register_method(
882     method    => 'unitize_items',
883     api_name  => 'open-ils.serial.receive_items',
884     api_level => 1,
885     argc      => 1,
886     signature => {
887         desc     => 'Marks an item as received, updates the shelving unit (creating a new shelving unit if needed), and updates the summaries',
888         'params' => [ {
889                  name => 'items',
890                  desc => 'array of serial items',
891                  type => 'array'
892             },
893             {
894                  name => 'barcodes',
895                  desc => 'hash of item_ids => barcodes',
896                  type => 'hash'
897             }
898         ],
899         'return' => {
900             desc => 'Returns number of received items (num_items) and new unit ID, if applicable (new_unit_id)',
901             type => 'hashref'
902         }
903     }
904 );
905
906 __PACKAGE__->register_method(
907     method    => 'unitize_items',
908     api_name  => 'open-ils.serial.bind_items',
909     api_level => 1,
910     argc      => 1,
911     signature => {
912         desc     => 'Marks an item as bound, updates the shelving unit (creating a new shelving unit if needed)',
913         'params' => [ {
914                  name => 'items',
915                  desc => 'array of serial items',
916                  type => 'array'
917             },
918             {
919                  name => 'barcodes',
920                  desc => 'hash of item_ids => barcodes',
921                  type => 'hash'
922             }
923         ],
924         'return' => {
925             desc => 'Returns number of bound items (num_items) and new unit ID, if applicable (new_unit_id)',
926             type => 'hashref'
927         }
928     }
929 );
930
931 sub unitize_items {
932     my ($self, $conn, $auth, $items, $barcodes) = @_;
933
934     my( $reqr, $evt ) = $U->checkses($auth);
935     return $evt if $evt;
936     my $editor = new_editor(requestor => $reqr, xact => 1);
937     $self->api_name =~ /serial\.(\w*)_items/;
938     my $mode = $1;
939     
940     my %found_unit_ids;
941     my %found_stream_ids;
942     my %found_types;
943
944     my %stream_ids_by_unit_id;
945
946     my %unit_map;
947     my %sdist_by_unit_id;
948     my %sdist_by_stream_id;
949
950     my $new_unit_id; # id for '-2' units to share
951     foreach my $item (@$items) {
952         # for debugging only, TODO: delete
953         if (!ref $item) { # hopefully we got an id instead
954             $item = $editor->retrieve_serial_item($item);
955         }
956         # get ids
957         my $unit_id = ref($item->unit) ? $item->unit->id : $item->unit;
958         my $stream_id = ref($item->stream) ? $item->stream->id : $item->stream;
959         my $issuance_id = ref($item->issuance) ? $item->issuance->id : $item->issuance;
960         #TODO: evt on any missing ids
961
962         if ($mode eq 'receive') {
963             $item->date_received('now');
964             $item->status('Received');
965         } else {
966             $item->status('Bindery');
967         }
968
969         # check for types to trigger summary updates
970         my $scap;
971         if (!ref $item->issuance) {
972             my $scaps = $editor->search_serial_caption_and_pattern([{"+siss" => {"id" => $issuance_id}}, { "join" => {"siss" => {}} }]);
973             $scap = $scaps->[0];
974         } elsif (!ref $item->issuance->caption_and_pattern) {
975             $scap = $editor->retrieve_serial_caption_and_pattern($item->issuance->caption_and_pattern);
976         } else {
977             $scap = $editor->issuance->caption_and_pattern;
978         }
979         if (!exists($found_types{$stream_id})) {
980             $found_types{$stream_id} = {};
981         }
982         $found_types{$stream_id}->{$scap->type} = 1;
983
984         # create unit if needed
985         if ($unit_id == -1 or (!$new_unit_id and $unit_id == -2)) { # create unit per item
986             my $unit;
987             my $sdists = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
988             $unit = _build_unit($editor, $sdists->[0], $mode, 0, $barcodes->{$item->id});
989             # if _build_unit fails, $unit is an event, so return it
990             if ($U->event_code($unit)) {
991                 $editor->rollback;
992                 $unit->{"note"} = "Item ID: " . $item->id;
993                 return $unit;
994             }
995             my $evt =  _create_sunit($editor, $unit);
996             return $evt if $evt;
997             if ($unit_id == -2) {
998                 $new_unit_id = $unit->id;
999                 $unit_id = $new_unit_id;
1000             } else {
1001                 $unit_id = $unit->id;
1002             }
1003             $item->unit($unit_id);
1004             
1005             # get unit with 'DEFAULT's and save unit and sdist for later use
1006             $unit = $editor->retrieve_serial_unit($unit->id);
1007             $unit_map{$unit_id} = $unit;
1008             $sdist_by_unit_id{$unit_id} = $sdists->[0];
1009             $sdist_by_stream_id{$stream_id} = $sdists->[0];
1010         } elsif ($unit_id == -2) { # create one unit for all '-2' items
1011             $unit_id = $new_unit_id;
1012             $item->unit($unit_id);
1013         }
1014
1015         $found_unit_ids{$unit_id} = 1;
1016         $found_stream_ids{$stream_id} = 1;
1017
1018         # save the stream_id for this unit_id
1019         # TODO: prevent items from different streams in same unit? (perhaps in interface)
1020         $stream_ids_by_unit_id{$unit_id} = $stream_id;
1021
1022         my $evt = _update_sitem($editor, undef, $item);
1023         return $evt if $evt;
1024     }
1025
1026     # deal with unit level labels
1027     foreach my $unit_id (keys %found_unit_ids) {
1028
1029         # get all the needed issuances for unit
1030         my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"unit" => $unit_id, "status" => ["Received", "Bindery"]}}, {"join" => {"sitem" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1031         #TODO: evt on search failure
1032
1033         my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
1034
1035         # special case for single formatted_part (may have summarized version)
1036         if (@$formatted_parts == 1) {
1037             #TODO: MFHD.pm should have a 'format_summary' method for this
1038         }
1039
1040         # retrieve and update unit contents
1041         my $sunit;
1042         my $sdist;
1043
1044         # if we just created the unit, we will already have it and the distribution stored
1045         if (exists $unit_map{$unit_id}) {
1046             $sunit = $unit_map{$unit_id};
1047             $sdist = $sdist_by_unit_id{$unit_id};
1048         } else {
1049             $sunit = $editor->retrieve_serial_unit($unit_id);
1050             $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_ids_by_unit_id{$unit_id}}}, { "join" => {"sstr" => {}} }]);
1051             $sdist = $sdist->[0];
1052         }
1053
1054         $sunit->detailed_contents($sdist->unit_label_prefix . ' '
1055                     . join(', ', @$formatted_parts) . ' '
1056                     . $sdist->unit_label_suffix);
1057
1058         $sunit->summary_contents($sunit->detailed_contents); #TODO: change this when real summary contents are available
1059
1060         # create sort_key by left padding numbers to 6 digits
1061         my $sort_key = $sunit->detailed_contents;
1062         $sort_key =~ s/(\d+)/sprintf '%06d', $1/eg; # this may need improvement
1063         $sunit->sort_key($sort_key);
1064         
1065         if ($mode eq 'bind') {
1066             $sunit->status(2); # set to 'Bindery' status
1067         }
1068
1069         my $evt = _update_sunit($editor, undef, $sunit);
1070         return $evt if $evt;
1071     }
1072
1073     # cleanup 'dead' units (units which are now emptied of their items)
1074     my $dead_units = $editor->search_serial_unit([{'+sitem' => {'id' => undef}, 'deleted' => 'f'}, {'join' => {'sitem' => {'type' => 'left'}}}]);
1075     foreach my $unit (@$dead_units) {
1076         _delete_sunit($editor, undef, $unit);
1077     }
1078
1079     if ($mode eq 'receive') { # the summary holdings do not change when binding
1080         # deal with stream level summaries
1081         # summaries will be built from the "primary" stream only, that is, the stream with the lowest ID per distribution
1082         # (TODO: consider direct designation)
1083         my %primary_streams_by_sdist;
1084         my %streams_by_sdist;
1085
1086         # see if we have primary streams, and if so, associate them with their distributions
1087         foreach my $stream_id (keys %found_stream_ids) {
1088             my $sdist;
1089             if (exists $sdist_by_stream_id{$stream_id}) {
1090                 $sdist = $sdist_by_stream_id{$stream_id};
1091             } else {
1092                 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
1093                 $sdist = $sdist->[0];
1094             }
1095             my $streams;
1096             if (!exists($streams_by_sdist{$sdist->id})) {
1097                 $streams = $editor->search_serial_stream([{"distribution" => $sdist->id}, {"order_by" => {"sstr" => "id"}}]);
1098                 $streams_by_sdist{$sdist->id} = $streams;
1099             } else {
1100                 $streams = $streams_by_sdist{$sdist->id};
1101             }
1102             $primary_streams_by_sdist{$sdist->id} = $streams->[0] if ($stream_id == $streams->[0]->id);
1103         }
1104
1105         # retrieve and update summaries for each affected primary stream's distribution
1106         foreach my $sdist_id (keys %primary_streams_by_sdist) {
1107             my $stream = $primary_streams_by_sdist{$sdist_id};
1108             my $stream_id = $stream->id;
1109             # get all the needed issuances for stream
1110             # FIXME: search in Bindery/Bound/Not Published? as well as Received
1111             foreach my $type (keys %{$found_types{$stream_id}}) {
1112                 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"stream" => $stream_id, "status" => "Received"}, "+scap" => {"type" => $type}}, {"join" => {"sitem" => {}, "scap" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1113                 #TODO: evt on search failure
1114
1115                 my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
1116
1117                 # retrieve and update the generated_coverage of the summary
1118                 my $search_method = "search_serial_${type}_summary";
1119                 my $summary = $editor->$search_method([{"distribution" => $sdist_id}]);
1120                 $summary = $summary->[0];
1121                 $summary->generated_coverage(join(', ', @$formatted_parts));
1122                 my $update_method = "update_serial_${type}_summary";
1123                 return $editor->event unless $editor->$update_method($summary);
1124             }
1125         }
1126     }
1127
1128     $editor->commit;
1129     return {'num_items' => scalar @$items, 'new_unit_id' => $new_unit_id};
1130 }
1131
1132 sub _find_or_create_call_number {
1133     my ($e, $lib, $cn_string, $record) = @_;
1134
1135     my $existing = $e->search_asset_call_number({
1136         "owning_lib" => $lib,
1137         "label" => $cn_string,
1138         "record" => $record,
1139         "deleted" => "f"
1140     }) or return $e->die_event;
1141
1142     if (@$existing) {
1143         return $existing->[0]->id;
1144     } else {
1145         return $e->die_event unless
1146             $e->allowed("CREATE_VOLUME", $lib);
1147
1148         my $acn = new Fieldmapper::asset::call_number;
1149
1150         $acn->creator($e->requestor->id);
1151         $acn->editor($e->requestor->id);
1152         $acn->record($record);
1153         $acn->label($cn_string);
1154         $acn->owning_lib($lib);
1155
1156         $e->create_asset_call_number($acn) or return $e->die_event;
1157         return $e->data->id;
1158     }
1159 }
1160
1161 sub _issuances_received {
1162     # XXX TODO: Add some caching or something. This is getting called
1163     # more often than it has to be.
1164     my ($e, $sitem) = @_;
1165
1166     my $results = $e->json_query({
1167         "select" => {"sitem" => ["issuance"]},
1168         "from" => {"sitem" => {"sstr" => {}, "siss" => {}}},
1169         "where" => {
1170             "+sstr" => {"distribution" => $sitem->stream->distribution->id},
1171             "+siss" => {"holding_type" => $sitem->issuance->holding_type},
1172             "+sitem" => {"date_received" => {"!=" => undef}}
1173         },
1174         "order_by" => {
1175             "siss" => {"date_published" => {"direction" => "asc"}}
1176         }
1177     }) or return $e->die_event;
1178
1179     my $uniq = +{map { $_->{"issuance"} => 1 } @$results};
1180     return [ map { $e->retrieve_serial_issuance($_) } keys %$uniq ];
1181 }
1182
1183 # XXX _prepare_unit_label() duplicates some code from unitize_items().
1184 # Hopefully we can unify code paths down the road.
1185 sub _prepare_unit_label {
1186     my ($e, $sunit, $sdist, $issuance) = @_;
1187
1188     my ($mfhd, $formatted_parts) = _summarize_contents($e, [$issuance]);
1189
1190     # special case for single formatted_part (may have summarized version)
1191     if (@$formatted_parts == 1) {
1192         #TODO: MFHD.pm should have a 'format_summary' method for this
1193     }
1194
1195     $sunit->detailed_contents(
1196         join(
1197             " ",
1198             $sdist->unit_label_prefix,
1199             join(", ", @$formatted_parts),
1200             $sdist->unit_label_suffix
1201         )
1202     );
1203
1204     # TODO: change this when real summary contents are available
1205     $sunit->summary_contents($sunit->detailed_contents);
1206
1207     # Create sort_key by left padding numbers to 6 digits.
1208     (my $sort_key = $sunit->detailed_contents) =~
1209         s/(\d+)/sprintf '%06d', $1/eg;
1210     $sunit->sort_key($sort_key);
1211 }
1212
1213 # XXX duplicates a block of code from unitize_items().  Once I fully understand
1214 # what's going on and I'm sure it's working right, I'd like to have
1215 # unitize_items() just use this, keeping the logic in one place.
1216 sub _prepare_summaries {
1217     my ($e, $sitem, $issuances) = @_;
1218
1219     my $dist_id = $sitem->stream->distribution->id;
1220     my $type = $sitem->issuance->holding_type;
1221
1222     # Make sure @$issuances contains the new issuance from sitem.
1223     unless (grep { $_->id == $sitem->issuance->id } @$issuances) {
1224         push @$issuances, $sitem->issuance;
1225     }
1226
1227     my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances);
1228
1229     my $search_method = "search_serial_${type}_summary";
1230     my $summary = $e->$search_method([{"distribution" => $dist_id}]);
1231
1232     my $cu_method = "update";
1233
1234     if (@$summary) {
1235         $summary = $summary->[0];
1236     } else {
1237         my $class = "Fieldmapper::serial::${type}_summary";
1238         $summary = $class->new;
1239         $summary->distribution($dist_id);
1240         $cu_method = "create";
1241     }
1242
1243     $summary->generated_coverage(join(", ", @$formatted_parts));
1244     my $method = "${cu_method}_serial_${type}_summary";
1245     return $e->die_event unless $e->$method($summary);
1246 }
1247
1248 sub _unit_by_iss_and_str {
1249     my ($e, $issuance, $stream) = @_;
1250
1251     my $unit = $e->json_query({
1252         "select" => {"sunit" => ["id"]},
1253         "from" => {"sitem" => {"sunit" => {}}},
1254         "where" => {
1255             "+sitem" => {
1256                 "issuance" => $issuance->id,
1257                 "stream" => $stream->id
1258             }
1259         }
1260     }) or return $e->die_event;
1261
1262     $e->retrieve_serial_unit($unit->[0]->{"id"}) or $e->die_event;
1263 }
1264
1265 sub move_previous_unit {
1266     my ($e, $prev_iss, $curr_item, $new_loc) = @_;
1267
1268     my $prev_unit = _unit_by_iss_and_str($e,$prev_iss,$curr_item->stream);
1269     return $prev_unit if defined $U->event_code($prev_unit);
1270
1271     if ($prev_unit->location != $new_loc) {
1272         $prev_unit->location($new_loc);
1273         $e->update_serial_unit($prev_unit) or return $e->die_event;
1274     }
1275     0;
1276 }
1277
1278 # _previous_issuance() assumes $existing is an ordered array
1279 sub _previous_issuance {
1280     my ($existing, $issuance) = @_;
1281
1282     my $last = $existing->[-1];
1283     return undef unless $last;
1284     return ($last->id == $issuance->id ? $existing->[-2] : $last);
1285 }
1286
1287 __PACKAGE__->register_method(
1288     "method" => "receive_items_one_unit_per",
1289     "api_name" => "open-ils.serial.receive_items.one_unit_per",
1290     "stream" => 1,
1291     "api_level" => 1,
1292     "argc" => 3,
1293     "signature" => {
1294         "desc" => "Marks items in a list as received, creates a new unit for each item if any unit is fleshed on, and updates summaries as needed",
1295         "params" => [
1296             {
1297                  "name" => "auth",
1298                  "desc" => "authtoken",
1299                  "type" => "string"
1300             },
1301             {
1302                  "name" => "items",
1303                  "desc" => "array of serial items, possibly fleshed with units and definitely fleshed with stream->distribution",
1304                  "type" => "array"
1305             },
1306             {
1307                 "name" => "record",
1308                 "desc" => "id of bib record these items are associated with
1309                     (XXX could/should be derived from items)",
1310                 "type" => "number"
1311             }
1312         ],
1313         "return" => {
1314             "desc" => "The item ID for each item successfully received",
1315             "type" => "int"
1316         }
1317     }
1318 );
1319
1320 sub receive_items_one_unit_per {
1321     # XXX This function may be temporary, as it does some of what
1322     # unitize_items() does, just in a different way.
1323     my ($self, $client, $auth, $items, $record) = @_;
1324
1325     my $e = new_editor("authtoken" => $auth, "xact" => 1);
1326     return $e->die_event unless $e->checkauth;
1327     return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
1328
1329     my $prev_loc_setting_map = {};
1330     my $user_id = $e->requestor->id;
1331
1332     # Get a list of all the non-virtual field names in a serial::unit for
1333     # merging given unit objects with template-built units later.
1334     # XXX move this somewhere global so it isn't re-run all the time
1335     my $all_unit_fields =
1336         $Fieldmapper::fieldmap->{"Fieldmapper::serial::unit"}->{"fields"};
1337     my @real_unit_fields = grep {
1338         not $all_unit_fields->{$_}->{"virtual"}
1339     } keys %$all_unit_fields;
1340
1341     foreach my $item (@$items) {
1342         # Note that we expect a certain fleshing on the items we're getting.
1343         my $sdist = $item->stream->distribution;
1344
1345         # Fetch a list of issuances with received copies already existing
1346         # on this distribution (and with the same holding type on the
1347         # issuance).  This will be used in up to two places: once when building
1348         # a summary, once when changing the copy location of the previous
1349         # issuance's copy.
1350         my $issuances_received = _issuances_received($e, $item);
1351         if ($U->event_code($issuances_received)) {
1352             $e->rollback;
1353             return $issuances_received;
1354         }
1355
1356         # Find out if we need to to deal with previous copy location changing.
1357         my $ou = $sdist->holding_lib->id;
1358         unless (exists $prev_loc_setting_map->{$ou}) {
1359             $prev_loc_setting_map->{$ou} = $U->ou_ancestor_setting_value(
1360                 $ou, "serial.prev_issuance_copy_location", $e
1361             );
1362         }
1363
1364         # If there is a previous copy location setting, we need the previous
1365         # issuance, from which we can in turn look up the item attached to the
1366         # same stream we're on now.
1367         if ($prev_loc_setting_map->{$ou}) {
1368             if (my $prev_iss =
1369                 _previous_issuance($issuances_received, $item->issuance)) {
1370
1371                 # Now we can change the copy location of the previous unit,
1372                 # if needed.
1373                 return $e->event if defined $U->event_code(
1374                     move_previous_unit(
1375                         $e, $prev_iss, $item, $prev_loc_setting_map->{$ou}
1376                     )
1377                 );
1378             }
1379         }
1380
1381         # Create unit if given by user
1382         if (ref $item->unit) {
1383             # detach from the item, as we need to create separately
1384             my $user_unit = $item->unit;
1385
1386             # get a unit based on associated template
1387             my $template_unit = _build_unit($e, $sdist, "receive", 1);
1388             if ($U->event_code($template_unit)) {
1389                 $e->rollback;
1390                 $template_unit->{"note"} = "Item ID: " . $item->id;
1391                 return $template_unit;
1392             }
1393
1394             # merge built unit with provided unit from user
1395             foreach (@real_unit_fields) {
1396                 unless ($user_unit->$_) {
1397                     $user_unit->$_($template_unit->$_);
1398                 }
1399             }
1400
1401             # Treat call number specially: the provided value from the
1402             # user will really be a string.
1403             if ($user_unit->call_number) {
1404                 my $real_cn = _find_or_create_call_number(
1405                     $e, $sdist->holding_lib->id,
1406                     $user_unit->call_number, $record
1407                 );
1408
1409                 if ($U->event_code($real_cn)) {
1410                     $e->rollback;
1411                     return $real_cn;
1412                 } else {
1413                     $user_unit->call_number($real_cn);
1414                 }
1415             }
1416
1417             my $evt = _prepare_unit_label(
1418                 $e, $user_unit, $sdist, $item->issuance
1419             );
1420             if ($U->event_code($evt)) {
1421                 $e->rollback;
1422                 return $evt;
1423             }
1424
1425             # create/update summary objects related to this distribution
1426             $evt = _prepare_summaries($e, $item, $issuances_received);
1427             if ($U->event_code($evt)) {
1428                 $e->rollback;
1429                 return $evt;
1430             }
1431
1432             # set the incontrovertibles on the unit
1433             $user_unit->edit_date("now");
1434             $user_unit->create_date("now");
1435             $user_unit->editor($user_id);
1436             $user_unit->creator($user_id);
1437
1438             return $e->die_event unless $e->create_serial_unit($user_unit);
1439
1440             # save reference to new unit
1441             $item->unit($e->data->id);
1442         }
1443
1444         # Create notes if given by user
1445         if (ref($item->notes) and @{$item->notes}) {
1446             foreach my $note (@{$item->notes}) {
1447                 $note->creator($user_id);
1448                 $note->create_date("now");
1449
1450                 return $e->die_event unless $e->create_serial_item_note($note);
1451             }
1452
1453             $item->clear_notes; # They're saved; we no longer want them here.
1454         }
1455
1456         # Set the incontrovertibles on the item
1457         $item->status("Received");
1458         $item->date_received("now");
1459         $item->edit_date("now");
1460         $item->editor($user_id);
1461
1462         return $e->die_event unless $e->update_serial_item($item);
1463
1464         # send client a response
1465         $client->respond($item->id);
1466     }
1467
1468     $e->commit or return $e->die_event;
1469     undef;
1470 }
1471
1472 sub _build_unit {
1473     my $editor = shift;
1474     my $sdist = shift;
1475     my $mode = shift;
1476     my $skip_call_number = shift;
1477     my $barcode = shift;
1478
1479     my $attr = $mode . '_unit_template';
1480     my $template = $editor->retrieve_asset_copy_template($sdist->$attr) or
1481         return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_COPY_TEMPLATE");
1482
1483     my @parts = qw( status location loan_duration fine_level age_protect circulate deposit ref holdable deposit_amount price circ_modifier circ_as_type alert_message opac_visible floating mint_condition );
1484
1485     my $unit = new Fieldmapper::serial::unit;
1486     foreach my $part (@parts) {
1487         my $value = $template->$part;
1488         next if !defined($value);
1489         $unit->$part($value);
1490     }
1491
1492     # ignore circ_lib in template, set to distribution holding_lib
1493     $unit->circ_lib($sdist->holding_lib);
1494     $unit->creator($editor->requestor->id);
1495     $unit->editor($editor->requestor->id);
1496
1497     unless ($skip_call_number) {
1498         $attr = $mode . '_call_number';
1499         my $cn = $sdist->$attr or
1500             return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_CALL_NUMBER");
1501
1502         $unit->call_number($cn);
1503     }
1504
1505     if ($barcode) {
1506         $unit->barcode($barcode);
1507     } else {
1508         $unit->barcode('AUTO');
1509     }
1510     $unit->sort_key('');
1511     $unit->summary_contents('');
1512     $unit->detailed_contents('');
1513
1514     return $unit;
1515 }
1516
1517
1518 sub _summarize_contents {
1519     my $editor = shift;
1520     my $issuances = shift;
1521
1522     # create MFHD record
1523     my $mfhd = MFHD->new(MARC::Record->new());
1524     my %scaps;
1525     my %scap_fields;
1526     my @scap_fields_ordered;
1527     my $seqno = 1;
1528     my $link_id = 1;
1529     foreach my $issuance (@$issuances) {
1530         my $scap_id = $issuance->caption_and_pattern;
1531         next if (!$scap_id); # skip issuances with no caption/pattern
1532
1533         my $scap;
1534         my $scap_field;
1535         # if this is the first appearance of this scap, retrieve it and add it to the temporary record
1536         if (!exists $scaps{$issuance->caption_and_pattern}) {
1537             $scaps{$scap_id} = $editor->retrieve_serial_caption_and_pattern($scap_id);
1538             $scap = $scaps{$scap_id};
1539             $scap_field = _revive_caption($scap);
1540             $scap_fields{$scap_id} = $scap_field;
1541             push(@scap_fields_ordered, $scap_field);
1542             $scap_field->update('8' => $link_id);
1543             $mfhd->append_fields($scap_field);
1544             $link_id++;
1545         } else {
1546             $scap = $scaps{$scap_id};
1547             $scap_field = $scap_fields{$scap_id};
1548         }
1549
1550         $mfhd->append_fields(_revive_holding($issuance->holding_code, $scap_field, $seqno));
1551         $seqno++;
1552     }
1553
1554     my @formatted_parts;
1555     foreach my $scap_field (@scap_fields_ordered) { #TODO: use generic MFHD "summarize" method, once available
1556        my @updated_holdings = $mfhd->get_compressed_holdings($scap_field);
1557        foreach my $holding (@updated_holdings) {
1558            push(@formatted_parts, $holding->format);
1559        }
1560     }
1561
1562     return ($mfhd, \@formatted_parts);
1563 }
1564
1565 ##########################################################################
1566 # note methods
1567 #
1568 __PACKAGE__->register_method(
1569     method      => 'fetch_notes',
1570     api_name        => 'open-ils.serial.item_note.retrieve.all',
1571     signature   => q/
1572         Returns an array of copy note objects.  
1573         @param args A named hash of parameters including:
1574             authtoken   : Required if viewing non-public notes
1575             item_id      : The id of the item whose notes we want to retrieve
1576             pub         : True if all the caller wants are public notes
1577         @return An array of note objects
1578     /
1579 );
1580
1581 __PACKAGE__->register_method(
1582     method      => 'fetch_notes',
1583     api_name        => 'open-ils.serial.subscription_note.retrieve.all',
1584     signature   => q/
1585         Returns an array of copy note objects.  
1586         @param args A named hash of parameters including:
1587             authtoken       : Required if viewing non-public notes
1588             subscription_id : The id of the item whose notes we want to retrieve
1589             pub             : True if all the caller wants are public notes
1590         @return An array of note objects
1591     /
1592 );
1593
1594 __PACKAGE__->register_method(
1595     method      => 'fetch_notes',
1596     api_name        => 'open-ils.serial.distribution_note.retrieve.all',
1597     signature   => q/
1598         Returns an array of copy note objects.  
1599         @param args A named hash of parameters including:
1600             authtoken       : Required if viewing non-public notes
1601             distribution_id : The id of the item whose notes we want to retrieve
1602             pub             : True if all the caller wants are public notes
1603         @return An array of note objects
1604     /
1605 );
1606
1607 # TODO: revisit this method to consider replacing cstore direct calls
1608 sub fetch_notes {
1609     my( $self, $connection, $args ) = @_;
1610     
1611     $self->api_name =~ /serial\.(\w*)_note/;
1612     my $type = $1;
1613
1614     my $id = $$args{object_id};
1615     my $authtoken = $$args{authtoken};
1616     my( $r, $evt);
1617
1618     if( $$args{pub} ) {
1619         return $U->cstorereq(
1620             'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic',
1621             { $type => $id, pub => 't' } );
1622     } else {
1623         # FIXME: restore perm check
1624         # ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
1625         # return $evt if $evt;
1626         return $U->cstorereq(
1627             'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic', {$type => $id} );
1628     }
1629
1630     return undef;
1631 }
1632
1633 __PACKAGE__->register_method(
1634     method      => 'create_note',
1635     api_name        => 'open-ils.serial.item_note.create',
1636     signature   => q/
1637         Creates a new item note
1638         @param authtoken The login session key
1639         @param note The note object to create
1640         @return The id of the new note object
1641     /
1642 );
1643
1644 __PACKAGE__->register_method(
1645     method      => 'create_note',
1646     api_name        => 'open-ils.serial.subscription_note.create',
1647     signature   => q/
1648         Creates a new subscription note
1649         @param authtoken The login session key
1650         @param note The note object to create
1651         @return The id of the new note object
1652     /
1653 );
1654
1655 __PACKAGE__->register_method(
1656     method      => 'create_note',
1657     api_name        => 'open-ils.serial.distribution_note.create',
1658     signature   => q/
1659         Creates a new distribution note
1660         @param authtoken The login session key
1661         @param note The note object to create
1662         @return The id of the new note object
1663     /
1664 );
1665
1666 sub create_note {
1667     my( $self, $connection, $authtoken, $note ) = @_;
1668
1669     $self->api_name =~ /serial\.(\w*)_note/;
1670     my $type = $1;
1671
1672     my $e = new_editor(xact=>1, authtoken=>$authtoken);
1673     return $e->event unless $e->checkauth;
1674
1675     # FIXME: restore permission support
1676 #    my $item = $e->retrieve_serial_item(
1677 #        [
1678 #            $note->item
1679 #        ]
1680 #    );
1681 #
1682 #    return $e->event unless
1683 #        $e->allowed('CREATE_COPY_NOTE', $item->call_number->owning_lib);
1684
1685     $note->create_date('now');
1686     $note->creator($e->requestor->id);
1687     $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
1688     $note->clear_id;
1689
1690     my $method = "create_serial_${type}_note";
1691     $e->$method($note) or return $e->event;
1692     $e->commit;
1693     return $note->id;
1694 }
1695
1696 __PACKAGE__->register_method(
1697     method      => 'delete_note',
1698     api_name        =>  'open-ils.serial.item_note.delete',
1699     signature   => q/
1700         Deletes an existing item note
1701         @param authtoken The login session key
1702         @param noteid The id of the note to delete
1703         @return 1 on success - Event otherwise.
1704         /
1705 );
1706
1707 __PACKAGE__->register_method(
1708     method      => 'delete_note',
1709     api_name        =>  'open-ils.serial.subscription_note.delete',
1710     signature   => q/
1711         Deletes an existing subscription note
1712         @param authtoken The login session key
1713         @param noteid The id of the note to delete
1714         @return 1 on success - Event otherwise.
1715         /
1716 );
1717
1718 __PACKAGE__->register_method(
1719     method      => 'delete_note',
1720     api_name        =>  'open-ils.serial.distribution_note.delete',
1721     signature   => q/
1722         Deletes an existing distribution note
1723         @param authtoken The login session key
1724         @param noteid The id of the note to delete
1725         @return 1 on success - Event otherwise.
1726         /
1727 );
1728
1729 sub delete_note {
1730     my( $self, $conn, $authtoken, $noteid ) = @_;
1731
1732     $self->api_name =~ /serial\.(\w*)_note/;
1733     my $type = $1;
1734
1735     my $e = new_editor(xact=>1, authtoken=>$authtoken);
1736     return $e->die_event unless $e->checkauth;
1737
1738     my $method = "retrieve_serial_${type}_note";
1739     my $note = $e->$method([
1740         $noteid,
1741     ]) or return $e->die_event;
1742
1743 # FIXME: restore permissions check
1744 #    if( $note->creator ne $e->requestor->id ) {
1745 #        return $e->die_event unless
1746 #            $e->allowed('DELETE_COPY_NOTE', $note->item->call_number->owning_lib);
1747 #    }
1748
1749     $method = "delete_serial_${type}_note";
1750     $e->$method($note) or return $e->die_event;
1751     $e->commit;
1752     return 1;
1753 }
1754
1755
1756 ##########################################################################
1757 # subscription methods
1758 #
1759 __PACKAGE__->register_method(
1760     method    => 'fleshed_ssub_alter',
1761     api_name  => 'open-ils.serial.subscription.fleshed.batch.update',
1762     api_level => 1,
1763     argc      => 2,
1764     signature => {
1765         desc     => 'Receives an array of one or more subscriptions and updates the database as needed',
1766         'params' => [ {
1767                  name => 'authtoken',
1768                  desc => 'Authtoken for current user session',
1769                  type => 'string'
1770             },
1771             {
1772                  name => 'subscriptions',
1773                  desc => 'Array of fleshed subscriptions',
1774                  type => 'array'
1775             }
1776
1777         ],
1778         'return' => {
1779             desc => 'Returns 1 if successful, event if failed',
1780             type => 'mixed'
1781         }
1782     }
1783 );
1784
1785 sub fleshed_ssub_alter {
1786     my( $self, $conn, $auth, $ssubs ) = @_;
1787     return 1 unless ref $ssubs;
1788     my( $reqr, $evt ) = $U->checkses($auth);
1789     return $evt if $evt;
1790     my $editor = new_editor(requestor => $reqr, xact => 1);
1791     my $override = $self->api_name =~ /override/;
1792
1793 # TODO: permission check
1794 #        return $editor->event unless
1795 #            $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
1796
1797     for my $ssub (@$ssubs) {
1798
1799         my $ssubid = $ssub->id;
1800
1801         if( $ssub->isdeleted ) {
1802             $evt = _delete_ssub( $editor, $override, $ssub);
1803         } elsif( $ssub->isnew ) {
1804             _cleanse_dates($ssub, ['start_date','end_date']);
1805             $evt = _create_ssub( $editor, $ssub );
1806         } else {
1807             _cleanse_dates($ssub, ['start_date','end_date']);
1808             $evt = _update_ssub( $editor, $override, $ssub );
1809         }
1810     }
1811
1812     if( $evt ) {
1813         $logger->info("fleshed subscription-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
1814         $editor->rollback;
1815         return $evt;
1816     }
1817     $logger->debug("subscription-alter: done updating subscription batch");
1818     $editor->commit;
1819     $logger->info("fleshed subscription-alter successfully updated ".scalar(@$ssubs)." subscriptions");
1820     return 1;
1821 }
1822
1823 sub _delete_ssub {
1824     my ($editor, $override, $ssub) = @_;
1825     $logger->info("subscription-alter: delete subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1826     my $sdists = $editor->search_serial_distribution(
1827             { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1828     my $cps = $editor->search_serial_caption_and_pattern(
1829             { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1830     my $sisses = $editor->search_serial_issuance(
1831             { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1832     return OpenILS::Event->new(
1833             'SERIAL_SUBSCRIPTION_NOT_EMPTY', payload => $ssub->id ) if (@$sdists or @$cps or @$sisses);
1834
1835     return $editor->event unless $editor->delete_serial_subscription($ssub);
1836     return 0;
1837 }
1838
1839 sub _create_ssub {
1840     my ($editor, $ssub) = @_;
1841
1842     $logger->info("subscription-alter: new subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1843     return $editor->event unless $editor->create_serial_subscription($ssub);
1844     return 0;
1845 }
1846
1847 sub _update_ssub {
1848     my ($editor, $override, $ssub) = @_;
1849
1850     $logger->info("subscription-alter: retrieving subscription ".$ssub->id);
1851     my $orig_ssub = $editor->retrieve_serial_subscription($ssub->id);
1852
1853     $logger->info("subscription-alter: original subscription ".OpenSRF::Utils::JSON->perl2JSON($orig_ssub));
1854     $logger->info("subscription-alter: updated subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1855     return $editor->event unless $editor->update_serial_subscription($ssub);
1856     return 0;
1857 }
1858
1859 __PACKAGE__->register_method(
1860     method  => "fleshed_serial_subscription_retrieve_batch",
1861     authoritative => 1,
1862     api_name    => "open-ils.serial.subscription.fleshed.batch.retrieve"
1863 );
1864
1865 sub fleshed_serial_subscription_retrieve_batch {
1866     my( $self, $client, $ids ) = @_;
1867 # FIXME: permissions?
1868     $logger->info("Fetching fleshed subscriptions @$ids");
1869     return $U->cstorereq(
1870         "open-ils.cstore.direct.serial.subscription.search.atomic",
1871         { id => $ids },
1872         { flesh => 1,
1873           flesh_fields => {ssub => [ qw/owning_lib notes/ ]}
1874         });
1875 }
1876
1877 __PACKAGE__->register_method(
1878         method  => "retrieve_sub_tree",
1879     authoritative => 1,
1880         api_name        => "open-ils.serial.subscription_tree.retrieve"
1881 );
1882
1883 __PACKAGE__->register_method(
1884         method  => "retrieve_sub_tree",
1885         api_name        => "open-ils.serial.subscription_tree.global.retrieve"
1886 );
1887
1888 sub retrieve_sub_tree {
1889
1890         my( $self, $client, $user_session, $docid, @org_ids ) = @_;
1891
1892         if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
1893
1894         $docid = "$docid";
1895
1896         # TODO: permission support
1897         if(!@org_ids and $user_session) {
1898                 my $user_obj = 
1899                         OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
1900                         @org_ids = ($user_obj->home_ou);
1901         }
1902
1903         if( $self->api_name =~ /global/ ) {
1904                 return _build_subs_list( { record_entry => $docid } ); # TODO: filter for !deleted, or active?
1905
1906         } else {
1907
1908                 my @all_subs;
1909                 for my $orgid (@org_ids) {
1910                         my $subs = _build_subs_list( 
1911                                         { record_entry => $docid, owning_lib => $orgid } );# TODO: filter for !deleted, or active?
1912                         push( @all_subs, @$subs );
1913                 }
1914                 
1915                 return \@all_subs;
1916         }
1917
1918         return undef;
1919 }
1920
1921 sub _build_subs_list {
1922         my $search_hash = shift;
1923
1924         #$search_hash->{deleted} = 'f';
1925         my $e = new_editor();
1926
1927         my $subs = $e->search_serial_subscription([$search_hash, { 'order_by' => {'ssub' => 'id'} }]);
1928
1929         my @built_subs;
1930
1931         for my $sub (@$subs) {
1932
1933         # TODO: filter on !deleted?
1934                 my $dists = $e->search_serial_distribution(
1935             [{ subscription => $sub->id }, { 'order_by' => {'sdist' => 'label'} }]
1936             );
1937
1938                 #$dists = [ sort { $a->label cmp $b->label } @$dists  ];
1939
1940                 $sub->distributions($dists);
1941         
1942         # TODO: filter on !deleted?
1943                 my $issuances = $e->search_serial_issuance(
1944                         [{ subscription => $sub->id }, { 'order_by' => {'siss' => 'label'} }]
1945             );
1946
1947                 #$issuances = [ sort { $a->label cmp $b->label } @$issuances  ];
1948                 $sub->issuances($issuances);
1949
1950         # TODO: filter on !deleted?
1951                 my $scaps = $e->search_serial_caption_and_pattern(
1952                         [{ subscription => $sub->id }, { 'order_by' => {'scap' => 'id'} }]
1953             );
1954
1955                 #$scaps = [ sort { $a->id cmp $b->id } @$scaps  ];
1956                 $sub->scaps($scaps);
1957                 push( @built_subs, $sub );
1958         }
1959
1960         return \@built_subs;
1961
1962 }
1963
1964 __PACKAGE__->register_method(
1965     method  => "subscription_orgs_for_title",
1966     authoritative => 1,
1967     api_name    => "open-ils.serial.subscription.retrieve_orgs_by_title"
1968 );
1969
1970 sub subscription_orgs_for_title {
1971     my( $self, $client, $record_id ) = @_;
1972
1973     my $subs = $U->simple_scalar_request(
1974         "open-ils.cstore",
1975         "open-ils.cstore.direct.serial.subscription.search.atomic",
1976         { record_entry => $record_id }); # TODO: filter on !deleted?
1977
1978     my $orgs = { map {$_->owning_lib => 1 } @$subs };
1979     return [ keys %$orgs ];
1980 }
1981
1982
1983 ##########################################################################
1984 # distribution methods
1985 #
1986 __PACKAGE__->register_method(
1987     method    => 'fleshed_sdist_alter',
1988     api_name  => 'open-ils.serial.distribution.fleshed.batch.update',
1989     api_level => 1,
1990     argc      => 2,
1991     signature => {
1992         desc     => 'Receives an array of one or more distributions and updates the database as needed',
1993         'params' => [ {
1994                  name => 'authtoken',
1995                  desc => 'Authtoken for current user session',
1996                  type => 'string'
1997             },
1998             {
1999                  name => 'distributions',
2000                  desc => 'Array of fleshed distributions',
2001                  type => 'array'
2002             }
2003
2004         ],
2005         'return' => {
2006             desc => 'Returns 1 if successful, event if failed',
2007             type => 'mixed'
2008         }
2009     }
2010 );
2011
2012 sub fleshed_sdist_alter {
2013     my( $self, $conn, $auth, $sdists ) = @_;
2014     return 1 unless ref $sdists;
2015     my( $reqr, $evt ) = $U->checkses($auth);
2016     return $evt if $evt;
2017     my $editor = new_editor(requestor => $reqr, xact => 1);
2018     my $override = $self->api_name =~ /override/;
2019
2020 # TODO: permission check
2021 #        return $editor->event unless
2022 #            $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2023
2024     for my $sdist (@$sdists) {
2025         my $sdistid = $sdist->id;
2026
2027         if( $sdist->isdeleted ) {
2028             $evt = _delete_sdist( $editor, $override, $sdist);
2029         } elsif( $sdist->isnew ) {
2030             $evt = _create_sdist( $editor, $sdist );
2031         } else {
2032             $evt = _update_sdist( $editor, $override, $sdist );
2033         }
2034     }
2035
2036     if( $evt ) {
2037         $logger->info("fleshed distribution-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2038         $editor->rollback;
2039         return $evt;
2040     }
2041     $logger->debug("distribution-alter: done updating distribution batch");
2042     $editor->commit;
2043     $logger->info("fleshed distribution-alter successfully updated ".scalar(@$sdists)." distributions");
2044     return 1;
2045 }
2046
2047 sub _delete_sdist {
2048     my ($editor, $override, $sdist) = @_;
2049     $logger->info("distribution-alter: delete distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2050     return $editor->event unless $editor->delete_serial_distribution($sdist);
2051     return 0;
2052 }
2053
2054 sub _create_sdist {
2055     my ($editor, $sdist) = @_;
2056
2057     $logger->info("distribution-alter: new distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2058     return $editor->event unless $editor->create_serial_distribution($sdist);
2059
2060     # create summaries too
2061     my $summary = new Fieldmapper::serial::basic_summary;
2062     $summary->distribution($sdist->id);
2063     $summary->generated_coverage('');
2064     return $editor->event unless $editor->create_serial_basic_summary($summary);
2065     $summary = new Fieldmapper::serial::supplement_summary;
2066     $summary->distribution($sdist->id);
2067     $summary->generated_coverage('');
2068     return $editor->event unless $editor->create_serial_supplement_summary($summary);
2069     $summary = new Fieldmapper::serial::index_summary;
2070     $summary->distribution($sdist->id);
2071     $summary->generated_coverage('');
2072     return $editor->event unless $editor->create_serial_index_summary($summary);
2073
2074     # create a starter stream (TODO: reconsider this)
2075     my $stream = new Fieldmapper::serial::stream;
2076     $stream->distribution($sdist->id);
2077     return $editor->event unless $editor->create_serial_stream($stream);
2078
2079     return 0;
2080 }
2081
2082 sub _update_sdist {
2083     my ($editor, $override, $sdist) = @_;
2084
2085     $logger->info("distribution-alter: retrieving distribution ".$sdist->id);
2086     my $orig_sdist = $editor->retrieve_serial_distribution($sdist->id);
2087
2088     $logger->info("distribution-alter: original distribution ".OpenSRF::Utils::JSON->perl2JSON($orig_sdist));
2089     $logger->info("distribution-alter: updated distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2090     return $editor->event unless $editor->update_serial_distribution($sdist);
2091     return 0;
2092 }
2093
2094 __PACKAGE__->register_method(
2095     method  => "fleshed_serial_distribution_retrieve_batch",
2096     authoritative => 1,
2097     api_name    => "open-ils.serial.distribution.fleshed.batch.retrieve"
2098 );
2099
2100 sub fleshed_serial_distribution_retrieve_batch {
2101     my( $self, $client, $ids ) = @_;
2102 # FIXME: permissions?
2103     $logger->info("Fetching fleshed distributions @$ids");
2104     return $U->cstorereq(
2105         "open-ils.cstore.direct.serial.distribution.search.atomic",
2106         { id => $ids },
2107         { flesh => 1,
2108           flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams / ]}
2109         });
2110 }
2111
2112 __PACKAGE__->register_method(
2113     method  => "retrieve_dist_tree",
2114     authoritative => 1,
2115     api_name    => "open-ils.serial.distribution_tree.retrieve"
2116 );
2117
2118 __PACKAGE__->register_method(
2119     method  => "retrieve_dist_tree",
2120     api_name    => "open-ils.serial.distribution_tree.global.retrieve"
2121 );
2122
2123 sub retrieve_dist_tree {
2124     my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2125
2126     if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2127
2128     $docid = "$docid";
2129
2130     # TODO: permission support
2131     if(!@org_ids and $user_session) {
2132         my $user_obj =
2133             OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2134             @org_ids = ($user_obj->home_ou);
2135     }
2136
2137     my $e = new_editor();
2138
2139     if( $self->api_name =~ /global/ ) {
2140         return $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }},
2141             {   flesh => 1,
2142                 flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams basic_summary supplement_summary index_summary / ]},
2143                 order_by => {'sdist' => 'id'},
2144                 'join' => {'ssub' => {}}
2145             }
2146         ]); # TODO: filter for !deleted?
2147
2148     } else {
2149         my @all_dists;
2150         for my $orgid (@org_ids) {
2151             my $dists = $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }, holding_lib => $orgid},
2152                 {   flesh => 1,
2153                     flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams basic_summary supplement_summary index_summary / ]},
2154                     order_by => {'sdist' => 'id'},
2155                     'join' => {'ssub' => {}}
2156                 }
2157             ]); # TODO: filter for !deleted?
2158             push( @all_dists, @$dists ) if $dists;
2159         }
2160
2161         return \@all_dists;
2162     }
2163
2164     return undef;
2165 }
2166
2167
2168 __PACKAGE__->register_method(
2169     method  => "distribution_orgs_for_title",
2170     authoritative => 1,
2171     api_name    => "open-ils.serial.distribution.retrieve_orgs_by_title"
2172 );
2173
2174 sub distribution_orgs_for_title {
2175     my( $self, $client, $record_id ) = @_;
2176
2177     my $dists = $U->cstorereq(
2178         "open-ils.cstore.direct.serial.distribution.search.atomic",
2179         { '+ssub' => { record_entry => $record_id } },
2180         { 'join' => {'ssub' => {}} }); # TODO: filter on !deleted?
2181
2182     my $orgs = { map {$_->holding_lib => 1 } @$dists };
2183     return [ keys %$orgs ];
2184 }
2185
2186
2187 ##########################################################################
2188 # caption and pattern methods
2189 #
2190 __PACKAGE__->register_method(
2191     method    => 'scap_alter',
2192     api_name  => 'open-ils.serial.caption_and_pattern.batch.update',
2193     api_level => 1,
2194     argc      => 2,
2195     signature => {
2196         desc     => 'Receives an array of one or more caption and patterns and updates the database as needed',
2197         'params' => [ {
2198                  name => 'authtoken',
2199                  desc => 'Authtoken for current user session',
2200                  type => 'string'
2201             },
2202             {
2203                  name => 'scaps',
2204                  desc => 'Array of caption and patterns',
2205                  type => 'array'
2206             }
2207
2208         ],
2209         'return' => {
2210             desc => 'Returns 1 if successful, event if failed',
2211             type => 'mixed'
2212         }
2213     }
2214 );
2215
2216 sub scap_alter {
2217     my( $self, $conn, $auth, $scaps ) = @_;
2218     return 1 unless ref $scaps;
2219     my( $reqr, $evt ) = $U->checkses($auth);
2220     return $evt if $evt;
2221     my $editor = new_editor(requestor => $reqr, xact => 1);
2222     my $override = $self->api_name =~ /override/;
2223
2224 # TODO: permission check
2225 #        return $editor->event unless
2226 #            $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2227
2228     for my $scap (@$scaps) {
2229         my $scapid = $scap->id;
2230
2231         if( $scap->isdeleted ) {
2232             $evt = _delete_scap( $editor, $override, $scap);
2233         } elsif( $scap->isnew ) {
2234             $evt = _create_scap( $editor, $scap );
2235         } else {
2236             $evt = _update_scap( $editor, $override, $scap );
2237         }
2238     }
2239
2240     if( $evt ) {
2241         $logger->info("caption_and_pattern-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2242         $editor->rollback;
2243         return $evt;
2244     }
2245     $logger->debug("caption_and_pattern-alter: done updating caption_and_pattern batch");
2246     $editor->commit;
2247     $logger->info("caption_and_pattern-alter successfully updated ".scalar(@$scaps)." caption_and_patterns");
2248     return 1;
2249 }
2250
2251 sub _delete_scap {
2252     my ($editor, $override, $scap) = @_;
2253     $logger->info("caption_and_pattern-alter: delete caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2254     my $sisses = $editor->search_serial_issuance(
2255             { caption_and_pattern => $scap->id }, { limit => 1 } ); #TODO: 'deleted' support?
2256     return OpenILS::Event->new(
2257             'SERIAL_CAPTION_AND_PATTERN_HAS_ISSUANCES', payload => $scap->id ) if (@$sisses);
2258
2259     return $editor->event unless $editor->delete_serial_caption_and_pattern($scap);
2260     return 0;
2261 }
2262
2263 sub _create_scap {
2264     my ($editor, $scap) = @_;
2265
2266     $logger->info("caption_and_pattern-alter: new caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2267     return $editor->event unless $editor->create_serial_caption_and_pattern($scap);
2268     return 0;
2269 }
2270
2271 sub _update_scap {
2272     my ($editor, $override, $scap) = @_;
2273
2274     $logger->info("caption_and_pattern-alter: retrieving caption_and_pattern ".$scap->id);
2275     my $orig_scap = $editor->retrieve_serial_caption_and_pattern($scap->id);
2276
2277     $logger->info("caption_and_pattern-alter: original caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($orig_scap));
2278     $logger->info("caption_and_pattern-alter: updated caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2279     return $editor->event unless $editor->update_serial_caption_and_pattern($scap);
2280     return 0;
2281 }
2282
2283 __PACKAGE__->register_method(
2284     method  => "serial_caption_and_pattern_retrieve_batch",
2285     authoritative => 1,
2286     api_name    => "open-ils.serial.caption_and_pattern.batch.retrieve"
2287 );
2288
2289 sub serial_caption_and_pattern_retrieve_batch {
2290     my( $self, $client, $ids ) = @_;
2291     $logger->info("Fetching caption_and_patterns @$ids");
2292     return $U->cstorereq(
2293         "open-ils.cstore.direct.serial.caption_and_pattern.search.atomic",
2294         { id => $ids }
2295     );
2296 }
2297
2298 ##########################################################################
2299 # stream methods
2300 #
2301 __PACKAGE__->register_method(
2302     method    => 'sstr_alter',
2303     api_name  => 'open-ils.serial.stream.batch.update',
2304     api_level => 1,
2305     argc      => 2,
2306     signature => {
2307         desc     => 'Receives an array of one or more streams and updates the database as needed',
2308         'params' => [ {
2309                  name => 'authtoken',
2310                  desc => 'Authtoken for current user session',
2311                  type => 'string'
2312             },
2313             {
2314                  name => 'sstrs',
2315                  desc => 'Array of streams',
2316                  type => 'array'
2317             }
2318
2319         ],
2320         'return' => {
2321             desc => 'Returns 1 if successful, event if failed',
2322             type => 'mixed'
2323         }
2324     }
2325 );
2326
2327 sub sstr_alter {
2328     my( $self, $conn, $auth, $sstrs ) = @_;
2329     return 1 unless ref $sstrs;
2330     my( $reqr, $evt ) = $U->checkses($auth);
2331     return $evt if $evt;
2332     my $editor = new_editor(requestor => $reqr, xact => 1);
2333     my $override = $self->api_name =~ /override/;
2334
2335 # TODO: permission check
2336 #        return $editor->event unless
2337 #            $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2338
2339     for my $sstr (@$sstrs) {
2340         my $sstrid = $sstr->id;
2341
2342         if( $sstr->isdeleted ) {
2343             $evt = _delete_sstr( $editor, $override, $sstr);
2344         } elsif( $sstr->isnew ) {
2345             $evt = _create_sstr( $editor, $sstr );
2346         } else {
2347             $evt = _update_sstr( $editor, $override, $sstr );
2348         }
2349     }
2350
2351     if( $evt ) {
2352         $logger->info("stream-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2353         $editor->rollback;
2354         return $evt;
2355     }
2356     $logger->debug("stream-alter: done updating stream batch");
2357     $editor->commit;
2358     $logger->info("stream-alter successfully updated ".scalar(@$sstrs)." streams");
2359     return 1;
2360 }
2361
2362 sub _delete_sstr {
2363     my ($editor, $override, $sstr) = @_;
2364     $logger->info("stream-alter: delete stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2365     my $sitems = $editor->search_serial_item(
2366             { stream => $sstr->id }, { limit => 1 } ); #TODO: 'deleted' support?
2367     return OpenILS::Event->new(
2368             'SERIAL_STREAM_HAS_ITEMS', payload => $sstr->id ) if (@$sitems);
2369
2370     return $editor->event unless $editor->delete_serial_stream($sstr);
2371     return 0;
2372 }
2373
2374 sub _create_sstr {
2375     my ($editor, $sstr) = @_;
2376
2377     $logger->info("stream-alter: new stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2378     return $editor->event unless $editor->create_serial_stream($sstr);
2379     return 0;
2380 }
2381
2382 sub _update_sstr {
2383     my ($editor, $override, $sstr) = @_;
2384
2385     $logger->info("stream-alter: retrieving stream ".$sstr->id);
2386     my $orig_sstr = $editor->retrieve_serial_stream($sstr->id);
2387
2388     $logger->info("stream-alter: original stream ".OpenSRF::Utils::JSON->perl2JSON($orig_sstr));
2389     $logger->info("stream-alter: updated stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2390     return $editor->event unless $editor->update_serial_stream($sstr);
2391     return 0;
2392 }
2393
2394 __PACKAGE__->register_method(
2395     method  => "serial_stream_retrieve_batch",
2396     authoritative => 1,
2397     api_name    => "open-ils.serial.stream.batch.retrieve"
2398 );
2399
2400 sub serial_stream_retrieve_batch {
2401     my( $self, $client, $ids ) = @_;
2402     $logger->info("Fetching streams @$ids");
2403     return $U->cstorereq(
2404         "open-ils.cstore.direct.serial.stream.search.atomic",
2405         { id => $ids }
2406     );
2407 }
2408
2409
2410 ##########################################################################
2411 # summary methods
2412 #
2413 __PACKAGE__->register_method(
2414     method    => 'sum_alter',
2415     api_name  => 'open-ils.serial.basic_summary.batch.update',
2416     api_level => 1,
2417     argc      => 2,
2418     signature => {
2419         desc     => 'Receives an array of one or more summaries and updates the database as needed',
2420         'params' => [ {
2421                  name => 'authtoken',
2422                  desc => 'Authtoken for current user session',
2423                  type => 'string'
2424             },
2425             {
2426                  name => 'sbsums',
2427                  desc => 'Array of basic summaries',
2428                  type => 'array'
2429             }
2430
2431         ],
2432         'return' => {
2433             desc => 'Returns 1 if successful, event if failed',
2434             type => 'mixed'
2435         }
2436     }
2437 );
2438
2439 __PACKAGE__->register_method(
2440     method    => 'sum_alter',
2441     api_name  => 'open-ils.serial.supplement_summary.batch.update',
2442     api_level => 1,
2443     argc      => 2,
2444     signature => {
2445         desc     => 'Receives an array of one or more summaries and updates the database as needed',
2446         'params' => [ {
2447                  name => 'authtoken',
2448                  desc => 'Authtoken for current user session',
2449                  type => 'string'
2450             },
2451             {
2452                  name => 'sbsums',
2453                  desc => 'Array of supplement summaries',
2454                  type => 'array'
2455             }
2456
2457         ],
2458         'return' => {
2459             desc => 'Returns 1 if successful, event if failed',
2460             type => 'mixed'
2461         }
2462     }
2463 );
2464
2465 __PACKAGE__->register_method(
2466     method    => 'sum_alter',
2467     api_name  => 'open-ils.serial.index_summary.batch.update',
2468     api_level => 1,
2469     argc      => 2,
2470     signature => {
2471         desc     => 'Receives an array of one or more summaries and updates the database as needed',
2472         'params' => [ {
2473                  name => 'authtoken',
2474                  desc => 'Authtoken for current user session',
2475                  type => 'string'
2476             },
2477             {
2478                  name => 'sbsums',
2479                  desc => 'Array of index summaries',
2480                  type => 'array'
2481             }
2482
2483         ],
2484         'return' => {
2485             desc => 'Returns 1 if successful, event if failed',
2486             type => 'mixed'
2487         }
2488     }
2489 );
2490
2491 sub sum_alter {
2492     my( $self, $conn, $auth, $sums ) = @_;
2493     return 1 unless ref $sums;
2494
2495     $self->api_name =~ /serial\.(\w*)_summary/;
2496     my $type = $1;
2497
2498     my( $reqr, $evt ) = $U->checkses($auth);
2499     return $evt if $evt;
2500     my $editor = new_editor(requestor => $reqr, xact => 1);
2501     my $override = $self->api_name =~ /override/;
2502
2503 # TODO: permission check
2504 #        return $editor->event unless
2505 #            $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2506
2507     for my $sum (@$sums) {
2508         my $sumid = $sum->id;
2509
2510         # XXX: (for now, at least) summaries should be created/deleted by the distribution functions
2511         if( $sum->isdeleted ) {
2512             $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2513         } elsif( $sum->isnew ) {
2514             $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2515         } else {
2516             $evt = _update_sum( $editor, $override, $sum, $type );
2517         }
2518     }
2519
2520     if( $evt ) {
2521         $logger->info("${type}_summary-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2522         $editor->rollback;
2523         return $evt;
2524     }
2525     $logger->debug("${type}_summary-alter: done updating ${type}_summary batch");
2526     $editor->commit;
2527     $logger->info("${type}_summary-alter successfully updated ".scalar(@$sums)." ${type}_summaries");
2528     return 1;
2529 }
2530
2531 sub _update_sum {
2532     my ($editor, $override, $sum, $type) = @_;
2533
2534     $logger->info("${type}_summary-alter: retrieving ${type}_summary ".$sum->id);
2535     my $retrieve_method = "retrieve_serial_${type}_summary";
2536     my $orig_sum = $editor->$retrieve_method($sum->id);
2537
2538     $logger->info("${type}_summary-alter: original ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($orig_sum));
2539     $logger->info("${type}_summary-alter: updated ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($sum));
2540     my $update_method = "update_serial_${type}_summary";
2541     return $editor->event unless $editor->$update_method($sum);
2542     return 0;
2543 }
2544
2545 __PACKAGE__->register_method(
2546     method  => "serial_summary_retrieve_batch",
2547     authoritative => 1,
2548     api_name    => "open-ils.serial.basic_summary.batch.retrieve"
2549 );
2550
2551 __PACKAGE__->register_method(
2552     method  => "serial_summary_retrieve_batch",
2553     authoritative => 1,
2554     api_name    => "open-ils.serial.supplement_summary.batch.retrieve"
2555 );
2556
2557 __PACKAGE__->register_method(
2558     method  => "serial_summary_retrieve_batch",
2559     authoritative => 1,
2560     api_name    => "open-ils.serial.index_summary.batch.retrieve"
2561 );
2562
2563 sub serial_summary_retrieve_batch {
2564     my( $self, $client, $ids ) = @_;
2565
2566     $self->api_name =~ /serial\.(\w*)_summary/;
2567     my $type = $1;
2568
2569     $logger->info("Fetching ${type}_summaries @$ids");
2570     return $U->cstorereq(
2571         "open-ils.cstore.direct.serial.".$type."_summary.search.atomic",
2572         { id => $ids }
2573     );
2574 }
2575
2576
2577 ##########################################################################
2578 # other methods
2579 #
2580 __PACKAGE__->register_method(
2581     "method" => "bre_by_identifier",
2582     "api_name" => "open-ils.serial.biblio.record_entry.by_identifier",
2583     "stream" => 1,
2584     "signature" => {
2585         "desc" => "Find instances of biblio.record_entry given a search token" .
2586             " that could be a value for any identifier defined in " .
2587             "config.metabib_field",
2588         "params" => [
2589             {"desc" => "Search token", "type" => "string"},
2590             {"desc" => "Options: require_subscriptions, add_mvr, is_actual_id" .
2591                 " (all boolean)", "type" => "object"}
2592         ],
2593         "return" => {
2594             "desc" => "Any matching BREs, or if the add_mvr option is true, " .
2595                 "objects with a 'bre' key/value pair, and an 'mvr' " .
2596                 "key-value pair.  BREs have subscriptions fleshed on.",
2597             "type" => "object"
2598         }
2599     }
2600 );
2601
2602 sub bre_by_identifier {
2603     my ($self, $client, $term, $options) = @_;
2604
2605     return new OpenILS::Event("BAD_PARAMS") unless $term;
2606
2607     $options ||= {};
2608     my $e = new_editor();
2609
2610     my @ids;
2611
2612     if ($options->{"is_actual_id"}) {
2613         @ids = ($term);
2614     } else {
2615         my $cmf =
2616             $e->search_config_metabib_field({"field_class" => "identifier"})
2617                 or return $e->die_event;
2618
2619         my @identifiers = map { $_->name } @$cmf;
2620         my $query = join(" || ", map { "id|$_: $term" } @identifiers);
2621
2622         my $search = create OpenSRF::AppSession("open-ils.search");
2623         my $search_result = $search->request(
2624             "open-ils.search.biblio.multiclass.query.staff", {}, $query
2625         )->gather(1);
2626         $search->disconnect;
2627
2628         # Un-nest results. They tend to look like [[1],[2],[3]] for some reason.
2629         @ids = map { @{$_} } @{$search_result->{"ids"}};
2630
2631         unless (@ids) {
2632             $e->disconnect;
2633             return undef;
2634         }
2635     }
2636
2637     my $bre = $e->search_biblio_record_entry([
2638         {"id" => \@ids}, {
2639             "flesh" => 2, "flesh_fields" => {
2640                 "bre" => ["subscriptions"],
2641                 "ssub" => ["owning_lib"]
2642             }
2643         }
2644     ]) or return $e->die_event;
2645
2646     if (@$bre && $options->{"require_subscriptions"}) {
2647         $bre = [ grep { @{$_->subscriptions} } @$bre ];
2648     }
2649
2650     $e->disconnect;
2651
2652     if (@$bre) { # re-evaluate after possible grep
2653         if ($options->{"add_mvr"}) {
2654             $client->respond(
2655                 {"bre" => $_, "mvr" => _get_mvr($_->id)}
2656             ) foreach (@$bre);
2657         } else {
2658             $client->respond($_) foreach (@$bre);
2659         }
2660     }
2661
2662     undef;
2663 }
2664
2665 __PACKAGE__->register_method(
2666     "method" => "get_receivable_items",
2667     "api_name" => "open-ils.serial.items.receivable.by_subscription",
2668     "stream" => 1,
2669     "signature" => {
2670         "desc" => "Return all receivable items under a given subscription",
2671         "params" => [
2672             {"desc" => "Authtoken", "type" => "string"},
2673             {"desc" => "Subscription ID", "type" => "number"},
2674         ],
2675         "return" => {
2676             "desc" => "All receivable items under a given subscription",
2677             "type" => "object"
2678         }
2679     }
2680 );
2681
2682 __PACKAGE__->register_method(
2683     "method" => "get_receivable_items",
2684     "api_name" => "open-ils.serial.items.receivable.by_issuance",
2685     "stream" => 1,
2686     "signature" => {
2687         "desc" => "Return all receivable items under a given issuance",
2688         "params" => [
2689             {"desc" => "Authtoken", "type" => "string"},
2690             {"desc" => "Issuance ID", "type" => "number"},
2691         ],
2692         "return" => {
2693             "desc" => "All receivable items under a given issuance",
2694             "type" => "object"
2695         }
2696     }
2697 );
2698
2699 sub get_receivable_items {
2700     my ($self, $client, $auth, $term)  = @_;
2701
2702     my $e = new_editor("authtoken" => $auth);
2703     return $e->die_event unless $e->checkauth;
2704
2705     # XXX permissions
2706
2707     my $by = ($self->api_name =~ /by_(\w+)$/)[0];
2708
2709     my %where = (
2710         "issuance" => {"issuance" => $term},
2711         "subscription" => {"+siss" => {"subscription" => $term}}
2712     );
2713
2714     my $item_ids = $e->json_query(
2715         {
2716             "select" => {"sitem" => ["id"]},
2717             "from" => {"sitem" => "siss"},
2718             "where" => {
2719                 %{$where{$by}}, "date_received" => undef
2720             },
2721             "order_by" => {"sitem" => ["id"]}
2722         }
2723     ) or return $e->die_event;
2724
2725     return undef unless @$item_ids;
2726
2727     foreach (map { $_->{"id"} } @$item_ids) {
2728         $client->respond(
2729             $e->retrieve_serial_item([
2730                 $_, {
2731                     "flesh" => 3,
2732                     "flesh_fields" => {
2733                         "sitem" => ["stream", "issuance"],
2734                         "sstr" => ["distribution"],
2735                         "sdist" => ["holding_lib"]
2736                     }
2737                 }
2738             ])
2739         );
2740     }
2741
2742     $e->disconnect;
2743     undef;
2744 }
2745
2746 __PACKAGE__->register_method(
2747     "method" => "get_receivable_issuances",
2748     "api_name" => "open-ils.serial.issuances.receivable",
2749     "stream" => 1,
2750     "signature" => {
2751         "desc" => "Return all issuances with receivable items given " .
2752             "a subscription ID",
2753         "params" => [
2754             {"desc" => "Authtoken", "type" => "string"},
2755             {"desc" => "Subscription ID", "type" => "number"},
2756         ],
2757         "return" => {
2758             "desc" => "All issuances with receivable items " .
2759                 "(but not the items themselves)", "type" => "object"
2760         }
2761     }
2762 );
2763
2764 sub get_receivable_issuances {
2765     my ($self, $client, $auth, $sub_id) = @_;
2766
2767     my $e = new_editor("authtoken" => $auth);
2768     return $e->die_event unless $e->checkauth;
2769
2770     # XXX permissions
2771
2772     my $issuance_ids = $e->json_query({
2773         "select" => {
2774             "siss" => [
2775                 {"transform" => "distinct", "column" => "id"},
2776                 "date_published"
2777             ]
2778         },
2779         "from" => {"siss" => "sitem"},
2780         "where" => {
2781             "subscription" => $sub_id,
2782             "+sitem" => {"date_received" => undef}
2783         },
2784         "order_by" => {
2785             "siss" => {"date_published" => {"direction" => "asc"}}
2786         }
2787
2788     }) or return $e->die_event;
2789
2790     $client->respond($e->retrieve_serial_issuance($_->{"id"}))
2791         foreach (@$issuance_ids);
2792
2793     $e->disconnect;
2794     undef;
2795 }
2796
2797 1;