From 3f376971b5837284d63d921d4eb235fa397b1b90 Mon Sep 17 00:00:00 2001 From: Toon Willems Date: Thu, 5 Dec 2024 13:37:24 +0100 Subject: [PATCH] Add resilience against credit notes being created manually for progressive billing invoices --- app/services/credit_notes/validate_item_service.rb | 4 ++-- app/services/credits/progressive_billing_service.rb | 2 +- .../subscriptions/progressive_billed_amount.rb | 12 +++++++++++- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/app/services/credit_notes/validate_item_service.rb b/app/services/credit_notes/validate_item_service.rb index 6d6ec33f108..16c1ab706a7 100644 --- a/app/services/credit_notes/validate_item_service.rb +++ b/app/services/credit_notes/validate_item_service.rb @@ -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 diff --git a/app/services/credits/progressive_billing_service.rb b/app/services/credits/progressive_billing_service.rb index 458ba27bfd2..16db63a6318 100644 --- a/app/services/credits/progressive_billing_service.rb +++ b/app/services/credits/progressive_billing_service.rb @@ -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( diff --git a/app/services/subscriptions/progressive_billed_amount.rb b/app/services/subscriptions/progressive_billed_amount.rb index 299f7f737a8..99408a232a8 100644 --- a/app/services/subscriptions/progressive_billed_amount.rb +++ b/app/services/subscriptions/progressive_billed_amount.rb @@ -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