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.

18.8 KB
Raw Blame
import { zodResolver } from '@hookform/resolvers/zod'
import type { Catalog, Channel, ChannelCreateParams } from '@spree/admin-sdk'
import {
  adminClient,
  Can,
  extensionFormValues,
  extensionSubmitValues,
  HostFormSlot,
  mapSpreeErrorsToForm,
  ResourceCombobox,
  ResourceTable,
  resourceSearchSchema,
  Subject,
  usePermissions,
  useStockLocations,
  useStore,
} from '@spree/dashboard-core'
import {
  Button,
  Field,
  FieldError,
  FieldGroup,
  FieldLabel,
  Input,
  RowActions,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  Sheet,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
  Switch,
  useConfirm,
  useRowClickBridge,
} from '@spree/dashboard-ui'
import { PlusIcon } from '@spree/dashboard-ui/icons'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useEffect, useState } from 'react'
import { Controller, type UseFormReturn, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { z } from 'zod/v4'
import { OrderRoutingRulesSection } from '../../../../components/spree/order-routing-rules-section'
import { StockLocationScopeField } from '../../../../components/spree/shipping/stock-location-scope-field'
import {
  useChannel,
  useCreateChannel,
  useDeleteChannel,
  useUpdateChannel,
} from '../../../../hooks/use-channels'
import { slugify } from '../../../../lib/slugify'
import {
  CHANNEL_DEFAULTS,
  type ChannelFormValues,
  channelFormSchema,
  channelValuesToParams,
  GUEST_CHECKOUT_VALUES,
  ORDER_ROUTING_STRATEGY_VALUES,
  RULES_ORDER_ROUTING_STRATEGY,
  STOREFRONT_ACCESS_VALUES,
} 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) && !channel.default,
                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()} />}
    </>
  )
}

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, ...extensionFormValues('channel', null) },
  })

  // 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', slugify(name ?? ''))
  }, [name, form])

  async function onSubmit(values: ChannelFormValues) {
    try {
      await createMutation.mutateAsync({
        ...(channelValuesToParams(values) as ChannelCreateParams),
        ...extensionSubmitValues('channel', form),
      })
      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} />
            <HostFormSlot
              form={form}
              name="channel.form_fields"
              context={{ channel: undefined, mode: 'new' }}
            />
          </div>
          <SheetFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={form.formState.isSubmitting}
            >
              {t('admin.actions.cancel')}
            </Button>
            <Button type="submit" 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 { store } = useStore()

  const form = useForm<ChannelFormValues>({
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    resolver: zodResolver(channelFormSchema) as any,
    defaultValues: CHANNEL_DEFAULTS,
  })

  // The rules editor only makes sense under the Rules strategy. Resolve the
  // effective strategy live from the (unsaved) select value, falling back to
  // the store-level preference for the "inherit" option.
  const strategyOverride = form.watch('order_routing_strategy')
  const effectiveStrategy =
    strategyOverride || store?.order_routing_strategy || RULES_ORDER_ROUTING_STRATEGY

  useEffect(() => {
    if (channel) {
      form.reset({
        name: channel.name,
        code: channel.code,
        active: channel.active,
        default: channel.default,
        order_routing_strategy: channel.order_routing_strategy ?? '',
        storefront_access: channel.storefront_access ?? '',
        guest_checkout: channel.guest_checkout == null ? '' : String(channel.guest_checkout),
        default_catalog_id: channel.default_catalog_id ?? '',
        stock_location_ids: channel.stock_location_ids ?? [],
        ...extensionFormValues('channel', channel),
      })
    }
  }, [channel, form])

  async function onSubmit(values: ChannelFormValues) {
    try {
      await updateMutation.mutateAsync({
        ...channelValuesToParams(values),
        ...extensionSubmitValues('channel', form),
      })
      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} />
              <HostFormSlot
                form={form}
                name="channel.form_fields"
                context={{ channel, mode: 'edit' }}
              />
              {effectiveStrategy === RULES_ORDER_ROUTING_STRATEGY && (
                <OrderRoutingRulesSection channelId={id} />
              )}
            </div>
            <SheetFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => onOpenChange(false)}
                disabled={form.formState.isSubmitting}
              >
                {t('admin.actions.cancel')}
              </Button>
              <Button
                type="submit"
                disabled={form.formState.isSubmitting || !form.formState.isDirty}
              >
                {form.formState.isSubmitting ? t('admin.actions.saving') : t('admin.actions.save')}
              </Button>
            </SheetFooter>
          </form>
        )}
      </SheetContent>
    </Sheet>
  )
}

type ChannelSelectFieldName = 'order_routing_strategy' | 'storefront_access' | 'guest_checkout'

