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