Skip to content

armgit / spree

Public Imported from GitHub
0

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.

Offer every registered resource when defining a custom field

Damian Legawiecc94aee81c1d5
diff --git a/packages/admin-sdk/examples/custom-field-definitions/resource-types.ts b/packages/admin-sdk/examples/custom-field-definitions/resource-types.ts
new file mode 100644
index 0000000000..e43a234bb1
--- /dev/null
+++ b/packages/admin-sdk/examples/custom-field-definitions/resource-types.ts
@@ -0,0 +1,15 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+// What a definition can be attached to. Comes from the server's registry, so
+// a resource an extension adds shows up here without a client release.
+const { data: resourceTypes } = await client.customFieldDefinitions.resourceTypes()
+
+// endregion:example
+
+export { resourceTypes }
diff --git a/packages/dashboard/src/components/spree/custom-fields/definition-form.tsx b/packages/dashboard/src/components/spree/custom-fields/definition-form.tsx
index 41f41244d7..4d32dc0072 100644
--- a/packages/dashboard/src/components/spree/custom-fields/definition-form.tsx
+++ b/packages/dashboard/src/components/spree/custom-fields/definition-form.tsx
@@ -12,6 +12,7 @@ import {
} from '@spree/dashboard-ui'
import { Controller, type UseFormReturn } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
+import { useCustomFieldResourceTypes } from '../../../hooks/use-custom-field-resource-types'
import {
type CustomFieldDefinitionFormValues,
DEFAULT_RESOURCE_TYPES,
@@ -69,10 +70,15 @@ export function DefinitionFormFields({
label: fieldTypeLabel(value),
}))
- const resourceTypeItems = DEFAULT_RESOURCE_TYPES.map((value) => ({
- value,
- label: resourceTypeLabel(value),
- }))
+ // From the server's registry. `DEFAULT_RESOURCE_TYPES` covers the first
+ // render while that request is in flight, so the select is never empty.
+ const { data: resourceTypesResponse } = useCustomFieldResourceTypes()
+ const resourceTypeItems = resourceTypesResponse
+ ? resourceTypesResponse.data.map(({ resource_type, name }) => ({
+ value: resource_type,
+ label: name,
+ }))
+ : DEFAULT_RESOURCE_TYPES.map((value) => ({ value, label: resourceTypeLabel(value) }))
return (
<div className="flex flex-col gap-4">
diff --git a/packages/dashboard/src/hooks/use-custom-field-resource-types.ts b/packages/dashboard/src/hooks/use-custom-field-resource-types.ts
new file mode 100644
index 0000000000..b1ee7a7cfb
--- /dev/null
+++ b/packages/dashboard/src/hooks/use-custom-field-resource-types.ts
@@ -0,0 +1,17 @@
+import { adminClient, useResourceKey } from '@spree/dashboard-core'
+import { useQuery } from '@tanstack/react-query'
+
+/**
+ * What a custom field definition can be attached to.
+ *
+ * Read from the server's registry rather than a list in the dashboard: an
+ * extension that registers a resource is then offered without a dashboard
+ * release, and a merchant is never shown a type the API would refuse.
+ */
+export function useCustomFieldResourceTypes() {
+ return useQuery({
+ queryKey: useResourceKey('custom-field-definitions', 'resource-types'),
+ queryFn: () => adminClient.customFieldDefinitions.resourceTypes(),
+ staleTime: Infinity,
+ })
+}
diff --git a/spree/api/app/controllers/spree/api/v3/admin/custom_field_definitions_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/custom_field_definitions_controller.rb
index 79524de2db..44ea5f56f8 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/custom_field_definitions_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/custom_field_definitions_controller.rb
@@ -10,6 +10,19 @@ module Spree
class CustomFieldDefinitionsController < ResourceController
scoped_resource :settings
+ # GET /api/v3/admin/custom_field_definitions/resource_types
+ #
+ # What a definition can be attached to, from
+ # `Spree.custom_fields.enabled_resources` — so a resource an
+ # extension registers is offered without the dashboard shipping a
+ # new list, and a merchant is never shown a type the server would
+ # then refuse.
+ def resource_types
+ authorize! :create, model_class
+
+ render json: { data: Spree::CustomFieldDefinition.enabled_resource_types }
+ end
+
protected
def model_class
@@ -25,6 +38,11 @@ module Spree
:resource_type, :storefront_visible,
:searchable, :sortable)
end
+
+ # Pure registry discovery — maps to the read scope.
+ def read_actions
+ super + %w[resource_types]
+ end
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/custom_field_definitions_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/custom_field_definitions_controller_spec.rb
index 6ebfcb488a..e3921665b6 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/custom_field_definitions_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/custom_field_definitions_controller_spec.rb
@@ -210,4 +210,59 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldDefinitionsController, type: :c
end
end
end
+
+ describe 'GET #resource_types' do
+ it 'offers everything the registry allows, not a list the dashboard carries' do
+ get :resource_types, as: :json
+
+ expect(response).to have_http_status(:ok)
+ types = json_response['data']
+ values = types.map { |t| t['resource_type'] }
+
+ # A resource is offered because core registered it — sellers included,
+ # which is what a marketplace needs to ask for a VAT number.
+ expect(values).to include('Spree::Seller', 'Spree::Product', 'Spree::Order')
+ expect(values.size).to be > 6
+ end
+
+ it 'names categories as a merchant does while storing them where they live' do
+ get :resource_types, as: :json
+
+ category = json_response['data'].find { |t| t['resource_type'] == 'Spree::Taxon' }
+
+ # The label follows the class a merchant knows; the value follows where
+ # existing definitions are actually filed.
+ expect(category['name']).to eq('Categories')
+ expect(json_response['data'].map { |t| t['resource_type'] }).not_to include('Spree::Category')
+ end
+
+ it 'accepts the category type it offers, which is stored under the old class name' do
+ get :resource_types, as: :json
+ category = json_response['data'].find { |t| t['name'] == 'Categories' }
+
+ post :create, params: {
+ namespace: 'merch', key: 'aisle', label: 'Aisle',
+ field_type: 'Spree::CustomFields::ShortText',
+ resource_type: category['resource_type']
+ }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['resource_type']).to eq('Spree::Taxon')
+ end
+
+ it 'accepts a type it offered' do
+ get :resource_types, as: :json
+ seller_type = json_response['data'].find { |t| t['resource_type'] == 'Spree::Seller' }
+
+ post :create, params: {
+ namespace: 'compliance', key: 'vat_number', label: 'VAT number',
+ field_type: 'Spree::CustomFields::ShortText',
+ resource_type: seller_type['resource_type']
+ }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['resource_type']).to eq('Spree::Seller')
+ end
+ end
+
end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/custom_field_definitions_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/custom_field_definitions_spec.rb
index 637191430d..e4f773c8e4 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/custom_field_definitions_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/custom_field_definitions_spec.rb
@@ -197,4 +197,52 @@ RSpec.describe 'Admin Custom Field Definitions API', type: :request, swagger_doc
end
end
end
+
+ path '/api/v3/admin/custom_field_definitions/resource_types' do
+ get 'List what custom fields can be attached to' do
+ tags 'Custom Field Definitions'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ The resources a definition can describe, from the server's own
+ registry (`Spree.custom_fields.enabled_resources`).
+
+ Read this rather than carrying a list: a resource an extension
+ registers appears here without a client release, and a `resource_type`
+ that is not listed is refused on create.
+
+ `resource_type` is the value to send; `name` is what a merchant calls
+ it. The two differ where a class has been renamed — categories are
+ stored under `Spree::Taxon` and shown as "Categories" — so send the
+ value back verbatim rather than deriving it from the name.
+ DESC
+ admin_scope :read, :settings
+
+ admin_sdk_example 'custom-field-definitions/resource-types'
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: :Authorization, in: :header, type: :string, required: true
+
+ response '200', 'resource types found' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+
+ schema type: :object,
+ properties: {
+ data: {
+ type: :array,
+ items: {
+ type: :object,
+ properties: {
+ resource_type: { type: :string, example: 'Spree::Seller' },
+ name: { type: :string, example: 'Sellers' }
+ }
+ }
+ }
+ }
+
+ run_test!
+ end
+ end
+ end
+
end
diff --git a/spree/core/app/models/spree/custom_field_definition.rb b/spree/core/app/models/spree/custom_field_definition.rb
index d238f32954..3a4250f947 100644
--- a/spree/core/app/models/spree/custom_field_definition.rb
+++ b/spree/core/app/models/spree/custom_field_definition.rb
@@ -111,6 +111,32 @@ module Spree
self.storefront_visible = value.to_s != 'back_end'
end
+ # What a definition can be attached to: every registered resource, named
+ # as the API names it, so a client renders a picker rather than carrying
+ # its own list that drifts from the registry.
+ #
+ # `Spree::Category` reports itself as `Spree::Taxon`: existing category
+ # definitions are stored under the old class name, and offering the new
+ # one would file a merchant's next definition somewhere the category card
+ # does not read. Drops with the alias in 6.1.
+ #
+ # @return [Array<Hash{Symbol => String}>] `resource_type` + `name`
+ def self.enabled_resource_types
+ # Through `available_resources`, not the registry directly: that is the
+ # accessor the rest of the class reads, so discovery and validation
+ # cannot disagree about what a host app has made available.
+ Array(available_resources).filter_map do |resource|
+ next if resource.nil?
+
+ # The label follows the class a merchant knows; the wire value follows
+ # where the rows are actually stored.
+ name = resource.to_s.demodulize.titleize.pluralize
+ resource_type = resource.to_s == 'Spree::Category' ? 'Spree::Taxon' : resource.to_s
+
+ { resource_type: resource_type, name: name }
+ end.uniq { |entry| entry[:resource_type] }.sort_by { |entry| entry[:name] }
+ end
+
# Returns the full key with namespace
# @return [String] eg. custom.id
def full_key
@@ -157,8 +183,14 @@ module Spree
errors.add(:field_type, :inclusion)
end
+ # Both the registry's own names and the ones discovery offers: a value a
+ # client was offered has to be accepted, and the two differ where a class
+ # has been renamed (categories are stored under Spree::Taxon while the
+ # registry holds Spree::Category). Existing callers name either, so
+ # narrowing to one would reject definitions that already work.
def valid_available_resources
- self.class.available_resources.map(&:to_s)
+ self.class.available_resources.map(&:to_s) |
+ self.class.enabled_resource_types.map { |resource| resource[:resource_type] }
end
def set_default_type