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 sub fund_exceeds_balance_stop_percent {
702 return fund_exceeds_balance_percent(
703 @_, "balance_stop_percent", "ACQ_FUND_EXCEEDS_STOP_PERCENT"
707 sub fund_exceeds_balance_warning_percent {
708 return fund_exceeds_balance_percent(
709 @_, "balance_warning_percent", "ACQ_FUND_EXCEEDS_WARN_PERCENT"
713 sub fund_exceeds_balance_percent {
714 my ($fund, $debit_amount, $e, $method_name, $event_name) = @_;
716 if ($fund->$method_name) {
718 $e->search_acq_fund_combined_balance({"fund" => $fund->id})->[0];
720 $e->search_acq_fund_allocation_total({"fund" => $fund->id})->[0];
722 $balance = ($balance) ? $balance->amount : 0;
723 $allocations = ($allocations) ? $allocations->amount : 0;
726 $allocations == 0 || # if no allocations were ever made, assume we have hit the stop percent
727 ((($balance - $debit_amount) / $allocations) * 100) <
735 "debit_amount" => $debit_amount
745 # ----------------------------------------------------------------------------
747 # ----------------------------------------------------------------------------
748 sub create_fund_debit {
749 my($mgr, $dry_run, %args) = @_;
751 # Verify the fund is not being spent beyond the hard stop amount
752 my $fund = $mgr->editor->retrieve_acq_fund($args{fund}) or return 0;
755 fund_exceeds_balance_stop_percent($fund, $args{"amount"}, $mgr->editor);
757 $dry_run and fund_exceeds_balance_warning_percent(
758 $fund, $args{"amount"}, $mgr->editor
761 my $debit = Fieldmapper::acq::fund_debit->new;
762 $debit->debit_type('purchase');
763 $debit->encumbrance('t');
764 $debit->$_($args{$_}) for keys %args;
766 $mgr->add_debit($debit->amount);
767 return $mgr->editor->create_acq_fund_debit($debit);
771 # ----------------------------------------------------------------------------
773 # ----------------------------------------------------------------------------
774 sub create_picklist {
775 my($mgr, %args) = @_;
776 my $picklist = Fieldmapper::acq::picklist->new;
777 $picklist->creator($mgr->editor->requestor->id);
778 $picklist->owner($picklist->creator);
779 $picklist->editor($picklist->creator);
780 $picklist->create_time('now');
781 $picklist->edit_time('now');
782 $picklist->org_unit($mgr->editor->requestor->ws_ou);
783 $picklist->owner($mgr->editor->requestor->id);
784 $picklist->$_($args{$_}) for keys %args;
786 $mgr->picklist($picklist);
787 return $mgr->editor->create_acq_picklist($picklist);
790 sub update_picklist {
791 my($mgr, $picklist) = @_;
792 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
793 $picklist->edit_time('now');
794 $picklist->editor($mgr->editor->requestor->id);
795 $mgr->picklist($picklist);
796 return $picklist if $mgr->editor->update_acq_picklist($picklist);
800 sub delete_picklist {
801 my($mgr, $picklist) = @_;
802 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
804 # delete all 'new' lineitems
805 my $li_ids = $mgr->editor->search_acq_lineitem({picklist => $picklist->id, state => 'new'}, {idlist => 1});
806 for my $li_id (@$li_ids) {
807 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
808 return 0 unless delete_lineitem($mgr, $li);
812 # detach all non-'new' lineitems
813 $li_ids = $mgr->editor->search_acq_lineitem({picklist => $picklist->id, state => {'!=' => 'new'}}, {idlist => 1});
814 for my $li_id (@$li_ids) {
815 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
817 return 0 unless update_lineitem($mgr, $li);
821 # remove any picklist-specific object perms
822 my $ops = $mgr->editor->search_permission_usr_object_perm_map({object_type => 'acqpl', object_id => ''.$picklist->id});
824 return 0 unless $mgr->editor->delete_usr_object_perm_map($op);
827 return $mgr->editor->delete_acq_picklist($picklist);
830 # ----------------------------------------------------------------------------
832 # ----------------------------------------------------------------------------
833 sub update_purchase_order {
835 $po = $mgr->editor->retrieve_acq_purchase_order($po) unless ref $po;
836 $po->editor($mgr->editor->requestor->id);
837 $po->edit_time('now');
838 $mgr->purchase_order($po);
839 return $mgr->editor->retrieve_acq_purchase_order($mgr->editor->data)
840 if $mgr->editor->update_acq_purchase_order($po);
844 sub create_purchase_order {
845 my($mgr, %args) = @_;
847 # verify the chosen provider is still active
848 my $provider = $mgr->editor->retrieve_acq_provider($args{provider}) or return 0;
849 unless($U->is_true($provider->active)) {
850 $logger->error("provider is not active. cannot create PO");
851 $mgr->editor->event(OpenILS::Event->new('ACQ_PROVIDER_INACTIVE'));
855 my $po = Fieldmapper::acq::purchase_order->new;
856 $po->creator($mgr->editor->requestor->id);
857 $po->editor($mgr->editor->requestor->id);
858 $po->owner($mgr->editor->requestor->id);
859 $po->edit_time('now');
860 $po->create_time('now');
861 $po->state('pending');
862 $po->ordering_agency($mgr->editor->requestor->ws_ou);
863 $po->$_($args{$_}) for keys %args;
865 $mgr->purchase_order($po);
866 return $mgr->editor->create_acq_purchase_order($po);
869 # ----------------------------------------------------------------------------
870 # if all of the lineitems for this PO are received,
871 # mark the PO as received
872 # ----------------------------------------------------------------------------
873 sub check_purchase_order_received {
874 my($mgr, $po_id) = @_;
876 my $non_recv_li = $mgr->editor->search_acq_lineitem(
877 { purchase_order => $po_id,
878 state => {'!=' => 'received'}
881 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id);
882 return $po if @$non_recv_li;
884 $po->state('received');
885 return update_purchase_order($mgr, $po);
889 # ----------------------------------------------------------------------------
890 # Bib, Callnumber, and Copy data
891 # ----------------------------------------------------------------------------
893 sub create_lineitem_assets {
894 my($mgr, $li_id) = @_;
897 my $li = $mgr->editor->retrieve_acq_lineitem([
900 flesh_fields => {jub => ['purchase_order', 'attributes']}
904 # -----------------------------------------------------------------
905 # first, create the bib record if necessary
906 # -----------------------------------------------------------------
908 unless($li->eg_bib_id) {
909 create_bib($mgr, $li) or return 0;
914 # -----------------------------------------------------------------
915 # The lineitem is going live, promote user request holds to real holds
916 # -----------------------------------------------------------------
917 promote_lineitem_holds($mgr, $li) or return 0;
919 my $li_details = $mgr->editor->search_acq_lineitem_detail({lineitem => $li_id}, {idlist=>1});
921 # -----------------------------------------------------------------
922 # for each lineitem_detail, create the volume if necessary, create
923 # a copy, and link them all together.
924 # -----------------------------------------------------------------
926 for my $lid_id (@{$li_details}) {
928 my $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid_id) or return 0;
929 next if $lid->eg_copy_id;
931 # use the same callnumber label for all items within this lineitem
932 $lid->cn_label($first_cn) if $first_cn and not $lid->cn_label;
934 # apply defaults if necessary
935 return 0 unless complete_lineitem_detail($mgr, $lid);
937 $first_cn = $lid->cn_label unless $first_cn;
939 my $org = $lid->owning_lib;
940 my $label = $lid->cn_label;
941 my $bibid = $li->eg_bib_id;
943 my $volume = $mgr->cache($org, "cn.$bibid.$label");
945 $volume = create_volume($mgr, $li, $lid) or return 0;
946 $mgr->cache($org, "cn.$bibid.$label", $volume);
948 create_copy($mgr, $volume, $lid) or return 0;
951 return { li => $li, new_bib => $new_bib };
957 my $record = OpenILS::Application::Cat::BibCommon->biblio_record_xml_import(
962 1, # override tcn collisions
965 if($U->event_code($record)) {
966 $mgr->editor->event($record);
967 $mgr->editor->rollback;
971 $li->eg_bib_id($record->id);
973 return update_lineitem($mgr, $li);
977 my($mgr, $li, $lid) = @_;
980 OpenILS::Application::Cat::AssetCommon->find_or_create_volume(
988 $mgr->editor->event($evt);
996 my($mgr, $volume, $lid) = @_;
997 my $copy = Fieldmapper::asset::copy->new;
999 $copy->loan_duration(2);
1000 $copy->fine_level(2);
1001 $copy->status(OILS_COPY_STATUS_ON_ORDER);
1002 $copy->barcode($lid->barcode);
1003 $copy->location($lid->location);
1004 $copy->call_number($volume->id);
1005 $copy->circ_lib($volume->owning_lib);
1006 $copy->circ_modifier($lid->circ_modifier);
1008 my $evt = OpenILS::Application::Cat::AssetCommon->create_copy($mgr->editor, $volume, $copy);
1010 $mgr->editor->event($evt);
1015 $lid->eg_copy_id($copy->id);
1016 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
1024 # ----------------------------------------------------------------------------
1025 # Workflow: Build a selection list from a Z39.50 search
1026 # ----------------------------------------------------------------------------
1028 __PACKAGE__->register_method(
1029 method => 'zsearch',
1030 api_name => 'open-ils.acq.picklist.search.z3950',
1033 desc => 'Performs a z3950 federated search and creates a picklist and associated lineitems',
1035 {desc => 'Authentication token', type => 'string'},
1036 {desc => 'Search definition', type => 'object'},
1037 {desc => 'Picklist name, optional', type => 'string'},
1043 my($self, $conn, $auth, $search, $name, $options) = @_;
1044 my $e = new_editor(authtoken=>$auth);
1045 return $e->event unless $e->checkauth;
1046 return $e->event unless $e->allowed('CREATE_PICKLIST');
1048 $search->{limit} ||= 10;
1051 my $ses = OpenSRF::AppSession->create('open-ils.search');
1052 my $req = $ses->request('open-ils.search.z3950.search_class', $auth, $search);
1057 while(my $resp = $req->recv(timeout=>60)) {
1060 my $e = new_editor(requestor=>$e->requestor, xact=>1);
1061 $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1062 $picklist = zsearch_build_pl($mgr, $name);
1066 my $result = $resp->content;
1067 my $count = $result->{count} || 0;
1068 $mgr->total( (($count < $search->{limit}) ? $count : $search->{limit})+1 );
1070 for my $rec (@{$result->{records}}) {
1072 my $li = create_lineitem($mgr,
1073 picklist => $picklist->id,
1074 source_label => $result->{service},
1075 marc => $rec->{marcxml},
1076 eg_bib_id => $rec->{bibid}
1079 if($$options{respond_li}) {
1080 $li->attributes($mgr->editor->search_acq_lineitem_attr({lineitem => $li->id}))
1081 if $$options{flesh_attrs};
1082 $li->clear_marc if $$options{clear_marc};
1083 $mgr->respond(lineitem => $li);
1090 $mgr->editor->commit;
1091 return $mgr->respond_complete;
1094 sub zsearch_build_pl {
1095 my($mgr, $name) = @_;
1098 my $picklist = $mgr->editor->search_acq_picklist({
1099 owner => $mgr->editor->requestor->id,
1103 if($name eq '' and $picklist) {
1104 return 0 unless delete_picklist($mgr, $picklist);
1108 return update_picklist($mgr, $picklist) if $picklist;
1109 return create_picklist($mgr, name => $name);
1113 # ----------------------------------------------------------------------------
1114 # Workflow: Build a selection list / PO by importing a batch of MARC records
1115 # ----------------------------------------------------------------------------
1117 __PACKAGE__->register_method(
1118 method => 'upload_records',
1119 api_name => 'open-ils.acq.process_upload_records',
1123 sub upload_records {
1124 my($self, $conn, $auth, $key) = @_;
1126 my $e = new_editor(authtoken => $auth, xact => 1);
1127 return $e->die_event unless $e->checkauth;
1128 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1130 my $cache = OpenSRF::Utils::Cache->new;
1132 my $data = $cache->get_cache("vandelay_import_spool_$key");
1133 my $purpose = $data->{purpose};
1134 my $filename = $data->{path};
1135 my $provider = $data->{provider};
1136 my $picklist = $data->{picklist};
1137 my $create_po = $data->{create_po};
1138 my $activate_po = $data->{activate_po};
1139 my $ordering_agency = $data->{ordering_agency};
1140 my $create_assets = $data->{create_assets};
1144 unless(-r $filename) {
1145 $logger->error("unable to read MARC file $filename");
1147 return OpenILS::Event->new('FILE_UPLOAD_ERROR', payload => {filename => $filename});
1150 $provider = $e->retrieve_acq_provider($provider) or return $e->die_event;
1153 $picklist = $e->retrieve_acq_picklist($picklist) or return $e->die_event;
1154 if($picklist->owner != $e->requestor->id) {
1155 return $e->die_event unless
1156 $e->allowed('CREATE_PICKLIST', $picklist->org_unit, $picklist);
1158 $mgr->picklist($picklist);
1163 $po = create_purchase_order($mgr,
1164 ordering_agency => $ordering_agency,
1165 provider => $provider->id,
1167 ) or return $mgr->editor->die_event;
1170 $logger->info("acq processing MARC file=$filename");
1172 my $marctype = 'USMARC'; # ?
1173 my $batch = new MARC::Batch ($marctype, $filename);
1188 } catch Error with {
1190 $logger->warn("Proccessing of record $count in set $key failed with error $err. Skipping this record");
1197 ($xml = $r->as_xml_record()) =~ s/\n//sog;
1198 $xml =~ s/^<\?xml.+\?\s*>//go;
1199 $xml =~ s/>\s+</></go;
1200 $xml =~ s/\p{Cc}//go;
1201 $xml = $U->entityize($xml);
1202 $xml =~ s/[\x00-\x1f]//go;
1204 } catch Error with {
1206 $logger->warn("Proccessing XML of record $count in set $key failed with error $err. Skipping this record");
1209 next if $err or not $xml;
1212 source_label => $provider->code,
1213 provider => $provider->id,
1217 $args{picklist} = $picklist->id if $picklist;
1219 $args{purchase_order} = $po->id;
1220 $args{state} = 'order-pending';
1223 my $li = create_lineitem($mgr, %args) or return $mgr->editor->die_event;
1225 $li->provider($provider); # flesh it, we'll need it later
1227 import_lineitem_details($mgr, $ordering_agency, $li) or return $mgr->editor->die_event;
1230 push(@li_list, $li->id);
1234 my $die_event = activate_purchase_order_impl($mgr, $po->id) if $po;;
1235 return $die_event if $die_event;
1239 $cache->delete_cache('vandelay_import_spool_' . $key);
1241 if($create_assets) {
1242 create_lineitem_list_assets($mgr, \@li_list) or return $e->die_event;
1245 return $mgr->respond_complete;
1248 sub import_lineitem_details {
1249 my($mgr, $ordering_agency, $li) = @_;
1251 my $holdings = $mgr->editor->json_query({from => ['acq.extract_provider_holding_data', $li->id]});
1252 return 1 unless @$holdings;
1253 my $org_path = $U->get_org_ancestors($ordering_agency);
1254 $org_path = [ reverse (@$org_path) ];
1259 # create a lineitem detail for each copy in the data
1261 my $compiled = extract_lineitem_detail_data($mgr, $org_path, $holdings, $idx);
1262 last unless defined $compiled;
1263 return 0 unless $compiled;
1265 # this takes the price of the last copy and uses it as the lineitem price
1266 # need to determine if a given record would include different prices for the same item
1267 $price = $$compiled{price};
1269 for(1..$$compiled{quantity}) {
1270 my $lid = create_lineitem_detail($mgr,
1271 lineitem => $li->id,
1272 owning_lib => $$compiled{owning_lib},
1273 cn_label => $$compiled{call_number},
1274 fund => $$compiled{fund},
1275 circ_modifier => $$compiled{circ_modifier},
1276 note => $$compiled{note},
1277 location => $$compiled{copy_location},
1278 collection_code => $$compiled{collection_code}
1286 $li->estimated_unit_price($price);
1287 update_lineitem($mgr, $li) or return 0;
1291 # return hash on success, 0 on error, undef on no more holdings
1292 sub extract_lineitem_detail_data {
1293 my($mgr, $org_path, $holdings, $index) = @_;
1295 my @data_list = grep { $_->{holding} eq $index } @$holdings;
1296 return undef unless @data_list;
1298 my %compiled = map { $_->{attr} => $_->{data} } @data_list;
1299 my $base_org = $$org_path[0];
1303 $logger->error("Item import extraction error: $msg");
1304 $logger->error('Holdings Data: ' . OpenSRF::Utils::JSON->perl2JSON(\%compiled));
1305 $mgr->editor->rollback;
1306 $mgr->editor->event(OpenILS::Event->new('ACQ_IMPORT_ERROR', payload => $msg));
1310 $compiled{quantity} ||= 1;
1312 # ---------------------------------------------------------------------
1314 my $code = $compiled{fund_code};
1315 return $killme->('no fund code provided') unless $code;
1317 my $fund = $mgr->cache($base_org, "fund.$code");
1319 # search up the org tree for the most appropriate fund
1320 for my $org (@$org_path) {
1321 $fund = $mgr->editor->search_acq_fund(
1322 {org => $org, code => $code, year => DateTime->now->year}, {idlist => 1})->[0];
1326 return $killme->("no fund with code $code at orgs [@$org_path]") unless $fund;
1327 $compiled{fund} = $fund;
1328 $mgr->cache($base_org, "fund.$code", $fund);
1331 # ---------------------------------------------------------------------
1333 my $sn = $compiled{owning_lib};
1334 return $killme->('no owning_lib defined') unless $sn;
1336 $mgr->cache($base_org, "orgsn.$sn") ||
1337 $mgr->editor->search_actor_org_unit({shortname => $sn}, {idlist => 1})->[0];
1338 return $killme->("invalid owning_lib defined: $sn") unless $org_id;
1339 $compiled{owning_lib} = $org_id;
1340 $mgr->cache($$org_path[0], "orgsn.$sn", $org_id);
1343 # ---------------------------------------------------------------------
1346 $code = $compiled{circ_modifier};
1350 $mod = $mgr->cache($base_org, "mod.$code") ||
1351 $mgr->editor->retrieve_config_circ_modifier($code);
1352 return $killme->("invlalid circ_modifier $code") unless $mod;
1353 $mgr->cache($base_org, "mod.$code", $mod);
1357 $mod = get_default_circ_modifier($mgr, $base_org)
1358 or return $killme->('no circ_modifier defined');
1361 $compiled{circ_modifier} = $mod;
1364 # ---------------------------------------------------------------------
1366 my $name = $compiled{copy_location};
1368 my $loc = $mgr->cache($base_org, "copy_loc.$name");
1370 for my $org (@$org_path) {
1371 $loc = $mgr->editor->search_asset_copy_location(
1372 {owning_lib => $org, name => $name}, {idlist => 1})->[0];
1376 return $killme->("Invalid copy location $name") unless $loc;
1377 $compiled{copy_location} = $loc;
1378 $mgr->cache($base_org, "copy_loc.$name", $loc);
1386 # ----------------------------------------------------------------------------
1387 # Workflow: Given an existing purchase order, import/create the bibs,
1388 # callnumber and copy objects
1389 # ----------------------------------------------------------------------------
1391 __PACKAGE__->register_method(
1392 method => 'create_po_assets',
1393 api_name => 'open-ils.acq.purchase_order.assets.create',
1395 desc => q/Creates assets for each lineitem in the purchase order/,
1397 {desc => 'Authentication token', type => 'string'},
1398 {desc => 'The purchase order id', type => 'number'},
1400 return => {desc => 'Streams a total versus completed counts object, event on error'}
1404 sub create_po_assets {
1405 my($self, $conn, $auth, $po_id) = @_;
1407 my $e = new_editor(authtoken=>$auth, xact=>1);
1408 return $e->die_event unless $e->checkauth;
1409 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1411 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1413 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1415 # it's ugly, but it's fast. Get the total count of lineitem detail objects to process
1416 my $lid_total = $e->json_query({
1417 select => { acqlid => [{aggregate => 1, transform => 'count', column => 'id'}] },
1423 join => {acqpo => {fkey => 'purchase_order', field => 'id'}}
1427 where => {'+acqpo' => {id => $po_id}}
1430 $mgr->total(scalar(@$li_ids) + $lid_total);
1432 create_lineitem_list_assets($mgr, $li_ids) or return $e->die_event;
1435 update_purchase_order($mgr, $po) or return $e->die_event;
1438 return $mgr->respond_complete;
1443 __PACKAGE__->register_method(
1444 method => 'create_purchase_order_api',
1445 api_name => 'open-ils.acq.purchase_order.create',
1447 desc => 'Creates a new purchase order',
1449 {desc => 'Authentication token', type => 'string'},
1450 {desc => 'purchase_order to create', type => 'object'}
1452 return => {desc => 'The purchase order id, Event on failure'}
1456 sub create_purchase_order_api {
1457 my($self, $conn, $auth, $po, $args) = @_;
1460 my $e = new_editor(xact=>1, authtoken=>$auth);
1461 return $e->die_event unless $e->checkauth;
1462 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
1463 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1466 my %pargs = (ordering_agency => $e->requestor->ws_ou); # default
1467 $pargs{provider} = $po->provider if $po->provider;
1468 $pargs{ordering_agency} = $po->ordering_agency if $po->ordering_agency;
1469 $pargs{prepayment_required} = $po->prepayment_required
1470 if $po->prepayment_required;
1471 $po = create_purchase_order($mgr, %pargs) or return $e->die_event;
1473 my $li_ids = $$args{lineitems};
1477 for my $li_id (@$li_ids) {
1479 my $li = $e->retrieve_acq_lineitem([
1481 {flesh => 1, flesh_fields => {jub => ['attributes']}}
1482 ]) or return $e->die_event;
1484 $li->provider($po->provider);
1485 $li->purchase_order($po->id);
1486 $li->state('pending-order');
1487 update_lineitem($mgr, $li) or return $e->die_event;
1492 # commit before starting the asset creation
1495 if($li_ids and $$args{create_assets}) {
1496 create_lineitem_list_assets($mgr, $li_ids) or return $e->die_event;
1499 return $mgr->respond_complete;
1503 __PACKAGE__->register_method(
1504 method => 'lineitem_detail_CUD_batch',
1505 api_name => 'open-ils.acq.lineitem_detail.cud.batch',
1508 desc => q/Creates a new purchase order line item detail.
1509 Additionally creates the associated fund_debit/,
1511 {desc => 'Authentication token', type => 'string'},
1512 {desc => 'List of lineitem_details to create', type => 'array'},
1514 return => {desc => 'Streaming response of current position in the array'}
1518 sub lineitem_detail_CUD_batch {
1519 my($self, $conn, $auth, $li_details) = @_;
1521 my $e = new_editor(xact=>1, authtoken=>$auth);
1522 return $e->die_event unless $e->checkauth;
1523 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1527 $mgr->total(scalar(@$li_details));
1531 for my $lid (@$li_details) {
1533 my $li = $li_cache{$lid->lineitem} || $e->retrieve_acq_lineitem($lid->lineitem);
1536 create_lineitem_detail($mgr, %{$lid->to_bare_hash}) or return $e->die_event;
1538 } elsif($lid->ischanged) {
1539 $e->update_acq_lineitem_detail($lid) or return $e->die_event;
1541 } elsif($lid->isdeleted) {
1542 delete_lineitem_detail($mgr, $lid) or return $e->die_event;
1545 $mgr->respond(li => $li);
1546 $li_cache{$lid->lineitem} = $li;
1550 return $mgr->respond_complete;
1554 __PACKAGE__->register_method(
1555 method => 'receive_po_api',
1556 api_name => 'open-ils.acq.purchase_order.receive'
1559 sub receive_po_api {
1560 my($self, $conn, $auth, $po_id) = @_;
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 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1566 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1568 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1570 for my $li_id (@$li_ids) {
1571 receive_lineitem($mgr, $li_id) or return $e->die_event;
1575 $po->state('received');
1576 update_purchase_order($mgr, $po) or return $e->die_event;
1579 return $mgr->respond_complete;
1583 # At the moment there's a lack of parallelism between the receive and unreceive
1584 # API methods for POs and the API methods for LIs and LIDs. The methods for
1585 # POs stream back objects as they act, whereas the methods for LIs and LIDs
1586 # atomically return an object that describes only what changed (in LIs and LIDs
1587 # themselves or in the objects to which to LIs and LIDs belong).
1589 # The methods for LIs and LIDs work the way they do to faciliate the UI's
1590 # maintaining correct information about the state of these things when a user
1591 # wants to receive or unreceive these objects without refreshing their whole
1592 # display. The UI feature for receiving and un-receiving a whole PO just
1593 # refreshes the whole display, so this absence of parallelism in the UI is also
1594 # relected in this module.
1596 # This could be neatened in the future by making POs receive and unreceive in
1597 # the same way the LIs and LIDs do.
1599 __PACKAGE__->register_method(
1600 method => 'receive_lineitem_detail_api',
1601 api_name => 'open-ils.acq.lineitem_detail.receive',
1603 desc => 'Mark a lineitem_detail as received',
1605 {desc => 'Authentication token', type => 'string'},
1606 {desc => 'lineitem detail ID', type => 'number'}
1609 "on success, object describing changes to LID and possibly " .
1610 "to LI and PO; on error, Event"
1615 sub receive_lineitem_detail_api {
1616 my($self, $conn, $auth, $lid_id) = @_;
1618 my $e = new_editor(xact=>1, authtoken=>$auth);
1619 return $e->die_event unless $e->checkauth;
1620 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1623 "flesh" => 2, "flesh_fields" => {
1624 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
1628 my $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1630 return $e->die_event unless $e->allowed(
1631 'RECEIVE_PURCHASE_ORDER', $lid->lineitem->purchase_order->ordering_agency);
1634 my $recvd = receive_lineitem_detail($mgr, $lid_id) or return $e->die_event;
1636 # .. and re-retrieve
1637 $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1639 # Now build result data structure.
1640 my $result = {"lid" => {$lid->id => {"recv_time" => $lid->recv_time}}};
1643 if ($recvd->class_name =~ /::purchase_order/) {
1644 $result->{"po"} = describe_affected_po($e, $recvd);
1646 $lid->lineitem->id => {"state" => $lid->lineitem->state}
1648 } elsif ($recvd->class_name =~ /::lineitem/) {
1649 $result->{"li"} = {$recvd->id => {"state" => $recvd->state}};
1653 describe_affected_po($e, $lid->lineitem->purchase_order);
1659 __PACKAGE__->register_method(
1660 method => 'receive_lineitem_api',
1661 api_name => 'open-ils.acq.lineitem.receive',
1663 desc => 'Mark a lineitem as received',
1665 {desc => 'Authentication token', type => 'string'},
1666 {desc => 'lineitem ID', type => 'number'}
1669 "on success, object describing changes to LI and possibly PO; " .
1675 sub receive_lineitem_api {
1676 my($self, $conn, $auth, $li_id) = @_;
1678 my $e = new_editor(xact=>1, authtoken=>$auth);
1679 return $e->die_event unless $e->checkauth;
1680 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1682 my $li = $e->retrieve_acq_lineitem([
1686 jub => ['purchase_order']
1689 ]) or return $e->die_event;
1691 return $e->die_event unless $e->allowed(
1692 'RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);
1694 my $res = receive_lineitem($mgr, $li_id) or return $e->die_event;
1696 $conn->respond_complete($res);
1697 $mgr->run_post_response_hooks;
1701 __PACKAGE__->register_method(
1702 method => 'rollback_receive_po_api',
1703 api_name => 'open-ils.acq.purchase_order.receive.rollback'
1706 sub rollback_receive_po_api {
1707 my($self, $conn, $auth, $po_id) = @_;
1708 my $e = new_editor(xact => 1, authtoken => $auth);
1709 return $e->die_event unless $e->checkauth;
1710 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1712 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1713 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1715 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1717 for my $li_id (@$li_ids) {
1718 rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
1722 $po->state('on-order');
1723 update_purchase_order($mgr, $po) or return $e->die_event;
1726 return $mgr->respond_complete;
1730 __PACKAGE__->register_method(
1731 method => 'rollback_receive_lineitem_detail_api',
1732 api_name => 'open-ils.acq.lineitem_detail.receive.rollback',
1734 desc => 'Mark a lineitem_detail as Un-received',
1736 {desc => 'Authentication token', type => 'string'},
1737 {desc => 'lineitem detail ID', type => 'number'}
1740 "on success, object describing changes to LID and possibly " .
1741 "to LI and PO; on error, Event"
1746 sub rollback_receive_lineitem_detail_api {
1747 my($self, $conn, $auth, $lid_id) = @_;
1749 my $e = new_editor(xact=>1, authtoken=>$auth);
1750 return $e->die_event unless $e->checkauth;
1751 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1753 my $lid = $e->retrieve_acq_lineitem_detail([
1757 acqlid => ['lineitem'],
1758 jub => ['purchase_order']
1762 my $li = $lid->lineitem;
1763 my $po = $li->purchase_order;
1765 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1769 my $recvd = rollback_receive_lineitem_detail($mgr, $lid_id)
1770 or return $e->die_event;
1773 $result->{"lid"} = {$recvd->id => {"recv_time" => $recvd->recv_time}};
1775 $result->{"lid"} = {$lid->id => {"recv_time" => $lid->recv_time}};
1778 if ($li->state eq "received") {
1779 $li->state("on-order");
1780 $li = update_lineitem($mgr, $li) or return $e->die_event;
1781 $result->{"li"} = {$li->id => {"state" => $li->state}};
1784 if ($po->state eq "received") {
1785 $po->state("on-order");
1786 $po = update_purchase_order($mgr, $po) or return $e->die_event;
1788 $result->{"po"} = describe_affected_po($e, $po);
1790 $e->commit and return $result or return $e->die_event;
1793 __PACKAGE__->register_method(
1794 method => 'rollback_receive_lineitem_api',
1795 api_name => 'open-ils.acq.lineitem.receive.rollback',
1797 desc => 'Mark a lineitem as Un-received',
1799 {desc => 'Authentication token', type => 'string'},
1800 {desc => 'lineitem ID', type => 'number'}
1803 "on success, object describing changes to LI and possibly PO; " .
1809 sub rollback_receive_lineitem_api {
1810 my($self, $conn, $auth, $li_id) = @_;
1812 my $e = new_editor(xact=>1, authtoken=>$auth);
1813 return $e->die_event unless $e->checkauth;
1814 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1816 my $li = $e->retrieve_acq_lineitem([
1818 "flesh" => 1, "flesh_fields" => {"jub" => ["purchase_order"]}
1821 my $po = $li->purchase_order;
1823 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1825 $li = rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
1827 my $result = {"li" => {$li->id => {"state" => $li->state}}};
1828 if ($po->state eq "received") {
1829 $po->state("on-order");
1830 $po = update_purchase_order($mgr, $po) or return $e->die_event;
1832 $result->{"po"} = describe_affected_po($e, $po);
1834 $e->commit and return $result or return $e->die_event;
1838 __PACKAGE__->register_method(
1839 method => 'set_lineitem_price_api',
1840 api_name => 'open-ils.acq.lineitem.price.set',
1842 desc => 'Set lineitem price. If debits already exist, update them as well',
1844 {desc => 'Authentication token', type => 'string'},
1845 {desc => 'lineitem ID', type => 'number'}
1847 return => {desc => 'status blob, Event on error'}
1851 sub set_lineitem_price_api {
1852 my($self, $conn, $auth, $li_id, $price) = @_;
1854 my $e = new_editor(xact=>1, authtoken=>$auth);
1855 return $e->die_event unless $e->checkauth;
1856 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1858 my $li = $e->retrieve_acq_lineitem([
1861 flesh_fields => {jub => ['purchase_order', 'picklist']}
1863 ]) or return $e->die_event;
1865 if($li->purchase_order) {
1866 return $e->die_event unless
1867 $e->allowed('CREATE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);
1869 return $e->die_event unless
1870 $e->allowed('CREATE_PICKLIST', $li->picklist->org_unit);
1873 $li->estimated_unit_price($price);
1874 update_lineitem($mgr, $li) or return $e->die_event;
1876 my $lid_ids = $e->search_acq_lineitem_detail(
1877 {lineitem => $li_id, fund_debit => {'!=' => undef}},
1881 for my $lid_id (@$lid_ids) {
1883 my $lid = $e->retrieve_acq_lineitem_detail([
1885 flesh => 1, flesh_fields => {acqlid => ['fund', 'fund_debit']}}
1888 $lid->fund_debit->amount($price);
1889 $e->update_acq_fund_debit($lid->fund_debit) or return $e->die_event;
1895 return $mgr->respond_complete;
1899 __PACKAGE__->register_method(
1900 method => 'clone_picklist_api',
1901 api_name => 'open-ils.acq.picklist.clone',
1903 desc => 'Clones a picklist, including lineitem and lineitem details',
1905 {desc => 'Authentication token', type => 'string'},
1906 {desc => 'Picklist ID', type => 'number'},
1907 {desc => 'New Picklist Name', type => 'string'}
1909 return => {desc => 'status blob, Event on error'}
1913 sub clone_picklist_api {
1914 my($self, $conn, $auth, $pl_id, $name) = @_;
1916 my $e = new_editor(xact=>1, authtoken=>$auth);
1917 return $e->die_event unless $e->checkauth;
1918 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1920 my $old_pl = $e->retrieve_acq_picklist($pl_id);
1921 my $new_pl = create_picklist($mgr, %{$old_pl->to_bare_hash}, name => $name) or return $e->die_event;
1923 my $li_ids = $e->search_acq_lineitem({picklist => $pl_id}, {idlist => 1});
1925 for my $li_id (@$li_ids) {
1927 # copy the lineitems
1928 my $li = $e->retrieve_acq_lineitem($li_id);
1929 my $new_li = create_lineitem($mgr, %{$li->to_bare_hash}, picklist => $new_pl->id) or return $e->die_event;
1931 my $lid_ids = $e->search_acq_lineitem_detail({lineitem => $li_id}, {idlist => 1});
1932 for my $lid_id (@$lid_ids) {
1934 # copy the lineitem details
1935 my $lid = $e->retrieve_acq_lineitem_detail($lid_id);
1936 create_lineitem_detail($mgr, %{$lid->to_bare_hash}, lineitem => $new_li->id) or return $e->die_event;
1943 return $mgr->respond_complete;
1947 __PACKAGE__->register_method(
1948 method => 'merge_picklist_api',
1949 api_name => 'open-ils.acq.picklist.merge',
1951 desc => 'Merges 2 or more picklists into a single list',
1953 {desc => 'Authentication token', type => 'string'},
1954 {desc => 'Lead Picklist ID', type => 'number'},
1955 {desc => 'List of subordinate picklist IDs', type => 'array'}
1957 return => {desc => 'status blob, Event on error'}
1961 sub merge_picklist_api {
1962 my($self, $conn, $auth, $lead_pl, $pl_list) = @_;
1964 my $e = new_editor(xact=>1, authtoken=>$auth);
1965 return $e->die_event unless $e->checkauth;
1966 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1968 # XXX perms on each picklist modified
1970 # point all of the lineitems at the lead picklist
1971 my $li_ids = $e->search_acq_lineitem({picklist => $pl_list}, {idlist => 1});
1973 for my $li_id (@$li_ids) {
1974 my $li = $e->retrieve_acq_lineitem($li_id);
1975 $li->picklist($lead_pl);
1976 update_lineitem($mgr, $li) or return $e->die_event;
1980 # now delete the subordinate lists
1981 for my $pl_id (@$pl_list) {
1982 my $pl = $e->retrieve_acq_picklist($pl_id);
1983 $e->delete_acq_picklist($pl) or return $e->die_event;
1987 return $mgr->respond_complete;
1991 __PACKAGE__->register_method(
1992 method => 'delete_picklist_api',
1993 api_name => 'open-ils.acq.picklist.delete',
1995 desc => q/Deletes a picklist. It also deletes any lineitems in the "new" state.
1996 Other attached lineitems are detached'/,
1998 {desc => 'Authentication token', type => 'string'},
1999 {desc => 'Picklist ID to delete', type => 'number'}
2001 return => {desc => '1 on success, Event on error'}
2005 sub delete_picklist_api {
2006 my($self, $conn, $auth, $picklist_id) = @_;
2007 my $e = new_editor(xact=>1, authtoken=>$auth);
2008 return $e->die_event unless $e->checkauth;
2009 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2010 my $pl = $e->retrieve_acq_picklist($picklist_id) or return $e->die_event;
2011 delete_picklist($mgr, $pl) or return $e->die_event;
2013 return $mgr->respond_complete;
2018 __PACKAGE__->register_method(
2019 method => 'activate_purchase_order',
2020 api_name => 'open-ils.acq.purchase_order.activate.dry_run'
2023 __PACKAGE__->register_method(
2024 method => 'activate_purchase_order',
2025 api_name => 'open-ils.acq.purchase_order.activate',
2027 desc => q/Activates a purchase order. This updates the status of the PO
2028 and Lineitems to 'on-order'. Activated PO's are ready for EDI delivery
2031 {desc => 'Authentication token', type => 'string'},
2032 {desc => 'Purchase ID', type => 'number'}
2034 return => {desc => '1 on success, Event on error'}
2038 sub activate_purchase_order {
2039 my($self, $conn, $auth, $po_id) = @_;
2041 my $dry_run = ($self->api_name =~ /\.dry_run/) ? 1 : 0;
2042 my $e = new_editor(xact=>1, authtoken=>$auth);
2043 return $e->die_event unless $e->checkauth;
2044 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2045 my $die_event = activate_purchase_order_impl($mgr, $po_id, $dry_run);
2046 return $die_event if $die_event;
2052 $conn->respond_complete(1);
2053 $mgr->run_post_response_hooks;
2057 sub activate_purchase_order_impl {
2058 my ($mgr, $po_id, $dry_run) = @_;
2059 my $e = $mgr->editor;
2061 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2062 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
2064 $po->state('on-order');
2065 $po->order_date('now');
2066 update_purchase_order($mgr, $po) or return $e->die_event;
2069 {purchase_order => $po_id, state => 'pending-order'},
2073 while( my $li = $e->search_acq_lineitem($query)->[0] ) {
2074 $li->state('on-order');
2075 create_lineitem_debits($mgr, $li, $dry_run) or return $e->die_event;
2076 update_lineitem($mgr, $li) or return $e->die_event;
2077 $mgr->post_process( sub { create_lineitem_status_events($mgr, $li->id, 'aur.ordered'); });
2085 __PACKAGE__->register_method(
2086 method => 'split_purchase_order_by_lineitems',
2087 api_name => 'open-ils.acq.purchase_order.split_by_lineitems',
2089 desc => q/Splits a PO into many POs, 1 per lineitem. Only works for
2090 POs a) with more than one lineitems, and b) in the "pending" state./,
2092 {desc => 'Authentication token', type => 'string'},
2093 {desc => 'Purchase order ID', type => 'number'}
2095 return => {desc => 'list of new PO IDs on success, Event on error'}
2099 sub split_purchase_order_by_lineitems {
2100 my ($self, $conn, $auth, $po_id) = @_;
2102 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2103 return $e->die_event unless $e->checkauth;
2105 my $po = $e->retrieve_acq_purchase_order([
2108 "flesh_fields" => {"acqpo" => [qw/lineitems notes/]}
2110 ]) or return $e->die_event;
2112 return $e->die_event
2113 unless $e->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2115 unless ($po->state eq "pending") {
2117 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_LATE");
2120 unless (@{$po->lineitems} > 1) {
2122 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_SHORT");
2125 # To split an existing PO into many, it seems unwise to just delete the
2126 # original PO, so we'll instead detach all of the original POs' lineitems
2127 # but the first, then create new POs for each of the remaining LIs, and
2128 # then attach the LIs to their new POs.
2130 my @po_ids = ($po->id);
2131 my @moving_li = @{$po->lineitems};
2132 shift @moving_li; # discard first LI
2134 foreach my $li (@moving_li) {
2135 my $new_po = $po->clone;
2137 $new_po->clear_name;
2138 $new_po->creator($e->requestor->id);
2139 $new_po->editor($e->requestor->id);
2140 $new_po->owner($e->requestor->id);
2141 $new_po->edit_time("now");
2142 $new_po->create_time("now");
2144 $new_po = $e->create_acq_purchase_order($new_po);
2146 # Clone any notes attached to the old PO and attach to the new one.
2147 foreach my $note (@{$po->notes}) {
2148 my $new_note = $note->clone;
2149 $new_note->clear_id;
2150 $new_note->edit_time("now");
2151 $new_note->purchase_order($new_po->id);
2152 $e->create_acq_po_note($new_note);
2155 $li->edit_time("now");
2156 $li->purchase_order($new_po->id);
2157 $e->update_acq_lineitem($li);
2159 push @po_ids, $new_po->id;
2162 $po->edit_time("now");
2163 $e->update_acq_purchase_order($po);
2165 return \@po_ids if $e->commit;
2166 return $e->die_event;
2170 sub not_cancelable {
2172 (ref $o eq "HASH" and $o->{"textcode"} eq "ACQ_NOT_CANCELABLE");
2175 __PACKAGE__->register_method(
2176 method => "cancel_purchase_order_api",
2177 api_name => "open-ils.acq.purchase_order.cancel",
2179 desc => q/Cancels an on-order purchase order/,
2181 {desc => "Authentication token", type => "string"},
2182 {desc => "PO ID to cancel", type => "number"},
2183 {desc => "Cancel reason ID", type => "number"}
2185 return => {desc => q/Object describing changed POs, LIs and LIDs
2186 on success; Event on error./}
2190 sub cancel_purchase_order_api {
2191 my ($self, $conn, $auth, $po_id, $cancel_reason) = @_;
2193 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2194 return $e->die_event unless $e->checkauth;
2195 my $mgr = new OpenILS::Application::Acq::BatchManager(
2196 "editor" => $e, "conn" => $conn
2199 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2200 return new OpenILS::Event(
2201 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2204 my $result = cancel_purchase_order($mgr, $po_id, $cancel_reason) or
2205 return $e->die_event;
2206 if (not_cancelable($result)) { # event not from CStoreEditor
2209 } elsif ($result == -1) {
2211 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2214 $e->commit or return $e->die_event;
2216 # XXX create purchase order status events?
2220 sub cancel_purchase_order {
2221 my ($mgr, $po_id, $cancel_reason) = @_;
2223 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id) or return 0;
2225 # XXX is "cancelled" a typo? It's not correct US spelling, anyway.
2226 # Depending on context, this may not warrant an event.
2227 return -1 if $po->state eq "cancelled";
2229 # But this always does.
2230 return new OpenILS::Event(
2231 "ACQ_NOT_CANCELABLE", "note" => "purchase_order $po_id"
2232 ) unless ($po->state eq "on-order" or $po->state eq "pending");
2235 $mgr->editor->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2237 $po->state("cancelled");
2238 $po->cancel_reason($cancel_reason);
2240 my $li_ids = $mgr->editor->search_acq_lineitem(
2241 {"purchase_order" => $po_id}, {"idlist" => 1}
2244 my $result = {"li" => {}, "lid" => {}};
2245 foreach my $li_id (@$li_ids) {
2246 my $li_result = cancel_lineitem($mgr, $li_id, $cancel_reason)
2249 next if $li_result == -1; # already canceled:skip.
2250 return $li_result if not_cancelable($li_result); # not cancelable:stop.
2252 # Merge in each LI result (there's only going to be
2253 # one per call to cancel_lineitem).
2254 my ($k, $v) = each %{$li_result->{"li"}};
2255 $result->{"li"}->{$k} = $v;
2257 # Merge in each LID result (there may be many per call to
2259 while (($k, $v) = each %{$li_result->{"lid"}}) {
2260 $result->{"lid"}->{$k} = $v;
2264 # TODO who/what/where/how do we indicate this change for electronic orders?
2265 # TODO return changes to encumbered/spent
2266 # TODO maybe cascade up from smaller object to container object if last
2267 # smaller object in the container has been canceled?
2269 update_purchase_order($mgr, $po) or return 0;
2271 $po_id => {"state" => $po->state, "cancel_reason" => $cancel_reason}
2277 __PACKAGE__->register_method(
2278 method => "cancel_lineitem_api",
2279 api_name => "open-ils.acq.lineitem.cancel",
2281 desc => q/Cancels an on-order lineitem/,
2283 {desc => "Authentication token", type => "string"},
2284 {desc => "Lineitem ID to cancel", type => "number"},
2285 {desc => "Cancel reason ID", type => "number"}
2287 return => {desc => q/Object describing changed LIs and LIDs on success;
2292 __PACKAGE__->register_method(
2293 method => "cancel_lineitem_api",
2294 api_name => "open-ils.acq.lineitem.cancel.batch",
2296 desc => q/Batched version of open-ils.acq.lineitem.cancel/,
2297 return => {desc => q/Object describing changed LIs and LIDs on success;
2302 sub cancel_lineitem_api {
2303 my ($self, $conn, $auth, $li_id, $cancel_reason) = @_;
2305 my $batched = $self->api_name =~ /\.batch/;
2307 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2308 return $e->die_event unless $e->checkauth;
2309 my $mgr = new OpenILS::Application::Acq::BatchManager(
2310 "editor" => $e, "conn" => $conn
2313 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2314 return new OpenILS::Event(
2315 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2318 my ($result, $maybe_event);
2321 $result = {"li" => {}, "lid" => {}};
2322 foreach my $one_li_id (@$li_id) {
2323 my $one = cancel_lineitem($mgr, $one_li_id, $cancel_reason) or
2324 return $e->die_event;
2325 if (not_cancelable($one)) {
2326 $maybe_event = $one;
2327 } elsif ($result == -1) {
2328 $maybe_event = new OpenILS::Event("ACQ_ALREADY_CANCELED");
2332 while (($k, $v) = each %{$one->{"li"}}) {
2333 $result->{"li"}->{$k} = $v;
2336 if ($one->{"lid"}) {
2337 while (($k, $v) = each %{$one->{"lid"}}) {
2338 $result->{"lid"}->{$k} = $v;
2344 $result = cancel_lineitem($mgr, $li_id, $cancel_reason) or
2345 return $e->die_event;
2347 if (not_cancelable($result)) {
2350 } elsif ($result == -1) {
2352 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2356 if ($batched and not scalar keys %{$result->{"li"}}) {
2358 return $maybe_event;
2360 $e->commit or return $e->die_event;
2361 # create_lineitem_status_events should handle array li_id ok
2362 create_lineitem_status_events($mgr, $li_id, "aur.cancelled");
2367 sub cancel_lineitem {
2368 my ($mgr, $li_id, $cancel_reason) = @_;
2369 my $li = $mgr->editor->retrieve_acq_lineitem([
2370 $li_id, {"flesh" => 1, "flesh_fields" => {"jub" => ["purchase_order"]}}
2373 return 0 unless $mgr->editor->allowed(
2374 "CREATE_PURCHASE_ORDER", $li->purchase_order->ordering_agency
2377 # Depending on context, this may not warrant an event.
2378 return -1 if $li->state eq "cancelled";
2380 # But this always does.
2381 return new OpenILS::Event(
2382 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id"
2384 $li->purchase_order and (
2385 $li->state eq "on-order" or $li->state eq "pending-order"
2389 $li->state("cancelled");
2390 $li->cancel_reason($cancel_reason);
2392 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
2393 {"lineitem" => $li_id}, {"idlist" => 1}
2396 my $result = {"lid" => {}};
2397 foreach my $lid_id (@$lid_ids) {
2398 my $lid_result = cancel_lineitem_detail($mgr, $lid_id, $cancel_reason)
2401 next if $lid_result == -1; # already canceled: just skip it.
2402 return $lid_result if not_cancelable($lid_result); # not cxlable: stop.
2404 # Merge in each LID result (there's only going to be one per call to
2405 # cancel_lineitem_detail).
2406 my ($k, $v) = each %{$lid_result->{"lid"}};
2407 $result->{"lid"}->{$k} = $v;
2410 # TODO delete the associated fund debits?
2411 # TODO who/what/where/how do we indicate this change for electronic orders?
2413 update_lineitem($mgr, $li) or return 0;
2416 "state" => $li->state,
2417 "cancel_reason" => $cancel_reason
2424 __PACKAGE__->register_method(
2425 method => "cancel_lineitem_detail_api",
2426 api_name => "open-ils.acq.lineitem_detail.cancel",
2428 desc => q/Cancels an on-order lineitem detail/,
2430 {desc => "Authentication token", type => "string"},
2431 {desc => "Lineitem detail ID to cancel", type => "number"},
2432 {desc => "Cancel reason ID", type => "number"}
2434 return => {desc => q/Object describing changed LIDs on success;
2439 sub cancel_lineitem_detail_api {
2440 my ($self, $conn, $auth, $lid_id, $cancel_reason) = @_;
2442 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2443 return $e->die_event unless $e->checkauth;
2444 my $mgr = new OpenILS::Application::Acq::BatchManager(
2445 "editor" => $e, "conn" => $conn
2448 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2449 return new OpenILS::Event(
2450 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2453 my $result = cancel_lineitem_detail($mgr, $lid_id, $cancel_reason) or
2454 return $e->die_event;
2456 if (not_cancelable($result)) {
2459 } elsif ($result == -1) {
2461 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2464 $e->commit or return $e->die_event;
2466 # XXX create lineitem detail status events?
2470 sub cancel_lineitem_detail {
2471 my ($mgr, $lid_id, $cancel_reason) = @_;
2472 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
2476 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
2481 # Depending on context, this may not warrant an event.
2482 return -1 if $lid->cancel_reason;
2484 # But this always does.
2485 return new OpenILS::Event(
2486 "ACQ_NOT_CANCELABLE", "note" => "lineitem_detail $lid_id"
2488 (not $lid->recv_time) and
2490 $lid->lineitem->purchase_order and (
2491 $lid->lineitem->state eq "on-order" or
2492 $lid->lineitem->state eq "pending-order"
2496 return 0 unless $mgr->editor->allowed(
2497 "CREATE_PURCHASE_ORDER",
2498 $lid->lineitem->purchase_order->ordering_agency
2501 $lid->cancel_reason($cancel_reason);
2503 # TODO who/what/where/how do we indicate this change for electronic orders?
2505 # XXX LIDs don't have either an editor or a edit_time field. Should we
2506 # update these on the LI when we alter an LID?
2507 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
2508 return {"lid" => {$lid_id => {"cancel_reason" => $cancel_reason}}};
2512 __PACKAGE__->register_method(
2513 method => 'user_requests',
2514 api_name => 'open-ils.acq.user_request.retrieve.by_user_id',
2517 desc => 'Retrieve fleshed user requests and related data for a given user.',
2519 { desc => 'Authentication token', type => 'string' },
2520 { desc => 'User ID of the owner, or array of IDs', },
2521 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
2526 desc => 'Fleshed user requests and related data',
2532 __PACKAGE__->register_method(
2533 method => 'user_requests',
2534 api_name => 'open-ils.acq.user_request.retrieve.by_home_ou',
2537 desc => 'Retrieve fleshed user requests and related data for a given org unit or units.',
2539 { desc => 'Authentication token', type => 'string' },
2540 { desc => 'Org unit ID, or array of IDs', },
2541 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
2546 desc => 'Fleshed user requests and related data',
2553 my($self, $conn, $auth, $search_value, $options) = @_;
2554 my $e = new_editor(authtoken => $auth);
2555 return $e->event unless $e->checkauth;
2556 my $rid = $e->requestor->id;
2560 "select"=>{"aur"=>["id"],"au"=>["home_ou", {column => 'id', alias => 'usr_id'} ]},
2561 "from"=>{ "aur" => { "au" => {}, "jub" => { "type" => "left" } } },
2565 {"id"=>undef}, # this with the left-join pulls in requests without lineitems
2566 {"state"=>["new","on-order","pending-order"]} # FIXME - probably needs softcoding
2570 "order_by"=>[{"class"=>"aur", "field"=>"request_date", "direction"=>"desc"}]
2573 foreach (qw/ order_by limit offset /) {
2574 $query->{$_} = $options->{$_} if defined $options->{$_};
2576 if (defined $options->{'state'}) {
2577 $query->{'where'}->{'+jub'}->{'-or'}->[1]->{'state'} = $options->{'state'};
2580 if ($self->api_name =~ /by_user_id/) {
2581 $query->{'where'}->{'usr'} = $search_value;
2583 $query->{'where'}->{'+au'} = { 'home_ou' => $search_value };
2586 my $pertinent_ids = $e->json_query($query);
2589 for my $id_blob (@$pertinent_ids) {
2590 if ($rid != $id_blob->{usr_id}) {
2591 if (!defined $perm_test{ $id_blob->{home_ou} }) {
2592 $perm_test{ $id_blob->{home_ou} } = $e->allowed( ['user_request.view'], $id_blob->{home_ou} );
2594 if (!$perm_test{ $id_blob->{home_ou} }) {
2598 my $aur_obj = $e->retrieve_acq_user_request([
2600 {flesh => 1, flesh_fields => { "aur" => [ 'lineitem' ] } }
2602 if (! $aur_obj) { next; }
2604 if ($aur_obj->lineitem()) {
2605 $aur_obj->lineitem()->clear_marc();
2607 $conn->respond($aur_obj);
2613 __PACKAGE__->register_method (
2614 method => 'update_user_request',
2615 api_name => 'open-ils.acq.user_request.cancel.batch',
2618 desc => 'If given a cancel reason, will update the request with that reason, otherwise, this will delete the request altogether. The ' .
2619 'intention is for staff interfaces or processes to provide cancel reasons, and for patron interfaces to just delete the requests.' ,
2621 { desc => 'Authentication token', type => 'string' },
2622 { desc => 'ID or array of IDs for the user requests to cancel' },
2623 { desc => 'Cancel Reason ID (optional)', type => 'string' }
2626 desc => 'progress object, event on error',
2630 __PACKAGE__->register_method (
2631 method => 'update_user_request',
2632 api_name => 'open-ils.acq.user_request.set_no_hold.batch',
2635 desc => 'Remove the hold from a user request or set of requests',
2637 { desc => 'Authentication token', type => 'string' },
2638 { desc => 'ID or array of IDs for the user requests to modify' }
2641 desc => 'progress object, event on error',
2646 sub update_user_request {
2647 my($self, $conn, $auth, $aur_ids, $cancel_reason) = @_;
2648 my $e = new_editor(xact => 1, authtoken => $auth);
2649 return $e->die_event unless $e->checkauth;
2650 my $rid = $e->requestor->id;
2654 for my $id (@$aur_ids) {
2656 my $aur_obj = $e->retrieve_acq_user_request([
2659 flesh_fields => { "aur" => ['lineitem', 'usr'] }
2661 ]) or return $e->die_event;
2663 my $context_org = $aur_obj->usr()->home_ou();
2664 $aur_obj->usr( $aur_obj->usr()->id() );
2666 if ($rid != $aur_obj->usr) {
2667 if (!defined $perm_test{ $context_org }) {
2668 $perm_test{ $context_org } = $e->allowed( ['user_request.update'], $context_org );
2670 if (!$perm_test{ $context_org }) {
2675 if($self->api_name =~ /set_no_hold/) {
2676 if ($U->is_true($aur_obj->hold)) {
2678 $e->update_acq_user_request($aur_obj) or return $e->die_event;
2682 if($self->api_name =~ /cancel/) {
2683 if ( $cancel_reason ) {
2684 $aur_obj->cancel_reason( $cancel_reason );
2685 $e->update_acq_user_request($aur_obj) or return $e->die_event;
2686 create_user_request_events( $e, [ $aur_obj ], 'aur.rejected' );
2688 $e->delete_acq_user_request($aur_obj);
2692 $conn->respond({maximum => scalar(@$aur_ids), progress => $x++});
2696 return {complete => 1};
2699 __PACKAGE__->register_method (
2700 method => 'new_user_request',
2701 api_name => 'open-ils.acq.user_request.create',
2703 desc => 'Create a new user request object in the DB',
2705 { desc => 'Authentication token', type => 'string' },
2706 { desc => 'User request data hash. Hash keys match the fields for the "aur" object', type => 'object' }
2709 desc => 'The created user request object, or event on error'
2714 sub new_user_request {
2715 my($self, $conn, $auth, $form_data) = @_;
2716 my $e = new_editor(xact => 1, authtoken => $auth);
2717 return $e->die_event unless $e->checkauth;
2718 my $rid = $e->requestor->id;
2719 my $target_user_fleshed;
2720 if (! defined $$form_data{'usr'}) {
2721 $$form_data{'usr'} = $rid;
2723 if ($$form_data{'usr'} != $rid) {
2724 # See if the requestor can place the request on behalf of a different user.
2725 $target_user_fleshed = $e->retrieve_actor_user($$form_data{'usr'}) or return $e->die_event;
2726 $e->allowed('user_request.create', $target_user_fleshed->home_ou) or return $e->die_event;
2728 $target_user_fleshed = $e->requestor;
2729 $e->allowed('CREATE_PURCHASE_REQUEST') or return $e->die_event;
2731 if (! defined $$form_data{'pickup_lib'}) {
2732 if ($target_user_fleshed->ws_ou) {
2733 $$form_data{'pickup_lib'} = $target_user_fleshed->ws_ou;
2735 $$form_data{'pickup_lib'} = $target_user_fleshed->home_ou;
2738 if (! defined $$form_data{'request_type'}) {
2739 $$form_data{'request_type'} = 1; # Books
2741 my $aur_obj = new Fieldmapper::acq::user_request;
2743 $aur_obj->usr( $$form_data{'usr'} );
2744 $aur_obj->request_date( 'now' );
2745 for my $field ( keys %$form_data ) {
2746 if (defined $$form_data{$field} and $field !~ /^(id|lineitem|eg_bib|request_date|cancel_reason)$/) {
2747 $aur_obj->$field( $$form_data{$field} );
2751 $aur_obj = $e->create_acq_user_request($aur_obj) or return $e->die_event;
2753 $e->commit and create_user_request_events( $e, [ $aur_obj ], 'aur.created' );
2758 sub create_user_request_events {
2759 my($e, $user_reqs, $hook) = @_;
2761 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
2764 my %cached_usr_home_ou = ();
2765 for my $user_req (@$user_reqs) {
2766 my $home_ou = $cached_usr_home_ou{$user_req->usr};
2768 my $user = $e->retrieve_actor_user($user_req->usr) or return $e->die_event;
2769 $home_ou = $user->home_ou;
2770 $cached_usr_home_ou{$user_req->usr} = $home_ou;
2772 my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $home_ou);
2781 __PACKAGE__->register_method(
2782 method => "po_note_CUD_batch",
2783 api_name => "open-ils.acq.po_note.cud.batch",
2786 desc => q/Manage purchase order notes/,
2788 {desc => "Authentication token", type => "string"},
2789 {desc => "List of po_notes to manage", type => "array"},
2791 return => {desc => "Stream of successfully managed objects"}
2795 sub po_note_CUD_batch {
2796 my ($self, $conn, $auth, $notes) = @_;
2798 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
2799 return $e->die_event unless $e->checkauth;
2802 my $total = @$notes;
2805 foreach my $note (@$notes) {
2807 $note->editor($e->requestor->id);
2808 $note->edit_time("now");
2811 $note->creator($e->requestor->id);
2812 $note = $e->create_acq_po_note($note) or return $e->die_event;
2813 } elsif ($note->isdeleted) {
2814 $e->delete_acq_po_note($note) or return $e->die_event;
2815 } elsif ($note->ischanged) {
2816 $e->update_acq_po_note($note) or return $e->die_event;
2819 unless ($note->isdeleted) {
2820 $note = $e->retrieve_acq_po_note($note->id) or
2821 return $e->die_event;
2825 {"maximum" => $total, "progress" => ++$count, "note" => $note}
2829 $e->commit and $conn->respond_complete or return $e->die_event;