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

feat: add email validation #2431

Merged
merged 2 commits into from
Aug 19, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions app/services/customers/create_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@ def create_from_api(organization:, params:)
new_customer = customer.new_record?
shipping_address = params[:shipping_address] ||= {}

unless valid_email?(params[:email])
return result.single_validation_failure!(
field: :email,
error_code: 'invalid_format'
)
end

unless valid_metadata_count?(metadata: params[:metadata])
return result.single_validation_failure!(
field: :metadata,
Expand Down Expand Up @@ -187,6 +194,13 @@ def create(**args)

private

def valid_email?(email)
return true if email.nil?

email_regexp = /\A[^@\s]+@[^@\s]+\z/
email_regexp.match?(email).present?
end

def valid_metadata_count?(metadata:)
return true if metadata.blank?
return true if metadata.count <= ::Metadata::CustomerMetadata::COUNT_PER_CUSTOMER
Expand Down
37 changes: 37 additions & 0 deletions spec/services/customers/create_service_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,43 @@
)
end

context 'with invalid email' do
let(:create_args) do
{
external_id:,
name: 'Foo Bar',
currency: 'EUR',
email: '@missingusername.com',
tax_identification_number: '123456789',
billing_configuration: {
document_locale: 'fr'
},
shipping_address: {
address_line1: 'line1',
address_line2: 'line2',
city: 'Paris',
zipcode: '123456',
state: 'foobar',
country: 'FR'
}
}
end

it 'fails to create customer with wrong email' do
result = customers_service.create_from_api(
organization:,
params: create_args
)

aggregate_failures do
expect(result).not_to be_success
expect(result.error).to be_a(BaseService::ValidationFailure)
expect(result.error.messages.keys).to include(:email)
expect(result.error.messages[:email]).to include('invalid_format')
end
end
end

context 'with external_id already used by a deleted customer' do
it 'creates a customer with the same external_id' do
create(:customer, :deleted, organization:, external_id:)
Expand Down