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 OpenILS::Utils::DateTime 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 'subscription' => 'ssub',
70 'distribution' => 'sdist',
74 # helper method for conforming dates to ISO8601
79 foreach my $field (@$fields) {
80 $item->$field(clean_ISO8601($item->$field)) if $item->$field;
88 "open-ils.search.biblio.record.mods_slim.retrieve",
94 ##########################################################################
97 __PACKAGE__->register_method(
98 method => "create_item_safely",
99 api_name => "open-ils.serial.item.create",
104 desc => q/Creates any number of items, respecting only a few of the
105 submitted fields, as the user shouldn't be able to freely set certain
108 {name=> "authtoken", desc => "Authtoken for current user session",
110 {name => "item", desc => "serial item",
111 type => "object", class => "sitem"},
113 desc => "optional: how many items to make " .
114 "(default 1; 1-100 permitted)",
118 desc => "created items (a stream of them)",
119 type => "object", class => "sitem"
123 __PACKAGE__->register_method(
124 method => "update_item_safely",
125 api_name => "open-ils.serial.item.update",
130 desc => q/Edit a serial item, respecting only a few of the
131 submitted fields, as the user shouldn't be able to freely set certain
134 {name=> "authtoken", desc => "Authtoken for current user session",
136 {name => "item", desc => "serial item",
137 type => "object", class => "sitem"},
140 desc => "created item", type => "object", class => "sitem"
145 sub _set_safe_item_fields {
148 my $requestor_id = shift;
149 # extra fields remain in @_
151 $dest->edit_date("now");
152 $dest->editor($requestor_id);
154 my @fields = qw/date_expected date_received status/;
156 for my $field (@fields, @_) {
157 $dest->$field($source->$field);
161 sub update_item_safely {
162 my ($self, $client, $auth, $item) = @_;
164 my $e = new_editor("xact" => 1, "authtoken" => $auth);
165 $e->checkauth or return $e->die_event;
167 my $orig = $e->retrieve_serial_item([
169 "flesh" => 2, "flesh_fields" => {
170 "sitem" => ["stream"], "sstr" => ["distribution"]
173 ]) or return $e->die_event;
175 return $e->die_event unless $e->allowed(
176 "ADMIN_SERIAL_ITEM", $orig->stream->distribution->holding_lib
179 _set_safe_item_fields($orig, $item, $e->requestor->id);
180 $e->update_serial_item($orig) or return $e->die_event;
182 $client->respond($e->retrieve_serial_item($item->id));
183 $e->commit or return $e->die_event;
187 sub create_item_safely {
188 my ($self, $client, $auth, $item, $count) = @_;
192 return new OpenILS::Event(
193 "BAD_PARAMS", note => "Count should be from 1 to 100"
194 ) unless $count >= 1 and $count <= 100;
196 my $e = new_editor("xact" => 1, "authtoken" => $auth);
197 $e->checkauth or return $e->die_event;
199 my $stream = $e->retrieve_serial_stream([
201 "flesh" => 1, "flesh_fields" => {"sstr" => ["distribution"]}
203 ]) or return $e->die_event;
205 return $e->die_event unless $e->allowed(
206 "ADMIN_SERIAL_ITEM", $stream->distribution->holding_lib
209 for (my $i = 0; $i < $count; $i++) {
210 my $actual = new Fieldmapper::serial::item;
211 $actual->creator($e->requestor->id);
212 _set_safe_item_fields(
213 $actual, $item, $e->requestor->id, "issuance", "stream"
216 $e->create_serial_item($actual) or return $e->die_event;
217 $client->respond($e->data);
220 $e->commit or return $e->die_event;
224 __PACKAGE__->register_method(
225 method => 'fleshed_item_alter',
226 api_name => 'open-ils.serial.item.fleshed.batch.update',
230 desc => 'Receives an array of one or more items and updates the database as needed',
233 desc => 'Authtoken for current user session',
238 desc => 'Array of fleshed items',
244 desc => 'Returns 1 if successful, event if failed',
250 sub fleshed_item_alter {
251 my( $self, $conn, $auth, $items ) = @_;
252 return 1 unless ref $items;
253 my( $reqr, $evt ) = $U->checkses($auth);
255 my $editor = new_editor(requestor => $reqr, xact => 1);
256 my $override = $self->api_name =~ /override/;
260 my %siss_to_potentially_delete;
262 for my $item (@$items) {
263 my $sstr_id = ref $item->stream ? $item->stream->id : $item->stream;
264 if (!exists($found_sstr_ids{$sstr_id})) {
266 if (ref $item->stream) {
267 $sstr = $item->stream;
269 $sstr = $editor->retrieve_serial_stream($item->stream) or return $editor->die_event;
271 if (!exists($found_sdist_ids{$sstr->distribution})) {
272 my $sdist = $editor->retrieve_serial_distribution($sstr->distribution) or return $editor->die_event;
273 return $editor->die_event unless
274 $editor->allowed("ADMIN_SERIAL_STREAM", $sdist->holding_lib);
275 $found_sdist_ids{$sstr->distribution} = 1;
277 $found_sstr_ids{$sstr_id} = 1;
280 $item->editor($editor->requestor->id);
281 $item->edit_date('now');
283 if( $item->isdeleted ) {
284 my $siss_id = ref $item->issuance ? $item->issuance->id : $item->issuance;
285 $siss_to_potentially_delete{$siss_id}++;
286 # We don't want to do a bunch of resetting churn for multiple items
287 # in the same unit/dist, so just gather ids for now
288 push(@deleted_items, $item);
289 } elsif( $item->isnew ) {
290 # TODO: reconsider this
291 # if the item has a new issuance, create the issuance first
292 if (ref $item->issuance eq 'Fieldmapper::serial::issuance' and $item->issuance->isnew) {
293 fleshed_issuance_alter($self, $conn, $auth, [$item->issuance]);
295 _cleanse_dates($item, ['date_expected','date_received']);
296 $evt = _create_sitem( $editor, $item );
298 _cleanse_dates($item, ['date_expected','date_received']);
299 $evt = _update_sitem( $editor, $override, $item );
303 if (@deleted_items) {
304 # First, reset as a batch any assigned to units. This cleans up units
305 # and rebuilds summaries as needed
307 # XXX: if we ever add a 'deleted' flag to items, we may want to
308 # preserve rather than reset the received information
309 my @unit_items = grep {$_->unit} @deleted_items;
310 my $reset_info = $self->method_lookup('open-ils.serial.reset_items')->run($auth, \@unit_items) if @unit_items;
312 # Next, do the actual deletes, unless we got an event
313 if ($U->event_code($reset_info)) {
316 foreach my $item (@deleted_items) {
317 $evt = _delete_sitem( $editor, $override, $item);
323 $logger->info("fleshed item-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
327 if( %siss_to_potentially_delete ) {
328 foreach my $id (keys %siss_to_potentially_delete) {
329 my $issuance = $editor->retrieve_serial_issuance([
331 "flesh" => 1, "flesh_fields" => {
337 $logger->warn("fleshed item-alter failed to retrieve issuance $id to potenitally delete");
339 return $editor->die_event;
341 unless (@{ $issuance->items }) {
342 $logger->info("fleshed item-alter deleting issuance $id as it has no items left");
343 $evt = _delete_siss( $editor, $override, $issuance);
345 $logger->info("fleshed item-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
352 $logger->debug("item-alter: done updating item batch");
354 $logger->info("fleshed item-alter successfully updated ".scalar(@$items)." items");
359 my ($editor, $override, $item) = @_;
360 $logger->info("item-alter: delete item ".OpenSRF::Utils::JSON->perl2JSON($item));
361 return $editor->event unless $editor->delete_serial_item($item);
366 my ($editor, $item) = @_;
368 $item->creator($editor->requestor->id);
369 $item->create_date('now');
371 $logger->info("item-alter: new item ".OpenSRF::Utils::JSON->perl2JSON($item));
372 return $editor->event unless $editor->create_serial_item($item);
377 my ($editor, $override, $item) = @_;
379 $logger->info("item-alter: retrieving item ".$item->id);
380 my $orig_item = $editor->retrieve_serial_item($item->id);
382 $logger->info("item-alter: original item ".OpenSRF::Utils::JSON->perl2JSON($orig_item));
383 $logger->info("item-alter: updated item ".OpenSRF::Utils::JSON->perl2JSON($item));
384 return $editor->event unless $editor->update_serial_item($item);
388 __PACKAGE__->register_method(
389 method => "fleshed_serial_item_retrieve_batch",
391 api_name => "open-ils.serial.item.fleshed.batch.retrieve"
394 sub fleshed_serial_item_retrieve_batch {
395 my( $self, $client, $ids ) = @_;
396 # FIXME: permissions?
397 $logger->info("Fetching fleshed serial items @$ids");
398 return $U->cstorereq(
399 "open-ils.cstore.direct.serial.item.search.atomic",
402 flesh_fields => {sitem => [ qw/issuance creator editor stream unit notes/ ], sunit => ["call_number"], siss => [qw/creator editor subscription/]}
407 ##########################################################################
410 __PACKAGE__->register_method(
411 method => 'fleshed_issuance_alter',
412 api_name => 'open-ils.serial.issuance.fleshed.batch.update',
416 desc => 'Receives an array of one or more issuances and updates the database as needed',
419 desc => 'Authtoken for current user session',
424 desc => 'Array of fleshed issuances',
430 desc => 'Returns 1 if successful, event if failed',
436 sub fleshed_issuance_alter {
437 my( $self, $conn, $auth, $issuances ) = @_;
438 return 1 unless ref $issuances;
439 my( $reqr, $evt ) = $U->checkses($auth);
441 my $editor = new_editor(authtoken => $auth, requestor => $reqr, xact => 1);
442 my $override = $self->api_name =~ /override/;
446 for my $issuance (@$issuances) {
447 my $ssub_id = ref $issuance->subscription ? $issuance->subscription->id : $issuance->subscription;
448 if (!exists($found_ssub_ids{$ssub_id})) {
450 if (ref $issuance->subscription) {
451 $owning_lib_id = $issuance->subscription->owning_lib;
453 my $ssub = $editor->retrieve_serial_subscription($issuance->subscription) or return $editor->die_event;
454 $owning_lib_id = $ssub->owning_lib;
456 return $editor->die_event unless
457 $editor->allowed("ADMIN_SERIAL_SUBSCRIPTION", $owning_lib_id);
458 $found_ssub_ids{$ssub_id} = 1;
461 my $issuanceid = $issuance->id;
462 $issuance->editor($editor->requestor->id);
463 $issuance->edit_date('now');
465 if( $issuance->isdeleted ) {
466 $evt = _delete_siss( $editor, $override, $issuance);
467 $regen_ssub_ids{$ssub_id} = 1;
468 } elsif( $issuance->isnew ) {
469 _cleanse_dates($issuance, ['date_published']);
470 $evt = _create_siss( $editor, $issuance );
472 _cleanse_dates($issuance, ['date_published']);
473 $evt = _update_siss( $editor, $override, $issuance );
480 # if we deleted any issuances, update the summaries
481 # for all dists in those ssubs
482 my @ssub_ids = keys %regen_ssub_ids;
483 $evt = _regenerate_summaries($editor, {'ssub_ids' => \@ssub_ids}) if @ssub_ids;
487 $logger->info("fleshed issuance-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
492 $logger->debug("issuance-alter: done updating issuance batch");
494 $logger->info("fleshed issuance-alter successfully updated ".scalar(@$issuances)." issuances");
499 my ($editor, $override, $issuance) = @_;
500 $logger->info("issuance-alter: delete issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
501 return $editor->event unless $editor->delete_serial_issuance($issuance);
506 my ($editor, $issuance) = @_;
508 $issuance->creator($editor->requestor->id);
509 $issuance->create_date('now');
511 $logger->info("issuance-alter: new issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
512 return $editor->event unless $editor->create_serial_issuance($issuance);
517 my ($editor, $override, $issuance) = @_;
519 $logger->info("issuance-alter: retrieving issuance ".$issuance->id);
520 my $orig_issuance = $editor->retrieve_serial_issuance($issuance->id);
522 $logger->info("issuance-alter: original issuance ".OpenSRF::Utils::JSON->perl2JSON($orig_issuance));
523 $logger->info("issuance-alter: updated issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
524 return $editor->event unless $editor->update_serial_issuance($issuance);
528 __PACKAGE__->register_method(
529 method => "fleshed_serial_issuance_retrieve_batch",
531 api_name => "open-ils.serial.issuance.fleshed.batch.retrieve"
534 sub fleshed_serial_issuance_retrieve_batch {
535 my( $self, $client, $ids ) = @_;
536 # FIXME: permissions?
537 $logger->info("Fetching fleshed serial issuances @$ids");
538 return $U->cstorereq(
539 "open-ils.cstore.direct.serial.issuance.search.atomic",
542 flesh_fields => {siss => [ qw/creator editor subscription/ ]}
546 __PACKAGE__->register_method(
547 method => "pub_fleshed_serial_issuance_retrieve_batch",
548 api_name => "open-ils.serial.issuance.pub_fleshed.batch.retrieve",
551 Public (i.e. OPAC) call for getting at the sub and
552 ultimately the record entry from an issuance
554 params => [{name => 'ids', desc => 'Array of IDs', type => 'array'}],
557 issuance objects, fleshed with subscriptions
563 sub pub_fleshed_serial_issuance_retrieve_batch {
564 my( $self, $client, $ids ) = @_;
565 return [] unless $ids and @$ids;
566 return new_editor()->search_serial_issuance([
570 flesh_fields => {siss => [ qw/subscription/ ]}
575 sub received_siss_by_bib {
576 # XXX this is somewhat wrong in implementation and should not be used in
577 # new places - senator
582 my $args = shift || {};
583 $$args{order} ||= 'asc';
585 my $global = $$args{global} == 0 ? 0 : 1;
587 my $e = new_editor();
588 my $issuances = $e->json_query({
591 $global ? { transform => "min", column => "id", aggregate => 1 } : "id",
596 # We're not really interested in the minimum here. This is
597 # just a way to distinguish issuances whose items have units
598 # from issuances whose items have no units, without altogether
599 # excluding the latter type of issuances.
600 {"transform" => "min", "alias" => "has_units",
601 "column" => "unit", "aggregate" => 1}
607 field => 'subscription',
613 $$args{ou} ? ( join => {
620 fkey => 'distribution'
631 '+ssub' => { record_entry => $bib },
632 $$args{type} ? ( '+siss' => { 'holding_type' => $$args{type} } ) : (),
634 # XXX should we also take specific item statuses into account?
635 date_received => { '!=' => undef },
636 $$args{status} ? ( 'status' => $$args{status} ) : ()
638 $$args{ou} ? ( '+sdist' => {
640 'in' => $U->get_org_descendants($$args{ou}, $$args{depth})
644 $$args{limit} ? ( limit => $$args{limit} ) : (),
645 $$args{offset} ? ( offset => $$args{offset} ) : (),
646 order_by => [{ class => 'siss', field => 'date_published', direction => $$args{order} }],
651 "issuance" => $e->retrieve_serial_issuance($_->{"id"}),
652 "has_units" => $_->{"has_units"} ? 1 : 0
657 __PACKAGE__->register_method(
658 method => 'received_siss_by_bib',
659 api_name => 'open-ils.serial.received_siss.retrieve.by_bib',
664 desc => 'Receives a Bib ID and other optional params and returns "siss" (issuance) objects',
667 desc => 'id of the bre to which the issuances belong',
672 q/A hash of optional arguments. Valid keys and their meanings:
673 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).
674 order := date_published sort direction, either "asc" (chronological, default) or "desc" (reverse chronological)
675 limit := Number of issuances to return. Useful for paging results, or finding the oldest or newest
676 offset := Number of issuance to skip before returning results. Useful for paging.
677 orgid := OU id used to scope retrieval, based on distribution.holding_lib
678 depth := OU depth used to range the scope of orgid
679 type := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
680 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).
688 sub scoped_bib_holdings_summary {
689 # XXX this is somewhat wrong in implementation and should not be used in
690 # new places - senator
694 my $args = shift || {};
696 $args->{order} = 'asc';
698 my ($issuances) = $self->method_lookup('open-ils.serial.received_siss.retrieve.by_bib.atomic')->run( $bibid => $args );
700 # split into issuance type sets
701 my %type_blob = (basic => [], supplement => [], index => []);
702 push @{ $type_blob{ $_->{"issuance"}->holding_type } }, $_->{"issuance"}
705 # generate a statement list for each type
707 for my $type ( keys %type_blob ) {
708 my ($mfhd,$list) = _summarize_contents(new_editor(), $type_blob{$type});
710 return {} if $U->event_code($mfhd); # _summarize_contents() failed, bad data?
712 $statement_blob{$type} = $list;
715 return \%statement_blob;
717 __PACKAGE__->register_method(
718 method => 'scoped_bib_holdings_summary',
719 api_name => 'open-ils.serial.bib.summary_statements',
723 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',
726 desc => 'id of the bre to which the issuances belong',
731 q/A hash of optional arguments. Valid keys and their meanings:
732 orgid := OU id used to scope retrieval, based on distribution.holding_lib
733 depth := OU depth used to range the scope of orgid
734 type := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
735 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).
743 ##########################################################################
746 __PACKAGE__->register_method(
747 method => 'fleshed_sunit_alter',
748 api_name => 'open-ils.serial.sunit.fleshed.batch.update',
752 desc => 'Receives an array of one or more Units and updates the database as needed',
755 desc => 'Authtoken for current user session',
760 desc => 'Array of fleshed Units',
766 desc => 'Returns 1 if successful, event if failed',
772 sub fleshed_sunit_alter {
773 my( $self, $conn, $auth, $sunits ) = @_;
774 return 1 unless ref $sunits;
775 my( $reqr, $evt ) = $U->checkses($auth);
777 my $editor = new_editor(requestor => $reqr, xact => 1);
778 my $override = $self->api_name =~ /override/;
781 for my $sunit (@$sunits) {
782 my $cn_id = ref $sunit->call_number ? $sunit->call_number->id : $sunit->call_number;
783 if (!exists($found_cn_ids{$cn_id})) {
785 if (ref $sunit->call_number) {
786 $owning_lib_id = $sunit->call_number->owning_lib;
788 my $cn = $editor->retrieve_asset_call_number($sunit->call_number) or return $editor->die_event;
789 $owning_lib_id = $cn->owning_lib;
791 return $editor->die_event unless
792 $editor->allowed("UPDATE_COPY", $owning_lib_id);
793 $found_cn_ids{$cn_id} = 1;
796 if( $sunit->isdeleted ) {
797 $evt = _delete_sunit( $editor, $override, $sunit );
799 $sunit->default_location( $sunit->default_location->id ) if ref $sunit->default_location;
801 if( $sunit->isnew ) {
802 $evt = _create_sunit( $editor, $sunit );
804 $evt = _update_sunit( $editor, $override, $sunit );
810 $logger->info("fleshed sunit-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
814 $logger->debug("sunit-alter: done updating sunit batch");
816 $logger->info("fleshed sunit-alter successfully updated ".scalar(@$sunits)." Units");
821 my ($editor, $override, $sunit) = @_;
822 $logger->info("sunit-alter: delete sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
823 return $editor->event unless $editor->delete_serial_unit($sunit);
828 my ($editor, $sunit) = @_;
830 # The unique barcode constraint does not span asset.copy and serial.unit.
831 # ensure the barcode on the new unit does not collide with an existing
832 # asset.copy barcode.
833 my $existing = $editor->search_asset_copy(
834 {deleted => 'f', barcode => $sunit->barcode})->[0];
837 # The DB will prevent duplicate serial.unit barcodes, but for
838 # consistency (and a more specific error message for the
839 # user), prevent creation attempts on serial unit barcode
840 # collisions as well.
841 $existing = $editor->search_serial_unit(
842 {deleted => 'f', barcode => $sunit->barcode})->[0];
847 return new OpenILS::Event(
848 'SERIAL_UNIT_BARCODE_COLLISION', note =>
849 'Serial unit barcode collides with existing unit/copy barcode',
850 payload => {barcode => $sunit->barcode}
854 $logger->info("sunit-alter: new Unit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
855 return $editor->die_event unless $editor->create_serial_unit($sunit);
860 my ($editor, $override, $sunit) = @_;
862 $logger->info("sunit-alter: retrieving sunit ".$sunit->id);
863 my $orig_sunit = $editor->retrieve_serial_unit($sunit->id);
865 $logger->info("sunit-alter: original sunit ".OpenSRF::Utils::JSON->perl2JSON($orig_sunit));
866 $logger->info("sunit-alter: updated sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
867 return $editor->event unless $editor->update_serial_unit($sunit);
871 __PACKAGE__->register_method(
872 method => "retrieve_unit_list",
874 api_name => "open-ils.serial.unit_list.retrieve"
877 sub retrieve_unit_list {
879 my( $self, $client, @sdist_ids ) = @_;
881 if(ref($sdist_ids[0])) { @sdist_ids = @{$sdist_ids[0]}; }
883 my $e = new_editor();
887 { 'sunit' => [ 'id', 'summary_contents', 'sort_key' ],
888 'sitem' => ['stream'],
889 'sstr' => ['distribution'],
890 'sdist' => [{'column' => 'label', 'alias' => 'sdist_label'}]
897 { 'join' => { 'sunit' => {} } }
902 'distinct' => 'true',
903 'where' => { '+sdist' => {'id' => \@sdist_ids} },
904 'order_by' => [{'class' => 'sunit', 'field' => 'sort_key'}]
907 my $unit_list_entries = $e->json_query($query);
910 foreach my $entry (@$unit_list_entries) {
911 my $value = {'sunit' => $entry->{id}, 'sstr' => $entry->{stream}, 'sdist' => $entry->{distribution}};
912 my $label = $entry->{summary_contents};
913 if (length($label) > 100) {
914 $label = substr($label, 0, 100) . '...'; # limited space in dropdown / menu
916 $label = "[$entry->{sdist_label}/$entry->{stream} #$entry->{id}] " . $label;
917 push (@entries, [$label, OpenSRF::Utils::JSON->perl2JSON($value)]);
925 ##########################################################################
926 # predict and receive methods
928 __PACKAGE__->register_method(
929 method => 'make_predictions',
930 api_name => 'open-ils.serial.make_predictions',
934 desc => 'Receives an ssub id and populates the issuance and item tables',
937 desc => 'Serial Subscription ID',
944 sub make_predictions {
945 my ($self, $conn, $authtoken, $args) = @_;
947 my $ssub_id = $args->{ssub_id};
949 my $editor = OpenILS::Utils::CStoreEditor->new();
950 my $ssub = $editor->retrieve_serial_subscription([$ssub_id]);
951 my $sdists = $editor->search_serial_distribution( [{ subscription => $ssub->id }, { flesh => 1, flesh_fields => {sdist => [ qw/ streams / ]} }] ); #TODO: 'deleted' support?
953 return store_predictions(
954 $self, $conn, $authtoken, $args, $ssub, $sdists,
955 make_prediction_values($self, $conn, $authtoken, $args, $ssub, $sdists, $editor)
959 __PACKAGE__->register_method(
960 method => 'make_prediction_values',
961 api_name => 'open-ils.serial.make_prediction_values',
965 desc => 'Receives an ssub id and returns objects that can be used to populate the issuance and item tables',
968 desc => 'Serial Subscription ID',
975 sub make_prediction_values {
976 my ($self, $conn, $authtoken, $args, $ssub, $sdists, $editor) = @_;
977 $logger->debug('make_prediction_values with args: ' . OpenSRF::Utils::JSON->perl2JSON($args));
979 my $ssub_id = $args->{ssub_id};
981 $editor ||= OpenILS::Utils::CStoreEditor->new();
982 $ssub ||= $editor->retrieve_serial_subscription([$ssub_id]);
983 $sdists ||= $editor->search_serial_distribution( [{ subscription => $ssub->id }, { flesh => 1, flesh_fields => {sdist => [ qw/ streams / ]} }] ); #TODO: 'deleted' support?
985 my $scaps = $editor->search_serial_caption_and_pattern({ subscription => $ssub_id, active => 't'});
986 my $mfhd = MFHD->new(MARC::Record->new());
988 my $total_streams = 0;
990 $total_streams += scalar(@{$_->streams});
992 if ($total_streams < 1) {
994 # XXX TODO new event type
995 return new OpenILS::Event(
996 "BAD_PARAMS", note =>
997 "There are no streams to direct items. Can't predict."
1002 $editor->disconnect;
1003 # XXX TODO new event type
1004 return new OpenILS::Event(
1005 "BAD_PARAMS", note =>
1006 "There are no active caption-and-pattern objects associated " .
1007 "with this subscription. Can't predict."
1013 foreach my $scap (@$scaps) {
1014 my $caption_field = _revive_caption($scap);
1015 $caption_field->update('8' => $link_id);
1016 my $fake_chron_needed = 0;
1017 # if we have missing chron pieces, we will add them later for prediction purposes
1018 if (!$caption_field->enumeration_is_chronology) {
1019 if (!$caption_field->subfield('i') # no year
1020 or !$caption_field->subfield('j')) { # we had a year, but no month or season
1021 $fake_chron_needed = '1';
1024 $mfhd->append_fields($caption_field);
1026 'caption' => $caption_field,
1027 'scap_id' => $scap->id,
1028 'include_base_issuance' => $args->{include_base_issuance},
1029 'num_to_predict' => $args->{num_to_predict},
1030 'end_date' => defined $args->{end_date} ?
1031 $_strp_date->parse_datetime($args->{end_date}) : undef
1033 my $predict_from_siss;
1034 if ($args->{base_issuance}) { # predict from a given issuance
1035 $predict_from_siss = $args->{base_issuance};
1036 } else { # default to predicting from last published
1037 my $last_published = $editor->search_serial_issuance([
1038 {'caption_and_pattern' => $scap->id,
1039 'subscription' => $ssub_id},
1040 {limit => 1, order_by => { siss => "date_published DESC" }}]
1042 if ($last_published->[0]) {
1043 $predict_from_siss = $last_published->[0];
1044 unless ($predict_from_siss->holding_code) {
1045 $editor->disconnect;
1046 # XXX TODO new event type
1047 return new OpenILS::Event(
1048 "BAD_PARAMS", note =>
1049 "Last issuance has no holding code. Can't predict."
1053 $editor->disconnect;
1054 # XXX TODO make a new event type instead of hijacking this one
1055 return new OpenILS::Event(
1056 "BAD_PARAMS", note => "No issuance from which to predict!"
1060 $logger->debug('make_prediction_values reviving holdings: ' . OpenSRF::Utils::JSON->perl2JSON($predict_from_siss));
1061 $options->{predict_from} = _revive_holding($predict_from_siss->holding_code, $caption_field, 1); # fresh MFHD Record, so we simply default to 1 for seqno
1062 if ($fake_chron_needed) {
1063 $options->{faked_chron_date} = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($predict_from_siss->date_published));
1065 $logger->debug('make_prediction_values predicting with options: ' . OpenSRF::Utils::JSON->perl2JSON($options));
1066 push( @predictions, _generate_issuance_values($mfhd, $options) );
1070 $logger->debug('make_prediction_values predictions: ' . OpenSRF::Utils::JSON->perl2JSON(\@predictions));
1071 return \@predictions;
1074 sub store_predictions {
1075 my ($self, $conn, $authtoken, $args, $ssub, $sdists, $predictions) = @_;
1078 foreach my $prediction (@$predictions) {
1079 my $issuance = new Fieldmapper::serial::issuance;
1080 $issuance->isnew(1);
1081 $issuance->label($prediction->{label});
1082 $issuance->date_published($prediction->{date_published}->strftime('%F'));
1083 $issuance->holding_code(OpenSRF::Utils::JSON->perl2JSON($prediction->{holding_code}));
1084 $issuance->holding_type($prediction->{holding_type});
1085 $issuance->caption_and_pattern($prediction->{caption_and_pattern});
1086 $issuance->subscription($ssub->id);
1087 push (@issuances, $issuance);
1090 my $evt = fleshed_issuance_alter($self, $conn, $authtoken, \@issuances);
1091 return $evt if ref $evt;
1094 for (my $i = 0; $i < @issuances; $i++) {
1095 my $date_expected = $$predictions[$i]->{date_published}->add(seconds => interval_to_seconds($ssub->expected_date_offset))->strftime('%F');
1096 my $issuance = $issuances[$i];
1097 #$issuance->label(interval_to_seconds($ssub->expected_date_offset));
1098 foreach my $sdist (@$sdists) {
1099 my $streams = $sdist->streams;
1100 foreach my $stream (@$streams) {
1101 my $item = new Fieldmapper::serial::item;
1103 $item->stream($stream->id);
1104 $item->date_expected($date_expected);
1105 $item->issuance($issuance->id);
1106 push (@items, $item);
1110 fleshed_item_alter($self, $conn, $authtoken, \@items); # FIXME: catch events
1115 # _generate_issuance_values() is an initial attempt at a function which can be used
1116 # to populate an issuance table with a list of predicted issues. It accepts
1117 # a hash ref of options initially defined as:
1118 # caption : the caption field to predict on
1119 # num_to_predict : the number of issues you wish to predict
1120 # 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
1122 # The basic method is to first convert to a single holding if compressed, then
1123 # increment the holding and save the resulting values to @issuances.
1125 # returns @issuance_values, an array of hashrefs containing (formatted
1126 # label, formatted chronology date, formatted estimated arrival date, and an
1127 # array ref of holding subfields as (key, value, key, value ...)) (not a hash
1128 # to protect order and possible duplicate keys), and a holding type.
1130 sub _generate_issuance_values {
1131 my ($mfhd, $options) = @_;
1132 my $caption = $options->{caption};
1133 my $scap_id = $options->{scap_id};
1134 my $include_base_issuance = $options->{include_base_issuance};
1135 my $num_to_predict = $options->{num_to_predict};
1136 my $end_date = $options->{end_date};
1137 my $predict_from = $options->{predict_from}; # MFHD::Holding to predict from
1138 my $faked_chron_date = $options->{faked_chron_date}; # serial does not have a (complete) chronology caption, so add one (temporarily) based on this date
1140 $logger->debug('_generate_issuance_values predict_from: ' . OpenSRF::Utils::JSON->perl2JSON($predict_from));
1142 # Only needed for 'real' MFHD records, not our temp records
1143 # my $link_id = $caption->link_id;
1144 # if(!$predict_from) {
1145 # my $htag = $caption->tag;
1146 # $htag =~ s/^85/86/;
1147 # my @holdings = $mfhd->holdings($htag, $link_id);
1148 # my $last_holding = $holdings[-1];
1150 # #if ($last_holding->is_compressed) {
1151 # # $last_holding->compressed_to_last; # convert to last in range
1153 # $predict_from = $last_holding;
1157 $predict_from->notes('public', []);
1158 # add a note marker for system use (?)
1159 $predict_from->notes('private', ['AUTOGEN']);
1161 # our basic method for dealing with 'faked' chronologies will be to add it in, do the predicting, then take it back out
1162 my @faked_subfield_chars;
1163 if ($faked_chron_date) {
1164 my $faked_caption = new MARC::Field($caption->tag, $caption->indicator(1), $caption->indicator(2), $caption->subfields_list);
1166 my %mfhd_chron_labels = ('i' => 'year', 'j' => 'month', 'k' => 'day');
1167 foreach my $subfield_char ('i', 'j', 'k') {
1168 if (!$caption->subfield($subfield_char)) { # if we are missing a piece, add it
1169 push(@faked_subfield_chars, $subfield_char);
1170 my $chron_name = $mfhd_chron_labels{$subfield_char};
1171 $faked_caption->add_subfields($subfield_char => "($chron_name)");
1172 my $method = $mfhd_chron_labels{$subfield_char};
1173 $predict_from->add_subfields($subfield_char => $faked_chron_date->$chron_name);
1176 # because of the way MFHD::Caption and Holding work, it is simplest
1177 # to recreate rather than try to update
1178 $faked_caption = new MFHD::Caption($faked_caption);
1179 $predict_from = new MFHD::Holding($predict_from->seqno, new MARC::Field($predict_from->tag, $predict_from->indicator(1), $predict_from->indicator(2), $predict_from->subfields_list), $faked_caption);
1180 $logger->debug('_generate_issuance_values fake predict_from: ' . OpenSRF::Utils::JSON->perl2JSON($predict_from));
1183 my @predictions = $mfhd->generate_predictions({
1184 'include_base_issuance' => $include_base_issuance,
1185 'base_holding' => $predict_from,
1186 'num_to_predict' => $num_to_predict,
1187 'end_date' => $end_date
1189 $logger->debug('_generate_issuance_values predictions: ' . OpenSRF::Utils::JSON->perl2JSON(\@predictions));
1192 my @issuance_values;
1193 foreach my $prediction (@predictions) {
1194 $pub_date = $_strp_date->parse_datetime($prediction->chron_to_date);
1195 if ($faked_chron_date) { # get rid of the chronology portions and restore original caption
1196 $prediction->delete_subfield(code => \@faked_subfield_chars);
1197 $prediction = new MFHD::Holding($prediction->seqno, new MARC::Field($prediction->tag, $prediction->indicator(1), $prediction->indicator(2), $prediction->subfields_list), $caption);
1203 label => $prediction->format,
1204 date_published => $pub_date,
1205 #date_expected => $date_expected->strftime('%F'),
1206 holding_code => [$prediction->indicator(1),$prediction->indicator(2),$prediction->subfields_list],
1207 holding_type => $MFHD_NAMES_BY_TAG{$caption->tag},
1208 caption_and_pattern => $scap_id
1213 return @issuance_values;
1216 sub _revive_caption {
1219 my $pattern_code = $scap->pattern_code;
1222 my $pattern_parts = OpenSRF::Utils::JSON->JSON2perl($pattern_code);
1223 unshift(@$pattern_parts, $MFHD_TAGS_BY_NAME{$scap->type});
1224 my $pattern_field = new MARC::Field(@$pattern_parts);
1226 # build MFHD::Caption
1227 return new MFHD::Caption($pattern_field);
1230 sub _revive_holding {
1231 my $holding_code = shift;
1232 my $caption_field = shift;
1236 my $holding_parts = OpenSRF::Utils::JSON->JSON2perl($holding_code);
1237 my $captag = $caption_field->tag;
1238 $captag =~ s/^85/86/;
1239 unshift(@$holding_parts, $captag);
1240 my $holding_field = new MARC::Field(@$holding_parts);
1242 # build MFHD::Holding
1243 return new MFHD::Holding($seqno, $holding_field, $caption_field);
1245 # TODO(?) the underlying MARC and the Holding object end up in conflict concerning subfield '8'
1248 __PACKAGE__->register_method(
1249 method => 'unitize_items',
1250 api_name => 'open-ils.serial.receive_items',
1254 desc => 'Marks an item as received, updates the shelving unit (creating a new shelving unit if needed), and updates the summaries',
1257 desc => 'array of serial items',
1262 desc => 'hash of item_ids => barcodes',
1266 name => 'call_numbers',
1267 desc => 'hash of item_ids => call_numbers',
1271 name => 'donor_unit_ids',
1272 desc => 'hash of unit_ids => 1, keyed with ids of any units giving up items',
1277 desc => 'hash of hashes, circ_mod code and copy_location id, keyed as above',
1282 desc => 'Returns number of received items (num_items) and new unit ID, if applicable (new_unit_id)',
1288 __PACKAGE__->register_method(
1289 method => 'unitize_items',
1290 api_name => 'open-ils.serial.bind_items',
1294 desc => 'Marks an item as bound, updates the shelving unit (creating a new shelving unit if needed)',
1297 desc => 'array of serial items',
1302 desc => 'hash of item_ids => barcodes',
1306 name => 'call_numbers',
1307 desc => 'hash of item_ids => call_numbers',
1311 name => 'donor_unit_ids',
1312 desc => 'hash of unit_ids => 1, keyed with ids of any units giving up items',
1317 desc => 'hash of hashes, circ_mod code and copy_location id, keyed as above',
1322 desc => 'Returns number of bound items (num_items) and new unit ID, if applicable (new_unit_id)',
1328 # TODO: reset/delete claims information once implemented
1329 # XXX: deal with emptied call numbers here?
1330 __PACKAGE__->register_method(
1331 method => 'unitize_items',
1332 api_name => 'open-ils.serial.reset_items',
1336 desc => 'Resets the items to Expected, updates the shelving unit (deleting the shelving unit if empty), and updates the summaries',
1339 desc => 'array of serial items',
1344 desc => 'Returns number of reset items (num_items)',
1351 my ($self, $conn, $auth, $items, $barcodes, $call_numbers, $donor_unit_ids, $extras) = @_;
1353 my $editor = new_editor("authtoken" => $auth, "xact" => 1);
1354 return $editor->die_event unless $editor->checkauth;
1355 return $editor->die_event unless $editor->allowed("RECEIVE_SERIAL");
1356 $self->api_name =~ /serial\.(\w*)_items/;
1360 if ($donor_unit_ids) { # units giving up items need updating as well
1361 %found_unit_ids = %$donor_unit_ids;
1363 my %found_stream_ids;
1365 my $prev_loc_setting_map = {};
1367 my %stream_ids_by_unit_id;
1370 my %sdist_by_unit_id;
1371 my %call_number_by_unit_id;
1372 my %sdist_by_stream_id;
1374 my $new_unit_id; # id for '-2' units to share
1375 foreach my $item (@$items) {
1376 # for debugging only, TODO: delete
1377 if (!ref $item) { # hopefully we got an id instead
1378 $item = $editor->retrieve_serial_item($item);
1381 my $unit_id = ref($item->unit) ? $item->unit->id : $item->unit;
1382 my $stream_id = ref($item->stream) ? $item->stream->id : $item->stream;
1383 my $issuance_id = ref($item->issuance) ? $item->issuance->id : $item->issuance;
1384 #TODO: evt on any missing ids
1386 if ($mode eq 'receive') {
1387 $item->date_received('now');
1388 $item->status('Received');
1389 } elsif ($mode eq 'reset') {
1390 # clear date_received
1391 $item->clear_date_received;
1392 # Set status to 'Expected'
1393 $item->status('Expected');
1398 # check for types to trigger summary updates
1400 if (!ref $item->issuance) {
1401 my $scaps = $editor->search_serial_caption_and_pattern([{"+siss" => {"id" => $issuance_id}}, { "join" => {"siss" => {}} }]);
1402 $scap = $scaps->[0];
1403 } elsif (!ref $item->issuance->caption_and_pattern) {
1404 $scap = $editor->retrieve_serial_caption_and_pattern($item->issuance->caption_and_pattern);
1406 $scap = $editor->issuance->caption_and_pattern;
1408 if (!exists($found_types{$stream_id})) {
1409 $found_types{$stream_id} = {};
1411 $found_types{$stream_id}->{$scap->type} = 1 if ($scap);
1413 # create unit if needed
1414 if ($unit_id == -1 or (!$new_unit_id and $unit_id == -2)) { # create unit per item
1416 my $sdists = $editor->search_serial_distribution([
1417 {"+sstr" => {"id" => $stream_id}},
1419 "join" => {"sstr" => {}},
1421 "flesh_fields" => {"sdist" => ["subscription"]}
1423 $unit = _build_unit($editor, $sdists->[0], $mode);
1424 # if _build_unit fails, $unit is an event, so return it
1425 if ($U->event_code($unit)) {
1427 $unit->{"note"} = "Item ID: " . $item->id;
1431 $unit->barcode($barcodes->{$item->id}) if exists($barcodes->{$item->id});
1432 $unit->location($extras->{copy_locations}->{$item->id}) if exists($extras->{copy_locations}->{$item->id});
1433 $unit->circ_modifier($extras->{circ_mods}->{$item->id}) if exists($extras->{circ_mods}->{$item->id});
1435 my $evt = _create_sunit($editor, $unit);
1436 return $evt if $evt;
1437 if ($unit_id == -2) {
1438 $new_unit_id = $unit->id;
1439 $unit_id = $new_unit_id;
1441 $unit_id = $unit->id;
1443 $item->unit($unit_id);
1445 # get unit with 'DEFAULT's and save unit, sdist, and call number for later use
1446 $unit = $editor->retrieve_serial_unit($unit->id);
1447 $unit_map{$unit_id} = $unit;
1448 $sdist_by_unit_id{$unit_id} = $sdists->[0];
1449 $call_number_by_unit_id{$unit_id} = $call_numbers->{$item->id};
1450 $sdist_by_stream_id{$stream_id} = $sdists->[0];
1451 } elsif ($unit_id == -2) { # create one unit for all '-2' items
1452 $unit_id = $new_unit_id;
1453 $item->unit($unit_id);
1456 $found_stream_ids{$stream_id} = 1;
1458 if (defined($unit_id) and $unit_id ne '') {
1459 $found_unit_ids{$unit_id} = 1;
1460 # save the stream_id for this unit_id
1461 # TODO: prevent items from different streams in same unit? (perhaps in interface)
1462 $stream_ids_by_unit_id{$unit_id} = $stream_id;
1467 my $evt = _update_sitem($editor, undef, $item);
1468 return $evt if $evt;
1470 if ($mode eq 'receive') {
1471 my $sdist = $editor->search_serial_distribution([
1472 {"+sstr" => {"id" => $stream_id}},
1474 "join" => {"sstr" => {}},
1476 "flesh_fields" => {"sdist" => ["subscription"]}
1479 #-------------------------------------------------------------------------
1480 # The following is copied from open-ils.serial.receive_items.one_unit_per
1482 # Fetch a list of issuances with received copies already existing
1483 # on this distribution (and with the same holding type on the
1484 # issuance). This will be used in up to two places: once when building
1485 # a summary, once when changing the copy location of the previous
1488 # manually flesh distribution if not present
1490 # this helps maintain compatiblity with XUL serial control receive
1491 if (!ref($item->stream->distribution)) {
1492 $item->stream->distribution($sdist);
1494 my $issuances_received = _issuances_received($editor, $item);
1495 if ($U->event_code($issuances_received)) {
1497 return $issuances_received;
1500 # Find out if we need to to deal with previous copy location changing.
1501 my $ou = $sdist->holding_lib;
1502 unless (exists $prev_loc_setting_map->{$ou}) {
1503 $prev_loc_setting_map->{$ou} = $U->ou_ancestor_setting_value(
1504 $ou, "serial.prev_issuance_copy_location", $editor
1508 # If there is a previous copy location setting, we need the previous
1509 # issuance, from which we can in turn look up the item attached to the
1510 # same stream we're on now.
1511 if ($prev_loc_setting_map->{$ou}) {
1513 _previous_issuance($issuances_received, $item->issuance)) {
1515 # Now we can change the copy location of the previous unit,
1517 return $editor->event if defined $U->event_code(
1519 $editor, $prev_iss, $item, $prev_loc_setting_map->{$ou}
1524 #-------------------------------------------------------------------------
1529 # cleanup 'dead' units (units which are now emptied of their items)
1530 my $dead_units = $editor->search_serial_unit([{'+sitem' => {'id' => undef}, 'deleted' => 'f'}, {'join' => {'sitem' => {'type' => 'left'}}}]);
1531 foreach my $unit (@$dead_units) {
1532 _delete_sunit($editor, undef, $unit);
1533 delete $found_unit_ids{$unit->id};
1536 # deal with unit level contents
1537 foreach my $unit_id (keys %found_unit_ids) {
1539 # get all the needed issuances for unit
1540 # TODO remove 'Bindery' from this search (leaving it in for now for backwards compatibility with any current test environment data)
1541 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"unit" => $unit_id, "status" => ["Received", "Bindery"]}}, {"join" => {"sitem" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1542 #TODO: evt on search failure
1544 # retrieve and update unit contents
1547 my $call_number_string;
1549 # if we just created the unit, we will already have it and the distribution stored, and we will need to assign the call number
1550 if (exists $unit_map{$unit_id}) {
1551 $sunit = $unit_map{$unit_id};
1552 $sdist = $sdist_by_unit_id{$unit_id};
1553 $call_number_string = $call_number_by_unit_id{$unit_id};
1554 $record_id = $sdist->subscription->record_entry;
1556 # XXX: this code assumes you will not have units which mix streams/distributions, but current code does not enforce this
1557 $sunit = $editor->retrieve_serial_unit($unit_id);
1558 if ($stream_ids_by_unit_id{$unit_id}) {
1559 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_ids_by_unit_id{$unit_id}}}, { "join" => {"sstr" => {}}, 'limit' => 1 }]);
1561 $sdist = $editor->search_serial_distribution([
1562 {'+sunit' => {'id' => $unit_id}},
1567 { 'join' => 'sunit' }
1574 $sdist = $sdist->[0];
1577 my $evt = _prepare_unit($editor, $sunit, $sdist, $issuances, $call_number_string, $record_id);
1578 if ($U->event_code($evt)) {
1583 $evt = _update_sunit($editor, undef, $sunit);
1584 if ($U->event_code($evt)) {
1590 if ($mode ne 'bind') { # the summary holdings do not change when binding
1591 # deal with stream level summaries
1592 # summaries will be built from the "primary" stream only, that is, the stream with the lowest ID per distribution
1593 # (TODO: consider direct designation)
1594 my %primary_streams_by_sdist;
1595 my %streams_by_sdist;
1597 # see if we have primary streams, and if so, associate them with their distributions
1598 foreach my $stream_id (keys %found_stream_ids) {
1600 if (exists $sdist_by_stream_id{$stream_id}) {
1601 $sdist = $sdist_by_stream_id{$stream_id};
1603 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
1604 $sdist = $sdist->[0];
1605 $sdist_by_stream_id{$stream_id} = $sdist;
1608 if (!exists($streams_by_sdist{$sdist->id})) {
1609 $streams = $editor->search_serial_stream([{"distribution" => $sdist->id}, {"order_by" => {"sstr" => "id"}}]);
1610 $streams_by_sdist{$sdist->id} = $streams;
1612 $streams = $streams_by_sdist{$sdist->id};
1614 $primary_streams_by_sdist{$sdist->id} = $streams->[0] if ($stream_id == $streams->[0]->id);
1617 # retrieve and update summaries for each affected primary stream's distribution
1618 foreach my $sdist_id (keys %primary_streams_by_sdist) {
1619 my $stream = $primary_streams_by_sdist{$sdist_id};
1620 my $stream_id = $stream->id;
1621 # get all the needed issuances for stream
1622 # FIXME: search in Bindery/Bound/Not Published? as well as Received
1623 foreach my $type (keys %{$found_types{$stream_id}}) {
1624 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"stream" => $stream_id, "status" => "Received"}, "+scap" => {"type" => $type}}, {"join" => {"sitem" => {}, "scap" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1625 #TODO: evt on search failure
1626 my $evt = _prepare_summaries($editor, $issuances, $sdist_by_stream_id{$stream_id}, $type);
1627 if ($U->event_code($evt)) {
1636 return {'num_items' => scalar @$items, 'new_unit_id' => $new_unit_id};
1639 sub _find_or_create_call_number {
1640 my ($e, $lib, $cn_string, $record) = @_;
1642 my ($prefix,$suffix) = ('','');
1643 if (ref($cn_string)) {
1644 ($prefix,$cn_string,$suffix) = @$cn_string;
1647 my $existing = $e->search_asset_call_number([{
1649 label => $cn_string,
1652 '+acnp' => { label => $prefix },
1653 '+acns' => { label => $suffix },
1656 join => { acnp => {}, acns => {} }
1657 }]) or return $e->die_event;
1660 return $existing->[0]->id;
1662 return $e->die_event unless
1663 $e->allowed("CREATE_VOLUME", $lib);
1665 $prefix = -1 if (!$prefix);
1666 $suffix = -1 if (!$suffix);
1668 if ($prefix ne '-1') {
1669 my $acnp = $e->search_asset_call_number_prefix({
1675 $acnp = new Fieldmapper::asset::call_number_prefix;
1676 $acnp->label($prefix);
1677 $acnp->owning_lib($lib);
1678 $e->create_asset_call_number_prefix($acnp) or return $e->die_event;
1679 $prefix = $e->data->id;
1681 $prefix = $acnp->id;
1685 if ($suffix ne '-1') {
1686 my $acns = $e->search_asset_call_number_suffix({
1692 $acns = new Fieldmapper::asset::call_number_suffix;
1693 $acns->label($suffix);
1694 $acns->owning_lib($lib);
1695 $e->create_asset_call_number_suffix($acns) or return $e->die_event;
1696 $suffix = $e->data->id;
1698 $suffix = $acns->id;
1702 my $acn = new Fieldmapper::asset::call_number;
1704 $acn->creator($e->requestor->id);
1705 $acn->editor($e->requestor->id);
1706 $acn->record($record);
1707 $acn->label($cn_string);
1708 $acn->owning_lib($lib);
1709 $acn->prefix($prefix);
1710 $acn->suffix($suffix);
1712 $e->create_asset_call_number($acn) or return $e->die_event;
1713 return $e->data->id;
1717 sub _issuances_received {
1718 # XXX TODO: Add some caching or something. This is getting called
1719 # more often than it has to be.
1720 my ($e, $sitem) = @_;
1722 my $results = $e->json_query({
1723 "select" => {"sitem" => ["issuance"]},
1724 "from" => {"sitem" => {"sstr" => {}, "siss" => {}}},
1726 "+sstr" => {"distribution" => $sitem->stream->distribution->id},
1727 "+siss" => {"holding_type" => $sitem->issuance->holding_type},
1728 "+sitem" => {"date_received" => {"!=" => undef}}
1731 "siss" => {"date_published" => {"direction" => "asc"}}
1733 }) or return $e->die_event;
1737 for my $iss_id (map { $_->{"issuance"} } @$results) {
1738 next if $seen{$iss_id};
1740 push(@$issuances, $e->retrieve_serial_issuance($iss_id));
1745 # _prepare_unit populates the detailed_contents, summary_contents, and
1746 # sort_key fields for a given unit based on a given set of issuances
1747 # Also finds/creates call number as needed
1749 my ($e, $sunit, $sdist, $issuances, $call_number_string, $record_id) = @_;
1751 # Handle call number first if we have one
1752 if ($call_number_string) {
1753 my $org_unit_id = ref $sdist->holding_lib ? $sdist->holding_lib->id : $sdist->holding_lib;
1754 my $real_cn = _find_or_create_call_number(
1756 $call_number_string, $record_id
1759 if ($U->event_code($real_cn)) {
1762 $sunit->call_number($real_cn);
1766 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances);
1767 return $mfhd if $U->event_code($mfhd);
1769 # special case for single formatted_part (may have summarized version)
1770 if (@$formatted_parts == 1) {
1771 #TODO: MFHD.pm should have a 'format_summary' method for this
1774 $sunit->detailed_contents(
1777 $sdist->unit_label_prefix,
1778 join(", ", @$formatted_parts),
1779 $sdist->unit_label_suffix
1783 # TODO: change this when real summary contents are available
1784 $sunit->summary_contents($sunit->detailed_contents);
1786 # Create sort_key by left padding numbers to 6 digits.
1787 (my $sort_key = $sunit->detailed_contents) =~
1788 s/(\d+)/sprintf '%06d', $1/eg;
1789 $sunit->sort_key($sort_key);
1792 # _prepare_summaries populates the generated_coverage field for a given summary
1793 # type ('basic', 'index', 'supplement') for a given distribution.
1794 # It also creates the summary if it doesn't yet exist.
1795 sub _prepare_summaries {
1796 my ($e, $issuances, $sdist, $type) = @_;
1798 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances, $sdist, $type);
1799 return $mfhd if $U->event_code($mfhd);
1801 my $search_method = "search_serial_${type}_summary";
1802 my $summary = $e->$search_method([{"distribution" => $sdist->id}]);
1804 my $cu_method = "update";
1807 $summary = $summary->[0];
1809 my $class = "Fieldmapper::serial::${type}_summary";
1810 $summary = $class->new;
1811 $summary->distribution($sdist->id);
1812 $cu_method = "create";
1815 if (@$formatted_parts) {
1816 $summary->generated_coverage(OpenSRF::Utils::JSON->perl2JSON($formatted_parts));
1818 # we had no issuances or MFHD data for this type, so clear any
1819 # generated data which may have existed before
1820 $summary->generated_coverage('');
1822 my $method = "${cu_method}_serial_${type}_summary";
1823 return $e->die_event unless $e->$method($summary);
1827 __PACKAGE__->register_method(
1828 method => 'regen_summaries',
1829 api_name => 'open-ils.serial.regenerate_summaries',
1833 'desc' => 'Regenerate all the generated_coverage fields for given distributions or subscriptions (depending on params given). Params are expected to be hash members.',
1835 name => 'sdist_ids',
1836 desc => 'IDs of the distribution whose coverage you want to regenerate',
1841 desc => 'IDs of the subscriptions whose coverage you want to regenerate',
1846 desc => 'Returns undef if successful, event if failed',
1849 #TODO: best practices for return values
1853 sub regen_summaries {
1854 my ($self, $conn, $auth, $opts) = @_;
1856 my $e = new_editor("authtoken" => $auth, "xact" => 1);
1857 return $e->die_event unless $e->checkauth;
1858 # Perm checks not necessary since generated_coverage is akin to
1859 # caching of data, not actual editing. XXX This might need more
1861 #return $editor->die_event unless $editor->allowed("RECEIVE_SERIAL");
1863 my $evt = _regenerate_summaries($e, $opts);
1864 if ($U->event_code($evt)) {
1874 sub _regenerate_summaries {
1875 my ($e, $opts) = @_;
1877 $logger->debug('_regenerate_summaries with opts: ' . OpenSRF::Utils::JSON->perl2JSON($opts));
1879 if ($opts->{'ssub_ids'}) {
1880 foreach my $ssub_id (@{$opts->{'ssub_ids'}}) {
1881 my $sdist_ids_temp = $e->search_serial_distribution(
1882 { 'subscription' => $ssub_id },
1885 push(@sdist_ids, @$sdist_ids_temp);
1887 } elsif ($opts->{'sdist_ids'}) {
1888 @sdist_ids = @$opts->{'sdist_ids'};
1891 foreach my $sdist_id (@sdist_ids) {
1893 my $sdist = $e->retrieve_serial_distribution($sdist_id)
1894 or return $e->die_event;
1896 # See large comment below
1897 # my $has_merged_mfhd;
1898 foreach my $type (@MFHD_NAMES) {
1900 my $issuances = $e->search_serial_issuance([
1902 "+sdist" => {"id" => $sdist_id},
1903 "+sitem" => {"status" => "Received"},
1904 "+scap" => {"type" => $type}
1911 "join" => {"sdist" =>{}}
1915 "siss" => "date_published"
1918 ]) or return $e->die_event;
1920 # This level of nuance doesn't appear to be necessary.
1921 # At the moment, we pass down an empty issuance list,
1922 # and the inner methods will "do the right thing" and
1923 # pull in the MFHD if called for, but in some cases not
1924 # ultimately generate any coverage. The code below is
1925 # broken in cases where we delete the last issuance, since
1926 # the now empty summary never gets updated.
1928 # Leaving this code for now (2014/04) in case pushing
1929 # the logic down ends up being too slow or complicates
1930 # the inner methods beyond their scope.
1932 # if (!@$issuances and !$has_merged_mfhd) {
1933 # if (!defined($has_merged_mfhd)) {
1934 # # even without issuances, we can generate a summary
1935 # # from a merged MFHD record, so look for one
1936 # my $mfhd_ids = $e->search_serial_record_entry(
1939 # 'id' => $sdist_id,
1940 # 'summary_method' => 'merge_with_sre'
1944 # 'join' => { 'sdist' => {} },
1948 # if ($mfhd_ids and @$mfhd_ids) {
1949 # $has_merged_mfhd = 1;
1954 # next; # abort to prevent empty summary creation (i.e. '[]')
1957 my $evt = _prepare_summaries($e, $issuances, $sdist, $type);
1958 if ($U->event_code($evt)) {
1968 sub _unit_by_iss_and_str {
1969 my ($e, $issuance, $stream) = @_;
1971 my $unit = $e->json_query({
1972 "select" => {"sunit" => ["id"]},
1973 "from" => {"sitem" => {"sunit" => {}}},
1976 "issuance" => $issuance->id,
1977 "stream" => $stream->id
1980 }) or return $e->die_event;
1981 return 0 if not @$unit;
1983 $e->retrieve_serial_unit($unit->[0]->{"id"}) or $e->die_event;
1986 sub move_previous_unit {
1987 my ($e, $prev_iss, $curr_item, $new_loc) = @_;
1989 my $prev_unit = _unit_by_iss_and_str($e,$prev_iss,$curr_item->stream);
1990 return $prev_unit if defined $U->event_code($prev_unit);
1991 return 0 if not $prev_unit;
1993 if ($prev_unit->location != $new_loc) {
1994 $prev_unit->location($new_loc);
1995 $e->update_serial_unit($prev_unit) or return $e->die_event;
2000 # _previous_issuance() assumes $existing is an ordered array
2001 sub _previous_issuance {
2002 my ($existing, $issuance) = @_;
2004 my $last = $existing->[-1];
2005 return undef unless $last;
2006 return ($last->id == $issuance->id ? $existing->[-2] : $last);
2009 __PACKAGE__->register_method(
2010 "method" => "receive_items_one_unit_per",
2011 "api_name" => "open-ils.serial.receive_items.one_unit_per",
2016 "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",
2020 "desc" => "authtoken",
2025 "desc" => "array of serial items, possibly fleshed with units and definitely fleshed with stream->distribution",
2030 "desc" => "id of bib record these items are associated with
2031 (XXX could/should be derived from items)",
2036 "desc" => "The item ID for each item successfully received",
2042 sub receive_items_one_unit_per {
2043 # XXX This function may be temporary, as it does some of what
2044 # unitize_items() does, just in a different way.
2045 my ($self, $client, $auth, $items, $record) = @_;
2047 my $e = new_editor("authtoken" => $auth, "xact" => 1);
2048 return $e->die_event unless $e->checkauth;
2049 return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
2051 my $prev_loc_setting_map = {};
2052 my $user_id = $e->requestor->id;
2054 # Get a list of all the non-virtual field names in a serial::unit for
2055 # merging given unit objects with template-built units later.
2056 # XXX move this somewhere global so it isn't re-run all the time
2057 my $all_unit_fields =
2058 $Fieldmapper::fieldmap->{"Fieldmapper::serial::unit"}->{"fields"};
2059 my @real_unit_fields = grep {
2060 not $all_unit_fields->{$_}->{"virtual"}
2061 } keys %$all_unit_fields;
2063 foreach my $item (@$items) {
2064 # Note that we expect a certain fleshing on the items we're getting.
2065 my $sdist = $item->stream->distribution;
2067 # Fetch a list of issuances with received copies already existing
2068 # on this distribution (and with the same holding type on the
2069 # issuance). This will be used in up to two places: once when building
2070 # a summary, once when changing the copy location of the previous
2072 my $issuances_received = _issuances_received($e, $item);
2073 if ($U->event_code($issuances_received)) {
2075 return $issuances_received;
2078 # Find out if we need to to deal with previous copy location changing.
2079 my $ou = $sdist->holding_lib->id;
2080 unless (exists $prev_loc_setting_map->{$ou}) {
2081 $prev_loc_setting_map->{$ou} = $U->ou_ancestor_setting_value(
2082 $ou, "serial.prev_issuance_copy_location", $e
2086 # If there is a previous copy location setting, we need the previous
2087 # issuance, from which we can in turn look up the item attached to the
2088 # same stream we're on now.
2089 if ($prev_loc_setting_map->{$ou}) {
2091 _previous_issuance($issuances_received, $item->issuance)) {
2093 # Now we can change the copy location of the previous unit,
2095 return $e->event if defined $U->event_code(
2097 $e, $prev_iss, $item, $prev_loc_setting_map->{$ou}
2103 # Create unit if given by user
2104 if (ref $item->unit) {
2105 # detach from the item, as we need to create separately
2106 my $user_unit = $item->unit;
2108 # get a unit based on associated template
2109 my $template_unit = _build_unit($e, $sdist, "receive");
2110 if ($U->event_code($template_unit)) {
2112 $template_unit->{"note"} = "Item ID: " . $item->id;
2113 return $template_unit;
2116 # merge built unit with provided unit from user
2117 foreach (@real_unit_fields) {
2118 unless ($user_unit->$_) {
2119 $user_unit->$_($template_unit->$_);
2123 # Treat call number specially: the provided value from the
2124 # user will really be a string.
2125 my $call_number_string;
2126 if ($user_unit->call_number) {
2127 $call_number_string = $user_unit->call_number;
2128 # clear call number for now (replaced in _prepare_unit)
2129 $user_unit->clear_call_number;
2132 my $evt = _prepare_unit(
2133 $e, $user_unit, $sdist, [$item->issuance],
2134 $call_number_string, $record
2136 if ($U->event_code($evt)) {
2141 # create/update summary objects related to this distribution
2142 # Make sure @$issuances_received contains current item's issuance
2143 unless (grep { $_->id == $item->issuance->id } @$issuances_received) {
2144 push @$issuances_received, $item->issuance;
2146 $evt = _prepare_summaries($e, $issuances_received, $item->stream->distribution, $item->issuance->holding_type);
2147 if ($U->event_code($evt)) {
2152 # set the incontrovertibles on the unit
2153 $user_unit->edit_date("now");
2154 $user_unit->create_date("now");
2155 $user_unit->editor($user_id);
2156 $user_unit->creator($user_id);
2158 $evt = _create_sunit($e, $user_unit);
2159 return $evt if $evt;
2161 # save reference to new unit
2162 $item->unit($e->data->id);
2165 # Create notes if given by user
2166 if (ref($item->notes) and @{$item->notes}) {
2167 foreach my $note (@{$item->notes}) {
2168 $note->creator($user_id);
2169 $note->create_date("now");
2171 return $e->die_event unless $e->create_serial_item_note($note);
2174 $item->clear_notes; # They're saved; we no longer want them here.
2177 # Set the incontrovertibles on the item
2178 $item->status("Received");
2179 $item->date_received("now");
2180 $item->edit_date("now");
2181 $item->editor($user_id);
2183 return $e->die_event unless $e->update_serial_item($item);
2185 # send client a response
2186 $client->respond($item->id);
2189 $e->commit or return $e->die_event;
2197 #my $skip_call_number = shift;
2199 my $attr = $mode . '_unit_template';
2200 my $template = $editor->retrieve_asset_copy_template($sdist->$attr) or
2201 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_COPY_TEMPLATE");
2203 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 );
2205 my $unit = new Fieldmapper::serial::unit;
2206 foreach my $part (@parts) {
2207 my $value = $template->$part;
2208 next if !defined($value);
2209 $unit->$part($value);
2212 # ignore circ_lib in template, set to distribution holding_lib
2213 $unit->circ_lib($sdist->holding_lib);
2214 $unit->creator($editor->requestor->id);
2215 $unit->editor($editor->requestor->id);
2217 # XXX: this feature has been pushed back until after 2.0 at least
2218 # unless ($skip_call_number) {
2219 # $attr = $mode . '_call_number';
2220 # my $cn = $sdist->$attr or
2221 # return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_CALL_NUMBER");
2223 # $unit->call_number($cn);
2225 $unit->call_number('-1'); # default to the dummy call number
2226 $unit->barcode('@@PLACEHOLDER'); # generic unit will start with a generated placeholder barcode
2227 $unit->sort_key('');
2228 $unit->summary_contents('');
2229 $unit->detailed_contents('');
2234 sub _summarize_contents {
2236 my $issuances = shift;
2240 # create or lookup MFHD record
2242 if ($sdist and defined($sdist->record_entry) and $sdist->summary_method eq 'merge_with_sre') {
2244 if (ref $sdist->record_entry) {
2245 $sre = $sdist->record_entry;
2247 $sre = $editor->retrieve_serial_record_entry($sdist->record_entry);
2249 $mfhd = MFHD->new(MARC::Record->new_from_xml($sre->marc));
2251 $logger->info($sdist);
2252 $mfhd = MFHD->new(MARC::Record->new());
2258 # We keep track of these separately to avoid link_id contamination,
2259 # e.g. a basic issuance, followed by a merging supplement, followed by
2260 # another basic. If we could be sure that they were not mixed, one
2261 # value could suffice.
2262 my %link_ids = ('basic' => 10000, 'index' => 10000, 'supplement' => 10000);
2263 my %first_scap = ('basic' => 1, 'index' => 1, 'supplement' => 1);
2264 foreach my $issuance (@$issuances) {
2265 my $scap_id = $issuance->caption_and_pattern;
2266 next if (!$scap_id); # skip issuances with no caption/pattern
2270 # if this is the first appearance of this scap, retrieve it and add it to the temporary record
2271 if (!exists $scaps{$issuance->caption_and_pattern}) {
2272 $scaps{$scap_id} = $editor->retrieve_serial_caption_and_pattern($scap_id);
2273 $scap = $scaps{$scap_id};
2274 $scap_field = _revive_caption($scap);
2276 if ($first_scap{$scap->type}) { # special merge processing
2277 $first_scap{$MFHD_TAGS_BY_NAME{$scap->type}} = 0;
2278 if ($sdist and $sdist->summary_method eq 'merge_with_sre') {
2279 # MFHD Caption objects do not yet have a built-in compare (TODO), so let's do a basic one
2280 my @field_85xs = $mfhd->field($MFHD_TAGS_BY_NAME{$scap->type});
2282 my $last_caption_field = $field_85xs[-1];
2283 my $last_link_id = $last_caption_field->subfield('8');
2284 # set the link id to match, temporarily, for comparison
2285 $last_caption_field->update('8' => $scap_field->subfield('8'));
2286 my $last_caption_json = OpenSRF::Utils::JSON->perl2JSON([$last_caption_field->indicator(1), $last_caption_field->indicator(2), $last_caption_field->subfields_list]);
2287 if ($last_caption_json eq $scap->pattern_code) { # merge is possible, they match
2289 $link_ids{$scap->type} = $last_link_id;
2290 # set scap_field to last field
2291 $scap_field = $last_caption_field;
2297 $scap_fields{$scap_id} = $scap_field;
2298 $scap_field->update('8' => $link_ids{$scap->type});
2299 # TODO: make MFHD/Caption smarter about this
2300 $scap_field->{_mfhdc_LINK_ID} = $link_ids{$scap->type};
2301 $mfhd->append_fields($scap_field) if !$did_merge;
2302 $link_ids{$scap->type}++;
2304 $scap_field = $scap_fields{$scap_id};
2307 $mfhd->append_fields(_revive_holding($issuance->holding_code, $scap_field, $seqno));
2311 my @formatted_parts;
2312 my @scap_fields_ordered;
2314 @scap_fields_ordered = $mfhd->field($MFHD_TAGS_BY_NAME{$type});
2316 # if they didn't give a type, send back whatever holdings we have.
2317 # this is really only sensible right now for summarizing one type,
2318 # and is used by the unitize code for this purpose
2320 # TODO: possible future support for binding (unitizing) of multiple
2321 # types into a sensible summary string
2322 @scap_fields_ordered = $mfhd->field('85[345]');
2325 foreach my $scap_field (@scap_fields_ordered) { #TODO: use generic MFHD "summarize" method, once available
2326 my @updated_holdings;
2328 @updated_holdings = $mfhd->get_combined_holdings($scap_field);
2331 my $msg = "get_combined_holdings(): $@ ; using sdist ID #" .
2332 ($sdist ? $sdist->id : "<NONE>") . " and " .
2333 scalar(@$issuances) . " issuances, of which one has ID #" .
2334 $issuances->[0]->id;
2337 $logger->error($msg);
2338 return new OpenILS::Event("BAD_PARAMS", note => $msg);
2341 push @formatted_parts, map { $_->format } @updated_holdings;
2344 return ($mfhd, \@formatted_parts);
2347 ##########################################################################
2350 __PACKAGE__->register_method(
2351 method => 'fetch_notes',
2352 api_name => 'open-ils.serial.item_note.retrieve.all',
2354 Returns an array of copy note objects.
2355 @param args A named hash of parameters including:
2356 authtoken : Required if viewing non-public notes
2357 item_id : The id of the item whose notes we want to retrieve
2358 pub : True if all the caller wants are public notes
2359 @return An array of note objects
2363 __PACKAGE__->register_method(
2364 method => 'fetch_notes',
2365 api_name => 'open-ils.serial.subscription_note.retrieve.all',
2367 Returns an array of copy note objects.
2368 @param args A named hash of parameters including:
2369 authtoken : Required if viewing non-public notes
2370 subscription_id : The id of the item whose notes we want to retrieve
2371 pub : True if all the caller wants are public notes
2372 @return An array of note objects
2376 __PACKAGE__->register_method(
2377 method => 'fetch_notes',
2378 api_name => 'open-ils.serial.distribution_note.retrieve.all',
2380 Returns an array of copy note objects.
2381 @param args A named hash of parameters including:
2382 authtoken : Required if viewing non-public notes
2383 distribution_id : The id of the item whose notes we want to retrieve
2384 pub : True if all the caller wants are public notes
2385 @return An array of note objects
2389 # TODO: revisit this method to consider replacing cstore direct calls
2391 my( $self, $connection, $args ) = @_;
2393 $self->api_name =~ /serial\.(\w*)_note/;
2396 my $id = $$args{object_id};
2397 my $authtoken = $$args{authtoken};
2398 my $order_by = $$args{order_by} || 'create_date';
2402 return $U->cstorereq(
2403 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic',
2404 { $type => $id, pub => 't' }, {'order_by' => {$FM_NAME_TO_ID{$type}.'n' => $order_by}} );
2406 # FIXME: restore perm check
2407 # ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
2408 # return $evt if $evt;
2409 return $U->cstorereq(
2410 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic', {$type => $id}, {'order_by' => {$FM_NAME_TO_ID{$type}.'n' => $order_by}} );
2416 __PACKAGE__->register_method(
2417 method => 'update_note',
2418 api_name => 'open-ils.serial.item_note.update',
2420 Updates or creates an item note
2421 @param authtoken The login session key
2422 @param note The note object to update or create
2423 @return The id of the note object
2427 __PACKAGE__->register_method(
2428 method => 'update_note',
2429 api_name => 'open-ils.serial.subscription_note.update',
2431 Updates or creates a subscription note
2432 @param authtoken The login session key
2433 @param note The note object to update or create
2434 @return The id of the note object
2438 __PACKAGE__->register_method(
2439 method => 'update_note',
2440 api_name => 'open-ils.serial.distribution_note.update',
2442 Updates or creates a distribution note
2443 @param authtoken The login session key
2444 @param note The note object to update or create
2445 @return The id of the note object
2450 my( $self, $connection, $authtoken, $note ) = @_;
2452 $self->api_name =~ /serial\.(\w*)_note/;
2455 my $e = new_editor(xact=>1, authtoken=>$authtoken);
2456 return $e->event unless $e->checkauth;
2458 if ($type eq 'item') {
2459 my $sitem = $e->retrieve_serial_item([
2461 "flesh" => 2, "flesh_fields" => {
2462 "sitem" => ["stream"], "sstr" => ["distribution"]
2465 ]) or return $e->die_event;
2467 return $e->die_event unless $e->allowed(
2468 "ADMIN_SERIAL_ITEM", $sitem->stream->distribution->holding_lib
2470 } elsif ($type eq 'distribution') {
2471 my $sdist = $e->retrieve_serial_distribution($note->distribution)
2472 or return $e->die_event;
2474 return $e->die_event unless
2475 $e->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2476 } else { # subscription
2477 my $sub = $e->retrieve_serial_subscription($note->subscription)
2478 or return $e->die_event;
2480 return $e->die_event unless
2481 $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
2484 $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
2487 $note->create_date('now');
2488 $note->creator($e->requestor->id);
2490 $method = "create_serial_${type}_note";
2492 $method = "update_serial_${type}_note";
2494 $e->$method($note) or return $e->event;
2499 __PACKAGE__->register_method(
2500 method => 'delete_note',
2501 api_name => 'open-ils.serial.item_note.delete',
2503 Deletes an existing item note
2504 @param authtoken The login session key
2505 @param noteid The id of the note to delete
2506 @return 1 on success - Event otherwise.
2510 __PACKAGE__->register_method(
2511 method => 'delete_note',
2512 api_name => 'open-ils.serial.subscription_note.delete',
2514 Deletes an existing subscription note
2515 @param authtoken The login session key
2516 @param noteid The id of the note to delete
2517 @return 1 on success - Event otherwise.
2521 __PACKAGE__->register_method(
2522 method => 'delete_note',
2523 api_name => 'open-ils.serial.distribution_note.delete',
2525 Deletes an existing distribution note
2526 @param authtoken The login session key
2527 @param noteid The id of the note to delete
2528 @return 1 on success - Event otherwise.
2533 my( $self, $conn, $authtoken, $noteid ) = @_;
2535 $self->api_name =~ /serial\.(\w*)_note/;
2538 my $e = new_editor(xact=>1, authtoken=>$authtoken);
2539 return $e->die_event unless $e->checkauth;
2541 my $method = "retrieve_serial_${type}_note";
2542 my $note = $e->$method([
2544 ]) or return $e->die_event;
2546 if ($type eq 'item') {
2547 my $sitem = $e->retrieve_serial_item([
2549 "flesh" => 2, "flesh_fields" => {
2550 "sitem" => ["stream"], "sstr" => ["distribution"]
2553 ]) or return $e->die_event;
2555 return $e->die_event unless $e->allowed(
2556 "ADMIN_SERIAL_ITEM", $sitem->stream->distribution->holding_lib
2558 } elsif ($type eq 'distribution') {
2559 my $sdist = $e->retrieve_serial_distribution($note->distribution)
2560 or return $e->die_event;
2562 return $e->die_event unless
2563 $e->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2564 } else { # subscription
2565 my $sub = $e->retrieve_serial_subscription($note->subscription)
2566 or return $e->die_event;
2568 return $e->die_event unless
2569 $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
2572 $method = "delete_serial_${type}_note";
2573 $e->$method($note) or return $e->die_event;
2579 ##########################################################################
2580 # subscription methods
2583 __PACKAGE__->register_method(
2584 method => 'safe_delete',
2585 api_name => 'open-ils.serial.subscription.safe_delete',
2587 Deletes an existing subscription and related records
2588 (distributions, streams, etc.), but only if there are no serial
2589 items with a status other than Expected, and no non-deleted
2591 @param authtoken The login session key
2592 @param subid The id of the subscription to delete
2593 @return 1 on success - Event otherwise.
2597 __PACKAGE__->register_method(
2598 method => 'safe_delete',
2599 api_name => 'open-ils.serial.distribution.safe_delete',
2601 Deletes an existing distribution and related records
2602 (streams, etc.), but only if there are no attached serial items
2603 with a status other than Expected, and no non-deleted serial
2605 @param authtoken The login session key
2606 @param subid The id of the distribution to delete
2607 @return 1 on success - Event otherwise.
2611 __PACKAGE__->register_method(
2612 method => 'safe_delete',
2613 api_name => 'open-ils.serial.stream.safe_delete',
2615 Deletes an existing stream and associated routing list, but only
2616 if there are no attached serial items with a status other than
2617 Expected, and no non-deleted serial units.
2618 items and no issuances.
2619 @param authtoken The login session key
2620 @param strid The id of the stream to delete
2621 @return 1 on success - Event otherwise.
2625 __PACKAGE__->register_method(
2626 method => 'safe_delete',
2627 api_name => 'open-ils.serial.caption_and_pattern.safe_delete',
2629 Deletes an existing caption and pattern object, but only
2630 if there are no attached serial issuances.
2631 @param authtoken The login session key
2632 @param strid The id of the scap to delete
2633 @return 1 on success - Event otherwise.
2637 __PACKAGE__->register_method(
2638 method => 'safe_delete',
2639 api_name => 'open-ils.serial.subscription.safe_delete.dry_run',
2641 __PACKAGE__->register_method(
2642 method => 'safe_delete',
2643 api_name => 'open-ils.serial.distribution.safe_delete.dry_run',
2645 __PACKAGE__->register_method(
2646 method => 'safe_delete',
2647 api_name => 'open-ils.serial.stream.safe_delete.dry_run',
2649 __PACKAGE__->register_method(
2650 method => 'safe_delete',
2651 api_name => 'open-ils.serial.caption_and_pattern.safe_delete.dry_run',
2655 my( $self, $conn, $authtoken, $id ) = @_;
2657 $self->api_name =~ /serial\.(\w*)\.safe_delete/;
2660 my $e = new_editor(xact=>1, authtoken=>$authtoken);
2661 return $e->die_event unless $e->checkauth;
2665 if ($type eq 'stream') {
2666 my $sstr = $e->retrieve_serial_stream([
2668 "flesh" => 2, "flesh_fields" => {
2669 "sstr" => ["items","distribution"],
2673 ]) or return $e->die_event;
2675 return $e->die_event unless $e->allowed(
2676 "ADMIN_SERIAL_STREAM", $sstr->distribution->holding_lib
2679 foreach my $sitem (@{$sstr->items}) {
2680 if ($sitem->status ne 'Expected') {
2681 return $e->die_event(OpenILS::Event->new('SERIAL_STREAM_NOT_EMPTY', payload=>$id));
2683 if ($sitem->unit && !$U->is_true($sitem->unit->deleted)) {
2684 return $e->die_event(OpenILS::Event->new('SERIAL_STREAM_NOT_EMPTY', payload=>$id));
2690 } elsif ($type eq 'distribution') {
2691 my $sdist = $e->retrieve_serial_distribution([
2693 "flesh" => 3, "flesh_fields" => {
2694 "sstr" => ["items"],
2695 "sdist" => ["streams"],
2699 ]) or return $e->die_event;
2701 return $e->die_event unless
2702 $e->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2704 foreach my $sstr (@{$sdist->streams}) {
2705 foreach my $sitem (@{$sstr->items}) {
2706 if ($sitem->status ne 'Expected') {
2707 return $e->die_event(OpenILS::Event->new('SERIAL_DISTRIBUTION_NOT_EMPTY', payload=>$id));
2709 if ($sitem->unit && !$U->is_true($sitem->unit->deleted)) {
2710 return $e->die_event(OpenILS::Event->new('SERIAL_DISTRIBUTION_NOT_EMPTY', payload=>$id));
2717 } elsif ($type eq 'caption_and_pattern') {
2718 my $scap = $e->retrieve_serial_caption_and_pattern([
2720 { flesh => 1, flesh_fields => { scap => ['subscription'] } }
2721 ]) or return $e->die_event;
2723 return $e->die_event unless
2724 $e->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $scap->subscription->owning_lib);
2726 my $issuances = $e->search_serial_issuance([{
2727 caption_and_pattern => $id
2736 foreach my $siss (@$issuances) {
2737 foreach my $sitem (@{$siss->items}) {
2738 if ($sitem->status ne 'Expected') {
2739 return $e->die_event(OpenILS::Event->new('SERIAL_CAPTION_AND_PATTERN_NOT_EMPTY', payload=>$id));
2741 if ($sitem->unit && !$U->is_true($sitem->unit->deleted)) {
2742 return $e->die_event(OpenILS::Event->new('SERIAL_CAPTION_AND_PATTERN_NOT_EMPTY', payload=>$id));
2749 } else { # subscription
2750 my $sub = $e->retrieve_serial_subscription([
2752 "flesh" => 4, "flesh_fields" => {
2753 "ssub" => [qw/distributions issuances/],
2754 "sdist" => [qw/streams/],
2755 "sstr" => ["items"],
2759 ]) or return $e->die_event;
2761 return $e->die_event unless
2762 $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
2764 foreach my $sdist (@{$sub->distributions}) {
2765 foreach my $sstr (@{$sdist->streams}) {
2766 foreach my $sitem (@{$sstr->items}) {
2767 if ($sitem->status ne 'Expected') {
2768 return $e->die_event(OpenILS::Event->new('SERIAL_SUBSCRIPTION_NOT_EMPTY', payload=>$id));
2770 if ($sitem->unit && !$U->is_true($sitem->unit->deleted)) {
2771 return $e->die_event(OpenILS::Event->new('SERIAL_SUBSCRIPTION_NOT_EMPTY', payload=>$id));
2780 if (! ($self->api_name =~ /dry_run/)) {
2781 my $method = "delete_serial_${type}";
2782 $e->$method($obj) or return $e->die_event;
2789 __PACKAGE__->register_method(
2790 method => 'fleshed_ssub_alter',
2791 api_name => 'open-ils.serial.subscription.fleshed.batch.update',
2795 desc => 'Receives an array of one or more subscriptions and updates the database as needed',
2797 name => 'authtoken',
2798 desc => 'Authtoken for current user session',
2802 name => 'subscriptions',
2803 desc => 'Array of fleshed subscriptions',
2809 desc => 'Returns 1 if successful, event if failed',
2815 sub fleshed_ssub_alter {
2816 my( $self, $conn, $auth, $ssubs ) = @_;
2817 return 1 unless ref $ssubs;
2818 my( $reqr, $evt ) = $U->checkses($auth);
2819 return $evt if $evt;
2820 my $editor = new_editor(requestor => $reqr, xact => 1);
2821 my $override = $self->api_name =~ /override/;
2823 for my $ssub (@$ssubs) {
2824 my $owning_lib_id = ref $ssub->owning_lib ? $ssub->owning_lib->id : $ssub->owning_lib;
2825 return $editor->die_event unless
2826 $editor->allowed("ADMIN_SERIAL_SUBSCRIPTION", $owning_lib_id);
2828 my $ssubid = $ssub->id;
2830 if( $ssub->isdeleted ) {
2831 $evt = _delete_ssub( $editor, $override, $ssub);
2832 } elsif( $ssub->isnew ) {
2833 _cleanse_dates($ssub, ['start_date','end_date']);
2834 $evt = _create_ssub( $editor, $ssub );
2836 _cleanse_dates($ssub, ['start_date','end_date']);
2837 $evt = _update_ssub( $editor, $override, $ssub );
2842 $logger->info("fleshed subscription-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2846 $logger->debug("subscription-alter: done updating subscription batch");
2848 $logger->info("fleshed subscription-alter successfully updated ".scalar(@$ssubs)." subscriptions");
2853 my ($editor, $override, $ssub) = @_;
2854 $logger->info("subscription-alter: delete subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2855 my $sdists = $editor->search_serial_distribution(
2856 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2857 my $cps = $editor->search_serial_caption_and_pattern(
2858 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2859 my $sisses = $editor->search_serial_issuance(
2860 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2861 return OpenILS::Event->new(
2862 'SERIAL_SUBSCRIPTION_NOT_EMPTY', payload => $ssub->id ) if (@$sdists or @$cps or @$sisses);
2864 return $editor->event unless $editor->delete_serial_subscription($ssub);
2869 my ($editor, $ssub) = @_;
2871 $logger->info("subscription-alter: new subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2872 return $editor->event unless $editor->create_serial_subscription($ssub);
2877 my ($editor, $override, $ssub) = @_;
2879 $logger->info("subscription-alter: retrieving subscription ".$ssub->id);
2880 my $orig_ssub = $editor->retrieve_serial_subscription($ssub->id);
2882 $logger->info("subscription-alter: original subscription ".OpenSRF::Utils::JSON->perl2JSON($orig_ssub));
2883 $logger->info("subscription-alter: updated subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2884 return $editor->event unless $editor->update_serial_subscription($ssub);
2888 __PACKAGE__->register_method(
2889 method => "fleshed_serial_subscription_retrieve_batch",
2891 api_name => "open-ils.serial.subscription.fleshed.batch.retrieve"
2894 sub fleshed_serial_subscription_retrieve_batch {
2895 my( $self, $client, $ids ) = @_;
2896 # FIXME: permissions?
2897 $logger->info("Fetching fleshed subscriptions @$ids");
2898 return $U->cstorereq(
2899 "open-ils.cstore.direct.serial.subscription.search.atomic",
2902 flesh_fields => {ssub => [ qw/owning_lib notes/ ]}
2906 __PACKAGE__->register_method(
2907 method => "retrieve_sub_tree",
2909 api_name => "open-ils.serial.subscription_tree.retrieve"
2912 __PACKAGE__->register_method(
2913 method => "retrieve_sub_tree",
2914 api_name => "open-ils.serial.subscription_tree.global.retrieve"
2917 sub retrieve_sub_tree {
2919 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2921 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2925 # TODO: permission support
2926 if(!@org_ids and $user_session) {
2928 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2929 @org_ids = ($user_obj->home_ou);
2932 if( $self->api_name =~ /global/ ) {
2933 return _build_subs_list( { record_entry => $docid } ); # TODO: filter for !deleted, or active?
2938 for my $orgid (@org_ids) {
2939 my $subs = _build_subs_list(
2940 { record_entry => $docid, owning_lib => $orgid } );# TODO: filter for !deleted, or active?
2941 push( @all_subs, @$subs );
2950 sub _build_subs_list {
2951 my $search_hash = shift;
2953 #$search_hash->{deleted} = 'f';
2954 my $e = new_editor();
2956 my $subs = $e->search_serial_subscription([$search_hash, { 'order_by' => {'ssub' => 'id'} }]);
2960 for my $sub (@$subs) {
2962 # TODO: filter on !deleted?
2963 my $dists = $e->search_serial_distribution(
2964 [{ subscription => $sub->id }, { 'order_by' => {'sdist' => 'label'} }]
2967 #$dists = [ sort { $a->label cmp $b->label } @$dists ];
2969 $sub->distributions($dists);
2971 # TODO: filter on !deleted?
2972 my $issuances = $e->search_serial_issuance(
2973 [{ subscription => $sub->id }, { 'order_by' => {'siss' => 'label'} }]
2976 #$issuances = [ sort { $a->label cmp $b->label } @$issuances ];
2977 $sub->issuances($issuances);
2979 # TODO: filter on !deleted?
2980 my $scaps = $e->search_serial_caption_and_pattern(
2981 [{ subscription => $sub->id }, { 'order_by' => {'scap' => 'id'} }]
2984 #$scaps = [ sort { $a->id cmp $b->id } @$scaps ];
2985 $sub->scaps($scaps);
2986 push( @built_subs, $sub );
2989 return \@built_subs;
2993 __PACKAGE__->register_method(
2994 method => "subscription_orgs_for_title",
2996 api_name => "open-ils.serial.subscription.retrieve_orgs_by_title"
2999 sub subscription_orgs_for_title {
3000 my( $self, $client, $record_id ) = @_;
3002 my $subs = $U->simple_scalar_request(
3004 "open-ils.cstore.direct.serial.subscription.search.atomic",
3005 { record_entry => $record_id }); # TODO: filter on !deleted?
3007 my $orgs = { map {$_->owning_lib => 1 } @$subs };
3008 return [ keys %$orgs ];
3012 ##########################################################################
3013 # distribution methods
3015 __PACKAGE__->register_method(
3016 method => 'fleshed_sdist_alter',
3017 api_name => 'open-ils.serial.distribution.fleshed.batch.update',
3021 desc => 'Receives an array of one or more distributions and updates the database as needed',
3023 name => 'authtoken',
3024 desc => 'Authtoken for current user session',
3028 name => 'distributions',
3029 desc => 'Array of fleshed distributions',
3035 desc => 'Returns 1 if successful, event if failed',
3041 sub fleshed_sdist_alter {
3042 my( $self, $conn, $auth, $sdists ) = @_;
3043 return 1 unless ref $sdists;
3044 my( $reqr, $evt ) = $U->checkses($auth);
3045 return $evt if $evt;
3046 my $editor = new_editor(requestor => $reqr, xact => 1);
3047 my $override = $self->api_name =~ /override/;
3049 for my $sdist (@$sdists) {
3050 my $holding_lib_id = ref $sdist->holding_lib ? $sdist->holding_lib->id : $sdist->holding_lib;
3051 return $editor->die_event unless
3052 $editor->allowed("ADMIN_SERIAL_DISTRIBUTION", $holding_lib_id);
3054 if( $sdist->isdeleted ) {
3055 $evt = _delete_sdist( $editor, $override, $sdist);
3056 } elsif( $sdist->isnew ) {
3057 $evt = _create_sdist( $editor, $sdist );
3059 $evt = _update_sdist( $editor, $override, $sdist );
3064 $logger->info("fleshed distribution-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
3068 $logger->debug("distribution-alter: done updating distribution batch");
3070 $logger->info("fleshed distribution-alter successfully updated ".scalar(@$sdists)." distributions");
3075 my ($editor, $override, $sdist) = @_;
3076 $logger->info("distribution-alter: delete distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
3077 return $editor->event unless $editor->delete_serial_distribution($sdist);
3082 my ($editor, $sdist) = @_;
3084 $logger->info("distribution-alter: new distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
3085 return $editor->event unless $editor->create_serial_distribution($sdist);
3087 # create summaries too
3088 my $summary = new Fieldmapper::serial::basic_summary;
3089 $summary->distribution($sdist->id);
3090 $summary->generated_coverage('');
3091 return $editor->event unless $editor->create_serial_basic_summary($summary);
3092 $summary = new Fieldmapper::serial::supplement_summary;
3093 $summary->distribution($sdist->id);
3094 $summary->generated_coverage('');
3095 return $editor->event unless $editor->create_serial_supplement_summary($summary);
3096 $summary = new Fieldmapper::serial::index_summary;
3097 $summary->distribution($sdist->id);
3098 $summary->generated_coverage('');
3099 return $editor->event unless $editor->create_serial_index_summary($summary);
3101 # create a starter stream (TODO: reconsider this)
3102 my $stream = new Fieldmapper::serial::stream;
3103 $stream->distribution($sdist->id);
3104 return $editor->event unless $editor->create_serial_stream($stream);
3110 my ($editor, $override, $sdist) = @_;
3112 $logger->info("distribution-alter: retrieving distribution ".$sdist->id);
3113 my $orig_sdist = $editor->retrieve_serial_distribution($sdist->id);
3115 $logger->info("distribution-alter: original distribution ".OpenSRF::Utils::JSON->perl2JSON($orig_sdist));
3116 $logger->info("distribution-alter: updated distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
3117 return $editor->event unless $editor->update_serial_distribution($sdist);
3121 __PACKAGE__->register_method(
3122 method => "fleshed_serial_distribution_retrieve_batch",
3124 api_name => "open-ils.serial.distribution.fleshed.batch.retrieve"
3127 sub fleshed_serial_distribution_retrieve_batch {
3128 my( $self, $client, $ids ) = @_;
3129 # FIXME: permissions?
3130 $logger->info("Fetching fleshed distributions @$ids");
3131 return $U->cstorereq(
3132 "open-ils.cstore.direct.serial.distribution.search.atomic",
3135 flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams notes / ]}
3139 __PACKAGE__->register_method(
3140 method => "retrieve_dist_tree",
3142 api_name => "open-ils.serial.distribution_tree.retrieve"
3145 __PACKAGE__->register_method(
3146 method => "retrieve_dist_tree",
3147 api_name => "open-ils.serial.distribution_tree.global.retrieve"
3150 sub retrieve_dist_tree {
3151 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
3153 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
3157 # TODO: permission support
3158 if(!@org_ids and $user_session) {
3160 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
3161 @org_ids = ($user_obj->home_ou);
3164 my $e = new_editor();
3166 if( $self->api_name =~ /global/ ) {
3167 return $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }},
3169 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 / ]},
3170 order_by => {'sdist' => 'id'},
3171 'join' => {'ssub' => {}}
3173 ]); # TODO: filter for !deleted?
3177 for my $orgid (@org_ids) {
3178 my $dists = $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }, holding_lib => $orgid},
3180 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 / ]},
3181 order_by => {'sdist' => 'id'},
3182 'join' => {'ssub' => {}}
3184 ]); # TODO: filter for !deleted?
3185 push( @all_dists, @$dists ) if $dists;
3195 __PACKAGE__->register_method(
3196 method => "distribution_orgs_for_title",
3198 api_name => "open-ils.serial.distribution.retrieve_orgs_by_title"
3201 sub distribution_orgs_for_title {
3202 my( $self, $client, $record_id ) = @_;
3204 my $dists = $U->cstorereq(
3205 "open-ils.cstore.direct.serial.distribution.search.atomic",
3206 { '+ssub' => { record_entry => $record_id } },
3207 { 'join' => {'ssub' => {}} }); # TODO: filter on !deleted?
3209 my $orgs = { map {$_->holding_lib => 1 } @$dists };
3210 return [ keys %$orgs ];
3214 ##########################################################################
3215 # caption and pattern methods
3217 __PACKAGE__->register_method(
3218 method => 'scap_alter',
3219 api_name => 'open-ils.serial.caption_and_pattern.batch.update',
3223 desc => 'Receives an array of one or more caption and patterns and updates the database as needed',
3225 name => 'authtoken',
3226 desc => 'Authtoken for current user session',
3231 desc => 'Array of caption and patterns',
3237 desc => 'Returns 1 if successful, event if failed',
3244 my( $self, $conn, $auth, $scaps ) = @_;
3245 return 1 unless ref $scaps;
3246 my( $reqr, $evt ) = $U->checkses($auth);
3247 return $evt if $evt;
3248 my $editor = new_editor(requestor => $reqr, xact => 1);
3249 my $override = $self->api_name =~ /override/;
3252 for my $scap (@$scaps) {
3253 if (!exists($found_ssub_ids{$scap->subscription})) {
3254 my $ssub = $editor->retrieve_serial_subscription($scap->subscription) or return $editor->die_event;
3255 return $editor->die_event unless
3256 $editor->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $ssub->owning_lib);
3257 $found_ssub_ids{$scap->subscription} = 1;
3260 if( $scap->isdeleted ) {
3261 $evt = _delete_scap( $editor, $override, $scap);
3262 } elsif( $scap->isnew ) {
3263 $evt = _create_scap( $editor, $scap );
3265 $evt = _update_scap( $editor, $override, $scap );
3270 $logger->info("caption_and_pattern-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
3274 $logger->debug("caption_and_pattern-alter: done updating caption_and_pattern batch");
3276 $logger->info("caption_and_pattern-alter successfully updated ".scalar(@$scaps)." caption_and_patterns");
3281 my ($editor, $override, $scap) = @_;
3282 $logger->info("caption_and_pattern-alter: delete caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
3283 my $sisses = $editor->search_serial_issuance(
3284 { caption_and_pattern => $scap->id }, { limit => 1 } ); #TODO: 'deleted' support?
3285 return OpenILS::Event->new(
3286 'SERIAL_CAPTION_AND_PATTERN_HAS_ISSUANCES', payload => $scap->id ) if (@$sisses);
3288 return $editor->event unless $editor->delete_serial_caption_and_pattern($scap);
3293 my ($editor, $scap) = @_;
3295 $logger->info("caption_and_pattern-alter: new caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
3296 return $editor->event unless $editor->create_serial_caption_and_pattern($scap);
3301 my ($editor, $override, $scap) = @_;
3303 $logger->info("caption_and_pattern-alter: retrieving caption_and_pattern ".$scap->id);
3304 my $orig_scap = $editor->retrieve_serial_caption_and_pattern($scap->id);
3306 $logger->info("caption_and_pattern-alter: original caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($orig_scap));
3307 $logger->info("caption_and_pattern-alter: updated caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
3308 return $editor->event unless $editor->update_serial_caption_and_pattern($scap);
3312 __PACKAGE__->register_method(
3313 method => "serial_caption_and_pattern_retrieve_batch",
3315 api_name => "open-ils.serial.caption_and_pattern.batch.retrieve"
3318 sub serial_caption_and_pattern_retrieve_batch {
3319 my( $self, $client, $ids ) = @_;
3320 $logger->info("Fetching caption_and_patterns @$ids");
3321 return $U->cstorereq(
3322 "open-ils.cstore.direct.serial.caption_and_pattern.search.atomic",
3327 ##########################################################################
3330 __PACKAGE__->register_method(
3331 method => 'sstr_alter',
3332 api_name => 'open-ils.serial.stream.batch.update',
3336 desc => 'Receives an array of one or more streams and updates the database as needed',
3338 name => 'authtoken',
3339 desc => 'Authtoken for current user session',
3344 desc => 'Array of streams',
3350 desc => 'Returns 1 if successful, event if failed',
3357 my( $self, $conn, $auth, $sstrs ) = @_;
3358 return 1 unless ref $sstrs;
3359 my( $reqr, $evt ) = $U->checkses($auth);
3360 return $evt if $evt;
3361 my $editor = new_editor(requestor => $reqr, xact => 1);
3362 my $override = $self->api_name =~ /override/;
3364 my %found_sdist_ids;
3365 for my $sstr (@$sstrs) {
3366 if (!exists($found_sdist_ids{$sstr->distribution})) {
3367 my $sdist = $editor->retrieve_serial_distribution($sstr->distribution) or return $editor->die_event;
3368 return $editor->die_event unless
3369 $editor->allowed("ADMIN_SERIAL_STREAM", $sdist->holding_lib);
3370 $found_sdist_ids{$sstr->distribution} = 1;
3373 if( $sstr->isdeleted ) {
3374 $evt = _delete_sstr( $editor, $override, $sstr);
3375 } elsif( $sstr->isnew ) {
3376 $evt = _create_sstr( $editor, $sstr );
3378 $evt = _update_sstr( $editor, $override, $sstr );
3383 $logger->info("stream-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
3387 $logger->debug("stream-alter: done updating stream batch");
3389 $logger->info("stream-alter successfully updated ".scalar(@$sstrs)." streams");
3394 my ($editor, $override, $sstr) = @_;
3395 $logger->info("stream-alter: delete stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
3396 my $sitems = $editor->search_serial_item(
3397 { stream => $sstr->id }, { limit => 1 } ); #TODO: 'deleted' support?
3398 return OpenILS::Event->new(
3399 'SERIAL_STREAM_HAS_ITEMS', payload => $sstr->id ) if (@$sitems);
3401 return $editor->event unless $editor->delete_serial_stream($sstr);
3406 my ($editor, $sstr) = @_;
3408 $logger->info("stream-alter: new stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
3409 return $editor->event unless $editor->create_serial_stream($sstr);
3414 my ($editor, $override, $sstr) = @_;
3416 $logger->info("stream-alter: retrieving stream ".$sstr->id);
3417 my $orig_sstr = $editor->retrieve_serial_stream($sstr->id);
3419 $logger->info("stream-alter: original stream ".OpenSRF::Utils::JSON->perl2JSON($orig_sstr));
3420 $logger->info("stream-alter: updated stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
3421 return $editor->event unless $editor->update_serial_stream($sstr);
3425 __PACKAGE__->register_method(
3426 method => "serial_stream_retrieve_batch",
3428 api_name => "open-ils.serial.stream.batch.retrieve"
3431 sub serial_stream_retrieve_batch {
3432 my( $self, $client, $ids ) = @_;
3433 $logger->info("Fetching streams @$ids");
3434 return $U->cstorereq(
3435 "open-ils.cstore.direct.serial.stream.search.atomic",
3441 ##########################################################################
3444 __PACKAGE__->register_method(
3445 method => 'sum_alter',
3446 api_name => 'open-ils.serial.basic_summary.batch.update',
3450 desc => 'Receives an array of one or more summaries and updates the database as needed',
3452 name => 'authtoken',
3453 desc => 'Authtoken for current user session',
3458 desc => 'Array of basic summaries',
3464 desc => 'Returns 1 if successful, event if failed',
3470 __PACKAGE__->register_method(
3471 method => 'sum_alter',
3472 api_name => 'open-ils.serial.supplement_summary.batch.update',
3476 desc => 'Receives an array of one or more summaries and updates the database as needed',
3478 name => 'authtoken',
3479 desc => 'Authtoken for current user session',
3484 desc => 'Array of supplement summaries',
3490 desc => 'Returns 1 if successful, event if failed',
3496 __PACKAGE__->register_method(
3497 method => 'sum_alter',
3498 api_name => 'open-ils.serial.index_summary.batch.update',
3502 desc => 'Receives an array of one or more summaries and updates the database as needed',
3504 name => 'authtoken',
3505 desc => 'Authtoken for current user session',
3510 desc => 'Array of index summaries',
3516 desc => 'Returns 1 if successful, event if failed',
3523 my( $self, $conn, $auth, $sums ) = @_;
3524 return 1 unless ref $sums;
3526 $self->api_name =~ /serial\.(\w*)_summary/;
3529 my( $reqr, $evt ) = $U->checkses($auth);
3530 return $evt if $evt;
3531 my $editor = new_editor(requestor => $reqr, xact => 1);
3532 my $override = $self->api_name =~ /override/;
3534 my %found_sdist_ids;
3535 for my $sum (@$sums) {
3536 if (!exists($found_sdist_ids{$sum->distribution})) {
3537 my $sdist = $editor->retrieve_serial_distribution($sum->distribution) or return $editor->die_event;
3538 return $editor->die_event unless
3539 $editor->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
3540 $found_sdist_ids{$sum->distribution} = 1;
3543 # XXX: (for now, at least) summaries should be created/deleted by the distribution functions
3544 if( $sum->isdeleted ) {
3545 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
3546 } elsif( $sum->isnew ) {
3547 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
3549 $evt = _update_sum( $editor, $override, $sum, $type );
3554 $logger->info("${type}_summary-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
3558 $logger->debug("${type}_summary-alter: done updating ${type}_summary batch");
3560 $logger->info("${type}_summary-alter successfully updated ".scalar(@$sums)." ${type}_summaries");
3565 my ($editor, $override, $sum, $type) = @_;
3567 $logger->info("${type}_summary-alter: retrieving ${type}_summary ".$sum->id);
3568 my $retrieve_method = "retrieve_serial_${type}_summary";
3569 my $orig_sum = $editor->$retrieve_method($sum->id);
3571 $logger->info("${type}_summary-alter: original ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($orig_sum));
3572 $logger->info("${type}_summary-alter: updated ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($sum));
3573 my $update_method = "update_serial_${type}_summary";
3574 return $editor->event unless $editor->$update_method($sum);
3578 __PACKAGE__->register_method(
3579 method => "serial_summary_retrieve_batch",
3581 api_name => "open-ils.serial.basic_summary.batch.retrieve"
3584 __PACKAGE__->register_method(
3585 method => "serial_summary_retrieve_batch",
3587 api_name => "open-ils.serial.supplement_summary.batch.retrieve"
3590 __PACKAGE__->register_method(
3591 method => "serial_summary_retrieve_batch",
3593 api_name => "open-ils.serial.index_summary.batch.retrieve"
3596 sub serial_summary_retrieve_batch {
3597 my( $self, $client, $ids ) = @_;
3599 $self->api_name =~ /serial\.(\w*)_summary/;
3602 $logger->info("Fetching ${type}_summaries @$ids");
3603 return $U->cstorereq(
3604 "open-ils.cstore.direct.serial.".$type."_summary.search.atomic",
3610 ##########################################################################
3613 __PACKAGE__->register_method(
3614 "method" => "bre_by_identifier",
3615 "api_name" => "open-ils.serial.biblio.record_entry.by_identifier",
3618 "desc" => "Find instances of biblio.record_entry given a search token" .
3619 " that could be a value for any identifier defined in " .
3620 "config.metabib_field",
3622 {"desc" => "Search token", "type" => "string"},
3623 {"desc" => "Options: require_subscriptions, add_mvr, is_actual_id" .
3624 ", id_list (all boolean)", "type" => "object"}
3627 "desc" => "Any matching BREs, or if the add_mvr option is true, " .
3628 "objects with a 'bre' key/value pair, and an 'mvr' " .
3629 "key-value pair. BREs have subscriptions fleshed on.",
3635 sub bre_by_identifier {
3636 my ($self, $client, $term, $options) = @_;
3638 return new OpenILS::Event("BAD_PARAMS") unless $term;
3641 my $e = new_editor();
3645 if ($options->{"is_actual_id"}) {
3649 $e->search_config_metabib_field({"field_class" => "identifier"})
3650 or return $e->die_event;
3652 my @identifiers = map { $_->name } @$cmf;
3653 my $query = join(" || ", map { "id|$_: $term" } @identifiers);
3655 my $search = create OpenSRF::AppSession("open-ils.search");
3656 my $search_result = $search->request(
3657 "open-ils.search.biblio.multiclass.query.staff", {}, $query
3659 $search->disconnect;
3661 # Un-nest results. They tend to look like [[1],[2],[3]] for some reason.
3662 @ids = map { @{$_}[0] } @{$search_result->{"ids"}};
3669 if ($options->{"id_list"}) {
3671 $client->respond($_) foreach (@ids);
3676 my $bre = $e->search_biblio_record_entry([
3678 "flesh" => 2, "flesh_fields" => {
3679 "bre" => ["subscriptions"],
3680 "ssub" => ["owning_lib"]
3683 ]) or return $e->die_event;
3685 if (@$bre && $options->{"require_subscriptions"}) {
3686 $bre = [ grep { @{$_->subscriptions} } @$bre ];
3691 if (@$bre) { # re-evaluate after possible grep
3692 if ($options->{"add_mvr"}) {
3694 {"bre" => $_, "mvr" => _get_mvr($_->id)}
3697 $client->respond($_) foreach (@$bre);
3704 __PACKAGE__->register_method(
3705 "method" => "get_items_by",
3706 "api_name" => "open-ils.serial.items.receivable.by_subscription",
3709 "desc" => "Return all receivable items under a given subscription",
3711 {"desc" => "Authtoken", "type" => "string"},
3712 {"desc" => "Subscription ID", "type" => "number"},
3715 "desc" => "All receivable items under a given subscription",
3716 "type" => "object", "class" => "sitem"
3721 __PACKAGE__->register_method(
3722 "method" => "get_items_by",
3723 "api_name" => "open-ils.serial.items.receivable.by_issuance",
3726 "desc" => "Return all receivable items under a given issuance",
3728 {"desc" => "Authtoken", "type" => "string"},
3729 {"desc" => "Issuance ID", "type" => "number"},
3732 "desc" => "All receivable items under a given issuance",
3733 "type" => "object", "class" => "sitem"
3738 __PACKAGE__->register_method(
3739 "method" => "get_items_by",
3740 "api_name" => "open-ils.serial.items.by_issuance",
3743 "desc" => "Return all items under a given issuance",
3745 {"desc" => "Authtoken", "type" => "string"},
3746 {"desc" => "Issuance ID", "type" => "number"},
3749 "desc" => "All items under a given issuance",
3750 "type" => "object", "class" => "sitem"
3756 my ($self, $client, $auth, $term, $opts) = @_;
3758 # Not to be used in the json_query, but after limiting by perm check.
3759 $opts = {} unless ref $opts eq "HASH";
3760 $opts->{"limit"} ||= 10000; # some existing users may want all results
3761 $opts->{"offset"} ||= 0;
3762 $opts->{"limit"} = int($opts->{"limit"});
3763 $opts->{"offset"} = int($opts->{"offset"});
3765 my $e = new_editor("authtoken" => $auth);
3766 return $e->die_event unless $e->checkauth;
3768 my $by = ($self->api_name =~ /by_(\w+)$/)[0];
3769 my $receivable = ($self->api_name =~ /receivable/);
3772 "issuance" => {"issuance" => $term},
3773 "subscription" => {"+siss" => {"subscription" => $term}}
3776 my $item_rows = $e->json_query(
3778 "select" => {"sitem" => ["id"], "sdist" => ["holding_lib"]},
3782 "sstr" => {"join" => {"sdist" => {}}}
3786 %{$where{$by}}, $receivable ? ("date_received" => undef) : ()
3788 "order_by" => {"sitem" => ["id"]}
3790 ) or return $e->die_event;
3792 return undef unless @$item_rows;
3796 foreach (@$item_rows) {
3797 last if $returned >= $opts->{"limit"};
3798 next unless $e->allowed("RECEIVE_SERIAL", $_->{"holding_lib"});
3799 if ($skipped < $opts->{"offset"}) {
3805 $e->retrieve_serial_item([
3809 "sitem" => [qw/stream issuance unit creator editor/],
3810 "sstr" => ["distribution"],
3811 "sdist" => ["holding_lib"]
3823 __PACKAGE__->register_method(
3824 "method" => "get_receivable_issuances",
3825 "api_name" => "open-ils.serial.issuances.receivable",
3828 "desc" => "Return all issuances with receivable items given " .
3829 "a subscription ID",
3831 {"desc" => "Authtoken", "type" => "string"},
3832 {"desc" => "Subscription ID", "type" => "number"},
3835 "desc" => "All issuances with receivable items " .
3836 "(but not the items themselves)", "type" => "object"
3841 sub get_receivable_issuances {
3842 my ($self, $client, $auth, $sub_id) = @_;
3844 my $e = new_editor("authtoken" => $auth);
3845 return $e->die_event unless $e->checkauth;
3849 my $issuance_ids = $e->json_query({
3852 {"transform" => "distinct", "column" => "id"},
3856 "from" => {"siss" => "sitem"},
3858 "subscription" => $sub_id,
3859 "+sitem" => {"date_received" => undef}
3862 "siss" => {"date_published" => {"direction" => "asc"}}
3865 }) or return $e->die_event;
3867 $client->respond($e->retrieve_serial_issuance($_->{"id"}))
3868 foreach (@$issuance_ids);
3875 __PACKAGE__->register_method(
3876 "method" => "get_routing_list_users",
3877 "api_name" => "open-ils.serial.routing_list_users.fleshed_and_ordered",
3880 "desc" => "Return all routing list users with reader fleshed " .
3881 "(with card and home_ou) for a given stream ID, sorted by pos",
3883 {"desc" => "Authtoken", "type" => "string"},
3884 {"desc" => "Stream ID (int or array of ints)", "type" => "mixed"},
3887 "desc" => "Stream of routing list users", "type" => "object",
3893 sub get_routing_list_users {
3894 my ($self, $client, $auth, $stream_id) = @_;
3896 my $e = new_editor("authtoken" => $auth);
3897 return $e->die_event unless $e->checkauth;
3899 my $users = $e->search_serial_routing_list_user([
3900 {"stream" => $stream_id}, {
3901 "order_by" => {"srlu" => "pos"},
3904 "srlu" => [qw/reader stream/],
3905 "au" => [qw/card home_ou mailing_address billing_address/],
3906 "sstr" => ["distribution"]
3909 ]) or return $e->die_event;
3911 return undef unless @$users;
3913 # The ADMIN_SERIAL_STREAM permission is used simply to avoid the
3914 # need for any new permission. The context OU will be the same
3915 # for every result of the above query, so we need only check once.
3916 return $e->die_event unless $e->allowed(
3917 "ADMIN_SERIAL_STREAM", $users->[0]->stream->distribution->holding_lib
3922 my @users = map { $_->stream($_->stream->id); $_ } @$users;
3923 @users = sort { $a->stream cmp $b->stream } @users if
3924 ref $stream_id eq "ARRAY";
3926 $client->respond($_) for @users;
3932 __PACKAGE__->register_method(
3933 "method" => "replace_routing_list_users",
3934 "api_name" => "open-ils.serial.routing_list_users.replace",
3936 "desc" => "Replace all routing list users on the specified streams " .
3937 "with those in the list argument",
3939 {"desc" => "Authtoken", "type" => "string"},
3940 {"desc" => "List of srlu objects", "type" => "array"},
3943 "desc" => "event on failure, undef on success"
3948 sub replace_routing_list_users {
3949 my ($self, $client, $auth, $users) = @_;
3951 return undef unless ref $users eq "ARRAY";
3953 if (grep { ref $_ ne "Fieldmapper::serial::routing_list_user" } @$users) {
3954 return new OpenILS::Event("BAD_PARAMS", "note" => "Only srlu objects");
3957 my $e = new_editor("authtoken" => $auth, "xact" => 1);
3958 return $e->die_event unless $e->checkauth;
3960 my %streams_ok = ();
3963 foreach my $user (@$users) {
3964 unless (exists $streams_ok{$user->stream}) {
3965 my $stream = $e->retrieve_serial_stream([
3968 "flesh_fields" => {"sstr" => ["distribution"]}
3970 ]) or return $e->die_event;
3972 "ADMIN_SERIAL_STREAM", $stream->distribution->holding_lib
3973 ) or return $e->die_event;
3975 my $to_delete = $e->search_serial_routing_list_user(
3976 {"stream" => $user->stream}
3977 ) or return $e->die_event;
3980 "Deleting srlu: [" .
3981 join(", ", map { $_->id; } @$to_delete) .
3985 foreach (@$to_delete) {
3986 $e->delete_serial_routing_list_user($_) or
3987 return $e->die_event;
3990 $streams_ok{$user->stream} = 1;
3993 next if $user->isdeleted;
3997 $e->create_serial_routing_list_user($user) or return $e->die_event;
4000 $e->commit or return $e->die_event;
4004 __PACKAGE__->register_method(
4005 "method" => "get_records_with_marc_85x",
4006 "api_name"=>"open-ils.serial.caption_and_pattern.find_legacy_by_bib_record",
4009 "desc" => "Return the specified BRE itself and/or any related SRE ".
4010 "whenever they have 853-855 tags",
4012 {"desc" => "Authtoken", "type" => "string"},
4013 {"desc" => "bib record ID", "type" => "number"},
4016 "desc" => "objects, either bre or sre", "type" => "object"
4021 sub get_records_with_marc_85x { # specifically, 853-855
4022 my ($self, $client, $auth, $bre_id) = @_;
4024 my $e = new_editor("authtoken" => $auth);
4025 return $e->die_event unless $e->checkauth;
4027 my $bre = $e->search_biblio_record_entry([
4028 {"id" => $bre_id, "deleted" => "f"}, {
4030 "flesh_fields" => {"bre" => [qw/creator editor owner/]}
4032 ]) or return $e->die_event;
4034 return undef unless @$bre;
4037 my $record = MARC::Record->new_from_xml($bre->marc);
4038 $client->respond($bre) if $record->field("85[3-5]");
4039 # XXX Is passing a regex to ->field() an abuse of MARC::Record ?
4041 my $sres = $e->search_serial_record_entry([
4042 {"record" => $bre_id, "deleted" => "f"}, {
4044 "flesh_fields" => {"sre" => [qw/creator editor owning_lib/]}
4046 ]) or return $e->die_event;
4050 foreach my $sre (@$sres) {
4051 $client->respond($sre) if
4052 MARC::Record->new_from_xml($sre->marc)->field("85[3-5]");
4058 __PACKAGE__->register_method(
4059 "method" => "create_scaps_from_marcxml",
4060 "api_name" => "open-ils.serial.caption_and_pattern.create_from_records",
4063 "desc" => "Create caption and pattern objects from 853-855 tags " .
4064 "in MARCXML documents",
4066 {"desc" => "Authtoken", "type" => "string"},
4067 {"desc" => "Subscription ID", "type" => "number"},
4068 {"desc" => "list of MARCXML documents as strings",
4072 "desc" => "Newly created caption and pattern objects",
4073 "type" => "object", "class" => "scap"
4078 sub create_scaps_from_marcxml {
4079 my ($self, $client, $auth, $sub_id, $docs) = @_;
4081 return undef unless ref $docs eq "ARRAY";
4083 my $e = new_editor("authtoken" => $auth, "xact" => 1);
4084 return $e->die_event unless $e->checkauth;
4086 # Retrieve the subscription just for perm checking (whether we can create
4087 # scaps at the owning lib).
4088 my $sub = $e->retrieve_serial_subscription($sub_id) or return $e->die_event;
4089 return $e->die_event unless
4090 $e->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $sub->owning_lib);
4092 foreach my $record (map { MARC::Record->new_from_xml($_) } @$docs) {
4093 foreach my $field ($record->field("85[3-5]")) {
4094 my $scap = new Fieldmapper::serial::caption_and_pattern;
4095 $scap->subscription($sub_id);
4096 $scap->type($MFHD_NAMES_BY_TAG{$field->tag});
4097 $scap->pattern_code(
4098 OpenSRF::Utils::JSON->perl2JSON(
4099 [ $field->indicator(1), $field->indicator(2),
4100 map { @$_ } $field->subfields ] # flattens nested array
4103 $e->create_serial_caption_and_pattern($scap) or
4104 return $e->die_event;
4105 $client->respond($e->data);
4109 $e->commit or return $e->die_event;
4113 # All these _clone_foo() functions could possibly have been consolidated into
4114 # one clever function, but it's faster to get things working this way.
4115 sub _clone_subscription {
4116 my ($sub, $bib_id, $e) = @_;
4119 my $new_sub = $sub->clone;
4120 $new_sub->record_entry(int $bib_id) if $bib_id;
4122 $new_sub->clear_distributions;
4123 $new_sub->clear_notes;
4124 $new_sub->clear_scaps;
4126 $e->create_serial_subscription($new_sub) or return $e->die_event;
4128 my $new_sub_id = $e->data->id;
4130 foreach my $dist (@{$sub->distributions}) {
4131 my $r = _clone_distribution($dist, $new_sub_id, $e);
4132 return $r if $U->event_code($r);
4136 foreach my $note (@{$sub->notes}) {
4137 my $r = _clone_subscription_note($note, $new_sub_id, $e);
4138 return $r if $U->event_code($r);
4142 foreach my $scap (@{$sub->scaps}) {
4143 my $r = _clone_caption_and_pattern($scap, $new_sub_id, $e);
4144 return $r if $U->event_code($r);
4150 sub _clone_distribution {
4151 my ($dist, $sub_id, $e) = @_;
4153 my $new_dist = $dist->clone;
4154 $new_dist->clear_id;
4155 $new_dist->clear_notes;
4156 $new_dist->clear_streams;
4157 $new_dist->subscription($sub_id);
4159 $e->create_serial_distribution($new_dist) or return $e->die_event;
4160 my $new_dist_id = $e->data->id;
4163 foreach my $stream (@{$dist->streams}) {
4164 my $r = _clone_stream($stream, $new_dist_id, $e);
4165 return $r if $U->event_code($r);
4168 # clone distribution notes
4169 foreach my $note (@{$dist->notes}) {
4170 my $r = _clone_distribution_note($note, $new_dist_id, $e);
4171 return $r if $U->event_code($r);
4174 return $new_dist_id;
4177 sub _clone_subscription_note {
4178 my ($note, $sub_id, $e) = @_;
4180 my $new_note = $note->clone;
4181 $new_note->clear_id;
4182 $new_note->creator($e->requestor->id);
4183 $new_note->create_date("now");
4184 $new_note->subscription($sub_id);
4186 $e->create_serial_subscription_note($new_note) or return $e->die_event;
4187 return $e->data->id;
4190 sub _clone_caption_and_pattern {
4191 my ($scap, $sub_id, $e) = @_;
4193 my $new_scap = $scap->clone;
4194 $new_scap->clear_id;
4195 $new_scap->subscription($sub_id);
4197 $e->create_serial_caption_and_pattern($new_scap) or return $e->die_event;
4198 return $e->data->id;
4201 sub _clone_distribution_note {
4202 my ($note, $dist_id, $e) = @_;
4204 my $new_note = $note->clone;
4205 $new_note->clear_id;
4206 $new_note->creator($e->requestor->id);
4207 $new_note->create_date("now");
4208 $new_note->distribution($dist_id);
4210 $e->create_serial_distribution_note($new_note) or return $e->die_event;
4211 return $e->data->id;
4215 my ($stream, $dist_id, $e) = @_;
4217 my $new_stream = $stream->clone;
4218 $new_stream->clear_id;
4219 $new_stream->clear_routing_list_users;
4220 $new_stream->distribution($dist_id);
4222 $e->create_serial_stream($new_stream) or return $e->die_event;
4223 my $new_stream_id = $e->data->id;
4225 # clone routing list users
4226 foreach my $user (@{$stream->routing_list_users}) {
4227 my $r = _clone_routing_list_user($user, $new_stream_id, $e);
4228 return $r if $U->event_code($r);
4231 return $new_stream_id;
4234 sub _clone_routing_list_user {
4235 my ($user, $stream_id, $e) = @_;
4237 my $new_user = $user->clone;
4238 $new_user->clear_id;
4239 $new_user->stream($stream_id);
4241 $e->create_serial_routing_list_user($new_user) or return $e->die_event;
4242 return $e->data->id;
4245 __PACKAGE__->register_method(
4246 "method" => "clone_subscription",
4247 "api_name" => "open-ils.serial.subscription.clone",
4249 "desc" => q{Clone a subscription, including its attending distributions,
4250 streams, captions and patterns, routing list users, distribution
4251 notes and subscription notes. Do not include holdings-specific
4252 things, like issuances, items, units, summaries. Attach the
4253 clone either to the same bib record as the original, or to one
4256 {"desc" => "Authtoken", "type" => "string"},
4257 {"desc" => "Subscription ID", "type" => "number"},
4258 {"desc" => "Bib Record ID (optional)", "type" => "number"}
4261 "desc" => "ID of the new subscription", "type" => "number"
4266 sub clone_subscription {
4267 my ($self, $client, $auth, $sub_id, $bib_id) = @_;
4269 my $e = new_editor("authtoken" => $auth, "xact" => 1);
4270 return $e->die_event unless $e->checkauth;
4272 my $sub = $e->retrieve_serial_subscription([
4276 "ssub" => [qw/distributions notes scaps/],
4277 "sdist" => [qw/streams notes/],
4278 "sstr" => ["routing_list_users"]
4281 ]) or return $e->die_event;
4283 # ADMIN_SERIAL_SUBSCRIPTION will have to be good enough as a
4284 # catch-all permisison for this operation.
4285 return $e->die_event unless
4286 $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
4288 my $result = _clone_subscription($sub, $bib_id, $e);
4290 return $e->die_event($result) if $U->event_code($result);
4292 $e->commit or return $e->die_event;
4296 __PACKAGE__->register_method(
4297 "method" => "summary_test",
4298 "api_name" => "open-ils.serial.summary_test",
4304 # This crummy little test method allows quicker reproduction of certain
4305 # failures (e.g. at item receive time) of the holdings summarization code.
4306 # Pass it an authtoken, an array of issuance IDs, and a single sdist ID
4308 my ($self, $conn, $authtoken, $iss_id_list, $sdist_id) = @_;
4310 my $e = new_editor(authtoken => $authtoken, xact => 1);
4311 return $e->die_event unless $e->checkauth;
4312 return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
4315 foreach my $id (@$iss_id_list) {
4316 my $iss = $e->retrieve_serial_issuance($id) or return $e->die_event;
4317 push @issuances, $iss;
4320 my $dist = $e->retrieve_serial_distribution($sdist_id) or return $e->die_event;
4322 $conn->respond(_summarize_contents($e, \@issuances, $dist));
4327 __PACKAGE__->register_method(
4328 "method" => "fetch_pattern_templates",
4329 "api_name" => "open-ils.serial.pattern_template.retrieve.at",
4332 "desc" => q{Return the set of pattern templates that are
4333 visible to the specified library.},
4335 {"desc" => "Authtoken", "type" => "string"},
4336 {"desc" => "OU ID", "type" => "number"},
4339 desc => "stream of pattern templates",
4340 type => "object", class => "spt"
4345 sub fetch_pattern_templates {
4346 my ($self, $client, $auth, $org_unit) = @_;
4348 my $e = new_editor("authtoken" => $auth);
4349 return $e->die_event unless $e->checkauth;
4351 my $patterns = $e->json_query({
4352 from => [ 'serial.pattern_templates_visible_to' => $org_unit ]
4354 $logger->info(Dumper($patterns)); use Data::Dumper;
4356 $client->respond($e->retrieve_serial_pattern_template($_->{id}))
4357 foreach (@$patterns);