Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[billing] Cancel non-positive invoices on charge #491

Merged
merged 1 commit into from Jan 10, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if not reason? Does it return null.. ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it does

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe it would be clearer with:

return unless (reason = CONDITIONS_TO_CHARGE.find { |condition| !method("#{condition}?").call })
I18n.t(reason, scope: %i[invoices reasons_cannot_charge])

But either way is fine 👍

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't even have to touch this, TBH. Just did to make it shorter. It's Ruby language anyway.

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