feat(portal): Translations and Languages pages
Ported from babyboo and trimmed to back-office labels: list with search and the Missing Chinese filter, edit panel with placeholder checks and an unsaved-changes guard, export, import with preview and summary, and the Languages page with guarded switches. A blank translation is no longer treated as an old placeholder mismatch, so Save blocks a broken new one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
This commit is contained in:
1 parent
27e0ec7bff
commit
a8bfcf5f6d
21 files changed
+1401
-6
No files matched your search
@@ -35,9 +35,9 @@ Verify commands:
|
||||
|
||||
## 5. Portal
|
||||
|
||||
- [ ] 5.1 Route handlers `app/api/locales/**` and `app/api/messages/**`, `routeModules`, sidebar System entries with icons. The language list reloads after sign-in.
|
||||
- [ ] 5.2 Languages page `/locales`: list, add, edit label and order, code read-only on edit, guarded switch with confirm, inline refusals.
|
||||
- [ ] 5.3 Translations page `/messages`:
|
||||
- [x] 5.1 Route handlers `app/api/locales/**` and `app/api/messages/**`, `routeModules`, sidebar System entries with icons. The language list reloads after sign-in.
|
||||
- [x] 5.2 Languages page `/locales`: list, add, edit label and order, code read-only on edit, guarded switch with confirm, inline refusals.
|
||||
- [x] 5.3 Translations page `/messages`:
|
||||
- list with code, English and Chinese;
|
||||
- search, the Missing Chinese filter and its badge;
|
||||
- the edit panel: placeholder checks, unsaved guard, code read-only;
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import { GET, POST, PUT } from "./route";
|
||||
|
||||
type Req = Parameters<typeof GET>[0];
|
||||
const req = (url: string, init?: RequestInit) => new Request(url, init) as unknown as Req;
|
||||
const ctx = (path?: string[]) => ({ params: Promise.resolve({ path }) });
|
||||
const json = (body: unknown, method: string) => ({ method, body: JSON.stringify(body) });
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} });
|
||||
mocks.getToken.mockReset().mockResolvedValue("jwt");
|
||||
});
|
||||
|
||||
describe("/api/locales", () => {
|
||||
it("returns 401 without a session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
expect((await GET(req("http://localhost/api/locales"), ctx())).status).toBe(401);
|
||||
});
|
||||
|
||||
it("lists", async () => {
|
||||
await GET(req("http://localhost/api/locales"), ctx());
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/locales", { token: "jwt" });
|
||||
});
|
||||
|
||||
it("creates with code and label only from the allowed fields", async () => {
|
||||
expect((await POST(req("http://localhost/api/locales", json({ code: "ms_MY" }, "POST")), ctx())).status).toBe(400);
|
||||
await POST(req("http://localhost/api/locales", json({ id: 3, code: " ms_MY ", label: "Bahasa", enabled: false, sortOrder: 3 }, "POST")), ctx());
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/locales",
|
||||
{ method: "POST", body: { code: "ms_MY", label: "Bahasa", enabled: false, sortOrder: 3 }, token: "jwt" });
|
||||
});
|
||||
|
||||
it("updates label, enabled and order at the path id; the code is never sent", async () => {
|
||||
await PUT(req("http://localhost/api/locales/2", json({ id: 9, code: "zh_TW", enabled: false }, "PUT")), ctx(["2"]));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/locales/2", { method: "PUT", body: { enabled: false }, token: "jwt" });
|
||||
expect((await PUT(req("http://localhost/api/locales/x", json({ enabled: true }, "PUT")), ctx(["x"]))).status).toBe(400);
|
||||
});
|
||||
|
||||
it("passes a refusal through with its code", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 409, error: "LocalesFallbackLocked", code: "LocalesFallbackLocked" });
|
||||
const res = await PUT(req("http://localhost/api/locales/1", json({ enabled: false }, "PUT")), ctx(["1"]));
|
||||
expect(res.status).toBe(409);
|
||||
expect(await res.json()).toMatchObject({ code: "LocalesFallbackLocked" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
// Proxy for /api/admin/locales. mobile-api owns the guards (list: any admin; writes: BO_LOCALES).
|
||||
// The code is set on create only and never sent on update.
|
||||
type Ctx = { params: Promise<{ path?: string[] }> };
|
||||
const ID = /^\d+$/;
|
||||
|
||||
export async function GET(_req: NextRequest, { params }: Ctx) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { path = [] } = await params;
|
||||
if (path.length !== 0) return badRequest("Invalid path.");
|
||||
return forward("/api/admin/locales", { token });
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest, { params }: Ctx) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { path = [] } = await params;
|
||||
if (path.length !== 0) return badRequest("Invalid path.");
|
||||
const body = (await req.json().catch(() => ({}))) as Record<string, unknown>;
|
||||
const code = typeof body.code === "string" ? body.code.trim() : "";
|
||||
const label = typeof body.label === "string" ? body.label.trim() : "";
|
||||
if (!code || !label) return badRequest("code and label are required.");
|
||||
return forward("/api/admin/locales", { method: "POST", body: { code, label, ...editable(body) }, token });
|
||||
}
|
||||
|
||||
export async function PUT(req: NextRequest, { params }: Ctx) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { path = [] } = await params;
|
||||
if (path.length !== 1 || !ID.test(path[0])) return badRequest("Invalid path.");
|
||||
const body = (await req.json().catch(() => ({}))) as Record<string, unknown>;
|
||||
const payload = editable(body);
|
||||
if (typeof body.label === "string") {
|
||||
if (!body.label.trim()) return badRequest("label is required.");
|
||||
payload.label = body.label.trim();
|
||||
}
|
||||
if (Object.keys(payload).length === 0) return badRequest("At least one field is required.");
|
||||
return forward(`/api/admin/locales/${encodeURIComponent(path[0])}`, { method: "PUT", body: payload, token });
|
||||
}
|
||||
|
||||
function editable(body: Record<string, unknown>): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = {};
|
||||
if (typeof body.enabled === "boolean") out.enabled = body.enabled;
|
||||
if (typeof body.sortOrder === "number") out.sortOrder = body.sortOrder;
|
||||
return out;
|
||||
}
|
||||
|
||||
async function forward(target: string, opts: Parameters<typeof callMobileApi>[1]) {
|
||||
const result = await callMobileApi<unknown>(target, opts);
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data ?? { ok: true });
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import { GET, POST, PUT } from "./route";
|
||||
|
||||
type Req = Parameters<typeof GET>[0];
|
||||
const req = (url: string, init?: RequestInit) => new Request(url, init) as unknown as Req;
|
||||
const ctx = (path?: string[]) => ({ params: Promise.resolve({ path }) });
|
||||
const json = (body: unknown, method: string) => ({ method, body: JSON.stringify(body) });
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} });
|
||||
mocks.getToken.mockReset().mockResolvedValue("jwt");
|
||||
});
|
||||
|
||||
describe("/api/messages", () => {
|
||||
it("returns 401 without a session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
expect((await GET(req("http://localhost/api/messages"), ctx())).status).toBe(401);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("forwards only the allowed list filters, with page defaults", async () => {
|
||||
await GET(req("http://localhost/api/messages?searchKey=线索&missingLocale=zh_CN&area=AP&evil=1"), ctx());
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith(
|
||||
`/api/admin/messages?searchKey=${encodeURIComponent("线索")}&missingLocale=zh_CN&page=0&size=20`, { token: "jwt" });
|
||||
});
|
||||
|
||||
it("forwards detail and export reads", async () => {
|
||||
await GET(req("http://localhost/api/messages/7"), ctx(["7"]));
|
||||
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/messages/7", { token: "jwt" });
|
||||
await GET(req("http://localhost/api/messages/export"), ctx(["export"]));
|
||||
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/messages/export", { token: "jwt" });
|
||||
});
|
||||
|
||||
it("refuses unknown or nested paths", async () => {
|
||||
expect((await GET(req("http://localhost/api/messages/.."), ctx([".."]))).status).toBe(400);
|
||||
expect((await GET(req("http://localhost/api/messages/7/x"), ctx(["7", "x"]))).status).toBe(400);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("PUT sends only the content to the path id", async () => {
|
||||
const res = await PUT(req("http://localhost/api/messages/7", json({ id: 9, code: "X", content: "{\"zh_CN\":\"线索\"}" }, "PUT")), ctx(["7"]));
|
||||
expect(res.status).toBe(200);
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/messages/7",
|
||||
{ method: "PUT", body: { content: "{\"zh_CN\":\"线索\"}" }, token: "jwt" });
|
||||
});
|
||||
|
||||
it("PUT needs a numeric id and a content string", async () => {
|
||||
expect((await PUT(req("http://localhost/api/messages/x", json({ content: "{}" }, "PUT")), ctx(["x"]))).status).toBe(400);
|
||||
expect((await PUT(req("http://localhost/api/messages/7", json({}, "PUT")), ctx(["7"]))).status).toBe(400);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("POST is import only, with a non-empty array", async () => {
|
||||
expect((await POST(req("http://localhost/api/messages", json({ code: "A" }, "POST")), ctx())).status).toBe(400);
|
||||
expect((await POST(req("http://localhost/api/messages/import", json([], "POST")), ctx(["import"]))).status).toBe(400);
|
||||
const rows = [{ code: "Leads", content: "{}" }];
|
||||
await POST(req("http://localhost/api/messages/import", json(rows, "POST")), ctx(["import"]));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/messages/import", { method: "POST", body: rows, token: "jwt" });
|
||||
});
|
||||
|
||||
it("passes a refusal through with its code", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 409, error: "MsgsCodeAreaLocked", code: "MsgsCodeAreaLocked" });
|
||||
const res = await PUT(req("http://localhost/api/messages/7", json({ content: "{}" }, "PUT")), ctx(["7"]));
|
||||
expect(res.status).toBe(409);
|
||||
expect(await res.json()).toMatchObject({ code: "MsgsCodeAreaLocked" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
// Proxy for /api/admin/messages (area A labels). mobile-api owns the BO_MESSAGES guard.
|
||||
// Reads: list, /{id}, /export. Writes: PUT /{id} (content only), POST /import. No create, no delete.
|
||||
type Ctx = { params: Promise<{ path?: string[] }> };
|
||||
const ID = /^\d+$/;
|
||||
|
||||
export async function GET(req: NextRequest, { params }: Ctx) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { path = [] } = await params;
|
||||
if (path.length === 0) {
|
||||
const q = new URL(req.url).searchParams;
|
||||
const out = new URLSearchParams();
|
||||
for (const key of ["searchKey", "missingLocale"]) {
|
||||
const v = q.get(key);
|
||||
if (v) out.set(key, v);
|
||||
}
|
||||
out.set("page", String(Number(q.get("page")) || 0));
|
||||
out.set("size", String(Number(q.get("size")) || 20));
|
||||
return forward(`/api/admin/messages?${out}`, { token });
|
||||
}
|
||||
if (path.length === 1 && (path[0] === "export" || ID.test(path[0]))) {
|
||||
return forward(`/api/admin/messages/${encodeURIComponent(path[0])}`, { token });
|
||||
}
|
||||
return badRequest("Invalid path.");
|
||||
}
|
||||
|
||||
export async function PUT(req: NextRequest, { params }: Ctx) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { path = [] } = await params;
|
||||
if (path.length !== 1 || !ID.test(path[0])) return badRequest("Invalid path.");
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const content = (body as { content?: unknown }).content;
|
||||
if (typeof content !== "string") return badRequest("content is required.");
|
||||
return forward(`/api/admin/messages/${encodeURIComponent(path[0])}`, { method: "PUT", body: { content }, token });
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest, { params }: Ctx) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { path = [] } = await params;
|
||||
if (path.length !== 1 || path[0] !== "import") return badRequest("Invalid path.");
|
||||
const rows = await req.json().catch(() => null);
|
||||
if (!Array.isArray(rows) || rows.length === 0) return badRequest("A non-empty JSON array of messages is required.");
|
||||
return forward("/api/admin/messages/import", { method: "POST", body: rows, token });
|
||||
}
|
||||
|
||||
async function forward(target: string, opts: Parameters<typeof callMobileApi>[1]) {
|
||||
const result = await callMobileApi<unknown>(target, opts);
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data ?? { ok: true });
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CalendarDays, Circle, ClipboardList, LayoutDashboard, LockKeyhole, Mail, MessageCircle, ScrollText, Shield, ShieldCheck, Store, Tags, UserCog, Users } from "lucide-react";
|
||||
import { CalendarDays, Circle, ClipboardList, Globe, Languages, LayoutDashboard, LockKeyhole, Mail, MessageCircle, ScrollText, Shield, ShieldCheck, Store, Tags, UserCog, Users } from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
|
||||
// Maps the aclMenu tree's `iconName` (a plain string served by
|
||||
@@ -24,6 +24,8 @@ const ICONS: Record<string, LucideIcon> = {
|
||||
ScrollText,
|
||||
Store,
|
||||
MessageCircle,
|
||||
Languages,
|
||||
Globe,
|
||||
};
|
||||
|
||||
/** Neutral fallback for an absent or unrecognised `iconName` (spec: "The
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/app/lib/utils"
|
||||
|
||||
// Small Textarea primitive mirroring input.tsx. The monospace/HTML-source
|
||||
// variant is applied via className (e.g. `font-mono text-xs`) — no separate
|
||||
// variant prop, keeping the primitive minimal per the ui/* convention.
|
||||
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||
return (
|
||||
<textarea
|
||||
data-slot="textarea"
|
||||
className={cn(
|
||||
"flex min-h-[80px] w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30",
|
||||
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
|
||||
"aria-[invalid=true]:border-destructive aria-[invalid=true]:ring-destructive/20 dark:aria-[invalid=true]:ring-destructive/40",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Textarea }
|
||||
@@ -19,7 +19,7 @@ export const SIDEBAR_SECTIONS: { label?: string; modules: string[] }[] = [
|
||||
{ label: "SidebarSectionEvents", modules: ["BO_EVENTS", "BO_EVENT_LEADS"] },
|
||||
{ label: "SidebarSectionLeads", modules: ["BO_LEADS", "BO_WHATSAPP", "BO_INTERESTS"] },
|
||||
{ label: "SidebarSectionAccess", modules: ["BO_USERS", "BO_ROLES", "BO_LOGIN_SECURITY"] },
|
||||
{ label: "SidebarSectionSystem", modules: ["BO_COMPANIES", "BO_EMAILS", "BO_AUDIT_LOG"] },
|
||||
{ label: "SidebarSectionSystem", modules: ["BO_COMPANIES", "BO_EMAILS", "BO_AUDIT_LOG", "BO_MESSAGES", "BO_LOCALES"] },
|
||||
];
|
||||
|
||||
// Icon overrides by module name, so a shared seed icon can differ in the sidebar.
|
||||
|
||||
@@ -655,4 +655,68 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
GuestRemoveFailed: "Could not remove the guest.",
|
||||
PrintCardsTitle: "Print cards",
|
||||
PrintButton: "Print",
|
||||
// add-zh-cn-messages: Languages and Translations
|
||||
BO_MESSAGES: "Translations",
|
||||
BO_LOCALES: "Languages",
|
||||
LocalesTitle: "Languages",
|
||||
LocalesAdd: "Add language",
|
||||
LocalesEdit: "Edit language",
|
||||
LocalesEditRow: "Edit {code}",
|
||||
LocalesLabel: "Label",
|
||||
LocalesSortOrder: "Order",
|
||||
LocalesCodeHint: "Language and region, for example ms_MY. It cannot be changed later.",
|
||||
LocalesActive: "Active",
|
||||
LocalesInactive: "Inactive",
|
||||
LocalesEnabledSwitch: "{label} enabled",
|
||||
LocalesEmpty: "No languages yet.",
|
||||
LocalesRequired: "Code and label are required.",
|
||||
LocalesLoadFailed: "Could not load the languages.",
|
||||
LocalesSaveFailed: "Could not save the language.",
|
||||
LocalesDuplicateCode: "This language code already exists.",
|
||||
LocalesCodeLocked: "A language code cannot be changed.",
|
||||
LocalesFallbackLocked: "English is the fallback language and stays on.",
|
||||
LocalesLastEnabledLocked: "At least one language must stay on.",
|
||||
LocaleNotFound: "This language no longer exists.",
|
||||
LocalesDisableTitle: "Switch off {label}?",
|
||||
LocalesDisableBody: "Staff can no longer pick {label}. Its translations are kept.",
|
||||
LocalesDisableConfirm: "Switch off",
|
||||
MsgsTitle: "Translations",
|
||||
MsgsEdit: "Edit translation",
|
||||
MsgsExport: "Export",
|
||||
MsgsImport: "Import",
|
||||
MsgsSearchGroup: "Search",
|
||||
MsgsSearchLabel: "Search translations",
|
||||
MsgsSearchPlaceholder: "Code, English or Chinese",
|
||||
MsgsMissingChineseFilter: "Missing Chinese",
|
||||
MsgsBadgeMissing: "Missing",
|
||||
MsgsBadgeSameAsEnglish: "Same as English",
|
||||
MsgsEmpty: "No translations yet.",
|
||||
MsgsNoMatch: "No translations match these filters.",
|
||||
MsgsLoadFailed: "Could not load the translations.",
|
||||
MsgsLoadOneFailed: "Could not open this translation.",
|
||||
MsgsSaveFailed: "Could not save the translation.",
|
||||
MsgsExportFailed: "Could not export the translations.",
|
||||
MsgsNotFound: "This translation no longer exists.",
|
||||
MsgsCodeAreaLocked: "A label's code cannot be changed.",
|
||||
MsgsDuplicateCode: "A label with this code already exists.",
|
||||
MsgsCodeRequired: "The code is missing.",
|
||||
MsgsPlaceholderMismatch: "Placeholders must match English. Missing: {missing}. Extra: {extra}.",
|
||||
MsgsPlaceholderAlreadyDifferent: "Placeholders already differed from English before this edit. Missing: {missing}. Extra: {extra}.",
|
||||
MsgsDiscardTitle: "Discard changes?",
|
||||
MsgsDiscardBody: "Your edits to this translation are not saved.",
|
||||
MsgsDiscardConfirm: "Discard",
|
||||
MsgsImportFileLabel: "Translations file (JSON)",
|
||||
MsgsImportInvalidJson: "This file is not valid JSON.",
|
||||
MsgsImportNotArray: "The file must hold a list of translations, as Export writes it.",
|
||||
MsgsImportReadFailed: "Could not read the current translations.",
|
||||
MsgsImportFailed: "The import failed.",
|
||||
MsgsImportPreview: "{created} to create, {updated} to update.",
|
||||
MsgsImportRowError: "Row {index} ({code}): {error}",
|
||||
MsgsImportRowInvalid: "needs a code and content, and is skipped",
|
||||
MsgsImportEnglishCol: "English",
|
||||
MsgsWillCreate: "Will create",
|
||||
MsgsWillUpdate: "Will update",
|
||||
MsgsImportChooseAnother: "Choose another file",
|
||||
MsgsConfirmImport: "Confirm import",
|
||||
MsgsImportSummary: "{created} created, {updated} updated, {errors} failed.",
|
||||
};
|
||||
@@ -14,7 +14,7 @@ describe("routeModules", () => {
|
||||
it("leaves other routes ungated", () => {
|
||||
expect(requiredModuleFor("/")).toBeUndefined();
|
||||
expect(requiredModulesFor("/members")).toBeUndefined();
|
||||
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/audit-log", "/emails", "/event-leads", "/events", "/interests", "/leads", "/login-security", "/roles", "/users", "/whatsapp"]);
|
||||
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/audit-log", "/emails", "/event-leads", "/events", "/interests", "/leads", "/locales", "/login-security", "/messages", "/roles", "/users", "/whatsapp"]);
|
||||
expect(requiredModuleFor("/emails")).toBe("BO_EMAILS");
|
||||
expect(requiredModuleFor("/leads")).toBe("BO_LEADS");
|
||||
});
|
||||
|
||||
@@ -13,6 +13,8 @@ export const ROUTE_MODULES: Record<string, string> = {
|
||||
"/login-security": "BO_LOGIN_SECURITY",
|
||||
"/audit-log": "BO_AUDIT_LOG",
|
||||
"/whatsapp": "BO_WHATSAPP",
|
||||
"/messages": "BO_MESSAGES",
|
||||
"/locales": "BO_LOCALES",
|
||||
};
|
||||
|
||||
export function requiredModuleFor(pathname: string): string | undefined {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { apiGet, apiPost, apiPut } from "@/app/lib/clientApi";
|
||||
import type { MessageRow } from "@/app/lib/translationText";
|
||||
|
||||
// Client calls for the Translations and Languages pages; they go only through the portal's own
|
||||
// /api/messages/** and /api/locales/** route handlers.
|
||||
|
||||
export interface LocaleRow {
|
||||
id: number;
|
||||
code: string;
|
||||
label: string;
|
||||
enabled: boolean;
|
||||
sortOrder: number;
|
||||
}
|
||||
|
||||
export interface ImportResult {
|
||||
created: number;
|
||||
updated: number;
|
||||
errors: { index: number; code: string; error: string }[];
|
||||
}
|
||||
|
||||
export const listLocales = () => apiGet<LocaleRow[]>("/api/locales");
|
||||
export const createLocale = (row: Omit<LocaleRow, "id">) => apiPost<LocaleRow>("/api/locales", row);
|
||||
/** The id is in the path; the code is never sent on update. */
|
||||
export const updateLocale = (id: number, patch: Partial<Pick<LocaleRow, "label" | "enabled" | "sortOrder">>) =>
|
||||
apiPut<LocaleRow>(`/api/locales/${id}`, patch);
|
||||
|
||||
/** `page` is 1-based like the other list pages; mobile-api is 0-based. */
|
||||
export async function listMessages(p: { searchKey?: string; missingChinese?: boolean; page: number; pageSize: number }) {
|
||||
const qs = new URLSearchParams();
|
||||
if (p.searchKey) qs.set("searchKey", p.searchKey);
|
||||
if (p.missingChinese) qs.set("missingLocale", "zh_CN");
|
||||
qs.set("page", String(Math.max(0, p.page - 1)));
|
||||
qs.set("size", String(p.pageSize));
|
||||
const raw = await apiGet<{ content?: MessageRow[]; totalElements?: number } | null>(`/api/messages?${qs}`);
|
||||
return { items: raw?.content ?? [], total: raw?.totalElements ?? 0 };
|
||||
}
|
||||
|
||||
export const getMessage = (id: number) => apiGet<MessageRow>(`/api/messages/${id}`);
|
||||
export const updateMessage = (id: number, content: string) => apiPut<unknown>(`/api/messages/${id}`, { content });
|
||||
export const exportMessages = () => apiGet<MessageRow[]>("/api/messages/export");
|
||||
export const importMessages = (rows: MessageRow[]) => apiPost<ImportResult>("/api/messages/import", rows);
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { buildContent, buildImportPreview, parseContent, placeholderMismatch } from "./translationText";
|
||||
|
||||
describe("translationText", () => {
|
||||
it("parses content and never throws on bad JSON", () => {
|
||||
expect(parseContent('{"en_US":"Leads","zh_CN":"线索"}')).toEqual({ en_US: "Leads", zh_CN: "线索" });
|
||||
expect(parseContent("not json")).toEqual({});
|
||||
expect(parseContent("[1]")).toEqual({});
|
||||
expect(parseContent(null)).toEqual({});
|
||||
});
|
||||
|
||||
it("applies edits, drops blanks and keeps languages the form did not show", () => {
|
||||
const stored = '{"en_US":"Leads","ms_MY":"Petunjuk","zh_CN":"旧"}';
|
||||
expect(JSON.parse(buildContent(stored, { en_US: " Leads ", zh_CN: "线索" }))).toEqual({ en_US: "Leads", ms_MY: "Petunjuk", zh_CN: "线索" });
|
||||
expect(JSON.parse(buildContent(stored, { zh_CN: " " }))).toEqual({ en_US: "Leads", ms_MY: "Petunjuk" });
|
||||
});
|
||||
|
||||
it("compares placeholders as sets", () => {
|
||||
expect(placeholderMismatch("Hi {name}, {count} new", "{count} 条新,{name}")).toEqual({ missing: [], extra: [] });
|
||||
expect(placeholderMismatch("Hi {name}", "你好 {nam}")).toEqual({ missing: ["{name}"], extra: ["{nam}"] });
|
||||
});
|
||||
|
||||
it("previews create or update by code ignoring case, ignoring ids", () => {
|
||||
const existing = [{ id: 7, code: "Leads", content: '{"en_US":"Leads"}' }];
|
||||
expect(buildImportPreview([
|
||||
{ id: 99, code: "leads", content: '{"en_US":"Leads!"}' },
|
||||
{ code: "NewOne", content: '{"en_US":"New"}' },
|
||||
], existing)).toEqual([
|
||||
{ code: "leads", action: "update", currentEn: "Leads", incomingEn: "Leads!" },
|
||||
{ code: "NewOne", action: "create", incomingEn: "New" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
// Helpers for the Translations page, ported from babyboo messageContent, messagePlaceholders and
|
||||
// messageImportPreview, trimmed to area A.
|
||||
|
||||
/** The stored `content` JSON (locale -> text) as a record; malformed content is `{}`, never a throw. */
|
||||
export function parseContent(content: string | null | undefined): Record<string, string> {
|
||||
if (!content) return {};
|
||||
try {
|
||||
const parsed = JSON.parse(content);
|
||||
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, string>) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The content to save: the stored text with the edited languages applied. A blank field is dropped,
|
||||
* and languages the form did not show (e.g. Tastefully's Malay) are kept as stored.
|
||||
*/
|
||||
export function buildContent(stored: string | null | undefined, edited: Record<string, string>): string {
|
||||
const out: Record<string, string> = { ...parseContent(stored) };
|
||||
for (const [code, value] of Object.entries(edited)) {
|
||||
const v = value.trim();
|
||||
if (v) out[code] = v;
|
||||
else delete out[code];
|
||||
}
|
||||
return JSON.stringify(out);
|
||||
}
|
||||
|
||||
const tokens = (text: string) => new Set(text.match(/\{[A-Za-z0-9_]+\}/g) ?? []);
|
||||
|
||||
/** Placeholders compared as sets: `missing` are in English but not in `other`, `extra` the reverse. */
|
||||
export function placeholderMismatch(english: string, other: string): { missing: string[]; extra: string[] } {
|
||||
const en = tokens(english);
|
||||
const ot = tokens(other);
|
||||
return { missing: [...en].filter((x) => !ot.has(x)).sort(), extra: [...ot].filter((x) => !en.has(x)).sort() };
|
||||
}
|
||||
|
||||
export interface MessageRow {
|
||||
id?: number;
|
||||
code: string;
|
||||
area?: string;
|
||||
content: string;
|
||||
description?: string | null;
|
||||
}
|
||||
|
||||
export interface ImportPreviewRow {
|
||||
code: string;
|
||||
action: "create" | "update";
|
||||
currentEn?: string;
|
||||
incomingEn?: string;
|
||||
}
|
||||
|
||||
/** Matches by code ignoring case, never by id, as the backend import does. */
|
||||
export function buildImportPreview(rows: MessageRow[], existing: MessageRow[]): ImportPreviewRow[] {
|
||||
const byCode = new Map<string, MessageRow>();
|
||||
for (const m of existing) if (!byCode.has(m.code.toLowerCase())) byCode.set(m.code.toLowerCase(), m);
|
||||
return rows.map((r) => {
|
||||
const cur = byCode.get(r.code.toLowerCase());
|
||||
const incomingEn = parseContent(r.content).en_US;
|
||||
return cur
|
||||
? { code: r.code, action: "update", currentEn: parseContent(cur.content).en_US, incomingEn }
|
||||
: { code: r.code, action: "create", incomingEn };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { render } from "@testing-library/react";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { groupSidebar, type SidebarLink } from "./aclSidebar";
|
||||
import { requiredModuleFor } from "./routeModules";
|
||||
import { iconFor } from "@/app/components/app/icon-map";
|
||||
|
||||
// add-zh-cn-messages: Translations and Languages sit in System after Audit log, each behind its own module.
|
||||
const link = (name: string, iconName?: string): SidebarLink => ({ name, url: `/${name}`, iconName, children: [] });
|
||||
|
||||
describe("Translations and Languages navigation", () => {
|
||||
it("guards /messages with BO_MESSAGES and /locales with BO_LOCALES", () => {
|
||||
expect(requiredModuleFor("/messages")).toBe("BO_MESSAGES");
|
||||
expect(requiredModuleFor("/locales")).toBe("BO_LOCALES");
|
||||
});
|
||||
|
||||
it("lists them in System after Audit log", () => {
|
||||
const sections = groupSidebar([link("BO_LOCALES"), link("BO_MESSAGES"), link("BO_AUDIT_LOG"), link("BO_COMPANIES"), link("BO_EMAILS")]);
|
||||
expect(sections).toHaveLength(1);
|
||||
expect(sections[0].label).toBe("SidebarSectionSystem");
|
||||
expect(sections[0].links.map((l) => l.name)).toEqual(["BO_COMPANIES", "BO_EMAILS", "BO_AUDIT_LOG", "BO_MESSAGES", "BO_LOCALES"]);
|
||||
});
|
||||
|
||||
it.each([["Languages", "lucide-languages"], ["Globe", "lucide-globe"]])("renders the seeded %s icon", (name, cls) => {
|
||||
const Icon = iconFor(name);
|
||||
const { container } = render(<Icon aria-hidden="true" />);
|
||||
expect(container.querySelector(`svg.${cls}`)).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), apiPut: vi.fn(), useAdminAuth: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", async (importOriginal) => ({
|
||||
ApiError: (await importOriginal<typeof import("@/app/lib/clientApi")>()).ApiError,
|
||||
apiGet: mocks.apiGet,
|
||||
apiPost: mocks.apiPost,
|
||||
apiPut: mocks.apiPut,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
|
||||
import LocalesPage from "./page";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
const ROWS = [
|
||||
{ id: 1, code: "en_US", label: "English", enabled: true, sortOrder: 1 },
|
||||
{ id: 2, code: "zh_CN", label: "简体中文", enabled: true, sortOrder: 2 },
|
||||
{ id: 3, code: "ms_MY", label: "Bahasa Melayu", enabled: false, sortOrder: 3 },
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
for (const m of Object.values(mocks)) m.mockReset();
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => true });
|
||||
mocks.apiGet.mockResolvedValue(ROWS);
|
||||
mocks.apiPut.mockResolvedValue({});
|
||||
mocks.apiPost.mockResolvedValue({});
|
||||
});
|
||||
|
||||
const row = (code: string) => screen.getByText(code).closest("tr")!;
|
||||
|
||||
describe("LocalesPage", () => {
|
||||
it("lists languages with their status and order", async () => {
|
||||
render(<LocalesPage />);
|
||||
await screen.findByText("zh_CN");
|
||||
expect(within(row("zh_CN")).getByText("简体中文")).toBeInTheDocument();
|
||||
expect(within(row("ms_MY")).getByText("Inactive")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("disables the English switch and says why", async () => {
|
||||
render(<LocalesPage />);
|
||||
await screen.findByText("en_US");
|
||||
expect(within(row("en_US")).getByRole("switch")).toBeDisabled();
|
||||
expect(within(row("en_US")).getByText(/English is the fallback/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("asks before switching a language off, and cancel changes nothing", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<LocalesPage />);
|
||||
await screen.findByText("zh_CN");
|
||||
await user.click(within(row("zh_CN")).getByRole("switch"));
|
||||
const dialog = await screen.findByRole("dialog");
|
||||
await user.click(within(dialog).getByRole("button", { name: /cancel/i }));
|
||||
expect(mocks.apiPut).not.toHaveBeenCalled();
|
||||
await user.click(within(row("zh_CN")).getByRole("switch"));
|
||||
await user.click(within(await screen.findByRole("dialog")).getByRole("button", { name: /switch off/i }));
|
||||
await waitFor(() => expect(mocks.apiPut).toHaveBeenCalledWith("/api/locales/2", { enabled: false }));
|
||||
});
|
||||
|
||||
it("switches a language on without asking", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<LocalesPage />);
|
||||
await screen.findByText("ms_MY");
|
||||
await user.click(within(row("ms_MY")).getByRole("switch"));
|
||||
await waitFor(() => expect(mocks.apiPut).toHaveBeenCalledWith("/api/locales/3", { enabled: true }));
|
||||
});
|
||||
|
||||
it("edits label and order with the code read-only", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<LocalesPage />);
|
||||
await screen.findByText("ms_MY");
|
||||
await user.click(within(row("ms_MY")).getByRole("button", { name: /edit ms_MY/i }));
|
||||
const dialog = await screen.findByRole("dialog");
|
||||
expect(within(dialog).queryByLabelText(/^code$/i)).toBeNull();
|
||||
const label = within(dialog).getByLabelText(/label/i);
|
||||
await user.clear(label);
|
||||
await user.type(label, "Melayu");
|
||||
await user.click(within(dialog).getByRole("button", { name: /save/i }));
|
||||
await waitFor(() => expect(mocks.apiPut).toHaveBeenCalledWith("/api/locales/3", { label: "Melayu", sortOrder: 3 }));
|
||||
});
|
||||
|
||||
it("adds a language and shows a duplicate refusal inline", async () => {
|
||||
const user = userEvent.setup();
|
||||
mocks.apiPost.mockRejectedValue(new ApiError("LocalesDuplicateCode", 409, { code: "LocalesDuplicateCode" }));
|
||||
render(<LocalesPage />);
|
||||
await screen.findByText("en_US");
|
||||
await user.click(screen.getByRole("button", { name: /add language/i }));
|
||||
const dialog = await screen.findByRole("dialog");
|
||||
await user.type(within(dialog).getByLabelText(/^code$/i), "zh_CN");
|
||||
await user.type(within(dialog).getByLabelText(/label/i), "中文");
|
||||
await user.click(within(dialog).getByRole("button", { name: /save/i }));
|
||||
await waitFor(() => expect(mocks.apiPost).toHaveBeenCalledWith("/api/locales", { code: "zh_CN", label: "中文", sortOrder: 0, enabled: true }));
|
||||
expect(await within(dialog).findByText(/already exists/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the not-authorised state without BO_LOCALES", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<LocalesPage />);
|
||||
expect(await screen.findByText(/not authori[sz]ed|don't have access|no access/i)).toBeInTheDocument();
|
||||
expect(mocks.apiGet).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,222 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState, type FormEvent } from "react";
|
||||
import { Pencil, Plus } from "lucide-react";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { Badge } from "@/app/components/ui/badge";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
import { Switch } from "@/app/components/ui/switch";
|
||||
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/app/components/ui/table";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { EmptyState, ErrorState, TableSkeleton } from "@/app/components/ui/states";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { createLocale, listLocales, updateLocale, type LocaleRow } from "@/app/lib/services/translations";
|
||||
|
||||
// /locales, ported from babyboo: which languages exist and which staff can pick. /messages holds their text.
|
||||
// Every refusal (duplicate code, English, last enabled) comes back from services-system and shows inline.
|
||||
|
||||
interface FormState {
|
||||
id?: number;
|
||||
code: string;
|
||||
label: string;
|
||||
sortOrder: number;
|
||||
}
|
||||
|
||||
const errorKey = (err: unknown, fallback: string) => (err instanceof Error ? err.message : fallback);
|
||||
|
||||
function LocaleFormDialog({ initial, onClose, onSaved }: { initial: FormState; onClose: () => void; onSaved: () => void }) {
|
||||
const t = useT();
|
||||
const [form, setForm] = useState(initial);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const adding = form.id == null;
|
||||
|
||||
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
const code = form.code.trim();
|
||||
const label = form.label.trim();
|
||||
if ((adding && !code) || !label) return setError("LocalesRequired");
|
||||
const sortOrder = Number.isFinite(form.sortOrder) ? form.sortOrder : 0;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
if (form.id == null) await createLocale({ code, label, sortOrder, enabled: true });
|
||||
else await updateLocale(form.id, { label, sortOrder });
|
||||
onSaved();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(errorKey(err, "LocalesSaveFailed"));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{adding ? t("LocalesAdd") : t("LocalesEdit")}</DialogTitle>
|
||||
</DialogHeader>
|
||||
{error && <ErrorState message={t(error)} />}
|
||||
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
|
||||
<div className="space-y-1.5">
|
||||
{adding ? (
|
||||
<>
|
||||
<Label htmlFor="locale-code">{t("Code")}</Label>
|
||||
<Input id="locale-code" value={form.code} disabled={saving}
|
||||
onChange={(e) => setForm((f) => ({ ...f, code: e.target.value }))} />
|
||||
<p className="text-xs text-muted-foreground">{t("LocalesCodeHint")}</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-sm font-medium">{t("Code")}</p>
|
||||
<p className="font-mono text-sm">{form.code}</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="locale-label">{t("LocalesLabel")}</Label>
|
||||
<Input id="locale-label" value={form.label} disabled={saving}
|
||||
onChange={(e) => setForm((f) => ({ ...f, label: e.target.value }))} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="locale-sort-order">{t("LocalesSortOrder")}</Label>
|
||||
<Input id="locale-sort-order" type="number" value={form.sortOrder} disabled={saving}
|
||||
onChange={(e) => setForm((f) => ({ ...f, sortOrder: Number(e.target.value) }))} />
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="submit" disabled={saving}>{t("Save")}</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function LocalesPageContent() {
|
||||
const t = useT();
|
||||
const [rows, setRows] = useState<LocaleRow[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const [confirmOff, setConfirmOff] = useState<LocaleRow | null>(null);
|
||||
const [dialog, setDialog] = useState<FormState | null>(null);
|
||||
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error ahead of the reload-triggered fetch below.
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
listLocales()
|
||||
.then((result) => !cancelled && setRows([...(result ?? [])].sort((a, b) => a.sortOrder - b.sortOrder)))
|
||||
.catch((err: unknown) => !cancelled && setError(errorKey(err, "LocalesLoadFailed")))
|
||||
.finally(() => !cancelled && setLoading(false));
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [reloadKey]);
|
||||
|
||||
async function setEnabled(row: LocaleRow, enabled: boolean) {
|
||||
setConfirmOff(null);
|
||||
setError(null);
|
||||
try {
|
||||
await updateLocale(row.id, { enabled });
|
||||
refetch();
|
||||
} catch (err) {
|
||||
setError(errorKey(err, "LocalesSaveFailed"));
|
||||
}
|
||||
}
|
||||
|
||||
const enabledCount = rows.filter((r) => r.enabled).length;
|
||||
// Mirrors the server refusals so the reason shows before anyone tries.
|
||||
const lockedReason = (row: LocaleRow) =>
|
||||
row.code === "en_US" && row.enabled ? "LocalesFallbackLocked" : row.enabled && enabledCount <= 1 ? "LocalesLastEnabledLocked" : null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={t("LocalesTitle")}
|
||||
actions={
|
||||
<Button onClick={() => setDialog({ code: "", label: "", sortOrder: 0 })}>
|
||||
<Plus aria-hidden="true" className="size-4" />
|
||||
{t("LocalesAdd")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
|
||||
{loading ? (
|
||||
<TableSkeleton columns={5} />
|
||||
) : rows.length === 0 ? (
|
||||
<EmptyState title={t("LocalesEmpty")} />
|
||||
) : (
|
||||
<div className="overflow-x-auto rounded-table border bg-card">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>{t("Code")}</TableHead>
|
||||
<TableHead>{t("LocalesLabel")}</TableHead>
|
||||
<TableHead>{t("Status")}</TableHead>
|
||||
<TableHead className="text-right">{t("LocalesSortOrder")}</TableHead>
|
||||
<TableHead className="text-right">{t("Enabled")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{rows.map((row) => {
|
||||
const locked = lockedReason(row);
|
||||
return (
|
||||
<TableRow key={row.code}>
|
||||
<TableCell className="font-mono">{row.code}</TableCell>
|
||||
<TableCell>{row.label}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={row.enabled ? "positive" : "neutral"}>{row.enabled ? t("LocalesActive") : t("LocalesInactive")}</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-right tabular">{row.sortOrder}</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
{locked && <span id={`locale-locked-${row.code}`} className="text-xs text-muted-foreground">{t(locked)}</span>}
|
||||
<Switch
|
||||
checked={row.enabled}
|
||||
disabled={!!locked}
|
||||
aria-describedby={locked ? `locale-locked-${row.code}` : undefined}
|
||||
aria-label={t("LocalesEnabledSwitch", { label: row.label })}
|
||||
onCheckedChange={(on) => (on ? setEnabled(row, true) : setConfirmOff(row))}
|
||||
/>
|
||||
<Button variant="ghost" size="sm" className="h-8 px-2" aria-label={t("LocalesEditRow", { code: row.code })}
|
||||
onClick={() => setDialog({ id: row.id, code: row.code, label: row.label, sortOrder: row.sortOrder })}>
|
||||
<Pencil aria-hidden="true" className="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
{confirmOff && (
|
||||
<ConfirmDialog
|
||||
title={t("LocalesDisableTitle", { label: confirmOff.label })}
|
||||
message={t("LocalesDisableBody", { label: confirmOff.label })}
|
||||
confirmLabel={t("LocalesDisableConfirm")}
|
||||
onConfirm={() => setEnabled(confirmOff, false)}
|
||||
onCancel={() => setConfirmOff(null)}
|
||||
/>
|
||||
)}
|
||||
{dialog && <LocaleFormDialog initial={dialog} onClose={() => setDialog(null)} onSaved={refetch} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function LocalesPage() {
|
||||
return (
|
||||
<RequireModule pathname="/locales">
|
||||
<LocalesPageContent />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Upload } from "lucide-react";
|
||||
import { Badge } from "@/app/components/ui/badge";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/app/components/ui/table";
|
||||
import { ErrorState } from "@/app/components/ui/states";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { buildImportPreview, type ImportPreviewRow, type MessageRow } from "@/app/lib/translationText";
|
||||
import { exportMessages, importMessages, type ImportResult } from "@/app/lib/services/translations";
|
||||
|
||||
/** Rows need a code and string content, and back-office area if any; the rest are reported by file row (1-based). */
|
||||
function splitRows(parsed: unknown[]) {
|
||||
const valid: MessageRow[] = [];
|
||||
const at: number[] = [];
|
||||
const bad: { index: number; code: string }[] = [];
|
||||
parsed.forEach((r, i) => {
|
||||
const row = r as Partial<MessageRow> | null;
|
||||
if (row && typeof row.code === "string" && row.code.trim() && typeof row.content === "string" && (row.area == null || row.area === "A")) {
|
||||
valid.push(row as MessageRow);
|
||||
at.push(i + 1);
|
||||
} else {
|
||||
bad.push({ index: i + 1, code: typeof row?.code === "string" ? row.code : "?" });
|
||||
}
|
||||
});
|
||||
return { valid, at, bad };
|
||||
}
|
||||
|
||||
/** Import, ported from babyboo: preview create/update by code, confirm, then a per-row summary. */
|
||||
export function ImportMessagesDialog({ onClose, onImported }: { onClose(): void; onImported(): void }) {
|
||||
const t = useT();
|
||||
const [rows, setRows] = useState<MessageRow[] | null>(null);
|
||||
const [rowAt, setRowAt] = useState<number[]>([]);
|
||||
const [badRows, setBadRows] = useState<{ index: number; code: string }[]>([]);
|
||||
const [preview, setPreview] = useState<ImportPreviewRow[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [result, setResult] = useState<ImportResult | null>(null);
|
||||
const [importing, setImporting] = useState(false);
|
||||
|
||||
async function handleFile(file: File) {
|
||||
setError(null);
|
||||
setResult(null);
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(await file.text());
|
||||
} catch {
|
||||
return setError("MsgsImportInvalidJson");
|
||||
}
|
||||
if (!Array.isArray(parsed)) return setError("MsgsImportNotArray");
|
||||
try {
|
||||
const { valid, at, bad } = splitRows(parsed);
|
||||
setPreview(buildImportPreview(valid, await exportMessages()));
|
||||
setBadRows(bad);
|
||||
setRowAt(at);
|
||||
setRows(valid);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "MsgsImportReadFailed");
|
||||
}
|
||||
}
|
||||
|
||||
async function handleConfirm() {
|
||||
if (!rows) return;
|
||||
setImporting(true);
|
||||
setError(null);
|
||||
try {
|
||||
setResult(await importMessages(rows));
|
||||
onImported();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "MsgsImportFailed");
|
||||
} finally {
|
||||
setImporting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("MsgsImport")}</DialogTitle>
|
||||
</DialogHeader>
|
||||
{error && <ErrorState message={t(error)} />}
|
||||
{!rows && (
|
||||
<Input type="file" accept="application/json" aria-label={t("MsgsImportFileLabel")}
|
||||
onChange={(e) => e.target.files?.[0] && handleFile(e.target.files[0])} />
|
||||
)}
|
||||
{rows && !result && (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("MsgsImportPreview", {
|
||||
created: preview.filter((p) => p.action === "create").length,
|
||||
updated: preview.filter((p) => p.action === "update").length,
|
||||
})}
|
||||
</p>
|
||||
{badRows.length > 0 && (
|
||||
<ul className="list-inside list-disc text-sm text-destructive">
|
||||
{badRows.map((b) => (
|
||||
<li key={b.index}>{t("MsgsImportRowError", { index: b.index, code: b.code, error: t("MsgsImportRowInvalid") })}</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<div className="max-h-64 overflow-y-auto rounded-xl border bg-card">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>{t("Code")}</TableHead>
|
||||
<TableHead>{t("Action")}</TableHead>
|
||||
<TableHead>{t("MsgsImportEnglishCol")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{preview.map((row, i) => (
|
||||
<TableRow key={`${i}|${row.code}`}>
|
||||
<TableCell className="font-mono">{row.code}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={row.action === "update" ? "outline" : "default"}>
|
||||
{row.action === "update" ? t("MsgsWillUpdate") : t("MsgsWillCreate")}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground">
|
||||
{row.action === "update" && <span className="line-through">{row.currentEn ?? "-"}</span>}
|
||||
{row.action === "update" && " / "}
|
||||
<span>{row.incomingEn ?? "-"}</span>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setRows(null)} disabled={importing}>{t("MsgsImportChooseAnother")}</Button>
|
||||
<Button onClick={handleConfirm} disabled={importing || rows.length === 0}>
|
||||
<Upload aria-hidden="true" />
|
||||
{t("MsgsConfirmImport")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
)}
|
||||
{result && (
|
||||
<div role="status">
|
||||
<p>{t("MsgsImportSummary", { created: result.created, updated: result.updated, errors: result.errors.length })}</p>
|
||||
{result.errors.length > 0 && (
|
||||
<ul className="mt-2 list-inside list-disc text-sm text-destructive">
|
||||
{result.errors.map((e) => (
|
||||
<li key={`${e.index}-${e.code}`}>
|
||||
{t("MsgsImportRowError", { index: rowAt[e.index] ?? e.index + 1, code: e.code || "?", error: t(e.error) })}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
"use client";
|
||||
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/app/components/ui/sheet";
|
||||
import { Textarea } from "@/app/components/ui/textarea";
|
||||
import { ErrorState } from "@/app/components/ui/states";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { useLocales } from "@/app/lib/i18n/LocalesProvider";
|
||||
import { buildContent, parseContent, placeholderMismatch, type MessageRow } from "@/app/lib/translationText";
|
||||
import { updateMessage } from "@/app/lib/services/translations";
|
||||
|
||||
const list = (xs: string[]) => (xs.length ? xs.join(", ") : "-");
|
||||
|
||||
/** Edit panel, ported from babyboo: the code is read-only, placeholders must match English, unsaved edits ask first. */
|
||||
export function MessageEditSheet({ message, onClose, onSaved }: { message: MessageRow & { id: number }; onClose: () => void; onSaved: () => void }) {
|
||||
const t = useT();
|
||||
// Enabled languages only, English first; the stored text of any other language is kept on save.
|
||||
const locales = useLocales()
|
||||
.filter((l) => l.enabled !== false)
|
||||
.sort((a, b) => Number(b.code === "en_US") - Number(a.code === "en_US"));
|
||||
const stored = parseContent(message.content);
|
||||
const initial = Object.fromEntries(locales.map((l) => [l.code, stored[l.code] ?? ""]));
|
||||
const [form, setForm] = useState<Record<string, string>>(initial);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
const dirty = JSON.stringify(form) !== JSON.stringify(initial);
|
||||
|
||||
// A language already mismatched when opened only warns, so an old row can still be saved.
|
||||
const checks = locales
|
||||
.filter((l) => l.code !== "en_US" && (form[l.code] ?? "").trim())
|
||||
.map((l) => {
|
||||
const now = placeholderMismatch(form.en_US ?? "", form[l.code] ?? "");
|
||||
// A blank field on open is a new translation, not an old mismatch.
|
||||
const before = (initial[l.code] ?? "").trim() ? placeholderMismatch(initial.en_US ?? "", initial[l.code]) : { missing: [], extra: [] };
|
||||
return {
|
||||
code: l.code,
|
||||
now,
|
||||
mismatched: now.missing.length + now.extra.length > 0,
|
||||
wasMismatched: before.missing.length + before.extra.length > 0,
|
||||
};
|
||||
});
|
||||
const blocked = checks.some((c) => c.mismatched && !c.wasMismatched);
|
||||
|
||||
const requestClose = () => (dirty ? setConfirmOpen(true) : onClose());
|
||||
|
||||
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
await updateMessage(message.id, buildContent(message.content, form));
|
||||
onSaved();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "MsgsSaveFailed");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Sheet open onOpenChange={(open) => !open && requestClose()}>
|
||||
<SheetContent side="right">
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t("MsgsEdit")}</SheetTitle>
|
||||
</SheetHeader>
|
||||
<div className="space-y-4 px-4 pb-4">
|
||||
{error && <ErrorState message={t(error)} />}
|
||||
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium">{t("Code")}</p>
|
||||
<code className="font-mono text-sm">{message.code}</code>
|
||||
</div>
|
||||
{locales.map((locale) => {
|
||||
const check = checks.find((c) => c.code === locale.code);
|
||||
return (
|
||||
<div key={locale.code} className="space-y-1.5">
|
||||
<Label htmlFor={`message-locale-${locale.code}`}>{locale.label}</Label>
|
||||
<Textarea
|
||||
id={`message-locale-${locale.code}`}
|
||||
value={form[locale.code] ?? ""}
|
||||
disabled={saving}
|
||||
onChange={(e) => setForm((f) => ({ ...f, [locale.code]: e.target.value }))}
|
||||
/>
|
||||
{check?.mismatched && (
|
||||
<p className="text-sm text-warning" role="alert">
|
||||
{t(check.wasMismatched ? "MsgsPlaceholderAlreadyDifferent" : "MsgsPlaceholderMismatch", {
|
||||
missing: list(check.now.missing),
|
||||
extra: list(check.now.extra),
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<div className="flex gap-2">
|
||||
<Button type="submit" disabled={saving || blocked}>{t("Save")}</Button>
|
||||
<Button type="button" variant="outline" onClick={requestClose}>{t("Cancel")}</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
{confirmOpen && (
|
||||
<ConfirmDialog
|
||||
title={t("MsgsDiscardTitle")}
|
||||
message={t("MsgsDiscardBody")}
|
||||
confirmLabel={t("MsgsDiscardConfirm")}
|
||||
destructive
|
||||
onConfirm={onClose}
|
||||
onCancel={() => setConfirmOpen(false)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), apiPut: vi.fn(), useAdminAuth: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", async (importOriginal) => ({
|
||||
ApiError: (await importOriginal<typeof import("@/app/lib/clientApi")>()).ApiError,
|
||||
apiGet: mocks.apiGet,
|
||||
apiPost: mocks.apiPost,
|
||||
apiPut: mocks.apiPut,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import MessagesPage from "./page";
|
||||
|
||||
const LEADS = { id: 7, code: "Leads", area: "A", content: '{"en_US":"Leads","zh_CN":"线索","ms_MY":"Petunjuk"}', description: null };
|
||||
const GREET = { id: 8, code: "Greet", area: "A", content: '{"en_US":"Hi {name}"}', description: null };
|
||||
const SAME = { id: 9, code: "WhatsApp", area: "A", content: '{"en_US":"WhatsApp","zh_CN":"WhatsApp"}', description: null };
|
||||
|
||||
function routeGets(list: unknown[] = [LEADS, GREET, SAME]) {
|
||||
mocks.apiGet.mockImplementation(async (path: string) => {
|
||||
if (path.startsWith("/api/messages?")) return { content: list, totalElements: list.length };
|
||||
if (path === "/api/messages/7") return LEADS;
|
||||
if (path === "/api/messages/8") return GREET;
|
||||
if (path === "/api/messages/export") return [LEADS, GREET];
|
||||
throw new Error(`unexpected ${path}`);
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
for (const m of Object.values(mocks)) m.mockReset();
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => true });
|
||||
mocks.apiPut.mockResolvedValue({ ok: true });
|
||||
routeGets();
|
||||
});
|
||||
|
||||
const lastListCall = () => mocks.apiGet.mock.calls.map((c) => c[0] as string).filter((p) => p.startsWith("/api/messages?")).at(-1)!;
|
||||
|
||||
describe("MessagesPage", () => {
|
||||
it("lists code, English and Chinese, flagging missing and copied English", async () => {
|
||||
render(<MessagesPage />);
|
||||
expect(await screen.findByText("线索")).toBeInTheDocument();
|
||||
expect(screen.getAllByText("Leads").length).toBeGreaterThan(0);
|
||||
expect(screen.getByText("Greet").closest("tr")!).toHaveTextContent(/missing/i);
|
||||
expect(screen.getByText("WhatsApp", { selector: "code" }).closest("tr")!).toHaveTextContent(/same as English/i);
|
||||
});
|
||||
|
||||
it("searches and filters missing Chinese from the first page", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MessagesPage />);
|
||||
await screen.findByText("线索");
|
||||
await user.click(screen.getByRole("checkbox", { name: /missing chinese/i }));
|
||||
await waitFor(() => expect(lastListCall()).toContain("missingLocale=zh_CN"));
|
||||
expect(lastListCall()).toContain("page=0");
|
||||
await user.type(screen.getByRole("searchbox", { name: /search/i }), "线索");
|
||||
await waitFor(() => expect(lastListCall()).toContain(`searchKey=${encodeURIComponent("线索")}`));
|
||||
});
|
||||
|
||||
it("edits Chinese and saves the content to the row's id, keeping other languages", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MessagesPage />);
|
||||
await user.click(await screen.findByText("线索"));
|
||||
const sheet = await screen.findByRole("dialog");
|
||||
expect(within(sheet).getByText("Leads", { selector: "code" })).toBeInTheDocument();
|
||||
expect(within(sheet).queryByRole("textbox", { name: /^code$/i })).toBeNull();
|
||||
const zh = within(sheet).getByLabelText("简体中文");
|
||||
await user.clear(zh);
|
||||
await user.type(zh, "潜在客户");
|
||||
await user.click(within(sheet).getByRole("button", { name: /save/i }));
|
||||
await waitFor(() => expect(mocks.apiPut).toHaveBeenCalled());
|
||||
const [path, body] = mocks.apiPut.mock.calls[0];
|
||||
expect(path).toBe("/api/messages/7");
|
||||
expect(JSON.parse(body.content)).toEqual({ en_US: "Leads", zh_CN: "潜在客户", ms_MY: "Petunjuk" });
|
||||
});
|
||||
|
||||
it("blocks Save when the Chinese loses a placeholder", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MessagesPage />);
|
||||
await user.click(await screen.findByText("Hi {name}"));
|
||||
const sheet = await screen.findByRole("dialog");
|
||||
await user.type(within(sheet).getByLabelText("简体中文"), "你好");
|
||||
expect(within(sheet).getByRole("alert")).toHaveTextContent("{name}");
|
||||
expect(within(sheet).getByRole("button", { name: /save/i })).toBeDisabled();
|
||||
await user.type(within(sheet).getByLabelText("简体中文"), " {{name}");
|
||||
expect(within(sheet).getByRole("button", { name: /save/i })).toBeEnabled();
|
||||
});
|
||||
|
||||
it("asks before closing with unsaved changes", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MessagesPage />);
|
||||
await user.click(await screen.findByText("线索"));
|
||||
const sheet = await screen.findByRole("dialog");
|
||||
await user.type(within(sheet).getByLabelText("简体中文"), "!");
|
||||
await user.click(within(sheet).getByRole("button", { name: /^cancel$/i }));
|
||||
expect(await screen.findByRole("button", { name: /^discard$/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("has no add or delete", async () => {
|
||||
render(<MessagesPage />);
|
||||
await screen.findByText("线索");
|
||||
expect(screen.queryByRole("button", { name: /add/i })).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: /delete/i })).toBeNull();
|
||||
});
|
||||
|
||||
it("imports with a preview, then shows the summary", async () => {
|
||||
const user = userEvent.setup();
|
||||
mocks.apiPost.mockResolvedValue({ created: 1, updated: 1, errors: [{ index: 1, code: "New", error: "MsgsDuplicateCode" }] });
|
||||
render(<MessagesPage />);
|
||||
await screen.findByText("线索");
|
||||
await user.click(screen.getAllByRole("button", { name: /import/i })[0]);
|
||||
const dialog = await screen.findByRole("dialog");
|
||||
const rows = [{ id: 1, code: "leads", content: '{"zh_CN":"线索"}' }, { code: "New", content: '{"en_US":"New"}' }, { content: "{}" }];
|
||||
const file = new File([JSON.stringify(rows)], "m.json", { type: "application/json" });
|
||||
await user.upload(within(dialog).getByLabelText(/file/i), file);
|
||||
expect(await within(dialog).findByText(/will update/i)).toBeInTheDocument();
|
||||
expect(within(dialog).getByText(/will create/i)).toBeInTheDocument();
|
||||
expect(within(dialog).getByText(/row 3/i)).toBeInTheDocument();
|
||||
await user.click(within(dialog).getByRole("button", { name: /confirm import/i }));
|
||||
await waitFor(() => expect(mocks.apiPost).toHaveBeenCalledWith("/api/messages/import", rows.slice(0, 2)));
|
||||
expect(await within(dialog).findByRole("status")).toHaveTextContent(/1 created, 1 updated, 1 failed/i);
|
||||
expect(within(dialog).getByText(/row 2/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the not-authorised state without BO_MESSAGES", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<MessagesPage />);
|
||||
expect(await screen.findByText(/not authorised/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,169 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Download, Upload } from "lucide-react";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { Badge } from "@/app/components/ui/badge";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Checkbox } from "@/app/components/ui/checkbox";
|
||||
import { FilterField, FilterPanel, FilterSearch } from "@/app/components/ui/filter-panel";
|
||||
import { DataTable } from "@/app/components/ui/data-table";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { useListFilters } from "@/app/lib/hooks/useListFilters";
|
||||
import { MIN_PAGE_SIZE, useFitPageSize } from "@/app/lib/hooks/useFitPageSize";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { useLocales } from "@/app/lib/i18n/LocalesProvider";
|
||||
import { parseContent, type MessageRow } from "@/app/lib/translationText";
|
||||
import { exportMessages, getMessage, listMessages } from "@/app/lib/services/translations";
|
||||
import { ImportMessagesDialog } from "./ImportMessagesDialog";
|
||||
import { MessageEditSheet } from "./MessageEditSheet";
|
||||
|
||||
// /messages, ported from babyboo and trimmed to back-office labels (area A): no area filter, no add, no delete.
|
||||
// Labels arrive with releases; staff only translate them.
|
||||
const DEFAULTS = { q: "", missing: "" };
|
||||
|
||||
function MessagesPageContent() {
|
||||
const t = useT();
|
||||
const locales = useLocales();
|
||||
const enLabel = locales.find((l) => l.code === "en_US")?.label ?? "English";
|
||||
const zhLabel = locales.find((l) => l.code === "zh_CN")?.label ?? "简体中文";
|
||||
const { tableRef, pageSize } = useFitPageSize();
|
||||
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
|
||||
const [data, setData] = useState<{ items: MessageRow[]; total: number }>({ items: [], total: 0 });
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const [editing, setEditing] = useState<(MessageRow & { id: number }) | null>(null);
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [importOpen, setImportOpen] = useState(false);
|
||||
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
|
||||
|
||||
useEffect(() => {
|
||||
if (pageSize == null) return;
|
||||
let cancelled = false;
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error ahead of the fetch below.
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
listMessages({ searchKey: filters.q || undefined, missingChinese: filters.missing === "zh_CN", page, pageSize })
|
||||
.then((result) => !cancelled && setData(result))
|
||||
.catch((err: unknown) => !cancelled && setError(err instanceof Error ? err.message : "MsgsLoadFailed"))
|
||||
.finally(() => !cancelled && setLoading(false));
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [filters, page, pageSize, reloadKey]);
|
||||
|
||||
async function handleExport() {
|
||||
setExporting(true);
|
||||
setError(null);
|
||||
try {
|
||||
const blob = new Blob([JSON.stringify(await exportMessages(), null, 2)], { type: "application/json" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `translations-${new Date().toISOString().slice(0, 10)}.json`;
|
||||
a.click();
|
||||
// Revoke after the browser has started the download.
|
||||
setTimeout(() => URL.revokeObjectURL(url), 0);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "MsgsExportFailed");
|
||||
} finally {
|
||||
setExporting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function openEdit(id: number) {
|
||||
try {
|
||||
setEditing({ ...(await getMessage(id)), id });
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "MsgsLoadOneFailed");
|
||||
}
|
||||
}
|
||||
|
||||
const columns = useMemo<ColumnDef<MessageRow, unknown>[]>(() => {
|
||||
const en = (m: MessageRow) => parseContent(m.content).en_US?.trim() ?? "";
|
||||
const zh = (m: MessageRow) => parseContent(m.content).zh_CN?.trim() ?? "";
|
||||
return [
|
||||
{ id: "en", enableSorting: false, header: enLabel, cell: ({ row }) => <span className="line-clamp-2">{en(row.original)}</span> },
|
||||
{
|
||||
id: "zh",
|
||||
enableSorting: false,
|
||||
header: zhLabel,
|
||||
cell: ({ row }) => {
|
||||
const e = en(row.original);
|
||||
const z = zh(row.original);
|
||||
return (
|
||||
<div className="flex items-start gap-1.5">
|
||||
<span className="line-clamp-2">{z}</span>
|
||||
{!z && <Badge variant="warning">{t("MsgsBadgeMissing")}</Badge>}
|
||||
{z && z === e && <Badge variant="neutral">{t("MsgsBadgeSameAsEnglish")}</Badge>}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "code",
|
||||
enableSorting: false,
|
||||
header: t("Code"),
|
||||
cell: ({ row }) => <code className="font-mono text-xs text-muted-foreground">{row.original.code}</code>,
|
||||
},
|
||||
];
|
||||
}, [t, enLabel, zhLabel]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={t("MsgsTitle")}
|
||||
actions={
|
||||
<>
|
||||
<Button variant="outline" onClick={handleExport} disabled={exporting}>
|
||||
<Download aria-hidden="true" className="size-4" />
|
||||
{t("MsgsExport")}
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setImportOpen(true)}>
|
||||
<Upload aria-hidden="true" className="size-4" />
|
||||
{t("MsgsImport")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
|
||||
<FilterPanel activeCount={activeCount} onClear={clear} className="mb-4">
|
||||
<FilterField label={t("MsgsSearchGroup")}>
|
||||
<FilterSearch aria-label={t("MsgsSearchLabel")} placeholder={t("MsgsSearchPlaceholder")} className="w-full"
|
||||
value={filters.q} onChange={(q) => set({ q })} />
|
||||
</FilterField>
|
||||
<label className="flex items-center gap-2 self-end pb-2 text-sm">
|
||||
<Checkbox checked={filters.missing === "zh_CN"} onCheckedChange={(on) => set({ missing: on === true ? "zh_CN" : "" })} />
|
||||
{t("MsgsMissingChineseFilter")}
|
||||
</label>
|
||||
</FilterPanel>
|
||||
<DataTable
|
||||
label={t("MsgsTitle")}
|
||||
columns={columns}
|
||||
data={data.items}
|
||||
total={data.total}
|
||||
page={page}
|
||||
pageSize={pageSize ?? MIN_PAGE_SIZE}
|
||||
onPageChange={setPage}
|
||||
isLoading={loading}
|
||||
tableRef={tableRef}
|
||||
rowKey={(m) => String(m.id ?? m.code)}
|
||||
onRowClick={(m) => m.id != null && openEdit(m.id)}
|
||||
empty={<EmptyState title={activeCount > 0 ? t("MsgsNoMatch") : t("MsgsEmpty")} />}
|
||||
/>
|
||||
{editing && <MessageEditSheet key={editing.id} message={editing} onClose={() => setEditing(null)} onSaved={refetch} />}
|
||||
{importOpen && <ImportMessagesDialog onClose={() => setImportOpen(false)} onImported={refetch} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function MessagesPage() {
|
||||
return (
|
||||
<RequireModule pathname="/messages">
|
||||
<MessagesPageContent />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user