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