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
Variant dimensions fixes (#14600)
Damian Legawiec3b2196fc957b
diff --git a/docs/api-reference/store.yaml b/docs/api-reference/store.yamlindex 64e30339a7..08e5748aff 100644--- a/docs/api-reference/store.yaml+++ b/docs/api-reference/store.yaml@@ -9721,6 +9721,8 @@ paths:height:width:depth:+ weight_unit: lb+ dimensions_unit: inminimum_order_quantity: 1order_multiple: 1purchase_unit: unit@@ -15133,6 +15135,10 @@ components:depth:type: numbernullable: true+ weight_unit:+ type: string+ dimensions_unit:+ type: stringminimum_order_quantity:type: numberorder_multiple:@@ -15188,6 +15194,8 @@ components:- height- width- depth+ - weight_unit+ - dimensions_unit- minimum_order_quantity- order_multiple- purchase_unitdiff --git a/packages/admin-sdk/src/types/generated/Variant.ts b/packages/admin-sdk/src/types/generated/Variant.tsindex e2e06cf471..8aa6b15a72 100644--- a/packages/admin-sdk/src/types/generated/Variant.ts+++ b/packages/admin-sdk/src/types/generated/Variant.ts@@ -1,4 +1,4 @@-// Typelizer digest 0de03573c3d9468651c894b5eed68c3f+// Typelizer digest 456fd69ee666876b202fce4f5de86d31//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {Price, PriceHistory, Seller, Media, OptionValue, CustomField, StockLevel} from '@/types'@@ -20,6 +20,8 @@ interface Variant {height: number | null;width: number | null;depth: number | null;+ weight_unit: string;+ dimensions_unit: string;minimum_order_quantity: number | null;order_multiple: number | null;purchase_unit: string | null;@@ -50,8 +52,6 @@ interface Variant {updated_at: string;preorderable: boolean;tax_category_id: string | null;- weight_unit: string | null;- dimensions_unit: string | null;carton_package_type_id: string | null;units_per_pallet: number | null;available_stock: number | null;diff --git a/packages/dashboard-core/src/locales/ar.json b/packages/dashboard-core/src/locales/ar.jsonindex 799f4571b9..112f82fb50 100644--- a/packages/dashboard-core/src/locales/ar.json+++ b/packages/dashboard-core/src/locales/ar.json@@ -1524,9 +1524,10 @@"identity": "هوية","tax_category_placeholder": "ترث من المنتج","ordering": "الطلب للشركات",- "ordering_help": "الكمية التي يجب على المشتري أخذها. لا يزال المخزون يُحسب بالوحدات.",+ "ordering_help": "الكمية التي يجب على المشتري أخذها. يتم التحقق منها عند الإضافة إلى السلة ومرة أخرى عند إتمام الطلب. يمكن لكتالوج مجموعة عملاء أو شركة تجاوز هذه القيم لمشتريه. لا يزال المخزون يُحسب بالوحدات.","packing": "التعبئة","packing_help": "كيف يغادر هذا المنتج المستودع بالجملة. تُبنى عروض أسعار الشحن على هذه الأرقام.",+ "no_carton_types": "أضف نوع كرتونة من <settingsLink>الإعدادات ← أنواع التغليف</settingsLink> لتسجيل كيفية تغليف هذا المنتج.","carton_placeholder": "بدون كرتونة","pending_save": "تُحفظ التغييرات هنا مع المنتج."},diff --git a/packages/dashboard-core/src/locales/de.json b/packages/dashboard-core/src/locales/de.jsonindex a8ab6dff59..d0fdf84d6d 100644--- a/packages/dashboard-core/src/locales/de.json+++ b/packages/dashboard-core/src/locales/de.json@@ -1525,9 +1525,10 @@"identity": "Identität","tax_category_placeholder": "Vom Produkt übernehmen","ordering": "B2B-Bestellung",- "ordering_help": "Wie viel ein Käufer abnehmen muss. Der Bestand wird weiterhin in Stück gezählt.",+ "ordering_help": "Wie viel ein Käufer abnehmen muss. Wird beim Hinzufügen zum Warenkorb und erneut beim Checkout geprüft. Ein Katalog einer Kundengruppe oder eines Unternehmens kann diese Werte für seine Käufer überschreiben. Der Bestand wird weiterhin in Stück gezählt.","packing": "Verpackung","packing_help": "Wie dieses Produkt als Großmenge das Lager verlässt. Frachtangebote beruhen auf diesen Zahlen.",+ "no_carton_types": "Legen Sie unter <settingsLink>Einstellungen → Verpackungsarten</settingsLink> eine Kartonart an, um zu erfassen, wie dieses Produkt verpackt ist.","carton_placeholder": "Kein Karton","pending_save": "Änderungen hier werden mit dem Produkt gespeichert."},diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.jsonindex 09fbd9f337..f14a7b209e 100644--- a/packages/dashboard-core/src/locales/en.json+++ b/packages/dashboard-core/src/locales/en.json@@ -1527,9 +1527,10 @@"identity": "Identity","tax_category_placeholder": "Inherit from product","ordering": "B2B ordering",- "ordering_help": "How much a buyer must take. Stock is still counted in units.",+ "ordering_help": "How much a buyer must take. Enforced when items are added to a cart and again at checkout. A customer group or company catalog can override these for its buyers. Stock is still counted in units.","packing": "Packing","packing_help": "How this product leaves the warehouse in bulk. Freight quotes are built from these numbers.",+ "no_carton_types": "Add a carton type under <settingsLink>Settings → Package types</settingsLink> to record how this product is packed.","carton_placeholder": "No carton","pending_save": "Changes here are saved with the product."},diff --git a/packages/dashboard-core/src/locales/fr.json b/packages/dashboard-core/src/locales/fr.jsonindex 10175c354b..f1f668ddde 100644--- a/packages/dashboard-core/src/locales/fr.json+++ b/packages/dashboard-core/src/locales/fr.json@@ -1525,9 +1525,10 @@"identity": "Identité","tax_category_placeholder": "Hériter du produit","ordering": "Commande B2B",- "ordering_help": "Combien un acheteur doit prendre. Le stock reste compté en unités.",+ "ordering_help": "Combien un acheteur doit prendre. Vérifié lors de l'ajout au panier puis de nouveau au paiement. Le catalogue d'un groupe de clients ou d'une entreprise peut remplacer ces valeurs pour ses acheteurs. Le stock reste compté en unités.","packing": "Emballage","packing_help": "Comment ce produit quitte l’entrepôt en gros. Les devis de fret reposent sur ces chiffres.",+ "no_carton_types": "Ajoutez un type de carton dans <settingsLink>Paramètres → Types d'emballage</settingsLink> pour enregistrer la façon dont ce produit est emballé.","carton_placeholder": "Aucun carton","pending_save": "Les modifications sont enregistrées avec le produit."},diff --git a/packages/dashboard-core/src/locales/pl.json b/packages/dashboard-core/src/locales/pl.jsonindex 2d66d6f34d..fe593365c3 100644--- a/packages/dashboard-core/src/locales/pl.json+++ b/packages/dashboard-core/src/locales/pl.json@@ -1548,9 +1548,10 @@"identity": "Tożsamość","tax_category_placeholder": "Dziedzicz z produktu","ordering": "Zamówienia B2B",- "ordering_help": "Ile kupujący musi wziąć. Stan magazynowy nadal liczony jest w sztukach.",+ "ordering_help": "Ile kupujący musi wziąć. Sprawdzane przy dodawaniu do koszyka i ponownie przy składaniu zamówienia. Katalog grupy klientów lub firmy może nadpisać te wartości dla swoich kupujących. Stan magazynowy nadal liczony jest w sztukach.","packing": "Pakowanie","packing_help": "Jak ten produkt opuszcza magazyn hurtowo. Na tych liczbach opierają się wyceny frachtu.",+ "no_carton_types": "Dodaj typ kartonu w sekcji <settingsLink>Ustawienia → Typy opakowań</settingsLink>, aby zapisać sposób pakowania tego produktu.","carton_placeholder": "Brak kartonu","pending_save": "Zmiany zapisują się razem z produktem."},diff --git a/packages/dashboard-core/src/locales/zh-CN.json b/packages/dashboard-core/src/locales/zh-CN.jsonindex 9c1cc8ac03..1998a906b1 100644--- a/packages/dashboard-core/src/locales/zh-CN.json+++ b/packages/dashboard-core/src/locales/zh-CN.json@@ -1524,9 +1524,10 @@"identity": "标识","tax_category_placeholder": "继承自商品","ordering": "B2B 订购",- "ordering_help": "买家必须订购的数量。库存仍以件计算。",+ "ordering_help": "买家必须订购的数量。在加入购物车时以及结账时都会强制执行。客户组或公司目录可以为其买家覆盖这些设置。库存仍以件计算。","packing": "装箱","packing_help": "此商品成批出库的方式。货运报价依据这些数字计算。",+ "no_carton_types": "在<settingsLink>设置 → 包装类型</settingsLink>中添加纸箱类型,以记录此产品的包装方式。","carton_placeholder": "未装箱","pending_save": "此处的更改随商品一并保存。"},diff --git a/packages/dashboard-core/src/products/bulk-variants-dialog.tsx b/packages/dashboard-core/src/products/bulk-variants-dialog.tsxindex b580be7296..7a6f92755d 100644--- a/packages/dashboard-core/src/products/bulk-variants-dialog.tsx+++ b/packages/dashboard-core/src/products/bulk-variants-dialog.tsx@@ -235,7 +235,16 @@ export function BulkVariantsDialog({ form, open, onOpenChange }: Props) {</Button></div></DialogHeader>- <DialogBody className="min-h-0 flex-1 overflow-auto p-3">+ {/* No gutter: the body holds nothing but the grid, so padding only+ narrows the space the columns have to fit in and leaves the+ table's own border floating inside the dialog's.++ `DialogBody` already scrolls on y and bounds its own height, so+ the grid inside it has something to size against and stays the one+ element that scrolls sideways. Do not add an overflow utility+ here: the base class sets the `overflow-y` longhand, which a bare+ `overflow-hidden` does not override at equal specificity. */}+ <DialogBody className="min-h-0 flex-1 p-0"><BulkVariantsTablerows={rows}onChange={handleChange}diff --git a/packages/dashboard-core/src/products/use-product-form-data.ts b/packages/dashboard-core/src/products/use-product-form-data.tsindex 323dce8d3a..c4fc3a5636 100644--- a/packages/dashboard-core/src/products/use-product-form-data.ts+++ b/packages/dashboard-core/src/products/use-product-form-data.ts@@ -24,6 +24,13 @@ import { useResourceKey } from '../lib/query-keys'* 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.+ *+ * They are also keyed UNDER the resource they mirror — `['package-types',+ * tenant, 'panel-form', ...]`, not `['panel-form-package-types', tenant]` — so+ * that the `invalidate: [['package-types']]` a management page already declares+ * sweeps them by prefix. Keyed to one side, a carton created in settings stayed+ * invisible to this form for the whole stale window below, and the section that+ * only renders once a carton exists went on claiming there were none.*/const FIVE_MINUTES = 1000 * 60 * 5@@ -32,7 +39,7 @@ export function useFormOptionTypes(enabled = true) {const client = getApiClient()return useQuery({- queryKey: useResourceKey('panel-form-option-types'),+ queryKey: useResourceKey('option-types', 'panel-form'),queryFn: async (): Promise<{ data: PanelOptionType[] }> =>(await client.optionTypes?.list({ limit: 100 })) ?? { data: [] },enabled: enabled && Boolean(client.optionTypes),@@ -44,7 +51,7 @@ export function useFormCategories(enabled = true) {const client = getApiClient()return useQuery({- queryKey: useResourceKey('panel-form-categories'),+ queryKey: useResourceKey('categories', 'panel-form'),queryFn: async (): Promise<{ data: PanelNamedRecord[] }> =>(await client.categories?.list({ limit: 100 })) ?? { data: [] },enabled: enabled && Boolean(client.categories),@@ -56,7 +63,7 @@ export function useFormCollections(enabled = true) {const client = getApiClient()return useQuery({- queryKey: useResourceKey('panel-form-collections'),+ queryKey: useResourceKey('collections', 'panel-form'),queryFn: async (): Promise<{ data: PanelCollection[] }> =>(await client.collections?.list({ limit: 100 })) ?? { data: [] },enabled: enabled && Boolean(client.collections),@@ -68,7 +75,7 @@ export function useFormProductTypes(enabled = true) {const client = getApiClient()return useQuery({- queryKey: useResourceKey('panel-form-product-types'),+ queryKey: useResourceKey('product-types', 'panel-form'),queryFn: async (): Promise<{ data: PanelProductType[] }> =>(await client.productTypes?.list({ limit: 100 })) ?? { data: [] },enabled: enabled && Boolean(client.productTypes),@@ -81,7 +88,7 @@ export function useFormProductType(id?: string) {const client = getApiClient()return useQuery({- queryKey: useResourceKey('panel-form-product-type', id),+ queryKey: useResourceKey('product-types', 'panel-form', id),queryFn: () => client.productTypes?.get(id as string) as Promise<PanelProductType>,enabled: Boolean(id) && Boolean(client.productTypes),staleTime: FIVE_MINUTES,@@ -109,7 +116,7 @@ export function useFormTaxCategories() {const client = getApiClient()return useQuery({- queryKey: useResourceKey('panel-form-tax-categories'),+ queryKey: useResourceKey('tax-categories', 'panel-form'),queryFn: async (): Promise<{ data: PanelNamedRecord[] }> =>(await client.taxCategories?.list({ limit: 100 })) ?? { data: [] },enabled: Boolean(client.taxCategories),@@ -121,7 +128,7 @@ export function useFormDeliveryProfiles() {const client = getApiClient()return useQuery({- queryKey: useResourceKey('panel-form-delivery-profiles'),+ queryKey: useResourceKey('delivery-profiles', 'panel-form'),queryFn: async (): Promise<{ data: PanelDeliveryProfile[] }> =>(await client.deliveryProfiles?.list({ limit: 100 })) ?? { data: [] },enabled: Boolean(client.deliveryProfiles),@@ -129,16 +136,26 @@ export function useFormDeliveryProfiles() {})}+/**+ * Carton package types, plus whether this panel manages them at all.+ *+ * `supported` is what separates "this panel has no such page" (a seller's,+ * where the packing card should not appear) from "the store has not created a+ * carton yet" (an operator's, where it appears disabled and says where to go).+ */export function useFormCartonPackageTypes() {const client = getApiClient()+ const supported = Boolean(client.packageTypes)- return useQuery({- queryKey: useResourceKey('panel-form-carton-package-types'),+ const query = useQuery({+ queryKey: useResourceKey('package-types', 'panel-form', 'cartons'),queryFn: async (): Promise<{ data: PanelPackageType[] }> =>(await client.packageTypes?.list({ limit: 100, kind_eq: 'carton' })) ?? { data: [] },- enabled: Boolean(client.packageTypes),+ enabled: supported,staleTime: FIVE_MINUTES,})++ return { ...query, supported }}/**@@ -149,8 +166,10 @@ export function useFormCartonPackageTypes() {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)+ // Resolved here rather than in the callback: it is a hook. No `panel-form`+ // segment on this one — it must match the key the gallery reads, which is+ // the operator dashboard's own `useProductMedia`.+ const mediaKey = useResourceKey('products', productId, 'media')return useMutation({mutationFn: async (mediaId: string) => {@@ -165,7 +184,7 @@ export function useFormDeleteProductMedia(productId: string) {export function useCreateOptionType() {const client = getApiClient()const queryClient = useQueryClient()- const optionTypesKey = useResourceKey('panel-form-option-types')+ const optionTypesKey = useResourceKey('option-types', 'panel-form')return useMutation({mutationFn: (params: { name: string; label: string } & Record<string, unknown>) =>@@ -179,7 +198,7 @@ export function useCreateOptionType() {export function useUpdateOptionType(id: string) {const client = getApiClient()const queryClient = useQueryClient()- const optionTypesKey = useResourceKey('panel-form-option-types')+ const optionTypesKey = useResourceKey('option-types', 'panel-form')return useMutation({mutationFn: (@@ -233,7 +252,7 @@ export function useFormCurrencyLocale(): (currency: string | undefined) => strinconst client = getApiClient()const { data } = useQuery({- queryKey: useResourceKey('panel-form-markets'),+ queryKey: useResourceKey('markets', 'panel-form'),queryFn: async (): Promise<{ data: PanelMarket[] }> =>(await client.markets?.list({ limit: 100 })) ?? { data: [] },enabled: Boolean(client.markets),diff --git a/packages/dashboard-core/src/products/variant-edit-sheet.tsx b/packages/dashboard-core/src/products/variant-edit-sheet.tsxindex efbf54bdac..d99df7d49d 100644--- a/packages/dashboard-core/src/products/variant-edit-sheet.tsx+++ b/packages/dashboard-core/src/products/variant-edit-sheet.tsx@@ -1,6 +1,8 @@import type { ProductFormValues, VariantFormValues } from '@spree/dashboard-core'import { CountryCombobox, StoreDatePicker } from '@spree/dashboard-core'import {+ Alert,+ AlertDescription,Button,Field,FieldDescription,@@ -25,9 +27,12 @@ import {SheetTitle,Switch,} from '@spree/dashboard-ui'+import { Link } from '@tanstack/react-router'+import { InfoIcon } from 'lucide-react'import { useEffect, useRef } from 'react'import { Controller, type UseFormReturn } from 'react-hook-form'-import { useTranslation } from 'react-i18next'+import { Trans, useTranslation } from 'react-i18next'+import { useTenantId } from '../providers/tenant-provider'import { cartonSize } from './carton-size'import { normalizeCustomsDescription, normalizeHsCode } from './normalize-customs'import { PURCHASE_UNITS } from './normalize-quantity'@@ -60,11 +65,22 @@ export function VariantEditSheet({ form, variantIndex, open, onOpenChange }: Proconst hasTaxCategories = taxCategories.length > 0const { data: optionTypesData } = useOptionTypes()const optionTypes = optionTypesData?.data ?? []- // Nothing to pack into means nothing to ask: the section stays hidden until- // the store has recorded a carton.- const { data: cartonTypesResponse } = useCartonPackageTypes()+ const tenantId = useTenantId()+ // A panel that does not manage package types at all (a seller's) has no+ // packing to ask about, so the section stays hidden there. An operator with+ // none created yet still sees it, disabled, saying where to make one —+ // hiding it outright left no trace of a feature they had not set up.+ const {+ data: cartonTypesResponse,+ isPending: cartonTypesPending,+ supported: cartonTypesSupported,+ } = useCartonPackageTypes()const cartonTypes = cartonTypesResponse?.data ?? []const hasCartonTypes = cartonTypes.length > 0+ // Only once the list has actually answered. While it is in flight the empty+ // array below is not yet evidence of an empty store, and telling a merchant+ // who has cartons to go and make one is worse than saying nothing.+ const knownEmpty = cartonTypesSupported && !cartonTypesPending && !hasCartonTypes// A packed carton is weighed on the same scale as the goods inside it, so// this follows the variant's own unit rather than offering a second one.const cartonWeightUnit = form.watch(`variants.${variantIndex}.weight_unit`) || ''@@ -292,11 +308,29 @@ export function VariantEditSheet({ form, variantIndex, open, onOpenChange }: Pro</div></FormSection>- {hasCartonTypes && (+ {cartonTypesSupported && (<FormSection title={t('admin.products.variants.sheet.packing')}><p className="text-sm text-muted-foreground">{t('admin.products.variants.sheet.packing_help')}</p>+ {knownEmpty && (+ <Alert variant="info">+ <InfoIcon />+ <AlertDescription>+ <Trans+ i18nKey="admin.products.variants.sheet.no_carton_types"+ components={{+ settingsLink: (+ <Link+ to={`/${tenantId}/settings/package-types` as never}+ className="underline underline-offset-3"+ />+ ),+ }}+ />+ </AlertDescription>+ </Alert>+ )}<Field><FieldLabel htmlFor={`variant-${variantIndex}-carton`}>{t('admin.fields.variant.carton_package_type_id.label')}@@ -309,7 +343,11 @@ export function VariantEditSheet({ form, variantIndex, open, onOpenChange }: Provalue={field.value ?? ''}onValueChange={(value) => field.onChange(value || null)}>- <SelectTrigger id={`variant-${variantIndex}-carton`} className="w-full">+ <SelectTrigger+ id={`variant-${variantIndex}-carton`}+ className="w-full"+ disabled={!hasCartonTypes}+ ><SelectValueplaceholder={t('admin.products.variants.sheet.carton_placeholder')}>@@ -361,6 +399,7 @@ export function VariantEditSheet({ form, variantIndex, open, onOpenChange }: Protype="number"step="0.01"min="0"+ disabled={!hasCartonTypes}value={field.value ?? ''}onChange={(event) => {const parsed = Number(event.target.value)@@ -391,6 +430,7 @@ export function VariantEditSheet({ form, variantIndex, open, onOpenChange }: Protype="number"min="1"step="1"+ disabled={!hasCartonTypes}{...form.register(`variants.${variantIndex}.cartons_per_pallet`)}/><FieldErrordiff --git a/packages/dashboard-ui/src/spree/bulk-variants-table.tsx b/packages/dashboard-ui/src/spree/bulk-variants-table.tsxindex 87b59e6a32..bf3120bae4 100644--- a/packages/dashboard-ui/src/spree/bulk-variants-table.tsx+++ b/packages/dashboard-ui/src/spree/bulk-variants-table.tsx@@ -411,17 +411,22 @@ export function BulkVariantsTable({cartonOptions,])+ // Roughly 130px a column, which is what the widest headers here ("Available+ // for pre-order", "Customs description") need before they wrap to two lines.+ // The grid scrolls sideways past that rather than squeezing them.+ const minWidth = cartonOptions+ ? 'min-w-[2470px]'+ : countryOptions+ ? 'min-w-[1950px]'+ : 'min-w-[1560px]'+return (- <div className="overflow-x-auto">- <DataGrid<BulkVariantsRow>- rows={rows}- columns={columns}- getRowId={(row) => row.id}- className={- cartonOptions ? 'min-w-[1900px]' : countryOptions ? 'min-w-[1500px]' : 'min-w-[1100px]'- }- aria-label={labels.gridAriaLabel}- />- </div>+ <DataGrid<BulkVariantsRow>+ rows={rows}+ columns={columns}+ getRowId={(row) => row.id}+ className={minWidth}+ aria-label={labels.gridAriaLabel}+ />)}diff --git a/packages/dashboard-ui/src/spree/data-grid/data-grid.tsx b/packages/dashboard-ui/src/spree/data-grid/data-grid.tsxindex 0462e9e8b6..5c86c592af 100644--- a/packages/dashboard-ui/src/spree/data-grid/data-grid.tsx+++ b/packages/dashboard-ui/src/spree/data-grid/data-grid.tsx@@ -177,7 +177,22 @@ function DataGridShell<T>({return (<DataGridContext.Provider value={ctx}><DataGridKeyboardMount gridRef={gridRef} />- <div className="relative overflow-hidden rounded-md">+ {/* Scrolls sideways rather than clipping: a grid wide enough to need it+ (the bulk variant editor sets a min-width well past any viewport) had+ its right-hand columns cut off with no way to reach them, because the+ `overflow-hidden` that used to clip this wrapper also beat the+ caller's own scroll container. Nothing rounds the corners now — the+ table's own cell borders draw its edges.++ `max-h-full` is what keeps the sticky header working. Declaring one+ overflow axis makes the other a scroll container too whatever it is+ declared as, so this div scrolls vertically whether or not we ask it+ to — and an unbounded one grows to its full content height, which+ leaves `position: sticky` with nothing to stick within. Bounding it+ to the caller's height gives the header a viewport again, and a+ caller that imposes no height (a grid that scrolls with the page)+ still resolves to no constraint. */}+ <div className="relative max-h-full overflow-auto"><tableref={gridRef}// Focusable so the grid itself can hold the keyboard when a cell'sdiff --git a/packages/sdk/src/types/generated/Variant.ts b/packages/sdk/src/types/generated/Variant.tsindex ecd0b1930e..2fcd4350f6 100644--- a/packages/sdk/src/types/generated/Variant.ts+++ b/packages/sdk/src/types/generated/Variant.ts@@ -1,4 +1,4 @@-// Typelizer digest 16e6bd684676c71f96f049dc4b2c82a3+// Typelizer digest 323062ff8845b8dbd94fc62b42308c6f//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {Price, PriceHistory, Seller, Media, OptionValue, CustomField} from '@/types'@@ -20,6 +20,8 @@ interface Variant {height: number | null;width: number | null;depth: number | null;+ weight_unit: string;+ dimensions_unit: string;minimum_order_quantity: number;order_multiple: number;purchase_unit: string;diff --git a/packages/sdk/src/zod/generated/Variant.ts b/packages/sdk/src/zod/generated/Variant.tsindex 3ac45c22db..ab14592433 100644--- a/packages/sdk/src/zod/generated/Variant.ts+++ b/packages/sdk/src/zod/generated/Variant.ts@@ -24,6 +24,8 @@ export const VariantSchema = z.object({height: z.number().nullable(),width: z.number().nullable(),depth: z.number().nullable(),+ weight_unit: z.string(),+ dimensions_unit: z.string(),minimum_order_quantity: z.number(),order_multiple: z.number(),purchase_unit: z.string(),diff --git a/packages/seller-sdk/src/types/generated/Variant.ts b/packages/seller-sdk/src/types/generated/Variant.tsindex 9f40cd18b3..a161072ce9 100644--- a/packages/seller-sdk/src/types/generated/Variant.ts+++ b/packages/seller-sdk/src/types/generated/Variant.ts@@ -1,4 +1,4 @@-// Typelizer digest 824e6b2a5d6b5917c16067f3ab7839b4+// Typelizer digest 574aa75d02c584feedfa23463bdd1a34//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {Price, PriceHistory, Seller, Media, OptionValue, CustomField, StockLevel} from '@/types'@@ -20,6 +20,8 @@ type Variant = {height: number | null;width: number | null;depth: number | null;+ weight_unit: string;+ dimensions_unit: string;minimum_order_quantity: number | null;order_multiple: number | null;purchase_unit: string | null;@@ -38,8 +40,6 @@ type Variant = {cost_price: string | null;cost_currency: string | null;barcode: string | null;- weight_unit: string | null;- dimensions_unit: string | null;backorder_limit: number | null;hs_code: string | null;country_of_origin: string | null;diff --git a/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rbindex bcf9291a16..d2f64941bb 100644--- a/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb@@ -12,7 +12,6 @@ module Spreeposition: :number, tax_category_id: [:string, nullable: true],cost_price: [:string, nullable: true], cost_currency: [:string, nullable: true],barcode: [:string, nullable: true],- weight_unit: [:string, nullable: true], dimensions_unit: [:string, nullable: true],available_stock: [:number, nullable: true],reserved_quantity: :number, total_on_hand: [:number, nullable: true],preorderable: :boolean, preorder_ships_at: [:string, nullable: true],@@ -49,17 +48,6 @@ module Spreevariant.tax_category&.prefixed_idend- # The stored columns, so an editor shows a blank where the merchant- # left one and saving does not write this store's units onto the- # row. Both readers resolve a fallback for display elsewhere.- attribute :weight_unit do |variant|- variant[:weight_unit]- end-- attribute :dimensions_unit do |variant|- variant[:dimensions_unit]- end-# Encoded from the foreign key: loading the carton row just to# re-encode its id is a query per variant on the product listing.attribute :carton_package_type_id do |variant|diff --git a/spree/api/app/serializers/spree/api/v3/seller/variant_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/variant_serializer.rbindex 4451e88d7d..d2071af751 100644--- a/spree/api/app/serializers/spree/api/v3/seller/variant_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/seller/variant_serializer.rb@@ -14,8 +14,6 @@ module Spreecost_price: [:string, nullable: true],cost_currency: [:string, nullable: true],barcode: [:string, nullable: true],- weight_unit: [:string, nullable: true],- dimensions_unit: [:string, nullable: true],available_stock: [:number, nullable: true],total_on_hand: [:number, nullable: true],preorderable: :boolean,@@ -29,7 +27,7 @@ module Spreemetadata: 'Record<string, unknown>'attributes :metadata, :position, :cost_price, :cost_currency,- :barcode, :weight_unit, :dimensions_unit, :backorder_limit,+ :barcode, :backorder_limit,:hs_code, :country_of_origin, :customs_description,preorder_ships_at: :iso8601,created_at: :iso8601, updated_at: :iso8601diff --git a/spree/api/app/serializers/spree/api/v3/variant_serializer.rb b/spree/api/app/serializers/spree/api/v3/variant_serializer.rbindex 51e23dec4a..6127d09025 100644--- a/spree/api/app/serializers/spree/api/v3/variant_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/variant_serializer.rb@@ -10,6 +10,7 @@ module Spreepurchasable: :boolean, in_stock: :boolean, backorderable: :boolean, preorder: :boolean,preorder_ships_at: [:string, nullable: true],weight: [:number, nullable: true], height: [:number, nullable: true], width: [:number, nullable: true], depth: [:number, nullable: true],+ weight_unit: :string, dimensions_unit: :string,price: 'Price',original_price: ['Price', nullable: true],minimum_order_quantity: :number, order_multiple: :number,@@ -65,6 +66,15 @@ module Spreevariant.depth&.to_fend+ # Resolved, not the raw columns: a variant that states no unit of its+ # own is measured in the store's, so the numbers above are meaningless+ # without this. Always present for the same reason the quantity rules+ # below are — a caller should not have to fetch the store to read a+ # weight.+ attribute :weight_unit, &:weight_unit++ attribute :dimensions_unit, &:dimensions_unit+# The buyer's RESOLVED rules — their catalog terms over the variant's# base — so a storefront draws the right stepper without knowing# which of the two answered. Always present: an unrestricted variantdiff --git a/spree/core/app/services/spree/imports/row_processors/product_variant.rb b/spree/core/app/services/spree/imports/row_processors/product_variant.rbindex c0a27253ba..0c32826cab 100644--- a/spree/core/app/services/spree/imports/row_processors/product_variant.rb+++ b/spree/core/app/services/spree/imports/row_processors/product_variant.rb@@ -27,9 +27,11 @@ module Spreevariant.sku = attributes['sku'] if attributes['sku'].present?variant.cost_price = attributes['cost_price'] if attributes['cost_price'].present?variant.weight = attributes['weight'] if attributes['weight'].present?+ variant.weight_unit = attributes['weight_unit'] if attributes['weight_unit'].present?variant.height = attributes['height'] if attributes['height'].present?variant.width = attributes['width'] if attributes['width'].present?variant.depth = attributes['depth'] if attributes['depth'].present?+ variant.dimensions_unit = attributes['dimensions_unit'] if attributes['dimensions_unit'].present?variant.track_inventory = attributes['track_inventory'] if attributes['track_inventory'].present?variant.hs_code = attributes['hs_code'] if attributes['hs_code'].present?variant.country_of_origin = attributes['country_of_origin'] if attributes['country_of_origin'].present?diff --git a/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb b/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rbindex 7402563188..3f8e19b885 100644--- a/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb+++ b/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb@@ -21,6 +21,64 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service docsv_row_headers.index_with { |header| attrs[header] }end+ context 'when importing measurements' do+ let(:product) { subject.process! }++ let(:row_data) do+ csv_row_hash(+ 'slug' => 'measured-kettle',+ 'name' => 'Measured Kettle',+ 'price' => '10.00',+ 'weight' => '19.8',+ 'weight_unit' => 'lb',+ 'width' => '13.8',+ 'height' => '15.7',+ 'depth' => '11.8',+ 'dimensions_unit' => 'in'+ )+ end++ before do+ %w[weight weight_unit width height depth dimensions_unit].each do |field|+ import.mappings.find_by(schema_field: field)&.update(file_column: field)+ end+ end++ # The units are stored, not just the numbers: read back through the model's+ # fallback they would answer the store's own unit either way, so an import+ # that dropped them looked correct everywhere except the editor, which+ # shows the raw column so a save cannot stamp one store's unit on a row.+ it 'stores the units the file declared alongside the measurements' do+ default_variant = product.default_variant++ expect(default_variant.weight.to_f).to eq 19.8+ expect(default_variant[:weight_unit]).to eq 'lb'+ expect(default_variant.width.to_f).to eq 13.8+ expect(default_variant.height.to_f).to eq 15.7+ expect(default_variant.depth.to_f).to eq 11.8+ expect(default_variant[:dimensions_unit]).to eq 'in'+ end++ context 'when the file declares no units' do+ let(:row_data) do+ csv_row_hash(+ 'slug' => 'unitless-kettle',+ 'name' => 'Unitless Kettle',+ 'price' => '10.00',+ 'weight' => '19.8',+ 'width' => '13.8'+ )+ end++ it 'leaves the columns blank rather than guessing' do+ default_variant = product.default_variant++ expect(default_variant[:weight_unit]).to be_nil+ expect(default_variant[:dimensions_unit]).to be_nil+ end+ end+ end+context 'when importing carton packing details' dolet!(:carton) { create(:package_type, store: store, kind: 'carton', name: 'Large carton') }let(:product) { subject.process! }