1 package OpenILS::Application::Acq::Invoice;
2 use base qw/OpenILS::Application/;
3 use strict; use warnings;
5 use OpenSRF::Utils::Logger qw(:logger);
6 use OpenILS::Utils::Fieldmapper;
7 use OpenILS::Utils::CStoreEditor q/:funcs/;
8 use OpenILS::Application::AppUtils;
10 my $U = 'OpenILS::Application::AppUtils';
13 # return nothing on success, event on failure
14 sub _prepare_fund_debit_for_inv_item {
15 my ($debit, $item, $e) = @_;
17 $debit->fund($item->fund);
18 $debit->amount($item->amount_paid);
19 $debit->origin_amount($item->amount_paid);
21 # future: cache funds locally
22 my $fund = $e->retrieve_acq_fund($item->fund) or return $e->die_event;
24 $debit->origin_currency_type($fund->currency_type);
25 $debit->encumbrance('f');
26 $debit->debit_type('direct_charge');
31 __PACKAGE__->register_method(
32 method => 'build_invoice_api',
33 api_name => 'open-ils.acq.invoice.update',
35 desc => q/Creates, updates, and deletes invoices, and related invoice entries, and invoice items/,
37 {desc => 'Authentication token', type => 'string'},
38 {desc => q/Invoice/, type => 'number'},
39 {desc => q/Entries. Array of 'acqie' objects/, type => 'array'},
40 {desc => q/Items. Array of 'acqii' objects/, type => 'array'},
42 return => {desc => 'The invoice w/ entries and items attached', type => 'object', class => 'acqinv'}
47 sub build_invoice_impl {
48 my ($e, $invoice, $entries, $items, $do_commit) = @_;
50 if ($invoice->isnew) {
51 $invoice->recv_method('PPR') unless $invoice->recv_method;
52 $invoice->recv_date('now') unless $invoice->recv_date;
53 $e->create_acq_invoice($invoice) or return $e->die_event;
54 } elsif ($invoice->isdeleted) {
55 $e->delete_acq_invoice($invoice) or return $e->die_event;
57 $e->update_acq_invoice($invoice) or return $e->die_event;
63 for my $entry (@$entries) {
64 $entry->invoice($invoice->id);
67 $e->create_acq_invoice_entry($entry) or return $e->die_event;
68 return $evt if $evt = uncancel_copies_as_needed($e, $entry);
69 return $evt if $evt = update_entry_debits($e, $entry);
70 } elsif ($entry->isdeleted) {
71 # XXX Deleting entries does not recancel anything previously
73 return $evt if $evt = rollback_entry_debits($e, $entry);
74 $e->delete_acq_invoice_entry($entry) or return $e->die_event;
75 } elsif ($entry->ischanged) {
76 my $orig_entry = $e->retrieve_acq_invoice_entry($entry->id) or
79 if ($orig_entry->amount_paid != $entry->amount_paid or
80 $entry->phys_item_count != $orig_entry->phys_item_count) {
81 return $evt if $evt = rollback_entry_debits($e,$orig_entry);
83 # XXX Updates can only uncancel more LIDs when
84 # phys_item_count goes up, but cannot recancel them when
85 # phys_item_count goes down.
86 return $evt if $evt = uncancel_copies_as_needed($e, $entry);
88 return $evt if $evt = update_entry_debits($e, $entry);
91 $e->update_acq_invoice_entry($entry) or return $e->die_event;
97 for my $item (@$items) {
98 $item->invoice($invoice->id);
101 $e->create_acq_invoice_item($item) or return $e->die_event;
103 # future: cache item types
104 my $item_type = $e->retrieve_acq_invoice_item_type(
105 $item->inv_item_type) or return $e->die_event;
107 # This following complex conditional statement effecively means:
108 # 1) Items with item_types that are prorate are handled
110 # 2) Only items with a po_item, or which are linked to a fund
111 # already, or which belong to invoices which we're trying
112 # to *close* will actually go through this fund_debit
113 # creation process. In other cases, we'll consider it
114 # ok for an item to remain sans fund_debit for the time
117 if (not $U->is_true($item_type->prorate) and
118 ($item->po_item or $item->fund or
119 $U->is_true($invoice->complete))) {
122 if ($item->po_item) {
123 my $po_item = $e->retrieve_acq_po_item($item->po_item)
124 or return $e->die_event;
125 $debit = $e->retrieve_acq_fund_debit($po_item->fund_debit)
126 or return $e->die_event;
128 $debit = Fieldmapper::acq::fund_debit->new;
133 $evt = _prepare_fund_debit_for_inv_item($debit, $item, $e);
136 $e->create_acq_fund_debit($debit)
137 or return $e->die_event;
139 $e->update_acq_fund_debit($debit)
140 or return $e->die_event;
143 $item->fund_debit($debit->id);
144 $e->update_acq_invoice_item($item) or return $e->die_event;
146 } elsif ($item->isdeleted) {
147 $e->delete_acq_invoice_item($item) or return $e->die_event;
149 if ($item->po_item and
150 $e->retrieve_acq_po_item($item->po_item)->fund_debit == $item->fund_debit) {
151 # the debit is attached to the po_item. instead of
152 # deleting it, roll it back to being an encumbrance.
153 # Note: a prorated invoice_item that points to a
154 # po_item could point to a different fund_debit. We
155 # can't go back in time to collect all the prorated
156 # invoice_items (nor is the caller asking us too),
157 # so when that happens, just delete the extraneous
158 # debit (in the else block).
159 my $debit = $e->retrieve_acq_fund_debit($item->fund_debit);
160 $debit->encumbrance('t');
161 $e->update_acq_fund_debit($debit) or return $e->die_event;
162 } elsif ($item->fund_debit) {
163 $e->delete_acq_fund_debit($e->retrieve_acq_fund_debit($item->fund_debit))
164 or return $e->die_event;
166 } elsif ($item->ischanged) {
169 if (!$item->fund_debit) {
170 # No fund_debit yet? Make one now.
171 $debit = Fieldmapper::acq::fund_debit->new;
175 $evt = _prepare_fund_debit_for_inv_item($debit, $item, $e);
177 $debit = $e->retrieve_acq_fund_debit($item->fund_debit) or
178 return $e->die_event;
181 $debit->amount($item->amount_paid);
182 $debit->fund($item->fund);
185 # Making a new debit, so make it and link our item to it.
186 $e->create_acq_fund_debit($debit) or return $e->die_event;
187 $item->fund_debit($e->data->id);
189 $e->update_acq_fund_debit($debit) or return $e->die_event;
192 $e->update_acq_invoice_item($item) or return $e->die_event;
197 $invoice = fetch_invoice_impl($e, $invoice->id);
199 $e->commit or return $e->die_event;
205 sub build_invoice_api {
206 my($self, $conn, $auth, $invoice, $entries, $items) = @_;
208 my $e = new_editor(xact => 1, authtoken=>$auth);
209 return $e->die_event unless $e->checkauth;
211 if (not ref $invoice) {
212 # caller only provided the ID
213 $invoice = $e->retrieve_acq_invoice($invoice) or return $e->die_event;
216 if (not $invoice->receiver and $invoice->isnew) {
217 $invoice->receiver($e->requestor->ws_ou);
220 return $e->die_event unless
221 $e->allowed('CREATE_INVOICE', $invoice->receiver);
223 return build_invoice_impl($e, $invoice, $entries, $items, 1);
227 sub rollback_entry_debits {
229 my $debits = find_entry_debits($e, $entry, 'f', entry_amount_per_item($entry));
230 my $lineitem = $e->retrieve_acq_lineitem($entry->lineitem) or return $e->die_event;
232 for my $debit (@$debits) {
233 # revert to the original estimated amount re-encumber
234 $debit->encumbrance('t');
235 $debit->amount($lineitem->estimated_unit_price());
236 $e->update_acq_fund_debit($debit) or return $e->die_event;
237 update_copy_cost($e, $debit) or return $e->die_event; # clear the cost
243 sub update_entry_debits {
246 my $debits = find_entry_debits($e, $entry, 't');
247 return undef unless @$debits;
249 if($entry->phys_item_count > @$debits) {
251 # We can't invoice for more items than we have debits for
252 return OpenILS::Event->new(
253 'ACQ_INVOICE_ENTRY_COUNT_EXCEEDS_DEBITS',
254 payload => {entry => $entry->id});
257 for my $debit (@$debits) {
258 my $amount = entry_amount_per_item($entry);
259 $debit->amount($amount);
260 $debit->encumbrance('f');
261 $e->update_acq_fund_debit($debit) or return $e->die_event;
263 # TODO: this does not reflect ancillary charges, like taxes, etc.
264 # We may need a way to indicate whether the amount attached to an
265 # invoice_item should be prorated and included in the copy cost.
266 # Note that acq.invoice_item_type.prorate does not necessarily
267 # mean a charge should be included in the copy price, only that
268 # it should spread accross funds.
269 update_copy_cost($e, $debit, $amount) or return $e->die_event;
275 # This was originally done only for EDI invoices, but needs added to the
276 # manual invoice-entering process for consistency's sake.
277 sub uncancel_copies_as_needed {
278 my ($e, $entry) = @_;
280 return unless $entry->lineitem and $entry->phys_item_count;
282 my $li = $e->retrieve_acq_lineitem($entry->lineitem) or
283 return $e->die_event;
285 # if an invoiced lineitem is marked as cancelled
286 # (e.g. back-order), invoicing the lineitem implies
287 # we need to un-cancel it
289 # collect the LIDs, starting with those that are
290 # not cancelled, followed by those that have keep-debits cancel_reasons,
291 # followed by non-keep-debit cancel reasons.
293 my $lid_ids = $e->json_query({
294 select => {acqlid => ['id']},
297 acqcr => {type => 'left'},
298 acqfdeb => {type => 'left'}
302 '+acqlid' => {lineitem => $li->id},
303 '+acqfdeb' => {encumbrance => 't'} # not-yet invoiced copies
307 field => 'keep_debits',
310 limit => $entry->phys_item_count # crucial
313 for my $lid_id (map {$_->{id}} @$lid_ids) {
314 my $lid = $e->retrieve_acq_lineitem_detail($lid_id);
315 next unless $lid->cancel_reason;
318 "un-cancelling invoice lineitem " . $li->id .
319 " lineitem_detail " . $lid_id
321 $lid->clear_cancel_reason;
322 return $e->die_event unless $e->update_acq_lineitem_detail($lid);
325 $li->clear_cancel_reason;
326 $li->state("on-order") if $li->state eq "cancelled"; # sic
327 $li->edit_time("now");
329 unless ($e->update_acq_lineitem($li)) {
330 my $evt = $e->die_event;
331 $logger->error("couldn't clear li cancel reason: ". $evt->{textcode});
339 # update the linked copy to reflect the amount paid for the item
340 # returns true on success, false on error
341 sub update_copy_cost {
342 my ($e, $debit, $amount) = @_;
344 my $lid = $e->search_acq_lineitem_detail([
345 {fund_debit => $debit->id},
346 {flesh => 1, flesh_fields => {acqlid => ['eg_copy_id']}}
349 if($lid and my $copy = $lid->eg_copy_id) {
350 defined $amount and $copy->cost($amount) or $copy->clear_cost;
352 # XXX It would be nice to have a way to record that a copy was
353 # updated by a non-user mechanism, like EDI, but we don't have
354 # a clear way to do that here.
356 $copy->editor($e->requestor->id);
357 $copy->edit_date('now');
360 $e->update_asset_copy($copy) or return 0;
367 sub entry_amount_per_item {
369 return $entry->amount_paid if $U->is_true($entry->billed_per_item);
370 return 0 if $entry->phys_item_count == 0;
371 return $entry->amount_paid / $entry->phys_item_count;
374 sub easy_money { # TODO XXX replace with something from a library
377 my $rounded = int($val * 100) / 100.0;
378 if ($rounded == $val) {
379 return sprintf("%.02f", $val);
381 return sprintf("%g", $val);
385 # 0 on failure (caller should call $e->die_event), array on success
386 sub amounts_spent_per_fund {
387 my ($e, $inv_id) = @_;
389 my $entries = $e->search_acq_invoice_entry({"invoice" => $inv_id}) or
392 my $items = $e->search_acq_invoice_item({"invoice" => $inv_id}) or
396 foreach my $entry (@$entries) {
397 my $debits = find_entry_debits($e, $entry, "f") or return 0;
399 $totals_by_fund{$_->fund} ||= 0.0;
400 $totals_by_fund{$_->fund} += $_->amount;
404 foreach my $item (@$items) {
405 next unless $item->fund and $item->amount_paid;
406 $totals_by_fund{$item->fund} ||= 0.0;
407 $totals_by_fund{$item->fund} += $item->amount_paid;
411 foreach my $fund_id (keys %totals_by_fund) {
412 my $fund = $e->retrieve_acq_fund($fund_id) or return 0;
414 "fund" => $fund->to_bare_hash,
415 "total" => easy_money($totals_by_fund{$fund_id})
422 # there is no direct link between invoice_entry and fund debits.
423 # when we need to retrieve the related debits, we have to do some searching
424 sub find_entry_debits {
425 my($e, $entry, $encumbrance, $amount) = @_;
428 select => {acqfdeb => ['id']},
436 filter => {id => $entry->id}
444 where => {'+acqfdeb' => {encumbrance => $encumbrance}},
445 order_by => {'acqlid' => ['recv_time']}, # un-received items will sort to the end
446 limit => $entry->phys_item_count
449 $query->{where}->{'+acqfdeb'}->{amount} = $amount if $amount;
451 my $debits = $e->json_query($query);
452 my $debit_ids = [map { $_->{id} } @$debits];
453 return (@$debit_ids) ? $e->search_acq_fund_debit({id => $debit_ids}) : [];
457 __PACKAGE__->register_method(
458 method => 'build_invoice_api',
459 api_name => 'open-ils.acq.invoice.retrieve',
462 desc => q/Creates a new stub invoice/,
464 {desc => 'Authentication token', type => 'string'},
465 {desc => q/Invoice Id/, type => 'number'},
467 return => {desc => 'The new invoice w/ entries and items attached', type => 'object', class => 'acqinv'}
472 sub fetch_invoice_api {
473 my($self, $conn, $auth, $invoice_id, $options) = @_;
475 my $e = new_editor(authtoken=>$auth);
476 return $e->event unless $e->checkauth;
478 my $invoice = fetch_invoice_impl($e, $invoice_id, $options) or
480 return $e->event unless $e->allowed(['VIEW_INVOICE', 'CREATE_INVOICE'], $invoice->receiver);
485 sub fetch_invoice_impl {
486 my ($e, $invoice_id, $options) = @_;
490 my $args = $options->{"no_flesh_misc"} ? $invoice_id : [
495 "acqinv" => ["entries", "items"],
496 "acqii" => ["fund_debit", "purchase_order", "po_item"]
501 return $e->retrieve_acq_invoice($args);
504 __PACKAGE__->register_method(
505 method => 'prorate_invoice',
506 api_name => 'open-ils.acq.invoice.apply_prorate',
509 For all invoice items that have the prorate flag set to true, this will create the necessary
510 additional invoice_item's to prorate the cost across all affected funds by percent spent for each fund.
513 {desc => 'Authentication token', type => 'string'},
514 {desc => q/Invoice Id/, type => 'number'},
516 return => {desc => 'The updated invoice w/ entries and items attached', type => 'object', class => 'acqinv'}
521 sub prorate_invoice {
522 my($self, $conn, $auth, $invoice_id) = @_;
524 my $e = new_editor(xact => 1, authtoken=>$auth);
525 return $e->die_event unless $e->checkauth;
527 my $invoice = fetch_invoice_impl($e, $invoice_id) or return $e->die_event;
528 return $e->die_event unless $e->allowed('CREATE_INVOICE', $invoice->receiver);
531 push(@lid_debits, @{find_entry_debits($e, $_, 'f', entry_amount_per_item($_))}) for @{$invoice->entries};
533 my $inv_items = $e->search_acq_invoice_item([
534 {"invoice" => $invoice_id, "fund_debit" => {"!=" => undef}},
535 {"flesh" => 1, "flesh_fields" => {"acqii" => ["fund_debit"]}}
536 ]) or return $e->die_event;
538 my @item_debits = map { $_->fund_debit } @$inv_items;
541 my $total_entry_paid = 0;
542 for my $debit (@lid_debits, @item_debits) {
543 $fund_totals{$debit->fund} = 0 unless $fund_totals{$debit->fund};
544 $fund_totals{$debit->fund} += $debit->amount;
545 $total_entry_paid += $debit->amount;
548 $logger->info("invoice: prorating against invoice amount $total_entry_paid");
550 for my $item (@{$invoice->items}) {
552 next if $item->fund_debit; # item has already been processed
554 # future: cache item types locally
555 my $item_type = $e->retrieve_acq_invoice_item_type($item->inv_item_type) or return $e->die_event;
556 next unless $U->is_true($item_type->prorate);
558 # Prorate charges across applicable funds
559 my $full_item_paid = $item->amount_paid; # total amount paid for this item before splitting
560 my $full_item_cost = $item->cost_billed; # total amount invoiced for this item before splitting
564 my $total_debited = 0;
565 my $total_costed = 0;
567 for my $fund_id (keys %fund_totals) {
569 my $spent_for_fund = $fund_totals{$fund_id};
570 next unless $spent_for_fund > 0;
572 my $prorated_amount = ($spent_for_fund / $total_entry_paid) * $full_item_paid;
573 my $prorated_cost = ($spent_for_fund / $total_entry_paid) * $full_item_cost;
574 $logger->info("invoice: attaching prorated amount $prorated_amount to fund $fund_id for invoice $invoice_id");
577 if($first_round and $item->po_item) {
578 # if this item is the result of a PO item, repurpose the original debit
579 # for the first chunk of the prorated amount
580 $debit = $e->retrieve_acq_fund_debit($item->po_item->fund_debit);
582 $debit = Fieldmapper::acq::fund_debit->new;
586 $debit->fund($fund_id);
587 $debit->amount($prorated_amount);
588 $debit->origin_amount($prorated_amount);
589 $debit->origin_currency_type($e->retrieve_acq_fund($fund_id)->currency_type); # future: cache funds locally
590 $debit->encumbrance('f');
591 $debit->debit_type('prorated_charge');
594 $e->create_acq_fund_debit($debit) or return $e->die_event;
596 $e->update_acq_fund_debit($debit) or return $e->die_event;
599 $total_debited += $prorated_amount;
600 $total_costed += $prorated_cost;
601 $largest_debit = $debit if !$largest_debit or $prorated_amount > $largest_debit->amount;
605 # re-purpose the original invoice_item for the first prorated amount
606 $item->fund($fund_id);
607 $item->fund_debit($debit->id);
608 $item->amount_paid($prorated_amount);
609 $item->cost_billed($prorated_cost);
610 $e->update_acq_invoice_item($item) or return $e->die_event;
611 $largest_item = $item if !$largest_item or $prorated_amount > $largest_item->amount_paid;
615 # for subsequent prorated amounts, create a new invoice_item
616 my $new_item = $item->clone;
618 $new_item->fund($fund_id);
619 $new_item->fund_debit($debit->id);
620 $new_item->amount_paid($prorated_amount);
621 $new_item->cost_billed($prorated_cost);
622 $e->create_acq_invoice_item($new_item) or return $e->die_event;
623 $largest_item = $new_item if !$largest_item or $prorated_amount > $largest_item->amount_paid;
629 # make sure the percentages didn't leave a small sliver of money over/under-debited
630 # if so, tweak the largest debit to smooth out the difference
631 if($total_debited != $full_item_paid or $total_costed != $full_item_cost) {
633 my $paid_diff = $full_item_paid - $total_debited;
634 my $cost_diff = $full_item_cost - $total_debited;
635 $logger->info("invoice: repairing prorate descrepency of paid:$paid_diff and cost:$cost_diff");
636 my $new_paid = $largest_item->amount_paid + $paid_diff;
637 my $new_cost = $largest_item->cost_billed + $cost_diff;
639 $largest_debit = $e->retrieve_acq_fund_debit($largest_debit->id); # get latest copy
640 $largest_debit->amount($new_paid);
641 $e->update_acq_fund_debit($largest_debit) or return $e->die_event;
643 $largest_item = $e->retrieve_acq_invoice_item($largest_item->id); # get latest copy
644 $largest_item->amount_paid($new_paid);
645 $largest_item->cost_billed($new_cost);
647 $e->update_acq_invoice_item($largest_item) or return $e->die_event;
651 $invoice = fetch_invoice_impl($e, $invoice_id);
658 __PACKAGE__->register_method(
659 method => "print_html_invoice",
660 api_name => "open-ils.acq.invoice.print.html",
663 desc => "Retrieve printable HTML vouchers for each given invoice",
665 {desc => "Authentication token", type => "string"},
666 {desc => "Invoice ID or a list of them", type => "mixed"},
669 desc => q{One A/T event containing a printable HTML voucher for
671 type => "object", class => "atev"}
676 sub print_html_invoice {
677 my ($self, $conn, $auth, $id_list) = @_;
679 my $e = new_editor("authtoken" => $auth);
680 return $e->die_event unless $e->checkauth;
682 $id_list = [$id_list] unless ref $id_list;
684 my $invoices = $e->search_acq_invoice({"id" => $id_list}) or
685 return $e->die_event;
687 foreach my $invoice (@$invoices) {
688 return $e->die_event unless
689 $e->allowed("VIEW_INVOICE", $invoice->receiver);
691 my $amounts = amounts_spent_per_fund($e, $invoice->id) or
692 return $e->die_event;
695 $U->fire_object_event(
696 undef, "format.acqinv.html", $invoice, $invoice->receiver,
697 "print-on-demand", $amounts