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