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