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');
1003 $item->status('Bindery');
1006 # check for types to trigger summary updates
1008 if (!ref $item->issuance) {
1009 my $scaps = $editor->search_serial_caption_and_pattern([{"+siss" => {"id" => $issuance_id}}, { "join" => {"siss" => {}} }]);
1010 $scap = $scaps->[0];
1011 } elsif (!ref $item->issuance->caption_and_pattern) {
1012 $scap = $editor->retrieve_serial_caption_and_pattern($item->issuance->caption_and_pattern);
1014 $scap = $editor->issuance->caption_and_pattern;
1016 if (!exists($found_types{$stream_id})) {
1017 $found_types{$stream_id} = {};
1019 $found_types{$stream_id}->{$scap->type} = 1;
1021 # create unit if needed
1022 if ($unit_id == -1 or (!$new_unit_id and $unit_id == -2)) { # create unit per item
1024 my $sdists = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
1025 $unit = _build_unit($editor, $sdists->[0], $mode, 0, $barcodes->{$item->id});
1026 # if _build_unit fails, $unit is an event, so return it
1027 if ($U->event_code($unit)) {
1029 $unit->{"note"} = "Item ID: " . $item->id;
1032 my $evt = _create_sunit($editor, $unit);
1033 return $evt if $evt;
1034 if ($unit_id == -2) {
1035 $new_unit_id = $unit->id;
1036 $unit_id = $new_unit_id;
1038 $unit_id = $unit->id;
1040 $item->unit($unit_id);
1042 # get unit with 'DEFAULT's and save unit and sdist for later use
1043 $unit = $editor->retrieve_serial_unit($unit->id);
1044 $unit_map{$unit_id} = $unit;
1045 $sdist_by_unit_id{$unit_id} = $sdists->[0];
1046 $sdist_by_stream_id{$stream_id} = $sdists->[0];
1047 } elsif ($unit_id == -2) { # create one unit for all '-2' items
1048 $unit_id = $new_unit_id;
1049 $item->unit($unit_id);
1052 $found_unit_ids{$unit_id} = 1;
1053 $found_stream_ids{$stream_id} = 1;
1055 # save the stream_id for this unit_id
1056 # TODO: prevent items from different streams in same unit? (perhaps in interface)
1057 $stream_ids_by_unit_id{$unit_id} = $stream_id;
1059 my $evt = _update_sitem($editor, undef, $item);
1060 return $evt if $evt;
1063 # deal with unit level labels
1064 foreach my $unit_id (keys %found_unit_ids) {
1066 # get all the needed issuances for unit
1067 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"unit" => $unit_id, "status" => ["Received", "Bindery"]}}, {"join" => {"sitem" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1068 #TODO: evt on search failure
1070 my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
1072 # special case for single formatted_part (may have summarized version)
1073 if (@$formatted_parts == 1) {
1074 #TODO: MFHD.pm should have a 'format_summary' method for this
1077 # retrieve and update unit contents
1081 # if we just created the unit, we will already have it and the distribution stored
1082 if (exists $unit_map{$unit_id}) {
1083 $sunit = $unit_map{$unit_id};
1084 $sdist = $sdist_by_unit_id{$unit_id};
1086 $sunit = $editor->retrieve_serial_unit($unit_id);
1087 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_ids_by_unit_id{$unit_id}}}, { "join" => {"sstr" => {}} }]);
1088 $sdist = $sdist->[0];
1091 $sunit->detailed_contents($sdist->unit_label_prefix . ' '
1092 . join(', ', @$formatted_parts) . ' '
1093 . $sdist->unit_label_suffix);
1095 $sunit->summary_contents($sunit->detailed_contents); #TODO: change this when real summary contents are available
1097 # create sort_key by left padding numbers to 6 digits
1098 my $sort_key = $sunit->detailed_contents;
1099 $sort_key =~ s/(\d+)/sprintf '%06d', $1/eg; # this may need improvement
1100 $sunit->sort_key($sort_key);
1102 if ($mode eq 'bind') {
1103 $sunit->status(2); # set to 'Bindery' status
1106 my $evt = _update_sunit($editor, undef, $sunit);
1107 return $evt if $evt;
1110 # cleanup 'dead' units (units which are now emptied of their items)
1111 my $dead_units = $editor->search_serial_unit([{'+sitem' => {'id' => undef}, 'deleted' => 'f'}, {'join' => {'sitem' => {'type' => 'left'}}}]);
1112 foreach my $unit (@$dead_units) {
1113 _delete_sunit($editor, undef, $unit);
1116 if ($mode eq 'receive') { # the summary holdings do not change when binding
1117 # deal with stream level summaries
1118 # summaries will be built from the "primary" stream only, that is, the stream with the lowest ID per distribution
1119 # (TODO: consider direct designation)
1120 my %primary_streams_by_sdist;
1121 my %streams_by_sdist;
1123 # see if we have primary streams, and if so, associate them with their distributions
1124 foreach my $stream_id (keys %found_stream_ids) {
1126 if (exists $sdist_by_stream_id{$stream_id}) {
1127 $sdist = $sdist_by_stream_id{$stream_id};
1129 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
1130 $sdist = $sdist->[0];
1133 if (!exists($streams_by_sdist{$sdist->id})) {
1134 $streams = $editor->search_serial_stream([{"distribution" => $sdist->id}, {"order_by" => {"sstr" => "id"}}]);
1135 $streams_by_sdist{$sdist->id} = $streams;
1137 $streams = $streams_by_sdist{$sdist->id};
1139 $primary_streams_by_sdist{$sdist->id} = $streams->[0] if ($stream_id == $streams->[0]->id);
1142 # retrieve and update summaries for each affected primary stream's distribution
1143 foreach my $sdist_id (keys %primary_streams_by_sdist) {
1144 my $stream = $primary_streams_by_sdist{$sdist_id};
1145 my $stream_id = $stream->id;
1146 # get all the needed issuances for stream
1147 # FIXME: search in Bindery/Bound/Not Published? as well as Received
1148 foreach my $type (keys %{$found_types{$stream_id}}) {
1149 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"stream" => $stream_id, "status" => "Received"}, "+scap" => {"type" => $type}}, {"join" => {"sitem" => {}, "scap" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1150 #TODO: evt on search failure
1152 my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
1154 # retrieve and update the generated_coverage of the summary
1155 my $search_method = "search_serial_${type}_summary";
1156 my $summary = $editor->$search_method([{"distribution" => $sdist_id}]);
1157 $summary = $summary->[0];
1158 $summary->generated_coverage(join(', ', @$formatted_parts));
1159 my $update_method = "update_serial_${type}_summary";
1160 return $editor->event unless $editor->$update_method($summary);
1166 return {'num_items' => scalar @$items, 'new_unit_id' => $new_unit_id};
1169 sub _find_or_create_call_number {
1170 my ($e, $lib, $cn_string, $record) = @_;
1172 my $existing = $e->search_asset_call_number({
1173 "owning_lib" => $lib,
1174 "label" => $cn_string,
1175 "record" => $record,
1177 }) or return $e->die_event;
1180 return $existing->[0]->id;
1182 return $e->die_event unless
1183 $e->allowed("CREATE_VOLUME", $lib);
1185 my $acn = new Fieldmapper::asset::call_number;
1187 $acn->creator($e->requestor->id);
1188 $acn->editor($e->requestor->id);
1189 $acn->record($record);
1190 $acn->label($cn_string);
1191 $acn->owning_lib($lib);
1193 $e->create_asset_call_number($acn) or return $e->die_event;
1194 return $e->data->id;
1198 sub _issuances_received {
1199 # XXX TODO: Add some caching or something. This is getting called
1200 # more often than it has to be.
1201 my ($e, $sitem) = @_;
1203 my $results = $e->json_query({
1204 "select" => {"sitem" => ["issuance"]},
1205 "from" => {"sitem" => {"sstr" => {}, "siss" => {}}},
1207 "+sstr" => {"distribution" => $sitem->stream->distribution->id},
1208 "+siss" => {"holding_type" => $sitem->issuance->holding_type},
1209 "+sitem" => {"date_received" => {"!=" => undef}}
1212 "siss" => {"date_published" => {"direction" => "asc"}}
1214 }) or return $e->die_event;
1216 my $uniq = +{map { $_->{"issuance"} => 1 } @$results};
1217 return [ map { $e->retrieve_serial_issuance($_) } keys %$uniq ];
1220 # XXX _prepare_unit_label() duplicates some code from unitize_items().
1221 # Hopefully we can unify code paths down the road.
1222 sub _prepare_unit_label {
1223 my ($e, $sunit, $sdist, $issuance) = @_;
1225 my ($mfhd, $formatted_parts) = _summarize_contents($e, [$issuance]);
1227 # special case for single formatted_part (may have summarized version)
1228 if (@$formatted_parts == 1) {
1229 #TODO: MFHD.pm should have a 'format_summary' method for this
1232 $sunit->detailed_contents(
1235 $sdist->unit_label_prefix,
1236 join(", ", @$formatted_parts),
1237 $sdist->unit_label_suffix
1241 # TODO: change this when real summary contents are available
1242 $sunit->summary_contents($sunit->detailed_contents);
1244 # Create sort_key by left padding numbers to 6 digits.
1245 (my $sort_key = $sunit->detailed_contents) =~
1246 s/(\d+)/sprintf '%06d', $1/eg;
1247 $sunit->sort_key($sort_key);
1250 # XXX duplicates a block of code from unitize_items(). Once I fully understand
1251 # what's going on and I'm sure it's working right, I'd like to have
1252 # unitize_items() just use this, keeping the logic in one place.
1253 sub _prepare_summaries {
1254 my ($e, $sitem, $issuances) = @_;
1256 my $dist_id = $sitem->stream->distribution->id;
1257 my $type = $sitem->issuance->holding_type;
1259 # Make sure @$issuances contains the new issuance from sitem.
1260 unless (grep { $_->id == $sitem->issuance->id } @$issuances) {
1261 push @$issuances, $sitem->issuance;
1264 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances);
1266 my $search_method = "search_serial_${type}_summary";
1267 my $summary = $e->$search_method([{"distribution" => $dist_id}]);
1269 my $cu_method = "update";
1272 $summary = $summary->[0];
1274 my $class = "Fieldmapper::serial::${type}_summary";
1275 $summary = $class->new;
1276 $summary->distribution($dist_id);
1277 $cu_method = "create";
1280 $summary->generated_coverage(join(", ", @$formatted_parts));
1281 my $method = "${cu_method}_serial_${type}_summary";
1282 return $e->die_event unless $e->$method($summary);
1285 sub _unit_by_iss_and_str {
1286 my ($e, $issuance, $stream) = @_;
1288 my $unit = $e->json_query({
1289 "select" => {"sunit" => ["id"]},
1290 "from" => {"sitem" => {"sunit" => {}}},
1293 "issuance" => $issuance->id,
1294 "stream" => $stream->id
1297 }) or return $e->die_event;
1298 return 0 if not @$unit;
1300 $e->retrieve_serial_unit($unit->[0]->{"id"}) or $e->die_event;
1303 sub move_previous_unit {
1304 my ($e, $prev_iss, $curr_item, $new_loc) = @_;
1306 my $prev_unit = _unit_by_iss_and_str($e,$prev_iss,$curr_item->stream);
1307 return $prev_unit if defined $U->event_code($prev_unit);
1308 return 0 if not $prev_unit;
1310 if ($prev_unit->location != $new_loc) {
1311 $prev_unit->location($new_loc);
1312 $e->update_serial_unit($prev_unit) or return $e->die_event;
1317 # _previous_issuance() assumes $existing is an ordered array
1318 sub _previous_issuance {
1319 my ($existing, $issuance) = @_;
1321 my $last = $existing->[-1];
1322 return undef unless $last;
1323 return ($last->id == $issuance->id ? $existing->[-2] : $last);
1326 __PACKAGE__->register_method(
1327 "method" => "receive_items_one_unit_per",
1328 "api_name" => "open-ils.serial.receive_items.one_unit_per",
1333 "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",
1337 "desc" => "authtoken",
1342 "desc" => "array of serial items, possibly fleshed with units and definitely fleshed with stream->distribution",
1347 "desc" => "id of bib record these items are associated with
1348 (XXX could/should be derived from items)",
1353 "desc" => "The item ID for each item successfully received",
1359 sub receive_items_one_unit_per {
1360 # XXX This function may be temporary, as it does some of what
1361 # unitize_items() does, just in a different way.
1362 my ($self, $client, $auth, $items, $record) = @_;
1364 my $e = new_editor("authtoken" => $auth, "xact" => 1);
1365 return $e->die_event unless $e->checkauth;
1366 return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
1368 my $prev_loc_setting_map = {};
1369 my $user_id = $e->requestor->id;
1371 # Get a list of all the non-virtual field names in a serial::unit for
1372 # merging given unit objects with template-built units later.
1373 # XXX move this somewhere global so it isn't re-run all the time
1374 my $all_unit_fields =
1375 $Fieldmapper::fieldmap->{"Fieldmapper::serial::unit"}->{"fields"};
1376 my @real_unit_fields = grep {
1377 not $all_unit_fields->{$_}->{"virtual"}
1378 } keys %$all_unit_fields;
1380 foreach my $item (@$items) {
1381 # Note that we expect a certain fleshing on the items we're getting.
1382 my $sdist = $item->stream->distribution;
1384 # Fetch a list of issuances with received copies already existing
1385 # on this distribution (and with the same holding type on the
1386 # issuance). This will be used in up to two places: once when building
1387 # a summary, once when changing the copy location of the previous
1389 my $issuances_received = _issuances_received($e, $item);
1390 if ($U->event_code($issuances_received)) {
1392 return $issuances_received;
1395 # Find out if we need to to deal with previous copy location changing.
1396 my $ou = $sdist->holding_lib->id;
1397 unless (exists $prev_loc_setting_map->{$ou}) {
1398 $prev_loc_setting_map->{$ou} = $U->ou_ancestor_setting_value(
1399 $ou, "serial.prev_issuance_copy_location", $e
1403 # If there is a previous copy location setting, we need the previous
1404 # issuance, from which we can in turn look up the item attached to the
1405 # same stream we're on now.
1406 if ($prev_loc_setting_map->{$ou}) {
1408 _previous_issuance($issuances_received, $item->issuance)) {
1410 # Now we can change the copy location of the previous unit,
1412 return $e->event if defined $U->event_code(
1414 $e, $prev_iss, $item, $prev_loc_setting_map->{$ou}
1420 # Create unit if given by user
1421 if (ref $item->unit) {
1422 # detach from the item, as we need to create separately
1423 my $user_unit = $item->unit;
1425 # get a unit based on associated template
1426 my $template_unit = _build_unit($e, $sdist, "receive", 1);
1427 if ($U->event_code($template_unit)) {
1429 $template_unit->{"note"} = "Item ID: " . $item->id;
1430 return $template_unit;
1433 # merge built unit with provided unit from user
1434 foreach (@real_unit_fields) {
1435 unless ($user_unit->$_) {
1436 $user_unit->$_($template_unit->$_);
1440 # Treat call number specially: the provided value from the
1441 # user will really be a string.
1442 if ($user_unit->call_number) {
1443 my $real_cn = _find_or_create_call_number(
1444 $e, $sdist->holding_lib->id,
1445 $user_unit->call_number, $record
1448 if ($U->event_code($real_cn)) {
1452 $user_unit->call_number($real_cn);
1456 my $evt = _prepare_unit_label(
1457 $e, $user_unit, $sdist, $item->issuance
1459 if ($U->event_code($evt)) {
1464 # create/update summary objects related to this distribution
1465 $evt = _prepare_summaries($e, $item, $issuances_received);
1466 if ($U->event_code($evt)) {
1471 # set the incontrovertibles on the unit
1472 $user_unit->edit_date("now");
1473 $user_unit->create_date("now");
1474 $user_unit->editor($user_id);
1475 $user_unit->creator($user_id);
1477 return $e->die_event unless $e->create_serial_unit($user_unit);
1479 # save reference to new unit
1480 $item->unit($e->data->id);
1483 # Create notes if given by user
1484 if (ref($item->notes) and @{$item->notes}) {
1485 foreach my $note (@{$item->notes}) {
1486 $note->creator($user_id);
1487 $note->create_date("now");
1489 return $e->die_event unless $e->create_serial_item_note($note);
1492 $item->clear_notes; # They're saved; we no longer want them here.
1495 # Set the incontrovertibles on the item
1496 $item->status("Received");
1497 $item->date_received("now");
1498 $item->edit_date("now");
1499 $item->editor($user_id);
1501 return $e->die_event unless $e->update_serial_item($item);
1503 # send client a response
1504 $client->respond($item->id);
1507 $e->commit or return $e->die_event;
1515 my $skip_call_number = shift;
1516 my $barcode = shift;
1518 my $attr = $mode . '_unit_template';
1519 my $template = $editor->retrieve_asset_copy_template($sdist->$attr) or
1520 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_COPY_TEMPLATE");
1522 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 );
1524 my $unit = new Fieldmapper::serial::unit;
1525 foreach my $part (@parts) {
1526 my $value = $template->$part;
1527 next if !defined($value);
1528 $unit->$part($value);
1531 # ignore circ_lib in template, set to distribution holding_lib
1532 $unit->circ_lib($sdist->holding_lib);
1533 $unit->creator($editor->requestor->id);
1534 $unit->editor($editor->requestor->id);
1536 unless ($skip_call_number) {
1537 $attr = $mode . '_call_number';
1538 my $cn = $sdist->$attr or
1539 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_CALL_NUMBER");
1541 $unit->call_number($cn);
1545 $unit->barcode($barcode);
1547 $unit->barcode('AUTO');
1549 $unit->sort_key('');
1550 $unit->summary_contents('');
1551 $unit->detailed_contents('');
1557 sub _summarize_contents {
1559 my $issuances = shift;
1561 # create MFHD record
1562 my $mfhd = MFHD->new(MARC::Record->new());
1565 my @scap_fields_ordered;
1568 foreach my $issuance (@$issuances) {
1569 my $scap_id = $issuance->caption_and_pattern;
1570 next if (!$scap_id); # skip issuances with no caption/pattern
1574 # if this is the first appearance of this scap, retrieve it and add it to the temporary record
1575 if (!exists $scaps{$issuance->caption_and_pattern}) {
1576 $scaps{$scap_id} = $editor->retrieve_serial_caption_and_pattern($scap_id);
1577 $scap = $scaps{$scap_id};
1578 $scap_field = _revive_caption($scap);
1579 $scap_fields{$scap_id} = $scap_field;
1580 push(@scap_fields_ordered, $scap_field);
1581 $scap_field->update('8' => $link_id);
1582 $mfhd->append_fields($scap_field);
1585 $scap = $scaps{$scap_id};
1586 $scap_field = $scap_fields{$scap_id};
1589 $mfhd->append_fields(_revive_holding($issuance->holding_code, $scap_field, $seqno));
1593 my @formatted_parts;
1594 foreach my $scap_field (@scap_fields_ordered) { #TODO: use generic MFHD "summarize" method, once available
1595 my @updated_holdings = $mfhd->get_compressed_holdings($scap_field);
1596 foreach my $holding (@updated_holdings) {
1597 push(@formatted_parts, $holding->format);
1601 return ($mfhd, \@formatted_parts);
1604 ##########################################################################
1607 __PACKAGE__->register_method(
1608 method => 'fetch_notes',
1609 api_name => 'open-ils.serial.item_note.retrieve.all',
1611 Returns an array of copy note objects.
1612 @param args A named hash of parameters including:
1613 authtoken : Required if viewing non-public notes
1614 item_id : The id of the item whose notes we want to retrieve
1615 pub : True if all the caller wants are public notes
1616 @return An array of note objects
1620 __PACKAGE__->register_method(
1621 method => 'fetch_notes',
1622 api_name => 'open-ils.serial.subscription_note.retrieve.all',
1624 Returns an array of copy note objects.
1625 @param args A named hash of parameters including:
1626 authtoken : Required if viewing non-public notes
1627 subscription_id : The id of the item whose notes we want to retrieve
1628 pub : True if all the caller wants are public notes
1629 @return An array of note objects
1633 __PACKAGE__->register_method(
1634 method => 'fetch_notes',
1635 api_name => 'open-ils.serial.distribution_note.retrieve.all',
1637 Returns an array of copy note objects.
1638 @param args A named hash of parameters including:
1639 authtoken : Required if viewing non-public notes
1640 distribution_id : The id of the item whose notes we want to retrieve
1641 pub : True if all the caller wants are public notes
1642 @return An array of note objects
1646 # TODO: revisit this method to consider replacing cstore direct calls
1648 my( $self, $connection, $args ) = @_;
1650 $self->api_name =~ /serial\.(\w*)_note/;
1653 my $id = $$args{object_id};
1654 my $authtoken = $$args{authtoken};
1658 return $U->cstorereq(
1659 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic',
1660 { $type => $id, pub => 't' } );
1662 # FIXME: restore perm check
1663 # ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
1664 # return $evt if $evt;
1665 return $U->cstorereq(
1666 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic', {$type => $id} );
1672 __PACKAGE__->register_method(
1673 method => 'create_note',
1674 api_name => 'open-ils.serial.item_note.create',
1676 Creates a new item note
1677 @param authtoken The login session key
1678 @param note The note object to create
1679 @return The id of the new note object
1683 __PACKAGE__->register_method(
1684 method => 'create_note',
1685 api_name => 'open-ils.serial.subscription_note.create',
1687 Creates a new subscription note
1688 @param authtoken The login session key
1689 @param note The note object to create
1690 @return The id of the new note object
1694 __PACKAGE__->register_method(
1695 method => 'create_note',
1696 api_name => 'open-ils.serial.distribution_note.create',
1698 Creates a new distribution note
1699 @param authtoken The login session key
1700 @param note The note object to create
1701 @return The id of the new note object
1706 my( $self, $connection, $authtoken, $note ) = @_;
1708 $self->api_name =~ /serial\.(\w*)_note/;
1711 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1712 return $e->event unless $e->checkauth;
1714 # FIXME: restore permission support
1715 # my $item = $e->retrieve_serial_item(
1721 # return $e->event unless
1722 # $e->allowed('CREATE_COPY_NOTE', $item->call_number->owning_lib);
1724 $note->create_date('now');
1725 $note->creator($e->requestor->id);
1726 $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
1729 my $method = "create_serial_${type}_note";
1730 $e->$method($note) or return $e->event;
1735 __PACKAGE__->register_method(
1736 method => 'delete_note',
1737 api_name => 'open-ils.serial.item_note.delete',
1739 Deletes an existing item note
1740 @param authtoken The login session key
1741 @param noteid The id of the note to delete
1742 @return 1 on success - Event otherwise.
1746 __PACKAGE__->register_method(
1747 method => 'delete_note',
1748 api_name => 'open-ils.serial.subscription_note.delete',
1750 Deletes an existing subscription note
1751 @param authtoken The login session key
1752 @param noteid The id of the note to delete
1753 @return 1 on success - Event otherwise.
1757 __PACKAGE__->register_method(
1758 method => 'delete_note',
1759 api_name => 'open-ils.serial.distribution_note.delete',
1761 Deletes an existing distribution note
1762 @param authtoken The login session key
1763 @param noteid The id of the note to delete
1764 @return 1 on success - Event otherwise.
1769 my( $self, $conn, $authtoken, $noteid ) = @_;
1771 $self->api_name =~ /serial\.(\w*)_note/;
1774 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1775 return $e->die_event unless $e->checkauth;
1777 my $method = "retrieve_serial_${type}_note";
1778 my $note = $e->$method([
1780 ]) or return $e->die_event;
1782 # FIXME: restore permissions check
1783 # if( $note->creator ne $e->requestor->id ) {
1784 # return $e->die_event unless
1785 # $e->allowed('DELETE_COPY_NOTE', $note->item->call_number->owning_lib);
1788 $method = "delete_serial_${type}_note";
1789 $e->$method($note) or return $e->die_event;
1795 ##########################################################################
1796 # subscription methods
1798 __PACKAGE__->register_method(
1799 method => 'fleshed_ssub_alter',
1800 api_name => 'open-ils.serial.subscription.fleshed.batch.update',
1804 desc => 'Receives an array of one or more subscriptions and updates the database as needed',
1806 name => 'authtoken',
1807 desc => 'Authtoken for current user session',
1811 name => 'subscriptions',
1812 desc => 'Array of fleshed subscriptions',
1818 desc => 'Returns 1 if successful, event if failed',
1824 sub fleshed_ssub_alter {
1825 my( $self, $conn, $auth, $ssubs ) = @_;
1826 return 1 unless ref $ssubs;
1827 my( $reqr, $evt ) = $U->checkses($auth);
1828 return $evt if $evt;
1829 my $editor = new_editor(requestor => $reqr, xact => 1);
1830 my $override = $self->api_name =~ /override/;
1832 # TODO: permission check
1833 # return $editor->event unless
1834 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
1836 for my $ssub (@$ssubs) {
1838 my $ssubid = $ssub->id;
1840 if( $ssub->isdeleted ) {
1841 $evt = _delete_ssub( $editor, $override, $ssub);
1842 } elsif( $ssub->isnew ) {
1843 _cleanse_dates($ssub, ['start_date','end_date']);
1844 $evt = _create_ssub( $editor, $ssub );
1846 _cleanse_dates($ssub, ['start_date','end_date']);
1847 $evt = _update_ssub( $editor, $override, $ssub );
1852 $logger->info("fleshed subscription-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
1856 $logger->debug("subscription-alter: done updating subscription batch");
1858 $logger->info("fleshed subscription-alter successfully updated ".scalar(@$ssubs)." subscriptions");
1863 my ($editor, $override, $ssub) = @_;
1864 $logger->info("subscription-alter: delete subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1865 my $sdists = $editor->search_serial_distribution(
1866 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1867 my $cps = $editor->search_serial_caption_and_pattern(
1868 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1869 my $sisses = $editor->search_serial_issuance(
1870 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1871 return OpenILS::Event->new(
1872 'SERIAL_SUBSCRIPTION_NOT_EMPTY', payload => $ssub->id ) if (@$sdists or @$cps or @$sisses);
1874 return $editor->event unless $editor->delete_serial_subscription($ssub);
1879 my ($editor, $ssub) = @_;
1881 $logger->info("subscription-alter: new subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1882 return $editor->event unless $editor->create_serial_subscription($ssub);
1887 my ($editor, $override, $ssub) = @_;
1889 $logger->info("subscription-alter: retrieving subscription ".$ssub->id);
1890 my $orig_ssub = $editor->retrieve_serial_subscription($ssub->id);
1892 $logger->info("subscription-alter: original subscription ".OpenSRF::Utils::JSON->perl2JSON($orig_ssub));
1893 $logger->info("subscription-alter: updated subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1894 return $editor->event unless $editor->update_serial_subscription($ssub);
1898 __PACKAGE__->register_method(
1899 method => "fleshed_serial_subscription_retrieve_batch",
1901 api_name => "open-ils.serial.subscription.fleshed.batch.retrieve"
1904 sub fleshed_serial_subscription_retrieve_batch {
1905 my( $self, $client, $ids ) = @_;
1906 # FIXME: permissions?
1907 $logger->info("Fetching fleshed subscriptions @$ids");
1908 return $U->cstorereq(
1909 "open-ils.cstore.direct.serial.subscription.search.atomic",
1912 flesh_fields => {ssub => [ qw/owning_lib notes/ ]}
1916 __PACKAGE__->register_method(
1917 method => "retrieve_sub_tree",
1919 api_name => "open-ils.serial.subscription_tree.retrieve"
1922 __PACKAGE__->register_method(
1923 method => "retrieve_sub_tree",
1924 api_name => "open-ils.serial.subscription_tree.global.retrieve"
1927 sub retrieve_sub_tree {
1929 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
1931 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
1935 # TODO: permission support
1936 if(!@org_ids and $user_session) {
1938 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
1939 @org_ids = ($user_obj->home_ou);
1942 if( $self->api_name =~ /global/ ) {
1943 return _build_subs_list( { record_entry => $docid } ); # TODO: filter for !deleted, or active?
1948 for my $orgid (@org_ids) {
1949 my $subs = _build_subs_list(
1950 { record_entry => $docid, owning_lib => $orgid } );# TODO: filter for !deleted, or active?
1951 push( @all_subs, @$subs );
1960 sub _build_subs_list {
1961 my $search_hash = shift;
1963 #$search_hash->{deleted} = 'f';
1964 my $e = new_editor();
1966 my $subs = $e->search_serial_subscription([$search_hash, { 'order_by' => {'ssub' => 'id'} }]);
1970 for my $sub (@$subs) {
1972 # TODO: filter on !deleted?
1973 my $dists = $e->search_serial_distribution(
1974 [{ subscription => $sub->id }, { 'order_by' => {'sdist' => 'label'} }]
1977 #$dists = [ sort { $a->label cmp $b->label } @$dists ];
1979 $sub->distributions($dists);
1981 # TODO: filter on !deleted?
1982 my $issuances = $e->search_serial_issuance(
1983 [{ subscription => $sub->id }, { 'order_by' => {'siss' => 'label'} }]
1986 #$issuances = [ sort { $a->label cmp $b->label } @$issuances ];
1987 $sub->issuances($issuances);
1989 # TODO: filter on !deleted?
1990 my $scaps = $e->search_serial_caption_and_pattern(
1991 [{ subscription => $sub->id }, { 'order_by' => {'scap' => 'id'} }]
1994 #$scaps = [ sort { $a->id cmp $b->id } @$scaps ];
1995 $sub->scaps($scaps);
1996 push( @built_subs, $sub );
1999 return \@built_subs;
2003 __PACKAGE__->register_method(
2004 method => "subscription_orgs_for_title",
2006 api_name => "open-ils.serial.subscription.retrieve_orgs_by_title"
2009 sub subscription_orgs_for_title {
2010 my( $self, $client, $record_id ) = @_;
2012 my $subs = $U->simple_scalar_request(
2014 "open-ils.cstore.direct.serial.subscription.search.atomic",
2015 { record_entry => $record_id }); # TODO: filter on !deleted?
2017 my $orgs = { map {$_->owning_lib => 1 } @$subs };
2018 return [ keys %$orgs ];
2022 ##########################################################################
2023 # distribution methods
2025 __PACKAGE__->register_method(
2026 method => 'fleshed_sdist_alter',
2027 api_name => 'open-ils.serial.distribution.fleshed.batch.update',
2031 desc => 'Receives an array of one or more distributions and updates the database as needed',
2033 name => 'authtoken',
2034 desc => 'Authtoken for current user session',
2038 name => 'distributions',
2039 desc => 'Array of fleshed distributions',
2045 desc => 'Returns 1 if successful, event if failed',
2051 sub fleshed_sdist_alter {
2052 my( $self, $conn, $auth, $sdists ) = @_;
2053 return 1 unless ref $sdists;
2054 my( $reqr, $evt ) = $U->checkses($auth);
2055 return $evt if $evt;
2056 my $editor = new_editor(requestor => $reqr, xact => 1);
2057 my $override = $self->api_name =~ /override/;
2059 # TODO: permission check
2060 # return $editor->event unless
2061 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2063 for my $sdist (@$sdists) {
2064 my $sdistid = $sdist->id;
2066 if( $sdist->isdeleted ) {
2067 $evt = _delete_sdist( $editor, $override, $sdist);
2068 } elsif( $sdist->isnew ) {
2069 $evt = _create_sdist( $editor, $sdist );
2071 $evt = _update_sdist( $editor, $override, $sdist );
2076 $logger->info("fleshed distribution-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2080 $logger->debug("distribution-alter: done updating distribution batch");
2082 $logger->info("fleshed distribution-alter successfully updated ".scalar(@$sdists)." distributions");
2087 my ($editor, $override, $sdist) = @_;
2088 $logger->info("distribution-alter: delete distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2089 return $editor->event unless $editor->delete_serial_distribution($sdist);
2094 my ($editor, $sdist) = @_;
2096 $logger->info("distribution-alter: new distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2097 return $editor->event unless $editor->create_serial_distribution($sdist);
2099 # create summaries too
2100 my $summary = new Fieldmapper::serial::basic_summary;
2101 $summary->distribution($sdist->id);
2102 $summary->generated_coverage('');
2103 return $editor->event unless $editor->create_serial_basic_summary($summary);
2104 $summary = new Fieldmapper::serial::supplement_summary;
2105 $summary->distribution($sdist->id);
2106 $summary->generated_coverage('');
2107 return $editor->event unless $editor->create_serial_supplement_summary($summary);
2108 $summary = new Fieldmapper::serial::index_summary;
2109 $summary->distribution($sdist->id);
2110 $summary->generated_coverage('');
2111 return $editor->event unless $editor->create_serial_index_summary($summary);
2113 # create a starter stream (TODO: reconsider this)
2114 my $stream = new Fieldmapper::serial::stream;
2115 $stream->distribution($sdist->id);
2116 return $editor->event unless $editor->create_serial_stream($stream);
2122 my ($editor, $override, $sdist) = @_;
2124 $logger->info("distribution-alter: retrieving distribution ".$sdist->id);
2125 my $orig_sdist = $editor->retrieve_serial_distribution($sdist->id);
2127 $logger->info("distribution-alter: original distribution ".OpenSRF::Utils::JSON->perl2JSON($orig_sdist));
2128 $logger->info("distribution-alter: updated distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2129 return $editor->event unless $editor->update_serial_distribution($sdist);
2133 __PACKAGE__->register_method(
2134 method => "fleshed_serial_distribution_retrieve_batch",
2136 api_name => "open-ils.serial.distribution.fleshed.batch.retrieve"
2139 sub fleshed_serial_distribution_retrieve_batch {
2140 my( $self, $client, $ids ) = @_;
2141 # FIXME: permissions?
2142 $logger->info("Fetching fleshed distributions @$ids");
2143 return $U->cstorereq(
2144 "open-ils.cstore.direct.serial.distribution.search.atomic",
2147 flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams / ]}
2151 __PACKAGE__->register_method(
2152 method => "retrieve_dist_tree",
2154 api_name => "open-ils.serial.distribution_tree.retrieve"
2157 __PACKAGE__->register_method(
2158 method => "retrieve_dist_tree",
2159 api_name => "open-ils.serial.distribution_tree.global.retrieve"
2162 sub retrieve_dist_tree {
2163 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2165 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2169 # TODO: permission support
2170 if(!@org_ids and $user_session) {
2172 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2173 @org_ids = ($user_obj->home_ou);
2176 my $e = new_editor();
2178 if( $self->api_name =~ /global/ ) {
2179 return $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }},
2181 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 / ]},
2182 order_by => {'sdist' => 'id'},
2183 'join' => {'ssub' => {}}
2185 ]); # TODO: filter for !deleted?
2189 for my $orgid (@org_ids) {
2190 my $dists = $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }, holding_lib => $orgid},
2192 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 / ]},
2193 order_by => {'sdist' => 'id'},
2194 'join' => {'ssub' => {}}
2196 ]); # TODO: filter for !deleted?
2197 push( @all_dists, @$dists ) if $dists;
2207 __PACKAGE__->register_method(
2208 method => "distribution_orgs_for_title",
2210 api_name => "open-ils.serial.distribution.retrieve_orgs_by_title"
2213 sub distribution_orgs_for_title {
2214 my( $self, $client, $record_id ) = @_;
2216 my $dists = $U->cstorereq(
2217 "open-ils.cstore.direct.serial.distribution.search.atomic",
2218 { '+ssub' => { record_entry => $record_id } },
2219 { 'join' => {'ssub' => {}} }); # TODO: filter on !deleted?
2221 my $orgs = { map {$_->holding_lib => 1 } @$dists };
2222 return [ keys %$orgs ];
2226 ##########################################################################
2227 # caption and pattern methods
2229 __PACKAGE__->register_method(
2230 method => 'scap_alter',
2231 api_name => 'open-ils.serial.caption_and_pattern.batch.update',
2235 desc => 'Receives an array of one or more caption and patterns and updates the database as needed',
2237 name => 'authtoken',
2238 desc => 'Authtoken for current user session',
2243 desc => 'Array of caption and patterns',
2249 desc => 'Returns 1 if successful, event if failed',
2256 my( $self, $conn, $auth, $scaps ) = @_;
2257 return 1 unless ref $scaps;
2258 my( $reqr, $evt ) = $U->checkses($auth);
2259 return $evt if $evt;
2260 my $editor = new_editor(requestor => $reqr, xact => 1);
2261 my $override = $self->api_name =~ /override/;
2263 # TODO: permission check
2264 # return $editor->event unless
2265 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2267 for my $scap (@$scaps) {
2268 my $scapid = $scap->id;
2270 if( $scap->isdeleted ) {
2271 $evt = _delete_scap( $editor, $override, $scap);
2272 } elsif( $scap->isnew ) {
2273 $evt = _create_scap( $editor, $scap );
2275 $evt = _update_scap( $editor, $override, $scap );
2280 $logger->info("caption_and_pattern-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2284 $logger->debug("caption_and_pattern-alter: done updating caption_and_pattern batch");
2286 $logger->info("caption_and_pattern-alter successfully updated ".scalar(@$scaps)." caption_and_patterns");
2291 my ($editor, $override, $scap) = @_;
2292 $logger->info("caption_and_pattern-alter: delete caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2293 my $sisses = $editor->search_serial_issuance(
2294 { caption_and_pattern => $scap->id }, { limit => 1 } ); #TODO: 'deleted' support?
2295 return OpenILS::Event->new(
2296 'SERIAL_CAPTION_AND_PATTERN_HAS_ISSUANCES', payload => $scap->id ) if (@$sisses);
2298 return $editor->event unless $editor->delete_serial_caption_and_pattern($scap);
2303 my ($editor, $scap) = @_;
2305 $logger->info("caption_and_pattern-alter: new caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2306 return $editor->event unless $editor->create_serial_caption_and_pattern($scap);
2311 my ($editor, $override, $scap) = @_;
2313 $logger->info("caption_and_pattern-alter: retrieving caption_and_pattern ".$scap->id);
2314 my $orig_scap = $editor->retrieve_serial_caption_and_pattern($scap->id);
2316 $logger->info("caption_and_pattern-alter: original caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($orig_scap));
2317 $logger->info("caption_and_pattern-alter: updated caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2318 return $editor->event unless $editor->update_serial_caption_and_pattern($scap);
2322 __PACKAGE__->register_method(
2323 method => "serial_caption_and_pattern_retrieve_batch",
2325 api_name => "open-ils.serial.caption_and_pattern.batch.retrieve"
2328 sub serial_caption_and_pattern_retrieve_batch {
2329 my( $self, $client, $ids ) = @_;
2330 $logger->info("Fetching caption_and_patterns @$ids");
2331 return $U->cstorereq(
2332 "open-ils.cstore.direct.serial.caption_and_pattern.search.atomic",
2337 ##########################################################################
2340 __PACKAGE__->register_method(
2341 method => 'sstr_alter',
2342 api_name => 'open-ils.serial.stream.batch.update',
2346 desc => 'Receives an array of one or more streams and updates the database as needed',
2348 name => 'authtoken',
2349 desc => 'Authtoken for current user session',
2354 desc => 'Array of streams',
2360 desc => 'Returns 1 if successful, event if failed',
2367 my( $self, $conn, $auth, $sstrs ) = @_;
2368 return 1 unless ref $sstrs;
2369 my( $reqr, $evt ) = $U->checkses($auth);
2370 return $evt if $evt;
2371 my $editor = new_editor(requestor => $reqr, xact => 1);
2372 my $override = $self->api_name =~ /override/;
2374 # TODO: permission check
2375 # return $editor->event unless
2376 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2378 for my $sstr (@$sstrs) {
2379 my $sstrid = $sstr->id;
2381 if( $sstr->isdeleted ) {
2382 $evt = _delete_sstr( $editor, $override, $sstr);
2383 } elsif( $sstr->isnew ) {
2384 $evt = _create_sstr( $editor, $sstr );
2386 $evt = _update_sstr( $editor, $override, $sstr );
2391 $logger->info("stream-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2395 $logger->debug("stream-alter: done updating stream batch");
2397 $logger->info("stream-alter successfully updated ".scalar(@$sstrs)." streams");
2402 my ($editor, $override, $sstr) = @_;
2403 $logger->info("stream-alter: delete stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2404 my $sitems = $editor->search_serial_item(
2405 { stream => $sstr->id }, { limit => 1 } ); #TODO: 'deleted' support?
2406 return OpenILS::Event->new(
2407 'SERIAL_STREAM_HAS_ITEMS', payload => $sstr->id ) if (@$sitems);
2409 return $editor->event unless $editor->delete_serial_stream($sstr);
2414 my ($editor, $sstr) = @_;
2416 $logger->info("stream-alter: new stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2417 return $editor->event unless $editor->create_serial_stream($sstr);
2422 my ($editor, $override, $sstr) = @_;
2424 $logger->info("stream-alter: retrieving stream ".$sstr->id);
2425 my $orig_sstr = $editor->retrieve_serial_stream($sstr->id);
2427 $logger->info("stream-alter: original stream ".OpenSRF::Utils::JSON->perl2JSON($orig_sstr));
2428 $logger->info("stream-alter: updated stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2429 return $editor->event unless $editor->update_serial_stream($sstr);
2433 __PACKAGE__->register_method(
2434 method => "serial_stream_retrieve_batch",
2436 api_name => "open-ils.serial.stream.batch.retrieve"
2439 sub serial_stream_retrieve_batch {
2440 my( $self, $client, $ids ) = @_;
2441 $logger->info("Fetching streams @$ids");
2442 return $U->cstorereq(
2443 "open-ils.cstore.direct.serial.stream.search.atomic",
2449 ##########################################################################
2452 __PACKAGE__->register_method(
2453 method => 'sum_alter',
2454 api_name => 'open-ils.serial.basic_summary.batch.update',
2458 desc => 'Receives an array of one or more summaries and updates the database as needed',
2460 name => 'authtoken',
2461 desc => 'Authtoken for current user session',
2466 desc => 'Array of basic summaries',
2472 desc => 'Returns 1 if successful, event if failed',
2478 __PACKAGE__->register_method(
2479 method => 'sum_alter',
2480 api_name => 'open-ils.serial.supplement_summary.batch.update',
2484 desc => 'Receives an array of one or more summaries and updates the database as needed',
2486 name => 'authtoken',
2487 desc => 'Authtoken for current user session',
2492 desc => 'Array of supplement summaries',
2498 desc => 'Returns 1 if successful, event if failed',
2504 __PACKAGE__->register_method(
2505 method => 'sum_alter',
2506 api_name => 'open-ils.serial.index_summary.batch.update',
2510 desc => 'Receives an array of one or more summaries and updates the database as needed',
2512 name => 'authtoken',
2513 desc => 'Authtoken for current user session',
2518 desc => 'Array of index summaries',
2524 desc => 'Returns 1 if successful, event if failed',
2531 my( $self, $conn, $auth, $sums ) = @_;
2532 return 1 unless ref $sums;
2534 $self->api_name =~ /serial\.(\w*)_summary/;
2537 my( $reqr, $evt ) = $U->checkses($auth);
2538 return $evt if $evt;
2539 my $editor = new_editor(requestor => $reqr, xact => 1);
2540 my $override = $self->api_name =~ /override/;
2542 # TODO: permission check
2543 # return $editor->event unless
2544 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2546 for my $sum (@$sums) {
2547 my $sumid = $sum->id;
2549 # XXX: (for now, at least) summaries should be created/deleted by the distribution functions
2550 if( $sum->isdeleted ) {
2551 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2552 } elsif( $sum->isnew ) {
2553 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2555 $evt = _update_sum( $editor, $override, $sum, $type );
2560 $logger->info("${type}_summary-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2564 $logger->debug("${type}_summary-alter: done updating ${type}_summary batch");
2566 $logger->info("${type}_summary-alter successfully updated ".scalar(@$sums)." ${type}_summaries");
2571 my ($editor, $override, $sum, $type) = @_;
2573 $logger->info("${type}_summary-alter: retrieving ${type}_summary ".$sum->id);
2574 my $retrieve_method = "retrieve_serial_${type}_summary";
2575 my $orig_sum = $editor->$retrieve_method($sum->id);
2577 $logger->info("${type}_summary-alter: original ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($orig_sum));
2578 $logger->info("${type}_summary-alter: updated ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($sum));
2579 my $update_method = "update_serial_${type}_summary";
2580 return $editor->event unless $editor->$update_method($sum);
2584 __PACKAGE__->register_method(
2585 method => "serial_summary_retrieve_batch",
2587 api_name => "open-ils.serial.basic_summary.batch.retrieve"
2590 __PACKAGE__->register_method(
2591 method => "serial_summary_retrieve_batch",
2593 api_name => "open-ils.serial.supplement_summary.batch.retrieve"
2596 __PACKAGE__->register_method(
2597 method => "serial_summary_retrieve_batch",
2599 api_name => "open-ils.serial.index_summary.batch.retrieve"
2602 sub serial_summary_retrieve_batch {
2603 my( $self, $client, $ids ) = @_;
2605 $self->api_name =~ /serial\.(\w*)_summary/;
2608 $logger->info("Fetching ${type}_summaries @$ids");
2609 return $U->cstorereq(
2610 "open-ils.cstore.direct.serial.".$type."_summary.search.atomic",
2616 ##########################################################################
2619 __PACKAGE__->register_method(
2620 "method" => "bre_by_identifier",
2621 "api_name" => "open-ils.serial.biblio.record_entry.by_identifier",
2624 "desc" => "Find instances of biblio.record_entry given a search token" .
2625 " that could be a value for any identifier defined in " .
2626 "config.metabib_field",
2628 {"desc" => "Search token", "type" => "string"},
2629 {"desc" => "Options: require_subscriptions, add_mvr, is_actual_id" .
2630 " (all boolean)", "type" => "object"}
2633 "desc" => "Any matching BREs, or if the add_mvr option is true, " .
2634 "objects with a 'bre' key/value pair, and an 'mvr' " .
2635 "key-value pair. BREs have subscriptions fleshed on.",
2641 sub bre_by_identifier {
2642 my ($self, $client, $term, $options) = @_;
2644 return new OpenILS::Event("BAD_PARAMS") unless $term;
2647 my $e = new_editor();
2651 if ($options->{"is_actual_id"}) {
2655 $e->search_config_metabib_field({"field_class" => "identifier"})
2656 or return $e->die_event;
2658 my @identifiers = map { $_->name } @$cmf;
2659 my $query = join(" || ", map { "id|$_: $term" } @identifiers);
2661 my $search = create OpenSRF::AppSession("open-ils.search");
2662 my $search_result = $search->request(
2663 "open-ils.search.biblio.multiclass.query.staff", {}, $query
2665 $search->disconnect;
2667 # Un-nest results. They tend to look like [[1],[2],[3]] for some reason.
2668 @ids = map { @{$_} } @{$search_result->{"ids"}};
2676 my $bre = $e->search_biblio_record_entry([
2678 "flesh" => 2, "flesh_fields" => {
2679 "bre" => ["subscriptions"],
2680 "ssub" => ["owning_lib"]
2683 ]) or return $e->die_event;
2685 if (@$bre && $options->{"require_subscriptions"}) {
2686 $bre = [ grep { @{$_->subscriptions} } @$bre ];
2691 if (@$bre) { # re-evaluate after possible grep
2692 if ($options->{"add_mvr"}) {
2694 {"bre" => $_, "mvr" => _get_mvr($_->id)}
2697 $client->respond($_) foreach (@$bre);
2704 __PACKAGE__->register_method(
2705 "method" => "get_receivable_items",
2706 "api_name" => "open-ils.serial.items.receivable.by_subscription",
2709 "desc" => "Return all receivable items under a given subscription",
2711 {"desc" => "Authtoken", "type" => "string"},
2712 {"desc" => "Subscription ID", "type" => "number"},
2715 "desc" => "All receivable items under a given subscription",
2721 __PACKAGE__->register_method(
2722 "method" => "get_receivable_items",
2723 "api_name" => "open-ils.serial.items.receivable.by_issuance",
2726 "desc" => "Return all receivable items under a given issuance",
2728 {"desc" => "Authtoken", "type" => "string"},
2729 {"desc" => "Issuance ID", "type" => "number"},
2732 "desc" => "All receivable items under a given issuance",
2738 sub get_receivable_items {
2739 my ($self, $client, $auth, $term) = @_;
2741 my $e = new_editor("authtoken" => $auth);
2742 return $e->die_event unless $e->checkauth;
2746 my $by = ($self->api_name =~ /by_(\w+)$/)[0];
2749 "issuance" => {"issuance" => $term},
2750 "subscription" => {"+siss" => {"subscription" => $term}}
2753 my $item_ids = $e->json_query(
2755 "select" => {"sitem" => ["id"]},
2756 "from" => {"sitem" => "siss"},
2758 %{$where{$by}}, "date_received" => undef
2760 "order_by" => {"sitem" => ["id"]}
2762 ) or return $e->die_event;
2764 return undef unless @$item_ids;
2766 foreach (map { $_->{"id"} } @$item_ids) {
2768 $e->retrieve_serial_item([
2772 "sitem" => ["stream", "issuance"],
2773 "sstr" => ["distribution"],
2774 "sdist" => ["holding_lib"]
2785 __PACKAGE__->register_method(
2786 "method" => "get_receivable_issuances",
2787 "api_name" => "open-ils.serial.issuances.receivable",
2790 "desc" => "Return all issuances with receivable items given " .
2791 "a subscription ID",
2793 {"desc" => "Authtoken", "type" => "string"},
2794 {"desc" => "Subscription ID", "type" => "number"},
2797 "desc" => "All issuances with receivable items " .
2798 "(but not the items themselves)", "type" => "object"
2803 sub get_receivable_issuances {
2804 my ($self, $client, $auth, $sub_id) = @_;
2806 my $e = new_editor("authtoken" => $auth);
2807 return $e->die_event unless $e->checkauth;
2811 my $issuance_ids = $e->json_query({
2814 {"transform" => "distinct", "column" => "id"},
2818 "from" => {"siss" => "sitem"},
2820 "subscription" => $sub_id,
2821 "+sitem" => {"date_received" => undef}
2824 "siss" => {"date_published" => {"direction" => "asc"}}
2827 }) or return $e->die_event;
2829 $client->respond($e->retrieve_serial_issuance($_->{"id"}))
2830 foreach (@$issuance_ids);
2837 __PACKAGE__->register_method(
2838 "method" => "get_routing_list_users",
2839 "api_name" => "open-ils.serial.routing_list_users.fleshed_and_ordered",
2842 "desc" => "Return all routing list users with reader fleshed " .
2843 "(with card and home_ou) for a given stream ID, sorted by pos",
2845 {"desc" => "Authtoken", "type" => "string"},
2846 {"desc" => "Stream ID (int or array of ints)", "type" => "mixed"},
2849 "desc" => "Stream of routing list users", "type" => "object",
2855 sub get_routing_list_users {
2856 my ($self, $client, $auth, $stream_id) = @_;
2858 my $e = new_editor("authtoken" => $auth);
2859 return $e->die_event unless $e->checkauth;
2861 my $users = $e->search_serial_routing_list_user([
2862 {"stream" => $stream_id}, {
2863 "order_by" => {"srlu" => "pos"},
2866 "srlu" => [qw/reader stream/],
2867 "au" => [qw/card home_ou/],
2868 "sstr" => ["distribution"]
2871 ]) or return $e->die_event;
2873 return undef unless @$users;
2875 # The ADMIN_SERIAL_STREAM permission is used simply to avoid the
2876 # need for any new permission. The context OU will be the same
2877 # for every result of the above query, so we need only check once.
2878 return $e->die_event unless $e->allowed(
2879 "ADMIN_SERIAL_STREAM", $users->[0]->stream->distribution->holding_lib
2884 my @users = map { $_->stream($_->stream->id); $_ } @$users;
2885 @users = sort { $a->stream cmp $b->stream } @users if
2886 ref $stream_id eq "ARRAY";
2888 $client->respond($_) for @users;
2894 __PACKAGE__->register_method(
2895 "method" => "replace_routing_list_users",
2896 "api_name" => "open-ils.serial.routing_list_users.replace",
2898 "desc" => "Replace all routing list users on the specified streams " .
2899 "with those in the list argument",
2901 {"desc" => "Authtoken", "type" => "string"},
2902 {"desc" => "List of srlu objects", "type" => "array"},
2905 "desc" => "event on failure, undef on success"
2910 sub replace_routing_list_users {
2911 my ($self, $client, $auth, $users) = @_;
2913 return undef unless ref $users eq "ARRAY";
2915 if (grep { ref $_ ne "Fieldmapper::serial::routing_list_user" } @$users) {
2916 return new OpenILS::Event("BAD_PARAMS", "note" => "Only srlu objects");
2919 my $e = new_editor("authtoken" => $auth, "xact" => 1);
2920 return $e->die_event unless $e->checkauth;
2922 my %streams_ok = ();
2925 foreach my $user (@$users) {
2926 unless (exists $streams_ok{$user->stream}) {
2927 my $stream = $e->retrieve_serial_stream([
2930 "flesh_fields" => {"sstr" => ["distribution"]}
2932 ]) or return $e->die_event;
2934 "ADMIN_SERIAL_STREAM", $stream->distribution->holding_lib
2935 ) or return $e->die_event;
2937 my $to_delete = $e->search_serial_routing_list_user(
2938 {"stream" => $user->stream}
2939 ) or return $e->die_event;
2942 "Deleting srlu: [" .
2943 join(", ", map { $_->id; } @$to_delete) .
2947 foreach (@$to_delete) {
2948 $e->delete_serial_routing_list_user($_) or
2949 return $e->die_event;
2952 $streams_ok{$user->stream} = 1;
2955 next if $user->isdeleted;
2959 $e->create_serial_routing_list_user($user) or return $e->die_event;
2962 $e->commit or return $e->die_event;
2966 __PACKAGE__->register_method(
2967 "method" => "get_records_with_marc_85x",
2968 "api_name"=>"open-ils.serial.caption_and_pattern.find_legacy_by_bib_record",
2971 "desc" => "Return the specified BRE itself and/or any related SRE ".
2972 "whenever they have 853-855 tags",
2974 {"desc" => "Authtoken", "type" => "string"},
2975 {"desc" => "bib record ID", "type" => "number"},
2978 "desc" => "objects, either bre or sre", "type" => "object"
2983 sub get_records_with_marc_85x { # specifically, 853-855
2984 my ($self, $client, $auth, $bre_id) = @_;
2986 my $e = new_editor("authtoken" => $auth);
2987 return $e->die_event unless $e->checkauth;
2989 my $bre = $e->search_biblio_record_entry([
2990 {"id" => $bre_id, "deleted" => "f"}, {
2992 "flesh_fields" => {"bre" => [qw/creator editor owner/]}
2994 ]) or return $e->die_event;
2996 return undef unless @$bre;
2999 my $record = MARC::Record->new_from_xml($bre->marc);
3000 $client->respond($bre) if $record->field("85[3-5]");
3001 # XXX Is passing a regex to ->field() an abuse of MARC::Record ?
3003 my $sres = $e->search_serial_record_entry([
3004 {"record" => $bre_id, "deleted" => "f"}, {
3006 "flesh_fields" => {"sre" => [qw/creator editor owning_lib/]}
3008 ]) or return $e->die_event;
3012 foreach my $sre (@$sres) {
3013 $client->respond($sre) if
3014 MARC::Record->new_from_xml($sre->marc)->field("85[3-5]");
3020 __PACKAGE__->register_method(
3021 "method" => "create_scaps_from_marcxml",
3022 "api_name" => "open-ils.serial.caption_and_pattern.create_from_records",
3025 "desc" => "Create caption and pattern objects from 853-855 tags " .
3026 "in MARCXML documents",
3028 {"desc" => "Authtoken", "type" => "string"},
3029 {"desc" => "Subscription ID", "type" => "number"},
3030 {"desc" => "list of MARCXML documents as strings",
3034 "desc" => "Newly created caption and pattern objects",
3035 "type" => "object", "class" => "scap"
3040 sub create_scaps_from_marcxml {
3041 my ($self, $client, $auth, $sub_id, $docs) = @_;
3043 return undef unless ref $docs eq "ARRAY";
3045 my $e = new_editor("authtoken" => $auth, "xact" => 1);
3046 return $e->die_event unless $e->checkauth;
3048 # Retrieve the subscription just for perm checking (whether we can create
3049 # scaps at the owning lib).
3050 my $sub = $e->retrieve_serial_subscription($sub_id) or return $e->die_event;
3051 return $e->die_event unless
3052 $e->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $sub->owning_lib);
3054 foreach my $record (map { MARC::Record->new_from_xml($_) } @$docs) {
3055 foreach my $field ($record->field("85[3-5]")) {
3056 my $scap = new Fieldmapper::serial::caption_and_pattern;
3057 $scap->subscription($sub_id);
3058 $scap->type($MFHD_NAMES_BY_TAG{$field->tag});
3059 $scap->pattern_code(
3060 OpenSRF::Utils::JSON->perl2JSON(
3061 [ $field->indicator(1), $field->indicator(2),
3062 map { @$_ } $field->subfields ] # flattens nested array
3065 $e->create_serial_caption_and_pattern($scap) or
3066 return $e->die_event;
3067 $client->respond($e->data);
3071 $e->commit or return $e->die_event;