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 displaying / formatting dates in dashboard

Damian Legawiec2ad6162b0f81
diff --git a/packages/dashboard-core/src/lib/formatters.ts b/packages/dashboard-core/src/lib/formatters.ts
index e66795899f..96ea14495e 100644
--- a/packages/dashboard-core/src/lib/formatters.ts
+++ b/packages/dashboard-core/src/lib/formatters.ts
@@ -1,10 +1,16 @@
import type { Price } from '@spree/admin-sdk'
+import { parseISO } from 'date-fns'
+import { formatInTimeZone } from 'date-fns-tz'
export function formatPrice(price: Pick<Price, 'amount' | 'currency' | 'display_amount'> | null) {
if (!price) return '—'
return price.display_amount ?? `${price.currency} ${price.amount}`
}
+export function formatStoreDateTime(iso: string, timezone: string) {
+ return formatInTimeZone(parseISO(iso), timezone, 'PPP p')
+}
+
export function getInitials(fullName: string | null | undefined, fallback: string): string {
const parts = (fullName ?? '').trim().split(/\s+/).filter(Boolean)
if (parts.length === 0) return fallback.charAt(0)
diff --git a/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx b/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx
index 3757d096dd..68e5c518d1 100644
--- a/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx
+++ b/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx
@@ -3,14 +3,13 @@ import type { PriceList, PriceRule, ResourceTypeDefinition } from '@spree/admin-
import {
adminClient,
Can,
+ formatStoreDateTime,
PageHeader,
PreferencesForm,
ResourceMultiAutocomplete,
useStore,
} from '@spree/dashboard-core'
import { useConfirm } from '@spree/dashboard-ui'
-import { parseISO } from 'date-fns'
-import { formatInTimeZone } from 'date-fns-tz'
import {
CalendarOffIcon,
PauseIcon,
@@ -339,8 +338,6 @@ function ActivationButtons({ priceList }: { priceList: PriceList }) {
const deactivate = useDeactivatePriceList(priceList.id)
const isActive = priceList.status === 'active' || priceList.status === 'scheduled'
- const formatStoreDateTime = (iso: string) => formatInTimeZone(parseISO(iso), timezone, 'PPP p')
-
async function handleDeactivate() {
const isScheduled = priceList.status === 'scheduled'
const namespace = isScheduled
@@ -361,8 +358,8 @@ function ActivationButtons({ priceList }: { priceList: PriceList }) {
}
async function handleActivate(willSchedule: boolean) {
- const startsAt = priceList.starts_at ? formatStoreDateTime(priceList.starts_at) : ''
- const endsAt = priceList.ends_at ? formatStoreDateTime(priceList.ends_at) : ''
+ const startsAt = priceList.starts_at ? formatStoreDateTime(priceList.starts_at, timezone) : ''
+ const endsAt = priceList.ends_at ? formatStoreDateTime(priceList.ends_at, timezone) : ''
const ok = await confirm({
title: t(
willSchedule
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx
new file mode 100644
index 0000000000..734c5f104c
--- /dev/null
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx
@@ -0,0 +1,118 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import { mapSpreeErrorsToForm, PageHeader } from '@spree/dashboard-core'
+import {
+ Button,
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ Field,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ Input,
+ ResourceLayout,
+ Textarea,
+} from '@spree/dashboard-ui'
+import { createFileRoute, useNavigate } from '@tanstack/react-router'
+import { useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
+import { useChannels } from '@/hooks/use-channels'
+import { useCreateProduct } from '@/hooks/use-product'
+import { productFormSchema } from '@/schemas/product'
+
+export const Route = createFileRoute('/_authenticated/$storeId/products/new')({
+ component: NewProductPage,
+})
+
+type CreateValues = { name: string; description?: string }
+
+function NewProductPage() {
+ const { t } = useTranslation()
+ 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. Mirrors Shopify's autoPublish behavior on the Online
+ // Store channel — the merchant can untick channels post-create.
+ const defaultChannelId = channelsResponse?.data.find((c) => c.default)?.id
+
+ const form = useForm<CreateValues>({
+ resolver: zodResolver(productFormSchema.pick({ name: true, description: true })),
+ defaultValues: { name: '', description: '' },
+ })
+
+ async function onSubmit(values: CreateValues) {
+ try {
+ const payload: Record<string, unknown> = { ...values }
+ if (defaultChannelId) {
+ payload.product_publications = [{ channel_id: defaultChannelId }]
+ }
+ const product = await create.mutateAsync(payload)
+ navigate({
+ to: '/$storeId/products/$productId',
+ params: { storeId, productId: product.id },
+ })
+ } catch (err) {
+ if (mapSpreeErrorsToForm(err, form.setError)) return
+ toast.error(t('admin.pages.products.new.create_failed'))
+ }
+ }
+
+ const { errors } = form.formState
+
+ return (
+ <form onSubmit={form.handleSubmit(onSubmit)}>
+ <ResourceLayout
+ header={
+ <PageHeader
+ title={t('admin.pages.products.new.title')}
+ description={t('admin.pages.products.new.description')}
+ backTo="products"
+ actions={
+ <Button type="submit" size="sm" disabled={form.formState.isSubmitting}>
+ {t('admin.pages.products.new.save_label')}
+ </Button>
+ }
+ />
+ }
+ main={
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('admin.pages.products.section_basics')}</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="name">{t('admin.fields.product.name.label')}</FieldLabel>
+ <Input
+ id="name"
+ autoFocus
+ placeholder={t('admin.fields.product.name.placeholder')}
+ aria-invalid={!!errors.name || undefined}
+ {...form.register('name')}
+ />
+ <FieldError errors={[errors.name]} />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="description">
+ {t('admin.fields.product.description.label')}
+ </FieldLabel>
+ <Textarea
+ id="description"
+ rows={5}
+ placeholder={t('admin.fields.product.description.placeholder')}
+ {...form.register('description')}
+ />
+ </Field>
+ </FieldGroup>
+ </CardContent>
+ </Card>
+ }
+ />
+ </form>
+ )
+}
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx
new file mode 100644
index 0000000000..6fd0a0079d
--- /dev/null
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx
@@ -0,0 +1,353 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import type { Channel, ChannelCreateParams } from '@spree/admin-sdk'
+import {
+ adminClient,
+ Can,
+ mapSpreeErrorsToForm,
+ ResourceTable,
+ resourceSearchSchema,
+ Subject,
+ usePermissions,
+} from '@spree/dashboard-core'
+import {
+ Button,
+ Field,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ Input,
+ RowActions,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+ Switch,
+ useConfirm,
+ useRowClickBridge,
+} from '@spree/dashboard-ui'
+import { createFileRoute, useNavigate } from '@tanstack/react-router'
+import { PlusIcon } from 'lucide-react'
+import { useEffect } from 'react'
+import { Controller, type UseFormReturn, useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import { z } from 'zod/v4'
+import {
+ useChannel,
+ useCreateChannel,
+ useDeleteChannel,
+ useUpdateChannel,
+} from '@/hooks/use-channels'
+import {
+ CHANNEL_DEFAULTS,
+ type ChannelFormValues,
+ channelFormSchema,
+ channelValuesToParams,
+} from '@/schemas/channel'
+import '@/tables/channels'
+
+const channelsSearchSchema = resourceSearchSchema.extend({
+ edit: z.string().optional(),
+ new: z.coerce.boolean().optional(),
+})
+
+export const Route = createFileRoute('/_authenticated/$storeId/settings/channels')({
+ validateSearch: channelsSearchSchema,
+ component: ChannelsPage,
+})
+
+function ChannelsPage() {
+ const { t } = useTranslation()
+ const search = Route.useSearch() as z.infer<typeof channelsSearchSchema>
+ const navigate = useNavigate()
+ const confirm = useConfirm()
+ const deleteMutation = useDeleteChannel()
+ const { permissions } = usePermissions()
+
+ const editId = search.edit
+ const isCreating = !!search.new
+
+ const closeSheet = () =>
+ navigate({
+ search: (prev: Record<string, unknown>) => {
+ const { edit: _e, new: _n, ...rest } = prev
+ return rest as never
+ },
+ })
+
+ const openCreate = () =>
+ navigate({ search: (prev: Record<string, unknown>) => ({ ...prev, new: true }) as never })
+
+ const openEdit = (id: string) =>
+ navigate({ search: (prev: Record<string, unknown>) => ({ ...prev, edit: id }) as never })
+
+ useRowClickBridge('data-channel-id', openEdit)
+
+ async function handleDelete(channel: Channel) {
+ const ok = await confirm({
+ title: t('admin.pages.channels.delete_confirm.title'),
+ message: t('admin.pages.channels.delete_confirm.message', { name: channel.name ?? '' }),
+ variant: 'destructive',
+ confirmLabel: t('admin.actions.delete'),
+ })
+ if (!ok) return
+ await deleteMutation.mutateAsync(channel.id).catch(() => undefined)
+ }
+
+ return (
+ <>
+ <ResourceTable<Channel>
+ tableKey="channels"
+ queryKey="channels"
+ queryFn={(params) => adminClient.channels.list(params)}
+ searchParams={search}
+ rowActions={(channel) => (
+ <RowActions
+ actions={[
+ { key: 'edit', onSelect: () => openEdit(channel.id) },
+ {
+ key: 'delete',
+ destructive: true,
+ visible: permissions.can('destroy', Subject.Channel),
+ disabled: deleteMutation.isPending,
+ onSelect: () => handleDelete(channel),
+ },
+ ]}
+ />
+ )}
+ actions={
+ <Can I="create" a={Subject.Channel}>
+ <Button size="sm" className="h-[2.125rem]" onClick={openCreate}>
+ <PlusIcon className="size-4" />
+ {t('admin.pages.channels.add_cta')}
+ </Button>
+ </Can>
+ }
+ />
+
+ {isCreating && <CreateChannelSheet open onOpenChange={(o) => !o && closeSheet()} />}
+ {editId && <EditChannelSheet id={editId} open onOpenChange={(o) => !o && closeSheet()} />}
+ </>
+ )
+}
+
+// Mirrors ActiveSupport's +String#parameterize+: lowercase, ASCII-friendly,
+// hyphen-separated. Keeps the SPA preview in sync with what +normalizes :code+
+// produces on the model so users see the final slug as they type.
+function slugifyChannelCode(value: string): string {
+ return value
+ .normalize('NFKD')
+ .replace(/\p{M}/gu, '')
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+}
+
+function CreateChannelSheet({
+ open,
+ onOpenChange,
+}: {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ const createMutation = useCreateChannel()
+ const form = useForm<ChannelFormValues>({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ resolver: zodResolver(channelFormSchema) as any,
+ defaultValues: CHANNEL_DEFAULTS,
+ })
+
+ // Auto-derive +code+ from +name+ while the user hasn't touched +code+ yet.
+ // The watch stops mirroring as soon as the user edits +code+ directly, so
+ // we never clobber a deliberate value.
+ const name = form.watch('name')
+ useEffect(() => {
+ if (form.getFieldState('code').isDirty) return
+ form.setValue('code', slugifyChannelCode(name ?? ''))
+ }, [name, form])
+
+ async function onSubmit(values: ChannelFormValues) {
+ try {
+ await createMutation.mutateAsync(channelValuesToParams(values) as ChannelCreateParams)
+ form.reset(CHANNEL_DEFAULTS)
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
+ }
+
+ return (
+ <Sheet
+ open={open}
+ onOpenChange={(next) => {
+ if (!next) form.reset(CHANNEL_DEFAULTS)
+ onOpenChange(next)
+ }}
+ >
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>{t('admin.pages.channels.add_sheet_title')}</SheetTitle>
+ <SheetDescription>{t('admin.pages.channels.create_description')}</SheetDescription>
+ </SheetHeader>
+ <form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">
+ <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
+ <ChannelFormFields form={form} />
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => onOpenChange(false)}
+ disabled={form.formState.isSubmitting}
+ >
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button type="submit" size="sm" disabled={form.formState.isSubmitting}>
+ {form.formState.isSubmitting
+ ? t('admin.actions.creating')
+ : t('admin.pages.channels.create_label')}
+ </Button>
+ </SheetFooter>
+ </form>
+ </SheetContent>
+ </Sheet>
+ )
+}
+
+function EditChannelSheet({
+ id,
+ open,
+ onOpenChange,
+}: {
+ id: string
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ const { data: channel, isLoading } = useChannel(id)
+ const updateMutation = useUpdateChannel(id)
+
+ const form = useForm<ChannelFormValues>({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ resolver: zodResolver(channelFormSchema) as any,
+ defaultValues: CHANNEL_DEFAULTS,
+ })
+
+ useEffect(() => {
+ if (channel) {
+ form.reset({
+ name: channel.name,
+ code: channel.code,
+ active: channel.active,
+ })
+ }
+ }, [channel, form])
+
+ async function onSubmit(values: ChannelFormValues) {
+ try {
+ await updateMutation.mutateAsync(channelValuesToParams(values))
+ form.reset(values)
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
+ }
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>{channel?.name ?? t('admin.pages.channels.edit_sheet_title')}</SheetTitle>
+ <SheetDescription>{t('admin.pages.channels.edit_description')}</SheetDescription>
+ </SheetHeader>
+ {isLoading ? (
+ <div className="p-4 text-sm text-muted-foreground">{t('admin.common.loading')}</div>
+ ) : (
+ <form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">
+ <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
+ <ChannelFormFields form={form} />
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => onOpenChange(false)}
+ disabled={form.formState.isSubmitting}
+ >
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button
+ type="submit"
+ size="sm"
+ disabled={form.formState.isSubmitting || !form.formState.isDirty}
+ >
+ {form.formState.isSubmitting ? t('admin.actions.saving') : t('admin.actions.save')}
+ </Button>
+ </SheetFooter>
+ </form>
+ )}
+ </SheetContent>
+ </Sheet>
+ )
+}
+
+function ChannelFormFields({ form }: { form: UseFormReturn<ChannelFormValues> }) {
+ const { t } = useTranslation()
+ const { errors } = form.formState
+ return (
+ <FieldGroup>
+ {errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {errors.root.message}
+ </p>
+ )}
+ <Field>
+ <FieldLabel htmlFor="name">{t('admin.fields.name.label')}</FieldLabel>
+ <Input
+ id="name"
+ autoFocus
+ placeholder={t('admin.fields.channel.name.placeholder')}
+ aria-invalid={!!errors.name || undefined}
+ {...form.register('name')}
+ />
+ <FieldError errors={[errors.name]} />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="code">{t('admin.fields.channel.code.label')}</FieldLabel>
+ <Input
+ id="code"
+ placeholder={t('admin.fields.channel.code.placeholder')}
+ aria-invalid={!!errors.code || undefined}
+ {...form.register('code')}
+ />
+ <span className="text-xs text-muted-foreground">{t('admin.fields.channel.code.help')}</span>
+ <FieldError errors={[errors.code]} />
+ </Field>
+
+ <Field>
+ <div className="flex items-start justify-between gap-4">
+ <div className="flex flex-col">
+ <FieldLabel htmlFor="active" className="cursor-pointer">
+ {t('admin.fields.channel.active.label')}
+ </FieldLabel>
+ <span className="text-xs text-muted-foreground">
+ {t('admin.fields.channel.active.help')}
+ </span>
+ </div>
+ <Controller
+ name="active"
+ control={form.control}
+ render={({ field }) => (
+ <Switch id="active" checked={!!field.value} onCheckedChange={field.onChange} />
+ )}
+ />
+ </div>
+ </Field>
+ </FieldGroup>
+ )
+}
diff --git a/packages/dashboard/src/schemas/channel.ts b/packages/dashboard/src/schemas/channel.ts
new file mode 100644
index 0000000000..526d306e57
--- /dev/null
+++ b/packages/dashboard/src/schemas/channel.ts
@@ -0,0 +1,32 @@
+import type { ChannelCreateParams, ChannelUpdateParams } from '@spree/admin-sdk'
+import { requiredMessage } from '@spree/dashboard-ui'
+import { z } from 'zod/v4'
+
+export const channelFormSchema = z.object({
+ name: z.string().min(1, { error: requiredMessage('name') }),
+ code: z
+ .string()
+ .min(1, { error: requiredMessage('code') })
+ .regex(/^[a-z0-9_-]+$/i, {
+ error: 'Lowercase letters, numbers, hyphens, underscores only',
+ }),
+ active: z.boolean(),
+})
+
+export type ChannelFormValues = z.infer<typeof channelFormSchema>
+
+export const CHANNEL_DEFAULTS: ChannelFormValues = {
+ name: '',
+ code: '',
+ active: true,
+}
+
+export function channelValuesToParams(
+ v: ChannelFormValues,
+): ChannelCreateParams & ChannelUpdateParams {
+ return {
+ name: v.name,
+ code: v.code,
+ active: v.active,
+ }
+}
diff --git a/packages/dashboard/src/tables/channels.tsx b/packages/dashboard/src/tables/channels.tsx
new file mode 100644
index 0000000000..02695d6b05
--- /dev/null
+++ b/packages/dashboard/src/tables/channels.tsx
@@ -0,0 +1,48 @@
+import type { Channel } from '@spree/admin-sdk'
+import { defineTable } from '@spree/dashboard-core'
+import { ActiveBadge, ResourceNameCell } from '@spree/dashboard-ui'
+import { RadioTowerIcon } from 'lucide-react'
+
+defineTable<Channel>('channels', {
+ title: 'Channels',
+ searchParam: 'name_cont',
+ searchPlaceholder: 'Search by name…',
+ defaultSort: { field: 'name', direction: 'asc' },
+ emptyIcon: <RadioTowerIcon className="size-8 text-muted-foreground" />,
+ emptyMessage: 'No channels yet',
+ columns: [
+ {
+ key: 'name',
+ label: 'Name',
+ sortable: true,
+ filterable: true,
+ default: true,
+ render: (channel) => (
+ <ResourceNameCell
+ id={channel.id}
+ dataAttr="data-channel-id"
+ name={channel.name}
+ secondary={channel.code}
+ />
+ ),
+ },
+ {
+ key: 'code',
+ label: 'Code',
+ sortable: true,
+ filterable: true,
+ default: true,
+ className: 'text-sm text-muted-foreground',
+ render: (channel) => channel.code,
+ },
+ {
+ key: 'active',
+ label: 'Status',
+ sortable: false,
+ filterable: true,
+ filterType: 'boolean',
+ default: true,
+ render: (channel) => <ActiveBadge active={channel.active} />,
+ },
+ ],
+})
diff --git a/spree/admin/app/controllers/spree/admin/channels_controller.rb b/spree/admin/app/controllers/spree/admin/channels_controller.rb
new file mode 100644
index 0000000000..b7388f53d2
--- /dev/null
+++ b/spree/admin/app/controllers/spree/admin/channels_controller.rb
@@ -0,0 +1,13 @@
+module Spree
+ module Admin
+ class ChannelsController < ResourceController
+ include Spree::Admin::SettingsConcern
+
+ private
+
+ def permitted_resource_params
+ params.require(:channel).permit(permitted_channel_attributes)
+ end
+ end
+ end
+end
diff --git a/spree/admin/app/helpers/spree/admin/publishing_helper.rb b/spree/admin/app/helpers/spree/admin/publishing_helper.rb
new file mode 100644
index 0000000000..ef6b33ce79
--- /dev/null
+++ b/spree/admin/app/helpers/spree/admin/publishing_helper.rb
@@ -0,0 +1,73 @@
+# frozen_string_literal: true
+
+module Spree
+ module Admin
+ # Helpers for the product Publishing card in the Rails admin. Mirrors the
+ # SPA's publishing card (see packages/dashboard/src/components/spree/products/publishing-card.tsx):
+ # per-channel status is gated by product status — Draft/Archived products
+ # render every publication as +not_available+ regardless of window.
+ module PublishingHelper
+ # @param product_status [String] the product's status (draft/active/archived)
+ # @param publication [Spree::ProductPublication]
+ # @return [Symbol] one of :live, :scheduled, :hidden, :not_available
+ def publication_schedule_status(product_status, publication)
+ return :not_available unless product_status == 'active'
+
+ now = Time.current
+ return :hidden if publication.unpublished_at && publication.unpublished_at <= now
+ return :scheduled if publication.published_at && publication.published_at > now
+
+ :live
+ end
+
+ # Renders a colored dot + status label for a publication row.
+ def publication_status_badge(product_status, publication)
+ status = publication_schedule_status(product_status, publication)
+ dot_class = case status
+ when :live then 'bg-success'
+ when :scheduled then 'bg-warning'
+ else 'bg-secondary'
+ end
+
+ label = Spree.t("admin.publishing.status_#{status}")
+
+ content_tag(:span, class: 'd-inline-flex align-items-center gap-1 text-muted small') do
+ content_tag(:span, '', class: "publication-dot rounded-circle #{dot_class}",
+ style: 'display:inline-block; width:0.5rem; height:0.5rem;') +
+ content_tag(:span, label)
+ end
+ end
+
+ # One-line summary of the publication window in the store's timezone.
+ def publication_caption(product_status, publication, store)
+ status = publication_schedule_status(product_status, publication)
+ tz = ActiveSupport::TimeZone[store.preferred_timezone] || Time.zone
+
+ case status
+ when :not_available
+ Spree.t('admin.publishing.caption_not_available',
+ product_status: Spree.t("admin.products.status_options.#{product_status}", default: product_status.to_s.humanize))
+ when :hidden
+ Spree.t('admin.publishing.caption_unpublished',
+ date: l(publication.unpublished_at.in_time_zone(tz), format: :short))
+ when :scheduled
+ if publication.unpublished_at
+ Spree.t('admin.publishing.caption_window',
+ start: l(publication.published_at.in_time_zone(tz), format: :short),
+ end: l(publication.unpublished_at.in_time_zone(tz), format: :short))
+ else
+ Spree.t('admin.publishing.caption_scheduled',
+ date: l(publication.published_at.in_time_zone(tz), format: :short))
+ end
+ else # :live
+ if publication.unpublished_at
+ Spree.t('admin.publishing.caption_hidden_after',
+ date: l(publication.unpublished_at.in_time_zone(tz), format: :short))
+ else
+ Spree.t('admin.publishing.caption_live')
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/admin/app/javascript/spree/admin/controllers/product_publishing_controller.js b/spree/admin/app/javascript/spree/admin/controllers/product_publishing_controller.js
new file mode 100644
index 0000000000..3e0e4b8cbe
--- /dev/null
+++ b/spree/admin/app/javascript/spree/admin/controllers/product_publishing_controller.js
@@ -0,0 +1,11 @@
+import { Controller } from '@hotwired/stimulus'
+
+// Toggles the "Manage" channel-checkbox panel on the product Publishing card.
+// Pairs with spree/admin/app/views/spree/admin/products/form/_publishing.html.erb.
+export default class extends Controller {
+ static targets = ['manage']
+
+ toggleManage() {
+ this.manageTarget.classList.toggle('d-none')
+ }
+}
diff --git a/spree/admin/app/views/spree/admin/channels/_form.html.erb b/spree/admin/app/views/spree/admin/channels/_form.html.erb
new file mode 100644
index 0000000000..1417107484
--- /dev/null
+++ b/spree/admin/app/views/spree/admin/channels/_form.html.erb
@@ -0,0 +1,7 @@
+<div class="card mb-6">
+ <div class="card-body">
+ <%= f.spree_text_field :name, autofocus: f.object.new_record?, required: true %>
+ <%= f.spree_text_field :code, required: true, hint: Spree.t('admin.channels.code_hint') %>
+ <%= f.spree_check_box :active, label: Spree.t(:active) %>
+ </div>
+</div>
diff --git a/spree/admin/app/views/spree/admin/channels/edit.html.erb b/spree/admin/app/views/spree/admin/channels/edit.html.erb
new file mode 100644
index 0000000000..f5b8f8cb5d
--- /dev/null
+++ b/spree/admin/app/views/spree/admin/channels/edit.html.erb
@@ -0,0 +1 @@
+<%= render 'spree/admin/shared/edit_resource' %>
diff --git a/spree/admin/app/views/spree/admin/channels/index.html.erb b/spree/admin/app/views/spree/admin/channels/index.html.erb
new file mode 100644
index 0000000000..16df5727b7
--- /dev/null
+++ b/spree/admin/app/views/spree/admin/channels/index.html.erb
@@ -0,0 +1,12 @@
+<% content_for :page_title do %>
+ <%= Spree.t(:channels) %>
+<% end %>
+
+<% content_for :page_actions do %>
+ <%= render_admin_partials(:channels_actions_partials) %>
+ <%= link_to_with_icon 'plus', Spree.t(:new_channel), new_object_url, class: "btn btn-primary" if can? :create, Spree::Channel %>
+<% end %>
+
+<%= render_admin_partials(:channels_header_partials) %>
+
+<%= render_table @collection, :channels %>
diff --git a/spree/admin/app/views/spree/admin/channels/new.html.erb b/spree/admin/app/views/spree/admin/channels/new.html.erb
new file mode 100644
index 0000000000..65a817edc9
--- /dev/null
+++ b/spree/admin/app/views/spree/admin/channels/new.html.erb
@@ -0,0 +1 @@
+<%= render 'spree/admin/shared/new_resource' %>
diff --git a/spree/admin/app/views/spree/admin/products/form/_publishing.html.erb b/spree/admin/app/views/spree/admin/products/form/_publishing.html.erb
new file mode 100644
index 0000000000..5f38ec913e
--- /dev/null
+++ b/spree/admin/app/views/spree/admin/products/form/_publishing.html.erb
@@ -0,0 +1,124 @@
+<%#
+ Publishing card — mirrors the SPA's <PublishingCard> in
+ packages/dashboard/src/components/spree/products/publishing-card.tsx.
+
+ All channel attach/detach AND per-channel scheduling submit through the
+ same nested-attributes form (+product_publications_attributes+). Each row
+ in the Manage panel toggles the +_destroy+ flag on the corresponding
+ publication; unchecked rows for unattached channels send blank attrs that
+ the model's +reject_if+ discards.
+
+ Datetime inputs render values in the store's timezone since datetime-local
+ has no TZ awareness (same pattern as the legacy form/_status partial).
+%>
+
+<%
+ store_timezone = ActiveSupport::TimeZone[current_store.preferred_timezone] || Time.zone
+ to_store_local = ->(value) { value&.in_time_zone(store_timezone)&.strftime('%Y-%m-%dT%H:%M') }
+ tz_help = Spree.t('admin.datetime_field_timezone_help', zone: store_timezone.name)
+ store_channels = current_store.channels.order(:name).to_a
+ publications_by_channel = @product.product_publications.includes(:channel).index_by(&:channel_id)
+
+ # Build one record per store channel: the existing publication when
+ # attached, or a fresh ProductPublication when not. Stable channel-keyed
+ # indices keep the form params deterministic so checkbox toggles always
+ # reference the right slot.
+ channel_rows = store_channels.map do |channel|
+ publication = publications_by_channel[channel.id] ||
+ @product.product_publications.build(channel: channel)
+ [channel, publication]
+ end
+%>
+
+<div class="card mb-6" data-controller="product-publishing">
+ <div class="card-header d-flex align-items-center justify-content-between">
+ <h6 class="card-title mb-0"><%= Spree.t('admin.publishing.title') %></h6>
+ <% if store_channels.any? %>
+ <button type="button"
+ class="btn btn-sm btn-outline-secondary"
+ data-action="product-publishing#toggleManage">
+ <%= Spree.t('admin.publishing.manage_cta') %>
+ </button>
+ <% end %>
+ </div>
+
+ <div class="card-body">
+ <% if store_channels.empty? %>
+ <p class="text-xs text-muted mb-0"><%= Spree.t('admin.publishing.no_channels') %></p>
+ <% else %>
+ <%# ---- Manage panel (hidden by default) ---- %>
+ <div class="d-none flex flex-col gap-2 mb-3" data-product-publishing-target="manage">
+ <p class="text-xs text-muted mb-1"><%= Spree.t('admin.publishing.manage_description') %></p>
+ <% channel_rows.each_with_index do |(channel, publication), index| %>
+ <%= f.fields_for :product_publications, publication, child_index: index do |pf| %>
+ <%= pf.hidden_field :id if publication.persisted? %>
+ <%= pf.hidden_field :channel_id, value: channel.id %>
+ <label class="flex items-center gap-3 rounded border px-3 py-2 cursor-pointer hover:bg-gray-50 text-sm">
+ <%# The +_destroy+ hidden field defaults to 1 (= destroy/skip);
+ the checkbox flips it to 0 (= keep/upsert) when checked.
+ +include_hidden: false+ on the checkbox keeps Rails from
+ emitting its own competing hidden field. %>
+ <%= pf.hidden_field :_destroy, value: '1', id: nil %>
+ <%= pf.check_box :_destroy,
+ { checked: publication.persisted?,
+ class: 'form-check-input m-0',
+ include_hidden: false },
+ '0', '1' %>
+ <span class="flex-1"><%= channel.name %></span>
+ <% unless channel.active? %>
+ <span class="text-xs text-muted"><%= Spree.t('admin.publishing.inactive_marker') %></span>
+ <% end %>
+ </label>
+ <% end %>
+ <% end %>
+ </div>
+
+ <%# ---- Per-publication scheduling rows ---- %>
+ <% if publications_by_channel.empty? %>
+ <p class="text-xs text-muted mb-0"><%= Spree.t('admin.publishing.empty') %></p>
+ <% else %>
+ <% channel_rows.each_with_index do |(channel, publication), index| %>
+ <% next unless publication.persisted? %>
+ <%= f.fields_for :product_publications, publication, child_index: index do |pf| %>
+ <details class="publication-row group rounded -mx-2 px-2 hover:bg-gray-50">
+ <summary class="flex items-start justify-between gap-3 py-2 cursor-pointer" style="list-style: none;">
+ <div class="flex min-w-0 flex-1 flex-col gap-0.5">
+ <div class="flex items-center gap-2">
+ <span class="truncate text-sm font-medium"><%= channel.name %></span>
+ <%= publication_status_badge(@product.status, publication) %>
+ </div>
+ <span class="text-xs text-muted">
+ <%= publication_caption(@product.status, publication, current_store) %>
+ </span>
+ </div>
+ <span class="shrink-0 mt-1 opacity-0 transition-opacity group-hover:opacity-100 text-muted">
+ <%= icon('pencil', class: 'h-3.5 w-3.5') %>
+ </span>
+ </summary>
+ <div class="mt-2 ps-2 pb-2 flex flex-col gap-3">
+ <div>
+ <%= pf.label :published_at,
+ Spree.t('admin.publishing.published_at_label'),
+ class: 'form-label text-xs mb-1' %>
+ <%= pf.datetime_field :published_at,
+ value: to_store_local.call(publication.published_at),
+ class: 'form-control form-control-sm' %>
+ <small class="text-muted text-xs"><%= tz_help %></small>
+ </div>
+ <div>
+ <%= pf.label :unpublished_at,
+ Spree.t('admin.publishing.unpublished_at_label'),
+ class: 'form-label text-xs mb-1' %>
+ <%= pf.datetime_field :unpublished_at,
+ value: to_store_local.call(publication.unpublished_at),
+ class: 'form-control form-control-sm' %>
+ <small class="text-muted text-xs"><%= tz_help %></small>
+ </div>
+ </div>
+ </details>
+ <% end %>
+ <% end %>
+ <% end %>
+ <% end %>
+ </div>
+</div>
diff --git a/spree/admin/spec/helpers/spree/admin/publishing_helper_spec.rb b/spree/admin/spec/helpers/spree/admin/publishing_helper_spec.rb
new file mode 100644
index 0000000000..ceb597b74e
--- /dev/null
+++ b/spree/admin/spec/helpers/spree/admin/publishing_helper_spec.rb
@@ -0,0 +1,88 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Admin::PublishingHelper, type: :helper do
+ let(:store) { @default_store }
+ let(:channel) { store.default_channel }
+ let(:product) { create(:product, store: store, status: 'active') }
+ let(:publication) { product.product_publications.first }
+
+ describe '#publication_schedule_status' do
+ context 'when product status is not active' do
+ it 'returns :not_available for draft' do
+ expect(helper.publication_schedule_status('draft', publication)).to eq(:not_available)
+ end
+
+ it 'returns :not_available for archived' do
+ expect(helper.publication_schedule_status('archived', publication)).to eq(:not_available)
+ end
+ end
+
+ context 'when product is active' do
+ it 'returns :live when no window is set' do
+ publication.update!(published_at: nil, unpublished_at: nil)
+ expect(helper.publication_schedule_status('active', publication)).to eq(:live)
+ end
+
+ it 'returns :scheduled when published_at is in the future' do
+ publication.update!(published_at: 1.day.from_now)
+ expect(helper.publication_schedule_status('active', publication)).to eq(:scheduled)
+ end
+
+ it 'returns :hidden when unpublished_at is in the past' do
+ publication.update!(published_at: 2.days.ago, unpublished_at: 1.day.ago)
+ expect(helper.publication_schedule_status('active', publication)).to eq(:hidden)
+ end
+
+ it 'returns :live when within the window' do
+ publication.update!(published_at: 1.day.ago, unpublished_at: 1.day.from_now)
+ expect(helper.publication_schedule_status('active', publication)).to eq(:live)
+ end
+ end
+ end
+
+ describe '#publication_status_badge' do
+ it 'renders the label for the current status' do
+ publication.update!(published_at: nil, unpublished_at: nil)
+ expect(helper.publication_status_badge('active', publication)).to include(I18n.t('spree.admin.publishing.status_live'))
+ end
+
+ it 'falls back to :not_available when product is draft' do
+ expect(helper.publication_status_badge('draft', publication)).to include(I18n.t('spree.admin.publishing.status_not_available'))
+ end
+ end
+
+ describe '#publication_caption' do
+ it 'returns the draft caption when product is not active' do
+ caption = helper.publication_caption('draft', publication, store)
+ expect(caption).to match(/Draft/)
+ end
+
+ it 'returns the live caption when active and window is open' do
+ publication.update!(published_at: nil, unpublished_at: nil)
+ expect(helper.publication_caption('active', publication, store)).to eq(I18n.t('spree.admin.publishing.caption_live'))
+ end
+
+ it 'returns the scheduled caption with a date' do
+ future = 2.days.from_now
+ publication.update!(published_at: future, unpublished_at: nil)
+ caption = helper.publication_caption('active', publication, store)
+ expect(caption).to include(I18n.l(future.in_time_zone(store.preferred_timezone), format: :short))
+ end
+
+ it 'returns the window caption when both endpoints are set in the future' do
+ future_start = 1.day.from_now
+ future_end = 3.days.from_now
+ publication.update!(published_at: future_start, unpublished_at: future_end)
+ caption = helper.publication_caption('active', publication, store)
+ expect(caption).to include(I18n.l(future_start.in_time_zone(store.preferred_timezone), format: :short))
+ expect(caption).to include(I18n.l(future_end.in_time_zone(store.preferred_timezone), format: :short))
+ end
+
+ it 'returns the hidden_after caption when live but with an end date' do
+ future = 3.days.from_now
+ publication.update!(published_at: 1.day.ago, unpublished_at: future)
+ caption = helper.publication_caption('active', publication, store)
+ expect(caption).to include(I18n.l(future.in_time_zone(store.preferred_timezone), format: :short))
+ end
+ end
+end