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