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);
17 purchase_order => undef,
23 $self->{ingest_queue} = [];
25 $self->throttle(5) unless $self->throttle;
26 $self->{post_proc_queue} = [];
27 $self->{last_respond_progress} = 0;
33 $self->{conn} = $val if $val;
38 $self->{throttle} = $val if $val;
39 return $self->{throttle};
42 my($self, %other_args) = @_;
43 if($self->throttle and not %other_args) {
45 ($self->{args}->{progress} - $self->{last_respond_progress}) >= $self->throttle
48 $self->conn->respond({ %{$self->{args}}, %other_args });
49 $self->{last_respond_progress} = $self->{args}->{progress};
51 sub respond_complete {
52 my($self, %other_args) = @_;
54 $self->conn->respond_complete({ %{$self->{args}}, %other_args });
55 $self->run_post_response_hooks;
59 # run the post response hook subs, shifting them off as we go
60 sub run_post_response_hooks {
62 (shift @{$self->{post_proc_queue}})->() while @{$self->{post_proc_queue}};
65 # any subs passed to this method will be run after the call to respond_complete
68 push(@{$self->{post_proc_queue}}, $sub);
73 $self->{args}->{total} = $val if defined $val;
74 $self->{args}->{maximum} = $self->{args}->{total};
75 return $self->{args}->{total};
79 $self->{args}->{purchase_order} = $val if $val;
84 $self->{args}->{picklist} = $val if $val;
89 $self->{args}->{lid} += 1;
90 $self->{args}->{progress} += 1;
95 $self->{args}->{li} += 1;
96 $self->{args}->{progress} += 1;
101 $self->{args}->{copies} += 1;
102 $self->{args}->{progress} += 1;
107 $self->{args}->{bibs} += 1;
108 $self->{args}->{progress} += 1;
112 my($self, $amount) = @_;
113 $self->{args}->{debits_accrued} += $amount;
114 $self->{args}->{progress} += 1;
118 my($self, $editor) = @_;
119 $self->{editor} = $editor if defined $editor;
120 return $self->{editor};
124 $self->{args}->{complete} = 1;
129 my($self, $val) = @_;
130 $self->{ingest_ses} = $val if $val;
131 return $self->{ingest_ses};
134 sub push_ingest_queue {
135 my($self, $rec_id) = @_;
137 $self->ingest_ses(OpenSRF::AppSession->connect('open-ils.ingest'))
138 unless $self->ingest_ses;
140 my $req = $self->ingest_ses->request('open-ils.ingest.full.biblio.record', $rec_id);
142 push(@{$self->{ingest_queue}}, $req);
145 sub process_ingest_records {
147 return unless @{$self->{ingest_queue}};
149 for my $req (@{$self->{ingest_queue}}) {
153 $self->{args}->{indexed} += 1;
154 $self->{args}->{progress} += 1;
159 $self->ingest_ses->disconnect;
164 my($self, $org, $key, $val) = @_;
165 $self->{cache}->{$org} = {} unless $self->{cache}->{org};
166 $self->{cache}->{$org}->{$key} = $val if defined $val;
167 return $self->{cache}->{$org}->{$key};
171 package OpenILS::Application::Acq::Order;
172 use base qw/OpenILS::Application/;
173 use strict; use warnings;
174 # ----------------------------------------------------------------------------
175 # Break up each component of the order process and pieces into managable
176 # actions that can be shared across different workflows
177 # ----------------------------------------------------------------------------
179 use OpenSRF::Utils::Logger qw(:logger);
180 use OpenSRF::Utils::JSON;
181 use OpenSRF::AppSession;
182 use OpenILS::Utils::Fieldmapper;
183 use OpenILS::Utils::CStoreEditor q/:funcs/;
184 use OpenILS::Const qw/:const/;
185 use OpenSRF::EX q/:try/;
186 use OpenILS::Application::AppUtils;
187 use OpenILS::Application::Cat::BibCommon;
188 use OpenILS::Application::Cat::AssetCommon;
192 my $U = 'OpenILS::Application::AppUtils';
195 # ----------------------------------------------------------------------------
197 # ----------------------------------------------------------------------------
198 sub create_lineitem {
199 my($mgr, %args) = @_;
200 my $li = Fieldmapper::acq::lineitem->new;
201 $li->creator($mgr->editor->requestor->id);
202 $li->selector($li->creator);
203 $li->editor($li->creator);
204 $li->create_time('now');
205 $li->edit_time('now');
207 $li->$_($args{$_}) for keys %args;
210 $mgr->editor->create_acq_lineitem($li) or return 0;
212 unless($li->estimated_unit_price) {
213 # extract the price from the MARC data
214 my $price = get_li_price_from_attr($mgr->editor, $li) or return $li;
215 $li->estimated_unit_price($price);
216 return update_lineitem($mgr, $li);
222 sub get_li_price_from_attr {
224 my $attrs = $li->attributes || $e->search_acq_lineitem_attr({lineitem => $li->id});
226 for my $attr_type (qw/
227 lineitem_local_attr_definition
228 lineitem_prov_attr_definition
229 lineitem_marc_attr_definition/) {
232 $_->attr_name eq 'estimated_price' and
233 $_->attr_type eq $attr_type } @$attrs;
235 return $attr->attr_value if $attr;
242 sub update_lineitem {
244 $li->edit_time('now');
245 $li->editor($mgr->editor->requestor->id);
247 return $mgr->editor->retrieve_acq_lineitem($mgr->editor->data) if
248 $mgr->editor->update_acq_lineitem($li);
253 # ----------------------------------------------------------------------------
254 # Create real holds from patron requests for a given lineitem
255 # ----------------------------------------------------------------------------
256 sub promote_lineitem_holds {
259 my $requests = $mgr->editor->search_acq_user_request(
260 { lineitem => $li->id,
262 [ { need_before => {'>' => 'now'} },
263 { need_before => undef }
268 for my $request ( @$requests ) {
270 $request->eg_bib( $li->eg_bib_id );
271 $mgr->editor->update_acq_user_request( $request ) or return 0;
273 next unless ($U->is_true( $request->hold ));
275 my $hold = Fieldmapper::action::hold_request->new;
276 $hold->usr( $request->usr );
277 $hold->requestor( $request->usr );
278 $hold->request_time( $request->request_date );
279 $hold->pickup_lib( $request->pickup_lib );
280 $hold->request_lib( $request->pickup_lib );
281 $hold->selection_ou( $request->pickup_lib );
282 $hold->phone_notify( $request->phone_notify );
283 $hold->email_notify( $request->email_notify );
284 $hold->expire_time( $request->need_before );
286 if ($request->holdable_formats) {
287 my $mrm = $mgr->editor->search_metabib_metarecord_source_map( { source => $li->eg_bib_id } )->[0];
289 $hold->hold_type( 'M' );
290 $hold->holdable_formats( $request->holdable_formats );
291 $hold->target( $mrm->metarecord );
295 if (!$hold->target) {
296 $hold->hold_type( 'T' );
297 $hold->target( $li->eg_bib_id );
300 $mgr->editor->create_actor_hold_request( $hold ) or return 0;
306 sub delete_lineitem {
308 $li = $mgr->editor->retrieve_acq_lineitem($li) unless ref $li;
310 # delete the attached lineitem_details
311 my $lid_ids = $mgr->editor->search_acq_lineitem_detail({lineitem => $li->id}, {idlist=>1});
312 for my $lid_id (@$lid_ids) {
313 return 0 unless delete_lineitem_detail($mgr, $lid_id);
317 return $mgr->editor->delete_acq_lineitem($li);
320 # begins and commit transactions as it goes
321 sub create_lineitem_list_assets {
322 my($mgr, $li_ids) = @_;
323 return undef if check_import_li_marc_perms($mgr, $li_ids);
325 # create the bibs/volumes/copies and ingest the records
326 for my $li_id (@$li_ids) {
327 $mgr->editor->xact_begin;
328 my $data = create_lineitem_assets($mgr, $li_id) or return undef;
329 $mgr->editor->xact_commit;
330 # XXX ingest is in-db now
331 #$mgr->push_ingest_queue($data->{li}->eg_bib_id) if $data->{new_bib};
334 $mgr->process_ingest_records;
338 # returns event on error, undef on success
339 sub check_import_li_marc_perms {
340 my($mgr, $li_ids) = @_;
342 # if there are any order records that are not linked to
343 # in-db bib records, verify staff has perms to import order records
344 my $order_li = $mgr->editor->search_acq_lineitem(
345 [{id => $li_ids, eg_bib_id => undef}, {limit => 1}], {idlist => 1})->[0];
348 return $mgr->editor->die_event unless
349 $mgr->editor->allowed('IMPORT_ACQ_LINEITEM_BIB_RECORD');
356 # ----------------------------------------------------------------------------
357 # if all of the lineitem details for this lineitem have
358 # been received, mark the lineitem as received
359 # returns 1 on non-received, li on received, 0 on error
360 # ----------------------------------------------------------------------------
362 sub describe_affected_po {
366 OpenILS::Application::Acq::Financials::build_price_summary(
371 "state" => $po->state,
372 "amount_encumbered" => $enc,
373 "amount_spent" => $spent
378 sub check_lineitem_received {
379 my($mgr, $li_id) = @_;
381 my $non_recv = $mgr->editor->search_acq_lineitem_detail(
382 {recv_time => undef, lineitem => $li_id}, {idlist=>1});
384 return 1 if @$non_recv;
386 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
387 $li->state('received');
388 return update_lineitem($mgr, $li);
391 sub receive_lineitem {
392 my($mgr, $li_id, $skip_complete_check) = @_;
393 my $li = $mgr->editor->retrieve_acq_lineitem($li_id) or return 0;
395 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
396 {lineitem => $li_id, recv_time => undef}, {idlist => 1});
398 for my $lid_id (@$lid_ids) {
399 receive_lineitem_detail($mgr, $lid_id, 1) or return 0;
403 $li->state('received');
405 $li = update_lineitem($mgr, $li) or return 0;
406 $mgr->post_process( sub { create_lineitem_status_events($mgr, $li_id, 'aur.received'); });
410 $skip_complete_check or (
411 $po = check_purchase_order_received($mgr, $li->purchase_order)
414 my $result = {"li" => {$li->id => {"state" => $li->state}}};
415 $result->{"po"} = describe_affected_po($mgr->editor, $po) if ref $po;
419 sub rollback_receive_lineitem {
420 my($mgr, $li_id) = @_;
421 my $li = $mgr->editor->retrieve_acq_lineitem($li_id) or return 0;
423 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
424 {lineitem => $li_id, recv_time => {'!=' => undef}}, {idlist => 1});
426 for my $lid_id (@$lid_ids) {
427 rollback_receive_lineitem_detail($mgr, $lid_id, 1) or return 0;
431 $li->state('on-order');
432 return update_lineitem($mgr, $li);
436 sub create_lineitem_status_events {
437 my($mgr, $li_id, $hook) = @_;
439 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
441 my $user_reqs = $mgr->editor->search_acq_user_request([
442 {lineitem => $li_id},
443 {flesh => 1, flesh_fields => {aur => ['usr']}}
446 for my $user_req (@$user_reqs) {
447 my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $user_req->usr->home_ou);
455 # ----------------------------------------------------------------------------
457 # ----------------------------------------------------------------------------
458 sub create_lineitem_detail {
459 my($mgr, %args) = @_;
460 my $lid = Fieldmapper::acq::lineitem_detail->new;
461 $lid->$_($args{$_}) for keys %args;
464 return $mgr->editor->create_acq_lineitem_detail($lid);
468 # flesh out any required data with default values where appropriate
469 sub complete_lineitem_detail {
471 unless($lid->barcode) {
472 my $pfx = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.tmp_barcode_prefix') || 'ACQ';
473 $lid->barcode($pfx.$lid->id);
476 unless($lid->cn_label) {
477 my $pfx = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.tmp_callnumber_prefix') || 'ACQ';
478 $lid->cn_label($pfx.$lid->id);
481 if(!$lid->location and my $loc = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.default_copy_location')) {
482 $lid->location($loc);
485 $lid->circ_modifier(get_default_circ_modifier($mgr, $lid->owning_lib))
486 unless defined $lid->circ_modifier;
488 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
492 sub get_default_circ_modifier {
494 my $code = $mgr->cache($org, 'def_circ_mod');
495 $code = $U->ou_ancestor_setting_value($org, 'acq.default_circ_modifier') unless defined $code;
496 return $mgr->cache($org, 'def_circ_mod', $code) if defined $code;
500 sub delete_lineitem_detail {
502 $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid) unless ref $lid;
503 return $mgr->editor->delete_acq_lineitem_detail($lid);
507 sub receive_lineitem_detail {
508 my($mgr, $lid_id, $skip_complete_check) = @_;
509 my $e = $mgr->editor;
511 my $lid = $e->retrieve_acq_lineitem_detail([
515 acqlid => ['fund_debit']
520 return 1 if $lid->recv_time;
522 $lid->recv_time('now');
523 $e->update_acq_lineitem_detail($lid) or return 0;
525 my $copy = $e->retrieve_asset_copy($lid->eg_copy_id) or return 0;
526 $copy->status(OILS_COPY_STATUS_IN_PROCESS);
527 $copy->edit_date('now');
528 $copy->editor($e->requestor->id);
529 $e->update_asset_copy($copy) or return 0;
533 return 1 if $skip_complete_check;
535 my $li = check_lineitem_received($mgr, $lid->lineitem) or return 0;
536 return 1 if $li == 1; # li not received
538 return check_purchase_order_received($mgr, $li->purchase_order) or return 0;
542 sub rollback_receive_lineitem_detail {
543 my($mgr, $lid_id) = @_;
544 my $e = $mgr->editor;
546 my $lid = $e->retrieve_acq_lineitem_detail([
550 acqlid => ['fund_debit']
555 return 1 unless $lid->recv_time;
557 $lid->clear_recv_time;
558 $e->update_acq_lineitem_detail($lid) or return 0;
560 my $copy = $e->retrieve_asset_copy($lid->eg_copy_id) or return 0;
561 $copy->status(OILS_COPY_STATUS_ON_ORDER);
562 $copy->edit_date('now');
563 $copy->editor($e->requestor->id);
564 $e->update_asset_copy($copy) or return 0;
570 # ----------------------------------------------------------------------------
572 # ----------------------------------------------------------------------------
573 sub set_lineitem_attr {
574 my($mgr, %args) = @_;
575 my $attr_type = $args{attr_type};
577 # first, see if it's already set. May just need to overwrite it
578 my $attr = $mgr->editor->search_acq_lineitem_attr({
579 lineitem => $args{lineitem},
580 attr_type => $args{attr_type},
581 attr_name => $args{attr_name}
585 $attr->attr_value($args{attr_value});
586 return $attr if $mgr->editor->update_acq_lineitem_attr($attr);
591 $attr = Fieldmapper::acq::lineitem_attr->new;
592 $attr->$_($args{$_}) for keys %args;
594 unless($attr->definition) {
595 my $find = "search_acq_$attr_type";
596 my $attr_def_id = $mgr->editor->$find({code => $attr->attr_name}, {idlist=>1})->[0] or return 0;
597 $attr->definition($attr_def_id);
599 return $mgr->editor->create_acq_lineitem_attr($attr);
603 # ----------------------------------------------------------------------------
605 # ----------------------------------------------------------------------------
606 sub create_lineitem_debits {
607 my ($mgr, $li, $dry_run) = @_;
609 unless($li->estimated_unit_price) {
610 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_PRICE', payload => $li->id));
611 $mgr->editor->rollback;
615 unless($li->provider) {
616 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_PROVIDER', payload => $li->id));
617 $mgr->editor->rollback;
621 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
622 {lineitem => $li->id},
626 for my $lid_id (@$lid_ids) {
628 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
631 flesh_fields => {acqlid => ['fund']}
635 create_lineitem_detail_debit($mgr, $li, $lid, $dry_run) or return 0;
644 sub create_lineitem_detail_debit {
645 my ($mgr, $li, $lid, $dry_run, $no_translate) = @_;
647 # don't create the debit if one already exists
648 return $mgr->editor->retrieve_acq_fund_debit($lid->fund_debit) if $lid->fund_debit;
650 my $li_id = ref($li) ? $li->id : $li;
652 unless(ref $li and ref $li->provider) {
653 $li = $mgr->editor->retrieve_acq_lineitem([
656 flesh_fields => {jub => ['provider']},
661 unless(ref $lid and ref $lid->fund) {
662 $lid = $mgr->editor->retrieve_acq_lineitem_detail([
665 flesh_fields => {acqlid => ['fund']}
670 my $amount = $li->estimated_unit_price;
671 if($li->provider->currency_type ne $lid->fund->currency_type and !$no_translate) {
673 # At Fund debit creation time, translate into the currency of the fund
674 # TODO: org setting to disable automatic currency conversion at debit create time?
676 $amount = $mgr->editor->json_query({
678 'acq.exchange_ratio',
679 $li->provider->currency_type, # source currency
680 $lid->fund->currency_type, # destination currency
681 $li->estimated_unit_price # source amount
686 my $debit = create_fund_debit(
689 fund => $lid->fund->id,
690 origin_amount => $li->estimated_unit_price,
691 origin_currency_type => $li->provider->currency_type,
695 $lid->fund_debit($debit->id);
696 $lid->fund($lid->fund->id);
697 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
702 __PACKAGE__->register_method(
703 "method" => "fund_exceeds_balance_percent_api",
704 "api_name" => "open-ils.acq.fund.check_balance_percentages",
706 "desc" => q/Determine whether a given fund exceeds its defined
707 "balance stop and warning percentages"/,
709 {"desc" => "Authentication token", "type" => "string"},
710 {"desc" => "Fund ID", "type" => "number"},
711 {"desc" => "Theoretical debit amount (optional)",
714 "return" => {"desc" => q/An array of two values, for stop and warning,
715 in that order: 1 if fund exceeds that balance percentage, else 0/}
719 sub fund_exceeds_balance_percent_api {
720 my ($self, $conn, $auth, $fund_id, $debit_amount) = @_;
724 my $e = new_editor("authtoken" => $auth);
725 return $e->die_event unless $e->checkauth;
727 my $fund = $e->retrieve_acq_fund($fund_id) or return $e->die_event;
728 return $e->die_event unless $e->allowed("VIEW_FUND", $fund->org);
731 fund_exceeds_balance_percent($fund, $debit_amount, $e, "stop"),
732 fund_exceeds_balance_percent($fund, $debit_amount, $e, "warning")
739 sub fund_exceeds_balance_percent {
740 my ($fund, $debit_amount, $e, $which) = @_;
742 my ($method_name, $event_name) = @{{
744 "balance_warning_percent", "ACQ_FUND_EXCEEDS_WARN_PERCENT"
747 "balance_stop_percent", "ACQ_FUND_EXCEEDS_STOP_PERCENT"
751 if ($fund->$method_name) {
753 $e->search_acq_fund_combined_balance({"fund" => $fund->id})->[0];
755 $e->search_acq_fund_allocation_total({"fund" => $fund->id})->[0];
757 $balance = ($balance) ? $balance->amount : 0;
758 $allocations = ($allocations) ? $allocations->amount : 0;
761 $allocations == 0 || # if no allocations were ever made, assume we have hit the stop percent
762 ((($balance - $debit_amount) / $allocations) * 100) <
765 $logger->info("fund would hit a limit: " . $fund->id . ", $balance, $debit_amount, $allocations, $method_name");
770 "fund" => $fund, "debit_amount" => $debit_amount
780 # ----------------------------------------------------------------------------
782 # ----------------------------------------------------------------------------
783 sub create_fund_debit {
784 my($mgr, $dry_run, %args) = @_;
786 # Verify the fund is not being spent beyond the hard stop amount
787 my $fund = $mgr->editor->retrieve_acq_fund($args{fund}) or return 0;
790 fund_exceeds_balance_percent(
791 $fund, $args{"amount"}, $mgr->editor, "stop"
794 $dry_run and fund_exceeds_balance_percent(
795 $fund, $args{"amount"}, $mgr->editor, "warning"
798 my $debit = Fieldmapper::acq::fund_debit->new;
799 $debit->debit_type('purchase');
800 $debit->encumbrance('t');
801 $debit->$_($args{$_}) for keys %args;
803 $mgr->add_debit($debit->amount);
804 return $mgr->editor->create_acq_fund_debit($debit);
808 # ----------------------------------------------------------------------------
810 # ----------------------------------------------------------------------------
811 sub create_picklist {
812 my($mgr, %args) = @_;
813 my $picklist = Fieldmapper::acq::picklist->new;
814 $picklist->creator($mgr->editor->requestor->id);
815 $picklist->owner($picklist->creator);
816 $picklist->editor($picklist->creator);
817 $picklist->create_time('now');
818 $picklist->edit_time('now');
819 $picklist->org_unit($mgr->editor->requestor->ws_ou);
820 $picklist->owner($mgr->editor->requestor->id);
821 $picklist->$_($args{$_}) for keys %args;
823 $mgr->picklist($picklist);
824 return $mgr->editor->create_acq_picklist($picklist);
827 sub update_picklist {
828 my($mgr, $picklist) = @_;
829 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
830 $picklist->edit_time('now');
831 $picklist->editor($mgr->editor->requestor->id);
832 if ($mgr->editor->update_acq_picklist($picklist)) {
833 $picklist = $mgr->editor->retrieve_acq_picklist($mgr->editor->data);
834 $mgr->picklist($picklist);
841 sub delete_picklist {
842 my($mgr, $picklist) = @_;
843 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
845 # delete all 'new' lineitems
846 my $li_ids = $mgr->editor->search_acq_lineitem({picklist => $picklist->id, state => 'new'}, {idlist => 1});
847 for my $li_id (@$li_ids) {
848 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
849 return 0 unless delete_lineitem($mgr, $li);
853 # detach all non-'new' lineitems
854 $li_ids = $mgr->editor->search_acq_lineitem({picklist => $picklist->id, state => {'!=' => 'new'}}, {idlist => 1});
855 for my $li_id (@$li_ids) {
856 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
858 return 0 unless update_lineitem($mgr, $li);
862 # remove any picklist-specific object perms
863 my $ops = $mgr->editor->search_permission_usr_object_perm_map({object_type => 'acqpl', object_id => ''.$picklist->id});
865 return 0 unless $mgr->editor->delete_usr_object_perm_map($op);
868 return $mgr->editor->delete_acq_picklist($picklist);
871 # ----------------------------------------------------------------------------
873 # ----------------------------------------------------------------------------
874 sub update_purchase_order {
876 $po = $mgr->editor->retrieve_acq_purchase_order($po) unless ref $po;
877 $po->editor($mgr->editor->requestor->id);
878 $po->edit_time('now');
879 $mgr->purchase_order($po);
880 return $mgr->editor->retrieve_acq_purchase_order($mgr->editor->data)
881 if $mgr->editor->update_acq_purchase_order($po);
885 sub create_purchase_order {
886 my($mgr, %args) = @_;
888 # verify the chosen provider is still active
889 my $provider = $mgr->editor->retrieve_acq_provider($args{provider}) or return 0;
890 unless($U->is_true($provider->active)) {
891 $logger->error("provider is not active. cannot create PO");
892 $mgr->editor->event(OpenILS::Event->new('ACQ_PROVIDER_INACTIVE'));
896 my $po = Fieldmapper::acq::purchase_order->new;
897 $po->creator($mgr->editor->requestor->id);
898 $po->editor($mgr->editor->requestor->id);
899 $po->owner($mgr->editor->requestor->id);
900 $po->edit_time('now');
901 $po->create_time('now');
902 $po->state('pending');
903 $po->ordering_agency($mgr->editor->requestor->ws_ou);
904 $po->$_($args{$_}) for keys %args;
906 $mgr->purchase_order($po);
907 return $mgr->editor->create_acq_purchase_order($po);
910 # ----------------------------------------------------------------------------
911 # if all of the lineitems for this PO are received,
912 # mark the PO as received
913 # ----------------------------------------------------------------------------
914 sub check_purchase_order_received {
915 my($mgr, $po_id) = @_;
917 my $non_recv_li = $mgr->editor->search_acq_lineitem(
918 { purchase_order => $po_id,
919 state => {'!=' => 'received'}
922 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id);
923 return $po if @$non_recv_li;
925 $po->state('received');
926 return update_purchase_order($mgr, $po);
930 # ----------------------------------------------------------------------------
931 # Bib, Callnumber, and Copy data
932 # ----------------------------------------------------------------------------
934 sub create_lineitem_assets {
935 my($mgr, $li_id) = @_;
938 my $li = $mgr->editor->retrieve_acq_lineitem([
941 flesh_fields => {jub => ['purchase_order', 'attributes']}
945 # -----------------------------------------------------------------
946 # first, create the bib record if necessary
947 # -----------------------------------------------------------------
949 unless($li->eg_bib_id) {
950 create_bib($mgr, $li) or return 0;
955 # -----------------------------------------------------------------
956 # The lineitem is going live, promote user request holds to real holds
957 # -----------------------------------------------------------------
958 promote_lineitem_holds($mgr, $li) or return 0;
960 my $li_details = $mgr->editor->search_acq_lineitem_detail({lineitem => $li_id}, {idlist=>1});
962 # -----------------------------------------------------------------
963 # for each lineitem_detail, create the volume if necessary, create
964 # a copy, and link them all together.
965 # -----------------------------------------------------------------
967 for my $lid_id (@{$li_details}) {
969 my $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid_id) or return 0;
970 next if $lid->eg_copy_id;
972 # use the same callnumber label for all items within this lineitem
973 $lid->cn_label($first_cn) if $first_cn and not $lid->cn_label;
975 # apply defaults if necessary
976 return 0 unless complete_lineitem_detail($mgr, $lid);
978 $first_cn = $lid->cn_label unless $first_cn;
980 my $org = $lid->owning_lib;
981 my $label = $lid->cn_label;
982 my $bibid = $li->eg_bib_id;
984 my $volume = $mgr->cache($org, "cn.$bibid.$label");
986 $volume = create_volume($mgr, $li, $lid) or return 0;
987 $mgr->cache($org, "cn.$bibid.$label", $volume);
989 create_copy($mgr, $volume, $lid, $li) or return 0;
992 return { li => $li, new_bib => $new_bib };
998 my $record = OpenILS::Application::Cat::BibCommon->biblio_record_xml_import(
1003 1, # override tcn collisions
1006 if($U->event_code($record)) {
1007 $mgr->editor->event($record);
1008 $mgr->editor->rollback;
1012 $li->eg_bib_id($record->id);
1014 return update_lineitem($mgr, $li);
1018 my($mgr, $li, $lid) = @_;
1020 my ($volume, $evt) =
1021 OpenILS::Application::Cat::AssetCommon->find_or_create_volume(
1029 $mgr->editor->event($evt);
1037 my($mgr, $volume, $lid, $li) = @_;
1038 my $copy = Fieldmapper::asset::copy->new;
1040 $copy->loan_duration(2);
1041 $copy->fine_level(2);
1042 $copy->status(($lid->recv_time) ? OILS_COPY_STATUS_IN_PROCESS : OILS_COPY_STATUS_ON_ORDER);
1043 $copy->barcode($lid->barcode);
1044 $copy->location($lid->location);
1045 $copy->call_number($volume->id);
1046 $copy->circ_lib($volume->owning_lib);
1047 $copy->circ_modifier($lid->circ_modifier);
1049 # AKA list price. We might need a $li->list_price field since
1050 # estimated price is not necessarily the same as list price
1051 $copy->price($li->estimated_unit_price);
1053 my $evt = OpenILS::Application::Cat::AssetCommon->create_copy($mgr->editor, $volume, $copy);
1055 $mgr->editor->event($evt);
1060 $lid->eg_copy_id($copy->id);
1061 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
1069 # ----------------------------------------------------------------------------
1070 # Workflow: Build a selection list from a Z39.50 search
1071 # ----------------------------------------------------------------------------
1073 __PACKAGE__->register_method(
1074 method => 'zsearch',
1075 api_name => 'open-ils.acq.picklist.search.z3950',
1078 desc => 'Performs a z3950 federated search and creates a picklist and associated lineitems',
1080 {desc => 'Authentication token', type => 'string'},
1081 {desc => 'Search definition', type => 'object'},
1082 {desc => 'Picklist name, optional', type => 'string'},
1088 my($self, $conn, $auth, $search, $name, $options) = @_;
1089 my $e = new_editor(authtoken=>$auth);
1090 return $e->event unless $e->checkauth;
1091 return $e->event unless $e->allowed('CREATE_PICKLIST');
1093 $search->{limit} ||= 10;
1096 my $ses = OpenSRF::AppSession->create('open-ils.search');
1097 my $req = $ses->request('open-ils.search.z3950.search_class', $auth, $search);
1102 while(my $resp = $req->recv(timeout=>60)) {
1105 my $e = new_editor(requestor=>$e->requestor, xact=>1);
1106 $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1107 $picklist = zsearch_build_pl($mgr, $name);
1111 my $result = $resp->content;
1112 my $count = $result->{count} || 0;
1113 $mgr->total( (($count < $search->{limit}) ? $count : $search->{limit})+1 );
1115 for my $rec (@{$result->{records}}) {
1117 my $li = create_lineitem($mgr,
1118 picklist => $picklist->id,
1119 source_label => $result->{service},
1120 marc => $rec->{marcxml},
1121 eg_bib_id => $rec->{bibid}
1124 if($$options{respond_li}) {
1125 $li->attributes($mgr->editor->search_acq_lineitem_attr({lineitem => $li->id}))
1126 if $$options{flesh_attrs};
1127 $li->clear_marc if $$options{clear_marc};
1128 $mgr->respond(lineitem => $li);
1135 $mgr->editor->commit;
1136 return $mgr->respond_complete;
1139 sub zsearch_build_pl {
1140 my($mgr, $name) = @_;
1143 my $picklist = $mgr->editor->search_acq_picklist({
1144 owner => $mgr->editor->requestor->id,
1148 if($name eq '' and $picklist) {
1149 return 0 unless delete_picklist($mgr, $picklist);
1153 return update_picklist($mgr, $picklist) if $picklist;
1154 return create_picklist($mgr, name => $name);
1158 # ----------------------------------------------------------------------------
1159 # Workflow: Build a selection list / PO by importing a batch of MARC records
1160 # ----------------------------------------------------------------------------
1162 __PACKAGE__->register_method(
1163 method => 'upload_records',
1164 api_name => 'open-ils.acq.process_upload_records',
1168 sub upload_records {
1169 my($self, $conn, $auth, $key) = @_;
1171 my $e = new_editor(authtoken => $auth, xact => 1);
1172 return $e->die_event unless $e->checkauth;
1173 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1175 my $cache = OpenSRF::Utils::Cache->new;
1177 my $data = $cache->get_cache("vandelay_import_spool_$key");
1178 my $purpose = $data->{purpose};
1179 my $filename = $data->{path};
1180 my $provider = $data->{provider};
1181 my $picklist = $data->{picklist};
1182 my $create_po = $data->{create_po};
1183 my $activate_po = $data->{activate_po};
1184 my $ordering_agency = $data->{ordering_agency};
1185 my $create_assets = $data->{create_assets};
1189 unless(-r $filename) {
1190 $logger->error("unable to read MARC file $filename");
1192 return OpenILS::Event->new('FILE_UPLOAD_ERROR', payload => {filename => $filename});
1195 $provider = $e->retrieve_acq_provider($provider) or return $e->die_event;
1198 $picklist = $e->retrieve_acq_picklist($picklist) or return $e->die_event;
1199 if($picklist->owner != $e->requestor->id) {
1200 return $e->die_event unless
1201 $e->allowed('CREATE_PICKLIST', $picklist->org_unit, $picklist);
1203 $mgr->picklist($picklist);
1208 $po = create_purchase_order($mgr,
1209 ordering_agency => $ordering_agency,
1210 provider => $provider->id,
1212 ) or return $mgr->editor->die_event;
1215 $logger->info("acq processing MARC file=$filename");
1217 my $batch = new MARC::Batch ('USMARC', $filename);
1225 my ($err, $xml, $r);
1230 } catch Error with {
1232 $logger->warn("Proccessing of record $count in set $key failed with error $err. Skipping this record");
1239 ($xml = $r->as_xml_record()) =~ s/\n//sog;
1240 $xml =~ s/^<\?xml.+\?\s*>//go;
1241 $xml =~ s/>\s+</></go;
1242 $xml =~ s/\p{Cc}//go;
1243 $xml = $U->entityize($xml);
1244 $xml =~ s/[\x00-\x1f]//go;
1246 } catch Error with {
1248 $logger->warn("Proccessing XML of record $count in set $key failed with error $err. Skipping this record");
1251 next if $err or not $xml;
1254 source_label => $provider->code,
1255 provider => $provider->id,
1259 $args{picklist} = $picklist->id if $picklist;
1261 $args{purchase_order} = $po->id;
1262 $args{state} = 'order-pending';
1265 my $li = create_lineitem($mgr, %args) or return $mgr->editor->die_event;
1267 $li->provider($provider); # flesh it, we'll need it later
1269 import_lineitem_details($mgr, $ordering_agency, $li) or return $mgr->editor->die_event;
1272 push(@li_list, $li->id);
1276 my $die_event = activate_purchase_order_impl($mgr, $po->id) if $po and $activate_po;
1277 return $die_event if $die_event;
1281 $cache->delete_cache('vandelay_import_spool_' . $key);
1283 if ($create_assets) {
1284 create_lineitem_list_assets($mgr, \@li_list) or return $e->die_event;
1287 return $mgr->respond_complete;
1290 sub import_lineitem_details {
1291 my($mgr, $ordering_agency, $li) = @_;
1293 my $holdings = $mgr->editor->json_query({from => ['acq.extract_provider_holding_data', $li->id]});
1294 return 1 unless @$holdings;
1295 my $org_path = $U->get_org_ancestors($ordering_agency);
1296 $org_path = [ reverse (@$org_path) ];
1302 # create a lineitem detail for each copy in the data
1304 my $compiled = extract_lineitem_detail_data($mgr, $org_path, $holdings, $idx);
1305 last unless defined $compiled;
1306 return 0 unless $compiled;
1308 # this takes the price of the last copy and uses it as the lineitem price
1309 # need to determine if a given record would include different prices for the same item
1310 $price = $$compiled{estimated_price};
1312 last unless $$compiled{quantity};
1314 for(1..$$compiled{quantity}) {
1315 my $lid = create_lineitem_detail(
1317 lineitem => $li->id,
1318 owning_lib => $$compiled{owning_lib},
1319 cn_label => $$compiled{call_number},
1320 fund => $$compiled{fund},
1321 circ_modifier => $$compiled{circ_modifier},
1322 note => $$compiled{note},
1323 location => $$compiled{copy_location},
1324 collection_code => $$compiled{collection_code}
1332 $li->estimated_unit_price($price);
1333 update_lineitem($mgr, $li) or return 0;
1337 # return hash on success, 0 on error, undef on no more holdings
1338 sub extract_lineitem_detail_data {
1339 my($mgr, $org_path, $holdings, $index) = @_;
1341 my @data_list = grep { $_->{holding} eq $index } @$holdings;
1342 return undef unless @data_list;
1344 my %compiled = map { $_->{attr} => $_->{data} } @data_list;
1345 my $base_org = $$org_path[0];
1349 $logger->error("Item import extraction error: $msg");
1350 $logger->error('Holdings Data: ' . OpenSRF::Utils::JSON->perl2JSON(\%compiled));
1351 $mgr->editor->rollback;
1352 $mgr->editor->event(OpenILS::Event->new('ACQ_IMPORT_ERROR', payload => $msg));
1356 # ---------------------------------------------------------------------
1358 if(my $code = $compiled{fund_code}) {
1360 my $fund = $mgr->cache($base_org, "fund.$code");
1362 # search up the org tree for the most appropriate fund
1363 for my $org (@$org_path) {
1364 $fund = $mgr->editor->search_acq_fund(
1365 {org => $org, code => $code, year => DateTime->now->year}, {idlist => 1})->[0];
1369 return $killme->("no fund with code $code at orgs [@$org_path]") unless $fund;
1370 $compiled{fund} = $fund;
1371 $mgr->cache($base_org, "fund.$code", $fund);
1375 # ---------------------------------------------------------------------
1377 if(my $sn = $compiled{owning_lib}) {
1378 my $org_id = $mgr->cache($base_org, "orgsn.$sn") ||
1379 $mgr->editor->search_actor_org_unit({shortname => $sn}, {idlist => 1})->[0];
1380 return $killme->("invalid owning_lib defined: $sn") unless $org_id;
1381 $compiled{owning_lib} = $org_id;
1382 $mgr->cache($$org_path[0], "orgsn.$sn", $org_id);
1386 # ---------------------------------------------------------------------
1388 my $code = $compiled{circ_modifier};
1392 # verify this is a valid circ modifier
1393 return $killme->("invlalid circ_modifier $code") unless
1394 defined $mgr->cache($base_org, "mod.$code") or
1395 $mgr->editor->retrieve_config_circ_modifier($code);
1397 # if valid, cache for future tests
1398 $mgr->cache($base_org, "mod.$code", $code);
1401 $compiled{circ_modifier} = get_default_circ_modifier($mgr, $base_org);
1405 # ---------------------------------------------------------------------
1407 if( my $name = $compiled{copy_location}) {
1408 my $loc = $mgr->cache($base_org, "copy_loc.$name");
1410 for my $org (@$org_path) {
1411 $loc = $mgr->editor->search_asset_copy_location(
1412 {owning_lib => $org, name => $name}, {idlist => 1})->[0];
1416 return $killme->("Invalid copy location $name") unless $loc;
1417 $compiled{copy_location} = $loc;
1418 $mgr->cache($base_org, "copy_loc.$name", $loc);
1426 # ----------------------------------------------------------------------------
1427 # Workflow: Given an existing purchase order, import/create the bibs,
1428 # callnumber and copy objects
1429 # ----------------------------------------------------------------------------
1431 __PACKAGE__->register_method(
1432 method => 'create_po_assets',
1433 api_name => 'open-ils.acq.purchase_order.assets.create',
1435 desc => q/Creates assets for each lineitem in the purchase order/,
1437 {desc => 'Authentication token', type => 'string'},
1438 {desc => 'The purchase order id', type => 'number'},
1440 return => {desc => 'Streams a total versus completed counts object, event on error'}
1444 sub create_po_assets {
1445 my($self, $conn, $auth, $po_id) = @_;
1447 my $e = new_editor(authtoken=>$auth, xact=>1);
1448 return $e->die_event unless $e->checkauth;
1449 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1451 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1453 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1455 # it's ugly, but it's fast. Get the total count of lineitem detail objects to process
1456 my $lid_total = $e->json_query({
1457 select => { acqlid => [{aggregate => 1, transform => 'count', column => 'id'}] },
1463 join => {acqpo => {fkey => 'purchase_order', field => 'id'}}
1467 where => {'+acqpo' => {id => $po_id}}
1470 $mgr->total(scalar(@$li_ids) + $lid_total);
1472 create_lineitem_list_assets($mgr, $li_ids) or return $e->die_event;
1475 update_purchase_order($mgr, $po) or return $e->die_event;
1478 return $mgr->respond_complete;
1483 __PACKAGE__->register_method(
1484 method => 'create_purchase_order_api',
1485 api_name => 'open-ils.acq.purchase_order.create',
1487 desc => 'Creates a new purchase order',
1489 {desc => 'Authentication token', type => 'string'},
1490 {desc => 'purchase_order to create', type => 'object'}
1492 return => {desc => 'The purchase order id, Event on failure'}
1496 sub create_purchase_order_api {
1497 my($self, $conn, $auth, $po, $args) = @_;
1500 my $e = new_editor(xact=>1, authtoken=>$auth);
1501 return $e->die_event unless $e->checkauth;
1502 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
1503 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1506 my %pargs = (ordering_agency => $e->requestor->ws_ou); # default
1507 $pargs{provider} = $po->provider if $po->provider;
1508 $pargs{ordering_agency} = $po->ordering_agency if $po->ordering_agency;
1509 $pargs{prepayment_required} = $po->prepayment_required if $po->prepayment_required;
1511 $po = create_purchase_order($mgr, %pargs) or return $e->die_event;
1513 my $li_ids = $$args{lineitems};
1517 for my $li_id (@$li_ids) {
1519 my $li = $e->retrieve_acq_lineitem([
1521 {flesh => 1, flesh_fields => {jub => ['attributes']}}
1522 ]) or return $e->die_event;
1524 $li->provider($po->provider);
1525 $li->purchase_order($po->id);
1526 $li->state('pending-order');
1527 update_lineitem($mgr, $li) or return $e->die_event;
1532 # commit before starting the asset creation
1535 if($li_ids and $$args{create_assets}) {
1536 create_lineitem_list_assets($mgr, $li_ids) or return $e->die_event;
1539 return $mgr->respond_complete;
1544 __PACKAGE__->register_method(
1545 method => 'update_lineitem_fund_batch',
1546 api_name => 'open-ils.acq.lineitem.fund.update.batch',
1549 desc => q/Given a set of lineitem IDS, updates the fund for all attached lineitem details/
1553 sub update_lineitem_fund_batch {
1554 my($self, $conn, $auth, $li_ids, $fund_id) = @_;
1555 my $e = new_editor(xact=>1, authtoken=>$auth);
1556 return $e->die_event unless $e->checkauth;
1557 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1558 for my $li_id (@$li_ids) {
1559 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
1560 return $evt if $evt;
1561 my $li_details = $e->search_acq_lineitem_detail({lineitem => $li_id});
1562 $_->fund($fund_id) and $_->ischanged(1) for @$li_details;
1563 $evt = lineitem_detail_CUD_batch($mgr, $li_details);
1564 return $evt if $evt;
1569 return $mgr->respond_complete;
1574 __PACKAGE__->register_method(
1575 method => 'lineitem_detail_CUD_batch_api',
1576 api_name => 'open-ils.acq.lineitem_detail.cud.batch',
1579 desc => q/Creates a new purchase order line item detail.
1580 Additionally creates the associated fund_debit/,
1582 {desc => 'Authentication token', type => 'string'},
1583 {desc => 'List of lineitem_details to create', type => 'array'},
1584 {desc => 'Create Debits. Used for creating post-po-asset-creation debits', type => 'bool'},
1586 return => {desc => 'Streaming response of current position in the array'}
1590 __PACKAGE__->register_method(
1591 method => 'lineitem_detail_CUD_batch_api',
1592 api_name => 'open-ils.acq.lineitem_detail.cud.batch.dry_run',
1596 Dry run version of open-ils.acq.lineitem_detail.cud.batch.
1597 In dry_run mode, updated fund_debit's the exceed the warning
1598 percent return an event.
1604 sub lineitem_detail_CUD_batch_api {
1605 my($self, $conn, $auth, $li_details, $create_debits) = @_;
1606 my $e = new_editor(xact=>1, authtoken=>$auth);
1607 return $e->die_event unless $e->checkauth;
1608 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1609 my $dry_run = ($self->api_name =~ /dry_run/o);
1610 my $evt = lineitem_detail_CUD_batch($mgr, $li_details, $create_debits, $dry_run);
1611 return $evt if $evt;
1613 return $mgr->respond_complete;
1617 sub lineitem_detail_CUD_batch {
1618 my($mgr, $li_details, $create_debits, $dry_run) = @_;
1620 $mgr->total(scalar(@$li_details));
1621 my $e = $mgr->editor;
1625 my $fund_cache = {};
1628 for my $lid (@$li_details) {
1630 unless($li = $li_cache{$lid->lineitem}) {
1631 ($li, $evt) = fetch_and_check_li($e, $lid->lineitem, 'write');
1632 return $evt if $evt;
1636 $lid = create_lineitem_detail($mgr, %{$lid->to_bare_hash}) or return $e->die_event;
1637 if($create_debits) {
1638 $li->provider($e->retrieve_acq_provider($li->provider)) or return $e->die_event;
1639 $lid->fund($e->retrieve_acq_fund($lid->fund)) or return $e->die_event;
1640 create_lineitem_detail_debit($mgr, $li, $lid, 0, 1) or return $e->die_event;
1643 } elsif($lid->ischanged) {
1644 return $evt if $evt = handle_changed_lid($e, $lid, $dry_run, $fund_cache);
1646 } elsif($lid->isdeleted) {
1647 delete_lineitem_detail($mgr, $lid) or return $e->die_event;
1650 $mgr->respond(li => $li);
1651 $li_cache{$lid->lineitem} = $li;
1657 sub handle_changed_lid {
1658 my($e, $lid, $dry_run, $fund_cache) = @_;
1660 my $orig_lid = $e->retrieve_acq_lineitem_detail($lid->id) or return $e->die_event;
1662 # updating the fund, so update the debit
1663 if($orig_lid->fund_debit and $orig_lid->fund != $lid->fund) {
1665 my $debit = $e->retrieve_acq_fund_debit($orig_lid->fund_debit);
1666 my $new_fund = $$fund_cache{$lid->fund} =
1667 $$fund_cache{$lid->fund} || $e->retrieve_acq_fund($lid->fund);
1669 # check the thresholds
1670 return $e->die_event if
1671 fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "stop");
1672 return $e->die_event if $dry_run and
1673 fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "warning");
1675 $debit->fund($new_fund->id);
1676 $e->update_acq_fund_debit($debit) or return $e->die_event;
1679 $e->update_acq_lineitem_detail($lid) or return $e->die_event;
1684 __PACKAGE__->register_method(
1685 method => 'receive_po_api',
1686 api_name => 'open-ils.acq.purchase_order.receive'
1689 sub receive_po_api {
1690 my($self, $conn, $auth, $po_id) = @_;
1691 my $e = new_editor(xact => 1, authtoken => $auth);
1692 return $e->die_event unless $e->checkauth;
1693 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1695 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1696 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1698 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1700 for my $li_id (@$li_ids) {
1701 receive_lineitem($mgr, $li_id) or return $e->die_event;
1705 $po->state('received');
1706 update_purchase_order($mgr, $po) or return $e->die_event;
1709 return $mgr->respond_complete;
1713 # At the moment there's a lack of parallelism between the receive and unreceive
1714 # API methods for POs and the API methods for LIs and LIDs. The methods for
1715 # POs stream back objects as they act, whereas the methods for LIs and LIDs
1716 # atomically return an object that describes only what changed (in LIs and LIDs
1717 # themselves or in the objects to which to LIs and LIDs belong).
1719 # The methods for LIs and LIDs work the way they do to faciliate the UI's
1720 # maintaining correct information about the state of these things when a user
1721 # wants to receive or unreceive these objects without refreshing their whole
1722 # display. The UI feature for receiving and un-receiving a whole PO just
1723 # refreshes the whole display, so this absence of parallelism in the UI is also
1724 # relected in this module.
1726 # This could be neatened in the future by making POs receive and unreceive in
1727 # the same way the LIs and LIDs do.
1729 __PACKAGE__->register_method(
1730 method => 'receive_lineitem_detail_api',
1731 api_name => 'open-ils.acq.lineitem_detail.receive',
1733 desc => 'Mark a lineitem_detail as received',
1735 {desc => 'Authentication token', type => 'string'},
1736 {desc => 'lineitem detail ID', type => 'number'}
1739 "on success, object describing changes to LID and possibly " .
1740 "to LI and PO; on error, Event"
1745 sub receive_lineitem_detail_api {
1746 my($self, $conn, $auth, $lid_id) = @_;
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);
1753 "flesh" => 2, "flesh_fields" => {
1754 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
1758 my $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1760 return $e->die_event unless $e->allowed(
1761 'RECEIVE_PURCHASE_ORDER', $lid->lineitem->purchase_order->ordering_agency);
1764 my $recvd = receive_lineitem_detail($mgr, $lid_id) or return $e->die_event;
1766 # .. and re-retrieve
1767 $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1769 # Now build result data structure.
1770 my $result = {"lid" => {$lid->id => {"recv_time" => $lid->recv_time}}};
1773 if ($recvd->class_name =~ /::purchase_order/) {
1774 $result->{"po"} = describe_affected_po($e, $recvd);
1776 $lid->lineitem->id => {"state" => $lid->lineitem->state}
1778 } elsif ($recvd->class_name =~ /::lineitem/) {
1779 $result->{"li"} = {$recvd->id => {"state" => $recvd->state}};
1783 describe_affected_po($e, $lid->lineitem->purchase_order);
1789 __PACKAGE__->register_method(
1790 method => 'receive_lineitem_api',
1791 api_name => 'open-ils.acq.lineitem.receive',
1793 desc => 'Mark a lineitem as received',
1795 {desc => 'Authentication token', type => 'string'},
1796 {desc => 'lineitem ID', type => 'number'}
1799 "on success, object describing changes to LI and possibly PO; " .
1805 sub receive_lineitem_api {
1806 my($self, $conn, $auth, $li_id) = @_;
1808 my $e = new_editor(xact=>1, authtoken=>$auth);
1809 return $e->die_event unless $e->checkauth;
1810 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1812 my $li = $e->retrieve_acq_lineitem([
1816 jub => ['purchase_order']
1819 ]) or return $e->die_event;
1821 return $e->die_event unless $e->allowed(
1822 'RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);
1824 my $res = receive_lineitem($mgr, $li_id) or return $e->die_event;
1826 $conn->respond_complete($res);
1827 $mgr->run_post_response_hooks;
1831 __PACKAGE__->register_method(
1832 method => 'rollback_receive_po_api',
1833 api_name => 'open-ils.acq.purchase_order.receive.rollback'
1836 sub rollback_receive_po_api {
1837 my($self, $conn, $auth, $po_id) = @_;
1838 my $e = new_editor(xact => 1, authtoken => $auth);
1839 return $e->die_event unless $e->checkauth;
1840 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1842 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1843 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1845 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1847 for my $li_id (@$li_ids) {
1848 rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
1852 $po->state('on-order');
1853 update_purchase_order($mgr, $po) or return $e->die_event;
1856 return $mgr->respond_complete;
1860 __PACKAGE__->register_method(
1861 method => 'rollback_receive_lineitem_detail_api',
1862 api_name => 'open-ils.acq.lineitem_detail.receive.rollback',
1864 desc => 'Mark a lineitem_detail as Un-received',
1866 {desc => 'Authentication token', type => 'string'},
1867 {desc => 'lineitem detail ID', type => 'number'}
1870 "on success, object describing changes to LID and possibly " .
1871 "to LI and PO; on error, Event"
1876 sub rollback_receive_lineitem_detail_api {
1877 my($self, $conn, $auth, $lid_id) = @_;
1879 my $e = new_editor(xact=>1, authtoken=>$auth);
1880 return $e->die_event unless $e->checkauth;
1881 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1883 my $lid = $e->retrieve_acq_lineitem_detail([
1887 acqlid => ['lineitem'],
1888 jub => ['purchase_order']
1892 my $li = $lid->lineitem;
1893 my $po = $li->purchase_order;
1895 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1899 my $recvd = rollback_receive_lineitem_detail($mgr, $lid_id)
1900 or return $e->die_event;
1903 $result->{"lid"} = {$recvd->id => {"recv_time" => $recvd->recv_time}};
1905 $result->{"lid"} = {$lid->id => {"recv_time" => $lid->recv_time}};
1908 if ($li->state eq "received") {
1909 $li->state("on-order");
1910 $li = update_lineitem($mgr, $li) or return $e->die_event;
1911 $result->{"li"} = {$li->id => {"state" => $li->state}};
1914 if ($po->state eq "received") {
1915 $po->state("on-order");
1916 $po = update_purchase_order($mgr, $po) or return $e->die_event;
1918 $result->{"po"} = describe_affected_po($e, $po);
1920 $e->commit and return $result or return $e->die_event;
1923 __PACKAGE__->register_method(
1924 method => 'rollback_receive_lineitem_api',
1925 api_name => 'open-ils.acq.lineitem.receive.rollback',
1927 desc => 'Mark a lineitem as Un-received',
1929 {desc => 'Authentication token', type => 'string'},
1930 {desc => 'lineitem ID', type => 'number'}
1933 "on success, object describing changes to LI and possibly PO; " .
1939 sub rollback_receive_lineitem_api {
1940 my($self, $conn, $auth, $li_id) = @_;
1942 my $e = new_editor(xact=>1, authtoken=>$auth);
1943 return $e->die_event unless $e->checkauth;
1944 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1946 my $li = $e->retrieve_acq_lineitem([
1948 "flesh" => 1, "flesh_fields" => {"jub" => ["purchase_order"]}
1951 my $po = $li->purchase_order;
1953 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1955 $li = rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
1957 my $result = {"li" => {$li->id => {"state" => $li->state}}};
1958 if ($po->state eq "received") {
1959 $po->state("on-order");
1960 $po = update_purchase_order($mgr, $po) or return $e->die_event;
1962 $result->{"po"} = describe_affected_po($e, $po);
1964 $e->commit and return $result or return $e->die_event;
1968 __PACKAGE__->register_method(
1969 method => 'set_lineitem_price_api',
1970 api_name => 'open-ils.acq.lineitem.price.set',
1972 desc => 'Set lineitem price. If debits already exist, update them as well',
1974 {desc => 'Authentication token', type => 'string'},
1975 {desc => 'lineitem ID', type => 'number'}
1977 return => {desc => 'status blob, Event on error'}
1981 sub set_lineitem_price_api {
1982 my($self, $conn, $auth, $li_id, $price) = @_;
1984 my $e = new_editor(xact=>1, authtoken=>$auth);
1985 return $e->die_event unless $e->checkauth;
1986 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1988 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
1989 return $evt if $evt;
1991 $li->estimated_unit_price($price);
1992 update_lineitem($mgr, $li) or return $e->die_event;
1994 my $lid_ids = $e->search_acq_lineitem_detail(
1995 {lineitem => $li_id, fund_debit => {'!=' => undef}},
1999 for my $lid_id (@$lid_ids) {
2001 my $lid = $e->retrieve_acq_lineitem_detail([
2003 flesh => 1, flesh_fields => {acqlid => ['fund', 'fund_debit']}}
2006 $lid->fund_debit->amount($price);
2007 $e->update_acq_fund_debit($lid->fund_debit) or return $e->die_event;
2013 return $mgr->respond_complete;
2017 __PACKAGE__->register_method(
2018 method => 'clone_picklist_api',
2019 api_name => 'open-ils.acq.picklist.clone',
2021 desc => 'Clones a picklist, including lineitem and lineitem details',
2023 {desc => 'Authentication token', type => 'string'},
2024 {desc => 'Picklist ID', type => 'number'},
2025 {desc => 'New Picklist Name', type => 'string'}
2027 return => {desc => 'status blob, Event on error'}
2031 sub clone_picklist_api {
2032 my($self, $conn, $auth, $pl_id, $name) = @_;
2034 my $e = new_editor(xact=>1, authtoken=>$auth);
2035 return $e->die_event unless $e->checkauth;
2036 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2038 my $old_pl = $e->retrieve_acq_picklist($pl_id);
2039 my $new_pl = create_picklist($mgr, %{$old_pl->to_bare_hash}, name => $name) or return $e->die_event;
2041 my $li_ids = $e->search_acq_lineitem({picklist => $pl_id}, {idlist => 1});
2043 for my $li_id (@$li_ids) {
2045 # copy the lineitems
2046 my $li = $e->retrieve_acq_lineitem($li_id);
2047 my $new_li = create_lineitem($mgr, %{$li->to_bare_hash}, picklist => $new_pl->id) or return $e->die_event;
2049 my $lid_ids = $e->search_acq_lineitem_detail({lineitem => $li_id}, {idlist => 1});
2050 for my $lid_id (@$lid_ids) {
2052 # copy the lineitem details
2053 my $lid = $e->retrieve_acq_lineitem_detail($lid_id);
2054 create_lineitem_detail($mgr, %{$lid->to_bare_hash}, lineitem => $new_li->id) or return $e->die_event;
2061 return $mgr->respond_complete;
2065 __PACKAGE__->register_method(
2066 method => 'merge_picklist_api',
2067 api_name => 'open-ils.acq.picklist.merge',
2069 desc => 'Merges 2 or more picklists into a single list',
2071 {desc => 'Authentication token', type => 'string'},
2072 {desc => 'Lead Picklist ID', type => 'number'},
2073 {desc => 'List of subordinate picklist IDs', type => 'array'}
2075 return => {desc => 'status blob, Event on error'}
2079 sub merge_picklist_api {
2080 my($self, $conn, $auth, $lead_pl, $pl_list) = @_;
2082 my $e = new_editor(xact=>1, authtoken=>$auth);
2083 return $e->die_event unless $e->checkauth;
2084 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2086 # XXX perms on each picklist modified
2088 $lead_pl = $e->retrieve_acq_picklist($lead_pl) or return $e->die_event;
2089 # point all of the lineitems at the lead picklist
2090 my $li_ids = $e->search_acq_lineitem({picklist => $pl_list}, {idlist => 1});
2092 for my $li_id (@$li_ids) {
2093 my $li = $e->retrieve_acq_lineitem($li_id);
2094 $li->picklist($lead_pl);
2095 update_lineitem($mgr, $li) or return $e->die_event;
2099 # now delete the subordinate lists
2100 for my $pl_id (@$pl_list) {
2101 my $pl = $e->retrieve_acq_picklist($pl_id);
2102 $e->delete_acq_picklist($pl) or return $e->die_event;
2105 update_picklist($mgr, $lead_pl) or return $e->die_event;
2108 return $mgr->respond_complete;
2112 __PACKAGE__->register_method(
2113 method => 'delete_picklist_api',
2114 api_name => 'open-ils.acq.picklist.delete',
2116 desc => q/Deletes a picklist. It also deletes any lineitems in the "new" state.
2117 Other attached lineitems are detached'/,
2119 {desc => 'Authentication token', type => 'string'},
2120 {desc => 'Picklist ID to delete', type => 'number'}
2122 return => {desc => '1 on success, Event on error'}
2126 sub delete_picklist_api {
2127 my($self, $conn, $auth, $picklist_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);
2131 my $pl = $e->retrieve_acq_picklist($picklist_id) or return $e->die_event;
2132 delete_picklist($mgr, $pl) or return $e->die_event;
2134 return $mgr->respond_complete;
2139 __PACKAGE__->register_method(
2140 method => 'activate_purchase_order',
2141 api_name => 'open-ils.acq.purchase_order.activate.dry_run'
2144 __PACKAGE__->register_method(
2145 method => 'activate_purchase_order',
2146 api_name => 'open-ils.acq.purchase_order.activate',
2148 desc => q/Activates a purchase order. This updates the status of the PO
2149 and Lineitems to 'on-order'. Activated PO's are ready for EDI delivery
2152 {desc => 'Authentication token', type => 'string'},
2153 {desc => 'Purchase ID', type => 'number'}
2155 return => {desc => '1 on success, Event on error'}
2159 sub activate_purchase_order {
2160 my($self, $conn, $auth, $po_id) = @_;
2162 my $dry_run = ($self->api_name =~ /\.dry_run/) ? 1 : 0;
2163 my $e = new_editor(xact=>1, authtoken=>$auth);
2164 return $e->die_event unless $e->checkauth;
2165 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2166 my $die_event = activate_purchase_order_impl($mgr, $po_id, $dry_run);
2167 return $e->die_event if $die_event;
2173 $conn->respond_complete(1);
2174 $mgr->run_post_response_hooks;
2178 sub activate_purchase_order_impl {
2179 my ($mgr, $po_id, $dry_run) = @_;
2180 my $e = $mgr->editor;
2182 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2183 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
2185 $po->state('on-order');
2186 $po->order_date('now');
2187 update_purchase_order($mgr, $po) or return $e->die_event;
2191 purchase_order => $po_id,
2192 '-or' => [{state => 'pending-order'}, {state => 'new'}]
2197 while( my $li_id = $e->search_acq_lineitem($query, {idlist => 1})->[0] ) {
2201 $li = $e->retrieve_acq_lineitem($li_id);
2203 # can't activate a PO w/o assets. Create lineitem assets as necessary
2204 my $data = create_lineitem_assets($mgr, $li_id) or return $e->die_event;
2208 $li->state('on-order');
2209 create_lineitem_debits($mgr, $li, $dry_run) or return $e->die_event;
2210 update_lineitem($mgr, $li) or return $e->die_event;
2211 $mgr->post_process( sub { create_lineitem_status_events($mgr, $li->id, 'aur.ordered'); });
2215 for my $po_item (@{$e->search_acq_po_item({purchase_order => $po_id})}) {
2217 my $debit = create_fund_debit(
2220 debit_type => 'direct_charge', # to match invoicing
2221 origin_amount => $po_item->estimated_cost,
2222 origin_currency_type => $e->retrieve_acq_fund($po_item->fund)->currency_type,
2223 amount => $po_item->estimated_cost,
2224 fund => $po_item->fund
2225 ) or return $e->die_event;
2226 $po_item->fund_debit($debit->id);
2227 $e->update_acq_po_item($po_item) or return $e->die_event;
2231 # tell the world we activated a PO
2232 $U->create_events_for_hook('acqpo.activated', $po, $po->ordering_agency);
2238 __PACKAGE__->register_method(
2239 method => 'split_purchase_order_by_lineitems',
2240 api_name => 'open-ils.acq.purchase_order.split_by_lineitems',
2242 desc => q/Splits a PO into many POs, 1 per lineitem. Only works for
2243 POs a) with more than one lineitems, and b) in the "pending" state./,
2245 {desc => 'Authentication token', type => 'string'},
2246 {desc => 'Purchase order ID', type => 'number'}
2248 return => {desc => 'list of new PO IDs on success, Event on error'}
2252 sub split_purchase_order_by_lineitems {
2253 my ($self, $conn, $auth, $po_id) = @_;
2255 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2256 return $e->die_event unless $e->checkauth;
2258 my $po = $e->retrieve_acq_purchase_order([
2261 "flesh_fields" => {"acqpo" => [qw/lineitems notes/]}
2263 ]) or return $e->die_event;
2265 return $e->die_event
2266 unless $e->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2268 unless ($po->state eq "pending") {
2270 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_LATE");
2273 unless (@{$po->lineitems} > 1) {
2275 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_SHORT");
2278 # To split an existing PO into many, it seems unwise to just delete the
2279 # original PO, so we'll instead detach all of the original POs' lineitems
2280 # but the first, then create new POs for each of the remaining LIs, and
2281 # then attach the LIs to their new POs.
2283 my @po_ids = ($po->id);
2284 my @moving_li = @{$po->lineitems};
2285 shift @moving_li; # discard first LI
2287 foreach my $li (@moving_li) {
2288 my $new_po = $po->clone;
2290 $new_po->clear_name;
2291 $new_po->creator($e->requestor->id);
2292 $new_po->editor($e->requestor->id);
2293 $new_po->owner($e->requestor->id);
2294 $new_po->edit_time("now");
2295 $new_po->create_time("now");
2297 $new_po = $e->create_acq_purchase_order($new_po);
2299 # Clone any notes attached to the old PO and attach to the new one.
2300 foreach my $note (@{$po->notes}) {
2301 my $new_note = $note->clone;
2302 $new_note->clear_id;
2303 $new_note->edit_time("now");
2304 $new_note->purchase_order($new_po->id);
2305 $e->create_acq_po_note($new_note);
2308 $li->edit_time("now");
2309 $li->purchase_order($new_po->id);
2310 $e->update_acq_lineitem($li);
2312 push @po_ids, $new_po->id;
2315 $po->edit_time("now");
2316 $e->update_acq_purchase_order($po);
2318 return \@po_ids if $e->commit;
2319 return $e->die_event;
2323 sub not_cancelable {
2325 (ref $o eq "HASH" and $o->{"textcode"} eq "ACQ_NOT_CANCELABLE");
2328 __PACKAGE__->register_method(
2329 method => "cancel_purchase_order_api",
2330 api_name => "open-ils.acq.purchase_order.cancel",
2332 desc => q/Cancels an on-order purchase order/,
2334 {desc => "Authentication token", type => "string"},
2335 {desc => "PO ID to cancel", type => "number"},
2336 {desc => "Cancel reason ID", type => "number"}
2338 return => {desc => q/Object describing changed POs, LIs and LIDs
2339 on success; Event on error./}
2343 sub cancel_purchase_order_api {
2344 my ($self, $conn, $auth, $po_id, $cancel_reason) = @_;
2346 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2347 return $e->die_event unless $e->checkauth;
2348 my $mgr = new OpenILS::Application::Acq::BatchManager(
2349 "editor" => $e, "conn" => $conn
2352 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2353 return new OpenILS::Event(
2354 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2357 my $result = cancel_purchase_order($mgr, $po_id, $cancel_reason) or
2358 return $e->die_event;
2359 if (not_cancelable($result)) { # event not from CStoreEditor
2362 } elsif ($result == -1) {
2364 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2367 $e->commit or return $e->die_event;
2369 # XXX create purchase order status events?
2371 if ($mgr->{post_commit}) {
2372 foreach my $func (@{$mgr->{post_commit}}) {
2380 sub cancel_purchase_order {
2381 my ($mgr, $po_id, $cancel_reason) = @_;
2383 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id) or return 0;
2385 # XXX is "cancelled" a typo? It's not correct US spelling, anyway.
2386 # Depending on context, this may not warrant an event.
2387 return -1 if $po->state eq "cancelled";
2389 # But this always does.
2390 return new OpenILS::Event(
2391 "ACQ_NOT_CANCELABLE", "note" => "purchase_order $po_id"
2392 ) unless ($po->state eq "on-order" or $po->state eq "pending");
2395 $mgr->editor->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2397 $po->state("cancelled");
2398 $po->cancel_reason($cancel_reason->id);
2400 my $li_ids = $mgr->editor->search_acq_lineitem(
2401 {"purchase_order" => $po_id}, {"idlist" => 1}
2404 my $result = {"li" => {}, "lid" => {}};
2405 foreach my $li_id (@$li_ids) {
2406 my $li_result = cancel_lineitem($mgr, $li_id, $cancel_reason)
2409 next if $li_result == -1; # already canceled:skip.
2410 return $li_result if not_cancelable($li_result); # not cancelable:stop.
2412 # Merge in each LI result (there's only going to be
2413 # one per call to cancel_lineitem).
2414 my ($k, $v) = each %{$li_result->{"li"}};
2415 $result->{"li"}->{$k} = $v;
2417 # Merge in each LID result (there may be many per call to
2419 while (($k, $v) = each %{$li_result->{"lid"}}) {
2420 $result->{"lid"}->{$k} = $v;
2424 # TODO who/what/where/how do we indicate this change for electronic orders?
2425 # TODO return changes to encumbered/spent
2426 # TODO maybe cascade up from smaller object to container object if last
2427 # smaller object in the container has been canceled?
2429 update_purchase_order($mgr, $po) or return 0;
2431 $po_id => {"state" => $po->state, "cancel_reason" => $cancel_reason}
2437 __PACKAGE__->register_method(
2438 method => "cancel_lineitem_api",
2439 api_name => "open-ils.acq.lineitem.cancel",
2441 desc => q/Cancels an on-order lineitem/,
2443 {desc => "Authentication token", type => "string"},
2444 {desc => "Lineitem ID to cancel", type => "number"},
2445 {desc => "Cancel reason ID", type => "number"}
2447 return => {desc => q/Object describing changed LIs and LIDs on success;
2452 __PACKAGE__->register_method(
2453 method => "cancel_lineitem_api",
2454 api_name => "open-ils.acq.lineitem.cancel.batch",
2456 desc => q/Batched version of open-ils.acq.lineitem.cancel/,
2457 return => {desc => q/Object describing changed LIs and LIDs on success;
2462 sub cancel_lineitem_api {
2463 my ($self, $conn, $auth, $li_id, $cancel_reason) = @_;
2465 my $batched = $self->api_name =~ /\.batch/;
2467 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2468 return $e->die_event unless $e->checkauth;
2469 my $mgr = new OpenILS::Application::Acq::BatchManager(
2470 "editor" => $e, "conn" => $conn
2473 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2474 return new OpenILS::Event(
2475 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2478 my ($result, $maybe_event);
2481 $result = {"li" => {}, "lid" => {}};
2482 foreach my $one_li_id (@$li_id) {
2483 my $one = cancel_lineitem($mgr, $one_li_id, $cancel_reason) or
2484 return $e->die_event;
2485 if (not_cancelable($one)) {
2486 $maybe_event = $one;
2487 } elsif ($result == -1) {
2488 $maybe_event = new OpenILS::Event("ACQ_ALREADY_CANCELED");
2492 while (($k, $v) = each %{$one->{"li"}}) {
2493 $result->{"li"}->{$k} = $v;
2496 if ($one->{"lid"}) {
2497 while (($k, $v) = each %{$one->{"lid"}}) {
2498 $result->{"lid"}->{$k} = $v;
2504 $result = cancel_lineitem($mgr, $li_id, $cancel_reason) or
2505 return $e->die_event;
2507 if (not_cancelable($result)) {
2510 } elsif ($result == -1) {
2512 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2516 if ($batched and not scalar keys %{$result->{"li"}}) {
2518 return $maybe_event;
2520 $e->commit or return $e->die_event;
2521 # create_lineitem_status_events should handle array li_id ok
2522 create_lineitem_status_events($mgr, $li_id, "aur.cancelled");
2524 if ($mgr->{post_commit}) {
2525 foreach my $func (@{$mgr->{post_commit}}) {
2534 sub cancel_lineitem {
2535 my ($mgr, $li_id, $cancel_reason) = @_;
2536 my $li = $mgr->editor->retrieve_acq_lineitem([
2537 $li_id, {flesh => 1, flesh_fields => {jub => ['purchase_order']}}
2540 return 0 unless $mgr->editor->allowed(
2541 "CREATE_PURCHASE_ORDER", $li->purchase_order->ordering_agency
2544 # Depending on context, this may not warrant an event.
2545 return -1 if $li->state eq "cancelled";
2547 # But this always does.
2548 return new OpenILS::Event(
2549 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id"
2551 (! $li->purchase_order) or (
2552 $li->purchase_order and (
2553 $li->state eq "on-order" or $li->state eq "pending-order"
2558 $li->state("cancelled");
2559 $li->cancel_reason($cancel_reason->id);
2561 my $lids = $mgr->editor->search_acq_lineitem_detail([{
2562 "lineitem" => $li_id
2565 flesh_fields => { acqlid => ['eg_copy_id'] }
2568 my $result = {"lid" => {}};
2570 foreach my $lid (@$lids) {
2571 my $lid_result = cancel_lineitem_detail($mgr, $lid->id, $cancel_reason)
2574 # gathering any real copies for deletion
2575 if ($lid->eg_copy_id) {
2576 $lid->eg_copy_id->isdeleted('t');
2577 push @$copies, $lid->eg_copy_id;
2580 next if $lid_result == -1; # already canceled: just skip it.
2581 return $lid_result if not_cancelable($lid_result); # not cxlable: stop.
2583 # Merge in each LID result (there's only going to be one per call to
2584 # cancel_lineitem_detail).
2585 my ($k, $v) = each %{$lid_result->{"lid"}};
2586 $result->{"lid"}->{$k} = $v;
2589 # Attempt to delete the gathered copies (this will also handle volume deletion and bib deletion)
2590 # Delete empty bibs according org unit setting
2591 my $force_delete_empty_bib = $U->ou_ancestor_setting_value(
2592 $mgr->editor->requestor->ws_ou, 'cat.bib.delete_on_no_copy_via_acq_lineitem_cancel', $mgr->editor);
2593 if (scalar(@$copies)>0) {
2595 my $delete_stats = undef;
2596 my $retarget_holds = [];
2597 my $cat_evt = OpenILS::Application::Cat::AssetCommon->update_fleshed_copies(
2598 $mgr->editor, $override, undef, $copies, $delete_stats, $retarget_holds,$force_delete_empty_bib);
2601 $logger->info("fleshed copy update failed with event: ".OpenSRF::Utils::JSON->perl2JSON($cat_evt));
2602 return new OpenILS::Event(
2603 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id", "payload" => $cat_evt
2607 # We can't do the following and stay within the same transaction, but that's okay, the hold targeter will pick these up later.
2608 #my $ses = OpenSRF::AppSession->create('open-ils.circ');
2609 #$ses->request('open-ils.circ.hold.reset.batch', $auth, $retarget_holds);
2612 # if we have a bib, check to see whether it has been deleted. if so, cancel any active holds targeting that bib
2613 if ($li->eg_bib_id) {
2614 my $bib = $mgr->editor->retrieve_biblio_record_entry($li->eg_bib_id) or return new OpenILS::Event(
2615 "ACQ_NOT_CANCELABLE", "note" => "Could not retrieve bib " . $li->eg_bib_id . " for lineitem $li_id"
2617 if ($U->is_true($bib->deleted)) {
2618 my $holds = $mgr->editor->search_action_hold_request(
2619 { cancel_time => undef,
2620 fulfillment_time => undef,
2621 target => $li->eg_bib_id
2625 my %cached_usr_home_ou = ();
2627 for my $hold (@$holds) {
2629 $logger->info("Cancelling hold ".$hold->id.
2630 " due to acq lineitem cancellation.");
2632 $hold->cancel_time('now');
2633 $hold->cancel_cause(5); # 'Staff forced'--we may want a new hold cancel cause reason for this
2634 $hold->cancel_note('Corresponding Acquistion Lineitem/Purchase Order was cancelled.');
2635 unless($mgr->editor->update_action_hold_request($hold)) {
2636 my $evt = $mgr->editor->event;
2637 $logger->error("Error updating hold ". $evt->textcode .":". $evt->desc .":". $evt->stacktrace);
2638 return new OpenILS::Event(
2639 "ACQ_NOT_CANCELABLE", "note" => "Could not cancel hold " . $hold->id . " for lineitem $li_id", "payload" => $evt
2642 if (! defined $mgr->{post_commit}) { # we need a mechanism for creating trigger events, but only if the transaction gets committed
2643 $mgr->{post_commit} = [];
2645 push @{ $mgr->{post_commit} }, sub {
2646 my $home_ou = $cached_usr_home_ou{$hold->usr};
2648 my $user = $mgr->editor->retrieve_actor_user($hold->usr); # FIXME: how do we want to handle failures here?
2649 $home_ou = $user->home_ou;
2650 $cached_usr_home_ou{$hold->usr} = $home_ou;
2652 $U->create_events_for_hook('hold_request.cancel.cancelled_order', $hold, $home_ou);
2658 update_lineitem($mgr, $li) or return 0;
2661 "state" => $li->state,
2662 "cancel_reason" => $cancel_reason
2669 __PACKAGE__->register_method(
2670 method => "cancel_lineitem_detail_api",
2671 api_name => "open-ils.acq.lineitem_detail.cancel",
2673 desc => q/Cancels an on-order lineitem detail/,
2675 {desc => "Authentication token", type => "string"},
2676 {desc => "Lineitem detail ID to cancel", type => "number"},
2677 {desc => "Cancel reason ID", type => "number"}
2679 return => {desc => q/Object describing changed LIDs on success;
2684 sub cancel_lineitem_detail_api {
2685 my ($self, $conn, $auth, $lid_id, $cancel_reason) = @_;
2687 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2688 return $e->die_event unless $e->checkauth;
2689 my $mgr = new OpenILS::Application::Acq::BatchManager(
2690 "editor" => $e, "conn" => $conn
2693 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2694 return new OpenILS::Event(
2695 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2698 my $result = cancel_lineitem_detail($mgr, $lid_id, $cancel_reason) or
2699 return $e->die_event;
2701 if (not_cancelable($result)) {
2704 } elsif ($result == -1) {
2706 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2709 $e->commit or return $e->die_event;
2711 # XXX create lineitem detail status events?
2715 sub cancel_lineitem_detail {
2716 my ($mgr, $lid_id, $cancel_reason) = @_;
2717 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
2721 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
2726 # Depending on context, this may not warrant an event.
2727 return -1 if $lid->cancel_reason;
2729 # But this always does.
2730 return new OpenILS::Event(
2731 "ACQ_NOT_CANCELABLE", "note" => "lineitem_detail $lid_id"
2733 (! $lid->lineitem->purchase_order) or
2735 (not $lid->recv_time) and
2737 $lid->lineitem->purchase_order and (
2738 $lid->lineitem->state eq "on-order" or
2739 $lid->lineitem->state eq "pending-order"
2744 return 0 unless $mgr->editor->allowed(
2745 "CREATE_PURCHASE_ORDER",
2746 $lid->lineitem->purchase_order->ordering_agency
2747 ) or (! $lid->lineitem->purchase_order);
2749 $lid->cancel_reason($cancel_reason->id);
2751 unless($U->is_true($cancel_reason->keep_debits)) {
2752 my $debit_id = $lid->fund_debit;
2753 $lid->clear_fund_debit;
2756 # item is cancelled. Remove the fund debit.
2757 my $debit = $mgr->editor->retrieve_acq_fund_debit($debit_id);
2758 if (!$U->is_true($debit->encumbrance)) {
2759 $mgr->editor->rollback;
2760 return OpenILS::Event->new('ACQ_NOT_CANCELABLE',
2761 note => "Debit is marked as paid: $debit_id");
2763 $mgr->editor->delete_acq_fund_debit($debit) or return $mgr->editor->die_event;
2767 # XXX LIDs don't have either an editor or a edit_time field. Should we
2768 # update these on the LI when we alter an LID?
2769 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
2771 return {"lid" => {$lid_id => {"cancel_reason" => $cancel_reason}}};
2775 __PACKAGE__->register_method(
2776 method => 'user_requests',
2777 api_name => 'open-ils.acq.user_request.retrieve.by_user_id',
2780 desc => 'Retrieve fleshed user requests and related data for a given user.',
2782 { desc => 'Authentication token', type => 'string' },
2783 { desc => 'User ID of the owner, or array of IDs', },
2784 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
2789 desc => 'Fleshed user requests and related data',
2795 __PACKAGE__->register_method(
2796 method => 'user_requests',
2797 api_name => 'open-ils.acq.user_request.retrieve.by_home_ou',
2800 desc => 'Retrieve fleshed user requests and related data for a given org unit or units.',
2802 { desc => 'Authentication token', type => 'string' },
2803 { desc => 'Org unit ID, or array of IDs', },
2804 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
2809 desc => 'Fleshed user requests and related data',
2816 my($self, $conn, $auth, $search_value, $options) = @_;
2817 my $e = new_editor(authtoken => $auth);
2818 return $e->event unless $e->checkauth;
2819 my $rid = $e->requestor->id;
2823 "select"=>{"aur"=>["id"],"au"=>["home_ou", {column => 'id', alias => 'usr_id'} ]},
2824 "from"=>{ "aur" => { "au" => {}, "jub" => { "type" => "left" } } },
2828 {"id"=>undef}, # this with the left-join pulls in requests without lineitems
2829 {"state"=>["new","on-order","pending-order"]} # FIXME - probably needs softcoding
2833 "order_by"=>[{"class"=>"aur", "field"=>"request_date", "direction"=>"desc"}]
2836 foreach (qw/ order_by limit offset /) {
2837 $query->{$_} = $options->{$_} if defined $options->{$_};
2839 if (defined $options->{'state'}) {
2840 $query->{'where'}->{'+jub'}->{'-or'}->[1]->{'state'} = $options->{'state'};
2843 if ($self->api_name =~ /by_user_id/) {
2844 $query->{'where'}->{'usr'} = $search_value;
2846 $query->{'where'}->{'+au'} = { 'home_ou' => $search_value };
2849 my $pertinent_ids = $e->json_query($query);
2852 for my $id_blob (@$pertinent_ids) {
2853 if ($rid != $id_blob->{usr_id}) {
2854 if (!defined $perm_test{ $id_blob->{home_ou} }) {
2855 $perm_test{ $id_blob->{home_ou} } = $e->allowed( ['user_request.view'], $id_blob->{home_ou} );
2857 if (!$perm_test{ $id_blob->{home_ou} }) {
2861 my $aur_obj = $e->retrieve_acq_user_request([
2863 {flesh => 1, flesh_fields => { "aur" => [ 'lineitem' ] } }
2865 if (! $aur_obj) { next; }
2867 if ($aur_obj->lineitem()) {
2868 $aur_obj->lineitem()->clear_marc();
2870 $conn->respond($aur_obj);
2876 __PACKAGE__->register_method (
2877 method => 'update_user_request',
2878 api_name => 'open-ils.acq.user_request.cancel.batch',
2881 desc => 'If given a cancel reason, will update the request with that reason, otherwise, this will delete the request altogether. The ' .
2882 'intention is for staff interfaces or processes to provide cancel reasons, and for patron interfaces to just delete the requests.' ,
2884 { desc => 'Authentication token', type => 'string' },
2885 { desc => 'ID or array of IDs for the user requests to cancel' },
2886 { desc => 'Cancel Reason ID (optional)', type => 'string' }
2889 desc => 'progress object, event on error',
2893 __PACKAGE__->register_method (
2894 method => 'update_user_request',
2895 api_name => 'open-ils.acq.user_request.set_no_hold.batch',
2898 desc => 'Remove the hold from a user request or set of requests',
2900 { desc => 'Authentication token', type => 'string' },
2901 { desc => 'ID or array of IDs for the user requests to modify' }
2904 desc => 'progress object, event on error',
2909 sub update_user_request {
2910 my($self, $conn, $auth, $aur_ids, $cancel_reason) = @_;
2911 my $e = new_editor(xact => 1, authtoken => $auth);
2912 return $e->die_event unless $e->checkauth;
2913 my $rid = $e->requestor->id;
2917 for my $id (@$aur_ids) {
2919 my $aur_obj = $e->retrieve_acq_user_request([
2922 flesh_fields => { "aur" => ['lineitem', 'usr'] }
2924 ]) or return $e->die_event;
2926 my $context_org = $aur_obj->usr()->home_ou();
2927 $aur_obj->usr( $aur_obj->usr()->id() );
2929 if ($rid != $aur_obj->usr) {
2930 if (!defined $perm_test{ $context_org }) {
2931 $perm_test{ $context_org } = $e->allowed( ['user_request.update'], $context_org );
2933 if (!$perm_test{ $context_org }) {
2938 if($self->api_name =~ /set_no_hold/) {
2939 if ($U->is_true($aur_obj->hold)) {
2941 $e->update_acq_user_request($aur_obj) or return $e->die_event;
2945 if($self->api_name =~ /cancel/) {
2946 if ( $cancel_reason ) {
2947 $aur_obj->cancel_reason( $cancel_reason );
2948 $e->update_acq_user_request($aur_obj) or return $e->die_event;
2949 create_user_request_events( $e, [ $aur_obj ], 'aur.rejected' );
2951 $e->delete_acq_user_request($aur_obj);
2955 $conn->respond({maximum => scalar(@$aur_ids), progress => $x++});
2959 return {complete => 1};
2962 __PACKAGE__->register_method (
2963 method => 'new_user_request',
2964 api_name => 'open-ils.acq.user_request.create',
2966 desc => 'Create a new user request object in the DB',
2968 { desc => 'Authentication token', type => 'string' },
2969 { desc => 'User request data hash. Hash keys match the fields for the "aur" object', type => 'object' }
2972 desc => 'The created user request object, or event on error'
2977 sub new_user_request {
2978 my($self, $conn, $auth, $form_data) = @_;
2979 my $e = new_editor(xact => 1, authtoken => $auth);
2980 return $e->die_event unless $e->checkauth;
2981 my $rid = $e->requestor->id;
2982 my $target_user_fleshed;
2983 if (! defined $$form_data{'usr'}) {
2984 $$form_data{'usr'} = $rid;
2986 if ($$form_data{'usr'} != $rid) {
2987 # See if the requestor can place the request on behalf of a different user.
2988 $target_user_fleshed = $e->retrieve_actor_user($$form_data{'usr'}) or return $e->die_event;
2989 $e->allowed('user_request.create', $target_user_fleshed->home_ou) or return $e->die_event;
2991 $target_user_fleshed = $e->requestor;
2992 $e->allowed('CREATE_PURCHASE_REQUEST') or return $e->die_event;
2994 if (! defined $$form_data{'pickup_lib'}) {
2995 if ($target_user_fleshed->ws_ou) {
2996 $$form_data{'pickup_lib'} = $target_user_fleshed->ws_ou;
2998 $$form_data{'pickup_lib'} = $target_user_fleshed->home_ou;
3001 if (! defined $$form_data{'request_type'}) {
3002 $$form_data{'request_type'} = 1; # Books
3004 my $aur_obj = new Fieldmapper::acq::user_request;
3006 $aur_obj->usr( $$form_data{'usr'} );
3007 $aur_obj->request_date( 'now' );
3008 for my $field ( keys %$form_data ) {
3009 if (defined $$form_data{$field} and $field !~ /^(id|lineitem|eg_bib|request_date|cancel_reason)$/) {
3010 $aur_obj->$field( $$form_data{$field} );
3014 $aur_obj = $e->create_acq_user_request($aur_obj) or return $e->die_event;
3016 $e->commit and create_user_request_events( $e, [ $aur_obj ], 'aur.created' );
3021 sub create_user_request_events {
3022 my($e, $user_reqs, $hook) = @_;
3024 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
3027 my %cached_usr_home_ou = ();
3028 for my $user_req (@$user_reqs) {
3029 my $home_ou = $cached_usr_home_ou{$user_req->usr};
3031 my $user = $e->retrieve_actor_user($user_req->usr) or return $e->die_event;
3032 $home_ou = $user->home_ou;
3033 $cached_usr_home_ou{$user_req->usr} = $home_ou;
3035 my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $home_ou);
3044 __PACKAGE__->register_method(
3045 method => "po_note_CUD_batch",
3046 api_name => "open-ils.acq.po_note.cud.batch",
3049 desc => q/Manage purchase order notes/,
3051 {desc => "Authentication token", type => "string"},
3052 {desc => "List of po_notes to manage", type => "array"},
3054 return => {desc => "Stream of successfully managed objects"}
3058 sub po_note_CUD_batch {
3059 my ($self, $conn, $auth, $notes) = @_;
3061 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3062 return $e->die_event unless $e->checkauth;
3065 my $total = @$notes;
3068 foreach my $note (@$notes) {
3070 $note->editor($e->requestor->id);
3071 $note->edit_time("now");
3074 $note->creator($e->requestor->id);
3075 $note = $e->create_acq_po_note($note) or return $e->die_event;
3076 } elsif ($note->isdeleted) {
3077 $e->delete_acq_po_note($note) or return $e->die_event;
3078 } elsif ($note->ischanged) {
3079 $e->update_acq_po_note($note) or return $e->die_event;
3082 unless ($note->isdeleted) {
3083 $note = $e->retrieve_acq_po_note($note->id) or
3084 return $e->die_event;
3088 {"maximum" => $total, "progress" => ++$count, "note" => $note}
3092 $e->commit and $conn->respond_complete or return $e->die_event;
3096 # retrieves a lineitem, fleshes its PO and PL, checks perms
3097 sub fetch_and_check_li {
3100 my $perm_mode = shift || 'read';
3102 my $li = $e->retrieve_acq_lineitem([
3105 flesh_fields => {jub => ['purchase_order', 'picklist']}
3107 ]) or return $e->die_event;
3109 if(my $po = $li->purchase_order) {
3110 my $perms = ($perm_mode eq 'read') ? 'VIEW_PURCHASE_ORDER' : 'CREATE_PURCHASE_ORDER';
3111 return ($li, $e->die_event) unless $e->allowed($perms, $po->ordering_agency);
3113 } elsif(my $pl = $li->picklist) {
3114 my $perms = ($perm_mode eq 'read') ? 'VIEW_PICKLIST' : 'CREATE_PICKLIST';
3115 return ($li, $e->die_event) unless $e->allowed($perms, $pl->org_unit);
3122 __PACKAGE__->register_method(
3123 method => "clone_distrib_form",
3124 api_name => "open-ils.acq.distribution_formula.clone",
3127 desc => q/Clone a distribution formula/,
3129 {desc => "Authentication token", type => "string"},
3130 {desc => "Original formula ID", type => 'integer'},
3131 {desc => "Name of new formula", type => 'string'},
3133 return => {desc => "ID of newly created formula"}
3137 sub clone_distrib_form {
3138 my($self, $client, $auth, $form_id, $new_name) = @_;
3140 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3141 return $e->die_event unless $e->checkauth;
3143 my $old_form = $e->retrieve_acq_distribution_formula($form_id) or return $e->die_event;
3144 return $e->die_event unless $e->allowed('ADMIN_ACQ_DISTRIB_FORMULA', $old_form->owner);
3146 my $new_form = Fieldmapper::acq::distribution_formula->new;
3148 $new_form->owner($old_form->owner);
3149 $new_form->name($new_name);
3150 $e->create_acq_distribution_formula($new_form) or return $e->die_event;
3152 my $entries = $e->search_acq_distribution_formula_entry({formula => $form_id});
3153 for my $entry (@$entries) {
3154 my $new_entry = Fieldmapper::acq::distribution_formula_entry->new;
3155 $new_entry->$_($entry->$_()) for $entry->real_fields;
3156 $new_entry->formula($new_form->id);
3157 $new_entry->clear_id;
3158 $e->create_acq_distribution_formula_entry($new_entry) or return $e->die_event;
3162 return $new_form->id;