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