【问题标题】:Applying payments to invoices in rails billing system在 Rails 计费系统中将付款应用于发票
【发布时间】:2012-05-01 12:13:03
【问题描述】:

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

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

models/invoice.rb

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

models/payment.rb

class Payment < ActiveRecord::Base
  belongs_to :customer

models/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/ 中自己的模块中。

这是我目前在 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

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

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 billing recurring-billing


    【解决方案1】:

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

    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
    

    【讨论】:

    • 太棒了!我没有那样想过,并且一直在思考 .each 循环。
    猜你喜欢
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    相关资源
    最近更新 更多