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 DateTime::Format::ISO8601;
52 use MARC::File::XML (BinaryEncoding => 'utf8');
53 my $U = 'OpenILS::Application::AppUtils';
54 my @MFHD_NAMES = ('basic','supplement','index');
55 my %MFHD_NAMES_BY_TAG = ( '853' => $MFHD_NAMES[0],
56 '863' => $MFHD_NAMES[0],
57 '854' => $MFHD_NAMES[1],
58 '864' => $MFHD_NAMES[1],
59 '855' => $MFHD_NAMES[2],
60 '865' => $MFHD_NAMES[2] );
61 my %MFHD_TAGS_BY_NAME = ( $MFHD_NAMES[0] => '853',
62 $MFHD_NAMES[1] => '854',
63 $MFHD_NAMES[2] => '855');
64 my $_strp_date = new DateTime::Format::Strptime(pattern => '%F');
66 # helper method for conforming dates to ISO8601
71 foreach my $field (@$fields) {
72 $item->$field(OpenSRF::Utils::clense_ISO8601($item->$field)) if $item->$field;
80 "open-ils.search.biblio.record.mods_slim.retrieve",
86 ##########################################################################
89 __PACKAGE__->register_method(
90 method => "create_item_safely",
91 api_name => "open-ils.serial.item.create",
96 desc => q/Creates any number of items, respecting only a few of the
97 submitted fields, as the user shouldn't be able to freely set certain
100 {name=> "authtoken", desc => "Authtoken for current user session",
102 {name => "item", desc => "serial item",
103 type => "object", class => "sitem"},
105 desc => "optional: how many items to make " .
106 "(default 1; 1-100 permitted)",
110 desc => "created items (a stream of them)",
111 type => "object", class => "sitem"
115 __PACKAGE__->register_method(
116 method => "update_item_safely",
117 api_name => "open-ils.serial.item.update",
122 desc => q/Edit a serial item, respecting only a few of the
123 submitted fields, as the user shouldn't be able to freely set certain
126 {name=> "authtoken", desc => "Authtoken for current user session",
128 {name => "item", desc => "serial item",
129 type => "object", class => "sitem"},
132 desc => "created item", type => "object", class => "sitem"
137 sub _set_safe_item_fields {
140 my $requestor_id = shift;
141 # extra fields remain in @_
143 $dest->edit_date("now");
144 $dest->editor($requestor_id);
146 my @fields = qw/date_expected date_received status/;
148 for my $field (@fields, @_) {
149 $dest->$field($source->$field);
153 sub update_item_safely {
154 my ($self, $client, $auth, $item) = @_;
156 my $e = new_editor("xact" => 1, "authtoken" => $auth);
157 $e->checkauth or return $e->die_event;
159 my $orig = $e->retrieve_serial_item([
161 "flesh" => 2, "flesh_fields" => {
162 "sitem" => ["stream"], "sstr" => ["distribution"]
165 ]) or return $e->die_event;
167 return $e->die_event unless $e->allowed(
168 "ADMIN_SERIAL_ITEM", $orig->stream->distribution->holding_lib
171 _set_safe_item_fields($orig, $item, $e->requestor->id);
172 $e->update_serial_item($orig) or return $e->die_event;
174 $client->respond($e->retrieve_serial_item($item->id));
175 $e->commit or return $e->die_event;
179 sub create_item_safely {
180 my ($self, $client, $auth, $item, $count) = @_;
184 return new OpenILS::Event(
185 "BAD_PARAMS", note => "Count should be from 1 to 100"
186 ) unless $count >= 1 and $count <= 100;
188 my $e = new_editor("xact" => 1, "authtoken" => $auth);
189 $e->checkauth or return $e->die_event;
191 my $stream = $e->retrieve_serial_stream([
193 "flesh" => 1, "flesh_fields" => {"sstr" => ["distribution"]}
195 ]) or return $e->die_event;
197 return $e->die_event unless $e->allowed(
198 "ADMIN_SERIAL_ITEM", $stream->distribution->holding_lib
201 for (my $i = 0; $i < $count; $i++) {
202 my $actual = new Fieldmapper::serial::item;
203 $actual->creator($e->requestor->id);
204 _set_safe_item_fields(
205 $actual, $item, $e->requestor->id, "issuance", "stream"
208 $e->create_serial_item($actual) or return $e->die_event;
209 $client->respond($e->data);
212 $e->commit or return $e->die_event;
216 __PACKAGE__->register_method(
217 method => 'fleshed_item_alter',
218 api_name => 'open-ils.serial.item.fleshed.batch.update',
222 desc => 'Receives an array of one or more items and updates the database as needed',
225 desc => 'Authtoken for current user session',
230 desc => 'Array of fleshed items',
236 desc => 'Returns 1 if successful, event if failed',
242 sub fleshed_item_alter {
243 my( $self, $conn, $auth, $items ) = @_;
244 return 1 unless ref $items;
245 my( $reqr, $evt ) = $U->checkses($auth);
247 my $editor = new_editor(requestor => $reqr, xact => 1);
248 my $override = $self->api_name =~ /override/;
252 for my $item (@$items) {
253 my $sstr_id = ref $item->stream ? $item->stream->id : $item->stream;
254 if (!exists($found_sstr_ids{$sstr_id})) {
256 if (ref $item->stream) {
257 $sstr = $item->stream;
259 $sstr = $editor->retrieve_serial_stream($item->stream) or return $editor->die_event;
261 if (!exists($found_sdist_ids{$sstr->distribution})) {
262 my $sdist = $editor->retrieve_serial_distribution($sstr->distribution) or return $editor->die_event;
263 return $editor->die_event unless
264 $editor->allowed("ADMIN_SERIAL_STREAM", $sdist->holding_lib);
265 $found_sdist_ids{$sstr->distribution} = 1;
267 $found_sstr_ids{$sstr_id} = 1;
270 $item->editor($editor->requestor->id);
271 $item->edit_date('now');
273 if( $item->isdeleted ) {
274 $evt = _delete_sitem( $editor, $override, $item);
275 } elsif( $item->isnew ) {
276 # TODO: reconsider this
277 # if the item has a new issuance, create the issuance first
278 if (ref $item->issuance eq 'Fieldmapper::serial::issuance' and $item->issuance->isnew) {
279 fleshed_issuance_alter($self, $conn, $auth, [$item->issuance]);
281 _cleanse_dates($item, ['date_expected','date_received']);
282 $evt = _create_sitem( $editor, $item );
284 _cleanse_dates($item, ['date_expected','date_received']);
285 $evt = _update_sitem( $editor, $override, $item );
290 $logger->info("fleshed item-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
294 $logger->debug("item-alter: done updating item batch");
296 $logger->info("fleshed item-alter successfully updated ".scalar(@$items)." items");
301 my ($editor, $override, $item) = @_;
302 $logger->info("item-alter: delete item ".OpenSRF::Utils::JSON->perl2JSON($item));
303 return $editor->event unless $editor->delete_serial_item($item);
308 my ($editor, $item) = @_;
310 $item->creator($editor->requestor->id);
311 $item->create_date('now');
313 $logger->info("item-alter: new item ".OpenSRF::Utils::JSON->perl2JSON($item));
314 return $editor->event unless $editor->create_serial_item($item);
319 my ($editor, $override, $item) = @_;
321 $logger->info("item-alter: retrieving item ".$item->id);
322 my $orig_item = $editor->retrieve_serial_item($item->id);
324 $logger->info("item-alter: original item ".OpenSRF::Utils::JSON->perl2JSON($orig_item));
325 $logger->info("item-alter: updated item ".OpenSRF::Utils::JSON->perl2JSON($item));
326 return $editor->event unless $editor->update_serial_item($item);
330 __PACKAGE__->register_method(
331 method => "fleshed_serial_item_retrieve_batch",
333 api_name => "open-ils.serial.item.fleshed.batch.retrieve"
336 sub fleshed_serial_item_retrieve_batch {
337 my( $self, $client, $ids ) = @_;
338 # FIXME: permissions?
339 $logger->info("Fetching fleshed serial items @$ids");
340 return $U->cstorereq(
341 "open-ils.cstore.direct.serial.item.search.atomic",
344 flesh_fields => {sitem => [ qw/issuance creator editor stream unit notes/ ], sstr => ["distribution"], sunit => ["call_number"], siss => [qw/creator editor subscription/]}
349 ##########################################################################
352 __PACKAGE__->register_method(
353 method => 'fleshed_issuance_alter',
354 api_name => 'open-ils.serial.issuance.fleshed.batch.update',
358 desc => 'Receives an array of one or more issuances and updates the database as needed',
361 desc => 'Authtoken for current user session',
366 desc => 'Array of fleshed issuances',
372 desc => 'Returns 1 if successful, event if failed',
378 sub fleshed_issuance_alter {
379 my( $self, $conn, $auth, $issuances ) = @_;
380 return 1 unless ref $issuances;
381 my( $reqr, $evt ) = $U->checkses($auth);
383 my $editor = new_editor(requestor => $reqr, xact => 1);
384 my $override = $self->api_name =~ /override/;
387 for my $issuance (@$issuances) {
388 my $ssub_id = ref $issuance->subscription ? $issuance->subscription->id : $issuance->subscription;
389 if (!exists($found_ssub_ids{$ssub_id})) {
391 if (ref $issuance->subscription) {
392 $owning_lib_id = $issuance->subscription->owning_lib;
394 my $ssub = $editor->retrieve_serial_subscription($issuance->subscription) or return $editor->die_event;
395 $owning_lib_id = $ssub->owning_lib;
397 return $editor->die_event unless
398 $editor->allowed("ADMIN_SERIAL_SUBSCRIPTION", $owning_lib_id);
399 $found_ssub_ids{$ssub_id} = 1;
402 my $issuanceid = $issuance->id;
403 $issuance->editor($editor->requestor->id);
404 $issuance->edit_date('now');
406 if( $issuance->isdeleted ) {
407 $evt = _delete_siss( $editor, $override, $issuance);
408 } elsif( $issuance->isnew ) {
409 _cleanse_dates($issuance, ['date_published']);
410 $evt = _create_siss( $editor, $issuance );
412 _cleanse_dates($issuance, ['date_published']);
413 $evt = _update_siss( $editor, $override, $issuance );
418 $logger->info("fleshed issuance-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
422 $logger->debug("issuance-alter: done updating issuance batch");
424 $logger->info("fleshed issuance-alter successfully updated ".scalar(@$issuances)." issuances");
429 my ($editor, $override, $issuance) = @_;
430 $logger->info("issuance-alter: delete issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
431 return $editor->event unless $editor->delete_serial_issuance($issuance);
436 my ($editor, $issuance) = @_;
438 $issuance->creator($editor->requestor->id);
439 $issuance->create_date('now');
441 $logger->info("issuance-alter: new issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
442 return $editor->event unless $editor->create_serial_issuance($issuance);
447 my ($editor, $override, $issuance) = @_;
449 $logger->info("issuance-alter: retrieving issuance ".$issuance->id);
450 my $orig_issuance = $editor->retrieve_serial_issuance($issuance->id);
452 $logger->info("issuance-alter: original issuance ".OpenSRF::Utils::JSON->perl2JSON($orig_issuance));
453 $logger->info("issuance-alter: updated issuance ".OpenSRF::Utils::JSON->perl2JSON($issuance));
454 return $editor->event unless $editor->update_serial_issuance($issuance);
458 __PACKAGE__->register_method(
459 method => "fleshed_serial_issuance_retrieve_batch",
461 api_name => "open-ils.serial.issuance.fleshed.batch.retrieve"
464 sub fleshed_serial_issuance_retrieve_batch {
465 my( $self, $client, $ids ) = @_;
466 # FIXME: permissions?
467 $logger->info("Fetching fleshed serial issuances @$ids");
468 return $U->cstorereq(
469 "open-ils.cstore.direct.serial.issuance.search.atomic",
472 flesh_fields => {siss => [ qw/creator editor subscription/ ]}
476 __PACKAGE__->register_method(
477 method => "pub_fleshed_serial_issuance_retrieve_batch",
478 api_name => "open-ils.serial.issuance.pub_fleshed.batch.retrieve",
481 Public (i.e. OPAC) call for getting at the sub and
482 ultimately the record entry from an issuance
484 params => [{name => 'ids', desc => 'Array of IDs', type => 'array'}],
487 issuance objects, fleshed with subscriptions
493 sub pub_fleshed_serial_issuance_retrieve_batch {
494 my( $self, $client, $ids ) = @_;
495 return [] unless $ids and @$ids;
496 return new_editor()->search_serial_issuance([
500 flesh_fields => {siss => [ qw/subscription/ ]}
505 sub received_siss_by_bib {
510 my $args = shift || {};
511 $$args{order} ||= 'asc';
513 my $global = $$args{global} == 0 ? 0 : 1;
515 my $e = new_editor();
516 my $issuances = $e->json_query({
519 $global ? { transform => "min", column => "id", aggregate => 1 } : "id",
524 # We're not really interested in the minimum here. This is
525 # just a way to distinguish issuances whose items have units
526 # from issuances whose items have no units, without altogether
527 # excluding the latter type of issuances.
528 {"transform" => "min", "alias" => "has_units",
529 "column" => "unit", "aggregate" => 1}
535 field => 'subscription',
541 $$args{ou} ? ( join => {
548 fkey => 'distribution'
559 '+ssub' => { record_entry => $bib },
560 $$args{type} ? ( '+siss' => { 'holding_type' => $$args{type} } ) : (),
562 # XXX should we also take specific item statuses into account?
563 date_received => { '!=' => undef },
564 $$args{status} ? ( 'status' => $$args{status} ) : ()
566 $$args{ou} ? ( '+sdist' => {
568 'in' => $U->get_org_descendants($$args{ou}, $$args{depth})
572 $$args{limit} ? ( limit => $$args{limit} ) : (),
573 $$args{offset} ? ( offset => $$args{offset} ) : (),
574 order_by => [{ class => 'siss', field => 'date_published', direction => $$args{order} }],
579 "issuance" => $e->retrieve_serial_issuance($_->{"id"}),
580 "has_units" => $_->{"has_units"} ? 1 : 0
585 __PACKAGE__->register_method(
586 method => 'received_siss_by_bib',
587 api_name => 'open-ils.serial.received_siss.retrieve.by_bib',
592 desc => 'Receives a Bib ID and other optional params and returns "siss" (issuance) objects',
595 desc => 'id of the bre to which the issuances belong',
600 q/A hash of optional arguments. Valid keys and their meanings:
601 global := If true, return only one representative version of a conceptual issuance regardless of the number of subscriptions, otherwise return all issuance objects meeting the requested criteria, including conceptual duplicates. Valid values are 0 (false) and 1 (true, default).
602 order := date_published sort direction, either "asc" (chronological, default) or "desc" (reverse chronological)
603 limit := Number of issuances to return. Useful for paging results, or finding the oldest or newest
604 offset := Number of issuance to skip before returning results. Useful for paging.
605 orgid := OU id used to scope retrieval, based on distribution.holding_lib
606 depth := OU depth used to range the scope of orgid
607 type := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
608 status := Item status filter. Valid values are "Bindery", "Bound", "Claimed", "Discarded", "Expected", "Not Held", "Not Published" and "Received". Can be a scalar (one) or arrayref (one or more).
616 sub scoped_bib_holdings_summary {
620 my $args = shift || {};
622 $args->{order} = 'asc';
624 my ($issuances) = $self->method_lookup('open-ils.serial.received_siss.retrieve.by_bib.atomic')->run( $bibid => $args );
626 # split into issuance type sets
627 my %type_blob = (basic => [], supplement => [], index => []);
628 push @{ $type_blob{ $_->{"issuance"}->holding_type } }, $_->{"issuance"}
631 # generate a statement list for each type
633 for my $type ( keys %type_blob ) {
634 my ($mfhd,$list) = _summarize_contents(new_editor(), $type_blob{$type});
635 $statement_blob{$type} = $list;
638 return \%statement_blob;
640 __PACKAGE__->register_method(
641 method => 'scoped_bib_holdings_summary',
642 api_name => 'open-ils.serial.bib.summary_statements',
646 desc => 'Receives a Bib ID and other optional params and returns set of holdings statements',
649 desc => 'id of the bre to which the issuances belong',
654 q/A hash of optional arguments. Valid keys and their meanings:
655 orgid := OU id used to scope retrieval, based on distribution.holding_lib
656 depth := OU depth used to range the scope of orgid
657 type := Holding type filter. Valid values are "basic", "supplement" and "index". Can be a scalar (one) or arrayref (one or more).
658 status := Item status filter. Valid values are "Bindery", "Bound", "Claimed", "Discarded", "Expected", "Not Held", "Not Published" and "Received". Can be a scalar (one) or arrayref (one or more).
666 ##########################################################################
669 __PACKAGE__->register_method(
670 method => 'fleshed_sunit_alter',
671 api_name => 'open-ils.serial.sunit.fleshed.batch.update',
675 desc => 'Receives an array of one or more Units and updates the database as needed',
678 desc => 'Authtoken for current user session',
683 desc => 'Array of fleshed Units',
689 desc => 'Returns 1 if successful, event if failed',
695 sub fleshed_sunit_alter {
696 my( $self, $conn, $auth, $sunits ) = @_;
697 return 1 unless ref $sunits;
698 my( $reqr, $evt ) = $U->checkses($auth);
700 my $editor = new_editor(requestor => $reqr, xact => 1);
701 my $override = $self->api_name =~ /override/;
704 for my $sunit (@$sunits) {
705 my $cn_id = ref $sunit->call_number ? $sunit->call_number->id : $sunit->call_number;
706 if (!exists($found_cn_ids{$cn_id})) {
708 if (ref $sunit->call_number) {
709 $owning_lib_id = $sunit->call_number->owning_lib;
711 my $cn = $editor->retrieve_asset_call_number($sunit->call_number) or return $editor->die_event;
712 $owning_lib_id = $cn->owning_lib;
714 return $editor->die_event unless
715 $editor->allowed("UPDATE_COPY", $owning_lib_id);
716 $found_cn_ids{$cn_id} = 1;
719 if( $sunit->isdeleted ) {
720 $evt = _delete_sunit( $editor, $override, $sunit );
722 $sunit->default_location( $sunit->default_location->id ) if ref $sunit->default_location;
724 if( $sunit->isnew ) {
725 $evt = _create_sunit( $editor, $sunit );
727 $evt = _update_sunit( $editor, $override, $sunit );
733 $logger->info("fleshed sunit-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
737 $logger->debug("sunit-alter: done updating sunit batch");
739 $logger->info("fleshed sunit-alter successfully updated ".scalar(@$sunits)." Units");
744 my ($editor, $override, $sunit) = @_;
745 $logger->info("sunit-alter: delete sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
746 return $editor->event unless $editor->delete_serial_unit($sunit);
751 my ($editor, $sunit) = @_;
753 $logger->info("sunit-alter: new Unit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
754 return $editor->event unless $editor->create_serial_unit($sunit);
759 my ($editor, $override, $sunit) = @_;
761 $logger->info("sunit-alter: retrieving sunit ".$sunit->id);
762 my $orig_sunit = $editor->retrieve_serial_unit($sunit->id);
764 $logger->info("sunit-alter: original sunit ".OpenSRF::Utils::JSON->perl2JSON($orig_sunit));
765 $logger->info("sunit-alter: updated sunit ".OpenSRF::Utils::JSON->perl2JSON($sunit));
766 return $editor->event unless $editor->update_serial_unit($sunit);
770 __PACKAGE__->register_method(
771 method => "retrieve_unit_list",
773 api_name => "open-ils.serial.unit_list.retrieve"
776 sub retrieve_unit_list {
778 my( $self, $client, @sdist_ids ) = @_;
780 if(ref($sdist_ids[0])) { @sdist_ids = @{$sdist_ids[0]}; }
782 my $e = new_editor();
786 { 'sunit' => [ 'id', 'summary_contents', 'sort_key' ],
787 'sitem' => ['stream'],
788 'sstr' => ['distribution'],
789 'sdist' => [{'column' => 'label', 'alias' => 'sdist_label'}]
796 { 'join' => { 'sunit' => {} } }
801 'distinct' => 'true',
802 'where' => { '+sdist' => {'id' => \@sdist_ids} },
803 'order_by' => [{'class' => 'sunit', 'field' => 'sort_key'}]
806 my $unit_list_entries = $e->json_query($query);
809 foreach my $entry (@$unit_list_entries) {
810 my $value = {'sunit' => $entry->{id}, 'sstr' => $entry->{stream}, 'sdist' => $entry->{distribution}};
811 my $label = $entry->{summary_contents};
812 if (length($label) > 100) {
813 $label = substr($label, 0, 100) . '...'; # limited space in dropdown / menu
815 $label = "[$entry->{sdist_label}/$entry->{stream} #$entry->{id}] " . $label;
816 push (@entries, [$label, OpenSRF::Utils::JSON->perl2JSON($value)]);
824 ##########################################################################
825 # predict and receive methods
827 __PACKAGE__->register_method(
828 method => 'make_predictions',
829 api_name => 'open-ils.serial.make_predictions',
833 desc => 'Receives an ssub id and populates the issuance and item tables',
836 desc => 'Serial Subscription ID',
843 sub make_predictions {
844 my ($self, $conn, $authtoken, $args) = @_;
846 my $editor = OpenILS::Utils::CStoreEditor->new();
847 my $ssub_id = $args->{ssub_id};
848 my $mfhd = MFHD->new(MARC::Record->new());
850 my $ssub = $editor->retrieve_serial_subscription([$ssub_id]);
851 my $scaps = $editor->search_serial_caption_and_pattern({ subscription => $ssub_id, active => 't'});
852 my $sdists = $editor->search_serial_distribution( [{ subscription => $ssub->id }, { flesh => 1, flesh_fields => {sdist => [ qw/ streams / ]} }] ); #TODO: 'deleted' support?
854 my $total_streams = 0;
856 $total_streams += scalar(@{$_->streams});
858 if ($total_streams < 1) {
860 # XXX TODO new event type
861 return new OpenILS::Event(
862 "BAD_PARAMS", note =>
863 "There are no streams to direct items. Can't predict."
869 # XXX TODO new event type
870 return new OpenILS::Event(
871 "BAD_PARAMS", note =>
872 "There are no active caption-and-pattern objects associated " .
873 "with this subscription. Can't predict."
879 foreach my $scap (@$scaps) {
880 my $caption_field = _revive_caption($scap);
881 $caption_field->update('8' => $link_id);
882 my $using_fake_chron = 0;
883 # if we have no chronology, add one for prediction puposes
884 if (!$caption_field->subfield('i') and !$caption_field->enumeration_is_chronology) {
885 $using_fake_chron = 1;
887 $mfhd->append_fields($caption_field);
889 'caption' => $caption_field,
890 'scap_id' => $scap->id,
891 'num_to_predict' => $args->{num_to_predict},
892 'end_date' => defined $args->{end_date} ?
893 $_strp_date->parse_datetime($args->{end_date}) : undef
895 if ($args->{base_issuance}) { # predict from a given issuance
896 $options->{predict_from} = _revive_holding($args->{base_issuance}->holding_code, $caption_field, 1); # fresh MFHD Record, so we simply default to 1 for seqno
897 $options->{faked_chron_date} = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($args->{base_issuance}->date_published)) if $using_fake_chron;
898 } else { # default to predicting from last published
899 my $last_published = $editor->search_serial_issuance([
900 {'caption_and_pattern' => $scap->id,
901 'subscription' => $ssub_id},
902 {limit => 1, order_by => { siss => "date_published DESC" }}]
904 if ($last_published->[0]) {
905 my $last_siss = $last_published->[0];
906 unless ($last_siss->holding_code) {
908 # XXX TODO new event type
909 return new OpenILS::Event(
910 "BAD_PARAMS", note =>
911 "Last issuance has no holding code. Can't predict."
914 $options->{predict_from} = _revive_holding($last_siss->holding_code, $caption_field, 1);
915 $options->{faked_chron_date} = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($last_siss->date_published)) if $using_fake_chron;
918 # XXX TODO make a new event type instead of hijacking this one
919 return new OpenILS::Event(
920 "BAD_PARAMS", note => "No issuance from which to predict!"
924 push( @predictions, _generate_issuance_values($mfhd, $options) );
929 foreach my $prediction (@predictions) {
930 my $issuance = new Fieldmapper::serial::issuance;
932 $issuance->label($prediction->{label});
933 $issuance->date_published($prediction->{date_published}->strftime('%F'));
934 $issuance->holding_code(OpenSRF::Utils::JSON->perl2JSON($prediction->{holding_code}));
935 $issuance->holding_type($prediction->{holding_type});
936 $issuance->caption_and_pattern($prediction->{caption_and_pattern});
937 $issuance->subscription($ssub->id);
938 push (@issuances, $issuance);
941 my $evt = fleshed_issuance_alter($self, $conn, $authtoken, \@issuances);
942 return $evt if ref $evt;
945 for (my $i = 0; $i < @issuances; $i++) {
946 my $date_expected = $predictions[$i]->{date_published}->add(seconds => interval_to_seconds($ssub->expected_date_offset))->strftime('%F');
947 my $issuance = $issuances[$i];
948 #$issuance->label(interval_to_seconds($ssub->expected_date_offset));
949 foreach my $sdist (@$sdists) {
950 my $streams = $sdist->streams;
951 foreach my $stream (@$streams) {
952 my $item = new Fieldmapper::serial::item;
954 $item->stream($stream->id);
955 $item->date_expected($date_expected);
956 $item->issuance($issuance->id);
957 push (@items, $item);
961 fleshed_item_alter($self, $conn, $authtoken, \@items); # FIXME: catch events
966 # _generate_issuance_values() is an initial attempt at a function which can be used
967 # to populate an issuance table with a list of predicted issues. It accepts
968 # a hash ref of options initially defined as:
969 # caption : the caption field to predict on
970 # num_to_predict : the number of issues you wish to predict
971 # faked_chron_date : if the serial does not actually have a chronology caption (but we need one for prediction's sake), base predictions on this date
973 # The basic method is to first convert to a single holding if compressed, then
974 # increment the holding and save the resulting values to @issuances.
976 # returns @issuance_values, an array of hashrefs containing (formatted
977 # label, formatted chronology date, formatted estimated arrival date, and an
978 # array ref of holding subfields as (key, value, key, value ...)) (not a hash
979 # to protect order and possible duplicate keys), and a holding type.
981 sub _generate_issuance_values {
982 my ($mfhd, $options) = @_;
983 my $caption = $options->{caption};
984 my $scap_id = $options->{scap_id};
985 my $num_to_predict = $options->{num_to_predict};
986 my $end_date = $options->{end_date};
987 my $predict_from = $options->{predict_from}; # issuance to predict from
988 my $faked_chron_date = $options->{faked_chron_date}; # serial does not have a chronology caption, so add one (temporarily) based on this date
991 # Only needed for 'real' MFHD records, not our temp records
992 # my $link_id = $caption->link_id;
993 # if(!$predict_from) {
994 # my $htag = $caption->tag;
995 # $htag =~ s/^85/86/;
996 # my @holdings = $mfhd->holdings($htag, $link_id);
997 # my $last_holding = $holdings[-1];
999 # #if ($last_holding->is_compressed) {
1000 # # $last_holding->compressed_to_last; # convert to last in range
1002 # $predict_from = $last_holding;
1006 $predict_from->notes('public', []);
1007 # add a note marker for system use (?)
1008 $predict_from->notes('private', ['AUTOGEN']);
1010 # our basic method for dealing with 'faked' chronologies will be to add it in, do the predicting, then take it back out
1013 if ($faked_chron_date) {
1014 $orig_caption = $predict_from->caption;
1015 # because of the way MFHD::Caption and Holding work, it is simplest
1016 # to recreate rather than try to update
1017 $faked_caption = new MFHD::Caption(new MARC::Field($orig_caption->tag, $orig_caption->indicator(1), $orig_caption->indicator(2), $orig_caption->subfields_list, 'i' => '(year)', 'j' => '(month)', 'k' => '(day)'));
1018 $predict_from = new MFHD::Holding($predict_from->seqno, new MARC::Field($predict_from->tag, $predict_from->indicator(1), $predict_from->indicator(2), $predict_from->subfields_list, 'i' => $faked_chron_date->year, 'j' => $faked_chron_date->month, 'k' => $faked_chron_date->day), $faked_caption);
1021 my @predictions = $mfhd->generate_predictions({'base_holding' => $predict_from, 'num_to_predict' => $num_to_predict, 'end_date' => $end_date});
1024 my @issuance_values;
1025 foreach my $prediction (@predictions) {
1026 $pub_date = $_strp_date->parse_datetime($prediction->chron_to_date);
1027 if ($faked_chron_date) { # get rid of the chronology portions and restore original caption
1028 $prediction->delete_subfield(code => ['i', 'j', 'k']);
1029 $prediction = new MFHD::Holding($prediction->seqno, new MARC::Field($prediction->tag, $prediction->indicator(1), $prediction->indicator(2), $prediction->subfields_list), $orig_caption);
1035 label => $prediction->format,
1036 date_published => $pub_date,
1037 #date_expected => $date_expected->strftime('%F'),
1038 holding_code => [$prediction->indicator(1),$prediction->indicator(2),$prediction->subfields_list],
1039 holding_type => $MFHD_NAMES_BY_TAG{$caption->tag},
1040 caption_and_pattern => $scap_id
1045 return @issuance_values;
1048 sub _revive_caption {
1051 my $pattern_code = $scap->pattern_code;
1054 my $pattern_parts = OpenSRF::Utils::JSON->JSON2perl($pattern_code);
1055 unshift(@$pattern_parts, $MFHD_TAGS_BY_NAME{$scap->type});
1056 my $pattern_field = new MARC::Field(@$pattern_parts);
1058 # build MFHD::Caption
1059 return new MFHD::Caption($pattern_field);
1062 sub _revive_holding {
1063 my $holding_code = shift;
1064 my $caption_field = shift;
1068 my $holding_parts = OpenSRF::Utils::JSON->JSON2perl($holding_code);
1069 my $captag = $caption_field->tag;
1070 $captag =~ s/^85/86/;
1071 unshift(@$holding_parts, $captag);
1072 my $holding_field = new MARC::Field(@$holding_parts);
1074 # build MFHD::Holding
1075 return new MFHD::Holding($seqno, $holding_field, $caption_field);
1077 # TODO(?) the underlying MARC and the Holding object end up in conflict concerning subfield '8'
1080 __PACKAGE__->register_method(
1081 method => 'unitize_items',
1082 api_name => 'open-ils.serial.receive_items',
1086 desc => 'Marks an item as received, updates the shelving unit (creating a new shelving unit if needed), and updates the summaries',
1089 desc => 'array of serial items',
1094 desc => 'hash of item_ids => barcodes',
1098 name => 'call_numbers',
1099 desc => 'hash of item_ids => call_numbers',
1103 name => 'donor_unit_ids',
1104 desc => 'hash of unit_ids => 1, keyed with ids of any units giving up items',
1109 desc => 'Returns number of received items (num_items) and new unit ID, if applicable (new_unit_id)',
1115 __PACKAGE__->register_method(
1116 method => 'unitize_items',
1117 api_name => 'open-ils.serial.bind_items',
1121 desc => 'Marks an item as bound, updates the shelving unit (creating a new shelving unit if needed)',
1124 desc => 'array of serial items',
1129 desc => 'hash of item_ids => barcodes',
1133 name => 'call_numbers',
1134 desc => 'hash of item_ids => call_numbers',
1138 name => 'donor_unit_ids',
1139 desc => 'hash of unit_ids => 1, keyed with ids of any units giving up items',
1144 desc => 'Returns number of bound items (num_items) and new unit ID, if applicable (new_unit_id)',
1150 # TODO: reset/delete claims information once implemented
1151 # XXX: deal with emptied call numbers here?
1152 __PACKAGE__->register_method(
1153 method => 'unitize_items',
1154 api_name => 'open-ils.serial.reset_items',
1158 desc => 'Resets the items to Expected, updates the shelving unit (deleting the shelving unit if empty), and updates the summaries',
1161 desc => 'array of serial items',
1166 desc => 'Returns number of reset items (num_items)',
1173 my ($self, $conn, $auth, $items, $barcodes, $call_numbers, $donor_unit_ids) = @_;
1175 my $editor = new_editor("authtoken" => $auth, "xact" => 1);
1176 return $editor->die_event unless $editor->checkauth;
1177 return $editor->die_event unless $editor->allowed("RECEIVE_SERIAL");
1178 $self->api_name =~ /serial\.(\w*)_items/;
1182 if ($donor_unit_ids) { # units giving up items need updating as well
1183 %found_unit_ids = %$donor_unit_ids;
1185 my %found_stream_ids;
1188 my %stream_ids_by_unit_id;
1191 my %sdist_by_unit_id;
1192 my %call_number_by_unit_id;
1193 my %sdist_by_stream_id;
1195 my $new_unit_id; # id for '-2' units to share
1196 foreach my $item (@$items) {
1197 # for debugging only, TODO: delete
1198 if (!ref $item) { # hopefully we got an id instead
1199 $item = $editor->retrieve_serial_item($item);
1202 my $unit_id = ref($item->unit) ? $item->unit->id : $item->unit;
1203 my $stream_id = ref($item->stream) ? $item->stream->id : $item->stream;
1204 my $issuance_id = ref($item->issuance) ? $item->issuance->id : $item->issuance;
1205 #TODO: evt on any missing ids
1207 if ($mode eq 'receive') {
1208 $item->date_received('now');
1209 $item->status('Received');
1210 } elsif ($mode eq 'reset') {
1211 # clear date_received
1212 $item->clear_date_received;
1213 # Set status to 'Expected'
1214 $item->status('Expected');
1219 # check for types to trigger summary updates
1221 if (!ref $item->issuance) {
1222 my $scaps = $editor->search_serial_caption_and_pattern([{"+siss" => {"id" => $issuance_id}}, { "join" => {"siss" => {}} }]);
1223 $scap = $scaps->[0];
1224 } elsif (!ref $item->issuance->caption_and_pattern) {
1225 $scap = $editor->retrieve_serial_caption_and_pattern($item->issuance->caption_and_pattern);
1227 $scap = $editor->issuance->caption_and_pattern;
1229 if (!exists($found_types{$stream_id})) {
1230 $found_types{$stream_id} = {};
1232 $found_types{$stream_id}->{$scap->type} = 1;
1234 # create unit if needed
1235 if ($unit_id == -1 or (!$new_unit_id and $unit_id == -2)) { # create unit per item
1237 my $sdists = $editor->search_serial_distribution([
1238 {"+sstr" => {"id" => $stream_id}},
1240 "join" => {"sstr" => {}},
1242 "flesh_fields" => {"sdist" => ["subscription"]}
1244 $unit = _build_unit($editor, $sdists->[0], $mode);
1245 # if _build_unit fails, $unit is an event, so return it
1246 if ($U->event_code($unit)) {
1248 $unit->{"note"} = "Item ID: " . $item->id;
1251 $unit->barcode($barcodes->{$item->id}) if exists($barcodes->{$item->id});
1252 my $evt = _create_sunit($editor, $unit);
1253 return $evt if $evt;
1254 if ($unit_id == -2) {
1255 $new_unit_id = $unit->id;
1256 $unit_id = $new_unit_id;
1258 $unit_id = $unit->id;
1260 $item->unit($unit_id);
1262 # get unit with 'DEFAULT's and save unit, sdist, and call number for later use
1263 $unit = $editor->retrieve_serial_unit($unit->id);
1264 $unit_map{$unit_id} = $unit;
1265 $sdist_by_unit_id{$unit_id} = $sdists->[0];
1266 $call_number_by_unit_id{$unit_id} = $call_numbers->{$item->id};
1267 $sdist_by_stream_id{$stream_id} = $sdists->[0];
1268 } elsif ($unit_id == -2) { # create one unit for all '-2' items
1269 $unit_id = $new_unit_id;
1270 $item->unit($unit_id);
1273 $found_stream_ids{$stream_id} = 1;
1275 if (defined($unit_id) and $unit_id ne '') {
1276 $found_unit_ids{$unit_id} = 1;
1277 # save the stream_id for this unit_id
1278 # TODO: prevent items from different streams in same unit? (perhaps in interface)
1279 $stream_ids_by_unit_id{$unit_id} = $stream_id;
1284 my $evt = _update_sitem($editor, undef, $item);
1285 return $evt if $evt;
1288 # cleanup 'dead' units (units which are now emptied of their items)
1289 my $dead_units = $editor->search_serial_unit([{'+sitem' => {'id' => undef}, 'deleted' => 'f'}, {'join' => {'sitem' => {'type' => 'left'}}}]);
1290 foreach my $unit (@$dead_units) {
1291 _delete_sunit($editor, undef, $unit);
1292 delete $found_unit_ids{$unit->id};
1295 # deal with unit level contents
1296 foreach my $unit_id (keys %found_unit_ids) {
1298 # get all the needed issuances for unit
1299 # TODO remove 'Bindery' from this search (leaving it in for now for backwards compatibility with any current test environment data)
1300 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"unit" => $unit_id, "status" => ["Received", "Bindery"]}}, {"join" => {"sitem" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1301 #TODO: evt on search failure
1303 # retrieve and update unit contents
1306 my $call_number_string;
1308 # if we just created the unit, we will already have it and the distribution stored, and we will need to assign the call number
1309 if (exists $unit_map{$unit_id}) {
1310 $sunit = $unit_map{$unit_id};
1311 $sdist = $sdist_by_unit_id{$unit_id};
1312 $call_number_string = $call_number_by_unit_id{$unit_id};
1313 $record_id = $sdist->subscription->record_entry;
1315 # XXX: this code assumes you will not have units which mix streams/distributions, but current code does not enforce this
1316 $sunit = $editor->retrieve_serial_unit($unit_id);
1317 if ($stream_ids_by_unit_id{$unit_id}) {
1318 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_ids_by_unit_id{$unit_id}}}, { "join" => {"sstr" => {}}, 'limit' => 1 }]);
1320 $sdist = $editor->search_serial_distribution([
1321 {'+sunit' => {'id' => $unit_id}},
1326 { 'join' => 'sunit' }
1333 $sdist = $sdist->[0];
1336 my $evt = _prepare_unit($editor, $sunit, $sdist, $issuances, $call_number_string, $record_id);
1337 if ($U->event_code($evt)) {
1342 $evt = _update_sunit($editor, undef, $sunit);
1343 if ($U->event_code($evt)) {
1349 if ($mode ne 'bind') { # the summary holdings do not change when binding
1350 # deal with stream level summaries
1351 # summaries will be built from the "primary" stream only, that is, the stream with the lowest ID per distribution
1352 # (TODO: consider direct designation)
1353 my %primary_streams_by_sdist;
1354 my %streams_by_sdist;
1356 # see if we have primary streams, and if so, associate them with their distributions
1357 foreach my $stream_id (keys %found_stream_ids) {
1359 if (exists $sdist_by_stream_id{$stream_id}) {
1360 $sdist = $sdist_by_stream_id{$stream_id};
1362 $sdist = $editor->search_serial_distribution([{"+sstr" => {"id" => $stream_id}}, { "join" => {"sstr" => {}} }]);
1363 $sdist = $sdist->[0];
1364 $sdist_by_stream_id{$stream_id} = $sdist;
1367 if (!exists($streams_by_sdist{$sdist->id})) {
1368 $streams = $editor->search_serial_stream([{"distribution" => $sdist->id}, {"order_by" => {"sstr" => "id"}}]);
1369 $streams_by_sdist{$sdist->id} = $streams;
1371 $streams = $streams_by_sdist{$sdist->id};
1373 $primary_streams_by_sdist{$sdist->id} = $streams->[0] if ($stream_id == $streams->[0]->id);
1376 # retrieve and update summaries for each affected primary stream's distribution
1377 foreach my $sdist_id (keys %primary_streams_by_sdist) {
1378 my $stream = $primary_streams_by_sdist{$sdist_id};
1379 my $stream_id = $stream->id;
1380 # get all the needed issuances for stream
1381 # FIXME: search in Bindery/Bound/Not Published? as well as Received
1382 foreach my $type (keys %{$found_types{$stream_id}}) {
1383 my $issuances = $editor->search_serial_issuance([ {"+sitem" => {"stream" => $stream_id, "status" => "Received"}, "+scap" => {"type" => $type}}, {"join" => {"sitem" => {}, "scap" => {}}, "order_by" => {"siss" => "date_published"}} ]);
1384 #TODO: evt on search failure
1385 my $evt = _prepare_summaries($editor, $issuances, $sdist_by_stream_id{$stream_id}, $type);
1386 if ($U->event_code($evt)) {
1395 return {'num_items' => scalar @$items, 'new_unit_id' => $new_unit_id};
1398 sub _find_or_create_call_number {
1399 my ($e, $lib, $cn_string, $record) = @_;
1401 # FIXME: should suffix and prefix come into play here?
1402 my $existing = $e->search_asset_call_number({
1403 "owning_lib" => $lib,
1404 "label" => $cn_string,
1405 "record" => $record,
1407 }) or return $e->die_event;
1410 return $existing->[0]->id;
1412 return $e->die_event unless
1413 $e->allowed("CREATE_VOLUME", $lib);
1415 my $acn = new Fieldmapper::asset::call_number;
1417 $acn->creator($e->requestor->id);
1418 $acn->editor($e->requestor->id);
1419 $acn->record($record);
1420 $acn->label($cn_string);
1421 $acn->owning_lib($lib);
1423 $e->create_asset_call_number($acn) or return $e->die_event;
1424 return $e->data->id;
1428 sub _issuances_received {
1429 # XXX TODO: Add some caching or something. This is getting called
1430 # more often than it has to be.
1431 my ($e, $sitem) = @_;
1433 my $results = $e->json_query({
1434 "select" => {"sitem" => ["issuance"]},
1435 "from" => {"sitem" => {"sstr" => {}, "siss" => {}}},
1437 "+sstr" => {"distribution" => $sitem->stream->distribution->id},
1438 "+siss" => {"holding_type" => $sitem->issuance->holding_type},
1439 "+sitem" => {"date_received" => {"!=" => undef}}
1442 "siss" => {"date_published" => {"direction" => "asc"}}
1444 }) or return $e->die_event;
1446 my $uniq = +{map { $_->{"issuance"} => 1 } @$results};
1447 return [ map { $e->retrieve_serial_issuance($_) } keys %$uniq ];
1450 # _prepare_unit populates the detailed_contents, summary_contents, and
1451 # sort_key fields for a given unit based on a given set of issuances
1452 # Also finds/creates call number as needed
1454 my ($e, $sunit, $sdist, $issuances, $call_number_string, $record_id) = @_;
1456 # Handle call number first if we have one
1457 if ($call_number_string) {
1458 my $org_unit_id = ref $sdist->holding_lib ? $sdist->holding_lib->id : $sdist->holding_lib;
1459 my $real_cn = _find_or_create_call_number(
1461 $call_number_string, $record_id
1464 if ($U->event_code($real_cn)) {
1467 $sunit->call_number($real_cn);
1471 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances);
1473 # special case for single formatted_part (may have summarized version)
1474 if (@$formatted_parts == 1) {
1475 #TODO: MFHD.pm should have a 'format_summary' method for this
1478 $sunit->detailed_contents(
1481 $sdist->unit_label_prefix,
1482 join(", ", @$formatted_parts),
1483 $sdist->unit_label_suffix
1487 # TODO: change this when real summary contents are available
1488 $sunit->summary_contents($sunit->detailed_contents);
1490 # Create sort_key by left padding numbers to 6 digits.
1491 (my $sort_key = $sunit->detailed_contents) =~
1492 s/(\d+)/sprintf '%06d', $1/eg;
1493 $sunit->sort_key($sort_key);
1496 # _prepare_summaries populates the generated_coverage field for a given summary
1497 # type ('basic', 'index', 'supplement') for a given distribution.
1498 # It also creates the summary if it doesn't yet exist.
1499 sub _prepare_summaries {
1500 my ($e, $issuances, $sdist, $type) = @_;
1502 my ($mfhd, $formatted_parts) = _summarize_contents($e, $issuances, $sdist);
1504 my $search_method = "search_serial_${type}_summary";
1505 my $summary = $e->$search_method([{"distribution" => $sdist->id}]);
1507 my $cu_method = "update";
1510 $summary = $summary->[0];
1512 my $class = "Fieldmapper::serial::${type}_summary";
1513 $summary = $class->new;
1514 $summary->distribution($sdist->id);
1515 $cu_method = "create";
1518 $summary->generated_coverage(OpenSRF::Utils::JSON->perl2JSON($formatted_parts));
1519 my $method = "${cu_method}_serial_${type}_summary";
1520 return $e->die_event unless $e->$method($summary);
1523 sub _unit_by_iss_and_str {
1524 my ($e, $issuance, $stream) = @_;
1526 my $unit = $e->json_query({
1527 "select" => {"sunit" => ["id"]},
1528 "from" => {"sitem" => {"sunit" => {}}},
1531 "issuance" => $issuance->id,
1532 "stream" => $stream->id
1535 }) or return $e->die_event;
1536 return 0 if not @$unit;
1538 $e->retrieve_serial_unit($unit->[0]->{"id"}) or $e->die_event;
1541 sub move_previous_unit {
1542 my ($e, $prev_iss, $curr_item, $new_loc) = @_;
1544 my $prev_unit = _unit_by_iss_and_str($e,$prev_iss,$curr_item->stream);
1545 return $prev_unit if defined $U->event_code($prev_unit);
1546 return 0 if not $prev_unit;
1548 if ($prev_unit->location != $new_loc) {
1549 $prev_unit->location($new_loc);
1550 $e->update_serial_unit($prev_unit) or return $e->die_event;
1555 # _previous_issuance() assumes $existing is an ordered array
1556 sub _previous_issuance {
1557 my ($existing, $issuance) = @_;
1559 my $last = $existing->[-1];
1560 return undef unless $last;
1561 return ($last->id == $issuance->id ? $existing->[-2] : $last);
1564 __PACKAGE__->register_method(
1565 "method" => "receive_items_one_unit_per",
1566 "api_name" => "open-ils.serial.receive_items.one_unit_per",
1571 "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",
1575 "desc" => "authtoken",
1580 "desc" => "array of serial items, possibly fleshed with units and definitely fleshed with stream->distribution",
1585 "desc" => "id of bib record these items are associated with
1586 (XXX could/should be derived from items)",
1591 "desc" => "The item ID for each item successfully received",
1597 sub receive_items_one_unit_per {
1598 # XXX This function may be temporary, as it does some of what
1599 # unitize_items() does, just in a different way.
1600 my ($self, $client, $auth, $items, $record) = @_;
1602 my $e = new_editor("authtoken" => $auth, "xact" => 1);
1603 return $e->die_event unless $e->checkauth;
1604 return $e->die_event unless $e->allowed("RECEIVE_SERIAL");
1606 my $prev_loc_setting_map = {};
1607 my $user_id = $e->requestor->id;
1609 # Get a list of all the non-virtual field names in a serial::unit for
1610 # merging given unit objects with template-built units later.
1611 # XXX move this somewhere global so it isn't re-run all the time
1612 my $all_unit_fields =
1613 $Fieldmapper::fieldmap->{"Fieldmapper::serial::unit"}->{"fields"};
1614 my @real_unit_fields = grep {
1615 not $all_unit_fields->{$_}->{"virtual"}
1616 } keys %$all_unit_fields;
1618 foreach my $item (@$items) {
1619 # Note that we expect a certain fleshing on the items we're getting.
1620 my $sdist = $item->stream->distribution;
1622 # Fetch a list of issuances with received copies already existing
1623 # on this distribution (and with the same holding type on the
1624 # issuance). This will be used in up to two places: once when building
1625 # a summary, once when changing the copy location of the previous
1627 my $issuances_received = _issuances_received($e, $item);
1628 if ($U->event_code($issuances_received)) {
1630 return $issuances_received;
1633 # Find out if we need to to deal with previous copy location changing.
1634 my $ou = $sdist->holding_lib->id;
1635 unless (exists $prev_loc_setting_map->{$ou}) {
1636 $prev_loc_setting_map->{$ou} = $U->ou_ancestor_setting_value(
1637 $ou, "serial.prev_issuance_copy_location", $e
1641 # If there is a previous copy location setting, we need the previous
1642 # issuance, from which we can in turn look up the item attached to the
1643 # same stream we're on now.
1644 if ($prev_loc_setting_map->{$ou}) {
1646 _previous_issuance($issuances_received, $item->issuance)) {
1648 # Now we can change the copy location of the previous unit,
1650 return $e->event if defined $U->event_code(
1652 $e, $prev_iss, $item, $prev_loc_setting_map->{$ou}
1658 # Create unit if given by user
1659 if (ref $item->unit) {
1660 # detach from the item, as we need to create separately
1661 my $user_unit = $item->unit;
1663 # get a unit based on associated template
1664 my $template_unit = _build_unit($e, $sdist, "receive");
1665 if ($U->event_code($template_unit)) {
1667 $template_unit->{"note"} = "Item ID: " . $item->id;
1668 return $template_unit;
1671 # merge built unit with provided unit from user
1672 foreach (@real_unit_fields) {
1673 unless ($user_unit->$_) {
1674 $user_unit->$_($template_unit->$_);
1678 # Treat call number specially: the provided value from the
1679 # user will really be a string.
1680 my $call_number_string;
1681 if ($user_unit->call_number) {
1682 $call_number_string = $user_unit->call_number;
1683 # clear call number for now (replaced in _prepare_unit)
1684 $user_unit->clear_call_number;
1687 my $evt = _prepare_unit(
1688 $e, $user_unit, $sdist, [$item->issuance],
1689 $call_number_string, $record
1691 if ($U->event_code($evt)) {
1696 # create/update summary objects related to this distribution
1697 # Make sure @$issuances_received contains current item's issuance
1698 unless (grep { $_->id == $item->issuance->id } @$issuances_received) {
1699 push @$issuances_received, $item->issuance;
1701 $evt = _prepare_summaries($e, $issuances_received, $item->stream->distribution, $item->issuance->holding_type);
1702 if ($U->event_code($evt)) {
1707 # set the incontrovertibles on the unit
1708 $user_unit->edit_date("now");
1709 $user_unit->create_date("now");
1710 $user_unit->editor($user_id);
1711 $user_unit->creator($user_id);
1713 return $e->die_event unless $e->create_serial_unit($user_unit);
1715 # save reference to new unit
1716 $item->unit($e->data->id);
1719 # Create notes if given by user
1720 if (ref($item->notes) and @{$item->notes}) {
1721 foreach my $note (@{$item->notes}) {
1722 $note->creator($user_id);
1723 $note->create_date("now");
1725 return $e->die_event unless $e->create_serial_item_note($note);
1728 $item->clear_notes; # They're saved; we no longer want them here.
1731 # Set the incontrovertibles on the item
1732 $item->status("Received");
1733 $item->date_received("now");
1734 $item->edit_date("now");
1735 $item->editor($user_id);
1737 return $e->die_event unless $e->update_serial_item($item);
1739 # send client a response
1740 $client->respond($item->id);
1743 $e->commit or return $e->die_event;
1751 #my $skip_call_number = shift;
1753 my $attr = $mode . '_unit_template';
1754 my $template = $editor->retrieve_asset_copy_template($sdist->$attr) or
1755 return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_COPY_TEMPLATE");
1757 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 );
1759 my $unit = new Fieldmapper::serial::unit;
1760 foreach my $part (@parts) {
1761 my $value = $template->$part;
1762 next if !defined($value);
1763 $unit->$part($value);
1766 # ignore circ_lib in template, set to distribution holding_lib
1767 $unit->circ_lib($sdist->holding_lib);
1768 $unit->creator($editor->requestor->id);
1769 $unit->editor($editor->requestor->id);
1771 # XXX: this feature has been pushed back until after 2.0 at least
1772 # unless ($skip_call_number) {
1773 # $attr = $mode . '_call_number';
1774 # my $cn = $sdist->$attr or
1775 # return new OpenILS::Event("SERIAL_DISTRIBUTION_HAS_NO_CALL_NUMBER");
1777 # $unit->call_number($cn);
1779 $unit->call_number('-1'); # default to the dummy call number
1780 $unit->barcode('@@PLACEHOLDER'); # generic unit will start with a generated placeholder barcode
1781 $unit->sort_key('');
1782 $unit->summary_contents('');
1783 $unit->detailed_contents('');
1789 sub _summarize_contents {
1791 my $issuances = shift;
1794 # create or lookup MFHD record
1796 if ($sdist and defined($sdist->record_entry) and $sdist->summary_method eq 'merge_with_sre') {
1798 if (ref $sdist->record_entry) {
1799 $sre = $sdist->record_entry;
1801 $sre = $editor->retrieve_serial_record_entry($sdist->record_entry);
1803 $mfhd = MFHD->new(MARC::Record->new_from_xml($sre->marc));
1805 $logger->info($sdist);
1806 $mfhd = MFHD->new(MARC::Record->new());
1812 # We keep track of these separately to avoid link_id contamination,
1813 # e.g. a basic issuance, followed by a merging supplement, followed by
1814 # another basic. If we could be sure that they were not mixed, one
1815 # value could suffice.
1816 my %link_ids = ('basic' => 10000, 'index' => 10000, 'supplement' => 10000);
1817 my %first_scap = ('basic' => 1, 'index' => 1, 'supplement' => 1);
1818 foreach my $issuance (@$issuances) {
1819 my $scap_id = $issuance->caption_and_pattern;
1820 next if (!$scap_id); # skip issuances with no caption/pattern
1824 # if this is the first appearance of this scap, retrieve it and add it to the temporary record
1825 if (!exists $scaps{$issuance->caption_and_pattern}) {
1826 $scaps{$scap_id} = $editor->retrieve_serial_caption_and_pattern($scap_id);
1827 $scap = $scaps{$scap_id};
1828 $scap_field = _revive_caption($scap);
1830 if ($first_scap{$scap->type}) { # special merge processing
1831 $first_scap{$MFHD_TAGS_BY_NAME{$scap->type}} = 0;
1832 if ($sdist and $sdist->summary_method eq 'merge_with_sre') {
1833 # MFHD Caption objects do not yet have a built-in compare (TODO), so let's do a basic one
1834 my @field_85xs = $mfhd->field($MFHD_TAGS_BY_NAME{$scap->type});
1836 my $last_caption_field = $field_85xs[-1];
1837 my $last_link_id = $last_caption_field->subfield('8');
1838 # set the link id to match, temporarily, for comparison
1839 $last_caption_field->update('8' => $scap_field->subfield('8'));
1840 my $last_caption_json = OpenSRF::Utils::JSON->perl2JSON([$last_caption_field->indicator(1), $last_caption_field->indicator(2), $last_caption_field->subfields_list]);
1841 if ($last_caption_json eq $scap->pattern_code) { # merge is possible, they match
1843 $link_ids{$scap->type} = $last_link_id;
1844 # set scap_field to last field
1845 $scap_field = $last_caption_field;
1851 $scap_fields{$scap_id} = $scap_field;
1852 $scap_field->update('8' => $link_ids{$scap->type});
1853 # TODO: make MFHD/Caption smarter about this
1854 $scap_field->{_mfhdc_LINK_ID} = $link_ids{$scap->type};
1855 $mfhd->append_fields($scap_field) if !$did_merge;
1856 $link_ids{$scap->type}++;
1858 $scap_field = $scap_fields{$scap_id};
1861 $mfhd->append_fields(_revive_holding($issuance->holding_code, $scap_field, $seqno));
1865 my @formatted_parts;
1866 my @scap_fields_ordered = $mfhd->field('85[345]');
1867 foreach my $scap_field (@scap_fields_ordered) { #TODO: use generic MFHD "summarize" method, once available
1868 my @updated_holdings = $mfhd->get_compressed_holdings($scap_field);
1869 foreach my $holding (@updated_holdings) {
1870 push(@formatted_parts, $holding->format);
1874 return ($mfhd, \@formatted_parts);
1877 ##########################################################################
1880 __PACKAGE__->register_method(
1881 method => 'fetch_notes',
1882 api_name => 'open-ils.serial.item_note.retrieve.all',
1884 Returns an array of copy note objects.
1885 @param args A named hash of parameters including:
1886 authtoken : Required if viewing non-public notes
1887 item_id : The id of the item whose notes we want to retrieve
1888 pub : True if all the caller wants are public notes
1889 @return An array of note objects
1893 __PACKAGE__->register_method(
1894 method => 'fetch_notes',
1895 api_name => 'open-ils.serial.subscription_note.retrieve.all',
1897 Returns an array of copy note objects.
1898 @param args A named hash of parameters including:
1899 authtoken : Required if viewing non-public notes
1900 subscription_id : The id of the item whose notes we want to retrieve
1901 pub : True if all the caller wants are public notes
1902 @return An array of note objects
1906 __PACKAGE__->register_method(
1907 method => 'fetch_notes',
1908 api_name => 'open-ils.serial.distribution_note.retrieve.all',
1910 Returns an array of copy note objects.
1911 @param args A named hash of parameters including:
1912 authtoken : Required if viewing non-public notes
1913 distribution_id : The id of the item whose notes we want to retrieve
1914 pub : True if all the caller wants are public notes
1915 @return An array of note objects
1919 # TODO: revisit this method to consider replacing cstore direct calls
1921 my( $self, $connection, $args ) = @_;
1923 $self->api_name =~ /serial\.(\w*)_note/;
1926 my $id = $$args{object_id};
1927 my $authtoken = $$args{authtoken};
1931 return $U->cstorereq(
1932 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic',
1933 { $type => $id, pub => 't' } );
1935 # FIXME: restore perm check
1936 # ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
1937 # return $evt if $evt;
1938 return $U->cstorereq(
1939 'open-ils.cstore.direct.serial.'.$type.'_note.search.atomic', {$type => $id} );
1945 __PACKAGE__->register_method(
1946 method => 'update_note',
1947 api_name => 'open-ils.serial.item_note.update',
1949 Updates or creates an item note
1950 @param authtoken The login session key
1951 @param note The note object to update or create
1952 @return The id of the note object
1956 __PACKAGE__->register_method(
1957 method => 'update_note',
1958 api_name => 'open-ils.serial.subscription_note.update',
1960 Updates or creates a subscription note
1961 @param authtoken The login session key
1962 @param note The note object to update or create
1963 @return The id of the note object
1967 __PACKAGE__->register_method(
1968 method => 'update_note',
1969 api_name => 'open-ils.serial.distribution_note.update',
1971 Updates or creates a distribution note
1972 @param authtoken The login session key
1973 @param note The note object to update or create
1974 @return The id of the note object
1979 my( $self, $connection, $authtoken, $note ) = @_;
1981 $self->api_name =~ /serial\.(\w*)_note/;
1984 my $e = new_editor(xact=>1, authtoken=>$authtoken);
1985 return $e->event unless $e->checkauth;
1987 if ($type eq 'item') {
1988 my $sitem = $e->retrieve_serial_item([
1990 "flesh" => 2, "flesh_fields" => {
1991 "sitem" => ["stream"], "sstr" => ["distribution"]
1994 ]) or return $e->die_event;
1996 return $e->die_event unless $e->allowed(
1997 "ADMIN_SERIAL_ITEM", $sitem->stream->distribution->holding_lib
1999 } elsif ($type eq 'distribution') {
2000 my $sdist = $e->retrieve_serial_distribution($note->distribution)
2001 or return $e->die_event;
2003 return $e->die_event unless
2004 $e->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2005 } else { # subscription
2006 my $sub = $e->retrieve_serial_subscription($note->subscription)
2007 or return $e->die_event;
2009 return $e->die_event unless
2010 $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
2013 $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
2016 $note->create_date('now');
2017 $note->creator($e->requestor->id);
2019 $method = "create_serial_${type}_note";
2021 $method = "update_serial_${type}_note";
2023 $e->$method($note) or return $e->event;
2028 __PACKAGE__->register_method(
2029 method => 'delete_note',
2030 api_name => 'open-ils.serial.item_note.delete',
2032 Deletes an existing item note
2033 @param authtoken The login session key
2034 @param noteid The id of the note to delete
2035 @return 1 on success - Event otherwise.
2039 __PACKAGE__->register_method(
2040 method => 'delete_note',
2041 api_name => 'open-ils.serial.subscription_note.delete',
2043 Deletes an existing subscription note
2044 @param authtoken The login session key
2045 @param noteid The id of the note to delete
2046 @return 1 on success - Event otherwise.
2050 __PACKAGE__->register_method(
2051 method => 'delete_note',
2052 api_name => 'open-ils.serial.distribution_note.delete',
2054 Deletes an existing distribution note
2055 @param authtoken The login session key
2056 @param noteid The id of the note to delete
2057 @return 1 on success - Event otherwise.
2062 my( $self, $conn, $authtoken, $noteid ) = @_;
2064 $self->api_name =~ /serial\.(\w*)_note/;
2067 my $e = new_editor(xact=>1, authtoken=>$authtoken);
2068 return $e->die_event unless $e->checkauth;
2070 my $method = "retrieve_serial_${type}_note";
2071 my $note = $e->$method([
2073 ]) or return $e->die_event;
2075 if ($type eq 'item') {
2076 my $sitem = $e->retrieve_serial_item([
2078 "flesh" => 2, "flesh_fields" => {
2079 "sitem" => ["stream"], "sstr" => ["distribution"]
2082 ]) or return $e->die_event;
2084 return $e->die_event unless $e->allowed(
2085 "ADMIN_SERIAL_ITEM", $sitem->stream->distribution->holding_lib
2087 } elsif ($type eq 'distribution') {
2088 my $sdist = $e->retrieve_serial_distribution($note->distribution)
2089 or return $e->die_event;
2091 return $e->die_event unless
2092 $e->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2093 } else { # subscription
2094 my $sub = $e->retrieve_serial_subscription($note->subscription)
2095 or return $e->die_event;
2097 return $e->die_event unless
2098 $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
2101 $method = "delete_serial_${type}_note";
2102 $e->$method($note) or return $e->die_event;
2108 ##########################################################################
2109 # subscription methods
2111 __PACKAGE__->register_method(
2112 method => 'fleshed_ssub_alter',
2113 api_name => 'open-ils.serial.subscription.fleshed.batch.update',
2117 desc => 'Receives an array of one or more subscriptions and updates the database as needed',
2119 name => 'authtoken',
2120 desc => 'Authtoken for current user session',
2124 name => 'subscriptions',
2125 desc => 'Array of fleshed subscriptions',
2131 desc => 'Returns 1 if successful, event if failed',
2137 sub fleshed_ssub_alter {
2138 my( $self, $conn, $auth, $ssubs ) = @_;
2139 return 1 unless ref $ssubs;
2140 my( $reqr, $evt ) = $U->checkses($auth);
2141 return $evt if $evt;
2142 my $editor = new_editor(requestor => $reqr, xact => 1);
2143 my $override = $self->api_name =~ /override/;
2145 for my $ssub (@$ssubs) {
2146 my $owning_lib_id = ref $ssub->owning_lib ? $ssub->owning_lib->id : $ssub->owning_lib;
2147 return $editor->die_event unless
2148 $editor->allowed("ADMIN_SERIAL_SUBSCRIPTION", $owning_lib_id);
2150 my $ssubid = $ssub->id;
2152 if( $ssub->isdeleted ) {
2153 $evt = _delete_ssub( $editor, $override, $ssub);
2154 } elsif( $ssub->isnew ) {
2155 _cleanse_dates($ssub, ['start_date','end_date']);
2156 $evt = _create_ssub( $editor, $ssub );
2158 _cleanse_dates($ssub, ['start_date','end_date']);
2159 $evt = _update_ssub( $editor, $override, $ssub );
2164 $logger->info("fleshed subscription-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2168 $logger->debug("subscription-alter: done updating subscription batch");
2170 $logger->info("fleshed subscription-alter successfully updated ".scalar(@$ssubs)." subscriptions");
2175 my ($editor, $override, $ssub) = @_;
2176 $logger->info("subscription-alter: delete subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2177 my $sdists = $editor->search_serial_distribution(
2178 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2179 my $cps = $editor->search_serial_caption_and_pattern(
2180 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2181 my $sisses = $editor->search_serial_issuance(
2182 { subscription => $ssub->id }, { limit => 1 } ); #TODO: 'deleted' support?
2183 return OpenILS::Event->new(
2184 'SERIAL_SUBSCRIPTION_NOT_EMPTY', payload => $ssub->id ) if (@$sdists or @$cps or @$sisses);
2186 return $editor->event unless $editor->delete_serial_subscription($ssub);
2191 my ($editor, $ssub) = @_;
2193 $logger->info("subscription-alter: new subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2194 return $editor->event unless $editor->create_serial_subscription($ssub);
2199 my ($editor, $override, $ssub) = @_;
2201 $logger->info("subscription-alter: retrieving subscription ".$ssub->id);
2202 my $orig_ssub = $editor->retrieve_serial_subscription($ssub->id);
2204 $logger->info("subscription-alter: original subscription ".OpenSRF::Utils::JSON->perl2JSON($orig_ssub));
2205 $logger->info("subscription-alter: updated subscription ".OpenSRF::Utils::JSON->perl2JSON($ssub));
2206 return $editor->event unless $editor->update_serial_subscription($ssub);
2210 __PACKAGE__->register_method(
2211 method => "fleshed_serial_subscription_retrieve_batch",
2213 api_name => "open-ils.serial.subscription.fleshed.batch.retrieve"
2216 sub fleshed_serial_subscription_retrieve_batch {
2217 my( $self, $client, $ids ) = @_;
2218 # FIXME: permissions?
2219 $logger->info("Fetching fleshed subscriptions @$ids");
2220 return $U->cstorereq(
2221 "open-ils.cstore.direct.serial.subscription.search.atomic",
2224 flesh_fields => {ssub => [ qw/owning_lib notes/ ]}
2228 __PACKAGE__->register_method(
2229 method => "retrieve_sub_tree",
2231 api_name => "open-ils.serial.subscription_tree.retrieve"
2234 __PACKAGE__->register_method(
2235 method => "retrieve_sub_tree",
2236 api_name => "open-ils.serial.subscription_tree.global.retrieve"
2239 sub retrieve_sub_tree {
2241 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2243 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2247 # TODO: permission support
2248 if(!@org_ids and $user_session) {
2250 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2251 @org_ids = ($user_obj->home_ou);
2254 if( $self->api_name =~ /global/ ) {
2255 return _build_subs_list( { record_entry => $docid } ); # TODO: filter for !deleted, or active?
2260 for my $orgid (@org_ids) {
2261 my $subs = _build_subs_list(
2262 { record_entry => $docid, owning_lib => $orgid } );# TODO: filter for !deleted, or active?
2263 push( @all_subs, @$subs );
2272 sub _build_subs_list {
2273 my $search_hash = shift;
2275 #$search_hash->{deleted} = 'f';
2276 my $e = new_editor();
2278 my $subs = $e->search_serial_subscription([$search_hash, { 'order_by' => {'ssub' => 'id'} }]);
2282 for my $sub (@$subs) {
2284 # TODO: filter on !deleted?
2285 my $dists = $e->search_serial_distribution(
2286 [{ subscription => $sub->id }, { 'order_by' => {'sdist' => 'label'} }]
2289 #$dists = [ sort { $a->label cmp $b->label } @$dists ];
2291 $sub->distributions($dists);
2293 # TODO: filter on !deleted?
2294 my $issuances = $e->search_serial_issuance(
2295 [{ subscription => $sub->id }, { 'order_by' => {'siss' => 'label'} }]
2298 #$issuances = [ sort { $a->label cmp $b->label } @$issuances ];
2299 $sub->issuances($issuances);
2301 # TODO: filter on !deleted?
2302 my $scaps = $e->search_serial_caption_and_pattern(
2303 [{ subscription => $sub->id }, { 'order_by' => {'scap' => 'id'} }]
2306 #$scaps = [ sort { $a->id cmp $b->id } @$scaps ];
2307 $sub->scaps($scaps);
2308 push( @built_subs, $sub );
2311 return \@built_subs;
2315 __PACKAGE__->register_method(
2316 method => "subscription_orgs_for_title",
2318 api_name => "open-ils.serial.subscription.retrieve_orgs_by_title"
2321 sub subscription_orgs_for_title {
2322 my( $self, $client, $record_id ) = @_;
2324 my $subs = $U->simple_scalar_request(
2326 "open-ils.cstore.direct.serial.subscription.search.atomic",
2327 { record_entry => $record_id }); # TODO: filter on !deleted?
2329 my $orgs = { map {$_->owning_lib => 1 } @$subs };
2330 return [ keys %$orgs ];
2334 ##########################################################################
2335 # distribution methods
2337 __PACKAGE__->register_method(
2338 method => 'fleshed_sdist_alter',
2339 api_name => 'open-ils.serial.distribution.fleshed.batch.update',
2343 desc => 'Receives an array of one or more distributions and updates the database as needed',
2345 name => 'authtoken',
2346 desc => 'Authtoken for current user session',
2350 name => 'distributions',
2351 desc => 'Array of fleshed distributions',
2357 desc => 'Returns 1 if successful, event if failed',
2363 sub fleshed_sdist_alter {
2364 my( $self, $conn, $auth, $sdists ) = @_;
2365 return 1 unless ref $sdists;
2366 my( $reqr, $evt ) = $U->checkses($auth);
2367 return $evt if $evt;
2368 my $editor = new_editor(requestor => $reqr, xact => 1);
2369 my $override = $self->api_name =~ /override/;
2371 for my $sdist (@$sdists) {
2372 my $holding_lib_id = ref $sdist->holding_lib ? $sdist->holding_lib->id : $sdist->holding_lib;
2373 return $editor->die_event unless
2374 $editor->allowed("ADMIN_SERIAL_DISTRIBUTION", $holding_lib_id);
2376 if( $sdist->isdeleted ) {
2377 $evt = _delete_sdist( $editor, $override, $sdist);
2378 } elsif( $sdist->isnew ) {
2379 $evt = _create_sdist( $editor, $sdist );
2381 $evt = _update_sdist( $editor, $override, $sdist );
2386 $logger->info("fleshed distribution-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2390 $logger->debug("distribution-alter: done updating distribution batch");
2392 $logger->info("fleshed distribution-alter successfully updated ".scalar(@$sdists)." distributions");
2397 my ($editor, $override, $sdist) = @_;
2398 $logger->info("distribution-alter: delete distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2399 return $editor->event unless $editor->delete_serial_distribution($sdist);
2404 my ($editor, $sdist) = @_;
2406 $logger->info("distribution-alter: new distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2407 return $editor->event unless $editor->create_serial_distribution($sdist);
2409 # create summaries too
2410 my $summary = new Fieldmapper::serial::basic_summary;
2411 $summary->distribution($sdist->id);
2412 $summary->generated_coverage('');
2413 return $editor->event unless $editor->create_serial_basic_summary($summary);
2414 $summary = new Fieldmapper::serial::supplement_summary;
2415 $summary->distribution($sdist->id);
2416 $summary->generated_coverage('');
2417 return $editor->event unless $editor->create_serial_supplement_summary($summary);
2418 $summary = new Fieldmapper::serial::index_summary;
2419 $summary->distribution($sdist->id);
2420 $summary->generated_coverage('');
2421 return $editor->event unless $editor->create_serial_index_summary($summary);
2423 # create a starter stream (TODO: reconsider this)
2424 my $stream = new Fieldmapper::serial::stream;
2425 $stream->distribution($sdist->id);
2426 return $editor->event unless $editor->create_serial_stream($stream);
2432 my ($editor, $override, $sdist) = @_;
2434 $logger->info("distribution-alter: retrieving distribution ".$sdist->id);
2435 my $orig_sdist = $editor->retrieve_serial_distribution($sdist->id);
2437 $logger->info("distribution-alter: original distribution ".OpenSRF::Utils::JSON->perl2JSON($orig_sdist));
2438 $logger->info("distribution-alter: updated distribution ".OpenSRF::Utils::JSON->perl2JSON($sdist));
2439 return $editor->event unless $editor->update_serial_distribution($sdist);
2443 __PACKAGE__->register_method(
2444 method => "fleshed_serial_distribution_retrieve_batch",
2446 api_name => "open-ils.serial.distribution.fleshed.batch.retrieve"
2449 sub fleshed_serial_distribution_retrieve_batch {
2450 my( $self, $client, $ids ) = @_;
2451 # FIXME: permissions?
2452 $logger->info("Fetching fleshed distributions @$ids");
2453 return $U->cstorereq(
2454 "open-ils.cstore.direct.serial.distribution.search.atomic",
2457 flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams / ]}
2461 __PACKAGE__->register_method(
2462 method => "retrieve_dist_tree",
2464 api_name => "open-ils.serial.distribution_tree.retrieve"
2467 __PACKAGE__->register_method(
2468 method => "retrieve_dist_tree",
2469 api_name => "open-ils.serial.distribution_tree.global.retrieve"
2472 sub retrieve_dist_tree {
2473 my( $self, $client, $user_session, $docid, @org_ids ) = @_;
2475 if(ref($org_ids[0])) { @org_ids = @{$org_ids[0]}; }
2479 # TODO: permission support
2480 if(!@org_ids and $user_session) {
2482 OpenILS::Application::AppUtils->check_user_session( $user_session ); #throws EX on error
2483 @org_ids = ($user_obj->home_ou);
2486 my $e = new_editor();
2488 if( $self->api_name =~ /global/ ) {
2489 return $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }},
2491 flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams basic_summary supplement_summary index_summary / ]},
2492 order_by => {'sdist' => 'id'},
2493 'join' => {'ssub' => {}}
2495 ]); # TODO: filter for !deleted?
2499 for my $orgid (@org_ids) {
2500 my $dists = $e->search_serial_distribution([{'+ssub' => { record_entry => $docid }, holding_lib => $orgid},
2502 flesh_fields => {sdist => [ qw/ holding_lib receive_call_number receive_unit_template bind_call_number bind_unit_template streams basic_summary supplement_summary index_summary / ]},
2503 order_by => {'sdist' => 'id'},
2504 'join' => {'ssub' => {}}
2506 ]); # TODO: filter for !deleted?
2507 push( @all_dists, @$dists ) if $dists;
2517 __PACKAGE__->register_method(
2518 method => "distribution_orgs_for_title",
2520 api_name => "open-ils.serial.distribution.retrieve_orgs_by_title"
2523 sub distribution_orgs_for_title {
2524 my( $self, $client, $record_id ) = @_;
2526 my $dists = $U->cstorereq(
2527 "open-ils.cstore.direct.serial.distribution.search.atomic",
2528 { '+ssub' => { record_entry => $record_id } },
2529 { 'join' => {'ssub' => {}} }); # TODO: filter on !deleted?
2531 my $orgs = { map {$_->holding_lib => 1 } @$dists };
2532 return [ keys %$orgs ];
2536 ##########################################################################
2537 # caption and pattern methods
2539 __PACKAGE__->register_method(
2540 method => 'scap_alter',
2541 api_name => 'open-ils.serial.caption_and_pattern.batch.update',
2545 desc => 'Receives an array of one or more caption and patterns and updates the database as needed',
2547 name => 'authtoken',
2548 desc => 'Authtoken for current user session',
2553 desc => 'Array of caption and patterns',
2559 desc => 'Returns 1 if successful, event if failed',
2566 my( $self, $conn, $auth, $scaps ) = @_;
2567 return 1 unless ref $scaps;
2568 my( $reqr, $evt ) = $U->checkses($auth);
2569 return $evt if $evt;
2570 my $editor = new_editor(requestor => $reqr, xact => 1);
2571 my $override = $self->api_name =~ /override/;
2574 for my $scap (@$scaps) {
2575 if (!exists($found_ssub_ids{$scap->subscription})) {
2576 my $ssub = $editor->retrieve_serial_subscription($scap->subscription) or return $editor->die_event;
2577 return $editor->die_event unless
2578 $editor->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $ssub->owning_lib);
2579 $found_ssub_ids{$scap->subscription} = 1;
2582 if( $scap->isdeleted ) {
2583 $evt = _delete_scap( $editor, $override, $scap);
2584 } elsif( $scap->isnew ) {
2585 $evt = _create_scap( $editor, $scap );
2587 $evt = _update_scap( $editor, $override, $scap );
2592 $logger->info("caption_and_pattern-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2596 $logger->debug("caption_and_pattern-alter: done updating caption_and_pattern batch");
2598 $logger->info("caption_and_pattern-alter successfully updated ".scalar(@$scaps)." caption_and_patterns");
2603 my ($editor, $override, $scap) = @_;
2604 $logger->info("caption_and_pattern-alter: delete caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2605 my $sisses = $editor->search_serial_issuance(
2606 { caption_and_pattern => $scap->id }, { limit => 1 } ); #TODO: 'deleted' support?
2607 return OpenILS::Event->new(
2608 'SERIAL_CAPTION_AND_PATTERN_HAS_ISSUANCES', payload => $scap->id ) if (@$sisses);
2610 return $editor->event unless $editor->delete_serial_caption_and_pattern($scap);
2615 my ($editor, $scap) = @_;
2617 $logger->info("caption_and_pattern-alter: new caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2618 return $editor->event unless $editor->create_serial_caption_and_pattern($scap);
2623 my ($editor, $override, $scap) = @_;
2625 $logger->info("caption_and_pattern-alter: retrieving caption_and_pattern ".$scap->id);
2626 my $orig_scap = $editor->retrieve_serial_caption_and_pattern($scap->id);
2628 $logger->info("caption_and_pattern-alter: original caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($orig_scap));
2629 $logger->info("caption_and_pattern-alter: updated caption_and_pattern ".OpenSRF::Utils::JSON->perl2JSON($scap));
2630 return $editor->event unless $editor->update_serial_caption_and_pattern($scap);
2634 __PACKAGE__->register_method(
2635 method => "serial_caption_and_pattern_retrieve_batch",
2637 api_name => "open-ils.serial.caption_and_pattern.batch.retrieve"
2640 sub serial_caption_and_pattern_retrieve_batch {
2641 my( $self, $client, $ids ) = @_;
2642 $logger->info("Fetching caption_and_patterns @$ids");
2643 return $U->cstorereq(
2644 "open-ils.cstore.direct.serial.caption_and_pattern.search.atomic",
2649 ##########################################################################
2652 __PACKAGE__->register_method(
2653 method => 'sstr_alter',
2654 api_name => 'open-ils.serial.stream.batch.update',
2658 desc => 'Receives an array of one or more streams and updates the database as needed',
2660 name => 'authtoken',
2661 desc => 'Authtoken for current user session',
2666 desc => 'Array of streams',
2672 desc => 'Returns 1 if successful, event if failed',
2679 my( $self, $conn, $auth, $sstrs ) = @_;
2680 return 1 unless ref $sstrs;
2681 my( $reqr, $evt ) = $U->checkses($auth);
2682 return $evt if $evt;
2683 my $editor = new_editor(requestor => $reqr, xact => 1);
2684 my $override = $self->api_name =~ /override/;
2686 my %found_sdist_ids;
2687 for my $sstr (@$sstrs) {
2688 if (!exists($found_sdist_ids{$sstr->distribution})) {
2689 my $sdist = $editor->retrieve_serial_distribution($sstr->distribution) or return $editor->die_event;
2690 return $editor->die_event unless
2691 $editor->allowed("ADMIN_SERIAL_STREAM", $sdist->holding_lib);
2692 $found_sdist_ids{$sstr->distribution} = 1;
2695 if( $sstr->isdeleted ) {
2696 $evt = _delete_sstr( $editor, $override, $sstr);
2697 } elsif( $sstr->isnew ) {
2698 $evt = _create_sstr( $editor, $sstr );
2700 $evt = _update_sstr( $editor, $override, $sstr );
2705 $logger->info("stream-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2709 $logger->debug("stream-alter: done updating stream batch");
2711 $logger->info("stream-alter successfully updated ".scalar(@$sstrs)." streams");
2716 my ($editor, $override, $sstr) = @_;
2717 $logger->info("stream-alter: delete stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2718 my $sitems = $editor->search_serial_item(
2719 { stream => $sstr->id }, { limit => 1 } ); #TODO: 'deleted' support?
2720 return OpenILS::Event->new(
2721 'SERIAL_STREAM_HAS_ITEMS', payload => $sstr->id ) if (@$sitems);
2723 return $editor->event unless $editor->delete_serial_stream($sstr);
2728 my ($editor, $sstr) = @_;
2730 $logger->info("stream-alter: new stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2731 return $editor->event unless $editor->create_serial_stream($sstr);
2736 my ($editor, $override, $sstr) = @_;
2738 $logger->info("stream-alter: retrieving stream ".$sstr->id);
2739 my $orig_sstr = $editor->retrieve_serial_stream($sstr->id);
2741 $logger->info("stream-alter: original stream ".OpenSRF::Utils::JSON->perl2JSON($orig_sstr));
2742 $logger->info("stream-alter: updated stream ".OpenSRF::Utils::JSON->perl2JSON($sstr));
2743 return $editor->event unless $editor->update_serial_stream($sstr);
2747 __PACKAGE__->register_method(
2748 method => "serial_stream_retrieve_batch",
2750 api_name => "open-ils.serial.stream.batch.retrieve"
2753 sub serial_stream_retrieve_batch {
2754 my( $self, $client, $ids ) = @_;
2755 $logger->info("Fetching streams @$ids");
2756 return $U->cstorereq(
2757 "open-ils.cstore.direct.serial.stream.search.atomic",
2763 ##########################################################################
2766 __PACKAGE__->register_method(
2767 method => 'sum_alter',
2768 api_name => 'open-ils.serial.basic_summary.batch.update',
2772 desc => 'Receives an array of one or more summaries and updates the database as needed',
2774 name => 'authtoken',
2775 desc => 'Authtoken for current user session',
2780 desc => 'Array of basic summaries',
2786 desc => 'Returns 1 if successful, event if failed',
2792 __PACKAGE__->register_method(
2793 method => 'sum_alter',
2794 api_name => 'open-ils.serial.supplement_summary.batch.update',
2798 desc => 'Receives an array of one or more summaries and updates the database as needed',
2800 name => 'authtoken',
2801 desc => 'Authtoken for current user session',
2806 desc => 'Array of supplement summaries',
2812 desc => 'Returns 1 if successful, event if failed',
2818 __PACKAGE__->register_method(
2819 method => 'sum_alter',
2820 api_name => 'open-ils.serial.index_summary.batch.update',
2824 desc => 'Receives an array of one or more summaries and updates the database as needed',
2826 name => 'authtoken',
2827 desc => 'Authtoken for current user session',
2832 desc => 'Array of index summaries',
2838 desc => 'Returns 1 if successful, event if failed',
2845 my( $self, $conn, $auth, $sums ) = @_;
2846 return 1 unless ref $sums;
2848 $self->api_name =~ /serial\.(\w*)_summary/;
2851 my( $reqr, $evt ) = $U->checkses($auth);
2852 return $evt if $evt;
2853 my $editor = new_editor(requestor => $reqr, xact => 1);
2854 my $override = $self->api_name =~ /override/;
2856 my %found_sdist_ids;
2857 for my $sum (@$sums) {
2858 if (!exists($found_sdist_ids{$sum->distribution})) {
2859 my $sdist = $editor->retrieve_serial_distribution($sum->distribution) or return $editor->die_event;
2860 return $editor->die_event unless
2861 $editor->allowed("ADMIN_SERIAL_DISTRIBUTION", $sdist->holding_lib);
2862 $found_sdist_ids{$sum->distribution} = 1;
2865 # XXX: (for now, at least) summaries should be created/deleted by the distribution functions
2866 if( $sum->isdeleted ) {
2867 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2868 } elsif( $sum->isnew ) {
2869 $evt = OpenILS::Event->new('SERIAL_SUMMARIES_NOT_INDEPENDENT');
2871 $evt = _update_sum( $editor, $override, $sum, $type );
2876 $logger->info("${type}_summary-alter failed with event: ".OpenSRF::Utils::JSON->perl2JSON($evt));
2880 $logger->debug("${type}_summary-alter: done updating ${type}_summary batch");
2882 $logger->info("${type}_summary-alter successfully updated ".scalar(@$sums)." ${type}_summaries");
2887 my ($editor, $override, $sum, $type) = @_;
2889 $logger->info("${type}_summary-alter: retrieving ${type}_summary ".$sum->id);
2890 my $retrieve_method = "retrieve_serial_${type}_summary";
2891 my $orig_sum = $editor->$retrieve_method($sum->id);
2893 $logger->info("${type}_summary-alter: original ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($orig_sum));
2894 $logger->info("${type}_summary-alter: updated ${type}_summary ".OpenSRF::Utils::JSON->perl2JSON($sum));
2895 my $update_method = "update_serial_${type}_summary";
2896 return $editor->event unless $editor->$update_method($sum);
2900 __PACKAGE__->register_method(
2901 method => "serial_summary_retrieve_batch",
2903 api_name => "open-ils.serial.basic_summary.batch.retrieve"
2906 __PACKAGE__->register_method(
2907 method => "serial_summary_retrieve_batch",
2909 api_name => "open-ils.serial.supplement_summary.batch.retrieve"
2912 __PACKAGE__->register_method(
2913 method => "serial_summary_retrieve_batch",
2915 api_name => "open-ils.serial.index_summary.batch.retrieve"
2918 sub serial_summary_retrieve_batch {
2919 my( $self, $client, $ids ) = @_;
2921 $self->api_name =~ /serial\.(\w*)_summary/;
2924 $logger->info("Fetching ${type}_summaries @$ids");
2925 return $U->cstorereq(
2926 "open-ils.cstore.direct.serial.".$type."_summary.search.atomic",
2932 ##########################################################################
2935 __PACKAGE__->register_method(
2936 "method" => "bre_by_identifier",
2937 "api_name" => "open-ils.serial.biblio.record_entry.by_identifier",
2940 "desc" => "Find instances of biblio.record_entry given a search token" .
2941 " that could be a value for any identifier defined in " .
2942 "config.metabib_field",
2944 {"desc" => "Search token", "type" => "string"},
2945 {"desc" => "Options: require_subscriptions, add_mvr, is_actual_id" .
2946 ", id_list (all boolean)", "type" => "object"}
2949 "desc" => "Any matching BREs, or if the add_mvr option is true, " .
2950 "objects with a 'bre' key/value pair, and an 'mvr' " .
2951 "key-value pair. BREs have subscriptions fleshed on.",
2957 sub bre_by_identifier {
2958 my ($self, $client, $term, $options) = @_;
2960 return new OpenILS::Event("BAD_PARAMS") unless $term;
2963 my $e = new_editor();
2967 if ($options->{"is_actual_id"}) {
2971 $e->search_config_metabib_field({"field_class" => "identifier"})
2972 or return $e->die_event;
2974 my @identifiers = map { $_->name } @$cmf;
2975 my $query = join(" || ", map { "id|$_: $term" } @identifiers);
2977 my $search = create OpenSRF::AppSession("open-ils.search");
2978 my $search_result = $search->request(
2979 "open-ils.search.biblio.multiclass.query.staff", {}, $query
2981 $search->disconnect;
2983 # Un-nest results. They tend to look like [[1],[2],[3]] for some reason.
2984 @ids = map { @{$_} } @{$search_result->{"ids"}};
2991 if ($options->{"id_list"}) {
2993 $client->respond($_) foreach (@ids);
2998 my $bre = $e->search_biblio_record_entry([
3000 "flesh" => 2, "flesh_fields" => {
3001 "bre" => ["subscriptions"],
3002 "ssub" => ["owning_lib"]
3005 ]) or return $e->die_event;
3007 if (@$bre && $options->{"require_subscriptions"}) {
3008 $bre = [ grep { @{$_->subscriptions} } @$bre ];
3013 if (@$bre) { # re-evaluate after possible grep
3014 if ($options->{"add_mvr"}) {
3016 {"bre" => $_, "mvr" => _get_mvr($_->id)}
3019 $client->respond($_) foreach (@$bre);
3026 __PACKAGE__->register_method(
3027 "method" => "get_items_by",
3028 "api_name" => "open-ils.serial.items.receivable.by_subscription",
3031 "desc" => "Return all receivable items under a given subscription",
3033 {"desc" => "Authtoken", "type" => "string"},
3034 {"desc" => "Subscription ID", "type" => "number"},
3037 "desc" => "All receivable items under a given subscription",
3038 "type" => "object", "class" => "sitem"
3043 __PACKAGE__->register_method(
3044 "method" => "get_items_by",
3045 "api_name" => "open-ils.serial.items.receivable.by_issuance",
3048 "desc" => "Return all receivable items under a given issuance",
3050 {"desc" => "Authtoken", "type" => "string"},
3051 {"desc" => "Issuance ID", "type" => "number"},
3054 "desc" => "All receivable items under a given issuance",
3055 "type" => "object", "class" => "sitem"
3060 __PACKAGE__->register_method(
3061 "method" => "get_items_by",
3062 "api_name" => "open-ils.serial.items.by_issuance",
3065 "desc" => "Return all items under a given issuance",
3067 {"desc" => "Authtoken", "type" => "string"},
3068 {"desc" => "Issuance ID", "type" => "number"},
3071 "desc" => "All items under a given issuance",
3072 "type" => "object", "class" => "sitem"
3078 my ($self, $client, $auth, $term, $opts) = @_;
3080 # Not to be used in the json_query, but after limiting by perm check.
3081 $opts = {} unless ref $opts eq "HASH";
3082 $opts->{"limit"} ||= 10000; # some existing users may want all results
3083 $opts->{"offset"} ||= 0;
3084 $opts->{"limit"} = int($opts->{"limit"});
3085 $opts->{"offset"} = int($opts->{"offset"});
3087 my $e = new_editor("authtoken" => $auth);
3088 return $e->die_event unless $e->checkauth;
3090 my $by = ($self->api_name =~ /by_(\w+)$/)[0];
3091 my $receivable = ($self->api_name =~ /receivable/);
3094 "issuance" => {"issuance" => $term},
3095 "subscription" => {"+siss" => {"subscription" => $term}}
3098 my $item_rows = $e->json_query(
3100 "select" => {"sitem" => ["id"], "sdist" => ["holding_lib"]},
3104 "sstr" => {"join" => {"sdist" => {}}}
3108 %{$where{$by}}, $receivable ? ("date_received" => undef) : ()
3110 "order_by" => {"sitem" => ["id"]}
3112 ) or return $e->die_event;
3114 return undef unless @$item_rows;
3118 foreach (@$item_rows) {
3119 last if $returned >= $opts->{"limit"};
3120 next unless $e->allowed("RECEIVE_SERIAL", $_->{"holding_lib"});
3121 if ($skipped < $opts->{"offset"}) {
3127 $e->retrieve_serial_item([
3131 "sitem" => [qw/stream issuance unit creator editor/],
3132 "sstr" => ["distribution"],
3133 "sdist" => ["holding_lib"]
3145 __PACKAGE__->register_method(
3146 "method" => "get_receivable_issuances",
3147 "api_name" => "open-ils.serial.issuances.receivable",
3150 "desc" => "Return all issuances with receivable items given " .
3151 "a subscription ID",
3153 {"desc" => "Authtoken", "type" => "string"},
3154 {"desc" => "Subscription ID", "type" => "number"},
3157 "desc" => "All issuances with receivable items " .
3158 "(but not the items themselves)", "type" => "object"
3163 sub get_receivable_issuances {
3164 my ($self, $client, $auth, $sub_id) = @_;
3166 my $e = new_editor("authtoken" => $auth);
3167 return $e->die_event unless $e->checkauth;
3171 my $issuance_ids = $e->json_query({
3174 {"transform" => "distinct", "column" => "id"},
3178 "from" => {"siss" => "sitem"},
3180 "subscription" => $sub_id,
3181 "+sitem" => {"date_received" => undef}
3184 "siss" => {"date_published" => {"direction" => "asc"}}
3187 }) or return $e->die_event;
3189 $client->respond($e->retrieve_serial_issuance($_->{"id"}))
3190 foreach (@$issuance_ids);
3197 __PACKAGE__->register_method(
3198 "method" => "get_routing_list_users",
3199 "api_name" => "open-ils.serial.routing_list_users.fleshed_and_ordered",
3202 "desc" => "Return all routing list users with reader fleshed " .
3203 "(with card and home_ou) for a given stream ID, sorted by pos",
3205 {"desc" => "Authtoken", "type" => "string"},
3206 {"desc" => "Stream ID (int or array of ints)", "type" => "mixed"},
3209 "desc" => "Stream of routing list users", "type" => "object",
3215 sub get_routing_list_users {
3216 my ($self, $client, $auth, $stream_id) = @_;
3218 my $e = new_editor("authtoken" => $auth);
3219 return $e->die_event unless $e->checkauth;
3221 my $users = $e->search_serial_routing_list_user([
3222 {"stream" => $stream_id}, {
3223 "order_by" => {"srlu" => "pos"},
3226 "srlu" => [qw/reader stream/],
3227 "au" => [qw/card home_ou/],
3228 "sstr" => ["distribution"]
3231 ]) or return $e->die_event;
3233 return undef unless @$users;
3235 # The ADMIN_SERIAL_STREAM permission is used simply to avoid the
3236 # need for any new permission. The context OU will be the same
3237 # for every result of the above query, so we need only check once.
3238 return $e->die_event unless $e->allowed(
3239 "ADMIN_SERIAL_STREAM", $users->[0]->stream->distribution->holding_lib
3244 my @users = map { $_->stream($_->stream->id); $_ } @$users;
3245 @users = sort { $a->stream cmp $b->stream } @users if
3246 ref $stream_id eq "ARRAY";
3248 $client->respond($_) for @users;
3254 __PACKAGE__->register_method(
3255 "method" => "replace_routing_list_users",
3256 "api_name" => "open-ils.serial.routing_list_users.replace",
3258 "desc" => "Replace all routing list users on the specified streams " .
3259 "with those in the list argument",
3261 {"desc" => "Authtoken", "type" => "string"},
3262 {"desc" => "List of srlu objects", "type" => "array"},
3265 "desc" => "event on failure, undef on success"
3270 sub replace_routing_list_users {
3271 my ($self, $client, $auth, $users) = @_;
3273 return undef unless ref $users eq "ARRAY";
3275 if (grep { ref $_ ne "Fieldmapper::serial::routing_list_user" } @$users) {
3276 return new OpenILS::Event("BAD_PARAMS", "note" => "Only srlu objects");
3279 my $e = new_editor("authtoken" => $auth, "xact" => 1);
3280 return $e->die_event unless $e->checkauth;
3282 my %streams_ok = ();
3285 foreach my $user (@$users) {
3286 unless (exists $streams_ok{$user->stream}) {
3287 my $stream = $e->retrieve_serial_stream([
3290 "flesh_fields" => {"sstr" => ["distribution"]}
3292 ]) or return $e->die_event;
3294 "ADMIN_SERIAL_STREAM", $stream->distribution->holding_lib
3295 ) or return $e->die_event;
3297 my $to_delete = $e->search_serial_routing_list_user(
3298 {"stream" => $user->stream}
3299 ) or return $e->die_event;
3302 "Deleting srlu: [" .
3303 join(", ", map { $_->id; } @$to_delete) .
3307 foreach (@$to_delete) {
3308 $e->delete_serial_routing_list_user($_) or
3309 return $e->die_event;
3312 $streams_ok{$user->stream} = 1;
3315 next if $user->isdeleted;
3319 $e->create_serial_routing_list_user($user) or return $e->die_event;
3322 $e->commit or return $e->die_event;
3326 __PACKAGE__->register_method(
3327 "method" => "get_records_with_marc_85x",
3328 "api_name"=>"open-ils.serial.caption_and_pattern.find_legacy_by_bib_record",
3331 "desc" => "Return the specified BRE itself and/or any related SRE ".
3332 "whenever they have 853-855 tags",
3334 {"desc" => "Authtoken", "type" => "string"},
3335 {"desc" => "bib record ID", "type" => "number"},
3338 "desc" => "objects, either bre or sre", "type" => "object"
3343 sub get_records_with_marc_85x { # specifically, 853-855
3344 my ($self, $client, $auth, $bre_id) = @_;
3346 my $e = new_editor("authtoken" => $auth);
3347 return $e->die_event unless $e->checkauth;
3349 my $bre = $e->search_biblio_record_entry([
3350 {"id" => $bre_id, "deleted" => "f"}, {
3352 "flesh_fields" => {"bre" => [qw/creator editor owner/]}
3354 ]) or return $e->die_event;
3356 return undef unless @$bre;
3359 my $record = MARC::Record->new_from_xml($bre->marc);
3360 $client->respond($bre) if $record->field("85[3-5]");
3361 # XXX Is passing a regex to ->field() an abuse of MARC::Record ?
3363 my $sres = $e->search_serial_record_entry([
3364 {"record" => $bre_id, "deleted" => "f"}, {
3366 "flesh_fields" => {"sre" => [qw/creator editor owning_lib/]}
3368 ]) or return $e->die_event;
3372 foreach my $sre (@$sres) {
3373 $client->respond($sre) if
3374 MARC::Record->new_from_xml($sre->marc)->field("85[3-5]");
3380 __PACKAGE__->register_method(
3381 "method" => "create_scaps_from_marcxml",
3382 "api_name" => "open-ils.serial.caption_and_pattern.create_from_records",
3385 "desc" => "Create caption and pattern objects from 853-855 tags " .
3386 "in MARCXML documents",
3388 {"desc" => "Authtoken", "type" => "string"},
3389 {"desc" => "Subscription ID", "type" => "number"},
3390 {"desc" => "list of MARCXML documents as strings",
3394 "desc" => "Newly created caption and pattern objects",
3395 "type" => "object", "class" => "scap"
3400 sub create_scaps_from_marcxml {
3401 my ($self, $client, $auth, $sub_id, $docs) = @_;
3403 return undef unless ref $docs eq "ARRAY";
3405 my $e = new_editor("authtoken" => $auth, "xact" => 1);
3406 return $e->die_event unless $e->checkauth;
3408 # Retrieve the subscription just for perm checking (whether we can create
3409 # scaps at the owning lib).
3410 my $sub = $e->retrieve_serial_subscription($sub_id) or return $e->die_event;
3411 return $e->die_event unless
3412 $e->allowed("ADMIN_SERIAL_CAPTION_PATTERN", $sub->owning_lib);
3414 foreach my $record (map { MARC::Record->new_from_xml($_) } @$docs) {
3415 foreach my $field ($record->field("85[3-5]")) {
3416 my $scap = new Fieldmapper::serial::caption_and_pattern;
3417 $scap->subscription($sub_id);
3418 $scap->type($MFHD_NAMES_BY_TAG{$field->tag});
3419 $scap->pattern_code(
3420 OpenSRF::Utils::JSON->perl2JSON(
3421 [ $field->indicator(1), $field->indicator(2),
3422 map { @$_ } $field->subfields ] # flattens nested array
3425 $e->create_serial_caption_and_pattern($scap) or
3426 return $e->die_event;
3427 $client->respond($e->data);
3431 $e->commit or return $e->die_event;
3435 # All these _clone_foo() functions could possibly have been consolidated into
3436 # one clever function, but it's faster to get things working this way.
3437 sub _clone_subscription {
3438 my ($sub, $bib_id, $e) = @_;
3441 my $new_sub = $sub->clone;
3442 $new_sub->record_entry(int $bib_id) if $bib_id;
3444 $new_sub->clear_distributions;
3445 $new_sub->clear_notes;
3446 $new_sub->clear_scaps;
3448 $e->create_serial_subscription($new_sub) or return $e->die_event;
3450 my $new_sub_id = $e->data->id;
3452 foreach my $dist (@{$sub->distributions}) {
3453 my $r = _clone_distribution($dist, $new_sub_id, $e);
3454 return $r if $U->event_code($r);
3458 foreach my $note (@{$sub->notes}) {
3459 my $r = _clone_subscription_note($note, $new_sub_id, $e);
3460 return $r if $U->event_code($r);
3464 foreach my $scap (@{$sub->scaps}) {
3465 my $r = _clone_caption_and_pattern($scap, $new_sub_id, $e);
3466 return $r if $U->event_code($r);
3472 sub _clone_distribution {
3473 my ($dist, $sub_id, $e) = @_;
3475 my $new_dist = $dist->clone;
3476 $new_dist->clear_id;
3477 $new_dist->clear_notes;
3478 $new_dist->clear_streams;
3479 $new_dist->subscription($sub_id);
3481 $e->create_serial_distribution($new_dist) or return $e->die_event;
3482 my $new_dist_id = $e->data->id;
3485 foreach my $stream (@{$dist->streams}) {
3486 my $r = _clone_stream($stream, $new_dist_id, $e);
3487 return $r if $U->event_code($r);
3490 # clone distribution notes
3491 foreach my $note (@{$dist->notes}) {
3492 my $r = _clone_distribution_note($note, $new_dist_id, $e);
3493 return $r if $U->event_code($r);
3496 return $new_dist_id;
3499 sub _clone_subscription_note {
3500 my ($note, $sub_id, $e) = @_;
3502 my $new_note = $note->clone;
3503 $new_note->clear_id;
3504 $new_note->creator($e->requestor->id);
3505 $new_note->create_date("now");
3506 $new_note->subscription($sub_id);
3508 $e->create_serial_subscription_note($new_note) or return $e->die_event;
3509 return $e->data->id;
3512 sub _clone_caption_and_pattern {
3513 my ($scap, $sub_id, $e) = @_;
3515 my $new_scap = $scap->clone;
3516 $new_scap->clear_id;
3517 $new_scap->subscription($sub_id);
3519 $e->create_serial_caption_and_pattern($new_scap) or return $e->die_event;
3520 return $e->data->id;
3523 sub _clone_distribution_note {
3524 my ($note, $dist_id, $e) = @_;
3526 my $new_note = $note->clone;
3527 $new_note->clear_id;
3528 $new_note->creator($e->requestor->id);
3529 $new_note->create_date("now");
3530 $new_note->distribution($dist_id);
3532 $e->create_serial_distribution_note($new_note) or return $e->die_event;
3533 return $e->data->id;
3537 my ($stream, $dist_id, $e) = @_;
3539 my $new_stream = $stream->clone;
3540 $new_stream->clear_id;
3541 $new_stream->clear_routing_list_users;
3542 $new_stream->distribution($dist_id);
3544 $e->create_serial_stream($new_stream) or return $e->die_event;
3545 my $new_stream_id = $e->data->id;
3547 # clone routing list users
3548 foreach my $user (@{$stream->routing_list_users}) {
3549 my $r = _clone_routing_list_user($user, $new_stream_id, $e);
3550 return $r if $U->event_code($r);
3553 return $new_stream_id;
3556 sub _clone_routing_list_user {
3557 my ($user, $stream_id, $e) = @_;
3559 my $new_user = $user->clone;
3560 $new_user->clear_id;
3561 $new_user->stream($stream_id);
3563 $e->create_serial_routing_list_user($new_user) or return $e->die_event;
3564 return $e->data->id;
3567 __PACKAGE__->register_method(
3568 "method" => "clone_subscription",
3569 "api_name" => "open-ils.serial.subscription.clone",
3571 "desc" => q{Clone a subscription, including its attending distributions,
3572 streams, captions and patterns, routing list users, distribution
3573 notes and subscription notes. Do not include holdings-specific
3574 things, like issuances, items, units, summaries. Attach the
3575 clone either to the same bib record as the original, or to one
3578 {"desc" => "Authtoken", "type" => "string"},
3579 {"desc" => "Subscription ID", "type" => "number"},
3580 {"desc" => "Bib Record ID (optional)", "type" => "number"}
3583 "desc" => "ID of the new subscription", "type" => "number"
3588 sub clone_subscription {
3589 my ($self, $client, $auth, $sub_id, $bib_id) = @_;
3591 my $e = new_editor("authtoken" => $auth, "xact" => 1);
3592 return $e->die_event unless $e->checkauth;
3594 my $sub = $e->retrieve_serial_subscription([
3598 "ssub" => [qw/distributions notes scaps/],
3599 "sdist" => [qw/streams notes/],
3600 "sstr" => ["routing_list_users"]
3603 ]) or return $e->die_event;
3605 # ADMIN_SERIAL_SUBSCRIPTION will have to be good enough as a
3606 # catch-all permisison for this operation.
3607 return $e->die_event unless
3608 $e->allowed("ADMIN_SERIAL_SUBSCRIPTION", $sub->owning_lib);
3610 my $result = _clone_subscription($sub, $bib_id, $e);
3612 return $e->die_event($result) if $U->event_code($result);
3614 $e->commit or return $e->die_event;