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