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.

Changed product pages to share one rule for which variants files can link to

Damian Legawiecf8b2a00afdf4
diff --git a/packages/dashboard-core/src/index.ts b/packages/dashboard-core/src/index.ts
index ffadb5c1ed..acc082ddb1 100644
--- a/packages/dashboard-core/src/index.ts
+++ b/packages/dashboard-core/src/index.ts
@@ -136,6 +136,7 @@ export * from './pages/stock-locations'
// Plugin facade — re-exported for convenience; same API as `/plugin` subpath
// ---------------------------------------------------------------------------
export * from './plugin'
+export * from './products/assignable-variants'
export * from './products/digital-assets-card'
export * from './products/normalize-customs'
export * from './products/normalize-quantity'
diff --git a/packages/dashboard-core/src/products/assignable-variants.ts b/packages/dashboard-core/src/products/assignable-variants.ts
new file mode 100644
index 0000000000..f11c66b96a
--- /dev/null
+++ b/packages/dashboard-core/src/products/assignable-variants.ts
@@ -0,0 +1,35 @@
+import { i18n, type ProductFormValues } from '@spree/dashboard-core'
+import { type Control, useWatch } from 'react-hook-form'
+
+interface LabelledVariant {
+ id: string
+ options_text?: string | null
+ sku?: string | null
+}
+
+/** The name a variant goes by in a picker. */
+export function variantLabel(variant: LabelledVariant): string {
+ const named = variant as LabelledVariant & { name?: string }
+ return (
+ named.options_text ||
+ named.name ||
+ named.sku ||
+ variant.id ||
+ i18n.t('admin.products.variants.variant_label')
+ )
+}
+
+/**
+ * The saved variants a file can be linked to. A card that links files saves
+ * at once, so it must not offer a variant the merchant removed in the form but
+ * has not saved yet: saving would delete that variant and its files with it.
+ * Variants added but not saved have no id to link to.
+ */
+export function useAssignableVariants<V extends { id: string }>(
+ control: Control<ProductFormValues>,
+ variants: V[] | undefined,
+): V[] {
+ const liveVariants = useWatch({ control, name: 'variants' })
+ const liveVariantIds = new Set((liveVariants ?? []).map((variant) => variant.id).filter(Boolean))
+ return (variants ?? []).filter((variant) => liveVariantIds.has(variant.id))
+}
diff --git a/packages/dashboard-core/src/products/digital-asset-edit-sheet.tsx b/packages/dashboard-core/src/products/digital-asset-edit-sheet.tsx
index 1ed3b8cacc..9650758bf0 100644
--- a/packages/dashboard-core/src/products/digital-asset-edit-sheet.tsx
+++ b/packages/dashboard-core/src/products/digital-asset-edit-sheet.tsx
@@ -18,31 +18,21 @@ import {
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import type { PanelDigitalAsset } from '../api-client'
+import { variantLabel } from './assignable-variants'
+import type { PanelVariant } from './product-types'
import { ProviderSettingsFields } from './provider-settings-fields'
import { useUpdateDigitalAsset } from './use-digital-assets'
-/** What the variant picker reads off either panel's variant. */
-export interface DigitalAssetVariantOption {
- id: string
- options_text?: string | null
- sku?: string | null
-}
-
interface Props {
productId: string
asset: PanelDigitalAsset | null
- variants?: DigitalAssetVariantOption[]
+ variants?: PanelVariant[]
/** Fields for a provider-backed asset; empty for an uploaded file. */
settingsSchema?: DigitalAssetProviderSettingField[]
open: boolean
onOpenChange: (open: boolean) => void
}
-/** The name a variant goes by in the picker, or undefined when there is none. */
-export function variantLabel(variant?: DigitalAssetVariantOption): string | undefined {
- return variant ? variant.options_text || variant.sku || variant.id : undefined
-}
-
/** Blank means "use the store's setting", so an empty box is a real value. */
function toInput(value: number | null | undefined): string {
return value == null ? '' : String(value)
@@ -136,10 +126,12 @@ export function DigitalAssetEditSheet({
<Select value={variantId} onValueChange={setVariantId}>
<SelectTrigger id="digital-asset-variant">
<SelectValue>
- {(value) =>
- variantLabel(variants?.find((v) => v.id === value)) ??
- t('admin.digital_assets.all_variants')
- }
+ {(value) => {
+ const variant = variants?.find((v) => v.id === value)
+ return variant
+ ? variantLabel(variant)
+ : t('admin.digital_assets.all_variants')
+ }}
</SelectValue>
</SelectTrigger>
<SelectContent>
diff --git a/packages/dashboard-core/src/products/digital-assets-card.tsx b/packages/dashboard-core/src/products/digital-assets-card.tsx
index 693622953b..6f0dacef0b 100644
--- a/packages/dashboard-core/src/products/digital-assets-card.tsx
+++ b/packages/dashboard-core/src/products/digital-assets-card.tsx
@@ -35,12 +35,10 @@ import {
import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import type { PanelDigitalAsset } from '../api-client'
-import {
- DigitalAssetEditSheet,
- type DigitalAssetVariantOption,
- variantLabel,
-} from './digital-asset-edit-sheet'
+import { variantLabel } from './assignable-variants'
+import { DigitalAssetEditSheet } from './digital-asset-edit-sheet'
import { DigitalAssetProviderSheet } from './digital-asset-provider-sheet'
+import type { PanelVariant } from './product-types'
import {
useCreateDigitalAsset,
useDeleteDigitalAsset,
@@ -53,12 +51,10 @@ export function DigitalAssetsCard({
variants,
}: {
productId?: string
- variants?: DigitalAssetVariantOption[]
+ variants?: PanelVariant[]
}) {
const { t } = useTranslation()
const confirm = useConfirm()
- // Files are part of the product, so changing them needs the product write
- // permission; a read-only role sees the list without the controls.
const { permissions } = usePermissions()
const canWrite = permissions.can('update', Subject.Product)
const fileInputRef = useRef<HTMLInputElement>(null)
@@ -163,6 +159,11 @@ export function DigitalAssetsCard({
return own == null ? t('admin.digital_assets.store_default', { count: effective }) : String(own)
}
+ function assetVariantLabel(asset: PanelDigitalAsset) {
+ const variant = variants?.find((v) => v.id === asset.variant_id)
+ return variant ? variantLabel(variant) : '—'
+ }
+
if (!productId) return null
return (
@@ -292,7 +293,7 @@ export function DigitalAssetsCard({
</TableCell>
{hasVariants && (
<TableCell className="text-muted-foreground">
- {variantLabel(variants?.find((v) => v.id === asset.variant_id)) ?? '—'}
+ {assetVariantLabel(asset)}
</TableCell>
)}
<TableCell className="tabular-nums">
diff --git a/packages/dashboard-core/src/products/media-edit-sheet.tsx b/packages/dashboard-core/src/products/media-edit-sheet.tsx
index 0f90b2fb0d..9a01bfee5e 100644
--- a/packages/dashboard-core/src/products/media-edit-sheet.tsx
+++ b/packages/dashboard-core/src/products/media-edit-sheet.tsx
@@ -20,9 +20,9 @@ import {
SheetTitle,
} from '@spree/dashboard-ui'
import { CheckIcon } from '@spree/dashboard-ui/icons'
-import i18n from 'i18next'
import { useCallback, useEffect, useRef } from 'react'
import type { UseFormReturn } from 'react-hook-form'
+import { variantLabel } from './assignable-variants'
import type { PanelVariant as Variant } from './product-types'
import { useSheetSaveHandlers } from './sheet-save-handlers'
@@ -382,14 +382,3 @@ export function MediaEditSheet({
</Sheet>
)
}
-
-function variantLabel(v: Variant): string {
- const named = v as { options_text?: string; name?: string; sku?: string | null }
- return (
- named.options_text ||
- named.name ||
- named.sku ||
- v.id ||
- i18n.t('admin.products.variants.variant_label')
- )
-}
diff --git a/packages/dashboard-core/src/products/use-digital-assets.ts b/packages/dashboard-core/src/products/use-digital-assets.ts
index 4420fd2d64..41f6361210 100644
--- a/packages/dashboard-core/src/products/use-digital-assets.ts
+++ b/packages/dashboard-core/src/products/use-digital-assets.ts
@@ -21,8 +21,7 @@ export function useDigitalAssets(productId: string, page = 1, enabled = true) {
// The selectable sources for a new asset. Almost always just the File default,
// so a host with no extra provider gets a one-entry list and the card keeps its
-// plain "Add file" button. A panel whose client registers no providers (a
-// seller's) never asks.
+// plain "Add file" button.
export function useDigitalAssetProviders(productId: string, enabled = true) {
const providers = getApiClient().digitalAssets?.providers
return useQuery({
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx
index 7c87f40df3..b95ac9fc24 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx
@@ -21,6 +21,7 @@ import {
Slot,
StatusCard,
TaxCard,
+ useAssignableVariants,
VariantsCard,
variantToWirePayload,
withExtensionRowValues,
@@ -118,18 +119,8 @@ function ProductForm({ product }: { product: Product }) {
const selectedProductTypeId = form.watch('product_type_id')
- // Variants the MediaCard can assign uploaded images to. Only server-persisted
- // variants have an `id` that can ride media[].variant_ids on the PATCH, so we
- // start from `product.variants`. But the merchant may have queued one of those
- // for deletion in the current session (matrix Trash button) — drop those by
- // intersecting against the live form `variants` ids. Newly-added variants
- // without a server id are unassignable until save (no id to send).
- const liveVariants = useWatch({ control: form.control, name: 'variants' })
const formStatus = useWatch({ control: form.control, name: 'status' }) ?? product?.status
- const liveVariantIds = new Set(
- (liveVariants ?? []).map((v) => v.id).filter((id): id is string => !!id),
- )
- const assignableVariants = (product.variants ?? []).filter((v) => liveVariantIds.has(v.id))
+ const assignableVariants = useAssignableVariants(form.control, product.variants)
// Reset the form whenever the source data changes — product itself (PATCH
// refetch) and media (separate query). Both queries invalidate on save so
diff --git a/packages/seller-dashboard/src/api-client.ts b/packages/seller-dashboard/src/api-client.ts
index 68a52400b2..b90d1df13b 100644
--- a/packages/seller-dashboard/src/api-client.ts
+++ b/packages/seller-dashboard/src/api-client.ts
@@ -146,8 +146,6 @@ export function createSellerApiClient({
update: (id, params) => sellerClient().packageTypes.update(id, params),
delete: (id) => sellerClient().packageTypes.delete(id),
},
- // No `providers`: a provider is the marketplace's own integration, so a
- // seller's Digital files card offers file uploads alone.
digitalAssets: {
list: (productId, params) => sellerClient().products.digitalAssets.list(productId, params),
create: (productId, params) =>
diff --git a/packages/seller-dashboard/src/pages/product.tsx b/packages/seller-dashboard/src/pages/product.tsx
index a32fcaddce..8c60d6502c 100644
--- a/packages/seller-dashboard/src/pages/product.tsx
+++ b/packages/seller-dashboard/src/pages/product.tsx
@@ -17,6 +17,7 @@ import {
productFormSchema,
productToFormValues,
Slot,
+ useAssignableVariants,
VariantsCard,
variantToWirePayload,
withExtensionRowValues,
@@ -26,7 +27,7 @@ import type { ProductCreateParams } from '@spree/seller-sdk'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate, useParams } from '@tanstack/react-router'
import { useEffect } from 'react'
-import { FormProvider, useForm, useWatch } from 'react-hook-form'
+import { FormProvider, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { sellerClient } from '../api-client'
import { CenteredMessage } from '../components/centered-message'
@@ -97,14 +98,7 @@ export function ProductPage({ mode }: { mode: 'new' | 'edit' }) {
defaultValues: { ...newProductFormDefaults(), ...extensionFormValues('seller.product', null) },
})
- // A file is moved between variants as soon as its sheet saves, so it must
- // not be offered a variant the seller removed in the form but not yet saved:
- // saving would delete that variant and the file with it.
- const liveVariants = useWatch({ control: form.control, name: 'variants' })
- const liveVariantIds = new Set((liveVariants ?? []).map((variant) => variant.id).filter(Boolean))
- const assignableVariants = (product?.variants ?? []).filter((variant) =>
- liveVariantIds.has(variant.id),
- )
+ const assignableVariants = useAssignableVariants(form.control, product?.variants)
// Reset once the record arrives, so the inputs show what was last saved
// rather than the blank defaults the form mounted with.
@@ -252,7 +246,7 @@ export function ProductPage({ mode }: { mode: 'new' | 'edit' }) {
<VariantsCard form={form} formKey="seller.product" />
<MediaCard
productId={productId}
- variants={product?.variants ?? []}
+ variants={assignableVariants}
form={form}
formKey="seller.product"
/>
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/digital_asset_writes.rb b/spree/api/app/controllers/concerns/spree/api/v3/digital_asset_writes.rb
index f09e2e3678..bdd22c5cce 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/digital_asset_writes.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/digital_asset_writes.rb
@@ -2,8 +2,8 @@ module Spree
module Api
module V3
# The downloadable files on one product, shared by the operator's and a
- # seller's branch. What differs is only how the including controller
- # reaches the product (`set_parent`) and which serializer answers.
+ # seller's branch. Each includer finds and authorizes the product in
+ # `set_parent` and names its serializer.
module DigitalAssetWrites
extend ActiveSupport::Concern
@@ -42,12 +42,8 @@ module Spree
Spree::DigitalAsset
end
- # The parent association reaches assets through `variants`, which
- # carries an ORDER BY on the variants table. Combined with the
- # collection's DISTINCT, PostgreSQL rejects the query outright
- # (ordering columns must appear in the select list), so order by
- # the assets' own table instead. SQLite accepts either form, so
- # this only fails on a real deployment.
+ # Assets reach the product through `variants`, whose ORDER BY
+ # PostgreSQL rejects alongside the collection's DISTINCT.
def scope
super.reorder(created_at: :asc)
end
@@ -56,9 +52,8 @@ module Spree
[:variant, { attachment_attachment: :blob }]
end
- # Not normalized: `provider_settings` carries the provider's own
- # values, which may look like prefixed ids. Extension attributes are
- # splatted in, the operator's or the seller's list by branch.
+ # Not normalized: `provider_settings` may hold values shaped like
+ # prefixed ids.
def permitted_params
params.permit(*declared_permitted_attributes, *model_additional_permitted_attributes)
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/products/digital_assets_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products/digital_assets_controller.rb
index dc6d3141bd..4df06f595d 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/products/digital_assets_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/products/digital_assets_controller.rb
@@ -47,7 +47,7 @@ module Spree
def set_parent
@parent = current_store.products.find_by_prefix_id!(params[:product_id])
- authorize!(:show, @parent)
+ authorize_parent!(@parent)
end
end
end