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