1

我已经为我的业务(无线 ISP)编写了一个自定义计费系统的大部分功能部分,但其中的一些内容让我自己感到困惑。

这是基本概述:它是我的客户的定期计费系统,每月自动生成并向每个客户发送发票。但是,我需要允许支票/现金支付,因为我与当地客户打交道,并且还需要允许预付款,所以我不能只使用 Stripe 的定期账单。从本质上讲,付款与发票没有直接关联,以允许这些类型的付款。

模型/发票.rb

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

模型/付款.rb

class Payment < ActiveRecord::Base
  belongs_to :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/.modules 模块中。

这是我迄今为止在models/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

关于用什么填写伪代码有什么建议吗?我对任何级别的重构持开放态度,所以如果您能想出更好的方法来处理这个问题,请告诉我!

4

1 回答 1

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
于 2012-04-20T04:16:33.430 回答