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