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_attrs($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) = @_;
649 my $li_id = ref($li) ? $li->id : $li;
651 unless(ref $li and ref $li->provider) {
652 $li = $mgr->editor->retrieve_acq_lineitem([
655 flesh_fields => {jub => ['provider']},
660 unless(ref $lid and ref $lid->fund) {
661 $lid = $mgr->editor->retrieve_acq_lineitem_detail([
664 flesh_fields => {acqlid => ['fund']}
669 my $amount = $li->estimated_unit_price;
670 if($li->provider->currency_type ne $lid->fund->currency_type) {
672 # At Fund debit creation time, translate into the currency of the fund
673 # TODO: org setting to disable automatic currency conversion at debit create time?
675 $amount = $mgr->editor->json_query({
677 'acq.exchange_ratio',
678 $li->provider->currency_type, # source currency
679 $lid->fund->currency_type, # destination currency
680 $li->estimated_unit_price # source amount
685 my $debit = create_fund_debit(
688 fund => $lid->fund->id,
689 origin_amount => $li->estimated_unit_price,
690 origin_currency_type => $li->provider->currency_type,
694 $lid->fund_debit($debit->id);
695 $lid->fund($lid->fund->id);
696 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
701 __PACKAGE__->register_method(
702 "method" => "fund_exceeds_balance_percent_api",
703 "api_name" => "open-ils.acq.fund.check_balance_percentages",
705 "desc" => q/Determine whether a given fund exceeds its defined
706 "balance stop and warning percentages"/,
708 {"desc" => "Authentication token", "type" => "string"},
709 {"desc" => "Fund ID", "type" => "number"},
710 {"desc" => "Theoretical debit amount (optional)",
713 "return" => {"desc" => q/An array of two values, for stop and warning,
714 in that order: 1 if fund exceeds that balance percentage, else 0/}
718 sub fund_exceeds_balance_percent_api {
719 my ($self, $conn, $auth, $fund_id, $debit_amount) = @_;
723 my $e = new_editor("authtoken" => $auth);
724 return $e->die_event unless $e->checkauth;
726 my $fund = $e->retrieve_acq_fund($fund_id) or return $e->die_event;
727 return $e->die_event unless $e->allowed("VIEW_FUND", $fund->org);
730 fund_exceeds_balance_percent($fund, $debit_amount, $e, "stop"),
731 fund_exceeds_balance_percent($fund, $debit_amount, $e, "warning")
738 sub fund_exceeds_balance_percent {
739 my ($fund, $debit_amount, $e, $which) = @_;
741 my ($method_name, $event_name) = @{{
743 "balance_warning_percent", "ACQ_FUND_EXCEEDS_WARN_PERCENT"
746 "balance_stop_percent", "ACQ_FUND_EXCEEDS_STOP_PERCENT"
750 if ($fund->$method_name) {
752 $e->search_acq_fund_combined_balance({"fund" => $fund->id})->[0];
754 $e->search_acq_fund_allocation_total({"fund" => $fund->id})->[0];
756 $balance = ($balance) ? $balance->amount : 0;
757 $allocations = ($allocations) ? $allocations->amount : 0;
760 $allocations == 0 || # if no allocations were ever made, assume we have hit the stop percent
761 ((($balance - $debit_amount) / $allocations) * 100) <
769 "debit_amount" => $debit_amount
779 # ----------------------------------------------------------------------------
781 # ----------------------------------------------------------------------------
782 sub create_fund_debit {
783 my($mgr, $dry_run, %args) = @_;
785 # Verify the fund is not being spent beyond the hard stop amount
786 my $fund = $mgr->editor->retrieve_acq_fund($args{fund}) or return 0;
789 fund_exceeds_balance_percent(
790 $fund, $args{"amount"}, $mgr->editor, "stop"
793 $dry_run and fund_exceeds_balance_percent(
794 $fund, $args{"amount"}, $mgr->editor, "warning"
797 my $debit = Fieldmapper::acq::fund_debit->new;
798 $debit->debit_type('purchase');
799 $debit->encumbrance('t');
800 $debit->$_($args{$_}) for keys %args;
802 $mgr->add_debit($debit->amount);
803 return $mgr->editor->create_acq_fund_debit($debit);
807 # ----------------------------------------------------------------------------
809 # ----------------------------------------------------------------------------
810 sub create_picklist {
811 my($mgr, %args) = @_;
812 my $picklist = Fieldmapper::acq::picklist->new;
813 $picklist->creator($mgr->editor->requestor->id);
814 $picklist->owner($picklist->creator);
815 $picklist->editor($picklist->creator);
816 $picklist->create_time('now');
817 $picklist->edit_time('now');
818 $picklist->org_unit($mgr->editor->requestor->ws_ou);
819 $picklist->owner($mgr->editor->requestor->id);
820 $picklist->$_($args{$_}) for keys %args;
822 $mgr->picklist($picklist);
823 return $mgr->editor->create_acq_picklist($picklist);
826 sub update_picklist {
827 my($mgr, $picklist) = @_;
828 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
829 $picklist->edit_time('now');
830 $picklist->editor($mgr->editor->requestor->id);
831 $mgr->picklist($picklist);
832 return $picklist if $mgr->editor->update_acq_picklist($picklist);
836 sub delete_picklist {
837 my($mgr, $picklist) = @_;
838 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
840 # delete all 'new' lineitems
841 my $li_ids = $mgr->editor->search_acq_lineitem({picklist => $picklist->id, state => 'new'}, {idlist => 1});
842 for my $li_id (@$li_ids) {
843 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
844 return 0 unless delete_lineitem($mgr, $li);
848 # detach all non-'new' lineitems
849 $li_ids = $mgr->editor->search_acq_lineitem({picklist => $picklist->id, state => {'!=' => 'new'}}, {idlist => 1});
850 for my $li_id (@$li_ids) {
851 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
853 return 0 unless update_lineitem($mgr, $li);
857 # remove any picklist-specific object perms
858 my $ops = $mgr->editor->search_permission_usr_object_perm_map({object_type => 'acqpl', object_id => ''.$picklist->id});
860 return 0 unless $mgr->editor->delete_usr_object_perm_map($op);
863 return $mgr->editor->delete_acq_picklist($picklist);
866 # ----------------------------------------------------------------------------
868 # ----------------------------------------------------------------------------
869 sub update_purchase_order {
871 $po = $mgr->editor->retrieve_acq_purchase_order($po) unless ref $po;
872 $po->editor($mgr->editor->requestor->id);
873 $po->edit_time('now');
874 $mgr->purchase_order($po);
875 return $mgr->editor->retrieve_acq_purchase_order($mgr->editor->data)
876 if $mgr->editor->update_acq_purchase_order($po);
880 sub create_purchase_order {
881 my($mgr, %args) = @_;
883 # verify the chosen provider is still active
884 my $provider = $mgr->editor->retrieve_acq_provider($args{provider}) or return 0;
885 unless($U->is_true($provider->active)) {
886 $logger->error("provider is not active. cannot create PO");
887 $mgr->editor->event(OpenILS::Event->new('ACQ_PROVIDER_INACTIVE'));
891 my $po = Fieldmapper::acq::purchase_order->new;
892 $po->creator($mgr->editor->requestor->id);
893 $po->editor($mgr->editor->requestor->id);
894 $po->owner($mgr->editor->requestor->id);
895 $po->edit_time('now');
896 $po->create_time('now');
897 $po->state('pending');
898 $po->ordering_agency($mgr->editor->requestor->ws_ou);
899 $po->$_($args{$_}) for keys %args;
901 $mgr->purchase_order($po);
902 return $mgr->editor->create_acq_purchase_order($po);
905 # ----------------------------------------------------------------------------
906 # if all of the lineitems for this PO are received,
907 # mark the PO as received
908 # ----------------------------------------------------------------------------
909 sub check_purchase_order_received {
910 my($mgr, $po_id) = @_;
912 my $non_recv_li = $mgr->editor->search_acq_lineitem(
913 { purchase_order => $po_id,
914 state => {'!=' => 'received'}
917 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id);
918 return $po if @$non_recv_li;
920 $po->state('received');
921 return update_purchase_order($mgr, $po);
925 # ----------------------------------------------------------------------------
926 # Bib, Callnumber, and Copy data
927 # ----------------------------------------------------------------------------
929 sub create_lineitem_assets {
930 my($mgr, $li_id) = @_;
933 my $li = $mgr->editor->retrieve_acq_lineitem([
936 flesh_fields => {jub => ['purchase_order', 'attributes']}
940 # -----------------------------------------------------------------
941 # first, create the bib record if necessary
942 # -----------------------------------------------------------------
944 unless($li->eg_bib_id) {
945 create_bib($mgr, $li) or return 0;
950 # -----------------------------------------------------------------
951 # The lineitem is going live, promote user request holds to real holds
952 # -----------------------------------------------------------------
953 promote_lineitem_holds($mgr, $li) or return 0;
955 my $li_details = $mgr->editor->search_acq_lineitem_detail({lineitem => $li_id}, {idlist=>1});
957 # -----------------------------------------------------------------
958 # for each lineitem_detail, create the volume if necessary, create
959 # a copy, and link them all together.
960 # -----------------------------------------------------------------
962 for my $lid_id (@{$li_details}) {
964 my $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid_id) or return 0;
965 next if $lid->eg_copy_id;
967 # use the same callnumber label for all items within this lineitem
968 $lid->cn_label($first_cn) if $first_cn and not $lid->cn_label;
970 # apply defaults if necessary
971 return 0 unless complete_lineitem_detail($mgr, $lid);
973 $first_cn = $lid->cn_label unless $first_cn;
975 my $org = $lid->owning_lib;
976 my $label = $lid->cn_label;
977 my $bibid = $li->eg_bib_id;
979 my $volume = $mgr->cache($org, "cn.$bibid.$label");
981 $volume = create_volume($mgr, $li, $lid) or return 0;
982 $mgr->cache($org, "cn.$bibid.$label", $volume);
984 create_copy($mgr, $volume, $lid) or return 0;
987 return { li => $li, new_bib => $new_bib };
993 my $record = OpenILS::Application::Cat::BibCommon->biblio_record_xml_import(
998 1, # override tcn collisions
1001 if($U->event_code($record)) {
1002 $mgr->editor->event($record);
1003 $mgr->editor->rollback;
1007 $li->eg_bib_id($record->id);
1009 return update_lineitem($mgr, $li);
1013 my($mgr, $li, $lid) = @_;
1015 my ($volume, $evt) =
1016 OpenILS::Application::Cat::AssetCommon->find_or_create_volume(
1024 $mgr->editor->event($evt);
1032 my($mgr, $volume, $lid) = @_;
1033 my $copy = Fieldmapper::asset::copy->new;
1035 $copy->loan_duration(2);
1036 $copy->fine_level(2);
1037 $copy->status(OILS_COPY_STATUS_ON_ORDER);
1038 $copy->barcode($lid->barcode);
1039 $copy->location($lid->location);
1040 $copy->call_number($volume->id);
1041 $copy->circ_lib($volume->owning_lib);
1042 $copy->circ_modifier($lid->circ_modifier);
1044 my $evt = OpenILS::Application::Cat::AssetCommon->create_copy($mgr->editor, $volume, $copy);
1046 $mgr->editor->event($evt);
1051 $lid->eg_copy_id($copy->id);
1052 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
1060 # ----------------------------------------------------------------------------
1061 # Workflow: Build a selection list from a Z39.50 search
1062 # ----------------------------------------------------------------------------
1064 __PACKAGE__->register_method(
1065 method => 'zsearch',
1066 api_name => 'open-ils.acq.picklist.search.z3950',
1069 desc => 'Performs a z3950 federated search and creates a picklist and associated lineitems',
1071 {desc => 'Authentication token', type => 'string'},
1072 {desc => 'Search definition', type => 'object'},
1073 {desc => 'Picklist name, optional', type => 'string'},
1079 my($self, $conn, $auth, $search, $name, $options) = @_;
1080 my $e = new_editor(authtoken=>$auth);
1081 return $e->event unless $e->checkauth;
1082 return $e->event unless $e->allowed('CREATE_PICKLIST');
1084 $search->{limit} ||= 10;
1087 my $ses = OpenSRF::AppSession->create('open-ils.search');
1088 my $req = $ses->request('open-ils.search.z3950.search_class', $auth, $search);
1093 while(my $resp = $req->recv(timeout=>60)) {
1096 my $e = new_editor(requestor=>$e->requestor, xact=>1);
1097 $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1098 $picklist = zsearch_build_pl($mgr, $name);
1102 my $result = $resp->content;
1103 my $count = $result->{count} || 0;
1104 $mgr->total( (($count < $search->{limit}) ? $count : $search->{limit})+1 );
1106 for my $rec (@{$result->{records}}) {
1108 my $li = create_lineitem($mgr,
1109 picklist => $picklist->id,
1110 source_label => $result->{service},
1111 marc => $rec->{marcxml},
1112 eg_bib_id => $rec->{bibid}
1115 if($$options{respond_li}) {
1116 $li->attributes($mgr->editor->search_acq_lineitem_attr({lineitem => $li->id}))
1117 if $$options{flesh_attrs};
1118 $li->clear_marc if $$options{clear_marc};
1119 $mgr->respond(lineitem => $li);
1126 $mgr->editor->commit;
1127 return $mgr->respond_complete;
1130 sub zsearch_build_pl {
1131 my($mgr, $name) = @_;
1134 my $picklist = $mgr->editor->search_acq_picklist({
1135 owner => $mgr->editor->requestor->id,
1139 if($name eq '' and $picklist) {
1140 return 0 unless delete_picklist($mgr, $picklist);
1144 return update_picklist($mgr, $picklist) if $picklist;
1145 return create_picklist($mgr, name => $name);
1149 # ----------------------------------------------------------------------------
1150 # Workflow: Build a selection list / PO by importing a batch of MARC records
1151 # ----------------------------------------------------------------------------
1153 __PACKAGE__->register_method(
1154 method => 'upload_records',
1155 api_name => 'open-ils.acq.process_upload_records',
1159 sub upload_records {
1160 my($self, $conn, $auth, $key) = @_;
1162 my $e = new_editor(authtoken => $auth, xact => 1);
1163 return $e->die_event unless $e->checkauth;
1164 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1166 my $cache = OpenSRF::Utils::Cache->new;
1168 my $data = $cache->get_cache("vandelay_import_spool_$key");
1169 my $purpose = $data->{purpose};
1170 my $filename = $data->{path};
1171 my $provider = $data->{provider};
1172 my $picklist = $data->{picklist};
1173 my $create_po = $data->{create_po};
1174 my $activate_po = $data->{activate_po};
1175 my $ordering_agency = $data->{ordering_agency};
1176 my $create_assets = $data->{create_assets};
1180 unless(-r $filename) {
1181 $logger->error("unable to read MARC file $filename");
1183 return OpenILS::Event->new('FILE_UPLOAD_ERROR', payload => {filename => $filename});
1186 $provider = $e->retrieve_acq_provider($provider) or return $e->die_event;
1189 $picklist = $e->retrieve_acq_picklist($picklist) or return $e->die_event;
1190 if($picklist->owner != $e->requestor->id) {
1191 return $e->die_event unless
1192 $e->allowed('CREATE_PICKLIST', $picklist->org_unit, $picklist);
1194 $mgr->picklist($picklist);
1199 $po = create_purchase_order($mgr,
1200 ordering_agency => $ordering_agency,
1201 provider => $provider->id,
1203 ) or return $mgr->editor->die_event;
1206 $logger->info("acq processing MARC file=$filename");
1208 my $marctype = 'USMARC'; # ?
1209 my $batch = new MARC::Batch ($marctype, $filename);
1224 } catch Error with {
1226 $logger->warn("Proccessing of record $count in set $key failed with error $err. Skipping this record");
1233 ($xml = $r->as_xml_record()) =~ s/\n//sog;
1234 $xml =~ s/^<\?xml.+\?\s*>//go;
1235 $xml =~ s/>\s+</></go;
1236 $xml =~ s/\p{Cc}//go;
1237 $xml = $U->entityize($xml);
1238 $xml =~ s/[\x00-\x1f]//go;
1240 } catch Error with {
1242 $logger->warn("Proccessing XML of record $count in set $key failed with error $err. Skipping this record");
1245 next if $err or not $xml;
1248 source_label => $provider->code,
1249 provider => $provider->id,
1253 $args{picklist} = $picklist->id if $picklist;
1255 $args{purchase_order} = $po->id;
1256 $args{state} = 'order-pending';
1259 my $li = create_lineitem($mgr, %args) or return $mgr->editor->die_event;
1261 $li->provider($provider); # flesh it, we'll need it later
1263 import_lineitem_details($mgr, $ordering_agency, $li) or return $mgr->editor->die_event;
1266 push(@li_list, $li->id);
1270 my $die_event = activate_purchase_order_impl($mgr, $po->id) if $po;;
1271 return $die_event if $die_event;
1275 $cache->delete_cache('vandelay_import_spool_' . $key);
1277 if($create_assets) {
1278 create_lineitem_list_assets($mgr, \@li_list) or return $e->die_event;
1281 return $mgr->respond_complete;
1284 sub import_lineitem_details {
1285 my($mgr, $ordering_agency, $li) = @_;
1287 my $holdings = $mgr->editor->json_query({from => ['acq.extract_provider_holding_data', $li->id]});
1288 return 1 unless @$holdings;
1289 my $org_path = $U->get_org_ancestors($ordering_agency);
1290 $org_path = [ reverse (@$org_path) ];
1295 # create a lineitem detail for each copy in the data
1297 my $compiled = extract_lineitem_detail_data($mgr, $org_path, $holdings, $idx);
1298 last unless defined $compiled;
1299 return 0 unless $compiled;
1301 # this takes the price of the last copy and uses it as the lineitem price
1302 # need to determine if a given record would include different prices for the same item
1303 $price = $$compiled{price};
1305 for(1..$$compiled{quantity}) {
1306 my $lid = create_lineitem_detail($mgr,
1307 lineitem => $li->id,
1308 owning_lib => $$compiled{owning_lib},
1309 cn_label => $$compiled{call_number},
1310 fund => $$compiled{fund},
1311 circ_modifier => $$compiled{circ_modifier},
1312 note => $$compiled{note},
1313 location => $$compiled{copy_location},
1314 collection_code => $$compiled{collection_code}
1322 $li->estimated_unit_price($price);
1323 update_lineitem($mgr, $li) or return 0;
1327 # return hash on success, 0 on error, undef on no more holdings
1328 sub extract_lineitem_detail_data {
1329 my($mgr, $org_path, $holdings, $index) = @_;
1331 my @data_list = grep { $_->{holding} eq $index } @$holdings;
1332 return undef unless @data_list;
1334 my %compiled = map { $_->{attr} => $_->{data} } @data_list;
1335 my $base_org = $$org_path[0];
1339 $logger->error("Item import extraction error: $msg");
1340 $logger->error('Holdings Data: ' . OpenSRF::Utils::JSON->perl2JSON(\%compiled));
1341 $mgr->editor->rollback;
1342 $mgr->editor->event(OpenILS::Event->new('ACQ_IMPORT_ERROR', payload => $msg));
1346 $compiled{quantity} ||= 1;
1348 # ---------------------------------------------------------------------
1350 my $code = $compiled{fund_code};
1351 return $killme->('no fund code provided') unless $code;
1353 my $fund = $mgr->cache($base_org, "fund.$code");
1355 # search up the org tree for the most appropriate fund
1356 for my $org (@$org_path) {
1357 $fund = $mgr->editor->search_acq_fund(
1358 {org => $org, code => $code, year => DateTime->now->year}, {idlist => 1})->[0];
1362 return $killme->("no fund with code $code at orgs [@$org_path]") unless $fund;
1363 $compiled{fund} = $fund;
1364 $mgr->cache($base_org, "fund.$code", $fund);
1367 # ---------------------------------------------------------------------
1369 my $sn = $compiled{owning_lib};
1370 return $killme->('no owning_lib defined') unless $sn;
1372 $mgr->cache($base_org, "orgsn.$sn") ||
1373 $mgr->editor->search_actor_org_unit({shortname => $sn}, {idlist => 1})->[0];
1374 return $killme->("invalid owning_lib defined: $sn") unless $org_id;
1375 $compiled{owning_lib} = $org_id;
1376 $mgr->cache($$org_path[0], "orgsn.$sn", $org_id);
1379 # ---------------------------------------------------------------------
1382 $code = $compiled{circ_modifier};
1386 $mod = $mgr->cache($base_org, "mod.$code") ||
1387 $mgr->editor->retrieve_config_circ_modifier($code);
1388 return $killme->("invlalid circ_modifier $code") unless $mod;
1389 $mgr->cache($base_org, "mod.$code", $mod);
1393 $mod = get_default_circ_modifier($mgr, $base_org)
1394 or return $killme->('no circ_modifier defined');
1397 $compiled{circ_modifier} = $mod;
1400 # ---------------------------------------------------------------------
1402 my $name = $compiled{copy_location};
1404 my $loc = $mgr->cache($base_org, "copy_loc.$name");
1406 for my $org (@$org_path) {
1407 $loc = $mgr->editor->search_asset_copy_location(
1408 {owning_lib => $org, name => $name}, {idlist => 1})->[0];
1412 return $killme->("Invalid copy location $name") unless $loc;
1413 $compiled{copy_location} = $loc;
1414 $mgr->cache($base_org, "copy_loc.$name", $loc);
1422 # ----------------------------------------------------------------------------
1423 # Workflow: Given an existing purchase order, import/create the bibs,
1424 # callnumber and copy objects
1425 # ----------------------------------------------------------------------------
1427 __PACKAGE__->register_method(
1428 method => 'create_po_assets',
1429 api_name => 'open-ils.acq.purchase_order.assets.create',
1431 desc => q/Creates assets for each lineitem in the purchase order/,
1433 {desc => 'Authentication token', type => 'string'},
1434 {desc => 'The purchase order id', type => 'number'},
1436 return => {desc => 'Streams a total versus completed counts object, event on error'}
1440 sub create_po_assets {
1441 my($self, $conn, $auth, $po_id) = @_;
1443 my $e = new_editor(authtoken=>$auth, xact=>1);
1444 return $e->die_event unless $e->checkauth;
1445 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1447 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1449 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1451 # it's ugly, but it's fast. Get the total count of lineitem detail objects to process
1452 my $lid_total = $e->json_query({
1453 select => { acqlid => [{aggregate => 1, transform => 'count', column => 'id'}] },
1459 join => {acqpo => {fkey => 'purchase_order', field => 'id'}}
1463 where => {'+acqpo' => {id => $po_id}}
1466 $mgr->total(scalar(@$li_ids) + $lid_total);
1468 create_lineitem_list_assets($mgr, $li_ids) or return $e->die_event;
1471 update_purchase_order($mgr, $po) or return $e->die_event;
1474 return $mgr->respond_complete;
1479 __PACKAGE__->register_method(
1480 method => 'create_purchase_order_api',
1481 api_name => 'open-ils.acq.purchase_order.create',
1483 desc => 'Creates a new purchase order',
1485 {desc => 'Authentication token', type => 'string'},
1486 {desc => 'purchase_order to create', type => 'object'}
1488 return => {desc => 'The purchase order id, Event on failure'}
1492 sub create_purchase_order_api {
1493 my($self, $conn, $auth, $po, $args) = @_;
1496 my $e = new_editor(xact=>1, authtoken=>$auth);
1497 return $e->die_event unless $e->checkauth;
1498 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
1499 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1502 my %pargs = (ordering_agency => $e->requestor->ws_ou); # default
1503 $pargs{provider} = $po->provider if $po->provider;
1504 $pargs{ordering_agency} = $po->ordering_agency if $po->ordering_agency;
1505 $pargs{prepayment_required} = $po->prepayment_required
1506 if $po->prepayment_required;
1507 $po = create_purchase_order($mgr, %pargs) or return $e->die_event;
1509 my $li_ids = $$args{lineitems};
1513 for my $li_id (@$li_ids) {
1515 my $li = $e->retrieve_acq_lineitem([
1517 {flesh => 1, flesh_fields => {jub => ['attributes']}}
1518 ]) or return $e->die_event;
1520 $li->provider($po->provider);
1521 $li->purchase_order($po->id);
1522 $li->state('pending-order');
1523 update_lineitem($mgr, $li) or return $e->die_event;
1528 # commit before starting the asset creation
1531 if($li_ids and $$args{create_assets}) {
1532 create_lineitem_list_assets($mgr, $li_ids) or return $e->die_event;
1535 return $mgr->respond_complete;
1539 __PACKAGE__->register_method(
1540 method => 'lineitem_detail_CUD_batch',
1541 api_name => 'open-ils.acq.lineitem_detail.cud.batch',
1544 desc => q/Creates a new purchase order line item detail.
1545 Additionally creates the associated fund_debit/,
1547 {desc => 'Authentication token', type => 'string'},
1548 {desc => 'List of lineitem_details to create', type => 'array'},
1550 return => {desc => 'Streaming response of current position in the array'}
1554 sub lineitem_detail_CUD_batch {
1555 my($self, $conn, $auth, $li_details) = @_;
1557 my $e = new_editor(xact=>1, authtoken=>$auth);
1558 return $e->die_event unless $e->checkauth;
1559 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1563 $mgr->total(scalar(@$li_details));
1567 for my $lid (@$li_details) {
1569 my $li = $li_cache{$lid->lineitem} || $e->retrieve_acq_lineitem($lid->lineitem);
1572 create_lineitem_detail($mgr, %{$lid->to_bare_hash}) or return $e->die_event;
1574 } elsif($lid->ischanged) {
1575 $e->update_acq_lineitem_detail($lid) or return $e->die_event;
1577 } elsif($lid->isdeleted) {
1578 delete_lineitem_detail($mgr, $lid) or return $e->die_event;
1581 $mgr->respond(li => $li);
1582 $li_cache{$lid->lineitem} = $li;
1586 return $mgr->respond_complete;
1590 __PACKAGE__->register_method(
1591 method => 'receive_po_api',
1592 api_name => 'open-ils.acq.purchase_order.receive'
1595 sub receive_po_api {
1596 my($self, $conn, $auth, $po_id) = @_;
1597 my $e = new_editor(xact => 1, authtoken => $auth);
1598 return $e->die_event unless $e->checkauth;
1599 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1601 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1602 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1604 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1606 for my $li_id (@$li_ids) {
1607 receive_lineitem($mgr, $li_id) or return $e->die_event;
1611 $po->state('received');
1612 update_purchase_order($mgr, $po) or return $e->die_event;
1615 return $mgr->respond_complete;
1619 # At the moment there's a lack of parallelism between the receive and unreceive
1620 # API methods for POs and the API methods for LIs and LIDs. The methods for
1621 # POs stream back objects as they act, whereas the methods for LIs and LIDs
1622 # atomically return an object that describes only what changed (in LIs and LIDs
1623 # themselves or in the objects to which to LIs and LIDs belong).
1625 # The methods for LIs and LIDs work the way they do to faciliate the UI's
1626 # maintaining correct information about the state of these things when a user
1627 # wants to receive or unreceive these objects without refreshing their whole
1628 # display. The UI feature for receiving and un-receiving a whole PO just
1629 # refreshes the whole display, so this absence of parallelism in the UI is also
1630 # relected in this module.
1632 # This could be neatened in the future by making POs receive and unreceive in
1633 # the same way the LIs and LIDs do.
1635 __PACKAGE__->register_method(
1636 method => 'receive_lineitem_detail_api',
1637 api_name => 'open-ils.acq.lineitem_detail.receive',
1639 desc => 'Mark a lineitem_detail as received',
1641 {desc => 'Authentication token', type => 'string'},
1642 {desc => 'lineitem detail ID', type => 'number'}
1645 "on success, object describing changes to LID and possibly " .
1646 "to LI and PO; on error, Event"
1651 sub receive_lineitem_detail_api {
1652 my($self, $conn, $auth, $lid_id) = @_;
1654 my $e = new_editor(xact=>1, authtoken=>$auth);
1655 return $e->die_event unless $e->checkauth;
1656 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1659 "flesh" => 2, "flesh_fields" => {
1660 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
1664 my $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1666 return $e->die_event unless $e->allowed(
1667 'RECEIVE_PURCHASE_ORDER', $lid->lineitem->purchase_order->ordering_agency);
1670 my $recvd = receive_lineitem_detail($mgr, $lid_id) or return $e->die_event;
1672 # .. and re-retrieve
1673 $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1675 # Now build result data structure.
1676 my $result = {"lid" => {$lid->id => {"recv_time" => $lid->recv_time}}};
1679 if ($recvd->class_name =~ /::purchase_order/) {
1680 $result->{"po"} = describe_affected_po($e, $recvd);
1682 $lid->lineitem->id => {"state" => $lid->lineitem->state}
1684 } elsif ($recvd->class_name =~ /::lineitem/) {
1685 $result->{"li"} = {$recvd->id => {"state" => $recvd->state}};
1689 describe_affected_po($e, $lid->lineitem->purchase_order);
1695 __PACKAGE__->register_method(
1696 method => 'receive_lineitem_api',
1697 api_name => 'open-ils.acq.lineitem.receive',
1699 desc => 'Mark a lineitem as received',
1701 {desc => 'Authentication token', type => 'string'},
1702 {desc => 'lineitem ID', type => 'number'}
1705 "on success, object describing changes to LI and possibly PO; " .
1711 sub receive_lineitem_api {
1712 my($self, $conn, $auth, $li_id) = @_;
1714 my $e = new_editor(xact=>1, authtoken=>$auth);
1715 return $e->die_event unless $e->checkauth;
1716 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1718 my $li = $e->retrieve_acq_lineitem([
1722 jub => ['purchase_order']
1725 ]) or return $e->die_event;
1727 return $e->die_event unless $e->allowed(
1728 'RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);
1730 my $res = receive_lineitem($mgr, $li_id) or return $e->die_event;
1732 $conn->respond_complete($res);
1733 $mgr->run_post_response_hooks;
1737 __PACKAGE__->register_method(
1738 method => 'rollback_receive_po_api',
1739 api_name => 'open-ils.acq.purchase_order.receive.rollback'
1742 sub rollback_receive_po_api {
1743 my($self, $conn, $auth, $po_id) = @_;
1744 my $e = new_editor(xact => 1, authtoken => $auth);
1745 return $e->die_event unless $e->checkauth;
1746 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1748 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1749 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1751 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1753 for my $li_id (@$li_ids) {
1754 rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
1758 $po->state('on-order');
1759 update_purchase_order($mgr, $po) or return $e->die_event;
1762 return $mgr->respond_complete;
1766 __PACKAGE__->register_method(
1767 method => 'rollback_receive_lineitem_detail_api',
1768 api_name => 'open-ils.acq.lineitem_detail.receive.rollback',
1770 desc => 'Mark a lineitem_detail as Un-received',
1772 {desc => 'Authentication token', type => 'string'},
1773 {desc => 'lineitem detail ID', type => 'number'}
1776 "on success, object describing changes to LID and possibly " .
1777 "to LI and PO; on error, Event"
1782 sub rollback_receive_lineitem_detail_api {
1783 my($self, $conn, $auth, $lid_id) = @_;
1785 my $e = new_editor(xact=>1, authtoken=>$auth);
1786 return $e->die_event unless $e->checkauth;
1787 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1789 my $lid = $e->retrieve_acq_lineitem_detail([
1793 acqlid => ['lineitem'],
1794 jub => ['purchase_order']
1798 my $li = $lid->lineitem;
1799 my $po = $li->purchase_order;
1801 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1805 my $recvd = rollback_receive_lineitem_detail($mgr, $lid_id)
1806 or return $e->die_event;
1809 $result->{"lid"} = {$recvd->id => {"recv_time" => $recvd->recv_time}};
1811 $result->{"lid"} = {$lid->id => {"recv_time" => $lid->recv_time}};
1814 if ($li->state eq "received") {
1815 $li->state("on-order");
1816 $li = update_lineitem($mgr, $li) or return $e->die_event;
1817 $result->{"li"} = {$li->id => {"state" => $li->state}};
1820 if ($po->state eq "received") {
1821 $po->state("on-order");
1822 $po = update_purchase_order($mgr, $po) or return $e->die_event;
1824 $result->{"po"} = describe_affected_po($e, $po);
1826 $e->commit and return $result or return $e->die_event;
1829 __PACKAGE__->register_method(
1830 method => 'rollback_receive_lineitem_api',
1831 api_name => 'open-ils.acq.lineitem.receive.rollback',
1833 desc => 'Mark a lineitem as Un-received',
1835 {desc => 'Authentication token', type => 'string'},
1836 {desc => 'lineitem ID', type => 'number'}
1839 "on success, object describing changes to LI and possibly PO; " .
1845 sub rollback_receive_lineitem_api {
1846 my($self, $conn, $auth, $li_id) = @_;
1848 my $e = new_editor(xact=>1, authtoken=>$auth);
1849 return $e->die_event unless $e->checkauth;
1850 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1852 my $li = $e->retrieve_acq_lineitem([
1854 "flesh" => 1, "flesh_fields" => {"jub" => ["purchase_order"]}
1857 my $po = $li->purchase_order;
1859 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1861 $li = rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
1863 my $result = {"li" => {$li->id => {"state" => $li->state}}};
1864 if ($po->state eq "received") {
1865 $po->state("on-order");
1866 $po = update_purchase_order($mgr, $po) or return $e->die_event;
1868 $result->{"po"} = describe_affected_po($e, $po);
1870 $e->commit and return $result or return $e->die_event;
1874 __PACKAGE__->register_method(
1875 method => 'set_lineitem_price_api',
1876 api_name => 'open-ils.acq.lineitem.price.set',
1878 desc => 'Set lineitem price. If debits already exist, update them as well',
1880 {desc => 'Authentication token', type => 'string'},
1881 {desc => 'lineitem ID', type => 'number'}
1883 return => {desc => 'status blob, Event on error'}
1887 sub set_lineitem_price_api {
1888 my($self, $conn, $auth, $li_id, $price) = @_;
1890 my $e = new_editor(xact=>1, authtoken=>$auth);
1891 return $e->die_event unless $e->checkauth;
1892 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1894 my $li = $e->retrieve_acq_lineitem([
1897 flesh_fields => {jub => ['purchase_order', 'picklist']}
1899 ]) or return $e->die_event;
1901 if($li->purchase_order) {
1902 return $e->die_event unless
1903 $e->allowed('CREATE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);
1905 return $e->die_event unless
1906 $e->allowed('CREATE_PICKLIST', $li->picklist->org_unit);
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 $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'); });
2121 __PACKAGE__->register_method(
2122 method => 'split_purchase_order_by_lineitems',
2123 api_name => 'open-ils.acq.purchase_order.split_by_lineitems',
2125 desc => q/Splits a PO into many POs, 1 per lineitem. Only works for
2126 POs a) with more than one lineitems, and b) in the "pending" state./,
2128 {desc => 'Authentication token', type => 'string'},
2129 {desc => 'Purchase order ID', type => 'number'}
2131 return => {desc => 'list of new PO IDs on success, Event on error'}
2135 sub split_purchase_order_by_lineitems {
2136 my ($self, $conn, $auth, $po_id) = @_;
2138 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2139 return $e->die_event unless $e->checkauth;
2141 my $po = $e->retrieve_acq_purchase_order([
2144 "flesh_fields" => {"acqpo" => [qw/lineitems notes/]}
2146 ]) or return $e->die_event;
2148 return $e->die_event
2149 unless $e->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2151 unless ($po->state eq "pending") {
2153 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_LATE");
2156 unless (@{$po->lineitems} > 1) {
2158 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_SHORT");
2161 # To split an existing PO into many, it seems unwise to just delete the
2162 # original PO, so we'll instead detach all of the original POs' lineitems
2163 # but the first, then create new POs for each of the remaining LIs, and
2164 # then attach the LIs to their new POs.
2166 my @po_ids = ($po->id);
2167 my @moving_li = @{$po->lineitems};
2168 shift @moving_li; # discard first LI
2170 foreach my $li (@moving_li) {
2171 my $new_po = $po->clone;
2173 $new_po->clear_name;
2174 $new_po->creator($e->requestor->id);
2175 $new_po->editor($e->requestor->id);
2176 $new_po->owner($e->requestor->id);
2177 $new_po->edit_time("now");
2178 $new_po->create_time("now");
2180 $new_po = $e->create_acq_purchase_order($new_po);
2182 # Clone any notes attached to the old PO and attach to the new one.
2183 foreach my $note (@{$po->notes}) {
2184 my $new_note = $note->clone;
2185 $new_note->clear_id;
2186 $new_note->edit_time("now");
2187 $new_note->purchase_order($new_po->id);
2188 $e->create_acq_po_note($new_note);
2191 $li->edit_time("now");
2192 $li->purchase_order($new_po->id);
2193 $e->update_acq_lineitem($li);
2195 push @po_ids, $new_po->id;
2198 $po->edit_time("now");
2199 $e->update_acq_purchase_order($po);
2201 return \@po_ids if $e->commit;
2202 return $e->die_event;
2206 sub not_cancelable {
2208 (ref $o eq "HASH" and $o->{"textcode"} eq "ACQ_NOT_CANCELABLE");
2211 __PACKAGE__->register_method(
2212 method => "cancel_purchase_order_api",
2213 api_name => "open-ils.acq.purchase_order.cancel",
2215 desc => q/Cancels an on-order purchase order/,
2217 {desc => "Authentication token", type => "string"},
2218 {desc => "PO ID to cancel", type => "number"},
2219 {desc => "Cancel reason ID", type => "number"}
2221 return => {desc => q/Object describing changed POs, LIs and LIDs
2222 on success; Event on error./}
2226 sub cancel_purchase_order_api {
2227 my ($self, $conn, $auth, $po_id, $cancel_reason) = @_;
2229 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2230 return $e->die_event unless $e->checkauth;
2231 my $mgr = new OpenILS::Application::Acq::BatchManager(
2232 "editor" => $e, "conn" => $conn
2235 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2236 return new OpenILS::Event(
2237 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2240 my $result = cancel_purchase_order($mgr, $po_id, $cancel_reason) or
2241 return $e->die_event;
2242 if (not_cancelable($result)) { # event not from CStoreEditor
2245 } elsif ($result == -1) {
2247 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2250 $e->commit or return $e->die_event;
2252 # XXX create purchase order status events?
2256 sub cancel_purchase_order {
2257 my ($mgr, $po_id, $cancel_reason) = @_;
2259 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id) or return 0;
2261 # XXX is "cancelled" a typo? It's not correct US spelling, anyway.
2262 # Depending on context, this may not warrant an event.
2263 return -1 if $po->state eq "cancelled";
2265 # But this always does.
2266 return new OpenILS::Event(
2267 "ACQ_NOT_CANCELABLE", "note" => "purchase_order $po_id"
2268 ) unless ($po->state eq "on-order" or $po->state eq "pending");
2271 $mgr->editor->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2273 $po->state("cancelled");
2274 $po->cancel_reason($cancel_reason);
2276 my $li_ids = $mgr->editor->search_acq_lineitem(
2277 {"purchase_order" => $po_id}, {"idlist" => 1}
2280 my $result = {"li" => {}, "lid" => {}};
2281 foreach my $li_id (@$li_ids) {
2282 my $li_result = cancel_lineitem($mgr, $li_id, $cancel_reason)
2285 next if $li_result == -1; # already canceled:skip.
2286 return $li_result if not_cancelable($li_result); # not cancelable:stop.
2288 # Merge in each LI result (there's only going to be
2289 # one per call to cancel_lineitem).
2290 my ($k, $v) = each %{$li_result->{"li"}};
2291 $result->{"li"}->{$k} = $v;
2293 # Merge in each LID result (there may be many per call to
2295 while (($k, $v) = each %{$li_result->{"lid"}}) {
2296 $result->{"lid"}->{$k} = $v;
2300 # TODO who/what/where/how do we indicate this change for electronic orders?
2301 # TODO return changes to encumbered/spent
2302 # TODO maybe cascade up from smaller object to container object if last
2303 # smaller object in the container has been canceled?
2305 update_purchase_order($mgr, $po) or return 0;
2307 $po_id => {"state" => $po->state, "cancel_reason" => $cancel_reason}
2313 __PACKAGE__->register_method(
2314 method => "cancel_lineitem_api",
2315 api_name => "open-ils.acq.lineitem.cancel",
2317 desc => q/Cancels an on-order lineitem/,
2319 {desc => "Authentication token", type => "string"},
2320 {desc => "Lineitem ID to cancel", type => "number"},
2321 {desc => "Cancel reason ID", type => "number"}
2323 return => {desc => q/Object describing changed LIs and LIDs on success;
2328 __PACKAGE__->register_method(
2329 method => "cancel_lineitem_api",
2330 api_name => "open-ils.acq.lineitem.cancel.batch",
2332 desc => q/Batched version of open-ils.acq.lineitem.cancel/,
2333 return => {desc => q/Object describing changed LIs and LIDs on success;
2338 sub cancel_lineitem_api {
2339 my ($self, $conn, $auth, $li_id, $cancel_reason) = @_;
2341 my $batched = $self->api_name =~ /\.batch/;
2343 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2344 return $e->die_event unless $e->checkauth;
2345 my $mgr = new OpenILS::Application::Acq::BatchManager(
2346 "editor" => $e, "conn" => $conn
2349 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2350 return new OpenILS::Event(
2351 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2354 my ($result, $maybe_event);
2357 $result = {"li" => {}, "lid" => {}};
2358 foreach my $one_li_id (@$li_id) {
2359 my $one = cancel_lineitem($mgr, $one_li_id, $cancel_reason) or
2360 return $e->die_event;
2361 if (not_cancelable($one)) {
2362 $maybe_event = $one;
2363 } elsif ($result == -1) {
2364 $maybe_event = new OpenILS::Event("ACQ_ALREADY_CANCELED");
2368 while (($k, $v) = each %{$one->{"li"}}) {
2369 $result->{"li"}->{$k} = $v;
2372 if ($one->{"lid"}) {
2373 while (($k, $v) = each %{$one->{"lid"}}) {
2374 $result->{"lid"}->{$k} = $v;
2380 $result = cancel_lineitem($mgr, $li_id, $cancel_reason) or
2381 return $e->die_event;
2383 if (not_cancelable($result)) {
2386 } elsif ($result == -1) {
2388 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2392 if ($batched and not scalar keys %{$result->{"li"}}) {
2394 return $maybe_event;
2396 $e->commit or return $e->die_event;
2397 # create_lineitem_status_events should handle array li_id ok
2398 create_lineitem_status_events($mgr, $li_id, "aur.cancelled");
2403 sub cancel_lineitem {
2404 my ($mgr, $li_id, $cancel_reason) = @_;
2405 my $li = $mgr->editor->retrieve_acq_lineitem([
2406 $li_id, {"flesh" => 1, "flesh_fields" => {"jub" => ["purchase_order"]}}
2409 return 0 unless $mgr->editor->allowed(
2410 "CREATE_PURCHASE_ORDER", $li->purchase_order->ordering_agency
2413 # Depending on context, this may not warrant an event.
2414 return -1 if $li->state eq "cancelled";
2416 # But this always does.
2417 return new OpenILS::Event(
2418 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id"
2420 (! $li->purchase_order) or (
2421 $li->purchase_order and (
2422 $li->state eq "on-order" or $li->state eq "pending-order"
2427 $li->state("cancelled");
2428 $li->cancel_reason($cancel_reason);
2430 my $lids = $mgr->editor->search_acq_lineitem_detail({
2431 "lineitem" => $li_id
2434 flesh_fields => { acqlid => ['eg_copy_id'] }
2437 my $result = {"lid" => {}};
2439 foreach my $lid (@$lids) {
2440 my $lid_result = cancel_lineitem_detail($mgr, $lid->id, $cancel_reason)
2443 # gathering any real copies for deletion
2444 if ($lid->eg_copy_id) {
2445 $lid->eg_copy_id->isdeleted('t');
2446 push @$copies, $lid->eg_copy_id;
2449 next if $lid_result == -1; # already canceled: just skip it.
2450 return $lid_result if not_cancelable($lid_result); # not cxlable: stop.
2452 # Merge in each LID result (there's only going to be one per call to
2453 # cancel_lineitem_detail).
2454 my ($k, $v) = each %{$lid_result->{"lid"}};
2455 $result->{"lid"}->{$k} = $v;
2458 # attempt to delete the gathered copies (will this may handle volume deletion and do hold retargeting for us?)
2459 my $cat_service = OpenSRF::AppSession->create('open-ils.cat');
2460 $cat_service->connect;
2461 my $cat_req = $cat_service->request('open-ils.cat.asset.copy.fleshed.batch.update', $mgr->editor->authtoken, $copies);
2462 my $cat_result = $cat_req->recv;
2463 $cat_service->disconnect;
2464 if ($cat_result != 1) { # failed to delete copies
2465 return new OpenILS::Event(
2466 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id", "payload" => $cat_result
2470 # TODO delete the associated fund debits?
2471 # TODO who/what/where/how do we indicate this change for electronic orders?
2473 update_lineitem($mgr, $li) or return 0;
2476 "state" => $li->state,
2477 "cancel_reason" => $cancel_reason
2484 __PACKAGE__->register_method(
2485 method => "cancel_lineitem_detail_api",
2486 api_name => "open-ils.acq.lineitem_detail.cancel",
2488 desc => q/Cancels an on-order lineitem detail/,
2490 {desc => "Authentication token", type => "string"},
2491 {desc => "Lineitem detail ID to cancel", type => "number"},
2492 {desc => "Cancel reason ID", type => "number"}
2494 return => {desc => q/Object describing changed LIDs on success;
2499 sub cancel_lineitem_detail_api {
2500 my ($self, $conn, $auth, $lid_id, $cancel_reason) = @_;
2502 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2503 return $e->die_event unless $e->checkauth;
2504 my $mgr = new OpenILS::Application::Acq::BatchManager(
2505 "editor" => $e, "conn" => $conn
2508 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2509 return new OpenILS::Event(
2510 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2513 my $result = cancel_lineitem_detail($mgr, $lid_id, $cancel_reason) or
2514 return $e->die_event;
2516 if (not_cancelable($result)) {
2519 } elsif ($result == -1) {
2521 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2524 $e->commit or return $e->die_event;
2526 # XXX create lineitem detail status events?
2530 sub cancel_lineitem_detail {
2531 my ($mgr, $lid_id, $cancel_reason) = @_;
2532 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
2536 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
2541 # Depending on context, this may not warrant an event.
2542 return -1 if $lid->cancel_reason;
2544 # But this always does.
2545 return new OpenILS::Event(
2546 "ACQ_NOT_CANCELABLE", "note" => "lineitem_detail $lid_id"
2548 (! $lid->lineitem->purchase_order) or
2550 (not $lid->recv_time) and
2552 $lid->lineitem->purchase_order and (
2553 $lid->lineitem->state eq "on-order" or
2554 $lid->lineitem->state eq "pending-order"
2559 return 0 unless $mgr->editor->allowed(
2560 "CREATE_PURCHASE_ORDER",
2561 $lid->lineitem->purchase_order->ordering_agency
2562 ) or (! $lid->lineitem->purchase_order);
2564 $lid->cancel_reason($cancel_reason);
2566 # TODO who/what/where/how do we indicate this change for electronic orders?
2568 # XXX LIDs don't have either an editor or a edit_time field. Should we
2569 # update these on the LI when we alter an LID?
2570 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
2571 return {"lid" => {$lid_id => {"cancel_reason" => $cancel_reason}}};
2575 __PACKAGE__->register_method(
2576 method => 'user_requests',
2577 api_name => 'open-ils.acq.user_request.retrieve.by_user_id',
2580 desc => 'Retrieve fleshed user requests and related data for a given user.',
2582 { desc => 'Authentication token', type => 'string' },
2583 { desc => 'User ID of the owner, or array of IDs', },
2584 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
2589 desc => 'Fleshed user requests and related data',
2595 __PACKAGE__->register_method(
2596 method => 'user_requests',
2597 api_name => 'open-ils.acq.user_request.retrieve.by_home_ou',
2600 desc => 'Retrieve fleshed user requests and related data for a given org unit or units.',
2602 { desc => 'Authentication token', type => 'string' },
2603 { desc => 'Org unit ID, or array of IDs', },
2604 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
2609 desc => 'Fleshed user requests and related data',
2616 my($self, $conn, $auth, $search_value, $options) = @_;
2617 my $e = new_editor(authtoken => $auth);
2618 return $e->event unless $e->checkauth;
2619 my $rid = $e->requestor->id;
2623 "select"=>{"aur"=>["id"],"au"=>["home_ou", {column => 'id', alias => 'usr_id'} ]},
2624 "from"=>{ "aur" => { "au" => {}, "jub" => { "type" => "left" } } },
2628 {"id"=>undef}, # this with the left-join pulls in requests without lineitems
2629 {"state"=>["new","on-order","pending-order"]} # FIXME - probably needs softcoding
2633 "order_by"=>[{"class"=>"aur", "field"=>"request_date", "direction"=>"desc"}]
2636 foreach (qw/ order_by limit offset /) {
2637 $query->{$_} = $options->{$_} if defined $options->{$_};
2639 if (defined $options->{'state'}) {
2640 $query->{'where'}->{'+jub'}->{'-or'}->[1]->{'state'} = $options->{'state'};
2643 if ($self->api_name =~ /by_user_id/) {
2644 $query->{'where'}->{'usr'} = $search_value;
2646 $query->{'where'}->{'+au'} = { 'home_ou' => $search_value };
2649 my $pertinent_ids = $e->json_query($query);
2652 for my $id_blob (@$pertinent_ids) {
2653 if ($rid != $id_blob->{usr_id}) {
2654 if (!defined $perm_test{ $id_blob->{home_ou} }) {
2655 $perm_test{ $id_blob->{home_ou} } = $e->allowed( ['user_request.view'], $id_blob->{home_ou} );
2657 if (!$perm_test{ $id_blob->{home_ou} }) {
2661 my $aur_obj = $e->retrieve_acq_user_request([
2663 {flesh => 1, flesh_fields => { "aur" => [ 'lineitem' ] } }
2665 if (! $aur_obj) { next; }
2667 if ($aur_obj->lineitem()) {
2668 $aur_obj->lineitem()->clear_marc();
2670 $conn->respond($aur_obj);
2676 __PACKAGE__->register_method (
2677 method => 'update_user_request',
2678 api_name => 'open-ils.acq.user_request.cancel.batch',
2681 desc => 'If given a cancel reason, will update the request with that reason, otherwise, this will delete the request altogether. The ' .
2682 'intention is for staff interfaces or processes to provide cancel reasons, and for patron interfaces to just delete the requests.' ,
2684 { desc => 'Authentication token', type => 'string' },
2685 { desc => 'ID or array of IDs for the user requests to cancel' },
2686 { desc => 'Cancel Reason ID (optional)', type => 'string' }
2689 desc => 'progress object, event on error',
2693 __PACKAGE__->register_method (
2694 method => 'update_user_request',
2695 api_name => 'open-ils.acq.user_request.set_no_hold.batch',
2698 desc => 'Remove the hold from a user request or set of requests',
2700 { desc => 'Authentication token', type => 'string' },
2701 { desc => 'ID or array of IDs for the user requests to modify' }
2704 desc => 'progress object, event on error',
2709 sub update_user_request {
2710 my($self, $conn, $auth, $aur_ids, $cancel_reason) = @_;
2711 my $e = new_editor(xact => 1, authtoken => $auth);
2712 return $e->die_event unless $e->checkauth;
2713 my $rid = $e->requestor->id;
2717 for my $id (@$aur_ids) {
2719 my $aur_obj = $e->retrieve_acq_user_request([
2722 flesh_fields => { "aur" => ['lineitem', 'usr'] }
2724 ]) or return $e->die_event;
2726 my $context_org = $aur_obj->usr()->home_ou();
2727 $aur_obj->usr( $aur_obj->usr()->id() );
2729 if ($rid != $aur_obj->usr) {
2730 if (!defined $perm_test{ $context_org }) {
2731 $perm_test{ $context_org } = $e->allowed( ['user_request.update'], $context_org );
2733 if (!$perm_test{ $context_org }) {
2738 if($self->api_name =~ /set_no_hold/) {
2739 if ($U->is_true($aur_obj->hold)) {
2741 $e->update_acq_user_request($aur_obj) or return $e->die_event;
2745 if($self->api_name =~ /cancel/) {
2746 if ( $cancel_reason ) {
2747 $aur_obj->cancel_reason( $cancel_reason );
2748 $e->update_acq_user_request($aur_obj) or return $e->die_event;
2749 create_user_request_events( $e, [ $aur_obj ], 'aur.rejected' );
2751 $e->delete_acq_user_request($aur_obj);
2755 $conn->respond({maximum => scalar(@$aur_ids), progress => $x++});
2759 return {complete => 1};
2762 __PACKAGE__->register_method (
2763 method => 'new_user_request',
2764 api_name => 'open-ils.acq.user_request.create',
2766 desc => 'Create a new user request object in the DB',
2768 { desc => 'Authentication token', type => 'string' },
2769 { desc => 'User request data hash. Hash keys match the fields for the "aur" object', type => 'object' }
2772 desc => 'The created user request object, or event on error'
2777 sub new_user_request {
2778 my($self, $conn, $auth, $form_data) = @_;
2779 my $e = new_editor(xact => 1, authtoken => $auth);
2780 return $e->die_event unless $e->checkauth;
2781 my $rid = $e->requestor->id;
2782 my $target_user_fleshed;
2783 if (! defined $$form_data{'usr'}) {
2784 $$form_data{'usr'} = $rid;
2786 if ($$form_data{'usr'} != $rid) {
2787 # See if the requestor can place the request on behalf of a different user.
2788 $target_user_fleshed = $e->retrieve_actor_user($$form_data{'usr'}) or return $e->die_event;
2789 $e->allowed('user_request.create', $target_user_fleshed->home_ou) or return $e->die_event;
2791 $target_user_fleshed = $e->requestor;
2792 $e->allowed('CREATE_PURCHASE_REQUEST') or return $e->die_event;
2794 if (! defined $$form_data{'pickup_lib'}) {
2795 if ($target_user_fleshed->ws_ou) {
2796 $$form_data{'pickup_lib'} = $target_user_fleshed->ws_ou;
2798 $$form_data{'pickup_lib'} = $target_user_fleshed->home_ou;
2801 if (! defined $$form_data{'request_type'}) {
2802 $$form_data{'request_type'} = 1; # Books
2804 my $aur_obj = new Fieldmapper::acq::user_request;
2806 $aur_obj->usr( $$form_data{'usr'} );
2807 $aur_obj->request_date( 'now' );
2808 for my $field ( keys %$form_data ) {
2809 if (defined $$form_data{$field} and $field !~ /^(id|lineitem|eg_bib|request_date|cancel_reason)$/) {
2810 $aur_obj->$field( $$form_data{$field} );
2814 $aur_obj = $e->create_acq_user_request($aur_obj) or return $e->die_event;
2816 $e->commit and create_user_request_events( $e, [ $aur_obj ], 'aur.created' );
2821 sub create_user_request_events {
2822 my($e, $user_reqs, $hook) = @_;
2824 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
2827 my %cached_usr_home_ou = ();
2828 for my $user_req (@$user_reqs) {
2829 my $home_ou = $cached_usr_home_ou{$user_req->usr};
2831 my $user = $e->retrieve_actor_user($user_req->usr) or return $e->die_event;
2832 $home_ou = $user->home_ou;
2833 $cached_usr_home_ou{$user_req->usr} = $home_ou;
2835 my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $home_ou);
2844 __PACKAGE__->register_method(
2845 method => "po_note_CUD_batch",
2846 api_name => "open-ils.acq.po_note.cud.batch",
2849 desc => q/Manage purchase order notes/,
2851 {desc => "Authentication token", type => "string"},
2852 {desc => "List of po_notes to manage", type => "array"},
2854 return => {desc => "Stream of successfully managed objects"}
2858 sub po_note_CUD_batch {
2859 my ($self, $conn, $auth, $notes) = @_;
2861 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
2862 return $e->die_event unless $e->checkauth;
2865 my $total = @$notes;
2868 foreach my $note (@$notes) {
2870 $note->editor($e->requestor->id);
2871 $note->edit_time("now");
2874 $note->creator($e->requestor->id);
2875 $note = $e->create_acq_po_note($note) or return $e->die_event;
2876 } elsif ($note->isdeleted) {
2877 $e->delete_acq_po_note($note) or return $e->die_event;
2878 } elsif ($note->ischanged) {
2879 $e->update_acq_po_note($note) or return $e->die_event;
2882 unless ($note->isdeleted) {
2883 $note = $e->retrieve_acq_po_note($note->id) or
2884 return $e->die_event;
2888 {"maximum" => $total, "progress" => ++$count, "note" => $note}
2892 $e->commit and $conn->respond_complete or return $e->die_event;