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 {
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) or return 0;
646 sub create_lineitem_detail_debit {
647 my($mgr, $li, $lid) = @_;
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(
687 fund => $lid->fund->id,
688 origin_amount => $li->estimated_unit_price,
689 origin_currency_type => $li->provider->currency_type,
693 $lid->fund_debit($debit->id);
694 $lid->fund($lid->fund->id);
695 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
700 # ----------------------------------------------------------------------------
702 # ----------------------------------------------------------------------------
703 sub create_fund_debit {
704 my($mgr, %args) = @_;
706 # Verify the fund is not being spent beyond the hard stop amount
707 my $fund = $mgr->editor->retrieve_acq_fund($args{fund}) or return 0;
709 if($fund->balance_stop_percent) {
711 my $balance = $mgr->editor->search_acq_fund_combined_balance({fund => $fund->id})->[0];
712 my $allocations = $mgr->editor->search_acq_fund_allocation_total({fund => $fund->id})->[0];
713 $balance = ($balance) ? $balance->amount : 0;
714 $allocations = ($allocations) ? $allocations->amount : 0;
717 $allocations == 0 || # if no allocations were ever made, assume we have hit the stop percent
718 ( ( ( ($balance - $args{amount}) / $allocations ) * 100 ) < $fund->balance_stop_percent))
720 $mgr->editor->event(OpenILS::Event->new(
721 'FUND_EXCEEDS_STOP_PERCENT',
722 payload => {fund => $fund->id, debit_amount => $args{amount}}
728 my $debit = Fieldmapper::acq::fund_debit->new;
729 $debit->debit_type('purchase');
730 $debit->encumbrance('t');
731 $debit->$_($args{$_}) for keys %args;
733 $mgr->add_debit($debit->amount);
734 return $mgr->editor->create_acq_fund_debit($debit);
738 # ----------------------------------------------------------------------------
740 # ----------------------------------------------------------------------------
741 sub create_picklist {
742 my($mgr, %args) = @_;
743 my $picklist = Fieldmapper::acq::picklist->new;
744 $picklist->creator($mgr->editor->requestor->id);
745 $picklist->owner($picklist->creator);
746 $picklist->editor($picklist->creator);
747 $picklist->create_time('now');
748 $picklist->edit_time('now');
749 $picklist->org_unit($mgr->editor->requestor->ws_ou);
750 $picklist->owner($mgr->editor->requestor->id);
751 $picklist->$_($args{$_}) for keys %args;
753 $mgr->picklist($picklist);
754 return $mgr->editor->create_acq_picklist($picklist);
757 sub update_picklist {
758 my($mgr, $picklist) = @_;
759 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
760 $picklist->edit_time('now');
761 $picklist->editor($mgr->editor->requestor->id);
762 $mgr->picklist($picklist);
763 return $picklist if $mgr->editor->update_acq_picklist($picklist);
767 sub delete_picklist {
768 my($mgr, $picklist) = @_;
769 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
771 # delete all 'new' lineitems
772 my $li_ids = $mgr->editor->search_acq_lineitem({picklist => $picklist->id, state => 'new'}, {idlist => 1});
773 for my $li_id (@$li_ids) {
774 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
775 return 0 unless delete_lineitem($mgr, $li);
779 # detach all non-'new' lineitems
780 $li_ids = $mgr->editor->search_acq_lineitem({picklist => $picklist->id, state => {'!=' => 'new'}}, {idlist => 1});
781 for my $li_id (@$li_ids) {
782 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
784 return 0 unless update_lineitem($mgr, $li);
788 # remove any picklist-specific object perms
789 my $ops = $mgr->editor->search_permission_usr_object_perm_map({object_type => 'acqpl', object_id => ''.$picklist->id});
791 return 0 unless $mgr->editor->delete_usr_object_perm_map($op);
794 return $mgr->editor->delete_acq_picklist($picklist);
797 # ----------------------------------------------------------------------------
799 # ----------------------------------------------------------------------------
800 sub update_purchase_order {
802 $po = $mgr->editor->retrieve_acq_purchase_order($po) unless ref $po;
803 $po->editor($mgr->editor->requestor->id);
804 $po->edit_time('now');
805 $mgr->purchase_order($po);
806 return $mgr->editor->retrieve_acq_purchase_order($mgr->editor->data)
807 if $mgr->editor->update_acq_purchase_order($po);
811 sub create_purchase_order {
812 my($mgr, %args) = @_;
814 # verify the chosen provider is still active
815 my $provider = $mgr->editor->retrieve_acq_provider($args{provider}) or return 0;
816 unless($U->is_true($provider->active)) {
817 $logger->error("provider is not active. cannot create PO");
818 $mgr->editor->event(OpenILS::Event->new('ACQ_PROVIDER_INACTIVE'));
822 my $po = Fieldmapper::acq::purchase_order->new;
823 $po->creator($mgr->editor->requestor->id);
824 $po->editor($mgr->editor->requestor->id);
825 $po->owner($mgr->editor->requestor->id);
826 $po->edit_time('now');
827 $po->create_time('now');
828 $po->state('pending');
829 $po->ordering_agency($mgr->editor->requestor->ws_ou);
830 $po->$_($args{$_}) for keys %args;
832 $mgr->purchase_order($po);
833 return $mgr->editor->create_acq_purchase_order($po);
836 # ----------------------------------------------------------------------------
837 # if all of the lineitems for this PO are received,
838 # mark the PO as received
839 # ----------------------------------------------------------------------------
840 sub check_purchase_order_received {
841 my($mgr, $po_id) = @_;
843 my $non_recv_li = $mgr->editor->search_acq_lineitem(
844 { purchase_order => $po_id,
845 state => {'!=' => 'received'}
848 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id);
849 return $po if @$non_recv_li;
851 $po->state('received');
852 return update_purchase_order($mgr, $po);
856 # ----------------------------------------------------------------------------
857 # Bib, Callnumber, and Copy data
858 # ----------------------------------------------------------------------------
860 sub create_lineitem_assets {
861 my($mgr, $li_id) = @_;
864 my $li = $mgr->editor->retrieve_acq_lineitem([
867 flesh_fields => {jub => ['purchase_order', 'attributes']}
871 # -----------------------------------------------------------------
872 # first, create the bib record if necessary
873 # -----------------------------------------------------------------
875 unless($li->eg_bib_id) {
876 create_bib($mgr, $li) or return 0;
881 # -----------------------------------------------------------------
882 # The lineitem is going live, promote user request holds to real holds
883 # -----------------------------------------------------------------
884 promote_lineitem_holds($mgr, $li) or return 0;
886 my $li_details = $mgr->editor->search_acq_lineitem_detail({lineitem => $li_id}, {idlist=>1});
888 # -----------------------------------------------------------------
889 # for each lineitem_detail, create the volume if necessary, create
890 # a copy, and link them all together.
891 # -----------------------------------------------------------------
893 for my $lid_id (@{$li_details}) {
895 my $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid_id) or return 0;
896 next if $lid->eg_copy_id;
898 # use the same callnumber label for all items within this lineitem
899 $lid->cn_label($first_cn) if $first_cn and not $lid->cn_label;
901 # apply defaults if necessary
902 return 0 unless complete_lineitem_detail($mgr, $lid);
904 $first_cn = $lid->cn_label unless $first_cn;
906 my $org = $lid->owning_lib;
907 my $label = $lid->cn_label;
908 my $bibid = $li->eg_bib_id;
910 my $volume = $mgr->cache($org, "cn.$bibid.$label");
912 $volume = create_volume($mgr, $li, $lid) or return 0;
913 $mgr->cache($org, "cn.$bibid.$label", $volume);
915 create_copy($mgr, $volume, $lid) or return 0;
918 return { li => $li, new_bib => $new_bib };
924 my $record = OpenILS::Application::Cat::BibCommon->biblio_record_xml_import(
929 1, # override tcn collisions
932 if($U->event_code($record)) {
933 $mgr->editor->event($record);
934 $mgr->editor->rollback;
938 $li->eg_bib_id($record->id);
940 return update_lineitem($mgr, $li);
944 my($mgr, $li, $lid) = @_;
947 OpenILS::Application::Cat::AssetCommon->find_or_create_volume(
955 $mgr->editor->event($evt);
963 my($mgr, $volume, $lid) = @_;
964 my $copy = Fieldmapper::asset::copy->new;
966 $copy->loan_duration(2);
967 $copy->fine_level(2);
968 $copy->status(OILS_COPY_STATUS_ON_ORDER);
969 $copy->barcode($lid->barcode);
970 $copy->location($lid->location);
971 $copy->call_number($volume->id);
972 $copy->circ_lib($volume->owning_lib);
973 $copy->circ_modifier($lid->circ_modifier);
975 my $evt = OpenILS::Application::Cat::AssetCommon->create_copy($mgr->editor, $volume, $copy);
977 $mgr->editor->event($evt);
982 $lid->eg_copy_id($copy->id);
983 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
991 # ----------------------------------------------------------------------------
992 # Workflow: Build a selection list from a Z39.50 search
993 # ----------------------------------------------------------------------------
995 __PACKAGE__->register_method(
997 api_name => 'open-ils.acq.picklist.search.z3950',
1000 desc => 'Performs a z3950 federated search and creates a picklist and associated lineitems',
1002 {desc => 'Authentication token', type => 'string'},
1003 {desc => 'Search definition', type => 'object'},
1004 {desc => 'Picklist name, optional', type => 'string'},
1010 my($self, $conn, $auth, $search, $name, $options) = @_;
1011 my $e = new_editor(authtoken=>$auth);
1012 return $e->event unless $e->checkauth;
1013 return $e->event unless $e->allowed('CREATE_PICKLIST');
1015 $search->{limit} ||= 10;
1018 my $ses = OpenSRF::AppSession->create('open-ils.search');
1019 my $req = $ses->request('open-ils.search.z3950.search_class', $auth, $search);
1024 while(my $resp = $req->recv(timeout=>60)) {
1027 my $e = new_editor(requestor=>$e->requestor, xact=>1);
1028 $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1029 $picklist = zsearch_build_pl($mgr, $name);
1033 my $result = $resp->content;
1034 my $count = $result->{count} || 0;
1035 $mgr->total( (($count < $search->{limit}) ? $count : $search->{limit})+1 );
1037 for my $rec (@{$result->{records}}) {
1039 my $li = create_lineitem($mgr,
1040 picklist => $picklist->id,
1041 source_label => $result->{service},
1042 marc => $rec->{marcxml},
1043 eg_bib_id => $rec->{bibid}
1046 if($$options{respond_li}) {
1047 $li->attributes($mgr->editor->search_acq_lineitem_attr({lineitem => $li->id}))
1048 if $$options{flesh_attrs};
1049 $li->clear_marc if $$options{clear_marc};
1050 $mgr->respond(lineitem => $li);
1057 $mgr->editor->commit;
1058 return $mgr->respond_complete;
1061 sub zsearch_build_pl {
1062 my($mgr, $name) = @_;
1065 my $picklist = $mgr->editor->search_acq_picklist({
1066 owner => $mgr->editor->requestor->id,
1070 if($name eq '' and $picklist) {
1071 return 0 unless delete_picklist($mgr, $picklist);
1075 return update_picklist($mgr, $picklist) if $picklist;
1076 return create_picklist($mgr, name => $name);
1080 # ----------------------------------------------------------------------------
1081 # Workflow: Build a selection list / PO by importing a batch of MARC records
1082 # ----------------------------------------------------------------------------
1084 __PACKAGE__->register_method(
1085 method => 'upload_records',
1086 api_name => 'open-ils.acq.process_upload_records',
1090 sub upload_records {
1091 my($self, $conn, $auth, $key) = @_;
1093 my $e = new_editor(authtoken => $auth, xact => 1);
1094 return $e->die_event unless $e->checkauth;
1095 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1097 my $cache = OpenSRF::Utils::Cache->new;
1099 my $data = $cache->get_cache("vandelay_import_spool_$key");
1100 my $purpose = $data->{purpose};
1101 my $filename = $data->{path};
1102 my $provider = $data->{provider};
1103 my $picklist = $data->{picklist};
1104 my $create_po = $data->{create_po};
1105 my $activate_po = $data->{activate_po};
1106 my $ordering_agency = $data->{ordering_agency};
1107 my $create_assets = $data->{create_assets};
1111 unless(-r $filename) {
1112 $logger->error("unable to read MARC file $filename");
1114 return OpenILS::Event->new('FILE_UPLOAD_ERROR', payload => {filename => $filename});
1117 $provider = $e->retrieve_acq_provider($provider) or return $e->die_event;
1120 $picklist = $e->retrieve_acq_picklist($picklist) or return $e->die_event;
1121 if($picklist->owner != $e->requestor->id) {
1122 return $e->die_event unless
1123 $e->allowed('CREATE_PICKLIST', $picklist->org_unit, $picklist);
1125 $mgr->picklist($picklist);
1130 $po = create_purchase_order($mgr,
1131 ordering_agency => $ordering_agency,
1132 provider => $provider->id,
1134 ) or return $mgr->editor->die_event;
1137 $logger->info("acq processing MARC file=$filename");
1139 my $marctype = 'USMARC'; # ?
1140 my $batch = new MARC::Batch ($marctype, $filename);
1155 } catch Error with {
1157 $logger->warn("Proccessing of record $count in set $key failed with error $err. Skipping this record");
1164 ($xml = $r->as_xml_record()) =~ s/\n//sog;
1165 $xml =~ s/^<\?xml.+\?\s*>//go;
1166 $xml =~ s/>\s+</></go;
1167 $xml =~ s/\p{Cc}//go;
1168 $xml = $U->entityize($xml);
1169 $xml =~ s/[\x00-\x1f]//go;
1171 } catch Error with {
1173 $logger->warn("Proccessing XML of record $count in set $key failed with error $err. Skipping this record");
1176 next if $err or not $xml;
1179 source_label => $provider->code,
1180 provider => $provider->id,
1184 $args{picklist} = $picklist->id if $picklist;
1186 $args{purchase_order} = $po->id;
1187 $args{state} = 'order-pending';
1190 my $li = create_lineitem($mgr, %args) or return $mgr->editor->die_event;
1192 $li->provider($provider); # flesh it, we'll need it later
1194 import_lineitem_details($mgr, $ordering_agency, $li) or return $mgr->editor->die_event;
1197 push(@li_list, $li->id);
1201 my $die_event = activate_purchase_order_impl($mgr, $po->id) if $po;;
1202 return $die_event if $die_event;
1206 $cache->delete_cache('vandelay_import_spool_' . $key);
1208 if($create_assets) {
1209 create_lineitem_list_assets($mgr, \@li_list) or return $e->die_event;
1212 return $mgr->respond_complete;
1215 sub import_lineitem_details {
1216 my($mgr, $ordering_agency, $li) = @_;
1218 my $holdings = $mgr->editor->json_query({from => ['acq.extract_provider_holding_data', $li->id]});
1219 return 1 unless @$holdings;
1220 my $org_path = $U->get_org_ancestors($ordering_agency);
1221 $org_path = [ reverse (@$org_path) ];
1226 # create a lineitem detail for each copy in the data
1228 my $compiled = extract_lineitem_detail_data($mgr, $org_path, $holdings, $idx);
1229 last unless defined $compiled;
1230 return 0 unless $compiled;
1232 # this takes the price of the last copy and uses it as the lineitem price
1233 # need to determine if a given record would include different prices for the same item
1234 $price = $$compiled{price};
1236 for(1..$$compiled{quantity}) {
1237 my $lid = create_lineitem_detail($mgr,
1238 lineitem => $li->id,
1239 owning_lib => $$compiled{owning_lib},
1240 cn_label => $$compiled{call_number},
1241 fund => $$compiled{fund},
1242 circ_modifier => $$compiled{circ_modifier},
1243 note => $$compiled{note},
1244 location => $$compiled{copy_location},
1245 collection_code => $$compiled{collection_code}
1253 $li->estimated_unit_price($price);
1254 update_lineitem($mgr, $li) or return 0;
1258 # return hash on success, 0 on error, undef on no more holdings
1259 sub extract_lineitem_detail_data {
1260 my($mgr, $org_path, $holdings, $index) = @_;
1262 my @data_list = grep { $_->{holding} eq $index } @$holdings;
1263 return undef unless @data_list;
1265 my %compiled = map { $_->{attr} => $_->{data} } @data_list;
1266 my $base_org = $$org_path[0];
1270 $logger->error("Item import extraction error: $msg");
1271 $logger->error('Holdings Data: ' . OpenSRF::Utils::JSON->perl2JSON(\%compiled));
1272 $mgr->editor->rollback;
1273 $mgr->editor->event(OpenILS::Event->new('ACQ_IMPORT_ERROR', payload => $msg));
1277 $compiled{quantity} ||= 1;
1279 # ---------------------------------------------------------------------
1281 my $code = $compiled{fund_code};
1282 return $killme->('no fund code provided') unless $code;
1284 my $fund = $mgr->cache($base_org, "fund.$code");
1286 # search up the org tree for the most appropriate fund
1287 for my $org (@$org_path) {
1288 $fund = $mgr->editor->search_acq_fund(
1289 {org => $org, code => $code, year => DateTime->now->year}, {idlist => 1})->[0];
1293 return $killme->("no fund with code $code at orgs [@$org_path]") unless $fund;
1294 $compiled{fund} = $fund;
1295 $mgr->cache($base_org, "fund.$code", $fund);
1298 # ---------------------------------------------------------------------
1300 my $sn = $compiled{owning_lib};
1301 return $killme->('no owning_lib defined') unless $sn;
1303 $mgr->cache($base_org, "orgsn.$sn") ||
1304 $mgr->editor->search_actor_org_unit({shortname => $sn}, {idlist => 1})->[0];
1305 return $killme->("invalid owning_lib defined: $sn") unless $org_id;
1306 $compiled{owning_lib} = $org_id;
1307 $mgr->cache($$org_path[0], "orgsn.$sn", $org_id);
1310 # ---------------------------------------------------------------------
1313 $code = $compiled{circ_modifier};
1317 $mod = $mgr->cache($base_org, "mod.$code") ||
1318 $mgr->editor->retrieve_config_circ_modifier($code);
1319 return $killme->("invlalid circ_modifier $code") unless $mod;
1320 $mgr->cache($base_org, "mod.$code", $mod);
1324 $mod = get_default_circ_modifier($mgr, $base_org)
1325 or return $killme->('no circ_modifier defined');
1328 $compiled{circ_modifier} = $mod;
1331 # ---------------------------------------------------------------------
1333 my $name = $compiled{copy_location};
1335 my $loc = $mgr->cache($base_org, "copy_loc.$name");
1337 for my $org (@$org_path) {
1338 $loc = $mgr->editor->search_asset_copy_location(
1339 {owning_lib => $org, name => $name}, {idlist => 1})->[0];
1343 return $killme->("Invalid copy location $name") unless $loc;
1344 $compiled{copy_location} = $loc;
1345 $mgr->cache($base_org, "copy_loc.$name", $loc);
1353 # ----------------------------------------------------------------------------
1354 # Workflow: Given an existing purchase order, import/create the bibs,
1355 # callnumber and copy objects
1356 # ----------------------------------------------------------------------------
1358 __PACKAGE__->register_method(
1359 method => 'create_po_assets',
1360 api_name => 'open-ils.acq.purchase_order.assets.create',
1362 desc => q/Creates assets for each lineitem in the purchase order/,
1364 {desc => 'Authentication token', type => 'string'},
1365 {desc => 'The purchase order id', type => 'number'},
1367 return => {desc => 'Streams a total versus completed counts object, event on error'}
1371 sub create_po_assets {
1372 my($self, $conn, $auth, $po_id) = @_;
1374 my $e = new_editor(authtoken=>$auth, xact=>1);
1375 return $e->die_event unless $e->checkauth;
1376 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1378 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1380 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1382 # it's ugly, but it's fast. Get the total count of lineitem detail objects to process
1383 my $lid_total = $e->json_query({
1384 select => { acqlid => [{aggregate => 1, transform => 'count', column => 'id'}] },
1390 join => {acqpo => {fkey => 'purchase_order', field => 'id'}}
1394 where => {'+acqpo' => {id => $po_id}}
1397 $mgr->total(scalar(@$li_ids) + $lid_total);
1399 create_lineitem_list_assets($mgr, $li_ids) or return $e->die_event;
1402 update_purchase_order($mgr, $po) or return $e->die_event;
1405 return $mgr->respond_complete;
1410 __PACKAGE__->register_method(
1411 method => 'create_purchase_order_api',
1412 api_name => 'open-ils.acq.purchase_order.create',
1414 desc => 'Creates a new purchase order',
1416 {desc => 'Authentication token', type => 'string'},
1417 {desc => 'purchase_order to create', type => 'object'}
1419 return => {desc => 'The purchase order id, Event on failure'}
1423 sub create_purchase_order_api {
1424 my($self, $conn, $auth, $po, $args) = @_;
1427 my $e = new_editor(xact=>1, authtoken=>$auth);
1428 return $e->die_event unless $e->checkauth;
1429 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
1430 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1433 my %pargs = (ordering_agency => $e->requestor->ws_ou); # default
1434 $pargs{provider} = $po->provider if $po->provider;
1435 $pargs{ordering_agency} = $po->ordering_agency if $po->ordering_agency;
1436 $po = create_purchase_order($mgr, %pargs) or return $e->die_event;
1438 my $li_ids = $$args{lineitems};
1442 for my $li_id (@$li_ids) {
1444 my $li = $e->retrieve_acq_lineitem([
1446 {flesh => 1, flesh_fields => {jub => ['attributes']}}
1447 ]) or return $e->die_event;
1449 $li->provider($po->provider);
1450 $li->purchase_order($po->id);
1451 $li->state('pending-order');
1452 update_lineitem($mgr, $li) or return $e->die_event;
1457 # commit before starting the asset creation
1460 if($li_ids and $$args{create_assets}) {
1461 create_lineitem_list_assets($mgr, $li_ids) or return $e->die_event;
1464 return $mgr->respond_complete;
1468 __PACKAGE__->register_method(
1469 method => 'lineitem_detail_CUD_batch',
1470 api_name => 'open-ils.acq.lineitem_detail.cud.batch',
1473 desc => q/Creates a new purchase order line item detail.
1474 Additionally creates the associated fund_debit/,
1476 {desc => 'Authentication token', type => 'string'},
1477 {desc => 'List of lineitem_details to create', type => 'array'},
1479 return => {desc => 'Streaming response of current position in the array'}
1483 sub lineitem_detail_CUD_batch {
1484 my($self, $conn, $auth, $li_details) = @_;
1486 my $e = new_editor(xact=>1, authtoken=>$auth);
1487 return $e->die_event unless $e->checkauth;
1488 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1492 $mgr->total(scalar(@$li_details));
1496 for my $lid (@$li_details) {
1498 my $li = $li_cache{$lid->lineitem} || $e->retrieve_acq_lineitem($lid->lineitem);
1501 create_lineitem_detail($mgr, %{$lid->to_bare_hash}) or return $e->die_event;
1503 } elsif($lid->ischanged) {
1504 $e->update_acq_lineitem_detail($lid) or return $e->die_event;
1506 } elsif($lid->isdeleted) {
1507 delete_lineitem_detail($mgr, $lid) or return $e->die_event;
1510 $mgr->respond(li => $li);
1511 $li_cache{$lid->lineitem} = $li;
1515 return $mgr->respond_complete;
1519 __PACKAGE__->register_method(
1520 method => 'receive_po_api',
1521 api_name => 'open-ils.acq.purchase_order.receive'
1524 sub receive_po_api {
1525 my($self, $conn, $auth, $po_id) = @_;
1526 my $e = new_editor(xact => 1, authtoken => $auth);
1527 return $e->die_event unless $e->checkauth;
1528 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1530 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1531 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1533 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1535 for my $li_id (@$li_ids) {
1536 receive_lineitem($mgr, $li_id) or return $e->die_event;
1540 $po->state('received');
1541 update_purchase_order($mgr, $po) or return $e->die_event;
1544 return $mgr->respond_complete;
1548 # At the moment there's a lack of parallelism between the receive and unreceive
1549 # API methods for POs and the API methods for LIs and LIDs. The methods for
1550 # POs stream back objects as they act, whereas the methods for LIs and LIDs
1551 # atomically return an object that describes only what changed (in LIs and LIDs
1552 # themselves or in the objects to which to LIs and LIDs belong).
1554 # The methods for LIs and LIDs work the way they do to faciliate the UI's
1555 # maintaining correct information about the state of these things when a user
1556 # wants to receive or unreceive these objects without refreshing their whole
1557 # display. The UI feature for receiving and un-receiving a whole PO just
1558 # refreshes the whole display, so this absence of parallelism in the UI is also
1559 # relected in this module.
1561 # This could be neatened in the future by making POs receive and unreceive in
1562 # the same way the LIs and LIDs do.
1564 __PACKAGE__->register_method(
1565 method => 'receive_lineitem_detail_api',
1566 api_name => 'open-ils.acq.lineitem_detail.receive',
1568 desc => 'Mark a lineitem_detail as received',
1570 {desc => 'Authentication token', type => 'string'},
1571 {desc => 'lineitem detail ID', type => 'number'}
1574 "on success, object describing changes to LID and possibly " .
1575 "to LI and PO; on error, Event"
1580 sub receive_lineitem_detail_api {
1581 my($self, $conn, $auth, $lid_id) = @_;
1583 my $e = new_editor(xact=>1, authtoken=>$auth);
1584 return $e->die_event unless $e->checkauth;
1585 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1588 "flesh" => 2, "flesh_fields" => {
1589 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
1593 my $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1595 return $e->die_event unless $e->allowed(
1596 'RECEIVE_PURCHASE_ORDER', $lid->lineitem->purchase_order->ordering_agency);
1599 my $recvd = receive_lineitem_detail($mgr, $lid_id) or return $e->die_event;
1601 # .. and re-retrieve
1602 $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1604 # Now build result data structure.
1605 my $result = {"lid" => {$lid->id => {"recv_time" => $lid->recv_time}}};
1608 if ($recvd->class_name =~ /::purchase_order/) {
1609 $result->{"po"} = describe_affected_po($e, $recvd);
1611 $lid->lineitem->id => {"state" => $lid->lineitem->state}
1613 } elsif ($recvd->class_name =~ /::lineitem/) {
1614 $result->{"li"} = {$recvd->id => {"state" => $recvd->state}};
1618 describe_affected_po($e, $lid->lineitem->purchase_order);
1624 __PACKAGE__->register_method(
1625 method => 'receive_lineitem_api',
1626 api_name => 'open-ils.acq.lineitem.receive',
1628 desc => 'Mark a lineitem as received',
1630 {desc => 'Authentication token', type => 'string'},
1631 {desc => 'lineitem ID', type => 'number'}
1634 "on success, object describing changes to LI and possibly PO; " .
1640 sub receive_lineitem_api {
1641 my($self, $conn, $auth, $li_id) = @_;
1643 my $e = new_editor(xact=>1, authtoken=>$auth);
1644 return $e->die_event unless $e->checkauth;
1645 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1647 my $li = $e->retrieve_acq_lineitem([
1651 jub => ['purchase_order']
1654 ]) or return $e->die_event;
1656 return $e->die_event unless $e->allowed(
1657 'RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);
1659 my $res = receive_lineitem($mgr, $li_id) or return $e->die_event;
1661 $conn->respond_complete($res);
1662 $mgr->run_post_response_hooks;
1666 __PACKAGE__->register_method(
1667 method => 'rollback_receive_po_api',
1668 api_name => 'open-ils.acq.purchase_order.receive.rollback'
1671 sub rollback_receive_po_api {
1672 my($self, $conn, $auth, $po_id) = @_;
1673 my $e = new_editor(xact => 1, authtoken => $auth);
1674 return $e->die_event unless $e->checkauth;
1675 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1677 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1678 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1680 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1682 for my $li_id (@$li_ids) {
1683 rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
1687 $po->state('on-order');
1688 update_purchase_order($mgr, $po) or return $e->die_event;
1691 return $mgr->respond_complete;
1695 __PACKAGE__->register_method(
1696 method => 'rollback_receive_lineitem_detail_api',
1697 api_name => 'open-ils.acq.lineitem_detail.receive.rollback',
1699 desc => 'Mark a lineitem_detail as Un-received',
1701 {desc => 'Authentication token', type => 'string'},
1702 {desc => 'lineitem detail ID', type => 'number'}
1705 "on success, object describing changes to LID and possibly " .
1706 "to LI and PO; on error, Event"
1711 sub rollback_receive_lineitem_detail_api {
1712 my($self, $conn, $auth, $lid_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 $lid = $e->retrieve_acq_lineitem_detail([
1722 acqlid => ['lineitem'],
1723 jub => ['purchase_order']
1727 my $li = $lid->lineitem;
1728 my $po = $li->purchase_order;
1730 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1734 my $recvd = rollback_receive_lineitem_detail($mgr, $lid_id)
1735 or return $e->die_event;
1738 $result->{"lid"} = {$recvd->id => {"recv_time" => $recvd->recv_time}};
1740 $result->{"lid"} = {$lid->id => {"recv_time" => $lid->recv_time}};
1743 if ($li->state eq "received") {
1744 $li->state("on-order");
1745 $li = update_lineitem($mgr, $li) or return $e->die_event;
1746 $result->{"li"} = {$li->id => {"state" => $li->state}};
1749 if ($po->state eq "received") {
1750 $po->state("on-order");
1751 $po = update_purchase_order($mgr, $po) or return $e->die_event;
1753 $result->{"po"} = describe_affected_po($e, $po);
1755 $e->commit and return $result or return $e->die_event;
1758 __PACKAGE__->register_method(
1759 method => 'rollback_receive_lineitem_api',
1760 api_name => 'open-ils.acq.lineitem.receive.rollback',
1762 desc => 'Mark a lineitem as Un-received',
1764 {desc => 'Authentication token', type => 'string'},
1765 {desc => 'lineitem ID', type => 'number'}
1768 "on success, object describing changes to LI and possibly PO; " .
1774 sub rollback_receive_lineitem_api {
1775 my($self, $conn, $auth, $li_id) = @_;
1777 my $e = new_editor(xact=>1, authtoken=>$auth);
1778 return $e->die_event unless $e->checkauth;
1779 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1781 my $li = $e->retrieve_acq_lineitem([
1783 "flesh" => 1, "flesh_fields" => {"jub" => ["purchase_order"]}
1786 my $po = $li->purchase_order;
1788 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1790 $li = rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
1792 my $result = {"li" => {$li->id => {"state" => $li->state}}};
1793 if ($po->state eq "received") {
1794 $po->state("on-order");
1795 $po = update_purchase_order($mgr, $po) or return $e->die_event;
1797 $result->{"po"} = describe_affected_po($e, $po);
1799 $e->commit and return $result or return $e->die_event;
1803 __PACKAGE__->register_method(
1804 method => 'set_lineitem_price_api',
1805 api_name => 'open-ils.acq.lineitem.price.set',
1807 desc => 'Set lineitem price. If debits already exist, update them as well',
1809 {desc => 'Authentication token', type => 'string'},
1810 {desc => 'lineitem ID', type => 'number'}
1812 return => {desc => 'status blob, Event on error'}
1816 sub set_lineitem_price_api {
1817 my($self, $conn, $auth, $li_id, $price) = @_;
1819 my $e = new_editor(xact=>1, authtoken=>$auth);
1820 return $e->die_event unless $e->checkauth;
1821 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1823 my $li = $e->retrieve_acq_lineitem([
1826 flesh_fields => {jub => ['purchase_order', 'picklist']}
1828 ]) or return $e->die_event;
1830 if($li->purchase_order) {
1831 return $e->die_event unless
1832 $e->allowed('CREATE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);
1834 return $e->die_event unless
1835 $e->allowed('CREATE_PICKLIST', $li->picklist->org_unit);
1838 $li->estimated_unit_price($price);
1839 update_lineitem($mgr, $li) or return $e->die_event;
1841 my $lid_ids = $e->search_acq_lineitem_detail(
1842 {lineitem => $li_id, fund_debit => {'!=' => undef}},
1846 for my $lid_id (@$lid_ids) {
1848 my $lid = $e->retrieve_acq_lineitem_detail([
1850 flesh => 1, flesh_fields => {acqlid => ['fund', 'fund_debit']}}
1853 $lid->fund_debit->amount($price);
1854 $e->update_acq_fund_debit($lid->fund_debit) or return $e->die_event;
1860 return $mgr->respond_complete;
1864 __PACKAGE__->register_method(
1865 method => 'clone_picklist_api',
1866 api_name => 'open-ils.acq.picklist.clone',
1868 desc => 'Clones a picklist, including lineitem and lineitem details',
1870 {desc => 'Authentication token', type => 'string'},
1871 {desc => 'Picklist ID', type => 'number'},
1872 {desc => 'New Picklist Name', type => 'string'}
1874 return => {desc => 'status blob, Event on error'}
1878 sub clone_picklist_api {
1879 my($self, $conn, $auth, $pl_id, $name) = @_;
1881 my $e = new_editor(xact=>1, authtoken=>$auth);
1882 return $e->die_event unless $e->checkauth;
1883 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1885 my $old_pl = $e->retrieve_acq_picklist($pl_id);
1886 my $new_pl = create_picklist($mgr, %{$old_pl->to_bare_hash}, name => $name) or return $e->die_event;
1888 my $li_ids = $e->search_acq_lineitem({picklist => $pl_id}, {idlist => 1});
1890 for my $li_id (@$li_ids) {
1892 # copy the lineitems
1893 my $li = $e->retrieve_acq_lineitem($li_id);
1894 my $new_li = create_lineitem($mgr, %{$li->to_bare_hash}, picklist => $new_pl->id) or return $e->die_event;
1896 my $lid_ids = $e->search_acq_lineitem_detail({lineitem => $li_id}, {idlist => 1});
1897 for my $lid_id (@$lid_ids) {
1899 # copy the lineitem details
1900 my $lid = $e->retrieve_acq_lineitem_detail($lid_id);
1901 create_lineitem_detail($mgr, %{$lid->to_bare_hash}, lineitem => $new_li->id) or return $e->die_event;
1908 return $mgr->respond_complete;
1912 __PACKAGE__->register_method(
1913 method => 'merge_picklist_api',
1914 api_name => 'open-ils.acq.picklist.merge',
1916 desc => 'Merges 2 or more picklists into a single list',
1918 {desc => 'Authentication token', type => 'string'},
1919 {desc => 'Lead Picklist ID', type => 'number'},
1920 {desc => 'List of subordinate picklist IDs', type => 'array'}
1922 return => {desc => 'status blob, Event on error'}
1926 sub merge_picklist_api {
1927 my($self, $conn, $auth, $lead_pl, $pl_list) = @_;
1929 my $e = new_editor(xact=>1, authtoken=>$auth);
1930 return $e->die_event unless $e->checkauth;
1931 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1933 # XXX perms on each picklist modified
1935 # point all of the lineitems at the lead picklist
1936 my $li_ids = $e->search_acq_lineitem({picklist => $pl_list}, {idlist => 1});
1938 for my $li_id (@$li_ids) {
1939 my $li = $e->retrieve_acq_lineitem($li_id);
1940 $li->picklist($lead_pl);
1941 update_lineitem($mgr, $li) or return $e->die_event;
1945 # now delete the subordinate lists
1946 for my $pl_id (@$pl_list) {
1947 my $pl = $e->retrieve_acq_picklist($pl_id);
1948 $e->delete_acq_picklist($pl) or return $e->die_event;
1952 return $mgr->respond_complete;
1956 __PACKAGE__->register_method(
1957 method => 'delete_picklist_api',
1958 api_name => 'open-ils.acq.picklist.delete',
1960 desc => q/Deletes a picklist. It also deletes any lineitems in the "new" state.
1961 Other attached lineitems are detached'/,
1963 {desc => 'Authentication token', type => 'string'},
1964 {desc => 'Picklist ID to delete', type => 'number'}
1966 return => {desc => '1 on success, Event on error'}
1970 sub delete_picklist_api {
1971 my($self, $conn, $auth, $picklist_id) = @_;
1972 my $e = new_editor(xact=>1, authtoken=>$auth);
1973 return $e->die_event unless $e->checkauth;
1974 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1975 my $pl = $e->retrieve_acq_picklist($picklist_id) or return $e->die_event;
1976 delete_picklist($mgr, $pl) or return $e->die_event;
1978 return $mgr->respond_complete;
1983 __PACKAGE__->register_method(
1984 method => 'activate_purchase_order',
1985 api_name => 'open-ils.acq.purchase_order.activate',
1987 desc => q/Activates a purchase order. This updates the status of the PO
1988 and Lineitems to 'on-order'. Activated PO's are ready for EDI delivery
1991 {desc => 'Authentication token', type => 'string'},
1992 {desc => 'Purchase ID', type => 'number'}
1994 return => {desc => '1 on success, Event on error'}
1998 sub activate_purchase_order {
1999 my($self, $conn, $auth, $po_id) = @_;
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);
2003 my $die_event = activate_purchase_order_impl($mgr, $po_id);
2004 return $die_event if $die_event;
2006 $conn->respond_complete(1);
2007 $mgr->run_post_response_hooks;
2011 sub activate_purchase_order_impl {
2012 my($mgr, $po_id) = @_;
2013 my $e = $mgr->editor;
2015 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2016 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
2018 $po->state('on-order');
2019 update_purchase_order($mgr, $po) or return $e->die_event;
2022 {purchase_order => $po_id, state => 'pending-order'},
2026 while( my $li = $e->search_acq_lineitem($query)->[0] ) {
2027 $li->state('on-order');
2028 create_lineitem_debits($mgr, $li) or return $e->die_event;
2029 update_lineitem($mgr, $li) or return $e->die_event;
2030 $mgr->post_process( sub { create_lineitem_status_events($mgr, $li->id, 'aur.ordered'); });
2038 __PACKAGE__->register_method(
2039 method => 'split_purchase_order_by_lineitems',
2040 api_name => 'open-ils.acq.purchase_order.split_by_lineitems',
2042 desc => q/Splits a PO into many POs, 1 per lineitem. Only works for
2043 POs a) with more than one lineitems, and b) in the "pending" state./,
2045 {desc => 'Authentication token', type => 'string'},
2046 {desc => 'Purchase order ID', type => 'number'}
2048 return => {desc => 'list of new PO IDs on success, Event on error'}
2052 sub split_purchase_order_by_lineitems {
2053 my ($self, $conn, $auth, $po_id) = @_;
2055 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2056 return $e->die_event unless $e->checkauth;
2058 my $po = $e->retrieve_acq_purchase_order([
2061 "flesh_fields" => {"acqpo" => [qw/lineitems notes/]}
2063 ]) or return $e->die_event;
2065 return $e->die_event
2066 unless $e->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2068 unless ($po->state eq "pending") {
2070 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_LATE");
2073 unless (@{$po->lineitems} > 1) {
2075 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_SHORT");
2078 # To split an existing PO into many, it seems unwise to just delete the
2079 # original PO, so we'll instead detach all of the original POs' lineitems
2080 # but the first, then create new POs for each of the remaining LIs, and
2081 # then attach the LIs to their new POs.
2083 my @po_ids = ($po->id);
2084 my @moving_li = @{$po->lineitems};
2085 shift @moving_li; # discard first LI
2087 foreach my $li (@moving_li) {
2088 my $new_po = $po->clone;
2090 $new_po->clear_name;
2091 $new_po->creator($e->requestor->id);
2092 $new_po->editor($e->requestor->id);
2093 $new_po->owner($e->requestor->id);
2094 $new_po->edit_time("now");
2095 $new_po->create_time("now");
2097 $new_po = $e->create_acq_purchase_order($new_po);
2099 # Clone any notes attached to the old PO and attach to the new one.
2100 foreach my $note (@{$po->notes}) {
2101 my $new_note = $note->clone;
2102 $new_note->clear_id;
2103 $new_note->edit_time("now");
2104 $new_note->purchase_order($new_po->id);
2105 $e->create_acq_po_note($new_note);
2108 $li->edit_time("now");
2109 $li->purchase_order($new_po->id);
2110 $e->update_acq_lineitem($li);
2112 push @po_ids, $new_po->id;
2115 $po->edit_time("now");
2116 $e->update_acq_purchase_order($po);
2118 return \@po_ids if $e->commit;
2119 return $e->die_event;
2123 __PACKAGE__->register_method(
2124 method => 'cancel_lineitem_api',
2125 api_name => 'open-ils.acq.lineitem.cancel',
2127 desc => q/Cancels an on-order lineitem/,
2129 {desc => 'Authentication token', type => 'string'},
2130 {desc => 'Lineitem ID to cancel', type => 'number'},
2131 {desc => 'Cancel Cause ID', type => 'number'}
2133 return => {desc => '1 on success, Event on error'}
2137 sub cancel_lineitem_api {
2138 my($self, $conn, $auth, $li_id, $cancel_cause) = @_;
2140 my $e = new_editor(xact=>1, authtoken=>$auth);
2141 return $e->die_event unless $e->checkauth;
2142 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2144 my $li = $e->retrieve_acq_lineitem([$li_id,
2145 {flesh => 1, flesh_fields => {jub => [q/purchase_order/]}}]);
2147 unless( $li->purchase_order and ($li->state eq 'on-order' or $li->state eq 'pending-order') ) {
2149 return OpenILS::Event->new('BAD_PARAMS')
2152 return $e->die_event unless
2153 $e->allowed('CREATE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);
2155 $li->state('cancelled');
2157 # TODO delete the associated fund debits?
2158 # TODO add support for cancel reasons
2159 # TODO who/what/where/how do we indicate this change for electronic orders?
2161 update_lineitem($mgr, $li) or return $e->die_event;
2164 $conn->respond_complete($li);
2165 create_lineitem_status_events($mgr, $li_id, 'aur.cancelled');
2169 __PACKAGE__->register_method (
2170 method => 'user_requests',
2171 api_name => 'open-ils.acq.user_request.retrieve.by_user_id',
2174 Retrieve fleshed user requests and related data for a given user or users.
2175 @param authtoken Login session key
2176 @param owner Id or array of id's for the pertinent users.
2177 @param options Allows one to override the query's 'order_by', 'limit', and 'offset'. And the 'state' of the lineitem in the search.
2181 __PACKAGE__->register_method (
2182 method => 'user_requests',
2183 api_name => 'open-ils.acq.user_request.retrieve.by_home_ou',
2186 Retrieve fleshed user requests and related data for a given org unit or units.
2187 @param authtoken Login session key
2188 @param owner Id or array of id's for the pertinent org units.
2189 @param options Allows one to override the query's 'order_by', 'limit', and 'offset'. And the 'state' of the lineitem in the search.
2194 my($self, $conn, $auth, $search_value, $options) = @_;
2195 my $e = new_editor(authtoken => $auth);
2196 return $e->event unless $e->checkauth;
2197 my $rid = $e->requestor->id;
2200 "select"=>{"aur"=>["id"],"au"=>["home_ou", {column => 'id', alias => 'usr_id'} ]},
2201 "from"=>{ "aur" => { "au" => {}, "jub" => { "type" => "left" } } },
2205 {"id"=>undef}, # this with the left-join pulls in requests without lineitems
2206 {"state"=>["new","on-order","pending-order"]} # FIXME - probably needs softcoding
2210 "order_by"=>[{"class"=>"aur", "field"=>"request_date", "direction"=>"desc"}]
2213 if ($options && defined $options->{'order_by'}) {
2214 $query->{'order_by'} = $options->{'order_by'};
2216 if ($options && defined $options->{'limit'}) {
2217 $query->{'limit'} = $options->{'limit'};
2219 if ($options && defined $options->{'offset'}) {
2220 $query->{'offset'} = $options->{'offset'};
2222 if ($options && defined $options->{'state'}) {
2223 $query->{'where'}->{'+jub'}->{'-or'}->[1]->{'state'} = $options->{'state'};
2226 if ($self->api_name =~ /by_user_id/) {
2227 $query->{'where'}->{'usr'} = $search_value;
2229 $query->{'where'}->{'+au'} = { 'home_ou' => $search_value };
2232 my $pertinent_ids = $e->json_query($query);
2235 for my $id_blob (@$pertinent_ids) {
2236 if ($rid != $id_blob->{usr_id}) {
2237 if (!defined $perm_test{ $id_blob->{home_ou} }) {
2238 $perm_test{ $id_blob->{home_ou} } = $e->allowed( ['user_request.view'], $id_blob->{home_ou} );
2240 if (!$perm_test{ $id_blob->{home_ou} }) {
2244 my $aur_obj = $e->retrieve_acq_user_request([
2246 {flesh => 1, flesh_fields => { "aur" => [ 'lineitem' ] } }
2248 if (! $aur_obj) { next; }
2250 if ($aur_obj->lineitem()) {
2251 $aur_obj->lineitem()->clear_marc();
2253 $conn->respond($aur_obj);
2259 __PACKAGE__->register_method (
2260 method => 'update_user_request',
2261 api_name => 'open-ils.acq.user_request.cancel.batch',
2264 __PACKAGE__->register_method (
2265 method => 'update_user_request',
2266 api_name => 'open-ils.acq.user_request.set_no_hold.batch',
2270 sub update_user_request {
2271 my($self, $conn, $auth, $aur_ids) = @_;
2272 my $e = new_editor(xact => 1, authtoken => $auth);
2273 return $e->die_event unless $e->checkauth;
2274 my $rid = $e->requestor->id;
2278 for my $id (@$aur_ids) {
2280 my $aur_obj = $e->retrieve_acq_user_request([
2283 flesh_fields => { "aur" => ['lineitem', 'usr'] }
2285 ]) or return $e->die_event;
2287 my $context_org = $aur_obj->usr()->home_ou();
2288 $aur_obj->usr( $aur_obj->usr()->id() );
2290 if ($rid != $aur_obj->usr) {
2291 if (!defined $perm_test{ $context_org }) {
2292 $perm_test{ $context_org } = $e->allowed( ['user_request.update'], $context_org );
2294 if (!$perm_test{ $context_org }) {
2299 if($self->api_name =~ /set_no_hold/) {
2300 if ($U->is_true($aur_obj->hold)) {
2302 $e->update_acq_user_request($aur_obj) or return $e->die_event;
2306 if($self->api_name =~ /cancel/) {
2307 $e->delete_acq_user_request($aur_obj);
2310 $conn->respond({maximum => scalar(@$aur_ids), progress => $x++});
2314 return {complete => 1};
2317 __PACKAGE__->register_method (
2318 method => 'new_user_request',
2319 api_name => 'open-ils.acq.user_request.create'
2322 sub new_user_request {
2323 my($self, $conn, $auth, $form_data) = @_;
2324 my $e = new_editor(xact => 1, authtoken => $auth);
2325 return $e->die_event unless $e->checkauth;
2326 my $rid = $e->requestor->id;
2327 my $target_user_fleshed;
2328 if (! defined $$form_data{'usr'}) {
2329 $$form_data{'usr'} = $rid;
2331 if ($$form_data{'usr'} != $rid) {
2332 # See if the requestor can place the request on behalf of a different user.
2333 $target_user_fleshed = $e->retrieve_actor_user($$form_data{'usr'}) or return $e->die_event;
2334 $e->allowed('user_request.create', $target_user_fleshed->home_ou) or return $e->die_event;
2336 $target_user_fleshed = $e->requestor;
2337 $e->allowed('CREATE_PURCHASE_REQUEST') or return $e->die_event;
2339 if (! defined $$form_data{'pickup_lib'}) {
2340 if ($target_user_fleshed->ws_ou) {
2341 $$form_data{'pickup_lib'} = $target_user_fleshed->ws_ou;
2343 $$form_data{'pickup_lib'} = $target_user_fleshed->home_ou;
2346 if (! defined $$form_data{'request_type'}) {
2347 $$form_data{'request_type'} = 1; # Books
2349 my $aur_obj = new Fieldmapper::acq::user_request;
2351 $aur_obj->usr( $$form_data{'usr'} );
2352 $aur_obj->request_date( 'now' );
2353 for my $field ( keys %$form_data ) {
2354 if (defined $$form_data{$field} and $field !~ /^(id|lineitem|eg_bib|request_date|cancel_reason)$/) {
2355 $aur_obj->$field( $$form_data{$field} );
2359 $aur_obj = $e->create_acq_user_request($aur_obj) or $e->die_event;