]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Serial.pm
071922c9de86ab7c0d4b68078a3c838516596c53
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / 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 DateTime::Format::ISO8601;
52 use MARC::File::XML (BinaryEncoding => 'utf8');
53
54 use OpenILS::Application::Serial::OPAC;
55
56 my $U = 'OpenILS::Application::AppUtils';
57 my @MFHD_NAMES = ('basic','supplement','index');
58 my %MFHD_NAMES_BY_TAG = (  '853' => $MFHD_NAMES[0],
59                         '863' => $MFHD_NAMES[0],
60                         '854' => $MFHD_NAMES[1],
61                         '864' => $MFHD_NAMES[1],
62                         '855' => $MFHD_NAMES[2],
63                         '865' => $MFHD_NAMES[2] );
64 my %MFHD_TAGS_BY_NAME = (  $MFHD_NAMES[0] => '853',
65                         $MFHD_NAMES[1] => '854',
66                         $MFHD_NAMES[2] => '855');
67 my $_strp_date = new DateTime::Format::Strptime(pattern => '%F');
68 my %FM_NAME_TO_ID = (
69     'subscription' => 'ssub',
70     'distribution' => 'sdist',
71     'item' => 'sitem'
72     );
73
74 # helper method for conforming dates to ISO8601
75 sub _cleanse_dates {
76     my $item = shift;
77     my $fields = shift;
78
79     foreach my $field (@$fields) {
80         $item->$field(OpenSRF::Utils::clense_ISO8601($item->$field)) if $item->$field;
81     }
82     return 0;
83 }
84
85 sub _get_mvr {
86     $U->simplereq(
87         "open-ils.search",
88         "open-ils.search.biblio.record.mods_slim.retrieve",
89         @_
90     );
91 }
92
93
94 ##########################################################################
95 # item methods
96 #
97 __PACKAGE__->register_method(
98     method    => "create_item_safely",
99     api_name  => "open-ils.serial.item.create",
100     api_level => 1,
101     stream    => 1,
102     argc      => 3,
103     signature => {
104         desc => q/Creates any number of items, respecting only a few of the
105         submitted fields, as the user shouldn't be able to freely set certain
106         ones/,
107         params => [
108             {name=> "authtoken", desc => "Authtoken for current user session",
109                 type => "string"},
110             {name => "item", desc => "serial item",
111                 type => "object", class => "sitem"},
112             {name => "count",
113                 desc => "optional: how many items to make " .
114                     "(default 1; 1-100 permitted)",
115                 type => "number"}
116         ],
117         return => {
118             desc => "created items (a stream of them)",
119             type => "object", class => "sitem"
120         }
121     }
122 );
123 __PACKAGE__->register_method(
124     method    => "update_item_safely",
125     api_name  => "open-ils.serial.item.update",
126     api_level => 1,
127     stream    => 1,
128     argc      => 2,
129     signature => {
130         desc => q/Edit a serial item, respecting only a few of the
131         submitted fields, as the user shouldn't be able to freely set certain
132         ones/,
133         params => [
134             {name=> "authtoken", desc => "Authtoken for current user session",
135                 type => "string"},
136             {name => "item", desc => "serial item",
137                 type => "object", class => "sitem"},
138         ],
139         return => {
140             desc => "created item", type => "object", class => "sitem"
141         }
142     }
143 );
144
145 sub _set_safe_item_fields {
146     my $dest = shift;
147     my $source = shift;
148     my $requestor_id = shift;
149     # extra fields remain in @_
150
151     $dest->edit_date("now");
152     $dest->editor($requestor_id);
153
154     my @fields = qw/date_expected date_received status/;
155
156     for my $field (@fields, @_) {
157         $dest->$field($source->$field);
158     }
159 }
160
161 sub update_item_safely {
162     my ($self, $client, $auth, $item) = @_;
163
164     my $e = new_editor("xact" => 1, "authtoken" => $auth);
165     $e->checkauth or return $e->die_event;
166
167     my $orig = $e->retrieve_serial_item([
168         $item->id, {
169             "flesh" => 2, "flesh_fields" => {
170                 "sitem" => ["stream"], "sstr" => ["distribution"]
171             }
172         }
173     ]) or return $e->die_event;
174
175     return $e->die_event unless $e->allowed(
176         "ADMIN_SERIAL_ITEM", $orig->stream->distribution->holding_lib
177     );
178
179     _set_safe_item_fields($orig, $item, $e->requestor->id);
180     $e->update_serial_item($orig) or return $e->die_event;
181
182     $client->respond($e->retrieve_serial_item($item->id));
183     $e->commit or return $e->die_event;
184     undef;
185 }
186
187 sub create_item_safely {
188     my ($self, $client, $auth, $item, $count) = @_;
189
190     $count = int $count;
191     $count ||= 1;
192     return new OpenILS::Event(
193         "BAD_PARAMS", note => "Count should be from 1 to 100"
194     ) unless $count >= 1 and $count <= 100;
195
196     my $e = new_editor("xact" => 1, "authtoken" => $auth);
197     $e->checkauth or return $e->die_event;
198
199     my $stream = $e->retrieve_serial_stream([
200         $item->stream, {
201             "flesh" => 1, "flesh_fields" => {"sstr" => ["distribution"]}
202         }
203     ]) or return $e->die_event;
204
205     return $e->die_event unless $e->allowed(
206         "ADMIN_SERIAL_ITEM", $stream->distribution->holding_lib
207     );
208
209     for (my $i = 0; $i < $count; $i++) {
210         my $actual = new Fieldmapper::serial::item;
211         $actual->creator($e->requestor->id);
212         _set_safe_item_fields(
213             $actual, $item, $e->requestor->id, "issuance", "stream"
214         );
215
216         $e->create_serial_item($actual) or return $e->die_event;
217         $client->respond($e->data);
218     }
219
220     $e->commit or return $e->die_event;
221     undef;
222 }
223
224 __PACKAGE__->register_method(
225     method    => 'fleshed_item_alter',
226     api_name  => 'open-ils.serial.item.fleshed.batch.update',
227     api_level => 1,
228     argc      => 2,
229     signature => {
230         desc     => 'Receives an array of one or more items and updates the database as needed',
231         'params' => [ {
232                  name => 'authtoken',
233                  desc => 'Authtoken for current user session',
234                  type => 'string'
235             },
236             {
237                  name => 'items',
238                  desc => 'Array of fleshed items',
239                  type => 'array'
240             }
241
242         ],
243         'return' => {
244             desc => 'Returns 1 if successful, event if failed',
245             type => 'mixed'
246         }
247     }
248 );
249
250 sub fleshed_item_alter {
251     my( $self, $conn, $auth, $items ) = @_;
252     return 1 unless ref $items;
253     my( $reqr, $evt ) = $U->checkses($auth);
254     return $evt if $evt;
255     my $editor = new_editor(requestor => $reqr, xact => 1);
256     my $override = $self->api_name =~ /override/;
257
258     my %found_sdist_ids;
259     my %found_sstr_ids;
260     for my $item (@$items) {
261         my $sstr_id = ref $item->stream ? $item->stream->id : $item->stream;
262         if (!exists($found_sstr_ids{$sstr_id})) {
263             my $sstr;
264             if (ref $item->stream) {
265                 $sstr = $item->stream;
266             } else {
267                 $sstr = $editor->retrieve_serial_stream($item->stream) or return $editor->die_event;
268             }
269             if (!exists($found_sdist_ids{$sstr->distribution})) {
270                 my $sdist = $editor->retrieve_serial_distribution($sstr->distribution) or return $editor->die_event;
271                 return $editor->die_event unless
272                     $editor->allowed("ADMIN_SERIAL_STREAM", $sdist->holding_lib);
273                 $found_sdist_ids{$sstr->distribution} = 1;
274             }
275             $found_sstr_ids{$sstr_id} = 1;
276         }
277
278         $item->editor($editor->requestor->id);
279         $item->edit_date('now');
280
281         if( $item->isdeleted ) {
282             $evt = _delete_sitem( $editor, $override, $item);
283         } elsif( $item->isnew ) {
284             # TODO: reconsider this
285             # if the item has a new issuance, create the issuance first
286             if (ref $item->issuance eq 'Fieldmapper::serial::issuance' and $item->issuance->isnew) {
287                 fleshed_issuance_alter($self, $conn, $auth, [$item->issuance]);
288             }
289             _cleanse_dates($item, ['date_expected','date_received']);
290             $evt = _create_sitem( $editor, $item );
291         } else {
292             _cleanse_dates($item, ['date_expected','date_received']);
293             $evt = _update_sitem( $editor, $override, $item );
294         }
295     }
296
297     if( $evt ) {
298         $logger->info("fleshed item-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
299         $editor->rollback;
300         return $evt;
301     }
302     $logger->debug("item-alter: done updating item batch");
303     $editor->commit;
304     $logger->info("fleshed item-alter successfully updated ".scalar(@$items)." items");
305     return 1;
306 }
307
308 sub _delete_sitem {
309     my ($editor, $override, $item) = @_;
310     $logger->info("item-alter: delete item ".OpenSRF::Utils::JSON->perl2JSON($item));
311     return $editor->event unless $editor->delete_serial_item($item);
312     return 0;
313 }
314
315 sub _create_sitem {
316     my ($editor, $item) = @_;
317
318     $item->creator($editor->requestor->id);
319     $item->create_date('now');
320
321     $logger->info("item-alter: new item ".OpenSRF::Utils::JSON->perl2JSON($item));
322     return $editor->event unless $editor->create_serial_item($item);
323     return 0;
324 }
325
326 sub _update_sitem {
327     my ($editor, $override, $item) = @_;
328
329     $logger->info("item-alter: retrieving item ".$item->id);
330     my $orig_item = $editor->retrieve_serial_item($item->id);
331
332     $logger->info("item-alter: original item ".OpenSRF::Utils::JSON->perl2JSON($orig_item));
333     $logger->info("item-alter: updated item ".OpenSRF::Utils::JSON->perl2JSON($item));
334     return $editor->event unless $editor->update_serial_item($item);
335     return 0;
336 }
337
338 __PACKAGE__->register_method(
339     method  => "fleshed_serial_item_retrieve_batch",
340     authoritative => 1,
341     api_name    => "open-ils.serial.item.fleshed.batch.retrieve"
342 );
343
344 sub fleshed_serial_item_retrieve_batch {
345     my( $self, $client, $ids ) = @_;
346 # FIXME: permissions?
347     $logger->info("Fetching fleshed serial items @$ids");
348     return $U->cstorereq(
349         "open-ils.cstore.direct.serial.item.search.atomic",
350         { id => $ids },
351         { flesh => 2,
352           flesh_fields => {sitem => [ qw/issuance creator editor stream unit notes/ ], sunit => ["call_number"], siss => [qw/creator editor subscription/]}
353         });
354 }
355
356
357 ##########################################################################
358 # issuance methods
359 #
360 __PACKAGE__->register_method(
361     method    => 'fleshed_issuance_alter',
362     api_name  => 'open-ils.serial.issuance.fleshed.batch.update',
363     api_level => 1,
364     argc      => 2,
365     signature => {
366         desc     => 'Receives an array of one or more issuances and updates the database as needed',
367         'params' => [ {
368                  name => 'authtoken',
369                  desc => 'Authtoken for current user session',
370                  type => 'string'
371             },
372             {
373                  name => 'issuances',
374                  desc => 'Array of fleshed issuances',
375                  type => 'array'
376             }
377
378         ],
379         'return' => {
380             desc => 'Returns 1 if successful, event if failed',
381             type => 'mixed'
382         }
383     }
384 );
385
386 sub fleshed_issuance_alter {
387     my( $self, $conn, $auth, $issuances ) = @_;
388     return 1 unless ref $issuances;
389     my( $reqr, $evt ) = $U->checkses($auth);
390     return $evt if $evt;
391     my $editor = new_editor(authtoken => $auth, requestor => $reqr, xact => 1);
392     my $override = $self->api_name =~ /override/;
393
394     my %found_ssub_ids;
395     my %regen_ssub_ids;
396     for my $issuance (@$issuances) {
397         my $ssub_id = ref $issuance->subscription ? $issuance->subscription->id : $issuance->subscription;
398         if (!exists($found_ssub_ids{$ssub_id})) {
399             my $owning_lib_id;
400             if (ref $issuance->subscription) {
401                 $owning_lib_id = $issuance->subscription->owning_lib;
402             } else {
403                 my $ssub = $editor->retrieve_serial_subscription($issuance->subscription) or return $editor->die_event;
404                 $owning_lib_id = $ssub->owning_lib;
405             }
406             return $editor->die_event unless
407                 $editor->allowed("ADMIN_SERIAL_SUBSCRIPTION", $owning_lib_id);
408             $found_ssub_ids{$ssub_id} = 1;
409         }
410
411         my $issuanceid = $issuance->id;
412         $issuance->editor($editor->requestor->id);
413         $issuance->edit_date('now');
414
415         if( $issuance->isdeleted ) {
416             $evt = _delete_siss( $editor, $override, $issuance);
417             $regen_ssub_ids{$ssub_id} = 1;
418         } elsif( $issuance->isnew ) {
419             _cleanse_dates($issuance, ['date_published']);
420             $evt = _create_siss( $editor, $issuance );
421         } else {
422             _cleanse_dates($issuance, ['date_published']);
423             $evt = _update_siss( $editor, $override, $issuance );
424         }
425
426         last if $evt;
427     }
428
429     if (!$evt) {
430         # if we deleted any issuances, update the summaries
431         # for all dists in those ssubs
432         my @ssub_ids = keys %regen_ssub_ids;
433         $evt = _regenerate_summaries($editor, {'ssub_ids' => \@ssub_ids}) if @ssub_ids;
434     }
435
436     if ( $evt ) {
437         $logger->info("fleshed issuance-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
438         $editor->rollback;
439         return $evt;
440     }
441
442     $logger->debug("issuance-alter: done updating issuance batch");
443     $editor->commit;
444     $logger->info("fleshed issuance-alter successfully updated ".scalar(@$issuances)." issuances");
445     return 1;
446 }
447
448 sub _delete_siss {
449     my ($editor, $override, $issuance) = @_;
450     $logger->info("issuance-alter: delete issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
451     return $editor->event unless $editor->delete_serial_issuance($issuance);
452     return 0;
453 }
454
455 sub _create_siss {
456     my ($editor, $issuance) = @_;
457
458     $issuance->creator($editor->requestor->id);
459     $issuance->create_date('now');
460
461     $logger->info("issuance-alter: new issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
462     return $editor->event unless $editor->create_serial_issuance($issuance);
463     return 0;
464 }
465
466 sub _update_siss {
467     my ($editor, $override, $issuance) = @_;
468
469     $logger->info("issuance-alter: retrieving issuance ".$issuance->id);
470     my $orig_issuance = $editor->retrieve_serial_issuance($issuance->id);
471
472     $logger->info("issuance-alter: original issuance ".OpenSRF::Utils::JSON->perl2JSON($orig_issuance));
473     $logger->info("issuance-alter: updated issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
474     return $editor->event unless $editor->update_serial_issuance($issuance);
475     return 0;
476 }
477
478 __PACKAGE__->register_method(
479     method  => "fleshed_serial_issuance_retrieve_batch",
480     authoritative => 1,
481     api_name    => "open-ils.serial.issuance.fleshed.batch.retrieve"
482 );
483
484 sub fleshed_serial_issuance_retrieve_batch {
485     my( $self, $client, $ids ) = @_;
486 # FIXME: permissions?
487     $logger->info("Fetching fleshed serial issuances @$ids");
488     return $U->cstorereq(
489         "open-ils.cstore.direct.serial.issuance.search.atomic",
490         { id => $ids },
491         { flesh => 1,
492           flesh_fields => {siss => [ qw/creator editor subscription/ ]}
493         });
494 }
495
496 __PACKAGE__->register_method(
497     method  => "pub_fleshed_serial_issuance_retrieve_batch",
498     api_name    => "open-ils.serial.issuance.pub_fleshed.batch.retrieve",
499     signature => {
500         desc => q/
501             Public (i.e. OPAC) call for getting at the sub and 
502             ultimately the record entry from an issuance
503         /,
504         params => [{name => 'ids', desc => 'Array of IDs', type => 'array'}],
505         return => {
506             desc => q/
507                 issuance objects, fleshed with subscriptions
508             /,
509             class => 'siss'
510         }
511     }
512 );
513 sub pub_fleshed_serial_issuance_retrieve_batch {
514     my( $self, $client, $ids ) = @_;
515     return [] unless $ids and @$ids;
516     return new_editor()->search_serial_issuance([
517         { id => $ids },
518         { 
519             flesh => 1,
520             flesh_fields => {siss => [ qw/subscription/ ]}
521         }
522     ]);
523 }
524
525 sub received_siss_by_bib {
526     # XXX this is somewhat wrong in implementation and should not be used in
527     # new places - senator
528     my $self = shift;
529     my $client = shift;
530     my $bib = shift;
531
532     my $args = shift || {};
533     $$args{order} ||= 'asc';
534
535     my $global = $$args{global} == 0 ? 0 : 1;
536
537     my $e = new_editor();
538     my $issuances = $e->json_query({
539         select  => {
540             siss => [
541                 $global ? { transform => "min", column => "id", aggregate => 1 } : "id",
542                 "label",
543                 "date_published"
544             ],
545             "sitem" => [
546                 # We're not really interested in the minimum here.  This is
547                 # just a way to distinguish issuances whose items have units
548                 # from issuances whose items have no units, without altogether
549                 # excluding the latter type of issuances.
550                 {"transform" => "min", "alias" => "has_units",
551                     "column" => "unit", "aggregate" => 1}
552             ]
553         },
554         from => {
555             ssub => {
556                 siss => {
557                     field => 'subscription',
558                     fkey  => 'id',
559                     join  => {
560                         sitem => {
561                             field  => 'issuance',
562                             fkey   => 'id',
563                             $$args{ou} ? ( join  => {
564                                 sstr => {
565                                     field => 'id',
566                                     fkey  => 'stream',
567                                     join  => {
568                                         sdist => {
569                                             field  => 'id',
570                                             fkey   => 'distribution'
571                                         }
572                                     }
573                                 }
574                             }) : ()
575                         }
576                     }
577                 }
578             }
579         },
580         where => {
581             '+ssub'  => { record_entry => $bib },
582             $$args{type} ? ( '+siss' => { 'holding_type' => $$args{type} } ) : (),
583             '+sitem' => {
584                 # XXX should we also take specific item statuses into account?
585                 date_received => { '!=' => undef },
586                 $$args{status} ? ( 'status' => $$args{status} ) : ()
587             },
588             $$args{ou} ? ( '+sdist' => {
589                 holding_lib => {
590                     'in' => $U->get_org_descendants($$args{ou}, $$args{depth})
591                 }
592             }) : ()
593         },
594         $$args{limit}  ? ( limit  => $$args{limit}  ) : (),
595         $$args{offset} ? ( offset => $$args{offset} ) : (),
596         order_by => [{ class => 'siss', field => 'date_published', direction => $$args{order} }],
597         distinct => 1
598     });
599
600     $client->respond({
601         "issuance" => $e->retrieve_serial_issuance($_->{"id"}),
602         "has_units" => $_->{"has_units"} ? 1 : 0
603     }) for @$issuances;
604
605     return undef;
606 }
607 __PACKAGE__->register_method(
608     method    => 'received_siss_by_bib',
609     api_name  => 'open-ils.serial.received_siss.retrieve.by_bib',
610     api_level => 1,
611     argc      => 1,
612     stream    => 1,
613     signature => {
614         desc   => 'Receives a Bib ID and other optional params and returns "siss" (issuance) objects',
615         params => [
616             {   name => 'bibid',
617                 desc => 'id of the bre to which the issuances belong',
618                 type => 'number'
619             },
620             {   name => 'args',
621                 desc =>
622 q/A hash of optional arguments.  Valid keys and their meanings:
623     global := If true, return only one representative version of a conceptual issuance regardless of the number of subscriptions, otherwise return all issuance objects meeting the requested criteria, including conceptual duplicates. Valid values are 0 (false) and 1 (true, default).
624     order  := date_published sort direction, either "asc" (chronological, default) or "desc" (reverse chronological)
625     limit  := Number of issuances to return.  Useful for paging results, or finding the oldest or newest
626     offset := Number of issuance to skip before returning results.  Useful for paging.
627     orgid  := OU id used to scope retrieval, based on distribution.holding_lib
628     depth  := OU depth used to range the scope of orgid
629     type   := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
630     status := Item status filter. Valid values are "Bindery", "Bound", "Claimed", "Discarded", "Expected", "Not Held", "Not Published" and "Received". Can be a scalar (one) or arrayref (one or more).
631 /
632             }
633         ]
634     }
635 );
636
637
638 sub scoped_bib_holdings_summary {
639     # XXX this is somewhat wrong in implementation and should not be used in
640     # new places - senator
641     my $self = shift;
642     my $client = shift;
643     my $bibid = shift;
644     my $args = shift || {};
645
646     $args->{order} = 'asc';
647
648     my ($issuances) = $self->method_lookup('open-ils.serial.received_siss.retrieve.by_bib.atomic')->run( $bibid => $args );
649
650     # split into issuance type sets
651     my %type_blob = (basic => [], supplement => [], index => []);
652     push @{ $type_blob{ $_->{"issuance"}->holding_type } }, $_->{"issuance"}
653         for (@$issuances);
654
655     # generate a statement list for each type
656     my %statement_blob;
657     for my $type ( keys %type_blob ) {
658         my ($mfhd,$list) = _summarize_contents(new_editor(), $type_blob{$type});
659
660         return {} if $U->event_code($mfhd); # _summarize_contents() failed, bad data?
661
662         $statement_blob{$type} = $list;
663     }
664
665     return \%statement_blob;
666 }
667 __PACKAGE__->register_method(
668     method    => 'scoped_bib_holdings_summary',
669     api_name  => 'open-ils.serial.bib.summary_statements',
670     api_level => 1,
671     argc      => 1,
672     signature => {
673         desc   => '** DEPRECATED and only used by JSPAC. Somewhat wrong in implementation. *** Receives a Bib ID and other optional params and returns set of holdings statements',
674         params => [
675             {   name => 'bibid',
676                 desc => 'id of the bre to which the issuances belong',
677                 type => 'number'
678             },
679             {   name => 'args',
680                 desc =>
681 q/A hash of optional arguments.  Valid keys and their meanings:
682     orgid  := OU id used to scope retrieval, based on distribution.holding_lib
683     depth  := OU depth used to range the scope of orgid
684     type   := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
685     status := Item status filter. Valid values are "Bindery", "Bound", "Claimed", "Discarded", "Expected", "Not Held", "Not Published" and "Received". Can be a scalar (one) or arrayref (one or more).
686 /
687             }
688         ]
689     }
690 );
691
692
693 ##########################################################################
694 # unit methods
695 #
696 __PACKAGE__->register_method(
697     method    => 'fleshed_sunit_alter',
698     api_name  => 'open-ils.serial.sunit.fleshed.batch.update',
699     api_level => 1,
700     argc      => 2,
701     signature => {
702         desc     => 'Receives an array of one or more Units and updates the database as needed',
703         'params' => [ {
704                  name => 'authtoken',
705                  desc => 'Authtoken for current user session',
706                  type => 'string'
707             },
708             {
709                  name => 'sunits',
710                  desc => 'Array of fleshed Units',
711                  type => 'array'
712             }
713
714         ],
715         'return' => {
716             desc => 'Returns 1 if successful, event if failed',
717             type => 'mixed'
718         }
719     }
720 );
721
722 sub fleshed_sunit_alter {
723     my( $self, $conn, $auth, $sunits ) = @_;
724     return 1 unless ref $sunits;
725     my( $reqr, $evt ) = $U->checkses($auth);
726     return $evt if $evt;
727     my $editor = new_editor(requestor => $reqr, xact => 1);
728     my $override = $self->api_name =~ /override/;
729
730     my %found_cn_ids;
731     for my $sunit (@$sunits) {
732         my $cn_id = ref $sunit->call_number ? $sunit->call_number->id : $sunit->call_number;
733         if (!exists($found_cn_ids{$cn_id})) {
734             my $owning_lib_id;
735             if (ref $sunit->call_number) {
736                 $owning_lib_id = $sunit->call_number->owning_lib;
737             } else {
738                 my $cn = $editor->retrieve_asset_call_number($sunit->call_number) or return $editor->die_event;
739                 $owning_lib_id = $cn->owning_lib;
740             }
741             return $editor->die_event unless
742                 $editor->allowed("UPDATE_COPY", $owning_lib_id);
743             $found_cn_ids{$cn_id} = 1;
744         }
745
746         if( $sunit->isdeleted ) {
747             $evt = _delete_sunit( $editor, $override, $sunit );
748         } else {
749             $sunit->default_location( $sunit->default_location->id ) if ref $sunit->default_location;
750
751             if( $sunit->isnew ) {
752                 $evt = _create_sunit( $editor, $sunit );
753             } else {
754                 $evt = _update_sunit( $editor, $override, $sunit );
755             }
756         }
757     }
758
759     if( $evt ) {
760         $logger->info("fleshed sunit-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
761         $editor->rollback;
762         return $evt;
763     }
764     $logger->debug("sunit-alter: done updating sunit batch");
765     $editor->commit;
766     $logger->info("fleshed sunit-alter successfully updated ".scalar(@$sunits)." Units");
767     return 1;
768 }
769
770 sub _delete_sunit {
771     my ($editor, $override, $sunit) = @_;
772     $logger->info("sunit-alter: delete sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
773     return $editor->event unless $editor->delete_serial_unit($sunit);
774     return 0;
775 }
776
777 sub _create_sunit {
778     my ($editor, $sunit) = @_;
779
780     # The unique barcode constraint does not span asset.copy and serial.unit.
781     # ensure the barcode on the new unit does not collide with an existing
782     # asset.copy barcode.
783     my $existing = $editor->search_asset_copy(
784         {deleted => 'f', barcode => $sunit->barcode})->[0];
785
786     if (!$existing) {
787         # The DB will prevent duplicate serial.unit barcodes, but for 
788         # consistency (and a more specific error message for the
789         # user), prevent creation attempts on serial unit barcode
790         # collisions as well.
791         $existing = $editor->search_serial_unit(
792             {deleted => 'f', barcode => $sunit->barcode})->[0];
793     }
794
795     if ($existing) {
796         $editor->rollback;
797         return new OpenILS::Event(
798             'SERIAL_UNIT_BARCODE_COLLISION', note => 
799             'Serial unit barcode collides with existing unit/copy barcode',
800             payload => {barcode => $sunit->barcode}
801         );
802     }
803
804     $logger->info("sunit-alter: new Unit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
805     return $editor->die_event unless $editor->create_serial_unit($sunit);
806     return 0;
807 }
808
809 sub _update_sunit {
810     my ($editor, $override, $sunit) = @_;
811
812     $logger->info("sunit-alter: retrieving sunit ".$sunit->id);
813     my $orig_sunit = $editor->retrieve_serial_unit($sunit->id);
814
815     $logger->info("sunit-alter: original sunit ".OpenSRF::Utils::JSON->perl2JSON($orig_sunit));
816     $logger->info("sunit-alter: updated sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
817     return $editor->event unless $editor->update_serial_unit($sunit);
818     return 0;
819 }
820
821 __PACKAGE__->register_method(
822     method  => "retrieve_unit_list",
823     authoritative => 1,
824     api_name    => "open-ils.serial.unit_list.retrieve"
825 );
826
827 sub retrieve_unit_list {
828
829     my( $self, $client, @sdist_ids ) = @_;
830
831     if(ref($sdist_ids[0])) { @sdist_ids = @{$sdist_ids[0]}; }
832
833     my $e = new_editor();
834
835     my $query = {
836         'select' => 
837             { 'sunit' => [ 'id', 'summary_contents', 'sort_key' ],
838               'sitem' => ['stream'],
839               'sstr' => ['distribution'],
840               'sdist' => [{'column' => 'label', 'alias' => 'sdist_label'}]
841             },
842         'from' =>
843             { 'sdist' =>
844                 { 'sstr' =>
845                     { 'join' =>
846                         { 'sitem' =>
847                             { 'join' => { 'sunit' => {} } }
848                         }
849                     }
850                 }
851             },
852         'distinct' => 'true',
853         'where' => { '+sdist' => {'id' => \@sdist_ids} },
854         'order_by' => [{'class' => 'sunit', 'field' => 'sort_key'}]
855     };
856
857     my $unit_list_entries = $e->json_query($query);
858     
859     my @entries;
860     foreach my $entry (@$unit_list_entries) {
861         my $value = {'sunit' => $entry->{id}, 'sstr' => $entry->{stream}, 'sdist' => $entry->{distribution}};
862         my $label = $entry->{summary_contents};
863         if (length($label) > 100) {
864             $label = substr($label, 0, 100) . '...'; # limited space in dropdown / menu
865         }
866         $label = "[$entry->{sdist_label}/$entry->{stream} #$entry->{id}] " . $label;
867         push (@entries, [$label, OpenSRF::Utils::JSON->perl2JSON($value)]);
868     }
869
870     return \@entries;
871 }
872
873
874
875 ##########################################################################
876 # predict and receive methods
877 #
878 __PACKAGE__->register_method(
879     method    => 'make_predictions',
880     api_name  => 'open-ils.serial.make_predictions',
881     api_level => 1,
882     argc      => 1,
883     signature => {
884         desc     => 'Receives an ssub id and populates the issuance and item tables',
885         'params' => [ {
886                  name => 'ssub_id',
887                  desc => 'Serial Subscription ID',
888                  type => 'int'
889             }
890         ]
891     }
892 );
893
894 sub make_predictions {
895     my ($self, $conn, $authtoken, $args) = @_;
896
897     my $editor = OpenILS::Utils::CStoreEditor->new();
898     my $ssub_id = $args->{ssub_id};
899     my $mfhd = MFHD->new(MARC::Record->new());
900
901     my $ssub = $editor->retrieve_serial_subscription([$ssub_id]);
902     my $scaps = $editor->search_serial_caption_and_pattern({ subscription => $ssub_id, active => 't'});
903     my $sdists = $editor->search_serial_distribution( [{ subscription => $ssub->id }, { flesh => 1, flesh_fields => {sdist => [ qw/ streams / ]} }] ); #TODO: 'deleted' support?
904
905     my $total_streams = 0;
906     foreach (@$sdists) {
907         $total_streams += scalar(@{$_->streams});
908     }
909     if ($total_streams < 1) {
910         $editor->disconnect;
911         # XXX TODO new event type
912         return new OpenILS::Event(
913             "BAD_PARAMS", note =>
914                 "There are no streams to direct items. Can't predict."
915         );
916     }
917
918     unless (@$scaps) {
919         $editor->disconnect;
920         # XXX TODO new event type
921         return new OpenILS::Event(
922             "BAD_PARAMS", note =>
923                 "There are no active caption-and-pattern objects associated " .
924                 "with this subscription. Can't predict."
925         );
926     }
927
928     my @predictions;
929     my $link_id = 1;
930     foreach my $scap (@$scaps) {
931         my $caption_field = _revive_caption($scap);
932         $caption_field->update('8' => $link_id);
933         my $fake_chron_needed = 0;
934         # if we have missing chron pieces, we will add them later for prediction purposes
935         if (!$caption_field->enumeration_is_chronology) {
936             if (!$caption_field->subfield('i') # no year
937                 or !$caption_field->subfield('j')) { # we had a year, but no month or season
938                 $fake_chron_needed = '1';
939             }
940         }
941         $mfhd->append_fields($caption_field);
942         my $options = {
943                 'caption' => $caption_field,
944                 'scap_id' => $scap->id,
945                 'num_to_predict' => $args->{num_to_predict},
946                 'end_date' => defined $args->{end_date} ?
947                     $_strp_date->parse_datetime($args->{end_date}) : undef
948                 };
949         my $predict_from_siss;
950         if ($args->{base_issuance}) { # predict from a given issuance
951             $predict_from_siss = $args->{base_issuance}->holding_code;
952         } else { # default to predicting from last published
953             my $last_published = $editor->search_serial_issuance([
954                     {'caption_and_pattern' => $scap->id,
955                     'subscription' => $ssub_id},
956                 {limit => 1, order_by => { siss => "date_published DESC" }}]
957                 );
958             if ($last_published->[0]) {
959                 $predict_from_siss = $last_published->[0];
960                 unless ($predict_from_siss->holding_code) {
961                     $editor->disconnect;
962                     # XXX TODO new event type
963                     return new OpenILS::Event(
964                         "BAD_PARAMS", note =>
965                             "Last issuance has no holding code. Can't predict."
966                     );
967                 }
968             } else {
969                 $editor->disconnect;
970                 # XXX TODO make a new event type instead of hijacking this one
971                 return new OpenILS::Event(
972                     "BAD_PARAMS", note => "No issuance from which to predict!"
973                 );
974             }
975         }
976         $options->{predict_from} = _revive_holding($predict_from_siss->holding_code, $caption_field, 1); # fresh MFHD Record, so we simply default to 1 for seqno
977         if ($fake_chron_needed) {
978             $options->{faked_chron_date} = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($predict_from_siss->date_published));
979         }
980         push( @predictions, _generate_issuance_values($mfhd, $options) );
981         $link_id++;
982     }
983
984     my @issuances;
985     foreach my $prediction (@predictions) {
986         my $issuance = new Fieldmapper::serial::issuance;
987         $issuance->isnew(1);
988         $issuance->label($prediction->{label});
989         $issuance->date_published($prediction->{date_published}->strftime('%F'));
990         $issuance->holding_code(OpenSRF::Utils::JSON->perl2JSON($prediction->{holding_code}));
991         $issuance->holding_type($prediction->{holding_type});
992         $issuance->caption_and_pattern($prediction->{caption_and_pattern});
993         $issuance->subscription($ssub->id);
994         push (@issuances, $issuance);
995     }
996
997     my $evt = fleshed_issuance_alter($self, $conn, $authtoken, \@issuances);
998     return $evt if ref $evt;
999
1000     my @items;
1001     for (my $i = 0; $i < @issuances; $i++) {
1002         my $date_expected = $predictions[$i]->{date_published}->add(seconds => interval_to_seconds($ssub->expected_date_offset))->strftime('%F');
1003         my $issuance = $issuances[$i];
1004         #$issuance->label(interval_to_seconds($ssub->expected_date_offset));
1005         foreach my $sdist (@$sdists) {
1006             my $streams = $sdist->streams;
1007             foreach my $stream (@$streams) {
1008                 my $item = new Fieldmapper::serial::item;
1009                 $item->isnew(1);
1010                 $item->stream($stream->id);
1011                 $item->date_expected($date_expected);
1012                 $item->issuance($issuance->id);
1013                 push (@items, $item);
1014             }
1015         }
1016     }
1017     fleshed_item_alter($self, $conn, $authtoken, \@items); # FIXME: catch events
1018     return \@items;
1019 }
1020
1021 #
1022 # _generate_issuance_values() is an initial attempt at a function which can be used
1023 # to populate an issuance table with a list of predicted issues.  It accepts
1024 # a hash ref of options initially defined as:
1025 # caption : the caption field to predict on
1026 # num_to_predict : the number of issues you wish to predict
1027 # faked_chron_date : if the serial does not actually have a chronology caption (but we need one for prediction's sake), base predictions on this date
1028 #
1029 # The basic method is to first convert to a single holding if compressed, then
1030 # increment the holding and save the resulting values to @issuances.
1031
1032 # returns @issuance_values, an array of hashrefs containing (formatted
1033 # label, formatted chronology date, formatted estimated arrival date, and an
1034 # array ref of holding subfields as (key, value, key, value ...)) (not a hash
1035 # to protect order and possible duplicate keys), and a holding type.
1036 #
1037 sub _generate_issuance_values {
1038     my ($mfhd, $options) = @_;
1039     my $caption = $options->{caption};
1040     my $scap_id = $options->{scap_id};
1041     my $num_to_predict = $options->{num_to_predict};
1042     my $end_date = $options->{end_date};
1043     my $predict_from = $options->{predict_from};   # MFHD::Holding to predict from
1044     my $faked_chron_date = $options->{faked_chron_date};   # serial does not have a (complete) chronology caption, so add one (temporarily) based on this date 
1045
1046
1047 # Only needed for 'real' MFHD records, not our temp records
1048 #    my $link_id = $caption->link_id;
1049 #    if(!$predict_from) {
1050 #        my $htag = $caption->tag;
1051 #        $htag =~ s/^85/86/;
1052 #        my @holdings = $mfhd->holdings($htag, $link_id);
1053 #        my $last_holding = $holdings[-1];
1054 #
1055 #        #if ($last_holding->is_compressed) {
1056 #        #    $last_holding->compressed_to_last; # convert to last in range
1057 #        #}
1058 #        $predict_from = $last_holding;
1059 #    }
1060 #
1061
1062     $predict_from->notes('public',  []);
1063 # add a note marker for system use (?)
1064     $predict_from->notes('private', ['AUTOGEN']);
1065
1066     # our basic method for dealing with 'faked' chronologies will be to add it in, do the predicting, then take it back out
1067     my @faked_subfield_chars;
1068     if ($faked_chron_date) {
1069         my $faked_caption = new MARC::Field($caption->tag, $caption->indicator(1), $caption->indicator(2), $caption->subfields_list);
1070
1071         my %mfhd_chron_labels = ('i' => 'year', 'j' => 'month', 'k' => 'day');
1072         foreach my $subfield_char ('i', 'j', 'k') {
1073             if (!$caption->subfield($subfield_char)) { # if we are missing a piece, add it
1074                 push(@faked_subfield_chars, $subfield_char);
1075                 my $chron_name = $mfhd_chron_labels{$subfield_char};
1076                 $faked_caption->add_subfields($subfield_char => "($chron_name)");
1077                 my $method = $mfhd_chron_labels{$subfield_char};
1078                 $predict_from->add_subfields($subfield_char => $faked_chron_date->$chron_name);
1079             }
1080         }
1081         # because of the way MFHD::Caption and Holding work, it is simplest
1082         # to recreate rather than try to update
1083         $faked_caption = new MFHD::Caption($faked_caption);
1084         $predict_from = new MFHD::Holding($predict_from->seqno, new MARC::Field($predict_from->tag, $predict_from->indicator(1), $predict_from->indicator(2), $predict_from->subfields_list), $faked_caption);
1085     }
1086
1087     my @predictions = $mfhd->generate_predictions({'base_holding' => $predict_from, 'num_to_predict' => $num_to_predict, 'end_date' => $end_date});
1088
1089     my $pub_date;
1090     my @issuance_values;
1091     foreach my $prediction (@predictions) {
1092         $pub_date = $_strp_date->parse_datetime($prediction->chron_to_date);
1093         if ($faked_chron_date) { # get rid of the chronology portions and restore original caption
1094             $prediction->delete_subfield(code => \@faked_subfield_chars);
1095             $prediction = new MFHD::Holding($prediction->seqno, new MARC::Field($prediction->tag, $prediction->indicator(1), $prediction->indicator(2), $prediction->subfields_list), $caption);
1096         }
1097         push(
1098                 @issuance_values,
1099                 {
1100                     #$link_id,
1101                     label => $prediction->format,
1102                     date_published => $pub_date,
1103                     #date_expected => $date_expected->strftime('%F'),
1104                     holding_code => [$prediction->indicator(1),$prediction->indicator(2),$prediction->subfields_list],
1105                     holding_type => $MFHD_NAMES_BY_TAG{$caption->tag},
1106                     caption_and_pattern => $scap_id
1107                 }
1108             );
1109     }
1110
1111     return @issuance_values;
1112 }
1113
1114 sub _revive_caption {
1115     my $scap = shift;
1116
1117     my $pattern_code = $scap->pattern_code;
1118
1119     # build MARC::Field
1120     my $pattern_parts = OpenSRF::Utils::JSON->JSON2perl($pattern_code);
1121     unshift(@$pattern_parts, $MFHD_TAGS_BY_NAME{$scap->type});
1122     my $pattern_field = new MARC::Field(@$pattern_parts);
1123
1124     # build MFHD::Caption
1125     return new MFHD::Caption($pattern_field);
1126 }
1127
1128 sub _revive_holding {
1129     my $holding_code = shift;
1130     my $caption_field = shift;
1131     my $seqno = shift;
1132
1133     # build MARC::Field
1134     my $holding_parts = OpenSRF::Utils::JSON->JSON2perl($holding_code);
1135     my $captag = $caption_field->tag;
1136     $captag =~ s/^85/86/;
1137     unshift(@$holding_parts, $captag);
1138     my $holding_field = new MARC::Field(@$holding_parts);
1139
1140     # build MFHD::Holding
1141     return new MFHD::Holding($seqno, $holding_field, $caption_field);
1142
1143     # TODO(?) the underlying MARC and the Holding object end up in conflict concerning subfield '8'
1144 }
1145
1146 __PACKAGE__->register_method(
1147     method    => 'unitize_items',
1148     api_name  => 'open-ils.serial.receive_items',
1149     api_level => 1,
1150     argc      => 1,
1151     signature => {
1152         desc     => 'Marks an item as received, updates the shelving unit (creating a new shelving unit if needed), and updates the summaries',
1153         'params' => [ {
1154                  name => 'items',
1155                  desc => 'array of serial items',
1156                  type => 'array'
1157             },
1158             {
1159                  name => 'barcodes',
1160                  desc => 'hash of item_ids => barcodes',
1161                  type => 'hash'
1162             },
1163             {
1164                  name => 'call_numbers',
1165                  desc => 'hash of item_ids => call_numbers',
1166                  type => 'hash'
1167             },
1168             {
1169                  name => 'donor_unit_ids',
1170                  desc => 'hash of unit_ids => 1, keyed with ids of any units giving up items',
1171                  type => 'hash'
1172             }
1173         ],
1174         'return' => {
1175             desc => 'Returns number of received items (num_items) and new unit ID, if applicable (new_unit_id)',
1176             type => 'hashref'
1177         }
1178     }
1179 );
1180
1181 __PACKAGE__->register_method(
1182     method    => 'unitize_items',
1183     api_name  => 'open-ils.serial.bind_items',
1184     api_level => 1,
1185     argc      => 1,
1186     signature => {
1187         desc     => 'Marks an item as bound, updates the shelving unit (creating a new shelving unit if needed)',
1188         'params' => [ {
1189                  name => 'items',
1190                  desc => 'array of serial items',
1191                  type => 'array'
1192             },
1193             {
1194                  name => 'barcodes',
1195                  desc => 'hash of item_ids => barcodes',
1196                  type => 'hash'
1197             },
1198             {
1199                  name => 'call_numbers',
1200                  desc => 'hash of item_ids => call_numbers',
1201                  type => 'hash'
1202             },
1203             {
1204                  name => 'donor_unit_ids',
1205                  desc => 'hash of unit_ids => 1, keyed with ids of any units giving up items',
1206                  type => 'hash'
1207             }
1208         ],
1209         'return' => {
1210             desc => 'Returns number of bound items (num_items) and new unit ID, if applicable (new_unit_id)',
1211             type => 'hashref'
1212         }
1213     }
1214 );
1215
1216 # TODO: reset/delete claims information once implemented
1217 # XXX: deal with emptied call numbers here?
1218 __PACKAGE__->register_method(
1219     method    => 'unitize_items',
1220     api_name  => 'open-ils.serial.reset_items',
1221     api_level => 1,
1222     argc      => 1,
1223     signature => {
1224         desc     => 'Resets the items to Expected, updates the shelving unit (deleting the shelving unit if empty), and updates the summaries',
1225         'params' => [ {
1226                  name => 'items',
1227                  desc => 'array of serial items',
1228                  type => 'array'
1229             }
1230         ],
1231         'return' => {
1232             desc => 'Returns number of reset items (num_items)',
1233             type => 'hashref'
1234         }
1235     }
1236 );
1237
1238 sub unitize_items {
1239     my ($self, $conn, $auth, $items, $barcodes, $call_numbers, $donor_unit_ids) = @_;
1240
1241     my $editor = new_editor("authtoken" => $auth, "xact" => 1);
1242     return $editor->die_event unless $editor->checkauth;
1243     return $editor->die_event unless $editor->allowed("RECEIVE_SERIAL");
1244     $self->api_name =~ /serial\.(\w*)_items/;
1245     my $mode = $1;
1246     
1247     my %found_unit_ids;
1248     if ($donor_unit_ids) { # units giving up items need updating as well
1249         %found_unit_ids = %$donor_unit_ids;
1250     }
1251     my %found_stream_ids;
1252     my %found_types;
1253
1254     my %stream_ids_by_unit_id;
1255
1256     my %unit_map;
1257     my %sdist_by_unit_id;
1258     my %call_number_by_unit_id;
1259     my %sdist_by_stream_id;
1260
1261     my $new_unit_id; # id for '-2' units to share
1262     foreach my $item (@$items) {
1263         # for debugging only, TODO: delete
1264         if (!ref $item) { # hopefully we got an id instead
1265             $item = $editor->retrieve_serial_item($item);
1266         }
1267         # get ids
1268         my $unit_id = ref($item->unit) ? $item->unit->id : $item->unit;
1269         my $stream_id = ref($item->stream) ? $item->stream->id : $item->stream;
1270         my $issuance_id = ref($item->issuance) ? $item->issuance->id : $item->issuance;
1271         #TODO: evt on any missing ids
1272
1273         if ($mode eq 'receive') {
1274             $item->date_received('now');
1275             $item->status('Received');
1276         } elsif ($mode eq 'reset') {
1277             # clear date_received
1278             $item->clear_date_received;
1279             # Set status to 'Expected'
1280             $item->status('Expected');
1281             # remove from unit
1282             $item->clear_unit;
1283         }
1284
1285         # check for types to trigger summary updates
1286         my $scap;
1287         if (!ref $item->issuance) {
1288             my $scaps = $editor->search_serial_caption_and_pattern([{"+siss" => {"id" => $issuance_id}}, { "join" => {"siss" => {}} }]);
1289             $scap = $scaps->[0];
1290         } elsif (!ref $item->issuance->caption_and_pattern) {
1291             $scap = $editor->retrieve_serial_caption_and_pattern($item->issuance->caption_and_pattern);
1292         } else {
1293             $scap = $editor->issuance->caption_and_pattern;
1294         }
1295         if (!exists($found_types{$stream_id})) {
1296             $found_types{$stream_id} = {};
1297         }
1298         $found_types{$stream_id}->{$scap->type} = 1;
1299
1300         # create unit if needed
1301         if ($unit_id == -1 or (!$new_unit_id and $unit_id == -2)) { # create unit per item
1302             my $unit;
1303             my $sdists = $editor->search_serial_distribution([
1304                 {"+sstr" => {"id" => $stream_id}},
1305                 {
1306                     "join" => {"sstr" => {}},
1307                     "flesh" => 1,
1308                     "flesh_fields" => {"sdist" => ["subscription"]}
1309                 }]);
1310             $unit = _build_unit($editor, $sdists->[0], $mode);
1311             # if _build_unit fails, $unit is an event, so return it
1312             if ($U->event_code($unit)) {
1313                 $editor->rollback;
1314                 $unit->{"note"} = "Item ID: " . $item->id;
1315                 return $unit;
1316             }
1317             $unit->barcode($barcodes->{$item->id}) if exists($barcodes->{$item->id});
1318             my $evt =  _create_sunit($editor, $unit);
1319             return $evt if $evt;
1320             if ($unit_id == -2) {
1321                 $new_unit_id = $unit->id;
1322                 $unit_id = $new_unit_id;
1323             } else {
1324                 $unit_id = $unit->id;
1325             }
1326             $item->unit($unit_id);
1327             
1328             # get unit with 'DEFAULT's and save unit, sdist, and call number for later use
1329             $unit = $editor->retrieve_serial_unit($unit->id);
1330             $unit_map{$unit_id} = $unit;
1331             $sdist_by_unit_id{$unit_id} = $sdists->[0];
1332             $call_number_by_unit_id{$unit_id} = $call_numbers->{$item->id};
1333             $sdist_by_stream_id{$stream_id} = $sdists->[0];
1334         } elsif ($unit_id == -2) { # create one unit for all '-2' items
1335             $unit_id = $new_unit_id;
1336             $item->unit($unit_id);
1337         }
1338
1339         $found_stream_ids{$stream_id} = 1;
1340
1341         if (defined($unit_id) and $unit_id ne '') {
1342             $found_unit_ids{$unit_id} = 1;
1343             # save the stream_id for this unit_id
1344             # TODO: prevent items from different streams in same unit? (perhaps in interface)
1345             $stream_ids_by_unit_id{$unit_id} = $stream_id;
1346         } else {
1347             $item->clear_unit;
1348         }
1349
1350         my $evt = _update_sitem($editor, undef, $item);
1351         return $evt if $evt;
1352     }
1353
1354     # cleanup 'dead' units (units which are now emptied of their items)
1355     my $dead_units = $editor->search_serial_unit([{'+sitem' => {'id' => undef}, 'deleted' => 'f'}, {'join' => {'sitem' => {'type' => 'left'}}}]);
1356     foreach my $unit (@$dead_units) {
1357         _delete_sunit($editor, undef, $unit);
1358         delete $found_unit_ids{$unit->id};
1359     }
1360
1361     # deal with unit level contents
1362     foreach my $unit_id (keys %found_unit_ids) {
1363
1364         # get all the needed issuances for unit
1365         # TODO remove 'Bindery' from this search (leaving it in for now for backwards compatibility with any current test environment data)
1366         my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"unit" => $unit_id, "status" => ["Received", "Bindery"]}}, {"join" => {"sitem" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1367         #TODO: evt on search failure
1368
1369         # retrieve and update unit contents
1370         my $sunit;
1371         my $sdist;
1372         my $call_number_string;
1373         my $record_id;
1374         # if we just created the unit, we will already have it and the distribution stored, and we will need to assign the call number
1375         if (exists $unit_map{$unit_id}) {
1376             $sunit = $unit_map{$unit_id};
1377             $sdist = $sdist_by_unit_id{$unit_id};
1378             $call_number_string = $call_number_by_unit_id{$unit_id};
1379             $record_id = $sdist->subscription->record_entry;
1380         } else {
1381             # XXX: this code assumes you will not have units which mix streams/distributions, but current code does not enforce this
1382             $sunit = $editor->retrieve_serial_unit($unit_id);
1383             if ($stream_ids_by_unit_id{$unit_id}) {
1384                 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_ids_by_unit_id{$unit_id}}}, { "join" => {"sstr" => {}}, 'limit' => 1 }]);
1385             } else {
1386                 $sdist = $editor->search_serial_distribution([
1387                     {'+sunit' => {'id' => $unit_id}},
1388                     { 'join' =>
1389                         {'sstr' =>
1390                             { 'join' =>
1391                                 { 'sitem' =>
1392                                     { 'join' => 'sunit' }
1393                                 } 
1394                             } 
1395                         },
1396                       'limit' => 1
1397                     }]);
1398             }
1399             $sdist = $sdist->[0];
1400         }
1401
1402         my $evt = _prepare_unit($editor, $sunit, $sdist, $issuances, $call_number_string, $record_id);
1403         if ($U->event_code($evt)) {
1404             $editor->rollback;
1405             return $evt;
1406         }
1407
1408         $evt = _update_sunit($editor, undef, $sunit);
1409         if ($U->event_code($evt)) {
1410             $editor->rollback;
1411             return $evt;
1412         }
1413     }
1414
1415     if ($mode ne 'bind') { # the summary holdings do not change when binding
1416         # deal with stream level summaries
1417         # summaries will be built from the "primary" stream only, that is, the stream with the lowest ID per distribution
1418         # (TODO: consider direct designation)
1419         my %primary_streams_by_sdist;
1420         my %streams_by_sdist;
1421
1422         # see if we have primary streams, and if so, associate them with their distributions
1423         foreach my $stream_id (keys %found_stream_ids) {
1424             my $sdist;
1425             if (exists $sdist_by_stream_id{$stream_id}) {
1426                 $sdist = $sdist_by_stream_id{$stream_id};
1427             } else {
1428                 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
1429                 $sdist = $sdist->[0];
1430                 $sdist_by_stream_id{$stream_id} = $sdist;
1431             }
1432             my $streams;
1433             if (!exists($streams_by_sdist{$sdist->id})) {
1434                 $streams = $editor->search_serial_stream([{"distribution" => $sdist->id}, {"order_by" => {"sstr" => "id"}}]);
1435                 $streams_by_sdist{$sdist->id} = $streams;
1436             } else {
1437                 $streams = $streams_by_sdist{$sdist->id};
1438             }
1439             $primary_streams_by_sdist{$sdist->id} = $streams->[0] if ($stream_id == $streams->[0]->id);
1440         }
1441
1442         # retrieve and update summaries for each affected primary stream's distribution
1443         foreach my $sdist_id (keys %primary_streams_by_sdist) {
1444             my $stream = $primary_streams_by_sdist{$sdist_id};
1445             my $stream_id = $stream->id;
1446             # get all the needed issuances for stream
1447             # FIXME: search in Bindery/Bound/Not Published? as well as Received
1448             foreach my $type (keys %{$found_types{$stream_id}}) {
1449                 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"stream" => $stream_id, "status" => "Received"}, "+scap" => {"type" => $type}}, {"join" => {"sitem" => {}, "scap" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1450                 #TODO: evt on search failure
1451                 my $evt = _prepare_summaries($editor, $issuances, $sdist_by_stream_id{$stream_id}, $type);
1452                 if ($U->event_code($evt)) {
1453                     $editor->rollback;
1454                     return $evt;
1455                 }
1456             }
1457         }
1458     }
1459
1460     $editor->commit;
1461     return {'num_items' => scalar @$items, 'new_unit_id' => $new_unit_id};
1462 }
1463
1464 sub _find_or_create_call_number {
1465     my ($e, $lib, $cn_string, $record) = @_;
1466
1467     # FIXME: should suffix and prefix come into play here?
1468     my $existing = $e->search_asset_call_number({
1469         "owning_lib" => $lib,
1470         "label" => $cn_string,
1471         "record" => $record,
1472         "deleted" => "f"
1473     }) or return $e->die_event;
1474
1475     if (@$existing) {
1476         return $existing->[0]->id;
1477     } else {
1478         return $e->die_event unless
1479             $e->allowed("CREATE_VOLUME", $lib);
1480
1481         my $acn = new Fieldmapper::asset::call_number;
1482
1483         $acn->creator($e->requestor->id);
1484         $acn->editor($e->requestor->id);
1485         $acn->record($record);
1486         $acn->label($cn_string);
1487         $acn->owning_lib($lib);
1488
1489         $e->create_asset_call_number($acn) or return $e->die_event;
1490         return $e->data->id;
1491     }
1492 }
1493
1494 sub _issuances_received {
1495     # XXX TODO: Add some caching or something. This is getting called
1496     # more often than it has to be.
1497     my ($e, $sitem) = @_;
1498
1499     my $results = $e->json_query({
1500         "select" => {"sitem" => ["issuance"]},
1501         "from" => {"sitem" => {"sstr" => {}, "siss" => {}}},
1502         "where" => {
1503             "+sstr" => {"distribution" => $sitem->stream->distribution->id},
1504             "+siss" => {"holding_type" => $sitem->issuance->holding_type},
1505             "+sitem" => {"date_received" => {"!=" => undef}}
1506         },
1507         "order_by" => {
1508             "siss" => {"date_published" => {"direction" => "asc"}}
1509         }
1510     }) or return $e->die_event;
1511
1512     my %seen;
1513     my $issuances = [];
1514     for my $iss_id (map { $_->{"issuance"} } @$results) {
1515         next if $seen{$iss_id};
1516         $seen{$iss_id} = 1;
1517         push(@$issuances, $e->retrieve_serial_issuance($iss_id));
1518     }
1519     return $issuances;
1520 }
1521
1522 # _prepare_unit populates the detailed_contents, summary_contents, and
1523 # sort_key fields for a given unit based on a given set of issuances
1524 # Also finds/creates call number as needed
1525 sub _prepare_unit {
1526     my ($e, $sunit, $sdist, $issuances, $call_number_string, $record_id) = @_;
1527
1528     # Handle call number first if we have one
1529     if ($call_number_string) {
1530         my $org_unit_id = ref $sdist->holding_lib ? $sdist->holding_lib->id : $sdist->holding_lib;
1531         my $real_cn = _find_or_create_call_number(
1532             $e, $org_unit_id,
1533             $call_number_string, $record_id
1534         );
1535
1536         if ($U->event_code($real_cn)) {
1537             return $real_cn;
1538         } else {
1539             $sunit->call_number($real_cn);
1540         }
1541     }
1542
1543     my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances);
1544     return $mfhd if $U->event_code($mfhd);
1545
1546     # special case for single formatted_part (may have summarized version)
1547     if (@$formatted_parts == 1) {
1548         #TODO: MFHD.pm should have a 'format_summary' method for this
1549     }
1550
1551     $sunit->detailed_contents(
1552         join(
1553             " ",
1554             $sdist->unit_label_prefix,
1555             join(", ", @$formatted_parts),
1556             $sdist->unit_label_suffix
1557         )
1558     );
1559
1560     # TODO: change this when real summary contents are available
1561     $sunit->summary_contents($sunit->detailed_contents);
1562
1563     # Create sort_key by left padding numbers to 6 digits.
1564     (my $sort_key = $sunit->detailed_contents) =~
1565         s/(\d+)/sprintf '%06d', $1/eg;
1566     $sunit->sort_key($sort_key);
1567 }
1568
1569 # _prepare_summaries populates the generated_coverage field for a given summary 
1570 # type ('basic', 'index', 'supplement') for a given distribution.
1571 # It also creates the summary if it doesn't yet exist.
1572 sub _prepare_summaries {
1573     my ($e, $issuances, $sdist, $type) = @_;
1574
1575     my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances, $sdist, $type);
1576     return $mfhd if $U->event_code($mfhd);
1577
1578     my $search_method = "search_serial_${type}_summary";
1579     my $summary = $e->$search_method([{"distribution" => $sdist->id}]);
1580
1581     my $cu_method = "update";
1582
1583     if (@$summary) {
1584         $summary = $summary->[0];
1585     } else {
1586         my $class = "Fieldmapper::serial::${type}_summary";
1587         $summary = $class->new;
1588         $summary->distribution($sdist->id);
1589         $cu_method = "create";
1590     }
1591
1592     if (@$formatted_parts) {
1593         $summary->generated_coverage(OpenSRF::Utils::JSON->perl2JSON($formatted_parts));
1594     } else {
1595         # we had no issuances or MFHD data for this type, so clear any
1596         # generated data which may have existed before
1597         $summary->generated_coverage('');
1598     }
1599     my $method = "${cu_method}_serial_${type}_summary";
1600     return $e->die_event unless $e->$method($summary);
1601 }
1602
1603
1604 __PACKAGE__->register_method(
1605     method    => 'regen_summaries',
1606     api_name  => 'open-ils.serial.regenerate_summaries',
1607     api_level => 1,
1608     argc      => 1,
1609     signature => {
1610         'desc'   => 'Regenerate all the generated_coverage fields for given distributions or subscriptions (depending on params given). Params are expected to be hash members.',
1611         'params' => [ {
1612                  name => 'sdist_ids',
1613                  desc => 'IDs of the distribution whose coverage you want to regenerate',
1614                  type => 'array'
1615             },
1616             {
1617                  name => 'ssub_ids',
1618                  desc => 'IDs of the subscriptions whose coverage you want to regenerate',
1619                  type => 'array'
1620             }
1621         ],
1622         'return' => {
1623             desc => 'Returns undef if successful, event if failed',
1624             type => 'mixed'
1625         }
1626 #TODO: best practices for return values
1627     }
1628 );
1629
1630 sub regen_summaries {
1631     my ($self, $conn, $auth, $opts) = @_;
1632
1633     my $e = new_editor("authtoken" => $auth, "xact" => 1);
1634     return $e->die_event unless $e->checkauth;
1635     # Perm checks not necessary since generated_coverage is akin to
1636     # caching of data, not actual editing.  XXX This might need more
1637     # consideration.
1638     #return $editor->die_event unless $editor->allowed("RECEIVE_SERIAL");
1639
1640     my $evt = _regenerate_summaries($e, $opts);
1641     if ($U->event_code($evt)) {
1642         $e->rollback;
1643         return $evt;
1644     }
1645
1646     $e->commit;
1647
1648     return undef;
1649 }
1650
1651 sub _regenerate_summaries {
1652     my ($e, $opts) = @_;
1653
1654     $logger->debug('_regenerate_summaries with opts: ' . OpenSRF::Utils::JSON->perl2JSON($opts));
1655     my @sdist_ids;
1656     if ($opts->{'ssub_ids'}) {
1657         foreach my $ssub_id (@{$opts->{'ssub_ids'}}) {
1658             my $sdist_ids_temp = $e->search_serial_distribution(
1659                 { 'subscription' => $ssub_id },
1660                 { 'idlist' => 1 }
1661             );
1662             push(@sdist_ids, @$sdist_ids_temp);
1663         }
1664     } elsif ($opts->{'sdist_ids'}) {
1665         @sdist_ids = @$opts->{'sdist_ids'};
1666     }
1667
1668     foreach my $sdist_id (@sdist_ids) {
1669         # get distribution
1670         my $sdist = $e->retrieve_serial_distribution($sdist_id)
1671             or return $e->die_event;
1672
1673 # See large comment below
1674 #        my $has_merged_mfhd;
1675         foreach my $type (@MFHD_NAMES) {
1676             # get issuances
1677             my $issuances = $e->search_serial_issuance([
1678                 {
1679                     "+sdist" => {"id" => $sdist_id},
1680                     "+sitem" => {"status" => "Received"},
1681                     "+scap" => {"type" => $type}
1682                 },
1683                 {
1684                     "join" => {
1685                         "sitem" => {},
1686                         "scap" => {},
1687                         "ssub" => {
1688                             "join" => {"sdist" =>{}}
1689                         }
1690                     },
1691                     "order_by" => {
1692                         "siss" => "date_published"
1693                     }
1694                 }
1695             ]) or return $e->die_event;
1696
1697 # This level of nuance doesn't appear to be necessary.
1698 # At the moment, we pass down an empty issuance list,
1699 # and the inner methods will "do the right thing" and
1700 # pull in the MFHD if called for, but in some cases not
1701 # ultimately generate any coverage.  The code below is
1702 # broken in cases where we delete the last issuance, since
1703 # the now empty summary never gets updated.
1704 #
1705 # Leaving this code for now (2014/04) in case pushing
1706 # the logic down ends up being too slow or complicates
1707 # the inner methods beyond their scope.
1708 #
1709 #            if (!@$issuances and !$has_merged_mfhd) {
1710 #                if (!defined($has_merged_mfhd)) {
1711 #                    # even without issuances, we can generate a summary
1712 #                    # from a merged MFHD record, so look for one
1713 #                    my $mfhd_ids = $e->search_serial_record_entry(
1714 #                        {
1715 #                            '+sdist' => {
1716 #                                'id' => $sdist_id,
1717 #                                'summary_method' => 'merge_with_sre'
1718 #                            }
1719 #                        },
1720 #                        {
1721 #                            'join' => { 'sdist' => {} },
1722 #                            'idlist' => 1
1723 #                        }
1724 #                    );
1725 #                    if ($mfhd_ids and @$mfhd_ids) {
1726 #                        $has_merged_mfhd = 1;
1727 #                    } else {
1728 #                        next;
1729 #                    }
1730 #                } else {
1731 #                    next; # abort to prevent empty summary creation (i.e. '[]')
1732 #                }
1733 #            }
1734             my $evt = _prepare_summaries($e, $issuances, $sdist, $type);
1735             if ($U->event_code($evt)) {
1736                 $e->rollback;
1737                 return $evt;
1738             }
1739         }
1740     }
1741
1742     return undef;
1743 }
1744
1745 sub _unit_by_iss_and_str {
1746     my ($e, $issuance, $stream) = @_;
1747
1748     my $unit = $e->json_query({
1749         "select" => {"sunit" => ["id"]},
1750         "from" => {"sitem" => {"sunit" => {}}},
1751         "where" => {
1752             "+sitem" => {
1753                 "issuance" => $issuance->id,
1754                 "stream" => $stream->id
1755             }
1756         }
1757     }) or return $e->die_event;
1758     return 0 if not @$unit;
1759
1760     $e->retrieve_serial_unit($unit->[0]->{"id"}) or $e->die_event;
1761 }
1762
1763 sub move_previous_unit {
1764     my ($e, $prev_iss, $curr_item, $new_loc) = @_;
1765
1766     my $prev_unit = _unit_by_iss_and_str($e,$prev_iss,$curr_item->stream);
1767     return $prev_unit if defined $U->event_code($prev_unit);
1768     return 0 if not $prev_unit;
1769
1770     if ($prev_unit->location != $new_loc) {
1771         $prev_unit->location($new_loc);
1772         $e->update_serial_unit($prev_unit) or return $e->die_event;
1773     }
1774     0;
1775 }
1776
1777 # _previous_issuance() assumes $existing is an ordered array
1778 sub _previous_issuance {
1779     my ($existing, $issuance) = @_;
1780
1781     my $last = $existing->[-1];
1782     return undef unless $last;
1783     return ($last->id == $issuance->id ? $existing->[-2] : $last);
1784 }
1785
1786 __PACKAGE__->register_method(
1787     "method" => "receive_items_one_unit_per",
1788     "api_name" => "open-ils.serial.receive_items.one_unit_per",
1789     "stream" => 1,
1790     "api_level" => 1,
1791     "argc" => 3,
1792     "signature" => {
1793         "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",
1794         "params" => [
1795             {
1796                  "name" => "auth",
1797                  "desc" => "authtoken",
1798                  "type" => "string"
1799             },
1800             {
1801                  "name" => "items",
1802                  "desc" => "array of serial items, possibly fleshed with units and definitely fleshed with stream->distribution",
1803                  "type" => "array"
1804             },
1805             {
1806                 "name" => "record",
1807                 "desc" => "id of bib record these items are associated with
1808                     (XXX could/should be derived from items)",
1809                 "type" => "number"
1810             }
1811         ],
1812         "return" => {
1813             "desc" => "The item ID for each item successfully received",
1814             "type" => "int"
1815         }
1816     }
1817 );
1818
1819 sub receive_items_one_unit_per {
1820     # XXX This function may be temporary, as it does some of what
1821     # unitize_items() does, just in a different way.
1822     my ($self, $client, $auth, $items, $record) = @_;
1823
1824     my $e = new_editor("authtoken" => $auth, "xact" => 1);
1825     return $e->die_event unless $e->checkauth;
1826     return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
1827
1828     my $prev_loc_setting_map = {};
1829     my $user_id = $e->requestor->id;
1830
1831     # Get a list of all the non-virtual field names in a serial::unit for
1832     # merging given unit objects with template-built units later.
1833     # XXX move this somewhere global so it isn't re-run all the time
1834     my $all_unit_fields =
1835         $Fieldmapper::fieldmap->{"Fieldmapper::serial::unit"}->{"fields"};
1836     my @real_unit_fields = grep {
1837         not $all_unit_fields->{$_}->{"virtual"}
1838     } keys %$all_unit_fields;
1839
1840     foreach my $item (@$items) {
1841         # Note that we expect a certain fleshing on the items we're getting.
1842         my $sdist = $item->stream->distribution;
1843
1844         # Fetch a list of issuances with received copies already existing
1845         # on this distribution (and with the same holding type on the
1846         # issuance).  This will be used in up to two places: once when building
1847         # a summary, once when changing the copy location of the previous
1848         # issuance's copy.
1849         my $issuances_received = _issuances_received($e, $item);
1850         if ($U->event_code($issuances_received)) {
1851             $e->rollback;
1852             return $issuances_received;
1853         }
1854
1855         # Find out if we need to to deal with previous copy location changing.
1856         my $ou = $sdist->holding_lib->id;
1857         unless (exists $prev_loc_setting_map->{$ou}) {
1858             $prev_loc_setting_map->{$ou} = $U->ou_ancestor_setting_value(
1859                 $ou, "serial.prev_issuance_copy_location", $e
1860             );
1861         }
1862
1863         # If there is a previous copy location setting, we need the previous
1864         # issuance, from which we can in turn look up the item attached to the
1865         # same stream we're on now.
1866         if ($prev_loc_setting_map->{$ou}) {
1867             if (my $prev_iss =
1868                 _previous_issuance($issuances_received, $item->issuance)) {
1869
1870                 # Now we can change the copy location of the previous unit,
1871                 # if needed.
1872                 return $e->event if defined $U->event_code(
1873                     move_previous_unit(
1874                         $e, $prev_iss, $item, $prev_loc_setting_map->{$ou}
1875                     )
1876                 );
1877             }
1878         }
1879
1880         # Create unit if given by user
1881         if (ref $item->unit) {
1882             # detach from the item, as we need to create separately
1883             my $user_unit = $item->unit;
1884
1885             # get a unit based on associated template
1886             my $template_unit = _build_unit($e, $sdist, "receive");
1887             if ($U->event_code($template_unit)) {
1888                 $e->rollback;
1889                 $template_unit->{"note"} = "Item ID: " . $item->id;
1890                 return $template_unit;
1891             }
1892
1893             # merge built unit with provided unit from user
1894             foreach (@real_unit_fields) {
1895                 unless ($user_unit->$_) {
1896                     $user_unit->$_($template_unit->$_);
1897                 }
1898             }
1899
1900             # Treat call number specially: the provided value from the
1901             # user will really be a string.
1902             my $call_number_string;
1903             if ($user_unit->call_number) {
1904                 $call_number_string = $user_unit->call_number;
1905                 # clear call number for now (replaced in _prepare_unit)
1906                 $user_unit->clear_call_number;
1907             }
1908
1909             my $evt = _prepare_unit(
1910                 $e, $user_unit, $sdist, [$item->issuance],
1911                 $call_number_string, $record
1912             );
1913             if ($U->event_code($evt)) {
1914                 $e->rollback;
1915                 return $evt;
1916             }
1917
1918             # create/update summary objects related to this distribution
1919             # Make sure @$issuances_received contains current item's issuance
1920             unless (grep { $_->id == $item->issuance->id } @$issuances_received) {
1921                 push @$issuances_received, $item->issuance;
1922             }
1923             $evt = _prepare_summaries($e, $issuances_received, $item->stream->distribution, $item->issuance->holding_type);
1924             if ($U->event_code($evt)) {
1925                 $e->rollback;
1926                 return $evt;
1927             }
1928
1929             # set the incontrovertibles on the unit
1930             $user_unit->edit_date("now");
1931             $user_unit->create_date("now");
1932             $user_unit->editor($user_id);
1933             $user_unit->creator($user_id);
1934
1935             $evt = _create_sunit($e, $user_unit);
1936             return $evt if $evt;
1937
1938             # save reference to new unit
1939             $item->unit($e->data->id);
1940         }
1941
1942         # Create notes if given by user
1943         if (ref($item->notes) and @{$item->notes}) {
1944             foreach my $note (@{$item->notes}) {
1945                 $note->creator($user_id);
1946                 $note->create_date("now");
1947
1948                 return $e->die_event unless $e->create_serial_item_note($note);
1949             }
1950
1951             $item->clear_notes; # They're saved; we no longer want them here.
1952         }
1953
1954         # Set the incontrovertibles on the item
1955         $item->status("Received");
1956         $item->date_received("now");
1957         $item->edit_date("now");
1958         $item->editor($user_id);
1959
1960         return $e->die_event unless $e->update_serial_item($item);
1961
1962         # send client a response
1963         $client->respond($item->id);
1964     }
1965
1966     $e->commit or return $e->die_event;
1967     undef;
1968 }
1969
1970 sub _build_unit {
1971     my $editor = shift;
1972     my $sdist = shift;
1973     my $mode = shift;
1974     #my $skip_call_number = shift;
1975
1976     my $attr = $mode . '_unit_template';
1977     my $template = $editor->retrieve_asset_copy_template($sdist->$attr) or
1978         return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_COPY_TEMPLATE");
1979
1980     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 );
1981
1982     my $unit = new Fieldmapper::serial::unit;
1983     foreach my $part (@parts) {
1984         my $value = $template->$part;
1985         next if !defined($value);
1986         $unit->$part($value);
1987     }
1988
1989     # ignore circ_lib in template, set to distribution holding_lib
1990     $unit->circ_lib($sdist->holding_lib);
1991     $unit->creator($editor->requestor->id);
1992     $unit->editor($editor->requestor->id);
1993
1994 # XXX: this feature has been pushed back until after 2.0 at least
1995 #    unless ($skip_call_number) {
1996 #        $attr = $mode . '_call_number';
1997 #        my $cn = $sdist->$attr or
1998 #            return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_CALL_NUMBER");
1999 #
2000 #        $unit->call_number($cn);
2001 #    }
2002     $unit->call_number('-1'); # default to the dummy call number
2003     $unit->barcode('@@PLACEHOLDER'); # generic unit will start with a generated placeholder barcode
2004     $unit->sort_key('');
2005     $unit->summary_contents('');
2006     $unit->detailed_contents('');
2007
2008     return $unit;
2009 }
2010
2011 sub _summarize_contents {
2012     my $editor = shift;
2013     my $issuances = shift;
2014     my $sdist = shift;
2015     my $type = shift;
2016
2017     # create or lookup MFHD record
2018     my $mfhd;
2019     if ($sdist and defined($sdist->record_entry) and $sdist->summary_method eq 'merge_with_sre') {
2020         my $sre;
2021         if (ref $sdist->record_entry) {
2022             $sre = $sdist->record_entry; 
2023         } else {
2024             $sre = $editor->retrieve_serial_record_entry($sdist->record_entry);
2025         }
2026         $mfhd = MFHD->new(MARC::Record->new_from_xml($sre->marc)); 
2027     } else {
2028         $logger->info($sdist);
2029         $mfhd = MFHD->new(MARC::Record->new());
2030     }
2031
2032     my %scaps;
2033     my %scap_fields;
2034     my $seqno = 1;
2035     # We keep track of these separately to avoid link_id contamination,
2036     # e.g. a basic issuance, followed by a merging supplement, followed by
2037     # another basic.  If we could be sure that they were not mixed, one
2038     # value could suffice.
2039     my %link_ids = ('basic' => 10000, 'index' => 10000, 'supplement' => 10000);
2040     my %first_scap = ('basic' => 1, 'index' => 1, 'supplement' => 1);
2041     foreach my $issuance (@$issuances) {
2042         my $scap_id = $issuance->caption_and_pattern;
2043         next if (!$scap_id); # skip issuances with no caption/pattern
2044
2045         my $scap;
2046         my $scap_field;
2047         # if this is the first appearance of this scap, retrieve it and add it to the temporary record
2048         if (!exists $scaps{$issuance->caption_and_pattern}) {
2049             $scaps{$scap_id} = $editor->retrieve_serial_caption_and_pattern($scap_id);
2050             $scap = $scaps{$scap_id};
2051             $scap_field = _revive_caption($scap);
2052             my $did_merge = 0;
2053             if ($first_scap{$scap->type}) { # special merge processing
2054                 $first_scap{$MFHD_TAGS_BY_NAME{$scap->type}} = 0;
2055                 if ($sdist and $sdist->summary_method eq 'merge_with_sre') {
2056                     # MFHD Caption objects do not yet have a built-in compare (TODO), so let's do a basic one
2057                     my @field_85xs = $mfhd->field($MFHD_TAGS_BY_NAME{$scap->type});
2058                     if (@field_85xs) {
2059                         my $last_caption_field = $field_85xs[-1];
2060                         my $last_link_id = $last_caption_field->subfield('8');
2061                         # set the link id to match, temporarily, for comparison
2062                         $last_caption_field->update('8' => $scap_field->subfield('8'));
2063                         my $last_caption_json = OpenSRF::Utils::JSON->perl2JSON([$last_caption_field->indicator(1), $last_caption_field->indicator(2), $last_caption_field->subfields_list]);
2064                         if ($last_caption_json eq $scap->pattern_code) { # merge is possible, they match
2065                             # restore link id
2066                             $link_ids{$scap->type} = $last_link_id;
2067                             # set scap_field to last field
2068                             $scap_field = $last_caption_field;
2069                             $did_merge = 1;
2070                         }
2071                     }
2072                 }
2073             }
2074             $scap_fields{$scap_id} = $scap_field;
2075             $scap_field->update('8' => $link_ids{$scap->type});
2076             # TODO: make MFHD/Caption smarter about this
2077             $scap_field->{_mfhdc_LINK_ID} = $link_ids{$scap->type};
2078             $mfhd->append_fields($scap_field) if !$did_merge;
2079             $link_ids{$scap->type}++;
2080         } else {
2081             $scap_field = $scap_fields{$scap_id};
2082         }
2083
2084         $mfhd->append_fields(_revive_holding($issuance->holding_code, $scap_field, $seqno));
2085         $seqno++;
2086     }
2087
2088     my @formatted_parts;
2089     my @scap_fields_ordered;
2090     if ($type) {
2091         @scap_fields_ordered = $mfhd->field($MFHD_TAGS_BY_NAME{$type});
2092     } else {
2093         # if they didn't give a type, send back whatever holdings we have.
2094         # this is really only sensible right now for summarizing one type,
2095         # and is used by the unitize code for this purpose
2096         #
2097         # TODO: possible future support for binding (unitizing) of multiple
2098         # types into a sensible summary string
2099         @scap_fields_ordered = $mfhd->field('85[345]');
2100     }
2101
2102     foreach my $scap_field (@scap_fields_ordered) { #TODO: use generic MFHD "summarize" method, once available
2103         my @updated_holdings;
2104         eval {
2105             @updated_holdings = $mfhd->get_combined_holdings($scap_field);
2106         };
2107         if ($@) {
2108             my $msg = "get_combined_holdings(): $@ ; using sdist ID #" .
2109                 ($sdist ? $sdist->id : "<NONE>") . " and " .
2110                 scalar(@$issuances) . " issuances, of which one has ID #" .
2111                 $issuances->[0]->id;
2112
2113             $msg =~ s/\n//gm;
2114             $logger->error($msg);
2115             return new OpenILS::Event("BAD_PARAMS", note => $msg);
2116         }
2117
2118         push @formatted_parts, map { $_->format } @updated_holdings;
2119     }
2120
2121     return ($mfhd, \@formatted_parts);
2122 }
2123
2124 ##########################################################################
2125 # note methods
2126 #
2127 __PACKAGE__->register_method(
2128     method      => 'fetch_notes',
2129     api_name        => 'open-ils.serial.item_note.retrieve.all',
2130     signature   => q/
2131         Returns an array of copy note objects.  
2132         @param args A named hash of parameters including:
2133             authtoken   : Required if viewing non-public notes
2134             item_id      : The id of the item whose notes we want to retrieve
2135             pub         : True if all the caller wants are public notes
2136         @return An array of note objects
2137     /
2138 );
2139
2140 __PACKAGE__->register_method(
2141     method      => 'fetch_notes',
2142     api_name        => 'open-ils.serial.subscription_note.retrieve.all',
2143     signature   => q/
2144         Returns an array of copy note objects.  
2145         @param args A named hash of parameters including:
2146             authtoken       : Required if viewing non-public notes
2147             subscription_id : The id of the item whose notes we want to retrieve
2148             pub             : True if all the caller wants are public notes
2149         @return An array of note objects
2150     /
2151 );
2152
2153 __PACKAGE__->register_method(
2154     method      => 'fetch_notes',
2155     api_name        => 'open-ils.serial.distribution_note.retrieve.all',
2156     signature   => q/
2157         Returns an array of copy note objects.  
2158         @param args A named hash of parameters including:
2159             authtoken       : Required if viewing non-public notes
2160             distribution_id : The id of the item whose notes we want to retrieve
2161             pub             : True if all the caller wants are public notes
2162         @return An array of note objects
2163     /
2164 );
2165
2166 # TODO: revisit this method to consider replacing cstore direct calls
2167 sub fetch_notes {
2168     my( $self, $connection, $args ) = @_;
2169     
2170     $self->api_name =~ /serial\.(\w*)_note/;
2171     my $type = $1;
2172
2173     my $id = $$args{object_id};
2174     my $authtoken = $$args{authtoken};
2175     my $order_by = $$args{order_by} || 'create_date';
2176     my( $r, $evt);
2177
2178     if( $$args{pub} ) {
2179         return $U->cstorereq(
2180             'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic',
2181             { $type => $id, pub => 't' }, {'order_by' => {$FM_NAME_TO_ID{$type}.'n' => $order_by}} );
2182     } else {
2183         # FIXME: restore perm check
2184         # ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
2185         # return $evt if $evt;
2186         return $U->cstorereq(
2187             'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic', {$type => $id}, {'order_by' => {$FM_NAME_TO_ID{$type}.'n' => $order_by}} );
2188     }
2189
2190     return undef;
2191 }
2192
2193 __PACKAGE__->register_method(
2194     method      => 'update_note',
2195     api_name        => 'open-ils.serial.item_note.update',
2196     signature   => q/
2197         Updates or creates an item note
2198         @param authtoken The login session key
2199         @param note The note object to update or create
2200         @return The id of the note object
2201     /
2202 );
2203
2204 __PACKAGE__->register_method(
2205     method      => 'update_note',
2206     api_name        => 'open-ils.serial.subscription_note.update',
2207     signature   => q/
2208         Updates or creates a subscription note
2209         @param authtoken The login session key
2210         @param note The note object to update or create
2211         @return The id of the note object
2212     /
2213 );
2214
2215 __PACKAGE__->register_method(
2216     method      => 'update_note',
2217     api_name        => 'open-ils.serial.distribution_note.update',
2218     signature   => q/
2219         Updates or creates a distribution note
2220         @param authtoken The login session key
2221         @param note The note object to update or create
2222         @return The id of the note object
2223     /
2224 );
2225
2226 sub update_note {
2227     my( $self, $connection, $authtoken, $note ) = @_;
2228
2229     $self->api_name =~ /serial\.(\w*)_note/;
2230     my $type = $1;
2231
2232     my $e = new_editor(xact=>1, authtoken=>$authtoken);
2233     return $e->event unless $e->checkauth;
2234
2235     if ($type eq 'item') {
2236         my $sitem = $e->retrieve_serial_item([
2237             $note->item, {
2238                 "flesh" => 2, "flesh_fields" => {
2239                     "sitem" => ["stream"], "sstr" => ["distribution"]
2240                 }
2241             }
2242         ]) or return $e->die_event;
2243
2244         return $e->die_event unless $e->allowed(
2245             "ADMIN_SERIAL_ITEM", $sitem->stream->distribution->holding_lib
2246         );
2247     } elsif ($type eq 'distribution') {
2248         my $sdist = $e->retrieve_serial_distribution($note->distribution)
2249             or return $e->die_event;
2250
2251         return $e->die_event unless
2252             $e->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2253     } else { # subscription
2254         my $sub = $e->retrieve_serial_subscription($note->subscription)
2255             or return $e->die_event;
2256
2257         return $e->die_event unless
2258             $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
2259     }
2260
2261     $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
2262     my $method;
2263     if ($note->isnew) {
2264         $note->create_date('now');
2265         $note->creator($e->requestor->id);
2266         $note->clear_id;
2267         $method = "create_serial_${type}_note";
2268     } else {
2269         $method = "update_serial_${type}_note";
2270     }
2271     $e->$method($note) or return $e->event;
2272     $e->commit;
2273     return $note->id;
2274 }
2275
2276 __PACKAGE__->register_method(
2277     method      => 'delete_note',
2278     api_name        =>  'open-ils.serial.item_note.delete',
2279     signature   => q/
2280         Deletes an existing item note
2281         @param authtoken The login session key
2282         @param noteid The id of the note to delete
2283         @return 1 on success - Event otherwise.
2284         /
2285 );
2286
2287 __PACKAGE__->register_method(
2288     method      => 'delete_note',
2289     api_name        =>  'open-ils.serial.subscription_note.delete',
2290     signature   => q/
2291         Deletes an existing subscription note
2292         @param authtoken The login session key
2293         @param noteid The id of the note to delete
2294         @return 1 on success - Event otherwise.
2295         /
2296 );
2297
2298 __PACKAGE__->register_method(
2299     method      => 'delete_note',
2300     api_name        =>  'open-ils.serial.distribution_note.delete',
2301     signature   => q/
2302         Deletes an existing distribution note
2303         @param authtoken The login session key
2304         @param noteid The id of the note to delete
2305         @return 1 on success - Event otherwise.
2306         /
2307 );
2308
2309 sub delete_note {
2310     my( $self, $conn, $authtoken, $noteid ) = @_;
2311
2312     $self->api_name =~ /serial\.(\w*)_note/;
2313     my $type = $1;
2314
2315     my $e = new_editor(xact=>1, authtoken=>$authtoken);
2316     return $e->die_event unless $e->checkauth;
2317
2318     my $method = "retrieve_serial_${type}_note";
2319     my $note = $e->$method([
2320         $noteid,
2321     ]) or return $e->die_event;
2322
2323     if ($type eq 'item') {
2324         my $sitem = $e->retrieve_serial_item([
2325             $note->item, {
2326                 "flesh" => 2, "flesh_fields" => {
2327                     "sitem" => ["stream"], "sstr" => ["distribution"]
2328                 }
2329             }
2330         ]) or return $e->die_event;
2331
2332         return $e->die_event unless $e->allowed(
2333             "ADMIN_SERIAL_ITEM", $sitem->stream->distribution->holding_lib
2334         );
2335     } elsif ($type eq 'distribution') {
2336         my $sdist = $e->retrieve_serial_distribution($note->distribution)
2337             or return $e->die_event;
2338
2339         return $e->die_event unless
2340             $e->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2341     } else { # subscription
2342         my $sub = $e->retrieve_serial_subscription($note->subscription)
2343             or return $e->die_event;
2344
2345         return $e->die_event unless
2346             $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
2347     }
2348
2349     $method = "delete_serial_${type}_note";
2350     $e->$method($note) or return $e->die_event;
2351     $e->commit;
2352     return 1;
2353 }
2354
2355
2356 ##########################################################################
2357 # subscription methods
2358 #
2359
2360 __PACKAGE__->register_method(
2361     method      => 'safe_delete',
2362     api_name        =>  'open-ils.serial.subscription.safe_delete',
2363     signature   => q/
2364         Deletes an existing subscription and related records
2365         (distributions, streams, etc.), but only if there are no serial
2366         items with a status other than Expected, and no non-deleted 
2367         serial units.
2368         @param authtoken The login session key
2369         @param subid The id of the subscription to delete
2370         @return 1 on success - Event otherwise.
2371         /
2372 );
2373
2374 __PACKAGE__->register_method(
2375     method      => 'safe_delete',
2376     api_name        =>  'open-ils.serial.distribution.safe_delete',
2377     signature   => q/
2378         Deletes an existing distribution and related records
2379         (streams, etc.), but only if there are no attached serial items
2380         with a status other than Expected, and no non-deleted serial
2381         units.
2382         @param authtoken The login session key
2383         @param subid The id of the distribution to delete
2384         @return 1 on success - Event otherwise.
2385         /
2386 );
2387
2388 __PACKAGE__->register_method(
2389     method      => 'safe_delete',
2390     api_name        =>  'open-ils.serial.stream.safe_delete',
2391     signature   => q/
2392         Deletes an existing stream and associated routing list, but only
2393         if there are no attached serial items with a status other than
2394         Expected, and no non-deleted serial units.
2395         items and no issuances.
2396         @param authtoken The login session key
2397         @param strid The id of the stream to delete
2398         @return 1 on success - Event otherwise.
2399         /
2400 );
2401
2402 __PACKAGE__->register_method(
2403     method      => 'safe_delete',
2404     api_name        =>  'open-ils.serial.subscription.safe_delete.dry_run',
2405 );
2406 __PACKAGE__->register_method(
2407     method      => 'safe_delete',
2408     api_name        =>  'open-ils.serial.distribution.safe_delete.dry_run',
2409 );
2410 __PACKAGE__->register_method(
2411     method      => 'safe_delete',
2412     api_name        =>  'open-ils.serial.stream.safe_delete.dry_run',
2413 );
2414
2415 sub safe_delete {
2416     my( $self, $conn, $authtoken, $id ) = @_;
2417
2418     $self->api_name =~ /serial\.(\w*)\.safe_delete/;
2419     my $type = $1;
2420
2421     my $e = new_editor(xact=>1, authtoken=>$authtoken);
2422     return $e->die_event unless $e->checkauth;
2423
2424     my $obj;
2425
2426     if ($type eq 'stream') {
2427         my $sstr = $e->retrieve_serial_stream([
2428             $id, {
2429                 "flesh" => 2, "flesh_fields" => {
2430                     "sstr" => ["items","distribution"],
2431                     "sitem" => ["unit"]
2432                 }
2433             }
2434         ]) or return $e->die_event;
2435
2436         return $e->die_event unless $e->allowed(
2437             "ADMIN_SERIAL_STREAM", $sstr->distribution->holding_lib
2438         );
2439
2440         foreach my $sitem (@{$sstr->items}) {
2441             if ($sitem->status ne 'Expected') {
2442                 return OpenILS::Event->new('SERIAL_STREAM_NOT_EMPTY', payload=>$id);
2443             }
2444             if ($sitem->unit && !$U->is_true($sitem->unit->deleted)) {
2445                 return OpenILS::Event->new('SERIAL_STREAM_NOT_EMPTY', payload=>$id);
2446             }
2447         }
2448
2449         $obj = $sstr;
2450
2451     } elsif ($type eq 'distribution') {
2452         my $sdist = $e->retrieve_serial_distribution([
2453             $id, {
2454                 "flesh" => 3, "flesh_fields" => {
2455                     "sstr" => ["items"],
2456                     "sdist" => ["streams"],
2457                     "sitem" => ["unit"]
2458                 }
2459             }
2460         ]) or return $e->die_event;
2461
2462         return $e->die_event unless
2463             $e->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2464
2465         foreach my $sstr (@{$sdist->streams}) {
2466             foreach my $sitem (@{$sstr->items}) {
2467                 if ($sitem->status ne 'Expected') {
2468                     return OpenILS::Event->new('SERIAL_DISTRIBUTION_NOT_EMPTY', payload=>$id);
2469                 }
2470                 if ($sitem->unit && !$U->is_true($sitem->unit->deleted)) {
2471                     return OpenILS::Event->new('SERIAL_DISTRIBUTION_NOT_EMPTY', payload=>$id);
2472                 }
2473             }
2474         }
2475
2476         $obj = $sdist;
2477
2478     } else { # subscription
2479         my $sub = $e->retrieve_serial_subscription([
2480             $id, {
2481                 "flesh" => 4, "flesh_fields" => {
2482                     "ssub" => [qw/distributions issuances/],
2483                     "sdist" => [qw/streams/],
2484                     "sstr" => ["items"],
2485                     "sitem" => ["unit"]
2486                 }
2487             }
2488         ]) or return $e->die_event;
2489
2490         return $e->die_event unless
2491             $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
2492
2493         foreach my $sdist (@{$sub->distributions}) {
2494             foreach my $sstr (@{$sdist->streams}) {
2495                 foreach my $sitem (@{$sstr->items}) {
2496                     if ($sitem->status ne 'Expected') {
2497                         return OpenILS::Event->new('SERIAL_SUBSCRIPTION_NOT_EMPTY', payload=>$id);
2498                     }
2499                     if ($sitem->unit && !$U->is_true($sitem->unit->deleted)) {
2500                         return OpenILS::Event->new('SERIAL_SUBSCRIPTION_NOT_EMPTY', payload=>$id);
2501                     }
2502                 }
2503             }
2504         }
2505
2506         $obj = $sub;
2507     }
2508
2509     if (! ($self->api_name =~ /dry_run/)) {
2510         my $method = "delete_serial_${type}";
2511         $e->$method($obj) or return $e->die_event;
2512         $e->commit;
2513     }
2514     return 1;
2515 }
2516
2517 __PACKAGE__->register_method(
2518     method    => 'fleshed_ssub_alter',
2519     api_name  => 'open-ils.serial.subscription.fleshed.batch.update',
2520     api_level => 1,
2521     argc      => 2,
2522     signature => {
2523         desc     => 'Receives an array of one or more subscriptions and updates the database as needed',
2524         'params' => [ {
2525                  name => 'authtoken',
2526                  desc => 'Authtoken for current user session',
2527                  type => 'string'
2528             },
2529             {
2530                  name => 'subscriptions',
2531                  desc => 'Array of fleshed subscriptions',
2532                  type => 'array'
2533             }
2534
2535         ],
2536         'return' => {
2537             desc => 'Returns 1 if successful, event if failed',
2538             type => 'mixed'
2539         }
2540     }
2541 );
2542
2543 sub fleshed_ssub_alter {
2544     my( $self, $conn, $auth, $ssubs ) = @_;
2545     return 1 unless ref $ssubs;
2546     my( $reqr, $evt ) = $U->checkses($auth);
2547     return $evt if $evt;
2548     my $editor = new_editor(requestor => $reqr, xact => 1);
2549     my $override = $self->api_name =~ /override/;
2550
2551     for my $ssub (@$ssubs) {
2552         my $owning_lib_id = ref $ssub->owning_lib ? $ssub->owning_lib->id : $ssub->owning_lib;
2553         return $editor->die_event unless
2554             $editor->allowed("ADMIN_SERIAL_SUBSCRIPTION", $owning_lib_id);
2555
2556         my $ssubid = $ssub->id;
2557
2558         if( $ssub->isdeleted ) {
2559             $evt = _delete_ssub( $editor, $override, $ssub);
2560         } elsif( $ssub->isnew ) {
2561             _cleanse_dates($ssub, ['start_date','end_date']);
2562             $evt = _create_ssub( $editor, $ssub );
2563         } else {
2564             _cleanse_dates($ssub, ['start_date','end_date']);
2565             $evt = _update_ssub( $editor, $override, $ssub );
2566         }
2567     }
2568
2569     if( $evt ) {
2570         $logger->info("fleshed subscription-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2571         $editor->rollback;
2572         return $evt;
2573     }
2574     $logger->debug("subscription-alter: done updating subscription batch");
2575     $editor->commit;
2576     $logger->info("fleshed subscription-alter successfully updated ".scalar(@$ssubs)." subscriptions");
2577     return 1;
2578 }
2579
2580 sub _delete_ssub {
2581     my ($editor, $override, $ssub) = @_;
2582     $logger->info("subscription-alter: delete subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2583     my $sdists = $editor->search_serial_distribution(
2584             { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2585     my $cps = $editor->search_serial_caption_and_pattern(
2586             { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2587     my $sisses = $editor->search_serial_issuance(
2588             { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2589     return OpenILS::Event->new(
2590             'SERIAL_SUBSCRIPTION_NOT_EMPTY', payload => $ssub->id ) if (@$sdists or @$cps or @$sisses);
2591
2592     return $editor->event unless $editor->delete_serial_subscription($ssub);
2593     return 0;
2594 }
2595
2596 sub _create_ssub {
2597     my ($editor, $ssub) = @_;
2598
2599     $logger->info("subscription-alter: new subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2600     return $editor->event unless $editor->create_serial_subscription($ssub);
2601     return 0;
2602 }
2603
2604 sub _update_ssub {
2605     my ($editor, $override, $ssub) = @_;
2606
2607     $logger->info("subscription-alter: retrieving subscription ".$ssub->id);
2608     my $orig_ssub = $editor->retrieve_serial_subscription($ssub->id);
2609
2610     $logger->info("subscription-alter: original subscription ".OpenSRF::Utils::JSON->perl2JSON($orig_ssub));
2611     $logger->info("subscription-alter: updated subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2612     return $editor->event unless $editor->update_serial_subscription($ssub);
2613     return 0;
2614 }
2615
2616 __PACKAGE__->register_method(
2617     method  => "fleshed_serial_subscription_retrieve_batch",
2618     authoritative => 1,
2619     api_name    => "open-ils.serial.subscription.fleshed.batch.retrieve"
2620 );
2621
2622 sub fleshed_serial_subscription_retrieve_batch {
2623     my( $self, $client, $ids ) = @_;
2624 # FIXME: permissions?
2625     $logger->info("Fetching fleshed subscriptions @$ids");
2626     return $U->cstorereq(
2627         "open-ils.cstore.direct.serial.subscription.search.atomic",
2628         { id => $ids },
2629         { flesh => 1,
2630           flesh_fields => {ssub => [ qw/owning_lib notes/ ]}
2631         });
2632 }
2633
2634 __PACKAGE__->register_method(
2635     method  => "retrieve_sub_tree",
2636     authoritative => 1,
2637     api_name    => "open-ils.serial.subscription_tree.retrieve"
2638 );
2639
2640 __PACKAGE__->register_method(
2641     method  => "retrieve_sub_tree",
2642     api_name    => "open-ils.serial.subscription_tree.global.retrieve"
2643 );
2644
2645 sub retrieve_sub_tree {
2646
2647     my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2648
2649     if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2650
2651     $docid = "$docid";
2652
2653     # TODO: permission support
2654     if(!@org_ids and $user_session) {
2655         my $user_obj = 
2656             OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2657             @org_ids = ($user_obj->home_ou);
2658     }
2659
2660     if( $self->api_name =~ /global/ ) {
2661         return _build_subs_list( { record_entry => $docid } ); # TODO: filter for !deleted, or active?
2662
2663     } else {
2664
2665         my @all_subs;
2666         for my $orgid (@org_ids) {
2667             my $subs = _build_subs_list( 
2668                     { record_entry => $docid, owning_lib => $orgid } );# TODO: filter for !deleted, or active?
2669             push( @all_subs, @$subs );
2670         }
2671         
2672         return \@all_subs;
2673     }
2674
2675     return undef;
2676 }
2677
2678 sub _build_subs_list {
2679     my $search_hash = shift;
2680
2681     #$search_hash->{deleted} = 'f';
2682     my $e = new_editor();
2683
2684     my $subs = $e->search_serial_subscription([$search_hash, { 'order_by' => {'ssub' => 'id'} }]);
2685
2686     my @built_subs;
2687
2688     for my $sub (@$subs) {
2689
2690         # TODO: filter on !deleted?
2691         my $dists = $e->search_serial_distribution(
2692             [{ subscription => $sub->id }, { 'order_by' => {'sdist' => 'label'} }]
2693             );
2694
2695         #$dists = [ sort { $a->label cmp $b->label } @$dists  ];
2696
2697         $sub->distributions($dists);
2698         
2699         # TODO: filter on !deleted?
2700         my $issuances = $e->search_serial_issuance(
2701             [{ subscription => $sub->id }, { 'order_by' => {'siss' => 'label'} }]
2702             );
2703
2704         #$issuances = [ sort { $a->label cmp $b->label } @$issuances  ];
2705         $sub->issuances($issuances);
2706
2707         # TODO: filter on !deleted?
2708         my $scaps = $e->search_serial_caption_and_pattern(
2709             [{ subscription => $sub->id }, { 'order_by' => {'scap' => 'id'} }]
2710             );
2711
2712         #$scaps = [ sort { $a->id cmp $b->id } @$scaps  ];
2713         $sub->scaps($scaps);
2714         push( @built_subs, $sub );
2715     }
2716
2717     return \@built_subs;
2718
2719 }
2720
2721 __PACKAGE__->register_method(
2722     method  => "subscription_orgs_for_title",
2723     authoritative => 1,
2724     api_name    => "open-ils.serial.subscription.retrieve_orgs_by_title"
2725 );
2726
2727 sub subscription_orgs_for_title {
2728     my( $self, $client, $record_id ) = @_;
2729
2730     my $subs = $U->simple_scalar_request(
2731         "open-ils.cstore",
2732         "open-ils.cstore.direct.serial.subscription.search.atomic",
2733         { record_entry => $record_id }); # TODO: filter on !deleted?
2734
2735     my $orgs = { map {$_->owning_lib => 1 } @$subs };
2736     return [ keys %$orgs ];
2737 }
2738
2739
2740 ##########################################################################
2741 # distribution methods
2742 #
2743 __PACKAGE__->register_method(
2744     method    => 'fleshed_sdist_alter',
2745     api_name  => 'open-ils.serial.distribution.fleshed.batch.update',
2746     api_level => 1,
2747     argc      => 2,
2748     signature => {
2749         desc     => 'Receives an array of one or more distributions and updates the database as needed',
2750         'params' => [ {
2751                  name => 'authtoken',
2752                  desc => 'Authtoken for current user session',
2753                  type => 'string'
2754             },
2755             {
2756                  name => 'distributions',
2757                  desc => 'Array of fleshed distributions',
2758                  type => 'array'
2759             }
2760
2761         ],
2762         'return' => {
2763             desc => 'Returns 1 if successful, event if failed',
2764             type => 'mixed'
2765         }
2766     }
2767 );
2768
2769 sub fleshed_sdist_alter {
2770     my( $self, $conn, $auth, $sdists ) = @_;
2771     return 1 unless ref $sdists;
2772     my( $reqr, $evt ) = $U->checkses($auth);
2773     return $evt if $evt;
2774     my $editor = new_editor(requestor => $reqr, xact => 1);
2775     my $override = $self->api_name =~ /override/;
2776
2777     for my $sdist (@$sdists) {
2778         my $holding_lib_id = ref $sdist->holding_lib ? $sdist->holding_lib->id : $sdist->holding_lib;
2779         return $editor->die_event unless
2780             $editor->allowed("ADMIN_SERIAL_DISTRIBUTION", $holding_lib_id);
2781
2782         if( $sdist->isdeleted ) {
2783             $evt = _delete_sdist( $editor, $override, $sdist);
2784         } elsif( $sdist->isnew ) {
2785             $evt = _create_sdist( $editor, $sdist );
2786         } else {
2787             $evt = _update_sdist( $editor, $override, $sdist );
2788         }
2789     }
2790
2791     if( $evt ) {
2792         $logger->info("fleshed distribution-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2793         $editor->rollback;
2794         return $evt;
2795     }
2796     $logger->debug("distribution-alter: done updating distribution batch");
2797     $editor->commit;
2798     $logger->info("fleshed distribution-alter successfully updated ".scalar(@$sdists)." distributions");
2799     return 1;
2800 }
2801
2802 sub _delete_sdist {
2803     my ($editor, $override, $sdist) = @_;
2804     $logger->info("distribution-alter: delete distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2805     return $editor->event unless $editor->delete_serial_distribution($sdist);
2806     return 0;
2807 }
2808
2809 sub _create_sdist {
2810     my ($editor, $sdist) = @_;
2811
2812     $logger->info("distribution-alter: new distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2813     return $editor->event unless $editor->create_serial_distribution($sdist);
2814
2815     # create summaries too
2816     my $summary = new Fieldmapper::serial::basic_summary;
2817     $summary->distribution($sdist->id);
2818     $summary->generated_coverage('');
2819     return $editor->event unless $editor->create_serial_basic_summary($summary);
2820     $summary = new Fieldmapper::serial::supplement_summary;
2821     $summary->distribution($sdist->id);
2822     $summary->generated_coverage('');
2823     return $editor->event unless $editor->create_serial_supplement_summary($summary);
2824     $summary = new Fieldmapper::serial::index_summary;
2825     $summary->distribution($sdist->id);
2826     $summary->generated_coverage('');
2827     return $editor->event unless $editor->create_serial_index_summary($summary);
2828
2829     # create a starter stream (TODO: reconsider this)
2830     my $stream = new Fieldmapper::serial::stream;
2831     $stream->distribution($sdist->id);
2832     return $editor->event unless $editor->create_serial_stream($stream);
2833
2834     return 0;
2835 }
2836
2837 sub _update_sdist {
2838     my ($editor, $override, $sdist) = @_;
2839
2840     $logger->info("distribution-alter: retrieving distribution ".$sdist->id);
2841     my $orig_sdist = $editor->retrieve_serial_distribution($sdist->id);
2842
2843     $logger->info("distribution-alter: original distribution ".OpenSRF::Utils::JSON->perl2JSON($orig_sdist));
2844     $logger->info("distribution-alter: updated distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2845     return $editor->event unless $editor->update_serial_distribution($sdist);
2846     return 0;
2847 }
2848
2849 __PACKAGE__->register_method(
2850     method  => "fleshed_serial_distribution_retrieve_batch",
2851     authoritative => 1,
2852     api_name    => "open-ils.serial.distribution.fleshed.batch.retrieve"
2853 );
2854
2855 sub fleshed_serial_distribution_retrieve_batch {
2856     my( $self, $client, $ids ) = @_;
2857 # FIXME: permissions?
2858     $logger->info("Fetching fleshed distributions @$ids");
2859     return $U->cstorereq(
2860         "open-ils.cstore.direct.serial.distribution.search.atomic",
2861         { id => $ids },
2862         { flesh => 1,
2863           flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams notes / ]}
2864         });
2865 }
2866
2867 __PACKAGE__->register_method(
2868     method  => "retrieve_dist_tree",
2869     authoritative => 1,
2870     api_name    => "open-ils.serial.distribution_tree.retrieve"
2871 );
2872
2873 __PACKAGE__->register_method(
2874     method  => "retrieve_dist_tree",
2875     api_name    => "open-ils.serial.distribution_tree.global.retrieve"
2876 );
2877
2878 sub retrieve_dist_tree {
2879     my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2880
2881     if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2882
2883     $docid = "$docid";
2884
2885     # TODO: permission support
2886     if(!@org_ids and $user_session) {
2887         my $user_obj =
2888             OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2889             @org_ids = ($user_obj->home_ou);
2890     }
2891
2892     my $e = new_editor();
2893
2894     if( $self->api_name =~ /global/ ) {
2895         return $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }},
2896             {   flesh => 1,
2897                 flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams basic_summary supplement_summary index_summary / ]},
2898                 order_by => {'sdist' => 'id'},
2899                 'join' => {'ssub' => {}}
2900             }
2901         ]); # TODO: filter for !deleted?
2902
2903     } else {
2904         my @all_dists;
2905         for my $orgid (@org_ids) {
2906             my $dists = $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }, holding_lib => $orgid},
2907                 {   flesh => 1,
2908                     flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams basic_summary supplement_summary index_summary / ]},
2909                     order_by => {'sdist' => 'id'},
2910                     'join' => {'ssub' => {}}
2911                 }
2912             ]); # TODO: filter for !deleted?
2913             push( @all_dists, @$dists ) if $dists;
2914         }
2915
2916         return \@all_dists;
2917     }
2918
2919     return undef;
2920 }
2921
2922
2923 __PACKAGE__->register_method(
2924     method  => "distribution_orgs_for_title",
2925     authoritative => 1,
2926     api_name    => "open-ils.serial.distribution.retrieve_orgs_by_title"
2927 );
2928
2929 sub distribution_orgs_for_title {
2930     my( $self, $client, $record_id ) = @_;
2931
2932     my $dists = $U->cstorereq(
2933         "open-ils.cstore.direct.serial.distribution.search.atomic",
2934         { '+ssub' => { record_entry => $record_id } },
2935         { 'join' => {'ssub' => {}} }); # TODO: filter on !deleted?
2936
2937     my $orgs = { map {$_->holding_lib => 1 } @$dists };
2938     return [ keys %$orgs ];
2939 }
2940
2941
2942 ##########################################################################
2943 # caption and pattern methods
2944 #
2945 __PACKAGE__->register_method(
2946     method    => 'scap_alter',
2947     api_name  => 'open-ils.serial.caption_and_pattern.batch.update',
2948     api_level => 1,
2949     argc      => 2,
2950     signature => {
2951         desc     => 'Receives an array of one or more caption and patterns and updates the database as needed',
2952         'params' => [ {
2953                  name => 'authtoken',
2954                  desc => 'Authtoken for current user session',
2955                  type => 'string'
2956             },
2957             {
2958                  name => 'scaps',
2959                  desc => 'Array of caption and patterns',
2960                  type => 'array'
2961             }
2962
2963         ],
2964         'return' => {
2965             desc => 'Returns 1 if successful, event if failed',
2966             type => 'mixed'
2967         }
2968     }
2969 );
2970
2971 sub scap_alter {
2972     my( $self, $conn, $auth, $scaps ) = @_;
2973     return 1 unless ref $scaps;
2974     my( $reqr, $evt ) = $U->checkses($auth);
2975     return $evt if $evt;
2976     my $editor = new_editor(requestor => $reqr, xact => 1);
2977     my $override = $self->api_name =~ /override/;
2978
2979     my %found_ssub_ids;
2980     for my $scap (@$scaps) {
2981         if (!exists($found_ssub_ids{$scap->subscription})) {
2982             my $ssub = $editor->retrieve_serial_subscription($scap->subscription) or return $editor->die_event;
2983             return $editor->die_event unless
2984                 $editor->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $ssub->owning_lib);
2985             $found_ssub_ids{$scap->subscription} = 1;
2986         }
2987
2988         if( $scap->isdeleted ) {
2989             $evt = _delete_scap( $editor, $override, $scap);
2990         } elsif( $scap->isnew ) {
2991             $evt = _create_scap( $editor, $scap );
2992         } else {
2993             $evt = _update_scap( $editor, $override, $scap );
2994         }
2995     }
2996
2997     if( $evt ) {
2998         $logger->info("caption_and_pattern-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2999         $editor->rollback;
3000         return $evt;
3001     }
3002     $logger->debug("caption_and_pattern-alter: done updating caption_and_pattern batch");
3003     $editor->commit;
3004     $logger->info("caption_and_pattern-alter successfully updated ".scalar(@$scaps)." caption_and_patterns");
3005     return 1;
3006 }
3007
3008 sub _delete_scap {
3009     my ($editor, $override, $scap) = @_;
3010     $logger->info("caption_and_pattern-alter: delete caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
3011     my $sisses = $editor->search_serial_issuance(
3012             { caption_and_pattern => $scap->id }, { limit => 1 } ); #TODO: 'deleted' support?
3013     return OpenILS::Event->new(
3014             'SERIAL_CAPTION_AND_PATTERN_HAS_ISSUANCES', payload => $scap->id ) if (@$sisses);
3015
3016     return $editor->event unless $editor->delete_serial_caption_and_pattern($scap);
3017     return 0;
3018 }
3019
3020 sub _create_scap {
3021     my ($editor, $scap) = @_;
3022
3023     $logger->info("caption_and_pattern-alter: new caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
3024     return $editor->event unless $editor->create_serial_caption_and_pattern($scap);
3025     return 0;
3026 }
3027
3028 sub _update_scap {
3029     my ($editor, $override, $scap) = @_;
3030
3031     $logger->info("caption_and_pattern-alter: retrieving caption_and_pattern ".$scap->id);
3032     my $orig_scap = $editor->retrieve_serial_caption_and_pattern($scap->id);
3033
3034     $logger->info("caption_and_pattern-alter: original caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($orig_scap));
3035     $logger->info("caption_and_pattern-alter: updated caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
3036     return $editor->event unless $editor->update_serial_caption_and_pattern($scap);
3037     return 0;
3038 }
3039
3040 __PACKAGE__->register_method(
3041     method  => "serial_caption_and_pattern_retrieve_batch",
3042     authoritative => 1,
3043     api_name    => "open-ils.serial.caption_and_pattern.batch.retrieve"
3044 );
3045
3046 sub serial_caption_and_pattern_retrieve_batch {
3047     my( $self, $client, $ids ) = @_;
3048     $logger->info("Fetching caption_and_patterns @$ids");
3049     return $U->cstorereq(
3050         "open-ils.cstore.direct.serial.caption_and_pattern.search.atomic",
3051         { id => $ids }
3052     );
3053 }
3054
3055 ##########################################################################
3056 # stream methods
3057 #
3058 __PACKAGE__->register_method(
3059     method    => 'sstr_alter',
3060     api_name  => 'open-ils.serial.stream.batch.update',
3061     api_level => 1,
3062     argc      => 2,
3063     signature => {
3064         desc     => 'Receives an array of one or more streams and updates the database as needed',
3065         'params' => [ {
3066                  name => 'authtoken',
3067                  desc => 'Authtoken for current user session',
3068                  type => 'string'
3069             },
3070             {
3071                  name => 'sstrs',
3072                  desc => 'Array of streams',
3073                  type => 'array'
3074             }
3075
3076         ],
3077         'return' => {
3078             desc => 'Returns 1 if successful, event if failed',
3079             type => 'mixed'
3080         }
3081     }
3082 );
3083
3084 sub sstr_alter {
3085     my( $self, $conn, $auth, $sstrs ) = @_;
3086     return 1 unless ref $sstrs;
3087     my( $reqr, $evt ) = $U->checkses($auth);
3088     return $evt if $evt;
3089     my $editor = new_editor(requestor => $reqr, xact => 1);
3090     my $override = $self->api_name =~ /override/;
3091
3092     my %found_sdist_ids;
3093     for my $sstr (@$sstrs) {
3094         if (!exists($found_sdist_ids{$sstr->distribution})) {
3095             my $sdist = $editor->retrieve_serial_distribution($sstr->distribution) or return $editor->die_event;
3096             return $editor->die_event unless
3097                 $editor->allowed("ADMIN_SERIAL_STREAM", $sdist->holding_lib);
3098             $found_sdist_ids{$sstr->distribution} = 1;
3099         }
3100
3101         if( $sstr->isdeleted ) {
3102             $evt = _delete_sstr( $editor, $override, $sstr);
3103         } elsif( $sstr->isnew ) {
3104             $evt = _create_sstr( $editor, $sstr );
3105         } else {
3106             $evt = _update_sstr( $editor, $override, $sstr );
3107         }
3108     }
3109
3110     if( $evt ) {
3111         $logger->info("stream-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
3112         $editor->rollback;
3113         return $evt;
3114     }
3115     $logger->debug("stream-alter: done updating stream batch");
3116     $editor->commit;
3117     $logger->info("stream-alter successfully updated ".scalar(@$sstrs)." streams");
3118     return 1;
3119 }
3120
3121 sub _delete_sstr {
3122     my ($editor, $override, $sstr) = @_;
3123     $logger->info("stream-alter: delete stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
3124     my $sitems = $editor->search_serial_item(
3125             { stream => $sstr->id }, { limit => 1 } ); #TODO: 'deleted' support?
3126     return OpenILS::Event->new(
3127             'SERIAL_STREAM_HAS_ITEMS', payload => $sstr->id ) if (@$sitems);
3128
3129     return $editor->event unless $editor->delete_serial_stream($sstr);
3130     return 0;
3131 }
3132
3133 sub _create_sstr {
3134     my ($editor, $sstr) = @_;
3135
3136     $logger->info("stream-alter: new stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
3137     return $editor->event unless $editor->create_serial_stream($sstr);
3138     return 0;
3139 }
3140
3141 sub _update_sstr {
3142     my ($editor, $override, $sstr) = @_;
3143
3144     $logger->info("stream-alter: retrieving stream ".$sstr->id);
3145     my $orig_sstr = $editor->retrieve_serial_stream($sstr->id);
3146
3147     $logger->info("stream-alter: original stream ".OpenSRF::Utils::JSON->perl2JSON($orig_sstr));
3148     $logger->info("stream-alter: updated stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
3149     return $editor->event unless $editor->update_serial_stream($sstr);
3150     return 0;
3151 }
3152
3153 __PACKAGE__->register_method(
3154     method  => "serial_stream_retrieve_batch",
3155     authoritative => 1,
3156     api_name    => "open-ils.serial.stream.batch.retrieve"
3157 );
3158
3159 sub serial_stream_retrieve_batch {
3160     my( $self, $client, $ids ) = @_;
3161     $logger->info("Fetching streams @$ids");
3162     return $U->cstorereq(
3163         "open-ils.cstore.direct.serial.stream.search.atomic",
3164         { id => $ids }
3165     );
3166 }
3167
3168
3169 ##########################################################################
3170 # summary methods
3171 #
3172 __PACKAGE__->register_method(
3173     method    => 'sum_alter',
3174     api_name  => 'open-ils.serial.basic_summary.batch.update',
3175     api_level => 1,
3176     argc      => 2,
3177     signature => {
3178         desc     => 'Receives an array of one or more summaries and updates the database as needed',
3179         'params' => [ {
3180                  name => 'authtoken',
3181                  desc => 'Authtoken for current user session',
3182                  type => 'string'
3183             },
3184             {
3185                  name => 'sbsums',
3186                  desc => 'Array of basic summaries',
3187                  type => 'array'
3188             }
3189
3190         ],
3191         'return' => {
3192             desc => 'Returns 1 if successful, event if failed',
3193             type => 'mixed'
3194         }
3195     }
3196 );
3197
3198 __PACKAGE__->register_method(
3199     method    => 'sum_alter',
3200     api_name  => 'open-ils.serial.supplement_summary.batch.update',
3201     api_level => 1,
3202     argc      => 2,
3203     signature => {
3204         desc     => 'Receives an array of one or more summaries and updates the database as needed',
3205         'params' => [ {
3206                  name => 'authtoken',
3207                  desc => 'Authtoken for current user session',
3208                  type => 'string'
3209             },
3210             {
3211                  name => 'sbsums',
3212                  desc => 'Array of supplement summaries',
3213                  type => 'array'
3214             }
3215
3216         ],
3217         'return' => {
3218             desc => 'Returns 1 if successful, event if failed',
3219             type => 'mixed'
3220         }
3221     }
3222 );
3223
3224 __PACKAGE__->register_method(
3225     method    => 'sum_alter',
3226     api_name  => 'open-ils.serial.index_summary.batch.update',
3227     api_level => 1,
3228     argc      => 2,
3229     signature => {
3230         desc     => 'Receives an array of one or more summaries and updates the database as needed',
3231         'params' => [ {
3232                  name => 'authtoken',
3233                  desc => 'Authtoken for current user session',
3234                  type => 'string'
3235             },
3236             {
3237                  name => 'sbsums',
3238                  desc => 'Array of index summaries',
3239                  type => 'array'
3240             }
3241
3242         ],
3243         'return' => {
3244             desc => 'Returns 1 if successful, event if failed',
3245             type => 'mixed'
3246         }
3247     }
3248 );
3249
3250 sub sum_alter {
3251     my( $self, $conn, $auth, $sums ) = @_;
3252     return 1 unless ref $sums;
3253
3254     $self->api_name =~ /serial\.(\w*)_summary/;
3255     my $type = $1;
3256
3257     my( $reqr, $evt ) = $U->checkses($auth);
3258     return $evt if $evt;
3259     my $editor = new_editor(requestor => $reqr, xact => 1);
3260     my $override = $self->api_name =~ /override/;
3261
3262     my %found_sdist_ids;
3263     for my $sum (@$sums) {
3264         if (!exists($found_sdist_ids{$sum->distribution})) {
3265             my $sdist = $editor->retrieve_serial_distribution($sum->distribution) or return $editor->die_event;
3266             return $editor->die_event unless
3267                 $editor->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
3268             $found_sdist_ids{$sum->distribution} = 1;
3269         }
3270
3271         # XXX: (for now, at least) summaries should be created/deleted by the distribution functions
3272         if( $sum->isdeleted ) {
3273             $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
3274         } elsif( $sum->isnew ) {
3275             $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
3276         } else {
3277             $evt = _update_sum( $editor, $override, $sum, $type );
3278         }
3279     }
3280
3281     if( $evt ) {
3282         $logger->info("${type}_summary-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
3283         $editor->rollback;
3284         return $evt;
3285     }
3286     $logger->debug("${type}_summary-alter: done updating ${type}_summary batch");
3287     $editor->commit;
3288     $logger->info("${type}_summary-alter successfully updated ".scalar(@$sums)." ${type}_summaries");
3289     return 1;
3290 }
3291
3292 sub _update_sum {
3293     my ($editor, $override, $sum, $type) = @_;
3294
3295     $logger->info("${type}_summary-alter: retrieving ${type}_summary ".$sum->id);
3296     my $retrieve_method = "retrieve_serial_${type}_summary";
3297     my $orig_sum = $editor->$retrieve_method($sum->id);
3298
3299     $logger->info("${type}_summary-alter: original ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($orig_sum));
3300     $logger->info("${type}_summary-alter: updated ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($sum));
3301     my $update_method = "update_serial_${type}_summary";
3302     return $editor->event unless $editor->$update_method($sum);
3303     return 0;
3304 }
3305
3306 __PACKAGE__->register_method(
3307     method  => "serial_summary_retrieve_batch",
3308     authoritative => 1,
3309     api_name    => "open-ils.serial.basic_summary.batch.retrieve"
3310 );
3311
3312 __PACKAGE__->register_method(
3313     method  => "serial_summary_retrieve_batch",
3314     authoritative => 1,
3315     api_name    => "open-ils.serial.supplement_summary.batch.retrieve"
3316 );
3317
3318 __PACKAGE__->register_method(
3319     method  => "serial_summary_retrieve_batch",
3320     authoritative => 1,
3321     api_name    => "open-ils.serial.index_summary.batch.retrieve"
3322 );
3323
3324 sub serial_summary_retrieve_batch {
3325     my( $self, $client, $ids ) = @_;
3326
3327     $self->api_name =~ /serial\.(\w*)_summary/;
3328     my $type = $1;
3329
3330     $logger->info("Fetching ${type}_summaries @$ids");
3331     return $U->cstorereq(
3332         "open-ils.cstore.direct.serial.".$type."_summary.search.atomic",
3333         { id => $ids }
3334     );
3335 }
3336
3337
3338 ##########################################################################
3339 # other methods
3340 #
3341 __PACKAGE__->register_method(
3342     "method" => "bre_by_identifier",
3343     "api_name" => "open-ils.serial.biblio.record_entry.by_identifier",
3344     "stream" => 1,
3345     "signature" => {
3346         "desc" => "Find instances of biblio.record_entry given a search token" .
3347             " that could be a value for any identifier defined in " .
3348             "config.metabib_field",
3349         "params" => [
3350             {"desc" => "Search token", "type" => "string"},
3351             {"desc" => "Options: require_subscriptions, add_mvr, is_actual_id" .
3352                 ", id_list (all boolean)", "type" => "object"}
3353         ],
3354         "return" => {
3355             "desc" => "Any matching BREs, or if the add_mvr option is true, " .
3356                 "objects with a 'bre' key/value pair, and an 'mvr' " .
3357                 "key-value pair.  BREs have subscriptions fleshed on.",
3358             "type" => "object"
3359         }
3360     }
3361 );
3362
3363 sub bre_by_identifier {
3364     my ($self, $client, $term, $options) = @_;
3365
3366     return new OpenILS::Event("BAD_PARAMS") unless $term;
3367
3368     $options ||= {};
3369     my $e = new_editor();
3370
3371     my @ids;
3372
3373     if ($options->{"is_actual_id"}) {
3374         @ids = ($term);
3375     } else {
3376         my $cmf =
3377             $e->search_config_metabib_field({"field_class" => "identifier"})
3378                 or return $e->die_event;
3379
3380         my @identifiers = map { $_->name } @$cmf;
3381         my $query = join(" || ", map { "id|$_: $term" } @identifiers);
3382
3383         my $search = create OpenSRF::AppSession("open-ils.search");
3384         my $search_result = $search->request(
3385             "open-ils.search.biblio.multiclass.query.staff", {}, $query
3386         )->gather(1);
3387         $search->disconnect;
3388
3389         # Un-nest results. They tend to look like [[1],[2],[3]] for some reason.
3390         @ids = map { @{$_} } @{$search_result->{"ids"}};
3391
3392         unless (@ids) {
3393             $e->disconnect;
3394             return undef;
3395         }
3396
3397         if ($options->{"id_list"}) {
3398             $e->disconnect;
3399             $client->respond($_) foreach (@ids);
3400             return undef;
3401         }
3402     }
3403
3404     my $bre = $e->search_biblio_record_entry([
3405         {"id" => \@ids}, {
3406             "flesh" => 2, "flesh_fields" => {
3407                 "bre" => ["subscriptions"],
3408                 "ssub" => ["owning_lib"]
3409             }
3410         }
3411     ]) or return $e->die_event;
3412
3413     if (@$bre && $options->{"require_subscriptions"}) {
3414         $bre = [ grep { @{$_->subscriptions} } @$bre ];
3415     }
3416
3417     $e->disconnect;
3418
3419     if (@$bre) { # re-evaluate after possible grep
3420         if ($options->{"add_mvr"}) {
3421             $client->respond(
3422                 {"bre" => $_, "mvr" => _get_mvr($_->id)}
3423             ) foreach (@$bre);
3424         } else {
3425             $client->respond($_) foreach (@$bre);
3426         }
3427     }
3428
3429     undef;
3430 }
3431
3432 __PACKAGE__->register_method(
3433     "method" => "get_items_by",
3434     "api_name" => "open-ils.serial.items.receivable.by_subscription",
3435     "stream" => 1,
3436     "signature" => {
3437         "desc" => "Return all receivable items under a given subscription",
3438         "params" => [
3439             {"desc" => "Authtoken", "type" => "string"},
3440             {"desc" => "Subscription ID", "type" => "number"},
3441         ],
3442         "return" => {
3443             "desc" => "All receivable items under a given subscription",
3444             "type" => "object", "class" => "sitem"
3445         }
3446     }
3447 );
3448
3449 __PACKAGE__->register_method(
3450     "method" => "get_items_by",
3451     "api_name" => "open-ils.serial.items.receivable.by_issuance",
3452     "stream" => 1,
3453     "signature" => {
3454         "desc" => "Return all receivable items under a given issuance",
3455         "params" => [
3456             {"desc" => "Authtoken", "type" => "string"},
3457             {"desc" => "Issuance ID", "type" => "number"},
3458         ],
3459         "return" => {
3460             "desc" => "All receivable items under a given issuance",
3461             "type" => "object", "class" => "sitem"
3462         }
3463     }
3464 );
3465
3466 __PACKAGE__->register_method(
3467     "method" => "get_items_by",
3468     "api_name" => "open-ils.serial.items.by_issuance",
3469     "stream" => 1,
3470     "signature" => {
3471         "desc" => "Return all items under a given issuance",
3472         "params" => [
3473             {"desc" => "Authtoken", "type" => "string"},
3474             {"desc" => "Issuance ID", "type" => "number"},
3475         ],
3476         "return" => {
3477             "desc" => "All items under a given issuance",
3478             "type" => "object", "class" => "sitem"
3479         }
3480     }
3481 );
3482
3483 sub get_items_by {
3484     my ($self, $client, $auth, $term, $opts)  = @_;
3485
3486     # Not to be used in the json_query, but after limiting by perm check.
3487     $opts = {} unless ref $opts eq "HASH";
3488     $opts->{"limit"} ||= 10000;    # some existing users may want all results
3489     $opts->{"offset"} ||= 0;
3490     $opts->{"limit"} = int($opts->{"limit"});
3491     $opts->{"offset"} = int($opts->{"offset"});
3492
3493     my $e = new_editor("authtoken" => $auth);
3494     return $e->die_event unless $e->checkauth;
3495
3496     my $by = ($self->api_name =~ /by_(\w+)$/)[0];
3497     my $receivable = ($self->api_name =~ /receivable/);
3498
3499     my %where = (
3500         "issuance" => {"issuance" => $term},
3501         "subscription" => {"+siss" => {"subscription" => $term}}
3502     );
3503
3504     my $item_rows = $e->json_query(
3505         {
3506             "select" => {"sitem" => ["id"], "sdist" => ["holding_lib"]},
3507             "from" => {
3508                 "sitem" => {
3509                     "siss" => {},
3510                     "sstr" => {"join" => {"sdist" => {}}}
3511                 }
3512             },
3513             "where" => {
3514                 %{$where{$by}}, $receivable ? ("date_received" => undef) : ()
3515             },
3516             "order_by" => {"sitem" => ["id"]}
3517         }
3518     ) or return $e->die_event;
3519
3520     return undef unless @$item_rows;
3521
3522     my $skipped = 0;
3523     my $returned = 0;
3524     foreach (@$item_rows) {
3525         last if $returned >= $opts->{"limit"};
3526         next unless $e->allowed("RECEIVE_SERIAL", $_->{"holding_lib"});
3527         if ($skipped < $opts->{"offset"}) {
3528             $skipped++;
3529             next;
3530         }
3531
3532         $client->respond(
3533             $e->retrieve_serial_item([
3534                 $_->{"id"}, {
3535                     "flesh" => 3,
3536                     "flesh_fields" => {
3537                         "sitem" => [qw/stream issuance unit creator editor/],
3538                         "sstr" => ["distribution"],
3539                         "sdist" => ["holding_lib"]
3540                     }
3541                 }
3542             ])
3543         );
3544         $returned++;
3545     }
3546
3547     $e->disconnect;
3548     undef;
3549 }
3550
3551 __PACKAGE__->register_method(
3552     "method" => "get_receivable_issuances",
3553     "api_name" => "open-ils.serial.issuances.receivable",
3554     "stream" => 1,
3555     "signature" => {
3556         "desc" => "Return all issuances with receivable items given " .
3557             "a subscription ID",
3558         "params" => [
3559             {"desc" => "Authtoken", "type" => "string"},
3560             {"desc" => "Subscription ID", "type" => "number"},
3561         ],
3562         "return" => {
3563             "desc" => "All issuances with receivable items " .
3564                 "(but not the items themselves)", "type" => "object"
3565         }
3566     }
3567 );
3568
3569 sub get_receivable_issuances {
3570     my ($self, $client, $auth, $sub_id) = @_;
3571
3572     my $e = new_editor("authtoken" => $auth);
3573     return $e->die_event unless $e->checkauth;
3574
3575     # XXX permissions
3576
3577     my $issuance_ids = $e->json_query({
3578         "select" => {
3579             "siss" => [
3580                 {"transform" => "distinct", "column" => "id"},
3581                 "date_published"
3582             ]
3583         },
3584         "from" => {"siss" => "sitem"},
3585         "where" => {
3586             "subscription" => $sub_id,
3587             "+sitem" => {"date_received" => undef}
3588         },
3589         "order_by" => {
3590             "siss" => {"date_published" => {"direction" => "asc"}}
3591         }
3592
3593     }) or return $e->die_event;
3594
3595     $client->respond($e->retrieve_serial_issuance($_->{"id"}))
3596         foreach (@$issuance_ids);
3597
3598     $e->disconnect;
3599     undef;
3600 }
3601
3602
3603 __PACKAGE__->register_method(
3604     "method" => "get_routing_list_users",
3605     "api_name" => "open-ils.serial.routing_list_users.fleshed_and_ordered",
3606     "stream" => 1,
3607     "signature" => {
3608         "desc" => "Return all routing list users with reader fleshed " .
3609             "(with card and home_ou) for a given stream ID, sorted by pos",
3610         "params" => [
3611             {"desc" => "Authtoken", "type" => "string"},
3612             {"desc" => "Stream ID (int or array of ints)", "type" => "mixed"},
3613         ],
3614         "return" => {
3615             "desc" => "Stream of routing list users", "type" => "object",
3616                 "class" => "srlu"
3617         }
3618     }
3619 );
3620
3621 sub get_routing_list_users {
3622     my ($self, $client, $auth, $stream_id) = @_;
3623
3624     my $e = new_editor("authtoken" => $auth);
3625     return $e->die_event unless $e->checkauth;
3626
3627     my $users = $e->search_serial_routing_list_user([
3628         {"stream" => $stream_id}, {
3629             "order_by" => {"srlu" => "pos"},
3630             "flesh" => 2,
3631             "flesh_fields" => {
3632                 "srlu" => [qw/reader stream/],
3633                 "au" => [qw/card home_ou mailing_address billing_address/],
3634                 "sstr" => ["distribution"]
3635             }
3636         }
3637     ]) or return $e->die_event;
3638
3639     return undef unless @$users;
3640
3641     # The ADMIN_SERIAL_STREAM permission is used simply to avoid the
3642     # need for any new permission.  The context OU will be the same
3643     # for every result of the above query, so we need only check once.
3644     return $e->die_event unless $e->allowed(
3645         "ADMIN_SERIAL_STREAM", $users->[0]->stream->distribution->holding_lib
3646     );
3647
3648     $e->disconnect;
3649
3650     my @users = map { $_->stream($_->stream->id); $_ } @$users;
3651     @users = sort { $a->stream cmp $b->stream } @users if
3652         ref $stream_id eq "ARRAY";
3653
3654     $client->respond($_) for @users;
3655
3656     undef;
3657 }
3658
3659
3660 __PACKAGE__->register_method(
3661     "method" => "replace_routing_list_users",
3662     "api_name" => "open-ils.serial.routing_list_users.replace",
3663     "signature" => {
3664         "desc" => "Replace all routing list users on the specified streams " .
3665             "with those in the list argument",
3666         "params" => [
3667             {"desc" => "Authtoken", "type" => "string"},
3668             {"desc" => "List of srlu objects", "type" => "array"},
3669         ],
3670         "return" => {
3671             "desc" => "event on failure, undef on success"
3672         }
3673     }
3674 );
3675
3676 sub replace_routing_list_users {
3677     my ($self, $client, $auth, $users) = @_;
3678
3679     return undef unless ref $users eq "ARRAY";
3680
3681     if (grep { ref $_ ne "Fieldmapper::serial::routing_list_user" } @$users) {
3682         return new OpenILS::Event("BAD_PARAMS", "note" => "Only srlu objects");
3683     }
3684
3685     my $e = new_editor("authtoken" => $auth, "xact" => 1);
3686     return $e->die_event unless $e->checkauth;
3687
3688     my %streams_ok = ();
3689     my $pos = 0;
3690
3691     foreach my $user (@$users) {
3692         unless (exists $streams_ok{$user->stream}) {
3693             my $stream = $e->retrieve_serial_stream([
3694                 $user->stream, {
3695                     "flesh" => 1,
3696                     "flesh_fields" => {"sstr" => ["distribution"]}
3697                 }
3698             ]) or return $e->die_event;
3699             $e->allowed(
3700                 "ADMIN_SERIAL_STREAM", $stream->distribution->holding_lib
3701             ) or return $e->die_event;
3702
3703             my $to_delete = $e->search_serial_routing_list_user(
3704                 {"stream" => $user->stream}
3705             ) or return $e->die_event;
3706
3707             $logger->info(
3708                 "Deleting srlu: [" .
3709                 join(", ", map { $_->id; } @$to_delete) .
3710                 "]"
3711             );
3712
3713             foreach (@$to_delete) {
3714                 $e->delete_serial_routing_list_user($_) or
3715                     return $e->die_event;
3716             }
3717
3718             $streams_ok{$user->stream} = 1;
3719         }
3720
3721         next if $user->isdeleted;
3722
3723         $user->clear_id;
3724         $user->pos($pos++);
3725         $e->create_serial_routing_list_user($user) or return $e->die_event;
3726     }
3727
3728     $e->commit or return $e->die_event;
3729     undef;
3730 }
3731
3732 __PACKAGE__->register_method(
3733     "method" => "get_records_with_marc_85x",
3734     "api_name"=>"open-ils.serial.caption_and_pattern.find_legacy_by_bib_record",
3735     "stream" => 1,
3736     "signature" => {
3737         "desc" => "Return the specified BRE itself and/or any related SRE ".
3738             "whenever they have 853-855 tags",
3739         "params" => [
3740             {"desc" => "Authtoken", "type" => "string"},
3741             {"desc" => "bib record ID", "type" => "number"},
3742         ],
3743         "return" => {
3744             "desc" => "objects, either bre or sre", "type" => "object"
3745         }
3746     }
3747 );
3748
3749 sub get_records_with_marc_85x { # specifically, 853-855
3750     my ($self, $client, $auth, $bre_id) = @_;
3751
3752     my $e = new_editor("authtoken" => $auth);
3753     return $e->die_event unless $e->checkauth;
3754
3755     my $bre = $e->search_biblio_record_entry([
3756         {"id" => $bre_id, "deleted" => "f"}, {
3757             "flesh" => 1,
3758             "flesh_fields" => {"bre" => [qw/creator editor owner/]}
3759         }
3760     ]) or return $e->die_event;
3761
3762     return undef unless @$bre;
3763     $bre = $bre->[0];
3764
3765     my $record = MARC::Record->new_from_xml($bre->marc);
3766     $client->respond($bre) if $record->field("85[3-5]");
3767     # XXX Is passing a regex to ->field() an abuse of MARC::Record ?
3768
3769     my $sres = $e->search_serial_record_entry([
3770         {"record" => $bre_id, "deleted" => "f"}, {
3771             "flesh" => 1,
3772             "flesh_fields" => {"sre" => [qw/creator editor owning_lib/]}
3773         }
3774     ]) or return $e->die_event;
3775
3776     $e->disconnect;
3777
3778     foreach my $sre (@$sres) {
3779         $client->respond($sre) if
3780             MARC::Record->new_from_xml($sre->marc)->field("85[3-5]");
3781     }
3782
3783     undef;
3784 }
3785
3786 __PACKAGE__->register_method(
3787     "method" => "create_scaps_from_marcxml",
3788     "api_name" => "open-ils.serial.caption_and_pattern.create_from_records",
3789     "stream" => 1,
3790     "signature" => {
3791         "desc" => "Create caption and pattern objects from 853-855 tags " .
3792             "in MARCXML documents",
3793         "params" => [
3794             {"desc" => "Authtoken", "type" => "string"},
3795             {"desc" => "Subscription ID", "type" => "number"},
3796             {"desc" => "list of MARCXML documents as strings",
3797                 "type" => "array"},
3798         ],
3799         "return" => {
3800             "desc" => "Newly created caption and pattern objects",
3801             "type" => "object", "class" => "scap"
3802         }
3803     }
3804 );
3805
3806 sub create_scaps_from_marcxml {
3807     my ($self, $client, $auth, $sub_id, $docs) = @_;
3808
3809     return undef unless ref $docs eq "ARRAY";
3810
3811     my $e = new_editor("authtoken" => $auth, "xact" => 1);
3812     return $e->die_event unless $e->checkauth;
3813
3814     # Retrieve the subscription just for perm checking (whether we can create
3815     # scaps at the owning lib).
3816     my $sub = $e->retrieve_serial_subscription($sub_id) or return $e->die_event;
3817     return $e->die_event unless
3818         $e->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $sub->owning_lib);
3819
3820     foreach my $record (map { MARC::Record->new_from_xml($_) } @$docs) {
3821         foreach my $field ($record->field("85[3-5]")) {
3822             my $scap = new Fieldmapper::serial::caption_and_pattern;
3823             $scap->subscription($sub_id);
3824             $scap->type($MFHD_NAMES_BY_TAG{$field->tag});
3825             $scap->pattern_code(
3826                 OpenSRF::Utils::JSON->perl2JSON(
3827                     [ $field->indicator(1), $field->indicator(2),
3828                         map { @$_ } $field->subfields ] # flattens nested array
3829                 )
3830             );
3831             $e->create_serial_caption_and_pattern($scap) or
3832                 return $e->die_event;
3833             $client->respond($e->data);
3834         }
3835     }
3836
3837     $e->commit or return $e->die_event;
3838     undef;
3839 }
3840
3841 # All these _clone_foo() functions could possibly have been consolidated into
3842 # one clever function, but it's faster to get things working this way.
3843 sub _clone_subscription {
3844     my ($sub, $bib_id, $e) = @_;
3845
3846     # clone sub itself
3847     my $new_sub = $sub->clone;
3848     $new_sub->record_entry(int $bib_id) if $bib_id;
3849     $new_sub->clear_id;
3850     $new_sub->clear_distributions;
3851     $new_sub->clear_notes;
3852     $new_sub->clear_scaps;
3853
3854     $e->create_serial_subscription($new_sub) or return $e->die_event;
3855
3856     my $new_sub_id = $e->data->id;
3857     # clone dists
3858     foreach my $dist (@{$sub->distributions}) {
3859         my $r = _clone_distribution($dist, $new_sub_id, $e);
3860         return $r if $U->event_code($r);
3861     }
3862
3863     # clone sub notes
3864     foreach my $note (@{$sub->notes}) {
3865         my $r = _clone_subscription_note($note, $new_sub_id, $e);
3866         return $r if $U->event_code($r);
3867     }
3868
3869     # clone scaps
3870     foreach my $scap (@{$sub->scaps}) {
3871         my $r = _clone_caption_and_pattern($scap, $new_sub_id, $e);
3872         return $r if $U->event_code($r);
3873     }
3874
3875     return $new_sub_id;
3876 }
3877
3878 sub _clone_distribution {
3879     my ($dist, $sub_id, $e) = @_;
3880
3881     my $new_dist = $dist->clone;
3882     $new_dist->clear_id;
3883     $new_dist->clear_notes;
3884     $new_dist->clear_streams;
3885     $new_dist->subscription($sub_id);
3886
3887     $e->create_serial_distribution($new_dist) or return $e->die_event;
3888     my $new_dist_id = $e->data->id;
3889
3890     # clone streams
3891     foreach my $stream (@{$dist->streams}) {
3892         my $r = _clone_stream($stream, $new_dist_id, $e);
3893         return $r if $U->event_code($r);
3894     }
3895
3896     # clone distribution notes
3897     foreach my $note (@{$dist->notes}) {
3898         my $r = _clone_distribution_note($note, $new_dist_id, $e);
3899         return $r if $U->event_code($r);
3900     }
3901
3902     return $new_dist_id;
3903 }
3904
3905 sub _clone_subscription_note {
3906     my ($note, $sub_id, $e) = @_;
3907
3908     my $new_note = $note->clone;
3909     $new_note->clear_id;
3910     $new_note->creator($e->requestor->id);
3911     $new_note->create_date("now");
3912     $new_note->subscription($sub_id);
3913
3914     $e->create_serial_subscription_note($new_note) or return $e->die_event;
3915     return $e->data->id;
3916 }
3917
3918 sub _clone_caption_and_pattern {
3919     my ($scap, $sub_id, $e) = @_;
3920
3921     my $new_scap = $scap->clone;
3922     $new_scap->clear_id;
3923     $new_scap->subscription($sub_id);
3924
3925     $e->create_serial_caption_and_pattern($new_scap) or return $e->die_event;
3926     return $e->data->id;
3927 }
3928
3929 sub _clone_distribution_note {
3930     my ($note, $dist_id, $e) = @_;
3931
3932     my $new_note = $note->clone;
3933     $new_note->clear_id;
3934     $new_note->creator($e->requestor->id);
3935     $new_note->create_date("now");
3936     $new_note->distribution($dist_id);
3937
3938     $e->create_serial_distribution_note($new_note) or return $e->die_event;
3939     return $e->data->id;
3940 }
3941
3942 sub _clone_stream {
3943     my ($stream, $dist_id, $e) = @_;
3944
3945     my $new_stream = $stream->clone;
3946     $new_stream->clear_id;
3947     $new_stream->clear_routing_list_users;
3948     $new_stream->distribution($dist_id);
3949
3950     $e->create_serial_stream($new_stream) or return $e->die_event;
3951     my $new_stream_id = $e->data->id;
3952
3953     # clone routing list users
3954     foreach my $user (@{$stream->routing_list_users}) {
3955         my $r = _clone_routing_list_user($user, $new_stream_id, $e);
3956         return $r if $U->event_code($r);
3957     }
3958
3959     return $new_stream_id;
3960 }
3961
3962 sub _clone_routing_list_user {
3963     my ($user, $stream_id, $e) = @_;
3964
3965     my $new_user = $user->clone;
3966     $new_user->clear_id;
3967     $new_user->stream($stream_id);
3968
3969     $e->create_serial_routing_list_user($new_user) or return $e->die_event;
3970     return $e->data->id;
3971 }
3972
3973 __PACKAGE__->register_method(
3974     "method" => "clone_subscription",
3975     "api_name" => "open-ils.serial.subscription.clone",
3976     "signature" => {
3977         "desc" => q{Clone a subscription, including its attending distributions,
3978             streams, captions and patterns, routing list users, distribution
3979             notes and subscription notes. Do not include holdings-specific
3980             things, like issuances, items, units, summaries. Attach the
3981             clone either to the same bib record as the original, or to one
3982             specified by ID.},
3983         "params" => [
3984             {"desc" => "Authtoken", "type" => "string"},
3985             {"desc" => "Subscription ID", "type" => "number"},
3986             {"desc" => "Bib Record ID (optional)", "type" => "number"}
3987         ],
3988         "return" => {
3989             "desc" => "ID of the new subscription", "type" => "number"
3990         }
3991     }
3992 );
3993
3994 sub clone_subscription {
3995     my ($self, $client, $auth, $sub_id, $bib_id) = @_;
3996
3997     my $e = new_editor("authtoken" => $auth, "xact" => 1);
3998     return $e->die_event unless $e->checkauth;
3999
4000     my $sub = $e->retrieve_serial_subscription([
4001         int $sub_id, {
4002             "flesh" => 3,
4003             "flesh_fields" => {
4004                 "ssub" => [qw/distributions notes scaps/],
4005                 "sdist" => [qw/streams notes/],
4006                 "sstr" => ["routing_list_users"]
4007             }
4008         }
4009     ]) or return $e->die_event;
4010
4011     # ADMIN_SERIAL_SUBSCRIPTION will have to be good enough as a
4012     # catch-all permisison for this operation.
4013     return $e->die_event unless
4014         $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
4015
4016     my $result = _clone_subscription($sub, $bib_id, $e);
4017
4018     return $e->die_event($result) if $U->event_code($result);
4019
4020     $e->commit or return $e->die_event;
4021     return $result;
4022 }
4023
4024 __PACKAGE__->register_method(
4025     "method" => "summary_test",
4026     "api_name" => "open-ils.serial.summary_test",
4027     "stream" => 1,
4028     "api_level" => 1,
4029     "argc" => 3
4030 );
4031
4032 # This crummy little test method allows quicker reproduction of certain
4033 # failures (e.g. at item receive time) of the holdings summarization code.
4034 # Pass it an authtoken, an array of issuance IDs, and a single sdist ID
4035 sub summary_test {
4036     my ($self, $conn, $authtoken, $iss_id_list, $sdist_id) = @_;
4037
4038     my $e = new_editor(authtoken => $authtoken, xact => 1);
4039     return $e->die_event unless $e->checkauth;
4040     return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
4041
4042     my @issuances;
4043     foreach my $id (@$iss_id_list) {
4044         my $iss = $e->retrieve_serial_issuance($id) or return $e->die_event;
4045         push @issuances, $iss;
4046     }
4047
4048     my $dist = $e->retrieve_serial_distribution($sdist_id) or return $e->die_event;
4049
4050     $conn->respond(_summarize_contents($e, \@issuances, $dist));
4051     $e->rollback;
4052     return;
4053 }
4054
4055 1;