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}) {
1652 my $loc = $mgr->cache($base_org, "copy_loc.$name");
1654 for my $org (@$org_path) {
1655 $loc = $mgr->editor->search_asset_copy_location(
1656 {owning_lib => $org, name => $name}, {idlist => 1})->[0];
1660 return $killme->("Invalid copy location $name") unless $loc;
1661 $compiled{copy_location} = $loc;
1662 $mgr->cache($base_org, "copy_loc.$name", $loc);
1670 # ----------------------------------------------------------------------------
1671 # Workflow: Given an existing purchase order, import/create the bibs,
1672 # callnumber and copy objects
1673 # ----------------------------------------------------------------------------
1675 __PACKAGE__->register_method(
1676 method => 'create_po_assets',
1677 api_name => 'open-ils.acq.purchase_order.assets.create',
1679 desc => q/Creates assets for each lineitem in the purchase order/,
1681 {desc => 'Authentication token', type => 'string'},
1682 {desc => 'The purchase order id', type => 'number'},
1684 return => {desc => 'Streams a total versus completed counts object, event on error'}
1686 max_chunk_count => 1
1689 sub create_po_assets {
1690 my($self, $conn, $auth, $po_id, $args) = @_;
1693 my $e = new_editor(authtoken=>$auth, xact=>1);
1694 return $e->die_event unless $e->checkauth;
1695 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1697 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1699 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1701 # it's ugly, but it's fast. Get the total count of lineitem detail objects to process
1702 my $lid_total = $e->json_query({
1703 select => { acqlid => [{aggregate => 1, transform => 'count', column => 'id'}] },
1709 join => {acqpo => {fkey => 'purchase_order', field => 'id'}}
1713 where => {'+acqpo' => {id => $po_id}}
1716 $mgr->total(scalar(@$li_ids) + $lid_total);
1718 create_lineitem_list_assets($mgr, $li_ids, $args->{vandelay})
1719 or return $e->die_event;
1722 update_purchase_order($mgr, $po) or return $e->die_event;
1725 return $mgr->respond_complete;
1730 __PACKAGE__->register_method(
1731 method => 'create_purchase_order_api',
1732 api_name => 'open-ils.acq.purchase_order.create',
1734 desc => 'Creates a new purchase order',
1736 {desc => 'Authentication token', type => 'string'},
1737 {desc => 'purchase_order to create', type => 'object'}
1739 return => {desc => 'The purchase order id, Event on failure'}
1741 max_chunk_count => 1
1744 sub create_purchase_order_api {
1745 my($self, $conn, $auth, $po, $args) = @_;
1748 my $e = new_editor(xact=>1, authtoken=>$auth);
1749 return $e->die_event unless $e->checkauth;
1750 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
1751 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1754 my %pargs = (ordering_agency => $e->requestor->ws_ou); # default
1755 $pargs{provider} = $po->provider if $po->provider;
1756 $pargs{ordering_agency} = $po->ordering_agency if $po->ordering_agency;
1757 $pargs{prepayment_required} = $po->prepayment_required if $po->prepayment_required;
1758 my $vandelay = $args->{vandelay};
1760 $po = create_purchase_order($mgr, %pargs) or return $e->die_event;
1762 my $li_ids = $$args{lineitems};
1766 for my $li_id (@$li_ids) {
1768 my $li = $e->retrieve_acq_lineitem([
1770 {flesh => 1, flesh_fields => {jub => ['attributes']}}
1771 ]) or return $e->die_event;
1773 $li->provider($po->provider);
1774 $li->purchase_order($po->id);
1775 $li->state('pending-order');
1776 update_lineitem($mgr, $li) or return $e->die_event;
1781 # commit before starting the asset creation
1784 if($li_ids and $vandelay) {
1785 create_lineitem_list_assets($mgr, $li_ids, $vandelay, !$$args{create_assets}) or return $e->die_event;
1788 return $mgr->respond_complete;
1793 __PACKAGE__->register_method(
1794 method => 'update_lineitem_fund_batch',
1795 api_name => 'open-ils.acq.lineitem.fund.update.batch',
1798 desc => q/Given a set of lineitem IDS, updates the fund for all attached lineitem details/
1802 sub update_lineitem_fund_batch {
1803 my($self, $conn, $auth, $li_ids, $fund_id) = @_;
1804 my $e = new_editor(xact=>1, authtoken=>$auth);
1805 return $e->die_event unless $e->checkauth;
1806 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1807 for my $li_id (@$li_ids) {
1808 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
1809 return $evt if $evt;
1810 my $li_details = $e->search_acq_lineitem_detail({lineitem => $li_id});
1811 $_->fund($fund_id) and $_->ischanged(1) for @$li_details;
1812 $evt = lineitem_detail_CUD_batch($mgr, $li_details);
1813 return $evt if $evt;
1818 return $mgr->respond_complete;
1823 __PACKAGE__->register_method(
1824 method => 'lineitem_detail_CUD_batch_api',
1825 api_name => 'open-ils.acq.lineitem_detail.cud.batch',
1828 desc => q/Creates a new purchase order line item detail. / .
1829 q/Additionally creates the associated fund_debit/,
1831 {desc => 'Authentication token', type => 'string'},
1832 {desc => 'List of lineitem_details to create', type => 'array'},
1833 {desc => 'Create Debits. Used for creating post-po-asset-creation debits', type => 'bool'},
1835 return => {desc => 'Streaming response of current position in the array'}
1839 __PACKAGE__->register_method(
1840 method => 'lineitem_detail_CUD_batch_api',
1841 api_name => 'open-ils.acq.lineitem_detail.cud.batch.dry_run',
1845 Dry run version of open-ils.acq.lineitem_detail.cud.batch.
1846 In dry_run mode, updated fund_debit's the exceed the warning
1847 percent return an event.
1853 sub lineitem_detail_CUD_batch_api {
1854 my($self, $conn, $auth, $li_details, $create_debits) = @_;
1855 my $e = new_editor(xact=>1, authtoken=>$auth);
1856 return $e->die_event unless $e->checkauth;
1857 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1858 my $dry_run = ($self->api_name =~ /dry_run/o);
1859 my $evt = lineitem_detail_CUD_batch($mgr, $li_details, $create_debits, $dry_run);
1860 return $evt if $evt;
1862 return $mgr->respond_complete;
1866 sub lineitem_detail_CUD_batch {
1867 my($mgr, $li_details, $create_debits, $dry_run) = @_;
1869 $mgr->total(scalar(@$li_details));
1870 my $e = $mgr->editor;
1874 my $fund_cache = {};
1877 for my $lid (@$li_details) {
1879 unless($li = $li_cache{$lid->lineitem}) {
1880 ($li, $evt) = fetch_and_check_li($e, $lid->lineitem, 'write');
1881 return $evt if $evt;
1885 $lid = create_lineitem_detail($mgr, %{$lid->to_bare_hash}) or return $e->die_event;
1886 if($create_debits) {
1887 $li->provider($e->retrieve_acq_provider($li->provider)) or return $e->die_event;
1888 $lid->fund($e->retrieve_acq_fund($lid->fund)) or return $e->die_event;
1889 create_lineitem_detail_debit($mgr, $li, $lid, 0, 1) or return $e->die_event;
1892 } elsif($lid->ischanged) {
1893 return $evt if $evt = handle_changed_lid($e, $lid, $dry_run, $fund_cache);
1895 } elsif($lid->isdeleted) {
1896 delete_lineitem_detail($mgr, $lid) or return $e->die_event;
1899 $mgr->respond(li => $li);
1900 $li_cache{$lid->lineitem} = $li;
1906 sub handle_changed_lid {
1907 my($e, $lid, $dry_run, $fund_cache) = @_;
1909 my $orig_lid = $e->retrieve_acq_lineitem_detail($lid->id) or return $e->die_event;
1911 # updating the fund, so update the debit
1912 if($orig_lid->fund_debit and $orig_lid->fund != $lid->fund) {
1914 my $debit = $e->retrieve_acq_fund_debit($orig_lid->fund_debit);
1915 my $new_fund = $$fund_cache{$lid->fund} =
1916 $$fund_cache{$lid->fund} || $e->retrieve_acq_fund($lid->fund);
1918 # check the thresholds
1919 return $e->die_event if
1920 fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "stop");
1921 return $e->die_event if $dry_run and
1922 fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "warning");
1924 $debit->fund($new_fund->id);
1925 $e->update_acq_fund_debit($debit) or return $e->die_event;
1928 $e->update_acq_lineitem_detail($lid) or return $e->die_event;
1933 __PACKAGE__->register_method(
1934 method => 'receive_po_api',
1935 api_name => 'open-ils.acq.purchase_order.receive'
1938 sub receive_po_api {
1939 my($self, $conn, $auth, $po_id) = @_;
1940 my $e = new_editor(xact => 1, authtoken => $auth);
1941 return $e->die_event unless $e->checkauth;
1942 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1944 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1945 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1947 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1949 for my $li_id (@$li_ids) {
1950 receive_lineitem($mgr, $li_id) or return $e->die_event;
1954 $po->state('received');
1955 update_purchase_order($mgr, $po) or return $e->die_event;
1958 return $mgr->respond_complete;
1962 # At the moment there's a lack of parallelism between the receive and unreceive
1963 # API methods for POs and the API methods for LIs and LIDs. The methods for
1964 # POs stream back objects as they act, whereas the methods for LIs and LIDs
1965 # atomically return an object that describes only what changed (in LIs and LIDs
1966 # themselves or in the objects to which to LIs and LIDs belong).
1968 # The methods for LIs and LIDs work the way they do to faciliate the UI's
1969 # maintaining correct information about the state of these things when a user
1970 # wants to receive or unreceive these objects without refreshing their whole
1971 # display. The UI feature for receiving and un-receiving a whole PO just
1972 # refreshes the whole display, so this absence of parallelism in the UI is also
1973 # relected in this module.
1975 # This could be neatened in the future by making POs receive and unreceive in
1976 # the same way the LIs and LIDs do.
1978 __PACKAGE__->register_method(
1979 method => 'receive_lineitem_detail_api',
1980 api_name => 'open-ils.acq.lineitem_detail.receive',
1982 desc => 'Mark a lineitem_detail as received',
1984 {desc => 'Authentication token', type => 'string'},
1985 {desc => 'lineitem detail ID', type => 'number'}
1988 "on success, object describing changes to LID and possibly " .
1989 "to LI and PO; on error, Event"
1994 sub receive_lineitem_detail_api {
1995 my($self, $conn, $auth, $lid_id) = @_;
1997 my $e = new_editor(xact=>1, authtoken=>$auth);
1998 return $e->die_event unless $e->checkauth;
1999 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2002 "flesh" => 2, "flesh_fields" => {
2003 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
2007 my $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
2009 return $e->die_event unless $e->allowed(
2010 'RECEIVE_PURCHASE_ORDER', $lid->lineitem->purchase_order->ordering_agency);
2013 my $recvd = receive_lineitem_detail($mgr, $lid_id) or return $e->die_event;
2015 # .. and re-retrieve
2016 $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
2018 # Now build result data structure.
2019 my $result = {"lid" => {$lid->id => {"recv_time" => $lid->recv_time}}};
2022 if ($recvd->class_name =~ /::purchase_order/) {
2023 $result->{"po"} = describe_affected_po($e, $recvd);
2025 $lid->lineitem->id => {"state" => $lid->lineitem->state}
2027 } elsif ($recvd->class_name =~ /::lineitem/) {
2028 $result->{"li"} = {$recvd->id => {"state" => $recvd->state}};
2032 describe_affected_po($e, $lid->lineitem->purchase_order);
2038 __PACKAGE__->register_method(
2039 method => 'receive_lineitem_api',
2040 api_name => 'open-ils.acq.lineitem.receive',
2042 desc => 'Mark a lineitem as received',
2044 {desc => 'Authentication token', type => 'string'},
2045 {desc => 'lineitem ID', type => 'number'}
2048 "on success, object describing changes to LI and possibly PO; " .
2054 sub receive_lineitem_api {
2055 my($self, $conn, $auth, $li_id) = @_;
2057 my $e = new_editor(xact=>1, authtoken=>$auth);
2058 return $e->die_event unless $e->checkauth;
2059 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2061 my $li = $e->retrieve_acq_lineitem([
2065 jub => ['purchase_order']
2068 ]) or return $e->die_event;
2070 return $e->die_event unless $e->allowed(
2071 'RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);
2073 my $res = receive_lineitem($mgr, $li_id) or return $e->die_event;
2075 $conn->respond_complete($res);
2076 $mgr->run_post_response_hooks
2080 __PACKAGE__->register_method(
2081 method => 'rollback_receive_po_api',
2082 api_name => 'open-ils.acq.purchase_order.receive.rollback'
2085 sub rollback_receive_po_api {
2086 my($self, $conn, $auth, $po_id) = @_;
2087 my $e = new_editor(xact => 1, authtoken => $auth);
2088 return $e->die_event unless $e->checkauth;
2089 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2091 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2092 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2094 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
2096 for my $li_id (@$li_ids) {
2097 rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
2101 $po->state('on-order');
2102 update_purchase_order($mgr, $po) or return $e->die_event;
2105 return $mgr->respond_complete;
2109 __PACKAGE__->register_method(
2110 method => 'rollback_receive_lineitem_detail_api',
2111 api_name => 'open-ils.acq.lineitem_detail.receive.rollback',
2113 desc => 'Mark a lineitem_detail as Un-received',
2115 {desc => 'Authentication token', type => 'string'},
2116 {desc => 'lineitem detail ID', type => 'number'}
2119 "on success, object describing changes to LID and possibly " .
2120 "to LI and PO; on error, Event"
2125 sub rollback_receive_lineitem_detail_api {
2126 my($self, $conn, $auth, $lid_id) = @_;
2128 my $e = new_editor(xact=>1, authtoken=>$auth);
2129 return $e->die_event unless $e->checkauth;
2130 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2132 my $lid = $e->retrieve_acq_lineitem_detail([
2136 acqlid => ['lineitem'],
2137 jub => ['purchase_order']
2141 my $li = $lid->lineitem;
2142 my $po = $li->purchase_order;
2144 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2148 my $recvd = rollback_receive_lineitem_detail($mgr, $lid_id)
2149 or return $e->die_event;
2152 $result->{"lid"} = {$recvd->id => {"recv_time" => $recvd->recv_time}};
2154 $result->{"lid"} = {$lid->id => {"recv_time" => $lid->recv_time}};
2157 if ($li->state eq "received") {
2158 $li->state("on-order");
2159 $li = update_lineitem($mgr, $li) or return $e->die_event;
2160 $result->{"li"} = {$li->id => {"state" => $li->state}};
2163 if ($po->state eq "received") {
2164 $po->state("on-order");
2165 $po = update_purchase_order($mgr, $po) or return $e->die_event;
2167 $result->{"po"} = describe_affected_po($e, $po);
2169 $e->commit and return $result or return $e->die_event;
2172 __PACKAGE__->register_method(
2173 method => 'rollback_receive_lineitem_api',
2174 api_name => 'open-ils.acq.lineitem.receive.rollback',
2176 desc => 'Mark a lineitem as Un-received',
2178 {desc => 'Authentication token', type => 'string'},
2179 {desc => 'lineitem ID', type => 'number'}
2182 "on success, object describing changes to LI and possibly PO; " .
2188 sub rollback_receive_lineitem_api {
2189 my($self, $conn, $auth, $li_id) = @_;
2191 my $e = new_editor(xact=>1, authtoken=>$auth);
2192 return $e->die_event unless $e->checkauth;
2193 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2195 my $li = $e->retrieve_acq_lineitem([
2197 "flesh" => 1, "flesh_fields" => {"jub" => ["purchase_order"]}
2200 my $po = $li->purchase_order;
2202 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2204 $li = rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
2206 my $result = {"li" => {$li->id => {"state" => $li->state}}};
2207 if ($po->state eq "received") {
2208 $po->state("on-order");
2209 $po = update_purchase_order($mgr, $po) or return $e->die_event;
2211 $result->{"po"} = describe_affected_po($e, $po);
2213 $e->commit and return $result or return $e->die_event;
2217 __PACKAGE__->register_method(
2218 method => 'set_lineitem_price_api',
2219 api_name => 'open-ils.acq.lineitem.price.set',
2221 desc => 'Set lineitem price. If debits already exist, update them as well',
2223 {desc => 'Authentication token', type => 'string'},
2224 {desc => 'lineitem ID', type => 'number'}
2226 return => {desc => 'status blob, Event on error'}
2230 sub set_lineitem_price_api {
2231 my($self, $conn, $auth, $li_id, $price) = @_;
2233 my $e = new_editor(xact=>1, authtoken=>$auth);
2234 return $e->die_event unless $e->checkauth;
2235 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2237 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
2238 return $evt if $evt;
2240 $li->estimated_unit_price($price);
2241 update_lineitem($mgr, $li) or return $e->die_event;
2243 my $lid_ids = $e->search_acq_lineitem_detail(
2244 {lineitem => $li_id, fund_debit => {'!=' => undef}},
2248 for my $lid_id (@$lid_ids) {
2250 my $lid = $e->retrieve_acq_lineitem_detail([
2252 flesh => 1, flesh_fields => {acqlid => ['fund', 'fund_debit']}}
2255 $lid->fund_debit->amount($price);
2256 $e->update_acq_fund_debit($lid->fund_debit) or return $e->die_event;
2262 return $mgr->respond_complete;
2266 __PACKAGE__->register_method(
2267 method => 'clone_picklist_api',
2268 api_name => 'open-ils.acq.picklist.clone',
2270 desc => 'Clones a picklist, including lineitem and lineitem details',
2272 {desc => 'Authentication token', type => 'string'},
2273 {desc => 'Picklist ID', type => 'number'},
2274 {desc => 'New Picklist Name', type => 'string'}
2276 return => {desc => 'status blob, Event on error'}
2280 sub clone_picklist_api {
2281 my($self, $conn, $auth, $pl_id, $name) = @_;
2283 my $e = new_editor(xact=>1, authtoken=>$auth);
2284 return $e->die_event unless $e->checkauth;
2285 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2287 my $old_pl = $e->retrieve_acq_picklist($pl_id);
2288 my $new_pl = create_picklist($mgr, %{$old_pl->to_bare_hash}, name => $name) or return $e->die_event;
2290 my $li_ids = $e->search_acq_lineitem({picklist => $pl_id}, {idlist => 1});
2292 # get the current user
2293 my $cloner = $mgr->editor->requestor->id;
2295 for my $li_id (@$li_ids) {
2297 # copy the lineitems' MARC
2298 my $marc = ($e->retrieve_acq_lineitem($li_id))->marc;
2300 # create a skeletal clone of the item
2301 my $li = Fieldmapper::acq::lineitem->new;
2302 $li->creator($cloner);
2303 $li->selector($cloner);
2304 $li->editor($cloner);
2307 my $new_li = create_lineitem($mgr, %{$li->to_bare_hash}, picklist => $new_pl->id) or return $e->die_event;
2313 return $mgr->respond_complete;
2317 __PACKAGE__->register_method(
2318 method => 'merge_picklist_api',
2319 api_name => 'open-ils.acq.picklist.merge',
2321 desc => 'Merges 2 or more picklists into a single list',
2323 {desc => 'Authentication token', type => 'string'},
2324 {desc => 'Lead Picklist ID', type => 'number'},
2325 {desc => 'List of subordinate picklist IDs', type => 'array'}
2327 return => {desc => 'status blob, Event on error'}
2331 sub merge_picklist_api {
2332 my($self, $conn, $auth, $lead_pl, $pl_list) = @_;
2334 my $e = new_editor(xact=>1, authtoken=>$auth);
2335 return $e->die_event unless $e->checkauth;
2336 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2338 # XXX perms on each picklist modified
2340 $lead_pl = $e->retrieve_acq_picklist($lead_pl) or return $e->die_event;
2341 # point all of the lineitems at the lead picklist
2342 my $li_ids = $e->search_acq_lineitem({picklist => $pl_list}, {idlist => 1});
2344 for my $li_id (@$li_ids) {
2345 my $li = $e->retrieve_acq_lineitem($li_id);
2346 $li->picklist($lead_pl);
2347 update_lineitem($mgr, $li) or return $e->die_event;
2351 # now delete the subordinate lists
2352 for my $pl_id (@$pl_list) {
2353 my $pl = $e->retrieve_acq_picklist($pl_id);
2354 $e->delete_acq_picklist($pl) or return $e->die_event;
2357 update_picklist($mgr, $lead_pl) or return $e->die_event;
2360 return $mgr->respond_complete;
2364 __PACKAGE__->register_method(
2365 method => 'delete_picklist_api',
2366 api_name => 'open-ils.acq.picklist.delete',
2368 desc => q/Deletes a picklist. It also deletes any lineitems in the "new" state. / .
2369 q/Other attached lineitems are detached/,
2371 {desc => 'Authentication token', type => 'string'},
2372 {desc => 'Picklist ID to delete', type => 'number'}
2374 return => {desc => '1 on success, Event on error'}
2378 sub delete_picklist_api {
2379 my($self, $conn, $auth, $picklist_id) = @_;
2380 my $e = new_editor(xact=>1, authtoken=>$auth);
2381 return $e->die_event unless $e->checkauth;
2382 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2383 my $pl = $e->retrieve_acq_picklist($picklist_id) or return $e->die_event;
2384 delete_picklist($mgr, $pl) or return $e->die_event;
2386 return $mgr->respond_complete;
2391 __PACKAGE__->register_method(
2392 method => 'activate_purchase_order',
2393 api_name => 'open-ils.acq.purchase_order.activate.dry_run'
2396 __PACKAGE__->register_method(
2397 method => 'activate_purchase_order',
2398 api_name => 'open-ils.acq.purchase_order.activate',
2400 desc => q/Activates a purchase order. This updates the status of the PO / .
2401 q/and Lineitems to 'on-order'. Activated PO's are ready for EDI delivery if appropriate./,
2403 {desc => 'Authentication token', type => 'string'},
2404 {desc => 'Purchase ID', type => 'number'}
2406 return => {desc => '1 on success, Event on error'}
2410 sub activate_purchase_order {
2411 my($self, $conn, $auth, $po_id, $vandelay, $options) = @_;
2414 my $dry_run = ($self->api_name =~ /\.dry_run/) ? 1 : 0;
2415 my $e = new_editor(authtoken=>$auth);
2416 return $e->die_event unless $e->checkauth;
2417 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2418 my $die_event = activate_purchase_order_impl($mgr, $po_id, $vandelay, $dry_run, $options);
2419 return $e->die_event if $die_event;
2420 $conn->respond_complete(1);
2421 $mgr->run_post_response_hooks unless $dry_run;
2425 # xacts managed within
2426 sub activate_purchase_order_impl {
2427 my ($mgr, $po_id, $vandelay, $dry_run, $options) = @_;
2429 # read-only until lineitem asset creation
2430 my $e = $mgr->editor;
2433 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2434 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
2436 return $e->die_event(OpenILS::Event->new('PO_ALREADY_ACTIVATED'))
2437 if $po->order_date; # PO cannot be re-activated
2439 my $provider = $e->retrieve_acq_provider($po->provider);
2441 # find lineitems and create assets for all
2444 purchase_order => $po_id,
2445 state => [qw/pending-order new order-ready/]
2448 my $li_ids = $e->search_acq_lineitem($query, {idlist => 1});
2450 my $vl_resp; # imported li's and the queue the managing queue
2452 $e->rollback; # read-only thus far
2453 $vl_resp = create_lineitem_list_assets($mgr, $li_ids, $vandelay)
2454 or return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED');
2458 # create fund debits for lineitems
2460 for my $li_id (@$li_ids) {
2461 my $li = $e->retrieve_acq_lineitem($li_id);
2463 if (!$li->eg_bib_id and !$dry_run) {
2464 # we encountered a lineitem that was not successfully imported.
2465 # we cannot continue. rollback and report.
2467 return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED', {queue => $vl_resp->{queue}});
2470 $li->state('on-order');
2471 $li->claim_policy($provider->default_claim_policy)
2472 if $provider->default_claim_policy and !$li->claim_policy;
2473 create_lineitem_debits($mgr, $li, $dry_run, $options) or return $e->die_event;
2474 update_lineitem($mgr, $li) or return $e->die_event;
2475 $mgr->post_process( sub { create_lineitem_status_events($mgr, $li->id, 'aur.ordered'); });
2479 # create po-item debits
2481 for my $po_item (@{$e->search_acq_po_item({purchase_order => $po_id})}) {
2483 my $debit = create_fund_debit(
2486 debit_type => 'direct_charge', # to match invoicing
2487 origin_amount => $po_item->estimated_cost,
2488 origin_currency_type => $e->retrieve_acq_fund($po_item->fund)->currency_type,
2489 amount => $po_item->estimated_cost,
2490 fund => $po_item->fund
2491 ) or return $e->die_event;
2492 $po_item->fund_debit($debit->id);
2493 $e->update_acq_po_item($po_item) or return $e->die_event;
2497 # mark PO as ordered
2499 $po->state('on-order');
2500 $po->order_date('now');
2501 update_purchase_order($mgr, $po) or return $e->die_event;
2504 $dry_run and $e->rollback or $e->commit;
2506 # tell the world we activated a PO
2507 $U->create_events_for_hook('acqpo.activated', $po, $po->ordering_agency) unless $dry_run;
2513 __PACKAGE__->register_method(
2514 method => 'split_purchase_order_by_lineitems',
2515 api_name => 'open-ils.acq.purchase_order.split_by_lineitems',
2517 desc => q/Splits a PO into many POs, 1 per lineitem. Only works for / .
2518 q/POs a) with more than one lineitems, and b) in the "pending" state./,
2520 {desc => 'Authentication token', type => 'string'},
2521 {desc => 'Purchase order ID', type => 'number'}
2523 return => {desc => 'list of new PO IDs on success, Event on error'}
2527 sub split_purchase_order_by_lineitems {
2528 my ($self, $conn, $auth, $po_id) = @_;
2530 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2531 return $e->die_event unless $e->checkauth;
2533 my $po = $e->retrieve_acq_purchase_order([
2536 "flesh_fields" => {"acqpo" => [qw/lineitems notes/]}
2538 ]) or return $e->die_event;
2540 return $e->die_event
2541 unless $e->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2543 unless ($po->state eq "pending") {
2545 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_LATE");
2548 unless (@{$po->lineitems} > 1) {
2550 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_SHORT");
2553 # To split an existing PO into many, it seems unwise to just delete the
2554 # original PO, so we'll instead detach all of the original POs' lineitems
2555 # but the first, then create new POs for each of the remaining LIs, and
2556 # then attach the LIs to their new POs.
2558 my @po_ids = ($po->id);
2559 my @moving_li = @{$po->lineitems};
2560 shift @moving_li; # discard first LI
2562 foreach my $li (@moving_li) {
2563 my $new_po = $po->clone;
2565 $new_po->clear_name;
2566 $new_po->creator($e->requestor->id);
2567 $new_po->editor($e->requestor->id);
2568 $new_po->owner($e->requestor->id);
2569 $new_po->edit_time("now");
2570 $new_po->create_time("now");
2572 $new_po = $e->create_acq_purchase_order($new_po);
2574 # Clone any notes attached to the old PO and attach to the new one.
2575 foreach my $note (@{$po->notes}) {
2576 my $new_note = $note->clone;
2577 $new_note->clear_id;
2578 $new_note->edit_time("now");
2579 $new_note->purchase_order($new_po->id);
2580 $e->create_acq_po_note($new_note);
2583 $li->edit_time("now");
2584 $li->purchase_order($new_po->id);
2585 $e->update_acq_lineitem($li);
2587 push @po_ids, $new_po->id;
2590 $po->edit_time("now");
2591 $e->update_acq_purchase_order($po);
2593 return \@po_ids if $e->commit;
2594 return $e->die_event;
2598 sub not_cancelable {
2600 (ref $o eq "HASH" and $o->{"textcode"} eq "ACQ_NOT_CANCELABLE");
2603 __PACKAGE__->register_method(
2604 method => "cancel_purchase_order_api",
2605 api_name => "open-ils.acq.purchase_order.cancel",
2607 desc => q/Cancels an on-order purchase order/,
2609 {desc => "Authentication token", type => "string"},
2610 {desc => "PO ID to cancel", type => "number"},
2611 {desc => "Cancel reason ID", type => "number"}
2613 return => {desc => q/Object describing changed POs, LIs and LIDs
2614 on success; Event on error./}
2618 sub cancel_purchase_order_api {
2619 my ($self, $conn, $auth, $po_id, $cancel_reason) = @_;
2621 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2622 return $e->die_event unless $e->checkauth;
2623 my $mgr = new OpenILS::Application::Acq::BatchManager(
2624 "editor" => $e, "conn" => $conn
2627 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2628 return new OpenILS::Event(
2629 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2632 my $result = cancel_purchase_order($mgr, $po_id, $cancel_reason) or
2633 return $e->die_event;
2634 if (not_cancelable($result)) { # event not from CStoreEditor
2637 } elsif ($result == -1) {
2639 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2642 $e->commit or return $e->die_event;
2644 # XXX create purchase order status events?
2646 if ($mgr->{post_commit}) {
2647 foreach my $func (@{$mgr->{post_commit}}) {
2655 sub cancel_purchase_order {
2656 my ($mgr, $po_id, $cancel_reason) = @_;
2658 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id) or return 0;
2660 # XXX is "cancelled" a typo? It's not correct US spelling, anyway.
2661 # Depending on context, this may not warrant an event.
2662 return -1 if $po->state eq "cancelled";
2664 # But this always does.
2665 return new OpenILS::Event(
2666 "ACQ_NOT_CANCELABLE", "note" => "purchase_order $po_id"
2667 ) unless ($po->state eq "on-order" or $po->state eq "pending");
2670 $mgr->editor->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2672 $po->state("cancelled");
2673 $po->cancel_reason($cancel_reason->id);
2675 my $li_ids = $mgr->editor->search_acq_lineitem(
2676 {"purchase_order" => $po_id}, {"idlist" => 1}
2679 my $result = {"li" => {}, "lid" => {}};
2680 foreach my $li_id (@$li_ids) {
2681 my $li_result = cancel_lineitem($mgr, $li_id, $cancel_reason)
2684 next if $li_result == -1; # already canceled:skip.
2685 return $li_result if not_cancelable($li_result); # not cancelable:stop.
2687 # Merge in each LI result (there's only going to be
2688 # one per call to cancel_lineitem).
2689 my ($k, $v) = each %{$li_result->{"li"}};
2690 $result->{"li"}->{$k} = $v;
2692 # Merge in each LID result (there may be many per call to
2694 while (($k, $v) = each %{$li_result->{"lid"}}) {
2695 $result->{"lid"}->{$k} = $v;
2699 # TODO who/what/where/how do we indicate this change for electronic orders?
2700 # TODO return changes to encumbered/spent
2701 # TODO maybe cascade up from smaller object to container object if last
2702 # smaller object in the container has been canceled?
2704 update_purchase_order($mgr, $po) or return 0;
2706 $po_id => {"state" => $po->state, "cancel_reason" => $cancel_reason}
2712 __PACKAGE__->register_method(
2713 method => "cancel_lineitem_api",
2714 api_name => "open-ils.acq.lineitem.cancel",
2716 desc => q/Cancels an on-order lineitem/,
2718 {desc => "Authentication token", type => "string"},
2719 {desc => "Lineitem ID to cancel", type => "number"},
2720 {desc => "Cancel reason ID", type => "number"}
2722 return => {desc => q/Object describing changed LIs and LIDs on success;
2727 __PACKAGE__->register_method(
2728 method => "cancel_lineitem_api",
2729 api_name => "open-ils.acq.lineitem.cancel.batch",
2731 desc => q/Batched version of open-ils.acq.lineitem.cancel/,
2732 return => {desc => q/Object describing changed LIs and LIDs on success;
2737 sub cancel_lineitem_api {
2738 my ($self, $conn, $auth, $li_id, $cancel_reason) = @_;
2740 my $batched = $self->api_name =~ /\.batch/;
2742 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2743 return $e->die_event unless $e->checkauth;
2744 my $mgr = new OpenILS::Application::Acq::BatchManager(
2745 "editor" => $e, "conn" => $conn
2748 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2749 return new OpenILS::Event(
2750 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2753 my ($result, $maybe_event);
2756 $result = {"li" => {}, "lid" => {}};
2757 foreach my $one_li_id (@$li_id) {
2758 my $one = cancel_lineitem($mgr, $one_li_id, $cancel_reason) or
2759 return $e->die_event;
2760 if (not_cancelable($one)) {
2761 $maybe_event = $one;
2762 } elsif ($result == -1) {
2763 $maybe_event = new OpenILS::Event("ACQ_ALREADY_CANCELED");
2767 while (($k, $v) = each %{$one->{"li"}}) {
2768 $result->{"li"}->{$k} = $v;
2771 if ($one->{"lid"}) {
2772 while (($k, $v) = each %{$one->{"lid"}}) {
2773 $result->{"lid"}->{$k} = $v;
2779 $result = cancel_lineitem($mgr, $li_id, $cancel_reason) or
2780 return $e->die_event;
2782 if (not_cancelable($result)) {
2785 } elsif ($result == -1) {
2787 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2791 if ($batched and not scalar keys %{$result->{"li"}}) {
2793 return $maybe_event;
2795 $e->commit or return $e->die_event;
2796 # create_lineitem_status_events should handle array li_id ok
2797 create_lineitem_status_events($mgr, $li_id, "aur.cancelled");
2799 if ($mgr->{post_commit}) {
2800 foreach my $func (@{$mgr->{post_commit}}) {
2809 sub cancel_lineitem {
2810 my ($mgr, $li_id, $cancel_reason) = @_;
2811 my $li = $mgr->editor->retrieve_acq_lineitem([
2812 $li_id, {flesh => 1, flesh_fields => {jub => ['purchase_order']}}
2815 return 0 unless $mgr->editor->allowed(
2816 "CREATE_PURCHASE_ORDER", $li->purchase_order->ordering_agency
2819 # Depending on context, this may not warrant an event.
2820 return -1 if $li->state eq "cancelled";
2822 # But this always does.
2823 return new OpenILS::Event(
2824 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id"
2826 (! $li->purchase_order) or (
2827 $li->purchase_order and (
2828 $li->state eq "on-order" or $li->state eq "pending-order"
2833 $li->state("cancelled");
2834 $li->cancel_reason($cancel_reason->id);
2836 my $lids = $mgr->editor->search_acq_lineitem_detail([{
2837 "lineitem" => $li_id
2840 flesh_fields => { acqlid => ['eg_copy_id'] }
2843 my $result = {"lid" => {}};
2845 foreach my $lid (@$lids) {
2846 my $lid_result = cancel_lineitem_detail($mgr, $lid->id, $cancel_reason)
2849 # gathering any real copies for deletion
2850 if ($lid->eg_copy_id) {
2851 $lid->eg_copy_id->isdeleted('t');
2852 push @$copies, $lid->eg_copy_id;
2855 next if $lid_result == -1; # already canceled: just skip it.
2856 return $lid_result if not_cancelable($lid_result); # not cxlable: stop.
2858 # Merge in each LID result (there's only going to be one per call to
2859 # cancel_lineitem_detail).
2860 my ($k, $v) = each %{$lid_result->{"lid"}};
2861 $result->{"lid"}->{$k} = $v;
2864 # Attempt to delete the gathered copies (this will also handle volume deletion and bib deletion)
2865 # Delete empty bibs according org unit setting
2866 my $force_delete_empty_bib = $U->ou_ancestor_setting_value(
2867 $mgr->editor->requestor->ws_ou, 'cat.bib.delete_on_no_copy_via_acq_lineitem_cancel', $mgr->editor);
2868 if (scalar(@$copies)>0) {
2870 my $delete_stats = undef;
2871 my $retarget_holds = [];
2872 my $cat_evt = OpenILS::Application::Cat::AssetCommon->update_fleshed_copies(
2873 $mgr->editor, $override, undef, $copies, $delete_stats, $retarget_holds,$force_delete_empty_bib);
2876 $logger->info("fleshed copy update failed with event: ".OpenSRF::Utils::JSON->perl2JSON($cat_evt));
2877 return new OpenILS::Event(
2878 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id", "payload" => $cat_evt
2882 # We can't do the following and stay within the same transaction, but that's okay, the hold targeter will pick these up later.
2883 #my $ses = OpenSRF::AppSession->create('open-ils.circ');
2884 #$ses->request('open-ils.circ.hold.reset.batch', $auth, $retarget_holds);
2887 # if we have a bib, check to see whether it has been deleted. if so, cancel any active holds targeting that bib
2888 if ($li->eg_bib_id) {
2889 my $bib = $mgr->editor->retrieve_biblio_record_entry($li->eg_bib_id) or return new OpenILS::Event(
2890 "ACQ_NOT_CANCELABLE", "note" => "Could not retrieve bib " . $li->eg_bib_id . " for lineitem $li_id"
2892 if ($U->is_true($bib->deleted)) {
2893 my $holds = $mgr->editor->search_action_hold_request(
2894 { cancel_time => undef,
2895 fulfillment_time => undef,
2896 target => $li->eg_bib_id
2900 my %cached_usr_home_ou = ();
2902 for my $hold (@$holds) {
2904 $logger->info("Cancelling hold ".$hold->id.
2905 " due to acq lineitem cancellation.");
2907 $hold->cancel_time('now');
2908 $hold->cancel_cause(5); # 'Staff forced'--we may want a new hold cancel cause reason for this
2909 $hold->cancel_note('Corresponding Acquistion Lineitem/Purchase Order was cancelled.');
2910 unless($mgr->editor->update_action_hold_request($hold)) {
2911 my $evt = $mgr->editor->event;
2912 $logger->error("Error updating hold ". $evt->textcode .":". $evt->desc .":". $evt->stacktrace);
2913 return new OpenILS::Event(
2914 "ACQ_NOT_CANCELABLE", "note" => "Could not cancel hold " . $hold->id . " for lineitem $li_id", "payload" => $evt
2917 if (! defined $mgr->{post_commit}) { # we need a mechanism for creating trigger events, but only if the transaction gets committed
2918 $mgr->{post_commit} = [];
2920 push @{ $mgr->{post_commit} }, sub {
2921 my $home_ou = $cached_usr_home_ou{$hold->usr};
2923 my $user = $mgr->editor->retrieve_actor_user($hold->usr); # FIXME: how do we want to handle failures here?
2924 $home_ou = $user->home_ou;
2925 $cached_usr_home_ou{$hold->usr} = $home_ou;
2927 $U->create_events_for_hook('hold_request.cancel.cancelled_order', $hold, $home_ou);
2933 update_lineitem($mgr, $li) or return 0;
2936 "state" => $li->state,
2937 "cancel_reason" => $cancel_reason
2944 __PACKAGE__->register_method(
2945 method => "cancel_lineitem_detail_api",
2946 api_name => "open-ils.acq.lineitem_detail.cancel",
2948 desc => q/Cancels an on-order lineitem detail/,
2950 {desc => "Authentication token", type => "string"},
2951 {desc => "Lineitem detail ID to cancel", type => "number"},
2952 {desc => "Cancel reason ID", type => "number"}
2954 return => {desc => q/Object describing changed LIDs on success;
2959 sub cancel_lineitem_detail_api {
2960 my ($self, $conn, $auth, $lid_id, $cancel_reason) = @_;
2962 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2963 return $e->die_event unless $e->checkauth;
2964 my $mgr = new OpenILS::Application::Acq::BatchManager(
2965 "editor" => $e, "conn" => $conn
2968 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2969 return new OpenILS::Event(
2970 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2973 my $result = cancel_lineitem_detail($mgr, $lid_id, $cancel_reason) or
2974 return $e->die_event;
2976 if (not_cancelable($result)) {
2979 } elsif ($result == -1) {
2981 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2984 $e->commit or return $e->die_event;
2986 # XXX create lineitem detail status events?
2990 sub cancel_lineitem_detail {
2991 my ($mgr, $lid_id, $cancel_reason) = @_;
2992 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
2996 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
3001 # Depending on context, this may not warrant an event.
3002 return -1 if $lid->cancel_reason;
3004 # But this always does.
3005 return new OpenILS::Event(
3006 "ACQ_NOT_CANCELABLE", "note" => "lineitem_detail $lid_id"
3008 (! $lid->lineitem->purchase_order) or
3010 (not $lid->recv_time) and
3012 $lid->lineitem->purchase_order and (
3013 $lid->lineitem->state eq "on-order" or
3014 $lid->lineitem->state eq "pending-order"
3019 return 0 unless $mgr->editor->allowed(
3020 "CREATE_PURCHASE_ORDER",
3021 $lid->lineitem->purchase_order->ordering_agency
3022 ) or (! $lid->lineitem->purchase_order);
3024 $lid->cancel_reason($cancel_reason->id);
3026 unless($U->is_true($cancel_reason->keep_debits)) {
3027 my $debit_id = $lid->fund_debit;
3028 $lid->clear_fund_debit;
3031 # item is cancelled. Remove the fund debit.
3032 my $debit = $mgr->editor->retrieve_acq_fund_debit($debit_id);
3033 if (!$U->is_true($debit->encumbrance)) {
3034 $mgr->editor->rollback;
3035 return OpenILS::Event->new('ACQ_NOT_CANCELABLE',
3036 note => "Debit is marked as paid: $debit_id");
3038 $mgr->editor->delete_acq_fund_debit($debit) or return $mgr->editor->die_event;
3042 # XXX LIDs don't have either an editor or a edit_time field. Should we
3043 # update these on the LI when we alter an LID?
3044 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
3046 return {"lid" => {$lid_id => {"cancel_reason" => $cancel_reason}}};
3050 __PACKAGE__->register_method(
3051 method => 'user_requests',
3052 api_name => 'open-ils.acq.user_request.retrieve.by_user_id',
3055 desc => 'Retrieve fleshed user requests and related data for a given user.',
3057 { desc => 'Authentication token', type => 'string' },
3058 { desc => 'User ID of the owner, or array of IDs', },
3059 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
3064 desc => 'Fleshed user requests and related data',
3070 __PACKAGE__->register_method(
3071 method => 'user_requests',
3072 api_name => 'open-ils.acq.user_request.retrieve.by_home_ou',
3075 desc => 'Retrieve fleshed user requests and related data for a given org unit or units.',
3077 { desc => 'Authentication token', type => 'string' },
3078 { desc => 'Org unit ID, or array of IDs', },
3079 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
3084 desc => 'Fleshed user requests and related data',
3091 my($self, $conn, $auth, $search_value, $options) = @_;
3092 my $e = new_editor(authtoken => $auth);
3093 return $e->event unless $e->checkauth;
3094 my $rid = $e->requestor->id;
3098 "select"=>{"aur"=>["id"],"au"=>["home_ou", {column => 'id', alias => 'usr_id'} ]},
3099 "from"=>{ "aur" => { "au" => {}, "jub" => { "type" => "left" } } },
3103 {"id"=>undef}, # this with the left-join pulls in requests without lineitems
3104 {"state"=>["new","on-order","pending-order"]} # FIXME - probably needs softcoding
3108 "order_by"=>[{"class"=>"aur", "field"=>"request_date", "direction"=>"desc"}]
3111 foreach (qw/ order_by limit offset /) {
3112 $query->{$_} = $options->{$_} if defined $options->{$_};
3114 if (defined $options->{'state'}) {
3115 $query->{'where'}->{'+jub'}->{'-or'}->[1]->{'state'} = $options->{'state'};
3118 if ($self->api_name =~ /by_user_id/) {
3119 $query->{'where'}->{'usr'} = $search_value;
3121 $query->{'where'}->{'+au'} = { 'home_ou' => $search_value };
3124 my $pertinent_ids = $e->json_query($query);
3127 for my $id_blob (@$pertinent_ids) {
3128 if ($rid != $id_blob->{usr_id}) {
3129 if (!defined $perm_test{ $id_blob->{home_ou} }) {
3130 $perm_test{ $id_blob->{home_ou} } = $e->allowed( ['user_request.view'], $id_blob->{home_ou} );
3132 if (!$perm_test{ $id_blob->{home_ou} }) {
3136 my $aur_obj = $e->retrieve_acq_user_request([
3138 {flesh => 1, flesh_fields => { "aur" => [ 'lineitem' ] } }
3140 if (! $aur_obj) { next; }
3142 if ($aur_obj->lineitem()) {
3143 $aur_obj->lineitem()->clear_marc();
3145 $conn->respond($aur_obj);
3151 __PACKAGE__->register_method (
3152 method => 'update_user_request',
3153 api_name => 'open-ils.acq.user_request.cancel.batch',
3156 desc => 'If given a cancel reason, will update the request with that reason, otherwise, this will delete the request altogether. The ' .
3157 'intention is for staff interfaces or processes to provide cancel reasons, and for patron interfaces to just delete the requests.' ,
3159 { desc => 'Authentication token', type => 'string' },
3160 { desc => 'ID or array of IDs for the user requests to cancel' },
3161 { desc => 'Cancel Reason ID (optional)', type => 'string' }
3164 desc => 'progress object, event on error',
3168 __PACKAGE__->register_method (
3169 method => 'update_user_request',
3170 api_name => 'open-ils.acq.user_request.set_no_hold.batch',
3173 desc => 'Remove the hold from a user request or set of requests',
3175 { desc => 'Authentication token', type => 'string' },
3176 { desc => 'ID or array of IDs for the user requests to modify' }
3179 desc => 'progress object, event on error',
3184 sub update_user_request {
3185 my($self, $conn, $auth, $aur_ids, $cancel_reason) = @_;
3186 my $e = new_editor(xact => 1, authtoken => $auth);
3187 return $e->die_event unless $e->checkauth;
3188 my $rid = $e->requestor->id;
3192 for my $id (@$aur_ids) {
3194 my $aur_obj = $e->retrieve_acq_user_request([
3197 flesh_fields => { "aur" => ['lineitem', 'usr'] }
3199 ]) or return $e->die_event;
3201 my $context_org = $aur_obj->usr()->home_ou();
3202 $aur_obj->usr( $aur_obj->usr()->id() );
3204 if ($rid != $aur_obj->usr) {
3205 if (!defined $perm_test{ $context_org }) {
3206 $perm_test{ $context_org } = $e->allowed( ['user_request.update'], $context_org );
3208 if (!$perm_test{ $context_org }) {
3213 if($self->api_name =~ /set_no_hold/) {
3214 if ($U->is_true($aur_obj->hold)) {
3216 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3220 if($self->api_name =~ /cancel/) {
3221 if ( $cancel_reason ) {
3222 $aur_obj->cancel_reason( $cancel_reason );
3223 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3224 create_user_request_events( $e, [ $aur_obj ], 'aur.rejected' );
3226 $e->delete_acq_user_request($aur_obj);
3230 $conn->respond({maximum => scalar(@$aur_ids), progress => $x++});
3234 return {complete => 1};
3237 __PACKAGE__->register_method (
3238 method => 'new_user_request',
3239 api_name => 'open-ils.acq.user_request.create',
3241 desc => 'Create a new user request object in the DB',
3243 { desc => 'Authentication token', type => 'string' },
3244 { desc => 'User request data hash. Hash keys match the fields for the "aur" object', type => 'object' }
3247 desc => 'The created user request object, or event on error'
3252 sub new_user_request {
3253 my($self, $conn, $auth, $form_data) = @_;
3254 my $e = new_editor(xact => 1, authtoken => $auth);
3255 return $e->die_event unless $e->checkauth;
3256 my $rid = $e->requestor->id;
3257 my $target_user_fleshed;
3258 if (! defined $$form_data{'usr'}) {
3259 $$form_data{'usr'} = $rid;
3261 if ($$form_data{'usr'} != $rid) {
3262 # See if the requestor can place the request on behalf of a different user.
3263 $target_user_fleshed = $e->retrieve_actor_user($$form_data{'usr'}) or return $e->die_event;
3264 $e->allowed('user_request.create', $target_user_fleshed->home_ou) or return $e->die_event;
3266 $target_user_fleshed = $e->requestor;
3267 $e->allowed('CREATE_PURCHASE_REQUEST') or return $e->die_event;
3269 if (! defined $$form_data{'pickup_lib'}) {
3270 if ($target_user_fleshed->ws_ou) {
3271 $$form_data{'pickup_lib'} = $target_user_fleshed->ws_ou;
3273 $$form_data{'pickup_lib'} = $target_user_fleshed->home_ou;
3276 if (! defined $$form_data{'request_type'}) {
3277 $$form_data{'request_type'} = 1; # Books
3279 my $aur_obj = new Fieldmapper::acq::user_request;
3281 $aur_obj->usr( $$form_data{'usr'} );
3282 $aur_obj->request_date( 'now' );
3283 for my $field ( keys %$form_data ) {
3284 if (defined $$form_data{$field} and $field !~ /^(id|lineitem|eg_bib|request_date|cancel_reason)$/) {
3285 $aur_obj->$field( $$form_data{$field} );
3289 $aur_obj = $e->create_acq_user_request($aur_obj) or return $e->die_event;
3291 $e->commit and create_user_request_events( $e, [ $aur_obj ], 'aur.created' );
3296 sub create_user_request_events {
3297 my($e, $user_reqs, $hook) = @_;
3299 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
3302 my %cached_usr_home_ou = ();
3303 for my $user_req (@$user_reqs) {
3304 my $home_ou = $cached_usr_home_ou{$user_req->usr};
3306 my $user = $e->retrieve_actor_user($user_req->usr) or return $e->die_event;
3307 $home_ou = $user->home_ou;
3308 $cached_usr_home_ou{$user_req->usr} = $home_ou;
3310 my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $home_ou);
3319 __PACKAGE__->register_method(
3320 method => "po_note_CUD_batch",
3321 api_name => "open-ils.acq.po_note.cud.batch",
3324 desc => q/Manage purchase order notes/,
3326 {desc => "Authentication token", type => "string"},
3327 {desc => "List of po_notes to manage", type => "array"},
3329 return => {desc => "Stream of successfully managed objects"}
3333 sub po_note_CUD_batch {
3334 my ($self, $conn, $auth, $notes) = @_;
3336 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3337 return $e->die_event unless $e->checkauth;
3340 my $total = @$notes;
3343 foreach my $note (@$notes) {
3345 $note->editor($e->requestor->id);
3346 $note->edit_time("now");
3349 $note->creator($e->requestor->id);
3350 $note = $e->create_acq_po_note($note) or return $e->die_event;
3351 } elsif ($note->isdeleted) {
3352 $e->delete_acq_po_note($note) or return $e->die_event;
3353 } elsif ($note->ischanged) {
3354 $e->update_acq_po_note($note) or return $e->die_event;
3357 unless ($note->isdeleted) {
3358 $note = $e->retrieve_acq_po_note($note->id) or
3359 return $e->die_event;
3363 {"maximum" => $total, "progress" => ++$count, "note" => $note}
3367 $e->commit and $conn->respond_complete or return $e->die_event;
3371 # retrieves a lineitem, fleshes its PO and PL, checks perms
3372 sub fetch_and_check_li {
3375 my $perm_mode = shift || 'read';
3377 my $li = $e->retrieve_acq_lineitem([
3380 flesh_fields => {jub => ['purchase_order', 'picklist']}
3382 ]) or return $e->die_event;
3384 if(my $po = $li->purchase_order) {
3385 my $perms = ($perm_mode eq 'read') ? 'VIEW_PURCHASE_ORDER' : 'CREATE_PURCHASE_ORDER';
3386 return ($li, $e->die_event) unless $e->allowed($perms, $po->ordering_agency);
3388 } elsif(my $pl = $li->picklist) {
3389 my $perms = ($perm_mode eq 'read') ? 'VIEW_PICKLIST' : 'CREATE_PICKLIST';
3390 return ($li, $e->die_event) unless $e->allowed($perms, $pl->org_unit);
3397 __PACKAGE__->register_method(
3398 method => "clone_distrib_form",
3399 api_name => "open-ils.acq.distribution_formula.clone",
3402 desc => q/Clone a distribution formula/,
3404 {desc => "Authentication token", type => "string"},
3405 {desc => "Original formula ID", type => 'integer'},
3406 {desc => "Name of new formula", type => 'string'},
3408 return => {desc => "ID of newly created formula"}
3412 sub clone_distrib_form {
3413 my($self, $client, $auth, $form_id, $new_name) = @_;
3415 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3416 return $e->die_event unless $e->checkauth;
3418 my $old_form = $e->retrieve_acq_distribution_formula($form_id) or return $e->die_event;
3419 return $e->die_event unless $e->allowed('ADMIN_ACQ_DISTRIB_FORMULA', $old_form->owner);
3421 my $new_form = Fieldmapper::acq::distribution_formula->new;
3423 $new_form->owner($old_form->owner);
3424 $new_form->name($new_name);
3425 $e->create_acq_distribution_formula($new_form) or return $e->die_event;
3427 my $entries = $e->search_acq_distribution_formula_entry({formula => $form_id});
3428 for my $entry (@$entries) {
3429 my $new_entry = Fieldmapper::acq::distribution_formula_entry->new;
3430 $new_entry->$_($entry->$_()) for $entry->real_fields;
3431 $new_entry->formula($new_form->id);
3432 $new_entry->clear_id;
3433 $e->create_acq_distribution_formula_entry($new_entry) or return $e->die_event;
3437 return $new_form->id;
3440 __PACKAGE__->register_method(
3441 method => 'add_li_to_po',
3442 api_name => 'open-ils.acq.purchase_order.add_lineitem',
3444 desc => q/Adds a lineitem to an existing purchase order/,
3446 {desc => 'Authentication token', type => 'string'},
3447 {desc => 'The purchase order id', type => 'number'},
3448 {desc => 'The lineitem ID', type => 'number'},
3450 return => {desc => 'Streams a total versus completed counts object, event on error'}
3455 my($self, $conn, $auth, $po_id, $li_id) = @_;
3457 my $e = new_editor(authtoken => $auth, xact => 1);
3458 return $e->die_event unless $e->checkauth;
3460 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
3462 my $po = $e->retrieve_acq_purchase_order($po_id)
3463 or return $e->die_event;
3465 my $li = $e->retrieve_acq_lineitem($li_id)
3466 or return $e->die_event;
3468 return $e->die_event unless
3469 $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
3471 unless ($po->state =~ /new|pending/) {
3473 return {success => 0, po => $po, error => 'bad-po-state'};
3476 unless ($li->state =~ /new|order-ready|pending-order/) {
3478 return {success => 0, li => $li, error => 'bad-li-state'};
3481 $li->provider($po->provider);
3482 $li->purchase_order($po_id);
3483 $li->state('pending-order');
3484 update_lineitem($mgr, $li) or return $e->die_event;
3487 return {success => 1};
3490 __PACKAGE__->register_method(
3491 method => 'po_lineitems_no_copies',
3492 api_name => 'open-ils.acq.purchase_order.no_copy_lineitems.id_list',
3496 desc => q/Returns the set of lineitem IDs for a given PO that have no copies attached/,
3498 {desc => 'Authentication token', type => 'string'},
3499 {desc => 'The purchase order id', type => 'number'},
3501 return => {desc => 'Stream of lineitem IDs on success, event on error'}
3505 sub po_lineitems_no_copies {
3506 my ($self, $conn, $auth, $po_id) = @_;
3508 my $e = new_editor(authtoken => $auth);
3509 return $e->event unless $e->checkauth;
3511 # first check the view perms for LI's attached to this PO
3512 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->event;
3513 return $e->event unless $e->allowed('VIEW_PURCHASE_ORDER', $po->ordering_agency);
3515 my $ids = $e->json_query({
3516 select => {jub => ['id']},
3517 from => {jub => {acqlid => {type => 'left'}}},
3519 '+jub' => {purchase_order => $po_id},
3520 '+acqlid' => {lineitem => undef}
3524 $conn->respond($_->{id}) for @$ids;