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