Skip to content

Commit

Permalink
Add resilience against credit notes being created manually for progre…
Browse files Browse the repository at this point in the history
…ssive billing invoices
  • Loading branch information
nudded committed Dec 5, 2024
1 parent 89ad7de commit 3f37697
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
4 changes: 2 additions & 2 deletions app/services/credit_notes/validate_item_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ def valid_fee?
false
end

# NOTE: Check if item amount is positive
# NOTE: Check if item amount is not negative
def valid_item_amount?
return true if item.amount_cents.positive?
return true unless item.amount_cents.negative?

add_error(field: :amount_cents, error_code: 'invalid_value')
end
Expand Down
2 changes: 1 addition & 1 deletion app/services/credits/progressive_billing_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def call

total_charges_amount = invoice.fees.charge.where(subscription: subscription).sum(:amount_cents)

amount_to_credit = progressive_billing_invoice.fees_amount_cents
amount_to_credit = progressive_billed_result.amount_to_credit

if amount_to_credit > total_charges_amount
CreditNotes::CreateFromProgressiveBillingInvoice.call(
Expand Down
12 changes: 11 additions & 1 deletion app/services/subscriptions/progressive_billed_amount.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,18 @@ def call
.order("invoices.issuing_date" => :desc, "invoices.created_at" => :desc).first

return result unless invoice_subscription
result.progressive_billing_invoice = invoice_subscription.invoice
invoice = invoice_subscription.invoice
result.progressive_billing_invoice = invoice
result.progressive_billed_amount = result.progressive_billing_invoice.fees_amount_cents
result.to_credit_amount = invoice.fees_amount_cents

if invoice.progressive_billing_credits.exists? || invoice.credit_notes.available.exists?
result.to_credit_amount -= invoice.progressive_billing_credits.sum(:amount_cents)
result.to_credit_amount -= invoice.credit_notes.available.sum(:credit_amount_cents)

# if for some reason this goes below zero, it should be zero.
result.to_credit_amount = 0 if result.credit_amount.negative?
end

result
end
Expand Down

0 comments on commit 3f37697

Please sign in to comment.