]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Serial.pm
Merge serials-integration branch, incorporating new work from Dan Wells.
[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     offest := 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 $all_dists = $args->{all_dists}; #TODO: this option supports test-level code, will be removed (i.e. always 'true')
672     my $mfhd = MFHD->new(MARC::Record->new());
673
674     my $ssub = $editor->retrieve_serial_subscription([$ssub_id]);
675     my $scaps = $editor->search_serial_caption_and_pattern({ subscription => $ssub_id, active => 't'});
676     my $sdists = $editor->search_serial_distribution( [{ subscription => $ssub->id }, {  flesh => 1,
677               flesh_fields => {sdist => [ qw/ streams / ]}, $all_dists ? () : (limit => 1) }] ); #TODO: 'deleted' support?
678
679     if ($all_dists) {
680         my $total_streams = 0;
681         foreach (@$sdists) {
682             $total_streams += scalar(@{$_->streams});
683         }
684         if ($total_streams < 1) {
685             $editor->disconnect;
686             # XXX TODO new event type
687             return new OpenILS::Event(
688                 "BAD_PARAMS", note =>
689                     "There are no streams to direct items. Can't predict."
690             );
691         }
692     }
693
694     unless (@$scaps) {
695         $editor->disconnect;
696         # XXX TODO new event type
697         return new OpenILS::Event(
698             "BAD_PARAMS", note =>
699                 "There are no active caption-and-pattern objects associated " .
700                 "with this subscription. Can't predict."
701         );
702     }
703
704     my @predictions;
705     my $link_id = 1;
706     foreach my $scap (@$scaps) {
707         my $caption_field = _revive_caption($scap);
708         $caption_field->update('8' => $link_id);
709         $mfhd->append_fields($caption_field);
710         my $options = {
711                 'caption' => $caption_field,
712                 'scap_id' => $scap->id,
713                 'num_to_predict' => $args->{num_to_predict},
714                 'end_date' => defined $args->{end_date} ?
715                     $_strp_date->parse_datetime($args->{end_date}) : undef
716                 };
717         if ($args->{base_issuance}) { # predict from a given issuance
718             $options->{predict_from} = _revive_holding($args->{base_issuance}->holding_code, $caption_field, 1); # fresh MFHD Record, so we simply default to 1 for seqno
719         } else { # default to predicting from last published
720             my $last_published = $editor->search_serial_issuance([
721                     {'caption_and_pattern' => $scap->id,
722                     'subscription' => $ssub_id},
723                 {limit => 1, order_by => { siss => "date_published DESC" }}]
724                 );
725             if ($last_published->[0]) {
726                 my $last_siss = $last_published->[0];
727                 unless ($last_siss->holding_code) {
728                     $editor->disconnect;
729                     # XXX TODO new event type
730                     return new OpenILS::Event(
731                         "BAD_PARAMS", note =>
732                             "Last issuance has no holding code. Can't predict."
733                     );
734                 }
735                 $options->{predict_from} = _revive_holding($last_siss->holding_code, $caption_field, 1);
736             } else {
737                 $editor->disconnect;
738                 # XXX TODO make a new event type instead of hijacking this one
739                 return new OpenILS::Event(
740                     "BAD_PARAMS", note => "No issuance from which to predict!"
741                 );
742             }
743         }
744         push( @predictions, _generate_issuance_values($mfhd, $options) );
745         $link_id++;
746     }
747
748     my @issuances;
749     foreach my $prediction (@predictions) {
750         my $issuance = new Fieldmapper::serial::issuance;
751         $issuance->isnew(1);
752         $issuance->label($prediction->{label});
753         $issuance->date_published($prediction->{date_published}->strftime('%F'));
754         $issuance->holding_code(OpenSRF::Utils::JSON->perl2JSON($prediction->{holding_code}));
755         $issuance->holding_type($prediction->{holding_type});
756         $issuance->caption_and_pattern($prediction->{caption_and_pattern});
757         $issuance->subscription($ssub->id);
758         push (@issuances, $issuance);
759     }
760
761     fleshed_issuance_alter($self, $conn, $authtoken, \@issuances); # FIXME: catch events
762
763     my @items;
764     for (my $i = 0; $i < @issuances; $i++) {
765         my $date_expected = $predictions[$i]->{date_published}->add(seconds => interval_to_seconds($ssub->expected_date_offset))->strftime('%F');
766         my $issuance = $issuances[$i];
767         #$issuance->label(interval_to_seconds($ssub->expected_date_offset));
768         foreach my $sdist (@$sdists) {
769             my $streams = $sdist->streams;
770             foreach my $stream (@$streams) {
771                 my $item = new Fieldmapper::serial::item;
772                 $item->isnew(1);
773                 $item->stream($stream->id);
774                 $item->date_expected($date_expected);
775                 $item->issuance($issuance->id);
776                 push (@items, $item);
777             }
778         }
779     }
780     fleshed_item_alter($self, $conn, $authtoken, \@items); # FIXME: catch events
781     return \@items;
782 }
783
784 #
785 # _generate_issuance_values() is an initial attempt at a function which can be used
786 # to populate an issuance table with a list of predicted issues.  It accepts
787 # a hash ref of options initially defined as:
788 # caption : the caption field to predict on
789 # num_to_predict : the number of issues you wish to predict
790 # last_rec_date : the date of the last received issue, to be used as an offset
791 #                 for predicting future issues
792 #
793 # The basic method is to first convert to a single holding if compressed, then
794 # increment the holding and save the resulting values to @issuances.
795
796 # returns @issuance_values, an array of hashrefs containing (formatted
797 # label, formatted chronology date, formatted estimated arrival date, and an
798 # array ref of holding subfields as (key, value, key, value ...)) (not a hash
799 # to protect order and possible duplicate keys), and a holding type.
800 #
801 sub _generate_issuance_values {
802     my ($mfhd, $options) = @_;
803     my $caption = $options->{caption};
804     my $scap_id = $options->{scap_id};
805     my $num_to_predict = $options->{num_to_predict};
806     my $end_date = $options->{end_date};
807     my $predict_from = $options->{predict_from};   # issuance to predict from
808     #my $last_rec_date = $options->{last_rec_date};   # expected or actual
809
810     # TODO: add support for predicting serials with no chronology by passing in
811     # a last_pub_date option?
812
813
814 # Only needed for 'real' MFHD records, not our temp records
815 #    my $link_id = $caption->link_id;
816 #    if(!$predict_from) {
817 #        my $htag = $caption->tag;
818 #        $htag =~ s/^85/86/;
819 #        my @holdings = $mfhd->holdings($htag, $link_id);
820 #        my $last_holding = $holdings[-1];
821 #
822 #        #if ($last_holding->is_compressed) {
823 #        #    $last_holding->compressed_to_last; # convert to last in range
824 #        #}
825 #        $predict_from = $last_holding;
826 #    }
827 #
828
829     $predict_from->notes('public',  []);
830 # add a note marker for system use (?)
831     $predict_from->notes('private', ['AUTOGEN']);
832
833     my $pub_date;
834     my @issuance_values;
835     my @predictions = $mfhd->generate_predictions({'base_holding' => $predict_from, 'num_to_predict' => $num_to_predict, 'end_date' => $end_date});
836     foreach my $prediction (@predictions) {
837         $pub_date = $_strp_date->parse_datetime($prediction->chron_to_date);
838         push(
839                 @issuance_values,
840                 {
841                     #$link_id,
842                     label => $prediction->format,
843                     date_published => $pub_date,
844                     #date_expected => $date_expected->strftime('%F'),
845                     holding_code => [$prediction->indicator(1),$prediction->indicator(2),$prediction->subfields_list],
846                     holding_type => $MFHD_NAMES_BY_TAG{$caption->tag},
847                     caption_and_pattern => $scap_id
848                 }
849             );
850     }
851
852     return @issuance_values;
853 }
854
855 sub _revive_caption {
856     my $scap = shift;
857
858     my $pattern_code = $scap->pattern_code;
859
860     # build MARC::Field
861     my $pattern_parts = OpenSRF::Utils::JSON->JSON2perl($pattern_code);
862     unshift(@$pattern_parts, $MFHD_TAGS_BY_NAME{$scap->type});
863     my $pattern_field = new MARC::Field(@$pattern_parts);
864
865     # build MFHD::Caption
866     return new MFHD::Caption($pattern_field);
867 }
868
869 sub _revive_holding {
870     my $holding_code = shift;
871     my $caption_field = shift;
872     my $seqno = shift;
873
874     # build MARC::Field
875     my $holding_parts = OpenSRF::Utils::JSON->JSON2perl($holding_code);
876     my $captag = $caption_field->tag;
877     $captag =~ s/^85/86/;
878     unshift(@$holding_parts, $captag);
879     my $holding_field = new MARC::Field(@$holding_parts);
880
881     # build MFHD::Holding
882     return new MFHD::Holding($seqno, $holding_field, $caption_field);
883 }
884
885 __PACKAGE__->register_method(
886     method    => 'unitize_items',
887     api_name  => 'open-ils.serial.receive_items',
888     api_level => 1,
889     argc      => 1,
890     signature => {
891         desc     => 'Marks an item as received, updates the shelving unit (creating a new shelving unit if needed), and updates the summaries',
892         'params' => [ {
893                  name => 'items',
894                  desc => 'array of serial items',
895                  type => 'array'
896             },
897             {
898                  name => 'barcodes',
899                  desc => 'hash of item_ids => barcodes',
900                  type => 'hash'
901             }
902         ],
903         'return' => {
904             desc => 'Returns number of received items (num_items) and new unit ID, if applicable (new_unit_id)',
905             type => 'hashref'
906         }
907     }
908 );
909
910 __PACKAGE__->register_method(
911     method    => 'unitize_items',
912     api_name  => 'open-ils.serial.bind_items',
913     api_level => 1,
914     argc      => 1,
915     signature => {
916         desc     => 'Marks an item as bound, updates the shelving unit (creating a new shelving unit if needed)',
917         'params' => [ {
918                  name => 'items',
919                  desc => 'array of serial items',
920                  type => 'array'
921             },
922             {
923                  name => 'barcodes',
924                  desc => 'hash of item_ids => barcodes',
925                  type => 'hash'
926             }
927         ],
928         'return' => {
929             desc => 'Returns number of bound items (num_items) and new unit ID, if applicable (new_unit_id)',
930             type => 'hashref'
931         }
932     }
933 );
934
935 sub unitize_items {
936     my ($self, $conn, $auth, $items, $barcodes) = @_;
937
938     my( $reqr, $evt ) = $U->checkses($auth);
939     return $evt if $evt;
940     my $editor = new_editor(requestor => $reqr, xact => 1);
941     $self->api_name =~ /serial\.(\w*)_items/;
942     my $mode = $1;
943     
944     my %found_unit_ids;
945     my %found_stream_ids;
946     my %found_types;
947
948     my %stream_ids_by_unit_id;
949
950     my %unit_map;
951     my %sdist_by_unit_id;
952     my %sdist_by_stream_id;
953
954     my $new_unit_id; # id for '-2' units to share
955     foreach my $item (@$items) {
956         # for debugging only, TODO: delete
957         if (!ref $item) { # hopefully we got an id instead
958             $item = $editor->retrieve_serial_item($item);
959         }
960         # get ids
961         my $unit_id = ref($item->unit) ? $item->unit->id : $item->unit;
962         my $stream_id = ref($item->stream) ? $item->stream->id : $item->stream;
963         my $issuance_id = ref($item->issuance) ? $item->issuance->id : $item->issuance;
964         #TODO: evt on any missing ids
965
966         if ($mode eq 'receive') {
967             $item->date_received('now');
968             $item->status('Received');
969         } else {
970             $item->status('Bindery');
971         }
972
973         # check for types to trigger summary updates
974         my $scap;
975         if (!ref $item->issuance) {
976             my $scaps = $editor->search_serial_caption_and_pattern([{"+siss" => {"id" => $issuance_id}}, { "join" => {"siss" => {}} }]);
977             $scap = $scaps->[0];
978         } elsif (!ref $item->issuance->caption_and_pattern) {
979             $scap = $editor->retrieve_serial_caption_and_pattern($item->issuance->caption_and_pattern);
980         } else {
981             $scap = $editor->issuance->caption_and_pattern;
982         }
983         if (!exists($found_types{$stream_id})) {
984             $found_types{$stream_id} = {};
985         }
986         $found_types{$stream_id}->{$scap->type} = 1;
987
988         # create unit if needed
989         if ($unit_id == -1 or (!$new_unit_id and $unit_id == -2)) { # create unit per item
990             my $unit;
991             my $sdists = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
992             $unit = _build_unit($editor, $sdists->[0], $mode, 0, $barcodes->{$item->id});
993             # TODO: catch events from _build_unit
994             my $evt =  _create_sunit($editor, $unit);
995             return $evt if $evt;
996             if ($unit_id == -2) {
997                 $new_unit_id = $unit->id;
998                 $unit_id = $new_unit_id;
999             } else {
1000                 $unit_id = $unit->id;
1001             }
1002             $item->unit($unit_id);
1003             
1004             # get unit with 'DEFAULT's and save unit and sdist for later use
1005             $unit = $editor->retrieve_serial_unit($unit->id);
1006             $unit_map{$unit_id} = $unit;
1007             $sdist_by_unit_id{$unit_id} = $sdists->[0];
1008             $sdist_by_stream_id{$stream_id} = $sdists->[0];
1009         } elsif ($unit_id == -2) { # create one unit for all '-2' items
1010             $unit_id = $new_unit_id;
1011             $item->unit($unit_id);
1012         }
1013
1014         $found_unit_ids{$unit_id} = 1;
1015         $found_stream_ids{$stream_id} = 1;
1016
1017         # save the stream_id for this unit_id
1018         # TODO: prevent items from different streams in same unit? (perhaps in interface)
1019         $stream_ids_by_unit_id{$unit_id} = $stream_id;
1020
1021         my $evt = _update_sitem($editor, undef, $item);
1022         return $evt if $evt;
1023     }
1024
1025     # deal with unit level labels
1026     foreach my $unit_id (keys %found_unit_ids) {
1027
1028         # get all the needed issuances for unit
1029         my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"unit" => $unit_id, "status" => ["Received", "Bindery"]}}, {"join" => {"sitem" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1030         #TODO: evt on search failure
1031
1032         my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
1033
1034         # special case for single formatted_part (may have summarized version)
1035         if (@$formatted_parts == 1) {
1036             #TODO: MFHD.pm should have a 'format_summary' method for this
1037         }
1038
1039         # retrieve and update unit contents
1040         my $sunit;
1041         my $sdist;
1042
1043         # if we just created the unit, we will already have it and the distribution stored
1044         if (exists $unit_map{$unit_id}) {
1045             $sunit = $unit_map{$unit_id};
1046             $sdist = $sdist_by_unit_id{$unit_id};
1047         } else {
1048             $sunit = $editor->retrieve_serial_unit($unit_id);
1049             $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_ids_by_unit_id{$unit_id}}}, { "join" => {"sstr" => {}} }]);
1050             $sdist = $sdist->[0];
1051         }
1052
1053         $sunit->detailed_contents($sdist->unit_label_prefix . ' '
1054                     . join(', ', @$formatted_parts) . ' '
1055                     . $sdist->unit_label_suffix);
1056
1057         $sunit->summary_contents($sunit->detailed_contents); #TODO: change this when real summary contents are available
1058
1059         # create sort_key by left padding numbers to 6 digits
1060         my $sort_key = $sunit->detailed_contents;
1061         $sort_key =~ s/(\d+)/sprintf '%06d', $1/eg; # this may need improvement
1062         $sunit->sort_key($sort_key);
1063         
1064         if ($mode eq 'bind') {
1065             $sunit->status(2); # set to 'Bindery' status
1066         }
1067
1068         my $evt = _update_sunit($editor, undef, $sunit);
1069         return $evt if $evt;
1070     }
1071
1072     # cleanup 'dead' units (units which are now emptied of their items)
1073     my $dead_units = $editor->search_serial_unit([{'+sitem' => {'id' => undef}, 'deleted' => 'f'}, {'join' => {'sitem' => {'type' => 'left'}}}]);
1074     foreach my $unit (@$dead_units) {
1075         _delete_sunit($editor, undef, $unit);
1076     }
1077
1078     if ($mode eq 'receive') { # the summary holdings do not change when binding
1079         # deal with stream level summaries
1080         # summaries will be built from the "primary" stream only, that is, the stream with the lowest ID per distribution
1081         # (TODO: consider direct designation)
1082         my %primary_streams_by_sdist;
1083         my %streams_by_sdist;
1084
1085         # see if we have primary streams, and if so, associate them with their distributions
1086         foreach my $stream_id (keys %found_stream_ids) {
1087             my $sdist;
1088             if (exists $sdist_by_stream_id{$stream_id}) {
1089                 $sdist = $sdist_by_stream_id{$stream_id};
1090             } else {
1091                 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
1092                 $sdist = $sdist->[0];
1093             }
1094             my $streams;
1095             if (!exists($streams_by_sdist{$sdist->id})) {
1096                 $streams = $editor->search_serial_stream([{"distribution" => $sdist->id}, {"order_by" => {"sstr" => "id"}}]);
1097                 $streams_by_sdist{$sdist->id} = $streams;
1098             } else {
1099                 $streams = $streams_by_sdist{$sdist->id};
1100             }
1101             $primary_streams_by_sdist{$sdist->id} = $streams->[0] if ($stream_id == $streams->[0]->id);
1102         }
1103
1104         # retrieve and update summaries for each affected primary stream's distribution
1105         foreach my $sdist_id (keys %primary_streams_by_sdist) {
1106             my $stream = $primary_streams_by_sdist{$sdist_id};
1107             my $stream_id = $stream->id;
1108             # get all the needed issuances for stream
1109             # FIXME: search in Bindery/Bound/Not Published? as well as Received
1110             foreach my $type (keys %{$found_types{$stream_id}}) {
1111                 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"stream" => $stream_id, "status" => "Received"}, "+scap" => {"type" => $type}}, {"join" => {"sitem" => {}, "scap" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1112                 #TODO: evt on search failure
1113
1114                 my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
1115
1116                 # retrieve and update the generated_coverage of the summary
1117                 my $search_method = "search_serial_${type}_summary";
1118                 my $summary = $editor->$search_method([{"distribution" => $sdist_id}]);
1119                 $summary = $summary->[0];
1120                 $summary->generated_coverage(join(', ', @$formatted_parts));
1121                 my $update_method = "update_serial_${type}_summary";
1122                 return $editor->event unless $editor->$update_method($summary);
1123             }
1124         }
1125     }
1126
1127     $editor->commit;
1128     return {'num_items' => scalar @$items, 'new_unit_id' => $new_unit_id};
1129 }
1130
1131 sub _find_or_create_call_number {
1132     my ($e, $lib, $cn_string, $record) = @_;
1133
1134     my $existing = $e->search_asset_call_number({
1135         "owning_lib" => $lib,
1136         "label" => $cn_string,
1137         "record" => $record,
1138         "deleted" => "f"
1139     }) or return $e->die_event;
1140
1141     if (@$existing) {
1142         return $existing->[0]->id;
1143     } else {
1144         return $e->die_event unless
1145             $e->allowed("CREATE_VOLUME", $lib);
1146
1147         my $acn = new Fieldmapper::asset::call_number;
1148
1149         $acn->creator($e->requestor->id);
1150         $acn->editor($e->requestor->id);
1151         $acn->record($record);
1152         $acn->label($cn_string);
1153         $acn->owning_lib($lib);
1154
1155         $e->create_asset_call_number($acn) or return $e->die_event;
1156         return $e->data->id;
1157     }
1158 }
1159
1160 sub _issuances_received {
1161     # XXX TODO: Add some caching or something. This is getting called
1162     # more often than it has to be.
1163     my ($e, $sitem) = @_;
1164
1165     my $results = $e->json_query({
1166         "select" => {"sitem" => ["issuance"]},
1167         "from" => {"sitem" => {"sstr" => {}, "siss" => {}}},
1168         "where" => {
1169             "+sstr" => {"distribution" => $sitem->stream->distribution->id},
1170             "+siss" => {"holding_type" => $sitem->issuance->holding_type},
1171             "+sitem" => {"date_received" => {"!=" => undef}}
1172         },
1173         "order_by" => {
1174             "siss" => {"date_published" => {"direction" => "asc"}}
1175         }
1176     }) or return $e->die_event;
1177
1178     my $uniq = +{map { $_->{"issuance"} => 1 } @$results};
1179     return [ map { $e->retrieve_serial_issuance($_) } keys %$uniq ];
1180 }
1181
1182 # XXX _prepare_unit_label() duplicates some code from unitize_items().
1183 # Hopefully we can unify code paths down the road.
1184 sub _prepare_unit_label {
1185     my ($e, $sunit, $sdist, $issuance) = @_;
1186
1187     my ($mfhd, $formatted_parts) = _summarize_contents($e, [$issuance]);
1188
1189     # special case for single formatted_part (may have summarized version)
1190     if (@$formatted_parts == 1) {
1191         #TODO: MFHD.pm should have a 'format_summary' method for this
1192     }
1193
1194     $sunit->detailed_contents(
1195         join(
1196             " ",
1197             $sdist->unit_label_prefix,
1198             join(", ", @$formatted_parts),
1199             $sdist->unit_label_suffix
1200         )
1201     );
1202
1203     # TODO: change this when real summary contents are available
1204     $sunit->summary_contents($sunit->detailed_contents);
1205
1206     # Create sort_key by left padding numbers to 6 digits.
1207     (my $sort_key = $sunit->detailed_contents) =~
1208         s/(\d+)/sprintf '%06d', $1/eg;
1209     $sunit->sort_key($sort_key);
1210 }
1211
1212 # XXX duplicates a block of code from unitize_items().  Once I fully understand
1213 # what's going on and I'm sure it's working right, I'd like to have
1214 # unitize_items() just use this, keeping the logic in one place.
1215 sub _prepare_summaries {
1216     my ($e, $sitem, $issuances) = @_;
1217
1218     my $dist_id = $sitem->stream->distribution->id;
1219     my $type = $sitem->issuance->holding_type;
1220
1221     # Make sure @$issuances contains the new issuance from sitem.
1222     unless (grep { $_->id == $sitem->issuance->id } @$issuances) {
1223         push @$issuances, $sitem->issuance;
1224     }
1225
1226     my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances);
1227
1228     my $search_method = "search_serial_${type}_summary";
1229     my $summary = $e->$search_method([{"distribution" => $dist_id}]);
1230
1231     my $cu_method = "update";
1232
1233     if (@$summary) {
1234         $summary = $summary->[0];
1235     } else {
1236         my $class = "Fieldmapper::serial::${type}_summary";
1237         $summary = $class->new;
1238         $summary->distribution($dist_id);
1239         $cu_method = "create";
1240     }
1241
1242     $summary->generated_coverage(join(", ", @$formatted_parts));
1243     my $method = "${cu_method}_serial_${type}_summary";
1244     return $e->die_event unless $e->$method($summary);
1245 }
1246
1247 sub _unit_by_iss_and_str {
1248     my ($e, $issuance, $stream) = @_;
1249
1250     my $unit = $e->json_query({
1251         "select" => {"sunit" => ["id"]},
1252         "from" => {"sitem" => {"sunit" => {}}},
1253         "where" => {
1254             "+sitem" => {
1255                 "issuance" => $issuance->id,
1256                 "stream" => $stream->id
1257             }
1258         }
1259     }) or return $e->die_event;
1260
1261     $e->retrieve_serial_unit($unit->[0]->{"id"}) or $e->die_event;
1262 }
1263
1264 sub move_previous_unit {
1265     my ($e, $prev_iss, $curr_item, $new_loc) = @_;
1266
1267     my $prev_unit = _unit_by_iss_and_str($e,$prev_iss,$curr_item->stream);
1268     return $prev_unit if defined $U->event_code($prev_unit);
1269
1270     if ($prev_unit->location != $new_loc) {
1271         $prev_unit->location($new_loc);
1272         $e->update_serial_unit($prev_unit) or return $e->die_event;
1273     }
1274     0;
1275 }
1276
1277 # _previous_issuance() assumes $existing is an ordered array
1278 sub _previous_issuance {
1279     my ($existing, $issuance) = @_;
1280
1281     my $last = $existing->[-1];
1282     return undef unless $last;
1283     return ($last->id == $issuance->id ? $existing->[-2] : $last);
1284 }
1285
1286 __PACKAGE__->register_method(
1287     "method" => "receive_items_one_unit_per",
1288     "api_name" => "open-ils.serial.receive_items.one_unit_per",
1289     "stream" => 1,
1290     "api_level" => 1,
1291     "argc" => 3,
1292     "signature" => {
1293         "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",
1294         "params" => [
1295             {
1296                  "name" => "auth",
1297                  "desc" => "authtoken",
1298                  "type" => "string"
1299             },
1300             {
1301                  "name" => "items",
1302                  "desc" => "array of serial items, possibly fleshed with units and definitely fleshed with stream->distribution",
1303                  "type" => "array"
1304             },
1305             {
1306                 "name" => "record",
1307                 "desc" => "id of bib record these items are associated with
1308                     (XXX could/should be derived from items)",
1309                 "type" => "number"
1310             }
1311         ],
1312         "return" => {
1313             "desc" => "The item ID for each item successfully received",
1314             "type" => "int"
1315         }
1316     }
1317 );
1318
1319 sub receive_items_one_unit_per {
1320     # XXX This function may be temporary, as it does some of what
1321     # unitize_items() does, just in a different way.
1322     my ($self, $client, $auth, $items, $record) = @_;
1323
1324     my $e = new_editor("authtoken" => $auth, "xact" => 1);
1325     return $e->die_event unless $e->checkauth;
1326     return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
1327
1328     my $prev_loc_setting_map = {};
1329     my $user_id = $e->requestor->id;
1330
1331     # Get a list of all the non-virtual field names in a serial::unit for
1332     # merging given unit objects with template-built units later.
1333     # XXX move this somewhere global so it isn't re-run all the time
1334     my $all_unit_fields =
1335         $Fieldmapper::fieldmap->{"Fieldmapper::serial::unit"}->{"fields"};
1336     my @real_unit_fields = grep {
1337         not $all_unit_fields->{$_}->{"virtual"}
1338     } keys %$all_unit_fields;
1339
1340     foreach my $item (@$items) {
1341         # Note that we expect a certain fleshing on the items we're getting.
1342         my $sdist = $item->stream->distribution;
1343
1344         # Fetch a list of issuances with received copies already existing
1345         # on this distribution (and with the same holding type on the
1346         # issuance).  This will be used in up to two places: once when building
1347         # a summary, once when changing the copy location of the previous
1348         # issuance's copy.
1349         my $issuances_received = _issuances_received($e, $item);
1350         if ($U->event_code($issuances_received)) {
1351             $e->rollback;
1352             return $issuances_received;
1353         }
1354
1355         # Find out if we need to to deal with previous copy location changing.
1356         my $ou = $sdist->holding_lib->id;
1357         unless (exists $prev_loc_setting_map->{$ou}) {
1358             $prev_loc_setting_map->{$ou} = $U->ou_ancestor_setting_value(
1359                 $ou, "serial.prev_issuance_copy_location", $e
1360             );
1361         }
1362
1363         # If there is a previous copy location setting, we need the previous
1364         # issuance, from which we can in turn look up the item attached to the
1365         # same stream we're on now.
1366         if ($prev_loc_setting_map->{$ou}) {
1367             if (my $prev_iss =
1368                 _previous_issuance($issuances_received, $item->issuance)) {
1369
1370                 # Now we can change the copy location of the previous unit,
1371                 # if needed.
1372                 return $e->event if defined $U->event_code(
1373                     move_previous_unit(
1374                         $e, $prev_iss, $item, $prev_loc_setting_map->{$ou}
1375                     )
1376                 );
1377             }
1378         }
1379
1380         # Create unit if given by user
1381         if (ref $item->unit) {
1382             # detach from the item, as we need to create separately
1383             my $user_unit = $item->unit;
1384
1385             # get a unit based on associated template
1386             my $template_unit = _build_unit($e, $sdist, "receive", 1);
1387             if ($U->event_code($template_unit)) {
1388                 $e->rollback;
1389                 $template_unit->{"note"} = "Item ID: " . $item->id;
1390                 return $template_unit;
1391             }
1392
1393             # merge built unit with provided unit from user
1394             foreach (@real_unit_fields) {
1395                 unless ($user_unit->$_) {
1396                     $user_unit->$_($template_unit->$_);
1397                 }
1398             }
1399
1400             # Treat call number specially: the provided value from the
1401             # user will really be a string.
1402             if ($user_unit->call_number) {
1403                 my $real_cn = _find_or_create_call_number(
1404                     $e, $sdist->holding_lib->id,
1405                     $user_unit->call_number, $record
1406                 );
1407
1408                 if ($U->event_code($real_cn)) {
1409                     $e->rollback;
1410                     return $real_cn;
1411                 } else {
1412                     $user_unit->call_number($real_cn);
1413                 }
1414             }
1415
1416             my $evt = _prepare_unit_label(
1417                 $e, $user_unit, $sdist, $item->issuance
1418             );
1419             if ($U->event_code($evt)) {
1420                 $e->rollback;
1421                 return $evt;
1422             }
1423
1424             # create/update summary objects related to this distribution
1425             $evt = _prepare_summaries($e, $item, $issuances_received);
1426             if ($U->event_code($evt)) {
1427                 $e->rollback;
1428                 return $evt;
1429             }
1430
1431             # set the incontrovertibles on the unit
1432             $user_unit->edit_date("now");
1433             $user_unit->create_date("now");
1434             $user_unit->editor($user_id);
1435             $user_unit->creator($user_id);
1436
1437             return $e->die_event unless $e->create_serial_unit($user_unit);
1438
1439             # save reference to new unit
1440             $item->unit($e->data->id);
1441         }
1442
1443         # Create notes if given by user
1444         if (ref($item->notes) and @{$item->notes}) {
1445             foreach my $note (@{$item->notes}) {
1446                 $note->creator($user_id);
1447                 $note->create_date("now");
1448
1449                 return $e->die_event unless $e->create_serial_item_note($note);
1450             }
1451
1452             $item->clear_notes; # They're saved; we no longer want them here.
1453         }
1454
1455         # Set the incontrovertibles on the item
1456         $item->status("Received");
1457         $item->date_received("now");
1458         $item->edit_date("now");
1459         $item->editor($user_id);
1460
1461         return $e->die_event unless $e->update_serial_item($item);
1462
1463         # send client a response
1464         $client->respond($item->id);
1465     }
1466
1467     $e->commit or return $e->die_event;
1468     undef;
1469 }
1470
1471 sub _build_unit {
1472     my $editor = shift;
1473     my $sdist = shift;
1474     my $mode = shift;
1475     my $skip_call_number = shift;
1476     my $barcode = shift;
1477
1478     my $attr = $mode . '_unit_template';
1479     my $template = $editor->retrieve_asset_copy_template($sdist->$attr) or
1480         return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_COPY_TEMPLATE");
1481
1482     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 );
1483
1484     my $unit = new Fieldmapper::serial::unit;
1485     foreach my $part (@parts) {
1486         my $value = $template->$part;
1487         next if !defined($value);
1488         $unit->$part($value);
1489     }
1490
1491     # ignore circ_lib in template, set to distribution holding_lib
1492     $unit->circ_lib($sdist->holding_lib);
1493     $unit->creator($editor->requestor->id);
1494     $unit->editor($editor->requestor->id);
1495
1496     unless ($skip_call_number) {
1497         $attr = $mode . '_call_number';
1498         my $cn = $sdist->$attr or
1499             return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_CALL_NUMBER");
1500
1501         $unit->call_number($cn);
1502     }
1503
1504     if ($barcode) {
1505         $unit->barcode($barcode);
1506     } else {
1507         $unit->barcode('AUTO');
1508     }
1509     $unit->sort_key('');
1510     $unit->summary_contents('');
1511     $unit->detailed_contents('');
1512
1513     return $unit;
1514 }
1515
1516
1517 sub _summarize_contents {
1518     my $editor = shift;
1519     my $issuances = shift;
1520
1521     # create MFHD record
1522     my $mfhd = MFHD->new(MARC::Record->new());
1523     my %scaps;
1524     my %scap_fields;
1525     my @scap_fields_ordered;
1526     my $seqno = 1;
1527     my $link_id = 1;
1528     foreach my $issuance (@$issuances) {
1529         my $scap_id = $issuance->caption_and_pattern;
1530         next if (!$scap_id); # skip issuances with no caption/pattern
1531
1532         my $scap;
1533         my $scap_field;
1534         # if this is the first appearance of this scap, retrieve it and add it to the temporary record
1535         if (!exists $scaps{$issuance->caption_and_pattern}) {
1536             $scaps{$scap_id} = $editor->retrieve_serial_caption_and_pattern($scap_id);
1537             $scap = $scaps{$scap_id};
1538             $scap_field = _revive_caption($scap);
1539             $scap_fields{$scap_id} = $scap_field;
1540             push(@scap_fields_ordered, $scap_field);
1541             $scap_field->update('8' => $link_id);
1542             $mfhd->append_fields($scap_field);
1543             $link_id++;
1544         } else {
1545             $scap = $scaps{$scap_id};
1546             $scap_field = $scap_fields{$scap_id};
1547         }
1548
1549         $mfhd->append_fields(_revive_holding($issuance->holding_code, $scap_field, $seqno));
1550         $seqno++;
1551     }
1552
1553     my @formatted_parts;
1554     foreach my $scap_field (@scap_fields_ordered) { #TODO: use generic MFHD "summarize" method, once available
1555        my @updated_holdings = $mfhd->get_compressed_holdings($scap_field);
1556        foreach my $holding (@updated_holdings) {
1557            push(@formatted_parts, $holding->format);
1558        }
1559     }
1560
1561     return ($mfhd, \@formatted_parts);
1562 }
1563
1564 ##########################################################################
1565 # note methods
1566 #
1567 __PACKAGE__->register_method(
1568     method      => 'fetch_notes',
1569     api_name        => 'open-ils.serial.item_note.retrieve.all',
1570     signature   => q/
1571         Returns an array of copy note objects.  
1572         @param args A named hash of parameters including:
1573             authtoken   : Required if viewing non-public notes
1574             item_id      : The id of the item whose notes we want to retrieve
1575             pub         : True if all the caller wants are public notes
1576         @return An array of note objects
1577     /
1578 );
1579
1580 __PACKAGE__->register_method(
1581     method      => 'fetch_notes',
1582     api_name        => 'open-ils.serial.subscription_note.retrieve.all',
1583     signature   => q/
1584         Returns an array of copy note objects.  
1585         @param args A named hash of parameters including:
1586             authtoken       : Required if viewing non-public notes
1587             subscription_id : The id of the item whose notes we want to retrieve
1588             pub             : True if all the caller wants are public notes
1589         @return An array of note objects
1590     /
1591 );
1592
1593 __PACKAGE__->register_method(
1594     method      => 'fetch_notes',
1595     api_name        => 'open-ils.serial.distribution_note.retrieve.all',
1596     signature   => q/
1597         Returns an array of copy note objects.  
1598         @param args A named hash of parameters including:
1599             authtoken       : Required if viewing non-public notes
1600             distribution_id : The id of the item whose notes we want to retrieve
1601             pub             : True if all the caller wants are public notes
1602         @return An array of note objects
1603     /
1604 );
1605
1606 # TODO: revisit this method to consider replacing cstore direct calls
1607 sub fetch_notes {
1608     my( $self, $connection, $args ) = @_;
1609     
1610     $self->api_name =~ /serial\.(\w*)_note/;
1611     my $type = $1;
1612
1613     my $id = $$args{object_id};
1614     my $authtoken = $$args{authtoken};
1615     my( $r, $evt);
1616
1617     if( $$args{pub} ) {
1618         return $U->cstorereq(
1619             'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic',
1620             { $type => $id, pub => 't' } );
1621     } else {
1622         # FIXME: restore perm check
1623         # ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
1624         # return $evt if $evt;
1625         return $U->cstorereq(
1626             'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic', {$type => $id} );
1627     }
1628
1629     return undef;
1630 }
1631
1632 __PACKAGE__->register_method(
1633     method      => 'create_note',
1634     api_name        => 'open-ils.serial.item_note.create',
1635     signature   => q/
1636         Creates a new item note
1637         @param authtoken The login session key
1638         @param note The note object to create
1639         @return The id of the new note object
1640     /
1641 );
1642
1643 __PACKAGE__->register_method(
1644     method      => 'create_note',
1645     api_name        => 'open-ils.serial.subscription_note.create',
1646     signature   => q/
1647         Creates a new subscription note
1648         @param authtoken The login session key
1649         @param note The note object to create
1650         @return The id of the new note object
1651     /
1652 );
1653
1654 __PACKAGE__->register_method(
1655     method      => 'create_note',
1656     api_name        => 'open-ils.serial.distribution_note.create',
1657     signature   => q/
1658         Creates a new distribution note
1659         @param authtoken The login session key
1660         @param note The note object to create
1661         @return The id of the new note object
1662     /
1663 );
1664
1665 sub create_note {
1666     my( $self, $connection, $authtoken, $note ) = @_;
1667
1668     $self->api_name =~ /serial\.(\w*)_note/;
1669     my $type = $1;
1670
1671     my $e = new_editor(xact=>1, authtoken=>$authtoken);
1672     return $e->event unless $e->checkauth;
1673
1674     # FIXME: restore permission support
1675 #    my $item = $e->retrieve_serial_item(
1676 #        [
1677 #            $note->item
1678 #        ]
1679 #    );
1680 #
1681 #    return $e->event unless
1682 #        $e->allowed('CREATE_COPY_NOTE', $item->call_number->owning_lib);
1683
1684     $note->create_date('now');
1685     $note->creator($e->requestor->id);
1686     $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
1687     $note->clear_id;
1688
1689     my $method = "create_serial_${type}_note";
1690     $e->$method($note) or return $e->event;
1691     $e->commit;
1692     return $note->id;
1693 }
1694
1695 __PACKAGE__->register_method(
1696     method      => 'delete_note',
1697     api_name        =>  'open-ils.serial.item_note.delete',
1698     signature   => q/
1699         Deletes an existing item note
1700         @param authtoken The login session key
1701         @param noteid The id of the note to delete
1702         @return 1 on success - Event otherwise.
1703         /
1704 );
1705
1706 __PACKAGE__->register_method(
1707     method      => 'delete_note',
1708     api_name        =>  'open-ils.serial.subscription_note.delete',
1709     signature   => q/
1710         Deletes an existing subscription note
1711         @param authtoken The login session key
1712         @param noteid The id of the note to delete
1713         @return 1 on success - Event otherwise.
1714         /
1715 );
1716
1717 __PACKAGE__->register_method(
1718     method      => 'delete_note',
1719     api_name        =>  'open-ils.serial.distribution_note.delete',
1720     signature   => q/
1721         Deletes an existing distribution note
1722         @param authtoken The login session key
1723         @param noteid The id of the note to delete
1724         @return 1 on success - Event otherwise.
1725         /
1726 );
1727
1728 sub delete_note {
1729     my( $self, $conn, $authtoken, $noteid ) = @_;
1730
1731     $self->api_name =~ /serial\.(\w*)_note/;
1732     my $type = $1;
1733
1734     my $e = new_editor(xact=>1, authtoken=>$authtoken);
1735     return $e->die_event unless $e->checkauth;
1736
1737     my $method = "retrieve_serial_${type}_note";
1738     my $note = $e->$method([
1739         $noteid,
1740     ]) or return $e->die_event;
1741
1742 # FIXME: restore permissions check
1743 #    if( $note->creator ne $e->requestor->id ) {
1744 #        return $e->die_event unless
1745 #            $e->allowed('DELETE_COPY_NOTE', $note->item->call_number->owning_lib);
1746 #    }
1747
1748     $method = "delete_serial_${type}_note";
1749     $e->$method($note) or return $e->die_event;
1750     $e->commit;
1751     return 1;
1752 }
1753
1754
1755 ##########################################################################
1756 # subscription methods
1757 #
1758 __PACKAGE__->register_method(
1759     method    => 'fleshed_ssub_alter',
1760     api_name  => 'open-ils.serial.subscription.fleshed.batch.update',
1761     api_level => 1,
1762     argc      => 2,
1763     signature => {
1764         desc     => 'Receives an array of one or more subscriptions and updates the database as needed',
1765         'params' => [ {
1766                  name => 'authtoken',
1767                  desc => 'Authtoken for current user session',
1768                  type => 'string'
1769             },
1770             {
1771                  name => 'subscriptions',
1772                  desc => 'Array of fleshed subscriptions',
1773                  type => 'array'
1774             }
1775
1776         ],
1777         'return' => {
1778             desc => 'Returns 1 if successful, event if failed',
1779             type => 'mixed'
1780         }
1781     }
1782 );
1783
1784 sub fleshed_ssub_alter {
1785     my( $self, $conn, $auth, $ssubs ) = @_;
1786     return 1 unless ref $ssubs;
1787     my( $reqr, $evt ) = $U->checkses($auth);
1788     return $evt if $evt;
1789     my $editor = new_editor(requestor => $reqr, xact => 1);
1790     my $override = $self->api_name =~ /override/;
1791
1792 # TODO: permission check
1793 #        return $editor->event unless
1794 #            $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
1795
1796     for my $ssub (@$ssubs) {
1797
1798         my $ssubid = $ssub->id;
1799
1800         if( $ssub->isdeleted ) {
1801             $evt = _delete_ssub( $editor, $override, $ssub);
1802         } elsif( $ssub->isnew ) {
1803             _cleanse_dates($ssub, ['start_date','end_date']);
1804             $evt = _create_ssub( $editor, $ssub );
1805         } else {
1806             _cleanse_dates($ssub, ['start_date','end_date']);
1807             $evt = _update_ssub( $editor, $override, $ssub );
1808         }
1809     }
1810
1811     if( $evt ) {
1812         $logger->info("fleshed subscription-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
1813         $editor->rollback;
1814         return $evt;
1815     }
1816     $logger->debug("subscription-alter: done updating subscription batch");
1817     $editor->commit;
1818     $logger->info("fleshed subscription-alter successfully updated ".scalar(@$ssubs)." subscriptions");
1819     return 1;
1820 }
1821
1822 sub _delete_ssub {
1823     my ($editor, $override, $ssub) = @_;
1824     $logger->info("subscription-alter: delete subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1825     my $sdists = $editor->search_serial_distribution(
1826             { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1827     my $cps = $editor->search_serial_caption_and_pattern(
1828             { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1829     my $sisses = $editor->search_serial_issuance(
1830             { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1831     return OpenILS::Event->new(
1832             'SERIAL_SUBSCRIPTION_NOT_EMPTY', payload => $ssub->id ) if (@$sdists or @$cps or @$sisses);
1833
1834     return $editor->event unless $editor->delete_serial_subscription($ssub);
1835     return 0;
1836 }
1837
1838 sub _create_ssub {
1839     my ($editor, $ssub) = @_;
1840
1841     $logger->info("subscription-alter: new subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1842     return $editor->event unless $editor->create_serial_subscription($ssub);
1843     return 0;
1844 }
1845
1846 sub _update_ssub {
1847     my ($editor, $override, $ssub) = @_;
1848
1849     $logger->info("subscription-alter: retrieving subscription ".$ssub->id);
1850     my $orig_ssub = $editor->retrieve_serial_subscription($ssub->id);
1851
1852     $logger->info("subscription-alter: original subscription ".OpenSRF::Utils::JSON->perl2JSON($orig_ssub));
1853     $logger->info("subscription-alter: updated subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1854     return $editor->event unless $editor->update_serial_subscription($ssub);
1855     return 0;
1856 }
1857
1858 __PACKAGE__->register_method(
1859     method  => "fleshed_serial_subscription_retrieve_batch",
1860     authoritative => 1,
1861     api_name    => "open-ils.serial.subscription.fleshed.batch.retrieve"
1862 );
1863
1864 sub fleshed_serial_subscription_retrieve_batch {
1865     my( $self, $client, $ids ) = @_;
1866 # FIXME: permissions?
1867     $logger->info("Fetching fleshed subscriptions @$ids");
1868     return $U->cstorereq(
1869         "open-ils.cstore.direct.serial.subscription.search.atomic",
1870         { id => $ids },
1871         { flesh => 1,
1872           flesh_fields => {ssub => [ qw/owning_lib notes/ ]}
1873         });
1874 }
1875
1876 __PACKAGE__->register_method(
1877         method  => "retrieve_sub_tree",
1878     authoritative => 1,
1879         api_name        => "open-ils.serial.subscription_tree.retrieve"
1880 );
1881
1882 __PACKAGE__->register_method(
1883         method  => "retrieve_sub_tree",
1884         api_name        => "open-ils.serial.subscription_tree.global.retrieve"
1885 );
1886
1887 sub retrieve_sub_tree {
1888
1889         my( $self, $client, $user_session, $docid, @org_ids ) = @_;
1890
1891         if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
1892
1893         $docid = "$docid";
1894
1895         # TODO: permission support
1896         if(!@org_ids and $user_session) {
1897                 my $user_obj = 
1898                         OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
1899                         @org_ids = ($user_obj->home_ou);
1900         }
1901
1902         if( $self->api_name =~ /global/ ) {
1903                 return _build_subs_list( { record_entry => $docid } ); # TODO: filter for !deleted, or active?
1904
1905         } else {
1906
1907                 my @all_subs;
1908                 for my $orgid (@org_ids) {
1909                         my $subs = _build_subs_list( 
1910                                         { record_entry => $docid, owning_lib => $orgid } );# TODO: filter for !deleted, or active?
1911                         push( @all_subs, @$subs );
1912                 }
1913                 
1914                 return \@all_subs;
1915         }
1916
1917         return undef;
1918 }
1919
1920 sub _build_subs_list {
1921         my $search_hash = shift;
1922
1923         #$search_hash->{deleted} = 'f';
1924         my $e = new_editor();
1925
1926         my $subs = $e->search_serial_subscription([$search_hash, { 'order_by' => {'ssub' => 'id'} }]);
1927
1928         my @built_subs;
1929
1930         for my $sub (@$subs) {
1931
1932         # TODO: filter on !deleted?
1933                 my $dists = $e->search_serial_distribution(
1934             [{ subscription => $sub->id }, { 'order_by' => {'sdist' => 'label'} }]
1935             );
1936
1937                 #$dists = [ sort { $a->label cmp $b->label } @$dists  ];
1938
1939                 $sub->distributions($dists);
1940         
1941         # TODO: filter on !deleted?
1942                 my $issuances = $e->search_serial_issuance(
1943                         [{ subscription => $sub->id }, { 'order_by' => {'siss' => 'label'} }]
1944             );
1945
1946                 #$issuances = [ sort { $a->label cmp $b->label } @$issuances  ];
1947                 $sub->issuances($issuances);
1948
1949         # TODO: filter on !deleted?
1950                 my $scaps = $e->search_serial_caption_and_pattern(
1951                         [{ subscription => $sub->id }, { 'order_by' => {'scap' => 'id'} }]
1952             );
1953
1954                 #$scaps = [ sort { $a->id cmp $b->id } @$scaps  ];
1955                 $sub->scaps($scaps);
1956                 push( @built_subs, $sub );
1957         }
1958
1959         return \@built_subs;
1960
1961 }
1962
1963 __PACKAGE__->register_method(
1964     method  => "subscription_orgs_for_title",
1965     authoritative => 1,
1966     api_name    => "open-ils.serial.subscription.retrieve_orgs_by_title"
1967 );
1968
1969 sub subscription_orgs_for_title {
1970     my( $self, $client, $record_id ) = @_;
1971
1972     my $subs = $U->simple_scalar_request(
1973         "open-ils.cstore",
1974         "open-ils.cstore.direct.serial.subscription.search.atomic",
1975         { record_entry => $record_id }); # TODO: filter on !deleted?
1976
1977     my $orgs = { map {$_->owning_lib => 1 } @$subs };
1978     return [ keys %$orgs ];
1979 }
1980
1981
1982 ##########################################################################
1983 # distribution methods
1984 #
1985 __PACKAGE__->register_method(
1986     method    => 'fleshed_sdist_alter',
1987     api_name  => 'open-ils.serial.distribution.fleshed.batch.update',
1988     api_level => 1,
1989     argc      => 2,
1990     signature => {
1991         desc     => 'Receives an array of one or more distributions and updates the database as needed',
1992         'params' => [ {
1993                  name => 'authtoken',
1994                  desc => 'Authtoken for current user session',
1995                  type => 'string'
1996             },
1997             {
1998                  name => 'distributions',
1999                  desc => 'Array of fleshed distributions',
2000                  type => 'array'
2001             }
2002
2003         ],
2004         'return' => {
2005             desc => 'Returns 1 if successful, event if failed',
2006             type => 'mixed'
2007         }
2008     }
2009 );
2010
2011 sub fleshed_sdist_alter {
2012     my( $self, $conn, $auth, $sdists ) = @_;
2013     return 1 unless ref $sdists;
2014     my( $reqr, $evt ) = $U->checkses($auth);
2015     return $evt if $evt;
2016     my $editor = new_editor(requestor => $reqr, xact => 1);
2017     my $override = $self->api_name =~ /override/;
2018
2019 # TODO: permission check
2020 #        return $editor->event unless
2021 #            $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2022
2023     for my $sdist (@$sdists) {
2024         my $sdistid = $sdist->id;
2025
2026         if( $sdist->isdeleted ) {
2027             $evt = _delete_sdist( $editor, $override, $sdist);
2028         } elsif( $sdist->isnew ) {
2029             $evt = _create_sdist( $editor, $sdist );
2030         } else {
2031             $evt = _update_sdist( $editor, $override, $sdist );
2032         }
2033     }
2034
2035     if( $evt ) {
2036         $logger->info("fleshed distribution-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2037         $editor->rollback;
2038         return $evt;
2039     }
2040     $logger->debug("distribution-alter: done updating distribution batch");
2041     $editor->commit;
2042     $logger->info("fleshed distribution-alter successfully updated ".scalar(@$sdists)." distributions");
2043     return 1;
2044 }
2045
2046 sub _delete_sdist {
2047     my ($editor, $override, $sdist) = @_;
2048     $logger->info("distribution-alter: delete distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2049     return $editor->event unless $editor->delete_serial_distribution($sdist);
2050     return 0;
2051 }
2052
2053 sub _create_sdist {
2054     my ($editor, $sdist) = @_;
2055
2056     $logger->info("distribution-alter: new distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2057     return $editor->event unless $editor->create_serial_distribution($sdist);
2058
2059     # create summaries too
2060     my $summary = new Fieldmapper::serial::basic_summary;
2061     $summary->distribution($sdist->id);
2062     $summary->generated_coverage('');
2063     return $editor->event unless $editor->create_serial_basic_summary($summary);
2064     $summary = new Fieldmapper::serial::supplement_summary;
2065     $summary->distribution($sdist->id);
2066     $summary->generated_coverage('');
2067     return $editor->event unless $editor->create_serial_supplement_summary($summary);
2068     $summary = new Fieldmapper::serial::index_summary;
2069     $summary->distribution($sdist->id);
2070     $summary->generated_coverage('');
2071     return $editor->event unless $editor->create_serial_index_summary($summary);
2072
2073     # create a starter stream (TODO: reconsider this)
2074     my $stream = new Fieldmapper::serial::stream;
2075     $stream->distribution($sdist->id);
2076     return $editor->event unless $editor->create_serial_stream($stream);
2077
2078     return 0;
2079 }
2080
2081 sub _update_sdist {
2082     my ($editor, $override, $sdist) = @_;
2083
2084     $logger->info("distribution-alter: retrieving distribution ".$sdist->id);
2085     my $orig_sdist = $editor->retrieve_serial_distribution($sdist->id);
2086
2087     $logger->info("distribution-alter: original distribution ".OpenSRF::Utils::JSON->perl2JSON($orig_sdist));
2088     $logger->info("distribution-alter: updated distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2089     return $editor->event unless $editor->update_serial_distribution($sdist);
2090     return 0;
2091 }
2092
2093 __PACKAGE__->register_method(
2094     method  => "fleshed_serial_distribution_retrieve_batch",
2095     authoritative => 1,
2096     api_name    => "open-ils.serial.distribution.fleshed.batch.retrieve"
2097 );
2098
2099 sub fleshed_serial_distribution_retrieve_batch {
2100     my( $self, $client, $ids ) = @_;
2101 # FIXME: permissions?
2102     $logger->info("Fetching fleshed distributions @$ids");
2103     return $U->cstorereq(
2104         "open-ils.cstore.direct.serial.distribution.search.atomic",
2105         { id => $ids },
2106         { flesh => 1,
2107           flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams / ]}
2108         });
2109 }
2110
2111 __PACKAGE__->register_method(
2112     method  => "retrieve_dist_tree",
2113     authoritative => 1,
2114     api_name    => "open-ils.serial.distribution_tree.retrieve"
2115 );
2116
2117 __PACKAGE__->register_method(
2118     method  => "retrieve_dist_tree",
2119     api_name    => "open-ils.serial.distribution_tree.global.retrieve"
2120 );
2121
2122 sub retrieve_dist_tree {
2123     my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2124
2125     if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2126
2127     $docid = "$docid";
2128
2129     # TODO: permission support
2130     if(!@org_ids and $user_session) {
2131         my $user_obj =
2132             OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2133             @org_ids = ($user_obj->home_ou);
2134     }
2135
2136     my $e = new_editor();
2137
2138     if( $self->api_name =~ /global/ ) {
2139         return $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }},
2140             {   flesh => 1,
2141                 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 / ]},
2142                 order_by => {'sdist' => 'id'},
2143                 'join' => {'ssub' => {}}
2144             }
2145         ]); # TODO: filter for !deleted?
2146
2147     } else {
2148         my @all_dists;
2149         for my $orgid (@org_ids) {
2150             my $dists = $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }, holding_lib => $orgid},
2151                 {   flesh => 1,
2152                     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 / ]},
2153                     order_by => {'sdist' => 'id'},
2154                     'join' => {'ssub' => {}}
2155                 }
2156             ]); # TODO: filter for !deleted?
2157             push( @all_dists, @$dists ) if $dists;
2158         }
2159
2160         return \@all_dists;
2161     }
2162
2163     return undef;
2164 }
2165
2166
2167 __PACKAGE__->register_method(
2168     method  => "distribution_orgs_for_title",
2169     authoritative => 1,
2170     api_name    => "open-ils.serial.distribution.retrieve_orgs_by_title"
2171 );
2172
2173 sub distribution_orgs_for_title {
2174     my( $self, $client, $record_id ) = @_;
2175
2176     my $dists = $U->cstorereq(
2177         "open-ils.cstore.direct.serial.distribution.search.atomic",
2178         { '+ssub' => { record_entry => $record_id } },
2179         { 'join' => {'ssub' => {}} }); # TODO: filter on !deleted?
2180
2181     my $orgs = { map {$_->holding_lib => 1 } @$dists };
2182     return [ keys %$orgs ];
2183 }
2184
2185
2186 ##########################################################################
2187 # caption and pattern methods
2188 #
2189 __PACKAGE__->register_method(
2190     method    => 'scap_alter',
2191     api_name  => 'open-ils.serial.caption_and_pattern.batch.update',
2192     api_level => 1,
2193     argc      => 2,
2194     signature => {
2195         desc     => 'Receives an array of one or more caption and patterns and updates the database as needed',
2196         'params' => [ {
2197                  name => 'authtoken',
2198                  desc => 'Authtoken for current user session',
2199                  type => 'string'
2200             },
2201             {
2202                  name => 'scaps',
2203                  desc => 'Array of caption and patterns',
2204                  type => 'array'
2205             }
2206
2207         ],
2208         'return' => {
2209             desc => 'Returns 1 if successful, event if failed',
2210             type => 'mixed'
2211         }
2212     }
2213 );
2214
2215 sub scap_alter {
2216     my( $self, $conn, $auth, $scaps ) = @_;
2217     return 1 unless ref $scaps;
2218     my( $reqr, $evt ) = $U->checkses($auth);
2219     return $evt if $evt;
2220     my $editor = new_editor(requestor => $reqr, xact => 1);
2221     my $override = $self->api_name =~ /override/;
2222
2223 # TODO: permission check
2224 #        return $editor->event unless
2225 #            $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2226
2227     for my $scap (@$scaps) {
2228         my $scapid = $scap->id;
2229
2230         if( $scap->isdeleted ) {
2231             $evt = _delete_scap( $editor, $override, $scap);
2232         } elsif( $scap->isnew ) {
2233             $evt = _create_scap( $editor, $scap );
2234         } else {
2235             $evt = _update_scap( $editor, $override, $scap );
2236         }
2237     }
2238
2239     if( $evt ) {
2240         $logger->info("caption_and_pattern-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2241         $editor->rollback;
2242         return $evt;
2243     }
2244     $logger->debug("caption_and_pattern-alter: done updating caption_and_pattern batch");
2245     $editor->commit;
2246     $logger->info("caption_and_pattern-alter successfully updated ".scalar(@$scaps)." caption_and_patterns");
2247     return 1;
2248 }
2249
2250 sub _delete_scap {
2251     my ($editor, $override, $scap) = @_;
2252     $logger->info("caption_and_pattern-alter: delete caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2253     my $sisses = $editor->search_serial_issuance(
2254             { caption_and_pattern => $scap->id }, { limit => 1 } ); #TODO: 'deleted' support?
2255     return OpenILS::Event->new(
2256             'SERIAL_CAPTION_AND_PATTERN_HAS_ISSUANCES', payload => $scap->id ) if (@$sisses);
2257
2258     return $editor->event unless $editor->delete_serial_caption_and_pattern($scap);
2259     return 0;
2260 }
2261
2262 sub _create_scap {
2263     my ($editor, $scap) = @_;
2264
2265     $logger->info("caption_and_pattern-alter: new caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2266     return $editor->event unless $editor->create_serial_caption_and_pattern($scap);
2267     return 0;
2268 }
2269
2270 sub _update_scap {
2271     my ($editor, $override, $scap) = @_;
2272
2273     $logger->info("caption_and_pattern-alter: retrieving caption_and_pattern ".$scap->id);
2274     my $orig_scap = $editor->retrieve_serial_caption_and_pattern($scap->id);
2275
2276     $logger->info("caption_and_pattern-alter: original caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($orig_scap));
2277     $logger->info("caption_and_pattern-alter: updated caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2278     return $editor->event unless $editor->update_serial_caption_and_pattern($scap);
2279     return 0;
2280 }
2281
2282 __PACKAGE__->register_method(
2283     method  => "serial_caption_and_pattern_retrieve_batch",
2284     authoritative => 1,
2285     api_name    => "open-ils.serial.caption_and_pattern.batch.retrieve"
2286 );
2287
2288 sub serial_caption_and_pattern_retrieve_batch {
2289     my( $self, $client, $ids ) = @_;
2290     $logger->info("Fetching caption_and_patterns @$ids");
2291     return $U->cstorereq(
2292         "open-ils.cstore.direct.serial.caption_and_pattern.search.atomic",
2293         { id => $ids }
2294     );
2295 }
2296
2297 ##########################################################################
2298 # stream methods
2299 #
2300 __PACKAGE__->register_method(
2301     method    => 'sstr_alter',
2302     api_name  => 'open-ils.serial.stream.batch.update',
2303     api_level => 1,
2304     argc      => 2,
2305     signature => {
2306         desc     => 'Receives an array of one or more streams and updates the database as needed',
2307         'params' => [ {
2308                  name => 'authtoken',
2309                  desc => 'Authtoken for current user session',
2310                  type => 'string'
2311             },
2312             {
2313                  name => 'sstrs',
2314                  desc => 'Array of streams',
2315                  type => 'array'
2316             }
2317
2318         ],
2319         'return' => {
2320             desc => 'Returns 1 if successful, event if failed',
2321             type => 'mixed'
2322         }
2323     }
2324 );
2325
2326 sub sstr_alter {
2327     my( $self, $conn, $auth, $sstrs ) = @_;
2328     return 1 unless ref $sstrs;
2329     my( $reqr, $evt ) = $U->checkses($auth);
2330     return $evt if $evt;
2331     my $editor = new_editor(requestor => $reqr, xact => 1);
2332     my $override = $self->api_name =~ /override/;
2333
2334 # TODO: permission check
2335 #        return $editor->event unless
2336 #            $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2337
2338     for my $sstr (@$sstrs) {
2339         my $sstrid = $sstr->id;
2340
2341         if( $sstr->isdeleted ) {
2342             $evt = _delete_sstr( $editor, $override, $sstr);
2343         } elsif( $sstr->isnew ) {
2344             $evt = _create_sstr( $editor, $sstr );
2345         } else {
2346             $evt = _update_sstr( $editor, $override, $sstr );
2347         }
2348     }
2349
2350     if( $evt ) {
2351         $logger->info("stream-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2352         $editor->rollback;
2353         return $evt;
2354     }
2355     $logger->debug("stream-alter: done updating stream batch");
2356     $editor->commit;
2357     $logger->info("stream-alter successfully updated ".scalar(@$sstrs)." streams");
2358     return 1;
2359 }
2360
2361 sub _delete_sstr {
2362     my ($editor, $override, $sstr) = @_;
2363     $logger->info("stream-alter: delete stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2364     my $sitems = $editor->search_serial_item(
2365             { stream => $sstr->id }, { limit => 1 } ); #TODO: 'deleted' support?
2366     return OpenILS::Event->new(
2367             'SERIAL_STREAM_HAS_ITEMS', payload => $sstr->id ) if (@$sitems);
2368
2369     return $editor->event unless $editor->delete_serial_stream($sstr);
2370     return 0;
2371 }
2372
2373 sub _create_sstr {
2374     my ($editor, $sstr) = @_;
2375
2376     $logger->info("stream-alter: new stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2377     return $editor->event unless $editor->create_serial_stream($sstr);
2378     return 0;
2379 }
2380
2381 sub _update_sstr {
2382     my ($editor, $override, $sstr) = @_;
2383
2384     $logger->info("stream-alter: retrieving stream ".$sstr->id);
2385     my $orig_sstr = $editor->retrieve_serial_stream($sstr->id);
2386
2387     $logger->info("stream-alter: original stream ".OpenSRF::Utils::JSON->perl2JSON($orig_sstr));
2388     $logger->info("stream-alter: updated stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2389     return $editor->event unless $editor->update_serial_stream($sstr);
2390     return 0;
2391 }
2392
2393 __PACKAGE__->register_method(
2394     method  => "serial_stream_retrieve_batch",
2395     authoritative => 1,
2396     api_name    => "open-ils.serial.stream.batch.retrieve"
2397 );
2398
2399 sub serial_stream_retrieve_batch {
2400     my( $self, $client, $ids ) = @_;
2401     $logger->info("Fetching streams @$ids");
2402     return $U->cstorereq(
2403         "open-ils.cstore.direct.serial.stream.search.atomic",
2404         { id => $ids }
2405     );
2406 }
2407
2408
2409 ##########################################################################
2410 # summary methods
2411 #
2412 __PACKAGE__->register_method(
2413     method    => 'sum_alter',
2414     api_name  => 'open-ils.serial.basic_summary.batch.update',
2415     api_level => 1,
2416     argc      => 2,
2417     signature => {
2418         desc     => 'Receives an array of one or more summaries and updates the database as needed',
2419         'params' => [ {
2420                  name => 'authtoken',
2421                  desc => 'Authtoken for current user session',
2422                  type => 'string'
2423             },
2424             {
2425                  name => 'sbsums',
2426                  desc => 'Array of basic summaries',
2427                  type => 'array'
2428             }
2429
2430         ],
2431         'return' => {
2432             desc => 'Returns 1 if successful, event if failed',
2433             type => 'mixed'
2434         }
2435     }
2436 );
2437
2438 __PACKAGE__->register_method(
2439     method    => 'sum_alter',
2440     api_name  => 'open-ils.serial.supplement_summary.batch.update',
2441     api_level => 1,
2442     argc      => 2,
2443     signature => {
2444         desc     => 'Receives an array of one or more summaries and updates the database as needed',
2445         'params' => [ {
2446                  name => 'authtoken',
2447                  desc => 'Authtoken for current user session',
2448                  type => 'string'
2449             },
2450             {
2451                  name => 'sbsums',
2452                  desc => 'Array of supplement summaries',
2453                  type => 'array'
2454             }
2455
2456         ],
2457         'return' => {
2458             desc => 'Returns 1 if successful, event if failed',
2459             type => 'mixed'
2460         }
2461     }
2462 );
2463
2464 __PACKAGE__->register_method(
2465     method    => 'sum_alter',
2466     api_name  => 'open-ils.serial.index_summary.batch.update',
2467     api_level => 1,
2468     argc      => 2,
2469     signature => {
2470         desc     => 'Receives an array of one or more summaries and updates the database as needed',
2471         'params' => [ {
2472                  name => 'authtoken',
2473                  desc => 'Authtoken for current user session',
2474                  type => 'string'
2475             },
2476             {
2477                  name => 'sbsums',
2478                  desc => 'Array of index summaries',
2479                  type => 'array'
2480             }
2481
2482         ],
2483         'return' => {
2484             desc => 'Returns 1 if successful, event if failed',
2485             type => 'mixed'
2486         }
2487     }
2488 );
2489
2490 sub sum_alter {
2491     my( $self, $conn, $auth, $sums ) = @_;
2492     return 1 unless ref $sums;
2493
2494     $self->api_name =~ /serial\.(\w*)_summary/;
2495     my $type = $1;
2496
2497     my( $reqr, $evt ) = $U->checkses($auth);
2498     return $evt if $evt;
2499     my $editor = new_editor(requestor => $reqr, xact => 1);
2500     my $override = $self->api_name =~ /override/;
2501
2502 # TODO: permission check
2503 #        return $editor->event unless
2504 #            $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2505
2506     for my $sum (@$sums) {
2507         my $sumid = $sum->id;
2508
2509         # XXX: (for now, at least) summaries should be created/deleted by the distribution functions
2510         if( $sum->isdeleted ) {
2511             $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2512         } elsif( $sum->isnew ) {
2513             $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2514         } else {
2515             $evt = _update_sum( $editor, $override, $sum, $type );
2516         }
2517     }
2518
2519     if( $evt ) {
2520         $logger->info("${type}_summary-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2521         $editor->rollback;
2522         return $evt;
2523     }
2524     $logger->debug("${type}_summary-alter: done updating ${type}_summary batch");
2525     $editor->commit;
2526     $logger->info("${type}_summary-alter successfully updated ".scalar(@$sums)." ${type}_summaries");
2527     return 1;
2528 }
2529
2530 sub _update_sum {
2531     my ($editor, $override, $sum, $type) = @_;
2532
2533     $logger->info("${type}_summary-alter: retrieving ${type}_summary ".$sum->id);
2534     my $retrieve_method = "retrieve_serial_${type}_summary";
2535     my $orig_sum = $editor->$retrieve_method($sum->id);
2536
2537     $logger->info("${type}_summary-alter: original ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($orig_sum));
2538     $logger->info("${type}_summary-alter: updated ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($sum));
2539     my $update_method = "update_serial_${type}_summary";
2540     return $editor->event unless $editor->$update_method($sum);
2541     return 0;
2542 }
2543
2544 __PACKAGE__->register_method(
2545     method  => "serial_summary_retrieve_batch",
2546     authoritative => 1,
2547     api_name    => "open-ils.serial.basic_summary.batch.retrieve"
2548 );
2549
2550 __PACKAGE__->register_method(
2551     method  => "serial_summary_retrieve_batch",
2552     authoritative => 1,
2553     api_name    => "open-ils.serial.supplement_summary.batch.retrieve"
2554 );
2555
2556 __PACKAGE__->register_method(
2557     method  => "serial_summary_retrieve_batch",
2558     authoritative => 1,
2559     api_name    => "open-ils.serial.index_summary.batch.retrieve"
2560 );
2561
2562 sub serial_summary_retrieve_batch {
2563     my( $self, $client, $ids ) = @_;
2564
2565     $self->api_name =~ /serial\.(\w*)_summary/;
2566     my $type = $1;
2567
2568     $logger->info("Fetching ${type}_summaries @$ids");
2569     return $U->cstorereq(
2570         "open-ils.cstore.direct.serial.".$type."_summary.search.atomic",
2571         { id => $ids }
2572     );
2573 }
2574
2575
2576 ##########################################################################
2577 # other methods
2578 #
2579 __PACKAGE__->register_method(
2580     "method" => "bre_by_identifier",
2581     "api_name" => "open-ils.serial.biblio.record_entry.by_identifier",
2582     "stream" => 1,
2583     "signature" => {
2584         "desc" => "Find instances of biblio.record_entry given a search token" .
2585             " that could be a value for any identifier defined in " .
2586             "config.metabib_field",
2587         "params" => [
2588             {"desc" => "Search token", "type" => "string"},
2589             {"desc" => "Options: require_subscriptions, add_mvr, is_actual_id" .
2590                 " (all boolean)", "type" => "object"}
2591         ],
2592         "return" => {
2593             "desc" => "Any matching BREs, or if the add_mvr option is true, " .
2594                 "objects with a 'bre' key/value pair, and an 'mvr' " .
2595                 "key-value pair.  BREs have subscriptions fleshed on.",
2596             "type" => "object"
2597         }
2598     }
2599 );
2600
2601 sub bre_by_identifier {
2602     my ($self, $client, $term, $options) = @_;
2603
2604     return new OpenILS::Event("BAD_PARAMS") unless $term;
2605
2606     $options ||= {};
2607     my $e = new_editor();
2608
2609     my @ids;
2610
2611     if ($options->{"is_actual_id"}) {
2612         @ids = ($term);
2613     } else {
2614         my $cmf =
2615             $e->search_config_metabib_field({"field_class" => "identifier"})
2616                 or return $e->die_event;
2617
2618         my @identifiers = map { $_->name } @$cmf;
2619         my $query = join(" || ", map { "id|$_: $term" } @identifiers);
2620
2621         my $search = create OpenSRF::AppSession("open-ils.search");
2622         my $search_result = $search->request(
2623             "open-ils.search.biblio.multiclass.query.staff", {}, $query
2624         )->gather(1);
2625         $search->disconnect;
2626
2627         # Un-nest results. They tend to look like [[1],[2],[3]] for some reason.
2628         @ids = map { @{$_} } @{$search_result->{"ids"}};
2629
2630         unless (@ids) {
2631             $e->disconnect;
2632             return undef;
2633         }
2634     }
2635
2636     my $bre = $e->search_biblio_record_entry([
2637         {"id" => \@ids}, {
2638             "flesh" => 2, "flesh_fields" => {
2639                 "bre" => ["subscriptions"],
2640                 "ssub" => ["owning_lib"]
2641             }
2642         }
2643     ]) or return $e->die_event;
2644
2645     if (@$bre && $options->{"require_subscriptions"}) {
2646         $bre = [ grep { @{$_->subscriptions} } @$bre ];
2647     }
2648
2649     $e->disconnect;
2650
2651     if (@$bre) { # re-evaluate after possible grep
2652         if ($options->{"add_mvr"}) {
2653             $client->respond(
2654                 {"bre" => $_, "mvr" => _get_mvr($_->id)}
2655             ) foreach (@$bre);
2656         } else {
2657             $client->respond($_) foreach (@$bre);
2658         }
2659     }
2660
2661     undef;
2662 }
2663
2664 __PACKAGE__->register_method(
2665     "method" => "get_receivable_items",
2666     "api_name" => "open-ils.serial.items.receivable.by_subscription",
2667     "stream" => 1,
2668     "signature" => {
2669         "desc" => "Return all receivable items under a given subscription",
2670         "params" => [
2671             {"desc" => "Authtoken", "type" => "string"},
2672             {"desc" => "Subscription ID", "type" => "number"},
2673         ],
2674         "return" => {
2675             "desc" => "All receivable items under a given subscription",
2676             "type" => "object"
2677         }
2678     }
2679 );
2680
2681 __PACKAGE__->register_method(
2682     "method" => "get_receivable_items",
2683     "api_name" => "open-ils.serial.items.receivable.by_issuance",
2684     "stream" => 1,
2685     "signature" => {
2686         "desc" => "Return all receivable items under a given issuance",
2687         "params" => [
2688             {"desc" => "Authtoken", "type" => "string"},
2689             {"desc" => "Issuance ID", "type" => "number"},
2690         ],
2691         "return" => {
2692             "desc" => "All receivable items under a given issuance",
2693             "type" => "object"
2694         }
2695     }
2696 );
2697
2698 sub get_receivable_items {
2699     my ($self, $client, $auth, $term)  = @_;
2700
2701     my $e = new_editor("authtoken" => $auth);
2702     return $e->die_event unless $e->checkauth;
2703
2704     # XXX permissions
2705
2706     my $by = ($self->api_name =~ /by_(\w+)$/)[0];
2707
2708     my %where = (
2709         "issuance" => {"issuance" => $term},
2710         "subscription" => {"+siss" => {"subscription" => $term}}
2711     );
2712
2713     my $item_ids = $e->json_query(
2714         {
2715             "select" => {"sitem" => ["id"]},
2716             "from" => {"sitem" => "siss"},
2717             "where" => {
2718                 %{$where{$by}}, "date_received" => undef
2719             },
2720             "order_by" => {"sitem" => ["id"]}
2721         }
2722     ) or return $e->die_event;
2723
2724     return undef unless @$item_ids;
2725
2726     foreach (map { $_->{"id"} } @$item_ids) {
2727         $client->respond(
2728             $e->retrieve_serial_item([
2729                 $_, {
2730                     "flesh" => 3,
2731                     "flesh_fields" => {
2732                         "sitem" => ["stream", "issuance"],
2733                         "sstr" => ["distribution"],
2734                         "sdist" => ["holding_lib"]
2735                     }
2736                 }
2737             ])
2738         );
2739     }
2740
2741     $e->disconnect;
2742     undef;
2743 }
2744
2745 __PACKAGE__->register_method(
2746     "method" => "get_receivable_issuances",
2747     "api_name" => "open-ils.serial.issuances.receivable",
2748     "stream" => 1,
2749     "signature" => {
2750         "desc" => "Return all issuances with receivable items given " .
2751             "a subscription ID",
2752         "params" => [
2753             {"desc" => "Authtoken", "type" => "string"},
2754             {"desc" => "Subscription ID", "type" => "number"},
2755         ],
2756         "return" => {
2757             "desc" => "All issuances with receivable items " .
2758                 "(but not the items themselves)", "type" => "object"
2759         }
2760     }
2761 );
2762
2763 sub get_receivable_issuances {
2764     my ($self, $client, $auth, $sub_id) = @_;
2765
2766     my $e = new_editor("authtoken" => $auth);
2767     return $e->die_event unless $e->checkauth;
2768
2769     # XXX permissions
2770
2771     my $issuance_ids = $e->json_query({
2772         "select" => {
2773             "siss" => [
2774                 {"transform" => "distinct", "column" => "id"},
2775                 "date_published"
2776             ]
2777         },
2778         "from" => {"siss" => "sitem"},
2779         "where" => {
2780             "subscription" => $sub_id,
2781             "+sitem" => {"date_received" => undef}
2782         },
2783         "order_by" => {
2784             "siss" => {"date_published" => {"direction" => "asc"}}
2785         }
2786
2787     }) or return $e->die_event;
2788
2789     $client->respond($e->retrieve_serial_issuance($_->{"id"}))
2790         foreach (@$issuance_ids);
2791
2792     $e->disconnect;
2793     undef;
2794 }
2795
2796 1;