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