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