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 __PACKAGE__->register_method(
14 method => 'build_invoice_api',
15 api_name => 'open-ils.acq.invoice.update',
17 desc => q/Creates, updates, and deletes invoices, and related invoice entries, and invoice items/,
19 {desc => 'Authentication token', type => 'string'},
20 {desc => q/Invoice/, type => 'number'},
21 {desc => q/Entries. Array of 'acqie' objects/, type => 'array'},
22 {desc => q/Items. Array of 'acqii' objects/, type => 'array'},
24 return => {desc => 'The invoice w/ entries and items attached', type => 'object', class => 'acqinv'}
28 sub build_invoice_api {
29 my($self, $conn, $auth, $invoice, $entries, $items) = @_;
31 my $e = new_editor(xact => 1, authtoken=>$auth);
32 return $e->die_event unless $e->checkauth;
37 $invoice->receiver($e->requestor->ws_ou) unless $invoice->receiver;
38 $invoice->recv_method('PPR') unless $invoice->recv_method;
39 $invoice->recv_date('now') unless $invoice->recv_date;
40 $e->create_acq_invoice($invoice) or return $e->die_event;
41 } elsif($invoice->isdeleted) {
42 i$e->delete_acq_invoice($invoice) or return $e->die_event;
44 $e->update_acq_invoice($invoice) or return $e->die_event;
47 # caller only provided the ID
48 $invoice = $e->retrieve_acq_invoice($invoice) or return $e->die_event;
51 return $e->die_event unless $e->allowed('CREATE_INVOICE', $invoice->receiver);
54 for my $entry (@$entries) {
55 $entry->invoice($invoice->id);
59 $e->create_acq_invoice_entry($entry) or return $e->die_event;
60 return $evt if $evt = update_entry_debits($e, $entry);
62 } elsif($entry->isdeleted) {
64 return $evt if $evt = rollback_entry_debits($e, $entry);
65 $e->delete_acq_invoice_entry($entry) or return $e->die_event;
67 } elsif($entry->ischanged) {
69 my $orig_entry = $e->retrieve_acq_invoice_entry($entry->id) or return $e->die_event;
71 if($orig_entry->amount_paid != $entry->amount_paid or
72 $entry->phys_item_count != $orig_entry->phys_item_count) {
74 return $evt if $evt = rollback_entry_debits($e, $orig_entry);
75 return $evt if $evt = update_entry_debits($e, $entry);
79 $e->update_acq_invoice_entry($entry) or return $e->die_event;
85 for my $item (@$items) {
86 $item->invoice($invoice->id);
90 $e->create_acq_invoice_item($item) or return $e->die_event;
92 # future: cache item types
93 my $item_type = $e->retrieve_acq_invoice_item_type(
94 $item->inv_item_type) or return $e->die_event;
96 # prorated items are handled separately
97 unless($U->is_true($item_type->prorate)) {
100 my $po_item = $e->retrieve_acq_po_item($item->po_item) or return $e->die_event;
101 $debit = $e->retrieve_acq_fund_debit($po_item->fund_debit) or return $e->die_event;
103 $debit = Fieldmapper::acq::fund_debit->new;
106 $debit->fund($item->fund);
107 $debit->amount($item->amount_paid);
108 $debit->origin_amount($item->amount_paid);
109 $debit->origin_currency_type($e->retrieve_acq_fund($item->fund)->currency_type); # future: cache funds locally
110 $debit->encumbrance('f');
111 $debit->debit_type('direct_charge');
114 $e->create_acq_fund_debit($debit) or return $e->die_event;
116 $e->update_acq_fund_debit($debit) or return $e->die_event;
119 $item->fund_debit($debit->id);
120 $e->update_acq_invoice_item($item) or return $e->die_event;
123 } elsif($item->isdeleted) {
125 $e->delete_acq_invoice_item($item) or return $e->die_event;
127 if($item->po_item and $e->retrieve_acq_po_item($item->po_item)->fund_debit == $item->fund_debit) {
128 # the debit is attached to the po_item. instead of deleting it, roll it back
129 # to being an encumbrance. Note: a prorated invoice_item that points to a po_item
130 # could point to a different fund_debit. We can't go back in time to collect all the
131 # prorated invoice_items (nor is the caller asking us too), so when that happens,
132 # just delete the extraneous debit (in the else block).
133 my $debit = $e->retrieve_acq_fund_debit($item->fund_debit);
134 $debit->encumbrance('t');
135 $e->update_acq_fund_debit($debit) or return $e->die_event;
137 $e->delete_acq_fund_debit($e->retrieve_acq_fund_debit($item->fund_debit))
138 or return $e->die_event;
142 } elsif($item->ischanged) {
144 my $debit = $e->retrieve_acq_fund_debit($item->fund_debit) or return $e->die_event;
145 $debit->amount($item->amount_paid);
146 $debit->fund($item->fund);
147 $e->update_acq_fund_debit($debit) or return $e->die_event;
148 $e->update_acq_invoice_item($item) or return $e->die_event;
153 $invoice = fetch_invoice_impl($e, $invoice->id);
160 sub rollback_entry_debits {
162 my $debits = find_entry_debits($e, $entry, 'f', entry_amount_per_item($entry));
163 my $lineitem = $e->retrieve_acq_lineitem($entry->lineitem) or return $e->die_event;
165 for my $debit (@$debits) {
166 # revert to the original estimated amount re-encumber
167 $debit->encumbrance('t');
168 $debit->amount($lineitem->estimated_unit_price());
169 $e->update_acq_fund_debit($debit) or return $e->die_event;
170 update_copy_cost($e, $debit) or return $e->die_event; # clear the cost
176 sub update_entry_debits {
179 my $debits = find_entry_debits($e, $entry, 't');
180 return undef unless @$debits;
182 if($entry->phys_item_count > @$debits) {
184 # We can't invoice for more items than we have debits for
185 return OpenILS::Event->new(
186 'ACQ_INVOICE_ENTRY_COUNT_EXCEEDS_DEBITS',
187 payload => {entry => $entry->id});
190 for my $debit (@$debits) {
191 my $amount = entry_amount_per_item($entry);
192 $debit->amount($amount);
193 $debit->encumbrance('f');
194 $e->update_acq_fund_debit($debit) or return $e->die_event;
196 # TODO: this does not reflect ancillary charges, like taxes, etc.
197 # We may need a way to indicate whether the amount attached to an
198 # invoice_item should be prorated and included in the copy cost.
199 # Note that acq.invoice_item_type.prorate does not necessarily
200 # mean a charge should be included in the copy price, only that
201 # it should spread accross funds.
202 update_copy_cost($e, $debit, $amount) or return $e->die_event;
208 # update the linked copy to reflect the amount paid for the item
209 # returns true on success, false on error
210 sub update_copy_cost {
211 my ($e, $debit, $amount) = @_;
213 my $lid = $e->search_acq_lineitem_detail([
214 {fund_debit => $debit->id},
215 {flesh => 1, flesh_fields => {acqlid => ['eg_copy_id']}}
218 if($lid and my $copy = $lid->eg_copy_id) {
219 defined $amount and $copy->cost($amount) or $copy->clear_cost;
220 $copy->editor($e->requestor->id);
221 $copy->edit_date('now');
222 $e->update_asset_copy($copy) or return 0;
229 sub entry_amount_per_item {
231 return $entry->amount_paid if $U->is_true($entry->billed_per_item);
232 return 0 if $entry->phys_item_count == 0;
233 return $entry->amount_paid / $entry->phys_item_count;
236 sub easy_money { # TODO XXX replace with something from a library
239 my $rounded = int($val * 100) / 100.0;
240 if ($rounded == $val) {
241 return sprintf("%.02f", $val);
243 return sprintf("%g", $val);
247 # 0 on failure (caller should call $e->die_event), array on success
248 sub amounts_spent_per_fund {
249 my ($e, $inv_id) = @_;
251 my $entries = $e->search_acq_invoice_entry({"invoice" => $inv_id}) or
255 foreach my $entry (@$entries) {
256 my $debits = find_entry_debits($e, $entry, "f") or return 0;
258 $totals_by_fund{$_->fund} ||= 0.0;
259 $totals_by_fund{$_->fund} += $_->amount;
264 foreach my $fund_id (keys %totals_by_fund) {
265 my $fund = $e->retrieve_acq_fund($fund_id) or return 0;
267 "fund" => $fund->to_bare_hash,
268 "total" => easy_money($totals_by_fund{$fund_id})
275 # there is no direct link between invoice_entry and fund debits.
276 # when we need to retrieve the related debits, we have to do some searching
277 sub find_entry_debits {
278 my($e, $entry, $encumbrance, $amount) = @_;
281 select => {acqfdeb => ['id']},
289 filter => {id => $entry->id}
297 where => {'+acqfdeb' => {encumbrance => $encumbrance}},
298 order_by => {'acqlid' => ['recv_time']}, # un-received items will sort to the end
299 limit => $entry->phys_item_count
302 $query->{where}->{'+acqfdeb'}->{amount} = $amount if $amount;
304 my $debits = $e->json_query($query);
305 my $debit_ids = [map { $_->{id} } @$debits];
306 return (@$debit_ids) ? $e->search_acq_fund_debit({id => $debit_ids}) : [];
310 __PACKAGE__->register_method(
311 method => 'build_invoice_api',
312 api_name => 'open-ils.acq.invoice.retrieve',
315 desc => q/Creates a new stub invoice/,
317 {desc => 'Authentication token', type => 'string'},
318 {desc => q/Invoice Id/, type => 'number'},
320 return => {desc => 'The new invoice w/ entries and items attached', type => 'object', class => 'acqinv'}
325 sub fetch_invoice_api {
326 my($self, $conn, $auth, $invoice_id, $options) = @_;
328 my $e = new_editor(authtoken=>$auth);
329 return $e->event unless $e->checkauth;
331 my $invoice = fetch_invoice_impl($e, $invoice_id, $options) or
333 return $e->event unless $e->allowed(['VIEW_INVOICE', 'CREATE_INVOICE'], $invoice->receiver);
338 sub fetch_invoice_impl {
339 my ($e, $invoice_id, $options) = @_;
343 my $args = $options->{"no_flesh_misc"} ? $invoice_id : [
348 "acqinv" => ["entries", "items"],
349 "acqii" => ["fund_debit", "purchase_order", "po_item"]
354 return $e->retrieve_acq_invoice($args);
357 __PACKAGE__->register_method(
358 method => 'prorate_invoice',
359 api_name => 'open-ils.acq.invoice.apply_prorate',
362 For all invoice items that have the prorate flag set to true, this will create the necessary
363 additional invoice_item's to prorate the cost across all affected funds by percent spent for each fund.
366 {desc => 'Authentication token', type => 'string'},
367 {desc => q/Invoice Id/, type => 'number'},
369 return => {desc => 'The updated invoice w/ entries and items attached', type => 'object', class => 'acqinv'}
374 sub prorate_invoice {
375 my($self, $conn, $auth, $invoice_id) = @_;
377 my $e = new_editor(xact => 1, authtoken=>$auth);
378 return $e->die_event unless $e->checkauth;
380 my $invoice = fetch_invoice_impl($e, $invoice_id) or return $e->die_event;
381 return $e->die_event unless $e->allowed('CREATE_INVOICE', $invoice->receiver);
384 push(@lid_debits, @{find_entry_debits($e, $_, 'f', entry_amount_per_item($_))}) for @{$invoice->entries};
387 my $total_entry_paid = 0;
388 for my $debit (@lid_debits) {
389 $fund_totals{$debit->fund} = 0 unless $fund_totals{$debit->fund};
390 $fund_totals{$debit->fund} += $debit->amount;
391 $total_entry_paid += $debit->amount;
394 $logger->info("invoice: prorating against invoice amount $total_entry_paid");
396 for my $item (@{$invoice->items}) {
398 next if $item->fund_debit; # item has already been processed
400 # future: cache item types locally
401 my $item_type = $e->retrieve_acq_invoice_item_type($item->inv_item_type) or return $e->die_event;
402 next unless $U->is_true($item_type->prorate);
404 # Prorate charges across applicable funds
405 my $full_item_paid = $item->amount_paid; # total amount paid for this item before splitting
406 my $full_item_cost = $item->cost_billed; # total amount invoiced for this item before splitting
410 my $total_debited = 0;
411 my $total_costed = 0;
413 for my $fund_id (keys %fund_totals) {
415 my $spent_for_fund = $fund_totals{$fund_id};
416 next unless $spent_for_fund > 0;
418 my $prorated_amount = ($spent_for_fund / $total_entry_paid) * $full_item_paid;
419 my $prorated_cost = ($spent_for_fund / $total_entry_paid) * $full_item_cost;
420 $logger->info("invoice: attaching prorated amount $prorated_amount to fund $fund_id for invoice $invoice_id");
423 if($first_round and $item->po_item) {
424 # if this item is the result of a PO item, repurpose the original debit
425 # for the first chunk of the prorated amount
426 $debit = $e->retrieve_acq_fund_debit($item->po_item->fund_debit);
428 $debit = Fieldmapper::acq::fund_debit->new;
432 $debit->fund($fund_id);
433 $debit->amount($prorated_amount);
434 $debit->origin_amount($prorated_amount);
435 $debit->origin_currency_type($e->retrieve_acq_fund($fund_id)->currency_type); # future: cache funds locally
436 $debit->encumbrance('f');
437 $debit->debit_type('prorated_charge');
440 $e->create_acq_fund_debit($debit) or return $e->die_event;
442 $e->update_acq_fund_debit($debit) or return $e->die_event;
445 $total_debited += $prorated_amount;
446 $total_costed += $prorated_cost;
447 $largest_debit = $debit if !$largest_debit or $prorated_amount > $largest_debit->amount;
451 # re-purpose the original invoice_item for the first prorated amount
452 $item->fund($fund_id);
453 $item->fund_debit($debit->id);
454 $item->amount_paid($prorated_amount);
455 $item->cost_billed($prorated_cost);
456 $e->update_acq_invoice_item($item) or return $e->die_event;
457 $largest_item = $item if !$largest_item or $prorated_amount > $largest_item->amount_paid;
461 # for subsequent prorated amounts, create a new invoice_item
462 my $new_item = $item->clone;
464 $new_item->fund($fund_id);
465 $new_item->fund_debit($debit->id);
466 $new_item->amount_paid($prorated_amount);
467 $new_item->cost_billed($prorated_cost);
468 $e->create_acq_invoice_item($new_item) or return $e->die_event;
469 $largest_item = $new_item if !$largest_item or $prorated_amount > $largest_item->amount_paid;
475 # make sure the percentages didn't leave a small sliver of money over/under-debited
476 # if so, tweak the largest debit to smooth out the difference
477 if($total_debited != $full_item_paid or $total_costed != $full_item_cost) {
479 my $paid_diff = $full_item_paid - $total_debited;
480 my $cost_diff = $full_item_cost - $total_debited;
481 $logger->info("invoice: repairing prorate descrepency of paid:$paid_diff and cost:$cost_diff");
482 my $new_paid = $largest_item->amount + $paid_diff;
483 my $new_cost = $largest_item->cost_billed + $cost_diff;
485 $largest_debit = $e->retrieve_acq_fund_debit($largest_debit->id); # get latest copy
486 $largest_debit->amount($new_paid);
487 $e->update_acq_fund_debit($largest_debit) or return $e->die_event;
489 $largest_item = $e->retrieve_acq_invoice_item($largest_item->id); # get latest copy
490 $largest_item->amount_paid($new_paid);
491 $largest_item->cost_billed($new_cost);
493 $e->update_acq_invoice_item($largest_item) or return $e->die_event;
497 $invoice = fetch_invoice_impl($e, $invoice_id);
504 __PACKAGE__->register_method(
505 method => "print_html_invoice",
506 api_name => "open-ils.acq.invoice.print.html",
509 desc => "Retrieve printable HTML vouchers for each given invoice",
511 {desc => "Authentication token", type => "string"},
512 {desc => "Invoice ID or a list of them", type => "mixed"},
515 desc => q{One A/T event containing a printable HTML voucher for
517 type => "object", class => "atev"}
522 sub print_html_invoice {
523 my ($self, $conn, $auth, $id_list) = @_;
525 my $e = new_editor("authtoken" => $auth);
526 return $e->die_event unless $e->checkauth;
528 $id_list = [$id_list] unless ref $id_list;
530 my $invoices = $e->search_acq_invoice({"id" => $id_list}) or
531 return $e->die_event;
533 foreach my $invoice (@$invoices) {
534 return $e->die_event unless
535 $e->allowed("VIEW_INVOICE", $invoice->receiver);
537 my $amounts = amounts_spent_per_fund($e, $invoice->id) or
538 return $e->die_event;
541 $U->fire_object_event(
542 undef, "format.acqinv.html", $invoice, $invoice->receiver,
543 "print-on-demand", $amounts