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 MARC::File::XML (BinaryEncoding => 'utf8');
52 my $U = 'OpenILS::Application::AppUtils';
53 my @MFHD_NAMES = ('basic','supplement','index');
54 my %MFHD_NAMES_BY_TAG = ( '853' => $MFHD_NAMES[0],
55 '863' => $MFHD_NAMES[0],
56 '854' => $MFHD_NAMES[1],
57 '864' => $MFHD_NAMES[1],
58 '855' => $MFHD_NAMES[2],
59 '865' => $MFHD_NAMES[2] );
60 my %MFHD_TAGS_BY_NAME = ( $MFHD_NAMES[0] => '853',
61 $MFHD_NAMES[1] => '854',
62 $MFHD_NAMES[2] => '855');
63 my $_strp_date = new DateTime::Format::Strptime(pattern => '%F');
65 # helper method for conforming dates to ISO8601
70 foreach my $field (@$fields) {
71 $item->$field(OpenSRF::Utils::clense_ISO8601($item->$field)) if $item->$field;
79 "open-ils.search.biblio.record.mods_slim.retrieve",
85 ##########################################################################
88 __PACKAGE__->register_method(
89 method => 'fleshed_item_alter',
90 api_name => 'open-ils.serial.item.fleshed.batch.update',
94 desc => 'Receives an array of one or more items and updates the database as needed',
97 desc => 'Authtoken for current user session',
102 desc => 'Array of fleshed items',
108 desc => 'Returns 1 if successful, event if failed',
114 sub fleshed_item_alter {
115 my( $self, $conn, $auth, $items ) = @_;
116 return 1 unless ref $items;
117 my( $reqr, $evt ) = $U->checkses($auth);
119 my $editor = new_editor(requestor => $reqr, xact => 1);
120 my $override = $self->api_name =~ /override/;
122 # TODO: permission check
123 # return $editor->event unless
124 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
126 for my $item (@$items) {
128 my $itemid = $item->id;
129 $item->editor($editor->requestor->id);
130 $item->edit_date('now');
132 if( $item->isdeleted ) {
133 $evt = _delete_sitem( $editor, $override, $item);
134 } elsif( $item->isnew ) {
135 # TODO: reconsider this
136 # if the item has a new issuance, create the issuance first
137 if (ref $item->issuance eq 'Fieldmapper::serial::issuance' and $item->issuance->isnew) {
138 fleshed_issuance_alter($self, $conn, $auth, [$item->issuance]);
140 _cleanse_dates($item, ['date_expected','date_received']);
141 $evt = _create_sitem( $editor, $item );
143 _cleanse_dates($item, ['date_expected','date_received']);
144 $evt = _update_sitem( $editor, $override, $item );
149 $logger->info("fleshed item-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
153 $logger->debug("item-alter: done updating item batch");
155 $logger->info("fleshed item-alter successfully updated ".scalar(@$items)." items");
160 my ($editor, $override, $item) = @_;
161 $logger->info("item-alter: delete item ".OpenSRF::Utils::JSON->perl2JSON($item));
162 return $editor->event unless $editor->delete_serial_item($item);
167 my ($editor, $item) = @_;
169 $item->creator($editor->requestor->id);
170 $item->create_date('now');
172 $logger->info("item-alter: new item ".OpenSRF::Utils::JSON->perl2JSON($item));
173 return $editor->event unless $editor->create_serial_item($item);
178 my ($editor, $override, $item) = @_;
180 $logger->info("item-alter: retrieving item ".$item->id);
181 my $orig_item = $editor->retrieve_serial_item($item->id);
183 $logger->info("item-alter: original item ".OpenSRF::Utils::JSON->perl2JSON($orig_item));
184 $logger->info("item-alter: updated item ".OpenSRF::Utils::JSON->perl2JSON($item));
185 return $editor->event unless $editor->update_serial_item($item);
189 __PACKAGE__->register_method(
190 method => "fleshed_serial_item_retrieve_batch",
192 api_name => "open-ils.serial.item.fleshed.batch.retrieve"
195 sub fleshed_serial_item_retrieve_batch {
196 my( $self, $client, $ids ) = @_;
197 # FIXME: permissions?
198 $logger->info("Fetching fleshed serial items @$ids");
199 return $U->cstorereq(
200 "open-ils.cstore.direct.serial.item.search.atomic",
203 flesh_fields => {sitem => [ qw/issuance creator editor stream unit notes/ ], sstr => ["distribution"], sunit => ["call_number"], siss => [qw/creator editor subscription/]}
208 ##########################################################################
211 __PACKAGE__->register_method(
212 method => 'fleshed_issuance_alter',
213 api_name => 'open-ils.serial.issuance.fleshed.batch.update',
217 desc => 'Receives an array of one or more issuances and updates the database as needed',
220 desc => 'Authtoken for current user session',
225 desc => 'Array of fleshed issuances',
231 desc => 'Returns 1 if successful, event if failed',
237 sub fleshed_issuance_alter {
238 my( $self, $conn, $auth, $issuances ) = @_;
239 return 1 unless ref $issuances;
240 my( $reqr, $evt ) = $U->checkses($auth);
242 my $editor = new_editor(requestor => $reqr, xact => 1);
243 my $override = $self->api_name =~ /override/;
245 # TODO: permission support
246 # return $editor->event unless
247 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
249 for my $issuance (@$issuances) {
250 my $issuanceid = $issuance->id;
251 $issuance->editor($editor->requestor->id);
252 $issuance->edit_date('now');
254 if( $issuance->isdeleted ) {
255 $evt = _delete_siss( $editor, $override, $issuance);
256 } elsif( $issuance->isnew ) {
257 _cleanse_dates($issuance, ['date_published']);
258 $evt = _create_siss( $editor, $issuance );
260 _cleanse_dates($issuance, ['date_published']);
261 $evt = _update_siss( $editor, $override, $issuance );
266 $logger->info("fleshed issuance-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
270 $logger->debug("issuance-alter: done updating issuance batch");
272 $logger->info("fleshed issuance-alter successfully updated ".scalar(@$issuances)." issuances");
277 my ($editor, $override, $issuance) = @_;
278 $logger->info("issuance-alter: delete issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
279 return $editor->event unless $editor->delete_serial_issuance($issuance);
284 my ($editor, $issuance) = @_;
286 $issuance->creator($editor->requestor->id);
287 $issuance->create_date('now');
289 $logger->info("issuance-alter: new issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
290 return $editor->event unless $editor->create_serial_issuance($issuance);
295 my ($editor, $override, $issuance) = @_;
297 $logger->info("issuance-alter: retrieving issuance ".$issuance->id);
298 my $orig_issuance = $editor->retrieve_serial_issuance($issuance->id);
300 $logger->info("issuance-alter: original issuance ".OpenSRF::Utils::JSON->perl2JSON($orig_issuance));
301 $logger->info("issuance-alter: updated issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
302 return $editor->event unless $editor->update_serial_issuance($issuance);
306 __PACKAGE__->register_method(
307 method => "fleshed_serial_issuance_retrieve_batch",
309 api_name => "open-ils.serial.issuance.fleshed.batch.retrieve"
312 sub fleshed_serial_issuance_retrieve_batch {
313 my( $self, $client, $ids ) = @_;
314 # FIXME: permissions?
315 $logger->info("Fetching fleshed serial issuances @$ids");
316 return $U->cstorereq(
317 "open-ils.cstore.direct.serial.issuance.search.atomic",
320 flesh_fields => {siss => [ qw/creator editor subscription/ ]}
324 __PACKAGE__->register_method(
325 method => "pub_fleshed_serial_issuance_retrieve_batch",
326 api_name => "open-ils.serial.issuance.pub_fleshed.batch.retrieve",
329 Public (i.e. OPAC) call for getting at the sub and
330 ultimately the record entry from an issuance
332 params => [{name => 'ids', desc => 'Array of IDs', type => 'array'}],
335 issuance objects, fleshed with subscriptions
341 sub pub_fleshed_serial_issuance_retrieve_batch {
342 my( $self, $client, $ids ) = @_;
343 return [] unless $ids and @$ids;
344 return new_editor()->search_serial_issuance([
348 flesh_fields => {siss => [ qw/subscription/ ]}
353 sub received_siss_by_bib {
358 my $args = shift || {};
359 $$args{order} ||= 'asc';
361 my $global = $$args{global} == 0 ? 0 : 1;
363 my $e = new_editor();
364 my $issuances = $e->json_query({
367 $global ? { transform => "min", column => "id", aggregate => 1 } : "id",
372 # We're not really interested in the minimum here. This is
373 # just a way to distinguish issuances whose items have units
374 # from issuances whose items have no units, without altogether
375 # excluding the latter type of issuances.
376 {"transform" => "min", "alias" => "has_units",
377 "column" => "unit", "aggregate" => 1}
383 field => 'subscription',
389 $$args{ou} ? ( join => {
396 fkey => 'distribution'
407 '+ssub' => { record_entry => $bib },
408 $$args{type} ? ( '+siss' => { 'holding_type' => $$args{type} } ) : (),
410 # XXX should we also take specific item statuses into account?
411 date_received => { '!=' => undef },
412 $$args{status} ? ( 'status' => $$args{status} ) : ()
414 $$args{ou} ? ( '+sdist' => {
416 'in' => $U->get_org_descendants($$args{ou}, $$args{depth})
420 $$args{limit} ? ( limit => $$args{limit} ) : (),
421 $$args{offset} ? ( offset => $$args{offset} ) : (),
422 order_by => [{ class => 'siss', field => 'date_published', direction => $$args{order} }],
427 "issuance" => $e->retrieve_serial_issuance($_->{"id"}),
428 "has_units" => $_->{"has_units"} ? 1 : 0
433 __PACKAGE__->register_method(
434 method => 'received_siss_by_bib',
435 api_name => 'open-ils.serial.received_siss.retrieve.by_bib',
440 desc => 'Receives a Bib ID and other optional params and returns "siss" (issuance) objects',
443 desc => 'id of the bre to which the issuances belong',
448 q/A hash of optional arguments. Valid keys and their meanings:
449 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).
450 order := date_published sort direction, either "asc" (chronological, default) or "desc" (reverse chronological)
451 limit := Number of issuances to return. Useful for paging results, or finding the oldest or newest
452 offset := Number of issuance to skip before returning results. Useful for paging.
453 orgid := OU id used to scope retrieval, based on distribution.holding_lib
454 depth := OU depth used to range the scope of orgid
455 type := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
456 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).
464 sub scoped_bib_holdings_summary {
468 my $args = shift || {};
470 $args->{order} = 'asc';
472 my ($issuances) = $self->method_lookup('open-ils.serial.received_siss.retrieve.by_bib.atomic')->run( $bibid => $args );
474 # split into issuance type sets
475 my %type_blob = (basic => [], supplement => [], index => []);
476 push @{ $type_blob{ $_->{"issuance"}->holding_type } }, $_->{"issuance"}
479 # generate a statement list for each type
481 for my $type ( keys %type_blob ) {
482 my ($mfhd,$list) = _summarize_contents(new_editor(), $type_blob{$type});
483 $statement_blob{$type} = $list;
486 return \%statement_blob;
488 __PACKAGE__->register_method(
489 method => 'scoped_bib_holdings_summary',
490 api_name => 'open-ils.serial.bib.summary_statements',
494 desc => 'Receives a Bib ID and other optional params and returns set of holdings statements',
497 desc => 'id of the bre to which the issuances belong',
502 q/A hash of optional arguments. Valid keys and their meanings:
503 orgid := OU id used to scope retrieval, based on distribution.holding_lib
504 depth := OU depth used to range the scope of orgid
505 type := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
506 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).
514 ##########################################################################
517 __PACKAGE__->register_method(
518 method => 'fleshed_sunit_alter',
519 api_name => 'open-ils.serial.sunit.fleshed.batch.update',
523 desc => 'Receives an array of one or more Units and updates the database as needed',
526 desc => 'Authtoken for current user session',
531 desc => 'Array of fleshed Units',
537 desc => 'Returns 1 if successful, event if failed',
543 sub fleshed_sunit_alter {
544 my( $self, $conn, $auth, $sunits ) = @_;
545 return 1 unless ref $sunits;
546 my( $reqr, $evt ) = $U->checkses($auth);
548 my $editor = new_editor(requestor => $reqr, xact => 1);
549 my $override = $self->api_name =~ /override/;
551 # TODO: permission support
552 # return $editor->event unless
553 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
555 for my $sunit (@$sunits) {
556 if( $sunit->isdeleted ) {
557 $evt = _delete_sunit( $editor, $override, $sunit );
559 $sunit->default_location( $sunit->default_location->id ) if ref $sunit->default_location;
561 if( $sunit->isnew ) {
562 $evt = _create_sunit( $editor, $sunit );
564 $evt = _update_sunit( $editor, $override, $sunit );
570 $logger->info("fleshed sunit-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
574 $logger->debug("sunit-alter: done updating sunit batch");
576 $logger->info("fleshed sunit-alter successfully updated ".scalar(@$sunits)." Units");
581 my ($editor, $override, $sunit) = @_;
582 $logger->info("sunit-alter: delete sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
583 return $editor->event unless $editor->delete_serial_unit($sunit);
588 my ($editor, $sunit) = @_;
590 $logger->info("sunit-alter: new Unit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
591 return $editor->event unless $editor->create_serial_unit($sunit);
596 my ($editor, $override, $sunit) = @_;
598 $logger->info("sunit-alter: retrieving sunit ".$sunit->id);
599 my $orig_sunit = $editor->retrieve_serial_unit($sunit->id);
601 $logger->info("sunit-alter: original sunit ".OpenSRF::Utils::JSON->perl2JSON($orig_sunit));
602 $logger->info("sunit-alter: updated sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
603 return $editor->event unless $editor->update_serial_unit($sunit);
607 __PACKAGE__->register_method(
608 method => "retrieve_unit_list",
610 api_name => "open-ils.serial.unit_list.retrieve"
613 sub retrieve_unit_list {
615 my( $self, $client, @sdist_ids ) = @_;
617 if(ref($sdist_ids[0])) { @sdist_ids = @{$sdist_ids[0]}; }
619 my $e = new_editor();
623 { 'sunit' => [ 'id', 'summary_contents', 'sort_key' ],
624 'sitem' => ['stream'],
625 'sstr' => ['distribution'],
626 'sdist' => [{'column' => 'label', 'alias' => 'sdist_label'}]
633 { 'join' => { 'sunit' => {} } }
638 'distinct' => 'true',
639 'where' => { '+sdist' => {'id' => \@sdist_ids} },
640 'order_by' => [{'class' => 'sunit', 'field' => 'sort_key'}]
643 my $unit_list_entries = $e->json_query($query);
646 foreach my $entry (@$unit_list_entries) {
647 my $value = {'sunit' => $entry->{id}, 'sstr' => $entry->{stream}, 'sdist' => $entry->{distribution}};
648 my $label = $entry->{summary_contents};
649 if (length($label) > 100) {
650 $label = substr($label, 0, 100) . '...'; # limited space in dropdown / menu
652 $label = "[$entry->{sdist_label}/$entry->{stream} #$entry->{id}] " . $label;
653 push (@entries, [$label, OpenSRF::Utils::JSON->perl2JSON($value)]);
661 ##########################################################################
662 # predict and receive methods
664 __PACKAGE__->register_method(
665 method => 'make_predictions',
666 api_name => 'open-ils.serial.make_predictions',
670 desc => 'Receives an ssub id and populates the issuance and item tables',
673 desc => 'Serial Subscription ID',
680 sub make_predictions {
681 my ($self, $conn, $authtoken, $args) = @_;
683 my $editor = OpenILS::Utils::CStoreEditor->new();
684 my $ssub_id = $args->{ssub_id};
685 my $mfhd = MFHD->new(MARC::Record->new());
687 my $ssub = $editor->retrieve_serial_subscription([$ssub_id]);
688 my $scaps = $editor->search_serial_caption_and_pattern({ subscription => $ssub_id, active => 't'});
689 my $sdists = $editor->search_serial_distribution( [{ subscription => $ssub->id }, { flesh => 1, flesh_fields => {sdist => [ qw/ streams / ]} }] ); #TODO: 'deleted' support?
691 my $total_streams = 0;
693 $total_streams += scalar(@{$_->streams});
695 if ($total_streams < 1) {
697 # XXX TODO new event type
698 return new OpenILS::Event(
699 "BAD_PARAMS", note =>
700 "There are no streams to direct items. Can't predict."
706 # XXX TODO new event type
707 return new OpenILS::Event(
708 "BAD_PARAMS", note =>
709 "There are no active caption-and-pattern objects associated " .
710 "with this subscription. Can't predict."
716 foreach my $scap (@$scaps) {
717 my $caption_field = _revive_caption($scap);
718 $caption_field->update('8' => $link_id);
719 $mfhd->append_fields($caption_field);
721 'caption' => $caption_field,
722 'scap_id' => $scap->id,
723 'num_to_predict' => $args->{num_to_predict},
724 'end_date' => defined $args->{end_date} ?
725 $_strp_date->parse_datetime($args->{end_date}) : undef
727 if ($args->{base_issuance}) { # predict from a given issuance
728 $options->{predict_from} = _revive_holding($args->{base_issuance}->holding_code, $caption_field, 1); # fresh MFHD Record, so we simply default to 1 for seqno
729 } else { # default to predicting from last published
730 my $last_published = $editor->search_serial_issuance([
731 {'caption_and_pattern' => $scap->id,
732 'subscription' => $ssub_id},
733 {limit => 1, order_by => { siss => "date_published DESC" }}]
735 if ($last_published->[0]) {
736 my $last_siss = $last_published->[0];
737 unless ($last_siss->holding_code) {
739 # XXX TODO new event type
740 return new OpenILS::Event(
741 "BAD_PARAMS", note =>
742 "Last issuance has no holding code. Can't predict."
745 $options->{predict_from} = _revive_holding($last_siss->holding_code, $caption_field, 1);
748 # XXX TODO make a new event type instead of hijacking this one
749 return new OpenILS::Event(
750 "BAD_PARAMS", note => "No issuance from which to predict!"
754 push( @predictions, _generate_issuance_values($mfhd, $options) );
759 foreach my $prediction (@predictions) {
760 my $issuance = new Fieldmapper::serial::issuance;
762 $issuance->label($prediction->{label});
763 $issuance->date_published($prediction->{date_published}->strftime('%F'));
764 $issuance->holding_code(OpenSRF::Utils::JSON->perl2JSON($prediction->{holding_code}));
765 $issuance->holding_type($prediction->{holding_type});
766 $issuance->caption_and_pattern($prediction->{caption_and_pattern});
767 $issuance->subscription($ssub->id);
768 push (@issuances, $issuance);
771 fleshed_issuance_alter($self, $conn, $authtoken, \@issuances); # FIXME: catch events
774 for (my $i = 0; $i < @issuances; $i++) {
775 my $date_expected = $predictions[$i]->{date_published}->add(seconds => interval_to_seconds($ssub->expected_date_offset))->strftime('%F');
776 my $issuance = $issuances[$i];
777 #$issuance->label(interval_to_seconds($ssub->expected_date_offset));
778 foreach my $sdist (@$sdists) {
779 my $streams = $sdist->streams;
780 foreach my $stream (@$streams) {
781 my $item = new Fieldmapper::serial::item;
783 $item->stream($stream->id);
784 $item->date_expected($date_expected);
785 $item->issuance($issuance->id);
786 push (@items, $item);
790 fleshed_item_alter($self, $conn, $authtoken, \@items); # FIXME: catch events
795 # _generate_issuance_values() is an initial attempt at a function which can be used
796 # to populate an issuance table with a list of predicted issues. It accepts
797 # a hash ref of options initially defined as:
798 # caption : the caption field to predict on
799 # num_to_predict : the number of issues you wish to predict
800 # last_rec_date : the date of the last received issue, to be used as an offset
801 # for predicting future issues
803 # The basic method is to first convert to a single holding if compressed, then
804 # increment the holding and save the resulting values to @issuances.
806 # returns @issuance_values, an array of hashrefs containing (formatted
807 # label, formatted chronology date, formatted estimated arrival date, and an
808 # array ref of holding subfields as (key, value, key, value ...)) (not a hash
809 # to protect order and possible duplicate keys), and a holding type.
811 sub _generate_issuance_values {
812 my ($mfhd, $options) = @_;
813 my $caption = $options->{caption};
814 my $scap_id = $options->{scap_id};
815 my $num_to_predict = $options->{num_to_predict};
816 my $end_date = $options->{end_date};
817 my $predict_from = $options->{predict_from}; # issuance to predict from
818 #my $last_rec_date = $options->{last_rec_date}; # expected or actual
820 # TODO: add support for predicting serials with no chronology by passing in
821 # a last_pub_date option?
824 # Only needed for 'real' MFHD records, not our temp records
825 # my $link_id = $caption->link_id;
826 # if(!$predict_from) {
827 # my $htag = $caption->tag;
828 # $htag =~ s/^85/86/;
829 # my @holdings = $mfhd->holdings($htag, $link_id);
830 # my $last_holding = $holdings[-1];
832 # #if ($last_holding->is_compressed) {
833 # # $last_holding->compressed_to_last; # convert to last in range
835 # $predict_from = $last_holding;
839 $predict_from->notes('public', []);
840 # add a note marker for system use (?)
841 $predict_from->notes('private', ['AUTOGEN']);
845 my @predictions = $mfhd->generate_predictions({'base_holding' => $predict_from, 'num_to_predict' => $num_to_predict, 'end_date' => $end_date});
846 foreach my $prediction (@predictions) {
847 $pub_date = $_strp_date->parse_datetime($prediction->chron_to_date);
852 label => $prediction->format,
853 date_published => $pub_date,
854 #date_expected => $date_expected->strftime('%F'),
855 holding_code => [$prediction->indicator(1),$prediction->indicator(2),$prediction->subfields_list],
856 holding_type => $MFHD_NAMES_BY_TAG{$caption->tag},
857 caption_and_pattern => $scap_id
862 return @issuance_values;
865 sub _revive_caption {
868 my $pattern_code = $scap->pattern_code;
871 my $pattern_parts = OpenSRF::Utils::JSON->JSON2perl($pattern_code);
872 unshift(@$pattern_parts, $MFHD_TAGS_BY_NAME{$scap->type});
873 my $pattern_field = new MARC::Field(@$pattern_parts);
875 # build MFHD::Caption
876 return new MFHD::Caption($pattern_field);
879 sub _revive_holding {
880 my $holding_code = shift;
881 my $caption_field = shift;
885 my $holding_parts = OpenSRF::Utils::JSON->JSON2perl($holding_code);
886 my $captag = $caption_field->tag;
887 $captag =~ s/^85/86/;
888 unshift(@$holding_parts, $captag);
889 my $holding_field = new MARC::Field(@$holding_parts);
891 # build MFHD::Holding
892 return new MFHD::Holding($seqno, $holding_field, $caption_field);
895 __PACKAGE__->register_method(
896 method => 'unitize_items',
897 api_name => 'open-ils.serial.receive_items',
901 desc => 'Marks an item as received, updates the shelving unit (creating a new shelving unit if needed), and updates the summaries',
904 desc => 'array of serial items',
909 desc => 'hash of item_ids => barcodes',
914 desc => 'Returns number of received items (num_items) and new unit ID, if applicable (new_unit_id)',
920 __PACKAGE__->register_method(
921 method => 'unitize_items',
922 api_name => 'open-ils.serial.bind_items',
926 desc => 'Marks an item as bound, updates the shelving unit (creating a new shelving unit if needed)',
929 desc => 'array of serial items',
934 desc => 'hash of item_ids => barcodes',
939 desc => 'Returns number of bound items (num_items) and new unit ID, if applicable (new_unit_id)',
946 my ($self, $conn, $auth, $items, $barcodes) = @_;
948 my( $reqr, $evt ) = $U->checkses($auth);
950 my $editor = new_editor(requestor => $reqr, xact => 1);
951 $self->api_name =~ /serial\.(\w*)_items/;
955 my %found_stream_ids;
958 my %stream_ids_by_unit_id;
961 my %sdist_by_unit_id;
962 my %sdist_by_stream_id;
964 my $new_unit_id; # id for '-2' units to share
965 foreach my $item (@$items) {
966 # for debugging only, TODO: delete
967 if (!ref $item) { # hopefully we got an id instead
968 $item = $editor->retrieve_serial_item($item);
971 my $unit_id = ref($item->unit) ? $item->unit->id : $item->unit;
972 my $stream_id = ref($item->stream) ? $item->stream->id : $item->stream;
973 my $issuance_id = ref($item->issuance) ? $item->issuance->id : $item->issuance;
974 #TODO: evt on any missing ids
976 if ($mode eq 'receive') {
977 $item->date_received('now');
978 $item->status('Received');
980 $item->status('Bindery');
983 # check for types to trigger summary updates
985 if (!ref $item->issuance) {
986 my $scaps = $editor->search_serial_caption_and_pattern([{"+siss" => {"id" => $issuance_id}}, { "join" => {"siss" => {}} }]);
988 } elsif (!ref $item->issuance->caption_and_pattern) {
989 $scap = $editor->retrieve_serial_caption_and_pattern($item->issuance->caption_and_pattern);
991 $scap = $editor->issuance->caption_and_pattern;
993 if (!exists($found_types{$stream_id})) {
994 $found_types{$stream_id} = {};
996 $found_types{$stream_id}->{$scap->type} = 1;
998 # create unit if needed
999 if ($unit_id == -1 or (!$new_unit_id and $unit_id == -2)) { # create unit per item
1001 my $sdists = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
1002 $unit = _build_unit($editor, $sdists->[0], $mode, 0, $barcodes->{$item->id});
1003 # if _build_unit fails, $unit is an event, so return it
1004 if ($U->event_code($unit)) {
1006 $unit->{"note"} = "Item ID: " . $item->id;
1009 my $evt = _create_sunit($editor, $unit);
1010 return $evt if $evt;
1011 if ($unit_id == -2) {
1012 $new_unit_id = $unit->id;
1013 $unit_id = $new_unit_id;
1015 $unit_id = $unit->id;
1017 $item->unit($unit_id);
1019 # get unit with 'DEFAULT's and save unit and sdist for later use
1020 $unit = $editor->retrieve_serial_unit($unit->id);
1021 $unit_map{$unit_id} = $unit;
1022 $sdist_by_unit_id{$unit_id} = $sdists->[0];
1023 $sdist_by_stream_id{$stream_id} = $sdists->[0];
1024 } elsif ($unit_id == -2) { # create one unit for all '-2' items
1025 $unit_id = $new_unit_id;
1026 $item->unit($unit_id);
1029 $found_unit_ids{$unit_id} = 1;
1030 $found_stream_ids{$stream_id} = 1;
1032 # save the stream_id for this unit_id
1033 # TODO: prevent items from different streams in same unit? (perhaps in interface)
1034 $stream_ids_by_unit_id{$unit_id} = $stream_id;
1036 my $evt = _update_sitem($editor, undef, $item);
1037 return $evt if $evt;
1040 # deal with unit level labels
1041 foreach my $unit_id (keys %found_unit_ids) {
1043 # get all the needed issuances for unit
1044 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"unit" => $unit_id, "status" => ["Received", "Bindery"]}}, {"join" => {"sitem" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1045 #TODO: evt on search failure
1047 my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
1049 # special case for single formatted_part (may have summarized version)
1050 if (@$formatted_parts == 1) {
1051 #TODO: MFHD.pm should have a 'format_summary' method for this
1054 # retrieve and update unit contents
1058 # if we just created the unit, we will already have it and the distribution stored
1059 if (exists $unit_map{$unit_id}) {
1060 $sunit = $unit_map{$unit_id};
1061 $sdist = $sdist_by_unit_id{$unit_id};
1063 $sunit = $editor->retrieve_serial_unit($unit_id);
1064 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_ids_by_unit_id{$unit_id}}}, { "join" => {"sstr" => {}} }]);
1065 $sdist = $sdist->[0];
1068 $sunit->detailed_contents($sdist->unit_label_prefix . ' '
1069 . join(', ', @$formatted_parts) . ' '
1070 . $sdist->unit_label_suffix);
1072 $sunit->summary_contents($sunit->detailed_contents); #TODO: change this when real summary contents are available
1074 # create sort_key by left padding numbers to 6 digits
1075 my $sort_key = $sunit->detailed_contents;
1076 $sort_key =~ s/(\d+)/sprintf '%06d', $1/eg; # this may need improvement
1077 $sunit->sort_key($sort_key);
1079 if ($mode eq 'bind') {
1080 $sunit->status(2); # set to 'Bindery' status
1083 my $evt = _update_sunit($editor, undef, $sunit);
1084 return $evt if $evt;
1087 # cleanup 'dead' units (units which are now emptied of their items)
1088 my $dead_units = $editor->search_serial_unit([{'+sitem' => {'id' => undef}, 'deleted' => 'f'}, {'join' => {'sitem' => {'type' => 'left'}}}]);
1089 foreach my $unit (@$dead_units) {
1090 _delete_sunit($editor, undef, $unit);
1093 if ($mode eq 'receive') { # the summary holdings do not change when binding
1094 # deal with stream level summaries
1095 # summaries will be built from the "primary" stream only, that is, the stream with the lowest ID per distribution
1096 # (TODO: consider direct designation)
1097 my %primary_streams_by_sdist;
1098 my %streams_by_sdist;
1100 # see if we have primary streams, and if so, associate them with their distributions
1101 foreach my $stream_id (keys %found_stream_ids) {
1103 if (exists $sdist_by_stream_id{$stream_id}) {
1104 $sdist = $sdist_by_stream_id{$stream_id};
1106 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
1107 $sdist = $sdist->[0];
1110 if (!exists($streams_by_sdist{$sdist->id})) {
1111 $streams = $editor->search_serial_stream([{"distribution" => $sdist->id}, {"order_by" => {"sstr" => "id"}}]);
1112 $streams_by_sdist{$sdist->id} = $streams;
1114 $streams = $streams_by_sdist{$sdist->id};
1116 $primary_streams_by_sdist{$sdist->id} = $streams->[0] if ($stream_id == $streams->[0]->id);
1119 # retrieve and update summaries for each affected primary stream's distribution
1120 foreach my $sdist_id (keys %primary_streams_by_sdist) {
1121 my $stream = $primary_streams_by_sdist{$sdist_id};
1122 my $stream_id = $stream->id;
1123 # get all the needed issuances for stream
1124 # FIXME: search in Bindery/Bound/Not Published? as well as Received
1125 foreach my $type (keys %{$found_types{$stream_id}}) {
1126 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"stream" => $stream_id, "status" => "Received"}, "+scap" => {"type" => $type}}, {"join" => {"sitem" => {}, "scap" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1127 #TODO: evt on search failure
1129 my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
1131 # retrieve and update the generated_coverage of the summary
1132 my $search_method = "search_serial_${type}_summary";
1133 my $summary = $editor->$search_method([{"distribution" => $sdist_id}]);
1134 $summary = $summary->[0];
1135 $summary->generated_coverage(join(', ', @$formatted_parts));
1136 my $update_method = "update_serial_${type}_summary";
1137 return $editor->event unless $editor->$update_method($summary);
1143 return {'num_items' => scalar @$items, 'new_unit_id' => $new_unit_id};
1146 sub _find_or_create_call_number {
1147 my ($e, $lib, $cn_string, $record) = @_;
1149 my $existing = $e->search_asset_call_number({
1150 "owning_lib" => $lib,
1151 "label" => $cn_string,
1152 "record" => $record,
1154 }) or return $e->die_event;
1157 return $existing->[0]->id;
1159 return $e->die_event unless
1160 $e->allowed("CREATE_VOLUME", $lib);
1162 my $acn = new Fieldmapper::asset::call_number;
1164 $acn->creator($e->requestor->id);
1165 $acn->editor($e->requestor->id);
1166 $acn->record($record);
1167 $acn->label($cn_string);
1168 $acn->owning_lib($lib);
1170 $e->create_asset_call_number($acn) or return $e->die_event;
1171 return $e->data->id;
1175 sub _issuances_received {
1176 # XXX TODO: Add some caching or something. This is getting called
1177 # more often than it has to be.
1178 my ($e, $sitem) = @_;
1180 my $results = $e->json_query({
1181 "select" => {"sitem" => ["issuance"]},
1182 "from" => {"sitem" => {"sstr" => {}, "siss" => {}}},
1184 "+sstr" => {"distribution" => $sitem->stream->distribution->id},
1185 "+siss" => {"holding_type" => $sitem->issuance->holding_type},
1186 "+sitem" => {"date_received" => {"!=" => undef}}
1189 "siss" => {"date_published" => {"direction" => "asc"}}
1191 }) or return $e->die_event;
1193 my $uniq = +{map { $_->{"issuance"} => 1 } @$results};
1194 return [ map { $e->retrieve_serial_issuance($_) } keys %$uniq ];
1197 # XXX _prepare_unit_label() duplicates some code from unitize_items().
1198 # Hopefully we can unify code paths down the road.
1199 sub _prepare_unit_label {
1200 my ($e, $sunit, $sdist, $issuance) = @_;
1202 my ($mfhd, $formatted_parts) = _summarize_contents($e, [$issuance]);
1204 # special case for single formatted_part (may have summarized version)
1205 if (@$formatted_parts == 1) {
1206 #TODO: MFHD.pm should have a 'format_summary' method for this
1209 $sunit->detailed_contents(
1212 $sdist->unit_label_prefix,
1213 join(", ", @$formatted_parts),
1214 $sdist->unit_label_suffix
1218 # TODO: change this when real summary contents are available
1219 $sunit->summary_contents($sunit->detailed_contents);
1221 # Create sort_key by left padding numbers to 6 digits.
1222 (my $sort_key = $sunit->detailed_contents) =~
1223 s/(\d+)/sprintf '%06d', $1/eg;
1224 $sunit->sort_key($sort_key);
1227 # XXX duplicates a block of code from unitize_items(). Once I fully understand
1228 # what's going on and I'm sure it's working right, I'd like to have
1229 # unitize_items() just use this, keeping the logic in one place.
1230 sub _prepare_summaries {
1231 my ($e, $sitem, $issuances) = @_;
1233 my $dist_id = $sitem->stream->distribution->id;
1234 my $type = $sitem->issuance->holding_type;
1236 # Make sure @$issuances contains the new issuance from sitem.
1237 unless (grep { $_->id == $sitem->issuance->id } @$issuances) {
1238 push @$issuances, $sitem->issuance;
1241 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances);
1243 my $search_method = "search_serial_${type}_summary";
1244 my $summary = $e->$search_method([{"distribution" => $dist_id}]);
1246 my $cu_method = "update";
1249 $summary = $summary->[0];
1251 my $class = "Fieldmapper::serial::${type}_summary";
1252 $summary = $class->new;
1253 $summary->distribution($dist_id);
1254 $cu_method = "create";
1257 $summary->generated_coverage(join(", ", @$formatted_parts));
1258 my $method = "${cu_method}_serial_${type}_summary";
1259 return $e->die_event unless $e->$method($summary);
1262 sub _unit_by_iss_and_str {
1263 my ($e, $issuance, $stream) = @_;
1265 my $unit = $e->json_query({
1266 "select" => {"sunit" => ["id"]},
1267 "from" => {"sitem" => {"sunit" => {}}},
1270 "issuance" => $issuance->id,
1271 "stream" => $stream->id
1274 }) or return $e->die_event;
1275 return 0 if not @$unit;
1277 $e->retrieve_serial_unit($unit->[0]->{"id"}) or $e->die_event;
1280 sub move_previous_unit {
1281 my ($e, $prev_iss, $curr_item, $new_loc) = @_;
1283 my $prev_unit = _unit_by_iss_and_str($e,$prev_iss,$curr_item->stream);
1284 return $prev_unit if defined $U->event_code($prev_unit);
1285 return 0 if not $prev_unit;
1287 if ($prev_unit->location != $new_loc) {
1288 $prev_unit->location($new_loc);
1289 $e->update_serial_unit($prev_unit) or return $e->die_event;
1294 # _previous_issuance() assumes $existing is an ordered array
1295 sub _previous_issuance {
1296 my ($existing, $issuance) = @_;
1298 my $last = $existing->[-1];
1299 return undef unless $last;
1300 return ($last->id == $issuance->id ? $existing->[-2] : $last);
1303 __PACKAGE__->register_method(
1304 "method" => "receive_items_one_unit_per",
1305 "api_name" => "open-ils.serial.receive_items.one_unit_per",
1310 "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",
1314 "desc" => "authtoken",
1319 "desc" => "array of serial items, possibly fleshed with units and definitely fleshed with stream->distribution",
1324 "desc" => "id of bib record these items are associated with
1325 (XXX could/should be derived from items)",
1330 "desc" => "The item ID for each item successfully received",
1336 sub receive_items_one_unit_per {
1337 # XXX This function may be temporary, as it does some of what
1338 # unitize_items() does, just in a different way.
1339 my ($self, $client, $auth, $items, $record) = @_;
1341 my $e = new_editor("authtoken" => $auth, "xact" => 1);
1342 return $e->die_event unless $e->checkauth;
1343 return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
1345 my $prev_loc_setting_map = {};
1346 my $user_id = $e->requestor->id;
1348 # Get a list of all the non-virtual field names in a serial::unit for
1349 # merging given unit objects with template-built units later.
1350 # XXX move this somewhere global so it isn't re-run all the time
1351 my $all_unit_fields =
1352 $Fieldmapper::fieldmap->{"Fieldmapper::serial::unit"}->{"fields"};
1353 my @real_unit_fields = grep {
1354 not $all_unit_fields->{$_}->{"virtual"}
1355 } keys %$all_unit_fields;
1357 foreach my $item (@$items) {
1358 # Note that we expect a certain fleshing on the items we're getting.
1359 my $sdist = $item->stream->distribution;
1361 # Fetch a list of issuances with received copies already existing
1362 # on this distribution (and with the same holding type on the
1363 # issuance). This will be used in up to two places: once when building
1364 # a summary, once when changing the copy location of the previous
1366 my $issuances_received = _issuances_received($e, $item);
1367 if ($U->event_code($issuances_received)) {
1369 return $issuances_received;
1372 # Find out if we need to to deal with previous copy location changing.
1373 my $ou = $sdist->holding_lib->id;
1374 unless (exists $prev_loc_setting_map->{$ou}) {
1375 $prev_loc_setting_map->{$ou} = $U->ou_ancestor_setting_value(
1376 $ou, "serial.prev_issuance_copy_location", $e
1380 # If there is a previous copy location setting, we need the previous
1381 # issuance, from which we can in turn look up the item attached to the
1382 # same stream we're on now.
1383 if ($prev_loc_setting_map->{$ou}) {
1385 _previous_issuance($issuances_received, $item->issuance)) {
1387 # Now we can change the copy location of the previous unit,
1389 return $e->event if defined $U->event_code(
1391 $e, $prev_iss, $item, $prev_loc_setting_map->{$ou}
1397 # Create unit if given by user
1398 if (ref $item->unit) {
1399 # detach from the item, as we need to create separately
1400 my $user_unit = $item->unit;
1402 # get a unit based on associated template
1403 my $template_unit = _build_unit($e, $sdist, "receive", 1);
1404 if ($U->event_code($template_unit)) {
1406 $template_unit->{"note"} = "Item ID: " . $item->id;
1407 return $template_unit;
1410 # merge built unit with provided unit from user
1411 foreach (@real_unit_fields) {
1412 unless ($user_unit->$_) {
1413 $user_unit->$_($template_unit->$_);
1417 # Treat call number specially: the provided value from the
1418 # user will really be a string.
1419 if ($user_unit->call_number) {
1420 my $real_cn = _find_or_create_call_number(
1421 $e, $sdist->holding_lib->id,
1422 $user_unit->call_number, $record
1425 if ($U->event_code($real_cn)) {
1429 $user_unit->call_number($real_cn);
1433 my $evt = _prepare_unit_label(
1434 $e, $user_unit, $sdist, $item->issuance
1436 if ($U->event_code($evt)) {
1441 # create/update summary objects related to this distribution
1442 $evt = _prepare_summaries($e, $item, $issuances_received);
1443 if ($U->event_code($evt)) {
1448 # set the incontrovertibles on the unit
1449 $user_unit->edit_date("now");
1450 $user_unit->create_date("now");
1451 $user_unit->editor($user_id);
1452 $user_unit->creator($user_id);
1454 return $e->die_event unless $e->create_serial_unit($user_unit);
1456 # save reference to new unit
1457 $item->unit($e->data->id);
1460 # Create notes if given by user
1461 if (ref($item->notes) and @{$item->notes}) {
1462 foreach my $note (@{$item->notes}) {
1463 $note->creator($user_id);
1464 $note->create_date("now");
1466 return $e->die_event unless $e->create_serial_item_note($note);
1469 $item->clear_notes; # They're saved; we no longer want them here.
1472 # Set the incontrovertibles on the item
1473 $item->status("Received");
1474 $item->date_received("now");
1475 $item->edit_date("now");
1476 $item->editor($user_id);
1478 return $e->die_event unless $e->update_serial_item($item);
1480 # send client a response
1481 $client->respond($item->id);
1484 $e->commit or return $e->die_event;
1492 my $skip_call_number = shift;
1493 my $barcode = shift;
1495 my $attr = $mode . '_unit_template';
1496 my $template = $editor->retrieve_asset_copy_template($sdist->$attr) or
1497 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_COPY_TEMPLATE");
1499 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 );
1501 my $unit = new Fieldmapper::serial::unit;
1502 foreach my $part (@parts) {
1503 my $value = $template->$part;
1504 next if !defined($value);
1505 $unit->$part($value);
1508 # ignore circ_lib in template, set to distribution holding_lib
1509 $unit->circ_lib($sdist->holding_lib);
1510 $unit->creator($editor->requestor->id);
1511 $unit->editor($editor->requestor->id);
1513 unless ($skip_call_number) {
1514 $attr = $mode . '_call_number';
1515 my $cn = $sdist->$attr or
1516 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_CALL_NUMBER");
1518 $unit->call_number($cn);
1522 $unit->barcode($barcode);
1524 $unit->barcode('AUTO');
1526 $unit->sort_key('');
1527 $unit->summary_contents('');
1528 $unit->detailed_contents('');
1534 sub _summarize_contents {
1536 my $issuances = shift;
1538 # create MFHD record
1539 my $mfhd = MFHD->new(MARC::Record->new());
1542 my @scap_fields_ordered;
1545 foreach my $issuance (@$issuances) {
1546 my $scap_id = $issuance->caption_and_pattern;
1547 next if (!$scap_id); # skip issuances with no caption/pattern
1551 # if this is the first appearance of this scap, retrieve it and add it to the temporary record
1552 if (!exists $scaps{$issuance->caption_and_pattern}) {
1553 $scaps{$scap_id} = $editor->retrieve_serial_caption_and_pattern($scap_id);
1554 $scap = $scaps{$scap_id};
1555 $scap_field = _revive_caption($scap);
1556 $scap_fields{$scap_id} = $scap_field;
1557 push(@scap_fields_ordered, $scap_field);
1558 $scap_field->update('8' => $link_id);
1559 $mfhd->append_fields($scap_field);
1562 $scap = $scaps{$scap_id};
1563 $scap_field = $scap_fields{$scap_id};
1566 $mfhd->append_fields(_revive_holding($issuance->holding_code, $scap_field, $seqno));
1570 my @formatted_parts;
1571 foreach my $scap_field (@scap_fields_ordered) { #TODO: use generic MFHD "summarize" method, once available
1572 my @updated_holdings = $mfhd->get_compressed_holdings($scap_field);
1573 foreach my $holding (@updated_holdings) {
1574 push(@formatted_parts, $holding->format);
1578 return ($mfhd, \@formatted_parts);
1581 ##########################################################################
1584 __PACKAGE__->register_method(
1585 method => 'fetch_notes',
1586 api_name => 'open-ils.serial.item_note.retrieve.all',
1588 Returns an array of copy note objects.
1589 @param args A named hash of parameters including:
1590 authtoken : Required if viewing non-public notes
1591 item_id : The id of the item whose notes we want to retrieve
1592 pub : True if all the caller wants are public notes
1593 @return An array of note objects
1597 __PACKAGE__->register_method(
1598 method => 'fetch_notes',
1599 api_name => 'open-ils.serial.subscription_note.retrieve.all',
1601 Returns an array of copy note objects.
1602 @param args A named hash of parameters including:
1603 authtoken : Required if viewing non-public notes
1604 subscription_id : The id of the item whose notes we want to retrieve
1605 pub : True if all the caller wants are public notes
1606 @return An array of note objects
1610 __PACKAGE__->register_method(
1611 method => 'fetch_notes',
1612 api_name => 'open-ils.serial.distribution_note.retrieve.all',
1614 Returns an array of copy note objects.
1615 @param args A named hash of parameters including:
1616 authtoken : Required if viewing non-public notes
1617 distribution_id : The id of the item whose notes we want to retrieve
1618 pub : True if all the caller wants are public notes
1619 @return An array of note objects
1623 # TODO: revisit this method to consider replacing cstore direct calls
1625 my( $self, $connection, $args ) = @_;
1627 $self->api_name =~ /serial\.(\w*)_note/;
1630 my $id = $$args{object_id};
1631 my $authtoken = $$args{authtoken};
1635 return $U->cstorereq(
1636 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic',
1637 { $type => $id, pub => 't' } );
1639 # FIXME: restore perm check
1640 # ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
1641 # return $evt if $evt;
1642 return $U->cstorereq(
1643 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic', {$type => $id} );
1649 __PACKAGE__->register_method(
1650 method => 'create_note',
1651 api_name => 'open-ils.serial.item_note.create',
1653 Creates a new item note
1654 @param authtoken The login session key
1655 @param note The note object to create
1656 @return The id of the new note object
1660 __PACKAGE__->register_method(
1661 method => 'create_note',
1662 api_name => 'open-ils.serial.subscription_note.create',
1664 Creates a new subscription note
1665 @param authtoken The login session key
1666 @param note The note object to create
1667 @return The id of the new note object
1671 __PACKAGE__->register_method(
1672 method => 'create_note',
1673 api_name => 'open-ils.serial.distribution_note.create',
1675 Creates a new distribution note
1676 @param authtoken The login session key
1677 @param note The note object to create
1678 @return The id of the new note object
1683 my( $self, $connection, $authtoken, $note ) = @_;
1685 $self->api_name =~ /serial\.(\w*)_note/;
1688 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1689 return $e->event unless $e->checkauth;
1691 # FIXME: restore permission support
1692 # my $item = $e->retrieve_serial_item(
1698 # return $e->event unless
1699 # $e->allowed('CREATE_COPY_NOTE', $item->call_number->owning_lib);
1701 $note->create_date('now');
1702 $note->creator($e->requestor->id);
1703 $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
1706 my $method = "create_serial_${type}_note";
1707 $e->$method($note) or return $e->event;
1712 __PACKAGE__->register_method(
1713 method => 'delete_note',
1714 api_name => 'open-ils.serial.item_note.delete',
1716 Deletes an existing item note
1717 @param authtoken The login session key
1718 @param noteid The id of the note to delete
1719 @return 1 on success - Event otherwise.
1723 __PACKAGE__->register_method(
1724 method => 'delete_note',
1725 api_name => 'open-ils.serial.subscription_note.delete',
1727 Deletes an existing subscription note
1728 @param authtoken The login session key
1729 @param noteid The id of the note to delete
1730 @return 1 on success - Event otherwise.
1734 __PACKAGE__->register_method(
1735 method => 'delete_note',
1736 api_name => 'open-ils.serial.distribution_note.delete',
1738 Deletes an existing distribution note
1739 @param authtoken The login session key
1740 @param noteid The id of the note to delete
1741 @return 1 on success - Event otherwise.
1746 my( $self, $conn, $authtoken, $noteid ) = @_;
1748 $self->api_name =~ /serial\.(\w*)_note/;
1751 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1752 return $e->die_event unless $e->checkauth;
1754 my $method = "retrieve_serial_${type}_note";
1755 my $note = $e->$method([
1757 ]) or return $e->die_event;
1759 # FIXME: restore permissions check
1760 # if( $note->creator ne $e->requestor->id ) {
1761 # return $e->die_event unless
1762 # $e->allowed('DELETE_COPY_NOTE', $note->item->call_number->owning_lib);
1765 $method = "delete_serial_${type}_note";
1766 $e->$method($note) or return $e->die_event;
1772 ##########################################################################
1773 # subscription methods
1775 __PACKAGE__->register_method(
1776 method => 'fleshed_ssub_alter',
1777 api_name => 'open-ils.serial.subscription.fleshed.batch.update',
1781 desc => 'Receives an array of one or more subscriptions and updates the database as needed',
1783 name => 'authtoken',
1784 desc => 'Authtoken for current user session',
1788 name => 'subscriptions',
1789 desc => 'Array of fleshed subscriptions',
1795 desc => 'Returns 1 if successful, event if failed',
1801 sub fleshed_ssub_alter {
1802 my( $self, $conn, $auth, $ssubs ) = @_;
1803 return 1 unless ref $ssubs;
1804 my( $reqr, $evt ) = $U->checkses($auth);
1805 return $evt if $evt;
1806 my $editor = new_editor(requestor => $reqr, xact => 1);
1807 my $override = $self->api_name =~ /override/;
1809 # TODO: permission check
1810 # return $editor->event unless
1811 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
1813 for my $ssub (@$ssubs) {
1815 my $ssubid = $ssub->id;
1817 if( $ssub->isdeleted ) {
1818 $evt = _delete_ssub( $editor, $override, $ssub);
1819 } elsif( $ssub->isnew ) {
1820 _cleanse_dates($ssub, ['start_date','end_date']);
1821 $evt = _create_ssub( $editor, $ssub );
1823 _cleanse_dates($ssub, ['start_date','end_date']);
1824 $evt = _update_ssub( $editor, $override, $ssub );
1829 $logger->info("fleshed subscription-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
1833 $logger->debug("subscription-alter: done updating subscription batch");
1835 $logger->info("fleshed subscription-alter successfully updated ".scalar(@$ssubs)." subscriptions");
1840 my ($editor, $override, $ssub) = @_;
1841 $logger->info("subscription-alter: delete subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1842 my $sdists = $editor->search_serial_distribution(
1843 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1844 my $cps = $editor->search_serial_caption_and_pattern(
1845 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1846 my $sisses = $editor->search_serial_issuance(
1847 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1848 return OpenILS::Event->new(
1849 'SERIAL_SUBSCRIPTION_NOT_EMPTY', payload => $ssub->id ) if (@$sdists or @$cps or @$sisses);
1851 return $editor->event unless $editor->delete_serial_subscription($ssub);
1856 my ($editor, $ssub) = @_;
1858 $logger->info("subscription-alter: new subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1859 return $editor->event unless $editor->create_serial_subscription($ssub);
1864 my ($editor, $override, $ssub) = @_;
1866 $logger->info("subscription-alter: retrieving subscription ".$ssub->id);
1867 my $orig_ssub = $editor->retrieve_serial_subscription($ssub->id);
1869 $logger->info("subscription-alter: original subscription ".OpenSRF::Utils::JSON->perl2JSON($orig_ssub));
1870 $logger->info("subscription-alter: updated subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1871 return $editor->event unless $editor->update_serial_subscription($ssub);
1875 __PACKAGE__->register_method(
1876 method => "fleshed_serial_subscription_retrieve_batch",
1878 api_name => "open-ils.serial.subscription.fleshed.batch.retrieve"
1881 sub fleshed_serial_subscription_retrieve_batch {
1882 my( $self, $client, $ids ) = @_;
1883 # FIXME: permissions?
1884 $logger->info("Fetching fleshed subscriptions @$ids");
1885 return $U->cstorereq(
1886 "open-ils.cstore.direct.serial.subscription.search.atomic",
1889 flesh_fields => {ssub => [ qw/owning_lib notes/ ]}
1893 __PACKAGE__->register_method(
1894 method => "retrieve_sub_tree",
1896 api_name => "open-ils.serial.subscription_tree.retrieve"
1899 __PACKAGE__->register_method(
1900 method => "retrieve_sub_tree",
1901 api_name => "open-ils.serial.subscription_tree.global.retrieve"
1904 sub retrieve_sub_tree {
1906 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
1908 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
1912 # TODO: permission support
1913 if(!@org_ids and $user_session) {
1915 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
1916 @org_ids = ($user_obj->home_ou);
1919 if( $self->api_name =~ /global/ ) {
1920 return _build_subs_list( { record_entry => $docid } ); # TODO: filter for !deleted, or active?
1925 for my $orgid (@org_ids) {
1926 my $subs = _build_subs_list(
1927 { record_entry => $docid, owning_lib => $orgid } );# TODO: filter for !deleted, or active?
1928 push( @all_subs, @$subs );
1937 sub _build_subs_list {
1938 my $search_hash = shift;
1940 #$search_hash->{deleted} = 'f';
1941 my $e = new_editor();
1943 my $subs = $e->search_serial_subscription([$search_hash, { 'order_by' => {'ssub' => 'id'} }]);
1947 for my $sub (@$subs) {
1949 # TODO: filter on !deleted?
1950 my $dists = $e->search_serial_distribution(
1951 [{ subscription => $sub->id }, { 'order_by' => {'sdist' => 'label'} }]
1954 #$dists = [ sort { $a->label cmp $b->label } @$dists ];
1956 $sub->distributions($dists);
1958 # TODO: filter on !deleted?
1959 my $issuances = $e->search_serial_issuance(
1960 [{ subscription => $sub->id }, { 'order_by' => {'siss' => 'label'} }]
1963 #$issuances = [ sort { $a->label cmp $b->label } @$issuances ];
1964 $sub->issuances($issuances);
1966 # TODO: filter on !deleted?
1967 my $scaps = $e->search_serial_caption_and_pattern(
1968 [{ subscription => $sub->id }, { 'order_by' => {'scap' => 'id'} }]
1971 #$scaps = [ sort { $a->id cmp $b->id } @$scaps ];
1972 $sub->scaps($scaps);
1973 push( @built_subs, $sub );
1976 return \@built_subs;
1980 __PACKAGE__->register_method(
1981 method => "subscription_orgs_for_title",
1983 api_name => "open-ils.serial.subscription.retrieve_orgs_by_title"
1986 sub subscription_orgs_for_title {
1987 my( $self, $client, $record_id ) = @_;
1989 my $subs = $U->simple_scalar_request(
1991 "open-ils.cstore.direct.serial.subscription.search.atomic",
1992 { record_entry => $record_id }); # TODO: filter on !deleted?
1994 my $orgs = { map {$_->owning_lib => 1 } @$subs };
1995 return [ keys %$orgs ];
1999 ##########################################################################
2000 # distribution methods
2002 __PACKAGE__->register_method(
2003 method => 'fleshed_sdist_alter',
2004 api_name => 'open-ils.serial.distribution.fleshed.batch.update',
2008 desc => 'Receives an array of one or more distributions and updates the database as needed',
2010 name => 'authtoken',
2011 desc => 'Authtoken for current user session',
2015 name => 'distributions',
2016 desc => 'Array of fleshed distributions',
2022 desc => 'Returns 1 if successful, event if failed',
2028 sub fleshed_sdist_alter {
2029 my( $self, $conn, $auth, $sdists ) = @_;
2030 return 1 unless ref $sdists;
2031 my( $reqr, $evt ) = $U->checkses($auth);
2032 return $evt if $evt;
2033 my $editor = new_editor(requestor => $reqr, xact => 1);
2034 my $override = $self->api_name =~ /override/;
2036 # TODO: permission check
2037 # return $editor->event unless
2038 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2040 for my $sdist (@$sdists) {
2041 my $sdistid = $sdist->id;
2043 if( $sdist->isdeleted ) {
2044 $evt = _delete_sdist( $editor, $override, $sdist);
2045 } elsif( $sdist->isnew ) {
2046 $evt = _create_sdist( $editor, $sdist );
2048 $evt = _update_sdist( $editor, $override, $sdist );
2053 $logger->info("fleshed distribution-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2057 $logger->debug("distribution-alter: done updating distribution batch");
2059 $logger->info("fleshed distribution-alter successfully updated ".scalar(@$sdists)." distributions");
2064 my ($editor, $override, $sdist) = @_;
2065 $logger->info("distribution-alter: delete distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2066 return $editor->event unless $editor->delete_serial_distribution($sdist);
2071 my ($editor, $sdist) = @_;
2073 $logger->info("distribution-alter: new distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2074 return $editor->event unless $editor->create_serial_distribution($sdist);
2076 # create summaries too
2077 my $summary = new Fieldmapper::serial::basic_summary;
2078 $summary->distribution($sdist->id);
2079 $summary->generated_coverage('');
2080 return $editor->event unless $editor->create_serial_basic_summary($summary);
2081 $summary = new Fieldmapper::serial::supplement_summary;
2082 $summary->distribution($sdist->id);
2083 $summary->generated_coverage('');
2084 return $editor->event unless $editor->create_serial_supplement_summary($summary);
2085 $summary = new Fieldmapper::serial::index_summary;
2086 $summary->distribution($sdist->id);
2087 $summary->generated_coverage('');
2088 return $editor->event unless $editor->create_serial_index_summary($summary);
2090 # create a starter stream (TODO: reconsider this)
2091 my $stream = new Fieldmapper::serial::stream;
2092 $stream->distribution($sdist->id);
2093 return $editor->event unless $editor->create_serial_stream($stream);
2099 my ($editor, $override, $sdist) = @_;
2101 $logger->info("distribution-alter: retrieving distribution ".$sdist->id);
2102 my $orig_sdist = $editor->retrieve_serial_distribution($sdist->id);
2104 $logger->info("distribution-alter: original distribution ".OpenSRF::Utils::JSON->perl2JSON($orig_sdist));
2105 $logger->info("distribution-alter: updated distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2106 return $editor->event unless $editor->update_serial_distribution($sdist);
2110 __PACKAGE__->register_method(
2111 method => "fleshed_serial_distribution_retrieve_batch",
2113 api_name => "open-ils.serial.distribution.fleshed.batch.retrieve"
2116 sub fleshed_serial_distribution_retrieve_batch {
2117 my( $self, $client, $ids ) = @_;
2118 # FIXME: permissions?
2119 $logger->info("Fetching fleshed distributions @$ids");
2120 return $U->cstorereq(
2121 "open-ils.cstore.direct.serial.distribution.search.atomic",
2124 flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams / ]}
2128 __PACKAGE__->register_method(
2129 method => "retrieve_dist_tree",
2131 api_name => "open-ils.serial.distribution_tree.retrieve"
2134 __PACKAGE__->register_method(
2135 method => "retrieve_dist_tree",
2136 api_name => "open-ils.serial.distribution_tree.global.retrieve"
2139 sub retrieve_dist_tree {
2140 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2142 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2146 # TODO: permission support
2147 if(!@org_ids and $user_session) {
2149 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2150 @org_ids = ($user_obj->home_ou);
2153 my $e = new_editor();
2155 if( $self->api_name =~ /global/ ) {
2156 return $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }},
2158 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 / ]},
2159 order_by => {'sdist' => 'id'},
2160 'join' => {'ssub' => {}}
2162 ]); # TODO: filter for !deleted?
2166 for my $orgid (@org_ids) {
2167 my $dists = $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }, holding_lib => $orgid},
2169 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 / ]},
2170 order_by => {'sdist' => 'id'},
2171 'join' => {'ssub' => {}}
2173 ]); # TODO: filter for !deleted?
2174 push( @all_dists, @$dists ) if $dists;
2184 __PACKAGE__->register_method(
2185 method => "distribution_orgs_for_title",
2187 api_name => "open-ils.serial.distribution.retrieve_orgs_by_title"
2190 sub distribution_orgs_for_title {
2191 my( $self, $client, $record_id ) = @_;
2193 my $dists = $U->cstorereq(
2194 "open-ils.cstore.direct.serial.distribution.search.atomic",
2195 { '+ssub' => { record_entry => $record_id } },
2196 { 'join' => {'ssub' => {}} }); # TODO: filter on !deleted?
2198 my $orgs = { map {$_->holding_lib => 1 } @$dists };
2199 return [ keys %$orgs ];
2203 ##########################################################################
2204 # caption and pattern methods
2206 __PACKAGE__->register_method(
2207 method => 'scap_alter',
2208 api_name => 'open-ils.serial.caption_and_pattern.batch.update',
2212 desc => 'Receives an array of one or more caption and patterns and updates the database as needed',
2214 name => 'authtoken',
2215 desc => 'Authtoken for current user session',
2220 desc => 'Array of caption and patterns',
2226 desc => 'Returns 1 if successful, event if failed',
2233 my( $self, $conn, $auth, $scaps ) = @_;
2234 return 1 unless ref $scaps;
2235 my( $reqr, $evt ) = $U->checkses($auth);
2236 return $evt if $evt;
2237 my $editor = new_editor(requestor => $reqr, xact => 1);
2238 my $override = $self->api_name =~ /override/;
2240 # TODO: permission check
2241 # return $editor->event unless
2242 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2244 for my $scap (@$scaps) {
2245 my $scapid = $scap->id;
2247 if( $scap->isdeleted ) {
2248 $evt = _delete_scap( $editor, $override, $scap);
2249 } elsif( $scap->isnew ) {
2250 $evt = _create_scap( $editor, $scap );
2252 $evt = _update_scap( $editor, $override, $scap );
2257 $logger->info("caption_and_pattern-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2261 $logger->debug("caption_and_pattern-alter: done updating caption_and_pattern batch");
2263 $logger->info("caption_and_pattern-alter successfully updated ".scalar(@$scaps)." caption_and_patterns");
2268 my ($editor, $override, $scap) = @_;
2269 $logger->info("caption_and_pattern-alter: delete caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2270 my $sisses = $editor->search_serial_issuance(
2271 { caption_and_pattern => $scap->id }, { limit => 1 } ); #TODO: 'deleted' support?
2272 return OpenILS::Event->new(
2273 'SERIAL_CAPTION_AND_PATTERN_HAS_ISSUANCES', payload => $scap->id ) if (@$sisses);
2275 return $editor->event unless $editor->delete_serial_caption_and_pattern($scap);
2280 my ($editor, $scap) = @_;
2282 $logger->info("caption_and_pattern-alter: new caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2283 return $editor->event unless $editor->create_serial_caption_and_pattern($scap);
2288 my ($editor, $override, $scap) = @_;
2290 $logger->info("caption_and_pattern-alter: retrieving caption_and_pattern ".$scap->id);
2291 my $orig_scap = $editor->retrieve_serial_caption_and_pattern($scap->id);
2293 $logger->info("caption_and_pattern-alter: original caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($orig_scap));
2294 $logger->info("caption_and_pattern-alter: updated caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2295 return $editor->event unless $editor->update_serial_caption_and_pattern($scap);
2299 __PACKAGE__->register_method(
2300 method => "serial_caption_and_pattern_retrieve_batch",
2302 api_name => "open-ils.serial.caption_and_pattern.batch.retrieve"
2305 sub serial_caption_and_pattern_retrieve_batch {
2306 my( $self, $client, $ids ) = @_;
2307 $logger->info("Fetching caption_and_patterns @$ids");
2308 return $U->cstorereq(
2309 "open-ils.cstore.direct.serial.caption_and_pattern.search.atomic",
2314 ##########################################################################
2317 __PACKAGE__->register_method(
2318 method => 'sstr_alter',
2319 api_name => 'open-ils.serial.stream.batch.update',
2323 desc => 'Receives an array of one or more streams and updates the database as needed',
2325 name => 'authtoken',
2326 desc => 'Authtoken for current user session',
2331 desc => 'Array of streams',
2337 desc => 'Returns 1 if successful, event if failed',
2344 my( $self, $conn, $auth, $sstrs ) = @_;
2345 return 1 unless ref $sstrs;
2346 my( $reqr, $evt ) = $U->checkses($auth);
2347 return $evt if $evt;
2348 my $editor = new_editor(requestor => $reqr, xact => 1);
2349 my $override = $self->api_name =~ /override/;
2351 # TODO: permission check
2352 # return $editor->event unless
2353 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2355 for my $sstr (@$sstrs) {
2356 my $sstrid = $sstr->id;
2358 if( $sstr->isdeleted ) {
2359 $evt = _delete_sstr( $editor, $override, $sstr);
2360 } elsif( $sstr->isnew ) {
2361 $evt = _create_sstr( $editor, $sstr );
2363 $evt = _update_sstr( $editor, $override, $sstr );
2368 $logger->info("stream-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2372 $logger->debug("stream-alter: done updating stream batch");
2374 $logger->info("stream-alter successfully updated ".scalar(@$sstrs)." streams");
2379 my ($editor, $override, $sstr) = @_;
2380 $logger->info("stream-alter: delete stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2381 my $sitems = $editor->search_serial_item(
2382 { stream => $sstr->id }, { limit => 1 } ); #TODO: 'deleted' support?
2383 return OpenILS::Event->new(
2384 'SERIAL_STREAM_HAS_ITEMS', payload => $sstr->id ) if (@$sitems);
2386 return $editor->event unless $editor->delete_serial_stream($sstr);
2391 my ($editor, $sstr) = @_;
2393 $logger->info("stream-alter: new stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2394 return $editor->event unless $editor->create_serial_stream($sstr);
2399 my ($editor, $override, $sstr) = @_;
2401 $logger->info("stream-alter: retrieving stream ".$sstr->id);
2402 my $orig_sstr = $editor->retrieve_serial_stream($sstr->id);
2404 $logger->info("stream-alter: original stream ".OpenSRF::Utils::JSON->perl2JSON($orig_sstr));
2405 $logger->info("stream-alter: updated stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2406 return $editor->event unless $editor->update_serial_stream($sstr);
2410 __PACKAGE__->register_method(
2411 method => "serial_stream_retrieve_batch",
2413 api_name => "open-ils.serial.stream.batch.retrieve"
2416 sub serial_stream_retrieve_batch {
2417 my( $self, $client, $ids ) = @_;
2418 $logger->info("Fetching streams @$ids");
2419 return $U->cstorereq(
2420 "open-ils.cstore.direct.serial.stream.search.atomic",
2426 ##########################################################################
2429 __PACKAGE__->register_method(
2430 method => 'sum_alter',
2431 api_name => 'open-ils.serial.basic_summary.batch.update',
2435 desc => 'Receives an array of one or more summaries and updates the database as needed',
2437 name => 'authtoken',
2438 desc => 'Authtoken for current user session',
2443 desc => 'Array of basic summaries',
2449 desc => 'Returns 1 if successful, event if failed',
2455 __PACKAGE__->register_method(
2456 method => 'sum_alter',
2457 api_name => 'open-ils.serial.supplement_summary.batch.update',
2461 desc => 'Receives an array of one or more summaries and updates the database as needed',
2463 name => 'authtoken',
2464 desc => 'Authtoken for current user session',
2469 desc => 'Array of supplement summaries',
2475 desc => 'Returns 1 if successful, event if failed',
2481 __PACKAGE__->register_method(
2482 method => 'sum_alter',
2483 api_name => 'open-ils.serial.index_summary.batch.update',
2487 desc => 'Receives an array of one or more summaries and updates the database as needed',
2489 name => 'authtoken',
2490 desc => 'Authtoken for current user session',
2495 desc => 'Array of index summaries',
2501 desc => 'Returns 1 if successful, event if failed',
2508 my( $self, $conn, $auth, $sums ) = @_;
2509 return 1 unless ref $sums;
2511 $self->api_name =~ /serial\.(\w*)_summary/;
2514 my( $reqr, $evt ) = $U->checkses($auth);
2515 return $evt if $evt;
2516 my $editor = new_editor(requestor => $reqr, xact => 1);
2517 my $override = $self->api_name =~ /override/;
2519 # TODO: permission check
2520 # return $editor->event unless
2521 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2523 for my $sum (@$sums) {
2524 my $sumid = $sum->id;
2526 # XXX: (for now, at least) summaries should be created/deleted by the distribution functions
2527 if( $sum->isdeleted ) {
2528 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2529 } elsif( $sum->isnew ) {
2530 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2532 $evt = _update_sum( $editor, $override, $sum, $type );
2537 $logger->info("${type}_summary-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2541 $logger->debug("${type}_summary-alter: done updating ${type}_summary batch");
2543 $logger->info("${type}_summary-alter successfully updated ".scalar(@$sums)." ${type}_summaries");
2548 my ($editor, $override, $sum, $type) = @_;
2550 $logger->info("${type}_summary-alter: retrieving ${type}_summary ".$sum->id);
2551 my $retrieve_method = "retrieve_serial_${type}_summary";
2552 my $orig_sum = $editor->$retrieve_method($sum->id);
2554 $logger->info("${type}_summary-alter: original ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($orig_sum));
2555 $logger->info("${type}_summary-alter: updated ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($sum));
2556 my $update_method = "update_serial_${type}_summary";
2557 return $editor->event unless $editor->$update_method($sum);
2561 __PACKAGE__->register_method(
2562 method => "serial_summary_retrieve_batch",
2564 api_name => "open-ils.serial.basic_summary.batch.retrieve"
2567 __PACKAGE__->register_method(
2568 method => "serial_summary_retrieve_batch",
2570 api_name => "open-ils.serial.supplement_summary.batch.retrieve"
2573 __PACKAGE__->register_method(
2574 method => "serial_summary_retrieve_batch",
2576 api_name => "open-ils.serial.index_summary.batch.retrieve"
2579 sub serial_summary_retrieve_batch {
2580 my( $self, $client, $ids ) = @_;
2582 $self->api_name =~ /serial\.(\w*)_summary/;
2585 $logger->info("Fetching ${type}_summaries @$ids");
2586 return $U->cstorereq(
2587 "open-ils.cstore.direct.serial.".$type."_summary.search.atomic",
2593 ##########################################################################
2596 __PACKAGE__->register_method(
2597 "method" => "bre_by_identifier",
2598 "api_name" => "open-ils.serial.biblio.record_entry.by_identifier",
2601 "desc" => "Find instances of biblio.record_entry given a search token" .
2602 " that could be a value for any identifier defined in " .
2603 "config.metabib_field",
2605 {"desc" => "Search token", "type" => "string"},
2606 {"desc" => "Options: require_subscriptions, add_mvr, is_actual_id" .
2607 " (all boolean)", "type" => "object"}
2610 "desc" => "Any matching BREs, or if the add_mvr option is true, " .
2611 "objects with a 'bre' key/value pair, and an 'mvr' " .
2612 "key-value pair. BREs have subscriptions fleshed on.",
2618 sub bre_by_identifier {
2619 my ($self, $client, $term, $options) = @_;
2621 return new OpenILS::Event("BAD_PARAMS") unless $term;
2624 my $e = new_editor();
2628 if ($options->{"is_actual_id"}) {
2632 $e->search_config_metabib_field({"field_class" => "identifier"})
2633 or return $e->die_event;
2635 my @identifiers = map { $_->name } @$cmf;
2636 my $query = join(" || ", map { "id|$_: $term" } @identifiers);
2638 my $search = create OpenSRF::AppSession("open-ils.search");
2639 my $search_result = $search->request(
2640 "open-ils.search.biblio.multiclass.query.staff", {}, $query
2642 $search->disconnect;
2644 # Un-nest results. They tend to look like [[1],[2],[3]] for some reason.
2645 @ids = map { @{$_} } @{$search_result->{"ids"}};
2653 my $bre = $e->search_biblio_record_entry([
2655 "flesh" => 2, "flesh_fields" => {
2656 "bre" => ["subscriptions"],
2657 "ssub" => ["owning_lib"]
2660 ]) or return $e->die_event;
2662 if (@$bre && $options->{"require_subscriptions"}) {
2663 $bre = [ grep { @{$_->subscriptions} } @$bre ];
2668 if (@$bre) { # re-evaluate after possible grep
2669 if ($options->{"add_mvr"}) {
2671 {"bre" => $_, "mvr" => _get_mvr($_->id)}
2674 $client->respond($_) foreach (@$bre);
2681 __PACKAGE__->register_method(
2682 "method" => "get_receivable_items",
2683 "api_name" => "open-ils.serial.items.receivable.by_subscription",
2686 "desc" => "Return all receivable items under a given subscription",
2688 {"desc" => "Authtoken", "type" => "string"},
2689 {"desc" => "Subscription ID", "type" => "number"},
2692 "desc" => "All receivable items under a given subscription",
2698 __PACKAGE__->register_method(
2699 "method" => "get_receivable_items",
2700 "api_name" => "open-ils.serial.items.receivable.by_issuance",
2703 "desc" => "Return all receivable items under a given issuance",
2705 {"desc" => "Authtoken", "type" => "string"},
2706 {"desc" => "Issuance ID", "type" => "number"},
2709 "desc" => "All receivable items under a given issuance",
2715 sub get_receivable_items {
2716 my ($self, $client, $auth, $term) = @_;
2718 my $e = new_editor("authtoken" => $auth);
2719 return $e->die_event unless $e->checkauth;
2723 my $by = ($self->api_name =~ /by_(\w+)$/)[0];
2726 "issuance" => {"issuance" => $term},
2727 "subscription" => {"+siss" => {"subscription" => $term}}
2730 my $item_ids = $e->json_query(
2732 "select" => {"sitem" => ["id"]},
2733 "from" => {"sitem" => "siss"},
2735 %{$where{$by}}, "date_received" => undef
2737 "order_by" => {"sitem" => ["id"]}
2739 ) or return $e->die_event;
2741 return undef unless @$item_ids;
2743 foreach (map { $_->{"id"} } @$item_ids) {
2745 $e->retrieve_serial_item([
2749 "sitem" => ["stream", "issuance"],
2750 "sstr" => ["distribution"],
2751 "sdist" => ["holding_lib"]
2762 __PACKAGE__->register_method(
2763 "method" => "get_receivable_issuances",
2764 "api_name" => "open-ils.serial.issuances.receivable",
2767 "desc" => "Return all issuances with receivable items given " .
2768 "a subscription ID",
2770 {"desc" => "Authtoken", "type" => "string"},
2771 {"desc" => "Subscription ID", "type" => "number"},
2774 "desc" => "All issuances with receivable items " .
2775 "(but not the items themselves)", "type" => "object"
2780 sub get_receivable_issuances {
2781 my ($self, $client, $auth, $sub_id) = @_;
2783 my $e = new_editor("authtoken" => $auth);
2784 return $e->die_event unless $e->checkauth;
2788 my $issuance_ids = $e->json_query({
2791 {"transform" => "distinct", "column" => "id"},
2795 "from" => {"siss" => "sitem"},
2797 "subscription" => $sub_id,
2798 "+sitem" => {"date_received" => undef}
2801 "siss" => {"date_published" => {"direction" => "asc"}}
2804 }) or return $e->die_event;
2806 $client->respond($e->retrieve_serial_issuance($_->{"id"}))
2807 foreach (@$issuance_ids);
2814 __PACKAGE__->register_method(
2815 "method" => "get_routing_list_users",
2816 "api_name" => "open-ils.serial.routing_list_users.fleshed_and_ordered",
2819 "desc" => "Return all routing list users with reader fleshed " .
2820 "(with card and home_ou) for a given stream ID, sorted by pos",
2822 {"desc" => "Authtoken", "type" => "string"},
2823 {"desc" => "Stream ID (int or array of ints)", "type" => "mixed"},
2826 "desc" => "Stream of routing list users", "type" => "object",
2832 sub get_routing_list_users {
2833 my ($self, $client, $auth, $stream_id) = @_;
2835 my $e = new_editor("authtoken" => $auth);
2836 return $e->die_event unless $e->checkauth;
2838 my $users = $e->search_serial_routing_list_user([
2839 {"stream" => $stream_id}, {
2840 "order_by" => {"srlu" => "pos"},
2843 "srlu" => [qw/reader stream/],
2844 "au" => [qw/card home_ou/],
2845 "sstr" => ["distribution"]
2848 ]) or return $e->die_event;
2850 return undef unless @$users;
2852 # The ADMIN_SERIAL_STREAM permission is used simply to avoid the
2853 # need for any new permission. The context OU will be the same
2854 # for every result of the above query, so we need only check once.
2855 return $e->die_event unless $e->allowed(
2856 "ADMIN_SERIAL_STREAM", $users->[0]->stream->distribution->holding_lib
2861 my @users = map { $_->stream($_->stream->id); $_ } @$users;
2862 @users = sort { $a->stream cmp $b->stream } @users if
2863 ref $stream_id eq "ARRAY";
2865 $client->respond($_) for @users;
2871 __PACKAGE__->register_method(
2872 "method" => "replace_routing_list_users",
2873 "api_name" => "open-ils.serial.routing_list_users.replace",
2875 "desc" => "Replace all routing list users on the specified streams " .
2876 "with those in the list argument",
2878 {"desc" => "Authtoken", "type" => "string"},
2879 {"desc" => "List of srlu objects", "type" => "array"},
2882 "desc" => "event on failure, undef on success"
2887 sub replace_routing_list_users {
2888 my ($self, $client, $auth, $users) = @_;
2890 return undef unless ref $users eq "ARRAY";
2892 if (grep { ref $_ ne "Fieldmapper::serial::routing_list_user" } @$users) {
2893 return new OpenILS::Event("BAD_PARAMS", "note" => "Only srlu objects");
2896 my $e = new_editor("authtoken" => $auth, "xact" => 1);
2897 return $e->die_event unless $e->checkauth;
2899 my %streams_ok = ();
2902 foreach my $user (@$users) {
2903 unless (exists $streams_ok{$user->stream}) {
2904 my $stream = $e->retrieve_serial_stream([
2907 "flesh_fields" => {"sstr" => ["distribution"]}
2909 ]) or return $e->die_event;
2911 "ADMIN_SERIAL_STREAM", $stream->distribution->holding_lib
2912 ) or return $e->die_event;
2914 my $to_delete = $e->search_serial_routing_list_user(
2915 {"stream" => $user->stream}
2916 ) or return $e->die_event;
2919 "Deleting srlu: [" .
2920 join(", ", map { $_->id; } @$to_delete) .
2924 foreach (@$to_delete) {
2925 $e->delete_serial_routing_list_user($_) or
2926 return $e->die_event;
2929 $streams_ok{$user->stream} = 1;
2932 next if $user->isdeleted;
2936 $e->create_serial_routing_list_user($user) or return $e->die_event;
2939 $e->commit or return $e->die_event;
2943 __PACKAGE__->register_method(
2944 "method" => "get_records_with_marc_85x",
2945 "api_name"=>"open-ils.serial.caption_and_pattern.find_legacy_by_bib_record",
2948 "desc" => "Return the specified BRE itself and/or any related SRE ".
2949 "whenever they have 853-855 tags",
2951 {"desc" => "Authtoken", "type" => "string"},
2952 {"desc" => "bib record ID", "type" => "number"},
2955 "desc" => "objects, either bre or sre", "type" => "object"
2960 sub get_records_with_marc_85x { # specifically, 853-855
2961 my ($self, $client, $auth, $bre_id) = @_;
2963 my $e = new_editor("authtoken" => $auth);
2964 return $e->die_event unless $e->checkauth;
2966 my $bre = $e->search_biblio_record_entry([
2967 {"id" => $bre_id, "deleted" => "f"}, {
2969 "flesh_fields" => {"bre" => [qw/creator editor owner/]}
2971 ]) or return $e->die_event;
2973 return undef unless @$bre;
2976 my $record = MARC::Record->new_from_xml($bre->marc);
2977 $client->respond($bre) if $record->field("85[3-5]");
2978 # XXX Is passing a regex to ->field() an abuse of MARC::Record ?
2980 my $sres = $e->search_serial_record_entry([
2981 {"record" => $bre_id, "deleted" => "f"}, {
2983 "flesh_fields" => {"sre" => [qw/creator editor owning_lib/]}
2985 ]) or return $e->die_event;
2989 foreach my $sre (@$sres) {
2990 $client->respond($sre) if
2991 MARC::Record->new_from_xml($sre->marc)->field("85[3-5]");
2997 __PACKAGE__->register_method(
2998 "method" => "create_scaps_from_marcxml",
2999 "api_name" => "open-ils.serial.caption_and_pattern.create_from_records",
3002 "desc" => "Create caption and pattern objects from 853-855 tags " .
3003 "in MARCXML documents",
3005 {"desc" => "Authtoken", "type" => "string"},
3006 {"desc" => "Subscription ID", "type" => "number"},
3007 {"desc" => "list of MARCXML documents as strings",
3011 "desc" => "Newly created caption and pattern objects",
3012 "type" => "object", "class" => "scap"
3017 sub create_scaps_from_marcxml {
3018 my ($self, $client, $auth, $sub_id, $docs) = @_;
3020 return undef unless ref $docs eq "ARRAY";
3022 my $e = new_editor("authtoken" => $auth, "xact" => 1);
3023 return $e->die_event unless $e->checkauth;
3025 # Retrieve the subscription just for perm checking (whether we can create
3026 # scaps at the owning lib).
3027 my $sub = $e->retrieve_serial_subscription($sub_id) or return $e->die_event;
3028 return $e->die_event unless
3029 $e->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $sub->owning_lib);
3031 foreach my $record (map { MARC::Record->new_from_xml($_) } @$docs) {
3032 foreach my $field ($record->field("85[3-5]")) {
3033 my $scap = new Fieldmapper::serial::caption_and_pattern;
3034 $scap->subscription($sub_id);
3035 $scap->type($MFHD_NAMES_BY_TAG{$field->tag});
3036 $scap->pattern_code(
3037 OpenSRF::Utils::JSON->perl2JSON(
3038 [ $field->indicator(1), $field->indicator(2),
3039 map { @$_ } $field->subfields ] # flattens nested array
3042 $e->create_serial_caption_and_pattern($scap) or
3043 return $e->die_event;
3044 $client->respond($e->data);
3048 $e->commit or return $e->die_event;