1

我已經將大部分功能部件寫入了我的業務(無線ISP)的自定義計費系統,但卻讓我自己陷入了一些困境。在rails收費系統中將支付應用到發票

以下是基本概述: 這是我的客戶每月自動生成並向每位客戶發送發票的循環計費系統。不過,我需要支付支票/現金支付,因爲我與當地的客戶打交道,並且還需要預付款,所以我不能僅僅使用像Stripe的經常性結算之類的東西。基本上,支付並不直接與發票相關聯以允許這些類型的支付。

型號/ invoice.rb

class Invoice < ActiveRecord::Base 
    belongs_to :customer 
    has_many :line_items 
    has_many :invoice_payments 
    has_many :payments, through: :invoice_payments 

型號/ payment.rb

class Payment < ActiveRecord::Base 
    belongs_to :customer 

型號/ customer.rb

class Customer < ActiveRecord::Base 
    has_many :subscriptions, dependent: :destroy 
    has_many :services, through: :subscriptions 
    has_many :invoices, :order => 'id DESC' 
    has_many :payments 

我需要一種將所有未付款的付款自動關聯到所有未付款發票的方法。現在我把它作爲def apply_unapplied_payments放在客戶模型上,但可能稍後將它抽象到它自己的lib /模塊中。

這是我在模型迄今所做/ customer.rb

def apply_unapplied_payments 
    unpaid_invoices = invoices.find_by_status("unpaid") 
    unapplied_payments = payments.where("invoice_id is null") 
    unpaid_invoices.each do |invoice| 
    # find the oldest unapplied payment 
    # apply payment to this invoice 
    # if payment > invoice, keep whatever amount is left and move to next invoice 
    # apply leftover amount to invoice, if invoice is still unpaid, move to next unapplied payment 
    end 
    customer.update_balance 
end 

在與僞什麼來填充任何建議?我可以接受任何重構級別,所以請讓我知道,如果你能想出一個更好的方法來處理這個問題!

回答

0

這裏是我會做什麼(可能需要在付款和發票類的一些輔助方法):

def apply_unapplied_payments 
    unpaid_invoices = invoices.find_by_status("unpaid") 
    unapplied_payments = payments.where("invoice_id is null") 
    invoice = unpaid_invoices.shift 
    payment = unapplied_payments.shift 
    while invoice && invoice.remaining_balance > 0 && payment && payment.remaining_credit > 0 
     apply_payment_to_invoice(invoice, payment) 
     invoice = unpaid_invoices.shift if invoice.remaining_balance == 0 
     payment = unapplied_payments.shift if payment.remaining_credit == 0 
    end 
end 
+0

輝煌!我沒有這樣想過,每個循環都陷入了思考。 – gmcintire 2012-04-20 16:25:35