]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Serial.pm
Serial note perms and edit support
[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(OpenSRF::Utils::JSON->perl2JSON($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      => 'update_note',
1947     api_name        => 'open-ils.serial.item_note.update',
1948     signature   => q/
1949         Updates or creates an item note
1950         @param authtoken The login session key
1951         @param note The note object to update or create
1952         @return The id of the note object
1953     /
1954 );
1955
1956 __PACKAGE__->register_method(
1957     method      => 'update_note',
1958     api_name        => 'open-ils.serial.subscription_note.update',
1959     signature   => q/
1960         Updates or creates a subscription note
1961         @param authtoken The login session key
1962         @param note The note object to update or create
1963         @return The id of the note object
1964     /
1965 );
1966
1967 __PACKAGE__->register_method(
1968     method      => 'update_note',
1969     api_name        => 'open-ils.serial.distribution_note.update',
1970     signature   => q/
1971         Updates or creates a distribution note
1972         @param authtoken The login session key
1973         @param note The note object to update or create
1974         @return The id of the note object
1975     /
1976 );
1977
1978 sub update_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     if ($type eq 'item') {
1988         my $sitem = $e->retrieve_serial_item([
1989             $note->item, {
1990                 "flesh" => 2, "flesh_fields" => {
1991                     "sitem" => ["stream"], "sstr" => ["distribution"]
1992                 }
1993             }
1994         ]) or return $e->die_event;
1995
1996         return $e->die_event unless $e->allowed(
1997             "ADMIN_SERIAL_ITEM", $sitem->stream->distribution->holding_lib
1998         );
1999     } elsif ($type eq 'distribution') {
2000         my $sdist = $e->retrieve_serial_distribution($note->distribution)
2001             or return $e->die_event;
2002
2003         return $e->die_event unless
2004             $e->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2005     } else { # subscription
2006         my $sub = $e->retrieve_serial_subscription($note->subscription)
2007             or return $e->die_event;
2008
2009         return $e->die_event unless
2010             $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
2011     }
2012
2013     $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
2014     my $method;
2015     if ($note->isnew) {
2016         $note->create_date('now');
2017         $note->creator($e->requestor->id);
2018         $note->clear_id;
2019         $method = "create_serial_${type}_note";
2020     } else {
2021         $method = "update_serial_${type}_note";
2022     }
2023     $e->$method($note) or return $e->event;
2024     $e->commit;
2025     return $note->id;
2026 }
2027
2028 __PACKAGE__->register_method(
2029     method      => 'delete_note',
2030     api_name        =>  'open-ils.serial.item_note.delete',
2031     signature   => q/
2032         Deletes an existing item note
2033         @param authtoken The login session key
2034         @param noteid The id of the note to delete
2035         @return 1 on success - Event otherwise.
2036         /
2037 );
2038
2039 __PACKAGE__->register_method(
2040     method      => 'delete_note',
2041     api_name        =>  'open-ils.serial.subscription_note.delete',
2042     signature   => q/
2043         Deletes an existing subscription note
2044         @param authtoken The login session key
2045         @param noteid The id of the note to delete
2046         @return 1 on success - Event otherwise.
2047         /
2048 );
2049
2050 __PACKAGE__->register_method(
2051     method      => 'delete_note',
2052     api_name        =>  'open-ils.serial.distribution_note.delete',
2053     signature   => q/
2054         Deletes an existing distribution note
2055         @param authtoken The login session key
2056         @param noteid The id of the note to delete
2057         @return 1 on success - Event otherwise.
2058         /
2059 );
2060
2061 sub delete_note {
2062     my( $self, $conn, $authtoken, $noteid ) = @_;
2063
2064     $self->api_name =~ /serial\.(\w*)_note/;
2065     my $type = $1;
2066
2067     my $e = new_editor(xact=>1, authtoken=>$authtoken);
2068     return $e->die_event unless $e->checkauth;
2069
2070     my $method = "retrieve_serial_${type}_note";
2071     my $note = $e->$method([
2072         $noteid,
2073     ]) or return $e->die_event;
2074
2075     if ($type eq 'item') {
2076         my $sitem = $e->retrieve_serial_item([
2077             $note->item, {
2078                 "flesh" => 2, "flesh_fields" => {
2079                     "sitem" => ["stream"], "sstr" => ["distribution"]
2080                 }
2081             }
2082         ]) or return $e->die_event;
2083
2084         return $e->die_event unless $e->allowed(
2085             "ADMIN_SERIAL_ITEM", $sitem->stream->distribution->holding_lib
2086         );
2087     } elsif ($type eq 'distribution') {
2088         my $sdist = $e->retrieve_serial_distribution($note->distribution)
2089             or return $e->die_event;
2090
2091         return $e->die_event unless
2092             $e->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2093     } else { # subscription
2094         my $sub = $e->retrieve_serial_subscription($note->subscription)
2095             or return $e->die_event;
2096
2097         return $e->die_event unless
2098             $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
2099     }
2100
2101     $method = "delete_serial_${type}_note";
2102     $e->$method($note) or return $e->die_event;
2103     $e->commit;
2104     return 1;
2105 }
2106
2107
2108 ##########################################################################
2109 # subscription methods
2110 #
2111 __PACKAGE__->register_method(
2112     method    => 'fleshed_ssub_alter',
2113     api_name  => 'open-ils.serial.subscription.fleshed.batch.update',
2114     api_level => 1,
2115     argc      => 2,
2116     signature => {
2117         desc     => 'Receives an array of one or more subscriptions and updates the database as needed',
2118         'params' => [ {
2119                  name => 'authtoken',
2120                  desc => 'Authtoken for current user session',
2121                  type => 'string'
2122             },
2123             {
2124                  name => 'subscriptions',
2125                  desc => 'Array of fleshed subscriptions',
2126                  type => 'array'
2127             }
2128
2129         ],
2130         'return' => {
2131             desc => 'Returns 1 if successful, event if failed',
2132             type => 'mixed'
2133         }
2134     }
2135 );
2136
2137 sub fleshed_ssub_alter {
2138     my( $self, $conn, $auth, $ssubs ) = @_;
2139     return 1 unless ref $ssubs;
2140     my( $reqr, $evt ) = $U->checkses($auth);
2141     return $evt if $evt;
2142     my $editor = new_editor(requestor => $reqr, xact => 1);
2143     my $override = $self->api_name =~ /override/;
2144
2145     for my $ssub (@$ssubs) {
2146         my $owning_lib_id = ref $ssub->owning_lib ? $ssub->owning_lib->id : $ssub->owning_lib;
2147         return $editor->die_event unless
2148             $editor->allowed("ADMIN_SERIAL_SUBSCRIPTION", $owning_lib_id);
2149
2150         my $ssubid = $ssub->id;
2151
2152         if( $ssub->isdeleted ) {
2153             $evt = _delete_ssub( $editor, $override, $ssub);
2154         } elsif( $ssub->isnew ) {
2155             _cleanse_dates($ssub, ['start_date','end_date']);
2156             $evt = _create_ssub( $editor, $ssub );
2157         } else {
2158             _cleanse_dates($ssub, ['start_date','end_date']);
2159             $evt = _update_ssub( $editor, $override, $ssub );
2160         }
2161     }
2162
2163     if( $evt ) {
2164         $logger->info("fleshed subscription-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2165         $editor->rollback;
2166         return $evt;
2167     }
2168     $logger->debug("subscription-alter: done updating subscription batch");
2169     $editor->commit;
2170     $logger->info("fleshed subscription-alter successfully updated ".scalar(@$ssubs)." subscriptions");
2171     return 1;
2172 }
2173
2174 sub _delete_ssub {
2175     my ($editor, $override, $ssub) = @_;
2176     $logger->info("subscription-alter: delete subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2177     my $sdists = $editor->search_serial_distribution(
2178             { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2179     my $cps = $editor->search_serial_caption_and_pattern(
2180             { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2181     my $sisses = $editor->search_serial_issuance(
2182             { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2183     return OpenILS::Event->new(
2184             'SERIAL_SUBSCRIPTION_NOT_EMPTY', payload => $ssub->id ) if (@$sdists or @$cps or @$sisses);
2185
2186     return $editor->event unless $editor->delete_serial_subscription($ssub);
2187     return 0;
2188 }
2189
2190 sub _create_ssub {
2191     my ($editor, $ssub) = @_;
2192
2193     $logger->info("subscription-alter: new subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2194     return $editor->event unless $editor->create_serial_subscription($ssub);
2195     return 0;
2196 }
2197
2198 sub _update_ssub {
2199     my ($editor, $override, $ssub) = @_;
2200
2201     $logger->info("subscription-alter: retrieving subscription ".$ssub->id);
2202     my $orig_ssub = $editor->retrieve_serial_subscription($ssub->id);
2203
2204     $logger->info("subscription-alter: original subscription ".OpenSRF::Utils::JSON->perl2JSON($orig_ssub));
2205     $logger->info("subscription-alter: updated subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2206     return $editor->event unless $editor->update_serial_subscription($ssub);
2207     return 0;
2208 }
2209
2210 __PACKAGE__->register_method(
2211     method  => "fleshed_serial_subscription_retrieve_batch",
2212     authoritative => 1,
2213     api_name    => "open-ils.serial.subscription.fleshed.batch.retrieve"
2214 );
2215
2216 sub fleshed_serial_subscription_retrieve_batch {
2217     my( $self, $client, $ids ) = @_;
2218 # FIXME: permissions?
2219     $logger->info("Fetching fleshed subscriptions @$ids");
2220     return $U->cstorereq(
2221         "open-ils.cstore.direct.serial.subscription.search.atomic",
2222         { id => $ids },
2223         { flesh => 1,
2224           flesh_fields => {ssub => [ qw/owning_lib notes/ ]}
2225         });
2226 }
2227
2228 __PACKAGE__->register_method(
2229         method  => "retrieve_sub_tree",
2230     authoritative => 1,
2231         api_name        => "open-ils.serial.subscription_tree.retrieve"
2232 );
2233
2234 __PACKAGE__->register_method(
2235         method  => "retrieve_sub_tree",
2236         api_name        => "open-ils.serial.subscription_tree.global.retrieve"
2237 );
2238
2239 sub retrieve_sub_tree {
2240
2241         my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2242
2243         if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2244
2245         $docid = "$docid";
2246
2247         # TODO: permission support
2248         if(!@org_ids and $user_session) {
2249                 my $user_obj = 
2250                         OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2251                         @org_ids = ($user_obj->home_ou);
2252         }
2253
2254         if( $self->api_name =~ /global/ ) {
2255                 return _build_subs_list( { record_entry => $docid } ); # TODO: filter for !deleted, or active?
2256
2257         } else {
2258
2259                 my @all_subs;
2260                 for my $orgid (@org_ids) {
2261                         my $subs = _build_subs_list( 
2262                                         { record_entry => $docid, owning_lib => $orgid } );# TODO: filter for !deleted, or active?
2263                         push( @all_subs, @$subs );
2264                 }
2265                 
2266                 return \@all_subs;
2267         }
2268
2269         return undef;
2270 }
2271
2272 sub _build_subs_list {
2273         my $search_hash = shift;
2274
2275         #$search_hash->{deleted} = 'f';
2276         my $e = new_editor();
2277
2278         my $subs = $e->search_serial_subscription([$search_hash, { 'order_by' => {'ssub' => 'id'} }]);
2279
2280         my @built_subs;
2281
2282         for my $sub (@$subs) {
2283
2284         # TODO: filter on !deleted?
2285                 my $dists = $e->search_serial_distribution(
2286             [{ subscription => $sub->id }, { 'order_by' => {'sdist' => 'label'} }]
2287             );
2288
2289                 #$dists = [ sort { $a->label cmp $b->label } @$dists  ];
2290
2291                 $sub->distributions($dists);
2292         
2293         # TODO: filter on !deleted?
2294                 my $issuances = $e->search_serial_issuance(
2295                         [{ subscription => $sub->id }, { 'order_by' => {'siss' => 'label'} }]
2296             );
2297
2298                 #$issuances = [ sort { $a->label cmp $b->label } @$issuances  ];
2299                 $sub->issuances($issuances);
2300
2301         # TODO: filter on !deleted?
2302                 my $scaps = $e->search_serial_caption_and_pattern(
2303                         [{ subscription => $sub->id }, { 'order_by' => {'scap' => 'id'} }]
2304             );
2305
2306                 #$scaps = [ sort { $a->id cmp $b->id } @$scaps  ];
2307                 $sub->scaps($scaps);
2308                 push( @built_subs, $sub );
2309         }
2310
2311         return \@built_subs;
2312
2313 }
2314
2315 __PACKAGE__->register_method(
2316     method  => "subscription_orgs_for_title",
2317     authoritative => 1,
2318     api_name    => "open-ils.serial.subscription.retrieve_orgs_by_title"
2319 );
2320
2321 sub subscription_orgs_for_title {
2322     my( $self, $client, $record_id ) = @_;
2323
2324     my $subs = $U->simple_scalar_request(
2325         "open-ils.cstore",
2326         "open-ils.cstore.direct.serial.subscription.search.atomic",
2327         { record_entry => $record_id }); # TODO: filter on !deleted?
2328
2329     my $orgs = { map {$_->owning_lib => 1 } @$subs };
2330     return [ keys %$orgs ];
2331 }
2332
2333
2334 ##########################################################################
2335 # distribution methods
2336 #
2337 __PACKAGE__->register_method(
2338     method    => 'fleshed_sdist_alter',
2339     api_name  => 'open-ils.serial.distribution.fleshed.batch.update',
2340     api_level => 1,
2341     argc      => 2,
2342     signature => {
2343         desc     => 'Receives an array of one or more distributions and updates the database as needed',
2344         'params' => [ {
2345                  name => 'authtoken',
2346                  desc => 'Authtoken for current user session',
2347                  type => 'string'
2348             },
2349             {
2350                  name => 'distributions',
2351                  desc => 'Array of fleshed distributions',
2352                  type => 'array'
2353             }
2354
2355         ],
2356         'return' => {
2357             desc => 'Returns 1 if successful, event if failed',
2358             type => 'mixed'
2359         }
2360     }
2361 );
2362
2363 sub fleshed_sdist_alter {
2364     my( $self, $conn, $auth, $sdists ) = @_;
2365     return 1 unless ref $sdists;
2366     my( $reqr, $evt ) = $U->checkses($auth);
2367     return $evt if $evt;
2368     my $editor = new_editor(requestor => $reqr, xact => 1);
2369     my $override = $self->api_name =~ /override/;
2370
2371     for my $sdist (@$sdists) {
2372         my $holding_lib_id = ref $sdist->holding_lib ? $sdist->holding_lib->id : $sdist->holding_lib;
2373         return $editor->die_event unless
2374             $editor->allowed("ADMIN_SERIAL_DISTRIBUTION", $holding_lib_id);
2375
2376         if( $sdist->isdeleted ) {
2377             $evt = _delete_sdist( $editor, $override, $sdist);
2378         } elsif( $sdist->isnew ) {
2379             $evt = _create_sdist( $editor, $sdist );
2380         } else {
2381             $evt = _update_sdist( $editor, $override, $sdist );
2382         }
2383     }
2384
2385     if( $evt ) {
2386         $logger->info("fleshed distribution-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2387         $editor->rollback;
2388         return $evt;
2389     }
2390     $logger->debug("distribution-alter: done updating distribution batch");
2391     $editor->commit;
2392     $logger->info("fleshed distribution-alter successfully updated ".scalar(@$sdists)." distributions");
2393     return 1;
2394 }
2395
2396 sub _delete_sdist {
2397     my ($editor, $override, $sdist) = @_;
2398     $logger->info("distribution-alter: delete distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2399     return $editor->event unless $editor->delete_serial_distribution($sdist);
2400     return 0;
2401 }
2402
2403 sub _create_sdist {
2404     my ($editor, $sdist) = @_;
2405
2406     $logger->info("distribution-alter: new distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2407     return $editor->event unless $editor->create_serial_distribution($sdist);
2408
2409     # create summaries too
2410     my $summary = new Fieldmapper::serial::basic_summary;
2411     $summary->distribution($sdist->id);
2412     $summary->generated_coverage('');
2413     return $editor->event unless $editor->create_serial_basic_summary($summary);
2414     $summary = new Fieldmapper::serial::supplement_summary;
2415     $summary->distribution($sdist->id);
2416     $summary->generated_coverage('');
2417     return $editor->event unless $editor->create_serial_supplement_summary($summary);
2418     $summary = new Fieldmapper::serial::index_summary;
2419     $summary->distribution($sdist->id);
2420     $summary->generated_coverage('');
2421     return $editor->event unless $editor->create_serial_index_summary($summary);
2422
2423     # create a starter stream (TODO: reconsider this)
2424     my $stream = new Fieldmapper::serial::stream;
2425     $stream->distribution($sdist->id);
2426     return $editor->event unless $editor->create_serial_stream($stream);
2427
2428     return 0;
2429 }
2430
2431 sub _update_sdist {
2432     my ($editor, $override, $sdist) = @_;
2433
2434     $logger->info("distribution-alter: retrieving distribution ".$sdist->id);
2435     my $orig_sdist = $editor->retrieve_serial_distribution($sdist->id);
2436
2437     $logger->info("distribution-alter: original distribution ".OpenSRF::Utils::JSON->perl2JSON($orig_sdist));
2438     $logger->info("distribution-alter: updated distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2439     return $editor->event unless $editor->update_serial_distribution($sdist);
2440     return 0;
2441 }
2442
2443 __PACKAGE__->register_method(
2444     method  => "fleshed_serial_distribution_retrieve_batch",
2445     authoritative => 1,
2446     api_name    => "open-ils.serial.distribution.fleshed.batch.retrieve"
2447 );
2448
2449 sub fleshed_serial_distribution_retrieve_batch {
2450     my( $self, $client, $ids ) = @_;
2451 # FIXME: permissions?
2452     $logger->info("Fetching fleshed distributions @$ids");
2453     return $U->cstorereq(
2454         "open-ils.cstore.direct.serial.distribution.search.atomic",
2455         { id => $ids },
2456         { flesh => 1,
2457           flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams / ]}
2458         });
2459 }
2460
2461 __PACKAGE__->register_method(
2462     method  => "retrieve_dist_tree",
2463     authoritative => 1,
2464     api_name    => "open-ils.serial.distribution_tree.retrieve"
2465 );
2466
2467 __PACKAGE__->register_method(
2468     method  => "retrieve_dist_tree",
2469     api_name    => "open-ils.serial.distribution_tree.global.retrieve"
2470 );
2471
2472 sub retrieve_dist_tree {
2473     my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2474
2475     if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2476
2477     $docid = "$docid";
2478
2479     # TODO: permission support
2480     if(!@org_ids and $user_session) {
2481         my $user_obj =
2482             OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2483             @org_ids = ($user_obj->home_ou);
2484     }
2485
2486     my $e = new_editor();
2487
2488     if( $self->api_name =~ /global/ ) {
2489         return $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }},
2490             {   flesh => 1,
2491                 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 / ]},
2492                 order_by => {'sdist' => 'id'},
2493                 'join' => {'ssub' => {}}
2494             }
2495         ]); # TODO: filter for !deleted?
2496
2497     } else {
2498         my @all_dists;
2499         for my $orgid (@org_ids) {
2500             my $dists = $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }, holding_lib => $orgid},
2501                 {   flesh => 1,
2502                     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 / ]},
2503                     order_by => {'sdist' => 'id'},
2504                     'join' => {'ssub' => {}}
2505                 }
2506             ]); # TODO: filter for !deleted?
2507             push( @all_dists, @$dists ) if $dists;
2508         }
2509
2510         return \@all_dists;
2511     }
2512
2513     return undef;
2514 }
2515
2516
2517 __PACKAGE__->register_method(
2518     method  => "distribution_orgs_for_title",
2519     authoritative => 1,
2520     api_name    => "open-ils.serial.distribution.retrieve_orgs_by_title"
2521 );
2522
2523 sub distribution_orgs_for_title {
2524     my( $self, $client, $record_id ) = @_;
2525
2526     my $dists = $U->cstorereq(
2527         "open-ils.cstore.direct.serial.distribution.search.atomic",
2528         { '+ssub' => { record_entry => $record_id } },
2529         { 'join' => {'ssub' => {}} }); # TODO: filter on !deleted?
2530
2531     my $orgs = { map {$_->holding_lib => 1 } @$dists };
2532     return [ keys %$orgs ];
2533 }
2534
2535
2536 ##########################################################################
2537 # caption and pattern methods
2538 #
2539 __PACKAGE__->register_method(
2540     method    => 'scap_alter',
2541     api_name  => 'open-ils.serial.caption_and_pattern.batch.update',
2542     api_level => 1,
2543     argc      => 2,
2544     signature => {
2545         desc     => 'Receives an array of one or more caption and patterns and updates the database as needed',
2546         'params' => [ {
2547                  name => 'authtoken',
2548                  desc => 'Authtoken for current user session',
2549                  type => 'string'
2550             },
2551             {
2552                  name => 'scaps',
2553                  desc => 'Array of caption and patterns',
2554                  type => 'array'
2555             }
2556
2557         ],
2558         'return' => {
2559             desc => 'Returns 1 if successful, event if failed',
2560             type => 'mixed'
2561         }
2562     }
2563 );
2564
2565 sub scap_alter {
2566     my( $self, $conn, $auth, $scaps ) = @_;
2567     return 1 unless ref $scaps;
2568     my( $reqr, $evt ) = $U->checkses($auth);
2569     return $evt if $evt;
2570     my $editor = new_editor(requestor => $reqr, xact => 1);
2571     my $override = $self->api_name =~ /override/;
2572
2573     my %found_ssub_ids;
2574     for my $scap (@$scaps) {
2575         if (!exists($found_ssub_ids{$scap->subscription})) {
2576             my $ssub = $editor->retrieve_serial_subscription($scap->subscription) or return $editor->die_event;
2577             return $editor->die_event unless
2578                 $editor->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $ssub->owning_lib);
2579             $found_ssub_ids{$scap->subscription} = 1;
2580         }
2581
2582         if( $scap->isdeleted ) {
2583             $evt = _delete_scap( $editor, $override, $scap);
2584         } elsif( $scap->isnew ) {
2585             $evt = _create_scap( $editor, $scap );
2586         } else {
2587             $evt = _update_scap( $editor, $override, $scap );
2588         }
2589     }
2590
2591     if( $evt ) {
2592         $logger->info("caption_and_pattern-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2593         $editor->rollback;
2594         return $evt;
2595     }
2596     $logger->debug("caption_and_pattern-alter: done updating caption_and_pattern batch");
2597     $editor->commit;
2598     $logger->info("caption_and_pattern-alter successfully updated ".scalar(@$scaps)." caption_and_patterns");
2599     return 1;
2600 }
2601
2602 sub _delete_scap {
2603     my ($editor, $override, $scap) = @_;
2604     $logger->info("caption_and_pattern-alter: delete caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2605     my $sisses = $editor->search_serial_issuance(
2606             { caption_and_pattern => $scap->id }, { limit => 1 } ); #TODO: 'deleted' support?
2607     return OpenILS::Event->new(
2608             'SERIAL_CAPTION_AND_PATTERN_HAS_ISSUANCES', payload => $scap->id ) if (@$sisses);
2609
2610     return $editor->event unless $editor->delete_serial_caption_and_pattern($scap);
2611     return 0;
2612 }
2613
2614 sub _create_scap {
2615     my ($editor, $scap) = @_;
2616
2617     $logger->info("caption_and_pattern-alter: new caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2618     return $editor->event unless $editor->create_serial_caption_and_pattern($scap);
2619     return 0;
2620 }
2621
2622 sub _update_scap {
2623     my ($editor, $override, $scap) = @_;
2624
2625     $logger->info("caption_and_pattern-alter: retrieving caption_and_pattern ".$scap->id);
2626     my $orig_scap = $editor->retrieve_serial_caption_and_pattern($scap->id);
2627
2628     $logger->info("caption_and_pattern-alter: original caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($orig_scap));
2629     $logger->info("caption_and_pattern-alter: updated caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2630     return $editor->event unless $editor->update_serial_caption_and_pattern($scap);
2631     return 0;
2632 }
2633
2634 __PACKAGE__->register_method(
2635     method  => "serial_caption_and_pattern_retrieve_batch",
2636     authoritative => 1,
2637     api_name    => "open-ils.serial.caption_and_pattern.batch.retrieve"
2638 );
2639
2640 sub serial_caption_and_pattern_retrieve_batch {
2641     my( $self, $client, $ids ) = @_;
2642     $logger->info("Fetching caption_and_patterns @$ids");
2643     return $U->cstorereq(
2644         "open-ils.cstore.direct.serial.caption_and_pattern.search.atomic",
2645         { id => $ids }
2646     );
2647 }
2648
2649 ##########################################################################
2650 # stream methods
2651 #
2652 __PACKAGE__->register_method(
2653     method    => 'sstr_alter',
2654     api_name  => 'open-ils.serial.stream.batch.update',
2655     api_level => 1,
2656     argc      => 2,
2657     signature => {
2658         desc     => 'Receives an array of one or more streams and updates the database as needed',
2659         'params' => [ {
2660                  name => 'authtoken',
2661                  desc => 'Authtoken for current user session',
2662                  type => 'string'
2663             },
2664             {
2665                  name => 'sstrs',
2666                  desc => 'Array of streams',
2667                  type => 'array'
2668             }
2669
2670         ],
2671         'return' => {
2672             desc => 'Returns 1 if successful, event if failed',
2673             type => 'mixed'
2674         }
2675     }
2676 );
2677
2678 sub sstr_alter {
2679     my( $self, $conn, $auth, $sstrs ) = @_;
2680     return 1 unless ref $sstrs;
2681     my( $reqr, $evt ) = $U->checkses($auth);
2682     return $evt if $evt;
2683     my $editor = new_editor(requestor => $reqr, xact => 1);
2684     my $override = $self->api_name =~ /override/;
2685
2686     my %found_sdist_ids;
2687     for my $sstr (@$sstrs) {
2688         if (!exists($found_sdist_ids{$sstr->distribution})) {
2689             my $sdist = $editor->retrieve_serial_distribution($sstr->distribution) or return $editor->die_event;
2690             return $editor->die_event unless
2691                 $editor->allowed("ADMIN_SERIAL_STREAM", $sdist->holding_lib);
2692             $found_sdist_ids{$sstr->distribution} = 1;
2693         }
2694
2695         if( $sstr->isdeleted ) {
2696             $evt = _delete_sstr( $editor, $override, $sstr);
2697         } elsif( $sstr->isnew ) {
2698             $evt = _create_sstr( $editor, $sstr );
2699         } else {
2700             $evt = _update_sstr( $editor, $override, $sstr );
2701         }
2702     }
2703
2704     if( $evt ) {
2705         $logger->info("stream-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2706         $editor->rollback;
2707         return $evt;
2708     }
2709     $logger->debug("stream-alter: done updating stream batch");
2710     $editor->commit;
2711     $logger->info("stream-alter successfully updated ".scalar(@$sstrs)." streams");
2712     return 1;
2713 }
2714
2715 sub _delete_sstr {
2716     my ($editor, $override, $sstr) = @_;
2717     $logger->info("stream-alter: delete stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2718     my $sitems = $editor->search_serial_item(
2719             { stream => $sstr->id }, { limit => 1 } ); #TODO: 'deleted' support?
2720     return OpenILS::Event->new(
2721             'SERIAL_STREAM_HAS_ITEMS', payload => $sstr->id ) if (@$sitems);
2722
2723     return $editor->event unless $editor->delete_serial_stream($sstr);
2724     return 0;
2725 }
2726
2727 sub _create_sstr {
2728     my ($editor, $sstr) = @_;
2729
2730     $logger->info("stream-alter: new stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2731     return $editor->event unless $editor->create_serial_stream($sstr);
2732     return 0;
2733 }
2734
2735 sub _update_sstr {
2736     my ($editor, $override, $sstr) = @_;
2737
2738     $logger->info("stream-alter: retrieving stream ".$sstr->id);
2739     my $orig_sstr = $editor->retrieve_serial_stream($sstr->id);
2740
2741     $logger->info("stream-alter: original stream ".OpenSRF::Utils::JSON->perl2JSON($orig_sstr));
2742     $logger->info("stream-alter: updated stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2743     return $editor->event unless $editor->update_serial_stream($sstr);
2744     return 0;
2745 }
2746
2747 __PACKAGE__->register_method(
2748     method  => "serial_stream_retrieve_batch",
2749     authoritative => 1,
2750     api_name    => "open-ils.serial.stream.batch.retrieve"
2751 );
2752
2753 sub serial_stream_retrieve_batch {
2754     my( $self, $client, $ids ) = @_;
2755     $logger->info("Fetching streams @$ids");
2756     return $U->cstorereq(
2757         "open-ils.cstore.direct.serial.stream.search.atomic",
2758         { id => $ids }
2759     );
2760 }
2761
2762
2763 ##########################################################################
2764 # summary methods
2765 #
2766 __PACKAGE__->register_method(
2767     method    => 'sum_alter',
2768     api_name  => 'open-ils.serial.basic_summary.batch.update',
2769     api_level => 1,
2770     argc      => 2,
2771     signature => {
2772         desc     => 'Receives an array of one or more summaries and updates the database as needed',
2773         'params' => [ {
2774                  name => 'authtoken',
2775                  desc => 'Authtoken for current user session',
2776                  type => 'string'
2777             },
2778             {
2779                  name => 'sbsums',
2780                  desc => 'Array of basic summaries',
2781                  type => 'array'
2782             }
2783
2784         ],
2785         'return' => {
2786             desc => 'Returns 1 if successful, event if failed',
2787             type => 'mixed'
2788         }
2789     }
2790 );
2791
2792 __PACKAGE__->register_method(
2793     method    => 'sum_alter',
2794     api_name  => 'open-ils.serial.supplement_summary.batch.update',
2795     api_level => 1,
2796     argc      => 2,
2797     signature => {
2798         desc     => 'Receives an array of one or more summaries and updates the database as needed',
2799         'params' => [ {
2800                  name => 'authtoken',
2801                  desc => 'Authtoken for current user session',
2802                  type => 'string'
2803             },
2804             {
2805                  name => 'sbsums',
2806                  desc => 'Array of supplement summaries',
2807                  type => 'array'
2808             }
2809
2810         ],
2811         'return' => {
2812             desc => 'Returns 1 if successful, event if failed',
2813             type => 'mixed'
2814         }
2815     }
2816 );
2817
2818 __PACKAGE__->register_method(
2819     method    => 'sum_alter',
2820     api_name  => 'open-ils.serial.index_summary.batch.update',
2821     api_level => 1,
2822     argc      => 2,
2823     signature => {
2824         desc     => 'Receives an array of one or more summaries and updates the database as needed',
2825         'params' => [ {
2826                  name => 'authtoken',
2827                  desc => 'Authtoken for current user session',
2828                  type => 'string'
2829             },
2830             {
2831                  name => 'sbsums',
2832                  desc => 'Array of index summaries',
2833                  type => 'array'
2834             }
2835
2836         ],
2837         'return' => {
2838             desc => 'Returns 1 if successful, event if failed',
2839             type => 'mixed'
2840         }
2841     }
2842 );
2843
2844 sub sum_alter {
2845     my( $self, $conn, $auth, $sums ) = @_;
2846     return 1 unless ref $sums;
2847
2848     $self->api_name =~ /serial\.(\w*)_summary/;
2849     my $type = $1;
2850
2851     my( $reqr, $evt ) = $U->checkses($auth);
2852     return $evt if $evt;
2853     my $editor = new_editor(requestor => $reqr, xact => 1);
2854     my $override = $self->api_name =~ /override/;
2855
2856     my %found_sdist_ids;
2857     for my $sum (@$sums) {
2858         if (!exists($found_sdist_ids{$sum->distribution})) {
2859             my $sdist = $editor->retrieve_serial_distribution($sum->distribution) or return $editor->die_event;
2860             return $editor->die_event unless
2861                 $editor->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2862             $found_sdist_ids{$sum->distribution} = 1;
2863         }
2864
2865         # XXX: (for now, at least) summaries should be created/deleted by the distribution functions
2866         if( $sum->isdeleted ) {
2867             $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2868         } elsif( $sum->isnew ) {
2869             $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2870         } else {
2871             $evt = _update_sum( $editor, $override, $sum, $type );
2872         }
2873     }
2874
2875     if( $evt ) {
2876         $logger->info("${type}_summary-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2877         $editor->rollback;
2878         return $evt;
2879     }
2880     $logger->debug("${type}_summary-alter: done updating ${type}_summary batch");
2881     $editor->commit;
2882     $logger->info("${type}_summary-alter successfully updated ".scalar(@$sums)." ${type}_summaries");
2883     return 1;
2884 }
2885
2886 sub _update_sum {
2887     my ($editor, $override, $sum, $type) = @_;
2888
2889     $logger->info("${type}_summary-alter: retrieving ${type}_summary ".$sum->id);
2890     my $retrieve_method = "retrieve_serial_${type}_summary";
2891     my $orig_sum = $editor->$retrieve_method($sum->id);
2892
2893     $logger->info("${type}_summary-alter: original ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($orig_sum));
2894     $logger->info("${type}_summary-alter: updated ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($sum));
2895     my $update_method = "update_serial_${type}_summary";
2896     return $editor->event unless $editor->$update_method($sum);
2897     return 0;
2898 }
2899
2900 __PACKAGE__->register_method(
2901     method  => "serial_summary_retrieve_batch",
2902     authoritative => 1,
2903     api_name    => "open-ils.serial.basic_summary.batch.retrieve"
2904 );
2905
2906 __PACKAGE__->register_method(
2907     method  => "serial_summary_retrieve_batch",
2908     authoritative => 1,
2909     api_name    => "open-ils.serial.supplement_summary.batch.retrieve"
2910 );
2911
2912 __PACKAGE__->register_method(
2913     method  => "serial_summary_retrieve_batch",
2914     authoritative => 1,
2915     api_name    => "open-ils.serial.index_summary.batch.retrieve"
2916 );
2917
2918 sub serial_summary_retrieve_batch {
2919     my( $self, $client, $ids ) = @_;
2920
2921     $self->api_name =~ /serial\.(\w*)_summary/;
2922     my $type = $1;
2923
2924     $logger->info("Fetching ${type}_summaries @$ids");
2925     return $U->cstorereq(
2926         "open-ils.cstore.direct.serial.".$type."_summary.search.atomic",
2927         { id => $ids }
2928     );
2929 }
2930
2931
2932 ##########################################################################
2933 # other methods
2934 #
2935 __PACKAGE__->register_method(
2936     "method" => "bre_by_identifier",
2937     "api_name" => "open-ils.serial.biblio.record_entry.by_identifier",
2938     "stream" => 1,
2939     "signature" => {
2940         "desc" => "Find instances of biblio.record_entry given a search token" .
2941             " that could be a value for any identifier defined in " .
2942             "config.metabib_field",
2943         "params" => [
2944             {"desc" => "Search token", "type" => "string"},
2945             {"desc" => "Options: require_subscriptions, add_mvr, is_actual_id" .
2946                 ", id_list (all boolean)", "type" => "object"}
2947         ],
2948         "return" => {
2949             "desc" => "Any matching BREs, or if the add_mvr option is true, " .
2950                 "objects with a 'bre' key/value pair, and an 'mvr' " .
2951                 "key-value pair.  BREs have subscriptions fleshed on.",
2952             "type" => "object"
2953         }
2954     }
2955 );
2956
2957 sub bre_by_identifier {
2958     my ($self, $client, $term, $options) = @_;
2959
2960     return new OpenILS::Event("BAD_PARAMS") unless $term;
2961
2962     $options ||= {};
2963     my $e = new_editor();
2964
2965     my @ids;
2966
2967     if ($options->{"is_actual_id"}) {
2968         @ids = ($term);
2969     } else {
2970         my $cmf =
2971             $e->search_config_metabib_field({"field_class" => "identifier"})
2972                 or return $e->die_event;
2973
2974         my @identifiers = map { $_->name } @$cmf;
2975         my $query = join(" || ", map { "id|$_: $term" } @identifiers);
2976
2977         my $search = create OpenSRF::AppSession("open-ils.search");
2978         my $search_result = $search->request(
2979             "open-ils.search.biblio.multiclass.query.staff", {}, $query
2980         )->gather(1);
2981         $search->disconnect;
2982
2983         # Un-nest results. They tend to look like [[1],[2],[3]] for some reason.
2984         @ids = map { @{$_} } @{$search_result->{"ids"}};
2985
2986         unless (@ids) {
2987             $e->disconnect;
2988             return undef;
2989         }
2990
2991         if ($options->{"id_list"}) {
2992             $e->disconnect;
2993             $client->respond($_) foreach (@ids);
2994             return undef;
2995         }
2996     }
2997
2998     my $bre = $e->search_biblio_record_entry([
2999         {"id" => \@ids}, {
3000             "flesh" => 2, "flesh_fields" => {
3001                 "bre" => ["subscriptions"],
3002                 "ssub" => ["owning_lib"]
3003             }
3004         }
3005     ]) or return $e->die_event;
3006
3007     if (@$bre && $options->{"require_subscriptions"}) {
3008         $bre = [ grep { @{$_->subscriptions} } @$bre ];
3009     }
3010
3011     $e->disconnect;
3012
3013     if (@$bre) { # re-evaluate after possible grep
3014         if ($options->{"add_mvr"}) {
3015             $client->respond(
3016                 {"bre" => $_, "mvr" => _get_mvr($_->id)}
3017             ) foreach (@$bre);
3018         } else {
3019             $client->respond($_) foreach (@$bre);
3020         }
3021     }
3022
3023     undef;
3024 }
3025
3026 __PACKAGE__->register_method(
3027     "method" => "get_items_by",
3028     "api_name" => "open-ils.serial.items.receivable.by_subscription",
3029     "stream" => 1,
3030     "signature" => {
3031         "desc" => "Return all receivable items under a given subscription",
3032         "params" => [
3033             {"desc" => "Authtoken", "type" => "string"},
3034             {"desc" => "Subscription ID", "type" => "number"},
3035         ],
3036         "return" => {
3037             "desc" => "All receivable items under a given subscription",
3038             "type" => "object", "class" => "sitem"
3039         }
3040     }
3041 );
3042
3043 __PACKAGE__->register_method(
3044     "method" => "get_items_by",
3045     "api_name" => "open-ils.serial.items.receivable.by_issuance",
3046     "stream" => 1,
3047     "signature" => {
3048         "desc" => "Return all receivable items under a given issuance",
3049         "params" => [
3050             {"desc" => "Authtoken", "type" => "string"},
3051             {"desc" => "Issuance ID", "type" => "number"},
3052         ],
3053         "return" => {
3054             "desc" => "All receivable items under a given issuance",
3055             "type" => "object", "class" => "sitem"
3056         }
3057     }
3058 );
3059
3060 __PACKAGE__->register_method(
3061     "method" => "get_items_by",
3062     "api_name" => "open-ils.serial.items.by_issuance",
3063     "stream" => 1,
3064     "signature" => {
3065         "desc" => "Return all items under a given issuance",
3066         "params" => [
3067             {"desc" => "Authtoken", "type" => "string"},
3068             {"desc" => "Issuance ID", "type" => "number"},
3069         ],
3070         "return" => {
3071             "desc" => "All items under a given issuance",
3072             "type" => "object", "class" => "sitem"
3073         }
3074     }
3075 );
3076
3077 sub get_items_by {
3078     my ($self, $client, $auth, $term, $opts)  = @_;
3079
3080     # Not to be used in the json_query, but after limiting by perm check.
3081     $opts = {} unless ref $opts eq "HASH";
3082     $opts->{"limit"} ||= 10000;    # some existing users may want all results
3083     $opts->{"offset"} ||= 0;
3084     $opts->{"limit"} = int($opts->{"limit"});
3085     $opts->{"offset"} = int($opts->{"offset"});
3086
3087     my $e = new_editor("authtoken" => $auth);
3088     return $e->die_event unless $e->checkauth;
3089
3090     my $by = ($self->api_name =~ /by_(\w+)$/)[0];
3091     my $receivable = ($self->api_name =~ /receivable/);
3092
3093     my %where = (
3094         "issuance" => {"issuance" => $term},
3095         "subscription" => {"+siss" => {"subscription" => $term}}
3096     );
3097
3098     my $item_rows = $e->json_query(
3099         {
3100             "select" => {"sitem" => ["id"], "sdist" => ["holding_lib"]},
3101             "from" => {
3102                 "sitem" => {
3103                     "siss" => {},
3104                     "sstr" => {"join" => {"sdist" => {}}}
3105                 }
3106             },
3107             "where" => {
3108                 %{$where{$by}}, $receivable ? ("date_received" => undef) : ()
3109             },
3110             "order_by" => {"sitem" => ["id"]}
3111         }
3112     ) or return $e->die_event;
3113
3114     return undef unless @$item_rows;
3115
3116     my $skipped = 0;
3117     my $returned = 0;
3118     foreach (@$item_rows) {
3119         last if $returned >= $opts->{"limit"};
3120         next unless $e->allowed("RECEIVE_SERIAL", $_->{"holding_lib"});
3121         if ($skipped < $opts->{"offset"}) {
3122             $skipped++;
3123             next;
3124         }
3125
3126         $client->respond(
3127             $e->retrieve_serial_item([
3128                 $_->{"id"}, {
3129                     "flesh" => 3,
3130                     "flesh_fields" => {
3131                         "sitem" => [qw/stream issuance unit creator editor/],
3132                         "sstr" => ["distribution"],
3133                         "sdist" => ["holding_lib"]
3134                     }
3135                 }
3136             ])
3137         );
3138         $returned++;
3139     }
3140
3141     $e->disconnect;
3142     undef;
3143 }
3144
3145 __PACKAGE__->register_method(
3146     "method" => "get_receivable_issuances",
3147     "api_name" => "open-ils.serial.issuances.receivable",
3148     "stream" => 1,
3149     "signature" => {
3150         "desc" => "Return all issuances with receivable items given " .
3151             "a subscription ID",
3152         "params" => [
3153             {"desc" => "Authtoken", "type" => "string"},
3154             {"desc" => "Subscription ID", "type" => "number"},
3155         ],
3156         "return" => {
3157             "desc" => "All issuances with receivable items " .
3158                 "(but not the items themselves)", "type" => "object"
3159         }
3160     }
3161 );
3162
3163 sub get_receivable_issuances {
3164     my ($self, $client, $auth, $sub_id) = @_;
3165
3166     my $e = new_editor("authtoken" => $auth);
3167     return $e->die_event unless $e->checkauth;
3168
3169     # XXX permissions
3170
3171     my $issuance_ids = $e->json_query({
3172         "select" => {
3173             "siss" => [
3174                 {"transform" => "distinct", "column" => "id"},
3175                 "date_published"
3176             ]
3177         },
3178         "from" => {"siss" => "sitem"},
3179         "where" => {
3180             "subscription" => $sub_id,
3181             "+sitem" => {"date_received" => undef}
3182         },
3183         "order_by" => {
3184             "siss" => {"date_published" => {"direction" => "asc"}}
3185         }
3186
3187     }) or return $e->die_event;
3188
3189     $client->respond($e->retrieve_serial_issuance($_->{"id"}))
3190         foreach (@$issuance_ids);
3191
3192     $e->disconnect;
3193     undef;
3194 }
3195
3196
3197 __PACKAGE__->register_method(
3198     "method" => "get_routing_list_users",
3199     "api_name" => "open-ils.serial.routing_list_users.fleshed_and_ordered",
3200     "stream" => 1,
3201     "signature" => {
3202         "desc" => "Return all routing list users with reader fleshed " .
3203             "(with card and home_ou) for a given stream ID, sorted by pos",
3204         "params" => [
3205             {"desc" => "Authtoken", "type" => "string"},
3206             {"desc" => "Stream ID (int or array of ints)", "type" => "mixed"},
3207         ],
3208         "return" => {
3209             "desc" => "Stream of routing list users", "type" => "object",
3210                 "class" => "srlu"
3211         }
3212     }
3213 );
3214
3215 sub get_routing_list_users {
3216     my ($self, $client, $auth, $stream_id) = @_;
3217
3218     my $e = new_editor("authtoken" => $auth);
3219     return $e->die_event unless $e->checkauth;
3220
3221     my $users = $e->search_serial_routing_list_user([
3222         {"stream" => $stream_id}, {
3223             "order_by" => {"srlu" => "pos"},
3224             "flesh" => 2,
3225             "flesh_fields" => {
3226                 "srlu" => [qw/reader stream/],
3227                 "au" => [qw/card home_ou/],
3228                 "sstr" => ["distribution"]
3229             }
3230         }
3231     ]) or return $e->die_event;
3232
3233     return undef unless @$users;
3234
3235     # The ADMIN_SERIAL_STREAM permission is used simply to avoid the
3236     # need for any new permission.  The context OU will be the same
3237     # for every result of the above query, so we need only check once.
3238     return $e->die_event unless $e->allowed(
3239         "ADMIN_SERIAL_STREAM", $users->[0]->stream->distribution->holding_lib
3240     );
3241
3242     $e->disconnect;
3243
3244     my @users = map { $_->stream($_->stream->id); $_ } @$users;
3245     @users = sort { $a->stream cmp $b->stream } @users if
3246         ref $stream_id eq "ARRAY";
3247
3248     $client->respond($_) for @users;
3249
3250     undef;
3251 }
3252
3253
3254 __PACKAGE__->register_method(
3255     "method" => "replace_routing_list_users",
3256     "api_name" => "open-ils.serial.routing_list_users.replace",
3257     "signature" => {
3258         "desc" => "Replace all routing list users on the specified streams " .
3259             "with those in the list argument",
3260         "params" => [
3261             {"desc" => "Authtoken", "type" => "string"},
3262             {"desc" => "List of srlu objects", "type" => "array"},
3263         ],
3264         "return" => {
3265             "desc" => "event on failure, undef on success"
3266         }
3267     }
3268 );
3269
3270 sub replace_routing_list_users {
3271     my ($self, $client, $auth, $users) = @_;
3272
3273     return undef unless ref $users eq "ARRAY";
3274
3275     if (grep { ref $_ ne "Fieldmapper::serial::routing_list_user" } @$users) {
3276         return new OpenILS::Event("BAD_PARAMS", "note" => "Only srlu objects");
3277     }
3278
3279     my $e = new_editor("authtoken" => $auth, "xact" => 1);
3280     return $e->die_event unless $e->checkauth;
3281
3282     my %streams_ok = ();
3283     my $pos = 0;
3284
3285     foreach my $user (@$users) {
3286         unless (exists $streams_ok{$user->stream}) {
3287             my $stream = $e->retrieve_serial_stream([
3288                 $user->stream, {
3289                     "flesh" => 1,
3290                     "flesh_fields" => {"sstr" => ["distribution"]}
3291                 }
3292             ]) or return $e->die_event;
3293             $e->allowed(
3294                 "ADMIN_SERIAL_STREAM", $stream->distribution->holding_lib
3295             ) or return $e->die_event;
3296
3297             my $to_delete = $e->search_serial_routing_list_user(
3298                 {"stream" => $user->stream}
3299             ) or return $e->die_event;
3300
3301             $logger->info(
3302                 "Deleting srlu: [" .
3303                 join(", ", map { $_->id; } @$to_delete) .
3304                 "]"
3305             );
3306
3307             foreach (@$to_delete) {
3308                 $e->delete_serial_routing_list_user($_) or
3309                     return $e->die_event;
3310             }
3311
3312             $streams_ok{$user->stream} = 1;
3313         }
3314
3315         next if $user->isdeleted;
3316
3317         $user->clear_id;
3318         $user->pos($pos++);
3319         $e->create_serial_routing_list_user($user) or return $e->die_event;
3320     }
3321
3322     $e->commit or return $e->die_event;
3323     undef;
3324 }
3325
3326 __PACKAGE__->register_method(
3327     "method" => "get_records_with_marc_85x",
3328     "api_name"=>"open-ils.serial.caption_and_pattern.find_legacy_by_bib_record",
3329     "stream" => 1,
3330     "signature" => {
3331         "desc" => "Return the specified BRE itself and/or any related SRE ".
3332             "whenever they have 853-855 tags",
3333         "params" => [
3334             {"desc" => "Authtoken", "type" => "string"},
3335             {"desc" => "bib record ID", "type" => "number"},
3336         ],
3337         "return" => {
3338             "desc" => "objects, either bre or sre", "type" => "object"
3339         }
3340     }
3341 );
3342
3343 sub get_records_with_marc_85x { # specifically, 853-855
3344     my ($self, $client, $auth, $bre_id) = @_;
3345
3346     my $e = new_editor("authtoken" => $auth);
3347     return $e->die_event unless $e->checkauth;
3348
3349     my $bre = $e->search_biblio_record_entry([
3350         {"id" => $bre_id, "deleted" => "f"}, {
3351             "flesh" => 1,
3352             "flesh_fields" => {"bre" => [qw/creator editor owner/]}
3353         }
3354     ]) or return $e->die_event;
3355
3356     return undef unless @$bre;
3357     $bre = $bre->[0];
3358
3359     my $record = MARC::Record->new_from_xml($bre->marc);
3360     $client->respond($bre) if $record->field("85[3-5]");
3361     # XXX Is passing a regex to ->field() an abuse of MARC::Record ?
3362
3363     my $sres = $e->search_serial_record_entry([
3364         {"record" => $bre_id, "deleted" => "f"}, {
3365             "flesh" => 1,
3366             "flesh_fields" => {"sre" => [qw/creator editor owning_lib/]}
3367         }
3368     ]) or return $e->die_event;
3369
3370     $e->disconnect;
3371
3372     foreach my $sre (@$sres) {
3373         $client->respond($sre) if
3374             MARC::Record->new_from_xml($sre->marc)->field("85[3-5]");
3375     }
3376
3377     undef;
3378 }
3379
3380 __PACKAGE__->register_method(
3381     "method" => "create_scaps_from_marcxml",
3382     "api_name" => "open-ils.serial.caption_and_pattern.create_from_records",
3383     "stream" => 1,
3384     "signature" => {
3385         "desc" => "Create caption and pattern objects from 853-855 tags " .
3386             "in MARCXML documents",
3387         "params" => [
3388             {"desc" => "Authtoken", "type" => "string"},
3389             {"desc" => "Subscription ID", "type" => "number"},
3390             {"desc" => "list of MARCXML documents as strings",
3391                 "type" => "array"},
3392         ],
3393         "return" => {
3394             "desc" => "Newly created caption and pattern objects",
3395             "type" => "object", "class" => "scap"
3396         }
3397     }
3398 );
3399
3400 sub create_scaps_from_marcxml {
3401     my ($self, $client, $auth, $sub_id, $docs) = @_;
3402
3403     return undef unless ref $docs eq "ARRAY";
3404
3405     my $e = new_editor("authtoken" => $auth, "xact" => 1);
3406     return $e->die_event unless $e->checkauth;
3407
3408     # Retrieve the subscription just for perm checking (whether we can create
3409     # scaps at the owning lib).
3410     my $sub = $e->retrieve_serial_subscription($sub_id) or return $e->die_event;
3411     return $e->die_event unless
3412         $e->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $sub->owning_lib);
3413
3414     foreach my $record (map { MARC::Record->new_from_xml($_) } @$docs) {
3415         foreach my $field ($record->field("85[3-5]")) {
3416             my $scap = new Fieldmapper::serial::caption_and_pattern;
3417             $scap->subscription($sub_id);
3418             $scap->type($MFHD_NAMES_BY_TAG{$field->tag});
3419             $scap->pattern_code(
3420                 OpenSRF::Utils::JSON->perl2JSON(
3421                     [ $field->indicator(1), $field->indicator(2),
3422                         map { @$_ } $field->subfields ] # flattens nested array
3423                 )
3424             );
3425             $e->create_serial_caption_and_pattern($scap) or
3426                 return $e->die_event;
3427             $client->respond($e->data);
3428         }
3429     }
3430
3431     $e->commit or return $e->die_event;
3432     undef;
3433 }
3434
3435 # All these _clone_foo() functions could possibly have been consolidated into
3436 # one clever function, but it's faster to get things working this way.
3437 sub _clone_subscription {
3438     my ($sub, $bib_id, $e) = @_;
3439
3440     # clone sub itself
3441     my $new_sub = $sub->clone;
3442     $new_sub->record_entry(int $bib_id) if $bib_id;
3443     $new_sub->clear_id;
3444     $new_sub->clear_distributions;
3445     $new_sub->clear_notes;
3446     $new_sub->clear_scaps;
3447
3448     $e->create_serial_subscription($new_sub) or return $e->die_event;
3449
3450     my $new_sub_id = $e->data->id;
3451     # clone dists
3452     foreach my $dist (@{$sub->distributions}) {
3453         my $r = _clone_distribution($dist, $new_sub_id, $e);
3454         return $r if $U->event_code($r);
3455     }
3456
3457     # clone sub notes
3458     foreach my $note (@{$sub->notes}) {
3459         my $r = _clone_subscription_note($note, $new_sub_id, $e);
3460         return $r if $U->event_code($r);
3461     }
3462
3463     # clone scaps
3464     foreach my $scap (@{$sub->scaps}) {
3465         my $r = _clone_caption_and_pattern($scap, $new_sub_id, $e);
3466         return $r if $U->event_code($r);
3467     }
3468
3469     return $new_sub_id;
3470 }
3471
3472 sub _clone_distribution {
3473     my ($dist, $sub_id, $e) = @_;
3474
3475     my $new_dist = $dist->clone;
3476     $new_dist->clear_id;
3477     $new_dist->clear_notes;
3478     $new_dist->clear_streams;
3479     $new_dist->subscription($sub_id);
3480
3481     $e->create_serial_distribution($new_dist) or return $e->die_event;
3482     my $new_dist_id = $e->data->id;
3483
3484     # clone streams
3485     foreach my $stream (@{$dist->streams}) {
3486         my $r = _clone_stream($stream, $new_dist_id, $e);
3487         return $r if $U->event_code($r);
3488     }
3489
3490     # clone distribution notes
3491     foreach my $note (@{$dist->notes}) {
3492         my $r = _clone_distribution_note($note, $new_dist_id, $e);
3493         return $r if $U->event_code($r);
3494     }
3495
3496     return $new_dist_id;
3497 }
3498
3499 sub _clone_subscription_note {
3500     my ($note, $sub_id, $e) = @_;
3501
3502     my $new_note = $note->clone;
3503     $new_note->clear_id;
3504     $new_note->creator($e->requestor->id);
3505     $new_note->create_date("now");
3506     $new_note->subscription($sub_id);
3507
3508     $e->create_serial_subscription_note($new_note) or return $e->die_event;
3509     return $e->data->id;
3510 }
3511
3512 sub _clone_caption_and_pattern {
3513     my ($scap, $sub_id, $e) = @_;
3514
3515     my $new_scap = $scap->clone;
3516     $new_scap->clear_id;
3517     $new_scap->subscription($sub_id);
3518
3519     $e->create_serial_caption_and_pattern($new_scap) or return $e->die_event;
3520     return $e->data->id;
3521 }
3522
3523 sub _clone_distribution_note {
3524     my ($note, $dist_id, $e) = @_;
3525
3526     my $new_note = $note->clone;
3527     $new_note->clear_id;
3528     $new_note->creator($e->requestor->id);
3529     $new_note->create_date("now");
3530     $new_note->distribution($dist_id);
3531
3532     $e->create_serial_distribution_note($new_note) or return $e->die_event;
3533     return $e->data->id;
3534 }
3535
3536 sub _clone_stream {
3537     my ($stream, $dist_id, $e) = @_;
3538
3539     my $new_stream = $stream->clone;
3540     $new_stream->clear_id;
3541     $new_stream->clear_routing_list_users;
3542     $new_stream->distribution($dist_id);
3543
3544     $e->create_serial_stream($new_stream) or return $e->die_event;
3545     my $new_stream_id = $e->data->id;
3546
3547     # clone routing list users
3548     foreach my $user (@{$stream->routing_list_users}) {
3549         my $r = _clone_routing_list_user($user, $new_stream_id, $e);
3550         return $r if $U->event_code($r);
3551     }
3552
3553     return $new_stream_id;
3554 }
3555
3556 sub _clone_routing_list_user {
3557     my ($user, $stream_id, $e) = @_;
3558
3559     my $new_user = $user->clone;
3560     $new_user->clear_id;
3561     $new_user->stream($stream_id);
3562
3563     $e->create_serial_routing_list_user($new_user) or return $e->die_event;
3564     return $e->data->id;
3565 }
3566
3567 __PACKAGE__->register_method(
3568     "method" => "clone_subscription",
3569     "api_name" => "open-ils.serial.subscription.clone",
3570     "signature" => {
3571         "desc" => q{Clone a subscription, including its attending distributions,
3572             streams, captions and patterns, routing list users, distribution
3573             notes and subscription notes. Do not include holdings-specific
3574             things, like issuances, items, units, summaries. Attach the
3575             clone either to the same bib record as the original, or to one
3576             specified by ID.},
3577         "params" => [
3578             {"desc" => "Authtoken", "type" => "string"},
3579             {"desc" => "Subscription ID", "type" => "number"},
3580             {"desc" => "Bib Record ID (optional)", "type" => "number"}
3581         ],
3582         "return" => {
3583             "desc" => "ID of the new subscription", "type" => "number"
3584         }
3585     }
3586 );
3587
3588 sub clone_subscription {
3589     my ($self, $client, $auth, $sub_id, $bib_id) = @_;
3590
3591     my $e = new_editor("authtoken" => $auth, "xact" => 1);
3592     return $e->die_event unless $e->checkauth;
3593
3594     my $sub = $e->retrieve_serial_subscription([
3595         int $sub_id, {
3596             "flesh" => 3,
3597             "flesh_fields" => {
3598                 "ssub" => [qw/distributions notes scaps/],
3599                 "sdist" => [qw/streams notes/],
3600                 "sstr" => ["routing_list_users"]
3601             }
3602         }
3603     ]) or return $e->die_event;
3604
3605     # ADMIN_SERIAL_SUBSCRIPTION will have to be good enough as a
3606     # catch-all permisison for this operation.
3607     return $e->die_event unless
3608         $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
3609
3610     my $result = _clone_subscription($sub, $bib_id, $e);
3611
3612     return $e->die_event($result) if $U->event_code($result);
3613
3614     $e->commit or return $e->die_event;
3615     return $result;
3616 }
3617
3618 1;