我已经将大部分功能部件写入了我的业务(无线ISP)的自定义计费系统,但我已经把它自己搞砸了。
以下是基本概述: 它是我的客户的定期计费系统,每月自动生成和发送发票给每个客户。但是,我需要允许支票/现金支付,因为我与本地客户打交道,还需要允许预付款,因此我不能只使用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 :(得分: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