1 package OpenILS::Application::Acq::BatchManager;
2 use OpenILS::Application::Acq::Financials;
3 use OpenSRF::AppSession;
4 use OpenSRF::EX qw/:try/;
5 use strict; use warnings;
8 my($class, %args) = @_;
9 my $self = bless(\%args, $class);
18 purchase_order => undef,
26 $self->throttle(4) unless $self->throttle;
27 $self->{post_proc_queue} = [];
28 $self->{last_respond_progress} = 0;
34 $self->{conn} = $val if $val;
39 $self->{throttle} = $val if $val;
40 return $self->{throttle};
43 my($self, %other_args) = @_;
44 if($self->throttle and not %other_args) {
46 ($self->{args}->{progress} - $self->{last_respond_progress}) >= $self->throttle
49 $self->conn->respond({ %{$self->{args}}, %other_args });
50 $self->{last_respond_progress} = $self->{args}->{progress};
51 $self->throttle($self->throttle * 2) unless $self->throttle >= 256;
53 sub respond_complete {
54 my($self, %other_args) = @_;
56 $self->conn->respond_complete({ %{$self->{args}}, %other_args });
57 $self->run_post_response_hooks;
61 # run the post response hook subs, shifting them off as we go
62 sub run_post_response_hooks {
64 (shift @{$self->{post_proc_queue}})->() while @{$self->{post_proc_queue}};
67 # any subs passed to this method will be run after the call to respond_complete
70 push(@{$self->{post_proc_queue}}, $sub);
75 $self->{args}->{total} = $val if defined $val;
76 $self->{args}->{maximum} = $self->{args}->{total};
77 return $self->{args}->{total};
81 $self->{args}->{purchase_order} = $val if $val;
86 $self->{args}->{picklist} = $val if $val;
91 $self->{args}->{lid} += 1;
92 $self->{args}->{progress} += 1;
97 $self->{args}->{li} += 1;
98 $self->{args}->{progress} += 1;
103 $self->{args}->{vqbr} += 1;
104 $self->{args}->{progress} += 1;
109 $self->{args}->{copies} += 1;
110 $self->{args}->{progress} += 1;
115 $self->{args}->{bibs} += 1;
116 $self->{args}->{progress} += 1;
120 my($self, $amount) = @_;
121 $self->{args}->{debits_accrued} += $amount;
122 $self->{args}->{progress} += 1;
126 my($self, $editor) = @_;
127 $self->{editor} = $editor if defined $editor;
128 return $self->{editor};
132 $self->{args}->{complete} = 1;
137 my($self, $org, $key, $val) = @_;
138 $self->{cache}->{$org} = {} unless $self->{cache}->{org};
139 $self->{cache}->{$org}->{$key} = $val if defined $val;
140 return $self->{cache}->{$org}->{$key};
144 package OpenILS::Application::Acq::Order;
145 use base qw/OpenILS::Application/;
146 use strict; use warnings;
147 # ----------------------------------------------------------------------------
148 # Break up each component of the order process and pieces into managable
149 # actions that can be shared across different workflows
150 # ----------------------------------------------------------------------------
152 use OpenSRF::Utils::Logger qw(:logger);
153 use OpenSRF::Utils::JSON;
154 use OpenSRF::AppSession;
155 use OpenILS::Utils::Fieldmapper;
156 use OpenILS::Utils::CStoreEditor q/:funcs/;
157 use OpenILS::Utils::Normalize qw/clean_marc/;
158 use OpenILS::Const qw/:const/;
159 use OpenSRF::EX q/:try/;
160 use OpenILS::Application::AppUtils;
161 use OpenILS::Application::Cat::BibCommon;
162 use OpenILS::Application::Cat::AssetCommon;
165 use MARC::File::XML (BinaryEncoding => 'UTF-8');
166 use Digest::MD5 qw(md5_hex);
168 $Data::Dumper::Indent = 0;
169 my $U = 'OpenILS::Application::AppUtils';
172 # ----------------------------------------------------------------------------
174 # ----------------------------------------------------------------------------
175 sub create_lineitem {
176 my($mgr, %args) = @_;
177 my $li = Fieldmapper::acq::lineitem->new;
178 $li->creator($mgr->editor->requestor->id);
179 $li->selector($li->creator);
180 $li->editor($li->creator);
181 $li->create_time('now');
182 $li->edit_time('now');
184 $li->$_($args{$_}) for keys %args;
187 $mgr->editor->create_acq_lineitem($li) or return 0;
189 unless($li->estimated_unit_price) {
190 # extract the price from the MARC data
191 my $price = get_li_price_from_attr($mgr->editor, $li) or return $li;
192 $li->estimated_unit_price($price);
193 return update_lineitem($mgr, $li);
199 sub get_li_price_from_attr {
201 my $attrs = $li->attributes || $e->search_acq_lineitem_attr({lineitem => $li->id});
203 for my $attr_type (qw/
204 lineitem_local_attr_definition
205 lineitem_prov_attr_definition
206 lineitem_marc_attr_definition/) {
209 $_->attr_name eq 'estimated_price' and
210 $_->attr_type eq $attr_type } @$attrs;
212 return $attr->attr_value if $attr;
219 sub update_lineitem {
221 $li->edit_time('now');
222 $li->editor($mgr->editor->requestor->id);
224 return $mgr->editor->retrieve_acq_lineitem($mgr->editor->data) if
225 $mgr->editor->update_acq_lineitem($li);
230 # ----------------------------------------------------------------------------
231 # Create real holds from patron requests for a given lineitem
232 # ----------------------------------------------------------------------------
233 sub promote_lineitem_holds {
236 my $requests = $mgr->editor->search_acq_user_request(
237 { lineitem => $li->id,
239 [ { need_before => {'>' => 'now'} },
240 { need_before => undef }
245 for my $request ( @$requests ) {
247 $request->eg_bib( $li->eg_bib_id );
248 $mgr->editor->update_acq_user_request( $request ) or return 0;
250 next unless ($U->is_true( $request->hold ));
252 my $hold = Fieldmapper::action::hold_request->new;
253 $hold->usr( $request->usr );
254 $hold->requestor( $request->usr );
255 $hold->request_time( $request->request_date );
256 $hold->pickup_lib( $request->pickup_lib );
257 $hold->request_lib( $request->pickup_lib );
258 $hold->selection_ou( $request->pickup_lib );
259 $hold->phone_notify( $request->phone_notify );
260 $hold->email_notify( $request->email_notify );
261 $hold->expire_time( $request->need_before );
263 if ($request->holdable_formats) {
264 my $mrm = $mgr->editor->search_metabib_metarecord_source_map( { source => $li->eg_bib_id } )->[0];
266 $hold->hold_type( 'M' );
267 $hold->holdable_formats( $request->holdable_formats );
268 $hold->target( $mrm->metarecord );
272 if (!$hold->target) {
273 $hold->hold_type( 'T' );
274 $hold->target( $li->eg_bib_id );
277 $mgr->editor->create_action_hold_request( $hold ) or return 0;
283 sub delete_lineitem {
285 $li = $mgr->editor->retrieve_acq_lineitem($li) unless ref $li;
287 # delete the attached lineitem_details
288 my $lid_ids = $mgr->editor->search_acq_lineitem_detail({lineitem => $li->id}, {idlist=>1});
289 for my $lid_id (@$lid_ids) {
290 return 0 unless delete_lineitem_detail($mgr, $lid_id);
294 return $mgr->editor->delete_acq_lineitem($li);
297 # begins and commit transactions as it goes
298 # bib_only exits before creation of copies and callnumbers
299 sub create_lineitem_list_assets {
300 my($mgr, $li_ids, $vandelay, $bib_only) = @_;
302 if (check_import_li_marc_perms($mgr, $li_ids)) { # event on error
303 $logger->error("acq-vl: user does not have permission to import acq records");
307 my $res = import_li_bibs_via_vandelay($mgr, $li_ids, $vandelay);
308 return undef unless $res;
309 return $res if $bib_only;
311 # create the bibs/volumes/copies for the successfully imported records
312 for my $li_id (@{$res->{li_ids}}) {
313 $mgr->editor->xact_begin;
314 my $data = create_lineitem_assets($mgr, $li_id) or return undef;
315 $mgr->editor->xact_commit;
322 sub test_vandelay_import_args {
323 my $vandelay = shift;
324 my $q_needed = shift;
326 # we need valid args and (sometimes) a queue
327 return 0 unless $vandelay and (
329 $vandelay->{queue_name} or
330 $vandelay->{existing_queue}
333 # match-based merge/overlay import
334 return 2 if $vandelay->{merge_profile} and (
335 $vandelay->{auto_overlay_exact} or
336 $vandelay->{auto_overlay_1match} or
337 $vandelay->{auto_overlay_best_match}
341 return 2 if $vandelay->{import_no_match};
343 return 1; # queue only
346 sub find_or_create_vandelay_queue {
347 my ($e, $vandelay) = @_;
350 if (my $name = $vandelay->{queue_name}) {
352 # first, see if a queue w/ this name already exists
353 # for this user. If so, use that instead.
355 $queue = $e->search_vandelay_bib_queue(
356 {name => $name, owner => $e->requestor->id})->[0];
360 $logger->info("acq-vl: using existing queue $name");
364 $logger->info("acq-vl: creating new vandelay queue $name");
366 $queue = new Fieldmapper::vandelay::bib_queue;
368 $queue->queue_type('acq');
369 $queue->owner($e->requestor->id);
370 $queue->match_set($vandelay->{match_set} || undef); # avoid ''
371 $queue = $e->create_vandelay_bib_queue($queue) or return undef;
375 $queue = $e->retrieve_vandelay_bib_queue($vandelay->{existing_queue})
383 sub import_li_bibs_via_vandelay {
384 my ($mgr, $li_ids, $vandelay) = @_;
385 my $res = {li_ids => []};
386 my $e = $mgr->editor;
389 my $needs_importing = $e->search_acq_lineitem(
390 {id => $li_ids, eg_bib_id => undef},
394 if (!@$needs_importing) {
395 $logger->info("acq-vl: all records already imported. no Vandelay work to do");
396 return {li_ids => $li_ids};
399 # see if we have any records that are not yet linked to VL records (i.e.
400 # not in a queue). This will tell us if lack of a queue name is an error.
401 my $non_queued = $e->search_acq_lineitem(
402 {id => $needs_importing, queued_record => undef},
406 # add the already-imported records to the response list
407 push(@{$res->{li_ids}}, grep { $_ != @$needs_importing } @$li_ids);
409 $logger->info("acq-vl: processing recs via Vandelay with args: ".Dumper($vandelay));
411 my $vl_stat = test_vandelay_import_args($vandelay, scalar(@$non_queued));
413 $logger->error("acq-vl: invalid vandelay arguments for acq import (queue needed)");
419 # when any non-queued lineitems exist, their vandelay counterparts
420 # require a place to live.
421 $queue = find_or_create_vandelay_queue($e, $vandelay) or return $res;
424 # if all lineitems are already queued, the queue reported to the user
425 # is purely for information / convenience. pick a random queue.
426 $queue = $e->retrieve_acq_lineitem([
427 $needs_importing->[0], {
430 jub => ['queued_record'],
434 ])->queued_record->queue;
437 $mgr->{args}->{queue} = $queue;
439 # load the lineitems into the queue for merge processing
442 for my $li_id (@$needs_importing) {
444 my $li = $e->retrieve_acq_lineitem($li_id) or return $res;
446 if ($li->queued_record) {
447 $logger->info("acq-vl: $li_id already linked to a vandelay record");
448 push(@vqbr_ids, $li->queued_record);
451 $logger->info("acq-vl: creating new vandelay record for lineitem $li_id");
453 # create a new VL queued record and link it up
454 my $vqbr = Fieldmapper::vandelay::queued_bib_record->new;
455 $vqbr->marc($li->marc);
456 $vqbr->queue($queue->id);
457 $vqbr->bib_source($vandelay->{bib_source} || undef); # avoid ''
458 $vqbr = $e->create_vandelay_queued_bib_record($vqbr) or return $res;
459 push(@vqbr_ids, $vqbr->id);
461 # tell the acq record which vandelay record it's linked to
462 $li->queued_record($vqbr->id);
463 $e->update_acq_lineitem($li) or return $res;
471 $logger->info("acq-vl: created vandelay records [@vqbr_ids]");
473 # we have to commit the transaction now since
474 # vandelay uses its own transactions.
477 return $res if $vl_stat == 1; # queue only
479 # Import the bibs via vandelay. Note: Vandely will
480 # update acq.lineitem.eg_bib_id on successful import.
482 $vandelay->{report_all} = 1;
483 my $ses = OpenSRF::AppSession->create('open-ils.vandelay');
484 my $req = $ses->request(
485 'open-ils.vandelay.bib_record.list.import',
486 $e->authtoken, \@vqbr_ids, $vandelay);
488 # pull the responses, noting all that were successfully imported
490 while (my $resp = $req->recv(timeout => 600)) {
491 my $stat = $resp->content;
493 if(!$stat or $U->event_code($stat)) { # import failure
494 $logger->error("acq-vl: error importing vandelay record " . Dumper($stat));
498 # "imported" refers to the vqbr id, not the
499 # success/failure of the vqbr merge attempt
500 next unless $stat->{imported};
502 my ($imported) = grep {$_->queued_record eq $stat->{imported}} @lis;
503 my $li_id = $imported->id;
505 if ($stat->{no_import}) {
506 $logger->info("acq-vl: acq lineitem $li_id did not import");
508 } else { # successful import
510 push(@success_lis, $li_id);
513 $logger->info("acq-vl: acq lineitem $li_id successfully merged/imported");
518 $logger->info("acq-vl: successfully imported lineitems [@success_lis]");
520 # add the successfully imported lineitems to the already-imported lineitems
521 push (@{$res->{li_ids}}, @success_lis);
526 # returns event on error, undef on success
527 sub check_import_li_marc_perms {
528 my($mgr, $li_ids) = @_;
530 # if there are any order records that are not linked to
531 # in-db bib records, verify staff has perms to import order records
532 my $order_li = $mgr->editor->search_acq_lineitem(
533 [{id => $li_ids, eg_bib_id => undef}, {limit => 1}], {idlist => 1})->[0];
536 return $mgr->editor->die_event unless
537 $mgr->editor->allowed('IMPORT_ACQ_LINEITEM_BIB_RECORD');
544 # ----------------------------------------------------------------------------
545 # if all of the lineitem details for this lineitem have
546 # been received, mark the lineitem as received
547 # returns 1 on non-received, li on received, 0 on error
548 # ----------------------------------------------------------------------------
550 sub describe_affected_po {
554 OpenILS::Application::Acq::Financials::build_price_summary(
559 "state" => $po->state,
560 "amount_encumbered" => $enc,
561 "amount_spent" => $spent
566 sub check_lineitem_received {
567 my($mgr, $li_id) = @_;
569 my $non_recv = $mgr->editor->search_acq_lineitem_detail(
570 {recv_time => undef, lineitem => $li_id}, {idlist=>1});
572 return 1 if @$non_recv;
574 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
575 $li->state('received');
576 return update_lineitem($mgr, $li);
579 sub receive_lineitem {
580 my($mgr, $li_id, $skip_complete_check) = @_;
581 my $li = $mgr->editor->retrieve_acq_lineitem($li_id) or return 0;
583 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
584 {lineitem => $li_id, recv_time => undef}, {idlist => 1});
586 for my $lid_id (@$lid_ids) {
587 receive_lineitem_detail($mgr, $lid_id, 1) or return 0;
591 $li->state('received');
593 $li = update_lineitem($mgr, $li) or return 0;
594 $mgr->post_process( sub { create_lineitem_status_events($mgr, $li_id, 'aur.received'); });
598 $skip_complete_check or (
599 $po = check_purchase_order_received($mgr, $li->purchase_order)
602 my $result = {"li" => {$li->id => {"state" => $li->state}}};
603 $result->{"po"} = describe_affected_po($mgr->editor, $po) if ref $po;
607 sub rollback_receive_lineitem {
608 my($mgr, $li_id) = @_;
609 my $li = $mgr->editor->retrieve_acq_lineitem($li_id) or return 0;
611 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
612 {lineitem => $li_id, recv_time => {'!=' => undef}}, {idlist => 1});
614 for my $lid_id (@$lid_ids) {
615 rollback_receive_lineitem_detail($mgr, $lid_id, 1) or return 0;
619 $li->state('on-order');
620 return update_lineitem($mgr, $li);
624 sub create_lineitem_status_events {
625 my($mgr, $li_id, $hook) = @_;
627 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
629 my $user_reqs = $mgr->editor->search_acq_user_request([
630 {lineitem => $li_id},
631 {flesh => 1, flesh_fields => {aur => ['usr']}}
634 for my $user_req (@$user_reqs) {
635 my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $user_req->usr->home_ou);
643 # ----------------------------------------------------------------------------
645 # ----------------------------------------------------------------------------
646 sub create_lineitem_detail {
647 my($mgr, %args) = @_;
648 my $lid = Fieldmapper::acq::lineitem_detail->new;
649 $lid->$_($args{$_}) for keys %args;
652 return $mgr->editor->create_acq_lineitem_detail($lid);
656 # flesh out any required data with default values where appropriate
657 sub complete_lineitem_detail {
659 unless($lid->barcode) {
660 my $pfx = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.tmp_barcode_prefix') || 'ACQ';
661 $lid->barcode($pfx.$lid->id);
664 unless($lid->cn_label) {
665 my $pfx = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.tmp_callnumber_prefix') || 'ACQ';
666 $lid->cn_label($pfx.$lid->id);
669 if(!$lid->location and my $loc = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.default_copy_location')) {
670 $lid->location($loc);
673 $lid->circ_modifier(get_default_circ_modifier($mgr, $lid->owning_lib))
674 unless defined $lid->circ_modifier;
676 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
680 sub get_default_circ_modifier {
682 my $code = $mgr->cache($org, 'def_circ_mod');
683 $code = $U->ou_ancestor_setting_value($org, 'acq.default_circ_modifier') unless defined $code;
684 return $mgr->cache($org, 'def_circ_mod', $code) if defined $code;
688 sub delete_lineitem_detail {
690 $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid) unless ref $lid;
691 return $mgr->editor->delete_acq_lineitem_detail($lid);
695 sub receive_lineitem_detail {
696 my($mgr, $lid_id, $skip_complete_check) = @_;
697 my $e = $mgr->editor;
699 my $lid = $e->retrieve_acq_lineitem_detail([
703 acqlid => ['fund_debit']
708 return 1 if $lid->recv_time;
710 $lid->receiver($e->requestor->id);
711 $lid->recv_time('now');
712 $e->update_acq_lineitem_detail($lid) or return 0;
714 if ($lid->eg_copy_id) {
715 my $copy = $e->retrieve_asset_copy($lid->eg_copy_id) or return 0;
716 # only update status if it hasn't already been updated
717 $copy->status(OILS_COPY_STATUS_IN_PROCESS) if $copy->status == OILS_COPY_STATUS_ON_ORDER;
718 $copy->edit_date('now');
719 $copy->editor($e->requestor->id);
720 $copy->creator($e->requestor->id) if $U->ou_ancestor_setting_value(
721 $e->requestor->ws_ou, 'acq.copy_creator_uses_receiver', $e);
722 $e->update_asset_copy($copy) or return 0;
727 return 1 if $skip_complete_check;
729 my $li = check_lineitem_received($mgr, $lid->lineitem) or return 0;
730 return 1 if $li == 1; # li not received
732 return check_purchase_order_received($mgr, $li->purchase_order) or return 0;
736 sub rollback_receive_lineitem_detail {
737 my($mgr, $lid_id) = @_;
738 my $e = $mgr->editor;
740 my $lid = $e->retrieve_acq_lineitem_detail([
744 acqlid => ['fund_debit']
749 return 1 unless $lid->recv_time;
751 $lid->clear_receiver;
752 $lid->clear_recv_time;
753 $e->update_acq_lineitem_detail($lid) or return 0;
755 if ($lid->eg_copy_id) {
756 my $copy = $e->retrieve_asset_copy($lid->eg_copy_id) or return 0;
757 $copy->status(OILS_COPY_STATUS_ON_ORDER);
758 $copy->edit_date('now');
759 $copy->editor($e->requestor->id);
760 $e->update_asset_copy($copy) or return 0;
767 # ----------------------------------------------------------------------------
769 # ----------------------------------------------------------------------------
770 sub set_lineitem_attr {
771 my($mgr, %args) = @_;
772 my $attr_type = $args{attr_type};
774 # first, see if it's already set. May just need to overwrite it
775 my $attr = $mgr->editor->search_acq_lineitem_attr({
776 lineitem => $args{lineitem},
777 attr_type => $args{attr_type},
778 attr_name => $args{attr_name}
782 $attr->attr_value($args{attr_value});
783 return $attr if $mgr->editor->update_acq_lineitem_attr($attr);
788 $attr = Fieldmapper::acq::lineitem_attr->new;
789 $attr->$_($args{$_}) for keys %args;
791 unless($attr->definition) {
792 my $find = "search_acq_$attr_type";
793 my $attr_def_id = $mgr->editor->$find({code => $attr->attr_name}, {idlist=>1})->[0] or return 0;
794 $attr->definition($attr_def_id);
796 return $mgr->editor->create_acq_lineitem_attr($attr);
800 # ----------------------------------------------------------------------------
802 # ----------------------------------------------------------------------------
803 sub create_lineitem_debits {
804 my ($mgr, $li, $dry_run, $options) = @_;
807 unless($li->estimated_unit_price) {
808 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_PRICE', payload => $li->id));
809 $mgr->editor->rollback;
813 unless($li->provider) {
814 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_PROVIDER', payload => $li->id));
815 $mgr->editor->rollback;
819 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
820 {lineitem => $li->id},
824 if (@$lid_ids == 0 and !$options->{zero_copy_activate}) {
825 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_COPIES', payload => $li->id));
826 $mgr->editor->rollback;
830 for my $lid_id (@$lid_ids) {
832 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
835 flesh_fields => {acqlid => ['fund']}
839 create_lineitem_detail_debit($mgr, $li, $lid, $dry_run) or return 0;
848 sub create_lineitem_detail_debit {
849 my ($mgr, $li, $lid, $dry_run, $no_translate) = @_;
851 # don't create the debit if one already exists
852 return $mgr->editor->retrieve_acq_fund_debit($lid->fund_debit) if $lid->fund_debit;
854 my $li_id = ref($li) ? $li->id : $li;
856 unless(ref $li and ref $li->provider) {
857 $li = $mgr->editor->retrieve_acq_lineitem([
860 flesh_fields => {jub => ['provider']},
866 $lid->fund($mgr->editor->retrieve_acq_fund($lid->fund)) unless(ref $lid->fund);
868 $lid = $mgr->editor->retrieve_acq_lineitem_detail([
871 flesh_fields => {acqlid => ['fund']}
876 unless ($lid->fund) {
878 new OpenILS::Event("ACQ_FUND_NOT_FOUND") # close enough
883 my $amount = $li->estimated_unit_price;
884 if($li->provider->currency_type ne $lid->fund->currency_type and !$no_translate) {
886 # At Fund debit creation time, translate into the currency of the fund
887 # TODO: org setting to disable automatic currency conversion at debit create time?
889 $amount = $mgr->editor->json_query({
891 'acq.exchange_ratio',
892 $li->provider->currency_type, # source currency
893 $lid->fund->currency_type, # destination currency
894 $li->estimated_unit_price # source amount
896 })->[0]->{'acq.exchange_ratio'};
899 my $debit = create_fund_debit(
902 fund => $lid->fund->id,
903 origin_amount => $li->estimated_unit_price,
904 origin_currency_type => $li->provider->currency_type,
908 $lid->fund_debit($debit->id);
909 $lid->fund($lid->fund->id);
910 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
915 __PACKAGE__->register_method(
916 "method" => "fund_exceeds_balance_percent_api",
917 "api_name" => "open-ils.acq.fund.check_balance_percentages",
919 "desc" => q/Determine whether a given fund exceeds its defined
920 "balance stop and warning percentages"/,
922 {"desc" => "Authentication token", "type" => "string"},
923 {"desc" => "Fund ID", "type" => "number"},
924 {"desc" => "Theoretical debit amount (optional)",
927 "return" => {"desc" => q/An array of two values, for stop and warning,
928 in that order: 1 if fund exceeds that balance percentage, else 0/}
932 sub fund_exceeds_balance_percent_api {
933 my ($self, $conn, $auth, $fund_id, $debit_amount) = @_;
937 my $e = new_editor("authtoken" => $auth);
938 return $e->die_event unless $e->checkauth;
940 my $fund = $e->retrieve_acq_fund($fund_id) or return $e->die_event;
941 return $e->die_event unless $e->allowed("VIEW_FUND", $fund->org);
944 fund_exceeds_balance_percent($fund, $debit_amount, $e, "stop"),
945 fund_exceeds_balance_percent($fund, $debit_amount, $e, "warning")
952 sub fund_exceeds_balance_percent {
953 my ($fund, $debit_amount, $e, $which) = @_;
955 my ($method_name, $event_name) = @{{
957 "balance_warning_percent", "ACQ_FUND_EXCEEDS_WARN_PERCENT"
960 "balance_stop_percent", "ACQ_FUND_EXCEEDS_STOP_PERCENT"
964 if ($fund->$method_name) {
966 $e->search_acq_fund_combined_balance({"fund" => $fund->id})->[0];
968 $e->search_acq_fund_allocation_total({"fund" => $fund->id})->[0];
970 $balance = ($balance) ? $balance->amount : 0;
971 $allocations = ($allocations) ? $allocations->amount : 0;
974 $allocations == 0 || # if no allocations were ever made, assume we have hit the stop percent
975 ((($allocations - $balance + $debit_amount) / $allocations) * 100) > $fund->$method_name
977 $logger->info("fund would hit a limit: " . $fund->id . ", $balance, $debit_amount, $allocations, $method_name");
982 "fund" => $fund, "debit_amount" => $debit_amount
992 # ----------------------------------------------------------------------------
994 # ----------------------------------------------------------------------------
995 sub create_fund_debit {
996 my($mgr, $dry_run, %args) = @_;
998 # Verify the fund is not being spent beyond the hard stop amount
999 my $fund = $mgr->editor->retrieve_acq_fund($args{fund}) or return 0;
1002 fund_exceeds_balance_percent(
1003 $fund, $args{"amount"}, $mgr->editor, "stop"
1006 $dry_run and fund_exceeds_balance_percent(
1007 $fund, $args{"amount"}, $mgr->editor, "warning"
1010 my $debit = Fieldmapper::acq::fund_debit->new;
1011 $debit->debit_type('purchase');
1012 $debit->encumbrance('t');
1013 $debit->$_($args{$_}) for keys %args;
1015 $mgr->add_debit($debit->amount);
1016 return $mgr->editor->create_acq_fund_debit($debit);
1020 # ----------------------------------------------------------------------------
1022 # ----------------------------------------------------------------------------
1023 sub create_picklist {
1024 my($mgr, %args) = @_;
1025 my $picklist = Fieldmapper::acq::picklist->new;
1026 $picklist->creator($mgr->editor->requestor->id);
1027 $picklist->owner($picklist->creator);
1028 $picklist->editor($picklist->creator);
1029 $picklist->create_time('now');
1030 $picklist->edit_time('now');
1031 $picklist->org_unit($mgr->editor->requestor->ws_ou);
1032 $picklist->owner($mgr->editor->requestor->id);
1033 $picklist->$_($args{$_}) for keys %args;
1034 $picklist->clear_id;
1035 $mgr->picklist($picklist);
1036 return $mgr->editor->create_acq_picklist($picklist);
1039 sub update_picklist {
1040 my($mgr, $picklist) = @_;
1041 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
1042 $picklist->edit_time('now');
1043 $picklist->editor($mgr->editor->requestor->id);
1044 if ($mgr->editor->update_acq_picklist($picklist)) {
1045 $picklist = $mgr->editor->retrieve_acq_picklist($mgr->editor->data);
1046 $mgr->picklist($picklist);
1053 sub delete_picklist {
1054 my($mgr, $picklist) = @_;
1055 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
1057 # delete all 'new' lineitems
1058 my $li_ids = $mgr->editor->search_acq_lineitem(
1060 picklist => $picklist->id,
1061 "-or" => {state => "new", purchase_order => undef}
1065 for my $li_id (@$li_ids) {
1066 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
1067 return 0 unless delete_lineitem($mgr, $li);
1071 # detach all non-'new' lineitems
1072 $li_ids = $mgr->editor->search_acq_lineitem({picklist => $picklist->id, state => {'!=' => 'new'}}, {idlist => 1});
1073 for my $li_id (@$li_ids) {
1074 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
1075 $li->clear_picklist;
1076 return 0 unless update_lineitem($mgr, $li);
1080 # remove any picklist-specific object perms
1081 my $ops = $mgr->editor->search_permission_usr_object_perm_map({object_type => 'acqpl', object_id => ''.$picklist->id});
1082 for my $op (@$ops) {
1083 return 0 unless $mgr->editor->delete_usr_object_perm_map($op);
1086 return $mgr->editor->delete_acq_picklist($picklist);
1089 # ----------------------------------------------------------------------------
1091 # ----------------------------------------------------------------------------
1092 sub update_purchase_order {
1094 $po = $mgr->editor->retrieve_acq_purchase_order($po) unless ref $po;
1095 $po->editor($mgr->editor->requestor->id);
1096 $po->edit_time('now');
1097 $mgr->purchase_order($po);
1098 return $mgr->editor->retrieve_acq_purchase_order($mgr->editor->data)
1099 if $mgr->editor->update_acq_purchase_order($po);
1103 sub create_purchase_order {
1104 my($mgr, %args) = @_;
1106 # verify the chosen provider is still active
1107 my $provider = $mgr->editor->retrieve_acq_provider($args{provider}) or return 0;
1108 unless($U->is_true($provider->active)) {
1109 $logger->error("provider is not active. cannot create PO");
1110 $mgr->editor->event(OpenILS::Event->new('ACQ_PROVIDER_INACTIVE'));
1114 my $po = Fieldmapper::acq::purchase_order->new;
1115 $po->creator($mgr->editor->requestor->id);
1116 $po->editor($mgr->editor->requestor->id);
1117 $po->owner($mgr->editor->requestor->id);
1118 $po->edit_time('now');
1119 $po->create_time('now');
1120 $po->state('pending');
1121 $po->ordering_agency($mgr->editor->requestor->ws_ou);
1122 $po->$_($args{$_}) for keys %args;
1124 $mgr->purchase_order($po);
1125 return $mgr->editor->create_acq_purchase_order($po);
1128 # ----------------------------------------------------------------------------
1129 # if all of the lineitems for this PO are received,
1130 # mark the PO as received
1131 # ----------------------------------------------------------------------------
1132 sub check_purchase_order_received {
1133 my($mgr, $po_id) = @_;
1135 my $non_recv_li = $mgr->editor->search_acq_lineitem(
1136 { purchase_order => $po_id,
1137 state => {'!=' => 'received'}
1140 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id);
1141 return $po if @$non_recv_li;
1143 $po->state('received');
1144 return update_purchase_order($mgr, $po);
1148 # ----------------------------------------------------------------------------
1149 # Bib, Callnumber, and Copy data
1150 # ----------------------------------------------------------------------------
1152 sub create_lineitem_assets {
1153 my($mgr, $li_id) = @_;
1156 my $li = $mgr->editor->retrieve_acq_lineitem([
1159 flesh_fields => {jub => ['purchase_order', 'attributes']}
1163 # note: at this point, the bib record this LI links to should already be created
1165 # -----------------------------------------------------------------
1166 # The lineitem is going live, promote user request holds to real holds
1167 # -----------------------------------------------------------------
1168 promote_lineitem_holds($mgr, $li) or return 0;
1170 my $li_details = $mgr->editor->search_acq_lineitem_detail({lineitem => $li_id}, {idlist=>1});
1172 # -----------------------------------------------------------------
1173 # for each lineitem_detail, create the volume if necessary, create
1174 # a copy, and link them all together.
1175 # -----------------------------------------------------------------
1177 for my $lid_id (@{$li_details}) {
1179 my $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid_id) or return 0;
1180 next if $lid->eg_copy_id;
1182 # use the same callnumber label for all items within this lineitem
1183 $lid->cn_label($first_cn) if $first_cn and not $lid->cn_label;
1185 # apply defaults if necessary
1186 return 0 unless complete_lineitem_detail($mgr, $lid);
1188 $first_cn = $lid->cn_label unless $first_cn;
1190 my $org = $lid->owning_lib;
1191 my $label = $lid->cn_label;
1192 my $bibid = $li->eg_bib_id;
1194 my $volume = $mgr->cache($org, "cn.$bibid.$label");
1196 $volume = create_volume($mgr, $li, $lid) or return 0;
1197 $mgr->cache($org, "cn.$bibid.$label", $volume);
1199 create_copy($mgr, $volume, $lid, $li) or return 0;
1202 return { li => $li };
1206 my($mgr, $li, $lid) = @_;
1208 my ($volume, $evt) =
1209 OpenILS::Application::Cat::AssetCommon->find_or_create_volume(
1217 $mgr->editor->event($evt);
1225 my($mgr, $volume, $lid, $li) = @_;
1226 my $copy = Fieldmapper::asset::copy->new;
1228 $copy->loan_duration(2);
1229 $copy->fine_level(2);
1230 $copy->status(($lid->recv_time) ? OILS_COPY_STATUS_IN_PROCESS : OILS_COPY_STATUS_ON_ORDER);
1231 $copy->barcode($lid->barcode);
1232 $copy->location($lid->location);
1233 $copy->call_number($volume->id);
1234 $copy->circ_lib($volume->owning_lib);
1235 $copy->circ_modifier($lid->circ_modifier);
1237 # AKA list price. We might need a $li->list_price field since
1238 # estimated price is not necessarily the same as list price
1239 $copy->price($li->estimated_unit_price);
1241 my $evt = OpenILS::Application::Cat::AssetCommon->create_copy($mgr->editor, $volume, $copy);
1243 $mgr->editor->event($evt);
1248 $lid->eg_copy_id($copy->id);
1249 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
1257 # ----------------------------------------------------------------------------
1258 # Workflow: Build a selection list from a Z39.50 search
1259 # ----------------------------------------------------------------------------
1261 __PACKAGE__->register_method(
1262 method => 'zsearch',
1263 api_name => 'open-ils.acq.picklist.search.z3950',
1266 desc => 'Performs a z3950 federated search and creates a picklist and associated lineitems',
1268 {desc => 'Authentication token', type => 'string'},
1269 {desc => 'Search definition', type => 'object'},
1270 {desc => 'Picklist name, optional', type => 'string'},
1276 my($self, $conn, $auth, $search, $name, $options) = @_;
1277 my $e = new_editor(authtoken=>$auth);
1278 return $e->event unless $e->checkauth;
1279 return $e->event unless $e->allowed('CREATE_PICKLIST');
1281 $search->{limit} ||= 10;
1284 my $ses = OpenSRF::AppSession->create('open-ils.search');
1285 my $req = $ses->request('open-ils.search.z3950.search_class', $auth, $search);
1290 while(my $resp = $req->recv(timeout=>60)) {
1293 my $e = new_editor(requestor=>$e->requestor, xact=>1);
1294 $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1295 $picklist = zsearch_build_pl($mgr, $name);
1299 my $result = $resp->content;
1300 my $count = $result->{count} || 0;
1301 $mgr->total( (($count < $search->{limit}) ? $count : $search->{limit})+1 );
1303 for my $rec (@{$result->{records}}) {
1305 my $li = create_lineitem($mgr,
1306 picklist => $picklist->id,
1307 source_label => $result->{service},
1308 marc => $rec->{marcxml},
1309 eg_bib_id => $rec->{bibid}
1312 if($$options{respond_li}) {
1313 $li->attributes($mgr->editor->search_acq_lineitem_attr({lineitem => $li->id}))
1314 if $$options{flesh_attrs};
1315 $li->clear_marc if $$options{clear_marc};
1316 $mgr->respond(lineitem => $li);
1323 $mgr->editor->commit;
1324 return $mgr->respond_complete;
1327 sub zsearch_build_pl {
1328 my($mgr, $name) = @_;
1331 my $picklist = $mgr->editor->search_acq_picklist({
1332 owner => $mgr->editor->requestor->id,
1336 if($name eq '' and $picklist) {
1337 return 0 unless delete_picklist($mgr, $picklist);
1341 return update_picklist($mgr, $picklist) if $picklist;
1342 return create_picklist($mgr, name => $name);
1346 # ----------------------------------------------------------------------------
1347 # Workflow: Build a selection list / PO by importing a batch of MARC records
1348 # ----------------------------------------------------------------------------
1350 __PACKAGE__->register_method(
1351 method => 'upload_records',
1352 api_name => 'open-ils.acq.process_upload_records',
1354 max_chunk_count => 1
1357 sub upload_records {
1358 my($self, $conn, $auth, $key, $args) = @_;
1361 my $e = new_editor(authtoken => $auth, xact => 1);
1362 return $e->die_event unless $e->checkauth;
1363 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1365 my $cache = OpenSRF::Utils::Cache->new;
1367 my $data = $cache->get_cache("vandelay_import_spool_$key");
1368 my $filename = $data->{path};
1369 my $provider = $args->{provider};
1370 my $picklist = $args->{picklist};
1371 my $create_po = $args->{create_po};
1372 my $activate_po = $args->{activate_po};
1373 my $vandelay = $args->{vandelay};
1374 my $ordering_agency = $args->{ordering_agency} || $e->requestor->ws_ou;
1375 my $fiscal_year = $args->{fiscal_year};
1377 # if the user provides no fiscal year, find the
1378 # current fiscal year for the ordering agency.
1379 $fiscal_year ||= $U->simplereq(
1381 'open-ils.acq.org_unit.current_fiscal_year',
1389 unless(-r $filename) {
1390 $logger->error("unable to read MARC file $filename");
1392 return OpenILS::Event->new('FILE_UPLOAD_ERROR', payload => {filename => $filename});
1395 $provider = $e->retrieve_acq_provider($provider) or return $e->die_event;
1398 $picklist = $e->retrieve_acq_picklist($picklist) or return $e->die_event;
1399 if($picklist->owner != $e->requestor->id) {
1400 return $e->die_event unless
1401 $e->allowed('CREATE_PICKLIST', $picklist->org_unit, $picklist);
1403 $mgr->picklist($picklist);
1407 return $e->die_event unless
1408 $e->allowed('CREATE_PURCHASE_ORDER', $ordering_agency);
1410 $po = create_purchase_order($mgr,
1411 ordering_agency => $ordering_agency,
1412 provider => $provider->id,
1413 state => 'pending' # will be updated later if activated
1414 ) or return $mgr->editor->die_event;
1417 $logger->info("acq processing MARC file=$filename");
1419 my $batch = new MARC::Batch ('USMARC', $filename);
1427 my ($err, $xml, $r);
1432 } catch Error with {
1434 $logger->warn("Proccessing of record $count in set $key failed with error $err. Skipping this record");
1441 $xml = clean_marc($r);
1442 } catch Error with {
1444 $logger->warn("Proccessing XML of record $count in set $key failed with error $err. Skipping this record");
1447 next if $err or not $xml;
1450 source_label => $provider->code,
1451 provider => $provider->id,
1455 $args{picklist} = $picklist->id if $picklist;
1457 $args{purchase_order} = $po->id;
1458 $args{state} = 'pending-order';
1461 my $li = create_lineitem($mgr, %args) or return $mgr->editor->die_event;
1463 $li->provider($provider); # flesh it, we'll need it later
1465 import_lineitem_details($mgr, $ordering_agency, $li, $fiscal_year)
1466 or return $mgr->editor->die_event;
1469 push(@li_list, $li->id);
1474 $evt = extract_po_name($mgr, $po, \@li_list);
1475 return $evt if $evt;
1480 $cache->delete_cache('vandelay_import_spool_' . $key);
1482 if ($po and $activate_po) {
1483 my $die_event = activate_purchase_order_impl($mgr, $po->id, $vandelay);
1484 return $die_event if $die_event;
1486 } elsif ($vandelay) {
1487 $vandelay->{new_rec_perm} = 'IMPORT_ACQ_LINEITEM_BIB_RECORD_UPLOAD';
1488 create_lineitem_list_assets($mgr, \@li_list, $vandelay,
1489 !$vandelay->{create_assets}) or return $e->die_event;
1492 return $mgr->respond_complete;
1495 # see if the PO name is encoded in the newly imported records
1496 sub extract_po_name {
1497 my ($mgr, $po, $li_ids) = @_;
1498 my $e = $mgr->editor;
1500 # find the first instance of the name
1501 my $attr = $e->search_acq_lineitem_attr([
1502 { lineitem => $li_ids,
1503 attr_type => 'lineitem_provider_attr_definition',
1504 attr_name => 'purchase_order'
1506 order_by => {aqlia => 'id'},
1509 ])->[0] or return undef;
1511 my $name = $attr->attr_value;
1513 # see if another PO already has the name, provider, and org
1514 my $existing = $e->search_acq_purchase_order(
1516 ordering_agency => $po->ordering_agency,
1517 provider => $po->provider
1522 # if a PO exists with the same name (and provider/org)
1523 # tack the po ID into the name to differentiate
1524 $name = sprintf("$name (%s)", $po->id) if $existing;
1526 $logger->info("Extracted PO name: $name");
1529 update_purchase_order($mgr, $po) or return $e->die_event;
1533 sub import_lineitem_details {
1534 my($mgr, $ordering_agency, $li, $fiscal_year) = @_;
1536 my $holdings = $mgr->editor->json_query({from => ['acq.extract_provider_holding_data', $li->id]});
1537 return 1 unless @$holdings;
1538 my $org_path = $U->get_org_ancestors($ordering_agency);
1539 $org_path = [ reverse (@$org_path) ];
1545 # create a lineitem detail for each copy in the data
1547 my $compiled = extract_lineitem_detail_data($mgr, $org_path, $holdings, $idx, $fiscal_year);
1548 last unless defined $compiled;
1549 return 0 unless $compiled;
1551 # this takes the price of the last copy and uses it as the lineitem price
1552 # need to determine if a given record would include different prices for the same item
1553 $price = $$compiled{estimated_price};
1555 last unless $$compiled{quantity};
1557 for(1..$$compiled{quantity}) {
1558 my $lid = create_lineitem_detail(
1560 lineitem => $li->id,
1561 owning_lib => $$compiled{owning_lib},
1562 cn_label => $$compiled{call_number},
1563 fund => $$compiled{fund},
1564 circ_modifier => $$compiled{circ_modifier},
1565 note => $$compiled{note},
1566 location => $$compiled{copy_location},
1567 collection_code => $$compiled{collection_code},
1568 barcode => $$compiled{barcode}
1576 $li->estimated_unit_price($price);
1577 update_lineitem($mgr, $li) or return 0;
1581 # return hash on success, 0 on error, undef on no more holdings
1582 sub extract_lineitem_detail_data {
1583 my($mgr, $org_path, $holdings, $index, $fiscal_year) = @_;
1585 my @data_list = grep { $_->{holding} eq $index } @$holdings;
1586 return undef unless @data_list;
1588 my %compiled = map { $_->{attr} => $_->{data} } @data_list;
1589 my $base_org = $$org_path[0];
1593 $logger->error("Item import extraction error: $msg");
1594 $logger->error('Holdings Data: ' . OpenSRF::Utils::JSON->perl2JSON(\%compiled));
1595 $mgr->editor->rollback;
1596 $mgr->editor->event(OpenILS::Event->new('ACQ_IMPORT_ERROR', payload => $msg));
1600 # ---------------------------------------------------------------------
1602 if(my $code = $compiled{fund_code}) {
1604 my $fund = $mgr->cache($base_org, "fund.$code");
1606 # search up the org tree for the most appropriate fund
1607 for my $org (@$org_path) {
1608 $fund = $mgr->editor->search_acq_fund(
1609 {org => $org, code => $code, year => $fiscal_year}, {idlist => 1})->[0];
1613 return $killme->("no fund with code $code at orgs [@$org_path]") unless $fund;
1614 $compiled{fund} = $fund;
1615 $mgr->cache($base_org, "fund.$code", $fund);
1619 # ---------------------------------------------------------------------
1621 if(my $sn = $compiled{owning_lib}) {
1622 my $org_id = $mgr->cache($base_org, "orgsn.$sn") ||
1623 $mgr->editor->search_actor_org_unit({shortname => $sn}, {idlist => 1})->[0];
1624 return $killme->("invalid owning_lib defined: $sn") unless $org_id;
1625 $compiled{owning_lib} = $org_id;
1626 $mgr->cache($$org_path[0], "orgsn.$sn", $org_id);
1630 # ---------------------------------------------------------------------
1632 my $code = $compiled{circ_modifier};
1636 # verify this is a valid circ modifier
1637 return $killme->("invlalid circ_modifier $code") unless
1638 defined $mgr->cache($base_org, "mod.$code") or
1639 $mgr->editor->retrieve_config_circ_modifier($code);
1641 # if valid, cache for future tests
1642 $mgr->cache($base_org, "mod.$code", $code);
1645 $compiled{circ_modifier} = get_default_circ_modifier($mgr, $base_org);
1649 # ---------------------------------------------------------------------
1651 if( my $name = $compiled{copy_location}) {
1653 my $cp_base_org = $base_org;
1655 if ($compiled{owning_lib}) {
1656 # start looking for copy locations at the copy
1657 # owning lib instaed of the upload context org
1658 $cp_base_org = $compiled{owning_lib};
1661 my $loc = $mgr->cache($cp_base_org, "copy_loc.$name");
1663 my $org = $cp_base_org;
1665 $loc = $mgr->editor->search_asset_copy_location(
1666 {owning_lib => $org, name => $name}, {idlist => 1})->[0];
1668 $org = $mgr->editor->retrieve_actor_org_unit($org)->parent_ou;
1671 return $killme->("Invalid copy location $name") unless $loc;
1672 $compiled{copy_location} = $loc;
1673 $mgr->cache($cp_base_org, "copy_loc.$name", $loc);
1681 # ----------------------------------------------------------------------------
1682 # Workflow: Given an existing purchase order, import/create the bibs,
1683 # callnumber and copy objects
1684 # ----------------------------------------------------------------------------
1686 __PACKAGE__->register_method(
1687 method => 'create_po_assets',
1688 api_name => 'open-ils.acq.purchase_order.assets.create',
1690 desc => q/Creates assets for each lineitem in the purchase order/,
1692 {desc => 'Authentication token', type => 'string'},
1693 {desc => 'The purchase order id', type => 'number'},
1695 return => {desc => 'Streams a total versus completed counts object, event on error'}
1697 max_chunk_count => 1
1700 sub create_po_assets {
1701 my($self, $conn, $auth, $po_id, $args) = @_;
1704 my $e = new_editor(authtoken=>$auth, xact=>1);
1705 return $e->die_event unless $e->checkauth;
1706 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1708 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1710 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1712 # it's ugly, but it's fast. Get the total count of lineitem detail objects to process
1713 my $lid_total = $e->json_query({
1714 select => { acqlid => [{aggregate => 1, transform => 'count', column => 'id'}] },
1720 join => {acqpo => {fkey => 'purchase_order', field => 'id'}}
1724 where => {'+acqpo' => {id => $po_id}}
1727 $mgr->total(scalar(@$li_ids) + $lid_total);
1729 create_lineitem_list_assets($mgr, $li_ids, $args->{vandelay})
1730 or return $e->die_event;
1733 update_purchase_order($mgr, $po) or return $e->die_event;
1736 return $mgr->respond_complete;
1741 __PACKAGE__->register_method(
1742 method => 'create_purchase_order_api',
1743 api_name => 'open-ils.acq.purchase_order.create',
1745 desc => 'Creates a new purchase order',
1747 {desc => 'Authentication token', type => 'string'},
1748 {desc => 'purchase_order to create', type => 'object'}
1750 return => {desc => 'The purchase order id, Event on failure'}
1752 max_chunk_count => 1
1755 sub create_purchase_order_api {
1756 my($self, $conn, $auth, $po, $args) = @_;
1759 my $e = new_editor(xact=>1, authtoken=>$auth);
1760 return $e->die_event unless $e->checkauth;
1761 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
1762 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1765 my %pargs = (ordering_agency => $e->requestor->ws_ou); # default
1766 $pargs{provider} = $po->provider if $po->provider;
1767 $pargs{ordering_agency} = $po->ordering_agency if $po->ordering_agency;
1768 $pargs{prepayment_required} = $po->prepayment_required if $po->prepayment_required;
1769 my $vandelay = $args->{vandelay};
1771 $po = create_purchase_order($mgr, %pargs) or return $e->die_event;
1773 my $li_ids = $$args{lineitems};
1777 for my $li_id (@$li_ids) {
1779 my $li = $e->retrieve_acq_lineitem([
1781 {flesh => 1, flesh_fields => {jub => ['attributes']}}
1782 ]) or return $e->die_event;
1784 $li->provider($po->provider);
1785 $li->purchase_order($po->id);
1786 $li->state('pending-order');
1787 update_lineitem($mgr, $li) or return $e->die_event;
1792 # commit before starting the asset creation
1798 create_lineitem_list_assets(
1799 $mgr, $li_ids, $vandelay, !$$args{create_assets})
1800 or return $e->die_event;
1804 apply_default_copies($mgr, $po) or return $e->die_event;
1808 return $mgr->respond_complete;
1811 # !transaction must be managed by the caller
1812 # creates the default number of copies for each lineitem on the PO.
1813 # when a LI already has copies attached, no default copies are added.
1814 # without li_id, all lineitems are checked/applied
1815 # returns 1 on success, 0 on error
1816 sub apply_default_copies {
1817 my ($mgr, $po, $li_id) = @_;
1819 my $e = $mgr->editor;
1821 my $provider = ref($po->provider) ? $po->provider :
1822 $e->retrieve_acq_provider($po->provider);
1824 my $copy_count = $provider->default_copy_count || return 1;
1826 $logger->info("Applying $copy_count default copies for PO ".$po->id);
1828 my $li_ids = $li_id ? [$li_id] :
1829 $e->search_acq_lineitem({
1830 purchase_order => $po->id,
1831 cancel_reason => undef
1836 for my $li_id (@$li_ids) {
1838 my $lid_ids = $e->search_acq_lineitem_detail(
1839 {lineitem => $li_id}, {idlist => 1});
1841 # do not apply default copies when copies already exist
1844 for (1 .. $copy_count) {
1845 create_lineitem_detail($mgr, lineitem => $li_id) or return 0;
1854 __PACKAGE__->register_method(
1855 method => 'update_lineitem_fund_batch',
1856 api_name => 'open-ils.acq.lineitem.fund.update.batch',
1859 desc => q/Given a set of lineitem IDS, updates the fund for all attached lineitem details/
1863 sub update_lineitem_fund_batch {
1864 my($self, $conn, $auth, $li_ids, $fund_id) = @_;
1865 my $e = new_editor(xact=>1, authtoken=>$auth);
1866 return $e->die_event unless $e->checkauth;
1867 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1868 for my $li_id (@$li_ids) {
1869 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
1870 return $evt if $evt;
1871 my $li_details = $e->search_acq_lineitem_detail({lineitem => $li_id});
1872 $_->fund($fund_id) and $_->ischanged(1) for @$li_details;
1873 $evt = lineitem_detail_CUD_batch($mgr, $li_details);
1874 return $evt if $evt;
1879 return $mgr->respond_complete;
1884 __PACKAGE__->register_method(
1885 method => 'lineitem_detail_CUD_batch_api',
1886 api_name => 'open-ils.acq.lineitem_detail.cud.batch',
1889 desc => q/Creates a new purchase order line item detail. / .
1890 q/Additionally creates the associated fund_debit/,
1892 {desc => 'Authentication token', type => 'string'},
1893 {desc => 'List of lineitem_details to create', type => 'array'},
1894 {desc => 'Create Debits. Used for creating post-po-asset-creation debits', type => 'bool'},
1896 return => {desc => 'Streaming response of current position in the array'}
1900 __PACKAGE__->register_method(
1901 method => 'lineitem_detail_CUD_batch_api',
1902 api_name => 'open-ils.acq.lineitem_detail.cud.batch.dry_run',
1906 Dry run version of open-ils.acq.lineitem_detail.cud.batch.
1907 In dry_run mode, updated fund_debit's the exceed the warning
1908 percent return an event.
1914 sub lineitem_detail_CUD_batch_api {
1915 my($self, $conn, $auth, $li_details, $create_debits) = @_;
1916 my $e = new_editor(xact=>1, authtoken=>$auth);
1917 return $e->die_event unless $e->checkauth;
1918 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1919 my $dry_run = ($self->api_name =~ /dry_run/o);
1920 my $evt = lineitem_detail_CUD_batch($mgr, $li_details, $create_debits, $dry_run);
1921 return $evt if $evt;
1923 return $mgr->respond_complete;
1927 sub lineitem_detail_CUD_batch {
1928 my($mgr, $li_details, $create_debits, $dry_run) = @_;
1930 $mgr->total(scalar(@$li_details));
1931 my $e = $mgr->editor;
1935 my $fund_cache = {};
1938 for my $lid (@$li_details) {
1940 unless($li = $li_cache{$lid->lineitem}) {
1941 ($li, $evt) = fetch_and_check_li($e, $lid->lineitem, 'write');
1942 return $evt if $evt;
1946 $lid = create_lineitem_detail($mgr, %{$lid->to_bare_hash}) or return $e->die_event;
1947 if($create_debits) {
1948 $li->provider($e->retrieve_acq_provider($li->provider)) or return $e->die_event;
1949 $lid->fund($e->retrieve_acq_fund($lid->fund)) or return $e->die_event;
1950 create_lineitem_detail_debit($mgr, $li, $lid, 0, 1) or return $e->die_event;
1953 } elsif($lid->ischanged) {
1954 return $evt if $evt = handle_changed_lid($e, $lid, $dry_run, $fund_cache);
1956 } elsif($lid->isdeleted) {
1957 delete_lineitem_detail($mgr, $lid) or return $e->die_event;
1960 $mgr->respond(li => $li);
1961 $li_cache{$lid->lineitem} = $li;
1967 sub handle_changed_lid {
1968 my($e, $lid, $dry_run, $fund_cache) = @_;
1970 my $orig_lid = $e->retrieve_acq_lineitem_detail($lid->id) or return $e->die_event;
1972 # updating the fund, so update the debit
1973 if($orig_lid->fund_debit and $orig_lid->fund != $lid->fund) {
1975 my $debit = $e->retrieve_acq_fund_debit($orig_lid->fund_debit);
1976 my $new_fund = $$fund_cache{$lid->fund} =
1977 $$fund_cache{$lid->fund} || $e->retrieve_acq_fund($lid->fund);
1979 # check the thresholds
1980 return $e->die_event if
1981 fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "stop");
1982 return $e->die_event if $dry_run and
1983 fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "warning");
1985 $debit->fund($new_fund->id);
1986 $e->update_acq_fund_debit($debit) or return $e->die_event;
1989 $e->update_acq_lineitem_detail($lid) or return $e->die_event;
1994 __PACKAGE__->register_method(
1995 method => 'receive_po_api',
1996 api_name => 'open-ils.acq.purchase_order.receive'
1999 sub receive_po_api {
2000 my($self, $conn, $auth, $po_id) = @_;
2001 my $e = new_editor(xact => 1, authtoken => $auth);
2002 return $e->die_event unless $e->checkauth;
2003 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2005 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2006 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2008 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
2010 for my $li_id (@$li_ids) {
2011 receive_lineitem($mgr, $li_id) or return $e->die_event;
2015 $po->state('received');
2016 update_purchase_order($mgr, $po) or return $e->die_event;
2019 return $mgr->respond_complete;
2023 # At the moment there's a lack of parallelism between the receive and unreceive
2024 # API methods for POs and the API methods for LIs and LIDs. The methods for
2025 # POs stream back objects as they act, whereas the methods for LIs and LIDs
2026 # atomically return an object that describes only what changed (in LIs and LIDs
2027 # themselves or in the objects to which to LIs and LIDs belong).
2029 # The methods for LIs and LIDs work the way they do to faciliate the UI's
2030 # maintaining correct information about the state of these things when a user
2031 # wants to receive or unreceive these objects without refreshing their whole
2032 # display. The UI feature for receiving and un-receiving a whole PO just
2033 # refreshes the whole display, so this absence of parallelism in the UI is also
2034 # relected in this module.
2036 # This could be neatened in the future by making POs receive and unreceive in
2037 # the same way the LIs and LIDs do.
2039 __PACKAGE__->register_method(
2040 method => 'receive_lineitem_detail_api',
2041 api_name => 'open-ils.acq.lineitem_detail.receive',
2043 desc => 'Mark a lineitem_detail as received',
2045 {desc => 'Authentication token', type => 'string'},
2046 {desc => 'lineitem detail ID', type => 'number'}
2049 "on success, object describing changes to LID and possibly " .
2050 "to LI and PO; on error, Event"
2055 sub receive_lineitem_detail_api {
2056 my($self, $conn, $auth, $lid_id) = @_;
2058 my $e = new_editor(xact=>1, authtoken=>$auth);
2059 return $e->die_event unless $e->checkauth;
2060 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2063 "flesh" => 2, "flesh_fields" => {
2064 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
2068 my $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
2070 return $e->die_event unless $e->allowed(
2071 'RECEIVE_PURCHASE_ORDER', $lid->lineitem->purchase_order->ordering_agency);
2074 my $recvd = receive_lineitem_detail($mgr, $lid_id) or return $e->die_event;
2076 # .. and re-retrieve
2077 $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
2079 # Now build result data structure.
2080 my $result = {"lid" => {$lid->id => {"recv_time" => $lid->recv_time}}};
2083 if ($recvd->class_name =~ /::purchase_order/) {
2084 $result->{"po"} = describe_affected_po($e, $recvd);
2086 $lid->lineitem->id => {"state" => $lid->lineitem->state}
2088 } elsif ($recvd->class_name =~ /::lineitem/) {
2089 $result->{"li"} = {$recvd->id => {"state" => $recvd->state}};
2093 describe_affected_po($e, $lid->lineitem->purchase_order);
2099 __PACKAGE__->register_method(
2100 method => 'receive_lineitem_api',
2101 api_name => 'open-ils.acq.lineitem.receive',
2103 desc => 'Mark a lineitem as received',
2105 {desc => 'Authentication token', type => 'string'},
2106 {desc => 'lineitem ID', type => 'number'}
2109 "on success, object describing changes to LI and possibly PO; " .
2115 sub receive_lineitem_api {
2116 my($self, $conn, $auth, $li_id) = @_;
2118 my $e = new_editor(xact=>1, authtoken=>$auth);
2119 return $e->die_event unless $e->checkauth;
2120 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2122 my $li = $e->retrieve_acq_lineitem([
2126 jub => ['purchase_order']
2129 ]) or return $e->die_event;
2131 return $e->die_event unless $e->allowed(
2132 'RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);
2134 my $res = receive_lineitem($mgr, $li_id) or return $e->die_event;
2136 $conn->respond_complete($res);
2137 $mgr->run_post_response_hooks
2141 __PACKAGE__->register_method(
2142 method => 'rollback_receive_po_api',
2143 api_name => 'open-ils.acq.purchase_order.receive.rollback'
2146 sub rollback_receive_po_api {
2147 my($self, $conn, $auth, $po_id) = @_;
2148 my $e = new_editor(xact => 1, authtoken => $auth);
2149 return $e->die_event unless $e->checkauth;
2150 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2152 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2153 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2155 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
2157 for my $li_id (@$li_ids) {
2158 rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
2162 $po->state('on-order');
2163 update_purchase_order($mgr, $po) or return $e->die_event;
2166 return $mgr->respond_complete;
2170 __PACKAGE__->register_method(
2171 method => 'rollback_receive_lineitem_detail_api',
2172 api_name => 'open-ils.acq.lineitem_detail.receive.rollback',
2174 desc => 'Mark a lineitem_detail as Un-received',
2176 {desc => 'Authentication token', type => 'string'},
2177 {desc => 'lineitem detail ID', type => 'number'}
2180 "on success, object describing changes to LID and possibly " .
2181 "to LI and PO; on error, Event"
2186 sub rollback_receive_lineitem_detail_api {
2187 my($self, $conn, $auth, $lid_id) = @_;
2189 my $e = new_editor(xact=>1, authtoken=>$auth);
2190 return $e->die_event unless $e->checkauth;
2191 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2193 my $lid = $e->retrieve_acq_lineitem_detail([
2197 acqlid => ['lineitem'],
2198 jub => ['purchase_order']
2202 my $li = $lid->lineitem;
2203 my $po = $li->purchase_order;
2205 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2209 my $recvd = rollback_receive_lineitem_detail($mgr, $lid_id)
2210 or return $e->die_event;
2213 $result->{"lid"} = {$recvd->id => {"recv_time" => $recvd->recv_time}};
2215 $result->{"lid"} = {$lid->id => {"recv_time" => $lid->recv_time}};
2218 if ($li->state eq "received") {
2219 $li->state("on-order");
2220 $li = update_lineitem($mgr, $li) or return $e->die_event;
2221 $result->{"li"} = {$li->id => {"state" => $li->state}};
2224 if ($po->state eq "received") {
2225 $po->state("on-order");
2226 $po = update_purchase_order($mgr, $po) or return $e->die_event;
2228 $result->{"po"} = describe_affected_po($e, $po);
2230 $e->commit and return $result or return $e->die_event;
2233 __PACKAGE__->register_method(
2234 method => 'rollback_receive_lineitem_api',
2235 api_name => 'open-ils.acq.lineitem.receive.rollback',
2237 desc => 'Mark a lineitem as Un-received',
2239 {desc => 'Authentication token', type => 'string'},
2240 {desc => 'lineitem ID', type => 'number'}
2243 "on success, object describing changes to LI and possibly PO; " .
2249 sub rollback_receive_lineitem_api {
2250 my($self, $conn, $auth, $li_id) = @_;
2252 my $e = new_editor(xact=>1, authtoken=>$auth);
2253 return $e->die_event unless $e->checkauth;
2254 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2256 my $li = $e->retrieve_acq_lineitem([
2258 "flesh" => 1, "flesh_fields" => {"jub" => ["purchase_order"]}
2261 my $po = $li->purchase_order;
2263 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2265 $li = rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
2267 my $result = {"li" => {$li->id => {"state" => $li->state}}};
2268 if ($po->state eq "received") {
2269 $po->state("on-order");
2270 $po = update_purchase_order($mgr, $po) or return $e->die_event;
2272 $result->{"po"} = describe_affected_po($e, $po);
2274 $e->commit and return $result or return $e->die_event;
2278 __PACKAGE__->register_method(
2279 method => 'set_lineitem_price_api',
2280 api_name => 'open-ils.acq.lineitem.price.set',
2282 desc => 'Set lineitem price. If debits already exist, update them as well',
2284 {desc => 'Authentication token', type => 'string'},
2285 {desc => 'lineitem ID', type => 'number'}
2287 return => {desc => 'status blob, Event on error'}
2291 sub set_lineitem_price_api {
2292 my($self, $conn, $auth, $li_id, $price) = @_;
2294 my $e = new_editor(xact=>1, authtoken=>$auth);
2295 return $e->die_event unless $e->checkauth;
2296 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2298 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
2299 return $evt if $evt;
2301 $li->estimated_unit_price($price);
2302 update_lineitem($mgr, $li) or return $e->die_event;
2304 my $lid_ids = $e->search_acq_lineitem_detail(
2305 {lineitem => $li_id, fund_debit => {'!=' => undef}},
2309 for my $lid_id (@$lid_ids) {
2311 my $lid = $e->retrieve_acq_lineitem_detail([
2313 flesh => 1, flesh_fields => {acqlid => ['fund', 'fund_debit']}}
2316 $lid->fund_debit->amount($price);
2317 $e->update_acq_fund_debit($lid->fund_debit) or return $e->die_event;
2323 return $mgr->respond_complete;
2327 __PACKAGE__->register_method(
2328 method => 'clone_picklist_api',
2329 api_name => 'open-ils.acq.picklist.clone',
2331 desc => 'Clones a picklist, including lineitem and lineitem details',
2333 {desc => 'Authentication token', type => 'string'},
2334 {desc => 'Picklist ID', type => 'number'},
2335 {desc => 'New Picklist Name', type => 'string'}
2337 return => {desc => 'status blob, Event on error'}
2341 sub clone_picklist_api {
2342 my($self, $conn, $auth, $pl_id, $name) = @_;
2344 my $e = new_editor(xact=>1, authtoken=>$auth);
2345 return $e->die_event unless $e->checkauth;
2346 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2348 my $old_pl = $e->retrieve_acq_picklist($pl_id);
2349 my $new_pl = create_picklist($mgr, %{$old_pl->to_bare_hash}, name => $name) or return $e->die_event;
2351 my $li_ids = $e->search_acq_lineitem({picklist => $pl_id}, {idlist => 1});
2353 # get the current user
2354 my $cloner = $mgr->editor->requestor->id;
2356 for my $li_id (@$li_ids) {
2358 # copy the lineitems' MARC
2359 my $marc = ($e->retrieve_acq_lineitem($li_id))->marc;
2361 # create a skeletal clone of the item
2362 my $li = Fieldmapper::acq::lineitem->new;
2363 $li->creator($cloner);
2364 $li->selector($cloner);
2365 $li->editor($cloner);
2368 my $new_li = create_lineitem($mgr, %{$li->to_bare_hash}, picklist => $new_pl->id) or return $e->die_event;
2374 return $mgr->respond_complete;
2378 __PACKAGE__->register_method(
2379 method => 'merge_picklist_api',
2380 api_name => 'open-ils.acq.picklist.merge',
2382 desc => 'Merges 2 or more picklists into a single list',
2384 {desc => 'Authentication token', type => 'string'},
2385 {desc => 'Lead Picklist ID', type => 'number'},
2386 {desc => 'List of subordinate picklist IDs', type => 'array'}
2388 return => {desc => 'status blob, Event on error'}
2392 sub merge_picklist_api {
2393 my($self, $conn, $auth, $lead_pl, $pl_list) = @_;
2395 my $e = new_editor(xact=>1, authtoken=>$auth);
2396 return $e->die_event unless $e->checkauth;
2397 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2399 # XXX perms on each picklist modified
2401 $lead_pl = $e->retrieve_acq_picklist($lead_pl) or return $e->die_event;
2402 # point all of the lineitems at the lead picklist
2403 my $li_ids = $e->search_acq_lineitem({picklist => $pl_list}, {idlist => 1});
2405 for my $li_id (@$li_ids) {
2406 my $li = $e->retrieve_acq_lineitem($li_id);
2407 $li->picklist($lead_pl);
2408 update_lineitem($mgr, $li) or return $e->die_event;
2412 # now delete the subordinate lists
2413 for my $pl_id (@$pl_list) {
2414 my $pl = $e->retrieve_acq_picklist($pl_id);
2415 $e->delete_acq_picklist($pl) or return $e->die_event;
2418 update_picklist($mgr, $lead_pl) or return $e->die_event;
2421 return $mgr->respond_complete;
2425 __PACKAGE__->register_method(
2426 method => 'delete_picklist_api',
2427 api_name => 'open-ils.acq.picklist.delete',
2429 desc => q/Deletes a picklist. It also deletes any lineitems in the "new" state. / .
2430 q/Other attached lineitems are detached/,
2432 {desc => 'Authentication token', type => 'string'},
2433 {desc => 'Picklist ID to delete', type => 'number'}
2435 return => {desc => '1 on success, Event on error'}
2439 sub delete_picklist_api {
2440 my($self, $conn, $auth, $picklist_id) = @_;
2441 my $e = new_editor(xact=>1, authtoken=>$auth);
2442 return $e->die_event unless $e->checkauth;
2443 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2444 my $pl = $e->retrieve_acq_picklist($picklist_id) or return $e->die_event;
2445 delete_picklist($mgr, $pl) or return $e->die_event;
2447 return $mgr->respond_complete;
2452 __PACKAGE__->register_method(
2453 method => 'activate_purchase_order',
2454 api_name => 'open-ils.acq.purchase_order.activate.dry_run'
2457 __PACKAGE__->register_method(
2458 method => 'activate_purchase_order',
2459 api_name => 'open-ils.acq.purchase_order.activate',
2461 desc => q/Activates a purchase order. This updates the status of the PO / .
2462 q/and Lineitems to 'on-order'. Activated PO's are ready for EDI delivery if appropriate./,
2464 {desc => 'Authentication token', type => 'string'},
2465 {desc => 'Purchase ID', type => 'number'}
2467 return => {desc => '1 on success, Event on error'}
2471 sub activate_purchase_order {
2472 my($self, $conn, $auth, $po_id, $vandelay, $options) = @_;
2475 my $dry_run = ($self->api_name =~ /\.dry_run/) ? 1 : 0;
2476 my $e = new_editor(authtoken=>$auth);
2477 return $e->die_event unless $e->checkauth;
2478 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2479 my $die_event = activate_purchase_order_impl($mgr, $po_id, $vandelay, $dry_run, $options);
2480 return $e->die_event if $die_event;
2481 $conn->respond_complete(1);
2482 $mgr->run_post_response_hooks unless $dry_run;
2486 # xacts managed within
2487 sub activate_purchase_order_impl {
2488 my ($mgr, $po_id, $vandelay, $dry_run, $options) = @_;
2490 # read-only until lineitem asset creation
2491 my $e = $mgr->editor;
2494 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2495 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
2497 return $e->die_event(OpenILS::Event->new('PO_ALREADY_ACTIVATED'))
2498 if $po->order_date; # PO cannot be re-activated
2500 my $provider = $e->retrieve_acq_provider($po->provider);
2502 # find lineitems and create assets for all
2505 purchase_order => $po_id,
2506 state => [qw/pending-order new order-ready/]
2509 my $li_ids = $e->search_acq_lineitem($query, {idlist => 1});
2511 my $vl_resp; # imported li's and the queue the managing queue
2513 $e->rollback; # read-only thus far
2514 $vl_resp = create_lineitem_list_assets($mgr, $li_ids, $vandelay)
2515 or return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED');
2519 # create fund debits for lineitems
2521 for my $li_id (@$li_ids) {
2522 my $li = $e->retrieve_acq_lineitem($li_id);
2524 if (!$li->eg_bib_id and !$dry_run) {
2525 # we encountered a lineitem that was not successfully imported.
2526 # we cannot continue. rollback and report.
2528 return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED', {queue => $vl_resp->{queue}});
2531 $li->state('on-order');
2532 $li->claim_policy($provider->default_claim_policy)
2533 if $provider->default_claim_policy and !$li->claim_policy;
2534 create_lineitem_debits($mgr, $li, $dry_run, $options) or return $e->die_event;
2535 update_lineitem($mgr, $li) or return $e->die_event;
2536 $mgr->post_process( sub { create_lineitem_status_events($mgr, $li->id, 'aur.ordered'); });
2540 # create po-item debits
2542 for my $po_item (@{$e->search_acq_po_item({purchase_order => $po_id})}) {
2544 my $debit = create_fund_debit(
2547 debit_type => 'direct_charge', # to match invoicing
2548 origin_amount => $po_item->estimated_cost,
2549 origin_currency_type => $e->retrieve_acq_fund($po_item->fund)->currency_type,
2550 amount => $po_item->estimated_cost,
2551 fund => $po_item->fund
2552 ) or return $e->die_event;
2553 $po_item->fund_debit($debit->id);
2554 $e->update_acq_po_item($po_item) or return $e->die_event;
2558 # mark PO as ordered
2560 $po->state('on-order');
2561 $po->order_date('now');
2562 update_purchase_order($mgr, $po) or return $e->die_event;
2565 $dry_run and $e->rollback or $e->commit;
2567 # tell the world we activated a PO
2568 $U->create_events_for_hook('acqpo.activated', $po, $po->ordering_agency) unless $dry_run;
2574 __PACKAGE__->register_method(
2575 method => 'split_purchase_order_by_lineitems',
2576 api_name => 'open-ils.acq.purchase_order.split_by_lineitems',
2578 desc => q/Splits a PO into many POs, 1 per lineitem. Only works for / .
2579 q/POs a) with more than one lineitems, and b) in the "pending" state./,
2581 {desc => 'Authentication token', type => 'string'},
2582 {desc => 'Purchase order ID', type => 'number'}
2584 return => {desc => 'list of new PO IDs on success, Event on error'}
2588 sub split_purchase_order_by_lineitems {
2589 my ($self, $conn, $auth, $po_id) = @_;
2591 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2592 return $e->die_event unless $e->checkauth;
2594 my $po = $e->retrieve_acq_purchase_order([
2597 "flesh_fields" => {"acqpo" => [qw/lineitems notes/]}
2599 ]) or return $e->die_event;
2601 return $e->die_event
2602 unless $e->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2604 unless ($po->state eq "pending") {
2606 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_LATE");
2609 unless (@{$po->lineitems} > 1) {
2611 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_SHORT");
2614 # To split an existing PO into many, it seems unwise to just delete the
2615 # original PO, so we'll instead detach all of the original POs' lineitems
2616 # but the first, then create new POs for each of the remaining LIs, and
2617 # then attach the LIs to their new POs.
2619 my @po_ids = ($po->id);
2620 my @moving_li = @{$po->lineitems};
2621 shift @moving_li; # discard first LI
2623 foreach my $li (@moving_li) {
2624 my $new_po = $po->clone;
2626 $new_po->clear_name;
2627 $new_po->creator($e->requestor->id);
2628 $new_po->editor($e->requestor->id);
2629 $new_po->owner($e->requestor->id);
2630 $new_po->edit_time("now");
2631 $new_po->create_time("now");
2633 $new_po = $e->create_acq_purchase_order($new_po);
2635 # Clone any notes attached to the old PO and attach to the new one.
2636 foreach my $note (@{$po->notes}) {
2637 my $new_note = $note->clone;
2638 $new_note->clear_id;
2639 $new_note->edit_time("now");
2640 $new_note->purchase_order($new_po->id);
2641 $e->create_acq_po_note($new_note);
2644 $li->edit_time("now");
2645 $li->purchase_order($new_po->id);
2646 $e->update_acq_lineitem($li);
2648 push @po_ids, $new_po->id;
2651 $po->edit_time("now");
2652 $e->update_acq_purchase_order($po);
2654 return \@po_ids if $e->commit;
2655 return $e->die_event;
2659 sub not_cancelable {
2661 (ref $o eq "HASH" and $o->{"textcode"} eq "ACQ_NOT_CANCELABLE");
2664 __PACKAGE__->register_method(
2665 method => "cancel_purchase_order_api",
2666 api_name => "open-ils.acq.purchase_order.cancel",
2668 desc => q/Cancels an on-order purchase order/,
2670 {desc => "Authentication token", type => "string"},
2671 {desc => "PO ID to cancel", type => "number"},
2672 {desc => "Cancel reason ID", type => "number"}
2674 return => {desc => q/Object describing changed POs, LIs and LIDs
2675 on success; Event on error./}
2679 sub cancel_purchase_order_api {
2680 my ($self, $conn, $auth, $po_id, $cancel_reason) = @_;
2682 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2683 return $e->die_event unless $e->checkauth;
2684 my $mgr = new OpenILS::Application::Acq::BatchManager(
2685 "editor" => $e, "conn" => $conn
2688 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2689 return new OpenILS::Event(
2690 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2693 my $result = cancel_purchase_order($mgr, $po_id, $cancel_reason) or
2694 return $e->die_event;
2695 if (not_cancelable($result)) { # event not from CStoreEditor
2698 } elsif ($result == -1) {
2700 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2703 $e->commit or return $e->die_event;
2705 # XXX create purchase order status events?
2707 if ($mgr->{post_commit}) {
2708 foreach my $func (@{$mgr->{post_commit}}) {
2716 sub cancel_purchase_order {
2717 my ($mgr, $po_id, $cancel_reason) = @_;
2719 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id) or return 0;
2721 # XXX is "cancelled" a typo? It's not correct US spelling, anyway.
2722 # Depending on context, this may not warrant an event.
2723 return -1 if $po->state eq "cancelled";
2725 # But this always does.
2726 return new OpenILS::Event(
2727 "ACQ_NOT_CANCELABLE", "note" => "purchase_order $po_id"
2728 ) unless ($po->state eq "on-order" or $po->state eq "pending");
2731 $mgr->editor->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2733 $po->state("cancelled");
2734 $po->cancel_reason($cancel_reason->id);
2736 my $li_ids = $mgr->editor->search_acq_lineitem(
2737 {"purchase_order" => $po_id}, {"idlist" => 1}
2740 my $result = {"li" => {}, "lid" => {}};
2741 foreach my $li_id (@$li_ids) {
2742 my $li_result = cancel_lineitem($mgr, $li_id, $cancel_reason)
2745 next if $li_result == -1; # already canceled:skip.
2746 return $li_result if not_cancelable($li_result); # not cancelable:stop.
2748 # Merge in each LI result (there's only going to be
2749 # one per call to cancel_lineitem).
2750 my ($k, $v) = each %{$li_result->{"li"}};
2751 $result->{"li"}->{$k} = $v;
2753 # Merge in each LID result (there may be many per call to
2755 while (($k, $v) = each %{$li_result->{"lid"}}) {
2756 $result->{"lid"}->{$k} = $v;
2760 # TODO who/what/where/how do we indicate this change for electronic orders?
2761 # TODO return changes to encumbered/spent
2762 # TODO maybe cascade up from smaller object to container object if last
2763 # smaller object in the container has been canceled?
2765 update_purchase_order($mgr, $po) or return 0;
2767 $po_id => {"state" => $po->state, "cancel_reason" => $cancel_reason}
2773 __PACKAGE__->register_method(
2774 method => "cancel_lineitem_api",
2775 api_name => "open-ils.acq.lineitem.cancel",
2777 desc => q/Cancels an on-order lineitem/,
2779 {desc => "Authentication token", type => "string"},
2780 {desc => "Lineitem ID to cancel", type => "number"},
2781 {desc => "Cancel reason ID", type => "number"}
2783 return => {desc => q/Object describing changed LIs and LIDs on success;
2788 __PACKAGE__->register_method(
2789 method => "cancel_lineitem_api",
2790 api_name => "open-ils.acq.lineitem.cancel.batch",
2792 desc => q/Batched version of open-ils.acq.lineitem.cancel/,
2793 return => {desc => q/Object describing changed LIs and LIDs on success;
2798 sub cancel_lineitem_api {
2799 my ($self, $conn, $auth, $li_id, $cancel_reason) = @_;
2801 my $batched = $self->api_name =~ /\.batch/;
2803 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2804 return $e->die_event unless $e->checkauth;
2805 my $mgr = new OpenILS::Application::Acq::BatchManager(
2806 "editor" => $e, "conn" => $conn
2809 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2810 return new OpenILS::Event(
2811 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2814 my ($result, $maybe_event);
2817 $result = {"li" => {}, "lid" => {}};
2818 foreach my $one_li_id (@$li_id) {
2819 my $one = cancel_lineitem($mgr, $one_li_id, $cancel_reason) or
2820 return $e->die_event;
2821 if (not_cancelable($one)) {
2822 $maybe_event = $one;
2823 } elsif ($result == -1) {
2824 $maybe_event = new OpenILS::Event("ACQ_ALREADY_CANCELED");
2828 while (($k, $v) = each %{$one->{"li"}}) {
2829 $result->{"li"}->{$k} = $v;
2832 if ($one->{"lid"}) {
2833 while (($k, $v) = each %{$one->{"lid"}}) {
2834 $result->{"lid"}->{$k} = $v;
2840 $result = cancel_lineitem($mgr, $li_id, $cancel_reason) or
2841 return $e->die_event;
2843 if (not_cancelable($result)) {
2846 } elsif ($result == -1) {
2848 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2852 if ($batched and not scalar keys %{$result->{"li"}}) {
2854 return $maybe_event;
2856 $e->commit or return $e->die_event;
2857 # create_lineitem_status_events should handle array li_id ok
2858 create_lineitem_status_events($mgr, $li_id, "aur.cancelled");
2860 if ($mgr->{post_commit}) {
2861 foreach my $func (@{$mgr->{post_commit}}) {
2870 sub cancel_lineitem {
2871 my ($mgr, $li_id, $cancel_reason) = @_;
2872 my $li = $mgr->editor->retrieve_acq_lineitem([
2873 $li_id, {flesh => 1, flesh_fields => {jub => ['purchase_order']}}
2876 return 0 unless $mgr->editor->allowed(
2877 "CREATE_PURCHASE_ORDER", $li->purchase_order->ordering_agency
2880 # Depending on context, this may not warrant an event.
2881 return -1 if $li->state eq "cancelled";
2883 # But this always does.
2884 return new OpenILS::Event(
2885 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id"
2887 (! $li->purchase_order) or (
2888 $li->purchase_order and (
2889 $li->state eq "on-order" or $li->state eq "pending-order"
2894 $li->state("cancelled");
2895 $li->cancel_reason($cancel_reason->id);
2897 my $lids = $mgr->editor->search_acq_lineitem_detail([{
2898 "lineitem" => $li_id
2901 flesh_fields => { acqlid => ['eg_copy_id'] }
2904 my $result = {"lid" => {}};
2906 foreach my $lid (@$lids) {
2907 my $lid_result = cancel_lineitem_detail($mgr, $lid->id, $cancel_reason)
2910 # gathering any real copies for deletion
2911 if ($lid->eg_copy_id) {
2912 $lid->eg_copy_id->isdeleted('t');
2913 push @$copies, $lid->eg_copy_id;
2916 next if $lid_result == -1; # already canceled: just skip it.
2917 return $lid_result if not_cancelable($lid_result); # not cxlable: stop.
2919 # Merge in each LID result (there's only going to be one per call to
2920 # cancel_lineitem_detail).
2921 my ($k, $v) = each %{$lid_result->{"lid"}};
2922 $result->{"lid"}->{$k} = $v;
2925 # Attempt to delete the gathered copies (this will also handle volume deletion and bib deletion)
2926 # Delete empty bibs according org unit setting
2927 my $force_delete_empty_bib = $U->ou_ancestor_setting_value(
2928 $mgr->editor->requestor->ws_ou, 'cat.bib.delete_on_no_copy_via_acq_lineitem_cancel', $mgr->editor);
2929 if (scalar(@$copies)>0) {
2931 my $delete_stats = undef;
2932 my $retarget_holds = [];
2933 my $cat_evt = OpenILS::Application::Cat::AssetCommon->update_fleshed_copies(
2934 $mgr->editor, $override, undef, $copies, $delete_stats, $retarget_holds,$force_delete_empty_bib);
2937 $logger->info("fleshed copy update failed with event: ".OpenSRF::Utils::JSON->perl2JSON($cat_evt));
2938 return new OpenILS::Event(
2939 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id", "payload" => $cat_evt
2943 # We can't do the following and stay within the same transaction, but that's okay, the hold targeter will pick these up later.
2944 #my $ses = OpenSRF::AppSession->create('open-ils.circ');
2945 #$ses->request('open-ils.circ.hold.reset.batch', $auth, $retarget_holds);
2948 # if we have a bib, check to see whether it has been deleted. if so, cancel any active holds targeting that bib
2949 if ($li->eg_bib_id) {
2950 my $bib = $mgr->editor->retrieve_biblio_record_entry($li->eg_bib_id) or return new OpenILS::Event(
2951 "ACQ_NOT_CANCELABLE", "note" => "Could not retrieve bib " . $li->eg_bib_id . " for lineitem $li_id"
2953 if ($U->is_true($bib->deleted)) {
2954 my $holds = $mgr->editor->search_action_hold_request(
2955 { cancel_time => undef,
2956 fulfillment_time => undef,
2957 target => $li->eg_bib_id
2961 my %cached_usr_home_ou = ();
2963 for my $hold (@$holds) {
2965 $logger->info("Cancelling hold ".$hold->id.
2966 " due to acq lineitem cancellation.");
2968 $hold->cancel_time('now');
2969 $hold->cancel_cause(5); # 'Staff forced'--we may want a new hold cancel cause reason for this
2970 $hold->cancel_note('Corresponding Acquistion Lineitem/Purchase Order was cancelled.');
2971 unless($mgr->editor->update_action_hold_request($hold)) {
2972 my $evt = $mgr->editor->event;
2973 $logger->error("Error updating hold ". $evt->textcode .":". $evt->desc .":". $evt->stacktrace);
2974 return new OpenILS::Event(
2975 "ACQ_NOT_CANCELABLE", "note" => "Could not cancel hold " . $hold->id . " for lineitem $li_id", "payload" => $evt
2978 if (! defined $mgr->{post_commit}) { # we need a mechanism for creating trigger events, but only if the transaction gets committed
2979 $mgr->{post_commit} = [];
2981 push @{ $mgr->{post_commit} }, sub {
2982 my $home_ou = $cached_usr_home_ou{$hold->usr};
2984 my $user = $mgr->editor->retrieve_actor_user($hold->usr); # FIXME: how do we want to handle failures here?
2985 $home_ou = $user->home_ou;
2986 $cached_usr_home_ou{$hold->usr} = $home_ou;
2988 $U->create_events_for_hook('hold_request.cancel.cancelled_order', $hold, $home_ou);
2994 update_lineitem($mgr, $li) or return 0;
2997 "state" => $li->state,
2998 "cancel_reason" => $cancel_reason
3005 __PACKAGE__->register_method(
3006 method => "cancel_lineitem_detail_api",
3007 api_name => "open-ils.acq.lineitem_detail.cancel",
3009 desc => q/Cancels an on-order lineitem detail/,
3011 {desc => "Authentication token", type => "string"},
3012 {desc => "Lineitem detail ID to cancel", type => "number"},
3013 {desc => "Cancel reason ID", type => "number"}
3015 return => {desc => q/Object describing changed LIDs on success;
3020 sub cancel_lineitem_detail_api {
3021 my ($self, $conn, $auth, $lid_id, $cancel_reason) = @_;
3023 my $e = new_editor("xact" => 1, "authtoken" => $auth);
3024 return $e->die_event unless $e->checkauth;
3025 my $mgr = new OpenILS::Application::Acq::BatchManager(
3026 "editor" => $e, "conn" => $conn
3029 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
3030 return new OpenILS::Event(
3031 "BAD_PARAMS", "note" => "Provide cancel reason ID"
3034 my $result = cancel_lineitem_detail($mgr, $lid_id, $cancel_reason) or
3035 return $e->die_event;
3037 if (not_cancelable($result)) {
3040 } elsif ($result == -1) {
3042 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
3045 $e->commit or return $e->die_event;
3047 # XXX create lineitem detail status events?
3051 sub cancel_lineitem_detail {
3052 my ($mgr, $lid_id, $cancel_reason) = @_;
3053 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
3057 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
3062 # Depending on context, this may not warrant an event.
3063 return -1 if $lid->cancel_reason;
3065 # But this always does.
3066 return new OpenILS::Event(
3067 "ACQ_NOT_CANCELABLE", "note" => "lineitem_detail $lid_id"
3069 (! $lid->lineitem->purchase_order) or
3071 (not $lid->recv_time) and
3073 $lid->lineitem->purchase_order and (
3074 $lid->lineitem->state eq "on-order" or
3075 $lid->lineitem->state eq "pending-order"
3080 return 0 unless $mgr->editor->allowed(
3081 "CREATE_PURCHASE_ORDER",
3082 $lid->lineitem->purchase_order->ordering_agency
3083 ) or (! $lid->lineitem->purchase_order);
3085 $lid->cancel_reason($cancel_reason->id);
3087 unless($U->is_true($cancel_reason->keep_debits)) {
3088 my $debit_id = $lid->fund_debit;
3089 $lid->clear_fund_debit;
3092 # item is cancelled. Remove the fund debit.
3093 my $debit = $mgr->editor->retrieve_acq_fund_debit($debit_id);
3094 if (!$U->is_true($debit->encumbrance)) {
3095 $mgr->editor->rollback;
3096 return OpenILS::Event->new('ACQ_NOT_CANCELABLE',
3097 note => "Debit is marked as paid: $debit_id");
3099 $mgr->editor->delete_acq_fund_debit($debit) or return $mgr->editor->die_event;
3103 # XXX LIDs don't have either an editor or a edit_time field. Should we
3104 # update these on the LI when we alter an LID?
3105 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
3107 return {"lid" => {$lid_id => {"cancel_reason" => $cancel_reason}}};
3111 __PACKAGE__->register_method(
3112 method => 'user_requests',
3113 api_name => 'open-ils.acq.user_request.retrieve.by_user_id',
3116 desc => 'Retrieve fleshed user requests and related data for a given user.',
3118 { desc => 'Authentication token', type => 'string' },
3119 { desc => 'User ID of the owner, or array of IDs', },
3120 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
3125 desc => 'Fleshed user requests and related data',
3131 __PACKAGE__->register_method(
3132 method => 'user_requests',
3133 api_name => 'open-ils.acq.user_request.retrieve.by_home_ou',
3136 desc => 'Retrieve fleshed user requests and related data for a given org unit or units.',
3138 { desc => 'Authentication token', type => 'string' },
3139 { desc => 'Org unit ID, or array of IDs', },
3140 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
3145 desc => 'Fleshed user requests and related data',
3152 my($self, $conn, $auth, $search_value, $options) = @_;
3153 my $e = new_editor(authtoken => $auth);
3154 return $e->event unless $e->checkauth;
3155 my $rid = $e->requestor->id;
3159 "select"=>{"aur"=>["id"],"au"=>["home_ou", {column => 'id', alias => 'usr_id'} ]},
3160 "from"=>{ "aur" => { "au" => {}, "jub" => { "type" => "left" } } },
3164 {"id"=>undef}, # this with the left-join pulls in requests without lineitems
3165 {"state"=>["new","on-order","pending-order"]} # FIXME - probably needs softcoding
3169 "order_by"=>[{"class"=>"aur", "field"=>"request_date", "direction"=>"desc"}]
3172 foreach (qw/ order_by limit offset /) {
3173 $query->{$_} = $options->{$_} if defined $options->{$_};
3175 if (defined $options->{'state'}) {
3176 $query->{'where'}->{'+jub'}->{'-or'}->[1]->{'state'} = $options->{'state'};
3179 if ($self->api_name =~ /by_user_id/) {
3180 $query->{'where'}->{'usr'} = $search_value;
3182 $query->{'where'}->{'+au'} = { 'home_ou' => $search_value };
3185 my $pertinent_ids = $e->json_query($query);
3188 for my $id_blob (@$pertinent_ids) {
3189 if ($rid != $id_blob->{usr_id}) {
3190 if (!defined $perm_test{ $id_blob->{home_ou} }) {
3191 $perm_test{ $id_blob->{home_ou} } = $e->allowed( ['user_request.view'], $id_blob->{home_ou} );
3193 if (!$perm_test{ $id_blob->{home_ou} }) {
3197 my $aur_obj = $e->retrieve_acq_user_request([
3199 {flesh => 1, flesh_fields => { "aur" => [ 'lineitem' ] } }
3201 if (! $aur_obj) { next; }
3203 if ($aur_obj->lineitem()) {
3204 $aur_obj->lineitem()->clear_marc();
3206 $conn->respond($aur_obj);
3212 __PACKAGE__->register_method (
3213 method => 'update_user_request',
3214 api_name => 'open-ils.acq.user_request.cancel.batch',
3217 desc => 'If given a cancel reason, will update the request with that reason, otherwise, this will delete the request altogether. The ' .
3218 'intention is for staff interfaces or processes to provide cancel reasons, and for patron interfaces to just delete the requests.' ,
3220 { desc => 'Authentication token', type => 'string' },
3221 { desc => 'ID or array of IDs for the user requests to cancel' },
3222 { desc => 'Cancel Reason ID (optional)', type => 'string' }
3225 desc => 'progress object, event on error',
3229 __PACKAGE__->register_method (
3230 method => 'update_user_request',
3231 api_name => 'open-ils.acq.user_request.set_no_hold.batch',
3234 desc => 'Remove the hold from a user request or set of requests',
3236 { desc => 'Authentication token', type => 'string' },
3237 { desc => 'ID or array of IDs for the user requests to modify' }
3240 desc => 'progress object, event on error',
3245 sub update_user_request {
3246 my($self, $conn, $auth, $aur_ids, $cancel_reason) = @_;
3247 my $e = new_editor(xact => 1, authtoken => $auth);
3248 return $e->die_event unless $e->checkauth;
3249 my $rid = $e->requestor->id;
3253 for my $id (@$aur_ids) {
3255 my $aur_obj = $e->retrieve_acq_user_request([
3258 flesh_fields => { "aur" => ['lineitem', 'usr'] }
3260 ]) or return $e->die_event;
3262 my $context_org = $aur_obj->usr()->home_ou();
3263 $aur_obj->usr( $aur_obj->usr()->id() );
3265 if ($rid != $aur_obj->usr) {
3266 if (!defined $perm_test{ $context_org }) {
3267 $perm_test{ $context_org } = $e->allowed( ['user_request.update'], $context_org );
3269 if (!$perm_test{ $context_org }) {
3274 if($self->api_name =~ /set_no_hold/) {
3275 if ($U->is_true($aur_obj->hold)) {
3277 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3281 if($self->api_name =~ /cancel/) {
3282 if ( $cancel_reason ) {
3283 $aur_obj->cancel_reason( $cancel_reason );
3284 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3285 create_user_request_events( $e, [ $aur_obj ], 'aur.rejected' );
3287 $e->delete_acq_user_request($aur_obj);
3291 $conn->respond({maximum => scalar(@$aur_ids), progress => $x++});
3295 return {complete => 1};
3298 __PACKAGE__->register_method (
3299 method => 'new_user_request',
3300 api_name => 'open-ils.acq.user_request.create',
3302 desc => 'Create a new user request object in the DB',
3304 { desc => 'Authentication token', type => 'string' },
3305 { desc => 'User request data hash. Hash keys match the fields for the "aur" object', type => 'object' }
3308 desc => 'The created user request object, or event on error'
3313 sub new_user_request {
3314 my($self, $conn, $auth, $form_data) = @_;
3315 my $e = new_editor(xact => 1, authtoken => $auth);
3316 return $e->die_event unless $e->checkauth;
3317 my $rid = $e->requestor->id;
3318 my $target_user_fleshed;
3319 if (! defined $$form_data{'usr'}) {
3320 $$form_data{'usr'} = $rid;
3322 if ($$form_data{'usr'} != $rid) {
3323 # See if the requestor can place the request on behalf of a different user.
3324 $target_user_fleshed = $e->retrieve_actor_user($$form_data{'usr'}) or return $e->die_event;
3325 $e->allowed('user_request.create', $target_user_fleshed->home_ou) or return $e->die_event;
3327 $target_user_fleshed = $e->requestor;
3328 $e->allowed('CREATE_PURCHASE_REQUEST') or return $e->die_event;
3330 if (! defined $$form_data{'pickup_lib'}) {
3331 if ($target_user_fleshed->ws_ou) {
3332 $$form_data{'pickup_lib'} = $target_user_fleshed->ws_ou;
3334 $$form_data{'pickup_lib'} = $target_user_fleshed->home_ou;
3337 if (! defined $$form_data{'request_type'}) {
3338 $$form_data{'request_type'} = 1; # Books
3340 my $aur_obj = new Fieldmapper::acq::user_request;
3342 $aur_obj->usr( $$form_data{'usr'} );
3343 $aur_obj->request_date( 'now' );
3344 for my $field ( keys %$form_data ) {
3345 if (defined $$form_data{$field} and $field !~ /^(id|lineitem|eg_bib|request_date|cancel_reason)$/) {
3346 $aur_obj->$field( $$form_data{$field} );
3350 $aur_obj = $e->create_acq_user_request($aur_obj) or return $e->die_event;
3352 $e->commit and create_user_request_events( $e, [ $aur_obj ], 'aur.created' );
3357 sub create_user_request_events {
3358 my($e, $user_reqs, $hook) = @_;
3360 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
3363 my %cached_usr_home_ou = ();
3364 for my $user_req (@$user_reqs) {
3365 my $home_ou = $cached_usr_home_ou{$user_req->usr};
3367 my $user = $e->retrieve_actor_user($user_req->usr) or return $e->die_event;
3368 $home_ou = $user->home_ou;
3369 $cached_usr_home_ou{$user_req->usr} = $home_ou;
3371 my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $home_ou);
3380 __PACKAGE__->register_method(
3381 method => "po_note_CUD_batch",
3382 api_name => "open-ils.acq.po_note.cud.batch",
3385 desc => q/Manage purchase order notes/,
3387 {desc => "Authentication token", type => "string"},
3388 {desc => "List of po_notes to manage", type => "array"},
3390 return => {desc => "Stream of successfully managed objects"}
3394 sub po_note_CUD_batch {
3395 my ($self, $conn, $auth, $notes) = @_;
3397 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3398 return $e->die_event unless $e->checkauth;
3401 my $total = @$notes;
3404 foreach my $note (@$notes) {
3406 $note->editor($e->requestor->id);
3407 $note->edit_time("now");
3410 $note->creator($e->requestor->id);
3411 $note = $e->create_acq_po_note($note) or return $e->die_event;
3412 } elsif ($note->isdeleted) {
3413 $e->delete_acq_po_note($note) or return $e->die_event;
3414 } elsif ($note->ischanged) {
3415 $e->update_acq_po_note($note) or return $e->die_event;
3418 unless ($note->isdeleted) {
3419 $note = $e->retrieve_acq_po_note($note->id) or
3420 return $e->die_event;
3424 {"maximum" => $total, "progress" => ++$count, "note" => $note}
3428 $e->commit and $conn->respond_complete or return $e->die_event;
3432 # retrieves a lineitem, fleshes its PO and PL, checks perms
3433 sub fetch_and_check_li {
3436 my $perm_mode = shift || 'read';
3438 my $li = $e->retrieve_acq_lineitem([
3441 flesh_fields => {jub => ['purchase_order', 'picklist']}
3443 ]) or return $e->die_event;
3445 if(my $po = $li->purchase_order) {
3446 my $perms = ($perm_mode eq 'read') ? 'VIEW_PURCHASE_ORDER' : 'CREATE_PURCHASE_ORDER';
3447 return ($li, $e->die_event) unless $e->allowed($perms, $po->ordering_agency);
3449 } elsif(my $pl = $li->picklist) {
3450 my $perms = ($perm_mode eq 'read') ? 'VIEW_PICKLIST' : 'CREATE_PICKLIST';
3451 return ($li, $e->die_event) unless $e->allowed($perms, $pl->org_unit);
3458 __PACKAGE__->register_method(
3459 method => "clone_distrib_form",
3460 api_name => "open-ils.acq.distribution_formula.clone",
3463 desc => q/Clone a distribution formula/,
3465 {desc => "Authentication token", type => "string"},
3466 {desc => "Original formula ID", type => 'integer'},
3467 {desc => "Name of new formula", type => 'string'},
3469 return => {desc => "ID of newly created formula"}
3473 sub clone_distrib_form {
3474 my($self, $client, $auth, $form_id, $new_name) = @_;
3476 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3477 return $e->die_event unless $e->checkauth;
3479 my $old_form = $e->retrieve_acq_distribution_formula($form_id) or return $e->die_event;
3480 return $e->die_event unless $e->allowed('ADMIN_ACQ_DISTRIB_FORMULA', $old_form->owner);
3482 my $new_form = Fieldmapper::acq::distribution_formula->new;
3484 $new_form->owner($old_form->owner);
3485 $new_form->name($new_name);
3486 $e->create_acq_distribution_formula($new_form) or return $e->die_event;
3488 my $entries = $e->search_acq_distribution_formula_entry({formula => $form_id});
3489 for my $entry (@$entries) {
3490 my $new_entry = Fieldmapper::acq::distribution_formula_entry->new;
3491 $new_entry->$_($entry->$_()) for $entry->real_fields;
3492 $new_entry->formula($new_form->id);
3493 $new_entry->clear_id;
3494 $e->create_acq_distribution_formula_entry($new_entry) or return $e->die_event;
3498 return $new_form->id;
3501 __PACKAGE__->register_method(
3502 method => 'add_li_to_po',
3503 api_name => 'open-ils.acq.purchase_order.add_lineitem',
3505 desc => q/Adds a lineitem to an existing purchase order/,
3507 {desc => 'Authentication token', type => 'string'},
3508 {desc => 'The purchase order id', type => 'number'},
3509 {desc => 'The lineitem ID', type => 'number'},
3511 return => {desc => 'Streams a total versus completed counts object, event on error'}
3516 my($self, $conn, $auth, $po_id, $li_id) = @_;
3518 my $e = new_editor(authtoken => $auth, xact => 1);
3519 return $e->die_event unless $e->checkauth;
3521 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
3523 my $po = $e->retrieve_acq_purchase_order($po_id)
3524 or return $e->die_event;
3526 my $li = $e->retrieve_acq_lineitem($li_id)
3527 or return $e->die_event;
3529 return $e->die_event unless
3530 $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
3532 unless ($po->state =~ /new|pending/) {
3534 return {success => 0, po => $po, error => 'bad-po-state'};
3537 unless ($li->state =~ /new|order-ready|pending-order/) {
3539 return {success => 0, li => $li, error => 'bad-li-state'};
3542 $li->provider($po->provider);
3543 $li->purchase_order($po_id);
3544 $li->state('pending-order');
3545 update_lineitem($mgr, $li) or return $e->die_event;
3548 return {success => 1};
3551 __PACKAGE__->register_method(
3552 method => 'po_lineitems_no_copies',
3553 api_name => 'open-ils.acq.purchase_order.no_copy_lineitems.id_list',
3557 desc => q/Returns the set of lineitem IDs for a given PO that have no copies attached/,
3559 {desc => 'Authentication token', type => 'string'},
3560 {desc => 'The purchase order id', type => 'number'},
3562 return => {desc => 'Stream of lineitem IDs on success, event on error'}
3566 sub po_lineitems_no_copies {
3567 my ($self, $conn, $auth, $po_id) = @_;
3569 my $e = new_editor(authtoken => $auth);
3570 return $e->event unless $e->checkauth;
3572 # first check the view perms for LI's attached to this PO
3573 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->event;
3574 return $e->event unless $e->allowed('VIEW_PURCHASE_ORDER', $po->ordering_agency);
3576 my $ids = $e->json_query({
3577 select => {jub => ['id']},
3578 from => {jub => {acqlid => {type => 'left'}}},
3580 '+jub' => {purchase_order => $po_id},
3581 '+acqlid' => {lineitem => undef}
3585 $conn->respond($_->{id}) for @$ids;