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