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.

PoC Admin Product edit screen

Damian Legawiec91b923e79372
diff --git a/package.json b/package.json
index 4851a5a2d2..9e467cc737 100644
--- a/package.json
+++ b/package.json
@@ -24,5 +24,8 @@
"packageManager": "[email protected]",
"engines": {
"node": ">=20"
+ },
+ "dependencies": {
+ "@base-ui/react": "^1.2.0"
}
}
diff --git a/packages/admin/package.json b/packages/admin/package.json
index c76f744014..4a82e256b8 100644
--- a/packages/admin/package.json
+++ b/packages/admin/package.json
@@ -12,20 +12,29 @@
"preview": "vite preview"
},
"dependencies": {
+ "@base-ui/react": "^1.2.0",
"@fontsource-variable/geist": "^5.2.8",
"@fontsource-variable/inter": "^5.2.8",
"@hookform/resolvers": "^5.2.2",
"@spree/sdk": "workspace:^",
"@tanstack/react-query": "^5.90.21",
"@tanstack/react-router": "^1.166.2",
+ "@tiptap/extension-link": "^3.20.1",
+ "@tiptap/extension-placeholder": "^3.20.1",
+ "@tiptap/react": "^3.20.1",
+ "@tiptap/starter-kit": "^3.20.1",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "date-fns": "^4.1.0",
"lucide-react": "^0.577.0",
"radix-ui": "^1.4.3",
"react": "^19.2.0",
+ "react-day-picker": "^9.14.0",
"react-dom": "^19.2.0",
"react-hook-form": "^7.71.2",
"shadcn": "^4.0.0",
+ "sonner": "^2.0.7",
+ "spark-md5": "^3.0.2",
"tailwind-merge": "^3.5.0",
"tw-animate-css": "^1.4.0",
"zod": "^4.3.6"
@@ -37,6 +46,7 @@
"@types/node": "^24.10.1",
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
+ "@types/spark-md5": "^3.0.5",
"@vitejs/plugin-react": "^5.1.1",
"tailwindcss": "^4.2.1",
"typescript": "~5.9.3",
diff --git a/packages/admin/src/components/nav-main.tsx b/packages/admin/src/components/nav-main.tsx
index edabd6485d..bb769f54bc 100644
--- a/packages/admin/src/components/nav-main.tsx
+++ b/packages/admin/src/components/nav-main.tsx
@@ -1,12 +1,12 @@
-import { Link, useRouterState } from '@tanstack/react-router'
-import { useState } from 'react'
-import type { NavItem } from '@/components/app-sidebar'
+import { Link, useRouterState } from "@tanstack/react-router";
+import { useState } from "react";
+import type { NavItem } from "@/components/app-sidebar";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
-} from '@/components/ui/dropdown-menu'
+} from "@/components/ui/dropdown-menu";
import {
SidebarGroup,
SidebarMenu,
@@ -16,25 +16,37 @@ import {
SidebarMenuSubButton,
SidebarMenuSubItem,
useSidebar,
-} from '@/components/ui/sidebar'
+} from "@/components/ui/sidebar";
-function NavIcon({ icon: Icon, isActive }: { icon: NavItem['icon']; isActive?: boolean }) {
+function NavIcon({
+ icon: Icon,
+ isActive,
+}: {
+ icon: NavItem["icon"];
+ isActive?: boolean;
+}) {
return (
<span
className={
- 'inline-flex shrink-0 items-center justify-center rounded-lg p-[0.2rem] transition-colors duration-100 ' +
+ "inline-flex shrink-0 items-center justify-center rounded-lg p-[0.2rem] transition-colors duration-100 " +
(isActive
- ? 'bg-zinc-950 text-white'
- : 'text-gray-400 group-hover/menu-button:text-zinc-950')
+ ? "bg-zinc-950 text-white"
+ : "group-hover/menu-button:text-zinc-950")
}
>
- <Icon className="size-[1.125rem]" strokeWidth={2.25} />
+ <Icon size={16} strokeWidth={2} />
</span>
- )
+ );
}
-function CollapsedDropdown({ item, children }: { item: NavItem; children: React.ReactNode }) {
- const [open, setOpen] = useState(false)
+function CollapsedDropdown({
+ item,
+ children,
+}: {
+ item: NavItem;
+ children: React.ReactNode;
+}) {
+ const [open, setOpen] = useState(false);
return (
<DropdownMenu open={open} onOpenChange={setOpen}>
@@ -58,7 +70,7 @@ function CollapsedDropdown({ item, children }: { item: NavItem; children: React.
))}
</DropdownMenuContent>
</DropdownMenu>
- )
+ );
}
function NavItemContent({
@@ -66,17 +78,18 @@ function NavItemContent({
currentPath,
isCollapsed,
}: {
- item: NavItem
- currentPath: string
- isCollapsed: boolean
+ item: NavItem;
+ currentPath: string;
+ isCollapsed: boolean;
}) {
- const isExactActive = currentPath === item.url
- const isActive = isExactActive || (item.url !== '/' && currentPath.startsWith(item.url))
+ const isExactActive = currentPath === item.url;
+ const isActive =
+ isExactActive || (item.url !== "/" && currentPath.startsWith(item.url));
const hasActiveChild = item.items?.some(
(sub) => currentPath === sub.url || currentPath.startsWith(sub.url),
- )
- const showSubmenu = isActive || hasActiveChild
- const itemIsActive = isActive || !!hasActiveChild
+ );
+ const showSubmenu = isActive || hasActiveChild;
+ const itemIsActive = isActive || !!hasActiveChild;
const button = (
<SidebarMenuButton
@@ -89,7 +102,7 @@ function NavItemContent({
<span>{item.title}</span>
</Link>
</SidebarMenuButton>
- )
+ );
return (
<SidebarMenuItem>
@@ -101,7 +114,9 @@ function NavItemContent({
{item.items && showSubmenu && (
<SidebarMenuSub>
{item.items.map((subItem) => {
- const subActive = currentPath === subItem.url || currentPath.startsWith(subItem.url)
+ const subActive =
+ currentPath === subItem.url ||
+ currentPath.startsWith(subItem.url);
return (
<SidebarMenuSubItem key={subItem.title}>
<SidebarMenuSubButton asChild isActive={subActive}>
@@ -110,19 +125,25 @@ function NavItemContent({
</Link>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
- )
+ );
})}
</SidebarMenuSub>
)}
</SidebarMenuItem>
- )
+ );
}
-export function NavMain({ items, bottomItems }: { items: NavItem[]; bottomItems?: NavItem[] }) {
- const routerState = useRouterState()
- const currentPath = routerState.location.pathname
- const { state } = useSidebar()
- const isCollapsed = state === 'collapsed'
+export function NavMain({
+ items,
+ bottomItems,
+}: {
+ items: NavItem[];
+ bottomItems?: NavItem[];
+}) {
+ const routerState = useRouterState();
+ const currentPath = routerState.location.pathname;
+ const { state } = useSidebar();
+ const isCollapsed = state === "collapsed";
return (
<>
@@ -144,22 +165,27 @@ export function NavMain({ items, bottomItems }: { items: NavItem[]; bottomItems?
<SidebarMenu>
{bottomItems.map((item) => {
const isActive =
- currentPath === item.url || (item.url !== '/' && currentPath.startsWith(item.url))
+ currentPath === item.url ||
+ (item.url !== "/" && currentPath.startsWith(item.url));
return (
<SidebarMenuItem key={item.title}>
- <SidebarMenuButton tooltip={item.title} asChild isActive={isActive}>
+ <SidebarMenuButton
+ tooltip={item.title}
+ asChild
+ isActive={isActive}
+ >
<Link to={item.url}>
<NavIcon icon={item.icon} isActive={isActive} />
<span>{item.title}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
- )
+ );
})}
</SidebarMenu>
</SidebarGroup>
)}
</>
- )
+ );
}
diff --git a/packages/admin/src/components/resource-table.tsx b/packages/admin/src/components/resource-table.tsx
index 587f0ebee8..f9f8c38ccb 100644
--- a/packages/admin/src/components/resource-table.tsx
+++ b/packages/admin/src/components/resource-table.tsx
@@ -1,9 +1,9 @@
-import { useQuery } from "@tanstack/react-query";
-import { useNavigate } from "@tanstack/react-router";
-import { type ReactNode, useDeferredValue, useState } from "react";
-import { z } from "zod/v4";
-import { TableToolbar } from "@/components/table-toolbar";
-import { Card, CardContent } from "@/components/ui/card";
+import { useQuery } from '@tanstack/react-query'
+import { useNavigate } from '@tanstack/react-router'
+import { type ReactNode, useDeferredValue, useState } from 'react'
+import { z } from 'zod/v4'
+import { TableToolbar } from '@/components/table-toolbar'
+import { Card, CardContent } from '@/components/ui/card'
import {
Table,
TableBody,
@@ -12,16 +12,16 @@ import {
TableHead,
TableHeader,
TableRow,
-} from "@/components/ui/data-table";
-import { Pagination, type PaginationMeta } from "@/components/ui/pagination";
-import { useAuth } from "@/hooks/use-auth";
+} from '@/components/ui/data-table'
+import { Pagination, type PaginationMeta } from '@/components/ui/pagination'
+import { useAuth } from '@/hooks/use-auth'
import {
type FilterRule,
getDefaultColumnKeys,
getDisplayableColumns,
getTable,
type SortOption,
-} from "@/lib/table-registry";
+} from '@/lib/table-registry'
// ============================================================================
// Search schema — shared by all resource table routes
@@ -32,30 +32,31 @@ const filterSchema = z.object({
field: z.string(),
operator: z.string(),
value: z.string(),
-});
+})
export const resourceSearchSchema = z.object({
page: z.coerce.number().optional().default(1),
+ limit: z.coerce.number().optional(),
sort: z.string().optional(),
- dir: z.enum(["asc", "desc"]).optional(),
+ dir: z.enum(['asc', 'desc']).optional(),
search: z.string().optional(),
filters: z.preprocess((val) => {
- if (typeof val === "string") {
+ if (typeof val === 'string') {
try {
- return JSON.parse(val);
+ return JSON.parse(val)
} catch {
- return [];
+ return []
}
}
- return val ?? [];
+ return val ?? []
}, z.array(filterSchema).optional().default([])),
columns: z.preprocess((val) => {
- if (typeof val === "string") return val.split(",");
- return val ?? undefined;
+ if (typeof val === 'string') return val.split(',')
+ return val ?? undefined
}, z.array(z.string()).optional()),
-});
+})
-export type ResourceSearch = z.infer<typeof resourceSearchSchema>;
+export type ResourceSearch = z.infer<typeof resourceSearchSchema>
// ============================================================================
// Props
@@ -63,21 +64,19 @@ export type ResourceSearch = z.infer<typeof resourceSearchSchema>;
interface ResourceTableProps<T> {
/** Registry key (e.g., 'products') */
- tableKey: string;
+ tableKey: string
/** TanStack Query key prefix (e.g., 'products') */
- queryKey: string;
+ queryKey: string
/** Function that calls the SDK to fetch data */
- queryFn: (
- params: Record<string, unknown>,
- ) => Promise<{ data: T[]; meta: PaginationMeta }>;
+ queryFn: (params: Record<string, unknown>) => Promise<{ data: T[]; meta: PaginationMeta }>
/** Current search params from the route */
- searchParams: ResourceSearch;
+ searchParams: ResourceSearch
/** Title displayed in the toolbar header. Overrides the table definition's title. */
- title?: string;
+ title?: string
/** Default params always sent with every request (e.g., { complete: 1 } for orders) */
- defaultParams?: Record<string, unknown>;
+ defaultParams?: Record<string, unknown>
/** Actions to render in the toolbar (e.g., "Add Product" button) */
- actions?: ReactNode;
+ actions?: ReactNode
}
// ============================================================================
@@ -93,111 +92,109 @@ export function ResourceTable<T extends Record<string, any>>({
defaultParams,
actions,
}: ResourceTableProps<T>) {
- const table = getTable<T>(tableKey);
- const { token } = useAuth();
- const navigate = useNavigate();
+ const table = getTable<T>(tableKey)
+ const { token } = useAuth()
+ const navigate = useNavigate()
const {
page,
+ limit,
sort: urlSort,
dir: urlDir,
search,
filters,
columns: urlColumns,
- } = searchParams;
+ } = searchParams
const defaultSort = table.defaultSort ?? {
- field: "updated_at",
- direction: "desc" as const,
- };
- const sort = urlSort ?? defaultSort.field;
- const dir = urlDir ?? defaultSort.direction;
+ field: 'updated_at',
+ direction: 'desc' as const,
+ }
+ const sort = urlSort ?? defaultSort.field
+ const dir = urlDir ?? defaultSort.direction
- const [searchInput, setSearchInput] = useState(search ?? "");
- const deferredSearch = useDeferredValue(searchInput);
+ const [searchInput, setSearchInput] = useState(search ?? '')
+ const deferredSearch = useDeferredValue(searchInput)
- const displayableColumns = getDisplayableColumns(table);
- const defaultColumnKeys = getDefaultColumnKeys(table);
- const visibleColumnKeys = urlColumns ?? defaultColumnKeys;
+ const displayableColumns = getDisplayableColumns(table)
+ const defaultColumnKeys = getDefaultColumnKeys(table)
+ const visibleColumnKeys = urlColumns ?? defaultColumnKeys
- const visibleColumns = displayableColumns.filter((c) =>
- visibleColumnKeys.includes(c.key),
- );
+ const visibleColumns = displayableColumns.filter((c) => visibleColumnKeys.includes(c.key))
// Build API params
- const sortString = dir === "desc" ? `-${sort}` : sort;
+ const sortString = dir === 'desc' ? `-${sort}` : sort
const { data, isLoading } = useQuery({
- queryKey: [
- queryKey,
- { page, sort: sortString, search: deferredSearch, filters },
- ],
+ queryKey: [queryKey, { page, limit, sort: sortString, search: deferredSearch, filters }],
queryFn: () => {
const params: Record<string, unknown> = {
page,
sort: sortString,
...defaultParams,
- };
+ }
+
+ if (limit) {
+ params.limit = limit
+ }
if (deferredSearch) {
- const searchParam = table.searchParam ?? "name_cont";
- params[searchParam] = deferredSearch;
+ const searchParam = table.searchParam ?? 'name_cont'
+ params[searchParam] = deferredSearch
}
// Convert FilterRule[] to Ransack params
for (const filter of filters as FilterRule[]) {
- const col = table.columns.find((c) => c.key === filter.field);
- const ransackKey = col?.ransackAttribute ?? filter.field;
- params[`${ransackKey}_${filter.operator}`] = filter.value;
+ const col = table.columns.find((c) => c.key === filter.field)
+ const ransackKey = col?.ransackAttribute ?? filter.field
+ params[`${ransackKey}_${filter.operator}`] = filter.value
}
- return queryFn(params);
+ return queryFn(params)
},
enabled: !!token,
- });
+ })
- const rows = data?.data ?? [];
- const meta = data?.meta;
+ const rows = data?.data ?? []
+ const meta = data?.meta
// Navigation helpers
function updateSearch(updates: Record<string, unknown>) {
navigate({
- search: (prev: Record<string, unknown>) =>
- ({ ...prev, ...updates }) as never,
- });
+ search: (prev: Record<string, unknown>) => ({ ...prev, ...updates }) as never,
+ })
}
function handleSearchChange(value: string) {
- setSearchInput(value);
- updateSearch({ search: value || undefined, page: 1 });
+ setSearchInput(value)
+ updateSearch({ search: value || undefined, page: 1 })
}
function handleSortChange(s: SortOption) {
- updateSearch({ sort: s.field, dir: s.direction, page: 1 });
+ updateSearch({ sort: s.field, dir: s.direction, page: 1 })
}
function handleFiltersChange(f: FilterRule[]) {
updateSearch({
filters: f.length > 0 ? JSON.stringify(f) : undefined,
page: 1,
- });
+ })
}
function handleColumnsChange(cols: string[]) {
const isDefault =
- cols.length === defaultColumnKeys.length &&
- cols.every((c) => defaultColumnKeys.includes(c));
- updateSearch({ columns: isDefault ? undefined : cols.join(",") });
+ cols.length === defaultColumnKeys.length && cols.every((c) => defaultColumnKeys.includes(c))
+ updateSearch({ columns: isDefault ? undefined : cols.join(',') })
}
// Header columns for price-like right-aligned columns
const headerColumns = visibleColumns.map((col) => {
- const isRightAligned = col.className?.includes("text-right");
+ const isRightAligned = col.className?.includes('text-right')
return {
...col,
- headerClassName: isRightAligned ? "text-right" : undefined,
- };
- });
+ headerClassName: isRightAligned ? 'text-right' : undefined,
+ }
+ })
return (
<Card className="rounded-2xl">
@@ -207,7 +204,7 @@ export function ResourceTable<T extends Record<string, any>>({
onVisibleColumnsChange={handleColumnsChange}
search={searchInput}
onSearchChange={handleSearchChange}
- searchPlaceholder={table.searchPlaceholder ?? "Search..."}
+ searchPlaceholder={table.searchPlaceholder ?? 'Search...'}
sort={{ field: sort, direction: dir }}
onSortChange={handleSortChange}
filters={filters as FilterRule[]}
@@ -229,18 +226,14 @@ export function ResourceTable<T extends Record<string, any>>({
</TableHeader>
<TableBody>
{isLoading ? (
- <TableEmpty colSpan={visibleColumns.length}>
- Loading...
- </TableEmpty>
+ <TableEmpty colSpan={visibleColumns.length}>Loading...</TableEmpty>
) : rows.length === 0 ? (
<TableEmpty colSpan={visibleColumns.length}>
<div className="flex flex-col items-center gap-2">
{table.emptyIcon}
- <p>{table.emptyMessage ?? "No results found"}</p>
+ <p>{table.emptyMessage ?? 'No results found'}</p>
{(deferredSearch || (filters as FilterRule[]).length > 0) && (
- <p className="text-xs">
- Try adjusting your search or filters
- </p>
+ <p className="text-xs">Try adjusting your search or filters</p>
)}
</div>
</TableEmpty>
@@ -249,9 +242,7 @@ export function ResourceTable<T extends Record<string, any>>({
<TableRow key={(row as any).id ?? i}>
{visibleColumns.map((col) => (
<TableCell key={col.key} className={col.className}>
- {col.render
- ? col.render(row)
- : String((row as any)[col.key] ?? "—")}
+ {col.render ? col.render(row) : String((row as any)[col.key] ?? '—')}
</TableCell>
))}
</TableRow>
@@ -263,9 +254,10 @@ export function ResourceTable<T extends Record<string, any>>({
<Pagination
meta={meta}
onPageChange={(p) => updateSearch({ page: p })}
+ onPageSizeChange={(size) => updateSearch({ limit: size, page: 1 })}
/>
)}
</CardContent>
</Card>
- );
+ )
}
diff --git a/packages/admin/src/components/ui/calendar.tsx b/packages/admin/src/components/ui/calendar.tsx
new file mode 100644
index 0000000000..aa4cb51d3a
--- /dev/null
+++ b/packages/admin/src/components/ui/calendar.tsx
@@ -0,0 +1,60 @@
+import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react'
+import type * as React from 'react'
+import { DayPicker } from 'react-day-picker'
+import { cn } from '@/lib/utils'
+
+function Calendar({
+ className,
+ classNames,
+ showOutsideDays = true,
+ ...props
+}: React.ComponentProps<typeof DayPicker>) {
+ return (
+ <DayPicker
+ showOutsideDays={showOutsideDays}
+ className={cn('p-3', className)}
+ classNames={{
+ months: 'flex flex-col sm:flex-row gap-2',
+ month: 'flex flex-col gap-4',
+ month_caption: 'flex justify-center pt-1 relative items-center w-full',
+ caption_label: 'text-sm font-medium',
+ nav: 'flex items-center gap-1',
+ button_previous:
+ 'absolute left-1 top-0 inline-flex size-7 items-center justify-center rounded-md border border-gray-200 bg-transparent p-0 text-gray-600 opacity-50 hover:opacity-100 transition-opacity',
+ button_next:
+ 'absolute right-1 top-0 inline-flex size-7 items-center justify-center rounded-md border border-gray-200 bg-transparent p-0 text-gray-600 opacity-50 hover:opacity-100 transition-opacity',
+ month_grid: 'w-full border-collapse',
+ weekdays: 'flex',
+ weekday: 'text-muted-foreground rounded-md w-8 font-normal text-xs',
+ week: 'flex w-full mt-2',
+ day: 'relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-blue-50 [&:has([aria-selected].day-outside)]:bg-blue-50/50 [&:has([aria-selected].day-range-end)]:rounded-r-md',
+ day_button: cn(
+ 'inline-flex size-8 items-center justify-center rounded-md p-0 font-normal transition-colors',
+ 'hover:bg-gray-100 hover:text-gray-950',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500',
+ 'aria-selected:bg-blue-600 aria-selected:text-white aria-selected:hover:bg-blue-700 aria-selected:focus:bg-blue-700',
+ ),
+ range_end: 'day-range-end rounded-r-md',
+ selected: 'bg-blue-600 text-white hover:bg-blue-700 focus:bg-blue-700',
+ today: 'bg-gray-100 text-gray-950',
+ outside:
+ 'day-outside text-muted-foreground opacity-50 aria-selected:bg-blue-50 aria-selected:text-muted-foreground aria-selected:opacity-30',
+ disabled: 'text-muted-foreground opacity-50',
+ range_middle: 'aria-selected:bg-blue-50 aria-selected:text-gray-950',
+ hidden: 'invisible',
+ ...classNames,
+ }}
+ components={{
+ Chevron: ({ orientation }) =>
+ orientation === 'left' ? (
+ <ChevronLeftIcon className="size-4" />
+ ) : (
+ <ChevronRightIcon className="size-4" />
+ ),
+ }}
+ {...props}
+ />
+ )
+}
+
+export { Calendar }
diff --git a/packages/admin/src/components/ui/combobox.tsx b/packages/admin/src/components/ui/combobox.tsx
new file mode 100644
index 0000000000..352afc332c
--- /dev/null
+++ b/packages/admin/src/components/ui/combobox.tsx
@@ -0,0 +1,299 @@
+"use client"
+
+import * as React from "react"
+import { Combobox as ComboboxPrimitive } from "@base-ui/react"
+
+import { cn } from "@/lib/utils"
+import { Button } from "@/components/ui/button"
+import {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupButton,
+ InputGroupInput,
+} from "@/components/ui/input-group"
+import { ChevronDownIcon, XIcon, CheckIcon } from "lucide-react"
+
+const Combobox = ComboboxPrimitive.Root
+
+function ComboboxValue({ ...props }: ComboboxPrimitive.Value.Props) {
+ return <ComboboxPrimitive.Value data-slot="combobox-value" {...props} />
+}
+
+function ComboboxTrigger({
+ className,
+ children,
+ ...props
+}: ComboboxPrimitive.Trigger.Props) {
+ return (
+ <ComboboxPrimitive.Trigger
+ data-slot="combobox-trigger"
+ className={cn("[&_svg:not([class*='size-'])]:size-4", className)}
+ {...props}
+ >
+ {children}
+ <ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />
+ </ComboboxPrimitive.Trigger>
+ )
+}
+
+function ComboboxClear({ className, ...props }: ComboboxPrimitive.Clear.Props) {
+ return (
+ <ComboboxPrimitive.Clear
+ data-slot="combobox-clear"
+ render={<InputGroupButton variant="ghost" size="icon-xs" />}
+ className={cn(className)}
+ {...props}
+ >
+ <XIcon className="pointer-events-none" />
+ </ComboboxPrimitive.Clear>
+ )
+}
+
+function ComboboxInput({
+ className,
+ children,
+ disabled = false,
+ showTrigger = true,
+ showClear = false,
+ ...props
+}: ComboboxPrimitive.Input.Props & {
+ showTrigger?: boolean
+ showClear?: boolean
+}) {
+ return (
+ <InputGroup className={cn("w-auto", className)}>
+ <ComboboxPrimitive.Input
+ render={<InputGroupInput disabled={disabled} />}
+ {...props}
+ />
+ <InputGroupAddon align="inline-end">
+ {showTrigger && (
+ <InputGroupButton
+ size="icon-xs"
+ variant="ghost"
+ asChild
+ data-slot="input-group-button"
+ className="group-has-data-[slot=combobox-clear]/input-group:hidden data-pressed:bg-transparent"
+ disabled={disabled}
+ >
+ <ComboboxTrigger />
+ </InputGroupButton>
+ )}
+ {showClear && <ComboboxClear disabled={disabled} />}
+ </InputGroupAddon>
+ {children}
+ </InputGroup>
+ )
+}
+
+function ComboboxContent({
+ className,
+ side = "bottom",
+ sideOffset = 6,
+ align = "start",
+ alignOffset = 0,
+ anchor,
+ ...props
+}: ComboboxPrimitive.Popup.Props &
+ Pick<
+ ComboboxPrimitive.Positioner.Props,
+ "side" | "align" | "sideOffset" | "alignOffset" | "anchor"
+ >) {
+ return (
+ <ComboboxPrimitive.Portal>
+ <ComboboxPrimitive.Positioner
+ side={side}
+ sideOffset={sideOffset}
+ align={align}
+ alignOffset={alignOffset}
+ anchor={anchor}
+ className="isolate z-50"
+ >
+ <ComboboxPrimitive.Popup
+ data-slot="combobox-content"
+ data-chips={!!anchor}
+ className={cn("group/combobox-content relative max-h-(--available-height) w-(--anchor-width) max-w-(--available-width) min-w-[calc(var(--anchor-width)+--spacing(7))] origin-(--transform-origin) overflow-hidden rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[chips=true]:min-w-(--anchor-width) data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 *:data-[slot=input-group]:m-1 *:data-[slot=input-group]:mb-0 *:data-[slot=input-group]:h-8 *:data-[slot=input-group]:border-input/30 *:data-[slot=input-group]:bg-input/30 *:data-[slot=input-group]:shadow-none data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
+ {...props}
+ />
+ </ComboboxPrimitive.Positioner>
+ </ComboboxPrimitive.Portal>
+ )
+}
+
+function ComboboxList({ className, ...props }: ComboboxPrimitive.List.Props) {
+ return (
+ <ComboboxPrimitive.List
+ data-slot="combobox-list"
+ className={cn(
+ "no-scrollbar max-h-[min(calc(--spacing(72)---spacing(9)),calc(var(--available-height)---spacing(9)))] scroll-py-1 overflow-y-auto overscroll-contain p-1 data-empty:p-0",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function ComboboxItem({
+ className,
+ children,
+ ...props
+}: ComboboxPrimitive.Item.Props) {
+ return (
+ <ComboboxPrimitive.Item
+ data-slot="combobox-item"
+ className={cn(
+ "relative flex w-full cursor-default items-center gap-2 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground not-data-[variant=destructive]:data-highlighted:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ <ComboboxPrimitive.ItemIndicator
+ render={
+ <span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center" />
+ }
+ >
+ <CheckIcon className="pointer-events-none" />
+ </ComboboxPrimitive.ItemIndicator>
+ </ComboboxPrimitive.Item>
+ )
+}
+
+function ComboboxGroup({ className, ...props }: ComboboxPrimitive.Group.Props) {
+ return (
+ <ComboboxPrimitive.Group
+ data-slot="combobox-group"
+ className={cn(className)}
+ {...props}
+ />
+ )
+}
+
+function ComboboxLabel({
+ className,
+ ...props
+}: ComboboxPrimitive.GroupLabel.Props) {
+ return (
+ <ComboboxPrimitive.GroupLabel
+ data-slot="combobox-label"
+ className={cn("px-2 py-1.5 text-xs text-muted-foreground", className)}
+ {...props}
+ />
+ )
+}
+
+function ComboboxCollection({ ...props }: ComboboxPrimitive.Collection.Props) {
+ return (
+ <ComboboxPrimitive.Collection data-slot="combobox-collection" {...props} />
+ )
+}
+
+function ComboboxEmpty({ className, ...props }: ComboboxPrimitive.Empty.Props) {
+ return (
+ <ComboboxPrimitive.Empty
+ data-slot="combobox-empty"
+ className={cn(
+ "hidden w-full justify-center py-2 text-center text-sm text-muted-foreground group-data-empty/combobox-content:flex",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function ComboboxSeparator({
+ className,
+ ...props
+}: ComboboxPrimitive.Separator.Props) {
+ return (
+ <ComboboxPrimitive.Separator
+ data-slot="combobox-separator"
+ className={cn("-mx-1 my-1 h-px bg-border", className)}
+ {...props}
+ />
+ )
+}
+
+function ComboboxChips({
+ className,
+ ...props
+}: React.ComponentPropsWithRef<typeof ComboboxPrimitive.Chips> &
+ ComboboxPrimitive.Chips.Props) {
+ return (
+ <ComboboxPrimitive.Chips
+ data-slot="combobox-chips"
+ className={cn(
+ "flex min-h-8 flex-wrap items-center gap-1 rounded-lg border border-input bg-transparent bg-clip-padding px-2.5 py-1 text-sm transition-colors focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50 has-aria-invalid:border-destructive has-aria-invalid:ring-3 has-aria-invalid:ring-destructive/20 has-data-[slot=combobox-chip]:px-1 dark:bg-input/30 dark:has-aria-invalid:border-destructive/50 dark:has-aria-invalid:ring-destructive/40",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function ComboboxChip({
+ className,
+ children,
+ showRemove = true,
+ ...props
+}: ComboboxPrimitive.Chip.Props & {
+ showRemove?: boolean
+}) {
+ return (
+ <ComboboxPrimitive.Chip
+ data-slot="combobox-chip"
+ className={cn(
+ "flex h-[calc(--spacing(5.25))] w-fit items-center justify-center gap-1 rounded-sm bg-muted px-1.5 text-xs font-medium whitespace-nowrap text-foreground has-disabled:pointer-events-none has-disabled:cursor-not-allowed has-disabled:opacity-50 has-data-[slot=combobox-chip-remove]:pr-0",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ {showRemove && (
+ <ComboboxPrimitive.ChipRemove
+ render={<Button variant="ghost" size="icon-xs" />}
+ className="-ml-1 opacity-50 hover:opacity-100"
+ data-slot="combobox-chip-remove"
+ >
+ <XIcon className="pointer-events-none" />
+ </ComboboxPrimitive.ChipRemove>
+ )}
+ </ComboboxPrimitive.Chip>
+ )
+}
+
+function ComboboxChipsInput({
+ className,
+ ...props
+}: ComboboxPrimitive.Input.Props) {
+ return (
+ <ComboboxPrimitive.Input
+ data-slot="combobox-chip-input"
+ className={cn("min-w-16 flex-1 outline-none", className)}
+ {...props}
+ />
+ )
+}
+
+function useComboboxAnchor() {
+ return React.useRef<HTMLDivElement | null>(null)
+}
+
+export {
+ Combobox,
+ ComboboxInput,
+ ComboboxContent,
+ ComboboxList,
+ ComboboxItem,
+ ComboboxGroup,
+ ComboboxLabel,
+ ComboboxCollection,
+ ComboboxEmpty,
+ ComboboxSeparator,
+ ComboboxChips,
+ ComboboxChip,
+ ComboboxChipsInput,
+ ComboboxTrigger,
+ ComboboxValue,
+ useComboboxAnchor,
+}
diff --git a/packages/admin/src/components/ui/date-picker.tsx b/packages/admin/src/components/ui/date-picker.tsx
new file mode 100644
index 0000000000..f5eba152ff
--- /dev/null
+++ b/packages/admin/src/components/ui/date-picker.tsx
@@ -0,0 +1,115 @@
+import { format, parseISO } from 'date-fns'
+import { CalendarIcon, XIcon } from 'lucide-react'
+import { useState } from 'react'
+import { Button } from '@/components/ui/button'
+import { Calendar } from '@/components/ui/calendar'
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
+import { cn } from '@/lib/utils'
+
+interface DatePickerProps {
+ value?: string | null
+ onChange?: (value: string | null) => void
+ placeholder?: string
+ className?: string
+ disabled?: boolean
+ includeTime?: boolean
+}
+
+function DatePicker({
+ value,
+ onChange,
+ placeholder = 'Pick a date',
+ className,
+ disabled = false,
+ includeTime = false,
+}: DatePickerProps) {
+ const [open, setOpen] = useState(false)
+
+ const date = value ? parseISO(value) : undefined
+ const isValidDate = date && !Number.isNaN(date.getTime())
+
+ const handleSelect = (selected: Date | undefined) => {
+ if (!selected) {
+ onChange?.(null)
+ return
+ }
+
+ if (includeTime && isValidDate) {
+ // Preserve existing time when changing date
+ selected.setHours(date.getHours(), date.getMinutes())
+ }
+
+ onChange?.(selected.toISOString())
+ if (!includeTime) setOpen(false)
+ }
+
+ const handleTimeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const [hours, minutes] = e.target.value.split(':').map(Number)
+ const d = isValidDate ? new Date(date) : new Date()
+ d.setHours(hours, minutes, 0, 0)
+ onChange?.(d.toISOString())
+ }
+
+ const handleClear = (e: React.MouseEvent) => {
+ e.stopPropagation()
+ onChange?.(null)
+ }
+
+ const timeValue = isValidDate
+ ? `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
+ : ''
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild disabled={disabled}>
+ <Button
+ type="button"
+ variant="outline"
+ data-empty={!isValidDate}
+ className={cn(
+ 'w-full justify-start text-left font-normal data-[empty=true]:text-gray-500',
+ className,
+ )}
+ >
+ <CalendarIcon className="size-4 shrink-0 text-gray-400" />
+ <span className="flex-1 truncate">
+ {isValidDate
+ ? format(date, includeTime ? 'PPP p' : 'PPP')
+ : placeholder}
+ </span>
+ {isValidDate && (
+ <span
+ role="button"
+ tabIndex={-1}
+ className="inline-flex size-4 items-center justify-center rounded-sm text-gray-400 hover:text-gray-600 transition-colors cursor-pointer"
+ onPointerDown={handleClear}
+ >
+ <XIcon className="size-3.5" />
+ </span>
+ )}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-auto p-0" align="start">
+ <Calendar
+ mode="single"
+ selected={isValidDate ? date : undefined}
+ onSelect={handleSelect}
+ defaultMonth={isValidDate ? date : undefined}
+ />
+ {includeTime && (
+ <div className="border-t border-gray-200 px-3 py-2">
+ <input
+ type="time"
+ value={timeValue}
+ onChange={handleTimeChange}
+ className="block w-full rounded-md border border-gray-200 bg-white px-2.5 py-1.5 text-sm outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1"
+ />
+ </div>
+ )}
+ </PopoverContent>
+ </Popover>
+ )
+}
+
+export { DatePicker }
+export type { DatePickerProps }
diff --git a/packages/admin/src/components/ui/dialog.tsx b/packages/admin/src/components/ui/dialog.tsx
new file mode 100644
index 0000000000..4555b62c13
--- /dev/null
+++ b/packages/admin/src/components/ui/dialog.tsx
@@ -0,0 +1,162 @@
+import { XIcon } from 'lucide-react'
+import { Dialog as DialogPrimitive } from 'radix-ui'
+import * as React from 'react'
+import { Button } from '@/components/ui/button'
+import { cn } from '@/lib/utils'
+
+function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
+ return <DialogPrimitive.Root data-slot="dialog" {...props} />
+}
+
+function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
+ return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
+}
+
+function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
+ return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
+}
+
+function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
+ return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
+}
+
+function DialogOverlay({
+ className,
+ ...props
+}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
+ return (
+ <DialogPrimitive.Overlay
+ data-slot="dialog-overlay"
+ className={cn(
+ 'fixed inset-0 isolate z-50 bg-white/80 duration-100 data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0',
+ className,
+ )}
+ {...props}
+ />
+ )
+}
+
+function DialogContent({
+ className,
+ children,
+ showCloseButton = true,
+ ...props
+}: React.ComponentProps<typeof DialogPrimitive.Content> & {
+ showCloseButton?: boolean
+}) {
+ return (
+ <DialogPortal>
+ <DialogOverlay />
+ <DialogPrimitive.Content
+ data-slot="dialog-content"
+ className={cn(
+ 'fixed top-1/2 left-1/2 z-50 flex w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden rounded-2xl bg-background text-sm duration-100 outline-none sm:max-w-[500px] data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
+ className,
+ )}
+ style={{
+ maxHeight: '90vh',
+ boxShadow:
+ '0px 0px 0px 1px rgba(179, 179, 179, 0.5), 0px 6px 12px -3px rgba(179, 179, 179, 0.35), 0px 6px 18px 0px rgba(179, 179, 179, 0.35)',
+ }}
+ {...props}
+ >
+ {children}
+ {showCloseButton && (
+ <DialogPrimitive.Close data-slot="dialog-close" asChild>
+ <Button variant="ghost" className="absolute top-3 right-3" size="icon-sm">
+ <XIcon />
+ <span className="sr-only">Close</span>
+ </Button>
+ </DialogPrimitive.Close>
+ )}
+ </DialogPrimitive.Content>
+ </DialogPortal>
+ )
+}
+
+function DialogHeader({ className, ...props }: React.ComponentProps<'div'>) {
+ return (
+ <div
+ data-slot="dialog-header"
+ className={cn('flex flex-col gap-1.5 border-b p-4', className)}
+ {...props}
+ />
+ )
+}
+
+function DialogBody({ className, ...props }: React.ComponentProps<'div'>) {
+ return (
+ <div
+ data-slot="dialog-body"
+ className={cn('flex-auto overflow-y-auto p-4', className)}
+ {...props}
+ />
+ )
+}
+
+function DialogFooter({
+ className,
+ showCloseButton = false,
+ children,
+ ...props
+}: React.ComponentProps<'div'> & {
+ showCloseButton?: boolean
+}) {
+ return (
+ <div
+ data-slot="dialog-footer"
+ className={cn(
+ 'flex flex-col-reverse gap-2 border-t bg-muted/50 p-4 sm:flex-row sm:justify-end',
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ {showCloseButton && (
+ <DialogPrimitive.Close asChild>
+ <Button variant="outline">Close</Button>
+ </DialogPrimitive.Close>
+ )}
+ </div>
+ )
+}
+
+function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
+ return (
+ <DialogPrimitive.Title
+ data-slot="dialog-title"
+ className={cn('text-base leading-none font-medium', className)}
+ {...props}
+ />
+ )
+}
+
+function DialogDescription({
+ className,
+ ...props
+}: React.ComponentProps<typeof DialogPrimitive.Description>) {
+ return (
+ <DialogPrimitive.Description
+ data-slot="dialog-description"
+ className={cn(
+ 'text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground',
+ className,
+ )}
+ {...props}
+ />
+ )
+}
+
+export {
+ Dialog,
+ DialogBody,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogOverlay,
+ DialogPortal,
+ DialogTitle,
+ DialogTrigger,
+}
diff --git a/packages/admin/src/components/ui/field.tsx b/packages/admin/src/components/ui/field.tsx
new file mode 100644
index 0000000000..4f1426f49e
--- /dev/null
+++ b/packages/admin/src/components/ui/field.tsx
@@ -0,0 +1,236 @@
+import { useMemo } from "react"
+import { cva, type VariantProps } from "class-variance-authority"
+
+import { cn } from "@/lib/utils"
+import { Label } from "@/components/ui/label"
+import { Separator } from "@/components/ui/separator"
+
+function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
+ return (
+ <fieldset
+ data-slot="field-set"
+ className={cn(
+ "flex flex-col gap-4 has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function FieldLegend({
+ className,
+ variant = "legend",
+ ...props
+}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
+ return (
+ <legend
+ data-slot="field-legend"
+ data-variant={variant}
+ className={cn(
+ "mb-1.5 font-medium data-[variant=label]:text-sm data-[variant=legend]:text-base",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="field-group"
+ className={cn(
+ "group/field-group @container/field-group flex w-full flex-col gap-5 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+const fieldVariants = cva(
+ "group/field flex w-full gap-2 data-[invalid=true]:text-destructive",
+ {
+ variants: {
+ orientation: {
+ vertical: "flex-col *:w-full [&>.sr-only]:w-auto",
+ horizontal:
+ "flex-row items-center has-[>[data-slot=field-content]]:items-start *:data-[slot=field-label]:flex-auto has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
+ responsive:
+ "flex-col *:w-full @md/field-group:flex-row @md/field-group:items-center @md/field-group:*:w-auto @md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:*:data-[slot=field-label]:flex-auto [&>.sr-only]:w-auto @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
+ },
+ },
+ defaultVariants: {
+ orientation: "vertical",
+ },
+ }
+)
+
+function Field({
+ className,
+ orientation = "vertical",
+ ...props
+}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
+ return (
+ <div
+ role="group"
+ data-slot="field"
+ data-orientation={orientation}
+ className={cn(fieldVariants({ orientation }), className)}
+ {...props}
+ />
+ )
+}
+
+function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="field-content"
+ className={cn(
+ "group/field-content flex flex-1 flex-col gap-0.5 leading-snug",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function FieldLabel({
+ className,
+ ...props
+}: React.ComponentProps<typeof Label>) {
+ return (
+ <Label
+ data-slot="field-label"
+ className={cn(
+ "group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50 has-data-checked:border-primary/30 has-data-checked:bg-primary/5 has-[>[data-slot=field]]:rounded-lg has-[>[data-slot=field]]:border *:data-[slot=field]:p-2.5 dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10",
+ "has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="field-label"
+ className={cn(
+ "flex w-fit items-center gap-2 text-sm leading-snug font-medium group-data-[disabled=true]/field:opacity-50",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
+ return (
+ <p
+ data-slot="field-description"
+ className={cn(
+ "text-left text-sm leading-normal font-normal text-muted-foreground group-has-data-horizontal/field:text-balance [[data-variant=legend]+&]:-mt-1.5",
+ "last:mt-0 nth-last-2:-mt-1",
+ "[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function FieldSeparator({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div"> & {
+ children?: React.ReactNode
+}) {
+ return (
+ <div
+ data-slot="field-separator"
+ data-content={!!children}
+ className={cn(
+ "relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
+ className
+ )}
+ {...props}
+ >
+ <Separator className="absolute inset-0 top-1/2" />
+ {children && (
+ <span
+ className="relative mx-auto block w-fit bg-background px-2 text-muted-foreground"
+ data-slot="field-separator-content"
+ >
+ {children}
+ </span>
+ )}
+ </div>
+ )
+}
+
+function FieldError({
+ className,
+ children,
+ errors,
+ ...props
+}: React.ComponentProps<"div"> & {
+ errors?: Array<{ message?: string } | undefined>
+}) {
+ const content = useMemo(() => {
+ if (children) {
+ return children
+ }
+
+ if (!errors?.length) {
+ return null
+ }
+
+ const uniqueErrors = [
+ ...new Map(errors.map((error) => [error?.message, error])).values(),
+ ]
+
+ if (uniqueErrors?.length == 1) {
+ return uniqueErrors[0]?.message
+ }
+
+ return (
+ <ul className="ml-4 flex list-disc flex-col gap-1">
+ {uniqueErrors.map(
+ (error, index) =>
+ error?.message && <li key={index}>{error.message}</li>
+ )}
+ </ul>
+ )
+ }, [children, errors])
+
+ if (!content) {
+ return null
+ }
+
+ return (
+ <div
+ role="alert"
+ data-slot="field-error"
+ className={cn("text-sm font-normal text-destructive", className)}
+ {...props}
+ >
+ {content}
+ </div>
+ )
+}
+
+export {
+ Field,
+ FieldLabel,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLegend,
+ FieldSeparator,
+ FieldSet,
+ FieldContent,
+ FieldTitle,
+}
diff --git a/packages/admin/src/components/ui/input-group.tsx b/packages/admin/src/components/ui/input-group.tsx
new file mode 100644
index 0000000000..0475d27b7c
--- /dev/null
+++ b/packages/admin/src/components/ui/input-group.tsx
@@ -0,0 +1,154 @@
+import * as React from "react"
+import { cva, type VariantProps } from "class-variance-authority"
+
+import { cn } from "@/lib/utils"
+import { Button } from "@/components/ui/button"
+import { Input } from "@/components/ui/input"
+import { Textarea } from "@/components/ui/textarea"
+
+function InputGroup({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="input-group"
+ role="group"
+ className={cn(
+ "group/input-group relative flex h-8 w-full min-w-0 items-center rounded-lg border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+const inputGroupAddonVariants = cva(
+ "flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-4",
+ {
+ variants: {
+ align: {
+ "inline-start":
+ "order-first pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem]",
+ "inline-end":
+ "order-last pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem]",
+ "block-start":
+ "order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-2 [.border-b]:pb-2",
+ "block-end":
+ "order-last w-full justify-start px-2.5 pb-2 group-has-[>input]/input-group:pb-2 [.border-t]:pt-2",
+ },
+ },
+ defaultVariants: {
+ align: "inline-start",
+ },
+ }
+)
+
+function InputGroupAddon({
+ className,
+ align = "inline-start",
+ ...props
+}: React.ComponentProps<"div"> & VariantProps<typeof inputGroupAddonVariants>) {
+ return (
+ <div
+ role="group"
+ data-slot="input-group-addon"
+ data-align={align}
+ className={cn(inputGroupAddonVariants({ align }), className)}
+ onClick={(e) => {
+ if ((e.target as HTMLElement).closest("button")) {
+ return
+ }
+ e.currentTarget.parentElement?.querySelector("input")?.focus()
+ }}
+ {...props}
+ />
+ )
+}
+
+const inputGroupButtonVariants = cva(
+ "flex items-center gap-2 text-sm shadow-none",
+ {
+ variants: {
+ size: {
+ xs: "h-6 gap-1 rounded-[calc(var(--radius)-3px)] px-1.5 [&>svg:not([class*='size-'])]:size-3.5",
+ sm: "",
+ "icon-xs":
+ "size-6 rounded-[calc(var(--radius)-3px)] p-0 has-[>svg]:p-0",
+ "icon-sm": "size-8 p-0 has-[>svg]:p-0",
+ },
+ },
+ defaultVariants: {
+ size: "xs",
+ },
+ }
+)
+
+function InputGroupButton({
+ className,
+ type = "button",
+ variant = "ghost",
+ size = "xs",
+ ...props
+}: Omit<React.ComponentProps<typeof Button>, "size"> &
+ VariantProps<typeof inputGroupButtonVariants>) {
+ return (
+ <Button
+ type={type}
+ data-size={size}
+ variant={variant}
+ className={cn(inputGroupButtonVariants({ size }), className)}
+ {...props}
+ />
+ )
+}
+
+function InputGroupText({ className, ...props }: React.ComponentProps<"span">) {
+ return (
+ <span
+ className={cn(
+ "flex items-center gap-2 text-sm text-muted-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function InputGroupInput({
+ className,
+ ...props
+}: React.ComponentProps<"input">) {
+ return (
+ <Input
+ data-slot="input-group-control"
+ className={cn(
+ "flex-1 rounded-none border-0 bg-transparent shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function InputGroupTextarea({
+ className,
+ ...props
+}: React.ComponentProps<"textarea">) {
+ return (
+ <Textarea
+ data-slot="input-group-control"
+ className={cn(
+ "flex-1 resize-none rounded-none border-0 bg-transparent py-2 shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+export {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupButton,
+ InputGroupText,
+ InputGroupInput,
+ InputGroupTextarea,
+}
diff --git a/packages/admin/src/components/ui/label.tsx b/packages/admin/src/components/ui/label.tsx
index f406f725e8..f752f82ba6 100644
--- a/packages/admin/src/components/ui/label.tsx
+++ b/packages/admin/src/components/ui/label.tsx
@@ -1,15 +1,18 @@
-import { Label as LabelPrimitive } from 'radix-ui'
-import type * as React from 'react'
+import * as React from "react"
+import { Label as LabelPrimitive } from "radix-ui"
-import { cn } from '@/lib/utils'
+import { cn } from "@/lib/utils"
-function Label({ className, ...props }: React.ComponentProps<typeof LabelPrimitive.Root>) {
+function Label({
+ className,
+ ...props
+}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
- 'flex items-center gap-2 text-sm font-medium leading-none cursor-pointer mb-2 select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50',
- className,
+ "flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
+ className
)}
{...props}
/>
diff --git a/packages/admin/src/components/ui/pagination.tsx b/packages/admin/src/components/ui/pagination.tsx
index adbd681872..9b4df77583 100644
--- a/packages/admin/src/components/ui/pagination.tsx
+++ b/packages/admin/src/components/ui/pagination.tsx
@@ -1,5 +1,17 @@
-import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react'
+import {
+ ChevronLeftIcon,
+ ChevronRightIcon,
+ ChevronsLeftIcon,
+ ChevronsRightIcon,
+} from 'lucide-react'
import { Button } from '@/components/ui/button'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select'
interface PaginationMeta {
page: number
@@ -15,69 +27,94 @@ interface PaginationMeta {
interface PaginationProps {
meta: PaginationMeta
onPageChange: (page: number) => void
+ onPageSizeChange?: (size: number) => void
+ pageSizeOptions?: number[]
}
-export function Pagination({ meta, onPageChange }: PaginationProps) {
- if (meta.pages <= 1) return null
+export function Pagination({
+ meta,
+ onPageChange,
+ onPageSizeChange,
+ pageSizeOptions = [10, 20, 25, 30, 50],
+}: PaginationProps) {
+ if (meta.pages <= 1 && !onPageSizeChange) return null
return (
- <div className="flex items-center justify-between border-t border-gray-200 bg-white px-4 py-3 rounded-b-2xl">
+ <div className="flex items-center justify-between border-t border-gray-200 px-4 py-3">
<div className="text-sm text-muted-foreground">
- {meta.from}–{meta.to} of {meta.count}
+ {meta.from}&ndash;{meta.to} of {meta.count}
</div>
- <div className="flex items-center gap-1">
- <Button
- variant="ghost"
- size="icon-sm"
- disabled={!meta.previous}
- onClick={() => meta.previous && onPageChange(meta.previous)}
- >
- <ChevronLeftIcon className="size-4" />
- </Button>
- {generatePageNumbers(meta.page, meta.pages).map((p, i) =>
- p === '...' ? (
- <span key={`ellipsis-${i}`} className="px-1 text-sm text-muted-foreground">
- ...
- </span>
- ) : (
- <Button
- key={p}
- variant={p === meta.page ? 'default' : 'ghost'}
- size="icon-sm"
- onClick={() => onPageChange(p as number)}
+ <div className="flex items-center gap-6">
+ {onPageSizeChange && (
+ <div className="flex items-center gap-2">
+ <span className="text-sm text-muted-foreground">Rows per page</span>
+ <Select
+ value={`${meta.limit}`}
+ onValueChange={(value) => onPageSizeChange(Number(value))}
>
- {p}
- </Button>
- ),
+ <SelectTrigger className="h-8 w-[70px]">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent side="top">
+ {pageSizeOptions.map((size) => (
+ <SelectItem key={size} value={`${size}`}>
+ {size}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ )}
+ {meta.pages > 1 && (
+ <>
+ <span className="text-sm text-muted-foreground">
+ Page {meta.page} of {meta.pages}
+ </span>
+ <div className="flex items-center gap-1">
+ <Button
+ variant="outline"
+ size="icon-sm"
+ className="hidden lg:flex"
+ disabled={!meta.previous}
+ onClick={() => onPageChange(1)}
+ >
+ <span className="sr-only">Go to first page</span>
+ <ChevronsLeftIcon />
+ </Button>
+ <Button
+ variant="outline"
+ size="icon-sm"
+ disabled={!meta.previous}
+ onClick={() => meta.previous && onPageChange(meta.previous)}
+ >
+ <span className="sr-only">Go to previous page</span>
+ <ChevronLeftIcon />
+ </Button>
+ <Button
+ variant="outline"
+ size="icon-sm"
+ disabled={!meta.next}
+ onClick={() => meta.next && onPageChange(meta.next)}
+ >
+ <span className="sr-only">Go to next page</span>
+ <ChevronRightIcon />
+ </Button>
+ <Button
+ variant="outline"
+ size="icon-sm"
+ className="hidden lg:flex"
+ disabled={!meta.next}
+ onClick={() => onPageChange(meta.pages)}
+ >
+ <span className="sr-only">Go to last page</span>
+ <ChevronsRightIcon />
+ </Button>
+ </div>
+ </>
)}
- <Button
- variant="ghost"
- size="icon-sm"
- disabled={!meta.next}
- onClick={() => meta.next && onPageChange(meta.next)}
- >
- <ChevronRightIcon className="size-4" />
- </Button>
</div>
</div>
)
}
-function generatePageNumbers(current: number, total: number): (number | '...')[] {
- if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1)
-
- const pages: (number | '...')[] = [1]
-
- if (current > 3) pages.push('...')
-
- const start = Math.max(2, current - 1)
- const end = Math.min(total - 1, current + 1)
- for (let i = start; i <= end; i++) pages.push(i)
-
- if (current < total - 2) pages.push('...')
-
- pages.push(total)
- return pages
-}
-
export type { PaginationMeta }
diff --git a/packages/admin/src/components/ui/popover.tsx b/packages/admin/src/components/ui/popover.tsx
new file mode 100644
index 0000000000..379b57d478
--- /dev/null
+++ b/packages/admin/src/components/ui/popover.tsx
@@ -0,0 +1,40 @@
+import { Popover as PopoverPrimitive } from 'radix-ui'
+import type * as React from 'react'
+import { cn } from '@/lib/utils'
+
+function Popover({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Root>) {
+ return <PopoverPrimitive.Root data-slot="popover" {...props} />
+}
+
+function PopoverTrigger({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
+ return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
+}
+
+function PopoverContent({
+ className,
+ align = 'center',
+ sideOffset = 4,
+ ...props
+}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
+ return (
+ <PopoverPrimitive.Portal>
+ <PopoverPrimitive.Content
+ data-slot="popover-content"
+ align={align}
+ sideOffset={sideOffset}
+ className={cn(
+ 'z-50 w-auto rounded-lg bg-white p-3 text-foreground shadow-[0px_0px_0px_1px_rgba(179,179,179,0.5),0px_6px_12px_-3px_rgba(179,179,179,0.35),0px_6px_18px_0px_rgba(179,179,179,0.35)]',
+ 'duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
+ className,
+ )}
+ {...props}
+ />
+ </PopoverPrimitive.Portal>
+ )
+}
+
+function PopoverAnchor({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
+ return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
+}
+
+export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }
diff --git a/packages/admin/src/components/ui/rich-text-editor.tsx b/packages/admin/src/components/ui/rich-text-editor.tsx
new file mode 100644
index 0000000000..03b305164f
--- /dev/null
+++ b/packages/admin/src/components/ui/rich-text-editor.tsx
@@ -0,0 +1,197 @@
+import { cn } from '@/lib/utils'
+import Link from '@tiptap/extension-link'
+import Placeholder from '@tiptap/extension-placeholder'
+import { EditorContent, useEditor } from '@tiptap/react'
+import StarterKit from '@tiptap/starter-kit'
+import {
+ BoldIcon,
+ ItalicIcon,
+ LinkIcon,
+ ListIcon,
+ ListOrderedIcon,
+ QuoteIcon,
+ RedoIcon,
+ StrikethroughIcon,
+ UndoIcon,
+} from 'lucide-react'
+import { useCallback, useEffect } from 'react'
+
+interface RichTextEditorProps {
+ value?: string
+ onChange?: (html: string) => void
+ placeholder?: string
+ className?: string
+ disabled?: boolean
+}
+
+export function RichTextEditor({
+ value = '',
+ onChange,
+ placeholder = 'Write something...',
+ className,
+ disabled = false,
+}: RichTextEditorProps) {
+ const editor = useEditor({
+ extensions: [
+ StarterKit.configure({ link: false }),
+ Placeholder.configure({ placeholder }),
+ Link.configure({ openOnClick: false }),
+ ],
+ content: value,
+ editable: !disabled,
+ onUpdate: ({ editor }) => {
+ onChange?.(editor.getHTML())
+ },
+ })
+
+ // Sync external value changes (e.g. form reset)
+ useEffect(() => {
+ if (!editor) return
+ if (editor.getHTML() !== value) {
+ editor.commands.setContent(value, { emitUpdate: false })
+ }
+ }, [editor, value])
+
+ useEffect(() => {
+ editor?.setEditable(!disabled)
+ }, [editor, disabled])
+
+ const setLink = useCallback(() => {
+ if (!editor) return
+ const previous = editor.getAttributes('link').href
+ const url = window.prompt('URL', previous)
+ if (url === null) return
+ if (url === '') {
+ editor.chain().focus().extendMarkRange('link').unsetLink().run()
+ } else {
+ editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run()
+ }
+ }, [editor])
+
+ if (!editor) return null
+
+ return (
+ <div
+ className={cn(
+ 'rounded-lg border border-gray-200 bg-white shadow-xs transition-all duration-100 ease-in-out focus-within:ring-2 focus-within:ring-blue-500 focus-within:ring-offset-2',
+ disabled && 'pointer-events-none bg-gray-50 border-gray-100',
+ className,
+ )}
+ >
+ {/* Toolbar */}
+ <div className="flex items-center gap-0.5 border-b border-gray-200 px-2 py-1.5">
+ <ToolbarButton
+ active={editor.isActive('bold')}
+ onClick={() => editor.chain().focus().toggleBold().run()}
+ title="Bold"
+ >
+ <BoldIcon className="size-4" />
+ </ToolbarButton>
+ <ToolbarButton
+ active={editor.isActive('italic')}
+ onClick={() => editor.chain().focus().toggleItalic().run()}
+ title="Italic"
+ >
+ <ItalicIcon className="size-4" />
+ </ToolbarButton>
+ <ToolbarButton
+ active={editor.isActive('strike')}
+ onClick={() => editor.chain().focus().toggleStrike().run()}
+ title="Strikethrough"
+ >
+ <StrikethroughIcon className="size-4" />
+ </ToolbarButton>
+
+ <ToolbarSeparator />
+
+ <ToolbarButton
+ active={editor.isActive('bulletList')}
+ onClick={() => editor.chain().focus().toggleBulletList().run()}
+ title="Bullet list"
+ >
+ <ListIcon className="size-4" />
+ </ToolbarButton>
+ <ToolbarButton
+ active={editor.isActive('orderedList')}
+ onClick={() => editor.chain().focus().toggleOrderedList().run()}
+ title="Ordered list"
+ >
+ <ListOrderedIcon className="size-4" />
+ </ToolbarButton>
+ <ToolbarButton
+ active={editor.isActive('blockquote')}
+ onClick={() => editor.chain().focus().toggleBlockquote().run()}
+ title="Blockquote"
+ >
+ <QuoteIcon className="size-4" />
+ </ToolbarButton>
+
+ <ToolbarSeparator />
+
+ <ToolbarButton
+ active={editor.isActive('link')}
+ onClick={setLink}
+ title="Link"
+ >
+ <LinkIcon className="size-4" />
+ </ToolbarButton>
+
+ <div className="ml-auto flex items-center gap-0.5">
+ <ToolbarButton
+ onClick={() => editor.chain().focus().undo().run()}
+ disabled={!editor.can().undo()}
+ title="Undo"
+ >
+ <UndoIcon className="size-4" />
+ </ToolbarButton>
+ <ToolbarButton
+ onClick={() => editor.chain().focus().redo().run()}
+ disabled={!editor.can().redo()}
+ title="Redo"
+ >
+ <RedoIcon className="size-4" />
+ </ToolbarButton>
+ </div>
+ </div>
+
+ {/* Editor */}
+ <EditorContent
+ editor={editor}
+ className="prose prose-sm max-w-none px-3 py-2 min-h-32 [&_.tiptap]:outline-none [&_.tiptap.is-editor-empty:first-child::before]:text-gray-500 [&_.tiptap.is-editor-empty:first-child::before]:content-[attr(data-placeholder)] [&_.tiptap.is-editor-empty:first-child::before]:float-left [&_.tiptap.is-editor-empty:first-child::before]:h-0 [&_.tiptap.is-editor-empty:first-child::before]:pointer-events-none"
+ />
+ </div>
+ )
+}
+
+function ToolbarButton({
+ active,
+ disabled,
+ onClick,
+ children,
+ title,
+}: {
+ active?: boolean
+ disabled?: boolean
+ onClick: () => void
+ children: React.ReactNode
+ title: string
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ disabled={disabled}
+ title={title}
+ className={cn(
+ 'inline-flex items-center justify-center rounded-md p-1.5 text-gray-600 hover:bg-gray-100 hover:text-gray-950 transition-colors disabled:opacity-40 disabled:pointer-events-none',
+ active && 'bg-gray-100 text-gray-950',
+ )}
+ >
+ {children}
+ </button>
+ )
+}
+
+function ToolbarSeparator() {
+ return <div className="mx-1 h-5 w-px bg-gray-200" />
+}
diff --git a/packages/admin/src/components/ui/separator.tsx b/packages/admin/src/components/ui/separator.tsx
index 0ff166af5d..d4570908d4 100644
--- a/packages/admin/src/components/ui/separator.tsx
+++ b/packages/admin/src/components/ui/separator.tsx
@@ -1,11 +1,13 @@
-import { Separator as SeparatorPrimitive } from 'radix-ui'
-import type * as React from 'react'
+"use client"
-import { cn } from '@/lib/utils'
+import * as React from "react"
+import { Separator as SeparatorPrimitive } from "radix-ui"
+
+import { cn } from "@/lib/utils"
function Separator({
className,
- orientation = 'horizontal',
+ orientation = "horizontal",
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
@@ -15,8 +17,8 @@ function Separator({
decorative={decorative}
orientation={orientation}
className={cn(
- 'shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch',
- className,
+ "shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",
+ className
)}
{...props}
/>
diff --git a/packages/admin/src/components/ui/sidebar.tsx b/packages/admin/src/components/ui/sidebar.tsx
index 39e1de11de..b9178b709a 100644
--- a/packages/admin/src/components/ui/sidebar.tsx
+++ b/packages/admin/src/components/ui/sidebar.tsx
@@ -672,7 +672,7 @@ function SidebarMenuSubButton({
data-size={size}
data-active={isActive}
className={cn(
- "relative flex h-7 min-w-0 items-center gap-2 overflow-hidden rounded-xl p-1 text-gray-800 ring-sidebar-ring outline-hidden group-data-[collapsible=icon]:hidden hover:bg-gray-50 hover:text-zinc-950 focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[size=md]:text-base data-[size=sm]:text-xs data-active:font-semibold data-active:text-zinc-950 data-active:bg-transparent data-active:shadow-none data-active:before:absolute data-active:before:-left-4 data-active:before:top-[10%] data-active:before:h-[80%] data-active:before:w-[3px] data-active:before:rounded-sm data-active:before:bg-zinc-950 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
+ "relative flex h-7 min-w-0 items-center gap-2 overflow-hidden rounded-xl p-1 text-gray-800 ring-sidebar-ring outline-hidden group-data-[collapsible=icon]:hidden hover:bg-gray-50 hover:text-zinc-950 focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[size=md]:text-base data-[size=sm]:text-xs data-active:font-semibold data-active:text-zinc-950 data-active:bg-transparent data-active:shadow-none data-active:before:absolute data-active:before:-left-4 data-active:before:top-[10%] data-active:before:h-[80%] data-active:before:w-[3px] data-active:before:rounded-sm data-active:before:bg-zinc-950 data-active:hover:bg-white [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
className,
)}
{...props}
diff --git a/packages/admin/src/components/ui/switch.tsx b/packages/admin/src/components/ui/switch.tsx
new file mode 100644
index 0000000000..51d2c17bbb
--- /dev/null
+++ b/packages/admin/src/components/ui/switch.tsx
@@ -0,0 +1,26 @@
+import { Switch as SwitchPrimitive } from 'radix-ui'
+import { cn } from '@/lib/utils'
+
+function Switch({
+ className,
+ ...props
+}: React.ComponentProps<typeof SwitchPrimitive.Root>) {
+ return (
+ <SwitchPrimitive.Root
+ data-slot="switch"
+ className={cn(
+ 'peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-blue-600 data-[state=unchecked]:bg-gray-200',
+ className,
+ )}
+ {...props}
+ >
+ <SwitchPrimitive.Thumb
+ className={cn(
+ 'pointer-events-none block h-4 w-4 rounded-full bg-white shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0',
+ )}
+ />
+ </SwitchPrimitive.Root>
+ )
+}
+
+export { Switch }
diff --git a/packages/admin/src/components/ui/textarea.tsx b/packages/admin/src/components/ui/textarea.tsx
new file mode 100644
index 0000000000..04d27f7d17
--- /dev/null
+++ b/packages/admin/src/components/ui/textarea.tsx
@@ -0,0 +1,18 @@
+import * as React from "react"
+
+import { cn } from "@/lib/utils"
+
+function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
+ return (
+ <textarea
+ data-slot="textarea"
+ className={cn(
+ "flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+export { Textarea }
diff --git a/packages/admin/src/hooks/use-direct-upload.ts b/packages/admin/src/hooks/use-direct-upload.ts
new file mode 100644
index 0000000000..bacba18ec4
--- /dev/null
+++ b/packages/admin/src/hooks/use-direct-upload.ts
@@ -0,0 +1,86 @@
+import { useMutation } from '@tanstack/react-query'
+import SparkMD5 from 'spark-md5'
+import { spreeClient } from '@/client'
+import { useAuth } from '@/hooks/use-auth'
+
+function computeMD5Checksum(file: File): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const chunkSize = 2097152 // 2MB chunks
+ const spark = new SparkMD5.ArrayBuffer()
+ const reader = new FileReader()
+ let currentChunk = 0
+ const chunks = Math.ceil(file.size / chunkSize)
+
+ reader.onload = (e) => {
+ spark.append(e.target!.result as ArrayBuffer)
+ currentChunk++
+
+ if (currentChunk < chunks) {
+ loadNext()
+ } else {
+ // Active Storage expects base64-encoded raw MD5 digest
+ resolve(btoa(spark.end(true)))
+ }
+ }
+
+ reader.onerror = () => reject(reader.error)
+
+ function loadNext() {
+ const start = currentChunk * chunkSize
+ const end = Math.min(start + chunkSize, file.size)
+ reader.readAsArrayBuffer(file.slice(start, end))
+ }
+
+ loadNext()
+ })
+}
+
+interface UploadResult {
+ signedId: string
+ previewUrl: string
+}
+
+export function useDirectUpload() {
+ const { token } = useAuth()
+
+ return useMutation({
+ mutationFn: async (file: File): Promise<UploadResult> => {
+ const checksum = await computeMD5Checksum(file)
+
+ // Step 1: Get presigned upload URL
+ let response: { direct_upload: { url: string; headers: Record<string, string> }; signed_id: string }
+ try {
+ response = await spreeClient.admin.directUploads.create(
+ {
+ blob: {
+ filename: file.name,
+ byte_size: file.size,
+ checksum,
+ content_type: file.type || 'application/octet-stream',
+ },
+ },
+ { token: token! },
+ )
+ } catch (err) {
+ throw new Error(`Presign failed: ${err instanceof Error ? err.message : err}`)
+ }
+
+ // Step 2: Upload file directly to storage
+ const uploadResponse = await fetch(response.direct_upload.url, {
+ method: 'PUT',
+ headers: response.direct_upload.headers,
+ body: file,
+ })
+
+ if (!uploadResponse.ok) {
+ const text = await uploadResponse.text().catch(() => '')
+ throw new Error(`Storage upload failed (${uploadResponse.status}): ${text}`)
+ }
+
+ return {
+ signedId: response.signed_id,
+ previewUrl: URL.createObjectURL(file),
+ }
+ },
+ })
+}
diff --git a/packages/admin/src/hooks/use-product-assets.ts b/packages/admin/src/hooks/use-product-assets.ts
new file mode 100644
index 0000000000..d95cb82c2d
--- /dev/null
+++ b/packages/admin/src/hooks/use-product-assets.ts
@@ -0,0 +1,55 @@
+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
+import { spreeClient } from '@/client'
+import { useAuth } from '@/hooks/use-auth'
+
+export function useProductAssets(productId: string) {
+ const { token } = useAuth()
+
+ return useQuery({
+ queryKey: ['products', productId, 'assets'],
+ queryFn: () =>
+ spreeClient.admin.products.assets.list(productId, {}, { token: token! }),
+ enabled: !!token && !!productId,
+ })
+}
+
+export function useCreateProductAsset(productId: string) {
+ const { token } = useAuth()
+ const queryClient = useQueryClient()
+
+ return useMutation({
+ mutationFn: (params: { signed_id: string; alt?: string; position?: number }) =>
+ spreeClient.admin.products.assets.create(productId, params, { token: token! }),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['products', productId, 'assets'] })
+ queryClient.invalidateQueries({ queryKey: ['products', productId] })
+ },
+ })
+}
+
+export function useUpdateProductAsset(productId: string) {
+ const { token } = useAuth()
+ const queryClient = useQueryClient()
+
+ return useMutation({
+ mutationFn: ({ id, ...params }: { id: string; alt?: string; position?: number }) =>
+ spreeClient.admin.products.assets.update(productId, id, params, { token: token! }),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['products', productId, 'assets'] })
+ },
+ })
+}
+
+export function useDeleteProductAsset(productId: string) {
+ const { token } = useAuth()
+ const queryClient = useQueryClient()
+
+ return useMutation({
+ mutationFn: (id: string) =>
+ spreeClient.admin.products.assets.delete(productId, id, { token: token! }),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['products', productId, 'assets'] })
+ queryClient.invalidateQueries({ queryKey: ['products', productId] })
+ },
+ })
+}
diff --git a/packages/admin/src/hooks/use-product.ts b/packages/admin/src/hooks/use-product.ts
new file mode 100644
index 0000000000..918677b8e4
--- /dev/null
+++ b/packages/admin/src/hooks/use-product.ts
@@ -0,0 +1,53 @@
+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
+import { spreeClient } from '@/client'
+import { useAuth } from '@/hooks/use-auth'
+
+export function useProduct(id: string) {
+ const { token } = useAuth()
+
+ return useQuery({
+ queryKey: ['products', id],
+ queryFn: () =>
+ spreeClient.admin.products.get(
+ id,
+ {
+ expand: [
+ 'variants',
+ 'images',
+ 'option_types',
+ 'taxons',
+ 'shipping_category',
+ 'tax_category',
+ ],
+ },
+ { token: token! },
+ ),
+ enabled: !!token && !!id,
+ })
+}
+
+export function useUpdateProduct() {
+ const { token } = useAuth()
+ const queryClient = useQueryClient()
+
+ return useMutation({
+ mutationFn: ({ id, ...params }: { id: string } & Record<string, unknown>) =>
+ spreeClient.admin.products.update(id, params, { token: token! }),
+ onSuccess: (_data, variables) => {
+ queryClient.invalidateQueries({ queryKey: ['products', variables.id] })
+ queryClient.invalidateQueries({ queryKey: ['products'] })
+ },
+ })
+}
+
+export function useDeleteProduct() {
+ const { token } = useAuth()
+ const queryClient = useQueryClient()
+
+ return useMutation({
+ mutationFn: (id: string) => spreeClient.admin.products.delete(id, { token: token! }),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['products'] })
+ },
+ })
+}
diff --git a/packages/admin/src/hooks/use-shipping-categories.ts b/packages/admin/src/hooks/use-shipping-categories.ts
new file mode 100644
index 0000000000..702ed230d6
--- /dev/null
+++ b/packages/admin/src/hooks/use-shipping-categories.ts
@@ -0,0 +1,14 @@
+import { useQuery } from '@tanstack/react-query'
+import { spreeClient } from '@/client'
+import { useAuth } from '@/hooks/use-auth'
+
+export function useShippingCategories() {
+ const { token } = useAuth()
+
+ return useQuery({
+ queryKey: ['shipping-categories'],
+ queryFn: () => spreeClient.admin.shippingCategories.list({}, { token: token! }),
+ enabled: !!token,
+ staleTime: 1000 * 60 * 5,
+ })
+}
diff --git a/packages/admin/src/hooks/use-tax-categories.ts b/packages/admin/src/hooks/use-tax-categories.ts
new file mode 100644
index 0000000000..e834222f1b
--- /dev/null
+++ b/packages/admin/src/hooks/use-tax-categories.ts
@@ -0,0 +1,14 @@
+import { useQuery } from '@tanstack/react-query'
+import { spreeClient } from '@/client'
+import { useAuth } from '@/hooks/use-auth'
+
+export function useTaxCategories() {
+ const { token } = useAuth()
+
+ return useQuery({
+ queryKey: ['tax-categories'],
+ queryFn: () => spreeClient.admin.taxCategories.list({}, { token: token! }),
+ enabled: !!token,
+ staleTime: 1000 * 60 * 5,
+ })
+}
diff --git a/packages/admin/src/hooks/use-taxons.ts b/packages/admin/src/hooks/use-taxons.ts
new file mode 100644
index 0000000000..e7f1f1b8b4
--- /dev/null
+++ b/packages/admin/src/hooks/use-taxons.ts
@@ -0,0 +1,18 @@
+import { useQuery } from '@tanstack/react-query'
+import { spreeClient } from '@/client'
+import { useAuth } from '@/hooks/use-auth'
+
+export function useTaxons() {
+ const { token } = useAuth()
+
+ return useQuery({
+ queryKey: ['taxons'],
+ queryFn: () =>
+ spreeClient.admin.taxons.list(
+ { limit: 100, expand: ['taxonomy'] },
+ { token: token! },
+ ),
+ enabled: !!token,
+ staleTime: 1000 * 60 * 5,
+ })
+}
diff --git a/packages/admin/src/routes/__root.tsx b/packages/admin/src/routes/__root.tsx
index e0c513ea9a..25a58a0b9f 100644
--- a/packages/admin/src/routes/__root.tsx
+++ b/packages/admin/src/routes/__root.tsx
@@ -1,4 +1,5 @@
import { createRootRouteWithContext, Outlet } from '@tanstack/react-router'
+import { Toaster } from 'sonner'
interface RouterContext {
auth: {
@@ -12,5 +13,10 @@ export const Route = createRootRouteWithContext<RouterContext>()({
})
function RootLayout() {
- return <Outlet />
+ return (
+ <>
+ <Outlet />
+ <Toaster position="bottom-right" richColors />
+ </>
+ )
}
diff --git a/packages/admin/src/routes/_authenticated/orders/$orderId.tsx b/packages/admin/src/routes/_authenticated/orders/$orderId.tsx
index 8b07bf1c7f..684c6aa566 100644
--- a/packages/admin/src/routes/_authenticated/orders/$orderId.tsx
+++ b/packages/admin/src/routes/_authenticated/orders/$orderId.tsx
@@ -1,16 +1,1412 @@
-import { createFileRoute } from '@tanstack/react-router'
+import type { AdminAddress, AdminOrder } from '@spree/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 { spreeClient } 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 { useAuth } from '@/hooks/use-auth'
+import { cn } from '@/lib/utils'
export const Route = createFileRoute('/_authenticated/orders/$orderId')({
component: OrderDetailPage,
})
+// ---------------------------------------------------------------------------
+// Data hooks
+// ---------------------------------------------------------------------------
+
+function useOrder(orderId: string) {
+ const { token } = useAuth()
+ return useQuery({
+ queryKey: ['order', orderId],
+ queryFn: () =>
+ spreeClient.admin.orders.get(
+ orderId,
+ {
+ expand: [
+ 'line_items',
+ 'shipments',
+ 'shipments.shipping_method',
+ 'shipments.stock_location',
+ 'payments',
+ 'payments.payment_method',
+ 'bill_address',
+ 'ship_address',
+ 'user',
+ 'adjustments',
+ ],
+ },
+ { token: token! },
+ ),
+ enabled: !!token,
+ })
+}
+
+/** 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: AdminOrder }) {
+ const { orderId } = Route.useParams()
+ const { token } = useAuth()
+ const backUrl = order.completed_at ? '/orders' : '/orders/drafts'
+
+ const cancelMutation = useOrderMutation(orderId, () =>
+ spreeClient.admin.orders.cancel(orderId, {}, { token: token! }),
+ )
+ const resendMutation = useOrderMutation(orderId, () =>
+ spreeClient.admin.orders.resendConfirmation(orderId, {}, { token: token! }),
+ )
+
+ 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_state && <StatusBadge status={order.payment_state} />}
+ {order.shipment_state && <StatusBadge status={order.shipment_state} />}
+
+ {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.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 { token } = useAuth()
+ const mutation = useOrderMutation(orderId, (params: { variant_id: string; quantity: number }) =>
+ spreeClient.admin.orders.lineItems.create(orderId, params, { token: token! }),
+ )
+
+ 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 { token } = useAuth()
+ const mutation = useOrderMutation(orderId, (params: { quantity: number }) =>
+ spreeClient.admin.orders.lineItems.update(orderId, lineItemId, params, { token: token! }),
+ )
+
+ 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: AdminOrder }) {
+ const { orderId } = Route.useParams()
+ const { token } = useAuth()
+ const items = order.line_items ?? []
+ const [addOpen, setAddOpen] = useState(false)
+ const [editItem, setEditItem] = useState<{ id: string; quantity: number } | null>(null)
+
+ const deleteMutation = useOrderMutation(orderId, (lineItemId: string) =>
+ spreeClient.admin.orders.lineItems.delete(orderId, lineItemId, { token: token! }),
+ )
+
+ 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.promo_total) !== 0 ? item.display_promo_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 { token } = useAuth()
+ const mutation = useOrderMutation(orderId, (params: { tracking: string }) =>
+ spreeClient.admin.orders.shipments.update(orderId, shipmentId, params, { token: token! }),
+ )
+
+ 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: AdminOrder }) {
+ const { orderId } = Route.useParams()
+ const { token } = useAuth()
+ const shipments = order.shipments ?? []
+ const [editTracking, setEditTracking] = useState<{
+ id: string
+ tracking: string | null
+ } | null>(null)
+
+ const shipMutation = useOrderMutation(orderId, (shipmentId: string) =>
+ spreeClient.admin.orders.shipments.ship(orderId, shipmentId, {}, { token: token! }),
+ )
+ const cancelShipmentMutation = useOrderMutation(orderId, (shipmentId: string) =>
+ spreeClient.admin.orders.shipments.cancel(orderId, shipmentId, {}, { token: token! }),
+ )
+
+ if (shipments.length === 0) return null
+
+ return (
+ <>
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ <TruckIcon className="size-4" />
+ Shipments
+ </CardTitle>
+ <CardAction className="flex items-center gap-2">
+ <Badge variant="info">{shipments.length}</Badge>
+ {order.shipment_state && <StatusBadge status={order.shipment_state} />}
+ </CardAction>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ {shipments.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.state} />
+ <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.state === 'ready' && (
+ <DropdownMenuItem
+ onClick={() => {
+ if (window.confirm('Ship this shipment?')) {
+ shipMutation.mutate(shipment.id)
+ }
+ }}
+ >
+ <TruckIcon className="size-4" />
+ Ship
+ </DropdownMenuItem>
+ )}
+ {['pending', 'ready'].includes(shipment.state) && (
+ <>
+ <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.shipping_method && (
+ <div className="flex items-center justify-between text-sm">
+ <span className="text-muted-foreground">{shipment.shipping_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.shipped_at && (
+ <span className="text-xs text-muted-foreground">
+ Shipped {timeAgo(shipment.shipped_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: AdminOrder }) {
+ const { orderId } = Route.useParams()
+ const { token } = useAuth()
+ const payments = order.payments ?? []
+
+ const captureMutation = useOrderMutation(orderId, (paymentId: string) =>
+ spreeClient.admin.orders.payments.capture(orderId, paymentId, {}, { token: token! }),
+ )
+ const voidMutation = useOrderMutation(orderId, (paymentId: string) =>
+ spreeClient.admin.orders.payments.void(orderId, paymentId, {}, { token: token! }),
+ )
+
+ 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_state && <StatusBadge status={order.payment_state} />}
+ </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.state} />
+ </td>
+ <td className="p-3 text-right font-medium whitespace-nowrap">
+ {payment.display_amount}
+ </td>
+ <td className="p-3 pr-5">
+ {(payment.state === 'checkout' ||
+ payment.state === 'pending' ||
+ payment.state === 'completed') && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon-xs">
+ <EllipsisVerticalIcon className="size-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {(payment.state === 'checkout' || payment.state === 'pending') && (
+ <DropdownMenuItem
+ onClick={() => {
+ if (window.confirm('Capture this payment?')) {
+ captureMutation.mutate(payment.id)
+ }
+ }}
+ >
+ <CreditCardIcon className="size-4" />
+ Capture
+ </DropdownMenuItem>
+ )}
+ {(payment.state === 'checkout' ||
+ payment.state === 'pending' ||
+ payment.state === '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 { token } = useAuth()
+ const mutation = useOrderMutation(orderId, (params: { label: string; amount: number }) =>
+ spreeClient.admin.orders.adjustments.create(orderId, params, { token: token! }),
+ )
+
+ 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: AdminOrder }) {
+ const { orderId } = Route.useParams()
+ const { token } = useAuth()
+ 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) =>
+ spreeClient.admin.orders.adjustments.delete(orderId, adjustmentId, { token: token! }),
+ )
+
+ 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: AdminOrder }) {
+ 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.ship_total) > 0 && (
+ <SummaryRow label="Shipping" value={order.display_ship_total} />
+ )}
+
+ {Number.parseFloat(order.promo_total) !== 0 && (
+ <SummaryRow label="Promotions" value={order.display_promo_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: AdminAddress | 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.zipcode].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: 'ship_address' | 'bill_address'
+ address: AdminAddress | null | undefined
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { token } = useAuth()
+ const mutation = useOrderMutation(orderId, (params: Record<string, unknown>) =>
+ spreeClient.admin.orders.update(orderId, { [type]: params } as any, { token: token! }),
+ )
+
+ function handleSubmit(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault()
+ const fd = new FormData(e.currentTarget)
+ mutation.mutate(
+ {
+ firstname: fd.get('firstname') as string,
+ lastname: fd.get('lastname') as string,
+ address1: fd.get('address1') as string,
+ city: fd.get('city') as string,
+ zipcode: fd.get('zipcode') 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 === 'ship_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="firstname"
+ defaultValue={address?.firstname ?? ''}
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor={`${type}-ln`}>Last Name</FieldLabel>
+ <Input id={`${type}-ln`} name="lastname" defaultValue={address?.lastname ?? ''} />
+ </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="zipcode" defaultValue={address?.zipcode ?? ''} />
+ </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: AdminOrder }) {
+ const { orderId } = Route.useParams()
+ const user = order.user
+ const [editAddress, setEditAddress] = useState<'ship_address' | 'bill_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('ship_address')}>
+ <PencilIcon className="size-4" />
+ Edit Shipping Address
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setEditAddress('bill_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.ship_address} />
+ <AddressBlock title="Billing Address" address={order.bill_address} />
+ </CardContent>
+ </Card>
+
+ {editAddress && (
+ <EditAddressDialog
+ orderId={orderId}
+ type={editAddress}
+ address={editAddress === 'ship_address' ? order.ship_address : order.bill_address}
+ open={!!editAddress}
+ onOpenChange={(open) => !open && setEditAddress(null)}
+ />
+ )}
+ </>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Special Instructions
+// ---------------------------------------------------------------------------
+
+function SpecialInstructionsCard({ order }: { order: AdminOrder }) {
+ const { orderId } = Route.useParams()
+ const { token } = useAuth()
+ const [editing, setEditing] = useState(false)
+ const mutation = useOrderMutation(orderId, (params: { special_instructions: string }) =>
+ spreeClient.admin.orders.update(orderId, params, { token: token! }),
+ )
+
+ function handleSubmit(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault()
+ const fd = new FormData(e.currentTarget)
+ mutation.mutate(
+ { special_instructions: fd.get('special_instructions') 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="special_instructions" defaultValue={order.special_instructions ?? ''} />
+ <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.special_instructions ? (
+ <p className="text-sm text-muted-foreground whitespace-pre-wrap">
+ {order.special_instructions}
+ </p>
+ ) : (
+ <p className="text-sm text-muted-foreground">None</p>
+ )}
+ </CardContent>
+ </Card>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Internal Note
+// ---------------------------------------------------------------------------
+
+function InternalNoteCard({ order }: { order: AdminOrder }) {
+ const { orderId } = Route.useParams()
+ const { token } = useAuth()
+ const [editing, setEditing] = useState(false)
+ const mutation = useOrderMutation(orderId, (params: { internal_note: string }) =>
+ spreeClient.admin.orders.update(orderId, params, { token: token! }),
+ )
+
+ 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="space-y-4">
- <h1 className="text-2xl font-medium">Order {orderId}</h1>
- <p className="text-muted-foreground">Order detail page will be implemented here.</p>
+ <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/products/$productId.tsx b/packages/admin/src/routes/_authenticated/products/$productId.tsx
index abcf53d9f6..5f9fa5c2b4 100644
--- a/packages/admin/src/routes/_authenticated/products/$productId.tsx
+++ b/packages/admin/src/routes/_authenticated/products/$productId.tsx
@@ -1,16 +1,1055 @@
-import { createFileRoute } from '@tanstack/react-router'
+import type { AdminImage, AdminProduct } from '@spree/sdk'
+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 { useShippingCategories } from '@/hooks/use-shipping-categories'
+import { useTaxCategories } from '@/hooks/use-tax-categories'
+import { useTaxons } from '@/hooks/use-taxons'
+import { productFormSchema, type ProductFormValues } from '@/schemas/product'
export const Route = createFileRoute('/_authenticated/products/$productId')({
component: ProductDetailPage,
})
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function productToFormValues(product: AdminProduct): 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,
+ taxon_ids: product.taxons?.map((t) => t.id) ?? [],
+ tags: product.tags ?? [],
+ 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,
+ shipping_category_id: product.shipping_category_id ?? null,
+ 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: AdminProduct }) {
+ 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 AdminImage}
+ 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: AdminImage
+ 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: AdminProduct }) {
+ 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: taxonsResponse } = useTaxons()
+ const taxons = taxonsResponse?.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="taxon_ids"
+ control={form.control}
+ render={({ field }) => (
+ <TaxonCombobox
+ taxons={taxons}
+ 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 TaxonOption {
+ id: string
+ name: string
+}
+
+function TaxonCombobox({
+ taxons,
+ value,
+ onChange,
+}: {
+ taxons: TaxonOption[]
+ 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}>
+ {taxons.find((t) => t.id === id)?.name ?? id}
+ </ComboboxChip>
+ ))
+ }
+ </ComboboxValue>
+ <ComboboxChipsInput placeholder="Search categories..." />
+ </ComboboxChips>
+ <ComboboxContent anchor={anchorRef}>
+ <ComboboxList>
+ {taxons.map((taxon) => (
+ <ComboboxItem key={taxon.id} value={taxon.id}>
+ {taxon.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 &ldquo;{inputValue.trim()}&rdquo;
+ </ComboboxItem>
+ )}
+ <ComboboxEmpty>Type and press Enter to create a tag</ComboboxEmpty>
+ </ComboboxList>
+ </ComboboxContent>
+ </Combobox>
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Shipping
+// ---------------------------------------------------------------------------
+
+function ShippingCard({ form, hasVariants }: FormCardProps & { hasVariants: boolean }) {
+ const { data: shippingCategoriesResponse } = useShippingCategories()
+ const shippingCategories = shippingCategoriesResponse?.data ?? []
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Shipping</CardTitle>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ <div className="grid gap-2">
+ <Label>Shipping category</Label>
+ <Controller
+ name="shipping_category_id"
+ control={form.control}
+ render={({ field }) => (
+ <Select value={field.value ?? ''} onValueChange={(v) => field.onChange(v || null)}>
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="Select shipping category" />
+ </SelectTrigger>
+ <SelectContent>
+ {shippingCategories.map((cat) => (
+ <SelectItem key={cat.id} value={cat.id}>
+ {cat.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ />
+ </div>
+
+ {!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="space-y-4">
- <h1 className="text-2xl font-medium">Product {productId}</h1>
- <p className="text-muted-foreground">Product detail page will be implemented here.</p>
+ <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/schemas/product.ts b/packages/admin/src/schemas/product.ts
new file mode 100644
index 0000000000..f9bdec98ff
--- /dev/null
+++ b/packages/admin/src/schemas/product.ts
@@ -0,0 +1,46 @@
+import { z } from 'zod/v4'
+
+export const productFormSchema = z.object({
+ // General
+ name: z.string().min(1, 'Name is required'),
+ description: z.string().optional(),
+
+ // Status
+ status: z.enum(['draft', 'active', 'archived']).optional(),
+ make_active_at: z.string().nullable().optional(),
+ available_on: z.string().nullable().optional(),
+ discontinue_on: z.string().nullable().optional(),
+
+ // Categorization
+ taxon_ids: z.array(z.string()).optional(),
+ tags: z.array(z.string()).optional(),
+
+ // Pricing (master variant)
+ price: z.coerce.number().optional(),
+ compare_at_price: z.coerce.number().nullable().optional(),
+ cost_price: z.coerce.number().nullable().optional(),
+
+ // Inventory (master variant)
+ sku: z.string().optional(),
+ barcode: z.string().optional(),
+ track_inventory: z.boolean().optional(),
+
+ // Shipping
+ shipping_category_id: z.string().nullable().optional(),
+ weight: z.coerce.number().nullable().optional(),
+ height: z.coerce.number().nullable().optional(),
+ width: z.coerce.number().nullable().optional(),
+ depth: z.coerce.number().nullable().optional(),
+ weight_unit: z.string().nullable().optional(),
+ dimensions_unit: z.string().nullable().optional(),
+
+ // Tax
+ tax_category_id: z.string().nullable().optional(),
+
+ // SEO
+ meta_title: z.string().optional(),
+ meta_description: z.string().optional(),
+ slug: z.string().optional(),
+})
+
+export type ProductFormValues = z.infer<typeof productFormSchema>
diff --git a/packages/sdk/src/admin-client.ts b/packages/sdk/src/admin-client.ts
index 07b892108a..bf4d0679fd 100644
--- a/packages/sdk/src/admin-client.ts
+++ b/packages/sdk/src/admin-client.ts
@@ -17,6 +17,8 @@ import type {
AdminProduct,
AdminRefund,
AdminShipment,
+ AdminShippingCategory,
+ AdminTaxCategory,
AdminTaxon,
AdminTaxonomy,
AdminVariant,
@@ -108,6 +110,56 @@ export class AdminClient {
this.request('POST', '/direct_uploads', { ...options, body: params }),
} as const;
+ // ============================================
+ // Shipping Categories (hand-written, not auto-generated)
+ // ============================================
+
+ readonly shippingCategories = {
+ list: (
+ params?: ListParams,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<AdminShippingCategory>> =>
+ this.request<PaginatedResponse<AdminShippingCategory>>('GET', '/shipping_categories', {
+ ...options,
+ params: transformListParams({ ...params }),
+ }),
+
+ get: (
+ id: string,
+ params?: ListParams,
+ options?: RequestOptions,
+ ): Promise<AdminShippingCategory> =>
+ this.request<AdminShippingCategory>('GET', `/shipping_categories/${id}`, {
+ ...options,
+ params: transformListParams({ ...params }),
+ }),
+ } as const;
+
+ // ============================================
+ // Tax Categories (hand-written, not auto-generated)
+ // ============================================
+
+ readonly taxCategories = {
+ list: (
+ params?: ListParams,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<AdminTaxCategory>> =>
+ this.request<PaginatedResponse<AdminTaxCategory>>('GET', '/tax_categories', {
+ ...options,
+ params: transformListParams({ ...params }),
+ }),
+
+ get: (
+ id: string,
+ params?: ListParams,
+ options?: RequestOptions,
+ ): Promise<AdminTaxCategory> =>
+ this.request<AdminTaxCategory>('GET', `/tax_categories/${id}`, {
+ ...options,
+ params: transformListParams({ ...params }),
+ }),
+ } as const;
+
// ============================================
// Option Types
// ============================================
diff --git a/packages/sdk/src/zod/generated/AdminOrder.ts b/packages/sdk/src/zod/generated/AdminOrder.ts
index 076ea4a108..3a76113c10 100644
--- a/packages/sdk/src/zod/generated/AdminOrder.ts
+++ b/packages/sdk/src/zod/generated/AdminOrder.ts
@@ -56,11 +56,11 @@ export const AdminOrderSchema: z.ZodObject<any> = z.object({
considered_risky: z.boolean(),
confirmation_delivered: z.boolean(),
store_owner_notification_delivered: z.boolean(),
- internal_note: z.string().nullable(),
payment_total: z.string(),
display_payment_total: z.string(),
canceled_at: z.string().nullable(),
approved_at: z.string().nullable(),
+ internal_note: z.string().nullable(),
metadata: z.record(z.string(), z.unknown()).nullable(),
approver_id: z.string().nullable(),
canceler_id: z.string().nullable(),
diff --git a/skills-lock.json b/skills-lock.json
new file mode 100644
index 0000000000..00ca5b6a78
--- /dev/null
+++ b/skills-lock.json
@@ -0,0 +1,10 @@
+{
+ "version": 1,
+ "skills": {
+ "shadcn": {
+ "source": "shadcn/ui",
+ "sourceType": "github",
+ "computedHash": "91c02eb706f046fb9d6a061efbb96496e4be751b5b14c283cf82baaa50f3a985"
+ }
+ }
+}
diff --git a/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb
index fc0a99a877..8313308e03 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb
@@ -19,9 +19,12 @@ module Spree
# Admin-only attributes
attributes :last_ip_address, :considered_risky,
:confirmation_delivered, :store_owner_notification_delivered,
- :internal_note, :payment_total, :display_payment_total,
- canceled_at: :iso8601, approved_at: :iso8601,
- created_at: :iso8601, updated_at: :iso8601
+ :payment_total, :display_payment_total,
+ canceled_at: :iso8601, approved_at: :iso8601
+
+ attribute :internal_note do |order|
+ order.internal_note&.to_plain_text.presence
+ end
attribute :metadata do |order|
order.metadata.presence