Backend modules from tastefully 8bd93d15: core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log, services-email. solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal from tastefully 8bd93d15. Copied as tracked files only. Literal secrets replaced with environment placeholders: - services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY, MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default) - services-system: JUMIO_TOKEN, JUMIO_SECRET (optional) - services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed - core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default removed, ipgeolocation key read from IPGEOLOCATION_API_KEY - services-system EkycAppConfig: commented Jumio credentials removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
206 lines
10 KiB
TypeScript
206 lines
10 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useRef, useState, type ReactNode } from "react";
|
|
import { ArrowDown, ArrowUp, Plus, Trash2 } from "lucide-react";
|
|
import { Button } from "@/app/components/ui/button";
|
|
import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card";
|
|
import { Input } from "@/app/components/ui/input";
|
|
import { Label } from "@/app/components/ui/label";
|
|
import { ErrorState } from "@/app/components/ui/states";
|
|
import { FieldError } from "@/app/components/catalog-setup/FieldError";
|
|
import { parseServerError, type FieldErrors } from "@/app/lib/catalogSetup";
|
|
import { MENU_TITLES, menuBody, moveAt, type MenuHandle, type MenuItem } from "@/app/lib/menus";
|
|
import { getMenu, saveMenu } from "@/app/lib/services/adminMenus";
|
|
import { ApiError } from "@/app/lib/clientApi";
|
|
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
|
|
|
// One storefront menu (add-storefront-menus): top-level items, each with links under it. Rows carry
|
|
// stable keys so moves keep their inputs.
|
|
|
|
export interface LinkOption {
|
|
label: string;
|
|
url: string;
|
|
}
|
|
|
|
interface Row {
|
|
key: number;
|
|
label: string;
|
|
url: string;
|
|
children: Row[];
|
|
}
|
|
|
|
const SELECT_CLASS =
|
|
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm disabled:cursor-not-allowed disabled:opacity-50";
|
|
|
|
/** Server error paths shown under a field; anything else goes to the summary alert. */
|
|
const RENDERED = /^(items|items\[\d+\]\.(label|url|children)|items\[\d+\]\.children\[\d+\]\.(label|url))$/;
|
|
|
|
function Field({ id, label, error, children }: { id: string; label: string; error?: string; children: ReactNode }) {
|
|
return (
|
|
<div className="space-y-1.5">
|
|
<Label htmlFor={id}>{label}</Label>
|
|
{children}
|
|
<FieldError message={error} />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export function MenuEditor({ handle, options }: { handle: MenuHandle; options: LinkOption[] }) {
|
|
const t = useT();
|
|
const title = MENU_TITLES[handle];
|
|
const nextKey = useRef(0);
|
|
const toRows = (items: MenuItem[]): Row[] =>
|
|
items.map((i) => ({ key: ++nextKey.current, label: i.label, url: i.url ?? "", children: toRows(i.children ?? []) }));
|
|
|
|
const [rows, setRows] = useState<Row[]>([]);
|
|
const [loading, setLoading] = useState(true);
|
|
const [loadError, setLoadError] = useState<string | null>(null);
|
|
const [errors, setErrors] = useState<FieldErrors>({});
|
|
const [summary, setSummary] = useState<string | null>(null);
|
|
const [notice, setNotice] = useState<string | null>(null);
|
|
const [saving, setSaving] = useState(false);
|
|
|
|
useEffect(() => {
|
|
let cancelled = false;
|
|
getMenu(handle)
|
|
.then((view) => {
|
|
if (!cancelled) setRows(toRows(view.items ?? []));
|
|
})
|
|
.catch((err: unknown) => {
|
|
if (!cancelled) setLoadError(err instanceof Error ? err.message : "MnuLoadFailed");
|
|
})
|
|
.finally(() => {
|
|
if (!cancelled) setLoading(false);
|
|
});
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps -- load once per handle
|
|
}, [handle]);
|
|
|
|
// Errors are keyed by position, so any reorder or removal clears them.
|
|
const reorder = (next: Row[]) => {
|
|
setErrors({});
|
|
setRows(next);
|
|
};
|
|
const updateRow = (key: number, patch: Partial<Row>) =>
|
|
setRows((rs) => rs.map((r) => (r.key === key ? { ...r, ...patch } : r)));
|
|
const updateChild = (parent: number, key: number, patch: Partial<Row>) =>
|
|
setRows((rs) => rs.map((r) => (r.key === parent ? { ...r, children: r.children.map((c) => (c.key === key ? { ...c, ...patch } : c)) } : r)));
|
|
const newRow = (): Row => ({ key: ++nextKey.current, label: "", url: "", children: [] });
|
|
|
|
async function save() {
|
|
setErrors({});
|
|
setSummary(null);
|
|
setNotice(null);
|
|
setSaving(true);
|
|
try {
|
|
const toItems = (rs: Row[]): MenuItem[] => rs.map((r) => ({ label: r.label, url: r.url, children: toItems(r.children) }));
|
|
await saveMenu(handle, menuBody(toItems(rows)));
|
|
setNotice("MnuSaved");
|
|
} catch (err) {
|
|
const message = err instanceof Error ? err.message : "MnuSaveFailed";
|
|
const { path, message: fieldMessage } = parseServerError(message);
|
|
if (err instanceof ApiError && err.status === 422 && path && RENDERED.test(path)) setErrors({ [path]: fieldMessage });
|
|
else setSummary(message);
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
}
|
|
|
|
const linkFields = (prefix: string, idBase: string, row: Row, onChange: (patch: Partial<Row>) => void) => (
|
|
<div className="grid gap-3 sm:grid-cols-3">
|
|
<Field id={`${idBase}-label`} label={t("MnuLabel")} error={errors[`${prefix}.label`]}>
|
|
<Input id={`${idBase}-label`} value={row.label} disabled={saving} onChange={(e) => onChange({ label: e.target.value })} />
|
|
</Field>
|
|
<Field id={`${idBase}-url`} label={t("MnuLink")} error={errors[`${prefix}.url`]}>
|
|
<Input id={`${idBase}-url`} value={row.url} placeholder={t("MnuLinkPlaceholder")} disabled={saving} onChange={(e) => onChange({ url: e.target.value })} />
|
|
</Field>
|
|
<Field id={`${idBase}-pick`} label={t("MnuPickLabel")}>
|
|
<select id={`${idBase}-pick`} className={SELECT_CLASS} value="" disabled={saving} onChange={(e) => e.target.value && onChange({ url: e.target.value })}>
|
|
<option value="">{t("MnuChoose")}</option>
|
|
{options.map((o) => (
|
|
<option key={o.url} value={o.url}>
|
|
{o.label}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</Field>
|
|
</div>
|
|
);
|
|
|
|
return (
|
|
<Card role="region" aria-label={t(title)}>
|
|
<CardHeader>
|
|
<CardTitle>{t(title)}</CardTitle>
|
|
</CardHeader>
|
|
<CardContent className="space-y-4">
|
|
{loadError ? (
|
|
<ErrorState message={t(loadError)} />
|
|
) : loading ? null : (
|
|
<>
|
|
{summary && <p role="alert" className="text-sm text-destructive">{t(summary)}</p>}
|
|
{notice && <p role="status" className="text-sm text-positive">{t(notice)}</p>}
|
|
<FieldError message={errors.items} />
|
|
|
|
{rows.map((row, i) => (
|
|
<fieldset key={row.key} aria-label={t("MnuItemN", { n: i + 1 })} className="space-y-3 rounded-xl border p-4">
|
|
<div className="flex items-center justify-between gap-2">
|
|
<span className="text-sm font-medium">{t("MnuItemN", { n: i + 1 })}</span>
|
|
<div className="flex gap-1">
|
|
<Button type="button" variant="ghost" size="icon" aria-label={t("MnuMoveItemUp")} disabled={saving || i === 0} onClick={() => reorder(moveAt(rows, i, -1))}>
|
|
<ArrowUp aria-hidden="true" className="size-4" />
|
|
</Button>
|
|
<Button type="button" variant="ghost" size="icon" aria-label={t("MnuMoveItemDown")} disabled={saving || i === rows.length - 1} onClick={() => reorder(moveAt(rows, i, 1))}>
|
|
<ArrowDown aria-hidden="true" className="size-4" />
|
|
</Button>
|
|
<Button type="button" variant="ghost" size="icon" aria-label={t("MnuRemoveItem")} disabled={saving} onClick={() => reorder(rows.filter((r) => r.key !== row.key))}>
|
|
<Trash2 aria-hidden="true" className="size-4" />
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
{linkFields(`items[${i}]`, `menu-${handle}-${row.key}`, row, (patch) => updateRow(row.key, patch))}
|
|
|
|
{row.children.map((c, j) => (
|
|
<fieldset key={c.key} aria-label={t("MnuItemLinkN", { i: i + 1, j: j + 1 })} className="ml-6 space-y-2 rounded-lg border border-dashed p-3">
|
|
<div className="flex items-center justify-between gap-2">
|
|
<span className="text-xs text-muted-foreground">{t("MnuLinkN", { n: j + 1 })}</span>
|
|
<div className="flex gap-1">
|
|
<Button type="button" variant="ghost" size="icon" aria-label={t("MnuMoveLinkUp")} disabled={saving || j === 0} onClick={() => reorder(rows.map((r) => (r.key === row.key ? { ...r, children: moveAt(r.children, j, -1) } : r)))}>
|
|
<ArrowUp aria-hidden="true" className="size-4" />
|
|
</Button>
|
|
<Button type="button" variant="ghost" size="icon" aria-label={t("MnuMoveLinkDown")} disabled={saving || j === row.children.length - 1} onClick={() => reorder(rows.map((r) => (r.key === row.key ? { ...r, children: moveAt(r.children, j, 1) } : r)))}>
|
|
<ArrowDown aria-hidden="true" className="size-4" />
|
|
</Button>
|
|
<Button type="button" variant="ghost" size="icon" aria-label={t("MnuRemoveLink")} disabled={saving} onClick={() => reorder(rows.map((r) => (r.key === row.key ? { ...r, children: r.children.filter((x) => x.key !== c.key) } : r)))}>
|
|
<Trash2 aria-hidden="true" className="size-4" />
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
{linkFields(`items[${i}].children[${j}]`, `menu-${handle}-${row.key}-${c.key}`, c, (patch) => updateChild(row.key, c.key, patch))}
|
|
</fieldset>
|
|
))}
|
|
<FieldError message={errors[`items[${i}].children`]} />
|
|
<Button type="button" variant="outline" size="sm" disabled={saving} onClick={() => updateRow(row.key, { children: [...row.children, newRow()] })}>
|
|
<Plus aria-hidden="true" className="size-4" />
|
|
{t("MnuAddLink")}
|
|
</Button>
|
|
</fieldset>
|
|
))}
|
|
|
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
|
<Button type="button" variant="outline" size="sm" disabled={saving} onClick={() => setRows((rs) => [...rs, newRow()])}>
|
|
<Plus aria-hidden="true" className="size-4" />
|
|
{t("MnuAddItem")}
|
|
</Button>
|
|
<Button type="button" disabled={saving} onClick={() => void save()}>
|
|
{t("Save")}
|
|
</Button>
|
|
</div>
|
|
</>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|