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,
1354 state => 'pending' # will be updated later if activated
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,
1424 !$vandelay->{create_assets}) or return $e->die_event;
1427 return $mgr->respond_complete;
1430 sub import_lineitem_details {
1431 my($mgr, $ordering_agency, $li) = @_;
1433 my $holdings = $mgr->editor->json_query({from => ['acq.extract_provider_holding_data', $li->id]});
1434 return 1 unless @$holdings;
1435 my $org_path = $U->get_org_ancestors($ordering_agency);
1436 $org_path = [ reverse (@$org_path) ];
1442 # create a lineitem detail for each copy in the data
1444 my $compiled = extract_lineitem_detail_data($mgr, $org_path, $holdings, $idx);
1445 last unless defined $compiled;
1446 return 0 unless $compiled;
1448 # this takes the price of the last copy and uses it as the lineitem price
1449 # need to determine if a given record would include different prices for the same item
1450 $price = $$compiled{estimated_price};
1452 last unless $$compiled{quantity};
1454 for(1..$$compiled{quantity}) {
1455 my $lid = create_lineitem_detail(
1457 lineitem => $li->id,
1458 owning_lib => $$compiled{owning_lib},
1459 cn_label => $$compiled{call_number},
1460 fund => $$compiled{fund},
1461 circ_modifier => $$compiled{circ_modifier},
1462 note => $$compiled{note},
1463 location => $$compiled{copy_location},
1464 collection_code => $$compiled{collection_code},
1465 barcode => $$compiled{barcode}
1473 $li->estimated_unit_price($price);
1474 update_lineitem($mgr, $li) or return 0;
1478 # return hash on success, 0 on error, undef on no more holdings
1479 sub extract_lineitem_detail_data {
1480 my($mgr, $org_path, $holdings, $index) = @_;
1482 my @data_list = grep { $_->{holding} eq $index } @$holdings;
1483 return undef unless @data_list;
1485 my %compiled = map { $_->{attr} => $_->{data} } @data_list;
1486 my $base_org = $$org_path[0];
1490 $logger->error("Item import extraction error: $msg");
1491 $logger->error('Holdings Data: ' . OpenSRF::Utils::JSON->perl2JSON(\%compiled));
1492 $mgr->editor->rollback;
1493 $mgr->editor->event(OpenILS::Event->new('ACQ_IMPORT_ERROR', payload => $msg));
1497 # ---------------------------------------------------------------------
1499 if(my $code = $compiled{fund_code}) {
1501 my $fund = $mgr->cache($base_org, "fund.$code");
1503 # search up the org tree for the most appropriate fund
1504 for my $org (@$org_path) {
1505 $fund = $mgr->editor->search_acq_fund(
1506 {org => $org, code => $code, year => DateTime->now->year}, {idlist => 1})->[0];
1510 return $killme->("no fund with code $code at orgs [@$org_path]") unless $fund;
1511 $compiled{fund} = $fund;
1512 $mgr->cache($base_org, "fund.$code", $fund);
1516 # ---------------------------------------------------------------------
1518 if(my $sn = $compiled{owning_lib}) {
1519 my $org_id = $mgr->cache($base_org, "orgsn.$sn") ||
1520 $mgr->editor->search_actor_org_unit({shortname => $sn}, {idlist => 1})->[0];
1521 return $killme->("invalid owning_lib defined: $sn") unless $org_id;
1522 $compiled{owning_lib} = $org_id;
1523 $mgr->cache($$org_path[0], "orgsn.$sn", $org_id);
1527 # ---------------------------------------------------------------------
1529 my $code = $compiled{circ_modifier};
1533 # verify this is a valid circ modifier
1534 return $killme->("invlalid circ_modifier $code") unless
1535 defined $mgr->cache($base_org, "mod.$code") or
1536 $mgr->editor->retrieve_config_circ_modifier($code);
1538 # if valid, cache for future tests
1539 $mgr->cache($base_org, "mod.$code", $code);
1542 $compiled{circ_modifier} = get_default_circ_modifier($mgr, $base_org);
1546 # ---------------------------------------------------------------------
1548 if( my $name = $compiled{copy_location}) {
1549 my $loc = $mgr->cache($base_org, "copy_loc.$name");
1551 for my $org (@$org_path) {
1552 $loc = $mgr->editor->search_asset_copy_location(
1553 {owning_lib => $org, name => $name}, {idlist => 1})->[0];
1557 return $killme->("Invalid copy location $name") unless $loc;
1558 $compiled{copy_location} = $loc;
1559 $mgr->cache($base_org, "copy_loc.$name", $loc);
1567 # ----------------------------------------------------------------------------
1568 # Workflow: Given an existing purchase order, import/create the bibs,
1569 # callnumber and copy objects
1570 # ----------------------------------------------------------------------------
1572 __PACKAGE__->register_method(
1573 method => 'create_po_assets',
1574 api_name => 'open-ils.acq.purchase_order.assets.create',
1576 desc => q/Creates assets for each lineitem in the purchase order/,
1578 {desc => 'Authentication token', type => 'string'},
1579 {desc => 'The purchase order id', type => 'number'},
1581 return => {desc => 'Streams a total versus completed counts object, event on error'}
1583 max_chunk_count => 1
1586 sub create_po_assets {
1587 my($self, $conn, $auth, $po_id, $args) = @_;
1590 my $e = new_editor(authtoken=>$auth, xact=>1);
1591 return $e->die_event unless $e->checkauth;
1592 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1594 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1596 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1598 # it's ugly, but it's fast. Get the total count of lineitem detail objects to process
1599 my $lid_total = $e->json_query({
1600 select => { acqlid => [{aggregate => 1, transform => 'count', column => 'id'}] },
1606 join => {acqpo => {fkey => 'purchase_order', field => 'id'}}
1610 where => {'+acqpo' => {id => $po_id}}
1613 $mgr->total(scalar(@$li_ids) + $lid_total);
1615 create_lineitem_list_assets($mgr, $li_ids, $args->{vandelay})
1616 or return $e->die_event;
1619 update_purchase_order($mgr, $po) or return $e->die_event;
1622 return $mgr->respond_complete;
1627 __PACKAGE__->register_method(
1628 method => 'create_purchase_order_api',
1629 api_name => 'open-ils.acq.purchase_order.create',
1631 desc => 'Creates a new purchase order',
1633 {desc => 'Authentication token', type => 'string'},
1634 {desc => 'purchase_order to create', type => 'object'}
1636 return => {desc => 'The purchase order id, Event on failure'}
1638 max_chunk_count => 1
1641 sub create_purchase_order_api {
1642 my($self, $conn, $auth, $po, $args) = @_;
1645 my $e = new_editor(xact=>1, authtoken=>$auth);
1646 return $e->die_event unless $e->checkauth;
1647 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
1648 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1651 my %pargs = (ordering_agency => $e->requestor->ws_ou); # default
1652 $pargs{provider} = $po->provider if $po->provider;
1653 $pargs{ordering_agency} = $po->ordering_agency if $po->ordering_agency;
1654 $pargs{prepayment_required} = $po->prepayment_required if $po->prepayment_required;
1655 my $vandelay = $args->{vandelay};
1657 $po = create_purchase_order($mgr, %pargs) or return $e->die_event;
1659 my $li_ids = $$args{lineitems};
1663 for my $li_id (@$li_ids) {
1665 my $li = $e->retrieve_acq_lineitem([
1667 {flesh => 1, flesh_fields => {jub => ['attributes']}}
1668 ]) or return $e->die_event;
1670 $li->provider($po->provider);
1671 $li->purchase_order($po->id);
1672 $li->state('pending-order');
1673 update_lineitem($mgr, $li) or return $e->die_event;
1678 # commit before starting the asset creation
1681 if($li_ids and $vandelay) {
1682 create_lineitem_list_assets($mgr, $li_ids, $vandelay, !$$args{create_assets}) or return $e->die_event;
1685 return $mgr->respond_complete;
1690 __PACKAGE__->register_method(
1691 method => 'update_lineitem_fund_batch',
1692 api_name => 'open-ils.acq.lineitem.fund.update.batch',
1695 desc => q/Given a set of lineitem IDS, updates the fund for all attached lineitem details/
1699 sub update_lineitem_fund_batch {
1700 my($self, $conn, $auth, $li_ids, $fund_id) = @_;
1701 my $e = new_editor(xact=>1, authtoken=>$auth);
1702 return $e->die_event unless $e->checkauth;
1703 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1704 for my $li_id (@$li_ids) {
1705 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
1706 return $evt if $evt;
1707 my $li_details = $e->search_acq_lineitem_detail({lineitem => $li_id});
1708 $_->fund($fund_id) and $_->ischanged(1) for @$li_details;
1709 $evt = lineitem_detail_CUD_batch($mgr, $li_details);
1710 return $evt if $evt;
1715 return $mgr->respond_complete;
1720 __PACKAGE__->register_method(
1721 method => 'lineitem_detail_CUD_batch_api',
1722 api_name => 'open-ils.acq.lineitem_detail.cud.batch',
1725 desc => q/Creates a new purchase order line item detail. / .
1726 q/Additionally creates the associated fund_debit/,
1728 {desc => 'Authentication token', type => 'string'},
1729 {desc => 'List of lineitem_details to create', type => 'array'},
1730 {desc => 'Create Debits. Used for creating post-po-asset-creation debits', type => 'bool'},
1732 return => {desc => 'Streaming response of current position in the array'}
1736 __PACKAGE__->register_method(
1737 method => 'lineitem_detail_CUD_batch_api',
1738 api_name => 'open-ils.acq.lineitem_detail.cud.batch.dry_run',
1742 Dry run version of open-ils.acq.lineitem_detail.cud.batch.
1743 In dry_run mode, updated fund_debit's the exceed the warning
1744 percent return an event.
1750 sub lineitem_detail_CUD_batch_api {
1751 my($self, $conn, $auth, $li_details, $create_debits) = @_;
1752 my $e = new_editor(xact=>1, authtoken=>$auth);
1753 return $e->die_event unless $e->checkauth;
1754 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1755 my $dry_run = ($self->api_name =~ /dry_run/o);
1756 my $evt = lineitem_detail_CUD_batch($mgr, $li_details, $create_debits, $dry_run);
1757 return $evt if $evt;
1759 return $mgr->respond_complete;
1763 sub lineitem_detail_CUD_batch {
1764 my($mgr, $li_details, $create_debits, $dry_run) = @_;
1766 $mgr->total(scalar(@$li_details));
1767 my $e = $mgr->editor;
1771 my $fund_cache = {};
1774 for my $lid (@$li_details) {
1776 unless($li = $li_cache{$lid->lineitem}) {
1777 ($li, $evt) = fetch_and_check_li($e, $lid->lineitem, 'write');
1778 return $evt if $evt;
1782 $lid = create_lineitem_detail($mgr, %{$lid->to_bare_hash}) or return $e->die_event;
1783 if($create_debits) {
1784 $li->provider($e->retrieve_acq_provider($li->provider)) or return $e->die_event;
1785 $lid->fund($e->retrieve_acq_fund($lid->fund)) or return $e->die_event;
1786 create_lineitem_detail_debit($mgr, $li, $lid, 0, 1) or return $e->die_event;
1789 } elsif($lid->ischanged) {
1790 return $evt if $evt = handle_changed_lid($e, $lid, $dry_run, $fund_cache);
1792 } elsif($lid->isdeleted) {
1793 delete_lineitem_detail($mgr, $lid) or return $e->die_event;
1796 $mgr->respond(li => $li);
1797 $li_cache{$lid->lineitem} = $li;
1803 sub handle_changed_lid {
1804 my($e, $lid, $dry_run, $fund_cache) = @_;
1806 my $orig_lid = $e->retrieve_acq_lineitem_detail($lid->id) or return $e->die_event;
1808 # updating the fund, so update the debit
1809 if($orig_lid->fund_debit and $orig_lid->fund != $lid->fund) {
1811 my $debit = $e->retrieve_acq_fund_debit($orig_lid->fund_debit);
1812 my $new_fund = $$fund_cache{$lid->fund} =
1813 $$fund_cache{$lid->fund} || $e->retrieve_acq_fund($lid->fund);
1815 # check the thresholds
1816 return $e->die_event if
1817 fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "stop");
1818 return $e->die_event if $dry_run and
1819 fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "warning");
1821 $debit->fund($new_fund->id);
1822 $e->update_acq_fund_debit($debit) or return $e->die_event;
1825 $e->update_acq_lineitem_detail($lid) or return $e->die_event;
1830 __PACKAGE__->register_method(
1831 method => 'receive_po_api',
1832 api_name => 'open-ils.acq.purchase_order.receive'
1835 sub receive_po_api {
1836 my($self, $conn, $auth, $po_id) = @_;
1837 my $e = new_editor(xact => 1, authtoken => $auth);
1838 return $e->die_event unless $e->checkauth;
1839 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1841 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1842 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1844 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1846 for my $li_id (@$li_ids) {
1847 receive_lineitem($mgr, $li_id) or return $e->die_event;
1851 $po->state('received');
1852 update_purchase_order($mgr, $po) or return $e->die_event;
1855 return $mgr->respond_complete;
1859 # At the moment there's a lack of parallelism between the receive and unreceive
1860 # API methods for POs and the API methods for LIs and LIDs. The methods for
1861 # POs stream back objects as they act, whereas the methods for LIs and LIDs
1862 # atomically return an object that describes only what changed (in LIs and LIDs
1863 # themselves or in the objects to which to LIs and LIDs belong).
1865 # The methods for LIs and LIDs work the way they do to faciliate the UI's
1866 # maintaining correct information about the state of these things when a user
1867 # wants to receive or unreceive these objects without refreshing their whole
1868 # display. The UI feature for receiving and un-receiving a whole PO just
1869 # refreshes the whole display, so this absence of parallelism in the UI is also
1870 # relected in this module.
1872 # This could be neatened in the future by making POs receive and unreceive in
1873 # the same way the LIs and LIDs do.
1875 __PACKAGE__->register_method(
1876 method => 'receive_lineitem_detail_api',
1877 api_name => 'open-ils.acq.lineitem_detail.receive',
1879 desc => 'Mark a lineitem_detail as received',
1881 {desc => 'Authentication token', type => 'string'},
1882 {desc => 'lineitem detail ID', type => 'number'}
1885 "on success, object describing changes to LID and possibly " .
1886 "to LI and PO; on error, Event"
1891 sub receive_lineitem_detail_api {
1892 my($self, $conn, $auth, $lid_id) = @_;
1894 my $e = new_editor(xact=>1, authtoken=>$auth);
1895 return $e->die_event unless $e->checkauth;
1896 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1899 "flesh" => 2, "flesh_fields" => {
1900 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
1904 my $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1906 return $e->die_event unless $e->allowed(
1907 'RECEIVE_PURCHASE_ORDER', $lid->lineitem->purchase_order->ordering_agency);
1910 my $recvd = receive_lineitem_detail($mgr, $lid_id) or return $e->die_event;
1912 # .. and re-retrieve
1913 $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1915 # Now build result data structure.
1916 my $result = {"lid" => {$lid->id => {"recv_time" => $lid->recv_time}}};
1919 if ($recvd->class_name =~ /::purchase_order/) {
1920 $result->{"po"} = describe_affected_po($e, $recvd);
1922 $lid->lineitem->id => {"state" => $lid->lineitem->state}
1924 } elsif ($recvd->class_name =~ /::lineitem/) {
1925 $result->{"li"} = {$recvd->id => {"state" => $recvd->state}};
1929 describe_affected_po($e, $lid->lineitem->purchase_order);
1935 __PACKAGE__->register_method(
1936 method => 'receive_lineitem_api',
1937 api_name => 'open-ils.acq.lineitem.receive',
1939 desc => 'Mark a lineitem as received',
1941 {desc => 'Authentication token', type => 'string'},
1942 {desc => 'lineitem ID', type => 'number'}
1945 "on success, object describing changes to LI and possibly PO; " .
1951 sub receive_lineitem_api {
1952 my($self, $conn, $auth, $li_id) = @_;
1954 my $e = new_editor(xact=>1, authtoken=>$auth);
1955 return $e->die_event unless $e->checkauth;
1956 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1958 my $li = $e->retrieve_acq_lineitem([
1962 jub => ['purchase_order']
1965 ]) or return $e->die_event;
1967 return $e->die_event unless $e->allowed(
1968 'RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);
1970 my $res = receive_lineitem($mgr, $li_id) or return $e->die_event;
1972 $conn->respond_complete($res);
1973 $mgr->run_post_response_hooks
1977 __PACKAGE__->register_method(
1978 method => 'rollback_receive_po_api',
1979 api_name => 'open-ils.acq.purchase_order.receive.rollback'
1982 sub rollback_receive_po_api {
1983 my($self, $conn, $auth, $po_id) = @_;
1984 my $e = new_editor(xact => 1, authtoken => $auth);
1985 return $e->die_event unless $e->checkauth;
1986 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1988 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1989 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1991 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1993 for my $li_id (@$li_ids) {
1994 rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
1998 $po->state('on-order');
1999 update_purchase_order($mgr, $po) or return $e->die_event;
2002 return $mgr->respond_complete;
2006 __PACKAGE__->register_method(
2007 method => 'rollback_receive_lineitem_detail_api',
2008 api_name => 'open-ils.acq.lineitem_detail.receive.rollback',
2010 desc => 'Mark a lineitem_detail as Un-received',
2012 {desc => 'Authentication token', type => 'string'},
2013 {desc => 'lineitem detail ID', type => 'number'}
2016 "on success, object describing changes to LID and possibly " .
2017 "to LI and PO; on error, Event"
2022 sub rollback_receive_lineitem_detail_api {
2023 my($self, $conn, $auth, $lid_id) = @_;
2025 my $e = new_editor(xact=>1, authtoken=>$auth);
2026 return $e->die_event unless $e->checkauth;
2027 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2029 my $lid = $e->retrieve_acq_lineitem_detail([
2033 acqlid => ['lineitem'],
2034 jub => ['purchase_order']
2038 my $li = $lid->lineitem;
2039 my $po = $li->purchase_order;
2041 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2045 my $recvd = rollback_receive_lineitem_detail($mgr, $lid_id)
2046 or return $e->die_event;
2049 $result->{"lid"} = {$recvd->id => {"recv_time" => $recvd->recv_time}};
2051 $result->{"lid"} = {$lid->id => {"recv_time" => $lid->recv_time}};
2054 if ($li->state eq "received") {
2055 $li->state("on-order");
2056 $li = update_lineitem($mgr, $li) or return $e->die_event;
2057 $result->{"li"} = {$li->id => {"state" => $li->state}};
2060 if ($po->state eq "received") {
2061 $po->state("on-order");
2062 $po = update_purchase_order($mgr, $po) or return $e->die_event;
2064 $result->{"po"} = describe_affected_po($e, $po);
2066 $e->commit and return $result or return $e->die_event;
2069 __PACKAGE__->register_method(
2070 method => 'rollback_receive_lineitem_api',
2071 api_name => 'open-ils.acq.lineitem.receive.rollback',
2073 desc => 'Mark a lineitem as Un-received',
2075 {desc => 'Authentication token', type => 'string'},
2076 {desc => 'lineitem ID', type => 'number'}
2079 "on success, object describing changes to LI and possibly PO; " .
2085 sub rollback_receive_lineitem_api {
2086 my($self, $conn, $auth, $li_id) = @_;
2088 my $e = new_editor(xact=>1, authtoken=>$auth);
2089 return $e->die_event unless $e->checkauth;
2090 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2092 my $li = $e->retrieve_acq_lineitem([
2094 "flesh" => 1, "flesh_fields" => {"jub" => ["purchase_order"]}
2097 my $po = $li->purchase_order;
2099 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2101 $li = rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
2103 my $result = {"li" => {$li->id => {"state" => $li->state}}};
2104 if ($po->state eq "received") {
2105 $po->state("on-order");
2106 $po = update_purchase_order($mgr, $po) or return $e->die_event;
2108 $result->{"po"} = describe_affected_po($e, $po);
2110 $e->commit and return $result or return $e->die_event;
2114 __PACKAGE__->register_method(
2115 method => 'set_lineitem_price_api',
2116 api_name => 'open-ils.acq.lineitem.price.set',
2118 desc => 'Set lineitem price. If debits already exist, update them as well',
2120 {desc => 'Authentication token', type => 'string'},
2121 {desc => 'lineitem ID', type => 'number'}
2123 return => {desc => 'status blob, Event on error'}
2127 sub set_lineitem_price_api {
2128 my($self, $conn, $auth, $li_id, $price) = @_;
2130 my $e = new_editor(xact=>1, authtoken=>$auth);
2131 return $e->die_event unless $e->checkauth;
2132 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2134 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
2135 return $evt if $evt;
2137 $li->estimated_unit_price($price);
2138 update_lineitem($mgr, $li) or return $e->die_event;
2140 my $lid_ids = $e->search_acq_lineitem_detail(
2141 {lineitem => $li_id, fund_debit => {'!=' => undef}},
2145 for my $lid_id (@$lid_ids) {
2147 my $lid = $e->retrieve_acq_lineitem_detail([
2149 flesh => 1, flesh_fields => {acqlid => ['fund', 'fund_debit']}}
2152 $lid->fund_debit->amount($price);
2153 $e->update_acq_fund_debit($lid->fund_debit) or return $e->die_event;
2159 return $mgr->respond_complete;
2163 __PACKAGE__->register_method(
2164 method => 'clone_picklist_api',
2165 api_name => 'open-ils.acq.picklist.clone',
2167 desc => 'Clones a picklist, including lineitem and lineitem details',
2169 {desc => 'Authentication token', type => 'string'},
2170 {desc => 'Picklist ID', type => 'number'},
2171 {desc => 'New Picklist Name', type => 'string'}
2173 return => {desc => 'status blob, Event on error'}
2177 sub clone_picklist_api {
2178 my($self, $conn, $auth, $pl_id, $name) = @_;
2180 my $e = new_editor(xact=>1, authtoken=>$auth);
2181 return $e->die_event unless $e->checkauth;
2182 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2184 my $old_pl = $e->retrieve_acq_picklist($pl_id);
2185 my $new_pl = create_picklist($mgr, %{$old_pl->to_bare_hash}, name => $name) or return $e->die_event;
2187 my $li_ids = $e->search_acq_lineitem({picklist => $pl_id}, {idlist => 1});
2189 # get the current user
2190 my $cloner = $mgr->editor->requestor->id;
2192 for my $li_id (@$li_ids) {
2194 # copy the lineitems' MARC
2195 my $marc = ($e->retrieve_acq_lineitem($li_id))->marc;
2197 # create a skeletal clone of the item
2198 my $li = Fieldmapper::acq::lineitem->new;
2199 $li->creator($cloner);
2200 $li->selector($cloner);
2201 $li->editor($cloner);
2204 my $new_li = create_lineitem($mgr, %{$li->to_bare_hash}, picklist => $new_pl->id) or return $e->die_event;
2210 return $mgr->respond_complete;
2214 __PACKAGE__->register_method(
2215 method => 'merge_picklist_api',
2216 api_name => 'open-ils.acq.picklist.merge',
2218 desc => 'Merges 2 or more picklists into a single list',
2220 {desc => 'Authentication token', type => 'string'},
2221 {desc => 'Lead Picklist ID', type => 'number'},
2222 {desc => 'List of subordinate picklist IDs', type => 'array'}
2224 return => {desc => 'status blob, Event on error'}
2228 sub merge_picklist_api {
2229 my($self, $conn, $auth, $lead_pl, $pl_list) = @_;
2231 my $e = new_editor(xact=>1, authtoken=>$auth);
2232 return $e->die_event unless $e->checkauth;
2233 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2235 # XXX perms on each picklist modified
2237 $lead_pl = $e->retrieve_acq_picklist($lead_pl) or return $e->die_event;
2238 # point all of the lineitems at the lead picklist
2239 my $li_ids = $e->search_acq_lineitem({picklist => $pl_list}, {idlist => 1});
2241 for my $li_id (@$li_ids) {
2242 my $li = $e->retrieve_acq_lineitem($li_id);
2243 $li->picklist($lead_pl);
2244 update_lineitem($mgr, $li) or return $e->die_event;
2248 # now delete the subordinate lists
2249 for my $pl_id (@$pl_list) {
2250 my $pl = $e->retrieve_acq_picklist($pl_id);
2251 $e->delete_acq_picklist($pl) or return $e->die_event;
2254 update_picklist($mgr, $lead_pl) or return $e->die_event;
2257 return $mgr->respond_complete;
2261 __PACKAGE__->register_method(
2262 method => 'delete_picklist_api',
2263 api_name => 'open-ils.acq.picklist.delete',
2265 desc => q/Deletes a picklist. It also deletes any lineitems in the "new" state. / .
2266 q/Other attached lineitems are detached/,
2268 {desc => 'Authentication token', type => 'string'},
2269 {desc => 'Picklist ID to delete', type => 'number'}
2271 return => {desc => '1 on success, Event on error'}
2275 sub delete_picklist_api {
2276 my($self, $conn, $auth, $picklist_id) = @_;
2277 my $e = new_editor(xact=>1, authtoken=>$auth);
2278 return $e->die_event unless $e->checkauth;
2279 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2280 my $pl = $e->retrieve_acq_picklist($picklist_id) or return $e->die_event;
2281 delete_picklist($mgr, $pl) or return $e->die_event;
2283 return $mgr->respond_complete;
2288 __PACKAGE__->register_method(
2289 method => 'activate_purchase_order',
2290 api_name => 'open-ils.acq.purchase_order.activate.dry_run'
2293 __PACKAGE__->register_method(
2294 method => 'activate_purchase_order',
2295 api_name => 'open-ils.acq.purchase_order.activate',
2297 desc => q/Activates a purchase order. This updates the status of the PO / .
2298 q/and Lineitems to 'on-order'. Activated PO's are ready for EDI delivery if appropriate./,
2300 {desc => 'Authentication token', type => 'string'},
2301 {desc => 'Purchase ID', type => 'number'}
2303 return => {desc => '1 on success, Event on error'}
2307 sub activate_purchase_order {
2308 my($self, $conn, $auth, $po_id, $vandelay) = @_;
2310 my $dry_run = ($self->api_name =~ /\.dry_run/) ? 1 : 0;
2311 my $e = new_editor(authtoken=>$auth);
2312 return $e->die_event unless $e->checkauth;
2313 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2314 my $die_event = activate_purchase_order_impl($mgr, $po_id, $vandelay, $dry_run);
2315 return $e->die_event if $die_event;
2316 $conn->respond_complete(1);
2317 $mgr->run_post_response_hooks unless $dry_run;
2321 # xacts managed within
2322 sub activate_purchase_order_impl {
2323 my ($mgr, $po_id, $vandelay, $dry_run) = @_;
2325 # read-only until lineitem asset creation
2326 my $e = $mgr->editor;
2329 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2330 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
2331 my $provider = $e->retrieve_acq_provider($po->provider);
2333 # find lineitems and create assets for all
2336 purchase_order => $po_id,
2337 state => [qw/pending-order new order-ready/]
2340 my $li_ids = $e->search_acq_lineitem($query, {idlist => 1});
2342 my $vl_resp; # imported li's and the queue the managing queue
2344 $e->rollback; # read-only thus far
2345 $vl_resp = create_lineitem_list_assets($mgr, $li_ids, $vandelay)
2346 or return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED');
2350 # create fund debits for lineitems
2352 for my $li_id (@$li_ids) {
2353 my $li = $e->retrieve_acq_lineitem($li_id);
2355 if (!$li->eg_bib_id and !$dry_run) {
2356 # we encountered a lineitem that was not successfully imported.
2357 # we cannot continue. rollback and report.
2359 return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED', {queue => $vl_resp->{queue}});
2362 $li->state('on-order');
2363 $li->claim_policy($provider->default_claim_policy)
2364 if $provider->default_claim_policy and !$li->claim_policy;
2365 create_lineitem_debits($mgr, $li, $dry_run) or return $e->die_event;
2366 update_lineitem($mgr, $li) or return $e->die_event;
2367 $mgr->post_process( sub { create_lineitem_status_events($mgr, $li->id, 'aur.ordered'); });
2371 # create po-item debits
2373 for my $po_item (@{$e->search_acq_po_item({purchase_order => $po_id})}) {
2375 my $debit = create_fund_debit(
2378 debit_type => 'direct_charge', # to match invoicing
2379 origin_amount => $po_item->estimated_cost,
2380 origin_currency_type => $e->retrieve_acq_fund($po_item->fund)->currency_type,
2381 amount => $po_item->estimated_cost,
2382 fund => $po_item->fund
2383 ) or return $e->die_event;
2384 $po_item->fund_debit($debit->id);
2385 $e->update_acq_po_item($po_item) or return $e->die_event;
2389 # mark PO as ordered
2391 $po->state('on-order');
2392 $po->order_date('now');
2393 update_purchase_order($mgr, $po) or return $e->die_event;
2396 $dry_run and $e->rollback or $e->commit;
2398 # tell the world we activated a PO
2399 $U->create_events_for_hook('acqpo.activated', $po, $po->ordering_agency) unless $dry_run;
2405 __PACKAGE__->register_method(
2406 method => 'split_purchase_order_by_lineitems',
2407 api_name => 'open-ils.acq.purchase_order.split_by_lineitems',
2409 desc => q/Splits a PO into many POs, 1 per lineitem. Only works for / .
2410 q/POs a) with more than one lineitems, and b) in the "pending" state./,
2412 {desc => 'Authentication token', type => 'string'},
2413 {desc => 'Purchase order ID', type => 'number'}
2415 return => {desc => 'list of new PO IDs on success, Event on error'}
2419 sub split_purchase_order_by_lineitems {
2420 my ($self, $conn, $auth, $po_id) = @_;
2422 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2423 return $e->die_event unless $e->checkauth;
2425 my $po = $e->retrieve_acq_purchase_order([
2428 "flesh_fields" => {"acqpo" => [qw/lineitems notes/]}
2430 ]) or return $e->die_event;
2432 return $e->die_event
2433 unless $e->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2435 unless ($po->state eq "pending") {
2437 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_LATE");
2440 unless (@{$po->lineitems} > 1) {
2442 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_SHORT");
2445 # To split an existing PO into many, it seems unwise to just delete the
2446 # original PO, so we'll instead detach all of the original POs' lineitems
2447 # but the first, then create new POs for each of the remaining LIs, and
2448 # then attach the LIs to their new POs.
2450 my @po_ids = ($po->id);
2451 my @moving_li = @{$po->lineitems};
2452 shift @moving_li; # discard first LI
2454 foreach my $li (@moving_li) {
2455 my $new_po = $po->clone;
2457 $new_po->clear_name;
2458 $new_po->creator($e->requestor->id);
2459 $new_po->editor($e->requestor->id);
2460 $new_po->owner($e->requestor->id);
2461 $new_po->edit_time("now");
2462 $new_po->create_time("now");
2464 $new_po = $e->create_acq_purchase_order($new_po);
2466 # Clone any notes attached to the old PO and attach to the new one.
2467 foreach my $note (@{$po->notes}) {
2468 my $new_note = $note->clone;
2469 $new_note->clear_id;
2470 $new_note->edit_time("now");
2471 $new_note->purchase_order($new_po->id);
2472 $e->create_acq_po_note($new_note);
2475 $li->edit_time("now");
2476 $li->purchase_order($new_po->id);
2477 $e->update_acq_lineitem($li);
2479 push @po_ids, $new_po->id;
2482 $po->edit_time("now");
2483 $e->update_acq_purchase_order($po);
2485 return \@po_ids if $e->commit;
2486 return $e->die_event;
2490 sub not_cancelable {
2492 (ref $o eq "HASH" and $o->{"textcode"} eq "ACQ_NOT_CANCELABLE");
2495 __PACKAGE__->register_method(
2496 method => "cancel_purchase_order_api",
2497 api_name => "open-ils.acq.purchase_order.cancel",
2499 desc => q/Cancels an on-order purchase order/,
2501 {desc => "Authentication token", type => "string"},
2502 {desc => "PO ID to cancel", type => "number"},
2503 {desc => "Cancel reason ID", type => "number"}
2505 return => {desc => q/Object describing changed POs, LIs and LIDs
2506 on success; Event on error./}
2510 sub cancel_purchase_order_api {
2511 my ($self, $conn, $auth, $po_id, $cancel_reason) = @_;
2513 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2514 return $e->die_event unless $e->checkauth;
2515 my $mgr = new OpenILS::Application::Acq::BatchManager(
2516 "editor" => $e, "conn" => $conn
2519 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2520 return new OpenILS::Event(
2521 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2524 my $result = cancel_purchase_order($mgr, $po_id, $cancel_reason) or
2525 return $e->die_event;
2526 if (not_cancelable($result)) { # event not from CStoreEditor
2529 } elsif ($result == -1) {
2531 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2534 $e->commit or return $e->die_event;
2536 # XXX create purchase order status events?
2538 if ($mgr->{post_commit}) {
2539 foreach my $func (@{$mgr->{post_commit}}) {
2547 sub cancel_purchase_order {
2548 my ($mgr, $po_id, $cancel_reason) = @_;
2550 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id) or return 0;
2552 # XXX is "cancelled" a typo? It's not correct US spelling, anyway.
2553 # Depending on context, this may not warrant an event.
2554 return -1 if $po->state eq "cancelled";
2556 # But this always does.
2557 return new OpenILS::Event(
2558 "ACQ_NOT_CANCELABLE", "note" => "purchase_order $po_id"
2559 ) unless ($po->state eq "on-order" or $po->state eq "pending");
2562 $mgr->editor->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2564 $po->state("cancelled");
2565 $po->cancel_reason($cancel_reason->id);
2567 my $li_ids = $mgr->editor->search_acq_lineitem(
2568 {"purchase_order" => $po_id}, {"idlist" => 1}
2571 my $result = {"li" => {}, "lid" => {}};
2572 foreach my $li_id (@$li_ids) {
2573 my $li_result = cancel_lineitem($mgr, $li_id, $cancel_reason)
2576 next if $li_result == -1; # already canceled:skip.
2577 return $li_result if not_cancelable($li_result); # not cancelable:stop.
2579 # Merge in each LI result (there's only going to be
2580 # one per call to cancel_lineitem).
2581 my ($k, $v) = each %{$li_result->{"li"}};
2582 $result->{"li"}->{$k} = $v;
2584 # Merge in each LID result (there may be many per call to
2586 while (($k, $v) = each %{$li_result->{"lid"}}) {
2587 $result->{"lid"}->{$k} = $v;
2591 # TODO who/what/where/how do we indicate this change for electronic orders?
2592 # TODO return changes to encumbered/spent
2593 # TODO maybe cascade up from smaller object to container object if last
2594 # smaller object in the container has been canceled?
2596 update_purchase_order($mgr, $po) or return 0;
2598 $po_id => {"state" => $po->state, "cancel_reason" => $cancel_reason}
2604 __PACKAGE__->register_method(
2605 method => "cancel_lineitem_api",
2606 api_name => "open-ils.acq.lineitem.cancel",
2608 desc => q/Cancels an on-order lineitem/,
2610 {desc => "Authentication token", type => "string"},
2611 {desc => "Lineitem ID to cancel", type => "number"},
2612 {desc => "Cancel reason ID", type => "number"}
2614 return => {desc => q/Object describing changed LIs and LIDs on success;
2619 __PACKAGE__->register_method(
2620 method => "cancel_lineitem_api",
2621 api_name => "open-ils.acq.lineitem.cancel.batch",
2623 desc => q/Batched version of open-ils.acq.lineitem.cancel/,
2624 return => {desc => q/Object describing changed LIs and LIDs on success;
2629 sub cancel_lineitem_api {
2630 my ($self, $conn, $auth, $li_id, $cancel_reason) = @_;
2632 my $batched = $self->api_name =~ /\.batch/;
2634 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2635 return $e->die_event unless $e->checkauth;
2636 my $mgr = new OpenILS::Application::Acq::BatchManager(
2637 "editor" => $e, "conn" => $conn
2640 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2641 return new OpenILS::Event(
2642 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2645 my ($result, $maybe_event);
2648 $result = {"li" => {}, "lid" => {}};
2649 foreach my $one_li_id (@$li_id) {
2650 my $one = cancel_lineitem($mgr, $one_li_id, $cancel_reason) or
2651 return $e->die_event;
2652 if (not_cancelable($one)) {
2653 $maybe_event = $one;
2654 } elsif ($result == -1) {
2655 $maybe_event = new OpenILS::Event("ACQ_ALREADY_CANCELED");
2659 while (($k, $v) = each %{$one->{"li"}}) {
2660 $result->{"li"}->{$k} = $v;
2663 if ($one->{"lid"}) {
2664 while (($k, $v) = each %{$one->{"lid"}}) {
2665 $result->{"lid"}->{$k} = $v;
2671 $result = cancel_lineitem($mgr, $li_id, $cancel_reason) or
2672 return $e->die_event;
2674 if (not_cancelable($result)) {
2677 } elsif ($result == -1) {
2679 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2683 if ($batched and not scalar keys %{$result->{"li"}}) {
2685 return $maybe_event;
2687 $e->commit or return $e->die_event;
2688 # create_lineitem_status_events should handle array li_id ok
2689 create_lineitem_status_events($mgr, $li_id, "aur.cancelled");
2691 if ($mgr->{post_commit}) {
2692 foreach my $func (@{$mgr->{post_commit}}) {
2701 sub cancel_lineitem {
2702 my ($mgr, $li_id, $cancel_reason) = @_;
2703 my $li = $mgr->editor->retrieve_acq_lineitem([
2704 $li_id, {flesh => 1, flesh_fields => {jub => ['purchase_order']}}
2707 return 0 unless $mgr->editor->allowed(
2708 "CREATE_PURCHASE_ORDER", $li->purchase_order->ordering_agency
2711 # Depending on context, this may not warrant an event.
2712 return -1 if $li->state eq "cancelled";
2714 # But this always does.
2715 return new OpenILS::Event(
2716 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id"
2718 (! $li->purchase_order) or (
2719 $li->purchase_order and (
2720 $li->state eq "on-order" or $li->state eq "pending-order"
2725 $li->state("cancelled");
2726 $li->cancel_reason($cancel_reason->id);
2728 my $lids = $mgr->editor->search_acq_lineitem_detail([{
2729 "lineitem" => $li_id
2732 flesh_fields => { acqlid => ['eg_copy_id'] }
2735 my $result = {"lid" => {}};
2737 foreach my $lid (@$lids) {
2738 my $lid_result = cancel_lineitem_detail($mgr, $lid->id, $cancel_reason)
2741 # gathering any real copies for deletion
2742 if ($lid->eg_copy_id) {
2743 $lid->eg_copy_id->isdeleted('t');
2744 push @$copies, $lid->eg_copy_id;
2747 next if $lid_result == -1; # already canceled: just skip it.
2748 return $lid_result if not_cancelable($lid_result); # not cxlable: stop.
2750 # Merge in each LID result (there's only going to be one per call to
2751 # cancel_lineitem_detail).
2752 my ($k, $v) = each %{$lid_result->{"lid"}};
2753 $result->{"lid"}->{$k} = $v;
2756 # Attempt to delete the gathered copies (this will also handle volume deletion and bib deletion)
2757 # Delete empty bibs according org unit setting
2758 my $force_delete_empty_bib = $U->ou_ancestor_setting_value(
2759 $mgr->editor->requestor->ws_ou, 'cat.bib.delete_on_no_copy_via_acq_lineitem_cancel', $mgr->editor);
2760 if (scalar(@$copies)>0) {
2762 my $delete_stats = undef;
2763 my $retarget_holds = [];
2764 my $cat_evt = OpenILS::Application::Cat::AssetCommon->update_fleshed_copies(
2765 $mgr->editor, $override, undef, $copies, $delete_stats, $retarget_holds,$force_delete_empty_bib);
2768 $logger->info("fleshed copy update failed with event: ".OpenSRF::Utils::JSON->perl2JSON($cat_evt));
2769 return new OpenILS::Event(
2770 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id", "payload" => $cat_evt
2774 # We can't do the following and stay within the same transaction, but that's okay, the hold targeter will pick these up later.
2775 #my $ses = OpenSRF::AppSession->create('open-ils.circ');
2776 #$ses->request('open-ils.circ.hold.reset.batch', $auth, $retarget_holds);
2779 # if we have a bib, check to see whether it has been deleted. if so, cancel any active holds targeting that bib
2780 if ($li->eg_bib_id) {
2781 my $bib = $mgr->editor->retrieve_biblio_record_entry($li->eg_bib_id) or return new OpenILS::Event(
2782 "ACQ_NOT_CANCELABLE", "note" => "Could not retrieve bib " . $li->eg_bib_id . " for lineitem $li_id"
2784 if ($U->is_true($bib->deleted)) {
2785 my $holds = $mgr->editor->search_action_hold_request(
2786 { cancel_time => undef,
2787 fulfillment_time => undef,
2788 target => $li->eg_bib_id
2792 my %cached_usr_home_ou = ();
2794 for my $hold (@$holds) {
2796 $logger->info("Cancelling hold ".$hold->id.
2797 " due to acq lineitem cancellation.");
2799 $hold->cancel_time('now');
2800 $hold->cancel_cause(5); # 'Staff forced'--we may want a new hold cancel cause reason for this
2801 $hold->cancel_note('Corresponding Acquistion Lineitem/Purchase Order was cancelled.');
2802 unless($mgr->editor->update_action_hold_request($hold)) {
2803 my $evt = $mgr->editor->event;
2804 $logger->error("Error updating hold ". $evt->textcode .":". $evt->desc .":". $evt->stacktrace);
2805 return new OpenILS::Event(
2806 "ACQ_NOT_CANCELABLE", "note" => "Could not cancel hold " . $hold->id . " for lineitem $li_id", "payload" => $evt
2809 if (! defined $mgr->{post_commit}) { # we need a mechanism for creating trigger events, but only if the transaction gets committed
2810 $mgr->{post_commit} = [];
2812 push @{ $mgr->{post_commit} }, sub {
2813 my $home_ou = $cached_usr_home_ou{$hold->usr};
2815 my $user = $mgr->editor->retrieve_actor_user($hold->usr); # FIXME: how do we want to handle failures here?
2816 $home_ou = $user->home_ou;
2817 $cached_usr_home_ou{$hold->usr} = $home_ou;
2819 $U->create_events_for_hook('hold_request.cancel.cancelled_order', $hold, $home_ou);
2825 update_lineitem($mgr, $li) or return 0;
2828 "state" => $li->state,
2829 "cancel_reason" => $cancel_reason
2836 __PACKAGE__->register_method(
2837 method => "cancel_lineitem_detail_api",
2838 api_name => "open-ils.acq.lineitem_detail.cancel",
2840 desc => q/Cancels an on-order lineitem detail/,
2842 {desc => "Authentication token", type => "string"},
2843 {desc => "Lineitem detail ID to cancel", type => "number"},
2844 {desc => "Cancel reason ID", type => "number"}
2846 return => {desc => q/Object describing changed LIDs on success;
2851 sub cancel_lineitem_detail_api {
2852 my ($self, $conn, $auth, $lid_id, $cancel_reason) = @_;
2854 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2855 return $e->die_event unless $e->checkauth;
2856 my $mgr = new OpenILS::Application::Acq::BatchManager(
2857 "editor" => $e, "conn" => $conn
2860 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2861 return new OpenILS::Event(
2862 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2865 my $result = cancel_lineitem_detail($mgr, $lid_id, $cancel_reason) or
2866 return $e->die_event;
2868 if (not_cancelable($result)) {
2871 } elsif ($result == -1) {
2873 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2876 $e->commit or return $e->die_event;
2878 # XXX create lineitem detail status events?
2882 sub cancel_lineitem_detail {
2883 my ($mgr, $lid_id, $cancel_reason) = @_;
2884 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
2888 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
2893 # Depending on context, this may not warrant an event.
2894 return -1 if $lid->cancel_reason;
2896 # But this always does.
2897 return new OpenILS::Event(
2898 "ACQ_NOT_CANCELABLE", "note" => "lineitem_detail $lid_id"
2900 (! $lid->lineitem->purchase_order) or
2902 (not $lid->recv_time) and
2904 $lid->lineitem->purchase_order and (
2905 $lid->lineitem->state eq "on-order" or
2906 $lid->lineitem->state eq "pending-order"
2911 return 0 unless $mgr->editor->allowed(
2912 "CREATE_PURCHASE_ORDER",
2913 $lid->lineitem->purchase_order->ordering_agency
2914 ) or (! $lid->lineitem->purchase_order);
2916 $lid->cancel_reason($cancel_reason->id);
2918 unless($U->is_true($cancel_reason->keep_debits)) {
2919 my $debit_id = $lid->fund_debit;
2920 $lid->clear_fund_debit;
2923 # item is cancelled. Remove the fund debit.
2924 my $debit = $mgr->editor->retrieve_acq_fund_debit($debit_id);
2925 if (!$U->is_true($debit->encumbrance)) {
2926 $mgr->editor->rollback;
2927 return OpenILS::Event->new('ACQ_NOT_CANCELABLE',
2928 note => "Debit is marked as paid: $debit_id");
2930 $mgr->editor->delete_acq_fund_debit($debit) or return $mgr->editor->die_event;
2934 # XXX LIDs don't have either an editor or a edit_time field. Should we
2935 # update these on the LI when we alter an LID?
2936 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
2938 return {"lid" => {$lid_id => {"cancel_reason" => $cancel_reason}}};
2942 __PACKAGE__->register_method(
2943 method => 'user_requests',
2944 api_name => 'open-ils.acq.user_request.retrieve.by_user_id',
2947 desc => 'Retrieve fleshed user requests and related data for a given user.',
2949 { desc => 'Authentication token', type => 'string' },
2950 { desc => 'User ID of the owner, or array of IDs', },
2951 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
2956 desc => 'Fleshed user requests and related data',
2962 __PACKAGE__->register_method(
2963 method => 'user_requests',
2964 api_name => 'open-ils.acq.user_request.retrieve.by_home_ou',
2967 desc => 'Retrieve fleshed user requests and related data for a given org unit or units.',
2969 { desc => 'Authentication token', type => 'string' },
2970 { desc => 'Org unit ID, or array of IDs', },
2971 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
2976 desc => 'Fleshed user requests and related data',
2983 my($self, $conn, $auth, $search_value, $options) = @_;
2984 my $e = new_editor(authtoken => $auth);
2985 return $e->event unless $e->checkauth;
2986 my $rid = $e->requestor->id;
2990 "select"=>{"aur"=>["id"],"au"=>["home_ou", {column => 'id', alias => 'usr_id'} ]},
2991 "from"=>{ "aur" => { "au" => {}, "jub" => { "type" => "left" } } },
2995 {"id"=>undef}, # this with the left-join pulls in requests without lineitems
2996 {"state"=>["new","on-order","pending-order"]} # FIXME - probably needs softcoding
3000 "order_by"=>[{"class"=>"aur", "field"=>"request_date", "direction"=>"desc"}]
3003 foreach (qw/ order_by limit offset /) {
3004 $query->{$_} = $options->{$_} if defined $options->{$_};
3006 if (defined $options->{'state'}) {
3007 $query->{'where'}->{'+jub'}->{'-or'}->[1]->{'state'} = $options->{'state'};
3010 if ($self->api_name =~ /by_user_id/) {
3011 $query->{'where'}->{'usr'} = $search_value;
3013 $query->{'where'}->{'+au'} = { 'home_ou' => $search_value };
3016 my $pertinent_ids = $e->json_query($query);
3019 for my $id_blob (@$pertinent_ids) {
3020 if ($rid != $id_blob->{usr_id}) {
3021 if (!defined $perm_test{ $id_blob->{home_ou} }) {
3022 $perm_test{ $id_blob->{home_ou} } = $e->allowed( ['user_request.view'], $id_blob->{home_ou} );
3024 if (!$perm_test{ $id_blob->{home_ou} }) {
3028 my $aur_obj = $e->retrieve_acq_user_request([
3030 {flesh => 1, flesh_fields => { "aur" => [ 'lineitem' ] } }
3032 if (! $aur_obj) { next; }
3034 if ($aur_obj->lineitem()) {
3035 $aur_obj->lineitem()->clear_marc();
3037 $conn->respond($aur_obj);
3043 __PACKAGE__->register_method (
3044 method => 'update_user_request',
3045 api_name => 'open-ils.acq.user_request.cancel.batch',
3048 desc => 'If given a cancel reason, will update the request with that reason, otherwise, this will delete the request altogether. The ' .
3049 'intention is for staff interfaces or processes to provide cancel reasons, and for patron interfaces to just delete the requests.' ,
3051 { desc => 'Authentication token', type => 'string' },
3052 { desc => 'ID or array of IDs for the user requests to cancel' },
3053 { desc => 'Cancel Reason ID (optional)', type => 'string' }
3056 desc => 'progress object, event on error',
3060 __PACKAGE__->register_method (
3061 method => 'update_user_request',
3062 api_name => 'open-ils.acq.user_request.set_no_hold.batch',
3065 desc => 'Remove the hold from a user request or set of requests',
3067 { desc => 'Authentication token', type => 'string' },
3068 { desc => 'ID or array of IDs for the user requests to modify' }
3071 desc => 'progress object, event on error',
3076 sub update_user_request {
3077 my($self, $conn, $auth, $aur_ids, $cancel_reason) = @_;
3078 my $e = new_editor(xact => 1, authtoken => $auth);
3079 return $e->die_event unless $e->checkauth;
3080 my $rid = $e->requestor->id;
3084 for my $id (@$aur_ids) {
3086 my $aur_obj = $e->retrieve_acq_user_request([
3089 flesh_fields => { "aur" => ['lineitem', 'usr'] }
3091 ]) or return $e->die_event;
3093 my $context_org = $aur_obj->usr()->home_ou();
3094 $aur_obj->usr( $aur_obj->usr()->id() );
3096 if ($rid != $aur_obj->usr) {
3097 if (!defined $perm_test{ $context_org }) {
3098 $perm_test{ $context_org } = $e->allowed( ['user_request.update'], $context_org );
3100 if (!$perm_test{ $context_org }) {
3105 if($self->api_name =~ /set_no_hold/) {
3106 if ($U->is_true($aur_obj->hold)) {
3108 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3112 if($self->api_name =~ /cancel/) {
3113 if ( $cancel_reason ) {
3114 $aur_obj->cancel_reason( $cancel_reason );
3115 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3116 create_user_request_events( $e, [ $aur_obj ], 'aur.rejected' );
3118 $e->delete_acq_user_request($aur_obj);
3122 $conn->respond({maximum => scalar(@$aur_ids), progress => $x++});
3126 return {complete => 1};
3129 __PACKAGE__->register_method (
3130 method => 'new_user_request',
3131 api_name => 'open-ils.acq.user_request.create',
3133 desc => 'Create a new user request object in the DB',
3135 { desc => 'Authentication token', type => 'string' },
3136 { desc => 'User request data hash. Hash keys match the fields for the "aur" object', type => 'object' }
3139 desc => 'The created user request object, or event on error'
3144 sub new_user_request {
3145 my($self, $conn, $auth, $form_data) = @_;
3146 my $e = new_editor(xact => 1, authtoken => $auth);
3147 return $e->die_event unless $e->checkauth;
3148 my $rid = $e->requestor->id;
3149 my $target_user_fleshed;
3150 if (! defined $$form_data{'usr'}) {
3151 $$form_data{'usr'} = $rid;
3153 if ($$form_data{'usr'} != $rid) {
3154 # See if the requestor can place the request on behalf of a different user.
3155 $target_user_fleshed = $e->retrieve_actor_user($$form_data{'usr'}) or return $e->die_event;
3156 $e->allowed('user_request.create', $target_user_fleshed->home_ou) or return $e->die_event;
3158 $target_user_fleshed = $e->requestor;
3159 $e->allowed('CREATE_PURCHASE_REQUEST') or return $e->die_event;
3161 if (! defined $$form_data{'pickup_lib'}) {
3162 if ($target_user_fleshed->ws_ou) {
3163 $$form_data{'pickup_lib'} = $target_user_fleshed->ws_ou;
3165 $$form_data{'pickup_lib'} = $target_user_fleshed->home_ou;
3168 if (! defined $$form_data{'request_type'}) {
3169 $$form_data{'request_type'} = 1; # Books
3171 my $aur_obj = new Fieldmapper::acq::user_request;
3173 $aur_obj->usr( $$form_data{'usr'} );
3174 $aur_obj->request_date( 'now' );
3175 for my $field ( keys %$form_data ) {
3176 if (defined $$form_data{$field} and $field !~ /^(id|lineitem|eg_bib|request_date|cancel_reason)$/) {
3177 $aur_obj->$field( $$form_data{$field} );
3181 $aur_obj = $e->create_acq_user_request($aur_obj) or return $e->die_event;
3183 $e->commit and create_user_request_events( $e, [ $aur_obj ], 'aur.created' );
3188 sub create_user_request_events {
3189 my($e, $user_reqs, $hook) = @_;
3191 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
3194 my %cached_usr_home_ou = ();
3195 for my $user_req (@$user_reqs) {
3196 my $home_ou = $cached_usr_home_ou{$user_req->usr};
3198 my $user = $e->retrieve_actor_user($user_req->usr) or return $e->die_event;
3199 $home_ou = $user->home_ou;
3200 $cached_usr_home_ou{$user_req->usr} = $home_ou;
3202 my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $home_ou);
3211 __PACKAGE__->register_method(
3212 method => "po_note_CUD_batch",
3213 api_name => "open-ils.acq.po_note.cud.batch",
3216 desc => q/Manage purchase order notes/,
3218 {desc => "Authentication token", type => "string"},
3219 {desc => "List of po_notes to manage", type => "array"},
3221 return => {desc => "Stream of successfully managed objects"}
3225 sub po_note_CUD_batch {
3226 my ($self, $conn, $auth, $notes) = @_;
3228 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3229 return $e->die_event unless $e->checkauth;
3232 my $total = @$notes;
3235 foreach my $note (@$notes) {
3237 $note->editor($e->requestor->id);
3238 $note->edit_time("now");
3241 $note->creator($e->requestor->id);
3242 $note = $e->create_acq_po_note($note) or return $e->die_event;
3243 } elsif ($note->isdeleted) {
3244 $e->delete_acq_po_note($note) or return $e->die_event;
3245 } elsif ($note->ischanged) {
3246 $e->update_acq_po_note($note) or return $e->die_event;
3249 unless ($note->isdeleted) {
3250 $note = $e->retrieve_acq_po_note($note->id) or
3251 return $e->die_event;
3255 {"maximum" => $total, "progress" => ++$count, "note" => $note}
3259 $e->commit and $conn->respond_complete or return $e->die_event;
3263 # retrieves a lineitem, fleshes its PO and PL, checks perms
3264 sub fetch_and_check_li {
3267 my $perm_mode = shift || 'read';
3269 my $li = $e->retrieve_acq_lineitem([
3272 flesh_fields => {jub => ['purchase_order', 'picklist']}
3274 ]) or return $e->die_event;
3276 if(my $po = $li->purchase_order) {
3277 my $perms = ($perm_mode eq 'read') ? 'VIEW_PURCHASE_ORDER' : 'CREATE_PURCHASE_ORDER';
3278 return ($li, $e->die_event) unless $e->allowed($perms, $po->ordering_agency);
3280 } elsif(my $pl = $li->picklist) {
3281 my $perms = ($perm_mode eq 'read') ? 'VIEW_PICKLIST' : 'CREATE_PICKLIST';
3282 return ($li, $e->die_event) unless $e->allowed($perms, $pl->org_unit);
3289 __PACKAGE__->register_method(
3290 method => "clone_distrib_form",
3291 api_name => "open-ils.acq.distribution_formula.clone",
3294 desc => q/Clone a distribution formula/,
3296 {desc => "Authentication token", type => "string"},
3297 {desc => "Original formula ID", type => 'integer'},
3298 {desc => "Name of new formula", type => 'string'},
3300 return => {desc => "ID of newly created formula"}
3304 sub clone_distrib_form {
3305 my($self, $client, $auth, $form_id, $new_name) = @_;
3307 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3308 return $e->die_event unless $e->checkauth;
3310 my $old_form = $e->retrieve_acq_distribution_formula($form_id) or return $e->die_event;
3311 return $e->die_event unless $e->allowed('ADMIN_ACQ_DISTRIB_FORMULA', $old_form->owner);
3313 my $new_form = Fieldmapper::acq::distribution_formula->new;
3315 $new_form->owner($old_form->owner);
3316 $new_form->name($new_name);
3317 $e->create_acq_distribution_formula($new_form) or return $e->die_event;
3319 my $entries = $e->search_acq_distribution_formula_entry({formula => $form_id});
3320 for my $entry (@$entries) {
3321 my $new_entry = Fieldmapper::acq::distribution_formula_entry->new;
3322 $new_entry->$_($entry->$_()) for $entry->real_fields;
3323 $new_entry->formula($new_form->id);
3324 $new_entry->clear_id;
3325 $e->create_acq_distribution_formula_entry($new_entry) or return $e->die_event;
3329 return $new_form->id;
3332 __PACKAGE__->register_method(
3333 method => 'add_li_to_po',
3334 api_name => 'open-ils.acq.purchase_order.add_lineitem',
3336 desc => q/Adds a lineitem to an existing purchase order/,
3338 {desc => 'Authentication token', type => 'string'},
3339 {desc => 'The purchase order id', type => 'number'},
3340 {desc => 'The lineitem ID', type => 'number'},
3342 return => {desc => 'Streams a total versus completed counts object, event on error'}
3347 my($self, $conn, $auth, $po_id, $li_id) = @_;
3349 my $e = new_editor(authtoken => $auth, xact => 1);
3350 return $e->die_event unless $e->checkauth;
3352 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
3354 my $po = $e->retrieve_acq_purchase_order($po_id)
3355 or return $e->die_event;
3357 my $li = $e->retrieve_acq_lineitem($li_id)
3358 or return $e->die_event;
3360 return $e->die_event unless
3361 $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
3363 unless ($po->state =~ /new|pending/) {
3365 return {success => 0, po => $po, error => 'bad-po-state'};
3368 unless ($li->state =~ /new|order-ready|pending-order/) {
3370 return {success => 0, li => $li, error => 'bad-li-state'};
3373 $li->purchase_order($po_id);
3374 $li->state('pending-order');
3375 update_lineitem($mgr, $li) or return $e->die_event;
3378 return {success => 1};