Skip to content

Commit

Permalink
Merge pull request #491 from 3scale/fix/negative-invoices
Browse files Browse the repository at this point in the history
[billing] Cancel non-positive invoices on charge
  • Loading branch information
guicassolato committed Jan 10, 2019
2 parents 62b0973 + d208420 commit 9167428
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
7 changes: 3 additions & 4 deletions app/models/invoice.rb
Expand Up @@ -429,6 +429,7 @@ def charge!(automatic = true)

unless chargeable?
logger.info "Not charging invoice ID #{self.id} (#{reason_cannot_charge})"
cancel! unless positive?
return
end

Expand Down Expand Up @@ -501,10 +502,8 @@ def not_paid?
CONDITIONS_TO_CHARGE = %i[not_paid provider_present provider_payment_gateway_configured positive buyer_account_paying_monthly].freeze

def reason_cannot_charge
CONDITIONS_TO_CHARGE.each do |condition_method|
return I18n.t(condition_method, scope: %i[invoices reasons_cannot_charge]) unless method("#{condition_method}?").call
end
nil
reason = CONDITIONS_TO_CHARGE.find { |condition| !method("#{condition}?").call }
I18n.t(reason, scope: %i[invoices reasons_cannot_charge]) if reason
end

def chargeable?
Expand Down
7 changes: 7 additions & 0 deletions test/unit/invoice_test.rb
Expand Up @@ -314,6 +314,13 @@ def build_invoice(attributes = {})
assert build_invoice.chargeable?
end

test 'charge! should cancel the invoice if negative' do
@invoice.update_attribute(:state, 'pending')
@invoice.stubs(:cost).returns(-100.0.to_has_money('EUR'))
refute @invoice.charge!
assert_equal 'cancelled', @invoice.state
end

test 'charge! should raise if cancelled or paid' do
@invoice.cancel!
assert_raises(Invoice::InvalidInvoiceStateException) { @invoice.charge! }
Expand Down

0 comments on commit 9167428

Please sign in to comment.