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;
1261 return 0 if not @$unit;
1263 $e->retrieve_serial_unit($unit->[0]->{"id"}) or $e->die_event;
1266 sub move_previous_unit {
1267 my ($e, $prev_iss, $curr_item, $new_loc) = @_;
1269 my $prev_unit = _unit_by_iss_and_str($e,$prev_iss,$curr_item->stream);
1270 return $prev_unit if defined $U->event_code($prev_unit);
1271 return 0 if not $prev_unit;
1273 if ($prev_unit->location != $new_loc) {
1274 $prev_unit->location($new_loc);
1275 $e->update_serial_unit($prev_unit) or return $e->die_event;
1280 # _previous_issuance() assumes $existing is an ordered array
1281 sub _previous_issuance {
1282 my ($existing, $issuance) = @_;
1284 my $last = $existing->[-1];
1285 return undef unless $last;
1286 return ($last->id == $issuance->id ? $existing->[-2] : $last);
1289 __PACKAGE__->register_method(
1290 "method" => "receive_items_one_unit_per",
1291 "api_name" => "open-ils.serial.receive_items.one_unit_per",
1296 "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",
1300 "desc" => "authtoken",
1305 "desc" => "array of serial items, possibly fleshed with units and definitely fleshed with stream->distribution",
1310 "desc" => "id of bib record these items are associated with
1311 (XXX could/should be derived from items)",
1316 "desc" => "The item ID for each item successfully received",
1322 sub receive_items_one_unit_per {
1323 # XXX This function may be temporary, as it does some of what
1324 # unitize_items() does, just in a different way.
1325 my ($self, $client, $auth, $items, $record) = @_;
1327 my $e = new_editor("authtoken" => $auth, "xact" => 1);
1328 return $e->die_event unless $e->checkauth;
1329 return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
1331 my $prev_loc_setting_map = {};
1332 my $user_id = $e->requestor->id;
1334 # Get a list of all the non-virtual field names in a serial::unit for
1335 # merging given unit objects with template-built units later.
1336 # XXX move this somewhere global so it isn't re-run all the time
1337 my $all_unit_fields =
1338 $Fieldmapper::fieldmap->{"Fieldmapper::serial::unit"}->{"fields"};
1339 my @real_unit_fields = grep {
1340 not $all_unit_fields->{$_}->{"virtual"}
1341 } keys %$all_unit_fields;
1343 foreach my $item (@$items) {
1344 # Note that we expect a certain fleshing on the items we're getting.
1345 my $sdist = $item->stream->distribution;
1347 # Fetch a list of issuances with received copies already existing
1348 # on this distribution (and with the same holding type on the
1349 # issuance). This will be used in up to two places: once when building
1350 # a summary, once when changing the copy location of the previous
1352 my $issuances_received = _issuances_received($e, $item);
1353 if ($U->event_code($issuances_received)) {
1355 return $issuances_received;
1358 # Find out if we need to to deal with previous copy location changing.
1359 my $ou = $sdist->holding_lib->id;
1360 unless (exists $prev_loc_setting_map->{$ou}) {
1361 $prev_loc_setting_map->{$ou} = $U->ou_ancestor_setting_value(
1362 $ou, "serial.prev_issuance_copy_location", $e
1366 # If there is a previous copy location setting, we need the previous
1367 # issuance, from which we can in turn look up the item attached to the
1368 # same stream we're on now.
1369 if ($prev_loc_setting_map->{$ou}) {
1371 _previous_issuance($issuances_received, $item->issuance)) {
1373 # Now we can change the copy location of the previous unit,
1375 return $e->event if defined $U->event_code(
1377 $e, $prev_iss, $item, $prev_loc_setting_map->{$ou}
1383 # Create unit if given by user
1384 if (ref $item->unit) {
1385 # detach from the item, as we need to create separately
1386 my $user_unit = $item->unit;
1388 # get a unit based on associated template
1389 my $template_unit = _build_unit($e, $sdist, "receive", 1);
1390 if ($U->event_code($template_unit)) {
1392 $template_unit->{"note"} = "Item ID: " . $item->id;
1393 return $template_unit;
1396 # merge built unit with provided unit from user
1397 foreach (@real_unit_fields) {
1398 unless ($user_unit->$_) {
1399 $user_unit->$_($template_unit->$_);
1403 # Treat call number specially: the provided value from the
1404 # user will really be a string.
1405 if ($user_unit->call_number) {
1406 my $real_cn = _find_or_create_call_number(
1407 $e, $sdist->holding_lib->id,
1408 $user_unit->call_number, $record
1411 if ($U->event_code($real_cn)) {
1415 $user_unit->call_number($real_cn);
1419 my $evt = _prepare_unit_label(
1420 $e, $user_unit, $sdist, $item->issuance
1422 if ($U->event_code($evt)) {
1427 # create/update summary objects related to this distribution
1428 $evt = _prepare_summaries($e, $item, $issuances_received);
1429 if ($U->event_code($evt)) {
1434 # set the incontrovertibles on the unit
1435 $user_unit->edit_date("now");
1436 $user_unit->create_date("now");
1437 $user_unit->editor($user_id);
1438 $user_unit->creator($user_id);
1440 return $e->die_event unless $e->create_serial_unit($user_unit);
1442 # save reference to new unit
1443 $item->unit($e->data->id);
1446 # Create notes if given by user
1447 if (ref($item->notes) and @{$item->notes}) {
1448 foreach my $note (@{$item->notes}) {
1449 $note->creator($user_id);
1450 $note->create_date("now");
1452 return $e->die_event unless $e->create_serial_item_note($note);
1455 $item->clear_notes; # They're saved; we no longer want them here.
1458 # Set the incontrovertibles on the item
1459 $item->status("Received");
1460 $item->date_received("now");
1461 $item->edit_date("now");
1462 $item->editor($user_id);
1464 return $e->die_event unless $e->update_serial_item($item);
1466 # send client a response
1467 $client->respond($item->id);
1470 $e->commit or return $e->die_event;
1478 my $skip_call_number = shift;
1479 my $barcode = shift;
1481 my $attr = $mode . '_unit_template';
1482 my $template = $editor->retrieve_asset_copy_template($sdist->$attr) or
1483 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_COPY_TEMPLATE");
1485 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 );
1487 my $unit = new Fieldmapper::serial::unit;
1488 foreach my $part (@parts) {
1489 my $value = $template->$part;
1490 next if !defined($value);
1491 $unit->$part($value);
1494 # ignore circ_lib in template, set to distribution holding_lib
1495 $unit->circ_lib($sdist->holding_lib);
1496 $unit->creator($editor->requestor->id);
1497 $unit->editor($editor->requestor->id);
1499 unless ($skip_call_number) {
1500 $attr = $mode . '_call_number';
1501 my $cn = $sdist->$attr or
1502 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_CALL_NUMBER");
1504 $unit->call_number($cn);
1508 $unit->barcode($barcode);
1510 $unit->barcode('AUTO');
1512 $unit->sort_key('');
1513 $unit->summary_contents('');
1514 $unit->detailed_contents('');
1520 sub _summarize_contents {
1522 my $issuances = shift;
1524 # create MFHD record
1525 my $mfhd = MFHD->new(MARC::Record->new());
1528 my @scap_fields_ordered;
1531 foreach my $issuance (@$issuances) {
1532 my $scap_id = $issuance->caption_and_pattern;
1533 next if (!$scap_id); # skip issuances with no caption/pattern
1537 # if this is the first appearance of this scap, retrieve it and add it to the temporary record
1538 if (!exists $scaps{$issuance->caption_and_pattern}) {
1539 $scaps{$scap_id} = $editor->retrieve_serial_caption_and_pattern($scap_id);
1540 $scap = $scaps{$scap_id};
1541 $scap_field = _revive_caption($scap);
1542 $scap_fields{$scap_id} = $scap_field;
1543 push(@scap_fields_ordered, $scap_field);
1544 $scap_field->update('8' => $link_id);
1545 $mfhd->append_fields($scap_field);
1548 $scap = $scaps{$scap_id};
1549 $scap_field = $scap_fields{$scap_id};
1552 $mfhd->append_fields(_revive_holding($issuance->holding_code, $scap_field, $seqno));
1556 my @formatted_parts;
1557 foreach my $scap_field (@scap_fields_ordered) { #TODO: use generic MFHD "summarize" method, once available
1558 my @updated_holdings = $mfhd->get_compressed_holdings($scap_field);
1559 foreach my $holding (@updated_holdings) {
1560 push(@formatted_parts, $holding->format);
1564 return ($mfhd, \@formatted_parts);
1567 ##########################################################################
1570 __PACKAGE__->register_method(
1571 method => 'fetch_notes',
1572 api_name => 'open-ils.serial.item_note.retrieve.all',
1574 Returns an array of copy note objects.
1575 @param args A named hash of parameters including:
1576 authtoken : Required if viewing non-public notes
1577 item_id : The id of the item whose notes we want to retrieve
1578 pub : True if all the caller wants are public notes
1579 @return An array of note objects
1583 __PACKAGE__->register_method(
1584 method => 'fetch_notes',
1585 api_name => 'open-ils.serial.subscription_note.retrieve.all',
1587 Returns an array of copy note objects.
1588 @param args A named hash of parameters including:
1589 authtoken : Required if viewing non-public notes
1590 subscription_id : The id of the item whose notes we want to retrieve
1591 pub : True if all the caller wants are public notes
1592 @return An array of note objects
1596 __PACKAGE__->register_method(
1597 method => 'fetch_notes',
1598 api_name => 'open-ils.serial.distribution_note.retrieve.all',
1600 Returns an array of copy note objects.
1601 @param args A named hash of parameters including:
1602 authtoken : Required if viewing non-public notes
1603 distribution_id : The id of the item whose notes we want to retrieve
1604 pub : True if all the caller wants are public notes
1605 @return An array of note objects
1609 # TODO: revisit this method to consider replacing cstore direct calls
1611 my( $self, $connection, $args ) = @_;
1613 $self->api_name =~ /serial\.(\w*)_note/;
1616 my $id = $$args{object_id};
1617 my $authtoken = $$args{authtoken};
1621 return $U->cstorereq(
1622 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic',
1623 { $type => $id, pub => 't' } );
1625 # FIXME: restore perm check
1626 # ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
1627 # return $evt if $evt;
1628 return $U->cstorereq(
1629 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic', {$type => $id} );
1635 __PACKAGE__->register_method(
1636 method => 'create_note',
1637 api_name => 'open-ils.serial.item_note.create',
1639 Creates a new item note
1640 @param authtoken The login session key
1641 @param note The note object to create
1642 @return The id of the new note object
1646 __PACKAGE__->register_method(
1647 method => 'create_note',
1648 api_name => 'open-ils.serial.subscription_note.create',
1650 Creates a new subscription note
1651 @param authtoken The login session key
1652 @param note The note object to create
1653 @return The id of the new note object
1657 __PACKAGE__->register_method(
1658 method => 'create_note',
1659 api_name => 'open-ils.serial.distribution_note.create',
1661 Creates a new distribution note
1662 @param authtoken The login session key
1663 @param note The note object to create
1664 @return The id of the new note object
1669 my( $self, $connection, $authtoken, $note ) = @_;
1671 $self->api_name =~ /serial\.(\w*)_note/;
1674 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1675 return $e->event unless $e->checkauth;
1677 # FIXME: restore permission support
1678 # my $item = $e->retrieve_serial_item(
1684 # return $e->event unless
1685 # $e->allowed('CREATE_COPY_NOTE', $item->call_number->owning_lib);
1687 $note->create_date('now');
1688 $note->creator($e->requestor->id);
1689 $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
1692 my $method = "create_serial_${type}_note";
1693 $e->$method($note) or return $e->event;
1698 __PACKAGE__->register_method(
1699 method => 'delete_note',
1700 api_name => 'open-ils.serial.item_note.delete',
1702 Deletes an existing item note
1703 @param authtoken The login session key
1704 @param noteid The id of the note to delete
1705 @return 1 on success - Event otherwise.
1709 __PACKAGE__->register_method(
1710 method => 'delete_note',
1711 api_name => 'open-ils.serial.subscription_note.delete',
1713 Deletes an existing subscription note
1714 @param authtoken The login session key
1715 @param noteid The id of the note to delete
1716 @return 1 on success - Event otherwise.
1720 __PACKAGE__->register_method(
1721 method => 'delete_note',
1722 api_name => 'open-ils.serial.distribution_note.delete',
1724 Deletes an existing distribution note
1725 @param authtoken The login session key
1726 @param noteid The id of the note to delete
1727 @return 1 on success - Event otherwise.
1732 my( $self, $conn, $authtoken, $noteid ) = @_;
1734 $self->api_name =~ /serial\.(\w*)_note/;
1737 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1738 return $e->die_event unless $e->checkauth;
1740 my $method = "retrieve_serial_${type}_note";
1741 my $note = $e->$method([
1743 ]) or return $e->die_event;
1745 # FIXME: restore permissions check
1746 # if( $note->creator ne $e->requestor->id ) {
1747 # return $e->die_event unless
1748 # $e->allowed('DELETE_COPY_NOTE', $note->item->call_number->owning_lib);
1751 $method = "delete_serial_${type}_note";
1752 $e->$method($note) or return $e->die_event;
1758 ##########################################################################
1759 # subscription methods
1761 __PACKAGE__->register_method(
1762 method => 'fleshed_ssub_alter',
1763 api_name => 'open-ils.serial.subscription.fleshed.batch.update',
1767 desc => 'Receives an array of one or more subscriptions and updates the database as needed',
1769 name => 'authtoken',
1770 desc => 'Authtoken for current user session',
1774 name => 'subscriptions',
1775 desc => 'Array of fleshed subscriptions',
1781 desc => 'Returns 1 if successful, event if failed',
1787 sub fleshed_ssub_alter {
1788 my( $self, $conn, $auth, $ssubs ) = @_;
1789 return 1 unless ref $ssubs;
1790 my( $reqr, $evt ) = $U->checkses($auth);
1791 return $evt if $evt;
1792 my $editor = new_editor(requestor => $reqr, xact => 1);
1793 my $override = $self->api_name =~ /override/;
1795 # TODO: permission check
1796 # return $editor->event unless
1797 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
1799 for my $ssub (@$ssubs) {
1801 my $ssubid = $ssub->id;
1803 if( $ssub->isdeleted ) {
1804 $evt = _delete_ssub( $editor, $override, $ssub);
1805 } elsif( $ssub->isnew ) {
1806 _cleanse_dates($ssub, ['start_date','end_date']);
1807 $evt = _create_ssub( $editor, $ssub );
1809 _cleanse_dates($ssub, ['start_date','end_date']);
1810 $evt = _update_ssub( $editor, $override, $ssub );
1815 $logger->info("fleshed subscription-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
1819 $logger->debug("subscription-alter: done updating subscription batch");
1821 $logger->info("fleshed subscription-alter successfully updated ".scalar(@$ssubs)." subscriptions");
1826 my ($editor, $override, $ssub) = @_;
1827 $logger->info("subscription-alter: delete subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1828 my $sdists = $editor->search_serial_distribution(
1829 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1830 my $cps = $editor->search_serial_caption_and_pattern(
1831 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1832 my $sisses = $editor->search_serial_issuance(
1833 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1834 return OpenILS::Event->new(
1835 'SERIAL_SUBSCRIPTION_NOT_EMPTY', payload => $ssub->id ) if (@$sdists or @$cps or @$sisses);
1837 return $editor->event unless $editor->delete_serial_subscription($ssub);
1842 my ($editor, $ssub) = @_;
1844 $logger->info("subscription-alter: new subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1845 return $editor->event unless $editor->create_serial_subscription($ssub);
1850 my ($editor, $override, $ssub) = @_;
1852 $logger->info("subscription-alter: retrieving subscription ".$ssub->id);
1853 my $orig_ssub = $editor->retrieve_serial_subscription($ssub->id);
1855 $logger->info("subscription-alter: original subscription ".OpenSRF::Utils::JSON->perl2JSON($orig_ssub));
1856 $logger->info("subscription-alter: updated subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1857 return $editor->event unless $editor->update_serial_subscription($ssub);
1861 __PACKAGE__->register_method(
1862 method => "fleshed_serial_subscription_retrieve_batch",
1864 api_name => "open-ils.serial.subscription.fleshed.batch.retrieve"
1867 sub fleshed_serial_subscription_retrieve_batch {
1868 my( $self, $client, $ids ) = @_;
1869 # FIXME: permissions?
1870 $logger->info("Fetching fleshed subscriptions @$ids");
1871 return $U->cstorereq(
1872 "open-ils.cstore.direct.serial.subscription.search.atomic",
1875 flesh_fields => {ssub => [ qw/owning_lib notes/ ]}
1879 __PACKAGE__->register_method(
1880 method => "retrieve_sub_tree",
1882 api_name => "open-ils.serial.subscription_tree.retrieve"
1885 __PACKAGE__->register_method(
1886 method => "retrieve_sub_tree",
1887 api_name => "open-ils.serial.subscription_tree.global.retrieve"
1890 sub retrieve_sub_tree {
1892 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
1894 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
1898 # TODO: permission support
1899 if(!@org_ids and $user_session) {
1901 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
1902 @org_ids = ($user_obj->home_ou);
1905 if( $self->api_name =~ /global/ ) {
1906 return _build_subs_list( { record_entry => $docid } ); # TODO: filter for !deleted, or active?
1911 for my $orgid (@org_ids) {
1912 my $subs = _build_subs_list(
1913 { record_entry => $docid, owning_lib => $orgid } );# TODO: filter for !deleted, or active?
1914 push( @all_subs, @$subs );
1923 sub _build_subs_list {
1924 my $search_hash = shift;
1926 #$search_hash->{deleted} = 'f';
1927 my $e = new_editor();
1929 my $subs = $e->search_serial_subscription([$search_hash, { 'order_by' => {'ssub' => 'id'} }]);
1933 for my $sub (@$subs) {
1935 # TODO: filter on !deleted?
1936 my $dists = $e->search_serial_distribution(
1937 [{ subscription => $sub->id }, { 'order_by' => {'sdist' => 'label'} }]
1940 #$dists = [ sort { $a->label cmp $b->label } @$dists ];
1942 $sub->distributions($dists);
1944 # TODO: filter on !deleted?
1945 my $issuances = $e->search_serial_issuance(
1946 [{ subscription => $sub->id }, { 'order_by' => {'siss' => 'label'} }]
1949 #$issuances = [ sort { $a->label cmp $b->label } @$issuances ];
1950 $sub->issuances($issuances);
1952 # TODO: filter on !deleted?
1953 my $scaps = $e->search_serial_caption_and_pattern(
1954 [{ subscription => $sub->id }, { 'order_by' => {'scap' => 'id'} }]
1957 #$scaps = [ sort { $a->id cmp $b->id } @$scaps ];
1958 $sub->scaps($scaps);
1959 push( @built_subs, $sub );
1962 return \@built_subs;
1966 __PACKAGE__->register_method(
1967 method => "subscription_orgs_for_title",
1969 api_name => "open-ils.serial.subscription.retrieve_orgs_by_title"
1972 sub subscription_orgs_for_title {
1973 my( $self, $client, $record_id ) = @_;
1975 my $subs = $U->simple_scalar_request(
1977 "open-ils.cstore.direct.serial.subscription.search.atomic",
1978 { record_entry => $record_id }); # TODO: filter on !deleted?
1980 my $orgs = { map {$_->owning_lib => 1 } @$subs };
1981 return [ keys %$orgs ];
1985 ##########################################################################
1986 # distribution methods
1988 __PACKAGE__->register_method(
1989 method => 'fleshed_sdist_alter',
1990 api_name => 'open-ils.serial.distribution.fleshed.batch.update',
1994 desc => 'Receives an array of one or more distributions and updates the database as needed',
1996 name => 'authtoken',
1997 desc => 'Authtoken for current user session',
2001 name => 'distributions',
2002 desc => 'Array of fleshed distributions',
2008 desc => 'Returns 1 if successful, event if failed',
2014 sub fleshed_sdist_alter {
2015 my( $self, $conn, $auth, $sdists ) = @_;
2016 return 1 unless ref $sdists;
2017 my( $reqr, $evt ) = $U->checkses($auth);
2018 return $evt if $evt;
2019 my $editor = new_editor(requestor => $reqr, xact => 1);
2020 my $override = $self->api_name =~ /override/;
2022 # TODO: permission check
2023 # return $editor->event unless
2024 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2026 for my $sdist (@$sdists) {
2027 my $sdistid = $sdist->id;
2029 if( $sdist->isdeleted ) {
2030 $evt = _delete_sdist( $editor, $override, $sdist);
2031 } elsif( $sdist->isnew ) {
2032 $evt = _create_sdist( $editor, $sdist );
2034 $evt = _update_sdist( $editor, $override, $sdist );
2039 $logger->info("fleshed distribution-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2043 $logger->debug("distribution-alter: done updating distribution batch");
2045 $logger->info("fleshed distribution-alter successfully updated ".scalar(@$sdists)." distributions");
2050 my ($editor, $override, $sdist) = @_;
2051 $logger->info("distribution-alter: delete distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2052 return $editor->event unless $editor->delete_serial_distribution($sdist);
2057 my ($editor, $sdist) = @_;
2059 $logger->info("distribution-alter: new distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2060 return $editor->event unless $editor->create_serial_distribution($sdist);
2062 # create summaries too
2063 my $summary = new Fieldmapper::serial::basic_summary;
2064 $summary->distribution($sdist->id);
2065 $summary->generated_coverage('');
2066 return $editor->event unless $editor->create_serial_basic_summary($summary);
2067 $summary = new Fieldmapper::serial::supplement_summary;
2068 $summary->distribution($sdist->id);
2069 $summary->generated_coverage('');
2070 return $editor->event unless $editor->create_serial_supplement_summary($summary);
2071 $summary = new Fieldmapper::serial::index_summary;
2072 $summary->distribution($sdist->id);
2073 $summary->generated_coverage('');
2074 return $editor->event unless $editor->create_serial_index_summary($summary);
2076 # create a starter stream (TODO: reconsider this)
2077 my $stream = new Fieldmapper::serial::stream;
2078 $stream->distribution($sdist->id);
2079 return $editor->event unless $editor->create_serial_stream($stream);
2085 my ($editor, $override, $sdist) = @_;
2087 $logger->info("distribution-alter: retrieving distribution ".$sdist->id);
2088 my $orig_sdist = $editor->retrieve_serial_distribution($sdist->id);
2090 $logger->info("distribution-alter: original distribution ".OpenSRF::Utils::JSON->perl2JSON($orig_sdist));
2091 $logger->info("distribution-alter: updated distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2092 return $editor->event unless $editor->update_serial_distribution($sdist);
2096 __PACKAGE__->register_method(
2097 method => "fleshed_serial_distribution_retrieve_batch",
2099 api_name => "open-ils.serial.distribution.fleshed.batch.retrieve"
2102 sub fleshed_serial_distribution_retrieve_batch {
2103 my( $self, $client, $ids ) = @_;
2104 # FIXME: permissions?
2105 $logger->info("Fetching fleshed distributions @$ids");
2106 return $U->cstorereq(
2107 "open-ils.cstore.direct.serial.distribution.search.atomic",
2110 flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams / ]}
2114 __PACKAGE__->register_method(
2115 method => "retrieve_dist_tree",
2117 api_name => "open-ils.serial.distribution_tree.retrieve"
2120 __PACKAGE__->register_method(
2121 method => "retrieve_dist_tree",
2122 api_name => "open-ils.serial.distribution_tree.global.retrieve"
2125 sub retrieve_dist_tree {
2126 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2128 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2132 # TODO: permission support
2133 if(!@org_ids and $user_session) {
2135 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2136 @org_ids = ($user_obj->home_ou);
2139 my $e = new_editor();
2141 if( $self->api_name =~ /global/ ) {
2142 return $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }},
2144 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 / ]},
2145 order_by => {'sdist' => 'id'},
2146 'join' => {'ssub' => {}}
2148 ]); # TODO: filter for !deleted?
2152 for my $orgid (@org_ids) {
2153 my $dists = $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }, holding_lib => $orgid},
2155 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 / ]},
2156 order_by => {'sdist' => 'id'},
2157 'join' => {'ssub' => {}}
2159 ]); # TODO: filter for !deleted?
2160 push( @all_dists, @$dists ) if $dists;
2170 __PACKAGE__->register_method(
2171 method => "distribution_orgs_for_title",
2173 api_name => "open-ils.serial.distribution.retrieve_orgs_by_title"
2176 sub distribution_orgs_for_title {
2177 my( $self, $client, $record_id ) = @_;
2179 my $dists = $U->cstorereq(
2180 "open-ils.cstore.direct.serial.distribution.search.atomic",
2181 { '+ssub' => { record_entry => $record_id } },
2182 { 'join' => {'ssub' => {}} }); # TODO: filter on !deleted?
2184 my $orgs = { map {$_->holding_lib => 1 } @$dists };
2185 return [ keys %$orgs ];
2189 ##########################################################################
2190 # caption and pattern methods
2192 __PACKAGE__->register_method(
2193 method => 'scap_alter',
2194 api_name => 'open-ils.serial.caption_and_pattern.batch.update',
2198 desc => 'Receives an array of one or more caption and patterns and updates the database as needed',
2200 name => 'authtoken',
2201 desc => 'Authtoken for current user session',
2206 desc => 'Array of caption and patterns',
2212 desc => 'Returns 1 if successful, event if failed',
2219 my( $self, $conn, $auth, $scaps ) = @_;
2220 return 1 unless ref $scaps;
2221 my( $reqr, $evt ) = $U->checkses($auth);
2222 return $evt if $evt;
2223 my $editor = new_editor(requestor => $reqr, xact => 1);
2224 my $override = $self->api_name =~ /override/;
2226 # TODO: permission check
2227 # return $editor->event unless
2228 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2230 for my $scap (@$scaps) {
2231 my $scapid = $scap->id;
2233 if( $scap->isdeleted ) {
2234 $evt = _delete_scap( $editor, $override, $scap);
2235 } elsif( $scap->isnew ) {
2236 $evt = _create_scap( $editor, $scap );
2238 $evt = _update_scap( $editor, $override, $scap );
2243 $logger->info("caption_and_pattern-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2247 $logger->debug("caption_and_pattern-alter: done updating caption_and_pattern batch");
2249 $logger->info("caption_and_pattern-alter successfully updated ".scalar(@$scaps)." caption_and_patterns");
2254 my ($editor, $override, $scap) = @_;
2255 $logger->info("caption_and_pattern-alter: delete caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2256 my $sisses = $editor->search_serial_issuance(
2257 { caption_and_pattern => $scap->id }, { limit => 1 } ); #TODO: 'deleted' support?
2258 return OpenILS::Event->new(
2259 'SERIAL_CAPTION_AND_PATTERN_HAS_ISSUANCES', payload => $scap->id ) if (@$sisses);
2261 return $editor->event unless $editor->delete_serial_caption_and_pattern($scap);
2266 my ($editor, $scap) = @_;
2268 $logger->info("caption_and_pattern-alter: new caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2269 return $editor->event unless $editor->create_serial_caption_and_pattern($scap);
2274 my ($editor, $override, $scap) = @_;
2276 $logger->info("caption_and_pattern-alter: retrieving caption_and_pattern ".$scap->id);
2277 my $orig_scap = $editor->retrieve_serial_caption_and_pattern($scap->id);
2279 $logger->info("caption_and_pattern-alter: original caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($orig_scap));
2280 $logger->info("caption_and_pattern-alter: updated caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2281 return $editor->event unless $editor->update_serial_caption_and_pattern($scap);
2285 __PACKAGE__->register_method(
2286 method => "serial_caption_and_pattern_retrieve_batch",
2288 api_name => "open-ils.serial.caption_and_pattern.batch.retrieve"
2291 sub serial_caption_and_pattern_retrieve_batch {
2292 my( $self, $client, $ids ) = @_;
2293 $logger->info("Fetching caption_and_patterns @$ids");
2294 return $U->cstorereq(
2295 "open-ils.cstore.direct.serial.caption_and_pattern.search.atomic",
2300 ##########################################################################
2303 __PACKAGE__->register_method(
2304 method => 'sstr_alter',
2305 api_name => 'open-ils.serial.stream.batch.update',
2309 desc => 'Receives an array of one or more streams and updates the database as needed',
2311 name => 'authtoken',
2312 desc => 'Authtoken for current user session',
2317 desc => 'Array of streams',
2323 desc => 'Returns 1 if successful, event if failed',
2330 my( $self, $conn, $auth, $sstrs ) = @_;
2331 return 1 unless ref $sstrs;
2332 my( $reqr, $evt ) = $U->checkses($auth);
2333 return $evt if $evt;
2334 my $editor = new_editor(requestor => $reqr, xact => 1);
2335 my $override = $self->api_name =~ /override/;
2337 # TODO: permission check
2338 # return $editor->event unless
2339 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2341 for my $sstr (@$sstrs) {
2342 my $sstrid = $sstr->id;
2344 if( $sstr->isdeleted ) {
2345 $evt = _delete_sstr( $editor, $override, $sstr);
2346 } elsif( $sstr->isnew ) {
2347 $evt = _create_sstr( $editor, $sstr );
2349 $evt = _update_sstr( $editor, $override, $sstr );
2354 $logger->info("stream-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2358 $logger->debug("stream-alter: done updating stream batch");
2360 $logger->info("stream-alter successfully updated ".scalar(@$sstrs)." streams");
2365 my ($editor, $override, $sstr) = @_;
2366 $logger->info("stream-alter: delete stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2367 my $sitems = $editor->search_serial_item(
2368 { stream => $sstr->id }, { limit => 1 } ); #TODO: 'deleted' support?
2369 return OpenILS::Event->new(
2370 'SERIAL_STREAM_HAS_ITEMS', payload => $sstr->id ) if (@$sitems);
2372 return $editor->event unless $editor->delete_serial_stream($sstr);
2377 my ($editor, $sstr) = @_;
2379 $logger->info("stream-alter: new stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2380 return $editor->event unless $editor->create_serial_stream($sstr);
2385 my ($editor, $override, $sstr) = @_;
2387 $logger->info("stream-alter: retrieving stream ".$sstr->id);
2388 my $orig_sstr = $editor->retrieve_serial_stream($sstr->id);
2390 $logger->info("stream-alter: original stream ".OpenSRF::Utils::JSON->perl2JSON($orig_sstr));
2391 $logger->info("stream-alter: updated stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2392 return $editor->event unless $editor->update_serial_stream($sstr);
2396 __PACKAGE__->register_method(
2397 method => "serial_stream_retrieve_batch",
2399 api_name => "open-ils.serial.stream.batch.retrieve"
2402 sub serial_stream_retrieve_batch {
2403 my( $self, $client, $ids ) = @_;
2404 $logger->info("Fetching streams @$ids");
2405 return $U->cstorereq(
2406 "open-ils.cstore.direct.serial.stream.search.atomic",
2412 ##########################################################################
2415 __PACKAGE__->register_method(
2416 method => 'sum_alter',
2417 api_name => 'open-ils.serial.basic_summary.batch.update',
2421 desc => 'Receives an array of one or more summaries and updates the database as needed',
2423 name => 'authtoken',
2424 desc => 'Authtoken for current user session',
2429 desc => 'Array of basic summaries',
2435 desc => 'Returns 1 if successful, event if failed',
2441 __PACKAGE__->register_method(
2442 method => 'sum_alter',
2443 api_name => 'open-ils.serial.supplement_summary.batch.update',
2447 desc => 'Receives an array of one or more summaries and updates the database as needed',
2449 name => 'authtoken',
2450 desc => 'Authtoken for current user session',
2455 desc => 'Array of supplement summaries',
2461 desc => 'Returns 1 if successful, event if failed',
2467 __PACKAGE__->register_method(
2468 method => 'sum_alter',
2469 api_name => 'open-ils.serial.index_summary.batch.update',
2473 desc => 'Receives an array of one or more summaries and updates the database as needed',
2475 name => 'authtoken',
2476 desc => 'Authtoken for current user session',
2481 desc => 'Array of index summaries',
2487 desc => 'Returns 1 if successful, event if failed',
2494 my( $self, $conn, $auth, $sums ) = @_;
2495 return 1 unless ref $sums;
2497 $self->api_name =~ /serial\.(\w*)_summary/;
2500 my( $reqr, $evt ) = $U->checkses($auth);
2501 return $evt if $evt;
2502 my $editor = new_editor(requestor => $reqr, xact => 1);
2503 my $override = $self->api_name =~ /override/;
2505 # TODO: permission check
2506 # return $editor->event unless
2507 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2509 for my $sum (@$sums) {
2510 my $sumid = $sum->id;
2512 # XXX: (for now, at least) summaries should be created/deleted by the distribution functions
2513 if( $sum->isdeleted ) {
2514 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2515 } elsif( $sum->isnew ) {
2516 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2518 $evt = _update_sum( $editor, $override, $sum, $type );
2523 $logger->info("${type}_summary-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2527 $logger->debug("${type}_summary-alter: done updating ${type}_summary batch");
2529 $logger->info("${type}_summary-alter successfully updated ".scalar(@$sums)." ${type}_summaries");
2534 my ($editor, $override, $sum, $type) = @_;
2536 $logger->info("${type}_summary-alter: retrieving ${type}_summary ".$sum->id);
2537 my $retrieve_method = "retrieve_serial_${type}_summary";
2538 my $orig_sum = $editor->$retrieve_method($sum->id);
2540 $logger->info("${type}_summary-alter: original ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($orig_sum));
2541 $logger->info("${type}_summary-alter: updated ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($sum));
2542 my $update_method = "update_serial_${type}_summary";
2543 return $editor->event unless $editor->$update_method($sum);
2547 __PACKAGE__->register_method(
2548 method => "serial_summary_retrieve_batch",
2550 api_name => "open-ils.serial.basic_summary.batch.retrieve"
2553 __PACKAGE__->register_method(
2554 method => "serial_summary_retrieve_batch",
2556 api_name => "open-ils.serial.supplement_summary.batch.retrieve"
2559 __PACKAGE__->register_method(
2560 method => "serial_summary_retrieve_batch",
2562 api_name => "open-ils.serial.index_summary.batch.retrieve"
2565 sub serial_summary_retrieve_batch {
2566 my( $self, $client, $ids ) = @_;
2568 $self->api_name =~ /serial\.(\w*)_summary/;
2571 $logger->info("Fetching ${type}_summaries @$ids");
2572 return $U->cstorereq(
2573 "open-ils.cstore.direct.serial.".$type."_summary.search.atomic",
2579 ##########################################################################
2582 __PACKAGE__->register_method(
2583 "method" => "bre_by_identifier",
2584 "api_name" => "open-ils.serial.biblio.record_entry.by_identifier",
2587 "desc" => "Find instances of biblio.record_entry given a search token" .
2588 " that could be a value for any identifier defined in " .
2589 "config.metabib_field",
2591 {"desc" => "Search token", "type" => "string"},
2592 {"desc" => "Options: require_subscriptions, add_mvr, is_actual_id" .
2593 " (all boolean)", "type" => "object"}
2596 "desc" => "Any matching BREs, or if the add_mvr option is true, " .
2597 "objects with a 'bre' key/value pair, and an 'mvr' " .
2598 "key-value pair. BREs have subscriptions fleshed on.",
2604 sub bre_by_identifier {
2605 my ($self, $client, $term, $options) = @_;
2607 return new OpenILS::Event("BAD_PARAMS") unless $term;
2610 my $e = new_editor();
2614 if ($options->{"is_actual_id"}) {
2618 $e->search_config_metabib_field({"field_class" => "identifier"})
2619 or return $e->die_event;
2621 my @identifiers = map { $_->name } @$cmf;
2622 my $query = join(" || ", map { "id|$_: $term" } @identifiers);
2624 my $search = create OpenSRF::AppSession("open-ils.search");
2625 my $search_result = $search->request(
2626 "open-ils.search.biblio.multiclass.query.staff", {}, $query
2628 $search->disconnect;
2630 # Un-nest results. They tend to look like [[1],[2],[3]] for some reason.
2631 @ids = map { @{$_} } @{$search_result->{"ids"}};
2639 my $bre = $e->search_biblio_record_entry([
2641 "flesh" => 2, "flesh_fields" => {
2642 "bre" => ["subscriptions"],
2643 "ssub" => ["owning_lib"]
2646 ]) or return $e->die_event;
2648 if (@$bre && $options->{"require_subscriptions"}) {
2649 $bre = [ grep { @{$_->subscriptions} } @$bre ];
2654 if (@$bre) { # re-evaluate after possible grep
2655 if ($options->{"add_mvr"}) {
2657 {"bre" => $_, "mvr" => _get_mvr($_->id)}
2660 $client->respond($_) foreach (@$bre);
2667 __PACKAGE__->register_method(
2668 "method" => "get_receivable_items",
2669 "api_name" => "open-ils.serial.items.receivable.by_subscription",
2672 "desc" => "Return all receivable items under a given subscription",
2674 {"desc" => "Authtoken", "type" => "string"},
2675 {"desc" => "Subscription ID", "type" => "number"},
2678 "desc" => "All receivable items under a given subscription",
2684 __PACKAGE__->register_method(
2685 "method" => "get_receivable_items",
2686 "api_name" => "open-ils.serial.items.receivable.by_issuance",
2689 "desc" => "Return all receivable items under a given issuance",
2691 {"desc" => "Authtoken", "type" => "string"},
2692 {"desc" => "Issuance ID", "type" => "number"},
2695 "desc" => "All receivable items under a given issuance",
2701 sub get_receivable_items {
2702 my ($self, $client, $auth, $term) = @_;
2704 my $e = new_editor("authtoken" => $auth);
2705 return $e->die_event unless $e->checkauth;
2709 my $by = ($self->api_name =~ /by_(\w+)$/)[0];
2712 "issuance" => {"issuance" => $term},
2713 "subscription" => {"+siss" => {"subscription" => $term}}
2716 my $item_ids = $e->json_query(
2718 "select" => {"sitem" => ["id"]},
2719 "from" => {"sitem" => "siss"},
2721 %{$where{$by}}, "date_received" => undef
2723 "order_by" => {"sitem" => ["id"]}
2725 ) or return $e->die_event;
2727 return undef unless @$item_ids;
2729 foreach (map { $_->{"id"} } @$item_ids) {
2731 $e->retrieve_serial_item([
2735 "sitem" => ["stream", "issuance"],
2736 "sstr" => ["distribution"],
2737 "sdist" => ["holding_lib"]
2748 __PACKAGE__->register_method(
2749 "method" => "get_receivable_issuances",
2750 "api_name" => "open-ils.serial.issuances.receivable",
2753 "desc" => "Return all issuances with receivable items given " .
2754 "a subscription ID",
2756 {"desc" => "Authtoken", "type" => "string"},
2757 {"desc" => "Subscription ID", "type" => "number"},
2760 "desc" => "All issuances with receivable items " .
2761 "(but not the items themselves)", "type" => "object"
2766 sub get_receivable_issuances {
2767 my ($self, $client, $auth, $sub_id) = @_;
2769 my $e = new_editor("authtoken" => $auth);
2770 return $e->die_event unless $e->checkauth;
2774 my $issuance_ids = $e->json_query({
2777 {"transform" => "distinct", "column" => "id"},
2781 "from" => {"siss" => "sitem"},
2783 "subscription" => $sub_id,
2784 "+sitem" => {"date_received" => undef}
2787 "siss" => {"date_published" => {"direction" => "asc"}}
2790 }) or return $e->die_event;
2792 $client->respond($e->retrieve_serial_issuance($_->{"id"}))
2793 foreach (@$issuance_ids);
2800 __PACKAGE__->register_method(
2801 "method" => "get_routing_list_users",
2802 "api_name" => "open-ils.serial.routing_list_users.fleshed_and_ordered",
2805 "desc" => "Return all routing list users with reader fleshed " .
2806 "(with card and home_ou) for a given stream ID, sorted by pos",
2808 {"desc" => "Authtoken", "type" => "string"},
2809 {"desc" => "Stream ID", "type" => "number"},
2812 "desc" => "Stream of routing list users", "type" => "object",
2818 sub get_routing_list_users {
2819 my ($self, $client, $auth, $stream_id) = @_;
2821 return undef unless $stream_id = int $stream_id; # sic, assignment
2823 my $e = new_editor("authtoken" => $auth);
2824 return $e->die_event unless $e->checkauth;
2826 my $users = $e->search_serial_routing_list_user([
2827 {"stream" => $stream_id}, {
2828 "order_by" => {"srlu" => "pos"},
2831 "srlu" => [qw/reader stream/],
2832 "au" => [qw/card home_ou/],
2833 "sstr" => ["distribution"]
2836 ]) or return $e->die_event;
2838 return undef unless @$users;
2840 # The ADMIN_SERIAL_STREAM permission is used simply to avoid the
2841 # need for any new permission. The context OU will be the same
2842 # for every result of the above query, so we need only check once.
2843 return $e->die_event unless $e->allowed(
2844 "ADMIN_SERIAL_STREAM", $users->[0]->stream->distribution->holding_lib
2849 # Now we can strip the stream/distribution info (only used for perm
2850 # checking) and send back the srlu's to the caller.
2851 $client->respond($_) for map { $_->stream($_->stream->id); $_ } @$users;
2857 __PACKAGE__->register_method(
2858 "method" => "replace_routing_list_users",
2859 "api_name" => "open-ils.serial.routing_list_users.replace",
2861 "desc" => "Replace all routing list users on the specified streams " .
2862 "with those in the list argument",
2864 {"desc" => "Authtoken", "type" => "string"},
2865 {"desc" => "List of srlu objects", "type" => "array"},
2868 "desc" => "event on failure, undef on success"
2873 sub replace_routing_list_users {
2874 my ($self, $client, $auth, $users) = @_;
2876 return undef unless ref $users eq "ARRAY";
2878 if (grep { ref $_ ne "Fieldmapper::serial::routing_list_user" } @$users) {
2879 return new OpenILS::Event("BAD_PARAMS", "note" => "Only srlu objects");
2882 my $e = new_editor("authtoken" => $auth, "xact" => 1);
2883 return $e->die_event unless $e->checkauth;
2885 my %streams_ok = ();
2888 foreach my $user (@$users) {
2889 unless (exists $streams_ok{$user->stream}) {
2890 my $stream = $e->retrieve_serial_stream([
2893 "flesh_fields" => {"sstr" => ["distribution"]}
2895 ]) or return $e->die_event;
2897 "ADMIN_SERIAL_STREAM", $stream->distribution->holding_lib
2898 ) or return $e->die_event;
2900 my $to_delete = $e->search_serial_routing_list_user(
2901 {"stream" => $user->stream}
2902 ) or return $e->die_event;
2905 "Deleting srlu: [" .
2906 join(", ", map { $_->id; } @$to_delete) .
2910 foreach (@$to_delete) {
2911 $e->delete_serial_routing_list_user($_) or
2912 return $e->die_event;
2915 $streams_ok{$user->stream} = 1;
2918 next if $user->isdeleted;
2922 $e->create_serial_routing_list_user($user) or return $e->die_event;
2925 $e->commit or return $e->die_event;