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(authtoken => $auth, 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 );
428 $logger->info("fleshed issuance-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
432 $logger->debug("issuance-alter: done updating issuance batch");
434 $logger->info("fleshed issuance-alter successfully updated ".scalar(@$issuances)." issuances");
439 my ($editor, $override, $issuance) = @_;
440 $logger->info("issuance-alter: delete issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
441 return $editor->event unless $editor->delete_serial_issuance($issuance);
446 my ($editor, $issuance) = @_;
448 $issuance->creator($editor->requestor->id);
449 $issuance->create_date('now');
451 $logger->info("issuance-alter: new issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
452 return $editor->event unless $editor->create_serial_issuance($issuance);
457 my ($editor, $override, $issuance) = @_;
459 $logger->info("issuance-alter: retrieving issuance ".$issuance->id);
460 my $orig_issuance = $editor->retrieve_serial_issuance($issuance->id);
462 $logger->info("issuance-alter: original issuance ".OpenSRF::Utils::JSON->perl2JSON($orig_issuance));
463 $logger->info("issuance-alter: updated issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
464 return $editor->event unless $editor->update_serial_issuance($issuance);
468 __PACKAGE__->register_method(
469 method => "fleshed_serial_issuance_retrieve_batch",
471 api_name => "open-ils.serial.issuance.fleshed.batch.retrieve"
474 sub fleshed_serial_issuance_retrieve_batch {
475 my( $self, $client, $ids ) = @_;
476 # FIXME: permissions?
477 $logger->info("Fetching fleshed serial issuances @$ids");
478 return $U->cstorereq(
479 "open-ils.cstore.direct.serial.issuance.search.atomic",
482 flesh_fields => {siss => [ qw/creator editor subscription/ ]}
486 __PACKAGE__->register_method(
487 method => "pub_fleshed_serial_issuance_retrieve_batch",
488 api_name => "open-ils.serial.issuance.pub_fleshed.batch.retrieve",
491 Public (i.e. OPAC) call for getting at the sub and
492 ultimately the record entry from an issuance
494 params => [{name => 'ids', desc => 'Array of IDs', type => 'array'}],
497 issuance objects, fleshed with subscriptions
503 sub pub_fleshed_serial_issuance_retrieve_batch {
504 my( $self, $client, $ids ) = @_;
505 return [] unless $ids and @$ids;
506 return new_editor()->search_serial_issuance([
510 flesh_fields => {siss => [ qw/subscription/ ]}
515 sub received_siss_by_bib {
516 # XXX this is somewhat wrong in implementation and should not be used in
517 # new places - senator
522 my $args = shift || {};
523 $$args{order} ||= 'asc';
525 my $global = $$args{global} == 0 ? 0 : 1;
527 my $e = new_editor();
528 my $issuances = $e->json_query({
531 $global ? { transform => "min", column => "id", aggregate => 1 } : "id",
536 # We're not really interested in the minimum here. This is
537 # just a way to distinguish issuances whose items have units
538 # from issuances whose items have no units, without altogether
539 # excluding the latter type of issuances.
540 {"transform" => "min", "alias" => "has_units",
541 "column" => "unit", "aggregate" => 1}
547 field => 'subscription',
553 $$args{ou} ? ( join => {
560 fkey => 'distribution'
571 '+ssub' => { record_entry => $bib },
572 $$args{type} ? ( '+siss' => { 'holding_type' => $$args{type} } ) : (),
574 # XXX should we also take specific item statuses into account?
575 date_received => { '!=' => undef },
576 $$args{status} ? ( 'status' => $$args{status} ) : ()
578 $$args{ou} ? ( '+sdist' => {
580 'in' => $U->get_org_descendants($$args{ou}, $$args{depth})
584 $$args{limit} ? ( limit => $$args{limit} ) : (),
585 $$args{offset} ? ( offset => $$args{offset} ) : (),
586 order_by => [{ class => 'siss', field => 'date_published', direction => $$args{order} }],
591 "issuance" => $e->retrieve_serial_issuance($_->{"id"}),
592 "has_units" => $_->{"has_units"} ? 1 : 0
597 __PACKAGE__->register_method(
598 method => 'received_siss_by_bib',
599 api_name => 'open-ils.serial.received_siss.retrieve.by_bib',
604 desc => 'Receives a Bib ID and other optional params and returns "siss" (issuance) objects',
607 desc => 'id of the bre to which the issuances belong',
612 q/A hash of optional arguments. Valid keys and their meanings:
613 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).
614 order := date_published sort direction, either "asc" (chronological, default) or "desc" (reverse chronological)
615 limit := Number of issuances to return. Useful for paging results, or finding the oldest or newest
616 offset := Number of issuance to skip before returning results. Useful for paging.
617 orgid := OU id used to scope retrieval, based on distribution.holding_lib
618 depth := OU depth used to range the scope of orgid
619 type := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
620 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).
628 sub scoped_bib_holdings_summary {
629 # XXX this is somewhat wrong in implementation and should not be used in
630 # new places - senator
634 my $args = shift || {};
636 $args->{order} = 'asc';
638 my ($issuances) = $self->method_lookup('open-ils.serial.received_siss.retrieve.by_bib.atomic')->run( $bibid => $args );
640 # split into issuance type sets
641 my %type_blob = (basic => [], supplement => [], index => []);
642 push @{ $type_blob{ $_->{"issuance"}->holding_type } }, $_->{"issuance"}
645 # generate a statement list for each type
647 for my $type ( keys %type_blob ) {
648 my ($mfhd,$list) = _summarize_contents(new_editor(), $type_blob{$type});
650 return {} if $U->event_code($mfhd); # _summarize_contents() failed, bad data?
652 $statement_blob{$type} = $list;
655 return \%statement_blob;
657 __PACKAGE__->register_method(
658 method => 'scoped_bib_holdings_summary',
659 api_name => 'open-ils.serial.bib.summary_statements',
663 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',
666 desc => 'id of the bre to which the issuances belong',
671 q/A hash of optional arguments. Valid keys and their meanings:
672 orgid := OU id used to scope retrieval, based on distribution.holding_lib
673 depth := OU depth used to range the scope of orgid
674 type := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
675 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).
683 ##########################################################################
686 __PACKAGE__->register_method(
687 method => 'fleshed_sunit_alter',
688 api_name => 'open-ils.serial.sunit.fleshed.batch.update',
692 desc => 'Receives an array of one or more Units and updates the database as needed',
695 desc => 'Authtoken for current user session',
700 desc => 'Array of fleshed Units',
706 desc => 'Returns 1 if successful, event if failed',
712 sub fleshed_sunit_alter {
713 my( $self, $conn, $auth, $sunits ) = @_;
714 return 1 unless ref $sunits;
715 my( $reqr, $evt ) = $U->checkses($auth);
717 my $editor = new_editor(requestor => $reqr, xact => 1);
718 my $override = $self->api_name =~ /override/;
721 for my $sunit (@$sunits) {
722 my $cn_id = ref $sunit->call_number ? $sunit->call_number->id : $sunit->call_number;
723 if (!exists($found_cn_ids{$cn_id})) {
725 if (ref $sunit->call_number) {
726 $owning_lib_id = $sunit->call_number->owning_lib;
728 my $cn = $editor->retrieve_asset_call_number($sunit->call_number) or return $editor->die_event;
729 $owning_lib_id = $cn->owning_lib;
731 return $editor->die_event unless
732 $editor->allowed("UPDATE_COPY", $owning_lib_id);
733 $found_cn_ids{$cn_id} = 1;
736 if( $sunit->isdeleted ) {
737 $evt = _delete_sunit( $editor, $override, $sunit );
739 $sunit->default_location( $sunit->default_location->id ) if ref $sunit->default_location;
741 if( $sunit->isnew ) {
742 $evt = _create_sunit( $editor, $sunit );
744 $evt = _update_sunit( $editor, $override, $sunit );
750 $logger->info("fleshed sunit-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
754 $logger->debug("sunit-alter: done updating sunit batch");
756 $logger->info("fleshed sunit-alter successfully updated ".scalar(@$sunits)." Units");
761 my ($editor, $override, $sunit) = @_;
762 $logger->info("sunit-alter: delete sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
763 return $editor->event unless $editor->delete_serial_unit($sunit);
768 my ($editor, $sunit) = @_;
770 # The unique barcode constraint does not span asset.copy and serial.unit.
771 # ensure the barcode on the new unit does not collide with an existing
772 # asset.copy barcode.
773 my $existing = $editor->search_asset_copy(
774 {deleted => 'f', barcode => $sunit->barcode})->[0];
777 # The DB will prevent duplicate serial.unit barcodes, but for
778 # consistency (and a more specific error message for the
779 # user), prevent creation attempts on serial unit barcode
780 # collisions as well.
781 $existing = $editor->search_serial_unit(
782 {deleted => 'f', barcode => $sunit->barcode})->[0];
787 return new OpenILS::Event(
788 'SERIAL_UNIT_BARCODE_COLLISION', note =>
789 'Serial unit barcode collides with existing unit/copy barcode',
790 payload => {barcode => $sunit->barcode}
794 $logger->info("sunit-alter: new Unit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
795 return $editor->die_event unless $editor->create_serial_unit($sunit);
800 my ($editor, $override, $sunit) = @_;
802 $logger->info("sunit-alter: retrieving sunit ".$sunit->id);
803 my $orig_sunit = $editor->retrieve_serial_unit($sunit->id);
805 $logger->info("sunit-alter: original sunit ".OpenSRF::Utils::JSON->perl2JSON($orig_sunit));
806 $logger->info("sunit-alter: updated sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
807 return $editor->event unless $editor->update_serial_unit($sunit);
811 __PACKAGE__->register_method(
812 method => "retrieve_unit_list",
814 api_name => "open-ils.serial.unit_list.retrieve"
817 sub retrieve_unit_list {
819 my( $self, $client, @sdist_ids ) = @_;
821 if(ref($sdist_ids[0])) { @sdist_ids = @{$sdist_ids[0]}; }
823 my $e = new_editor();
827 { 'sunit' => [ 'id', 'summary_contents', 'sort_key' ],
828 'sitem' => ['stream'],
829 'sstr' => ['distribution'],
830 'sdist' => [{'column' => 'label', 'alias' => 'sdist_label'}]
837 { 'join' => { 'sunit' => {} } }
842 'distinct' => 'true',
843 'where' => { '+sdist' => {'id' => \@sdist_ids} },
844 'order_by' => [{'class' => 'sunit', 'field' => 'sort_key'}]
847 my $unit_list_entries = $e->json_query($query);
850 foreach my $entry (@$unit_list_entries) {
851 my $value = {'sunit' => $entry->{id}, 'sstr' => $entry->{stream}, 'sdist' => $entry->{distribution}};
852 my $label = $entry->{summary_contents};
853 if (length($label) > 100) {
854 $label = substr($label, 0, 100) . '...'; # limited space in dropdown / menu
856 $label = "[$entry->{sdist_label}/$entry->{stream} #$entry->{id}] " . $label;
857 push (@entries, [$label, OpenSRF::Utils::JSON->perl2JSON($value)]);
865 ##########################################################################
866 # predict and receive methods
868 __PACKAGE__->register_method(
869 method => 'make_predictions',
870 api_name => 'open-ils.serial.make_predictions',
874 desc => 'Receives an ssub id and populates the issuance and item tables',
877 desc => 'Serial Subscription ID',
884 sub make_predictions {
885 my ($self, $conn, $authtoken, $args) = @_;
887 my $editor = OpenILS::Utils::CStoreEditor->new();
888 my $ssub_id = $args->{ssub_id};
889 my $mfhd = MFHD->new(MARC::Record->new());
891 my $ssub = $editor->retrieve_serial_subscription([$ssub_id]);
892 my $scaps = $editor->search_serial_caption_and_pattern({ subscription => $ssub_id, active => 't'});
893 my $sdists = $editor->search_serial_distribution( [{ subscription => $ssub->id }, { flesh => 1, flesh_fields => {sdist => [ qw/ streams / ]} }] ); #TODO: 'deleted' support?
895 my $total_streams = 0;
897 $total_streams += scalar(@{$_->streams});
899 if ($total_streams < 1) {
901 # XXX TODO new event type
902 return new OpenILS::Event(
903 "BAD_PARAMS", note =>
904 "There are no streams to direct items. Can't predict."
910 # XXX TODO new event type
911 return new OpenILS::Event(
912 "BAD_PARAMS", note =>
913 "There are no active caption-and-pattern objects associated " .
914 "with this subscription. Can't predict."
920 foreach my $scap (@$scaps) {
921 my $caption_field = _revive_caption($scap);
922 $caption_field->update('8' => $link_id);
923 my $fake_chron_needed = 0;
924 # if we have missing chron pieces, we will add them later for prediction purposes
925 if (!$caption_field->enumeration_is_chronology) {
926 if (!$caption_field->subfield('i') # no year
927 or !$caption_field->subfield('j')) { # we had a year, but no month or season
928 $fake_chron_needed = '1';
931 $mfhd->append_fields($caption_field);
933 'caption' => $caption_field,
934 'scap_id' => $scap->id,
935 'num_to_predict' => $args->{num_to_predict},
936 'end_date' => defined $args->{end_date} ?
937 $_strp_date->parse_datetime($args->{end_date}) : undef
939 my $predict_from_siss;
940 if ($args->{base_issuance}) { # predict from a given issuance
941 $predict_from_siss = $args->{base_issuance}->holding_code;
942 } else { # default to predicting from last published
943 my $last_published = $editor->search_serial_issuance([
944 {'caption_and_pattern' => $scap->id,
945 'subscription' => $ssub_id},
946 {limit => 1, order_by => { siss => "date_published DESC" }}]
948 if ($last_published->[0]) {
949 $predict_from_siss = $last_published->[0];
950 unless ($predict_from_siss->holding_code) {
952 # XXX TODO new event type
953 return new OpenILS::Event(
954 "BAD_PARAMS", note =>
955 "Last issuance has no holding code. Can't predict."
960 # XXX TODO make a new event type instead of hijacking this one
961 return new OpenILS::Event(
962 "BAD_PARAMS", note => "No issuance from which to predict!"
966 $options->{predict_from} = _revive_holding($predict_from_siss->holding_code, $caption_field, 1); # fresh MFHD Record, so we simply default to 1 for seqno
967 if ($fake_chron_needed) {
968 $options->{faked_chron_date} = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($predict_from_siss->date_published));
970 push( @predictions, _generate_issuance_values($mfhd, $options) );
975 foreach my $prediction (@predictions) {
976 my $issuance = new Fieldmapper::serial::issuance;
978 $issuance->label($prediction->{label});
979 $issuance->date_published($prediction->{date_published}->strftime('%F'));
980 $issuance->holding_code(OpenSRF::Utils::JSON->perl2JSON($prediction->{holding_code}));
981 $issuance->holding_type($prediction->{holding_type});
982 $issuance->caption_and_pattern($prediction->{caption_and_pattern});
983 $issuance->subscription($ssub->id);
984 push (@issuances, $issuance);
987 my $evt = fleshed_issuance_alter($self, $conn, $authtoken, \@issuances);
988 return $evt if ref $evt;
991 for (my $i = 0; $i < @issuances; $i++) {
992 my $date_expected = $predictions[$i]->{date_published}->add(seconds => interval_to_seconds($ssub->expected_date_offset))->strftime('%F');
993 my $issuance = $issuances[$i];
994 #$issuance->label(interval_to_seconds($ssub->expected_date_offset));
995 foreach my $sdist (@$sdists) {
996 my $streams = $sdist->streams;
997 foreach my $stream (@$streams) {
998 my $item = new Fieldmapper::serial::item;
1000 $item->stream($stream->id);
1001 $item->date_expected($date_expected);
1002 $item->issuance($issuance->id);
1003 push (@items, $item);
1007 fleshed_item_alter($self, $conn, $authtoken, \@items); # FIXME: catch events
1012 # _generate_issuance_values() is an initial attempt at a function which can be used
1013 # to populate an issuance table with a list of predicted issues. It accepts
1014 # a hash ref of options initially defined as:
1015 # caption : the caption field to predict on
1016 # num_to_predict : the number of issues you wish to predict
1017 # 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
1019 # The basic method is to first convert to a single holding if compressed, then
1020 # increment the holding and save the resulting values to @issuances.
1022 # returns @issuance_values, an array of hashrefs containing (formatted
1023 # label, formatted chronology date, formatted estimated arrival date, and an
1024 # array ref of holding subfields as (key, value, key, value ...)) (not a hash
1025 # to protect order and possible duplicate keys), and a holding type.
1027 sub _generate_issuance_values {
1028 my ($mfhd, $options) = @_;
1029 my $caption = $options->{caption};
1030 my $scap_id = $options->{scap_id};
1031 my $num_to_predict = $options->{num_to_predict};
1032 my $end_date = $options->{end_date};
1033 my $predict_from = $options->{predict_from}; # MFHD::Holding to predict from
1034 my $faked_chron_date = $options->{faked_chron_date}; # serial does not have a (complete) chronology caption, so add one (temporarily) based on this date
1037 # Only needed for 'real' MFHD records, not our temp records
1038 # my $link_id = $caption->link_id;
1039 # if(!$predict_from) {
1040 # my $htag = $caption->tag;
1041 # $htag =~ s/^85/86/;
1042 # my @holdings = $mfhd->holdings($htag, $link_id);
1043 # my $last_holding = $holdings[-1];
1045 # #if ($last_holding->is_compressed) {
1046 # # $last_holding->compressed_to_last; # convert to last in range
1048 # $predict_from = $last_holding;
1052 $predict_from->notes('public', []);
1053 # add a note marker for system use (?)
1054 $predict_from->notes('private', ['AUTOGEN']);
1056 # our basic method for dealing with 'faked' chronologies will be to add it in, do the predicting, then take it back out
1057 my @faked_subfield_chars;
1058 if ($faked_chron_date) {
1059 my $faked_caption = new MARC::Field($caption->tag, $caption->indicator(1), $caption->indicator(2), $caption->subfields_list);
1061 my %mfhd_chron_labels = ('i' => 'year', 'j' => 'month', 'k' => 'day');
1062 foreach my $subfield_char ('i', 'j', 'k') {
1063 if (!$caption->subfield($subfield_char)) { # if we are missing a piece, add it
1064 push(@faked_subfield_chars, $subfield_char);
1065 my $chron_name = $mfhd_chron_labels{$subfield_char};
1066 $faked_caption->add_subfields($subfield_char => "($chron_name)");
1067 my $method = $mfhd_chron_labels{$subfield_char};
1068 $predict_from->add_subfields($subfield_char => $faked_chron_date->$chron_name);
1071 # because of the way MFHD::Caption and Holding work, it is simplest
1072 # to recreate rather than try to update
1073 $faked_caption = new MFHD::Caption($faked_caption);
1074 $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);
1077 my @predictions = $mfhd->generate_predictions({'base_holding' => $predict_from, 'num_to_predict' => $num_to_predict, 'end_date' => $end_date});
1080 my @issuance_values;
1081 foreach my $prediction (@predictions) {
1082 $pub_date = $_strp_date->parse_datetime($prediction->chron_to_date);
1083 if ($faked_chron_date) { # get rid of the chronology portions and restore original caption
1084 $prediction->delete_subfield(code => \@faked_subfield_chars);
1085 $prediction = new MFHD::Holding($prediction->seqno, new MARC::Field($prediction->tag, $prediction->indicator(1), $prediction->indicator(2), $prediction->subfields_list), $caption);
1091 label => $prediction->format,
1092 date_published => $pub_date,
1093 #date_expected => $date_expected->strftime('%F'),
1094 holding_code => [$prediction->indicator(1),$prediction->indicator(2),$prediction->subfields_list],
1095 holding_type => $MFHD_NAMES_BY_TAG{$caption->tag},
1096 caption_and_pattern => $scap_id
1101 return @issuance_values;
1104 sub _revive_caption {
1107 my $pattern_code = $scap->pattern_code;
1110 my $pattern_parts = OpenSRF::Utils::JSON->JSON2perl($pattern_code);
1111 unshift(@$pattern_parts, $MFHD_TAGS_BY_NAME{$scap->type});
1112 my $pattern_field = new MARC::Field(@$pattern_parts);
1114 # build MFHD::Caption
1115 return new MFHD::Caption($pattern_field);
1118 sub _revive_holding {
1119 my $holding_code = shift;
1120 my $caption_field = shift;
1124 my $holding_parts = OpenSRF::Utils::JSON->JSON2perl($holding_code);
1125 my $captag = $caption_field->tag;
1126 $captag =~ s/^85/86/;
1127 unshift(@$holding_parts, $captag);
1128 my $holding_field = new MARC::Field(@$holding_parts);
1130 # build MFHD::Holding
1131 return new MFHD::Holding($seqno, $holding_field, $caption_field);
1133 # TODO(?) the underlying MARC and the Holding object end up in conflict concerning subfield '8'
1136 __PACKAGE__->register_method(
1137 method => 'unitize_items',
1138 api_name => 'open-ils.serial.receive_items',
1142 desc => 'Marks an item as received, updates the shelving unit (creating a new shelving unit if needed), and updates the summaries',
1145 desc => 'array of serial items',
1150 desc => 'hash of item_ids => barcodes',
1154 name => 'call_numbers',
1155 desc => 'hash of item_ids => call_numbers',
1159 name => 'donor_unit_ids',
1160 desc => 'hash of unit_ids => 1, keyed with ids of any units giving up items',
1165 desc => 'Returns number of received items (num_items) and new unit ID, if applicable (new_unit_id)',
1171 __PACKAGE__->register_method(
1172 method => 'unitize_items',
1173 api_name => 'open-ils.serial.bind_items',
1177 desc => 'Marks an item as bound, updates the shelving unit (creating a new shelving unit if needed)',
1180 desc => 'array of serial items',
1185 desc => 'hash of item_ids => barcodes',
1189 name => 'call_numbers',
1190 desc => 'hash of item_ids => call_numbers',
1194 name => 'donor_unit_ids',
1195 desc => 'hash of unit_ids => 1, keyed with ids of any units giving up items',
1200 desc => 'Returns number of bound items (num_items) and new unit ID, if applicable (new_unit_id)',
1206 # TODO: reset/delete claims information once implemented
1207 # XXX: deal with emptied call numbers here?
1208 __PACKAGE__->register_method(
1209 method => 'unitize_items',
1210 api_name => 'open-ils.serial.reset_items',
1214 desc => 'Resets the items to Expected, updates the shelving unit (deleting the shelving unit if empty), and updates the summaries',
1217 desc => 'array of serial items',
1222 desc => 'Returns number of reset items (num_items)',
1229 my ($self, $conn, $auth, $items, $barcodes, $call_numbers, $donor_unit_ids) = @_;
1231 my $editor = new_editor("authtoken" => $auth, "xact" => 1);
1232 return $editor->die_event unless $editor->checkauth;
1233 return $editor->die_event unless $editor->allowed("RECEIVE_SERIAL");
1234 $self->api_name =~ /serial\.(\w*)_items/;
1238 if ($donor_unit_ids) { # units giving up items need updating as well
1239 %found_unit_ids = %$donor_unit_ids;
1241 my %found_stream_ids;
1244 my %stream_ids_by_unit_id;
1247 my %sdist_by_unit_id;
1248 my %call_number_by_unit_id;
1249 my %sdist_by_stream_id;
1251 my $new_unit_id; # id for '-2' units to share
1252 foreach my $item (@$items) {
1253 # for debugging only, TODO: delete
1254 if (!ref $item) { # hopefully we got an id instead
1255 $item = $editor->retrieve_serial_item($item);
1258 my $unit_id = ref($item->unit) ? $item->unit->id : $item->unit;
1259 my $stream_id = ref($item->stream) ? $item->stream->id : $item->stream;
1260 my $issuance_id = ref($item->issuance) ? $item->issuance->id : $item->issuance;
1261 #TODO: evt on any missing ids
1263 if ($mode eq 'receive') {
1264 $item->date_received('now');
1265 $item->status('Received');
1266 } elsif ($mode eq 'reset') {
1267 # clear date_received
1268 $item->clear_date_received;
1269 # Set status to 'Expected'
1270 $item->status('Expected');
1275 # check for types to trigger summary updates
1277 if (!ref $item->issuance) {
1278 my $scaps = $editor->search_serial_caption_and_pattern([{"+siss" => {"id" => $issuance_id}}, { "join" => {"siss" => {}} }]);
1279 $scap = $scaps->[0];
1280 } elsif (!ref $item->issuance->caption_and_pattern) {
1281 $scap = $editor->retrieve_serial_caption_and_pattern($item->issuance->caption_and_pattern);
1283 $scap = $editor->issuance->caption_and_pattern;
1285 if (!exists($found_types{$stream_id})) {
1286 $found_types{$stream_id} = {};
1288 $found_types{$stream_id}->{$scap->type} = 1;
1290 # create unit if needed
1291 if ($unit_id == -1 or (!$new_unit_id and $unit_id == -2)) { # create unit per item
1293 my $sdists = $editor->search_serial_distribution([
1294 {"+sstr" => {"id" => $stream_id}},
1296 "join" => {"sstr" => {}},
1298 "flesh_fields" => {"sdist" => ["subscription"]}
1300 $unit = _build_unit($editor, $sdists->[0], $mode);
1301 # if _build_unit fails, $unit is an event, so return it
1302 if ($U->event_code($unit)) {
1304 $unit->{"note"} = "Item ID: " . $item->id;
1307 $unit->barcode($barcodes->{$item->id}) if exists($barcodes->{$item->id});
1308 my $evt = _create_sunit($editor, $unit);
1309 return $evt if $evt;
1310 if ($unit_id == -2) {
1311 $new_unit_id = $unit->id;
1312 $unit_id = $new_unit_id;
1314 $unit_id = $unit->id;
1316 $item->unit($unit_id);
1318 # get unit with 'DEFAULT's and save unit, sdist, and call number for later use
1319 $unit = $editor->retrieve_serial_unit($unit->id);
1320 $unit_map{$unit_id} = $unit;
1321 $sdist_by_unit_id{$unit_id} = $sdists->[0];
1322 $call_number_by_unit_id{$unit_id} = $call_numbers->{$item->id};
1323 $sdist_by_stream_id{$stream_id} = $sdists->[0];
1324 } elsif ($unit_id == -2) { # create one unit for all '-2' items
1325 $unit_id = $new_unit_id;
1326 $item->unit($unit_id);
1329 $found_stream_ids{$stream_id} = 1;
1331 if (defined($unit_id) and $unit_id ne '') {
1332 $found_unit_ids{$unit_id} = 1;
1333 # save the stream_id for this unit_id
1334 # TODO: prevent items from different streams in same unit? (perhaps in interface)
1335 $stream_ids_by_unit_id{$unit_id} = $stream_id;
1340 my $evt = _update_sitem($editor, undef, $item);
1341 return $evt if $evt;
1344 # cleanup 'dead' units (units which are now emptied of their items)
1345 my $dead_units = $editor->search_serial_unit([{'+sitem' => {'id' => undef}, 'deleted' => 'f'}, {'join' => {'sitem' => {'type' => 'left'}}}]);
1346 foreach my $unit (@$dead_units) {
1347 _delete_sunit($editor, undef, $unit);
1348 delete $found_unit_ids{$unit->id};
1351 # deal with unit level contents
1352 foreach my $unit_id (keys %found_unit_ids) {
1354 # get all the needed issuances for unit
1355 # TODO remove 'Bindery' from this search (leaving it in for now for backwards compatibility with any current test environment data)
1356 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"unit" => $unit_id, "status" => ["Received", "Bindery"]}}, {"join" => {"sitem" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1357 #TODO: evt on search failure
1359 # retrieve and update unit contents
1362 my $call_number_string;
1364 # if we just created the unit, we will already have it and the distribution stored, and we will need to assign the call number
1365 if (exists $unit_map{$unit_id}) {
1366 $sunit = $unit_map{$unit_id};
1367 $sdist = $sdist_by_unit_id{$unit_id};
1368 $call_number_string = $call_number_by_unit_id{$unit_id};
1369 $record_id = $sdist->subscription->record_entry;
1371 # XXX: this code assumes you will not have units which mix streams/distributions, but current code does not enforce this
1372 $sunit = $editor->retrieve_serial_unit($unit_id);
1373 if ($stream_ids_by_unit_id{$unit_id}) {
1374 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_ids_by_unit_id{$unit_id}}}, { "join" => {"sstr" => {}}, 'limit' => 1 }]);
1376 $sdist = $editor->search_serial_distribution([
1377 {'+sunit' => {'id' => $unit_id}},
1382 { 'join' => 'sunit' }
1389 $sdist = $sdist->[0];
1392 my $evt = _prepare_unit($editor, $sunit, $sdist, $issuances, $call_number_string, $record_id);
1393 if ($U->event_code($evt)) {
1398 $evt = _update_sunit($editor, undef, $sunit);
1399 if ($U->event_code($evt)) {
1405 if ($mode ne 'bind') { # the summary holdings do not change when binding
1406 # deal with stream level summaries
1407 # summaries will be built from the "primary" stream only, that is, the stream with the lowest ID per distribution
1408 # (TODO: consider direct designation)
1409 my %primary_streams_by_sdist;
1410 my %streams_by_sdist;
1412 # see if we have primary streams, and if so, associate them with their distributions
1413 foreach my $stream_id (keys %found_stream_ids) {
1415 if (exists $sdist_by_stream_id{$stream_id}) {
1416 $sdist = $sdist_by_stream_id{$stream_id};
1418 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
1419 $sdist = $sdist->[0];
1420 $sdist_by_stream_id{$stream_id} = $sdist;
1423 if (!exists($streams_by_sdist{$sdist->id})) {
1424 $streams = $editor->search_serial_stream([{"distribution" => $sdist->id}, {"order_by" => {"sstr" => "id"}}]);
1425 $streams_by_sdist{$sdist->id} = $streams;
1427 $streams = $streams_by_sdist{$sdist->id};
1429 $primary_streams_by_sdist{$sdist->id} = $streams->[0] if ($stream_id == $streams->[0]->id);
1432 # retrieve and update summaries for each affected primary stream's distribution
1433 foreach my $sdist_id (keys %primary_streams_by_sdist) {
1434 my $stream = $primary_streams_by_sdist{$sdist_id};
1435 my $stream_id = $stream->id;
1436 # get all the needed issuances for stream
1437 # FIXME: search in Bindery/Bound/Not Published? as well as Received
1438 foreach my $type (keys %{$found_types{$stream_id}}) {
1439 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"stream" => $stream_id, "status" => "Received"}, "+scap" => {"type" => $type}}, {"join" => {"sitem" => {}, "scap" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1440 #TODO: evt on search failure
1441 my $evt = _prepare_summaries($editor, $issuances, $sdist_by_stream_id{$stream_id}, $type);
1442 if ($U->event_code($evt)) {
1451 return {'num_items' => scalar @$items, 'new_unit_id' => $new_unit_id};
1454 sub _find_or_create_call_number {
1455 my ($e, $lib, $cn_string, $record) = @_;
1457 # FIXME: should suffix and prefix come into play here?
1458 my $existing = $e->search_asset_call_number({
1459 "owning_lib" => $lib,
1460 "label" => $cn_string,
1461 "record" => $record,
1463 }) or return $e->die_event;
1466 return $existing->[0]->id;
1468 return $e->die_event unless
1469 $e->allowed("CREATE_VOLUME", $lib);
1471 my $acn = new Fieldmapper::asset::call_number;
1473 $acn->creator($e->requestor->id);
1474 $acn->editor($e->requestor->id);
1475 $acn->record($record);
1476 $acn->label($cn_string);
1477 $acn->owning_lib($lib);
1479 $e->create_asset_call_number($acn) or return $e->die_event;
1480 return $e->data->id;
1484 sub _issuances_received {
1485 # XXX TODO: Add some caching or something. This is getting called
1486 # more often than it has to be.
1487 my ($e, $sitem) = @_;
1489 my $results = $e->json_query({
1490 "select" => {"sitem" => ["issuance"]},
1491 "from" => {"sitem" => {"sstr" => {}, "siss" => {}}},
1493 "+sstr" => {"distribution" => $sitem->stream->distribution->id},
1494 "+siss" => {"holding_type" => $sitem->issuance->holding_type},
1495 "+sitem" => {"date_received" => {"!=" => undef}}
1498 "siss" => {"date_published" => {"direction" => "asc"}}
1500 }) or return $e->die_event;
1504 for my $iss_id (map { $_->{"issuance"} } @$results) {
1505 next if $seen{$iss_id};
1507 push(@$issuances, $e->retrieve_serial_issuance($iss_id));
1512 # _prepare_unit populates the detailed_contents, summary_contents, and
1513 # sort_key fields for a given unit based on a given set of issuances
1514 # Also finds/creates call number as needed
1516 my ($e, $sunit, $sdist, $issuances, $call_number_string, $record_id) = @_;
1518 # Handle call number first if we have one
1519 if ($call_number_string) {
1520 my $org_unit_id = ref $sdist->holding_lib ? $sdist->holding_lib->id : $sdist->holding_lib;
1521 my $real_cn = _find_or_create_call_number(
1523 $call_number_string, $record_id
1526 if ($U->event_code($real_cn)) {
1529 $sunit->call_number($real_cn);
1533 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances);
1534 return $mfhd if $U->event_code($mfhd);
1536 # special case for single formatted_part (may have summarized version)
1537 if (@$formatted_parts == 1) {
1538 #TODO: MFHD.pm should have a 'format_summary' method for this
1541 $sunit->detailed_contents(
1544 $sdist->unit_label_prefix,
1545 join(", ", @$formatted_parts),
1546 $sdist->unit_label_suffix
1550 # TODO: change this when real summary contents are available
1551 $sunit->summary_contents($sunit->detailed_contents);
1553 # Create sort_key by left padding numbers to 6 digits.
1554 (my $sort_key = $sunit->detailed_contents) =~
1555 s/(\d+)/sprintf '%06d', $1/eg;
1556 $sunit->sort_key($sort_key);
1559 # _prepare_summaries populates the generated_coverage field for a given summary
1560 # type ('basic', 'index', 'supplement') for a given distribution.
1561 # It also creates the summary if it doesn't yet exist.
1562 sub _prepare_summaries {
1563 my ($e, $issuances, $sdist, $type) = @_;
1565 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances, $sdist, $type);
1566 return $mfhd if $U->event_code($mfhd);
1568 my $search_method = "search_serial_${type}_summary";
1569 my $summary = $e->$search_method([{"distribution" => $sdist->id}]);
1571 my $cu_method = "update";
1574 $summary = $summary->[0];
1576 my $class = "Fieldmapper::serial::${type}_summary";
1577 $summary = $class->new;
1578 $summary->distribution($sdist->id);
1579 $cu_method = "create";
1582 if (@$formatted_parts) {
1583 $summary->generated_coverage(OpenSRF::Utils::JSON->perl2JSON($formatted_parts));
1585 # we had no issuances or MFHD data for this type, so clear any
1586 # generated data which may have existed before
1587 $summary->generated_coverage('');
1589 my $method = "${cu_method}_serial_${type}_summary";
1590 return $e->die_event unless $e->$method($summary);
1593 sub _unit_by_iss_and_str {
1594 my ($e, $issuance, $stream) = @_;
1596 my $unit = $e->json_query({
1597 "select" => {"sunit" => ["id"]},
1598 "from" => {"sitem" => {"sunit" => {}}},
1601 "issuance" => $issuance->id,
1602 "stream" => $stream->id
1605 }) or return $e->die_event;
1606 return 0 if not @$unit;
1608 $e->retrieve_serial_unit($unit->[0]->{"id"}) or $e->die_event;
1611 sub move_previous_unit {
1612 my ($e, $prev_iss, $curr_item, $new_loc) = @_;
1614 my $prev_unit = _unit_by_iss_and_str($e,$prev_iss,$curr_item->stream);
1615 return $prev_unit if defined $U->event_code($prev_unit);
1616 return 0 if not $prev_unit;
1618 if ($prev_unit->location != $new_loc) {
1619 $prev_unit->location($new_loc);
1620 $e->update_serial_unit($prev_unit) or return $e->die_event;
1625 # _previous_issuance() assumes $existing is an ordered array
1626 sub _previous_issuance {
1627 my ($existing, $issuance) = @_;
1629 my $last = $existing->[-1];
1630 return undef unless $last;
1631 return ($last->id == $issuance->id ? $existing->[-2] : $last);
1634 __PACKAGE__->register_method(
1635 "method" => "receive_items_one_unit_per",
1636 "api_name" => "open-ils.serial.receive_items.one_unit_per",
1641 "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",
1645 "desc" => "authtoken",
1650 "desc" => "array of serial items, possibly fleshed with units and definitely fleshed with stream->distribution",
1655 "desc" => "id of bib record these items are associated with
1656 (XXX could/should be derived from items)",
1661 "desc" => "The item ID for each item successfully received",
1667 sub receive_items_one_unit_per {
1668 # XXX This function may be temporary, as it does some of what
1669 # unitize_items() does, just in a different way.
1670 my ($self, $client, $auth, $items, $record) = @_;
1672 my $e = new_editor("authtoken" => $auth, "xact" => 1);
1673 return $e->die_event unless $e->checkauth;
1674 return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
1676 my $prev_loc_setting_map = {};
1677 my $user_id = $e->requestor->id;
1679 # Get a list of all the non-virtual field names in a serial::unit for
1680 # merging given unit objects with template-built units later.
1681 # XXX move this somewhere global so it isn't re-run all the time
1682 my $all_unit_fields =
1683 $Fieldmapper::fieldmap->{"Fieldmapper::serial::unit"}->{"fields"};
1684 my @real_unit_fields = grep {
1685 not $all_unit_fields->{$_}->{"virtual"}
1686 } keys %$all_unit_fields;
1688 foreach my $item (@$items) {
1689 # Note that we expect a certain fleshing on the items we're getting.
1690 my $sdist = $item->stream->distribution;
1692 # Fetch a list of issuances with received copies already existing
1693 # on this distribution (and with the same holding type on the
1694 # issuance). This will be used in up to two places: once when building
1695 # a summary, once when changing the copy location of the previous
1697 my $issuances_received = _issuances_received($e, $item);
1698 if ($U->event_code($issuances_received)) {
1700 return $issuances_received;
1703 # Find out if we need to to deal with previous copy location changing.
1704 my $ou = $sdist->holding_lib->id;
1705 unless (exists $prev_loc_setting_map->{$ou}) {
1706 $prev_loc_setting_map->{$ou} = $U->ou_ancestor_setting_value(
1707 $ou, "serial.prev_issuance_copy_location", $e
1711 # If there is a previous copy location setting, we need the previous
1712 # issuance, from which we can in turn look up the item attached to the
1713 # same stream we're on now.
1714 if ($prev_loc_setting_map->{$ou}) {
1716 _previous_issuance($issuances_received, $item->issuance)) {
1718 # Now we can change the copy location of the previous unit,
1720 return $e->event if defined $U->event_code(
1722 $e, $prev_iss, $item, $prev_loc_setting_map->{$ou}
1728 # Create unit if given by user
1729 if (ref $item->unit) {
1730 # detach from the item, as we need to create separately
1731 my $user_unit = $item->unit;
1733 # get a unit based on associated template
1734 my $template_unit = _build_unit($e, $sdist, "receive");
1735 if ($U->event_code($template_unit)) {
1737 $template_unit->{"note"} = "Item ID: " . $item->id;
1738 return $template_unit;
1741 # merge built unit with provided unit from user
1742 foreach (@real_unit_fields) {
1743 unless ($user_unit->$_) {
1744 $user_unit->$_($template_unit->$_);
1748 # Treat call number specially: the provided value from the
1749 # user will really be a string.
1750 my $call_number_string;
1751 if ($user_unit->call_number) {
1752 $call_number_string = $user_unit->call_number;
1753 # clear call number for now (replaced in _prepare_unit)
1754 $user_unit->clear_call_number;
1757 my $evt = _prepare_unit(
1758 $e, $user_unit, $sdist, [$item->issuance],
1759 $call_number_string, $record
1761 if ($U->event_code($evt)) {
1766 # create/update summary objects related to this distribution
1767 # Make sure @$issuances_received contains current item's issuance
1768 unless (grep { $_->id == $item->issuance->id } @$issuances_received) {
1769 push @$issuances_received, $item->issuance;
1771 $evt = _prepare_summaries($e, $issuances_received, $item->stream->distribution, $item->issuance->holding_type);
1772 if ($U->event_code($evt)) {
1777 # set the incontrovertibles on the unit
1778 $user_unit->edit_date("now");
1779 $user_unit->create_date("now");
1780 $user_unit->editor($user_id);
1781 $user_unit->creator($user_id);
1783 $evt = _create_sunit($e, $user_unit);
1784 return $evt if $evt;
1786 # save reference to new unit
1787 $item->unit($e->data->id);
1790 # Create notes if given by user
1791 if (ref($item->notes) and @{$item->notes}) {
1792 foreach my $note (@{$item->notes}) {
1793 $note->creator($user_id);
1794 $note->create_date("now");
1796 return $e->die_event unless $e->create_serial_item_note($note);
1799 $item->clear_notes; # They're saved; we no longer want them here.
1802 # Set the incontrovertibles on the item
1803 $item->status("Received");
1804 $item->date_received("now");
1805 $item->edit_date("now");
1806 $item->editor($user_id);
1808 return $e->die_event unless $e->update_serial_item($item);
1810 # send client a response
1811 $client->respond($item->id);
1814 $e->commit or return $e->die_event;
1822 #my $skip_call_number = shift;
1824 my $attr = $mode . '_unit_template';
1825 my $template = $editor->retrieve_asset_copy_template($sdist->$attr) or
1826 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_COPY_TEMPLATE");
1828 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 );
1830 my $unit = new Fieldmapper::serial::unit;
1831 foreach my $part (@parts) {
1832 my $value = $template->$part;
1833 next if !defined($value);
1834 $unit->$part($value);
1837 # ignore circ_lib in template, set to distribution holding_lib
1838 $unit->circ_lib($sdist->holding_lib);
1839 $unit->creator($editor->requestor->id);
1840 $unit->editor($editor->requestor->id);
1842 # XXX: this feature has been pushed back until after 2.0 at least
1843 # unless ($skip_call_number) {
1844 # $attr = $mode . '_call_number';
1845 # my $cn = $sdist->$attr or
1846 # return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_CALL_NUMBER");
1848 # $unit->call_number($cn);
1850 $unit->call_number('-1'); # default to the dummy call number
1851 $unit->barcode('@@PLACEHOLDER'); # generic unit will start with a generated placeholder barcode
1852 $unit->sort_key('');
1853 $unit->summary_contents('');
1854 $unit->detailed_contents('');
1859 sub _summarize_contents {
1861 my $issuances = shift;
1865 # create or lookup MFHD record
1867 if ($sdist and defined($sdist->record_entry) and $sdist->summary_method eq 'merge_with_sre') {
1869 if (ref $sdist->record_entry) {
1870 $sre = $sdist->record_entry;
1872 $sre = $editor->retrieve_serial_record_entry($sdist->record_entry);
1874 $mfhd = MFHD->new(MARC::Record->new_from_xml($sre->marc));
1876 $logger->info($sdist);
1877 $mfhd = MFHD->new(MARC::Record->new());
1883 # We keep track of these separately to avoid link_id contamination,
1884 # e.g. a basic issuance, followed by a merging supplement, followed by
1885 # another basic. If we could be sure that they were not mixed, one
1886 # value could suffice.
1887 my %link_ids = ('basic' => 10000, 'index' => 10000, 'supplement' => 10000);
1888 my %first_scap = ('basic' => 1, 'index' => 1, 'supplement' => 1);
1889 foreach my $issuance (@$issuances) {
1890 my $scap_id = $issuance->caption_and_pattern;
1891 next if (!$scap_id); # skip issuances with no caption/pattern
1895 # if this is the first appearance of this scap, retrieve it and add it to the temporary record
1896 if (!exists $scaps{$issuance->caption_and_pattern}) {
1897 $scaps{$scap_id} = $editor->retrieve_serial_caption_and_pattern($scap_id);
1898 $scap = $scaps{$scap_id};
1899 $scap_field = _revive_caption($scap);
1901 if ($first_scap{$scap->type}) { # special merge processing
1902 $first_scap{$MFHD_TAGS_BY_NAME{$scap->type}} = 0;
1903 if ($sdist and $sdist->summary_method eq 'merge_with_sre') {
1904 # MFHD Caption objects do not yet have a built-in compare (TODO), so let's do a basic one
1905 my @field_85xs = $mfhd->field($MFHD_TAGS_BY_NAME{$scap->type});
1907 my $last_caption_field = $field_85xs[-1];
1908 my $last_link_id = $last_caption_field->subfield('8');
1909 # set the link id to match, temporarily, for comparison
1910 $last_caption_field->update('8' => $scap_field->subfield('8'));
1911 my $last_caption_json = OpenSRF::Utils::JSON->perl2JSON([$last_caption_field->indicator(1), $last_caption_field->indicator(2), $last_caption_field->subfields_list]);
1912 if ($last_caption_json eq $scap->pattern_code) { # merge is possible, they match
1914 $link_ids{$scap->type} = $last_link_id;
1915 # set scap_field to last field
1916 $scap_field = $last_caption_field;
1922 $scap_fields{$scap_id} = $scap_field;
1923 $scap_field->update('8' => $link_ids{$scap->type});
1924 # TODO: make MFHD/Caption smarter about this
1925 $scap_field->{_mfhdc_LINK_ID} = $link_ids{$scap->type};
1926 $mfhd->append_fields($scap_field) if !$did_merge;
1927 $link_ids{$scap->type}++;
1929 $scap_field = $scap_fields{$scap_id};
1932 $mfhd->append_fields(_revive_holding($issuance->holding_code, $scap_field, $seqno));
1936 my @formatted_parts;
1937 my @scap_fields_ordered = $mfhd->field($MFHD_TAGS_BY_NAME{$type});
1939 foreach my $scap_field (@scap_fields_ordered) { #TODO: use generic MFHD "summarize" method, once available
1940 my @updated_holdings;
1942 @updated_holdings = $mfhd->get_combined_holdings($scap_field);
1945 my $msg = "get_combined_holdings(): $@ ; using sdist ID #" .
1946 ($sdist ? $sdist->id : "<NONE>") . " and " .
1947 scalar(@$issuances) . " issuances, of which one has ID #" .
1948 $issuances->[0]->id;
1951 $logger->error($msg);
1952 return new OpenILS::Event("BAD_PARAMS", note => $msg);
1955 push @formatted_parts, map { $_->format } @updated_holdings;
1958 return ($mfhd, \@formatted_parts);
1961 ##########################################################################
1964 __PACKAGE__->register_method(
1965 method => 'fetch_notes',
1966 api_name => 'open-ils.serial.item_note.retrieve.all',
1968 Returns an array of copy note objects.
1969 @param args A named hash of parameters including:
1970 authtoken : Required if viewing non-public notes
1971 item_id : The id of the item whose notes we want to retrieve
1972 pub : True if all the caller wants are public notes
1973 @return An array of note objects
1977 __PACKAGE__->register_method(
1978 method => 'fetch_notes',
1979 api_name => 'open-ils.serial.subscription_note.retrieve.all',
1981 Returns an array of copy note objects.
1982 @param args A named hash of parameters including:
1983 authtoken : Required if viewing non-public notes
1984 subscription_id : The id of the item whose notes we want to retrieve
1985 pub : True if all the caller wants are public notes
1986 @return An array of note objects
1990 __PACKAGE__->register_method(
1991 method => 'fetch_notes',
1992 api_name => 'open-ils.serial.distribution_note.retrieve.all',
1994 Returns an array of copy note objects.
1995 @param args A named hash of parameters including:
1996 authtoken : Required if viewing non-public notes
1997 distribution_id : The id of the item whose notes we want to retrieve
1998 pub : True if all the caller wants are public notes
1999 @return An array of note objects
2003 # TODO: revisit this method to consider replacing cstore direct calls
2005 my( $self, $connection, $args ) = @_;
2007 $self->api_name =~ /serial\.(\w*)_note/;
2010 my $id = $$args{object_id};
2011 my $authtoken = $$args{authtoken};
2012 my $order_by = $$args{order_by} || 'create_date';
2016 return $U->cstorereq(
2017 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic',
2018 { $type => $id, pub => 't' }, {'order_by' => {$FM_NAME_TO_ID{$type}.'n' => $order_by}} );
2020 # FIXME: restore perm check
2021 # ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
2022 # return $evt if $evt;
2023 return $U->cstorereq(
2024 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic', {$type => $id}, {'order_by' => {$FM_NAME_TO_ID{$type}.'n' => $order_by}} );
2030 __PACKAGE__->register_method(
2031 method => 'update_note',
2032 api_name => 'open-ils.serial.item_note.update',
2034 Updates or creates an item note
2035 @param authtoken The login session key
2036 @param note The note object to update or create
2037 @return The id of the note object
2041 __PACKAGE__->register_method(
2042 method => 'update_note',
2043 api_name => 'open-ils.serial.subscription_note.update',
2045 Updates or creates a subscription note
2046 @param authtoken The login session key
2047 @param note The note object to update or create
2048 @return The id of the note object
2052 __PACKAGE__->register_method(
2053 method => 'update_note',
2054 api_name => 'open-ils.serial.distribution_note.update',
2056 Updates or creates a distribution note
2057 @param authtoken The login session key
2058 @param note The note object to update or create
2059 @return The id of the note object
2064 my( $self, $connection, $authtoken, $note ) = @_;
2066 $self->api_name =~ /serial\.(\w*)_note/;
2069 my $e = new_editor(xact=>1, authtoken=>$authtoken);
2070 return $e->event unless $e->checkauth;
2072 if ($type eq 'item') {
2073 my $sitem = $e->retrieve_serial_item([
2075 "flesh" => 2, "flesh_fields" => {
2076 "sitem" => ["stream"], "sstr" => ["distribution"]
2079 ]) or return $e->die_event;
2081 return $e->die_event unless $e->allowed(
2082 "ADMIN_SERIAL_ITEM", $sitem->stream->distribution->holding_lib
2084 } elsif ($type eq 'distribution') {
2085 my $sdist = $e->retrieve_serial_distribution($note->distribution)
2086 or return $e->die_event;
2088 return $e->die_event unless
2089 $e->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2090 } else { # subscription
2091 my $sub = $e->retrieve_serial_subscription($note->subscription)
2092 or return $e->die_event;
2094 return $e->die_event unless
2095 $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
2098 $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
2101 $note->create_date('now');
2102 $note->creator($e->requestor->id);
2104 $method = "create_serial_${type}_note";
2106 $method = "update_serial_${type}_note";
2108 $e->$method($note) or return $e->event;
2113 __PACKAGE__->register_method(
2114 method => 'delete_note',
2115 api_name => 'open-ils.serial.item_note.delete',
2117 Deletes an existing item note
2118 @param authtoken The login session key
2119 @param noteid The id of the note to delete
2120 @return 1 on success - Event otherwise.
2124 __PACKAGE__->register_method(
2125 method => 'delete_note',
2126 api_name => 'open-ils.serial.subscription_note.delete',
2128 Deletes an existing subscription note
2129 @param authtoken The login session key
2130 @param noteid The id of the note to delete
2131 @return 1 on success - Event otherwise.
2135 __PACKAGE__->register_method(
2136 method => 'delete_note',
2137 api_name => 'open-ils.serial.distribution_note.delete',
2139 Deletes an existing distribution note
2140 @param authtoken The login session key
2141 @param noteid The id of the note to delete
2142 @return 1 on success - Event otherwise.
2147 my( $self, $conn, $authtoken, $noteid ) = @_;
2149 $self->api_name =~ /serial\.(\w*)_note/;
2152 my $e = new_editor(xact=>1, authtoken=>$authtoken);
2153 return $e->die_event unless $e->checkauth;
2155 my $method = "retrieve_serial_${type}_note";
2156 my $note = $e->$method([
2158 ]) or return $e->die_event;
2160 if ($type eq 'item') {
2161 my $sitem = $e->retrieve_serial_item([
2163 "flesh" => 2, "flesh_fields" => {
2164 "sitem" => ["stream"], "sstr" => ["distribution"]
2167 ]) or return $e->die_event;
2169 return $e->die_event unless $e->allowed(
2170 "ADMIN_SERIAL_ITEM", $sitem->stream->distribution->holding_lib
2172 } elsif ($type eq 'distribution') {
2173 my $sdist = $e->retrieve_serial_distribution($note->distribution)
2174 or return $e->die_event;
2176 return $e->die_event unless
2177 $e->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2178 } else { # subscription
2179 my $sub = $e->retrieve_serial_subscription($note->subscription)
2180 or return $e->die_event;
2182 return $e->die_event unless
2183 $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
2186 $method = "delete_serial_${type}_note";
2187 $e->$method($note) or return $e->die_event;
2193 ##########################################################################
2194 # subscription methods
2196 __PACKAGE__->register_method(
2197 method => 'fleshed_ssub_alter',
2198 api_name => 'open-ils.serial.subscription.fleshed.batch.update',
2202 desc => 'Receives an array of one or more subscriptions and updates the database as needed',
2204 name => 'authtoken',
2205 desc => 'Authtoken for current user session',
2209 name => 'subscriptions',
2210 desc => 'Array of fleshed subscriptions',
2216 desc => 'Returns 1 if successful, event if failed',
2222 sub fleshed_ssub_alter {
2223 my( $self, $conn, $auth, $ssubs ) = @_;
2224 return 1 unless ref $ssubs;
2225 my( $reqr, $evt ) = $U->checkses($auth);
2226 return $evt if $evt;
2227 my $editor = new_editor(requestor => $reqr, xact => 1);
2228 my $override = $self->api_name =~ /override/;
2230 for my $ssub (@$ssubs) {
2231 my $owning_lib_id = ref $ssub->owning_lib ? $ssub->owning_lib->id : $ssub->owning_lib;
2232 return $editor->die_event unless
2233 $editor->allowed("ADMIN_SERIAL_SUBSCRIPTION", $owning_lib_id);
2235 my $ssubid = $ssub->id;
2237 if( $ssub->isdeleted ) {
2238 $evt = _delete_ssub( $editor, $override, $ssub);
2239 } elsif( $ssub->isnew ) {
2240 _cleanse_dates($ssub, ['start_date','end_date']);
2241 $evt = _create_ssub( $editor, $ssub );
2243 _cleanse_dates($ssub, ['start_date','end_date']);
2244 $evt = _update_ssub( $editor, $override, $ssub );
2249 $logger->info("fleshed subscription-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2253 $logger->debug("subscription-alter: done updating subscription batch");
2255 $logger->info("fleshed subscription-alter successfully updated ".scalar(@$ssubs)." subscriptions");
2260 my ($editor, $override, $ssub) = @_;
2261 $logger->info("subscription-alter: delete subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2262 my $sdists = $editor->search_serial_distribution(
2263 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2264 my $cps = $editor->search_serial_caption_and_pattern(
2265 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2266 my $sisses = $editor->search_serial_issuance(
2267 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2268 return OpenILS::Event->new(
2269 'SERIAL_SUBSCRIPTION_NOT_EMPTY', payload => $ssub->id ) if (@$sdists or @$cps or @$sisses);
2271 return $editor->event unless $editor->delete_serial_subscription($ssub);
2276 my ($editor, $ssub) = @_;
2278 $logger->info("subscription-alter: new subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2279 return $editor->event unless $editor->create_serial_subscription($ssub);
2284 my ($editor, $override, $ssub) = @_;
2286 $logger->info("subscription-alter: retrieving subscription ".$ssub->id);
2287 my $orig_ssub = $editor->retrieve_serial_subscription($ssub->id);
2289 $logger->info("subscription-alter: original subscription ".OpenSRF::Utils::JSON->perl2JSON($orig_ssub));
2290 $logger->info("subscription-alter: updated subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2291 return $editor->event unless $editor->update_serial_subscription($ssub);
2295 __PACKAGE__->register_method(
2296 method => "fleshed_serial_subscription_retrieve_batch",
2298 api_name => "open-ils.serial.subscription.fleshed.batch.retrieve"
2301 sub fleshed_serial_subscription_retrieve_batch {
2302 my( $self, $client, $ids ) = @_;
2303 # FIXME: permissions?
2304 $logger->info("Fetching fleshed subscriptions @$ids");
2305 return $U->cstorereq(
2306 "open-ils.cstore.direct.serial.subscription.search.atomic",
2309 flesh_fields => {ssub => [ qw/owning_lib notes/ ]}
2313 __PACKAGE__->register_method(
2314 method => "retrieve_sub_tree",
2316 api_name => "open-ils.serial.subscription_tree.retrieve"
2319 __PACKAGE__->register_method(
2320 method => "retrieve_sub_tree",
2321 api_name => "open-ils.serial.subscription_tree.global.retrieve"
2324 sub retrieve_sub_tree {
2326 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2328 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2332 # TODO: permission support
2333 if(!@org_ids and $user_session) {
2335 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2336 @org_ids = ($user_obj->home_ou);
2339 if( $self->api_name =~ /global/ ) {
2340 return _build_subs_list( { record_entry => $docid } ); # TODO: filter for !deleted, or active?
2345 for my $orgid (@org_ids) {
2346 my $subs = _build_subs_list(
2347 { record_entry => $docid, owning_lib => $orgid } );# TODO: filter for !deleted, or active?
2348 push( @all_subs, @$subs );
2357 sub _build_subs_list {
2358 my $search_hash = shift;
2360 #$search_hash->{deleted} = 'f';
2361 my $e = new_editor();
2363 my $subs = $e->search_serial_subscription([$search_hash, { 'order_by' => {'ssub' => 'id'} }]);
2367 for my $sub (@$subs) {
2369 # TODO: filter on !deleted?
2370 my $dists = $e->search_serial_distribution(
2371 [{ subscription => $sub->id }, { 'order_by' => {'sdist' => 'label'} }]
2374 #$dists = [ sort { $a->label cmp $b->label } @$dists ];
2376 $sub->distributions($dists);
2378 # TODO: filter on !deleted?
2379 my $issuances = $e->search_serial_issuance(
2380 [{ subscription => $sub->id }, { 'order_by' => {'siss' => 'label'} }]
2383 #$issuances = [ sort { $a->label cmp $b->label } @$issuances ];
2384 $sub->issuances($issuances);
2386 # TODO: filter on !deleted?
2387 my $scaps = $e->search_serial_caption_and_pattern(
2388 [{ subscription => $sub->id }, { 'order_by' => {'scap' => 'id'} }]
2391 #$scaps = [ sort { $a->id cmp $b->id } @$scaps ];
2392 $sub->scaps($scaps);
2393 push( @built_subs, $sub );
2396 return \@built_subs;
2400 __PACKAGE__->register_method(
2401 method => "subscription_orgs_for_title",
2403 api_name => "open-ils.serial.subscription.retrieve_orgs_by_title"
2406 sub subscription_orgs_for_title {
2407 my( $self, $client, $record_id ) = @_;
2409 my $subs = $U->simple_scalar_request(
2411 "open-ils.cstore.direct.serial.subscription.search.atomic",
2412 { record_entry => $record_id }); # TODO: filter on !deleted?
2414 my $orgs = { map {$_->owning_lib => 1 } @$subs };
2415 return [ keys %$orgs ];
2419 ##########################################################################
2420 # distribution methods
2422 __PACKAGE__->register_method(
2423 method => 'fleshed_sdist_alter',
2424 api_name => 'open-ils.serial.distribution.fleshed.batch.update',
2428 desc => 'Receives an array of one or more distributions and updates the database as needed',
2430 name => 'authtoken',
2431 desc => 'Authtoken for current user session',
2435 name => 'distributions',
2436 desc => 'Array of fleshed distributions',
2442 desc => 'Returns 1 if successful, event if failed',
2448 sub fleshed_sdist_alter {
2449 my( $self, $conn, $auth, $sdists ) = @_;
2450 return 1 unless ref $sdists;
2451 my( $reqr, $evt ) = $U->checkses($auth);
2452 return $evt if $evt;
2453 my $editor = new_editor(requestor => $reqr, xact => 1);
2454 my $override = $self->api_name =~ /override/;
2456 for my $sdist (@$sdists) {
2457 my $holding_lib_id = ref $sdist->holding_lib ? $sdist->holding_lib->id : $sdist->holding_lib;
2458 return $editor->die_event unless
2459 $editor->allowed("ADMIN_SERIAL_DISTRIBUTION", $holding_lib_id);
2461 if( $sdist->isdeleted ) {
2462 $evt = _delete_sdist( $editor, $override, $sdist);
2463 } elsif( $sdist->isnew ) {
2464 $evt = _create_sdist( $editor, $sdist );
2466 $evt = _update_sdist( $editor, $override, $sdist );
2471 $logger->info("fleshed distribution-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2475 $logger->debug("distribution-alter: done updating distribution batch");
2477 $logger->info("fleshed distribution-alter successfully updated ".scalar(@$sdists)." distributions");
2482 my ($editor, $override, $sdist) = @_;
2483 $logger->info("distribution-alter: delete distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2484 return $editor->event unless $editor->delete_serial_distribution($sdist);
2489 my ($editor, $sdist) = @_;
2491 $logger->info("distribution-alter: new distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2492 return $editor->event unless $editor->create_serial_distribution($sdist);
2494 # create summaries too
2495 my $summary = new Fieldmapper::serial::basic_summary;
2496 $summary->distribution($sdist->id);
2497 $summary->generated_coverage('');
2498 return $editor->event unless $editor->create_serial_basic_summary($summary);
2499 $summary = new Fieldmapper::serial::supplement_summary;
2500 $summary->distribution($sdist->id);
2501 $summary->generated_coverage('');
2502 return $editor->event unless $editor->create_serial_supplement_summary($summary);
2503 $summary = new Fieldmapper::serial::index_summary;
2504 $summary->distribution($sdist->id);
2505 $summary->generated_coverage('');
2506 return $editor->event unless $editor->create_serial_index_summary($summary);
2508 # create a starter stream (TODO: reconsider this)
2509 my $stream = new Fieldmapper::serial::stream;
2510 $stream->distribution($sdist->id);
2511 return $editor->event unless $editor->create_serial_stream($stream);
2517 my ($editor, $override, $sdist) = @_;
2519 $logger->info("distribution-alter: retrieving distribution ".$sdist->id);
2520 my $orig_sdist = $editor->retrieve_serial_distribution($sdist->id);
2522 $logger->info("distribution-alter: original distribution ".OpenSRF::Utils::JSON->perl2JSON($orig_sdist));
2523 $logger->info("distribution-alter: updated distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2524 return $editor->event unless $editor->update_serial_distribution($sdist);
2528 __PACKAGE__->register_method(
2529 method => "fleshed_serial_distribution_retrieve_batch",
2531 api_name => "open-ils.serial.distribution.fleshed.batch.retrieve"
2534 sub fleshed_serial_distribution_retrieve_batch {
2535 my( $self, $client, $ids ) = @_;
2536 # FIXME: permissions?
2537 $logger->info("Fetching fleshed distributions @$ids");
2538 return $U->cstorereq(
2539 "open-ils.cstore.direct.serial.distribution.search.atomic",
2542 flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams notes / ]}
2546 __PACKAGE__->register_method(
2547 method => "retrieve_dist_tree",
2549 api_name => "open-ils.serial.distribution_tree.retrieve"
2552 __PACKAGE__->register_method(
2553 method => "retrieve_dist_tree",
2554 api_name => "open-ils.serial.distribution_tree.global.retrieve"
2557 sub retrieve_dist_tree {
2558 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2560 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2564 # TODO: permission support
2565 if(!@org_ids and $user_session) {
2567 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2568 @org_ids = ($user_obj->home_ou);
2571 my $e = new_editor();
2573 if( $self->api_name =~ /global/ ) {
2574 return $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }},
2576 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 / ]},
2577 order_by => {'sdist' => 'id'},
2578 'join' => {'ssub' => {}}
2580 ]); # TODO: filter for !deleted?
2584 for my $orgid (@org_ids) {
2585 my $dists = $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }, holding_lib => $orgid},
2587 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 / ]},
2588 order_by => {'sdist' => 'id'},
2589 'join' => {'ssub' => {}}
2591 ]); # TODO: filter for !deleted?
2592 push( @all_dists, @$dists ) if $dists;
2602 __PACKAGE__->register_method(
2603 method => "distribution_orgs_for_title",
2605 api_name => "open-ils.serial.distribution.retrieve_orgs_by_title"
2608 sub distribution_orgs_for_title {
2609 my( $self, $client, $record_id ) = @_;
2611 my $dists = $U->cstorereq(
2612 "open-ils.cstore.direct.serial.distribution.search.atomic",
2613 { '+ssub' => { record_entry => $record_id } },
2614 { 'join' => {'ssub' => {}} }); # TODO: filter on !deleted?
2616 my $orgs = { map {$_->holding_lib => 1 } @$dists };
2617 return [ keys %$orgs ];
2621 ##########################################################################
2622 # caption and pattern methods
2624 __PACKAGE__->register_method(
2625 method => 'scap_alter',
2626 api_name => 'open-ils.serial.caption_and_pattern.batch.update',
2630 desc => 'Receives an array of one or more caption and patterns and updates the database as needed',
2632 name => 'authtoken',
2633 desc => 'Authtoken for current user session',
2638 desc => 'Array of caption and patterns',
2644 desc => 'Returns 1 if successful, event if failed',
2651 my( $self, $conn, $auth, $scaps ) = @_;
2652 return 1 unless ref $scaps;
2653 my( $reqr, $evt ) = $U->checkses($auth);
2654 return $evt if $evt;
2655 my $editor = new_editor(requestor => $reqr, xact => 1);
2656 my $override = $self->api_name =~ /override/;
2659 for my $scap (@$scaps) {
2660 if (!exists($found_ssub_ids{$scap->subscription})) {
2661 my $ssub = $editor->retrieve_serial_subscription($scap->subscription) or return $editor->die_event;
2662 return $editor->die_event unless
2663 $editor->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $ssub->owning_lib);
2664 $found_ssub_ids{$scap->subscription} = 1;
2667 if( $scap->isdeleted ) {
2668 $evt = _delete_scap( $editor, $override, $scap);
2669 } elsif( $scap->isnew ) {
2670 $evt = _create_scap( $editor, $scap );
2672 $evt = _update_scap( $editor, $override, $scap );
2677 $logger->info("caption_and_pattern-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2681 $logger->debug("caption_and_pattern-alter: done updating caption_and_pattern batch");
2683 $logger->info("caption_and_pattern-alter successfully updated ".scalar(@$scaps)." caption_and_patterns");
2688 my ($editor, $override, $scap) = @_;
2689 $logger->info("caption_and_pattern-alter: delete caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2690 my $sisses = $editor->search_serial_issuance(
2691 { caption_and_pattern => $scap->id }, { limit => 1 } ); #TODO: 'deleted' support?
2692 return OpenILS::Event->new(
2693 'SERIAL_CAPTION_AND_PATTERN_HAS_ISSUANCES', payload => $scap->id ) if (@$sisses);
2695 return $editor->event unless $editor->delete_serial_caption_and_pattern($scap);
2700 my ($editor, $scap) = @_;
2702 $logger->info("caption_and_pattern-alter: new caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2703 return $editor->event unless $editor->create_serial_caption_and_pattern($scap);
2708 my ($editor, $override, $scap) = @_;
2710 $logger->info("caption_and_pattern-alter: retrieving caption_and_pattern ".$scap->id);
2711 my $orig_scap = $editor->retrieve_serial_caption_and_pattern($scap->id);
2713 $logger->info("caption_and_pattern-alter: original caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($orig_scap));
2714 $logger->info("caption_and_pattern-alter: updated caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2715 return $editor->event unless $editor->update_serial_caption_and_pattern($scap);
2719 __PACKAGE__->register_method(
2720 method => "serial_caption_and_pattern_retrieve_batch",
2722 api_name => "open-ils.serial.caption_and_pattern.batch.retrieve"
2725 sub serial_caption_and_pattern_retrieve_batch {
2726 my( $self, $client, $ids ) = @_;
2727 $logger->info("Fetching caption_and_patterns @$ids");
2728 return $U->cstorereq(
2729 "open-ils.cstore.direct.serial.caption_and_pattern.search.atomic",
2734 ##########################################################################
2737 __PACKAGE__->register_method(
2738 method => 'sstr_alter',
2739 api_name => 'open-ils.serial.stream.batch.update',
2743 desc => 'Receives an array of one or more streams and updates the database as needed',
2745 name => 'authtoken',
2746 desc => 'Authtoken for current user session',
2751 desc => 'Array of streams',
2757 desc => 'Returns 1 if successful, event if failed',
2764 my( $self, $conn, $auth, $sstrs ) = @_;
2765 return 1 unless ref $sstrs;
2766 my( $reqr, $evt ) = $U->checkses($auth);
2767 return $evt if $evt;
2768 my $editor = new_editor(requestor => $reqr, xact => 1);
2769 my $override = $self->api_name =~ /override/;
2771 my %found_sdist_ids;
2772 for my $sstr (@$sstrs) {
2773 if (!exists($found_sdist_ids{$sstr->distribution})) {
2774 my $sdist = $editor->retrieve_serial_distribution($sstr->distribution) or return $editor->die_event;
2775 return $editor->die_event unless
2776 $editor->allowed("ADMIN_SERIAL_STREAM", $sdist->holding_lib);
2777 $found_sdist_ids{$sstr->distribution} = 1;
2780 if( $sstr->isdeleted ) {
2781 $evt = _delete_sstr( $editor, $override, $sstr);
2782 } elsif( $sstr->isnew ) {
2783 $evt = _create_sstr( $editor, $sstr );
2785 $evt = _update_sstr( $editor, $override, $sstr );
2790 $logger->info("stream-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2794 $logger->debug("stream-alter: done updating stream batch");
2796 $logger->info("stream-alter successfully updated ".scalar(@$sstrs)." streams");
2801 my ($editor, $override, $sstr) = @_;
2802 $logger->info("stream-alter: delete stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2803 my $sitems = $editor->search_serial_item(
2804 { stream => $sstr->id }, { limit => 1 } ); #TODO: 'deleted' support?
2805 return OpenILS::Event->new(
2806 'SERIAL_STREAM_HAS_ITEMS', payload => $sstr->id ) if (@$sitems);
2808 return $editor->event unless $editor->delete_serial_stream($sstr);
2813 my ($editor, $sstr) = @_;
2815 $logger->info("stream-alter: new stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2816 return $editor->event unless $editor->create_serial_stream($sstr);
2821 my ($editor, $override, $sstr) = @_;
2823 $logger->info("stream-alter: retrieving stream ".$sstr->id);
2824 my $orig_sstr = $editor->retrieve_serial_stream($sstr->id);
2826 $logger->info("stream-alter: original stream ".OpenSRF::Utils::JSON->perl2JSON($orig_sstr));
2827 $logger->info("stream-alter: updated stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2828 return $editor->event unless $editor->update_serial_stream($sstr);
2832 __PACKAGE__->register_method(
2833 method => "serial_stream_retrieve_batch",
2835 api_name => "open-ils.serial.stream.batch.retrieve"
2838 sub serial_stream_retrieve_batch {
2839 my( $self, $client, $ids ) = @_;
2840 $logger->info("Fetching streams @$ids");
2841 return $U->cstorereq(
2842 "open-ils.cstore.direct.serial.stream.search.atomic",
2848 ##########################################################################
2851 __PACKAGE__->register_method(
2852 method => 'sum_alter',
2853 api_name => 'open-ils.serial.basic_summary.batch.update',
2857 desc => 'Receives an array of one or more summaries and updates the database as needed',
2859 name => 'authtoken',
2860 desc => 'Authtoken for current user session',
2865 desc => 'Array of basic summaries',
2871 desc => 'Returns 1 if successful, event if failed',
2877 __PACKAGE__->register_method(
2878 method => 'sum_alter',
2879 api_name => 'open-ils.serial.supplement_summary.batch.update',
2883 desc => 'Receives an array of one or more summaries and updates the database as needed',
2885 name => 'authtoken',
2886 desc => 'Authtoken for current user session',
2891 desc => 'Array of supplement summaries',
2897 desc => 'Returns 1 if successful, event if failed',
2903 __PACKAGE__->register_method(
2904 method => 'sum_alter',
2905 api_name => 'open-ils.serial.index_summary.batch.update',
2909 desc => 'Receives an array of one or more summaries and updates the database as needed',
2911 name => 'authtoken',
2912 desc => 'Authtoken for current user session',
2917 desc => 'Array of index summaries',
2923 desc => 'Returns 1 if successful, event if failed',
2930 my( $self, $conn, $auth, $sums ) = @_;
2931 return 1 unless ref $sums;
2933 $self->api_name =~ /serial\.(\w*)_summary/;
2936 my( $reqr, $evt ) = $U->checkses($auth);
2937 return $evt if $evt;
2938 my $editor = new_editor(requestor => $reqr, xact => 1);
2939 my $override = $self->api_name =~ /override/;
2941 my %found_sdist_ids;
2942 for my $sum (@$sums) {
2943 if (!exists($found_sdist_ids{$sum->distribution})) {
2944 my $sdist = $editor->retrieve_serial_distribution($sum->distribution) or return $editor->die_event;
2945 return $editor->die_event unless
2946 $editor->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2947 $found_sdist_ids{$sum->distribution} = 1;
2950 # XXX: (for now, at least) summaries should be created/deleted by the distribution functions
2951 if( $sum->isdeleted ) {
2952 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2953 } elsif( $sum->isnew ) {
2954 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2956 $evt = _update_sum( $editor, $override, $sum, $type );
2961 $logger->info("${type}_summary-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2965 $logger->debug("${type}_summary-alter: done updating ${type}_summary batch");
2967 $logger->info("${type}_summary-alter successfully updated ".scalar(@$sums)." ${type}_summaries");
2972 my ($editor, $override, $sum, $type) = @_;
2974 $logger->info("${type}_summary-alter: retrieving ${type}_summary ".$sum->id);
2975 my $retrieve_method = "retrieve_serial_${type}_summary";
2976 my $orig_sum = $editor->$retrieve_method($sum->id);
2978 $logger->info("${type}_summary-alter: original ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($orig_sum));
2979 $logger->info("${type}_summary-alter: updated ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($sum));
2980 my $update_method = "update_serial_${type}_summary";
2981 return $editor->event unless $editor->$update_method($sum);
2985 __PACKAGE__->register_method(
2986 method => "serial_summary_retrieve_batch",
2988 api_name => "open-ils.serial.basic_summary.batch.retrieve"
2991 __PACKAGE__->register_method(
2992 method => "serial_summary_retrieve_batch",
2994 api_name => "open-ils.serial.supplement_summary.batch.retrieve"
2997 __PACKAGE__->register_method(
2998 method => "serial_summary_retrieve_batch",
3000 api_name => "open-ils.serial.index_summary.batch.retrieve"
3003 sub serial_summary_retrieve_batch {
3004 my( $self, $client, $ids ) = @_;
3006 $self->api_name =~ /serial\.(\w*)_summary/;
3009 $logger->info("Fetching ${type}_summaries @$ids");
3010 return $U->cstorereq(
3011 "open-ils.cstore.direct.serial.".$type."_summary.search.atomic",
3017 ##########################################################################
3020 __PACKAGE__->register_method(
3021 "method" => "bre_by_identifier",
3022 "api_name" => "open-ils.serial.biblio.record_entry.by_identifier",
3025 "desc" => "Find instances of biblio.record_entry given a search token" .
3026 " that could be a value for any identifier defined in " .
3027 "config.metabib_field",
3029 {"desc" => "Search token", "type" => "string"},
3030 {"desc" => "Options: require_subscriptions, add_mvr, is_actual_id" .
3031 ", id_list (all boolean)", "type" => "object"}
3034 "desc" => "Any matching BREs, or if the add_mvr option is true, " .
3035 "objects with a 'bre' key/value pair, and an 'mvr' " .
3036 "key-value pair. BREs have subscriptions fleshed on.",
3042 sub bre_by_identifier {
3043 my ($self, $client, $term, $options) = @_;
3045 return new OpenILS::Event("BAD_PARAMS") unless $term;
3048 my $e = new_editor();
3052 if ($options->{"is_actual_id"}) {
3056 $e->search_config_metabib_field({"field_class" => "identifier"})
3057 or return $e->die_event;
3059 my @identifiers = map { $_->name } @$cmf;
3060 my $query = join(" || ", map { "id|$_: $term" } @identifiers);
3062 my $search = create OpenSRF::AppSession("open-ils.search");
3063 my $search_result = $search->request(
3064 "open-ils.search.biblio.multiclass.query.staff", {}, $query
3066 $search->disconnect;
3068 # Un-nest results. They tend to look like [[1],[2],[3]] for some reason.
3069 @ids = map { @{$_} } @{$search_result->{"ids"}};
3076 if ($options->{"id_list"}) {
3078 $client->respond($_) foreach (@ids);
3083 my $bre = $e->search_biblio_record_entry([
3085 "flesh" => 2, "flesh_fields" => {
3086 "bre" => ["subscriptions"],
3087 "ssub" => ["owning_lib"]
3090 ]) or return $e->die_event;
3092 if (@$bre && $options->{"require_subscriptions"}) {
3093 $bre = [ grep { @{$_->subscriptions} } @$bre ];
3098 if (@$bre) { # re-evaluate after possible grep
3099 if ($options->{"add_mvr"}) {
3101 {"bre" => $_, "mvr" => _get_mvr($_->id)}
3104 $client->respond($_) foreach (@$bre);
3111 __PACKAGE__->register_method(
3112 "method" => "get_items_by",
3113 "api_name" => "open-ils.serial.items.receivable.by_subscription",
3116 "desc" => "Return all receivable items under a given subscription",
3118 {"desc" => "Authtoken", "type" => "string"},
3119 {"desc" => "Subscription ID", "type" => "number"},
3122 "desc" => "All receivable items under a given subscription",
3123 "type" => "object", "class" => "sitem"
3128 __PACKAGE__->register_method(
3129 "method" => "get_items_by",
3130 "api_name" => "open-ils.serial.items.receivable.by_issuance",
3133 "desc" => "Return all receivable items under a given issuance",
3135 {"desc" => "Authtoken", "type" => "string"},
3136 {"desc" => "Issuance ID", "type" => "number"},
3139 "desc" => "All receivable items under a given issuance",
3140 "type" => "object", "class" => "sitem"
3145 __PACKAGE__->register_method(
3146 "method" => "get_items_by",
3147 "api_name" => "open-ils.serial.items.by_issuance",
3150 "desc" => "Return all items under a given issuance",
3152 {"desc" => "Authtoken", "type" => "string"},
3153 {"desc" => "Issuance ID", "type" => "number"},
3156 "desc" => "All items under a given issuance",
3157 "type" => "object", "class" => "sitem"
3163 my ($self, $client, $auth, $term, $opts) = @_;
3165 # Not to be used in the json_query, but after limiting by perm check.
3166 $opts = {} unless ref $opts eq "HASH";
3167 $opts->{"limit"} ||= 10000; # some existing users may want all results
3168 $opts->{"offset"} ||= 0;
3169 $opts->{"limit"} = int($opts->{"limit"});
3170 $opts->{"offset"} = int($opts->{"offset"});
3172 my $e = new_editor("authtoken" => $auth);
3173 return $e->die_event unless $e->checkauth;
3175 my $by = ($self->api_name =~ /by_(\w+)$/)[0];
3176 my $receivable = ($self->api_name =~ /receivable/);
3179 "issuance" => {"issuance" => $term},
3180 "subscription" => {"+siss" => {"subscription" => $term}}
3183 my $item_rows = $e->json_query(
3185 "select" => {"sitem" => ["id"], "sdist" => ["holding_lib"]},
3189 "sstr" => {"join" => {"sdist" => {}}}
3193 %{$where{$by}}, $receivable ? ("date_received" => undef) : ()
3195 "order_by" => {"sitem" => ["id"]}
3197 ) or return $e->die_event;
3199 return undef unless @$item_rows;
3203 foreach (@$item_rows) {
3204 last if $returned >= $opts->{"limit"};
3205 next unless $e->allowed("RECEIVE_SERIAL", $_->{"holding_lib"});
3206 if ($skipped < $opts->{"offset"}) {
3212 $e->retrieve_serial_item([
3216 "sitem" => [qw/stream issuance unit creator editor/],
3217 "sstr" => ["distribution"],
3218 "sdist" => ["holding_lib"]
3230 __PACKAGE__->register_method(
3231 "method" => "get_receivable_issuances",
3232 "api_name" => "open-ils.serial.issuances.receivable",
3235 "desc" => "Return all issuances with receivable items given " .
3236 "a subscription ID",
3238 {"desc" => "Authtoken", "type" => "string"},
3239 {"desc" => "Subscription ID", "type" => "number"},
3242 "desc" => "All issuances with receivable items " .
3243 "(but not the items themselves)", "type" => "object"
3248 sub get_receivable_issuances {
3249 my ($self, $client, $auth, $sub_id) = @_;
3251 my $e = new_editor("authtoken" => $auth);
3252 return $e->die_event unless $e->checkauth;
3256 my $issuance_ids = $e->json_query({
3259 {"transform" => "distinct", "column" => "id"},
3263 "from" => {"siss" => "sitem"},
3265 "subscription" => $sub_id,
3266 "+sitem" => {"date_received" => undef}
3269 "siss" => {"date_published" => {"direction" => "asc"}}
3272 }) or return $e->die_event;
3274 $client->respond($e->retrieve_serial_issuance($_->{"id"}))
3275 foreach (@$issuance_ids);
3282 __PACKAGE__->register_method(
3283 "method" => "get_routing_list_users",
3284 "api_name" => "open-ils.serial.routing_list_users.fleshed_and_ordered",
3287 "desc" => "Return all routing list users with reader fleshed " .
3288 "(with card and home_ou) for a given stream ID, sorted by pos",
3290 {"desc" => "Authtoken", "type" => "string"},
3291 {"desc" => "Stream ID (int or array of ints)", "type" => "mixed"},
3294 "desc" => "Stream of routing list users", "type" => "object",
3300 sub get_routing_list_users {
3301 my ($self, $client, $auth, $stream_id) = @_;
3303 my $e = new_editor("authtoken" => $auth);
3304 return $e->die_event unless $e->checkauth;
3306 my $users = $e->search_serial_routing_list_user([
3307 {"stream" => $stream_id}, {
3308 "order_by" => {"srlu" => "pos"},
3311 "srlu" => [qw/reader stream/],
3312 "au" => [qw/card home_ou mailing_address billing_address/],
3313 "sstr" => ["distribution"]
3316 ]) or return $e->die_event;
3318 return undef unless @$users;
3320 # The ADMIN_SERIAL_STREAM permission is used simply to avoid the
3321 # need for any new permission. The context OU will be the same
3322 # for every result of the above query, so we need only check once.
3323 return $e->die_event unless $e->allowed(
3324 "ADMIN_SERIAL_STREAM", $users->[0]->stream->distribution->holding_lib
3329 my @users = map { $_->stream($_->stream->id); $_ } @$users;
3330 @users = sort { $a->stream cmp $b->stream } @users if
3331 ref $stream_id eq "ARRAY";
3333 $client->respond($_) for @users;
3339 __PACKAGE__->register_method(
3340 "method" => "replace_routing_list_users",
3341 "api_name" => "open-ils.serial.routing_list_users.replace",
3343 "desc" => "Replace all routing list users on the specified streams " .
3344 "with those in the list argument",
3346 {"desc" => "Authtoken", "type" => "string"},
3347 {"desc" => "List of srlu objects", "type" => "array"},
3350 "desc" => "event on failure, undef on success"
3355 sub replace_routing_list_users {
3356 my ($self, $client, $auth, $users) = @_;
3358 return undef unless ref $users eq "ARRAY";
3360 if (grep { ref $_ ne "Fieldmapper::serial::routing_list_user" } @$users) {
3361 return new OpenILS::Event("BAD_PARAMS", "note" => "Only srlu objects");
3364 my $e = new_editor("authtoken" => $auth, "xact" => 1);
3365 return $e->die_event unless $e->checkauth;
3367 my %streams_ok = ();
3370 foreach my $user (@$users) {
3371 unless (exists $streams_ok{$user->stream}) {
3372 my $stream = $e->retrieve_serial_stream([
3375 "flesh_fields" => {"sstr" => ["distribution"]}
3377 ]) or return $e->die_event;
3379 "ADMIN_SERIAL_STREAM", $stream->distribution->holding_lib
3380 ) or return $e->die_event;
3382 my $to_delete = $e->search_serial_routing_list_user(
3383 {"stream" => $user->stream}
3384 ) or return $e->die_event;
3387 "Deleting srlu: [" .
3388 join(", ", map { $_->id; } @$to_delete) .
3392 foreach (@$to_delete) {
3393 $e->delete_serial_routing_list_user($_) or
3394 return $e->die_event;
3397 $streams_ok{$user->stream} = 1;
3400 next if $user->isdeleted;
3404 $e->create_serial_routing_list_user($user) or return $e->die_event;
3407 $e->commit or return $e->die_event;
3411 __PACKAGE__->register_method(
3412 "method" => "get_records_with_marc_85x",
3413 "api_name"=>"open-ils.serial.caption_and_pattern.find_legacy_by_bib_record",
3416 "desc" => "Return the specified BRE itself and/or any related SRE ".
3417 "whenever they have 853-855 tags",
3419 {"desc" => "Authtoken", "type" => "string"},
3420 {"desc" => "bib record ID", "type" => "number"},
3423 "desc" => "objects, either bre or sre", "type" => "object"
3428 sub get_records_with_marc_85x { # specifically, 853-855
3429 my ($self, $client, $auth, $bre_id) = @_;
3431 my $e = new_editor("authtoken" => $auth);
3432 return $e->die_event unless $e->checkauth;
3434 my $bre = $e->search_biblio_record_entry([
3435 {"id" => $bre_id, "deleted" => "f"}, {
3437 "flesh_fields" => {"bre" => [qw/creator editor owner/]}
3439 ]) or return $e->die_event;
3441 return undef unless @$bre;
3444 my $record = MARC::Record->new_from_xml($bre->marc);
3445 $client->respond($bre) if $record->field("85[3-5]");
3446 # XXX Is passing a regex to ->field() an abuse of MARC::Record ?
3448 my $sres = $e->search_serial_record_entry([
3449 {"record" => $bre_id, "deleted" => "f"}, {
3451 "flesh_fields" => {"sre" => [qw/creator editor owning_lib/]}
3453 ]) or return $e->die_event;
3457 foreach my $sre (@$sres) {
3458 $client->respond($sre) if
3459 MARC::Record->new_from_xml($sre->marc)->field("85[3-5]");
3465 __PACKAGE__->register_method(
3466 "method" => "create_scaps_from_marcxml",
3467 "api_name" => "open-ils.serial.caption_and_pattern.create_from_records",
3470 "desc" => "Create caption and pattern objects from 853-855 tags " .
3471 "in MARCXML documents",
3473 {"desc" => "Authtoken", "type" => "string"},
3474 {"desc" => "Subscription ID", "type" => "number"},
3475 {"desc" => "list of MARCXML documents as strings",
3479 "desc" => "Newly created caption and pattern objects",
3480 "type" => "object", "class" => "scap"
3485 sub create_scaps_from_marcxml {
3486 my ($self, $client, $auth, $sub_id, $docs) = @_;
3488 return undef unless ref $docs eq "ARRAY";
3490 my $e = new_editor("authtoken" => $auth, "xact" => 1);
3491 return $e->die_event unless $e->checkauth;
3493 # Retrieve the subscription just for perm checking (whether we can create
3494 # scaps at the owning lib).
3495 my $sub = $e->retrieve_serial_subscription($sub_id) or return $e->die_event;
3496 return $e->die_event unless
3497 $e->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $sub->owning_lib);
3499 foreach my $record (map { MARC::Record->new_from_xml($_) } @$docs) {
3500 foreach my $field ($record->field("85[3-5]")) {
3501 my $scap = new Fieldmapper::serial::caption_and_pattern;
3502 $scap->subscription($sub_id);
3503 $scap->type($MFHD_NAMES_BY_TAG{$field->tag});
3504 $scap->pattern_code(
3505 OpenSRF::Utils::JSON->perl2JSON(
3506 [ $field->indicator(1), $field->indicator(2),
3507 map { @$_ } $field->subfields ] # flattens nested array
3510 $e->create_serial_caption_and_pattern($scap) or
3511 return $e->die_event;
3512 $client->respond($e->data);
3516 $e->commit or return $e->die_event;
3520 # All these _clone_foo() functions could possibly have been consolidated into
3521 # one clever function, but it's faster to get things working this way.
3522 sub _clone_subscription {
3523 my ($sub, $bib_id, $e) = @_;
3526 my $new_sub = $sub->clone;
3527 $new_sub->record_entry(int $bib_id) if $bib_id;
3529 $new_sub->clear_distributions;
3530 $new_sub->clear_notes;
3531 $new_sub->clear_scaps;
3533 $e->create_serial_subscription($new_sub) or return $e->die_event;
3535 my $new_sub_id = $e->data->id;
3537 foreach my $dist (@{$sub->distributions}) {
3538 my $r = _clone_distribution($dist, $new_sub_id, $e);
3539 return $r if $U->event_code($r);
3543 foreach my $note (@{$sub->notes}) {
3544 my $r = _clone_subscription_note($note, $new_sub_id, $e);
3545 return $r if $U->event_code($r);
3549 foreach my $scap (@{$sub->scaps}) {
3550 my $r = _clone_caption_and_pattern($scap, $new_sub_id, $e);
3551 return $r if $U->event_code($r);
3557 sub _clone_distribution {
3558 my ($dist, $sub_id, $e) = @_;
3560 my $new_dist = $dist->clone;
3561 $new_dist->clear_id;
3562 $new_dist->clear_notes;
3563 $new_dist->clear_streams;
3564 $new_dist->subscription($sub_id);
3566 $e->create_serial_distribution($new_dist) or return $e->die_event;
3567 my $new_dist_id = $e->data->id;
3570 foreach my $stream (@{$dist->streams}) {
3571 my $r = _clone_stream($stream, $new_dist_id, $e);
3572 return $r if $U->event_code($r);
3575 # clone distribution notes
3576 foreach my $note (@{$dist->notes}) {
3577 my $r = _clone_distribution_note($note, $new_dist_id, $e);
3578 return $r if $U->event_code($r);
3581 return $new_dist_id;
3584 sub _clone_subscription_note {
3585 my ($note, $sub_id, $e) = @_;
3587 my $new_note = $note->clone;
3588 $new_note->clear_id;
3589 $new_note->creator($e->requestor->id);
3590 $new_note->create_date("now");
3591 $new_note->subscription($sub_id);
3593 $e->create_serial_subscription_note($new_note) or return $e->die_event;
3594 return $e->data->id;
3597 sub _clone_caption_and_pattern {
3598 my ($scap, $sub_id, $e) = @_;
3600 my $new_scap = $scap->clone;
3601 $new_scap->clear_id;
3602 $new_scap->subscription($sub_id);
3604 $e->create_serial_caption_and_pattern($new_scap) or return $e->die_event;
3605 return $e->data->id;
3608 sub _clone_distribution_note {
3609 my ($note, $dist_id, $e) = @_;
3611 my $new_note = $note->clone;
3612 $new_note->clear_id;
3613 $new_note->creator($e->requestor->id);
3614 $new_note->create_date("now");
3615 $new_note->distribution($dist_id);
3617 $e->create_serial_distribution_note($new_note) or return $e->die_event;
3618 return $e->data->id;
3622 my ($stream, $dist_id, $e) = @_;
3624 my $new_stream = $stream->clone;
3625 $new_stream->clear_id;
3626 $new_stream->clear_routing_list_users;
3627 $new_stream->distribution($dist_id);
3629 $e->create_serial_stream($new_stream) or return $e->die_event;
3630 my $new_stream_id = $e->data->id;
3632 # clone routing list users
3633 foreach my $user (@{$stream->routing_list_users}) {
3634 my $r = _clone_routing_list_user($user, $new_stream_id, $e);
3635 return $r if $U->event_code($r);
3638 return $new_stream_id;
3641 sub _clone_routing_list_user {
3642 my ($user, $stream_id, $e) = @_;
3644 my $new_user = $user->clone;
3645 $new_user->clear_id;
3646 $new_user->stream($stream_id);
3648 $e->create_serial_routing_list_user($new_user) or return $e->die_event;
3649 return $e->data->id;
3652 __PACKAGE__->register_method(
3653 "method" => "clone_subscription",
3654 "api_name" => "open-ils.serial.subscription.clone",
3656 "desc" => q{Clone a subscription, including its attending distributions,
3657 streams, captions and patterns, routing list users, distribution
3658 notes and subscription notes. Do not include holdings-specific
3659 things, like issuances, items, units, summaries. Attach the
3660 clone either to the same bib record as the original, or to one
3663 {"desc" => "Authtoken", "type" => "string"},
3664 {"desc" => "Subscription ID", "type" => "number"},
3665 {"desc" => "Bib Record ID (optional)", "type" => "number"}
3668 "desc" => "ID of the new subscription", "type" => "number"
3673 sub clone_subscription {
3674 my ($self, $client, $auth, $sub_id, $bib_id) = @_;
3676 my $e = new_editor("authtoken" => $auth, "xact" => 1);
3677 return $e->die_event unless $e->checkauth;
3679 my $sub = $e->retrieve_serial_subscription([
3683 "ssub" => [qw/distributions notes scaps/],
3684 "sdist" => [qw/streams notes/],
3685 "sstr" => ["routing_list_users"]
3688 ]) or return $e->die_event;
3690 # ADMIN_SERIAL_SUBSCRIPTION will have to be good enough as a
3691 # catch-all permisison for this operation.
3692 return $e->die_event unless
3693 $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
3695 my $result = _clone_subscription($sub, $bib_id, $e);
3697 return $e->die_event($result) if $U->event_code($result);
3699 $e->commit or return $e->die_event;
3703 __PACKAGE__->register_method(
3704 "method" => "summary_test",
3705 "api_name" => "open-ils.serial.summary_test",
3711 # This crummy little test method allows quicker reproduction of certain
3712 # failures (e.g. at item receive time) of the holdings summarization code.
3713 # Pass it an authtoken, an array of issuance IDs, and a single sdist ID
3715 my ($self, $conn, $authtoken, $iss_id_list, $sdist_id) = @_;
3717 my $e = new_editor(authtoken => $authtoken, xact => 1);
3718 return $e->die_event unless $e->checkauth;
3719 return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
3722 foreach my $id (@$iss_id_list) {
3723 my $iss = $e->retrieve_serial_issuance($id) or return $e->die_event;
3724 push @issuances, $iss;
3727 my $dist = $e->retrieve_serial_distribution($sdist_id) or return $e->die_event;
3729 $conn->respond(_summarize_contents($e, \@issuances, $dist));