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(5) 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};
52 sub respond_complete {
53 my($self, %other_args) = @_;
55 $self->conn->respond_complete({ %{$self->{args}}, %other_args });
56 $self->run_post_response_hooks;
60 # run the post response hook subs, shifting them off as we go
61 sub run_post_response_hooks {
63 (shift @{$self->{post_proc_queue}})->() while @{$self->{post_proc_queue}};
66 # any subs passed to this method will be run after the call to respond_complete
69 push(@{$self->{post_proc_queue}}, $sub);
74 $self->{args}->{total} = $val if defined $val;
75 $self->{args}->{maximum} = $self->{args}->{total};
76 return $self->{args}->{total};
80 $self->{args}->{purchase_order} = $val if $val;
85 $self->{args}->{picklist} = $val if $val;
90 $self->{args}->{lid} += 1;
91 $self->{args}->{progress} += 1;
96 $self->{args}->{li} += 1;
97 $self->{args}->{progress} += 1;
102 $self->{args}->{vqbr} += 1;
103 $self->{args}->{progress} += 1;
108 $self->{args}->{copies} += 1;
109 $self->{args}->{progress} += 1;
114 $self->{args}->{bibs} += 1;
115 $self->{args}->{progress} += 1;
119 my($self, $amount) = @_;
120 $self->{args}->{debits_accrued} += $amount;
121 $self->{args}->{progress} += 1;
125 my($self, $editor) = @_;
126 $self->{editor} = $editor if defined $editor;
127 return $self->{editor};
131 $self->{args}->{complete} = 1;
136 my($self, $org, $key, $val) = @_;
137 $self->{cache}->{$org} = {} unless $self->{cache}->{org};
138 $self->{cache}->{$org}->{$key} = $val if defined $val;
139 return $self->{cache}->{$org}->{$key};
143 package OpenILS::Application::Acq::Order;
144 use base qw/OpenILS::Application/;
145 use strict; use warnings;
146 # ----------------------------------------------------------------------------
147 # Break up each component of the order process and pieces into managable
148 # actions that can be shared across different workflows
149 # ----------------------------------------------------------------------------
151 use OpenSRF::Utils::Logger qw(:logger);
152 use OpenSRF::Utils::JSON;
153 use OpenSRF::AppSession;
154 use OpenILS::Utils::Fieldmapper;
155 use OpenILS::Utils::CStoreEditor q/:funcs/;
156 use OpenILS::Utils::Normalize qw/clean_marc/;
157 use OpenILS::Const qw/:const/;
158 use OpenSRF::EX q/:try/;
159 use OpenILS::Application::AppUtils;
160 use OpenILS::Application::Cat::BibCommon;
161 use OpenILS::Application::Cat::AssetCommon;
164 use MARC::File::XML (BinaryEncoding => 'UTF-8');
165 use Digest::MD5 qw(md5_hex);
167 $Data::Dumper::Indent = 0;
168 my $U = 'OpenILS::Application::AppUtils';
171 # ----------------------------------------------------------------------------
173 # ----------------------------------------------------------------------------
174 sub create_lineitem {
175 my($mgr, %args) = @_;
176 my $li = Fieldmapper::acq::lineitem->new;
177 $li->creator($mgr->editor->requestor->id);
178 $li->selector($li->creator);
179 $li->editor($li->creator);
180 $li->create_time('now');
181 $li->edit_time('now');
183 $li->$_($args{$_}) for keys %args;
186 $mgr->editor->create_acq_lineitem($li) or return 0;
188 unless($li->estimated_unit_price) {
189 # extract the price from the MARC data
190 my $price = get_li_price_from_attr($mgr->editor, $li) or return $li;
191 $li->estimated_unit_price($price);
192 return update_lineitem($mgr, $li);
198 sub get_li_price_from_attr {
200 my $attrs = $li->attributes || $e->search_acq_lineitem_attr({lineitem => $li->id});
202 for my $attr_type (qw/
203 lineitem_local_attr_definition
204 lineitem_prov_attr_definition
205 lineitem_marc_attr_definition/) {
208 $_->attr_name eq 'estimated_price' and
209 $_->attr_type eq $attr_type } @$attrs;
211 return $attr->attr_value if $attr;
218 sub update_lineitem {
220 $li->edit_time('now');
221 $li->editor($mgr->editor->requestor->id);
223 return $mgr->editor->retrieve_acq_lineitem($mgr->editor->data) if
224 $mgr->editor->update_acq_lineitem($li);
229 # ----------------------------------------------------------------------------
230 # Create real holds from patron requests for a given lineitem
231 # ----------------------------------------------------------------------------
232 sub promote_lineitem_holds {
235 my $requests = $mgr->editor->search_acq_user_request(
236 { lineitem => $li->id,
238 [ { need_before => {'>' => 'now'} },
239 { need_before => undef }
244 for my $request ( @$requests ) {
246 $request->eg_bib( $li->eg_bib_id );
247 $mgr->editor->update_acq_user_request( $request ) or return 0;
249 next unless ($U->is_true( $request->hold ));
251 my $hold = Fieldmapper::action::hold_request->new;
252 $hold->usr( $request->usr );
253 $hold->requestor( $request->usr );
254 $hold->request_time( $request->request_date );
255 $hold->pickup_lib( $request->pickup_lib );
256 $hold->request_lib( $request->pickup_lib );
257 $hold->selection_ou( $request->pickup_lib );
258 $hold->phone_notify( $request->phone_notify );
259 $hold->email_notify( $request->email_notify );
260 $hold->expire_time( $request->need_before );
262 if ($request->holdable_formats) {
263 my $mrm = $mgr->editor->search_metabib_metarecord_source_map( { source => $li->eg_bib_id } )->[0];
265 $hold->hold_type( 'M' );
266 $hold->holdable_formats( $request->holdable_formats );
267 $hold->target( $mrm->metarecord );
271 if (!$hold->target) {
272 $hold->hold_type( 'T' );
273 $hold->target( $li->eg_bib_id );
276 $mgr->editor->create_actor_hold_request( $hold ) or return 0;
282 sub delete_lineitem {
284 $li = $mgr->editor->retrieve_acq_lineitem($li) unless ref $li;
286 # delete the attached lineitem_details
287 my $lid_ids = $mgr->editor->search_acq_lineitem_detail({lineitem => $li->id}, {idlist=>1});
288 for my $lid_id (@$lid_ids) {
289 return 0 unless delete_lineitem_detail($mgr, $lid_id);
293 return $mgr->editor->delete_acq_lineitem($li);
296 # begins and commit transactions as it goes
297 sub create_lineitem_list_assets {
298 my($mgr, $li_ids, $vandelay) = @_;
300 if (check_import_li_marc_perms($mgr, $li_ids)) { # event on error
301 $logger->error("acq-vl: user does not have permission to import acq records");
305 my $res = import_li_bibs_via_vandelay($mgr, $li_ids, $vandelay);
306 return undef unless $res;
308 # create the bibs/volumes/copies for the successfully imported records
309 for my $li_id (@{$res->{li_ids}}) {
310 $mgr->editor->xact_begin;
311 my $data = create_lineitem_assets($mgr, $li_id) or return undef;
312 $mgr->editor->xact_commit;
319 sub test_vandelay_import_args {
320 my $vandelay = shift;
323 return 0 unless $vandelay and
324 ($vandelay->{queue_name} or $vandelay->{existing_queue});
326 # match-based merge/overlay import
327 return 2 if $vandelay->{merge_profile} and (
328 $vandelay->{auto_overlay_exact} or
329 $vandelay->{auto_overlay_1match} or
330 $vandelay->{auto_overlay_best_match}
334 return 2 if $vandelay->{import_no_match};
336 return 1; # queue only
339 sub find_or_create_vandelay_queue {
340 my ($e, $vandelay) = @_;
343 if (my $name = $vandelay->{queue_name}) {
345 # first, see if a queue w/ this name already exists
346 # for this user. If so, use that instead.
348 $queue = $e->search_vandelay_bib_queue(
349 {name => $name, owner => $e->requestor->id})->[0];
353 $logger->info("acq-vl: using existing queue $name");
357 $logger->info("acq-vl: creating new vandelay queue $name");
359 $queue = new Fieldmapper::vandelay::bib_queue;
361 $queue->queue_type('acq');
362 $queue->owner($e->requestor->id);
363 $queue->match_set($vandelay->{match_set} || undef); # avoid ''
364 $queue = $e->create_vandelay_bib_queue($queue) or return undef;
368 $queue = $e->retrieve_vandelay_bib_queue($vandelay->{existing_queue})
376 sub import_li_bibs_via_vandelay {
377 my ($mgr, $li_ids, $vandelay) = @_;
378 my $res = {li_ids => []};
379 my $e = $mgr->editor;
382 my $needs_importing = $e->search_acq_lineitem(
383 {id => $li_ids, eg_bib_id => undef},
387 if (!@$needs_importing) {
388 $logger->info("acq-vl: all records already imported. no Vandelay work to do");
389 return {li_ids => $li_ids};
392 # add the already-imported records to the response list
393 push(@{$res->{li_ids}}, grep { $_ != @$needs_importing } @$li_ids);
395 $logger->info("acq-vl: processing recs via Vandelay with args: ".Dumper($vandelay));
397 my $vl_stat = test_vandelay_import_args($vandelay);
399 $logger->error("acq-vl: invalid vandelay arguments for acq import (queue needed)");
403 my $queue = find_or_create_vandelay_queue($e, $vandelay) or return $res;
404 $mgr->{args}->{queue} = $queue;
406 # load the lineitems into the queue for merge processing
409 for my $li_id (@$needs_importing) {
411 my $li = $e->retrieve_acq_lineitem($li_id) or return $res;
413 my $vqbr = Fieldmapper::vandelay::queued_bib_record->new;
414 $vqbr->marc($li->marc);
415 $vqbr->queue($queue->id);
416 $vqbr->bib_source($vandelay->{bib_source} || undef); # avoid ''
417 $vqbr = $e->create_vandelay_queued_bib_record($vqbr) or return $res;
418 push(@vqbr_ids, $vqbr->id);
422 # tell the acq record which vandelay record it's linked to
423 $li->queued_record($vqbr->id);
424 $e->update_acq_lineitem($li) or return $res;
428 $logger->info("acq-vl: created vandelay records [@vqbr_ids]");
430 # we have to commit the transaction now since
431 # vandelay uses its own transactions.
434 return $res if $vl_stat == 1; # queue only
436 # Import the bibs via vandelay. Note: Vandely will
437 # update acq.lineitem.eg_bib_id on successful import.
439 $vandelay->{report_all} = 1;
440 my $ses = OpenSRF::AppSession->create('open-ils.vandelay');
441 my $req = $ses->request(
442 'open-ils.vandelay.bib_record.list.import',
443 $e->authtoken, \@vqbr_ids, $vandelay);
445 # pull the responses, noting all that were successfully imported
447 while (my $resp = $req->recv(timeout => 600)) {
448 my $stat = $resp->content;
450 if(!$stat or $U->event_code($stat)) { # import failure
451 $logger->error("acq-vl: error importing vandelay record " . Dumper($stat));
455 # "imported" refers to the vqbr id, not the
456 # success/failure of the vqbr merge attempt
457 next unless $stat->{imported};
459 my ($imported) = grep {$_->queued_record eq $stat->{imported}} @lis;
460 my $li_id = $imported->id;
462 if ($stat->{no_import}) {
463 $logger->info("acq-vl: acq lineitem $li_id did not import");
465 } else { # successful import
467 push(@success_lis, $li_id);
470 $logger->info("acq-vl: acq lineitem $li_id successfully merged/imported");
475 $logger->info("acq-vl: successfully imported lineitems [@success_lis]");
477 # add the successfully imported lineitems to the already-imported lineitems
478 push (@{$res->{li_ids}}, @success_lis);
483 # returns event on error, undef on success
484 sub check_import_li_marc_perms {
485 my($mgr, $li_ids) = @_;
487 # if there are any order records that are not linked to
488 # in-db bib records, verify staff has perms to import order records
489 my $order_li = $mgr->editor->search_acq_lineitem(
490 [{id => $li_ids, eg_bib_id => undef}, {limit => 1}], {idlist => 1})->[0];
493 return $mgr->editor->die_event unless
494 $mgr->editor->allowed('IMPORT_ACQ_LINEITEM_BIB_RECORD');
501 # ----------------------------------------------------------------------------
502 # if all of the lineitem details for this lineitem have
503 # been received, mark the lineitem as received
504 # returns 1 on non-received, li on received, 0 on error
505 # ----------------------------------------------------------------------------
507 sub describe_affected_po {
511 OpenILS::Application::Acq::Financials::build_price_summary(
516 "state" => $po->state,
517 "amount_encumbered" => $enc,
518 "amount_spent" => $spent
523 sub check_lineitem_received {
524 my($mgr, $li_id) = @_;
526 my $non_recv = $mgr->editor->search_acq_lineitem_detail(
527 {recv_time => undef, lineitem => $li_id}, {idlist=>1});
529 return 1 if @$non_recv;
531 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
532 $li->state('received');
533 return update_lineitem($mgr, $li);
536 sub receive_lineitem {
537 my($mgr, $li_id, $skip_complete_check) = @_;
538 my $li = $mgr->editor->retrieve_acq_lineitem($li_id) or return 0;
540 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
541 {lineitem => $li_id, recv_time => undef}, {idlist => 1});
543 for my $lid_id (@$lid_ids) {
544 receive_lineitem_detail($mgr, $lid_id, 1) or return 0;
548 $li->state('received');
550 $li = update_lineitem($mgr, $li) or return 0;
551 $mgr->post_process( sub { create_lineitem_status_events($mgr, $li_id, 'aur.received'); });
555 $skip_complete_check or (
556 $po = check_purchase_order_received($mgr, $li->purchase_order)
559 my $result = {"li" => {$li->id => {"state" => $li->state}}};
560 $result->{"po"} = describe_affected_po($mgr->editor, $po) if ref $po;
564 sub rollback_receive_lineitem {
565 my($mgr, $li_id) = @_;
566 my $li = $mgr->editor->retrieve_acq_lineitem($li_id) or return 0;
568 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
569 {lineitem => $li_id, recv_time => {'!=' => undef}}, {idlist => 1});
571 for my $lid_id (@$lid_ids) {
572 rollback_receive_lineitem_detail($mgr, $lid_id, 1) or return 0;
576 $li->state('on-order');
577 return update_lineitem($mgr, $li);
581 sub create_lineitem_status_events {
582 my($mgr, $li_id, $hook) = @_;
584 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
586 my $user_reqs = $mgr->editor->search_acq_user_request([
587 {lineitem => $li_id},
588 {flesh => 1, flesh_fields => {aur => ['usr']}}
591 for my $user_req (@$user_reqs) {
592 my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $user_req->usr->home_ou);
600 # ----------------------------------------------------------------------------
602 # ----------------------------------------------------------------------------
603 sub create_lineitem_detail {
604 my($mgr, %args) = @_;
605 my $lid = Fieldmapper::acq::lineitem_detail->new;
606 $lid->$_($args{$_}) for keys %args;
609 return $mgr->editor->create_acq_lineitem_detail($lid);
613 # flesh out any required data with default values where appropriate
614 sub complete_lineitem_detail {
616 unless($lid->barcode) {
617 my $pfx = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.tmp_barcode_prefix') || 'ACQ';
618 $lid->barcode($pfx.$lid->id);
621 unless($lid->cn_label) {
622 my $pfx = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.tmp_callnumber_prefix') || 'ACQ';
623 $lid->cn_label($pfx.$lid->id);
626 if(!$lid->location and my $loc = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.default_copy_location')) {
627 $lid->location($loc);
630 $lid->circ_modifier(get_default_circ_modifier($mgr, $lid->owning_lib))
631 unless defined $lid->circ_modifier;
633 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
637 sub get_default_circ_modifier {
639 my $code = $mgr->cache($org, 'def_circ_mod');
640 $code = $U->ou_ancestor_setting_value($org, 'acq.default_circ_modifier') unless defined $code;
641 return $mgr->cache($org, 'def_circ_mod', $code) if defined $code;
645 sub delete_lineitem_detail {
647 $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid) unless ref $lid;
648 return $mgr->editor->delete_acq_lineitem_detail($lid);
652 sub receive_lineitem_detail {
653 my($mgr, $lid_id, $skip_complete_check) = @_;
654 my $e = $mgr->editor;
656 my $lid = $e->retrieve_acq_lineitem_detail([
660 acqlid => ['fund_debit']
665 return 1 if $lid->recv_time;
667 $lid->receiver($e->requestor->id);
668 $lid->recv_time('now');
669 $e->update_acq_lineitem_detail($lid) or return 0;
671 if ($lid->eg_copy_id) {
672 my $copy = $e->retrieve_asset_copy($lid->eg_copy_id) or return 0;
673 $copy->status(OILS_COPY_STATUS_IN_PROCESS);
674 $copy->edit_date('now');
675 $copy->editor($e->requestor->id);
676 $copy->creator($e->requestor->id) if $U->ou_ancestor_setting_value(
677 $e->requestor->ws_ou, 'acq.copy_creator_uses_receiver', $e);
678 $e->update_asset_copy($copy) or return 0;
683 return 1 if $skip_complete_check;
685 my $li = check_lineitem_received($mgr, $lid->lineitem) or return 0;
686 return 1 if $li == 1; # li not received
688 return check_purchase_order_received($mgr, $li->purchase_order) or return 0;
692 sub rollback_receive_lineitem_detail {
693 my($mgr, $lid_id) = @_;
694 my $e = $mgr->editor;
696 my $lid = $e->retrieve_acq_lineitem_detail([
700 acqlid => ['fund_debit']
705 return 1 unless $lid->recv_time;
707 $lid->clear_receiver;
708 $lid->clear_recv_time;
709 $e->update_acq_lineitem_detail($lid) or return 0;
711 if ($lid->eg_copy_id) {
712 my $copy = $e->retrieve_asset_copy($lid->eg_copy_id) or return 0;
713 $copy->status(OILS_COPY_STATUS_ON_ORDER);
714 $copy->edit_date('now');
715 $copy->editor($e->requestor->id);
716 $e->update_asset_copy($copy) or return 0;
723 # ----------------------------------------------------------------------------
725 # ----------------------------------------------------------------------------
726 sub set_lineitem_attr {
727 my($mgr, %args) = @_;
728 my $attr_type = $args{attr_type};
730 # first, see if it's already set. May just need to overwrite it
731 my $attr = $mgr->editor->search_acq_lineitem_attr({
732 lineitem => $args{lineitem},
733 attr_type => $args{attr_type},
734 attr_name => $args{attr_name}
738 $attr->attr_value($args{attr_value});
739 return $attr if $mgr->editor->update_acq_lineitem_attr($attr);
744 $attr = Fieldmapper::acq::lineitem_attr->new;
745 $attr->$_($args{$_}) for keys %args;
747 unless($attr->definition) {
748 my $find = "search_acq_$attr_type";
749 my $attr_def_id = $mgr->editor->$find({code => $attr->attr_name}, {idlist=>1})->[0] or return 0;
750 $attr->definition($attr_def_id);
752 return $mgr->editor->create_acq_lineitem_attr($attr);
756 # ----------------------------------------------------------------------------
758 # ----------------------------------------------------------------------------
759 sub create_lineitem_debits {
760 my ($mgr, $li, $dry_run) = @_;
762 unless($li->estimated_unit_price) {
763 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_PRICE', payload => $li->id));
764 $mgr->editor->rollback;
768 unless($li->provider) {
769 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_PROVIDER', payload => $li->id));
770 $mgr->editor->rollback;
774 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
775 {lineitem => $li->id},
779 for my $lid_id (@$lid_ids) {
781 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
784 flesh_fields => {acqlid => ['fund']}
788 create_lineitem_detail_debit($mgr, $li, $lid, $dry_run) or return 0;
797 sub create_lineitem_detail_debit {
798 my ($mgr, $li, $lid, $dry_run, $no_translate) = @_;
800 # don't create the debit if one already exists
801 return $mgr->editor->retrieve_acq_fund_debit($lid->fund_debit) if $lid->fund_debit;
803 my $li_id = ref($li) ? $li->id : $li;
805 unless(ref $li and ref $li->provider) {
806 $li = $mgr->editor->retrieve_acq_lineitem([
809 flesh_fields => {jub => ['provider']},
815 $lid->fund($mgr->editor->retrieve_acq_fund($lid->fund)) unless(ref $lid->fund);
817 $lid = $mgr->editor->retrieve_acq_lineitem_detail([
820 flesh_fields => {acqlid => ['fund']}
825 unless ($lid->fund) {
827 new OpenILS::Event("ACQ_FUND_NOT_FOUND") # close enough
832 my $amount = $li->estimated_unit_price;
833 if($li->provider->currency_type ne $lid->fund->currency_type and !$no_translate) {
835 # At Fund debit creation time, translate into the currency of the fund
836 # TODO: org setting to disable automatic currency conversion at debit create time?
838 $amount = $mgr->editor->json_query({
840 'acq.exchange_ratio',
841 $li->provider->currency_type, # source currency
842 $lid->fund->currency_type, # destination currency
843 $li->estimated_unit_price # source amount
845 })->[0]->{'acq.exchange_ratio'};
848 my $debit = create_fund_debit(
851 fund => $lid->fund->id,
852 origin_amount => $li->estimated_unit_price,
853 origin_currency_type => $li->provider->currency_type,
857 $lid->fund_debit($debit->id);
858 $lid->fund($lid->fund->id);
859 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
864 __PACKAGE__->register_method(
865 "method" => "fund_exceeds_balance_percent_api",
866 "api_name" => "open-ils.acq.fund.check_balance_percentages",
868 "desc" => q/Determine whether a given fund exceeds its defined
869 "balance stop and warning percentages"/,
871 {"desc" => "Authentication token", "type" => "string"},
872 {"desc" => "Fund ID", "type" => "number"},
873 {"desc" => "Theoretical debit amount (optional)",
876 "return" => {"desc" => q/An array of two values, for stop and warning,
877 in that order: 1 if fund exceeds that balance percentage, else 0/}
881 sub fund_exceeds_balance_percent_api {
882 my ($self, $conn, $auth, $fund_id, $debit_amount) = @_;
886 my $e = new_editor("authtoken" => $auth);
887 return $e->die_event unless $e->checkauth;
889 my $fund = $e->retrieve_acq_fund($fund_id) or return $e->die_event;
890 return $e->die_event unless $e->allowed("VIEW_FUND", $fund->org);
893 fund_exceeds_balance_percent($fund, $debit_amount, $e, "stop"),
894 fund_exceeds_balance_percent($fund, $debit_amount, $e, "warning")
901 sub fund_exceeds_balance_percent {
902 my ($fund, $debit_amount, $e, $which) = @_;
904 my ($method_name, $event_name) = @{{
906 "balance_warning_percent", "ACQ_FUND_EXCEEDS_WARN_PERCENT"
909 "balance_stop_percent", "ACQ_FUND_EXCEEDS_STOP_PERCENT"
913 if ($fund->$method_name) {
915 $e->search_acq_fund_combined_balance({"fund" => $fund->id})->[0];
917 $e->search_acq_fund_allocation_total({"fund" => $fund->id})->[0];
919 $balance = ($balance) ? $balance->amount : 0;
920 $allocations = ($allocations) ? $allocations->amount : 0;
923 $allocations == 0 || # if no allocations were ever made, assume we have hit the stop percent
924 ((($allocations - $balance + $debit_amount) / $allocations) * 100) > $fund->$method_name
926 $logger->info("fund would hit a limit: " . $fund->id . ", $balance, $debit_amount, $allocations, $method_name");
931 "fund" => $fund, "debit_amount" => $debit_amount
941 # ----------------------------------------------------------------------------
943 # ----------------------------------------------------------------------------
944 sub create_fund_debit {
945 my($mgr, $dry_run, %args) = @_;
947 # Verify the fund is not being spent beyond the hard stop amount
948 my $fund = $mgr->editor->retrieve_acq_fund($args{fund}) or return 0;
951 fund_exceeds_balance_percent(
952 $fund, $args{"amount"}, $mgr->editor, "stop"
955 $dry_run and fund_exceeds_balance_percent(
956 $fund, $args{"amount"}, $mgr->editor, "warning"
959 my $debit = Fieldmapper::acq::fund_debit->new;
960 $debit->debit_type('purchase');
961 $debit->encumbrance('t');
962 $debit->$_($args{$_}) for keys %args;
964 $mgr->add_debit($debit->amount);
965 return $mgr->editor->create_acq_fund_debit($debit);
969 # ----------------------------------------------------------------------------
971 # ----------------------------------------------------------------------------
972 sub create_picklist {
973 my($mgr, %args) = @_;
974 my $picklist = Fieldmapper::acq::picklist->new;
975 $picklist->creator($mgr->editor->requestor->id);
976 $picklist->owner($picklist->creator);
977 $picklist->editor($picklist->creator);
978 $picklist->create_time('now');
979 $picklist->edit_time('now');
980 $picklist->org_unit($mgr->editor->requestor->ws_ou);
981 $picklist->owner($mgr->editor->requestor->id);
982 $picklist->$_($args{$_}) for keys %args;
984 $mgr->picklist($picklist);
985 return $mgr->editor->create_acq_picklist($picklist);
988 sub update_picklist {
989 my($mgr, $picklist) = @_;
990 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
991 $picklist->edit_time('now');
992 $picklist->editor($mgr->editor->requestor->id);
993 if ($mgr->editor->update_acq_picklist($picklist)) {
994 $picklist = $mgr->editor->retrieve_acq_picklist($mgr->editor->data);
995 $mgr->picklist($picklist);
1002 sub delete_picklist {
1003 my($mgr, $picklist) = @_;
1004 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
1006 # delete all 'new' lineitems
1007 my $li_ids = $mgr->editor->search_acq_lineitem(
1009 picklist => $picklist->id,
1010 "-or" => {state => "new", purchase_order => undef}
1014 for my $li_id (@$li_ids) {
1015 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
1016 return 0 unless delete_lineitem($mgr, $li);
1020 # detach all non-'new' lineitems
1021 $li_ids = $mgr->editor->search_acq_lineitem({picklist => $picklist->id, state => {'!=' => 'new'}}, {idlist => 1});
1022 for my $li_id (@$li_ids) {
1023 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
1024 $li->clear_picklist;
1025 return 0 unless update_lineitem($mgr, $li);
1029 # remove any picklist-specific object perms
1030 my $ops = $mgr->editor->search_permission_usr_object_perm_map({object_type => 'acqpl', object_id => ''.$picklist->id});
1031 for my $op (@$ops) {
1032 return 0 unless $mgr->editor->delete_usr_object_perm_map($op);
1035 return $mgr->editor->delete_acq_picklist($picklist);
1038 # ----------------------------------------------------------------------------
1040 # ----------------------------------------------------------------------------
1041 sub update_purchase_order {
1043 $po = $mgr->editor->retrieve_acq_purchase_order($po) unless ref $po;
1044 $po->editor($mgr->editor->requestor->id);
1045 $po->edit_time('now');
1046 $mgr->purchase_order($po);
1047 return $mgr->editor->retrieve_acq_purchase_order($mgr->editor->data)
1048 if $mgr->editor->update_acq_purchase_order($po);
1052 sub create_purchase_order {
1053 my($mgr, %args) = @_;
1055 # verify the chosen provider is still active
1056 my $provider = $mgr->editor->retrieve_acq_provider($args{provider}) or return 0;
1057 unless($U->is_true($provider->active)) {
1058 $logger->error("provider is not active. cannot create PO");
1059 $mgr->editor->event(OpenILS::Event->new('ACQ_PROVIDER_INACTIVE'));
1063 my $po = Fieldmapper::acq::purchase_order->new;
1064 $po->creator($mgr->editor->requestor->id);
1065 $po->editor($mgr->editor->requestor->id);
1066 $po->owner($mgr->editor->requestor->id);
1067 $po->edit_time('now');
1068 $po->create_time('now');
1069 $po->state('pending');
1070 $po->ordering_agency($mgr->editor->requestor->ws_ou);
1071 $po->$_($args{$_}) for keys %args;
1073 $mgr->purchase_order($po);
1074 return $mgr->editor->create_acq_purchase_order($po);
1077 # ----------------------------------------------------------------------------
1078 # if all of the lineitems for this PO are received,
1079 # mark the PO as received
1080 # ----------------------------------------------------------------------------
1081 sub check_purchase_order_received {
1082 my($mgr, $po_id) = @_;
1084 my $non_recv_li = $mgr->editor->search_acq_lineitem(
1085 { purchase_order => $po_id,
1086 state => {'!=' => 'received'}
1089 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id);
1090 return $po if @$non_recv_li;
1092 $po->state('received');
1093 return update_purchase_order($mgr, $po);
1097 # ----------------------------------------------------------------------------
1098 # Bib, Callnumber, and Copy data
1099 # ----------------------------------------------------------------------------
1101 sub create_lineitem_assets {
1102 my($mgr, $li_id) = @_;
1105 my $li = $mgr->editor->retrieve_acq_lineitem([
1108 flesh_fields => {jub => ['purchase_order', 'attributes']}
1112 # note: at this point, the bib record this LI links to should already be created
1114 # -----------------------------------------------------------------
1115 # The lineitem is going live, promote user request holds to real holds
1116 # -----------------------------------------------------------------
1117 promote_lineitem_holds($mgr, $li) or return 0;
1119 my $li_details = $mgr->editor->search_acq_lineitem_detail({lineitem => $li_id}, {idlist=>1});
1121 # -----------------------------------------------------------------
1122 # for each lineitem_detail, create the volume if necessary, create
1123 # a copy, and link them all together.
1124 # -----------------------------------------------------------------
1126 for my $lid_id (@{$li_details}) {
1128 my $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid_id) or return 0;
1129 next if $lid->eg_copy_id;
1131 # use the same callnumber label for all items within this lineitem
1132 $lid->cn_label($first_cn) if $first_cn and not $lid->cn_label;
1134 # apply defaults if necessary
1135 return 0 unless complete_lineitem_detail($mgr, $lid);
1137 $first_cn = $lid->cn_label unless $first_cn;
1139 my $org = $lid->owning_lib;
1140 my $label = $lid->cn_label;
1141 my $bibid = $li->eg_bib_id;
1143 my $volume = $mgr->cache($org, "cn.$bibid.$label");
1145 $volume = create_volume($mgr, $li, $lid) or return 0;
1146 $mgr->cache($org, "cn.$bibid.$label", $volume);
1148 create_copy($mgr, $volume, $lid, $li) or return 0;
1151 return { li => $li };
1155 my($mgr, $li, $lid) = @_;
1157 my ($volume, $evt) =
1158 OpenILS::Application::Cat::AssetCommon->find_or_create_volume(
1166 $mgr->editor->event($evt);
1174 my($mgr, $volume, $lid, $li) = @_;
1175 my $copy = Fieldmapper::asset::copy->new;
1177 $copy->loan_duration(2);
1178 $copy->fine_level(2);
1179 $copy->status(($lid->recv_time) ? OILS_COPY_STATUS_IN_PROCESS : OILS_COPY_STATUS_ON_ORDER);
1180 $copy->barcode($lid->barcode);
1181 $copy->location($lid->location);
1182 $copy->call_number($volume->id);
1183 $copy->circ_lib($volume->owning_lib);
1184 $copy->circ_modifier($lid->circ_modifier);
1186 # AKA list price. We might need a $li->list_price field since
1187 # estimated price is not necessarily the same as list price
1188 $copy->price($li->estimated_unit_price);
1190 my $evt = OpenILS::Application::Cat::AssetCommon->create_copy($mgr->editor, $volume, $copy);
1192 $mgr->editor->event($evt);
1197 $lid->eg_copy_id($copy->id);
1198 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
1206 # ----------------------------------------------------------------------------
1207 # Workflow: Build a selection list from a Z39.50 search
1208 # ----------------------------------------------------------------------------
1210 __PACKAGE__->register_method(
1211 method => 'zsearch',
1212 api_name => 'open-ils.acq.picklist.search.z3950',
1215 desc => 'Performs a z3950 federated search and creates a picklist and associated lineitems',
1217 {desc => 'Authentication token', type => 'string'},
1218 {desc => 'Search definition', type => 'object'},
1219 {desc => 'Picklist name, optional', type => 'string'},
1225 my($self, $conn, $auth, $search, $name, $options) = @_;
1226 my $e = new_editor(authtoken=>$auth);
1227 return $e->event unless $e->checkauth;
1228 return $e->event unless $e->allowed('CREATE_PICKLIST');
1230 $search->{limit} ||= 10;
1233 my $ses = OpenSRF::AppSession->create('open-ils.search');
1234 my $req = $ses->request('open-ils.search.z3950.search_class', $auth, $search);
1239 while(my $resp = $req->recv(timeout=>60)) {
1242 my $e = new_editor(requestor=>$e->requestor, xact=>1);
1243 $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1244 $picklist = zsearch_build_pl($mgr, $name);
1248 my $result = $resp->content;
1249 my $count = $result->{count} || 0;
1250 $mgr->total( (($count < $search->{limit}) ? $count : $search->{limit})+1 );
1252 for my $rec (@{$result->{records}}) {
1254 my $li = create_lineitem($mgr,
1255 picklist => $picklist->id,
1256 source_label => $result->{service},
1257 marc => $rec->{marcxml},
1258 eg_bib_id => $rec->{bibid}
1261 if($$options{respond_li}) {
1262 $li->attributes($mgr->editor->search_acq_lineitem_attr({lineitem => $li->id}))
1263 if $$options{flesh_attrs};
1264 $li->clear_marc if $$options{clear_marc};
1265 $mgr->respond(lineitem => $li);
1272 $mgr->editor->commit;
1273 return $mgr->respond_complete;
1276 sub zsearch_build_pl {
1277 my($mgr, $name) = @_;
1280 my $picklist = $mgr->editor->search_acq_picklist({
1281 owner => $mgr->editor->requestor->id,
1285 if($name eq '' and $picklist) {
1286 return 0 unless delete_picklist($mgr, $picklist);
1290 return update_picklist($mgr, $picklist) if $picklist;
1291 return create_picklist($mgr, name => $name);
1295 # ----------------------------------------------------------------------------
1296 # Workflow: Build a selection list / PO by importing a batch of MARC records
1297 # ----------------------------------------------------------------------------
1299 __PACKAGE__->register_method(
1300 method => 'upload_records',
1301 api_name => 'open-ils.acq.process_upload_records',
1303 max_chunk_count => 1
1306 sub upload_records {
1307 my($self, $conn, $auth, $key, $args) = @_;
1310 my $e = new_editor(authtoken => $auth, xact => 1);
1311 return $e->die_event unless $e->checkauth;
1312 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1314 my $cache = OpenSRF::Utils::Cache->new;
1316 my $data = $cache->get_cache("vandelay_import_spool_$key");
1317 my $filename = $data->{path};
1318 my $provider = $args->{provider};
1319 my $picklist = $args->{picklist};
1320 my $create_po = $args->{create_po};
1321 my $activate_po = $args->{activate_po};
1322 my $vandelay = $args->{vandelay};
1323 my $ordering_agency = $args->{ordering_agency} || $e->requestor->ws_ou;
1327 unless(-r $filename) {
1328 $logger->error("unable to read MARC file $filename");
1330 return OpenILS::Event->new('FILE_UPLOAD_ERROR', payload => {filename => $filename});
1333 $provider = $e->retrieve_acq_provider($provider) or return $e->die_event;
1336 $picklist = $e->retrieve_acq_picklist($picklist) or return $e->die_event;
1337 if($picklist->owner != $e->requestor->id) {
1338 return $e->die_event unless
1339 $e->allowed('CREATE_PICKLIST', $picklist->org_unit, $picklist);
1341 $mgr->picklist($picklist);
1345 return $e->die_event unless
1346 $e->allowed('CREATE_PURCHASE_ORDER', $ordering_agency);
1348 $po = create_purchase_order($mgr,
1349 ordering_agency => $ordering_agency,
1350 provider => $provider->id,
1352 ) or return $mgr->editor->die_event;
1355 $logger->info("acq processing MARC file=$filename");
1357 my $batch = new MARC::Batch ('USMARC', $filename);
1365 my ($err, $xml, $r);
1370 } catch Error with {
1372 $logger->warn("Proccessing of record $count in set $key failed with error $err. Skipping this record");
1379 $xml = clean_marc($r);
1380 } catch Error with {
1382 $logger->warn("Proccessing XML of record $count in set $key failed with error $err. Skipping this record");
1385 next if $err or not $xml;
1388 source_label => $provider->code,
1389 provider => $provider->id,
1393 $args{picklist} = $picklist->id if $picklist;
1395 $args{purchase_order} = $po->id;
1396 $args{state} = 'pending-order';
1399 my $li = create_lineitem($mgr, %args) or return $mgr->editor->die_event;
1401 $li->provider($provider); # flesh it, we'll need it later
1403 import_lineitem_details($mgr, $ordering_agency, $li) or return $mgr->editor->die_event;
1406 push(@li_list, $li->id);
1412 $cache->delete_cache('vandelay_import_spool_' . $key);
1414 if ($po and $activate_po) {
1415 my $die_event = activate_purchase_order_impl($mgr, $po->id, $vandelay);
1416 return $die_event if $die_event;
1418 } elsif ($vandelay) {
1419 $vandelay->{new_rec_perm} = 'IMPORT_ACQ_LINEITEM_BIB_RECORD_UPLOAD';
1420 create_lineitem_list_assets($mgr, \@li_list, $vandelay) or return $e->die_event;
1423 return $mgr->respond_complete;
1426 sub import_lineitem_details {
1427 my($mgr, $ordering_agency, $li) = @_;
1429 my $holdings = $mgr->editor->json_query({from => ['acq.extract_provider_holding_data', $li->id]});
1430 return 1 unless @$holdings;
1431 my $org_path = $U->get_org_ancestors($ordering_agency);
1432 $org_path = [ reverse (@$org_path) ];
1438 # create a lineitem detail for each copy in the data
1440 my $compiled = extract_lineitem_detail_data($mgr, $org_path, $holdings, $idx);
1441 last unless defined $compiled;
1442 return 0 unless $compiled;
1444 # this takes the price of the last copy and uses it as the lineitem price
1445 # need to determine if a given record would include different prices for the same item
1446 $price = $$compiled{estimated_price};
1448 last unless $$compiled{quantity};
1450 for(1..$$compiled{quantity}) {
1451 my $lid = create_lineitem_detail(
1453 lineitem => $li->id,
1454 owning_lib => $$compiled{owning_lib},
1455 cn_label => $$compiled{call_number},
1456 fund => $$compiled{fund},
1457 circ_modifier => $$compiled{circ_modifier},
1458 note => $$compiled{note},
1459 location => $$compiled{copy_location},
1460 collection_code => $$compiled{collection_code},
1461 barcode => $$compiled{barcode}
1469 $li->estimated_unit_price($price);
1470 update_lineitem($mgr, $li) or return 0;
1474 # return hash on success, 0 on error, undef on no more holdings
1475 sub extract_lineitem_detail_data {
1476 my($mgr, $org_path, $holdings, $index) = @_;
1478 my @data_list = grep { $_->{holding} eq $index } @$holdings;
1479 return undef unless @data_list;
1481 my %compiled = map { $_->{attr} => $_->{data} } @data_list;
1482 my $base_org = $$org_path[0];
1486 $logger->error("Item import extraction error: $msg");
1487 $logger->error('Holdings Data: ' . OpenSRF::Utils::JSON->perl2JSON(\%compiled));
1488 $mgr->editor->rollback;
1489 $mgr->editor->event(OpenILS::Event->new('ACQ_IMPORT_ERROR', payload => $msg));
1493 # ---------------------------------------------------------------------
1495 if(my $code = $compiled{fund_code}) {
1497 my $fund = $mgr->cache($base_org, "fund.$code");
1499 # search up the org tree for the most appropriate fund
1500 for my $org (@$org_path) {
1501 $fund = $mgr->editor->search_acq_fund(
1502 {org => $org, code => $code, year => DateTime->now->year}, {idlist => 1})->[0];
1506 return $killme->("no fund with code $code at orgs [@$org_path]") unless $fund;
1507 $compiled{fund} = $fund;
1508 $mgr->cache($base_org, "fund.$code", $fund);
1512 # ---------------------------------------------------------------------
1514 if(my $sn = $compiled{owning_lib}) {
1515 my $org_id = $mgr->cache($base_org, "orgsn.$sn") ||
1516 $mgr->editor->search_actor_org_unit({shortname => $sn}, {idlist => 1})->[0];
1517 return $killme->("invalid owning_lib defined: $sn") unless $org_id;
1518 $compiled{owning_lib} = $org_id;
1519 $mgr->cache($$org_path[0], "orgsn.$sn", $org_id);
1523 # ---------------------------------------------------------------------
1525 my $code = $compiled{circ_modifier};
1529 # verify this is a valid circ modifier
1530 return $killme->("invlalid circ_modifier $code") unless
1531 defined $mgr->cache($base_org, "mod.$code") or
1532 $mgr->editor->retrieve_config_circ_modifier($code);
1534 # if valid, cache for future tests
1535 $mgr->cache($base_org, "mod.$code", $code);
1538 $compiled{circ_modifier} = get_default_circ_modifier($mgr, $base_org);
1542 # ---------------------------------------------------------------------
1544 if( my $name = $compiled{copy_location}) {
1545 my $loc = $mgr->cache($base_org, "copy_loc.$name");
1547 for my $org (@$org_path) {
1548 $loc = $mgr->editor->search_asset_copy_location(
1549 {owning_lib => $org, name => $name}, {idlist => 1})->[0];
1553 return $killme->("Invalid copy location $name") unless $loc;
1554 $compiled{copy_location} = $loc;
1555 $mgr->cache($base_org, "copy_loc.$name", $loc);
1563 # ----------------------------------------------------------------------------
1564 # Workflow: Given an existing purchase order, import/create the bibs,
1565 # callnumber and copy objects
1566 # ----------------------------------------------------------------------------
1568 __PACKAGE__->register_method(
1569 method => 'create_po_assets',
1570 api_name => 'open-ils.acq.purchase_order.assets.create',
1572 desc => q/Creates assets for each lineitem in the purchase order/,
1574 {desc => 'Authentication token', type => 'string'},
1575 {desc => 'The purchase order id', type => 'number'},
1577 return => {desc => 'Streams a total versus completed counts object, event on error'}
1579 max_chunk_count => 1
1582 sub create_po_assets {
1583 my($self, $conn, $auth, $po_id, $args) = @_;
1586 my $e = new_editor(authtoken=>$auth, xact=>1);
1587 return $e->die_event unless $e->checkauth;
1588 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1590 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1592 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1594 # it's ugly, but it's fast. Get the total count of lineitem detail objects to process
1595 my $lid_total = $e->json_query({
1596 select => { acqlid => [{aggregate => 1, transform => 'count', column => 'id'}] },
1602 join => {acqpo => {fkey => 'purchase_order', field => 'id'}}
1606 where => {'+acqpo' => {id => $po_id}}
1609 $mgr->total(scalar(@$li_ids) + $lid_total);
1611 create_lineitem_list_assets($mgr, $li_ids, $args->{vandelay})
1612 or return $e->die_event;
1615 update_purchase_order($mgr, $po) or return $e->die_event;
1618 return $mgr->respond_complete;
1623 __PACKAGE__->register_method(
1624 method => 'create_purchase_order_api',
1625 api_name => 'open-ils.acq.purchase_order.create',
1627 desc => 'Creates a new purchase order',
1629 {desc => 'Authentication token', type => 'string'},
1630 {desc => 'purchase_order to create', type => 'object'}
1632 return => {desc => 'The purchase order id, Event on failure'}
1634 max_chunk_count => 1
1637 sub create_purchase_order_api {
1638 my($self, $conn, $auth, $po, $args) = @_;
1641 my $e = new_editor(xact=>1, authtoken=>$auth);
1642 return $e->die_event unless $e->checkauth;
1643 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
1644 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1647 my %pargs = (ordering_agency => $e->requestor->ws_ou); # default
1648 $pargs{provider} = $po->provider if $po->provider;
1649 $pargs{ordering_agency} = $po->ordering_agency if $po->ordering_agency;
1650 $pargs{prepayment_required} = $po->prepayment_required if $po->prepayment_required;
1651 my $vandelay = $args->{vandelay};
1653 $po = create_purchase_order($mgr, %pargs) or return $e->die_event;
1655 my $li_ids = $$args{lineitems};
1659 for my $li_id (@$li_ids) {
1661 my $li = $e->retrieve_acq_lineitem([
1663 {flesh => 1, flesh_fields => {jub => ['attributes']}}
1664 ]) or return $e->die_event;
1666 $li->provider($po->provider);
1667 $li->purchase_order($po->id);
1668 $li->state('pending-order');
1669 update_lineitem($mgr, $li) or return $e->die_event;
1674 # commit before starting the asset creation
1677 if($li_ids and $vandelay) {
1678 create_lineitem_list_assets($mgr, $li_ids, $vandelay) or return $e->die_event;
1681 return $mgr->respond_complete;
1686 __PACKAGE__->register_method(
1687 method => 'update_lineitem_fund_batch',
1688 api_name => 'open-ils.acq.lineitem.fund.update.batch',
1691 desc => q/Given a set of lineitem IDS, updates the fund for all attached lineitem details/
1695 sub update_lineitem_fund_batch {
1696 my($self, $conn, $auth, $li_ids, $fund_id) = @_;
1697 my $e = new_editor(xact=>1, authtoken=>$auth);
1698 return $e->die_event unless $e->checkauth;
1699 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1700 for my $li_id (@$li_ids) {
1701 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
1702 return $evt if $evt;
1703 my $li_details = $e->search_acq_lineitem_detail({lineitem => $li_id});
1704 $_->fund($fund_id) and $_->ischanged(1) for @$li_details;
1705 $evt = lineitem_detail_CUD_batch($mgr, $li_details);
1706 return $evt if $evt;
1711 return $mgr->respond_complete;
1716 __PACKAGE__->register_method(
1717 method => 'lineitem_detail_CUD_batch_api',
1718 api_name => 'open-ils.acq.lineitem_detail.cud.batch',
1721 desc => q/Creates a new purchase order line item detail. / .
1722 q/Additionally creates the associated fund_debit/,
1724 {desc => 'Authentication token', type => 'string'},
1725 {desc => 'List of lineitem_details to create', type => 'array'},
1726 {desc => 'Create Debits. Used for creating post-po-asset-creation debits', type => 'bool'},
1728 return => {desc => 'Streaming response of current position in the array'}
1732 __PACKAGE__->register_method(
1733 method => 'lineitem_detail_CUD_batch_api',
1734 api_name => 'open-ils.acq.lineitem_detail.cud.batch.dry_run',
1738 Dry run version of open-ils.acq.lineitem_detail.cud.batch.
1739 In dry_run mode, updated fund_debit's the exceed the warning
1740 percent return an event.
1746 sub lineitem_detail_CUD_batch_api {
1747 my($self, $conn, $auth, $li_details, $create_debits) = @_;
1748 my $e = new_editor(xact=>1, authtoken=>$auth);
1749 return $e->die_event unless $e->checkauth;
1750 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1751 my $dry_run = ($self->api_name =~ /dry_run/o);
1752 my $evt = lineitem_detail_CUD_batch($mgr, $li_details, $create_debits, $dry_run);
1753 return $evt if $evt;
1755 return $mgr->respond_complete;
1759 sub lineitem_detail_CUD_batch {
1760 my($mgr, $li_details, $create_debits, $dry_run) = @_;
1762 $mgr->total(scalar(@$li_details));
1763 my $e = $mgr->editor;
1767 my $fund_cache = {};
1770 for my $lid (@$li_details) {
1772 unless($li = $li_cache{$lid->lineitem}) {
1773 ($li, $evt) = fetch_and_check_li($e, $lid->lineitem, 'write');
1774 return $evt if $evt;
1778 $lid = create_lineitem_detail($mgr, %{$lid->to_bare_hash}) or return $e->die_event;
1779 if($create_debits) {
1780 $li->provider($e->retrieve_acq_provider($li->provider)) or return $e->die_event;
1781 $lid->fund($e->retrieve_acq_fund($lid->fund)) or return $e->die_event;
1782 create_lineitem_detail_debit($mgr, $li, $lid, 0, 1) or return $e->die_event;
1785 } elsif($lid->ischanged) {
1786 return $evt if $evt = handle_changed_lid($e, $lid, $dry_run, $fund_cache);
1788 } elsif($lid->isdeleted) {
1789 delete_lineitem_detail($mgr, $lid) or return $e->die_event;
1792 $mgr->respond(li => $li);
1793 $li_cache{$lid->lineitem} = $li;
1799 sub handle_changed_lid {
1800 my($e, $lid, $dry_run, $fund_cache) = @_;
1802 my $orig_lid = $e->retrieve_acq_lineitem_detail($lid->id) or return $e->die_event;
1804 # updating the fund, so update the debit
1805 if($orig_lid->fund_debit and $orig_lid->fund != $lid->fund) {
1807 my $debit = $e->retrieve_acq_fund_debit($orig_lid->fund_debit);
1808 my $new_fund = $$fund_cache{$lid->fund} =
1809 $$fund_cache{$lid->fund} || $e->retrieve_acq_fund($lid->fund);
1811 # check the thresholds
1812 return $e->die_event if
1813 fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "stop");
1814 return $e->die_event if $dry_run and
1815 fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "warning");
1817 $debit->fund($new_fund->id);
1818 $e->update_acq_fund_debit($debit) or return $e->die_event;
1821 $e->update_acq_lineitem_detail($lid) or return $e->die_event;
1826 __PACKAGE__->register_method(
1827 method => 'receive_po_api',
1828 api_name => 'open-ils.acq.purchase_order.receive'
1831 sub receive_po_api {
1832 my($self, $conn, $auth, $po_id) = @_;
1833 my $e = new_editor(xact => 1, authtoken => $auth);
1834 return $e->die_event unless $e->checkauth;
1835 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1837 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1838 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1840 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1842 for my $li_id (@$li_ids) {
1843 receive_lineitem($mgr, $li_id) or return $e->die_event;
1847 $po->state('received');
1848 update_purchase_order($mgr, $po) or return $e->die_event;
1851 return $mgr->respond_complete;
1855 # At the moment there's a lack of parallelism between the receive and unreceive
1856 # API methods for POs and the API methods for LIs and LIDs. The methods for
1857 # POs stream back objects as they act, whereas the methods for LIs and LIDs
1858 # atomically return an object that describes only what changed (in LIs and LIDs
1859 # themselves or in the objects to which to LIs and LIDs belong).
1861 # The methods for LIs and LIDs work the way they do to faciliate the UI's
1862 # maintaining correct information about the state of these things when a user
1863 # wants to receive or unreceive these objects without refreshing their whole
1864 # display. The UI feature for receiving and un-receiving a whole PO just
1865 # refreshes the whole display, so this absence of parallelism in the UI is also
1866 # relected in this module.
1868 # This could be neatened in the future by making POs receive and unreceive in
1869 # the same way the LIs and LIDs do.
1871 __PACKAGE__->register_method(
1872 method => 'receive_lineitem_detail_api',
1873 api_name => 'open-ils.acq.lineitem_detail.receive',
1875 desc => 'Mark a lineitem_detail as received',
1877 {desc => 'Authentication token', type => 'string'},
1878 {desc => 'lineitem detail ID', type => 'number'}
1881 "on success, object describing changes to LID and possibly " .
1882 "to LI and PO; on error, Event"
1887 sub receive_lineitem_detail_api {
1888 my($self, $conn, $auth, $lid_id) = @_;
1890 my $e = new_editor(xact=>1, authtoken=>$auth);
1891 return $e->die_event unless $e->checkauth;
1892 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1895 "flesh" => 2, "flesh_fields" => {
1896 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
1900 my $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1902 return $e->die_event unless $e->allowed(
1903 'RECEIVE_PURCHASE_ORDER', $lid->lineitem->purchase_order->ordering_agency);
1906 my $recvd = receive_lineitem_detail($mgr, $lid_id) or return $e->die_event;
1908 # .. and re-retrieve
1909 $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1911 # Now build result data structure.
1912 my $result = {"lid" => {$lid->id => {"recv_time" => $lid->recv_time}}};
1915 if ($recvd->class_name =~ /::purchase_order/) {
1916 $result->{"po"} = describe_affected_po($e, $recvd);
1918 $lid->lineitem->id => {"state" => $lid->lineitem->state}
1920 } elsif ($recvd->class_name =~ /::lineitem/) {
1921 $result->{"li"} = {$recvd->id => {"state" => $recvd->state}};
1925 describe_affected_po($e, $lid->lineitem->purchase_order);
1931 __PACKAGE__->register_method(
1932 method => 'receive_lineitem_api',
1933 api_name => 'open-ils.acq.lineitem.receive',
1935 desc => 'Mark a lineitem as received',
1937 {desc => 'Authentication token', type => 'string'},
1938 {desc => 'lineitem ID', type => 'number'}
1941 "on success, object describing changes to LI and possibly PO; " .
1947 sub receive_lineitem_api {
1948 my($self, $conn, $auth, $li_id) = @_;
1950 my $e = new_editor(xact=>1, authtoken=>$auth);
1951 return $e->die_event unless $e->checkauth;
1952 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1954 my $li = $e->retrieve_acq_lineitem([
1958 jub => ['purchase_order']
1961 ]) or return $e->die_event;
1963 return $e->die_event unless $e->allowed(
1964 'RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);
1966 my $res = receive_lineitem($mgr, $li_id) or return $e->die_event;
1968 $conn->respond_complete($res);
1969 $mgr->run_post_response_hooks
1973 __PACKAGE__->register_method(
1974 method => 'rollback_receive_po_api',
1975 api_name => 'open-ils.acq.purchase_order.receive.rollback'
1978 sub rollback_receive_po_api {
1979 my($self, $conn, $auth, $po_id) = @_;
1980 my $e = new_editor(xact => 1, authtoken => $auth);
1981 return $e->die_event unless $e->checkauth;
1982 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1984 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1985 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1987 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1989 for my $li_id (@$li_ids) {
1990 rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
1994 $po->state('on-order');
1995 update_purchase_order($mgr, $po) or return $e->die_event;
1998 return $mgr->respond_complete;
2002 __PACKAGE__->register_method(
2003 method => 'rollback_receive_lineitem_detail_api',
2004 api_name => 'open-ils.acq.lineitem_detail.receive.rollback',
2006 desc => 'Mark a lineitem_detail as Un-received',
2008 {desc => 'Authentication token', type => 'string'},
2009 {desc => 'lineitem detail ID', type => 'number'}
2012 "on success, object describing changes to LID and possibly " .
2013 "to LI and PO; on error, Event"
2018 sub rollback_receive_lineitem_detail_api {
2019 my($self, $conn, $auth, $lid_id) = @_;
2021 my $e = new_editor(xact=>1, authtoken=>$auth);
2022 return $e->die_event unless $e->checkauth;
2023 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2025 my $lid = $e->retrieve_acq_lineitem_detail([
2029 acqlid => ['lineitem'],
2030 jub => ['purchase_order']
2034 my $li = $lid->lineitem;
2035 my $po = $li->purchase_order;
2037 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2041 my $recvd = rollback_receive_lineitem_detail($mgr, $lid_id)
2042 or return $e->die_event;
2045 $result->{"lid"} = {$recvd->id => {"recv_time" => $recvd->recv_time}};
2047 $result->{"lid"} = {$lid->id => {"recv_time" => $lid->recv_time}};
2050 if ($li->state eq "received") {
2051 $li->state("on-order");
2052 $li = update_lineitem($mgr, $li) or return $e->die_event;
2053 $result->{"li"} = {$li->id => {"state" => $li->state}};
2056 if ($po->state eq "received") {
2057 $po->state("on-order");
2058 $po = update_purchase_order($mgr, $po) or return $e->die_event;
2060 $result->{"po"} = describe_affected_po($e, $po);
2062 $e->commit and return $result or return $e->die_event;
2065 __PACKAGE__->register_method(
2066 method => 'rollback_receive_lineitem_api',
2067 api_name => 'open-ils.acq.lineitem.receive.rollback',
2069 desc => 'Mark a lineitem as Un-received',
2071 {desc => 'Authentication token', type => 'string'},
2072 {desc => 'lineitem ID', type => 'number'}
2075 "on success, object describing changes to LI and possibly PO; " .
2081 sub rollback_receive_lineitem_api {
2082 my($self, $conn, $auth, $li_id) = @_;
2084 my $e = new_editor(xact=>1, authtoken=>$auth);
2085 return $e->die_event unless $e->checkauth;
2086 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2088 my $li = $e->retrieve_acq_lineitem([
2090 "flesh" => 1, "flesh_fields" => {"jub" => ["purchase_order"]}
2093 my $po = $li->purchase_order;
2095 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2097 $li = rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
2099 my $result = {"li" => {$li->id => {"state" => $li->state}}};
2100 if ($po->state eq "received") {
2101 $po->state("on-order");
2102 $po = update_purchase_order($mgr, $po) or return $e->die_event;
2104 $result->{"po"} = describe_affected_po($e, $po);
2106 $e->commit and return $result or return $e->die_event;
2110 __PACKAGE__->register_method(
2111 method => 'set_lineitem_price_api',
2112 api_name => 'open-ils.acq.lineitem.price.set',
2114 desc => 'Set lineitem price. If debits already exist, update them as well',
2116 {desc => 'Authentication token', type => 'string'},
2117 {desc => 'lineitem ID', type => 'number'}
2119 return => {desc => 'status blob, Event on error'}
2123 sub set_lineitem_price_api {
2124 my($self, $conn, $auth, $li_id, $price) = @_;
2126 my $e = new_editor(xact=>1, authtoken=>$auth);
2127 return $e->die_event unless $e->checkauth;
2128 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2130 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
2131 return $evt if $evt;
2133 $li->estimated_unit_price($price);
2134 update_lineitem($mgr, $li) or return $e->die_event;
2136 my $lid_ids = $e->search_acq_lineitem_detail(
2137 {lineitem => $li_id, fund_debit => {'!=' => undef}},
2141 for my $lid_id (@$lid_ids) {
2143 my $lid = $e->retrieve_acq_lineitem_detail([
2145 flesh => 1, flesh_fields => {acqlid => ['fund', 'fund_debit']}}
2148 $lid->fund_debit->amount($price);
2149 $e->update_acq_fund_debit($lid->fund_debit) or return $e->die_event;
2155 return $mgr->respond_complete;
2159 __PACKAGE__->register_method(
2160 method => 'clone_picklist_api',
2161 api_name => 'open-ils.acq.picklist.clone',
2163 desc => 'Clones a picklist, including lineitem and lineitem details',
2165 {desc => 'Authentication token', type => 'string'},
2166 {desc => 'Picklist ID', type => 'number'},
2167 {desc => 'New Picklist Name', type => 'string'}
2169 return => {desc => 'status blob, Event on error'}
2173 sub clone_picklist_api {
2174 my($self, $conn, $auth, $pl_id, $name) = @_;
2176 my $e = new_editor(xact=>1, authtoken=>$auth);
2177 return $e->die_event unless $e->checkauth;
2178 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2180 my $old_pl = $e->retrieve_acq_picklist($pl_id);
2181 my $new_pl = create_picklist($mgr, %{$old_pl->to_bare_hash}, name => $name) or return $e->die_event;
2183 my $li_ids = $e->search_acq_lineitem({picklist => $pl_id}, {idlist => 1});
2185 for my $li_id (@$li_ids) {
2187 # copy the lineitems
2188 my $li = $e->retrieve_acq_lineitem($li_id);
2189 my $new_li = create_lineitem($mgr, %{$li->to_bare_hash}, picklist => $new_pl->id) or return $e->die_event;
2191 my $lid_ids = $e->search_acq_lineitem_detail({lineitem => $li_id}, {idlist => 1});
2192 for my $lid_id (@$lid_ids) {
2194 # copy the lineitem details
2195 my $lid = $e->retrieve_acq_lineitem_detail($lid_id);
2196 create_lineitem_detail($mgr, %{$lid->to_bare_hash}, lineitem => $new_li->id) or return $e->die_event;
2203 return $mgr->respond_complete;
2207 __PACKAGE__->register_method(
2208 method => 'merge_picklist_api',
2209 api_name => 'open-ils.acq.picklist.merge',
2211 desc => 'Merges 2 or more picklists into a single list',
2213 {desc => 'Authentication token', type => 'string'},
2214 {desc => 'Lead Picklist ID', type => 'number'},
2215 {desc => 'List of subordinate picklist IDs', type => 'array'}
2217 return => {desc => 'status blob, Event on error'}
2221 sub merge_picklist_api {
2222 my($self, $conn, $auth, $lead_pl, $pl_list) = @_;
2224 my $e = new_editor(xact=>1, authtoken=>$auth);
2225 return $e->die_event unless $e->checkauth;
2226 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2228 # XXX perms on each picklist modified
2230 $lead_pl = $e->retrieve_acq_picklist($lead_pl) or return $e->die_event;
2231 # point all of the lineitems at the lead picklist
2232 my $li_ids = $e->search_acq_lineitem({picklist => $pl_list}, {idlist => 1});
2234 for my $li_id (@$li_ids) {
2235 my $li = $e->retrieve_acq_lineitem($li_id);
2236 $li->picklist($lead_pl);
2237 update_lineitem($mgr, $li) or return $e->die_event;
2241 # now delete the subordinate lists
2242 for my $pl_id (@$pl_list) {
2243 my $pl = $e->retrieve_acq_picklist($pl_id);
2244 $e->delete_acq_picklist($pl) or return $e->die_event;
2247 update_picklist($mgr, $lead_pl) or return $e->die_event;
2250 return $mgr->respond_complete;
2254 __PACKAGE__->register_method(
2255 method => 'delete_picklist_api',
2256 api_name => 'open-ils.acq.picklist.delete',
2258 desc => q/Deletes a picklist. It also deletes any lineitems in the "new" state. / .
2259 q/Other attached lineitems are detached/,
2261 {desc => 'Authentication token', type => 'string'},
2262 {desc => 'Picklist ID to delete', type => 'number'}
2264 return => {desc => '1 on success, Event on error'}
2268 sub delete_picklist_api {
2269 my($self, $conn, $auth, $picklist_id) = @_;
2270 my $e = new_editor(xact=>1, authtoken=>$auth);
2271 return $e->die_event unless $e->checkauth;
2272 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2273 my $pl = $e->retrieve_acq_picklist($picklist_id) or return $e->die_event;
2274 delete_picklist($mgr, $pl) or return $e->die_event;
2276 return $mgr->respond_complete;
2281 __PACKAGE__->register_method(
2282 method => 'activate_purchase_order',
2283 api_name => 'open-ils.acq.purchase_order.activate.dry_run'
2286 __PACKAGE__->register_method(
2287 method => 'activate_purchase_order',
2288 api_name => 'open-ils.acq.purchase_order.activate',
2290 desc => q/Activates a purchase order. This updates the status of the PO / .
2291 q/and Lineitems to 'on-order'. Activated PO's are ready for EDI delivery if appropriate./,
2293 {desc => 'Authentication token', type => 'string'},
2294 {desc => 'Purchase ID', type => 'number'}
2296 return => {desc => '1 on success, Event on error'}
2300 sub activate_purchase_order {
2301 my($self, $conn, $auth, $po_id, $vandelay) = @_;
2303 my $dry_run = ($self->api_name =~ /\.dry_run/) ? 1 : 0;
2304 my $e = new_editor(authtoken=>$auth);
2305 return $e->die_event unless $e->checkauth;
2306 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2307 my $die_event = activate_purchase_order_impl($mgr, $po_id, $vandelay, $dry_run);
2308 return $e->die_event if $die_event;
2309 $conn->respond_complete(1);
2310 $mgr->run_post_response_hooks unless $dry_run;
2314 # xacts managed within
2315 sub activate_purchase_order_impl {
2316 my ($mgr, $po_id, $vandelay, $dry_run) = @_;
2318 # read-only until lineitem asset creation
2319 my $e = $mgr->editor;
2322 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2323 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
2324 my $provider = $e->retrieve_acq_provider($po->provider);
2326 # find lineitems and create assets for all
2329 purchase_order => $po_id,
2330 state => [qw/pending-order new order-ready/]
2333 my $li_ids = $e->search_acq_lineitem($query, {idlist => 1});
2335 my $vl_resp; # imported li's and the queue the managing queue
2337 $e->rollback; # read-only thus far
2338 $vl_resp = create_lineitem_list_assets($mgr, $li_ids, $vandelay)
2339 or return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED');
2343 # create fund debits for lineitems
2345 for my $li_id (@$li_ids) {
2346 my $li = $e->retrieve_acq_lineitem($li_id);
2348 if (!$li->eg_bib_id and !$dry_run) {
2349 # we encountered a lineitem that was not successfully imported.
2350 # we cannot continue. rollback and report.
2352 return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED', {queue => $vl_resp->{queue}});
2355 $li->state('on-order');
2356 $li->claim_policy($provider->default_claim_policy)
2357 if $provider->default_claim_policy and !$li->claim_policy;
2358 create_lineitem_debits($mgr, $li, $dry_run) or return $e->die_event;
2359 update_lineitem($mgr, $li) or return $e->die_event;
2360 $mgr->post_process( sub { create_lineitem_status_events($mgr, $li->id, 'aur.ordered'); });
2364 # create po-item debits
2366 for my $po_item (@{$e->search_acq_po_item({purchase_order => $po_id})}) {
2368 my $debit = create_fund_debit(
2371 debit_type => 'direct_charge', # to match invoicing
2372 origin_amount => $po_item->estimated_cost,
2373 origin_currency_type => $e->retrieve_acq_fund($po_item->fund)->currency_type,
2374 amount => $po_item->estimated_cost,
2375 fund => $po_item->fund
2376 ) or return $e->die_event;
2377 $po_item->fund_debit($debit->id);
2378 $e->update_acq_po_item($po_item) or return $e->die_event;
2382 # mark PO as ordered
2384 $po->state('on-order');
2385 $po->order_date('now');
2386 update_purchase_order($mgr, $po) or return $e->die_event;
2389 $dry_run and $e->rollback or $e->commit;
2391 # tell the world we activated a PO
2392 $U->create_events_for_hook('acqpo.activated', $po, $po->ordering_agency) unless $dry_run;
2398 __PACKAGE__->register_method(
2399 method => 'split_purchase_order_by_lineitems',
2400 api_name => 'open-ils.acq.purchase_order.split_by_lineitems',
2402 desc => q/Splits a PO into many POs, 1 per lineitem. Only works for / .
2403 q/POs a) with more than one lineitems, and b) in the "pending" state./,
2405 {desc => 'Authentication token', type => 'string'},
2406 {desc => 'Purchase order ID', type => 'number'}
2408 return => {desc => 'list of new PO IDs on success, Event on error'}
2412 sub split_purchase_order_by_lineitems {
2413 my ($self, $conn, $auth, $po_id) = @_;
2415 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2416 return $e->die_event unless $e->checkauth;
2418 my $po = $e->retrieve_acq_purchase_order([
2421 "flesh_fields" => {"acqpo" => [qw/lineitems notes/]}
2423 ]) or return $e->die_event;
2425 return $e->die_event
2426 unless $e->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2428 unless ($po->state eq "pending") {
2430 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_LATE");
2433 unless (@{$po->lineitems} > 1) {
2435 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_SHORT");
2438 # To split an existing PO into many, it seems unwise to just delete the
2439 # original PO, so we'll instead detach all of the original POs' lineitems
2440 # but the first, then create new POs for each of the remaining LIs, and
2441 # then attach the LIs to their new POs.
2443 my @po_ids = ($po->id);
2444 my @moving_li = @{$po->lineitems};
2445 shift @moving_li; # discard first LI
2447 foreach my $li (@moving_li) {
2448 my $new_po = $po->clone;
2450 $new_po->clear_name;
2451 $new_po->creator($e->requestor->id);
2452 $new_po->editor($e->requestor->id);
2453 $new_po->owner($e->requestor->id);
2454 $new_po->edit_time("now");
2455 $new_po->create_time("now");
2457 $new_po = $e->create_acq_purchase_order($new_po);
2459 # Clone any notes attached to the old PO and attach to the new one.
2460 foreach my $note (@{$po->notes}) {
2461 my $new_note = $note->clone;
2462 $new_note->clear_id;
2463 $new_note->edit_time("now");
2464 $new_note->purchase_order($new_po->id);
2465 $e->create_acq_po_note($new_note);
2468 $li->edit_time("now");
2469 $li->purchase_order($new_po->id);
2470 $e->update_acq_lineitem($li);
2472 push @po_ids, $new_po->id;
2475 $po->edit_time("now");
2476 $e->update_acq_purchase_order($po);
2478 return \@po_ids if $e->commit;
2479 return $e->die_event;
2483 sub not_cancelable {
2485 (ref $o eq "HASH" and $o->{"textcode"} eq "ACQ_NOT_CANCELABLE");
2488 __PACKAGE__->register_method(
2489 method => "cancel_purchase_order_api",
2490 api_name => "open-ils.acq.purchase_order.cancel",
2492 desc => q/Cancels an on-order purchase order/,
2494 {desc => "Authentication token", type => "string"},
2495 {desc => "PO ID to cancel", type => "number"},
2496 {desc => "Cancel reason ID", type => "number"}
2498 return => {desc => q/Object describing changed POs, LIs and LIDs
2499 on success; Event on error./}
2503 sub cancel_purchase_order_api {
2504 my ($self, $conn, $auth, $po_id, $cancel_reason) = @_;
2506 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2507 return $e->die_event unless $e->checkauth;
2508 my $mgr = new OpenILS::Application::Acq::BatchManager(
2509 "editor" => $e, "conn" => $conn
2512 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2513 return new OpenILS::Event(
2514 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2517 my $result = cancel_purchase_order($mgr, $po_id, $cancel_reason) or
2518 return $e->die_event;
2519 if (not_cancelable($result)) { # event not from CStoreEditor
2522 } elsif ($result == -1) {
2524 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2527 $e->commit or return $e->die_event;
2529 # XXX create purchase order status events?
2531 if ($mgr->{post_commit}) {
2532 foreach my $func (@{$mgr->{post_commit}}) {
2540 sub cancel_purchase_order {
2541 my ($mgr, $po_id, $cancel_reason) = @_;
2543 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id) or return 0;
2545 # XXX is "cancelled" a typo? It's not correct US spelling, anyway.
2546 # Depending on context, this may not warrant an event.
2547 return -1 if $po->state eq "cancelled";
2549 # But this always does.
2550 return new OpenILS::Event(
2551 "ACQ_NOT_CANCELABLE", "note" => "purchase_order $po_id"
2552 ) unless ($po->state eq "on-order" or $po->state eq "pending");
2555 $mgr->editor->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2557 $po->state("cancelled");
2558 $po->cancel_reason($cancel_reason->id);
2560 my $li_ids = $mgr->editor->search_acq_lineitem(
2561 {"purchase_order" => $po_id}, {"idlist" => 1}
2564 my $result = {"li" => {}, "lid" => {}};
2565 foreach my $li_id (@$li_ids) {
2566 my $li_result = cancel_lineitem($mgr, $li_id, $cancel_reason)
2569 next if $li_result == -1; # already canceled:skip.
2570 return $li_result if not_cancelable($li_result); # not cancelable:stop.
2572 # Merge in each LI result (there's only going to be
2573 # one per call to cancel_lineitem).
2574 my ($k, $v) = each %{$li_result->{"li"}};
2575 $result->{"li"}->{$k} = $v;
2577 # Merge in each LID result (there may be many per call to
2579 while (($k, $v) = each %{$li_result->{"lid"}}) {
2580 $result->{"lid"}->{$k} = $v;
2584 # TODO who/what/where/how do we indicate this change for electronic orders?
2585 # TODO return changes to encumbered/spent
2586 # TODO maybe cascade up from smaller object to container object if last
2587 # smaller object in the container has been canceled?
2589 update_purchase_order($mgr, $po) or return 0;
2591 $po_id => {"state" => $po->state, "cancel_reason" => $cancel_reason}
2597 __PACKAGE__->register_method(
2598 method => "cancel_lineitem_api",
2599 api_name => "open-ils.acq.lineitem.cancel",
2601 desc => q/Cancels an on-order lineitem/,
2603 {desc => "Authentication token", type => "string"},
2604 {desc => "Lineitem ID to cancel", type => "number"},
2605 {desc => "Cancel reason ID", type => "number"}
2607 return => {desc => q/Object describing changed LIs and LIDs on success;
2612 __PACKAGE__->register_method(
2613 method => "cancel_lineitem_api",
2614 api_name => "open-ils.acq.lineitem.cancel.batch",
2616 desc => q/Batched version of open-ils.acq.lineitem.cancel/,
2617 return => {desc => q/Object describing changed LIs and LIDs on success;
2622 sub cancel_lineitem_api {
2623 my ($self, $conn, $auth, $li_id, $cancel_reason) = @_;
2625 my $batched = $self->api_name =~ /\.batch/;
2627 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2628 return $e->die_event unless $e->checkauth;
2629 my $mgr = new OpenILS::Application::Acq::BatchManager(
2630 "editor" => $e, "conn" => $conn
2633 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2634 return new OpenILS::Event(
2635 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2638 my ($result, $maybe_event);
2641 $result = {"li" => {}, "lid" => {}};
2642 foreach my $one_li_id (@$li_id) {
2643 my $one = cancel_lineitem($mgr, $one_li_id, $cancel_reason) or
2644 return $e->die_event;
2645 if (not_cancelable($one)) {
2646 $maybe_event = $one;
2647 } elsif ($result == -1) {
2648 $maybe_event = new OpenILS::Event("ACQ_ALREADY_CANCELED");
2652 while (($k, $v) = each %{$one->{"li"}}) {
2653 $result->{"li"}->{$k} = $v;
2656 if ($one->{"lid"}) {
2657 while (($k, $v) = each %{$one->{"lid"}}) {
2658 $result->{"lid"}->{$k} = $v;
2664 $result = cancel_lineitem($mgr, $li_id, $cancel_reason) or
2665 return $e->die_event;
2667 if (not_cancelable($result)) {
2670 } elsif ($result == -1) {
2672 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2676 if ($batched and not scalar keys %{$result->{"li"}}) {
2678 return $maybe_event;
2680 $e->commit or return $e->die_event;
2681 # create_lineitem_status_events should handle array li_id ok
2682 create_lineitem_status_events($mgr, $li_id, "aur.cancelled");
2684 if ($mgr->{post_commit}) {
2685 foreach my $func (@{$mgr->{post_commit}}) {
2694 sub cancel_lineitem {
2695 my ($mgr, $li_id, $cancel_reason) = @_;
2696 my $li = $mgr->editor->retrieve_acq_lineitem([
2697 $li_id, {flesh => 1, flesh_fields => {jub => ['purchase_order']}}
2700 return 0 unless $mgr->editor->allowed(
2701 "CREATE_PURCHASE_ORDER", $li->purchase_order->ordering_agency
2704 # Depending on context, this may not warrant an event.
2705 return -1 if $li->state eq "cancelled";
2707 # But this always does.
2708 return new OpenILS::Event(
2709 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id"
2711 (! $li->purchase_order) or (
2712 $li->purchase_order and (
2713 $li->state eq "on-order" or $li->state eq "pending-order"
2718 $li->state("cancelled");
2719 $li->cancel_reason($cancel_reason->id);
2721 my $lids = $mgr->editor->search_acq_lineitem_detail([{
2722 "lineitem" => $li_id
2725 flesh_fields => { acqlid => ['eg_copy_id'] }
2728 my $result = {"lid" => {}};
2730 foreach my $lid (@$lids) {
2731 my $lid_result = cancel_lineitem_detail($mgr, $lid->id, $cancel_reason)
2734 # gathering any real copies for deletion
2735 if ($lid->eg_copy_id) {
2736 $lid->eg_copy_id->isdeleted('t');
2737 push @$copies, $lid->eg_copy_id;
2740 next if $lid_result == -1; # already canceled: just skip it.
2741 return $lid_result if not_cancelable($lid_result); # not cxlable: stop.
2743 # Merge in each LID result (there's only going to be one per call to
2744 # cancel_lineitem_detail).
2745 my ($k, $v) = each %{$lid_result->{"lid"}};
2746 $result->{"lid"}->{$k} = $v;
2749 # Attempt to delete the gathered copies (this will also handle volume deletion and bib deletion)
2750 # Delete empty bibs according org unit setting
2751 my $force_delete_empty_bib = $U->ou_ancestor_setting_value(
2752 $mgr->editor->requestor->ws_ou, 'cat.bib.delete_on_no_copy_via_acq_lineitem_cancel', $mgr->editor);
2753 if (scalar(@$copies)>0) {
2755 my $delete_stats = undef;
2756 my $retarget_holds = [];
2757 my $cat_evt = OpenILS::Application::Cat::AssetCommon->update_fleshed_copies(
2758 $mgr->editor, $override, undef, $copies, $delete_stats, $retarget_holds,$force_delete_empty_bib);
2761 $logger->info("fleshed copy update failed with event: ".OpenSRF::Utils::JSON->perl2JSON($cat_evt));
2762 return new OpenILS::Event(
2763 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id", "payload" => $cat_evt
2767 # We can't do the following and stay within the same transaction, but that's okay, the hold targeter will pick these up later.
2768 #my $ses = OpenSRF::AppSession->create('open-ils.circ');
2769 #$ses->request('open-ils.circ.hold.reset.batch', $auth, $retarget_holds);
2772 # if we have a bib, check to see whether it has been deleted. if so, cancel any active holds targeting that bib
2773 if ($li->eg_bib_id) {
2774 my $bib = $mgr->editor->retrieve_biblio_record_entry($li->eg_bib_id) or return new OpenILS::Event(
2775 "ACQ_NOT_CANCELABLE", "note" => "Could not retrieve bib " . $li->eg_bib_id . " for lineitem $li_id"
2777 if ($U->is_true($bib->deleted)) {
2778 my $holds = $mgr->editor->search_action_hold_request(
2779 { cancel_time => undef,
2780 fulfillment_time => undef,
2781 target => $li->eg_bib_id
2785 my %cached_usr_home_ou = ();
2787 for my $hold (@$holds) {
2789 $logger->info("Cancelling hold ".$hold->id.
2790 " due to acq lineitem cancellation.");
2792 $hold->cancel_time('now');
2793 $hold->cancel_cause(5); # 'Staff forced'--we may want a new hold cancel cause reason for this
2794 $hold->cancel_note('Corresponding Acquistion Lineitem/Purchase Order was cancelled.');
2795 unless($mgr->editor->update_action_hold_request($hold)) {
2796 my $evt = $mgr->editor->event;
2797 $logger->error("Error updating hold ". $evt->textcode .":". $evt->desc .":". $evt->stacktrace);
2798 return new OpenILS::Event(
2799 "ACQ_NOT_CANCELABLE", "note" => "Could not cancel hold " . $hold->id . " for lineitem $li_id", "payload" => $evt
2802 if (! defined $mgr->{post_commit}) { # we need a mechanism for creating trigger events, but only if the transaction gets committed
2803 $mgr->{post_commit} = [];
2805 push @{ $mgr->{post_commit} }, sub {
2806 my $home_ou = $cached_usr_home_ou{$hold->usr};
2808 my $user = $mgr->editor->retrieve_actor_user($hold->usr); # FIXME: how do we want to handle failures here?
2809 $home_ou = $user->home_ou;
2810 $cached_usr_home_ou{$hold->usr} = $home_ou;
2812 $U->create_events_for_hook('hold_request.cancel.cancelled_order', $hold, $home_ou);
2818 update_lineitem($mgr, $li) or return 0;
2821 "state" => $li->state,
2822 "cancel_reason" => $cancel_reason
2829 __PACKAGE__->register_method(
2830 method => "cancel_lineitem_detail_api",
2831 api_name => "open-ils.acq.lineitem_detail.cancel",
2833 desc => q/Cancels an on-order lineitem detail/,
2835 {desc => "Authentication token", type => "string"},
2836 {desc => "Lineitem detail ID to cancel", type => "number"},
2837 {desc => "Cancel reason ID", type => "number"}
2839 return => {desc => q/Object describing changed LIDs on success;
2844 sub cancel_lineitem_detail_api {
2845 my ($self, $conn, $auth, $lid_id, $cancel_reason) = @_;
2847 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2848 return $e->die_event unless $e->checkauth;
2849 my $mgr = new OpenILS::Application::Acq::BatchManager(
2850 "editor" => $e, "conn" => $conn
2853 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2854 return new OpenILS::Event(
2855 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2858 my $result = cancel_lineitem_detail($mgr, $lid_id, $cancel_reason) or
2859 return $e->die_event;
2861 if (not_cancelable($result)) {
2864 } elsif ($result == -1) {
2866 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2869 $e->commit or return $e->die_event;
2871 # XXX create lineitem detail status events?
2875 sub cancel_lineitem_detail {
2876 my ($mgr, $lid_id, $cancel_reason) = @_;
2877 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
2881 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
2886 # Depending on context, this may not warrant an event.
2887 return -1 if $lid->cancel_reason;
2889 # But this always does.
2890 return new OpenILS::Event(
2891 "ACQ_NOT_CANCELABLE", "note" => "lineitem_detail $lid_id"
2893 (! $lid->lineitem->purchase_order) or
2895 (not $lid->recv_time) and
2897 $lid->lineitem->purchase_order and (
2898 $lid->lineitem->state eq "on-order" or
2899 $lid->lineitem->state eq "pending-order"
2904 return 0 unless $mgr->editor->allowed(
2905 "CREATE_PURCHASE_ORDER",
2906 $lid->lineitem->purchase_order->ordering_agency
2907 ) or (! $lid->lineitem->purchase_order);
2909 $lid->cancel_reason($cancel_reason->id);
2911 unless($U->is_true($cancel_reason->keep_debits)) {
2912 my $debit_id = $lid->fund_debit;
2913 $lid->clear_fund_debit;
2916 # item is cancelled. Remove the fund debit.
2917 my $debit = $mgr->editor->retrieve_acq_fund_debit($debit_id);
2918 if (!$U->is_true($debit->encumbrance)) {
2919 $mgr->editor->rollback;
2920 return OpenILS::Event->new('ACQ_NOT_CANCELABLE',
2921 note => "Debit is marked as paid: $debit_id");
2923 $mgr->editor->delete_acq_fund_debit($debit) or return $mgr->editor->die_event;
2927 # XXX LIDs don't have either an editor or a edit_time field. Should we
2928 # update these on the LI when we alter an LID?
2929 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
2931 return {"lid" => {$lid_id => {"cancel_reason" => $cancel_reason}}};
2935 __PACKAGE__->register_method(
2936 method => 'user_requests',
2937 api_name => 'open-ils.acq.user_request.retrieve.by_user_id',
2940 desc => 'Retrieve fleshed user requests and related data for a given user.',
2942 { desc => 'Authentication token', type => 'string' },
2943 { desc => 'User ID of the owner, or array of IDs', },
2944 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
2949 desc => 'Fleshed user requests and related data',
2955 __PACKAGE__->register_method(
2956 method => 'user_requests',
2957 api_name => 'open-ils.acq.user_request.retrieve.by_home_ou',
2960 desc => 'Retrieve fleshed user requests and related data for a given org unit or units.',
2962 { desc => 'Authentication token', type => 'string' },
2963 { desc => 'Org unit ID, or array of IDs', },
2964 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
2969 desc => 'Fleshed user requests and related data',
2976 my($self, $conn, $auth, $search_value, $options) = @_;
2977 my $e = new_editor(authtoken => $auth);
2978 return $e->event unless $e->checkauth;
2979 my $rid = $e->requestor->id;
2983 "select"=>{"aur"=>["id"],"au"=>["home_ou", {column => 'id', alias => 'usr_id'} ]},
2984 "from"=>{ "aur" => { "au" => {}, "jub" => { "type" => "left" } } },
2988 {"id"=>undef}, # this with the left-join pulls in requests without lineitems
2989 {"state"=>["new","on-order","pending-order"]} # FIXME - probably needs softcoding
2993 "order_by"=>[{"class"=>"aur", "field"=>"request_date", "direction"=>"desc"}]
2996 foreach (qw/ order_by limit offset /) {
2997 $query->{$_} = $options->{$_} if defined $options->{$_};
2999 if (defined $options->{'state'}) {
3000 $query->{'where'}->{'+jub'}->{'-or'}->[1]->{'state'} = $options->{'state'};
3003 if ($self->api_name =~ /by_user_id/) {
3004 $query->{'where'}->{'usr'} = $search_value;
3006 $query->{'where'}->{'+au'} = { 'home_ou' => $search_value };
3009 my $pertinent_ids = $e->json_query($query);
3012 for my $id_blob (@$pertinent_ids) {
3013 if ($rid != $id_blob->{usr_id}) {
3014 if (!defined $perm_test{ $id_blob->{home_ou} }) {
3015 $perm_test{ $id_blob->{home_ou} } = $e->allowed( ['user_request.view'], $id_blob->{home_ou} );
3017 if (!$perm_test{ $id_blob->{home_ou} }) {
3021 my $aur_obj = $e->retrieve_acq_user_request([
3023 {flesh => 1, flesh_fields => { "aur" => [ 'lineitem' ] } }
3025 if (! $aur_obj) { next; }
3027 if ($aur_obj->lineitem()) {
3028 $aur_obj->lineitem()->clear_marc();
3030 $conn->respond($aur_obj);
3036 __PACKAGE__->register_method (
3037 method => 'update_user_request',
3038 api_name => 'open-ils.acq.user_request.cancel.batch',
3041 desc => 'If given a cancel reason, will update the request with that reason, otherwise, this will delete the request altogether. The ' .
3042 'intention is for staff interfaces or processes to provide cancel reasons, and for patron interfaces to just delete the requests.' ,
3044 { desc => 'Authentication token', type => 'string' },
3045 { desc => 'ID or array of IDs for the user requests to cancel' },
3046 { desc => 'Cancel Reason ID (optional)', type => 'string' }
3049 desc => 'progress object, event on error',
3053 __PACKAGE__->register_method (
3054 method => 'update_user_request',
3055 api_name => 'open-ils.acq.user_request.set_no_hold.batch',
3058 desc => 'Remove the hold from a user request or set of requests',
3060 { desc => 'Authentication token', type => 'string' },
3061 { desc => 'ID or array of IDs for the user requests to modify' }
3064 desc => 'progress object, event on error',
3069 sub update_user_request {
3070 my($self, $conn, $auth, $aur_ids, $cancel_reason) = @_;
3071 my $e = new_editor(xact => 1, authtoken => $auth);
3072 return $e->die_event unless $e->checkauth;
3073 my $rid = $e->requestor->id;
3077 for my $id (@$aur_ids) {
3079 my $aur_obj = $e->retrieve_acq_user_request([
3082 flesh_fields => { "aur" => ['lineitem', 'usr'] }
3084 ]) or return $e->die_event;
3086 my $context_org = $aur_obj->usr()->home_ou();
3087 $aur_obj->usr( $aur_obj->usr()->id() );
3089 if ($rid != $aur_obj->usr) {
3090 if (!defined $perm_test{ $context_org }) {
3091 $perm_test{ $context_org } = $e->allowed( ['user_request.update'], $context_org );
3093 if (!$perm_test{ $context_org }) {
3098 if($self->api_name =~ /set_no_hold/) {
3099 if ($U->is_true($aur_obj->hold)) {
3101 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3105 if($self->api_name =~ /cancel/) {
3106 if ( $cancel_reason ) {
3107 $aur_obj->cancel_reason( $cancel_reason );
3108 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3109 create_user_request_events( $e, [ $aur_obj ], 'aur.rejected' );
3111 $e->delete_acq_user_request($aur_obj);
3115 $conn->respond({maximum => scalar(@$aur_ids), progress => $x++});
3119 return {complete => 1};
3122 __PACKAGE__->register_method (
3123 method => 'new_user_request',
3124 api_name => 'open-ils.acq.user_request.create',
3126 desc => 'Create a new user request object in the DB',
3128 { desc => 'Authentication token', type => 'string' },
3129 { desc => 'User request data hash. Hash keys match the fields for the "aur" object', type => 'object' }
3132 desc => 'The created user request object, or event on error'
3137 sub new_user_request {
3138 my($self, $conn, $auth, $form_data) = @_;
3139 my $e = new_editor(xact => 1, authtoken => $auth);
3140 return $e->die_event unless $e->checkauth;
3141 my $rid = $e->requestor->id;
3142 my $target_user_fleshed;
3143 if (! defined $$form_data{'usr'}) {
3144 $$form_data{'usr'} = $rid;
3146 if ($$form_data{'usr'} != $rid) {
3147 # See if the requestor can place the request on behalf of a different user.
3148 $target_user_fleshed = $e->retrieve_actor_user($$form_data{'usr'}) or return $e->die_event;
3149 $e->allowed('user_request.create', $target_user_fleshed->home_ou) or return $e->die_event;
3151 $target_user_fleshed = $e->requestor;
3152 $e->allowed('CREATE_PURCHASE_REQUEST') or return $e->die_event;
3154 if (! defined $$form_data{'pickup_lib'}) {
3155 if ($target_user_fleshed->ws_ou) {
3156 $$form_data{'pickup_lib'} = $target_user_fleshed->ws_ou;
3158 $$form_data{'pickup_lib'} = $target_user_fleshed->home_ou;
3161 if (! defined $$form_data{'request_type'}) {
3162 $$form_data{'request_type'} = 1; # Books
3164 my $aur_obj = new Fieldmapper::acq::user_request;
3166 $aur_obj->usr( $$form_data{'usr'} );
3167 $aur_obj->request_date( 'now' );
3168 for my $field ( keys %$form_data ) {
3169 if (defined $$form_data{$field} and $field !~ /^(id|lineitem|eg_bib|request_date|cancel_reason)$/) {
3170 $aur_obj->$field( $$form_data{$field} );
3174 $aur_obj = $e->create_acq_user_request($aur_obj) or return $e->die_event;
3176 $e->commit and create_user_request_events( $e, [ $aur_obj ], 'aur.created' );
3181 sub create_user_request_events {
3182 my($e, $user_reqs, $hook) = @_;
3184 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
3187 my %cached_usr_home_ou = ();
3188 for my $user_req (@$user_reqs) {
3189 my $home_ou = $cached_usr_home_ou{$user_req->usr};
3191 my $user = $e->retrieve_actor_user($user_req->usr) or return $e->die_event;
3192 $home_ou = $user->home_ou;
3193 $cached_usr_home_ou{$user_req->usr} = $home_ou;
3195 my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $home_ou);
3204 __PACKAGE__->register_method(
3205 method => "po_note_CUD_batch",
3206 api_name => "open-ils.acq.po_note.cud.batch",
3209 desc => q/Manage purchase order notes/,
3211 {desc => "Authentication token", type => "string"},
3212 {desc => "List of po_notes to manage", type => "array"},
3214 return => {desc => "Stream of successfully managed objects"}
3218 sub po_note_CUD_batch {
3219 my ($self, $conn, $auth, $notes) = @_;
3221 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3222 return $e->die_event unless $e->checkauth;
3225 my $total = @$notes;
3228 foreach my $note (@$notes) {
3230 $note->editor($e->requestor->id);
3231 $note->edit_time("now");
3234 $note->creator($e->requestor->id);
3235 $note = $e->create_acq_po_note($note) or return $e->die_event;
3236 } elsif ($note->isdeleted) {
3237 $e->delete_acq_po_note($note) or return $e->die_event;
3238 } elsif ($note->ischanged) {
3239 $e->update_acq_po_note($note) or return $e->die_event;
3242 unless ($note->isdeleted) {
3243 $note = $e->retrieve_acq_po_note($note->id) or
3244 return $e->die_event;
3248 {"maximum" => $total, "progress" => ++$count, "note" => $note}
3252 $e->commit and $conn->respond_complete or return $e->die_event;
3256 # retrieves a lineitem, fleshes its PO and PL, checks perms
3257 sub fetch_and_check_li {
3260 my $perm_mode = shift || 'read';
3262 my $li = $e->retrieve_acq_lineitem([
3265 flesh_fields => {jub => ['purchase_order', 'picklist']}
3267 ]) or return $e->die_event;
3269 if(my $po = $li->purchase_order) {
3270 my $perms = ($perm_mode eq 'read') ? 'VIEW_PURCHASE_ORDER' : 'CREATE_PURCHASE_ORDER';
3271 return ($li, $e->die_event) unless $e->allowed($perms, $po->ordering_agency);
3273 } elsif(my $pl = $li->picklist) {
3274 my $perms = ($perm_mode eq 'read') ? 'VIEW_PICKLIST' : 'CREATE_PICKLIST';
3275 return ($li, $e->die_event) unless $e->allowed($perms, $pl->org_unit);
3282 __PACKAGE__->register_method(
3283 method => "clone_distrib_form",
3284 api_name => "open-ils.acq.distribution_formula.clone",
3287 desc => q/Clone a distribution formula/,
3289 {desc => "Authentication token", type => "string"},
3290 {desc => "Original formula ID", type => 'integer'},
3291 {desc => "Name of new formula", type => 'string'},
3293 return => {desc => "ID of newly created formula"}
3297 sub clone_distrib_form {
3298 my($self, $client, $auth, $form_id, $new_name) = @_;
3300 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3301 return $e->die_event unless $e->checkauth;
3303 my $old_form = $e->retrieve_acq_distribution_formula($form_id) or return $e->die_event;
3304 return $e->die_event unless $e->allowed('ADMIN_ACQ_DISTRIB_FORMULA', $old_form->owner);
3306 my $new_form = Fieldmapper::acq::distribution_formula->new;
3308 $new_form->owner($old_form->owner);
3309 $new_form->name($new_name);
3310 $e->create_acq_distribution_formula($new_form) or return $e->die_event;
3312 my $entries = $e->search_acq_distribution_formula_entry({formula => $form_id});
3313 for my $entry (@$entries) {
3314 my $new_entry = Fieldmapper::acq::distribution_formula_entry->new;
3315 $new_entry->$_($entry->$_()) for $entry->real_fields;
3316 $new_entry->formula($new_form->id);
3317 $new_entry->clear_id;
3318 $e->create_acq_distribution_formula_entry($new_entry) or return $e->die_event;
3322 return $new_form->id;
3325 __PACKAGE__->register_method(
3326 method => 'add_li_to_po',
3327 api_name => 'open-ils.acq.purchase_order.add_lineitem',
3329 desc => q/Adds a lineitem to an existing purchase order/,
3331 {desc => 'Authentication token', type => 'string'},
3332 {desc => 'The purchase order id', type => 'number'},
3333 {desc => 'The lineitem ID', type => 'number'},
3335 return => {desc => 'Streams a total versus completed counts object, event on error'}
3340 my($self, $conn, $auth, $po_id, $li_id) = @_;
3342 my $e = new_editor(authtoken => $auth, xact => 1);
3343 return $e->die_event unless $e->checkauth;
3345 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
3347 my $po = $e->retrieve_acq_purchase_order($po_id)
3348 or return $e->die_event;
3350 my $li = $e->retrieve_acq_lineitem($li_id)
3351 or return $e->die_event;
3353 return $e->die_event unless
3354 $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
3356 unless ($po->state =~ /new|pending/) {
3358 return {success => 0, po => $po, error => 'bad-po-state'};
3361 unless ($li->state =~ /new|order-ready|pending-order/) {
3363 return {success => 0, li => $li, error => 'bad-li-state'};
3366 $li->purchase_order($po_id);
3367 $li->state('pending-order');
3368 update_lineitem($mgr, $li) or return $e->die_event;
3371 return {success => 1};