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