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