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 my %siss_to_potentially_delete;
261 for my $item (@$items) {
262 my $sstr_id = ref $item->stream ? $item->stream->id : $item->stream;
263 if (!exists($found_sstr_ids{$sstr_id})) {
265 if (ref $item->stream) {
266 $sstr = $item->stream;
268 $sstr = $editor->retrieve_serial_stream($item->stream) or return $editor->die_event;
270 if (!exists($found_sdist_ids{$sstr->distribution})) {
271 my $sdist = $editor->retrieve_serial_distribution($sstr->distribution) or return $editor->die_event;
272 return $editor->die_event unless
273 $editor->allowed("ADMIN_SERIAL_STREAM", $sdist->holding_lib);
274 $found_sdist_ids{$sstr->distribution} = 1;
276 $found_sstr_ids{$sstr_id} = 1;
279 $item->editor($editor->requestor->id);
280 $item->edit_date('now');
282 if( $item->isdeleted ) {
283 my $siss_id = ref $item->issuance ? $item->issuance->id : $item->issuance;
284 $siss_to_potentially_delete{$siss_id}++;
285 $evt = _delete_sitem( $editor, $override, $item);
286 } elsif( $item->isnew ) {
287 # TODO: reconsider this
288 # if the item has a new issuance, create the issuance first
289 if (ref $item->issuance eq 'Fieldmapper::serial::issuance' and $item->issuance->isnew) {
290 fleshed_issuance_alter($self, $conn, $auth, [$item->issuance]);
292 _cleanse_dates($item, ['date_expected','date_received']);
293 $evt = _create_sitem( $editor, $item );
295 _cleanse_dates($item, ['date_expected','date_received']);
296 $evt = _update_sitem( $editor, $override, $item );
301 $logger->info("fleshed item-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
305 if( %siss_to_potentially_delete ) {
306 foreach my $id (keys %siss_to_potentially_delete) {
307 my $issuance = $editor->retrieve_serial_issuance([
309 "flesh" => 1, "flesh_fields" => {
315 $logger->warn("fleshed item-alter failed to retrieve issuance $id to potenitally delete");
317 return $editor->die_event;
319 unless (@{ $issuance->items }) {
320 $logger->info("fleshed item-alter deleting issuance $id as it has no items left");
321 $evt = _delete_siss( $editor, $override, $issuance);
323 $logger->info("fleshed item-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
330 $logger->debug("item-alter: done updating item batch");
332 $logger->info("fleshed item-alter successfully updated ".scalar(@$items)." items");
337 my ($editor, $override, $item) = @_;
338 $logger->info("item-alter: delete item ".OpenSRF::Utils::JSON->perl2JSON($item));
339 return $editor->event unless $editor->delete_serial_item($item);
344 my ($editor, $item) = @_;
346 $item->creator($editor->requestor->id);
347 $item->create_date('now');
349 $logger->info("item-alter: new item ".OpenSRF::Utils::JSON->perl2JSON($item));
350 return $editor->event unless $editor->create_serial_item($item);
355 my ($editor, $override, $item) = @_;
357 $logger->info("item-alter: retrieving item ".$item->id);
358 my $orig_item = $editor->retrieve_serial_item($item->id);
360 $logger->info("item-alter: original item ".OpenSRF::Utils::JSON->perl2JSON($orig_item));
361 $logger->info("item-alter: updated item ".OpenSRF::Utils::JSON->perl2JSON($item));
362 return $editor->event unless $editor->update_serial_item($item);
366 __PACKAGE__->register_method(
367 method => "fleshed_serial_item_retrieve_batch",
369 api_name => "open-ils.serial.item.fleshed.batch.retrieve"
372 sub fleshed_serial_item_retrieve_batch {
373 my( $self, $client, $ids ) = @_;
374 # FIXME: permissions?
375 $logger->info("Fetching fleshed serial items @$ids");
376 return $U->cstorereq(
377 "open-ils.cstore.direct.serial.item.search.atomic",
380 flesh_fields => {sitem => [ qw/issuance creator editor stream unit notes/ ], sunit => ["call_number"], siss => [qw/creator editor subscription/]}
385 ##########################################################################
388 __PACKAGE__->register_method(
389 method => 'fleshed_issuance_alter',
390 api_name => 'open-ils.serial.issuance.fleshed.batch.update',
394 desc => 'Receives an array of one or more issuances and updates the database as needed',
397 desc => 'Authtoken for current user session',
402 desc => 'Array of fleshed issuances',
408 desc => 'Returns 1 if successful, event if failed',
414 sub fleshed_issuance_alter {
415 my( $self, $conn, $auth, $issuances ) = @_;
416 return 1 unless ref $issuances;
417 my( $reqr, $evt ) = $U->checkses($auth);
419 my $editor = new_editor(authtoken => $auth, requestor => $reqr, xact => 1);
420 my $override = $self->api_name =~ /override/;
424 for my $issuance (@$issuances) {
425 my $ssub_id = ref $issuance->subscription ? $issuance->subscription->id : $issuance->subscription;
426 if (!exists($found_ssub_ids{$ssub_id})) {
428 if (ref $issuance->subscription) {
429 $owning_lib_id = $issuance->subscription->owning_lib;
431 my $ssub = $editor->retrieve_serial_subscription($issuance->subscription) or return $editor->die_event;
432 $owning_lib_id = $ssub->owning_lib;
434 return $editor->die_event unless
435 $editor->allowed("ADMIN_SERIAL_SUBSCRIPTION", $owning_lib_id);
436 $found_ssub_ids{$ssub_id} = 1;
439 my $issuanceid = $issuance->id;
440 $issuance->editor($editor->requestor->id);
441 $issuance->edit_date('now');
443 if( $issuance->isdeleted ) {
444 $evt = _delete_siss( $editor, $override, $issuance);
445 $regen_ssub_ids{$ssub_id} = 1;
446 } elsif( $issuance->isnew ) {
447 _cleanse_dates($issuance, ['date_published']);
448 $evt = _create_siss( $editor, $issuance );
450 _cleanse_dates($issuance, ['date_published']);
451 $evt = _update_siss( $editor, $override, $issuance );
458 # if we deleted any issuances, update the summaries
459 # for all dists in those ssubs
460 my @ssub_ids = keys %regen_ssub_ids;
461 $evt = _regenerate_summaries($editor, {'ssub_ids' => \@ssub_ids}) if @ssub_ids;
465 $logger->info("fleshed issuance-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
470 $logger->debug("issuance-alter: done updating issuance batch");
472 $logger->info("fleshed issuance-alter successfully updated ".scalar(@$issuances)." issuances");
477 my ($editor, $override, $issuance) = @_;
478 $logger->info("issuance-alter: delete issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
479 return $editor->event unless $editor->delete_serial_issuance($issuance);
484 my ($editor, $issuance) = @_;
486 $issuance->creator($editor->requestor->id);
487 $issuance->create_date('now');
489 $logger->info("issuance-alter: new issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
490 return $editor->event unless $editor->create_serial_issuance($issuance);
495 my ($editor, $override, $issuance) = @_;
497 $logger->info("issuance-alter: retrieving issuance ".$issuance->id);
498 my $orig_issuance = $editor->retrieve_serial_issuance($issuance->id);
500 $logger->info("issuance-alter: original issuance ".OpenSRF::Utils::JSON->perl2JSON($orig_issuance));
501 $logger->info("issuance-alter: updated issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
502 return $editor->event unless $editor->update_serial_issuance($issuance);
506 __PACKAGE__->register_method(
507 method => "fleshed_serial_issuance_retrieve_batch",
509 api_name => "open-ils.serial.issuance.fleshed.batch.retrieve"
512 sub fleshed_serial_issuance_retrieve_batch {
513 my( $self, $client, $ids ) = @_;
514 # FIXME: permissions?
515 $logger->info("Fetching fleshed serial issuances @$ids");
516 return $U->cstorereq(
517 "open-ils.cstore.direct.serial.issuance.search.atomic",
520 flesh_fields => {siss => [ qw/creator editor subscription/ ]}
524 __PACKAGE__->register_method(
525 method => "pub_fleshed_serial_issuance_retrieve_batch",
526 api_name => "open-ils.serial.issuance.pub_fleshed.batch.retrieve",
529 Public (i.e. OPAC) call for getting at the sub and
530 ultimately the record entry from an issuance
532 params => [{name => 'ids', desc => 'Array of IDs', type => 'array'}],
535 issuance objects, fleshed with subscriptions
541 sub pub_fleshed_serial_issuance_retrieve_batch {
542 my( $self, $client, $ids ) = @_;
543 return [] unless $ids and @$ids;
544 return new_editor()->search_serial_issuance([
548 flesh_fields => {siss => [ qw/subscription/ ]}
553 sub received_siss_by_bib {
554 # XXX this is somewhat wrong in implementation and should not be used in
555 # new places - senator
560 my $args = shift || {};
561 $$args{order} ||= 'asc';
563 my $global = $$args{global} == 0 ? 0 : 1;
565 my $e = new_editor();
566 my $issuances = $e->json_query({
569 $global ? { transform => "min", column => "id", aggregate => 1 } : "id",
574 # We're not really interested in the minimum here. This is
575 # just a way to distinguish issuances whose items have units
576 # from issuances whose items have no units, without altogether
577 # excluding the latter type of issuances.
578 {"transform" => "min", "alias" => "has_units",
579 "column" => "unit", "aggregate" => 1}
585 field => 'subscription',
591 $$args{ou} ? ( join => {
598 fkey => 'distribution'
609 '+ssub' => { record_entry => $bib },
610 $$args{type} ? ( '+siss' => { 'holding_type' => $$args{type} } ) : (),
612 # XXX should we also take specific item statuses into account?
613 date_received => { '!=' => undef },
614 $$args{status} ? ( 'status' => $$args{status} ) : ()
616 $$args{ou} ? ( '+sdist' => {
618 'in' => $U->get_org_descendants($$args{ou}, $$args{depth})
622 $$args{limit} ? ( limit => $$args{limit} ) : (),
623 $$args{offset} ? ( offset => $$args{offset} ) : (),
624 order_by => [{ class => 'siss', field => 'date_published', direction => $$args{order} }],
629 "issuance" => $e->retrieve_serial_issuance($_->{"id"}),
630 "has_units" => $_->{"has_units"} ? 1 : 0
635 __PACKAGE__->register_method(
636 method => 'received_siss_by_bib',
637 api_name => 'open-ils.serial.received_siss.retrieve.by_bib',
642 desc => 'Receives a Bib ID and other optional params and returns "siss" (issuance) objects',
645 desc => 'id of the bre to which the issuances belong',
650 q/A hash of optional arguments. Valid keys and their meanings:
651 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).
652 order := date_published sort direction, either "asc" (chronological, default) or "desc" (reverse chronological)
653 limit := Number of issuances to return. Useful for paging results, or finding the oldest or newest
654 offset := Number of issuance to skip before returning results. Useful for paging.
655 orgid := OU id used to scope retrieval, based on distribution.holding_lib
656 depth := OU depth used to range the scope of orgid
657 type := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
658 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).
666 sub scoped_bib_holdings_summary {
667 # XXX this is somewhat wrong in implementation and should not be used in
668 # new places - senator
672 my $args = shift || {};
674 $args->{order} = 'asc';
676 my ($issuances) = $self->method_lookup('open-ils.serial.received_siss.retrieve.by_bib.atomic')->run( $bibid => $args );
678 # split into issuance type sets
679 my %type_blob = (basic => [], supplement => [], index => []);
680 push @{ $type_blob{ $_->{"issuance"}->holding_type } }, $_->{"issuance"}
683 # generate a statement list for each type
685 for my $type ( keys %type_blob ) {
686 my ($mfhd,$list) = _summarize_contents(new_editor(), $type_blob{$type});
688 return {} if $U->event_code($mfhd); # _summarize_contents() failed, bad data?
690 $statement_blob{$type} = $list;
693 return \%statement_blob;
695 __PACKAGE__->register_method(
696 method => 'scoped_bib_holdings_summary',
697 api_name => 'open-ils.serial.bib.summary_statements',
701 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',
704 desc => 'id of the bre to which the issuances belong',
709 q/A hash of optional arguments. Valid keys and their meanings:
710 orgid := OU id used to scope retrieval, based on distribution.holding_lib
711 depth := OU depth used to range the scope of orgid
712 type := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
713 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).
721 ##########################################################################
724 __PACKAGE__->register_method(
725 method => 'fleshed_sunit_alter',
726 api_name => 'open-ils.serial.sunit.fleshed.batch.update',
730 desc => 'Receives an array of one or more Units and updates the database as needed',
733 desc => 'Authtoken for current user session',
738 desc => 'Array of fleshed Units',
744 desc => 'Returns 1 if successful, event if failed',
750 sub fleshed_sunit_alter {
751 my( $self, $conn, $auth, $sunits ) = @_;
752 return 1 unless ref $sunits;
753 my( $reqr, $evt ) = $U->checkses($auth);
755 my $editor = new_editor(requestor => $reqr, xact => 1);
756 my $override = $self->api_name =~ /override/;
759 for my $sunit (@$sunits) {
760 my $cn_id = ref $sunit->call_number ? $sunit->call_number->id : $sunit->call_number;
761 if (!exists($found_cn_ids{$cn_id})) {
763 if (ref $sunit->call_number) {
764 $owning_lib_id = $sunit->call_number->owning_lib;
766 my $cn = $editor->retrieve_asset_call_number($sunit->call_number) or return $editor->die_event;
767 $owning_lib_id = $cn->owning_lib;
769 return $editor->die_event unless
770 $editor->allowed("UPDATE_COPY", $owning_lib_id);
771 $found_cn_ids{$cn_id} = 1;
774 if( $sunit->isdeleted ) {
775 $evt = _delete_sunit( $editor, $override, $sunit );
777 $sunit->default_location( $sunit->default_location->id ) if ref $sunit->default_location;
779 if( $sunit->isnew ) {
780 $evt = _create_sunit( $editor, $sunit );
782 $evt = _update_sunit( $editor, $override, $sunit );
788 $logger->info("fleshed sunit-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
792 $logger->debug("sunit-alter: done updating sunit batch");
794 $logger->info("fleshed sunit-alter successfully updated ".scalar(@$sunits)." Units");
799 my ($editor, $override, $sunit) = @_;
800 $logger->info("sunit-alter: delete sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
801 return $editor->event unless $editor->delete_serial_unit($sunit);
806 my ($editor, $sunit) = @_;
808 # The unique barcode constraint does not span asset.copy and serial.unit.
809 # ensure the barcode on the new unit does not collide with an existing
810 # asset.copy barcode.
811 my $existing = $editor->search_asset_copy(
812 {deleted => 'f', barcode => $sunit->barcode})->[0];
815 # The DB will prevent duplicate serial.unit barcodes, but for
816 # consistency (and a more specific error message for the
817 # user), prevent creation attempts on serial unit barcode
818 # collisions as well.
819 $existing = $editor->search_serial_unit(
820 {deleted => 'f', barcode => $sunit->barcode})->[0];
825 return new OpenILS::Event(
826 'SERIAL_UNIT_BARCODE_COLLISION', note =>
827 'Serial unit barcode collides with existing unit/copy barcode',
828 payload => {barcode => $sunit->barcode}
832 $logger->info("sunit-alter: new Unit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
833 return $editor->die_event unless $editor->create_serial_unit($sunit);
838 my ($editor, $override, $sunit) = @_;
840 $logger->info("sunit-alter: retrieving sunit ".$sunit->id);
841 my $orig_sunit = $editor->retrieve_serial_unit($sunit->id);
843 $logger->info("sunit-alter: original sunit ".OpenSRF::Utils::JSON->perl2JSON($orig_sunit));
844 $logger->info("sunit-alter: updated sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
845 return $editor->event unless $editor->update_serial_unit($sunit);
849 __PACKAGE__->register_method(
850 method => "retrieve_unit_list",
852 api_name => "open-ils.serial.unit_list.retrieve"
855 sub retrieve_unit_list {
857 my( $self, $client, @sdist_ids ) = @_;
859 if(ref($sdist_ids[0])) { @sdist_ids = @{$sdist_ids[0]}; }
861 my $e = new_editor();
865 { 'sunit' => [ 'id', 'summary_contents', 'sort_key' ],
866 'sitem' => ['stream'],
867 'sstr' => ['distribution'],
868 'sdist' => [{'column' => 'label', 'alias' => 'sdist_label'}]
875 { 'join' => { 'sunit' => {} } }
880 'distinct' => 'true',
881 'where' => { '+sdist' => {'id' => \@sdist_ids} },
882 'order_by' => [{'class' => 'sunit', 'field' => 'sort_key'}]
885 my $unit_list_entries = $e->json_query($query);
888 foreach my $entry (@$unit_list_entries) {
889 my $value = {'sunit' => $entry->{id}, 'sstr' => $entry->{stream}, 'sdist' => $entry->{distribution}};
890 my $label = $entry->{summary_contents};
891 if (length($label) > 100) {
892 $label = substr($label, 0, 100) . '...'; # limited space in dropdown / menu
894 $label = "[$entry->{sdist_label}/$entry->{stream} #$entry->{id}] " . $label;
895 push (@entries, [$label, OpenSRF::Utils::JSON->perl2JSON($value)]);
903 ##########################################################################
904 # predict and receive methods
906 __PACKAGE__->register_method(
907 method => 'make_predictions',
908 api_name => 'open-ils.serial.make_predictions',
912 desc => 'Receives an ssub id and populates the issuance and item tables',
915 desc => 'Serial Subscription ID',
922 sub make_predictions {
923 my ($self, $conn, $authtoken, $args) = @_;
925 my $ssub_id = $args->{ssub_id};
927 my $editor = OpenILS::Utils::CStoreEditor->new();
928 my $ssub = $editor->retrieve_serial_subscription([$ssub_id]);
929 my $sdists = $editor->search_serial_distribution( [{ subscription => $ssub->id }, { flesh => 1, flesh_fields => {sdist => [ qw/ streams / ]} }] ); #TODO: 'deleted' support?
931 return store_predictions(
932 $self, $conn, $authtoken, $args, $ssub, $sdists,
933 make_prediction_values($self, $conn, $authtoken, $args, $ssub, $sdists, $editor)
937 __PACKAGE__->register_method(
938 method => 'make_prediction_values',
939 api_name => 'open-ils.serial.make_prediction_values',
943 desc => 'Receives an ssub id and returns objects that can be used to populate the issuance and item tables',
946 desc => 'Serial Subscription ID',
953 sub make_prediction_values {
954 my ($self, $conn, $authtoken, $args, $ssub, $sdists, $editor) = @_;
955 $logger->debug('make_prediction_values with args: ' . OpenSRF::Utils::JSON->perl2JSON($args));
957 my $ssub_id = $args->{ssub_id};
959 $editor ||= OpenILS::Utils::CStoreEditor->new();
960 $ssub ||= $editor->retrieve_serial_subscription([$ssub_id]);
961 $sdists ||= $editor->search_serial_distribution( [{ subscription => $ssub->id }, { flesh => 1, flesh_fields => {sdist => [ qw/ streams / ]} }] ); #TODO: 'deleted' support?
963 my $scaps = $editor->search_serial_caption_and_pattern({ subscription => $ssub_id, active => 't'});
964 my $mfhd = MFHD->new(MARC::Record->new());
966 my $total_streams = 0;
968 $total_streams += scalar(@{$_->streams});
970 if ($total_streams < 1) {
972 # XXX TODO new event type
973 return new OpenILS::Event(
974 "BAD_PARAMS", note =>
975 "There are no streams to direct items. Can't predict."
981 # XXX TODO new event type
982 return new OpenILS::Event(
983 "BAD_PARAMS", note =>
984 "There are no active caption-and-pattern objects associated " .
985 "with this subscription. Can't predict."
991 foreach my $scap (@$scaps) {
992 my $caption_field = _revive_caption($scap);
993 $caption_field->update('8' => $link_id);
994 my $fake_chron_needed = 0;
995 # if we have missing chron pieces, we will add them later for prediction purposes
996 if (!$caption_field->enumeration_is_chronology) {
997 if (!$caption_field->subfield('i') # no year
998 or !$caption_field->subfield('j')) { # we had a year, but no month or season
999 $fake_chron_needed = '1';
1002 $mfhd->append_fields($caption_field);
1004 'caption' => $caption_field,
1005 'scap_id' => $scap->id,
1006 'include_base_issuance' => $args->{include_base_issuance},
1007 'num_to_predict' => $args->{num_to_predict},
1008 'end_date' => defined $args->{end_date} ?
1009 $_strp_date->parse_datetime($args->{end_date}) : undef
1011 my $predict_from_siss;
1012 if ($args->{base_issuance}) { # predict from a given issuance
1013 $predict_from_siss = $args->{base_issuance};
1014 } else { # default to predicting from last published
1015 my $last_published = $editor->search_serial_issuance([
1016 {'caption_and_pattern' => $scap->id,
1017 'subscription' => $ssub_id},
1018 {limit => 1, order_by => { siss => "date_published DESC" }}]
1020 if ($last_published->[0]) {
1021 $predict_from_siss = $last_published->[0];
1022 unless ($predict_from_siss->holding_code) {
1023 $editor->disconnect;
1024 # XXX TODO new event type
1025 return new OpenILS::Event(
1026 "BAD_PARAMS", note =>
1027 "Last issuance has no holding code. Can't predict."
1031 $editor->disconnect;
1032 # XXX TODO make a new event type instead of hijacking this one
1033 return new OpenILS::Event(
1034 "BAD_PARAMS", note => "No issuance from which to predict!"
1038 $logger->debug('make_prediction_values reviving holdings: ' . OpenSRF::Utils::JSON->perl2JSON($predict_from_siss));
1039 $options->{predict_from} = _revive_holding($predict_from_siss->holding_code, $caption_field, 1); # fresh MFHD Record, so we simply default to 1 for seqno
1040 if ($fake_chron_needed) {
1041 $options->{faked_chron_date} = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($predict_from_siss->date_published));
1043 $logger->debug('make_prediction_values predicting with options: ' . OpenSRF::Utils::JSON->perl2JSON($options));
1044 push( @predictions, _generate_issuance_values($mfhd, $options) );
1048 $logger->debug('make_prediction_values predictions: ' . OpenSRF::Utils::JSON->perl2JSON(\@predictions));
1049 return \@predictions;
1052 sub store_predictions {
1053 my ($self, $conn, $authtoken, $args, $ssub, $sdists, $predictions) = @_;
1056 foreach my $prediction (@$predictions) {
1057 my $issuance = new Fieldmapper::serial::issuance;
1058 $issuance->isnew(1);
1059 $issuance->label($prediction->{label});
1060 $issuance->date_published($prediction->{date_published}->strftime('%F'));
1061 $issuance->holding_code(OpenSRF::Utils::JSON->perl2JSON($prediction->{holding_code}));
1062 $issuance->holding_type($prediction->{holding_type});
1063 $issuance->caption_and_pattern($prediction->{caption_and_pattern});
1064 $issuance->subscription($ssub->id);
1065 push (@issuances, $issuance);
1068 my $evt = fleshed_issuance_alter($self, $conn, $authtoken, \@issuances);
1069 return $evt if ref $evt;
1072 for (my $i = 0; $i < @issuances; $i++) {
1073 my $date_expected = $$predictions[$i]->{date_published}->add(seconds => interval_to_seconds($ssub->expected_date_offset))->strftime('%F');
1074 my $issuance = $issuances[$i];
1075 #$issuance->label(interval_to_seconds($ssub->expected_date_offset));
1076 foreach my $sdist (@$sdists) {
1077 my $streams = $sdist->streams;
1078 foreach my $stream (@$streams) {
1079 my $item = new Fieldmapper::serial::item;
1081 $item->stream($stream->id);
1082 $item->date_expected($date_expected);
1083 $item->issuance($issuance->id);
1084 push (@items, $item);
1088 fleshed_item_alter($self, $conn, $authtoken, \@items); # FIXME: catch events
1093 # _generate_issuance_values() is an initial attempt at a function which can be used
1094 # to populate an issuance table with a list of predicted issues. It accepts
1095 # a hash ref of options initially defined as:
1096 # caption : the caption field to predict on
1097 # num_to_predict : the number of issues you wish to predict
1098 # 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
1100 # The basic method is to first convert to a single holding if compressed, then
1101 # increment the holding and save the resulting values to @issuances.
1103 # returns @issuance_values, an array of hashrefs containing (formatted
1104 # label, formatted chronology date, formatted estimated arrival date, and an
1105 # array ref of holding subfields as (key, value, key, value ...)) (not a hash
1106 # to protect order and possible duplicate keys), and a holding type.
1108 sub _generate_issuance_values {
1109 my ($mfhd, $options) = @_;
1110 my $caption = $options->{caption};
1111 my $scap_id = $options->{scap_id};
1112 my $include_base_issuance = $options->{include_base_issuance};
1113 my $num_to_predict = $options->{num_to_predict};
1114 my $end_date = $options->{end_date};
1115 my $predict_from = $options->{predict_from}; # MFHD::Holding to predict from
1116 my $faked_chron_date = $options->{faked_chron_date}; # serial does not have a (complete) chronology caption, so add one (temporarily) based on this date
1118 $logger->debug('_generate_issuance_values predict_from: ' . OpenSRF::Utils::JSON->perl2JSON($predict_from));
1120 # Only needed for 'real' MFHD records, not our temp records
1121 # my $link_id = $caption->link_id;
1122 # if(!$predict_from) {
1123 # my $htag = $caption->tag;
1124 # $htag =~ s/^85/86/;
1125 # my @holdings = $mfhd->holdings($htag, $link_id);
1126 # my $last_holding = $holdings[-1];
1128 # #if ($last_holding->is_compressed) {
1129 # # $last_holding->compressed_to_last; # convert to last in range
1131 # $predict_from = $last_holding;
1135 $predict_from->notes('public', []);
1136 # add a note marker for system use (?)
1137 $predict_from->notes('private', ['AUTOGEN']);
1139 # our basic method for dealing with 'faked' chronologies will be to add it in, do the predicting, then take it back out
1140 my @faked_subfield_chars;
1141 if ($faked_chron_date) {
1142 my $faked_caption = new MARC::Field($caption->tag, $caption->indicator(1), $caption->indicator(2), $caption->subfields_list);
1144 my %mfhd_chron_labels = ('i' => 'year', 'j' => 'month', 'k' => 'day');
1145 foreach my $subfield_char ('i', 'j', 'k') {
1146 if (!$caption->subfield($subfield_char)) { # if we are missing a piece, add it
1147 push(@faked_subfield_chars, $subfield_char);
1148 my $chron_name = $mfhd_chron_labels{$subfield_char};
1149 $faked_caption->add_subfields($subfield_char => "($chron_name)");
1150 my $method = $mfhd_chron_labels{$subfield_char};
1151 $predict_from->add_subfields($subfield_char => $faked_chron_date->$chron_name);
1154 # because of the way MFHD::Caption and Holding work, it is simplest
1155 # to recreate rather than try to update
1156 $faked_caption = new MFHD::Caption($faked_caption);
1157 $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);
1158 $logger->debug('_generate_issuance_values fake predict_from: ' . OpenSRF::Utils::JSON->perl2JSON($predict_from));
1161 my @predictions = $mfhd->generate_predictions({
1162 'include_base_issuance' => $include_base_issuance,
1163 'base_holding' => $predict_from,
1164 'num_to_predict' => $num_to_predict,
1165 'end_date' => $end_date
1167 $logger->debug('_generate_issuance_values predictions: ' . OpenSRF::Utils::JSON->perl2JSON(\@predictions));
1170 my @issuance_values;
1171 foreach my $prediction (@predictions) {
1172 $pub_date = $_strp_date->parse_datetime($prediction->chron_to_date);
1173 if ($faked_chron_date) { # get rid of the chronology portions and restore original caption
1174 $prediction->delete_subfield(code => \@faked_subfield_chars);
1175 $prediction = new MFHD::Holding($prediction->seqno, new MARC::Field($prediction->tag, $prediction->indicator(1), $prediction->indicator(2), $prediction->subfields_list), $caption);
1181 label => $prediction->format,
1182 date_published => $pub_date,
1183 #date_expected => $date_expected->strftime('%F'),
1184 holding_code => [$prediction->indicator(1),$prediction->indicator(2),$prediction->subfields_list],
1185 holding_type => $MFHD_NAMES_BY_TAG{$caption->tag},
1186 caption_and_pattern => $scap_id
1191 return @issuance_values;
1194 sub _revive_caption {
1197 my $pattern_code = $scap->pattern_code;
1200 my $pattern_parts = OpenSRF::Utils::JSON->JSON2perl($pattern_code);
1201 unshift(@$pattern_parts, $MFHD_TAGS_BY_NAME{$scap->type});
1202 my $pattern_field = new MARC::Field(@$pattern_parts);
1204 # build MFHD::Caption
1205 return new MFHD::Caption($pattern_field);
1208 sub _revive_holding {
1209 my $holding_code = shift;
1210 my $caption_field = shift;
1214 my $holding_parts = OpenSRF::Utils::JSON->JSON2perl($holding_code);
1215 my $captag = $caption_field->tag;
1216 $captag =~ s/^85/86/;
1217 unshift(@$holding_parts, $captag);
1218 my $holding_field = new MARC::Field(@$holding_parts);
1220 # build MFHD::Holding
1221 return new MFHD::Holding($seqno, $holding_field, $caption_field);
1223 # TODO(?) the underlying MARC and the Holding object end up in conflict concerning subfield '8'
1226 __PACKAGE__->register_method(
1227 method => 'unitize_items',
1228 api_name => 'open-ils.serial.receive_items',
1232 desc => 'Marks an item as received, updates the shelving unit (creating a new shelving unit if needed), and updates the summaries',
1235 desc => 'array of serial items',
1240 desc => 'hash of item_ids => barcodes',
1244 name => 'call_numbers',
1245 desc => 'hash of item_ids => call_numbers',
1249 name => 'donor_unit_ids',
1250 desc => 'hash of unit_ids => 1, keyed with ids of any units giving up items',
1255 desc => 'hash of hashes, circ_mod code and copy_location id, keyed as above',
1260 desc => 'Returns number of received items (num_items) and new unit ID, if applicable (new_unit_id)',
1266 __PACKAGE__->register_method(
1267 method => 'unitize_items',
1268 api_name => 'open-ils.serial.bind_items',
1272 desc => 'Marks an item as bound, updates the shelving unit (creating a new shelving unit if needed)',
1275 desc => 'array of serial items',
1280 desc => 'hash of item_ids => barcodes',
1284 name => 'call_numbers',
1285 desc => 'hash of item_ids => call_numbers',
1289 name => 'donor_unit_ids',
1290 desc => 'hash of unit_ids => 1, keyed with ids of any units giving up items',
1295 desc => 'hash of hashes, circ_mod code and copy_location id, keyed as above',
1300 desc => 'Returns number of bound items (num_items) and new unit ID, if applicable (new_unit_id)',
1306 # TODO: reset/delete claims information once implemented
1307 # XXX: deal with emptied call numbers here?
1308 __PACKAGE__->register_method(
1309 method => 'unitize_items',
1310 api_name => 'open-ils.serial.reset_items',
1314 desc => 'Resets the items to Expected, updates the shelving unit (deleting the shelving unit if empty), and updates the summaries',
1317 desc => 'array of serial items',
1322 desc => 'Returns number of reset items (num_items)',
1329 my ($self, $conn, $auth, $items, $barcodes, $call_numbers, $donor_unit_ids, $extras) = @_;
1331 my $editor = new_editor("authtoken" => $auth, "xact" => 1);
1332 return $editor->die_event unless $editor->checkauth;
1333 return $editor->die_event unless $editor->allowed("RECEIVE_SERIAL");
1334 $self->api_name =~ /serial\.(\w*)_items/;
1338 if ($donor_unit_ids) { # units giving up items need updating as well
1339 %found_unit_ids = %$donor_unit_ids;
1341 my %found_stream_ids;
1343 my $prev_loc_setting_map = {};
1345 my %stream_ids_by_unit_id;
1348 my %sdist_by_unit_id;
1349 my %call_number_by_unit_id;
1350 my %sdist_by_stream_id;
1352 my $new_unit_id; # id for '-2' units to share
1353 foreach my $item (@$items) {
1354 # for debugging only, TODO: delete
1355 if (!ref $item) { # hopefully we got an id instead
1356 $item = $editor->retrieve_serial_item($item);
1359 my $unit_id = ref($item->unit) ? $item->unit->id : $item->unit;
1360 my $stream_id = ref($item->stream) ? $item->stream->id : $item->stream;
1361 my $issuance_id = ref($item->issuance) ? $item->issuance->id : $item->issuance;
1362 #TODO: evt on any missing ids
1364 if ($mode eq 'receive') {
1365 $item->date_received('now');
1366 $item->status('Received');
1367 } elsif ($mode eq 'reset') {
1368 # clear date_received
1369 $item->clear_date_received;
1370 # Set status to 'Expected'
1371 $item->status('Expected');
1376 # check for types to trigger summary updates
1378 if (!ref $item->issuance) {
1379 my $scaps = $editor->search_serial_caption_and_pattern([{"+siss" => {"id" => $issuance_id}}, { "join" => {"siss" => {}} }]);
1380 $scap = $scaps->[0];
1381 } elsif (!ref $item->issuance->caption_and_pattern) {
1382 $scap = $editor->retrieve_serial_caption_and_pattern($item->issuance->caption_and_pattern);
1384 $scap = $editor->issuance->caption_and_pattern;
1386 if (!exists($found_types{$stream_id})) {
1387 $found_types{$stream_id} = {};
1389 $found_types{$stream_id}->{$scap->type} = 1 if ($scap);
1391 # create unit if needed
1392 if ($unit_id == -1 or (!$new_unit_id and $unit_id == -2)) { # create unit per item
1394 my $sdists = $editor->search_serial_distribution([
1395 {"+sstr" => {"id" => $stream_id}},
1397 "join" => {"sstr" => {}},
1399 "flesh_fields" => {"sdist" => ["subscription"]}
1401 $unit = _build_unit($editor, $sdists->[0], $mode);
1402 # if _build_unit fails, $unit is an event, so return it
1403 if ($U->event_code($unit)) {
1405 $unit->{"note"} = "Item ID: " . $item->id;
1409 $unit->barcode($barcodes->{$item->id}) if exists($barcodes->{$item->id});
1410 $unit->location($extras->{copy_locations}->{$item->id}) if exists($extras->{copy_locations}->{$item->id});
1411 $unit->circ_modifier($extras->{circ_mods}->{$item->id}) if exists($extras->{circ_mods}->{$item->id});
1413 my $evt = _create_sunit($editor, $unit);
1414 return $evt if $evt;
1415 if ($unit_id == -2) {
1416 $new_unit_id = $unit->id;
1417 $unit_id = $new_unit_id;
1419 $unit_id = $unit->id;
1421 $item->unit($unit_id);
1423 # get unit with 'DEFAULT's and save unit, sdist, and call number for later use
1424 $unit = $editor->retrieve_serial_unit($unit->id);
1425 $unit_map{$unit_id} = $unit;
1426 $sdist_by_unit_id{$unit_id} = $sdists->[0];
1427 $call_number_by_unit_id{$unit_id} = $call_numbers->{$item->id};
1428 $sdist_by_stream_id{$stream_id} = $sdists->[0];
1429 } elsif ($unit_id == -2) { # create one unit for all '-2' items
1430 $unit_id = $new_unit_id;
1431 $item->unit($unit_id);
1434 $found_stream_ids{$stream_id} = 1;
1436 if (defined($unit_id) and $unit_id ne '') {
1437 $found_unit_ids{$unit_id} = 1;
1438 # save the stream_id for this unit_id
1439 # TODO: prevent items from different streams in same unit? (perhaps in interface)
1440 $stream_ids_by_unit_id{$unit_id} = $stream_id;
1445 my $evt = _update_sitem($editor, undef, $item);
1446 return $evt if $evt;
1448 if ($mode eq 'receive') {
1449 my $sdist = $editor->search_serial_distribution([
1450 {"+sstr" => {"id" => $stream_id}},
1452 "join" => {"sstr" => {}},
1454 "flesh_fields" => {"sdist" => ["subscription"]}
1457 #-------------------------------------------------------------------------
1458 # The following is copied from open-ils.serial.receive_items.one_unit_per
1460 # Fetch a list of issuances with received copies already existing
1461 # on this distribution (and with the same holding type on the
1462 # issuance). This will be used in up to two places: once when building
1463 # a summary, once when changing the copy location of the previous
1466 # manually flesh distribution if not present
1468 # this helps maintain compatiblity with XUL serial control receive
1469 if (!ref($item->stream->distribution)) {
1470 $item->stream->distribution($sdist);
1472 my $issuances_received = _issuances_received($editor, $item);
1473 if ($U->event_code($issuances_received)) {
1475 return $issuances_received;
1478 # Find out if we need to to deal with previous copy location changing.
1479 my $ou = $sdist->holding_lib;
1480 unless (exists $prev_loc_setting_map->{$ou}) {
1481 $prev_loc_setting_map->{$ou} = $U->ou_ancestor_setting_value(
1482 $ou, "serial.prev_issuance_copy_location", $editor
1486 # If there is a previous copy location setting, we need the previous
1487 # issuance, from which we can in turn look up the item attached to the
1488 # same stream we're on now.
1489 if ($prev_loc_setting_map->{$ou}) {
1491 _previous_issuance($issuances_received, $item->issuance)) {
1493 # Now we can change the copy location of the previous unit,
1495 return $editor->event if defined $U->event_code(
1497 $editor, $prev_iss, $item, $prev_loc_setting_map->{$ou}
1502 #-------------------------------------------------------------------------
1507 # cleanup 'dead' units (units which are now emptied of their items)
1508 my $dead_units = $editor->search_serial_unit([{'+sitem' => {'id' => undef}, 'deleted' => 'f'}, {'join' => {'sitem' => {'type' => 'left'}}}]);
1509 foreach my $unit (@$dead_units) {
1510 _delete_sunit($editor, undef, $unit);
1511 delete $found_unit_ids{$unit->id};
1514 # deal with unit level contents
1515 foreach my $unit_id (keys %found_unit_ids) {
1517 # get all the needed issuances for unit
1518 # TODO remove 'Bindery' from this search (leaving it in for now for backwards compatibility with any current test environment data)
1519 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"unit" => $unit_id, "status" => ["Received", "Bindery"]}}, {"join" => {"sitem" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1520 #TODO: evt on search failure
1522 # retrieve and update unit contents
1525 my $call_number_string;
1527 # if we just created the unit, we will already have it and the distribution stored, and we will need to assign the call number
1528 if (exists $unit_map{$unit_id}) {
1529 $sunit = $unit_map{$unit_id};
1530 $sdist = $sdist_by_unit_id{$unit_id};
1531 $call_number_string = $call_number_by_unit_id{$unit_id};
1532 $record_id = $sdist->subscription->record_entry;
1534 # XXX: this code assumes you will not have units which mix streams/distributions, but current code does not enforce this
1535 $sunit = $editor->retrieve_serial_unit($unit_id);
1536 if ($stream_ids_by_unit_id{$unit_id}) {
1537 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_ids_by_unit_id{$unit_id}}}, { "join" => {"sstr" => {}}, 'limit' => 1 }]);
1539 $sdist = $editor->search_serial_distribution([
1540 {'+sunit' => {'id' => $unit_id}},
1545 { 'join' => 'sunit' }
1552 $sdist = $sdist->[0];
1555 my $evt = _prepare_unit($editor, $sunit, $sdist, $issuances, $call_number_string, $record_id);
1556 if ($U->event_code($evt)) {
1561 $evt = _update_sunit($editor, undef, $sunit);
1562 if ($U->event_code($evt)) {
1568 if ($mode ne 'bind') { # the summary holdings do not change when binding
1569 # deal with stream level summaries
1570 # summaries will be built from the "primary" stream only, that is, the stream with the lowest ID per distribution
1571 # (TODO: consider direct designation)
1572 my %primary_streams_by_sdist;
1573 my %streams_by_sdist;
1575 # see if we have primary streams, and if so, associate them with their distributions
1576 foreach my $stream_id (keys %found_stream_ids) {
1578 if (exists $sdist_by_stream_id{$stream_id}) {
1579 $sdist = $sdist_by_stream_id{$stream_id};
1581 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
1582 $sdist = $sdist->[0];
1583 $sdist_by_stream_id{$stream_id} = $sdist;
1586 if (!exists($streams_by_sdist{$sdist->id})) {
1587 $streams = $editor->search_serial_stream([{"distribution" => $sdist->id}, {"order_by" => {"sstr" => "id"}}]);
1588 $streams_by_sdist{$sdist->id} = $streams;
1590 $streams = $streams_by_sdist{$sdist->id};
1592 $primary_streams_by_sdist{$sdist->id} = $streams->[0] if ($stream_id == $streams->[0]->id);
1595 # retrieve and update summaries for each affected primary stream's distribution
1596 foreach my $sdist_id (keys %primary_streams_by_sdist) {
1597 my $stream = $primary_streams_by_sdist{$sdist_id};
1598 my $stream_id = $stream->id;
1599 # get all the needed issuances for stream
1600 # FIXME: search in Bindery/Bound/Not Published? as well as Received
1601 foreach my $type (keys %{$found_types{$stream_id}}) {
1602 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"stream" => $stream_id, "status" => "Received"}, "+scap" => {"type" => $type}}, {"join" => {"sitem" => {}, "scap" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1603 #TODO: evt on search failure
1604 my $evt = _prepare_summaries($editor, $issuances, $sdist_by_stream_id{$stream_id}, $type);
1605 if ($U->event_code($evt)) {
1614 return {'num_items' => scalar @$items, 'new_unit_id' => $new_unit_id};
1617 sub _find_or_create_call_number {
1618 my ($e, $lib, $cn_string, $record) = @_;
1620 my ($prefix,$suffix) = ('','');
1621 if (ref($cn_string)) {
1622 ($prefix,$cn_string,$suffix) = @$cn_string;
1625 my $existing = $e->search_asset_call_number([{
1627 label => $cn_string,
1630 '+acnp' => { label => $prefix },
1631 '+acns' => { label => $suffix },
1634 join => { acnp => {}, acns => {} }
1635 }]) or return $e->die_event;
1638 return $existing->[0]->id;
1640 return $e->die_event unless
1641 $e->allowed("CREATE_VOLUME", $lib);
1643 $prefix = -1 if (!$prefix);
1644 $suffix = -1 if (!$suffix);
1646 if ($prefix ne '-1') {
1647 my $acnp = $e->search_asset_call_number_prefix({
1653 $acnp = new Fieldmapper::asset::call_number_prefix;
1654 $acnp->label($prefix);
1655 $acnp->owning_lib($lib);
1656 $e->create_asset_call_number_prefix($acnp) or return $e->die_event;
1657 $prefix = $e->data->id;
1659 $prefix = $acnp->id;
1663 if ($suffix ne '-1') {
1664 my $acns = $e->search_asset_call_number_suffix({
1670 $acns = new Fieldmapper::asset::call_number_suffix;
1671 $acns->label($suffix);
1672 $acns->owning_lib($lib);
1673 $e->create_asset_call_number_suffix($acns) or return $e->die_event;
1674 $suffix = $e->data->id;
1676 $suffix = $acns->id;
1680 my $acn = new Fieldmapper::asset::call_number;
1682 $acn->creator($e->requestor->id);
1683 $acn->editor($e->requestor->id);
1684 $acn->record($record);
1685 $acn->label($cn_string);
1686 $acn->owning_lib($lib);
1687 $acn->prefix($prefix);
1688 $acn->suffix($suffix);
1690 $e->create_asset_call_number($acn) or return $e->die_event;
1691 return $e->data->id;
1695 sub _issuances_received {
1696 # XXX TODO: Add some caching or something. This is getting called
1697 # more often than it has to be.
1698 my ($e, $sitem) = @_;
1700 my $results = $e->json_query({
1701 "select" => {"sitem" => ["issuance"]},
1702 "from" => {"sitem" => {"sstr" => {}, "siss" => {}}},
1704 "+sstr" => {"distribution" => $sitem->stream->distribution->id},
1705 "+siss" => {"holding_type" => $sitem->issuance->holding_type},
1706 "+sitem" => {"date_received" => {"!=" => undef}}
1709 "siss" => {"date_published" => {"direction" => "asc"}}
1711 }) or return $e->die_event;
1715 for my $iss_id (map { $_->{"issuance"} } @$results) {
1716 next if $seen{$iss_id};
1718 push(@$issuances, $e->retrieve_serial_issuance($iss_id));
1723 # _prepare_unit populates the detailed_contents, summary_contents, and
1724 # sort_key fields for a given unit based on a given set of issuances
1725 # Also finds/creates call number as needed
1727 my ($e, $sunit, $sdist, $issuances, $call_number_string, $record_id) = @_;
1729 # Handle call number first if we have one
1730 if ($call_number_string) {
1731 my $org_unit_id = ref $sdist->holding_lib ? $sdist->holding_lib->id : $sdist->holding_lib;
1732 my $real_cn = _find_or_create_call_number(
1734 $call_number_string, $record_id
1737 if ($U->event_code($real_cn)) {
1740 $sunit->call_number($real_cn);
1744 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances);
1745 return $mfhd if $U->event_code($mfhd);
1747 # special case for single formatted_part (may have summarized version)
1748 if (@$formatted_parts == 1) {
1749 #TODO: MFHD.pm should have a 'format_summary' method for this
1752 $sunit->detailed_contents(
1755 $sdist->unit_label_prefix,
1756 join(", ", @$formatted_parts),
1757 $sdist->unit_label_suffix
1761 # TODO: change this when real summary contents are available
1762 $sunit->summary_contents($sunit->detailed_contents);
1764 # Create sort_key by left padding numbers to 6 digits.
1765 (my $sort_key = $sunit->detailed_contents) =~
1766 s/(\d+)/sprintf '%06d', $1/eg;
1767 $sunit->sort_key($sort_key);
1770 # _prepare_summaries populates the generated_coverage field for a given summary
1771 # type ('basic', 'index', 'supplement') for a given distribution.
1772 # It also creates the summary if it doesn't yet exist.
1773 sub _prepare_summaries {
1774 my ($e, $issuances, $sdist, $type) = @_;
1776 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances, $sdist, $type);
1777 return $mfhd if $U->event_code($mfhd);
1779 my $search_method = "search_serial_${type}_summary";
1780 my $summary = $e->$search_method([{"distribution" => $sdist->id}]);
1782 my $cu_method = "update";
1785 $summary = $summary->[0];
1787 my $class = "Fieldmapper::serial::${type}_summary";
1788 $summary = $class->new;
1789 $summary->distribution($sdist->id);
1790 $cu_method = "create";
1793 if (@$formatted_parts) {
1794 $summary->generated_coverage(OpenSRF::Utils::JSON->perl2JSON($formatted_parts));
1796 # we had no issuances or MFHD data for this type, so clear any
1797 # generated data which may have existed before
1798 $summary->generated_coverage('');
1800 my $method = "${cu_method}_serial_${type}_summary";
1801 return $e->die_event unless $e->$method($summary);
1805 __PACKAGE__->register_method(
1806 method => 'regen_summaries',
1807 api_name => 'open-ils.serial.regenerate_summaries',
1811 'desc' => 'Regenerate all the generated_coverage fields for given distributions or subscriptions (depending on params given). Params are expected to be hash members.',
1813 name => 'sdist_ids',
1814 desc => 'IDs of the distribution whose coverage you want to regenerate',
1819 desc => 'IDs of the subscriptions whose coverage you want to regenerate',
1824 desc => 'Returns undef if successful, event if failed',
1827 #TODO: best practices for return values
1831 sub regen_summaries {
1832 my ($self, $conn, $auth, $opts) = @_;
1834 my $e = new_editor("authtoken" => $auth, "xact" => 1);
1835 return $e->die_event unless $e->checkauth;
1836 # Perm checks not necessary since generated_coverage is akin to
1837 # caching of data, not actual editing. XXX This might need more
1839 #return $editor->die_event unless $editor->allowed("RECEIVE_SERIAL");
1841 my $evt = _regenerate_summaries($e, $opts);
1842 if ($U->event_code($evt)) {
1852 sub _regenerate_summaries {
1853 my ($e, $opts) = @_;
1855 $logger->debug('_regenerate_summaries with opts: ' . OpenSRF::Utils::JSON->perl2JSON($opts));
1857 if ($opts->{'ssub_ids'}) {
1858 foreach my $ssub_id (@{$opts->{'ssub_ids'}}) {
1859 my $sdist_ids_temp = $e->search_serial_distribution(
1860 { 'subscription' => $ssub_id },
1863 push(@sdist_ids, @$sdist_ids_temp);
1865 } elsif ($opts->{'sdist_ids'}) {
1866 @sdist_ids = @$opts->{'sdist_ids'};
1869 foreach my $sdist_id (@sdist_ids) {
1871 my $sdist = $e->retrieve_serial_distribution($sdist_id)
1872 or return $e->die_event;
1874 # See large comment below
1875 # my $has_merged_mfhd;
1876 foreach my $type (@MFHD_NAMES) {
1878 my $issuances = $e->search_serial_issuance([
1880 "+sdist" => {"id" => $sdist_id},
1881 "+sitem" => {"status" => "Received"},
1882 "+scap" => {"type" => $type}
1889 "join" => {"sdist" =>{}}
1893 "siss" => "date_published"
1896 ]) or return $e->die_event;
1898 # This level of nuance doesn't appear to be necessary.
1899 # At the moment, we pass down an empty issuance list,
1900 # and the inner methods will "do the right thing" and
1901 # pull in the MFHD if called for, but in some cases not
1902 # ultimately generate any coverage. The code below is
1903 # broken in cases where we delete the last issuance, since
1904 # the now empty summary never gets updated.
1906 # Leaving this code for now (2014/04) in case pushing
1907 # the logic down ends up being too slow or complicates
1908 # the inner methods beyond their scope.
1910 # if (!@$issuances and !$has_merged_mfhd) {
1911 # if (!defined($has_merged_mfhd)) {
1912 # # even without issuances, we can generate a summary
1913 # # from a merged MFHD record, so look for one
1914 # my $mfhd_ids = $e->search_serial_record_entry(
1917 # 'id' => $sdist_id,
1918 # 'summary_method' => 'merge_with_sre'
1922 # 'join' => { 'sdist' => {} },
1926 # if ($mfhd_ids and @$mfhd_ids) {
1927 # $has_merged_mfhd = 1;
1932 # next; # abort to prevent empty summary creation (i.e. '[]')
1935 my $evt = _prepare_summaries($e, $issuances, $sdist, $type);
1936 if ($U->event_code($evt)) {
1946 sub _unit_by_iss_and_str {
1947 my ($e, $issuance, $stream) = @_;
1949 my $unit = $e->json_query({
1950 "select" => {"sunit" => ["id"]},
1951 "from" => {"sitem" => {"sunit" => {}}},
1954 "issuance" => $issuance->id,
1955 "stream" => $stream->id
1958 }) or return $e->die_event;
1959 return 0 if not @$unit;
1961 $e->retrieve_serial_unit($unit->[0]->{"id"}) or $e->die_event;
1964 sub move_previous_unit {
1965 my ($e, $prev_iss, $curr_item, $new_loc) = @_;
1967 my $prev_unit = _unit_by_iss_and_str($e,$prev_iss,$curr_item->stream);
1968 return $prev_unit if defined $U->event_code($prev_unit);
1969 return 0 if not $prev_unit;
1971 if ($prev_unit->location != $new_loc) {
1972 $prev_unit->location($new_loc);
1973 $e->update_serial_unit($prev_unit) or return $e->die_event;
1978 # _previous_issuance() assumes $existing is an ordered array
1979 sub _previous_issuance {
1980 my ($existing, $issuance) = @_;
1982 my $last = $existing->[-1];
1983 return undef unless $last;
1984 return ($last->id == $issuance->id ? $existing->[-2] : $last);
1987 __PACKAGE__->register_method(
1988 "method" => "receive_items_one_unit_per",
1989 "api_name" => "open-ils.serial.receive_items.one_unit_per",
1994 "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",
1998 "desc" => "authtoken",
2003 "desc" => "array of serial items, possibly fleshed with units and definitely fleshed with stream->distribution",
2008 "desc" => "id of bib record these items are associated with
2009 (XXX could/should be derived from items)",
2014 "desc" => "The item ID for each item successfully received",
2020 sub receive_items_one_unit_per {
2021 # XXX This function may be temporary, as it does some of what
2022 # unitize_items() does, just in a different way.
2023 my ($self, $client, $auth, $items, $record) = @_;
2025 my $e = new_editor("authtoken" => $auth, "xact" => 1);
2026 return $e->die_event unless $e->checkauth;
2027 return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
2029 my $prev_loc_setting_map = {};
2030 my $user_id = $e->requestor->id;
2032 # Get a list of all the non-virtual field names in a serial::unit for
2033 # merging given unit objects with template-built units later.
2034 # XXX move this somewhere global so it isn't re-run all the time
2035 my $all_unit_fields =
2036 $Fieldmapper::fieldmap->{"Fieldmapper::serial::unit"}->{"fields"};
2037 my @real_unit_fields = grep {
2038 not $all_unit_fields->{$_}->{"virtual"}
2039 } keys %$all_unit_fields;
2041 foreach my $item (@$items) {
2042 # Note that we expect a certain fleshing on the items we're getting.
2043 my $sdist = $item->stream->distribution;
2045 # Fetch a list of issuances with received copies already existing
2046 # on this distribution (and with the same holding type on the
2047 # issuance). This will be used in up to two places: once when building
2048 # a summary, once when changing the copy location of the previous
2050 my $issuances_received = _issuances_received($e, $item);
2051 if ($U->event_code($issuances_received)) {
2053 return $issuances_received;
2056 # Find out if we need to to deal with previous copy location changing.
2057 my $ou = $sdist->holding_lib->id;
2058 unless (exists $prev_loc_setting_map->{$ou}) {
2059 $prev_loc_setting_map->{$ou} = $U->ou_ancestor_setting_value(
2060 $ou, "serial.prev_issuance_copy_location", $e
2064 # If there is a previous copy location setting, we need the previous
2065 # issuance, from which we can in turn look up the item attached to the
2066 # same stream we're on now.
2067 if ($prev_loc_setting_map->{$ou}) {
2069 _previous_issuance($issuances_received, $item->issuance)) {
2071 # Now we can change the copy location of the previous unit,
2073 return $e->event if defined $U->event_code(
2075 $e, $prev_iss, $item, $prev_loc_setting_map->{$ou}
2081 # Create unit if given by user
2082 if (ref $item->unit) {
2083 # detach from the item, as we need to create separately
2084 my $user_unit = $item->unit;
2086 # get a unit based on associated template
2087 my $template_unit = _build_unit($e, $sdist, "receive");
2088 if ($U->event_code($template_unit)) {
2090 $template_unit->{"note"} = "Item ID: " . $item->id;
2091 return $template_unit;
2094 # merge built unit with provided unit from user
2095 foreach (@real_unit_fields) {
2096 unless ($user_unit->$_) {
2097 $user_unit->$_($template_unit->$_);
2101 # Treat call number specially: the provided value from the
2102 # user will really be a string.
2103 my $call_number_string;
2104 if ($user_unit->call_number) {
2105 $call_number_string = $user_unit->call_number;
2106 # clear call number for now (replaced in _prepare_unit)
2107 $user_unit->clear_call_number;
2110 my $evt = _prepare_unit(
2111 $e, $user_unit, $sdist, [$item->issuance],
2112 $call_number_string, $record
2114 if ($U->event_code($evt)) {
2119 # create/update summary objects related to this distribution
2120 # Make sure @$issuances_received contains current item's issuance
2121 unless (grep { $_->id == $item->issuance->id } @$issuances_received) {
2122 push @$issuances_received, $item->issuance;
2124 $evt = _prepare_summaries($e, $issuances_received, $item->stream->distribution, $item->issuance->holding_type);
2125 if ($U->event_code($evt)) {
2130 # set the incontrovertibles on the unit
2131 $user_unit->edit_date("now");
2132 $user_unit->create_date("now");
2133 $user_unit->editor($user_id);
2134 $user_unit->creator($user_id);
2136 $evt = _create_sunit($e, $user_unit);
2137 return $evt if $evt;
2139 # save reference to new unit
2140 $item->unit($e->data->id);
2143 # Create notes if given by user
2144 if (ref($item->notes) and @{$item->notes}) {
2145 foreach my $note (@{$item->notes}) {
2146 $note->creator($user_id);
2147 $note->create_date("now");
2149 return $e->die_event unless $e->create_serial_item_note($note);
2152 $item->clear_notes; # They're saved; we no longer want them here.
2155 # Set the incontrovertibles on the item
2156 $item->status("Received");
2157 $item->date_received("now");
2158 $item->edit_date("now");
2159 $item->editor($user_id);
2161 return $e->die_event unless $e->update_serial_item($item);
2163 # send client a response
2164 $client->respond($item->id);
2167 $e->commit or return $e->die_event;
2175 #my $skip_call_number = shift;
2177 my $attr = $mode . '_unit_template';
2178 my $template = $editor->retrieve_asset_copy_template($sdist->$attr) or
2179 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_COPY_TEMPLATE");
2181 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 );
2183 my $unit = new Fieldmapper::serial::unit;
2184 foreach my $part (@parts) {
2185 my $value = $template->$part;
2186 next if !defined($value);
2187 $unit->$part($value);
2190 # ignore circ_lib in template, set to distribution holding_lib
2191 $unit->circ_lib($sdist->holding_lib);
2192 $unit->creator($editor->requestor->id);
2193 $unit->editor($editor->requestor->id);
2195 # XXX: this feature has been pushed back until after 2.0 at least
2196 # unless ($skip_call_number) {
2197 # $attr = $mode . '_call_number';
2198 # my $cn = $sdist->$attr or
2199 # return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_CALL_NUMBER");
2201 # $unit->call_number($cn);
2203 $unit->call_number('-1'); # default to the dummy call number
2204 $unit->barcode('@@PLACEHOLDER'); # generic unit will start with a generated placeholder barcode
2205 $unit->sort_key('');
2206 $unit->summary_contents('');
2207 $unit->detailed_contents('');
2212 sub _summarize_contents {
2214 my $issuances = shift;
2218 # create or lookup MFHD record
2220 if ($sdist and defined($sdist->record_entry) and $sdist->summary_method eq 'merge_with_sre') {
2222 if (ref $sdist->record_entry) {
2223 $sre = $sdist->record_entry;
2225 $sre = $editor->retrieve_serial_record_entry($sdist->record_entry);
2227 $mfhd = MFHD->new(MARC::Record->new_from_xml($sre->marc));
2229 $logger->info($sdist);
2230 $mfhd = MFHD->new(MARC::Record->new());
2236 # We keep track of these separately to avoid link_id contamination,
2237 # e.g. a basic issuance, followed by a merging supplement, followed by
2238 # another basic. If we could be sure that they were not mixed, one
2239 # value could suffice.
2240 my %link_ids = ('basic' => 10000, 'index' => 10000, 'supplement' => 10000);
2241 my %first_scap = ('basic' => 1, 'index' => 1, 'supplement' => 1);
2242 foreach my $issuance (@$issuances) {
2243 my $scap_id = $issuance->caption_and_pattern;
2244 next if (!$scap_id); # skip issuances with no caption/pattern
2248 # if this is the first appearance of this scap, retrieve it and add it to the temporary record
2249 if (!exists $scaps{$issuance->caption_and_pattern}) {
2250 $scaps{$scap_id} = $editor->retrieve_serial_caption_and_pattern($scap_id);
2251 $scap = $scaps{$scap_id};
2252 $scap_field = _revive_caption($scap);
2254 if ($first_scap{$scap->type}) { # special merge processing
2255 $first_scap{$MFHD_TAGS_BY_NAME{$scap->type}} = 0;
2256 if ($sdist and $sdist->summary_method eq 'merge_with_sre') {
2257 # MFHD Caption objects do not yet have a built-in compare (TODO), so let's do a basic one
2258 my @field_85xs = $mfhd->field($MFHD_TAGS_BY_NAME{$scap->type});
2260 my $last_caption_field = $field_85xs[-1];
2261 my $last_link_id = $last_caption_field->subfield('8');
2262 # set the link id to match, temporarily, for comparison
2263 $last_caption_field->update('8' => $scap_field->subfield('8'));
2264 my $last_caption_json = OpenSRF::Utils::JSON->perl2JSON([$last_caption_field->indicator(1), $last_caption_field->indicator(2), $last_caption_field->subfields_list]);
2265 if ($last_caption_json eq $scap->pattern_code) { # merge is possible, they match
2267 $link_ids{$scap->type} = $last_link_id;
2268 # set scap_field to last field
2269 $scap_field = $last_caption_field;
2275 $scap_fields{$scap_id} = $scap_field;
2276 $scap_field->update('8' => $link_ids{$scap->type});
2277 # TODO: make MFHD/Caption smarter about this
2278 $scap_field->{_mfhdc_LINK_ID} = $link_ids{$scap->type};
2279 $mfhd->append_fields($scap_field) if !$did_merge;
2280 $link_ids{$scap->type}++;
2282 $scap_field = $scap_fields{$scap_id};
2285 $mfhd->append_fields(_revive_holding($issuance->holding_code, $scap_field, $seqno));
2289 my @formatted_parts;
2290 my @scap_fields_ordered;
2292 @scap_fields_ordered = $mfhd->field($MFHD_TAGS_BY_NAME{$type});
2294 # if they didn't give a type, send back whatever holdings we have.
2295 # this is really only sensible right now for summarizing one type,
2296 # and is used by the unitize code for this purpose
2298 # TODO: possible future support for binding (unitizing) of multiple
2299 # types into a sensible summary string
2300 @scap_fields_ordered = $mfhd->field('85[345]');
2303 foreach my $scap_field (@scap_fields_ordered) { #TODO: use generic MFHD "summarize" method, once available
2304 my @updated_holdings;
2306 @updated_holdings = $mfhd->get_combined_holdings($scap_field);
2309 my $msg = "get_combined_holdings(): $@ ; using sdist ID #" .
2310 ($sdist ? $sdist->id : "<NONE>") . " and " .
2311 scalar(@$issuances) . " issuances, of which one has ID #" .
2312 $issuances->[0]->id;
2315 $logger->error($msg);
2316 return new OpenILS::Event("BAD_PARAMS", note => $msg);
2319 push @formatted_parts, map { $_->format } @updated_holdings;
2322 return ($mfhd, \@formatted_parts);
2325 ##########################################################################
2328 __PACKAGE__->register_method(
2329 method => 'fetch_notes',
2330 api_name => 'open-ils.serial.item_note.retrieve.all',
2332 Returns an array of copy note objects.
2333 @param args A named hash of parameters including:
2334 authtoken : Required if viewing non-public notes
2335 item_id : The id of the item whose notes we want to retrieve
2336 pub : True if all the caller wants are public notes
2337 @return An array of note objects
2341 __PACKAGE__->register_method(
2342 method => 'fetch_notes',
2343 api_name => 'open-ils.serial.subscription_note.retrieve.all',
2345 Returns an array of copy note objects.
2346 @param args A named hash of parameters including:
2347 authtoken : Required if viewing non-public notes
2348 subscription_id : The id of the item whose notes we want to retrieve
2349 pub : True if all the caller wants are public notes
2350 @return An array of note objects
2354 __PACKAGE__->register_method(
2355 method => 'fetch_notes',
2356 api_name => 'open-ils.serial.distribution_note.retrieve.all',
2358 Returns an array of copy note objects.
2359 @param args A named hash of parameters including:
2360 authtoken : Required if viewing non-public notes
2361 distribution_id : The id of the item whose notes we want to retrieve
2362 pub : True if all the caller wants are public notes
2363 @return An array of note objects
2367 # TODO: revisit this method to consider replacing cstore direct calls
2369 my( $self, $connection, $args ) = @_;
2371 $self->api_name =~ /serial\.(\w*)_note/;
2374 my $id = $$args{object_id};
2375 my $authtoken = $$args{authtoken};
2376 my $order_by = $$args{order_by} || 'create_date';
2380 return $U->cstorereq(
2381 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic',
2382 { $type => $id, pub => 't' }, {'order_by' => {$FM_NAME_TO_ID{$type}.'n' => $order_by}} );
2384 # FIXME: restore perm check
2385 # ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
2386 # return $evt if $evt;
2387 return $U->cstorereq(
2388 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic', {$type => $id}, {'order_by' => {$FM_NAME_TO_ID{$type}.'n' => $order_by}} );
2394 __PACKAGE__->register_method(
2395 method => 'update_note',
2396 api_name => 'open-ils.serial.item_note.update',
2398 Updates or creates an item note
2399 @param authtoken The login session key
2400 @param note The note object to update or create
2401 @return The id of the note object
2405 __PACKAGE__->register_method(
2406 method => 'update_note',
2407 api_name => 'open-ils.serial.subscription_note.update',
2409 Updates or creates a subscription note
2410 @param authtoken The login session key
2411 @param note The note object to update or create
2412 @return The id of the note object
2416 __PACKAGE__->register_method(
2417 method => 'update_note',
2418 api_name => 'open-ils.serial.distribution_note.update',
2420 Updates or creates a distribution note
2421 @param authtoken The login session key
2422 @param note The note object to update or create
2423 @return The id of the note object
2428 my( $self, $connection, $authtoken, $note ) = @_;
2430 $self->api_name =~ /serial\.(\w*)_note/;
2433 my $e = new_editor(xact=>1, authtoken=>$authtoken);
2434 return $e->event unless $e->checkauth;
2436 if ($type eq 'item') {
2437 my $sitem = $e->retrieve_serial_item([
2439 "flesh" => 2, "flesh_fields" => {
2440 "sitem" => ["stream"], "sstr" => ["distribution"]
2443 ]) or return $e->die_event;
2445 return $e->die_event unless $e->allowed(
2446 "ADMIN_SERIAL_ITEM", $sitem->stream->distribution->holding_lib
2448 } elsif ($type eq 'distribution') {
2449 my $sdist = $e->retrieve_serial_distribution($note->distribution)
2450 or return $e->die_event;
2452 return $e->die_event unless
2453 $e->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2454 } else { # subscription
2455 my $sub = $e->retrieve_serial_subscription($note->subscription)
2456 or return $e->die_event;
2458 return $e->die_event unless
2459 $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
2462 $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
2465 $note->create_date('now');
2466 $note->creator($e->requestor->id);
2468 $method = "create_serial_${type}_note";
2470 $method = "update_serial_${type}_note";
2472 $e->$method($note) or return $e->event;
2477 __PACKAGE__->register_method(
2478 method => 'delete_note',
2479 api_name => 'open-ils.serial.item_note.delete',
2481 Deletes an existing item note
2482 @param authtoken The login session key
2483 @param noteid The id of the note to delete
2484 @return 1 on success - Event otherwise.
2488 __PACKAGE__->register_method(
2489 method => 'delete_note',
2490 api_name => 'open-ils.serial.subscription_note.delete',
2492 Deletes an existing subscription note
2493 @param authtoken The login session key
2494 @param noteid The id of the note to delete
2495 @return 1 on success - Event otherwise.
2499 __PACKAGE__->register_method(
2500 method => 'delete_note',
2501 api_name => 'open-ils.serial.distribution_note.delete',
2503 Deletes an existing distribution note
2504 @param authtoken The login session key
2505 @param noteid The id of the note to delete
2506 @return 1 on success - Event otherwise.
2511 my( $self, $conn, $authtoken, $noteid ) = @_;
2513 $self->api_name =~ /serial\.(\w*)_note/;
2516 my $e = new_editor(xact=>1, authtoken=>$authtoken);
2517 return $e->die_event unless $e->checkauth;
2519 my $method = "retrieve_serial_${type}_note";
2520 my $note = $e->$method([
2522 ]) or return $e->die_event;
2524 if ($type eq 'item') {
2525 my $sitem = $e->retrieve_serial_item([
2527 "flesh" => 2, "flesh_fields" => {
2528 "sitem" => ["stream"], "sstr" => ["distribution"]
2531 ]) or return $e->die_event;
2533 return $e->die_event unless $e->allowed(
2534 "ADMIN_SERIAL_ITEM", $sitem->stream->distribution->holding_lib
2536 } elsif ($type eq 'distribution') {
2537 my $sdist = $e->retrieve_serial_distribution($note->distribution)
2538 or return $e->die_event;
2540 return $e->die_event unless
2541 $e->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2542 } else { # subscription
2543 my $sub = $e->retrieve_serial_subscription($note->subscription)
2544 or return $e->die_event;
2546 return $e->die_event unless
2547 $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
2550 $method = "delete_serial_${type}_note";
2551 $e->$method($note) or return $e->die_event;
2557 ##########################################################################
2558 # subscription methods
2561 __PACKAGE__->register_method(
2562 method => 'safe_delete',
2563 api_name => 'open-ils.serial.subscription.safe_delete',
2565 Deletes an existing subscription and related records
2566 (distributions, streams, etc.), but only if there are no serial
2567 items with a status other than Expected, and no non-deleted
2569 @param authtoken The login session key
2570 @param subid The id of the subscription to delete
2571 @return 1 on success - Event otherwise.
2575 __PACKAGE__->register_method(
2576 method => 'safe_delete',
2577 api_name => 'open-ils.serial.distribution.safe_delete',
2579 Deletes an existing distribution and related records
2580 (streams, etc.), but only if there are no attached serial items
2581 with a status other than Expected, and no non-deleted serial
2583 @param authtoken The login session key
2584 @param subid The id of the distribution to delete
2585 @return 1 on success - Event otherwise.
2589 __PACKAGE__->register_method(
2590 method => 'safe_delete',
2591 api_name => 'open-ils.serial.stream.safe_delete',
2593 Deletes an existing stream and associated routing list, but only
2594 if there are no attached serial items with a status other than
2595 Expected, and no non-deleted serial units.
2596 items and no issuances.
2597 @param authtoken The login session key
2598 @param strid The id of the stream to delete
2599 @return 1 on success - Event otherwise.
2603 __PACKAGE__->register_method(
2604 method => 'safe_delete',
2605 api_name => 'open-ils.serial.caption_and_pattern.safe_delete',
2607 Deletes an existing caption and pattern object, but only
2608 if there are no attached serial issuances.
2609 @param authtoken The login session key
2610 @param strid The id of the scap to delete
2611 @return 1 on success - Event otherwise.
2615 __PACKAGE__->register_method(
2616 method => 'safe_delete',
2617 api_name => 'open-ils.serial.subscription.safe_delete.dry_run',
2619 __PACKAGE__->register_method(
2620 method => 'safe_delete',
2621 api_name => 'open-ils.serial.distribution.safe_delete.dry_run',
2623 __PACKAGE__->register_method(
2624 method => 'safe_delete',
2625 api_name => 'open-ils.serial.stream.safe_delete.dry_run',
2627 __PACKAGE__->register_method(
2628 method => 'safe_delete',
2629 api_name => 'open-ils.serial.caption_and_pattern.safe_delete.dry_run',
2633 my( $self, $conn, $authtoken, $id ) = @_;
2635 $self->api_name =~ /serial\.(\w*)\.safe_delete/;
2638 my $e = new_editor(xact=>1, authtoken=>$authtoken);
2639 return $e->die_event unless $e->checkauth;
2643 if ($type eq 'stream') {
2644 my $sstr = $e->retrieve_serial_stream([
2646 "flesh" => 2, "flesh_fields" => {
2647 "sstr" => ["items","distribution"],
2651 ]) or return $e->die_event;
2653 return $e->die_event unless $e->allowed(
2654 "ADMIN_SERIAL_STREAM", $sstr->distribution->holding_lib
2657 foreach my $sitem (@{$sstr->items}) {
2658 if ($sitem->status ne 'Expected') {
2659 return $e->die_event(OpenILS::Event->new('SERIAL_STREAM_NOT_EMPTY', payload=>$id));
2661 if ($sitem->unit && !$U->is_true($sitem->unit->deleted)) {
2662 return $e->die_event(OpenILS::Event->new('SERIAL_STREAM_NOT_EMPTY', payload=>$id));
2668 } elsif ($type eq 'distribution') {
2669 my $sdist = $e->retrieve_serial_distribution([
2671 "flesh" => 3, "flesh_fields" => {
2672 "sstr" => ["items"],
2673 "sdist" => ["streams"],
2677 ]) or return $e->die_event;
2679 return $e->die_event unless
2680 $e->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2682 foreach my $sstr (@{$sdist->streams}) {
2683 foreach my $sitem (@{$sstr->items}) {
2684 if ($sitem->status ne 'Expected') {
2685 return $e->die_event(OpenILS::Event->new('SERIAL_DISTRIBUTION_NOT_EMPTY', payload=>$id));
2687 if ($sitem->unit && !$U->is_true($sitem->unit->deleted)) {
2688 return $e->die_event(OpenILS::Event->new('SERIAL_DISTRIBUTION_NOT_EMPTY', payload=>$id));
2695 } elsif ($type eq 'caption_and_pattern') {
2696 my $scap = $e->retrieve_serial_caption_and_pattern([
2698 { flesh => 1, flesh_fields => { scap => ['subscription'] } }
2699 ]) or return $e->die_event;
2701 return $e->die_event unless
2702 $e->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $scap->subscription->owning_lib);
2704 my $issuances = $e->search_serial_issuance([{
2705 caption_and_pattern => $id
2714 foreach my $siss (@$issuances) {
2715 foreach my $sitem (@{$siss->items}) {
2716 if ($sitem->status ne 'Expected') {
2717 return $e->die_event(OpenILS::Event->new('SERIAL_CAPTION_AND_PATTERN_NOT_EMPTY', payload=>$id));
2719 if ($sitem->unit && !$U->is_true($sitem->unit->deleted)) {
2720 return $e->die_event(OpenILS::Event->new('SERIAL_CAPTION_AND_PATTERN_NOT_EMPTY', payload=>$id));
2727 } else { # subscription
2728 my $sub = $e->retrieve_serial_subscription([
2730 "flesh" => 4, "flesh_fields" => {
2731 "ssub" => [qw/distributions issuances/],
2732 "sdist" => [qw/streams/],
2733 "sstr" => ["items"],
2737 ]) or return $e->die_event;
2739 return $e->die_event unless
2740 $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
2742 foreach my $sdist (@{$sub->distributions}) {
2743 foreach my $sstr (@{$sdist->streams}) {
2744 foreach my $sitem (@{$sstr->items}) {
2745 if ($sitem->status ne 'Expected') {
2746 return $e->die_event(OpenILS::Event->new('SERIAL_SUBSCRIPTION_NOT_EMPTY', payload=>$id));
2748 if ($sitem->unit && !$U->is_true($sitem->unit->deleted)) {
2749 return $e->die_event(OpenILS::Event->new('SERIAL_SUBSCRIPTION_NOT_EMPTY', payload=>$id));
2758 if (! ($self->api_name =~ /dry_run/)) {
2759 my $method = "delete_serial_${type}";
2760 $e->$method($obj) or return $e->die_event;
2767 __PACKAGE__->register_method(
2768 method => 'fleshed_ssub_alter',
2769 api_name => 'open-ils.serial.subscription.fleshed.batch.update',
2773 desc => 'Receives an array of one or more subscriptions and updates the database as needed',
2775 name => 'authtoken',
2776 desc => 'Authtoken for current user session',
2780 name => 'subscriptions',
2781 desc => 'Array of fleshed subscriptions',
2787 desc => 'Returns 1 if successful, event if failed',
2793 sub fleshed_ssub_alter {
2794 my( $self, $conn, $auth, $ssubs ) = @_;
2795 return 1 unless ref $ssubs;
2796 my( $reqr, $evt ) = $U->checkses($auth);
2797 return $evt if $evt;
2798 my $editor = new_editor(requestor => $reqr, xact => 1);
2799 my $override = $self->api_name =~ /override/;
2801 for my $ssub (@$ssubs) {
2802 my $owning_lib_id = ref $ssub->owning_lib ? $ssub->owning_lib->id : $ssub->owning_lib;
2803 return $editor->die_event unless
2804 $editor->allowed("ADMIN_SERIAL_SUBSCRIPTION", $owning_lib_id);
2806 my $ssubid = $ssub->id;
2808 if( $ssub->isdeleted ) {
2809 $evt = _delete_ssub( $editor, $override, $ssub);
2810 } elsif( $ssub->isnew ) {
2811 _cleanse_dates($ssub, ['start_date','end_date']);
2812 $evt = _create_ssub( $editor, $ssub );
2814 _cleanse_dates($ssub, ['start_date','end_date']);
2815 $evt = _update_ssub( $editor, $override, $ssub );
2820 $logger->info("fleshed subscription-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2824 $logger->debug("subscription-alter: done updating subscription batch");
2826 $logger->info("fleshed subscription-alter successfully updated ".scalar(@$ssubs)." subscriptions");
2831 my ($editor, $override, $ssub) = @_;
2832 $logger->info("subscription-alter: delete subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2833 my $sdists = $editor->search_serial_distribution(
2834 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2835 my $cps = $editor->search_serial_caption_and_pattern(
2836 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2837 my $sisses = $editor->search_serial_issuance(
2838 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2839 return OpenILS::Event->new(
2840 'SERIAL_SUBSCRIPTION_NOT_EMPTY', payload => $ssub->id ) if (@$sdists or @$cps or @$sisses);
2842 return $editor->event unless $editor->delete_serial_subscription($ssub);
2847 my ($editor, $ssub) = @_;
2849 $logger->info("subscription-alter: new subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2850 return $editor->event unless $editor->create_serial_subscription($ssub);
2855 my ($editor, $override, $ssub) = @_;
2857 $logger->info("subscription-alter: retrieving subscription ".$ssub->id);
2858 my $orig_ssub = $editor->retrieve_serial_subscription($ssub->id);
2860 $logger->info("subscription-alter: original subscription ".OpenSRF::Utils::JSON->perl2JSON($orig_ssub));
2861 $logger->info("subscription-alter: updated subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2862 return $editor->event unless $editor->update_serial_subscription($ssub);
2866 __PACKAGE__->register_method(
2867 method => "fleshed_serial_subscription_retrieve_batch",
2869 api_name => "open-ils.serial.subscription.fleshed.batch.retrieve"
2872 sub fleshed_serial_subscription_retrieve_batch {
2873 my( $self, $client, $ids ) = @_;
2874 # FIXME: permissions?
2875 $logger->info("Fetching fleshed subscriptions @$ids");
2876 return $U->cstorereq(
2877 "open-ils.cstore.direct.serial.subscription.search.atomic",
2880 flesh_fields => {ssub => [ qw/owning_lib notes/ ]}
2884 __PACKAGE__->register_method(
2885 method => "retrieve_sub_tree",
2887 api_name => "open-ils.serial.subscription_tree.retrieve"
2890 __PACKAGE__->register_method(
2891 method => "retrieve_sub_tree",
2892 api_name => "open-ils.serial.subscription_tree.global.retrieve"
2895 sub retrieve_sub_tree {
2897 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2899 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2903 # TODO: permission support
2904 if(!@org_ids and $user_session) {
2906 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2907 @org_ids = ($user_obj->home_ou);
2910 if( $self->api_name =~ /global/ ) {
2911 return _build_subs_list( { record_entry => $docid } ); # TODO: filter for !deleted, or active?
2916 for my $orgid (@org_ids) {
2917 my $subs = _build_subs_list(
2918 { record_entry => $docid, owning_lib => $orgid } );# TODO: filter for !deleted, or active?
2919 push( @all_subs, @$subs );
2928 sub _build_subs_list {
2929 my $search_hash = shift;
2931 #$search_hash->{deleted} = 'f';
2932 my $e = new_editor();
2934 my $subs = $e->search_serial_subscription([$search_hash, { 'order_by' => {'ssub' => 'id'} }]);
2938 for my $sub (@$subs) {
2940 # TODO: filter on !deleted?
2941 my $dists = $e->search_serial_distribution(
2942 [{ subscription => $sub->id }, { 'order_by' => {'sdist' => 'label'} }]
2945 #$dists = [ sort { $a->label cmp $b->label } @$dists ];
2947 $sub->distributions($dists);
2949 # TODO: filter on !deleted?
2950 my $issuances = $e->search_serial_issuance(
2951 [{ subscription => $sub->id }, { 'order_by' => {'siss' => 'label'} }]
2954 #$issuances = [ sort { $a->label cmp $b->label } @$issuances ];
2955 $sub->issuances($issuances);
2957 # TODO: filter on !deleted?
2958 my $scaps = $e->search_serial_caption_and_pattern(
2959 [{ subscription => $sub->id }, { 'order_by' => {'scap' => 'id'} }]
2962 #$scaps = [ sort { $a->id cmp $b->id } @$scaps ];
2963 $sub->scaps($scaps);
2964 push( @built_subs, $sub );
2967 return \@built_subs;
2971 __PACKAGE__->register_method(
2972 method => "subscription_orgs_for_title",
2974 api_name => "open-ils.serial.subscription.retrieve_orgs_by_title"
2977 sub subscription_orgs_for_title {
2978 my( $self, $client, $record_id ) = @_;
2980 my $subs = $U->simple_scalar_request(
2982 "open-ils.cstore.direct.serial.subscription.search.atomic",
2983 { record_entry => $record_id }); # TODO: filter on !deleted?
2985 my $orgs = { map {$_->owning_lib => 1 } @$subs };
2986 return [ keys %$orgs ];
2990 ##########################################################################
2991 # distribution methods
2993 __PACKAGE__->register_method(
2994 method => 'fleshed_sdist_alter',
2995 api_name => 'open-ils.serial.distribution.fleshed.batch.update',
2999 desc => 'Receives an array of one or more distributions and updates the database as needed',
3001 name => 'authtoken',
3002 desc => 'Authtoken for current user session',
3006 name => 'distributions',
3007 desc => 'Array of fleshed distributions',
3013 desc => 'Returns 1 if successful, event if failed',
3019 sub fleshed_sdist_alter {
3020 my( $self, $conn, $auth, $sdists ) = @_;
3021 return 1 unless ref $sdists;
3022 my( $reqr, $evt ) = $U->checkses($auth);
3023 return $evt if $evt;
3024 my $editor = new_editor(requestor => $reqr, xact => 1);
3025 my $override = $self->api_name =~ /override/;
3027 for my $sdist (@$sdists) {
3028 my $holding_lib_id = ref $sdist->holding_lib ? $sdist->holding_lib->id : $sdist->holding_lib;
3029 return $editor->die_event unless
3030 $editor->allowed("ADMIN_SERIAL_DISTRIBUTION", $holding_lib_id);
3032 if( $sdist->isdeleted ) {
3033 $evt = _delete_sdist( $editor, $override, $sdist);
3034 } elsif( $sdist->isnew ) {
3035 $evt = _create_sdist( $editor, $sdist );
3037 $evt = _update_sdist( $editor, $override, $sdist );
3042 $logger->info("fleshed distribution-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
3046 $logger->debug("distribution-alter: done updating distribution batch");
3048 $logger->info("fleshed distribution-alter successfully updated ".scalar(@$sdists)." distributions");
3053 my ($editor, $override, $sdist) = @_;
3054 $logger->info("distribution-alter: delete distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
3055 return $editor->event unless $editor->delete_serial_distribution($sdist);
3060 my ($editor, $sdist) = @_;
3062 $logger->info("distribution-alter: new distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
3063 return $editor->event unless $editor->create_serial_distribution($sdist);
3065 # create summaries too
3066 my $summary = new Fieldmapper::serial::basic_summary;
3067 $summary->distribution($sdist->id);
3068 $summary->generated_coverage('');
3069 return $editor->event unless $editor->create_serial_basic_summary($summary);
3070 $summary = new Fieldmapper::serial::supplement_summary;
3071 $summary->distribution($sdist->id);
3072 $summary->generated_coverage('');
3073 return $editor->event unless $editor->create_serial_supplement_summary($summary);
3074 $summary = new Fieldmapper::serial::index_summary;
3075 $summary->distribution($sdist->id);
3076 $summary->generated_coverage('');
3077 return $editor->event unless $editor->create_serial_index_summary($summary);
3079 # create a starter stream (TODO: reconsider this)
3080 my $stream = new Fieldmapper::serial::stream;
3081 $stream->distribution($sdist->id);
3082 return $editor->event unless $editor->create_serial_stream($stream);
3088 my ($editor, $override, $sdist) = @_;
3090 $logger->info("distribution-alter: retrieving distribution ".$sdist->id);
3091 my $orig_sdist = $editor->retrieve_serial_distribution($sdist->id);
3093 $logger->info("distribution-alter: original distribution ".OpenSRF::Utils::JSON->perl2JSON($orig_sdist));
3094 $logger->info("distribution-alter: updated distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
3095 return $editor->event unless $editor->update_serial_distribution($sdist);
3099 __PACKAGE__->register_method(
3100 method => "fleshed_serial_distribution_retrieve_batch",
3102 api_name => "open-ils.serial.distribution.fleshed.batch.retrieve"
3105 sub fleshed_serial_distribution_retrieve_batch {
3106 my( $self, $client, $ids ) = @_;
3107 # FIXME: permissions?
3108 $logger->info("Fetching fleshed distributions @$ids");
3109 return $U->cstorereq(
3110 "open-ils.cstore.direct.serial.distribution.search.atomic",
3113 flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams notes / ]}
3117 __PACKAGE__->register_method(
3118 method => "retrieve_dist_tree",
3120 api_name => "open-ils.serial.distribution_tree.retrieve"
3123 __PACKAGE__->register_method(
3124 method => "retrieve_dist_tree",
3125 api_name => "open-ils.serial.distribution_tree.global.retrieve"
3128 sub retrieve_dist_tree {
3129 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
3131 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
3135 # TODO: permission support
3136 if(!@org_ids and $user_session) {
3138 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
3139 @org_ids = ($user_obj->home_ou);
3142 my $e = new_editor();
3144 if( $self->api_name =~ /global/ ) {
3145 return $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }},
3147 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 / ]},
3148 order_by => {'sdist' => 'id'},
3149 'join' => {'ssub' => {}}
3151 ]); # TODO: filter for !deleted?
3155 for my $orgid (@org_ids) {
3156 my $dists = $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }, holding_lib => $orgid},
3158 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 / ]},
3159 order_by => {'sdist' => 'id'},
3160 'join' => {'ssub' => {}}
3162 ]); # TODO: filter for !deleted?
3163 push( @all_dists, @$dists ) if $dists;
3173 __PACKAGE__->register_method(
3174 method => "distribution_orgs_for_title",
3176 api_name => "open-ils.serial.distribution.retrieve_orgs_by_title"
3179 sub distribution_orgs_for_title {
3180 my( $self, $client, $record_id ) = @_;
3182 my $dists = $U->cstorereq(
3183 "open-ils.cstore.direct.serial.distribution.search.atomic",
3184 { '+ssub' => { record_entry => $record_id } },
3185 { 'join' => {'ssub' => {}} }); # TODO: filter on !deleted?
3187 my $orgs = { map {$_->holding_lib => 1 } @$dists };
3188 return [ keys %$orgs ];
3192 ##########################################################################
3193 # caption and pattern methods
3195 __PACKAGE__->register_method(
3196 method => 'scap_alter',
3197 api_name => 'open-ils.serial.caption_and_pattern.batch.update',
3201 desc => 'Receives an array of one or more caption and patterns and updates the database as needed',
3203 name => 'authtoken',
3204 desc => 'Authtoken for current user session',
3209 desc => 'Array of caption and patterns',
3215 desc => 'Returns 1 if successful, event if failed',
3222 my( $self, $conn, $auth, $scaps ) = @_;
3223 return 1 unless ref $scaps;
3224 my( $reqr, $evt ) = $U->checkses($auth);
3225 return $evt if $evt;
3226 my $editor = new_editor(requestor => $reqr, xact => 1);
3227 my $override = $self->api_name =~ /override/;
3230 for my $scap (@$scaps) {
3231 if (!exists($found_ssub_ids{$scap->subscription})) {
3232 my $ssub = $editor->retrieve_serial_subscription($scap->subscription) or return $editor->die_event;
3233 return $editor->die_event unless
3234 $editor->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $ssub->owning_lib);
3235 $found_ssub_ids{$scap->subscription} = 1;
3238 if( $scap->isdeleted ) {
3239 $evt = _delete_scap( $editor, $override, $scap);
3240 } elsif( $scap->isnew ) {
3241 $evt = _create_scap( $editor, $scap );
3243 $evt = _update_scap( $editor, $override, $scap );
3248 $logger->info("caption_and_pattern-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
3252 $logger->debug("caption_and_pattern-alter: done updating caption_and_pattern batch");
3254 $logger->info("caption_and_pattern-alter successfully updated ".scalar(@$scaps)." caption_and_patterns");
3259 my ($editor, $override, $scap) = @_;
3260 $logger->info("caption_and_pattern-alter: delete caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
3261 my $sisses = $editor->search_serial_issuance(
3262 { caption_and_pattern => $scap->id }, { limit => 1 } ); #TODO: 'deleted' support?
3263 return OpenILS::Event->new(
3264 'SERIAL_CAPTION_AND_PATTERN_HAS_ISSUANCES', payload => $scap->id ) if (@$sisses);
3266 return $editor->event unless $editor->delete_serial_caption_and_pattern($scap);
3271 my ($editor, $scap) = @_;
3273 $logger->info("caption_and_pattern-alter: new caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
3274 return $editor->event unless $editor->create_serial_caption_and_pattern($scap);
3279 my ($editor, $override, $scap) = @_;
3281 $logger->info("caption_and_pattern-alter: retrieving caption_and_pattern ".$scap->id);
3282 my $orig_scap = $editor->retrieve_serial_caption_and_pattern($scap->id);
3284 $logger->info("caption_and_pattern-alter: original caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($orig_scap));
3285 $logger->info("caption_and_pattern-alter: updated caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
3286 return $editor->event unless $editor->update_serial_caption_and_pattern($scap);
3290 __PACKAGE__->register_method(
3291 method => "serial_caption_and_pattern_retrieve_batch",
3293 api_name => "open-ils.serial.caption_and_pattern.batch.retrieve"
3296 sub serial_caption_and_pattern_retrieve_batch {
3297 my( $self, $client, $ids ) = @_;
3298 $logger->info("Fetching caption_and_patterns @$ids");
3299 return $U->cstorereq(
3300 "open-ils.cstore.direct.serial.caption_and_pattern.search.atomic",
3305 ##########################################################################
3308 __PACKAGE__->register_method(
3309 method => 'sstr_alter',
3310 api_name => 'open-ils.serial.stream.batch.update',
3314 desc => 'Receives an array of one or more streams and updates the database as needed',
3316 name => 'authtoken',
3317 desc => 'Authtoken for current user session',
3322 desc => 'Array of streams',
3328 desc => 'Returns 1 if successful, event if failed',
3335 my( $self, $conn, $auth, $sstrs ) = @_;
3336 return 1 unless ref $sstrs;
3337 my( $reqr, $evt ) = $U->checkses($auth);
3338 return $evt if $evt;
3339 my $editor = new_editor(requestor => $reqr, xact => 1);
3340 my $override = $self->api_name =~ /override/;
3342 my %found_sdist_ids;
3343 for my $sstr (@$sstrs) {
3344 if (!exists($found_sdist_ids{$sstr->distribution})) {
3345 my $sdist = $editor->retrieve_serial_distribution($sstr->distribution) or return $editor->die_event;
3346 return $editor->die_event unless
3347 $editor->allowed("ADMIN_SERIAL_STREAM", $sdist->holding_lib);
3348 $found_sdist_ids{$sstr->distribution} = 1;
3351 if( $sstr->isdeleted ) {
3352 $evt = _delete_sstr( $editor, $override, $sstr);
3353 } elsif( $sstr->isnew ) {
3354 $evt = _create_sstr( $editor, $sstr );
3356 $evt = _update_sstr( $editor, $override, $sstr );
3361 $logger->info("stream-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
3365 $logger->debug("stream-alter: done updating stream batch");
3367 $logger->info("stream-alter successfully updated ".scalar(@$sstrs)." streams");
3372 my ($editor, $override, $sstr) = @_;
3373 $logger->info("stream-alter: delete stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
3374 my $sitems = $editor->search_serial_item(
3375 { stream => $sstr->id }, { limit => 1 } ); #TODO: 'deleted' support?
3376 return OpenILS::Event->new(
3377 'SERIAL_STREAM_HAS_ITEMS', payload => $sstr->id ) if (@$sitems);
3379 return $editor->event unless $editor->delete_serial_stream($sstr);
3384 my ($editor, $sstr) = @_;
3386 $logger->info("stream-alter: new stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
3387 return $editor->event unless $editor->create_serial_stream($sstr);
3392 my ($editor, $override, $sstr) = @_;
3394 $logger->info("stream-alter: retrieving stream ".$sstr->id);
3395 my $orig_sstr = $editor->retrieve_serial_stream($sstr->id);
3397 $logger->info("stream-alter: original stream ".OpenSRF::Utils::JSON->perl2JSON($orig_sstr));
3398 $logger->info("stream-alter: updated stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
3399 return $editor->event unless $editor->update_serial_stream($sstr);
3403 __PACKAGE__->register_method(
3404 method => "serial_stream_retrieve_batch",
3406 api_name => "open-ils.serial.stream.batch.retrieve"
3409 sub serial_stream_retrieve_batch {
3410 my( $self, $client, $ids ) = @_;
3411 $logger->info("Fetching streams @$ids");
3412 return $U->cstorereq(
3413 "open-ils.cstore.direct.serial.stream.search.atomic",
3419 ##########################################################################
3422 __PACKAGE__->register_method(
3423 method => 'sum_alter',
3424 api_name => 'open-ils.serial.basic_summary.batch.update',
3428 desc => 'Receives an array of one or more summaries and updates the database as needed',
3430 name => 'authtoken',
3431 desc => 'Authtoken for current user session',
3436 desc => 'Array of basic summaries',
3442 desc => 'Returns 1 if successful, event if failed',
3448 __PACKAGE__->register_method(
3449 method => 'sum_alter',
3450 api_name => 'open-ils.serial.supplement_summary.batch.update',
3454 desc => 'Receives an array of one or more summaries and updates the database as needed',
3456 name => 'authtoken',
3457 desc => 'Authtoken for current user session',
3462 desc => 'Array of supplement summaries',
3468 desc => 'Returns 1 if successful, event if failed',
3474 __PACKAGE__->register_method(
3475 method => 'sum_alter',
3476 api_name => 'open-ils.serial.index_summary.batch.update',
3480 desc => 'Receives an array of one or more summaries and updates the database as needed',
3482 name => 'authtoken',
3483 desc => 'Authtoken for current user session',
3488 desc => 'Array of index summaries',
3494 desc => 'Returns 1 if successful, event if failed',
3501 my( $self, $conn, $auth, $sums ) = @_;
3502 return 1 unless ref $sums;
3504 $self->api_name =~ /serial\.(\w*)_summary/;
3507 my( $reqr, $evt ) = $U->checkses($auth);
3508 return $evt if $evt;
3509 my $editor = new_editor(requestor => $reqr, xact => 1);
3510 my $override = $self->api_name =~ /override/;
3512 my %found_sdist_ids;
3513 for my $sum (@$sums) {
3514 if (!exists($found_sdist_ids{$sum->distribution})) {
3515 my $sdist = $editor->retrieve_serial_distribution($sum->distribution) or return $editor->die_event;
3516 return $editor->die_event unless
3517 $editor->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
3518 $found_sdist_ids{$sum->distribution} = 1;
3521 # XXX: (for now, at least) summaries should be created/deleted by the distribution functions
3522 if( $sum->isdeleted ) {
3523 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
3524 } elsif( $sum->isnew ) {
3525 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
3527 $evt = _update_sum( $editor, $override, $sum, $type );
3532 $logger->info("${type}_summary-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
3536 $logger->debug("${type}_summary-alter: done updating ${type}_summary batch");
3538 $logger->info("${type}_summary-alter successfully updated ".scalar(@$sums)." ${type}_summaries");
3543 my ($editor, $override, $sum, $type) = @_;
3545 $logger->info("${type}_summary-alter: retrieving ${type}_summary ".$sum->id);
3546 my $retrieve_method = "retrieve_serial_${type}_summary";
3547 my $orig_sum = $editor->$retrieve_method($sum->id);
3549 $logger->info("${type}_summary-alter: original ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($orig_sum));
3550 $logger->info("${type}_summary-alter: updated ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($sum));
3551 my $update_method = "update_serial_${type}_summary";
3552 return $editor->event unless $editor->$update_method($sum);
3556 __PACKAGE__->register_method(
3557 method => "serial_summary_retrieve_batch",
3559 api_name => "open-ils.serial.basic_summary.batch.retrieve"
3562 __PACKAGE__->register_method(
3563 method => "serial_summary_retrieve_batch",
3565 api_name => "open-ils.serial.supplement_summary.batch.retrieve"
3568 __PACKAGE__->register_method(
3569 method => "serial_summary_retrieve_batch",
3571 api_name => "open-ils.serial.index_summary.batch.retrieve"
3574 sub serial_summary_retrieve_batch {
3575 my( $self, $client, $ids ) = @_;
3577 $self->api_name =~ /serial\.(\w*)_summary/;
3580 $logger->info("Fetching ${type}_summaries @$ids");
3581 return $U->cstorereq(
3582 "open-ils.cstore.direct.serial.".$type."_summary.search.atomic",
3588 ##########################################################################
3591 __PACKAGE__->register_method(
3592 "method" => "bre_by_identifier",
3593 "api_name" => "open-ils.serial.biblio.record_entry.by_identifier",
3596 "desc" => "Find instances of biblio.record_entry given a search token" .
3597 " that could be a value for any identifier defined in " .
3598 "config.metabib_field",
3600 {"desc" => "Search token", "type" => "string"},
3601 {"desc" => "Options: require_subscriptions, add_mvr, is_actual_id" .
3602 ", id_list (all boolean)", "type" => "object"}
3605 "desc" => "Any matching BREs, or if the add_mvr option is true, " .
3606 "objects with a 'bre' key/value pair, and an 'mvr' " .
3607 "key-value pair. BREs have subscriptions fleshed on.",
3613 sub bre_by_identifier {
3614 my ($self, $client, $term, $options) = @_;
3616 return new OpenILS::Event("BAD_PARAMS") unless $term;
3619 my $e = new_editor();
3623 if ($options->{"is_actual_id"}) {
3627 $e->search_config_metabib_field({"field_class" => "identifier"})
3628 or return $e->die_event;
3630 my @identifiers = map { $_->name } @$cmf;
3631 my $query = join(" || ", map { "id|$_: $term" } @identifiers);
3633 my $search = create OpenSRF::AppSession("open-ils.search");
3634 my $search_result = $search->request(
3635 "open-ils.search.biblio.multiclass.query.staff", {}, $query
3637 $search->disconnect;
3639 # Un-nest results. They tend to look like [[1],[2],[3]] for some reason.
3640 @ids = map { @{$_}[0] } @{$search_result->{"ids"}};
3647 if ($options->{"id_list"}) {
3649 $client->respond($_) foreach (@ids);
3654 my $bre = $e->search_biblio_record_entry([
3656 "flesh" => 2, "flesh_fields" => {
3657 "bre" => ["subscriptions"],
3658 "ssub" => ["owning_lib"]
3661 ]) or return $e->die_event;
3663 if (@$bre && $options->{"require_subscriptions"}) {
3664 $bre = [ grep { @{$_->subscriptions} } @$bre ];
3669 if (@$bre) { # re-evaluate after possible grep
3670 if ($options->{"add_mvr"}) {
3672 {"bre" => $_, "mvr" => _get_mvr($_->id)}
3675 $client->respond($_) foreach (@$bre);
3682 __PACKAGE__->register_method(
3683 "method" => "get_items_by",
3684 "api_name" => "open-ils.serial.items.receivable.by_subscription",
3687 "desc" => "Return all receivable items under a given subscription",
3689 {"desc" => "Authtoken", "type" => "string"},
3690 {"desc" => "Subscription ID", "type" => "number"},
3693 "desc" => "All receivable items under a given subscription",
3694 "type" => "object", "class" => "sitem"
3699 __PACKAGE__->register_method(
3700 "method" => "get_items_by",
3701 "api_name" => "open-ils.serial.items.receivable.by_issuance",
3704 "desc" => "Return all receivable items under a given issuance",
3706 {"desc" => "Authtoken", "type" => "string"},
3707 {"desc" => "Issuance ID", "type" => "number"},
3710 "desc" => "All receivable items under a given issuance",
3711 "type" => "object", "class" => "sitem"
3716 __PACKAGE__->register_method(
3717 "method" => "get_items_by",
3718 "api_name" => "open-ils.serial.items.by_issuance",
3721 "desc" => "Return all items under a given issuance",
3723 {"desc" => "Authtoken", "type" => "string"},
3724 {"desc" => "Issuance ID", "type" => "number"},
3727 "desc" => "All items under a given issuance",
3728 "type" => "object", "class" => "sitem"
3734 my ($self, $client, $auth, $term, $opts) = @_;
3736 # Not to be used in the json_query, but after limiting by perm check.
3737 $opts = {} unless ref $opts eq "HASH";
3738 $opts->{"limit"} ||= 10000; # some existing users may want all results
3739 $opts->{"offset"} ||= 0;
3740 $opts->{"limit"} = int($opts->{"limit"});
3741 $opts->{"offset"} = int($opts->{"offset"});
3743 my $e = new_editor("authtoken" => $auth);
3744 return $e->die_event unless $e->checkauth;
3746 my $by = ($self->api_name =~ /by_(\w+)$/)[0];
3747 my $receivable = ($self->api_name =~ /receivable/);
3750 "issuance" => {"issuance" => $term},
3751 "subscription" => {"+siss" => {"subscription" => $term}}
3754 my $item_rows = $e->json_query(
3756 "select" => {"sitem" => ["id"], "sdist" => ["holding_lib"]},
3760 "sstr" => {"join" => {"sdist" => {}}}
3764 %{$where{$by}}, $receivable ? ("date_received" => undef) : ()
3766 "order_by" => {"sitem" => ["id"]}
3768 ) or return $e->die_event;
3770 return undef unless @$item_rows;
3774 foreach (@$item_rows) {
3775 last if $returned >= $opts->{"limit"};
3776 next unless $e->allowed("RECEIVE_SERIAL", $_->{"holding_lib"});
3777 if ($skipped < $opts->{"offset"}) {
3783 $e->retrieve_serial_item([
3787 "sitem" => [qw/stream issuance unit creator editor/],
3788 "sstr" => ["distribution"],
3789 "sdist" => ["holding_lib"]
3801 __PACKAGE__->register_method(
3802 "method" => "get_receivable_issuances",
3803 "api_name" => "open-ils.serial.issuances.receivable",
3806 "desc" => "Return all issuances with receivable items given " .
3807 "a subscription ID",
3809 {"desc" => "Authtoken", "type" => "string"},
3810 {"desc" => "Subscription ID", "type" => "number"},
3813 "desc" => "All issuances with receivable items " .
3814 "(but not the items themselves)", "type" => "object"
3819 sub get_receivable_issuances {
3820 my ($self, $client, $auth, $sub_id) = @_;
3822 my $e = new_editor("authtoken" => $auth);
3823 return $e->die_event unless $e->checkauth;
3827 my $issuance_ids = $e->json_query({
3830 {"transform" => "distinct", "column" => "id"},
3834 "from" => {"siss" => "sitem"},
3836 "subscription" => $sub_id,
3837 "+sitem" => {"date_received" => undef}
3840 "siss" => {"date_published" => {"direction" => "asc"}}
3843 }) or return $e->die_event;
3845 $client->respond($e->retrieve_serial_issuance($_->{"id"}))
3846 foreach (@$issuance_ids);
3853 __PACKAGE__->register_method(
3854 "method" => "get_routing_list_users",
3855 "api_name" => "open-ils.serial.routing_list_users.fleshed_and_ordered",
3858 "desc" => "Return all routing list users with reader fleshed " .
3859 "(with card and home_ou) for a given stream ID, sorted by pos",
3861 {"desc" => "Authtoken", "type" => "string"},
3862 {"desc" => "Stream ID (int or array of ints)", "type" => "mixed"},
3865 "desc" => "Stream of routing list users", "type" => "object",
3871 sub get_routing_list_users {
3872 my ($self, $client, $auth, $stream_id) = @_;
3874 my $e = new_editor("authtoken" => $auth);
3875 return $e->die_event unless $e->checkauth;
3877 my $users = $e->search_serial_routing_list_user([
3878 {"stream" => $stream_id}, {
3879 "order_by" => {"srlu" => "pos"},
3882 "srlu" => [qw/reader stream/],
3883 "au" => [qw/card home_ou mailing_address billing_address/],
3884 "sstr" => ["distribution"]
3887 ]) or return $e->die_event;
3889 return undef unless @$users;
3891 # The ADMIN_SERIAL_STREAM permission is used simply to avoid the
3892 # need for any new permission. The context OU will be the same
3893 # for every result of the above query, so we need only check once.
3894 return $e->die_event unless $e->allowed(
3895 "ADMIN_SERIAL_STREAM", $users->[0]->stream->distribution->holding_lib
3900 my @users = map { $_->stream($_->stream->id); $_ } @$users;
3901 @users = sort { $a->stream cmp $b->stream } @users if
3902 ref $stream_id eq "ARRAY";
3904 $client->respond($_) for @users;
3910 __PACKAGE__->register_method(
3911 "method" => "replace_routing_list_users",
3912 "api_name" => "open-ils.serial.routing_list_users.replace",
3914 "desc" => "Replace all routing list users on the specified streams " .
3915 "with those in the list argument",
3917 {"desc" => "Authtoken", "type" => "string"},
3918 {"desc" => "List of srlu objects", "type" => "array"},
3921 "desc" => "event on failure, undef on success"
3926 sub replace_routing_list_users {
3927 my ($self, $client, $auth, $users) = @_;
3929 return undef unless ref $users eq "ARRAY";
3931 if (grep { ref $_ ne "Fieldmapper::serial::routing_list_user" } @$users) {
3932 return new OpenILS::Event("BAD_PARAMS", "note" => "Only srlu objects");
3935 my $e = new_editor("authtoken" => $auth, "xact" => 1);
3936 return $e->die_event unless $e->checkauth;
3938 my %streams_ok = ();
3941 foreach my $user (@$users) {
3942 unless (exists $streams_ok{$user->stream}) {
3943 my $stream = $e->retrieve_serial_stream([
3946 "flesh_fields" => {"sstr" => ["distribution"]}
3948 ]) or return $e->die_event;
3950 "ADMIN_SERIAL_STREAM", $stream->distribution->holding_lib
3951 ) or return $e->die_event;
3953 my $to_delete = $e->search_serial_routing_list_user(
3954 {"stream" => $user->stream}
3955 ) or return $e->die_event;
3958 "Deleting srlu: [" .
3959 join(", ", map { $_->id; } @$to_delete) .
3963 foreach (@$to_delete) {
3964 $e->delete_serial_routing_list_user($_) or
3965 return $e->die_event;
3968 $streams_ok{$user->stream} = 1;
3971 next if $user->isdeleted;
3975 $e->create_serial_routing_list_user($user) or return $e->die_event;
3978 $e->commit or return $e->die_event;
3982 __PACKAGE__->register_method(
3983 "method" => "get_records_with_marc_85x",
3984 "api_name"=>"open-ils.serial.caption_and_pattern.find_legacy_by_bib_record",
3987 "desc" => "Return the specified BRE itself and/or any related SRE ".
3988 "whenever they have 853-855 tags",
3990 {"desc" => "Authtoken", "type" => "string"},
3991 {"desc" => "bib record ID", "type" => "number"},
3994 "desc" => "objects, either bre or sre", "type" => "object"
3999 sub get_records_with_marc_85x { # specifically, 853-855
4000 my ($self, $client, $auth, $bre_id) = @_;
4002 my $e = new_editor("authtoken" => $auth);
4003 return $e->die_event unless $e->checkauth;
4005 my $bre = $e->search_biblio_record_entry([
4006 {"id" => $bre_id, "deleted" => "f"}, {
4008 "flesh_fields" => {"bre" => [qw/creator editor owner/]}
4010 ]) or return $e->die_event;
4012 return undef unless @$bre;
4015 my $record = MARC::Record->new_from_xml($bre->marc);
4016 $client->respond($bre) if $record->field("85[3-5]");
4017 # XXX Is passing a regex to ->field() an abuse of MARC::Record ?
4019 my $sres = $e->search_serial_record_entry([
4020 {"record" => $bre_id, "deleted" => "f"}, {
4022 "flesh_fields" => {"sre" => [qw/creator editor owning_lib/]}
4024 ]) or return $e->die_event;
4028 foreach my $sre (@$sres) {
4029 $client->respond($sre) if
4030 MARC::Record->new_from_xml($sre->marc)->field("85[3-5]");
4036 __PACKAGE__->register_method(
4037 "method" => "create_scaps_from_marcxml",
4038 "api_name" => "open-ils.serial.caption_and_pattern.create_from_records",
4041 "desc" => "Create caption and pattern objects from 853-855 tags " .
4042 "in MARCXML documents",
4044 {"desc" => "Authtoken", "type" => "string"},
4045 {"desc" => "Subscription ID", "type" => "number"},
4046 {"desc" => "list of MARCXML documents as strings",
4050 "desc" => "Newly created caption and pattern objects",
4051 "type" => "object", "class" => "scap"
4056 sub create_scaps_from_marcxml {
4057 my ($self, $client, $auth, $sub_id, $docs) = @_;
4059 return undef unless ref $docs eq "ARRAY";
4061 my $e = new_editor("authtoken" => $auth, "xact" => 1);
4062 return $e->die_event unless $e->checkauth;
4064 # Retrieve the subscription just for perm checking (whether we can create
4065 # scaps at the owning lib).
4066 my $sub = $e->retrieve_serial_subscription($sub_id) or return $e->die_event;
4067 return $e->die_event unless
4068 $e->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $sub->owning_lib);
4070 foreach my $record (map { MARC::Record->new_from_xml($_) } @$docs) {
4071 foreach my $field ($record->field("85[3-5]")) {
4072 my $scap = new Fieldmapper::serial::caption_and_pattern;
4073 $scap->subscription($sub_id);
4074 $scap->type($MFHD_NAMES_BY_TAG{$field->tag});
4075 $scap->pattern_code(
4076 OpenSRF::Utils::JSON->perl2JSON(
4077 [ $field->indicator(1), $field->indicator(2),
4078 map { @$_ } $field->subfields ] # flattens nested array
4081 $e->create_serial_caption_and_pattern($scap) or
4082 return $e->die_event;
4083 $client->respond($e->data);
4087 $e->commit or return $e->die_event;
4091 # All these _clone_foo() functions could possibly have been consolidated into
4092 # one clever function, but it's faster to get things working this way.
4093 sub _clone_subscription {
4094 my ($sub, $bib_id, $e) = @_;
4097 my $new_sub = $sub->clone;
4098 $new_sub->record_entry(int $bib_id) if $bib_id;
4100 $new_sub->clear_distributions;
4101 $new_sub->clear_notes;
4102 $new_sub->clear_scaps;
4104 $e->create_serial_subscription($new_sub) or return $e->die_event;
4106 my $new_sub_id = $e->data->id;
4108 foreach my $dist (@{$sub->distributions}) {
4109 my $r = _clone_distribution($dist, $new_sub_id, $e);
4110 return $r if $U->event_code($r);
4114 foreach my $note (@{$sub->notes}) {
4115 my $r = _clone_subscription_note($note, $new_sub_id, $e);
4116 return $r if $U->event_code($r);
4120 foreach my $scap (@{$sub->scaps}) {
4121 my $r = _clone_caption_and_pattern($scap, $new_sub_id, $e);
4122 return $r if $U->event_code($r);
4128 sub _clone_distribution {
4129 my ($dist, $sub_id, $e) = @_;
4131 my $new_dist = $dist->clone;
4132 $new_dist->clear_id;
4133 $new_dist->clear_notes;
4134 $new_dist->clear_streams;
4135 $new_dist->subscription($sub_id);
4137 $e->create_serial_distribution($new_dist) or return $e->die_event;
4138 my $new_dist_id = $e->data->id;
4141 foreach my $stream (@{$dist->streams}) {
4142 my $r = _clone_stream($stream, $new_dist_id, $e);
4143 return $r if $U->event_code($r);
4146 # clone distribution notes
4147 foreach my $note (@{$dist->notes}) {
4148 my $r = _clone_distribution_note($note, $new_dist_id, $e);
4149 return $r if $U->event_code($r);
4152 return $new_dist_id;
4155 sub _clone_subscription_note {
4156 my ($note, $sub_id, $e) = @_;
4158 my $new_note = $note->clone;
4159 $new_note->clear_id;
4160 $new_note->creator($e->requestor->id);
4161 $new_note->create_date("now");
4162 $new_note->subscription($sub_id);
4164 $e->create_serial_subscription_note($new_note) or return $e->die_event;
4165 return $e->data->id;
4168 sub _clone_caption_and_pattern {
4169 my ($scap, $sub_id, $e) = @_;
4171 my $new_scap = $scap->clone;
4172 $new_scap->clear_id;
4173 $new_scap->subscription($sub_id);
4175 $e->create_serial_caption_and_pattern($new_scap) or return $e->die_event;
4176 return $e->data->id;
4179 sub _clone_distribution_note {
4180 my ($note, $dist_id, $e) = @_;
4182 my $new_note = $note->clone;
4183 $new_note->clear_id;
4184 $new_note->creator($e->requestor->id);
4185 $new_note->create_date("now");
4186 $new_note->distribution($dist_id);
4188 $e->create_serial_distribution_note($new_note) or return $e->die_event;
4189 return $e->data->id;
4193 my ($stream, $dist_id, $e) = @_;
4195 my $new_stream = $stream->clone;
4196 $new_stream->clear_id;
4197 $new_stream->clear_routing_list_users;
4198 $new_stream->distribution($dist_id);
4200 $e->create_serial_stream($new_stream) or return $e->die_event;
4201 my $new_stream_id = $e->data->id;
4203 # clone routing list users
4204 foreach my $user (@{$stream->routing_list_users}) {
4205 my $r = _clone_routing_list_user($user, $new_stream_id, $e);
4206 return $r if $U->event_code($r);
4209 return $new_stream_id;
4212 sub _clone_routing_list_user {
4213 my ($user, $stream_id, $e) = @_;
4215 my $new_user = $user->clone;
4216 $new_user->clear_id;
4217 $new_user->stream($stream_id);
4219 $e->create_serial_routing_list_user($new_user) or return $e->die_event;
4220 return $e->data->id;
4223 __PACKAGE__->register_method(
4224 "method" => "clone_subscription",
4225 "api_name" => "open-ils.serial.subscription.clone",
4227 "desc" => q{Clone a subscription, including its attending distributions,
4228 streams, captions and patterns, routing list users, distribution
4229 notes and subscription notes. Do not include holdings-specific
4230 things, like issuances, items, units, summaries. Attach the
4231 clone either to the same bib record as the original, or to one
4234 {"desc" => "Authtoken", "type" => "string"},
4235 {"desc" => "Subscription ID", "type" => "number"},
4236 {"desc" => "Bib Record ID (optional)", "type" => "number"}
4239 "desc" => "ID of the new subscription", "type" => "number"
4244 sub clone_subscription {
4245 my ($self, $client, $auth, $sub_id, $bib_id) = @_;
4247 my $e = new_editor("authtoken" => $auth, "xact" => 1);
4248 return $e->die_event unless $e->checkauth;
4250 my $sub = $e->retrieve_serial_subscription([
4254 "ssub" => [qw/distributions notes scaps/],
4255 "sdist" => [qw/streams notes/],
4256 "sstr" => ["routing_list_users"]
4259 ]) or return $e->die_event;
4261 # ADMIN_SERIAL_SUBSCRIPTION will have to be good enough as a
4262 # catch-all permisison for this operation.
4263 return $e->die_event unless
4264 $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
4266 my $result = _clone_subscription($sub, $bib_id, $e);
4268 return $e->die_event($result) if $U->event_code($result);
4270 $e->commit or return $e->die_event;
4274 __PACKAGE__->register_method(
4275 "method" => "summary_test",
4276 "api_name" => "open-ils.serial.summary_test",
4282 # This crummy little test method allows quicker reproduction of certain
4283 # failures (e.g. at item receive time) of the holdings summarization code.
4284 # Pass it an authtoken, an array of issuance IDs, and a single sdist ID
4286 my ($self, $conn, $authtoken, $iss_id_list, $sdist_id) = @_;
4288 my $e = new_editor(authtoken => $authtoken, xact => 1);
4289 return $e->die_event unless $e->checkauth;
4290 return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
4293 foreach my $id (@$iss_id_list) {
4294 my $iss = $e->retrieve_serial_issuance($id) or return $e->die_event;
4295 push @issuances, $iss;
4298 my $dist = $e->retrieve_serial_distribution($sdist_id) or return $e->die_event;
4300 $conn->respond(_summarize_contents($e, \@issuances, $dist));
4305 __PACKAGE__->register_method(
4306 "method" => "fetch_pattern_templates",
4307 "api_name" => "open-ils.serial.pattern_template.retrieve.at",
4310 "desc" => q{Return the set of pattern templates that are
4311 visible to the specified library.},
4313 {"desc" => "Authtoken", "type" => "string"},
4314 {"desc" => "OU ID", "type" => "number"},
4317 desc => "stream of pattern templates",
4318 type => "object", class => "spt"
4323 sub fetch_pattern_templates {
4324 my ($self, $client, $auth, $org_unit) = @_;
4326 my $e = new_editor("authtoken" => $auth);
4327 return $e->die_event unless $e->checkauth;
4329 my $patterns = $e->json_query({
4330 from => [ 'serial.pattern_templates_visible_to' => $org_unit ]
4332 $logger->info(Dumper($patterns)); use Data::Dumper;
4334 $client->respond($e->retrieve_serial_pattern_template($_->{id}))
4335 foreach (@$patterns);