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
Dashboard: when creating a new product automatically enable default channel (#14131)
Damian Legawiecb07d5efcc5b8
diff --git a/packages/dashboard/e2e/products-publishing.spec.ts b/packages/dashboard/e2e/products-publishing.spec.tsnew file mode 100644index 0000000000..3cdab37944--- /dev/null+++ b/packages/dashboard/e2e/products-publishing.spec.ts@@ -0,0 +1,181 @@+import { expect, type Page, test } from '@playwright/test'+import { FIXTURE_BULK_CHANNEL_NAME, gotoIndex, login } from './helpers'+import { PRODUCTS_PATH, publishingCard } from './products-helpers'++// Drive the New Product form just far enough to land on the edit page.+// The point of this spec is the Publishing card, not the rest of the form.+async function createMinimalProduct(page: Page, storeId: string, name: string): Promise<void> {+ await gotoIndex(page, PRODUCTS_PATH(storeId), /add product/i)+ await page.getByRole('button', { name: /add product/i }).click()+ await expect(page.getByRole('heading', { name: /^new product$/i })).toBeVisible()+ await page.getByLabel(/^name$/i).fill(name)+}++test.describe('product publishing', () => {+ test('new product seeds the default channel before save', async ({ page }) => {+ const creds = await login(page)+ const productName = `E2E Publish Default ${Date.now()}`++ // Land on /new with the form pristine — the Publishing card auto-seeds+ // the store's default channel ("Online Store") so merchants don't have+ // to open Manage before save. The seed runs via setValue with+ // shouldDirty:false, so the form stays pristine: Create button stays+ // disabled until the merchant types something, no Discard button, no+ // beforeunload warning.+ await gotoIndex(page, PRODUCTS_PATH(creds.store_id), /add product/i)+ await page.getByRole('button', { name: /add product/i }).click()+ await expect(page.getByRole('heading', { name: /^new product$/i })).toBeVisible()++ const card = publishingCard(page)+ await expect(card.getByText(/online store/i)).toBeVisible({ timeout: 15_000 })+ await expect(card.getByText(/not listed on any sales channel/i)).not.toBeVisible()++ // Form stays pristine after the seed: Create is disabled, no Discard.+ await expect(page.getByRole('button', { name: /^create product$/i })).toBeDisabled()+ await expect(page.getByRole('button', { name: /^discard$/i })).not.toBeVisible()++ // Now type a name → form is dirty → Create enables and we can submit.+ await page.getByLabel(/^name$/i).fill(productName)+ await page.getByRole('button', { name: /^create product$/i }).click()+ await expect(page).toHaveURL(new RegExp(`/${creds.store_id}/products/prod_[^/]+$`), {+ timeout: 30_000,+ })++ // The publication persisted — the edit page's Publishing card shows it.+ await expect(publishingCard(page).getByText(/online store/i)).toBeVisible({+ timeout: 15_000,+ })+ })++ test('merchant can add a second channel before save', async ({ page }) => {+ const creds = await login(page)+ const productName = `E2E Publish Add Channel ${Date.now()}`++ await createMinimalProduct(page, creds.store_id, productName)+ const card = publishingCard(page)+ await expect(card.getByText(/online store/i)).toBeVisible({ timeout: 15_000 })++ // Add the bulk channel via Manage.+ await card.getByRole('button', { name: /^manage$/i }).click()+ const sheet = page.getByRole('dialog')+ await expect(sheet.getByRole('heading', { name: /^manage sales channels$/i })).toBeVisible()+ await sheet.getByRole('button', { name: new RegExp(FIXTURE_BULK_CHANNEL_NAME, 'i') }).click()+ await sheet.getByRole('button', { name: /^done$/i }).click()++ // Both rows visible on the New Product page.+ await expect(card.getByText(/online store/i)).toBeVisible()+ await expect(card.getByText(new RegExp(FIXTURE_BULK_CHANNEL_NAME, 'i'))).toBeVisible()++ await page.getByRole('button', { name: /^create product$/i }).click()+ await expect(page).toHaveURL(new RegExp(`/${creds.store_id}/products/prod_[^/]+$`), {+ timeout: 30_000,+ })++ // Both publications survived the round-trip.+ const persistedCard = publishingCard(page)+ await expect(persistedCard.getByText(/online store/i)).toBeVisible({ timeout: 15_000 })+ await expect(persistedCard.getByText(new RegExp(FIXTURE_BULK_CHANNEL_NAME, 'i'))).toBeVisible()+ })++ test('merchant can untick the default channel and ship a no-channel product', async ({+ page,+ }) => {+ const creds = await login(page)+ const productName = `E2E Publish Untick Default ${Date.now()}`++ await createMinimalProduct(page, creds.store_id, productName)+ const card = publishingCard(page)+ await expect(card.getByText(/online store/i)).toBeVisible({ timeout: 15_000 })++ // Untick the default channel — the merchant deliberately wants the+ // product invisible on the storefront on first save.+ await card.getByRole('button', { name: /^manage$/i }).click()+ const sheet = page.getByRole('dialog')+ await sheet.getByRole('button', { name: /online store/i }).click()+ await sheet.getByRole('button', { name: /^done$/i }).click()++ await expect(card.getByText(/online store/i)).not.toBeVisible()+ await expect(card.getByText(/not listed on any sales channel/i)).toBeVisible()++ await page.getByRole('button', { name: /^create product$/i }).click()+ await expect(page).toHaveURL(new RegExp(`/${creds.store_id}/products/prod_[^/]+$`), {+ timeout: 30_000,+ })++ // No publication persisted — the untick decision held.+ await expect(publishingCard(page).getByText(/not listed on any sales channel/i)).toBeVisible({+ timeout: 15_000,+ })+ })++ test('merchant can schedule a publication window via the inline editor', async ({ page }) => {+ const creds = await login(page)+ const productName = `E2E Publish Schedule ${Date.now()}`++ // Save the product first — the schedule editor opens the same way pre-+ // and post-save, but the edit page is where merchants typically set a+ // publication window. Flip status to Active so scheduleStatus actually+ // computes from published_at (it short-circuits to "not_available"+ // while the product is Draft).+ await createMinimalProduct(page, creds.store_id, productName)+ await page.getByRole('button', { name: /^create product$/i }).click()+ await expect(page).toHaveURL(new RegExp(`/${creds.store_id}/products/prod_[^/]+$`), {+ timeout: 30_000,+ })++ // Switch status to Active.+ const statusCard = page+ .locator('[data-slot="card"]')+ .filter({ has: page.locator('[data-slot="card-title"]', { hasText: /^Status$/ }) })+ await statusCard.getByRole('combobox').click()+ await page.getByRole('option', { name: /^active$/i }).click()++ const edit = publishingCard(page)+ await expect(edit.getByText(/online store/i)).toBeVisible({ timeout: 15_000 })+ // With Active status + no published_at, the default channel row is "live".+ await expect(edit.getByText(/^live$/i)).toBeVisible({ timeout: 5_000 })++ // Open the inline editor by clicking the channel row.+ await edit.getByRole('button', { name: /online store/i }).click()++ // Scope to the "Publish from" field row (a <Field> renders as a+ // role=group with the FieldLabel text inside) so the picker is+ // unambiguous even if the placeholder copy ("Live immediately") is+ // reworded in en.json — the FieldLabel is the stable anchor.+ const publishedAtField = edit.getByRole('group').filter({ hasText: /^publish from/i })+ await publishedAtField.getByRole('button').first().click()++ const calendarDialog = page.getByRole('dialog')+ await expect(calendarDialog).toBeVisible({ timeout: 5_000 })++ // Advance one month so the day we pick is unambiguously in the future,+ // regardless of when in the current month the spec runs. Without this+ // step, picking `.last()` on a month-end Saturday selects today (the+ // calendar's last cell IS today), and the DatePicker emits midnight+ // today — scheduleStatus uses strict `>` against Date.now() so status+ // falls through to 'live' and the test flakes once or twice a year.+ await calendarDialog.getByRole('button', { name: /next month/i }).click()+ // Pick the 15th of the next month — middle of the row, guaranteed not+ // an outside day, guaranteed in the future, no edge-case math.+ // react-day-picker emits the day as a button inside the gridcell with+ // an aria-label like "Monday, January 15th, 2026"; filter by text 15.+ await calendarDialog.getByRole('gridcell', { name: '15' }).click()++ // Close the inline editor.+ await edit.getByRole('button', { name: /^done$/i }).click()++ // The chosen date is in the future → status flips to "scheduled".+ await expect(edit.getByText(/^scheduled$/i)).toBeVisible({ timeout: 5_000 })++ // Persist and reload — the schedule survives.+ await page.getByRole('button', { name: /save product/i }).click()+ await expect(page.getByRole('button', { name: /save product/i })).toBeDisabled({+ timeout: 30_000,+ })++ await page.reload()+ await expect(publishingCard(page).getByText(/^scheduled$/i)).toBeVisible({+ timeout: 15_000,+ })+ })+})diff --git a/packages/dashboard/src/components/spree/products/publishing-card.tsx b/packages/dashboard/src/components/spree/products/publishing-card.tsxindex 12f490696d..8ccb896923 100644--- a/packages/dashboard/src/components/spree/products/publishing-card.tsx+++ b/packages/dashboard/src/components/spree/products/publishing-card.tsx@@ -19,7 +19,7 @@ import {} from '@spree/dashboard-ui'import { parseISO } from 'date-fns'import { PencilIcon, SettingsIcon } from 'lucide-react'-import { useMemo, useState } from 'react'+import { useEffect, useMemo, useRef, useState } from 'react'import { Controller, type UseFormReturn, useFieldArray } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { useChannels } from '@/hooks/use-channels'@@ -44,7 +44,20 @@ function scheduleStatus(return 'live'}-export function PublishingCard({ form }: { form: ProductForm }) {+export function PublishingCard({+ form,+ seedDefaultChannel = false,+}: {+ form: ProductForm+ /**+ * On the New Product page, seed the store's default channel into the+ * publications array once channels resolve, so the merchant doesn't have+ * to open Manage before save. Only fires when the array is empty and+ * untouched. Default false: the edit page uses persisted publications+ * verbatim — no auto-seeding.+ */+ seedDefaultChannel?: boolean+}) {const { t } = useTranslation()const [manageOpen, setManageOpen] = useState(false)const [editingIndex, setEditingIndex] = useState<number | null>(null)@@ -59,6 +72,54 @@ export function PublishingCard({ form }: { form: ProductForm }) {keyName: '_key',})+ // Seed the default channel once. useFieldArray maintains its own+ // internal list of fields keyed by `_key`. Two pitfalls to avoid:+ // - `useFieldArray.append` unconditionally flips `isDirty=true`, which+ // would surface the Discard button, enable Save on an empty form,+ // and fire the beforeunload warning on mount.+ // - `form.setValue(name, ..., { shouldDirty: false })` doesn't emit a+ // dirty-fields event, but `form.formState.isDirty` is computed by+ // diffing current values against defaults — so the seeded array+ // still reads as dirty unless we update defaults too.+ //+ // Solution: `form.reset` with the new publications merged into the+ // CURRENT defaults (not current values). `keepDirtyValues: true`+ // preserves anything the merchant typed in the brief render window+ // before channels resolved, and keeps those fields marked dirty+ // against the new baseline. useFieldArray's array subscription picks+ // up the reset and updates its internal `fields` list correctly.+ //+ // Guard with a ref so the merchant unticking the seeded channel doesn't+ // re-add it on the next render.+ //+ // Filter on `active` so deactivated default channels don't auto-seed. A+ // merchant who flips Online Store inactive (e.g. during maintenance)+ // would otherwise get products published to a channel the storefront+ // filters out — invisible products without a warning in the admin.+ const defaultChannelId = channelsResponse?.data.find((c) => c.default && c.active)?.id+ const seededRef = useRef(false)+ useEffect(() => {+ if (!seedDefaultChannel) return+ if (seededRef.current) return+ if (!defaultChannelId) return+ seededRef.current = true+ if (publicationsArray.fields.length > 0) return+ const currentDefaults = form.formState.defaultValues ?? {}+ form.reset(+ {+ ...currentDefaults,+ product_publications: [+ {+ channel_id: defaultChannelId,+ published_at: null,+ unpublished_at: null,+ },+ ],+ } as ProductFormValues,+ { keepDirtyValues: true },+ )+ }, [seedDefaultChannel, defaultChannelId, publicationsArray, form])+const channelName = (id: string) => channelsById.get(id)?.name ?? channelsById.get(id)?.code ?? idreturn (diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsxindex dbc1159ed1..2eeea5b6c2 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx@@ -3,7 +3,6 @@ import { type ProductCreateParams, SpreeError } from '@spree/admin-sdk'import { mapSpreeErrorsToForm, PageHeader } from '@spree/dashboard-core'import { FormActions, ResourceLayout, useFormSubmitShortcut } from '@spree/dashboard-ui'import { createFileRoute, useNavigate } from '@tanstack/react-router'-import { useEffect } from 'react'import { useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { toast } from 'sonner'@@ -23,7 +22,6 @@ import {VariantsCard,} from '@/components/spree/products/product-form-cards'import { PublishingCard } from '@/components/spree/products/publishing-card'-import { useChannels } from '@/hooks/use-channels'import { useCreateProduct } from '@/hooks/use-product'import {isPlaceholderDefaultVariant,@@ -42,33 +40,13 @@ function NewProductPage() {const { storeId } = Route.useParams()const navigate = useNavigate()const create = useCreateProduct()- const { data: channelsResponse } = useChannels()- // Pre-select the store's default channel so a freshly-created product is- // visible on the storefront without the merchant having to open the- // Publishing card. Merchant can untick channels post-create.- const defaultChannelId = channelsResponse?.data.find((c) => c.default)?.idconst form = useForm<ProductFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-anyresolver: zodResolver(productFormSchema) as any,- defaultValues: {- ...newProductFormDefaults(),- // Seed the default channel publication so merchants don't have to- // open Publishing on every new product.- ...(defaultChannelId ? { product_publications: [{ channel_id: defaultChannelId }] } : {}),- },+ defaultValues: newProductFormDefaults(),})- // If channels arrive after first render, seed the default-channel- // publication once. Skip if the merchant has already touched the array- // (we'd otherwise stomp on their edit).- useEffect(() => {- if (!defaultChannelId) return- const current = form.getValues('product_publications') ?? []- if (current.length > 0) return- form.setValue('product_publications', [{ channel_id: defaultChannelId }])- }, [defaultChannelId, form])-const onSubmit = async (data: ProductFormValues) => {const { variants, custom_fields, media, ...rest } = data@@ -202,7 +180,7 @@ function NewProductPage() {sidebar={<><StatusCard form={form} />- <PublishingCard form={form} />+ <PublishingCard form={form} seedDefaultChannel /><CategorizationCard form={form} /><TaxCard form={form} /><SEOCard form={form} />