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/ ]}
324 ##########################################################################
327 __PACKAGE__->register_method(
328 method => 'fleshed_sunit_alter',
329 api_name => 'open-ils.serial.sunit.fleshed.batch.update',
333 desc => 'Receives an array of one or more Units and updates the database as needed',
336 desc => 'Authtoken for current user session',
341 desc => 'Array of fleshed Units',
347 desc => 'Returns 1 if successful, event if failed',
353 sub fleshed_sunit_alter {
354 my( $self, $conn, $auth, $sunits ) = @_;
355 return 1 unless ref $sunits;
356 my( $reqr, $evt ) = $U->checkses($auth);
358 my $editor = new_editor(requestor => $reqr, xact => 1);
359 my $override = $self->api_name =~ /override/;
361 # TODO: permission support
362 # return $editor->event unless
363 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
365 for my $sunit (@$sunits) {
366 if( $sunit->isdeleted ) {
367 $evt = _delete_sunit( $editor, $override, $sunit );
369 $sunit->default_location( $sunit->default_location->id ) if ref $sunit->default_location;
371 if( $sunit->isnew ) {
372 $evt = _create_sunit( $editor, $sunit );
374 $evt = _update_sunit( $editor, $override, $sunit );
380 $logger->info("fleshed sunit-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
384 $logger->debug("sunit-alter: done updating sunit batch");
386 $logger->info("fleshed sunit-alter successfully updated ".scalar(@$sunits)." Units");
391 my ($editor, $override, $sunit) = @_;
392 $logger->info("sunit-alter: delete sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
393 return $editor->event unless $editor->delete_serial_unit($sunit);
398 my ($editor, $sunit) = @_;
400 $logger->info("sunit-alter: new Unit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
401 return $editor->event unless $editor->create_serial_unit($sunit);
406 my ($editor, $override, $sunit) = @_;
408 $logger->info("sunit-alter: retrieving sunit ".$sunit->id);
409 my $orig_sunit = $editor->retrieve_serial_unit($sunit->id);
411 $logger->info("sunit-alter: original sunit ".OpenSRF::Utils::JSON->perl2JSON($orig_sunit));
412 $logger->info("sunit-alter: updated sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
413 return $editor->event unless $editor->update_serial_unit($sunit);
417 __PACKAGE__->register_method(
418 method => "retrieve_unit_list",
420 api_name => "open-ils.serial.unit_list.retrieve"
423 sub retrieve_unit_list {
425 my( $self, $client, @sdist_ids ) = @_;
427 if(ref($sdist_ids[0])) { @sdist_ids = @{$sdist_ids[0]}; }
429 my $e = new_editor();
433 { 'sunit' => [ 'id', 'summary_contents', 'sort_key' ],
434 'sitem' => ['stream'],
435 'sstr' => ['distribution'],
436 'sdist' => [{'column' => 'label', 'alias' => 'sdist_label'}]
443 { 'join' => { 'sunit' => {} } }
448 'distinct' => 'true',
449 'where' => { '+sdist' => {'id' => \@sdist_ids} },
450 'order_by' => [{'class' => 'sunit', 'field' => 'sort_key'}]
453 my $unit_list_entries = $e->json_query($query);
456 foreach my $entry (@$unit_list_entries) {
457 my $value = {'sunit' => $entry->{id}, 'sstr' => $entry->{stream}, 'sdist' => $entry->{distribution}};
458 my $label = $entry->{summary_contents};
459 if (length($label) > 100) {
460 $label = substr($label, 0, 100) . '...'; # limited space in dropdown / menu
462 $label = "[$entry->{sdist_label}/$entry->{stream} #$entry->{id}] " . $label;
463 push (@entries, [$label, OpenSRF::Utils::JSON->perl2JSON($value)]);
471 ##########################################################################
472 # predict and receive methods
474 __PACKAGE__->register_method(
475 method => 'make_predictions',
476 api_name => 'open-ils.serial.make_predictions',
480 desc => 'Receives an ssub id and populates the issuance and item tables',
483 desc => 'Serial Subscription ID',
490 sub make_predictions {
491 my ($self, $conn, $authtoken, $args) = @_;
493 my $editor = OpenILS::Utils::CStoreEditor->new();
494 my $ssub_id = $args->{ssub_id};
495 my $mfhd = MFHD->new(MARC::Record->new());
497 my $ssub = $editor->retrieve_serial_subscription([$ssub_id]);
498 my $scaps = $editor->search_serial_caption_and_pattern({ subscription => $ssub_id, active => 't'});
499 my $sdists = $editor->search_serial_distribution( [{ subscription => $ssub->id }, { flesh => 1,
500 flesh_fields => {sdist => [ qw/ streams / ]}, limit => 1 }] ); #TODO: 'deleted' support?
504 foreach my $scap (@$scaps) {
505 my $caption_field = _revive_caption($scap);
506 $caption_field->update('8' => $link_id);
507 $mfhd->append_fields($caption_field);
509 'caption' => $caption_field,
510 'scap_id' => $scap->id,
511 'num_to_predict' => $args->{num_to_predict}
513 if ($args->{base_issuance}) { # predict from a given issuance
514 $options->{predict_from} = _revive_holding($args->{base_issuance}->holding_code, $caption_field, 1); # fresh MFHD Record, so we simply default to 1 for seqno
515 } else { # default to predicting from last published
516 my $last_published = $editor->search_serial_issuance([
517 {'caption_and_pattern' => $scap->id,
518 'subscription' => $ssub_id},
519 {limit => 1, order_by => { siss => "date_published DESC" }}]
521 if ($last_published->[0]) {
522 my $last_siss = $last_published->[0];
523 $options->{predict_from} = _revive_holding($last_siss->holding_code, $caption_field, 1);
525 #TODO: throw event (can't predict from nothing!)
528 push( @predictions, _generate_issuance_values($mfhd, $options) );
533 foreach my $prediction (@predictions) {
534 my $issuance = new Fieldmapper::serial::issuance;
536 $issuance->label($prediction->{label});
537 $issuance->date_published($prediction->{date_published}->strftime('%F'));
538 $issuance->holding_code(OpenSRF::Utils::JSON->perl2JSON($prediction->{holding_code}));
539 $issuance->holding_type($prediction->{holding_type});
540 $issuance->caption_and_pattern($prediction->{caption_and_pattern});
541 $issuance->subscription($ssub->id);
542 push (@issuances, $issuance);
545 fleshed_issuance_alter($self, $conn, $authtoken, \@issuances); # FIXME: catch events
548 for (my $i = 0; $i < @issuances; $i++) {
549 my $date_expected = $predictions[$i]->{date_published}->add(seconds => interval_to_seconds($ssub->expected_date_offset))->strftime('%F');
550 my $issuance = $issuances[$i];
551 #$issuance->label(interval_to_seconds($ssub->expected_date_offset));
552 foreach my $sdist (@$sdists) {
553 my $streams = $sdist->streams;
554 foreach my $stream (@$streams) {
555 my $item = new Fieldmapper::serial::item;
557 $item->stream($stream->id);
558 $item->date_expected($date_expected);
559 $item->issuance($issuance->id);
560 push (@items, $item);
564 fleshed_item_alter($self, $conn, $authtoken, \@items); # FIXME: catch events
569 # _generate_issuance_values() is an initial attempt at a function which can be used
570 # to populate an issuance table with a list of predicted issues. It accepts
571 # a hash ref of options initially defined as:
572 # caption : the caption field to predict on
573 # num_to_predict : the number of issues you wish to predict
574 # last_rec_date : the date of the last received issue, to be used as an offset
575 # for predicting future issues
577 # The basic method is to first convert to a single holding if compressed, then
578 # increment the holding and save the resulting values to @issuances.
580 # returns @issuance_values, an array of hashrefs containing (formatted
581 # label, formatted chronology date, formatted estimated arrival date, and an
582 # array ref of holding subfields as (key, value, key, value ...)) (not a hash
583 # to protect order and possible duplicate keys), and a holding type.
585 sub _generate_issuance_values {
586 my ($mfhd, $options) = @_;
587 my $caption = $options->{caption};
588 my $scap_id = $options->{scap_id};
589 my $num_to_predict = $options->{num_to_predict};
590 my $predict_from = $options->{predict_from}; # issuance to predict from
591 #my $last_rec_date = $options->{last_rec_date}; # expected or actual
593 # TODO: add support for predicting serials with no chronology by passing in
594 # a last_pub_date option?
597 # Only needed for 'real' MFHD records, not our temp records
598 # my $link_id = $caption->link_id;
599 # if(!$predict_from) {
600 # my $htag = $caption->tag;
601 # $htag =~ s/^85/86/;
602 # my @holdings = $mfhd->holdings($htag, $link_id);
603 # my $last_holding = $holdings[-1];
605 # #if ($last_holding->is_compressed) {
606 # # $last_holding->compressed_to_last; # convert to last in range
608 # $predict_from = $last_holding;
612 $predict_from->notes('public', []);
613 # add a note marker for system use (?)
614 $predict_from->notes('private', ['AUTOGEN']);
616 my $strp = new DateTime::Format::Strptime(pattern => '%F');
619 my @predictions = $mfhd->generate_predictions({'base_holding' => $predict_from, 'num_to_predict' => $num_to_predict});
620 foreach my $prediction (@predictions) {
621 $pub_date = $strp->parse_datetime($prediction->chron_to_date);
626 label => $prediction->format,
627 date_published => $pub_date,
628 #date_expected => $date_expected->strftime('%F'),
629 holding_code => [$prediction->indicator(1),$prediction->indicator(2),$prediction->subfields_list],
630 holding_type => $MFHD_NAMES_BY_TAG{$caption->tag},
631 caption_and_pattern => $scap_id
636 return @issuance_values;
639 sub _revive_caption {
642 my $pattern_code = $scap->pattern_code;
645 my $pattern_parts = OpenSRF::Utils::JSON->JSON2perl($pattern_code);
646 unshift(@$pattern_parts, $MFHD_TAGS_BY_NAME{$scap->type});
647 my $pattern_field = new MARC::Field(@$pattern_parts);
649 # build MFHD::Caption
650 return new MFHD::Caption($pattern_field);
653 sub _revive_holding {
654 my $holding_code = shift;
655 my $caption_field = shift;
659 my $holding_parts = OpenSRF::Utils::JSON->JSON2perl($holding_code);
660 my $captag = $caption_field->tag;
661 $captag =~ s/^85/86/;
662 unshift(@$holding_parts, $captag);
663 my $holding_field = new MARC::Field(@$holding_parts);
665 # build MFHD::Holding
666 return new MFHD::Holding($seqno, $holding_field, $caption_field);
669 __PACKAGE__->register_method(
670 method => 'unitize_items',
671 api_name => 'open-ils.serial.receive_items',
675 desc => 'Marks an item as received, updates the shelving unit (creating a new shelving unit if needed), and updates the summaries',
678 desc => 'array of serial items',
683 desc => 'Returns number of received items',
690 my ($self, $conn, $auth, $items) = @_;
692 my( $reqr, $evt ) = $U->checkses($auth);
694 my $editor = new_editor(requestor => $reqr, xact => 1);
695 $self->api_name =~ /serial\.(\w*)_items/;
699 my %found_stream_ids;
702 my %stream_ids_by_unit_id;
705 my %sdist_by_unit_id;
706 my %sdist_by_stream_id;
708 my $new_unit_id; # id for '-2' units to share
709 foreach my $item (@$items) {
710 # for debugging only, TODO: delete
711 if (!ref $item) { # hopefully we got an id instead
712 $item = $editor->retrieve_serial_item($item);
715 my $unit_id = ref($item->unit) ? $item->unit->id : $item->unit;
716 my $stream_id = ref($item->stream) ? $item->stream->id : $item->stream;
717 my $issuance_id = ref($item->issuance) ? $item->issuance->id : $item->issuance;
718 #TODO: evt on any missing ids
720 if ($mode eq 'receive') {
721 $item->date_received('now');
722 $item->status('Received');
724 $item->status('Bindery');
727 # check for types to trigger summary updates
729 if (!ref $item->issuance) {
730 my $scaps = $editor->search_serial_caption_and_pattern([{"+siss" => {"id" => $issuance_id}}, { "join" => {"siss" => {}} }]);
732 } elsif (!ref $item->issuance->caption_and_pattern) {
733 $scap = $editor->retrieve_serial_caption_and_pattern($item->issuance->caption_and_pattern);
735 $scap = $editor->issuance->caption_and_pattern;
737 if (!exists($found_types{$stream_id})) {
738 $found_types{$stream_id} = {};
740 $found_types{$stream_id}->{$scap->type} = 1;
742 # create unit if needed
743 if ($unit_id == -1 or (!$new_unit_id and $unit_id == -2)) { # create unit per item
745 my $sdists = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
746 $unit = _build_unit($editor, $sdists->[0], $mode);
747 my $evt = _create_sunit($editor, $unit);
749 if ($unit_id == -2) {
750 $new_unit_id = $unit->id;
751 $unit_id = $new_unit_id;
753 $unit_id = $unit->id;
755 $item->unit($unit_id);
757 # get unit with 'DEFAULT's and save unit and sdist for later use
758 $unit = $editor->retrieve_serial_unit($unit->id);
759 $unit_map{$unit_id} = $unit;
760 $sdist_by_unit_id{$unit_id} = $sdists->[0];
761 $sdist_by_stream_id{$stream_id} = $sdists->[0];
762 } elsif ($unit_id == -2) { # create one unit for all '-2' items
763 $unit_id = $new_unit_id;
764 $item->unit($unit_id);
767 $found_unit_ids{$unit_id} = 1;
768 $found_stream_ids{$stream_id} = 1;
770 # save the stream_id for this unit_id
771 # TODO: prevent items from different streams in same unit? (perhaps in interface)
772 $stream_ids_by_unit_id{$unit_id} = $stream_id;
774 my $evt = _update_sitem($editor, undef, $item);
778 # deal with unit level labels
779 foreach my $unit_id (keys %found_unit_ids) {
781 # get all the needed issuances for unit
782 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"unit" => $unit_id, "status" => "Received"}}, {"join" => {"sitem" => {}}, "order_by" => {"siss" => "date_published"}} ]);
783 #TODO: evt on search failure
785 my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
787 # special case for single formatted_part (may have summarized version)
788 if (@$formatted_parts == 1) {
789 #TODO: MFHD.pm should have a 'format_summary' method for this
792 # retrieve and update unit contents
796 # if we just created the unit, we will already have it and the distribution stored
797 if (exists $unit_map{$unit_id}) {
798 $sunit = $unit_map{$unit_id};
799 $sdist = $sdist_by_unit_id{$unit_id};
801 $sunit = $editor->retrieve_serial_unit($unit_id);
802 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_ids_by_unit_id{$unit_id}}}, { "join" => {"sstr" => {}} }]);
803 $sdist = $sdist->[0];
806 $sunit->detailed_contents($sdist->unit_label_prefix . ' '
807 . join(', ', @$formatted_parts) . ' '
808 . $sdist->unit_label_suffix);
810 $sunit->summary_contents($sunit->detailed_contents); #TODO: change this when real summary contents are available
812 # create sort_key by left padding numbers to 6 digits
813 my $sort_key = $sunit->detailed_contents;
814 $sort_key =~ s/(\d+)/sprintf '%06d', $1/eg; # this may need improvement
815 $sunit->sort_key($sort_key);
817 if ($mode eq 'bind') {
818 $sunit->status(2); # set to 'Bindery' status
821 my $evt = _update_sunit($editor, undef, $sunit);
825 # TODO: cleanup 'dead' units (units which are now emptied of their items)
827 if ($mode eq 'receive') { # the summary holdings do not change when binding
828 # deal with stream level summaries
829 # summaries will be built from the "primary" stream only, that is, the stream with the lowest ID per distribution
830 # (TODO: consider direct designation)
831 my %primary_streams_by_sdist;
832 my %streams_by_sdist;
834 # see if we have primary streams, and if so, associate them with their distributions
835 foreach my $stream_id (keys %found_stream_ids) {
837 if (exists $sdist_by_stream_id{$stream_id}) {
838 $sdist = $sdist_by_stream_id{$stream_id};
840 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
841 $sdist = $sdist->[0];
844 if (!exists($streams_by_sdist{$sdist->id})) {
845 $streams = $editor->search_serial_stream([{"distribution" => $sdist->id}, {"order_by" => {"sstr" => "id"}}]);
846 $streams_by_sdist{$sdist->id} = $streams;
848 $streams = $streams_by_sdist{$sdist->id};
850 $primary_streams_by_sdist{$sdist->id} = $streams->[0] if ($stream_id == $streams->[0]->id);
853 # retrieve and update summaries for each affected primary stream's distribution
854 foreach my $sdist_id (keys %primary_streams_by_sdist) {
855 my $stream = $primary_streams_by_sdist{$sdist_id};
856 my $stream_id = $stream->id;
857 # get all the needed issuances for stream
858 # FIXME: search in Bindery/Bound/Not Published? as well as Received
859 foreach my $type (keys %{$found_types{$stream_id}}) {
860 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"stream" => $stream_id, "status" => "Received"}, "+scap" => {"type" => $type}}, {"join" => {"sitem" => {}, "scap" => {}}, "order_by" => {"siss" => "date_published"}} ]);
861 #TODO: evt on search failure
863 my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
865 # retrieve and update the generated_coverage of the summary
866 my $search_method = "search_serial_${type}_summary";
867 my $summary = $editor->$search_method([{"distribution" => $sdist_id}]);
868 $summary = $summary->[0];
869 $summary->generated_coverage(join(', ', @$formatted_parts));
870 my $update_method = "update_serial_${type}_summary";
871 return $editor->event unless $editor->$update_method($summary);
877 return {'num_items_received' => scalar @$items, 'new_unit_id' => $new_unit_id};
880 sub _find_or_create_call_number {
881 my ($e, $lib, $cn_string, $record) = @_;
883 my $existing = $e->search_asset_call_number({
884 "owning_lib" => $lib,
885 "label" => $cn_string,
888 }) or return $e->die_event;
891 return $existing->[0]->id;
893 return $e->die_event unless
894 $e->allowed("CREATE_VOLUME", $lib);
896 my $acn = new Fieldmapper::asset::call_number;
898 $acn->creator($e->requestor->id);
899 $acn->editor($e->requestor->id);
900 $acn->record($record);
901 $acn->label($cn_string);
902 $acn->owning_lib($lib);
904 $e->create_asset_call_number($acn) or return $e->die_event;
909 sub _issuances_received {
910 my ($e, $sitem) = @_;
912 my $results = $e->json_query({
915 {"transform" => "distinct", "column" => "issuance"}
918 "from" => {"sitem" => {"sstr" => {}, "siss" => {}}},
920 "+sstr" => {"distribution" => $sitem->stream->distribution->id},
921 "+siss" => {"holding_type" => $sitem->issuance->holding_type},
922 "+sitem" => {"date_received" => {"!=" => undef}}
924 }) or return $e->die_event;
926 return [ map { $e->retrieve_serial_issuance($_->{"issuance"}) } @$results ];
929 # XXX _prepare_unit_label() duplicates some code from unitize_items().
930 # Hopefully we can unify code paths down the road.
931 sub _prepare_unit_label {
932 my ($e, $sunit, $sdist, $issuance) = @_;
934 my ($mfhd, $formatted_parts) = _summarize_contents($e, [$issuance]);
936 # special case for single formatted_part (may have summarized version)
937 if (@$formatted_parts == 1) {
938 #TODO: MFHD.pm should have a 'format_summary' method for this
941 $sunit->detailed_contents(
944 $sdist->unit_label_prefix,
945 join(", ", @$formatted_parts),
946 $sdist->unit_label_suffix
950 # TODO: change this when real summary contents are available
951 $sunit->summary_contents($sunit->detailed_contents);
953 # Create sort_key by left padding numbers to 6 digits.
954 (my $sort_key = $sunit->detailed_contents) =~
955 s/(\d+)/sprintf '%06d', $1/eg;
956 $sunit->sort_key($sort_key);
959 # XXX duplicates a block of code from unitize_items(). Once I fully understand
960 # what's going on and I'm sure it's working right, I'd like to have
961 # unitize_items() just use this, keeping the logic in one place.
962 sub _prepare_summaries {
963 my ($e, $sitem, $issuances) = @_;
965 my $dist_id = $sitem->stream->distribution->id;
966 my $type = $sitem->issuance->holding_type;
968 # Make sure @$issuances contains the new issuance from sitem.
969 unless (grep { $_->id == $sitem->issuance->id } @$issuances) {
970 push @$issuances, $sitem->issuance;
973 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances);
975 my $search_method = "search_serial_${type}_summary";
976 my $summary = $e->$search_method([{"distribution" => $dist_id}]);
978 my $cu_method = "update";
981 $summary = $summary->[0];
983 my $class = "Fieldmapper::serial::${type}_summary";
984 $summary = $class->new;
985 $summary->distribution($dist_id);
986 $cu_method = "create";
989 $summary->generated_coverage(join(", ", @$formatted_parts));
990 my $method = "${cu_method}_serial_${type}_summary";
991 return $e->die_event unless $e->$method($summary);
994 __PACKAGE__->register_method(
995 "method" => "receive_items_one_unit_per",
996 "api_name" => "open-ils.serial.receive_items.one_unit_per",
1001 "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",
1005 "desc" => "authtoken",
1010 "desc" => "array of serial items, possibly fleshed with units and definitely fleshed with stream->distribution",
1015 "desc" => "id of bib record these items are associated with
1016 (XXX could/should be derived from items)",
1021 "desc" => "The item ID for each item successfully received",
1027 sub receive_items_one_unit_per {
1028 # XXX This function may be temporary, as it does some of what
1029 # unitize_items() does, just in a different way.
1030 my ($self, $client, $auth, $items, $record) = @_;
1032 my $e = new_editor("authtoken" => $auth, "xact" => 1);
1033 return $e->die_event unless $e->checkauth;
1035 my $user_id = $e->requestor->id;
1037 # Get a list of all the non-virtual field names in a serial::unit for
1038 # merging given unit objects with template-built units later.
1039 # XXX move this somewhere global so it isn't re-run all the time
1040 my $all_unit_fields =
1041 $Fieldmapper::fieldmap->{"Fieldmapper::serial::unit"}->{"fields"};
1042 my @real_unit_fields = grep {
1043 not $all_unit_fields->{$_}->{"virtual"}
1044 } keys %$all_unit_fields;
1046 foreach my $item (@$items) {
1047 # Note that we expect a certain fleshing on the items we're getting.
1048 my $sdist = $item->stream->distribution;
1050 # Create unit if given by user
1051 if (ref $item->unit) {
1052 # detach from the item, as we need to create separately
1053 my $user_unit = $item->unit;
1055 # get a unit based on associated template
1056 my $template_unit = _build_unit($e, $sdist, "receive", 1);
1057 if ($U->event_code($template_unit)) {
1059 $template_unit->{"note"} = "Item ID: " . $item->id;
1060 return $template_unit;
1063 # merge built unit with provided unit from user
1064 foreach (@real_unit_fields) {
1065 unless ($user_unit->$_) {
1066 $user_unit->$_($template_unit->$_);
1070 # Treat call number specially: the provided value from the
1071 # user will really be a string.
1072 if ($user_unit->call_number) {
1073 my $real_cn = _find_or_create_call_number(
1074 $e, $sdist->holding_lib->id,
1075 $user_unit->call_number, $record
1078 if ($U->event_code($real_cn)) {
1082 $user_unit->call_number($real_cn);
1086 my $evt = _prepare_unit_label(
1087 $e, $user_unit, $sdist, $item->issuance
1089 if ($U->event_code($evt)) {
1094 # fetch a list of issuances with received copies already existing
1095 # on this distribution.
1096 my $issuances = _issuances_received($e, $item); #XXX optimize later
1097 if ($U->event_code($issuances)) {
1102 # create/update summary objects related to this distribution
1103 $evt = _prepare_summaries($e, $item, $issuances);
1104 if ($U->event_code($evt)) {
1109 # set the incontrovertibles on the unit
1110 $user_unit->edit_date("now");
1111 $user_unit->create_date("now");
1112 $user_unit->editor($user_id);
1113 $user_unit->creator($user_id);
1115 return $e->die_event unless $e->create_serial_unit($user_unit);
1117 # save reference to new unit
1118 $item->unit($e->data->id);
1121 # Create notes if given by user
1122 if (ref($item->notes) and @{$item->notes}) {
1123 foreach my $note (@{$item->notes}) {
1124 $note->creator($user_id);
1125 $note->create_date("now");
1127 return $e->die_event unless $e->create_serial_item_note($note);
1130 $item->clear_notes; # They're saved; we no longer want them here.
1133 # Set the incontrovertibles on the item
1134 $item->status("Received");
1135 $item->date_received("now");
1136 $item->edit_date("now");
1137 $item->editor($user_id);
1139 return $e->die_event unless $e->update_serial_item($item);
1141 # send client a response
1142 $client->respond($item->id);
1145 $e->commit or return $e->die_event;
1153 my $skip_call_number = shift;
1155 my $attr = $mode . '_unit_template';
1156 my $template = $editor->retrieve_asset_copy_template($sdist->$attr) or
1157 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_COPY_TEMPLATE");
1159 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 );
1161 my $unit = new Fieldmapper::serial::unit;
1162 foreach my $part (@parts) {
1163 my $value = $template->$part;
1164 next if !defined($value);
1165 $unit->$part($value);
1168 # ignore circ_lib in template, set to distribution holding_lib
1169 $unit->circ_lib($sdist->holding_lib);
1170 $unit->creator($editor->requestor->id);
1171 $unit->editor($editor->requestor->id);
1173 unless ($skip_call_number) {
1174 $attr = $mode . '_call_number';
1175 my $cn = $sdist->$attr or
1176 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_CALL_NUMBER");
1178 $unit->call_number($cn);
1181 $unit->barcode('AUTO');
1182 $unit->sort_key('');
1183 $unit->summary_contents('');
1184 $unit->detailed_contents('');
1190 sub _summarize_contents {
1192 my $issuances = shift;
1194 # create MFHD record
1195 my $mfhd = MFHD->new(MARC::Record->new());
1198 my @scap_fields_ordered;
1201 foreach my $issuance (@$issuances) {
1202 my $scap_id = $issuance->caption_and_pattern;
1203 next if (!$scap_id); # skip issuances with no caption/pattern
1207 # if this is the first appearance of this scap, retrieve it and add it to the temporary record
1208 if (!exists $scaps{$issuance->caption_and_pattern}) {
1209 $scaps{$scap_id} = $editor->retrieve_serial_caption_and_pattern($scap_id);
1210 $scap = $scaps{$scap_id};
1211 $scap_field = _revive_caption($scap);
1212 $scap_fields{$scap_id} = $scap_field;
1213 push(@scap_fields_ordered, $scap_field);
1214 $scap_field->update('8' => $link_id);
1215 $mfhd->append_fields($scap_field);
1218 $scap = $scaps{$scap_id};
1219 $scap_field = $scap_fields{$scap_id};
1222 $mfhd->append_fields(_revive_holding($issuance->holding_code, $scap_field, $seqno));
1226 my @formatted_parts;
1227 foreach my $scap_field (@scap_fields_ordered) { #TODO: use generic MFHD "summarize" method, once available
1228 my @updated_holdings = $mfhd->get_compressed_holdings($scap_field);
1229 foreach my $holding (@updated_holdings) {
1230 push(@formatted_parts, $holding->format);
1234 return ($mfhd, \@formatted_parts);
1237 ##########################################################################
1240 __PACKAGE__->register_method(
1241 method => 'fetch_notes',
1242 api_name => 'open-ils.serial.item_note.retrieve.all',
1244 Returns an array of copy note objects.
1245 @param args A named hash of parameters including:
1246 authtoken : Required if viewing non-public notes
1247 item_id : The id of the item whose notes we want to retrieve
1248 pub : True if all the caller wants are public notes
1249 @return An array of note objects
1253 __PACKAGE__->register_method(
1254 method => 'fetch_notes',
1255 api_name => 'open-ils.serial.subscription_note.retrieve.all',
1257 Returns an array of copy note objects.
1258 @param args A named hash of parameters including:
1259 authtoken : Required if viewing non-public notes
1260 subscription_id : The id of the item whose notes we want to retrieve
1261 pub : True if all the caller wants are public notes
1262 @return An array of note objects
1266 __PACKAGE__->register_method(
1267 method => 'fetch_notes',
1268 api_name => 'open-ils.serial.distribution_note.retrieve.all',
1270 Returns an array of copy note objects.
1271 @param args A named hash of parameters including:
1272 authtoken : Required if viewing non-public notes
1273 distribution_id : The id of the item whose notes we want to retrieve
1274 pub : True if all the caller wants are public notes
1275 @return An array of note objects
1279 # TODO: revisit this method to consider replacing cstore direct calls
1281 my( $self, $connection, $args ) = @_;
1283 $self->api_name =~ /serial\.(\w*)_note/;
1286 my $id = $$args{object_id};
1287 my $authtoken = $$args{authtoken};
1291 return $U->cstorereq(
1292 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic',
1293 { $type => $id, pub => 't' } );
1295 # FIXME: restore perm check
1296 # ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
1297 # return $evt if $evt;
1298 return $U->cstorereq(
1299 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic', {$type => $id} );
1305 __PACKAGE__->register_method(
1306 method => 'create_note',
1307 api_name => 'open-ils.serial.item_note.create',
1309 Creates a new item note
1310 @param authtoken The login session key
1311 @param note The note object to create
1312 @return The id of the new note object
1316 __PACKAGE__->register_method(
1317 method => 'create_note',
1318 api_name => 'open-ils.serial.subscription_note.create',
1320 Creates a new subscription note
1321 @param authtoken The login session key
1322 @param note The note object to create
1323 @return The id of the new note object
1327 __PACKAGE__->register_method(
1328 method => 'create_note',
1329 api_name => 'open-ils.serial.distribution_note.create',
1331 Creates a new distribution note
1332 @param authtoken The login session key
1333 @param note The note object to create
1334 @return The id of the new note object
1339 my( $self, $connection, $authtoken, $note ) = @_;
1341 $self->api_name =~ /serial\.(\w*)_note/;
1344 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1345 return $e->event unless $e->checkauth;
1347 # FIXME: restore permission support
1348 # my $item = $e->retrieve_serial_item(
1354 # return $e->event unless
1355 # $e->allowed('CREATE_COPY_NOTE', $item->call_number->owning_lib);
1357 $note->create_date('now');
1358 $note->creator($e->requestor->id);
1359 $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
1362 my $method = "create_serial_${type}_note";
1363 $e->$method($note) or return $e->event;
1368 __PACKAGE__->register_method(
1369 method => 'delete_note',
1370 api_name => 'open-ils.serial.item_note.delete',
1372 Deletes an existing item note
1373 @param authtoken The login session key
1374 @param noteid The id of the note to delete
1375 @return 1 on success - Event otherwise.
1379 __PACKAGE__->register_method(
1380 method => 'delete_note',
1381 api_name => 'open-ils.serial.subscription_note.delete',
1383 Deletes an existing subscription note
1384 @param authtoken The login session key
1385 @param noteid The id of the note to delete
1386 @return 1 on success - Event otherwise.
1390 __PACKAGE__->register_method(
1391 method => 'delete_note',
1392 api_name => 'open-ils.serial.distribution_note.delete',
1394 Deletes an existing distribution note
1395 @param authtoken The login session key
1396 @param noteid The id of the note to delete
1397 @return 1 on success - Event otherwise.
1402 my( $self, $conn, $authtoken, $noteid ) = @_;
1404 $self->api_name =~ /serial\.(\w*)_note/;
1407 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1408 return $e->die_event unless $e->checkauth;
1410 my $method = "retrieve_serial_${type}_note";
1411 my $note = $e->$method([
1413 ]) or return $e->die_event;
1415 # FIXME: restore permissions check
1416 # if( $note->creator ne $e->requestor->id ) {
1417 # return $e->die_event unless
1418 # $e->allowed('DELETE_COPY_NOTE', $note->item->call_number->owning_lib);
1421 $method = "delete_serial_${type}_note";
1422 $e->$method($note) or return $e->die_event;
1428 ##########################################################################
1429 # subscription methods
1431 __PACKAGE__->register_method(
1432 method => 'fleshed_ssub_alter',
1433 api_name => 'open-ils.serial.subscription.fleshed.batch.update',
1437 desc => 'Receives an array of one or more subscriptions and updates the database as needed',
1439 name => 'authtoken',
1440 desc => 'Authtoken for current user session',
1444 name => 'subscriptions',
1445 desc => 'Array of fleshed subscriptions',
1451 desc => 'Returns 1 if successful, event if failed',
1457 sub fleshed_ssub_alter {
1458 my( $self, $conn, $auth, $ssubs ) = @_;
1459 return 1 unless ref $ssubs;
1460 my( $reqr, $evt ) = $U->checkses($auth);
1461 return $evt if $evt;
1462 my $editor = new_editor(requestor => $reqr, xact => 1);
1463 my $override = $self->api_name =~ /override/;
1465 # TODO: permission check
1466 # return $editor->event unless
1467 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
1469 for my $ssub (@$ssubs) {
1471 my $ssubid = $ssub->id;
1473 if( $ssub->isdeleted ) {
1474 $evt = _delete_ssub( $editor, $override, $ssub);
1475 } elsif( $ssub->isnew ) {
1476 _cleanse_dates($ssub, ['start_date','end_date']);
1477 $evt = _create_ssub( $editor, $ssub );
1479 _cleanse_dates($ssub, ['start_date','end_date']);
1480 $evt = _update_ssub( $editor, $override, $ssub );
1485 $logger->info("fleshed subscription-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
1489 $logger->debug("subscription-alter: done updating subscription batch");
1491 $logger->info("fleshed subscription-alter successfully updated ".scalar(@$ssubs)." subscriptions");
1496 my ($editor, $override, $ssub) = @_;
1497 $logger->info("subscription-alter: delete subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1498 my $sdists = $editor->search_serial_distribution(
1499 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1500 my $cps = $editor->search_serial_caption_and_pattern(
1501 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1502 my $sisses = $editor->search_serial_issuance(
1503 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1504 return OpenILS::Event->new(
1505 'SERIAL_SUBSCRIPTION_NOT_EMPTY', payload => $ssub->id ) if (@$sdists or @$cps or @$sisses);
1507 return $editor->event unless $editor->delete_serial_subscription($ssub);
1512 my ($editor, $ssub) = @_;
1514 $logger->info("subscription-alter: new subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1515 return $editor->event unless $editor->create_serial_subscription($ssub);
1520 my ($editor, $override, $ssub) = @_;
1522 $logger->info("subscription-alter: retrieving subscription ".$ssub->id);
1523 my $orig_ssub = $editor->retrieve_serial_subscription($ssub->id);
1525 $logger->info("subscription-alter: original subscription ".OpenSRF::Utils::JSON->perl2JSON($orig_ssub));
1526 $logger->info("subscription-alter: updated subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1527 return $editor->event unless $editor->update_serial_subscription($ssub);
1531 __PACKAGE__->register_method(
1532 method => "fleshed_serial_subscription_retrieve_batch",
1534 api_name => "open-ils.serial.subscription.fleshed.batch.retrieve"
1537 sub fleshed_serial_subscription_retrieve_batch {
1538 my( $self, $client, $ids ) = @_;
1539 # FIXME: permissions?
1540 $logger->info("Fetching fleshed subscriptions @$ids");
1541 return $U->cstorereq(
1542 "open-ils.cstore.direct.serial.subscription.search.atomic",
1545 flesh_fields => {ssub => [ qw/owning_lib notes/ ]}
1549 __PACKAGE__->register_method(
1550 method => "retrieve_sub_tree",
1552 api_name => "open-ils.serial.subscription_tree.retrieve"
1555 __PACKAGE__->register_method(
1556 method => "retrieve_sub_tree",
1557 api_name => "open-ils.serial.subscription_tree.global.retrieve"
1560 sub retrieve_sub_tree {
1562 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
1564 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
1568 # TODO: permission support
1569 if(!@org_ids and $user_session) {
1571 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
1572 @org_ids = ($user_obj->home_ou);
1575 if( $self->api_name =~ /global/ ) {
1576 return _build_subs_list( { record_entry => $docid } ); # TODO: filter for !deleted, or active?
1581 for my $orgid (@org_ids) {
1582 my $subs = _build_subs_list(
1583 { record_entry => $docid, owning_lib => $orgid } );# TODO: filter for !deleted, or active?
1584 push( @all_subs, @$subs );
1593 sub _build_subs_list {
1594 my $search_hash = shift;
1596 #$search_hash->{deleted} = 'f';
1597 my $e = new_editor();
1599 my $subs = $e->search_serial_subscription([$search_hash, { 'order_by' => {'ssub' => 'id'} }]);
1603 for my $sub (@$subs) {
1605 # TODO: filter on !deleted?
1606 my $dists = $e->search_serial_distribution(
1607 [{ subscription => $sub->id }, { 'order_by' => {'sdist' => 'label'} }]
1610 #$dists = [ sort { $a->label cmp $b->label } @$dists ];
1612 $sub->distributions($dists);
1614 # TODO: filter on !deleted?
1615 my $issuances = $e->search_serial_issuance(
1616 [{ subscription => $sub->id }, { 'order_by' => {'siss' => 'label'} }]
1619 #$issuances = [ sort { $a->label cmp $b->label } @$issuances ];
1620 $sub->issuances($issuances);
1622 # TODO: filter on !deleted?
1623 my $scaps = $e->search_serial_caption_and_pattern(
1624 [{ subscription => $sub->id }, { 'order_by' => {'scap' => 'id'} }]
1627 #$scaps = [ sort { $a->id cmp $b->id } @$scaps ];
1628 $sub->scaps($scaps);
1629 push( @built_subs, $sub );
1632 return \@built_subs;
1636 __PACKAGE__->register_method(
1637 method => "subscription_orgs_for_title",
1639 api_name => "open-ils.serial.subscription.retrieve_orgs_by_title"
1642 sub subscription_orgs_for_title {
1643 my( $self, $client, $record_id ) = @_;
1645 my $subs = $U->simple_scalar_request(
1647 "open-ils.cstore.direct.serial.subscription.search.atomic",
1648 { record_entry => $record_id }); # TODO: filter on !deleted?
1650 my $orgs = { map {$_->owning_lib => 1 } @$subs };
1651 return [ keys %$orgs ];
1655 ##########################################################################
1656 # distribution methods
1658 __PACKAGE__->register_method(
1659 method => 'fleshed_sdist_alter',
1660 api_name => 'open-ils.serial.distribution.fleshed.batch.update',
1664 desc => 'Receives an array of one or more distributions and updates the database as needed',
1666 name => 'authtoken',
1667 desc => 'Authtoken for current user session',
1671 name => 'distributions',
1672 desc => 'Array of fleshed distributions',
1678 desc => 'Returns 1 if successful, event if failed',
1684 sub fleshed_sdist_alter {
1685 my( $self, $conn, $auth, $sdists ) = @_;
1686 return 1 unless ref $sdists;
1687 my( $reqr, $evt ) = $U->checkses($auth);
1688 return $evt if $evt;
1689 my $editor = new_editor(requestor => $reqr, xact => 1);
1690 my $override = $self->api_name =~ /override/;
1692 # TODO: permission check
1693 # return $editor->event unless
1694 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
1696 for my $sdist (@$sdists) {
1697 my $sdistid = $sdist->id;
1699 if( $sdist->isdeleted ) {
1700 $evt = _delete_sdist( $editor, $override, $sdist);
1701 } elsif( $sdist->isnew ) {
1702 $evt = _create_sdist( $editor, $sdist );
1704 $evt = _update_sdist( $editor, $override, $sdist );
1709 $logger->info("fleshed distribution-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
1713 $logger->debug("distribution-alter: done updating distribution batch");
1715 $logger->info("fleshed distribution-alter successfully updated ".scalar(@$sdists)." distributions");
1720 my ($editor, $override, $sdist) = @_;
1721 $logger->info("distribution-alter: delete distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
1722 return $editor->event unless $editor->delete_serial_distribution($sdist);
1727 my ($editor, $sdist) = @_;
1729 $logger->info("distribution-alter: new distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
1730 return $editor->event unless $editor->create_serial_distribution($sdist);
1732 # create summaries too
1733 my $summary = new Fieldmapper::serial::basic_summary;
1734 $summary->distribution($sdist->id);
1735 $summary->generated_coverage('');
1736 return $editor->event unless $editor->create_serial_basic_summary($summary);
1737 $summary = new Fieldmapper::serial::supplement_summary;
1738 $summary->distribution($sdist->id);
1739 $summary->generated_coverage('');
1740 return $editor->event unless $editor->create_serial_supplement_summary($summary);
1741 $summary = new Fieldmapper::serial::index_summary;
1742 $summary->distribution($sdist->id);
1743 $summary->generated_coverage('');
1744 return $editor->event unless $editor->create_serial_index_summary($summary);
1746 # create a starter stream (TODO: reconsider this)
1747 my $stream = new Fieldmapper::serial::stream;
1748 $stream->distribution($sdist->id);
1749 return $editor->event unless $editor->create_serial_stream($stream);
1755 my ($editor, $override, $sdist) = @_;
1757 $logger->info("distribution-alter: retrieving distribution ".$sdist->id);
1758 my $orig_sdist = $editor->retrieve_serial_distribution($sdist->id);
1760 $logger->info("distribution-alter: original distribution ".OpenSRF::Utils::JSON->perl2JSON($orig_sdist));
1761 $logger->info("distribution-alter: updated distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
1762 return $editor->event unless $editor->update_serial_distribution($sdist);
1766 __PACKAGE__->register_method(
1767 method => "fleshed_serial_distribution_retrieve_batch",
1769 api_name => "open-ils.serial.distribution.fleshed.batch.retrieve"
1772 sub fleshed_serial_distribution_retrieve_batch {
1773 my( $self, $client, $ids ) = @_;
1774 # FIXME: permissions?
1775 $logger->info("Fetching fleshed distributions @$ids");
1776 return $U->cstorereq(
1777 "open-ils.cstore.direct.serial.distribution.search.atomic",
1780 flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams / ]}
1784 ##########################################################################
1785 # caption and pattern methods
1787 __PACKAGE__->register_method(
1788 method => 'scap_alter',
1789 api_name => 'open-ils.serial.caption_and_pattern.batch.update',
1793 desc => 'Receives an array of one or more caption and patterns and updates the database as needed',
1795 name => 'authtoken',
1796 desc => 'Authtoken for current user session',
1801 desc => 'Array of caption and patterns',
1807 desc => 'Returns 1 if successful, event if failed',
1814 my( $self, $conn, $auth, $scaps ) = @_;
1815 return 1 unless ref $scaps;
1816 my( $reqr, $evt ) = $U->checkses($auth);
1817 return $evt if $evt;
1818 my $editor = new_editor(requestor => $reqr, xact => 1);
1819 my $override = $self->api_name =~ /override/;
1821 # TODO: permission check
1822 # return $editor->event unless
1823 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
1825 for my $scap (@$scaps) {
1826 my $scapid = $scap->id;
1828 if( $scap->isdeleted ) {
1829 $evt = _delete_scap( $editor, $override, $scap);
1830 } elsif( $scap->isnew ) {
1831 $evt = _create_scap( $editor, $scap );
1833 $evt = _update_scap( $editor, $override, $scap );
1838 $logger->info("caption_and_pattern-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
1842 $logger->debug("caption_and_pattern-alter: done updating caption_and_pattern batch");
1844 $logger->info("caption_and_pattern-alter successfully updated ".scalar(@$scaps)." caption_and_patterns");
1849 my ($editor, $override, $scap) = @_;
1850 $logger->info("caption_and_pattern-alter: delete caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
1851 my $sisses = $editor->search_serial_issuance(
1852 { caption_and_pattern => $scap->id }, { limit => 1 } ); #TODO: 'deleted' support?
1853 return OpenILS::Event->new(
1854 'SERIAL_CAPTION_AND_PATTERN_HAS_ISSUANCES', payload => $scap->id ) if (@$sisses);
1856 return $editor->event unless $editor->delete_serial_caption_and_pattern($scap);
1861 my ($editor, $scap) = @_;
1863 $logger->info("caption_and_pattern-alter: new caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
1864 return $editor->event unless $editor->create_serial_caption_and_pattern($scap);
1869 my ($editor, $override, $scap) = @_;
1871 $logger->info("caption_and_pattern-alter: retrieving caption_and_pattern ".$scap->id);
1872 my $orig_scap = $editor->retrieve_serial_caption_and_pattern($scap->id);
1874 $logger->info("caption_and_pattern-alter: original caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($orig_scap));
1875 $logger->info("caption_and_pattern-alter: updated caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
1876 return $editor->event unless $editor->update_serial_caption_and_pattern($scap);
1880 __PACKAGE__->register_method(
1881 method => "serial_caption_and_pattern_retrieve_batch",
1883 api_name => "open-ils.serial.caption_and_pattern.batch.retrieve"
1886 sub serial_caption_and_pattern_retrieve_batch {
1887 my( $self, $client, $ids ) = @_;
1888 $logger->info("Fetching caption_and_patterns @$ids");
1889 return $U->cstorereq(
1890 "open-ils.cstore.direct.serial.caption_and_pattern.search.atomic",
1895 __PACKAGE__->register_method(
1896 "method" => "bre_by_identifier",
1897 "api_name" => "open-ils.serial.biblio.record_entry.by_identifier",
1900 "desc" => "Find instances of biblio.record_entry given a search token" .
1901 " that could be a value for any identifier defined in " .
1902 "config.metabib_field",
1904 {"desc" => "Search token", "type" => "string"},
1905 {"desc" => "Options: require_subscriptions, add_mvr, is_actual_id" .
1906 " (all boolean)", "type" => "object"}
1909 "desc" => "Any matching BREs, or if the add_mvr option is true, " .
1910 "objects with a 'bre' key/value pair, and an 'mvr' " .
1911 "key-value pair. BREs have subscriptions fleshed on.",
1917 sub bre_by_identifier {
1918 my ($self, $client, $term, $options) = @_;
1920 return new OpenILS::Event("BAD_PARAMS") unless $term;
1923 my $e = new_editor();
1927 if ($options->{"is_actual_id"}) {
1931 $e->search_config_metabib_field({"field_class" => "identifier"})
1932 or return $e->die_event;
1934 my @identifiers = map { $_->name } @$cmf;
1935 my $query = join(" || ", map { "id|$_: $term" } @identifiers);
1937 my $search = create OpenSRF::AppSession("open-ils.search");
1938 my $search_result = $search->request(
1939 "open-ils.search.biblio.multiclass.query.staff", {}, $query
1941 $search->disconnect;
1943 # Un-nest results. They tend to look like [[1],[2],[3]] for some reason.
1944 @ids = map { @{$_} } @{$search_result->{"ids"}};
1952 my $bre = $e->search_biblio_record_entry([
1954 "flesh" => 2, "flesh_fields" => {
1955 "bre" => ["subscriptions"],
1956 "ssub" => ["owning_lib"]
1959 ]) or return $e->die_event;
1961 if (@$bre && $options->{"require_subscriptions"}) {
1962 $bre = [ grep { @{$_->subscriptions} } @$bre ];
1967 if (@$bre) { # re-evaluate after possible grep
1968 if ($options->{"add_mvr"}) {
1970 {"bre" => $_, "mvr" => _get_mvr($_->id)}
1973 $client->respond($_) foreach (@$bre);
1980 __PACKAGE__->register_method(
1981 "method" => "get_receivable_items",
1982 "api_name" => "open-ils.serial.items.receivable.by_subscription",
1985 "desc" => "Return all receivable items under a given subscription",
1987 {"desc" => "Authtoken", "type" => "string"},
1988 {"desc" => "Subscription ID", "type" => "number"},
1991 "desc" => "All receivable items under a given subscription",
1997 __PACKAGE__->register_method(
1998 "method" => "get_receivable_items",
1999 "api_name" => "open-ils.serial.items.receivable.by_issuance",
2002 "desc" => "Return all receivable items under a given issuance",
2004 {"desc" => "Authtoken", "type" => "string"},
2005 {"desc" => "Issuance ID", "type" => "number"},
2008 "desc" => "All receivable items under a given issuance",
2014 sub get_receivable_items {
2015 my ($self, $client, $auth, $term) = @_;
2017 my $e = new_editor("authtoken" => $auth);
2018 return $e->die_event unless $e->checkauth;
2022 my $by = ($self->api_name =~ /by_(\w+)$/)[0];
2025 "issuance" => {"issuance" => $term},
2026 "subscription" => {"+siss" => {"subscription" => $term}}
2029 my $item_ids = $e->json_query(
2031 "select" => {"sitem" => ["id"]},
2032 "from" => {"sitem" => "siss"},
2034 %{$where{$by}}, "date_received" => undef
2036 "order_by" => {"sitem" => ["id"]}
2038 ) or return $e->die_event;
2040 return undef unless @$item_ids;
2042 foreach (map { $_->{"id"} } @$item_ids) {
2044 $e->retrieve_serial_item([
2048 "sitem" => ["stream", "issuance"],
2049 "sstr" => ["distribution"],
2050 "sdist" => ["holding_lib"]
2061 __PACKAGE__->register_method(
2062 "method" => "get_receivable_issuances",
2063 "api_name" => "open-ils.serial.issuances.receivable",
2066 "desc" => "Return all issuances with receivable items given " .
2067 "a subscription ID",
2069 {"desc" => "Authtoken", "type" => "string"},
2070 {"desc" => "Subscription ID", "type" => "number"},
2073 "desc" => "All issuances with receivable items " .
2074 "(but not the items themselves)", "type" => "object"
2079 sub get_receivable_issuances {
2080 my ($self, $client, $auth, $sub_id) = @_;
2082 my $e = new_editor("authtoken" => $auth);
2083 return $e->die_event unless $e->checkauth;
2087 my $issuance_ids = $e->json_query({
2090 {"transform" => "distinct", "column" => "id"},
2094 "from" => {"siss" => "sitem"},
2096 "subscription" => $sub_id,
2097 "+sitem" => {"date_received" => undef}
2100 "siss" => {"date_published" => {"direction" => "asc"}}
2103 }) or return $e->die_event;
2105 $client->respond($e->retrieve_serial_issuance($_->{"id"}))
2106 foreach (@$issuance_ids);