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