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