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
Consolidate admin SPA routes under $storeId prefix
Damian Legawiec5f5b19679474
diff --git a/packages/admin/src/components/app-sidebar.tsx b/packages/admin/src/components/app-sidebar.tsxindex 98b4b5e681..e4ada08a46 100644--- a/packages/admin/src/components/app-sidebar.tsx+++ b/packages/admin/src/components/app-sidebar.tsx@@ -9,6 +9,7 @@ import {UsersIcon,} from 'lucide-react'import type { ComponentProps } from 'react'+import { useParams } from '@tanstack/react-router'import { NavMain } from '@/components/nav-main'import { NavUser } from '@/components/nav-user'import { StoreSwitcher } from '@/components/store-switcher'@@ -21,63 +22,71 @@ export type NavItem = {items?: { title: string; url: string }[]}-const navigation: NavItem[] = [- {- title: 'Home',- url: '/',- icon: HomeIcon,- },- {- title: 'Orders',- url: '/orders',- icon: InboxIcon,- items: [{ title: 'Draft Orders', url: '/orders/drafts' }],- },- {- title: 'Products',- url: '/products',- icon: PackageIcon,- items: [- { title: 'Price Lists', url: '/products/price-lists' },- { title: 'Stock', url: '/products/stock' },- { title: 'Categories', url: '/products/categories' },- { title: 'Options', url: '/products/options' },- ],- },- {- title: 'Customers',- url: '/customers',- icon: UsersIcon,- },- {- title: 'Promotions',- url: '/promotions',- icon: TagIcon,- items: [{ title: 'Gift Cards', url: '/promotions/gift-cards' }],- },- {- title: 'Reports',- url: '/reports',- icon: BarChart3Icon,- },-]+function buildNavigation(storeId: string): NavItem[] {+ const p = `/${storeId}`+ return [+ {+ title: 'Home',+ url: p,+ icon: HomeIcon,+ },+ {+ title: 'Orders',+ url: `${p}/orders`,+ icon: InboxIcon,+ items: [{ title: 'Draft Orders', url: `${p}/orders/drafts` }],+ },+ {+ title: 'Products',+ url: `${p}/products`,+ icon: PackageIcon,+ items: [+ { title: 'Price Lists', url: `${p}/products/price-lists` },+ { title: 'Stock', url: `${p}/products/stock` },+ { title: 'Categories', url: `${p}/products/categories` },+ { title: 'Options', url: `${p}/products/options` },+ ],+ },+ {+ title: 'Customers',+ url: `${p}/customers`,+ icon: UsersIcon,+ },+ {+ title: 'Promotions',+ url: `${p}/promotions`,+ icon: TagIcon,+ items: [{ title: 'Gift Cards', url: `${p}/promotions/gift-cards` }],+ },+ {+ title: 'Reports',+ url: `${p}/reports`,+ icon: BarChart3Icon,+ },+ ]+}-const bottomNavigation: NavItem[] = [- {- title: 'Settings',- url: '/settings',- icon: SettingsIcon,- },-]+function buildBottomNavigation(storeId: string): NavItem[] {+ return [+ {+ title: 'Settings',+ url: `/${storeId}/settings`,+ icon: SettingsIcon,+ },+ ]+}export function AppSidebar(props: ComponentProps<typeof Sidebar>) {+ const { storeId } = useParams({ strict: false }) as { storeId?: string }+ const id = storeId || 'default'+return (<Sidebar collapsible="icon" {...props}><SidebarHeader><StoreSwitcher /></SidebarHeader><SidebarContent>- <NavMain items={navigation} bottomItems={bottomNavigation} />+ <NavMain items={buildNavigation(id)} bottomItems={buildBottomNavigation(id)} /></SidebarContent><SidebarFooter><NavUser />diff --git a/packages/admin/src/components/nav-main.tsx b/packages/admin/src/components/nav-main.tsxindex bb769f54bc..b83d46efe1 100644--- a/packages/admin/src/components/nav-main.tsx+++ b/packages/admin/src/components/nav-main.tsx@@ -82,9 +82,11 @@ function NavItemContent({currentPath: string;isCollapsed: boolean;}) {- const isExactActive = currentPath === item.url;+ const isExactActive = currentPath === item.url || currentPath === item.url + '/';+ // Only prefix-match for items with a sub-path after the storeId segment (e.g. /store_abc/orders)+ const hasSubPath = item.url.split('/').filter(Boolean).length > 1;const isActive =- isExactActive || (item.url !== "/" && currentPath.startsWith(item.url));+ isExactActive || (hasSubPath && currentPath.startsWith(item.url));const hasActiveChild = item.items?.some((sub) => currentPath === sub.url || currentPath.startsWith(sub.url),);diff --git a/packages/admin/src/routeTree.gen.ts b/packages/admin/src/routeTree.gen.tsindex b9121ac6d0..43d7f9b7ff 100644--- a/packages/admin/src/routeTree.gen.ts+++ b/packages/admin/src/routeTree.gen.ts@@ -13,12 +13,7 @@ import { Route as LoginRouteImport } from './routes/login'import { Route as AuthenticatedRouteImport } from './routes/_authenticated'import { Route as AuthenticatedIndexRouteImport } from './routes/_authenticated/index'import { Route as AuthenticatedStoreIdRouteImport } from './routes/_authenticated/$storeId'-import { Route as AuthenticatedProductsIndexRouteImport } from './routes/_authenticated/products/index'-import { Route as AuthenticatedOrdersIndexRouteImport } from './routes/_authenticated/orders/index'import { Route as AuthenticatedStoreIdIndexRouteImport } from './routes/_authenticated/$storeId/index'-import { Route as AuthenticatedProductsProductIdRouteImport } from './routes/_authenticated/products/$productId'-import { Route as AuthenticatedOrdersDraftsRouteImport } from './routes/_authenticated/orders/drafts'-import { Route as AuthenticatedOrdersOrderIdRouteImport } from './routes/_authenticated/orders/$orderId'import { Route as AuthenticatedStoreIdProductsIndexRouteImport } from './routes/_authenticated/$storeId/products/index'import { Route as AuthenticatedStoreIdOrdersIndexRouteImport } from './routes/_authenticated/$storeId/orders/index'import { Route as AuthenticatedStoreIdProductsProductIdRouteImport } from './routes/_authenticated/$storeId/products/$productId'@@ -44,42 +39,12 @@ const AuthenticatedStoreIdRoute = AuthenticatedStoreIdRouteImport.update({path: '/$storeId',getParentRoute: () => AuthenticatedRoute,} as any)-const AuthenticatedProductsIndexRoute =- AuthenticatedProductsIndexRouteImport.update({- id: '/products/',- path: '/products/',- getParentRoute: () => AuthenticatedRoute,- } as any)-const AuthenticatedOrdersIndexRoute =- AuthenticatedOrdersIndexRouteImport.update({- id: '/orders/',- path: '/orders/',- getParentRoute: () => AuthenticatedRoute,- } as any)const AuthenticatedStoreIdIndexRoute =AuthenticatedStoreIdIndexRouteImport.update({id: '/',path: '/',getParentRoute: () => AuthenticatedStoreIdRoute,} as any)-const AuthenticatedProductsProductIdRoute =- AuthenticatedProductsProductIdRouteImport.update({- id: '/products/$productId',- path: '/products/$productId',- getParentRoute: () => AuthenticatedRoute,- } as any)-const AuthenticatedOrdersDraftsRoute =- AuthenticatedOrdersDraftsRouteImport.update({- id: '/orders/drafts',- path: '/orders/drafts',- getParentRoute: () => AuthenticatedRoute,- } as any)-const AuthenticatedOrdersOrderIdRoute =- AuthenticatedOrdersOrderIdRouteImport.update({- id: '/orders/$orderId',- path: '/orders/$orderId',- getParentRoute: () => AuthenticatedRoute,- } as any)const AuthenticatedStoreIdProductsIndexRoute =AuthenticatedStoreIdProductsIndexRouteImport.update({id: '/products/',@@ -115,12 +80,7 @@ export interface FileRoutesByFullPath {'/': typeof AuthenticatedIndexRoute'/login': typeof LoginRoute'/$storeId': typeof AuthenticatedStoreIdRouteWithChildren- '/orders/$orderId': typeof AuthenticatedOrdersOrderIdRoute- '/orders/drafts': typeof AuthenticatedOrdersDraftsRoute- '/products/$productId': typeof AuthenticatedProductsProductIdRoute'/$storeId/': typeof AuthenticatedStoreIdIndexRoute- '/orders/': typeof AuthenticatedOrdersIndexRoute- '/products/': typeof AuthenticatedProductsIndexRoute'/$storeId/orders/$orderId': typeof AuthenticatedStoreIdOrdersOrderIdRoute'/$storeId/orders/drafts': typeof AuthenticatedStoreIdOrdersDraftsRoute'/$storeId/products/$productId': typeof AuthenticatedStoreIdProductsProductIdRoute@@ -130,12 +90,7 @@ export interface FileRoutesByFullPath {export interface FileRoutesByTo {'/login': typeof LoginRoute'/': typeof AuthenticatedIndexRoute- '/orders/$orderId': typeof AuthenticatedOrdersOrderIdRoute- '/orders/drafts': typeof AuthenticatedOrdersDraftsRoute- '/products/$productId': typeof AuthenticatedProductsProductIdRoute'/$storeId': typeof AuthenticatedStoreIdIndexRoute- '/orders': typeof AuthenticatedOrdersIndexRoute- '/products': typeof AuthenticatedProductsIndexRoute'/$storeId/orders/$orderId': typeof AuthenticatedStoreIdOrdersOrderIdRoute'/$storeId/orders/drafts': typeof AuthenticatedStoreIdOrdersDraftsRoute'/$storeId/products/$productId': typeof AuthenticatedStoreIdProductsProductIdRoute@@ -148,12 +103,7 @@ export interface FileRoutesById {'/login': typeof LoginRoute'/_authenticated/$storeId': typeof AuthenticatedStoreIdRouteWithChildren'/_authenticated/': typeof AuthenticatedIndexRoute- '/_authenticated/orders/$orderId': typeof AuthenticatedOrdersOrderIdRoute- '/_authenticated/orders/drafts': typeof AuthenticatedOrdersDraftsRoute- '/_authenticated/products/$productId': typeof AuthenticatedProductsProductIdRoute'/_authenticated/$storeId/': typeof AuthenticatedStoreIdIndexRoute- '/_authenticated/orders/': typeof AuthenticatedOrdersIndexRoute- '/_authenticated/products/': typeof AuthenticatedProductsIndexRoute'/_authenticated/$storeId/orders/$orderId': typeof AuthenticatedStoreIdOrdersOrderIdRoute'/_authenticated/$storeId/orders/drafts': typeof AuthenticatedStoreIdOrdersDraftsRoute'/_authenticated/$storeId/products/$productId': typeof AuthenticatedStoreIdProductsProductIdRoute@@ -166,12 +116,7 @@ export interface FileRouteTypes {| '/'| '/login'| '/$storeId'- | '/orders/$orderId'- | '/orders/drafts'- | '/products/$productId'| '/$storeId/'- | '/orders/'- | '/products/'| '/$storeId/orders/$orderId'| '/$storeId/orders/drafts'| '/$storeId/products/$productId'@@ -181,12 +126,7 @@ export interface FileRouteTypes {to:| '/login'| '/'- | '/orders/$orderId'- | '/orders/drafts'- | '/products/$productId'| '/$storeId'- | '/orders'- | '/products'| '/$storeId/orders/$orderId'| '/$storeId/orders/drafts'| '/$storeId/products/$productId'@@ -198,12 +138,7 @@ export interface FileRouteTypes {| '/login'| '/_authenticated/$storeId'| '/_authenticated/'- | '/_authenticated/orders/$orderId'- | '/_authenticated/orders/drafts'- | '/_authenticated/products/$productId'| '/_authenticated/$storeId/'- | '/_authenticated/orders/'- | '/_authenticated/products/'| '/_authenticated/$storeId/orders/$orderId'| '/_authenticated/$storeId/orders/drafts'| '/_authenticated/$storeId/products/$productId'@@ -246,20 +181,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AuthenticatedStoreIdRouteImportparentRoute: typeof AuthenticatedRoute}- '/_authenticated/products/': {- id: '/_authenticated/products/'- path: '/products'- fullPath: '/products/'- preLoaderRoute: typeof AuthenticatedProductsIndexRouteImport- parentRoute: typeof AuthenticatedRoute- }- '/_authenticated/orders/': {- id: '/_authenticated/orders/'- path: '/orders'- fullPath: '/orders/'- preLoaderRoute: typeof AuthenticatedOrdersIndexRouteImport- parentRoute: typeof AuthenticatedRoute- }'/_authenticated/$storeId/': {id: '/_authenticated/$storeId/'path: '/'@@ -267,27 +188,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AuthenticatedStoreIdIndexRouteImportparentRoute: typeof AuthenticatedStoreIdRoute}- '/_authenticated/products/$productId': {- id: '/_authenticated/products/$productId'- path: '/products/$productId'- fullPath: '/products/$productId'- preLoaderRoute: typeof AuthenticatedProductsProductIdRouteImport- parentRoute: typeof AuthenticatedRoute- }- '/_authenticated/orders/drafts': {- id: '/_authenticated/orders/drafts'- path: '/orders/drafts'- fullPath: '/orders/drafts'- preLoaderRoute: typeof AuthenticatedOrdersDraftsRouteImport- parentRoute: typeof AuthenticatedRoute- }- '/_authenticated/orders/$orderId': {- id: '/_authenticated/orders/$orderId'- path: '/orders/$orderId'- fullPath: '/orders/$orderId'- preLoaderRoute: typeof AuthenticatedOrdersOrderIdRouteImport- parentRoute: typeof AuthenticatedRoute- }'/_authenticated/$storeId/products/': {id: '/_authenticated/$storeId/products/'path: '/products'@@ -353,21 +253,11 @@ const AuthenticatedStoreIdRouteWithChildren =interface AuthenticatedRouteChildren {AuthenticatedStoreIdRoute: typeof AuthenticatedStoreIdRouteWithChildrenAuthenticatedIndexRoute: typeof AuthenticatedIndexRoute- AuthenticatedOrdersOrderIdRoute: typeof AuthenticatedOrdersOrderIdRoute- AuthenticatedOrdersDraftsRoute: typeof AuthenticatedOrdersDraftsRoute- AuthenticatedProductsProductIdRoute: typeof AuthenticatedProductsProductIdRoute- AuthenticatedOrdersIndexRoute: typeof AuthenticatedOrdersIndexRoute- AuthenticatedProductsIndexRoute: typeof AuthenticatedProductsIndexRoute}const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {AuthenticatedStoreIdRoute: AuthenticatedStoreIdRouteWithChildren,AuthenticatedIndexRoute: AuthenticatedIndexRoute,- AuthenticatedOrdersOrderIdRoute: AuthenticatedOrdersOrderIdRoute,- AuthenticatedOrdersDraftsRoute: AuthenticatedOrdersDraftsRoute,- AuthenticatedProductsProductIdRoute: AuthenticatedProductsProductIdRoute,- AuthenticatedOrdersIndexRoute: AuthenticatedOrdersIndexRoute,- AuthenticatedProductsIndexRoute: AuthenticatedProductsIndexRoute,}const AuthenticatedRouteWithChildren = AuthenticatedRoute._addFileChildren(diff --git a/packages/admin/src/routes/_authenticated/index.tsx b/packages/admin/src/routes/_authenticated/index.tsxindex 0d97ceef84..3e1b14810a 100644--- a/packages/admin/src/routes/_authenticated/index.tsx+++ b/packages/admin/src/routes/_authenticated/index.tsx@@ -1,14 +1,17 @@-import { createFileRoute } from '@tanstack/react-router'+import { createFileRoute, redirect } from '@tanstack/react-router'+import { adminClient } from '@/client'export const Route = createFileRoute('/_authenticated/')({- component: DashboardPage,+ beforeLoad: async () => {+ // Fetch the current store to get its prefixed ID for the URL+ try {+ const store = await adminClient.store.get()+ throw redirect({ to: '/$storeId', params: { storeId: store.id } })+ } catch (e) {+ // If it's already a redirect, re-throw+ if (e instanceof Error && 'to' in e) throw e+ // Fallback: use 'default' as store ID+ throw redirect({ to: '/$storeId', params: { storeId: 'default' } })+ }+ },})--function DashboardPage() {- return (- <div className="space-y-4">- <h1 className="text-2xl font-bold">Dashboard</h1>- <p className="text-muted-foreground">Welcome to the Spree Admin dashboard.</p>- </div>- )-}diff --git a/packages/admin/src/routes/_authenticated/orders/$orderId.tsx b/packages/admin/src/routes/_authenticated/orders/$orderId.tsxdeleted file mode 100644index 5bcf83ce02..0000000000--- a/packages/admin/src/routes/_authenticated/orders/$orderId.tsx+++ /dev/null@@ -1,1393 +0,0 @@-import type { Address, Order } from '@spree/admin-sdk'-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'-import { createFileRoute, Link } from '@tanstack/react-router'-import {- ArrowLeftIcon,- CreditCardIcon,- EllipsisVerticalIcon,- ExternalLinkIcon,- MailIcon,- MapPinIcon,- PackageIcon,- PencilIcon,- PlusIcon,- ShoppingCartIcon,- SlidersHorizontalIcon,- TrashIcon,- TruckIcon,- XCircleIcon,-} from 'lucide-react'-import { type FormEvent, useState } from 'react'-import { adminClient } from '@/client'-import { Badge, StatusBadge } from '@/components/ui/badge'-import { Button } from '@/components/ui/button'-import { Card, CardAction, CardContent, CardHeader, CardTitle } from '@/components/ui/card'-import {- Dialog,- DialogBody,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from '@/components/ui/dialog'-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from '@/components/ui/dropdown-menu'-import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'-import { Input } from '@/components/ui/input'-import { Separator } from '@/components/ui/separator'-import { Skeleton } from '@/components/ui/skeleton'-import { Textarea } from '@/components/ui/textarea'-import { cn } from '@/lib/utils'--export const Route = createFileRoute('/_authenticated/orders/$orderId')({- component: OrderDetailPage,-})--// ----------------------------------------------------------------------------// Data hooks-// -----------------------------------------------------------------------------function useOrder(orderId: string) {- return useQuery({- queryKey: ['order', orderId],- queryFn: () =>- adminClient.orders.get(orderId, {- expand: [- 'items',- 'fulfillments',- 'fulfillments.delivery_method',- 'fulfillments.stock_location',- 'payments',- 'payments.payment_method',- 'billing_address',- 'shipping_address',- 'customer',- 'adjustments',- ],- }),- })-}--/** Wrapper for mutations that invalidate the order query on success */-function useOrderMutation<TParams>(- orderId: string,- mutationFn: (params: TParams) => Promise<unknown>,-) {- const queryClient = useQueryClient()- return useMutation({- mutationFn,- onSuccess: () => queryClient.invalidateQueries({ queryKey: ['order', orderId] }),- })-}--// ----------------------------------------------------------------------------// Helpers-// -----------------------------------------------------------------------------function formatDate(iso: string | null) {- if (!iso) return '—'- return new Date(iso).toLocaleDateString('en-US', {- month: 'short',- day: 'numeric',- year: 'numeric',- hour: 'numeric',- minute: '2-digit',- })-}--function timeAgo(iso: string | null) {- if (!iso) return ''- const diff = Date.now() - new Date(iso).getTime()- const minutes = Math.floor(diff / 60000)- if (minutes < 60) return `${minutes}m ago`- const hours = Math.floor(minutes / 60)- if (hours < 24) return `${hours}h ago`- const days = Math.floor(hours / 24)- return `${days}d ago`-}--// ----------------------------------------------------------------------------// Page-// -----------------------------------------------------------------------------function OrderDetailPage() {- const { orderId } = Route.useParams()- const { data: order, isLoading, error } = useOrder(orderId)-- if (isLoading) return <OrderSkeleton />- if (error || !order) return <p className="text-destructive">Failed to load order {orderId}.</p>-- return (- <div className="flex flex-col gap-6">- <OrderHeader order={order} />-- <div className="grid grid-cols-12 gap-6">- {/* Main content */}- <div className="col-span-12 lg:col-span-8 flex flex-col gap-6">- <LineItemsCard order={order} />- <ShipmentsCard order={order} />- <PaymentsCard order={order} />- <AdjustmentsCard order={order} />- <OrderSummaryCard order={order} />- </div>-- {/* Sidebar */}- <div className="col-span-12 lg:col-span-4 flex flex-col gap-6">- <CustomerCard order={order} />- <SpecialInstructionsCard order={order} />- <InternalNoteCard order={order} />- </div>- </div>- </div>- )-}--// ----------------------------------------------------------------------------// Header-// -----------------------------------------------------------------------------function OrderHeader({ order }: { order: Order }) {- const { orderId } = Route.useParams()- const backUrl = order.completed_at ? '/orders' : '/orders/drafts'-- const cancelMutation = useOrderMutation(orderId, () =>- adminClient.orders.cancel(orderId),- )- const resendMutation = useOrderMutation(orderId, () =>- adminClient.orders.resendConfirmation(orderId),- )-- return (- <div className="flex items-center gap-3">- <Link- to={backUrl}- search={{ filters: [], columns: [] }}- className="inline-flex items-center justify-center rounded-lg p-1.5 text-muted-foreground hover:bg-gray-200/50 hover:text-foreground transition-colors"- >- <ArrowLeftIcon className="size-5" />- </Link>-- <h1 className="text-2xl font-medium">{order.number}</h1>-- {order.payment_status && <StatusBadge status={order.payment_status} />}- {order.fulfillment_status && <StatusBadge status={order.fulfillment_status} />}-- {order.completed_at && (- <span className="text-sm text-muted-foreground">- Completed {timeAgo(order.completed_at)}- </span>- )}-- <div className="ml-auto">- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button variant="outline" size="icon-sm">- <EllipsisVerticalIcon className="size-4" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- {order.completed_at && (- <>- <DropdownMenuItem>- <ExternalLinkIcon className="size-4" />- Preview Order- </DropdownMenuItem>- <DropdownMenuItem- onClick={() => resendMutation.mutate(undefined)}- disabled={resendMutation.isPending}- >- <MailIcon className="size-4" />- Resend Confirmation- </DropdownMenuItem>- <DropdownMenuSeparator />- </>- )}- {(order as any).state !== 'canceled' && (- <DropdownMenuItem- className="text-destructive focus:text-destructive"- onClick={() => {- if (window.confirm('Are you sure you want to cancel this order?')) {- cancelMutation.mutate(undefined)- }- }}- disabled={cancelMutation.isPending}- >- <XCircleIcon className="size-4" />- Cancel Order- </DropdownMenuItem>- )}- </DropdownMenuContent>- </DropdownMenu>- </div>- </div>- )-}--// ----------------------------------------------------------------------------// Line Items-// -----------------------------------------------------------------------------function AddLineItemDialog({- orderId,- open,- onOpenChange,-}: {- orderId: string- open: boolean- onOpenChange: (open: boolean) => void-}) {- const mutation = useOrderMutation(orderId, (params: { variant_id: string; quantity: number }) =>- adminClient.orders.lineItems.create(orderId, params),- )-- function handleSubmit(e: FormEvent<HTMLFormElement>) {- e.preventDefault()- const fd = new FormData(e.currentTarget)- mutation.mutate(- { variant_id: fd.get('variant_id') as string, quantity: Number(fd.get('quantity')) || 1 },- { onSuccess: () => onOpenChange(false) },- )- }-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent>- <DialogHeader>- <DialogTitle>Add Line Item</DialogTitle>- <DialogDescription>Add a product variant to this order.</DialogDescription>- </DialogHeader>- <form onSubmit={handleSubmit}>- <DialogBody>- <FieldGroup>- <Field>- <FieldLabel htmlFor="variant_id">Variant ID</FieldLabel>- <Input id="variant_id" name="variant_id" placeholder="variant_xxx" required />- </Field>- <Field>- <FieldLabel htmlFor="quantity">Quantity</FieldLabel>- <Input id="quantity" name="quantity" type="number" min={1} defaultValue={1} />- </Field>- </FieldGroup>- </DialogBody>- <DialogFooter>- <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>- Cancel- </Button>- <Button type="submit" disabled={mutation.isPending}>- {mutation.isPending ? 'Adding…' : 'Add Item'}- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>- )-}--function EditQuantityDialog({- orderId,- lineItemId,- currentQuantity,- open,- onOpenChange,-}: {- orderId: string- lineItemId: string- currentQuantity: number- open: boolean- onOpenChange: (open: boolean) => void-}) {- const mutation = useOrderMutation(orderId, (params: { quantity: number }) =>- adminClient.orders.lineItems.update(orderId, lineItemId, params),- )-- function handleSubmit(e: FormEvent<HTMLFormElement>) {- e.preventDefault()- const fd = new FormData(e.currentTarget)- mutation.mutate(- { quantity: Number(fd.get('quantity')) || 1 },- { onSuccess: () => onOpenChange(false) },- )- }-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent>- <DialogHeader>- <DialogTitle>Edit Quantity</DialogTitle>- <DialogDescription>Update the quantity for this line item.</DialogDescription>- </DialogHeader>- <form onSubmit={handleSubmit}>- <DialogBody>- <FieldGroup>- <Field>- <FieldLabel htmlFor="edit-quantity">Quantity</FieldLabel>- <Input- id="edit-quantity"- name="quantity"- type="number"- min={1}- defaultValue={currentQuantity}- />- </Field>- </FieldGroup>- </DialogBody>- <DialogFooter>- <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>- Cancel- </Button>- <Button type="submit" disabled={mutation.isPending}>- {mutation.isPending ? 'Saving…' : 'Save'}- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>- )-}--function LineItemsCard({ order }: { order: Order }) {- const { orderId } = Route.useParams()- const items = order.items ?? []- const [addOpen, setAddOpen] = useState(false)- const [editItem, setEditItem] = useState<{ id: string; quantity: number } | null>(null)-- const deleteMutation = useOrderMutation(orderId, (lineItemId: string) =>- adminClient.orders.lineItems.delete(orderId, lineItemId),- )-- return (- <>- <Card>- <CardHeader>- <CardTitle>- <ShoppingCartIcon className="size-4" />- Line Items- </CardTitle>- <CardAction className="flex items-center gap-2">- {items.length > 0 && <Badge variant="info">{items.length}</Badge>}- <Button size="sm" variant="secondary" onClick={() => setAddOpen(true)}>- <PlusIcon data-icon="inline-start" />- Add Item- </Button>- </CardAction>- </CardHeader>- {items.length > 0 ? (- <div className="overflow-x-auto">- <table className="w-full text-sm">- <thead>- <tr className="border-b bg-muted/50 text-muted-foreground">- <th className="p-3 pl-5 text-left font-normal">Item</th>- <th className="p-3 text-right font-normal">Price</th>- <th className="p-3 text-right font-normal">Qty</th>- <th className="p-3 text-right font-normal">Tax</th>- <th className="p-3 text-right font-normal">Discount</th>- <th className="p-3 text-right font-normal">Total</th>- <th className="p-3 pr-5 w-10" />- </tr>- </thead>- <tbody>- {items.map((item) => (- <tr key={item.id} className="border-b last:border-b-0">- <td className="p-3 pl-5">- <div className="flex items-center gap-3">- {item.thumbnail_url ? (- <img- src={item.thumbnail_url}- alt={item.name}- className="size-10 rounded-lg border object-cover"- />- ) : (- <div className="flex size-10 items-center justify-center rounded-lg border bg-muted">- <PackageIcon className="size-4 text-muted-foreground" />- </div>- )}- <div className="min-w-0">- <div className="truncate font-medium">{item.name}</div>- {item.options_text && (- <div className="truncate text-xs text-muted-foreground">- {item.options_text}- </div>- )}- </div>- </div>- </td>- <td className="p-3 text-right whitespace-nowrap">{item.display_price}</td>- <td className="p-3 text-right">{item.quantity}</td>- <td className="p-3 text-right whitespace-nowrap">- {item.display_additional_tax_total}- </td>- <td className="p-3 text-right whitespace-nowrap">- {Number.parseFloat(item.discount_total) !== 0 ? item.display_discount_total : '—'}- </td>- <td className="p-3 text-right font-medium whitespace-nowrap">- {item.display_total}- </td>- <td className="p-3 pr-5">- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button variant="ghost" size="icon-xs">- <EllipsisVerticalIcon className="size-4" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem- onClick={() => setEditItem({ id: item.id, quantity: item.quantity })}- >- <PencilIcon className="size-4" />- Edit Quantity- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem- className="text-destructive focus:text-destructive"- onClick={() => {- if (window.confirm('Remove this item from the order?')) {- deleteMutation.mutate(item.id)- }- }}- >- <TrashIcon className="size-4" />- Remove- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </td>- </tr>- ))}- </tbody>- </table>- </div>- ) : (- <CardContent>- <p className="text-center text-muted-foreground py-8">No line items</p>- </CardContent>- )}- </Card>-- <AddLineItemDialog orderId={orderId} open={addOpen} onOpenChange={setAddOpen} />-- {editItem && (- <EditQuantityDialog- orderId={orderId}- lineItemId={editItem.id}- currentQuantity={editItem.quantity}- open={!!editItem}- onOpenChange={(open) => !open && setEditItem(null)}- />- )}- </>- )-}--// ----------------------------------------------------------------------------// Shipments-// -----------------------------------------------------------------------------function EditTrackingDialog({- orderId,- shipmentId,- currentTracking,- open,- onOpenChange,-}: {- orderId: string- shipmentId: string- currentTracking: string | null- open: boolean- onOpenChange: (open: boolean) => void-}) {- const mutation = useOrderMutation(orderId, (params: { tracking: string }) =>- adminClient.orders.shipments.update(orderId, shipmentId, params),- )-- function handleSubmit(e: FormEvent<HTMLFormElement>) {- e.preventDefault()- const fd = new FormData(e.currentTarget)- mutation.mutate(- { tracking: fd.get('tracking') as string },- { onSuccess: () => onOpenChange(false) },- )- }-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent>- <DialogHeader>- <DialogTitle>Edit Tracking</DialogTitle>- <DialogDescription>Update the tracking number for this shipment.</DialogDescription>- </DialogHeader>- <form onSubmit={handleSubmit}>- <DialogBody>- <FieldGroup>- <Field>- <FieldLabel htmlFor="tracking">Tracking Number</FieldLabel>- <Input id="tracking" name="tracking" defaultValue={currentTracking ?? ''} />- </Field>- </FieldGroup>- </DialogBody>- <DialogFooter>- <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>- Cancel- </Button>- <Button type="submit" disabled={mutation.isPending}>- {mutation.isPending ? 'Saving…' : 'Save'}- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>- )-}--function ShipmentsCard({ order }: { order: Order }) {- const { orderId } = Route.useParams()- const fulfillments = order.fulfillments ?? []- const [editTracking, setEditTracking] = useState<{- id: string- tracking: string | null- } | null>(null)-- const shipMutation = useOrderMutation(orderId, (shipmentId: string) =>- adminClient.orders.shipments.ship(orderId, shipmentId),- )- const cancelShipmentMutation = useOrderMutation(orderId, (shipmentId: string) =>- adminClient.orders.shipments.cancel(orderId, shipmentId),- )-- if (fulfillments.length === 0) return null-- return (- <>- <Card>- <CardHeader>- <CardTitle>- <TruckIcon className="size-4" />- Shipments- </CardTitle>- <CardAction className="flex items-center gap-2">- <Badge variant="info">{fulfillments.length}</Badge>- {order.fulfillment_status && <StatusBadge status={order.fulfillment_status} />}- </CardAction>- </CardHeader>- <CardContent className="flex flex-col gap-4">- {fulfillments.map((shipment) => (- <div key={shipment.id} className="rounded-lg border p-4 flex flex-col gap-3">- <div className="flex items-center justify-between">- <div className="flex items-center gap-2">- <StatusBadge status={shipment.status} />- <span className="text-sm font-medium">{shipment.number}</span>- </div>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button variant="ghost" size="icon-xs">- <EllipsisVerticalIcon className="size-4" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem- onClick={() =>- setEditTracking({ id: shipment.id, tracking: shipment.tracking })- }- >- <PencilIcon className="size-4" />- {shipment.tracking ? 'Edit Tracking' : 'Add Tracking'}- </DropdownMenuItem>- {shipment.status === 'ready' && (- <DropdownMenuItem- onClick={() => {- if (window.confirm('Ship this shipment?')) {- shipMutation.mutate(shipment.id)- }- }}- >- <TruckIcon className="size-4" />- Ship- </DropdownMenuItem>- )}- {['pending', 'ready'].includes(shipment.status) && (- <>- <DropdownMenuSeparator />- <DropdownMenuItem- className="text-destructive focus:text-destructive"- onClick={() => {- if (window.confirm('Cancel this shipment?')) {- cancelShipmentMutation.mutate(shipment.id)- }- }}- >- <XCircleIcon className="size-4" />- Cancel Shipment- </DropdownMenuItem>- </>- )}- </DropdownMenuContent>- </DropdownMenu>- </div>-- {shipment.delivery_method && (- <div className="flex items-center justify-between text-sm">- <span className="text-muted-foreground">{shipment.delivery_method.name}</span>- <span>{shipment.display_cost}</span>- </div>- )}-- {shipment.stock_location && (- <div className="flex items-center gap-1.5 text-xs text-muted-foreground">- <MapPinIcon className="size-3" />- {shipment.stock_location.name}- </div>- )}-- {shipment.tracking && (- <div className="text-sm">- <span className="text-muted-foreground">Tracking: </span>- {shipment.tracking_url ? (- <a- href={shipment.tracking_url}- target="_blank"- rel="noopener noreferrer"- className="text-blue-600 hover:underline"- >- {shipment.tracking}- </a>- ) : (- <span>{shipment.tracking}</span>- )}- </div>- )}-- {shipment.fulfilled_at && (- <span className="text-xs text-muted-foreground">- Shipped {timeAgo(shipment.fulfilled_at)}- </span>- )}- </div>- ))}- </CardContent>- </Card>-- {editTracking && (- <EditTrackingDialog- orderId={orderId}- shipmentId={editTracking.id}- currentTracking={editTracking.tracking}- open={!!editTracking}- onOpenChange={(open) => !open && setEditTracking(null)}- />- )}- </>- )-}--// ----------------------------------------------------------------------------// Payments-// -----------------------------------------------------------------------------function PaymentsCard({ order }: { order: Order }) {- const { orderId } = Route.useParams()- const payments = order.payments ?? []-- const captureMutation = useOrderMutation(orderId, (paymentId: string) =>- adminClient.orders.payments.capture(orderId, paymentId),- )- const voidMutation = useOrderMutation(orderId, (paymentId: string) =>- adminClient.orders.payments.void(orderId, paymentId),- )-- if (payments.length === 0) return null-- return (- <Card>- <CardHeader>- <CardTitle>- <CreditCardIcon className="size-4" />- Payments- </CardTitle>- <CardAction className="flex items-center gap-2">- <Badge variant="info">{payments.length}</Badge>- {order.payment_status && <StatusBadge status={order.payment_status} />}- </CardAction>- </CardHeader>- <div className="overflow-x-auto">- <table className="w-full text-sm">- <thead>- <tr className="border-b bg-muted/50 text-muted-foreground">- <th className="p-3 pl-5 text-left font-normal">Number</th>- <th className="p-3 text-left font-normal">Method</th>- <th className="p-3 text-left font-normal">State</th>- <th className="p-3 text-right font-normal">Amount</th>- <th className="p-3 pr-5 w-10" />- </tr>- </thead>- <tbody>- {payments.map((payment) => (- <tr key={payment.id} className="border-b last:border-b-0">- <td className="p-3 pl-5 font-medium">{payment.number}</td>- <td className="p-3 text-muted-foreground">{payment.payment_method?.name ?? '—'}</td>- <td className="p-3">- <StatusBadge status={payment.status} />- </td>- <td className="p-3 text-right font-medium whitespace-nowrap">- {payment.display_amount}- </td>- <td className="p-3 pr-5">- {(payment.status === 'checkout' ||- payment.status === 'pending' ||- payment.status === 'completed') && (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button variant="ghost" size="icon-xs">- <EllipsisVerticalIcon className="size-4" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- {(payment.status === 'checkout' || payment.status === 'pending') && (- <DropdownMenuItem- onClick={() => {- if (window.confirm('Capture this payment?')) {- captureMutation.mutate(payment.id)- }- }}- >- <CreditCardIcon className="size-4" />- Capture- </DropdownMenuItem>- )}- {(payment.status === 'checkout' ||- payment.status === 'pending' ||- payment.status === 'completed') && (- <DropdownMenuItem- className="text-destructive focus:text-destructive"- onClick={() => {- if (window.confirm('Void this payment?')) {- voidMutation.mutate(payment.id)- }- }}- >- <XCircleIcon className="size-4" />- Void- </DropdownMenuItem>- )}- </DropdownMenuContent>- </DropdownMenu>- )}- </td>- </tr>- ))}- </tbody>- </table>- </div>- </Card>- )-}--// ----------------------------------------------------------------------------// Adjustments-// -----------------------------------------------------------------------------function AddAdjustmentDialog({- orderId,- open,- onOpenChange,-}: {- orderId: string- open: boolean- onOpenChange: (open: boolean) => void-}) {- const mutation = useOrderMutation(orderId, (params: { label: string; amount: number }) =>- adminClient.orders.adjustments.create(orderId, params),- )-- function handleSubmit(e: FormEvent<HTMLFormElement>) {- e.preventDefault()- const fd = new FormData(e.currentTarget)- mutation.mutate(- { label: fd.get('label') as string, amount: Number(fd.get('amount')) },- { onSuccess: () => onOpenChange(false) },- )- }-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent>- <DialogHeader>- <DialogTitle>Add Adjustment</DialogTitle>- <DialogDescription>- Add a manual adjustment to this order. Use a negative amount for discounts.- </DialogDescription>- </DialogHeader>- <form onSubmit={handleSubmit}>- <DialogBody>- <FieldGroup>- <Field>- <FieldLabel htmlFor="adj-label">Label</FieldLabel>- <Input id="adj-label" name="label" placeholder="e.g. Manual discount" required />- </Field>- <Field>- <FieldLabel htmlFor="adj-amount">Amount</FieldLabel>- <Input- id="adj-amount"- name="amount"- type="number"- step="0.01"- placeholder="-10.00"- required- />- </Field>- </FieldGroup>- </DialogBody>- <DialogFooter>- <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>- Cancel- </Button>- <Button type="submit" disabled={mutation.isPending}>- {mutation.isPending ? 'Adding…' : 'Add Adjustment'}- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>- )-}--function AdjustmentsCard({ order }: { order: Order }) {- const { orderId } = Route.useParams()- const adjustments = (order.adjustments ?? []).filter(- (a) => a.source_type !== 'Spree::TaxRate' && a.source_type !== 'Spree::PromotionAction',- )- const [addOpen, setAddOpen] = useState(false)-- const deleteMutation = useOrderMutation(orderId, (adjustmentId: string) =>- adminClient.orders.adjustments.delete(orderId, adjustmentId),- )-- return (- <>- <Card>- <CardHeader>- <CardTitle>- <SlidersHorizontalIcon className="size-4" />- Adjustments- </CardTitle>- <CardAction className="flex items-center gap-2">- {adjustments.length > 0 && <Badge variant="info">{adjustments.length}</Badge>}- <Button size="sm" variant="secondary" onClick={() => setAddOpen(true)}>- <PlusIcon data-icon="inline-start" />- Add- </Button>- </CardAction>- </CardHeader>- {adjustments.length > 0 ? (- <div className="overflow-x-auto">- <table className="w-full text-sm">- <thead>- <tr className="border-b bg-muted/50 text-muted-foreground">- <th className="p-3 pl-5 text-left font-normal">Label</th>- <th className="p-3 text-left font-normal">State</th>- <th className="p-3 text-right font-normal">Amount</th>- <th className="p-3 pr-5 w-10" />- </tr>- </thead>- <tbody>- {adjustments.map((adj) => (- <tr key={adj.id} className="border-b last:border-b-0">- <td className="p-3 pl-5">{adj.label ?? '—'}</td>- <td className="p-3">- <StatusBadge status={adj.state} />- </td>- <td className="p-3 text-right font-medium whitespace-nowrap">- {order.currency} {Number.parseFloat(adj.amount).toFixed(2)}- </td>- <td className="p-3 pr-5">- {!adj.source_type && (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button variant="ghost" size="icon-xs">- <EllipsisVerticalIcon className="size-4" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem- className="text-destructive focus:text-destructive"- onClick={() => {- if (window.confirm('Remove this adjustment?')) {- deleteMutation.mutate(adj.id)- }- }}- >- <TrashIcon className="size-4" />- Remove- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- )}- </td>- </tr>- ))}- </tbody>- </table>- </div>- ) : (- <CardContent>- <p className="text-center text-muted-foreground py-8">No adjustments</p>- </CardContent>- )}- </Card>-- <AddAdjustmentDialog orderId={orderId} open={addOpen} onOpenChange={setAddOpen} />- </>- )-}--// ----------------------------------------------------------------------------// Order Summary-// -----------------------------------------------------------------------------function SummaryRow({- label,- value,- bold,- danger,- highlight,-}: {- label: string- value: string- bold?: boolean- danger?: boolean- highlight?: boolean-}) {- return (- <div- className={cn('flex items-center justify-between px-5 py-2.5', highlight && 'bg-muted/50')}- >- <span className="text-sm">{label}</span>- <span className={cn('text-sm', bold && 'font-bold', danger && 'text-destructive')}>- {value}- </span>- </div>- )-}--function OrderSummaryCard({ order }: { order: Order }) {- const outstandingBalance = Number.parseFloat(order.total) - Number.parseFloat(order.payment_total)-- return (- <Card>- <CardHeader>- <CardTitle>Summary</CardTitle>- </CardHeader>- <div className="py-1">- {order.completed_at && (- <>- <SummaryRow label="Completed" value={formatDate(order.completed_at)} />- {order.canceled_at && (- <SummaryRow label="Canceled" value={formatDate(order.canceled_at)} />- )}- <Separator />- </>- )}-- <SummaryRow label="Locale" value={order.locale ?? '—'} />- <SummaryRow label="Currency" value={order.currency} />-- <Separator />-- <SummaryRow label="Subtotal" value={order.display_item_total} />-- {Number.parseFloat(order.delivery_total) > 0 && (- <SummaryRow label="Shipping" value={order.display_delivery_total} />- )}-- {Number.parseFloat(order.discount_total) !== 0 && (- <SummaryRow label="Promotions" value={order.display_discount_total} />- )}-- {Number.parseFloat(order.adjustment_total) !== 0 && (- <SummaryRow label="Adjustments" value={order.display_adjustment_total} />- )}-- {Number.parseFloat(order.included_tax_total) > 0 && (- <SummaryRow label="Tax (included)" value={order.display_included_tax_total} />- )}-- {Number.parseFloat(order.additional_tax_total) > 0 && (- <SummaryRow label="Tax (additional)" value={order.display_additional_tax_total} />- )}-- <Separator />-- <SummaryRow label="Total" value={order.display_total} bold />-- <Separator />-- <SummaryRow label="Payment total" value={order.display_payment_total} highlight />- <SummaryRow- label="Outstanding balance"- value={`${order.currency} ${Math.abs(outstandingBalance).toFixed(2)}`}- highlight- danger={outstandingBalance > 0}- />- </div>- </Card>- )-}--// ----------------------------------------------------------------------------// Customer Sidebar-// -----------------------------------------------------------------------------function AddressBlock({- title,- address,-}: {- title: string- address: Address | null | undefined-}) {- return (- <div>- <h6 className="font-semibold text-sm mb-1.5">{title}</h6>- {address ? (- <div className="text-sm text-muted-foreground flex flex-col gap-0.5">- <div>{address.full_name}</div>- {address.company && <div>{address.company}</div>}- <div>{address.address1}</div>- {address.address2 && <div>{address.address2}</div>}- <div>- {[address.city, address.state_text, address.postal_code].filter(Boolean).join(', ')}- </div>- <div>{address.country_name}</div>- {address.phone && <div>{address.phone}</div>}- </div>- ) : (- <span className="text-sm text-muted-foreground">Not provided</span>- )}- </div>- )-}--function EditAddressDialog({- orderId,- type,- address,- open,- onOpenChange,-}: {- orderId: string- type: 'shipping_address' | 'billing_address'- address: Address | null | undefined- open: boolean- onOpenChange: (open: boolean) => void-}) {- const mutation = useOrderMutation(orderId, (params: Record<string, unknown>) =>- adminClient.orders.update(orderId, { [type]: params } as any),- )-- function handleSubmit(e: FormEvent<HTMLFormElement>) {- e.preventDefault()- const fd = new FormData(e.currentTarget)- mutation.mutate(- {- first_name: fd.get('first_name') as string,- last_name: fd.get('last_name') as string,- address1: fd.get('address1') as string,- city: fd.get('city') as string,- postal_code: fd.get('postal_code') as string,- country_iso: fd.get('country_iso') as string,- state_abbr: fd.get('state_abbr') as string,- phone: fd.get('phone') as string,- },- { onSuccess: () => onOpenChange(false) },- )- }-- const title = type === 'shipping_address' ? 'Edit Shipping Address' : 'Edit Billing Address'-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent>- <DialogHeader>- <DialogTitle>{title}</DialogTitle>- <DialogDescription>Update the address details.</DialogDescription>- </DialogHeader>- <form onSubmit={handleSubmit}>- <DialogBody>- <FieldGroup>- <div className="grid grid-cols-2 gap-3">- <Field>- <FieldLabel htmlFor={`${type}-fn`}>First Name</FieldLabel>- <Input- id={`${type}-fn`}- name="first_name"- defaultValue={address?.first_name ?? ''}- />- </Field>- <Field>- <FieldLabel htmlFor={`${type}-ln`}>Last Name</FieldLabel>- <Input id={`${type}-ln`} name="last_name" defaultValue={address?.last_name ?? ''} />- </Field>- </div>- <Field>- <FieldLabel htmlFor={`${type}-a1`}>Address</FieldLabel>- <Input id={`${type}-a1`} name="address1" defaultValue={address?.address1 ?? ''} />- </Field>- <div className="grid grid-cols-2 gap-3">- <Field>- <FieldLabel htmlFor={`${type}-city`}>City</FieldLabel>- <Input id={`${type}-city`} name="city" defaultValue={address?.city ?? ''} />- </Field>- <Field>- <FieldLabel htmlFor={`${type}-zip`}>Zip Code</FieldLabel>- <Input id={`${type}-zip`} name="postal_code" defaultValue={address?.postal_code ?? ''} />- </Field>- </div>- <div className="grid grid-cols-2 gap-3">- <Field>- <FieldLabel htmlFor={`${type}-country`}>Country ISO</FieldLabel>- <Input- id={`${type}-country`}- name="country_iso"- defaultValue={address?.country_iso ?? ''}- placeholder="US"- />- </Field>- <Field>- <FieldLabel htmlFor={`${type}-state`}>State</FieldLabel>- <Input- id={`${type}-state`}- name="state_abbr"- defaultValue={address?.state_abbr ?? ''}- placeholder="CA"- />- </Field>- </div>- <Field>- <FieldLabel htmlFor={`${type}-phone`}>Phone</FieldLabel>- <Input id={`${type}-phone`} name="phone" defaultValue={address?.phone ?? ''} />- </Field>- </FieldGroup>- </DialogBody>- <DialogFooter>- <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>- Cancel- </Button>- <Button type="submit" disabled={mutation.isPending}>- {mutation.isPending ? 'Saving…' : 'Save'}- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>- )-}--function CustomerCard({ order }: { order: Order }) {- const { orderId } = Route.useParams()- const user = order.customer- const [editAddress, setEditAddress] = useState<'shipping_address' | 'billing_address' | null>(null)-- return (- <>- <Card>- <CardHeader>- <CardTitle>Customer</CardTitle>- <CardAction>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button variant="ghost" size="icon-xs">- <EllipsisVerticalIcon className="size-4" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem onClick={() => setEditAddress('shipping_address')}>- <PencilIcon className="size-4" />- Edit Shipping Address- </DropdownMenuItem>- <DropdownMenuItem onClick={() => setEditAddress('billing_address')}>- <PencilIcon className="size-4" />- Edit Billing Address- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </CardAction>- </CardHeader>- <CardContent className="flex flex-col gap-5">- {/* Contact info */}- {user ? (- <div className="flex items-center gap-3 rounded-xl bg-muted p-3">- <div className="flex size-9 items-center justify-center rounded-lg bg-zinc-950 text-white text-xs font-medium">- {[user.first_name, user.last_name]- .filter(Boolean)- .map((n) => n![0])- .join('')- .toUpperCase() || user.email[0]!.toUpperCase()}- </div>- <div className="min-w-0 flex-1">- <div className="truncate text-sm font-medium">- {[user.first_name, user.last_name].filter(Boolean).join(' ') || user.email}- </div>- <div className="truncate text-xs text-muted-foreground">{user.email}</div>- </div>- </div>- ) : order.email ? (- <div className="text-sm text-blue-600">{order.email}</div>- ) : (- <span className="text-sm text-muted-foreground">No customer information</span>- )}-- <AddressBlock title="Shipping Address" address={order.shipping_address} />- <AddressBlock title="Billing Address" address={order.billing_address} />- </CardContent>- </Card>-- {editAddress && (- <EditAddressDialog- orderId={orderId}- type={editAddress}- address={editAddress === 'shipping_address' ? order.shipping_address : order.billing_address}- open={!!editAddress}- onOpenChange={(open) => !open && setEditAddress(null)}- />- )}- </>- )-}--// ----------------------------------------------------------------------------// Special Instructions-// -----------------------------------------------------------------------------function SpecialInstructionsCard({ order }: { order: Order }) {- const { orderId } = Route.useParams()- const [editing, setEditing] = useState(false)- const mutation = useOrderMutation(orderId, (params: { customer_note: string }) =>- adminClient.orders.update(orderId, params),- )-- function handleSubmit(e: FormEvent<HTMLFormElement>) {- e.preventDefault()- const fd = new FormData(e.currentTarget)- mutation.mutate(- { customer_note: fd.get('customer_note') as string },- { onSuccess: () => setEditing(false) },- )- }-- return (- <Card>- <CardHeader>- <CardTitle>Special Instructions</CardTitle>- <CardAction>- <Button variant="ghost" size="icon-xs" onClick={() => setEditing(!editing)}>- <PencilIcon className="size-4" />- </Button>- </CardAction>- </CardHeader>- <CardContent>- {editing ? (- <form onSubmit={handleSubmit} className="flex flex-col gap-3">- <Textarea name="customer_note" defaultValue={order.customer_note ?? ''} />- <div className="flex justify-end gap-2">- <Button type="button" variant="outline" size="sm" onClick={() => setEditing(false)}>- Cancel- </Button>- <Button type="submit" size="sm" disabled={mutation.isPending}>- {mutation.isPending ? 'Saving…' : 'Save'}- </Button>- </div>- </form>- ) : order.customer_note ? (- <p className="text-sm text-muted-foreground whitespace-pre-wrap">- {order.customer_note}- </p>- ) : (- <p className="text-sm text-muted-foreground">None</p>- )}- </CardContent>- </Card>- )-}--// ----------------------------------------------------------------------------// Internal Note-// -----------------------------------------------------------------------------function InternalNoteCard({ order }: { order: Order }) {- const { orderId } = Route.useParams()- const [editing, setEditing] = useState(false)- const mutation = useOrderMutation(orderId, (params: { internal_note: string }) =>- adminClient.orders.update(orderId, params),- )-- function handleSubmit(e: FormEvent<HTMLFormElement>) {- e.preventDefault()- const fd = new FormData(e.currentTarget)- mutation.mutate(- { internal_note: fd.get('internal_note') as string },- { onSuccess: () => setEditing(false) },- )- }-- return (- <Card>- <CardHeader>- <CardTitle>Internal Note</CardTitle>- <CardAction>- <Button variant="ghost" size="icon-xs" onClick={() => setEditing(!editing)}>- <PencilIcon className="size-4" />- </Button>- </CardAction>- </CardHeader>- <CardContent>- {editing ? (- <form onSubmit={handleSubmit} className="flex flex-col gap-3">- <Textarea name="internal_note" defaultValue={order.internal_note ?? ''} />- <div className="flex justify-end gap-2">- <Button type="button" variant="outline" size="sm" onClick={() => setEditing(false)}>- Cancel- </Button>- <Button type="submit" size="sm" disabled={mutation.isPending}>- {mutation.isPending ? 'Saving…' : 'Save'}- </Button>- </div>- </form>- ) : order.internal_note ? (- <p className="text-sm text-muted-foreground whitespace-pre-wrap">{order.internal_note}</p>- ) : (- <p className="text-sm text-muted-foreground">None</p>- )}- </CardContent>- </Card>- )-}--// ----------------------------------------------------------------------------// Loading skeleton-// -----------------------------------------------------------------------------function OrderSkeleton() {- return (- <div className="flex flex-col gap-6">- <div className="flex items-center gap-3">- <Skeleton className="size-8 rounded-lg" />- <Skeleton className="h-8 w-40" />- <Skeleton className="h-5 w-16 rounded-md" />- <Skeleton className="h-5 w-16 rounded-md" />- </div>- <div className="grid grid-cols-12 gap-6">- <div className="col-span-12 lg:col-span-8 flex flex-col gap-6">- <Skeleton className="h-64 w-full rounded-xl" />- <Skeleton className="h-48 w-full rounded-xl" />- <Skeleton className="h-48 w-full rounded-xl" />- </div>- <div className="col-span-12 lg:col-span-4 flex flex-col gap-6">- <Skeleton className="h-64 w-full rounded-xl" />- </div>- </div>- </div>- )-}diff --git a/packages/admin/src/routes/_authenticated/orders/drafts.tsx b/packages/admin/src/routes/_authenticated/orders/drafts.tsxdeleted file mode 100644index 3a60fcb9fc..0000000000--- a/packages/admin/src/routes/_authenticated/orders/drafts.tsx+++ /dev/null@@ -1,32 +0,0 @@-import { createFileRoute } from '@tanstack/react-router'-import { PlusIcon } from 'lucide-react'-import { adminClient } from '@/client'-import { ResourceTable, resourceSearchSchema } from '@/components/resource-table'-import { Button } from '@/components/ui/button'-import '@/tables/orders'--export const Route = createFileRoute('/_authenticated/orders/drafts')({- validateSearch: resourceSearchSchema,- component: DraftOrdersPage,-})--function DraftOrdersPage() {- const searchParams = Route.useSearch()-- return (- <ResourceTable- tableKey="orders"- queryKey="draft-orders"- queryFn={(params) => adminClient.orders.list(params)}- searchParams={searchParams}- defaultParams={{ incomplete: 1 }}- title="Draft Orders"- actions={- <Button size="sm" className="h-[2.125rem]">- <PlusIcon className="size-4" />- New Order- </Button>- }- />- )-}diff --git a/packages/admin/src/routes/_authenticated/orders/index.tsx b/packages/admin/src/routes/_authenticated/orders/index.tsxdeleted file mode 100644index 55488d4f49..0000000000--- a/packages/admin/src/routes/_authenticated/orders/index.tsx+++ /dev/null@@ -1,31 +0,0 @@-import { createFileRoute } from '@tanstack/react-router'-import { PlusIcon } from 'lucide-react'-import { adminClient } from '@/client'-import { ResourceTable, resourceSearchSchema } from '@/components/resource-table'-import { Button } from '@/components/ui/button'-import '@/tables/orders'--export const Route = createFileRoute('/_authenticated/orders/')({- validateSearch: resourceSearchSchema,- component: OrdersPage,-})--function OrdersPage() {- const searchParams = Route.useSearch()-- return (- <ResourceTable- tableKey="orders"- queryKey="orders"- queryFn={(params) => adminClient.orders.list(params)}- searchParams={searchParams}- defaultParams={{ complete: 1 }}- actions={- <Button size="sm" className="h-[2.125rem]">- <PlusIcon className="size-4" />- New Order- </Button>- }- />- )-}diff --git a/packages/admin/src/routes/_authenticated/products/$productId.tsx b/packages/admin/src/routes/_authenticated/products/$productId.tsxdeleted file mode 100644index 8f666dad82..0000000000--- a/packages/admin/src/routes/_authenticated/products/$productId.tsx+++ /dev/null@@ -1,1041 +0,0 @@-import type { Media, Product as BaseProduct, Variant as BaseVariant } from '@spree/admin-sdk'--// Extended types for fields not yet in generated types-type Variant = BaseVariant & {- barcode?: string | null- weight_unit?: string | null- dimensions_unit?: string | null-}-type Product = Omit<BaseProduct, 'master_variant' | 'variants'> & {- tax_category_id?: string | null- meta_title?: string | null- master_variant?: Variant- variants?: Variant[]-}-import { zodResolver } from '@hookform/resolvers/zod'-import { createFileRoute, Link, useRouter } from '@tanstack/react-router'-import {- ArrowLeftIcon,- ImagePlusIcon,- Loader2Icon,- SaveIcon,- TrashIcon,- XIcon,-} from 'lucide-react'-import { useCallback, useEffect, useRef, useState } from 'react'-import { Controller, useForm, type UseFormReturn } from 'react-hook-form'-import { toast } from 'sonner'-import { StatusBadge } from '@/components/ui/badge'-import { Button } from '@/components/ui/button'-import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'-import { DatePicker } from '@/components/ui/date-picker'-import { Input } from '@/components/ui/input'-import { Label } from '@/components/ui/label'-import {- Combobox,- ComboboxChip,- ComboboxChips,- ComboboxChipsInput,- ComboboxContent,- ComboboxEmpty,- ComboboxItem,- ComboboxList,- ComboboxValue,- useComboboxAnchor,-} from '@/components/ui/combobox'-import { RichTextEditor } from '@/components/ui/rich-text-editor'-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from '@/components/ui/select'-import { Skeleton } from '@/components/ui/skeleton'-import { Switch } from '@/components/ui/switch'-import { Textarea } from '@/components/ui/textarea'-import { useDirectUpload } from '@/hooks/use-direct-upload'-import { useProduct, useUpdateProduct, useDeleteProduct } from '@/hooks/use-product'-import {- useProductAssets,- useCreateProductAsset,- useDeleteProductAsset,-} from '@/hooks/use-product-assets'-import { useTaxCategories } from '@/hooks/use-tax-categories'-import { useCategories } from '@/hooks/use-categories'-import { productFormSchema, type ProductFormValues } from '@/schemas/product'--export const Route = createFileRoute('/_authenticated/products/$productId')({- component: ProductDetailPage,-})--// ----------------------------------------------------------------------------// Helpers-// -----------------------------------------------------------------------------function productToFormValues(product: Product): ProductFormValues {- const master = product.master_variant-- return {- name: product.name,- description: product.description ?? '',- status: (product.status as ProductFormValues['status']) ?? 'draft',- make_active_at: product.make_active_at ?? null,- available_on: product.available_on ?? null,- discontinue_on: product.discontinue_on ?? null,- category_ids: product.categories?.map((t) => t.id) ?? [],- tags: product.tags?.map((t: any) => t.name ?? t) ?? [],- price: master?.price?.amount ? Number(master.price.amount) : undefined,- compare_at_price: master?.original_price?.amount- ? Number(master.original_price.amount)- : null,- cost_price: product.cost_price ? Number(product.cost_price) : null,- sku: master?.sku ?? '',- barcode: master?.barcode ?? '',- track_inventory: master?.track_inventory ?? true,- weight: master?.weight ?? null,- height: master?.height ?? null,- width: master?.width ?? null,- depth: master?.depth ?? null,- weight_unit: master?.weight_unit ?? null,- dimensions_unit: master?.dimensions_unit ?? null,- tax_category_id: product.tax_category_id ?? null,- meta_title: product.meta_title ?? '',- meta_description: product.meta_description ?? '',- slug: product.slug ?? '',- }-}--// ----------------------------------------------------------------------------// Page-// -----------------------------------------------------------------------------function ProductDetailPage() {- const { productId } = Route.useParams()- const { data: product, isLoading, error } = useProduct(productId)-- if (isLoading) return <ProductSkeleton />- if (error || !product) {- return <p className="text-destructive p-4">Failed to load product.</p>- }-- return <ProductForm product={product} />-}--// ----------------------------------------------------------------------------// Form-// -----------------------------------------------------------------------------function ProductForm({ product }: { product: Product }) {- const { productId } = Route.useParams()- const router = useRouter()- const updateProduct = useUpdateProduct()- const deleteProduct = useDeleteProduct()- const hasVariants = (product.variant_count ?? 0) > 0-- const form = useForm<ProductFormValues>({- // eslint-disable-next-line @typescript-eslint/no-explicit-any- resolver: zodResolver(productFormSchema) as any,- defaultValues: productToFormValues(product),- })-- useEffect(() => {- form.reset(productToFormValues(product))- }, [product, form])-- const onSubmit = async (data: ProductFormValues) => {- try {- await updateProduct.mutateAsync({ id: productId, ...data })- toast.success('Product saved')- } catch {- toast.error('Failed to save product')- }- }-- const handleDelete = async () => {- if (!window.confirm('Are you sure you want to delete this product?')) return- try {- await deleteProduct.mutateAsync(productId)- toast.success('Product deleted')- await router.navigate({ to: '/products', search: { filters: [], columns: [] } })- } catch {- toast.error('Failed to delete product')- }- }-- return (- <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-6">- {/* Header */}- <div className="flex items-center gap-3">- <Link- to="/products"- search={{ filters: [], columns: [] }}- className="inline-flex items-center justify-center rounded-lg p-1.5 text-muted-foreground hover:bg-gray-100 hover:text-foreground transition-colors"- >- <ArrowLeftIcon className="size-5" />- </Link>-- <h1 className="text-2xl font-medium truncate">{product.name}</h1>- <StatusBadge status={product.status} />-- <div className="ml-auto flex items-center gap-2">- <Button- type="button"- variant="outline"- size="sm"- onClick={handleDelete}- disabled={deleteProduct.isPending}- >- <TrashIcon className="size-4" />- Delete- </Button>- <Button- type="submit"- size="sm"- disabled={updateProduct.isPending || !form.formState.isDirty}- >- {updateProduct.isPending ? (- <Loader2Icon className="size-4 animate-spin" />- ) : (- <SaveIcon className="size-4" />- )}- Save- </Button>- </div>- </div>-- {/* Two-column layout */}- <div className="grid grid-cols-12 gap-6">- {/* Left column */}- <div className="col-span-12 lg:col-span-8 flex flex-col gap-6">- <GeneralCard form={form} />- <MediaCard productId={productId} />- {!hasVariants && <PricingCard form={form} />}- {!hasVariants && <InventoryCard form={form} />}- <SEOCard form={form} product={product} />- </div>-- {/* Right column */}- <div className="col-span-12 lg:col-span-4 flex flex-col gap-6">- <StatusCard form={form} />- <CategorizationCard form={form} />- <ShippingCard form={form} hasVariants={hasVariants} />- <TaxCard form={form} />- </div>- </div>- </form>- )-}--// ----------------------------------------------------------------------------// Shared types-// -----------------------------------------------------------------------------// eslint-disable-next-line @typescript-eslint/no-explicit-any-type FormCardProps = {- form: UseFormReturn<ProductFormValues, any, any>-}--// ----------------------------------------------------------------------------// General-// -----------------------------------------------------------------------------function GeneralCard({ form }: FormCardProps) {- return (- <Card>- <CardHeader>- <CardTitle>General</CardTitle>- </CardHeader>- <CardContent className="flex flex-col gap-4">- <div className="grid gap-2">- <Label htmlFor="name">Name</Label>- <Input id="name" placeholder="Product name" {...form.register('name')} />- {form.formState.errors.name && (- <p className="text-sm text-destructive">{form.formState.errors.name.message}</p>- )}- </div>-- <div className="grid gap-2">- <Label>Description</Label>- <Controller- name="description"- control={form.control}- render={({ field }) => (- <RichTextEditor- value={field.value}- onChange={field.onChange}- placeholder="Write a product description..."- />- )}- />- </div>- </CardContent>- </Card>- )-}--// ----------------------------------------------------------------------------// Media-// -----------------------------------------------------------------------------interface PendingUpload {- id: string- file: File- preview: string- progress: 'uploading' | 'attaching' | 'done' | 'error'-}--function MediaCard({ productId }: { productId: string }) {- const { data: assetsResponse } = useProductAssets(productId)- const createAsset = useCreateProductAsset(productId)- const deleteAsset = useDeleteProductAsset(productId)- const directUpload = useDirectUpload()- const [pending, setPending] = useState<PendingUpload[]>([])- const fileInputRef = useRef<HTMLInputElement>(null)-- const assets = assetsResponse?.data ?? []-- const handleFiles = useCallback(- async (files: FileList | File[]) => {- const fileArray = Array.from(files)-- for (const file of fileArray) {- const uploadId = crypto.randomUUID()- const preview = URL.createObjectURL(file)-- setPending((prev) => [...prev, { id: uploadId, file, preview, progress: 'uploading' }])-- try {- const result = await directUpload.mutateAsync(file)-- setPending((prev) =>- prev.map((p) => (p.id === uploadId ? { ...p, progress: 'attaching' as const } : p)),- )-- await createAsset.mutateAsync({- signed_id: result.signedId,- alt: file.name,- position: assets.length + fileArray.indexOf(file) + 1,- })-- setPending((prev) => prev.filter((p) => p.id !== uploadId))- URL.revokeObjectURL(preview)- } catch (err) {- console.error(`Upload failed for ${file.name}:`, err)- setPending((prev) =>- prev.map((p) => (p.id === uploadId ? { ...p, progress: 'error' as const } : p)),- )- const message = err instanceof Error ? err.message : 'Unknown error'- toast.error(`Failed to upload ${file.name}: ${message}`)- }- }- },- [directUpload, createAsset, assets.length],- )-- const handleDrop = useCallback(- (e: React.DragEvent) => {- e.preventDefault()- if (e.dataTransfer.files.length > 0) {- handleFiles(e.dataTransfer.files)- }- },- [handleFiles],- )-- const handleDragOver = useCallback((e: React.DragEvent) => {- e.preventDefault()- }, [])-- const handleDeleteAsset = async (assetId: string) => {- try {- await deleteAsset.mutateAsync(assetId)- toast.success('Image deleted')- } catch {- toast.error('Failed to delete image')- }- }-- return (- <Card>- <CardHeader>- <CardTitle>Media</CardTitle>- </CardHeader>- <CardContent className="flex flex-col gap-4">- {/* Image grid */}- {(assets.length > 0 || pending.length > 0) && (- <div className="grid grid-cols-4 gap-3">- {assets.map((asset) => (- <MediaThumbnail- key={asset.id}- asset={asset as unknown as Media}- onDelete={() => handleDeleteAsset(asset.id)}- />- ))}- {pending.map((upload) => (- <div- key={upload.id}- className="relative aspect-square overflow-hidden rounded-lg border border-gray-200 bg-gray-50"- >- <img- src={upload.preview}- alt=""- className="size-full object-cover opacity-60"- />- <div className="absolute inset-0 flex items-center justify-center">- {upload.progress === 'error' ? (- <span className="text-xs text-destructive font-medium">Failed</span>- ) : (- <Loader2Icon className="size-5 animate-spin text-gray-500" />- )}- </div>- </div>- ))}- </div>- )}-- {/* Drop zone */}- <div- onDrop={handleDrop}- onDragOver={handleDragOver}- className="flex flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed border-gray-200 p-6 text-center transition-colors hover:border-gray-300 cursor-pointer"- onClick={() => fileInputRef.current?.click()}- onKeyDown={(e) => e.key === 'Enter' && fileInputRef.current?.click()}- role="button"- tabIndex={0}- >- <ImagePlusIcon className="size-8 text-gray-400" />- <p className="text-sm text-gray-600">- Drag & drop images here, or click to browse- </p>- <p className="text-xs text-gray-400">PNG, JPG, WebP up to 10MB</p>- <input- ref={fileInputRef}- type="file"- accept="image/*"- multiple- className="hidden"- onChange={(e) => e.target.files && handleFiles(e.target.files)}- />- </div>- </CardContent>- </Card>- )-}--function MediaThumbnail({- asset,- onDelete,-}: {- asset: Media- onDelete: () => void-}) {- const imageUrl = asset.small_url || asset.mini_url || asset.original_url-- return (- <div className="group relative aspect-square overflow-hidden rounded-lg border border-gray-200 bg-gray-50">- {imageUrl ? (- <img src={imageUrl} alt={asset.alt ?? ''} className="size-full object-cover" />- ) : (- <div className="flex size-full items-center justify-center text-gray-400">- <ImagePlusIcon className="size-6" />- </div>- )}- <button- type="button"- onClick={onDelete}- className="absolute top-1.5 right-1.5 hidden group-hover:inline-flex items-center justify-center rounded-md size-6 bg-white/90 text-gray-600 hover:text-destructive hover:bg-white shadow-sm transition-colors"- >- <XIcon className="size-3.5" />- </button>- </div>- )-}--// ----------------------------------------------------------------------------// Pricing-// -----------------------------------------------------------------------------function PricingCard({ form }: FormCardProps) {- return (- <Card>- <CardHeader>- <CardTitle>Pricing</CardTitle>- </CardHeader>- <CardContent className="flex flex-col gap-4">- <div className="grid grid-cols-2 gap-4">- <div className="grid gap-2">- <Label htmlFor="price">Price</Label>- <Input- id="price"- type="number"- step="0.01"- min="0"- placeholder="0.00"- {...form.register('price')}- />- </div>- <div className="grid gap-2">- <Label htmlFor="compare_at_price">Compare at price</Label>- <Input- id="compare_at_price"- type="number"- step="0.01"- min="0"- placeholder="0.00"- {...form.register('compare_at_price')}- />- <p className="text-xs text-muted-foreground">- Original price shown as strikethrough- </p>- </div>- </div>- <div className="grid gap-2 max-w-[50%]">- <Label htmlFor="cost_price">Cost price</Label>- <Input- id="cost_price"- type="number"- step="0.01"- min="0"- placeholder="0.00"- {...form.register('cost_price')}- />- <p className="text-xs text-muted-foreground">Not visible to customers</p>- </div>- </CardContent>- </Card>- )-}--// ----------------------------------------------------------------------------// Inventory-// -----------------------------------------------------------------------------function InventoryCard({ form }: FormCardProps) {- const trackInventory = form.watch('track_inventory')-- return (- <Card>- <CardHeader>- <CardTitle>Inventory</CardTitle>- </CardHeader>- <CardContent className="flex flex-col gap-4">- <div className="grid grid-cols-2 gap-4">- <div className="grid gap-2">- <Label htmlFor="sku">SKU</Label>- <Input id="sku" placeholder="SKU-001" {...form.register('sku')} />- </div>- <div className="grid gap-2">- <Label htmlFor="barcode">Barcode</Label>- <Input id="barcode" placeholder="ISBN, UPC, GTIN..." {...form.register('barcode')} />- </div>- </div>-- <div className="flex items-center gap-3">- <Controller- name="track_inventory"- control={form.control}- render={({ field }) => (- <Switch- id="track_inventory"- checked={field.value}- onCheckedChange={field.onChange}- />- )}- />- <Label htmlFor="track_inventory">Track inventory</Label>- </div>-- {trackInventory && (- <p className="text-sm text-muted-foreground">- Stock levels are managed per stock location.- </p>- )}- </CardContent>- </Card>- )-}--// ----------------------------------------------------------------------------// SEO-// -----------------------------------------------------------------------------function SEOCard({ form, product }: FormCardProps & { product: Product }) {- const slug = form.watch('slug')- const metaTitle = form.watch('meta_title')- const metaDescription = form.watch('meta_description')-- return (- <Card>- <CardHeader>- <CardTitle>SEO</CardTitle>- </CardHeader>- <CardContent className="flex flex-col gap-4">- {/* Preview */}- <div className="rounded-lg border border-gray-200 p-4 space-y-1">- <p className="text-sm font-medium text-blue-700 truncate">- {metaTitle || product.name}- </p>- <p className="text-xs text-green-700 truncate">- example.com/products/{slug || product.slug}- </p>- {metaDescription && (- <p className="text-xs text-muted-foreground line-clamp-2">{metaDescription}</p>- )}- </div>-- <div className="grid gap-2">- <Label htmlFor="slug">URL handle</Label>- <Input id="slug" placeholder="product-url-handle" {...form.register('slug')} />- </div>-- <div className="grid gap-2">- <Label htmlFor="meta_title">Meta title</Label>- <Input id="meta_title" placeholder="SEO title" {...form.register('meta_title')} />- </div>-- <div className="grid gap-2">- <Label htmlFor="meta_description">Meta description</Label>- <Textarea- id="meta_description"- placeholder="SEO description"- rows={3}- {...form.register('meta_description')}- />- </div>- </CardContent>- </Card>- )-}--// ----------------------------------------------------------------------------// Status-// -----------------------------------------------------------------------------function StatusCard({ form }: FormCardProps) {- const status = form.watch('status')-- return (- <Card>- <CardHeader>- <CardTitle>Status</CardTitle>- </CardHeader>- <CardContent className="flex flex-col gap-4">- <div className="grid gap-2">- <Label>Status</Label>- <Controller- name="status"- control={form.control}- render={({ field }) => (- <Select value={field.value} onValueChange={field.onChange}>- <SelectTrigger className="w-full">- <SelectValue />- </SelectTrigger>- <SelectContent>- <SelectItem value="draft">Draft</SelectItem>- <SelectItem value="active">Active</SelectItem>- <SelectItem value="archived">Archived</SelectItem>- </SelectContent>- </Select>- )}- />- </div>-- {status !== 'active' && (- <div className="grid gap-2">- <Label>Schedule activation</Label>- <Controller- name="make_active_at"- control={form.control}- render={({ field }) => (- <DatePicker- value={field.value}- onChange={field.onChange}- placeholder="Pick a date"- includeTime- />- )}- />- </div>- )}-- <div className="grid gap-2">- <Label>Available on</Label>- <Controller- name="available_on"- control={form.control}- render={({ field }) => (- <DatePicker- value={field.value}- onChange={field.onChange}- placeholder="Pick a date"- includeTime- />- )}- />- </div>-- <div className="grid gap-2">- <Label>Discontinue on</Label>- <Controller- name="discontinue_on"- control={form.control}- render={({ field }) => (- <DatePicker- value={field.value}- onChange={field.onChange}- placeholder="Pick a date"- includeTime- />- )}- />- </div>- </CardContent>- </Card>- )-}--// ----------------------------------------------------------------------------// Categorization-// -----------------------------------------------------------------------------function CategorizationCard({ form }: FormCardProps) {- const { data: categoriesResponse } = useCategories()- const categories = categoriesResponse?.data ?? []-- return (- <Card>- <CardHeader>- <CardTitle>Categorization</CardTitle>- </CardHeader>- <CardContent className="flex flex-col gap-4">- <div className="grid gap-2">- <Label>Categories</Label>- <Controller- name="category_ids"- control={form.control}- render={({ field }) => (- <CategoryCombobox- categories={categories}- value={field.value ?? []}- onChange={field.onChange}- />- )}- />- </div>-- <div className="grid gap-2">- <Label>Tags</Label>- <Controller- name="tags"- control={form.control}- render={({ field }) => (- <TagCombobox- value={field.value ?? []}- onChange={field.onChange}- />- )}- />- </div>- </CardContent>- </Card>- )-}--interface CategoryOption {- id: string- name: string-}--function CategoryCombobox({- categories,- value,- onChange,-}: {- categories: CategoryOption[]- value: string[]- onChange: (value: string[]) => void-}) {- const anchorRef = useComboboxAnchor()-- return (- <Combobox- multiple- value={value}- onValueChange={onChange}- >- <ComboboxChips ref={anchorRef}>- <ComboboxValue>- {(selectedValues: string[]) =>- selectedValues.map((id) => (- <ComboboxChip key={id}>- {categories.find((c) => c.id === id)?.name ?? id}- </ComboboxChip>- ))- }- </ComboboxValue>- <ComboboxChipsInput placeholder="Search categories..." />- </ComboboxChips>- <ComboboxContent anchor={anchorRef}>- <ComboboxList>- {categories.map((category) => (- <ComboboxItem key={category.id} value={category.id}>- {category.name}- </ComboboxItem>- ))}- <ComboboxEmpty>No categories found</ComboboxEmpty>- </ComboboxList>- </ComboboxContent>- </Combobox>- )-}--function TagCombobox({- value,- onChange,-}: {- value: string[]- onChange: (value: string[]) => void-}) {- const anchorRef = useComboboxAnchor()- const [inputValue, setInputValue] = useState('')-- const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {- if (e.key === 'Enter' && inputValue.trim()) {- e.preventDefault()- const tag = inputValue.trim()- if (!value.includes(tag)) {- onChange([...value, tag])- }- setInputValue('')- }- }-- return (- <Combobox- multiple- value={value}- onValueChange={onChange}- >- <ComboboxChips ref={anchorRef}>- <ComboboxValue>- {(selectedValues: string[]) =>- selectedValues.map((tag) => (- <ComboboxChip key={tag}>- {tag}- </ComboboxChip>- ))- }- </ComboboxValue>- <ComboboxChipsInput- placeholder="Type to add tags..."- value={inputValue}- onChange={(e) => setInputValue((e.target as HTMLInputElement).value)}- onKeyDown={handleKeyDown}- />- </ComboboxChips>- <ComboboxContent anchor={anchorRef}>- <ComboboxList>- {value.map((tag) => (- <ComboboxItem key={tag} value={tag}>- {tag}- </ComboboxItem>- ))}- {inputValue.trim() && !value.includes(inputValue.trim()) && (- <ComboboxItem value={inputValue.trim()}>- Create “{inputValue.trim()}”- </ComboboxItem>- )}- <ComboboxEmpty>Type and press Enter to create a tag</ComboboxEmpty>- </ComboboxList>- </ComboboxContent>- </Combobox>- )-}--// ----------------------------------------------------------------------------// Shipping-// -----------------------------------------------------------------------------function ShippingCard({ form, hasVariants }: FormCardProps & { hasVariants: boolean }) {- return (- <Card>- <CardHeader>- <CardTitle>Shipping</CardTitle>- </CardHeader>- <CardContent className="flex flex-col gap-4">- {!hasVariants && (- <>- <div className="grid grid-cols-2 gap-3">- <div className="grid gap-2">- <Label htmlFor="weight">Weight</Label>- <Input- id="weight"- type="number"- step="any"- placeholder="0.0"- {...form.register('weight')}- />- </div>- <div className="grid gap-2">- <Label>Unit</Label>- <Controller- name="weight_unit"- control={form.control}- render={({ field }) => (- <Select- value={field.value ?? ''}- onValueChange={(v) => field.onChange(v || null)}- >- <SelectTrigger className="w-full">- <SelectValue placeholder="Unit" />- </SelectTrigger>- <SelectContent>- <SelectItem value="oz">oz</SelectItem>- <SelectItem value="lb">lb</SelectItem>- <SelectItem value="g">g</SelectItem>- <SelectItem value="kg">kg</SelectItem>- </SelectContent>- </Select>- )}- />- </div>- </div>-- <div className="grid grid-cols-3 gap-3">- <div className="grid gap-2">- <Label htmlFor="height">H</Label>- <Input- id="height"- type="number"- step="any"- placeholder="0.0"- {...form.register('height')}- />- </div>- <div className="grid gap-2">- <Label htmlFor="width">W</Label>- <Input- id="width"- type="number"- step="any"- placeholder="0.0"- {...form.register('width')}- />- </div>- <div className="grid gap-2">- <Label htmlFor="depth">D</Label>- <Input- id="depth"- type="number"- step="any"- placeholder="0.0"- {...form.register('depth')}- />- </div>- </div>-- <div className="grid gap-2">- <Label>Dimensions unit</Label>- <Controller- name="dimensions_unit"- control={form.control}- render={({ field }) => (- <Select- value={field.value ?? ''}- onValueChange={(v) => field.onChange(v || null)}- >- <SelectTrigger className="w-full">- <SelectValue placeholder="Unit" />- </SelectTrigger>- <SelectContent>- <SelectItem value="in">in</SelectItem>- <SelectItem value="ft">ft</SelectItem>- <SelectItem value="cm">cm</SelectItem>- <SelectItem value="mm">mm</SelectItem>- </SelectContent>- </Select>- )}- />- </div>- </>- )}- </CardContent>- </Card>- )-}--// ----------------------------------------------------------------------------// Tax-// -----------------------------------------------------------------------------function TaxCard({ form }: FormCardProps) {- const { data: taxCategoriesResponse } = useTaxCategories()- const taxCategories = taxCategoriesResponse?.data ?? []-- return (- <Card>- <CardHeader>- <CardTitle>Tax</CardTitle>- </CardHeader>- <CardContent>- <div className="grid gap-2">- <Label>Tax category</Label>- <Controller- name="tax_category_id"- control={form.control}- render={({ field }) => (- <Select value={field.value ?? ''} onValueChange={(v) => field.onChange(v || null)}>- <SelectTrigger className="w-full">- <SelectValue placeholder="Select tax category" />- </SelectTrigger>- <SelectContent>- {taxCategories.map((cat) => (- <SelectItem key={cat.id} value={cat.id}>- {cat.name}- </SelectItem>- ))}- </SelectContent>- </Select>- )}- />- </div>- </CardContent>- </Card>- )-}--// ----------------------------------------------------------------------------// Loading skeleton-// -----------------------------------------------------------------------------function ProductSkeleton() {- return (- <div className="flex flex-col gap-6">- <div className="flex items-center gap-3">- <Skeleton className="size-8 rounded-lg" />- <Skeleton className="h-8 w-48" />- <Skeleton className="h-5 w-16 rounded-md" />- <div className="ml-auto flex items-center gap-2">- <Skeleton className="h-8 w-20 rounded-lg" />- <Skeleton className="h-8 w-16 rounded-lg" />- </div>- </div>- <div className="grid grid-cols-12 gap-6">- <div className="col-span-12 lg:col-span-8 flex flex-col gap-6">- <Skeleton className="h-72 w-full rounded-xl" />- <Skeleton className="h-48 w-full rounded-xl" />- <Skeleton className="h-40 w-full rounded-xl" />- <Skeleton className="h-40 w-full rounded-xl" />- <Skeleton className="h-52 w-full rounded-xl" />- </div>- <div className="col-span-12 lg:col-span-4 flex flex-col gap-6">- <Skeleton className="h-56 w-full rounded-xl" />- <Skeleton className="h-40 w-full rounded-xl" />- <Skeleton className="h-52 w-full rounded-xl" />- <Skeleton className="h-24 w-full rounded-xl" />- </div>- </div>- </div>- )-}diff --git a/packages/admin/src/routes/_authenticated/products/index.tsx b/packages/admin/src/routes/_authenticated/products/index.tsxdeleted file mode 100644index 103ecb672b..0000000000--- a/packages/admin/src/routes/_authenticated/products/index.tsx+++ /dev/null@@ -1,30 +0,0 @@-import { createFileRoute } from '@tanstack/react-router'-import { PlusIcon } from 'lucide-react'-import { adminClient } from '@/client'-import { ResourceTable, resourceSearchSchema } from '@/components/resource-table'-import { Button } from '@/components/ui/button'-import '@/tables/products'--export const Route = createFileRoute('/_authenticated/products/')({- validateSearch: resourceSearchSchema,- component: ProductsPage,-})--function ProductsPage() {- const searchParams = Route.useSearch()-- return (- <ResourceTable- tableKey="products"- queryKey="products"- queryFn={(params) => adminClient.products.list(params)}- searchParams={searchParams}- actions={- <Button size="sm" className="h-[2.125rem]">- <PlusIcon className="size-4" />- Add Product- </Button>- }- />- )-}diff --git a/packages/admin/src/routes/login.tsx b/packages/admin/src/routes/login.tsxindex bd445fee0a..648d6717bd 100644--- a/packages/admin/src/routes/login.tsx+++ b/packages/admin/src/routes/login.tsx@@ -19,7 +19,7 @@ type LoginForm = z.infer<typeof loginSchema>export const Route = createFileRoute('/login')({beforeLoad: ({ context }) => {if (context.auth.isAuthenticated) {- throw redirect({ to: '/' })+ throw redirect({ to: '/' }) // Will redirect to /$storeId via _authenticated/index}},component: LoginPage,diff --git a/packages/admin/src/tables/orders.tsx b/packages/admin/src/tables/orders.tsxindex 5cb0fa36f5..0f4fd443f0 100644--- a/packages/admin/src/tables/orders.tsx+++ b/packages/admin/src/tables/orders.tsx@@ -20,8 +20,8 @@ defineTable('orders', {default: true,render: (order) => (<Link- to="/orders/$orderId"- params={{ orderId: order.id }}+ to="/$storeId/orders/$orderId"+ params={{ orderId: order.id } as Record<string, string>}className="font-medium text-zinc-950 no-underline">#{order.number}diff --git a/packages/admin/src/tables/products.tsx b/packages/admin/src/tables/products.tsxindex 56233d3fd2..df0295065f 100644--- a/packages/admin/src/tables/products.tsx+++ b/packages/admin/src/tables/products.tsx@@ -20,8 +20,8 @@ defineTable("products", {default: true,render: (product) => (<Link- to="/products/$productId"- params={{ productId: product.id }}+ to="/$storeId/products/$productId"+ params={{ productId: product.id } as Record<string, string>}className="flex items-center gap-3 no-underline"><div className="flex size-10 shrink-0 items-center justify-center rounded-lg border border-gray-200 bg-gray-50 overflow-hidden">