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');
64 # helper method for conforming dates to ISO8601
69 foreach my $field (@$fields) {
70 $item->$field(OpenSRF::Utils::clense_ISO8601($item->$field)) if $item->$field;
78 "open-ils.search.biblio.record.mods_slim.retrieve",
84 ##########################################################################
87 __PACKAGE__->register_method(
88 method => 'fleshed_item_alter',
89 api_name => 'open-ils.serial.item.fleshed.batch.update',
93 desc => 'Receives an array of one or more items and updates the database as needed',
96 desc => 'Authtoken for current user session',
101 desc => 'Array of fleshed items',
107 desc => 'Returns 1 if successful, event if failed',
113 sub fleshed_item_alter {
114 my( $self, $conn, $auth, $items ) = @_;
115 return 1 unless ref $items;
116 my( $reqr, $evt ) = $U->checkses($auth);
118 my $editor = new_editor(requestor => $reqr, xact => 1);
119 my $override = $self->api_name =~ /override/;
121 # TODO: permission check
122 # return $editor->event unless
123 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
125 for my $item (@$items) {
127 my $itemid = $item->id;
128 $item->editor($editor->requestor->id);
129 $item->edit_date('now');
131 if( $item->isdeleted ) {
132 $evt = _delete_sitem( $editor, $override, $item);
133 } elsif( $item->isnew ) {
134 # TODO: reconsider this
135 # if the item has a new issuance, create the issuance first
136 if (ref $item->issuance eq 'Fieldmapper::serial::issuance' and $item->issuance->isnew) {
137 fleshed_issuance_alter($self, $conn, $auth, [$item->issuance]);
139 _cleanse_dates($item, ['date_expected','date_received']);
140 $evt = _create_sitem( $editor, $item );
142 _cleanse_dates($item, ['date_expected','date_received']);
143 $evt = _update_sitem( $editor, $override, $item );
148 $logger->info("fleshed item-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
152 $logger->debug("item-alter: done updating item batch");
154 $logger->info("fleshed item-alter successfully updated ".scalar(@$items)." items");
159 my ($editor, $override, $item) = @_;
160 $logger->info("item-alter: delete item ".OpenSRF::Utils::JSON->perl2JSON($item));
161 return $editor->event unless $editor->delete_serial_item($item);
166 my ($editor, $item) = @_;
168 $item->creator($editor->requestor->id);
169 $item->create_date('now');
171 $logger->info("item-alter: new item ".OpenSRF::Utils::JSON->perl2JSON($item));
172 return $editor->event unless $editor->create_serial_item($item);
177 my ($editor, $override, $item) = @_;
179 $logger->info("item-alter: retrieving item ".$item->id);
180 my $orig_item = $editor->retrieve_serial_item($item->id);
182 $logger->info("item-alter: original item ".OpenSRF::Utils::JSON->perl2JSON($orig_item));
183 $logger->info("item-alter: updated item ".OpenSRF::Utils::JSON->perl2JSON($item));
184 return $editor->event unless $editor->update_serial_item($item);
188 __PACKAGE__->register_method(
189 method => "fleshed_serial_item_retrieve_batch",
191 api_name => "open-ils.serial.item.fleshed.batch.retrieve"
194 sub fleshed_serial_item_retrieve_batch {
195 my( $self, $client, $ids ) = @_;
196 # FIXME: permissions?
197 $logger->info("Fetching fleshed serial items @$ids");
198 return $U->cstorereq(
199 "open-ils.cstore.direct.serial.item.search.atomic",
202 flesh_fields => {sitem => [ qw/issuance creator editor stream unit notes/ ], sstr => ["distribution"], sunit => ["call_number"], siss => [qw/creator editor subscription/]}
207 ##########################################################################
210 __PACKAGE__->register_method(
211 method => 'fleshed_issuance_alter',
212 api_name => 'open-ils.serial.issuance.fleshed.batch.update',
216 desc => 'Receives an array of one or more issuances and updates the database as needed',
219 desc => 'Authtoken for current user session',
224 desc => 'Array of fleshed issuances',
230 desc => 'Returns 1 if successful, event if failed',
236 sub fleshed_issuance_alter {
237 my( $self, $conn, $auth, $issuances ) = @_;
238 return 1 unless ref $issuances;
239 my( $reqr, $evt ) = $U->checkses($auth);
241 my $editor = new_editor(requestor => $reqr, xact => 1);
242 my $override = $self->api_name =~ /override/;
244 # TODO: permission support
245 # return $editor->event unless
246 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
248 for my $issuance (@$issuances) {
249 my $issuanceid = $issuance->id;
250 $issuance->editor($editor->requestor->id);
251 $issuance->edit_date('now');
253 if( $issuance->isdeleted ) {
254 $evt = _delete_siss( $editor, $override, $issuance);
255 } elsif( $issuance->isnew ) {
256 _cleanse_dates($issuance, ['date_published']);
257 $evt = _create_siss( $editor, $issuance );
259 _cleanse_dates($issuance, ['date_published']);
260 $evt = _update_siss( $editor, $override, $issuance );
265 $logger->info("fleshed issuance-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
269 $logger->debug("issuance-alter: done updating issuance batch");
271 $logger->info("fleshed issuance-alter successfully updated ".scalar(@$issuances)." issuances");
276 my ($editor, $override, $issuance) = @_;
277 $logger->info("issuance-alter: delete issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
278 return $editor->event unless $editor->delete_serial_issuance($issuance);
283 my ($editor, $issuance) = @_;
285 $issuance->creator($editor->requestor->id);
286 $issuance->create_date('now');
288 $logger->info("issuance-alter: new issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
289 return $editor->event unless $editor->create_serial_issuance($issuance);
294 my ($editor, $override, $issuance) = @_;
296 $logger->info("issuance-alter: retrieving issuance ".$issuance->id);
297 my $orig_issuance = $editor->retrieve_serial_issuance($issuance->id);
299 $logger->info("issuance-alter: original issuance ".OpenSRF::Utils::JSON->perl2JSON($orig_issuance));
300 $logger->info("issuance-alter: updated issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
301 return $editor->event unless $editor->update_serial_issuance($issuance);
305 __PACKAGE__->register_method(
306 method => "fleshed_serial_issuance_retrieve_batch",
308 api_name => "open-ils.serial.issuance.fleshed.batch.retrieve"
311 sub fleshed_serial_issuance_retrieve_batch {
312 my( $self, $client, $ids ) = @_;
313 # FIXME: permissions?
314 $logger->info("Fetching fleshed serial issuances @$ids");
315 return $U->cstorereq(
316 "open-ils.cstore.direct.serial.issuance.search.atomic",
319 flesh_fields => {siss => [ qw/creator editor subscription/ ]}
323 __PACKAGE__->register_method(
324 method => "pub_fleshed_serial_issuance_retrieve_batch",
325 api_name => "open-ils.serial.issuance.pub_fleshed.batch.retrieve",
328 Public (i.e. OPAC) call for getting at the sub and
329 ultimately the record entry from an issuance
331 params => [{name => 'ids', desc => 'Array of IDs', type => 'array'}],
334 issuance objects, fleshed with subscriptions
340 sub pub_fleshed_serial_issuance_retrieve_batch {
341 my( $self, $client, $ids ) = @_;
342 return [] unless $ids and @$ids;
343 return new_editor()->search_serial_issuance([
347 flesh_fields => {siss => [ qw/subscription/ ]}
353 ##########################################################################
356 __PACKAGE__->register_method(
357 method => 'fleshed_sunit_alter',
358 api_name => 'open-ils.serial.sunit.fleshed.batch.update',
362 desc => 'Receives an array of one or more Units and updates the database as needed',
365 desc => 'Authtoken for current user session',
370 desc => 'Array of fleshed Units',
376 desc => 'Returns 1 if successful, event if failed',
382 sub fleshed_sunit_alter {
383 my( $self, $conn, $auth, $sunits ) = @_;
384 return 1 unless ref $sunits;
385 my( $reqr, $evt ) = $U->checkses($auth);
387 my $editor = new_editor(requestor => $reqr, xact => 1);
388 my $override = $self->api_name =~ /override/;
390 # TODO: permission support
391 # return $editor->event unless
392 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
394 for my $sunit (@$sunits) {
395 if( $sunit->isdeleted ) {
396 $evt = _delete_sunit( $editor, $override, $sunit );
398 $sunit->default_location( $sunit->default_location->id ) if ref $sunit->default_location;
400 if( $sunit->isnew ) {
401 $evt = _create_sunit( $editor, $sunit );
403 $evt = _update_sunit( $editor, $override, $sunit );
409 $logger->info("fleshed sunit-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
413 $logger->debug("sunit-alter: done updating sunit batch");
415 $logger->info("fleshed sunit-alter successfully updated ".scalar(@$sunits)." Units");
420 my ($editor, $override, $sunit) = @_;
421 $logger->info("sunit-alter: delete sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
422 return $editor->event unless $editor->delete_serial_unit($sunit);
427 my ($editor, $sunit) = @_;
429 $logger->info("sunit-alter: new Unit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
430 return $editor->event unless $editor->create_serial_unit($sunit);
435 my ($editor, $override, $sunit) = @_;
437 $logger->info("sunit-alter: retrieving sunit ".$sunit->id);
438 my $orig_sunit = $editor->retrieve_serial_unit($sunit->id);
440 $logger->info("sunit-alter: original sunit ".OpenSRF::Utils::JSON->perl2JSON($orig_sunit));
441 $logger->info("sunit-alter: updated sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
442 return $editor->event unless $editor->update_serial_unit($sunit);
446 __PACKAGE__->register_method(
447 method => "retrieve_unit_list",
449 api_name => "open-ils.serial.unit_list.retrieve"
452 sub retrieve_unit_list {
454 my( $self, $client, @sdist_ids ) = @_;
456 if(ref($sdist_ids[0])) { @sdist_ids = @{$sdist_ids[0]}; }
458 my $e = new_editor();
462 { 'sunit' => [ 'id', 'summary_contents', 'sort_key' ],
463 'sitem' => ['stream'],
464 'sstr' => ['distribution'],
465 'sdist' => [{'column' => 'label', 'alias' => 'sdist_label'}]
472 { 'join' => { 'sunit' => {} } }
477 'distinct' => 'true',
478 'where' => { '+sdist' => {'id' => \@sdist_ids} },
479 'order_by' => [{'class' => 'sunit', 'field' => 'sort_key'}]
482 my $unit_list_entries = $e->json_query($query);
485 foreach my $entry (@$unit_list_entries) {
486 my $value = {'sunit' => $entry->{id}, 'sstr' => $entry->{stream}, 'sdist' => $entry->{distribution}};
487 my $label = $entry->{summary_contents};
488 if (length($label) > 100) {
489 $label = substr($label, 0, 100) . '...'; # limited space in dropdown / menu
491 $label = "[$entry->{sdist_label}/$entry->{stream} #$entry->{id}] " . $label;
492 push (@entries, [$label, OpenSRF::Utils::JSON->perl2JSON($value)]);
500 ##########################################################################
501 # predict and receive methods
503 __PACKAGE__->register_method(
504 method => 'make_predictions',
505 api_name => 'open-ils.serial.make_predictions',
509 desc => 'Receives an ssub id and populates the issuance and item tables',
512 desc => 'Serial Subscription ID',
519 sub make_predictions {
520 my ($self, $conn, $authtoken, $args) = @_;
522 my $editor = OpenILS::Utils::CStoreEditor->new();
523 my $ssub_id = $args->{ssub_id};
524 my $mfhd = MFHD->new(MARC::Record->new());
526 my $ssub = $editor->retrieve_serial_subscription([$ssub_id]);
527 my $scaps = $editor->search_serial_caption_and_pattern({ subscription => $ssub_id, active => 't'});
528 my $sdists = $editor->search_serial_distribution( [{ subscription => $ssub->id }, { flesh => 1,
529 flesh_fields => {sdist => [ qw/ streams / ]}, limit => 1 }] ); #TODO: 'deleted' support?
533 foreach my $scap (@$scaps) {
534 my $caption_field = _revive_caption($scap);
535 $caption_field->update('8' => $link_id);
536 $mfhd->append_fields($caption_field);
538 'caption' => $caption_field,
539 'scap_id' => $scap->id,
540 'num_to_predict' => $args->{num_to_predict}
542 if ($args->{base_issuance}) { # predict from a given issuance
543 $options->{predict_from} = _revive_holding($args->{base_issuance}->holding_code, $caption_field, 1); # fresh MFHD Record, so we simply default to 1 for seqno
544 } else { # default to predicting from last published
545 my $last_published = $editor->search_serial_issuance([
546 {'caption_and_pattern' => $scap->id,
547 'subscription' => $ssub_id},
548 {limit => 1, order_by => { siss => "date_published DESC" }}]
550 if ($last_published->[0]) {
551 my $last_siss = $last_published->[0];
552 $options->{predict_from} = _revive_holding($last_siss->holding_code, $caption_field, 1);
554 #TODO: throw event (can't predict from nothing!)
557 push( @predictions, _generate_issuance_values($mfhd, $options) );
562 foreach my $prediction (@predictions) {
563 my $issuance = new Fieldmapper::serial::issuance;
565 $issuance->label($prediction->{label});
566 $issuance->date_published($prediction->{date_published}->strftime('%F'));
567 $issuance->holding_code(OpenSRF::Utils::JSON->perl2JSON($prediction->{holding_code}));
568 $issuance->holding_type($prediction->{holding_type});
569 $issuance->caption_and_pattern($prediction->{caption_and_pattern});
570 $issuance->subscription($ssub->id);
571 push (@issuances, $issuance);
574 fleshed_issuance_alter($self, $conn, $authtoken, \@issuances); # FIXME: catch events
577 for (my $i = 0; $i < @issuances; $i++) {
578 my $date_expected = $predictions[$i]->{date_published}->add(seconds => interval_to_seconds($ssub->expected_date_offset))->strftime('%F');
579 my $issuance = $issuances[$i];
580 #$issuance->label(interval_to_seconds($ssub->expected_date_offset));
581 foreach my $sdist (@$sdists) {
582 my $streams = $sdist->streams;
583 foreach my $stream (@$streams) {
584 my $item = new Fieldmapper::serial::item;
586 $item->stream($stream->id);
587 $item->date_expected($date_expected);
588 $item->issuance($issuance->id);
589 push (@items, $item);
593 fleshed_item_alter($self, $conn, $authtoken, \@items); # FIXME: catch events
598 # _generate_issuance_values() is an initial attempt at a function which can be used
599 # to populate an issuance table with a list of predicted issues. It accepts
600 # a hash ref of options initially defined as:
601 # caption : the caption field to predict on
602 # num_to_predict : the number of issues you wish to predict
603 # last_rec_date : the date of the last received issue, to be used as an offset
604 # for predicting future issues
606 # The basic method is to first convert to a single holding if compressed, then
607 # increment the holding and save the resulting values to @issuances.
609 # returns @issuance_values, an array of hashrefs containing (formatted
610 # label, formatted chronology date, formatted estimated arrival date, and an
611 # array ref of holding subfields as (key, value, key, value ...)) (not a hash
612 # to protect order and possible duplicate keys), and a holding type.
614 sub _generate_issuance_values {
615 my ($mfhd, $options) = @_;
616 my $caption = $options->{caption};
617 my $scap_id = $options->{scap_id};
618 my $num_to_predict = $options->{num_to_predict};
619 my $predict_from = $options->{predict_from}; # issuance to predict from
620 #my $last_rec_date = $options->{last_rec_date}; # expected or actual
622 # TODO: add support for predicting serials with no chronology by passing in
623 # a last_pub_date option?
626 # Only needed for 'real' MFHD records, not our temp records
627 # my $link_id = $caption->link_id;
628 # if(!$predict_from) {
629 # my $htag = $caption->tag;
630 # $htag =~ s/^85/86/;
631 # my @holdings = $mfhd->holdings($htag, $link_id);
632 # my $last_holding = $holdings[-1];
634 # #if ($last_holding->is_compressed) {
635 # # $last_holding->compressed_to_last; # convert to last in range
637 # $predict_from = $last_holding;
641 $predict_from->notes('public', []);
642 # add a note marker for system use (?)
643 $predict_from->notes('private', ['AUTOGEN']);
645 my $strp = new DateTime::Format::Strptime(pattern => '%F');
648 my @predictions = $mfhd->generate_predictions({'base_holding' => $predict_from, 'num_to_predict' => $num_to_predict});
649 foreach my $prediction (@predictions) {
650 $pub_date = $strp->parse_datetime($prediction->chron_to_date);
655 label => $prediction->format,
656 date_published => $pub_date,
657 #date_expected => $date_expected->strftime('%F'),
658 holding_code => [$prediction->indicator(1),$prediction->indicator(2),$prediction->subfields_list],
659 holding_type => $MFHD_NAMES_BY_TAG{$caption->tag},
660 caption_and_pattern => $scap_id
665 return @issuance_values;
668 sub _revive_caption {
671 my $pattern_code = $scap->pattern_code;
674 my $pattern_parts = OpenSRF::Utils::JSON->JSON2perl($pattern_code);
675 unshift(@$pattern_parts, $MFHD_TAGS_BY_NAME{$scap->type});
676 my $pattern_field = new MARC::Field(@$pattern_parts);
678 # build MFHD::Caption
679 return new MFHD::Caption($pattern_field);
682 sub _revive_holding {
683 my $holding_code = shift;
684 my $caption_field = shift;
688 my $holding_parts = OpenSRF::Utils::JSON->JSON2perl($holding_code);
689 my $captag = $caption_field->tag;
690 $captag =~ s/^85/86/;
691 unshift(@$holding_parts, $captag);
692 my $holding_field = new MARC::Field(@$holding_parts);
694 # build MFHD::Holding
695 return new MFHD::Holding($seqno, $holding_field, $caption_field);
698 __PACKAGE__->register_method(
699 method => 'unitize_items',
700 api_name => 'open-ils.serial.receive_items',
704 desc => 'Marks an item as received, updates the shelving unit (creating a new shelving unit if needed), and updates the summaries',
707 desc => 'array of serial items',
712 desc => 'Returns number of received items',
719 my ($self, $conn, $auth, $items) = @_;
721 my( $reqr, $evt ) = $U->checkses($auth);
723 my $editor = new_editor(requestor => $reqr, xact => 1);
724 $self->api_name =~ /serial\.(\w*)_items/;
728 my %found_stream_ids;
731 my %stream_ids_by_unit_id;
734 my %sdist_by_unit_id;
735 my %sdist_by_stream_id;
737 my $new_unit_id; # id for '-2' units to share
738 foreach my $item (@$items) {
739 # for debugging only, TODO: delete
740 if (!ref $item) { # hopefully we got an id instead
741 $item = $editor->retrieve_serial_item($item);
744 my $unit_id = ref($item->unit) ? $item->unit->id : $item->unit;
745 my $stream_id = ref($item->stream) ? $item->stream->id : $item->stream;
746 my $issuance_id = ref($item->issuance) ? $item->issuance->id : $item->issuance;
747 #TODO: evt on any missing ids
749 if ($mode eq 'receive') {
750 $item->date_received('now');
751 $item->status('Received');
753 $item->status('Bindery');
756 # check for types to trigger summary updates
758 if (!ref $item->issuance) {
759 my $scaps = $editor->search_serial_caption_and_pattern([{"+siss" => {"id" => $issuance_id}}, { "join" => {"siss" => {}} }]);
761 } elsif (!ref $item->issuance->caption_and_pattern) {
762 $scap = $editor->retrieve_serial_caption_and_pattern($item->issuance->caption_and_pattern);
764 $scap = $editor->issuance->caption_and_pattern;
766 if (!exists($found_types{$stream_id})) {
767 $found_types{$stream_id} = {};
769 $found_types{$stream_id}->{$scap->type} = 1;
771 # create unit if needed
772 if ($unit_id == -1 or (!$new_unit_id and $unit_id == -2)) { # create unit per item
774 my $sdists = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
775 $unit = _build_unit($editor, $sdists->[0], $mode);
776 my $evt = _create_sunit($editor, $unit);
778 if ($unit_id == -2) {
779 $new_unit_id = $unit->id;
780 $unit_id = $new_unit_id;
782 $unit_id = $unit->id;
784 $item->unit($unit_id);
786 # get unit with 'DEFAULT's and save unit and sdist for later use
787 $unit = $editor->retrieve_serial_unit($unit->id);
788 $unit_map{$unit_id} = $unit;
789 $sdist_by_unit_id{$unit_id} = $sdists->[0];
790 $sdist_by_stream_id{$stream_id} = $sdists->[0];
791 } elsif ($unit_id == -2) { # create one unit for all '-2' items
792 $unit_id = $new_unit_id;
793 $item->unit($unit_id);
796 $found_unit_ids{$unit_id} = 1;
797 $found_stream_ids{$stream_id} = 1;
799 # save the stream_id for this unit_id
800 # TODO: prevent items from different streams in same unit? (perhaps in interface)
801 $stream_ids_by_unit_id{$unit_id} = $stream_id;
803 my $evt = _update_sitem($editor, undef, $item);
807 # deal with unit level labels
808 foreach my $unit_id (keys %found_unit_ids) {
810 # get all the needed issuances for unit
811 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"unit" => $unit_id, "status" => "Received"}}, {"join" => {"sitem" => {}}, "order_by" => {"siss" => "date_published"}} ]);
812 #TODO: evt on search failure
814 my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
816 # special case for single formatted_part (may have summarized version)
817 if (@$formatted_parts == 1) {
818 #TODO: MFHD.pm should have a 'format_summary' method for this
821 # retrieve and update unit contents
825 # if we just created the unit, we will already have it and the distribution stored
826 if (exists $unit_map{$unit_id}) {
827 $sunit = $unit_map{$unit_id};
828 $sdist = $sdist_by_unit_id{$unit_id};
830 $sunit = $editor->retrieve_serial_unit($unit_id);
831 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_ids_by_unit_id{$unit_id}}}, { "join" => {"sstr" => {}} }]);
832 $sdist = $sdist->[0];
835 $sunit->detailed_contents($sdist->unit_label_prefix . ' '
836 . join(', ', @$formatted_parts) . ' '
837 . $sdist->unit_label_suffix);
839 $sunit->summary_contents($sunit->detailed_contents); #TODO: change this when real summary contents are available
841 # create sort_key by left padding numbers to 6 digits
842 my $sort_key = $sunit->detailed_contents;
843 $sort_key =~ s/(\d+)/sprintf '%06d', $1/eg; # this may need improvement
844 $sunit->sort_key($sort_key);
846 if ($mode eq 'bind') {
847 $sunit->status(2); # set to 'Bindery' status
850 my $evt = _update_sunit($editor, undef, $sunit);
854 # TODO: cleanup 'dead' units (units which are now emptied of their items)
856 if ($mode eq 'receive') { # the summary holdings do not change when binding
857 # deal with stream level summaries
858 # summaries will be built from the "primary" stream only, that is, the stream with the lowest ID per distribution
859 # (TODO: consider direct designation)
860 my %primary_streams_by_sdist;
861 my %streams_by_sdist;
863 # see if we have primary streams, and if so, associate them with their distributions
864 foreach my $stream_id (keys %found_stream_ids) {
866 if (exists $sdist_by_stream_id{$stream_id}) {
867 $sdist = $sdist_by_stream_id{$stream_id};
869 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
870 $sdist = $sdist->[0];
873 if (!exists($streams_by_sdist{$sdist->id})) {
874 $streams = $editor->search_serial_stream([{"distribution" => $sdist->id}, {"order_by" => {"sstr" => "id"}}]);
875 $streams_by_sdist{$sdist->id} = $streams;
877 $streams = $streams_by_sdist{$sdist->id};
879 $primary_streams_by_sdist{$sdist->id} = $streams->[0] if ($stream_id == $streams->[0]->id);
882 # retrieve and update summaries for each affected primary stream's distribution
883 foreach my $sdist_id (keys %primary_streams_by_sdist) {
884 my $stream = $primary_streams_by_sdist{$sdist_id};
885 my $stream_id = $stream->id;
886 # get all the needed issuances for stream
887 # FIXME: search in Bindery/Bound/Not Published? as well as Received
888 foreach my $type (keys %{$found_types{$stream_id}}) {
889 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"stream" => $stream_id, "status" => "Received"}, "+scap" => {"type" => $type}}, {"join" => {"sitem" => {}, "scap" => {}}, "order_by" => {"siss" => "date_published"}} ]);
890 #TODO: evt on search failure
892 my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
894 # retrieve and update the generated_coverage of the summary
895 my $search_method = "search_serial_${type}_summary";
896 my $summary = $editor->$search_method([{"distribution" => $sdist_id}]);
897 $summary = $summary->[0];
898 $summary->generated_coverage(join(', ', @$formatted_parts));
899 my $update_method = "update_serial_${type}_summary";
900 return $editor->event unless $editor->$update_method($summary);
906 return {'num_items_received' => scalar @$items, 'new_unit_id' => $new_unit_id};
909 sub _find_or_create_call_number {
910 my ($e, $lib, $cn_string, $record) = @_;
912 my $existing = $e->search_asset_call_number({
913 "owning_lib" => $lib,
914 "label" => $cn_string,
917 }) or return $e->die_event;
920 return $existing->[0]->id;
922 return $e->die_event unless
923 $e->allowed("CREATE_VOLUME", $lib);
925 my $acn = new Fieldmapper::asset::call_number;
927 $acn->creator($e->requestor->id);
928 $acn->editor($e->requestor->id);
929 $acn->record($record);
930 $acn->label($cn_string);
931 $acn->owning_lib($lib);
933 $e->create_asset_call_number($acn) or return $e->die_event;
938 sub _issuances_received {
939 my ($e, $sitem) = @_;
941 my $results = $e->json_query({
944 {"transform" => "distinct", "column" => "issuance"}
947 "from" => {"sitem" => {"sstr" => {}, "siss" => {}}},
949 "+sstr" => {"distribution" => $sitem->stream->distribution->id},
950 "+siss" => {"holding_type" => $sitem->issuance->holding_type},
951 "+sitem" => {"date_received" => {"!=" => undef}}
953 }) or return $e->die_event;
955 return [ map { $e->retrieve_serial_issuance($_->{"issuance"}) } @$results ];
958 # XXX _prepare_unit_label() duplicates some code from unitize_items().
959 # Hopefully we can unify code paths down the road.
960 sub _prepare_unit_label {
961 my ($e, $sunit, $sdist, $issuance) = @_;
963 my ($mfhd, $formatted_parts) = _summarize_contents($e, [$issuance]);
965 # special case for single formatted_part (may have summarized version)
966 if (@$formatted_parts == 1) {
967 #TODO: MFHD.pm should have a 'format_summary' method for this
970 $sunit->detailed_contents(
973 $sdist->unit_label_prefix,
974 join(", ", @$formatted_parts),
975 $sdist->unit_label_suffix
979 # TODO: change this when real summary contents are available
980 $sunit->summary_contents($sunit->detailed_contents);
982 # Create sort_key by left padding numbers to 6 digits.
983 (my $sort_key = $sunit->detailed_contents) =~
984 s/(\d+)/sprintf '%06d', $1/eg;
985 $sunit->sort_key($sort_key);
988 # XXX duplicates a block of code from unitize_items(). Once I fully understand
989 # what's going on and I'm sure it's working right, I'd like to have
990 # unitize_items() just use this, keeping the logic in one place.
991 sub _prepare_summaries {
992 my ($e, $sitem, $issuances) = @_;
994 my $dist_id = $sitem->stream->distribution->id;
995 my $type = $sitem->issuance->holding_type;
997 # Make sure @$issuances contains the new issuance from sitem.
998 unless (grep { $_->id == $sitem->issuance->id } @$issuances) {
999 push @$issuances, $sitem->issuance;
1002 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances);
1004 my $search_method = "search_serial_${type}_summary";
1005 my $summary = $e->$search_method([{"distribution" => $dist_id}]);
1007 my $cu_method = "update";
1010 $summary = $summary->[0];
1012 my $class = "Fieldmapper::serial::${type}_summary";
1013 $summary = $class->new;
1014 $summary->distribution($dist_id);
1015 $cu_method = "create";
1018 $summary->generated_coverage(join(", ", @$formatted_parts));
1019 my $method = "${cu_method}_serial_${type}_summary";
1020 return $e->die_event unless $e->$method($summary);
1023 __PACKAGE__->register_method(
1024 "method" => "receive_items_one_unit_per",
1025 "api_name" => "open-ils.serial.receive_items.one_unit_per",
1030 "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",
1034 "desc" => "authtoken",
1039 "desc" => "array of serial items, possibly fleshed with units and definitely fleshed with stream->distribution",
1044 "desc" => "id of bib record these items are associated with
1045 (XXX could/should be derived from items)",
1050 "desc" => "The item ID for each item successfully received",
1056 sub receive_items_one_unit_per {
1057 # XXX This function may be temporary, as it does some of what
1058 # unitize_items() does, just in a different way.
1059 my ($self, $client, $auth, $items, $record) = @_;
1061 my $e = new_editor("authtoken" => $auth, "xact" => 1);
1062 return $e->die_event unless $e->checkauth;
1064 my $user_id = $e->requestor->id;
1066 # Get a list of all the non-virtual field names in a serial::unit for
1067 # merging given unit objects with template-built units later.
1068 # XXX move this somewhere global so it isn't re-run all the time
1069 my $all_unit_fields =
1070 $Fieldmapper::fieldmap->{"Fieldmapper::serial::unit"}->{"fields"};
1071 my @real_unit_fields = grep {
1072 not $all_unit_fields->{$_}->{"virtual"}
1073 } keys %$all_unit_fields;
1075 foreach my $item (@$items) {
1076 # Note that we expect a certain fleshing on the items we're getting.
1077 my $sdist = $item->stream->distribution;
1079 # Create unit if given by user
1080 if (ref $item->unit) {
1081 # detach from the item, as we need to create separately
1082 my $user_unit = $item->unit;
1084 # get a unit based on associated template
1085 my $template_unit = _build_unit($e, $sdist, "receive", 1);
1086 if ($U->event_code($template_unit)) {
1088 $template_unit->{"note"} = "Item ID: " . $item->id;
1089 return $template_unit;
1092 # merge built unit with provided unit from user
1093 foreach (@real_unit_fields) {
1094 unless ($user_unit->$_) {
1095 $user_unit->$_($template_unit->$_);
1099 # Treat call number specially: the provided value from the
1100 # user will really be a string.
1101 if ($user_unit->call_number) {
1102 my $real_cn = _find_or_create_call_number(
1103 $e, $sdist->holding_lib->id,
1104 $user_unit->call_number, $record
1107 if ($U->event_code($real_cn)) {
1111 $user_unit->call_number($real_cn);
1115 my $evt = _prepare_unit_label(
1116 $e, $user_unit, $sdist, $item->issuance
1118 if ($U->event_code($evt)) {
1123 # fetch a list of issuances with received copies already existing
1124 # on this distribution.
1125 my $issuances = _issuances_received($e, $item); #XXX optimize later
1126 if ($U->event_code($issuances)) {
1131 # create/update summary objects related to this distribution
1132 $evt = _prepare_summaries($e, $item, $issuances);
1133 if ($U->event_code($evt)) {
1138 # set the incontrovertibles on the unit
1139 $user_unit->edit_date("now");
1140 $user_unit->create_date("now");
1141 $user_unit->editor($user_id);
1142 $user_unit->creator($user_id);
1144 return $e->die_event unless $e->create_serial_unit($user_unit);
1146 # save reference to new unit
1147 $item->unit($e->data->id);
1150 # Create notes if given by user
1151 if (ref($item->notes) and @{$item->notes}) {
1152 foreach my $note (@{$item->notes}) {
1153 $note->creator($user_id);
1154 $note->create_date("now");
1156 return $e->die_event unless $e->create_serial_item_note($note);
1159 $item->clear_notes; # They're saved; we no longer want them here.
1162 # Set the incontrovertibles on the item
1163 $item->status("Received");
1164 $item->date_received("now");
1165 $item->edit_date("now");
1166 $item->editor($user_id);
1168 return $e->die_event unless $e->update_serial_item($item);
1170 # send client a response
1171 $client->respond($item->id);
1174 $e->commit or return $e->die_event;
1182 my $skip_call_number = shift;
1184 my $attr = $mode . '_unit_template';
1185 my $template = $editor->retrieve_asset_copy_template($sdist->$attr) or
1186 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_COPY_TEMPLATE");
1188 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 );
1190 my $unit = new Fieldmapper::serial::unit;
1191 foreach my $part (@parts) {
1192 my $value = $template->$part;
1193 next if !defined($value);
1194 $unit->$part($value);
1197 # ignore circ_lib in template, set to distribution holding_lib
1198 $unit->circ_lib($sdist->holding_lib);
1199 $unit->creator($editor->requestor->id);
1200 $unit->editor($editor->requestor->id);
1202 unless ($skip_call_number) {
1203 $attr = $mode . '_call_number';
1204 my $cn = $sdist->$attr or
1205 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_CALL_NUMBER");
1207 $unit->call_number($cn);
1210 $unit->barcode('AUTO');
1211 $unit->sort_key('');
1212 $unit->summary_contents('');
1213 $unit->detailed_contents('');
1219 sub _summarize_contents {
1221 my $issuances = shift;
1223 # create MFHD record
1224 my $mfhd = MFHD->new(MARC::Record->new());
1227 my @scap_fields_ordered;
1230 foreach my $issuance (@$issuances) {
1231 my $scap_id = $issuance->caption_and_pattern;
1232 next if (!$scap_id); # skip issuances with no caption/pattern
1236 # if this is the first appearance of this scap, retrieve it and add it to the temporary record
1237 if (!exists $scaps{$issuance->caption_and_pattern}) {
1238 $scaps{$scap_id} = $editor->retrieve_serial_caption_and_pattern($scap_id);
1239 $scap = $scaps{$scap_id};
1240 $scap_field = _revive_caption($scap);
1241 $scap_fields{$scap_id} = $scap_field;
1242 push(@scap_fields_ordered, $scap_field);
1243 $scap_field->update('8' => $link_id);
1244 $mfhd->append_fields($scap_field);
1247 $scap = $scaps{$scap_id};
1248 $scap_field = $scap_fields{$scap_id};
1251 $mfhd->append_fields(_revive_holding($issuance->holding_code, $scap_field, $seqno));
1255 my @formatted_parts;
1256 foreach my $scap_field (@scap_fields_ordered) { #TODO: use generic MFHD "summarize" method, once available
1257 my @updated_holdings = $mfhd->get_compressed_holdings($scap_field);
1258 foreach my $holding (@updated_holdings) {
1259 push(@formatted_parts, $holding->format);
1263 return ($mfhd, \@formatted_parts);
1266 ##########################################################################
1269 __PACKAGE__->register_method(
1270 method => 'fetch_notes',
1271 api_name => 'open-ils.serial.item_note.retrieve.all',
1273 Returns an array of copy note objects.
1274 @param args A named hash of parameters including:
1275 authtoken : Required if viewing non-public notes
1276 item_id : The id of the item whose notes we want to retrieve
1277 pub : True if all the caller wants are public notes
1278 @return An array of note objects
1282 __PACKAGE__->register_method(
1283 method => 'fetch_notes',
1284 api_name => 'open-ils.serial.subscription_note.retrieve.all',
1286 Returns an array of copy note objects.
1287 @param args A named hash of parameters including:
1288 authtoken : Required if viewing non-public notes
1289 subscription_id : The id of the item whose notes we want to retrieve
1290 pub : True if all the caller wants are public notes
1291 @return An array of note objects
1295 __PACKAGE__->register_method(
1296 method => 'fetch_notes',
1297 api_name => 'open-ils.serial.distribution_note.retrieve.all',
1299 Returns an array of copy note objects.
1300 @param args A named hash of parameters including:
1301 authtoken : Required if viewing non-public notes
1302 distribution_id : The id of the item whose notes we want to retrieve
1303 pub : True if all the caller wants are public notes
1304 @return An array of note objects
1308 # TODO: revisit this method to consider replacing cstore direct calls
1310 my( $self, $connection, $args ) = @_;
1312 $self->api_name =~ /serial\.(\w*)_note/;
1315 my $id = $$args{object_id};
1316 my $authtoken = $$args{authtoken};
1320 return $U->cstorereq(
1321 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic',
1322 { $type => $id, pub => 't' } );
1324 # FIXME: restore perm check
1325 # ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
1326 # return $evt if $evt;
1327 return $U->cstorereq(
1328 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic', {$type => $id} );
1334 __PACKAGE__->register_method(
1335 method => 'create_note',
1336 api_name => 'open-ils.serial.item_note.create',
1338 Creates a new item note
1339 @param authtoken The login session key
1340 @param note The note object to create
1341 @return The id of the new note object
1345 __PACKAGE__->register_method(
1346 method => 'create_note',
1347 api_name => 'open-ils.serial.subscription_note.create',
1349 Creates a new subscription note
1350 @param authtoken The login session key
1351 @param note The note object to create
1352 @return The id of the new note object
1356 __PACKAGE__->register_method(
1357 method => 'create_note',
1358 api_name => 'open-ils.serial.distribution_note.create',
1360 Creates a new distribution note
1361 @param authtoken The login session key
1362 @param note The note object to create
1363 @return The id of the new note object
1368 my( $self, $connection, $authtoken, $note ) = @_;
1370 $self->api_name =~ /serial\.(\w*)_note/;
1373 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1374 return $e->event unless $e->checkauth;
1376 # FIXME: restore permission support
1377 # my $item = $e->retrieve_serial_item(
1383 # return $e->event unless
1384 # $e->allowed('CREATE_COPY_NOTE', $item->call_number->owning_lib);
1386 $note->create_date('now');
1387 $note->creator($e->requestor->id);
1388 $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
1391 my $method = "create_serial_${type}_note";
1392 $e->$method($note) or return $e->event;
1397 __PACKAGE__->register_method(
1398 method => 'delete_note',
1399 api_name => 'open-ils.serial.item_note.delete',
1401 Deletes an existing item note
1402 @param authtoken The login session key
1403 @param noteid The id of the note to delete
1404 @return 1 on success - Event otherwise.
1408 __PACKAGE__->register_method(
1409 method => 'delete_note',
1410 api_name => 'open-ils.serial.subscription_note.delete',
1412 Deletes an existing subscription note
1413 @param authtoken The login session key
1414 @param noteid The id of the note to delete
1415 @return 1 on success - Event otherwise.
1419 __PACKAGE__->register_method(
1420 method => 'delete_note',
1421 api_name => 'open-ils.serial.distribution_note.delete',
1423 Deletes an existing distribution note
1424 @param authtoken The login session key
1425 @param noteid The id of the note to delete
1426 @return 1 on success - Event otherwise.
1431 my( $self, $conn, $authtoken, $noteid ) = @_;
1433 $self->api_name =~ /serial\.(\w*)_note/;
1436 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1437 return $e->die_event unless $e->checkauth;
1439 my $method = "retrieve_serial_${type}_note";
1440 my $note = $e->$method([
1442 ]) or return $e->die_event;
1444 # FIXME: restore permissions check
1445 # if( $note->creator ne $e->requestor->id ) {
1446 # return $e->die_event unless
1447 # $e->allowed('DELETE_COPY_NOTE', $note->item->call_number->owning_lib);
1450 $method = "delete_serial_${type}_note";
1451 $e->$method($note) or return $e->die_event;
1457 ##########################################################################
1458 # subscription methods
1460 __PACKAGE__->register_method(
1461 method => 'fleshed_ssub_alter',
1462 api_name => 'open-ils.serial.subscription.fleshed.batch.update',
1466 desc => 'Receives an array of one or more subscriptions and updates the database as needed',
1468 name => 'authtoken',
1469 desc => 'Authtoken for current user session',
1473 name => 'subscriptions',
1474 desc => 'Array of fleshed subscriptions',
1480 desc => 'Returns 1 if successful, event if failed',
1486 sub fleshed_ssub_alter {
1487 my( $self, $conn, $auth, $ssubs ) = @_;
1488 return 1 unless ref $ssubs;
1489 my( $reqr, $evt ) = $U->checkses($auth);
1490 return $evt if $evt;
1491 my $editor = new_editor(requestor => $reqr, xact => 1);
1492 my $override = $self->api_name =~ /override/;
1494 # TODO: permission check
1495 # return $editor->event unless
1496 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
1498 for my $ssub (@$ssubs) {
1500 my $ssubid = $ssub->id;
1502 if( $ssub->isdeleted ) {
1503 $evt = _delete_ssub( $editor, $override, $ssub);
1504 } elsif( $ssub->isnew ) {
1505 _cleanse_dates($ssub, ['start_date','end_date']);
1506 $evt = _create_ssub( $editor, $ssub );
1508 _cleanse_dates($ssub, ['start_date','end_date']);
1509 $evt = _update_ssub( $editor, $override, $ssub );
1514 $logger->info("fleshed subscription-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
1518 $logger->debug("subscription-alter: done updating subscription batch");
1520 $logger->info("fleshed subscription-alter successfully updated ".scalar(@$ssubs)." subscriptions");
1525 my ($editor, $override, $ssub) = @_;
1526 $logger->info("subscription-alter: delete subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1527 my $sdists = $editor->search_serial_distribution(
1528 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1529 my $cps = $editor->search_serial_caption_and_pattern(
1530 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1531 my $sisses = $editor->search_serial_issuance(
1532 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1533 return OpenILS::Event->new(
1534 'SERIAL_SUBSCRIPTION_NOT_EMPTY', payload => $ssub->id ) if (@$sdists or @$cps or @$sisses);
1536 return $editor->event unless $editor->delete_serial_subscription($ssub);
1541 my ($editor, $ssub) = @_;
1543 $logger->info("subscription-alter: new subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1544 return $editor->event unless $editor->create_serial_subscription($ssub);
1549 my ($editor, $override, $ssub) = @_;
1551 $logger->info("subscription-alter: retrieving subscription ".$ssub->id);
1552 my $orig_ssub = $editor->retrieve_serial_subscription($ssub->id);
1554 $logger->info("subscription-alter: original subscription ".OpenSRF::Utils::JSON->perl2JSON($orig_ssub));
1555 $logger->info("subscription-alter: updated subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1556 return $editor->event unless $editor->update_serial_subscription($ssub);
1560 __PACKAGE__->register_method(
1561 method => "fleshed_serial_subscription_retrieve_batch",
1563 api_name => "open-ils.serial.subscription.fleshed.batch.retrieve"
1566 sub fleshed_serial_subscription_retrieve_batch {
1567 my( $self, $client, $ids ) = @_;
1568 # FIXME: permissions?
1569 $logger->info("Fetching fleshed subscriptions @$ids");
1570 return $U->cstorereq(
1571 "open-ils.cstore.direct.serial.subscription.search.atomic",
1574 flesh_fields => {ssub => [ qw/owning_lib notes/ ]}
1578 __PACKAGE__->register_method(
1579 method => "retrieve_sub_tree",
1581 api_name => "open-ils.serial.subscription_tree.retrieve"
1584 __PACKAGE__->register_method(
1585 method => "retrieve_sub_tree",
1586 api_name => "open-ils.serial.subscription_tree.global.retrieve"
1589 sub retrieve_sub_tree {
1591 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
1593 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
1597 # TODO: permission support
1598 if(!@org_ids and $user_session) {
1600 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
1601 @org_ids = ($user_obj->home_ou);
1604 if( $self->api_name =~ /global/ ) {
1605 return _build_subs_list( { record_entry => $docid } ); # TODO: filter for !deleted, or active?
1610 for my $orgid (@org_ids) {
1611 my $subs = _build_subs_list(
1612 { record_entry => $docid, owning_lib => $orgid } );# TODO: filter for !deleted, or active?
1613 push( @all_subs, @$subs );
1622 sub _build_subs_list {
1623 my $search_hash = shift;
1625 #$search_hash->{deleted} = 'f';
1626 my $e = new_editor();
1628 my $subs = $e->search_serial_subscription([$search_hash, { 'order_by' => {'ssub' => 'id'} }]);
1632 for my $sub (@$subs) {
1634 # TODO: filter on !deleted?
1635 my $dists = $e->search_serial_distribution(
1636 [{ subscription => $sub->id }, { 'order_by' => {'sdist' => 'label'} }]
1639 #$dists = [ sort { $a->label cmp $b->label } @$dists ];
1641 $sub->distributions($dists);
1643 # TODO: filter on !deleted?
1644 my $issuances = $e->search_serial_issuance(
1645 [{ subscription => $sub->id }, { 'order_by' => {'siss' => 'label'} }]
1648 #$issuances = [ sort { $a->label cmp $b->label } @$issuances ];
1649 $sub->issuances($issuances);
1651 # TODO: filter on !deleted?
1652 my $scaps = $e->search_serial_caption_and_pattern(
1653 [{ subscription => $sub->id }, { 'order_by' => {'scap' => 'id'} }]
1656 #$scaps = [ sort { $a->id cmp $b->id } @$scaps ];
1657 $sub->scaps($scaps);
1658 push( @built_subs, $sub );
1661 return \@built_subs;
1665 __PACKAGE__->register_method(
1666 method => "subscription_orgs_for_title",
1668 api_name => "open-ils.serial.subscription.retrieve_orgs_by_title"
1671 sub subscription_orgs_for_title {
1672 my( $self, $client, $record_id ) = @_;
1674 my $subs = $U->simple_scalar_request(
1676 "open-ils.cstore.direct.serial.subscription.search.atomic",
1677 { record_entry => $record_id }); # TODO: filter on !deleted?
1679 my $orgs = { map {$_->owning_lib => 1 } @$subs };
1680 return [ keys %$orgs ];
1684 ##########################################################################
1685 # distribution methods
1687 __PACKAGE__->register_method(
1688 method => 'fleshed_sdist_alter',
1689 api_name => 'open-ils.serial.distribution.fleshed.batch.update',
1693 desc => 'Receives an array of one or more distributions and updates the database as needed',
1695 name => 'authtoken',
1696 desc => 'Authtoken for current user session',
1700 name => 'distributions',
1701 desc => 'Array of fleshed distributions',
1707 desc => 'Returns 1 if successful, event if failed',
1713 sub fleshed_sdist_alter {
1714 my( $self, $conn, $auth, $sdists ) = @_;
1715 return 1 unless ref $sdists;
1716 my( $reqr, $evt ) = $U->checkses($auth);
1717 return $evt if $evt;
1718 my $editor = new_editor(requestor => $reqr, xact => 1);
1719 my $override = $self->api_name =~ /override/;
1721 # TODO: permission check
1722 # return $editor->event unless
1723 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
1725 for my $sdist (@$sdists) {
1726 my $sdistid = $sdist->id;
1728 if( $sdist->isdeleted ) {
1729 $evt = _delete_sdist( $editor, $override, $sdist);
1730 } elsif( $sdist->isnew ) {
1731 $evt = _create_sdist( $editor, $sdist );
1733 $evt = _update_sdist( $editor, $override, $sdist );
1738 $logger->info("fleshed distribution-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
1742 $logger->debug("distribution-alter: done updating distribution batch");
1744 $logger->info("fleshed distribution-alter successfully updated ".scalar(@$sdists)." distributions");
1749 my ($editor, $override, $sdist) = @_;
1750 $logger->info("distribution-alter: delete distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
1751 return $editor->event unless $editor->delete_serial_distribution($sdist);
1756 my ($editor, $sdist) = @_;
1758 $logger->info("distribution-alter: new distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
1759 return $editor->event unless $editor->create_serial_distribution($sdist);
1761 # create summaries too
1762 my $summary = new Fieldmapper::serial::basic_summary;
1763 $summary->distribution($sdist->id);
1764 $summary->generated_coverage('');
1765 return $editor->event unless $editor->create_serial_basic_summary($summary);
1766 $summary = new Fieldmapper::serial::supplement_summary;
1767 $summary->distribution($sdist->id);
1768 $summary->generated_coverage('');
1769 return $editor->event unless $editor->create_serial_supplement_summary($summary);
1770 $summary = new Fieldmapper::serial::index_summary;
1771 $summary->distribution($sdist->id);
1772 $summary->generated_coverage('');
1773 return $editor->event unless $editor->create_serial_index_summary($summary);
1775 # create a starter stream (TODO: reconsider this)
1776 my $stream = new Fieldmapper::serial::stream;
1777 $stream->distribution($sdist->id);
1778 return $editor->event unless $editor->create_serial_stream($stream);
1784 my ($editor, $override, $sdist) = @_;
1786 $logger->info("distribution-alter: retrieving distribution ".$sdist->id);
1787 my $orig_sdist = $editor->retrieve_serial_distribution($sdist->id);
1789 $logger->info("distribution-alter: original distribution ".OpenSRF::Utils::JSON->perl2JSON($orig_sdist));
1790 $logger->info("distribution-alter: updated distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
1791 return $editor->event unless $editor->update_serial_distribution($sdist);
1795 __PACKAGE__->register_method(
1796 method => "fleshed_serial_distribution_retrieve_batch",
1798 api_name => "open-ils.serial.distribution.fleshed.batch.retrieve"
1801 sub fleshed_serial_distribution_retrieve_batch {
1802 my( $self, $client, $ids ) = @_;
1803 # FIXME: permissions?
1804 $logger->info("Fetching fleshed distributions @$ids");
1805 return $U->cstorereq(
1806 "open-ils.cstore.direct.serial.distribution.search.atomic",
1809 flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams / ]}
1813 ##########################################################################
1814 # caption and pattern methods
1816 __PACKAGE__->register_method(
1817 method => 'scap_alter',
1818 api_name => 'open-ils.serial.caption_and_pattern.batch.update',
1822 desc => 'Receives an array of one or more caption and patterns and updates the database as needed',
1824 name => 'authtoken',
1825 desc => 'Authtoken for current user session',
1830 desc => 'Array of caption and patterns',
1836 desc => 'Returns 1 if successful, event if failed',
1843 my( $self, $conn, $auth, $scaps ) = @_;
1844 return 1 unless ref $scaps;
1845 my( $reqr, $evt ) = $U->checkses($auth);
1846 return $evt if $evt;
1847 my $editor = new_editor(requestor => $reqr, xact => 1);
1848 my $override = $self->api_name =~ /override/;
1850 # TODO: permission check
1851 # return $editor->event unless
1852 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
1854 for my $scap (@$scaps) {
1855 my $scapid = $scap->id;
1857 if( $scap->isdeleted ) {
1858 $evt = _delete_scap( $editor, $override, $scap);
1859 } elsif( $scap->isnew ) {
1860 $evt = _create_scap( $editor, $scap );
1862 $evt = _update_scap( $editor, $override, $scap );
1867 $logger->info("caption_and_pattern-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
1871 $logger->debug("caption_and_pattern-alter: done updating caption_and_pattern batch");
1873 $logger->info("caption_and_pattern-alter successfully updated ".scalar(@$scaps)." caption_and_patterns");
1878 my ($editor, $override, $scap) = @_;
1879 $logger->info("caption_and_pattern-alter: delete caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
1880 my $sisses = $editor->search_serial_issuance(
1881 { caption_and_pattern => $scap->id }, { limit => 1 } ); #TODO: 'deleted' support?
1882 return OpenILS::Event->new(
1883 'SERIAL_CAPTION_AND_PATTERN_HAS_ISSUANCES', payload => $scap->id ) if (@$sisses);
1885 return $editor->event unless $editor->delete_serial_caption_and_pattern($scap);
1890 my ($editor, $scap) = @_;
1892 $logger->info("caption_and_pattern-alter: new caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
1893 return $editor->event unless $editor->create_serial_caption_and_pattern($scap);
1898 my ($editor, $override, $scap) = @_;
1900 $logger->info("caption_and_pattern-alter: retrieving caption_and_pattern ".$scap->id);
1901 my $orig_scap = $editor->retrieve_serial_caption_and_pattern($scap->id);
1903 $logger->info("caption_and_pattern-alter: original caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($orig_scap));
1904 $logger->info("caption_and_pattern-alter: updated caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
1905 return $editor->event unless $editor->update_serial_caption_and_pattern($scap);
1909 __PACKAGE__->register_method(
1910 method => "serial_caption_and_pattern_retrieve_batch",
1912 api_name => "open-ils.serial.caption_and_pattern.batch.retrieve"
1915 sub serial_caption_and_pattern_retrieve_batch {
1916 my( $self, $client, $ids ) = @_;
1917 $logger->info("Fetching caption_and_patterns @$ids");
1918 return $U->cstorereq(
1919 "open-ils.cstore.direct.serial.caption_and_pattern.search.atomic",
1924 __PACKAGE__->register_method(
1925 "method" => "bre_by_identifier",
1926 "api_name" => "open-ils.serial.biblio.record_entry.by_identifier",
1929 "desc" => "Find instances of biblio.record_entry given a search token" .
1930 " that could be a value for any identifier defined in " .
1931 "config.metabib_field",
1933 {"desc" => "Search token", "type" => "string"},
1934 {"desc" => "Options: require_subscriptions, add_mvr, is_actual_id" .
1935 " (all boolean)", "type" => "object"}
1938 "desc" => "Any matching BREs, or if the add_mvr option is true, " .
1939 "objects with a 'bre' key/value pair, and an 'mvr' " .
1940 "key-value pair. BREs have subscriptions fleshed on.",
1946 sub bre_by_identifier {
1947 my ($self, $client, $term, $options) = @_;
1949 return new OpenILS::Event("BAD_PARAMS") unless $term;
1952 my $e = new_editor();
1956 if ($options->{"is_actual_id"}) {
1960 $e->search_config_metabib_field({"field_class" => "identifier"})
1961 or return $e->die_event;
1963 my @identifiers = map { $_->name } @$cmf;
1964 my $query = join(" || ", map { "id|$_: $term" } @identifiers);
1966 my $search = create OpenSRF::AppSession("open-ils.search");
1967 my $search_result = $search->request(
1968 "open-ils.search.biblio.multiclass.query.staff", {}, $query
1970 $search->disconnect;
1972 # Un-nest results. They tend to look like [[1],[2],[3]] for some reason.
1973 @ids = map { @{$_} } @{$search_result->{"ids"}};
1981 my $bre = $e->search_biblio_record_entry([
1983 "flesh" => 2, "flesh_fields" => {
1984 "bre" => ["subscriptions"],
1985 "ssub" => ["owning_lib"]
1988 ]) or return $e->die_event;
1990 if (@$bre && $options->{"require_subscriptions"}) {
1991 $bre = [ grep { @{$_->subscriptions} } @$bre ];
1996 if (@$bre) { # re-evaluate after possible grep
1997 if ($options->{"add_mvr"}) {
1999 {"bre" => $_, "mvr" => _get_mvr($_->id)}
2002 $client->respond($_) foreach (@$bre);
2009 __PACKAGE__->register_method(
2010 "method" => "get_receivable_items",
2011 "api_name" => "open-ils.serial.items.receivable.by_subscription",
2014 "desc" => "Return all receivable items under a given subscription",
2016 {"desc" => "Authtoken", "type" => "string"},
2017 {"desc" => "Subscription ID", "type" => "number"},
2020 "desc" => "All receivable items under a given subscription",
2026 __PACKAGE__->register_method(
2027 "method" => "get_receivable_items",
2028 "api_name" => "open-ils.serial.items.receivable.by_issuance",
2031 "desc" => "Return all receivable items under a given issuance",
2033 {"desc" => "Authtoken", "type" => "string"},
2034 {"desc" => "Issuance ID", "type" => "number"},
2037 "desc" => "All receivable items under a given issuance",
2043 sub get_receivable_items {
2044 my ($self, $client, $auth, $term) = @_;
2046 my $e = new_editor("authtoken" => $auth);
2047 return $e->die_event unless $e->checkauth;
2051 my $by = ($self->api_name =~ /by_(\w+)$/)[0];
2054 "issuance" => {"issuance" => $term},
2055 "subscription" => {"+siss" => {"subscription" => $term}}
2058 my $item_ids = $e->json_query(
2060 "select" => {"sitem" => ["id"]},
2061 "from" => {"sitem" => "siss"},
2063 %{$where{$by}}, "date_received" => undef
2065 "order_by" => {"sitem" => ["id"]}
2067 ) or return $e->die_event;
2069 return undef unless @$item_ids;
2071 foreach (map { $_->{"id"} } @$item_ids) {
2073 $e->retrieve_serial_item([
2077 "sitem" => ["stream", "issuance"],
2078 "sstr" => ["distribution"],
2079 "sdist" => ["holding_lib"]
2090 __PACKAGE__->register_method(
2091 "method" => "get_receivable_issuances",
2092 "api_name" => "open-ils.serial.issuances.receivable",
2095 "desc" => "Return all issuances with receivable items given " .
2096 "a subscription ID",
2098 {"desc" => "Authtoken", "type" => "string"},
2099 {"desc" => "Subscription ID", "type" => "number"},
2102 "desc" => "All issuances with receivable items " .
2103 "(but not the items themselves)", "type" => "object"
2108 sub get_receivable_issuances {
2109 my ($self, $client, $auth, $sub_id) = @_;
2111 my $e = new_editor("authtoken" => $auth);
2112 return $e->die_event unless $e->checkauth;
2116 my $issuance_ids = $e->json_query({
2119 {"transform" => "distinct", "column" => "id"},
2123 "from" => {"siss" => "sitem"},
2125 "subscription" => $sub_id,
2126 "+sitem" => {"date_received" => undef}
2129 "siss" => {"date_published" => {"direction" => "asc"}}
2132 }) or return $e->die_event;
2134 $client->respond($e->retrieve_serial_issuance($_->{"id"}))
2135 foreach (@$issuance_ids);