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');
53 my $U = 'OpenILS::Application::AppUtils';
54 my @MFHD_NAMES = ('basic','supplement','index');
55 my %MFHD_NAMES_BY_TAG = ( '853' => $MFHD_NAMES[0],
56 '863' => $MFHD_NAMES[0],
57 '854' => $MFHD_NAMES[1],
58 '864' => $MFHD_NAMES[1],
59 '855' => $MFHD_NAMES[2],
60 '865' => $MFHD_NAMES[2] );
61 my %MFHD_TAGS_BY_NAME = ( $MFHD_NAMES[0] => '853',
62 $MFHD_NAMES[1] => '854',
63 $MFHD_NAMES[2] => '855');
64 my $_strp_date = new DateTime::Format::Strptime(pattern => '%F');
66 # helper method for conforming dates to ISO8601
71 foreach my $field (@$fields) {
72 $item->$field(OpenSRF::Utils::clense_ISO8601($item->$field)) if $item->$field;
80 "open-ils.search.biblio.record.mods_slim.retrieve",
86 ##########################################################################
89 __PACKAGE__->register_method(
90 method => "create_item_safely",
91 api_name => "open-ils.serial.item.create",
96 desc => q/Creates any number of items, respecting only a few of the
97 submitted fields, as the user shouldn't be able to freely set certain
100 {name=> "authtoken", desc => "Authtoken for current user session",
102 {name => "item", desc => "serial item",
103 type => "object", class => "sitem"},
105 desc => "optional: how many items to make " .
106 "(default 1; 1-100 permitted)",
110 desc => "created items (a stream of them)",
111 type => "object", class => "sitem"
115 __PACKAGE__->register_method(
116 method => "update_item_safely",
117 api_name => "open-ils.serial.item.update",
122 desc => q/Edit a serial item, respecting only a few of the
123 submitted fields, as the user shouldn't be able to freely set certain
126 {name=> "authtoken", desc => "Authtoken for current user session",
128 {name => "item", desc => "serial item",
129 type => "object", class => "sitem"},
132 desc => "created item", type => "object", class => "sitem"
137 sub _set_safe_item_fields {
140 my $requestor_id = shift;
141 # extra fields remain in @_
143 $dest->edit_date("now");
144 $dest->editor($requestor_id);
146 my @fields = qw/date_expected date_received status/;
148 for my $field (@fields, @_) {
149 $dest->$field($source->$field);
153 sub update_item_safely {
154 my ($self, $client, $auth, $item) = @_;
156 my $e = new_editor("xact" => 1, "authtoken" => $auth);
157 $e->checkauth or return $e->die_event;
159 my $orig = $e->retrieve_serial_item([
161 "flesh" => 2, "flesh_fields" => {
162 "sitem" => ["stream"], "sstr" => ["distribution"]
165 ]) or return $e->die_event;
167 return $e->die_event unless $e->allowed(
168 "ADMIN_SERIAL_ITEM", $orig->stream->distribution->holding_lib
171 _set_safe_item_fields($orig, $item, $e->requestor->id);
172 $e->update_serial_item($orig) or return $e->die_event;
174 $client->respond($e->retrieve_serial_item($item->id));
175 $e->commit or return $e->die_event;
179 sub create_item_safely {
180 my ($self, $client, $auth, $item, $count) = @_;
184 return new OpenILS::Event(
185 "BAD_PARAMS", note => "Count should be from 1 to 100"
186 ) unless $count >= 1 and $count <= 100;
188 my $e = new_editor("xact" => 1, "authtoken" => $auth);
189 $e->checkauth or return $e->die_event;
191 my $stream = $e->retrieve_serial_stream([
193 "flesh" => 1, "flesh_fields" => {"sstr" => ["distribution"]}
195 ]) or return $e->die_event;
197 return $e->die_event unless $e->allowed(
198 "ADMIN_SERIAL_ITEM", $stream->distribution->holding_lib
201 for (my $i = 0; $i < $count; $i++) {
202 my $actual = new Fieldmapper::serial::item;
203 $actual->creator($e->requestor->id);
204 _set_safe_item_fields(
205 $actual, $item, $e->requestor->id, "issuance", "stream"
208 $e->create_serial_item($actual) or return $e->die_event;
209 $client->respond($e->data);
212 $e->commit or return $e->die_event;
216 __PACKAGE__->register_method(
217 method => 'fleshed_item_alter',
218 api_name => 'open-ils.serial.item.fleshed.batch.update',
222 desc => 'Receives an array of one or more items and updates the database as needed',
225 desc => 'Authtoken for current user session',
230 desc => 'Array of fleshed items',
236 desc => 'Returns 1 if successful, event if failed',
242 sub fleshed_item_alter {
243 my( $self, $conn, $auth, $items ) = @_;
244 return 1 unless ref $items;
245 my( $reqr, $evt ) = $U->checkses($auth);
247 my $editor = new_editor(requestor => $reqr, xact => 1);
248 my $override = $self->api_name =~ /override/;
250 # TODO: permission check
251 # return $editor->event unless
252 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
254 for my $item (@$items) {
256 my $itemid = $item->id;
257 $item->editor($editor->requestor->id);
258 $item->edit_date('now');
260 if( $item->isdeleted ) {
261 $evt = _delete_sitem( $editor, $override, $item);
262 } elsif( $item->isnew ) {
263 # TODO: reconsider this
264 # if the item has a new issuance, create the issuance first
265 if (ref $item->issuance eq 'Fieldmapper::serial::issuance' and $item->issuance->isnew) {
266 fleshed_issuance_alter($self, $conn, $auth, [$item->issuance]);
268 _cleanse_dates($item, ['date_expected','date_received']);
269 $evt = _create_sitem( $editor, $item );
271 _cleanse_dates($item, ['date_expected','date_received']);
272 $evt = _update_sitem( $editor, $override, $item );
277 $logger->info("fleshed item-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
281 $logger->debug("item-alter: done updating item batch");
283 $logger->info("fleshed item-alter successfully updated ".scalar(@$items)." items");
288 my ($editor, $override, $item) = @_;
289 $logger->info("item-alter: delete item ".OpenSRF::Utils::JSON->perl2JSON($item));
290 return $editor->event unless $editor->delete_serial_item($item);
295 my ($editor, $item) = @_;
297 $item->creator($editor->requestor->id);
298 $item->create_date('now');
300 $logger->info("item-alter: new item ".OpenSRF::Utils::JSON->perl2JSON($item));
301 return $editor->event unless $editor->create_serial_item($item);
306 my ($editor, $override, $item) = @_;
308 $logger->info("item-alter: retrieving item ".$item->id);
309 my $orig_item = $editor->retrieve_serial_item($item->id);
311 $logger->info("item-alter: original item ".OpenSRF::Utils::JSON->perl2JSON($orig_item));
312 $logger->info("item-alter: updated item ".OpenSRF::Utils::JSON->perl2JSON($item));
313 return $editor->event unless $editor->update_serial_item($item);
317 __PACKAGE__->register_method(
318 method => "fleshed_serial_item_retrieve_batch",
320 api_name => "open-ils.serial.item.fleshed.batch.retrieve"
323 sub fleshed_serial_item_retrieve_batch {
324 my( $self, $client, $ids ) = @_;
325 # FIXME: permissions?
326 $logger->info("Fetching fleshed serial items @$ids");
327 return $U->cstorereq(
328 "open-ils.cstore.direct.serial.item.search.atomic",
331 flesh_fields => {sitem => [ qw/issuance creator editor stream unit notes/ ], sstr => ["distribution"], sunit => ["call_number"], siss => [qw/creator editor subscription/]}
336 ##########################################################################
339 __PACKAGE__->register_method(
340 method => 'fleshed_issuance_alter',
341 api_name => 'open-ils.serial.issuance.fleshed.batch.update',
345 desc => 'Receives an array of one or more issuances and updates the database as needed',
348 desc => 'Authtoken for current user session',
353 desc => 'Array of fleshed issuances',
359 desc => 'Returns 1 if successful, event if failed',
365 sub fleshed_issuance_alter {
366 my( $self, $conn, $auth, $issuances ) = @_;
367 return 1 unless ref $issuances;
368 my( $reqr, $evt ) = $U->checkses($auth);
370 my $editor = new_editor(requestor => $reqr, xact => 1);
371 my $override = $self->api_name =~ /override/;
373 # TODO: permission support
374 # return $editor->event unless
375 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
377 for my $issuance (@$issuances) {
378 my $issuanceid = $issuance->id;
379 $issuance->editor($editor->requestor->id);
380 $issuance->edit_date('now');
382 if( $issuance->isdeleted ) {
383 $evt = _delete_siss( $editor, $override, $issuance);
384 } elsif( $issuance->isnew ) {
385 _cleanse_dates($issuance, ['date_published']);
386 $evt = _create_siss( $editor, $issuance );
388 _cleanse_dates($issuance, ['date_published']);
389 $evt = _update_siss( $editor, $override, $issuance );
394 $logger->info("fleshed issuance-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
398 $logger->debug("issuance-alter: done updating issuance batch");
400 $logger->info("fleshed issuance-alter successfully updated ".scalar(@$issuances)." issuances");
405 my ($editor, $override, $issuance) = @_;
406 $logger->info("issuance-alter: delete issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
407 return $editor->event unless $editor->delete_serial_issuance($issuance);
412 my ($editor, $issuance) = @_;
414 $issuance->creator($editor->requestor->id);
415 $issuance->create_date('now');
417 $logger->info("issuance-alter: new issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
418 return $editor->event unless $editor->create_serial_issuance($issuance);
423 my ($editor, $override, $issuance) = @_;
425 $logger->info("issuance-alter: retrieving issuance ".$issuance->id);
426 my $orig_issuance = $editor->retrieve_serial_issuance($issuance->id);
428 $logger->info("issuance-alter: original issuance ".OpenSRF::Utils::JSON->perl2JSON($orig_issuance));
429 $logger->info("issuance-alter: updated issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
430 return $editor->event unless $editor->update_serial_issuance($issuance);
434 __PACKAGE__->register_method(
435 method => "fleshed_serial_issuance_retrieve_batch",
437 api_name => "open-ils.serial.issuance.fleshed.batch.retrieve"
440 sub fleshed_serial_issuance_retrieve_batch {
441 my( $self, $client, $ids ) = @_;
442 # FIXME: permissions?
443 $logger->info("Fetching fleshed serial issuances @$ids");
444 return $U->cstorereq(
445 "open-ils.cstore.direct.serial.issuance.search.atomic",
448 flesh_fields => {siss => [ qw/creator editor subscription/ ]}
452 __PACKAGE__->register_method(
453 method => "pub_fleshed_serial_issuance_retrieve_batch",
454 api_name => "open-ils.serial.issuance.pub_fleshed.batch.retrieve",
457 Public (i.e. OPAC) call for getting at the sub and
458 ultimately the record entry from an issuance
460 params => [{name => 'ids', desc => 'Array of IDs', type => 'array'}],
463 issuance objects, fleshed with subscriptions
469 sub pub_fleshed_serial_issuance_retrieve_batch {
470 my( $self, $client, $ids ) = @_;
471 return [] unless $ids and @$ids;
472 return new_editor()->search_serial_issuance([
476 flesh_fields => {siss => [ qw/subscription/ ]}
481 sub received_siss_by_bib {
486 my $args = shift || {};
487 $$args{order} ||= 'asc';
489 my $global = $$args{global} == 0 ? 0 : 1;
491 my $e = new_editor();
492 my $issuances = $e->json_query({
495 $global ? { transform => "min", column => "id", aggregate => 1 } : "id",
500 # We're not really interested in the minimum here. This is
501 # just a way to distinguish issuances whose items have units
502 # from issuances whose items have no units, without altogether
503 # excluding the latter type of issuances.
504 {"transform" => "min", "alias" => "has_units",
505 "column" => "unit", "aggregate" => 1}
511 field => 'subscription',
517 $$args{ou} ? ( join => {
524 fkey => 'distribution'
535 '+ssub' => { record_entry => $bib },
536 $$args{type} ? ( '+siss' => { 'holding_type' => $$args{type} } ) : (),
538 # XXX should we also take specific item statuses into account?
539 date_received => { '!=' => undef },
540 $$args{status} ? ( 'status' => $$args{status} ) : ()
542 $$args{ou} ? ( '+sdist' => {
544 'in' => $U->get_org_descendants($$args{ou}, $$args{depth})
548 $$args{limit} ? ( limit => $$args{limit} ) : (),
549 $$args{offset} ? ( offset => $$args{offset} ) : (),
550 order_by => [{ class => 'siss', field => 'date_published', direction => $$args{order} }],
555 "issuance" => $e->retrieve_serial_issuance($_->{"id"}),
556 "has_units" => $_->{"has_units"} ? 1 : 0
561 __PACKAGE__->register_method(
562 method => 'received_siss_by_bib',
563 api_name => 'open-ils.serial.received_siss.retrieve.by_bib',
568 desc => 'Receives a Bib ID and other optional params and returns "siss" (issuance) objects',
571 desc => 'id of the bre to which the issuances belong',
576 q/A hash of optional arguments. Valid keys and their meanings:
577 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).
578 order := date_published sort direction, either "asc" (chronological, default) or "desc" (reverse chronological)
579 limit := Number of issuances to return. Useful for paging results, or finding the oldest or newest
580 offset := Number of issuance to skip before returning results. Useful for paging.
581 orgid := OU id used to scope retrieval, based on distribution.holding_lib
582 depth := OU depth used to range the scope of orgid
583 type := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
584 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).
592 sub scoped_bib_holdings_summary {
596 my $args = shift || {};
598 $args->{order} = 'asc';
600 my ($issuances) = $self->method_lookup('open-ils.serial.received_siss.retrieve.by_bib.atomic')->run( $bibid => $args );
602 # split into issuance type sets
603 my %type_blob = (basic => [], supplement => [], index => []);
604 push @{ $type_blob{ $_->{"issuance"}->holding_type } }, $_->{"issuance"}
607 # generate a statement list for each type
609 for my $type ( keys %type_blob ) {
610 my ($mfhd,$list) = _summarize_contents(new_editor(), $type_blob{$type});
611 $statement_blob{$type} = $list;
614 return \%statement_blob;
616 __PACKAGE__->register_method(
617 method => 'scoped_bib_holdings_summary',
618 api_name => 'open-ils.serial.bib.summary_statements',
622 desc => 'Receives a Bib ID and other optional params and returns set of holdings statements',
625 desc => 'id of the bre to which the issuances belong',
630 q/A hash of optional arguments. Valid keys and their meanings:
631 orgid := OU id used to scope retrieval, based on distribution.holding_lib
632 depth := OU depth used to range the scope of orgid
633 type := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
634 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).
642 ##########################################################################
645 __PACKAGE__->register_method(
646 method => 'fleshed_sunit_alter',
647 api_name => 'open-ils.serial.sunit.fleshed.batch.update',
651 desc => 'Receives an array of one or more Units and updates the database as needed',
654 desc => 'Authtoken for current user session',
659 desc => 'Array of fleshed Units',
665 desc => 'Returns 1 if successful, event if failed',
671 sub fleshed_sunit_alter {
672 my( $self, $conn, $auth, $sunits ) = @_;
673 return 1 unless ref $sunits;
674 my( $reqr, $evt ) = $U->checkses($auth);
676 my $editor = new_editor(requestor => $reqr, xact => 1);
677 my $override = $self->api_name =~ /override/;
679 # TODO: permission support
680 # return $editor->event unless
681 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
683 for my $sunit (@$sunits) {
684 if( $sunit->isdeleted ) {
685 $evt = _delete_sunit( $editor, $override, $sunit );
687 $sunit->default_location( $sunit->default_location->id ) if ref $sunit->default_location;
689 if( $sunit->isnew ) {
690 $evt = _create_sunit( $editor, $sunit );
692 $evt = _update_sunit( $editor, $override, $sunit );
698 $logger->info("fleshed sunit-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
702 $logger->debug("sunit-alter: done updating sunit batch");
704 $logger->info("fleshed sunit-alter successfully updated ".scalar(@$sunits)." Units");
709 my ($editor, $override, $sunit) = @_;
710 $logger->info("sunit-alter: delete sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
711 return $editor->event unless $editor->delete_serial_unit($sunit);
716 my ($editor, $sunit) = @_;
718 $logger->info("sunit-alter: new Unit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
719 return $editor->event unless $editor->create_serial_unit($sunit);
724 my ($editor, $override, $sunit) = @_;
726 $logger->info("sunit-alter: retrieving sunit ".$sunit->id);
727 my $orig_sunit = $editor->retrieve_serial_unit($sunit->id);
729 $logger->info("sunit-alter: original sunit ".OpenSRF::Utils::JSON->perl2JSON($orig_sunit));
730 $logger->info("sunit-alter: updated sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
731 return $editor->event unless $editor->update_serial_unit($sunit);
735 __PACKAGE__->register_method(
736 method => "retrieve_unit_list",
738 api_name => "open-ils.serial.unit_list.retrieve"
741 sub retrieve_unit_list {
743 my( $self, $client, @sdist_ids ) = @_;
745 if(ref($sdist_ids[0])) { @sdist_ids = @{$sdist_ids[0]}; }
747 my $e = new_editor();
751 { 'sunit' => [ 'id', 'summary_contents', 'sort_key' ],
752 'sitem' => ['stream'],
753 'sstr' => ['distribution'],
754 'sdist' => [{'column' => 'label', 'alias' => 'sdist_label'}]
761 { 'join' => { 'sunit' => {} } }
766 'distinct' => 'true',
767 'where' => { '+sdist' => {'id' => \@sdist_ids} },
768 'order_by' => [{'class' => 'sunit', 'field' => 'sort_key'}]
771 my $unit_list_entries = $e->json_query($query);
774 foreach my $entry (@$unit_list_entries) {
775 my $value = {'sunit' => $entry->{id}, 'sstr' => $entry->{stream}, 'sdist' => $entry->{distribution}};
776 my $label = $entry->{summary_contents};
777 if (length($label) > 100) {
778 $label = substr($label, 0, 100) . '...'; # limited space in dropdown / menu
780 $label = "[$entry->{sdist_label}/$entry->{stream} #$entry->{id}] " . $label;
781 push (@entries, [$label, OpenSRF::Utils::JSON->perl2JSON($value)]);
789 ##########################################################################
790 # predict and receive methods
792 __PACKAGE__->register_method(
793 method => 'make_predictions',
794 api_name => 'open-ils.serial.make_predictions',
798 desc => 'Receives an ssub id and populates the issuance and item tables',
801 desc => 'Serial Subscription ID',
808 sub make_predictions {
809 my ($self, $conn, $authtoken, $args) = @_;
811 my $editor = OpenILS::Utils::CStoreEditor->new();
812 my $ssub_id = $args->{ssub_id};
813 my $mfhd = MFHD->new(MARC::Record->new());
815 my $ssub = $editor->retrieve_serial_subscription([$ssub_id]);
816 my $scaps = $editor->search_serial_caption_and_pattern({ subscription => $ssub_id, active => 't'});
817 my $sdists = $editor->search_serial_distribution( [{ subscription => $ssub->id }, { flesh => 1, flesh_fields => {sdist => [ qw/ streams / ]} }] ); #TODO: 'deleted' support?
819 my $total_streams = 0;
821 $total_streams += scalar(@{$_->streams});
823 if ($total_streams < 1) {
825 # XXX TODO new event type
826 return new OpenILS::Event(
827 "BAD_PARAMS", note =>
828 "There are no streams to direct items. Can't predict."
834 # XXX TODO new event type
835 return new OpenILS::Event(
836 "BAD_PARAMS", note =>
837 "There are no active caption-and-pattern objects associated " .
838 "with this subscription. Can't predict."
844 foreach my $scap (@$scaps) {
845 my $caption_field = _revive_caption($scap);
846 $caption_field->update('8' => $link_id);
847 my $using_fake_chron = 0;
848 # if we have no chronology, add one for prediction puposes
849 if (!$caption_field->subfield('i') and !$caption_field->enumeration_is_chronology) {
850 $using_fake_chron = 1;
852 $mfhd->append_fields($caption_field);
854 'caption' => $caption_field,
855 'scap_id' => $scap->id,
856 'num_to_predict' => $args->{num_to_predict},
857 'end_date' => defined $args->{end_date} ?
858 $_strp_date->parse_datetime($args->{end_date}) : undef
860 if ($args->{base_issuance}) { # predict from a given issuance
861 $options->{predict_from} = _revive_holding($args->{base_issuance}->holding_code, $caption_field, 1); # fresh MFHD Record, so we simply default to 1 for seqno
862 $options->{faked_chron_date} = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($args->{base_issuance}->date_published)) if $using_fake_chron;
863 } else { # default to predicting from last published
864 my $last_published = $editor->search_serial_issuance([
865 {'caption_and_pattern' => $scap->id,
866 'subscription' => $ssub_id},
867 {limit => 1, order_by => { siss => "date_published DESC" }}]
869 if ($last_published->[0]) {
870 my $last_siss = $last_published->[0];
871 unless ($last_siss->holding_code) {
873 # XXX TODO new event type
874 return new OpenILS::Event(
875 "BAD_PARAMS", note =>
876 "Last issuance has no holding code. Can't predict."
879 $options->{predict_from} = _revive_holding($last_siss->holding_code, $caption_field, 1);
880 $options->{faked_chron_date} = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($last_siss->date_published)) if $using_fake_chron;
883 # XXX TODO make a new event type instead of hijacking this one
884 return new OpenILS::Event(
885 "BAD_PARAMS", note => "No issuance from which to predict!"
889 push( @predictions, _generate_issuance_values($mfhd, $options) );
894 foreach my $prediction (@predictions) {
895 my $issuance = new Fieldmapper::serial::issuance;
897 $issuance->label($prediction->{label});
898 $issuance->date_published($prediction->{date_published}->strftime('%F'));
899 $issuance->holding_code(OpenSRF::Utils::JSON->perl2JSON($prediction->{holding_code}));
900 $issuance->holding_type($prediction->{holding_type});
901 $issuance->caption_and_pattern($prediction->{caption_and_pattern});
902 $issuance->subscription($ssub->id);
903 push (@issuances, $issuance);
906 fleshed_issuance_alter($self, $conn, $authtoken, \@issuances); # FIXME: catch events
909 for (my $i = 0; $i < @issuances; $i++) {
910 my $date_expected = $predictions[$i]->{date_published}->add(seconds => interval_to_seconds($ssub->expected_date_offset))->strftime('%F');
911 my $issuance = $issuances[$i];
912 #$issuance->label(interval_to_seconds($ssub->expected_date_offset));
913 foreach my $sdist (@$sdists) {
914 my $streams = $sdist->streams;
915 foreach my $stream (@$streams) {
916 my $item = new Fieldmapper::serial::item;
918 $item->stream($stream->id);
919 $item->date_expected($date_expected);
920 $item->issuance($issuance->id);
921 push (@items, $item);
925 fleshed_item_alter($self, $conn, $authtoken, \@items); # FIXME: catch events
930 # _generate_issuance_values() is an initial attempt at a function which can be used
931 # to populate an issuance table with a list of predicted issues. It accepts
932 # a hash ref of options initially defined as:
933 # caption : the caption field to predict on
934 # num_to_predict : the number of issues you wish to predict
935 # last_rec_date : the date of the last received issue, to be used as an offset
936 # for predicting future issues
937 # 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
939 # The basic method is to first convert to a single holding if compressed, then
940 # increment the holding and save the resulting values to @issuances.
942 # returns @issuance_values, an array of hashrefs containing (formatted
943 # label, formatted chronology date, formatted estimated arrival date, and an
944 # array ref of holding subfields as (key, value, key, value ...)) (not a hash
945 # to protect order and possible duplicate keys), and a holding type.
947 sub _generate_issuance_values {
948 my ($mfhd, $options) = @_;
949 my $caption = $options->{caption};
950 my $scap_id = $options->{scap_id};
951 my $num_to_predict = $options->{num_to_predict};
952 my $end_date = $options->{end_date};
953 my $predict_from = $options->{predict_from}; # issuance to predict from
954 my $faked_chron_date = $options->{faked_chron_date}; # serial does not have a chronology caption, so add one (temporarily) based on this date
955 #my $last_rec_date = $options->{last_rec_date}; # expected or actual
958 # Only needed for 'real' MFHD records, not our temp records
959 # my $link_id = $caption->link_id;
960 # if(!$predict_from) {
961 # my $htag = $caption->tag;
962 # $htag =~ s/^85/86/;
963 # my @holdings = $mfhd->holdings($htag, $link_id);
964 # my $last_holding = $holdings[-1];
966 # #if ($last_holding->is_compressed) {
967 # # $last_holding->compressed_to_last; # convert to last in range
969 # $predict_from = $last_holding;
973 $predict_from->notes('public', []);
974 # add a note marker for system use (?)
975 $predict_from->notes('private', ['AUTOGEN']);
977 # our basic method for dealing with 'faked' chronologies will be to add it in, do the predicting, then take it back out
980 if ($faked_chron_date) {
981 $orig_caption = $predict_from->caption;
982 # because of the way MFHD::Caption and Holding work, it is simplest
983 # to recreate rather than try to update
984 $faked_caption = new MFHD::Caption(new MARC::Field($orig_caption->tag, $orig_caption->indicator(1), $orig_caption->indicator(2), $orig_caption->subfields_list, 'i' => '(year)', 'j' => '(month)', 'k' => '(day)'));
985 $predict_from = new MFHD::Holding($predict_from->seqno, new MARC::Field($predict_from->tag, $predict_from->indicator(1), $predict_from->indicator(2), $predict_from->subfields_list, 'i' => $faked_chron_date->year, 'j' => $faked_chron_date->month, 'k' => $faked_chron_date->day), $faked_caption);
988 my @predictions = $mfhd->generate_predictions({'base_holding' => $predict_from, 'num_to_predict' => $num_to_predict, 'end_date' => $end_date});
992 foreach my $prediction (@predictions) {
993 $pub_date = $_strp_date->parse_datetime($prediction->chron_to_date);
994 if ($faked_chron_date) { # get rid of the chronology portions and restore original caption
995 $prediction->delete_subfield(code => ['i', 'j', 'k']);
996 $prediction = new MFHD::Holding($prediction->seqno, new MARC::Field($prediction->tag, $prediction->indicator(1), $prediction->indicator(2), $prediction->subfields_list), $orig_caption);
1002 label => $prediction->format,
1003 date_published => $pub_date,
1004 #date_expected => $date_expected->strftime('%F'),
1005 holding_code => [$prediction->indicator(1),$prediction->indicator(2),$prediction->subfields_list],
1006 holding_type => $MFHD_NAMES_BY_TAG{$caption->tag},
1007 caption_and_pattern => $scap_id
1012 return @issuance_values;
1015 sub _revive_caption {
1018 my $pattern_code = $scap->pattern_code;
1021 my $pattern_parts = OpenSRF::Utils::JSON->JSON2perl($pattern_code);
1022 unshift(@$pattern_parts, $MFHD_TAGS_BY_NAME{$scap->type});
1023 my $pattern_field = new MARC::Field(@$pattern_parts);
1025 # build MFHD::Caption
1026 return new MFHD::Caption($pattern_field);
1029 sub _revive_holding {
1030 my $holding_code = shift;
1031 my $caption_field = shift;
1035 my $holding_parts = OpenSRF::Utils::JSON->JSON2perl($holding_code);
1036 my $captag = $caption_field->tag;
1037 $captag =~ s/^85/86/;
1038 unshift(@$holding_parts, $captag);
1039 my $holding_field = new MARC::Field(@$holding_parts);
1041 # build MFHD::Holding
1042 return new MFHD::Holding($seqno, $holding_field, $caption_field);
1045 __PACKAGE__->register_method(
1046 method => 'unitize_items',
1047 api_name => 'open-ils.serial.receive_items',
1051 desc => 'Marks an item as received, updates the shelving unit (creating a new shelving unit if needed), and updates the summaries',
1054 desc => 'array of serial items',
1059 desc => 'hash of item_ids => barcodes',
1064 desc => 'Returns number of received items (num_items) and new unit ID, if applicable (new_unit_id)',
1070 __PACKAGE__->register_method(
1071 method => 'unitize_items',
1072 api_name => 'open-ils.serial.bind_items',
1076 desc => 'Marks an item as bound, updates the shelving unit (creating a new shelving unit if needed)',
1079 desc => 'array of serial items',
1084 desc => 'hash of item_ids => barcodes',
1089 desc => 'Returns number of bound items (num_items) and new unit ID, if applicable (new_unit_id)',
1096 my ($self, $conn, $auth, $items, $barcodes) = @_;
1098 my( $reqr, $evt ) = $U->checkses($auth);
1099 return $evt if $evt;
1100 my $editor = new_editor(requestor => $reqr, xact => 1);
1101 $self->api_name =~ /serial\.(\w*)_items/;
1105 my %found_stream_ids;
1108 my %stream_ids_by_unit_id;
1111 my %sdist_by_unit_id;
1112 my %sdist_by_stream_id;
1114 my $new_unit_id; # id for '-2' units to share
1115 foreach my $item (@$items) {
1116 # for debugging only, TODO: delete
1117 if (!ref $item) { # hopefully we got an id instead
1118 $item = $editor->retrieve_serial_item($item);
1121 my $unit_id = ref($item->unit) ? $item->unit->id : $item->unit;
1122 my $stream_id = ref($item->stream) ? $item->stream->id : $item->stream;
1123 my $issuance_id = ref($item->issuance) ? $item->issuance->id : $item->issuance;
1124 #TODO: evt on any missing ids
1126 if ($mode eq 'receive') {
1127 $item->date_received('now');
1128 $item->status('Received');
1131 # check for types to trigger summary updates
1133 if (!ref $item->issuance) {
1134 my $scaps = $editor->search_serial_caption_and_pattern([{"+siss" => {"id" => $issuance_id}}, { "join" => {"siss" => {}} }]);
1135 $scap = $scaps->[0];
1136 } elsif (!ref $item->issuance->caption_and_pattern) {
1137 $scap = $editor->retrieve_serial_caption_and_pattern($item->issuance->caption_and_pattern);
1139 $scap = $editor->issuance->caption_and_pattern;
1141 if (!exists($found_types{$stream_id})) {
1142 $found_types{$stream_id} = {};
1144 $found_types{$stream_id}->{$scap->type} = 1;
1146 # create unit if needed
1147 if ($unit_id == -1 or (!$new_unit_id and $unit_id == -2)) { # create unit per item
1149 my $sdists = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
1150 $unit = _build_unit($editor, $sdists->[0], $mode, 0, $barcodes->{$item->id});
1151 # if _build_unit fails, $unit is an event, so return it
1152 if ($U->event_code($unit)) {
1154 $unit->{"note"} = "Item ID: " . $item->id;
1157 my $evt = _create_sunit($editor, $unit);
1158 return $evt if $evt;
1159 if ($unit_id == -2) {
1160 $new_unit_id = $unit->id;
1161 $unit_id = $new_unit_id;
1163 $unit_id = $unit->id;
1165 $item->unit($unit_id);
1167 # get unit with 'DEFAULT's and save unit and sdist for later use
1168 $unit = $editor->retrieve_serial_unit($unit->id);
1169 $unit_map{$unit_id} = $unit;
1170 $sdist_by_unit_id{$unit_id} = $sdists->[0];
1171 $sdist_by_stream_id{$stream_id} = $sdists->[0];
1172 } elsif ($unit_id == -2) { # create one unit for all '-2' items
1173 $unit_id = $new_unit_id;
1174 $item->unit($unit_id);
1177 $found_unit_ids{$unit_id} = 1;
1178 $found_stream_ids{$stream_id} = 1;
1180 # save the stream_id for this unit_id
1181 # TODO: prevent items from different streams in same unit? (perhaps in interface)
1182 $stream_ids_by_unit_id{$unit_id} = $stream_id;
1184 my $evt = _update_sitem($editor, undef, $item);
1185 return $evt if $evt;
1188 # deal with unit level labels
1189 foreach my $unit_id (keys %found_unit_ids) {
1191 # get all the needed issuances for unit
1192 # TODO remove 'Bindery' from this search (leaving it in for now for backwards compatibility with any current test environment data)
1193 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"unit" => $unit_id, "status" => ["Received", "Bindery"]}}, {"join" => {"sitem" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1194 #TODO: evt on search failure
1196 my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
1198 # special case for single formatted_part (may have summarized version)
1199 if (@$formatted_parts == 1) {
1200 #TODO: MFHD.pm should have a 'format_summary' method for this
1203 # retrieve and update unit contents
1207 # if we just created the unit, we will already have it and the distribution stored
1208 if (exists $unit_map{$unit_id}) {
1209 $sunit = $unit_map{$unit_id};
1210 $sdist = $sdist_by_unit_id{$unit_id};
1212 $sunit = $editor->retrieve_serial_unit($unit_id);
1213 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_ids_by_unit_id{$unit_id}}}, { "join" => {"sstr" => {}} }]);
1214 $sdist = $sdist->[0];
1217 $sunit->detailed_contents($sdist->unit_label_prefix . ' '
1218 . join(', ', @$formatted_parts) . ' '
1219 . $sdist->unit_label_suffix);
1221 $sunit->summary_contents($sunit->detailed_contents); #TODO: change this when real summary contents are available
1223 # create sort_key by left padding numbers to 6 digits
1224 my $sort_key = $sunit->detailed_contents;
1225 $sort_key =~ s/(\d+)/sprintf '%06d', $1/eg; # this may need improvement
1226 $sunit->sort_key($sort_key);
1228 my $evt = _update_sunit($editor, undef, $sunit);
1229 return $evt if $evt;
1232 # cleanup 'dead' units (units which are now emptied of their items)
1233 my $dead_units = $editor->search_serial_unit([{'+sitem' => {'id' => undef}, 'deleted' => 'f'}, {'join' => {'sitem' => {'type' => 'left'}}}]);
1234 foreach my $unit (@$dead_units) {
1235 _delete_sunit($editor, undef, $unit);
1238 if ($mode eq 'receive') { # the summary holdings do not change when binding
1239 # deal with stream level summaries
1240 # summaries will be built from the "primary" stream only, that is, the stream with the lowest ID per distribution
1241 # (TODO: consider direct designation)
1242 my %primary_streams_by_sdist;
1243 my %streams_by_sdist;
1245 # see if we have primary streams, and if so, associate them with their distributions
1246 foreach my $stream_id (keys %found_stream_ids) {
1248 if (exists $sdist_by_stream_id{$stream_id}) {
1249 $sdist = $sdist_by_stream_id{$stream_id};
1251 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
1252 $sdist = $sdist->[0];
1255 if (!exists($streams_by_sdist{$sdist->id})) {
1256 $streams = $editor->search_serial_stream([{"distribution" => $sdist->id}, {"order_by" => {"sstr" => "id"}}]);
1257 $streams_by_sdist{$sdist->id} = $streams;
1259 $streams = $streams_by_sdist{$sdist->id};
1261 $primary_streams_by_sdist{$sdist->id} = $streams->[0] if ($stream_id == $streams->[0]->id);
1264 # retrieve and update summaries for each affected primary stream's distribution
1265 foreach my $sdist_id (keys %primary_streams_by_sdist) {
1266 my $stream = $primary_streams_by_sdist{$sdist_id};
1267 my $stream_id = $stream->id;
1268 # get all the needed issuances for stream
1269 # FIXME: search in Bindery/Bound/Not Published? as well as Received
1270 foreach my $type (keys %{$found_types{$stream_id}}) {
1271 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"stream" => $stream_id, "status" => "Received"}, "+scap" => {"type" => $type}}, {"join" => {"sitem" => {}, "scap" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1272 #TODO: evt on search failure
1273 $evt = _prepare_summaries($editor, $issuances, $sdist_id, $type);
1274 if ($U->event_code($evt)) {
1283 return {'num_items' => scalar @$items, 'new_unit_id' => $new_unit_id};
1286 sub _find_or_create_call_number {
1287 my ($e, $lib, $cn_string, $record) = @_;
1289 my $existing = $e->search_asset_call_number({
1290 "owning_lib" => $lib,
1291 "label" => $cn_string,
1292 "record" => $record,
1294 }) or return $e->die_event;
1297 return $existing->[0]->id;
1299 return $e->die_event unless
1300 $e->allowed("CREATE_VOLUME", $lib);
1302 my $acn = new Fieldmapper::asset::call_number;
1304 $acn->creator($e->requestor->id);
1305 $acn->editor($e->requestor->id);
1306 $acn->record($record);
1307 $acn->label($cn_string);
1308 $acn->owning_lib($lib);
1310 $e->create_asset_call_number($acn) or return $e->die_event;
1311 return $e->data->id;
1315 sub _issuances_received {
1316 # XXX TODO: Add some caching or something. This is getting called
1317 # more often than it has to be.
1318 my ($e, $sitem) = @_;
1320 my $results = $e->json_query({
1321 "select" => {"sitem" => ["issuance"]},
1322 "from" => {"sitem" => {"sstr" => {}, "siss" => {}}},
1324 "+sstr" => {"distribution" => $sitem->stream->distribution->id},
1325 "+siss" => {"holding_type" => $sitem->issuance->holding_type},
1326 "+sitem" => {"date_received" => {"!=" => undef}}
1329 "siss" => {"date_published" => {"direction" => "asc"}}
1331 }) or return $e->die_event;
1333 my $uniq = +{map { $_->{"issuance"} => 1 } @$results};
1334 return [ map { $e->retrieve_serial_issuance($_) } keys %$uniq ];
1337 # XXX _prepare_unit_label() duplicates some code from unitize_items().
1338 # Hopefully we can unify code paths down the road.
1339 sub _prepare_unit_label {
1340 my ($e, $sunit, $sdist, $issuance) = @_;
1342 my ($mfhd, $formatted_parts) = _summarize_contents($e, [$issuance]);
1344 # special case for single formatted_part (may have summarized version)
1345 if (@$formatted_parts == 1) {
1346 #TODO: MFHD.pm should have a 'format_summary' method for this
1349 $sunit->detailed_contents(
1352 $sdist->unit_label_prefix,
1353 join(", ", @$formatted_parts),
1354 $sdist->unit_label_suffix
1358 # TODO: change this when real summary contents are available
1359 $sunit->summary_contents($sunit->detailed_contents);
1361 # Create sort_key by left padding numbers to 6 digits.
1362 (my $sort_key = $sunit->detailed_contents) =~
1363 s/(\d+)/sprintf '%06d', $1/eg;
1364 $sunit->sort_key($sort_key);
1367 # _prepare_summaries populates the generated_coverage field for a given summary
1368 # type ('basic', 'index', 'supplement') for a given distribution.
1369 # It also creates the summary if it doesn't yet exist.
1370 sub _prepare_summaries {
1371 my ($e, $issuances, $dist_id, $type) = @_;
1373 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances);
1375 my $search_method = "search_serial_${type}_summary";
1376 my $summary = $e->$search_method([{"distribution" => $dist_id}]);
1378 my $cu_method = "update";
1381 $summary = $summary->[0];
1383 my $class = "Fieldmapper::serial::${type}_summary";
1384 $summary = $class->new;
1385 $summary->distribution($dist_id);
1386 $cu_method = "create";
1389 $summary->generated_coverage(join(", ", @$formatted_parts));
1390 my $method = "${cu_method}_serial_${type}_summary";
1391 return $e->die_event unless $e->$method($summary);
1394 sub _unit_by_iss_and_str {
1395 my ($e, $issuance, $stream) = @_;
1397 my $unit = $e->json_query({
1398 "select" => {"sunit" => ["id"]},
1399 "from" => {"sitem" => {"sunit" => {}}},
1402 "issuance" => $issuance->id,
1403 "stream" => $stream->id
1406 }) or return $e->die_event;
1407 return 0 if not @$unit;
1409 $e->retrieve_serial_unit($unit->[0]->{"id"}) or $e->die_event;
1412 sub move_previous_unit {
1413 my ($e, $prev_iss, $curr_item, $new_loc) = @_;
1415 my $prev_unit = _unit_by_iss_and_str($e,$prev_iss,$curr_item->stream);
1416 return $prev_unit if defined $U->event_code($prev_unit);
1417 return 0 if not $prev_unit;
1419 if ($prev_unit->location != $new_loc) {
1420 $prev_unit->location($new_loc);
1421 $e->update_serial_unit($prev_unit) or return $e->die_event;
1426 # _previous_issuance() assumes $existing is an ordered array
1427 sub _previous_issuance {
1428 my ($existing, $issuance) = @_;
1430 my $last = $existing->[-1];
1431 return undef unless $last;
1432 return ($last->id == $issuance->id ? $existing->[-2] : $last);
1435 __PACKAGE__->register_method(
1436 "method" => "receive_items_one_unit_per",
1437 "api_name" => "open-ils.serial.receive_items.one_unit_per",
1442 "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",
1446 "desc" => "authtoken",
1451 "desc" => "array of serial items, possibly fleshed with units and definitely fleshed with stream->distribution",
1456 "desc" => "id of bib record these items are associated with
1457 (XXX could/should be derived from items)",
1462 "desc" => "The item ID for each item successfully received",
1468 sub receive_items_one_unit_per {
1469 # XXX This function may be temporary, as it does some of what
1470 # unitize_items() does, just in a different way.
1471 my ($self, $client, $auth, $items, $record) = @_;
1473 my $e = new_editor("authtoken" => $auth, "xact" => 1);
1474 return $e->die_event unless $e->checkauth;
1475 return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
1477 my $prev_loc_setting_map = {};
1478 my $user_id = $e->requestor->id;
1480 # Get a list of all the non-virtual field names in a serial::unit for
1481 # merging given unit objects with template-built units later.
1482 # XXX move this somewhere global so it isn't re-run all the time
1483 my $all_unit_fields =
1484 $Fieldmapper::fieldmap->{"Fieldmapper::serial::unit"}->{"fields"};
1485 my @real_unit_fields = grep {
1486 not $all_unit_fields->{$_}->{"virtual"}
1487 } keys %$all_unit_fields;
1489 foreach my $item (@$items) {
1490 # Note that we expect a certain fleshing on the items we're getting.
1491 my $sdist = $item->stream->distribution;
1493 # Fetch a list of issuances with received copies already existing
1494 # on this distribution (and with the same holding type on the
1495 # issuance). This will be used in up to two places: once when building
1496 # a summary, once when changing the copy location of the previous
1498 my $issuances_received = _issuances_received($e, $item);
1499 if ($U->event_code($issuances_received)) {
1501 return $issuances_received;
1504 # Find out if we need to to deal with previous copy location changing.
1505 my $ou = $sdist->holding_lib->id;
1506 unless (exists $prev_loc_setting_map->{$ou}) {
1507 $prev_loc_setting_map->{$ou} = $U->ou_ancestor_setting_value(
1508 $ou, "serial.prev_issuance_copy_location", $e
1512 # If there is a previous copy location setting, we need the previous
1513 # issuance, from which we can in turn look up the item attached to the
1514 # same stream we're on now.
1515 if ($prev_loc_setting_map->{$ou}) {
1517 _previous_issuance($issuances_received, $item->issuance)) {
1519 # Now we can change the copy location of the previous unit,
1521 return $e->event if defined $U->event_code(
1523 $e, $prev_iss, $item, $prev_loc_setting_map->{$ou}
1529 # Create unit if given by user
1530 if (ref $item->unit) {
1531 # detach from the item, as we need to create separately
1532 my $user_unit = $item->unit;
1534 # get a unit based on associated template
1535 my $template_unit = _build_unit($e, $sdist, "receive", 1);
1536 if ($U->event_code($template_unit)) {
1538 $template_unit->{"note"} = "Item ID: " . $item->id;
1539 return $template_unit;
1542 # merge built unit with provided unit from user
1543 foreach (@real_unit_fields) {
1544 unless ($user_unit->$_) {
1545 $user_unit->$_($template_unit->$_);
1549 # Treat call number specially: the provided value from the
1550 # user will really be a string.
1551 if ($user_unit->call_number) {
1552 my $real_cn = _find_or_create_call_number(
1553 $e, $sdist->holding_lib->id,
1554 $user_unit->call_number, $record
1557 if ($U->event_code($real_cn)) {
1561 $user_unit->call_number($real_cn);
1565 my $evt = _prepare_unit_label(
1566 $e, $user_unit, $sdist, $item->issuance
1568 if ($U->event_code($evt)) {
1573 # create/update summary objects related to this distribution
1574 # Make sure @$issuances_received contains current item's issuance
1575 unless (grep { $_->id == $item->issuance->id } @$issuances_received) {
1576 push @$issuances_received, $item->issuance;
1578 $evt = _prepare_summaries($e, $issuances_received, $item->stream->distribution->id, $item->issuance->holding_type);
1579 if ($U->event_code($evt)) {
1584 # set the incontrovertibles on the unit
1585 $user_unit->edit_date("now");
1586 $user_unit->create_date("now");
1587 $user_unit->editor($user_id);
1588 $user_unit->creator($user_id);
1590 return $e->die_event unless $e->create_serial_unit($user_unit);
1592 # save reference to new unit
1593 $item->unit($e->data->id);
1596 # Create notes if given by user
1597 if (ref($item->notes) and @{$item->notes}) {
1598 foreach my $note (@{$item->notes}) {
1599 $note->creator($user_id);
1600 $note->create_date("now");
1602 return $e->die_event unless $e->create_serial_item_note($note);
1605 $item->clear_notes; # They're saved; we no longer want them here.
1608 # Set the incontrovertibles on the item
1609 $item->status("Received");
1610 $item->date_received("now");
1611 $item->edit_date("now");
1612 $item->editor($user_id);
1614 return $e->die_event unless $e->update_serial_item($item);
1616 # send client a response
1617 $client->respond($item->id);
1620 $e->commit or return $e->die_event;
1628 my $skip_call_number = shift;
1629 my $barcode = shift;
1631 my $attr = $mode . '_unit_template';
1632 my $template = $editor->retrieve_asset_copy_template($sdist->$attr) or
1633 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_COPY_TEMPLATE");
1635 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 );
1637 my $unit = new Fieldmapper::serial::unit;
1638 foreach my $part (@parts) {
1639 my $value = $template->$part;
1640 next if !defined($value);
1641 $unit->$part($value);
1644 # ignore circ_lib in template, set to distribution holding_lib
1645 $unit->circ_lib($sdist->holding_lib);
1646 $unit->creator($editor->requestor->id);
1647 $unit->editor($editor->requestor->id);
1649 unless ($skip_call_number) {
1650 $attr = $mode . '_call_number';
1651 my $cn = $sdist->$attr or
1652 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_CALL_NUMBER");
1654 $unit->call_number($cn);
1658 $unit->barcode($barcode);
1660 $unit->barcode('AUTO');
1662 $unit->sort_key('');
1663 $unit->summary_contents('');
1664 $unit->detailed_contents('');
1670 sub _summarize_contents {
1672 my $issuances = shift;
1674 # create MFHD record
1675 my $mfhd = MFHD->new(MARC::Record->new());
1678 my @scap_fields_ordered;
1681 foreach my $issuance (@$issuances) {
1682 my $scap_id = $issuance->caption_and_pattern;
1683 next if (!$scap_id); # skip issuances with no caption/pattern
1687 # if this is the first appearance of this scap, retrieve it and add it to the temporary record
1688 if (!exists $scaps{$issuance->caption_and_pattern}) {
1689 $scaps{$scap_id} = $editor->retrieve_serial_caption_and_pattern($scap_id);
1690 $scap = $scaps{$scap_id};
1691 $scap_field = _revive_caption($scap);
1692 $scap_fields{$scap_id} = $scap_field;
1693 push(@scap_fields_ordered, $scap_field);
1694 $scap_field->update('8' => $link_id);
1695 $mfhd->append_fields($scap_field);
1698 $scap = $scaps{$scap_id};
1699 $scap_field = $scap_fields{$scap_id};
1702 $mfhd->append_fields(_revive_holding($issuance->holding_code, $scap_field, $seqno));
1706 my @formatted_parts;
1707 foreach my $scap_field (@scap_fields_ordered) { #TODO: use generic MFHD "summarize" method, once available
1708 my @updated_holdings = $mfhd->get_compressed_holdings($scap_field);
1709 foreach my $holding (@updated_holdings) {
1710 push(@formatted_parts, $holding->format);
1714 return ($mfhd, \@formatted_parts);
1717 ##########################################################################
1720 __PACKAGE__->register_method(
1721 method => 'fetch_notes',
1722 api_name => 'open-ils.serial.item_note.retrieve.all',
1724 Returns an array of copy note objects.
1725 @param args A named hash of parameters including:
1726 authtoken : Required if viewing non-public notes
1727 item_id : The id of the item whose notes we want to retrieve
1728 pub : True if all the caller wants are public notes
1729 @return An array of note objects
1733 __PACKAGE__->register_method(
1734 method => 'fetch_notes',
1735 api_name => 'open-ils.serial.subscription_note.retrieve.all',
1737 Returns an array of copy note objects.
1738 @param args A named hash of parameters including:
1739 authtoken : Required if viewing non-public notes
1740 subscription_id : The id of the item whose notes we want to retrieve
1741 pub : True if all the caller wants are public notes
1742 @return An array of note objects
1746 __PACKAGE__->register_method(
1747 method => 'fetch_notes',
1748 api_name => 'open-ils.serial.distribution_note.retrieve.all',
1750 Returns an array of copy note objects.
1751 @param args A named hash of parameters including:
1752 authtoken : Required if viewing non-public notes
1753 distribution_id : The id of the item whose notes we want to retrieve
1754 pub : True if all the caller wants are public notes
1755 @return An array of note objects
1759 # TODO: revisit this method to consider replacing cstore direct calls
1761 my( $self, $connection, $args ) = @_;
1763 $self->api_name =~ /serial\.(\w*)_note/;
1766 my $id = $$args{object_id};
1767 my $authtoken = $$args{authtoken};
1771 return $U->cstorereq(
1772 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic',
1773 { $type => $id, pub => 't' } );
1775 # FIXME: restore perm check
1776 # ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
1777 # return $evt if $evt;
1778 return $U->cstorereq(
1779 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic', {$type => $id} );
1785 __PACKAGE__->register_method(
1786 method => 'create_note',
1787 api_name => 'open-ils.serial.item_note.create',
1789 Creates a new item note
1790 @param authtoken The login session key
1791 @param note The note object to create
1792 @return The id of the new note object
1796 __PACKAGE__->register_method(
1797 method => 'create_note',
1798 api_name => 'open-ils.serial.subscription_note.create',
1800 Creates a new subscription note
1801 @param authtoken The login session key
1802 @param note The note object to create
1803 @return The id of the new note object
1807 __PACKAGE__->register_method(
1808 method => 'create_note',
1809 api_name => 'open-ils.serial.distribution_note.create',
1811 Creates a new distribution note
1812 @param authtoken The login session key
1813 @param note The note object to create
1814 @return The id of the new note object
1819 my( $self, $connection, $authtoken, $note ) = @_;
1821 $self->api_name =~ /serial\.(\w*)_note/;
1824 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1825 return $e->event unless $e->checkauth;
1827 # FIXME: restore permission support
1828 # my $item = $e->retrieve_serial_item(
1834 # return $e->event unless
1835 # $e->allowed('CREATE_COPY_NOTE', $item->call_number->owning_lib);
1837 $note->create_date('now');
1838 $note->creator($e->requestor->id);
1839 $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
1842 my $method = "create_serial_${type}_note";
1843 $e->$method($note) or return $e->event;
1848 __PACKAGE__->register_method(
1849 method => 'delete_note',
1850 api_name => 'open-ils.serial.item_note.delete',
1852 Deletes an existing item note
1853 @param authtoken The login session key
1854 @param noteid The id of the note to delete
1855 @return 1 on success - Event otherwise.
1859 __PACKAGE__->register_method(
1860 method => 'delete_note',
1861 api_name => 'open-ils.serial.subscription_note.delete',
1863 Deletes an existing subscription note
1864 @param authtoken The login session key
1865 @param noteid The id of the note to delete
1866 @return 1 on success - Event otherwise.
1870 __PACKAGE__->register_method(
1871 method => 'delete_note',
1872 api_name => 'open-ils.serial.distribution_note.delete',
1874 Deletes an existing distribution note
1875 @param authtoken The login session key
1876 @param noteid The id of the note to delete
1877 @return 1 on success - Event otherwise.
1882 my( $self, $conn, $authtoken, $noteid ) = @_;
1884 $self->api_name =~ /serial\.(\w*)_note/;
1887 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1888 return $e->die_event unless $e->checkauth;
1890 my $method = "retrieve_serial_${type}_note";
1891 my $note = $e->$method([
1893 ]) or return $e->die_event;
1895 # FIXME: restore permissions check
1896 # if( $note->creator ne $e->requestor->id ) {
1897 # return $e->die_event unless
1898 # $e->allowed('DELETE_COPY_NOTE', $note->item->call_number->owning_lib);
1901 $method = "delete_serial_${type}_note";
1902 $e->$method($note) or return $e->die_event;
1908 ##########################################################################
1909 # subscription methods
1911 __PACKAGE__->register_method(
1912 method => 'fleshed_ssub_alter',
1913 api_name => 'open-ils.serial.subscription.fleshed.batch.update',
1917 desc => 'Receives an array of one or more subscriptions and updates the database as needed',
1919 name => 'authtoken',
1920 desc => 'Authtoken for current user session',
1924 name => 'subscriptions',
1925 desc => 'Array of fleshed subscriptions',
1931 desc => 'Returns 1 if successful, event if failed',
1937 sub fleshed_ssub_alter {
1938 my( $self, $conn, $auth, $ssubs ) = @_;
1939 return 1 unless ref $ssubs;
1940 my( $reqr, $evt ) = $U->checkses($auth);
1941 return $evt if $evt;
1942 my $editor = new_editor(requestor => $reqr, xact => 1);
1943 my $override = $self->api_name =~ /override/;
1945 # TODO: permission check
1946 # return $editor->event unless
1947 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
1949 for my $ssub (@$ssubs) {
1951 my $ssubid = $ssub->id;
1953 if( $ssub->isdeleted ) {
1954 $evt = _delete_ssub( $editor, $override, $ssub);
1955 } elsif( $ssub->isnew ) {
1956 _cleanse_dates($ssub, ['start_date','end_date']);
1957 $evt = _create_ssub( $editor, $ssub );
1959 _cleanse_dates($ssub, ['start_date','end_date']);
1960 $evt = _update_ssub( $editor, $override, $ssub );
1965 $logger->info("fleshed subscription-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
1969 $logger->debug("subscription-alter: done updating subscription batch");
1971 $logger->info("fleshed subscription-alter successfully updated ".scalar(@$ssubs)." subscriptions");
1976 my ($editor, $override, $ssub) = @_;
1977 $logger->info("subscription-alter: delete subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1978 my $sdists = $editor->search_serial_distribution(
1979 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1980 my $cps = $editor->search_serial_caption_and_pattern(
1981 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1982 my $sisses = $editor->search_serial_issuance(
1983 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1984 return OpenILS::Event->new(
1985 'SERIAL_SUBSCRIPTION_NOT_EMPTY', payload => $ssub->id ) if (@$sdists or @$cps or @$sisses);
1987 return $editor->event unless $editor->delete_serial_subscription($ssub);
1992 my ($editor, $ssub) = @_;
1994 $logger->info("subscription-alter: new subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1995 return $editor->event unless $editor->create_serial_subscription($ssub);
2000 my ($editor, $override, $ssub) = @_;
2002 $logger->info("subscription-alter: retrieving subscription ".$ssub->id);
2003 my $orig_ssub = $editor->retrieve_serial_subscription($ssub->id);
2005 $logger->info("subscription-alter: original subscription ".OpenSRF::Utils::JSON->perl2JSON($orig_ssub));
2006 $logger->info("subscription-alter: updated subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2007 return $editor->event unless $editor->update_serial_subscription($ssub);
2011 __PACKAGE__->register_method(
2012 method => "fleshed_serial_subscription_retrieve_batch",
2014 api_name => "open-ils.serial.subscription.fleshed.batch.retrieve"
2017 sub fleshed_serial_subscription_retrieve_batch {
2018 my( $self, $client, $ids ) = @_;
2019 # FIXME: permissions?
2020 $logger->info("Fetching fleshed subscriptions @$ids");
2021 return $U->cstorereq(
2022 "open-ils.cstore.direct.serial.subscription.search.atomic",
2025 flesh_fields => {ssub => [ qw/owning_lib notes/ ]}
2029 __PACKAGE__->register_method(
2030 method => "retrieve_sub_tree",
2032 api_name => "open-ils.serial.subscription_tree.retrieve"
2035 __PACKAGE__->register_method(
2036 method => "retrieve_sub_tree",
2037 api_name => "open-ils.serial.subscription_tree.global.retrieve"
2040 sub retrieve_sub_tree {
2042 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2044 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2048 # TODO: permission support
2049 if(!@org_ids and $user_session) {
2051 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2052 @org_ids = ($user_obj->home_ou);
2055 if( $self->api_name =~ /global/ ) {
2056 return _build_subs_list( { record_entry => $docid } ); # TODO: filter for !deleted, or active?
2061 for my $orgid (@org_ids) {
2062 my $subs = _build_subs_list(
2063 { record_entry => $docid, owning_lib => $orgid } );# TODO: filter for !deleted, or active?
2064 push( @all_subs, @$subs );
2073 sub _build_subs_list {
2074 my $search_hash = shift;
2076 #$search_hash->{deleted} = 'f';
2077 my $e = new_editor();
2079 my $subs = $e->search_serial_subscription([$search_hash, { 'order_by' => {'ssub' => 'id'} }]);
2083 for my $sub (@$subs) {
2085 # TODO: filter on !deleted?
2086 my $dists = $e->search_serial_distribution(
2087 [{ subscription => $sub->id }, { 'order_by' => {'sdist' => 'label'} }]
2090 #$dists = [ sort { $a->label cmp $b->label } @$dists ];
2092 $sub->distributions($dists);
2094 # TODO: filter on !deleted?
2095 my $issuances = $e->search_serial_issuance(
2096 [{ subscription => $sub->id }, { 'order_by' => {'siss' => 'label'} }]
2099 #$issuances = [ sort { $a->label cmp $b->label } @$issuances ];
2100 $sub->issuances($issuances);
2102 # TODO: filter on !deleted?
2103 my $scaps = $e->search_serial_caption_and_pattern(
2104 [{ subscription => $sub->id }, { 'order_by' => {'scap' => 'id'} }]
2107 #$scaps = [ sort { $a->id cmp $b->id } @$scaps ];
2108 $sub->scaps($scaps);
2109 push( @built_subs, $sub );
2112 return \@built_subs;
2116 __PACKAGE__->register_method(
2117 method => "subscription_orgs_for_title",
2119 api_name => "open-ils.serial.subscription.retrieve_orgs_by_title"
2122 sub subscription_orgs_for_title {
2123 my( $self, $client, $record_id ) = @_;
2125 my $subs = $U->simple_scalar_request(
2127 "open-ils.cstore.direct.serial.subscription.search.atomic",
2128 { record_entry => $record_id }); # TODO: filter on !deleted?
2130 my $orgs = { map {$_->owning_lib => 1 } @$subs };
2131 return [ keys %$orgs ];
2135 ##########################################################################
2136 # distribution methods
2138 __PACKAGE__->register_method(
2139 method => 'fleshed_sdist_alter',
2140 api_name => 'open-ils.serial.distribution.fleshed.batch.update',
2144 desc => 'Receives an array of one or more distributions and updates the database as needed',
2146 name => 'authtoken',
2147 desc => 'Authtoken for current user session',
2151 name => 'distributions',
2152 desc => 'Array of fleshed distributions',
2158 desc => 'Returns 1 if successful, event if failed',
2164 sub fleshed_sdist_alter {
2165 my( $self, $conn, $auth, $sdists ) = @_;
2166 return 1 unless ref $sdists;
2167 my( $reqr, $evt ) = $U->checkses($auth);
2168 return $evt if $evt;
2169 my $editor = new_editor(requestor => $reqr, xact => 1);
2170 my $override = $self->api_name =~ /override/;
2172 # TODO: permission check
2173 # return $editor->event unless
2174 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2176 for my $sdist (@$sdists) {
2177 my $sdistid = $sdist->id;
2179 if( $sdist->isdeleted ) {
2180 $evt = _delete_sdist( $editor, $override, $sdist);
2181 } elsif( $sdist->isnew ) {
2182 $evt = _create_sdist( $editor, $sdist );
2184 $evt = _update_sdist( $editor, $override, $sdist );
2189 $logger->info("fleshed distribution-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2193 $logger->debug("distribution-alter: done updating distribution batch");
2195 $logger->info("fleshed distribution-alter successfully updated ".scalar(@$sdists)." distributions");
2200 my ($editor, $override, $sdist) = @_;
2201 $logger->info("distribution-alter: delete distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2202 return $editor->event unless $editor->delete_serial_distribution($sdist);
2207 my ($editor, $sdist) = @_;
2209 $logger->info("distribution-alter: new distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2210 return $editor->event unless $editor->create_serial_distribution($sdist);
2212 # create summaries too
2213 my $summary = new Fieldmapper::serial::basic_summary;
2214 $summary->distribution($sdist->id);
2215 $summary->generated_coverage('');
2216 return $editor->event unless $editor->create_serial_basic_summary($summary);
2217 $summary = new Fieldmapper::serial::supplement_summary;
2218 $summary->distribution($sdist->id);
2219 $summary->generated_coverage('');
2220 return $editor->event unless $editor->create_serial_supplement_summary($summary);
2221 $summary = new Fieldmapper::serial::index_summary;
2222 $summary->distribution($sdist->id);
2223 $summary->generated_coverage('');
2224 return $editor->event unless $editor->create_serial_index_summary($summary);
2226 # create a starter stream (TODO: reconsider this)
2227 my $stream = new Fieldmapper::serial::stream;
2228 $stream->distribution($sdist->id);
2229 return $editor->event unless $editor->create_serial_stream($stream);
2235 my ($editor, $override, $sdist) = @_;
2237 $logger->info("distribution-alter: retrieving distribution ".$sdist->id);
2238 my $orig_sdist = $editor->retrieve_serial_distribution($sdist->id);
2240 $logger->info("distribution-alter: original distribution ".OpenSRF::Utils::JSON->perl2JSON($orig_sdist));
2241 $logger->info("distribution-alter: updated distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2242 return $editor->event unless $editor->update_serial_distribution($sdist);
2246 __PACKAGE__->register_method(
2247 method => "fleshed_serial_distribution_retrieve_batch",
2249 api_name => "open-ils.serial.distribution.fleshed.batch.retrieve"
2252 sub fleshed_serial_distribution_retrieve_batch {
2253 my( $self, $client, $ids ) = @_;
2254 # FIXME: permissions?
2255 $logger->info("Fetching fleshed distributions @$ids");
2256 return $U->cstorereq(
2257 "open-ils.cstore.direct.serial.distribution.search.atomic",
2260 flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams / ]}
2264 __PACKAGE__->register_method(
2265 method => "retrieve_dist_tree",
2267 api_name => "open-ils.serial.distribution_tree.retrieve"
2270 __PACKAGE__->register_method(
2271 method => "retrieve_dist_tree",
2272 api_name => "open-ils.serial.distribution_tree.global.retrieve"
2275 sub retrieve_dist_tree {
2276 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2278 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2282 # TODO: permission support
2283 if(!@org_ids and $user_session) {
2285 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2286 @org_ids = ($user_obj->home_ou);
2289 my $e = new_editor();
2291 if( $self->api_name =~ /global/ ) {
2292 return $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }},
2294 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 / ]},
2295 order_by => {'sdist' => 'id'},
2296 'join' => {'ssub' => {}}
2298 ]); # TODO: filter for !deleted?
2302 for my $orgid (@org_ids) {
2303 my $dists = $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }, holding_lib => $orgid},
2305 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 / ]},
2306 order_by => {'sdist' => 'id'},
2307 'join' => {'ssub' => {}}
2309 ]); # TODO: filter for !deleted?
2310 push( @all_dists, @$dists ) if $dists;
2320 __PACKAGE__->register_method(
2321 method => "distribution_orgs_for_title",
2323 api_name => "open-ils.serial.distribution.retrieve_orgs_by_title"
2326 sub distribution_orgs_for_title {
2327 my( $self, $client, $record_id ) = @_;
2329 my $dists = $U->cstorereq(
2330 "open-ils.cstore.direct.serial.distribution.search.atomic",
2331 { '+ssub' => { record_entry => $record_id } },
2332 { 'join' => {'ssub' => {}} }); # TODO: filter on !deleted?
2334 my $orgs = { map {$_->holding_lib => 1 } @$dists };
2335 return [ keys %$orgs ];
2339 ##########################################################################
2340 # caption and pattern methods
2342 __PACKAGE__->register_method(
2343 method => 'scap_alter',
2344 api_name => 'open-ils.serial.caption_and_pattern.batch.update',
2348 desc => 'Receives an array of one or more caption and patterns and updates the database as needed',
2350 name => 'authtoken',
2351 desc => 'Authtoken for current user session',
2356 desc => 'Array of caption and patterns',
2362 desc => 'Returns 1 if successful, event if failed',
2369 my( $self, $conn, $auth, $scaps ) = @_;
2370 return 1 unless ref $scaps;
2371 my( $reqr, $evt ) = $U->checkses($auth);
2372 return $evt if $evt;
2373 my $editor = new_editor(requestor => $reqr, xact => 1);
2374 my $override = $self->api_name =~ /override/;
2376 # TODO: permission check
2377 # return $editor->event unless
2378 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2380 for my $scap (@$scaps) {
2381 my $scapid = $scap->id;
2383 if( $scap->isdeleted ) {
2384 $evt = _delete_scap( $editor, $override, $scap);
2385 } elsif( $scap->isnew ) {
2386 $evt = _create_scap( $editor, $scap );
2388 $evt = _update_scap( $editor, $override, $scap );
2393 $logger->info("caption_and_pattern-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2397 $logger->debug("caption_and_pattern-alter: done updating caption_and_pattern batch");
2399 $logger->info("caption_and_pattern-alter successfully updated ".scalar(@$scaps)." caption_and_patterns");
2404 my ($editor, $override, $scap) = @_;
2405 $logger->info("caption_and_pattern-alter: delete caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2406 my $sisses = $editor->search_serial_issuance(
2407 { caption_and_pattern => $scap->id }, { limit => 1 } ); #TODO: 'deleted' support?
2408 return OpenILS::Event->new(
2409 'SERIAL_CAPTION_AND_PATTERN_HAS_ISSUANCES', payload => $scap->id ) if (@$sisses);
2411 return $editor->event unless $editor->delete_serial_caption_and_pattern($scap);
2416 my ($editor, $scap) = @_;
2418 $logger->info("caption_and_pattern-alter: new caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2419 return $editor->event unless $editor->create_serial_caption_and_pattern($scap);
2424 my ($editor, $override, $scap) = @_;
2426 $logger->info("caption_and_pattern-alter: retrieving caption_and_pattern ".$scap->id);
2427 my $orig_scap = $editor->retrieve_serial_caption_and_pattern($scap->id);
2429 $logger->info("caption_and_pattern-alter: original caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($orig_scap));
2430 $logger->info("caption_and_pattern-alter: updated caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2431 return $editor->event unless $editor->update_serial_caption_and_pattern($scap);
2435 __PACKAGE__->register_method(
2436 method => "serial_caption_and_pattern_retrieve_batch",
2438 api_name => "open-ils.serial.caption_and_pattern.batch.retrieve"
2441 sub serial_caption_and_pattern_retrieve_batch {
2442 my( $self, $client, $ids ) = @_;
2443 $logger->info("Fetching caption_and_patterns @$ids");
2444 return $U->cstorereq(
2445 "open-ils.cstore.direct.serial.caption_and_pattern.search.atomic",
2450 ##########################################################################
2453 __PACKAGE__->register_method(
2454 method => 'sstr_alter',
2455 api_name => 'open-ils.serial.stream.batch.update',
2459 desc => 'Receives an array of one or more streams and updates the database as needed',
2461 name => 'authtoken',
2462 desc => 'Authtoken for current user session',
2467 desc => 'Array of streams',
2473 desc => 'Returns 1 if successful, event if failed',
2480 my( $self, $conn, $auth, $sstrs ) = @_;
2481 return 1 unless ref $sstrs;
2482 my( $reqr, $evt ) = $U->checkses($auth);
2483 return $evt if $evt;
2484 my $editor = new_editor(requestor => $reqr, xact => 1);
2485 my $override = $self->api_name =~ /override/;
2487 # TODO: permission check
2488 # return $editor->event unless
2489 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2491 for my $sstr (@$sstrs) {
2492 my $sstrid = $sstr->id;
2494 if( $sstr->isdeleted ) {
2495 $evt = _delete_sstr( $editor, $override, $sstr);
2496 } elsif( $sstr->isnew ) {
2497 $evt = _create_sstr( $editor, $sstr );
2499 $evt = _update_sstr( $editor, $override, $sstr );
2504 $logger->info("stream-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2508 $logger->debug("stream-alter: done updating stream batch");
2510 $logger->info("stream-alter successfully updated ".scalar(@$sstrs)." streams");
2515 my ($editor, $override, $sstr) = @_;
2516 $logger->info("stream-alter: delete stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2517 my $sitems = $editor->search_serial_item(
2518 { stream => $sstr->id }, { limit => 1 } ); #TODO: 'deleted' support?
2519 return OpenILS::Event->new(
2520 'SERIAL_STREAM_HAS_ITEMS', payload => $sstr->id ) if (@$sitems);
2522 return $editor->event unless $editor->delete_serial_stream($sstr);
2527 my ($editor, $sstr) = @_;
2529 $logger->info("stream-alter: new stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2530 return $editor->event unless $editor->create_serial_stream($sstr);
2535 my ($editor, $override, $sstr) = @_;
2537 $logger->info("stream-alter: retrieving stream ".$sstr->id);
2538 my $orig_sstr = $editor->retrieve_serial_stream($sstr->id);
2540 $logger->info("stream-alter: original stream ".OpenSRF::Utils::JSON->perl2JSON($orig_sstr));
2541 $logger->info("stream-alter: updated stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2542 return $editor->event unless $editor->update_serial_stream($sstr);
2546 __PACKAGE__->register_method(
2547 method => "serial_stream_retrieve_batch",
2549 api_name => "open-ils.serial.stream.batch.retrieve"
2552 sub serial_stream_retrieve_batch {
2553 my( $self, $client, $ids ) = @_;
2554 $logger->info("Fetching streams @$ids");
2555 return $U->cstorereq(
2556 "open-ils.cstore.direct.serial.stream.search.atomic",
2562 ##########################################################################
2565 __PACKAGE__->register_method(
2566 method => 'sum_alter',
2567 api_name => 'open-ils.serial.basic_summary.batch.update',
2571 desc => 'Receives an array of one or more summaries and updates the database as needed',
2573 name => 'authtoken',
2574 desc => 'Authtoken for current user session',
2579 desc => 'Array of basic summaries',
2585 desc => 'Returns 1 if successful, event if failed',
2591 __PACKAGE__->register_method(
2592 method => 'sum_alter',
2593 api_name => 'open-ils.serial.supplement_summary.batch.update',
2597 desc => 'Receives an array of one or more summaries and updates the database as needed',
2599 name => 'authtoken',
2600 desc => 'Authtoken for current user session',
2605 desc => 'Array of supplement summaries',
2611 desc => 'Returns 1 if successful, event if failed',
2617 __PACKAGE__->register_method(
2618 method => 'sum_alter',
2619 api_name => 'open-ils.serial.index_summary.batch.update',
2623 desc => 'Receives an array of one or more summaries and updates the database as needed',
2625 name => 'authtoken',
2626 desc => 'Authtoken for current user session',
2631 desc => 'Array of index summaries',
2637 desc => 'Returns 1 if successful, event if failed',
2644 my( $self, $conn, $auth, $sums ) = @_;
2645 return 1 unless ref $sums;
2647 $self->api_name =~ /serial\.(\w*)_summary/;
2650 my( $reqr, $evt ) = $U->checkses($auth);
2651 return $evt if $evt;
2652 my $editor = new_editor(requestor => $reqr, xact => 1);
2653 my $override = $self->api_name =~ /override/;
2655 # TODO: permission check
2656 # return $editor->event unless
2657 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2659 for my $sum (@$sums) {
2660 my $sumid = $sum->id;
2662 # XXX: (for now, at least) summaries should be created/deleted by the distribution functions
2663 if( $sum->isdeleted ) {
2664 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2665 } elsif( $sum->isnew ) {
2666 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2668 $evt = _update_sum( $editor, $override, $sum, $type );
2673 $logger->info("${type}_summary-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2677 $logger->debug("${type}_summary-alter: done updating ${type}_summary batch");
2679 $logger->info("${type}_summary-alter successfully updated ".scalar(@$sums)." ${type}_summaries");
2684 my ($editor, $override, $sum, $type) = @_;
2686 $logger->info("${type}_summary-alter: retrieving ${type}_summary ".$sum->id);
2687 my $retrieve_method = "retrieve_serial_${type}_summary";
2688 my $orig_sum = $editor->$retrieve_method($sum->id);
2690 $logger->info("${type}_summary-alter: original ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($orig_sum));
2691 $logger->info("${type}_summary-alter: updated ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($sum));
2692 my $update_method = "update_serial_${type}_summary";
2693 return $editor->event unless $editor->$update_method($sum);
2697 __PACKAGE__->register_method(
2698 method => "serial_summary_retrieve_batch",
2700 api_name => "open-ils.serial.basic_summary.batch.retrieve"
2703 __PACKAGE__->register_method(
2704 method => "serial_summary_retrieve_batch",
2706 api_name => "open-ils.serial.supplement_summary.batch.retrieve"
2709 __PACKAGE__->register_method(
2710 method => "serial_summary_retrieve_batch",
2712 api_name => "open-ils.serial.index_summary.batch.retrieve"
2715 sub serial_summary_retrieve_batch {
2716 my( $self, $client, $ids ) = @_;
2718 $self->api_name =~ /serial\.(\w*)_summary/;
2721 $logger->info("Fetching ${type}_summaries @$ids");
2722 return $U->cstorereq(
2723 "open-ils.cstore.direct.serial.".$type."_summary.search.atomic",
2729 ##########################################################################
2732 __PACKAGE__->register_method(
2733 "method" => "bre_by_identifier",
2734 "api_name" => "open-ils.serial.biblio.record_entry.by_identifier",
2737 "desc" => "Find instances of biblio.record_entry given a search token" .
2738 " that could be a value for any identifier defined in " .
2739 "config.metabib_field",
2741 {"desc" => "Search token", "type" => "string"},
2742 {"desc" => "Options: require_subscriptions, add_mvr, is_actual_id" .
2743 " (all boolean)", "type" => "object"}
2746 "desc" => "Any matching BREs, or if the add_mvr option is true, " .
2747 "objects with a 'bre' key/value pair, and an 'mvr' " .
2748 "key-value pair. BREs have subscriptions fleshed on.",
2754 sub bre_by_identifier {
2755 my ($self, $client, $term, $options) = @_;
2757 return new OpenILS::Event("BAD_PARAMS") unless $term;
2760 my $e = new_editor();
2764 if ($options->{"is_actual_id"}) {
2768 $e->search_config_metabib_field({"field_class" => "identifier"})
2769 or return $e->die_event;
2771 my @identifiers = map { $_->name } @$cmf;
2772 my $query = join(" || ", map { "id|$_: $term" } @identifiers);
2774 my $search = create OpenSRF::AppSession("open-ils.search");
2775 my $search_result = $search->request(
2776 "open-ils.search.biblio.multiclass.query.staff", {}, $query
2778 $search->disconnect;
2780 # Un-nest results. They tend to look like [[1],[2],[3]] for some reason.
2781 @ids = map { @{$_} } @{$search_result->{"ids"}};
2789 my $bre = $e->search_biblio_record_entry([
2791 "flesh" => 2, "flesh_fields" => {
2792 "bre" => ["subscriptions"],
2793 "ssub" => ["owning_lib"]
2796 ]) or return $e->die_event;
2798 if (@$bre && $options->{"require_subscriptions"}) {
2799 $bre = [ grep { @{$_->subscriptions} } @$bre ];
2804 if (@$bre) { # re-evaluate after possible grep
2805 if ($options->{"add_mvr"}) {
2807 {"bre" => $_, "mvr" => _get_mvr($_->id)}
2810 $client->respond($_) foreach (@$bre);
2817 __PACKAGE__->register_method(
2818 "method" => "get_items_by",
2819 "api_name" => "open-ils.serial.items.receivable.by_subscription",
2822 "desc" => "Return all receivable items under a given subscription",
2824 {"desc" => "Authtoken", "type" => "string"},
2825 {"desc" => "Subscription ID", "type" => "number"},
2828 "desc" => "All receivable items under a given subscription",
2829 "type" => "object", "class" => "sitem"
2834 __PACKAGE__->register_method(
2835 "method" => "get_items_by",
2836 "api_name" => "open-ils.serial.items.receivable.by_issuance",
2839 "desc" => "Return all receivable items under a given issuance",
2841 {"desc" => "Authtoken", "type" => "string"},
2842 {"desc" => "Issuance ID", "type" => "number"},
2845 "desc" => "All receivable items under a given issuance",
2846 "type" => "object", "class" => "sitem"
2851 __PACKAGE__->register_method(
2852 "method" => "get_items_by",
2853 "api_name" => "open-ils.serial.items.by_issuance",
2856 "desc" => "Return all items under a given issuance",
2858 {"desc" => "Authtoken", "type" => "string"},
2859 {"desc" => "Issuance ID", "type" => "number"},
2862 "desc" => "All items under a given issuance",
2863 "type" => "object", "class" => "sitem"
2869 my ($self, $client, $auth, $term, $opts) = @_;
2871 # Not to be used in the json_query, but after limiting by perm check.
2872 $opts = {} unless ref $opts eq "HASH";
2873 $opts->{"limit"} ||= 10000; # some existing users may want all results
2874 $opts->{"offset"} ||= 0;
2875 $opts->{"limit"} = int($opts->{"limit"});
2876 $opts->{"offset"} = int($opts->{"offset"});
2878 my $e = new_editor("authtoken" => $auth);
2879 return $e->die_event unless $e->checkauth;
2881 my $by = ($self->api_name =~ /by_(\w+)$/)[0];
2882 my $receivable = ($self->api_name =~ /receivable/);
2885 "issuance" => {"issuance" => $term},
2886 "subscription" => {"+siss" => {"subscription" => $term}}
2889 my $item_rows = $e->json_query(
2891 "select" => {"sitem" => ["id"], "sdist" => ["holding_lib"]},
2895 "sstr" => {"join" => {"sdist" => {}}}
2899 %{$where{$by}}, $receivable ? ("date_received" => undef) : ()
2901 "order_by" => {"sitem" => ["id"]}
2903 ) or return $e->die_event;
2905 return undef unless @$item_rows;
2909 foreach (@$item_rows) {
2910 last if $returned >= $opts->{"limit"};
2911 next unless $e->allowed("RECEIVE_SERIAL", $_->{"holding_lib"});
2912 if ($skipped < $opts->{"offset"}) {
2918 $e->retrieve_serial_item([
2922 "sitem" => [qw/stream issuance unit creator editor/],
2923 "sstr" => ["distribution"],
2924 "sdist" => ["holding_lib"]
2936 __PACKAGE__->register_method(
2937 "method" => "get_receivable_issuances",
2938 "api_name" => "open-ils.serial.issuances.receivable",
2941 "desc" => "Return all issuances with receivable items given " .
2942 "a subscription ID",
2944 {"desc" => "Authtoken", "type" => "string"},
2945 {"desc" => "Subscription ID", "type" => "number"},
2948 "desc" => "All issuances with receivable items " .
2949 "(but not the items themselves)", "type" => "object"
2954 sub get_receivable_issuances {
2955 my ($self, $client, $auth, $sub_id) = @_;
2957 my $e = new_editor("authtoken" => $auth);
2958 return $e->die_event unless $e->checkauth;
2962 my $issuance_ids = $e->json_query({
2965 {"transform" => "distinct", "column" => "id"},
2969 "from" => {"siss" => "sitem"},
2971 "subscription" => $sub_id,
2972 "+sitem" => {"date_received" => undef}
2975 "siss" => {"date_published" => {"direction" => "asc"}}
2978 }) or return $e->die_event;
2980 $client->respond($e->retrieve_serial_issuance($_->{"id"}))
2981 foreach (@$issuance_ids);
2988 __PACKAGE__->register_method(
2989 "method" => "get_routing_list_users",
2990 "api_name" => "open-ils.serial.routing_list_users.fleshed_and_ordered",
2993 "desc" => "Return all routing list users with reader fleshed " .
2994 "(with card and home_ou) for a given stream ID, sorted by pos",
2996 {"desc" => "Authtoken", "type" => "string"},
2997 {"desc" => "Stream ID (int or array of ints)", "type" => "mixed"},
3000 "desc" => "Stream of routing list users", "type" => "object",
3006 sub get_routing_list_users {
3007 my ($self, $client, $auth, $stream_id) = @_;
3009 my $e = new_editor("authtoken" => $auth);
3010 return $e->die_event unless $e->checkauth;
3012 my $users = $e->search_serial_routing_list_user([
3013 {"stream" => $stream_id}, {
3014 "order_by" => {"srlu" => "pos"},
3017 "srlu" => [qw/reader stream/],
3018 "au" => [qw/card home_ou/],
3019 "sstr" => ["distribution"]
3022 ]) or return $e->die_event;
3024 return undef unless @$users;
3026 # The ADMIN_SERIAL_STREAM permission is used simply to avoid the
3027 # need for any new permission. The context OU will be the same
3028 # for every result of the above query, so we need only check once.
3029 return $e->die_event unless $e->allowed(
3030 "ADMIN_SERIAL_STREAM", $users->[0]->stream->distribution->holding_lib
3035 my @users = map { $_->stream($_->stream->id); $_ } @$users;
3036 @users = sort { $a->stream cmp $b->stream } @users if
3037 ref $stream_id eq "ARRAY";
3039 $client->respond($_) for @users;
3045 __PACKAGE__->register_method(
3046 "method" => "replace_routing_list_users",
3047 "api_name" => "open-ils.serial.routing_list_users.replace",
3049 "desc" => "Replace all routing list users on the specified streams " .
3050 "with those in the list argument",
3052 {"desc" => "Authtoken", "type" => "string"},
3053 {"desc" => "List of srlu objects", "type" => "array"},
3056 "desc" => "event on failure, undef on success"
3061 sub replace_routing_list_users {
3062 my ($self, $client, $auth, $users) = @_;
3064 return undef unless ref $users eq "ARRAY";
3066 if (grep { ref $_ ne "Fieldmapper::serial::routing_list_user" } @$users) {
3067 return new OpenILS::Event("BAD_PARAMS", "note" => "Only srlu objects");
3070 my $e = new_editor("authtoken" => $auth, "xact" => 1);
3071 return $e->die_event unless $e->checkauth;
3073 my %streams_ok = ();
3076 foreach my $user (@$users) {
3077 unless (exists $streams_ok{$user->stream}) {
3078 my $stream = $e->retrieve_serial_stream([
3081 "flesh_fields" => {"sstr" => ["distribution"]}
3083 ]) or return $e->die_event;
3085 "ADMIN_SERIAL_STREAM", $stream->distribution->holding_lib
3086 ) or return $e->die_event;
3088 my $to_delete = $e->search_serial_routing_list_user(
3089 {"stream" => $user->stream}
3090 ) or return $e->die_event;
3093 "Deleting srlu: [" .
3094 join(", ", map { $_->id; } @$to_delete) .
3098 foreach (@$to_delete) {
3099 $e->delete_serial_routing_list_user($_) or
3100 return $e->die_event;
3103 $streams_ok{$user->stream} = 1;
3106 next if $user->isdeleted;
3110 $e->create_serial_routing_list_user($user) or return $e->die_event;
3113 $e->commit or return $e->die_event;
3117 __PACKAGE__->register_method(
3118 "method" => "get_records_with_marc_85x",
3119 "api_name"=>"open-ils.serial.caption_and_pattern.find_legacy_by_bib_record",
3122 "desc" => "Return the specified BRE itself and/or any related SRE ".
3123 "whenever they have 853-855 tags",
3125 {"desc" => "Authtoken", "type" => "string"},
3126 {"desc" => "bib record ID", "type" => "number"},
3129 "desc" => "objects, either bre or sre", "type" => "object"
3134 sub get_records_with_marc_85x { # specifically, 853-855
3135 my ($self, $client, $auth, $bre_id) = @_;
3137 my $e = new_editor("authtoken" => $auth);
3138 return $e->die_event unless $e->checkauth;
3140 my $bre = $e->search_biblio_record_entry([
3141 {"id" => $bre_id, "deleted" => "f"}, {
3143 "flesh_fields" => {"bre" => [qw/creator editor owner/]}
3145 ]) or return $e->die_event;
3147 return undef unless @$bre;
3150 my $record = MARC::Record->new_from_xml($bre->marc);
3151 $client->respond($bre) if $record->field("85[3-5]");
3152 # XXX Is passing a regex to ->field() an abuse of MARC::Record ?
3154 my $sres = $e->search_serial_record_entry([
3155 {"record" => $bre_id, "deleted" => "f"}, {
3157 "flesh_fields" => {"sre" => [qw/creator editor owning_lib/]}
3159 ]) or return $e->die_event;
3163 foreach my $sre (@$sres) {
3164 $client->respond($sre) if
3165 MARC::Record->new_from_xml($sre->marc)->field("85[3-5]");
3171 __PACKAGE__->register_method(
3172 "method" => "create_scaps_from_marcxml",
3173 "api_name" => "open-ils.serial.caption_and_pattern.create_from_records",
3176 "desc" => "Create caption and pattern objects from 853-855 tags " .
3177 "in MARCXML documents",
3179 {"desc" => "Authtoken", "type" => "string"},
3180 {"desc" => "Subscription ID", "type" => "number"},
3181 {"desc" => "list of MARCXML documents as strings",
3185 "desc" => "Newly created caption and pattern objects",
3186 "type" => "object", "class" => "scap"
3191 sub create_scaps_from_marcxml {
3192 my ($self, $client, $auth, $sub_id, $docs) = @_;
3194 return undef unless ref $docs eq "ARRAY";
3196 my $e = new_editor("authtoken" => $auth, "xact" => 1);
3197 return $e->die_event unless $e->checkauth;
3199 # Retrieve the subscription just for perm checking (whether we can create
3200 # scaps at the owning lib).
3201 my $sub = $e->retrieve_serial_subscription($sub_id) or return $e->die_event;
3202 return $e->die_event unless
3203 $e->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $sub->owning_lib);
3205 foreach my $record (map { MARC::Record->new_from_xml($_) } @$docs) {
3206 foreach my $field ($record->field("85[3-5]")) {
3207 my $scap = new Fieldmapper::serial::caption_and_pattern;
3208 $scap->subscription($sub_id);
3209 $scap->type($MFHD_NAMES_BY_TAG{$field->tag});
3210 $scap->pattern_code(
3211 OpenSRF::Utils::JSON->perl2JSON(
3212 [ $field->indicator(1), $field->indicator(2),
3213 map { @$_ } $field->subfields ] # flattens nested array
3216 $e->create_serial_caption_and_pattern($scap) or
3217 return $e->die_event;
3218 $client->respond($e->data);
3222 $e->commit or return $e->die_event;