// One channel-preference <Select> that shares the "inherit from store" blank
// option. Builds its own option list from `values` + the i18n `scope`
// (`<scope>.label` / `.help` / `.inherit` / `.options.<value>`).
function InheritableSelectField({
  form,
  name,
  scope,
  values,
}: {
  form: UseFormReturn<ChannelFormValues>
  name: ChannelSelectFieldName
  scope: string
  values: readonly string[]
}) {
  const { t } = useTranslation()
  const error = form.formState.errors[name]
  const options = values.map((value) => ({
    value,
    label:
      value === ''
        ? t(`${scope}.inherit`)
        : t(`${scope}.options.${value}`, { defaultValue: value }),
  }))
  return (
    <Field>
      <FieldLabel htmlFor={name}>{t(`${scope}.label`)}</FieldLabel>
      <Controller
        name={name}
        control={form.control}
        render={({ field }) => (
          <Select items={options} value={field.value ?? ''} onValueChange={field.onChange}>
            <SelectTrigger id={name} className="w-full" aria-invalid={!!error || undefined}>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {options.map((o) => (
                <SelectItem key={o.value || 'inherit'} value={o.value}>
                  {o.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        )}
      />
      <span className="text-xs text-muted-foreground">{t(`${scope}.help`)}</span>
      <FieldError errors={[error]} />
    </Field>
  )
}

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>

      <Field>
        <div className="flex items-start justify-between gap-4">
          <div className="flex flex-col">
            <FieldLabel htmlFor="default" className="cursor-pointer">
              {t('admin.fields.channel.default.label')}
            </FieldLabel>
            <span className="text-xs text-muted-foreground">
              {t('admin.fields.channel.default.help')}
            </span>
          </div>
          <Controller
            name="default"
            control={form.control}
            render={({ field }) => (
              <Switch id="default" checked={!!field.value} onCheckedChange={field.onChange} />
            )}
          />
        </div>
      </Field>

      <InheritableSelectField
        form={form}
        name="order_routing_strategy"
        scope="admin.fields.channel.order_routing_strategy"
        values={ORDER_ROUTING_STRATEGY_VALUES}
      />

      <InheritableSelectField
        form={form}
        name="storefront_access"
        scope="admin.fields.channel.storefront_access"
        values={STOREFRONT_ACCESS_VALUES}
      />

      <InheritableSelectField
        form={form}
        name="guest_checkout"
        scope="admin.fields.channel.guest_checkout"
        values={GUEST_CHECKOUT_VALUES}
      />

      <DefaultCatalogField form={form} />

      <FulfillmentLocationsField form={form} />
    </FieldGroup>
  )
}

/**
 * What shoppers outside any company or customer-group catalog see on this
 * channel — the last branch of the visibility precedence, so a company buyer
 * sees their own catalogs instead of this one. A curated catalog here makes
 * the rest of the channel's range private; one with an empty assortment
 * prices only and hides nothing.
 */
function DefaultCatalogField({ form }: { form: UseFormReturn<ChannelFormValues> }) {
  const { t } = useTranslation()

  return (
    <Field>
      <FieldLabel htmlFor="channel-default-catalog">
        {t('admin.fields.channel.default_catalog.label')}
      </FieldLabel>
      <Controller
        name="default_catalog_id"
        control={form.control}
        render={({ field }) => (
          <ResourceCombobox<Catalog>
            id="channel-default-catalog"
            queryKey="channel-default-catalogs"
            search={(q) => adminClient.catalogs.list({ name_cont: q, limit: 10 })}
            hydrate={(ids) => adminClient.catalogs.list({ id_in: ids, limit: ids.length })}
            getOptionLabel={(catalog) => catalog.name}
            placeholder={t('admin.fields.channel.default_catalog.placeholder')}
            emptyText={t('admin.fields.channel.default_catalog.empty')}
            value={field.value || undefined}
            onChange={(id) => field.onChange(id ?? '')}
          />
        )}
      />
      <span className="text-xs text-muted-foreground">
        {t('admin.fields.channel.default_catalog.help')}
      </span>
    </Field>
  )
}

/**
 * Which warehouses and counters fulfill this channel's orders. Narrowing is
 * the exception — a channel serves every location of the store until the
 * merchant says otherwise, which is how the API reads an empty array.
 */
function FulfillmentLocationsField({ form }: { form: UseFormReturn<ChannelFormValues> }) {
  const { t } = useTranslation()
  const { data: stockLocations } = useStockLocations()

  const selectedIds = form.watch('stock_location_ids') ?? []
  const locations = stockLocations?.data ?? []

  // The radio reads the field rather than holding a second source of truth, so
  // a saved channel reopens on the branch it was left in.
  const [scope, setScope] = useState<'all' | 'selected'>(
    selectedIds.length > 0 ? 'selected' : 'all',
  )
  useEffect(() => {
    if (selectedIds.length > 0) setScope('selected')
  }, [selectedIds.length])

  return (
    <>
      <Field>
        <FieldLabel>{t('admin.fields.channel.fulfillment_locations.label')}</FieldLabel>
        <span className="text-xs text-muted-foreground">
          {t('admin.fields.channel.fulfillment_locations.help')}
        </span>
        <Controller
          name="stock_location_ids"
          control={form.control}
          render={({ field }) => (
            <StockLocationScopeField
              idPrefix="channel-locations"
              scope={scope}
              onScopeChange={(next) => {
                setScope(next)
                if (next === 'all') field.onChange([])
              }}
              locations={locations}
              selectedIds={field.value ?? []}
              onSelectedIdsChange={field.onChange}
              allLabel={t('admin.fields.channel.fulfillment_locations.all')}
              selectedLabel={t('admin.fields.channel.fulfillment_locations.selected')}
              emptyLabel={t('admin.delivery_profiles.detail.no_stock_locations')}
            />
          )}
        />
      </Field>

      {scope === 'selected' && selectedIds.length === 0 && (
        <p className="text-muted-foreground text-xs">
          {t('admin.fields.channel.fulfillment_locations.none_selected_hint')}
        </p>
      )}
    </>
  )
}