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 Create Line Items promotion action editor in dashboard (#14552)

Damian Legawiec0c088b971a24
diff --git a/packages/dashboard/e2e/promotions.spec.ts b/packages/dashboard/e2e/promotions.spec.ts
index 7f043b0a70..62ecb030e8 100644
--- a/packages/dashboard/e2e/promotions.spec.ts
+++ b/packages/dashboard/e2e/promotions.spec.ts
@@ -341,6 +341,26 @@ test.describe('promotions', () => {
await submitCreate(page, name)
})
+ test('creates a promotion with a Create Line Items action', async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)
+
+ const name = `E2E Line Items Promo ${Date.now()}`
+ await startNewPromotion(page, creds.store_id, name)
+
+ await pickAction(page, /^create line items$/i)
+ await expect(page.getByRole('heading', { name: /^create line items$/i })).toBeVisible({
+ timeout: 5_000,
+ })
+
+ await pickAutocompleteOption(page, /search variants by name or sku/i, FIXTURE_PROMO_PRODUCT)
+ await saveEditor(page)
+
+ await expect(page.getByText(/1 variants/i).first()).toBeVisible({ timeout: 5_000 })
+
+ await submitCreate(page, name)
+ })
+
test('deletes a promotion', async ({ page }) => {
const creds = await login(page)
await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)
diff --git a/packages/dashboard/src/components/spree/promotion-editors/action-create-line-items.tsx b/packages/dashboard/src/components/spree/promotion-editors/action-create-line-items.tsx
new file mode 100644
index 0000000000..a89d2e75f9
--- /dev/null
+++ b/packages/dashboard/src/components/spree/promotion-editors/action-create-line-items.tsx
@@ -0,0 +1,212 @@
+import type { Variant } from '@spree/admin-sdk'
+import { adminClient, formatPrice, ResourceCombobox } from '@spree/dashboard-core'
+import {
+ Button,
+ Field,
+ FieldGroup,
+ FieldLabel,
+ Input,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@spree/dashboard-ui'
+import { TrashIcon } from '@spree/dashboard-ui/icons'
+import { useQuery } from '@tanstack/react-query'
+import { useMemo, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { EditorShell } from './editor-shell'
+import type { PromotionActionEditorContext, PromotionActionLineItemParams } from './types'
+
+interface LineItemDraft extends PromotionActionLineItemParams {
+ variant?: Variant
+}
+
+export function CreateLineItemsActionEditor({
+ draft,
+ onSave,
+ onClose,
+}: PromotionActionEditorContext) {
+ const { t } = useTranslation()
+ const initialIds = useMemo(
+ () => (draft.line_items ?? []).map((row) => row.variant_id),
+ [draft.line_items],
+ )
+ const variantById = useRef(new Map<string, Variant>())
+
+ const { data: loadedVariants = [], isLoading: variantsLoading } = useQuery({
+ queryKey: ['promotion-create-line-items-variants', initialIds],
+ queryFn: async () => {
+ const variants = await Promise.all(
+ initialIds.map(async (id) => {
+ try {
+ return await adminClient.variants.get(id)
+ } catch {
+ return null
+ }
+ }),
+ )
+ for (const variant of variants) {
+ if (variant) variantById.current.set(variant.id, variant)
+ }
+ return variants.filter(Boolean) as Variant[]
+ },
+ enabled: initialIds.length > 0,
+ staleTime: Number.POSITIVE_INFINITY,
+ })
+
+ const [lineItems, setLineItems] = useState<LineItemDraft[]>(() =>
+ (draft.line_items ?? []).map((row) => ({
+ variant_id: row.variant_id,
+ quantity: row.quantity,
+ })),
+ )
+
+ const resolvedLineItems = useMemo(
+ () =>
+ lineItems.map((row) => ({
+ ...row,
+ variant:
+ row.variant ??
+ variantById.current.get(row.variant_id) ??
+ loadedVariants.find((variant) => variant.id === row.variant_id),
+ })),
+ [lineItems, loadedVariants],
+ )
+
+ function addVariant(variant: Variant) {
+ setLineItems((current) => {
+ const existing = current.find((row) => row.variant_id === variant.id)
+ if (existing) {
+ return current.map((row) =>
+ row.variant_id === variant.id ? { ...row, quantity: row.quantity + 1, variant } : row,
+ )
+ }
+ variantById.current.set(variant.id, variant)
+ return [...current, { variant_id: variant.id, quantity: 1, variant }]
+ })
+ }
+
+ function updateQuantity(variantId: string, quantity: number) {
+ const nextQuantity = Number.isFinite(quantity) && quantity > 0 ? Math.floor(quantity) : 1
+ setLineItems((current) =>
+ current.map((row) =>
+ row.variant_id === variantId ? { ...row, quantity: nextQuantity } : row,
+ ),
+ )
+ }
+
+ function removeVariant(variantId: string) {
+ setLineItems((current) => current.filter((row) => row.variant_id !== variantId))
+ }
+
+ function handleSave() {
+ onSave({
+ ...draft,
+ line_items: lineItems.map(({ variant_id, quantity }) => ({ variant_id, quantity })),
+ })
+ onClose()
+ }
+
+ return (
+ <EditorShell
+ onSave={handleSave}
+ onCancel={onClose}
+ pending={variantsLoading}
+ saveDisabled={lineItems.length === 0}
+ >
+ <p className="text-sm text-muted-foreground">
+ {t('admin.components.create_line_items_action_editor.description')}
+ </p>
+
+ {resolvedLineItems.length === 0 ? (
+ <p className="text-sm text-muted-foreground">
+ {t('admin.components.create_line_items_action_editor.empty')}
+ </p>
+ ) : (
+ <div className="overflow-x-auto">
+ <Table roundedBottom>
+ <TableHeader>
+ <TableRow>
+ <TableHead>{t('admin.orders.new.items_table.variant')}</TableHead>
+ <TableHead>{t('admin.orders.new.items_table.sku')}</TableHead>
+ <TableHead className="text-right">{t('admin.fields.quantity.label')}</TableHead>
+ <TableHead className="w-10" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {resolvedLineItems.map((row) => (
+ <TableRow key={row.variant_id}>
+ <TableCell className="font-medium">
+ {row.variant?.product_name ?? row.variant?.sku ?? row.variant_id}
+ </TableCell>
+ <TableCell className="text-muted-foreground">{row.variant?.sku ?? '—'}</TableCell>
+ <TableCell className="text-right">
+ <Input
+ type="number"
+ min={1}
+ value={row.quantity}
+ onChange={(event) =>
+ updateQuantity(row.variant_id, Number(event.target.value))
+ }
+ className="ml-auto w-20 text-right"
+ />
+ </TableCell>
+ <TableCell className="text-right">
+ <Button
+ type="button"
+ size="icon-xs"
+ variant="ghost"
+ onClick={() => removeVariant(row.variant_id)}
+ >
+ <TrashIcon className="size-4" />
+ <span className="sr-only">{t('admin.actions.remove')}</span>
+ </Button>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ )}
+
+ <FieldGroup>
+ <Field>
+ <FieldLabel>
+ {t('admin.components.create_line_items_action_editor.variant_label')}
+ </FieldLabel>
+ <ResourceCombobox<Variant>
+ queryKey="promotion-create-line-items-variant-picker"
+ value=""
+ onChange={(id) => {
+ const variant = id ? variantById.current.get(id) : undefined
+ if (variant) addVariant(variant)
+ }}
+ search={async (query) => {
+ const res = await adminClient.variants.list({ search: query, limit: 8 })
+ for (const variant of res.data) variantById.current.set(variant.id, variant)
+ return res
+ }}
+ hydrate={async () => ({ data: [] })}
+ getOptionLabel={(variant) => variant.product_name ?? variant.sku ?? variant.id}
+ renderOption={(variant) => (
+ <div className="flex flex-col">
+ <span className="font-medium">
+ {variant.product_name ?? variant.sku ?? variant.id}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {variant.options_text && <span>{variant.options_text} · </span>}
+ {t('admin.orders.detail.variant_search.sku_prefix')}: {variant.sku || '—'} ·{' '}
+ {formatPrice(variant.price)}
+ </span>
+ </div>
+ )}
+ placeholder={t('admin.components.create_line_items_action_editor.search_placeholder')}
+ />
+ </Field>
+ </FieldGroup>
+ </EditorShell>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/promotion-editors/register.ts b/packages/dashboard/src/components/spree/promotion-editors/register.ts
index 6715deaab0..9d1b361f1c 100644
--- a/packages/dashboard/src/components/spree/promotion-editors/register.ts
+++ b/packages/dashboard/src/components/spree/promotion-editors/register.ts
@@ -1,5 +1,6 @@
import { registerSlot } from '@spree/dashboard-core'
import { AdjustmentActionEditor } from './action-adjustment'
+import { CreateLineItemsActionEditor } from './action-create-line-items'
import { CategoryRuleEditor } from './rule-category'
import { ChannelRuleEditor } from './rule-channel'
import { CountryRuleEditor } from './rule-country'
@@ -68,3 +69,8 @@ registerSlot(actionFormSlot('create_item_adjustments'), {
id: 'builtin',
component: AdjustmentActionEditor,
})
+
+registerSlot(actionFormSlot('create_line_items'), {
+ id: 'builtin',
+ component: CreateLineItemsActionEditor,
+})
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 799dee2b1c..0ddc67b7eb 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -580,6 +580,12 @@
"select_calculator": "اختر آلة حاسبة",
"settings_label": "إعدادات الآلة الحاسبة"
},
+ "create_line_items_action_editor": {
+ "description": "عند تأهل العرض الترويجي، تُضاف هذه العناصر إلى السلة.",
+ "empty": "لا توجد متغيرات بعد. ابحث أدناه لإضافة واحد.",
+ "search_placeholder": "ابحث عن المتغيرات بالاسم أو SKU…",
+ "variant_label": "إضافة متغير"
+ },
"custom_fields": {
"default_resource": "السجلات",
"empty_description": "تتبّع تفاصيل منظمة مثل الخامة أو المقاس أو تعليمات العناية.",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 9ccef7e096..c044170965 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -573,6 +573,12 @@
"select_calculator": "Kalkulator auswählen",
"settings_label": "Kalkulator-Einstellungen"
},
+ "create_line_items_action_editor": {
+ "description": "Wenn die Promotion greift, werden diese Artikel dem Warenkorb hinzugefügt.",
+ "empty": "Noch keine Varianten. Suchen Sie unten, um eine hinzuzufügen.",
+ "search_placeholder": "Varianten nach Name oder SKU suchen…",
+ "variant_label": "Variante hinzufügen"
+ },
"custom_fields": {
"default_resource": "Datensätzen",
"empty_description": "Erfassen Sie strukturierte Details wie Material, Passform oder Pflegehinweise.",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index a5ce5920bd..7aa996474c 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -573,6 +573,12 @@
"select_calculator": "Select a calculator",
"settings_label": "Calculator settings"
},
+ "create_line_items_action_editor": {
+ "description": "When the promotion qualifies, these items are added to the cart.",
+ "empty": "No variants yet. Search below to add one.",
+ "search_placeholder": "Search variants by name or SKU…",
+ "variant_label": "Add variant"
+ },
"custom_fields": {
"default_resource": "records",
"empty_description": "Track structured details like material, fit, or care instructions.",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index acda5aba32..e07c7d0e51 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -573,6 +573,12 @@
"select_calculator": "Sélectionner un calculateur",
"settings_label": "Paramètres du calculateur"
},
+ "create_line_items_action_editor": {
+ "description": "Lorsque la promotion est éligible, ces articles sont ajoutés au panier.",
+ "empty": "Aucune variante pour l'instant. Recherchez ci-dessous pour en ajouter une.",
+ "search_placeholder": "Rechercher des variantes par nom ou SKU…",
+ "variant_label": "Ajouter une variante"
+ },
"custom_fields": {
"default_resource": "enregistrements",
"empty_description": "Suivez des détails structurés comme la matière, la coupe ou les instructions d’entretien.",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 0dfd20c328..9a1cdeac62 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -579,6 +579,12 @@
"select_calculator": "Wybierz kalkulator",
"settings_label": "Ustawienia kalkulatora"
},
+ "create_line_items_action_editor": {
+ "description": "Gdy promocja kwalifikuje się, te pozycje są dodawane do koszyka.",
+ "empty": "Brak wariantów. Wyszukaj poniżej, aby dodać.",
+ "search_placeholder": "Szukaj wariantów po nazwie lub SKU…",
+ "variant_label": "Dodaj wariant"
+ },
"custom_fields": {
"default_resource": "rekordy",
"empty_description": "Śledź ustrukturyzowane szczegóły, takie jak materiał, krój czy instrukcje pielęgnacji.",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 89a6dbdf34..3953657579 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -571,6 +571,12 @@
"select_calculator": "选择一个计算器",
"settings_label": "计算器设置"
},
+ "create_line_items_action_editor": {
+ "description": "当促销符合条件时,这些商品会加入购物车。",
+ "empty": "尚无变体。请在下方搜索以添加。",
+ "search_placeholder": "按名称或 SKU 搜索变体…",
+ "variant_label": "添加变体"
+ },
"custom_fields": {
"default_resource": "记录",
"empty_description": "记录结构化的详细信息,例如材质、版型或保养说明。",