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