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