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