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_action_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, $options) = @_;
766 unless($li->estimated_unit_price) {
767 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_PRICE', payload => $li->id));
768 $mgr->editor->rollback;
772 unless($li->provider) {
773 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_PROVIDER', payload => $li->id));
774 $mgr->editor->rollback;
778 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
779 {lineitem => $li->id},
783 if (@$lid_ids == 0 and !$options->{zero_copy_activate}) {
784 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_COPIES', payload => $li->id));
785 $mgr->editor->rollback;
789 for my $lid_id (@$lid_ids) {
791 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
794 flesh_fields => {acqlid => ['fund']}
798 create_lineitem_detail_debit($mgr, $li, $lid, $dry_run) or return 0;
807 sub create_lineitem_detail_debit {
808 my ($mgr, $li, $lid, $dry_run, $no_translate) = @_;
810 # don't create the debit if one already exists
811 return $mgr->editor->retrieve_acq_fund_debit($lid->fund_debit) if $lid->fund_debit;
813 my $li_id = ref($li) ? $li->id : $li;
815 unless(ref $li and ref $li->provider) {
816 $li = $mgr->editor->retrieve_acq_lineitem([
819 flesh_fields => {jub => ['provider']},
825 $lid->fund($mgr->editor->retrieve_acq_fund($lid->fund)) unless(ref $lid->fund);
827 $lid = $mgr->editor->retrieve_acq_lineitem_detail([
830 flesh_fields => {acqlid => ['fund']}
835 unless ($lid->fund) {
837 new OpenILS::Event("ACQ_FUND_NOT_FOUND") # close enough
842 my $amount = $li->estimated_unit_price;
843 if($li->provider->currency_type ne $lid->fund->currency_type and !$no_translate) {
845 # At Fund debit creation time, translate into the currency of the fund
846 # TODO: org setting to disable automatic currency conversion at debit create time?
848 $amount = $mgr->editor->json_query({
850 'acq.exchange_ratio',
851 $li->provider->currency_type, # source currency
852 $lid->fund->currency_type, # destination currency
853 $li->estimated_unit_price # source amount
855 })->[0]->{'acq.exchange_ratio'};
858 my $debit = create_fund_debit(
861 fund => $lid->fund->id,
862 origin_amount => $li->estimated_unit_price,
863 origin_currency_type => $li->provider->currency_type,
867 $lid->fund_debit($debit->id);
868 $lid->fund($lid->fund->id);
869 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
874 __PACKAGE__->register_method(
875 "method" => "fund_exceeds_balance_percent_api",
876 "api_name" => "open-ils.acq.fund.check_balance_percentages",
878 "desc" => q/Determine whether a given fund exceeds its defined
879 "balance stop and warning percentages"/,
881 {"desc" => "Authentication token", "type" => "string"},
882 {"desc" => "Fund ID", "type" => "number"},
883 {"desc" => "Theoretical debit amount (optional)",
886 "return" => {"desc" => q/An array of two values, for stop and warning,
887 in that order: 1 if fund exceeds that balance percentage, else 0/}
891 sub fund_exceeds_balance_percent_api {
892 my ($self, $conn, $auth, $fund_id, $debit_amount) = @_;
896 my $e = new_editor("authtoken" => $auth);
897 return $e->die_event unless $e->checkauth;
899 my $fund = $e->retrieve_acq_fund($fund_id) or return $e->die_event;
900 return $e->die_event unless $e->allowed("VIEW_FUND", $fund->org);
903 fund_exceeds_balance_percent($fund, $debit_amount, $e, "stop"),
904 fund_exceeds_balance_percent($fund, $debit_amount, $e, "warning")
911 sub fund_exceeds_balance_percent {
912 my ($fund, $debit_amount, $e, $which) = @_;
914 my ($method_name, $event_name) = @{{
916 "balance_warning_percent", "ACQ_FUND_EXCEEDS_WARN_PERCENT"
919 "balance_stop_percent", "ACQ_FUND_EXCEEDS_STOP_PERCENT"
923 if ($fund->$method_name) {
925 $e->search_acq_fund_combined_balance({"fund" => $fund->id})->[0];
927 $e->search_acq_fund_allocation_total({"fund" => $fund->id})->[0];
929 $balance = ($balance) ? $balance->amount : 0;
930 $allocations = ($allocations) ? $allocations->amount : 0;
933 $allocations == 0 || # if no allocations were ever made, assume we have hit the stop percent
934 ((($allocations - $balance + $debit_amount) / $allocations) * 100) > $fund->$method_name
936 $logger->info("fund would hit a limit: " . $fund->id . ", $balance, $debit_amount, $allocations, $method_name");
941 "fund" => $fund, "debit_amount" => $debit_amount
951 # ----------------------------------------------------------------------------
953 # ----------------------------------------------------------------------------
954 sub create_fund_debit {
955 my($mgr, $dry_run, %args) = @_;
957 # Verify the fund is not being spent beyond the hard stop amount
958 my $fund = $mgr->editor->retrieve_acq_fund($args{fund}) or return 0;
961 fund_exceeds_balance_percent(
962 $fund, $args{"amount"}, $mgr->editor, "stop"
965 $dry_run and fund_exceeds_balance_percent(
966 $fund, $args{"amount"}, $mgr->editor, "warning"
969 my $debit = Fieldmapper::acq::fund_debit->new;
970 $debit->debit_type('purchase');
971 $debit->encumbrance('t');
972 $debit->$_($args{$_}) for keys %args;
974 $mgr->add_debit($debit->amount);
975 return $mgr->editor->create_acq_fund_debit($debit);
979 # ----------------------------------------------------------------------------
981 # ----------------------------------------------------------------------------
982 sub create_picklist {
983 my($mgr, %args) = @_;
984 my $picklist = Fieldmapper::acq::picklist->new;
985 $picklist->creator($mgr->editor->requestor->id);
986 $picklist->owner($picklist->creator);
987 $picklist->editor($picklist->creator);
988 $picklist->create_time('now');
989 $picklist->edit_time('now');
990 $picklist->org_unit($mgr->editor->requestor->ws_ou);
991 $picklist->owner($mgr->editor->requestor->id);
992 $picklist->$_($args{$_}) for keys %args;
994 $mgr->picklist($picklist);
995 return $mgr->editor->create_acq_picklist($picklist);
998 sub update_picklist {
999 my($mgr, $picklist) = @_;
1000 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
1001 $picklist->edit_time('now');
1002 $picklist->editor($mgr->editor->requestor->id);
1003 if ($mgr->editor->update_acq_picklist($picklist)) {
1004 $picklist = $mgr->editor->retrieve_acq_picklist($mgr->editor->data);
1005 $mgr->picklist($picklist);
1012 sub delete_picklist {
1013 my($mgr, $picklist) = @_;
1014 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
1016 # delete all 'new' lineitems
1017 my $li_ids = $mgr->editor->search_acq_lineitem(
1019 picklist => $picklist->id,
1020 "-or" => {state => "new", purchase_order => undef}
1024 for my $li_id (@$li_ids) {
1025 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
1026 return 0 unless delete_lineitem($mgr, $li);
1030 # detach all non-'new' lineitems
1031 $li_ids = $mgr->editor->search_acq_lineitem({picklist => $picklist->id, state => {'!=' => 'new'}}, {idlist => 1});
1032 for my $li_id (@$li_ids) {
1033 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
1034 $li->clear_picklist;
1035 return 0 unless update_lineitem($mgr, $li);
1039 # remove any picklist-specific object perms
1040 my $ops = $mgr->editor->search_permission_usr_object_perm_map({object_type => 'acqpl', object_id => ''.$picklist->id});
1041 for my $op (@$ops) {
1042 return 0 unless $mgr->editor->delete_usr_object_perm_map($op);
1045 return $mgr->editor->delete_acq_picklist($picklist);
1048 # ----------------------------------------------------------------------------
1050 # ----------------------------------------------------------------------------
1051 sub update_purchase_order {
1053 $po = $mgr->editor->retrieve_acq_purchase_order($po) unless ref $po;
1054 $po->editor($mgr->editor->requestor->id);
1055 $po->edit_time('now');
1056 $mgr->purchase_order($po);
1057 return $mgr->editor->retrieve_acq_purchase_order($mgr->editor->data)
1058 if $mgr->editor->update_acq_purchase_order($po);
1062 sub create_purchase_order {
1063 my($mgr, %args) = @_;
1065 # verify the chosen provider is still active
1066 my $provider = $mgr->editor->retrieve_acq_provider($args{provider}) or return 0;
1067 unless($U->is_true($provider->active)) {
1068 $logger->error("provider is not active. cannot create PO");
1069 $mgr->editor->event(OpenILS::Event->new('ACQ_PROVIDER_INACTIVE'));
1073 my $po = Fieldmapper::acq::purchase_order->new;
1074 $po->creator($mgr->editor->requestor->id);
1075 $po->editor($mgr->editor->requestor->id);
1076 $po->owner($mgr->editor->requestor->id);
1077 $po->edit_time('now');
1078 $po->create_time('now');
1079 $po->state('pending');
1080 $po->ordering_agency($mgr->editor->requestor->ws_ou);
1081 $po->$_($args{$_}) for keys %args;
1083 $mgr->purchase_order($po);
1084 return $mgr->editor->create_acq_purchase_order($po);
1087 # ----------------------------------------------------------------------------
1088 # if all of the lineitems for this PO are received,
1089 # mark the PO as received
1090 # ----------------------------------------------------------------------------
1091 sub check_purchase_order_received {
1092 my($mgr, $po_id) = @_;
1094 my $non_recv_li = $mgr->editor->search_acq_lineitem(
1095 { purchase_order => $po_id,
1096 state => {'!=' => 'received'}
1099 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id);
1100 return $po if @$non_recv_li;
1102 $po->state('received');
1103 return update_purchase_order($mgr, $po);
1107 # ----------------------------------------------------------------------------
1108 # Bib, Callnumber, and Copy data
1109 # ----------------------------------------------------------------------------
1111 sub create_lineitem_assets {
1112 my($mgr, $li_id) = @_;
1115 my $li = $mgr->editor->retrieve_acq_lineitem([
1118 flesh_fields => {jub => ['purchase_order', 'attributes']}
1122 # note: at this point, the bib record this LI links to should already be created
1124 # -----------------------------------------------------------------
1125 # The lineitem is going live, promote user request holds to real holds
1126 # -----------------------------------------------------------------
1127 promote_lineitem_holds($mgr, $li) or return 0;
1129 my $li_details = $mgr->editor->search_acq_lineitem_detail({lineitem => $li_id}, {idlist=>1});
1131 # -----------------------------------------------------------------
1132 # for each lineitem_detail, create the volume if necessary, create
1133 # a copy, and link them all together.
1134 # -----------------------------------------------------------------
1136 for my $lid_id (@{$li_details}) {
1138 my $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid_id) or return 0;
1139 next if $lid->eg_copy_id;
1141 # use the same callnumber label for all items within this lineitem
1142 $lid->cn_label($first_cn) if $first_cn and not $lid->cn_label;
1144 # apply defaults if necessary
1145 return 0 unless complete_lineitem_detail($mgr, $lid);
1147 $first_cn = $lid->cn_label unless $first_cn;
1149 my $org = $lid->owning_lib;
1150 my $label = $lid->cn_label;
1151 my $bibid = $li->eg_bib_id;
1153 my $volume = $mgr->cache($org, "cn.$bibid.$label");
1155 $volume = create_volume($mgr, $li, $lid) or return 0;
1156 $mgr->cache($org, "cn.$bibid.$label", $volume);
1158 create_copy($mgr, $volume, $lid, $li) or return 0;
1161 return { li => $li };
1165 my($mgr, $li, $lid) = @_;
1167 my ($volume, $evt) =
1168 OpenILS::Application::Cat::AssetCommon->find_or_create_volume(
1176 $mgr->editor->event($evt);
1184 my($mgr, $volume, $lid, $li) = @_;
1185 my $copy = Fieldmapper::asset::copy->new;
1187 $copy->loan_duration(2);
1188 $copy->fine_level(2);
1189 $copy->status(($lid->recv_time) ? OILS_COPY_STATUS_IN_PROCESS : OILS_COPY_STATUS_ON_ORDER);
1190 $copy->barcode($lid->barcode);
1191 $copy->location($lid->location);
1192 $copy->call_number($volume->id);
1193 $copy->circ_lib($volume->owning_lib);
1194 $copy->circ_modifier($lid->circ_modifier);
1196 # AKA list price. We might need a $li->list_price field since
1197 # estimated price is not necessarily the same as list price
1198 $copy->price($li->estimated_unit_price);
1200 my $evt = OpenILS::Application::Cat::AssetCommon->create_copy($mgr->editor, $volume, $copy);
1202 $mgr->editor->event($evt);
1207 $lid->eg_copy_id($copy->id);
1208 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
1216 # ----------------------------------------------------------------------------
1217 # Workflow: Build a selection list from a Z39.50 search
1218 # ----------------------------------------------------------------------------
1220 __PACKAGE__->register_method(
1221 method => 'zsearch',
1222 api_name => 'open-ils.acq.picklist.search.z3950',
1225 desc => 'Performs a z3950 federated search and creates a picklist and associated lineitems',
1227 {desc => 'Authentication token', type => 'string'},
1228 {desc => 'Search definition', type => 'object'},
1229 {desc => 'Picklist name, optional', type => 'string'},
1235 my($self, $conn, $auth, $search, $name, $options) = @_;
1236 my $e = new_editor(authtoken=>$auth);
1237 return $e->event unless $e->checkauth;
1238 return $e->event unless $e->allowed('CREATE_PICKLIST');
1240 $search->{limit} ||= 10;
1243 my $ses = OpenSRF::AppSession->create('open-ils.search');
1244 my $req = $ses->request('open-ils.search.z3950.search_class', $auth, $search);
1249 while(my $resp = $req->recv(timeout=>60)) {
1252 my $e = new_editor(requestor=>$e->requestor, xact=>1);
1253 $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1254 $picklist = zsearch_build_pl($mgr, $name);
1258 my $result = $resp->content;
1259 my $count = $result->{count} || 0;
1260 $mgr->total( (($count < $search->{limit}) ? $count : $search->{limit})+1 );
1262 for my $rec (@{$result->{records}}) {
1264 my $li = create_lineitem($mgr,
1265 picklist => $picklist->id,
1266 source_label => $result->{service},
1267 marc => $rec->{marcxml},
1268 eg_bib_id => $rec->{bibid}
1271 if($$options{respond_li}) {
1272 $li->attributes($mgr->editor->search_acq_lineitem_attr({lineitem => $li->id}))
1273 if $$options{flesh_attrs};
1274 $li->clear_marc if $$options{clear_marc};
1275 $mgr->respond(lineitem => $li);
1282 $mgr->editor->commit;
1283 return $mgr->respond_complete;
1286 sub zsearch_build_pl {
1287 my($mgr, $name) = @_;
1290 my $picklist = $mgr->editor->search_acq_picklist({
1291 owner => $mgr->editor->requestor->id,
1295 if($name eq '' and $picklist) {
1296 return 0 unless delete_picklist($mgr, $picklist);
1300 return update_picklist($mgr, $picklist) if $picklist;
1301 return create_picklist($mgr, name => $name);
1305 # ----------------------------------------------------------------------------
1306 # Workflow: Build a selection list / PO by importing a batch of MARC records
1307 # ----------------------------------------------------------------------------
1309 __PACKAGE__->register_method(
1310 method => 'upload_records',
1311 api_name => 'open-ils.acq.process_upload_records',
1313 max_chunk_count => 1
1316 sub upload_records {
1317 my($self, $conn, $auth, $key, $args) = @_;
1320 my $e = new_editor(authtoken => $auth, xact => 1);
1321 return $e->die_event unless $e->checkauth;
1322 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1324 my $cache = OpenSRF::Utils::Cache->new;
1326 my $data = $cache->get_cache("vandelay_import_spool_$key");
1327 my $filename = $data->{path};
1328 my $provider = $args->{provider};
1329 my $picklist = $args->{picklist};
1330 my $create_po = $args->{create_po};
1331 my $activate_po = $args->{activate_po};
1332 my $vandelay = $args->{vandelay};
1333 my $ordering_agency = $args->{ordering_agency} || $e->requestor->ws_ou;
1337 unless(-r $filename) {
1338 $logger->error("unable to read MARC file $filename");
1340 return OpenILS::Event->new('FILE_UPLOAD_ERROR', payload => {filename => $filename});
1343 $provider = $e->retrieve_acq_provider($provider) or return $e->die_event;
1346 $picklist = $e->retrieve_acq_picklist($picklist) or return $e->die_event;
1347 if($picklist->owner != $e->requestor->id) {
1348 return $e->die_event unless
1349 $e->allowed('CREATE_PICKLIST', $picklist->org_unit, $picklist);
1351 $mgr->picklist($picklist);
1355 return $e->die_event unless
1356 $e->allowed('CREATE_PURCHASE_ORDER', $ordering_agency);
1358 $po = create_purchase_order($mgr,
1359 ordering_agency => $ordering_agency,
1360 provider => $provider->id,
1361 state => 'pending' # will be updated later if activated
1362 ) or return $mgr->editor->die_event;
1365 $logger->info("acq processing MARC file=$filename");
1367 my $batch = new MARC::Batch ('USMARC', $filename);
1375 my ($err, $xml, $r);
1380 } catch Error with {
1382 $logger->warn("Proccessing of record $count in set $key failed with error $err. Skipping this record");
1389 $xml = clean_marc($r);
1390 } catch Error with {
1392 $logger->warn("Proccessing XML of record $count in set $key failed with error $err. Skipping this record");
1395 next if $err or not $xml;
1398 source_label => $provider->code,
1399 provider => $provider->id,
1403 $args{picklist} = $picklist->id if $picklist;
1405 $args{purchase_order} = $po->id;
1406 $args{state} = 'pending-order';
1409 my $li = create_lineitem($mgr, %args) or return $mgr->editor->die_event;
1411 $li->provider($provider); # flesh it, we'll need it later
1413 import_lineitem_details($mgr, $ordering_agency, $li) or return $mgr->editor->die_event;
1416 push(@li_list, $li->id);
1422 $cache->delete_cache('vandelay_import_spool_' . $key);
1424 if ($po and $activate_po) {
1425 my $die_event = activate_purchase_order_impl($mgr, $po->id, $vandelay);
1426 return $die_event if $die_event;
1428 } elsif ($vandelay) {
1429 $vandelay->{new_rec_perm} = 'IMPORT_ACQ_LINEITEM_BIB_RECORD_UPLOAD';
1430 create_lineitem_list_assets($mgr, \@li_list, $vandelay,
1431 !$vandelay->{create_assets}) or return $e->die_event;
1434 return $mgr->respond_complete;
1437 sub import_lineitem_details {
1438 my($mgr, $ordering_agency, $li) = @_;
1440 my $holdings = $mgr->editor->json_query({from => ['acq.extract_provider_holding_data', $li->id]});
1441 return 1 unless @$holdings;
1442 my $org_path = $U->get_org_ancestors($ordering_agency);
1443 $org_path = [ reverse (@$org_path) ];
1449 # create a lineitem detail for each copy in the data
1451 my $compiled = extract_lineitem_detail_data($mgr, $org_path, $holdings, $idx);
1452 last unless defined $compiled;
1453 return 0 unless $compiled;
1455 # this takes the price of the last copy and uses it as the lineitem price
1456 # need to determine if a given record would include different prices for the same item
1457 $price = $$compiled{estimated_price};
1459 last unless $$compiled{quantity};
1461 for(1..$$compiled{quantity}) {
1462 my $lid = create_lineitem_detail(
1464 lineitem => $li->id,
1465 owning_lib => $$compiled{owning_lib},
1466 cn_label => $$compiled{call_number},
1467 fund => $$compiled{fund},
1468 circ_modifier => $$compiled{circ_modifier},
1469 note => $$compiled{note},
1470 location => $$compiled{copy_location},
1471 collection_code => $$compiled{collection_code},
1472 barcode => $$compiled{barcode}
1480 $li->estimated_unit_price($price);
1481 update_lineitem($mgr, $li) or return 0;
1485 # return hash on success, 0 on error, undef on no more holdings
1486 sub extract_lineitem_detail_data {
1487 my($mgr, $org_path, $holdings, $index) = @_;
1489 my @data_list = grep { $_->{holding} eq $index } @$holdings;
1490 return undef unless @data_list;
1492 my %compiled = map { $_->{attr} => $_->{data} } @data_list;
1493 my $base_org = $$org_path[0];
1497 $logger->error("Item import extraction error: $msg");
1498 $logger->error('Holdings Data: ' . OpenSRF::Utils::JSON->perl2JSON(\%compiled));
1499 $mgr->editor->rollback;
1500 $mgr->editor->event(OpenILS::Event->new('ACQ_IMPORT_ERROR', payload => $msg));
1504 # ---------------------------------------------------------------------
1506 if(my $code = $compiled{fund_code}) {
1508 my $fund = $mgr->cache($base_org, "fund.$code");
1510 # search up the org tree for the most appropriate fund
1511 for my $org (@$org_path) {
1512 $fund = $mgr->editor->search_acq_fund(
1513 {org => $org, code => $code, year => DateTime->now->year}, {idlist => 1})->[0];
1517 return $killme->("no fund with code $code at orgs [@$org_path]") unless $fund;
1518 $compiled{fund} = $fund;
1519 $mgr->cache($base_org, "fund.$code", $fund);
1523 # ---------------------------------------------------------------------
1525 if(my $sn = $compiled{owning_lib}) {
1526 my $org_id = $mgr->cache($base_org, "orgsn.$sn") ||
1527 $mgr->editor->search_actor_org_unit({shortname => $sn}, {idlist => 1})->[0];
1528 return $killme->("invalid owning_lib defined: $sn") unless $org_id;
1529 $compiled{owning_lib} = $org_id;
1530 $mgr->cache($$org_path[0], "orgsn.$sn", $org_id);
1534 # ---------------------------------------------------------------------
1536 my $code = $compiled{circ_modifier};
1540 # verify this is a valid circ modifier
1541 return $killme->("invlalid circ_modifier $code") unless
1542 defined $mgr->cache($base_org, "mod.$code") or
1543 $mgr->editor->retrieve_config_circ_modifier($code);
1545 # if valid, cache for future tests
1546 $mgr->cache($base_org, "mod.$code", $code);
1549 $compiled{circ_modifier} = get_default_circ_modifier($mgr, $base_org);
1553 # ---------------------------------------------------------------------
1555 if( my $name = $compiled{copy_location}) {
1556 my $loc = $mgr->cache($base_org, "copy_loc.$name");
1558 for my $org (@$org_path) {
1559 $loc = $mgr->editor->search_asset_copy_location(
1560 {owning_lib => $org, name => $name}, {idlist => 1})->[0];
1564 return $killme->("Invalid copy location $name") unless $loc;
1565 $compiled{copy_location} = $loc;
1566 $mgr->cache($base_org, "copy_loc.$name", $loc);
1574 # ----------------------------------------------------------------------------
1575 # Workflow: Given an existing purchase order, import/create the bibs,
1576 # callnumber and copy objects
1577 # ----------------------------------------------------------------------------
1579 __PACKAGE__->register_method(
1580 method => 'create_po_assets',
1581 api_name => 'open-ils.acq.purchase_order.assets.create',
1583 desc => q/Creates assets for each lineitem in the purchase order/,
1585 {desc => 'Authentication token', type => 'string'},
1586 {desc => 'The purchase order id', type => 'number'},
1588 return => {desc => 'Streams a total versus completed counts object, event on error'}
1590 max_chunk_count => 1
1593 sub create_po_assets {
1594 my($self, $conn, $auth, $po_id, $args) = @_;
1597 my $e = new_editor(authtoken=>$auth, xact=>1);
1598 return $e->die_event unless $e->checkauth;
1599 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1601 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1603 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1605 # it's ugly, but it's fast. Get the total count of lineitem detail objects to process
1606 my $lid_total = $e->json_query({
1607 select => { acqlid => [{aggregate => 1, transform => 'count', column => 'id'}] },
1613 join => {acqpo => {fkey => 'purchase_order', field => 'id'}}
1617 where => {'+acqpo' => {id => $po_id}}
1620 $mgr->total(scalar(@$li_ids) + $lid_total);
1622 create_lineitem_list_assets($mgr, $li_ids, $args->{vandelay})
1623 or return $e->die_event;
1626 update_purchase_order($mgr, $po) or return $e->die_event;
1629 return $mgr->respond_complete;
1634 __PACKAGE__->register_method(
1635 method => 'create_purchase_order_api',
1636 api_name => 'open-ils.acq.purchase_order.create',
1638 desc => 'Creates a new purchase order',
1640 {desc => 'Authentication token', type => 'string'},
1641 {desc => 'purchase_order to create', type => 'object'}
1643 return => {desc => 'The purchase order id, Event on failure'}
1645 max_chunk_count => 1
1648 sub create_purchase_order_api {
1649 my($self, $conn, $auth, $po, $args) = @_;
1652 my $e = new_editor(xact=>1, authtoken=>$auth);
1653 return $e->die_event unless $e->checkauth;
1654 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
1655 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1658 my %pargs = (ordering_agency => $e->requestor->ws_ou); # default
1659 $pargs{provider} = $po->provider if $po->provider;
1660 $pargs{ordering_agency} = $po->ordering_agency if $po->ordering_agency;
1661 $pargs{prepayment_required} = $po->prepayment_required if $po->prepayment_required;
1662 my $vandelay = $args->{vandelay};
1664 $po = create_purchase_order($mgr, %pargs) or return $e->die_event;
1666 my $li_ids = $$args{lineitems};
1670 for my $li_id (@$li_ids) {
1672 my $li = $e->retrieve_acq_lineitem([
1674 {flesh => 1, flesh_fields => {jub => ['attributes']}}
1675 ]) or return $e->die_event;
1677 $li->provider($po->provider);
1678 $li->purchase_order($po->id);
1679 $li->state('pending-order');
1680 update_lineitem($mgr, $li) or return $e->die_event;
1685 # commit before starting the asset creation
1688 if($li_ids and $vandelay) {
1689 create_lineitem_list_assets($mgr, $li_ids, $vandelay, !$$args{create_assets}) or return $e->die_event;
1692 return $mgr->respond_complete;
1697 __PACKAGE__->register_method(
1698 method => 'update_lineitem_fund_batch',
1699 api_name => 'open-ils.acq.lineitem.fund.update.batch',
1702 desc => q/Given a set of lineitem IDS, updates the fund for all attached lineitem details/
1706 sub update_lineitem_fund_batch {
1707 my($self, $conn, $auth, $li_ids, $fund_id) = @_;
1708 my $e = new_editor(xact=>1, authtoken=>$auth);
1709 return $e->die_event unless $e->checkauth;
1710 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1711 for my $li_id (@$li_ids) {
1712 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
1713 return $evt if $evt;
1714 my $li_details = $e->search_acq_lineitem_detail({lineitem => $li_id});
1715 $_->fund($fund_id) and $_->ischanged(1) for @$li_details;
1716 $evt = lineitem_detail_CUD_batch($mgr, $li_details);
1717 return $evt if $evt;
1722 return $mgr->respond_complete;
1727 __PACKAGE__->register_method(
1728 method => 'lineitem_detail_CUD_batch_api',
1729 api_name => 'open-ils.acq.lineitem_detail.cud.batch',
1732 desc => q/Creates a new purchase order line item detail. / .
1733 q/Additionally creates the associated fund_debit/,
1735 {desc => 'Authentication token', type => 'string'},
1736 {desc => 'List of lineitem_details to create', type => 'array'},
1737 {desc => 'Create Debits. Used for creating post-po-asset-creation debits', type => 'bool'},
1739 return => {desc => 'Streaming response of current position in the array'}
1743 __PACKAGE__->register_method(
1744 method => 'lineitem_detail_CUD_batch_api',
1745 api_name => 'open-ils.acq.lineitem_detail.cud.batch.dry_run',
1749 Dry run version of open-ils.acq.lineitem_detail.cud.batch.
1750 In dry_run mode, updated fund_debit's the exceed the warning
1751 percent return an event.
1757 sub lineitem_detail_CUD_batch_api {
1758 my($self, $conn, $auth, $li_details, $create_debits) = @_;
1759 my $e = new_editor(xact=>1, authtoken=>$auth);
1760 return $e->die_event unless $e->checkauth;
1761 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1762 my $dry_run = ($self->api_name =~ /dry_run/o);
1763 my $evt = lineitem_detail_CUD_batch($mgr, $li_details, $create_debits, $dry_run);
1764 return $evt if $evt;
1766 return $mgr->respond_complete;
1770 sub lineitem_detail_CUD_batch {
1771 my($mgr, $li_details, $create_debits, $dry_run) = @_;
1773 $mgr->total(scalar(@$li_details));
1774 my $e = $mgr->editor;
1778 my $fund_cache = {};
1781 for my $lid (@$li_details) {
1783 unless($li = $li_cache{$lid->lineitem}) {
1784 ($li, $evt) = fetch_and_check_li($e, $lid->lineitem, 'write');
1785 return $evt if $evt;
1789 $lid = create_lineitem_detail($mgr, %{$lid->to_bare_hash}) or return $e->die_event;
1790 if($create_debits) {
1791 $li->provider($e->retrieve_acq_provider($li->provider)) or return $e->die_event;
1792 $lid->fund($e->retrieve_acq_fund($lid->fund)) or return $e->die_event;
1793 create_lineitem_detail_debit($mgr, $li, $lid, 0, 1) or return $e->die_event;
1796 } elsif($lid->ischanged) {
1797 return $evt if $evt = handle_changed_lid($e, $lid, $dry_run, $fund_cache);
1799 } elsif($lid->isdeleted) {
1800 delete_lineitem_detail($mgr, $lid) or return $e->die_event;
1803 $mgr->respond(li => $li);
1804 $li_cache{$lid->lineitem} = $li;
1810 sub handle_changed_lid {
1811 my($e, $lid, $dry_run, $fund_cache) = @_;
1813 my $orig_lid = $e->retrieve_acq_lineitem_detail($lid->id) or return $e->die_event;
1815 # updating the fund, so update the debit
1816 if($orig_lid->fund_debit and $orig_lid->fund != $lid->fund) {
1818 my $debit = $e->retrieve_acq_fund_debit($orig_lid->fund_debit);
1819 my $new_fund = $$fund_cache{$lid->fund} =
1820 $$fund_cache{$lid->fund} || $e->retrieve_acq_fund($lid->fund);
1822 # check the thresholds
1823 return $e->die_event if
1824 fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "stop");
1825 return $e->die_event if $dry_run and
1826 fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "warning");
1828 $debit->fund($new_fund->id);
1829 $e->update_acq_fund_debit($debit) or return $e->die_event;
1832 $e->update_acq_lineitem_detail($lid) or return $e->die_event;
1837 __PACKAGE__->register_method(
1838 method => 'receive_po_api',
1839 api_name => 'open-ils.acq.purchase_order.receive'
1842 sub receive_po_api {
1843 my($self, $conn, $auth, $po_id) = @_;
1844 my $e = new_editor(xact => 1, authtoken => $auth);
1845 return $e->die_event unless $e->checkauth;
1846 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1848 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1849 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1851 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1853 for my $li_id (@$li_ids) {
1854 receive_lineitem($mgr, $li_id) or return $e->die_event;
1858 $po->state('received');
1859 update_purchase_order($mgr, $po) or return $e->die_event;
1862 return $mgr->respond_complete;
1866 # At the moment there's a lack of parallelism between the receive and unreceive
1867 # API methods for POs and the API methods for LIs and LIDs. The methods for
1868 # POs stream back objects as they act, whereas the methods for LIs and LIDs
1869 # atomically return an object that describes only what changed (in LIs and LIDs
1870 # themselves or in the objects to which to LIs and LIDs belong).
1872 # The methods for LIs and LIDs work the way they do to faciliate the UI's
1873 # maintaining correct information about the state of these things when a user
1874 # wants to receive or unreceive these objects without refreshing their whole
1875 # display. The UI feature for receiving and un-receiving a whole PO just
1876 # refreshes the whole display, so this absence of parallelism in the UI is also
1877 # relected in this module.
1879 # This could be neatened in the future by making POs receive and unreceive in
1880 # the same way the LIs and LIDs do.
1882 __PACKAGE__->register_method(
1883 method => 'receive_lineitem_detail_api',
1884 api_name => 'open-ils.acq.lineitem_detail.receive',
1886 desc => 'Mark a lineitem_detail as received',
1888 {desc => 'Authentication token', type => 'string'},
1889 {desc => 'lineitem detail ID', type => 'number'}
1892 "on success, object describing changes to LID and possibly " .
1893 "to LI and PO; on error, Event"
1898 sub receive_lineitem_detail_api {
1899 my($self, $conn, $auth, $lid_id) = @_;
1901 my $e = new_editor(xact=>1, authtoken=>$auth);
1902 return $e->die_event unless $e->checkauth;
1903 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1906 "flesh" => 2, "flesh_fields" => {
1907 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
1911 my $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1913 return $e->die_event unless $e->allowed(
1914 'RECEIVE_PURCHASE_ORDER', $lid->lineitem->purchase_order->ordering_agency);
1917 my $recvd = receive_lineitem_detail($mgr, $lid_id) or return $e->die_event;
1919 # .. and re-retrieve
1920 $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1922 # Now build result data structure.
1923 my $result = {"lid" => {$lid->id => {"recv_time" => $lid->recv_time}}};
1926 if ($recvd->class_name =~ /::purchase_order/) {
1927 $result->{"po"} = describe_affected_po($e, $recvd);
1929 $lid->lineitem->id => {"state" => $lid->lineitem->state}
1931 } elsif ($recvd->class_name =~ /::lineitem/) {
1932 $result->{"li"} = {$recvd->id => {"state" => $recvd->state}};
1936 describe_affected_po($e, $lid->lineitem->purchase_order);
1942 __PACKAGE__->register_method(
1943 method => 'receive_lineitem_api',
1944 api_name => 'open-ils.acq.lineitem.receive',
1946 desc => 'Mark a lineitem as received',
1948 {desc => 'Authentication token', type => 'string'},
1949 {desc => 'lineitem ID', type => 'number'}
1952 "on success, object describing changes to LI and possibly PO; " .
1958 sub receive_lineitem_api {
1959 my($self, $conn, $auth, $li_id) = @_;
1961 my $e = new_editor(xact=>1, authtoken=>$auth);
1962 return $e->die_event unless $e->checkauth;
1963 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1965 my $li = $e->retrieve_acq_lineitem([
1969 jub => ['purchase_order']
1972 ]) or return $e->die_event;
1974 return $e->die_event unless $e->allowed(
1975 'RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);
1977 my $res = receive_lineitem($mgr, $li_id) or return $e->die_event;
1979 $conn->respond_complete($res);
1980 $mgr->run_post_response_hooks
1984 __PACKAGE__->register_method(
1985 method => 'rollback_receive_po_api',
1986 api_name => 'open-ils.acq.purchase_order.receive.rollback'
1989 sub rollback_receive_po_api {
1990 my($self, $conn, $auth, $po_id) = @_;
1991 my $e = new_editor(xact => 1, authtoken => $auth);
1992 return $e->die_event unless $e->checkauth;
1993 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1995 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1996 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1998 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
2000 for my $li_id (@$li_ids) {
2001 rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
2005 $po->state('on-order');
2006 update_purchase_order($mgr, $po) or return $e->die_event;
2009 return $mgr->respond_complete;
2013 __PACKAGE__->register_method(
2014 method => 'rollback_receive_lineitem_detail_api',
2015 api_name => 'open-ils.acq.lineitem_detail.receive.rollback',
2017 desc => 'Mark a lineitem_detail as Un-received',
2019 {desc => 'Authentication token', type => 'string'},
2020 {desc => 'lineitem detail ID', type => 'number'}
2023 "on success, object describing changes to LID and possibly " .
2024 "to LI and PO; on error, Event"
2029 sub rollback_receive_lineitem_detail_api {
2030 my($self, $conn, $auth, $lid_id) = @_;
2032 my $e = new_editor(xact=>1, authtoken=>$auth);
2033 return $e->die_event unless $e->checkauth;
2034 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2036 my $lid = $e->retrieve_acq_lineitem_detail([
2040 acqlid => ['lineitem'],
2041 jub => ['purchase_order']
2045 my $li = $lid->lineitem;
2046 my $po = $li->purchase_order;
2048 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2052 my $recvd = rollback_receive_lineitem_detail($mgr, $lid_id)
2053 or return $e->die_event;
2056 $result->{"lid"} = {$recvd->id => {"recv_time" => $recvd->recv_time}};
2058 $result->{"lid"} = {$lid->id => {"recv_time" => $lid->recv_time}};
2061 if ($li->state eq "received") {
2062 $li->state("on-order");
2063 $li = update_lineitem($mgr, $li) or return $e->die_event;
2064 $result->{"li"} = {$li->id => {"state" => $li->state}};
2067 if ($po->state eq "received") {
2068 $po->state("on-order");
2069 $po = update_purchase_order($mgr, $po) or return $e->die_event;
2071 $result->{"po"} = describe_affected_po($e, $po);
2073 $e->commit and return $result or return $e->die_event;
2076 __PACKAGE__->register_method(
2077 method => 'rollback_receive_lineitem_api',
2078 api_name => 'open-ils.acq.lineitem.receive.rollback',
2080 desc => 'Mark a lineitem as Un-received',
2082 {desc => 'Authentication token', type => 'string'},
2083 {desc => 'lineitem ID', type => 'number'}
2086 "on success, object describing changes to LI and possibly PO; " .
2092 sub rollback_receive_lineitem_api {
2093 my($self, $conn, $auth, $li_id) = @_;
2095 my $e = new_editor(xact=>1, authtoken=>$auth);
2096 return $e->die_event unless $e->checkauth;
2097 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2099 my $li = $e->retrieve_acq_lineitem([
2101 "flesh" => 1, "flesh_fields" => {"jub" => ["purchase_order"]}
2104 my $po = $li->purchase_order;
2106 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2108 $li = rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
2110 my $result = {"li" => {$li->id => {"state" => $li->state}}};
2111 if ($po->state eq "received") {
2112 $po->state("on-order");
2113 $po = update_purchase_order($mgr, $po) or return $e->die_event;
2115 $result->{"po"} = describe_affected_po($e, $po);
2117 $e->commit and return $result or return $e->die_event;
2121 __PACKAGE__->register_method(
2122 method => 'set_lineitem_price_api',
2123 api_name => 'open-ils.acq.lineitem.price.set',
2125 desc => 'Set lineitem price. If debits already exist, update them as well',
2127 {desc => 'Authentication token', type => 'string'},
2128 {desc => 'lineitem ID', type => 'number'}
2130 return => {desc => 'status blob, Event on error'}
2134 sub set_lineitem_price_api {
2135 my($self, $conn, $auth, $li_id, $price) = @_;
2137 my $e = new_editor(xact=>1, authtoken=>$auth);
2138 return $e->die_event unless $e->checkauth;
2139 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2141 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
2142 return $evt if $evt;
2144 $li->estimated_unit_price($price);
2145 update_lineitem($mgr, $li) or return $e->die_event;
2147 my $lid_ids = $e->search_acq_lineitem_detail(
2148 {lineitem => $li_id, fund_debit => {'!=' => undef}},
2152 for my $lid_id (@$lid_ids) {
2154 my $lid = $e->retrieve_acq_lineitem_detail([
2156 flesh => 1, flesh_fields => {acqlid => ['fund', 'fund_debit']}}
2159 $lid->fund_debit->amount($price);
2160 $e->update_acq_fund_debit($lid->fund_debit) or return $e->die_event;
2166 return $mgr->respond_complete;
2170 __PACKAGE__->register_method(
2171 method => 'clone_picklist_api',
2172 api_name => 'open-ils.acq.picklist.clone',
2174 desc => 'Clones a picklist, including lineitem and lineitem details',
2176 {desc => 'Authentication token', type => 'string'},
2177 {desc => 'Picklist ID', type => 'number'},
2178 {desc => 'New Picklist Name', type => 'string'}
2180 return => {desc => 'status blob, Event on error'}
2184 sub clone_picklist_api {
2185 my($self, $conn, $auth, $pl_id, $name) = @_;
2187 my $e = new_editor(xact=>1, authtoken=>$auth);
2188 return $e->die_event unless $e->checkauth;
2189 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2191 my $old_pl = $e->retrieve_acq_picklist($pl_id);
2192 my $new_pl = create_picklist($mgr, %{$old_pl->to_bare_hash}, name => $name) or return $e->die_event;
2194 my $li_ids = $e->search_acq_lineitem({picklist => $pl_id}, {idlist => 1});
2196 # get the current user
2197 my $cloner = $mgr->editor->requestor->id;
2199 for my $li_id (@$li_ids) {
2201 # copy the lineitems' MARC
2202 my $marc = ($e->retrieve_acq_lineitem($li_id))->marc;
2204 # create a skeletal clone of the item
2205 my $li = Fieldmapper::acq::lineitem->new;
2206 $li->creator($cloner);
2207 $li->selector($cloner);
2208 $li->editor($cloner);
2211 my $new_li = create_lineitem($mgr, %{$li->to_bare_hash}, picklist => $new_pl->id) or return $e->die_event;
2217 return $mgr->respond_complete;
2221 __PACKAGE__->register_method(
2222 method => 'merge_picklist_api',
2223 api_name => 'open-ils.acq.picklist.merge',
2225 desc => 'Merges 2 or more picklists into a single list',
2227 {desc => 'Authentication token', type => 'string'},
2228 {desc => 'Lead Picklist ID', type => 'number'},
2229 {desc => 'List of subordinate picklist IDs', type => 'array'}
2231 return => {desc => 'status blob, Event on error'}
2235 sub merge_picklist_api {
2236 my($self, $conn, $auth, $lead_pl, $pl_list) = @_;
2238 my $e = new_editor(xact=>1, authtoken=>$auth);
2239 return $e->die_event unless $e->checkauth;
2240 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2242 # XXX perms on each picklist modified
2244 $lead_pl = $e->retrieve_acq_picklist($lead_pl) or return $e->die_event;
2245 # point all of the lineitems at the lead picklist
2246 my $li_ids = $e->search_acq_lineitem({picklist => $pl_list}, {idlist => 1});
2248 for my $li_id (@$li_ids) {
2249 my $li = $e->retrieve_acq_lineitem($li_id);
2250 $li->picklist($lead_pl);
2251 update_lineitem($mgr, $li) or return $e->die_event;
2255 # now delete the subordinate lists
2256 for my $pl_id (@$pl_list) {
2257 my $pl = $e->retrieve_acq_picklist($pl_id);
2258 $e->delete_acq_picklist($pl) or return $e->die_event;
2261 update_picklist($mgr, $lead_pl) or return $e->die_event;
2264 return $mgr->respond_complete;
2268 __PACKAGE__->register_method(
2269 method => 'delete_picklist_api',
2270 api_name => 'open-ils.acq.picklist.delete',
2272 desc => q/Deletes a picklist. It also deletes any lineitems in the "new" state. / .
2273 q/Other attached lineitems are detached/,
2275 {desc => 'Authentication token', type => 'string'},
2276 {desc => 'Picklist ID to delete', type => 'number'}
2278 return => {desc => '1 on success, Event on error'}
2282 sub delete_picklist_api {
2283 my($self, $conn, $auth, $picklist_id) = @_;
2284 my $e = new_editor(xact=>1, authtoken=>$auth);
2285 return $e->die_event unless $e->checkauth;
2286 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2287 my $pl = $e->retrieve_acq_picklist($picklist_id) or return $e->die_event;
2288 delete_picklist($mgr, $pl) or return $e->die_event;
2290 return $mgr->respond_complete;
2295 __PACKAGE__->register_method(
2296 method => 'activate_purchase_order',
2297 api_name => 'open-ils.acq.purchase_order.activate.dry_run'
2300 __PACKAGE__->register_method(
2301 method => 'activate_purchase_order',
2302 api_name => 'open-ils.acq.purchase_order.activate',
2304 desc => q/Activates a purchase order. This updates the status of the PO / .
2305 q/and Lineitems to 'on-order'. Activated PO's are ready for EDI delivery if appropriate./,
2307 {desc => 'Authentication token', type => 'string'},
2308 {desc => 'Purchase ID', type => 'number'}
2310 return => {desc => '1 on success, Event on error'}
2314 sub activate_purchase_order {
2315 my($self, $conn, $auth, $po_id, $vandelay, $options) = @_;
2318 my $dry_run = ($self->api_name =~ /\.dry_run/) ? 1 : 0;
2319 my $e = new_editor(authtoken=>$auth);
2320 return $e->die_event unless $e->checkauth;
2321 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2322 my $die_event = activate_purchase_order_impl($mgr, $po_id, $vandelay, $dry_run, $options);
2323 return $e->die_event if $die_event;
2324 $conn->respond_complete(1);
2325 $mgr->run_post_response_hooks unless $dry_run;
2329 # xacts managed within
2330 sub activate_purchase_order_impl {
2331 my ($mgr, $po_id, $vandelay, $dry_run, $options) = @_;
2333 # read-only until lineitem asset creation
2334 my $e = $mgr->editor;
2337 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2338 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
2340 return $e->die_event(OpenILS::Event->new('PO_ALREADY_ACTIVATED'))
2341 if $po->order_date; # PO cannot be re-activated
2343 my $provider = $e->retrieve_acq_provider($po->provider);
2345 # find lineitems and create assets for all
2348 purchase_order => $po_id,
2349 state => [qw/pending-order new order-ready/]
2352 my $li_ids = $e->search_acq_lineitem($query, {idlist => 1});
2354 my $vl_resp; # imported li's and the queue the managing queue
2356 $e->rollback; # read-only thus far
2357 $vl_resp = create_lineitem_list_assets($mgr, $li_ids, $vandelay)
2358 or return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED');
2362 # create fund debits for lineitems
2364 for my $li_id (@$li_ids) {
2365 my $li = $e->retrieve_acq_lineitem($li_id);
2367 if (!$li->eg_bib_id and !$dry_run) {
2368 # we encountered a lineitem that was not successfully imported.
2369 # we cannot continue. rollback and report.
2371 return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED', {queue => $vl_resp->{queue}});
2374 $li->state('on-order');
2375 $li->claim_policy($provider->default_claim_policy)
2376 if $provider->default_claim_policy and !$li->claim_policy;
2377 create_lineitem_debits($mgr, $li, $dry_run, $options) or return $e->die_event;
2378 update_lineitem($mgr, $li) or return $e->die_event;
2379 $mgr->post_process( sub { create_lineitem_status_events($mgr, $li->id, 'aur.ordered'); });
2383 # create po-item debits
2385 for my $po_item (@{$e->search_acq_po_item({purchase_order => $po_id})}) {
2387 my $debit = create_fund_debit(
2390 debit_type => 'direct_charge', # to match invoicing
2391 origin_amount => $po_item->estimated_cost,
2392 origin_currency_type => $e->retrieve_acq_fund($po_item->fund)->currency_type,
2393 amount => $po_item->estimated_cost,
2394 fund => $po_item->fund
2395 ) or return $e->die_event;
2396 $po_item->fund_debit($debit->id);
2397 $e->update_acq_po_item($po_item) or return $e->die_event;
2401 # mark PO as ordered
2403 $po->state('on-order');
2404 $po->order_date('now');
2405 update_purchase_order($mgr, $po) or return $e->die_event;
2408 $dry_run and $e->rollback or $e->commit;
2410 # tell the world we activated a PO
2411 $U->create_events_for_hook('acqpo.activated', $po, $po->ordering_agency) unless $dry_run;
2417 __PACKAGE__->register_method(
2418 method => 'split_purchase_order_by_lineitems',
2419 api_name => 'open-ils.acq.purchase_order.split_by_lineitems',
2421 desc => q/Splits a PO into many POs, 1 per lineitem. Only works for / .
2422 q/POs a) with more than one lineitems, and b) in the "pending" state./,
2424 {desc => 'Authentication token', type => 'string'},
2425 {desc => 'Purchase order ID', type => 'number'}
2427 return => {desc => 'list of new PO IDs on success, Event on error'}
2431 sub split_purchase_order_by_lineitems {
2432 my ($self, $conn, $auth, $po_id) = @_;
2434 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2435 return $e->die_event unless $e->checkauth;
2437 my $po = $e->retrieve_acq_purchase_order([
2440 "flesh_fields" => {"acqpo" => [qw/lineitems notes/]}
2442 ]) or return $e->die_event;
2444 return $e->die_event
2445 unless $e->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2447 unless ($po->state eq "pending") {
2449 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_LATE");
2452 unless (@{$po->lineitems} > 1) {
2454 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_SHORT");
2457 # To split an existing PO into many, it seems unwise to just delete the
2458 # original PO, so we'll instead detach all of the original POs' lineitems
2459 # but the first, then create new POs for each of the remaining LIs, and
2460 # then attach the LIs to their new POs.
2462 my @po_ids = ($po->id);
2463 my @moving_li = @{$po->lineitems};
2464 shift @moving_li; # discard first LI
2466 foreach my $li (@moving_li) {
2467 my $new_po = $po->clone;
2469 $new_po->clear_name;
2470 $new_po->creator($e->requestor->id);
2471 $new_po->editor($e->requestor->id);
2472 $new_po->owner($e->requestor->id);
2473 $new_po->edit_time("now");
2474 $new_po->create_time("now");
2476 $new_po = $e->create_acq_purchase_order($new_po);
2478 # Clone any notes attached to the old PO and attach to the new one.
2479 foreach my $note (@{$po->notes}) {
2480 my $new_note = $note->clone;
2481 $new_note->clear_id;
2482 $new_note->edit_time("now");
2483 $new_note->purchase_order($new_po->id);
2484 $e->create_acq_po_note($new_note);
2487 $li->edit_time("now");
2488 $li->purchase_order($new_po->id);
2489 $e->update_acq_lineitem($li);
2491 push @po_ids, $new_po->id;
2494 $po->edit_time("now");
2495 $e->update_acq_purchase_order($po);
2497 return \@po_ids if $e->commit;
2498 return $e->die_event;
2502 sub not_cancelable {
2504 (ref $o eq "HASH" and $o->{"textcode"} eq "ACQ_NOT_CANCELABLE");
2507 __PACKAGE__->register_method(
2508 method => "cancel_purchase_order_api",
2509 api_name => "open-ils.acq.purchase_order.cancel",
2511 desc => q/Cancels an on-order purchase order/,
2513 {desc => "Authentication token", type => "string"},
2514 {desc => "PO ID to cancel", type => "number"},
2515 {desc => "Cancel reason ID", type => "number"}
2517 return => {desc => q/Object describing changed POs, LIs and LIDs
2518 on success; Event on error./}
2522 sub cancel_purchase_order_api {
2523 my ($self, $conn, $auth, $po_id, $cancel_reason) = @_;
2525 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2526 return $e->die_event unless $e->checkauth;
2527 my $mgr = new OpenILS::Application::Acq::BatchManager(
2528 "editor" => $e, "conn" => $conn
2531 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2532 return new OpenILS::Event(
2533 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2536 my $result = cancel_purchase_order($mgr, $po_id, $cancel_reason) or
2537 return $e->die_event;
2538 if (not_cancelable($result)) { # event not from CStoreEditor
2541 } elsif ($result == -1) {
2543 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2546 $e->commit or return $e->die_event;
2548 # XXX create purchase order status events?
2550 if ($mgr->{post_commit}) {
2551 foreach my $func (@{$mgr->{post_commit}}) {
2559 sub cancel_purchase_order {
2560 my ($mgr, $po_id, $cancel_reason) = @_;
2562 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id) or return 0;
2564 # XXX is "cancelled" a typo? It's not correct US spelling, anyway.
2565 # Depending on context, this may not warrant an event.
2566 return -1 if $po->state eq "cancelled";
2568 # But this always does.
2569 return new OpenILS::Event(
2570 "ACQ_NOT_CANCELABLE", "note" => "purchase_order $po_id"
2571 ) unless ($po->state eq "on-order" or $po->state eq "pending");
2574 $mgr->editor->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2576 $po->state("cancelled");
2577 $po->cancel_reason($cancel_reason->id);
2579 my $li_ids = $mgr->editor->search_acq_lineitem(
2580 {"purchase_order" => $po_id}, {"idlist" => 1}
2583 my $result = {"li" => {}, "lid" => {}};
2584 foreach my $li_id (@$li_ids) {
2585 my $li_result = cancel_lineitem($mgr, $li_id, $cancel_reason)
2588 next if $li_result == -1; # already canceled:skip.
2589 return $li_result if not_cancelable($li_result); # not cancelable:stop.
2591 # Merge in each LI result (there's only going to be
2592 # one per call to cancel_lineitem).
2593 my ($k, $v) = each %{$li_result->{"li"}};
2594 $result->{"li"}->{$k} = $v;
2596 # Merge in each LID result (there may be many per call to
2598 while (($k, $v) = each %{$li_result->{"lid"}}) {
2599 $result->{"lid"}->{$k} = $v;
2603 # TODO who/what/where/how do we indicate this change for electronic orders?
2604 # TODO return changes to encumbered/spent
2605 # TODO maybe cascade up from smaller object to container object if last
2606 # smaller object in the container has been canceled?
2608 update_purchase_order($mgr, $po) or return 0;
2610 $po_id => {"state" => $po->state, "cancel_reason" => $cancel_reason}
2616 __PACKAGE__->register_method(
2617 method => "cancel_lineitem_api",
2618 api_name => "open-ils.acq.lineitem.cancel",
2620 desc => q/Cancels an on-order lineitem/,
2622 {desc => "Authentication token", type => "string"},
2623 {desc => "Lineitem ID to cancel", type => "number"},
2624 {desc => "Cancel reason ID", type => "number"}
2626 return => {desc => q/Object describing changed LIs and LIDs on success;
2631 __PACKAGE__->register_method(
2632 method => "cancel_lineitem_api",
2633 api_name => "open-ils.acq.lineitem.cancel.batch",
2635 desc => q/Batched version of open-ils.acq.lineitem.cancel/,
2636 return => {desc => q/Object describing changed LIs and LIDs on success;
2641 sub cancel_lineitem_api {
2642 my ($self, $conn, $auth, $li_id, $cancel_reason) = @_;
2644 my $batched = $self->api_name =~ /\.batch/;
2646 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2647 return $e->die_event unless $e->checkauth;
2648 my $mgr = new OpenILS::Application::Acq::BatchManager(
2649 "editor" => $e, "conn" => $conn
2652 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2653 return new OpenILS::Event(
2654 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2657 my ($result, $maybe_event);
2660 $result = {"li" => {}, "lid" => {}};
2661 foreach my $one_li_id (@$li_id) {
2662 my $one = cancel_lineitem($mgr, $one_li_id, $cancel_reason) or
2663 return $e->die_event;
2664 if (not_cancelable($one)) {
2665 $maybe_event = $one;
2666 } elsif ($result == -1) {
2667 $maybe_event = new OpenILS::Event("ACQ_ALREADY_CANCELED");
2671 while (($k, $v) = each %{$one->{"li"}}) {
2672 $result->{"li"}->{$k} = $v;
2675 if ($one->{"lid"}) {
2676 while (($k, $v) = each %{$one->{"lid"}}) {
2677 $result->{"lid"}->{$k} = $v;
2683 $result = cancel_lineitem($mgr, $li_id, $cancel_reason) or
2684 return $e->die_event;
2686 if (not_cancelable($result)) {
2689 } elsif ($result == -1) {
2691 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2695 if ($batched and not scalar keys %{$result->{"li"}}) {
2697 return $maybe_event;
2699 $e->commit or return $e->die_event;
2700 # create_lineitem_status_events should handle array li_id ok
2701 create_lineitem_status_events($mgr, $li_id, "aur.cancelled");
2703 if ($mgr->{post_commit}) {
2704 foreach my $func (@{$mgr->{post_commit}}) {
2713 sub cancel_lineitem {
2714 my ($mgr, $li_id, $cancel_reason) = @_;
2715 my $li = $mgr->editor->retrieve_acq_lineitem([
2716 $li_id, {flesh => 1, flesh_fields => {jub => ['purchase_order']}}
2719 return 0 unless $mgr->editor->allowed(
2720 "CREATE_PURCHASE_ORDER", $li->purchase_order->ordering_agency
2723 # Depending on context, this may not warrant an event.
2724 return -1 if $li->state eq "cancelled";
2726 # But this always does.
2727 return new OpenILS::Event(
2728 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id"
2730 (! $li->purchase_order) or (
2731 $li->purchase_order and (
2732 $li->state eq "on-order" or $li->state eq "pending-order"
2737 $li->state("cancelled");
2738 $li->cancel_reason($cancel_reason->id);
2740 my $lids = $mgr->editor->search_acq_lineitem_detail([{
2741 "lineitem" => $li_id
2744 flesh_fields => { acqlid => ['eg_copy_id'] }
2747 my $result = {"lid" => {}};
2749 foreach my $lid (@$lids) {
2750 my $lid_result = cancel_lineitem_detail($mgr, $lid->id, $cancel_reason)
2753 # gathering any real copies for deletion
2754 if ($lid->eg_copy_id) {
2755 $lid->eg_copy_id->isdeleted('t');
2756 push @$copies, $lid->eg_copy_id;
2759 next if $lid_result == -1; # already canceled: just skip it.
2760 return $lid_result if not_cancelable($lid_result); # not cxlable: stop.
2762 # Merge in each LID result (there's only going to be one per call to
2763 # cancel_lineitem_detail).
2764 my ($k, $v) = each %{$lid_result->{"lid"}};
2765 $result->{"lid"}->{$k} = $v;
2768 # Attempt to delete the gathered copies (this will also handle volume deletion and bib deletion)
2769 # Delete empty bibs according org unit setting
2770 my $force_delete_empty_bib = $U->ou_ancestor_setting_value(
2771 $mgr->editor->requestor->ws_ou, 'cat.bib.delete_on_no_copy_via_acq_lineitem_cancel', $mgr->editor);
2772 if (scalar(@$copies)>0) {
2774 my $delete_stats = undef;
2775 my $retarget_holds = [];
2776 my $cat_evt = OpenILS::Application::Cat::AssetCommon->update_fleshed_copies(
2777 $mgr->editor, $override, undef, $copies, $delete_stats, $retarget_holds,$force_delete_empty_bib);
2780 $logger->info("fleshed copy update failed with event: ".OpenSRF::Utils::JSON->perl2JSON($cat_evt));
2781 return new OpenILS::Event(
2782 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id", "payload" => $cat_evt
2786 # We can't do the following and stay within the same transaction, but that's okay, the hold targeter will pick these up later.
2787 #my $ses = OpenSRF::AppSession->create('open-ils.circ');
2788 #$ses->request('open-ils.circ.hold.reset.batch', $auth, $retarget_holds);
2791 # if we have a bib, check to see whether it has been deleted. if so, cancel any active holds targeting that bib
2792 if ($li->eg_bib_id) {
2793 my $bib = $mgr->editor->retrieve_biblio_record_entry($li->eg_bib_id) or return new OpenILS::Event(
2794 "ACQ_NOT_CANCELABLE", "note" => "Could not retrieve bib " . $li->eg_bib_id . " for lineitem $li_id"
2796 if ($U->is_true($bib->deleted)) {
2797 my $holds = $mgr->editor->search_action_hold_request(
2798 { cancel_time => undef,
2799 fulfillment_time => undef,
2800 target => $li->eg_bib_id
2804 my %cached_usr_home_ou = ();
2806 for my $hold (@$holds) {
2808 $logger->info("Cancelling hold ".$hold->id.
2809 " due to acq lineitem cancellation.");
2811 $hold->cancel_time('now');
2812 $hold->cancel_cause(5); # 'Staff forced'--we may want a new hold cancel cause reason for this
2813 $hold->cancel_note('Corresponding Acquistion Lineitem/Purchase Order was cancelled.');
2814 unless($mgr->editor->update_action_hold_request($hold)) {
2815 my $evt = $mgr->editor->event;
2816 $logger->error("Error updating hold ". $evt->textcode .":". $evt->desc .":". $evt->stacktrace);
2817 return new OpenILS::Event(
2818 "ACQ_NOT_CANCELABLE", "note" => "Could not cancel hold " . $hold->id . " for lineitem $li_id", "payload" => $evt
2821 if (! defined $mgr->{post_commit}) { # we need a mechanism for creating trigger events, but only if the transaction gets committed
2822 $mgr->{post_commit} = [];
2824 push @{ $mgr->{post_commit} }, sub {
2825 my $home_ou = $cached_usr_home_ou{$hold->usr};
2827 my $user = $mgr->editor->retrieve_actor_user($hold->usr); # FIXME: how do we want to handle failures here?
2828 $home_ou = $user->home_ou;
2829 $cached_usr_home_ou{$hold->usr} = $home_ou;
2831 $U->create_events_for_hook('hold_request.cancel.cancelled_order', $hold, $home_ou);
2837 update_lineitem($mgr, $li) or return 0;
2840 "state" => $li->state,
2841 "cancel_reason" => $cancel_reason
2848 __PACKAGE__->register_method(
2849 method => "cancel_lineitem_detail_api",
2850 api_name => "open-ils.acq.lineitem_detail.cancel",
2852 desc => q/Cancels an on-order lineitem detail/,
2854 {desc => "Authentication token", type => "string"},
2855 {desc => "Lineitem detail ID to cancel", type => "number"},
2856 {desc => "Cancel reason ID", type => "number"}
2858 return => {desc => q/Object describing changed LIDs on success;
2863 sub cancel_lineitem_detail_api {
2864 my ($self, $conn, $auth, $lid_id, $cancel_reason) = @_;
2866 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2867 return $e->die_event unless $e->checkauth;
2868 my $mgr = new OpenILS::Application::Acq::BatchManager(
2869 "editor" => $e, "conn" => $conn
2872 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2873 return new OpenILS::Event(
2874 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2877 my $result = cancel_lineitem_detail($mgr, $lid_id, $cancel_reason) or
2878 return $e->die_event;
2880 if (not_cancelable($result)) {
2883 } elsif ($result == -1) {
2885 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2888 $e->commit or return $e->die_event;
2890 # XXX create lineitem detail status events?
2894 sub cancel_lineitem_detail {
2895 my ($mgr, $lid_id, $cancel_reason) = @_;
2896 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
2900 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
2905 # Depending on context, this may not warrant an event.
2906 return -1 if $lid->cancel_reason;
2908 # But this always does.
2909 return new OpenILS::Event(
2910 "ACQ_NOT_CANCELABLE", "note" => "lineitem_detail $lid_id"
2912 (! $lid->lineitem->purchase_order) or
2914 (not $lid->recv_time) and
2916 $lid->lineitem->purchase_order and (
2917 $lid->lineitem->state eq "on-order" or
2918 $lid->lineitem->state eq "pending-order"
2923 return 0 unless $mgr->editor->allowed(
2924 "CREATE_PURCHASE_ORDER",
2925 $lid->lineitem->purchase_order->ordering_agency
2926 ) or (! $lid->lineitem->purchase_order);
2928 $lid->cancel_reason($cancel_reason->id);
2930 unless($U->is_true($cancel_reason->keep_debits)) {
2931 my $debit_id = $lid->fund_debit;
2932 $lid->clear_fund_debit;
2935 # item is cancelled. Remove the fund debit.
2936 my $debit = $mgr->editor->retrieve_acq_fund_debit($debit_id);
2937 if (!$U->is_true($debit->encumbrance)) {
2938 $mgr->editor->rollback;
2939 return OpenILS::Event->new('ACQ_NOT_CANCELABLE',
2940 note => "Debit is marked as paid: $debit_id");
2942 $mgr->editor->delete_acq_fund_debit($debit) or return $mgr->editor->die_event;
2946 # XXX LIDs don't have either an editor or a edit_time field. Should we
2947 # update these on the LI when we alter an LID?
2948 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
2950 return {"lid" => {$lid_id => {"cancel_reason" => $cancel_reason}}};
2954 __PACKAGE__->register_method(
2955 method => 'user_requests',
2956 api_name => 'open-ils.acq.user_request.retrieve.by_user_id',
2959 desc => 'Retrieve fleshed user requests and related data for a given user.',
2961 { desc => 'Authentication token', type => 'string' },
2962 { desc => 'User ID of the owner, or array of IDs', },
2963 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
2968 desc => 'Fleshed user requests and related data',
2974 __PACKAGE__->register_method(
2975 method => 'user_requests',
2976 api_name => 'open-ils.acq.user_request.retrieve.by_home_ou',
2979 desc => 'Retrieve fleshed user requests and related data for a given org unit or units.',
2981 { desc => 'Authentication token', type => 'string' },
2982 { desc => 'Org unit ID, or array of IDs', },
2983 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
2988 desc => 'Fleshed user requests and related data',
2995 my($self, $conn, $auth, $search_value, $options) = @_;
2996 my $e = new_editor(authtoken => $auth);
2997 return $e->event unless $e->checkauth;
2998 my $rid = $e->requestor->id;
3002 "select"=>{"aur"=>["id"],"au"=>["home_ou", {column => 'id', alias => 'usr_id'} ]},
3003 "from"=>{ "aur" => { "au" => {}, "jub" => { "type" => "left" } } },
3007 {"id"=>undef}, # this with the left-join pulls in requests without lineitems
3008 {"state"=>["new","on-order","pending-order"]} # FIXME - probably needs softcoding
3012 "order_by"=>[{"class"=>"aur", "field"=>"request_date", "direction"=>"desc"}]
3015 foreach (qw/ order_by limit offset /) {
3016 $query->{$_} = $options->{$_} if defined $options->{$_};
3018 if (defined $options->{'state'}) {
3019 $query->{'where'}->{'+jub'}->{'-or'}->[1]->{'state'} = $options->{'state'};
3022 if ($self->api_name =~ /by_user_id/) {
3023 $query->{'where'}->{'usr'} = $search_value;
3025 $query->{'where'}->{'+au'} = { 'home_ou' => $search_value };
3028 my $pertinent_ids = $e->json_query($query);
3031 for my $id_blob (@$pertinent_ids) {
3032 if ($rid != $id_blob->{usr_id}) {
3033 if (!defined $perm_test{ $id_blob->{home_ou} }) {
3034 $perm_test{ $id_blob->{home_ou} } = $e->allowed( ['user_request.view'], $id_blob->{home_ou} );
3036 if (!$perm_test{ $id_blob->{home_ou} }) {
3040 my $aur_obj = $e->retrieve_acq_user_request([
3042 {flesh => 1, flesh_fields => { "aur" => [ 'lineitem' ] } }
3044 if (! $aur_obj) { next; }
3046 if ($aur_obj->lineitem()) {
3047 $aur_obj->lineitem()->clear_marc();
3049 $conn->respond($aur_obj);
3055 __PACKAGE__->register_method (
3056 method => 'update_user_request',
3057 api_name => 'open-ils.acq.user_request.cancel.batch',
3060 desc => 'If given a cancel reason, will update the request with that reason, otherwise, this will delete the request altogether. The ' .
3061 'intention is for staff interfaces or processes to provide cancel reasons, and for patron interfaces to just delete the requests.' ,
3063 { desc => 'Authentication token', type => 'string' },
3064 { desc => 'ID or array of IDs for the user requests to cancel' },
3065 { desc => 'Cancel Reason ID (optional)', type => 'string' }
3068 desc => 'progress object, event on error',
3072 __PACKAGE__->register_method (
3073 method => 'update_user_request',
3074 api_name => 'open-ils.acq.user_request.set_no_hold.batch',
3077 desc => 'Remove the hold from a user request or set of requests',
3079 { desc => 'Authentication token', type => 'string' },
3080 { desc => 'ID or array of IDs for the user requests to modify' }
3083 desc => 'progress object, event on error',
3088 sub update_user_request {
3089 my($self, $conn, $auth, $aur_ids, $cancel_reason) = @_;
3090 my $e = new_editor(xact => 1, authtoken => $auth);
3091 return $e->die_event unless $e->checkauth;
3092 my $rid = $e->requestor->id;
3096 for my $id (@$aur_ids) {
3098 my $aur_obj = $e->retrieve_acq_user_request([
3101 flesh_fields => { "aur" => ['lineitem', 'usr'] }
3103 ]) or return $e->die_event;
3105 my $context_org = $aur_obj->usr()->home_ou();
3106 $aur_obj->usr( $aur_obj->usr()->id() );
3108 if ($rid != $aur_obj->usr) {
3109 if (!defined $perm_test{ $context_org }) {
3110 $perm_test{ $context_org } = $e->allowed( ['user_request.update'], $context_org );
3112 if (!$perm_test{ $context_org }) {
3117 if($self->api_name =~ /set_no_hold/) {
3118 if ($U->is_true($aur_obj->hold)) {
3120 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3124 if($self->api_name =~ /cancel/) {
3125 if ( $cancel_reason ) {
3126 $aur_obj->cancel_reason( $cancel_reason );
3127 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3128 create_user_request_events( $e, [ $aur_obj ], 'aur.rejected' );
3130 $e->delete_acq_user_request($aur_obj);
3134 $conn->respond({maximum => scalar(@$aur_ids), progress => $x++});
3138 return {complete => 1};
3141 __PACKAGE__->register_method (
3142 method => 'new_user_request',
3143 api_name => 'open-ils.acq.user_request.create',
3145 desc => 'Create a new user request object in the DB',
3147 { desc => 'Authentication token', type => 'string' },
3148 { desc => 'User request data hash. Hash keys match the fields for the "aur" object', type => 'object' }
3151 desc => 'The created user request object, or event on error'
3156 sub new_user_request {
3157 my($self, $conn, $auth, $form_data) = @_;
3158 my $e = new_editor(xact => 1, authtoken => $auth);
3159 return $e->die_event unless $e->checkauth;
3160 my $rid = $e->requestor->id;
3161 my $target_user_fleshed;
3162 if (! defined $$form_data{'usr'}) {
3163 $$form_data{'usr'} = $rid;
3165 if ($$form_data{'usr'} != $rid) {
3166 # See if the requestor can place the request on behalf of a different user.
3167 $target_user_fleshed = $e->retrieve_actor_user($$form_data{'usr'}) or return $e->die_event;
3168 $e->allowed('user_request.create', $target_user_fleshed->home_ou) or return $e->die_event;
3170 $target_user_fleshed = $e->requestor;
3171 $e->allowed('CREATE_PURCHASE_REQUEST') or return $e->die_event;
3173 if (! defined $$form_data{'pickup_lib'}) {
3174 if ($target_user_fleshed->ws_ou) {
3175 $$form_data{'pickup_lib'} = $target_user_fleshed->ws_ou;
3177 $$form_data{'pickup_lib'} = $target_user_fleshed->home_ou;
3180 if (! defined $$form_data{'request_type'}) {
3181 $$form_data{'request_type'} = 1; # Books
3183 my $aur_obj = new Fieldmapper::acq::user_request;
3185 $aur_obj->usr( $$form_data{'usr'} );
3186 $aur_obj->request_date( 'now' );
3187 for my $field ( keys %$form_data ) {
3188 if (defined $$form_data{$field} and $field !~ /^(id|lineitem|eg_bib|request_date|cancel_reason)$/) {
3189 $aur_obj->$field( $$form_data{$field} );
3193 $aur_obj = $e->create_acq_user_request($aur_obj) or return $e->die_event;
3195 $e->commit and create_user_request_events( $e, [ $aur_obj ], 'aur.created' );
3200 sub create_user_request_events {
3201 my($e, $user_reqs, $hook) = @_;
3203 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
3206 my %cached_usr_home_ou = ();
3207 for my $user_req (@$user_reqs) {
3208 my $home_ou = $cached_usr_home_ou{$user_req->usr};
3210 my $user = $e->retrieve_actor_user($user_req->usr) or return $e->die_event;
3211 $home_ou = $user->home_ou;
3212 $cached_usr_home_ou{$user_req->usr} = $home_ou;
3214 my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $home_ou);
3223 __PACKAGE__->register_method(
3224 method => "po_note_CUD_batch",
3225 api_name => "open-ils.acq.po_note.cud.batch",
3228 desc => q/Manage purchase order notes/,
3230 {desc => "Authentication token", type => "string"},
3231 {desc => "List of po_notes to manage", type => "array"},
3233 return => {desc => "Stream of successfully managed objects"}
3237 sub po_note_CUD_batch {
3238 my ($self, $conn, $auth, $notes) = @_;
3240 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3241 return $e->die_event unless $e->checkauth;
3244 my $total = @$notes;
3247 foreach my $note (@$notes) {
3249 $note->editor($e->requestor->id);
3250 $note->edit_time("now");
3253 $note->creator($e->requestor->id);
3254 $note = $e->create_acq_po_note($note) or return $e->die_event;
3255 } elsif ($note->isdeleted) {
3256 $e->delete_acq_po_note($note) or return $e->die_event;
3257 } elsif ($note->ischanged) {
3258 $e->update_acq_po_note($note) or return $e->die_event;
3261 unless ($note->isdeleted) {
3262 $note = $e->retrieve_acq_po_note($note->id) or
3263 return $e->die_event;
3267 {"maximum" => $total, "progress" => ++$count, "note" => $note}
3271 $e->commit and $conn->respond_complete or return $e->die_event;
3275 # retrieves a lineitem, fleshes its PO and PL, checks perms
3276 sub fetch_and_check_li {
3279 my $perm_mode = shift || 'read';
3281 my $li = $e->retrieve_acq_lineitem([
3284 flesh_fields => {jub => ['purchase_order', 'picklist']}
3286 ]) or return $e->die_event;
3288 if(my $po = $li->purchase_order) {
3289 my $perms = ($perm_mode eq 'read') ? 'VIEW_PURCHASE_ORDER' : 'CREATE_PURCHASE_ORDER';
3290 return ($li, $e->die_event) unless $e->allowed($perms, $po->ordering_agency);
3292 } elsif(my $pl = $li->picklist) {
3293 my $perms = ($perm_mode eq 'read') ? 'VIEW_PICKLIST' : 'CREATE_PICKLIST';
3294 return ($li, $e->die_event) unless $e->allowed($perms, $pl->org_unit);
3301 __PACKAGE__->register_method(
3302 method => "clone_distrib_form",
3303 api_name => "open-ils.acq.distribution_formula.clone",
3306 desc => q/Clone a distribution formula/,
3308 {desc => "Authentication token", type => "string"},
3309 {desc => "Original formula ID", type => 'integer'},
3310 {desc => "Name of new formula", type => 'string'},
3312 return => {desc => "ID of newly created formula"}
3316 sub clone_distrib_form {
3317 my($self, $client, $auth, $form_id, $new_name) = @_;
3319 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3320 return $e->die_event unless $e->checkauth;
3322 my $old_form = $e->retrieve_acq_distribution_formula($form_id) or return $e->die_event;
3323 return $e->die_event unless $e->allowed('ADMIN_ACQ_DISTRIB_FORMULA', $old_form->owner);
3325 my $new_form = Fieldmapper::acq::distribution_formula->new;
3327 $new_form->owner($old_form->owner);
3328 $new_form->name($new_name);
3329 $e->create_acq_distribution_formula($new_form) or return $e->die_event;
3331 my $entries = $e->search_acq_distribution_formula_entry({formula => $form_id});
3332 for my $entry (@$entries) {
3333 my $new_entry = Fieldmapper::acq::distribution_formula_entry->new;
3334 $new_entry->$_($entry->$_()) for $entry->real_fields;
3335 $new_entry->formula($new_form->id);
3336 $new_entry->clear_id;
3337 $e->create_acq_distribution_formula_entry($new_entry) or return $e->die_event;
3341 return $new_form->id;
3344 __PACKAGE__->register_method(
3345 method => 'add_li_to_po',
3346 api_name => 'open-ils.acq.purchase_order.add_lineitem',
3348 desc => q/Adds a lineitem to an existing purchase order/,
3350 {desc => 'Authentication token', type => 'string'},
3351 {desc => 'The purchase order id', type => 'number'},
3352 {desc => 'The lineitem ID', type => 'number'},
3354 return => {desc => 'Streams a total versus completed counts object, event on error'}
3359 my($self, $conn, $auth, $po_id, $li_id) = @_;
3361 my $e = new_editor(authtoken => $auth, xact => 1);
3362 return $e->die_event unless $e->checkauth;
3364 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
3366 my $po = $e->retrieve_acq_purchase_order($po_id)
3367 or return $e->die_event;
3369 my $li = $e->retrieve_acq_lineitem($li_id)
3370 or return $e->die_event;
3372 return $e->die_event unless
3373 $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
3375 unless ($po->state =~ /new|pending/) {
3377 return {success => 0, po => $po, error => 'bad-po-state'};
3380 unless ($li->state =~ /new|order-ready|pending-order/) {
3382 return {success => 0, li => $li, error => 'bad-li-state'};
3385 $li->purchase_order($po_id);
3386 $li->state('pending-order');
3387 update_lineitem($mgr, $li) or return $e->die_event;
3390 return {success => 1};
3393 __PACKAGE__->register_method(
3394 method => 'po_lineitems_no_copies',
3395 api_name => 'open-ils.acq.purchase_order.no_copy_lineitems.id_list',
3399 desc => q/Returns the set of lineitem IDs for a given PO that have no copies attached/,
3401 {desc => 'Authentication token', type => 'string'},
3402 {desc => 'The purchase order id', type => 'number'},
3404 return => {desc => 'Stream of lineitem IDs on success, event on error'}
3408 sub po_lineitems_no_copies {
3409 my ($self, $conn, $auth, $po_id) = @_;
3411 my $e = new_editor(authtoken => $auth);
3412 return $e->event unless $e->checkauth;
3414 # first check the view perms for LI's attached to this PO
3415 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->event;
3416 return $e->event unless $e->allowed('VIEW_PURCHASE_ORDER', $po->ordering_agency);
3418 my $ids = $e->json_query({
3419 select => {jub => ['id']},
3420 from => {jub => {acqlid => {type => 'left'}}},
3422 '+jub' => {purchase_order => $po_id},
3423 '+acqlid' => {lineitem => undef}
3427 $conn->respond($_->{id}) for @$ids;