Skip to content

Commit

Permalink
Chore: add validation on credit note creation and estimate to have it…
Browse files Browse the repository at this point in the history
…ems as an array (#3096)

## Context

When receiving a request to estimate/create a credit note with missing
items, now we simply fail with server error, instead we want to return a
validation error

## Description

Added validation to credit_notes/create_service and
credit_notes/estimate_service to check if the received items is an array
  • Loading branch information
annvelents authored Jan 23, 2025
1 parent b74556d commit 2f9d1a9
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 0 deletions.
2 changes: 2 additions & 0 deletions app/services/credit_notes/create_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@ def issuing_date
end

def create_items
return result.validation_failure!(errors: {items: ['must_be_an_array']}) unless items_attr.is_a?(Array)

items_attr.each do |item_attr|
amount_cents = item_attr[:amount_cents] || 0

Expand Down
2 changes: 2 additions & 0 deletions app/services/credit_notes/estimate_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ def valid_type_or_status?
end

def validate_items
return result.validation_failure!(errors: {items: ['must_be_an_array']}) unless items.is_a?(Array)

items.each do |item_attr|
amount_cents = item_attr[:amount_cents]&.to_i || 0

Expand Down
17 changes: 17 additions & 0 deletions spec/services/credit_notes/create_service_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,23 @@
end
end

context 'when items are missing' do
let(:items) {}

it 'returns a failed result' do
result = create_service.call

expect(result).not_to be_success
expect(result.error).to be_a(BaseService::ValidationFailure)
expect(result.error.messages.keys).to include(:items)
expect(result.error.messages[:items]).to eq(
%w[
must_be_an_array
]
)
end
end

context 'with a refund, a payment and a succeeded invoice' do
let(:payment) { create(:payment, payable: invoice) }

Expand Down
17 changes: 17 additions & 0 deletions spec/services/credit_notes/estimate_service_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,23 @@
end
end

context 'with missing items' do
let(:items) {}

it 'returns a failed result' do
result = estimate_service.call

expect(result).not_to be_success
expect(result.error).to be_a(BaseService::ValidationFailure)
expect(result.error.messages.keys).to include(:items)
expect(result.error.messages[:items]).to eq(
%w[
must_be_an_array
]
)
end
end

context 'when invoice is not found' do
let(:invoice) { nil }
let(:items) { [] }
Expand Down

0 comments on commit 2f9d1a9

Please sign in to comment.