diff --git a/openspec/changes/add-zh-cn-messages/tasks.md b/openspec/changes/add-zh-cn-messages/tasks.md index 9ee66b5..39df073 100644 --- a/openspec/changes/add-zh-cn-messages/tasks.md +++ b/openspec/changes/add-zh-cn-messages/tasks.md @@ -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; diff --git a/solvway-admin-portal/app/api/locales/[[...path]]/route.test.ts b/solvway-admin-portal/app/api/locales/[[...path]]/route.test.ts new file mode 100644 index 0000000..f75a93f --- /dev/null +++ b/solvway-admin-portal/app/api/locales/[[...path]]/route.test.ts @@ -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[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" }); + }); +}); diff --git a/solvway-admin-portal/app/api/locales/[[...path]]/route.ts b/solvway-admin-portal/app/api/locales/[[...path]]/route.ts new file mode 100644 index 0000000..0bbdfba --- /dev/null +++ b/solvway-admin-portal/app/api/locales/[[...path]]/route.ts @@ -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; + 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; + 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): Record { + const out: Record = {}; + 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[1]) { + const result = await callMobileApi(target, opts); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data ?? { ok: true }); +} diff --git a/solvway-admin-portal/app/api/messages/[[...path]]/route.test.ts b/solvway-admin-portal/app/api/messages/[[...path]]/route.test.ts new file mode 100644 index 0000000..46763a5 --- /dev/null +++ b/solvway-admin-portal/app/api/messages/[[...path]]/route.test.ts @@ -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[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" }); + }); +}); diff --git a/solvway-admin-portal/app/api/messages/[[...path]]/route.ts b/solvway-admin-portal/app/api/messages/[[...path]]/route.ts new file mode 100644 index 0000000..d650456 --- /dev/null +++ b/solvway-admin-portal/app/api/messages/[[...path]]/route.ts @@ -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[1]) { + const result = await callMobileApi(target, opts); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data ?? { ok: true }); +} diff --git a/solvway-admin-portal/app/components/app/icon-map.ts b/solvway-admin-portal/app/components/app/icon-map.ts index e2fd804..83447b2 100644 --- a/solvway-admin-portal/app/components/app/icon-map.ts +++ b/solvway-admin-portal/app/components/app/icon-map.ts @@ -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 = { ScrollText, Store, MessageCircle, + Languages, + Globe, }; /** Neutral fallback for an absent or unrecognised `iconName` (spec: "The diff --git a/solvway-admin-portal/app/components/ui/textarea.tsx b/solvway-admin-portal/app/components/ui/textarea.tsx new file mode 100644 index 0000000..0805ba7 --- /dev/null +++ b/solvway-admin-portal/app/components/ui/textarea.tsx @@ -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 ( +