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.

Fix six defects found in review

Damian Legawiec98bd2024d991
diff --git a/packages/dashboard-core/src/products/use-product-form-data.ts b/packages/dashboard-core/src/products/use-product-form-data.ts
index c224ca0cfb..531ea5ca5f 100644
--- a/packages/dashboard-core/src/products/use-product-form-data.ts
+++ b/packages/dashboard-core/src/products/use-product-form-data.ts
@@ -7,6 +7,7 @@ import type {
PanelProductType,
} from '../api-client'
import { getApiClient } from '../api-client'
+import { useResourceKey } from '../lib/query-keys'
/**
* The reference data the product form's pickers read.
@@ -16,6 +17,11 @@ import { getApiClient } from '../api-client'
* resource needs. These read through the registered panel client, so the same
* cards work in a seller's panel against the Seller API — and answer empty
* when a panel registers no such resource, which is how a card knows to hide.
+ *
+ * Keys go through `useResourceKey`, so they carry the tenant — the store on the
+ * operator's panel, the seller on a seller's. Flat keys would serve one
+ * tenant's categories to the next within the stale window, and a save from that
+ * form would write ids belonging to somebody else.
*/
const FIVE_MINUTES = 1000 * 60 * 5
@@ -24,7 +30,7 @@ export function useFormOptionTypes(enabled = true) {
const client = getApiClient()
return useQuery({
- queryKey: ['panel', 'form', 'option-types'],
+ queryKey: useResourceKey('panel-form-option-types'),
queryFn: async (): Promise<{ data: PanelOptionType[] }> =>
(await client.optionTypes?.list({ limit: 100 })) ?? { data: [] },
enabled: enabled && Boolean(client.optionTypes),
@@ -36,7 +42,7 @@ export function useFormCategories(enabled = true) {
const client = getApiClient()
return useQuery({
- queryKey: ['panel', 'form', 'categories'],
+ queryKey: useResourceKey('panel-form-categories'),
queryFn: async (): Promise<{ data: PanelNamedRecord[] }> =>
(await client.categories?.list({ limit: 100 })) ?? { data: [] },
enabled: enabled && Boolean(client.categories),
@@ -48,7 +54,7 @@ export function useFormCollections(enabled = true) {
const client = getApiClient()
return useQuery({
- queryKey: ['panel', 'form', 'collections'],
+ queryKey: useResourceKey('panel-form-collections'),
queryFn: async (): Promise<{ data: PanelCollection[] }> =>
(await client.collections?.list({ limit: 100 })) ?? { data: [] },
enabled: enabled && Boolean(client.collections),
@@ -60,7 +66,7 @@ export function useFormProductTypes(enabled = true) {
const client = getApiClient()
return useQuery({
- queryKey: ['panel', 'form', 'product-types'],
+ queryKey: useResourceKey('panel-form-product-types'),
queryFn: async (): Promise<{ data: PanelProductType[] }> =>
(await client.productTypes?.list({ limit: 100 })) ?? { data: [] },
enabled: enabled && Boolean(client.productTypes),
@@ -73,7 +79,7 @@ export function useFormProductType(id?: string) {
const client = getApiClient()
return useQuery({
- queryKey: ['panel', 'form', 'product-type', id],
+ queryKey: useResourceKey('panel-form-product-type', id),
queryFn: () => client.productTypes?.get(id as string) as Promise<PanelProductType>,
enabled: Boolean(id) && Boolean(client.productTypes),
staleTime: FIVE_MINUTES,
@@ -101,7 +107,7 @@ export function useFormTaxCategories() {
const client = getApiClient()
return useQuery({
- queryKey: ['panel', 'form', 'tax-categories'],
+ queryKey: useResourceKey('panel-form-tax-categories'),
queryFn: async (): Promise<{ data: PanelNamedRecord[] }> =>
(await client.taxCategories?.list({ limit: 100 })) ?? { data: [] },
enabled: Boolean(client.taxCategories),
@@ -113,7 +119,7 @@ export function useFormDeliveryProfiles() {
const client = getApiClient()
return useQuery({
- queryKey: ['panel', 'form', 'delivery-profiles'],
+ queryKey: useResourceKey('panel-form-delivery-profiles'),
queryFn: async (): Promise<{ data: PanelDeliveryProfile[] }> =>
(await client.deliveryProfiles?.list({ limit: 100 })) ?? { data: [] },
enabled: Boolean(client.deliveryProfiles),
@@ -129,13 +135,15 @@ export function useFormDeliveryProfiles() {
export function useFormDeleteProductMedia(productId: string) {
const client = getApiClient()
const queryClient = useQueryClient()
+ // Resolved here rather than in the callback: it is a hook.
+ const mediaKey = useResourceKey('panel-form-media', productId)
return useMutation({
mutationFn: async (mediaId: string) => {
await client.deleteProductMedia?.(productId, mediaId)
},
onSuccess: () => {
- void queryClient.invalidateQueries({ queryKey: ['panel', 'form', 'media', productId] })
+ void queryClient.invalidateQueries({ queryKey: mediaKey })
},
})
}
@@ -143,12 +151,13 @@ export function useFormDeleteProductMedia(productId: string) {
export function useCreateOptionType() {
const client = getApiClient()
const queryClient = useQueryClient()
+ const optionTypesKey = useResourceKey('panel-form-option-types')
return useMutation({
mutationFn: (params: Record<string, unknown>) =>
client.optionTypes?.create?.(params) as Promise<PanelOptionType>,
onSuccess: () => {
- void queryClient.invalidateQueries({ queryKey: ['panel', 'form', 'option-types'] })
+ void queryClient.invalidateQueries({ queryKey: optionTypesKey })
},
})
}
@@ -156,12 +165,13 @@ export function useCreateOptionType() {
export function useUpdateOptionType(id: string) {
const client = getApiClient()
const queryClient = useQueryClient()
+ const optionTypesKey = useResourceKey('panel-form-option-types')
return useMutation({
mutationFn: (params: Record<string, unknown>) =>
client.optionTypes?.update?.(id, params) as Promise<PanelOptionType>,
onSuccess: () => {
- void queryClient.invalidateQueries({ queryKey: ['panel', 'form', 'option-types'] })
+ void queryClient.invalidateQueries({ queryKey: optionTypesKey })
},
})
}
diff --git a/packages/dashboard/e2e/seller-catalog.spec.ts b/packages/dashboard/e2e/seller-catalog.spec.ts
index de07679954..d0367a2cd6 100644
--- a/packages/dashboard/e2e/seller-catalog.spec.ts
+++ b/packages/dashboard/e2e/seller-catalog.spec.ts
@@ -74,8 +74,11 @@ test.describe('seller catalog and orders', () => {
// record was saved rather than merely posted.
const productName = `E2E Lamp ${Date.now()}`
await sellerPage.getByRole('button', { name: /add product/i }).click()
- await sellerPage.locator('#name').fill(productName)
- await sellerPage.locator('#amount').fill('19.99')
+ // `#product-name` is what the shared GeneralCard renders. The price is
+ // not filled here: it lives in the prices grid, whose inputs carry
+ // generated ids, and what this spec proves is that a listing saves and
+ // gets its own page — pricing has its own coverage in the API suite.
+ await sellerPage.locator('#product-name').fill(productName)
await sellerPage.getByRole('button', { name: /^save$/i }).click()
// The URL is what proves it saved: creating navigates to the new
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx
index 853848994c..7ee542f4fb 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx
@@ -38,6 +38,7 @@ import { useEffect } from 'react'
import { FormProvider, useForm, useWatch } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { CustomFieldsInlineCard } from '../../../../components/spree/custom-fields/custom-fields-inline'
+import { MediaRichTextEditor } from '../../../../components/spree/media-rich-text-editor'
import { ProductCustomFieldsProvider } from '../../../../components/spree/products/product-custom-fields-provider'
import { PublishingCard } from '../../../../components/spree/products/publishing-card'
import { ResourceTranslationsCard } from '../../../../components/spree/translations/resource-translations-card'
@@ -275,7 +276,7 @@ function ProductForm({ product }: { product: Product }) {
}
main={
<>
- <GeneralCard form={form} />
+ <GeneralCard form={form} descriptionEditor={MediaRichTextEditor} />
<VariantsCard form={form} />
<MediaCard productId={productId} variants={assignableVariants} form={form} />
<PricesCard form={form} productName={product.name} />
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx
index 788feec07c..1e44af67d3 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx
@@ -30,6 +30,7 @@ import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { FormProvider, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { CustomFieldsInlineCard } from '../../../../components/spree/custom-fields/custom-fields-inline'
+import { MediaRichTextEditor } from '../../../../components/spree/media-rich-text-editor'
import { ProductCustomFieldsProvider } from '../../../../components/spree/products/product-custom-fields-provider'
import { PublishingCard } from '../../../../components/spree/products/publishing-card'
import { useCreateProduct } from '../../../../hooks/use-product'
@@ -177,7 +178,7 @@ function NewProductPage() {
}
main={
<>
- <GeneralCard form={form} />
+ <GeneralCard form={form} descriptionEditor={MediaRichTextEditor} />
<VariantsCard form={form} seedFromType />
{/* Form-backed media uploader — files are uploaded to ActiveStorage
pre-save and their signed_ids ride the product POST. */}
diff --git a/packages/seller-dashboard/src/pages/product.tsx b/packages/seller-dashboard/src/pages/product.tsx
index 6dc59263b6..1eef162a86 100644
--- a/packages/seller-dashboard/src/pages/product.tsx
+++ b/packages/seller-dashboard/src/pages/product.tsx
@@ -110,7 +110,10 @@ export function ProductPage({ mode }: { mode: 'new' | 'edit' }) {
},
onSuccess: (saved) => {
void queryClient.invalidateQueries({ queryKey: ['seller-products'] })
- queryClient.setQueryData(['seller', sellerId, 'product', saved.id], saved)
+ // Invalidated, never seeded: the write's response carries no expands, so
+ // planting it would blank the variants and media the form is showing —
+ // the reset effect would read a product whose collections are undefined.
+ void queryClient.invalidateQueries({ queryKey: ['seller', sellerId, 'product', saved.id] })
toastManager.add({ type: 'success', title: t('products.saved') })
if (!productId) {
navigate({
diff --git a/spree/api/app/controllers/spree/api/v3/seller/products_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/products_controller.rb
index c6a527888c..8efaea5a9f 100644
--- a/spree/api/app/controllers/spree/api/v3/seller/products_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/seller/products_controller.rb
@@ -105,21 +105,52 @@ module Spree
]
)
- # A price the client did not name a currency for is priced in the
- # store's. `Variant#prices=` matches base prices on the currency it
- # is handed and drops the ones missing from the payload, so a
- # guessed currency does not merely add a stray price — it removes
- # the right one. Blank counts as unnamed: an empty form field would
- # otherwise key a price on "".
- return attrs if attrs[:prices].blank?
-
- attrs[:prices] = attrs[:prices].map do |price|
- price[:currency].present? ? price : price.merge(currency: Spree::Current.currency)
+ # Assigned only when present: writing a nil `prices` or
+ # `stock_levels` key reaches the association setter as nil, which
+ # raises rather than meaning "leave alone".
+ attrs[:prices] = default_price_currencies(attrs[:prices]) if attrs.key?(:prices)
+
+ attrs[:variants] = attrs[:variants]&.map do |variant|
+ variant = variant.merge(prices: default_price_currencies(variant[:prices])) if variant.key?(:prices)
+ variant = variant.merge(stock_levels: own_stock_levels(variant[:stock_levels])) if variant.key?(:stock_levels)
+ variant
end
attrs
end
+ # A price the client did not name a currency for is priced in the
+ # store's. `Variant#prices=` matches base prices on the currency it is
+ # handed and drops the ones missing from the payload, so a guessed
+ # currency does not merely add a stray price — it removes the right
+ # one. Blank counts as unnamed: an empty form field would otherwise
+ # key a price on "".
+ def default_price_currencies(prices)
+ return prices if prices.blank?
+
+ prices.map do |price|
+ price[:currency].present? ? price : price.merge(currency: Spree::Current.currency)
+ end
+ end
+
+ # Stock belongs to the warehouse it sits in, and a seller has their
+ # own. `Variant#stock_levels=` resolves a location against the
+ # product's *store*, which on a marketplace spans every seller — so a
+ # payload naming somebody else's warehouse would write into it. The
+ # ids are narrowed to this seller's here, where `current_seller` is
+ # known; an id from elsewhere is dropped, matching how the model
+ # already skips one it cannot resolve.
+ def own_stock_levels(stock_levels)
+ return stock_levels if stock_levels.blank?
+
+ own_ids = current_seller.stock_locations.pluck(:id).to_set
+
+ stock_levels.select do |level|
+ id = Spree::StockLocation.decode_own_prefixed_id(level[:stock_location_id])
+ id.present? && own_ids.include?(id)
+ end
+ end
+
def collection_includes
[:default_variant, :primary_media]
end
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/products_controller_spec.rb
index c74f5bcd12..1375a4c892 100644
--- a/spree/api/spec/controllers/spree/api/v3/seller/products_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/seller/products_controller_spec.rb
@@ -211,6 +211,46 @@ RSpec.describe Spree::Api::V3::Seller::ProductsController, type: :controller do
expect(mine.reload.variants.map(&:sku)).to include('LAMP-1')
end
+ # `Variant#stock_levels=` resolves a location against the product's store,
+ # which on a marketplace spans every seller — so the ids are narrowed to
+ # this seller's before the payload gets there.
+ it "cannot write stock into another seller's warehouse" do
+ rival = create(:seller, :approved, store: store)
+ rival_location = create(:stock_location, store: store, seller: rival)
+
+ patch :update,
+ params: {
+ id: mine.prefixed_id,
+ variants: [{
+ id: mine.default_variant.prefixed_id, options: [],
+ stock_levels: [{ stock_location_id: rival_location.prefixed_id, count_on_hand: 99 }]
+ }]
+ },
+ as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(Spree::StockLevel.find_by(stock_location: rival_location, variant: mine.default_variant)).to be_nil
+ end
+
+ it 'writes stock into its own warehouse' do
+ own_location = create(:stock_location, store: store, seller: seller)
+
+ patch :update,
+ params: {
+ id: mine.prefixed_id,
+ variants: [{
+ id: mine.default_variant.prefixed_id, options: [],
+ stock_levels: [{ stock_location_id: own_location.prefixed_id, count_on_hand: 7 }]
+ }]
+ },
+ as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(
+ Spree::StockLevel.find_by(stock_location: own_location, variant: mine.default_variant).count_on_hand
+ ).to eq(7)
+ end
+
it 'attaches an uploaded image' do
blob = ActiveStorage::Blob.create_and_upload!(
io: File.open(Spree::Core::Engine.root.join('spec', 'fixtures', 'thinking-cat.jpg')),
diff --git a/spree/core/lib/spree/core/permission_configuration.rb b/spree/core/lib/spree/core/permission_configuration.rb
index a5184313ca..bec1ecc912 100644
--- a/spree/core/lib/spree/core/permission_configuration.rb
+++ b/spree/core/lib/spree/core/permission_configuration.rb
@@ -40,12 +40,13 @@ module Spree
# @param write [Boolean] whether a `write_<name>` key exists
# @param audiences [Array<Symbol>] the non-staff audiences whose roles may
# hold this resource's keys
- def initialize(name:, group:, subjects:, write: true, audiences: [])
+ def initialize(name:, group:, subjects:, write: true, audiences: [], read_only_for: [])
@name = name.to_sym
@group = group.to_sym
@subjects = subjects
@write = write
@audiences = (Array(audiences).map(&:to_sym) | [STAFF_AUDIENCE]).freeze
+ @read_only_for = Array(read_only_for).map(&:to_sym).freeze
end
# @return [Boolean]
@@ -86,6 +87,18 @@ module Spree
def keys
[read_key, write_key].compact
end
+
+ # The keys one audience may hold. A resource the operator writes can
+ # still be read-only for somebody else — product types are the case:
+ # staff define them, a seller only picks from them.
+ #
+ # @param audience [Symbol, String, nil]
+ # @return [Array<String>]
+ def keys_for(audience)
+ return [read_key] if @read_only_for.include?(audience.to_s.to_sym)
+
+ keys
+ end
end
def initialize
@@ -107,13 +120,14 @@ module Spree
# store's own staff, so it is a deliberate act. Never open `settings`,
# `staff` or `api_keys`.
# @return [Resource]
- def register_resource(name, group:, subjects:, write: true, audiences: [])
+ def register_resource(name, group:, subjects:, write: true, audiences: [], read_only_for: [])
# `read_all` / `write_all` are the API-key wildcard aliases — a resource
# named `all` would silently mint keys that grant the whole catalog.
raise ArgumentError, "the permission resource name 'all' is reserved" if name.to_s == 'all'
resource = Resource.new(
- name: name, group: group, subjects: subjects, write: write, audiences: audiences
+ name: name, group: group, subjects: subjects, write: write,
+ audiences: audiences, read_only_for: read_only_for
)
@resources[resource.name] = resource
end
@@ -180,7 +194,7 @@ module Spree
# @param audience [Symbol, String]
# @return [Array<String>] every key that audience may hold, in catalog order
def grantable_keys(audience)
- grantable_resources(audience).flat_map(&:keys)
+ grantable_resources(audience).flat_map { |resource| resource.keys_for(audience) }
end
# @return [Array<Entry>] every grantable key with metadata, in catalog order
@@ -296,11 +310,15 @@ module Spree
Spree::Catalog, Spree::CatalogProduct,
Spree::CatalogAssignment, Spree::CustomField]
})
- # A seller fills in a type's custom fields; they do not define the types.
- # Read-only rather than absent, because the product form has to offer the
- # picker (docs/plans/6.0-seller-product-submission.md).
- register_resource(:product_types, group: :catalog, write: false,
- audiences: %i[seller],
+ # Its own resource so a seller can be granted the read without the
+ # write, but the write key has to exist: the operator's endpoint serves
+ # create/update/destroy, and a resource declared `write: false` has no
+ # `write_product_types` for that gate to accept — every scoped key and
+ # every non-admin staff role would 403
+ # (docs/plans/6.0-seller-product-submission.md). Sellers hold the read
+ # alone; `grantable_keys` is what bounds them, not the catalog.
+ register_resource(:product_types, group: :catalog,
+ audiences: %i[seller], read_only_for: %i[seller],
subjects: -> { [Spree::ProductType] })
# Which channels carry a product is marketplace merchandising. Closed to
# the seller audience: a seller lists, the marketplace distributes.
diff --git a/spree/core/spec/lib/spree/core/permission_configuration_spec.rb b/spree/core/spec/lib/spree/core/permission_configuration_spec.rb
index 9c2a281969..de334bbb25 100644
--- a/spree/core/spec/lib/spree/core/permission_configuration_spec.rb
+++ b/spree/core/spec/lib/spree/core/permission_configuration_spec.rb
@@ -239,4 +239,21 @@ RSpec.describe Spree::PermissionConfiguration do
expect(Spree.permissions.resource_for_subject(Spree::Seller).name).to eq(:sellers)
end
end
+
+ # Product types are the worked example of a resource the operator writes and
+ # another audience only reads. The write key has to exist — the operator's
+ # endpoint serves create/update/destroy and its gate looks the key up — while
+ # staying out of what a seller may be granted.
+ describe 'a resource that is read-only for one audience' do
+ it 'gives staff both keys' do
+ expect(Spree.permissions.grantable_keys(:store)).to include('read_product_types', 'write_product_types')
+ end
+
+ it 'gives the seller audience the read alone' do
+ keys = Spree.permissions.grantable_keys(:seller)
+
+ expect(keys).to include('read_product_types')
+ expect(keys).not_to include('write_product_types')
+ end
+ end
end