Skip to content

Commit

Permalink
fix(wallet): Validate currency (#2999)
Browse files Browse the repository at this point in the history
## Context

This PR is related to 
```
ActiveRecord::NotNullViolation

PG::NotNullViolation: ERROR:  null value in column "balance_currency" of relation "wallets" violates not-null constraint (ActiveRecord::NotNullViolation)
```
The error is raised when creating a wallet with a null currency if the
related customer does not have a currency.

## Description

The PR
- Add a validation on `wallet#currency` making sure it is included in
the accepted currency list.
- Avoid updating the customer currency with a nil value
  • Loading branch information
vincent-pochet authored Dec 23, 2024
1 parent db1da6a commit 274faaa
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
2 changes: 2 additions & 0 deletions app/models/wallet.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

class Wallet < ApplicationRecord
include PaperTrailTraceable
include Currencies

belongs_to :customer, -> { with_discarded }

Expand All @@ -15,6 +16,7 @@ class Wallet < ApplicationRecord
monetize :ongoing_balance_cents, :ongoing_usage_balance_cents, with_model_currency: :balance_currency

validates :rate_amount, numericality: {greater_than: 0}
validates :currency, inclusion: {in: currency_list}

STATUSES = [
:active,
Expand Down
6 changes: 3 additions & 3 deletions app/services/wallets/create_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ def call
wallet = Wallet.new(attributes)

ActiveRecord::Base.transaction do
Customers::UpdateCurrencyService
.call(customer: result.current_customer, currency: params[:currency])
.raise_if_error!
if params[:currency].present?
Customers::UpdateCurrencyService.call!(customer: result.current_customer, currency: params[:currency])
end

wallet.currency = wallet.customer.currency
wallet.save!
Expand Down
20 changes: 20 additions & 0 deletions spec/services/wallets/create_service_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,26 @@
service_result
expect(customer.reload.currency).to eq('EUR')
end

context 'when no currency is provided' do
let(:params) do
{
name: 'New Wallet',
customer:,
organization_id: organization.id,
currency: nil,
rate_amount: '1.00',
expiration_at:,
paid_credits:,
granted_credits:
}
end

it 'returns an error' do
expect(service_result).not_to be_success
expect(service_result.error.messages[:currency]).to eq(['value_is_invalid'])
end
end
end

context 'when wallet have transaction metadata' do
Expand Down

0 comments on commit 274faaa

Please sign in to comment.