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