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 => 'fleshed_item_alter',
91 api_name => 'open-ils.serial.item.fleshed.batch.update',
95 desc => 'Receives an array of one or more items and updates the database as needed',
98 desc => 'Authtoken for current user session',
103 desc => 'Array of fleshed items',
109 desc => 'Returns 1 if successful, event if failed',
115 sub fleshed_item_alter {
116 my( $self, $conn, $auth, $items ) = @_;
117 return 1 unless ref $items;
118 my( $reqr, $evt ) = $U->checkses($auth);
120 my $editor = new_editor(requestor => $reqr, xact => 1);
121 my $override = $self->api_name =~ /override/;
123 # TODO: permission check
124 # return $editor->event unless
125 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
127 for my $item (@$items) {
129 my $itemid = $item->id;
130 $item->editor($editor->requestor->id);
131 $item->edit_date('now');
133 if( $item->isdeleted ) {
134 $evt = _delete_sitem( $editor, $override, $item);
135 } elsif( $item->isnew ) {
136 # TODO: reconsider this
137 # if the item has a new issuance, create the issuance first
138 if (ref $item->issuance eq 'Fieldmapper::serial::issuance' and $item->issuance->isnew) {
139 fleshed_issuance_alter($self, $conn, $auth, [$item->issuance]);
141 _cleanse_dates($item, ['date_expected','date_received']);
142 $evt = _create_sitem( $editor, $item );
144 _cleanse_dates($item, ['date_expected','date_received']);
145 $evt = _update_sitem( $editor, $override, $item );
150 $logger->info("fleshed item-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
154 $logger->debug("item-alter: done updating item batch");
156 $logger->info("fleshed item-alter successfully updated ".scalar(@$items)." items");
161 my ($editor, $override, $item) = @_;
162 $logger->info("item-alter: delete item ".OpenSRF::Utils::JSON->perl2JSON($item));
163 return $editor->event unless $editor->delete_serial_item($item);
168 my ($editor, $item) = @_;
170 $item->creator($editor->requestor->id);
171 $item->create_date('now');
173 $logger->info("item-alter: new item ".OpenSRF::Utils::JSON->perl2JSON($item));
174 return $editor->event unless $editor->create_serial_item($item);
179 my ($editor, $override, $item) = @_;
181 $logger->info("item-alter: retrieving item ".$item->id);
182 my $orig_item = $editor->retrieve_serial_item($item->id);
184 $logger->info("item-alter: original item ".OpenSRF::Utils::JSON->perl2JSON($orig_item));
185 $logger->info("item-alter: updated item ".OpenSRF::Utils::JSON->perl2JSON($item));
186 return $editor->event unless $editor->update_serial_item($item);
190 __PACKAGE__->register_method(
191 method => "fleshed_serial_item_retrieve_batch",
193 api_name => "open-ils.serial.item.fleshed.batch.retrieve"
196 sub fleshed_serial_item_retrieve_batch {
197 my( $self, $client, $ids ) = @_;
198 # FIXME: permissions?
199 $logger->info("Fetching fleshed serial items @$ids");
200 return $U->cstorereq(
201 "open-ils.cstore.direct.serial.item.search.atomic",
204 flesh_fields => {sitem => [ qw/issuance creator editor stream unit notes/ ], sstr => ["distribution"], sunit => ["call_number"], siss => [qw/creator editor subscription/]}
209 ##########################################################################
212 __PACKAGE__->register_method(
213 method => 'fleshed_issuance_alter',
214 api_name => 'open-ils.serial.issuance.fleshed.batch.update',
218 desc => 'Receives an array of one or more issuances and updates the database as needed',
221 desc => 'Authtoken for current user session',
226 desc => 'Array of fleshed issuances',
232 desc => 'Returns 1 if successful, event if failed',
238 sub fleshed_issuance_alter {
239 my( $self, $conn, $auth, $issuances ) = @_;
240 return 1 unless ref $issuances;
241 my( $reqr, $evt ) = $U->checkses($auth);
243 my $editor = new_editor(requestor => $reqr, xact => 1);
244 my $override = $self->api_name =~ /override/;
246 # TODO: permission support
247 # return $editor->event unless
248 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
250 for my $issuance (@$issuances) {
251 my $issuanceid = $issuance->id;
252 $issuance->editor($editor->requestor->id);
253 $issuance->edit_date('now');
255 if( $issuance->isdeleted ) {
256 $evt = _delete_siss( $editor, $override, $issuance);
257 } elsif( $issuance->isnew ) {
258 _cleanse_dates($issuance, ['date_published']);
259 $evt = _create_siss( $editor, $issuance );
261 _cleanse_dates($issuance, ['date_published']);
262 $evt = _update_siss( $editor, $override, $issuance );
267 $logger->info("fleshed issuance-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
271 $logger->debug("issuance-alter: done updating issuance batch");
273 $logger->info("fleshed issuance-alter successfully updated ".scalar(@$issuances)." issuances");
278 my ($editor, $override, $issuance) = @_;
279 $logger->info("issuance-alter: delete issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
280 return $editor->event unless $editor->delete_serial_issuance($issuance);
285 my ($editor, $issuance) = @_;
287 $issuance->creator($editor->requestor->id);
288 $issuance->create_date('now');
290 $logger->info("issuance-alter: new issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
291 return $editor->event unless $editor->create_serial_issuance($issuance);
296 my ($editor, $override, $issuance) = @_;
298 $logger->info("issuance-alter: retrieving issuance ".$issuance->id);
299 my $orig_issuance = $editor->retrieve_serial_issuance($issuance->id);
301 $logger->info("issuance-alter: original issuance ".OpenSRF::Utils::JSON->perl2JSON($orig_issuance));
302 $logger->info("issuance-alter: updated issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
303 return $editor->event unless $editor->update_serial_issuance($issuance);
307 __PACKAGE__->register_method(
308 method => "fleshed_serial_issuance_retrieve_batch",
310 api_name => "open-ils.serial.issuance.fleshed.batch.retrieve"
313 sub fleshed_serial_issuance_retrieve_batch {
314 my( $self, $client, $ids ) = @_;
315 # FIXME: permissions?
316 $logger->info("Fetching fleshed serial issuances @$ids");
317 return $U->cstorereq(
318 "open-ils.cstore.direct.serial.issuance.search.atomic",
321 flesh_fields => {siss => [ qw/creator editor subscription/ ]}
325 __PACKAGE__->register_method(
326 method => "pub_fleshed_serial_issuance_retrieve_batch",
327 api_name => "open-ils.serial.issuance.pub_fleshed.batch.retrieve",
330 Public (i.e. OPAC) call for getting at the sub and
331 ultimately the record entry from an issuance
333 params => [{name => 'ids', desc => 'Array of IDs', type => 'array'}],
336 issuance objects, fleshed with subscriptions
342 sub pub_fleshed_serial_issuance_retrieve_batch {
343 my( $self, $client, $ids ) = @_;
344 return [] unless $ids and @$ids;
345 return new_editor()->search_serial_issuance([
349 flesh_fields => {siss => [ qw/subscription/ ]}
354 sub received_siss_by_bib {
359 my $args = shift || {};
360 $$args{order} ||= 'asc';
362 my $global = $$args{global} == 0 ? 0 : 1;
364 my $e = new_editor();
365 my $issuances = $e->json_query({
368 $global ? { transform => "min", column => "id", aggregate => 1 } : "id",
373 # We're not really interested in the minimum here. This is
374 # just a way to distinguish issuances whose items have units
375 # from issuances whose items have no units, without altogether
376 # excluding the latter type of issuances.
377 {"transform" => "min", "alias" => "has_units",
378 "column" => "unit", "aggregate" => 1}
384 field => 'subscription',
390 $$args{ou} ? ( join => {
397 fkey => 'distribution'
408 '+ssub' => { record_entry => $bib },
409 $$args{type} ? ( '+siss' => { 'holding_type' => $$args{type} } ) : (),
411 # XXX should we also take specific item statuses into account?
412 date_received => { '!=' => undef },
413 $$args{status} ? ( 'status' => $$args{status} ) : ()
415 $$args{ou} ? ( '+sdist' => {
417 'in' => $U->get_org_descendants($$args{ou}, $$args{depth})
421 $$args{limit} ? ( limit => $$args{limit} ) : (),
422 $$args{offset} ? ( offset => $$args{offset} ) : (),
423 order_by => [{ class => 'siss', field => 'date_published', direction => $$args{order} }],
428 "issuance" => $e->retrieve_serial_issuance($_->{"id"}),
429 "has_units" => $_->{"has_units"} ? 1 : 0
434 __PACKAGE__->register_method(
435 method => 'received_siss_by_bib',
436 api_name => 'open-ils.serial.received_siss.retrieve.by_bib',
441 desc => 'Receives a Bib ID and other optional params and returns "siss" (issuance) objects',
444 desc => 'id of the bre to which the issuances belong',
449 q/A hash of optional arguments. Valid keys and their meanings:
450 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).
451 order := date_published sort direction, either "asc" (chronological, default) or "desc" (reverse chronological)
452 limit := Number of issuances to return. Useful for paging results, or finding the oldest or newest
453 offset := Number of issuance to skip before returning results. Useful for paging.
454 orgid := OU id used to scope retrieval, based on distribution.holding_lib
455 depth := OU depth used to range the scope of orgid
456 type := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
457 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).
465 sub scoped_bib_holdings_summary {
469 my $args = shift || {};
471 $args->{order} = 'asc';
473 my ($issuances) = $self->method_lookup('open-ils.serial.received_siss.retrieve.by_bib.atomic')->run( $bibid => $args );
475 # split into issuance type sets
476 my %type_blob = (basic => [], supplement => [], index => []);
477 push @{ $type_blob{ $_->{"issuance"}->holding_type } }, $_->{"issuance"}
480 # generate a statement list for each type
482 for my $type ( keys %type_blob ) {
483 my ($mfhd,$list) = _summarize_contents(new_editor(), $type_blob{$type});
484 $statement_blob{$type} = $list;
487 return \%statement_blob;
489 __PACKAGE__->register_method(
490 method => 'scoped_bib_holdings_summary',
491 api_name => 'open-ils.serial.bib.summary_statements',
495 desc => 'Receives a Bib ID and other optional params and returns set of holdings statements',
498 desc => 'id of the bre to which the issuances belong',
503 q/A hash of optional arguments. Valid keys and their meanings:
504 orgid := OU id used to scope retrieval, based on distribution.holding_lib
505 depth := OU depth used to range the scope of orgid
506 type := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
507 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).
515 ##########################################################################
518 __PACKAGE__->register_method(
519 method => 'fleshed_sunit_alter',
520 api_name => 'open-ils.serial.sunit.fleshed.batch.update',
524 desc => 'Receives an array of one or more Units and updates the database as needed',
527 desc => 'Authtoken for current user session',
532 desc => 'Array of fleshed Units',
538 desc => 'Returns 1 if successful, event if failed',
544 sub fleshed_sunit_alter {
545 my( $self, $conn, $auth, $sunits ) = @_;
546 return 1 unless ref $sunits;
547 my( $reqr, $evt ) = $U->checkses($auth);
549 my $editor = new_editor(requestor => $reqr, xact => 1);
550 my $override = $self->api_name =~ /override/;
552 # TODO: permission support
553 # return $editor->event unless
554 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
556 for my $sunit (@$sunits) {
557 if( $sunit->isdeleted ) {
558 $evt = _delete_sunit( $editor, $override, $sunit );
560 $sunit->default_location( $sunit->default_location->id ) if ref $sunit->default_location;
562 if( $sunit->isnew ) {
563 $evt = _create_sunit( $editor, $sunit );
565 $evt = _update_sunit( $editor, $override, $sunit );
571 $logger->info("fleshed sunit-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
575 $logger->debug("sunit-alter: done updating sunit batch");
577 $logger->info("fleshed sunit-alter successfully updated ".scalar(@$sunits)." Units");
582 my ($editor, $override, $sunit) = @_;
583 $logger->info("sunit-alter: delete sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
584 return $editor->event unless $editor->delete_serial_unit($sunit);
589 my ($editor, $sunit) = @_;
591 $logger->info("sunit-alter: new Unit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
592 return $editor->event unless $editor->create_serial_unit($sunit);
597 my ($editor, $override, $sunit) = @_;
599 $logger->info("sunit-alter: retrieving sunit ".$sunit->id);
600 my $orig_sunit = $editor->retrieve_serial_unit($sunit->id);
602 $logger->info("sunit-alter: original sunit ".OpenSRF::Utils::JSON->perl2JSON($orig_sunit));
603 $logger->info("sunit-alter: updated sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
604 return $editor->event unless $editor->update_serial_unit($sunit);
608 __PACKAGE__->register_method(
609 method => "retrieve_unit_list",
611 api_name => "open-ils.serial.unit_list.retrieve"
614 sub retrieve_unit_list {
616 my( $self, $client, @sdist_ids ) = @_;
618 if(ref($sdist_ids[0])) { @sdist_ids = @{$sdist_ids[0]}; }
620 my $e = new_editor();
624 { 'sunit' => [ 'id', 'summary_contents', 'sort_key' ],
625 'sitem' => ['stream'],
626 'sstr' => ['distribution'],
627 'sdist' => [{'column' => 'label', 'alias' => 'sdist_label'}]
634 { 'join' => { 'sunit' => {} } }
639 'distinct' => 'true',
640 'where' => { '+sdist' => {'id' => \@sdist_ids} },
641 'order_by' => [{'class' => 'sunit', 'field' => 'sort_key'}]
644 my $unit_list_entries = $e->json_query($query);
647 foreach my $entry (@$unit_list_entries) {
648 my $value = {'sunit' => $entry->{id}, 'sstr' => $entry->{stream}, 'sdist' => $entry->{distribution}};
649 my $label = $entry->{summary_contents};
650 if (length($label) > 100) {
651 $label = substr($label, 0, 100) . '...'; # limited space in dropdown / menu
653 $label = "[$entry->{sdist_label}/$entry->{stream} #$entry->{id}] " . $label;
654 push (@entries, [$label, OpenSRF::Utils::JSON->perl2JSON($value)]);
662 ##########################################################################
663 # predict and receive methods
665 __PACKAGE__->register_method(
666 method => 'make_predictions',
667 api_name => 'open-ils.serial.make_predictions',
671 desc => 'Receives an ssub id and populates the issuance and item tables',
674 desc => 'Serial Subscription ID',
681 sub make_predictions {
682 my ($self, $conn, $authtoken, $args) = @_;
684 my $editor = OpenILS::Utils::CStoreEditor->new();
685 my $ssub_id = $args->{ssub_id};
686 my $mfhd = MFHD->new(MARC::Record->new());
688 my $ssub = $editor->retrieve_serial_subscription([$ssub_id]);
689 my $scaps = $editor->search_serial_caption_and_pattern({ subscription => $ssub_id, active => 't'});
690 my $sdists = $editor->search_serial_distribution( [{ subscription => $ssub->id }, { flesh => 1, flesh_fields => {sdist => [ qw/ streams / ]} }] ); #TODO: 'deleted' support?
692 my $total_streams = 0;
694 $total_streams += scalar(@{$_->streams});
696 if ($total_streams < 1) {
698 # XXX TODO new event type
699 return new OpenILS::Event(
700 "BAD_PARAMS", note =>
701 "There are no streams to direct items. Can't predict."
707 # XXX TODO new event type
708 return new OpenILS::Event(
709 "BAD_PARAMS", note =>
710 "There are no active caption-and-pattern objects associated " .
711 "with this subscription. Can't predict."
717 foreach my $scap (@$scaps) {
718 my $caption_field = _revive_caption($scap);
719 $caption_field->update('8' => $link_id);
720 my $using_fake_chron = 0;
721 # if we have no chronology, add one for prediction puposes
722 if (!$caption_field->subfield('i') and !$caption_field->enumeration_is_chronology) {
723 $using_fake_chron = 1;
725 $mfhd->append_fields($caption_field);
727 'caption' => $caption_field,
728 'scap_id' => $scap->id,
729 'num_to_predict' => $args->{num_to_predict},
730 'end_date' => defined $args->{end_date} ?
731 $_strp_date->parse_datetime($args->{end_date}) : undef
733 if ($args->{base_issuance}) { # predict from a given issuance
734 $options->{predict_from} = _revive_holding($args->{base_issuance}->holding_code, $caption_field, 1); # fresh MFHD Record, so we simply default to 1 for seqno
735 $options->{faked_chron_date} = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($args->{base_issuance}->date_published)) if $using_fake_chron;
736 } else { # default to predicting from last published
737 my $last_published = $editor->search_serial_issuance([
738 {'caption_and_pattern' => $scap->id,
739 'subscription' => $ssub_id},
740 {limit => 1, order_by => { siss => "date_published DESC" }}]
742 if ($last_published->[0]) {
743 my $last_siss = $last_published->[0];
744 unless ($last_siss->holding_code) {
746 # XXX TODO new event type
747 return new OpenILS::Event(
748 "BAD_PARAMS", note =>
749 "Last issuance has no holding code. Can't predict."
752 $options->{predict_from} = _revive_holding($last_siss->holding_code, $caption_field, 1);
753 $options->{faked_chron_date} = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($last_siss->date_published)) if $using_fake_chron;
756 # XXX TODO make a new event type instead of hijacking this one
757 return new OpenILS::Event(
758 "BAD_PARAMS", note => "No issuance from which to predict!"
762 push( @predictions, _generate_issuance_values($mfhd, $options) );
767 foreach my $prediction (@predictions) {
768 my $issuance = new Fieldmapper::serial::issuance;
770 $issuance->label($prediction->{label});
771 $issuance->date_published($prediction->{date_published}->strftime('%F'));
772 $issuance->holding_code(OpenSRF::Utils::JSON->perl2JSON($prediction->{holding_code}));
773 $issuance->holding_type($prediction->{holding_type});
774 $issuance->caption_and_pattern($prediction->{caption_and_pattern});
775 $issuance->subscription($ssub->id);
776 push (@issuances, $issuance);
779 fleshed_issuance_alter($self, $conn, $authtoken, \@issuances); # FIXME: catch events
782 for (my $i = 0; $i < @issuances; $i++) {
783 my $date_expected = $predictions[$i]->{date_published}->add(seconds => interval_to_seconds($ssub->expected_date_offset))->strftime('%F');
784 my $issuance = $issuances[$i];
785 #$issuance->label(interval_to_seconds($ssub->expected_date_offset));
786 foreach my $sdist (@$sdists) {
787 my $streams = $sdist->streams;
788 foreach my $stream (@$streams) {
789 my $item = new Fieldmapper::serial::item;
791 $item->stream($stream->id);
792 $item->date_expected($date_expected);
793 $item->issuance($issuance->id);
794 push (@items, $item);
798 fleshed_item_alter($self, $conn, $authtoken, \@items); # FIXME: catch events
803 # _generate_issuance_values() is an initial attempt at a function which can be used
804 # to populate an issuance table with a list of predicted issues. It accepts
805 # a hash ref of options initially defined as:
806 # caption : the caption field to predict on
807 # num_to_predict : the number of issues you wish to predict
808 # last_rec_date : the date of the last received issue, to be used as an offset
809 # for predicting future issues
810 # 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
812 # The basic method is to first convert to a single holding if compressed, then
813 # increment the holding and save the resulting values to @issuances.
815 # returns @issuance_values, an array of hashrefs containing (formatted
816 # label, formatted chronology date, formatted estimated arrival date, and an
817 # array ref of holding subfields as (key, value, key, value ...)) (not a hash
818 # to protect order and possible duplicate keys), and a holding type.
820 sub _generate_issuance_values {
821 my ($mfhd, $options) = @_;
822 my $caption = $options->{caption};
823 my $scap_id = $options->{scap_id};
824 my $num_to_predict = $options->{num_to_predict};
825 my $end_date = $options->{end_date};
826 my $predict_from = $options->{predict_from}; # issuance to predict from
827 my $faked_chron_date = $options->{faked_chron_date}; # serial does not have a chronology caption, so add one (temporarily) based on this date
828 #my $last_rec_date = $options->{last_rec_date}; # expected or actual
831 # Only needed for 'real' MFHD records, not our temp records
832 # my $link_id = $caption->link_id;
833 # if(!$predict_from) {
834 # my $htag = $caption->tag;
835 # $htag =~ s/^85/86/;
836 # my @holdings = $mfhd->holdings($htag, $link_id);
837 # my $last_holding = $holdings[-1];
839 # #if ($last_holding->is_compressed) {
840 # # $last_holding->compressed_to_last; # convert to last in range
842 # $predict_from = $last_holding;
846 $predict_from->notes('public', []);
847 # add a note marker for system use (?)
848 $predict_from->notes('private', ['AUTOGEN']);
850 # our basic method for dealing with 'faked' chronologies will be to add it in, do the predicting, then take it back out
853 if ($faked_chron_date) {
854 $orig_caption = $predict_from->caption;
855 # because of the way MFHD::Caption and Holding work, it is simplest
856 # to recreate rather than try to update
857 $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)'));
858 $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);
861 my @predictions = $mfhd->generate_predictions({'base_holding' => $predict_from, 'num_to_predict' => $num_to_predict, 'end_date' => $end_date});
865 foreach my $prediction (@predictions) {
866 $pub_date = $_strp_date->parse_datetime($prediction->chron_to_date);
867 if ($faked_chron_date) { # get rid of the chronology portions and restore original caption
868 $prediction->delete_subfield(code => ['i', 'j', 'k']);
869 $prediction = new MFHD::Holding($prediction->seqno, new MARC::Field($prediction->tag, $prediction->indicator(1), $prediction->indicator(2), $prediction->subfields_list), $orig_caption);
875 label => $prediction->format,
876 date_published => $pub_date,
877 #date_expected => $date_expected->strftime('%F'),
878 holding_code => [$prediction->indicator(1),$prediction->indicator(2),$prediction->subfields_list],
879 holding_type => $MFHD_NAMES_BY_TAG{$caption->tag},
880 caption_and_pattern => $scap_id
885 return @issuance_values;
888 sub _revive_caption {
891 my $pattern_code = $scap->pattern_code;
894 my $pattern_parts = OpenSRF::Utils::JSON->JSON2perl($pattern_code);
895 unshift(@$pattern_parts, $MFHD_TAGS_BY_NAME{$scap->type});
896 my $pattern_field = new MARC::Field(@$pattern_parts);
898 # build MFHD::Caption
899 return new MFHD::Caption($pattern_field);
902 sub _revive_holding {
903 my $holding_code = shift;
904 my $caption_field = shift;
908 my $holding_parts = OpenSRF::Utils::JSON->JSON2perl($holding_code);
909 my $captag = $caption_field->tag;
910 $captag =~ s/^85/86/;
911 unshift(@$holding_parts, $captag);
912 my $holding_field = new MARC::Field(@$holding_parts);
914 # build MFHD::Holding
915 return new MFHD::Holding($seqno, $holding_field, $caption_field);
918 __PACKAGE__->register_method(
919 method => 'unitize_items',
920 api_name => 'open-ils.serial.receive_items',
924 desc => 'Marks an item as received, updates the shelving unit (creating a new shelving unit if needed), and updates the summaries',
927 desc => 'array of serial items',
932 desc => 'hash of item_ids => barcodes',
937 desc => 'Returns number of received items (num_items) and new unit ID, if applicable (new_unit_id)',
943 __PACKAGE__->register_method(
944 method => 'unitize_items',
945 api_name => 'open-ils.serial.bind_items',
949 desc => 'Marks an item as bound, updates the shelving unit (creating a new shelving unit if needed)',
952 desc => 'array of serial items',
957 desc => 'hash of item_ids => barcodes',
962 desc => 'Returns number of bound items (num_items) and new unit ID, if applicable (new_unit_id)',
969 my ($self, $conn, $auth, $items, $barcodes) = @_;
971 my( $reqr, $evt ) = $U->checkses($auth);
973 my $editor = new_editor(requestor => $reqr, xact => 1);
974 $self->api_name =~ /serial\.(\w*)_items/;
978 my %found_stream_ids;
981 my %stream_ids_by_unit_id;
984 my %sdist_by_unit_id;
985 my %sdist_by_stream_id;
987 my $new_unit_id; # id for '-2' units to share
988 foreach my $item (@$items) {
989 # for debugging only, TODO: delete
990 if (!ref $item) { # hopefully we got an id instead
991 $item = $editor->retrieve_serial_item($item);
994 my $unit_id = ref($item->unit) ? $item->unit->id : $item->unit;
995 my $stream_id = ref($item->stream) ? $item->stream->id : $item->stream;
996 my $issuance_id = ref($item->issuance) ? $item->issuance->id : $item->issuance;
997 #TODO: evt on any missing ids
999 if ($mode eq 'receive') {
1000 $item->date_received('now');
1001 $item->status('Received');
1004 # check for types to trigger summary updates
1006 if (!ref $item->issuance) {
1007 my $scaps = $editor->search_serial_caption_and_pattern([{"+siss" => {"id" => $issuance_id}}, { "join" => {"siss" => {}} }]);
1008 $scap = $scaps->[0];
1009 } elsif (!ref $item->issuance->caption_and_pattern) {
1010 $scap = $editor->retrieve_serial_caption_and_pattern($item->issuance->caption_and_pattern);
1012 $scap = $editor->issuance->caption_and_pattern;
1014 if (!exists($found_types{$stream_id})) {
1015 $found_types{$stream_id} = {};
1017 $found_types{$stream_id}->{$scap->type} = 1;
1019 # create unit if needed
1020 if ($unit_id == -1 or (!$new_unit_id and $unit_id == -2)) { # create unit per item
1022 my $sdists = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
1023 $unit = _build_unit($editor, $sdists->[0], $mode, 0, $barcodes->{$item->id});
1024 # if _build_unit fails, $unit is an event, so return it
1025 if ($U->event_code($unit)) {
1027 $unit->{"note"} = "Item ID: " . $item->id;
1030 my $evt = _create_sunit($editor, $unit);
1031 return $evt if $evt;
1032 if ($unit_id == -2) {
1033 $new_unit_id = $unit->id;
1034 $unit_id = $new_unit_id;
1036 $unit_id = $unit->id;
1038 $item->unit($unit_id);
1040 # get unit with 'DEFAULT's and save unit and sdist for later use
1041 $unit = $editor->retrieve_serial_unit($unit->id);
1042 $unit_map{$unit_id} = $unit;
1043 $sdist_by_unit_id{$unit_id} = $sdists->[0];
1044 $sdist_by_stream_id{$stream_id} = $sdists->[0];
1045 } elsif ($unit_id == -2) { # create one unit for all '-2' items
1046 $unit_id = $new_unit_id;
1047 $item->unit($unit_id);
1050 $found_unit_ids{$unit_id} = 1;
1051 $found_stream_ids{$stream_id} = 1;
1053 # save the stream_id for this unit_id
1054 # TODO: prevent items from different streams in same unit? (perhaps in interface)
1055 $stream_ids_by_unit_id{$unit_id} = $stream_id;
1057 my $evt = _update_sitem($editor, undef, $item);
1058 return $evt if $evt;
1061 # deal with unit level labels
1062 foreach my $unit_id (keys %found_unit_ids) {
1064 # get all the needed issuances for unit
1065 # TODO remove 'Bindery' from this search (leaving it in for now for backwards compatibility with any current test environment data)
1066 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"unit" => $unit_id, "status" => ["Received", "Bindery"]}}, {"join" => {"sitem" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1067 #TODO: evt on search failure
1069 my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
1071 # special case for single formatted_part (may have summarized version)
1072 if (@$formatted_parts == 1) {
1073 #TODO: MFHD.pm should have a 'format_summary' method for this
1076 # retrieve and update unit contents
1080 # if we just created the unit, we will already have it and the distribution stored
1081 if (exists $unit_map{$unit_id}) {
1082 $sunit = $unit_map{$unit_id};
1083 $sdist = $sdist_by_unit_id{$unit_id};
1085 $sunit = $editor->retrieve_serial_unit($unit_id);
1086 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_ids_by_unit_id{$unit_id}}}, { "join" => {"sstr" => {}} }]);
1087 $sdist = $sdist->[0];
1090 $sunit->detailed_contents($sdist->unit_label_prefix . ' '
1091 . join(', ', @$formatted_parts) . ' '
1092 . $sdist->unit_label_suffix);
1094 $sunit->summary_contents($sunit->detailed_contents); #TODO: change this when real summary contents are available
1096 # create sort_key by left padding numbers to 6 digits
1097 my $sort_key = $sunit->detailed_contents;
1098 $sort_key =~ s/(\d+)/sprintf '%06d', $1/eg; # this may need improvement
1099 $sunit->sort_key($sort_key);
1101 my $evt = _update_sunit($editor, undef, $sunit);
1102 return $evt if $evt;
1105 # cleanup 'dead' units (units which are now emptied of their items)
1106 my $dead_units = $editor->search_serial_unit([{'+sitem' => {'id' => undef}, 'deleted' => 'f'}, {'join' => {'sitem' => {'type' => 'left'}}}]);
1107 foreach my $unit (@$dead_units) {
1108 _delete_sunit($editor, undef, $unit);
1111 if ($mode eq 'receive') { # the summary holdings do not change when binding
1112 # deal with stream level summaries
1113 # summaries will be built from the "primary" stream only, that is, the stream with the lowest ID per distribution
1114 # (TODO: consider direct designation)
1115 my %primary_streams_by_sdist;
1116 my %streams_by_sdist;
1118 # see if we have primary streams, and if so, associate them with their distributions
1119 foreach my $stream_id (keys %found_stream_ids) {
1121 if (exists $sdist_by_stream_id{$stream_id}) {
1122 $sdist = $sdist_by_stream_id{$stream_id};
1124 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
1125 $sdist = $sdist->[0];
1128 if (!exists($streams_by_sdist{$sdist->id})) {
1129 $streams = $editor->search_serial_stream([{"distribution" => $sdist->id}, {"order_by" => {"sstr" => "id"}}]);
1130 $streams_by_sdist{$sdist->id} = $streams;
1132 $streams = $streams_by_sdist{$sdist->id};
1134 $primary_streams_by_sdist{$sdist->id} = $streams->[0] if ($stream_id == $streams->[0]->id);
1137 # retrieve and update summaries for each affected primary stream's distribution
1138 foreach my $sdist_id (keys %primary_streams_by_sdist) {
1139 my $stream = $primary_streams_by_sdist{$sdist_id};
1140 my $stream_id = $stream->id;
1141 # get all the needed issuances for stream
1142 # FIXME: search in Bindery/Bound/Not Published? as well as Received
1143 foreach my $type (keys %{$found_types{$stream_id}}) {
1144 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"stream" => $stream_id, "status" => "Received"}, "+scap" => {"type" => $type}}, {"join" => {"sitem" => {}, "scap" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1145 #TODO: evt on search failure
1147 my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
1149 # retrieve and update the generated_coverage of the summary
1150 my $search_method = "search_serial_${type}_summary";
1151 my $summary = $editor->$search_method([{"distribution" => $sdist_id}]);
1152 $summary = $summary->[0];
1153 $summary->generated_coverage(join(', ', @$formatted_parts));
1154 my $update_method = "update_serial_${type}_summary";
1155 return $editor->event unless $editor->$update_method($summary);
1161 return {'num_items' => scalar @$items, 'new_unit_id' => $new_unit_id};
1164 sub _find_or_create_call_number {
1165 my ($e, $lib, $cn_string, $record) = @_;
1167 my $existing = $e->search_asset_call_number({
1168 "owning_lib" => $lib,
1169 "label" => $cn_string,
1170 "record" => $record,
1172 }) or return $e->die_event;
1175 return $existing->[0]->id;
1177 return $e->die_event unless
1178 $e->allowed("CREATE_VOLUME", $lib);
1180 my $acn = new Fieldmapper::asset::call_number;
1182 $acn->creator($e->requestor->id);
1183 $acn->editor($e->requestor->id);
1184 $acn->record($record);
1185 $acn->label($cn_string);
1186 $acn->owning_lib($lib);
1188 $e->create_asset_call_number($acn) or return $e->die_event;
1189 return $e->data->id;
1193 sub _issuances_received {
1194 # XXX TODO: Add some caching or something. This is getting called
1195 # more often than it has to be.
1196 my ($e, $sitem) = @_;
1198 my $results = $e->json_query({
1199 "select" => {"sitem" => ["issuance"]},
1200 "from" => {"sitem" => {"sstr" => {}, "siss" => {}}},
1202 "+sstr" => {"distribution" => $sitem->stream->distribution->id},
1203 "+siss" => {"holding_type" => $sitem->issuance->holding_type},
1204 "+sitem" => {"date_received" => {"!=" => undef}}
1207 "siss" => {"date_published" => {"direction" => "asc"}}
1209 }) or return $e->die_event;
1211 my $uniq = +{map { $_->{"issuance"} => 1 } @$results};
1212 return [ map { $e->retrieve_serial_issuance($_) } keys %$uniq ];
1215 # XXX _prepare_unit_label() duplicates some code from unitize_items().
1216 # Hopefully we can unify code paths down the road.
1217 sub _prepare_unit_label {
1218 my ($e, $sunit, $sdist, $issuance) = @_;
1220 my ($mfhd, $formatted_parts) = _summarize_contents($e, [$issuance]);
1222 # special case for single formatted_part (may have summarized version)
1223 if (@$formatted_parts == 1) {
1224 #TODO: MFHD.pm should have a 'format_summary' method for this
1227 $sunit->detailed_contents(
1230 $sdist->unit_label_prefix,
1231 join(", ", @$formatted_parts),
1232 $sdist->unit_label_suffix
1236 # TODO: change this when real summary contents are available
1237 $sunit->summary_contents($sunit->detailed_contents);
1239 # Create sort_key by left padding numbers to 6 digits.
1240 (my $sort_key = $sunit->detailed_contents) =~
1241 s/(\d+)/sprintf '%06d', $1/eg;
1242 $sunit->sort_key($sort_key);
1245 # XXX duplicates a block of code from unitize_items(). Once I fully understand
1246 # what's going on and I'm sure it's working right, I'd like to have
1247 # unitize_items() just use this, keeping the logic in one place.
1248 sub _prepare_summaries {
1249 my ($e, $sitem, $issuances) = @_;
1251 my $dist_id = $sitem->stream->distribution->id;
1252 my $type = $sitem->issuance->holding_type;
1254 # Make sure @$issuances contains the new issuance from sitem.
1255 unless (grep { $_->id == $sitem->issuance->id } @$issuances) {
1256 push @$issuances, $sitem->issuance;
1259 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances);
1261 my $search_method = "search_serial_${type}_summary";
1262 my $summary = $e->$search_method([{"distribution" => $dist_id}]);
1264 my $cu_method = "update";
1267 $summary = $summary->[0];
1269 my $class = "Fieldmapper::serial::${type}_summary";
1270 $summary = $class->new;
1271 $summary->distribution($dist_id);
1272 $cu_method = "create";
1275 $summary->generated_coverage(join(", ", @$formatted_parts));
1276 my $method = "${cu_method}_serial_${type}_summary";
1277 return $e->die_event unless $e->$method($summary);
1280 sub _unit_by_iss_and_str {
1281 my ($e, $issuance, $stream) = @_;
1283 my $unit = $e->json_query({
1284 "select" => {"sunit" => ["id"]},
1285 "from" => {"sitem" => {"sunit" => {}}},
1288 "issuance" => $issuance->id,
1289 "stream" => $stream->id
1292 }) or return $e->die_event;
1293 return 0 if not @$unit;
1295 $e->retrieve_serial_unit($unit->[0]->{"id"}) or $e->die_event;
1298 sub move_previous_unit {
1299 my ($e, $prev_iss, $curr_item, $new_loc) = @_;
1301 my $prev_unit = _unit_by_iss_and_str($e,$prev_iss,$curr_item->stream);
1302 return $prev_unit if defined $U->event_code($prev_unit);
1303 return 0 if not $prev_unit;
1305 if ($prev_unit->location != $new_loc) {
1306 $prev_unit->location($new_loc);
1307 $e->update_serial_unit($prev_unit) or return $e->die_event;
1312 # _previous_issuance() assumes $existing is an ordered array
1313 sub _previous_issuance {
1314 my ($existing, $issuance) = @_;
1316 my $last = $existing->[-1];
1317 return undef unless $last;
1318 return ($last->id == $issuance->id ? $existing->[-2] : $last);
1321 __PACKAGE__->register_method(
1322 "method" => "receive_items_one_unit_per",
1323 "api_name" => "open-ils.serial.receive_items.one_unit_per",
1328 "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",
1332 "desc" => "authtoken",
1337 "desc" => "array of serial items, possibly fleshed with units and definitely fleshed with stream->distribution",
1342 "desc" => "id of bib record these items are associated with
1343 (XXX could/should be derived from items)",
1348 "desc" => "The item ID for each item successfully received",
1354 sub receive_items_one_unit_per {
1355 # XXX This function may be temporary, as it does some of what
1356 # unitize_items() does, just in a different way.
1357 my ($self, $client, $auth, $items, $record) = @_;
1359 my $e = new_editor("authtoken" => $auth, "xact" => 1);
1360 return $e->die_event unless $e->checkauth;
1361 return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
1363 my $prev_loc_setting_map = {};
1364 my $user_id = $e->requestor->id;
1366 # Get a list of all the non-virtual field names in a serial::unit for
1367 # merging given unit objects with template-built units later.
1368 # XXX move this somewhere global so it isn't re-run all the time
1369 my $all_unit_fields =
1370 $Fieldmapper::fieldmap->{"Fieldmapper::serial::unit"}->{"fields"};
1371 my @real_unit_fields = grep {
1372 not $all_unit_fields->{$_}->{"virtual"}
1373 } keys %$all_unit_fields;
1375 foreach my $item (@$items) {
1376 # Note that we expect a certain fleshing on the items we're getting.
1377 my $sdist = $item->stream->distribution;
1379 # Fetch a list of issuances with received copies already existing
1380 # on this distribution (and with the same holding type on the
1381 # issuance). This will be used in up to two places: once when building
1382 # a summary, once when changing the copy location of the previous
1384 my $issuances_received = _issuances_received($e, $item);
1385 if ($U->event_code($issuances_received)) {
1387 return $issuances_received;
1390 # Find out if we need to to deal with previous copy location changing.
1391 my $ou = $sdist->holding_lib->id;
1392 unless (exists $prev_loc_setting_map->{$ou}) {
1393 $prev_loc_setting_map->{$ou} = $U->ou_ancestor_setting_value(
1394 $ou, "serial.prev_issuance_copy_location", $e
1398 # If there is a previous copy location setting, we need the previous
1399 # issuance, from which we can in turn look up the item attached to the
1400 # same stream we're on now.
1401 if ($prev_loc_setting_map->{$ou}) {
1403 _previous_issuance($issuances_received, $item->issuance)) {
1405 # Now we can change the copy location of the previous unit,
1407 return $e->event if defined $U->event_code(
1409 $e, $prev_iss, $item, $prev_loc_setting_map->{$ou}
1415 # Create unit if given by user
1416 if (ref $item->unit) {
1417 # detach from the item, as we need to create separately
1418 my $user_unit = $item->unit;
1420 # get a unit based on associated template
1421 my $template_unit = _build_unit($e, $sdist, "receive", 1);
1422 if ($U->event_code($template_unit)) {
1424 $template_unit->{"note"} = "Item ID: " . $item->id;
1425 return $template_unit;
1428 # merge built unit with provided unit from user
1429 foreach (@real_unit_fields) {
1430 unless ($user_unit->$_) {
1431 $user_unit->$_($template_unit->$_);
1435 # Treat call number specially: the provided value from the
1436 # user will really be a string.
1437 if ($user_unit->call_number) {
1438 my $real_cn = _find_or_create_call_number(
1439 $e, $sdist->holding_lib->id,
1440 $user_unit->call_number, $record
1443 if ($U->event_code($real_cn)) {
1447 $user_unit->call_number($real_cn);
1451 my $evt = _prepare_unit_label(
1452 $e, $user_unit, $sdist, $item->issuance
1454 if ($U->event_code($evt)) {
1459 # create/update summary objects related to this distribution
1460 $evt = _prepare_summaries($e, $item, $issuances_received);
1461 if ($U->event_code($evt)) {
1466 # set the incontrovertibles on the unit
1467 $user_unit->edit_date("now");
1468 $user_unit->create_date("now");
1469 $user_unit->editor($user_id);
1470 $user_unit->creator($user_id);
1472 return $e->die_event unless $e->create_serial_unit($user_unit);
1474 # save reference to new unit
1475 $item->unit($e->data->id);
1478 # Create notes if given by user
1479 if (ref($item->notes) and @{$item->notes}) {
1480 foreach my $note (@{$item->notes}) {
1481 $note->creator($user_id);
1482 $note->create_date("now");
1484 return $e->die_event unless $e->create_serial_item_note($note);
1487 $item->clear_notes; # They're saved; we no longer want them here.
1490 # Set the incontrovertibles on the item
1491 $item->status("Received");
1492 $item->date_received("now");
1493 $item->edit_date("now");
1494 $item->editor($user_id);
1496 return $e->die_event unless $e->update_serial_item($item);
1498 # send client a response
1499 $client->respond($item->id);
1502 $e->commit or return $e->die_event;
1510 my $skip_call_number = shift;
1511 my $barcode = shift;
1513 my $attr = $mode . '_unit_template';
1514 my $template = $editor->retrieve_asset_copy_template($sdist->$attr) or
1515 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_COPY_TEMPLATE");
1517 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 );
1519 my $unit = new Fieldmapper::serial::unit;
1520 foreach my $part (@parts) {
1521 my $value = $template->$part;
1522 next if !defined($value);
1523 $unit->$part($value);
1526 # ignore circ_lib in template, set to distribution holding_lib
1527 $unit->circ_lib($sdist->holding_lib);
1528 $unit->creator($editor->requestor->id);
1529 $unit->editor($editor->requestor->id);
1531 unless ($skip_call_number) {
1532 $attr = $mode . '_call_number';
1533 my $cn = $sdist->$attr or
1534 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_CALL_NUMBER");
1536 $unit->call_number($cn);
1540 $unit->barcode($barcode);
1542 $unit->barcode('AUTO');
1544 $unit->sort_key('');
1545 $unit->summary_contents('');
1546 $unit->detailed_contents('');
1552 sub _summarize_contents {
1554 my $issuances = shift;
1556 # create MFHD record
1557 my $mfhd = MFHD->new(MARC::Record->new());
1560 my @scap_fields_ordered;
1563 foreach my $issuance (@$issuances) {
1564 my $scap_id = $issuance->caption_and_pattern;
1565 next if (!$scap_id); # skip issuances with no caption/pattern
1569 # if this is the first appearance of this scap, retrieve it and add it to the temporary record
1570 if (!exists $scaps{$issuance->caption_and_pattern}) {
1571 $scaps{$scap_id} = $editor->retrieve_serial_caption_and_pattern($scap_id);
1572 $scap = $scaps{$scap_id};
1573 $scap_field = _revive_caption($scap);
1574 $scap_fields{$scap_id} = $scap_field;
1575 push(@scap_fields_ordered, $scap_field);
1576 $scap_field->update('8' => $link_id);
1577 $mfhd->append_fields($scap_field);
1580 $scap = $scaps{$scap_id};
1581 $scap_field = $scap_fields{$scap_id};
1584 $mfhd->append_fields(_revive_holding($issuance->holding_code, $scap_field, $seqno));
1588 my @formatted_parts;
1589 foreach my $scap_field (@scap_fields_ordered) { #TODO: use generic MFHD "summarize" method, once available
1590 my @updated_holdings = $mfhd->get_compressed_holdings($scap_field);
1591 foreach my $holding (@updated_holdings) {
1592 push(@formatted_parts, $holding->format);
1596 return ($mfhd, \@formatted_parts);
1599 ##########################################################################
1602 __PACKAGE__->register_method(
1603 method => 'fetch_notes',
1604 api_name => 'open-ils.serial.item_note.retrieve.all',
1606 Returns an array of copy note objects.
1607 @param args A named hash of parameters including:
1608 authtoken : Required if viewing non-public notes
1609 item_id : The id of the item whose notes we want to retrieve
1610 pub : True if all the caller wants are public notes
1611 @return An array of note objects
1615 __PACKAGE__->register_method(
1616 method => 'fetch_notes',
1617 api_name => 'open-ils.serial.subscription_note.retrieve.all',
1619 Returns an array of copy note objects.
1620 @param args A named hash of parameters including:
1621 authtoken : Required if viewing non-public notes
1622 subscription_id : The id of the item whose notes we want to retrieve
1623 pub : True if all the caller wants are public notes
1624 @return An array of note objects
1628 __PACKAGE__->register_method(
1629 method => 'fetch_notes',
1630 api_name => 'open-ils.serial.distribution_note.retrieve.all',
1632 Returns an array of copy note objects.
1633 @param args A named hash of parameters including:
1634 authtoken : Required if viewing non-public notes
1635 distribution_id : The id of the item whose notes we want to retrieve
1636 pub : True if all the caller wants are public notes
1637 @return An array of note objects
1641 # TODO: revisit this method to consider replacing cstore direct calls
1643 my( $self, $connection, $args ) = @_;
1645 $self->api_name =~ /serial\.(\w*)_note/;
1648 my $id = $$args{object_id};
1649 my $authtoken = $$args{authtoken};
1653 return $U->cstorereq(
1654 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic',
1655 { $type => $id, pub => 't' } );
1657 # FIXME: restore perm check
1658 # ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
1659 # return $evt if $evt;
1660 return $U->cstorereq(
1661 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic', {$type => $id} );
1667 __PACKAGE__->register_method(
1668 method => 'create_note',
1669 api_name => 'open-ils.serial.item_note.create',
1671 Creates a new item note
1672 @param authtoken The login session key
1673 @param note The note object to create
1674 @return The id of the new note object
1678 __PACKAGE__->register_method(
1679 method => 'create_note',
1680 api_name => 'open-ils.serial.subscription_note.create',
1682 Creates a new subscription note
1683 @param authtoken The login session key
1684 @param note The note object to create
1685 @return The id of the new note object
1689 __PACKAGE__->register_method(
1690 method => 'create_note',
1691 api_name => 'open-ils.serial.distribution_note.create',
1693 Creates a new distribution note
1694 @param authtoken The login session key
1695 @param note The note object to create
1696 @return The id of the new note object
1701 my( $self, $connection, $authtoken, $note ) = @_;
1703 $self->api_name =~ /serial\.(\w*)_note/;
1706 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1707 return $e->event unless $e->checkauth;
1709 # FIXME: restore permission support
1710 # my $item = $e->retrieve_serial_item(
1716 # return $e->event unless
1717 # $e->allowed('CREATE_COPY_NOTE', $item->call_number->owning_lib);
1719 $note->create_date('now');
1720 $note->creator($e->requestor->id);
1721 $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
1724 my $method = "create_serial_${type}_note";
1725 $e->$method($note) or return $e->event;
1730 __PACKAGE__->register_method(
1731 method => 'delete_note',
1732 api_name => 'open-ils.serial.item_note.delete',
1734 Deletes an existing item note
1735 @param authtoken The login session key
1736 @param noteid The id of the note to delete
1737 @return 1 on success - Event otherwise.
1741 __PACKAGE__->register_method(
1742 method => 'delete_note',
1743 api_name => 'open-ils.serial.subscription_note.delete',
1745 Deletes an existing subscription note
1746 @param authtoken The login session key
1747 @param noteid The id of the note to delete
1748 @return 1 on success - Event otherwise.
1752 __PACKAGE__->register_method(
1753 method => 'delete_note',
1754 api_name => 'open-ils.serial.distribution_note.delete',
1756 Deletes an existing distribution note
1757 @param authtoken The login session key
1758 @param noteid The id of the note to delete
1759 @return 1 on success - Event otherwise.
1764 my( $self, $conn, $authtoken, $noteid ) = @_;
1766 $self->api_name =~ /serial\.(\w*)_note/;
1769 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1770 return $e->die_event unless $e->checkauth;
1772 my $method = "retrieve_serial_${type}_note";
1773 my $note = $e->$method([
1775 ]) or return $e->die_event;
1777 # FIXME: restore permissions check
1778 # if( $note->creator ne $e->requestor->id ) {
1779 # return $e->die_event unless
1780 # $e->allowed('DELETE_COPY_NOTE', $note->item->call_number->owning_lib);
1783 $method = "delete_serial_${type}_note";
1784 $e->$method($note) or return $e->die_event;
1790 ##########################################################################
1791 # subscription methods
1793 __PACKAGE__->register_method(
1794 method => 'fleshed_ssub_alter',
1795 api_name => 'open-ils.serial.subscription.fleshed.batch.update',
1799 desc => 'Receives an array of one or more subscriptions and updates the database as needed',
1801 name => 'authtoken',
1802 desc => 'Authtoken for current user session',
1806 name => 'subscriptions',
1807 desc => 'Array of fleshed subscriptions',
1813 desc => 'Returns 1 if successful, event if failed',
1819 sub fleshed_ssub_alter {
1820 my( $self, $conn, $auth, $ssubs ) = @_;
1821 return 1 unless ref $ssubs;
1822 my( $reqr, $evt ) = $U->checkses($auth);
1823 return $evt if $evt;
1824 my $editor = new_editor(requestor => $reqr, xact => 1);
1825 my $override = $self->api_name =~ /override/;
1827 # TODO: permission check
1828 # return $editor->event unless
1829 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
1831 for my $ssub (@$ssubs) {
1833 my $ssubid = $ssub->id;
1835 if( $ssub->isdeleted ) {
1836 $evt = _delete_ssub( $editor, $override, $ssub);
1837 } elsif( $ssub->isnew ) {
1838 _cleanse_dates($ssub, ['start_date','end_date']);
1839 $evt = _create_ssub( $editor, $ssub );
1841 _cleanse_dates($ssub, ['start_date','end_date']);
1842 $evt = _update_ssub( $editor, $override, $ssub );
1847 $logger->info("fleshed subscription-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
1851 $logger->debug("subscription-alter: done updating subscription batch");
1853 $logger->info("fleshed subscription-alter successfully updated ".scalar(@$ssubs)." subscriptions");
1858 my ($editor, $override, $ssub) = @_;
1859 $logger->info("subscription-alter: delete subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1860 my $sdists = $editor->search_serial_distribution(
1861 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1862 my $cps = $editor->search_serial_caption_and_pattern(
1863 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1864 my $sisses = $editor->search_serial_issuance(
1865 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1866 return OpenILS::Event->new(
1867 'SERIAL_SUBSCRIPTION_NOT_EMPTY', payload => $ssub->id ) if (@$sdists or @$cps or @$sisses);
1869 return $editor->event unless $editor->delete_serial_subscription($ssub);
1874 my ($editor, $ssub) = @_;
1876 $logger->info("subscription-alter: new subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1877 return $editor->event unless $editor->create_serial_subscription($ssub);
1882 my ($editor, $override, $ssub) = @_;
1884 $logger->info("subscription-alter: retrieving subscription ".$ssub->id);
1885 my $orig_ssub = $editor->retrieve_serial_subscription($ssub->id);
1887 $logger->info("subscription-alter: original subscription ".OpenSRF::Utils::JSON->perl2JSON($orig_ssub));
1888 $logger->info("subscription-alter: updated subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1889 return $editor->event unless $editor->update_serial_subscription($ssub);
1893 __PACKAGE__->register_method(
1894 method => "fleshed_serial_subscription_retrieve_batch",
1896 api_name => "open-ils.serial.subscription.fleshed.batch.retrieve"
1899 sub fleshed_serial_subscription_retrieve_batch {
1900 my( $self, $client, $ids ) = @_;
1901 # FIXME: permissions?
1902 $logger->info("Fetching fleshed subscriptions @$ids");
1903 return $U->cstorereq(
1904 "open-ils.cstore.direct.serial.subscription.search.atomic",
1907 flesh_fields => {ssub => [ qw/owning_lib notes/ ]}
1911 __PACKAGE__->register_method(
1912 method => "retrieve_sub_tree",
1914 api_name => "open-ils.serial.subscription_tree.retrieve"
1917 __PACKAGE__->register_method(
1918 method => "retrieve_sub_tree",
1919 api_name => "open-ils.serial.subscription_tree.global.retrieve"
1922 sub retrieve_sub_tree {
1924 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
1926 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
1930 # TODO: permission support
1931 if(!@org_ids and $user_session) {
1933 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
1934 @org_ids = ($user_obj->home_ou);
1937 if( $self->api_name =~ /global/ ) {
1938 return _build_subs_list( { record_entry => $docid } ); # TODO: filter for !deleted, or active?
1943 for my $orgid (@org_ids) {
1944 my $subs = _build_subs_list(
1945 { record_entry => $docid, owning_lib => $orgid } );# TODO: filter for !deleted, or active?
1946 push( @all_subs, @$subs );
1955 sub _build_subs_list {
1956 my $search_hash = shift;
1958 #$search_hash->{deleted} = 'f';
1959 my $e = new_editor();
1961 my $subs = $e->search_serial_subscription([$search_hash, { 'order_by' => {'ssub' => 'id'} }]);
1965 for my $sub (@$subs) {
1967 # TODO: filter on !deleted?
1968 my $dists = $e->search_serial_distribution(
1969 [{ subscription => $sub->id }, { 'order_by' => {'sdist' => 'label'} }]
1972 #$dists = [ sort { $a->label cmp $b->label } @$dists ];
1974 $sub->distributions($dists);
1976 # TODO: filter on !deleted?
1977 my $issuances = $e->search_serial_issuance(
1978 [{ subscription => $sub->id }, { 'order_by' => {'siss' => 'label'} }]
1981 #$issuances = [ sort { $a->label cmp $b->label } @$issuances ];
1982 $sub->issuances($issuances);
1984 # TODO: filter on !deleted?
1985 my $scaps = $e->search_serial_caption_and_pattern(
1986 [{ subscription => $sub->id }, { 'order_by' => {'scap' => 'id'} }]
1989 #$scaps = [ sort { $a->id cmp $b->id } @$scaps ];
1990 $sub->scaps($scaps);
1991 push( @built_subs, $sub );
1994 return \@built_subs;
1998 __PACKAGE__->register_method(
1999 method => "subscription_orgs_for_title",
2001 api_name => "open-ils.serial.subscription.retrieve_orgs_by_title"
2004 sub subscription_orgs_for_title {
2005 my( $self, $client, $record_id ) = @_;
2007 my $subs = $U->simple_scalar_request(
2009 "open-ils.cstore.direct.serial.subscription.search.atomic",
2010 { record_entry => $record_id }); # TODO: filter on !deleted?
2012 my $orgs = { map {$_->owning_lib => 1 } @$subs };
2013 return [ keys %$orgs ];
2017 ##########################################################################
2018 # distribution methods
2020 __PACKAGE__->register_method(
2021 method => 'fleshed_sdist_alter',
2022 api_name => 'open-ils.serial.distribution.fleshed.batch.update',
2026 desc => 'Receives an array of one or more distributions and updates the database as needed',
2028 name => 'authtoken',
2029 desc => 'Authtoken for current user session',
2033 name => 'distributions',
2034 desc => 'Array of fleshed distributions',
2040 desc => 'Returns 1 if successful, event if failed',
2046 sub fleshed_sdist_alter {
2047 my( $self, $conn, $auth, $sdists ) = @_;
2048 return 1 unless ref $sdists;
2049 my( $reqr, $evt ) = $U->checkses($auth);
2050 return $evt if $evt;
2051 my $editor = new_editor(requestor => $reqr, xact => 1);
2052 my $override = $self->api_name =~ /override/;
2054 # TODO: permission check
2055 # return $editor->event unless
2056 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2058 for my $sdist (@$sdists) {
2059 my $sdistid = $sdist->id;
2061 if( $sdist->isdeleted ) {
2062 $evt = _delete_sdist( $editor, $override, $sdist);
2063 } elsif( $sdist->isnew ) {
2064 $evt = _create_sdist( $editor, $sdist );
2066 $evt = _update_sdist( $editor, $override, $sdist );
2071 $logger->info("fleshed distribution-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2075 $logger->debug("distribution-alter: done updating distribution batch");
2077 $logger->info("fleshed distribution-alter successfully updated ".scalar(@$sdists)." distributions");
2082 my ($editor, $override, $sdist) = @_;
2083 $logger->info("distribution-alter: delete distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2084 return $editor->event unless $editor->delete_serial_distribution($sdist);
2089 my ($editor, $sdist) = @_;
2091 $logger->info("distribution-alter: new distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2092 return $editor->event unless $editor->create_serial_distribution($sdist);
2094 # create summaries too
2095 my $summary = new Fieldmapper::serial::basic_summary;
2096 $summary->distribution($sdist->id);
2097 $summary->generated_coverage('');
2098 return $editor->event unless $editor->create_serial_basic_summary($summary);
2099 $summary = new Fieldmapper::serial::supplement_summary;
2100 $summary->distribution($sdist->id);
2101 $summary->generated_coverage('');
2102 return $editor->event unless $editor->create_serial_supplement_summary($summary);
2103 $summary = new Fieldmapper::serial::index_summary;
2104 $summary->distribution($sdist->id);
2105 $summary->generated_coverage('');
2106 return $editor->event unless $editor->create_serial_index_summary($summary);
2108 # create a starter stream (TODO: reconsider this)
2109 my $stream = new Fieldmapper::serial::stream;
2110 $stream->distribution($sdist->id);
2111 return $editor->event unless $editor->create_serial_stream($stream);
2117 my ($editor, $override, $sdist) = @_;
2119 $logger->info("distribution-alter: retrieving distribution ".$sdist->id);
2120 my $orig_sdist = $editor->retrieve_serial_distribution($sdist->id);
2122 $logger->info("distribution-alter: original distribution ".OpenSRF::Utils::JSON->perl2JSON($orig_sdist));
2123 $logger->info("distribution-alter: updated distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2124 return $editor->event unless $editor->update_serial_distribution($sdist);
2128 __PACKAGE__->register_method(
2129 method => "fleshed_serial_distribution_retrieve_batch",
2131 api_name => "open-ils.serial.distribution.fleshed.batch.retrieve"
2134 sub fleshed_serial_distribution_retrieve_batch {
2135 my( $self, $client, $ids ) = @_;
2136 # FIXME: permissions?
2137 $logger->info("Fetching fleshed distributions @$ids");
2138 return $U->cstorereq(
2139 "open-ils.cstore.direct.serial.distribution.search.atomic",
2142 flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams / ]}
2146 __PACKAGE__->register_method(
2147 method => "retrieve_dist_tree",
2149 api_name => "open-ils.serial.distribution_tree.retrieve"
2152 __PACKAGE__->register_method(
2153 method => "retrieve_dist_tree",
2154 api_name => "open-ils.serial.distribution_tree.global.retrieve"
2157 sub retrieve_dist_tree {
2158 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2160 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2164 # TODO: permission support
2165 if(!@org_ids and $user_session) {
2167 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2168 @org_ids = ($user_obj->home_ou);
2171 my $e = new_editor();
2173 if( $self->api_name =~ /global/ ) {
2174 return $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }},
2176 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 / ]},
2177 order_by => {'sdist' => 'id'},
2178 'join' => {'ssub' => {}}
2180 ]); # TODO: filter for !deleted?
2184 for my $orgid (@org_ids) {
2185 my $dists = $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }, holding_lib => $orgid},
2187 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 / ]},
2188 order_by => {'sdist' => 'id'},
2189 'join' => {'ssub' => {}}
2191 ]); # TODO: filter for !deleted?
2192 push( @all_dists, @$dists ) if $dists;
2202 __PACKAGE__->register_method(
2203 method => "distribution_orgs_for_title",
2205 api_name => "open-ils.serial.distribution.retrieve_orgs_by_title"
2208 sub distribution_orgs_for_title {
2209 my( $self, $client, $record_id ) = @_;
2211 my $dists = $U->cstorereq(
2212 "open-ils.cstore.direct.serial.distribution.search.atomic",
2213 { '+ssub' => { record_entry => $record_id } },
2214 { 'join' => {'ssub' => {}} }); # TODO: filter on !deleted?
2216 my $orgs = { map {$_->holding_lib => 1 } @$dists };
2217 return [ keys %$orgs ];
2221 ##########################################################################
2222 # caption and pattern methods
2224 __PACKAGE__->register_method(
2225 method => 'scap_alter',
2226 api_name => 'open-ils.serial.caption_and_pattern.batch.update',
2230 desc => 'Receives an array of one or more caption and patterns and updates the database as needed',
2232 name => 'authtoken',
2233 desc => 'Authtoken for current user session',
2238 desc => 'Array of caption and patterns',
2244 desc => 'Returns 1 if successful, event if failed',
2251 my( $self, $conn, $auth, $scaps ) = @_;
2252 return 1 unless ref $scaps;
2253 my( $reqr, $evt ) = $U->checkses($auth);
2254 return $evt if $evt;
2255 my $editor = new_editor(requestor => $reqr, xact => 1);
2256 my $override = $self->api_name =~ /override/;
2258 # TODO: permission check
2259 # return $editor->event unless
2260 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2262 for my $scap (@$scaps) {
2263 my $scapid = $scap->id;
2265 if( $scap->isdeleted ) {
2266 $evt = _delete_scap( $editor, $override, $scap);
2267 } elsif( $scap->isnew ) {
2268 $evt = _create_scap( $editor, $scap );
2270 $evt = _update_scap( $editor, $override, $scap );
2275 $logger->info("caption_and_pattern-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2279 $logger->debug("caption_and_pattern-alter: done updating caption_and_pattern batch");
2281 $logger->info("caption_and_pattern-alter successfully updated ".scalar(@$scaps)." caption_and_patterns");
2286 my ($editor, $override, $scap) = @_;
2287 $logger->info("caption_and_pattern-alter: delete caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2288 my $sisses = $editor->search_serial_issuance(
2289 { caption_and_pattern => $scap->id }, { limit => 1 } ); #TODO: 'deleted' support?
2290 return OpenILS::Event->new(
2291 'SERIAL_CAPTION_AND_PATTERN_HAS_ISSUANCES', payload => $scap->id ) if (@$sisses);
2293 return $editor->event unless $editor->delete_serial_caption_and_pattern($scap);
2298 my ($editor, $scap) = @_;
2300 $logger->info("caption_and_pattern-alter: new caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2301 return $editor->event unless $editor->create_serial_caption_and_pattern($scap);
2306 my ($editor, $override, $scap) = @_;
2308 $logger->info("caption_and_pattern-alter: retrieving caption_and_pattern ".$scap->id);
2309 my $orig_scap = $editor->retrieve_serial_caption_and_pattern($scap->id);
2311 $logger->info("caption_and_pattern-alter: original caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($orig_scap));
2312 $logger->info("caption_and_pattern-alter: updated caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2313 return $editor->event unless $editor->update_serial_caption_and_pattern($scap);
2317 __PACKAGE__->register_method(
2318 method => "serial_caption_and_pattern_retrieve_batch",
2320 api_name => "open-ils.serial.caption_and_pattern.batch.retrieve"
2323 sub serial_caption_and_pattern_retrieve_batch {
2324 my( $self, $client, $ids ) = @_;
2325 $logger->info("Fetching caption_and_patterns @$ids");
2326 return $U->cstorereq(
2327 "open-ils.cstore.direct.serial.caption_and_pattern.search.atomic",
2332 ##########################################################################
2335 __PACKAGE__->register_method(
2336 method => 'sstr_alter',
2337 api_name => 'open-ils.serial.stream.batch.update',
2341 desc => 'Receives an array of one or more streams and updates the database as needed',
2343 name => 'authtoken',
2344 desc => 'Authtoken for current user session',
2349 desc => 'Array of streams',
2355 desc => 'Returns 1 if successful, event if failed',
2362 my( $self, $conn, $auth, $sstrs ) = @_;
2363 return 1 unless ref $sstrs;
2364 my( $reqr, $evt ) = $U->checkses($auth);
2365 return $evt if $evt;
2366 my $editor = new_editor(requestor => $reqr, xact => 1);
2367 my $override = $self->api_name =~ /override/;
2369 # TODO: permission check
2370 # return $editor->event unless
2371 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2373 for my $sstr (@$sstrs) {
2374 my $sstrid = $sstr->id;
2376 if( $sstr->isdeleted ) {
2377 $evt = _delete_sstr( $editor, $override, $sstr);
2378 } elsif( $sstr->isnew ) {
2379 $evt = _create_sstr( $editor, $sstr );
2381 $evt = _update_sstr( $editor, $override, $sstr );
2386 $logger->info("stream-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2390 $logger->debug("stream-alter: done updating stream batch");
2392 $logger->info("stream-alter successfully updated ".scalar(@$sstrs)." streams");
2397 my ($editor, $override, $sstr) = @_;
2398 $logger->info("stream-alter: delete stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2399 my $sitems = $editor->search_serial_item(
2400 { stream => $sstr->id }, { limit => 1 } ); #TODO: 'deleted' support?
2401 return OpenILS::Event->new(
2402 'SERIAL_STREAM_HAS_ITEMS', payload => $sstr->id ) if (@$sitems);
2404 return $editor->event unless $editor->delete_serial_stream($sstr);
2409 my ($editor, $sstr) = @_;
2411 $logger->info("stream-alter: new stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2412 return $editor->event unless $editor->create_serial_stream($sstr);
2417 my ($editor, $override, $sstr) = @_;
2419 $logger->info("stream-alter: retrieving stream ".$sstr->id);
2420 my $orig_sstr = $editor->retrieve_serial_stream($sstr->id);
2422 $logger->info("stream-alter: original stream ".OpenSRF::Utils::JSON->perl2JSON($orig_sstr));
2423 $logger->info("stream-alter: updated stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2424 return $editor->event unless $editor->update_serial_stream($sstr);
2428 __PACKAGE__->register_method(
2429 method => "serial_stream_retrieve_batch",
2431 api_name => "open-ils.serial.stream.batch.retrieve"
2434 sub serial_stream_retrieve_batch {
2435 my( $self, $client, $ids ) = @_;
2436 $logger->info("Fetching streams @$ids");
2437 return $U->cstorereq(
2438 "open-ils.cstore.direct.serial.stream.search.atomic",
2444 ##########################################################################
2447 __PACKAGE__->register_method(
2448 method => 'sum_alter',
2449 api_name => 'open-ils.serial.basic_summary.batch.update',
2453 desc => 'Receives an array of one or more summaries and updates the database as needed',
2455 name => 'authtoken',
2456 desc => 'Authtoken for current user session',
2461 desc => 'Array of basic summaries',
2467 desc => 'Returns 1 if successful, event if failed',
2473 __PACKAGE__->register_method(
2474 method => 'sum_alter',
2475 api_name => 'open-ils.serial.supplement_summary.batch.update',
2479 desc => 'Receives an array of one or more summaries and updates the database as needed',
2481 name => 'authtoken',
2482 desc => 'Authtoken for current user session',
2487 desc => 'Array of supplement summaries',
2493 desc => 'Returns 1 if successful, event if failed',
2499 __PACKAGE__->register_method(
2500 method => 'sum_alter',
2501 api_name => 'open-ils.serial.index_summary.batch.update',
2505 desc => 'Receives an array of one or more summaries and updates the database as needed',
2507 name => 'authtoken',
2508 desc => 'Authtoken for current user session',
2513 desc => 'Array of index summaries',
2519 desc => 'Returns 1 if successful, event if failed',
2526 my( $self, $conn, $auth, $sums ) = @_;
2527 return 1 unless ref $sums;
2529 $self->api_name =~ /serial\.(\w*)_summary/;
2532 my( $reqr, $evt ) = $U->checkses($auth);
2533 return $evt if $evt;
2534 my $editor = new_editor(requestor => $reqr, xact => 1);
2535 my $override = $self->api_name =~ /override/;
2537 # TODO: permission check
2538 # return $editor->event unless
2539 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2541 for my $sum (@$sums) {
2542 my $sumid = $sum->id;
2544 # XXX: (for now, at least) summaries should be created/deleted by the distribution functions
2545 if( $sum->isdeleted ) {
2546 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2547 } elsif( $sum->isnew ) {
2548 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2550 $evt = _update_sum( $editor, $override, $sum, $type );
2555 $logger->info("${type}_summary-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2559 $logger->debug("${type}_summary-alter: done updating ${type}_summary batch");
2561 $logger->info("${type}_summary-alter successfully updated ".scalar(@$sums)." ${type}_summaries");
2566 my ($editor, $override, $sum, $type) = @_;
2568 $logger->info("${type}_summary-alter: retrieving ${type}_summary ".$sum->id);
2569 my $retrieve_method = "retrieve_serial_${type}_summary";
2570 my $orig_sum = $editor->$retrieve_method($sum->id);
2572 $logger->info("${type}_summary-alter: original ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($orig_sum));
2573 $logger->info("${type}_summary-alter: updated ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($sum));
2574 my $update_method = "update_serial_${type}_summary";
2575 return $editor->event unless $editor->$update_method($sum);
2579 __PACKAGE__->register_method(
2580 method => "serial_summary_retrieve_batch",
2582 api_name => "open-ils.serial.basic_summary.batch.retrieve"
2585 __PACKAGE__->register_method(
2586 method => "serial_summary_retrieve_batch",
2588 api_name => "open-ils.serial.supplement_summary.batch.retrieve"
2591 __PACKAGE__->register_method(
2592 method => "serial_summary_retrieve_batch",
2594 api_name => "open-ils.serial.index_summary.batch.retrieve"
2597 sub serial_summary_retrieve_batch {
2598 my( $self, $client, $ids ) = @_;
2600 $self->api_name =~ /serial\.(\w*)_summary/;
2603 $logger->info("Fetching ${type}_summaries @$ids");
2604 return $U->cstorereq(
2605 "open-ils.cstore.direct.serial.".$type."_summary.search.atomic",
2611 ##########################################################################
2614 __PACKAGE__->register_method(
2615 "method" => "bre_by_identifier",
2616 "api_name" => "open-ils.serial.biblio.record_entry.by_identifier",
2619 "desc" => "Find instances of biblio.record_entry given a search token" .
2620 " that could be a value for any identifier defined in " .
2621 "config.metabib_field",
2623 {"desc" => "Search token", "type" => "string"},
2624 {"desc" => "Options: require_subscriptions, add_mvr, is_actual_id" .
2625 " (all boolean)", "type" => "object"}
2628 "desc" => "Any matching BREs, or if the add_mvr option is true, " .
2629 "objects with a 'bre' key/value pair, and an 'mvr' " .
2630 "key-value pair. BREs have subscriptions fleshed on.",
2636 sub bre_by_identifier {
2637 my ($self, $client, $term, $options) = @_;
2639 return new OpenILS::Event("BAD_PARAMS") unless $term;
2642 my $e = new_editor();
2646 if ($options->{"is_actual_id"}) {
2650 $e->search_config_metabib_field({"field_class" => "identifier"})
2651 or return $e->die_event;
2653 my @identifiers = map { $_->name } @$cmf;
2654 my $query = join(" || ", map { "id|$_: $term" } @identifiers);
2656 my $search = create OpenSRF::AppSession("open-ils.search");
2657 my $search_result = $search->request(
2658 "open-ils.search.biblio.multiclass.query.staff", {}, $query
2660 $search->disconnect;
2662 # Un-nest results. They tend to look like [[1],[2],[3]] for some reason.
2663 @ids = map { @{$_} } @{$search_result->{"ids"}};
2671 my $bre = $e->search_biblio_record_entry([
2673 "flesh" => 2, "flesh_fields" => {
2674 "bre" => ["subscriptions"],
2675 "ssub" => ["owning_lib"]
2678 ]) or return $e->die_event;
2680 if (@$bre && $options->{"require_subscriptions"}) {
2681 $bre = [ grep { @{$_->subscriptions} } @$bre ];
2686 if (@$bre) { # re-evaluate after possible grep
2687 if ($options->{"add_mvr"}) {
2689 {"bre" => $_, "mvr" => _get_mvr($_->id)}
2692 $client->respond($_) foreach (@$bre);
2699 __PACKAGE__->register_method(
2700 "method" => "get_receivable_items",
2701 "api_name" => "open-ils.serial.items.receivable.by_subscription",
2704 "desc" => "Return all receivable items under a given subscription",
2706 {"desc" => "Authtoken", "type" => "string"},
2707 {"desc" => "Subscription ID", "type" => "number"},
2710 "desc" => "All receivable items under a given subscription",
2716 __PACKAGE__->register_method(
2717 "method" => "get_receivable_items",
2718 "api_name" => "open-ils.serial.items.receivable.by_issuance",
2721 "desc" => "Return all receivable items under a given issuance",
2723 {"desc" => "Authtoken", "type" => "string"},
2724 {"desc" => "Issuance ID", "type" => "number"},
2727 "desc" => "All receivable items under a given issuance",
2733 sub get_receivable_items {
2734 my ($self, $client, $auth, $term) = @_;
2736 my $e = new_editor("authtoken" => $auth);
2737 return $e->die_event unless $e->checkauth;
2741 my $by = ($self->api_name =~ /by_(\w+)$/)[0];
2744 "issuance" => {"issuance" => $term},
2745 "subscription" => {"+siss" => {"subscription" => $term}}
2748 my $item_ids = $e->json_query(
2750 "select" => {"sitem" => ["id"]},
2751 "from" => {"sitem" => "siss"},
2753 %{$where{$by}}, "date_received" => undef
2755 "order_by" => {"sitem" => ["id"]}
2757 ) or return $e->die_event;
2759 return undef unless @$item_ids;
2761 foreach (map { $_->{"id"} } @$item_ids) {
2763 $e->retrieve_serial_item([
2767 "sitem" => ["stream", "issuance"],
2768 "sstr" => ["distribution"],
2769 "sdist" => ["holding_lib"]
2780 __PACKAGE__->register_method(
2781 "method" => "get_receivable_issuances",
2782 "api_name" => "open-ils.serial.issuances.receivable",
2785 "desc" => "Return all issuances with receivable items given " .
2786 "a subscription ID",
2788 {"desc" => "Authtoken", "type" => "string"},
2789 {"desc" => "Subscription ID", "type" => "number"},
2792 "desc" => "All issuances with receivable items " .
2793 "(but not the items themselves)", "type" => "object"
2798 sub get_receivable_issuances {
2799 my ($self, $client, $auth, $sub_id) = @_;
2801 my $e = new_editor("authtoken" => $auth);
2802 return $e->die_event unless $e->checkauth;
2806 my $issuance_ids = $e->json_query({
2809 {"transform" => "distinct", "column" => "id"},
2813 "from" => {"siss" => "sitem"},
2815 "subscription" => $sub_id,
2816 "+sitem" => {"date_received" => undef}
2819 "siss" => {"date_published" => {"direction" => "asc"}}
2822 }) or return $e->die_event;
2824 $client->respond($e->retrieve_serial_issuance($_->{"id"}))
2825 foreach (@$issuance_ids);
2832 __PACKAGE__->register_method(
2833 "method" => "get_routing_list_users",
2834 "api_name" => "open-ils.serial.routing_list_users.fleshed_and_ordered",
2837 "desc" => "Return all routing list users with reader fleshed " .
2838 "(with card and home_ou) for a given stream ID, sorted by pos",
2840 {"desc" => "Authtoken", "type" => "string"},
2841 {"desc" => "Stream ID (int or array of ints)", "type" => "mixed"},
2844 "desc" => "Stream of routing list users", "type" => "object",
2850 sub get_routing_list_users {
2851 my ($self, $client, $auth, $stream_id) = @_;
2853 my $e = new_editor("authtoken" => $auth);
2854 return $e->die_event unless $e->checkauth;
2856 my $users = $e->search_serial_routing_list_user([
2857 {"stream" => $stream_id}, {
2858 "order_by" => {"srlu" => "pos"},
2861 "srlu" => [qw/reader stream/],
2862 "au" => [qw/card home_ou/],
2863 "sstr" => ["distribution"]
2866 ]) or return $e->die_event;
2868 return undef unless @$users;
2870 # The ADMIN_SERIAL_STREAM permission is used simply to avoid the
2871 # need for any new permission. The context OU will be the same
2872 # for every result of the above query, so we need only check once.
2873 return $e->die_event unless $e->allowed(
2874 "ADMIN_SERIAL_STREAM", $users->[0]->stream->distribution->holding_lib
2879 my @users = map { $_->stream($_->stream->id); $_ } @$users;
2880 @users = sort { $a->stream cmp $b->stream } @users if
2881 ref $stream_id eq "ARRAY";
2883 $client->respond($_) for @users;
2889 __PACKAGE__->register_method(
2890 "method" => "replace_routing_list_users",
2891 "api_name" => "open-ils.serial.routing_list_users.replace",
2893 "desc" => "Replace all routing list users on the specified streams " .
2894 "with those in the list argument",
2896 {"desc" => "Authtoken", "type" => "string"},
2897 {"desc" => "List of srlu objects", "type" => "array"},
2900 "desc" => "event on failure, undef on success"
2905 sub replace_routing_list_users {
2906 my ($self, $client, $auth, $users) = @_;
2908 return undef unless ref $users eq "ARRAY";
2910 if (grep { ref $_ ne "Fieldmapper::serial::routing_list_user" } @$users) {
2911 return new OpenILS::Event("BAD_PARAMS", "note" => "Only srlu objects");
2914 my $e = new_editor("authtoken" => $auth, "xact" => 1);
2915 return $e->die_event unless $e->checkauth;
2917 my %streams_ok = ();
2920 foreach my $user (@$users) {
2921 unless (exists $streams_ok{$user->stream}) {
2922 my $stream = $e->retrieve_serial_stream([
2925 "flesh_fields" => {"sstr" => ["distribution"]}
2927 ]) or return $e->die_event;
2929 "ADMIN_SERIAL_STREAM", $stream->distribution->holding_lib
2930 ) or return $e->die_event;
2932 my $to_delete = $e->search_serial_routing_list_user(
2933 {"stream" => $user->stream}
2934 ) or return $e->die_event;
2937 "Deleting srlu: [" .
2938 join(", ", map { $_->id; } @$to_delete) .
2942 foreach (@$to_delete) {
2943 $e->delete_serial_routing_list_user($_) or
2944 return $e->die_event;
2947 $streams_ok{$user->stream} = 1;
2950 next if $user->isdeleted;
2954 $e->create_serial_routing_list_user($user) or return $e->die_event;
2957 $e->commit or return $e->die_event;
2961 __PACKAGE__->register_method(
2962 "method" => "get_records_with_marc_85x",
2963 "api_name"=>"open-ils.serial.caption_and_pattern.find_legacy_by_bib_record",
2966 "desc" => "Return the specified BRE itself and/or any related SRE ".
2967 "whenever they have 853-855 tags",
2969 {"desc" => "Authtoken", "type" => "string"},
2970 {"desc" => "bib record ID", "type" => "number"},
2973 "desc" => "objects, either bre or sre", "type" => "object"
2978 sub get_records_with_marc_85x { # specifically, 853-855
2979 my ($self, $client, $auth, $bre_id) = @_;
2981 my $e = new_editor("authtoken" => $auth);
2982 return $e->die_event unless $e->checkauth;
2984 my $bre = $e->search_biblio_record_entry([
2985 {"id" => $bre_id, "deleted" => "f"}, {
2987 "flesh_fields" => {"bre" => [qw/creator editor owner/]}
2989 ]) or return $e->die_event;
2991 return undef unless @$bre;
2994 my $record = MARC::Record->new_from_xml($bre->marc);
2995 $client->respond($bre) if $record->field("85[3-5]");
2996 # XXX Is passing a regex to ->field() an abuse of MARC::Record ?
2998 my $sres = $e->search_serial_record_entry([
2999 {"record" => $bre_id, "deleted" => "f"}, {
3001 "flesh_fields" => {"sre" => [qw/creator editor owning_lib/]}
3003 ]) or return $e->die_event;
3007 foreach my $sre (@$sres) {
3008 $client->respond($sre) if
3009 MARC::Record->new_from_xml($sre->marc)->field("85[3-5]");
3015 __PACKAGE__->register_method(
3016 "method" => "create_scaps_from_marcxml",
3017 "api_name" => "open-ils.serial.caption_and_pattern.create_from_records",
3020 "desc" => "Create caption and pattern objects from 853-855 tags " .
3021 "in MARCXML documents",
3023 {"desc" => "Authtoken", "type" => "string"},
3024 {"desc" => "Subscription ID", "type" => "number"},
3025 {"desc" => "list of MARCXML documents as strings",
3029 "desc" => "Newly created caption and pattern objects",
3030 "type" => "object", "class" => "scap"
3035 sub create_scaps_from_marcxml {
3036 my ($self, $client, $auth, $sub_id, $docs) = @_;
3038 return undef unless ref $docs eq "ARRAY";
3040 my $e = new_editor("authtoken" => $auth, "xact" => 1);
3041 return $e->die_event unless $e->checkauth;
3043 # Retrieve the subscription just for perm checking (whether we can create
3044 # scaps at the owning lib).
3045 my $sub = $e->retrieve_serial_subscription($sub_id) or return $e->die_event;
3046 return $e->die_event unless
3047 $e->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $sub->owning_lib);
3049 foreach my $record (map { MARC::Record->new_from_xml($_) } @$docs) {
3050 foreach my $field ($record->field("85[3-5]")) {
3051 my $scap = new Fieldmapper::serial::caption_and_pattern;
3052 $scap->subscription($sub_id);
3053 $scap->type($MFHD_NAMES_BY_TAG{$field->tag});
3054 $scap->pattern_code(
3055 OpenSRF::Utils::JSON->perl2JSON(
3056 [ $field->indicator(1), $field->indicator(2),
3057 map { @$_ } $field->subfields ] # flattens nested array
3060 $e->create_serial_caption_and_pattern($scap) or
3061 return $e->die_event;
3062 $client->respond($e->data);
3066 $e->commit or return $e->die_event;