{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"orders-table","type":"registry:block","title":"Orders table","description":"Search, payment and fulfillment filters, export and pages; ship selected orders and the rows update in place.","dependencies":["lucide-react"],"registryDependencies":["https://dashral.com/r/utils.json","https://dashral.com/r/avatar.json","https://dashral.com/r/badge.json","https://dashral.com/r/button.json","https://dashral.com/r/data-table.json","https://dashral.com/r/dropdown-menu.json"],"files":[{"path":"registry/dashral/blocks/orders-table.tsx","type":"registry:file","target":"components/dashral/blocks/orders-table.tsx","content":"\"use client\"\n\nimport { useMemo, useRef, useState } from \"react\"\nimport { CircleCheck, CircleX, Clock, MoreHorizontal, PackageCheck, Plus, RotateCcw, Truck } from \"lucide-react\"\nimport { Avatar } from \"../avatar\"\nimport { Badge } from \"../badge\"\nimport { Button } from \"../button\"\nimport {\n  createDataTableColumnHelper,\n  DataTable,\n  DataTableColumnHeader,\n  dataTableSelectColumn,\n  type DataTableFilter,\n} from \"../data-table\"\nimport { DropdownMenu } from \"../dropdown-menu\"\n\nexport type Payment = \"paid\" | \"pending\" | \"refunded\" | \"failed\"\nexport type Fulfillment = \"unfulfilled\" | \"shipped\" | \"delivered\"\nexport type Order = {\n  id: string\n  date: string\n  customer: string\n  email: string\n  avatar?: string\n  items: number\n  total: number\n  payment: Payment\n  fulfillment: Fulfillment\n}\n\nconst initialOrders: Order[] = [\n  { id: \"#1048\", date: \"2026-10-17\", customer: \"Olivia Martin\", email: \"olivia@example.com\", avatar: \"https://randomuser.me/api/portraits/women/44.jpg\", items: 3, total: 249, payment: \"paid\", fulfillment: \"unfulfilled\" },\n  { id: \"#1047\", date: \"2026-10-17\", customer: \"Jackson Lee\", email: \"jackson@example.com\", avatar: \"https://randomuser.me/api/portraits/men/22.jpg\", items: 1, total: 129, payment: \"pending\", fulfillment: \"unfulfilled\" },\n  { id: \"#1046\", date: \"2026-10-16\", customer: \"Isabella Nguyen\", email: \"isabella@example.com\", avatar: \"https://randomuser.me/api/portraits/women/65.jpg\", items: 2, total: 98, payment: \"paid\", fulfillment: \"shipped\" },\n  { id: \"#1045\", date: \"2026-10-16\", customer: \"William Kim\", email: \"will@example.com\", items: 1, total: 129, payment: \"refunded\", fulfillment: \"delivered\" },\n  { id: \"#1044\", date: \"2026-10-15\", customer: \"Sofia Davis\", email: \"sofia@example.com\", avatar: \"https://randomuser.me/api/portraits/women/68.jpg\", items: 4, total: 412, payment: \"paid\", fulfillment: \"delivered\" },\n  { id: \"#1043\", date: \"2026-10-15\", customer: \"Budi Santoso\", email: \"budi@example.com\", items: 1, total: 249, payment: \"failed\", fulfillment: \"unfulfilled\" },\n  { id: \"#1042\", date: \"2026-10-14\", customer: \"Ayu Lestari\", email: \"ayu@example.com\", avatar: \"https://randomuser.me/api/portraits/women/12.jpg\", items: 2, total: 74, payment: \"paid\", fulfillment: \"shipped\" },\n  { id: \"#1041\", date: \"2026-10-14\", customer: \"Liam Johnson\", email: \"liam@example.com\", avatar: \"https://randomuser.me/api/portraits/men/32.jpg\", items: 5, total: 538, payment: \"paid\", fulfillment: \"delivered\" },\n  { id: \"#1040\", date: \"2026-10-13\", customer: \"Emma Wilson\", email: \"emma@example.com\", items: 1, total: 249, payment: \"pending\", fulfillment: \"unfulfilled\" },\n  { id: \"#1039\", date: \"2026-10-13\", customer: \"Rizky Pratama\", email: \"rizky@example.com\", avatar: \"https://randomuser.me/api/portraits/men/75.jpg\", items: 2, total: 98, payment: \"paid\", fulfillment: \"delivered\" },\n  { id: \"#1038\", date: \"2026-10-12\", customer: \"Noah Brown\", email: \"noah@example.com\", items: 3, total: 187, payment: \"paid\", fulfillment: \"delivered\" },\n  { id: \"#1037\", date: \"2026-10-11\", customer: \"Mia Garcia\", email: \"mia@example.com\", avatar: \"https://randomuser.me/api/portraits/women/90.jpg\", items: 1, total: 49, payment: \"refunded\", fulfillment: \"unfulfilled\" },\n]\n\nconst day = new Intl.DateTimeFormat(\"en-US\", { month: \"short\", day: \"numeric\", timeZone: \"UTC\" })\n\n// Status is always an icon and a word, never color alone.\nconst payments = {\n  paid: { label: \"Paid\", icon: CircleCheck, color: \"success\" },\n  pending: { label: \"Pending\", icon: Clock, color: \"warning\" },\n  refunded: { label: \"Refunded\", icon: RotateCcw, color: \"neutral\" },\n  failed: { label: \"Failed\", icon: CircleX, color: \"destructive\" },\n} as const\nconst fulfillments = {\n  unfulfilled: { label: \"Unfulfilled\", icon: Clock, color: \"warning\" },\n  shipped: { label: \"Shipped\", icon: Truck, color: \"info\" },\n  delivered: { label: \"Delivered\", icon: PackageCheck, color: \"success\" },\n} as const\n\nfunction StatusBadge({ status }: { status: { label: string; icon: React.ComponentType; color: \"success\" | \"warning\" | \"neutral\" | \"destructive\" | \"info\" } }) {\n  const Icon = status.icon\n  return (\n    <Badge variant=\"soft\" color={status.color}>\n      <Icon aria-hidden />\n      {status.label}\n    </Badge>\n  )\n}\n\nconst filters: DataTableFilter[] = [\n  { column: \"payment\", title: \"Payment\", options: Object.entries(payments).map(([value, s]) => ({ value, label: s.label, icon: s.icon })) },\n  { column: \"fulfillment\", title: \"Fulfillment\", options: Object.entries(fulfillments).map(([value, s]) => ({ value, label: s.label, icon: s.icon })) },\n]\n\nconst helper = createDataTableColumnHelper<Order>()\n\n/**\n * A store's orders: search, payment and fulfillment filters, sorting, columns, export, and pages. Select rows to\n * ship or deliver them together; each row's menu does the same for one order, and the table updates in place. Your\n * orders come in as `orders` (a new list replaces what's shown), and every change goes to `onUpdate` first in the\n * table, undone with its message if it throws.\n */\nexport function OrdersTable({\n  title = \"Orders\",\n  orders: given = initialOrders,\n  currency = \"USD\",\n  locale = \"en-US\",\n  onUpdate,\n  onCreate,\n}: {\n  title?: React.ReactNode\n  orders?: Order[]\n  currency?: string\n  locale?: string\n  /** Ships, delivers or refunds orders, by id. */\n  onUpdate?: (ids: string[], change: Partial<Pick<Order, \"fulfillment\" | \"payment\">>) => Promise<void> | void\n  onCreate?: () => void\n}) {\n  const [orders, setOrders] = useState(given)\n  // A new list from you replaces what's shown.\n  const [lastGiven, setLastGiven] = useState(given)\n  if (given !== lastGiven) {\n    setLastGiven(given)\n    setOrders(given)\n  }\n  const [problem, setProblem] = useState<string | null>(null)\n  // The latest handler, for the row menus the columns made once.\n  const onUpdateRef = useRef(onUpdate)\n  onUpdateRef.current = onUpdate\n  const money = useMemo(() => new Intl.NumberFormat(locale, { style: \"currency\", currency }), [locale, currency])\n\n  function update(ids: string[], change: Partial<Pick<Order, \"fulfillment\" | \"payment\">>) {\n    let before: Order[] = []\n    setOrders((all) => {\n      before = all\n      return all.map((order) => (ids.includes(order.id) ? { ...order, ...change } : order))\n    })\n    setProblem(null)\n    void Promise.resolve()\n      .then(() => onUpdateRef.current?.(ids, change))\n      .catch((e) => {\n        setOrders(before)\n        setProblem(e instanceof Error ? e.message : \"That didn't go through. Try again.\")\n      })\n  }\n\n  const columns = useMemo(\n    () =>\n      helper.columns([\n        dataTableSelectColumn<Order>(),\n        helper.accessor(\"id\", {\n          header: ({ column }) => <DataTableColumnHeader column={column} title=\"Order\" />,\n          cell: ({ row }) => (\n            <div>\n              <p className=\"font-medium tabular-nums\">{row.original.id}</p>\n              <p className=\"text-xs text-muted-foreground\">{day.format(new Date(row.original.date))}</p>\n            </div>\n          ),\n          enableHiding: false,\n        }),\n        helper.accessor(\"customer\", {\n          header: ({ column }) => <DataTableColumnHeader column={column} title=\"Customer\" />,\n          cell: ({ row }) => (\n            <div className=\"flex items-center gap-3\">\n              <Avatar src={row.original.avatar} name={row.original.customer} size=\"sm\" />\n              <div className=\"min-w-0\">\n                <p className=\"truncate font-medium\">{row.original.customer}</p>\n                <p className=\"truncate text-xs text-muted-foreground\">{row.original.email}</p>\n              </div>\n            </div>\n          ),\n        }),\n        helper.accessor(\"payment\", {\n          header: \"Payment\",\n          cell: ({ getValue }) => <StatusBadge status={payments[getValue()]} />,\n          filterFn: \"oneOf\",\n        }),\n        helper.accessor(\"fulfillment\", {\n          header: \"Fulfillment\",\n          cell: ({ getValue }) => <StatusBadge status={fulfillments[getValue()]} />,\n          filterFn: \"oneOf\",\n        }),\n        helper.accessor(\"items\", {\n          header: \"Items\",\n          cell: ({ getValue }) => <span className=\"text-muted-foreground tabular-nums\">{getValue()}</span>,\n        }),\n        helper.accessor(\"total\", {\n          header: ({ column }) => (\n            <div className=\"text-end\">\n              <DataTableColumnHeader column={column} title=\"Total\" className=\"-me-3\" />\n            </div>\n          ),\n          cell: ({ getValue }) => <div className=\"text-end font-medium tabular-nums\">{money.format(getValue())}</div>,\n        }),\n        helper.display({\n          id: \"actions\",\n          cell: ({ row }) => {\n            const order = row.original\n            return (\n              <div className=\"text-end\">\n                <DropdownMenu\n                  trigger={\n                    <Button variant=\"ghost\" size=\"icon-sm\" aria-label={`Actions for order ${order.id}`}>\n                      <MoreHorizontal />\n                    </Button>\n                  }\n                  align=\"end\"\n                  items={[\n                    { type: \"label\", label: `Order ${order.id}` },\n                    { label: \"Mark as shipped\", icon: <Truck />, disabled: order.fulfillment !== \"unfulfilled\", onSelect: () => update([order.id], { fulfillment: \"shipped\" }) },\n                    { label: \"Mark as delivered\", icon: <PackageCheck />, disabled: order.fulfillment === \"delivered\", onSelect: () => update([order.id], { fulfillment: \"delivered\" }) },\n                    { type: \"separator\" },\n                    { label: \"Refund\", icon: <RotateCcw />, color: \"destructive\", disabled: order.payment !== \"paid\", onSelect: () => update([order.id], { payment: \"refunded\" }) },\n                  ]}\n                />\n              </div>\n            )\n          },\n        }),\n      ]),\n    [money]\n  )\n\n  const open = orders.filter((order) => order.fulfillment === \"unfulfilled\" && order.payment === \"paid\").length\n\n  return (\n    <section aria-labelledby=\"orders-table-title\" className=\"bg-background p-4 sm:p-6\">\n      <div className=\"rounded-xl border bg-card\">\n        <div className=\"flex flex-wrap items-start justify-between gap-3 border-b p-4 sm:px-6\">\n          <div>\n            <h2 id=\"orders-table-title\" className=\"font-semibold\">\n              {title}\n            </h2>\n            <p className={problem ? \"mt-0.5 text-sm text-destructive-text\" : \"mt-0.5 text-sm text-muted-foreground\"} role={problem ? \"alert\" : undefined}>\n              {problem ?? (open === 0 ? \"Every paid order is on its way.\" : `${open} paid ${open === 1 ? \"order is\" : \"orders are\"} waiting to ship.`)}\n            </p>\n          </div>\n          <Button size=\"sm\" onClick={onCreate}>\n            <Plus aria-hidden /> Create order\n          </Button>\n        </div>\n        <DataTable\n          className=\"p-4 sm:px-6\"\n          columns={columns}\n          data={orders}\n          getRowId={(row) => row.id}\n          searchPlaceholder=\"Search orders…\"\n          filters={filters}\n          pageSizes={[8, 20, 50]}\n          exportable={{ filename: \"orders\", columns: { total: { label: `Total (${currency})` } } }}\n          emptyMessage=\"No orders match. Try another search or clear the filters.\"\n          toolbar={(table) => {\n            const ids = Object.keys(table.state.rowSelection)\n            if (ids.length === 0) return null\n            // Shipping skips what's already on its way; nothing moves backwards.\n            const unshipped = orders.filter((order) => ids.includes(order.id) && order.fulfillment === \"unfulfilled\").map((order) => order.id)\n            const done = (targets: string[], change: Partial<Order>) => {\n              update(targets, change)\n              table.resetRowSelection()\n            }\n            return (\n              <>\n                <Button size=\"sm\" variant=\"outline\" className=\"h-8\" disabled={unshipped.length === 0} onClick={() => done(unshipped, { fulfillment: \"shipped\" })}>\n                  <Truck aria-hidden /> Ship {unshipped.length || \"\"}\n                </Button>\n                <Button size=\"sm\" variant=\"outline\" className=\"h-8\" onClick={() => done(ids, { fulfillment: \"delivered\" })}>\n                  <PackageCheck aria-hidden /> Mark delivered\n                </Button>\n              </>\n            )\n          }}\n        />\n      </div>\n    </section>\n  )\n}\n"}],"cssVars":{"theme":{"color-destructive-foreground":"var(--destructive-foreground)","color-destructive-text":"var(--destructive-text)"},"light":{"destructive-foreground":"oklch(0.985 0 0)","destructive-text":"#bd2800"},"dark":{"destructive-foreground":"oklch(0.2 0 0)","destructive-text":"#ff8a5c"}}}