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