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