3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 OpenILS::Application::Serial - Performs serials-related tasks such as receiving issues and generating predictions
31 Dan Wells, dbw2@calvin.edu
35 package OpenILS::Application::Serial;
41 use OpenILS::Application;
42 use base qw/OpenILS::Application/;
43 use OpenILS::Application::AppUtils;
45 use OpenSRF::AppSession;
46 use OpenSRF::Utils qw/:datetime/;
47 use OpenSRF::Utils::Logger qw/:logger/;
48 use OpenILS::Utils::CStoreEditor q/:funcs/;
49 use OpenILS::Utils::Fieldmapper;
50 use OpenILS::Utils::MFHD;
51 use DateTime::Format::ISO8601;
52 use MARC::File::XML (BinaryEncoding => 'utf8');
54 use OpenILS::Application::Serial::OPAC;
56 my $U = 'OpenILS::Application::AppUtils';
57 my @MFHD_NAMES = ('basic','supplement','index');
58 my %MFHD_NAMES_BY_TAG = ( '853' => $MFHD_NAMES[0],
59 '863' => $MFHD_NAMES[0],
60 '854' => $MFHD_NAMES[1],
61 '864' => $MFHD_NAMES[1],
62 '855' => $MFHD_NAMES[2],
63 '865' => $MFHD_NAMES[2] );
64 my %MFHD_TAGS_BY_NAME = ( $MFHD_NAMES[0] => '853',
65 $MFHD_NAMES[1] => '854',
66 $MFHD_NAMES[2] => '855');
67 my $_strp_date = new DateTime::Format::Strptime(pattern => '%F');
69 'subscription' => 'ssub',
70 'distribution' => 'sdist',
74 # helper method for conforming dates to ISO8601
79 foreach my $field (@$fields) {
80 $item->$field(OpenSRF::Utils::clense_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 for my $item (@$items) {
261 my $sstr_id = ref $item->stream ? $item->stream->id : $item->stream;
262 if (!exists($found_sstr_ids{$sstr_id})) {
264 if (ref $item->stream) {
265 $sstr = $item->stream;
267 $sstr = $editor->retrieve_serial_stream($item->stream) or return $editor->die_event;
269 if (!exists($found_sdist_ids{$sstr->distribution})) {
270 my $sdist = $editor->retrieve_serial_distribution($sstr->distribution) or return $editor->die_event;
271 return $editor->die_event unless
272 $editor->allowed("ADMIN_SERIAL_STREAM", $sdist->holding_lib);
273 $found_sdist_ids{$sstr->distribution} = 1;
275 $found_sstr_ids{$sstr_id} = 1;
278 $item->editor($editor->requestor->id);
279 $item->edit_date('now');
281 if( $item->isdeleted ) {
282 $evt = _delete_sitem( $editor, $override, $item);
283 } elsif( $item->isnew ) {
284 # TODO: reconsider this
285 # if the item has a new issuance, create the issuance first
286 if (ref $item->issuance eq 'Fieldmapper::serial::issuance' and $item->issuance->isnew) {
287 fleshed_issuance_alter($self, $conn, $auth, [$item->issuance]);
289 _cleanse_dates($item, ['date_expected','date_received']);
290 $evt = _create_sitem( $editor, $item );
292 _cleanse_dates($item, ['date_expected','date_received']);
293 $evt = _update_sitem( $editor, $override, $item );
298 $logger->info("fleshed item-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
302 $logger->debug("item-alter: done updating item batch");
304 $logger->info("fleshed item-alter successfully updated ".scalar(@$items)." items");
309 my ($editor, $override, $item) = @_;
310 $logger->info("item-alter: delete item ".OpenSRF::Utils::JSON->perl2JSON($item));
311 return $editor->event unless $editor->delete_serial_item($item);
316 my ($editor, $item) = @_;
318 $item->creator($editor->requestor->id);
319 $item->create_date('now');
321 $logger->info("item-alter: new item ".OpenSRF::Utils::JSON->perl2JSON($item));
322 return $editor->event unless $editor->create_serial_item($item);
327 my ($editor, $override, $item) = @_;
329 $logger->info("item-alter: retrieving item ".$item->id);
330 my $orig_item = $editor->retrieve_serial_item($item->id);
332 $logger->info("item-alter: original item ".OpenSRF::Utils::JSON->perl2JSON($orig_item));
333 $logger->info("item-alter: updated item ".OpenSRF::Utils::JSON->perl2JSON($item));
334 return $editor->event unless $editor->update_serial_item($item);
338 __PACKAGE__->register_method(
339 method => "fleshed_serial_item_retrieve_batch",
341 api_name => "open-ils.serial.item.fleshed.batch.retrieve"
344 sub fleshed_serial_item_retrieve_batch {
345 my( $self, $client, $ids ) = @_;
346 # FIXME: permissions?
347 $logger->info("Fetching fleshed serial items @$ids");
348 return $U->cstorereq(
349 "open-ils.cstore.direct.serial.item.search.atomic",
352 flesh_fields => {sitem => [ qw/issuance creator editor stream unit notes/ ], sunit => ["call_number"], siss => [qw/creator editor subscription/]}
357 ##########################################################################
360 __PACKAGE__->register_method(
361 method => 'fleshed_issuance_alter',
362 api_name => 'open-ils.serial.issuance.fleshed.batch.update',
366 desc => 'Receives an array of one or more issuances and updates the database as needed',
369 desc => 'Authtoken for current user session',
374 desc => 'Array of fleshed issuances',
380 desc => 'Returns 1 if successful, event if failed',
386 sub fleshed_issuance_alter {
387 my( $self, $conn, $auth, $issuances ) = @_;
388 return 1 unless ref $issuances;
389 my( $reqr, $evt ) = $U->checkses($auth);
391 my $editor = new_editor(requestor => $reqr, xact => 1);
392 my $override = $self->api_name =~ /override/;
395 for my $issuance (@$issuances) {
396 my $ssub_id = ref $issuance->subscription ? $issuance->subscription->id : $issuance->subscription;
397 if (!exists($found_ssub_ids{$ssub_id})) {
399 if (ref $issuance->subscription) {
400 $owning_lib_id = $issuance->subscription->owning_lib;
402 my $ssub = $editor->retrieve_serial_subscription($issuance->subscription) or return $editor->die_event;
403 $owning_lib_id = $ssub->owning_lib;
405 return $editor->die_event unless
406 $editor->allowed("ADMIN_SERIAL_SUBSCRIPTION", $owning_lib_id);
407 $found_ssub_ids{$ssub_id} = 1;
410 my $issuanceid = $issuance->id;
411 $issuance->editor($editor->requestor->id);
412 $issuance->edit_date('now');
414 if( $issuance->isdeleted ) {
415 $evt = _delete_siss( $editor, $override, $issuance);
416 } elsif( $issuance->isnew ) {
417 _cleanse_dates($issuance, ['date_published']);
418 $evt = _create_siss( $editor, $issuance );
420 _cleanse_dates($issuance, ['date_published']);
421 $evt = _update_siss( $editor, $override, $issuance );
426 $logger->info("fleshed issuance-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
430 $logger->debug("issuance-alter: done updating issuance batch");
432 $logger->info("fleshed issuance-alter successfully updated ".scalar(@$issuances)." issuances");
437 my ($editor, $override, $issuance) = @_;
438 $logger->info("issuance-alter: delete issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
439 return $editor->event unless $editor->delete_serial_issuance($issuance);
444 my ($editor, $issuance) = @_;
446 $issuance->creator($editor->requestor->id);
447 $issuance->create_date('now');
449 $logger->info("issuance-alter: new issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
450 return $editor->event unless $editor->create_serial_issuance($issuance);
455 my ($editor, $override, $issuance) = @_;
457 $logger->info("issuance-alter: retrieving issuance ".$issuance->id);
458 my $orig_issuance = $editor->retrieve_serial_issuance($issuance->id);
460 $logger->info("issuance-alter: original issuance ".OpenSRF::Utils::JSON->perl2JSON($orig_issuance));
461 $logger->info("issuance-alter: updated issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
462 return $editor->event unless $editor->update_serial_issuance($issuance);
466 __PACKAGE__->register_method(
467 method => "fleshed_serial_issuance_retrieve_batch",
469 api_name => "open-ils.serial.issuance.fleshed.batch.retrieve"
472 sub fleshed_serial_issuance_retrieve_batch {
473 my( $self, $client, $ids ) = @_;
474 # FIXME: permissions?
475 $logger->info("Fetching fleshed serial issuances @$ids");
476 return $U->cstorereq(
477 "open-ils.cstore.direct.serial.issuance.search.atomic",
480 flesh_fields => {siss => [ qw/creator editor subscription/ ]}
484 __PACKAGE__->register_method(
485 method => "pub_fleshed_serial_issuance_retrieve_batch",
486 api_name => "open-ils.serial.issuance.pub_fleshed.batch.retrieve",
489 Public (i.e. OPAC) call for getting at the sub and
490 ultimately the record entry from an issuance
492 params => [{name => 'ids', desc => 'Array of IDs', type => 'array'}],
495 issuance objects, fleshed with subscriptions
501 sub pub_fleshed_serial_issuance_retrieve_batch {
502 my( $self, $client, $ids ) = @_;
503 return [] unless $ids and @$ids;
504 return new_editor()->search_serial_issuance([
508 flesh_fields => {siss => [ qw/subscription/ ]}
513 sub received_siss_by_bib {
514 # XXX this is somewhat wrong in implementation and should not be used in
515 # new places - senator
520 my $args = shift || {};
521 $$args{order} ||= 'asc';
523 my $global = $$args{global} == 0 ? 0 : 1;
525 my $e = new_editor();
526 my $issuances = $e->json_query({
529 $global ? { transform => "min", column => "id", aggregate => 1 } : "id",
534 # We're not really interested in the minimum here. This is
535 # just a way to distinguish issuances whose items have units
536 # from issuances whose items have no units, without altogether
537 # excluding the latter type of issuances.
538 {"transform" => "min", "alias" => "has_units",
539 "column" => "unit", "aggregate" => 1}
545 field => 'subscription',
551 $$args{ou} ? ( join => {
558 fkey => 'distribution'
569 '+ssub' => { record_entry => $bib },
570 $$args{type} ? ( '+siss' => { 'holding_type' => $$args{type} } ) : (),
572 # XXX should we also take specific item statuses into account?
573 date_received => { '!=' => undef },
574 $$args{status} ? ( 'status' => $$args{status} ) : ()
576 $$args{ou} ? ( '+sdist' => {
578 'in' => $U->get_org_descendants($$args{ou}, $$args{depth})
582 $$args{limit} ? ( limit => $$args{limit} ) : (),
583 $$args{offset} ? ( offset => $$args{offset} ) : (),
584 order_by => [{ class => 'siss', field => 'date_published', direction => $$args{order} }],
589 "issuance" => $e->retrieve_serial_issuance($_->{"id"}),
590 "has_units" => $_->{"has_units"} ? 1 : 0
595 __PACKAGE__->register_method(
596 method => 'received_siss_by_bib',
597 api_name => 'open-ils.serial.received_siss.retrieve.by_bib',
602 desc => 'Receives a Bib ID and other optional params and returns "siss" (issuance) objects',
605 desc => 'id of the bre to which the issuances belong',
610 q/A hash of optional arguments. Valid keys and their meanings:
611 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).
612 order := date_published sort direction, either "asc" (chronological, default) or "desc" (reverse chronological)
613 limit := Number of issuances to return. Useful for paging results, or finding the oldest or newest
614 offset := Number of issuance to skip before returning results. Useful for paging.
615 orgid := OU id used to scope retrieval, based on distribution.holding_lib
616 depth := OU depth used to range the scope of orgid
617 type := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
618 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).
626 sub scoped_bib_holdings_summary {
627 # XXX this is somewhat wrong in implementation and should not be used in
628 # new places - senator
632 my $args = shift || {};
634 $args->{order} = 'asc';
636 my ($issuances) = $self->method_lookup('open-ils.serial.received_siss.retrieve.by_bib.atomic')->run( $bibid => $args );
638 # split into issuance type sets
639 my %type_blob = (basic => [], supplement => [], index => []);
640 push @{ $type_blob{ $_->{"issuance"}->holding_type } }, $_->{"issuance"}
643 # generate a statement list for each type
645 for my $type ( keys %type_blob ) {
646 my ($mfhd,$list) = _summarize_contents(new_editor(), $type_blob{$type});
648 return {} if $U->event_code($mfhd); # _summarize_contents() failed, bad data?
650 $statement_blob{$type} = $list;
653 return \%statement_blob;
655 __PACKAGE__->register_method(
656 method => 'scoped_bib_holdings_summary',
657 api_name => 'open-ils.serial.bib.summary_statements',
661 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',
664 desc => 'id of the bre to which the issuances belong',
669 q/A hash of optional arguments. Valid keys and their meanings:
670 orgid := OU id used to scope retrieval, based on distribution.holding_lib
671 depth := OU depth used to range the scope of orgid
672 type := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
673 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).
681 ##########################################################################
684 __PACKAGE__->register_method(
685 method => 'fleshed_sunit_alter',
686 api_name => 'open-ils.serial.sunit.fleshed.batch.update',
690 desc => 'Receives an array of one or more Units and updates the database as needed',
693 desc => 'Authtoken for current user session',
698 desc => 'Array of fleshed Units',
704 desc => 'Returns 1 if successful, event if failed',
710 sub fleshed_sunit_alter {
711 my( $self, $conn, $auth, $sunits ) = @_;
712 return 1 unless ref $sunits;
713 my( $reqr, $evt ) = $U->checkses($auth);
715 my $editor = new_editor(requestor => $reqr, xact => 1);
716 my $override = $self->api_name =~ /override/;
719 for my $sunit (@$sunits) {
720 my $cn_id = ref $sunit->call_number ? $sunit->call_number->id : $sunit->call_number;
721 if (!exists($found_cn_ids{$cn_id})) {
723 if (ref $sunit->call_number) {
724 $owning_lib_id = $sunit->call_number->owning_lib;
726 my $cn = $editor->retrieve_asset_call_number($sunit->call_number) or return $editor->die_event;
727 $owning_lib_id = $cn->owning_lib;
729 return $editor->die_event unless
730 $editor->allowed("UPDATE_COPY", $owning_lib_id);
731 $found_cn_ids{$cn_id} = 1;
734 if( $sunit->isdeleted ) {
735 $evt = _delete_sunit( $editor, $override, $sunit );
737 $sunit->default_location( $sunit->default_location->id ) if ref $sunit->default_location;
739 if( $sunit->isnew ) {
740 $evt = _create_sunit( $editor, $sunit );
742 $evt = _update_sunit( $editor, $override, $sunit );
748 $logger->info("fleshed sunit-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
752 $logger->debug("sunit-alter: done updating sunit batch");
754 $logger->info("fleshed sunit-alter successfully updated ".scalar(@$sunits)." Units");
759 my ($editor, $override, $sunit) = @_;
760 $logger->info("sunit-alter: delete sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
761 return $editor->event unless $editor->delete_serial_unit($sunit);
766 my ($editor, $sunit) = @_;
768 # The unique barcode constraint does not span asset.copy and serial.unit.
769 # ensure the barcode on the new unit does not collide with an existing
770 # asset.copy barcode.
771 my $existing = $editor->search_asset_copy(
772 {deleted => 'f', barcode => $sunit->barcode})->[0];
775 # The DB will prevent duplicate serial.unit barcodes, but for
776 # consistency (and a more specific error message for the
777 # user), prevent creation attempts on serial unit barcode
778 # collisions as well.
779 $existing = $editor->search_serial_unit(
780 {deleted => 'f', barcode => $sunit->barcode})->[0];
785 return new OpenILS::Event(
786 'SERIAL_UNIT_BARCODE_COLLISION', note =>
787 'Serial unit barcode collides with existing unit/copy barcode',
788 payload => {barcode => $sunit->barcode}
792 $logger->info("sunit-alter: new Unit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
793 return $editor->die_event unless $editor->create_serial_unit($sunit);
798 my ($editor, $override, $sunit) = @_;
800 $logger->info("sunit-alter: retrieving sunit ".$sunit->id);
801 my $orig_sunit = $editor->retrieve_serial_unit($sunit->id);
803 $logger->info("sunit-alter: original sunit ".OpenSRF::Utils::JSON->perl2JSON($orig_sunit));
804 $logger->info("sunit-alter: updated sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
805 return $editor->event unless $editor->update_serial_unit($sunit);
809 __PACKAGE__->register_method(
810 method => "retrieve_unit_list",
812 api_name => "open-ils.serial.unit_list.retrieve"
815 sub retrieve_unit_list {
817 my( $self, $client, @sdist_ids ) = @_;
819 if(ref($sdist_ids[0])) { @sdist_ids = @{$sdist_ids[0]}; }
821 my $e = new_editor();
825 { 'sunit' => [ 'id', 'summary_contents', 'sort_key' ],
826 'sitem' => ['stream'],
827 'sstr' => ['distribution'],
828 'sdist' => [{'column' => 'label', 'alias' => 'sdist_label'}]
835 { 'join' => { 'sunit' => {} } }
840 'distinct' => 'true',
841 'where' => { '+sdist' => {'id' => \@sdist_ids} },
842 'order_by' => [{'class' => 'sunit', 'field' => 'sort_key'}]
845 my $unit_list_entries = $e->json_query($query);
848 foreach my $entry (@$unit_list_entries) {
849 my $value = {'sunit' => $entry->{id}, 'sstr' => $entry->{stream}, 'sdist' => $entry->{distribution}};
850 my $label = $entry->{summary_contents};
851 if (length($label) > 100) {
852 $label = substr($label, 0, 100) . '...'; # limited space in dropdown / menu
854 $label = "[$entry->{sdist_label}/$entry->{stream} #$entry->{id}] " . $label;
855 push (@entries, [$label, OpenSRF::Utils::JSON->perl2JSON($value)]);
863 ##########################################################################
864 # predict and receive methods
866 __PACKAGE__->register_method(
867 method => 'make_predictions',
868 api_name => 'open-ils.serial.make_predictions',
872 desc => 'Receives an ssub id and populates the issuance and item tables',
875 desc => 'Serial Subscription ID',
882 sub make_predictions {
883 my ($self, $conn, $authtoken, $args) = @_;
885 my $editor = OpenILS::Utils::CStoreEditor->new();
886 my $ssub_id = $args->{ssub_id};
887 my $mfhd = MFHD->new(MARC::Record->new());
889 my $ssub = $editor->retrieve_serial_subscription([$ssub_id]);
890 my $scaps = $editor->search_serial_caption_and_pattern({ subscription => $ssub_id, active => 't'});
891 my $sdists = $editor->search_serial_distribution( [{ subscription => $ssub->id }, { flesh => 1, flesh_fields => {sdist => [ qw/ streams / ]} }] ); #TODO: 'deleted' support?
893 my $total_streams = 0;
895 $total_streams += scalar(@{$_->streams});
897 if ($total_streams < 1) {
899 # XXX TODO new event type
900 return new OpenILS::Event(
901 "BAD_PARAMS", note =>
902 "There are no streams to direct items. Can't predict."
908 # XXX TODO new event type
909 return new OpenILS::Event(
910 "BAD_PARAMS", note =>
911 "There are no active caption-and-pattern objects associated " .
912 "with this subscription. Can't predict."
918 foreach my $scap (@$scaps) {
919 my $caption_field = _revive_caption($scap);
920 $caption_field->update('8' => $link_id);
921 my $fake_chron_needed = 0;
922 # if we have missing chron pieces, we will add them later for prediction purposes
923 if (!$caption_field->enumeration_is_chronology) {
924 if (!$caption_field->subfield('i') # no year
925 or !$caption_field->subfield('j')) { # we had a year, but no month or season
926 $fake_chron_needed = '1';
929 $mfhd->append_fields($caption_field);
931 'caption' => $caption_field,
932 'scap_id' => $scap->id,
933 'num_to_predict' => $args->{num_to_predict},
934 'end_date' => defined $args->{end_date} ?
935 $_strp_date->parse_datetime($args->{end_date}) : undef
937 my $predict_from_siss;
938 if ($args->{base_issuance}) { # predict from a given issuance
939 $predict_from_siss = $args->{base_issuance}->holding_code;
940 } else { # default to predicting from last published
941 my $last_published = $editor->search_serial_issuance([
942 {'caption_and_pattern' => $scap->id,
943 'subscription' => $ssub_id},
944 {limit => 1, order_by => { siss => "date_published DESC" }}]
946 if ($last_published->[0]) {
947 $predict_from_siss = $last_published->[0];
948 unless ($predict_from_siss->holding_code) {
950 # XXX TODO new event type
951 return new OpenILS::Event(
952 "BAD_PARAMS", note =>
953 "Last issuance has no holding code. Can't predict."
958 # XXX TODO make a new event type instead of hijacking this one
959 return new OpenILS::Event(
960 "BAD_PARAMS", note => "No issuance from which to predict!"
964 $options->{predict_from} = _revive_holding($predict_from_siss->holding_code, $caption_field, 1); # fresh MFHD Record, so we simply default to 1 for seqno
965 if ($fake_chron_needed) {
966 $options->{faked_chron_date} = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($predict_from_siss->date_published));
968 push( @predictions, _generate_issuance_values($mfhd, $options) );
973 foreach my $prediction (@predictions) {
974 my $issuance = new Fieldmapper::serial::issuance;
976 $issuance->label($prediction->{label});
977 $issuance->date_published($prediction->{date_published}->strftime('%F'));
978 $issuance->holding_code(OpenSRF::Utils::JSON->perl2JSON($prediction->{holding_code}));
979 $issuance->holding_type($prediction->{holding_type});
980 $issuance->caption_and_pattern($prediction->{caption_and_pattern});
981 $issuance->subscription($ssub->id);
982 push (@issuances, $issuance);
985 my $evt = fleshed_issuance_alter($self, $conn, $authtoken, \@issuances);
986 return $evt if ref $evt;
989 for (my $i = 0; $i < @issuances; $i++) {
990 my $date_expected = $predictions[$i]->{date_published}->add(seconds => interval_to_seconds($ssub->expected_date_offset))->strftime('%F');
991 my $issuance = $issuances[$i];
992 #$issuance->label(interval_to_seconds($ssub->expected_date_offset));
993 foreach my $sdist (@$sdists) {
994 my $streams = $sdist->streams;
995 foreach my $stream (@$streams) {
996 my $item = new Fieldmapper::serial::item;
998 $item->stream($stream->id);
999 $item->date_expected($date_expected);
1000 $item->issuance($issuance->id);
1001 push (@items, $item);
1005 fleshed_item_alter($self, $conn, $authtoken, \@items); # FIXME: catch events
1010 # _generate_issuance_values() is an initial attempt at a function which can be used
1011 # to populate an issuance table with a list of predicted issues. It accepts
1012 # a hash ref of options initially defined as:
1013 # caption : the caption field to predict on
1014 # num_to_predict : the number of issues you wish to predict
1015 # 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
1017 # The basic method is to first convert to a single holding if compressed, then
1018 # increment the holding and save the resulting values to @issuances.
1020 # returns @issuance_values, an array of hashrefs containing (formatted
1021 # label, formatted chronology date, formatted estimated arrival date, and an
1022 # array ref of holding subfields as (key, value, key, value ...)) (not a hash
1023 # to protect order and possible duplicate keys), and a holding type.
1025 sub _generate_issuance_values {
1026 my ($mfhd, $options) = @_;
1027 my $caption = $options->{caption};
1028 my $scap_id = $options->{scap_id};
1029 my $num_to_predict = $options->{num_to_predict};
1030 my $end_date = $options->{end_date};
1031 my $predict_from = $options->{predict_from}; # MFHD::Holding to predict from
1032 my $faked_chron_date = $options->{faked_chron_date}; # serial does not have a (complete) chronology caption, so add one (temporarily) based on this date
1035 # Only needed for 'real' MFHD records, not our temp records
1036 # my $link_id = $caption->link_id;
1037 # if(!$predict_from) {
1038 # my $htag = $caption->tag;
1039 # $htag =~ s/^85/86/;
1040 # my @holdings = $mfhd->holdings($htag, $link_id);
1041 # my $last_holding = $holdings[-1];
1043 # #if ($last_holding->is_compressed) {
1044 # # $last_holding->compressed_to_last; # convert to last in range
1046 # $predict_from = $last_holding;
1050 $predict_from->notes('public', []);
1051 # add a note marker for system use (?)
1052 $predict_from->notes('private', ['AUTOGEN']);
1054 # our basic method for dealing with 'faked' chronologies will be to add it in, do the predicting, then take it back out
1055 my @faked_subfield_chars;
1056 if ($faked_chron_date) {
1057 my $faked_caption = new MARC::Field($caption->tag, $caption->indicator(1), $caption->indicator(2), $caption->subfields_list);
1059 my %mfhd_chron_labels = ('i' => 'year', 'j' => 'month', 'k' => 'day');
1060 foreach my $subfield_char ('i', 'j', 'k') {
1061 if (!$caption->subfield($subfield_char)) { # if we are missing a piece, add it
1062 push(@faked_subfield_chars, $subfield_char);
1063 my $chron_name = $mfhd_chron_labels{$subfield_char};
1064 $faked_caption->add_subfields($subfield_char => "($chron_name)");
1065 my $method = $mfhd_chron_labels{$subfield_char};
1066 $predict_from->add_subfields($subfield_char => $faked_chron_date->$chron_name);
1069 # because of the way MFHD::Caption and Holding work, it is simplest
1070 # to recreate rather than try to update
1071 $faked_caption = new MFHD::Caption($faked_caption);
1072 $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);
1075 my @predictions = $mfhd->generate_predictions({'base_holding' => $predict_from, 'num_to_predict' => $num_to_predict, 'end_date' => $end_date});
1078 my @issuance_values;
1079 foreach my $prediction (@predictions) {
1080 $pub_date = $_strp_date->parse_datetime($prediction->chron_to_date);
1081 if ($faked_chron_date) { # get rid of the chronology portions and restore original caption
1082 $prediction->delete_subfield(code => \@faked_subfield_chars);
1083 $prediction = new MFHD::Holding($prediction->seqno, new MARC::Field($prediction->tag, $prediction->indicator(1), $prediction->indicator(2), $prediction->subfields_list), $caption);
1089 label => $prediction->format,
1090 date_published => $pub_date,
1091 #date_expected => $date_expected->strftime('%F'),
1092 holding_code => [$prediction->indicator(1),$prediction->indicator(2),$prediction->subfields_list],
1093 holding_type => $MFHD_NAMES_BY_TAG{$caption->tag},
1094 caption_and_pattern => $scap_id
1099 return @issuance_values;
1102 sub _revive_caption {
1105 my $pattern_code = $scap->pattern_code;
1108 my $pattern_parts = OpenSRF::Utils::JSON->JSON2perl($pattern_code);
1109 unshift(@$pattern_parts, $MFHD_TAGS_BY_NAME{$scap->type});
1110 my $pattern_field = new MARC::Field(@$pattern_parts);
1112 # build MFHD::Caption
1113 return new MFHD::Caption($pattern_field);
1116 sub _revive_holding {
1117 my $holding_code = shift;
1118 my $caption_field = shift;
1122 my $holding_parts = OpenSRF::Utils::JSON->JSON2perl($holding_code);
1123 my $captag = $caption_field->tag;
1124 $captag =~ s/^85/86/;
1125 unshift(@$holding_parts, $captag);
1126 my $holding_field = new MARC::Field(@$holding_parts);
1128 # build MFHD::Holding
1129 return new MFHD::Holding($seqno, $holding_field, $caption_field);
1131 # TODO(?) the underlying MARC and the Holding object end up in conflict concerning subfield '8'
1134 __PACKAGE__->register_method(
1135 method => 'unitize_items',
1136 api_name => 'open-ils.serial.receive_items',
1140 desc => 'Marks an item as received, updates the shelving unit (creating a new shelving unit if needed), and updates the summaries',
1143 desc => 'array of serial items',
1148 desc => 'hash of item_ids => barcodes',
1152 name => 'call_numbers',
1153 desc => 'hash of item_ids => call_numbers',
1157 name => 'donor_unit_ids',
1158 desc => 'hash of unit_ids => 1, keyed with ids of any units giving up items',
1163 desc => 'Returns number of received items (num_items) and new unit ID, if applicable (new_unit_id)',
1169 __PACKAGE__->register_method(
1170 method => 'unitize_items',
1171 api_name => 'open-ils.serial.bind_items',
1175 desc => 'Marks an item as bound, updates the shelving unit (creating a new shelving unit if needed)',
1178 desc => 'array of serial items',
1183 desc => 'hash of item_ids => barcodes',
1187 name => 'call_numbers',
1188 desc => 'hash of item_ids => call_numbers',
1192 name => 'donor_unit_ids',
1193 desc => 'hash of unit_ids => 1, keyed with ids of any units giving up items',
1198 desc => 'Returns number of bound items (num_items) and new unit ID, if applicable (new_unit_id)',
1204 # TODO: reset/delete claims information once implemented
1205 # XXX: deal with emptied call numbers here?
1206 __PACKAGE__->register_method(
1207 method => 'unitize_items',
1208 api_name => 'open-ils.serial.reset_items',
1212 desc => 'Resets the items to Expected, updates the shelving unit (deleting the shelving unit if empty), and updates the summaries',
1215 desc => 'array of serial items',
1220 desc => 'Returns number of reset items (num_items)',
1227 my ($self, $conn, $auth, $items, $barcodes, $call_numbers, $donor_unit_ids) = @_;
1229 my $editor = new_editor("authtoken" => $auth, "xact" => 1);
1230 return $editor->die_event unless $editor->checkauth;
1231 return $editor->die_event unless $editor->allowed("RECEIVE_SERIAL");
1232 $self->api_name =~ /serial\.(\w*)_items/;
1236 if ($donor_unit_ids) { # units giving up items need updating as well
1237 %found_unit_ids = %$donor_unit_ids;
1239 my %found_stream_ids;
1242 my %stream_ids_by_unit_id;
1245 my %sdist_by_unit_id;
1246 my %call_number_by_unit_id;
1247 my %sdist_by_stream_id;
1249 my $new_unit_id; # id for '-2' units to share
1250 foreach my $item (@$items) {
1251 # for debugging only, TODO: delete
1252 if (!ref $item) { # hopefully we got an id instead
1253 $item = $editor->retrieve_serial_item($item);
1256 my $unit_id = ref($item->unit) ? $item->unit->id : $item->unit;
1257 my $stream_id = ref($item->stream) ? $item->stream->id : $item->stream;
1258 my $issuance_id = ref($item->issuance) ? $item->issuance->id : $item->issuance;
1259 #TODO: evt on any missing ids
1261 if ($mode eq 'receive') {
1262 $item->date_received('now');
1263 $item->status('Received');
1264 } elsif ($mode eq 'reset') {
1265 # clear date_received
1266 $item->clear_date_received;
1267 # Set status to 'Expected'
1268 $item->status('Expected');
1273 # check for types to trigger summary updates
1275 if (!ref $item->issuance) {
1276 my $scaps = $editor->search_serial_caption_and_pattern([{"+siss" => {"id" => $issuance_id}}, { "join" => {"siss" => {}} }]);
1277 $scap = $scaps->[0];
1278 } elsif (!ref $item->issuance->caption_and_pattern) {
1279 $scap = $editor->retrieve_serial_caption_and_pattern($item->issuance->caption_and_pattern);
1281 $scap = $editor->issuance->caption_and_pattern;
1283 if (!exists($found_types{$stream_id})) {
1284 $found_types{$stream_id} = {};
1286 $found_types{$stream_id}->{$scap->type} = 1;
1288 # create unit if needed
1289 if ($unit_id == -1 or (!$new_unit_id and $unit_id == -2)) { # create unit per item
1291 my $sdists = $editor->search_serial_distribution([
1292 {"+sstr" => {"id" => $stream_id}},
1294 "join" => {"sstr" => {}},
1296 "flesh_fields" => {"sdist" => ["subscription"]}
1298 $unit = _build_unit($editor, $sdists->[0], $mode);
1299 # if _build_unit fails, $unit is an event, so return it
1300 if ($U->event_code($unit)) {
1302 $unit->{"note"} = "Item ID: " . $item->id;
1305 $unit->barcode($barcodes->{$item->id}) if exists($barcodes->{$item->id});
1306 my $evt = _create_sunit($editor, $unit);
1307 return $evt if $evt;
1308 if ($unit_id == -2) {
1309 $new_unit_id = $unit->id;
1310 $unit_id = $new_unit_id;
1312 $unit_id = $unit->id;
1314 $item->unit($unit_id);
1316 # get unit with 'DEFAULT's and save unit, sdist, and call number for later use
1317 $unit = $editor->retrieve_serial_unit($unit->id);
1318 $unit_map{$unit_id} = $unit;
1319 $sdist_by_unit_id{$unit_id} = $sdists->[0];
1320 $call_number_by_unit_id{$unit_id} = $call_numbers->{$item->id};
1321 $sdist_by_stream_id{$stream_id} = $sdists->[0];
1322 } elsif ($unit_id == -2) { # create one unit for all '-2' items
1323 $unit_id = $new_unit_id;
1324 $item->unit($unit_id);
1327 $found_stream_ids{$stream_id} = 1;
1329 if (defined($unit_id) and $unit_id ne '') {
1330 $found_unit_ids{$unit_id} = 1;
1331 # save the stream_id for this unit_id
1332 # TODO: prevent items from different streams in same unit? (perhaps in interface)
1333 $stream_ids_by_unit_id{$unit_id} = $stream_id;
1338 my $evt = _update_sitem($editor, undef, $item);
1339 return $evt if $evt;
1342 # cleanup 'dead' units (units which are now emptied of their items)
1343 my $dead_units = $editor->search_serial_unit([{'+sitem' => {'id' => undef}, 'deleted' => 'f'}, {'join' => {'sitem' => {'type' => 'left'}}}]);
1344 foreach my $unit (@$dead_units) {
1345 _delete_sunit($editor, undef, $unit);
1346 delete $found_unit_ids{$unit->id};
1349 # deal with unit level contents
1350 foreach my $unit_id (keys %found_unit_ids) {
1352 # get all the needed issuances for unit
1353 # TODO remove 'Bindery' from this search (leaving it in for now for backwards compatibility with any current test environment data)
1354 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"unit" => $unit_id, "status" => ["Received", "Bindery"]}}, {"join" => {"sitem" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1355 #TODO: evt on search failure
1357 # retrieve and update unit contents
1360 my $call_number_string;
1362 # if we just created the unit, we will already have it and the distribution stored, and we will need to assign the call number
1363 if (exists $unit_map{$unit_id}) {
1364 $sunit = $unit_map{$unit_id};
1365 $sdist = $sdist_by_unit_id{$unit_id};
1366 $call_number_string = $call_number_by_unit_id{$unit_id};
1367 $record_id = $sdist->subscription->record_entry;
1369 # XXX: this code assumes you will not have units which mix streams/distributions, but current code does not enforce this
1370 $sunit = $editor->retrieve_serial_unit($unit_id);
1371 if ($stream_ids_by_unit_id{$unit_id}) {
1372 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_ids_by_unit_id{$unit_id}}}, { "join" => {"sstr" => {}}, 'limit' => 1 }]);
1374 $sdist = $editor->search_serial_distribution([
1375 {'+sunit' => {'id' => $unit_id}},
1380 { 'join' => 'sunit' }
1387 $sdist = $sdist->[0];
1390 my $evt = _prepare_unit($editor, $sunit, $sdist, $issuances, $call_number_string, $record_id);
1391 if ($U->event_code($evt)) {
1396 $evt = _update_sunit($editor, undef, $sunit);
1397 if ($U->event_code($evt)) {
1403 if ($mode ne 'bind') { # the summary holdings do not change when binding
1404 # deal with stream level summaries
1405 # summaries will be built from the "primary" stream only, that is, the stream with the lowest ID per distribution
1406 # (TODO: consider direct designation)
1407 my %primary_streams_by_sdist;
1408 my %streams_by_sdist;
1410 # see if we have primary streams, and if so, associate them with their distributions
1411 foreach my $stream_id (keys %found_stream_ids) {
1413 if (exists $sdist_by_stream_id{$stream_id}) {
1414 $sdist = $sdist_by_stream_id{$stream_id};
1416 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
1417 $sdist = $sdist->[0];
1418 $sdist_by_stream_id{$stream_id} = $sdist;
1421 if (!exists($streams_by_sdist{$sdist->id})) {
1422 $streams = $editor->search_serial_stream([{"distribution" => $sdist->id}, {"order_by" => {"sstr" => "id"}}]);
1423 $streams_by_sdist{$sdist->id} = $streams;
1425 $streams = $streams_by_sdist{$sdist->id};
1427 $primary_streams_by_sdist{$sdist->id} = $streams->[0] if ($stream_id == $streams->[0]->id);
1430 # retrieve and update summaries for each affected primary stream's distribution
1431 foreach my $sdist_id (keys %primary_streams_by_sdist) {
1432 my $stream = $primary_streams_by_sdist{$sdist_id};
1433 my $stream_id = $stream->id;
1434 # get all the needed issuances for stream
1435 # FIXME: search in Bindery/Bound/Not Published? as well as Received
1436 foreach my $type (keys %{$found_types{$stream_id}}) {
1437 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"stream" => $stream_id, "status" => "Received"}, "+scap" => {"type" => $type}}, {"join" => {"sitem" => {}, "scap" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1438 #TODO: evt on search failure
1439 my $evt = _prepare_summaries($editor, $issuances, $sdist_by_stream_id{$stream_id}, $type);
1440 if ($U->event_code($evt)) {
1449 return {'num_items' => scalar @$items, 'new_unit_id' => $new_unit_id};
1452 sub _find_or_create_call_number {
1453 my ($e, $lib, $cn_string, $record) = @_;
1455 # FIXME: should suffix and prefix come into play here?
1456 my $existing = $e->search_asset_call_number({
1457 "owning_lib" => $lib,
1458 "label" => $cn_string,
1459 "record" => $record,
1461 }) or return $e->die_event;
1464 return $existing->[0]->id;
1466 return $e->die_event unless
1467 $e->allowed("CREATE_VOLUME", $lib);
1469 my $acn = new Fieldmapper::asset::call_number;
1471 $acn->creator($e->requestor->id);
1472 $acn->editor($e->requestor->id);
1473 $acn->record($record);
1474 $acn->label($cn_string);
1475 $acn->owning_lib($lib);
1477 $e->create_asset_call_number($acn) or return $e->die_event;
1478 return $e->data->id;
1482 sub _issuances_received {
1483 # XXX TODO: Add some caching or something. This is getting called
1484 # more often than it has to be.
1485 my ($e, $sitem) = @_;
1487 my $results = $e->json_query({
1488 "select" => {"sitem" => ["issuance"]},
1489 "from" => {"sitem" => {"sstr" => {}, "siss" => {}}},
1491 "+sstr" => {"distribution" => $sitem->stream->distribution->id},
1492 "+siss" => {"holding_type" => $sitem->issuance->holding_type},
1493 "+sitem" => {"date_received" => {"!=" => undef}}
1496 "siss" => {"date_published" => {"direction" => "asc"}}
1498 }) or return $e->die_event;
1500 my $uniq = +{map { $_->{"issuance"} => 1 } @$results};
1501 return [ map { $e->retrieve_serial_issuance($_) } keys %$uniq ];
1504 # _prepare_unit populates the detailed_contents, summary_contents, and
1505 # sort_key fields for a given unit based on a given set of issuances
1506 # Also finds/creates call number as needed
1508 my ($e, $sunit, $sdist, $issuances, $call_number_string, $record_id) = @_;
1510 # Handle call number first if we have one
1511 if ($call_number_string) {
1512 my $org_unit_id = ref $sdist->holding_lib ? $sdist->holding_lib->id : $sdist->holding_lib;
1513 my $real_cn = _find_or_create_call_number(
1515 $call_number_string, $record_id
1518 if ($U->event_code($real_cn)) {
1521 $sunit->call_number($real_cn);
1525 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances);
1526 return $mfhd if $U->event_code($mfhd);
1528 # special case for single formatted_part (may have summarized version)
1529 if (@$formatted_parts == 1) {
1530 #TODO: MFHD.pm should have a 'format_summary' method for this
1533 $sunit->detailed_contents(
1536 $sdist->unit_label_prefix,
1537 join(", ", @$formatted_parts),
1538 $sdist->unit_label_suffix
1542 # TODO: change this when real summary contents are available
1543 $sunit->summary_contents($sunit->detailed_contents);
1545 # Create sort_key by left padding numbers to 6 digits.
1546 (my $sort_key = $sunit->detailed_contents) =~
1547 s/(\d+)/sprintf '%06d', $1/eg;
1548 $sunit->sort_key($sort_key);
1551 # _prepare_summaries populates the generated_coverage field for a given summary
1552 # type ('basic', 'index', 'supplement') for a given distribution.
1553 # It also creates the summary if it doesn't yet exist.
1554 sub _prepare_summaries {
1555 my ($e, $issuances, $sdist, $type) = @_;
1557 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances, $sdist);
1558 return $mfhd if $U->event_code($mfhd);
1560 my $search_method = "search_serial_${type}_summary";
1561 my $summary = $e->$search_method([{"distribution" => $sdist->id}]);
1563 my $cu_method = "update";
1566 $summary = $summary->[0];
1568 my $class = "Fieldmapper::serial::${type}_summary";
1569 $summary = $class->new;
1570 $summary->distribution($sdist->id);
1571 $cu_method = "create";
1574 $summary->generated_coverage(OpenSRF::Utils::JSON->perl2JSON($formatted_parts));
1575 my $method = "${cu_method}_serial_${type}_summary";
1576 return $e->die_event unless $e->$method($summary);
1579 sub _unit_by_iss_and_str {
1580 my ($e, $issuance, $stream) = @_;
1582 my $unit = $e->json_query({
1583 "select" => {"sunit" => ["id"]},
1584 "from" => {"sitem" => {"sunit" => {}}},
1587 "issuance" => $issuance->id,
1588 "stream" => $stream->id
1591 }) or return $e->die_event;
1592 return 0 if not @$unit;
1594 $e->retrieve_serial_unit($unit->[0]->{"id"}) or $e->die_event;
1597 sub move_previous_unit {
1598 my ($e, $prev_iss, $curr_item, $new_loc) = @_;
1600 my $prev_unit = _unit_by_iss_and_str($e,$prev_iss,$curr_item->stream);
1601 return $prev_unit if defined $U->event_code($prev_unit);
1602 return 0 if not $prev_unit;
1604 if ($prev_unit->location != $new_loc) {
1605 $prev_unit->location($new_loc);
1606 $e->update_serial_unit($prev_unit) or return $e->die_event;
1611 # _previous_issuance() assumes $existing is an ordered array
1612 sub _previous_issuance {
1613 my ($existing, $issuance) = @_;
1615 my $last = $existing->[-1];
1616 return undef unless $last;
1617 return ($last->id == $issuance->id ? $existing->[-2] : $last);
1620 __PACKAGE__->register_method(
1621 "method" => "receive_items_one_unit_per",
1622 "api_name" => "open-ils.serial.receive_items.one_unit_per",
1627 "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",
1631 "desc" => "authtoken",
1636 "desc" => "array of serial items, possibly fleshed with units and definitely fleshed with stream->distribution",
1641 "desc" => "id of bib record these items are associated with
1642 (XXX could/should be derived from items)",
1647 "desc" => "The item ID for each item successfully received",
1653 sub receive_items_one_unit_per {
1654 # XXX This function may be temporary, as it does some of what
1655 # unitize_items() does, just in a different way.
1656 my ($self, $client, $auth, $items, $record) = @_;
1658 my $e = new_editor("authtoken" => $auth, "xact" => 1);
1659 return $e->die_event unless $e->checkauth;
1660 return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
1662 my $prev_loc_setting_map = {};
1663 my $user_id = $e->requestor->id;
1665 # Get a list of all the non-virtual field names in a serial::unit for
1666 # merging given unit objects with template-built units later.
1667 # XXX move this somewhere global so it isn't re-run all the time
1668 my $all_unit_fields =
1669 $Fieldmapper::fieldmap->{"Fieldmapper::serial::unit"}->{"fields"};
1670 my @real_unit_fields = grep {
1671 not $all_unit_fields->{$_}->{"virtual"}
1672 } keys %$all_unit_fields;
1674 foreach my $item (@$items) {
1675 # Note that we expect a certain fleshing on the items we're getting.
1676 my $sdist = $item->stream->distribution;
1678 # Fetch a list of issuances with received copies already existing
1679 # on this distribution (and with the same holding type on the
1680 # issuance). This will be used in up to two places: once when building
1681 # a summary, once when changing the copy location of the previous
1683 my $issuances_received = _issuances_received($e, $item);
1684 if ($U->event_code($issuances_received)) {
1686 return $issuances_received;
1689 # Find out if we need to to deal with previous copy location changing.
1690 my $ou = $sdist->holding_lib->id;
1691 unless (exists $prev_loc_setting_map->{$ou}) {
1692 $prev_loc_setting_map->{$ou} = $U->ou_ancestor_setting_value(
1693 $ou, "serial.prev_issuance_copy_location", $e
1697 # If there is a previous copy location setting, we need the previous
1698 # issuance, from which we can in turn look up the item attached to the
1699 # same stream we're on now.
1700 if ($prev_loc_setting_map->{$ou}) {
1702 _previous_issuance($issuances_received, $item->issuance)) {
1704 # Now we can change the copy location of the previous unit,
1706 return $e->event if defined $U->event_code(
1708 $e, $prev_iss, $item, $prev_loc_setting_map->{$ou}
1714 # Create unit if given by user
1715 if (ref $item->unit) {
1716 # detach from the item, as we need to create separately
1717 my $user_unit = $item->unit;
1719 # get a unit based on associated template
1720 my $template_unit = _build_unit($e, $sdist, "receive");
1721 if ($U->event_code($template_unit)) {
1723 $template_unit->{"note"} = "Item ID: " . $item->id;
1724 return $template_unit;
1727 # merge built unit with provided unit from user
1728 foreach (@real_unit_fields) {
1729 unless ($user_unit->$_) {
1730 $user_unit->$_($template_unit->$_);
1734 # Treat call number specially: the provided value from the
1735 # user will really be a string.
1736 my $call_number_string;
1737 if ($user_unit->call_number) {
1738 $call_number_string = $user_unit->call_number;
1739 # clear call number for now (replaced in _prepare_unit)
1740 $user_unit->clear_call_number;
1743 my $evt = _prepare_unit(
1744 $e, $user_unit, $sdist, [$item->issuance],
1745 $call_number_string, $record
1747 if ($U->event_code($evt)) {
1752 # create/update summary objects related to this distribution
1753 # Make sure @$issuances_received contains current item's issuance
1754 unless (grep { $_->id == $item->issuance->id } @$issuances_received) {
1755 push @$issuances_received, $item->issuance;
1757 $evt = _prepare_summaries($e, $issuances_received, $item->stream->distribution, $item->issuance->holding_type);
1758 if ($U->event_code($evt)) {
1763 # set the incontrovertibles on the unit
1764 $user_unit->edit_date("now");
1765 $user_unit->create_date("now");
1766 $user_unit->editor($user_id);
1767 $user_unit->creator($user_id);
1769 $evt = _create_sunit($e, $user_unit);
1770 return $evt if $evt;
1772 # save reference to new unit
1773 $item->unit($e->data->id);
1776 # Create notes if given by user
1777 if (ref($item->notes) and @{$item->notes}) {
1778 foreach my $note (@{$item->notes}) {
1779 $note->creator($user_id);
1780 $note->create_date("now");
1782 return $e->die_event unless $e->create_serial_item_note($note);
1785 $item->clear_notes; # They're saved; we no longer want them here.
1788 # Set the incontrovertibles on the item
1789 $item->status("Received");
1790 $item->date_received("now");
1791 $item->edit_date("now");
1792 $item->editor($user_id);
1794 return $e->die_event unless $e->update_serial_item($item);
1796 # send client a response
1797 $client->respond($item->id);
1800 $e->commit or return $e->die_event;
1808 #my $skip_call_number = shift;
1810 my $attr = $mode . '_unit_template';
1811 my $template = $editor->retrieve_asset_copy_template($sdist->$attr) or
1812 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_COPY_TEMPLATE");
1814 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 );
1816 my $unit = new Fieldmapper::serial::unit;
1817 foreach my $part (@parts) {
1818 my $value = $template->$part;
1819 next if !defined($value);
1820 $unit->$part($value);
1823 # ignore circ_lib in template, set to distribution holding_lib
1824 $unit->circ_lib($sdist->holding_lib);
1825 $unit->creator($editor->requestor->id);
1826 $unit->editor($editor->requestor->id);
1828 # XXX: this feature has been pushed back until after 2.0 at least
1829 # unless ($skip_call_number) {
1830 # $attr = $mode . '_call_number';
1831 # my $cn = $sdist->$attr or
1832 # return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_CALL_NUMBER");
1834 # $unit->call_number($cn);
1836 $unit->call_number('-1'); # default to the dummy call number
1837 $unit->barcode('@@PLACEHOLDER'); # generic unit will start with a generated placeholder barcode
1838 $unit->sort_key('');
1839 $unit->summary_contents('');
1840 $unit->detailed_contents('');
1845 sub _summarize_contents {
1847 my $issuances = shift;
1850 # create or lookup MFHD record
1852 if ($sdist and defined($sdist->record_entry) and $sdist->summary_method eq 'merge_with_sre') {
1854 if (ref $sdist->record_entry) {
1855 $sre = $sdist->record_entry;
1857 $sre = $editor->retrieve_serial_record_entry($sdist->record_entry);
1859 $mfhd = MFHD->new(MARC::Record->new_from_xml($sre->marc));
1861 $logger->info($sdist);
1862 $mfhd = MFHD->new(MARC::Record->new());
1868 # We keep track of these separately to avoid link_id contamination,
1869 # e.g. a basic issuance, followed by a merging supplement, followed by
1870 # another basic. If we could be sure that they were not mixed, one
1871 # value could suffice.
1872 my %link_ids = ('basic' => 10000, 'index' => 10000, 'supplement' => 10000);
1873 my %first_scap = ('basic' => 1, 'index' => 1, 'supplement' => 1);
1874 foreach my $issuance (@$issuances) {
1875 my $scap_id = $issuance->caption_and_pattern;
1876 next if (!$scap_id); # skip issuances with no caption/pattern
1880 # if this is the first appearance of this scap, retrieve it and add it to the temporary record
1881 if (!exists $scaps{$issuance->caption_and_pattern}) {
1882 $scaps{$scap_id} = $editor->retrieve_serial_caption_and_pattern($scap_id);
1883 $scap = $scaps{$scap_id};
1884 $scap_field = _revive_caption($scap);
1886 if ($first_scap{$scap->type}) { # special merge processing
1887 $first_scap{$MFHD_TAGS_BY_NAME{$scap->type}} = 0;
1888 if ($sdist and $sdist->summary_method eq 'merge_with_sre') {
1889 # MFHD Caption objects do not yet have a built-in compare (TODO), so let's do a basic one
1890 my @field_85xs = $mfhd->field($MFHD_TAGS_BY_NAME{$scap->type});
1892 my $last_caption_field = $field_85xs[-1];
1893 my $last_link_id = $last_caption_field->subfield('8');
1894 # set the link id to match, temporarily, for comparison
1895 $last_caption_field->update('8' => $scap_field->subfield('8'));
1896 my $last_caption_json = OpenSRF::Utils::JSON->perl2JSON([$last_caption_field->indicator(1), $last_caption_field->indicator(2), $last_caption_field->subfields_list]);
1897 if ($last_caption_json eq $scap->pattern_code) { # merge is possible, they match
1899 $link_ids{$scap->type} = $last_link_id;
1900 # set scap_field to last field
1901 $scap_field = $last_caption_field;
1907 $scap_fields{$scap_id} = $scap_field;
1908 $scap_field->update('8' => $link_ids{$scap->type});
1909 # TODO: make MFHD/Caption smarter about this
1910 $scap_field->{_mfhdc_LINK_ID} = $link_ids{$scap->type};
1911 $mfhd->append_fields($scap_field) if !$did_merge;
1912 $link_ids{$scap->type}++;
1914 $scap_field = $scap_fields{$scap_id};
1917 $mfhd->append_fields(_revive_holding($issuance->holding_code, $scap_field, $seqno));
1921 my @formatted_parts;
1922 my @scap_fields_ordered = $mfhd->field('85[345]');
1924 foreach my $scap_field (@scap_fields_ordered) { #TODO: use generic MFHD "summarize" method, once available
1925 my @updated_holdings;
1927 @updated_holdings = $mfhd->get_combined_holdings($scap_field);
1930 my $msg = "get_combined_holdings(): $@ ; using sdist ID #" .
1931 ($sdist ? $sdist->id : "<NONE>") . " and " .
1932 scalar(@$issuances) . " issuances, of which one has ID #" .
1933 $issuances->[0]->id;
1936 $logger->error($msg);
1937 return new OpenILS::Event("BAD_PARAMS", note => $msg);
1940 push @formatted_parts, map { $_->format } @updated_holdings;
1943 return ($mfhd, \@formatted_parts);
1946 ##########################################################################
1949 __PACKAGE__->register_method(
1950 method => 'fetch_notes',
1951 api_name => 'open-ils.serial.item_note.retrieve.all',
1953 Returns an array of copy note objects.
1954 @param args A named hash of parameters including:
1955 authtoken : Required if viewing non-public notes
1956 item_id : The id of the item whose notes we want to retrieve
1957 pub : True if all the caller wants are public notes
1958 @return An array of note objects
1962 __PACKAGE__->register_method(
1963 method => 'fetch_notes',
1964 api_name => 'open-ils.serial.subscription_note.retrieve.all',
1966 Returns an array of copy note objects.
1967 @param args A named hash of parameters including:
1968 authtoken : Required if viewing non-public notes
1969 subscription_id : The id of the item whose notes we want to retrieve
1970 pub : True if all the caller wants are public notes
1971 @return An array of note objects
1975 __PACKAGE__->register_method(
1976 method => 'fetch_notes',
1977 api_name => 'open-ils.serial.distribution_note.retrieve.all',
1979 Returns an array of copy note objects.
1980 @param args A named hash of parameters including:
1981 authtoken : Required if viewing non-public notes
1982 distribution_id : The id of the item whose notes we want to retrieve
1983 pub : True if all the caller wants are public notes
1984 @return An array of note objects
1988 # TODO: revisit this method to consider replacing cstore direct calls
1990 my( $self, $connection, $args ) = @_;
1992 $self->api_name =~ /serial\.(\w*)_note/;
1995 my $id = $$args{object_id};
1996 my $authtoken = $$args{authtoken};
1997 my $order_by = $$args{order_by} || 'create_date';
2001 return $U->cstorereq(
2002 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic',
2003 { $type => $id, pub => 't' }, {'order_by' => {$FM_NAME_TO_ID{$type}.'n' => $order_by}} );
2005 # FIXME: restore perm check
2006 # ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
2007 # return $evt if $evt;
2008 return $U->cstorereq(
2009 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic', {$type => $id}, {'order_by' => {$FM_NAME_TO_ID{$type}.'n' => $order_by}} );
2015 __PACKAGE__->register_method(
2016 method => 'update_note',
2017 api_name => 'open-ils.serial.item_note.update',
2019 Updates or creates an item note
2020 @param authtoken The login session key
2021 @param note The note object to update or create
2022 @return The id of the note object
2026 __PACKAGE__->register_method(
2027 method => 'update_note',
2028 api_name => 'open-ils.serial.subscription_note.update',
2030 Updates or creates a subscription note
2031 @param authtoken The login session key
2032 @param note The note object to update or create
2033 @return The id of the note object
2037 __PACKAGE__->register_method(
2038 method => 'update_note',
2039 api_name => 'open-ils.serial.distribution_note.update',
2041 Updates or creates a distribution note
2042 @param authtoken The login session key
2043 @param note The note object to update or create
2044 @return The id of the note object
2049 my( $self, $connection, $authtoken, $note ) = @_;
2051 $self->api_name =~ /serial\.(\w*)_note/;
2054 my $e = new_editor(xact=>1, authtoken=>$authtoken);
2055 return $e->event unless $e->checkauth;
2057 if ($type eq 'item') {
2058 my $sitem = $e->retrieve_serial_item([
2060 "flesh" => 2, "flesh_fields" => {
2061 "sitem" => ["stream"], "sstr" => ["distribution"]
2064 ]) or return $e->die_event;
2066 return $e->die_event unless $e->allowed(
2067 "ADMIN_SERIAL_ITEM", $sitem->stream->distribution->holding_lib
2069 } elsif ($type eq 'distribution') {
2070 my $sdist = $e->retrieve_serial_distribution($note->distribution)
2071 or return $e->die_event;
2073 return $e->die_event unless
2074 $e->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2075 } else { # subscription
2076 my $sub = $e->retrieve_serial_subscription($note->subscription)
2077 or return $e->die_event;
2079 return $e->die_event unless
2080 $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
2083 $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
2086 $note->create_date('now');
2087 $note->creator($e->requestor->id);
2089 $method = "create_serial_${type}_note";
2091 $method = "update_serial_${type}_note";
2093 $e->$method($note) or return $e->event;
2098 __PACKAGE__->register_method(
2099 method => 'delete_note',
2100 api_name => 'open-ils.serial.item_note.delete',
2102 Deletes an existing item note
2103 @param authtoken The login session key
2104 @param noteid The id of the note to delete
2105 @return 1 on success - Event otherwise.
2109 __PACKAGE__->register_method(
2110 method => 'delete_note',
2111 api_name => 'open-ils.serial.subscription_note.delete',
2113 Deletes an existing subscription note
2114 @param authtoken The login session key
2115 @param noteid The id of the note to delete
2116 @return 1 on success - Event otherwise.
2120 __PACKAGE__->register_method(
2121 method => 'delete_note',
2122 api_name => 'open-ils.serial.distribution_note.delete',
2124 Deletes an existing distribution note
2125 @param authtoken The login session key
2126 @param noteid The id of the note to delete
2127 @return 1 on success - Event otherwise.
2132 my( $self, $conn, $authtoken, $noteid ) = @_;
2134 $self->api_name =~ /serial\.(\w*)_note/;
2137 my $e = new_editor(xact=>1, authtoken=>$authtoken);
2138 return $e->die_event unless $e->checkauth;
2140 my $method = "retrieve_serial_${type}_note";
2141 my $note = $e->$method([
2143 ]) or return $e->die_event;
2145 if ($type eq 'item') {
2146 my $sitem = $e->retrieve_serial_item([
2148 "flesh" => 2, "flesh_fields" => {
2149 "sitem" => ["stream"], "sstr" => ["distribution"]
2152 ]) or return $e->die_event;
2154 return $e->die_event unless $e->allowed(
2155 "ADMIN_SERIAL_ITEM", $sitem->stream->distribution->holding_lib
2157 } elsif ($type eq 'distribution') {
2158 my $sdist = $e->retrieve_serial_distribution($note->distribution)
2159 or return $e->die_event;
2161 return $e->die_event unless
2162 $e->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2163 } else { # subscription
2164 my $sub = $e->retrieve_serial_subscription($note->subscription)
2165 or return $e->die_event;
2167 return $e->die_event unless
2168 $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
2171 $method = "delete_serial_${type}_note";
2172 $e->$method($note) or return $e->die_event;
2178 ##########################################################################
2179 # subscription methods
2181 __PACKAGE__->register_method(
2182 method => 'fleshed_ssub_alter',
2183 api_name => 'open-ils.serial.subscription.fleshed.batch.update',
2187 desc => 'Receives an array of one or more subscriptions and updates the database as needed',
2189 name => 'authtoken',
2190 desc => 'Authtoken for current user session',
2194 name => 'subscriptions',
2195 desc => 'Array of fleshed subscriptions',
2201 desc => 'Returns 1 if successful, event if failed',
2207 sub fleshed_ssub_alter {
2208 my( $self, $conn, $auth, $ssubs ) = @_;
2209 return 1 unless ref $ssubs;
2210 my( $reqr, $evt ) = $U->checkses($auth);
2211 return $evt if $evt;
2212 my $editor = new_editor(requestor => $reqr, xact => 1);
2213 my $override = $self->api_name =~ /override/;
2215 for my $ssub (@$ssubs) {
2216 my $owning_lib_id = ref $ssub->owning_lib ? $ssub->owning_lib->id : $ssub->owning_lib;
2217 return $editor->die_event unless
2218 $editor->allowed("ADMIN_SERIAL_SUBSCRIPTION", $owning_lib_id);
2220 my $ssubid = $ssub->id;
2222 if( $ssub->isdeleted ) {
2223 $evt = _delete_ssub( $editor, $override, $ssub);
2224 } elsif( $ssub->isnew ) {
2225 _cleanse_dates($ssub, ['start_date','end_date']);
2226 $evt = _create_ssub( $editor, $ssub );
2228 _cleanse_dates($ssub, ['start_date','end_date']);
2229 $evt = _update_ssub( $editor, $override, $ssub );
2234 $logger->info("fleshed subscription-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2238 $logger->debug("subscription-alter: done updating subscription batch");
2240 $logger->info("fleshed subscription-alter successfully updated ".scalar(@$ssubs)." subscriptions");
2245 my ($editor, $override, $ssub) = @_;
2246 $logger->info("subscription-alter: delete subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2247 my $sdists = $editor->search_serial_distribution(
2248 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2249 my $cps = $editor->search_serial_caption_and_pattern(
2250 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2251 my $sisses = $editor->search_serial_issuance(
2252 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2253 return OpenILS::Event->new(
2254 'SERIAL_SUBSCRIPTION_NOT_EMPTY', payload => $ssub->id ) if (@$sdists or @$cps or @$sisses);
2256 return $editor->event unless $editor->delete_serial_subscription($ssub);
2261 my ($editor, $ssub) = @_;
2263 $logger->info("subscription-alter: new subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2264 return $editor->event unless $editor->create_serial_subscription($ssub);
2269 my ($editor, $override, $ssub) = @_;
2271 $logger->info("subscription-alter: retrieving subscription ".$ssub->id);
2272 my $orig_ssub = $editor->retrieve_serial_subscription($ssub->id);
2274 $logger->info("subscription-alter: original subscription ".OpenSRF::Utils::JSON->perl2JSON($orig_ssub));
2275 $logger->info("subscription-alter: updated subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2276 return $editor->event unless $editor->update_serial_subscription($ssub);
2280 __PACKAGE__->register_method(
2281 method => "fleshed_serial_subscription_retrieve_batch",
2283 api_name => "open-ils.serial.subscription.fleshed.batch.retrieve"
2286 sub fleshed_serial_subscription_retrieve_batch {
2287 my( $self, $client, $ids ) = @_;
2288 # FIXME: permissions?
2289 $logger->info("Fetching fleshed subscriptions @$ids");
2290 return $U->cstorereq(
2291 "open-ils.cstore.direct.serial.subscription.search.atomic",
2294 flesh_fields => {ssub => [ qw/owning_lib notes/ ]}
2298 __PACKAGE__->register_method(
2299 method => "retrieve_sub_tree",
2301 api_name => "open-ils.serial.subscription_tree.retrieve"
2304 __PACKAGE__->register_method(
2305 method => "retrieve_sub_tree",
2306 api_name => "open-ils.serial.subscription_tree.global.retrieve"
2309 sub retrieve_sub_tree {
2311 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2313 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2317 # TODO: permission support
2318 if(!@org_ids and $user_session) {
2320 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2321 @org_ids = ($user_obj->home_ou);
2324 if( $self->api_name =~ /global/ ) {
2325 return _build_subs_list( { record_entry => $docid } ); # TODO: filter for !deleted, or active?
2330 for my $orgid (@org_ids) {
2331 my $subs = _build_subs_list(
2332 { record_entry => $docid, owning_lib => $orgid } );# TODO: filter for !deleted, or active?
2333 push( @all_subs, @$subs );
2342 sub _build_subs_list {
2343 my $search_hash = shift;
2345 #$search_hash->{deleted} = 'f';
2346 my $e = new_editor();
2348 my $subs = $e->search_serial_subscription([$search_hash, { 'order_by' => {'ssub' => 'id'} }]);
2352 for my $sub (@$subs) {
2354 # TODO: filter on !deleted?
2355 my $dists = $e->search_serial_distribution(
2356 [{ subscription => $sub->id }, { 'order_by' => {'sdist' => 'label'} }]
2359 #$dists = [ sort { $a->label cmp $b->label } @$dists ];
2361 $sub->distributions($dists);
2363 # TODO: filter on !deleted?
2364 my $issuances = $e->search_serial_issuance(
2365 [{ subscription => $sub->id }, { 'order_by' => {'siss' => 'label'} }]
2368 #$issuances = [ sort { $a->label cmp $b->label } @$issuances ];
2369 $sub->issuances($issuances);
2371 # TODO: filter on !deleted?
2372 my $scaps = $e->search_serial_caption_and_pattern(
2373 [{ subscription => $sub->id }, { 'order_by' => {'scap' => 'id'} }]
2376 #$scaps = [ sort { $a->id cmp $b->id } @$scaps ];
2377 $sub->scaps($scaps);
2378 push( @built_subs, $sub );
2381 return \@built_subs;
2385 __PACKAGE__->register_method(
2386 method => "subscription_orgs_for_title",
2388 api_name => "open-ils.serial.subscription.retrieve_orgs_by_title"
2391 sub subscription_orgs_for_title {
2392 my( $self, $client, $record_id ) = @_;
2394 my $subs = $U->simple_scalar_request(
2396 "open-ils.cstore.direct.serial.subscription.search.atomic",
2397 { record_entry => $record_id }); # TODO: filter on !deleted?
2399 my $orgs = { map {$_->owning_lib => 1 } @$subs };
2400 return [ keys %$orgs ];
2404 ##########################################################################
2405 # distribution methods
2407 __PACKAGE__->register_method(
2408 method => 'fleshed_sdist_alter',
2409 api_name => 'open-ils.serial.distribution.fleshed.batch.update',
2413 desc => 'Receives an array of one or more distributions and updates the database as needed',
2415 name => 'authtoken',
2416 desc => 'Authtoken for current user session',
2420 name => 'distributions',
2421 desc => 'Array of fleshed distributions',
2427 desc => 'Returns 1 if successful, event if failed',
2433 sub fleshed_sdist_alter {
2434 my( $self, $conn, $auth, $sdists ) = @_;
2435 return 1 unless ref $sdists;
2436 my( $reqr, $evt ) = $U->checkses($auth);
2437 return $evt if $evt;
2438 my $editor = new_editor(requestor => $reqr, xact => 1);
2439 my $override = $self->api_name =~ /override/;
2441 for my $sdist (@$sdists) {
2442 my $holding_lib_id = ref $sdist->holding_lib ? $sdist->holding_lib->id : $sdist->holding_lib;
2443 return $editor->die_event unless
2444 $editor->allowed("ADMIN_SERIAL_DISTRIBUTION", $holding_lib_id);
2446 if( $sdist->isdeleted ) {
2447 $evt = _delete_sdist( $editor, $override, $sdist);
2448 } elsif( $sdist->isnew ) {
2449 $evt = _create_sdist( $editor, $sdist );
2451 $evt = _update_sdist( $editor, $override, $sdist );
2456 $logger->info("fleshed distribution-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2460 $logger->debug("distribution-alter: done updating distribution batch");
2462 $logger->info("fleshed distribution-alter successfully updated ".scalar(@$sdists)." distributions");
2467 my ($editor, $override, $sdist) = @_;
2468 $logger->info("distribution-alter: delete distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2469 return $editor->event unless $editor->delete_serial_distribution($sdist);
2474 my ($editor, $sdist) = @_;
2476 $logger->info("distribution-alter: new distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2477 return $editor->event unless $editor->create_serial_distribution($sdist);
2479 # create summaries too
2480 my $summary = new Fieldmapper::serial::basic_summary;
2481 $summary->distribution($sdist->id);
2482 $summary->generated_coverage('');
2483 return $editor->event unless $editor->create_serial_basic_summary($summary);
2484 $summary = new Fieldmapper::serial::supplement_summary;
2485 $summary->distribution($sdist->id);
2486 $summary->generated_coverage('');
2487 return $editor->event unless $editor->create_serial_supplement_summary($summary);
2488 $summary = new Fieldmapper::serial::index_summary;
2489 $summary->distribution($sdist->id);
2490 $summary->generated_coverage('');
2491 return $editor->event unless $editor->create_serial_index_summary($summary);
2493 # create a starter stream (TODO: reconsider this)
2494 my $stream = new Fieldmapper::serial::stream;
2495 $stream->distribution($sdist->id);
2496 return $editor->event unless $editor->create_serial_stream($stream);
2502 my ($editor, $override, $sdist) = @_;
2504 $logger->info("distribution-alter: retrieving distribution ".$sdist->id);
2505 my $orig_sdist = $editor->retrieve_serial_distribution($sdist->id);
2507 $logger->info("distribution-alter: original distribution ".OpenSRF::Utils::JSON->perl2JSON($orig_sdist));
2508 $logger->info("distribution-alter: updated distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2509 return $editor->event unless $editor->update_serial_distribution($sdist);
2513 __PACKAGE__->register_method(
2514 method => "fleshed_serial_distribution_retrieve_batch",
2516 api_name => "open-ils.serial.distribution.fleshed.batch.retrieve"
2519 sub fleshed_serial_distribution_retrieve_batch {
2520 my( $self, $client, $ids ) = @_;
2521 # FIXME: permissions?
2522 $logger->info("Fetching fleshed distributions @$ids");
2523 return $U->cstorereq(
2524 "open-ils.cstore.direct.serial.distribution.search.atomic",
2527 flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams notes / ]}
2531 __PACKAGE__->register_method(
2532 method => "retrieve_dist_tree",
2534 api_name => "open-ils.serial.distribution_tree.retrieve"
2537 __PACKAGE__->register_method(
2538 method => "retrieve_dist_tree",
2539 api_name => "open-ils.serial.distribution_tree.global.retrieve"
2542 sub retrieve_dist_tree {
2543 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2545 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2549 # TODO: permission support
2550 if(!@org_ids and $user_session) {
2552 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2553 @org_ids = ($user_obj->home_ou);
2556 my $e = new_editor();
2558 if( $self->api_name =~ /global/ ) {
2559 return $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }},
2561 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 / ]},
2562 order_by => {'sdist' => 'id'},
2563 'join' => {'ssub' => {}}
2565 ]); # TODO: filter for !deleted?
2569 for my $orgid (@org_ids) {
2570 my $dists = $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }, holding_lib => $orgid},
2572 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 / ]},
2573 order_by => {'sdist' => 'id'},
2574 'join' => {'ssub' => {}}
2576 ]); # TODO: filter for !deleted?
2577 push( @all_dists, @$dists ) if $dists;
2587 __PACKAGE__->register_method(
2588 method => "distribution_orgs_for_title",
2590 api_name => "open-ils.serial.distribution.retrieve_orgs_by_title"
2593 sub distribution_orgs_for_title {
2594 my( $self, $client, $record_id ) = @_;
2596 my $dists = $U->cstorereq(
2597 "open-ils.cstore.direct.serial.distribution.search.atomic",
2598 { '+ssub' => { record_entry => $record_id } },
2599 { 'join' => {'ssub' => {}} }); # TODO: filter on !deleted?
2601 my $orgs = { map {$_->holding_lib => 1 } @$dists };
2602 return [ keys %$orgs ];
2606 ##########################################################################
2607 # caption and pattern methods
2609 __PACKAGE__->register_method(
2610 method => 'scap_alter',
2611 api_name => 'open-ils.serial.caption_and_pattern.batch.update',
2615 desc => 'Receives an array of one or more caption and patterns and updates the database as needed',
2617 name => 'authtoken',
2618 desc => 'Authtoken for current user session',
2623 desc => 'Array of caption and patterns',
2629 desc => 'Returns 1 if successful, event if failed',
2636 my( $self, $conn, $auth, $scaps ) = @_;
2637 return 1 unless ref $scaps;
2638 my( $reqr, $evt ) = $U->checkses($auth);
2639 return $evt if $evt;
2640 my $editor = new_editor(requestor => $reqr, xact => 1);
2641 my $override = $self->api_name =~ /override/;
2644 for my $scap (@$scaps) {
2645 if (!exists($found_ssub_ids{$scap->subscription})) {
2646 my $ssub = $editor->retrieve_serial_subscription($scap->subscription) or return $editor->die_event;
2647 return $editor->die_event unless
2648 $editor->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $ssub->owning_lib);
2649 $found_ssub_ids{$scap->subscription} = 1;
2652 if( $scap->isdeleted ) {
2653 $evt = _delete_scap( $editor, $override, $scap);
2654 } elsif( $scap->isnew ) {
2655 $evt = _create_scap( $editor, $scap );
2657 $evt = _update_scap( $editor, $override, $scap );
2662 $logger->info("caption_and_pattern-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2666 $logger->debug("caption_and_pattern-alter: done updating caption_and_pattern batch");
2668 $logger->info("caption_and_pattern-alter successfully updated ".scalar(@$scaps)." caption_and_patterns");
2673 my ($editor, $override, $scap) = @_;
2674 $logger->info("caption_and_pattern-alter: delete caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2675 my $sisses = $editor->search_serial_issuance(
2676 { caption_and_pattern => $scap->id }, { limit => 1 } ); #TODO: 'deleted' support?
2677 return OpenILS::Event->new(
2678 'SERIAL_CAPTION_AND_PATTERN_HAS_ISSUANCES', payload => $scap->id ) if (@$sisses);
2680 return $editor->event unless $editor->delete_serial_caption_and_pattern($scap);
2685 my ($editor, $scap) = @_;
2687 $logger->info("caption_and_pattern-alter: new caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2688 return $editor->event unless $editor->create_serial_caption_and_pattern($scap);
2693 my ($editor, $override, $scap) = @_;
2695 $logger->info("caption_and_pattern-alter: retrieving caption_and_pattern ".$scap->id);
2696 my $orig_scap = $editor->retrieve_serial_caption_and_pattern($scap->id);
2698 $logger->info("caption_and_pattern-alter: original caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($orig_scap));
2699 $logger->info("caption_and_pattern-alter: updated caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2700 return $editor->event unless $editor->update_serial_caption_and_pattern($scap);
2704 __PACKAGE__->register_method(
2705 method => "serial_caption_and_pattern_retrieve_batch",
2707 api_name => "open-ils.serial.caption_and_pattern.batch.retrieve"
2710 sub serial_caption_and_pattern_retrieve_batch {
2711 my( $self, $client, $ids ) = @_;
2712 $logger->info("Fetching caption_and_patterns @$ids");
2713 return $U->cstorereq(
2714 "open-ils.cstore.direct.serial.caption_and_pattern.search.atomic",
2719 ##########################################################################
2722 __PACKAGE__->register_method(
2723 method => 'sstr_alter',
2724 api_name => 'open-ils.serial.stream.batch.update',
2728 desc => 'Receives an array of one or more streams and updates the database as needed',
2730 name => 'authtoken',
2731 desc => 'Authtoken for current user session',
2736 desc => 'Array of streams',
2742 desc => 'Returns 1 if successful, event if failed',
2749 my( $self, $conn, $auth, $sstrs ) = @_;
2750 return 1 unless ref $sstrs;
2751 my( $reqr, $evt ) = $U->checkses($auth);
2752 return $evt if $evt;
2753 my $editor = new_editor(requestor => $reqr, xact => 1);
2754 my $override = $self->api_name =~ /override/;
2756 my %found_sdist_ids;
2757 for my $sstr (@$sstrs) {
2758 if (!exists($found_sdist_ids{$sstr->distribution})) {
2759 my $sdist = $editor->retrieve_serial_distribution($sstr->distribution) or return $editor->die_event;
2760 return $editor->die_event unless
2761 $editor->allowed("ADMIN_SERIAL_STREAM", $sdist->holding_lib);
2762 $found_sdist_ids{$sstr->distribution} = 1;
2765 if( $sstr->isdeleted ) {
2766 $evt = _delete_sstr( $editor, $override, $sstr);
2767 } elsif( $sstr->isnew ) {
2768 $evt = _create_sstr( $editor, $sstr );
2770 $evt = _update_sstr( $editor, $override, $sstr );
2775 $logger->info("stream-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2779 $logger->debug("stream-alter: done updating stream batch");
2781 $logger->info("stream-alter successfully updated ".scalar(@$sstrs)." streams");
2786 my ($editor, $override, $sstr) = @_;
2787 $logger->info("stream-alter: delete stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2788 my $sitems = $editor->search_serial_item(
2789 { stream => $sstr->id }, { limit => 1 } ); #TODO: 'deleted' support?
2790 return OpenILS::Event->new(
2791 'SERIAL_STREAM_HAS_ITEMS', payload => $sstr->id ) if (@$sitems);
2793 return $editor->event unless $editor->delete_serial_stream($sstr);
2798 my ($editor, $sstr) = @_;
2800 $logger->info("stream-alter: new stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2801 return $editor->event unless $editor->create_serial_stream($sstr);
2806 my ($editor, $override, $sstr) = @_;
2808 $logger->info("stream-alter: retrieving stream ".$sstr->id);
2809 my $orig_sstr = $editor->retrieve_serial_stream($sstr->id);
2811 $logger->info("stream-alter: original stream ".OpenSRF::Utils::JSON->perl2JSON($orig_sstr));
2812 $logger->info("stream-alter: updated stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2813 return $editor->event unless $editor->update_serial_stream($sstr);
2817 __PACKAGE__->register_method(
2818 method => "serial_stream_retrieve_batch",
2820 api_name => "open-ils.serial.stream.batch.retrieve"
2823 sub serial_stream_retrieve_batch {
2824 my( $self, $client, $ids ) = @_;
2825 $logger->info("Fetching streams @$ids");
2826 return $U->cstorereq(
2827 "open-ils.cstore.direct.serial.stream.search.atomic",
2833 ##########################################################################
2836 __PACKAGE__->register_method(
2837 method => 'sum_alter',
2838 api_name => 'open-ils.serial.basic_summary.batch.update',
2842 desc => 'Receives an array of one or more summaries and updates the database as needed',
2844 name => 'authtoken',
2845 desc => 'Authtoken for current user session',
2850 desc => 'Array of basic summaries',
2856 desc => 'Returns 1 if successful, event if failed',
2862 __PACKAGE__->register_method(
2863 method => 'sum_alter',
2864 api_name => 'open-ils.serial.supplement_summary.batch.update',
2868 desc => 'Receives an array of one or more summaries and updates the database as needed',
2870 name => 'authtoken',
2871 desc => 'Authtoken for current user session',
2876 desc => 'Array of supplement summaries',
2882 desc => 'Returns 1 if successful, event if failed',
2888 __PACKAGE__->register_method(
2889 method => 'sum_alter',
2890 api_name => 'open-ils.serial.index_summary.batch.update',
2894 desc => 'Receives an array of one or more summaries and updates the database as needed',
2896 name => 'authtoken',
2897 desc => 'Authtoken for current user session',
2902 desc => 'Array of index summaries',
2908 desc => 'Returns 1 if successful, event if failed',
2915 my( $self, $conn, $auth, $sums ) = @_;
2916 return 1 unless ref $sums;
2918 $self->api_name =~ /serial\.(\w*)_summary/;
2921 my( $reqr, $evt ) = $U->checkses($auth);
2922 return $evt if $evt;
2923 my $editor = new_editor(requestor => $reqr, xact => 1);
2924 my $override = $self->api_name =~ /override/;
2926 my %found_sdist_ids;
2927 for my $sum (@$sums) {
2928 if (!exists($found_sdist_ids{$sum->distribution})) {
2929 my $sdist = $editor->retrieve_serial_distribution($sum->distribution) or return $editor->die_event;
2930 return $editor->die_event unless
2931 $editor->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2932 $found_sdist_ids{$sum->distribution} = 1;
2935 # XXX: (for now, at least) summaries should be created/deleted by the distribution functions
2936 if( $sum->isdeleted ) {
2937 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2938 } elsif( $sum->isnew ) {
2939 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2941 $evt = _update_sum( $editor, $override, $sum, $type );
2946 $logger->info("${type}_summary-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2950 $logger->debug("${type}_summary-alter: done updating ${type}_summary batch");
2952 $logger->info("${type}_summary-alter successfully updated ".scalar(@$sums)." ${type}_summaries");
2957 my ($editor, $override, $sum, $type) = @_;
2959 $logger->info("${type}_summary-alter: retrieving ${type}_summary ".$sum->id);
2960 my $retrieve_method = "retrieve_serial_${type}_summary";
2961 my $orig_sum = $editor->$retrieve_method($sum->id);
2963 $logger->info("${type}_summary-alter: original ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($orig_sum));
2964 $logger->info("${type}_summary-alter: updated ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($sum));
2965 my $update_method = "update_serial_${type}_summary";
2966 return $editor->event unless $editor->$update_method($sum);
2970 __PACKAGE__->register_method(
2971 method => "serial_summary_retrieve_batch",
2973 api_name => "open-ils.serial.basic_summary.batch.retrieve"
2976 __PACKAGE__->register_method(
2977 method => "serial_summary_retrieve_batch",
2979 api_name => "open-ils.serial.supplement_summary.batch.retrieve"
2982 __PACKAGE__->register_method(
2983 method => "serial_summary_retrieve_batch",
2985 api_name => "open-ils.serial.index_summary.batch.retrieve"
2988 sub serial_summary_retrieve_batch {
2989 my( $self, $client, $ids ) = @_;
2991 $self->api_name =~ /serial\.(\w*)_summary/;
2994 $logger->info("Fetching ${type}_summaries @$ids");
2995 return $U->cstorereq(
2996 "open-ils.cstore.direct.serial.".$type."_summary.search.atomic",
3002 ##########################################################################
3005 __PACKAGE__->register_method(
3006 "method" => "bre_by_identifier",
3007 "api_name" => "open-ils.serial.biblio.record_entry.by_identifier",
3010 "desc" => "Find instances of biblio.record_entry given a search token" .
3011 " that could be a value for any identifier defined in " .
3012 "config.metabib_field",
3014 {"desc" => "Search token", "type" => "string"},
3015 {"desc" => "Options: require_subscriptions, add_mvr, is_actual_id" .
3016 ", id_list (all boolean)", "type" => "object"}
3019 "desc" => "Any matching BREs, or if the add_mvr option is true, " .
3020 "objects with a 'bre' key/value pair, and an 'mvr' " .
3021 "key-value pair. BREs have subscriptions fleshed on.",
3027 sub bre_by_identifier {
3028 my ($self, $client, $term, $options) = @_;
3030 return new OpenILS::Event("BAD_PARAMS") unless $term;
3033 my $e = new_editor();
3037 if ($options->{"is_actual_id"}) {
3041 $e->search_config_metabib_field({"field_class" => "identifier"})
3042 or return $e->die_event;
3044 my @identifiers = map { $_->name } @$cmf;
3045 my $query = join(" || ", map { "id|$_: $term" } @identifiers);
3047 my $search = create OpenSRF::AppSession("open-ils.search");
3048 my $search_result = $search->request(
3049 "open-ils.search.biblio.multiclass.query.staff", {}, $query
3051 $search->disconnect;
3053 # Un-nest results. They tend to look like [[1],[2],[3]] for some reason.
3054 @ids = map { @{$_} } @{$search_result->{"ids"}};
3061 if ($options->{"id_list"}) {
3063 $client->respond($_) foreach (@ids);
3068 my $bre = $e->search_biblio_record_entry([
3070 "flesh" => 2, "flesh_fields" => {
3071 "bre" => ["subscriptions"],
3072 "ssub" => ["owning_lib"]
3075 ]) or return $e->die_event;
3077 if (@$bre && $options->{"require_subscriptions"}) {
3078 $bre = [ grep { @{$_->subscriptions} } @$bre ];
3083 if (@$bre) { # re-evaluate after possible grep
3084 if ($options->{"add_mvr"}) {
3086 {"bre" => $_, "mvr" => _get_mvr($_->id)}
3089 $client->respond($_) foreach (@$bre);
3096 __PACKAGE__->register_method(
3097 "method" => "get_items_by",
3098 "api_name" => "open-ils.serial.items.receivable.by_subscription",
3101 "desc" => "Return all receivable items under a given subscription",
3103 {"desc" => "Authtoken", "type" => "string"},
3104 {"desc" => "Subscription ID", "type" => "number"},
3107 "desc" => "All receivable items under a given subscription",
3108 "type" => "object", "class" => "sitem"
3113 __PACKAGE__->register_method(
3114 "method" => "get_items_by",
3115 "api_name" => "open-ils.serial.items.receivable.by_issuance",
3118 "desc" => "Return all receivable items under a given issuance",
3120 {"desc" => "Authtoken", "type" => "string"},
3121 {"desc" => "Issuance ID", "type" => "number"},
3124 "desc" => "All receivable items under a given issuance",
3125 "type" => "object", "class" => "sitem"
3130 __PACKAGE__->register_method(
3131 "method" => "get_items_by",
3132 "api_name" => "open-ils.serial.items.by_issuance",
3135 "desc" => "Return all items under a given issuance",
3137 {"desc" => "Authtoken", "type" => "string"},
3138 {"desc" => "Issuance ID", "type" => "number"},
3141 "desc" => "All items under a given issuance",
3142 "type" => "object", "class" => "sitem"
3148 my ($self, $client, $auth, $term, $opts) = @_;
3150 # Not to be used in the json_query, but after limiting by perm check.
3151 $opts = {} unless ref $opts eq "HASH";
3152 $opts->{"limit"} ||= 10000; # some existing users may want all results
3153 $opts->{"offset"} ||= 0;
3154 $opts->{"limit"} = int($opts->{"limit"});
3155 $opts->{"offset"} = int($opts->{"offset"});
3157 my $e = new_editor("authtoken" => $auth);
3158 return $e->die_event unless $e->checkauth;
3160 my $by = ($self->api_name =~ /by_(\w+)$/)[0];
3161 my $receivable = ($self->api_name =~ /receivable/);
3164 "issuance" => {"issuance" => $term},
3165 "subscription" => {"+siss" => {"subscription" => $term}}
3168 my $item_rows = $e->json_query(
3170 "select" => {"sitem" => ["id"], "sdist" => ["holding_lib"]},
3174 "sstr" => {"join" => {"sdist" => {}}}
3178 %{$where{$by}}, $receivable ? ("date_received" => undef) : ()
3180 "order_by" => {"sitem" => ["id"]}
3182 ) or return $e->die_event;
3184 return undef unless @$item_rows;
3188 foreach (@$item_rows) {
3189 last if $returned >= $opts->{"limit"};
3190 next unless $e->allowed("RECEIVE_SERIAL", $_->{"holding_lib"});
3191 if ($skipped < $opts->{"offset"}) {
3197 $e->retrieve_serial_item([
3201 "sitem" => [qw/stream issuance unit creator editor/],
3202 "sstr" => ["distribution"],
3203 "sdist" => ["holding_lib"]
3215 __PACKAGE__->register_method(
3216 "method" => "get_receivable_issuances",
3217 "api_name" => "open-ils.serial.issuances.receivable",
3220 "desc" => "Return all issuances with receivable items given " .
3221 "a subscription ID",
3223 {"desc" => "Authtoken", "type" => "string"},
3224 {"desc" => "Subscription ID", "type" => "number"},
3227 "desc" => "All issuances with receivable items " .
3228 "(but not the items themselves)", "type" => "object"
3233 sub get_receivable_issuances {
3234 my ($self, $client, $auth, $sub_id) = @_;
3236 my $e = new_editor("authtoken" => $auth);
3237 return $e->die_event unless $e->checkauth;
3241 my $issuance_ids = $e->json_query({
3244 {"transform" => "distinct", "column" => "id"},
3248 "from" => {"siss" => "sitem"},
3250 "subscription" => $sub_id,
3251 "+sitem" => {"date_received" => undef}
3254 "siss" => {"date_published" => {"direction" => "asc"}}
3257 }) or return $e->die_event;
3259 $client->respond($e->retrieve_serial_issuance($_->{"id"}))
3260 foreach (@$issuance_ids);
3267 __PACKAGE__->register_method(
3268 "method" => "get_routing_list_users",
3269 "api_name" => "open-ils.serial.routing_list_users.fleshed_and_ordered",
3272 "desc" => "Return all routing list users with reader fleshed " .
3273 "(with card and home_ou) for a given stream ID, sorted by pos",
3275 {"desc" => "Authtoken", "type" => "string"},
3276 {"desc" => "Stream ID (int or array of ints)", "type" => "mixed"},
3279 "desc" => "Stream of routing list users", "type" => "object",
3285 sub get_routing_list_users {
3286 my ($self, $client, $auth, $stream_id) = @_;
3288 my $e = new_editor("authtoken" => $auth);
3289 return $e->die_event unless $e->checkauth;
3291 my $users = $e->search_serial_routing_list_user([
3292 {"stream" => $stream_id}, {
3293 "order_by" => {"srlu" => "pos"},
3296 "srlu" => [qw/reader stream/],
3297 "au" => [qw/card home_ou mailing_address billing_address/],
3298 "sstr" => ["distribution"]
3301 ]) or return $e->die_event;
3303 return undef unless @$users;
3305 # The ADMIN_SERIAL_STREAM permission is used simply to avoid the
3306 # need for any new permission. The context OU will be the same
3307 # for every result of the above query, so we need only check once.
3308 return $e->die_event unless $e->allowed(
3309 "ADMIN_SERIAL_STREAM", $users->[0]->stream->distribution->holding_lib
3314 my @users = map { $_->stream($_->stream->id); $_ } @$users;
3315 @users = sort { $a->stream cmp $b->stream } @users if
3316 ref $stream_id eq "ARRAY";
3318 $client->respond($_) for @users;
3324 __PACKAGE__->register_method(
3325 "method" => "replace_routing_list_users",
3326 "api_name" => "open-ils.serial.routing_list_users.replace",
3328 "desc" => "Replace all routing list users on the specified streams " .
3329 "with those in the list argument",
3331 {"desc" => "Authtoken", "type" => "string"},
3332 {"desc" => "List of srlu objects", "type" => "array"},
3335 "desc" => "event on failure, undef on success"
3340 sub replace_routing_list_users {
3341 my ($self, $client, $auth, $users) = @_;
3343 return undef unless ref $users eq "ARRAY";
3345 if (grep { ref $_ ne "Fieldmapper::serial::routing_list_user" } @$users) {
3346 return new OpenILS::Event("BAD_PARAMS", "note" => "Only srlu objects");
3349 my $e = new_editor("authtoken" => $auth, "xact" => 1);
3350 return $e->die_event unless $e->checkauth;
3352 my %streams_ok = ();
3355 foreach my $user (@$users) {
3356 unless (exists $streams_ok{$user->stream}) {
3357 my $stream = $e->retrieve_serial_stream([
3360 "flesh_fields" => {"sstr" => ["distribution"]}
3362 ]) or return $e->die_event;
3364 "ADMIN_SERIAL_STREAM", $stream->distribution->holding_lib
3365 ) or return $e->die_event;
3367 my $to_delete = $e->search_serial_routing_list_user(
3368 {"stream" => $user->stream}
3369 ) or return $e->die_event;
3372 "Deleting srlu: [" .
3373 join(", ", map { $_->id; } @$to_delete) .
3377 foreach (@$to_delete) {
3378 $e->delete_serial_routing_list_user($_) or
3379 return $e->die_event;
3382 $streams_ok{$user->stream} = 1;
3385 next if $user->isdeleted;
3389 $e->create_serial_routing_list_user($user) or return $e->die_event;
3392 $e->commit or return $e->die_event;
3396 __PACKAGE__->register_method(
3397 "method" => "get_records_with_marc_85x",
3398 "api_name"=>"open-ils.serial.caption_and_pattern.find_legacy_by_bib_record",
3401 "desc" => "Return the specified BRE itself and/or any related SRE ".
3402 "whenever they have 853-855 tags",
3404 {"desc" => "Authtoken", "type" => "string"},
3405 {"desc" => "bib record ID", "type" => "number"},
3408 "desc" => "objects, either bre or sre", "type" => "object"
3413 sub get_records_with_marc_85x { # specifically, 853-855
3414 my ($self, $client, $auth, $bre_id) = @_;
3416 my $e = new_editor("authtoken" => $auth);
3417 return $e->die_event unless $e->checkauth;
3419 my $bre = $e->search_biblio_record_entry([
3420 {"id" => $bre_id, "deleted" => "f"}, {
3422 "flesh_fields" => {"bre" => [qw/creator editor owner/]}
3424 ]) or return $e->die_event;
3426 return undef unless @$bre;
3429 my $record = MARC::Record->new_from_xml($bre->marc);
3430 $client->respond($bre) if $record->field("85[3-5]");
3431 # XXX Is passing a regex to ->field() an abuse of MARC::Record ?
3433 my $sres = $e->search_serial_record_entry([
3434 {"record" => $bre_id, "deleted" => "f"}, {
3436 "flesh_fields" => {"sre" => [qw/creator editor owning_lib/]}
3438 ]) or return $e->die_event;
3442 foreach my $sre (@$sres) {
3443 $client->respond($sre) if
3444 MARC::Record->new_from_xml($sre->marc)->field("85[3-5]");
3450 __PACKAGE__->register_method(
3451 "method" => "create_scaps_from_marcxml",
3452 "api_name" => "open-ils.serial.caption_and_pattern.create_from_records",
3455 "desc" => "Create caption and pattern objects from 853-855 tags " .
3456 "in MARCXML documents",
3458 {"desc" => "Authtoken", "type" => "string"},
3459 {"desc" => "Subscription ID", "type" => "number"},
3460 {"desc" => "list of MARCXML documents as strings",
3464 "desc" => "Newly created caption and pattern objects",
3465 "type" => "object", "class" => "scap"
3470 sub create_scaps_from_marcxml {
3471 my ($self, $client, $auth, $sub_id, $docs) = @_;
3473 return undef unless ref $docs eq "ARRAY";
3475 my $e = new_editor("authtoken" => $auth, "xact" => 1);
3476 return $e->die_event unless $e->checkauth;
3478 # Retrieve the subscription just for perm checking (whether we can create
3479 # scaps at the owning lib).
3480 my $sub = $e->retrieve_serial_subscription($sub_id) or return $e->die_event;
3481 return $e->die_event unless
3482 $e->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $sub->owning_lib);
3484 foreach my $record (map { MARC::Record->new_from_xml($_) } @$docs) {
3485 foreach my $field ($record->field("85[3-5]")) {
3486 my $scap = new Fieldmapper::serial::caption_and_pattern;
3487 $scap->subscription($sub_id);
3488 $scap->type($MFHD_NAMES_BY_TAG{$field->tag});
3489 $scap->pattern_code(
3490 OpenSRF::Utils::JSON->perl2JSON(
3491 [ $field->indicator(1), $field->indicator(2),
3492 map { @$_ } $field->subfields ] # flattens nested array
3495 $e->create_serial_caption_and_pattern($scap) or
3496 return $e->die_event;
3497 $client->respond($e->data);
3501 $e->commit or return $e->die_event;
3505 # All these _clone_foo() functions could possibly have been consolidated into
3506 # one clever function, but it's faster to get things working this way.
3507 sub _clone_subscription {
3508 my ($sub, $bib_id, $e) = @_;
3511 my $new_sub = $sub->clone;
3512 $new_sub->record_entry(int $bib_id) if $bib_id;
3514 $new_sub->clear_distributions;
3515 $new_sub->clear_notes;
3516 $new_sub->clear_scaps;
3518 $e->create_serial_subscription($new_sub) or return $e->die_event;
3520 my $new_sub_id = $e->data->id;
3522 foreach my $dist (@{$sub->distributions}) {
3523 my $r = _clone_distribution($dist, $new_sub_id, $e);
3524 return $r if $U->event_code($r);
3528 foreach my $note (@{$sub->notes}) {
3529 my $r = _clone_subscription_note($note, $new_sub_id, $e);
3530 return $r if $U->event_code($r);
3534 foreach my $scap (@{$sub->scaps}) {
3535 my $r = _clone_caption_and_pattern($scap, $new_sub_id, $e);
3536 return $r if $U->event_code($r);
3542 sub _clone_distribution {
3543 my ($dist, $sub_id, $e) = @_;
3545 my $new_dist = $dist->clone;
3546 $new_dist->clear_id;
3547 $new_dist->clear_notes;
3548 $new_dist->clear_streams;
3549 $new_dist->subscription($sub_id);
3551 $e->create_serial_distribution($new_dist) or return $e->die_event;
3552 my $new_dist_id = $e->data->id;
3555 foreach my $stream (@{$dist->streams}) {
3556 my $r = _clone_stream($stream, $new_dist_id, $e);
3557 return $r if $U->event_code($r);
3560 # clone distribution notes
3561 foreach my $note (@{$dist->notes}) {
3562 my $r = _clone_distribution_note($note, $new_dist_id, $e);
3563 return $r if $U->event_code($r);
3566 return $new_dist_id;
3569 sub _clone_subscription_note {
3570 my ($note, $sub_id, $e) = @_;
3572 my $new_note = $note->clone;
3573 $new_note->clear_id;
3574 $new_note->creator($e->requestor->id);
3575 $new_note->create_date("now");
3576 $new_note->subscription($sub_id);
3578 $e->create_serial_subscription_note($new_note) or return $e->die_event;
3579 return $e->data->id;
3582 sub _clone_caption_and_pattern {
3583 my ($scap, $sub_id, $e) = @_;
3585 my $new_scap = $scap->clone;
3586 $new_scap->clear_id;
3587 $new_scap->subscription($sub_id);
3589 $e->create_serial_caption_and_pattern($new_scap) or return $e->die_event;
3590 return $e->data->id;
3593 sub _clone_distribution_note {
3594 my ($note, $dist_id, $e) = @_;
3596 my $new_note = $note->clone;
3597 $new_note->clear_id;
3598 $new_note->creator($e->requestor->id);
3599 $new_note->create_date("now");
3600 $new_note->distribution($dist_id);
3602 $e->create_serial_distribution_note($new_note) or return $e->die_event;
3603 return $e->data->id;
3607 my ($stream, $dist_id, $e) = @_;
3609 my $new_stream = $stream->clone;
3610 $new_stream->clear_id;
3611 $new_stream->clear_routing_list_users;
3612 $new_stream->distribution($dist_id);
3614 $e->create_serial_stream($new_stream) or return $e->die_event;
3615 my $new_stream_id = $e->data->id;
3617 # clone routing list users
3618 foreach my $user (@{$stream->routing_list_users}) {
3619 my $r = _clone_routing_list_user($user, $new_stream_id, $e);
3620 return $r if $U->event_code($r);
3623 return $new_stream_id;
3626 sub _clone_routing_list_user {
3627 my ($user, $stream_id, $e) = @_;
3629 my $new_user = $user->clone;
3630 $new_user->clear_id;
3631 $new_user->stream($stream_id);
3633 $e->create_serial_routing_list_user($new_user) or return $e->die_event;
3634 return $e->data->id;
3637 __PACKAGE__->register_method(
3638 "method" => "clone_subscription",
3639 "api_name" => "open-ils.serial.subscription.clone",
3641 "desc" => q{Clone a subscription, including its attending distributions,
3642 streams, captions and patterns, routing list users, distribution
3643 notes and subscription notes. Do not include holdings-specific
3644 things, like issuances, items, units, summaries. Attach the
3645 clone either to the same bib record as the original, or to one
3648 {"desc" => "Authtoken", "type" => "string"},
3649 {"desc" => "Subscription ID", "type" => "number"},
3650 {"desc" => "Bib Record ID (optional)", "type" => "number"}
3653 "desc" => "ID of the new subscription", "type" => "number"
3658 sub clone_subscription {
3659 my ($self, $client, $auth, $sub_id, $bib_id) = @_;
3661 my $e = new_editor("authtoken" => $auth, "xact" => 1);
3662 return $e->die_event unless $e->checkauth;
3664 my $sub = $e->retrieve_serial_subscription([
3668 "ssub" => [qw/distributions notes scaps/],
3669 "sdist" => [qw/streams notes/],
3670 "sstr" => ["routing_list_users"]
3673 ]) or return $e->die_event;
3675 # ADMIN_SERIAL_SUBSCRIPTION will have to be good enough as a
3676 # catch-all permisison for this operation.
3677 return $e->die_event unless
3678 $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
3680 my $result = _clone_subscription($sub, $bib_id, $e);
3682 return $e->die_event($result) if $U->event_code($result);
3684 $e->commit or return $e->die_event;
3688 __PACKAGE__->register_method(
3689 "method" => "summary_test",
3690 "api_name" => "open-ils.serial.summary_test",
3696 # This crummy little test method allows quicker reproduction of certain
3697 # failures (e.g. at item receive time) of the holdings summarization code.
3698 # Pass it an authtoken, an array of issuance IDs, and a single sdist ID
3700 my ($self, $conn, $authtoken, $iss_id_list, $sdist_id) = @_;
3702 my $e = new_editor(authtoken => $authtoken, xact => 1);
3703 return $e->die_event unless $e->checkauth;
3704 return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
3707 foreach my $id (@$iss_id_list) {
3708 my $iss = $e->retrieve_serial_issuance($id) or return $e->die_event;
3709 push @issuances, $iss;
3712 my $dist = $e->retrieve_serial_distribution($sdist_id) or return $e->die_event;
3714 $conn->respond(_summarize_contents($e, \@issuances, $dist));