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