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 if(!$lid->circ_modifier and my $mod = get_default_circ_modifier($mgr, $lid->owning_lib)) {
486 $lid->circ_modifier($mod);
489 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
493 sub get_default_circ_modifier {
495 my $mod = $mgr->cache($org, 'def_circ_mod');
497 $mod = $U->ou_ancestor_setting_value($org, 'acq.default_circ_modifier');
498 return $mgr->cache($org, 'def_circ_mod', $mod) if $mod;
502 sub delete_lineitem_detail {
504 $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid) unless ref $lid;
505 return $mgr->editor->delete_acq_lineitem_detail($lid);
509 sub receive_lineitem_detail {
510 my($mgr, $lid_id, $skip_complete_check) = @_;
511 my $e = $mgr->editor;
513 my $lid = $e->retrieve_acq_lineitem_detail([
517 acqlid => ['fund_debit']
522 return 1 if $lid->recv_time;
524 $lid->recv_time('now');
525 $e->update_acq_lineitem_detail($lid) or return 0;
527 my $copy = $e->retrieve_asset_copy($lid->eg_copy_id) or return 0;
528 $copy->status(OILS_COPY_STATUS_IN_PROCESS);
529 $copy->edit_date('now');
530 $copy->editor($e->requestor->id);
531 $e->update_asset_copy($copy) or return 0;
535 return 1 if $skip_complete_check;
537 my $li = check_lineitem_received($mgr, $lid->lineitem) or return 0;
538 return 1 if $li == 1; # li not received
540 return check_purchase_order_received($mgr, $li->purchase_order) or return 0;
544 sub rollback_receive_lineitem_detail {
545 my($mgr, $lid_id) = @_;
546 my $e = $mgr->editor;
548 my $lid = $e->retrieve_acq_lineitem_detail([
552 acqlid => ['fund_debit']
557 return 1 unless $lid->recv_time;
559 $lid->clear_recv_time;
560 $e->update_acq_lineitem_detail($lid) or return 0;
562 my $copy = $e->retrieve_asset_copy($lid->eg_copy_id) or return 0;
563 $copy->status(OILS_COPY_STATUS_ON_ORDER);
564 $copy->edit_date('now');
565 $copy->editor($e->requestor->id);
566 $e->update_asset_copy($copy) or return 0;
572 # ----------------------------------------------------------------------------
574 # ----------------------------------------------------------------------------
575 sub set_lineitem_attr {
576 my($mgr, %args) = @_;
577 my $attr_type = $args{attr_type};
579 # first, see if it's already set. May just need to overwrite it
580 my $attr = $mgr->editor->search_acq_lineitem_attr({
581 lineitem => $args{lineitem},
582 attr_type => $args{attr_type},
583 attr_name => $args{attr_name}
587 $attr->attr_value($args{attr_value});
588 return $attr if $mgr->editor->update_acq_lineitem_attr($attr);
593 $attr = Fieldmapper::acq::lineitem_attr->new;
594 $attr->$_($args{$_}) for keys %args;
596 unless($attr->definition) {
597 my $find = "search_acq_$attr_type";
598 my $attr_def_id = $mgr->editor->$find({code => $attr->attr_name}, {idlist=>1})->[0] or return 0;
599 $attr->definition($attr_def_id);
601 return $mgr->editor->create_acq_lineitem_attr($attr);
605 # ----------------------------------------------------------------------------
607 # ----------------------------------------------------------------------------
608 sub create_lineitem_debits {
609 my ($mgr, $li, $dry_run) = @_;
611 unless($li->estimated_unit_price) {
612 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_PRICE', payload => $li->id));
613 $mgr->editor->rollback;
617 unless($li->provider) {
618 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_PROVIDER', payload => $li->id));
619 $mgr->editor->rollback;
623 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
624 {lineitem => $li->id},
628 for my $lid_id (@$lid_ids) {
630 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
633 flesh_fields => {acqlid => ['fund']}
637 create_lineitem_detail_debit($mgr, $li, $lid, $dry_run) or return 0;
646 sub create_lineitem_detail_debit {
647 my ($mgr, $li, $lid, $dry_run, $no_translate) = @_;
649 # don't create the debit if one already exists
650 return $mgr->editor->retrieve_acq_fund_debit($lid->fund_debit) if $lid->fund_debit;
652 my $li_id = ref($li) ? $li->id : $li;
654 unless(ref $li and ref $li->provider) {
655 $li = $mgr->editor->retrieve_acq_lineitem([
658 flesh_fields => {jub => ['provider']},
663 unless(ref $lid and ref $lid->fund) {
664 $lid = $mgr->editor->retrieve_acq_lineitem_detail([
667 flesh_fields => {acqlid => ['fund']}
672 my $amount = $li->estimated_unit_price;
673 if($li->provider->currency_type ne $lid->fund->currency_type and !$no_translate) {
675 # At Fund debit creation time, translate into the currency of the fund
676 # TODO: org setting to disable automatic currency conversion at debit create time?
678 $amount = $mgr->editor->json_query({
680 'acq.exchange_ratio',
681 $li->provider->currency_type, # source currency
682 $lid->fund->currency_type, # destination currency
683 $li->estimated_unit_price # source amount
688 my $debit = create_fund_debit(
691 fund => $lid->fund->id,
692 origin_amount => $li->estimated_unit_price,
693 origin_currency_type => $li->provider->currency_type,
697 $lid->fund_debit($debit->id);
698 $lid->fund($lid->fund->id);
699 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
704 __PACKAGE__->register_method(
705 "method" => "fund_exceeds_balance_percent_api",
706 "api_name" => "open-ils.acq.fund.check_balance_percentages",
708 "desc" => q/Determine whether a given fund exceeds its defined
709 "balance stop and warning percentages"/,
711 {"desc" => "Authentication token", "type" => "string"},
712 {"desc" => "Fund ID", "type" => "number"},
713 {"desc" => "Theoretical debit amount (optional)",
716 "return" => {"desc" => q/An array of two values, for stop and warning,
717 in that order: 1 if fund exceeds that balance percentage, else 0/}
721 sub fund_exceeds_balance_percent_api {
722 my ($self, $conn, $auth, $fund_id, $debit_amount) = @_;
726 my $e = new_editor("authtoken" => $auth);
727 return $e->die_event unless $e->checkauth;
729 my $fund = $e->retrieve_acq_fund($fund_id) or return $e->die_event;
730 return $e->die_event unless $e->allowed("VIEW_FUND", $fund->org);
733 fund_exceeds_balance_percent($fund, $debit_amount, $e, "stop"),
734 fund_exceeds_balance_percent($fund, $debit_amount, $e, "warning")
741 sub fund_exceeds_balance_percent {
742 my ($fund, $debit_amount, $e, $which) = @_;
744 my ($method_name, $event_name) = @{{
746 "balance_warning_percent", "ACQ_FUND_EXCEEDS_WARN_PERCENT"
749 "balance_stop_percent", "ACQ_FUND_EXCEEDS_STOP_PERCENT"
753 if ($fund->$method_name) {
755 $e->search_acq_fund_combined_balance({"fund" => $fund->id})->[0];
757 $e->search_acq_fund_allocation_total({"fund" => $fund->id})->[0];
759 $balance = ($balance) ? $balance->amount : 0;
760 $allocations = ($allocations) ? $allocations->amount : 0;
763 $allocations == 0 || # if no allocations were ever made, assume we have hit the stop percent
764 ((($balance - $debit_amount) / $allocations) * 100) <
767 $logger->info("fund would hit a limit: " . $fund->id . ", $balance, $debit_amount, $allocations, $method_name");
772 "fund" => $fund, "debit_amount" => $debit_amount
782 # ----------------------------------------------------------------------------
784 # ----------------------------------------------------------------------------
785 sub create_fund_debit {
786 my($mgr, $dry_run, %args) = @_;
788 # Verify the fund is not being spent beyond the hard stop amount
789 my $fund = $mgr->editor->retrieve_acq_fund($args{fund}) or return 0;
792 fund_exceeds_balance_percent(
793 $fund, $args{"amount"}, $mgr->editor, "stop"
796 $dry_run and fund_exceeds_balance_percent(
797 $fund, $args{"amount"}, $mgr->editor, "warning"
800 my $debit = Fieldmapper::acq::fund_debit->new;
801 $debit->debit_type('purchase');
802 $debit->encumbrance('t');
803 $debit->$_($args{$_}) for keys %args;
805 $mgr->add_debit($debit->amount);
806 return $mgr->editor->create_acq_fund_debit($debit);
810 # ----------------------------------------------------------------------------
812 # ----------------------------------------------------------------------------
813 sub create_picklist {
814 my($mgr, %args) = @_;
815 my $picklist = Fieldmapper::acq::picklist->new;
816 $picklist->creator($mgr->editor->requestor->id);
817 $picklist->owner($picklist->creator);
818 $picklist->editor($picklist->creator);
819 $picklist->create_time('now');
820 $picklist->edit_time('now');
821 $picklist->org_unit($mgr->editor->requestor->ws_ou);
822 $picklist->owner($mgr->editor->requestor->id);
823 $picklist->$_($args{$_}) for keys %args;
825 $mgr->picklist($picklist);
826 return $mgr->editor->create_acq_picklist($picklist);
829 sub update_picklist {
830 my($mgr, $picklist) = @_;
831 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
832 $picklist->edit_time('now');
833 $picklist->editor($mgr->editor->requestor->id);
834 $mgr->picklist($picklist);
835 return $picklist if $mgr->editor->update_acq_picklist($picklist);
839 sub delete_picklist {
840 my($mgr, $picklist) = @_;
841 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
843 # delete all 'new' lineitems
844 my $li_ids = $mgr->editor->search_acq_lineitem({picklist => $picklist->id, state => 'new'}, {idlist => 1});
845 for my $li_id (@$li_ids) {
846 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
847 return 0 unless delete_lineitem($mgr, $li);
851 # detach all non-'new' lineitems
852 $li_ids = $mgr->editor->search_acq_lineitem({picklist => $picklist->id, state => {'!=' => 'new'}}, {idlist => 1});
853 for my $li_id (@$li_ids) {
854 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
856 return 0 unless update_lineitem($mgr, $li);
860 # remove any picklist-specific object perms
861 my $ops = $mgr->editor->search_permission_usr_object_perm_map({object_type => 'acqpl', object_id => ''.$picklist->id});
863 return 0 unless $mgr->editor->delete_usr_object_perm_map($op);
866 return $mgr->editor->delete_acq_picklist($picklist);
869 # ----------------------------------------------------------------------------
871 # ----------------------------------------------------------------------------
872 sub update_purchase_order {
874 $po = $mgr->editor->retrieve_acq_purchase_order($po) unless ref $po;
875 $po->editor($mgr->editor->requestor->id);
876 $po->edit_time('now');
877 $mgr->purchase_order($po);
878 return $mgr->editor->retrieve_acq_purchase_order($mgr->editor->data)
879 if $mgr->editor->update_acq_purchase_order($po);
883 sub create_purchase_order {
884 my($mgr, %args) = @_;
886 # verify the chosen provider is still active
887 my $provider = $mgr->editor->retrieve_acq_provider($args{provider}) or return 0;
888 unless($U->is_true($provider->active)) {
889 $logger->error("provider is not active. cannot create PO");
890 $mgr->editor->event(OpenILS::Event->new('ACQ_PROVIDER_INACTIVE'));
894 my $po = Fieldmapper::acq::purchase_order->new;
895 $po->creator($mgr->editor->requestor->id);
896 $po->editor($mgr->editor->requestor->id);
897 $po->owner($mgr->editor->requestor->id);
898 $po->edit_time('now');
899 $po->create_time('now');
900 $po->state('pending');
901 $po->ordering_agency($mgr->editor->requestor->ws_ou);
902 $po->$_($args{$_}) for keys %args;
904 $mgr->purchase_order($po);
905 return $mgr->editor->create_acq_purchase_order($po);
908 # ----------------------------------------------------------------------------
909 # if all of the lineitems for this PO are received,
910 # mark the PO as received
911 # ----------------------------------------------------------------------------
912 sub check_purchase_order_received {
913 my($mgr, $po_id) = @_;
915 my $non_recv_li = $mgr->editor->search_acq_lineitem(
916 { purchase_order => $po_id,
917 state => {'!=' => 'received'}
920 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id);
921 return $po if @$non_recv_li;
923 $po->state('received');
924 return update_purchase_order($mgr, $po);
928 # ----------------------------------------------------------------------------
929 # Bib, Callnumber, and Copy data
930 # ----------------------------------------------------------------------------
932 sub create_lineitem_assets {
933 my($mgr, $li_id) = @_;
936 my $li = $mgr->editor->retrieve_acq_lineitem([
939 flesh_fields => {jub => ['purchase_order', 'attributes']}
943 # -----------------------------------------------------------------
944 # first, create the bib record if necessary
945 # -----------------------------------------------------------------
947 unless($li->eg_bib_id) {
948 create_bib($mgr, $li) or return 0;
953 # -----------------------------------------------------------------
954 # The lineitem is going live, promote user request holds to real holds
955 # -----------------------------------------------------------------
956 promote_lineitem_holds($mgr, $li) or return 0;
958 my $li_details = $mgr->editor->search_acq_lineitem_detail({lineitem => $li_id}, {idlist=>1});
960 # -----------------------------------------------------------------
961 # for each lineitem_detail, create the volume if necessary, create
962 # a copy, and link them all together.
963 # -----------------------------------------------------------------
965 for my $lid_id (@{$li_details}) {
967 my $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid_id) or return 0;
968 next if $lid->eg_copy_id;
970 # use the same callnumber label for all items within this lineitem
971 $lid->cn_label($first_cn) if $first_cn and not $lid->cn_label;
973 # apply defaults if necessary
974 return 0 unless complete_lineitem_detail($mgr, $lid);
976 $first_cn = $lid->cn_label unless $first_cn;
978 my $org = $lid->owning_lib;
979 my $label = $lid->cn_label;
980 my $bibid = $li->eg_bib_id;
982 my $volume = $mgr->cache($org, "cn.$bibid.$label");
984 $volume = create_volume($mgr, $li, $lid) or return 0;
985 $mgr->cache($org, "cn.$bibid.$label", $volume);
987 create_copy($mgr, $volume, $lid) or return 0;
990 return { li => $li, new_bib => $new_bib };
996 my $record = OpenILS::Application::Cat::BibCommon->biblio_record_xml_import(
1001 1, # override tcn collisions
1004 if($U->event_code($record)) {
1005 $mgr->editor->event($record);
1006 $mgr->editor->rollback;
1010 $li->eg_bib_id($record->id);
1012 return update_lineitem($mgr, $li);
1016 my($mgr, $li, $lid) = @_;
1018 my ($volume, $evt) =
1019 OpenILS::Application::Cat::AssetCommon->find_or_create_volume(
1027 $mgr->editor->event($evt);
1035 my($mgr, $volume, $lid) = @_;
1036 my $copy = Fieldmapper::asset::copy->new;
1038 $copy->loan_duration(2);
1039 $copy->fine_level(2);
1040 $copy->status(($lid->recv_time) ? OILS_COPY_STATUS_IN_PROCESS : OILS_COPY_STATUS_ON_ORDER);
1041 $copy->barcode($lid->barcode);
1042 $copy->location($lid->location);
1043 $copy->call_number($volume->id);
1044 $copy->circ_lib($volume->owning_lib);
1045 $copy->circ_modifier($lid->circ_modifier);
1047 my $evt = OpenILS::Application::Cat::AssetCommon->create_copy($mgr->editor, $volume, $copy);
1049 $mgr->editor->event($evt);
1054 $lid->eg_copy_id($copy->id);
1055 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
1063 # ----------------------------------------------------------------------------
1064 # Workflow: Build a selection list from a Z39.50 search
1065 # ----------------------------------------------------------------------------
1067 __PACKAGE__->register_method(
1068 method => 'zsearch',
1069 api_name => 'open-ils.acq.picklist.search.z3950',
1072 desc => 'Performs a z3950 federated search and creates a picklist and associated lineitems',
1074 {desc => 'Authentication token', type => 'string'},
1075 {desc => 'Search definition', type => 'object'},
1076 {desc => 'Picklist name, optional', type => 'string'},
1082 my($self, $conn, $auth, $search, $name, $options) = @_;
1083 my $e = new_editor(authtoken=>$auth);
1084 return $e->event unless $e->checkauth;
1085 return $e->event unless $e->allowed('CREATE_PICKLIST');
1087 $search->{limit} ||= 10;
1090 my $ses = OpenSRF::AppSession->create('open-ils.search');
1091 my $req = $ses->request('open-ils.search.z3950.search_class', $auth, $search);
1096 while(my $resp = $req->recv(timeout=>60)) {
1099 my $e = new_editor(requestor=>$e->requestor, xact=>1);
1100 $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1101 $picklist = zsearch_build_pl($mgr, $name);
1105 my $result = $resp->content;
1106 my $count = $result->{count} || 0;
1107 $mgr->total( (($count < $search->{limit}) ? $count : $search->{limit})+1 );
1109 for my $rec (@{$result->{records}}) {
1111 my $li = create_lineitem($mgr,
1112 picklist => $picklist->id,
1113 source_label => $result->{service},
1114 marc => $rec->{marcxml},
1115 eg_bib_id => $rec->{bibid}
1118 if($$options{respond_li}) {
1119 $li->attributes($mgr->editor->search_acq_lineitem_attr({lineitem => $li->id}))
1120 if $$options{flesh_attrs};
1121 $li->clear_marc if $$options{clear_marc};
1122 $mgr->respond(lineitem => $li);
1129 $mgr->editor->commit;
1130 return $mgr->respond_complete;
1133 sub zsearch_build_pl {
1134 my($mgr, $name) = @_;
1137 my $picklist = $mgr->editor->search_acq_picklist({
1138 owner => $mgr->editor->requestor->id,
1142 if($name eq '' and $picklist) {
1143 return 0 unless delete_picklist($mgr, $picklist);
1147 return update_picklist($mgr, $picklist) if $picklist;
1148 return create_picklist($mgr, name => $name);
1152 # ----------------------------------------------------------------------------
1153 # Workflow: Build a selection list / PO by importing a batch of MARC records
1154 # ----------------------------------------------------------------------------
1156 __PACKAGE__->register_method(
1157 method => 'upload_records',
1158 api_name => 'open-ils.acq.process_upload_records',
1162 sub upload_records {
1163 my($self, $conn, $auth, $key) = @_;
1165 my $e = new_editor(authtoken => $auth, xact => 1);
1166 return $e->die_event unless $e->checkauth;
1167 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1169 my $cache = OpenSRF::Utils::Cache->new;
1171 my $data = $cache->get_cache("vandelay_import_spool_$key");
1172 my $purpose = $data->{purpose};
1173 my $filename = $data->{path};
1174 my $provider = $data->{provider};
1175 my $picklist = $data->{picklist};
1176 my $create_po = $data->{create_po};
1177 my $activate_po = $data->{activate_po};
1178 my $ordering_agency = $data->{ordering_agency};
1179 my $create_assets = $data->{create_assets};
1183 unless(-r $filename) {
1184 $logger->error("unable to read MARC file $filename");
1186 return OpenILS::Event->new('FILE_UPLOAD_ERROR', payload => {filename => $filename});
1189 $provider = $e->retrieve_acq_provider($provider) or return $e->die_event;
1192 $picklist = $e->retrieve_acq_picklist($picklist) or return $e->die_event;
1193 if($picklist->owner != $e->requestor->id) {
1194 return $e->die_event unless
1195 $e->allowed('CREATE_PICKLIST', $picklist->org_unit, $picklist);
1197 $mgr->picklist($picklist);
1202 $po = create_purchase_order($mgr,
1203 ordering_agency => $ordering_agency,
1204 provider => $provider->id,
1206 ) or return $mgr->editor->die_event;
1209 $logger->info("acq processing MARC file=$filename");
1211 my $marctype = 'USMARC'; # ?
1212 my $batch = new MARC::Batch ($marctype, $filename);
1227 } catch Error with {
1229 $logger->warn("Proccessing of record $count in set $key failed with error $err. Skipping this record");
1236 ($xml = $r->as_xml_record()) =~ s/\n//sog;
1237 $xml =~ s/^<\?xml.+\?\s*>//go;
1238 $xml =~ s/>\s+</></go;
1239 $xml =~ s/\p{Cc}//go;
1240 $xml = $U->entityize($xml);
1241 $xml =~ s/[\x00-\x1f]//go;
1243 } catch Error with {
1245 $logger->warn("Proccessing XML of record $count in set $key failed with error $err. Skipping this record");
1248 next if $err or not $xml;
1251 source_label => $provider->code,
1252 provider => $provider->id,
1256 $args{picklist} = $picklist->id if $picklist;
1258 $args{purchase_order} = $po->id;
1259 $args{state} = 'order-pending';
1262 my $li = create_lineitem($mgr, %args) or return $mgr->editor->die_event;
1264 $li->provider($provider); # flesh it, we'll need it later
1266 import_lineitem_details($mgr, $ordering_agency, $li) or return $mgr->editor->die_event;
1269 push(@li_list, $li->id);
1273 my $die_event = activate_purchase_order_impl($mgr, $po->id) if $po;;
1274 return $die_event if $die_event;
1278 $cache->delete_cache('vandelay_import_spool_' . $key);
1280 if($create_assets) {
1281 create_lineitem_list_assets($mgr, \@li_list) or return $e->die_event;
1284 return $mgr->respond_complete;
1287 sub import_lineitem_details {
1288 my($mgr, $ordering_agency, $li) = @_;
1290 my $holdings = $mgr->editor->json_query({from => ['acq.extract_provider_holding_data', $li->id]});
1291 return 1 unless @$holdings;
1292 my $org_path = $U->get_org_ancestors($ordering_agency);
1293 $org_path = [ reverse (@$org_path) ];
1298 # create a lineitem detail for each copy in the data
1300 my $compiled = extract_lineitem_detail_data($mgr, $org_path, $holdings, $idx);
1301 last unless defined $compiled;
1302 return 0 unless $compiled;
1304 # this takes the price of the last copy and uses it as the lineitem price
1305 # need to determine if a given record would include different prices for the same item
1306 $price = $$compiled{price};
1308 for(1..$$compiled{quantity}) {
1309 my $lid = create_lineitem_detail($mgr,
1310 lineitem => $li->id,
1311 owning_lib => $$compiled{owning_lib},
1312 cn_label => $$compiled{call_number},
1313 fund => $$compiled{fund},
1314 circ_modifier => $$compiled{circ_modifier},
1315 note => $$compiled{note},
1316 location => $$compiled{copy_location},
1317 collection_code => $$compiled{collection_code}
1325 $li->estimated_unit_price($price);
1326 update_lineitem($mgr, $li) or return 0;
1330 # return hash on success, 0 on error, undef on no more holdings
1331 sub extract_lineitem_detail_data {
1332 my($mgr, $org_path, $holdings, $index) = @_;
1334 my @data_list = grep { $_->{holding} eq $index } @$holdings;
1335 return undef unless @data_list;
1337 my %compiled = map { $_->{attr} => $_->{data} } @data_list;
1338 my $base_org = $$org_path[0];
1342 $logger->error("Item import extraction error: $msg");
1343 $logger->error('Holdings Data: ' . OpenSRF::Utils::JSON->perl2JSON(\%compiled));
1344 $mgr->editor->rollback;
1345 $mgr->editor->event(OpenILS::Event->new('ACQ_IMPORT_ERROR', payload => $msg));
1349 $compiled{quantity} ||= 1;
1351 # ---------------------------------------------------------------------
1353 my $code = $compiled{fund_code};
1354 return $killme->('no fund code provided') unless $code;
1356 my $fund = $mgr->cache($base_org, "fund.$code");
1358 # search up the org tree for the most appropriate fund
1359 for my $org (@$org_path) {
1360 $fund = $mgr->editor->search_acq_fund(
1361 {org => $org, code => $code, year => DateTime->now->year}, {idlist => 1})->[0];
1365 return $killme->("no fund with code $code at orgs [@$org_path]") unless $fund;
1366 $compiled{fund} = $fund;
1367 $mgr->cache($base_org, "fund.$code", $fund);
1370 # ---------------------------------------------------------------------
1372 my $sn = $compiled{owning_lib};
1373 return $killme->('no owning_lib defined') unless $sn;
1375 $mgr->cache($base_org, "orgsn.$sn") ||
1376 $mgr->editor->search_actor_org_unit({shortname => $sn}, {idlist => 1})->[0];
1377 return $killme->("invalid owning_lib defined: $sn") unless $org_id;
1378 $compiled{owning_lib} = $org_id;
1379 $mgr->cache($$org_path[0], "orgsn.$sn", $org_id);
1382 # ---------------------------------------------------------------------
1385 $code = $compiled{circ_modifier};
1389 $mod = $mgr->cache($base_org, "mod.$code") ||
1390 $mgr->editor->retrieve_config_circ_modifier($code);
1391 return $killme->("invlalid circ_modifier $code") unless $mod;
1392 $mgr->cache($base_org, "mod.$code", $mod);
1396 $mod = get_default_circ_modifier($mgr, $base_org)
1397 or return $killme->('no circ_modifier defined');
1400 $compiled{circ_modifier} = $mod;
1403 # ---------------------------------------------------------------------
1405 my $name = $compiled{copy_location};
1407 my $loc = $mgr->cache($base_org, "copy_loc.$name");
1409 for my $org (@$org_path) {
1410 $loc = $mgr->editor->search_asset_copy_location(
1411 {owning_lib => $org, name => $name}, {idlist => 1})->[0];
1415 return $killme->("Invalid copy location $name") unless $loc;
1416 $compiled{copy_location} = $loc;
1417 $mgr->cache($base_org, "copy_loc.$name", $loc);
1425 # ----------------------------------------------------------------------------
1426 # Workflow: Given an existing purchase order, import/create the bibs,
1427 # callnumber and copy objects
1428 # ----------------------------------------------------------------------------
1430 __PACKAGE__->register_method(
1431 method => 'create_po_assets',
1432 api_name => 'open-ils.acq.purchase_order.assets.create',
1434 desc => q/Creates assets for each lineitem in the purchase order/,
1436 {desc => 'Authentication token', type => 'string'},
1437 {desc => 'The purchase order id', type => 'number'},
1439 return => {desc => 'Streams a total versus completed counts object, event on error'}
1443 sub create_po_assets {
1444 my($self, $conn, $auth, $po_id) = @_;
1446 my $e = new_editor(authtoken=>$auth, xact=>1);
1447 return $e->die_event unless $e->checkauth;
1448 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1450 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1452 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1454 # it's ugly, but it's fast. Get the total count of lineitem detail objects to process
1455 my $lid_total = $e->json_query({
1456 select => { acqlid => [{aggregate => 1, transform => 'count', column => 'id'}] },
1462 join => {acqpo => {fkey => 'purchase_order', field => 'id'}}
1466 where => {'+acqpo' => {id => $po_id}}
1469 $mgr->total(scalar(@$li_ids) + $lid_total);
1471 create_lineitem_list_assets($mgr, $li_ids) or return $e->die_event;
1474 update_purchase_order($mgr, $po) or return $e->die_event;
1477 return $mgr->respond_complete;
1482 __PACKAGE__->register_method(
1483 method => 'create_purchase_order_api',
1484 api_name => 'open-ils.acq.purchase_order.create',
1486 desc => 'Creates a new purchase order',
1488 {desc => 'Authentication token', type => 'string'},
1489 {desc => 'purchase_order to create', type => 'object'}
1491 return => {desc => 'The purchase order id, Event on failure'}
1495 sub create_purchase_order_api {
1496 my($self, $conn, $auth, $po, $args) = @_;
1499 my $e = new_editor(xact=>1, authtoken=>$auth);
1500 return $e->die_event unless $e->checkauth;
1501 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
1502 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1505 my %pargs = (ordering_agency => $e->requestor->ws_ou); # default
1506 $pargs{provider} = $po->provider if $po->provider;
1507 $pargs{ordering_agency} = $po->ordering_agency if $po->ordering_agency;
1508 $pargs{prepayment_required} = $po->prepayment_required
1509 if $po->prepayment_required;
1510 $po = create_purchase_order($mgr, %pargs) or return $e->die_event;
1512 my $li_ids = $$args{lineitems};
1516 for my $li_id (@$li_ids) {
1518 my $li = $e->retrieve_acq_lineitem([
1520 {flesh => 1, flesh_fields => {jub => ['attributes']}}
1521 ]) or return $e->die_event;
1523 $li->provider($po->provider);
1524 $li->purchase_order($po->id);
1525 $li->state('pending-order');
1526 update_lineitem($mgr, $li) or return $e->die_event;
1531 # commit before starting the asset creation
1534 if($li_ids and $$args{create_assets}) {
1535 create_lineitem_list_assets($mgr, $li_ids) or return $e->die_event;
1538 return $mgr->respond_complete;
1542 __PACKAGE__->register_method(
1543 method => 'lineitem_detail_CUD_batch',
1544 api_name => 'open-ils.acq.lineitem_detail.cud.batch',
1547 desc => q/Creates a new purchase order line item detail.
1548 Additionally creates the associated fund_debit/,
1550 {desc => 'Authentication token', type => 'string'},
1551 {desc => 'List of lineitem_details to create', type => 'array'},
1552 {desc => 'Create Debits. Used for creating post-po-asset-creation debits', type => 'bool'},
1554 return => {desc => 'Streaming response of current position in the array'}
1558 sub lineitem_detail_CUD_batch {
1559 my($self, $conn, $auth, $li_details, $create_debits) = @_;
1561 my $e = new_editor(xact=>1, authtoken=>$auth);
1562 return $e->die_event unless $e->checkauth;
1563 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1565 $mgr->total(scalar(@$li_details));
1571 for my $lid (@$li_details) {
1573 unless($li = $li_cache{$lid->lineitem}) {
1574 ($li, $evt) = fetch_and_check_li($e, $lid->lineitem, 'write');
1575 return $evt if $evt;
1579 $lid = create_lineitem_detail($mgr, %{$lid->to_bare_hash}) or return $e->die_event;
1580 if($create_debits) {
1581 $li->provider($e->retrieve_acq_provider($li->provider)) or return $e->die_event;
1582 $lid->fund($e->retrieve_acq_fund($lid->fund)) or return $e->die_event;
1583 create_lineitem_detail_debit($mgr, $li, $lid, 0, 1) or return $e->die_event;
1586 } elsif($lid->ischanged) {
1587 $e->update_acq_lineitem_detail($lid) or return $e->die_event;
1589 } elsif($lid->isdeleted) {
1590 delete_lineitem_detail($mgr, $lid) or return $e->die_event;
1593 $mgr->respond(li => $li);
1594 $li_cache{$lid->lineitem} = $li;
1598 return $mgr->respond_complete;
1602 __PACKAGE__->register_method(
1603 method => 'receive_po_api',
1604 api_name => 'open-ils.acq.purchase_order.receive'
1607 sub receive_po_api {
1608 my($self, $conn, $auth, $po_id) = @_;
1609 my $e = new_editor(xact => 1, authtoken => $auth);
1610 return $e->die_event unless $e->checkauth;
1611 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1613 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1614 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1616 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1618 for my $li_id (@$li_ids) {
1619 receive_lineitem($mgr, $li_id) or return $e->die_event;
1623 $po->state('received');
1624 update_purchase_order($mgr, $po) or return $e->die_event;
1627 return $mgr->respond_complete;
1631 # At the moment there's a lack of parallelism between the receive and unreceive
1632 # API methods for POs and the API methods for LIs and LIDs. The methods for
1633 # POs stream back objects as they act, whereas the methods for LIs and LIDs
1634 # atomically return an object that describes only what changed (in LIs and LIDs
1635 # themselves or in the objects to which to LIs and LIDs belong).
1637 # The methods for LIs and LIDs work the way they do to faciliate the UI's
1638 # maintaining correct information about the state of these things when a user
1639 # wants to receive or unreceive these objects without refreshing their whole
1640 # display. The UI feature for receiving and un-receiving a whole PO just
1641 # refreshes the whole display, so this absence of parallelism in the UI is also
1642 # relected in this module.
1644 # This could be neatened in the future by making POs receive and unreceive in
1645 # the same way the LIs and LIDs do.
1647 __PACKAGE__->register_method(
1648 method => 'receive_lineitem_detail_api',
1649 api_name => 'open-ils.acq.lineitem_detail.receive',
1651 desc => 'Mark a lineitem_detail as received',
1653 {desc => 'Authentication token', type => 'string'},
1654 {desc => 'lineitem detail ID', type => 'number'}
1657 "on success, object describing changes to LID and possibly " .
1658 "to LI and PO; on error, Event"
1663 sub receive_lineitem_detail_api {
1664 my($self, $conn, $auth, $lid_id) = @_;
1666 my $e = new_editor(xact=>1, authtoken=>$auth);
1667 return $e->die_event unless $e->checkauth;
1668 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1671 "flesh" => 2, "flesh_fields" => {
1672 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
1676 my $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1678 return $e->die_event unless $e->allowed(
1679 'RECEIVE_PURCHASE_ORDER', $lid->lineitem->purchase_order->ordering_agency);
1682 my $recvd = receive_lineitem_detail($mgr, $lid_id) or return $e->die_event;
1684 # .. and re-retrieve
1685 $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1687 # Now build result data structure.
1688 my $result = {"lid" => {$lid->id => {"recv_time" => $lid->recv_time}}};
1691 if ($recvd->class_name =~ /::purchase_order/) {
1692 $result->{"po"} = describe_affected_po($e, $recvd);
1694 $lid->lineitem->id => {"state" => $lid->lineitem->state}
1696 } elsif ($recvd->class_name =~ /::lineitem/) {
1697 $result->{"li"} = {$recvd->id => {"state" => $recvd->state}};
1701 describe_affected_po($e, $lid->lineitem->purchase_order);
1707 __PACKAGE__->register_method(
1708 method => 'receive_lineitem_api',
1709 api_name => 'open-ils.acq.lineitem.receive',
1711 desc => 'Mark a lineitem as received',
1713 {desc => 'Authentication token', type => 'string'},
1714 {desc => 'lineitem ID', type => 'number'}
1717 "on success, object describing changes to LI and possibly PO; " .
1723 sub receive_lineitem_api {
1724 my($self, $conn, $auth, $li_id) = @_;
1726 my $e = new_editor(xact=>1, authtoken=>$auth);
1727 return $e->die_event unless $e->checkauth;
1728 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1730 my $li = $e->retrieve_acq_lineitem([
1734 jub => ['purchase_order']
1737 ]) or return $e->die_event;
1739 return $e->die_event unless $e->allowed(
1740 'RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);
1742 my $res = receive_lineitem($mgr, $li_id) or return $e->die_event;
1744 $conn->respond_complete($res);
1745 $mgr->run_post_response_hooks;
1749 __PACKAGE__->register_method(
1750 method => 'rollback_receive_po_api',
1751 api_name => 'open-ils.acq.purchase_order.receive.rollback'
1754 sub rollback_receive_po_api {
1755 my($self, $conn, $auth, $po_id) = @_;
1756 my $e = new_editor(xact => 1, authtoken => $auth);
1757 return $e->die_event unless $e->checkauth;
1758 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1760 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1761 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1763 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1765 for my $li_id (@$li_ids) {
1766 rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
1770 $po->state('on-order');
1771 update_purchase_order($mgr, $po) or return $e->die_event;
1774 return $mgr->respond_complete;
1778 __PACKAGE__->register_method(
1779 method => 'rollback_receive_lineitem_detail_api',
1780 api_name => 'open-ils.acq.lineitem_detail.receive.rollback',
1782 desc => 'Mark a lineitem_detail as Un-received',
1784 {desc => 'Authentication token', type => 'string'},
1785 {desc => 'lineitem detail ID', type => 'number'}
1788 "on success, object describing changes to LID and possibly " .
1789 "to LI and PO; on error, Event"
1794 sub rollback_receive_lineitem_detail_api {
1795 my($self, $conn, $auth, $lid_id) = @_;
1797 my $e = new_editor(xact=>1, authtoken=>$auth);
1798 return $e->die_event unless $e->checkauth;
1799 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1801 my $lid = $e->retrieve_acq_lineitem_detail([
1805 acqlid => ['lineitem'],
1806 jub => ['purchase_order']
1810 my $li = $lid->lineitem;
1811 my $po = $li->purchase_order;
1813 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1817 my $recvd = rollback_receive_lineitem_detail($mgr, $lid_id)
1818 or return $e->die_event;
1821 $result->{"lid"} = {$recvd->id => {"recv_time" => $recvd->recv_time}};
1823 $result->{"lid"} = {$lid->id => {"recv_time" => $lid->recv_time}};
1826 if ($li->state eq "received") {
1827 $li->state("on-order");
1828 $li = update_lineitem($mgr, $li) or return $e->die_event;
1829 $result->{"li"} = {$li->id => {"state" => $li->state}};
1832 if ($po->state eq "received") {
1833 $po->state("on-order");
1834 $po = update_purchase_order($mgr, $po) or return $e->die_event;
1836 $result->{"po"} = describe_affected_po($e, $po);
1838 $e->commit and return $result or return $e->die_event;
1841 __PACKAGE__->register_method(
1842 method => 'rollback_receive_lineitem_api',
1843 api_name => 'open-ils.acq.lineitem.receive.rollback',
1845 desc => 'Mark a lineitem as Un-received',
1847 {desc => 'Authentication token', type => 'string'},
1848 {desc => 'lineitem ID', type => 'number'}
1851 "on success, object describing changes to LI and possibly PO; " .
1857 sub rollback_receive_lineitem_api {
1858 my($self, $conn, $auth, $li_id) = @_;
1860 my $e = new_editor(xact=>1, authtoken=>$auth);
1861 return $e->die_event unless $e->checkauth;
1862 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1864 my $li = $e->retrieve_acq_lineitem([
1866 "flesh" => 1, "flesh_fields" => {"jub" => ["purchase_order"]}
1869 my $po = $li->purchase_order;
1871 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1873 $li = rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
1875 my $result = {"li" => {$li->id => {"state" => $li->state}}};
1876 if ($po->state eq "received") {
1877 $po->state("on-order");
1878 $po = update_purchase_order($mgr, $po) or return $e->die_event;
1880 $result->{"po"} = describe_affected_po($e, $po);
1882 $e->commit and return $result or return $e->die_event;
1886 __PACKAGE__->register_method(
1887 method => 'set_lineitem_price_api',
1888 api_name => 'open-ils.acq.lineitem.price.set',
1890 desc => 'Set lineitem price. If debits already exist, update them as well',
1892 {desc => 'Authentication token', type => 'string'},
1893 {desc => 'lineitem ID', type => 'number'}
1895 return => {desc => 'status blob, Event on error'}
1899 sub set_lineitem_price_api {
1900 my($self, $conn, $auth, $li_id, $price) = @_;
1902 my $e = new_editor(xact=>1, authtoken=>$auth);
1903 return $e->die_event unless $e->checkauth;
1904 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1906 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
1907 return $evt if $evt;
1909 $li->estimated_unit_price($price);
1910 update_lineitem($mgr, $li) or return $e->die_event;
1912 my $lid_ids = $e->search_acq_lineitem_detail(
1913 {lineitem => $li_id, fund_debit => {'!=' => undef}},
1917 for my $lid_id (@$lid_ids) {
1919 my $lid = $e->retrieve_acq_lineitem_detail([
1921 flesh => 1, flesh_fields => {acqlid => ['fund', 'fund_debit']}}
1924 $lid->fund_debit->amount($price);
1925 $e->update_acq_fund_debit($lid->fund_debit) or return $e->die_event;
1931 return $mgr->respond_complete;
1935 __PACKAGE__->register_method(
1936 method => 'clone_picklist_api',
1937 api_name => 'open-ils.acq.picklist.clone',
1939 desc => 'Clones a picklist, including lineitem and lineitem details',
1941 {desc => 'Authentication token', type => 'string'},
1942 {desc => 'Picklist ID', type => 'number'},
1943 {desc => 'New Picklist Name', type => 'string'}
1945 return => {desc => 'status blob, Event on error'}
1949 sub clone_picklist_api {
1950 my($self, $conn, $auth, $pl_id, $name) = @_;
1952 my $e = new_editor(xact=>1, authtoken=>$auth);
1953 return $e->die_event unless $e->checkauth;
1954 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1956 my $old_pl = $e->retrieve_acq_picklist($pl_id);
1957 my $new_pl = create_picklist($mgr, %{$old_pl->to_bare_hash}, name => $name) or return $e->die_event;
1959 my $li_ids = $e->search_acq_lineitem({picklist => $pl_id}, {idlist => 1});
1961 for my $li_id (@$li_ids) {
1963 # copy the lineitems
1964 my $li = $e->retrieve_acq_lineitem($li_id);
1965 my $new_li = create_lineitem($mgr, %{$li->to_bare_hash}, picklist => $new_pl->id) or return $e->die_event;
1967 my $lid_ids = $e->search_acq_lineitem_detail({lineitem => $li_id}, {idlist => 1});
1968 for my $lid_id (@$lid_ids) {
1970 # copy the lineitem details
1971 my $lid = $e->retrieve_acq_lineitem_detail($lid_id);
1972 create_lineitem_detail($mgr, %{$lid->to_bare_hash}, lineitem => $new_li->id) or return $e->die_event;
1979 return $mgr->respond_complete;
1983 __PACKAGE__->register_method(
1984 method => 'merge_picklist_api',
1985 api_name => 'open-ils.acq.picklist.merge',
1987 desc => 'Merges 2 or more picklists into a single list',
1989 {desc => 'Authentication token', type => 'string'},
1990 {desc => 'Lead Picklist ID', type => 'number'},
1991 {desc => 'List of subordinate picklist IDs', type => 'array'}
1993 return => {desc => 'status blob, Event on error'}
1997 sub merge_picklist_api {
1998 my($self, $conn, $auth, $lead_pl, $pl_list) = @_;
2000 my $e = new_editor(xact=>1, authtoken=>$auth);
2001 return $e->die_event unless $e->checkauth;
2002 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2004 # XXX perms on each picklist modified
2006 # point all of the lineitems at the lead picklist
2007 my $li_ids = $e->search_acq_lineitem({picklist => $pl_list}, {idlist => 1});
2009 for my $li_id (@$li_ids) {
2010 my $li = $e->retrieve_acq_lineitem($li_id);
2011 $li->picklist($lead_pl);
2012 update_lineitem($mgr, $li) or return $e->die_event;
2016 # now delete the subordinate lists
2017 for my $pl_id (@$pl_list) {
2018 my $pl = $e->retrieve_acq_picklist($pl_id);
2019 $e->delete_acq_picklist($pl) or return $e->die_event;
2023 return $mgr->respond_complete;
2027 __PACKAGE__->register_method(
2028 method => 'delete_picklist_api',
2029 api_name => 'open-ils.acq.picklist.delete',
2031 desc => q/Deletes a picklist. It also deletes any lineitems in the "new" state.
2032 Other attached lineitems are detached'/,
2034 {desc => 'Authentication token', type => 'string'},
2035 {desc => 'Picklist ID to delete', type => 'number'}
2037 return => {desc => '1 on success, Event on error'}
2041 sub delete_picklist_api {
2042 my($self, $conn, $auth, $picklist_id) = @_;
2043 my $e = new_editor(xact=>1, authtoken=>$auth);
2044 return $e->die_event unless $e->checkauth;
2045 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2046 my $pl = $e->retrieve_acq_picklist($picklist_id) or return $e->die_event;
2047 delete_picklist($mgr, $pl) or return $e->die_event;
2049 return $mgr->respond_complete;
2054 __PACKAGE__->register_method(
2055 method => 'activate_purchase_order',
2056 api_name => 'open-ils.acq.purchase_order.activate.dry_run'
2059 __PACKAGE__->register_method(
2060 method => 'activate_purchase_order',
2061 api_name => 'open-ils.acq.purchase_order.activate',
2063 desc => q/Activates a purchase order. This updates the status of the PO
2064 and Lineitems to 'on-order'. Activated PO's are ready for EDI delivery
2067 {desc => 'Authentication token', type => 'string'},
2068 {desc => 'Purchase ID', type => 'number'}
2070 return => {desc => '1 on success, Event on error'}
2074 sub activate_purchase_order {
2075 my($self, $conn, $auth, $po_id) = @_;
2077 my $dry_run = ($self->api_name =~ /\.dry_run/) ? 1 : 0;
2078 my $e = new_editor(xact=>1, authtoken=>$auth);
2079 return $e->die_event unless $e->checkauth;
2080 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2081 my $die_event = activate_purchase_order_impl($mgr, $po_id, $dry_run);
2082 return $e->die_event if $die_event;
2088 $conn->respond_complete(1);
2089 $mgr->run_post_response_hooks;
2093 sub activate_purchase_order_impl {
2094 my ($mgr, $po_id, $dry_run) = @_;
2095 my $e = $mgr->editor;
2097 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2098 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
2100 $po->state('on-order');
2101 $po->order_date('now');
2102 update_purchase_order($mgr, $po) or return $e->die_event;
2105 {purchase_order => $po_id, state => 'pending-order'},
2109 while( my $li = $e->search_acq_lineitem($query)->[0] ) {
2110 $li->state('on-order');
2111 create_lineitem_debits($mgr, $li, $dry_run) or return $e->die_event;
2112 update_lineitem($mgr, $li) or return $e->die_event;
2113 $mgr->post_process( sub { create_lineitem_status_events($mgr, $li->id, 'aur.ordered'); });
2117 for my $po_item (@{$e->search_acq_po_item({purchase_order => $po_id})}) {
2119 my $debit = create_fund_debit(
2122 debit_type => 'direct_charge', # to match invoicing
2123 origin_amount => $po_item->estimated_cost,
2124 origin_currency_type => $e->retrieve_acq_fund($po_item->fund)->currency_type,
2125 amount => $po_item->estimated_cost,
2126 fund => $po_item->fund
2127 ) or return $e->die_event;
2128 $po_item->fund_debit($debit->id);
2129 $e->update_acq_po_item($po_item) or return $e->die_event;
2137 __PACKAGE__->register_method(
2138 method => 'split_purchase_order_by_lineitems',
2139 api_name => 'open-ils.acq.purchase_order.split_by_lineitems',
2141 desc => q/Splits a PO into many POs, 1 per lineitem. Only works for
2142 POs a) with more than one lineitems, and b) in the "pending" state./,
2144 {desc => 'Authentication token', type => 'string'},
2145 {desc => 'Purchase order ID', type => 'number'}
2147 return => {desc => 'list of new PO IDs on success, Event on error'}
2151 sub split_purchase_order_by_lineitems {
2152 my ($self, $conn, $auth, $po_id) = @_;
2154 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2155 return $e->die_event unless $e->checkauth;
2157 my $po = $e->retrieve_acq_purchase_order([
2160 "flesh_fields" => {"acqpo" => [qw/lineitems notes/]}
2162 ]) or return $e->die_event;
2164 return $e->die_event
2165 unless $e->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2167 unless ($po->state eq "pending") {
2169 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_LATE");
2172 unless (@{$po->lineitems} > 1) {
2174 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_SHORT");
2177 # To split an existing PO into many, it seems unwise to just delete the
2178 # original PO, so we'll instead detach all of the original POs' lineitems
2179 # but the first, then create new POs for each of the remaining LIs, and
2180 # then attach the LIs to their new POs.
2182 my @po_ids = ($po->id);
2183 my @moving_li = @{$po->lineitems};
2184 shift @moving_li; # discard first LI
2186 foreach my $li (@moving_li) {
2187 my $new_po = $po->clone;
2189 $new_po->clear_name;
2190 $new_po->creator($e->requestor->id);
2191 $new_po->editor($e->requestor->id);
2192 $new_po->owner($e->requestor->id);
2193 $new_po->edit_time("now");
2194 $new_po->create_time("now");
2196 $new_po = $e->create_acq_purchase_order($new_po);
2198 # Clone any notes attached to the old PO and attach to the new one.
2199 foreach my $note (@{$po->notes}) {
2200 my $new_note = $note->clone;
2201 $new_note->clear_id;
2202 $new_note->edit_time("now");
2203 $new_note->purchase_order($new_po->id);
2204 $e->create_acq_po_note($new_note);
2207 $li->edit_time("now");
2208 $li->purchase_order($new_po->id);
2209 $e->update_acq_lineitem($li);
2211 push @po_ids, $new_po->id;
2214 $po->edit_time("now");
2215 $e->update_acq_purchase_order($po);
2217 return \@po_ids if $e->commit;
2218 return $e->die_event;
2222 sub not_cancelable {
2224 (ref $o eq "HASH" and $o->{"textcode"} eq "ACQ_NOT_CANCELABLE");
2227 __PACKAGE__->register_method(
2228 method => "cancel_purchase_order_api",
2229 api_name => "open-ils.acq.purchase_order.cancel",
2231 desc => q/Cancels an on-order purchase order/,
2233 {desc => "Authentication token", type => "string"},
2234 {desc => "PO ID to cancel", type => "number"},
2235 {desc => "Cancel reason ID", type => "number"}
2237 return => {desc => q/Object describing changed POs, LIs and LIDs
2238 on success; Event on error./}
2242 sub cancel_purchase_order_api {
2243 my ($self, $conn, $auth, $po_id, $cancel_reason) = @_;
2245 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2246 return $e->die_event unless $e->checkauth;
2247 my $mgr = new OpenILS::Application::Acq::BatchManager(
2248 "editor" => $e, "conn" => $conn
2251 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2252 return new OpenILS::Event(
2253 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2256 my $result = cancel_purchase_order($mgr, $po_id, $cancel_reason) or
2257 return $e->die_event;
2258 if (not_cancelable($result)) { # event not from CStoreEditor
2261 } elsif ($result == -1) {
2263 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2266 $e->commit or return $e->die_event;
2268 # XXX create purchase order status events?
2270 if ($mgr->{post_commit}) {
2271 foreach my $func (@{$mgr->{post_commit}}) {
2279 sub cancel_purchase_order {
2280 my ($mgr, $po_id, $cancel_reason) = @_;
2282 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id) or return 0;
2284 # XXX is "cancelled" a typo? It's not correct US spelling, anyway.
2285 # Depending on context, this may not warrant an event.
2286 return -1 if $po->state eq "cancelled";
2288 # But this always does.
2289 return new OpenILS::Event(
2290 "ACQ_NOT_CANCELABLE", "note" => "purchase_order $po_id"
2291 ) unless ($po->state eq "on-order" or $po->state eq "pending");
2294 $mgr->editor->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2296 $po->state("cancelled");
2297 $po->cancel_reason($cancel_reason->id);
2299 my $li_ids = $mgr->editor->search_acq_lineitem(
2300 {"purchase_order" => $po_id}, {"idlist" => 1}
2303 my $result = {"li" => {}, "lid" => {}};
2304 foreach my $li_id (@$li_ids) {
2305 my $li_result = cancel_lineitem($mgr, $li_id, $cancel_reason)
2308 next if $li_result == -1; # already canceled:skip.
2309 return $li_result if not_cancelable($li_result); # not cancelable:stop.
2311 # Merge in each LI result (there's only going to be
2312 # one per call to cancel_lineitem).
2313 my ($k, $v) = each %{$li_result->{"li"}};
2314 $result->{"li"}->{$k} = $v;
2316 # Merge in each LID result (there may be many per call to
2318 while (($k, $v) = each %{$li_result->{"lid"}}) {
2319 $result->{"lid"}->{$k} = $v;
2323 # TODO who/what/where/how do we indicate this change for electronic orders?
2324 # TODO return changes to encumbered/spent
2325 # TODO maybe cascade up from smaller object to container object if last
2326 # smaller object in the container has been canceled?
2328 update_purchase_order($mgr, $po) or return 0;
2330 $po_id => {"state" => $po->state, "cancel_reason" => $cancel_reason}
2336 __PACKAGE__->register_method(
2337 method => "cancel_lineitem_api",
2338 api_name => "open-ils.acq.lineitem.cancel",
2340 desc => q/Cancels an on-order lineitem/,
2342 {desc => "Authentication token", type => "string"},
2343 {desc => "Lineitem ID to cancel", type => "number"},
2344 {desc => "Cancel reason ID", type => "number"}
2346 return => {desc => q/Object describing changed LIs and LIDs on success;
2351 __PACKAGE__->register_method(
2352 method => "cancel_lineitem_api",
2353 api_name => "open-ils.acq.lineitem.cancel.batch",
2355 desc => q/Batched version of open-ils.acq.lineitem.cancel/,
2356 return => {desc => q/Object describing changed LIs and LIDs on success;
2361 sub cancel_lineitem_api {
2362 my ($self, $conn, $auth, $li_id, $cancel_reason) = @_;
2364 my $batched = $self->api_name =~ /\.batch/;
2366 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2367 return $e->die_event unless $e->checkauth;
2368 my $mgr = new OpenILS::Application::Acq::BatchManager(
2369 "editor" => $e, "conn" => $conn
2372 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2373 return new OpenILS::Event(
2374 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2377 my ($result, $maybe_event);
2380 $result = {"li" => {}, "lid" => {}};
2381 foreach my $one_li_id (@$li_id) {
2382 my $one = cancel_lineitem($mgr, $one_li_id, $cancel_reason) or
2383 return $e->die_event;
2384 if (not_cancelable($one)) {
2385 $maybe_event = $one;
2386 } elsif ($result == -1) {
2387 $maybe_event = new OpenILS::Event("ACQ_ALREADY_CANCELED");
2391 while (($k, $v) = each %{$one->{"li"}}) {
2392 $result->{"li"}->{$k} = $v;
2395 if ($one->{"lid"}) {
2396 while (($k, $v) = each %{$one->{"lid"}}) {
2397 $result->{"lid"}->{$k} = $v;
2403 $result = cancel_lineitem($mgr, $li_id, $cancel_reason) or
2404 return $e->die_event;
2406 if (not_cancelable($result)) {
2409 } elsif ($result == -1) {
2411 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2415 if ($batched and not scalar keys %{$result->{"li"}}) {
2417 return $maybe_event;
2419 $e->commit or return $e->die_event;
2420 # create_lineitem_status_events should handle array li_id ok
2421 create_lineitem_status_events($mgr, $li_id, "aur.cancelled");
2423 if ($mgr->{post_commit}) {
2424 foreach my $func (@{$mgr->{post_commit}}) {
2433 sub cancel_lineitem {
2434 my ($mgr, $li_id, $cancel_reason) = @_;
2435 my $li = $mgr->editor->retrieve_acq_lineitem([
2436 $li_id, {flesh => 1, flesh_fields => {jub => ['purchase_order']}}
2439 return 0 unless $mgr->editor->allowed(
2440 "CREATE_PURCHASE_ORDER", $li->purchase_order->ordering_agency
2443 # Depending on context, this may not warrant an event.
2444 return -1 if $li->state eq "cancelled";
2446 # But this always does.
2447 return new OpenILS::Event(
2448 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id"
2450 (! $li->purchase_order) or (
2451 $li->purchase_order and (
2452 $li->state eq "on-order" or $li->state eq "pending-order"
2457 $li->state("cancelled");
2458 $li->cancel_reason($cancel_reason->id);
2460 my $lids = $mgr->editor->search_acq_lineitem_detail([{
2461 "lineitem" => $li_id
2464 flesh_fields => { acqlid => ['eg_copy_id'] }
2467 my $result = {"lid" => {}};
2469 foreach my $lid (@$lids) {
2470 my $lid_result = cancel_lineitem_detail($mgr, $lid->id, $cancel_reason)
2473 # gathering any real copies for deletion
2474 if ($lid->eg_copy_id) {
2475 $lid->eg_copy_id->isdeleted('t');
2476 push @$copies, $lid->eg_copy_id;
2479 next if $lid_result == -1; # already canceled: just skip it.
2480 return $lid_result if not_cancelable($lid_result); # not cxlable: stop.
2482 # Merge in each LID result (there's only going to be one per call to
2483 # cancel_lineitem_detail).
2484 my ($k, $v) = each %{$lid_result->{"lid"}};
2485 $result->{"lid"}->{$k} = $v;
2488 # Attempt to delete the gathered copies (this will also handle volume deletion and bib deletion)
2489 # Delete empty bibs according org unit setting
2490 my $force_delete_empty_bib = $U->ou_ancestor_setting_value(
2491 $mgr->editor->requestor->ws_ou, 'cat.bib.delete_on_no_copy_via_acq_lineitem_cancel', $mgr->editor);
2492 if (scalar(@$copies)>0) {
2494 my $delete_stats = undef;
2495 my $retarget_holds = [];
2496 my $cat_evt = OpenILS::Application::Cat::AssetCommon->update_fleshed_copies(
2497 $mgr->editor, $override, undef, $copies, $delete_stats, $retarget_holds,$force_delete_empty_bib);
2500 $logger->info("fleshed copy update failed with event: ".OpenSRF::Utils::JSON->perl2JSON($cat_evt));
2501 return new OpenILS::Event(
2502 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id", "payload" => $cat_evt
2506 # We can't do the following and stay within the same transaction, but that's okay, the hold targeter will pick these up later.
2507 #my $ses = OpenSRF::AppSession->create('open-ils.circ');
2508 #$ses->request('open-ils.circ.hold.reset.batch', $auth, $retarget_holds);
2511 # if we have a bib, check to see whether it has been deleted. if so, cancel any active holds targeting that bib
2512 if ($li->eg_bib_id) {
2513 my $bib = $mgr->editor->retrieve_biblio_record_entry($li->eg_bib_id) or return new OpenILS::Event(
2514 "ACQ_NOT_CANCELABLE", "note" => "Could not retrieve bib " . $li->eg_bib_id . " for lineitem $li_id"
2516 if ($U->is_true($bib->deleted)) {
2517 my $holds = $mgr->editor->search_action_hold_request(
2518 { cancel_time => undef,
2519 fulfillment_time => undef,
2520 target => $li->eg_bib_id
2524 my %cached_usr_home_ou = ();
2526 for my $hold (@$holds) {
2528 $logger->info("Cancelling hold ".$hold->id.
2529 " due to acq lineitem cancellation.");
2531 $hold->cancel_time('now');
2532 $hold->cancel_cause(5); # 'Staff forced'--we may want a new hold cancel cause reason for this
2533 $hold->cancel_note('Corresponding Acquistion Lineitem/Purchase Order was cancelled.');
2534 unless($mgr->editor->update_action_hold_request($hold)) {
2535 my $evt = $mgr->editor->event;
2536 $logger->error("Error updating hold ". $evt->textcode .":". $evt->desc .":". $evt->stacktrace);
2537 return new OpenILS::Event(
2538 "ACQ_NOT_CANCELABLE", "note" => "Could not cancel hold " . $hold->id . " for lineitem $li_id", "payload" => $evt
2541 if (! defined $mgr->{post_commit}) { # we need a mechanism for creating trigger events, but only if the transaction gets committed
2542 $mgr->{post_commit} = [];
2544 push @{ $mgr->{post_commit} }, sub {
2545 my $home_ou = $cached_usr_home_ou{$hold->usr};
2547 my $user = $mgr->editor->retrieve_actor_user($hold->usr); # FIXME: how do we want to handle failures here?
2548 $home_ou = $user->home_ou;
2549 $cached_usr_home_ou{$hold->usr} = $home_ou;
2551 $U->create_events_for_hook('hold_request.cancel.cancelled_order', $hold, $home_ou);
2557 update_lineitem($mgr, $li) or return 0;
2560 "state" => $li->state,
2561 "cancel_reason" => $cancel_reason
2568 __PACKAGE__->register_method(
2569 method => "cancel_lineitem_detail_api",
2570 api_name => "open-ils.acq.lineitem_detail.cancel",
2572 desc => q/Cancels an on-order lineitem detail/,
2574 {desc => "Authentication token", type => "string"},
2575 {desc => "Lineitem detail ID to cancel", type => "number"},
2576 {desc => "Cancel reason ID", type => "number"}
2578 return => {desc => q/Object describing changed LIDs on success;
2583 sub cancel_lineitem_detail_api {
2584 my ($self, $conn, $auth, $lid_id, $cancel_reason) = @_;
2586 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2587 return $e->die_event unless $e->checkauth;
2588 my $mgr = new OpenILS::Application::Acq::BatchManager(
2589 "editor" => $e, "conn" => $conn
2592 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2593 return new OpenILS::Event(
2594 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2597 my $result = cancel_lineitem_detail($mgr, $lid_id, $cancel_reason) or
2598 return $e->die_event;
2600 if (not_cancelable($result)) {
2603 } elsif ($result == -1) {
2605 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2608 $e->commit or return $e->die_event;
2610 # XXX create lineitem detail status events?
2614 sub cancel_lineitem_detail {
2615 my ($mgr, $lid_id, $cancel_reason) = @_;
2616 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
2620 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
2625 # Depending on context, this may not warrant an event.
2626 return -1 if $lid->cancel_reason;
2628 # But this always does.
2629 return new OpenILS::Event(
2630 "ACQ_NOT_CANCELABLE", "note" => "lineitem_detail $lid_id"
2632 (! $lid->lineitem->purchase_order) or
2634 (not $lid->recv_time) and
2636 $lid->lineitem->purchase_order and (
2637 $lid->lineitem->state eq "on-order" or
2638 $lid->lineitem->state eq "pending-order"
2643 return 0 unless $mgr->editor->allowed(
2644 "CREATE_PURCHASE_ORDER",
2645 $lid->lineitem->purchase_order->ordering_agency
2646 ) or (! $lid->lineitem->purchase_order);
2648 $lid->cancel_reason($cancel_reason->id);
2650 unless($U->is_true($cancel_reason->keep_debits)) {
2651 my $debit_id = $lid->fund_debit;
2652 $lid->clear_fund_debit;
2655 # item is cancelled. Remove the fund debit.
2656 my $debit = $mgr->editor->retrieve_acq_fund_debit($debit_id);
2657 if (!$U->is_true($debit->encumbrance)) {
2658 $mgr->editor->rollback;
2659 return OpenILS::Event->new('ACQ_NOT_CANCELABLE',
2660 note => "Debit is marked as paid: $debit_id");
2662 $mgr->editor->delete_acq_fund_debit($debit) or return $mgr->editor->die_event;
2666 # XXX LIDs don't have either an editor or a edit_time field. Should we
2667 # update these on the LI when we alter an LID?
2668 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
2670 return {"lid" => {$lid_id => {"cancel_reason" => $cancel_reason}}};
2674 __PACKAGE__->register_method(
2675 method => 'user_requests',
2676 api_name => 'open-ils.acq.user_request.retrieve.by_user_id',
2679 desc => 'Retrieve fleshed user requests and related data for a given user.',
2681 { desc => 'Authentication token', type => 'string' },
2682 { desc => 'User ID of the owner, or array of IDs', },
2683 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
2688 desc => 'Fleshed user requests and related data',
2694 __PACKAGE__->register_method(
2695 method => 'user_requests',
2696 api_name => 'open-ils.acq.user_request.retrieve.by_home_ou',
2699 desc => 'Retrieve fleshed user requests and related data for a given org unit or units.',
2701 { desc => 'Authentication token', type => 'string' },
2702 { desc => 'Org unit ID, or array of IDs', },
2703 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
2708 desc => 'Fleshed user requests and related data',
2715 my($self, $conn, $auth, $search_value, $options) = @_;
2716 my $e = new_editor(authtoken => $auth);
2717 return $e->event unless $e->checkauth;
2718 my $rid = $e->requestor->id;
2722 "select"=>{"aur"=>["id"],"au"=>["home_ou", {column => 'id', alias => 'usr_id'} ]},
2723 "from"=>{ "aur" => { "au" => {}, "jub" => { "type" => "left" } } },
2727 {"id"=>undef}, # this with the left-join pulls in requests without lineitems
2728 {"state"=>["new","on-order","pending-order"]} # FIXME - probably needs softcoding
2732 "order_by"=>[{"class"=>"aur", "field"=>"request_date", "direction"=>"desc"}]
2735 foreach (qw/ order_by limit offset /) {
2736 $query->{$_} = $options->{$_} if defined $options->{$_};
2738 if (defined $options->{'state'}) {
2739 $query->{'where'}->{'+jub'}->{'-or'}->[1]->{'state'} = $options->{'state'};
2742 if ($self->api_name =~ /by_user_id/) {
2743 $query->{'where'}->{'usr'} = $search_value;
2745 $query->{'where'}->{'+au'} = { 'home_ou' => $search_value };
2748 my $pertinent_ids = $e->json_query($query);
2751 for my $id_blob (@$pertinent_ids) {
2752 if ($rid != $id_blob->{usr_id}) {
2753 if (!defined $perm_test{ $id_blob->{home_ou} }) {
2754 $perm_test{ $id_blob->{home_ou} } = $e->allowed( ['user_request.view'], $id_blob->{home_ou} );
2756 if (!$perm_test{ $id_blob->{home_ou} }) {
2760 my $aur_obj = $e->retrieve_acq_user_request([
2762 {flesh => 1, flesh_fields => { "aur" => [ 'lineitem' ] } }
2764 if (! $aur_obj) { next; }
2766 if ($aur_obj->lineitem()) {
2767 $aur_obj->lineitem()->clear_marc();
2769 $conn->respond($aur_obj);
2775 __PACKAGE__->register_method (
2776 method => 'update_user_request',
2777 api_name => 'open-ils.acq.user_request.cancel.batch',
2780 desc => 'If given a cancel reason, will update the request with that reason, otherwise, this will delete the request altogether. The ' .
2781 'intention is for staff interfaces or processes to provide cancel reasons, and for patron interfaces to just delete the requests.' ,
2783 { desc => 'Authentication token', type => 'string' },
2784 { desc => 'ID or array of IDs for the user requests to cancel' },
2785 { desc => 'Cancel Reason ID (optional)', type => 'string' }
2788 desc => 'progress object, event on error',
2792 __PACKAGE__->register_method (
2793 method => 'update_user_request',
2794 api_name => 'open-ils.acq.user_request.set_no_hold.batch',
2797 desc => 'Remove the hold from a user request or set of requests',
2799 { desc => 'Authentication token', type => 'string' },
2800 { desc => 'ID or array of IDs for the user requests to modify' }
2803 desc => 'progress object, event on error',
2808 sub update_user_request {
2809 my($self, $conn, $auth, $aur_ids, $cancel_reason) = @_;
2810 my $e = new_editor(xact => 1, authtoken => $auth);
2811 return $e->die_event unless $e->checkauth;
2812 my $rid = $e->requestor->id;
2816 for my $id (@$aur_ids) {
2818 my $aur_obj = $e->retrieve_acq_user_request([
2821 flesh_fields => { "aur" => ['lineitem', 'usr'] }
2823 ]) or return $e->die_event;
2825 my $context_org = $aur_obj->usr()->home_ou();
2826 $aur_obj->usr( $aur_obj->usr()->id() );
2828 if ($rid != $aur_obj->usr) {
2829 if (!defined $perm_test{ $context_org }) {
2830 $perm_test{ $context_org } = $e->allowed( ['user_request.update'], $context_org );
2832 if (!$perm_test{ $context_org }) {
2837 if($self->api_name =~ /set_no_hold/) {
2838 if ($U->is_true($aur_obj->hold)) {
2840 $e->update_acq_user_request($aur_obj) or return $e->die_event;
2844 if($self->api_name =~ /cancel/) {
2845 if ( $cancel_reason ) {
2846 $aur_obj->cancel_reason( $cancel_reason );
2847 $e->update_acq_user_request($aur_obj) or return $e->die_event;
2848 create_user_request_events( $e, [ $aur_obj ], 'aur.rejected' );
2850 $e->delete_acq_user_request($aur_obj);
2854 $conn->respond({maximum => scalar(@$aur_ids), progress => $x++});
2858 return {complete => 1};
2861 __PACKAGE__->register_method (
2862 method => 'new_user_request',
2863 api_name => 'open-ils.acq.user_request.create',
2865 desc => 'Create a new user request object in the DB',
2867 { desc => 'Authentication token', type => 'string' },
2868 { desc => 'User request data hash. Hash keys match the fields for the "aur" object', type => 'object' }
2871 desc => 'The created user request object, or event on error'
2876 sub new_user_request {
2877 my($self, $conn, $auth, $form_data) = @_;
2878 my $e = new_editor(xact => 1, authtoken => $auth);
2879 return $e->die_event unless $e->checkauth;
2880 my $rid = $e->requestor->id;
2881 my $target_user_fleshed;
2882 if (! defined $$form_data{'usr'}) {
2883 $$form_data{'usr'} = $rid;
2885 if ($$form_data{'usr'} != $rid) {
2886 # See if the requestor can place the request on behalf of a different user.
2887 $target_user_fleshed = $e->retrieve_actor_user($$form_data{'usr'}) or return $e->die_event;
2888 $e->allowed('user_request.create', $target_user_fleshed->home_ou) or return $e->die_event;
2890 $target_user_fleshed = $e->requestor;
2891 $e->allowed('CREATE_PURCHASE_REQUEST') or return $e->die_event;
2893 if (! defined $$form_data{'pickup_lib'}) {
2894 if ($target_user_fleshed->ws_ou) {
2895 $$form_data{'pickup_lib'} = $target_user_fleshed->ws_ou;
2897 $$form_data{'pickup_lib'} = $target_user_fleshed->home_ou;
2900 if (! defined $$form_data{'request_type'}) {
2901 $$form_data{'request_type'} = 1; # Books
2903 my $aur_obj = new Fieldmapper::acq::user_request;
2905 $aur_obj->usr( $$form_data{'usr'} );
2906 $aur_obj->request_date( 'now' );
2907 for my $field ( keys %$form_data ) {
2908 if (defined $$form_data{$field} and $field !~ /^(id|lineitem|eg_bib|request_date|cancel_reason)$/) {
2909 $aur_obj->$field( $$form_data{$field} );
2913 $aur_obj = $e->create_acq_user_request($aur_obj) or return $e->die_event;
2915 $e->commit and create_user_request_events( $e, [ $aur_obj ], 'aur.created' );
2920 sub create_user_request_events {
2921 my($e, $user_reqs, $hook) = @_;
2923 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
2926 my %cached_usr_home_ou = ();
2927 for my $user_req (@$user_reqs) {
2928 my $home_ou = $cached_usr_home_ou{$user_req->usr};
2930 my $user = $e->retrieve_actor_user($user_req->usr) or return $e->die_event;
2931 $home_ou = $user->home_ou;
2932 $cached_usr_home_ou{$user_req->usr} = $home_ou;
2934 my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $home_ou);
2943 __PACKAGE__->register_method(
2944 method => "po_note_CUD_batch",
2945 api_name => "open-ils.acq.po_note.cud.batch",
2948 desc => q/Manage purchase order notes/,
2950 {desc => "Authentication token", type => "string"},
2951 {desc => "List of po_notes to manage", type => "array"},
2953 return => {desc => "Stream of successfully managed objects"}
2957 sub po_note_CUD_batch {
2958 my ($self, $conn, $auth, $notes) = @_;
2960 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
2961 return $e->die_event unless $e->checkauth;
2964 my $total = @$notes;
2967 foreach my $note (@$notes) {
2969 $note->editor($e->requestor->id);
2970 $note->edit_time("now");
2973 $note->creator($e->requestor->id);
2974 $note = $e->create_acq_po_note($note) or return $e->die_event;
2975 } elsif ($note->isdeleted) {
2976 $e->delete_acq_po_note($note) or return $e->die_event;
2977 } elsif ($note->ischanged) {
2978 $e->update_acq_po_note($note) or return $e->die_event;
2981 unless ($note->isdeleted) {
2982 $note = $e->retrieve_acq_po_note($note->id) or
2983 return $e->die_event;
2987 {"maximum" => $total, "progress" => ++$count, "note" => $note}
2991 $e->commit and $conn->respond_complete or return $e->die_event;
2995 # retrieves a lineitem, fleshes its PO and PL, checks perms
2996 sub fetch_and_check_li {
2999 my $perm_mode = shift || 'read';
3001 my $li = $e->retrieve_acq_lineitem([
3004 flesh_fields => {jub => ['purchase_order', 'picklist']}
3006 ]) or return $e->die_event;
3008 if(my $po = $li->purchase_order) {
3009 my $perms = ($perm_mode eq 'read') ? 'VIEW_PURCHASE_ORDER' : 'CREATE_PURCHASE_ORDER';
3010 return ($li, $e->die_event) unless $e->allowed($perms, $po->ordering_agency);
3012 } elsif(my $pl = $li->picklist) {
3013 my $perms = ($perm_mode eq 'read') ? 'VIEW_PICKLIST' : 'CREATE_PICKLIST';
3014 return ($li, $e->die_event) unless $e->allowed($perms, $pl->org_unit);