438 lines
13 KiB
TypeScript
438 lines
13 KiB
TypeScript
import { useState } from "react";
|
|
import { useLocation } from "wouter";
|
|
import { z } from "zod";
|
|
import Button from "@mui/material/Button";
|
|
import Alert from "@mui/material/Alert";
|
|
import {
|
|
adminProduct,
|
|
adminProductSummary,
|
|
productInput,
|
|
variant,
|
|
variantInput,
|
|
group,
|
|
groupInput,
|
|
money,
|
|
type AdminProduct,
|
|
uuid,
|
|
} from "@/lib/commerce";
|
|
import { usePlatform } from "@/lib/platform";
|
|
import { WorkspaceShell } from "@/components/WorkspaceShell";
|
|
import {
|
|
ActionForm,
|
|
Check,
|
|
Field,
|
|
Pager,
|
|
Panel,
|
|
QueryView,
|
|
Table,
|
|
usePrivateQuery,
|
|
readText,
|
|
WorkspaceLink,
|
|
} from "@/components/WorkspaceTools";
|
|
import { RecordSelection } from "@/components/RecordSelection";
|
|
import { ConfirmAction } from "@/components/ConfirmAction";
|
|
function ProductForm({
|
|
item,
|
|
onSave,
|
|
}: {
|
|
item?: AdminProduct;
|
|
onSave: () => Promise<unknown>;
|
|
}) {
|
|
const { request } = usePlatform(),
|
|
[, navigate] = useLocation();
|
|
return (
|
|
<ActionForm
|
|
key={item?.id || "new"}
|
|
label="Save product"
|
|
read={(data) => ({
|
|
name: readText(data, "name"),
|
|
slug: readText(data, "slug"),
|
|
description: readText(data, "description"),
|
|
groupIds: data.getAll("groupIds").map(String),
|
|
})}
|
|
submit={async (value) => {
|
|
const saved = await request(
|
|
item ? `/products/${item.id}` : "/products",
|
|
adminProductSummary,
|
|
{ method: item ? "PUT" : "POST", body: productInput.parse(value) },
|
|
);
|
|
await onSave();
|
|
if (!item) navigate(`/admin/catalog/${saved.id}`);
|
|
}}
|
|
>
|
|
<Field
|
|
name="name"
|
|
label="Product name"
|
|
maxLength={160}
|
|
value={item?.name}
|
|
/>
|
|
<Field
|
|
name="slug"
|
|
label="URL slug"
|
|
maxLength={160}
|
|
value={item?.slug}
|
|
helper="Lowercase words separated by hyphens."
|
|
/>
|
|
<Field
|
|
name="description"
|
|
label="Description"
|
|
required={false}
|
|
maxLength={5000}
|
|
value={item?.description}
|
|
/>
|
|
<RecordSelection
|
|
name="groupIds"
|
|
label="Categories and collections"
|
|
path="/catalog-groups"
|
|
initial={item?.groups.map((g) => g.group.id)}
|
|
/>
|
|
</ActionForm>
|
|
);
|
|
}
|
|
function VariantForm({
|
|
productId,
|
|
item,
|
|
onSave,
|
|
}: {
|
|
productId: string;
|
|
item?: z.infer<typeof variant>;
|
|
onSave: () => Promise<unknown>;
|
|
}) {
|
|
const { request } = usePlatform();
|
|
const [attributes, setAttributes] = useState(
|
|
Object.entries(item?.attributes || {}),
|
|
);
|
|
return (
|
|
<ActionForm
|
|
key={item?.id || "new"}
|
|
label="Save variant"
|
|
read={(data) => {
|
|
const entries = attributes.map((_, i) => [
|
|
readText(data, `key${i}`).trim(),
|
|
readText(data, `value${i}`),
|
|
]);
|
|
if (new Set(entries.map((e) => e[0])).size !== entries.length)
|
|
throw new Error("Attribute names must be unique.");
|
|
return {
|
|
name: readText(data, "name"),
|
|
sku: readText(data, "sku"),
|
|
price: readText(data, "price"),
|
|
currency: readText(data, "currency"),
|
|
active: data.has("active"),
|
|
attributes: Object.fromEntries(entries),
|
|
};
|
|
}}
|
|
submit={async (value) => {
|
|
await request(
|
|
`/products/${productId}/variants${item ? `/${item.id}` : ""}`,
|
|
variant,
|
|
{ method: item ? "PUT" : "POST", body: variantInput.parse(value) },
|
|
);
|
|
await onSave();
|
|
}}
|
|
>
|
|
<Field
|
|
name="name"
|
|
label="Variant name"
|
|
maxLength={160}
|
|
value={item?.name}
|
|
/>
|
|
<Field name="sku" label="SKU" maxLength={64} value={item?.sku} />
|
|
<Field
|
|
name="price"
|
|
label="Price"
|
|
value={item ? money(item.price) : ""}
|
|
helper="Positive decimal with two fractional digits, e.g. 250.00."
|
|
/>
|
|
<Field
|
|
name="currency"
|
|
label="Currency"
|
|
value={item?.currency || "INR"}
|
|
options={["INR", "USD", "EUR", "GBP"].map((value) => ({
|
|
value,
|
|
label: value,
|
|
}))}
|
|
/>
|
|
<Check
|
|
name="active"
|
|
label="Active variant"
|
|
value={item?.active ?? true}
|
|
/>
|
|
{attributes.map(([key, value], i) => (
|
|
<div className="attribute-row" key={i}>
|
|
<Field
|
|
name={`key${i}`}
|
|
label={`Attribute ${i + 1} name`}
|
|
value={key}
|
|
onChange={(next) =>
|
|
setAttributes((rows) =>
|
|
rows.map((row, index) => (index === i ? [next, row[1]] : row)),
|
|
)
|
|
}
|
|
maxLength={32}
|
|
/>
|
|
<Field
|
|
name={`value${i}`}
|
|
label={`Attribute ${i + 1} value`}
|
|
value={value}
|
|
onChange={(next) =>
|
|
setAttributes((rows) =>
|
|
rows.map((row, index) => (index === i ? [row[0], next] : row)),
|
|
)
|
|
}
|
|
maxLength={100}
|
|
/>
|
|
<Button
|
|
onClick={() =>
|
|
setAttributes((rows) => rows.filter((_, index) => index !== i))
|
|
}
|
|
>
|
|
Remove attribute
|
|
</Button>
|
|
</div>
|
|
))}
|
|
<Button
|
|
disabled={attributes.length >= 20}
|
|
onClick={() => setAttributes((rows) => [...rows, ["", ""]])}
|
|
>
|
|
Add attribute
|
|
</Button>
|
|
</ActionForm>
|
|
);
|
|
}
|
|
function Groups() {
|
|
const { request, can } = usePlatform();
|
|
const [offset, setOffset] = useState(0),
|
|
[editing, setEditing] = useState<z.infer<typeof group> | null>(null);
|
|
const query = usePrivateQuery(
|
|
`/catalog-groups?limit=25&offset=${offset}`,
|
|
z.array(group),
|
|
);
|
|
return (
|
|
<Panel title="Categories and collections">
|
|
<QueryView query={query}>
|
|
{(items) => (
|
|
<>
|
|
<Table
|
|
head={["Name", "Kind", "Slug", "Action"]}
|
|
rowKeys={items.map((item) => item.id)}
|
|
rows={items.map((g) => [
|
|
g.name,
|
|
g.kind,
|
|
g.slug,
|
|
can("catalog.manage") ? (
|
|
<Button onClick={() => setEditing(g)}>Edit</Button>
|
|
) : (
|
|
"Read only"
|
|
),
|
|
])}
|
|
/>
|
|
<Pager offset={offset} count={items.length} onPage={setOffset} />
|
|
</>
|
|
)}
|
|
</QueryView>
|
|
{can("catalog.manage") && (
|
|
<>
|
|
<ActionForm
|
|
key={editing?.id || "new"}
|
|
label="Save group"
|
|
read={(data) => ({
|
|
name: readText(data, "name"),
|
|
slug: readText(data, "slug"),
|
|
kind: readText(data, "kind"),
|
|
})}
|
|
submit={async (value) => {
|
|
await request(
|
|
editing ? `/catalog-groups/${editing.id}` : "/catalog-groups",
|
|
group,
|
|
{
|
|
method: editing ? "PUT" : "POST",
|
|
body: groupInput.parse(value),
|
|
},
|
|
);
|
|
setEditing(null);
|
|
await query.refetch();
|
|
}}
|
|
>
|
|
<Field
|
|
name="name"
|
|
label="Group name"
|
|
value={editing?.name}
|
|
maxLength={100}
|
|
/>
|
|
<Field
|
|
name="slug"
|
|
label="Group slug"
|
|
value={editing?.slug}
|
|
maxLength={100}
|
|
/>
|
|
<Field
|
|
name="kind"
|
|
label="Group kind"
|
|
value={editing?.kind || "CATEGORY"}
|
|
options={["CATEGORY", "COLLECTION"].map((value) => ({
|
|
value,
|
|
label: value,
|
|
}))}
|
|
/>
|
|
</ActionForm>
|
|
{editing && (
|
|
<Button onClick={() => setEditing(null)}>Cancel editing</Button>
|
|
)}
|
|
</>
|
|
)}
|
|
</Panel>
|
|
);
|
|
}
|
|
function Products() {
|
|
const { can } = usePlatform();
|
|
const [offset, setOffset] = useState(0);
|
|
const query = usePrivateQuery(
|
|
`/products?limit=25&offset=${offset}`,
|
|
z.array(adminProductSummary),
|
|
);
|
|
return (
|
|
<>
|
|
<Panel title="Products">
|
|
<QueryView query={query}>
|
|
{(items) => (
|
|
<>
|
|
<Table
|
|
head={["Product", "Status", "Slug"]}
|
|
rowKeys={items.map((item) => item.id)}
|
|
rows={items.map((p) => [
|
|
<WorkspaceLink href={`/admin/catalog/${p.id}`}>
|
|
{p.name}
|
|
</WorkspaceLink>,
|
|
p.status,
|
|
p.slug,
|
|
])}
|
|
/>
|
|
<Pager offset={offset} count={items.length} onPage={setOffset} />
|
|
</>
|
|
)}
|
|
</QueryView>
|
|
</Panel>
|
|
{can("catalog.manage") && (
|
|
<Panel title="New draft product">
|
|
<ProductForm onSave={() => query.refetch()} />
|
|
</Panel>
|
|
)}
|
|
<Groups />
|
|
</>
|
|
);
|
|
}
|
|
function ProductEditor({ id }: { id: string }) {
|
|
const { request, can } = usePlatform();
|
|
const query = usePrivateQuery(`/products/${id}`, adminProduct);
|
|
const [editingVariant, setEditingVariant] = useState<
|
|
z.infer<typeof variant> | undefined
|
|
>();
|
|
return (
|
|
<QueryView query={query}>
|
|
{(item) => (
|
|
<>
|
|
<Panel title={item.name}>
|
|
<p>Status: {item.status}</p>
|
|
<p className="workspace-id">Product ID: {item.id}</p>
|
|
{item.status === "ARCHIVED" ? (
|
|
<Alert severity="info">Archived products cannot be edited.</Alert>
|
|
) : (
|
|
<>
|
|
{can("catalog.manage") && (
|
|
<ProductForm item={item} onSave={() => query.refetch()} />
|
|
)}{" "}
|
|
{can("catalog.publish") &&
|
|
["DRAFT", "PUBLISHED", "ARCHIVED"]
|
|
.filter((status) => status !== item.status)
|
|
.map((status) => (
|
|
<ConfirmAction
|
|
key={status}
|
|
label={
|
|
status === "PUBLISHED"
|
|
? "Publish"
|
|
: status === "DRAFT"
|
|
? "Return to draft"
|
|
: "Archive"
|
|
}
|
|
message={
|
|
status === "ARCHIVED"
|
|
? "Archive this product? Archived products cannot be edited or republished."
|
|
: `Change this product to ${status.toLowerCase()}? Publishing requires an active variant.`
|
|
}
|
|
onConfirm={async () => {
|
|
await request(
|
|
`/products/${id}/status`,
|
|
adminProductSummary,
|
|
{ method: "PATCH", body: { status } },
|
|
);
|
|
await query.refetch();
|
|
}}
|
|
/>
|
|
))}
|
|
</>
|
|
)}
|
|
</Panel>
|
|
<Panel title="Variants">
|
|
<Table
|
|
head={["Variant", "SKU", "Price", "Active", "ID", "Action"]}
|
|
rowKeys={item.variants.map((item) => item.id)}
|
|
rows={item.variants.map((v) => [
|
|
v.name,
|
|
v.sku,
|
|
`${v.currency} ${money(v.price)}`,
|
|
v.active ? "Yes" : "No",
|
|
v.id,
|
|
<>
|
|
{can("catalog.manage") && item.status !== "ARCHIVED" && (
|
|
<Button onClick={() => setEditingVariant(v)} aria-label={`Edit ${v.name}`}>Edit</Button>
|
|
)}
|
|
{can("bom.read") && <div><WorkspaceLink href={`/admin/boms/${v.id}`}>Production BOMs for {v.name}</WorkspaceLink></div>}
|
|
{can("packaging.read") && <div><WorkspaceLink href={`/admin/packaging-boms/${v.id}`}>Packaging BOMs for {v.name}</WorkspaceLink></div>}
|
|
{!can("bom.read") && !can("packaging.read") && (!can("catalog.manage") || item.status === "ARCHIVED") && "Read only"}
|
|
</>,
|
|
])}
|
|
/>
|
|
{can("catalog.manage") && item.status !== "ARCHIVED" && (
|
|
<>
|
|
<h3>
|
|
{editingVariant
|
|
? `Edit ${editingVariant.name}`
|
|
: "New variant"}
|
|
</h3>
|
|
<VariantForm
|
|
key={editingVariant?.id || "new"}
|
|
productId={id}
|
|
item={editingVariant}
|
|
onSave={async () => {
|
|
setEditingVariant(undefined);
|
|
await query.refetch();
|
|
}}
|
|
/>
|
|
{editingVariant && (
|
|
<Button onClick={() => setEditingVariant(undefined)}>
|
|
Cancel editing
|
|
</Button>
|
|
)}
|
|
</>
|
|
)}
|
|
</Panel>
|
|
</>
|
|
)}
|
|
</QueryView>
|
|
);
|
|
}
|
|
export default function CatalogAdminPage({ id }: { id?: string }) {
|
|
return (
|
|
<WorkspaceShell title="Catalog Administration" permission="catalog.read">
|
|
{id && !uuid.safeParse(id).success ? (
|
|
<Alert severity="error">Invalid product identifier.</Alert>
|
|
) : id ? (
|
|
<ProductEditor key={uuid.parse(id)} id={uuid.parse(id)} />
|
|
) : (
|
|
<Products />
|
|
)}
|
|
</WorkspaceShell>
|
|
);
|
|
}
|