From a6a3632b75521acc9660188a07b0f336ae1d7e77 Mon Sep 17 00:00:00 2001 From: brunomiguelpinto Date: Mon, 19 Aug 2024 17:12:11 +0100 Subject: [PATCH] feat: add email validation (#2431) --- app/services/customers/create_service.rb | 14 +++++++ .../services/customers/create_service_spec.rb | 37 +++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/app/services/customers/create_service.rb b/app/services/customers/create_service.rb index 2c0a981a0a3..b66a209b95a 100644 --- a/app/services/customers/create_service.rb +++ b/app/services/customers/create_service.rb @@ -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, @@ -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 diff --git a/spec/services/customers/create_service_spec.rb b/spec/services/customers/create_service_spec.rb index 7b4ad8480aa..3b999fc4353 100644 --- a/spec/services/customers/create_service_spec.rb +++ b/spec/services/customers/create_service_spec.rb @@ -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:)