在rails收费系统中将支付应用到发票

问题描述:

我已经将大部分功能部件写入了我的业务(无线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 

在与伪什么来填充任何建议?我可以接受任何重构级别,所以请让我知道,如果你能想出一个更好的方法来处理这个问题!

这里是我会做什么(可能需要在付款和发票类的一些辅助方法):

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