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;
324 my $q_needed = shift;
326 # we need valid args and (sometimes) a queue
327 return 0 unless $vandelay and (
329 $vandelay->{queue_name} or
330 $vandelay->{existing_queue}
333 # match-based merge/overlay import
334 return 2 if $vandelay->{merge_profile} and (
335 $vandelay->{auto_overlay_exact} or
336 $vandelay->{auto_overlay_1match} or
337 $vandelay->{auto_overlay_best_match}
341 return 2 if $vandelay->{import_no_match};
343 return 1; # queue only
346 sub find_or_create_vandelay_queue {
347 my ($e, $vandelay) = @_;
350 if (my $name = $vandelay->{queue_name}) {
352 # first, see if a queue w/ this name already exists
353 # for this user. If so, use that instead.
355 $queue = $e->search_vandelay_bib_queue(
356 {name => $name, owner => $e->requestor->id})->[0];
360 $logger->info("acq-vl: using existing queue $name");
364 $logger->info("acq-vl: creating new vandelay queue $name");
366 $queue = new Fieldmapper::vandelay::bib_queue;
368 $queue->queue_type('acq');
369 $queue->owner($e->requestor->id);
370 $queue->match_set($vandelay->{match_set} || undef); # avoid ''
371 $queue = $e->create_vandelay_bib_queue($queue) or return undef;
375 $queue = $e->retrieve_vandelay_bib_queue($vandelay->{existing_queue})
383 sub import_li_bibs_via_vandelay {
384 my ($mgr, $li_ids, $vandelay) = @_;
385 my $res = {li_ids => []};
386 my $e = $mgr->editor;
389 my $needs_importing = $e->search_acq_lineitem(
390 {id => $li_ids, eg_bib_id => undef},
394 if (!@$needs_importing) {
395 $logger->info("acq-vl: all records already imported. no Vandelay work to do");
396 return {li_ids => $li_ids};
399 # see if we have any records that are not yet linked to VL records (i.e.
400 # not in a queue). This will tell us if lack of a queue name is an error.
401 my $non_queued = $e->search_acq_lineitem(
402 {id => $needs_importing, queued_record => undef},
406 # add the already-imported records to the response list
407 push(@{$res->{li_ids}}, grep { $_ != @$needs_importing } @$li_ids);
409 $logger->info("acq-vl: processing recs via Vandelay with args: ".Dumper($vandelay));
411 my $vl_stat = test_vandelay_import_args($vandelay, scalar(@$non_queued));
413 $logger->error("acq-vl: invalid vandelay arguments for acq import (queue needed)");
419 # when any non-queued lineitems exist, their vandelay counterparts
420 # require a place to live.
421 $queue = find_or_create_vandelay_queue($e, $vandelay) or return $res;
424 # if all lineitems are already queued, the queue reported to the user
425 # is purely for information / convenience. pick a random queue.
426 $queue = $e->retrieve_acq_lineitem([
427 $needs_importing->[0], {
430 jub => ['queued_record'],
434 ])->queued_record->queue;
437 $mgr->{args}->{queue} = $queue;
439 # load the lineitems into the queue for merge processing
442 for my $li_id (@$needs_importing) {
444 my $li = $e->retrieve_acq_lineitem($li_id) or return $res;
446 if ($li->queued_record) {
447 $logger->info("acq-vl: $li_id already linked to a vandelay record");
448 push(@vqbr_ids, $li->queued_record);
451 $logger->info("acq-vl: creating new vandelay record for lineitem $li_id");
453 # create a new VL queued record and link it up
454 my $vqbr = Fieldmapper::vandelay::queued_bib_record->new;
455 $vqbr->marc($li->marc);
456 $vqbr->queue($queue->id);
457 $vqbr->bib_source($vandelay->{bib_source} || undef); # avoid ''
458 $vqbr = $e->create_vandelay_queued_bib_record($vqbr) or return $res;
459 push(@vqbr_ids, $vqbr->id);
461 # tell the acq record which vandelay record it's linked to
462 $li->queued_record($vqbr->id);
463 $e->update_acq_lineitem($li) or return $res;
471 $logger->info("acq-vl: created vandelay records [@vqbr_ids]");
473 # we have to commit the transaction now since
474 # vandelay uses its own transactions.
477 return $res if $vl_stat == 1; # queue only
479 # Import the bibs via vandelay. Note: Vandely will
480 # update acq.lineitem.eg_bib_id on successful import.
482 $vandelay->{report_all} = 1;
483 my $ses = OpenSRF::AppSession->create('open-ils.vandelay');
484 my $req = $ses->request(
485 'open-ils.vandelay.bib_record.list.import',
486 $e->authtoken, \@vqbr_ids, $vandelay);
488 # pull the responses, noting all that were successfully imported
490 while (my $resp = $req->recv(timeout => 600)) {
491 my $stat = $resp->content;
493 if(!$stat or $U->event_code($stat)) { # import failure
494 $logger->error("acq-vl: error importing vandelay record " . Dumper($stat));
498 # "imported" refers to the vqbr id, not the
499 # success/failure of the vqbr merge attempt
500 next unless $stat->{imported};
502 my ($imported) = grep {$_->queued_record eq $stat->{imported}} @lis;
503 my $li_id = $imported->id;
505 if ($stat->{no_import}) {
506 $logger->info("acq-vl: acq lineitem $li_id did not import");
508 } else { # successful import
510 push(@success_lis, $li_id);
513 $logger->info("acq-vl: acq lineitem $li_id successfully merged/imported");
518 $logger->info("acq-vl: successfully imported lineitems [@success_lis]");
520 # add the successfully imported lineitems to the already-imported lineitems
521 push (@{$res->{li_ids}}, @success_lis);
526 # returns event on error, undef on success
527 sub check_import_li_marc_perms {
528 my($mgr, $li_ids) = @_;
530 # if there are any order records that are not linked to
531 # in-db bib records, verify staff has perms to import order records
532 my $order_li = $mgr->editor->search_acq_lineitem(
533 [{id => $li_ids, eg_bib_id => undef}, {limit => 1}], {idlist => 1})->[0];
536 return $mgr->editor->die_event unless
537 $mgr->editor->allowed('IMPORT_ACQ_LINEITEM_BIB_RECORD');
544 # ----------------------------------------------------------------------------
545 # if all of the lineitem details for this lineitem have
546 # been received, mark the lineitem as received
547 # returns 1 on non-received, li on received, 0 on error
548 # ----------------------------------------------------------------------------
550 sub describe_affected_po {
554 OpenILS::Application::Acq::Financials::build_price_summary(
559 "state" => $po->state,
560 "amount_encumbered" => $enc,
561 "amount_spent" => $spent
566 sub check_lineitem_received {
567 my($mgr, $li_id) = @_;
569 my $non_recv = $mgr->editor->search_acq_lineitem_detail(
570 {recv_time => undef, lineitem => $li_id}, {idlist=>1});
572 return 1 if @$non_recv;
574 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
575 $li->state('received');
576 return update_lineitem($mgr, $li);
579 sub receive_lineitem {
580 my($mgr, $li_id, $skip_complete_check) = @_;
581 my $li = $mgr->editor->retrieve_acq_lineitem($li_id) or return 0;
583 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
584 {lineitem => $li_id, recv_time => undef}, {idlist => 1});
586 for my $lid_id (@$lid_ids) {
587 receive_lineitem_detail($mgr, $lid_id, 1) or return 0;
591 $li->state('received');
593 $li = update_lineitem($mgr, $li) or return 0;
594 $mgr->post_process( sub { create_lineitem_status_events($mgr, $li_id, 'aur.received'); });
598 $skip_complete_check or (
599 $po = check_purchase_order_received($mgr, $li->purchase_order)
602 my $result = {"li" => {$li->id => {"state" => $li->state}}};
603 $result->{"po"} = describe_affected_po($mgr->editor, $po) if ref $po;
607 sub rollback_receive_lineitem {
608 my($mgr, $li_id) = @_;
609 my $li = $mgr->editor->retrieve_acq_lineitem($li_id) or return 0;
611 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
612 {lineitem => $li_id, recv_time => {'!=' => undef}}, {idlist => 1});
614 for my $lid_id (@$lid_ids) {
615 rollback_receive_lineitem_detail($mgr, $lid_id, 1) or return 0;
619 $li->state('on-order');
620 return update_lineitem($mgr, $li);
624 sub create_lineitem_status_events {
625 my($mgr, $li_id, $hook) = @_;
627 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
629 my $user_reqs = $mgr->editor->search_acq_user_request([
630 {lineitem => $li_id},
631 {flesh => 1, flesh_fields => {aur => ['usr']}}
634 for my $user_req (@$user_reqs) {
635 my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $user_req->usr->home_ou);
643 # ----------------------------------------------------------------------------
645 # ----------------------------------------------------------------------------
646 sub create_lineitem_detail {
647 my($mgr, %args) = @_;
648 my $lid = Fieldmapper::acq::lineitem_detail->new;
649 $lid->$_($args{$_}) for keys %args;
652 return $mgr->editor->create_acq_lineitem_detail($lid);
656 # flesh out any required data with default values where appropriate
657 sub complete_lineitem_detail {
659 unless($lid->barcode) {
660 my $pfx = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.tmp_barcode_prefix') || 'ACQ';
661 $lid->barcode($pfx.$lid->id);
664 unless($lid->cn_label) {
665 my $pfx = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.tmp_callnumber_prefix') || 'ACQ';
666 $lid->cn_label($pfx.$lid->id);
669 if(!$lid->location and my $loc = $U->ou_ancestor_setting_value($lid->owning_lib, 'acq.default_copy_location')) {
670 $lid->location($loc);
673 $lid->circ_modifier(get_default_circ_modifier($mgr, $lid->owning_lib))
674 unless defined $lid->circ_modifier;
676 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
680 sub get_default_circ_modifier {
682 my $code = $mgr->cache($org, 'def_circ_mod');
683 $code = $U->ou_ancestor_setting_value($org, 'acq.default_circ_modifier') unless defined $code;
684 return $mgr->cache($org, 'def_circ_mod', $code) if defined $code;
688 sub delete_lineitem_detail {
690 $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid) unless ref $lid;
691 return $mgr->editor->delete_acq_lineitem_detail($lid);
695 sub receive_lineitem_detail {
696 my($mgr, $lid_id, $skip_complete_check) = @_;
697 my $e = $mgr->editor;
699 my $lid = $e->retrieve_acq_lineitem_detail([
703 acqlid => ['fund_debit']
708 return 1 if $lid->recv_time;
710 $lid->receiver($e->requestor->id);
711 $lid->recv_time('now');
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_IN_PROCESS);
717 $copy->edit_date('now');
718 $copy->editor($e->requestor->id);
719 $copy->creator($e->requestor->id) if $U->ou_ancestor_setting_value(
720 $e->requestor->ws_ou, 'acq.copy_creator_uses_receiver', $e);
721 $e->update_asset_copy($copy) or return 0;
726 return 1 if $skip_complete_check;
728 my $li = check_lineitem_received($mgr, $lid->lineitem) or return 0;
729 return 1 if $li == 1; # li not received
731 return check_purchase_order_received($mgr, $li->purchase_order) or return 0;
735 sub rollback_receive_lineitem_detail {
736 my($mgr, $lid_id) = @_;
737 my $e = $mgr->editor;
739 my $lid = $e->retrieve_acq_lineitem_detail([
743 acqlid => ['fund_debit']
748 return 1 unless $lid->recv_time;
750 $lid->clear_receiver;
751 $lid->clear_recv_time;
752 $e->update_acq_lineitem_detail($lid) or return 0;
754 if ($lid->eg_copy_id) {
755 my $copy = $e->retrieve_asset_copy($lid->eg_copy_id) or return 0;
756 $copy->status(OILS_COPY_STATUS_ON_ORDER);
757 $copy->edit_date('now');
758 $copy->editor($e->requestor->id);
759 $e->update_asset_copy($copy) or return 0;
766 # ----------------------------------------------------------------------------
768 # ----------------------------------------------------------------------------
769 sub set_lineitem_attr {
770 my($mgr, %args) = @_;
771 my $attr_type = $args{attr_type};
773 # first, see if it's already set. May just need to overwrite it
774 my $attr = $mgr->editor->search_acq_lineitem_attr({
775 lineitem => $args{lineitem},
776 attr_type => $args{attr_type},
777 attr_name => $args{attr_name}
781 $attr->attr_value($args{attr_value});
782 return $attr if $mgr->editor->update_acq_lineitem_attr($attr);
787 $attr = Fieldmapper::acq::lineitem_attr->new;
788 $attr->$_($args{$_}) for keys %args;
790 unless($attr->definition) {
791 my $find = "search_acq_$attr_type";
792 my $attr_def_id = $mgr->editor->$find({code => $attr->attr_name}, {idlist=>1})->[0] or return 0;
793 $attr->definition($attr_def_id);
795 return $mgr->editor->create_acq_lineitem_attr($attr);
799 # ----------------------------------------------------------------------------
801 # ----------------------------------------------------------------------------
802 sub create_lineitem_debits {
803 my ($mgr, $li, $dry_run, $options) = @_;
806 unless($li->estimated_unit_price) {
807 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_PRICE', payload => $li->id));
808 $mgr->editor->rollback;
812 unless($li->provider) {
813 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_PROVIDER', payload => $li->id));
814 $mgr->editor->rollback;
818 my $lid_ids = $mgr->editor->search_acq_lineitem_detail(
819 {lineitem => $li->id},
823 if (@$lid_ids == 0 and !$options->{zero_copy_activate}) {
824 $mgr->editor->event(OpenILS::Event->new('ACQ_LINEITEM_NO_COPIES', payload => $li->id));
825 $mgr->editor->rollback;
829 for my $lid_id (@$lid_ids) {
831 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
834 flesh_fields => {acqlid => ['fund']}
838 create_lineitem_detail_debit($mgr, $li, $lid, $dry_run) or return 0;
847 sub create_lineitem_detail_debit {
848 my ($mgr, $li, $lid, $dry_run, $no_translate) = @_;
850 # don't create the debit if one already exists
851 return $mgr->editor->retrieve_acq_fund_debit($lid->fund_debit) if $lid->fund_debit;
853 my $li_id = ref($li) ? $li->id : $li;
855 unless(ref $li and ref $li->provider) {
856 $li = $mgr->editor->retrieve_acq_lineitem([
859 flesh_fields => {jub => ['provider']},
865 $lid->fund($mgr->editor->retrieve_acq_fund($lid->fund)) unless(ref $lid->fund);
867 $lid = $mgr->editor->retrieve_acq_lineitem_detail([
870 flesh_fields => {acqlid => ['fund']}
875 unless ($lid->fund) {
877 new OpenILS::Event("ACQ_FUND_NOT_FOUND") # close enough
882 my $amount = $li->estimated_unit_price;
883 if($li->provider->currency_type ne $lid->fund->currency_type and !$no_translate) {
885 # At Fund debit creation time, translate into the currency of the fund
886 # TODO: org setting to disable automatic currency conversion at debit create time?
888 $amount = $mgr->editor->json_query({
890 'acq.exchange_ratio',
891 $li->provider->currency_type, # source currency
892 $lid->fund->currency_type, # destination currency
893 $li->estimated_unit_price # source amount
895 })->[0]->{'acq.exchange_ratio'};
898 my $debit = create_fund_debit(
901 fund => $lid->fund->id,
902 origin_amount => $li->estimated_unit_price,
903 origin_currency_type => $li->provider->currency_type,
907 $lid->fund_debit($debit->id);
908 $lid->fund($lid->fund->id);
909 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
914 __PACKAGE__->register_method(
915 "method" => "fund_exceeds_balance_percent_api",
916 "api_name" => "open-ils.acq.fund.check_balance_percentages",
918 "desc" => q/Determine whether a given fund exceeds its defined
919 "balance stop and warning percentages"/,
921 {"desc" => "Authentication token", "type" => "string"},
922 {"desc" => "Fund ID", "type" => "number"},
923 {"desc" => "Theoretical debit amount (optional)",
926 "return" => {"desc" => q/An array of two values, for stop and warning,
927 in that order: 1 if fund exceeds that balance percentage, else 0/}
931 sub fund_exceeds_balance_percent_api {
932 my ($self, $conn, $auth, $fund_id, $debit_amount) = @_;
936 my $e = new_editor("authtoken" => $auth);
937 return $e->die_event unless $e->checkauth;
939 my $fund = $e->retrieve_acq_fund($fund_id) or return $e->die_event;
940 return $e->die_event unless $e->allowed("VIEW_FUND", $fund->org);
943 fund_exceeds_balance_percent($fund, $debit_amount, $e, "stop"),
944 fund_exceeds_balance_percent($fund, $debit_amount, $e, "warning")
951 sub fund_exceeds_balance_percent {
952 my ($fund, $debit_amount, $e, $which) = @_;
954 my ($method_name, $event_name) = @{{
956 "balance_warning_percent", "ACQ_FUND_EXCEEDS_WARN_PERCENT"
959 "balance_stop_percent", "ACQ_FUND_EXCEEDS_STOP_PERCENT"
963 if ($fund->$method_name) {
965 $e->search_acq_fund_combined_balance({"fund" => $fund->id})->[0];
967 $e->search_acq_fund_allocation_total({"fund" => $fund->id})->[0];
969 $balance = ($balance) ? $balance->amount : 0;
970 $allocations = ($allocations) ? $allocations->amount : 0;
973 $allocations == 0 || # if no allocations were ever made, assume we have hit the stop percent
974 ((($allocations - $balance + $debit_amount) / $allocations) * 100) > $fund->$method_name
976 $logger->info("fund would hit a limit: " . $fund->id . ", $balance, $debit_amount, $allocations, $method_name");
981 "fund" => $fund, "debit_amount" => $debit_amount
991 # ----------------------------------------------------------------------------
993 # ----------------------------------------------------------------------------
994 sub create_fund_debit {
995 my($mgr, $dry_run, %args) = @_;
997 # Verify the fund is not being spent beyond the hard stop amount
998 my $fund = $mgr->editor->retrieve_acq_fund($args{fund}) or return 0;
1001 fund_exceeds_balance_percent(
1002 $fund, $args{"amount"}, $mgr->editor, "stop"
1005 $dry_run and fund_exceeds_balance_percent(
1006 $fund, $args{"amount"}, $mgr->editor, "warning"
1009 my $debit = Fieldmapper::acq::fund_debit->new;
1010 $debit->debit_type('purchase');
1011 $debit->encumbrance('t');
1012 $debit->$_($args{$_}) for keys %args;
1014 $mgr->add_debit($debit->amount);
1015 return $mgr->editor->create_acq_fund_debit($debit);
1019 # ----------------------------------------------------------------------------
1021 # ----------------------------------------------------------------------------
1022 sub create_picklist {
1023 my($mgr, %args) = @_;
1024 my $picklist = Fieldmapper::acq::picklist->new;
1025 $picklist->creator($mgr->editor->requestor->id);
1026 $picklist->owner($picklist->creator);
1027 $picklist->editor($picklist->creator);
1028 $picklist->create_time('now');
1029 $picklist->edit_time('now');
1030 $picklist->org_unit($mgr->editor->requestor->ws_ou);
1031 $picklist->owner($mgr->editor->requestor->id);
1032 $picklist->$_($args{$_}) for keys %args;
1033 $picklist->clear_id;
1034 $mgr->picklist($picklist);
1035 return $mgr->editor->create_acq_picklist($picklist);
1038 sub update_picklist {
1039 my($mgr, $picklist) = @_;
1040 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
1041 $picklist->edit_time('now');
1042 $picklist->editor($mgr->editor->requestor->id);
1043 if ($mgr->editor->update_acq_picklist($picklist)) {
1044 $picklist = $mgr->editor->retrieve_acq_picklist($mgr->editor->data);
1045 $mgr->picklist($picklist);
1052 sub delete_picklist {
1053 my($mgr, $picklist) = @_;
1054 $picklist = $mgr->editor->retrieve_acq_picklist($picklist) unless ref $picklist;
1056 # delete all 'new' lineitems
1057 my $li_ids = $mgr->editor->search_acq_lineitem(
1059 picklist => $picklist->id,
1060 "-or" => {state => "new", purchase_order => undef}
1064 for my $li_id (@$li_ids) {
1065 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
1066 return 0 unless delete_lineitem($mgr, $li);
1070 # detach all non-'new' lineitems
1071 $li_ids = $mgr->editor->search_acq_lineitem({picklist => $picklist->id, state => {'!=' => 'new'}}, {idlist => 1});
1072 for my $li_id (@$li_ids) {
1073 my $li = $mgr->editor->retrieve_acq_lineitem($li_id);
1074 $li->clear_picklist;
1075 return 0 unless update_lineitem($mgr, $li);
1079 # remove any picklist-specific object perms
1080 my $ops = $mgr->editor->search_permission_usr_object_perm_map({object_type => 'acqpl', object_id => ''.$picklist->id});
1081 for my $op (@$ops) {
1082 return 0 unless $mgr->editor->delete_usr_object_perm_map($op);
1085 return $mgr->editor->delete_acq_picklist($picklist);
1088 # ----------------------------------------------------------------------------
1090 # ----------------------------------------------------------------------------
1091 sub update_purchase_order {
1093 $po = $mgr->editor->retrieve_acq_purchase_order($po) unless ref $po;
1094 $po->editor($mgr->editor->requestor->id);
1095 $po->edit_time('now');
1096 $mgr->purchase_order($po);
1097 return $mgr->editor->retrieve_acq_purchase_order($mgr->editor->data)
1098 if $mgr->editor->update_acq_purchase_order($po);
1102 sub create_purchase_order {
1103 my($mgr, %args) = @_;
1105 # verify the chosen provider is still active
1106 my $provider = $mgr->editor->retrieve_acq_provider($args{provider}) or return 0;
1107 unless($U->is_true($provider->active)) {
1108 $logger->error("provider is not active. cannot create PO");
1109 $mgr->editor->event(OpenILS::Event->new('ACQ_PROVIDER_INACTIVE'));
1113 my $po = Fieldmapper::acq::purchase_order->new;
1114 $po->creator($mgr->editor->requestor->id);
1115 $po->editor($mgr->editor->requestor->id);
1116 $po->owner($mgr->editor->requestor->id);
1117 $po->edit_time('now');
1118 $po->create_time('now');
1119 $po->state('pending');
1120 $po->ordering_agency($mgr->editor->requestor->ws_ou);
1121 $po->$_($args{$_}) for keys %args;
1123 $mgr->purchase_order($po);
1124 return $mgr->editor->create_acq_purchase_order($po);
1127 # ----------------------------------------------------------------------------
1128 # if all of the lineitems for this PO are received,
1129 # mark the PO as received
1130 # ----------------------------------------------------------------------------
1131 sub check_purchase_order_received {
1132 my($mgr, $po_id) = @_;
1134 my $non_recv_li = $mgr->editor->search_acq_lineitem(
1135 { purchase_order => $po_id,
1136 state => {'!=' => 'received'}
1139 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id);
1140 return $po if @$non_recv_li;
1142 $po->state('received');
1143 return update_purchase_order($mgr, $po);
1147 # ----------------------------------------------------------------------------
1148 # Bib, Callnumber, and Copy data
1149 # ----------------------------------------------------------------------------
1151 sub create_lineitem_assets {
1152 my($mgr, $li_id) = @_;
1155 my $li = $mgr->editor->retrieve_acq_lineitem([
1158 flesh_fields => {jub => ['purchase_order', 'attributes']}
1162 # note: at this point, the bib record this LI links to should already be created
1164 # -----------------------------------------------------------------
1165 # The lineitem is going live, promote user request holds to real holds
1166 # -----------------------------------------------------------------
1167 promote_lineitem_holds($mgr, $li) or return 0;
1169 my $li_details = $mgr->editor->search_acq_lineitem_detail({lineitem => $li_id}, {idlist=>1});
1171 # -----------------------------------------------------------------
1172 # for each lineitem_detail, create the volume if necessary, create
1173 # a copy, and link them all together.
1174 # -----------------------------------------------------------------
1176 for my $lid_id (@{$li_details}) {
1178 my $lid = $mgr->editor->retrieve_acq_lineitem_detail($lid_id) or return 0;
1179 next if $lid->eg_copy_id;
1181 # use the same callnumber label for all items within this lineitem
1182 $lid->cn_label($first_cn) if $first_cn and not $lid->cn_label;
1184 # apply defaults if necessary
1185 return 0 unless complete_lineitem_detail($mgr, $lid);
1187 $first_cn = $lid->cn_label unless $first_cn;
1189 my $org = $lid->owning_lib;
1190 my $label = $lid->cn_label;
1191 my $bibid = $li->eg_bib_id;
1193 my $volume = $mgr->cache($org, "cn.$bibid.$label");
1195 $volume = create_volume($mgr, $li, $lid) or return 0;
1196 $mgr->cache($org, "cn.$bibid.$label", $volume);
1198 create_copy($mgr, $volume, $lid, $li) or return 0;
1201 return { li => $li };
1205 my($mgr, $li, $lid) = @_;
1207 my ($volume, $evt) =
1208 OpenILS::Application::Cat::AssetCommon->find_or_create_volume(
1216 $mgr->editor->event($evt);
1224 my($mgr, $volume, $lid, $li) = @_;
1225 my $copy = Fieldmapper::asset::copy->new;
1227 $copy->loan_duration(2);
1228 $copy->fine_level(2);
1229 $copy->status(($lid->recv_time) ? OILS_COPY_STATUS_IN_PROCESS : OILS_COPY_STATUS_ON_ORDER);
1230 $copy->barcode($lid->barcode);
1231 $copy->location($lid->location);
1232 $copy->call_number($volume->id);
1233 $copy->circ_lib($volume->owning_lib);
1234 $copy->circ_modifier($lid->circ_modifier);
1236 # AKA list price. We might need a $li->list_price field since
1237 # estimated price is not necessarily the same as list price
1238 $copy->price($li->estimated_unit_price);
1240 my $evt = OpenILS::Application::Cat::AssetCommon->create_copy($mgr->editor, $volume, $copy);
1242 $mgr->editor->event($evt);
1247 $lid->eg_copy_id($copy->id);
1248 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
1256 # ----------------------------------------------------------------------------
1257 # Workflow: Build a selection list from a Z39.50 search
1258 # ----------------------------------------------------------------------------
1260 __PACKAGE__->register_method(
1261 method => 'zsearch',
1262 api_name => 'open-ils.acq.picklist.search.z3950',
1265 desc => 'Performs a z3950 federated search and creates a picklist and associated lineitems',
1267 {desc => 'Authentication token', type => 'string'},
1268 {desc => 'Search definition', type => 'object'},
1269 {desc => 'Picklist name, optional', type => 'string'},
1275 my($self, $conn, $auth, $search, $name, $options) = @_;
1276 my $e = new_editor(authtoken=>$auth);
1277 return $e->event unless $e->checkauth;
1278 return $e->event unless $e->allowed('CREATE_PICKLIST');
1280 $search->{limit} ||= 10;
1283 my $ses = OpenSRF::AppSession->create('open-ils.search');
1284 my $req = $ses->request('open-ils.search.z3950.search_class', $auth, $search);
1289 while(my $resp = $req->recv(timeout=>60)) {
1292 my $e = new_editor(requestor=>$e->requestor, xact=>1);
1293 $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1294 $picklist = zsearch_build_pl($mgr, $name);
1298 my $result = $resp->content;
1299 my $count = $result->{count} || 0;
1300 $mgr->total( (($count < $search->{limit}) ? $count : $search->{limit})+1 );
1302 for my $rec (@{$result->{records}}) {
1304 my $li = create_lineitem($mgr,
1305 picklist => $picklist->id,
1306 source_label => $result->{service},
1307 marc => $rec->{marcxml},
1308 eg_bib_id => $rec->{bibid}
1311 if($$options{respond_li}) {
1312 $li->attributes($mgr->editor->search_acq_lineitem_attr({lineitem => $li->id}))
1313 if $$options{flesh_attrs};
1314 $li->clear_marc if $$options{clear_marc};
1315 $mgr->respond(lineitem => $li);
1322 $mgr->editor->commit;
1323 return $mgr->respond_complete;
1326 sub zsearch_build_pl {
1327 my($mgr, $name) = @_;
1330 my $picklist = $mgr->editor->search_acq_picklist({
1331 owner => $mgr->editor->requestor->id,
1335 if($name eq '' and $picklist) {
1336 return 0 unless delete_picklist($mgr, $picklist);
1340 return update_picklist($mgr, $picklist) if $picklist;
1341 return create_picklist($mgr, name => $name);
1345 # ----------------------------------------------------------------------------
1346 # Workflow: Build a selection list / PO by importing a batch of MARC records
1347 # ----------------------------------------------------------------------------
1349 __PACKAGE__->register_method(
1350 method => 'upload_records',
1351 api_name => 'open-ils.acq.process_upload_records',
1353 max_chunk_count => 1
1356 sub upload_records {
1357 my($self, $conn, $auth, $key, $args) = @_;
1360 my $e = new_editor(authtoken => $auth, xact => 1);
1361 return $e->die_event unless $e->checkauth;
1362 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1364 my $cache = OpenSRF::Utils::Cache->new;
1366 my $data = $cache->get_cache("vandelay_import_spool_$key");
1367 my $filename = $data->{path};
1368 my $provider = $args->{provider};
1369 my $picklist = $args->{picklist};
1370 my $create_po = $args->{create_po};
1371 my $activate_po = $args->{activate_po};
1372 my $vandelay = $args->{vandelay};
1373 my $ordering_agency = $args->{ordering_agency} || $e->requestor->ws_ou;
1374 my $fiscal_year = $args->{fiscal_year} || DateTime->now->year;
1378 unless(-r $filename) {
1379 $logger->error("unable to read MARC file $filename");
1381 return OpenILS::Event->new('FILE_UPLOAD_ERROR', payload => {filename => $filename});
1384 $provider = $e->retrieve_acq_provider($provider) or return $e->die_event;
1387 $picklist = $e->retrieve_acq_picklist($picklist) or return $e->die_event;
1388 if($picklist->owner != $e->requestor->id) {
1389 return $e->die_event unless
1390 $e->allowed('CREATE_PICKLIST', $picklist->org_unit, $picklist);
1392 $mgr->picklist($picklist);
1396 return $e->die_event unless
1397 $e->allowed('CREATE_PURCHASE_ORDER', $ordering_agency);
1399 $po = create_purchase_order($mgr,
1400 ordering_agency => $ordering_agency,
1401 provider => $provider->id,
1402 state => 'pending' # will be updated later if activated
1403 ) or return $mgr->editor->die_event;
1406 $logger->info("acq processing MARC file=$filename");
1408 my $batch = new MARC::Batch ('USMARC', $filename);
1416 my ($err, $xml, $r);
1421 } catch Error with {
1423 $logger->warn("Proccessing of record $count in set $key failed with error $err. Skipping this record");
1430 $xml = clean_marc($r);
1431 } catch Error with {
1433 $logger->warn("Proccessing XML of record $count in set $key failed with error $err. Skipping this record");
1436 next if $err or not $xml;
1439 source_label => $provider->code,
1440 provider => $provider->id,
1444 $args{picklist} = $picklist->id if $picklist;
1446 $args{purchase_order} = $po->id;
1447 $args{state} = 'pending-order';
1450 my $li = create_lineitem($mgr, %args) or return $mgr->editor->die_event;
1452 $li->provider($provider); # flesh it, we'll need it later
1454 import_lineitem_details($mgr, $ordering_agency, $li, $fiscal_year)
1455 or return $mgr->editor->die_event;
1458 push(@li_list, $li->id);
1463 $evt = extract_po_name($mgr, $po, \@li_list);
1464 return $evt if $evt;
1469 $cache->delete_cache('vandelay_import_spool_' . $key);
1471 if ($po and $activate_po) {
1472 my $die_event = activate_purchase_order_impl($mgr, $po->id, $vandelay);
1473 return $die_event if $die_event;
1475 } elsif ($vandelay) {
1476 $vandelay->{new_rec_perm} = 'IMPORT_ACQ_LINEITEM_BIB_RECORD_UPLOAD';
1477 create_lineitem_list_assets($mgr, \@li_list, $vandelay,
1478 !$vandelay->{create_assets}) or return $e->die_event;
1481 return $mgr->respond_complete;
1484 # see if the PO name is encoded in the newly imported records
1485 sub extract_po_name {
1486 my ($mgr, $po, $li_ids) = @_;
1487 my $e = $mgr->editor;
1489 # find the first instance of the name
1490 my $attr = $e->search_acq_lineitem_attr([
1491 { lineitem => $li_ids,
1492 attr_type => 'lineitem_provider_attr_definition',
1493 attr_name => 'purchase_order'
1495 order_by => {aqlia => 'id'},
1498 ])->[0] or return undef;
1500 my $name = $attr->attr_value;
1502 # see if another PO already has the name, provider, and org
1503 my $existing = $e->search_acq_purchase_order(
1505 ordering_agency => $po->ordering_agency,
1506 provider => $po->provider
1511 # if a PO exists with the same name (and provider/org)
1512 # tack the po ID into the name to differentiate
1513 $name = sprintf("$name (%s)", $po->id) if $existing;
1515 $logger->info("Extracted PO name: $name");
1518 update_purchase_order($mgr, $po) or return $e->die_event;
1522 sub import_lineitem_details {
1523 my($mgr, $ordering_agency, $li, $fiscal_year) = @_;
1525 my $holdings = $mgr->editor->json_query({from => ['acq.extract_provider_holding_data', $li->id]});
1526 return 1 unless @$holdings;
1527 my $org_path = $U->get_org_ancestors($ordering_agency);
1528 $org_path = [ reverse (@$org_path) ];
1534 # create a lineitem detail for each copy in the data
1536 my $compiled = extract_lineitem_detail_data($mgr, $org_path, $holdings, $idx, $fiscal_year);
1537 last unless defined $compiled;
1538 return 0 unless $compiled;
1540 # this takes the price of the last copy and uses it as the lineitem price
1541 # need to determine if a given record would include different prices for the same item
1542 $price = $$compiled{estimated_price};
1544 last unless $$compiled{quantity};
1546 for(1..$$compiled{quantity}) {
1547 my $lid = create_lineitem_detail(
1549 lineitem => $li->id,
1550 owning_lib => $$compiled{owning_lib},
1551 cn_label => $$compiled{call_number},
1552 fund => $$compiled{fund},
1553 circ_modifier => $$compiled{circ_modifier},
1554 note => $$compiled{note},
1555 location => $$compiled{copy_location},
1556 collection_code => $$compiled{collection_code},
1557 barcode => $$compiled{barcode}
1565 $li->estimated_unit_price($price);
1566 update_lineitem($mgr, $li) or return 0;
1570 # return hash on success, 0 on error, undef on no more holdings
1571 sub extract_lineitem_detail_data {
1572 my($mgr, $org_path, $holdings, $index, $fiscal_year) = @_;
1574 my @data_list = grep { $_->{holding} eq $index } @$holdings;
1575 return undef unless @data_list;
1577 my %compiled = map { $_->{attr} => $_->{data} } @data_list;
1578 my $base_org = $$org_path[0];
1582 $logger->error("Item import extraction error: $msg");
1583 $logger->error('Holdings Data: ' . OpenSRF::Utils::JSON->perl2JSON(\%compiled));
1584 $mgr->editor->rollback;
1585 $mgr->editor->event(OpenILS::Event->new('ACQ_IMPORT_ERROR', payload => $msg));
1589 # ---------------------------------------------------------------------
1591 if(my $code = $compiled{fund_code}) {
1593 my $fund = $mgr->cache($base_org, "fund.$code");
1595 # search up the org tree for the most appropriate fund
1596 for my $org (@$org_path) {
1597 $fund = $mgr->editor->search_acq_fund(
1598 {org => $org, code => $code, year => $fiscal_year}, {idlist => 1})->[0];
1602 return $killme->("no fund with code $code at orgs [@$org_path]") unless $fund;
1603 $compiled{fund} = $fund;
1604 $mgr->cache($base_org, "fund.$code", $fund);
1608 # ---------------------------------------------------------------------
1610 if(my $sn = $compiled{owning_lib}) {
1611 my $org_id = $mgr->cache($base_org, "orgsn.$sn") ||
1612 $mgr->editor->search_actor_org_unit({shortname => $sn}, {idlist => 1})->[0];
1613 return $killme->("invalid owning_lib defined: $sn") unless $org_id;
1614 $compiled{owning_lib} = $org_id;
1615 $mgr->cache($$org_path[0], "orgsn.$sn", $org_id);
1619 # ---------------------------------------------------------------------
1621 my $code = $compiled{circ_modifier};
1625 # verify this is a valid circ modifier
1626 return $killme->("invlalid circ_modifier $code") unless
1627 defined $mgr->cache($base_org, "mod.$code") or
1628 $mgr->editor->retrieve_config_circ_modifier($code);
1630 # if valid, cache for future tests
1631 $mgr->cache($base_org, "mod.$code", $code);
1634 $compiled{circ_modifier} = get_default_circ_modifier($mgr, $base_org);
1638 # ---------------------------------------------------------------------
1640 if( my $name = $compiled{copy_location}) {
1641 my $loc = $mgr->cache($base_org, "copy_loc.$name");
1643 for my $org (@$org_path) {
1644 $loc = $mgr->editor->search_asset_copy_location(
1645 {owning_lib => $org, name => $name}, {idlist => 1})->[0];
1649 return $killme->("Invalid copy location $name") unless $loc;
1650 $compiled{copy_location} = $loc;
1651 $mgr->cache($base_org, "copy_loc.$name", $loc);
1659 # ----------------------------------------------------------------------------
1660 # Workflow: Given an existing purchase order, import/create the bibs,
1661 # callnumber and copy objects
1662 # ----------------------------------------------------------------------------
1664 __PACKAGE__->register_method(
1665 method => 'create_po_assets',
1666 api_name => 'open-ils.acq.purchase_order.assets.create',
1668 desc => q/Creates assets for each lineitem in the purchase order/,
1670 {desc => 'Authentication token', type => 'string'},
1671 {desc => 'The purchase order id', type => 'number'},
1673 return => {desc => 'Streams a total versus completed counts object, event on error'}
1675 max_chunk_count => 1
1678 sub create_po_assets {
1679 my($self, $conn, $auth, $po_id, $args) = @_;
1682 my $e = new_editor(authtoken=>$auth, xact=>1);
1683 return $e->die_event unless $e->checkauth;
1684 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1686 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1688 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1690 # it's ugly, but it's fast. Get the total count of lineitem detail objects to process
1691 my $lid_total = $e->json_query({
1692 select => { acqlid => [{aggregate => 1, transform => 'count', column => 'id'}] },
1698 join => {acqpo => {fkey => 'purchase_order', field => 'id'}}
1702 where => {'+acqpo' => {id => $po_id}}
1705 $mgr->total(scalar(@$li_ids) + $lid_total);
1707 create_lineitem_list_assets($mgr, $li_ids, $args->{vandelay})
1708 or return $e->die_event;
1711 update_purchase_order($mgr, $po) or return $e->die_event;
1714 return $mgr->respond_complete;
1719 __PACKAGE__->register_method(
1720 method => 'create_purchase_order_api',
1721 api_name => 'open-ils.acq.purchase_order.create',
1723 desc => 'Creates a new purchase order',
1725 {desc => 'Authentication token', type => 'string'},
1726 {desc => 'purchase_order to create', type => 'object'}
1728 return => {desc => 'The purchase order id, Event on failure'}
1730 max_chunk_count => 1
1733 sub create_purchase_order_api {
1734 my($self, $conn, $auth, $po, $args) = @_;
1737 my $e = new_editor(xact=>1, authtoken=>$auth);
1738 return $e->die_event unless $e->checkauth;
1739 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
1740 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1743 my %pargs = (ordering_agency => $e->requestor->ws_ou); # default
1744 $pargs{provider} = $po->provider if $po->provider;
1745 $pargs{ordering_agency} = $po->ordering_agency if $po->ordering_agency;
1746 $pargs{prepayment_required} = $po->prepayment_required if $po->prepayment_required;
1747 my $vandelay = $args->{vandelay};
1749 $po = create_purchase_order($mgr, %pargs) or return $e->die_event;
1751 my $li_ids = $$args{lineitems};
1755 for my $li_id (@$li_ids) {
1757 my $li = $e->retrieve_acq_lineitem([
1759 {flesh => 1, flesh_fields => {jub => ['attributes']}}
1760 ]) or return $e->die_event;
1762 $li->provider($po->provider);
1763 $li->purchase_order($po->id);
1764 $li->state('pending-order');
1765 update_lineitem($mgr, $li) or return $e->die_event;
1770 # commit before starting the asset creation
1773 if($li_ids and $vandelay) {
1774 create_lineitem_list_assets($mgr, $li_ids, $vandelay, !$$args{create_assets}) or return $e->die_event;
1777 return $mgr->respond_complete;
1782 __PACKAGE__->register_method(
1783 method => 'update_lineitem_fund_batch',
1784 api_name => 'open-ils.acq.lineitem.fund.update.batch',
1787 desc => q/Given a set of lineitem IDS, updates the fund for all attached lineitem details/
1791 sub update_lineitem_fund_batch {
1792 my($self, $conn, $auth, $li_ids, $fund_id) = @_;
1793 my $e = new_editor(xact=>1, authtoken=>$auth);
1794 return $e->die_event unless $e->checkauth;
1795 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1796 for my $li_id (@$li_ids) {
1797 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
1798 return $evt if $evt;
1799 my $li_details = $e->search_acq_lineitem_detail({lineitem => $li_id});
1800 $_->fund($fund_id) and $_->ischanged(1) for @$li_details;
1801 $evt = lineitem_detail_CUD_batch($mgr, $li_details);
1802 return $evt if $evt;
1807 return $mgr->respond_complete;
1812 __PACKAGE__->register_method(
1813 method => 'lineitem_detail_CUD_batch_api',
1814 api_name => 'open-ils.acq.lineitem_detail.cud.batch',
1817 desc => q/Creates a new purchase order line item detail. / .
1818 q/Additionally creates the associated fund_debit/,
1820 {desc => 'Authentication token', type => 'string'},
1821 {desc => 'List of lineitem_details to create', type => 'array'},
1822 {desc => 'Create Debits. Used for creating post-po-asset-creation debits', type => 'bool'},
1824 return => {desc => 'Streaming response of current position in the array'}
1828 __PACKAGE__->register_method(
1829 method => 'lineitem_detail_CUD_batch_api',
1830 api_name => 'open-ils.acq.lineitem_detail.cud.batch.dry_run',
1834 Dry run version of open-ils.acq.lineitem_detail.cud.batch.
1835 In dry_run mode, updated fund_debit's the exceed the warning
1836 percent return an event.
1842 sub lineitem_detail_CUD_batch_api {
1843 my($self, $conn, $auth, $li_details, $create_debits) = @_;
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);
1847 my $dry_run = ($self->api_name =~ /dry_run/o);
1848 my $evt = lineitem_detail_CUD_batch($mgr, $li_details, $create_debits, $dry_run);
1849 return $evt if $evt;
1851 return $mgr->respond_complete;
1855 sub lineitem_detail_CUD_batch {
1856 my($mgr, $li_details, $create_debits, $dry_run) = @_;
1858 $mgr->total(scalar(@$li_details));
1859 my $e = $mgr->editor;
1863 my $fund_cache = {};
1866 for my $lid (@$li_details) {
1868 unless($li = $li_cache{$lid->lineitem}) {
1869 ($li, $evt) = fetch_and_check_li($e, $lid->lineitem, 'write');
1870 return $evt if $evt;
1874 $lid = create_lineitem_detail($mgr, %{$lid->to_bare_hash}) or return $e->die_event;
1875 if($create_debits) {
1876 $li->provider($e->retrieve_acq_provider($li->provider)) or return $e->die_event;
1877 $lid->fund($e->retrieve_acq_fund($lid->fund)) or return $e->die_event;
1878 create_lineitem_detail_debit($mgr, $li, $lid, 0, 1) or return $e->die_event;
1881 } elsif($lid->ischanged) {
1882 return $evt if $evt = handle_changed_lid($e, $lid, $dry_run, $fund_cache);
1884 } elsif($lid->isdeleted) {
1885 delete_lineitem_detail($mgr, $lid) or return $e->die_event;
1888 $mgr->respond(li => $li);
1889 $li_cache{$lid->lineitem} = $li;
1895 sub handle_changed_lid {
1896 my($e, $lid, $dry_run, $fund_cache) = @_;
1898 my $orig_lid = $e->retrieve_acq_lineitem_detail($lid->id) or return $e->die_event;
1900 # updating the fund, so update the debit
1901 if($orig_lid->fund_debit and $orig_lid->fund != $lid->fund) {
1903 my $debit = $e->retrieve_acq_fund_debit($orig_lid->fund_debit);
1904 my $new_fund = $$fund_cache{$lid->fund} =
1905 $$fund_cache{$lid->fund} || $e->retrieve_acq_fund($lid->fund);
1907 # check the thresholds
1908 return $e->die_event if
1909 fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "stop");
1910 return $e->die_event if $dry_run and
1911 fund_exceeds_balance_percent($new_fund, $debit->amount, $e, "warning");
1913 $debit->fund($new_fund->id);
1914 $e->update_acq_fund_debit($debit) or return $e->die_event;
1917 $e->update_acq_lineitem_detail($lid) or return $e->die_event;
1922 __PACKAGE__->register_method(
1923 method => 'receive_po_api',
1924 api_name => 'open-ils.acq.purchase_order.receive'
1927 sub receive_po_api {
1928 my($self, $conn, $auth, $po_id) = @_;
1929 my $e = new_editor(xact => 1, authtoken => $auth);
1930 return $e->die_event unless $e->checkauth;
1931 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1933 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
1934 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
1936 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
1938 for my $li_id (@$li_ids) {
1939 receive_lineitem($mgr, $li_id) or return $e->die_event;
1943 $po->state('received');
1944 update_purchase_order($mgr, $po) or return $e->die_event;
1947 return $mgr->respond_complete;
1951 # At the moment there's a lack of parallelism between the receive and unreceive
1952 # API methods for POs and the API methods for LIs and LIDs. The methods for
1953 # POs stream back objects as they act, whereas the methods for LIs and LIDs
1954 # atomically return an object that describes only what changed (in LIs and LIDs
1955 # themselves or in the objects to which to LIs and LIDs belong).
1957 # The methods for LIs and LIDs work the way they do to faciliate the UI's
1958 # maintaining correct information about the state of these things when a user
1959 # wants to receive or unreceive these objects without refreshing their whole
1960 # display. The UI feature for receiving and un-receiving a whole PO just
1961 # refreshes the whole display, so this absence of parallelism in the UI is also
1962 # relected in this module.
1964 # This could be neatened in the future by making POs receive and unreceive in
1965 # the same way the LIs and LIDs do.
1967 __PACKAGE__->register_method(
1968 method => 'receive_lineitem_detail_api',
1969 api_name => 'open-ils.acq.lineitem_detail.receive',
1971 desc => 'Mark a lineitem_detail as received',
1973 {desc => 'Authentication token', type => 'string'},
1974 {desc => 'lineitem detail ID', type => 'number'}
1977 "on success, object describing changes to LID and possibly " .
1978 "to LI and PO; on error, Event"
1983 sub receive_lineitem_detail_api {
1984 my($self, $conn, $auth, $lid_id) = @_;
1986 my $e = new_editor(xact=>1, authtoken=>$auth);
1987 return $e->die_event unless $e->checkauth;
1988 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
1991 "flesh" => 2, "flesh_fields" => {
1992 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
1996 my $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
1998 return $e->die_event unless $e->allowed(
1999 'RECEIVE_PURCHASE_ORDER', $lid->lineitem->purchase_order->ordering_agency);
2002 my $recvd = receive_lineitem_detail($mgr, $lid_id) or return $e->die_event;
2004 # .. and re-retrieve
2005 $lid = $e->retrieve_acq_lineitem_detail([$lid_id, $fleshing]);
2007 # Now build result data structure.
2008 my $result = {"lid" => {$lid->id => {"recv_time" => $lid->recv_time}}};
2011 if ($recvd->class_name =~ /::purchase_order/) {
2012 $result->{"po"} = describe_affected_po($e, $recvd);
2014 $lid->lineitem->id => {"state" => $lid->lineitem->state}
2016 } elsif ($recvd->class_name =~ /::lineitem/) {
2017 $result->{"li"} = {$recvd->id => {"state" => $recvd->state}};
2021 describe_affected_po($e, $lid->lineitem->purchase_order);
2027 __PACKAGE__->register_method(
2028 method => 'receive_lineitem_api',
2029 api_name => 'open-ils.acq.lineitem.receive',
2031 desc => 'Mark a lineitem as received',
2033 {desc => 'Authentication token', type => 'string'},
2034 {desc => 'lineitem ID', type => 'number'}
2037 "on success, object describing changes to LI and possibly PO; " .
2043 sub receive_lineitem_api {
2044 my($self, $conn, $auth, $li_id) = @_;
2046 my $e = new_editor(xact=>1, authtoken=>$auth);
2047 return $e->die_event unless $e->checkauth;
2048 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2050 my $li = $e->retrieve_acq_lineitem([
2054 jub => ['purchase_order']
2057 ]) or return $e->die_event;
2059 return $e->die_event unless $e->allowed(
2060 'RECEIVE_PURCHASE_ORDER', $li->purchase_order->ordering_agency);
2062 my $res = receive_lineitem($mgr, $li_id) or return $e->die_event;
2064 $conn->respond_complete($res);
2065 $mgr->run_post_response_hooks
2069 __PACKAGE__->register_method(
2070 method => 'rollback_receive_po_api',
2071 api_name => 'open-ils.acq.purchase_order.receive.rollback'
2074 sub rollback_receive_po_api {
2075 my($self, $conn, $auth, $po_id) = @_;
2076 my $e = new_editor(xact => 1, authtoken => $auth);
2077 return $e->die_event unless $e->checkauth;
2078 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2080 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2081 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2083 my $li_ids = $e->search_acq_lineitem({purchase_order => $po_id}, {idlist => 1});
2085 for my $li_id (@$li_ids) {
2086 rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
2090 $po->state('on-order');
2091 update_purchase_order($mgr, $po) or return $e->die_event;
2094 return $mgr->respond_complete;
2098 __PACKAGE__->register_method(
2099 method => 'rollback_receive_lineitem_detail_api',
2100 api_name => 'open-ils.acq.lineitem_detail.receive.rollback',
2102 desc => 'Mark a lineitem_detail as Un-received',
2104 {desc => 'Authentication token', type => 'string'},
2105 {desc => 'lineitem detail ID', type => 'number'}
2108 "on success, object describing changes to LID and possibly " .
2109 "to LI and PO; on error, Event"
2114 sub rollback_receive_lineitem_detail_api {
2115 my($self, $conn, $auth, $lid_id) = @_;
2117 my $e = new_editor(xact=>1, authtoken=>$auth);
2118 return $e->die_event unless $e->checkauth;
2119 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2121 my $lid = $e->retrieve_acq_lineitem_detail([
2125 acqlid => ['lineitem'],
2126 jub => ['purchase_order']
2130 my $li = $lid->lineitem;
2131 my $po = $li->purchase_order;
2133 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2137 my $recvd = rollback_receive_lineitem_detail($mgr, $lid_id)
2138 or return $e->die_event;
2141 $result->{"lid"} = {$recvd->id => {"recv_time" => $recvd->recv_time}};
2143 $result->{"lid"} = {$lid->id => {"recv_time" => $lid->recv_time}};
2146 if ($li->state eq "received") {
2147 $li->state("on-order");
2148 $li = update_lineitem($mgr, $li) or return $e->die_event;
2149 $result->{"li"} = {$li->id => {"state" => $li->state}};
2152 if ($po->state eq "received") {
2153 $po->state("on-order");
2154 $po = update_purchase_order($mgr, $po) or return $e->die_event;
2156 $result->{"po"} = describe_affected_po($e, $po);
2158 $e->commit and return $result or return $e->die_event;
2161 __PACKAGE__->register_method(
2162 method => 'rollback_receive_lineitem_api',
2163 api_name => 'open-ils.acq.lineitem.receive.rollback',
2165 desc => 'Mark a lineitem as Un-received',
2167 {desc => 'Authentication token', type => 'string'},
2168 {desc => 'lineitem ID', type => 'number'}
2171 "on success, object describing changes to LI and possibly PO; " .
2177 sub rollback_receive_lineitem_api {
2178 my($self, $conn, $auth, $li_id) = @_;
2180 my $e = new_editor(xact=>1, authtoken=>$auth);
2181 return $e->die_event unless $e->checkauth;
2182 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2184 my $li = $e->retrieve_acq_lineitem([
2186 "flesh" => 1, "flesh_fields" => {"jub" => ["purchase_order"]}
2189 my $po = $li->purchase_order;
2191 return $e->die_event unless $e->allowed('RECEIVE_PURCHASE_ORDER', $po->ordering_agency);
2193 $li = rollback_receive_lineitem($mgr, $li_id) or return $e->die_event;
2195 my $result = {"li" => {$li->id => {"state" => $li->state}}};
2196 if ($po->state eq "received") {
2197 $po->state("on-order");
2198 $po = update_purchase_order($mgr, $po) or return $e->die_event;
2200 $result->{"po"} = describe_affected_po($e, $po);
2202 $e->commit and return $result or return $e->die_event;
2206 __PACKAGE__->register_method(
2207 method => 'set_lineitem_price_api',
2208 api_name => 'open-ils.acq.lineitem.price.set',
2210 desc => 'Set lineitem price. If debits already exist, update them as well',
2212 {desc => 'Authentication token', type => 'string'},
2213 {desc => 'lineitem ID', type => 'number'}
2215 return => {desc => 'status blob, Event on error'}
2219 sub set_lineitem_price_api {
2220 my($self, $conn, $auth, $li_id, $price) = @_;
2222 my $e = new_editor(xact=>1, authtoken=>$auth);
2223 return $e->die_event unless $e->checkauth;
2224 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2226 my ($li, $evt) = fetch_and_check_li($e, $li_id, 'write');
2227 return $evt if $evt;
2229 $li->estimated_unit_price($price);
2230 update_lineitem($mgr, $li) or return $e->die_event;
2232 my $lid_ids = $e->search_acq_lineitem_detail(
2233 {lineitem => $li_id, fund_debit => {'!=' => undef}},
2237 for my $lid_id (@$lid_ids) {
2239 my $lid = $e->retrieve_acq_lineitem_detail([
2241 flesh => 1, flesh_fields => {acqlid => ['fund', 'fund_debit']}}
2244 $lid->fund_debit->amount($price);
2245 $e->update_acq_fund_debit($lid->fund_debit) or return $e->die_event;
2251 return $mgr->respond_complete;
2255 __PACKAGE__->register_method(
2256 method => 'clone_picklist_api',
2257 api_name => 'open-ils.acq.picklist.clone',
2259 desc => 'Clones a picklist, including lineitem and lineitem details',
2261 {desc => 'Authentication token', type => 'string'},
2262 {desc => 'Picklist ID', type => 'number'},
2263 {desc => 'New Picklist Name', type => 'string'}
2265 return => {desc => 'status blob, Event on error'}
2269 sub clone_picklist_api {
2270 my($self, $conn, $auth, $pl_id, $name) = @_;
2272 my $e = new_editor(xact=>1, authtoken=>$auth);
2273 return $e->die_event unless $e->checkauth;
2274 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2276 my $old_pl = $e->retrieve_acq_picklist($pl_id);
2277 my $new_pl = create_picklist($mgr, %{$old_pl->to_bare_hash}, name => $name) or return $e->die_event;
2279 my $li_ids = $e->search_acq_lineitem({picklist => $pl_id}, {idlist => 1});
2281 # get the current user
2282 my $cloner = $mgr->editor->requestor->id;
2284 for my $li_id (@$li_ids) {
2286 # copy the lineitems' MARC
2287 my $marc = ($e->retrieve_acq_lineitem($li_id))->marc;
2289 # create a skeletal clone of the item
2290 my $li = Fieldmapper::acq::lineitem->new;
2291 $li->creator($cloner);
2292 $li->selector($cloner);
2293 $li->editor($cloner);
2296 my $new_li = create_lineitem($mgr, %{$li->to_bare_hash}, picklist => $new_pl->id) or return $e->die_event;
2302 return $mgr->respond_complete;
2306 __PACKAGE__->register_method(
2307 method => 'merge_picklist_api',
2308 api_name => 'open-ils.acq.picklist.merge',
2310 desc => 'Merges 2 or more picklists into a single list',
2312 {desc => 'Authentication token', type => 'string'},
2313 {desc => 'Lead Picklist ID', type => 'number'},
2314 {desc => 'List of subordinate picklist IDs', type => 'array'}
2316 return => {desc => 'status blob, Event on error'}
2320 sub merge_picklist_api {
2321 my($self, $conn, $auth, $lead_pl, $pl_list) = @_;
2323 my $e = new_editor(xact=>1, authtoken=>$auth);
2324 return $e->die_event unless $e->checkauth;
2325 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2327 # XXX perms on each picklist modified
2329 $lead_pl = $e->retrieve_acq_picklist($lead_pl) or return $e->die_event;
2330 # point all of the lineitems at the lead picklist
2331 my $li_ids = $e->search_acq_lineitem({picklist => $pl_list}, {idlist => 1});
2333 for my $li_id (@$li_ids) {
2334 my $li = $e->retrieve_acq_lineitem($li_id);
2335 $li->picklist($lead_pl);
2336 update_lineitem($mgr, $li) or return $e->die_event;
2340 # now delete the subordinate lists
2341 for my $pl_id (@$pl_list) {
2342 my $pl = $e->retrieve_acq_picklist($pl_id);
2343 $e->delete_acq_picklist($pl) or return $e->die_event;
2346 update_picklist($mgr, $lead_pl) or return $e->die_event;
2349 return $mgr->respond_complete;
2353 __PACKAGE__->register_method(
2354 method => 'delete_picklist_api',
2355 api_name => 'open-ils.acq.picklist.delete',
2357 desc => q/Deletes a picklist. It also deletes any lineitems in the "new" state. / .
2358 q/Other attached lineitems are detached/,
2360 {desc => 'Authentication token', type => 'string'},
2361 {desc => 'Picklist ID to delete', type => 'number'}
2363 return => {desc => '1 on success, Event on error'}
2367 sub delete_picklist_api {
2368 my($self, $conn, $auth, $picklist_id) = @_;
2369 my $e = new_editor(xact=>1, authtoken=>$auth);
2370 return $e->die_event unless $e->checkauth;
2371 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2372 my $pl = $e->retrieve_acq_picklist($picklist_id) or return $e->die_event;
2373 delete_picklist($mgr, $pl) or return $e->die_event;
2375 return $mgr->respond_complete;
2380 __PACKAGE__->register_method(
2381 method => 'activate_purchase_order',
2382 api_name => 'open-ils.acq.purchase_order.activate.dry_run'
2385 __PACKAGE__->register_method(
2386 method => 'activate_purchase_order',
2387 api_name => 'open-ils.acq.purchase_order.activate',
2389 desc => q/Activates a purchase order. This updates the status of the PO / .
2390 q/and Lineitems to 'on-order'. Activated PO's are ready for EDI delivery if appropriate./,
2392 {desc => 'Authentication token', type => 'string'},
2393 {desc => 'Purchase ID', type => 'number'}
2395 return => {desc => '1 on success, Event on error'}
2399 sub activate_purchase_order {
2400 my($self, $conn, $auth, $po_id, $vandelay, $options) = @_;
2403 my $dry_run = ($self->api_name =~ /\.dry_run/) ? 1 : 0;
2404 my $e = new_editor(authtoken=>$auth);
2405 return $e->die_event unless $e->checkauth;
2406 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
2407 my $die_event = activate_purchase_order_impl($mgr, $po_id, $vandelay, $dry_run, $options);
2408 return $e->die_event if $die_event;
2409 $conn->respond_complete(1);
2410 $mgr->run_post_response_hooks unless $dry_run;
2414 # xacts managed within
2415 sub activate_purchase_order_impl {
2416 my ($mgr, $po_id, $vandelay, $dry_run, $options) = @_;
2418 # read-only until lineitem asset creation
2419 my $e = $mgr->editor;
2422 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->die_event;
2423 return $e->die_event unless $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
2425 return $e->die_event(OpenILS::Event->new('PO_ALREADY_ACTIVATED'))
2426 if $po->order_date; # PO cannot be re-activated
2428 my $provider = $e->retrieve_acq_provider($po->provider);
2430 # find lineitems and create assets for all
2433 purchase_order => $po_id,
2434 state => [qw/pending-order new order-ready/]
2437 my $li_ids = $e->search_acq_lineitem($query, {idlist => 1});
2439 my $vl_resp; # imported li's and the queue the managing queue
2441 $e->rollback; # read-only thus far
2442 $vl_resp = create_lineitem_list_assets($mgr, $li_ids, $vandelay)
2443 or return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED');
2447 # create fund debits for lineitems
2449 for my $li_id (@$li_ids) {
2450 my $li = $e->retrieve_acq_lineitem($li_id);
2452 if (!$li->eg_bib_id and !$dry_run) {
2453 # we encountered a lineitem that was not successfully imported.
2454 # we cannot continue. rollback and report.
2456 return OpenILS::Event->new('ACQ_LI_IMPORT_FAILED', {queue => $vl_resp->{queue}});
2459 $li->state('on-order');
2460 $li->claim_policy($provider->default_claim_policy)
2461 if $provider->default_claim_policy and !$li->claim_policy;
2462 create_lineitem_debits($mgr, $li, $dry_run, $options) or return $e->die_event;
2463 update_lineitem($mgr, $li) or return $e->die_event;
2464 $mgr->post_process( sub { create_lineitem_status_events($mgr, $li->id, 'aur.ordered'); });
2468 # create po-item debits
2470 for my $po_item (@{$e->search_acq_po_item({purchase_order => $po_id})}) {
2472 my $debit = create_fund_debit(
2475 debit_type => 'direct_charge', # to match invoicing
2476 origin_amount => $po_item->estimated_cost,
2477 origin_currency_type => $e->retrieve_acq_fund($po_item->fund)->currency_type,
2478 amount => $po_item->estimated_cost,
2479 fund => $po_item->fund
2480 ) or return $e->die_event;
2481 $po_item->fund_debit($debit->id);
2482 $e->update_acq_po_item($po_item) or return $e->die_event;
2486 # mark PO as ordered
2488 $po->state('on-order');
2489 $po->order_date('now');
2490 update_purchase_order($mgr, $po) or return $e->die_event;
2493 $dry_run and $e->rollback or $e->commit;
2495 # tell the world we activated a PO
2496 $U->create_events_for_hook('acqpo.activated', $po, $po->ordering_agency) unless $dry_run;
2502 __PACKAGE__->register_method(
2503 method => 'split_purchase_order_by_lineitems',
2504 api_name => 'open-ils.acq.purchase_order.split_by_lineitems',
2506 desc => q/Splits a PO into many POs, 1 per lineitem. Only works for / .
2507 q/POs a) with more than one lineitems, and b) in the "pending" state./,
2509 {desc => 'Authentication token', type => 'string'},
2510 {desc => 'Purchase order ID', type => 'number'}
2512 return => {desc => 'list of new PO IDs on success, Event on error'}
2516 sub split_purchase_order_by_lineitems {
2517 my ($self, $conn, $auth, $po_id) = @_;
2519 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2520 return $e->die_event unless $e->checkauth;
2522 my $po = $e->retrieve_acq_purchase_order([
2525 "flesh_fields" => {"acqpo" => [qw/lineitems notes/]}
2527 ]) or return $e->die_event;
2529 return $e->die_event
2530 unless $e->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2532 unless ($po->state eq "pending") {
2534 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_LATE");
2537 unless (@{$po->lineitems} > 1) {
2539 return new OpenILS::Event("ACQ_PURCHASE_ORDER_TOO_SHORT");
2542 # To split an existing PO into many, it seems unwise to just delete the
2543 # original PO, so we'll instead detach all of the original POs' lineitems
2544 # but the first, then create new POs for each of the remaining LIs, and
2545 # then attach the LIs to their new POs.
2547 my @po_ids = ($po->id);
2548 my @moving_li = @{$po->lineitems};
2549 shift @moving_li; # discard first LI
2551 foreach my $li (@moving_li) {
2552 my $new_po = $po->clone;
2554 $new_po->clear_name;
2555 $new_po->creator($e->requestor->id);
2556 $new_po->editor($e->requestor->id);
2557 $new_po->owner($e->requestor->id);
2558 $new_po->edit_time("now");
2559 $new_po->create_time("now");
2561 $new_po = $e->create_acq_purchase_order($new_po);
2563 # Clone any notes attached to the old PO and attach to the new one.
2564 foreach my $note (@{$po->notes}) {
2565 my $new_note = $note->clone;
2566 $new_note->clear_id;
2567 $new_note->edit_time("now");
2568 $new_note->purchase_order($new_po->id);
2569 $e->create_acq_po_note($new_note);
2572 $li->edit_time("now");
2573 $li->purchase_order($new_po->id);
2574 $e->update_acq_lineitem($li);
2576 push @po_ids, $new_po->id;
2579 $po->edit_time("now");
2580 $e->update_acq_purchase_order($po);
2582 return \@po_ids if $e->commit;
2583 return $e->die_event;
2587 sub not_cancelable {
2589 (ref $o eq "HASH" and $o->{"textcode"} eq "ACQ_NOT_CANCELABLE");
2592 __PACKAGE__->register_method(
2593 method => "cancel_purchase_order_api",
2594 api_name => "open-ils.acq.purchase_order.cancel",
2596 desc => q/Cancels an on-order purchase order/,
2598 {desc => "Authentication token", type => "string"},
2599 {desc => "PO ID to cancel", type => "number"},
2600 {desc => "Cancel reason ID", type => "number"}
2602 return => {desc => q/Object describing changed POs, LIs and LIDs
2603 on success; Event on error./}
2607 sub cancel_purchase_order_api {
2608 my ($self, $conn, $auth, $po_id, $cancel_reason) = @_;
2610 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2611 return $e->die_event unless $e->checkauth;
2612 my $mgr = new OpenILS::Application::Acq::BatchManager(
2613 "editor" => $e, "conn" => $conn
2616 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2617 return new OpenILS::Event(
2618 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2621 my $result = cancel_purchase_order($mgr, $po_id, $cancel_reason) or
2622 return $e->die_event;
2623 if (not_cancelable($result)) { # event not from CStoreEditor
2626 } elsif ($result == -1) {
2628 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2631 $e->commit or return $e->die_event;
2633 # XXX create purchase order status events?
2635 if ($mgr->{post_commit}) {
2636 foreach my $func (@{$mgr->{post_commit}}) {
2644 sub cancel_purchase_order {
2645 my ($mgr, $po_id, $cancel_reason) = @_;
2647 my $po = $mgr->editor->retrieve_acq_purchase_order($po_id) or return 0;
2649 # XXX is "cancelled" a typo? It's not correct US spelling, anyway.
2650 # Depending on context, this may not warrant an event.
2651 return -1 if $po->state eq "cancelled";
2653 # But this always does.
2654 return new OpenILS::Event(
2655 "ACQ_NOT_CANCELABLE", "note" => "purchase_order $po_id"
2656 ) unless ($po->state eq "on-order" or $po->state eq "pending");
2659 $mgr->editor->allowed("CREATE_PURCHASE_ORDER", $po->ordering_agency);
2661 $po->state("cancelled");
2662 $po->cancel_reason($cancel_reason->id);
2664 my $li_ids = $mgr->editor->search_acq_lineitem(
2665 {"purchase_order" => $po_id}, {"idlist" => 1}
2668 my $result = {"li" => {}, "lid" => {}};
2669 foreach my $li_id (@$li_ids) {
2670 my $li_result = cancel_lineitem($mgr, $li_id, $cancel_reason)
2673 next if $li_result == -1; # already canceled:skip.
2674 return $li_result if not_cancelable($li_result); # not cancelable:stop.
2676 # Merge in each LI result (there's only going to be
2677 # one per call to cancel_lineitem).
2678 my ($k, $v) = each %{$li_result->{"li"}};
2679 $result->{"li"}->{$k} = $v;
2681 # Merge in each LID result (there may be many per call to
2683 while (($k, $v) = each %{$li_result->{"lid"}}) {
2684 $result->{"lid"}->{$k} = $v;
2688 # TODO who/what/where/how do we indicate this change for electronic orders?
2689 # TODO return changes to encumbered/spent
2690 # TODO maybe cascade up from smaller object to container object if last
2691 # smaller object in the container has been canceled?
2693 update_purchase_order($mgr, $po) or return 0;
2695 $po_id => {"state" => $po->state, "cancel_reason" => $cancel_reason}
2701 __PACKAGE__->register_method(
2702 method => "cancel_lineitem_api",
2703 api_name => "open-ils.acq.lineitem.cancel",
2705 desc => q/Cancels an on-order lineitem/,
2707 {desc => "Authentication token", type => "string"},
2708 {desc => "Lineitem ID to cancel", type => "number"},
2709 {desc => "Cancel reason ID", type => "number"}
2711 return => {desc => q/Object describing changed LIs and LIDs on success;
2716 __PACKAGE__->register_method(
2717 method => "cancel_lineitem_api",
2718 api_name => "open-ils.acq.lineitem.cancel.batch",
2720 desc => q/Batched version of open-ils.acq.lineitem.cancel/,
2721 return => {desc => q/Object describing changed LIs and LIDs on success;
2726 sub cancel_lineitem_api {
2727 my ($self, $conn, $auth, $li_id, $cancel_reason) = @_;
2729 my $batched = $self->api_name =~ /\.batch/;
2731 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2732 return $e->die_event unless $e->checkauth;
2733 my $mgr = new OpenILS::Application::Acq::BatchManager(
2734 "editor" => $e, "conn" => $conn
2737 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2738 return new OpenILS::Event(
2739 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2742 my ($result, $maybe_event);
2745 $result = {"li" => {}, "lid" => {}};
2746 foreach my $one_li_id (@$li_id) {
2747 my $one = cancel_lineitem($mgr, $one_li_id, $cancel_reason) or
2748 return $e->die_event;
2749 if (not_cancelable($one)) {
2750 $maybe_event = $one;
2751 } elsif ($result == -1) {
2752 $maybe_event = new OpenILS::Event("ACQ_ALREADY_CANCELED");
2756 while (($k, $v) = each %{$one->{"li"}}) {
2757 $result->{"li"}->{$k} = $v;
2760 if ($one->{"lid"}) {
2761 while (($k, $v) = each %{$one->{"lid"}}) {
2762 $result->{"lid"}->{$k} = $v;
2768 $result = cancel_lineitem($mgr, $li_id, $cancel_reason) or
2769 return $e->die_event;
2771 if (not_cancelable($result)) {
2774 } elsif ($result == -1) {
2776 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2780 if ($batched and not scalar keys %{$result->{"li"}}) {
2782 return $maybe_event;
2784 $e->commit or return $e->die_event;
2785 # create_lineitem_status_events should handle array li_id ok
2786 create_lineitem_status_events($mgr, $li_id, "aur.cancelled");
2788 if ($mgr->{post_commit}) {
2789 foreach my $func (@{$mgr->{post_commit}}) {
2798 sub cancel_lineitem {
2799 my ($mgr, $li_id, $cancel_reason) = @_;
2800 my $li = $mgr->editor->retrieve_acq_lineitem([
2801 $li_id, {flesh => 1, flesh_fields => {jub => ['purchase_order']}}
2804 return 0 unless $mgr->editor->allowed(
2805 "CREATE_PURCHASE_ORDER", $li->purchase_order->ordering_agency
2808 # Depending on context, this may not warrant an event.
2809 return -1 if $li->state eq "cancelled";
2811 # But this always does.
2812 return new OpenILS::Event(
2813 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id"
2815 (! $li->purchase_order) or (
2816 $li->purchase_order and (
2817 $li->state eq "on-order" or $li->state eq "pending-order"
2822 $li->state("cancelled");
2823 $li->cancel_reason($cancel_reason->id);
2825 my $lids = $mgr->editor->search_acq_lineitem_detail([{
2826 "lineitem" => $li_id
2829 flesh_fields => { acqlid => ['eg_copy_id'] }
2832 my $result = {"lid" => {}};
2834 foreach my $lid (@$lids) {
2835 my $lid_result = cancel_lineitem_detail($mgr, $lid->id, $cancel_reason)
2838 # gathering any real copies for deletion
2839 if ($lid->eg_copy_id) {
2840 $lid->eg_copy_id->isdeleted('t');
2841 push @$copies, $lid->eg_copy_id;
2844 next if $lid_result == -1; # already canceled: just skip it.
2845 return $lid_result if not_cancelable($lid_result); # not cxlable: stop.
2847 # Merge in each LID result (there's only going to be one per call to
2848 # cancel_lineitem_detail).
2849 my ($k, $v) = each %{$lid_result->{"lid"}};
2850 $result->{"lid"}->{$k} = $v;
2853 # Attempt to delete the gathered copies (this will also handle volume deletion and bib deletion)
2854 # Delete empty bibs according org unit setting
2855 my $force_delete_empty_bib = $U->ou_ancestor_setting_value(
2856 $mgr->editor->requestor->ws_ou, 'cat.bib.delete_on_no_copy_via_acq_lineitem_cancel', $mgr->editor);
2857 if (scalar(@$copies)>0) {
2859 my $delete_stats = undef;
2860 my $retarget_holds = [];
2861 my $cat_evt = OpenILS::Application::Cat::AssetCommon->update_fleshed_copies(
2862 $mgr->editor, $override, undef, $copies, $delete_stats, $retarget_holds,$force_delete_empty_bib);
2865 $logger->info("fleshed copy update failed with event: ".OpenSRF::Utils::JSON->perl2JSON($cat_evt));
2866 return new OpenILS::Event(
2867 "ACQ_NOT_CANCELABLE", "note" => "lineitem $li_id", "payload" => $cat_evt
2871 # We can't do the following and stay within the same transaction, but that's okay, the hold targeter will pick these up later.
2872 #my $ses = OpenSRF::AppSession->create('open-ils.circ');
2873 #$ses->request('open-ils.circ.hold.reset.batch', $auth, $retarget_holds);
2876 # if we have a bib, check to see whether it has been deleted. if so, cancel any active holds targeting that bib
2877 if ($li->eg_bib_id) {
2878 my $bib = $mgr->editor->retrieve_biblio_record_entry($li->eg_bib_id) or return new OpenILS::Event(
2879 "ACQ_NOT_CANCELABLE", "note" => "Could not retrieve bib " . $li->eg_bib_id . " for lineitem $li_id"
2881 if ($U->is_true($bib->deleted)) {
2882 my $holds = $mgr->editor->search_action_hold_request(
2883 { cancel_time => undef,
2884 fulfillment_time => undef,
2885 target => $li->eg_bib_id
2889 my %cached_usr_home_ou = ();
2891 for my $hold (@$holds) {
2893 $logger->info("Cancelling hold ".$hold->id.
2894 " due to acq lineitem cancellation.");
2896 $hold->cancel_time('now');
2897 $hold->cancel_cause(5); # 'Staff forced'--we may want a new hold cancel cause reason for this
2898 $hold->cancel_note('Corresponding Acquistion Lineitem/Purchase Order was cancelled.');
2899 unless($mgr->editor->update_action_hold_request($hold)) {
2900 my $evt = $mgr->editor->event;
2901 $logger->error("Error updating hold ". $evt->textcode .":". $evt->desc .":". $evt->stacktrace);
2902 return new OpenILS::Event(
2903 "ACQ_NOT_CANCELABLE", "note" => "Could not cancel hold " . $hold->id . " for lineitem $li_id", "payload" => $evt
2906 if (! defined $mgr->{post_commit}) { # we need a mechanism for creating trigger events, but only if the transaction gets committed
2907 $mgr->{post_commit} = [];
2909 push @{ $mgr->{post_commit} }, sub {
2910 my $home_ou = $cached_usr_home_ou{$hold->usr};
2912 my $user = $mgr->editor->retrieve_actor_user($hold->usr); # FIXME: how do we want to handle failures here?
2913 $home_ou = $user->home_ou;
2914 $cached_usr_home_ou{$hold->usr} = $home_ou;
2916 $U->create_events_for_hook('hold_request.cancel.cancelled_order', $hold, $home_ou);
2922 update_lineitem($mgr, $li) or return 0;
2925 "state" => $li->state,
2926 "cancel_reason" => $cancel_reason
2933 __PACKAGE__->register_method(
2934 method => "cancel_lineitem_detail_api",
2935 api_name => "open-ils.acq.lineitem_detail.cancel",
2937 desc => q/Cancels an on-order lineitem detail/,
2939 {desc => "Authentication token", type => "string"},
2940 {desc => "Lineitem detail ID to cancel", type => "number"},
2941 {desc => "Cancel reason ID", type => "number"}
2943 return => {desc => q/Object describing changed LIDs on success;
2948 sub cancel_lineitem_detail_api {
2949 my ($self, $conn, $auth, $lid_id, $cancel_reason) = @_;
2951 my $e = new_editor("xact" => 1, "authtoken" => $auth);
2952 return $e->die_event unless $e->checkauth;
2953 my $mgr = new OpenILS::Application::Acq::BatchManager(
2954 "editor" => $e, "conn" => $conn
2957 $cancel_reason = $mgr->editor->retrieve_acq_cancel_reason($cancel_reason) or
2958 return new OpenILS::Event(
2959 "BAD_PARAMS", "note" => "Provide cancel reason ID"
2962 my $result = cancel_lineitem_detail($mgr, $lid_id, $cancel_reason) or
2963 return $e->die_event;
2965 if (not_cancelable($result)) {
2968 } elsif ($result == -1) {
2970 return new OpenILS::Event("ACQ_ALREADY_CANCELED");
2973 $e->commit or return $e->die_event;
2975 # XXX create lineitem detail status events?
2979 sub cancel_lineitem_detail {
2980 my ($mgr, $lid_id, $cancel_reason) = @_;
2981 my $lid = $mgr->editor->retrieve_acq_lineitem_detail([
2985 "acqlid" => ["lineitem"], "jub" => ["purchase_order"]
2990 # Depending on context, this may not warrant an event.
2991 return -1 if $lid->cancel_reason;
2993 # But this always does.
2994 return new OpenILS::Event(
2995 "ACQ_NOT_CANCELABLE", "note" => "lineitem_detail $lid_id"
2997 (! $lid->lineitem->purchase_order) or
2999 (not $lid->recv_time) and
3001 $lid->lineitem->purchase_order and (
3002 $lid->lineitem->state eq "on-order" or
3003 $lid->lineitem->state eq "pending-order"
3008 return 0 unless $mgr->editor->allowed(
3009 "CREATE_PURCHASE_ORDER",
3010 $lid->lineitem->purchase_order->ordering_agency
3011 ) or (! $lid->lineitem->purchase_order);
3013 $lid->cancel_reason($cancel_reason->id);
3015 unless($U->is_true($cancel_reason->keep_debits)) {
3016 my $debit_id = $lid->fund_debit;
3017 $lid->clear_fund_debit;
3020 # item is cancelled. Remove the fund debit.
3021 my $debit = $mgr->editor->retrieve_acq_fund_debit($debit_id);
3022 if (!$U->is_true($debit->encumbrance)) {
3023 $mgr->editor->rollback;
3024 return OpenILS::Event->new('ACQ_NOT_CANCELABLE',
3025 note => "Debit is marked as paid: $debit_id");
3027 $mgr->editor->delete_acq_fund_debit($debit) or return $mgr->editor->die_event;
3031 # XXX LIDs don't have either an editor or a edit_time field. Should we
3032 # update these on the LI when we alter an LID?
3033 $mgr->editor->update_acq_lineitem_detail($lid) or return 0;
3035 return {"lid" => {$lid_id => {"cancel_reason" => $cancel_reason}}};
3039 __PACKAGE__->register_method(
3040 method => 'user_requests',
3041 api_name => 'open-ils.acq.user_request.retrieve.by_user_id',
3044 desc => 'Retrieve fleshed user requests and related data for a given user.',
3046 { desc => 'Authentication token', type => 'string' },
3047 { desc => 'User ID of the owner, or array of IDs', },
3048 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
3053 desc => 'Fleshed user requests and related data',
3059 __PACKAGE__->register_method(
3060 method => 'user_requests',
3061 api_name => 'open-ils.acq.user_request.retrieve.by_home_ou',
3064 desc => 'Retrieve fleshed user requests and related data for a given org unit or units.',
3066 { desc => 'Authentication token', type => 'string' },
3067 { desc => 'Org unit ID, or array of IDs', },
3068 { desc => 'Options hash (optional) with any of the keys: order_by, limit, offset, state (of the lineitem)',
3073 desc => 'Fleshed user requests and related data',
3080 my($self, $conn, $auth, $search_value, $options) = @_;
3081 my $e = new_editor(authtoken => $auth);
3082 return $e->event unless $e->checkauth;
3083 my $rid = $e->requestor->id;
3087 "select"=>{"aur"=>["id"],"au"=>["home_ou", {column => 'id', alias => 'usr_id'} ]},
3088 "from"=>{ "aur" => { "au" => {}, "jub" => { "type" => "left" } } },
3092 {"id"=>undef}, # this with the left-join pulls in requests without lineitems
3093 {"state"=>["new","on-order","pending-order"]} # FIXME - probably needs softcoding
3097 "order_by"=>[{"class"=>"aur", "field"=>"request_date", "direction"=>"desc"}]
3100 foreach (qw/ order_by limit offset /) {
3101 $query->{$_} = $options->{$_} if defined $options->{$_};
3103 if (defined $options->{'state'}) {
3104 $query->{'where'}->{'+jub'}->{'-or'}->[1]->{'state'} = $options->{'state'};
3107 if ($self->api_name =~ /by_user_id/) {
3108 $query->{'where'}->{'usr'} = $search_value;
3110 $query->{'where'}->{'+au'} = { 'home_ou' => $search_value };
3113 my $pertinent_ids = $e->json_query($query);
3116 for my $id_blob (@$pertinent_ids) {
3117 if ($rid != $id_blob->{usr_id}) {
3118 if (!defined $perm_test{ $id_blob->{home_ou} }) {
3119 $perm_test{ $id_blob->{home_ou} } = $e->allowed( ['user_request.view'], $id_blob->{home_ou} );
3121 if (!$perm_test{ $id_blob->{home_ou} }) {
3125 my $aur_obj = $e->retrieve_acq_user_request([
3127 {flesh => 1, flesh_fields => { "aur" => [ 'lineitem' ] } }
3129 if (! $aur_obj) { next; }
3131 if ($aur_obj->lineitem()) {
3132 $aur_obj->lineitem()->clear_marc();
3134 $conn->respond($aur_obj);
3140 __PACKAGE__->register_method (
3141 method => 'update_user_request',
3142 api_name => 'open-ils.acq.user_request.cancel.batch',
3145 desc => 'If given a cancel reason, will update the request with that reason, otherwise, this will delete the request altogether. The ' .
3146 'intention is for staff interfaces or processes to provide cancel reasons, and for patron interfaces to just delete the requests.' ,
3148 { desc => 'Authentication token', type => 'string' },
3149 { desc => 'ID or array of IDs for the user requests to cancel' },
3150 { desc => 'Cancel Reason ID (optional)', type => 'string' }
3153 desc => 'progress object, event on error',
3157 __PACKAGE__->register_method (
3158 method => 'update_user_request',
3159 api_name => 'open-ils.acq.user_request.set_no_hold.batch',
3162 desc => 'Remove the hold from a user request or set of requests',
3164 { desc => 'Authentication token', type => 'string' },
3165 { desc => 'ID or array of IDs for the user requests to modify' }
3168 desc => 'progress object, event on error',
3173 sub update_user_request {
3174 my($self, $conn, $auth, $aur_ids, $cancel_reason) = @_;
3175 my $e = new_editor(xact => 1, authtoken => $auth);
3176 return $e->die_event unless $e->checkauth;
3177 my $rid = $e->requestor->id;
3181 for my $id (@$aur_ids) {
3183 my $aur_obj = $e->retrieve_acq_user_request([
3186 flesh_fields => { "aur" => ['lineitem', 'usr'] }
3188 ]) or return $e->die_event;
3190 my $context_org = $aur_obj->usr()->home_ou();
3191 $aur_obj->usr( $aur_obj->usr()->id() );
3193 if ($rid != $aur_obj->usr) {
3194 if (!defined $perm_test{ $context_org }) {
3195 $perm_test{ $context_org } = $e->allowed( ['user_request.update'], $context_org );
3197 if (!$perm_test{ $context_org }) {
3202 if($self->api_name =~ /set_no_hold/) {
3203 if ($U->is_true($aur_obj->hold)) {
3205 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3209 if($self->api_name =~ /cancel/) {
3210 if ( $cancel_reason ) {
3211 $aur_obj->cancel_reason( $cancel_reason );
3212 $e->update_acq_user_request($aur_obj) or return $e->die_event;
3213 create_user_request_events( $e, [ $aur_obj ], 'aur.rejected' );
3215 $e->delete_acq_user_request($aur_obj);
3219 $conn->respond({maximum => scalar(@$aur_ids), progress => $x++});
3223 return {complete => 1};
3226 __PACKAGE__->register_method (
3227 method => 'new_user_request',
3228 api_name => 'open-ils.acq.user_request.create',
3230 desc => 'Create a new user request object in the DB',
3232 { desc => 'Authentication token', type => 'string' },
3233 { desc => 'User request data hash. Hash keys match the fields for the "aur" object', type => 'object' }
3236 desc => 'The created user request object, or event on error'
3241 sub new_user_request {
3242 my($self, $conn, $auth, $form_data) = @_;
3243 my $e = new_editor(xact => 1, authtoken => $auth);
3244 return $e->die_event unless $e->checkauth;
3245 my $rid = $e->requestor->id;
3246 my $target_user_fleshed;
3247 if (! defined $$form_data{'usr'}) {
3248 $$form_data{'usr'} = $rid;
3250 if ($$form_data{'usr'} != $rid) {
3251 # See if the requestor can place the request on behalf of a different user.
3252 $target_user_fleshed = $e->retrieve_actor_user($$form_data{'usr'}) or return $e->die_event;
3253 $e->allowed('user_request.create', $target_user_fleshed->home_ou) or return $e->die_event;
3255 $target_user_fleshed = $e->requestor;
3256 $e->allowed('CREATE_PURCHASE_REQUEST') or return $e->die_event;
3258 if (! defined $$form_data{'pickup_lib'}) {
3259 if ($target_user_fleshed->ws_ou) {
3260 $$form_data{'pickup_lib'} = $target_user_fleshed->ws_ou;
3262 $$form_data{'pickup_lib'} = $target_user_fleshed->home_ou;
3265 if (! defined $$form_data{'request_type'}) {
3266 $$form_data{'request_type'} = 1; # Books
3268 my $aur_obj = new Fieldmapper::acq::user_request;
3270 $aur_obj->usr( $$form_data{'usr'} );
3271 $aur_obj->request_date( 'now' );
3272 for my $field ( keys %$form_data ) {
3273 if (defined $$form_data{$field} and $field !~ /^(id|lineitem|eg_bib|request_date|cancel_reason)$/) {
3274 $aur_obj->$field( $$form_data{$field} );
3278 $aur_obj = $e->create_acq_user_request($aur_obj) or return $e->die_event;
3280 $e->commit and create_user_request_events( $e, [ $aur_obj ], 'aur.created' );
3285 sub create_user_request_events {
3286 my($e, $user_reqs, $hook) = @_;
3288 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
3291 my %cached_usr_home_ou = ();
3292 for my $user_req (@$user_reqs) {
3293 my $home_ou = $cached_usr_home_ou{$user_req->usr};
3295 my $user = $e->retrieve_actor_user($user_req->usr) or return $e->die_event;
3296 $home_ou = $user->home_ou;
3297 $cached_usr_home_ou{$user_req->usr} = $home_ou;
3299 my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $user_req, $home_ou);
3308 __PACKAGE__->register_method(
3309 method => "po_note_CUD_batch",
3310 api_name => "open-ils.acq.po_note.cud.batch",
3313 desc => q/Manage purchase order notes/,
3315 {desc => "Authentication token", type => "string"},
3316 {desc => "List of po_notes to manage", type => "array"},
3318 return => {desc => "Stream of successfully managed objects"}
3322 sub po_note_CUD_batch {
3323 my ($self, $conn, $auth, $notes) = @_;
3325 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3326 return $e->die_event unless $e->checkauth;
3329 my $total = @$notes;
3332 foreach my $note (@$notes) {
3334 $note->editor($e->requestor->id);
3335 $note->edit_time("now");
3338 $note->creator($e->requestor->id);
3339 $note = $e->create_acq_po_note($note) or return $e->die_event;
3340 } elsif ($note->isdeleted) {
3341 $e->delete_acq_po_note($note) or return $e->die_event;
3342 } elsif ($note->ischanged) {
3343 $e->update_acq_po_note($note) or return $e->die_event;
3346 unless ($note->isdeleted) {
3347 $note = $e->retrieve_acq_po_note($note->id) or
3348 return $e->die_event;
3352 {"maximum" => $total, "progress" => ++$count, "note" => $note}
3356 $e->commit and $conn->respond_complete or return $e->die_event;
3360 # retrieves a lineitem, fleshes its PO and PL, checks perms
3361 sub fetch_and_check_li {
3364 my $perm_mode = shift || 'read';
3366 my $li = $e->retrieve_acq_lineitem([
3369 flesh_fields => {jub => ['purchase_order', 'picklist']}
3371 ]) or return $e->die_event;
3373 if(my $po = $li->purchase_order) {
3374 my $perms = ($perm_mode eq 'read') ? 'VIEW_PURCHASE_ORDER' : 'CREATE_PURCHASE_ORDER';
3375 return ($li, $e->die_event) unless $e->allowed($perms, $po->ordering_agency);
3377 } elsif(my $pl = $li->picklist) {
3378 my $perms = ($perm_mode eq 'read') ? 'VIEW_PICKLIST' : 'CREATE_PICKLIST';
3379 return ($li, $e->die_event) unless $e->allowed($perms, $pl->org_unit);
3386 __PACKAGE__->register_method(
3387 method => "clone_distrib_form",
3388 api_name => "open-ils.acq.distribution_formula.clone",
3391 desc => q/Clone a distribution formula/,
3393 {desc => "Authentication token", type => "string"},
3394 {desc => "Original formula ID", type => 'integer'},
3395 {desc => "Name of new formula", type => 'string'},
3397 return => {desc => "ID of newly created formula"}
3401 sub clone_distrib_form {
3402 my($self, $client, $auth, $form_id, $new_name) = @_;
3404 my $e = new_editor("xact"=> 1, "authtoken" => $auth);
3405 return $e->die_event unless $e->checkauth;
3407 my $old_form = $e->retrieve_acq_distribution_formula($form_id) or return $e->die_event;
3408 return $e->die_event unless $e->allowed('ADMIN_ACQ_DISTRIB_FORMULA', $old_form->owner);
3410 my $new_form = Fieldmapper::acq::distribution_formula->new;
3412 $new_form->owner($old_form->owner);
3413 $new_form->name($new_name);
3414 $e->create_acq_distribution_formula($new_form) or return $e->die_event;
3416 my $entries = $e->search_acq_distribution_formula_entry({formula => $form_id});
3417 for my $entry (@$entries) {
3418 my $new_entry = Fieldmapper::acq::distribution_formula_entry->new;
3419 $new_entry->$_($entry->$_()) for $entry->real_fields;
3420 $new_entry->formula($new_form->id);
3421 $new_entry->clear_id;
3422 $e->create_acq_distribution_formula_entry($new_entry) or return $e->die_event;
3426 return $new_form->id;
3429 __PACKAGE__->register_method(
3430 method => 'add_li_to_po',
3431 api_name => 'open-ils.acq.purchase_order.add_lineitem',
3433 desc => q/Adds a lineitem to an existing purchase order/,
3435 {desc => 'Authentication token', type => 'string'},
3436 {desc => 'The purchase order id', type => 'number'},
3437 {desc => 'The lineitem ID', type => 'number'},
3439 return => {desc => 'Streams a total versus completed counts object, event on error'}
3444 my($self, $conn, $auth, $po_id, $li_id) = @_;
3446 my $e = new_editor(authtoken => $auth, xact => 1);
3447 return $e->die_event unless $e->checkauth;
3449 my $mgr = OpenILS::Application::Acq::BatchManager->new(editor => $e, conn => $conn);
3451 my $po = $e->retrieve_acq_purchase_order($po_id)
3452 or return $e->die_event;
3454 my $li = $e->retrieve_acq_lineitem($li_id)
3455 or return $e->die_event;
3457 return $e->die_event unless
3458 $e->allowed('CREATE_PURCHASE_ORDER', $po->ordering_agency);
3460 unless ($po->state =~ /new|pending/) {
3462 return {success => 0, po => $po, error => 'bad-po-state'};
3465 unless ($li->state =~ /new|order-ready|pending-order/) {
3467 return {success => 0, li => $li, error => 'bad-li-state'};
3470 $li->provider($po->provider);
3471 $li->purchase_order($po_id);
3472 $li->state('pending-order');
3473 update_lineitem($mgr, $li) or return $e->die_event;
3476 return {success => 1};
3479 __PACKAGE__->register_method(
3480 method => 'po_lineitems_no_copies',
3481 api_name => 'open-ils.acq.purchase_order.no_copy_lineitems.id_list',
3485 desc => q/Returns the set of lineitem IDs for a given PO that have no copies attached/,
3487 {desc => 'Authentication token', type => 'string'},
3488 {desc => 'The purchase order id', type => 'number'},
3490 return => {desc => 'Stream of lineitem IDs on success, event on error'}
3494 sub po_lineitems_no_copies {
3495 my ($self, $conn, $auth, $po_id) = @_;
3497 my $e = new_editor(authtoken => $auth);
3498 return $e->event unless $e->checkauth;
3500 # first check the view perms for LI's attached to this PO
3501 my $po = $e->retrieve_acq_purchase_order($po_id) or return $e->event;
3502 return $e->event unless $e->allowed('VIEW_PURCHASE_ORDER', $po->ordering_agency);
3504 my $ids = $e->json_query({
3505 select => {jub => ['id']},
3506 from => {jub => {acqlid => {type => 'left'}}},
3508 '+jub' => {purchase_order => $po_id},
3509 '+acqlid' => {lineitem => undef}
3513 $conn->respond($_->{id}) for @$ids;