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/ ]}
352 sub received_siss_by_bib {
357 my $args = shift || {};
358 $$args{order} ||= 'asc';
360 my $e = new_editor();
361 my $issuances = $e->json_query({
362 select => { 'siss' => [ 'id' ] },
367 fkey => 'subscription'
372 $$args{ou} ? ( join => {
379 fkey => 'distribution'
388 '+ssub' => { record_entry => $bib },
390 # XXX should we also take specific item statuses into account?
391 date_received => { '!=' => undef }
393 $$args{ou} ? ( '+sdist' => {
397 'actor.org_unit_descendants',
398 defined($$args{depth}) ? ( $$args{ou}, $$args{depth} ) : ( $$args{ou} )
404 $$args{limit} ? ( limit => $$args{limit} ) : (),
405 $$args{offset} ? ( offset => $$args{offset} ) : (),
406 order_by => [{ class => 'siss', field => 'date_published', direction => $$args{order} }],
410 $client->respond($e->retrieve_serial_issuance($_->{id})) for @$issuances;
413 __PACKAGE__->register_method(
414 method => 'received_siss_by_bib',
415 api_name => 'open-ils.serial.siss.retrieve.by_bib',
420 desc => 'Receives a Bib ID and other optional params and returns "siss" (issuance) objects',
423 desc => 'id of the bre to which the issuances belong',
428 q/A hash of optional arguments. Valid keys and their meanings:
429 order := date_published sort direction, either "asc" (chronological, default) or "desc" (reverse chronological)
430 limit := Number of issuances to return. Useful for paging results, or finding the oldest or newest
431 offest := Number of issuance to skip before returning results. Useful for paging.
432 orgid := OU id used to scope retrieval, based on distribution.holding_lib
433 depth := OU depth used to range the scope of orgid
441 ##########################################################################
444 __PACKAGE__->register_method(
445 method => 'fleshed_sunit_alter',
446 api_name => 'open-ils.serial.sunit.fleshed.batch.update',
450 desc => 'Receives an array of one or more Units and updates the database as needed',
453 desc => 'Authtoken for current user session',
458 desc => 'Array of fleshed Units',
464 desc => 'Returns 1 if successful, event if failed',
470 sub fleshed_sunit_alter {
471 my( $self, $conn, $auth, $sunits ) = @_;
472 return 1 unless ref $sunits;
473 my( $reqr, $evt ) = $U->checkses($auth);
475 my $editor = new_editor(requestor => $reqr, xact => 1);
476 my $override = $self->api_name =~ /override/;
478 # TODO: permission support
479 # return $editor->event unless
480 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
482 for my $sunit (@$sunits) {
483 if( $sunit->isdeleted ) {
484 $evt = _delete_sunit( $editor, $override, $sunit );
486 $sunit->default_location( $sunit->default_location->id ) if ref $sunit->default_location;
488 if( $sunit->isnew ) {
489 $evt = _create_sunit( $editor, $sunit );
491 $evt = _update_sunit( $editor, $override, $sunit );
497 $logger->info("fleshed sunit-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
501 $logger->debug("sunit-alter: done updating sunit batch");
503 $logger->info("fleshed sunit-alter successfully updated ".scalar(@$sunits)." Units");
508 my ($editor, $override, $sunit) = @_;
509 $logger->info("sunit-alter: delete sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
510 return $editor->event unless $editor->delete_serial_unit($sunit);
515 my ($editor, $sunit) = @_;
517 $logger->info("sunit-alter: new Unit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
518 return $editor->event unless $editor->create_serial_unit($sunit);
523 my ($editor, $override, $sunit) = @_;
525 $logger->info("sunit-alter: retrieving sunit ".$sunit->id);
526 my $orig_sunit = $editor->retrieve_serial_unit($sunit->id);
528 $logger->info("sunit-alter: original sunit ".OpenSRF::Utils::JSON->perl2JSON($orig_sunit));
529 $logger->info("sunit-alter: updated sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
530 return $editor->event unless $editor->update_serial_unit($sunit);
534 __PACKAGE__->register_method(
535 method => "retrieve_unit_list",
537 api_name => "open-ils.serial.unit_list.retrieve"
540 sub retrieve_unit_list {
542 my( $self, $client, @sdist_ids ) = @_;
544 if(ref($sdist_ids[0])) { @sdist_ids = @{$sdist_ids[0]}; }
546 my $e = new_editor();
550 { 'sunit' => [ 'id', 'summary_contents', 'sort_key' ],
551 'sitem' => ['stream'],
552 'sstr' => ['distribution'],
553 'sdist' => [{'column' => 'label', 'alias' => 'sdist_label'}]
560 { 'join' => { 'sunit' => {} } }
565 'distinct' => 'true',
566 'where' => { '+sdist' => {'id' => \@sdist_ids} },
567 'order_by' => [{'class' => 'sunit', 'field' => 'sort_key'}]
570 my $unit_list_entries = $e->json_query($query);
573 foreach my $entry (@$unit_list_entries) {
574 my $value = {'sunit' => $entry->{id}, 'sstr' => $entry->{stream}, 'sdist' => $entry->{distribution}};
575 my $label = $entry->{summary_contents};
576 if (length($label) > 100) {
577 $label = substr($label, 0, 100) . '...'; # limited space in dropdown / menu
579 $label = "[$entry->{sdist_label}/$entry->{stream} #$entry->{id}] " . $label;
580 push (@entries, [$label, OpenSRF::Utils::JSON->perl2JSON($value)]);
588 ##########################################################################
589 # predict and receive methods
591 __PACKAGE__->register_method(
592 method => 'make_predictions',
593 api_name => 'open-ils.serial.make_predictions',
597 desc => 'Receives an ssub id and populates the issuance and item tables',
600 desc => 'Serial Subscription ID',
607 sub make_predictions {
608 my ($self, $conn, $authtoken, $args) = @_;
610 my $editor = OpenILS::Utils::CStoreEditor->new();
611 my $ssub_id = $args->{ssub_id};
612 my $mfhd = MFHD->new(MARC::Record->new());
614 my $ssub = $editor->retrieve_serial_subscription([$ssub_id]);
615 my $scaps = $editor->search_serial_caption_and_pattern({ subscription => $ssub_id, active => 't'});
616 my $sdists = $editor->search_serial_distribution( [{ subscription => $ssub->id }, { flesh => 1,
617 flesh_fields => {sdist => [ qw/ streams / ]}, limit => 1 }] ); #TODO: 'deleted' support?
621 foreach my $scap (@$scaps) {
622 my $caption_field = _revive_caption($scap);
623 $caption_field->update('8' => $link_id);
624 $mfhd->append_fields($caption_field);
626 'caption' => $caption_field,
627 'scap_id' => $scap->id,
628 'num_to_predict' => $args->{num_to_predict}
630 if ($args->{base_issuance}) { # predict from a given issuance
631 $options->{predict_from} = _revive_holding($args->{base_issuance}->holding_code, $caption_field, 1); # fresh MFHD Record, so we simply default to 1 for seqno
632 } else { # default to predicting from last published
633 my $last_published = $editor->search_serial_issuance([
634 {'caption_and_pattern' => $scap->id,
635 'subscription' => $ssub_id},
636 {limit => 1, order_by => { siss => "date_published DESC" }}]
638 if ($last_published->[0]) {
639 my $last_siss = $last_published->[0];
640 $options->{predict_from} = _revive_holding($last_siss->holding_code, $caption_field, 1);
642 #TODO: throw event (can't predict from nothing!)
645 push( @predictions, _generate_issuance_values($mfhd, $options) );
650 foreach my $prediction (@predictions) {
651 my $issuance = new Fieldmapper::serial::issuance;
653 $issuance->label($prediction->{label});
654 $issuance->date_published($prediction->{date_published}->strftime('%F'));
655 $issuance->holding_code(OpenSRF::Utils::JSON->perl2JSON($prediction->{holding_code}));
656 $issuance->holding_type($prediction->{holding_type});
657 $issuance->caption_and_pattern($prediction->{caption_and_pattern});
658 $issuance->subscription($ssub->id);
659 push (@issuances, $issuance);
662 fleshed_issuance_alter($self, $conn, $authtoken, \@issuances); # FIXME: catch events
665 for (my $i = 0; $i < @issuances; $i++) {
666 my $date_expected = $predictions[$i]->{date_published}->add(seconds => interval_to_seconds($ssub->expected_date_offset))->strftime('%F');
667 my $issuance = $issuances[$i];
668 #$issuance->label(interval_to_seconds($ssub->expected_date_offset));
669 foreach my $sdist (@$sdists) {
670 my $streams = $sdist->streams;
671 foreach my $stream (@$streams) {
672 my $item = new Fieldmapper::serial::item;
674 $item->stream($stream->id);
675 $item->date_expected($date_expected);
676 $item->issuance($issuance->id);
677 push (@items, $item);
681 fleshed_item_alter($self, $conn, $authtoken, \@items); # FIXME: catch events
686 # _generate_issuance_values() is an initial attempt at a function which can be used
687 # to populate an issuance table with a list of predicted issues. It accepts
688 # a hash ref of options initially defined as:
689 # caption : the caption field to predict on
690 # num_to_predict : the number of issues you wish to predict
691 # last_rec_date : the date of the last received issue, to be used as an offset
692 # for predicting future issues
694 # The basic method is to first convert to a single holding if compressed, then
695 # increment the holding and save the resulting values to @issuances.
697 # returns @issuance_values, an array of hashrefs containing (formatted
698 # label, formatted chronology date, formatted estimated arrival date, and an
699 # array ref of holding subfields as (key, value, key, value ...)) (not a hash
700 # to protect order and possible duplicate keys), and a holding type.
702 sub _generate_issuance_values {
703 my ($mfhd, $options) = @_;
704 my $caption = $options->{caption};
705 my $scap_id = $options->{scap_id};
706 my $num_to_predict = $options->{num_to_predict};
707 my $predict_from = $options->{predict_from}; # issuance to predict from
708 #my $last_rec_date = $options->{last_rec_date}; # expected or actual
710 # TODO: add support for predicting serials with no chronology by passing in
711 # a last_pub_date option?
714 # Only needed for 'real' MFHD records, not our temp records
715 # my $link_id = $caption->link_id;
716 # if(!$predict_from) {
717 # my $htag = $caption->tag;
718 # $htag =~ s/^85/86/;
719 # my @holdings = $mfhd->holdings($htag, $link_id);
720 # my $last_holding = $holdings[-1];
722 # #if ($last_holding->is_compressed) {
723 # # $last_holding->compressed_to_last; # convert to last in range
725 # $predict_from = $last_holding;
729 $predict_from->notes('public', []);
730 # add a note marker for system use (?)
731 $predict_from->notes('private', ['AUTOGEN']);
733 my $strp = new DateTime::Format::Strptime(pattern => '%F');
736 my @predictions = $mfhd->generate_predictions({'base_holding' => $predict_from, 'num_to_predict' => $num_to_predict});
737 foreach my $prediction (@predictions) {
738 $pub_date = $strp->parse_datetime($prediction->chron_to_date);
743 label => $prediction->format,
744 date_published => $pub_date,
745 #date_expected => $date_expected->strftime('%F'),
746 holding_code => [$prediction->indicator(1),$prediction->indicator(2),$prediction->subfields_list],
747 holding_type => $MFHD_NAMES_BY_TAG{$caption->tag},
748 caption_and_pattern => $scap_id
753 return @issuance_values;
756 sub _revive_caption {
759 my $pattern_code = $scap->pattern_code;
762 my $pattern_parts = OpenSRF::Utils::JSON->JSON2perl($pattern_code);
763 unshift(@$pattern_parts, $MFHD_TAGS_BY_NAME{$scap->type});
764 my $pattern_field = new MARC::Field(@$pattern_parts);
766 # build MFHD::Caption
767 return new MFHD::Caption($pattern_field);
770 sub _revive_holding {
771 my $holding_code = shift;
772 my $caption_field = shift;
776 my $holding_parts = OpenSRF::Utils::JSON->JSON2perl($holding_code);
777 my $captag = $caption_field->tag;
778 $captag =~ s/^85/86/;
779 unshift(@$holding_parts, $captag);
780 my $holding_field = new MARC::Field(@$holding_parts);
782 # build MFHD::Holding
783 return new MFHD::Holding($seqno, $holding_field, $caption_field);
786 __PACKAGE__->register_method(
787 method => 'unitize_items',
788 api_name => 'open-ils.serial.receive_items',
792 desc => 'Marks an item as received, updates the shelving unit (creating a new shelving unit if needed), and updates the summaries',
795 desc => 'array of serial items',
800 desc => 'Returns number of received items',
807 my ($self, $conn, $auth, $items) = @_;
809 my( $reqr, $evt ) = $U->checkses($auth);
811 my $editor = new_editor(requestor => $reqr, xact => 1);
812 $self->api_name =~ /serial\.(\w*)_items/;
816 my %found_stream_ids;
819 my %stream_ids_by_unit_id;
822 my %sdist_by_unit_id;
823 my %sdist_by_stream_id;
825 my $new_unit_id; # id for '-2' units to share
826 foreach my $item (@$items) {
827 # for debugging only, TODO: delete
828 if (!ref $item) { # hopefully we got an id instead
829 $item = $editor->retrieve_serial_item($item);
832 my $unit_id = ref($item->unit) ? $item->unit->id : $item->unit;
833 my $stream_id = ref($item->stream) ? $item->stream->id : $item->stream;
834 my $issuance_id = ref($item->issuance) ? $item->issuance->id : $item->issuance;
835 #TODO: evt on any missing ids
837 if ($mode eq 'receive') {
838 $item->date_received('now');
839 $item->status('Received');
841 $item->status('Bindery');
844 # check for types to trigger summary updates
846 if (!ref $item->issuance) {
847 my $scaps = $editor->search_serial_caption_and_pattern([{"+siss" => {"id" => $issuance_id}}, { "join" => {"siss" => {}} }]);
849 } elsif (!ref $item->issuance->caption_and_pattern) {
850 $scap = $editor->retrieve_serial_caption_and_pattern($item->issuance->caption_and_pattern);
852 $scap = $editor->issuance->caption_and_pattern;
854 if (!exists($found_types{$stream_id})) {
855 $found_types{$stream_id} = {};
857 $found_types{$stream_id}->{$scap->type} = 1;
859 # create unit if needed
860 if ($unit_id == -1 or (!$new_unit_id and $unit_id == -2)) { # create unit per item
862 my $sdists = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
863 $unit = _build_unit($editor, $sdists->[0], $mode);
864 my $evt = _create_sunit($editor, $unit);
866 if ($unit_id == -2) {
867 $new_unit_id = $unit->id;
868 $unit_id = $new_unit_id;
870 $unit_id = $unit->id;
872 $item->unit($unit_id);
874 # get unit with 'DEFAULT's and save unit and sdist for later use
875 $unit = $editor->retrieve_serial_unit($unit->id);
876 $unit_map{$unit_id} = $unit;
877 $sdist_by_unit_id{$unit_id} = $sdists->[0];
878 $sdist_by_stream_id{$stream_id} = $sdists->[0];
879 } elsif ($unit_id == -2) { # create one unit for all '-2' items
880 $unit_id = $new_unit_id;
881 $item->unit($unit_id);
884 $found_unit_ids{$unit_id} = 1;
885 $found_stream_ids{$stream_id} = 1;
887 # save the stream_id for this unit_id
888 # TODO: prevent items from different streams in same unit? (perhaps in interface)
889 $stream_ids_by_unit_id{$unit_id} = $stream_id;
891 my $evt = _update_sitem($editor, undef, $item);
895 # deal with unit level labels
896 foreach my $unit_id (keys %found_unit_ids) {
898 # get all the needed issuances for unit
899 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"unit" => $unit_id, "status" => "Received"}}, {"join" => {"sitem" => {}}, "order_by" => {"siss" => "date_published"}} ]);
900 #TODO: evt on search failure
902 my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
904 # special case for single formatted_part (may have summarized version)
905 if (@$formatted_parts == 1) {
906 #TODO: MFHD.pm should have a 'format_summary' method for this
909 # retrieve and update unit contents
913 # if we just created the unit, we will already have it and the distribution stored
914 if (exists $unit_map{$unit_id}) {
915 $sunit = $unit_map{$unit_id};
916 $sdist = $sdist_by_unit_id{$unit_id};
918 $sunit = $editor->retrieve_serial_unit($unit_id);
919 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_ids_by_unit_id{$unit_id}}}, { "join" => {"sstr" => {}} }]);
920 $sdist = $sdist->[0];
923 $sunit->detailed_contents($sdist->unit_label_prefix . ' '
924 . join(', ', @$formatted_parts) . ' '
925 . $sdist->unit_label_suffix);
927 $sunit->summary_contents($sunit->detailed_contents); #TODO: change this when real summary contents are available
929 # create sort_key by left padding numbers to 6 digits
930 my $sort_key = $sunit->detailed_contents;
931 $sort_key =~ s/(\d+)/sprintf '%06d', $1/eg; # this may need improvement
932 $sunit->sort_key($sort_key);
934 if ($mode eq 'bind') {
935 $sunit->status(2); # set to 'Bindery' status
938 my $evt = _update_sunit($editor, undef, $sunit);
942 # TODO: cleanup 'dead' units (units which are now emptied of their items)
944 if ($mode eq 'receive') { # the summary holdings do not change when binding
945 # deal with stream level summaries
946 # summaries will be built from the "primary" stream only, that is, the stream with the lowest ID per distribution
947 # (TODO: consider direct designation)
948 my %primary_streams_by_sdist;
949 my %streams_by_sdist;
951 # see if we have primary streams, and if so, associate them with their distributions
952 foreach my $stream_id (keys %found_stream_ids) {
954 if (exists $sdist_by_stream_id{$stream_id}) {
955 $sdist = $sdist_by_stream_id{$stream_id};
957 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
958 $sdist = $sdist->[0];
961 if (!exists($streams_by_sdist{$sdist->id})) {
962 $streams = $editor->search_serial_stream([{"distribution" => $sdist->id}, {"order_by" => {"sstr" => "id"}}]);
963 $streams_by_sdist{$sdist->id} = $streams;
965 $streams = $streams_by_sdist{$sdist->id};
967 $primary_streams_by_sdist{$sdist->id} = $streams->[0] if ($stream_id == $streams->[0]->id);
970 # retrieve and update summaries for each affected primary stream's distribution
971 foreach my $sdist_id (keys %primary_streams_by_sdist) {
972 my $stream = $primary_streams_by_sdist{$sdist_id};
973 my $stream_id = $stream->id;
974 # get all the needed issuances for stream
975 # FIXME: search in Bindery/Bound/Not Published? as well as Received
976 foreach my $type (keys %{$found_types{$stream_id}}) {
977 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"stream" => $stream_id, "status" => "Received"}, "+scap" => {"type" => $type}}, {"join" => {"sitem" => {}, "scap" => {}}, "order_by" => {"siss" => "date_published"}} ]);
978 #TODO: evt on search failure
980 my ($mfhd, $formatted_parts) = _summarize_contents($editor, $issuances);
982 # retrieve and update the generated_coverage of the summary
983 my $search_method = "search_serial_${type}_summary";
984 my $summary = $editor->$search_method([{"distribution" => $sdist_id}]);
985 $summary = $summary->[0];
986 $summary->generated_coverage(join(', ', @$formatted_parts));
987 my $update_method = "update_serial_${type}_summary";
988 return $editor->event unless $editor->$update_method($summary);
994 return {'num_items_received' => scalar @$items, 'new_unit_id' => $new_unit_id};
997 sub _find_or_create_call_number {
998 my ($e, $lib, $cn_string, $record) = @_;
1000 my $existing = $e->search_asset_call_number({
1001 "owning_lib" => $lib,
1002 "label" => $cn_string,
1003 "record" => $record,
1005 }) or return $e->die_event;
1008 return $existing->[0]->id;
1010 return $e->die_event unless
1011 $e->allowed("CREATE_VOLUME", $lib);
1013 my $acn = new Fieldmapper::asset::call_number;
1015 $acn->creator($e->requestor->id);
1016 $acn->editor($e->requestor->id);
1017 $acn->record($record);
1018 $acn->label($cn_string);
1019 $acn->owning_lib($lib);
1021 $e->create_asset_call_number($acn) or return $e->die_event;
1022 return $e->data->id;
1026 sub _issuances_received {
1027 my ($e, $sitem) = @_;
1029 my $results = $e->json_query({
1032 {"transform" => "distinct", "column" => "issuance"}
1035 "from" => {"sitem" => {"sstr" => {}, "siss" => {}}},
1037 "+sstr" => {"distribution" => $sitem->stream->distribution->id},
1038 "+siss" => {"holding_type" => $sitem->issuance->holding_type},
1039 "+sitem" => {"date_received" => {"!=" => undef}}
1041 }) or return $e->die_event;
1043 return [ map { $e->retrieve_serial_issuance($_->{"issuance"}) } @$results ];
1046 # XXX _prepare_unit_label() duplicates some code from unitize_items().
1047 # Hopefully we can unify code paths down the road.
1048 sub _prepare_unit_label {
1049 my ($e, $sunit, $sdist, $issuance) = @_;
1051 my ($mfhd, $formatted_parts) = _summarize_contents($e, [$issuance]);
1053 # special case for single formatted_part (may have summarized version)
1054 if (@$formatted_parts == 1) {
1055 #TODO: MFHD.pm should have a 'format_summary' method for this
1058 $sunit->detailed_contents(
1061 $sdist->unit_label_prefix,
1062 join(", ", @$formatted_parts),
1063 $sdist->unit_label_suffix
1067 # TODO: change this when real summary contents are available
1068 $sunit->summary_contents($sunit->detailed_contents);
1070 # Create sort_key by left padding numbers to 6 digits.
1071 (my $sort_key = $sunit->detailed_contents) =~
1072 s/(\d+)/sprintf '%06d', $1/eg;
1073 $sunit->sort_key($sort_key);
1076 # XXX duplicates a block of code from unitize_items(). Once I fully understand
1077 # what's going on and I'm sure it's working right, I'd like to have
1078 # unitize_items() just use this, keeping the logic in one place.
1079 sub _prepare_summaries {
1080 my ($e, $sitem, $issuances) = @_;
1082 my $dist_id = $sitem->stream->distribution->id;
1083 my $type = $sitem->issuance->holding_type;
1085 # Make sure @$issuances contains the new issuance from sitem.
1086 unless (grep { $_->id == $sitem->issuance->id } @$issuances) {
1087 push @$issuances, $sitem->issuance;
1090 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances);
1092 my $search_method = "search_serial_${type}_summary";
1093 my $summary = $e->$search_method([{"distribution" => $dist_id}]);
1095 my $cu_method = "update";
1098 $summary = $summary->[0];
1100 my $class = "Fieldmapper::serial::${type}_summary";
1101 $summary = $class->new;
1102 $summary->distribution($dist_id);
1103 $cu_method = "create";
1106 $summary->generated_coverage(join(", ", @$formatted_parts));
1107 my $method = "${cu_method}_serial_${type}_summary";
1108 return $e->die_event unless $e->$method($summary);
1111 __PACKAGE__->register_method(
1112 "method" => "receive_items_one_unit_per",
1113 "api_name" => "open-ils.serial.receive_items.one_unit_per",
1118 "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",
1122 "desc" => "authtoken",
1127 "desc" => "array of serial items, possibly fleshed with units and definitely fleshed with stream->distribution",
1132 "desc" => "id of bib record these items are associated with
1133 (XXX could/should be derived from items)",
1138 "desc" => "The item ID for each item successfully received",
1144 sub receive_items_one_unit_per {
1145 # XXX This function may be temporary, as it does some of what
1146 # unitize_items() does, just in a different way.
1147 my ($self, $client, $auth, $items, $record) = @_;
1149 my $e = new_editor("authtoken" => $auth, "xact" => 1);
1150 return $e->die_event unless $e->checkauth;
1152 my $user_id = $e->requestor->id;
1154 # Get a list of all the non-virtual field names in a serial::unit for
1155 # merging given unit objects with template-built units later.
1156 # XXX move this somewhere global so it isn't re-run all the time
1157 my $all_unit_fields =
1158 $Fieldmapper::fieldmap->{"Fieldmapper::serial::unit"}->{"fields"};
1159 my @real_unit_fields = grep {
1160 not $all_unit_fields->{$_}->{"virtual"}
1161 } keys %$all_unit_fields;
1163 foreach my $item (@$items) {
1164 # Note that we expect a certain fleshing on the items we're getting.
1165 my $sdist = $item->stream->distribution;
1167 # Create unit if given by user
1168 if (ref $item->unit) {
1169 # detach from the item, as we need to create separately
1170 my $user_unit = $item->unit;
1172 # get a unit based on associated template
1173 my $template_unit = _build_unit($e, $sdist, "receive", 1);
1174 if ($U->event_code($template_unit)) {
1176 $template_unit->{"note"} = "Item ID: " . $item->id;
1177 return $template_unit;
1180 # merge built unit with provided unit from user
1181 foreach (@real_unit_fields) {
1182 unless ($user_unit->$_) {
1183 $user_unit->$_($template_unit->$_);
1187 # Treat call number specially: the provided value from the
1188 # user will really be a string.
1189 if ($user_unit->call_number) {
1190 my $real_cn = _find_or_create_call_number(
1191 $e, $sdist->holding_lib->id,
1192 $user_unit->call_number, $record
1195 if ($U->event_code($real_cn)) {
1199 $user_unit->call_number($real_cn);
1203 my $evt = _prepare_unit_label(
1204 $e, $user_unit, $sdist, $item->issuance
1206 if ($U->event_code($evt)) {
1211 # fetch a list of issuances with received copies already existing
1212 # on this distribution.
1213 my $issuances = _issuances_received($e, $item); #XXX optimize later
1214 if ($U->event_code($issuances)) {
1219 # create/update summary objects related to this distribution
1220 $evt = _prepare_summaries($e, $item, $issuances);
1221 if ($U->event_code($evt)) {
1226 # set the incontrovertibles on the unit
1227 $user_unit->edit_date("now");
1228 $user_unit->create_date("now");
1229 $user_unit->editor($user_id);
1230 $user_unit->creator($user_id);
1232 return $e->die_event unless $e->create_serial_unit($user_unit);
1234 # save reference to new unit
1235 $item->unit($e->data->id);
1238 # Create notes if given by user
1239 if (ref($item->notes) and @{$item->notes}) {
1240 foreach my $note (@{$item->notes}) {
1241 $note->creator($user_id);
1242 $note->create_date("now");
1244 return $e->die_event unless $e->create_serial_item_note($note);
1247 $item->clear_notes; # They're saved; we no longer want them here.
1250 # Set the incontrovertibles on the item
1251 $item->status("Received");
1252 $item->date_received("now");
1253 $item->edit_date("now");
1254 $item->editor($user_id);
1256 return $e->die_event unless $e->update_serial_item($item);
1258 # send client a response
1259 $client->respond($item->id);
1262 $e->commit or return $e->die_event;
1270 my $skip_call_number = shift;
1272 my $attr = $mode . '_unit_template';
1273 my $template = $editor->retrieve_asset_copy_template($sdist->$attr) or
1274 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_COPY_TEMPLATE");
1276 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 );
1278 my $unit = new Fieldmapper::serial::unit;
1279 foreach my $part (@parts) {
1280 my $value = $template->$part;
1281 next if !defined($value);
1282 $unit->$part($value);
1285 # ignore circ_lib in template, set to distribution holding_lib
1286 $unit->circ_lib($sdist->holding_lib);
1287 $unit->creator($editor->requestor->id);
1288 $unit->editor($editor->requestor->id);
1290 unless ($skip_call_number) {
1291 $attr = $mode . '_call_number';
1292 my $cn = $sdist->$attr or
1293 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_CALL_NUMBER");
1295 $unit->call_number($cn);
1298 $unit->barcode('AUTO');
1299 $unit->sort_key('');
1300 $unit->summary_contents('');
1301 $unit->detailed_contents('');
1307 sub _summarize_contents {
1309 my $issuances = shift;
1311 # create MFHD record
1312 my $mfhd = MFHD->new(MARC::Record->new());
1315 my @scap_fields_ordered;
1318 foreach my $issuance (@$issuances) {
1319 my $scap_id = $issuance->caption_and_pattern;
1320 next if (!$scap_id); # skip issuances with no caption/pattern
1324 # if this is the first appearance of this scap, retrieve it and add it to the temporary record
1325 if (!exists $scaps{$issuance->caption_and_pattern}) {
1326 $scaps{$scap_id} = $editor->retrieve_serial_caption_and_pattern($scap_id);
1327 $scap = $scaps{$scap_id};
1328 $scap_field = _revive_caption($scap);
1329 $scap_fields{$scap_id} = $scap_field;
1330 push(@scap_fields_ordered, $scap_field);
1331 $scap_field->update('8' => $link_id);
1332 $mfhd->append_fields($scap_field);
1335 $scap = $scaps{$scap_id};
1336 $scap_field = $scap_fields{$scap_id};
1339 $mfhd->append_fields(_revive_holding($issuance->holding_code, $scap_field, $seqno));
1343 my @formatted_parts;
1344 foreach my $scap_field (@scap_fields_ordered) { #TODO: use generic MFHD "summarize" method, once available
1345 my @updated_holdings = $mfhd->get_compressed_holdings($scap_field);
1346 foreach my $holding (@updated_holdings) {
1347 push(@formatted_parts, $holding->format);
1351 return ($mfhd, \@formatted_parts);
1354 ##########################################################################
1357 __PACKAGE__->register_method(
1358 method => 'fetch_notes',
1359 api_name => 'open-ils.serial.item_note.retrieve.all',
1361 Returns an array of copy note objects.
1362 @param args A named hash of parameters including:
1363 authtoken : Required if viewing non-public notes
1364 item_id : The id of the item whose notes we want to retrieve
1365 pub : True if all the caller wants are public notes
1366 @return An array of note objects
1370 __PACKAGE__->register_method(
1371 method => 'fetch_notes',
1372 api_name => 'open-ils.serial.subscription_note.retrieve.all',
1374 Returns an array of copy note objects.
1375 @param args A named hash of parameters including:
1376 authtoken : Required if viewing non-public notes
1377 subscription_id : The id of the item whose notes we want to retrieve
1378 pub : True if all the caller wants are public notes
1379 @return An array of note objects
1383 __PACKAGE__->register_method(
1384 method => 'fetch_notes',
1385 api_name => 'open-ils.serial.distribution_note.retrieve.all',
1387 Returns an array of copy note objects.
1388 @param args A named hash of parameters including:
1389 authtoken : Required if viewing non-public notes
1390 distribution_id : The id of the item whose notes we want to retrieve
1391 pub : True if all the caller wants are public notes
1392 @return An array of note objects
1396 # TODO: revisit this method to consider replacing cstore direct calls
1398 my( $self, $connection, $args ) = @_;
1400 $self->api_name =~ /serial\.(\w*)_note/;
1403 my $id = $$args{object_id};
1404 my $authtoken = $$args{authtoken};
1408 return $U->cstorereq(
1409 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic',
1410 { $type => $id, pub => 't' } );
1412 # FIXME: restore perm check
1413 # ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
1414 # return $evt if $evt;
1415 return $U->cstorereq(
1416 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic', {$type => $id} );
1422 __PACKAGE__->register_method(
1423 method => 'create_note',
1424 api_name => 'open-ils.serial.item_note.create',
1426 Creates a new item note
1427 @param authtoken The login session key
1428 @param note The note object to create
1429 @return The id of the new note object
1433 __PACKAGE__->register_method(
1434 method => 'create_note',
1435 api_name => 'open-ils.serial.subscription_note.create',
1437 Creates a new subscription note
1438 @param authtoken The login session key
1439 @param note The note object to create
1440 @return The id of the new note object
1444 __PACKAGE__->register_method(
1445 method => 'create_note',
1446 api_name => 'open-ils.serial.distribution_note.create',
1448 Creates a new distribution note
1449 @param authtoken The login session key
1450 @param note The note object to create
1451 @return The id of the new note object
1456 my( $self, $connection, $authtoken, $note ) = @_;
1458 $self->api_name =~ /serial\.(\w*)_note/;
1461 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1462 return $e->event unless $e->checkauth;
1464 # FIXME: restore permission support
1465 # my $item = $e->retrieve_serial_item(
1471 # return $e->event unless
1472 # $e->allowed('CREATE_COPY_NOTE', $item->call_number->owning_lib);
1474 $note->create_date('now');
1475 $note->creator($e->requestor->id);
1476 $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
1479 my $method = "create_serial_${type}_note";
1480 $e->$method($note) or return $e->event;
1485 __PACKAGE__->register_method(
1486 method => 'delete_note',
1487 api_name => 'open-ils.serial.item_note.delete',
1489 Deletes an existing item note
1490 @param authtoken The login session key
1491 @param noteid The id of the note to delete
1492 @return 1 on success - Event otherwise.
1496 __PACKAGE__->register_method(
1497 method => 'delete_note',
1498 api_name => 'open-ils.serial.subscription_note.delete',
1500 Deletes an existing subscription note
1501 @param authtoken The login session key
1502 @param noteid The id of the note to delete
1503 @return 1 on success - Event otherwise.
1507 __PACKAGE__->register_method(
1508 method => 'delete_note',
1509 api_name => 'open-ils.serial.distribution_note.delete',
1511 Deletes an existing distribution note
1512 @param authtoken The login session key
1513 @param noteid The id of the note to delete
1514 @return 1 on success - Event otherwise.
1519 my( $self, $conn, $authtoken, $noteid ) = @_;
1521 $self->api_name =~ /serial\.(\w*)_note/;
1524 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1525 return $e->die_event unless $e->checkauth;
1527 my $method = "retrieve_serial_${type}_note";
1528 my $note = $e->$method([
1530 ]) or return $e->die_event;
1532 # FIXME: restore permissions check
1533 # if( $note->creator ne $e->requestor->id ) {
1534 # return $e->die_event unless
1535 # $e->allowed('DELETE_COPY_NOTE', $note->item->call_number->owning_lib);
1538 $method = "delete_serial_${type}_note";
1539 $e->$method($note) or return $e->die_event;
1545 ##########################################################################
1546 # subscription methods
1548 __PACKAGE__->register_method(
1549 method => 'fleshed_ssub_alter',
1550 api_name => 'open-ils.serial.subscription.fleshed.batch.update',
1554 desc => 'Receives an array of one or more subscriptions and updates the database as needed',
1556 name => 'authtoken',
1557 desc => 'Authtoken for current user session',
1561 name => 'subscriptions',
1562 desc => 'Array of fleshed subscriptions',
1568 desc => 'Returns 1 if successful, event if failed',
1574 sub fleshed_ssub_alter {
1575 my( $self, $conn, $auth, $ssubs ) = @_;
1576 return 1 unless ref $ssubs;
1577 my( $reqr, $evt ) = $U->checkses($auth);
1578 return $evt if $evt;
1579 my $editor = new_editor(requestor => $reqr, xact => 1);
1580 my $override = $self->api_name =~ /override/;
1582 # TODO: permission check
1583 # return $editor->event unless
1584 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
1586 for my $ssub (@$ssubs) {
1588 my $ssubid = $ssub->id;
1590 if( $ssub->isdeleted ) {
1591 $evt = _delete_ssub( $editor, $override, $ssub);
1592 } elsif( $ssub->isnew ) {
1593 _cleanse_dates($ssub, ['start_date','end_date']);
1594 $evt = _create_ssub( $editor, $ssub );
1596 _cleanse_dates($ssub, ['start_date','end_date']);
1597 $evt = _update_ssub( $editor, $override, $ssub );
1602 $logger->info("fleshed subscription-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
1606 $logger->debug("subscription-alter: done updating subscription batch");
1608 $logger->info("fleshed subscription-alter successfully updated ".scalar(@$ssubs)." subscriptions");
1613 my ($editor, $override, $ssub) = @_;
1614 $logger->info("subscription-alter: delete subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1615 my $sdists = $editor->search_serial_distribution(
1616 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1617 my $cps = $editor->search_serial_caption_and_pattern(
1618 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1619 my $sisses = $editor->search_serial_issuance(
1620 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
1621 return OpenILS::Event->new(
1622 'SERIAL_SUBSCRIPTION_NOT_EMPTY', payload => $ssub->id ) if (@$sdists or @$cps or @$sisses);
1624 return $editor->event unless $editor->delete_serial_subscription($ssub);
1629 my ($editor, $ssub) = @_;
1631 $logger->info("subscription-alter: new subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1632 return $editor->event unless $editor->create_serial_subscription($ssub);
1637 my ($editor, $override, $ssub) = @_;
1639 $logger->info("subscription-alter: retrieving subscription ".$ssub->id);
1640 my $orig_ssub = $editor->retrieve_serial_subscription($ssub->id);
1642 $logger->info("subscription-alter: original subscription ".OpenSRF::Utils::JSON->perl2JSON($orig_ssub));
1643 $logger->info("subscription-alter: updated subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
1644 return $editor->event unless $editor->update_serial_subscription($ssub);
1648 __PACKAGE__->register_method(
1649 method => "fleshed_serial_subscription_retrieve_batch",
1651 api_name => "open-ils.serial.subscription.fleshed.batch.retrieve"
1654 sub fleshed_serial_subscription_retrieve_batch {
1655 my( $self, $client, $ids ) = @_;
1656 # FIXME: permissions?
1657 $logger->info("Fetching fleshed subscriptions @$ids");
1658 return $U->cstorereq(
1659 "open-ils.cstore.direct.serial.subscription.search.atomic",
1662 flesh_fields => {ssub => [ qw/owning_lib notes/ ]}
1666 __PACKAGE__->register_method(
1667 method => "retrieve_sub_tree",
1669 api_name => "open-ils.serial.subscription_tree.retrieve"
1672 __PACKAGE__->register_method(
1673 method => "retrieve_sub_tree",
1674 api_name => "open-ils.serial.subscription_tree.global.retrieve"
1677 sub retrieve_sub_tree {
1679 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
1681 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
1685 # TODO: permission support
1686 if(!@org_ids and $user_session) {
1688 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
1689 @org_ids = ($user_obj->home_ou);
1692 if( $self->api_name =~ /global/ ) {
1693 return _build_subs_list( { record_entry => $docid } ); # TODO: filter for !deleted, or active?
1698 for my $orgid (@org_ids) {
1699 my $subs = _build_subs_list(
1700 { record_entry => $docid, owning_lib => $orgid } );# TODO: filter for !deleted, or active?
1701 push( @all_subs, @$subs );
1710 sub _build_subs_list {
1711 my $search_hash = shift;
1713 #$search_hash->{deleted} = 'f';
1714 my $e = new_editor();
1716 my $subs = $e->search_serial_subscription([$search_hash, { 'order_by' => {'ssub' => 'id'} }]);
1720 for my $sub (@$subs) {
1722 # TODO: filter on !deleted?
1723 my $dists = $e->search_serial_distribution(
1724 [{ subscription => $sub->id }, { 'order_by' => {'sdist' => 'label'} }]
1727 #$dists = [ sort { $a->label cmp $b->label } @$dists ];
1729 $sub->distributions($dists);
1731 # TODO: filter on !deleted?
1732 my $issuances = $e->search_serial_issuance(
1733 [{ subscription => $sub->id }, { 'order_by' => {'siss' => 'label'} }]
1736 #$issuances = [ sort { $a->label cmp $b->label } @$issuances ];
1737 $sub->issuances($issuances);
1739 # TODO: filter on !deleted?
1740 my $scaps = $e->search_serial_caption_and_pattern(
1741 [{ subscription => $sub->id }, { 'order_by' => {'scap' => 'id'} }]
1744 #$scaps = [ sort { $a->id cmp $b->id } @$scaps ];
1745 $sub->scaps($scaps);
1746 push( @built_subs, $sub );
1749 return \@built_subs;
1753 __PACKAGE__->register_method(
1754 method => "subscription_orgs_for_title",
1756 api_name => "open-ils.serial.subscription.retrieve_orgs_by_title"
1759 sub subscription_orgs_for_title {
1760 my( $self, $client, $record_id ) = @_;
1762 my $subs = $U->simple_scalar_request(
1764 "open-ils.cstore.direct.serial.subscription.search.atomic",
1765 { record_entry => $record_id }); # TODO: filter on !deleted?
1767 my $orgs = { map {$_->owning_lib => 1 } @$subs };
1768 return [ keys %$orgs ];
1772 ##########################################################################
1773 # distribution methods
1775 __PACKAGE__->register_method(
1776 method => 'fleshed_sdist_alter',
1777 api_name => 'open-ils.serial.distribution.fleshed.batch.update',
1781 desc => 'Receives an array of one or more distributions and updates the database as needed',
1783 name => 'authtoken',
1784 desc => 'Authtoken for current user session',
1788 name => 'distributions',
1789 desc => 'Array of fleshed distributions',
1795 desc => 'Returns 1 if successful, event if failed',
1801 sub fleshed_sdist_alter {
1802 my( $self, $conn, $auth, $sdists ) = @_;
1803 return 1 unless ref $sdists;
1804 my( $reqr, $evt ) = $U->checkses($auth);
1805 return $evt if $evt;
1806 my $editor = new_editor(requestor => $reqr, xact => 1);
1807 my $override = $self->api_name =~ /override/;
1809 # TODO: permission check
1810 # return $editor->event unless
1811 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
1813 for my $sdist (@$sdists) {
1814 my $sdistid = $sdist->id;
1816 if( $sdist->isdeleted ) {
1817 $evt = _delete_sdist( $editor, $override, $sdist);
1818 } elsif( $sdist->isnew ) {
1819 $evt = _create_sdist( $editor, $sdist );
1821 $evt = _update_sdist( $editor, $override, $sdist );
1826 $logger->info("fleshed distribution-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
1830 $logger->debug("distribution-alter: done updating distribution batch");
1832 $logger->info("fleshed distribution-alter successfully updated ".scalar(@$sdists)." distributions");
1837 my ($editor, $override, $sdist) = @_;
1838 $logger->info("distribution-alter: delete distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
1839 return $editor->event unless $editor->delete_serial_distribution($sdist);
1844 my ($editor, $sdist) = @_;
1846 $logger->info("distribution-alter: new distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
1847 return $editor->event unless $editor->create_serial_distribution($sdist);
1849 # create summaries too
1850 my $summary = new Fieldmapper::serial::basic_summary;
1851 $summary->distribution($sdist->id);
1852 $summary->generated_coverage('');
1853 return $editor->event unless $editor->create_serial_basic_summary($summary);
1854 $summary = new Fieldmapper::serial::supplement_summary;
1855 $summary->distribution($sdist->id);
1856 $summary->generated_coverage('');
1857 return $editor->event unless $editor->create_serial_supplement_summary($summary);
1858 $summary = new Fieldmapper::serial::index_summary;
1859 $summary->distribution($sdist->id);
1860 $summary->generated_coverage('');
1861 return $editor->event unless $editor->create_serial_index_summary($summary);
1863 # create a starter stream (TODO: reconsider this)
1864 my $stream = new Fieldmapper::serial::stream;
1865 $stream->distribution($sdist->id);
1866 return $editor->event unless $editor->create_serial_stream($stream);
1872 my ($editor, $override, $sdist) = @_;
1874 $logger->info("distribution-alter: retrieving distribution ".$sdist->id);
1875 my $orig_sdist = $editor->retrieve_serial_distribution($sdist->id);
1877 $logger->info("distribution-alter: original distribution ".OpenSRF::Utils::JSON->perl2JSON($orig_sdist));
1878 $logger->info("distribution-alter: updated distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
1879 return $editor->event unless $editor->update_serial_distribution($sdist);
1883 __PACKAGE__->register_method(
1884 method => "fleshed_serial_distribution_retrieve_batch",
1886 api_name => "open-ils.serial.distribution.fleshed.batch.retrieve"
1889 sub fleshed_serial_distribution_retrieve_batch {
1890 my( $self, $client, $ids ) = @_;
1891 # FIXME: permissions?
1892 $logger->info("Fetching fleshed distributions @$ids");
1893 return $U->cstorereq(
1894 "open-ils.cstore.direct.serial.distribution.search.atomic",
1897 flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams / ]}
1901 ##########################################################################
1902 # caption and pattern methods
1904 __PACKAGE__->register_method(
1905 method => 'scap_alter',
1906 api_name => 'open-ils.serial.caption_and_pattern.batch.update',
1910 desc => 'Receives an array of one or more caption and patterns and updates the database as needed',
1912 name => 'authtoken',
1913 desc => 'Authtoken for current user session',
1918 desc => 'Array of caption and patterns',
1924 desc => 'Returns 1 if successful, event if failed',
1931 my( $self, $conn, $auth, $scaps ) = @_;
1932 return 1 unless ref $scaps;
1933 my( $reqr, $evt ) = $U->checkses($auth);
1934 return $evt if $evt;
1935 my $editor = new_editor(requestor => $reqr, xact => 1);
1936 my $override = $self->api_name =~ /override/;
1938 # TODO: permission check
1939 # return $editor->event unless
1940 # $editor->allowed('UPDATE_COPY', $class->copy_perm_org($vol, $copy));
1942 for my $scap (@$scaps) {
1943 my $scapid = $scap->id;
1945 if( $scap->isdeleted ) {
1946 $evt = _delete_scap( $editor, $override, $scap);
1947 } elsif( $scap->isnew ) {
1948 $evt = _create_scap( $editor, $scap );
1950 $evt = _update_scap( $editor, $override, $scap );
1955 $logger->info("caption_and_pattern-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
1959 $logger->debug("caption_and_pattern-alter: done updating caption_and_pattern batch");
1961 $logger->info("caption_and_pattern-alter successfully updated ".scalar(@$scaps)." caption_and_patterns");
1966 my ($editor, $override, $scap) = @_;
1967 $logger->info("caption_and_pattern-alter: delete caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
1968 my $sisses = $editor->search_serial_issuance(
1969 { caption_and_pattern => $scap->id }, { limit => 1 } ); #TODO: 'deleted' support?
1970 return OpenILS::Event->new(
1971 'SERIAL_CAPTION_AND_PATTERN_HAS_ISSUANCES', payload => $scap->id ) if (@$sisses);
1973 return $editor->event unless $editor->delete_serial_caption_and_pattern($scap);
1978 my ($editor, $scap) = @_;
1980 $logger->info("caption_and_pattern-alter: new caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
1981 return $editor->event unless $editor->create_serial_caption_and_pattern($scap);
1986 my ($editor, $override, $scap) = @_;
1988 $logger->info("caption_and_pattern-alter: retrieving caption_and_pattern ".$scap->id);
1989 my $orig_scap = $editor->retrieve_serial_caption_and_pattern($scap->id);
1991 $logger->info("caption_and_pattern-alter: original caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($orig_scap));
1992 $logger->info("caption_and_pattern-alter: updated caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
1993 return $editor->event unless $editor->update_serial_caption_and_pattern($scap);
1997 __PACKAGE__->register_method(
1998 method => "serial_caption_and_pattern_retrieve_batch",
2000 api_name => "open-ils.serial.caption_and_pattern.batch.retrieve"
2003 sub serial_caption_and_pattern_retrieve_batch {
2004 my( $self, $client, $ids ) = @_;
2005 $logger->info("Fetching caption_and_patterns @$ids");
2006 return $U->cstorereq(
2007 "open-ils.cstore.direct.serial.caption_and_pattern.search.atomic",
2012 __PACKAGE__->register_method(
2013 "method" => "bre_by_identifier",
2014 "api_name" => "open-ils.serial.biblio.record_entry.by_identifier",
2017 "desc" => "Find instances of biblio.record_entry given a search token" .
2018 " that could be a value for any identifier defined in " .
2019 "config.metabib_field",
2021 {"desc" => "Search token", "type" => "string"},
2022 {"desc" => "Options: require_subscriptions, add_mvr, is_actual_id" .
2023 " (all boolean)", "type" => "object"}
2026 "desc" => "Any matching BREs, or if the add_mvr option is true, " .
2027 "objects with a 'bre' key/value pair, and an 'mvr' " .
2028 "key-value pair. BREs have subscriptions fleshed on.",
2034 sub bre_by_identifier {
2035 my ($self, $client, $term, $options) = @_;
2037 return new OpenILS::Event("BAD_PARAMS") unless $term;
2040 my $e = new_editor();
2044 if ($options->{"is_actual_id"}) {
2048 $e->search_config_metabib_field({"field_class" => "identifier"})
2049 or return $e->die_event;
2051 my @identifiers = map { $_->name } @$cmf;
2052 my $query = join(" || ", map { "id|$_: $term" } @identifiers);
2054 my $search = create OpenSRF::AppSession("open-ils.search");
2055 my $search_result = $search->request(
2056 "open-ils.search.biblio.multiclass.query.staff", {}, $query
2058 $search->disconnect;
2060 # Un-nest results. They tend to look like [[1],[2],[3]] for some reason.
2061 @ids = map { @{$_} } @{$search_result->{"ids"}};
2069 my $bre = $e->search_biblio_record_entry([
2071 "flesh" => 2, "flesh_fields" => {
2072 "bre" => ["subscriptions"],
2073 "ssub" => ["owning_lib"]
2076 ]) or return $e->die_event;
2078 if (@$bre && $options->{"require_subscriptions"}) {
2079 $bre = [ grep { @{$_->subscriptions} } @$bre ];
2084 if (@$bre) { # re-evaluate after possible grep
2085 if ($options->{"add_mvr"}) {
2087 {"bre" => $_, "mvr" => _get_mvr($_->id)}
2090 $client->respond($_) foreach (@$bre);
2097 __PACKAGE__->register_method(
2098 "method" => "get_receivable_items",
2099 "api_name" => "open-ils.serial.items.receivable.by_subscription",
2102 "desc" => "Return all receivable items under a given subscription",
2104 {"desc" => "Authtoken", "type" => "string"},
2105 {"desc" => "Subscription ID", "type" => "number"},
2108 "desc" => "All receivable items under a given subscription",
2114 __PACKAGE__->register_method(
2115 "method" => "get_receivable_items",
2116 "api_name" => "open-ils.serial.items.receivable.by_issuance",
2119 "desc" => "Return all receivable items under a given issuance",
2121 {"desc" => "Authtoken", "type" => "string"},
2122 {"desc" => "Issuance ID", "type" => "number"},
2125 "desc" => "All receivable items under a given issuance",
2131 sub get_receivable_items {
2132 my ($self, $client, $auth, $term) = @_;
2134 my $e = new_editor("authtoken" => $auth);
2135 return $e->die_event unless $e->checkauth;
2139 my $by = ($self->api_name =~ /by_(\w+)$/)[0];
2142 "issuance" => {"issuance" => $term},
2143 "subscription" => {"+siss" => {"subscription" => $term}}
2146 my $item_ids = $e->json_query(
2148 "select" => {"sitem" => ["id"]},
2149 "from" => {"sitem" => "siss"},
2151 %{$where{$by}}, "date_received" => undef
2153 "order_by" => {"sitem" => ["id"]}
2155 ) or return $e->die_event;
2157 return undef unless @$item_ids;
2159 foreach (map { $_->{"id"} } @$item_ids) {
2161 $e->retrieve_serial_item([
2165 "sitem" => ["stream", "issuance"],
2166 "sstr" => ["distribution"],
2167 "sdist" => ["holding_lib"]
2178 __PACKAGE__->register_method(
2179 "method" => "get_receivable_issuances",
2180 "api_name" => "open-ils.serial.issuances.receivable",
2183 "desc" => "Return all issuances with receivable items given " .
2184 "a subscription ID",
2186 {"desc" => "Authtoken", "type" => "string"},
2187 {"desc" => "Subscription ID", "type" => "number"},
2190 "desc" => "All issuances with receivable items " .
2191 "(but not the items themselves)", "type" => "object"
2196 sub get_receivable_issuances {
2197 my ($self, $client, $auth, $sub_id) = @_;
2199 my $e = new_editor("authtoken" => $auth);
2200 return $e->die_event unless $e->checkauth;
2204 my $issuance_ids = $e->json_query({
2207 {"transform" => "distinct", "column" => "id"},
2211 "from" => {"siss" => "sitem"},
2213 "subscription" => $sub_id,
2214 "+sitem" => {"date_received" => undef}
2217 "siss" => {"date_published" => {"direction" => "asc"}}
2220 }) or return $e->die_event;
2222 $client->respond($e->retrieve_serial_issuance($_->{"id"}))
2223 foreach (@$issuance_ids);