3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 OpenILS::Application::Serial - Performs serials-related tasks such as receiving issues and generating predictions
31 Dan Wells, dbw2@calvin.edu
35 package OpenILS::Application::Serial;
41 use OpenILS::Application;
42 use base qw/OpenILS::Application/;
43 use OpenILS::Application::AppUtils;
45 use OpenSRF::AppSession;
46 use OpenSRF::Utils qw/:datetime/;
47 use OpenSRF::Utils::Logger qw/:logger/;
48 use OpenILS::Utils::CStoreEditor q/:funcs/;
49 use OpenILS::Utils::Fieldmapper;
50 use OpenILS::Utils::MFHD;
51 use MARC::File::XML (BinaryEncoding => 'utf8');
52 my $U = 'OpenILS::Application::AppUtils';
53 my @MFHD_NAMES = ('basic','supplement','index');
54 my %MFHD_NAMES_BY_TAG = ( '853' => $MFHD_NAMES[0],
55 '863' => $MFHD_NAMES[0],
56 '854' => $MFHD_NAMES[1],
57 '864' => $MFHD_NAMES[1],
58 '855' => $MFHD_NAMES[2],
59 '865' => $MFHD_NAMES[2] );
60 my %MFHD_TAGS_BY_NAME = ( $MFHD_NAMES[0] => '853',
61 $MFHD_NAMES[1] => '854',
62 $MFHD_NAMES[2] => '855');
63 my $_strp_date = new DateTime::Format::Strptime(pattern => '%F');
65 # helper method for conforming dates to ISO8601
70 foreach my $field (@$fields) {
71 $item->$field(OpenSRF::Utils::clense_ISO8601($item->$field)) if $item->$field;
79 "open-ils.search.biblio.record.mods_slim.retrieve",
85 ##########################################################################
88 __PACKAGE__->register_method(
89 method => 'fleshed_item_alter',
90 api_name => 'open-ils.serial.item.fleshed.batch.update',
94 desc => 'Receives an array of one or more items and updates the database as needed',
97 desc => 'Authtoken for current user session',
102 desc => 'Array of fleshed items',
108 desc => 'Returns 1 if successful, event if failed',
114 sub fleshed_item_alter {
115 my( $self, $conn, $auth, $items ) = @_;
116 return 1 unless ref $items;
117 my( $reqr, $evt ) = $U->checkses($auth);
119 my $editor = new_editor(requestor => $reqr, xact => 1);
120 my $override = $self->api_name =~ /override/;
122 # TODO: permission check
123 # return $editor->event unless
124 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
126 for my $item (@$items) {
128 my $itemid = $item->id;
129 $item->editor($editor->requestor->id);
130 $item->edit_date('now');
132 if( $item->isdeleted ) {
133 $evt = _delete_sitem( $editor, $override, $item);
134 } elsif( $item->isnew ) {
135 # TODO: reconsider this
136 # if the item has a new issuance, create the issuance first
137 if (ref $item->issuance eq 'Fieldmapper::serial::issuance' and $item->issuance->isnew) {
138 fleshed_issuance_alter($self, $conn, $auth, [$item->issuance]);
140 _cleanse_dates($item, ['date_expected','date_received']);
141 $evt = _create_sitem( $editor, $item );
143 _cleanse_dates($item, ['date_expected','date_received']);
144 $evt = _update_sitem( $editor, $override, $item );
149 $logger->info("fleshed item-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
153 $logger->debug("item-alter: done updating item batch");
155 $logger->info("fleshed item-alter successfully updated ".scalar(@$items)." items");
160 my ($editor, $override, $item) = @_;
161 $logger->info("item-alter: delete item ".OpenSRF::Utils::JSON->perl2JSON($item));
162 return $editor->event unless $editor->delete_serial_item($item);
167 my ($editor, $item) = @_;
169 $item->creator($editor->requestor->id);
170 $item->create_date('now');
172 $logger->info("item-alter: new item ".OpenSRF::Utils::JSON->perl2JSON($item));
173 return $editor->event unless $editor->create_serial_item($item);
178 my ($editor, $override, $item) = @_;
180 $logger->info("item-alter: retrieving item ".$item->id);
181 my $orig_item = $editor->retrieve_serial_item($item->id);
183 $logger->info("item-alter: original item ".OpenSRF::Utils::JSON->perl2JSON($orig_item));
184 $logger->info("item-alter: updated item ".OpenSRF::Utils::JSON->perl2JSON($item));
185 return $editor->event unless $editor->update_serial_item($item);
189 __PACKAGE__->register_method(
190 method => "fleshed_serial_item_retrieve_batch",
192 api_name => "open-ils.serial.item.fleshed.batch.retrieve"
195 sub fleshed_serial_item_retrieve_batch {
196 my( $self, $client, $ids ) = @_;
197 # FIXME: permissions?
198 $logger->info("Fetching fleshed serial items @$ids");
199 return $U->cstorereq(
200 "open-ils.cstore.direct.serial.item.search.atomic",
203 flesh_fields => {sitem => [ qw/issuance creator editor stream unit notes/ ], sstr => ["distribution"], sunit => ["call_number"], siss => [qw/creator editor subscription/]}
208 ##########################################################################
211 __PACKAGE__->register_method(
212 method => 'fleshed_issuance_alter',
213 api_name => 'open-ils.serial.issuance.fleshed.batch.update',
217 desc => 'Receives an array of one or more issuances and updates the database as needed',
220 desc => 'Authtoken for current user session',
225 desc => 'Array of fleshed issuances',
231 desc => 'Returns 1 if successful, event if failed',
237 sub fleshed_issuance_alter {
238 my( $self, $conn, $auth, $issuances ) = @_;
239 return 1 unless ref $issuances;
240 my( $reqr, $evt ) = $U->checkses($auth);
242 my $editor = new_editor(requestor => $reqr, xact => 1);
243 my $override = $self->api_name =~ /override/;
245 # TODO: permission support
246 # return $editor->event unless
247 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
249 for my $issuance (@$issuances) {
250 my $issuanceid = $issuance->id;
251 $issuance->editor($editor->requestor->id);
252 $issuance->edit_date('now');
254 if( $issuance->isdeleted ) {
255 $evt = _delete_siss( $editor, $override, $issuance);
256 } elsif( $issuance->isnew ) {
257 _cleanse_dates($issuance, ['date_published']);
258 $evt = _create_siss( $editor, $issuance );
260 _cleanse_dates($issuance, ['date_published']);
261 $evt = _update_siss( $editor, $override, $issuance );
266 $logger->info("fleshed issuance-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
270 $logger->debug("issuance-alter: done updating issuance batch");
272 $logger->info("fleshed issuance-alter successfully updated ".scalar(@$issuances)." issuances");
277 my ($editor, $override, $issuance) = @_;
278 $logger->info("issuance-alter: delete issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
279 return $editor->event unless $editor->delete_serial_issuance($issuance);
284 my ($editor, $issuance) = @_;
286 $issuance->creator($editor->requestor->id);
287 $issuance->create_date('now');
289 $logger->info("issuance-alter: new issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
290 return $editor->event unless $editor->create_serial_issuance($issuance);
295 my ($editor, $override, $issuance) = @_;
297 $logger->info("issuance-alter: retrieving issuance ".$issuance->id);
298 my $orig_issuance = $editor->retrieve_serial_issuance($issuance->id);
300 $logger->info("issuance-alter: original issuance ".OpenSRF::Utils::JSON->perl2JSON($orig_issuance));
301 $logger->info("issuance-alter: updated issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
302 return $editor->event unless $editor->update_serial_issuance($issuance);
306 __PACKAGE__->register_method(
307 method => "fleshed_serial_issuance_retrieve_batch",
309 api_name => "open-ils.serial.issuance.fleshed.batch.retrieve"
312 sub fleshed_serial_issuance_retrieve_batch {
313 my( $self, $client, $ids ) = @_;
314 # FIXME: permissions?
315 $logger->info("Fetching fleshed serial issuances @$ids");
316 return $U->cstorereq(
317 "open-ils.cstore.direct.serial.issuance.search.atomic",
320 flesh_fields => {siss => [ qw/creator editor subscription/ ]}
324 __PACKAGE__->register_method(
325 method => "pub_fleshed_serial_issuance_retrieve_batch",
326 api_name => "open-ils.serial.issuance.pub_fleshed.batch.retrieve",
329 Public (i.e. OPAC) call for getting at the sub and
330 ultimately the record entry from an issuance
332 params => [{name => 'ids', desc => 'Array of IDs', type => 'array'}],
335 issuance objects, fleshed with subscriptions
341 sub pub_fleshed_serial_issuance_retrieve_batch {
342 my( $self, $client, $ids ) = @_;
343 return [] unless $ids and @$ids;
344 return new_editor()->search_serial_issuance([
348 flesh_fields => {siss => [ qw/subscription/ ]}
353 sub received_siss_by_bib {
358 my $args = shift || {};
359 $$args{order} ||= 'asc';
361 my $global = $$args{global} == 0 ? 0 : 1;
363 my $e = new_editor();
364 my $issuances = $e->json_query({
367 $global ? { transform => "min", column => "id", aggregate => 1 } : "id",
374 field => 'subscription',
380 $$args{ou} ? ( join => {
387 fkey => 'distribution'
398 '+ssub' => { record_entry => $bib },
399 $$args{type} ? ( '+siss' => { 'holding_type' => $$args{type} } ) : (),
401 # XXX should we also take specific item statuses into account?
402 date_received => { '!=' => undef },
403 $$args{status} ? ( 'status' => $$args{status} ) : ()
405 $$args{ou} ? ( '+sdist' => {
407 'in' => $U->get_org_descendants($$args{ou}, $$args{depth})
411 $$args{limit} ? ( limit => $$args{limit} ) : (),
412 $$args{offset} ? ( offset => $$args{offset} ) : (),
413 order_by => [{ class => 'siss', field => 'date_published', direction => $$args{order} }],
417 $client->respond($e->retrieve_serial_issuance($_->{id})) for @$issuances;
420 __PACKAGE__->register_method(
421 method => 'received_siss_by_bib',
422 api_name => 'open-ils.serial.received_siss.retrieve.by_bib',
427 desc => 'Receives a Bib ID and other optional params and returns "siss" (issuance) objects',
430 desc => 'id of the bre to which the issuances belong',
435 q/A hash of optional arguments. Valid keys and their meanings:
436 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).
437 order := date_published sort direction, either "asc" (chronological, default) or "desc" (reverse chronological)
438 limit := Number of issuances to return. Useful for paging results, or finding the oldest or newest
439 offset := Number of issuance to skip before returning results. Useful for paging.
440 orgid := OU id used to scope retrieval, based on distribution.holding_lib
441 depth := OU depth used to range the scope of orgid
442 type := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
443 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).
451 sub scoped_bib_holdings_summary {
455 my $args = shift || {};
457 $args->{order} = 'asc';
459 my ($issuances) = $self->method_lookup('open-ils.serial.received_siss.retrieve.by_bib.atomic')->run( $bibid => $args );
461 # split into issuance type sets
462 my %type_blob = (basic => [], supplement => [], index => []);
463 push @{ $type_blob{ $_->holding_type } }, $_ for (@$issuances);
465 # generate a statement list for each type
467 for my $type ( keys %type_blob ) {
468 my ($mfhd,$list) = _summarize_contents(new_editor(), $type_blob{$type});
469 $statement_blob{$type} = $list;
472 return \%statement_blob;
474 __PACKAGE__->register_method(
475 method => 'scoped_bib_holdings_summary',
476 api_name => 'open-ils.serial.bib.summary_statements',
480 desc => 'Receives a Bib ID and other optional params and returns set of holdings statements',
483 desc => 'id of the bre to which the issuances belong',
488 q/A hash of optional arguments. Valid keys and their meanings:
489 orgid := OU id used to scope retrieval, based on distribution.holding_lib
490 depth := OU depth used to range the scope of orgid
491 type := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
492 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).
500 ##########################################################################
503 __PACKAGE__->register_method(
504 method => 'fleshed_sunit_alter',
505 api_name => 'open-ils.serial.sunit.fleshed.batch.update',
509 desc => 'Receives an array of one or more Units and updates the database as needed',
512 desc => 'Authtoken for current user session',
517 desc => 'Array of fleshed Units',
523 desc => 'Returns 1 if successful, event if failed',
529 sub fleshed_sunit_alter {
530 my( $self, $conn, $auth, $sunits ) = @_;
531 return 1 unless ref $sunits;
532 my( $reqr, $evt ) = $U->checkses($auth);
534 my $editor = new_editor(requestor => $reqr, xact => 1);
535 my $override = $self->api_name =~ /override/;
537 # TODO: permission support
538 # return $editor->event unless
539 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
541 for my $sunit (@$sunits) {
542 if( $sunit->isdeleted ) {
543 $evt = _delete_sunit( $editor, $override, $sunit );
545 $sunit->default_location( $sunit->default_location->id ) if ref $sunit->default_location;
547 if( $sunit->isnew ) {
548 $evt = _create_sunit( $editor, $sunit );
550 $evt = _update_sunit( $editor, $override, $sunit );
556 $logger->info("fleshed sunit-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
560 $logger->debug("sunit-alter: done updating sunit batch");
562 $logger->info("fleshed sunit-alter successfully updated ".scalar(@$sunits)." Units");
567 my ($editor, $override, $sunit) = @_;
568 $logger->info("sunit-alter: delete sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
569 return $editor->event unless $editor->delete_serial_unit($sunit);
574 my ($editor, $sunit) = @_;
576 $logger->info("sunit-alter: new Unit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
577 return $editor->event unless $editor->create_serial_unit($sunit);
582 my ($editor, $override, $sunit) = @_;
584 $logger->info("sunit-alter: retrieving sunit ".$sunit->id);
585 my $orig_sunit = $editor->retrieve_serial_unit($sunit->id);
587 $logger->info("sunit-alter: original sunit ".OpenSRF::Utils::JSON->perl2JSON($orig_sunit));
588 $logger->info("sunit-alter: updated sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
589 return $editor->event unless $editor->update_serial_unit($sunit);
593 __PACKAGE__->register_method(
594 method => "retrieve_unit_list",
596 api_name => "open-ils.serial.unit_list.retrieve"
599 sub retrieve_unit_list {
601 my( $self, $client, @sdist_ids ) = @_;
603 if(ref($sdist_ids[0])) { @sdist_ids = @{$sdist_ids[0]}; }
605 my $e = new_editor();
609 { 'sunit' => [ 'id', 'summary_contents', 'sort_key' ],
610 'sitem' => ['stream'],
611 'sstr' => ['distribution'],
612 'sdist' => [{'column' => 'label', 'alias' => 'sdist_label'}]
619 { 'join' => { 'sunit' => {} } }
624 'distinct' => 'true',
625 'where' => { '+sdist' => {'id' => \@sdist_ids} },
626 'order_by' => [{'class' => 'sunit', 'field' => 'sort_key'}]
629 my $unit_list_entries = $e->json_query($query);
632 foreach my $entry (@$unit_list_entries) {
633 my $value = {'sunit' => $entry->{id}, 'sstr' => $entry->{stream}, 'sdist' => $entry->{distribution}};
634 my $label = $entry->{summary_contents};
635 if (length($label) > 100) {
636 $label = substr($label, 0, 100) . '...'; # limited space in dropdown / menu
638 $label = "[$entry->{sdist_label}/$entry->{stream} #$entry->{id}] " . $label;
639 push (@entries, [$label, OpenSRF::Utils::JSON->perl2JSON($value)]);
647 ##########################################################################
648 # predict and receive methods
650 __PACKAGE__->register_method(
651 method => 'make_predictions',
652 api_name => 'open-ils.serial.make_predictions',
656 desc => 'Receives an ssub id and populates the issuance and item tables',
659 desc => 'Serial Subscription ID',
666 sub make_predictions {
667 my ($self, $conn, $authtoken, $args) = @_;
669 my $editor = OpenILS::Utils::CStoreEditor->new();
670 my $ssub_id = $args->{ssub_id};
671 my $mfhd = MFHD->new(MARC::Record->new());
673 my $ssub = $editor->retrieve_serial_subscription([$ssub_id]);
674 my $scaps = $editor->search_serial_caption_and_pattern({ subscription => $ssub_id, active => 't'});
675 my $sdists = $editor->search_serial_distribution( [{ subscription => $ssub->id }, { flesh => 1, flesh_fields => {sdist => [ qw/ streams / ]} }] ); #TODO: 'deleted' support?
677 my $total_streams = 0;
679 $total_streams += scalar(@{$_->streams});
681 if ($total_streams < 1) {
683 # XXX TODO new event type
684 return new OpenILS::Event(
685 "BAD_PARAMS", note =>
686 "There are no streams to direct items. Can't predict."
692 # XXX TODO new event type
693 return new OpenILS::Event(
694 "BAD_PARAMS", note =>
695 "There are no active caption-and-pattern objects associated " .
696 "with this subscription. Can't predict."
702 foreach my $scap (@$scaps) {
703 my $caption_field = _revive_caption($scap);
704 $caption_field->update('8' => $link_id);
705 $mfhd->append_fields($caption_field);
707 'caption' => $caption_field,
708 'scap_id' => $scap->id,
709 'num_to_predict' => $args->{num_to_predict},
710 'end_date' => defined $args->{end_date} ?
711 $_strp_date->parse_datetime($args->{end_date}) : undef
713 if ($args->{base_issuance}) { # predict from a given issuance
714 $options->{predict_from} = _revive_holding($args->{base_issuance}->holding_code, $caption_field, 1); # fresh MFHD Record, so we simply default to 1 for seqno
715 } else { # default to predicting from last published
716 my $last_published = $editor->search_serial_issuance([
717 {'caption_and_pattern' => $scap->id,
718 'subscription' => $ssub_id},
719 {limit => 1, order_by => { siss => "date_published DESC" }}]
721 if ($last_published->[0]) {
722 my $last_siss = $last_published->[0];
723 unless ($last_siss->holding_code) {
725 # XXX TODO new event type
726 return new OpenILS::Event(
727 "BAD_PARAMS", note =>
728 "Last issuance has no holding code. Can't predict."
731 $options->{predict_from} = _revive_holding($last_siss->holding_code, $caption_field, 1);
734 # XXX TODO make a new event type instead of hijacking this one
735 return new OpenILS::Event(
736 "BAD_PARAMS", note => "No issuance from which to predict!"
740 push( @predictions, _generate_issuance_values($mfhd, $options) );
745 foreach my $prediction (@predictions) {
746 my $issuance = new Fieldmapper::serial::issuance;
748 $issuance->label($prediction->{label});
749 $issuance->date_published($prediction->{date_published}->strftime('%F'));
750 $issuance->holding_code(OpenSRF::Utils::JSON->perl2JSON($prediction->{holding_code}));
751 $issuance->holding_type($prediction->{holding_type});
752 $issuance->caption_and_pattern($prediction->{caption_and_pattern});
753 $issuance->subscription($ssub->id);
754 push (@issuances, $issuance);
757 fleshed_issuance_alter($self, $conn, $authtoken, \@issuances); # FIXME: catch events
760 for (my $i = 0; $i < @issuances; $i++) {
761 my $date_expected = $predictions[$i]->{date_published}->add(seconds => interval_to_seconds($ssub->expected_date_offset))->strftime('%F');
762 my $issuance = $issuances[$i];
763 #$issuance->label(interval_to_seconds($ssub->expected_date_offset));
764 foreach my $sdist (@$sdists) {
765 my $streams = $sdist->streams;
766 foreach my $stream (@$streams) {
767 my $item = new Fieldmapper::serial::item;
769 $item->stream($stream->id);
770 $item->date_expected($date_expected);
771 $item->issuance($issuance->id);
772 push (@items, $item);
776 fleshed_item_alter($self, $conn, $authtoken, \@items); # FIXME: catch events
781 # _generate_issuance_values() is an initial attempt at a function which can be used
782 # to populate an issuance table with a list of predicted issues. It accepts
783 # a hash ref of options initially defined as:
784 # caption : the caption field to predict on
785 # num_to_predict : the number of issues you wish to predict
786 # last_rec_date : the date of the last received issue, to be used as an offset
787 # for predicting future issues
789 # The basic method is to first convert to a single holding if compressed, then
790 # increment the holding and save the resulting values to @issuances.
792 # returns @issuance_values, an array of hashrefs containing (formatted
793 # label, formatted chronology date, formatted estimated arrival date, and an
794 # array ref of holding subfields as (key, value, key, value ...)) (not a hash
795 # to protect order and possible duplicate keys), and a holding type.
797 sub _generate_issuance_values {
798 my ($mfhd, $options) = @_;
799 my $caption = $options->{caption};
800 my $scap_id = $options->{scap_id};
801 my $num_to_predict = $options->{num_to_predict};
802 my $end_date = $options->{end_date};
803 my $predict_from = $options->{predict_from}; # issuance to predict from
804 #my $last_rec_date = $options->{last_rec_date}; # expected or actual
806 # TODO: add support for predicting serials with no chronology by passing in
807 # a last_pub_date option?
810 # Only needed for 'real' MFHD records, not our temp records
811 # my $link_id = $caption->link_id;
812 # if(!$predict_from) {
813 # my $htag = $caption->tag;
814 # $htag =~ s/^85/86/;
815 # my @holdings = $mfhd->holdings($htag, $link_id);
816 # my $last_holding = $holdings[-1];
818 # #if ($last_holding->is_compressed) {
819 # # $last_holding->compressed_to_last; # convert to last in range
821 # $predict_from = $last_holding;
825 $predict_from->notes('public', []);
826 # add a note marker for system use (?)
827 $predict_from->notes('private', ['AUTOGEN']);
831 my @predictions = $mfhd->generate_predictions({'base_holding' => $predict_from, 'num_to_predict' => $num_to_predict, 'end_date' => $end_date});
832 foreach my $prediction (@predictions) {
833 $pub_date = $_strp_date->parse_datetime($prediction->chron_to_date);
838 label => $prediction->format,
839 date_published => $pub_date,
840 #date_expected => $date_expected->strftime('%F'),
841 holding_code => [$prediction->indicator(1),$prediction->indicator(2),$prediction->subfields_list],
842 holding_type => $MFHD_NAMES_BY_TAG{$caption->tag},
843 caption_and_pattern => $scap_id
848 return @issuance_values;
851 sub _revive_caption {
854 my $pattern_code = $scap->pattern_code;
857 my $pattern_parts = OpenSRF::Utils::JSON->JSON2perl($pattern_code);
858 unshift(@$pattern_parts, $MFHD_TAGS_BY_NAME{$scap->type});
859 my $pattern_field = new MARC::Field(@$pattern_parts);
861 # build MFHD::Caption
862 return new MFHD::Caption($pattern_field);
865 sub _revive_holding {
866 my $holding_code = shift;
867 my $caption_field = shift;
871 my $holding_parts = OpenSRF::Utils::JSON->JSON2perl($holding_code);
872 my $captag = $caption_field->tag;
873 $captag =~ s/^85/86/;
874 unshift(@$holding_parts, $captag);
875 my $holding_field = new MARC::Field(@$holding_parts);
877 # build MFHD::Holding
878 return new MFHD::Holding($seqno, $holding_field, $caption_field);
881 __PACKAGE__->register_method(
882 method => 'unitize_items',
883 api_name => 'open-ils.serial.receive_items',
887 desc => 'Marks an item as received, updates the shelving unit (creating a new shelving unit if needed), and updates the summaries',
890 desc => 'array of serial items',
895 desc => 'hash of item_ids => barcodes',
900 desc => 'Returns number of received items (num_items) and new unit ID, if applicable (new_unit_id)',
906 __PACKAGE__->register_method(
907 method => 'unitize_items',
908 api_name => 'open-ils.serial.bind_items',
912 desc => 'Marks an item as bound, updates the shelving unit (creating a new shelving unit if needed)',
915 desc => 'array of serial items',
920 desc => 'hash of item_ids => barcodes',
925 desc => 'Returns number of bound items (num_items) and new unit ID, if applicable (new_unit_id)',
932 my ($self, $conn, $auth, $items, $barcodes) = @_;
934 my( $reqr, $evt ) = $U->checkses($auth);
936 my $editor = new_editor(requestor => $reqr, xact => 1);
937 $self->api_name =~ /serial\.(\w*)_items/;
941 my %found_stream_ids;
944 my %stream_ids_by_unit_id;
947 my %sdist_by_unit_id;
948 my %sdist_by_stream_id;
950 my $new_unit_id; # id for '-2' units to share
951 foreach my $item (@$items) {
952 # for debugging only, TODO: delete
953 if (!ref $item) { # hopefully we got an id instead
954 $item = $editor->retrieve_serial_item($item);
957 my $unit_id = ref($item->unit) ? $item->unit->id : $item->unit;
958 my $stream_id = ref($item->stream) ? $item->stream->id : $item->stream;
959 my $issuance_id = ref($item->issuance) ? $item->issuance->id : $item->issuance;
960 #TODO: evt on any missing ids
962 if ($mode eq 'receive') {
963 $item->date_received('now');
964 $item->status('Received');
966 $item->status('Bindery');
969 # check for types to trigger summary updates
971 if (!ref $item->issuance) {
972 my $scaps = $editor->search_serial_caption_and_pattern([{"+siss" => {"id" => $issuance_id}}, { "join" => {"siss" => {}} }]);
974 } elsif (!ref $item->issuance->caption_and_pattern) {
975 $scap = $editor->retrieve_serial_caption_and_pattern($item->issuance->caption_and_pattern);
977 $scap = $editor->issuance->caption_and_pattern;
979 if (!exists($found_types{$stream_id})) {
980 $found_types{$stream_id} = {};
982 $found_types{$stream_id}->{$scap->type} = 1;
984 # create unit if needed
985 if ($unit_id == -1 or (!$new_unit_id and $unit_id == -2)) { # create unit per item
987 my $sdists = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
988 $unit = _build_unit($editor, $sdists->[0], $mode, 0, $barcodes->{$item->id});
989 # if _build_unit fails, $unit is an event, so return it
990 if ($U->event_code($unit)) {
992 $unit->{"note"} = "Item ID: " . $item->id;
995 my $evt = _create_sunit($editor, $unit);
997 if ($unit_id == -2) {
998 $new_unit_id = $unit->id;
999 $unit_id = $new_unit_id;
1001 $unit_id = $unit->id;
1003 $item->unit($unit_id);
1005 # get unit with 'DEFAULT's and save unit and sdist for later use
1006 $unit = $editor->retrieve_serial_unit($unit->id);
1007 $unit_map{$unit_id} = $unit;
1008 $sdist_by_unit_id{$unit_id} = $sdists->[0];
1009 $sdist_by_stream_id{$stream_id} = $sdists->[0];
1010 } elsif ($unit_id == -2) { # create one unit for all '-2' items
1011 $unit_id = $new_unit_id;
1012 $item->unit($unit_id);
1015 $found_unit_ids{$unit_id} = 1;
1016 $found_stream_ids{$stream_id} = 1;
1018 # save the stream_id for this unit_id
1019 # TODO: prevent items from different streams in same unit? (perhaps in interface)
1020 $stream_ids_by_unit_id{$unit_id} = $stream_id;
1022 my $evt = _update_sitem($editor, undef, $item);
1023 return $evt if $evt;
1026 # deal with unit level labels
1027 foreach my $unit_id (keys %found_unit_ids) {
1029 # get all the needed issuances for unit
1030 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"unit" => $unit_id, "status" => ["Received", "Bindery"]}}, {"join" => {"sitem" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1031 #TODO: evt on search failure
1033 my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
1035 # special case for single formatted_part (may have summarized version)
1036 if (@$formatted_parts == 1) {
1037 #TODO: MFHD.pm should have a 'format_summary' method for this
1040 # retrieve and update unit contents
1044 # if we just created the unit, we will already have it and the distribution stored
1045 if (exists $unit_map{$unit_id}) {
1046 $sunit = $unit_map{$unit_id};
1047 $sdist = $sdist_by_unit_id{$unit_id};
1049 $sunit = $editor->retrieve_serial_unit($unit_id);
1050 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_ids_by_unit_id{$unit_id}}}, { "join" => {"sstr" => {}} }]);
1051 $sdist = $sdist->[0];
1054 $sunit->detailed_contents($sdist->unit_label_prefix . ' '
1055 . join(', ', @$formatted_parts) . ' '
1056 . $sdist->unit_label_suffix);
1058 $sunit->summary_contents($sunit->detailed_contents); #TODO: change this when real summary contents are available
1060 # create sort_key by left padding numbers to 6 digits
1061 my $sort_key = $sunit->detailed_contents;
1062 $sort_key =~ s/(\d+)/sprintf '%06d', $1/eg; # this may need improvement
1063 $sunit->sort_key($sort_key);
1065 if ($mode eq 'bind') {
1066 $sunit->status(2); # set to 'Bindery' status
1069 my $evt = _update_sunit($editor, undef, $sunit);
1070 return $evt if $evt;
1073 # cleanup 'dead' units (units which are now emptied of their items)
1074 my $dead_units = $editor->search_serial_unit([{'+sitem' => {'id' => undef}, 'deleted' => 'f'}, {'join' => {'sitem' => {'type' => 'left'}}}]);
1075 foreach my $unit (@$dead_units) {
1076 _delete_sunit($editor, undef, $unit);
1079 if ($mode eq 'receive') { # the summary holdings do not change when binding
1080 # deal with stream level summaries
1081 # summaries will be built from the "primary" stream only, that is, the stream with the lowest ID per distribution
1082 # (TODO: consider direct designation)
1083 my %primary_streams_by_sdist;
1084 my %streams_by_sdist;
1086 # see if we have primary streams, and if so, associate them with their distributions
1087 foreach my $stream_id (keys %found_stream_ids) {
1089 if (exists $sdist_by_stream_id{$stream_id}) {
1090 $sdist = $sdist_by_stream_id{$stream_id};
1092 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
1093 $sdist = $sdist->[0];
1096 if (!exists($streams_by_sdist{$sdist->id})) {
1097 $streams = $editor->search_serial_stream([{"distribution" => $sdist->id}, {"order_by" => {"sstr" => "id"}}]);
1098 $streams_by_sdist{$sdist->id} = $streams;
1100 $streams = $streams_by_sdist{$sdist->id};
1102 $primary_streams_by_sdist{$sdist->id} = $streams->[0] if ($stream_id == $streams->[0]->id);
1105 # retrieve and update summaries for each affected primary stream's distribution
1106 foreach my $sdist_id (keys %primary_streams_by_sdist) {
1107 my $stream = $primary_streams_by_sdist{$sdist_id};
1108 my $stream_id = $stream->id;
1109 # get all the needed issuances for stream
1110 # FIXME: search in Bindery/Bound/Not Published? as well as Received
1111 foreach my $type (keys %{$found_types{$stream_id}}) {
1112 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"stream" => $stream_id, "status" => "Received"}, "+scap" => {"type" => $type}}, {"join" => {"sitem" => {}, "scap" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1113 #TODO: evt on search failure
1115 my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
1117 # retrieve and update the generated_coverage of the summary
1118 my $search_method = "search_serial_${type}_summary";
1119 my $summary = $editor->$search_method([{"distribution" => $sdist_id}]);
1120 $summary = $summary->[0];
1121 $summary->generated_coverage(join(', ', @$formatted_parts));
1122 my $update_method = "update_serial_${type}_summary";
1123 return $editor->event unless $editor->$update_method($summary);
1129 return {'num_items' => scalar @$items, 'new_unit_id' => $new_unit_id};
1132 sub _find_or_create_call_number {
1133 my ($e, $lib, $cn_string, $record) = @_;
1135 my $existing = $e->search_asset_call_number({
1136 "owning_lib" => $lib,
1137 "label" => $cn_string,
1138 "record" => $record,
1140 }) or return $e->die_event;
1143 return $existing->[0]->id;
1145 return $e->die_event unless
1146 $e->allowed("CREATE_VOLUME", $lib);
1148 my $acn = new Fieldmapper::asset::call_number;
1150 $acn->creator($e->requestor->id);
1151 $acn->editor($e->requestor->id);
1152 $acn->record($record);
1153 $acn->label($cn_string);
1154 $acn->owning_lib($lib);
1156 $e->create_asset_call_number($acn) or return $e->die_event;
1157 return $e->data->id;
1161 sub _issuances_received {
1162 # XXX TODO: Add some caching or something. This is getting called
1163 # more often than it has to be.
1164 my ($e, $sitem) = @_;
1166 my $results = $e->json_query({
1167 "select" => {"sitem" => ["issuance"]},
1168 "from" => {"sitem" => {"sstr" => {}, "siss" => {}}},
1170 "+sstr" => {"distribution" => $sitem->stream->distribution->id},
1171 "+siss" => {"holding_type" => $sitem->issuance->holding_type},
1172 "+sitem" => {"date_received" => {"!=" => undef}}
1175 "siss" => {"date_published" => {"direction" => "asc"}}
1177 }) or return $e->die_event;
1179 my $uniq = +{map { $_->{"issuance"} => 1 } @$results};
1180 return [ map { $e->retrieve_serial_issuance($_) } keys %$uniq ];
1183 # XXX _prepare_unit_label() duplicates some code from unitize_items().
1184 # Hopefully we can unify code paths down the road.
1185 sub _prepare_unit_label {
1186 my ($e, $sunit, $sdist, $issuance) = @_;
1188 my ($mfhd, $formatted_parts) = _summarize_contents($e, [$issuance]);
1190 # special case for single formatted_part (may have summarized version)
1191 if (@$formatted_parts == 1) {
1192 #TODO: MFHD.pm should have a 'format_summary' method for this
1195 $sunit->detailed_contents(
1198 $sdist->unit_label_prefix,
1199 join(", ", @$formatted_parts),
1200 $sdist->unit_label_suffix
1204 # TODO: change this when real summary contents are available
1205 $sunit->summary_contents($sunit->detailed_contents);
1207 # Create sort_key by left padding numbers to 6 digits.
1208 (my $sort_key = $sunit->detailed_contents) =~
1209 s/(\d+)/sprintf '%06d', $1/eg;
1210 $sunit->sort_key($sort_key);
1213 # XXX duplicates a block of code from unitize_items(). Once I fully understand
1214 # what's going on and I'm sure it's working right, I'd like to have
1215 # unitize_items() just use this, keeping the logic in one place.
1216 sub _prepare_summaries {
1217 my ($e, $sitem, $issuances) = @_;
1219 my $dist_id = $sitem->stream->distribution->id;
1220 my $type = $sitem->issuance->holding_type;
1222 # Make sure @$issuances contains the new issuance from sitem.
1223 unless (grep { $_->id == $sitem->issuance->id } @$issuances) {
1224 push @$issuances, $sitem->issuance;
1227 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances);
1229 my $search_method = "search_serial_${type}_summary";
1230 my $summary = $e->$search_method([{"distribution" => $dist_id}]);
1232 my $cu_method = "update";
1235 $summary = $summary->[0];
1237 my $class = "Fieldmapper::serial::${type}_summary";
1238 $summary = $class->new;
1239 $summary->distribution($dist_id);
1240 $cu_method = "create";
1243 $summary->generated_coverage(join(", ", @$formatted_parts));
1244 my $method = "${cu_method}_serial_${type}_summary";
1245 return $e->die_event unless $e->$method($summary);
1248 sub _unit_by_iss_and_str {
1249 my ($e, $issuance, $stream) = @_;
1251 my $unit = $e->json_query({
1252 "select" => {"sunit" => ["id"]},
1253 "from" => {"sitem" => {"sunit" => {}}},
1256 "issuance" => $issuance->id,
1257 "stream" => $stream->id
1260 }) or return $e->die_event;
1262 $e->retrieve_serial_unit($unit->[0]->{"id"}) or $e->die_event;
1265 sub move_previous_unit {
1266 my ($e, $prev_iss, $curr_item, $new_loc) = @_;
1268 my $prev_unit = _unit_by_iss_and_str($e,$prev_iss,$curr_item->stream);
1269 return $prev_unit if defined $U->event_code($prev_unit);
1271 if ($prev_unit->location != $new_loc) {
1272 $prev_unit->location($new_loc);
1273 $e->update_serial_unit($prev_unit) or return $e->die_event;
1278 # _previous_issuance() assumes $existing is an ordered array
1279 sub _previous_issuance {
1280 my ($existing, $issuance) = @_;
1282 my $last = $existing->[-1];
1283 return undef unless $last;
1284 return ($last->id == $issuance->id ? $existing->[-2] : $last);
1287 __PACKAGE__->register_method(
1288 "method" => "receive_items_one_unit_per",
1289 "api_name" => "open-ils.serial.receive_items.one_unit_per",
1294 "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",
1298 "desc" => "authtoken",
1303 "desc" => "array of serial items, possibly fleshed with units and definitely fleshed with stream->distribution",
1308 "desc" => "id of bib record these items are associated with
1309 (XXX could/should be derived from items)",
1314 "desc" => "The item ID for each item successfully received",
1320 sub receive_items_one_unit_per {
1321 # XXX This function may be temporary, as it does some of what
1322 # unitize_items() does, just in a different way.
1323 my ($self, $client, $auth, $items, $record) = @_;
1325 my $e = new_editor("authtoken" => $auth, "xact" => 1);
1326 return $e->die_event unless $e->checkauth;
1327 return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
1329 my $prev_loc_setting_map = {};
1330 my $user_id = $e->requestor->id;
1332 # Get a list of all the non-virtual field names in a serial::unit for
1333 # merging given unit objects with template-built units later.
1334 # XXX move this somewhere global so it isn't re-run all the time
1335 my $all_unit_fields =
1336 $Fieldmapper::fieldmap->{"Fieldmapper::serial::unit"}->{"fields"};
1337 my @real_unit_fields = grep {
1338 not $all_unit_fields->{$_}->{"virtual"}
1339 } keys %$all_unit_fields;
1341 foreach my $item (@$items) {
1342 # Note that we expect a certain fleshing on the items we're getting.
1343 my $sdist = $item->stream->distribution;
1345 # Fetch a list of issuances with received copies already existing
1346 # on this distribution (and with the same holding type on the
1347 # issuance). This will be used in up to two places: once when building
1348 # a summary, once when changing the copy location of the previous
1350 my $issuances_received = _issuances_received($e, $item);
1351 if ($U->event_code($issuances_received)) {
1353 return $issuances_received;
1356 # Find out if we need to to deal with previous copy location changing.
1357 my $ou = $sdist->holding_lib->id;
1358 unless (exists $prev_loc_setting_map->{$ou}) {
1359 $prev_loc_setting_map->{$ou} = $U->ou_ancestor_setting_value(
1360 $ou, "serial.prev_issuance_copy_location", $e
1364 # If there is a previous copy location setting, we need the previous
1365 # issuance, from which we can in turn look up the item attached to the
1366 # same stream we're on now.
1367 if ($prev_loc_setting_map->{$ou}) {
1369 _previous_issuance($issuances_received, $item->issuance)) {
1371 # Now we can change the copy location of the previous unit,
1373 return $e->event if defined $U->event_code(
1375 $e, $prev_iss, $item, $prev_loc_setting_map->{$ou}
1381 # Create unit if given by user
1382 if (ref $item->unit) {
1383 # detach from the item, as we need to create separately
1384 my $user_unit = $item->unit;
1386 # get a unit based on associated template
1387 my $template_unit = _build_unit($e, $sdist, "receive", 1);
1388 if ($U->event_code($template_unit)) {
1390 $template_unit->{"note"} = "Item ID: " . $item->id;
1391 return $template_unit;
1394 # merge built unit with provided unit from user
1395 foreach (@real_unit_fields) {
1396 unless ($user_unit->$_) {
1397 $user_unit->$_($template_unit->$_);
1401 # Treat call number specially: the provided value from the
1402 # user will really be a string.
1403 if ($user_unit->call_number) {
1404 my $real_cn = _find_or_create_call_number(
1405 $e, $sdist->holding_lib->id,
1406 $user_unit->call_number, $record
1409 if ($U->event_code($real_cn)) {
1413 $user_unit->call_number($real_cn);
1417 my $evt = _prepare_unit_label(
1418 $e, $user_unit, $sdist, $item->issuance
1420 if ($U->event_code($evt)) {
1425 # create/update summary objects related to this distribution
1426 $evt = _prepare_summaries($e, $item, $issuances_received);
1427 if ($U->event_code($evt)) {
1432 # set the incontrovertibles on the unit
1433 $user_unit->edit_date("now");
1434 $user_unit->create_date("now");
1435 $user_unit->editor($user_id);
1436 $user_unit->creator($user_id);
1438 return $e->die_event unless $e->create_serial_unit($user_unit);
1440 # save reference to new unit
1441 $item->unit($e->data->id);
1444 # Create notes if given by user
1445 if (ref($item->notes) and @{$item->notes}) {
1446 foreach my $note (@{$item->notes}) {
1447 $note->creator($user_id);
1448 $note->create_date("now");
1450 return $e->die_event unless $e->create_serial_item_note($note);
1453 $item->clear_notes; # They're saved; we no longer want them here.
1456 # Set the incontrovertibles on the item
1457 $item->status("Received");
1458 $item->date_received("now");
1459 $item->edit_date("now");
1460 $item->editor($user_id);
1462 return $e->die_event unless $e->update_serial_item($item);
1464 # send client a response
1465 $client->respond($item->id);
1468 $e->commit or return $e->die_event;
1476 my $skip_call_number = shift;
1477 my $barcode = shift;
1479 my $attr = $mode . '_unit_template';
1480 my $template = $editor->retrieve_asset_copy_template($sdist->$attr) or
1481 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_COPY_TEMPLATE");
1483 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 );
1485 my $unit = new Fieldmapper::serial::unit;
1486 foreach my $part (@parts) {
1487 my $value = $template->$part;
1488 next if !defined($value);
1489 $unit->$part($value);
1492 # ignore circ_lib in template, set to distribution holding_lib
1493 $unit->circ_lib($sdist->holding_lib);
1494 $unit->creator($editor->requestor->id);
1495 $unit->editor($editor->requestor->id);
1497 unless ($skip_call_number) {
1498 $attr = $mode . '_call_number';
1499 my $cn = $sdist->$attr or
1500 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_CALL_NUMBER");
1502 $unit->call_number($cn);
1506 $unit->barcode($barcode);
1508 $unit->barcode('AUTO');
1510 $unit->sort_key('');
1511 $unit->summary_contents('');
1512 $unit->detailed_contents('');
1518 sub _summarize_contents {
1520 my $issuances = shift;
1522 # create MFHD record
1523 my $mfhd = MFHD->new(MARC::Record->new());
1526 my @scap_fields_ordered;
1529 foreach my $issuance (@$issuances) {
1530 my $scap_id = $issuance->caption_and_pattern;
1531 next if (!$scap_id); # skip issuances with no caption/pattern
1535 # if this is the first appearance of this scap, retrieve it and add it to the temporary record
1536 if (!exists $scaps{$issuance->caption_and_pattern}) {
1537 $scaps{$scap_id} = $editor->retrieve_serial_caption_and_pattern($scap_id);
1538 $scap = $scaps{$scap_id};
1539 $scap_field = _revive_caption($scap);
1540 $scap_fields{$scap_id} = $scap_field;
1541 push(@scap_fields_ordered, $scap_field);
1542 $scap_field->update('8' => $link_id);
1543 $mfhd->append_fields($scap_field);
1546 $scap = $scaps{$scap_id};
1547 $scap_field = $scap_fields{$scap_id};
1550 $mfhd->append_fields(_revive_holding($issuance->holding_code, $scap_field, $seqno));
1554 my @formatted_parts;
1555 foreach my $scap_field (@scap_fields_ordered) { #TODO: use generic MFHD "summarize" method, once available
1556 my @updated_holdings = $mfhd->get_compressed_holdings($scap_field);
1557 foreach my $holding (@updated_holdings) {
1558 push(@formatted_parts, $holding->format);
1562 return ($mfhd, \@formatted_parts);
1565 ##########################################################################
1568 __PACKAGE__->register_method(
1569 method => 'fetch_notes',
1570 api_name => 'open-ils.serial.item_note.retrieve.all',
1572 Returns an array of copy note objects.
1573 @param args A named hash of parameters including:
1574 authtoken : Required if viewing non-public notes
1575 item_id : The id of the item whose notes we want to retrieve
1576 pub : True if all the caller wants are public notes
1577 @return An array of note objects
1581 __PACKAGE__->register_method(
1582 method => 'fetch_notes',
1583 api_name => 'open-ils.serial.subscription_note.retrieve.all',
1585 Returns an array of copy note objects.
1586 @param args A named hash of parameters including:
1587 authtoken : Required if viewing non-public notes
1588 subscription_id : The id of the item whose notes we want to retrieve
1589 pub : True if all the caller wants are public notes
1590 @return An array of note objects
1594 __PACKAGE__->register_method(
1595 method => 'fetch_notes',
1596 api_name => 'open-ils.serial.distribution_note.retrieve.all',
1598 Returns an array of copy note objects.
1599 @param args A named hash of parameters including:
1600 authtoken : Required if viewing non-public notes
1601 distribution_id : The id of the item whose notes we want to retrieve
1602 pub : True if all the caller wants are public notes
1603 @return An array of note objects
1607 # TODO: revisit this method to consider replacing cstore direct calls
1609 my( $self, $connection, $args ) = @_;
1611 $self->api_name =~ /serial\.(\w*)_note/;
1614 my $id = $$args{object_id};
1615 my $authtoken = $$args{authtoken};
1619 return $U->cstorereq(
1620 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic',
1621 { $type => $id, pub => 't' } );
1623 # FIXME: restore perm check
1624 # ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
1625 # return $evt if $evt;
1626 return $U->cstorereq(
1627 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic', {$type => $id} );
1633 __PACKAGE__->register_method(
1634 method => 'create_note',
1635 api_name => 'open-ils.serial.item_note.create',
1637 Creates a new item note
1638 @param authtoken The login session key
1639 @param note The note object to create
1640 @return The id of the new note object
1644 __PACKAGE__->register_method(
1645 method => 'create_note',
1646 api_name => 'open-ils.serial.subscription_note.create',
1648 Creates a new subscription note
1649 @param authtoken The login session key
1650 @param note The note object to create
1651 @return The id of the new note object
1655 __PACKAGE__->register_method(
1656 method => 'create_note',
1657 api_name => 'open-ils.serial.distribution_note.create',
1659 Creates a new distribution note
1660 @param authtoken The login session key
1661 @param note The note object to create
1662 @return The id of the new note object
1667 my( $self, $connection, $authtoken, $note ) = @_;
1669 $self->api_name =~ /serial\.(\w*)_note/;
1672 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1673 return $e->event unless $e->checkauth;
1675 # FIXME: restore permission support
1676 # my $item = $e->retrieve_serial_item(
1682 # return $e->event unless
1683 # $e->allowed('CREATE_COPY_NOTE', $item->call_number->owning_lib);
1685 $note->create_date('now');
1686 $note->creator($e->requestor->id);
1687 $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
1690 my $method = "create_serial_${type}_note";
1691 $e->$method($note) or return $e->event;
1696 __PACKAGE__->register_method(
1697 method => 'delete_note',
1698 api_name => 'open-ils.serial.item_note.delete',
1700 Deletes an existing item note
1701 @param authtoken The login session key
1702 @param noteid The id of the note to delete
1703 @return 1 on success - Event otherwise.
1707 __PACKAGE__->register_method(
1708 method => 'delete_note',
1709 api_name => 'open-ils.serial.subscription_note.delete',
1711 Deletes an existing subscription note
1712 @param authtoken The login session key
1713 @param noteid The id of the note to delete
1714 @return 1 on success - Event otherwise.
1718 __PACKAGE__->register_method(
1719 method => 'delete_note',
1720 api_name => 'open-ils.serial.distribution_note.delete',
1722 Deletes an existing distribution note
1723 @param authtoken The login session key
1724 @param noteid The id of the note to delete
1725 @return 1 on success - Event otherwise.
1730 my( $self, $conn, $authtoken, $noteid ) = @_;
1732 $self->api_name =~ /serial\.(\w*)_note/;
1735 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1736 return $e->die_event unless $e->checkauth;
1738 my $method = "retrieve_serial_${type}_note";
1739 my $note = $e->$method([
1741 ]) or return $e->die_event;
1743 # FIXME: restore permissions check
1744 # if( $note->creator ne $e->requestor->id ) {
1745 # return $e->die_event unless
1746 # $e->allowed('DELETE_COPY_NOTE', $note->item->call_number->owning_lib);
1749 $method = "delete_serial_${type}_note";
1750 $e->$method($note) or return $e->die_event;
1756 ##########################################################################
1757 # subscription methods
1759 __PACKAGE__->register_method(
1760 method => 'fleshed_ssub_alter',
1761 api_name => 'open-ils.serial.subscription.fleshed.batch.update',
1765 desc => 'Receives an array of one or more subscriptions and updates the database as needed',
1767 name => 'authtoken',
1768 desc => 'Authtoken for current user session',
1772 name => 'subscriptions',
1773 desc => 'Array of fleshed subscriptions',
1779 desc => 'Returns 1 if successful, event if failed',
1785 sub fleshed_ssub_alter {
1786 my( $self, $conn, $auth, $ssubs ) = @_;
1787 return 1 unless ref $ssubs;
1788 my( $reqr, $evt ) = $U->checkses($auth);
1789 return $evt if $evt;
1790 my $editor = new_editor(requestor => $reqr, xact => 1);
1791 my $override = $self->api_name =~ /override/;
1793 # TODO: permission check
1794 # return $editor->event unless
1795 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
1797 for my $ssub (@$ssubs) {
1799 my $ssubid = $ssub->id;
1801 if( $ssub->isdeleted ) {
1802 $evt = _delete_ssub( $editor, $override, $ssub);
1803 } elsif( $ssub->isnew ) {
1804 _cleanse_dates($ssub, ['start_date','end_date']);
1805 $evt = _create_ssub( $editor, $ssub );
1807 _cleanse_dates($ssub, ['start_date','end_date']);
1808 $evt = _update_ssub( $editor, $override, $ssub );
1813 $logger->info("fleshed subscription-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
1817 $logger->debug("subscription-alter: done updating subscription batch");
1819 $logger->info("fleshed subscription-alter successfully updated ".scalar(@$ssubs)." subscriptions");
1824 my ($editor, $override, $ssub) = @_;
1825 $logger->info("subscription-alter: delete subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1826 my $sdists = $editor->search_serial_distribution(
1827 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1828 my $cps = $editor->search_serial_caption_and_pattern(
1829 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1830 my $sisses = $editor->search_serial_issuance(
1831 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1832 return OpenILS::Event->new(
1833 'SERIAL_SUBSCRIPTION_NOT_EMPTY', payload => $ssub->id ) if (@$sdists or @$cps or @$sisses);
1835 return $editor->event unless $editor->delete_serial_subscription($ssub);
1840 my ($editor, $ssub) = @_;
1842 $logger->info("subscription-alter: new subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1843 return $editor->event unless $editor->create_serial_subscription($ssub);
1848 my ($editor, $override, $ssub) = @_;
1850 $logger->info("subscription-alter: retrieving subscription ".$ssub->id);
1851 my $orig_ssub = $editor->retrieve_serial_subscription($ssub->id);
1853 $logger->info("subscription-alter: original subscription ".OpenSRF::Utils::JSON->perl2JSON($orig_ssub));
1854 $logger->info("subscription-alter: updated subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1855 return $editor->event unless $editor->update_serial_subscription($ssub);
1859 __PACKAGE__->register_method(
1860 method => "fleshed_serial_subscription_retrieve_batch",
1862 api_name => "open-ils.serial.subscription.fleshed.batch.retrieve"
1865 sub fleshed_serial_subscription_retrieve_batch {
1866 my( $self, $client, $ids ) = @_;
1867 # FIXME: permissions?
1868 $logger->info("Fetching fleshed subscriptions @$ids");
1869 return $U->cstorereq(
1870 "open-ils.cstore.direct.serial.subscription.search.atomic",
1873 flesh_fields => {ssub => [ qw/owning_lib notes/ ]}
1877 __PACKAGE__->register_method(
1878 method => "retrieve_sub_tree",
1880 api_name => "open-ils.serial.subscription_tree.retrieve"
1883 __PACKAGE__->register_method(
1884 method => "retrieve_sub_tree",
1885 api_name => "open-ils.serial.subscription_tree.global.retrieve"
1888 sub retrieve_sub_tree {
1890 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
1892 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
1896 # TODO: permission support
1897 if(!@org_ids and $user_session) {
1899 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
1900 @org_ids = ($user_obj->home_ou);
1903 if( $self->api_name =~ /global/ ) {
1904 return _build_subs_list( { record_entry => $docid } ); # TODO: filter for !deleted, or active?
1909 for my $orgid (@org_ids) {
1910 my $subs = _build_subs_list(
1911 { record_entry => $docid, owning_lib => $orgid } );# TODO: filter for !deleted, or active?
1912 push( @all_subs, @$subs );
1921 sub _build_subs_list {
1922 my $search_hash = shift;
1924 #$search_hash->{deleted} = 'f';
1925 my $e = new_editor();
1927 my $subs = $e->search_serial_subscription([$search_hash, { 'order_by' => {'ssub' => 'id'} }]);
1931 for my $sub (@$subs) {
1933 # TODO: filter on !deleted?
1934 my $dists = $e->search_serial_distribution(
1935 [{ subscription => $sub->id }, { 'order_by' => {'sdist' => 'label'} }]
1938 #$dists = [ sort { $a->label cmp $b->label } @$dists ];
1940 $sub->distributions($dists);
1942 # TODO: filter on !deleted?
1943 my $issuances = $e->search_serial_issuance(
1944 [{ subscription => $sub->id }, { 'order_by' => {'siss' => 'label'} }]
1947 #$issuances = [ sort { $a->label cmp $b->label } @$issuances ];
1948 $sub->issuances($issuances);
1950 # TODO: filter on !deleted?
1951 my $scaps = $e->search_serial_caption_and_pattern(
1952 [{ subscription => $sub->id }, { 'order_by' => {'scap' => 'id'} }]
1955 #$scaps = [ sort { $a->id cmp $b->id } @$scaps ];
1956 $sub->scaps($scaps);
1957 push( @built_subs, $sub );
1960 return \@built_subs;
1964 __PACKAGE__->register_method(
1965 method => "subscription_orgs_for_title",
1967 api_name => "open-ils.serial.subscription.retrieve_orgs_by_title"
1970 sub subscription_orgs_for_title {
1971 my( $self, $client, $record_id ) = @_;
1973 my $subs = $U->simple_scalar_request(
1975 "open-ils.cstore.direct.serial.subscription.search.atomic",
1976 { record_entry => $record_id }); # TODO: filter on !deleted?
1978 my $orgs = { map {$_->owning_lib => 1 } @$subs };
1979 return [ keys %$orgs ];
1983 ##########################################################################
1984 # distribution methods
1986 __PACKAGE__->register_method(
1987 method => 'fleshed_sdist_alter',
1988 api_name => 'open-ils.serial.distribution.fleshed.batch.update',
1992 desc => 'Receives an array of one or more distributions and updates the database as needed',
1994 name => 'authtoken',
1995 desc => 'Authtoken for current user session',
1999 name => 'distributions',
2000 desc => 'Array of fleshed distributions',
2006 desc => 'Returns 1 if successful, event if failed',
2012 sub fleshed_sdist_alter {
2013 my( $self, $conn, $auth, $sdists ) = @_;
2014 return 1 unless ref $sdists;
2015 my( $reqr, $evt ) = $U->checkses($auth);
2016 return $evt if $evt;
2017 my $editor = new_editor(requestor => $reqr, xact => 1);
2018 my $override = $self->api_name =~ /override/;
2020 # TODO: permission check
2021 # return $editor->event unless
2022 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2024 for my $sdist (@$sdists) {
2025 my $sdistid = $sdist->id;
2027 if( $sdist->isdeleted ) {
2028 $evt = _delete_sdist( $editor, $override, $sdist);
2029 } elsif( $sdist->isnew ) {
2030 $evt = _create_sdist( $editor, $sdist );
2032 $evt = _update_sdist( $editor, $override, $sdist );
2037 $logger->info("fleshed distribution-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2041 $logger->debug("distribution-alter: done updating distribution batch");
2043 $logger->info("fleshed distribution-alter successfully updated ".scalar(@$sdists)." distributions");
2048 my ($editor, $override, $sdist) = @_;
2049 $logger->info("distribution-alter: delete distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2050 return $editor->event unless $editor->delete_serial_distribution($sdist);
2055 my ($editor, $sdist) = @_;
2057 $logger->info("distribution-alter: new distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2058 return $editor->event unless $editor->create_serial_distribution($sdist);
2060 # create summaries too
2061 my $summary = new Fieldmapper::serial::basic_summary;
2062 $summary->distribution($sdist->id);
2063 $summary->generated_coverage('');
2064 return $editor->event unless $editor->create_serial_basic_summary($summary);
2065 $summary = new Fieldmapper::serial::supplement_summary;
2066 $summary->distribution($sdist->id);
2067 $summary->generated_coverage('');
2068 return $editor->event unless $editor->create_serial_supplement_summary($summary);
2069 $summary = new Fieldmapper::serial::index_summary;
2070 $summary->distribution($sdist->id);
2071 $summary->generated_coverage('');
2072 return $editor->event unless $editor->create_serial_index_summary($summary);
2074 # create a starter stream (TODO: reconsider this)
2075 my $stream = new Fieldmapper::serial::stream;
2076 $stream->distribution($sdist->id);
2077 return $editor->event unless $editor->create_serial_stream($stream);
2083 my ($editor, $override, $sdist) = @_;
2085 $logger->info("distribution-alter: retrieving distribution ".$sdist->id);
2086 my $orig_sdist = $editor->retrieve_serial_distribution($sdist->id);
2088 $logger->info("distribution-alter: original distribution ".OpenSRF::Utils::JSON->perl2JSON($orig_sdist));
2089 $logger->info("distribution-alter: updated distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2090 return $editor->event unless $editor->update_serial_distribution($sdist);
2094 __PACKAGE__->register_method(
2095 method => "fleshed_serial_distribution_retrieve_batch",
2097 api_name => "open-ils.serial.distribution.fleshed.batch.retrieve"
2100 sub fleshed_serial_distribution_retrieve_batch {
2101 my( $self, $client, $ids ) = @_;
2102 # FIXME: permissions?
2103 $logger->info("Fetching fleshed distributions @$ids");
2104 return $U->cstorereq(
2105 "open-ils.cstore.direct.serial.distribution.search.atomic",
2108 flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams / ]}
2112 __PACKAGE__->register_method(
2113 method => "retrieve_dist_tree",
2115 api_name => "open-ils.serial.distribution_tree.retrieve"
2118 __PACKAGE__->register_method(
2119 method => "retrieve_dist_tree",
2120 api_name => "open-ils.serial.distribution_tree.global.retrieve"
2123 sub retrieve_dist_tree {
2124 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2126 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2130 # TODO: permission support
2131 if(!@org_ids and $user_session) {
2133 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2134 @org_ids = ($user_obj->home_ou);
2137 my $e = new_editor();
2139 if( $self->api_name =~ /global/ ) {
2140 return $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }},
2142 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 / ]},
2143 order_by => {'sdist' => 'id'},
2144 'join' => {'ssub' => {}}
2146 ]); # TODO: filter for !deleted?
2150 for my $orgid (@org_ids) {
2151 my $dists = $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }, holding_lib => $orgid},
2153 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 / ]},
2154 order_by => {'sdist' => 'id'},
2155 'join' => {'ssub' => {}}
2157 ]); # TODO: filter for !deleted?
2158 push( @all_dists, @$dists ) if $dists;
2168 __PACKAGE__->register_method(
2169 method => "distribution_orgs_for_title",
2171 api_name => "open-ils.serial.distribution.retrieve_orgs_by_title"
2174 sub distribution_orgs_for_title {
2175 my( $self, $client, $record_id ) = @_;
2177 my $dists = $U->cstorereq(
2178 "open-ils.cstore.direct.serial.distribution.search.atomic",
2179 { '+ssub' => { record_entry => $record_id } },
2180 { 'join' => {'ssub' => {}} }); # TODO: filter on !deleted?
2182 my $orgs = { map {$_->holding_lib => 1 } @$dists };
2183 return [ keys %$orgs ];
2187 ##########################################################################
2188 # caption and pattern methods
2190 __PACKAGE__->register_method(
2191 method => 'scap_alter',
2192 api_name => 'open-ils.serial.caption_and_pattern.batch.update',
2196 desc => 'Receives an array of one or more caption and patterns and updates the database as needed',
2198 name => 'authtoken',
2199 desc => 'Authtoken for current user session',
2204 desc => 'Array of caption and patterns',
2210 desc => 'Returns 1 if successful, event if failed',
2217 my( $self, $conn, $auth, $scaps ) = @_;
2218 return 1 unless ref $scaps;
2219 my( $reqr, $evt ) = $U->checkses($auth);
2220 return $evt if $evt;
2221 my $editor = new_editor(requestor => $reqr, xact => 1);
2222 my $override = $self->api_name =~ /override/;
2224 # TODO: permission check
2225 # return $editor->event unless
2226 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2228 for my $scap (@$scaps) {
2229 my $scapid = $scap->id;
2231 if( $scap->isdeleted ) {
2232 $evt = _delete_scap( $editor, $override, $scap);
2233 } elsif( $scap->isnew ) {
2234 $evt = _create_scap( $editor, $scap );
2236 $evt = _update_scap( $editor, $override, $scap );
2241 $logger->info("caption_and_pattern-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2245 $logger->debug("caption_and_pattern-alter: done updating caption_and_pattern batch");
2247 $logger->info("caption_and_pattern-alter successfully updated ".scalar(@$scaps)." caption_and_patterns");
2252 my ($editor, $override, $scap) = @_;
2253 $logger->info("caption_and_pattern-alter: delete caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2254 my $sisses = $editor->search_serial_issuance(
2255 { caption_and_pattern => $scap->id }, { limit => 1 } ); #TODO: 'deleted' support?
2256 return OpenILS::Event->new(
2257 'SERIAL_CAPTION_AND_PATTERN_HAS_ISSUANCES', payload => $scap->id ) if (@$sisses);
2259 return $editor->event unless $editor->delete_serial_caption_and_pattern($scap);
2264 my ($editor, $scap) = @_;
2266 $logger->info("caption_and_pattern-alter: new caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2267 return $editor->event unless $editor->create_serial_caption_and_pattern($scap);
2272 my ($editor, $override, $scap) = @_;
2274 $logger->info("caption_and_pattern-alter: retrieving caption_and_pattern ".$scap->id);
2275 my $orig_scap = $editor->retrieve_serial_caption_and_pattern($scap->id);
2277 $logger->info("caption_and_pattern-alter: original caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($orig_scap));
2278 $logger->info("caption_and_pattern-alter: updated caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2279 return $editor->event unless $editor->update_serial_caption_and_pattern($scap);
2283 __PACKAGE__->register_method(
2284 method => "serial_caption_and_pattern_retrieve_batch",
2286 api_name => "open-ils.serial.caption_and_pattern.batch.retrieve"
2289 sub serial_caption_and_pattern_retrieve_batch {
2290 my( $self, $client, $ids ) = @_;
2291 $logger->info("Fetching caption_and_patterns @$ids");
2292 return $U->cstorereq(
2293 "open-ils.cstore.direct.serial.caption_and_pattern.search.atomic",
2298 ##########################################################################
2301 __PACKAGE__->register_method(
2302 method => 'sstr_alter',
2303 api_name => 'open-ils.serial.stream.batch.update',
2307 desc => 'Receives an array of one or more streams and updates the database as needed',
2309 name => 'authtoken',
2310 desc => 'Authtoken for current user session',
2315 desc => 'Array of streams',
2321 desc => 'Returns 1 if successful, event if failed',
2328 my( $self, $conn, $auth, $sstrs ) = @_;
2329 return 1 unless ref $sstrs;
2330 my( $reqr, $evt ) = $U->checkses($auth);
2331 return $evt if $evt;
2332 my $editor = new_editor(requestor => $reqr, xact => 1);
2333 my $override = $self->api_name =~ /override/;
2335 # TODO: permission check
2336 # return $editor->event unless
2337 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2339 for my $sstr (@$sstrs) {
2340 my $sstrid = $sstr->id;
2342 if( $sstr->isdeleted ) {
2343 $evt = _delete_sstr( $editor, $override, $sstr);
2344 } elsif( $sstr->isnew ) {
2345 $evt = _create_sstr( $editor, $sstr );
2347 $evt = _update_sstr( $editor, $override, $sstr );
2352 $logger->info("stream-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2356 $logger->debug("stream-alter: done updating stream batch");
2358 $logger->info("stream-alter successfully updated ".scalar(@$sstrs)." streams");
2363 my ($editor, $override, $sstr) = @_;
2364 $logger->info("stream-alter: delete stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2365 my $sitems = $editor->search_serial_item(
2366 { stream => $sstr->id }, { limit => 1 } ); #TODO: 'deleted' support?
2367 return OpenILS::Event->new(
2368 'SERIAL_STREAM_HAS_ITEMS', payload => $sstr->id ) if (@$sitems);
2370 return $editor->event unless $editor->delete_serial_stream($sstr);
2375 my ($editor, $sstr) = @_;
2377 $logger->info("stream-alter: new stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2378 return $editor->event unless $editor->create_serial_stream($sstr);
2383 my ($editor, $override, $sstr) = @_;
2385 $logger->info("stream-alter: retrieving stream ".$sstr->id);
2386 my $orig_sstr = $editor->retrieve_serial_stream($sstr->id);
2388 $logger->info("stream-alter: original stream ".OpenSRF::Utils::JSON->perl2JSON($orig_sstr));
2389 $logger->info("stream-alter: updated stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2390 return $editor->event unless $editor->update_serial_stream($sstr);
2394 __PACKAGE__->register_method(
2395 method => "serial_stream_retrieve_batch",
2397 api_name => "open-ils.serial.stream.batch.retrieve"
2400 sub serial_stream_retrieve_batch {
2401 my( $self, $client, $ids ) = @_;
2402 $logger->info("Fetching streams @$ids");
2403 return $U->cstorereq(
2404 "open-ils.cstore.direct.serial.stream.search.atomic",
2410 ##########################################################################
2413 __PACKAGE__->register_method(
2414 method => 'sum_alter',
2415 api_name => 'open-ils.serial.basic_summary.batch.update',
2419 desc => 'Receives an array of one or more summaries and updates the database as needed',
2421 name => 'authtoken',
2422 desc => 'Authtoken for current user session',
2427 desc => 'Array of basic summaries',
2433 desc => 'Returns 1 if successful, event if failed',
2439 __PACKAGE__->register_method(
2440 method => 'sum_alter',
2441 api_name => 'open-ils.serial.supplement_summary.batch.update',
2445 desc => 'Receives an array of one or more summaries and updates the database as needed',
2447 name => 'authtoken',
2448 desc => 'Authtoken for current user session',
2453 desc => 'Array of supplement summaries',
2459 desc => 'Returns 1 if successful, event if failed',
2465 __PACKAGE__->register_method(
2466 method => 'sum_alter',
2467 api_name => 'open-ils.serial.index_summary.batch.update',
2471 desc => 'Receives an array of one or more summaries and updates the database as needed',
2473 name => 'authtoken',
2474 desc => 'Authtoken for current user session',
2479 desc => 'Array of index summaries',
2485 desc => 'Returns 1 if successful, event if failed',
2492 my( $self, $conn, $auth, $sums ) = @_;
2493 return 1 unless ref $sums;
2495 $self->api_name =~ /serial\.(\w*)_summary/;
2498 my( $reqr, $evt ) = $U->checkses($auth);
2499 return $evt if $evt;
2500 my $editor = new_editor(requestor => $reqr, xact => 1);
2501 my $override = $self->api_name =~ /override/;
2503 # TODO: permission check
2504 # return $editor->event unless
2505 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2507 for my $sum (@$sums) {
2508 my $sumid = $sum->id;
2510 # XXX: (for now, at least) summaries should be created/deleted by the distribution functions
2511 if( $sum->isdeleted ) {
2512 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2513 } elsif( $sum->isnew ) {
2514 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2516 $evt = _update_sum( $editor, $override, $sum, $type );
2521 $logger->info("${type}_summary-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2525 $logger->debug("${type}_summary-alter: done updating ${type}_summary batch");
2527 $logger->info("${type}_summary-alter successfully updated ".scalar(@$sums)." ${type}_summaries");
2532 my ($editor, $override, $sum, $type) = @_;
2534 $logger->info("${type}_summary-alter: retrieving ${type}_summary ".$sum->id);
2535 my $retrieve_method = "retrieve_serial_${type}_summary";
2536 my $orig_sum = $editor->$retrieve_method($sum->id);
2538 $logger->info("${type}_summary-alter: original ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($orig_sum));
2539 $logger->info("${type}_summary-alter: updated ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($sum));
2540 my $update_method = "update_serial_${type}_summary";
2541 return $editor->event unless $editor->$update_method($sum);
2545 __PACKAGE__->register_method(
2546 method => "serial_summary_retrieve_batch",
2548 api_name => "open-ils.serial.basic_summary.batch.retrieve"
2551 __PACKAGE__->register_method(
2552 method => "serial_summary_retrieve_batch",
2554 api_name => "open-ils.serial.supplement_summary.batch.retrieve"
2557 __PACKAGE__->register_method(
2558 method => "serial_summary_retrieve_batch",
2560 api_name => "open-ils.serial.index_summary.batch.retrieve"
2563 sub serial_summary_retrieve_batch {
2564 my( $self, $client, $ids ) = @_;
2566 $self->api_name =~ /serial\.(\w*)_summary/;
2569 $logger->info("Fetching ${type}_summaries @$ids");
2570 return $U->cstorereq(
2571 "open-ils.cstore.direct.serial.".$type."_summary.search.atomic",
2577 ##########################################################################
2580 __PACKAGE__->register_method(
2581 "method" => "bre_by_identifier",
2582 "api_name" => "open-ils.serial.biblio.record_entry.by_identifier",
2585 "desc" => "Find instances of biblio.record_entry given a search token" .
2586 " that could be a value for any identifier defined in " .
2587 "config.metabib_field",
2589 {"desc" => "Search token", "type" => "string"},
2590 {"desc" => "Options: require_subscriptions, add_mvr, is_actual_id" .
2591 " (all boolean)", "type" => "object"}
2594 "desc" => "Any matching BREs, or if the add_mvr option is true, " .
2595 "objects with a 'bre' key/value pair, and an 'mvr' " .
2596 "key-value pair. BREs have subscriptions fleshed on.",
2602 sub bre_by_identifier {
2603 my ($self, $client, $term, $options) = @_;
2605 return new OpenILS::Event("BAD_PARAMS") unless $term;
2608 my $e = new_editor();
2612 if ($options->{"is_actual_id"}) {
2616 $e->search_config_metabib_field({"field_class" => "identifier"})
2617 or return $e->die_event;
2619 my @identifiers = map { $_->name } @$cmf;
2620 my $query = join(" || ", map { "id|$_: $term" } @identifiers);
2622 my $search = create OpenSRF::AppSession("open-ils.search");
2623 my $search_result = $search->request(
2624 "open-ils.search.biblio.multiclass.query.staff", {}, $query
2626 $search->disconnect;
2628 # Un-nest results. They tend to look like [[1],[2],[3]] for some reason.
2629 @ids = map { @{$_} } @{$search_result->{"ids"}};
2637 my $bre = $e->search_biblio_record_entry([
2639 "flesh" => 2, "flesh_fields" => {
2640 "bre" => ["subscriptions"],
2641 "ssub" => ["owning_lib"]
2644 ]) or return $e->die_event;
2646 if (@$bre && $options->{"require_subscriptions"}) {
2647 $bre = [ grep { @{$_->subscriptions} } @$bre ];
2652 if (@$bre) { # re-evaluate after possible grep
2653 if ($options->{"add_mvr"}) {
2655 {"bre" => $_, "mvr" => _get_mvr($_->id)}
2658 $client->respond($_) foreach (@$bre);
2665 __PACKAGE__->register_method(
2666 "method" => "get_receivable_items",
2667 "api_name" => "open-ils.serial.items.receivable.by_subscription",
2670 "desc" => "Return all receivable items under a given subscription",
2672 {"desc" => "Authtoken", "type" => "string"},
2673 {"desc" => "Subscription ID", "type" => "number"},
2676 "desc" => "All receivable items under a given subscription",
2682 __PACKAGE__->register_method(
2683 "method" => "get_receivable_items",
2684 "api_name" => "open-ils.serial.items.receivable.by_issuance",
2687 "desc" => "Return all receivable items under a given issuance",
2689 {"desc" => "Authtoken", "type" => "string"},
2690 {"desc" => "Issuance ID", "type" => "number"},
2693 "desc" => "All receivable items under a given issuance",
2699 sub get_receivable_items {
2700 my ($self, $client, $auth, $term) = @_;
2702 my $e = new_editor("authtoken" => $auth);
2703 return $e->die_event unless $e->checkauth;
2707 my $by = ($self->api_name =~ /by_(\w+)$/)[0];
2710 "issuance" => {"issuance" => $term},
2711 "subscription" => {"+siss" => {"subscription" => $term}}
2714 my $item_ids = $e->json_query(
2716 "select" => {"sitem" => ["id"]},
2717 "from" => {"sitem" => "siss"},
2719 %{$where{$by}}, "date_received" => undef
2721 "order_by" => {"sitem" => ["id"]}
2723 ) or return $e->die_event;
2725 return undef unless @$item_ids;
2727 foreach (map { $_->{"id"} } @$item_ids) {
2729 $e->retrieve_serial_item([
2733 "sitem" => ["stream", "issuance"],
2734 "sstr" => ["distribution"],
2735 "sdist" => ["holding_lib"]
2746 __PACKAGE__->register_method(
2747 "method" => "get_receivable_issuances",
2748 "api_name" => "open-ils.serial.issuances.receivable",
2751 "desc" => "Return all issuances with receivable items given " .
2752 "a subscription ID",
2754 {"desc" => "Authtoken", "type" => "string"},
2755 {"desc" => "Subscription ID", "type" => "number"},
2758 "desc" => "All issuances with receivable items " .
2759 "(but not the items themselves)", "type" => "object"
2764 sub get_receivable_issuances {
2765 my ($self, $client, $auth, $sub_id) = @_;
2767 my $e = new_editor("authtoken" => $auth);
2768 return $e->die_event unless $e->checkauth;
2772 my $issuance_ids = $e->json_query({
2775 {"transform" => "distinct", "column" => "id"},
2779 "from" => {"siss" => "sitem"},
2781 "subscription" => $sub_id,
2782 "+sitem" => {"date_received" => undef}
2785 "siss" => {"date_published" => {"direction" => "asc"}}
2788 }) or return $e->die_event;
2790 $client->respond($e->retrieve_serial_issuance($_->{"id"}))
2791 foreach (@$issuance_ids);