Method: Client#recommend_invoice_assignments_for
- Defined in:
- app/models/client.rb
#recommend_invoice_assignments_for(amount) ⇒ Object
Returns an array of unsaved InvoicePayment objects, with unset payment_ids, and ‘recommended’ amounts. If the provided amount exactly equals an outstanding invoice’s amount, we return a InvoicePayment for the oldest such matching invoice. Otherwise, we start applying the amount to invoices in ascending order by issued_date.
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 |
# File 'app/models/client.rb', line 105 def recommend_invoice_assignments_for(amount) amount = amount.to_money invs = unpaid_invoices( :all, # Using this order forces the closest-amount match to be above anything else, followed by date sorting :order => '(amount_outstanding_in_cents = %d) DESC, issued_on ASC, created_at ASC' % amount.cents ) unassigned_outstanding = invs.inject(Money.new(0)){|total, inv| total + inv.amount_outstanding} invs.collect{ |inv| if amount > 0 and unassigned_outstanding > 0 assignment = (amount >= inv.amount_outstanding) ? inv.amount_outstanding : amount unassigned_outstanding -= assignment amount -= assignment InvoicePayment.new :invoice => inv, :amount => assignment if assignment > 0 end }.compact end |