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);
18 purchase_order => undef,
26 $self->throttle(4) unless $self->throttle;
27 $self->{post_proc_queue} = [];
28 $self->{last_respond_progress} = 0;
34 $self->{conn} = $val if $val;
39 $self->{throttle} = $val if $val;
40 return $self->{throttle};
43 my($self, %other_args) = @_;
44 if($self->throttle and not %other_args) {
46 ($self->{args}->{progress} - $self->{last_respond_progress}) >= $self->throttle
49 $self->conn->respond({ %{$self->{args}}, %other_args });
50 $self->{last_respond_progress} = $self->{args}->{progress};
51 $self->throttle($self->throttle * 2) unless $self->throttle >= 256;
53 sub respond_complete {
54 my($self, %other_args) = @_;
56 $self->conn->respond_complete({ %{$self->{args}}, %other_args });
57 $self->run_post_response_hooks;
61 # run the post response hook subs, shifting them off as we go
62 sub run_post_response_hooks {
64 (shift @{$self->{post_proc_queue}})->() while @{$self->{post_proc_queue}};
67 # any subs passed to this method will be run after the call to respond_complete
70 push(@{$self->{post_proc_queue}}, $sub);
75 $self->{args}->{total} = $val if defined $val;
76 $self->{args}->{maximum} = $self->{args}->{total};
77 return $self->{args}->{total};
81 $self->{args}->{purchase_order} = $val if $val;
86 $self->{args}->{picklist} = $val if $val;
91 $self->{args}->{lid} += 1;
92 $self->{args}->{progress} += 1;
97 $self->{args}->{li} += 1;
98 $self->{args}->{progress} += 1;
103 $self->{args}->{vqbr} += 1;
104 $self->{args}->{progress} += 1;
109 $self->{args}->{copies} += 1;
110 $self->{args}->{progress} += 1;
115 $self->{args}->{bibs} += 1;
116 $self->{args}->{progress} += 1;
120 my($self, $amount) = @_;
121 $self->{args}->{debits_accrued} += $amount;
122 $self->{args}->{progress} += 1;
126 my($self, $editor) = @_;
127 $self->{editor} = $editor if defined $editor;
128 return $self->{editor};
132 $self->{args}->{complete} = 1;
137 my($self, $org, $key, $val) = @_;
138 $self->{cache}->{$org} = {} unless $self->{cache}->{org};
139 $self->{cache}->{$org}->{$key} = $val if defined $val;
140 return $self->{cache}->{$org}->{$key};
144 package OpenILS::Application::Acq::Order;
145 use base qw/OpenILS::Application/;
146 use strict; use warnings;
147 # ----------------------------------------------------------------------------
148 # Break up each component of the order process and pieces into managable
149 # actions that can be shared across different workflows
150 # ----------------------------------------------------------------------------
152 use OpenSRF::Utils::Logger qw(:logger);
153 use OpenSRF::Utils::JSON;
154 use OpenSRF::AppSession;
155 use OpenILS::Utils::Fieldmapper;
156 use OpenILS::Utils::CStoreEditor q/:funcs/;
157 use OpenILS::Utils::Normalize qw/clean_marc/;
158 use OpenILS::Const qw/:const/;
159 use OpenSRF::EX q/:try/;
160 use OpenILS::Application::AppUtils;
161 use OpenILS::Application::Cat::BibCommon;
162 use OpenILS::Application::Cat::AssetCommon;
165 use MARC::File::XML (BinaryEncoding => 'UTF-8');
166 use Digest::MD5 qw(md5_hex);
168 $Data::Dumper::Indent = 0;
169 my $U = 'OpenILS::Application::AppUtils';
172 # ----------------------------------------------------------------------------
174 # ----------------------------------------------------------------------------
175 sub create_lineitem {
176 my($mgr, %args) = @_;
177 my $li = Fieldmapper::acq::lineitem->new;
178 $li->creator($mgr->editor->requestor->id);
179 $li->selector($li->creator);
180 $li->editor($li->creator);
181 $li->create_time('now');
182 $li->edit_time('now');
184 $li->$_($args{$_}) for keys %args;
187 $mgr->editor->create_acq_lineitem($li) or return 0;
189 unless($li->estimated_unit_price) {
190 # extract the price from the MARC data
191 my $price = get_li_price_from_attr($mgr->editor, $li) or return $li;
192 $li->estimated_unit_price($price);
193 return update_lineitem($mgr, $li);
199 sub get_li_price_from_attr {
201 my $attrs = $li->attributes || $e->search_acq_lineitem_attr({lineitem => $li->id});
203 for my $attr_type (qw/
204 lineitem_local_attr_definition
205 lineitem_prov_attr_definition
206 lineitem_marc_attr_definition/) {
209 $_->attr_name eq 'estimated_price' and
210 $_->attr_type eq $attr_type } @$attrs;
212 return $attr->attr_value if $attr;
219 sub update_lineitem {
221 $li->edit_time('now');
222 $li->editor($mgr->editor->requestor->id);
224 return $mgr->editor->retrieve_acq_lineitem($mgr->editor->data) if
225 $mgr->editor->update_acq_lineitem($li);
230 # ----------------------------------------------------------------------------
231 # Create real holds from patron requests for a given lineitem
232 # ----------------------------------------------------------------------------
233 sub promote_lineitem_holds {
236 my $requests = $mgr->editor->search_acq_user_request(
237 { lineitem => $li->id,
239 [ { need_before => {'>' => 'now'} },
240 { need_before => undef }
245 for my $request ( @$requests ) {
247 $request->eg_bib( $li->eg_bib_id );
248 $mgr->editor->update_acq_user_request( $request ) or return 0;
250 next unless ($U->is_true( $request->hold ));
252 my $hold = Fieldmapper::action::hold_request->new;
253 $hold->usr( $request->usr );
254 $hold->requestor( $request->usr );
255 $hold->request_time( $request->request_date );
256 $hold->pickup_lib( $request->pickup_lib );
257 $hold->request_lib( $request->pickup_lib );
258 $hold->selection_ou( $request->pickup_lib );
259 $hold->phone_notify( $request->phone_notify );
260 $hold->email_notify( $request->email_notify );
261 $hold->expire_time( $request->need_before );
263 if ($request->holdable_formats) {
264 my $mrm = $mgr->editor->search_metabib_metarecord_source_map( { source => $li->eg_bib_id } )->[0];
266 $hold->hold_type( 'M' );
267 $hold->holdable_formats( $request->holdable_formats );
268 $hold->target( $mrm->metarecord );
272 if (!$hold->target) {
273 $hold->hold_type( 'T' );
274 $hold->target( $li->eg_bib_id );
277 $mgr->editor->create_actor_hold_request( $hold ) or return 0;
283 sub delete_lineitem {
285 $li = $mgr->editor->retrieve_acq_lineitem($li) unless ref $li;
287 # delete the attached lineitem_details
288 my $lid_ids = $mgr->editor->search_acq_lineitem_detail({lineitem => $li->id}, {idlist=>1});
289 for my $lid_id (@$lid_ids) {
290 return 0 unless delete_lineitem_detail($mgr, $lid_id);
294 return $mgr->editor->delete_acq_lineitem($li);
297 # begins and commit transactions as it goes
298 # bib_only exits before creation of copies and callnumbers
299 sub create_lineitem_list_assets {
300 my($mgr, $li_ids, $vandelay, $bib_only) = @_;
302 if (check_import_li_marc_perms($mgr, $li_ids)) { # event on error
303 $logger->error("acq-vl: user does not have permission to import acq records");
307 my $res = import_li_bibs_via_vandelay($mgr, $li_ids, $vandelay);
308 return undef unless $res;
309 return $res if $bib_only;
311 # create the bibs/volumes/copies for the successfully imported records
312 for my $li_id (@{$res->{li_ids}}) {
313 $mgr->editor->xact_begin;
314 my $data = create_lineitem_assets($mgr, $li_id) or return undef;
315 $mgr->editor->xact_commit;
322 sub test_vandelay_import_args {
323 my $vandelay = shift;
326 return 0 unless $vandelay and
327 ($vandelay->{queue_name} or $vandelay->{existing_queue});
329 # match-based merge/overlay import
330 return 2 if $vandelay->{merge_profile} and (
331 $vandelay->{auto_overlay_exact} or
332 $vandelay->{auto_overlay_1match} or
333 $vandelay->{auto_overlay_best_match}
337 return 2 if $vandelay->{import_no_match};
339 return 1; # queue only
342 sub find_or_create_vandelay_queue {
343 my ($e, $vandelay) = @_;
346 if (my $name = $vandelay->{queue_name}) {
348 # first, see if a queue w/ this name already exists
349 # for this user. If so, use that instead.
351 $queue = $e->search_vandelay_bib_queue(
352 {name => $name, owner => $e->requestor->id})->[0];
356 $logger->info("acq-vl: using existing queue $name");
360 $logger->info("acq-vl: creating new vandelay queue $name");
362 $queue = new Fieldmapper::vandelay::bib_queue;
364 $queue->queue_type('acq');
365 $queue->owner($e->requestor->id);
366 $queue->match_set($vandelay->{match_set} || undef); # avoid ''
367 $queue = $e->create_vandelay_bib_queue($queue) or return undef;
371 $queue = $e->retrieve_vandelay_bib_queue($vandelay->{existing_queue})
379 sub import_li_bibs_via_vandelay {
380 my ($mgr, $li_ids, $vandelay) = @_;
381 my $res = {li_ids => []};
382 my $e = $mgr->editor;
385 my $needs_importing = $e->search_acq_lineitem(
386 {id => $li_ids, eg_bib_id => undef},
390 if (!@$needs_importing) {
391 $logger->info("acq-vl: all records already imported. no Vandelay work to do");
392 return {li_ids => $li_ids};
395 # add the already-imported records to the response list
396 push(@{$res->{li_ids}}, grep { $_ != @$needs_importing } @$li_ids);
398 $logger->info("acq-vl: processing recs via Vandelay with args: ".Dumper($vandelay));
400 my $vl_stat = test_vandelay_import_args($vandelay);
402 $logger->error("acq-vl: invalid vandelay arguments for acq import (queue needed)");
406 my $queue = find_or_create_vandelay_queue($e, $vandelay) or return $res;
407 $mgr->{args}->{queue} = $queue;
409 # load the lineitems into the queue for merge processing
412 for my $li_id (@$needs_importing) {
414 my $li = $e->retrieve_acq_lineitem($li_id) or return $res;
416 my $vqbr = Fieldmapper::vandelay::queued_bib_record->new;
417 $vqbr->marc($li->marc);
418 $vqbr->queue($queue->id);
419 $vqbr->bib_source($vandelay->{bib_source} || undef); # avoid ''
420 $vqbr = $e->create_vandelay_queued_bib_record($vqbr) or return $res;
421 push(@vqbr_ids, $vqbr->id);
425 # tell the acq record which vandelay record it's linked to
426 $li->queued_record($vqbr->id);
427 $e->update_acq_lineitem($li) or return $res;
431 $logger->info("acq-vl: created vandelay records [@vqbr_ids]");
433 # we have to commit the transaction now since
434 # vandelay uses its own transactions.
437 return $res if $vl_stat == 1; # queue only
439 # Import the bibs via vandelay. Note: Vandely will
440 # update acq.lineitem.eg_bib_id on successful import.
442 $vandelay->{report_all} = 1;
443 my $ses = OpenSRF::AppSession->create('open-ils.vandelay');
444 my $req = $ses->request(
445 'open-ils.vandelay.bib_record.list.import',
446 $e->authtoken, \@vqbr_ids, $vandelay);
448 # pull the responses, noting all that were successfully imported
450 while (my $resp = $req->recv(timeout => 600)) {
451 my $stat = $resp->content;
453 if(!$stat or $U->event_code($stat)) { # import failure
454 $logger->error("acq-vl: error importing vandelay record " . Dumper($stat));
458 # "imported" refers to the vqbr id, not the
459 # success/failure of the vqbr merge attempt
460 next unless $stat->{imported};
462 my ($imported) = grep {$_->queued_record eq $stat->{imported}} @lis;
463 my $li_id = $imported->id;
465 if ($stat->{no_import}) {
466 $logger->info("acq-vl: acq lineitem $li_id did not import");
468 } else { # successful import
470 push(@success_lis, $li_id);
473 $logger->info("acq-vl: acq lineitem $li_id successfully merged/imported");
478 $logger->info("acq-vl: successfully imported lineitems [@success_lis]");
480 # add the successfully imported lineitems to the already-imported lineitems
481 push (@{$res->{li_ids}}, @success_lis);
486 # returns event on error, undef on success
487 sub check_import_li_marc_perms {
488 my($mgr, $li_ids) = @_;
490 # if there are any order records that are not linked to
491 # in-db bib records, verify staff has perms to import order records
492 my $order_li = $mgr->editor->search_acq_lineitem(
493 [{id => $li_ids, eg_bib_id => undef}, {limit => 1}], {idlist => 1})->[0];
496 return $mgr->editor->die_event unless
497 $mgr->editor->allowed('IMPORT_ACQ_LINEITEM_BIB_RECORD');
504 # ----------------------------------------------------------------------------
505 # if all of the lineitem details for this lineitem have
506 # been received, mark the lineitem as received
507 # returns 1 on non-received, li on received, 0 on error
508 # ----------------------------------------------------------------------------
510 sub describe_affected_po {
514 OpenILS::Application::Acq::Financials::build_price_summary(
519 "state" => $po->state,
520 "amount_encumbered" => $enc,
521 "amount_spent" => $spent
526 sub check_lineitem_received {
527 my($mgr, $li_id) = @_;
529 my $non_recv = $mgr->editor->search_acq_lineitem_detail(
530 {recv_time => undef, lineitem => $li_id}, {idlist=>1});
532 return 1 if @$non_recv;
534 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
535 $li->state('received');
536 return update_lineitem($mgr, $li);
539 sub receive_lineitem {
540 my($mgr, $li_id, $skip_complete_check) = @_;
541 my $li = $mgr->editor->retrieve_acq_lineitem($li_id) or return 0;
543 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
544 {lineitem => $li_id, recv_time => undef}, {idlist => 1});
546 for my $lid_id (@$lid_ids) {
547 receive_lineitem_detail($mgr, $lid_id, 1) or return 0;
551 $li->state('received');
553 $li = update_lineitem($mgr, $li) or return 0;
554 $mgr->post_process( sub { create_lineitem_status_events($mgr, $li_id, 'aur.received'); });
558 $skip_complete_check or (
559 $po = check_purchase_order_received($mgr, $li->purchase_order)
562 my $result = {"li" => {$li->id => {"state" => $li->state}}};
563 $result->{"po"} = describe_affected_po($mgr->editor, $po) if ref $po;
567 sub rollback_receive_lineitem {
568 my($mgr, $li_id) = @_;
569 my $li = $mgr->editor->retrieve_acq_lineitem($li_id) or return 0;
571 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
572 {lineitem => $li_id, recv_time => {'!=' => undef}}, {idlist => 1});
574 for my $lid_id (@$lid_ids) {
575 rollback_receive_lineitem_detail($mgr, $lid_id, 1) or return 0;
579 $li->state('on-order');
580 return update_lineitem($mgr, $li);
584 sub create_lineitem_status_events {
585 my($mgr, $li_id, $hook) = @_;
587 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
589 my $user_reqs = $mgr->editor->search_acq_user_request([
590 {lineitem => $li_id},
591 {flesh => 1, flesh_fields => {aur => ['usr']}}
594 for my $user_req (@$user_reqs) {
595 my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $user_req->usr->home_ou);
603 # ----------------------------------------------------------------------------
605 # ----------------------------------------------------------------------------
606 sub create_lineitem_detail {
607 my($mgr, %args) = @_;
608 my $lid = Fieldmapper::acq::lineitem_detail->new;
609 $lid->$_($args{$_}) for keys %args;
612 return $mgr->editor->create_acq_lineitem_detail($lid);
616 # flesh out any required data with default values where appropriate
617 sub complete_lineitem_detail {
619 unless($lid->barcode) {
620 my $pfx = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.tmp_barcode_prefix') || 'ACQ';
621 $lid->barcode($pfx.$lid->id);
624 unless($lid->cn_label) {
625 my $pfx = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.tmp_callnumber_prefix') || 'ACQ';
626 $lid->cn_label($pfx.$lid->id);
629 if(!$lid->location and my $loc = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.default_copy_location')) {
630 $lid->location($loc);
633 $lid->circ_modifier(get_default_circ_modifier($mgr, $lid->owning_lib))
634 unless defined $lid->circ_modifier;
636 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
640 sub get_default_circ_modifier {
642 my $code = $mgr->cache($org, 'def_circ_mod');
643 $code = $U->ou_ancestor_setting_value($org, 'acq.default_circ_modifier') unless defined $code;
644 return $mgr->cache($org, 'def_circ_mod', $code) if defined $code;
648 sub delete_lineitem_detail {
650 $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid) unless ref $lid;
651 return $mgr->editor->delete_acq_lineitem_detail($lid);
655 sub receive_lineitem_detail {
656 my($mgr, $lid_id, $skip_complete_check) = @_;
657 my $e = $mgr->editor;
659 my $lid = $e->retrieve_acq_lineitem_detail([
663 acqlid => ['fund_debit']
668 return 1 if $lid->recv_time;
670 $lid->receiver($e->requestor->id);
671 $lid->recv_time('now');
672 $e->update_acq_lineitem_detail($lid) or return 0;
674 if ($lid->eg_copy_id) {
675 my $copy = $e->retrieve_asset_copy($lid->eg_copy_id) or return 0;
676 $copy->status(OILS_COPY_STATUS_IN_PROCESS);
677 $copy->edit_date('now');
678 $copy->editor($e->requestor->id);
679 $copy->creator($e->requestor->id) if $U->ou_ancestor_setting_value(
680 $e->requestor->ws_ou, 'acq.copy_creator_uses_receiver', $e);
681 $e->update_asset_copy($copy) or return 0;
686 return 1 if $skip_complete_check;
688 my $li = check_lineitem_received($mgr, $lid->lineitem) or return 0;
689 return 1 if $li == 1; # li not received
691 return check_purchase_order_received($mgr, $li->purchase_order) or return 0;
695 sub rollback_receive_lineitem_detail {
696 my($mgr, $lid_id) = @_;
697 my $e = $mgr->editor;
699 my $lid = $e->retrieve_acq_lineitem_detail([
703 acqlid => ['fund_debit']
708 return 1 unless $lid->recv_time;
710 $lid->clear_receiver;
711 $lid->clear_recv_time;
712 $e->update_acq_lineitem_detail($lid) or return 0;
714 if ($lid->eg_copy_id) {
715 my $copy = $e->retrieve_asset_copy($lid->eg_copy_id) or return 0;
716 $copy->status(OILS_COPY_STATUS_ON_ORDER);
717 $copy->edit_date('now');
718 $copy->editor($e->requestor->id);
719 $e->update_asset_copy($copy) or return 0;
726 # ----------------------------------------------------------------------------
728 # ----------------------------------------------------------------------------
729 sub set_lineitem_attr {
730 my($mgr, %args) = @_;
731 my $attr_type = $args{attr_type};
733 # first, see if it's already set. May just need to overwrite it
734 my $attr = $mgr->editor->search_acq_lineitem_attr({
735 lineitem => $args{lineitem},
736 attr_type => $args{attr_type},
737 attr_name => $args{attr_name}
741 $attr->attr_value($args{attr_value});
742 return $attr if $mgr->editor->update_acq_lineitem_attr($attr);
747 $attr = Fieldmapper::acq::lineitem_attr->new;
748 $attr->$_($args{$_}) for keys %args;
750 unless($attr->definition) {
751 my $find = "search_acq_$attr_type";
752 my $attr_def_id = $mgr->editor->$find({code => $attr->attr_name}, {idlist=>1})->[0] or return 0;
753 $attr->definition($attr_def_id);
755 return $mgr->editor->create_acq_lineitem_attr($attr);
759 # ----------------------------------------------------------------------------
761 # ----------------------------------------------------------------------------
762 sub create_lineitem_debits {
763 my ($mgr, $li, $dry_run) = @_;
765 unless($li->estimated_unit_price) {
766 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_PRICE', payload => $li->id));
767 $mgr->editor->rollback;
771 unless($li->provider) {
772 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_PROVIDER', payload => $li->id));
773 $mgr->editor->rollback;
777 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
778 {lineitem => $li->id},
782 for my $lid_id (@$lid_ids) {
784 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
787 flesh_fields => {acqlid => ['fund']}
791 create_lineitem_detail_debit($mgr, $li, $lid, $dry_run) or return 0;
800 sub create_lineitem_detail_debit {
801 my ($mgr, $li, $lid, $dry_run, $no_translate) = @_;
803 # don't create the debit if one already exists
804 return $mgr->editor->retrieve_acq_fund_debit($lid->fund_debit) if $lid->fund_debit;
806 my $li_id = ref($li) ? $li->id : $li;
808 unless(ref $li and ref $li->provider) {
809 $li = $mgr->editor->retrieve_acq_lineitem([
812 flesh_fields => {jub => ['provider']},
818 $lid->fund($mgr->editor->retrieve_acq_fund($lid->fund)) unless(ref $lid->fund);
820 $lid = $mgr->editor->retrieve_acq_lineitem_detail([
823 flesh_fields => {acqlid => ['fund']}
828 unless ($lid->fund) {
830 new OpenILS::Event("ACQ_FUND_NOT_FOUND") # close enough
835 my $amount = $li->estimated_unit_price;
836 if($li->provider->currency_type ne $lid->fund->currency_type and !$no_translate) {
838 # At Fund debit creation time, translate into the currency of the fund
839 # TODO: org setting to disable automatic currency conversion at debit create time?
841 $amount = $mgr->editor->json_query({
843 'acq.exchange_ratio',
844 $li->provider->currency_type, # source currency
845 $lid->fund->currency_type, # destination currency
846 $li->estimated_unit_price # source amount
848 })->[0]->{'acq.exchange_ratio'};
851 my $debit = create_fund_debit(
854 fund => $lid->fund->id,
855 origin_amount => $li->estimated_unit_price,
856 origin_currency_type => $li->provider->currency_type,
860 $lid->fund_debit($debit->id);
861 $lid->fund($lid->fund->id);
862 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
867 __PACKAGE__->register_method(
868 "method" => "fund_exceeds_balance_percent_api",
869 "api_name" => "open-ils.acq.fund.check_balance_percentages",
871 "desc" => q/Determine whether a given fund exceeds its defined
872 "balance stop and warning percentages"/,
874 {"desc" => "Authentication token", "type" => "string"},
875 {"desc" => "Fund ID", "type" => "number"},
876 {"desc" => "Theoretical debit amount (optional)",
879 "return" => {"desc" => q/An array of two values, for stop and warning,
880 in that order: 1 if fund exceeds that balance percentage, else 0/}
884 sub fund_exceeds_balance_percent_api {
885 my ($self, $conn, $auth, $fund_id, $debit_amount) = @_;
889 my $e = new_editor("authtoken" => $auth);
890 return $e->die_event unless $e->checkauth;
892 my $fund = $e->retrieve_acq_fund($fund_id) or return $e->die_event;
893 return $e->die_event unless $e->allowed("VIEW_FUND", $fund->org);
896 fund_exceeds_balance_percent($fund, $debit_amount, $e, "stop"),
897 fund_exceeds_balance_percent($fund, $debit_amount, $e, "warning")
904 sub fund_exceeds_balance_percent {
905 my ($fund, $debit_amount, $e, $which) = @_;
907 my ($method_name, $event_name) = @{{
909 "balance_warning_percent", "ACQ_FUND_EXCEEDS_WARN_PERCENT"
912 "balance_stop_percent", "ACQ_FUND_EXCEEDS_STOP_PERCENT"
916 if ($fund->$method_name) {
918 $e->search_acq_fund_combined_balance({"fund" => $fund->id})->[0];
920 $e->search_acq_fund_allocation_total({"fund" => $fund->id})->[0];
922 $balance = ($balance) ? $balance->amount : 0;
923 $allocations = ($allocations) ? $allocations->amount : 0;
926 $allocations == 0 || # if no allocations were ever made, assume we have hit the stop percent
927 ((($allocations - $balance + $debit_amount) / $allocations) * 100) > $fund->$method_name
929 $logger->info("fund would hit a limit: " . $fund->id . ", $balance, $debit_amount, $allocations, $method_name");
934 "fund" => $fund, "debit_amount" => $debit_amount
944 # ----------------------------------------------------------------------------
946 # ----------------------------------------------------------------------------
947 sub create_fund_debit {
948 my($mgr, $dry_run, %args) = @_;
950 # Verify the fund is not being spent beyond the hard stop amount
951 my $fund = $mgr->editor->retrieve_acq_fund($args{fund}) or return 0;
954 fund_exceeds_balance_percent(
955 $fund, $args{"amount"}, $mgr->editor, "stop"
958 $dry_run and fund_exceeds_balance_percent(
959 $fund, $args{"amount"}, $mgr->editor, "warning"
962 my $debit = Fieldmapper::acq::fund_debit->new;
963 $debit->debit_type('purchase');
964 $debit->encumbrance('t');
965 $debit->$_($args{$_}) for keys %args;
967 $mgr->add_debit($debit->amount);
968 return $mgr->editor->create_acq_fund_debit($debit);
972 # ----------------------------------------------------------------------------
974 # ----------------------------------------------------------------------------
975 sub create_picklist {
976 my($mgr, %args) = @_;
977 my $picklist = Fieldmapper::acq::picklist->new;
978 $picklist->creator($mgr->editor->requestor->id);
979 $picklist->owner($picklist->creator);
980 $picklist->editor($picklist->creator);
981 $picklist->create_time('now');
982 $picklist->edit_time('now');
983 $picklist->org_unit($mgr->editor->requestor->ws_ou);
984 $picklist->owner($mgr->editor->requestor->id);
985 $picklist->$_($args{$_}) for keys %args;
987 $mgr->picklist($picklist);
988 return $mgr->editor->create_acq_picklist($picklist);
991 sub update_picklist {
992 my($mgr, $picklist) = @_;
993 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
994 $picklist->edit_time('now');
995 $picklist->editor($mgr->editor->requestor->id);
996 if ($mgr->editor->update_acq_picklist($picklist)) {
997 $picklist = $mgr->editor->retrieve_acq_picklist($mgr->editor->data);
998 $mgr->picklist($picklist);
1005 sub delete_picklist {
1006 my($mgr, $picklist) = @_;
1007 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
1009 # delete all 'new' lineitems
1010 my $li_ids = $mgr->editor->search_acq_lineitem(
1012 picklist => $picklist->id,
1013 "-or" => {state => "new", purchase_order => undef}
1017 for my $li_id (@$li_ids) {
1018 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
1019 return 0 unless delete_lineitem($mgr, $li);
1023 # detach all non-'new' lineitems
1024 $li_ids = $mgr->editor->search_acq_lineitem({picklist => $picklist->id, state => {'!=' => 'new'}}, {idlist => 1});
1025 for my $li_id (@$li_ids) {
1026 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
1027 $li->clear_picklist;
1028 return 0 unless update_lineitem($mgr, $li);
1032 # remove any picklist-specific object perms
1033 my $ops = $mgr->editor->search_permission_usr_object_perm_map({object_type => 'acqpl', object_id => ''.$picklist->id});
1034 for my $op (@$ops) {
1035 return 0 unless $mgr->editor->delete_usr_object_perm_map($op);
1038 return $mgr->editor->delete_acq_picklist($picklist);
1041 # ----------------------------------------------------------------------------
1043 # ----------------------------------------------------------------------------
1044 sub update_purchase_order {
1046 $po = $mgr->editor->retrieve_acq_purchase_order($po) unless ref $po;
1047 $po->editor($mgr->editor->requestor->id);
1048 $po->edit_time('now');
1049 $mgr->purchase_order($po);
1050 return $mgr->editor->retrieve_acq_purchase_order($mgr->editor->data)
1051 if $mgr->editor->update_acq_purchase_order($po);
1055 sub create_purchase_order {
1056 my($mgr, %args) = @_;
1058 # verify the chosen provider is still active
1059 my $provider = $mgr->editor->retrieve_acq_provider($args{provider}) or return 0;
1060 unless($U->is_true($provider->active)) {
1061 $logger->error("provider is not active. cannot create PO");
1062 $mgr->editor->event(OpenILS::Event->new('ACQ_PROVIDER_INACTIVE'));
1066 my $po = Fieldmapper::acq::purchase_order->new;
1067 $po->creator($mgr->editor->requestor->id);
1068 $po->editor($mgr->editor->requestor->id);
1069 $po->owner($mgr->editor->requestor->id);
1070 $po->edit_time('now');
1071 $po->create_time('now');
1072 $po->state('pending');
1073 $po->ordering_agency($mgr->editor->requestor->ws_ou);
1074 $po->$_($args{$_}) for keys %args;
1076 $mgr->purchase_order($po);
1077 return $mgr->editor->create_acq_purchase_order($po);
1080 # ----------------------------------------------------------------------------
1081 # if all of the lineitems for this PO are received,
1082 # mark the PO as received
1083 # ----------------------------------------------------------------------------
1084 sub check_purchase_order_received {
1085 my($mgr, $po_id) = @_;
1087 my $non_recv_li = $mgr->editor->search_acq_lineitem(
1088 { purchase_order => $po_id,
1089 state => {'!=' => 'received'}
1092 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id);
1093 return $po if @$non_recv_li;
1095 $po->state('received');
1096 return update_purchase_order($mgr, $po);
1100 # ----------------------------------------------------------------------------
1101 # Bib, Callnumber, and Copy data
1102 # ----------------------------------------------------------------------------
1104 sub create_lineitem_assets {
1105 my($mgr, $li_id) = @_;
1108 my $li = $mgr->editor->retrieve_acq_lineitem([
1111 flesh_fields => {jub => ['purchase_order', 'attributes']}
1115 # note: at this point, the bib record this LI links to should already be created
1117 # -----------------------------------------------------------------
1118 # The lineitem is going live, promote user request holds to real holds
1119 # -----------------------------------------------------------------
1120 promote_lineitem_holds($mgr, $li) or return 0;
1122 my $li_details = $mgr->editor->search_acq_lineitem_detail({lineitem => $li_id}, {idlist=>1});
1124 # -----------------------------------------------------------------
1125 # for each lineitem_detail, create the volume if necessary, create
1126 # a copy, and link them all together.
1127 # -----------------------------------------------------------------
1129 for my $lid_id (@{$li_details}) {
1131 my $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid_id) or return 0;
1132 next if $lid->eg_copy_id;
1134 # use the same callnumber label for all items within this lineitem
1135 $lid->cn_label($first_cn) if $first_cn and not $lid->cn_label;
1137 # apply defaults if necessary
1138 return 0 unless complete_lineitem_detail($mgr, $lid);
1140 $first_cn = $lid->cn_label unless $first_cn;
1142 my $org = $lid->owning_lib;
1143 my $label = $lid->cn_label;
1144 my $bibid = $li->eg_bib_id;
1146 my $volume = $mgr->cache($org, "cn.$bibid.$label");
1148 $volume = create_volume($mgr, $li, $lid) or return 0;
1149 $mgr->cache($org, "cn.$bibid.$label", $volume);
1151 create_copy($mgr, $volume, $lid, $li) or return 0;
1154 return { li => $li };
1158 my($mgr, $li, $lid) = @_;
1160 my ($volume, $evt) =
1161 OpenILS::Application::Cat::AssetCommon->find_or_create_volume(
1169 $mgr->editor->event($evt);
1177 my($mgr, $volume, $lid, $li) = @_;
1178 my $copy = Fieldmapper::asset::copy->new;
1180 $copy->loan_duration(2);
1181 $copy->fine_level(2);
1182 $copy->status(($lid->recv_time) ? OILS_COPY_STATUS_IN_PROCESS : OILS_COPY_STATUS_ON_ORDER);
1183 $copy->barcode($lid->barcode);
1184 $copy->location($lid->location);
1185 $copy->call_number($volume->id);
1186 $copy->circ_lib($volume->owning_lib);
1187 $copy->circ_modifier($lid->circ_modifier);
1189 # AKA list price. We might need a $li->list_price field since
1190 # estimated price is not necessarily the same as list price
1191 $copy->price($li->estimated_unit_price);
1193 my $evt = OpenILS::Application::Cat::AssetCommon->create_copy($mgr->editor, $volume, $copy);
1195 $mgr->editor->event($evt);
1200 $lid->eg_copy_id($copy->id);
1201 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
1209 # ----------------------------------------------------------------------------
1210 # Workflow: Build a selection list from a Z39.50 search
1211 # ----------------------------------------------------------------------------
1213 __PACKAGE__->register_method(
1214 method => 'zsearch',
1215 api_name => 'open-ils.acq.picklist.search.z3950',
1218 desc => 'Performs a z3950 federated search and creates a picklist and associated lineitems',
1220 {desc => 'Authentication token', type => 'string'},
1221 {desc => 'Search definition', type => 'object'},
1222 {desc => 'Picklist name, optional', type => 'string'},
1228 my($self, $conn, $auth, $search, $name, $options) = @_;
1229 my $e = new_editor(authtoken=>$auth);
1230 return $e->event unless $e->checkauth;
1231 return $e->event unless $e->allowed('CREATE_PICKLIST');
1233 $search->{limit} ||= 10;
1236 my $ses = OpenSRF::AppSession->create('open-ils.search');
1237 my $req = $ses->request('open-ils.search.z3950.search_class', $auth, $search);
1242 while(my $resp = $req->recv(timeout=>60)) {
1245 my $e = new_editor(requestor=>$e->requestor, xact=>1);
1246 $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1247 $picklist = zsearch_build_pl($mgr, $name);
1251 my $result = $resp->content;
1252 my $count = $result->{count} || 0;
1253 $mgr->total( (($count < $search->{limit}) ? $count : $search->{limit})+1 );
1255 for my $rec (@{$result->{records}}) {
1257 my $li = create_lineitem($mgr,
1258 picklist => $picklist->id,
1259 source_label => $result->{service},
1260 marc => $rec->{marcxml},
1261 eg_bib_id => $rec->{bibid}
1264 if($$options{respond_li}) {
1265 $li->attributes($mgr->editor->search_acq_lineitem_attr({lineitem => $li->id}))
1266 if $$options{flesh_attrs};
1267 $li->clear_marc if $$options{clear_marc};
1268 $mgr->respond(lineitem => $li);
1275 $mgr->editor->commit;
1276 return $mgr->respond_complete;
1279 sub zsearch_build_pl {
1280 my($mgr, $name) = @_;
1283 my $picklist = $mgr->editor->search_acq_picklist({
1284 owner => $mgr->editor->requestor->id,
1288 if($name eq '' and $picklist) {
1289 return 0 unless delete_picklist($mgr, $picklist);
1293 return update_picklist($mgr, $picklist) if $picklist;
1294 return create_picklist($mgr, name => $name);
1298 # ----------------------------------------------------------------------------
1299 # Workflow: Build a selection list / PO by importing a batch of MARC records
1300 # ----------------------------------------------------------------------------
1302 __PACKAGE__->register_method(
1303 method => 'upload_records',
1304 api_name => 'open-ils.acq.process_upload_records',
1306 max_chunk_count => 1
1309 sub upload_records {
1310 my($self, $conn, $auth, $key, $args) = @_;
1313 my $e = new_editor(authtoken => $auth, xact => 1);
1314 return $e->die_event unless $e->checkauth;
1315 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1317 my $cache = OpenSRF::Utils::Cache->new;
1319 my $data = $cache->get_cache("vandelay_import_spool_$key");
1320 my $filename = $data->{path};
1321 my $provider = $args->{provider};
1322 my $picklist = $args->{picklist};
1323 my $create_po = $args->{create_po};
1324 my $activate_po = $args->{activate_po};
1325 my $vandelay = $args->{vandelay};
1326 my $ordering_agency = $args->{ordering_agency} || $e->requestor->ws_ou;
1330 unless(-r $filename) {
1331 $logger->error("unable to read MARC file $filename");
1333 return OpenILS::Event->new('FILE_UPLOAD_ERROR', payload => {filename => $filename});
1336 $provider = $e->retrieve_acq_provider($provider) or return $e->die_event;
1339 $picklist = $e->retrieve_acq_picklist($picklist) or return $e->die_event;
1340 if($picklist->owner != $e->requestor->id) {
1341 return $e->die_event unless
1342 $e->allowed('CREATE_PICKLIST', $picklist->org_unit, $picklist);
1344 $mgr->picklist($picklist);
1348 return $e->die_event unless
1349 $e->allowed('CREATE_PURCHASE_ORDER', $ordering_agency);
1351 $po = create_purchase_order($mgr,
1352 ordering_agency => $ordering_agency,
1353 provider => $provider->id,
1355 ) or return $mgr->editor->die_event;
1358 $logger->info("acq processing MARC file=$filename");
1360 my $batch = new MARC::Batch ('USMARC', $filename);
1368 my ($err, $xml, $r);
1373 } catch Error with {
1375 $logger->warn("Proccessing of record $count in set $key failed with error $err. Skipping this record");
1382 $xml = clean_marc($r);
1383 } catch Error with {
1385 $logger->warn("Proccessing XML of record $count in set $key failed with error $err. Skipping this record");
1388 next if $err or not $xml;
1391 source_label => $provider->code,
1392 provider => $provider->id,
1396 $args{picklist} = $picklist->id if $picklist;
1398 $args{purchase_order} = $po->id;
1399 $args{state} = 'pending-order';
1402 my $li = create_lineitem($mgr, %args) or return $mgr->editor->die_event;
1404 $li->provider($provider); # flesh it, we'll need it later
1406 import_lineitem_details($mgr, $ordering_agency, $li) or return $mgr->editor->die_event;
1409 push(@li_list, $li->id);
1415 $cache->delete_cache('vandelay_import_spool_' . $key);
1417 if ($po and $activate_po) {
1418 my $die_event = activate_purchase_order_impl($mgr, $po->id, $vandelay);
1419 return $die_event if $die_event;
1421 } elsif ($vandelay) {
1422 $vandelay->{new_rec_perm} = 'IMPORT_ACQ_LINEITEM_BIB_RECORD_UPLOAD';
1423 create_lineitem_list_assets($mgr, \@li_list, $vandelay, 1) or return $e->die_event;
1426 return $mgr->respond_complete;
1429 sub import_lineitem_details {
1430 my($mgr, $ordering_agency, $li) = @_;
1432 my $holdings = $mgr->editor->json_query({from => ['acq.extract_provider_holding_data', $li->id]});
1433 return 1 unless @$holdings;
1434 my $org_path = $U->get_org_ancestors($ordering_agency);
1435 $org_path = [ reverse (@$org_path) ];
1441 # create a lineitem detail for each copy in the data
1443 my $compiled = extract_lineitem_detail_data($mgr, $org_path, $holdings, $idx);
1444 last unless defined $compiled;
1445 return 0 unless $compiled;
1447 # this takes the price of the last copy and uses it as the lineitem price
1448 # need to determine if a given record would include different prices for the same item
1449 $price = $$compiled{estimated_price};
1451 last unless $$compiled{quantity};
1453 for(1..$$compiled{quantity}) {
1454 my $lid = create_lineitem_detail(
1456 lineitem => $li->id,
1457 owning_lib => $$compiled{owning_lib},
1458 cn_label => $$compiled{call_number},
1459 fund => $$compiled{fund},
1460 circ_modifier => $$compiled{circ_modifier},
1461 note => $$compiled{note},
1462 location => $$compiled{copy_location},
1463 collection_code => $$compiled{collection_code},
1464 barcode => $$compiled{barcode}
1472 $li->estimated_unit_price($price);
1473 update_lineitem($mgr, $li) or return 0;
1477 # return hash on success, 0 on error, undef on no more holdings
1478 sub extract_lineitem_detail_data {
1479 my($mgr, $org_path, $holdings, $index) = @_;
1481 my @data_list = grep { $_->{holding} eq $index } @$holdings;
1482 return undef unless @data_list;
1484 my %compiled = map { $_->{attr} => $_->{data} } @data_list;
1485 my $base_org = $$org_path[0];
1489 $logger->error("Item import extraction error: $msg");
1490 $logger->error('Holdings Data: ' . OpenSRF::Utils::JSON->perl2JSON(\%compiled));
1491 $mgr->editor->rollback;
1492 $mgr->editor->event(OpenILS::Event->new('ACQ_IMPORT_ERROR', payload => $msg));
1496 # ---------------------------------------------------------------------
1498 if(my $code = $compiled{fund_code}) {
1500 my $fund = $mgr->cache($base_org, "fund.$code");
1502 # search up the org tree for the most appropriate fund
1503 for my $org (@$org_path) {
1504 $fund = $mgr->editor->search_acq_fund(
1505 {org => $org, code => $code, year => DateTime->now->year}, {idlist => 1})->[0];
1509 return $killme->("no fund with code $code at orgs [@$org_path]") unless $fund;
1510 $compiled{fund} = $fund;
1511 $mgr->cache($base_org, "fund.$code", $fund);
1515 # ---------------------------------------------------------------------
1517 if(my $sn = $compiled{owning_lib}) {
1518 my $org_id = $mgr->cache($base_org, "orgsn.$sn") ||
1519 $mgr->editor->search_actor_org_unit({shortname => $sn}, {idlist => 1})->[0];
1520 return $killme->("invalid owning_lib defined: $sn") unless $org_id;
1521 $compiled{owning_lib} = $org_id;
1522 $mgr->cache($$org_path[0], "orgsn.$sn", $org_id);
1526 # ---------------------------------------------------------------------
1528 my $code = $compiled{circ_modifier};
1532 # verify this is a valid circ modifier
1533 return $killme->("invlalid circ_modifier $code") unless
1534 defined $mgr->cache($base_org, "mod.$code") or
1535 $mgr->editor->retrieve_config_circ_modifier($code);
1537 # if valid, cache for future tests
1538 $mgr->cache($base_org, "mod.$code", $code);
1541 $compiled{circ_modifier} = get_default_circ_modifier($mgr, $base_org);
1545 # ---------------------------------------------------------------------
1547 if( my $name = $compiled{copy_location}) {
1548 my $loc = $mgr->cache($base_org, "copy_loc.$name");
1550 for my $org (@$org_path) {
1551 $loc = $mgr->editor->search_asset_copy_location(
1552 {owning_lib => $org, name => $name}, {idlist => 1})->[0];
1556 return $killme->("Invalid copy location $name") unless $loc;
1557 $compiled{copy_location} = $loc;
1558 $mgr->cache($base_org, "copy_loc.$name", $loc);
1566 # ----------------------------------------------------------------------------
1567 # Workflow: Given an existing purchase order, import/create the bibs,
1568 # callnumber and copy objects
1569 # ----------------------------------------------------------------------------
1571 __PACKAGE__->register_method(
1572 method => 'create_po_assets',
1573 api_name => 'open-ils.acq.purchase_order.assets.create',
1575 desc => q/Creates assets for each lineitem in the purchase order/,
1577 {desc => 'Authentication token', type => 'string'},
1578 {desc => 'The purchase order id', type => 'number'},
1580 return => {desc => 'Streams a total versus completed counts object, event on error'}
1582 max_chunk_count => 1
1585 sub create_po_assets {
1586 my($self, $conn, $auth, $po_id, $args) = @_;
1589 my $e = new_editor(authtoken=>$auth, xact=>1);
1590 return $e->die_event unless $e->checkauth;
1591 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1593 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1595 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1597 # it's ugly, but it's fast. Get the total count of lineitem detail objects to process
1598 my $lid_total = $e->json_query({
1599 select => { acqlid => [{aggregate => 1, transform => 'count', column => 'id'}] },
1605 join => {acqpo => {fkey => 'purchase_order', field => 'id'}}
1609 where => {'+acqpo' => {id => $po_id}}
1612 $mgr->total(scalar(@$li_ids) + $lid_total);
1614 create_lineitem_list_assets($mgr, $li_ids, $args->{vandelay})
1615 or return $e->die_event;
1618 update_purchase_order($mgr, $po) or return $e->die_event;
1621 return $mgr->respond_complete;
1626 __PACKAGE__->register_method(
1627 method => 'create_purchase_order_api',
1628 api_name => 'open-ils.acq.purchase_order.create',
1630 desc => 'Creates a new purchase order',
1632 {desc => 'Authentication token', type => 'string'},
1633 {desc => 'purchase_order to create', type => 'object'}
1635 return => {desc => 'The purchase order id, Event on failure'}
1637 max_chunk_count => 1
1640 sub create_purchase_order_api {
1641 my($self, $conn, $auth, $po, $args) = @_;
1644 my $e = new_editor(xact=>1, authtoken=>$auth);
1645 return $e->die_event unless $e->checkauth;
1646 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
1647 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1650 my %pargs = (ordering_agency => $e->requestor->ws_ou); # default
1651 $pargs{provider} = $po->provider if $po->provider;
1652 $pargs{ordering_agency} = $po->ordering_agency if $po->ordering_agency;
1653 $pargs{prepayment_required} = $po->prepayment_required if $po->prepayment_required;
1654 my $vandelay = $args->{vandelay};
1656 $po = create_purchase_order($mgr, %pargs) or return $e->die_event;
1658 my $li_ids = $$args{lineitems};
1662 for my $li_id (@$li_ids) {
1664 my $li = $e->retrieve_acq_lineitem([
1666 {flesh => 1, flesh_fields => {jub => ['attributes']}}
1667 ]) or return $e->die_event;
1669 $li->provider($po->provider);
1670 $li->purchase_order($po->id);
1671 $li->state('pending-order');
1672 update_lineitem($mgr, $li) or return $e->die_event;
1677 # commit before starting the asset creation
1680 if($li_ids and $vandelay) {
1681 create_lineitem_list_assets($mgr, $li_ids, $vandelay, !$$args{create_assets}) or return $e->die_event;
1684 return $mgr->respond_complete;
1689 __PACKAGE__->register_method(
1690 method => 'update_lineitem_fund_batch',
1691 api_name => 'open-ils.acq.lineitem.fund.update.batch',
1694 desc => q/Given a set of lineitem IDS, updates the fund for all attached lineitem details/
1698 sub update_lineitem_fund_batch {
1699 my($self, $conn, $auth, $li_ids, $fund_id) = @_;
1700 my $e = new_editor(xact=>1, authtoken=>$auth);
1701 return $e->die_event unless $e->checkauth;
1702 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1703 for my $li_id (@$li_ids) {
1704 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
1705 return $evt if $evt;
1706 my $li_details = $e->search_acq_lineitem_detail({lineitem => $li_id});
1707 $_->fund($fund_id) and $_->ischanged(1) for @$li_details;
1708 $evt = lineitem_detail_CUD_batch($mgr, $li_details);
1709 return $evt if $evt;
1714 return $mgr->respond_complete;
1719 __PACKAGE__->register_method(
1720 method => 'lineitem_detail_CUD_batch_api',
1721 api_name => 'open-ils.acq.lineitem_detail.cud.batch',
1724 desc => q/Creates a new purchase order line item detail. / .
1725 q/Additionally creates the associated fund_debit/,
1727 {desc => 'Authentication token', type => 'string'},
1728 {desc => 'List of lineitem_details to create', type => 'array'},
1729 {desc => 'Create Debits. Used for creating post-po-asset-creation debits', type => 'bool'},
1731 return => {desc => 'Streaming response of current position in the array'}
1735 __PACKAGE__->register_method(
1736 method => 'lineitem_detail_CUD_batch_api',
1737 api_name => 'open-ils.acq.lineitem_detail.cud.batch.dry_run',
1741 Dry run version of open-ils.acq.lineitem_detail.cud.batch.
1742 In dry_run mode, updated fund_debit's the exceed the warning
1743 percent return an event.
1749 sub lineitem_detail_CUD_batch_api {
1750 my($self, $conn, $auth, $li_details, $create_debits) = @_;
1751 my $e = new_editor(xact=>1, authtoken=>$auth);
1752 return $e->die_event unless $e->checkauth;
1753 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1754 my $dry_run = ($self->api_name =~ /dry_run/o);
1755 my $evt = lineitem_detail_CUD_batch($mgr, $li_details, $create_debits, $dry_run);
1756 return $evt if $evt;
1758 return $mgr->respond_complete;
1762 sub lineitem_detail_CUD_batch {
1763 my($mgr, $li_details, $create_debits, $dry_run) = @_;
1765 $mgr->total(scalar(@$li_details));
1766 my $e = $mgr->editor;
1770 my $fund_cache = {};
1773 for my $lid (@$li_details) {
1775 unless($li = $li_cache{$lid->lineitem}) {
1776 ($li, $evt) = fetch_and_check_li($e, $lid->lineitem, 'write');
1777 return $evt if $evt;
1781 $lid = create_lineitem_detail($mgr, %{$lid->to_bare_hash}) or return $e->die_event;
1782 if($create_debits) {
1783 $li->provider($e->retrieve_acq_provider($li->provider)) or return $e->die_event;
1784 $lid->fund($e->retrieve_acq_fund($lid->fund)) or return $e->die_event;
1785 create_lineitem_detail_debit($mgr, $li, $lid, 0, 1) or return $e->die_event;
1788 } elsif($lid->ischanged) {
1789 return $evt if $evt = handle_changed_lid($e, $lid, $dry_run, $fund_cache);
1791 } elsif($lid->isdeleted) {
1792 delete_lineitem_detail($mgr, $lid) or return $e->die_event;
1795 $mgr->respond(li => $li);
1796 $li_cache{$lid->lineitem} = $li;
1802 sub handle_changed_lid {
1803 my($e, $lid, $dry_run, $fund_cache) = @_;
1805 my $orig_lid = $e->retrieve_acq_lineitem_detail($lid->id) or return $e->die_event;
1807 # updating the fund, so update the debit
1808 if($orig_lid->fund_debit and $orig_lid->fund != $lid->fund) {
1810 my $debit = $e->retrieve_acq_fund_debit($orig_lid->fund_debit);
1811 my $new_fund = $$fund_cache{$lid->fund} =
1812 $$fund_cache{$lid->fund} || $e->retrieve_acq_fund($lid->fund);
1814 # check the thresholds
1815 return $e->die_event if
1816 fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "stop");
1817 return $e->die_event if $dry_run and
1818 fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "warning");
1820 $debit->fund($new_fund->id);
1821 $e->update_acq_fund_debit($debit) or return $e->die_event;
1824 $e->update_acq_lineitem_detail($lid) or return $e->die_event;
1829 __PACKAGE__->register_method(
1830 method => 'receive_po_api',
1831 api_name => 'open-ils.acq.purchase_order.receive'
1834 sub receive_po_api {
1835 my($self, $conn, $auth, $po_id) = @_;
1836 my $e = new_editor(xact => 1, authtoken => $auth);
1837 return $e->die_event unless $e->checkauth;
1838 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1840 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1841 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1843 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1845 for my $li_id (@$li_ids) {
1846 receive_lineitem($mgr, $li_id) or return $e->die_event;
1850 $po->state('received');
1851 update_purchase_order($mgr, $po) or return $e->die_event;
1854 return $mgr->respond_complete;
1858 # At the moment there's a lack of parallelism between the receive and unreceive
1859 # API methods for POs and the API methods for LIs and LIDs. The methods for
1860 # POs stream back objects as they act, whereas the methods for LIs and LIDs
1861 # atomically return an object that describes only what changed (in LIs and LIDs
1862 # themselves or in the objects to which to LIs and LIDs belong).
1864 # The methods for LIs and LIDs work the way they do to faciliate the UI's
1865 # maintaining correct information about the state of these things when a user
1866 # wants to receive or unreceive these objects without refreshing their whole
1867 # display. The UI feature for receiving and un-receiving a whole PO just
1868 # refreshes the whole display, so this absence of parallelism in the UI is also
1869 # relected in this module.
1871 # This could be neatened in the future by making POs receive and unreceive in
1872 # the same way the LIs and LIDs do.
1874 __PACKAGE__->register_method(
1875 method => 'receive_lineitem_detail_api',
1876 api_name => 'open-ils.acq.lineitem_detail.receive',
1878 desc => 'Mark a lineitem_detail as received',
1880 {desc => 'Authentication token', type => 'string'},
1881 {desc => 'lineitem detail ID', type => 'number'}
1884 "on success, object describing changes to LID and possibly " .
1885 "to LI and PO; on error, Event"
1890 sub receive_lineitem_detail_api {
1891 my($self, $conn, $auth, $lid_id) = @_;
1893 my $e = new_editor(xact=>1, authtoken=>$auth);
1894 return $e->die_event unless $e->checkauth;
1895 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1898 "flesh" => 2, "flesh_fields" => {
1899 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
1903 my $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1905 return $e->die_event unless $e->allowed(
1906 'RECEIVE_PURCHASE_ORDER', $lid->lineitem->purchase_order->ordering_agency);
1909 my $recvd = receive_lineitem_detail($mgr, $lid_id) or return $e->die_event;
1911 # .. and re-retrieve
1912 $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1914 # Now build result data structure.
1915 my $result = {"lid" => {$lid->id => {"recv_time" => $lid->recv_time}}};
1918 if ($recvd->class_name =~ /::purchase_order/) {
1919 $result->{"po"} = describe_affected_po($e, $recvd);
1921 $lid->lineitem->id => {"state" => $lid->lineitem->state}
1923 } elsif ($recvd->class_name =~ /::lineitem/) {
1924 $result->{"li"} = {$recvd->id => {"state" => $recvd->state}};
1928 describe_affected_po($e, $lid->lineitem->purchase_order);
1934 __PACKAGE__->register_method(
1935 method => 'receive_lineitem_api',
1936 api_name => 'open-ils.acq.lineitem.receive',
1938 desc => 'Mark a lineitem as received',
1940 {desc => 'Authentication token', type => 'string'},
1941 {desc => 'lineitem ID', type => 'number'}
1944 "on success, object describing changes to LI and possibly PO; " .
1950 sub receive_lineitem_api {
1951 my($self, $conn, $auth, $li_id) = @_;
1953 my $e = new_editor(xact=>1, authtoken=>$auth);
1954 return $e->die_event unless $e->checkauth;
1955 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1957 my $li = $e->retrieve_acq_lineitem([
1961 jub => ['purchase_order']
1964 ]) or return $e->die_event;
1966 return $e->die_event unless $e->allowed(
1967 'RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);
1969 my $res = receive_lineitem($mgr, $li_id) or return $e->die_event;
1971 $conn->respond_complete($res);
1972 $mgr->run_post_response_hooks
1976 __PACKAGE__->register_method(
1977 method => 'rollback_receive_po_api',
1978 api_name => 'open-ils.acq.purchase_order.receive.rollback'
1981 sub rollback_receive_po_api {
1982 my($self, $conn, $auth, $po_id) = @_;
1983 my $e = new_editor(xact => 1, authtoken => $auth);
1984 return $e->die_event unless $e->checkauth;
1985 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1987 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1988 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1990 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1992 for my $li_id (@$li_ids) {
1993 rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
1997 $po->state('on-order');
1998 update_purchase_order($mgr, $po) or return $e->die_event;
2001 return $mgr->respond_complete;
2005 __PACKAGE__->register_method(
2006 method => 'rollback_receive_lineitem_detail_api',
2007 api_name => 'open-ils.acq.lineitem_detail.receive.rollback',
2009 desc => 'Mark a lineitem_detail as Un-received',
2011 {desc => 'Authentication token', type => 'string'},
2012 {desc => 'lineitem detail ID', type => 'number'}
2015 "on success, object describing changes to LID and possibly " .
2016 "to LI and PO; on error, Event"
2021 sub rollback_receive_lineitem_detail_api {
2022 my($self, $conn, $auth, $lid_id) = @_;
2024 my $e = new_editor(xact=>1, authtoken=>$auth);
2025 return $e->die_event unless $e->checkauth;
2026 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2028 my $lid = $e->retrieve_acq_lineitem_detail([
2032 acqlid => ['lineitem'],
2033 jub => ['purchase_order']
2037 my $li = $lid->lineitem;
2038 my $po = $li->purchase_order;
2040 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2044 my $recvd = rollback_receive_lineitem_detail($mgr, $lid_id)
2045 or return $e->die_event;
2048 $result->{"lid"} = {$recvd->id => {"recv_time" => $recvd->recv_time}};
2050 $result->{"lid"} = {$lid->id => {"recv_time" => $lid->recv_time}};
2053 if ($li->state eq "received") {
2054 $li->state("on-order");
2055 $li = update_lineitem($mgr, $li) or return $e->die_event;
2056 $result->{"li"} = {$li->id => {"state" => $li->state}};
2059 if ($po->state eq "received") {
2060 $po->state("on-order");
2061 $po = update_purchase_order($mgr, $po) or return $e->die_event;
2063 $result->{"po"} = describe_affected_po($e, $po);
2065 $e->commit and return $result or return $e->die_event;
2068 __PACKAGE__->register_method(
2069 method => 'rollback_receive_lineitem_api',
2070 api_name => 'open-ils.acq.lineitem.receive.rollback',
2072 desc => 'Mark a lineitem as Un-received',
2074 {desc => 'Authentication token', type => 'string'},
2075 {desc => 'lineitem ID', type => 'number'}
2078 "on success, object describing changes to LI and possibly PO; " .
2084 sub rollback_receive_lineitem_api {
2085 my($self, $conn, $auth, $li_id) = @_;
2087 my $e = new_editor(xact=>1, authtoken=>$auth);
2088 return $e->die_event unless $e->checkauth;
2089 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2091 my $li = $e->retrieve_acq_lineitem([
2093 "flesh" => 1, "flesh_fields" => {"jub" => ["purchase_order"]}
2096 my $po = $li->purchase_order;
2098 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2100 $li = rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
2102 my $result = {"li" => {$li->id => {"state" => $li->state}}};
2103 if ($po->state eq "received") {
2104 $po->state("on-order");
2105 $po = update_purchase_order($mgr, $po) or return $e->die_event;
2107 $result->{"po"} = describe_affected_po($e, $po);
2109 $e->commit and return $result or return $e->die_event;
2113 __PACKAGE__->register_method(
2114 method => 'set_lineitem_price_api',
2115 api_name => 'open-ils.acq.lineitem.price.set',
2117 desc => 'Set lineitem price. If debits already exist, update them as well',
2119 {desc => 'Authentication token', type => 'string'},
2120 {desc => 'lineitem ID', type => 'number'}
2122 return => {desc => 'status blob, Event on error'}
2126 sub set_lineitem_price_api {
2127 my($self, $conn, $auth, $li_id, $price) = @_;
2129 my $e = new_editor(xact=>1, authtoken=>$auth);
2130 return $e->die_event unless $e->checkauth;
2131 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2133 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
2134 return $evt if $evt;
2136 $li->estimated_unit_price($price);
2137 update_lineitem($mgr, $li) or return $e->die_event;
2139 my $lid_ids = $e->search_acq_lineitem_detail(
2140 {lineitem => $li_id, fund_debit => {'!=' => undef}},
2144 for my $lid_id (@$lid_ids) {
2146 my $lid = $e->retrieve_acq_lineitem_detail([
2148 flesh => 1, flesh_fields => {acqlid => ['fund', 'fund_debit']}}
2151 $lid->fund_debit->amount($price);
2152 $e->update_acq_fund_debit($lid->fund_debit) or return $e->die_event;
2158 return $mgr->respond_complete;
2162 __PACKAGE__->register_method(
2163 method => 'clone_picklist_api',
2164 api_name => 'open-ils.acq.picklist.clone',
2166 desc => 'Clones a picklist, including lineitem and lineitem details',
2168 {desc => 'Authentication token', type => 'string'},
2169 {desc => 'Picklist ID', type => 'number'},
2170 {desc => 'New Picklist Name', type => 'string'}
2172 return => {desc => 'status blob, Event on error'}
2176 sub clone_picklist_api {
2177 my($self, $conn, $auth, $pl_id, $name) = @_;
2179 my $e = new_editor(xact=>1, authtoken=>$auth);
2180 return $e->die_event unless $e->checkauth;
2181 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2183 my $old_pl = $e->retrieve_acq_picklist($pl_id);
2184 my $new_pl = create_picklist($mgr, %{$old_pl->to_bare_hash}, name => $name) or return $e->die_event;
2186 my $li_ids = $e->search_acq_lineitem({picklist => $pl_id}, {idlist => 1});
2188 for my $li_id (@$li_ids) {
2190 # copy the lineitems
2191 my $li = $e->retrieve_acq_lineitem($li_id);
2192 my $new_li = create_lineitem($mgr, %{$li->to_bare_hash}, picklist => $new_pl->id) or return $e->die_event;
2194 my $lid_ids = $e->search_acq_lineitem_detail({lineitem => $li_id}, {idlist => 1});
2195 for my $lid_id (@$lid_ids) {
2197 # copy the lineitem details
2198 my $lid = $e->retrieve_acq_lineitem_detail($lid_id);
2199 create_lineitem_detail($mgr, %{$lid->to_bare_hash}, lineitem => $new_li->id) or return $e->die_event;
2206 return $mgr->respond_complete;
2210 __PACKAGE__->register_method(
2211 method => 'merge_picklist_api',
2212 api_name => 'open-ils.acq.picklist.merge',
2214 desc => 'Merges 2 or more picklists into a single list',
2216 {desc => 'Authentication token', type => 'string'},
2217 {desc => 'Lead Picklist ID', type => 'number'},
2218 {desc => 'List of subordinate picklist IDs', type => 'array'}
2220 return => {desc => 'status blob, Event on error'}
2224 sub merge_picklist_api {
2225 my($self, $conn, $auth, $lead_pl, $pl_list) = @_;
2227 my $e = new_editor(xact=>1, authtoken=>$auth);
2228 return $e->die_event unless $e->checkauth;
2229 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2231 # XXX perms on each picklist modified
2233 $lead_pl = $e->retrieve_acq_picklist($lead_pl) or return $e->die_event;
2234 # point all of the lineitems at the lead picklist
2235 my $li_ids = $e->search_acq_lineitem({picklist => $pl_list}, {idlist => 1});
2237 for my $li_id (@$li_ids) {
2238 my $li = $e->retrieve_acq_lineitem($li_id);
2239 $li->picklist($lead_pl);
2240 update_lineitem($mgr, $li) or return $e->die_event;
2244 # now delete the subordinate lists
2245 for my $pl_id (@$pl_list) {
2246 my $pl = $e->retrieve_acq_picklist($pl_id);
2247 $e->delete_acq_picklist($pl) or return $e->die_event;
2250 update_picklist($mgr, $lead_pl) or return $e->die_event;
2253 return $mgr->respond_complete;
2257 __PACKAGE__->register_method(
2258 method => 'delete_picklist_api',
2259 api_name => 'open-ils.acq.picklist.delete',
2261 desc => q/Deletes a picklist. It also deletes any lineitems in the "new" state. / .
2262 q/Other attached lineitems are detached/,
2264 {desc => 'Authentication token', type => 'string'},
2265 {desc => 'Picklist ID to delete', type => 'number'}
2267 return => {desc => '1 on success, Event on error'}
2271 sub delete_picklist_api {
2272 my($self, $conn, $auth, $picklist_id) = @_;
2273 my $e = new_editor(xact=>1, authtoken=>$auth);
2274 return $e->die_event unless $e->checkauth;
2275 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2276 my $pl = $e->retrieve_acq_picklist($picklist_id) or return $e->die_event;
2277 delete_picklist($mgr, $pl) or return $e->die_event;
2279 return $mgr->respond_complete;
2284 __PACKAGE__->register_method(
2285 method => 'activate_purchase_order',
2286 api_name => 'open-ils.acq.purchase_order.activate.dry_run'
2289 __PACKAGE__->register_method(
2290 method => 'activate_purchase_order',
2291 api_name => 'open-ils.acq.purchase_order.activate',
2293 desc => q/Activates a purchase order. This updates the status of the PO / .
2294 q/and Lineitems to 'on-order'. Activated PO's are ready for EDI delivery if appropriate./,
2296 {desc => 'Authentication token', type => 'string'},
2297 {desc => 'Purchase ID', type => 'number'}
2299 return => {desc => '1 on success, Event on error'}
2303 sub activate_purchase_order {
2304 my($self, $conn, $auth, $po_id, $vandelay) = @_;
2306 my $dry_run = ($self->api_name =~ /\.dry_run/) ? 1 : 0;
2307 my $e = new_editor(authtoken=>$auth);
2308 return $e->die_event unless $e->checkauth;
2309 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2310 my $die_event = activate_purchase_order_impl($mgr, $po_id, $vandelay, $dry_run);
2311 return $e->die_event if $die_event;
2312 $conn->respond_complete(1);
2313 $mgr->run_post_response_hooks unless $dry_run;
2317 # xacts managed within
2318 sub activate_purchase_order_impl {
2319 my ($mgr, $po_id, $vandelay, $dry_run) = @_;
2321 # read-only until lineitem asset creation
2322 my $e = $mgr->editor;
2325 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2326 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
2327 my $provider = $e->retrieve_acq_provider($po->provider);
2329 # find lineitems and create assets for all
2332 purchase_order => $po_id,
2333 state => [qw/pending-order new order-ready/]
2336 my $li_ids = $e->search_acq_lineitem($query, {idlist => 1});
2338 my $vl_resp; # imported li's and the queue the managing queue
2340 $e->rollback; # read-only thus far
2341 $vl_resp = create_lineitem_list_assets($mgr, $li_ids, $vandelay)
2342 or return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED');
2346 # create fund debits for lineitems
2348 for my $li_id (@$li_ids) {
2349 my $li = $e->retrieve_acq_lineitem($li_id);
2351 if (!$li->eg_bib_id and !$dry_run) {
2352 # we encountered a lineitem that was not successfully imported.
2353 # we cannot continue. rollback and report.
2355 return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED', {queue => $vl_resp->{queue}});
2358 $li->state('on-order');
2359 $li->claim_policy($provider->default_claim_policy)
2360 if $provider->default_claim_policy and !$li->claim_policy;
2361 create_lineitem_debits($mgr, $li, $dry_run) or return $e->die_event;
2362 update_lineitem($mgr, $li) or return $e->die_event;
2363 $mgr->post_process( sub { create_lineitem_status_events($mgr, $li->id, 'aur.ordered'); });
2367 # create po-item debits
2369 for my $po_item (@{$e->search_acq_po_item({purchase_order => $po_id})}) {
2371 my $debit = create_fund_debit(
2374 debit_type => 'direct_charge', # to match invoicing
2375 origin_amount => $po_item->estimated_cost,
2376 origin_currency_type => $e->retrieve_acq_fund($po_item->fund)->currency_type,
2377 amount => $po_item->estimated_cost,
2378 fund => $po_item->fund
2379 ) or return $e->die_event;
2380 $po_item->fund_debit($debit->id);
2381 $e->update_acq_po_item($po_item) or return $e->die_event;
2385 # mark PO as ordered
2387 $po->state('on-order');
2388 $po->order_date('now');
2389 update_purchase_order($mgr, $po) or return $e->die_event;
2392 $dry_run and $e->rollback or $e->commit;
2394 # tell the world we activated a PO
2395 $U->create_events_for_hook('acqpo.activated', $po, $po->ordering_agency) unless $dry_run;
2401 __PACKAGE__->register_method(
2402 method => 'split_purchase_order_by_lineitems',
2403 api_name => 'open-ils.acq.purchase_order.split_by_lineitems',
2405 desc => q/Splits a PO into many POs, 1 per lineitem. Only works for / .
2406 q/POs a) with more than one lineitems, and b) in the "pending" state./,
2408 {desc => 'Authentication token', type => 'string'},
2409 {desc => 'Purchase order ID', type => 'number'}
2411 return => {desc => 'list of new PO IDs on success, Event on error'}
2415 sub split_purchase_order_by_lineitems {
2416 my ($self, $conn, $auth, $po_id) = @_;
2418 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2419 return $e->die_event unless $e->checkauth;
2421 my $po = $e->retrieve_acq_purchase_order([
2424 "flesh_fields" => {"acqpo" => [qw/lineitems notes/]}
2426 ]) or return $e->die_event;
2428 return $e->die_event
2429 unless $e->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2431 unless ($po->state eq "pending") {
2433 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_LATE");
2436 unless (@{$po->lineitems} > 1) {
2438 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_SHORT");
2441 # To split an existing PO into many, it seems unwise to just delete the
2442 # original PO, so we'll instead detach all of the original POs' lineitems
2443 # but the first, then create new POs for each of the remaining LIs, and
2444 # then attach the LIs to their new POs.
2446 my @po_ids = ($po->id);
2447 my @moving_li = @{$po->lineitems};
2448 shift @moving_li; # discard first LI
2450 foreach my $li (@moving_li) {
2451 my $new_po = $po->clone;
2453 $new_po->clear_name;
2454 $new_po->creator($e->requestor->id);
2455 $new_po->editor($e->requestor->id);
2456 $new_po->owner($e->requestor->id);
2457 $new_po->edit_time("now");
2458 $new_po->create_time("now");
2460 $new_po = $e->create_acq_purchase_order($new_po);
2462 # Clone any notes attached to the old PO and attach to the new one.
2463 foreach my $note (@{$po->notes}) {
2464 my $new_note = $note->clone;
2465 $new_note->clear_id;
2466 $new_note->edit_time("now");
2467 $new_note->purchase_order($new_po->id);
2468 $e->create_acq_po_note($new_note);
2471 $li->edit_time("now");
2472 $li->purchase_order($new_po->id);
2473 $e->update_acq_lineitem($li);
2475 push @po_ids, $new_po->id;
2478 $po->edit_time("now");
2479 $e->update_acq_purchase_order($po);
2481 return \@po_ids if $e->commit;
2482 return $e->die_event;
2486 sub not_cancelable {
2488 (ref $o eq "HASH" and $o->{"textcode"} eq "ACQ_NOT_CANCELABLE");
2491 __PACKAGE__->register_method(
2492 method => "cancel_purchase_order_api",
2493 api_name => "open-ils.acq.purchase_order.cancel",
2495 desc => q/Cancels an on-order purchase order/,
2497 {desc => "Authentication token", type => "string"},
2498 {desc => "PO ID to cancel", type => "number"},
2499 {desc => "Cancel reason ID", type => "number"}
2501 return => {desc => q/Object describing changed POs, LIs and LIDs
2502 on success; Event on error./}
2506 sub cancel_purchase_order_api {
2507 my ($self, $conn, $auth, $po_id, $cancel_reason) = @_;
2509 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2510 return $e->die_event unless $e->checkauth;
2511 my $mgr = new OpenILS::Application::Acq::BatchManager(
2512 "editor" => $e, "conn" => $conn
2515 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2516 return new OpenILS::Event(
2517 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2520 my $result = cancel_purchase_order($mgr, $po_id, $cancel_reason) or
2521 return $e->die_event;
2522 if (not_cancelable($result)) { # event not from CStoreEditor
2525 } elsif ($result == -1) {
2527 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2530 $e->commit or return $e->die_event;
2532 # XXX create purchase order status events?
2534 if ($mgr->{post_commit}) {
2535 foreach my $func (@{$mgr->{post_commit}}) {
2543 sub cancel_purchase_order {
2544 my ($mgr, $po_id, $cancel_reason) = @_;
2546 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id) or return 0;
2548 # XXX is "cancelled" a typo? It's not correct US spelling, anyway.
2549 # Depending on context, this may not warrant an event.
2550 return -1 if $po->state eq "cancelled";
2552 # But this always does.
2553 return new OpenILS::Event(
2554 "ACQ_NOT_CANCELABLE", "note" => "purchase_order $po_id"
2555 ) unless ($po->state eq "on-order" or $po->state eq "pending");
2558 $mgr->editor->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2560 $po->state("cancelled");
2561 $po->cancel_reason($cancel_reason->id);
2563 my $li_ids = $mgr->editor->search_acq_lineitem(
2564 {"purchase_order" => $po_id}, {"idlist" => 1}
2567 my $result = {"li" => {}, "lid" => {}};
2568 foreach my $li_id (@$li_ids) {
2569 my $li_result = cancel_lineitem($mgr, $li_id, $cancel_reason)
2572 next if $li_result == -1; # already canceled:skip.
2573 return $li_result if not_cancelable($li_result); # not cancelable:stop.
2575 # Merge in each LI result (there's only going to be
2576 # one per call to cancel_lineitem).
2577 my ($k, $v) = each %{$li_result->{"li"}};
2578 $result->{"li"}->{$k} = $v;
2580 # Merge in each LID result (there may be many per call to
2582 while (($k, $v) = each %{$li_result->{"lid"}}) {
2583 $result->{"lid"}->{$k} = $v;
2587 # TODO who/what/where/how do we indicate this change for electronic orders?
2588 # TODO return changes to encumbered/spent
2589 # TODO maybe cascade up from smaller object to container object if last
2590 # smaller object in the container has been canceled?
2592 update_purchase_order($mgr, $po) or return 0;
2594 $po_id => {"state" => $po->state, "cancel_reason" => $cancel_reason}
2600 __PACKAGE__->register_method(
2601 method => "cancel_lineitem_api",
2602 api_name => "open-ils.acq.lineitem.cancel",
2604 desc => q/Cancels an on-order lineitem/,
2606 {desc => "Authentication token", type => "string"},
2607 {desc => "Lineitem ID to cancel", type => "number"},
2608 {desc => "Cancel reason ID", type => "number"}
2610 return => {desc => q/Object describing changed LIs and LIDs on success;
2615 __PACKAGE__->register_method(
2616 method => "cancel_lineitem_api",
2617 api_name => "open-ils.acq.lineitem.cancel.batch",
2619 desc => q/Batched version of open-ils.acq.lineitem.cancel/,
2620 return => {desc => q/Object describing changed LIs and LIDs on success;
2625 sub cancel_lineitem_api {
2626 my ($self, $conn, $auth, $li_id, $cancel_reason) = @_;
2628 my $batched = $self->api_name =~ /\.batch/;
2630 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2631 return $e->die_event unless $e->checkauth;
2632 my $mgr = new OpenILS::Application::Acq::BatchManager(
2633 "editor" => $e, "conn" => $conn
2636 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2637 return new OpenILS::Event(
2638 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2641 my ($result, $maybe_event);
2644 $result = {"li" => {}, "lid" => {}};
2645 foreach my $one_li_id (@$li_id) {
2646 my $one = cancel_lineitem($mgr, $one_li_id, $cancel_reason) or
2647 return $e->die_event;
2648 if (not_cancelable($one)) {
2649 $maybe_event = $one;
2650 } elsif ($result == -1) {
2651 $maybe_event = new OpenILS::Event("ACQ_ALREADY_CANCELED");
2655 while (($k, $v) = each %{$one->{"li"}}) {
2656 $result->{"li"}->{$k} = $v;
2659 if ($one->{"lid"}) {
2660 while (($k, $v) = each %{$one->{"lid"}}) {
2661 $result->{"lid"}->{$k} = $v;
2667 $result = cancel_lineitem($mgr, $li_id, $cancel_reason) or
2668 return $e->die_event;
2670 if (not_cancelable($result)) {
2673 } elsif ($result == -1) {
2675 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2679 if ($batched and not scalar keys %{$result->{"li"}}) {
2681 return $maybe_event;
2683 $e->commit or return $e->die_event;
2684 # create_lineitem_status_events should handle array li_id ok
2685 create_lineitem_status_events($mgr, $li_id, "aur.cancelled");
2687 if ($mgr->{post_commit}) {
2688 foreach my $func (@{$mgr->{post_commit}}) {
2697 sub cancel_lineitem {
2698 my ($mgr, $li_id, $cancel_reason) = @_;
2699 my $li = $mgr->editor->retrieve_acq_lineitem([
2700 $li_id, {flesh => 1, flesh_fields => {jub => ['purchase_order']}}
2703 return 0 unless $mgr->editor->allowed(
2704 "CREATE_PURCHASE_ORDER", $li->purchase_order->ordering_agency
2707 # Depending on context, this may not warrant an event.
2708 return -1 if $li->state eq "cancelled";
2710 # But this always does.
2711 return new OpenILS::Event(
2712 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id"
2714 (! $li->purchase_order) or (
2715 $li->purchase_order and (
2716 $li->state eq "on-order" or $li->state eq "pending-order"
2721 $li->state("cancelled");
2722 $li->cancel_reason($cancel_reason->id);
2724 my $lids = $mgr->editor->search_acq_lineitem_detail([{
2725 "lineitem" => $li_id
2728 flesh_fields => { acqlid => ['eg_copy_id'] }
2731 my $result = {"lid" => {}};
2733 foreach my $lid (@$lids) {
2734 my $lid_result = cancel_lineitem_detail($mgr, $lid->id, $cancel_reason)
2737 # gathering any real copies for deletion
2738 if ($lid->eg_copy_id) {
2739 $lid->eg_copy_id->isdeleted('t');
2740 push @$copies, $lid->eg_copy_id;
2743 next if $lid_result == -1; # already canceled: just skip it.
2744 return $lid_result if not_cancelable($lid_result); # not cxlable: stop.
2746 # Merge in each LID result (there's only going to be one per call to
2747 # cancel_lineitem_detail).
2748 my ($k, $v) = each %{$lid_result->{"lid"}};
2749 $result->{"lid"}->{$k} = $v;
2752 # Attempt to delete the gathered copies (this will also handle volume deletion and bib deletion)
2753 # Delete empty bibs according org unit setting
2754 my $force_delete_empty_bib = $U->ou_ancestor_setting_value(
2755 $mgr->editor->requestor->ws_ou, 'cat.bib.delete_on_no_copy_via_acq_lineitem_cancel', $mgr->editor);
2756 if (scalar(@$copies)>0) {
2758 my $delete_stats = undef;
2759 my $retarget_holds = [];
2760 my $cat_evt = OpenILS::Application::Cat::AssetCommon->update_fleshed_copies(
2761 $mgr->editor, $override, undef, $copies, $delete_stats, $retarget_holds,$force_delete_empty_bib);
2764 $logger->info("fleshed copy update failed with event: ".OpenSRF::Utils::JSON->perl2JSON($cat_evt));
2765 return new OpenILS::Event(
2766 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id", "payload" => $cat_evt
2770 # We can't do the following and stay within the same transaction, but that's okay, the hold targeter will pick these up later.
2771 #my $ses = OpenSRF::AppSession->create('open-ils.circ');
2772 #$ses->request('open-ils.circ.hold.reset.batch', $auth, $retarget_holds);
2775 # if we have a bib, check to see whether it has been deleted. if so, cancel any active holds targeting that bib
2776 if ($li->eg_bib_id) {
2777 my $bib = $mgr->editor->retrieve_biblio_record_entry($li->eg_bib_id) or return new OpenILS::Event(
2778 "ACQ_NOT_CANCELABLE", "note" => "Could not retrieve bib " . $li->eg_bib_id . " for lineitem $li_id"
2780 if ($U->is_true($bib->deleted)) {
2781 my $holds = $mgr->editor->search_action_hold_request(
2782 { cancel_time => undef,
2783 fulfillment_time => undef,
2784 target => $li->eg_bib_id
2788 my %cached_usr_home_ou = ();
2790 for my $hold (@$holds) {
2792 $logger->info("Cancelling hold ".$hold->id.
2793 " due to acq lineitem cancellation.");
2795 $hold->cancel_time('now');
2796 $hold->cancel_cause(5); # 'Staff forced'--we may want a new hold cancel cause reason for this
2797 $hold->cancel_note('Corresponding Acquistion Lineitem/Purchase Order was cancelled.');
2798 unless($mgr->editor->update_action_hold_request($hold)) {
2799 my $evt = $mgr->editor->event;
2800 $logger->error("Error updating hold ". $evt->textcode .":". $evt->desc .":". $evt->stacktrace);
2801 return new OpenILS::Event(
2802 "ACQ_NOT_CANCELABLE", "note" => "Could not cancel hold " . $hold->id . " for lineitem $li_id", "payload" => $evt
2805 if (! defined $mgr->{post_commit}) { # we need a mechanism for creating trigger events, but only if the transaction gets committed
2806 $mgr->{post_commit} = [];
2808 push @{ $mgr->{post_commit} }, sub {
2809 my $home_ou = $cached_usr_home_ou{$hold->usr};
2811 my $user = $mgr->editor->retrieve_actor_user($hold->usr); # FIXME: how do we want to handle failures here?
2812 $home_ou = $user->home_ou;
2813 $cached_usr_home_ou{$hold->usr} = $home_ou;
2815 $U->create_events_for_hook('hold_request.cancel.cancelled_order', $hold, $home_ou);
2821 update_lineitem($mgr, $li) or return 0;
2824 "state" => $li->state,
2825 "cancel_reason" => $cancel_reason
2832 __PACKAGE__->register_method(
2833 method => "cancel_lineitem_detail_api",
2834 api_name => "open-ils.acq.lineitem_detail.cancel",
2836 desc => q/Cancels an on-order lineitem detail/,
2838 {desc => "Authentication token", type => "string"},
2839 {desc => "Lineitem detail ID to cancel", type => "number"},
2840 {desc => "Cancel reason ID", type => "number"}
2842 return => {desc => q/Object describing changed LIDs on success;
2847 sub cancel_lineitem_detail_api {
2848 my ($self, $conn, $auth, $lid_id, $cancel_reason) = @_;
2850 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2851 return $e->die_event unless $e->checkauth;
2852 my $mgr = new OpenILS::Application::Acq::BatchManager(
2853 "editor" => $e, "conn" => $conn
2856 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2857 return new OpenILS::Event(
2858 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2861 my $result = cancel_lineitem_detail($mgr, $lid_id, $cancel_reason) or
2862 return $e->die_event;
2864 if (not_cancelable($result)) {
2867 } elsif ($result == -1) {
2869 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2872 $e->commit or return $e->die_event;
2874 # XXX create lineitem detail status events?
2878 sub cancel_lineitem_detail {
2879 my ($mgr, $lid_id, $cancel_reason) = @_;
2880 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
2884 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
2889 # Depending on context, this may not warrant an event.
2890 return -1 if $lid->cancel_reason;
2892 # But this always does.
2893 return new OpenILS::Event(
2894 "ACQ_NOT_CANCELABLE", "note" => "lineitem_detail $lid_id"
2896 (! $lid->lineitem->purchase_order) or
2898 (not $lid->recv_time) and
2900 $lid->lineitem->purchase_order and (
2901 $lid->lineitem->state eq "on-order" or
2902 $lid->lineitem->state eq "pending-order"
2907 return 0 unless $mgr->editor->allowed(
2908 "CREATE_PURCHASE_ORDER",
2909 $lid->lineitem->purchase_order->ordering_agency
2910 ) or (! $lid->lineitem->purchase_order);
2912 $lid->cancel_reason($cancel_reason->id);
2914 unless($U->is_true($cancel_reason->keep_debits)) {
2915 my $debit_id = $lid->fund_debit;
2916 $lid->clear_fund_debit;
2919 # item is cancelled. Remove the fund debit.
2920 my $debit = $mgr->editor->retrieve_acq_fund_debit($debit_id);
2921 if (!$U->is_true($debit->encumbrance)) {
2922 $mgr->editor->rollback;
2923 return OpenILS::Event->new('ACQ_NOT_CANCELABLE',
2924 note => "Debit is marked as paid: $debit_id");
2926 $mgr->editor->delete_acq_fund_debit($debit) or return $mgr->editor->die_event;
2930 # XXX LIDs don't have either an editor or a edit_time field. Should we
2931 # update these on the LI when we alter an LID?
2932 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
2934 return {"lid" => {$lid_id => {"cancel_reason" => $cancel_reason}}};
2938 __PACKAGE__->register_method(
2939 method => 'user_requests',
2940 api_name => 'open-ils.acq.user_request.retrieve.by_user_id',
2943 desc => 'Retrieve fleshed user requests and related data for a given user.',
2945 { desc => 'Authentication token', type => 'string' },
2946 { desc => 'User ID of the owner, or array of IDs', },
2947 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
2952 desc => 'Fleshed user requests and related data',
2958 __PACKAGE__->register_method(
2959 method => 'user_requests',
2960 api_name => 'open-ils.acq.user_request.retrieve.by_home_ou',
2963 desc => 'Retrieve fleshed user requests and related data for a given org unit or units.',
2965 { desc => 'Authentication token', type => 'string' },
2966 { desc => 'Org unit ID, or array of IDs', },
2967 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
2972 desc => 'Fleshed user requests and related data',
2979 my($self, $conn, $auth, $search_value, $options) = @_;
2980 my $e = new_editor(authtoken => $auth);
2981 return $e->event unless $e->checkauth;
2982 my $rid = $e->requestor->id;
2986 "select"=>{"aur"=>["id"],"au"=>["home_ou", {column => 'id', alias => 'usr_id'} ]},
2987 "from"=>{ "aur" => { "au" => {}, "jub" => { "type" => "left" } } },
2991 {"id"=>undef}, # this with the left-join pulls in requests without lineitems
2992 {"state"=>["new","on-order","pending-order"]} # FIXME - probably needs softcoding
2996 "order_by"=>[{"class"=>"aur", "field"=>"request_date", "direction"=>"desc"}]
2999 foreach (qw/ order_by limit offset /) {
3000 $query->{$_} = $options->{$_} if defined $options->{$_};
3002 if (defined $options->{'state'}) {
3003 $query->{'where'}->{'+jub'}->{'-or'}->[1]->{'state'} = $options->{'state'};
3006 if ($self->api_name =~ /by_user_id/) {
3007 $query->{'where'}->{'usr'} = $search_value;
3009 $query->{'where'}->{'+au'} = { 'home_ou' => $search_value };
3012 my $pertinent_ids = $e->json_query($query);
3015 for my $id_blob (@$pertinent_ids) {
3016 if ($rid != $id_blob->{usr_id}) {
3017 if (!defined $perm_test{ $id_blob->{home_ou} }) {
3018 $perm_test{ $id_blob->{home_ou} } = $e->allowed( ['user_request.view'], $id_blob->{home_ou} );
3020 if (!$perm_test{ $id_blob->{home_ou} }) {
3024 my $aur_obj = $e->retrieve_acq_user_request([
3026 {flesh => 1, flesh_fields => { "aur" => [ 'lineitem' ] } }
3028 if (! $aur_obj) { next; }
3030 if ($aur_obj->lineitem()) {
3031 $aur_obj->lineitem()->clear_marc();
3033 $conn->respond($aur_obj);
3039 __PACKAGE__->register_method (
3040 method => 'update_user_request',
3041 api_name => 'open-ils.acq.user_request.cancel.batch',
3044 desc => 'If given a cancel reason, will update the request with that reason, otherwise, this will delete the request altogether. The ' .
3045 'intention is for staff interfaces or processes to provide cancel reasons, and for patron interfaces to just delete the requests.' ,
3047 { desc => 'Authentication token', type => 'string' },
3048 { desc => 'ID or array of IDs for the user requests to cancel' },
3049 { desc => 'Cancel Reason ID (optional)', type => 'string' }
3052 desc => 'progress object, event on error',
3056 __PACKAGE__->register_method (
3057 method => 'update_user_request',
3058 api_name => 'open-ils.acq.user_request.set_no_hold.batch',
3061 desc => 'Remove the hold from a user request or set of requests',
3063 { desc => 'Authentication token', type => 'string' },
3064 { desc => 'ID or array of IDs for the user requests to modify' }
3067 desc => 'progress object, event on error',
3072 sub update_user_request {
3073 my($self, $conn, $auth, $aur_ids, $cancel_reason) = @_;
3074 my $e = new_editor(xact => 1, authtoken => $auth);
3075 return $e->die_event unless $e->checkauth;
3076 my $rid = $e->requestor->id;
3080 for my $id (@$aur_ids) {
3082 my $aur_obj = $e->retrieve_acq_user_request([
3085 flesh_fields => { "aur" => ['lineitem', 'usr'] }
3087 ]) or return $e->die_event;
3089 my $context_org = $aur_obj->usr()->home_ou();
3090 $aur_obj->usr( $aur_obj->usr()->id() );
3092 if ($rid != $aur_obj->usr) {
3093 if (!defined $perm_test{ $context_org }) {
3094 $perm_test{ $context_org } = $e->allowed( ['user_request.update'], $context_org );
3096 if (!$perm_test{ $context_org }) {
3101 if($self->api_name =~ /set_no_hold/) {
3102 if ($U->is_true($aur_obj->hold)) {
3104 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3108 if($self->api_name =~ /cancel/) {
3109 if ( $cancel_reason ) {
3110 $aur_obj->cancel_reason( $cancel_reason );
3111 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3112 create_user_request_events( $e, [ $aur_obj ], 'aur.rejected' );
3114 $e->delete_acq_user_request($aur_obj);
3118 $conn->respond({maximum => scalar(@$aur_ids), progress => $x++});
3122 return {complete => 1};
3125 __PACKAGE__->register_method (
3126 method => 'new_user_request',
3127 api_name => 'open-ils.acq.user_request.create',
3129 desc => 'Create a new user request object in the DB',
3131 { desc => 'Authentication token', type => 'string' },
3132 { desc => 'User request data hash. Hash keys match the fields for the "aur" object', type => 'object' }
3135 desc => 'The created user request object, or event on error'
3140 sub new_user_request {
3141 my($self, $conn, $auth, $form_data) = @_;
3142 my $e = new_editor(xact => 1, authtoken => $auth);
3143 return $e->die_event unless $e->checkauth;
3144 my $rid = $e->requestor->id;
3145 my $target_user_fleshed;
3146 if (! defined $$form_data{'usr'}) {
3147 $$form_data{'usr'} = $rid;
3149 if ($$form_data{'usr'} != $rid) {
3150 # See if the requestor can place the request on behalf of a different user.
3151 $target_user_fleshed = $e->retrieve_actor_user($$form_data{'usr'}) or return $e->die_event;
3152 $e->allowed('user_request.create', $target_user_fleshed->home_ou) or return $e->die_event;
3154 $target_user_fleshed = $e->requestor;
3155 $e->allowed('CREATE_PURCHASE_REQUEST') or return $e->die_event;
3157 if (! defined $$form_data{'pickup_lib'}) {
3158 if ($target_user_fleshed->ws_ou) {
3159 $$form_data{'pickup_lib'} = $target_user_fleshed->ws_ou;
3161 $$form_data{'pickup_lib'} = $target_user_fleshed->home_ou;
3164 if (! defined $$form_data{'request_type'}) {
3165 $$form_data{'request_type'} = 1; # Books
3167 my $aur_obj = new Fieldmapper::acq::user_request;
3169 $aur_obj->usr( $$form_data{'usr'} );
3170 $aur_obj->request_date( 'now' );
3171 for my $field ( keys %$form_data ) {
3172 if (defined $$form_data{$field} and $field !~ /^(id|lineitem|eg_bib|request_date|cancel_reason)$/) {
3173 $aur_obj->$field( $$form_data{$field} );
3177 $aur_obj = $e->create_acq_user_request($aur_obj) or return $e->die_event;
3179 $e->commit and create_user_request_events( $e, [ $aur_obj ], 'aur.created' );
3184 sub create_user_request_events {
3185 my($e, $user_reqs, $hook) = @_;
3187 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
3190 my %cached_usr_home_ou = ();
3191 for my $user_req (@$user_reqs) {
3192 my $home_ou = $cached_usr_home_ou{$user_req->usr};
3194 my $user = $e->retrieve_actor_user($user_req->usr) or return $e->die_event;
3195 $home_ou = $user->home_ou;
3196 $cached_usr_home_ou{$user_req->usr} = $home_ou;
3198 my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $home_ou);
3207 __PACKAGE__->register_method(
3208 method => "po_note_CUD_batch",
3209 api_name => "open-ils.acq.po_note.cud.batch",
3212 desc => q/Manage purchase order notes/,
3214 {desc => "Authentication token", type => "string"},
3215 {desc => "List of po_notes to manage", type => "array"},
3217 return => {desc => "Stream of successfully managed objects"}
3221 sub po_note_CUD_batch {
3222 my ($self, $conn, $auth, $notes) = @_;
3224 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3225 return $e->die_event unless $e->checkauth;
3228 my $total = @$notes;
3231 foreach my $note (@$notes) {
3233 $note->editor($e->requestor->id);
3234 $note->edit_time("now");
3237 $note->creator($e->requestor->id);
3238 $note = $e->create_acq_po_note($note) or return $e->die_event;
3239 } elsif ($note->isdeleted) {
3240 $e->delete_acq_po_note($note) or return $e->die_event;
3241 } elsif ($note->ischanged) {
3242 $e->update_acq_po_note($note) or return $e->die_event;
3245 unless ($note->isdeleted) {
3246 $note = $e->retrieve_acq_po_note($note->id) or
3247 return $e->die_event;
3251 {"maximum" => $total, "progress" => ++$count, "note" => $note}
3255 $e->commit and $conn->respond_complete or return $e->die_event;
3259 # retrieves a lineitem, fleshes its PO and PL, checks perms
3260 sub fetch_and_check_li {
3263 my $perm_mode = shift || 'read';
3265 my $li = $e->retrieve_acq_lineitem([
3268 flesh_fields => {jub => ['purchase_order', 'picklist']}
3270 ]) or return $e->die_event;
3272 if(my $po = $li->purchase_order) {
3273 my $perms = ($perm_mode eq 'read') ? 'VIEW_PURCHASE_ORDER' : 'CREATE_PURCHASE_ORDER';
3274 return ($li, $e->die_event) unless $e->allowed($perms, $po->ordering_agency);
3276 } elsif(my $pl = $li->picklist) {
3277 my $perms = ($perm_mode eq 'read') ? 'VIEW_PICKLIST' : 'CREATE_PICKLIST';
3278 return ($li, $e->die_event) unless $e->allowed($perms, $pl->org_unit);
3285 __PACKAGE__->register_method(
3286 method => "clone_distrib_form",
3287 api_name => "open-ils.acq.distribution_formula.clone",
3290 desc => q/Clone a distribution formula/,
3292 {desc => "Authentication token", type => "string"},
3293 {desc => "Original formula ID", type => 'integer'},
3294 {desc => "Name of new formula", type => 'string'},
3296 return => {desc => "ID of newly created formula"}
3300 sub clone_distrib_form {
3301 my($self, $client, $auth, $form_id, $new_name) = @_;
3303 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3304 return $e->die_event unless $e->checkauth;
3306 my $old_form = $e->retrieve_acq_distribution_formula($form_id) or return $e->die_event;
3307 return $e->die_event unless $e->allowed('ADMIN_ACQ_DISTRIB_FORMULA', $old_form->owner);
3309 my $new_form = Fieldmapper::acq::distribution_formula->new;
3311 $new_form->owner($old_form->owner);
3312 $new_form->name($new_name);
3313 $e->create_acq_distribution_formula($new_form) or return $e->die_event;
3315 my $entries = $e->search_acq_distribution_formula_entry({formula => $form_id});
3316 for my $entry (@$entries) {
3317 my $new_entry = Fieldmapper::acq::distribution_formula_entry->new;
3318 $new_entry->$_($entry->$_()) for $entry->real_fields;
3319 $new_entry->formula($new_form->id);
3320 $new_entry->clear_id;
3321 $e->create_acq_distribution_formula_entry($new_entry) or return $e->die_event;
3325 return $new_form->id;
3328 __PACKAGE__->register_method(
3329 method => 'add_li_to_po',
3330 api_name => 'open-ils.acq.purchase_order.add_lineitem',
3332 desc => q/Adds a lineitem to an existing purchase order/,
3334 {desc => 'Authentication token', type => 'string'},
3335 {desc => 'The purchase order id', type => 'number'},
3336 {desc => 'The lineitem ID', type => 'number'},
3338 return => {desc => 'Streams a total versus completed counts object, event on error'}
3343 my($self, $conn, $auth, $po_id, $li_id) = @_;
3345 my $e = new_editor(authtoken => $auth, xact => 1);
3346 return $e->die_event unless $e->checkauth;
3348 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
3350 my $po = $e->retrieve_acq_purchase_order($po_id)
3351 or return $e->die_event;
3353 my $li = $e->retrieve_acq_lineitem($li_id)
3354 or return $e->die_event;
3356 return $e->die_event unless
3357 $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
3359 unless ($po->state =~ /new|pending/) {
3361 return {success => 0, po => $po, error => 'bad-po-state'};
3364 unless ($li->state =~ /new|order-ready|pending-order/) {
3366 return {success => 0, li => $li, error => 'bad-li-state'};
3369 $li->purchase_order($po_id);
3370 $li->state('pending-order');
3371 update_lineitem($mgr, $li) or return $e->die_event;
3374 return {success => 1};