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(5) 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};
52 sub respond_complete {
53 my($self, %other_args) = @_;
55 $self->conn->respond_complete({ %{$self->{args}}, %other_args });
56 $self->run_post_response_hooks;
60 # run the post response hook subs, shifting them off as we go
61 sub run_post_response_hooks {
63 (shift @{$self->{post_proc_queue}})->() while @{$self->{post_proc_queue}};
66 # any subs passed to this method will be run after the call to respond_complete
69 push(@{$self->{post_proc_queue}}, $sub);
74 $self->{args}->{total} = $val if defined $val;
75 $self->{args}->{maximum} = $self->{args}->{total};
76 return $self->{args}->{total};
80 $self->{args}->{purchase_order} = $val if $val;
85 $self->{args}->{picklist} = $val if $val;
90 $self->{args}->{lid} += 1;
91 $self->{args}->{progress} += 1;
96 $self->{args}->{li} += 1;
97 $self->{args}->{progress} += 1;
102 $self->{args}->{vqbr} += 1;
103 $self->{args}->{progress} += 1;
108 $self->{args}->{copies} += 1;
109 $self->{args}->{progress} += 1;
114 $self->{args}->{bibs} += 1;
115 $self->{args}->{progress} += 1;
119 my($self, $amount) = @_;
120 $self->{args}->{debits_accrued} += $amount;
121 $self->{args}->{progress} += 1;
125 my($self, $editor) = @_;
126 $self->{editor} = $editor if defined $editor;
127 return $self->{editor};
131 $self->{args}->{complete} = 1;
136 my($self, $org, $key, $val) = @_;
137 $self->{cache}->{$org} = {} unless $self->{cache}->{org};
138 $self->{cache}->{$org}->{$key} = $val if defined $val;
139 return $self->{cache}->{$org}->{$key};
143 package OpenILS::Application::Acq::Order;
144 use base qw/OpenILS::Application/;
145 use strict; use warnings;
146 # ----------------------------------------------------------------------------
147 # Break up each component of the order process and pieces into managable
148 # actions that can be shared across different workflows
149 # ----------------------------------------------------------------------------
151 use OpenSRF::Utils::Logger qw(:logger);
152 use OpenSRF::Utils::JSON;
153 use OpenSRF::AppSession;
154 use OpenILS::Utils::Fieldmapper;
155 use OpenILS::Utils::CStoreEditor q/:funcs/;
156 use OpenILS::Utils::Normalize qw/clean_marc/;
157 use OpenILS::Const qw/:const/;
158 use OpenSRF::EX q/:try/;
159 use OpenILS::Application::AppUtils;
160 use OpenILS::Application::Cat::BibCommon;
161 use OpenILS::Application::Cat::AssetCommon;
164 use MARC::File::XML (BinaryEncoding => 'UTF-8');
165 use Digest::MD5 qw(md5_hex);
167 $Data::Dumper::Indent = 0;
168 my $U = 'OpenILS::Application::AppUtils';
171 # ----------------------------------------------------------------------------
173 # ----------------------------------------------------------------------------
174 sub create_lineitem {
175 my($mgr, %args) = @_;
176 my $li = Fieldmapper::acq::lineitem->new;
177 $li->creator($mgr->editor->requestor->id);
178 $li->selector($li->creator);
179 $li->editor($li->creator);
180 $li->create_time('now');
181 $li->edit_time('now');
183 $li->$_($args{$_}) for keys %args;
186 $mgr->editor->create_acq_lineitem($li) or return 0;
188 unless($li->estimated_unit_price) {
189 # extract the price from the MARC data
190 my $price = get_li_price_from_attr($mgr->editor, $li) or return $li;
191 $li->estimated_unit_price($price);
192 return update_lineitem($mgr, $li);
198 sub get_li_price_from_attr {
200 my $attrs = $li->attributes || $e->search_acq_lineitem_attr({lineitem => $li->id});
202 for my $attr_type (qw/
203 lineitem_local_attr_definition
204 lineitem_prov_attr_definition
205 lineitem_marc_attr_definition/) {
208 $_->attr_name eq 'estimated_price' and
209 $_->attr_type eq $attr_type } @$attrs;
211 return $attr->attr_value if $attr;
218 sub update_lineitem {
220 $li->edit_time('now');
221 $li->editor($mgr->editor->requestor->id);
223 return $mgr->editor->retrieve_acq_lineitem($mgr->editor->data) if
224 $mgr->editor->update_acq_lineitem($li);
229 # ----------------------------------------------------------------------------
230 # Create real holds from patron requests for a given lineitem
231 # ----------------------------------------------------------------------------
232 sub promote_lineitem_holds {
235 my $requests = $mgr->editor->search_acq_user_request(
236 { lineitem => $li->id,
238 [ { need_before => {'>' => 'now'} },
239 { need_before => undef }
244 for my $request ( @$requests ) {
246 $request->eg_bib( $li->eg_bib_id );
247 $mgr->editor->update_acq_user_request( $request ) or return 0;
249 next unless ($U->is_true( $request->hold ));
251 my $hold = Fieldmapper::action::hold_request->new;
252 $hold->usr( $request->usr );
253 $hold->requestor( $request->usr );
254 $hold->request_time( $request->request_date );
255 $hold->pickup_lib( $request->pickup_lib );
256 $hold->request_lib( $request->pickup_lib );
257 $hold->selection_ou( $request->pickup_lib );
258 $hold->phone_notify( $request->phone_notify );
259 $hold->email_notify( $request->email_notify );
260 $hold->expire_time( $request->need_before );
262 if ($request->holdable_formats) {
263 my $mrm = $mgr->editor->search_metabib_metarecord_source_map( { source => $li->eg_bib_id } )->[0];
265 $hold->hold_type( 'M' );
266 $hold->holdable_formats( $request->holdable_formats );
267 $hold->target( $mrm->metarecord );
271 if (!$hold->target) {
272 $hold->hold_type( 'T' );
273 $hold->target( $li->eg_bib_id );
276 $mgr->editor->create_actor_hold_request( $hold ) or return 0;
282 sub delete_lineitem {
284 $li = $mgr->editor->retrieve_acq_lineitem($li) unless ref $li;
286 # delete the attached lineitem_details
287 my $lid_ids = $mgr->editor->search_acq_lineitem_detail({lineitem => $li->id}, {idlist=>1});
288 for my $lid_id (@$lid_ids) {
289 return 0 unless delete_lineitem_detail($mgr, $lid_id);
293 return $mgr->editor->delete_acq_lineitem($li);
296 # begins and commit transactions as it goes
297 sub create_lineitem_list_assets {
298 my($mgr, $li_ids, $vandelay) = @_;
300 if (check_import_li_marc_perms($mgr, $li_ids)) { # event on error
301 $logger->error("acq-vl: user does not have permission to import acq records");
305 my $res = import_li_bibs_via_vandelay($mgr, $li_ids, $vandelay);
306 return undef unless $res;
308 # create the bibs/volumes/copies for the successfully imported records
309 for my $li_id (@{$res->{li_ids}}) {
310 $mgr->editor->xact_begin;
311 my $data = create_lineitem_assets($mgr, $li_id) or return undef;
312 $mgr->editor->xact_commit;
319 sub verify_vandelay_import_args {
320 my $vandelay = shift;
323 return 0 unless $vandelay and
324 ($vandelay->{queue_name} or $vandelay->{existing_queue});
326 # match-based merge/overlay import
327 return 1 if $vandelay->{merge_profile} and (
328 $vandelay->{auto_overlay_exact} or
329 $vandelay->{auto_overlay_1match} or
330 $vandelay->{auto_overlay_best_match}
334 return 1 if $vandelay->{import_no_match};
339 sub find_or_create_vandelay_queue {
340 my ($e, $vandelay) = @_;
343 if (my $name = $vandelay->{queue_name}) {
345 # first, see if a queue w/ this name already exists
346 # for this user. If so, use that instead.
348 $queue = $e->search_vandelay_bib_queue(
349 {name => $name, owner => $e->requestor->id})->[0];
353 $logger->info("acq-vl: using existing queue $name");
357 $logger->info("acq-vl: creating new vandelay queue $name");
359 $queue = new Fieldmapper::vandelay::bib_queue;
361 $queue->queue_type('acq');
362 $queue->owner($e->requestor->id);
363 $queue->match_set($vandelay->{match_set} || undef); # avoid ''
364 $queue = $e->create_vandelay_bib_queue($queue) or return undef;
368 $queue = $e->retrieve_vandelay_bib_queue($vandelay->{existing_queue})
376 sub import_li_bibs_via_vandelay {
377 my ($mgr, $li_ids, $vandelay) = @_;
378 my $res = {li_ids => []};
379 my $e = $mgr->editor;
382 my $needs_importing = $e->search_acq_lineitem(
383 {id => $li_ids, eg_bib_id => undef},
387 if (!@$needs_importing) {
388 $logger->info("acq-vl: all records already imported. no Vandelay work to do");
389 return {li_ids => $li_ids};
392 # add the already-imported records to the response list
393 push(@{$res->{li_ids}}, grep { $_ != @$needs_importing } @$li_ids);
395 $logger->info("acq-vl: processing recs via Vandelay with args: ".Dumper($vandelay));
397 if (!verify_vandelay_import_args($vandelay)) {
398 $logger->error("acq-vl: invalid vandelay arguments for acq import");
402 my $queue = find_or_create_vandelay_queue($e, $vandelay) or return $res;
403 $mgr->{args}->{queue} = $queue;
405 # load the lineitems into the queue for merge processing
408 for my $li_id (@$needs_importing) {
410 my $li = $e->retrieve_acq_lineitem($li_id) or return $res;
412 my $vqbr = Fieldmapper::vandelay::queued_bib_record->new;
413 $vqbr->marc($li->marc);
414 $vqbr->queue($queue->id);
415 $vqbr->bib_source($vandelay->{bib_source} || undef); # avoid ''
416 $vqbr = $e->create_vandelay_queued_bib_record($vqbr) or return $res;
417 push(@vqbr_ids, $vqbr->id);
421 # tell the acq record which vandelay record it's linked to
422 $li->queued_record($vqbr->id);
423 $e->update_acq_lineitem($li) or return $res;
427 $logger->info("acq-vl: created vandelay records [@vqbr_ids]");
429 # we have to commit the transaction now since
430 # vandelay uses its own transactions.
433 # Import the bibs via vandelay. Note: Vandely will
434 # update acq.lineitem.eg_bib_id on successful import.
436 $vandelay->{report_all} = 1;
437 my $ses = OpenSRF::AppSession->create('open-ils.vandelay');
438 my $req = $ses->request(
439 'open-ils.vandelay.bib_record.list.import',
440 $e->authtoken, \@vqbr_ids, $vandelay);
442 # pull the responses, noting all that were successfully imported
444 while (my $resp = $req->recv(timeout => 600)) {
445 my $stat = $resp->content;
447 if(!$stat or $U->event_code($stat)) { # import failure
448 $logger->error("acq-vl: error importing vandelay record " . Dumper($stat));
452 # "imported" refers to the vqbr id, not the
453 # success/failure of the vqbr merge attempt
454 next unless $stat->{imported};
456 my ($imported) = grep {$_->queued_record eq $stat->{imported}} @lis;
457 my $li_id = $imported->id;
459 if ($stat->{no_import}) {
460 $logger->info("acq-vl: acq lineitem $li_id did not import");
462 } else { # successful import
464 push(@success_lis, $li_id);
467 $logger->info("acq-vl: acq lineitem $li_id successfully merged/imported");
472 $logger->info("acq-vl: successfully imported lineitems [@success_lis]");
474 # add the successfully imported lineitems to the already-imported lineitems
475 push (@{$res->{li_ids}}, @success_lis);
480 # returns event on error, undef on success
481 sub check_import_li_marc_perms {
482 my($mgr, $li_ids) = @_;
484 # if there are any order records that are not linked to
485 # in-db bib records, verify staff has perms to import order records
486 my $order_li = $mgr->editor->search_acq_lineitem(
487 [{id => $li_ids, eg_bib_id => undef}, {limit => 1}], {idlist => 1})->[0];
490 return $mgr->editor->die_event unless
491 $mgr->editor->allowed('IMPORT_ACQ_LINEITEM_BIB_RECORD');
498 # ----------------------------------------------------------------------------
499 # if all of the lineitem details for this lineitem have
500 # been received, mark the lineitem as received
501 # returns 1 on non-received, li on received, 0 on error
502 # ----------------------------------------------------------------------------
504 sub describe_affected_po {
508 OpenILS::Application::Acq::Financials::build_price_summary(
513 "state" => $po->state,
514 "amount_encumbered" => $enc,
515 "amount_spent" => $spent
520 sub check_lineitem_received {
521 my($mgr, $li_id) = @_;
523 my $non_recv = $mgr->editor->search_acq_lineitem_detail(
524 {recv_time => undef, lineitem => $li_id}, {idlist=>1});
526 return 1 if @$non_recv;
528 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
529 $li->state('received');
530 return update_lineitem($mgr, $li);
533 sub receive_lineitem {
534 my($mgr, $li_id, $skip_complete_check) = @_;
535 my $li = $mgr->editor->retrieve_acq_lineitem($li_id) or return 0;
537 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
538 {lineitem => $li_id, recv_time => undef}, {idlist => 1});
540 for my $lid_id (@$lid_ids) {
541 receive_lineitem_detail($mgr, $lid_id, 1) or return 0;
545 $li->state('received');
547 $li = update_lineitem($mgr, $li) or return 0;
548 $mgr->post_process( sub { create_lineitem_status_events($mgr, $li_id, 'aur.received'); });
552 $skip_complete_check or (
553 $po = check_purchase_order_received($mgr, $li->purchase_order)
556 my $result = {"li" => {$li->id => {"state" => $li->state}}};
557 $result->{"po"} = describe_affected_po($mgr->editor, $po) if ref $po;
561 sub rollback_receive_lineitem {
562 my($mgr, $li_id) = @_;
563 my $li = $mgr->editor->retrieve_acq_lineitem($li_id) or return 0;
565 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
566 {lineitem => $li_id, recv_time => {'!=' => undef}}, {idlist => 1});
568 for my $lid_id (@$lid_ids) {
569 rollback_receive_lineitem_detail($mgr, $lid_id, 1) or return 0;
573 $li->state('on-order');
574 return update_lineitem($mgr, $li);
578 sub create_lineitem_status_events {
579 my($mgr, $li_id, $hook) = @_;
581 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
583 my $user_reqs = $mgr->editor->search_acq_user_request([
584 {lineitem => $li_id},
585 {flesh => 1, flesh_fields => {aur => ['usr']}}
588 for my $user_req (@$user_reqs) {
589 my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $user_req->usr->home_ou);
597 # ----------------------------------------------------------------------------
599 # ----------------------------------------------------------------------------
600 sub create_lineitem_detail {
601 my($mgr, %args) = @_;
602 my $lid = Fieldmapper::acq::lineitem_detail->new;
603 $lid->$_($args{$_}) for keys %args;
606 return $mgr->editor->create_acq_lineitem_detail($lid);
610 # flesh out any required data with default values where appropriate
611 sub complete_lineitem_detail {
613 unless($lid->barcode) {
614 my $pfx = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.tmp_barcode_prefix') || 'ACQ';
615 $lid->barcode($pfx.$lid->id);
618 unless($lid->cn_label) {
619 my $pfx = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.tmp_callnumber_prefix') || 'ACQ';
620 $lid->cn_label($pfx.$lid->id);
623 if(!$lid->location and my $loc = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.default_copy_location')) {
624 $lid->location($loc);
627 $lid->circ_modifier(get_default_circ_modifier($mgr, $lid->owning_lib))
628 unless defined $lid->circ_modifier;
630 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
634 sub get_default_circ_modifier {
636 my $code = $mgr->cache($org, 'def_circ_mod');
637 $code = $U->ou_ancestor_setting_value($org, 'acq.default_circ_modifier') unless defined $code;
638 return $mgr->cache($org, 'def_circ_mod', $code) if defined $code;
642 sub delete_lineitem_detail {
644 $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid) unless ref $lid;
645 return $mgr->editor->delete_acq_lineitem_detail($lid);
649 sub receive_lineitem_detail {
650 my($mgr, $lid_id, $skip_complete_check) = @_;
651 my $e = $mgr->editor;
653 my $lid = $e->retrieve_acq_lineitem_detail([
657 acqlid => ['fund_debit']
662 return 1 if $lid->recv_time;
664 $lid->receiver($e->requestor->id);
665 $lid->recv_time('now');
666 $e->update_acq_lineitem_detail($lid) or return 0;
668 if ($lid->eg_copy_id) {
669 my $copy = $e->retrieve_asset_copy($lid->eg_copy_id) or return 0;
670 $copy->status(OILS_COPY_STATUS_IN_PROCESS);
671 $copy->edit_date('now');
672 $copy->editor($e->requestor->id);
673 $copy->creator($e->requestor->id) if $U->ou_ancestor_setting_value(
674 $e->requestor->ws_ou, 'acq.copy_creator_uses_receiver', $e);
675 $e->update_asset_copy($copy) or return 0;
680 return 1 if $skip_complete_check;
682 my $li = check_lineitem_received($mgr, $lid->lineitem) or return 0;
683 return 1 if $li == 1; # li not received
685 return check_purchase_order_received($mgr, $li->purchase_order) or return 0;
689 sub rollback_receive_lineitem_detail {
690 my($mgr, $lid_id) = @_;
691 my $e = $mgr->editor;
693 my $lid = $e->retrieve_acq_lineitem_detail([
697 acqlid => ['fund_debit']
702 return 1 unless $lid->recv_time;
704 $lid->clear_receiver;
705 $lid->clear_recv_time;
706 $e->update_acq_lineitem_detail($lid) or return 0;
708 if ($lid->eg_copy_id) {
709 my $copy = $e->retrieve_asset_copy($lid->eg_copy_id) or return 0;
710 $copy->status(OILS_COPY_STATUS_ON_ORDER);
711 $copy->edit_date('now');
712 $copy->editor($e->requestor->id);
713 $e->update_asset_copy($copy) or return 0;
720 # ----------------------------------------------------------------------------
722 # ----------------------------------------------------------------------------
723 sub set_lineitem_attr {
724 my($mgr, %args) = @_;
725 my $attr_type = $args{attr_type};
727 # first, see if it's already set. May just need to overwrite it
728 my $attr = $mgr->editor->search_acq_lineitem_attr({
729 lineitem => $args{lineitem},
730 attr_type => $args{attr_type},
731 attr_name => $args{attr_name}
735 $attr->attr_value($args{attr_value});
736 return $attr if $mgr->editor->update_acq_lineitem_attr($attr);
741 $attr = Fieldmapper::acq::lineitem_attr->new;
742 $attr->$_($args{$_}) for keys %args;
744 unless($attr->definition) {
745 my $find = "search_acq_$attr_type";
746 my $attr_def_id = $mgr->editor->$find({code => $attr->attr_name}, {idlist=>1})->[0] or return 0;
747 $attr->definition($attr_def_id);
749 return $mgr->editor->create_acq_lineitem_attr($attr);
753 # ----------------------------------------------------------------------------
755 # ----------------------------------------------------------------------------
756 sub create_lineitem_debits {
757 my ($mgr, $li, $dry_run) = @_;
759 unless($li->estimated_unit_price) {
760 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_PRICE', payload => $li->id));
761 $mgr->editor->rollback;
765 unless($li->provider) {
766 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_PROVIDER', payload => $li->id));
767 $mgr->editor->rollback;
771 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
772 {lineitem => $li->id},
776 for my $lid_id (@$lid_ids) {
778 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
781 flesh_fields => {acqlid => ['fund']}
785 create_lineitem_detail_debit($mgr, $li, $lid, $dry_run) or return 0;
794 sub create_lineitem_detail_debit {
795 my ($mgr, $li, $lid, $dry_run, $no_translate) = @_;
797 # don't create the debit if one already exists
798 return $mgr->editor->retrieve_acq_fund_debit($lid->fund_debit) if $lid->fund_debit;
800 my $li_id = ref($li) ? $li->id : $li;
802 unless(ref $li and ref $li->provider) {
803 $li = $mgr->editor->retrieve_acq_lineitem([
806 flesh_fields => {jub => ['provider']},
812 $lid->fund($mgr->editor->retrieve_acq_fund($lid->fund)) unless(ref $lid->fund);
814 $lid = $mgr->editor->retrieve_acq_lineitem_detail([
817 flesh_fields => {acqlid => ['fund']}
822 unless ($lid->fund) {
824 new OpenILS::Event("ACQ_FUND_NOT_FOUND") # close enough
829 my $amount = $li->estimated_unit_price;
830 if($li->provider->currency_type ne $lid->fund->currency_type and !$no_translate) {
832 # At Fund debit creation time, translate into the currency of the fund
833 # TODO: org setting to disable automatic currency conversion at debit create time?
835 $amount = $mgr->editor->json_query({
837 'acq.exchange_ratio',
838 $li->provider->currency_type, # source currency
839 $lid->fund->currency_type, # destination currency
840 $li->estimated_unit_price # source amount
842 })->[0]->{'acq.exchange_ratio'};
845 my $debit = create_fund_debit(
848 fund => $lid->fund->id,
849 origin_amount => $li->estimated_unit_price,
850 origin_currency_type => $li->provider->currency_type,
854 $lid->fund_debit($debit->id);
855 $lid->fund($lid->fund->id);
856 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
861 __PACKAGE__->register_method(
862 "method" => "fund_exceeds_balance_percent_api",
863 "api_name" => "open-ils.acq.fund.check_balance_percentages",
865 "desc" => q/Determine whether a given fund exceeds its defined
866 "balance stop and warning percentages"/,
868 {"desc" => "Authentication token", "type" => "string"},
869 {"desc" => "Fund ID", "type" => "number"},
870 {"desc" => "Theoretical debit amount (optional)",
873 "return" => {"desc" => q/An array of two values, for stop and warning,
874 in that order: 1 if fund exceeds that balance percentage, else 0/}
878 sub fund_exceeds_balance_percent_api {
879 my ($self, $conn, $auth, $fund_id, $debit_amount) = @_;
883 my $e = new_editor("authtoken" => $auth);
884 return $e->die_event unless $e->checkauth;
886 my $fund = $e->retrieve_acq_fund($fund_id) or return $e->die_event;
887 return $e->die_event unless $e->allowed("VIEW_FUND", $fund->org);
890 fund_exceeds_balance_percent($fund, $debit_amount, $e, "stop"),
891 fund_exceeds_balance_percent($fund, $debit_amount, $e, "warning")
898 sub fund_exceeds_balance_percent {
899 my ($fund, $debit_amount, $e, $which) = @_;
901 my ($method_name, $event_name) = @{{
903 "balance_warning_percent", "ACQ_FUND_EXCEEDS_WARN_PERCENT"
906 "balance_stop_percent", "ACQ_FUND_EXCEEDS_STOP_PERCENT"
910 if ($fund->$method_name) {
912 $e->search_acq_fund_combined_balance({"fund" => $fund->id})->[0];
914 $e->search_acq_fund_allocation_total({"fund" => $fund->id})->[0];
916 $balance = ($balance) ? $balance->amount : 0;
917 $allocations = ($allocations) ? $allocations->amount : 0;
920 $allocations == 0 || # if no allocations were ever made, assume we have hit the stop percent
921 ((($allocations - $balance + $debit_amount) / $allocations) * 100) > $fund->$method_name
923 $logger->info("fund would hit a limit: " . $fund->id . ", $balance, $debit_amount, $allocations, $method_name");
928 "fund" => $fund, "debit_amount" => $debit_amount
938 # ----------------------------------------------------------------------------
940 # ----------------------------------------------------------------------------
941 sub create_fund_debit {
942 my($mgr, $dry_run, %args) = @_;
944 # Verify the fund is not being spent beyond the hard stop amount
945 my $fund = $mgr->editor->retrieve_acq_fund($args{fund}) or return 0;
948 fund_exceeds_balance_percent(
949 $fund, $args{"amount"}, $mgr->editor, "stop"
952 $dry_run and fund_exceeds_balance_percent(
953 $fund, $args{"amount"}, $mgr->editor, "warning"
956 my $debit = Fieldmapper::acq::fund_debit->new;
957 $debit->debit_type('purchase');
958 $debit->encumbrance('t');
959 $debit->$_($args{$_}) for keys %args;
961 $mgr->add_debit($debit->amount);
962 return $mgr->editor->create_acq_fund_debit($debit);
966 # ----------------------------------------------------------------------------
968 # ----------------------------------------------------------------------------
969 sub create_picklist {
970 my($mgr, %args) = @_;
971 my $picklist = Fieldmapper::acq::picklist->new;
972 $picklist->creator($mgr->editor->requestor->id);
973 $picklist->owner($picklist->creator);
974 $picklist->editor($picklist->creator);
975 $picklist->create_time('now');
976 $picklist->edit_time('now');
977 $picklist->org_unit($mgr->editor->requestor->ws_ou);
978 $picklist->owner($mgr->editor->requestor->id);
979 $picklist->$_($args{$_}) for keys %args;
981 $mgr->picklist($picklist);
982 return $mgr->editor->create_acq_picklist($picklist);
985 sub update_picklist {
986 my($mgr, $picklist) = @_;
987 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
988 $picklist->edit_time('now');
989 $picklist->editor($mgr->editor->requestor->id);
990 if ($mgr->editor->update_acq_picklist($picklist)) {
991 $picklist = $mgr->editor->retrieve_acq_picklist($mgr->editor->data);
992 $mgr->picklist($picklist);
999 sub delete_picklist {
1000 my($mgr, $picklist) = @_;
1001 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
1003 # delete all 'new' lineitems
1004 my $li_ids = $mgr->editor->search_acq_lineitem(
1006 picklist => $picklist->id,
1007 "-or" => {state => "new", purchase_order => undef}
1011 for my $li_id (@$li_ids) {
1012 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
1013 return 0 unless delete_lineitem($mgr, $li);
1017 # detach all non-'new' lineitems
1018 $li_ids = $mgr->editor->search_acq_lineitem({picklist => $picklist->id, state => {'!=' => 'new'}}, {idlist => 1});
1019 for my $li_id (@$li_ids) {
1020 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
1021 $li->clear_picklist;
1022 return 0 unless update_lineitem($mgr, $li);
1026 # remove any picklist-specific object perms
1027 my $ops = $mgr->editor->search_permission_usr_object_perm_map({object_type => 'acqpl', object_id => ''.$picklist->id});
1028 for my $op (@$ops) {
1029 return 0 unless $mgr->editor->delete_usr_object_perm_map($op);
1032 return $mgr->editor->delete_acq_picklist($picklist);
1035 # ----------------------------------------------------------------------------
1037 # ----------------------------------------------------------------------------
1038 sub update_purchase_order {
1040 $po = $mgr->editor->retrieve_acq_purchase_order($po) unless ref $po;
1041 $po->editor($mgr->editor->requestor->id);
1042 $po->edit_time('now');
1043 $mgr->purchase_order($po);
1044 return $mgr->editor->retrieve_acq_purchase_order($mgr->editor->data)
1045 if $mgr->editor->update_acq_purchase_order($po);
1049 sub create_purchase_order {
1050 my($mgr, %args) = @_;
1052 # verify the chosen provider is still active
1053 my $provider = $mgr->editor->retrieve_acq_provider($args{provider}) or return 0;
1054 unless($U->is_true($provider->active)) {
1055 $logger->error("provider is not active. cannot create PO");
1056 $mgr->editor->event(OpenILS::Event->new('ACQ_PROVIDER_INACTIVE'));
1060 my $po = Fieldmapper::acq::purchase_order->new;
1061 $po->creator($mgr->editor->requestor->id);
1062 $po->editor($mgr->editor->requestor->id);
1063 $po->owner($mgr->editor->requestor->id);
1064 $po->edit_time('now');
1065 $po->create_time('now');
1066 $po->state('pending');
1067 $po->ordering_agency($mgr->editor->requestor->ws_ou);
1068 $po->$_($args{$_}) for keys %args;
1070 $mgr->purchase_order($po);
1071 return $mgr->editor->create_acq_purchase_order($po);
1074 # ----------------------------------------------------------------------------
1075 # if all of the lineitems for this PO are received,
1076 # mark the PO as received
1077 # ----------------------------------------------------------------------------
1078 sub check_purchase_order_received {
1079 my($mgr, $po_id) = @_;
1081 my $non_recv_li = $mgr->editor->search_acq_lineitem(
1082 { purchase_order => $po_id,
1083 state => {'!=' => 'received'}
1086 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id);
1087 return $po if @$non_recv_li;
1089 $po->state('received');
1090 return update_purchase_order($mgr, $po);
1094 # ----------------------------------------------------------------------------
1095 # Bib, Callnumber, and Copy data
1096 # ----------------------------------------------------------------------------
1098 sub create_lineitem_assets {
1099 my($mgr, $li_id) = @_;
1102 my $li = $mgr->editor->retrieve_acq_lineitem([
1105 flesh_fields => {jub => ['purchase_order', 'attributes']}
1109 # note: at this point, the bib record this LI links to should already be created
1111 # -----------------------------------------------------------------
1112 # The lineitem is going live, promote user request holds to real holds
1113 # -----------------------------------------------------------------
1114 promote_lineitem_holds($mgr, $li) or return 0;
1116 my $li_details = $mgr->editor->search_acq_lineitem_detail({lineitem => $li_id}, {idlist=>1});
1118 # -----------------------------------------------------------------
1119 # for each lineitem_detail, create the volume if necessary, create
1120 # a copy, and link them all together.
1121 # -----------------------------------------------------------------
1123 for my $lid_id (@{$li_details}) {
1125 my $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid_id) or return 0;
1126 next if $lid->eg_copy_id;
1128 # use the same callnumber label for all items within this lineitem
1129 $lid->cn_label($first_cn) if $first_cn and not $lid->cn_label;
1131 # apply defaults if necessary
1132 return 0 unless complete_lineitem_detail($mgr, $lid);
1134 $first_cn = $lid->cn_label unless $first_cn;
1136 my $org = $lid->owning_lib;
1137 my $label = $lid->cn_label;
1138 my $bibid = $li->eg_bib_id;
1140 my $volume = $mgr->cache($org, "cn.$bibid.$label");
1142 $volume = create_volume($mgr, $li, $lid) or return 0;
1143 $mgr->cache($org, "cn.$bibid.$label", $volume);
1145 create_copy($mgr, $volume, $lid, $li) or return 0;
1148 return { li => $li };
1152 my($mgr, $li, $lid) = @_;
1154 my ($volume, $evt) =
1155 OpenILS::Application::Cat::AssetCommon->find_or_create_volume(
1163 $mgr->editor->event($evt);
1171 my($mgr, $volume, $lid, $li) = @_;
1172 my $copy = Fieldmapper::asset::copy->new;
1174 $copy->loan_duration(2);
1175 $copy->fine_level(2);
1176 $copy->status(($lid->recv_time) ? OILS_COPY_STATUS_IN_PROCESS : OILS_COPY_STATUS_ON_ORDER);
1177 $copy->barcode($lid->barcode);
1178 $copy->location($lid->location);
1179 $copy->call_number($volume->id);
1180 $copy->circ_lib($volume->owning_lib);
1181 $copy->circ_modifier($lid->circ_modifier);
1183 # AKA list price. We might need a $li->list_price field since
1184 # estimated price is not necessarily the same as list price
1185 $copy->price($li->estimated_unit_price);
1187 my $evt = OpenILS::Application::Cat::AssetCommon->create_copy($mgr->editor, $volume, $copy);
1189 $mgr->editor->event($evt);
1194 $lid->eg_copy_id($copy->id);
1195 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
1203 # ----------------------------------------------------------------------------
1204 # Workflow: Build a selection list from a Z39.50 search
1205 # ----------------------------------------------------------------------------
1207 __PACKAGE__->register_method(
1208 method => 'zsearch',
1209 api_name => 'open-ils.acq.picklist.search.z3950',
1212 desc => 'Performs a z3950 federated search and creates a picklist and associated lineitems',
1214 {desc => 'Authentication token', type => 'string'},
1215 {desc => 'Search definition', type => 'object'},
1216 {desc => 'Picklist name, optional', type => 'string'},
1222 my($self, $conn, $auth, $search, $name, $options) = @_;
1223 my $e = new_editor(authtoken=>$auth);
1224 return $e->event unless $e->checkauth;
1225 return $e->event unless $e->allowed('CREATE_PICKLIST');
1227 $search->{limit} ||= 10;
1230 my $ses = OpenSRF::AppSession->create('open-ils.search');
1231 my $req = $ses->request('open-ils.search.z3950.search_class', $auth, $search);
1236 while(my $resp = $req->recv(timeout=>60)) {
1239 my $e = new_editor(requestor=>$e->requestor, xact=>1);
1240 $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1241 $picklist = zsearch_build_pl($mgr, $name);
1245 my $result = $resp->content;
1246 my $count = $result->{count} || 0;
1247 $mgr->total( (($count < $search->{limit}) ? $count : $search->{limit})+1 );
1249 for my $rec (@{$result->{records}}) {
1251 my $li = create_lineitem($mgr,
1252 picklist => $picklist->id,
1253 source_label => $result->{service},
1254 marc => $rec->{marcxml},
1255 eg_bib_id => $rec->{bibid}
1258 if($$options{respond_li}) {
1259 $li->attributes($mgr->editor->search_acq_lineitem_attr({lineitem => $li->id}))
1260 if $$options{flesh_attrs};
1261 $li->clear_marc if $$options{clear_marc};
1262 $mgr->respond(lineitem => $li);
1269 $mgr->editor->commit;
1270 return $mgr->respond_complete;
1273 sub zsearch_build_pl {
1274 my($mgr, $name) = @_;
1277 my $picklist = $mgr->editor->search_acq_picklist({
1278 owner => $mgr->editor->requestor->id,
1282 if($name eq '' and $picklist) {
1283 return 0 unless delete_picklist($mgr, $picklist);
1287 return update_picklist($mgr, $picklist) if $picklist;
1288 return create_picklist($mgr, name => $name);
1292 # ----------------------------------------------------------------------------
1293 # Workflow: Build a selection list / PO by importing a batch of MARC records
1294 # ----------------------------------------------------------------------------
1296 __PACKAGE__->register_method(
1297 method => 'upload_records',
1298 api_name => 'open-ils.acq.process_upload_records',
1300 max_chunk_count => 1
1303 sub upload_records {
1304 my($self, $conn, $auth, $key, $args) = @_;
1307 my $e = new_editor(authtoken => $auth, xact => 1);
1308 return $e->die_event unless $e->checkauth;
1309 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1311 my $cache = OpenSRF::Utils::Cache->new;
1313 my $data = $cache->get_cache("vandelay_import_spool_$key");
1314 my $filename = $data->{path};
1315 my $provider = $args->{provider};
1316 my $picklist = $args->{picklist};
1317 my $create_po = $args->{create_po};
1318 my $activate_po = $args->{activate_po};
1319 my $ordering_agency = $args->{ordering_agency};
1320 my $vandelay = $args->{vandelay};
1324 unless(-r $filename) {
1325 $logger->error("unable to read MARC file $filename");
1327 return OpenILS::Event->new('FILE_UPLOAD_ERROR', payload => {filename => $filename});
1330 $provider = $e->retrieve_acq_provider($provider) or return $e->die_event;
1333 $picklist = $e->retrieve_acq_picklist($picklist) or return $e->die_event;
1334 if($picklist->owner != $e->requestor->id) {
1335 return $e->die_event unless
1336 $e->allowed('CREATE_PICKLIST', $picklist->org_unit, $picklist);
1338 $mgr->picklist($picklist);
1343 $po = create_purchase_order($mgr,
1344 ordering_agency => $ordering_agency,
1345 provider => $provider->id,
1347 ) or return $mgr->editor->die_event;
1350 $logger->info("acq processing MARC file=$filename");
1352 my $batch = new MARC::Batch ('USMARC', $filename);
1360 my ($err, $xml, $r);
1365 } catch Error with {
1367 $logger->warn("Proccessing of record $count in set $key failed with error $err. Skipping this record");
1374 $xml = clean_marc($r);
1375 } catch Error with {
1377 $logger->warn("Proccessing XML of record $count in set $key failed with error $err. Skipping this record");
1380 next if $err or not $xml;
1383 source_label => $provider->code,
1384 provider => $provider->id,
1388 $args{picklist} = $picklist->id if $picklist;
1390 $args{purchase_order} = $po->id;
1391 $args{state} = 'pending-order';
1394 my $li = create_lineitem($mgr, %args) or return $mgr->editor->die_event;
1396 $li->provider($provider); # flesh it, we'll need it later
1398 import_lineitem_details($mgr, $ordering_agency, $li) or return $mgr->editor->die_event;
1401 push(@li_list, $li->id);
1407 $cache->delete_cache('vandelay_import_spool_' . $key);
1409 if ($po and $activate_po) {
1410 my $die_event = activate_purchase_order_impl($mgr, $po->id, $vandelay);
1411 return $die_event if $die_event;
1413 } elsif ($vandelay) {
1414 create_lineitem_list_assets($mgr, \@li_list, $vandelay) or return $e->die_event;
1417 return $mgr->respond_complete;
1420 sub import_lineitem_details {
1421 my($mgr, $ordering_agency, $li) = @_;
1423 my $holdings = $mgr->editor->json_query({from => ['acq.extract_provider_holding_data', $li->id]});
1424 return 1 unless @$holdings;
1425 my $org_path = $U->get_org_ancestors($ordering_agency);
1426 $org_path = [ reverse (@$org_path) ];
1432 # create a lineitem detail for each copy in the data
1434 my $compiled = extract_lineitem_detail_data($mgr, $org_path, $holdings, $idx);
1435 last unless defined $compiled;
1436 return 0 unless $compiled;
1438 # this takes the price of the last copy and uses it as the lineitem price
1439 # need to determine if a given record would include different prices for the same item
1440 $price = $$compiled{estimated_price};
1442 last unless $$compiled{quantity};
1444 for(1..$$compiled{quantity}) {
1445 my $lid = create_lineitem_detail(
1447 lineitem => $li->id,
1448 owning_lib => $$compiled{owning_lib},
1449 cn_label => $$compiled{call_number},
1450 fund => $$compiled{fund},
1451 circ_modifier => $$compiled{circ_modifier},
1452 note => $$compiled{note},
1453 location => $$compiled{copy_location},
1454 collection_code => $$compiled{collection_code},
1455 barcode => $$compiled{barcode}
1463 $li->estimated_unit_price($price);
1464 update_lineitem($mgr, $li) or return 0;
1468 # return hash on success, 0 on error, undef on no more holdings
1469 sub extract_lineitem_detail_data {
1470 my($mgr, $org_path, $holdings, $index) = @_;
1472 my @data_list = grep { $_->{holding} eq $index } @$holdings;
1473 return undef unless @data_list;
1475 my %compiled = map { $_->{attr} => $_->{data} } @data_list;
1476 my $base_org = $$org_path[0];
1480 $logger->error("Item import extraction error: $msg");
1481 $logger->error('Holdings Data: ' . OpenSRF::Utils::JSON->perl2JSON(\%compiled));
1482 $mgr->editor->rollback;
1483 $mgr->editor->event(OpenILS::Event->new('ACQ_IMPORT_ERROR', payload => $msg));
1487 # ---------------------------------------------------------------------
1489 if(my $code = $compiled{fund_code}) {
1491 my $fund = $mgr->cache($base_org, "fund.$code");
1493 # search up the org tree for the most appropriate fund
1494 for my $org (@$org_path) {
1495 $fund = $mgr->editor->search_acq_fund(
1496 {org => $org, code => $code, year => DateTime->now->year}, {idlist => 1})->[0];
1500 return $killme->("no fund with code $code at orgs [@$org_path]") unless $fund;
1501 $compiled{fund} = $fund;
1502 $mgr->cache($base_org, "fund.$code", $fund);
1506 # ---------------------------------------------------------------------
1508 if(my $sn = $compiled{owning_lib}) {
1509 my $org_id = $mgr->cache($base_org, "orgsn.$sn") ||
1510 $mgr->editor->search_actor_org_unit({shortname => $sn}, {idlist => 1})->[0];
1511 return $killme->("invalid owning_lib defined: $sn") unless $org_id;
1512 $compiled{owning_lib} = $org_id;
1513 $mgr->cache($$org_path[0], "orgsn.$sn", $org_id);
1517 # ---------------------------------------------------------------------
1519 my $code = $compiled{circ_modifier};
1523 # verify this is a valid circ modifier
1524 return $killme->("invlalid circ_modifier $code") unless
1525 defined $mgr->cache($base_org, "mod.$code") or
1526 $mgr->editor->retrieve_config_circ_modifier($code);
1528 # if valid, cache for future tests
1529 $mgr->cache($base_org, "mod.$code", $code);
1532 $compiled{circ_modifier} = get_default_circ_modifier($mgr, $base_org);
1536 # ---------------------------------------------------------------------
1538 if( my $name = $compiled{copy_location}) {
1539 my $loc = $mgr->cache($base_org, "copy_loc.$name");
1541 for my $org (@$org_path) {
1542 $loc = $mgr->editor->search_asset_copy_location(
1543 {owning_lib => $org, name => $name}, {idlist => 1})->[0];
1547 return $killme->("Invalid copy location $name") unless $loc;
1548 $compiled{copy_location} = $loc;
1549 $mgr->cache($base_org, "copy_loc.$name", $loc);
1557 # ----------------------------------------------------------------------------
1558 # Workflow: Given an existing purchase order, import/create the bibs,
1559 # callnumber and copy objects
1560 # ----------------------------------------------------------------------------
1562 __PACKAGE__->register_method(
1563 method => 'create_po_assets',
1564 api_name => 'open-ils.acq.purchase_order.assets.create',
1566 desc => q/Creates assets for each lineitem in the purchase order/,
1568 {desc => 'Authentication token', type => 'string'},
1569 {desc => 'The purchase order id', type => 'number'},
1571 return => {desc => 'Streams a total versus completed counts object, event on error'}
1573 max_chunk_count => 1
1576 sub create_po_assets {
1577 my($self, $conn, $auth, $po_id, $args) = @_;
1580 my $e = new_editor(authtoken=>$auth, xact=>1);
1581 return $e->die_event unless $e->checkauth;
1582 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1584 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1586 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1588 # it's ugly, but it's fast. Get the total count of lineitem detail objects to process
1589 my $lid_total = $e->json_query({
1590 select => { acqlid => [{aggregate => 1, transform => 'count', column => 'id'}] },
1596 join => {acqpo => {fkey => 'purchase_order', field => 'id'}}
1600 where => {'+acqpo' => {id => $po_id}}
1603 $mgr->total(scalar(@$li_ids) + $lid_total);
1605 create_lineitem_list_assets($mgr, $li_ids, $args->{vandelay})
1606 or return $e->die_event;
1609 update_purchase_order($mgr, $po) or return $e->die_event;
1612 return $mgr->respond_complete;
1617 __PACKAGE__->register_method(
1618 method => 'create_purchase_order_api',
1619 api_name => 'open-ils.acq.purchase_order.create',
1621 desc => 'Creates a new purchase order',
1623 {desc => 'Authentication token', type => 'string'},
1624 {desc => 'purchase_order to create', type => 'object'}
1626 return => {desc => 'The purchase order id, Event on failure'}
1628 max_chunk_count => 1
1631 sub create_purchase_order_api {
1632 my($self, $conn, $auth, $po, $args) = @_;
1635 my $e = new_editor(xact=>1, authtoken=>$auth);
1636 return $e->die_event unless $e->checkauth;
1637 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
1638 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1641 my %pargs = (ordering_agency => $e->requestor->ws_ou); # default
1642 $pargs{provider} = $po->provider if $po->provider;
1643 $pargs{ordering_agency} = $po->ordering_agency if $po->ordering_agency;
1644 $pargs{prepayment_required} = $po->prepayment_required if $po->prepayment_required;
1645 my $vandelay = $args->{vandelay};
1647 $po = create_purchase_order($mgr, %pargs) or return $e->die_event;
1649 my $li_ids = $$args{lineitems};
1653 for my $li_id (@$li_ids) {
1655 my $li = $e->retrieve_acq_lineitem([
1657 {flesh => 1, flesh_fields => {jub => ['attributes']}}
1658 ]) or return $e->die_event;
1660 $li->provider($po->provider);
1661 $li->purchase_order($po->id);
1662 $li->state('pending-order');
1663 update_lineitem($mgr, $li) or return $e->die_event;
1668 # commit before starting the asset creation
1671 if($li_ids and $vandelay) {
1672 create_lineitem_list_assets($mgr, $li_ids, $vandelay) or return $e->die_event;
1675 return $mgr->respond_complete;
1680 __PACKAGE__->register_method(
1681 method => 'update_lineitem_fund_batch',
1682 api_name => 'open-ils.acq.lineitem.fund.update.batch',
1685 desc => q/Given a set of lineitem IDS, updates the fund for all attached lineitem details/
1689 sub update_lineitem_fund_batch {
1690 my($self, $conn, $auth, $li_ids, $fund_id) = @_;
1691 my $e = new_editor(xact=>1, authtoken=>$auth);
1692 return $e->die_event unless $e->checkauth;
1693 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1694 for my $li_id (@$li_ids) {
1695 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
1696 return $evt if $evt;
1697 my $li_details = $e->search_acq_lineitem_detail({lineitem => $li_id});
1698 $_->fund($fund_id) and $_->ischanged(1) for @$li_details;
1699 $evt = lineitem_detail_CUD_batch($mgr, $li_details);
1700 return $evt if $evt;
1705 return $mgr->respond_complete;
1710 __PACKAGE__->register_method(
1711 method => 'lineitem_detail_CUD_batch_api',
1712 api_name => 'open-ils.acq.lineitem_detail.cud.batch',
1715 desc => q/Creates a new purchase order line item detail. / .
1716 q/Additionally creates the associated fund_debit/,
1718 {desc => 'Authentication token', type => 'string'},
1719 {desc => 'List of lineitem_details to create', type => 'array'},
1720 {desc => 'Create Debits. Used for creating post-po-asset-creation debits', type => 'bool'},
1722 return => {desc => 'Streaming response of current position in the array'}
1726 __PACKAGE__->register_method(
1727 method => 'lineitem_detail_CUD_batch_api',
1728 api_name => 'open-ils.acq.lineitem_detail.cud.batch.dry_run',
1732 Dry run version of open-ils.acq.lineitem_detail.cud.batch.
1733 In dry_run mode, updated fund_debit's the exceed the warning
1734 percent return an event.
1740 sub lineitem_detail_CUD_batch_api {
1741 my($self, $conn, $auth, $li_details, $create_debits) = @_;
1742 my $e = new_editor(xact=>1, authtoken=>$auth);
1743 return $e->die_event unless $e->checkauth;
1744 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1745 my $dry_run = ($self->api_name =~ /dry_run/o);
1746 my $evt = lineitem_detail_CUD_batch($mgr, $li_details, $create_debits, $dry_run);
1747 return $evt if $evt;
1749 return $mgr->respond_complete;
1753 sub lineitem_detail_CUD_batch {
1754 my($mgr, $li_details, $create_debits, $dry_run) = @_;
1756 $mgr->total(scalar(@$li_details));
1757 my $e = $mgr->editor;
1761 my $fund_cache = {};
1764 for my $lid (@$li_details) {
1766 unless($li = $li_cache{$lid->lineitem}) {
1767 ($li, $evt) = fetch_and_check_li($e, $lid->lineitem, 'write');
1768 return $evt if $evt;
1772 $lid = create_lineitem_detail($mgr, %{$lid->to_bare_hash}) or return $e->die_event;
1773 if($create_debits) {
1774 $li->provider($e->retrieve_acq_provider($li->provider)) or return $e->die_event;
1775 $lid->fund($e->retrieve_acq_fund($lid->fund)) or return $e->die_event;
1776 create_lineitem_detail_debit($mgr, $li, $lid, 0, 1) or return $e->die_event;
1779 } elsif($lid->ischanged) {
1780 return $evt if $evt = handle_changed_lid($e, $lid, $dry_run, $fund_cache);
1782 } elsif($lid->isdeleted) {
1783 delete_lineitem_detail($mgr, $lid) or return $e->die_event;
1786 $mgr->respond(li => $li);
1787 $li_cache{$lid->lineitem} = $li;
1793 sub handle_changed_lid {
1794 my($e, $lid, $dry_run, $fund_cache) = @_;
1796 my $orig_lid = $e->retrieve_acq_lineitem_detail($lid->id) or return $e->die_event;
1798 # updating the fund, so update the debit
1799 if($orig_lid->fund_debit and $orig_lid->fund != $lid->fund) {
1801 my $debit = $e->retrieve_acq_fund_debit($orig_lid->fund_debit);
1802 my $new_fund = $$fund_cache{$lid->fund} =
1803 $$fund_cache{$lid->fund} || $e->retrieve_acq_fund($lid->fund);
1805 # check the thresholds
1806 return $e->die_event if
1807 fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "stop");
1808 return $e->die_event if $dry_run and
1809 fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "warning");
1811 $debit->fund($new_fund->id);
1812 $e->update_acq_fund_debit($debit) or return $e->die_event;
1815 $e->update_acq_lineitem_detail($lid) or return $e->die_event;
1820 __PACKAGE__->register_method(
1821 method => 'receive_po_api',
1822 api_name => 'open-ils.acq.purchase_order.receive'
1825 sub receive_po_api {
1826 my($self, $conn, $auth, $po_id) = @_;
1827 my $e = new_editor(xact => 1, authtoken => $auth);
1828 return $e->die_event unless $e->checkauth;
1829 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1831 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1832 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1834 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1836 for my $li_id (@$li_ids) {
1837 receive_lineitem($mgr, $li_id) or return $e->die_event;
1841 $po->state('received');
1842 update_purchase_order($mgr, $po) or return $e->die_event;
1845 return $mgr->respond_complete;
1849 # At the moment there's a lack of parallelism between the receive and unreceive
1850 # API methods for POs and the API methods for LIs and LIDs. The methods for
1851 # POs stream back objects as they act, whereas the methods for LIs and LIDs
1852 # atomically return an object that describes only what changed (in LIs and LIDs
1853 # themselves or in the objects to which to LIs and LIDs belong).
1855 # The methods for LIs and LIDs work the way they do to faciliate the UI's
1856 # maintaining correct information about the state of these things when a user
1857 # wants to receive or unreceive these objects without refreshing their whole
1858 # display. The UI feature for receiving and un-receiving a whole PO just
1859 # refreshes the whole display, so this absence of parallelism in the UI is also
1860 # relected in this module.
1862 # This could be neatened in the future by making POs receive and unreceive in
1863 # the same way the LIs and LIDs do.
1865 __PACKAGE__->register_method(
1866 method => 'receive_lineitem_detail_api',
1867 api_name => 'open-ils.acq.lineitem_detail.receive',
1869 desc => 'Mark a lineitem_detail as received',
1871 {desc => 'Authentication token', type => 'string'},
1872 {desc => 'lineitem detail ID', type => 'number'}
1875 "on success, object describing changes to LID and possibly " .
1876 "to LI and PO; on error, Event"
1881 sub receive_lineitem_detail_api {
1882 my($self, $conn, $auth, $lid_id) = @_;
1884 my $e = new_editor(xact=>1, authtoken=>$auth);
1885 return $e->die_event unless $e->checkauth;
1886 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1889 "flesh" => 2, "flesh_fields" => {
1890 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
1894 my $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1896 return $e->die_event unless $e->allowed(
1897 'RECEIVE_PURCHASE_ORDER', $lid->lineitem->purchase_order->ordering_agency);
1900 my $recvd = receive_lineitem_detail($mgr, $lid_id) or return $e->die_event;
1902 # .. and re-retrieve
1903 $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1905 # Now build result data structure.
1906 my $result = {"lid" => {$lid->id => {"recv_time" => $lid->recv_time}}};
1909 if ($recvd->class_name =~ /::purchase_order/) {
1910 $result->{"po"} = describe_affected_po($e, $recvd);
1912 $lid->lineitem->id => {"state" => $lid->lineitem->state}
1914 } elsif ($recvd->class_name =~ /::lineitem/) {
1915 $result->{"li"} = {$recvd->id => {"state" => $recvd->state}};
1919 describe_affected_po($e, $lid->lineitem->purchase_order);
1925 __PACKAGE__->register_method(
1926 method => 'receive_lineitem_api',
1927 api_name => 'open-ils.acq.lineitem.receive',
1929 desc => 'Mark a lineitem as received',
1931 {desc => 'Authentication token', type => 'string'},
1932 {desc => 'lineitem ID', type => 'number'}
1935 "on success, object describing changes to LI and possibly PO; " .
1941 sub receive_lineitem_api {
1942 my($self, $conn, $auth, $li_id) = @_;
1944 my $e = new_editor(xact=>1, authtoken=>$auth);
1945 return $e->die_event unless $e->checkauth;
1946 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1948 my $li = $e->retrieve_acq_lineitem([
1952 jub => ['purchase_order']
1955 ]) or return $e->die_event;
1957 return $e->die_event unless $e->allowed(
1958 'RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);
1960 my $res = receive_lineitem($mgr, $li_id) or return $e->die_event;
1962 $conn->respond_complete($res);
1963 $mgr->run_post_response_hooks
1967 __PACKAGE__->register_method(
1968 method => 'rollback_receive_po_api',
1969 api_name => 'open-ils.acq.purchase_order.receive.rollback'
1972 sub rollback_receive_po_api {
1973 my($self, $conn, $auth, $po_id) = @_;
1974 my $e = new_editor(xact => 1, authtoken => $auth);
1975 return $e->die_event unless $e->checkauth;
1976 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1978 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1979 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1981 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1983 for my $li_id (@$li_ids) {
1984 rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
1988 $po->state('on-order');
1989 update_purchase_order($mgr, $po) or return $e->die_event;
1992 return $mgr->respond_complete;
1996 __PACKAGE__->register_method(
1997 method => 'rollback_receive_lineitem_detail_api',
1998 api_name => 'open-ils.acq.lineitem_detail.receive.rollback',
2000 desc => 'Mark a lineitem_detail as Un-received',
2002 {desc => 'Authentication token', type => 'string'},
2003 {desc => 'lineitem detail ID', type => 'number'}
2006 "on success, object describing changes to LID and possibly " .
2007 "to LI and PO; on error, Event"
2012 sub rollback_receive_lineitem_detail_api {
2013 my($self, $conn, $auth, $lid_id) = @_;
2015 my $e = new_editor(xact=>1, authtoken=>$auth);
2016 return $e->die_event unless $e->checkauth;
2017 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2019 my $lid = $e->retrieve_acq_lineitem_detail([
2023 acqlid => ['lineitem'],
2024 jub => ['purchase_order']
2028 my $li = $lid->lineitem;
2029 my $po = $li->purchase_order;
2031 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2035 my $recvd = rollback_receive_lineitem_detail($mgr, $lid_id)
2036 or return $e->die_event;
2039 $result->{"lid"} = {$recvd->id => {"recv_time" => $recvd->recv_time}};
2041 $result->{"lid"} = {$lid->id => {"recv_time" => $lid->recv_time}};
2044 if ($li->state eq "received") {
2045 $li->state("on-order");
2046 $li = update_lineitem($mgr, $li) or return $e->die_event;
2047 $result->{"li"} = {$li->id => {"state" => $li->state}};
2050 if ($po->state eq "received") {
2051 $po->state("on-order");
2052 $po = update_purchase_order($mgr, $po) or return $e->die_event;
2054 $result->{"po"} = describe_affected_po($e, $po);
2056 $e->commit and return $result or return $e->die_event;
2059 __PACKAGE__->register_method(
2060 method => 'rollback_receive_lineitem_api',
2061 api_name => 'open-ils.acq.lineitem.receive.rollback',
2063 desc => 'Mark a lineitem as Un-received',
2065 {desc => 'Authentication token', type => 'string'},
2066 {desc => 'lineitem ID', type => 'number'}
2069 "on success, object describing changes to LI and possibly PO; " .
2075 sub rollback_receive_lineitem_api {
2076 my($self, $conn, $auth, $li_id) = @_;
2078 my $e = new_editor(xact=>1, authtoken=>$auth);
2079 return $e->die_event unless $e->checkauth;
2080 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2082 my $li = $e->retrieve_acq_lineitem([
2084 "flesh" => 1, "flesh_fields" => {"jub" => ["purchase_order"]}
2087 my $po = $li->purchase_order;
2089 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2091 $li = rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
2093 my $result = {"li" => {$li->id => {"state" => $li->state}}};
2094 if ($po->state eq "received") {
2095 $po->state("on-order");
2096 $po = update_purchase_order($mgr, $po) or return $e->die_event;
2098 $result->{"po"} = describe_affected_po($e, $po);
2100 $e->commit and return $result or return $e->die_event;
2104 __PACKAGE__->register_method(
2105 method => 'set_lineitem_price_api',
2106 api_name => 'open-ils.acq.lineitem.price.set',
2108 desc => 'Set lineitem price. If debits already exist, update them as well',
2110 {desc => 'Authentication token', type => 'string'},
2111 {desc => 'lineitem ID', type => 'number'}
2113 return => {desc => 'status blob, Event on error'}
2117 sub set_lineitem_price_api {
2118 my($self, $conn, $auth, $li_id, $price) = @_;
2120 my $e = new_editor(xact=>1, authtoken=>$auth);
2121 return $e->die_event unless $e->checkauth;
2122 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2124 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
2125 return $evt if $evt;
2127 $li->estimated_unit_price($price);
2128 update_lineitem($mgr, $li) or return $e->die_event;
2130 my $lid_ids = $e->search_acq_lineitem_detail(
2131 {lineitem => $li_id, fund_debit => {'!=' => undef}},
2135 for my $lid_id (@$lid_ids) {
2137 my $lid = $e->retrieve_acq_lineitem_detail([
2139 flesh => 1, flesh_fields => {acqlid => ['fund', 'fund_debit']}}
2142 $lid->fund_debit->amount($price);
2143 $e->update_acq_fund_debit($lid->fund_debit) or return $e->die_event;
2149 return $mgr->respond_complete;
2153 __PACKAGE__->register_method(
2154 method => 'clone_picklist_api',
2155 api_name => 'open-ils.acq.picklist.clone',
2157 desc => 'Clones a picklist, including lineitem and lineitem details',
2159 {desc => 'Authentication token', type => 'string'},
2160 {desc => 'Picklist ID', type => 'number'},
2161 {desc => 'New Picklist Name', type => 'string'}
2163 return => {desc => 'status blob, Event on error'}
2167 sub clone_picklist_api {
2168 my($self, $conn, $auth, $pl_id, $name) = @_;
2170 my $e = new_editor(xact=>1, authtoken=>$auth);
2171 return $e->die_event unless $e->checkauth;
2172 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2174 my $old_pl = $e->retrieve_acq_picklist($pl_id);
2175 my $new_pl = create_picklist($mgr, %{$old_pl->to_bare_hash}, name => $name) or return $e->die_event;
2177 my $li_ids = $e->search_acq_lineitem({picklist => $pl_id}, {idlist => 1});
2179 for my $li_id (@$li_ids) {
2181 # copy the lineitems
2182 my $li = $e->retrieve_acq_lineitem($li_id);
2183 my $new_li = create_lineitem($mgr, %{$li->to_bare_hash}, picklist => $new_pl->id) or return $e->die_event;
2185 my $lid_ids = $e->search_acq_lineitem_detail({lineitem => $li_id}, {idlist => 1});
2186 for my $lid_id (@$lid_ids) {
2188 # copy the lineitem details
2189 my $lid = $e->retrieve_acq_lineitem_detail($lid_id);
2190 create_lineitem_detail($mgr, %{$lid->to_bare_hash}, lineitem => $new_li->id) or return $e->die_event;
2197 return $mgr->respond_complete;
2201 __PACKAGE__->register_method(
2202 method => 'merge_picklist_api',
2203 api_name => 'open-ils.acq.picklist.merge',
2205 desc => 'Merges 2 or more picklists into a single list',
2207 {desc => 'Authentication token', type => 'string'},
2208 {desc => 'Lead Picklist ID', type => 'number'},
2209 {desc => 'List of subordinate picklist IDs', type => 'array'}
2211 return => {desc => 'status blob, Event on error'}
2215 sub merge_picklist_api {
2216 my($self, $conn, $auth, $lead_pl, $pl_list) = @_;
2218 my $e = new_editor(xact=>1, authtoken=>$auth);
2219 return $e->die_event unless $e->checkauth;
2220 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2222 # XXX perms on each picklist modified
2224 $lead_pl = $e->retrieve_acq_picklist($lead_pl) or return $e->die_event;
2225 # point all of the lineitems at the lead picklist
2226 my $li_ids = $e->search_acq_lineitem({picklist => $pl_list}, {idlist => 1});
2228 for my $li_id (@$li_ids) {
2229 my $li = $e->retrieve_acq_lineitem($li_id);
2230 $li->picklist($lead_pl);
2231 update_lineitem($mgr, $li) or return $e->die_event;
2235 # now delete the subordinate lists
2236 for my $pl_id (@$pl_list) {
2237 my $pl = $e->retrieve_acq_picklist($pl_id);
2238 $e->delete_acq_picklist($pl) or return $e->die_event;
2241 update_picklist($mgr, $lead_pl) or return $e->die_event;
2244 return $mgr->respond_complete;
2248 __PACKAGE__->register_method(
2249 method => 'delete_picklist_api',
2250 api_name => 'open-ils.acq.picklist.delete',
2252 desc => q/Deletes a picklist. It also deletes any lineitems in the "new" state. / .
2253 q/Other attached lineitems are detached/,
2255 {desc => 'Authentication token', type => 'string'},
2256 {desc => 'Picklist ID to delete', type => 'number'}
2258 return => {desc => '1 on success, Event on error'}
2262 sub delete_picklist_api {
2263 my($self, $conn, $auth, $picklist_id) = @_;
2264 my $e = new_editor(xact=>1, authtoken=>$auth);
2265 return $e->die_event unless $e->checkauth;
2266 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2267 my $pl = $e->retrieve_acq_picklist($picklist_id) or return $e->die_event;
2268 delete_picklist($mgr, $pl) or return $e->die_event;
2270 return $mgr->respond_complete;
2275 __PACKAGE__->register_method(
2276 method => 'activate_purchase_order',
2277 api_name => 'open-ils.acq.purchase_order.activate.dry_run'
2280 __PACKAGE__->register_method(
2281 method => 'activate_purchase_order',
2282 api_name => 'open-ils.acq.purchase_order.activate',
2284 desc => q/Activates a purchase order. This updates the status of the PO / .
2285 q/and Lineitems to 'on-order'. Activated PO's are ready for EDI delivery if appropriate./,
2287 {desc => 'Authentication token', type => 'string'},
2288 {desc => 'Purchase ID', type => 'number'}
2290 return => {desc => '1 on success, Event on error'}
2294 sub activate_purchase_order {
2295 my($self, $conn, $auth, $po_id, $vandelay) = @_;
2297 my $dry_run = ($self->api_name =~ /\.dry_run/) ? 1 : 0;
2298 my $e = new_editor(authtoken=>$auth);
2299 return $e->die_event unless $e->checkauth;
2300 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2301 my $die_event = activate_purchase_order_impl($mgr, $po_id, $vandelay, $dry_run);
2302 return $e->die_event if $die_event;
2303 $conn->respond_complete(1);
2304 $mgr->run_post_response_hooks unless $dry_run;
2308 # xacts managed within
2309 sub activate_purchase_order_impl {
2310 my ($mgr, $po_id, $vandelay, $dry_run) = @_;
2312 # read-only until lineitem asset creation
2313 my $e = $mgr->editor;
2316 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2317 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
2318 my $provider = $e->retrieve_acq_provider($po->provider);
2320 # find lineitems and create assets for all
2323 purchase_order => $po_id,
2324 state => [qw/pending-order new order-ready/]
2327 my $li_ids = $e->search_acq_lineitem($query, {idlist => 1});
2329 my $vl_resp; # imported li's and the queue the managing queue
2331 $e->rollback; # read-only thus far
2332 $vl_resp = create_lineitem_list_assets($mgr, $li_ids, $vandelay)
2333 or return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED');
2337 # create fund debits for lineitems
2339 for my $li_id (@$li_ids) {
2340 my $li = $e->retrieve_acq_lineitem($li_id);
2342 if (!$li->eg_bib_id and !$dry_run) {
2343 # we encountered a lineitem that was not successfully imported.
2344 # we cannot continue. rollback and report.
2346 return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED', {queue => $vl_resp->{queue}});
2349 $li->state('on-order');
2350 $li->claim_policy($provider->default_claim_policy)
2351 if $provider->default_claim_policy and !$li->claim_policy;
2352 create_lineitem_debits($mgr, $li, $dry_run) or return $e->die_event;
2353 update_lineitem($mgr, $li) or return $e->die_event;
2354 $mgr->post_process( sub { create_lineitem_status_events($mgr, $li->id, 'aur.ordered'); });
2358 # create po-item debits
2360 for my $po_item (@{$e->search_acq_po_item({purchase_order => $po_id})}) {
2362 my $debit = create_fund_debit(
2365 debit_type => 'direct_charge', # to match invoicing
2366 origin_amount => $po_item->estimated_cost,
2367 origin_currency_type => $e->retrieve_acq_fund($po_item->fund)->currency_type,
2368 amount => $po_item->estimated_cost,
2369 fund => $po_item->fund
2370 ) or return $e->die_event;
2371 $po_item->fund_debit($debit->id);
2372 $e->update_acq_po_item($po_item) or return $e->die_event;
2376 # mark PO as ordered
2378 $po->state('on-order');
2379 $po->order_date('now');
2380 update_purchase_order($mgr, $po) or return $e->die_event;
2383 $dry_run and $e->rollback or $e->commit;
2385 # tell the world we activated a PO
2386 $U->create_events_for_hook('acqpo.activated', $po, $po->ordering_agency) unless $dry_run;
2392 __PACKAGE__->register_method(
2393 method => 'split_purchase_order_by_lineitems',
2394 api_name => 'open-ils.acq.purchase_order.split_by_lineitems',
2396 desc => q/Splits a PO into many POs, 1 per lineitem. Only works for / .
2397 q/POs a) with more than one lineitems, and b) in the "pending" state./,
2399 {desc => 'Authentication token', type => 'string'},
2400 {desc => 'Purchase order ID', type => 'number'}
2402 return => {desc => 'list of new PO IDs on success, Event on error'}
2406 sub split_purchase_order_by_lineitems {
2407 my ($self, $conn, $auth, $po_id) = @_;
2409 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2410 return $e->die_event unless $e->checkauth;
2412 my $po = $e->retrieve_acq_purchase_order([
2415 "flesh_fields" => {"acqpo" => [qw/lineitems notes/]}
2417 ]) or return $e->die_event;
2419 return $e->die_event
2420 unless $e->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2422 unless ($po->state eq "pending") {
2424 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_LATE");
2427 unless (@{$po->lineitems} > 1) {
2429 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_SHORT");
2432 # To split an existing PO into many, it seems unwise to just delete the
2433 # original PO, so we'll instead detach all of the original POs' lineitems
2434 # but the first, then create new POs for each of the remaining LIs, and
2435 # then attach the LIs to their new POs.
2437 my @po_ids = ($po->id);
2438 my @moving_li = @{$po->lineitems};
2439 shift @moving_li; # discard first LI
2441 foreach my $li (@moving_li) {
2442 my $new_po = $po->clone;
2444 $new_po->clear_name;
2445 $new_po->creator($e->requestor->id);
2446 $new_po->editor($e->requestor->id);
2447 $new_po->owner($e->requestor->id);
2448 $new_po->edit_time("now");
2449 $new_po->create_time("now");
2451 $new_po = $e->create_acq_purchase_order($new_po);
2453 # Clone any notes attached to the old PO and attach to the new one.
2454 foreach my $note (@{$po->notes}) {
2455 my $new_note = $note->clone;
2456 $new_note->clear_id;
2457 $new_note->edit_time("now");
2458 $new_note->purchase_order($new_po->id);
2459 $e->create_acq_po_note($new_note);
2462 $li->edit_time("now");
2463 $li->purchase_order($new_po->id);
2464 $e->update_acq_lineitem($li);
2466 push @po_ids, $new_po->id;
2469 $po->edit_time("now");
2470 $e->update_acq_purchase_order($po);
2472 return \@po_ids if $e->commit;
2473 return $e->die_event;
2477 sub not_cancelable {
2479 (ref $o eq "HASH" and $o->{"textcode"} eq "ACQ_NOT_CANCELABLE");
2482 __PACKAGE__->register_method(
2483 method => "cancel_purchase_order_api",
2484 api_name => "open-ils.acq.purchase_order.cancel",
2486 desc => q/Cancels an on-order purchase order/,
2488 {desc => "Authentication token", type => "string"},
2489 {desc => "PO ID to cancel", type => "number"},
2490 {desc => "Cancel reason ID", type => "number"}
2492 return => {desc => q/Object describing changed POs, LIs and LIDs
2493 on success; Event on error./}
2497 sub cancel_purchase_order_api {
2498 my ($self, $conn, $auth, $po_id, $cancel_reason) = @_;
2500 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2501 return $e->die_event unless $e->checkauth;
2502 my $mgr = new OpenILS::Application::Acq::BatchManager(
2503 "editor" => $e, "conn" => $conn
2506 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2507 return new OpenILS::Event(
2508 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2511 my $result = cancel_purchase_order($mgr, $po_id, $cancel_reason) or
2512 return $e->die_event;
2513 if (not_cancelable($result)) { # event not from CStoreEditor
2516 } elsif ($result == -1) {
2518 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2521 $e->commit or return $e->die_event;
2523 # XXX create purchase order status events?
2525 if ($mgr->{post_commit}) {
2526 foreach my $func (@{$mgr->{post_commit}}) {
2534 sub cancel_purchase_order {
2535 my ($mgr, $po_id, $cancel_reason) = @_;
2537 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id) or return 0;
2539 # XXX is "cancelled" a typo? It's not correct US spelling, anyway.
2540 # Depending on context, this may not warrant an event.
2541 return -1 if $po->state eq "cancelled";
2543 # But this always does.
2544 return new OpenILS::Event(
2545 "ACQ_NOT_CANCELABLE", "note" => "purchase_order $po_id"
2546 ) unless ($po->state eq "on-order" or $po->state eq "pending");
2549 $mgr->editor->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2551 $po->state("cancelled");
2552 $po->cancel_reason($cancel_reason->id);
2554 my $li_ids = $mgr->editor->search_acq_lineitem(
2555 {"purchase_order" => $po_id}, {"idlist" => 1}
2558 my $result = {"li" => {}, "lid" => {}};
2559 foreach my $li_id (@$li_ids) {
2560 my $li_result = cancel_lineitem($mgr, $li_id, $cancel_reason)
2563 next if $li_result == -1; # already canceled:skip.
2564 return $li_result if not_cancelable($li_result); # not cancelable:stop.
2566 # Merge in each LI result (there's only going to be
2567 # one per call to cancel_lineitem).
2568 my ($k, $v) = each %{$li_result->{"li"}};
2569 $result->{"li"}->{$k} = $v;
2571 # Merge in each LID result (there may be many per call to
2573 while (($k, $v) = each %{$li_result->{"lid"}}) {
2574 $result->{"lid"}->{$k} = $v;
2578 # TODO who/what/where/how do we indicate this change for electronic orders?
2579 # TODO return changes to encumbered/spent
2580 # TODO maybe cascade up from smaller object to container object if last
2581 # smaller object in the container has been canceled?
2583 update_purchase_order($mgr, $po) or return 0;
2585 $po_id => {"state" => $po->state, "cancel_reason" => $cancel_reason}
2591 __PACKAGE__->register_method(
2592 method => "cancel_lineitem_api",
2593 api_name => "open-ils.acq.lineitem.cancel",
2595 desc => q/Cancels an on-order lineitem/,
2597 {desc => "Authentication token", type => "string"},
2598 {desc => "Lineitem ID to cancel", type => "number"},
2599 {desc => "Cancel reason ID", type => "number"}
2601 return => {desc => q/Object describing changed LIs and LIDs on success;
2606 __PACKAGE__->register_method(
2607 method => "cancel_lineitem_api",
2608 api_name => "open-ils.acq.lineitem.cancel.batch",
2610 desc => q/Batched version of open-ils.acq.lineitem.cancel/,
2611 return => {desc => q/Object describing changed LIs and LIDs on success;
2616 sub cancel_lineitem_api {
2617 my ($self, $conn, $auth, $li_id, $cancel_reason) = @_;
2619 my $batched = $self->api_name =~ /\.batch/;
2621 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2622 return $e->die_event unless $e->checkauth;
2623 my $mgr = new OpenILS::Application::Acq::BatchManager(
2624 "editor" => $e, "conn" => $conn
2627 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2628 return new OpenILS::Event(
2629 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2632 my ($result, $maybe_event);
2635 $result = {"li" => {}, "lid" => {}};
2636 foreach my $one_li_id (@$li_id) {
2637 my $one = cancel_lineitem($mgr, $one_li_id, $cancel_reason) or
2638 return $e->die_event;
2639 if (not_cancelable($one)) {
2640 $maybe_event = $one;
2641 } elsif ($result == -1) {
2642 $maybe_event = new OpenILS::Event("ACQ_ALREADY_CANCELED");
2646 while (($k, $v) = each %{$one->{"li"}}) {
2647 $result->{"li"}->{$k} = $v;
2650 if ($one->{"lid"}) {
2651 while (($k, $v) = each %{$one->{"lid"}}) {
2652 $result->{"lid"}->{$k} = $v;
2658 $result = cancel_lineitem($mgr, $li_id, $cancel_reason) or
2659 return $e->die_event;
2661 if (not_cancelable($result)) {
2664 } elsif ($result == -1) {
2666 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2670 if ($batched and not scalar keys %{$result->{"li"}}) {
2672 return $maybe_event;
2674 $e->commit or return $e->die_event;
2675 # create_lineitem_status_events should handle array li_id ok
2676 create_lineitem_status_events($mgr, $li_id, "aur.cancelled");
2678 if ($mgr->{post_commit}) {
2679 foreach my $func (@{$mgr->{post_commit}}) {
2688 sub cancel_lineitem {
2689 my ($mgr, $li_id, $cancel_reason) = @_;
2690 my $li = $mgr->editor->retrieve_acq_lineitem([
2691 $li_id, {flesh => 1, flesh_fields => {jub => ['purchase_order']}}
2694 return 0 unless $mgr->editor->allowed(
2695 "CREATE_PURCHASE_ORDER", $li->purchase_order->ordering_agency
2698 # Depending on context, this may not warrant an event.
2699 return -1 if $li->state eq "cancelled";
2701 # But this always does.
2702 return new OpenILS::Event(
2703 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id"
2705 (! $li->purchase_order) or (
2706 $li->purchase_order and (
2707 $li->state eq "on-order" or $li->state eq "pending-order"
2712 $li->state("cancelled");
2713 $li->cancel_reason($cancel_reason->id);
2715 my $lids = $mgr->editor->search_acq_lineitem_detail([{
2716 "lineitem" => $li_id
2719 flesh_fields => { acqlid => ['eg_copy_id'] }
2722 my $result = {"lid" => {}};
2724 foreach my $lid (@$lids) {
2725 my $lid_result = cancel_lineitem_detail($mgr, $lid->id, $cancel_reason)
2728 # gathering any real copies for deletion
2729 if ($lid->eg_copy_id) {
2730 $lid->eg_copy_id->isdeleted('t');
2731 push @$copies, $lid->eg_copy_id;
2734 next if $lid_result == -1; # already canceled: just skip it.
2735 return $lid_result if not_cancelable($lid_result); # not cxlable: stop.
2737 # Merge in each LID result (there's only going to be one per call to
2738 # cancel_lineitem_detail).
2739 my ($k, $v) = each %{$lid_result->{"lid"}};
2740 $result->{"lid"}->{$k} = $v;
2743 # Attempt to delete the gathered copies (this will also handle volume deletion and bib deletion)
2744 # Delete empty bibs according org unit setting
2745 my $force_delete_empty_bib = $U->ou_ancestor_setting_value(
2746 $mgr->editor->requestor->ws_ou, 'cat.bib.delete_on_no_copy_via_acq_lineitem_cancel', $mgr->editor);
2747 if (scalar(@$copies)>0) {
2749 my $delete_stats = undef;
2750 my $retarget_holds = [];
2751 my $cat_evt = OpenILS::Application::Cat::AssetCommon->update_fleshed_copies(
2752 $mgr->editor, $override, undef, $copies, $delete_stats, $retarget_holds,$force_delete_empty_bib);
2755 $logger->info("fleshed copy update failed with event: ".OpenSRF::Utils::JSON->perl2JSON($cat_evt));
2756 return new OpenILS::Event(
2757 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id", "payload" => $cat_evt
2761 # We can't do the following and stay within the same transaction, but that's okay, the hold targeter will pick these up later.
2762 #my $ses = OpenSRF::AppSession->create('open-ils.circ');
2763 #$ses->request('open-ils.circ.hold.reset.batch', $auth, $retarget_holds);
2766 # if we have a bib, check to see whether it has been deleted. if so, cancel any active holds targeting that bib
2767 if ($li->eg_bib_id) {
2768 my $bib = $mgr->editor->retrieve_biblio_record_entry($li->eg_bib_id) or return new OpenILS::Event(
2769 "ACQ_NOT_CANCELABLE", "note" => "Could not retrieve bib " . $li->eg_bib_id . " for lineitem $li_id"
2771 if ($U->is_true($bib->deleted)) {
2772 my $holds = $mgr->editor->search_action_hold_request(
2773 { cancel_time => undef,
2774 fulfillment_time => undef,
2775 target => $li->eg_bib_id
2779 my %cached_usr_home_ou = ();
2781 for my $hold (@$holds) {
2783 $logger->info("Cancelling hold ".$hold->id.
2784 " due to acq lineitem cancellation.");
2786 $hold->cancel_time('now');
2787 $hold->cancel_cause(5); # 'Staff forced'--we may want a new hold cancel cause reason for this
2788 $hold->cancel_note('Corresponding Acquistion Lineitem/Purchase Order was cancelled.');
2789 unless($mgr->editor->update_action_hold_request($hold)) {
2790 my $evt = $mgr->editor->event;
2791 $logger->error("Error updating hold ". $evt->textcode .":". $evt->desc .":". $evt->stacktrace);
2792 return new OpenILS::Event(
2793 "ACQ_NOT_CANCELABLE", "note" => "Could not cancel hold " . $hold->id . " for lineitem $li_id", "payload" => $evt
2796 if (! defined $mgr->{post_commit}) { # we need a mechanism for creating trigger events, but only if the transaction gets committed
2797 $mgr->{post_commit} = [];
2799 push @{ $mgr->{post_commit} }, sub {
2800 my $home_ou = $cached_usr_home_ou{$hold->usr};
2802 my $user = $mgr->editor->retrieve_actor_user($hold->usr); # FIXME: how do we want to handle failures here?
2803 $home_ou = $user->home_ou;
2804 $cached_usr_home_ou{$hold->usr} = $home_ou;
2806 $U->create_events_for_hook('hold_request.cancel.cancelled_order', $hold, $home_ou);
2812 update_lineitem($mgr, $li) or return 0;
2815 "state" => $li->state,
2816 "cancel_reason" => $cancel_reason
2823 __PACKAGE__->register_method(
2824 method => "cancel_lineitem_detail_api",
2825 api_name => "open-ils.acq.lineitem_detail.cancel",
2827 desc => q/Cancels an on-order lineitem detail/,
2829 {desc => "Authentication token", type => "string"},
2830 {desc => "Lineitem detail ID to cancel", type => "number"},
2831 {desc => "Cancel reason ID", type => "number"}
2833 return => {desc => q/Object describing changed LIDs on success;
2838 sub cancel_lineitem_detail_api {
2839 my ($self, $conn, $auth, $lid_id, $cancel_reason) = @_;
2841 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2842 return $e->die_event unless $e->checkauth;
2843 my $mgr = new OpenILS::Application::Acq::BatchManager(
2844 "editor" => $e, "conn" => $conn
2847 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2848 return new OpenILS::Event(
2849 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2852 my $result = cancel_lineitem_detail($mgr, $lid_id, $cancel_reason) or
2853 return $e->die_event;
2855 if (not_cancelable($result)) {
2858 } elsif ($result == -1) {
2860 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2863 $e->commit or return $e->die_event;
2865 # XXX create lineitem detail status events?
2869 sub cancel_lineitem_detail {
2870 my ($mgr, $lid_id, $cancel_reason) = @_;
2871 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
2875 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
2880 # Depending on context, this may not warrant an event.
2881 return -1 if $lid->cancel_reason;
2883 # But this always does.
2884 return new OpenILS::Event(
2885 "ACQ_NOT_CANCELABLE", "note" => "lineitem_detail $lid_id"
2887 (! $lid->lineitem->purchase_order) or
2889 (not $lid->recv_time) and
2891 $lid->lineitem->purchase_order and (
2892 $lid->lineitem->state eq "on-order" or
2893 $lid->lineitem->state eq "pending-order"
2898 return 0 unless $mgr->editor->allowed(
2899 "CREATE_PURCHASE_ORDER",
2900 $lid->lineitem->purchase_order->ordering_agency
2901 ) or (! $lid->lineitem->purchase_order);
2903 $lid->cancel_reason($cancel_reason->id);
2905 unless($U->is_true($cancel_reason->keep_debits)) {
2906 my $debit_id = $lid->fund_debit;
2907 $lid->clear_fund_debit;
2910 # item is cancelled. Remove the fund debit.
2911 my $debit = $mgr->editor->retrieve_acq_fund_debit($debit_id);
2912 if (!$U->is_true($debit->encumbrance)) {
2913 $mgr->editor->rollback;
2914 return OpenILS::Event->new('ACQ_NOT_CANCELABLE',
2915 note => "Debit is marked as paid: $debit_id");
2917 $mgr->editor->delete_acq_fund_debit($debit) or return $mgr->editor->die_event;
2921 # XXX LIDs don't have either an editor or a edit_time field. Should we
2922 # update these on the LI when we alter an LID?
2923 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
2925 return {"lid" => {$lid_id => {"cancel_reason" => $cancel_reason}}};
2929 __PACKAGE__->register_method(
2930 method => 'user_requests',
2931 api_name => 'open-ils.acq.user_request.retrieve.by_user_id',
2934 desc => 'Retrieve fleshed user requests and related data for a given user.',
2936 { desc => 'Authentication token', type => 'string' },
2937 { desc => 'User ID of the owner, or array of IDs', },
2938 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
2943 desc => 'Fleshed user requests and related data',
2949 __PACKAGE__->register_method(
2950 method => 'user_requests',
2951 api_name => 'open-ils.acq.user_request.retrieve.by_home_ou',
2954 desc => 'Retrieve fleshed user requests and related data for a given org unit or units.',
2956 { desc => 'Authentication token', type => 'string' },
2957 { desc => 'Org unit ID, or array of IDs', },
2958 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
2963 desc => 'Fleshed user requests and related data',
2970 my($self, $conn, $auth, $search_value, $options) = @_;
2971 my $e = new_editor(authtoken => $auth);
2972 return $e->event unless $e->checkauth;
2973 my $rid = $e->requestor->id;
2977 "select"=>{"aur"=>["id"],"au"=>["home_ou", {column => 'id', alias => 'usr_id'} ]},
2978 "from"=>{ "aur" => { "au" => {}, "jub" => { "type" => "left" } } },
2982 {"id"=>undef}, # this with the left-join pulls in requests without lineitems
2983 {"state"=>["new","on-order","pending-order"]} # FIXME - probably needs softcoding
2987 "order_by"=>[{"class"=>"aur", "field"=>"request_date", "direction"=>"desc"}]
2990 foreach (qw/ order_by limit offset /) {
2991 $query->{$_} = $options->{$_} if defined $options->{$_};
2993 if (defined $options->{'state'}) {
2994 $query->{'where'}->{'+jub'}->{'-or'}->[1]->{'state'} = $options->{'state'};
2997 if ($self->api_name =~ /by_user_id/) {
2998 $query->{'where'}->{'usr'} = $search_value;
3000 $query->{'where'}->{'+au'} = { 'home_ou' => $search_value };
3003 my $pertinent_ids = $e->json_query($query);
3006 for my $id_blob (@$pertinent_ids) {
3007 if ($rid != $id_blob->{usr_id}) {
3008 if (!defined $perm_test{ $id_blob->{home_ou} }) {
3009 $perm_test{ $id_blob->{home_ou} } = $e->allowed( ['user_request.view'], $id_blob->{home_ou} );
3011 if (!$perm_test{ $id_blob->{home_ou} }) {
3015 my $aur_obj = $e->retrieve_acq_user_request([
3017 {flesh => 1, flesh_fields => { "aur" => [ 'lineitem' ] } }
3019 if (! $aur_obj) { next; }
3021 if ($aur_obj->lineitem()) {
3022 $aur_obj->lineitem()->clear_marc();
3024 $conn->respond($aur_obj);
3030 __PACKAGE__->register_method (
3031 method => 'update_user_request',
3032 api_name => 'open-ils.acq.user_request.cancel.batch',
3035 desc => 'If given a cancel reason, will update the request with that reason, otherwise, this will delete the request altogether. The ' .
3036 'intention is for staff interfaces or processes to provide cancel reasons, and for patron interfaces to just delete the requests.' ,
3038 { desc => 'Authentication token', type => 'string' },
3039 { desc => 'ID or array of IDs for the user requests to cancel' },
3040 { desc => 'Cancel Reason ID (optional)', type => 'string' }
3043 desc => 'progress object, event on error',
3047 __PACKAGE__->register_method (
3048 method => 'update_user_request',
3049 api_name => 'open-ils.acq.user_request.set_no_hold.batch',
3052 desc => 'Remove the hold from a user request or set of requests',
3054 { desc => 'Authentication token', type => 'string' },
3055 { desc => 'ID or array of IDs for the user requests to modify' }
3058 desc => 'progress object, event on error',
3063 sub update_user_request {
3064 my($self, $conn, $auth, $aur_ids, $cancel_reason) = @_;
3065 my $e = new_editor(xact => 1, authtoken => $auth);
3066 return $e->die_event unless $e->checkauth;
3067 my $rid = $e->requestor->id;
3071 for my $id (@$aur_ids) {
3073 my $aur_obj = $e->retrieve_acq_user_request([
3076 flesh_fields => { "aur" => ['lineitem', 'usr'] }
3078 ]) or return $e->die_event;
3080 my $context_org = $aur_obj->usr()->home_ou();
3081 $aur_obj->usr( $aur_obj->usr()->id() );
3083 if ($rid != $aur_obj->usr) {
3084 if (!defined $perm_test{ $context_org }) {
3085 $perm_test{ $context_org } = $e->allowed( ['user_request.update'], $context_org );
3087 if (!$perm_test{ $context_org }) {
3092 if($self->api_name =~ /set_no_hold/) {
3093 if ($U->is_true($aur_obj->hold)) {
3095 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3099 if($self->api_name =~ /cancel/) {
3100 if ( $cancel_reason ) {
3101 $aur_obj->cancel_reason( $cancel_reason );
3102 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3103 create_user_request_events( $e, [ $aur_obj ], 'aur.rejected' );
3105 $e->delete_acq_user_request($aur_obj);
3109 $conn->respond({maximum => scalar(@$aur_ids), progress => $x++});
3113 return {complete => 1};
3116 __PACKAGE__->register_method (
3117 method => 'new_user_request',
3118 api_name => 'open-ils.acq.user_request.create',
3120 desc => 'Create a new user request object in the DB',
3122 { desc => 'Authentication token', type => 'string' },
3123 { desc => 'User request data hash. Hash keys match the fields for the "aur" object', type => 'object' }
3126 desc => 'The created user request object, or event on error'
3131 sub new_user_request {
3132 my($self, $conn, $auth, $form_data) = @_;
3133 my $e = new_editor(xact => 1, authtoken => $auth);
3134 return $e->die_event unless $e->checkauth;
3135 my $rid = $e->requestor->id;
3136 my $target_user_fleshed;
3137 if (! defined $$form_data{'usr'}) {
3138 $$form_data{'usr'} = $rid;
3140 if ($$form_data{'usr'} != $rid) {
3141 # See if the requestor can place the request on behalf of a different user.
3142 $target_user_fleshed = $e->retrieve_actor_user($$form_data{'usr'}) or return $e->die_event;
3143 $e->allowed('user_request.create', $target_user_fleshed->home_ou) or return $e->die_event;
3145 $target_user_fleshed = $e->requestor;
3146 $e->allowed('CREATE_PURCHASE_REQUEST') or return $e->die_event;
3148 if (! defined $$form_data{'pickup_lib'}) {
3149 if ($target_user_fleshed->ws_ou) {
3150 $$form_data{'pickup_lib'} = $target_user_fleshed->ws_ou;
3152 $$form_data{'pickup_lib'} = $target_user_fleshed->home_ou;
3155 if (! defined $$form_data{'request_type'}) {
3156 $$form_data{'request_type'} = 1; # Books
3158 my $aur_obj = new Fieldmapper::acq::user_request;
3160 $aur_obj->usr( $$form_data{'usr'} );
3161 $aur_obj->request_date( 'now' );
3162 for my $field ( keys %$form_data ) {
3163 if (defined $$form_data{$field} and $field !~ /^(id|lineitem|eg_bib|request_date|cancel_reason)$/) {
3164 $aur_obj->$field( $$form_data{$field} );
3168 $aur_obj = $e->create_acq_user_request($aur_obj) or return $e->die_event;
3170 $e->commit and create_user_request_events( $e, [ $aur_obj ], 'aur.created' );
3175 sub create_user_request_events {
3176 my($e, $user_reqs, $hook) = @_;
3178 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
3181 my %cached_usr_home_ou = ();
3182 for my $user_req (@$user_reqs) {
3183 my $home_ou = $cached_usr_home_ou{$user_req->usr};
3185 my $user = $e->retrieve_actor_user($user_req->usr) or return $e->die_event;
3186 $home_ou = $user->home_ou;
3187 $cached_usr_home_ou{$user_req->usr} = $home_ou;
3189 my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $home_ou);
3198 __PACKAGE__->register_method(
3199 method => "po_note_CUD_batch",
3200 api_name => "open-ils.acq.po_note.cud.batch",
3203 desc => q/Manage purchase order notes/,
3205 {desc => "Authentication token", type => "string"},
3206 {desc => "List of po_notes to manage", type => "array"},
3208 return => {desc => "Stream of successfully managed objects"}
3212 sub po_note_CUD_batch {
3213 my ($self, $conn, $auth, $notes) = @_;
3215 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3216 return $e->die_event unless $e->checkauth;
3219 my $total = @$notes;
3222 foreach my $note (@$notes) {
3224 $note->editor($e->requestor->id);
3225 $note->edit_time("now");
3228 $note->creator($e->requestor->id);
3229 $note = $e->create_acq_po_note($note) or return $e->die_event;
3230 } elsif ($note->isdeleted) {
3231 $e->delete_acq_po_note($note) or return $e->die_event;
3232 } elsif ($note->ischanged) {
3233 $e->update_acq_po_note($note) or return $e->die_event;
3236 unless ($note->isdeleted) {
3237 $note = $e->retrieve_acq_po_note($note->id) or
3238 return $e->die_event;
3242 {"maximum" => $total, "progress" => ++$count, "note" => $note}
3246 $e->commit and $conn->respond_complete or return $e->die_event;
3250 # retrieves a lineitem, fleshes its PO and PL, checks perms
3251 sub fetch_and_check_li {
3254 my $perm_mode = shift || 'read';
3256 my $li = $e->retrieve_acq_lineitem([
3259 flesh_fields => {jub => ['purchase_order', 'picklist']}
3261 ]) or return $e->die_event;
3263 if(my $po = $li->purchase_order) {
3264 my $perms = ($perm_mode eq 'read') ? 'VIEW_PURCHASE_ORDER' : 'CREATE_PURCHASE_ORDER';
3265 return ($li, $e->die_event) unless $e->allowed($perms, $po->ordering_agency);
3267 } elsif(my $pl = $li->picklist) {
3268 my $perms = ($perm_mode eq 'read') ? 'VIEW_PICKLIST' : 'CREATE_PICKLIST';
3269 return ($li, $e->die_event) unless $e->allowed($perms, $pl->org_unit);
3276 __PACKAGE__->register_method(
3277 method => "clone_distrib_form",
3278 api_name => "open-ils.acq.distribution_formula.clone",
3281 desc => q/Clone a distribution formula/,
3283 {desc => "Authentication token", type => "string"},
3284 {desc => "Original formula ID", type => 'integer'},
3285 {desc => "Name of new formula", type => 'string'},
3287 return => {desc => "ID of newly created formula"}
3291 sub clone_distrib_form {
3292 my($self, $client, $auth, $form_id, $new_name) = @_;
3294 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3295 return $e->die_event unless $e->checkauth;
3297 my $old_form = $e->retrieve_acq_distribution_formula($form_id) or return $e->die_event;
3298 return $e->die_event unless $e->allowed('ADMIN_ACQ_DISTRIB_FORMULA', $old_form->owner);
3300 my $new_form = Fieldmapper::acq::distribution_formula->new;
3302 $new_form->owner($old_form->owner);
3303 $new_form->name($new_name);
3304 $e->create_acq_distribution_formula($new_form) or return $e->die_event;
3306 my $entries = $e->search_acq_distribution_formula_entry({formula => $form_id});
3307 for my $entry (@$entries) {
3308 my $new_entry = Fieldmapper::acq::distribution_formula_entry->new;
3309 $new_entry->$_($entry->$_()) for $entry->real_fields;
3310 $new_entry->formula($new_form->id);
3311 $new_entry->clear_id;
3312 $e->create_acq_distribution_formula_entry($new_entry) or return $e->die_event;
3316 return $new_form->id;
3319 __PACKAGE__->register_method(
3320 method => 'add_li_to_po',
3321 api_name => 'open-ils.acq.purchase_order.add_lineitem',
3323 desc => q/Adds a lineitem to an existing purchase order/,
3325 {desc => 'Authentication token', type => 'string'},
3326 {desc => 'The purchase order id', type => 'number'},
3327 {desc => 'The lineitem ID', type => 'number'},
3329 return => {desc => 'Streams a total versus completed counts object, event on error'}
3334 my($self, $conn, $auth, $po_id, $li_id) = @_;
3336 my $e = new_editor(authtoken => $auth, xact => 1);
3337 return $e->die_event unless $e->checkauth;
3339 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
3341 my $po = $e->retrieve_acq_purchase_order($po_id)
3342 or return $e->die_event;
3344 my $li = $e->retrieve_acq_lineitem($li_id)
3345 or return $e->die_event;
3347 return $e->die_event unless
3348 $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
3350 unless ($po->state =~ /new|pending/) {
3352 return {success => 0, po => $po, error => 'bad-po-state'};
3355 unless ($li->state =~ /new|order-ready|pending-order/) {
3357 return {success => 0, li => $li, error => 'bad-li-state'};
3360 $li->purchase_order($po_id);
3361 $li->state('pending-order');
3362 update_lineitem($mgr, $li) or return $e->die_event;
3365 return {success => 1};