Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Simplify serializers and re-use existing ones
Damian Legawiecddf3ef7bf778
diff --git a/packages/sdk/src/types/generated/StoreCountry.ts b/packages/sdk/src/types/generated/StoreCountry.tsindex f1ad7129be..cd6426aa7c 100644--- a/packages/sdk/src/types/generated/StoreCountry.ts+++ b/packages/sdk/src/types/generated/StoreCountry.ts@@ -1,4 +1,4 @@-// Typelizer digest 79a79179390a45b7da4d55fd1026b998+// Typelizer digest 4545e257718aff2ed7c320bd335463d8//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {StoreState} from '@/types'@@ -9,10 +9,8 @@ type StoreCountry = {name: string;states_required: boolean;zipcode_required: boolean;- currency: string | null;- default_locale: string | null;- supported_locales: Array<string>;states?: Array<StoreState>;+ market?: unknown;}export default StoreCountry;diff --git a/packages/sdk/src/types/generated/StoreMarket.ts b/packages/sdk/src/types/generated/StoreMarket.tsnew file mode 100644index 0000000000..10cfcae982--- /dev/null+++ b/packages/sdk/src/types/generated/StoreMarket.ts@@ -0,0 +1,17 @@+// Typelizer digest 20bd4bc243bf73ba027fb4c29977903a+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.+import type {StoreCountry} from '@/types'++type StoreMarket = {+ id: string;+ name: string;+ currency: string;+ default_locale: string;+ tax_inclusive: boolean;+ default: boolean;+ supported_locales: Array<string>;+ countries?: Array<StoreCountry>;+}++export default StoreMarket;diff --git a/packages/sdk/src/types/generated/index.ts b/packages/sdk/src/types/generated/index.tsindex eab0e8cee1..a4b58ed5b2 100644--- a/packages/sdk/src/types/generated/index.ts+++ b/packages/sdk/src/types/generated/index.ts@@ -1,4 +1,4 @@-// Typelizer digest ba113ecbc539cf6c1d714f86a1aff20a+// Typelizer digest 38722111a0f5aebd15b5d766b592482e//// DO NOT MODIFY: This file was automatically generated by Typelizer.export type { default as StoreAddress } from './StoreAddress'@@ -29,6 +29,7 @@ export type { default as StoreImport } from './StoreImport'export type { default as StoreInvitation } from './StoreInvitation'export type { default as StoreLineItem } from './StoreLineItem'export type { default as StoreLocale } from './StoreLocale'+export type { default as StoreMarket } from './StoreMarket'export type { default as StoreMetafield } from './StoreMetafield'export type { default as StoreNewsletterSubscriber } from './StoreNewsletterSubscriber'export type { default as StoreOptionType } from './StoreOptionType'diff --git a/packages/sdk/src/zod/generated/StoreAddress.ts b/packages/sdk/src/zod/generated/StoreAddress.tsindex fb327c9111..19b25ec5b9 100644--- a/packages/sdk/src/zod/generated/StoreAddress.ts+++ b/packages/sdk/src/zod/generated/StoreAddress.ts@@ -16,8 +16,8 @@ export const StoreAddressSchema = z.object({country_iso: z.string(),state_text: z.string().nullable(),state_abbr: z.string().nullable(),- state_name: z.string().nullable(),quick_checkout: z.boolean(),+ state_name: z.string().nullable(),});export type StoreAddress = z.infer<typeof StoreAddressSchema>;diff --git a/packages/sdk/src/zod/generated/StoreCountry.ts b/packages/sdk/src/zod/generated/StoreCountry.tsindex 6fa13a12d4..9f985f15e2 100644--- a/packages/sdk/src/zod/generated/StoreCountry.ts+++ b/packages/sdk/src/zod/generated/StoreCountry.ts@@ -8,10 +8,8 @@ export const StoreCountrySchema = z.object({name: z.string(),states_required: z.boolean(),zipcode_required: z.boolean(),- currency: z.string().nullable(),- default_locale: z.string().nullable(),- supported_locales: z.array(z.string()),states: z.array(StoreStateSchema).optional(),+ market: z.any().optional(),});export type StoreCountry = z.infer<typeof StoreCountrySchema>;diff --git a/packages/sdk/src/zod/generated/StoreMarket.ts b/packages/sdk/src/zod/generated/StoreMarket.tsnew file mode 100644index 0000000000..6691546140--- /dev/null+++ b/packages/sdk/src/zod/generated/StoreMarket.ts@@ -0,0 +1,16 @@+// This file is auto-generated. Do not edit directly.+import { z } from 'zod';+import { StoreCountrySchema } from './StoreCountry';++export const StoreMarketSchema = z.object({+ id: z.string(),+ name: z.string(),+ currency: z.string(),+ default_locale: z.string(),+ tax_inclusive: z.boolean(),+ default: z.boolean(),+ supported_locales: z.array(z.string()),+ countries: z.array(StoreCountrySchema).optional(),+});++export type StoreMarket = z.infer<typeof StoreMarketSchema>;diff --git a/packages/sdk/src/zod/generated/index.ts b/packages/sdk/src/zod/generated/index.tsindex 28fb0237dd..3daecb13a3 100644--- a/packages/sdk/src/zod/generated/index.ts+++ b/packages/sdk/src/zod/generated/index.ts@@ -27,6 +27,7 @@ export { StoreImportRowSchema, type StoreImportRow } from './StoreImportRow';export { StoreInvitationSchema, type StoreInvitation } from './StoreInvitation';export { StoreLineItemSchema, type StoreLineItem } from './StoreLineItem';export { StoreLocaleSchema, type StoreLocale } from './StoreLocale';+export { StoreMarketSchema, type StoreMarket } from './StoreMarket';export { StoreMetafieldSchema, type StoreMetafield } from './StoreMetafield';export { StoreNewsletterSubscriberSchema, type StoreNewsletterSubscriber } from './StoreNewsletterSubscriber';export { StoreOptionTypeSchema, type StoreOptionType } from './StoreOptionType';diff --git a/spree/api/app/controllers/spree/api/v3/store/markets/countries_controller.rb b/spree/api/app/controllers/spree/api/v3/store/markets/countries_controller.rbindex 5f473b5272..cbdc054097 100644--- a/spree/api/app/controllers/spree/api/v3/store/markets/countries_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/markets/countries_controller.rb@@ -29,7 +29,7 @@ module Spreeenddef serialize_country(country)- Spree.api.market_country_serializer.new(country, params: serializer_params).to_h+ Spree.api.country_serializer.new(country, params: serializer_params).to_hendendenddiff --git a/spree/api/app/serializers/spree/api/v3/country_serializer.rb b/spree/api/app/serializers/spree/api/v3/country_serializer.rbindex e9eda9bb17..f41820acad 100644--- a/spree/api/app/serializers/spree/api/v3/country_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/country_serializer.rb@@ -5,41 +5,19 @@ module Spreeinclude Alba::Resourceinclude Typelizer::DSL- # ISO 3166-1 codes - iso is the identifier, no redundant id fieldtypelize iso: :string, iso3: :string, name: :string,- states_required: :boolean, zipcode_required: :boolean,- currency: [:string, nullable: true],- default_locale: [:string, nullable: true],- supported_locales: [:string, multi: true],- tax_inclusive: :boolean,- market: [:object, nullable: true, properties: { id: :string, name: :string }]+ states_required: :boolean, zipcode_required: :booleanattributes :iso, :iso3, :name, :states_required, :zipcode_required- attribute :currency do |country|- country.market_currency- end-- attribute :default_locale do |country|- country.market_locale- end-- attribute :supported_locales do |country|- country.market_supported_locales- end-- attribute :tax_inclusive do |country|- country.current_market&.tax_inclusive || false- end-- attribute :market do |country|- m = country.current_market- m ? { id: m.prefixed_id, name: m.name } : nil- end-many :states,resource: Spree.api.state_serializer,if: proc { params[:includes]&.include?('states') }++ attribute :market, if: proc { params[:includes]&.include?('market') } do |country|+ m = country.current_market+ m ? Spree.api.market_serializer.new(m, params: params).to_h : nil+ endendendenddiff --git a/spree/api/app/serializers/spree/api/v3/market_country_serializer.rb b/spree/api/app/serializers/spree/api/v3/market_country_serializer.rbdeleted file mode 100644index 7f6c45e421..0000000000--- a/spree/api/app/serializers/spree/api/v3/market_country_serializer.rb+++ /dev/null@@ -1,21 +0,0 @@-module Spree- module Api- module V3- # Lightweight country serializer for use when nested inside MarketSerializer.- # Omits market-derived fields (currency, locale) since the parent market already has them.- class MarketCountrySerializer- include Alba::Resource- include Typelizer::DSL-- typelize iso: :string, iso3: :string, name: :string,- states_required: :boolean, zipcode_required: :boolean-- attributes :iso, :iso3, :name, :states_required, :zipcode_required-- many :states,- resource: Spree.api.state_serializer,- if: proc { params[:includes]&.include?('states') }- end- end- end-enddiff --git a/spree/api/app/serializers/spree/api/v3/market_serializer.rb b/spree/api/app/serializers/spree/api/v3/market_serializer.rbindex da1215dc19..a6fc96f320 100644--- a/spree/api/app/serializers/spree/api/v3/market_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/market_serializer.rb@@ -8,14 +8,14 @@ module Spreetax_inclusive: :boolean,default: :boolean- attributes :id, :name, :currency, :default_locale, :tax_inclusive, :default+ attributes :name, :currency, :default_locale, :tax_inclusive, :defaultattribute :supported_locales do |market|market.supported_locales_listendmany :countries,- resource: Spree.api.market_country_serializer,+ resource: Spree.api.country_serializer,if: proc { include?(:countries) }endenddiff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rbindex e23636f9a3..bfb7f325ca 100644--- a/spree/api/lib/spree/api/dependencies.rb+++ b/spree/api/lib/spree/api/dependencies.rb@@ -108,7 +108,6 @@ module Spreecustomer_serializer: 'Spree::Api::V3::CustomerSerializer',country_serializer: 'Spree::Api::V3::CountrySerializer',market_serializer: 'Spree::Api::V3::MarketSerializer',- market_country_serializer: 'Spree::Api::V3::MarketCountrySerializer',state_serializer: 'Spree::Api::V3::StateSerializer',store_serializer: 'Spree::Api::V3::StoreSerializer',wishlist_serializer: 'Spree::Api::V3::WishlistSerializer',diff --git a/spree/api/spec/integration/spree/api/v3/store/countries_spec.rb b/spree/api/spec/integration/spree/api/v3/store/countries_spec.rbindex f4d4143e53..61c9729d12 100644--- a/spree/api/spec/integration/spree/api/v3/store/countries_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/store/countries_spec.rb@@ -18,7 +18,7 @@ RSpec.describe 'Countries API', type: :request, swagger_doc: 'api-reference/stortags 'Internationalization'produces 'application/json'security [api_key: []]- description 'Returns countries available in the store with their currency and locale (derived from markets)'+ description 'Returns countries available in the store. Use ?include=market to include market details (currency, locale, tax_inclusive).'sdk_example <<~JSconst countries = await client.store.countries.list()@@ -45,15 +45,10 @@ RSpec.describe 'Countries API', type: :request, swagger_doc: 'api-reference/storus_country = data['data'].find { |c| c['iso'] == 'US' }expect(us_country).to be_presentexpect(us_country['name']).to be_present- expect(us_country['currency']).to eq('USD')- expect(us_country['default_locale']).to eq('en')- expect(us_country['supported_locales']).to match_array(['en', 'es'])+ expect(us_country['iso3']).to be_presentde_country = data['data'].find { |c| c['iso'] == 'DE' }expect(de_country).to be_present- expect(de_country['currency']).to eq('EUR')- expect(de_country['default_locale']).to eq('de')- expect(de_country['supported_locales']).to match_array(['de', 'en'])endend@@ -72,7 +67,7 @@ RSpec.describe 'Countries API', type: :request, swagger_doc: 'api-reference/stortags 'Internationalization'produces 'application/json'security [api_key: []]- description 'Returns a single country by ISO code with currency and locale. Supports ?include=states for address forms.'+ description 'Returns a single country by ISO code. Supports ?include=states for address forms and ?include=market for market details.'sdk_example <<~JSconst country = await client.store.countries.get('US')@@ -92,30 +87,14 @@ RSpec.describe 'Countries API', type: :request, swagger_doc: 'api-reference/storiso3: { type: :string },name: { type: :string },states_required: { type: :boolean },- zipcode_required: { type: :boolean },- currency: { type: :string, nullable: true },- default_locale: { type: :string, nullable: true },- supported_locales: { type: :array, items: { type: :string } },- states: {- type: :array,- items: {- type: :object,- properties: {- abbr: { type: :string },- name: { type: :string }- },- required: %w[abbr name]- }- }+ zipcode_required: { type: :boolean }},required: %w[iso iso3 name states_required zipcode_required]run_test! do |response|data = JSON.parse(response.body)expect(data['iso']).to eq('US')- expect(data['currency']).to eq('USD')- expect(data['default_locale']).to eq('en')- expect(data['supported_locales']).to match_array(['en', 'es'])+ expect(data['name']).to be_presentendend@@ -130,7 +109,7 @@ RSpec.describe 'Countries API', type: :request, swagger_doc: 'api-reference/storendend- # Non-swagger test for ?include=states functionality+ # Non-swagger tests for ?include functionalitydescribe 'GET /api/v3/store/countries/:iso?include=states' doit 'includes states when requested' doget "/api/v3/store/countries/US?include=states", headers: { 'x-spree-api-key' => api_key.token }@@ -142,4 +121,19 @@ RSpec.describe 'Countries API', type: :request, swagger_doc: 'api-reference/storexpect(state_abbrs).to match_array(['CA', 'NY'])endend++ describe 'GET /api/v3/store/countries/:iso?include=market' do+ it 'includes market details when requested' do+ get "/api/v3/store/countries/US?include=market", headers: { 'x-spree-api-key' => api_key.token }++ expect(response).to have_http_status(:ok)+ data = JSON.parse(response.body)+ expect(data['market']).to be_present+ expect(data['market']['name']).to eq('North America')+ expect(data['market']['currency']).to eq('USD')+ expect(data['market']['default_locale']).to eq('en')+ expect(data['market']['supported_locales']).to match_array(['en', 'es'])+ expect(data['market']['tax_inclusive']).to eq(false)+ end+ endenddiff --git a/spree/api/spec/integration/spree/api/v3/store/markets_spec.rb b/spree/api/spec/integration/spree/api/v3/store/markets_spec.rbindex 3050ef7af4..9eb5d46198 100644--- a/spree/api/spec/integration/spree/api/v3/store/markets_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/store/markets_spec.rb@@ -13,37 +13,6 @@ RSpec.describe 'Markets API', type: :request, swagger_doc: 'api-reference/store.let!(:na_market) { create(:market, :default, name: 'North America', store: store, countries: [usa], currency: 'USD', default_locale: 'en', supported_locales: 'en,es') }let!(:eu_market) { create(:market, name: 'Europe', store: store, countries: [germany, france], currency: 'EUR', default_locale: 'de', supported_locales: 'de,en,fr', tax_inclusive: true) }- let(:market_country_schema) do- {- type: :object,- properties: {- iso: { type: :string },- iso3: { type: :string },- name: { type: :string },- states_required: { type: :boolean },- zipcode_required: { type: :boolean }- },- required: %w[iso iso3 name states_required zipcode_required]- }- end-- let(:market_schema) do- {- type: :object,- properties: {- id: { type: :string },- name: { type: :string },- currency: { type: :string },- default_locale: { type: :string },- supported_locales: { type: :array, items: { type: :string } },- tax_inclusive: { type: :boolean },- default: { type: :boolean },- countries: { type: :array, items: market_country_schema }- },- required: %w[id name currency default_locale supported_locales tax_inclusive default countries]- }- end-path '/api/v3/store/markets' doget 'List markets' dotags 'Markets'@@ -201,3 +170,60 @@ RSpec.describe 'Markets API', type: :request, swagger_doc: 'api-reference/store.schema type: :object,properties: {+ data: { type: :array }+ },+ required: ['data']++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['data'].size).to eq(2)+ isos = data['data'].map { |c| c['iso'] }+ expect(isos).to match_array(['DE', 'FR'])+ end+ end+ end+ end++ path '/api/v3/store/markets/{market_id}/countries/{id}' do+ get 'Get a country in a market' do+ tags 'Markets'+ produces 'application/json'+ security [api_key: []]+ description 'Returns a single country by ISO code within a market. Supports ?include=states for address forms.'++ sdk_example <<~JS+ const country = await client.store.markets.countries.get('mkt_xxx', 'DE')+ JS++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :market_id, in: :path, type: :string, required: true,+ description: 'Market prefixed ID'+ parameter name: :id, in: :path, type: :string, required: true,+ description: 'Country ISO 3166-1 alpha-2 code (e.g., "DE")'++ response '200', 'country found' do+ let(:'x-spree-api-key') { api_key.token }+ let(:market_id) { na_market.prefixed_id }+ let(:id) { 'US' }++ schema type: :object++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['iso']).to eq('US')+ expect(data['states_required']).to eq(true)+ end+ end++ response '404', 'country not in market' do+ let(:'x-spree-api-key') { api_key.token }+ let(:market_id) { eu_market.prefixed_id }+ let(:id) { 'US' }++ schema '$ref' => '#/components/schemas/ErrorResponse'++ run_test!+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/country.rb b/spree/core/app/models/spree/country.rbindex 75dfc49886..90d9ec77a3 100644--- a/spree/core/app/models/spree/country.rb+++ b/spree/core/app/models/spree/country.rb@@ -38,29 +38,8 @@ module Spreeiso.upcase.chars.map { |c| (c.ord + 127397).chr(Encoding::UTF_8) }.joinend- # Returns the currency for this country from its market in the current store.- # Looks up which market contains this country and returns that market's currency.- #- # @return [String, nil] currency code (e.g., 'USD', 'EUR') or nil if no market found- def market_currency- current_market&.currency- end-- # Returns the default locale for this country from its market in the current store.- # Looks up which market contains this country and returns that market's default locale.- #- # @return [String, nil] locale code (e.g., 'en', 'de') or nil if no market found- def market_locale- current_market&.default_locale- end-- # Returns the supported locales for this country from its market in the current store.- #- # @return [Array<String>] locale codes (e.g., ['en', 'fr']) or empty array if no market found- def market_supported_locales- current_market&.supported_locales_list || []- end-+ # Lookups Market for Country for the current Store+ # @return [Spree::Market, nil]def current_market@current_market ||= Spree::Current.store&.market_for_country(self)enddiff --git a/spree/core/spec/models/spree/country_spec.rb b/spree/core/spec/models/spree/country_spec.rbindex 02be3c24a6..39633eaf19 100644--- a/spree/core/spec/models/spree/country_spec.rb+++ b/spree/core/spec/models/spree/country_spec.rb@@ -30,6 +30,29 @@ describe Spree::Country, type: :model doendend+ describe '#current_market' do+ let!(:market) { create(:market, store: store, countries: [america], currency: 'USD') }++ before do+ allow(Spree::Current).to receive(:store).and_return(store)+ america.instance_variable_set(:@current_market, nil)+ canada.instance_variable_set(:@current_market, nil)+ end++ it 'returns the market for the country in the current store' do+ expect(america.current_market).to eq(market)+ end++ it 'returns nil for a country not in any market' do+ expect(canada.current_market).to be_nil+ end++ it 'returns nil when there is no current store' do+ allow(Spree::Current).to receive(:store).and_return(nil)+ expect(america.current_market).to be_nil+ end+ end+describe '#default?' dobefore doallow_any_instance_of(Spree::Store).to receive(:default).and_return(store)@@ -57,126 +80,4 @@ describe Spree::Country, type: :model doendendend-- describe '#default_currency' do- it 'returns the currency code from ISO3166' do- expect(america.default_currency).to eq('USD')- end-- it 'returns EUR for Germany' do- germany = create(:country, name: 'Germany', iso_name: 'GERMANY', iso: 'DE', iso3: 'DEU', numcode: '276')- expect(germany.default_currency).to eq('EUR')- end-- it 'returns nil for invalid ISO code' do- invalid_country = build(:country, iso: 'XX')- expect(invalid_country.default_currency).to be_nil- end- end-- describe '#default_locale' do- it 'returns the primary language from ISO3166' do- expect(america.default_locale).to eq('en')- end-- it 'returns de for Germany' do- germany = create(:country, name: 'Germany', iso_name: 'GERMANY', iso: 'DE', iso3: 'DEU', numcode: '276')- expect(germany.default_locale).to eq('de')- end-- it 'returns nil for invalid ISO code' do- invalid_country = build(:country, iso: 'XX')- expect(invalid_country.default_locale).to be_nil- end- end-- describe '#market_currency' do- before do- america.remove_instance_variable(:@current_market) if america.instance_variable_defined?(:@current_market)- Spree::Current.store = store- end- after { Spree::Current.reset }-- context 'when country belongs to a market' do- let!(:market) { create(:market, :default, store: store, countries: [america], currency: 'EUR') }-- it 'returns the market currency' do- expect(america.market_currency).to eq('EUR')- end- end-- context 'when country does not belong to any market' do- it 'returns nil' do- expect(canada.market_currency).to be_nil- end- end-- context 'when no current store is set' do- before { Spree::Current.store = nil }-- it 'returns nil' do- expect(america.market_currency).to be_nil- end- end- end-- describe '#market_locale' do- before do- america.remove_instance_variable(:@current_market) if america.instance_variable_defined?(:@current_market)- Spree::Current.store = store- end- after { Spree::Current.reset }-- context 'when country belongs to a market' do- let!(:market) { create(:market, :default, store: store, countries: [america], default_locale: 'de') }-- it 'returns the market default locale' do- expect(america.market_locale).to eq('de')- end- end-- context 'when country does not belong to any market' do- it 'returns nil' do- expect(canada.market_locale).to be_nil- end- end-- context 'when no current store is set' do- before { Spree::Current.store = nil }-- it 'returns nil' do- expect(america.market_locale).to be_nil- end- end- end-- describe '#market_supported_locales' do- before do- america.remove_instance_variable(:@current_market) if america.instance_variable_defined?(:@current_market)- Spree::Current.store = store- end- after { Spree::Current.reset }-- context 'when country belongs to a market' do- let!(:market) { create(:market, :default, store: store, countries: [america], default_locale: 'en', supported_locales: 'en,fr') }-- it 'returns the market supported locales' do- expect(america.market_supported_locales).to match_array(['en', 'fr'])- end- end-- context 'when country does not belong to any market' do- it 'returns an empty array' do- expect(canada.market_supported_locales).to eq([])- end- end-- context 'when no current store is set' do- before { Spree::Current.store = nil }-- it 'returns an empty array' do- expect(america.market_supported_locales).to eq([])- end- end- endend