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.
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.
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.
19 OpenILS::Application::Serial - Performs serials-related tasks such as receiving issues and generating predictions
31 Dan Wells, dbw2@calvin.edu
35 package OpenILS::Application::Serial;
41 use OpenILS::Application;
42 use base qw/OpenILS::Application/;
43 use OpenILS::Application::AppUtils;
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');
54 use OpenILS::Application::Serial::OPAC;
56 my $U = 'OpenILS::Application::AppUtils';
57 my @MFHD_NAMES = ('basic','supplement','index');
58 my %MFHD_NAMES_BY_TAG = ( '853' => $MFHD_NAMES[0],
59 '863' => $MFHD_NAMES[0],
60 '854' => $MFHD_NAMES[1],
61 '864' => $MFHD_NAMES[1],
62 '855' => $MFHD_NAMES[2],
63 '865' => $MFHD_NAMES[2] );
64 my %MFHD_TAGS_BY_NAME = ( $MFHD_NAMES[0] => '853',
65 $MFHD_NAMES[1] => '854',
66 $MFHD_NAMES[2] => '855');
67 my $_strp_date = new DateTime::Format::Strptime(pattern => '%F');
69 # helper method for conforming dates to ISO8601
74 foreach my $field (@$fields) {
75 $item->$field(OpenSRF::Utils::clense_ISO8601($item->$field)) if $item->$field;
83 "open-ils.search.biblio.record.mods_slim.retrieve",
89 ##########################################################################
92 __PACKAGE__->register_method(
93 method => "create_item_safely",
94 api_name => "open-ils.serial.item.create",
99 desc => q/Creates any number of items, respecting only a few of the
100 submitted fields, as the user shouldn't be able to freely set certain
103 {name=> "authtoken", desc => "Authtoken for current user session",
105 {name => "item", desc => "serial item",
106 type => "object", class => "sitem"},
108 desc => "optional: how many items to make " .
109 "(default 1; 1-100 permitted)",
113 desc => "created items (a stream of them)",
114 type => "object", class => "sitem"
118 __PACKAGE__->register_method(
119 method => "update_item_safely",
120 api_name => "open-ils.serial.item.update",
125 desc => q/Edit a serial item, respecting only a few of the
126 submitted fields, as the user shouldn't be able to freely set certain
129 {name=> "authtoken", desc => "Authtoken for current user session",
131 {name => "item", desc => "serial item",
132 type => "object", class => "sitem"},
135 desc => "created item", type => "object", class => "sitem"
140 sub _set_safe_item_fields {
143 my $requestor_id = shift;
144 # extra fields remain in @_
146 $dest->edit_date("now");
147 $dest->editor($requestor_id);
149 my @fields = qw/date_expected date_received status/;
151 for my $field (@fields, @_) {
152 $dest->$field($source->$field);
156 sub update_item_safely {
157 my ($self, $client, $auth, $item) = @_;
159 my $e = new_editor("xact" => 1, "authtoken" => $auth);
160 $e->checkauth or return $e->die_event;
162 my $orig = $e->retrieve_serial_item([
164 "flesh" => 2, "flesh_fields" => {
165 "sitem" => ["stream"], "sstr" => ["distribution"]
168 ]) or return $e->die_event;
170 return $e->die_event unless $e->allowed(
171 "ADMIN_SERIAL_ITEM", $orig->stream->distribution->holding_lib
174 _set_safe_item_fields($orig, $item, $e->requestor->id);
175 $e->update_serial_item($orig) or return $e->die_event;
177 $client->respond($e->retrieve_serial_item($item->id));
178 $e->commit or return $e->die_event;
182 sub create_item_safely {
183 my ($self, $client, $auth, $item, $count) = @_;
187 return new OpenILS::Event(
188 "BAD_PARAMS", note => "Count should be from 1 to 100"
189 ) unless $count >= 1 and $count <= 100;
191 my $e = new_editor("xact" => 1, "authtoken" => $auth);
192 $e->checkauth or return $e->die_event;
194 my $stream = $e->retrieve_serial_stream([
196 "flesh" => 1, "flesh_fields" => {"sstr" => ["distribution"]}
198 ]) or return $e->die_event;
200 return $e->die_event unless $e->allowed(
201 "ADMIN_SERIAL_ITEM", $stream->distribution->holding_lib
204 for (my $i = 0; $i < $count; $i++) {
205 my $actual = new Fieldmapper::serial::item;
206 $actual->creator($e->requestor->id);
207 _set_safe_item_fields(
208 $actual, $item, $e->requestor->id, "issuance", "stream"
211 $e->create_serial_item($actual) or return $e->die_event;
212 $client->respond($e->data);
215 $e->commit or return $e->die_event;
219 __PACKAGE__->register_method(
220 method => 'fleshed_item_alter',
221 api_name => 'open-ils.serial.item.fleshed.batch.update',
225 desc => 'Receives an array of one or more items and updates the database as needed',
228 desc => 'Authtoken for current user session',
233 desc => 'Array of fleshed items',
239 desc => 'Returns 1 if successful, event if failed',
245 sub fleshed_item_alter {
246 my( $self, $conn, $auth, $items ) = @_;
247 return 1 unless ref $items;
248 my( $reqr, $evt ) = $U->checkses($auth);
250 my $editor = new_editor(requestor => $reqr, xact => 1);
251 my $override = $self->api_name =~ /override/;
255 for my $item (@$items) {
256 my $sstr_id = ref $item->stream ? $item->stream->id : $item->stream;
257 if (!exists($found_sstr_ids{$sstr_id})) {
259 if (ref $item->stream) {
260 $sstr = $item->stream;
262 $sstr = $editor->retrieve_serial_stream($item->stream) or return $editor->die_event;
264 if (!exists($found_sdist_ids{$sstr->distribution})) {
265 my $sdist = $editor->retrieve_serial_distribution($sstr->distribution) or return $editor->die_event;
266 return $editor->die_event unless
267 $editor->allowed("ADMIN_SERIAL_STREAM", $sdist->holding_lib);
268 $found_sdist_ids{$sstr->distribution} = 1;
270 $found_sstr_ids{$sstr_id} = 1;
273 $item->editor($editor->requestor->id);
274 $item->edit_date('now');
276 if( $item->isdeleted ) {
277 $evt = _delete_sitem( $editor, $override, $item);
278 } elsif( $item->isnew ) {
279 # TODO: reconsider this
280 # if the item has a new issuance, create the issuance first
281 if (ref $item->issuance eq 'Fieldmapper::serial::issuance' and $item->issuance->isnew) {
282 fleshed_issuance_alter($self, $conn, $auth, [$item->issuance]);
284 _cleanse_dates($item, ['date_expected','date_received']);
285 $evt = _create_sitem( $editor, $item );
287 _cleanse_dates($item, ['date_expected','date_received']);
288 $evt = _update_sitem( $editor, $override, $item );
293 $logger->info("fleshed item-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
297 $logger->debug("item-alter: done updating item batch");
299 $logger->info("fleshed item-alter successfully updated ".scalar(@$items)." items");
304 my ($editor, $override, $item) = @_;
305 $logger->info("item-alter: delete item ".OpenSRF::Utils::JSON->perl2JSON($item));
306 return $editor->event unless $editor->delete_serial_item($item);
311 my ($editor, $item) = @_;
313 $item->creator($editor->requestor->id);
314 $item->create_date('now');
316 $logger->info("item-alter: new item ".OpenSRF::Utils::JSON->perl2JSON($item));
317 return $editor->event unless $editor->create_serial_item($item);
322 my ($editor, $override, $item) = @_;
324 $logger->info("item-alter: retrieving item ".$item->id);
325 my $orig_item = $editor->retrieve_serial_item($item->id);
327 $logger->info("item-alter: original item ".OpenSRF::Utils::JSON->perl2JSON($orig_item));
328 $logger->info("item-alter: updated item ".OpenSRF::Utils::JSON->perl2JSON($item));
329 return $editor->event unless $editor->update_serial_item($item);
333 __PACKAGE__->register_method(
334 method => "fleshed_serial_item_retrieve_batch",
336 api_name => "open-ils.serial.item.fleshed.batch.retrieve"
339 sub fleshed_serial_item_retrieve_batch {
340 my( $self, $client, $ids ) = @_;
341 # FIXME: permissions?
342 $logger->info("Fetching fleshed serial items @$ids");
343 return $U->cstorereq(
344 "open-ils.cstore.direct.serial.item.search.atomic",
347 flesh_fields => {sitem => [ qw/issuance creator editor stream unit notes/ ], sstr => ["distribution"], sunit => ["call_number"], siss => [qw/creator editor subscription/]}
352 ##########################################################################
355 __PACKAGE__->register_method(
356 method => 'fleshed_issuance_alter',
357 api_name => 'open-ils.serial.issuance.fleshed.batch.update',
361 desc => 'Receives an array of one or more issuances and updates the database as needed',
364 desc => 'Authtoken for current user session',
369 desc => 'Array of fleshed issuances',
375 desc => 'Returns 1 if successful, event if failed',
381 sub fleshed_issuance_alter {
382 my( $self, $conn, $auth, $issuances ) = @_;
383 return 1 unless ref $issuances;
384 my( $reqr, $evt ) = $U->checkses($auth);
386 my $editor = new_editor(requestor => $reqr, xact => 1);
387 my $override = $self->api_name =~ /override/;
390 for my $issuance (@$issuances) {
391 my $ssub_id = ref $issuance->subscription ? $issuance->subscription->id : $issuance->subscription;
392 if (!exists($found_ssub_ids{$ssub_id})) {
394 if (ref $issuance->subscription) {
395 $owning_lib_id = $issuance->subscription->owning_lib;
397 my $ssub = $editor->retrieve_serial_subscription($issuance->subscription) or return $editor->die_event;
398 $owning_lib_id = $ssub->owning_lib;
400 return $editor->die_event unless
401 $editor->allowed("ADMIN_SERIAL_SUBSCRIPTION", $owning_lib_id);
402 $found_ssub_ids{$ssub_id} = 1;
405 my $issuanceid = $issuance->id;
406 $issuance->editor($editor->requestor->id);
407 $issuance->edit_date('now');
409 if( $issuance->isdeleted ) {
410 $evt = _delete_siss( $editor, $override, $issuance);
411 } elsif( $issuance->isnew ) {
412 _cleanse_dates($issuance, ['date_published']);
413 $evt = _create_siss( $editor, $issuance );
415 _cleanse_dates($issuance, ['date_published']);
416 $evt = _update_siss( $editor, $override, $issuance );
421 $logger->info("fleshed issuance-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
425 $logger->debug("issuance-alter: done updating issuance batch");
427 $logger->info("fleshed issuance-alter successfully updated ".scalar(@$issuances)." issuances");
432 my ($editor, $override, $issuance) = @_;
433 $logger->info("issuance-alter: delete issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
434 return $editor->event unless $editor->delete_serial_issuance($issuance);
439 my ($editor, $issuance) = @_;
441 $issuance->creator($editor->requestor->id);
442 $issuance->create_date('now');
444 $logger->info("issuance-alter: new issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
445 return $editor->event unless $editor->create_serial_issuance($issuance);
450 my ($editor, $override, $issuance) = @_;
452 $logger->info("issuance-alter: retrieving issuance ".$issuance->id);
453 my $orig_issuance = $editor->retrieve_serial_issuance($issuance->id);
455 $logger->info("issuance-alter: original issuance ".OpenSRF::Utils::JSON->perl2JSON($orig_issuance));
456 $logger->info("issuance-alter: updated issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
457 return $editor->event unless $editor->update_serial_issuance($issuance);
461 __PACKAGE__->register_method(
462 method => "fleshed_serial_issuance_retrieve_batch",
464 api_name => "open-ils.serial.issuance.fleshed.batch.retrieve"
467 sub fleshed_serial_issuance_retrieve_batch {
468 my( $self, $client, $ids ) = @_;
469 # FIXME: permissions?
470 $logger->info("Fetching fleshed serial issuances @$ids");
471 return $U->cstorereq(
472 "open-ils.cstore.direct.serial.issuance.search.atomic",
475 flesh_fields => {siss => [ qw/creator editor subscription/ ]}
479 __PACKAGE__->register_method(
480 method => "pub_fleshed_serial_issuance_retrieve_batch",
481 api_name => "open-ils.serial.issuance.pub_fleshed.batch.retrieve",
484 Public (i.e. OPAC) call for getting at the sub and
485 ultimately the record entry from an issuance
487 params => [{name => 'ids', desc => 'Array of IDs', type => 'array'}],
490 issuance objects, fleshed with subscriptions
496 sub pub_fleshed_serial_issuance_retrieve_batch {
497 my( $self, $client, $ids ) = @_;
498 return [] unless $ids and @$ids;
499 return new_editor()->search_serial_issuance([
503 flesh_fields => {siss => [ qw/subscription/ ]}
508 sub received_siss_by_bib {
509 # XXX this is somewhat wrong in implementation and should not be used in
510 # new places - senator
515 my $args = shift || {};
516 $$args{order} ||= 'asc';
518 my $global = $$args{global} == 0 ? 0 : 1;
520 my $e = new_editor();
521 my $issuances = $e->json_query({
524 $global ? { transform => "min", column => "id", aggregate => 1 } : "id",
529 # We're not really interested in the minimum here. This is
530 # just a way to distinguish issuances whose items have units
531 # from issuances whose items have no units, without altogether
532 # excluding the latter type of issuances.
533 {"transform" => "min", "alias" => "has_units",
534 "column" => "unit", "aggregate" => 1}
540 field => 'subscription',
546 $$args{ou} ? ( join => {
553 fkey => 'distribution'
564 '+ssub' => { record_entry => $bib },
565 $$args{type} ? ( '+siss' => { 'holding_type' => $$args{type} } ) : (),
567 # XXX should we also take specific item statuses into account?
568 date_received => { '!=' => undef },
569 $$args{status} ? ( 'status' => $$args{status} ) : ()
571 $$args{ou} ? ( '+sdist' => {
573 'in' => $U->get_org_descendants($$args{ou}, $$args{depth})
577 $$args{limit} ? ( limit => $$args{limit} ) : (),
578 $$args{offset} ? ( offset => $$args{offset} ) : (),
579 order_by => [{ class => 'siss', field => 'date_published', direction => $$args{order} }],
584 "issuance" => $e->retrieve_serial_issuance($_->{"id"}),
585 "has_units" => $_->{"has_units"} ? 1 : 0
590 __PACKAGE__->register_method(
591 method => 'received_siss_by_bib',
592 api_name => 'open-ils.serial.received_siss.retrieve.by_bib',
597 desc => 'Receives a Bib ID and other optional params and returns "siss" (issuance) objects',
600 desc => 'id of the bre to which the issuances belong',
605 q/A hash of optional arguments. Valid keys and their meanings:
606 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).
607 order := date_published sort direction, either "asc" (chronological, default) or "desc" (reverse chronological)
608 limit := Number of issuances to return. Useful for paging results, or finding the oldest or newest
609 offset := Number of issuance to skip before returning results. Useful for paging.
610 orgid := OU id used to scope retrieval, based on distribution.holding_lib
611 depth := OU depth used to range the scope of orgid
612 type := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
613 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).
621 sub scoped_bib_holdings_summary {
622 # XXX this is somewhat wrong in implementation and should not be used in
623 # new places - senator
627 my $args = shift || {};
629 $args->{order} = 'asc';
631 my ($issuances) = $self->method_lookup('open-ils.serial.received_siss.retrieve.by_bib.atomic')->run( $bibid => $args );
633 # split into issuance type sets
634 my %type_blob = (basic => [], supplement => [], index => []);
635 push @{ $type_blob{ $_->{"issuance"}->holding_type } }, $_->{"issuance"}
638 # generate a statement list for each type
640 for my $type ( keys %type_blob ) {
641 my ($mfhd,$list) = _summarize_contents(new_editor(), $type_blob{$type});
642 $statement_blob{$type} = $list;
645 return \%statement_blob;
647 __PACKAGE__->register_method(
648 method => 'scoped_bib_holdings_summary',
649 api_name => 'open-ils.serial.bib.summary_statements',
653 desc => '** DEPRECATED and only used by JSPAC. Somewhat wrong in implementation. *** Receives a Bib ID and other optional params and returns set of holdings statements',
656 desc => 'id of the bre to which the issuances belong',
661 q/A hash of optional arguments. Valid keys and their meanings:
662 orgid := OU id used to scope retrieval, based on distribution.holding_lib
663 depth := OU depth used to range the scope of orgid
664 type := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
665 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).
673 ##########################################################################
676 __PACKAGE__->register_method(
677 method => 'fleshed_sunit_alter',
678 api_name => 'open-ils.serial.sunit.fleshed.batch.update',
682 desc => 'Receives an array of one or more Units and updates the database as needed',
685 desc => 'Authtoken for current user session',
690 desc => 'Array of fleshed Units',
696 desc => 'Returns 1 if successful, event if failed',
702 sub fleshed_sunit_alter {
703 my( $self, $conn, $auth, $sunits ) = @_;
704 return 1 unless ref $sunits;
705 my( $reqr, $evt ) = $U->checkses($auth);
707 my $editor = new_editor(requestor => $reqr, xact => 1);
708 my $override = $self->api_name =~ /override/;
711 for my $sunit (@$sunits) {
712 my $cn_id = ref $sunit->call_number ? $sunit->call_number->id : $sunit->call_number;
713 if (!exists($found_cn_ids{$cn_id})) {
715 if (ref $sunit->call_number) {
716 $owning_lib_id = $sunit->call_number->owning_lib;
718 my $cn = $editor->retrieve_asset_call_number($sunit->call_number) or return $editor->die_event;
719 $owning_lib_id = $cn->owning_lib;
721 return $editor->die_event unless
722 $editor->allowed("UPDATE_COPY", $owning_lib_id);
723 $found_cn_ids{$cn_id} = 1;
726 if( $sunit->isdeleted ) {
727 $evt = _delete_sunit( $editor, $override, $sunit );
729 $sunit->default_location( $sunit->default_location->id ) if ref $sunit->default_location;
731 if( $sunit->isnew ) {
732 $evt = _create_sunit( $editor, $sunit );
734 $evt = _update_sunit( $editor, $override, $sunit );
740 $logger->info("fleshed sunit-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
744 $logger->debug("sunit-alter: done updating sunit batch");
746 $logger->info("fleshed sunit-alter successfully updated ".scalar(@$sunits)." Units");
751 my ($editor, $override, $sunit) = @_;
752 $logger->info("sunit-alter: delete sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
753 return $editor->event unless $editor->delete_serial_unit($sunit);
758 my ($editor, $sunit) = @_;
760 $logger->info("sunit-alter: new Unit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
761 return $editor->event unless $editor->create_serial_unit($sunit);
766 my ($editor, $override, $sunit) = @_;
768 $logger->info("sunit-alter: retrieving sunit ".$sunit->id);
769 my $orig_sunit = $editor->retrieve_serial_unit($sunit->id);
771 $logger->info("sunit-alter: original sunit ".OpenSRF::Utils::JSON->perl2JSON($orig_sunit));
772 $logger->info("sunit-alter: updated sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
773 return $editor->event unless $editor->update_serial_unit($sunit);
777 __PACKAGE__->register_method(
778 method => "retrieve_unit_list",
780 api_name => "open-ils.serial.unit_list.retrieve"
783 sub retrieve_unit_list {
785 my( $self, $client, @sdist_ids ) = @_;
787 if(ref($sdist_ids[0])) { @sdist_ids = @{$sdist_ids[0]}; }
789 my $e = new_editor();
793 { 'sunit' => [ 'id', 'summary_contents', 'sort_key' ],
794 'sitem' => ['stream'],
795 'sstr' => ['distribution'],
796 'sdist' => [{'column' => 'label', 'alias' => 'sdist_label'}]
803 { 'join' => { 'sunit' => {} } }
808 'distinct' => 'true',
809 'where' => { '+sdist' => {'id' => \@sdist_ids} },
810 'order_by' => [{'class' => 'sunit', 'field' => 'sort_key'}]
813 my $unit_list_entries = $e->json_query($query);
816 foreach my $entry (@$unit_list_entries) {
817 my $value = {'sunit' => $entry->{id}, 'sstr' => $entry->{stream}, 'sdist' => $entry->{distribution}};
818 my $label = $entry->{summary_contents};
819 if (length($label) > 100) {
820 $label = substr($label, 0, 100) . '...'; # limited space in dropdown / menu
822 $label = "[$entry->{sdist_label}/$entry->{stream} #$entry->{id}] " . $label;
823 push (@entries, [$label, OpenSRF::Utils::JSON->perl2JSON($value)]);
831 ##########################################################################
832 # predict and receive methods
834 __PACKAGE__->register_method(
835 method => 'make_predictions',
836 api_name => 'open-ils.serial.make_predictions',
840 desc => 'Receives an ssub id and populates the issuance and item tables',
843 desc => 'Serial Subscription ID',
850 sub make_predictions {
851 my ($self, $conn, $authtoken, $args) = @_;
853 my $editor = OpenILS::Utils::CStoreEditor->new();
854 my $ssub_id = $args->{ssub_id};
855 my $mfhd = MFHD->new(MARC::Record->new());
857 my $ssub = $editor->retrieve_serial_subscription([$ssub_id]);
858 my $scaps = $editor->search_serial_caption_and_pattern({ subscription => $ssub_id, active => 't'});
859 my $sdists = $editor->search_serial_distribution( [{ subscription => $ssub->id }, { flesh => 1, flesh_fields => {sdist => [ qw/ streams / ]} }] ); #TODO: 'deleted' support?
861 my $total_streams = 0;
863 $total_streams += scalar(@{$_->streams});
865 if ($total_streams < 1) {
867 # XXX TODO new event type
868 return new OpenILS::Event(
869 "BAD_PARAMS", note =>
870 "There are no streams to direct items. Can't predict."
876 # XXX TODO new event type
877 return new OpenILS::Event(
878 "BAD_PARAMS", note =>
879 "There are no active caption-and-pattern objects associated " .
880 "with this subscription. Can't predict."
886 foreach my $scap (@$scaps) {
887 my $caption_field = _revive_caption($scap);
888 $caption_field->update('8' => $link_id);
889 my $using_fake_chron = 0;
890 # if we have no chronology, add one for prediction puposes
891 if (!$caption_field->subfield('i') and !$caption_field->enumeration_is_chronology) {
892 $using_fake_chron = 1;
894 $mfhd->append_fields($caption_field);
896 'caption' => $caption_field,
897 'scap_id' => $scap->id,
898 'num_to_predict' => $args->{num_to_predict},
899 'end_date' => defined $args->{end_date} ?
900 $_strp_date->parse_datetime($args->{end_date}) : undef
902 if ($args->{base_issuance}) { # predict from a given issuance
903 $options->{predict_from} = _revive_holding($args->{base_issuance}->holding_code, $caption_field, 1); # fresh MFHD Record, so we simply default to 1 for seqno
904 $options->{faked_chron_date} = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($args->{base_issuance}->date_published)) if $using_fake_chron;
905 } else { # default to predicting from last published
906 my $last_published = $editor->search_serial_issuance([
907 {'caption_and_pattern' => $scap->id,
908 'subscription' => $ssub_id},
909 {limit => 1, order_by => { siss => "date_published DESC" }}]
911 if ($last_published->[0]) {
912 my $last_siss = $last_published->[0];
913 unless ($last_siss->holding_code) {
915 # XXX TODO new event type
916 return new OpenILS::Event(
917 "BAD_PARAMS", note =>
918 "Last issuance has no holding code. Can't predict."
921 $options->{predict_from} = _revive_holding($last_siss->holding_code, $caption_field, 1);
922 $options->{faked_chron_date} = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($last_siss->date_published)) if $using_fake_chron;
925 # XXX TODO make a new event type instead of hijacking this one
926 return new OpenILS::Event(
927 "BAD_PARAMS", note => "No issuance from which to predict!"
931 push( @predictions, _generate_issuance_values($mfhd, $options) );
936 foreach my $prediction (@predictions) {
937 my $issuance = new Fieldmapper::serial::issuance;
939 $issuance->label($prediction->{label});
940 $issuance->date_published($prediction->{date_published}->strftime('%F'));
941 $issuance->holding_code(OpenSRF::Utils::JSON->perl2JSON($prediction->{holding_code}));
942 $issuance->holding_type($prediction->{holding_type});
943 $issuance->caption_and_pattern($prediction->{caption_and_pattern});
944 $issuance->subscription($ssub->id);
945 push (@issuances, $issuance);
948 my $evt = fleshed_issuance_alter($self, $conn, $authtoken, \@issuances);
949 return $evt if ref $evt;
952 for (my $i = 0; $i < @issuances; $i++) {
953 my $date_expected = $predictions[$i]->{date_published}->add(seconds => interval_to_seconds($ssub->expected_date_offset))->strftime('%F');
954 my $issuance = $issuances[$i];
955 #$issuance->label(interval_to_seconds($ssub->expected_date_offset));
956 foreach my $sdist (@$sdists) {
957 my $streams = $sdist->streams;
958 foreach my $stream (@$streams) {
959 my $item = new Fieldmapper::serial::item;
961 $item->stream($stream->id);
962 $item->date_expected($date_expected);
963 $item->issuance($issuance->id);
964 push (@items, $item);
968 fleshed_item_alter($self, $conn, $authtoken, \@items); # FIXME: catch events
973 # _generate_issuance_values() is an initial attempt at a function which can be used
974 # to populate an issuance table with a list of predicted issues. It accepts
975 # a hash ref of options initially defined as:
976 # caption : the caption field to predict on
977 # num_to_predict : the number of issues you wish to predict
978 # 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
980 # The basic method is to first convert to a single holding if compressed, then
981 # increment the holding and save the resulting values to @issuances.
983 # returns @issuance_values, an array of hashrefs containing (formatted
984 # label, formatted chronology date, formatted estimated arrival date, and an
985 # array ref of holding subfields as (key, value, key, value ...)) (not a hash
986 # to protect order and possible duplicate keys), and a holding type.
988 sub _generate_issuance_values {
989 my ($mfhd, $options) = @_;
990 my $caption = $options->{caption};
991 my $scap_id = $options->{scap_id};
992 my $num_to_predict = $options->{num_to_predict};
993 my $end_date = $options->{end_date};
994 my $predict_from = $options->{predict_from}; # issuance to predict from
995 my $faked_chron_date = $options->{faked_chron_date}; # serial does not have a chronology caption, so add one (temporarily) based on this date
998 # Only needed for 'real' MFHD records, not our temp records
999 # my $link_id = $caption->link_id;
1000 # if(!$predict_from) {
1001 # my $htag = $caption->tag;
1002 # $htag =~ s/^85/86/;
1003 # my @holdings = $mfhd->holdings($htag, $link_id);
1004 # my $last_holding = $holdings[-1];
1006 # #if ($last_holding->is_compressed) {
1007 # # $last_holding->compressed_to_last; # convert to last in range
1009 # $predict_from = $last_holding;
1013 $predict_from->notes('public', []);
1014 # add a note marker for system use (?)
1015 $predict_from->notes('private', ['AUTOGEN']);
1017 # our basic method for dealing with 'faked' chronologies will be to add it in, do the predicting, then take it back out
1020 if ($faked_chron_date) {
1021 $orig_caption = $predict_from->caption;
1022 # because of the way MFHD::Caption and Holding work, it is simplest
1023 # to recreate rather than try to update
1024 $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)'));
1025 $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);
1028 my @predictions = $mfhd->generate_predictions({'base_holding' => $predict_from, 'num_to_predict' => $num_to_predict, 'end_date' => $end_date});
1031 my @issuance_values;
1032 foreach my $prediction (@predictions) {
1033 $pub_date = $_strp_date->parse_datetime($prediction->chron_to_date);
1034 if ($faked_chron_date) { # get rid of the chronology portions and restore original caption
1035 $prediction->delete_subfield(code => ['i', 'j', 'k']);
1036 $prediction = new MFHD::Holding($prediction->seqno, new MARC::Field($prediction->tag, $prediction->indicator(1), $prediction->indicator(2), $prediction->subfields_list), $orig_caption);
1042 label => $prediction->format,
1043 date_published => $pub_date,
1044 #date_expected => $date_expected->strftime('%F'),
1045 holding_code => [$prediction->indicator(1),$prediction->indicator(2),$prediction->subfields_list],
1046 holding_type => $MFHD_NAMES_BY_TAG{$caption->tag},
1047 caption_and_pattern => $scap_id
1052 return @issuance_values;
1055 sub _revive_caption {
1058 my $pattern_code = $scap->pattern_code;
1061 my $pattern_parts = OpenSRF::Utils::JSON->JSON2perl($pattern_code);
1062 unshift(@$pattern_parts, $MFHD_TAGS_BY_NAME{$scap->type});
1063 my $pattern_field = new MARC::Field(@$pattern_parts);
1065 # build MFHD::Caption
1066 return new MFHD::Caption($pattern_field);
1069 sub _revive_holding {
1070 my $holding_code = shift;
1071 my $caption_field = shift;
1075 my $holding_parts = OpenSRF::Utils::JSON->JSON2perl($holding_code);
1076 my $captag = $caption_field->tag;
1077 $captag =~ s/^85/86/;
1078 unshift(@$holding_parts, $captag);
1079 my $holding_field = new MARC::Field(@$holding_parts);
1081 # build MFHD::Holding
1082 return new MFHD::Holding($seqno, $holding_field, $caption_field);
1084 # TODO(?) the underlying MARC and the Holding object end up in conflict concerning subfield '8'
1087 __PACKAGE__->register_method(
1088 method => 'unitize_items',
1089 api_name => 'open-ils.serial.receive_items',
1093 desc => 'Marks an item as received, updates the shelving unit (creating a new shelving unit if needed), and updates the summaries',
1096 desc => 'array of serial items',
1101 desc => 'hash of item_ids => barcodes',
1105 name => 'call_numbers',
1106 desc => 'hash of item_ids => call_numbers',
1110 name => 'donor_unit_ids',
1111 desc => 'hash of unit_ids => 1, keyed with ids of any units giving up items',
1116 desc => 'Returns number of received items (num_items) and new unit ID, if applicable (new_unit_id)',
1122 __PACKAGE__->register_method(
1123 method => 'unitize_items',
1124 api_name => 'open-ils.serial.bind_items',
1128 desc => 'Marks an item as bound, updates the shelving unit (creating a new shelving unit if needed)',
1131 desc => 'array of serial items',
1136 desc => 'hash of item_ids => barcodes',
1140 name => 'call_numbers',
1141 desc => 'hash of item_ids => call_numbers',
1145 name => 'donor_unit_ids',
1146 desc => 'hash of unit_ids => 1, keyed with ids of any units giving up items',
1151 desc => 'Returns number of bound items (num_items) and new unit ID, if applicable (new_unit_id)',
1157 # TODO: reset/delete claims information once implemented
1158 # XXX: deal with emptied call numbers here?
1159 __PACKAGE__->register_method(
1160 method => 'unitize_items',
1161 api_name => 'open-ils.serial.reset_items',
1165 desc => 'Resets the items to Expected, updates the shelving unit (deleting the shelving unit if empty), and updates the summaries',
1168 desc => 'array of serial items',
1173 desc => 'Returns number of reset items (num_items)',
1180 my ($self, $conn, $auth, $items, $barcodes, $call_numbers, $donor_unit_ids) = @_;
1182 my $editor = new_editor("authtoken" => $auth, "xact" => 1);
1183 return $editor->die_event unless $editor->checkauth;
1184 return $editor->die_event unless $editor->allowed("RECEIVE_SERIAL");
1185 $self->api_name =~ /serial\.(\w*)_items/;
1189 if ($donor_unit_ids) { # units giving up items need updating as well
1190 %found_unit_ids = %$donor_unit_ids;
1192 my %found_stream_ids;
1195 my %stream_ids_by_unit_id;
1198 my %sdist_by_unit_id;
1199 my %call_number_by_unit_id;
1200 my %sdist_by_stream_id;
1202 my $new_unit_id; # id for '-2' units to share
1203 foreach my $item (@$items) {
1204 # for debugging only, TODO: delete
1205 if (!ref $item) { # hopefully we got an id instead
1206 $item = $editor->retrieve_serial_item($item);
1209 my $unit_id = ref($item->unit) ? $item->unit->id : $item->unit;
1210 my $stream_id = ref($item->stream) ? $item->stream->id : $item->stream;
1211 my $issuance_id = ref($item->issuance) ? $item->issuance->id : $item->issuance;
1212 #TODO: evt on any missing ids
1214 if ($mode eq 'receive') {
1215 $item->date_received('now');
1216 $item->status('Received');
1217 } elsif ($mode eq 'reset') {
1218 # clear date_received
1219 $item->clear_date_received;
1220 # Set status to 'Expected'
1221 $item->status('Expected');
1226 # check for types to trigger summary updates
1228 if (!ref $item->issuance) {
1229 my $scaps = $editor->search_serial_caption_and_pattern([{"+siss" => {"id" => $issuance_id}}, { "join" => {"siss" => {}} }]);
1230 $scap = $scaps->[0];
1231 } elsif (!ref $item->issuance->caption_and_pattern) {
1232 $scap = $editor->retrieve_serial_caption_and_pattern($item->issuance->caption_and_pattern);
1234 $scap = $editor->issuance->caption_and_pattern;
1236 if (!exists($found_types{$stream_id})) {
1237 $found_types{$stream_id} = {};
1239 $found_types{$stream_id}->{$scap->type} = 1;
1241 # create unit if needed
1242 if ($unit_id == -1 or (!$new_unit_id and $unit_id == -2)) { # create unit per item
1244 my $sdists = $editor->search_serial_distribution([
1245 {"+sstr" => {"id" => $stream_id}},
1247 "join" => {"sstr" => {}},
1249 "flesh_fields" => {"sdist" => ["subscription"]}
1251 $unit = _build_unit($editor, $sdists->[0], $mode);
1252 # if _build_unit fails, $unit is an event, so return it
1253 if ($U->event_code($unit)) {
1255 $unit->{"note"} = "Item ID: " . $item->id;
1258 $unit->barcode($barcodes->{$item->id}) if exists($barcodes->{$item->id});
1259 my $evt = _create_sunit($editor, $unit);
1260 return $evt if $evt;
1261 if ($unit_id == -2) {
1262 $new_unit_id = $unit->id;
1263 $unit_id = $new_unit_id;
1265 $unit_id = $unit->id;
1267 $item->unit($unit_id);
1269 # get unit with 'DEFAULT's and save unit, sdist, and call number for later use
1270 $unit = $editor->retrieve_serial_unit($unit->id);
1271 $unit_map{$unit_id} = $unit;
1272 $sdist_by_unit_id{$unit_id} = $sdists->[0];
1273 $call_number_by_unit_id{$unit_id} = $call_numbers->{$item->id};
1274 $sdist_by_stream_id{$stream_id} = $sdists->[0];
1275 } elsif ($unit_id == -2) { # create one unit for all '-2' items
1276 $unit_id = $new_unit_id;
1277 $item->unit($unit_id);
1280 $found_stream_ids{$stream_id} = 1;
1282 if (defined($unit_id) and $unit_id ne '') {
1283 $found_unit_ids{$unit_id} = 1;
1284 # save the stream_id for this unit_id
1285 # TODO: prevent items from different streams in same unit? (perhaps in interface)
1286 $stream_ids_by_unit_id{$unit_id} = $stream_id;
1291 my $evt = _update_sitem($editor, undef, $item);
1292 return $evt if $evt;
1295 # cleanup 'dead' units (units which are now emptied of their items)
1296 my $dead_units = $editor->search_serial_unit([{'+sitem' => {'id' => undef}, 'deleted' => 'f'}, {'join' => {'sitem' => {'type' => 'left'}}}]);
1297 foreach my $unit (@$dead_units) {
1298 _delete_sunit($editor, undef, $unit);
1299 delete $found_unit_ids{$unit->id};
1302 # deal with unit level contents
1303 foreach my $unit_id (keys %found_unit_ids) {
1305 # get all the needed issuances for unit
1306 # TODO remove 'Bindery' from this search (leaving it in for now for backwards compatibility with any current test environment data)
1307 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"unit" => $unit_id, "status" => ["Received", "Bindery"]}}, {"join" => {"sitem" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1308 #TODO: evt on search failure
1310 # retrieve and update unit contents
1313 my $call_number_string;
1315 # if we just created the unit, we will already have it and the distribution stored, and we will need to assign the call number
1316 if (exists $unit_map{$unit_id}) {
1317 $sunit = $unit_map{$unit_id};
1318 $sdist = $sdist_by_unit_id{$unit_id};
1319 $call_number_string = $call_number_by_unit_id{$unit_id};
1320 $record_id = $sdist->subscription->record_entry;
1322 # XXX: this code assumes you will not have units which mix streams/distributions, but current code does not enforce this
1323 $sunit = $editor->retrieve_serial_unit($unit_id);
1324 if ($stream_ids_by_unit_id{$unit_id}) {
1325 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_ids_by_unit_id{$unit_id}}}, { "join" => {"sstr" => {}}, 'limit' => 1 }]);
1327 $sdist = $editor->search_serial_distribution([
1328 {'+sunit' => {'id' => $unit_id}},
1333 { 'join' => 'sunit' }
1340 $sdist = $sdist->[0];
1343 my $evt = _prepare_unit($editor, $sunit, $sdist, $issuances, $call_number_string, $record_id);
1344 if ($U->event_code($evt)) {
1349 $evt = _update_sunit($editor, undef, $sunit);
1350 if ($U->event_code($evt)) {
1356 if ($mode ne 'bind') { # the summary holdings do not change when binding
1357 # deal with stream level summaries
1358 # summaries will be built from the "primary" stream only, that is, the stream with the lowest ID per distribution
1359 # (TODO: consider direct designation)
1360 my %primary_streams_by_sdist;
1361 my %streams_by_sdist;
1363 # see if we have primary streams, and if so, associate them with their distributions
1364 foreach my $stream_id (keys %found_stream_ids) {
1366 if (exists $sdist_by_stream_id{$stream_id}) {
1367 $sdist = $sdist_by_stream_id{$stream_id};
1369 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
1370 $sdist = $sdist->[0];
1371 $sdist_by_stream_id{$stream_id} = $sdist;
1374 if (!exists($streams_by_sdist{$sdist->id})) {
1375 $streams = $editor->search_serial_stream([{"distribution" => $sdist->id}, {"order_by" => {"sstr" => "id"}}]);
1376 $streams_by_sdist{$sdist->id} = $streams;
1378 $streams = $streams_by_sdist{$sdist->id};
1380 $primary_streams_by_sdist{$sdist->id} = $streams->[0] if ($stream_id == $streams->[0]->id);
1383 # retrieve and update summaries for each affected primary stream's distribution
1384 foreach my $sdist_id (keys %primary_streams_by_sdist) {
1385 my $stream = $primary_streams_by_sdist{$sdist_id};
1386 my $stream_id = $stream->id;
1387 # get all the needed issuances for stream
1388 # FIXME: search in Bindery/Bound/Not Published? as well as Received
1389 foreach my $type (keys %{$found_types{$stream_id}}) {
1390 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"stream" => $stream_id, "status" => "Received"}, "+scap" => {"type" => $type}}, {"join" => {"sitem" => {}, "scap" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1391 #TODO: evt on search failure
1392 my $evt = _prepare_summaries($editor, $issuances, $sdist_by_stream_id{$stream_id}, $type);
1393 if ($U->event_code($evt)) {
1402 return {'num_items' => scalar @$items, 'new_unit_id' => $new_unit_id};
1405 sub _find_or_create_call_number {
1406 my ($e, $lib, $cn_string, $record) = @_;
1408 # FIXME: should suffix and prefix come into play here?
1409 my $existing = $e->search_asset_call_number({
1410 "owning_lib" => $lib,
1411 "label" => $cn_string,
1412 "record" => $record,
1414 }) or return $e->die_event;
1417 return $existing->[0]->id;
1419 return $e->die_event unless
1420 $e->allowed("CREATE_VOLUME", $lib);
1422 my $acn = new Fieldmapper::asset::call_number;
1424 $acn->creator($e->requestor->id);
1425 $acn->editor($e->requestor->id);
1426 $acn->record($record);
1427 $acn->label($cn_string);
1428 $acn->owning_lib($lib);
1430 $e->create_asset_call_number($acn) or return $e->die_event;
1431 return $e->data->id;
1435 sub _issuances_received {
1436 # XXX TODO: Add some caching or something. This is getting called
1437 # more often than it has to be.
1438 my ($e, $sitem) = @_;
1440 my $results = $e->json_query({
1441 "select" => {"sitem" => ["issuance"]},
1442 "from" => {"sitem" => {"sstr" => {}, "siss" => {}}},
1444 "+sstr" => {"distribution" => $sitem->stream->distribution->id},
1445 "+siss" => {"holding_type" => $sitem->issuance->holding_type},
1446 "+sitem" => {"date_received" => {"!=" => undef}}
1449 "siss" => {"date_published" => {"direction" => "asc"}}
1451 }) or return $e->die_event;
1453 my $uniq = +{map { $_->{"issuance"} => 1 } @$results};
1454 return [ map { $e->retrieve_serial_issuance($_) } keys %$uniq ];
1457 # _prepare_unit populates the detailed_contents, summary_contents, and
1458 # sort_key fields for a given unit based on a given set of issuances
1459 # Also finds/creates call number as needed
1461 my ($e, $sunit, $sdist, $issuances, $call_number_string, $record_id) = @_;
1463 # Handle call number first if we have one
1464 if ($call_number_string) {
1465 my $org_unit_id = ref $sdist->holding_lib ? $sdist->holding_lib->id : $sdist->holding_lib;
1466 my $real_cn = _find_or_create_call_number(
1468 $call_number_string, $record_id
1471 if ($U->event_code($real_cn)) {
1474 $sunit->call_number($real_cn);
1478 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances);
1480 # special case for single formatted_part (may have summarized version)
1481 if (@$formatted_parts == 1) {
1482 #TODO: MFHD.pm should have a 'format_summary' method for this
1485 $sunit->detailed_contents(
1488 $sdist->unit_label_prefix,
1489 join(", ", @$formatted_parts),
1490 $sdist->unit_label_suffix
1494 # TODO: change this when real summary contents are available
1495 $sunit->summary_contents($sunit->detailed_contents);
1497 # Create sort_key by left padding numbers to 6 digits.
1498 (my $sort_key = $sunit->detailed_contents) =~
1499 s/(\d+)/sprintf '%06d', $1/eg;
1500 $sunit->sort_key($sort_key);
1503 # _prepare_summaries populates the generated_coverage field for a given summary
1504 # type ('basic', 'index', 'supplement') for a given distribution.
1505 # It also creates the summary if it doesn't yet exist.
1506 sub _prepare_summaries {
1507 my ($e, $issuances, $sdist, $type) = @_;
1509 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances, $sdist);
1511 my $search_method = "search_serial_${type}_summary";
1512 my $summary = $e->$search_method([{"distribution" => $sdist->id}]);
1514 my $cu_method = "update";
1517 $summary = $summary->[0];
1519 my $class = "Fieldmapper::serial::${type}_summary";
1520 $summary = $class->new;
1521 $summary->distribution($sdist->id);
1522 $cu_method = "create";
1525 $summary->generated_coverage(OpenSRF::Utils::JSON->perl2JSON($formatted_parts));
1526 my $method = "${cu_method}_serial_${type}_summary";
1527 return $e->die_event unless $e->$method($summary);
1530 sub _unit_by_iss_and_str {
1531 my ($e, $issuance, $stream) = @_;
1533 my $unit = $e->json_query({
1534 "select" => {"sunit" => ["id"]},
1535 "from" => {"sitem" => {"sunit" => {}}},
1538 "issuance" => $issuance->id,
1539 "stream" => $stream->id
1542 }) or return $e->die_event;
1543 return 0 if not @$unit;
1545 $e->retrieve_serial_unit($unit->[0]->{"id"}) or $e->die_event;
1548 sub move_previous_unit {
1549 my ($e, $prev_iss, $curr_item, $new_loc) = @_;
1551 my $prev_unit = _unit_by_iss_and_str($e,$prev_iss,$curr_item->stream);
1552 return $prev_unit if defined $U->event_code($prev_unit);
1553 return 0 if not $prev_unit;
1555 if ($prev_unit->location != $new_loc) {
1556 $prev_unit->location($new_loc);
1557 $e->update_serial_unit($prev_unit) or return $e->die_event;
1562 # _previous_issuance() assumes $existing is an ordered array
1563 sub _previous_issuance {
1564 my ($existing, $issuance) = @_;
1566 my $last = $existing->[-1];
1567 return undef unless $last;
1568 return ($last->id == $issuance->id ? $existing->[-2] : $last);
1571 __PACKAGE__->register_method(
1572 "method" => "receive_items_one_unit_per",
1573 "api_name" => "open-ils.serial.receive_items.one_unit_per",
1578 "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",
1582 "desc" => "authtoken",
1587 "desc" => "array of serial items, possibly fleshed with units and definitely fleshed with stream->distribution",
1592 "desc" => "id of bib record these items are associated with
1593 (XXX could/should be derived from items)",
1598 "desc" => "The item ID for each item successfully received",
1604 sub receive_items_one_unit_per {
1605 # XXX This function may be temporary, as it does some of what
1606 # unitize_items() does, just in a different way.
1607 my ($self, $client, $auth, $items, $record) = @_;
1609 my $e = new_editor("authtoken" => $auth, "xact" => 1);
1610 return $e->die_event unless $e->checkauth;
1611 return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
1613 my $prev_loc_setting_map = {};
1614 my $user_id = $e->requestor->id;
1616 # Get a list of all the non-virtual field names in a serial::unit for
1617 # merging given unit objects with template-built units later.
1618 # XXX move this somewhere global so it isn't re-run all the time
1619 my $all_unit_fields =
1620 $Fieldmapper::fieldmap->{"Fieldmapper::serial::unit"}->{"fields"};
1621 my @real_unit_fields = grep {
1622 not $all_unit_fields->{$_}->{"virtual"}
1623 } keys %$all_unit_fields;
1625 foreach my $item (@$items) {
1626 # Note that we expect a certain fleshing on the items we're getting.
1627 my $sdist = $item->stream->distribution;
1629 # Fetch a list of issuances with received copies already existing
1630 # on this distribution (and with the same holding type on the
1631 # issuance). This will be used in up to two places: once when building
1632 # a summary, once when changing the copy location of the previous
1634 my $issuances_received = _issuances_received($e, $item);
1635 if ($U->event_code($issuances_received)) {
1637 return $issuances_received;
1640 # Find out if we need to to deal with previous copy location changing.
1641 my $ou = $sdist->holding_lib->id;
1642 unless (exists $prev_loc_setting_map->{$ou}) {
1643 $prev_loc_setting_map->{$ou} = $U->ou_ancestor_setting_value(
1644 $ou, "serial.prev_issuance_copy_location", $e
1648 # If there is a previous copy location setting, we need the previous
1649 # issuance, from which we can in turn look up the item attached to the
1650 # same stream we're on now.
1651 if ($prev_loc_setting_map->{$ou}) {
1653 _previous_issuance($issuances_received, $item->issuance)) {
1655 # Now we can change the copy location of the previous unit,
1657 return $e->event if defined $U->event_code(
1659 $e, $prev_iss, $item, $prev_loc_setting_map->{$ou}
1665 # Create unit if given by user
1666 if (ref $item->unit) {
1667 # detach from the item, as we need to create separately
1668 my $user_unit = $item->unit;
1670 # get a unit based on associated template
1671 my $template_unit = _build_unit($e, $sdist, "receive");
1672 if ($U->event_code($template_unit)) {
1674 $template_unit->{"note"} = "Item ID: " . $item->id;
1675 return $template_unit;
1678 # merge built unit with provided unit from user
1679 foreach (@real_unit_fields) {
1680 unless ($user_unit->$_) {
1681 $user_unit->$_($template_unit->$_);
1685 # Treat call number specially: the provided value from the
1686 # user will really be a string.
1687 my $call_number_string;
1688 if ($user_unit->call_number) {
1689 $call_number_string = $user_unit->call_number;
1690 # clear call number for now (replaced in _prepare_unit)
1691 $user_unit->clear_call_number;
1694 my $evt = _prepare_unit(
1695 $e, $user_unit, $sdist, [$item->issuance],
1696 $call_number_string, $record
1698 if ($U->event_code($evt)) {
1703 # create/update summary objects related to this distribution
1704 # Make sure @$issuances_received contains current item's issuance
1705 unless (grep { $_->id == $item->issuance->id } @$issuances_received) {
1706 push @$issuances_received, $item->issuance;
1708 $evt = _prepare_summaries($e, $issuances_received, $item->stream->distribution, $item->issuance->holding_type);
1709 if ($U->event_code($evt)) {
1714 # set the incontrovertibles on the unit
1715 $user_unit->edit_date("now");
1716 $user_unit->create_date("now");
1717 $user_unit->editor($user_id);
1718 $user_unit->creator($user_id);
1720 return $e->die_event unless $e->create_serial_unit($user_unit);
1722 # save reference to new unit
1723 $item->unit($e->data->id);
1726 # Create notes if given by user
1727 if (ref($item->notes) and @{$item->notes}) {
1728 foreach my $note (@{$item->notes}) {
1729 $note->creator($user_id);
1730 $note->create_date("now");
1732 return $e->die_event unless $e->create_serial_item_note($note);
1735 $item->clear_notes; # They're saved; we no longer want them here.
1738 # Set the incontrovertibles on the item
1739 $item->status("Received");
1740 $item->date_received("now");
1741 $item->edit_date("now");
1742 $item->editor($user_id);
1744 return $e->die_event unless $e->update_serial_item($item);
1746 # send client a response
1747 $client->respond($item->id);
1750 $e->commit or return $e->die_event;
1758 #my $skip_call_number = shift;
1760 my $attr = $mode . '_unit_template';
1761 my $template = $editor->retrieve_asset_copy_template($sdist->$attr) or
1762 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_COPY_TEMPLATE");
1764 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 );
1766 my $unit = new Fieldmapper::serial::unit;
1767 foreach my $part (@parts) {
1768 my $value = $template->$part;
1769 next if !defined($value);
1770 $unit->$part($value);
1773 # ignore circ_lib in template, set to distribution holding_lib
1774 $unit->circ_lib($sdist->holding_lib);
1775 $unit->creator($editor->requestor->id);
1776 $unit->editor($editor->requestor->id);
1778 # XXX: this feature has been pushed back until after 2.0 at least
1779 # unless ($skip_call_number) {
1780 # $attr = $mode . '_call_number';
1781 # my $cn = $sdist->$attr or
1782 # return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_CALL_NUMBER");
1784 # $unit->call_number($cn);
1786 $unit->call_number('-1'); # default to the dummy call number
1787 $unit->barcode('@@PLACEHOLDER'); # generic unit will start with a generated placeholder barcode
1788 $unit->sort_key('');
1789 $unit->summary_contents('');
1790 $unit->detailed_contents('');
1796 sub _summarize_contents {
1798 my $issuances = shift;
1801 # create or lookup MFHD record
1803 if ($sdist and defined($sdist->record_entry) and $sdist->summary_method eq 'merge_with_sre') {
1805 if (ref $sdist->record_entry) {
1806 $sre = $sdist->record_entry;
1808 $sre = $editor->retrieve_serial_record_entry($sdist->record_entry);
1810 $mfhd = MFHD->new(MARC::Record->new_from_xml($sre->marc));
1812 $logger->info($sdist);
1813 $mfhd = MFHD->new(MARC::Record->new());
1819 # We keep track of these separately to avoid link_id contamination,
1820 # e.g. a basic issuance, followed by a merging supplement, followed by
1821 # another basic. If we could be sure that they were not mixed, one
1822 # value could suffice.
1823 my %link_ids = ('basic' => 10000, 'index' => 10000, 'supplement' => 10000);
1824 my %first_scap = ('basic' => 1, 'index' => 1, 'supplement' => 1);
1825 foreach my $issuance (@$issuances) {
1826 my $scap_id = $issuance->caption_and_pattern;
1827 next if (!$scap_id); # skip issuances with no caption/pattern
1831 # if this is the first appearance of this scap, retrieve it and add it to the temporary record
1832 if (!exists $scaps{$issuance->caption_and_pattern}) {
1833 $scaps{$scap_id} = $editor->retrieve_serial_caption_and_pattern($scap_id);
1834 $scap = $scaps{$scap_id};
1835 $scap_field = _revive_caption($scap);
1837 if ($first_scap{$scap->type}) { # special merge processing
1838 $first_scap{$MFHD_TAGS_BY_NAME{$scap->type}} = 0;
1839 if ($sdist and $sdist->summary_method eq 'merge_with_sre') {
1840 # MFHD Caption objects do not yet have a built-in compare (TODO), so let's do a basic one
1841 my @field_85xs = $mfhd->field($MFHD_TAGS_BY_NAME{$scap->type});
1843 my $last_caption_field = $field_85xs[-1];
1844 my $last_link_id = $last_caption_field->subfield('8');
1845 # set the link id to match, temporarily, for comparison
1846 $last_caption_field->update('8' => $scap_field->subfield('8'));
1847 my $last_caption_json = OpenSRF::Utils::JSON->perl2JSON([$last_caption_field->indicator(1), $last_caption_field->indicator(2), $last_caption_field->subfields_list]);
1848 if ($last_caption_json eq $scap->pattern_code) { # merge is possible, they match
1850 $link_ids{$scap->type} = $last_link_id;
1851 # set scap_field to last field
1852 $scap_field = $last_caption_field;
1858 $scap_fields{$scap_id} = $scap_field;
1859 $scap_field->update('8' => $link_ids{$scap->type});
1860 # TODO: make MFHD/Caption smarter about this
1861 $scap_field->{_mfhdc_LINK_ID} = $link_ids{$scap->type};
1862 $mfhd->append_fields($scap_field) if !$did_merge;
1863 $link_ids{$scap->type}++;
1865 $scap_field = $scap_fields{$scap_id};
1868 $mfhd->append_fields(_revive_holding($issuance->holding_code, $scap_field, $seqno));
1872 my @formatted_parts;
1873 my @scap_fields_ordered = $mfhd->field('85[345]');
1874 foreach my $scap_field (@scap_fields_ordered) { #TODO: use generic MFHD "summarize" method, once available
1875 my @updated_holdings = $mfhd->get_compressed_holdings($scap_field);
1876 foreach my $holding (@updated_holdings) {
1877 push(@formatted_parts, $holding->format);
1881 return ($mfhd, \@formatted_parts);
1884 ##########################################################################
1887 __PACKAGE__->register_method(
1888 method => 'fetch_notes',
1889 api_name => 'open-ils.serial.item_note.retrieve.all',
1891 Returns an array of copy note objects.
1892 @param args A named hash of parameters including:
1893 authtoken : Required if viewing non-public notes
1894 item_id : The id of the item whose notes we want to retrieve
1895 pub : True if all the caller wants are public notes
1896 @return An array of note objects
1900 __PACKAGE__->register_method(
1901 method => 'fetch_notes',
1902 api_name => 'open-ils.serial.subscription_note.retrieve.all',
1904 Returns an array of copy note objects.
1905 @param args A named hash of parameters including:
1906 authtoken : Required if viewing non-public notes
1907 subscription_id : The id of the item whose notes we want to retrieve
1908 pub : True if all the caller wants are public notes
1909 @return An array of note objects
1913 __PACKAGE__->register_method(
1914 method => 'fetch_notes',
1915 api_name => 'open-ils.serial.distribution_note.retrieve.all',
1917 Returns an array of copy note objects.
1918 @param args A named hash of parameters including:
1919 authtoken : Required if viewing non-public notes
1920 distribution_id : The id of the item whose notes we want to retrieve
1921 pub : True if all the caller wants are public notes
1922 @return An array of note objects
1926 # TODO: revisit this method to consider replacing cstore direct calls
1928 my( $self, $connection, $args ) = @_;
1930 $self->api_name =~ /serial\.(\w*)_note/;
1933 my $id = $$args{object_id};
1934 my $authtoken = $$args{authtoken};
1938 return $U->cstorereq(
1939 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic',
1940 { $type => $id, pub => 't' } );
1942 # FIXME: restore perm check
1943 # ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
1944 # return $evt if $evt;
1945 return $U->cstorereq(
1946 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic', {$type => $id} );
1952 __PACKAGE__->register_method(
1953 method => 'update_note',
1954 api_name => 'open-ils.serial.item_note.update',
1956 Updates or creates an item note
1957 @param authtoken The login session key
1958 @param note The note object to update or create
1959 @return The id of the note object
1963 __PACKAGE__->register_method(
1964 method => 'update_note',
1965 api_name => 'open-ils.serial.subscription_note.update',
1967 Updates or creates a subscription note
1968 @param authtoken The login session key
1969 @param note The note object to update or create
1970 @return The id of the note object
1974 __PACKAGE__->register_method(
1975 method => 'update_note',
1976 api_name => 'open-ils.serial.distribution_note.update',
1978 Updates or creates a distribution note
1979 @param authtoken The login session key
1980 @param note The note object to update or create
1981 @return The id of the note object
1986 my( $self, $connection, $authtoken, $note ) = @_;
1988 $self->api_name =~ /serial\.(\w*)_note/;
1991 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1992 return $e->event unless $e->checkauth;
1994 if ($type eq 'item') {
1995 my $sitem = $e->retrieve_serial_item([
1997 "flesh" => 2, "flesh_fields" => {
1998 "sitem" => ["stream"], "sstr" => ["distribution"]
2001 ]) or return $e->die_event;
2003 return $e->die_event unless $e->allowed(
2004 "ADMIN_SERIAL_ITEM", $sitem->stream->distribution->holding_lib
2006 } elsif ($type eq 'distribution') {
2007 my $sdist = $e->retrieve_serial_distribution($note->distribution)
2008 or return $e->die_event;
2010 return $e->die_event unless
2011 $e->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2012 } else { # subscription
2013 my $sub = $e->retrieve_serial_subscription($note->subscription)
2014 or return $e->die_event;
2016 return $e->die_event unless
2017 $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
2020 $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
2023 $note->create_date('now');
2024 $note->creator($e->requestor->id);
2026 $method = "create_serial_${type}_note";
2028 $method = "update_serial_${type}_note";
2030 $e->$method($note) or return $e->event;
2035 __PACKAGE__->register_method(
2036 method => 'delete_note',
2037 api_name => 'open-ils.serial.item_note.delete',
2039 Deletes an existing item note
2040 @param authtoken The login session key
2041 @param noteid The id of the note to delete
2042 @return 1 on success - Event otherwise.
2046 __PACKAGE__->register_method(
2047 method => 'delete_note',
2048 api_name => 'open-ils.serial.subscription_note.delete',
2050 Deletes an existing subscription note
2051 @param authtoken The login session key
2052 @param noteid The id of the note to delete
2053 @return 1 on success - Event otherwise.
2057 __PACKAGE__->register_method(
2058 method => 'delete_note',
2059 api_name => 'open-ils.serial.distribution_note.delete',
2061 Deletes an existing distribution note
2062 @param authtoken The login session key
2063 @param noteid The id of the note to delete
2064 @return 1 on success - Event otherwise.
2069 my( $self, $conn, $authtoken, $noteid ) = @_;
2071 $self->api_name =~ /serial\.(\w*)_note/;
2074 my $e = new_editor(xact=>1, authtoken=>$authtoken);
2075 return $e->die_event unless $e->checkauth;
2077 my $method = "retrieve_serial_${type}_note";
2078 my $note = $e->$method([
2080 ]) or return $e->die_event;
2082 if ($type eq 'item') {
2083 my $sitem = $e->retrieve_serial_item([
2085 "flesh" => 2, "flesh_fields" => {
2086 "sitem" => ["stream"], "sstr" => ["distribution"]
2089 ]) or return $e->die_event;
2091 return $e->die_event unless $e->allowed(
2092 "ADMIN_SERIAL_ITEM", $sitem->stream->distribution->holding_lib
2094 } elsif ($type eq 'distribution') {
2095 my $sdist = $e->retrieve_serial_distribution($note->distribution)
2096 or return $e->die_event;
2098 return $e->die_event unless
2099 $e->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2100 } else { # subscription
2101 my $sub = $e->retrieve_serial_subscription($note->subscription)
2102 or return $e->die_event;
2104 return $e->die_event unless
2105 $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
2108 $method = "delete_serial_${type}_note";
2109 $e->$method($note) or return $e->die_event;
2115 ##########################################################################
2116 # subscription methods
2118 __PACKAGE__->register_method(
2119 method => 'fleshed_ssub_alter',
2120 api_name => 'open-ils.serial.subscription.fleshed.batch.update',
2124 desc => 'Receives an array of one or more subscriptions and updates the database as needed',
2126 name => 'authtoken',
2127 desc => 'Authtoken for current user session',
2131 name => 'subscriptions',
2132 desc => 'Array of fleshed subscriptions',
2138 desc => 'Returns 1 if successful, event if failed',
2144 sub fleshed_ssub_alter {
2145 my( $self, $conn, $auth, $ssubs ) = @_;
2146 return 1 unless ref $ssubs;
2147 my( $reqr, $evt ) = $U->checkses($auth);
2148 return $evt if $evt;
2149 my $editor = new_editor(requestor => $reqr, xact => 1);
2150 my $override = $self->api_name =~ /override/;
2152 for my $ssub (@$ssubs) {
2153 my $owning_lib_id = ref $ssub->owning_lib ? $ssub->owning_lib->id : $ssub->owning_lib;
2154 return $editor->die_event unless
2155 $editor->allowed("ADMIN_SERIAL_SUBSCRIPTION", $owning_lib_id);
2157 my $ssubid = $ssub->id;
2159 if( $ssub->isdeleted ) {
2160 $evt = _delete_ssub( $editor, $override, $ssub);
2161 } elsif( $ssub->isnew ) {
2162 _cleanse_dates($ssub, ['start_date','end_date']);
2163 $evt = _create_ssub( $editor, $ssub );
2165 _cleanse_dates($ssub, ['start_date','end_date']);
2166 $evt = _update_ssub( $editor, $override, $ssub );
2171 $logger->info("fleshed subscription-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2175 $logger->debug("subscription-alter: done updating subscription batch");
2177 $logger->info("fleshed subscription-alter successfully updated ".scalar(@$ssubs)." subscriptions");
2182 my ($editor, $override, $ssub) = @_;
2183 $logger->info("subscription-alter: delete subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2184 my $sdists = $editor->search_serial_distribution(
2185 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2186 my $cps = $editor->search_serial_caption_and_pattern(
2187 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2188 my $sisses = $editor->search_serial_issuance(
2189 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2190 return OpenILS::Event->new(
2191 'SERIAL_SUBSCRIPTION_NOT_EMPTY', payload => $ssub->id ) if (@$sdists or @$cps or @$sisses);
2193 return $editor->event unless $editor->delete_serial_subscription($ssub);
2198 my ($editor, $ssub) = @_;
2200 $logger->info("subscription-alter: new subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2201 return $editor->event unless $editor->create_serial_subscription($ssub);
2206 my ($editor, $override, $ssub) = @_;
2208 $logger->info("subscription-alter: retrieving subscription ".$ssub->id);
2209 my $orig_ssub = $editor->retrieve_serial_subscription($ssub->id);
2211 $logger->info("subscription-alter: original subscription ".OpenSRF::Utils::JSON->perl2JSON($orig_ssub));
2212 $logger->info("subscription-alter: updated subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2213 return $editor->event unless $editor->update_serial_subscription($ssub);
2217 __PACKAGE__->register_method(
2218 method => "fleshed_serial_subscription_retrieve_batch",
2220 api_name => "open-ils.serial.subscription.fleshed.batch.retrieve"
2223 sub fleshed_serial_subscription_retrieve_batch {
2224 my( $self, $client, $ids ) = @_;
2225 # FIXME: permissions?
2226 $logger->info("Fetching fleshed subscriptions @$ids");
2227 return $U->cstorereq(
2228 "open-ils.cstore.direct.serial.subscription.search.atomic",
2231 flesh_fields => {ssub => [ qw/owning_lib notes/ ]}
2235 __PACKAGE__->register_method(
2236 method => "retrieve_sub_tree",
2238 api_name => "open-ils.serial.subscription_tree.retrieve"
2241 __PACKAGE__->register_method(
2242 method => "retrieve_sub_tree",
2243 api_name => "open-ils.serial.subscription_tree.global.retrieve"
2246 sub retrieve_sub_tree {
2248 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2250 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2254 # TODO: permission support
2255 if(!@org_ids and $user_session) {
2257 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2258 @org_ids = ($user_obj->home_ou);
2261 if( $self->api_name =~ /global/ ) {
2262 return _build_subs_list( { record_entry => $docid } ); # TODO: filter for !deleted, or active?
2267 for my $orgid (@org_ids) {
2268 my $subs = _build_subs_list(
2269 { record_entry => $docid, owning_lib => $orgid } );# TODO: filter for !deleted, or active?
2270 push( @all_subs, @$subs );
2279 sub _build_subs_list {
2280 my $search_hash = shift;
2282 #$search_hash->{deleted} = 'f';
2283 my $e = new_editor();
2285 my $subs = $e->search_serial_subscription([$search_hash, { 'order_by' => {'ssub' => 'id'} }]);
2289 for my $sub (@$subs) {
2291 # TODO: filter on !deleted?
2292 my $dists = $e->search_serial_distribution(
2293 [{ subscription => $sub->id }, { 'order_by' => {'sdist' => 'label'} }]
2296 #$dists = [ sort { $a->label cmp $b->label } @$dists ];
2298 $sub->distributions($dists);
2300 # TODO: filter on !deleted?
2301 my $issuances = $e->search_serial_issuance(
2302 [{ subscription => $sub->id }, { 'order_by' => {'siss' => 'label'} }]
2305 #$issuances = [ sort { $a->label cmp $b->label } @$issuances ];
2306 $sub->issuances($issuances);
2308 # TODO: filter on !deleted?
2309 my $scaps = $e->search_serial_caption_and_pattern(
2310 [{ subscription => $sub->id }, { 'order_by' => {'scap' => 'id'} }]
2313 #$scaps = [ sort { $a->id cmp $b->id } @$scaps ];
2314 $sub->scaps($scaps);
2315 push( @built_subs, $sub );
2318 return \@built_subs;
2322 __PACKAGE__->register_method(
2323 method => "subscription_orgs_for_title",
2325 api_name => "open-ils.serial.subscription.retrieve_orgs_by_title"
2328 sub subscription_orgs_for_title {
2329 my( $self, $client, $record_id ) = @_;
2331 my $subs = $U->simple_scalar_request(
2333 "open-ils.cstore.direct.serial.subscription.search.atomic",
2334 { record_entry => $record_id }); # TODO: filter on !deleted?
2336 my $orgs = { map {$_->owning_lib => 1 } @$subs };
2337 return [ keys %$orgs ];
2341 ##########################################################################
2342 # distribution methods
2344 __PACKAGE__->register_method(
2345 method => 'fleshed_sdist_alter',
2346 api_name => 'open-ils.serial.distribution.fleshed.batch.update',
2350 desc => 'Receives an array of one or more distributions and updates the database as needed',
2352 name => 'authtoken',
2353 desc => 'Authtoken for current user session',
2357 name => 'distributions',
2358 desc => 'Array of fleshed distributions',
2364 desc => 'Returns 1 if successful, event if failed',
2370 sub fleshed_sdist_alter {
2371 my( $self, $conn, $auth, $sdists ) = @_;
2372 return 1 unless ref $sdists;
2373 my( $reqr, $evt ) = $U->checkses($auth);
2374 return $evt if $evt;
2375 my $editor = new_editor(requestor => $reqr, xact => 1);
2376 my $override = $self->api_name =~ /override/;
2378 for my $sdist (@$sdists) {
2379 my $holding_lib_id = ref $sdist->holding_lib ? $sdist->holding_lib->id : $sdist->holding_lib;
2380 return $editor->die_event unless
2381 $editor->allowed("ADMIN_SERIAL_DISTRIBUTION", $holding_lib_id);
2383 if( $sdist->isdeleted ) {
2384 $evt = _delete_sdist( $editor, $override, $sdist);
2385 } elsif( $sdist->isnew ) {
2386 $evt = _create_sdist( $editor, $sdist );
2388 $evt = _update_sdist( $editor, $override, $sdist );
2393 $logger->info("fleshed distribution-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2397 $logger->debug("distribution-alter: done updating distribution batch");
2399 $logger->info("fleshed distribution-alter successfully updated ".scalar(@$sdists)." distributions");
2404 my ($editor, $override, $sdist) = @_;
2405 $logger->info("distribution-alter: delete distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2406 return $editor->event unless $editor->delete_serial_distribution($sdist);
2411 my ($editor, $sdist) = @_;
2413 $logger->info("distribution-alter: new distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2414 return $editor->event unless $editor->create_serial_distribution($sdist);
2416 # create summaries too
2417 my $summary = new Fieldmapper::serial::basic_summary;
2418 $summary->distribution($sdist->id);
2419 $summary->generated_coverage('');
2420 return $editor->event unless $editor->create_serial_basic_summary($summary);
2421 $summary = new Fieldmapper::serial::supplement_summary;
2422 $summary->distribution($sdist->id);
2423 $summary->generated_coverage('');
2424 return $editor->event unless $editor->create_serial_supplement_summary($summary);
2425 $summary = new Fieldmapper::serial::index_summary;
2426 $summary->distribution($sdist->id);
2427 $summary->generated_coverage('');
2428 return $editor->event unless $editor->create_serial_index_summary($summary);
2430 # create a starter stream (TODO: reconsider this)
2431 my $stream = new Fieldmapper::serial::stream;
2432 $stream->distribution($sdist->id);
2433 return $editor->event unless $editor->create_serial_stream($stream);
2439 my ($editor, $override, $sdist) = @_;
2441 $logger->info("distribution-alter: retrieving distribution ".$sdist->id);
2442 my $orig_sdist = $editor->retrieve_serial_distribution($sdist->id);
2444 $logger->info("distribution-alter: original distribution ".OpenSRF::Utils::JSON->perl2JSON($orig_sdist));
2445 $logger->info("distribution-alter: updated distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2446 return $editor->event unless $editor->update_serial_distribution($sdist);
2450 __PACKAGE__->register_method(
2451 method => "fleshed_serial_distribution_retrieve_batch",
2453 api_name => "open-ils.serial.distribution.fleshed.batch.retrieve"
2456 sub fleshed_serial_distribution_retrieve_batch {
2457 my( $self, $client, $ids ) = @_;
2458 # FIXME: permissions?
2459 $logger->info("Fetching fleshed distributions @$ids");
2460 return $U->cstorereq(
2461 "open-ils.cstore.direct.serial.distribution.search.atomic",
2464 flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams / ]}
2468 __PACKAGE__->register_method(
2469 method => "retrieve_dist_tree",
2471 api_name => "open-ils.serial.distribution_tree.retrieve"
2474 __PACKAGE__->register_method(
2475 method => "retrieve_dist_tree",
2476 api_name => "open-ils.serial.distribution_tree.global.retrieve"
2479 sub retrieve_dist_tree {
2480 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2482 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2486 # TODO: permission support
2487 if(!@org_ids and $user_session) {
2489 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2490 @org_ids = ($user_obj->home_ou);
2493 my $e = new_editor();
2495 if( $self->api_name =~ /global/ ) {
2496 return $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }},
2498 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 / ]},
2499 order_by => {'sdist' => 'id'},
2500 'join' => {'ssub' => {}}
2502 ]); # TODO: filter for !deleted?
2506 for my $orgid (@org_ids) {
2507 my $dists = $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }, holding_lib => $orgid},
2509 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 / ]},
2510 order_by => {'sdist' => 'id'},
2511 'join' => {'ssub' => {}}
2513 ]); # TODO: filter for !deleted?
2514 push( @all_dists, @$dists ) if $dists;
2524 __PACKAGE__->register_method(
2525 method => "distribution_orgs_for_title",
2527 api_name => "open-ils.serial.distribution.retrieve_orgs_by_title"
2530 sub distribution_orgs_for_title {
2531 my( $self, $client, $record_id ) = @_;
2533 my $dists = $U->cstorereq(
2534 "open-ils.cstore.direct.serial.distribution.search.atomic",
2535 { '+ssub' => { record_entry => $record_id } },
2536 { 'join' => {'ssub' => {}} }); # TODO: filter on !deleted?
2538 my $orgs = { map {$_->holding_lib => 1 } @$dists };
2539 return [ keys %$orgs ];
2543 ##########################################################################
2544 # caption and pattern methods
2546 __PACKAGE__->register_method(
2547 method => 'scap_alter',
2548 api_name => 'open-ils.serial.caption_and_pattern.batch.update',
2552 desc => 'Receives an array of one or more caption and patterns and updates the database as needed',
2554 name => 'authtoken',
2555 desc => 'Authtoken for current user session',
2560 desc => 'Array of caption and patterns',
2566 desc => 'Returns 1 if successful, event if failed',
2573 my( $self, $conn, $auth, $scaps ) = @_;
2574 return 1 unless ref $scaps;
2575 my( $reqr, $evt ) = $U->checkses($auth);
2576 return $evt if $evt;
2577 my $editor = new_editor(requestor => $reqr, xact => 1);
2578 my $override = $self->api_name =~ /override/;
2581 for my $scap (@$scaps) {
2582 if (!exists($found_ssub_ids{$scap->subscription})) {
2583 my $ssub = $editor->retrieve_serial_subscription($scap->subscription) or return $editor->die_event;
2584 return $editor->die_event unless
2585 $editor->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $ssub->owning_lib);
2586 $found_ssub_ids{$scap->subscription} = 1;
2589 if( $scap->isdeleted ) {
2590 $evt = _delete_scap( $editor, $override, $scap);
2591 } elsif( $scap->isnew ) {
2592 $evt = _create_scap( $editor, $scap );
2594 $evt = _update_scap( $editor, $override, $scap );
2599 $logger->info("caption_and_pattern-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2603 $logger->debug("caption_and_pattern-alter: done updating caption_and_pattern batch");
2605 $logger->info("caption_and_pattern-alter successfully updated ".scalar(@$scaps)." caption_and_patterns");
2610 my ($editor, $override, $scap) = @_;
2611 $logger->info("caption_and_pattern-alter: delete caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2612 my $sisses = $editor->search_serial_issuance(
2613 { caption_and_pattern => $scap->id }, { limit => 1 } ); #TODO: 'deleted' support?
2614 return OpenILS::Event->new(
2615 'SERIAL_CAPTION_AND_PATTERN_HAS_ISSUANCES', payload => $scap->id ) if (@$sisses);
2617 return $editor->event unless $editor->delete_serial_caption_and_pattern($scap);
2622 my ($editor, $scap) = @_;
2624 $logger->info("caption_and_pattern-alter: new caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2625 return $editor->event unless $editor->create_serial_caption_and_pattern($scap);
2630 my ($editor, $override, $scap) = @_;
2632 $logger->info("caption_and_pattern-alter: retrieving caption_and_pattern ".$scap->id);
2633 my $orig_scap = $editor->retrieve_serial_caption_and_pattern($scap->id);
2635 $logger->info("caption_and_pattern-alter: original caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($orig_scap));
2636 $logger->info("caption_and_pattern-alter: updated caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2637 return $editor->event unless $editor->update_serial_caption_and_pattern($scap);
2641 __PACKAGE__->register_method(
2642 method => "serial_caption_and_pattern_retrieve_batch",
2644 api_name => "open-ils.serial.caption_and_pattern.batch.retrieve"
2647 sub serial_caption_and_pattern_retrieve_batch {
2648 my( $self, $client, $ids ) = @_;
2649 $logger->info("Fetching caption_and_patterns @$ids");
2650 return $U->cstorereq(
2651 "open-ils.cstore.direct.serial.caption_and_pattern.search.atomic",
2656 ##########################################################################
2659 __PACKAGE__->register_method(
2660 method => 'sstr_alter',
2661 api_name => 'open-ils.serial.stream.batch.update',
2665 desc => 'Receives an array of one or more streams and updates the database as needed',
2667 name => 'authtoken',
2668 desc => 'Authtoken for current user session',
2673 desc => 'Array of streams',
2679 desc => 'Returns 1 if successful, event if failed',
2686 my( $self, $conn, $auth, $sstrs ) = @_;
2687 return 1 unless ref $sstrs;
2688 my( $reqr, $evt ) = $U->checkses($auth);
2689 return $evt if $evt;
2690 my $editor = new_editor(requestor => $reqr, xact => 1);
2691 my $override = $self->api_name =~ /override/;
2693 my %found_sdist_ids;
2694 for my $sstr (@$sstrs) {
2695 if (!exists($found_sdist_ids{$sstr->distribution})) {
2696 my $sdist = $editor->retrieve_serial_distribution($sstr->distribution) or return $editor->die_event;
2697 return $editor->die_event unless
2698 $editor->allowed("ADMIN_SERIAL_STREAM", $sdist->holding_lib);
2699 $found_sdist_ids{$sstr->distribution} = 1;
2702 if( $sstr->isdeleted ) {
2703 $evt = _delete_sstr( $editor, $override, $sstr);
2704 } elsif( $sstr->isnew ) {
2705 $evt = _create_sstr( $editor, $sstr );
2707 $evt = _update_sstr( $editor, $override, $sstr );
2712 $logger->info("stream-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2716 $logger->debug("stream-alter: done updating stream batch");
2718 $logger->info("stream-alter successfully updated ".scalar(@$sstrs)." streams");
2723 my ($editor, $override, $sstr) = @_;
2724 $logger->info("stream-alter: delete stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2725 my $sitems = $editor->search_serial_item(
2726 { stream => $sstr->id }, { limit => 1 } ); #TODO: 'deleted' support?
2727 return OpenILS::Event->new(
2728 'SERIAL_STREAM_HAS_ITEMS', payload => $sstr->id ) if (@$sitems);
2730 return $editor->event unless $editor->delete_serial_stream($sstr);
2735 my ($editor, $sstr) = @_;
2737 $logger->info("stream-alter: new stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2738 return $editor->event unless $editor->create_serial_stream($sstr);
2743 my ($editor, $override, $sstr) = @_;
2745 $logger->info("stream-alter: retrieving stream ".$sstr->id);
2746 my $orig_sstr = $editor->retrieve_serial_stream($sstr->id);
2748 $logger->info("stream-alter: original stream ".OpenSRF::Utils::JSON->perl2JSON($orig_sstr));
2749 $logger->info("stream-alter: updated stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2750 return $editor->event unless $editor->update_serial_stream($sstr);
2754 __PACKAGE__->register_method(
2755 method => "serial_stream_retrieve_batch",
2757 api_name => "open-ils.serial.stream.batch.retrieve"
2760 sub serial_stream_retrieve_batch {
2761 my( $self, $client, $ids ) = @_;
2762 $logger->info("Fetching streams @$ids");
2763 return $U->cstorereq(
2764 "open-ils.cstore.direct.serial.stream.search.atomic",
2770 ##########################################################################
2773 __PACKAGE__->register_method(
2774 method => 'sum_alter',
2775 api_name => 'open-ils.serial.basic_summary.batch.update',
2779 desc => 'Receives an array of one or more summaries and updates the database as needed',
2781 name => 'authtoken',
2782 desc => 'Authtoken for current user session',
2787 desc => 'Array of basic summaries',
2793 desc => 'Returns 1 if successful, event if failed',
2799 __PACKAGE__->register_method(
2800 method => 'sum_alter',
2801 api_name => 'open-ils.serial.supplement_summary.batch.update',
2805 desc => 'Receives an array of one or more summaries and updates the database as needed',
2807 name => 'authtoken',
2808 desc => 'Authtoken for current user session',
2813 desc => 'Array of supplement summaries',
2819 desc => 'Returns 1 if successful, event if failed',
2825 __PACKAGE__->register_method(
2826 method => 'sum_alter',
2827 api_name => 'open-ils.serial.index_summary.batch.update',
2831 desc => 'Receives an array of one or more summaries and updates the database as needed',
2833 name => 'authtoken',
2834 desc => 'Authtoken for current user session',
2839 desc => 'Array of index summaries',
2845 desc => 'Returns 1 if successful, event if failed',
2852 my( $self, $conn, $auth, $sums ) = @_;
2853 return 1 unless ref $sums;
2855 $self->api_name =~ /serial\.(\w*)_summary/;
2858 my( $reqr, $evt ) = $U->checkses($auth);
2859 return $evt if $evt;
2860 my $editor = new_editor(requestor => $reqr, xact => 1);
2861 my $override = $self->api_name =~ /override/;
2863 my %found_sdist_ids;
2864 for my $sum (@$sums) {
2865 if (!exists($found_sdist_ids{$sum->distribution})) {
2866 my $sdist = $editor->retrieve_serial_distribution($sum->distribution) or return $editor->die_event;
2867 return $editor->die_event unless
2868 $editor->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2869 $found_sdist_ids{$sum->distribution} = 1;
2872 # XXX: (for now, at least) summaries should be created/deleted by the distribution functions
2873 if( $sum->isdeleted ) {
2874 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2875 } elsif( $sum->isnew ) {
2876 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2878 $evt = _update_sum( $editor, $override, $sum, $type );
2883 $logger->info("${type}_summary-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2887 $logger->debug("${type}_summary-alter: done updating ${type}_summary batch");
2889 $logger->info("${type}_summary-alter successfully updated ".scalar(@$sums)." ${type}_summaries");
2894 my ($editor, $override, $sum, $type) = @_;
2896 $logger->info("${type}_summary-alter: retrieving ${type}_summary ".$sum->id);
2897 my $retrieve_method = "retrieve_serial_${type}_summary";
2898 my $orig_sum = $editor->$retrieve_method($sum->id);
2900 $logger->info("${type}_summary-alter: original ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($orig_sum));
2901 $logger->info("${type}_summary-alter: updated ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($sum));
2902 my $update_method = "update_serial_${type}_summary";
2903 return $editor->event unless $editor->$update_method($sum);
2907 __PACKAGE__->register_method(
2908 method => "serial_summary_retrieve_batch",
2910 api_name => "open-ils.serial.basic_summary.batch.retrieve"
2913 __PACKAGE__->register_method(
2914 method => "serial_summary_retrieve_batch",
2916 api_name => "open-ils.serial.supplement_summary.batch.retrieve"
2919 __PACKAGE__->register_method(
2920 method => "serial_summary_retrieve_batch",
2922 api_name => "open-ils.serial.index_summary.batch.retrieve"
2925 sub serial_summary_retrieve_batch {
2926 my( $self, $client, $ids ) = @_;
2928 $self->api_name =~ /serial\.(\w*)_summary/;
2931 $logger->info("Fetching ${type}_summaries @$ids");
2932 return $U->cstorereq(
2933 "open-ils.cstore.direct.serial.".$type."_summary.search.atomic",
2939 ##########################################################################
2942 __PACKAGE__->register_method(
2943 "method" => "bre_by_identifier",
2944 "api_name" => "open-ils.serial.biblio.record_entry.by_identifier",
2947 "desc" => "Find instances of biblio.record_entry given a search token" .
2948 " that could be a value for any identifier defined in " .
2949 "config.metabib_field",
2951 {"desc" => "Search token", "type" => "string"},
2952 {"desc" => "Options: require_subscriptions, add_mvr, is_actual_id" .
2953 ", id_list (all boolean)", "type" => "object"}
2956 "desc" => "Any matching BREs, or if the add_mvr option is true, " .
2957 "objects with a 'bre' key/value pair, and an 'mvr' " .
2958 "key-value pair. BREs have subscriptions fleshed on.",
2964 sub bre_by_identifier {
2965 my ($self, $client, $term, $options) = @_;
2967 return new OpenILS::Event("BAD_PARAMS") unless $term;
2970 my $e = new_editor();
2974 if ($options->{"is_actual_id"}) {
2978 $e->search_config_metabib_field({"field_class" => "identifier"})
2979 or return $e->die_event;
2981 my @identifiers = map { $_->name } @$cmf;
2982 my $query = join(" || ", map { "id|$_: $term" } @identifiers);
2984 my $search = create OpenSRF::AppSession("open-ils.search");
2985 my $search_result = $search->request(
2986 "open-ils.search.biblio.multiclass.query.staff", {}, $query
2988 $search->disconnect;
2990 # Un-nest results. They tend to look like [[1],[2],[3]] for some reason.
2991 @ids = map { @{$_} } @{$search_result->{"ids"}};
2998 if ($options->{"id_list"}) {
3000 $client->respond($_) foreach (@ids);
3005 my $bre = $e->search_biblio_record_entry([
3007 "flesh" => 2, "flesh_fields" => {
3008 "bre" => ["subscriptions"],
3009 "ssub" => ["owning_lib"]
3012 ]) or return $e->die_event;
3014 if (@$bre && $options->{"require_subscriptions"}) {
3015 $bre = [ grep { @{$_->subscriptions} } @$bre ];
3020 if (@$bre) { # re-evaluate after possible grep
3021 if ($options->{"add_mvr"}) {
3023 {"bre" => $_, "mvr" => _get_mvr($_->id)}
3026 $client->respond($_) foreach (@$bre);
3033 __PACKAGE__->register_method(
3034 "method" => "get_items_by",
3035 "api_name" => "open-ils.serial.items.receivable.by_subscription",
3038 "desc" => "Return all receivable items under a given subscription",
3040 {"desc" => "Authtoken", "type" => "string"},
3041 {"desc" => "Subscription ID", "type" => "number"},
3044 "desc" => "All receivable items under a given subscription",
3045 "type" => "object", "class" => "sitem"
3050 __PACKAGE__->register_method(
3051 "method" => "get_items_by",
3052 "api_name" => "open-ils.serial.items.receivable.by_issuance",
3055 "desc" => "Return all receivable items under a given issuance",
3057 {"desc" => "Authtoken", "type" => "string"},
3058 {"desc" => "Issuance ID", "type" => "number"},
3061 "desc" => "All receivable items under a given issuance",
3062 "type" => "object", "class" => "sitem"
3067 __PACKAGE__->register_method(
3068 "method" => "get_items_by",
3069 "api_name" => "open-ils.serial.items.by_issuance",
3072 "desc" => "Return all items under a given issuance",
3074 {"desc" => "Authtoken", "type" => "string"},
3075 {"desc" => "Issuance ID", "type" => "number"},
3078 "desc" => "All items under a given issuance",
3079 "type" => "object", "class" => "sitem"
3085 my ($self, $client, $auth, $term, $opts) = @_;
3087 # Not to be used in the json_query, but after limiting by perm check.
3088 $opts = {} unless ref $opts eq "HASH";
3089 $opts->{"limit"} ||= 10000; # some existing users may want all results
3090 $opts->{"offset"} ||= 0;
3091 $opts->{"limit"} = int($opts->{"limit"});
3092 $opts->{"offset"} = int($opts->{"offset"});
3094 my $e = new_editor("authtoken" => $auth);
3095 return $e->die_event unless $e->checkauth;
3097 my $by = ($self->api_name =~ /by_(\w+)$/)[0];
3098 my $receivable = ($self->api_name =~ /receivable/);
3101 "issuance" => {"issuance" => $term},
3102 "subscription" => {"+siss" => {"subscription" => $term}}
3105 my $item_rows = $e->json_query(
3107 "select" => {"sitem" => ["id"], "sdist" => ["holding_lib"]},
3111 "sstr" => {"join" => {"sdist" => {}}}
3115 %{$where{$by}}, $receivable ? ("date_received" => undef) : ()
3117 "order_by" => {"sitem" => ["id"]}
3119 ) or return $e->die_event;
3121 return undef unless @$item_rows;
3125 foreach (@$item_rows) {
3126 last if $returned >= $opts->{"limit"};
3127 next unless $e->allowed("RECEIVE_SERIAL", $_->{"holding_lib"});
3128 if ($skipped < $opts->{"offset"}) {
3134 $e->retrieve_serial_item([
3138 "sitem" => [qw/stream issuance unit creator editor/],
3139 "sstr" => ["distribution"],
3140 "sdist" => ["holding_lib"]
3152 __PACKAGE__->register_method(
3153 "method" => "get_receivable_issuances",
3154 "api_name" => "open-ils.serial.issuances.receivable",
3157 "desc" => "Return all issuances with receivable items given " .
3158 "a subscription ID",
3160 {"desc" => "Authtoken", "type" => "string"},
3161 {"desc" => "Subscription ID", "type" => "number"},
3164 "desc" => "All issuances with receivable items " .
3165 "(but not the items themselves)", "type" => "object"
3170 sub get_receivable_issuances {
3171 my ($self, $client, $auth, $sub_id) = @_;
3173 my $e = new_editor("authtoken" => $auth);
3174 return $e->die_event unless $e->checkauth;
3178 my $issuance_ids = $e->json_query({
3181 {"transform" => "distinct", "column" => "id"},
3185 "from" => {"siss" => "sitem"},
3187 "subscription" => $sub_id,
3188 "+sitem" => {"date_received" => undef}
3191 "siss" => {"date_published" => {"direction" => "asc"}}
3194 }) or return $e->die_event;
3196 $client->respond($e->retrieve_serial_issuance($_->{"id"}))
3197 foreach (@$issuance_ids);
3204 __PACKAGE__->register_method(
3205 "method" => "get_routing_list_users",
3206 "api_name" => "open-ils.serial.routing_list_users.fleshed_and_ordered",
3209 "desc" => "Return all routing list users with reader fleshed " .
3210 "(with card and home_ou) for a given stream ID, sorted by pos",
3212 {"desc" => "Authtoken", "type" => "string"},
3213 {"desc" => "Stream ID (int or array of ints)", "type" => "mixed"},
3216 "desc" => "Stream of routing list users", "type" => "object",
3222 sub get_routing_list_users {
3223 my ($self, $client, $auth, $stream_id) = @_;
3225 my $e = new_editor("authtoken" => $auth);
3226 return $e->die_event unless $e->checkauth;
3228 my $users = $e->search_serial_routing_list_user([
3229 {"stream" => $stream_id}, {
3230 "order_by" => {"srlu" => "pos"},
3233 "srlu" => [qw/reader stream/],
3234 "au" => [qw/card home_ou/],
3235 "sstr" => ["distribution"]
3238 ]) or return $e->die_event;
3240 return undef unless @$users;
3242 # The ADMIN_SERIAL_STREAM permission is used simply to avoid the
3243 # need for any new permission. The context OU will be the same
3244 # for every result of the above query, so we need only check once.
3245 return $e->die_event unless $e->allowed(
3246 "ADMIN_SERIAL_STREAM", $users->[0]->stream->distribution->holding_lib
3251 my @users = map { $_->stream($_->stream->id); $_ } @$users;
3252 @users = sort { $a->stream cmp $b->stream } @users if
3253 ref $stream_id eq "ARRAY";
3255 $client->respond($_) for @users;
3261 __PACKAGE__->register_method(
3262 "method" => "replace_routing_list_users",
3263 "api_name" => "open-ils.serial.routing_list_users.replace",
3265 "desc" => "Replace all routing list users on the specified streams " .
3266 "with those in the list argument",
3268 {"desc" => "Authtoken", "type" => "string"},
3269 {"desc" => "List of srlu objects", "type" => "array"},
3272 "desc" => "event on failure, undef on success"
3277 sub replace_routing_list_users {
3278 my ($self, $client, $auth, $users) = @_;
3280 return undef unless ref $users eq "ARRAY";
3282 if (grep { ref $_ ne "Fieldmapper::serial::routing_list_user" } @$users) {
3283 return new OpenILS::Event("BAD_PARAMS", "note" => "Only srlu objects");
3286 my $e = new_editor("authtoken" => $auth, "xact" => 1);
3287 return $e->die_event unless $e->checkauth;
3289 my %streams_ok = ();
3292 foreach my $user (@$users) {
3293 unless (exists $streams_ok{$user->stream}) {
3294 my $stream = $e->retrieve_serial_stream([
3297 "flesh_fields" => {"sstr" => ["distribution"]}
3299 ]) or return $e->die_event;
3301 "ADMIN_SERIAL_STREAM", $stream->distribution->holding_lib
3302 ) or return $e->die_event;
3304 my $to_delete = $e->search_serial_routing_list_user(
3305 {"stream" => $user->stream}
3306 ) or return $e->die_event;
3309 "Deleting srlu: [" .
3310 join(", ", map { $_->id; } @$to_delete) .
3314 foreach (@$to_delete) {
3315 $e->delete_serial_routing_list_user($_) or
3316 return $e->die_event;
3319 $streams_ok{$user->stream} = 1;
3322 next if $user->isdeleted;
3326 $e->create_serial_routing_list_user($user) or return $e->die_event;
3329 $e->commit or return $e->die_event;
3333 __PACKAGE__->register_method(
3334 "method" => "get_records_with_marc_85x",
3335 "api_name"=>"open-ils.serial.caption_and_pattern.find_legacy_by_bib_record",
3338 "desc" => "Return the specified BRE itself and/or any related SRE ".
3339 "whenever they have 853-855 tags",
3341 {"desc" => "Authtoken", "type" => "string"},
3342 {"desc" => "bib record ID", "type" => "number"},
3345 "desc" => "objects, either bre or sre", "type" => "object"
3350 sub get_records_with_marc_85x { # specifically, 853-855
3351 my ($self, $client, $auth, $bre_id) = @_;
3353 my $e = new_editor("authtoken" => $auth);
3354 return $e->die_event unless $e->checkauth;
3356 my $bre = $e->search_biblio_record_entry([
3357 {"id" => $bre_id, "deleted" => "f"}, {
3359 "flesh_fields" => {"bre" => [qw/creator editor owner/]}
3361 ]) or return $e->die_event;
3363 return undef unless @$bre;
3366 my $record = MARC::Record->new_from_xml($bre->marc);
3367 $client->respond($bre) if $record->field("85[3-5]");
3368 # XXX Is passing a regex to ->field() an abuse of MARC::Record ?
3370 my $sres = $e->search_serial_record_entry([
3371 {"record" => $bre_id, "deleted" => "f"}, {
3373 "flesh_fields" => {"sre" => [qw/creator editor owning_lib/]}
3375 ]) or return $e->die_event;
3379 foreach my $sre (@$sres) {
3380 $client->respond($sre) if
3381 MARC::Record->new_from_xml($sre->marc)->field("85[3-5]");
3387 __PACKAGE__->register_method(
3388 "method" => "create_scaps_from_marcxml",
3389 "api_name" => "open-ils.serial.caption_and_pattern.create_from_records",
3392 "desc" => "Create caption and pattern objects from 853-855 tags " .
3393 "in MARCXML documents",
3395 {"desc" => "Authtoken", "type" => "string"},
3396 {"desc" => "Subscription ID", "type" => "number"},
3397 {"desc" => "list of MARCXML documents as strings",
3401 "desc" => "Newly created caption and pattern objects",
3402 "type" => "object", "class" => "scap"
3407 sub create_scaps_from_marcxml {
3408 my ($self, $client, $auth, $sub_id, $docs) = @_;
3410 return undef unless ref $docs eq "ARRAY";
3412 my $e = new_editor("authtoken" => $auth, "xact" => 1);
3413 return $e->die_event unless $e->checkauth;
3415 # Retrieve the subscription just for perm checking (whether we can create
3416 # scaps at the owning lib).
3417 my $sub = $e->retrieve_serial_subscription($sub_id) or return $e->die_event;
3418 return $e->die_event unless
3419 $e->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $sub->owning_lib);
3421 foreach my $record (map { MARC::Record->new_from_xml($_) } @$docs) {
3422 foreach my $field ($record->field("85[3-5]")) {
3423 my $scap = new Fieldmapper::serial::caption_and_pattern;
3424 $scap->subscription($sub_id);
3425 $scap->type($MFHD_NAMES_BY_TAG{$field->tag});
3426 $scap->pattern_code(
3427 OpenSRF::Utils::JSON->perl2JSON(
3428 [ $field->indicator(1), $field->indicator(2),
3429 map { @$_ } $field->subfields ] # flattens nested array
3432 $e->create_serial_caption_and_pattern($scap) or
3433 return $e->die_event;
3434 $client->respond($e->data);
3438 $e->commit or return $e->die_event;
3442 # All these _clone_foo() functions could possibly have been consolidated into
3443 # one clever function, but it's faster to get things working this way.
3444 sub _clone_subscription {
3445 my ($sub, $bib_id, $e) = @_;
3448 my $new_sub = $sub->clone;
3449 $new_sub->record_entry(int $bib_id) if $bib_id;
3451 $new_sub->clear_distributions;
3452 $new_sub->clear_notes;
3453 $new_sub->clear_scaps;
3455 $e->create_serial_subscription($new_sub) or return $e->die_event;
3457 my $new_sub_id = $e->data->id;
3459 foreach my $dist (@{$sub->distributions}) {
3460 my $r = _clone_distribution($dist, $new_sub_id, $e);
3461 return $r if $U->event_code($r);
3465 foreach my $note (@{$sub->notes}) {
3466 my $r = _clone_subscription_note($note, $new_sub_id, $e);
3467 return $r if $U->event_code($r);
3471 foreach my $scap (@{$sub->scaps}) {
3472 my $r = _clone_caption_and_pattern($scap, $new_sub_id, $e);
3473 return $r if $U->event_code($r);
3479 sub _clone_distribution {
3480 my ($dist, $sub_id, $e) = @_;
3482 my $new_dist = $dist->clone;
3483 $new_dist->clear_id;
3484 $new_dist->clear_notes;
3485 $new_dist->clear_streams;
3486 $new_dist->subscription($sub_id);
3488 $e->create_serial_distribution($new_dist) or return $e->die_event;
3489 my $new_dist_id = $e->data->id;
3492 foreach my $stream (@{$dist->streams}) {
3493 my $r = _clone_stream($stream, $new_dist_id, $e);
3494 return $r if $U->event_code($r);
3497 # clone distribution notes
3498 foreach my $note (@{$dist->notes}) {
3499 my $r = _clone_distribution_note($note, $new_dist_id, $e);
3500 return $r if $U->event_code($r);
3503 return $new_dist_id;
3506 sub _clone_subscription_note {
3507 my ($note, $sub_id, $e) = @_;
3509 my $new_note = $note->clone;
3510 $new_note->clear_id;
3511 $new_note->creator($e->requestor->id);
3512 $new_note->create_date("now");
3513 $new_note->subscription($sub_id);
3515 $e->create_serial_subscription_note($new_note) or return $e->die_event;
3516 return $e->data->id;
3519 sub _clone_caption_and_pattern {
3520 my ($scap, $sub_id, $e) = @_;
3522 my $new_scap = $scap->clone;
3523 $new_scap->clear_id;
3524 $new_scap->subscription($sub_id);
3526 $e->create_serial_caption_and_pattern($new_scap) or return $e->die_event;
3527 return $e->data->id;
3530 sub _clone_distribution_note {
3531 my ($note, $dist_id, $e) = @_;
3533 my $new_note = $note->clone;
3534 $new_note->clear_id;
3535 $new_note->creator($e->requestor->id);
3536 $new_note->create_date("now");
3537 $new_note->distribution($dist_id);
3539 $e->create_serial_distribution_note($new_note) or return $e->die_event;
3540 return $e->data->id;
3544 my ($stream, $dist_id, $e) = @_;
3546 my $new_stream = $stream->clone;
3547 $new_stream->clear_id;
3548 $new_stream->clear_routing_list_users;
3549 $new_stream->distribution($dist_id);
3551 $e->create_serial_stream($new_stream) or return $e->die_event;
3552 my $new_stream_id = $e->data->id;
3554 # clone routing list users
3555 foreach my $user (@{$stream->routing_list_users}) {
3556 my $r = _clone_routing_list_user($user, $new_stream_id, $e);
3557 return $r if $U->event_code($r);
3560 return $new_stream_id;
3563 sub _clone_routing_list_user {
3564 my ($user, $stream_id, $e) = @_;
3566 my $new_user = $user->clone;
3567 $new_user->clear_id;
3568 $new_user->stream($stream_id);
3570 $e->create_serial_routing_list_user($new_user) or return $e->die_event;
3571 return $e->data->id;
3574 __PACKAGE__->register_method(
3575 "method" => "clone_subscription",
3576 "api_name" => "open-ils.serial.subscription.clone",
3578 "desc" => q{Clone a subscription, including its attending distributions,
3579 streams, captions and patterns, routing list users, distribution
3580 notes and subscription notes. Do not include holdings-specific
3581 things, like issuances, items, units, summaries. Attach the
3582 clone either to the same bib record as the original, or to one
3585 {"desc" => "Authtoken", "type" => "string"},
3586 {"desc" => "Subscription ID", "type" => "number"},
3587 {"desc" => "Bib Record ID (optional)", "type" => "number"}
3590 "desc" => "ID of the new subscription", "type" => "number"
3595 sub clone_subscription {
3596 my ($self, $client, $auth, $sub_id, $bib_id) = @_;
3598 my $e = new_editor("authtoken" => $auth, "xact" => 1);
3599 return $e->die_event unless $e->checkauth;
3601 my $sub = $e->retrieve_serial_subscription([
3605 "ssub" => [qw/distributions notes scaps/],
3606 "sdist" => [qw/streams notes/],
3607 "sstr" => ["routing_list_users"]
3610 ]) or return $e->die_event;
3612 # ADMIN_SERIAL_SUBSCRIPTION will have to be good enough as a
3613 # catch-all permisison for this operation.
3614 return $e->die_event unless
3615 $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
3617 my $result = _clone_subscription($sub, $bib_id, $e);
3619 return $e->die_event($result) if $U->event_code($result);
3621 $e->commit or return $e->die_event;