Make customer's address writable on API

This commit is contained in:
Maikel Linke
2022-03-24 17:04:36 +11:00
parent 51420934f3
commit d789fb32e9
4 changed files with 81 additions and 1 deletions

View File

@@ -73,13 +73,55 @@ module Api
attributes = params.require(:customer).permit(
:email, :enterprise_id,
:code, :first_name, :last_name,
:billing_address, shipping_address: [
:phone, :latitude, :longitude,
:first_name, :last_name,
:street_address_1, :street_address_2,
:postal_code, :locality, :region, :country,
]
).to_h
attributes.merge!(tag_list: params[:tags]) if params.key?(:tags)
transform_address!(attributes, :billing_address, :bill_address)
transform_address!(attributes, :shipping_address, :ship_address)
attributes
end
def transform_address!(attributes, from, to)
return unless attributes.key?(from)
address = attributes.delete(from)
if address.nil?
attributes[to] = nil
return
end
address.transform_keys! do |key|
{
phone: :phone, latitude: :latitude, longitude: :longitude,
first_name: :firstname, last_name: :lastname,
street_address_1: :address1, street_address_2: :address2,
postal_code: :zipcode,
locality: :city,
region: :state_name,
country: :country,
}.with_indifferent_access[key]
end
if address[:state_name].present?
address[:state] = Spree::State.find_by(name: address[:state_name])
end
if address[:country].present?
address[:country] = Spree::Country.find_by(name: address[:country])
end
attributes["#{to}_attributes"] = address
end
def editable_enterprises
OpenFoodNetwork::Permissions.new(current_api_user).editable_enterprises.select(:id)
end

View File

@@ -55,7 +55,6 @@ class CustomerSchema < JsonApiSchema
:id,
:allow_charges,
:terms_and_conditions_accepted_at,
:billing_address, :shipping_address,
)
end

View File

@@ -148,6 +148,7 @@ describe "Customers", type: :request do
email: "alice@example.com",
enterprise_id: enterprise1.id,
tags: ["staff", "discount"],
shipping_address: CustomerSchema.address_example
)
end
end

View File

@@ -350,6 +350,25 @@ paths:
example:
- staff
- discount
billing_address:
type: object
nullable: true
example:
shipping_address:
type: object
nullable: true
example:
phone: 0404 333 222 111
latitude: -37.8173751
longitude: 144.964803195704
first_name: Alice
last_name: Springs
street_address_1: 1 Flinders Street
street_address_2: ''
postal_code: '1234'
locality: Melbourne
region: Victoria
country: Australia
required:
- enterprise_id
- email
@@ -435,6 +454,25 @@ paths:
example:
- staff
- discount
billing_address:
type: object
nullable: true
example:
shipping_address:
type: object
nullable: true
example:
phone: 0404 333 222 111
latitude: -37.8173751
longitude: 144.964803195704
first_name: Alice
last_name: Springs
street_address_1: 1 Flinders Street
street_address_2: ''
postal_code: '1234'
locality: Melbourne
region: Victoria
country: Australia
required:
- enterprise_id
- email