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