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 offest := 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 $all_dists = $args->{all_dists};
672 my $mfhd = MFHD->new(MARC::Record->new());
674 my $ssub = $editor->retrieve_serial_subscription([$ssub_id]);
675 my $scaps = $editor->search_serial_caption_and_pattern({ subscription => $ssub_id, active => 't'});
676 my $sdists = $editor->search_serial_distribution( [{ subscription => $ssub->id }, { flesh => 1,
677 flesh_fields => {sdist => [ qw/ streams / ]}, $all_dists ? () : (limit => 1) }] ); #TODO: 'deleted' support?
680 my $total_streams = 0;
682 $total_streams += scalar(@{$_->streams});
684 if ($total_streams < 1) {
686 # XXX TODO new event type
687 return new OpenILS::Event(
688 "BAD_PARAMS", note =>
689 "There are no streams to direct items. Can't predict."
696 # XXX TODO new event type
697 return new OpenILS::Event(
698 "BAD_PARAMS", note =>
699 "There are no active caption-and-pattern objects associated " .
700 "with this subscription. Can't predict."
706 foreach my $scap (@$scaps) {
707 my $caption_field = _revive_caption($scap);
708 $caption_field->update('8' => $link_id);
709 $mfhd->append_fields($caption_field);
711 'caption' => $caption_field,
712 'scap_id' => $scap->id,
713 'num_to_predict' => $args->{num_to_predict},
714 'end_date' => defined $args->{end_date} ?
715 $_strp_date->parse_datetime($args->{end_date}) : undef
717 if ($args->{base_issuance}) { # predict from a given issuance
718 $options->{predict_from} = _revive_holding($args->{base_issuance}->holding_code, $caption_field, 1); # fresh MFHD Record, so we simply default to 1 for seqno
719 } else { # default to predicting from last published
720 my $last_published = $editor->search_serial_issuance([
721 {'caption_and_pattern' => $scap->id,
722 'subscription' => $ssub_id},
723 {limit => 1, order_by => { siss => "date_published DESC" }}]
725 if ($last_published->[0]) {
726 my $last_siss = $last_published->[0];
727 unless ($last_siss->holding_code) {
729 # XXX TODO new event type
730 return new OpenILS::Event(
731 "BAD_PARAMS", note =>
732 "Last issuance has no holding code. Can't predict."
735 $options->{predict_from} = _revive_holding($last_siss->holding_code, $caption_field, 1);
738 # XXX TODO make a new event type instead of hijacking this one
739 return new OpenILS::Event(
740 "BAD_PARAMS", note => "No issuance from which to predict!"
744 push( @predictions, _generate_issuance_values($mfhd, $options) );
749 foreach my $prediction (@predictions) {
750 my $issuance = new Fieldmapper::serial::issuance;
752 $issuance->label($prediction->{label});
753 $issuance->date_published($prediction->{date_published}->strftime('%F'));
754 $issuance->holding_code(OpenSRF::Utils::JSON->perl2JSON($prediction->{holding_code}));
755 $issuance->holding_type($prediction->{holding_type});
756 $issuance->caption_and_pattern($prediction->{caption_and_pattern});
757 $issuance->subscription($ssub->id);
758 push (@issuances, $issuance);
761 fleshed_issuance_alter($self, $conn, $authtoken, \@issuances); # FIXME: catch events
764 for (my $i = 0; $i < @issuances; $i++) {
765 my $date_expected = $predictions[$i]->{date_published}->add(seconds => interval_to_seconds($ssub->expected_date_offset))->strftime('%F');
766 my $issuance = $issuances[$i];
767 #$issuance->label(interval_to_seconds($ssub->expected_date_offset));
768 foreach my $sdist (@$sdists) {
769 my $streams = $sdist->streams;
770 foreach my $stream (@$streams) {
771 my $item = new Fieldmapper::serial::item;
773 $item->stream($stream->id);
774 $item->date_expected($date_expected);
775 $item->issuance($issuance->id);
776 push (@items, $item);
780 fleshed_item_alter($self, $conn, $authtoken, \@items); # FIXME: catch events
785 # _generate_issuance_values() is an initial attempt at a function which can be used
786 # to populate an issuance table with a list of predicted issues. It accepts
787 # a hash ref of options initially defined as:
788 # caption : the caption field to predict on
789 # num_to_predict : the number of issues you wish to predict
790 # last_rec_date : the date of the last received issue, to be used as an offset
791 # for predicting future issues
793 # The basic method is to first convert to a single holding if compressed, then
794 # increment the holding and save the resulting values to @issuances.
796 # returns @issuance_values, an array of hashrefs containing (formatted
797 # label, formatted chronology date, formatted estimated arrival date, and an
798 # array ref of holding subfields as (key, value, key, value ...)) (not a hash
799 # to protect order and possible duplicate keys), and a holding type.
801 sub _generate_issuance_values {
802 my ($mfhd, $options) = @_;
803 my $caption = $options->{caption};
804 my $scap_id = $options->{scap_id};
805 my $num_to_predict = $options->{num_to_predict};
806 my $end_date = $options->{end_date};
807 my $predict_from = $options->{predict_from}; # issuance to predict from
808 #my $last_rec_date = $options->{last_rec_date}; # expected or actual
810 # TODO: add support for predicting serials with no chronology by passing in
811 # a last_pub_date option?
814 # Only needed for 'real' MFHD records, not our temp records
815 # my $link_id = $caption->link_id;
816 # if(!$predict_from) {
817 # my $htag = $caption->tag;
818 # $htag =~ s/^85/86/;
819 # my @holdings = $mfhd->holdings($htag, $link_id);
820 # my $last_holding = $holdings[-1];
822 # #if ($last_holding->is_compressed) {
823 # # $last_holding->compressed_to_last; # convert to last in range
825 # $predict_from = $last_holding;
829 $predict_from->notes('public', []);
830 # add a note marker for system use (?)
831 $predict_from->notes('private', ['AUTOGEN']);
835 my @predictions = $mfhd->generate_predictions({'base_holding' => $predict_from, 'num_to_predict' => $num_to_predict, 'end_date' => $end_date});
836 foreach my $prediction (@predictions) {
837 $pub_date = $_strp_date->parse_datetime($prediction->chron_to_date);
842 label => $prediction->format,
843 date_published => $pub_date,
844 #date_expected => $date_expected->strftime('%F'),
845 holding_code => [$prediction->indicator(1),$prediction->indicator(2),$prediction->subfields_list],
846 holding_type => $MFHD_NAMES_BY_TAG{$caption->tag},
847 caption_and_pattern => $scap_id
852 return @issuance_values;
855 sub _revive_caption {
858 my $pattern_code = $scap->pattern_code;
861 my $pattern_parts = OpenSRF::Utils::JSON->JSON2perl($pattern_code);
862 unshift(@$pattern_parts, $MFHD_TAGS_BY_NAME{$scap->type});
863 my $pattern_field = new MARC::Field(@$pattern_parts);
865 # build MFHD::Caption
866 return new MFHD::Caption($pattern_field);
869 sub _revive_holding {
870 my $holding_code = shift;
871 my $caption_field = shift;
875 my $holding_parts = OpenSRF::Utils::JSON->JSON2perl($holding_code);
876 my $captag = $caption_field->tag;
877 $captag =~ s/^85/86/;
878 unshift(@$holding_parts, $captag);
879 my $holding_field = new MARC::Field(@$holding_parts);
881 # build MFHD::Holding
882 return new MFHD::Holding($seqno, $holding_field, $caption_field);
885 __PACKAGE__->register_method(
886 method => 'unitize_items',
887 api_name => 'open-ils.serial.receive_items',
891 desc => 'Marks an item as received, updates the shelving unit (creating a new shelving unit if needed), and updates the summaries',
894 desc => 'array of serial items',
899 desc => 'Returns number of received items',
906 my ($self, $conn, $auth, $items) = @_;
908 my( $reqr, $evt ) = $U->checkses($auth);
910 my $editor = new_editor(requestor => $reqr, xact => 1);
911 $self->api_name =~ /serial\.(\w*)_items/;
915 my %found_stream_ids;
918 my %stream_ids_by_unit_id;
921 my %sdist_by_unit_id;
922 my %sdist_by_stream_id;
924 my $new_unit_id; # id for '-2' units to share
925 foreach my $item (@$items) {
926 # for debugging only, TODO: delete
927 if (!ref $item) { # hopefully we got an id instead
928 $item = $editor->retrieve_serial_item($item);
931 my $unit_id = ref($item->unit) ? $item->unit->id : $item->unit;
932 my $stream_id = ref($item->stream) ? $item->stream->id : $item->stream;
933 my $issuance_id = ref($item->issuance) ? $item->issuance->id : $item->issuance;
934 #TODO: evt on any missing ids
936 if ($mode eq 'receive') {
937 $item->date_received('now');
938 $item->status('Received');
940 $item->status('Bindery');
943 # check for types to trigger summary updates
945 if (!ref $item->issuance) {
946 my $scaps = $editor->search_serial_caption_and_pattern([{"+siss" => {"id" => $issuance_id}}, { "join" => {"siss" => {}} }]);
948 } elsif (!ref $item->issuance->caption_and_pattern) {
949 $scap = $editor->retrieve_serial_caption_and_pattern($item->issuance->caption_and_pattern);
951 $scap = $editor->issuance->caption_and_pattern;
953 if (!exists($found_types{$stream_id})) {
954 $found_types{$stream_id} = {};
956 $found_types{$stream_id}->{$scap->type} = 1;
958 # create unit if needed
959 if ($unit_id == -1 or (!$new_unit_id and $unit_id == -2)) { # create unit per item
961 my $sdists = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
962 $unit = _build_unit($editor, $sdists->[0], $mode);
963 my $evt = _create_sunit($editor, $unit);
965 if ($unit_id == -2) {
966 $new_unit_id = $unit->id;
967 $unit_id = $new_unit_id;
969 $unit_id = $unit->id;
971 $item->unit($unit_id);
973 # get unit with 'DEFAULT's and save unit and sdist for later use
974 $unit = $editor->retrieve_serial_unit($unit->id);
975 $unit_map{$unit_id} = $unit;
976 $sdist_by_unit_id{$unit_id} = $sdists->[0];
977 $sdist_by_stream_id{$stream_id} = $sdists->[0];
978 } elsif ($unit_id == -2) { # create one unit for all '-2' items
979 $unit_id = $new_unit_id;
980 $item->unit($unit_id);
983 $found_unit_ids{$unit_id} = 1;
984 $found_stream_ids{$stream_id} = 1;
986 # save the stream_id for this unit_id
987 # TODO: prevent items from different streams in same unit? (perhaps in interface)
988 $stream_ids_by_unit_id{$unit_id} = $stream_id;
990 my $evt = _update_sitem($editor, undef, $item);
994 # deal with unit level labels
995 foreach my $unit_id (keys %found_unit_ids) {
997 # get all the needed issuances for unit
998 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"unit" => $unit_id, "status" => "Received"}}, {"join" => {"sitem" => {}}, "order_by" => {"siss" => "date_published"}} ]);
999 #TODO: evt on search failure
1001 my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
1003 # special case for single formatted_part (may have summarized version)
1004 if (@$formatted_parts == 1) {
1005 #TODO: MFHD.pm should have a 'format_summary' method for this
1008 # retrieve and update unit contents
1012 # if we just created the unit, we will already have it and the distribution stored
1013 if (exists $unit_map{$unit_id}) {
1014 $sunit = $unit_map{$unit_id};
1015 $sdist = $sdist_by_unit_id{$unit_id};
1017 $sunit = $editor->retrieve_serial_unit($unit_id);
1018 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_ids_by_unit_id{$unit_id}}}, { "join" => {"sstr" => {}} }]);
1019 $sdist = $sdist->[0];
1022 $sunit->detailed_contents($sdist->unit_label_prefix . ' '
1023 . join(', ', @$formatted_parts) . ' '
1024 . $sdist->unit_label_suffix);
1026 $sunit->summary_contents($sunit->detailed_contents); #TODO: change this when real summary contents are available
1028 # create sort_key by left padding numbers to 6 digits
1029 my $sort_key = $sunit->detailed_contents;
1030 $sort_key =~ s/(\d+)/sprintf '%06d', $1/eg; # this may need improvement
1031 $sunit->sort_key($sort_key);
1033 if ($mode eq 'bind') {
1034 $sunit->status(2); # set to 'Bindery' status
1037 my $evt = _update_sunit($editor, undef, $sunit);
1038 return $evt if $evt;
1041 # TODO: cleanup 'dead' units (units which are now emptied of their items)
1043 if ($mode eq 'receive') { # the summary holdings do not change when binding
1044 # deal with stream level summaries
1045 # summaries will be built from the "primary" stream only, that is, the stream with the lowest ID per distribution
1046 # (TODO: consider direct designation)
1047 my %primary_streams_by_sdist;
1048 my %streams_by_sdist;
1050 # see if we have primary streams, and if so, associate them with their distributions
1051 foreach my $stream_id (keys %found_stream_ids) {
1053 if (exists $sdist_by_stream_id{$stream_id}) {
1054 $sdist = $sdist_by_stream_id{$stream_id};
1056 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
1057 $sdist = $sdist->[0];
1060 if (!exists($streams_by_sdist{$sdist->id})) {
1061 $streams = $editor->search_serial_stream([{"distribution" => $sdist->id}, {"order_by" => {"sstr" => "id"}}]);
1062 $streams_by_sdist{$sdist->id} = $streams;
1064 $streams = $streams_by_sdist{$sdist->id};
1066 $primary_streams_by_sdist{$sdist->id} = $streams->[0] if ($stream_id == $streams->[0]->id);
1069 # retrieve and update summaries for each affected primary stream's distribution
1070 foreach my $sdist_id (keys %primary_streams_by_sdist) {
1071 my $stream = $primary_streams_by_sdist{$sdist_id};
1072 my $stream_id = $stream->id;
1073 # get all the needed issuances for stream
1074 # FIXME: search in Bindery/Bound/Not Published? as well as Received
1075 foreach my $type (keys %{$found_types{$stream_id}}) {
1076 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"stream" => $stream_id, "status" => "Received"}, "+scap" => {"type" => $type}}, {"join" => {"sitem" => {}, "scap" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1077 #TODO: evt on search failure
1079 my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
1081 # retrieve and update the generated_coverage of the summary
1082 my $search_method = "search_serial_${type}_summary";
1083 my $summary = $editor->$search_method([{"distribution" => $sdist_id}]);
1084 $summary = $summary->[0];
1085 $summary->generated_coverage(join(', ', @$formatted_parts));
1086 my $update_method = "update_serial_${type}_summary";
1087 return $editor->event unless $editor->$update_method($summary);
1093 return {'num_items_received' => scalar @$items, 'new_unit_id' => $new_unit_id};
1096 sub _find_or_create_call_number {
1097 my ($e, $lib, $cn_string, $record) = @_;
1099 my $existing = $e->search_asset_call_number({
1100 "owning_lib" => $lib,
1101 "label" => $cn_string,
1102 "record" => $record,
1104 }) or return $e->die_event;
1107 return $existing->[0]->id;
1109 return $e->die_event unless
1110 $e->allowed("CREATE_VOLUME", $lib);
1112 my $acn = new Fieldmapper::asset::call_number;
1114 $acn->creator($e->requestor->id);
1115 $acn->editor($e->requestor->id);
1116 $acn->record($record);
1117 $acn->label($cn_string);
1118 $acn->owning_lib($lib);
1120 $e->create_asset_call_number($acn) or return $e->die_event;
1121 return $e->data->id;
1125 sub _issuances_received {
1126 my ($e, $sitem) = @_;
1128 my $results = $e->json_query({
1131 {"transform" => "distinct", "column" => "issuance"}
1134 "from" => {"sitem" => {"sstr" => {}, "siss" => {}}},
1136 "+sstr" => {"distribution" => $sitem->stream->distribution->id},
1137 "+siss" => {"holding_type" => $sitem->issuance->holding_type},
1138 "+sitem" => {"date_received" => {"!=" => undef}}
1140 }) or return $e->die_event;
1142 return [ map { $e->retrieve_serial_issuance($_->{"issuance"}) } @$results ];
1145 # XXX _prepare_unit_label() duplicates some code from unitize_items().
1146 # Hopefully we can unify code paths down the road.
1147 sub _prepare_unit_label {
1148 my ($e, $sunit, $sdist, $issuance) = @_;
1150 my ($mfhd, $formatted_parts) = _summarize_contents($e, [$issuance]);
1152 # special case for single formatted_part (may have summarized version)
1153 if (@$formatted_parts == 1) {
1154 #TODO: MFHD.pm should have a 'format_summary' method for this
1157 $sunit->detailed_contents(
1160 $sdist->unit_label_prefix,
1161 join(", ", @$formatted_parts),
1162 $sdist->unit_label_suffix
1166 # TODO: change this when real summary contents are available
1167 $sunit->summary_contents($sunit->detailed_contents);
1169 # Create sort_key by left padding numbers to 6 digits.
1170 (my $sort_key = $sunit->detailed_contents) =~
1171 s/(\d+)/sprintf '%06d', $1/eg;
1172 $sunit->sort_key($sort_key);
1175 # XXX duplicates a block of code from unitize_items(). Once I fully understand
1176 # what's going on and I'm sure it's working right, I'd like to have
1177 # unitize_items() just use this, keeping the logic in one place.
1178 sub _prepare_summaries {
1179 my ($e, $sitem, $issuances) = @_;
1181 my $dist_id = $sitem->stream->distribution->id;
1182 my $type = $sitem->issuance->holding_type;
1184 # Make sure @$issuances contains the new issuance from sitem.
1185 unless (grep { $_->id == $sitem->issuance->id } @$issuances) {
1186 push @$issuances, $sitem->issuance;
1189 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances);
1191 my $search_method = "search_serial_${type}_summary";
1192 my $summary = $e->$search_method([{"distribution" => $dist_id}]);
1194 my $cu_method = "update";
1197 $summary = $summary->[0];
1199 my $class = "Fieldmapper::serial::${type}_summary";
1200 $summary = $class->new;
1201 $summary->distribution($dist_id);
1202 $cu_method = "create";
1205 $summary->generated_coverage(join(", ", @$formatted_parts));
1206 my $method = "${cu_method}_serial_${type}_summary";
1207 return $e->die_event unless $e->$method($summary);
1210 __PACKAGE__->register_method(
1211 "method" => "receive_items_one_unit_per",
1212 "api_name" => "open-ils.serial.receive_items.one_unit_per",
1217 "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",
1221 "desc" => "authtoken",
1226 "desc" => "array of serial items, possibly fleshed with units and definitely fleshed with stream->distribution",
1231 "desc" => "id of bib record these items are associated with
1232 (XXX could/should be derived from items)",
1237 "desc" => "The item ID for each item successfully received",
1243 sub receive_items_one_unit_per {
1244 # XXX This function may be temporary, as it does some of what
1245 # unitize_items() does, just in a different way.
1246 my ($self, $client, $auth, $items, $record) = @_;
1248 my $e = new_editor("authtoken" => $auth, "xact" => 1);
1249 return $e->die_event unless $e->checkauth;
1250 return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
1252 my $user_id = $e->requestor->id;
1254 # Get a list of all the non-virtual field names in a serial::unit for
1255 # merging given unit objects with template-built units later.
1256 # XXX move this somewhere global so it isn't re-run all the time
1257 my $all_unit_fields =
1258 $Fieldmapper::fieldmap->{"Fieldmapper::serial::unit"}->{"fields"};
1259 my @real_unit_fields = grep {
1260 not $all_unit_fields->{$_}->{"virtual"}
1261 } keys %$all_unit_fields;
1263 foreach my $item (@$items) {
1264 # Note that we expect a certain fleshing on the items we're getting.
1265 my $sdist = $item->stream->distribution;
1267 # Create unit if given by user
1268 if (ref $item->unit) {
1269 # detach from the item, as we need to create separately
1270 my $user_unit = $item->unit;
1272 # get a unit based on associated template
1273 my $template_unit = _build_unit($e, $sdist, "receive", 1);
1274 if ($U->event_code($template_unit)) {
1276 $template_unit->{"note"} = "Item ID: " . $item->id;
1277 return $template_unit;
1280 # merge built unit with provided unit from user
1281 foreach (@real_unit_fields) {
1282 unless ($user_unit->$_) {
1283 $user_unit->$_($template_unit->$_);
1287 # Treat call number specially: the provided value from the
1288 # user will really be a string.
1289 if ($user_unit->call_number) {
1290 my $real_cn = _find_or_create_call_number(
1291 $e, $sdist->holding_lib->id,
1292 $user_unit->call_number, $record
1295 if ($U->event_code($real_cn)) {
1299 $user_unit->call_number($real_cn);
1303 my $evt = _prepare_unit_label(
1304 $e, $user_unit, $sdist, $item->issuance
1306 if ($U->event_code($evt)) {
1311 # fetch a list of issuances with received copies already existing
1312 # on this distribution.
1313 my $issuances = _issuances_received($e, $item); #XXX optimize later
1314 if ($U->event_code($issuances)) {
1319 # create/update summary objects related to this distribution
1320 $evt = _prepare_summaries($e, $item, $issuances);
1321 if ($U->event_code($evt)) {
1326 # set the incontrovertibles on the unit
1327 $user_unit->edit_date("now");
1328 $user_unit->create_date("now");
1329 $user_unit->editor($user_id);
1330 $user_unit->creator($user_id);
1332 return $e->die_event unless $e->create_serial_unit($user_unit);
1334 # save reference to new unit
1335 $item->unit($e->data->id);
1338 # Create notes if given by user
1339 if (ref($item->notes) and @{$item->notes}) {
1340 foreach my $note (@{$item->notes}) {
1341 $note->creator($user_id);
1342 $note->create_date("now");
1344 return $e->die_event unless $e->create_serial_item_note($note);
1347 $item->clear_notes; # They're saved; we no longer want them here.
1350 # Set the incontrovertibles on the item
1351 $item->status("Received");
1352 $item->date_received("now");
1353 $item->edit_date("now");
1354 $item->editor($user_id);
1356 return $e->die_event unless $e->update_serial_item($item);
1358 # send client a response
1359 $client->respond($item->id);
1362 $e->commit or return $e->die_event;
1370 my $skip_call_number = shift;
1372 my $attr = $mode . '_unit_template';
1373 my $template = $editor->retrieve_asset_copy_template($sdist->$attr) or
1374 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_COPY_TEMPLATE");
1376 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 );
1378 my $unit = new Fieldmapper::serial::unit;
1379 foreach my $part (@parts) {
1380 my $value = $template->$part;
1381 next if !defined($value);
1382 $unit->$part($value);
1385 # ignore circ_lib in template, set to distribution holding_lib
1386 $unit->circ_lib($sdist->holding_lib);
1387 $unit->creator($editor->requestor->id);
1388 $unit->editor($editor->requestor->id);
1390 unless ($skip_call_number) {
1391 $attr = $mode . '_call_number';
1392 my $cn = $sdist->$attr or
1393 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_CALL_NUMBER");
1395 $unit->call_number($cn);
1398 $unit->barcode('AUTO');
1399 $unit->sort_key('');
1400 $unit->summary_contents('');
1401 $unit->detailed_contents('');
1407 sub _summarize_contents {
1409 my $issuances = shift;
1411 # create MFHD record
1412 my $mfhd = MFHD->new(MARC::Record->new());
1415 my @scap_fields_ordered;
1418 foreach my $issuance (@$issuances) {
1419 my $scap_id = $issuance->caption_and_pattern;
1420 next if (!$scap_id); # skip issuances with no caption/pattern
1424 # if this is the first appearance of this scap, retrieve it and add it to the temporary record
1425 if (!exists $scaps{$issuance->caption_and_pattern}) {
1426 $scaps{$scap_id} = $editor->retrieve_serial_caption_and_pattern($scap_id);
1427 $scap = $scaps{$scap_id};
1428 $scap_field = _revive_caption($scap);
1429 $scap_fields{$scap_id} = $scap_field;
1430 push(@scap_fields_ordered, $scap_field);
1431 $scap_field->update('8' => $link_id);
1432 $mfhd->append_fields($scap_field);
1435 $scap = $scaps{$scap_id};
1436 $scap_field = $scap_fields{$scap_id};
1439 $mfhd->append_fields(_revive_holding($issuance->holding_code, $scap_field, $seqno));
1443 my @formatted_parts;
1444 foreach my $scap_field (@scap_fields_ordered) { #TODO: use generic MFHD "summarize" method, once available
1445 my @updated_holdings = $mfhd->get_compressed_holdings($scap_field);
1446 foreach my $holding (@updated_holdings) {
1447 push(@formatted_parts, $holding->format);
1451 return ($mfhd, \@formatted_parts);
1454 ##########################################################################
1457 __PACKAGE__->register_method(
1458 method => 'fetch_notes',
1459 api_name => 'open-ils.serial.item_note.retrieve.all',
1461 Returns an array of copy note objects.
1462 @param args A named hash of parameters including:
1463 authtoken : Required if viewing non-public notes
1464 item_id : The id of the item whose notes we want to retrieve
1465 pub : True if all the caller wants are public notes
1466 @return An array of note objects
1470 __PACKAGE__->register_method(
1471 method => 'fetch_notes',
1472 api_name => 'open-ils.serial.subscription_note.retrieve.all',
1474 Returns an array of copy note objects.
1475 @param args A named hash of parameters including:
1476 authtoken : Required if viewing non-public notes
1477 subscription_id : The id of the item whose notes we want to retrieve
1478 pub : True if all the caller wants are public notes
1479 @return An array of note objects
1483 __PACKAGE__->register_method(
1484 method => 'fetch_notes',
1485 api_name => 'open-ils.serial.distribution_note.retrieve.all',
1487 Returns an array of copy note objects.
1488 @param args A named hash of parameters including:
1489 authtoken : Required if viewing non-public notes
1490 distribution_id : The id of the item whose notes we want to retrieve
1491 pub : True if all the caller wants are public notes
1492 @return An array of note objects
1496 # TODO: revisit this method to consider replacing cstore direct calls
1498 my( $self, $connection, $args ) = @_;
1500 $self->api_name =~ /serial\.(\w*)_note/;
1503 my $id = $$args{object_id};
1504 my $authtoken = $$args{authtoken};
1508 return $U->cstorereq(
1509 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic',
1510 { $type => $id, pub => 't' } );
1512 # FIXME: restore perm check
1513 # ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
1514 # return $evt if $evt;
1515 return $U->cstorereq(
1516 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic', {$type => $id} );
1522 __PACKAGE__->register_method(
1523 method => 'create_note',
1524 api_name => 'open-ils.serial.item_note.create',
1526 Creates a new item note
1527 @param authtoken The login session key
1528 @param note The note object to create
1529 @return The id of the new note object
1533 __PACKAGE__->register_method(
1534 method => 'create_note',
1535 api_name => 'open-ils.serial.subscription_note.create',
1537 Creates a new subscription note
1538 @param authtoken The login session key
1539 @param note The note object to create
1540 @return The id of the new note object
1544 __PACKAGE__->register_method(
1545 method => 'create_note',
1546 api_name => 'open-ils.serial.distribution_note.create',
1548 Creates a new distribution note
1549 @param authtoken The login session key
1550 @param note The note object to create
1551 @return The id of the new note object
1556 my( $self, $connection, $authtoken, $note ) = @_;
1558 $self->api_name =~ /serial\.(\w*)_note/;
1561 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1562 return $e->event unless $e->checkauth;
1564 # FIXME: restore permission support
1565 # my $item = $e->retrieve_serial_item(
1571 # return $e->event unless
1572 # $e->allowed('CREATE_COPY_NOTE', $item->call_number->owning_lib);
1574 $note->create_date('now');
1575 $note->creator($e->requestor->id);
1576 $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
1579 my $method = "create_serial_${type}_note";
1580 $e->$method($note) or return $e->event;
1585 __PACKAGE__->register_method(
1586 method => 'delete_note',
1587 api_name => 'open-ils.serial.item_note.delete',
1589 Deletes an existing item note
1590 @param authtoken The login session key
1591 @param noteid The id of the note to delete
1592 @return 1 on success - Event otherwise.
1596 __PACKAGE__->register_method(
1597 method => 'delete_note',
1598 api_name => 'open-ils.serial.subscription_note.delete',
1600 Deletes an existing subscription note
1601 @param authtoken The login session key
1602 @param noteid The id of the note to delete
1603 @return 1 on success - Event otherwise.
1607 __PACKAGE__->register_method(
1608 method => 'delete_note',
1609 api_name => 'open-ils.serial.distribution_note.delete',
1611 Deletes an existing distribution note
1612 @param authtoken The login session key
1613 @param noteid The id of the note to delete
1614 @return 1 on success - Event otherwise.
1619 my( $self, $conn, $authtoken, $noteid ) = @_;
1621 $self->api_name =~ /serial\.(\w*)_note/;
1624 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1625 return $e->die_event unless $e->checkauth;
1627 my $method = "retrieve_serial_${type}_note";
1628 my $note = $e->$method([
1630 ]) or return $e->die_event;
1632 # FIXME: restore permissions check
1633 # if( $note->creator ne $e->requestor->id ) {
1634 # return $e->die_event unless
1635 # $e->allowed('DELETE_COPY_NOTE', $note->item->call_number->owning_lib);
1638 $method = "delete_serial_${type}_note";
1639 $e->$method($note) or return $e->die_event;
1645 ##########################################################################
1646 # subscription methods
1648 __PACKAGE__->register_method(
1649 method => 'fleshed_ssub_alter',
1650 api_name => 'open-ils.serial.subscription.fleshed.batch.update',
1654 desc => 'Receives an array of one or more subscriptions and updates the database as needed',
1656 name => 'authtoken',
1657 desc => 'Authtoken for current user session',
1661 name => 'subscriptions',
1662 desc => 'Array of fleshed subscriptions',
1668 desc => 'Returns 1 if successful, event if failed',
1674 sub fleshed_ssub_alter {
1675 my( $self, $conn, $auth, $ssubs ) = @_;
1676 return 1 unless ref $ssubs;
1677 my( $reqr, $evt ) = $U->checkses($auth);
1678 return $evt if $evt;
1679 my $editor = new_editor(requestor => $reqr, xact => 1);
1680 my $override = $self->api_name =~ /override/;
1682 # TODO: permission check
1683 # return $editor->event unless
1684 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
1686 for my $ssub (@$ssubs) {
1688 my $ssubid = $ssub->id;
1690 if( $ssub->isdeleted ) {
1691 $evt = _delete_ssub( $editor, $override, $ssub);
1692 } elsif( $ssub->isnew ) {
1693 _cleanse_dates($ssub, ['start_date','end_date']);
1694 $evt = _create_ssub( $editor, $ssub );
1696 _cleanse_dates($ssub, ['start_date','end_date']);
1697 $evt = _update_ssub( $editor, $override, $ssub );
1702 $logger->info("fleshed subscription-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
1706 $logger->debug("subscription-alter: done updating subscription batch");
1708 $logger->info("fleshed subscription-alter successfully updated ".scalar(@$ssubs)." subscriptions");
1713 my ($editor, $override, $ssub) = @_;
1714 $logger->info("subscription-alter: delete subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1715 my $sdists = $editor->search_serial_distribution(
1716 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1717 my $cps = $editor->search_serial_caption_and_pattern(
1718 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1719 my $sisses = $editor->search_serial_issuance(
1720 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1721 return OpenILS::Event->new(
1722 'SERIAL_SUBSCRIPTION_NOT_EMPTY', payload => $ssub->id ) if (@$sdists or @$cps or @$sisses);
1724 return $editor->event unless $editor->delete_serial_subscription($ssub);
1729 my ($editor, $ssub) = @_;
1731 $logger->info("subscription-alter: new subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1732 return $editor->event unless $editor->create_serial_subscription($ssub);
1737 my ($editor, $override, $ssub) = @_;
1739 $logger->info("subscription-alter: retrieving subscription ".$ssub->id);
1740 my $orig_ssub = $editor->retrieve_serial_subscription($ssub->id);
1742 $logger->info("subscription-alter: original subscription ".OpenSRF::Utils::JSON->perl2JSON($orig_ssub));
1743 $logger->info("subscription-alter: updated subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1744 return $editor->event unless $editor->update_serial_subscription($ssub);
1748 __PACKAGE__->register_method(
1749 method => "fleshed_serial_subscription_retrieve_batch",
1751 api_name => "open-ils.serial.subscription.fleshed.batch.retrieve"
1754 sub fleshed_serial_subscription_retrieve_batch {
1755 my( $self, $client, $ids ) = @_;
1756 # FIXME: permissions?
1757 $logger->info("Fetching fleshed subscriptions @$ids");
1758 return $U->cstorereq(
1759 "open-ils.cstore.direct.serial.subscription.search.atomic",
1762 flesh_fields => {ssub => [ qw/owning_lib notes/ ]}
1766 __PACKAGE__->register_method(
1767 method => "retrieve_sub_tree",
1769 api_name => "open-ils.serial.subscription_tree.retrieve"
1772 __PACKAGE__->register_method(
1773 method => "retrieve_sub_tree",
1774 api_name => "open-ils.serial.subscription_tree.global.retrieve"
1777 sub retrieve_sub_tree {
1779 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
1781 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
1785 # TODO: permission support
1786 if(!@org_ids and $user_session) {
1788 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
1789 @org_ids = ($user_obj->home_ou);
1792 if( $self->api_name =~ /global/ ) {
1793 return _build_subs_list( { record_entry => $docid } ); # TODO: filter for !deleted, or active?
1798 for my $orgid (@org_ids) {
1799 my $subs = _build_subs_list(
1800 { record_entry => $docid, owning_lib => $orgid } );# TODO: filter for !deleted, or active?
1801 push( @all_subs, @$subs );
1810 sub _build_subs_list {
1811 my $search_hash = shift;
1813 #$search_hash->{deleted} = 'f';
1814 my $e = new_editor();
1816 my $subs = $e->search_serial_subscription([$search_hash, { 'order_by' => {'ssub' => 'id'} }]);
1820 for my $sub (@$subs) {
1822 # TODO: filter on !deleted?
1823 my $dists = $e->search_serial_distribution(
1824 [{ subscription => $sub->id }, { 'order_by' => {'sdist' => 'label'} }]
1827 #$dists = [ sort { $a->label cmp $b->label } @$dists ];
1829 $sub->distributions($dists);
1831 # TODO: filter on !deleted?
1832 my $issuances = $e->search_serial_issuance(
1833 [{ subscription => $sub->id }, { 'order_by' => {'siss' => 'label'} }]
1836 #$issuances = [ sort { $a->label cmp $b->label } @$issuances ];
1837 $sub->issuances($issuances);
1839 # TODO: filter on !deleted?
1840 my $scaps = $e->search_serial_caption_and_pattern(
1841 [{ subscription => $sub->id }, { 'order_by' => {'scap' => 'id'} }]
1844 #$scaps = [ sort { $a->id cmp $b->id } @$scaps ];
1845 $sub->scaps($scaps);
1846 push( @built_subs, $sub );
1849 return \@built_subs;
1853 __PACKAGE__->register_method(
1854 method => "subscription_orgs_for_title",
1856 api_name => "open-ils.serial.subscription.retrieve_orgs_by_title"
1859 sub subscription_orgs_for_title {
1860 my( $self, $client, $record_id ) = @_;
1862 my $subs = $U->simple_scalar_request(
1864 "open-ils.cstore.direct.serial.subscription.search.atomic",
1865 { record_entry => $record_id }); # TODO: filter on !deleted?
1867 my $orgs = { map {$_->owning_lib => 1 } @$subs };
1868 return [ keys %$orgs ];
1872 ##########################################################################
1873 # distribution methods
1875 __PACKAGE__->register_method(
1876 method => 'fleshed_sdist_alter',
1877 api_name => 'open-ils.serial.distribution.fleshed.batch.update',
1881 desc => 'Receives an array of one or more distributions and updates the database as needed',
1883 name => 'authtoken',
1884 desc => 'Authtoken for current user session',
1888 name => 'distributions',
1889 desc => 'Array of fleshed distributions',
1895 desc => 'Returns 1 if successful, event if failed',
1901 sub fleshed_sdist_alter {
1902 my( $self, $conn, $auth, $sdists ) = @_;
1903 return 1 unless ref $sdists;
1904 my( $reqr, $evt ) = $U->checkses($auth);
1905 return $evt if $evt;
1906 my $editor = new_editor(requestor => $reqr, xact => 1);
1907 my $override = $self->api_name =~ /override/;
1909 # TODO: permission check
1910 # return $editor->event unless
1911 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
1913 for my $sdist (@$sdists) {
1914 my $sdistid = $sdist->id;
1916 if( $sdist->isdeleted ) {
1917 $evt = _delete_sdist( $editor, $override, $sdist);
1918 } elsif( $sdist->isnew ) {
1919 $evt = _create_sdist( $editor, $sdist );
1921 $evt = _update_sdist( $editor, $override, $sdist );
1926 $logger->info("fleshed distribution-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
1930 $logger->debug("distribution-alter: done updating distribution batch");
1932 $logger->info("fleshed distribution-alter successfully updated ".scalar(@$sdists)." distributions");
1937 my ($editor, $override, $sdist) = @_;
1938 $logger->info("distribution-alter: delete distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
1939 return $editor->event unless $editor->delete_serial_distribution($sdist);
1944 my ($editor, $sdist) = @_;
1946 $logger->info("distribution-alter: new distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
1947 return $editor->event unless $editor->create_serial_distribution($sdist);
1949 # create summaries too
1950 my $summary = new Fieldmapper::serial::basic_summary;
1951 $summary->distribution($sdist->id);
1952 $summary->generated_coverage('');
1953 return $editor->event unless $editor->create_serial_basic_summary($summary);
1954 $summary = new Fieldmapper::serial::supplement_summary;
1955 $summary->distribution($sdist->id);
1956 $summary->generated_coverage('');
1957 return $editor->event unless $editor->create_serial_supplement_summary($summary);
1958 $summary = new Fieldmapper::serial::index_summary;
1959 $summary->distribution($sdist->id);
1960 $summary->generated_coverage('');
1961 return $editor->event unless $editor->create_serial_index_summary($summary);
1963 # create a starter stream (TODO: reconsider this)
1964 my $stream = new Fieldmapper::serial::stream;
1965 $stream->distribution($sdist->id);
1966 return $editor->event unless $editor->create_serial_stream($stream);
1972 my ($editor, $override, $sdist) = @_;
1974 $logger->info("distribution-alter: retrieving distribution ".$sdist->id);
1975 my $orig_sdist = $editor->retrieve_serial_distribution($sdist->id);
1977 $logger->info("distribution-alter: original distribution ".OpenSRF::Utils::JSON->perl2JSON($orig_sdist));
1978 $logger->info("distribution-alter: updated distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
1979 return $editor->event unless $editor->update_serial_distribution($sdist);
1983 __PACKAGE__->register_method(
1984 method => "fleshed_serial_distribution_retrieve_batch",
1986 api_name => "open-ils.serial.distribution.fleshed.batch.retrieve"
1989 sub fleshed_serial_distribution_retrieve_batch {
1990 my( $self, $client, $ids ) = @_;
1991 # FIXME: permissions?
1992 $logger->info("Fetching fleshed distributions @$ids");
1993 return $U->cstorereq(
1994 "open-ils.cstore.direct.serial.distribution.search.atomic",
1997 flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams / ]}
2001 ##########################################################################
2002 # caption and pattern methods
2004 __PACKAGE__->register_method(
2005 method => 'scap_alter',
2006 api_name => 'open-ils.serial.caption_and_pattern.batch.update',
2010 desc => 'Receives an array of one or more caption and patterns and updates the database as needed',
2012 name => 'authtoken',
2013 desc => 'Authtoken for current user session',
2018 desc => 'Array of caption and patterns',
2024 desc => 'Returns 1 if successful, event if failed',
2031 my( $self, $conn, $auth, $scaps ) = @_;
2032 return 1 unless ref $scaps;
2033 my( $reqr, $evt ) = $U->checkses($auth);
2034 return $evt if $evt;
2035 my $editor = new_editor(requestor => $reqr, xact => 1);
2036 my $override = $self->api_name =~ /override/;
2038 # TODO: permission check
2039 # return $editor->event unless
2040 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
2042 for my $scap (@$scaps) {
2043 my $scapid = $scap->id;
2045 if( $scap->isdeleted ) {
2046 $evt = _delete_scap( $editor, $override, $scap);
2047 } elsif( $scap->isnew ) {
2048 $evt = _create_scap( $editor, $scap );
2050 $evt = _update_scap( $editor, $override, $scap );
2055 $logger->info("caption_and_pattern-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2059 $logger->debug("caption_and_pattern-alter: done updating caption_and_pattern batch");
2061 $logger->info("caption_and_pattern-alter successfully updated ".scalar(@$scaps)." caption_and_patterns");
2066 my ($editor, $override, $scap) = @_;
2067 $logger->info("caption_and_pattern-alter: delete caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2068 my $sisses = $editor->search_serial_issuance(
2069 { caption_and_pattern => $scap->id }, { limit => 1 } ); #TODO: 'deleted' support?
2070 return OpenILS::Event->new(
2071 'SERIAL_CAPTION_AND_PATTERN_HAS_ISSUANCES', payload => $scap->id ) if (@$sisses);
2073 return $editor->event unless $editor->delete_serial_caption_and_pattern($scap);
2078 my ($editor, $scap) = @_;
2080 $logger->info("caption_and_pattern-alter: new caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2081 return $editor->event unless $editor->create_serial_caption_and_pattern($scap);
2086 my ($editor, $override, $scap) = @_;
2088 $logger->info("caption_and_pattern-alter: retrieving caption_and_pattern ".$scap->id);
2089 my $orig_scap = $editor->retrieve_serial_caption_and_pattern($scap->id);
2091 $logger->info("caption_and_pattern-alter: original caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($orig_scap));
2092 $logger->info("caption_and_pattern-alter: updated caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2093 return $editor->event unless $editor->update_serial_caption_and_pattern($scap);
2097 __PACKAGE__->register_method(
2098 method => "serial_caption_and_pattern_retrieve_batch",
2100 api_name => "open-ils.serial.caption_and_pattern.batch.retrieve"
2103 sub serial_caption_and_pattern_retrieve_batch {
2104 my( $self, $client, $ids ) = @_;
2105 $logger->info("Fetching caption_and_patterns @$ids");
2106 return $U->cstorereq(
2107 "open-ils.cstore.direct.serial.caption_and_pattern.search.atomic",
2112 __PACKAGE__->register_method(
2113 "method" => "bre_by_identifier",
2114 "api_name" => "open-ils.serial.biblio.record_entry.by_identifier",
2117 "desc" => "Find instances of biblio.record_entry given a search token" .
2118 " that could be a value for any identifier defined in " .
2119 "config.metabib_field",
2121 {"desc" => "Search token", "type" => "string"},
2122 {"desc" => "Options: require_subscriptions, add_mvr, is_actual_id" .
2123 " (all boolean)", "type" => "object"}
2126 "desc" => "Any matching BREs, or if the add_mvr option is true, " .
2127 "objects with a 'bre' key/value pair, and an 'mvr' " .
2128 "key-value pair. BREs have subscriptions fleshed on.",
2134 sub bre_by_identifier {
2135 my ($self, $client, $term, $options) = @_;
2137 return new OpenILS::Event("BAD_PARAMS") unless $term;
2140 my $e = new_editor();
2144 if ($options->{"is_actual_id"}) {
2148 $e->search_config_metabib_field({"field_class" => "identifier"})
2149 or return $e->die_event;
2151 my @identifiers = map { $_->name } @$cmf;
2152 my $query = join(" || ", map { "id|$_: $term" } @identifiers);
2154 my $search = create OpenSRF::AppSession("open-ils.search");
2155 my $search_result = $search->request(
2156 "open-ils.search.biblio.multiclass.query.staff", {}, $query
2158 $search->disconnect;
2160 # Un-nest results. They tend to look like [[1],[2],[3]] for some reason.
2161 @ids = map { @{$_} } @{$search_result->{"ids"}};
2169 my $bre = $e->search_biblio_record_entry([
2171 "flesh" => 2, "flesh_fields" => {
2172 "bre" => ["subscriptions"],
2173 "ssub" => ["owning_lib"]
2176 ]) or return $e->die_event;
2178 if (@$bre && $options->{"require_subscriptions"}) {
2179 $bre = [ grep { @{$_->subscriptions} } @$bre ];
2184 if (@$bre) { # re-evaluate after possible grep
2185 if ($options->{"add_mvr"}) {
2187 {"bre" => $_, "mvr" => _get_mvr($_->id)}
2190 $client->respond($_) foreach (@$bre);
2197 __PACKAGE__->register_method(
2198 "method" => "get_receivable_items",
2199 "api_name" => "open-ils.serial.items.receivable.by_subscription",
2202 "desc" => "Return all receivable items under a given subscription",
2204 {"desc" => "Authtoken", "type" => "string"},
2205 {"desc" => "Subscription ID", "type" => "number"},
2208 "desc" => "All receivable items under a given subscription",
2214 __PACKAGE__->register_method(
2215 "method" => "get_receivable_items",
2216 "api_name" => "open-ils.serial.items.receivable.by_issuance",
2219 "desc" => "Return all receivable items under a given issuance",
2221 {"desc" => "Authtoken", "type" => "string"},
2222 {"desc" => "Issuance ID", "type" => "number"},
2225 "desc" => "All receivable items under a given issuance",
2231 sub get_receivable_items {
2232 my ($self, $client, $auth, $term) = @_;
2234 my $e = new_editor("authtoken" => $auth);
2235 return $e->die_event unless $e->checkauth;
2239 my $by = ($self->api_name =~ /by_(\w+)$/)[0];
2242 "issuance" => {"issuance" => $term},
2243 "subscription" => {"+siss" => {"subscription" => $term}}
2246 my $item_ids = $e->json_query(
2248 "select" => {"sitem" => ["id"]},
2249 "from" => {"sitem" => "siss"},
2251 %{$where{$by}}, "date_received" => undef
2253 "order_by" => {"sitem" => ["id"]}
2255 ) or return $e->die_event;
2257 return undef unless @$item_ids;
2259 foreach (map { $_->{"id"} } @$item_ids) {
2261 $e->retrieve_serial_item([
2265 "sitem" => ["stream", "issuance"],
2266 "sstr" => ["distribution"],
2267 "sdist" => ["holding_lib"]
2278 __PACKAGE__->register_method(
2279 "method" => "get_receivable_issuances",
2280 "api_name" => "open-ils.serial.issuances.receivable",
2283 "desc" => "Return all issuances with receivable items given " .
2284 "a subscription ID",
2286 {"desc" => "Authtoken", "type" => "string"},
2287 {"desc" => "Subscription ID", "type" => "number"},
2290 "desc" => "All issuances with receivable items " .
2291 "(but not the items themselves)", "type" => "object"
2296 sub get_receivable_issuances {
2297 my ($self, $client, $auth, $sub_id) = @_;
2299 my $e = new_editor("authtoken" => $auth);
2300 return $e->die_event unless $e->checkauth;
2304 my $issuance_ids = $e->json_query({
2307 {"transform" => "distinct", "column" => "id"},
2311 "from" => {"siss" => "sitem"},
2313 "subscription" => $sub_id,
2314 "+sitem" => {"date_received" => undef}
2317 "siss" => {"date_published" => {"direction" => "asc"}}
2320 }) or return $e->die_event;
2322 $client->respond($e->retrieve_serial_issuance($_->{"id"}))
2323 foreach (@$issuance_ids);