1 package OpenILS::Application::Acq::BatchManager;
2 use OpenILS::Application::Acq::Financials;
3 use OpenSRF::AppSession;
4 use OpenSRF::EX qw/:try/;
5 use strict; use warnings;
8 my($class, %args) = @_;
9 my $self = bless(\%args, $class);
18 purchase_order => undef,
26 $self->throttle(5) unless $self->throttle;
27 $self->{post_proc_queue} = [];
28 $self->{last_respond_progress} = 0;
34 $self->{conn} = $val if $val;
39 $self->{throttle} = $val if $val;
40 return $self->{throttle};
43 my($self, %other_args) = @_;
44 if($self->throttle and not %other_args) {
46 ($self->{args}->{progress} - $self->{last_respond_progress}) >= $self->throttle
49 $self->conn->respond({ %{$self->{args}}, %other_args });
50 $self->{last_respond_progress} = $self->{args}->{progress};
52 sub respond_complete {
53 my($self, %other_args) = @_;
55 $self->conn->respond_complete({ %{$self->{args}}, %other_args });
56 $self->run_post_response_hooks;
60 # run the post response hook subs, shifting them off as we go
61 sub run_post_response_hooks {
63 (shift @{$self->{post_proc_queue}})->() while @{$self->{post_proc_queue}};
66 # any subs passed to this method will be run after the call to respond_complete
69 push(@{$self->{post_proc_queue}}, $sub);
74 $self->{args}->{total} = $val if defined $val;
75 $self->{args}->{maximum} = $self->{args}->{total};
76 return $self->{args}->{total};
80 $self->{args}->{purchase_order} = $val if $val;
85 $self->{args}->{picklist} = $val if $val;
90 $self->{args}->{lid} += 1;
91 $self->{args}->{progress} += 1;
96 $self->{args}->{li} += 1;
97 $self->{args}->{progress} += 1;
102 $self->{args}->{vqbr} += 1;
103 $self->{args}->{progress} += 1;
108 $self->{args}->{copies} += 1;
109 $self->{args}->{progress} += 1;
114 $self->{args}->{bibs} += 1;
115 $self->{args}->{progress} += 1;
119 my($self, $amount) = @_;
120 $self->{args}->{debits_accrued} += $amount;
121 $self->{args}->{progress} += 1;
125 my($self, $editor) = @_;
126 $self->{editor} = $editor if defined $editor;
127 return $self->{editor};
131 $self->{args}->{complete} = 1;
136 my($self, $org, $key, $val) = @_;
137 $self->{cache}->{$org} = {} unless $self->{cache}->{org};
138 $self->{cache}->{$org}->{$key} = $val if defined $val;
139 return $self->{cache}->{$org}->{$key};
143 package OpenILS::Application::Acq::Order;
144 use base qw/OpenILS::Application/;
145 use strict; use warnings;
146 # ----------------------------------------------------------------------------
147 # Break up each component of the order process and pieces into managable
148 # actions that can be shared across different workflows
149 # ----------------------------------------------------------------------------
151 use OpenSRF::Utils::Logger qw(:logger);
152 use OpenSRF::Utils::JSON;
153 use OpenSRF::AppSession;
154 use OpenILS::Utils::Fieldmapper;
155 use OpenILS::Utils::CStoreEditor q/:funcs/;
156 use OpenILS::Utils::Normalize qw/clean_marc/;
157 use OpenILS::Const qw/:const/;
158 use OpenSRF::EX q/:try/;
159 use OpenILS::Application::AppUtils;
160 use OpenILS::Application::Cat::BibCommon;
161 use OpenILS::Application::Cat::AssetCommon;
164 use MARC::File::XML (BinaryEncoding => 'UTF-8');
165 use Digest::MD5 qw(md5_hex);
167 $Data::Dumper::Indent = 0;
168 my $U = 'OpenILS::Application::AppUtils';
171 # ----------------------------------------------------------------------------
173 # ----------------------------------------------------------------------------
174 sub create_lineitem {
175 my($mgr, %args) = @_;
176 my $li = Fieldmapper::acq::lineitem->new;
177 $li->creator($mgr->editor->requestor->id);
178 $li->selector($li->creator);
179 $li->editor($li->creator);
180 $li->create_time('now');
181 $li->edit_time('now');
183 $li->$_($args{$_}) for keys %args;
186 $mgr->editor->create_acq_lineitem($li) or return 0;
188 unless($li->estimated_unit_price) {
189 # extract the price from the MARC data
190 my $price = get_li_price_from_attr($mgr->editor, $li) or return $li;
191 $li->estimated_unit_price($price);
192 return update_lineitem($mgr, $li);
198 sub get_li_price_from_attr {
200 my $attrs = $li->attributes || $e->search_acq_lineitem_attr({lineitem => $li->id});
202 for my $attr_type (qw/
203 lineitem_local_attr_definition
204 lineitem_prov_attr_definition
205 lineitem_marc_attr_definition/) {
208 $_->attr_name eq 'estimated_price' and
209 $_->attr_type eq $attr_type } @$attrs;
211 return $attr->attr_value if $attr;
218 sub update_lineitem {
220 $li->edit_time('now');
221 $li->editor($mgr->editor->requestor->id);
223 return $mgr->editor->retrieve_acq_lineitem($mgr->editor->data) if
224 $mgr->editor->update_acq_lineitem($li);
229 # ----------------------------------------------------------------------------
230 # Create real holds from patron requests for a given lineitem
231 # ----------------------------------------------------------------------------
232 sub promote_lineitem_holds {
235 my $requests = $mgr->editor->search_acq_user_request(
236 { lineitem => $li->id,
238 [ { need_before => {'>' => 'now'} },
239 { need_before => undef }
244 for my $request ( @$requests ) {
246 $request->eg_bib( $li->eg_bib_id );
247 $mgr->editor->update_acq_user_request( $request ) or return 0;
249 next unless ($U->is_true( $request->hold ));
251 my $hold = Fieldmapper::action::hold_request->new;
252 $hold->usr( $request->usr );
253 $hold->requestor( $request->usr );
254 $hold->request_time( $request->request_date );
255 $hold->pickup_lib( $request->pickup_lib );
256 $hold->request_lib( $request->pickup_lib );
257 $hold->selection_ou( $request->pickup_lib );
258 $hold->phone_notify( $request->phone_notify );
259 $hold->email_notify( $request->email_notify );
260 $hold->expire_time( $request->need_before );
262 if ($request->holdable_formats) {
263 my $mrm = $mgr->editor->search_metabib_metarecord_source_map( { source => $li->eg_bib_id } )->[0];
265 $hold->hold_type( 'M' );
266 $hold->holdable_formats( $request->holdable_formats );
267 $hold->target( $mrm->metarecord );
271 if (!$hold->target) {
272 $hold->hold_type( 'T' );
273 $hold->target( $li->eg_bib_id );
276 $mgr->editor->create_actor_hold_request( $hold ) or return 0;
282 sub delete_lineitem {
284 $li = $mgr->editor->retrieve_acq_lineitem($li) unless ref $li;
286 # delete the attached lineitem_details
287 my $lid_ids = $mgr->editor->search_acq_lineitem_detail({lineitem => $li->id}, {idlist=>1});
288 for my $lid_id (@$lid_ids) {
289 return 0 unless delete_lineitem_detail($mgr, $lid_id);
293 return $mgr->editor->delete_acq_lineitem($li);
296 # begins and commit transactions as it goes
297 sub create_lineitem_list_assets {
298 my($mgr, $li_ids, $vandelay) = @_;
300 if (check_import_li_marc_perms($mgr, $li_ids)) { # event on error
301 $logger->error("acq-vl: user does not have permission to import acq records");
305 my $res = import_li_bibs_via_vandelay($mgr, $li_ids, $vandelay);
306 return undef unless $res;
308 # create the bibs/volumes/copies for the successfully imported records
309 for my $li_id (@{$res->{li_ids}}) {
310 $mgr->editor->xact_begin;
311 my $data = create_lineitem_assets($mgr, $li_id) or return undef;
312 $mgr->editor->xact_commit;
319 sub verify_vandelay_import_args {
320 my $vandelay = shift;
323 return 0 unless $vandelay and
324 ($vandelay->{queue_name} or $vandelay->{existing_queue});
326 # match-based merge/overlay import
327 return 1 if $vandelay->{merge_profile} and (
328 $vandelay->{auto_overlay_exact} or
329 $vandelay->{auto_overlay_1match} or
330 $vandelay->{auto_overlay_best_match}
334 return 1 if $vandelay->{import_no_match};
339 sub find_or_create_vandelay_queue {
340 my ($e, $vandelay) = @_;
343 if (my $name = $vandelay->{queue_name}) {
345 # first, see if a queue w/ this name already exists
346 # for this user. If so, use that instead.
348 $queue = $e->search_vandelay_bib_queue(
349 {name => $name, owner => $e->requestor->id})->[0];
353 $logger->info("acq-vl: using existing queue $name");
357 $logger->info("acq-vl: creating new vandelay queue $name");
359 $queue = new Fieldmapper::vandelay::bib_queue;
361 $queue->queue_type('acq');
362 $queue->owner($e->requestor->id);
363 $queue->match_set($vandelay->{match_set} || undef); # avoid ''
364 $queue = $e->create_vandelay_bib_queue($queue) or return undef;
368 $queue = $e->retrieve_vandelay_bib_queue($vandelay->{existing_queue})
376 sub import_li_bibs_via_vandelay {
377 my ($mgr, $li_ids, $vandelay) = @_;
378 my $res = {li_ids => []};
379 my $e = $mgr->editor;
382 my $needs_importing = $e->search_acq_lineitem(
383 {id => $li_ids, eg_bib_id => undef},
387 if (!@$needs_importing) {
388 $logger->info("acq-vl: all records already imported. no Vandelay work to do");
389 return {li_ids => $li_ids};
392 # add the already-imported records to the response list
393 push(@{$res->{li_ids}}, grep { $_ != @$needs_importing } @$li_ids);
395 $logger->info("acq-vl: processing recs via Vandelay with args: ".Dumper($vandelay));
397 if (!verify_vandelay_import_args($vandelay)) {
398 $logger->error("acq-vl: invalid vandelay arguments for acq import");
402 my $queue = find_or_create_vandelay_queue($e, $vandelay) or return $res;
403 $mgr->{args}->{queue} = $queue;
405 # load the lineitems into the queue for merge processing
408 for my $li_id (@$needs_importing) {
410 my $li = $e->retrieve_acq_lineitem($li_id) or return $res;
412 my $vqbr = Fieldmapper::vandelay::queued_bib_record->new;
413 $vqbr->marc($li->marc);
414 $vqbr->queue($queue->id);
415 $vqbr->bib_source($vandelay->{bib_source} || undef); # avoid ''
416 $vqbr = $e->create_vandelay_queued_bib_record($vqbr) or return $res;
417 push(@vqbr_ids, $vqbr->id);
421 # tell the acq record which vandelay record it's linked to
422 $li->queued_record($vqbr->id);
423 $e->update_acq_lineitem($li) or return $res;
427 $logger->info("acq-vl: created vandelay records [@vqbr_ids]");
429 # we have to commit the transaction now since
430 # vandelay uses its own transactions.
433 # Import the bibs via vandelay. Note: Vandely will
434 # update acq.lineitem.eg_bib_id on successful import.
436 $vandelay->{report_all} = 1;
437 my $ses = OpenSRF::AppSession->create('open-ils.vandelay');
438 my $req = $ses->request(
439 'open-ils.vandelay.bib_record.list.import',
440 $e->authtoken, \@vqbr_ids, $vandelay);
442 # pull the responses, noting all that were successfully imported
444 while (my $resp = $req->recv(timeout => 600)) {
445 my $stat = $resp->content;
447 if(!$stat or $U->event_code($stat)) { # import failure
448 $logger->error("acq-vl: error importing vandelay record " . Dumper($stat));
452 # "imported" refers to the vqbr id, not the
453 # success/failure of the vqbr merge attempt
454 next unless $stat->{imported};
456 my ($imported) = grep {$_->queued_record eq $stat->{imported}} @lis;
457 my $li_id = $imported->id;
459 if ($stat->{no_import}) {
460 $logger->info("acq-vl: acq lineitem $li_id did not import");
462 } else { # successful import
464 push(@success_lis, $li_id);
467 $logger->info("acq-vl: acq lineitem $li_id successfully merged/imported");
472 $logger->info("acq-vl: successfully imported lineitems [@success_lis]");
474 # add the successfully imported lineitems to the already-imported lineitems
475 push (@{$res->{li_ids}}, @success_lis);
480 # returns event on error, undef on success
481 sub check_import_li_marc_perms {
482 my($mgr, $li_ids) = @_;
484 # if there are any order records that are not linked to
485 # in-db bib records, verify staff has perms to import order records
486 my $order_li = $mgr->editor->search_acq_lineitem(
487 [{id => $li_ids, eg_bib_id => undef}, {limit => 1}], {idlist => 1})->[0];
490 return $mgr->editor->die_event unless
491 $mgr->editor->allowed('IMPORT_ACQ_LINEITEM_BIB_RECORD');
498 # ----------------------------------------------------------------------------
499 # if all of the lineitem details for this lineitem have
500 # been received, mark the lineitem as received
501 # returns 1 on non-received, li on received, 0 on error
502 # ----------------------------------------------------------------------------
504 sub describe_affected_po {
508 OpenILS::Application::Acq::Financials::build_price_summary(
513 "state" => $po->state,
514 "amount_encumbered" => $enc,
515 "amount_spent" => $spent
520 sub check_lineitem_received {
521 my($mgr, $li_id) = @_;
523 my $non_recv = $mgr->editor->search_acq_lineitem_detail(
524 {recv_time => undef, lineitem => $li_id}, {idlist=>1});
526 return 1 if @$non_recv;
528 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
529 $li->state('received');
530 return update_lineitem($mgr, $li);
533 sub receive_lineitem {
534 my($mgr, $li_id, $skip_complete_check) = @_;
535 my $li = $mgr->editor->retrieve_acq_lineitem($li_id) or return 0;
537 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
538 {lineitem => $li_id, recv_time => undef}, {idlist => 1});
540 for my $lid_id (@$lid_ids) {
541 receive_lineitem_detail($mgr, $lid_id, 1) or return 0;
545 $li->state('received');
547 $li = update_lineitem($mgr, $li) or return 0;
548 $mgr->post_process( sub { create_lineitem_status_events($mgr, $li_id, 'aur.received'); });
552 $skip_complete_check or (
553 $po = check_purchase_order_received($mgr, $li->purchase_order)
556 my $result = {"li" => {$li->id => {"state" => $li->state}}};
557 $result->{"po"} = describe_affected_po($mgr->editor, $po) if ref $po;
561 sub rollback_receive_lineitem {
562 my($mgr, $li_id) = @_;
563 my $li = $mgr->editor->retrieve_acq_lineitem($li_id) or return 0;
565 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
566 {lineitem => $li_id, recv_time => {'!=' => undef}}, {idlist => 1});
568 for my $lid_id (@$lid_ids) {
569 rollback_receive_lineitem_detail($mgr, $lid_id, 1) or return 0;
573 $li->state('on-order');
574 return update_lineitem($mgr, $li);
578 sub create_lineitem_status_events {
579 my($mgr, $li_id, $hook) = @_;
581 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
583 my $user_reqs = $mgr->editor->search_acq_user_request([
584 {lineitem => $li_id},
585 {flesh => 1, flesh_fields => {aur => ['usr']}}
588 for my $user_req (@$user_reqs) {
589 my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $user_req->usr->home_ou);
597 # ----------------------------------------------------------------------------
599 # ----------------------------------------------------------------------------
600 sub create_lineitem_detail {
601 my($mgr, %args) = @_;
602 my $lid = Fieldmapper::acq::lineitem_detail->new;
603 $lid->$_($args{$_}) for keys %args;
606 return $mgr->editor->create_acq_lineitem_detail($lid);
610 # flesh out any required data with default values where appropriate
611 sub complete_lineitem_detail {
613 unless($lid->barcode) {
614 my $pfx = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.tmp_barcode_prefix') || 'ACQ';
615 $lid->barcode($pfx.$lid->id);
618 unless($lid->cn_label) {
619 my $pfx = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.tmp_callnumber_prefix') || 'ACQ';
620 $lid->cn_label($pfx.$lid->id);
623 if(!$lid->location and my $loc = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.default_copy_location')) {
624 $lid->location($loc);
627 $lid->circ_modifier(get_default_circ_modifier($mgr, $lid->owning_lib))
628 unless defined $lid->circ_modifier;
630 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
634 sub get_default_circ_modifier {
636 my $code = $mgr->cache($org, 'def_circ_mod');
637 $code = $U->ou_ancestor_setting_value($org, 'acq.default_circ_modifier') unless defined $code;
638 return $mgr->cache($org, 'def_circ_mod', $code) if defined $code;
642 sub delete_lineitem_detail {
644 $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid) unless ref $lid;
645 return $mgr->editor->delete_acq_lineitem_detail($lid);
649 sub receive_lineitem_detail {
650 my($mgr, $lid_id, $skip_complete_check) = @_;
651 my $e = $mgr->editor;
653 my $lid = $e->retrieve_acq_lineitem_detail([
657 acqlid => ['fund_debit']
662 return 1 if $lid->recv_time;
664 $lid->receiver($e->requestor->id);
665 $lid->recv_time('now');
666 $e->update_acq_lineitem_detail($lid) or return 0;
668 if ($lid->eg_copy_id) {
669 my $copy = $e->retrieve_asset_copy($lid->eg_copy_id) or return 0;
670 $copy->status(OILS_COPY_STATUS_IN_PROCESS);
671 $copy->edit_date('now');
672 $copy->editor($e->requestor->id);
673 $copy->creator($e->requestor->id) if $U->ou_ancestor_setting_value(
674 $e->requestor->ws_ou, 'acq.copy_creator_uses_receiver', $e);
675 $e->update_asset_copy($copy) or return 0;
680 return 1 if $skip_complete_check;
682 my $li = check_lineitem_received($mgr, $lid->lineitem) or return 0;
683 return 1 if $li == 1; # li not received
685 return check_purchase_order_received($mgr, $li->purchase_order) or return 0;
689 sub rollback_receive_lineitem_detail {
690 my($mgr, $lid_id) = @_;
691 my $e = $mgr->editor;
693 my $lid = $e->retrieve_acq_lineitem_detail([
697 acqlid => ['fund_debit']
702 return 1 unless $lid->recv_time;
704 $lid->clear_receiver;
705 $lid->clear_recv_time;
706 $e->update_acq_lineitem_detail($lid) or return 0;
708 if ($lid->eg_copy_id) {
709 my $copy = $e->retrieve_asset_copy($lid->eg_copy_id) or return 0;
710 $copy->status(OILS_COPY_STATUS_ON_ORDER);
711 $copy->edit_date('now');
712 $copy->editor($e->requestor->id);
713 $e->update_asset_copy($copy) or return 0;
720 # ----------------------------------------------------------------------------
722 # ----------------------------------------------------------------------------
723 sub set_lineitem_attr {
724 my($mgr, %args) = @_;
725 my $attr_type = $args{attr_type};
727 # first, see if it's already set. May just need to overwrite it
728 my $attr = $mgr->editor->search_acq_lineitem_attr({
729 lineitem => $args{lineitem},
730 attr_type => $args{attr_type},
731 attr_name => $args{attr_name}
735 $attr->attr_value($args{attr_value});
736 return $attr if $mgr->editor->update_acq_lineitem_attr($attr);
741 $attr = Fieldmapper::acq::lineitem_attr->new;
742 $attr->$_($args{$_}) for keys %args;
744 unless($attr->definition) {
745 my $find = "search_acq_$attr_type";
746 my $attr_def_id = $mgr->editor->$find({code => $attr->attr_name}, {idlist=>1})->[0] or return 0;
747 $attr->definition($attr_def_id);
749 return $mgr->editor->create_acq_lineitem_attr($attr);
753 # ----------------------------------------------------------------------------
755 # ----------------------------------------------------------------------------
756 sub create_lineitem_debits {
757 my ($mgr, $li, $dry_run) = @_;
759 unless($li->estimated_unit_price) {
760 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_PRICE', payload => $li->id));
761 $mgr->editor->rollback;
765 unless($li->provider) {
766 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_PROVIDER', payload => $li->id));
767 $mgr->editor->rollback;
771 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
772 {lineitem => $li->id},
776 for my $lid_id (@$lid_ids) {
778 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
781 flesh_fields => {acqlid => ['fund']}
785 create_lineitem_detail_debit($mgr, $li, $lid, $dry_run) or return 0;
794 sub create_lineitem_detail_debit {
795 my ($mgr, $li, $lid, $dry_run, $no_translate) = @_;
797 # don't create the debit if one already exists
798 return $mgr->editor->retrieve_acq_fund_debit($lid->fund_debit) if $lid->fund_debit;
800 my $li_id = ref($li) ? $li->id : $li;
802 unless(ref $li and ref $li->provider) {
803 $li = $mgr->editor->retrieve_acq_lineitem([
806 flesh_fields => {jub => ['provider']},
812 $lid->fund($mgr->editor->retrieve_acq_fund($lid->fund)) unless(ref $lid->fund);
814 $lid = $mgr->editor->retrieve_acq_lineitem_detail([
817 flesh_fields => {acqlid => ['fund']}
822 unless ($lid->fund) {
824 new OpenILS::Event("ACQ_FUND_NOT_FOUND") # close enough
829 my $amount = $li->estimated_unit_price;
830 if($li->provider->currency_type ne $lid->fund->currency_type and !$no_translate) {
832 # At Fund debit creation time, translate into the currency of the fund
833 # TODO: org setting to disable automatic currency conversion at debit create time?
835 $amount = $mgr->editor->json_query({
837 'acq.exchange_ratio',
838 $li->provider->currency_type, # source currency
839 $lid->fund->currency_type, # destination currency
840 $li->estimated_unit_price # source amount
842 })->[0]->{'acq.exchange_ratio'};
845 my $debit = create_fund_debit(
848 fund => $lid->fund->id,
849 origin_amount => $li->estimated_unit_price,
850 origin_currency_type => $li->provider->currency_type,
854 $lid->fund_debit($debit->id);
855 $lid->fund($lid->fund->id);
856 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
861 __PACKAGE__->register_method(
862 "method" => "fund_exceeds_balance_percent_api",
863 "api_name" => "open-ils.acq.fund.check_balance_percentages",
865 "desc" => q/Determine whether a given fund exceeds its defined
866 "balance stop and warning percentages"/,
868 {"desc" => "Authentication token", "type" => "string"},
869 {"desc" => "Fund ID", "type" => "number"},
870 {"desc" => "Theoretical debit amount (optional)",
873 "return" => {"desc" => q/An array of two values, for stop and warning,
874 in that order: 1 if fund exceeds that balance percentage, else 0/}
878 sub fund_exceeds_balance_percent_api {
879 my ($self, $conn, $auth, $fund_id, $debit_amount) = @_;
883 my $e = new_editor("authtoken" => $auth);
884 return $e->die_event unless $e->checkauth;
886 my $fund = $e->retrieve_acq_fund($fund_id) or return $e->die_event;
887 return $e->die_event unless $e->allowed("VIEW_FUND", $fund->org);
890 fund_exceeds_balance_percent($fund, $debit_amount, $e, "stop"),
891 fund_exceeds_balance_percent($fund, $debit_amount, $e, "warning")
898 sub fund_exceeds_balance_percent {
899 my ($fund, $debit_amount, $e, $which) = @_;
901 my ($method_name, $event_name) = @{{
903 "balance_warning_percent", "ACQ_FUND_EXCEEDS_WARN_PERCENT"
906 "balance_stop_percent", "ACQ_FUND_EXCEEDS_STOP_PERCENT"
910 if ($fund->$method_name) {
912 $e->search_acq_fund_combined_balance({"fund" => $fund->id})->[0];
914 $e->search_acq_fund_allocation_total({"fund" => $fund->id})->[0];
916 $balance = ($balance) ? $balance->amount : 0;
917 $allocations = ($allocations) ? $allocations->amount : 0;
920 $allocations == 0 || # if no allocations were ever made, assume we have hit the stop percent
921 ((($allocations - $balance + $debit_amount) / $allocations) * 100) > $fund->$method_name
923 $logger->info("fund would hit a limit: " . $fund->id . ", $balance, $debit_amount, $allocations, $method_name");
928 "fund" => $fund, "debit_amount" => $debit_amount
938 # ----------------------------------------------------------------------------
940 # ----------------------------------------------------------------------------
941 sub create_fund_debit {
942 my($mgr, $dry_run, %args) = @_;
944 # Verify the fund is not being spent beyond the hard stop amount
945 my $fund = $mgr->editor->retrieve_acq_fund($args{fund}) or return 0;
948 fund_exceeds_balance_percent(
949 $fund, $args{"amount"}, $mgr->editor, "stop"
952 $dry_run and fund_exceeds_balance_percent(
953 $fund, $args{"amount"}, $mgr->editor, "warning"
956 my $debit = Fieldmapper::acq::fund_debit->new;
957 $debit->debit_type('purchase');
958 $debit->encumbrance('t');
959 $debit->$_($args{$_}) for keys %args;
961 $mgr->add_debit($debit->amount);
962 return $mgr->editor->create_acq_fund_debit($debit);
966 # ----------------------------------------------------------------------------
968 # ----------------------------------------------------------------------------
969 sub create_picklist {
970 my($mgr, %args) = @_;
971 my $picklist = Fieldmapper::acq::picklist->new;
972 $picklist->creator($mgr->editor->requestor->id);
973 $picklist->owner($picklist->creator);
974 $picklist->editor($picklist->creator);
975 $picklist->create_time('now');
976 $picklist->edit_time('now');
977 $picklist->org_unit($mgr->editor->requestor->ws_ou);
978 $picklist->owner($mgr->editor->requestor->id);
979 $picklist->$_($args{$_}) for keys %args;
981 $mgr->picklist($picklist);
982 return $mgr->editor->create_acq_picklist($picklist);
985 sub update_picklist {
986 my($mgr, $picklist) = @_;
987 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
988 $picklist->edit_time('now');
989 $picklist->editor($mgr->editor->requestor->id);
990 if ($mgr->editor->update_acq_picklist($picklist)) {
991 $picklist = $mgr->editor->retrieve_acq_picklist($mgr->editor->data);
992 $mgr->picklist($picklist);
999 sub delete_picklist {
1000 my($mgr, $picklist) = @_;
1001 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
1003 # delete all 'new' lineitems
1004 my $li_ids = $mgr->editor->search_acq_lineitem(
1006 picklist => $picklist->id,
1007 "-or" => {state => "new", purchase_order => undef}
1011 for my $li_id (@$li_ids) {
1012 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
1013 return 0 unless delete_lineitem($mgr, $li);
1017 # detach all non-'new' lineitems
1018 $li_ids = $mgr->editor->search_acq_lineitem({picklist => $picklist->id, state => {'!=' => 'new'}}, {idlist => 1});
1019 for my $li_id (@$li_ids) {
1020 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
1021 $li->clear_picklist;
1022 return 0 unless update_lineitem($mgr, $li);
1026 # remove any picklist-specific object perms
1027 my $ops = $mgr->editor->search_permission_usr_object_perm_map({object_type => 'acqpl', object_id => ''.$picklist->id});
1028 for my $op (@$ops) {
1029 return 0 unless $mgr->editor->delete_usr_object_perm_map($op);
1032 return $mgr->editor->delete_acq_picklist($picklist);
1035 # ----------------------------------------------------------------------------
1037 # ----------------------------------------------------------------------------
1038 sub update_purchase_order {
1040 $po = $mgr->editor->retrieve_acq_purchase_order($po) unless ref $po;
1041 $po->editor($mgr->editor->requestor->id);
1042 $po->edit_time('now');
1043 $mgr->purchase_order($po);
1044 return $mgr->editor->retrieve_acq_purchase_order($mgr->editor->data)
1045 if $mgr->editor->update_acq_purchase_order($po);
1049 sub create_purchase_order {
1050 my($mgr, %args) = @_;
1052 # verify the chosen provider is still active
1053 my $provider = $mgr->editor->retrieve_acq_provider($args{provider}) or return 0;
1054 unless($U->is_true($provider->active)) {
1055 $logger->error("provider is not active. cannot create PO");
1056 $mgr->editor->event(OpenILS::Event->new('ACQ_PROVIDER_INACTIVE'));
1060 my $po = Fieldmapper::acq::purchase_order->new;
1061 $po->creator($mgr->editor->requestor->id);
1062 $po->editor($mgr->editor->requestor->id);
1063 $po->owner($mgr->editor->requestor->id);
1064 $po->edit_time('now');
1065 $po->create_time('now');
1066 $po->state('pending');
1067 $po->ordering_agency($mgr->editor->requestor->ws_ou);
1068 $po->$_($args{$_}) for keys %args;
1070 $mgr->purchase_order($po);
1071 return $mgr->editor->create_acq_purchase_order($po);
1074 # ----------------------------------------------------------------------------
1075 # if all of the lineitems for this PO are received,
1076 # mark the PO as received
1077 # ----------------------------------------------------------------------------
1078 sub check_purchase_order_received {
1079 my($mgr, $po_id) = @_;
1081 my $non_recv_li = $mgr->editor->search_acq_lineitem(
1082 { purchase_order => $po_id,
1083 state => {'!=' => 'received'}
1086 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id);
1087 return $po if @$non_recv_li;
1089 $po->state('received');
1090 return update_purchase_order($mgr, $po);
1094 # ----------------------------------------------------------------------------
1095 # Bib, Callnumber, and Copy data
1096 # ----------------------------------------------------------------------------
1098 sub create_lineitem_assets {
1099 my($mgr, $li_id) = @_;
1102 my $li = $mgr->editor->retrieve_acq_lineitem([
1105 flesh_fields => {jub => ['purchase_order', 'attributes']}
1109 # note: at this point, the bib record this LI links to should already be created
1111 # -----------------------------------------------------------------
1112 # The lineitem is going live, promote user request holds to real holds
1113 # -----------------------------------------------------------------
1114 promote_lineitem_holds($mgr, $li) or return 0;
1116 my $li_details = $mgr->editor->search_acq_lineitem_detail({lineitem => $li_id}, {idlist=>1});
1118 # -----------------------------------------------------------------
1119 # for each lineitem_detail, create the volume if necessary, create
1120 # a copy, and link them all together.
1121 # -----------------------------------------------------------------
1123 for my $lid_id (@{$li_details}) {
1125 my $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid_id) or return 0;
1126 next if $lid->eg_copy_id;
1128 # use the same callnumber label for all items within this lineitem
1129 $lid->cn_label($first_cn) if $first_cn and not $lid->cn_label;
1131 # apply defaults if necessary
1132 return 0 unless complete_lineitem_detail($mgr, $lid);
1134 $first_cn = $lid->cn_label unless $first_cn;
1136 my $org = $lid->owning_lib;
1137 my $label = $lid->cn_label;
1138 my $bibid = $li->eg_bib_id;
1140 my $volume = $mgr->cache($org, "cn.$bibid.$label");
1142 $volume = create_volume($mgr, $li, $lid) or return 0;
1143 $mgr->cache($org, "cn.$bibid.$label", $volume);
1145 create_copy($mgr, $volume, $lid, $li) or return 0;
1148 return { li => $li };
1152 my($mgr, $li, $lid) = @_;
1154 my ($volume, $evt) =
1155 OpenILS::Application::Cat::AssetCommon->find_or_create_volume(
1163 $mgr->editor->event($evt);
1171 my($mgr, $volume, $lid, $li) = @_;
1172 my $copy = Fieldmapper::asset::copy->new;
1174 $copy->loan_duration(2);
1175 $copy->fine_level(2);
1176 $copy->status(($lid->recv_time) ? OILS_COPY_STATUS_IN_PROCESS : OILS_COPY_STATUS_ON_ORDER);
1177 $copy->barcode($lid->barcode);
1178 $copy->location($lid->location);
1179 $copy->call_number($volume->id);
1180 $copy->circ_lib($volume->owning_lib);
1181 $copy->circ_modifier($lid->circ_modifier);
1183 # AKA list price. We might need a $li->list_price field since
1184 # estimated price is not necessarily the same as list price
1185 $copy->price($li->estimated_unit_price);
1187 my $evt = OpenILS::Application::Cat::AssetCommon->create_copy($mgr->editor, $volume, $copy);
1189 $mgr->editor->event($evt);
1194 $lid->eg_copy_id($copy->id);
1195 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
1203 # ----------------------------------------------------------------------------
1204 # Workflow: Build a selection list from a Z39.50 search
1205 # ----------------------------------------------------------------------------
1207 __PACKAGE__->register_method(
1208 method => 'zsearch',
1209 api_name => 'open-ils.acq.picklist.search.z3950',
1212 desc => 'Performs a z3950 federated search and creates a picklist and associated lineitems',
1214 {desc => 'Authentication token', type => 'string'},
1215 {desc => 'Search definition', type => 'object'},
1216 {desc => 'Picklist name, optional', type => 'string'},
1222 my($self, $conn, $auth, $search, $name, $options) = @_;
1223 my $e = new_editor(authtoken=>$auth);
1224 return $e->event unless $e->checkauth;
1225 return $e->event unless $e->allowed('CREATE_PICKLIST');
1227 $search->{limit} ||= 10;
1230 my $ses = OpenSRF::AppSession->create('open-ils.search');
1231 my $req = $ses->request('open-ils.search.z3950.search_class', $auth, $search);
1236 while(my $resp = $req->recv(timeout=>60)) {
1239 my $e = new_editor(requestor=>$e->requestor, xact=>1);
1240 $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1241 $picklist = zsearch_build_pl($mgr, $name);
1245 my $result = $resp->content;
1246 my $count = $result->{count} || 0;
1247 $mgr->total( (($count < $search->{limit}) ? $count : $search->{limit})+1 );
1249 for my $rec (@{$result->{records}}) {
1251 my $li = create_lineitem($mgr,
1252 picklist => $picklist->id,
1253 source_label => $result->{service},
1254 marc => $rec->{marcxml},
1255 eg_bib_id => $rec->{bibid}
1258 if($$options{respond_li}) {
1259 $li->attributes($mgr->editor->search_acq_lineitem_attr({lineitem => $li->id}))
1260 if $$options{flesh_attrs};
1261 $li->clear_marc if $$options{clear_marc};
1262 $mgr->respond(lineitem => $li);
1269 $mgr->editor->commit;
1270 return $mgr->respond_complete;
1273 sub zsearch_build_pl {
1274 my($mgr, $name) = @_;
1277 my $picklist = $mgr->editor->search_acq_picklist({
1278 owner => $mgr->editor->requestor->id,
1282 if($name eq '' and $picklist) {
1283 return 0 unless delete_picklist($mgr, $picklist);
1287 return update_picklist($mgr, $picklist) if $picklist;
1288 return create_picklist($mgr, name => $name);
1292 # ----------------------------------------------------------------------------
1293 # Workflow: Build a selection list / PO by importing a batch of MARC records
1294 # ----------------------------------------------------------------------------
1296 __PACKAGE__->register_method(
1297 method => 'upload_records',
1298 api_name => 'open-ils.acq.process_upload_records',
1300 max_chunk_count => 1
1303 sub upload_records {
1304 my($self, $conn, $auth, $key, $args) = @_;
1307 my $e = new_editor(authtoken => $auth, xact => 1);
1308 return $e->die_event unless $e->checkauth;
1309 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1311 my $cache = OpenSRF::Utils::Cache->new;
1313 my $data = $cache->get_cache("vandelay_import_spool_$key");
1314 my $filename = $data->{path};
1315 my $provider = $args->{provider};
1316 my $picklist = $args->{picklist};
1317 my $create_po = $args->{create_po};
1318 my $activate_po = $args->{activate_po};
1319 my $vandelay = $args->{vandelay};
1320 my $ordering_agency = $args->{ordering_agency} || $e->requestor->ws_ou;
1324 unless(-r $filename) {
1325 $logger->error("unable to read MARC file $filename");
1327 return OpenILS::Event->new('FILE_UPLOAD_ERROR', payload => {filename => $filename});
1330 $provider = $e->retrieve_acq_provider($provider) or return $e->die_event;
1333 $picklist = $e->retrieve_acq_picklist($picklist) or return $e->die_event;
1334 if($picklist->owner != $e->requestor->id) {
1335 return $e->die_event unless
1336 $e->allowed('CREATE_PICKLIST', $picklist->org_unit, $picklist);
1338 $mgr->picklist($picklist);
1342 return $e->die_event unless
1343 $e->allowed('CREATE_PURCHASE_ORDER', $ordering_agency);
1345 $po = create_purchase_order($mgr,
1346 ordering_agency => $ordering_agency,
1347 provider => $provider->id,
1349 ) or return $mgr->editor->die_event;
1352 $logger->info("acq processing MARC file=$filename");
1354 my $batch = new MARC::Batch ('USMARC', $filename);
1362 my ($err, $xml, $r);
1367 } catch Error with {
1369 $logger->warn("Proccessing of record $count in set $key failed with error $err. Skipping this record");
1376 $xml = clean_marc($r);
1377 } catch Error with {
1379 $logger->warn("Proccessing XML of record $count in set $key failed with error $err. Skipping this record");
1382 next if $err or not $xml;
1385 source_label => $provider->code,
1386 provider => $provider->id,
1390 $args{picklist} = $picklist->id if $picklist;
1392 $args{purchase_order} = $po->id;
1393 $args{state} = 'pending-order';
1396 my $li = create_lineitem($mgr, %args) or return $mgr->editor->die_event;
1398 $li->provider($provider); # flesh it, we'll need it later
1400 import_lineitem_details($mgr, $ordering_agency, $li) or return $mgr->editor->die_event;
1403 push(@li_list, $li->id);
1409 $cache->delete_cache('vandelay_import_spool_' . $key);
1411 if ($po and $activate_po) {
1412 my $die_event = activate_purchase_order_impl($mgr, $po->id, $vandelay);
1413 return $die_event if $die_event;
1415 } elsif ($vandelay) {
1416 $vandelay->{new_rec_perm} = 'IMPORT_ACQ_LINEITEM_BIB_RECORD_UPLOAD';
1417 create_lineitem_list_assets($mgr, \@li_list, $vandelay) or return $e->die_event;
1420 return $mgr->respond_complete;
1423 sub import_lineitem_details {
1424 my($mgr, $ordering_agency, $li) = @_;
1426 my $holdings = $mgr->editor->json_query({from => ['acq.extract_provider_holding_data', $li->id]});
1427 return 1 unless @$holdings;
1428 my $org_path = $U->get_org_ancestors($ordering_agency);
1429 $org_path = [ reverse (@$org_path) ];
1435 # create a lineitem detail for each copy in the data
1437 my $compiled = extract_lineitem_detail_data($mgr, $org_path, $holdings, $idx);
1438 last unless defined $compiled;
1439 return 0 unless $compiled;
1441 # this takes the price of the last copy and uses it as the lineitem price
1442 # need to determine if a given record would include different prices for the same item
1443 $price = $$compiled{estimated_price};
1445 last unless $$compiled{quantity};
1447 for(1..$$compiled{quantity}) {
1448 my $lid = create_lineitem_detail(
1450 lineitem => $li->id,
1451 owning_lib => $$compiled{owning_lib},
1452 cn_label => $$compiled{call_number},
1453 fund => $$compiled{fund},
1454 circ_modifier => $$compiled{circ_modifier},
1455 note => $$compiled{note},
1456 location => $$compiled{copy_location},
1457 collection_code => $$compiled{collection_code},
1458 barcode => $$compiled{barcode}
1466 $li->estimated_unit_price($price);
1467 update_lineitem($mgr, $li) or return 0;
1471 # return hash on success, 0 on error, undef on no more holdings
1472 sub extract_lineitem_detail_data {
1473 my($mgr, $org_path, $holdings, $index) = @_;
1475 my @data_list = grep { $_->{holding} eq $index } @$holdings;
1476 return undef unless @data_list;
1478 my %compiled = map { $_->{attr} => $_->{data} } @data_list;
1479 my $base_org = $$org_path[0];
1483 $logger->error("Item import extraction error: $msg");
1484 $logger->error('Holdings Data: ' . OpenSRF::Utils::JSON->perl2JSON(\%compiled));
1485 $mgr->editor->rollback;
1486 $mgr->editor->event(OpenILS::Event->new('ACQ_IMPORT_ERROR', payload => $msg));
1490 # ---------------------------------------------------------------------
1492 if(my $code = $compiled{fund_code}) {
1494 my $fund = $mgr->cache($base_org, "fund.$code");
1496 # search up the org tree for the most appropriate fund
1497 for my $org (@$org_path) {
1498 $fund = $mgr->editor->search_acq_fund(
1499 {org => $org, code => $code, year => DateTime->now->year}, {idlist => 1})->[0];
1503 return $killme->("no fund with code $code at orgs [@$org_path]") unless $fund;
1504 $compiled{fund} = $fund;
1505 $mgr->cache($base_org, "fund.$code", $fund);
1509 # ---------------------------------------------------------------------
1511 if(my $sn = $compiled{owning_lib}) {
1512 my $org_id = $mgr->cache($base_org, "orgsn.$sn") ||
1513 $mgr->editor->search_actor_org_unit({shortname => $sn}, {idlist => 1})->[0];
1514 return $killme->("invalid owning_lib defined: $sn") unless $org_id;
1515 $compiled{owning_lib} = $org_id;
1516 $mgr->cache($$org_path[0], "orgsn.$sn", $org_id);
1520 # ---------------------------------------------------------------------
1522 my $code = $compiled{circ_modifier};
1526 # verify this is a valid circ modifier
1527 return $killme->("invlalid circ_modifier $code") unless
1528 defined $mgr->cache($base_org, "mod.$code") or
1529 $mgr->editor->retrieve_config_circ_modifier($code);
1531 # if valid, cache for future tests
1532 $mgr->cache($base_org, "mod.$code", $code);
1535 $compiled{circ_modifier} = get_default_circ_modifier($mgr, $base_org);
1539 # ---------------------------------------------------------------------
1541 if( my $name = $compiled{copy_location}) {
1542 my $loc = $mgr->cache($base_org, "copy_loc.$name");
1544 for my $org (@$org_path) {
1545 $loc = $mgr->editor->search_asset_copy_location(
1546 {owning_lib => $org, name => $name}, {idlist => 1})->[0];
1550 return $killme->("Invalid copy location $name") unless $loc;
1551 $compiled{copy_location} = $loc;
1552 $mgr->cache($base_org, "copy_loc.$name", $loc);
1560 # ----------------------------------------------------------------------------
1561 # Workflow: Given an existing purchase order, import/create the bibs,
1562 # callnumber and copy objects
1563 # ----------------------------------------------------------------------------
1565 __PACKAGE__->register_method(
1566 method => 'create_po_assets',
1567 api_name => 'open-ils.acq.purchase_order.assets.create',
1569 desc => q/Creates assets for each lineitem in the purchase order/,
1571 {desc => 'Authentication token', type => 'string'},
1572 {desc => 'The purchase order id', type => 'number'},
1574 return => {desc => 'Streams a total versus completed counts object, event on error'}
1576 max_chunk_count => 1
1579 sub create_po_assets {
1580 my($self, $conn, $auth, $po_id, $args) = @_;
1583 my $e = new_editor(authtoken=>$auth, xact=>1);
1584 return $e->die_event unless $e->checkauth;
1585 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1587 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1589 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1591 # it's ugly, but it's fast. Get the total count of lineitem detail objects to process
1592 my $lid_total = $e->json_query({
1593 select => { acqlid => [{aggregate => 1, transform => 'count', column => 'id'}] },
1599 join => {acqpo => {fkey => 'purchase_order', field => 'id'}}
1603 where => {'+acqpo' => {id => $po_id}}
1606 $mgr->total(scalar(@$li_ids) + $lid_total);
1608 create_lineitem_list_assets($mgr, $li_ids, $args->{vandelay})
1609 or return $e->die_event;
1612 update_purchase_order($mgr, $po) or return $e->die_event;
1615 return $mgr->respond_complete;
1620 __PACKAGE__->register_method(
1621 method => 'create_purchase_order_api',
1622 api_name => 'open-ils.acq.purchase_order.create',
1624 desc => 'Creates a new purchase order',
1626 {desc => 'Authentication token', type => 'string'},
1627 {desc => 'purchase_order to create', type => 'object'}
1629 return => {desc => 'The purchase order id, Event on failure'}
1631 max_chunk_count => 1
1634 sub create_purchase_order_api {
1635 my($self, $conn, $auth, $po, $args) = @_;
1638 my $e = new_editor(xact=>1, authtoken=>$auth);
1639 return $e->die_event unless $e->checkauth;
1640 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
1641 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1644 my %pargs = (ordering_agency => $e->requestor->ws_ou); # default
1645 $pargs{provider} = $po->provider if $po->provider;
1646 $pargs{ordering_agency} = $po->ordering_agency if $po->ordering_agency;
1647 $pargs{prepayment_required} = $po->prepayment_required if $po->prepayment_required;
1648 my $vandelay = $args->{vandelay};
1650 $po = create_purchase_order($mgr, %pargs) or return $e->die_event;
1652 my $li_ids = $$args{lineitems};
1656 for my $li_id (@$li_ids) {
1658 my $li = $e->retrieve_acq_lineitem([
1660 {flesh => 1, flesh_fields => {jub => ['attributes']}}
1661 ]) or return $e->die_event;
1663 $li->provider($po->provider);
1664 $li->purchase_order($po->id);
1665 $li->state('pending-order');
1666 update_lineitem($mgr, $li) or return $e->die_event;
1671 # commit before starting the asset creation
1674 if($li_ids and $vandelay) {
1675 create_lineitem_list_assets($mgr, $li_ids, $vandelay) or return $e->die_event;
1678 return $mgr->respond_complete;
1683 __PACKAGE__->register_method(
1684 method => 'update_lineitem_fund_batch',
1685 api_name => 'open-ils.acq.lineitem.fund.update.batch',
1688 desc => q/Given a set of lineitem IDS, updates the fund for all attached lineitem details/
1692 sub update_lineitem_fund_batch {
1693 my($self, $conn, $auth, $li_ids, $fund_id) = @_;
1694 my $e = new_editor(xact=>1, authtoken=>$auth);
1695 return $e->die_event unless $e->checkauth;
1696 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1697 for my $li_id (@$li_ids) {
1698 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
1699 return $evt if $evt;
1700 my $li_details = $e->search_acq_lineitem_detail({lineitem => $li_id});
1701 $_->fund($fund_id) and $_->ischanged(1) for @$li_details;
1702 $evt = lineitem_detail_CUD_batch($mgr, $li_details);
1703 return $evt if $evt;
1708 return $mgr->respond_complete;
1713 __PACKAGE__->register_method(
1714 method => 'lineitem_detail_CUD_batch_api',
1715 api_name => 'open-ils.acq.lineitem_detail.cud.batch',
1718 desc => q/Creates a new purchase order line item detail. / .
1719 q/Additionally creates the associated fund_debit/,
1721 {desc => 'Authentication token', type => 'string'},
1722 {desc => 'List of lineitem_details to create', type => 'array'},
1723 {desc => 'Create Debits. Used for creating post-po-asset-creation debits', type => 'bool'},
1725 return => {desc => 'Streaming response of current position in the array'}
1729 __PACKAGE__->register_method(
1730 method => 'lineitem_detail_CUD_batch_api',
1731 api_name => 'open-ils.acq.lineitem_detail.cud.batch.dry_run',
1735 Dry run version of open-ils.acq.lineitem_detail.cud.batch.
1736 In dry_run mode, updated fund_debit's the exceed the warning
1737 percent return an event.
1743 sub lineitem_detail_CUD_batch_api {
1744 my($self, $conn, $auth, $li_details, $create_debits) = @_;
1745 my $e = new_editor(xact=>1, authtoken=>$auth);
1746 return $e->die_event unless $e->checkauth;
1747 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1748 my $dry_run = ($self->api_name =~ /dry_run/o);
1749 my $evt = lineitem_detail_CUD_batch($mgr, $li_details, $create_debits, $dry_run);
1750 return $evt if $evt;
1752 return $mgr->respond_complete;
1756 sub lineitem_detail_CUD_batch {
1757 my($mgr, $li_details, $create_debits, $dry_run) = @_;
1759 $mgr->total(scalar(@$li_details));
1760 my $e = $mgr->editor;
1764 my $fund_cache = {};
1767 for my $lid (@$li_details) {
1769 unless($li = $li_cache{$lid->lineitem}) {
1770 ($li, $evt) = fetch_and_check_li($e, $lid->lineitem, 'write');
1771 return $evt if $evt;
1775 $lid = create_lineitem_detail($mgr, %{$lid->to_bare_hash}) or return $e->die_event;
1776 if($create_debits) {
1777 $li->provider($e->retrieve_acq_provider($li->provider)) or return $e->die_event;
1778 $lid->fund($e->retrieve_acq_fund($lid->fund)) or return $e->die_event;
1779 create_lineitem_detail_debit($mgr, $li, $lid, 0, 1) or return $e->die_event;
1782 } elsif($lid->ischanged) {
1783 return $evt if $evt = handle_changed_lid($e, $lid, $dry_run, $fund_cache);
1785 } elsif($lid->isdeleted) {
1786 delete_lineitem_detail($mgr, $lid) or return $e->die_event;
1789 $mgr->respond(li => $li);
1790 $li_cache{$lid->lineitem} = $li;
1796 sub handle_changed_lid {
1797 my($e, $lid, $dry_run, $fund_cache) = @_;
1799 my $orig_lid = $e->retrieve_acq_lineitem_detail($lid->id) or return $e->die_event;
1801 # updating the fund, so update the debit
1802 if($orig_lid->fund_debit and $orig_lid->fund != $lid->fund) {
1804 my $debit = $e->retrieve_acq_fund_debit($orig_lid->fund_debit);
1805 my $new_fund = $$fund_cache{$lid->fund} =
1806 $$fund_cache{$lid->fund} || $e->retrieve_acq_fund($lid->fund);
1808 # check the thresholds
1809 return $e->die_event if
1810 fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "stop");
1811 return $e->die_event if $dry_run and
1812 fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "warning");
1814 $debit->fund($new_fund->id);
1815 $e->update_acq_fund_debit($debit) or return $e->die_event;
1818 $e->update_acq_lineitem_detail($lid) or return $e->die_event;
1823 __PACKAGE__->register_method(
1824 method => 'receive_po_api',
1825 api_name => 'open-ils.acq.purchase_order.receive'
1828 sub receive_po_api {
1829 my($self, $conn, $auth, $po_id) = @_;
1830 my $e = new_editor(xact => 1, authtoken => $auth);
1831 return $e->die_event unless $e->checkauth;
1832 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1834 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1835 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1837 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1839 for my $li_id (@$li_ids) {
1840 receive_lineitem($mgr, $li_id) or return $e->die_event;
1844 $po->state('received');
1845 update_purchase_order($mgr, $po) or return $e->die_event;
1848 return $mgr->respond_complete;
1852 # At the moment there's a lack of parallelism between the receive and unreceive
1853 # API methods for POs and the API methods for LIs and LIDs. The methods for
1854 # POs stream back objects as they act, whereas the methods for LIs and LIDs
1855 # atomically return an object that describes only what changed (in LIs and LIDs
1856 # themselves or in the objects to which to LIs and LIDs belong).
1858 # The methods for LIs and LIDs work the way they do to faciliate the UI's
1859 # maintaining correct information about the state of these things when a user
1860 # wants to receive or unreceive these objects without refreshing their whole
1861 # display. The UI feature for receiving and un-receiving a whole PO just
1862 # refreshes the whole display, so this absence of parallelism in the UI is also
1863 # relected in this module.
1865 # This could be neatened in the future by making POs receive and unreceive in
1866 # the same way the LIs and LIDs do.
1868 __PACKAGE__->register_method(
1869 method => 'receive_lineitem_detail_api',
1870 api_name => 'open-ils.acq.lineitem_detail.receive',
1872 desc => 'Mark a lineitem_detail as received',
1874 {desc => 'Authentication token', type => 'string'},
1875 {desc => 'lineitem detail ID', type => 'number'}
1878 "on success, object describing changes to LID and possibly " .
1879 "to LI and PO; on error, Event"
1884 sub receive_lineitem_detail_api {
1885 my($self, $conn, $auth, $lid_id) = @_;
1887 my $e = new_editor(xact=>1, authtoken=>$auth);
1888 return $e->die_event unless $e->checkauth;
1889 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1892 "flesh" => 2, "flesh_fields" => {
1893 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
1897 my $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1899 return $e->die_event unless $e->allowed(
1900 'RECEIVE_PURCHASE_ORDER', $lid->lineitem->purchase_order->ordering_agency);
1903 my $recvd = receive_lineitem_detail($mgr, $lid_id) or return $e->die_event;
1905 # .. and re-retrieve
1906 $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1908 # Now build result data structure.
1909 my $result = {"lid" => {$lid->id => {"recv_time" => $lid->recv_time}}};
1912 if ($recvd->class_name =~ /::purchase_order/) {
1913 $result->{"po"} = describe_affected_po($e, $recvd);
1915 $lid->lineitem->id => {"state" => $lid->lineitem->state}
1917 } elsif ($recvd->class_name =~ /::lineitem/) {
1918 $result->{"li"} = {$recvd->id => {"state" => $recvd->state}};
1922 describe_affected_po($e, $lid->lineitem->purchase_order);
1928 __PACKAGE__->register_method(
1929 method => 'receive_lineitem_api',
1930 api_name => 'open-ils.acq.lineitem.receive',
1932 desc => 'Mark a lineitem as received',
1934 {desc => 'Authentication token', type => 'string'},
1935 {desc => 'lineitem ID', type => 'number'}
1938 "on success, object describing changes to LI and possibly PO; " .
1944 sub receive_lineitem_api {
1945 my($self, $conn, $auth, $li_id) = @_;
1947 my $e = new_editor(xact=>1, authtoken=>$auth);
1948 return $e->die_event unless $e->checkauth;
1949 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1951 my $li = $e->retrieve_acq_lineitem([
1955 jub => ['purchase_order']
1958 ]) or return $e->die_event;
1960 return $e->die_event unless $e->allowed(
1961 'RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);
1963 my $res = receive_lineitem($mgr, $li_id) or return $e->die_event;
1965 $conn->respond_complete($res);
1966 $mgr->run_post_response_hooks
1970 __PACKAGE__->register_method(
1971 method => 'rollback_receive_po_api',
1972 api_name => 'open-ils.acq.purchase_order.receive.rollback'
1975 sub rollback_receive_po_api {
1976 my($self, $conn, $auth, $po_id) = @_;
1977 my $e = new_editor(xact => 1, authtoken => $auth);
1978 return $e->die_event unless $e->checkauth;
1979 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1981 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1982 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1984 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1986 for my $li_id (@$li_ids) {
1987 rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
1991 $po->state('on-order');
1992 update_purchase_order($mgr, $po) or return $e->die_event;
1995 return $mgr->respond_complete;
1999 __PACKAGE__->register_method(
2000 method => 'rollback_receive_lineitem_detail_api',
2001 api_name => 'open-ils.acq.lineitem_detail.receive.rollback',
2003 desc => 'Mark a lineitem_detail as Un-received',
2005 {desc => 'Authentication token', type => 'string'},
2006 {desc => 'lineitem detail ID', type => 'number'}
2009 "on success, object describing changes to LID and possibly " .
2010 "to LI and PO; on error, Event"
2015 sub rollback_receive_lineitem_detail_api {
2016 my($self, $conn, $auth, $lid_id) = @_;
2018 my $e = new_editor(xact=>1, authtoken=>$auth);
2019 return $e->die_event unless $e->checkauth;
2020 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2022 my $lid = $e->retrieve_acq_lineitem_detail([
2026 acqlid => ['lineitem'],
2027 jub => ['purchase_order']
2031 my $li = $lid->lineitem;
2032 my $po = $li->purchase_order;
2034 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2038 my $recvd = rollback_receive_lineitem_detail($mgr, $lid_id)
2039 or return $e->die_event;
2042 $result->{"lid"} = {$recvd->id => {"recv_time" => $recvd->recv_time}};
2044 $result->{"lid"} = {$lid->id => {"recv_time" => $lid->recv_time}};
2047 if ($li->state eq "received") {
2048 $li->state("on-order");
2049 $li = update_lineitem($mgr, $li) or return $e->die_event;
2050 $result->{"li"} = {$li->id => {"state" => $li->state}};
2053 if ($po->state eq "received") {
2054 $po->state("on-order");
2055 $po = update_purchase_order($mgr, $po) or return $e->die_event;
2057 $result->{"po"} = describe_affected_po($e, $po);
2059 $e->commit and return $result or return $e->die_event;
2062 __PACKAGE__->register_method(
2063 method => 'rollback_receive_lineitem_api',
2064 api_name => 'open-ils.acq.lineitem.receive.rollback',
2066 desc => 'Mark a lineitem as Un-received',
2068 {desc => 'Authentication token', type => 'string'},
2069 {desc => 'lineitem ID', type => 'number'}
2072 "on success, object describing changes to LI and possibly PO; " .
2078 sub rollback_receive_lineitem_api {
2079 my($self, $conn, $auth, $li_id) = @_;
2081 my $e = new_editor(xact=>1, authtoken=>$auth);
2082 return $e->die_event unless $e->checkauth;
2083 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2085 my $li = $e->retrieve_acq_lineitem([
2087 "flesh" => 1, "flesh_fields" => {"jub" => ["purchase_order"]}
2090 my $po = $li->purchase_order;
2092 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2094 $li = rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
2096 my $result = {"li" => {$li->id => {"state" => $li->state}}};
2097 if ($po->state eq "received") {
2098 $po->state("on-order");
2099 $po = update_purchase_order($mgr, $po) or return $e->die_event;
2101 $result->{"po"} = describe_affected_po($e, $po);
2103 $e->commit and return $result or return $e->die_event;
2107 __PACKAGE__->register_method(
2108 method => 'set_lineitem_price_api',
2109 api_name => 'open-ils.acq.lineitem.price.set',
2111 desc => 'Set lineitem price. If debits already exist, update them as well',
2113 {desc => 'Authentication token', type => 'string'},
2114 {desc => 'lineitem ID', type => 'number'}
2116 return => {desc => 'status blob, Event on error'}
2120 sub set_lineitem_price_api {
2121 my($self, $conn, $auth, $li_id, $price) = @_;
2123 my $e = new_editor(xact=>1, authtoken=>$auth);
2124 return $e->die_event unless $e->checkauth;
2125 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2127 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
2128 return $evt if $evt;
2130 $li->estimated_unit_price($price);
2131 update_lineitem($mgr, $li) or return $e->die_event;
2133 my $lid_ids = $e->search_acq_lineitem_detail(
2134 {lineitem => $li_id, fund_debit => {'!=' => undef}},
2138 for my $lid_id (@$lid_ids) {
2140 my $lid = $e->retrieve_acq_lineitem_detail([
2142 flesh => 1, flesh_fields => {acqlid => ['fund', 'fund_debit']}}
2145 $lid->fund_debit->amount($price);
2146 $e->update_acq_fund_debit($lid->fund_debit) or return $e->die_event;
2152 return $mgr->respond_complete;
2156 __PACKAGE__->register_method(
2157 method => 'clone_picklist_api',
2158 api_name => 'open-ils.acq.picklist.clone',
2160 desc => 'Clones a picklist, including lineitem and lineitem details',
2162 {desc => 'Authentication token', type => 'string'},
2163 {desc => 'Picklist ID', type => 'number'},
2164 {desc => 'New Picklist Name', type => 'string'}
2166 return => {desc => 'status blob, Event on error'}
2170 sub clone_picklist_api {
2171 my($self, $conn, $auth, $pl_id, $name) = @_;
2173 my $e = new_editor(xact=>1, authtoken=>$auth);
2174 return $e->die_event unless $e->checkauth;
2175 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2177 my $old_pl = $e->retrieve_acq_picklist($pl_id);
2178 my $new_pl = create_picklist($mgr, %{$old_pl->to_bare_hash}, name => $name) or return $e->die_event;
2180 my $li_ids = $e->search_acq_lineitem({picklist => $pl_id}, {idlist => 1});
2182 for my $li_id (@$li_ids) {
2184 # copy the lineitems
2185 my $li = $e->retrieve_acq_lineitem($li_id);
2186 my $new_li = create_lineitem($mgr, %{$li->to_bare_hash}, picklist => $new_pl->id) or return $e->die_event;
2188 my $lid_ids = $e->search_acq_lineitem_detail({lineitem => $li_id}, {idlist => 1});
2189 for my $lid_id (@$lid_ids) {
2191 # copy the lineitem details
2192 my $lid = $e->retrieve_acq_lineitem_detail($lid_id);
2193 create_lineitem_detail($mgr, %{$lid->to_bare_hash}, lineitem => $new_li->id) or return $e->die_event;
2200 return $mgr->respond_complete;
2204 __PACKAGE__->register_method(
2205 method => 'merge_picklist_api',
2206 api_name => 'open-ils.acq.picklist.merge',
2208 desc => 'Merges 2 or more picklists into a single list',
2210 {desc => 'Authentication token', type => 'string'},
2211 {desc => 'Lead Picklist ID', type => 'number'},
2212 {desc => 'List of subordinate picklist IDs', type => 'array'}
2214 return => {desc => 'status blob, Event on error'}
2218 sub merge_picklist_api {
2219 my($self, $conn, $auth, $lead_pl, $pl_list) = @_;
2221 my $e = new_editor(xact=>1, authtoken=>$auth);
2222 return $e->die_event unless $e->checkauth;
2223 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2225 # XXX perms on each picklist modified
2227 $lead_pl = $e->retrieve_acq_picklist($lead_pl) or return $e->die_event;
2228 # point all of the lineitems at the lead picklist
2229 my $li_ids = $e->search_acq_lineitem({picklist => $pl_list}, {idlist => 1});
2231 for my $li_id (@$li_ids) {
2232 my $li = $e->retrieve_acq_lineitem($li_id);
2233 $li->picklist($lead_pl);
2234 update_lineitem($mgr, $li) or return $e->die_event;
2238 # now delete the subordinate lists
2239 for my $pl_id (@$pl_list) {
2240 my $pl = $e->retrieve_acq_picklist($pl_id);
2241 $e->delete_acq_picklist($pl) or return $e->die_event;
2244 update_picklist($mgr, $lead_pl) or return $e->die_event;
2247 return $mgr->respond_complete;
2251 __PACKAGE__->register_method(
2252 method => 'delete_picklist_api',
2253 api_name => 'open-ils.acq.picklist.delete',
2255 desc => q/Deletes a picklist. It also deletes any lineitems in the "new" state. / .
2256 q/Other attached lineitems are detached/,
2258 {desc => 'Authentication token', type => 'string'},
2259 {desc => 'Picklist ID to delete', type => 'number'}
2261 return => {desc => '1 on success, Event on error'}
2265 sub delete_picklist_api {
2266 my($self, $conn, $auth, $picklist_id) = @_;
2267 my $e = new_editor(xact=>1, authtoken=>$auth);
2268 return $e->die_event unless $e->checkauth;
2269 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2270 my $pl = $e->retrieve_acq_picklist($picklist_id) or return $e->die_event;
2271 delete_picklist($mgr, $pl) or return $e->die_event;
2273 return $mgr->respond_complete;
2278 __PACKAGE__->register_method(
2279 method => 'activate_purchase_order',
2280 api_name => 'open-ils.acq.purchase_order.activate.dry_run'
2283 __PACKAGE__->register_method(
2284 method => 'activate_purchase_order',
2285 api_name => 'open-ils.acq.purchase_order.activate',
2287 desc => q/Activates a purchase order. This updates the status of the PO / .
2288 q/and Lineitems to 'on-order'. Activated PO's are ready for EDI delivery if appropriate./,
2290 {desc => 'Authentication token', type => 'string'},
2291 {desc => 'Purchase ID', type => 'number'}
2293 return => {desc => '1 on success, Event on error'}
2297 sub activate_purchase_order {
2298 my($self, $conn, $auth, $po_id, $vandelay) = @_;
2300 my $dry_run = ($self->api_name =~ /\.dry_run/) ? 1 : 0;
2301 my $e = new_editor(authtoken=>$auth);
2302 return $e->die_event unless $e->checkauth;
2303 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2304 my $die_event = activate_purchase_order_impl($mgr, $po_id, $vandelay, $dry_run);
2305 return $e->die_event if $die_event;
2306 $conn->respond_complete(1);
2307 $mgr->run_post_response_hooks unless $dry_run;
2311 # xacts managed within
2312 sub activate_purchase_order_impl {
2313 my ($mgr, $po_id, $vandelay, $dry_run) = @_;
2315 # read-only until lineitem asset creation
2316 my $e = $mgr->editor;
2319 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2320 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
2321 my $provider = $e->retrieve_acq_provider($po->provider);
2323 # find lineitems and create assets for all
2326 purchase_order => $po_id,
2327 state => [qw/pending-order new order-ready/]
2330 my $li_ids = $e->search_acq_lineitem($query, {idlist => 1});
2332 my $vl_resp; # imported li's and the queue the managing queue
2334 $e->rollback; # read-only thus far
2335 $vl_resp = create_lineitem_list_assets($mgr, $li_ids, $vandelay)
2336 or return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED');
2340 # create fund debits for lineitems
2342 for my $li_id (@$li_ids) {
2343 my $li = $e->retrieve_acq_lineitem($li_id);
2345 if (!$li->eg_bib_id and !$dry_run) {
2346 # we encountered a lineitem that was not successfully imported.
2347 # we cannot continue. rollback and report.
2349 return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED', {queue => $vl_resp->{queue}});
2352 $li->state('on-order');
2353 $li->claim_policy($provider->default_claim_policy)
2354 if $provider->default_claim_policy and !$li->claim_policy;
2355 create_lineitem_debits($mgr, $li, $dry_run) or return $e->die_event;
2356 update_lineitem($mgr, $li) or return $e->die_event;
2357 $mgr->post_process( sub { create_lineitem_status_events($mgr, $li->id, 'aur.ordered'); });
2361 # create po-item debits
2363 for my $po_item (@{$e->search_acq_po_item({purchase_order => $po_id})}) {
2365 my $debit = create_fund_debit(
2368 debit_type => 'direct_charge', # to match invoicing
2369 origin_amount => $po_item->estimated_cost,
2370 origin_currency_type => $e->retrieve_acq_fund($po_item->fund)->currency_type,
2371 amount => $po_item->estimated_cost,
2372 fund => $po_item->fund
2373 ) or return $e->die_event;
2374 $po_item->fund_debit($debit->id);
2375 $e->update_acq_po_item($po_item) or return $e->die_event;
2379 # mark PO as ordered
2381 $po->state('on-order');
2382 $po->order_date('now');
2383 update_purchase_order($mgr, $po) or return $e->die_event;
2386 $dry_run and $e->rollback or $e->commit;
2388 # tell the world we activated a PO
2389 $U->create_events_for_hook('acqpo.activated', $po, $po->ordering_agency) unless $dry_run;
2395 __PACKAGE__->register_method(
2396 method => 'split_purchase_order_by_lineitems',
2397 api_name => 'open-ils.acq.purchase_order.split_by_lineitems',
2399 desc => q/Splits a PO into many POs, 1 per lineitem. Only works for / .
2400 q/POs a) with more than one lineitems, and b) in the "pending" state./,
2402 {desc => 'Authentication token', type => 'string'},
2403 {desc => 'Purchase order ID', type => 'number'}
2405 return => {desc => 'list of new PO IDs on success, Event on error'}
2409 sub split_purchase_order_by_lineitems {
2410 my ($self, $conn, $auth, $po_id) = @_;
2412 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2413 return $e->die_event unless $e->checkauth;
2415 my $po = $e->retrieve_acq_purchase_order([
2418 "flesh_fields" => {"acqpo" => [qw/lineitems notes/]}
2420 ]) or return $e->die_event;
2422 return $e->die_event
2423 unless $e->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2425 unless ($po->state eq "pending") {
2427 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_LATE");
2430 unless (@{$po->lineitems} > 1) {
2432 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_SHORT");
2435 # To split an existing PO into many, it seems unwise to just delete the
2436 # original PO, so we'll instead detach all of the original POs' lineitems
2437 # but the first, then create new POs for each of the remaining LIs, and
2438 # then attach the LIs to their new POs.
2440 my @po_ids = ($po->id);
2441 my @moving_li = @{$po->lineitems};
2442 shift @moving_li; # discard first LI
2444 foreach my $li (@moving_li) {
2445 my $new_po = $po->clone;
2447 $new_po->clear_name;
2448 $new_po->creator($e->requestor->id);
2449 $new_po->editor($e->requestor->id);
2450 $new_po->owner($e->requestor->id);
2451 $new_po->edit_time("now");
2452 $new_po->create_time("now");
2454 $new_po = $e->create_acq_purchase_order($new_po);
2456 # Clone any notes attached to the old PO and attach to the new one.
2457 foreach my $note (@{$po->notes}) {
2458 my $new_note = $note->clone;
2459 $new_note->clear_id;
2460 $new_note->edit_time("now");
2461 $new_note->purchase_order($new_po->id);
2462 $e->create_acq_po_note($new_note);
2465 $li->edit_time("now");
2466 $li->purchase_order($new_po->id);
2467 $e->update_acq_lineitem($li);
2469 push @po_ids, $new_po->id;
2472 $po->edit_time("now");
2473 $e->update_acq_purchase_order($po);
2475 return \@po_ids if $e->commit;
2476 return $e->die_event;
2480 sub not_cancelable {
2482 (ref $o eq "HASH" and $o->{"textcode"} eq "ACQ_NOT_CANCELABLE");
2485 __PACKAGE__->register_method(
2486 method => "cancel_purchase_order_api",
2487 api_name => "open-ils.acq.purchase_order.cancel",
2489 desc => q/Cancels an on-order purchase order/,
2491 {desc => "Authentication token", type => "string"},
2492 {desc => "PO ID to cancel", type => "number"},
2493 {desc => "Cancel reason ID", type => "number"}
2495 return => {desc => q/Object describing changed POs, LIs and LIDs
2496 on success; Event on error./}
2500 sub cancel_purchase_order_api {
2501 my ($self, $conn, $auth, $po_id, $cancel_reason) = @_;
2503 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2504 return $e->die_event unless $e->checkauth;
2505 my $mgr = new OpenILS::Application::Acq::BatchManager(
2506 "editor" => $e, "conn" => $conn
2509 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2510 return new OpenILS::Event(
2511 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2514 my $result = cancel_purchase_order($mgr, $po_id, $cancel_reason) or
2515 return $e->die_event;
2516 if (not_cancelable($result)) { # event not from CStoreEditor
2519 } elsif ($result == -1) {
2521 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2524 $e->commit or return $e->die_event;
2526 # XXX create purchase order status events?
2528 if ($mgr->{post_commit}) {
2529 foreach my $func (@{$mgr->{post_commit}}) {
2537 sub cancel_purchase_order {
2538 my ($mgr, $po_id, $cancel_reason) = @_;
2540 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id) or return 0;
2542 # XXX is "cancelled" a typo? It's not correct US spelling, anyway.
2543 # Depending on context, this may not warrant an event.
2544 return -1 if $po->state eq "cancelled";
2546 # But this always does.
2547 return new OpenILS::Event(
2548 "ACQ_NOT_CANCELABLE", "note" => "purchase_order $po_id"
2549 ) unless ($po->state eq "on-order" or $po->state eq "pending");
2552 $mgr->editor->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2554 $po->state("cancelled");
2555 $po->cancel_reason($cancel_reason->id);
2557 my $li_ids = $mgr->editor->search_acq_lineitem(
2558 {"purchase_order" => $po_id}, {"idlist" => 1}
2561 my $result = {"li" => {}, "lid" => {}};
2562 foreach my $li_id (@$li_ids) {
2563 my $li_result = cancel_lineitem($mgr, $li_id, $cancel_reason)
2566 next if $li_result == -1; # already canceled:skip.
2567 return $li_result if not_cancelable($li_result); # not cancelable:stop.
2569 # Merge in each LI result (there's only going to be
2570 # one per call to cancel_lineitem).
2571 my ($k, $v) = each %{$li_result->{"li"}};
2572 $result->{"li"}->{$k} = $v;
2574 # Merge in each LID result (there may be many per call to
2576 while (($k, $v) = each %{$li_result->{"lid"}}) {
2577 $result->{"lid"}->{$k} = $v;
2581 # TODO who/what/where/how do we indicate this change for electronic orders?
2582 # TODO return changes to encumbered/spent
2583 # TODO maybe cascade up from smaller object to container object if last
2584 # smaller object in the container has been canceled?
2586 update_purchase_order($mgr, $po) or return 0;
2588 $po_id => {"state" => $po->state, "cancel_reason" => $cancel_reason}
2594 __PACKAGE__->register_method(
2595 method => "cancel_lineitem_api",
2596 api_name => "open-ils.acq.lineitem.cancel",
2598 desc => q/Cancels an on-order lineitem/,
2600 {desc => "Authentication token", type => "string"},
2601 {desc => "Lineitem ID to cancel", type => "number"},
2602 {desc => "Cancel reason ID", type => "number"}
2604 return => {desc => q/Object describing changed LIs and LIDs on success;
2609 __PACKAGE__->register_method(
2610 method => "cancel_lineitem_api",
2611 api_name => "open-ils.acq.lineitem.cancel.batch",
2613 desc => q/Batched version of open-ils.acq.lineitem.cancel/,
2614 return => {desc => q/Object describing changed LIs and LIDs on success;
2619 sub cancel_lineitem_api {
2620 my ($self, $conn, $auth, $li_id, $cancel_reason) = @_;
2622 my $batched = $self->api_name =~ /\.batch/;
2624 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2625 return $e->die_event unless $e->checkauth;
2626 my $mgr = new OpenILS::Application::Acq::BatchManager(
2627 "editor" => $e, "conn" => $conn
2630 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2631 return new OpenILS::Event(
2632 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2635 my ($result, $maybe_event);
2638 $result = {"li" => {}, "lid" => {}};
2639 foreach my $one_li_id (@$li_id) {
2640 my $one = cancel_lineitem($mgr, $one_li_id, $cancel_reason) or
2641 return $e->die_event;
2642 if (not_cancelable($one)) {
2643 $maybe_event = $one;
2644 } elsif ($result == -1) {
2645 $maybe_event = new OpenILS::Event("ACQ_ALREADY_CANCELED");
2649 while (($k, $v) = each %{$one->{"li"}}) {
2650 $result->{"li"}->{$k} = $v;
2653 if ($one->{"lid"}) {
2654 while (($k, $v) = each %{$one->{"lid"}}) {
2655 $result->{"lid"}->{$k} = $v;
2661 $result = cancel_lineitem($mgr, $li_id, $cancel_reason) or
2662 return $e->die_event;
2664 if (not_cancelable($result)) {
2667 } elsif ($result == -1) {
2669 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2673 if ($batched and not scalar keys %{$result->{"li"}}) {
2675 return $maybe_event;
2677 $e->commit or return $e->die_event;
2678 # create_lineitem_status_events should handle array li_id ok
2679 create_lineitem_status_events($mgr, $li_id, "aur.cancelled");
2681 if ($mgr->{post_commit}) {
2682 foreach my $func (@{$mgr->{post_commit}}) {
2691 sub cancel_lineitem {
2692 my ($mgr, $li_id, $cancel_reason) = @_;
2693 my $li = $mgr->editor->retrieve_acq_lineitem([
2694 $li_id, {flesh => 1, flesh_fields => {jub => ['purchase_order']}}
2697 return 0 unless $mgr->editor->allowed(
2698 "CREATE_PURCHASE_ORDER", $li->purchase_order->ordering_agency
2701 # Depending on context, this may not warrant an event.
2702 return -1 if $li->state eq "cancelled";
2704 # But this always does.
2705 return new OpenILS::Event(
2706 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id"
2708 (! $li->purchase_order) or (
2709 $li->purchase_order and (
2710 $li->state eq "on-order" or $li->state eq "pending-order"
2715 $li->state("cancelled");
2716 $li->cancel_reason($cancel_reason->id);
2718 my $lids = $mgr->editor->search_acq_lineitem_detail([{
2719 "lineitem" => $li_id
2722 flesh_fields => { acqlid => ['eg_copy_id'] }
2725 my $result = {"lid" => {}};
2727 foreach my $lid (@$lids) {
2728 my $lid_result = cancel_lineitem_detail($mgr, $lid->id, $cancel_reason)
2731 # gathering any real copies for deletion
2732 if ($lid->eg_copy_id) {
2733 $lid->eg_copy_id->isdeleted('t');
2734 push @$copies, $lid->eg_copy_id;
2737 next if $lid_result == -1; # already canceled: just skip it.
2738 return $lid_result if not_cancelable($lid_result); # not cxlable: stop.
2740 # Merge in each LID result (there's only going to be one per call to
2741 # cancel_lineitem_detail).
2742 my ($k, $v) = each %{$lid_result->{"lid"}};
2743 $result->{"lid"}->{$k} = $v;
2746 # Attempt to delete the gathered copies (this will also handle volume deletion and bib deletion)
2747 # Delete empty bibs according org unit setting
2748 my $force_delete_empty_bib = $U->ou_ancestor_setting_value(
2749 $mgr->editor->requestor->ws_ou, 'cat.bib.delete_on_no_copy_via_acq_lineitem_cancel', $mgr->editor);
2750 if (scalar(@$copies)>0) {
2752 my $delete_stats = undef;
2753 my $retarget_holds = [];
2754 my $cat_evt = OpenILS::Application::Cat::AssetCommon->update_fleshed_copies(
2755 $mgr->editor, $override, undef, $copies, $delete_stats, $retarget_holds,$force_delete_empty_bib);
2758 $logger->info("fleshed copy update failed with event: ".OpenSRF::Utils::JSON->perl2JSON($cat_evt));
2759 return new OpenILS::Event(
2760 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id", "payload" => $cat_evt
2764 # We can't do the following and stay within the same transaction, but that's okay, the hold targeter will pick these up later.
2765 #my $ses = OpenSRF::AppSession->create('open-ils.circ');
2766 #$ses->request('open-ils.circ.hold.reset.batch', $auth, $retarget_holds);
2769 # if we have a bib, check to see whether it has been deleted. if so, cancel any active holds targeting that bib
2770 if ($li->eg_bib_id) {
2771 my $bib = $mgr->editor->retrieve_biblio_record_entry($li->eg_bib_id) or return new OpenILS::Event(
2772 "ACQ_NOT_CANCELABLE", "note" => "Could not retrieve bib " . $li->eg_bib_id . " for lineitem $li_id"
2774 if ($U->is_true($bib->deleted)) {
2775 my $holds = $mgr->editor->search_action_hold_request(
2776 { cancel_time => undef,
2777 fulfillment_time => undef,
2778 target => $li->eg_bib_id
2782 my %cached_usr_home_ou = ();
2784 for my $hold (@$holds) {
2786 $logger->info("Cancelling hold ".$hold->id.
2787 " due to acq lineitem cancellation.");
2789 $hold->cancel_time('now');
2790 $hold->cancel_cause(5); # 'Staff forced'--we may want a new hold cancel cause reason for this
2791 $hold->cancel_note('Corresponding Acquistion Lineitem/Purchase Order was cancelled.');
2792 unless($mgr->editor->update_action_hold_request($hold)) {
2793 my $evt = $mgr->editor->event;
2794 $logger->error("Error updating hold ". $evt->textcode .":". $evt->desc .":". $evt->stacktrace);
2795 return new OpenILS::Event(
2796 "ACQ_NOT_CANCELABLE", "note" => "Could not cancel hold " . $hold->id . " for lineitem $li_id", "payload" => $evt
2799 if (! defined $mgr->{post_commit}) { # we need a mechanism for creating trigger events, but only if the transaction gets committed
2800 $mgr->{post_commit} = [];
2802 push @{ $mgr->{post_commit} }, sub {
2803 my $home_ou = $cached_usr_home_ou{$hold->usr};
2805 my $user = $mgr->editor->retrieve_actor_user($hold->usr); # FIXME: how do we want to handle failures here?
2806 $home_ou = $user->home_ou;
2807 $cached_usr_home_ou{$hold->usr} = $home_ou;
2809 $U->create_events_for_hook('hold_request.cancel.cancelled_order', $hold, $home_ou);
2815 update_lineitem($mgr, $li) or return 0;
2818 "state" => $li->state,
2819 "cancel_reason" => $cancel_reason
2826 __PACKAGE__->register_method(
2827 method => "cancel_lineitem_detail_api",
2828 api_name => "open-ils.acq.lineitem_detail.cancel",
2830 desc => q/Cancels an on-order lineitem detail/,
2832 {desc => "Authentication token", type => "string"},
2833 {desc => "Lineitem detail ID to cancel", type => "number"},
2834 {desc => "Cancel reason ID", type => "number"}
2836 return => {desc => q/Object describing changed LIDs on success;
2841 sub cancel_lineitem_detail_api {
2842 my ($self, $conn, $auth, $lid_id, $cancel_reason) = @_;
2844 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2845 return $e->die_event unless $e->checkauth;
2846 my $mgr = new OpenILS::Application::Acq::BatchManager(
2847 "editor" => $e, "conn" => $conn
2850 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2851 return new OpenILS::Event(
2852 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2855 my $result = cancel_lineitem_detail($mgr, $lid_id, $cancel_reason) or
2856 return $e->die_event;
2858 if (not_cancelable($result)) {
2861 } elsif ($result == -1) {
2863 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2866 $e->commit or return $e->die_event;
2868 # XXX create lineitem detail status events?
2872 sub cancel_lineitem_detail {
2873 my ($mgr, $lid_id, $cancel_reason) = @_;
2874 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
2878 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
2883 # Depending on context, this may not warrant an event.
2884 return -1 if $lid->cancel_reason;
2886 # But this always does.
2887 return new OpenILS::Event(
2888 "ACQ_NOT_CANCELABLE", "note" => "lineitem_detail $lid_id"
2890 (! $lid->lineitem->purchase_order) or
2892 (not $lid->recv_time) and
2894 $lid->lineitem->purchase_order and (
2895 $lid->lineitem->state eq "on-order" or
2896 $lid->lineitem->state eq "pending-order"
2901 return 0 unless $mgr->editor->allowed(
2902 "CREATE_PURCHASE_ORDER",
2903 $lid->lineitem->purchase_order->ordering_agency
2904 ) or (! $lid->lineitem->purchase_order);
2906 $lid->cancel_reason($cancel_reason->id);
2908 unless($U->is_true($cancel_reason->keep_debits)) {
2909 my $debit_id = $lid->fund_debit;
2910 $lid->clear_fund_debit;
2913 # item is cancelled. Remove the fund debit.
2914 my $debit = $mgr->editor->retrieve_acq_fund_debit($debit_id);
2915 if (!$U->is_true($debit->encumbrance)) {
2916 $mgr->editor->rollback;
2917 return OpenILS::Event->new('ACQ_NOT_CANCELABLE',
2918 note => "Debit is marked as paid: $debit_id");
2920 $mgr->editor->delete_acq_fund_debit($debit) or return $mgr->editor->die_event;
2924 # XXX LIDs don't have either an editor or a edit_time field. Should we
2925 # update these on the LI when we alter an LID?
2926 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
2928 return {"lid" => {$lid_id => {"cancel_reason" => $cancel_reason}}};
2932 __PACKAGE__->register_method(
2933 method => 'user_requests',
2934 api_name => 'open-ils.acq.user_request.retrieve.by_user_id',
2937 desc => 'Retrieve fleshed user requests and related data for a given user.',
2939 { desc => 'Authentication token', type => 'string' },
2940 { desc => 'User ID of the owner, or array of IDs', },
2941 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
2946 desc => 'Fleshed user requests and related data',
2952 __PACKAGE__->register_method(
2953 method => 'user_requests',
2954 api_name => 'open-ils.acq.user_request.retrieve.by_home_ou',
2957 desc => 'Retrieve fleshed user requests and related data for a given org unit or units.',
2959 { desc => 'Authentication token', type => 'string' },
2960 { desc => 'Org unit ID, or array of IDs', },
2961 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
2966 desc => 'Fleshed user requests and related data',
2973 my($self, $conn, $auth, $search_value, $options) = @_;
2974 my $e = new_editor(authtoken => $auth);
2975 return $e->event unless $e->checkauth;
2976 my $rid = $e->requestor->id;
2980 "select"=>{"aur"=>["id"],"au"=>["home_ou", {column => 'id', alias => 'usr_id'} ]},
2981 "from"=>{ "aur" => { "au" => {}, "jub" => { "type" => "left" } } },
2985 {"id"=>undef}, # this with the left-join pulls in requests without lineitems
2986 {"state"=>["new","on-order","pending-order"]} # FIXME - probably needs softcoding
2990 "order_by"=>[{"class"=>"aur", "field"=>"request_date", "direction"=>"desc"}]
2993 foreach (qw/ order_by limit offset /) {
2994 $query->{$_} = $options->{$_} if defined $options->{$_};
2996 if (defined $options->{'state'}) {
2997 $query->{'where'}->{'+jub'}->{'-or'}->[1]->{'state'} = $options->{'state'};
3000 if ($self->api_name =~ /by_user_id/) {
3001 $query->{'where'}->{'usr'} = $search_value;
3003 $query->{'where'}->{'+au'} = { 'home_ou' => $search_value };
3006 my $pertinent_ids = $e->json_query($query);
3009 for my $id_blob (@$pertinent_ids) {
3010 if ($rid != $id_blob->{usr_id}) {
3011 if (!defined $perm_test{ $id_blob->{home_ou} }) {
3012 $perm_test{ $id_blob->{home_ou} } = $e->allowed( ['user_request.view'], $id_blob->{home_ou} );
3014 if (!$perm_test{ $id_blob->{home_ou} }) {
3018 my $aur_obj = $e->retrieve_acq_user_request([
3020 {flesh => 1, flesh_fields => { "aur" => [ 'lineitem' ] } }
3022 if (! $aur_obj) { next; }
3024 if ($aur_obj->lineitem()) {
3025 $aur_obj->lineitem()->clear_marc();
3027 $conn->respond($aur_obj);
3033 __PACKAGE__->register_method (
3034 method => 'update_user_request',
3035 api_name => 'open-ils.acq.user_request.cancel.batch',
3038 desc => 'If given a cancel reason, will update the request with that reason, otherwise, this will delete the request altogether. The ' .
3039 'intention is for staff interfaces or processes to provide cancel reasons, and for patron interfaces to just delete the requests.' ,
3041 { desc => 'Authentication token', type => 'string' },
3042 { desc => 'ID or array of IDs for the user requests to cancel' },
3043 { desc => 'Cancel Reason ID (optional)', type => 'string' }
3046 desc => 'progress object, event on error',
3050 __PACKAGE__->register_method (
3051 method => 'update_user_request',
3052 api_name => 'open-ils.acq.user_request.set_no_hold.batch',
3055 desc => 'Remove the hold from a user request or set of requests',
3057 { desc => 'Authentication token', type => 'string' },
3058 { desc => 'ID or array of IDs for the user requests to modify' }
3061 desc => 'progress object, event on error',
3066 sub update_user_request {
3067 my($self, $conn, $auth, $aur_ids, $cancel_reason) = @_;
3068 my $e = new_editor(xact => 1, authtoken => $auth);
3069 return $e->die_event unless $e->checkauth;
3070 my $rid = $e->requestor->id;
3074 for my $id (@$aur_ids) {
3076 my $aur_obj = $e->retrieve_acq_user_request([
3079 flesh_fields => { "aur" => ['lineitem', 'usr'] }
3081 ]) or return $e->die_event;
3083 my $context_org = $aur_obj->usr()->home_ou();
3084 $aur_obj->usr( $aur_obj->usr()->id() );
3086 if ($rid != $aur_obj->usr) {
3087 if (!defined $perm_test{ $context_org }) {
3088 $perm_test{ $context_org } = $e->allowed( ['user_request.update'], $context_org );
3090 if (!$perm_test{ $context_org }) {
3095 if($self->api_name =~ /set_no_hold/) {
3096 if ($U->is_true($aur_obj->hold)) {
3098 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3102 if($self->api_name =~ /cancel/) {
3103 if ( $cancel_reason ) {
3104 $aur_obj->cancel_reason( $cancel_reason );
3105 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3106 create_user_request_events( $e, [ $aur_obj ], 'aur.rejected' );
3108 $e->delete_acq_user_request($aur_obj);
3112 $conn->respond({maximum => scalar(@$aur_ids), progress => $x++});
3116 return {complete => 1};
3119 __PACKAGE__->register_method (
3120 method => 'new_user_request',
3121 api_name => 'open-ils.acq.user_request.create',
3123 desc => 'Create a new user request object in the DB',
3125 { desc => 'Authentication token', type => 'string' },
3126 { desc => 'User request data hash. Hash keys match the fields for the "aur" object', type => 'object' }
3129 desc => 'The created user request object, or event on error'
3134 sub new_user_request {
3135 my($self, $conn, $auth, $form_data) = @_;
3136 my $e = new_editor(xact => 1, authtoken => $auth);
3137 return $e->die_event unless $e->checkauth;
3138 my $rid = $e->requestor->id;
3139 my $target_user_fleshed;
3140 if (! defined $$form_data{'usr'}) {
3141 $$form_data{'usr'} = $rid;
3143 if ($$form_data{'usr'} != $rid) {
3144 # See if the requestor can place the request on behalf of a different user.
3145 $target_user_fleshed = $e->retrieve_actor_user($$form_data{'usr'}) or return $e->die_event;
3146 $e->allowed('user_request.create', $target_user_fleshed->home_ou) or return $e->die_event;
3148 $target_user_fleshed = $e->requestor;
3149 $e->allowed('CREATE_PURCHASE_REQUEST') or return $e->die_event;
3151 if (! defined $$form_data{'pickup_lib'}) {
3152 if ($target_user_fleshed->ws_ou) {
3153 $$form_data{'pickup_lib'} = $target_user_fleshed->ws_ou;
3155 $$form_data{'pickup_lib'} = $target_user_fleshed->home_ou;
3158 if (! defined $$form_data{'request_type'}) {
3159 $$form_data{'request_type'} = 1; # Books
3161 my $aur_obj = new Fieldmapper::acq::user_request;
3163 $aur_obj->usr( $$form_data{'usr'} );
3164 $aur_obj->request_date( 'now' );
3165 for my $field ( keys %$form_data ) {
3166 if (defined $$form_data{$field} and $field !~ /^(id|lineitem|eg_bib|request_date|cancel_reason)$/) {
3167 $aur_obj->$field( $$form_data{$field} );
3171 $aur_obj = $e->create_acq_user_request($aur_obj) or return $e->die_event;
3173 $e->commit and create_user_request_events( $e, [ $aur_obj ], 'aur.created' );
3178 sub create_user_request_events {
3179 my($e, $user_reqs, $hook) = @_;
3181 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
3184 my %cached_usr_home_ou = ();
3185 for my $user_req (@$user_reqs) {
3186 my $home_ou = $cached_usr_home_ou{$user_req->usr};
3188 my $user = $e->retrieve_actor_user($user_req->usr) or return $e->die_event;
3189 $home_ou = $user->home_ou;
3190 $cached_usr_home_ou{$user_req->usr} = $home_ou;
3192 my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $home_ou);
3201 __PACKAGE__->register_method(
3202 method => "po_note_CUD_batch",
3203 api_name => "open-ils.acq.po_note.cud.batch",
3206 desc => q/Manage purchase order notes/,
3208 {desc => "Authentication token", type => "string"},
3209 {desc => "List of po_notes to manage", type => "array"},
3211 return => {desc => "Stream of successfully managed objects"}
3215 sub po_note_CUD_batch {
3216 my ($self, $conn, $auth, $notes) = @_;
3218 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3219 return $e->die_event unless $e->checkauth;
3222 my $total = @$notes;
3225 foreach my $note (@$notes) {
3227 $note->editor($e->requestor->id);
3228 $note->edit_time("now");
3231 $note->creator($e->requestor->id);
3232 $note = $e->create_acq_po_note($note) or return $e->die_event;
3233 } elsif ($note->isdeleted) {
3234 $e->delete_acq_po_note($note) or return $e->die_event;
3235 } elsif ($note->ischanged) {
3236 $e->update_acq_po_note($note) or return $e->die_event;
3239 unless ($note->isdeleted) {
3240 $note = $e->retrieve_acq_po_note($note->id) or
3241 return $e->die_event;
3245 {"maximum" => $total, "progress" => ++$count, "note" => $note}
3249 $e->commit and $conn->respond_complete or return $e->die_event;
3253 # retrieves a lineitem, fleshes its PO and PL, checks perms
3254 sub fetch_and_check_li {
3257 my $perm_mode = shift || 'read';
3259 my $li = $e->retrieve_acq_lineitem([
3262 flesh_fields => {jub => ['purchase_order', 'picklist']}
3264 ]) or return $e->die_event;
3266 if(my $po = $li->purchase_order) {
3267 my $perms = ($perm_mode eq 'read') ? 'VIEW_PURCHASE_ORDER' : 'CREATE_PURCHASE_ORDER';
3268 return ($li, $e->die_event) unless $e->allowed($perms, $po->ordering_agency);
3270 } elsif(my $pl = $li->picklist) {
3271 my $perms = ($perm_mode eq 'read') ? 'VIEW_PICKLIST' : 'CREATE_PICKLIST';
3272 return ($li, $e->die_event) unless $e->allowed($perms, $pl->org_unit);
3279 __PACKAGE__->register_method(
3280 method => "clone_distrib_form",
3281 api_name => "open-ils.acq.distribution_formula.clone",
3284 desc => q/Clone a distribution formula/,
3286 {desc => "Authentication token", type => "string"},
3287 {desc => "Original formula ID", type => 'integer'},
3288 {desc => "Name of new formula", type => 'string'},
3290 return => {desc => "ID of newly created formula"}
3294 sub clone_distrib_form {
3295 my($self, $client, $auth, $form_id, $new_name) = @_;
3297 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3298 return $e->die_event unless $e->checkauth;
3300 my $old_form = $e->retrieve_acq_distribution_formula($form_id) or return $e->die_event;
3301 return $e->die_event unless $e->allowed('ADMIN_ACQ_DISTRIB_FORMULA', $old_form->owner);
3303 my $new_form = Fieldmapper::acq::distribution_formula->new;
3305 $new_form->owner($old_form->owner);
3306 $new_form->name($new_name);
3307 $e->create_acq_distribution_formula($new_form) or return $e->die_event;
3309 my $entries = $e->search_acq_distribution_formula_entry({formula => $form_id});
3310 for my $entry (@$entries) {
3311 my $new_entry = Fieldmapper::acq::distribution_formula_entry->new;
3312 $new_entry->$_($entry->$_()) for $entry->real_fields;
3313 $new_entry->formula($new_form->id);
3314 $new_entry->clear_id;
3315 $e->create_acq_distribution_formula_entry($new_entry) or return $e->die_event;
3319 return $new_form->id;
3322 __PACKAGE__->register_method(
3323 method => 'add_li_to_po',
3324 api_name => 'open-ils.acq.purchase_order.add_lineitem',
3326 desc => q/Adds a lineitem to an existing purchase order/,
3328 {desc => 'Authentication token', type => 'string'},
3329 {desc => 'The purchase order id', type => 'number'},
3330 {desc => 'The lineitem ID', type => 'number'},
3332 return => {desc => 'Streams a total versus completed counts object, event on error'}
3337 my($self, $conn, $auth, $po_id, $li_id) = @_;
3339 my $e = new_editor(authtoken => $auth, xact => 1);
3340 return $e->die_event unless $e->checkauth;
3342 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
3344 my $po = $e->retrieve_acq_purchase_order($po_id)
3345 or return $e->die_event;
3347 my $li = $e->retrieve_acq_lineitem($li_id)
3348 or return $e->die_event;
3350 return $e->die_event unless
3351 $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
3353 unless ($po->state =~ /new|pending/) {
3355 return {success => 0, po => $po, error => 'bad-po-state'};
3358 unless ($li->state =~ /new|order-ready|pending-order/) {
3360 return {success => 0, li => $li, error => 'bad-li-state'};
3363 $li->purchase_order($po_id);
3364 $li->state('pending-order');
3365 update_lineitem($mgr, $li) or return $e->die_event;
3368 return {success => 1};