From 94e805fc19eea6f50509881fc9cdd2568106b0b2 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 12:26:57 +0800 Subject: [PATCH 01/15] docs: design for Chinese translations and the locale screens Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs --- .../specs/2026-12-02-zh-cn-messages-design.md | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 docs/superpowers/specs/2026-12-02-zh-cn-messages-design.md diff --git a/docs/superpowers/specs/2026-12-02-zh-cn-messages-design.md b/docs/superpowers/specs/2026-12-02-zh-cn-messages-design.md new file mode 100644 index 0000000..3645093 --- /dev/null +++ b/docs/superpowers/specs/2026-12-02-zh-cn-messages-design.md @@ -0,0 +1,95 @@ +# Chinese For Staff: Translations And Locale Screens (Design) + +Date: 2026-12-02. Change: `add-zh-cn-messages`. + +## Intent + +INS and CV staff work in Chinese. Picking 简体中文 in the header must turn the whole back office into Chinese, and the company must be able to correct the wording itself, without a release. + +## What Exists Today + +- The portal already carries babyboo's loading side. It loads the catalog server-side, caches it per catalog version, offers a language switcher and resolves labels through `t()`. A guard test keeps every visible label on `t()`, with no exceptions. +- **The endpoints it calls were never ported.** `/api/admin/messages/catalog/{locale}`, `/api/admin/messages/catalog-version` and `/api/admin/locales` all answer 404 in mobile-api. So the portal always shows its built-in English (`defaultMessages.ts`, 643 labels), whatever language is picked. +- `service-system.message` holds about 3,400 area-A rows from Tastefully, with JSON content per locale (`en_US`, `ms_MY`, `zh_CN`, `zh_TW`, `in_ID`). Only 43 of the 643 portal labels have a row; 39 of those have Chinese, some of it wrong ("Add Member", 职责 for Role). +- Once the catalog loads, database English overrides the built-in English. Four rows would change visible text: `LogIn` would show "Login", `Member` "Visitor", `Wallet` "Loyalty Point" and `Tree` "My Referral". + +## Goals + +1. Port babyboo's translation and locale management, backend and screens, so the catalog loads and staff can edit it. +2. Ship a first-pass Simplified Chinese for every back-office label, marked for a native speaker to check. +3. Keep new features from shipping English-only labels. + +## Non-goals + +- The visitor pages (`/r`, `/i`, `/c`) and emails. They share labels, so a visitor whose browser asks for Chinese gets the Chinese labels; the privacy notice stays per company in English and BM. +- Malay, Traditional Chinese and Indonesian text. +- babyboo's currency screens, which share the same specs but are unrelated. + +## Anti-goals + +- A staff member who never picks Chinese sees any English change, other than the four fixes above. +- A typo in the catalog breaks a page. Catalog text stays data, never markup, and a placeholder such as `{n}` must survive translation. + +## Approaches Considered + +- **A. Repo translation file turned into SQL** (first pick). Dropped once the owner pointed at babyboo's locale screen. With an editor, the database is the source of truth and a repo copy would drift. +- **B. SQL only.** Nothing would stop English-only labels, and reviewing text in SQL strings is painful. +- **C. Port babyboo's editor, then load Chinese into it** (chosen, owner 2026-12-02). It fixes the broken loading, gives the company a way to correct wording, and babyboo proves the flow. + +## Design + +### Port from babyboo (porting rule: list the old screens' rules, turn them into tests, then build) + +- **services-system:** + - the `supported_locale` table and its controller (list, create, update; a duplicate code refused; an update cannot leave the registry unusable); + - `catalog_meta`, whose version bumps in the same transaction as every message save; + - the message search, save (upsert, no code change, no duplicate), import and export endpoints, and the missing-Chinese search. +- **mobile-api:** + - `AdminLocaleController`: the list for any signed-in admin; changes need `BO_LOCALES`; + - the public list of enabled locales; + - `AdminMessageController` under `BO_MESSAGES`: catalog, catalog version, list, detail, save, update, import, export. Saves, imports and exports are audited. +- **Portal:** + - `/locales`: turn languages on and off, guarded so the last enabled language and the default cannot be switched off; + - `/messages`: search wording in any language, a "Missing Chinese" filter, an edit panel that checks placeholders and guards unsaved edits, and export and import with a preview; + - route handlers, `routeModules`, sidebar entries under System. +- **Modules:** `BO_MESSAGES` and `BO_LOCALES`, granted to no role. My call: like interests, translations are shared by INS and CV, so only super admins hold them by default. A super admin may still grant them to a translator's role. + +### Locales seeded + +`en_US` and `zh_CN` enabled. `ms_MY`, `zh_TW` and `in_ID` are seeded disabled, so their existing text stays editable but they do not appear in the switcher. + +### The Chinese + +- I write `zh_CN` for all 643 labels in plain office Chinese, with one glossary kept consistent: + - lead 线索 + - event lead 活动线索 + - salesperson 销售员 + - interest 兴趣 + - role 角色 + - check-in 签到 + - WhatsApp, QR and the company codes left as they are. +- **Delivery:** `sql/03-zh-cn-messages.sql` in the change folder, mirrored into `local/seed/`. For each portal label it upserts the area-A row: + - insert a missing row with `en_US` from `defaultMessages.ts` and the new `zh_CN`; + - on an existing row, set `zh_CN` (overwriting the Tastefully text) and leave other languages alone. + - It also sets `en_US` on the four conflicting rows to the portal's English, and bumps the catalog version. + - The four rows only matter to the Tastefully customer portal, which is not deployed. +- **Review:** the deployment doc and the hand-over say the Chinese is a first pass. A native speaker reviews it in `/messages`: export, fix, import, or edit in place. The "Missing Chinese" filter shows any gap. + +### Keeping new labels translated + +- The SQL is generated from `solvway-admin-portal/app/lib/i18n/zh_CN.seed.json` by a small script, and a test checks that the committed SQL matches the generator output. +- A portal test fails when a key in `defaultMessages.ts` has no non-empty entry in that file, or when an entry loses or adds a `{placeholder}`. +- Later changes add their Chinese lines to the file and ship a generated insert-if-missing SQL for their new labels only, so staff edits in the database are never overwritten. +- The file is a seed, not the source of truth. Its header says so. + +## Constraints + +- Branch from `origin/main`. TDD. A live Playwright check of both screens and the Chinese back office, at 1280 and 360 px. +- No customer data. The SQL holds label text only. +- Catalog text is rendered as text, never HTML (an existing test covers this). + +## Left To The Builder + +- The exact babyboo files to port, and trimming babyboo-only parts: the currency screens and the member-message areas. +- Sidebar icons for the two screens. +- Wording inside the glossary's bounds. From e81ccc51accbf914150b7961eed8cfe8373ae63e Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 12:30:45 +0800 Subject: [PATCH 02/15] docs: OpenSpec change add-zh-cn-messages Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs --- .../changes/add-zh-cn-messages/.openspec.yaml | 2 + openspec/changes/add-zh-cn-messages/design.md | 93 +++++++ .../changes/add-zh-cn-messages/proposal.md | 41 +++ .../specs/admin-visual-design/spec.md | 31 +++ .../specs/ui-translations/spec.md | 249 ++++++++++++++++++ openspec/changes/add-zh-cn-messages/tasks.md | 71 +++++ 6 files changed, 487 insertions(+) create mode 100644 openspec/changes/add-zh-cn-messages/.openspec.yaml create mode 100644 openspec/changes/add-zh-cn-messages/design.md create mode 100644 openspec/changes/add-zh-cn-messages/proposal.md create mode 100644 openspec/changes/add-zh-cn-messages/specs/admin-visual-design/spec.md create mode 100644 openspec/changes/add-zh-cn-messages/specs/ui-translations/spec.md create mode 100644 openspec/changes/add-zh-cn-messages/tasks.md diff --git a/openspec/changes/add-zh-cn-messages/.openspec.yaml b/openspec/changes/add-zh-cn-messages/.openspec.yaml new file mode 100644 index 0000000..eb2b21e --- /dev/null +++ b/openspec/changes/add-zh-cn-messages/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-12-02 diff --git a/openspec/changes/add-zh-cn-messages/design.md b/openspec/changes/add-zh-cn-messages/design.md new file mode 100644 index 0000000..c18ef8c --- /dev/null +++ b/openspec/changes/add-zh-cn-messages/design.md @@ -0,0 +1,93 @@ +## Context + +The product design is `docs/superpowers/specs/2026-12-02-zh-cn-messages-design.md` (owner approval 2026-12-02). Facts from the codebase: + +- **The portal side already exists.** It came over from babyboo: + - `app/lib/server/messages.ts` loads the catalog keyed on the catalog version; + - `app/lib/server/locales.ts` loads the language list, from the admin path with a session and the public path without one; + - `app/lib/i18n/t.ts` resolves the catalog, then the built-in English, then the code; + - the language switcher, and the guard test that keeps every visible label on `t()`. +- **The backend side is missing.** mobile-api answers 404 on `/api/admin/messages/catalog/{locale}`, `/api/admin/messages/catalog-version`, `/api/admin/locales` and `/api/public/locales`. services-system has `/message/*` reads and a plain save, but no `supported_locale`, no `catalog_meta`, no search and no save checks. +- **The data.** `service-system.message` holds about 3,400 area-`A` rows from Tastefully, with JSON `content` per language. Only 43 of the 643 portal labels have a row, and 4 of those would change visible English. +- **The gateway** lets any URL containing `/message/` through without a user token. babyboo narrowed this to exact read paths. +- **Error shape.** services-system answers refusals as ProblemDetail, with the reason in `detail`. The core handler wins over service-level advice (memory `counter-error-body`). mobile-api reads the reason from `detail`. +- **Source to port:** babyboo `~/Projects/babyboo`: + - specs `locale-registry`, `admin-portal-locale-ui`, `message-admin-api`, `catalog-cache-invalidation`, `admin-portal-i18n`; + - code `SupportedLocale*`, `CatalogVersionService`, `MessageService`, `MessageController`, `AdminLocaleController`, `AdminMessageController`; + - portal `app/locales`, `app/messages`, `app/api/locales`, `app/api/messages`. + +## Goals / Non-Goals + +**Goals:** everything in the spec delta. + +**Non-goals:** +- the visitor pages' own wording and the emails; +- Malay, Traditional Chinese and Indonesian text; +- babyboo's currency screens and the customer-portal areas (`AP`, `M`); +- adding or deleting labels from the screen. + +## Decisions + +1. **Port, trimmed to Co-Lite.** These babyboo parts stay out, because nothing in Co-Lite uses them and the customer portal is not deployed: + - the Area filter: the Translations page and the export work on area `A` only; + - the add-label form: labels come with releases, and staff only translate; + - the currency endpoints. + + Everything else follows babyboo's rules, which are listed in the specs above and turned into tests before the screens are built. +2. **services-system:** + - `SupportedLocale` (table `supported_locale`: id, unique code, label, enabled, sort_order) under `/locale/*`: `findAll`, `findAllEnabled`, `findById`, `save`, `update`. It refuses with the reasons `LocalesDuplicateCode`, `LocalesCodeLocked`, `LocalesFallbackLocked` and `LocalesLastEnabledLocked`. + - `catalog_meta` (one row, `id = 1`), bumped by an atomic single-row update in the same transaction as every message save or import and every locale save or update. A refused write does not bump. + - `/message/catalogVersion`. + - `/message/search`: searchKey matches the code, `en_US` or `zh_CN` ignoring case; `missingLocale=zh_CN` matches absent, blank or equal to English; area filter; paged and sorted by code. + - `/message/save` refuses a code or area change (`MsgsCodeAreaLocked`) and a duplicate code in an area, ignoring case (`MsgsDuplicateCode`), and returns failures instead of swallowing them. +3. **mobile-api:** + - `AdminLocaleController`: `GET /api/admin/locales` for any signed-in admin; `POST` and `PUT /{id}` under `BO_LOCALES`. + - `GET /api/public/locales`: enabled only, no session. + - `AdminMessageController` under `BO_MESSAGES`: `GET messages` (search, missingLocale, page), `GET messages/{id}`, `PUT messages/{id}` (the path id wins over the body), `GET messages/export`, `POST messages/import` (per-row upsert, matched by code ignoring case within area `A`, summary `{created, updated, errors[{index, code, error}]}`). + - `GET messages/catalog/{locale}` and `GET messages/catalog-version` need the API key but no session. + - Refusal reasons pass through as 409s. `@Audited` covers PUT, import, export (a sensitive read) and the locale writes. +4. **Gateway.** Replace the `url.contains("/message/")` bypass with exact read paths: `/message/catalogVersion`, `/message/getAllMessages/`, `/message/getMessageJsonForMobile/` and any other read in use today (check callers first), plus `GET /locale/findAllEnabled`. Saves, search, `findAll` and the locale writes then need the user token that mobile-api already forwards. This is security code, so the whole diff is read in review. +5. **Portal:** + - `/locales` and `/messages` pages, ported with the edit panel (`MessageEditSheet`) and the import dialog; + - route handlers under `app/api/locales/**` and `app/api/messages/**`, forwarding the session token; + - `routeModules` entries; + - the sidebar System section gets `BO_MESSAGES` (icon `Languages`) and `BO_LOCALES` (icon `Globe`), after Audit log. + - After sign-in the portal refreshes its server components, so the language list reloads (babyboo `admin-locales-after-login`); check whether Co-Lite already does this. +6. **Modules and SQL** (change folder `sql/`, mirrored into `local/seed/`): + - `01-locales.sql` (DDL: `supported_locale` with the five rows, `catalog_meta` at version 0); + - `02-modules.sql` (`BO_MESSAGES`, `BO_LOCALES`, area BO, parent System, granted to no role); + - `03-zh-cn-messages.sql` (generated); + - `99-rollback.sql`. + + The local seed appends `01` and `02` to `03-colite.sql` and adds `04-zh-cn-messages.sql`. +7. **The Chinese:** + - `solvway-admin-portal/app/lib/i18n/zh_CN.seed.json` maps each `defaultMessages.ts` key to its Chinese. + - `npm run i18n:sql` writes `03-zh-cn-messages.sql` from `defaultMessages.ts` and the JSON: + - for each key, insert the area-`A` row with `en_US` and `zh_CN` when no row matches the code ignoring case; + - otherwise `JSON_SET` its `zh_CN`; + - set `en_US` for the four conflicting codes (`LogIn`, `Member`, `Wallet`, `Tree`); + - bump `catalog_meta`. + - Tests: + - every key has non-empty Chinese; + - the placeholder sets are equal; + - no extra keys in the JSON; + - the committed SQL equals the generator output. + - Glossary: lead 线索, event lead 活动线索, salesperson 销售员, interest 兴趣, role 角色, check-in 签到, event 活动, user 用户, company 公司, dashboard 仪表板, audit log 审计日志. WhatsApp, QR and company codes stay as they are. + - Later changes add their new keys to the JSON and ship an insert-if-missing SQL for those keys only. +8. **The four English rows.** They hold Tastefully MLM wording that only the undeployed customer portal reads. Setting them to the portal's English is the smallest fix. Deleting them would change that portal more. + +## Risks / Trade-offs + +- **Narrowing the gateway** can break a caller that relied on the open `/message/` prefix, such as the customer portal or a service. Mitigation: grep every `/message/` caller before narrowing, and run the full backend verify. +- **Catalog English now overrides the built-in English** for any key that has a database row. The SQL aligns the four known conflicts. A guard test compares the generated SQL's English with `defaultMessages.ts`, and the live check signs in in English. +- **First-pass Chinese can read machine-like.** It is marked for review. The Missing Chinese filter and export/import make the review cheap. The deployment doc says so. +- **The catalog read is public.** It is label text only, behind the API key, and babyboo makes the same call. +- **The repo seed and the database can drift** after staff edits. The JSON is a seed, not the source of truth. Later SQL only inserts what is missing, so edits are never overwritten. + +## Migration Plan + +1. Run `sql/01-locales.sql` (DDL), `sql/02-modules.sql` and `sql/03-zh-cn-messages.sql`. +2. Deploy services-system, the gateway, mobile-api and the portal. +3. A super admin checks the back office in 简体中文 and grants `BO_MESSAGES` to the reviewer's role if needed. + +Rollback: `sql/99-rollback.sql` drops the two tables and the modules. The Chinese text stays in `message`, which is harmless with the previous images, because they never read it. diff --git a/openspec/changes/add-zh-cn-messages/proposal.md b/openspec/changes/add-zh-cn-messages/proposal.md new file mode 100644 index 0000000..23c2e8b --- /dev/null +++ b/openspec/changes/add-zh-cn-messages/proposal.md @@ -0,0 +1,41 @@ +## Why + +INS and CV staff work in Chinese, but picking 简体中文 changes almost nothing. The portal was built to load its labels from the database message catalog, but the mobile-api endpoints it calls were never ported from babyboo, so it always shows its built-in English. There is also no way for the company to correct wording without a release. Owner decision 2026-12-02: port babyboo's translation and language screens, then load Chinese for every back-office label. + +## What Changes + +- **Catalog loading works.** services-system gets a catalog version that bumps on every message or locale write. mobile-api serves the catalog, its version and the locale list at the paths the portal already calls. A wording change shows on the next page load. +- **Languages screen (`/locales`, module `BO_LOCALES`).** Lists the supported languages, adds one, edits its label and order, and switches one on or off. English and the last enabled language cannot be switched off, and a code cannot be renamed. +- **Translations screen (`/messages`, module `BO_MESSAGES`).** Lists the back-office labels with English and Chinese. It searches wording in either language, filters to missing Chinese, and edits a label with placeholder checks and an unsaved-edit guard. Export and import with a preview are included. Labels cannot be added or deleted here. +- **Languages seeded.** English and 简体中文 are enabled. Malay, Traditional Chinese and Indonesian are present but disabled. +- **First-pass Chinese for every back-office label (643)**, marked for review by a native speaker. The four old Tastefully rows whose English would change visible portal text are reset to the portal's English. +- **Guard.** A portal test fails when a label has no Chinese, or when its Chinese loses or adds a placeholder. +- **Gateway.** The gateway stops letting message and locale writes through without a user token; only the catalog reads stay open. +- Both modules are granted to no role, so only super admins have them until a super admin grants them. + +## Capabilities + +### New Capabilities + +- `ui-translations`: the message catalog and its version, the language registry, the Translations and Languages screens, their APIs and access, and the Chinese coverage of the back office. + +### Modified Capabilities + +- `admin-visual-design`: the System section of the sidebar lists Translations and Languages. + +## Impact + +- **services-system:** + - `supported_locale` and `catalog_meta` tables; + - locale endpoints; + - message search, a save that refuses code changes and duplicates, and the version bump. +- **mobile-api:** `AdminLocaleController`, `AdminMessageController`, the public locale and catalog-version reads, and audit entries for saves, imports and exports. +- **Gateway:** narrower public paths for `/message/` and `/locale/`. +- **Portal:** + - the `/locales` and `/messages` pages, with the edit panel and the import dialog; + - route handlers under `app/api/locales` and `app/api/messages`; + - `routeModules`, sidebar, messages; + - a Chinese seed file and its guard test. +- **SQL** (in this change folder and mirrored into `local/seed/`): the tables and seeded languages, the two modules, and the Chinese labels. +- **No customer data** is involved. **Security:** the catalog read stays public, because the login page needs labels, and it is label text only; every write needs a session and the module. +- **Design:** `docs/superpowers/specs/2026-12-02-zh-cn-messages-design.md`. **Order:** archive `add-whatsapp-inbox` first, since both change the sidebar requirement. diff --git a/openspec/changes/add-zh-cn-messages/specs/admin-visual-design/spec.md b/openspec/changes/add-zh-cn-messages/specs/admin-visual-design/spec.md new file mode 100644 index 0000000..2669888 --- /dev/null +++ b/openspec/changes/add-zh-cn-messages/specs/admin-visual-design/spec.md @@ -0,0 +1,31 @@ +## MODIFIED Requirements + +### Requirement: Sidebar Sections + +The sidebar SHALL show Dashboard first, then the labelled sections Events, Leads, Access and System, each with a fixed set and order of pages. A page not in any section SHALL appear in a final section without a label. A section SHALL be marked by a divider and a small muted label, with only the divider in the collapsed rail, and SHALL NOT show when it has no page the user may open. Every page SHALL have a distinct icon. + +#### Scenario: WhatsApp inbox in the Leads section + +- **WHEN** a user with `BO_WHATSAPP` and two unread conversations opens the portal +- **THEN** the Leads section lists Leads, WhatsApp and Interests, with a badge showing 2 + +#### Scenario: Super admin sidebar + +- **WHEN** a super admin opens the portal +- **THEN** the sidebar shows Dashboard, then "Events" with Events and Event leads, "Leads" with Leads, WhatsApp and Interests, "Access" with Users, Roles and Login security, and "System" with Companies, Emails, Audit log, Translations and Languages + +#### Scenario: Staff without admin pages + +- **WHEN** a staff user who can open only Events and Event leads opens the portal +- **THEN** the sidebar shows only the "Events" section +- **AND** no "Leads", "Access" or "System" label + +#### Scenario: Unknown page + +- **WHEN** the server menu has a page that is not in the category map +- **THEN** it is listed after the System section, without a label + +#### Scenario: Collapsed rail + +- **WHEN** an admin collapses the sidebar to the icon rail +- **THEN** the sections are separated by dividers and no section label shows diff --git a/openspec/changes/add-zh-cn-messages/specs/ui-translations/spec.md b/openspec/changes/add-zh-cn-messages/specs/ui-translations/spec.md new file mode 100644 index 0000000..b2522fd --- /dev/null +++ b/openspec/changes/add-zh-cn-messages/specs/ui-translations/spec.md @@ -0,0 +1,249 @@ +## ADDED Requirements + +### Requirement: The Portal Shows Labels In The Chosen Language + +The admin portal SHALL show every label in the language the user picked, read from the back-office message catalog. A label with no text in that language SHALL fall back to its English text, then to the portal's built-in English, and never show blank. The catalog read SHALL need no session, because the sign-in page shows labels too, and it SHALL return label text only. + +#### Scenario: Chinese picked + +- **GIVEN** the catalog has Chinese text for the label `Leads` +- **WHEN** a signed-in user picks 简体中文 +- **THEN** the sidebar shows the Chinese text instead of "Leads" + +#### Scenario: A label without Chinese + +- **GIVEN** a label has English text in the catalog and no Chinese text +- **WHEN** a user who picked 简体中文 opens a page with that label +- **THEN** the label shows its English text + +#### Scenario: Catalog unavailable + +- **WHEN** the catalog cannot be read +- **THEN** the portal shows the last catalog it loaded, or its built-in English if it has none +- **AND** no label is blank + +### Requirement: A Wording Change Shows On The Next Page Load + +The system SHALL keep a catalog version that increases with every saved or imported label and every language change, within the same write. The portal SHALL check the version on each page load and reload the catalog when it has changed, on every portal instance, with no fixed waiting time. + +#### Scenario: A label is edited + +- **GIVEN** a user sees a label's Chinese text +- **WHEN** a translator saves new Chinese text for that label +- **THEN** the next page load shows the new text + +#### Scenario: A refused save + +- **WHEN** a label save or language change is refused +- **THEN** the catalog version does not change + +### Requirement: Supported Languages Are Kept In A Registry + +The system SHALL keep the supported languages in a registry, each with a code that matches the catalog's language keys, a label, an enabled flag and an order. It SHALL start with English (`en_US`) and 简体中文 (`zh_CN`) enabled, and Bahasa Melayu (`ms_MY`), 繁體中文 (`zh_TW`) and Bahasa Indonesia (`in_ID`) disabled. The language picker SHALL list only enabled languages in their order, before and after sign-in. If the registry cannot be read, the picker SHALL offer English and 简体中文. + +#### Scenario: Picker after rollout + +- **WHEN** a user opens the language picker +- **THEN** it lists English and 简体中文 only + +#### Scenario: A language is enabled + +- **WHEN** an admin enables Bahasa Melayu on the Languages page +- **THEN** the picker lists it on the next page load, with no redeploy + +#### Scenario: Registry unavailable + +- **WHEN** the language list cannot be read +- **THEN** the picker lists English and 简体中文 + +### Requirement: A Language Change Cannot Break The Registry + +The system SHALL refuse: +- a new language whose code already exists; +- a change of a language's code; +- switching English off; +- switching off the last enabled language. + +Each refusal SHALL leave the registry unchanged and SHALL reach the user as a named reason, not a generic error. + +#### Scenario: Duplicate code + +- **WHEN** an admin adds a language with the code `zh_CN` +- **THEN** it is refused and the page says the code already exists + +#### Scenario: English cannot be switched off + +- **WHEN** the Languages page lists English +- **THEN** its switch is disabled and the page says why +- **AND** a direct request to disable English is refused + +#### Scenario: Last enabled language + +- **GIVEN** only one language is enabled +- **WHEN** a request disables it +- **THEN** it is refused + +### Requirement: The Languages Page + +The portal SHALL provide a Languages page at `/locales` that lists every language with its code, label, order and an enabled switch. It SHALL let the user add a language and edit a label and order. The code SHALL be editable only when adding. Switching a language off SHALL ask for confirmation first. Refusals SHALL show on the page. + +#### Scenario: Switching a language off asks first + +- **WHEN** a user switches 简体中文 off +- **THEN** a confirmation is shown +- **AND** nothing changes unless the user confirms + +#### Scenario: Code read-only when editing + +- **WHEN** a user edits an existing language +- **THEN** its code is shown read-only + +### Requirement: The Translations Page Lists And Finds Back-Office Labels + +The portal SHALL provide a Translations page at `/messages` listing the back-office labels in pages, each with its code, English text and Chinese text. The search SHALL match the code, the English text or the Chinese text, ignoring case. A "Missing Chinese" filter SHALL list labels whose Chinese text is absent, blank or the same as the English text. Each such label SHALL be marked with a text badge, not colour alone. The page SHALL offer no way to add or delete a label. + +#### Scenario: Search by Chinese wording + +- **GIVEN** a label whose Chinese text contains "线索" +- **WHEN** the user searches "线索" +- **THEN** that label is listed + +#### Scenario: Copied English counts as missing + +- **GIVEN** a label whose English and Chinese text are both "WhatsApp" +- **WHEN** the user turns on "Missing Chinese" +- **THEN** that label is listed with a badge that says why + +#### Scenario: No add or delete + +- **WHEN** the Translations page and its row actions are inspected +- **THEN** there is no add and no delete action + +### Requirement: Editing A Translation + +Opening a label SHALL show an edit panel with one multi-line field per enabled language and the code read-only. Closing it with unsaved changes SHALL ask before discarding them. The server SHALL refuse a save that changes a label's code, or that creates a label whose code already exists ignoring case. Label text SHALL always be shown as text, never as markup. + +#### Scenario: Unsaved edits + +- **WHEN** the user changes a field and closes the panel +- **THEN** the panel asks before discarding the change + +#### Scenario: Code change refused + +- **WHEN** a save request changes an existing label's code +- **THEN** it is refused and the label is unchanged + +#### Scenario: Markup is shown as text + +- **GIVEN** a translator saves `Leads` as a label's Chinese text +- **WHEN** a page shows that label +- **THEN** the angle brackets show as text and nothing is bold + +### Requirement: Placeholders Are Kept In Translations + +Each non-English text SHALL keep the same placeholders as the English text, in the `{name}` and `{0}` forms. When an edit creates a mismatch, the edit panel SHALL name the missing or extra placeholders and block Save. When the label was mismatched before the edit, it SHALL warn without blocking. + +#### Scenario: A new placeholder mismatch blocks Save + +- **GIVEN** a label whose English is "{n} unread" and Chinese is "{n} 条未读" +- **WHEN** the user changes the Chinese to "条未读" +- **THEN** the panel names `{n}` as missing +- **AND** Save is disabled + +#### Scenario: An old mismatch only warns + +- **GIVEN** a label whose English is "{n} unread" and Chinese is "未读" +- **WHEN** the user edits the English +- **THEN** the panel warns that `{n}` is missing in Chinese +- **AND** Save stays enabled + +### Requirement: Translations Export + +The Translations page SHALL export every back-office label, with the text in every language, as a JSON file download, without leaving the page. + +#### Scenario: Export downloads + +- **WHEN** the user clicks Export +- **THEN** the browser offers a JSON file with every back-office label +- **AND** the page stays on `/messages` + +### Requirement: Translations Import With A Preview + +The Translations page SHALL import a file in the export shape. It SHALL first show a preview that marks each row as an update, matched by code ignoring case and never by an id in the file, or as a new label. It SHALL apply nothing until the user confirms. A file that is not a JSON list SHALL be rejected on the page without sending anything. Each row SHALL be saved on its own, and a summary SHALL show the counts created and updated and name the failed rows. + +#### Scenario: Preview before import + +- **WHEN** the user picks an export file +- **THEN** the page lists every row as an update or a new label +- **AND** nothing is saved until the user confirms + +#### Scenario: Matched by code + +- **GIVEN** a file row with code `leads` and the id of another label +- **AND** the catalog holds the label `Leads` +- **WHEN** the file is imported +- **THEN** the `Leads` label is updated + +#### Scenario: Not a list + +- **WHEN** the user picks a file that is not a JSON list +- **THEN** the page shows an error and sends nothing + +#### Scenario: One bad row + +- **WHEN** an import has one row that fails and others that succeed +- **THEN** the other rows are saved +- **AND** the summary names the failed row + +### Requirement: Access To Translations And Languages + +The Translations page SHALL require `BO_MESSAGES` and the Languages page `BO_LOCALES`, checked on the server for every list, detail, export and write, with a signed-in admin. Both modules SHALL be granted to no role, so only super admins have them until a super admin grants them. Saves, imports, exports and language changes SHALL be audited. + +#### Scenario: Without the module + +- **WHEN** a staff user without `BO_MESSAGES` opens `/messages` +- **THEN** the not-authorised page is shown +- **AND** a direct save request is refused + +#### Scenario: A save is audited + +- **WHEN** a super admin saves a translation +- **THEN** the audit log records who saved which label + +### Requirement: Internal Catalog Writes Need A Token + +Inside the system, message and language writes and full listings SHALL need a user token. Only the catalog, its version and the enabled-language list SHALL be readable without one. + +#### Scenario: Internal write without a token + +- **WHEN** a request without a user token tries to save a message or language inside the system +- **THEN** it is refused + +#### Scenario: Catalog read without a token + +- **WHEN** the sign-in page loads the catalog without a session +- **THEN** the catalog is returned + +### Requirement: Every Back-Office Label Has Chinese + +Every back-office label SHALL have Simplified Chinese text with the same placeholders as its English, using one consistent glossary, as a first pass for a native speaker to review. Every new back-office label SHALL ship with its Chinese text. + +#### Scenario: Back office in Chinese + +- **WHEN** a user picks 简体中文 and opens any back-office page +- **THEN** every label on it shows Chinese text + +#### Scenario: A new label without Chinese + +- **WHEN** a developer adds a back-office label with no Chinese text +- **THEN** the portal's tests fail and name the label + +### Requirement: Loading The Chinese Keeps English Unchanged + +Loading the Chinese SHALL replace earlier Chinese for the back-office labels, leave other languages unchanged, and add missing labels with their English. It SHALL reset the English of any label whose old database text differs from the portal's English, so nobody who keeps English sees a change. + +#### Scenario: English unchanged + +- **GIVEN** the old database English for the sign-in button is "Login" +- **WHEN** the Chinese is loaded and a user who keeps English opens the sign-in page +- **THEN** the button reads "Log in" diff --git a/openspec/changes/add-zh-cn-messages/tasks.md b/openspec/changes/add-zh-cn-messages/tasks.md new file mode 100644 index 0000000..c734daf --- /dev/null +++ b/openspec/changes/add-zh-cn-messages/tasks.md @@ -0,0 +1,71 @@ +# Tasks: add-zh-cn-messages + +Design: `design.md` and `docs/superpowers/specs/2026-12-02-zh-cn-messages-design.md`. Every task is TDD: list the babyboo rules it ports, turn them into failing tests, then build. The owner said no workers (2026-12-02), so everything runs serially in the main session with a self-review per task. + +Verify commands: +- **Backend:** `mvn -T 1C -B -q -pl -am verify`. +- **Portal:** `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint` (check the vitest exit code). + +## 1. Data + +- [ ] 1.1 SQL: `sql/01-locales.sql` (`supported_locale` with the five languages, English and 简体中文 enabled; `catalog_meta` at version 0), `sql/02-modules.sql` (`BO_MESSAGES`, `BO_LOCALES` under System, no role) and `sql/99-rollback.sql`. Append `01` and `02` to `local/seed/03-colite.sql`. + - Verify: load the seed into a throwaway local MySQL volume and list the tables and modules. + +## 2. services-system + +- [ ] 2.1 Language registry: entity, repository, service and `/locale/*` controller, with the duplicate, code-locked, English-locked and last-enabled refusals, and the catalog version bump on save and update. + - Verify: `mvn -T 1C -B -q -pl solvway-services-system -am verify` +- [ ] 2.2 Messages: + - `catalog_meta` with `/message/catalogVersion`; + - `/message/search` (searchKey over code, `en_US`, `zh_CN`; missingLocale; area; paging); + - save refusals (`MsgsCodeAreaLocked`, `MsgsDuplicateCode`); + - the version bump on every save and none on a refusal. + - Verify: as 2.1. + +## 3. Gateway + +- [ ] 3.1 Narrow the token bypass from any `/message/` URL to the exact read paths in use (grep the callers first), plus `/locale/findAllEnabled`. Tests cover open reads and token-gated writes. Security code: read the whole diff. + - Verify: `mvn -T 1C -B -q -pl solvway-api-gateway -am verify` + +## 4. mobile-api + +- [ ] 4.1 `AdminLocaleController` and the public `/api/public/locales`. Refusals pass through as 409 with the reason; locale writes are audited. +- [ ] 4.2 `AdminMessageController`: catalog and catalog-version (API key, no session); list and search; detail; `PUT` (the path id wins); export (audited as a sensitive read); import (match by code ignoring case, per-row summary, audited); module `BO_MESSAGES`; no create and no delete mapping. + - Verify (4.1 and 4.2): `mvn -T 1C -B -q -pl solvway-mobile-api -am verify` + +## 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`: + - list with code, English and Chinese; + - search, the Missing Chinese filter and its badge; + - the edit panel: placeholder checks, unsaved guard, code read-only; + - export download, and import with preview and summary; + - no add or delete. + - Verify (5.1 to 5.3): portal verify. + +## 6. Chinese + +- [ ] 6.1 `zh_CN.seed.json` for every `defaultMessages.ts` key, following the glossary in design decision 7. Guard tests: full coverage, equal placeholders, no extra keys. +- [ ] 6.2 Generator `npm run i18n:sql` writing `sql/03-zh-cn-messages.sql`. It upserts zh_CN, inserts missing rows with English, aligns the four English rows and bumps the version. A test checks the committed SQL matches the generator. Mirror it into `local/seed/04-zh-cn-messages.sql`. + - Verify: portal verify, then apply the SQL to the local DB and confirm the catalog endpoint returns Chinese for a sample of keys. + +## 7. Release + +- [ ] 7.1 `docs/deployment.md`: the SQL order, the modules, the first-pass note for the native-speaker review, and the gateway narrowing. +- [ ] 7.2 Live Playwright check on the local stack, at 1280 and 360 px: + - switch to 简体中文 and walk every sidebar page; + - English unchanged after sign-in ("Log in"); + - edit a translation and see it on the next load; + - a placeholder mismatch blocks Save; + - Missing Chinese filter; + - export, then import with the preview; + - Languages: the English switch is disabled, switching 简体中文 off asks first (cancel); + - a user without the modules gets the not-authorised page. +- [ ] 7.3 Whole-branch self-review, then the PR to main and the merge. + +## Workflow follow-up + +- Archive after `add-whatsapp-inbox` is archived, since both modify the sidebar requirement. +- Tell the owner the Chinese is ready for the native-speaker review, and which screen to use. From 075a3a34d11f01f63eb4378ac14c645a21b62ac5 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 12:37:08 +0800 Subject: [PATCH 03/15] feat: language registry, catalog version and translation modules (SQL) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs --- local/seed/03-colite.sql | 31 +++++++++++++++++++ .../add-zh-cn-messages/sql/01-locales.sql | 29 +++++++++++++++++ .../add-zh-cn-messages/sql/02-modules.sql | 7 +++++ .../add-zh-cn-messages/sql/99-rollback.sql | 6 ++++ openspec/changes/add-zh-cn-messages/tasks.md | 2 +- 5 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 openspec/changes/add-zh-cn-messages/sql/01-locales.sql create mode 100644 openspec/changes/add-zh-cn-messages/sql/02-modules.sql create mode 100644 openspec/changes/add-zh-cn-messages/sql/99-rollback.sql diff --git a/local/seed/03-colite.sql b/local/seed/03-colite.sql index 98a43a9..f100394 100644 --- a/local/seed/03-colite.sql +++ b/local/seed/03-colite.sql @@ -428,3 +428,34 @@ USE `service-system`; INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES (41200000, 'BO_WHATSAPP', 'WhatsApp', 'BO', 'M', 40000000, '/whatsapp', 'MessageCircle'), (41300000, 'BO_WHATSAPP_ADMIN', 'WhatsApp admin', 'BO', 'M', 40000000, NULL, NULL); + +-- add-zh-cn-messages: language registry, catalog version, Translations and Languages modules +SET NAMES utf8mb4; +USE `service-system`; +CREATE TABLE `supported_locale` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `code` varchar(35) NOT NULL COMMENT 'Matches the language keys of message.content', + `label` varchar(100) NOT NULL, + `enabled` tinyint(1) NOT NULL DEFAULT 1, + `sort_order` int NOT NULL DEFAULT 0, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_supported_locale_code` (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +INSERT INTO `supported_locale` (`code`, `label`, `enabled`, `sort_order`) VALUES + ('en_US', 'English', 1, 1), + ('zh_CN', '简体中文', 1, 2), + ('ms_MY', 'Bahasa Melayu', 0, 3), + ('zh_TW', '繁體中文', 0, 4), + ('in_ID', 'Bahasa Indonesia', 0, 5); +CREATE TABLE `catalog_meta` ( + `id` bigint NOT NULL, + `version` bigint NOT NULL DEFAULT 0, + `updated_at` datetime NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +INSERT INTO `catalog_meta` (`id`, `version`, `updated_at`) VALUES (1, 0, NOW()); + +USE `service-system`; +INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES + (41400000, 'BO_MESSAGES', 'Translations', 'BO', 'M', 40000000, '/messages', 'Languages'), + (41500000, 'BO_LOCALES', 'Languages', 'BO', 'M', 40000000, '/locales', 'Globe'); diff --git a/openspec/changes/add-zh-cn-messages/sql/01-locales.sql b/openspec/changes/add-zh-cn-messages/sql/01-locales.sql new file mode 100644 index 0000000..9b9c4ab --- /dev/null +++ b/openspec/changes/add-zh-cn-messages/sql/01-locales.sql @@ -0,0 +1,29 @@ +-- Co-Lite change add-zh-cn-messages: the language registry and the catalog version (ported from babyboo add-admin-locale-management). +-- Target: `service-system`. Additive only. Run once, before the new services-system starts. +-- DDL: run with a user that may create tables, not the services' user. +SET NAMES utf8mb4; +USE `service-system`; +CREATE TABLE `supported_locale` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `code` varchar(35) NOT NULL COMMENT 'Matches the language keys of message.content', + `label` varchar(100) NOT NULL, + `enabled` tinyint(1) NOT NULL DEFAULT 1, + `sort_order` int NOT NULL DEFAULT 0, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_supported_locale_code` (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +-- English and Simplified Chinese are in use; the others keep their existing catalog text but stay out of the picker. +INSERT INTO `supported_locale` (`code`, `label`, `enabled`, `sort_order`) VALUES + ('en_US', 'English', 1, 1), + ('zh_CN', '简体中文', 1, 2), + ('ms_MY', 'Bahasa Melayu', 0, 3), + ('zh_TW', '繁體中文', 0, 4), + ('in_ID', 'Bahasa Indonesia', 0, 5); +-- One row. Every message or language write bumps `version`; the portal reloads its catalog when it changes. +CREATE TABLE `catalog_meta` ( + `id` bigint NOT NULL, + `version` bigint NOT NULL DEFAULT 0, + `updated_at` datetime NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; +INSERT INTO `catalog_meta` (`id`, `version`, `updated_at`) VALUES (1, 0, NOW()); diff --git a/openspec/changes/add-zh-cn-messages/sql/02-modules.sql b/openspec/changes/add-zh-cn-messages/sql/02-modules.sql new file mode 100644 index 0000000..60f48b6 --- /dev/null +++ b/openspec/changes/add-zh-cn-messages/sql/02-modules.sql @@ -0,0 +1,7 @@ +-- Co-Lite change add-zh-cn-messages: the Translations and Languages back-office modules (area BO). +-- Target: `service-system`.`module`. Additive only. Run once. +-- No role grant: super admins see every module; translations are shared by every company, so a super admin grants them only to a translator's role. +USE `service-system`; +INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES + (41400000, 'BO_MESSAGES', 'Translations', 'BO', 'M', 40000000, '/messages', 'Languages'), + (41500000, 'BO_LOCALES', 'Languages', 'BO', 'M', 40000000, '/locales', 'Globe'); diff --git a/openspec/changes/add-zh-cn-messages/sql/99-rollback.sql b/openspec/changes/add-zh-cn-messages/sql/99-rollback.sql new file mode 100644 index 0000000..585c154 --- /dev/null +++ b/openspec/changes/add-zh-cn-messages/sql/99-rollback.sql @@ -0,0 +1,6 @@ +-- Co-Lite change add-zh-cn-messages: rollback of 01-02. The Chinese text loaded by 03 stays in `message`; the previous images never read it. +USE `service-system`; +DELETE FROM `modules_roles` WHERE `module_id` IN (41400000, 41500000); +DELETE FROM `module` WHERE `id` IN (41400000, 41500000); +DROP TABLE IF EXISTS `catalog_meta`; +DROP TABLE IF EXISTS `supported_locale`; diff --git a/openspec/changes/add-zh-cn-messages/tasks.md b/openspec/changes/add-zh-cn-messages/tasks.md index c734daf..57e72e2 100644 --- a/openspec/changes/add-zh-cn-messages/tasks.md +++ b/openspec/changes/add-zh-cn-messages/tasks.md @@ -8,7 +8,7 @@ Verify commands: ## 1. Data -- [ ] 1.1 SQL: `sql/01-locales.sql` (`supported_locale` with the five languages, English and 简体中文 enabled; `catalog_meta` at version 0), `sql/02-modules.sql` (`BO_MESSAGES`, `BO_LOCALES` under System, no role) and `sql/99-rollback.sql`. Append `01` and `02` to `local/seed/03-colite.sql`. +- [x] 1.1 SQL: `sql/01-locales.sql` (`supported_locale` with the five languages, English and 简体中文 enabled; `catalog_meta` at version 0), `sql/02-modules.sql` (`BO_MESSAGES`, `BO_LOCALES` under System, no role) and `sql/99-rollback.sql`. Append `01` and `02` to `local/seed/03-colite.sql`. - Verify: load the seed into a throwaway local MySQL volume and list the tables and modules. ## 2. services-system From 4622a5219db4251649c8d22e2412f2145ad723b2 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 12:40:15 +0800 Subject: [PATCH 04/15] feat(system): language registry with guarded updates and a catalog version Ported from babyboo locale-registry: a duplicate code, a code change, switching English off and switching off the last enabled language are refused as 409s with a message code; every accepted change bumps the catalog version. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs --- openspec/changes/add-zh-cn-messages/tasks.md | 2 +- .../controller/SupportedLocaleController.java | 42 ++++++ .../services/system/model/CatalogMeta.java | 19 +++ .../system/model/SupportedLocale.java | 20 +++ .../system/repo/CatalogMetaRepository.java | 13 ++ .../repo/SupportedLocaleRepository.java | 15 ++ .../system/service/CatalogVersionService.java | 23 +++ .../service/SupportedLocaleService.java | 87 +++++++++++ .../service/SupportedLocaleServiceTest.java | 139 ++++++++++++++++++ 9 files changed, 359 insertions(+), 1 deletion(-) create mode 100644 solvway-services-system/src/main/java/com/solvway/services/system/controller/SupportedLocaleController.java create mode 100644 solvway-services-system/src/main/java/com/solvway/services/system/model/CatalogMeta.java create mode 100644 solvway-services-system/src/main/java/com/solvway/services/system/model/SupportedLocale.java create mode 100644 solvway-services-system/src/main/java/com/solvway/services/system/repo/CatalogMetaRepository.java create mode 100644 solvway-services-system/src/main/java/com/solvway/services/system/repo/SupportedLocaleRepository.java create mode 100644 solvway-services-system/src/main/java/com/solvway/services/system/service/CatalogVersionService.java create mode 100644 solvway-services-system/src/main/java/com/solvway/services/system/service/SupportedLocaleService.java create mode 100644 solvway-services-system/src/test/java/com/solvway/services/system/service/SupportedLocaleServiceTest.java diff --git a/openspec/changes/add-zh-cn-messages/tasks.md b/openspec/changes/add-zh-cn-messages/tasks.md index 57e72e2..d87c9ba 100644 --- a/openspec/changes/add-zh-cn-messages/tasks.md +++ b/openspec/changes/add-zh-cn-messages/tasks.md @@ -13,7 +13,7 @@ Verify commands: ## 2. services-system -- [ ] 2.1 Language registry: entity, repository, service and `/locale/*` controller, with the duplicate, code-locked, English-locked and last-enabled refusals, and the catalog version bump on save and update. +- [x] 2.1 Language registry: entity, repository, service and `/locale/*` controller, with the duplicate, code-locked, English-locked and last-enabled refusals, and the catalog version bump on save and update. - Verify: `mvn -T 1C -B -q -pl solvway-services-system -am verify` - [ ] 2.2 Messages: - `catalog_meta` with `/message/catalogVersion`; diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/controller/SupportedLocaleController.java b/solvway-services-system/src/main/java/com/solvway/services/system/controller/SupportedLocaleController.java new file mode 100644 index 0000000..5f2ab36 --- /dev/null +++ b/solvway-services-system/src/main/java/com/solvway/services/system/controller/SupportedLocaleController.java @@ -0,0 +1,42 @@ +package com.solvway.services.system.controller; + +import com.solvway.services.system.model.SupportedLocale; +import com.solvway.services.system.service.SupportedLocaleService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Optional; + +/** Language registry. Only findAllEnabled is readable without a user token (gateway). */ +@RestController +@RequestMapping("/locale") +@RequiredArgsConstructor +public class SupportedLocaleController { + private final SupportedLocaleService service; + + @GetMapping("/findAll") + public List findAll() { + return service.findAll(); + } + + @GetMapping("/findAllEnabled") + public List findAllEnabled() { + return service.findAllEnabled(); + } + + @GetMapping("/findById/{id}") + public Optional findById(@PathVariable Long id) { + return service.findById(id); + } + + @PostMapping("/save") + public SupportedLocale save(@RequestBody SupportedLocale bean) { + return service.save(bean); + } + + @PostMapping("/update") + public SupportedLocale update(@RequestBody SupportedLocale bean) { + return service.update(bean); + } +} diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/model/CatalogMeta.java b/solvway-services-system/src/main/java/com/solvway/services/system/model/CatalogMeta.java new file mode 100644 index 0000000..db1eaca --- /dev/null +++ b/solvway-services-system/src/main/java/com/solvway/services/system/model/CatalogMeta.java @@ -0,0 +1,19 @@ +package com.solvway.services.system.model; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +/** The single row (id 1) holding the catalog version; created by SQL, only ever incremented here. */ +@Entity +@Table(name = "catalog_meta") +@Getter +@Setter +public class CatalogMeta { + @Id + private Long id; + private Long version; + private LocalDateTime updatedAt; +} diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/model/SupportedLocale.java b/solvway-services-system/src/main/java/com/solvway/services/system/model/SupportedLocale.java new file mode 100644 index 0000000..2443c4e --- /dev/null +++ b/solvway-services-system/src/main/java/com/solvway/services/system/model/SupportedLocale.java @@ -0,0 +1,20 @@ +package com.solvway.services.system.model; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; + +/** A UI language. {@code code} matches the language keys of message.content and is unique; disabled languages stay out of the picker. */ +@Entity +@Table(name = "supported_locale") +@Getter +@Setter +public class SupportedLocale { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String code; + private String label; + private Boolean enabled; + private Integer sortOrder; +} diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/repo/CatalogMetaRepository.java b/solvway-services-system/src/main/java/com/solvway/services/system/repo/CatalogMetaRepository.java new file mode 100644 index 0000000..5d71ef8 --- /dev/null +++ b/solvway-services-system/src/main/java/com/solvway/services/system/repo/CatalogMetaRepository.java @@ -0,0 +1,13 @@ +package com.solvway.services.system.repo; + +import com.solvway.services.system.model.CatalogMeta; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; + +public interface CatalogMetaRepository extends JpaRepository { + /** Atomic increment inside the caller's write transaction, so no reader sees a change without a new version. */ + @Modifying + @Query(value = "UPDATE catalog_meta SET version = version + 1, updated_at = NOW() WHERE id = 1", nativeQuery = true) + int bumpVersion(); +} diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/repo/SupportedLocaleRepository.java b/solvway-services-system/src/main/java/com/solvway/services/system/repo/SupportedLocaleRepository.java new file mode 100644 index 0000000..5151cb1 --- /dev/null +++ b/solvway-services-system/src/main/java/com/solvway/services/system/repo/SupportedLocaleRepository.java @@ -0,0 +1,15 @@ +package com.solvway.services.system.repo; + +import com.solvway.services.system.model.SupportedLocale; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; +import java.util.Optional; + +public interface SupportedLocaleRepository extends JpaRepository { + Optional findByCode(String code); + + List findByEnabledTrueOrderBySortOrderAsc(); + + List findAllByOrderBySortOrderAsc(); +} diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/service/CatalogVersionService.java b/solvway-services-system/src/main/java/com/solvway/services/system/service/CatalogVersionService.java new file mode 100644 index 0000000..7046b42 --- /dev/null +++ b/solvway-services-system/src/main/java/com/solvway/services/system/service/CatalogVersionService.java @@ -0,0 +1,23 @@ +package com.solvway.services.system.service; + +import com.solvway.services.system.model.CatalogMeta; +import com.solvway.services.system.repo.CatalogMetaRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** The catalog version the portals key their catalog cache on. Every message or language write bumps it in its own transaction. */ +@Service +@RequiredArgsConstructor +public class CatalogVersionService { + private final CatalogMetaRepository repository; + + public long current() { + return repository.findById(1L).map(CatalogMeta::getVersion).orElse(0L); + } + + @Transactional + public void bump() { + repository.bumpVersion(); + } +} diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/service/SupportedLocaleService.java b/solvway-services-system/src/main/java/com/solvway/services/system/service/SupportedLocaleService.java new file mode 100644 index 0000000..5f1f2b5 --- /dev/null +++ b/solvway-services-system/src/main/java/com/solvway/services/system/service/SupportedLocaleService.java @@ -0,0 +1,87 @@ +package com.solvway.services.system.service; + +import com.solvway.services.system.model.SupportedLocale; +import com.solvway.services.system.repo.SupportedLocaleRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.server.ResponseStatusException; + +import java.util.List; +import java.util.Optional; + +/** + * The language registry (ported from babyboo locale-registry). Refusals are 409s whose reason is a UI message code: + * a duplicate code, a code change, switching English off, switching off the last enabled language. A refusal + * changes nothing and does not bump the catalog version. + */ +@Service +@RequiredArgsConstructor +public class SupportedLocaleService { + private static final String FALLBACK = "en_US"; + + private final SupportedLocaleRepository repository; + private final CatalogVersionService catalogVersion; + + public List findAll() { + return repository.findAllByOrderBySortOrderAsc(); + } + + public List findAllEnabled() { + return repository.findByEnabledTrueOrderBySortOrderAsc(); + } + + public Optional findById(Long id) { + return repository.findById(id); + } + + @Transactional + public SupportedLocale save(SupportedLocale bean) { + if (repository.findByCode(bean.getCode()).isPresent()) { + throw refused("LocalesDuplicateCode"); + } + bean.setId(null); + SupportedLocale saved = persist(bean); + catalogVersion.bump(); + return saved; + } + + /** Applies label, order and enabled; a field the body leaves out keeps its stored value. */ + @Transactional + public SupportedLocale update(SupportedLocale bean) { + SupportedLocale stored = (bean.getId() == null ? Optional.empty() : repository.findById(bean.getId())) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "LocaleNotFound")); + if (bean.getCode() != null && !bean.getCode().equals(stored.getCode())) { + throw refused("LocalesCodeLocked"); + } + if (Boolean.FALSE.equals(bean.getEnabled()) && Boolean.TRUE.equals(stored.getEnabled())) { + if (FALLBACK.equals(stored.getCode())) { + throw refused("LocalesFallbackLocked"); + } + if (repository.findByEnabledTrueOrderBySortOrderAsc().size() <= 1) { + throw refused("LocalesLastEnabledLocked"); + } + } + if (bean.getLabel() != null) stored.setLabel(bean.getLabel()); + if (bean.getEnabled() != null) stored.setEnabled(bean.getEnabled()); + if (bean.getSortOrder() != null) stored.setSortOrder(bean.getSortOrder()); + SupportedLocale saved = persist(stored); + catalogVersion.bump(); + return saved; + } + + private SupportedLocale persist(SupportedLocale l) { + try { + return repository.save(l); + } catch (DataIntegrityViolationException e) { + // Two creates raced past the pre-check; the unique key caught the loser. + throw refused("LocalesDuplicateCode"); + } + } + + private static ResponseStatusException refused(String reason) { + return new ResponseStatusException(HttpStatus.CONFLICT, reason); + } +} diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/service/SupportedLocaleServiceTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/service/SupportedLocaleServiceTest.java new file mode 100644 index 0000000..6afea50 --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/service/SupportedLocaleServiceTest.java @@ -0,0 +1,139 @@ +package com.solvway.services.system.service; + +import com.solvway.services.system.model.SupportedLocale; +import com.solvway.services.system.repo.SupportedLocaleRepository; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Language registry rules ported from babyboo locale-registry: duplicates, locked code, English and last enabled, version bump. */ +@ExtendWith(MockitoExtension.class) +class SupportedLocaleServiceTest { + + @Mock + private SupportedLocaleRepository repository; + @Mock + private CatalogVersionService catalogVersion; + @InjectMocks + private SupportedLocaleService service; + + @Test + void enabledListComesInOrder() { + List enabled = List.of(locale(1L, "en_US", true), locale(2L, "zh_CN", true)); + when(repository.findByEnabledTrueOrderBySortOrderAsc()).thenReturn(enabled); + + assertThat(service.findAllEnabled()).isEqualTo(enabled); + } + + @Test + void addingANewCodeSavesAndBumpsTheVersion() { + SupportedLocale ms = locale(null, "ms_MY", false); + when(repository.findByCode("ms_MY")).thenReturn(Optional.empty()); + when(repository.save(ms)).thenReturn(ms); + + assertThat(service.save(ms)).isSameAs(ms); + verify(catalogVersion).bump(); + } + + @Test + void addingAnExistingCodeIsRefusedWithoutABump() { + when(repository.findByCode("zh_CN")).thenReturn(Optional.of(locale(2L, "zh_CN", true))); + + assertRefused(() -> service.save(locale(null, "zh_CN", true)), "LocalesDuplicateCode"); + verify(repository, never()).save(any()); + verify(catalogVersion, never()).bump(); + } + + @Test + void aRaceOnTheUniqueKeyIsStillADuplicate() { + SupportedLocale ms = locale(null, "ms_MY", true); + when(repository.findByCode("ms_MY")).thenReturn(Optional.empty()); + when(repository.save(ms)).thenThrow(new DataIntegrityViolationException("uk_supported_locale_code")); + + assertRefused(() -> service.save(ms), "LocalesDuplicateCode"); + verify(catalogVersion, never()).bump(); + } + + @Test + void renamingACodeIsRefused() { + when(repository.findById(2L)).thenReturn(Optional.of(locale(2L, "zh_CN", true))); + + assertRefused(() -> service.update(locale(2L, "zh_TW", true)), "LocalesCodeLocked"); + verify(repository, never()).save(any()); + verify(catalogVersion, never()).bump(); + } + + @Test + void switchingEnglishOffIsRefused() { + when(repository.findById(1L)).thenReturn(Optional.of(locale(1L, "en_US", true))); + + assertRefused(() -> service.update(locale(1L, "en_US", false)), "LocalesFallbackLocked"); + verify(catalogVersion, never()).bump(); + } + + @Test + void switchingOffTheLastEnabledLanguageIsRefused() { + when(repository.findById(2L)).thenReturn(Optional.of(locale(2L, "zh_CN", true))); + when(repository.findByEnabledTrueOrderBySortOrderAsc()).thenReturn(List.of(locale(2L, "zh_CN", true))); + + assertRefused(() -> service.update(locale(2L, "zh_CN", false)), "LocalesLastEnabledLocked"); + } + + @Test + void updateKeepsFieldsTheBodyLeavesOutAndBumps() { + SupportedLocale stored = locale(3L, "ms_MY", false); + stored.setLabel("Bahasa Melayu"); + stored.setSortOrder(3); + when(repository.findById(3L)).thenReturn(Optional.of(stored)); + when(repository.save(stored)).thenReturn(stored); + SupportedLocale body = new SupportedLocale(); + body.setId(3L); + body.setEnabled(true); + + SupportedLocale saved = service.update(body); + + assertThat(saved.getCode()).isEqualTo("ms_MY"); + assertThat(saved.getLabel()).isEqualTo("Bahasa Melayu"); + assertThat(saved.getSortOrder()).isEqualTo(3); + assertThat(saved.getEnabled()).isTrue(); + verify(catalogVersion).bump(); + } + + @Test + void updatingAnUnknownIdIsNotFound() { + when(repository.findById(9L)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.update(locale(9L, "xx", true))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + } + + private static void assertRefused(Runnable call, String reason) { + assertThatThrownBy(call::run).isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(e.getReason()).isEqualTo(reason); + }); + } + + private static SupportedLocale locale(Long id, String code, boolean enabled) { + SupportedLocale l = new SupportedLocale(); + l.setId(id); + l.setCode(code); + l.setEnabled(enabled); + return l; + } +} From ebfee582c29cde5517c82c2b39b8bd2ed0b84196 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 12:42:59 +0800 Subject: [PATCH 05/15] feat(system): message search, guarded saves and the catalog version read Ported from babyboo message-admin-api: search over the code, English and Chinese text; a missing-Chinese filter; a save that refuses a code change or a duplicate code (409, no longer swallowed) and bumps the catalog version. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs --- openspec/changes/add-zh-cn-messages/tasks.md | 2 +- .../system/controller/MessageController.java | 25 ++- .../system/model/MessageSearchRequest.java | 16 ++ .../system/service/MessageService.java | 80 ++++++++- .../MessageServiceTranslationsTest.java | 154 ++++++++++++++++++ 5 files changed, 268 insertions(+), 9 deletions(-) create mode 100644 solvway-services-system/src/main/java/com/solvway/services/system/model/MessageSearchRequest.java create mode 100644 solvway-services-system/src/test/java/com/solvway/services/system/service/MessageServiceTranslationsTest.java diff --git a/openspec/changes/add-zh-cn-messages/tasks.md b/openspec/changes/add-zh-cn-messages/tasks.md index d87c9ba..7a6c599 100644 --- a/openspec/changes/add-zh-cn-messages/tasks.md +++ b/openspec/changes/add-zh-cn-messages/tasks.md @@ -15,7 +15,7 @@ Verify commands: - [x] 2.1 Language registry: entity, repository, service and `/locale/*` controller, with the duplicate, code-locked, English-locked and last-enabled refusals, and the catalog version bump on save and update. - Verify: `mvn -T 1C -B -q -pl solvway-services-system -am verify` -- [ ] 2.2 Messages: +- [x] 2.2 Messages: - `catalog_meta` with `/message/catalogVersion`; - `/message/search` (searchKey over code, `en_US`, `zh_CN`; missingLocale; area; paging); - save refusals (`MsgsCodeAreaLocked`, `MsgsDuplicateCode`); diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/controller/MessageController.java b/solvway-services-system/src/main/java/com/solvway/services/system/controller/MessageController.java index 035b963..8e431cf 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/controller/MessageController.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/controller/MessageController.java @@ -3,6 +3,8 @@ package com.solvway.services.system.controller; import com.solvway.core.utils.StackTraceUtil; import com.solvway.services.system.constant.SystemConstants.Area; import com.solvway.services.system.model.Message; +import com.solvway.services.system.model.MessageSearchRequest; +import com.solvway.services.system.service.CatalogVersionService; import com.solvway.services.system.service.MessageService; import com.solvway.services.system.util.paging.PageableRest; import org.modelmapper.ModelMapper; @@ -32,6 +34,9 @@ public class MessageController { @Autowired private MessageService messageService; + + @Autowired + private CatalogVersionService catalogVersion; @Autowired ModelMapper modelMapper; @@ -69,15 +74,21 @@ public class MessageController { return messageService.findByCodeContaining(searchKey, pageable); } + /** Refusals (MsgsCodeAreaLocked, MsgsDuplicateCode) reach the caller as 409s; nothing is swallowed. */ @RequestMapping("/save") public void save(@RequestBody Message message) { - try { - messageService.save(message); - }catch(Exception ignore){ - //return false; - } - - //return true; + messageService.save(message); + } + + @RequestMapping("/search") + public Page search(@RequestBody MessageSearchRequest req) { + return messageService.search(req); + } + + /** The catalog version the portals key their cache on; a read, never a bump. */ + @RequestMapping("/catalogVersion") + public Map catalogVersion() { + return Map.of("version", catalogVersion.current()); } @RequestMapping("/findById/{id}") diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/model/MessageSearchRequest.java b/solvway-services-system/src/main/java/com/solvway/services/system/model/MessageSearchRequest.java new file mode 100644 index 0000000..acd2583 --- /dev/null +++ b/solvway-services-system/src/main/java/com/solvway/services/system/model/MessageSearchRequest.java @@ -0,0 +1,16 @@ +package com.solvway.services.system.model; + +import com.solvway.services.system.constant.SystemConstants.Area; +import lombok.Getter; +import lombok.Setter; + +/** Translations search: searchKey over the code, English and Chinese text; missingLocale lists labels lacking that language. */ +@Getter +@Setter +public class MessageSearchRequest { + private String searchKey; + private Area area; + private String missingLocale; + private int page; + private int size; +} diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/service/MessageService.java b/solvway-services-system/src/main/java/com/solvway/services/system/service/MessageService.java index 504080b..9b08117 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/service/MessageService.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/service/MessageService.java @@ -3,16 +3,24 @@ package com.solvway.services.system.service; import com.google.gson.Gson; import com.solvway.services.system.constant.SystemConstants.Area; import com.solvway.services.system.model.Message; +import com.solvway.services.system.model.MessageSearchRequest; import com.solvway.services.system.repo.MessageRepository; import com.solvway.services.system.util.paging.PageableRest; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.util.ArrayList; +import java.util.Comparator; import java.util.HashMap; +import java.util.Locale; +import java.util.Objects; import java.util.List; import java.util.Map; import java.util.Optional; @@ -48,9 +56,79 @@ public class MessageService { return messageRepository.findByCodeContainingOrderByIdAsc(searchKey, PageRequest.of(pageable.getNumber(), pageable.getSize(), pageable.getSort())); } + @Autowired + private CatalogVersionService catalogVersion; + + /** + * Upsert of one label. Code and area are a label's identity, so an update may not change them and a create may + * not reuse a code (ignoring case) in its area; both are 409s with a message code. Every accepted save bumps the + * catalog version in the same transaction, so the portals reload on their next request. + */ @Transactional public void save(Message message) { - messageRepository.save(message); + Message stored = message.getId() > 0 ? messageRepository.findById(message.getId()).orElse(null) : null; + if (stored != null) { + if (!Objects.equals(stored.getCode(), message.getCode()) || stored.getArea() != message.getArea()) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "MsgsCodeAreaLocked"); + } + } else { + Message existing = messageRepository.findByCodeAndArea(message.getCode(), message.getArea()); + if (existing != null && existing.getCode() != null && existing.getCode().equalsIgnoreCase(message.getCode())) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "MsgsDuplicateCode"); + } + } + messageRepository.save(message); + catalogVersion.bump(); + } + + /** Filters in memory, sorted by code. ponytail: fine for the ~3.5k area-A rows; move to SQL past ~50k. */ + public Page search(MessageSearchRequest req) { + List rows = req.getArea() == null ? messageRepository.findAll() : messageRepository.findAllByArea(req.getArea()); + String key = StringUtils.isEmpty(req.getSearchKey()) || req.getSearchKey().isBlank() ? null : lower(req.getSearchKey().trim()); + String missing = StringUtils.isEmpty(req.getMissingLocale()) ? null : req.getMissingLocale(); + List hits = new ArrayList<>(); + for (Message m : rows) { + Map text = parseContent(m.getContent()); + if (key != null && !(lower(m.getCode()).contains(key) || lower(text.get("en_US")).contains(key) || lower(text.get("zh_CN")).contains(key))) { + continue; + } + if (missing != null && !isMissing(text, missing)) { + continue; + } + hits.add(m); + } + hits.sort(Comparator.comparing((Message m) -> lower(m.getCode()))); + int size = req.getSize() >= 1 ? req.getSize() : 20; + int number = Math.max(req.getPage(), 0); + int from = (int) Math.min((long) number * size, hits.size()); + int to = Math.min(from + size, hits.size()); + return new PageImpl<>(new ArrayList<>(hits.subList(from, to)), PageRequest.of(number, size), hits.size()); + } + + private Map parseContent(String json) { + if (StringUtils.isEmpty(json)) { + return Map.of(); + } + try { + Map raw = gson.fromJson(json, Map.class); + Map out = new HashMap<>(); + if (raw != null) { + raw.forEach((k, v) -> out.put(String.valueOf(k), v == null ? null : String.valueOf(v))); + } + return out; + } catch (RuntimeException e) { + return Map.of(); + } + } + + private static String lower(String s) { + return s == null ? "" : s.toLowerCase(Locale.ROOT); + } + + /** Absent, blank, or the English copied over. */ + private static boolean isMissing(Map text, String locale) { + String v = text.get(locale); + return v == null || v.isBlank() || (!"en_US".equals(locale) && v.equals(text.get("en_US"))); } public Optional findById(Long id) { return messageRepository.findById(id); diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/service/MessageServiceTranslationsTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/service/MessageServiceTranslationsTest.java new file mode 100644 index 0000000..6d43d8f --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/service/MessageServiceTranslationsTest.java @@ -0,0 +1,154 @@ +package com.solvway.services.system.service; + +import com.google.gson.Gson; +import com.solvway.services.system.constant.SystemConstants.Area; +import com.solvway.services.system.model.Message; +import com.solvway.services.system.model.MessageSearchRequest; +import com.solvway.services.system.repo.MessageRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.Page; +import org.springframework.http.HttpStatus; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.web.server.ResponseStatusException; + +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Translations rules ported from babyboo message-admin-api: search, missing Chinese, save refusals, the version bump. */ +@ExtendWith(MockitoExtension.class) +class MessageServiceTranslationsTest { + + @Mock + private MessageRepository repository; + @Mock + private CatalogVersionService catalogVersion; + + private MessageService service; + + @BeforeEach + void setUp() { + service = new MessageService(); + ReflectionTestUtils.setField(service, "messageRepository", repository); + ReflectionTestUtils.setField(service, "gson", new Gson()); + ReflectionTestUtils.setField(service, "catalogVersion", catalogVersion); + } + + @Test + void searchMatchesCodeEnglishOrChineseIgnoringCase() { + when(repository.findAllByArea(Area.A)).thenReturn(List.of( + msg(1, "Leads", "Leads", "线索"), + msg(2, "Users", "Users", "用户"), + msg(3, "EventLeads", "Event leads", "活动线索"))); + + assertThat(codes(service.search(req("线索", null, 0, 10)))).containsExactly("EventLeads", "Leads"); + assertThat(codes(service.search(req("users", null, 0, 10)))).containsExactly("Users"); + assertThat(codes(service.search(req("EVENT", null, 0, 10)))).containsExactly("EventLeads"); + } + + @Test + void searchNeverMatchesLanguageKeyNames() { + when(repository.findAllByArea(Area.A)).thenReturn(List.of(msg(1, "Leads", "Leads", "线索"))); + + assertThat(service.search(req("en_US", null, 0, 10)).getTotalElements()).isZero(); + } + + @Test + void missingChineseMeansAbsentBlankOrCopiedEnglish() { + when(repository.findAllByArea(Area.A)).thenReturn(List.of( + msg(1, "Leads", "Leads", "线索"), + msg(2, "WhatsApp", "WhatsApp", "WhatsApp"), + msg(3, "Users", "Users", null), + msg(4, "Roles", "Roles", " "))); + + assertThat(codes(service.search(req(null, "zh_CN", 0, 10)))).containsExactly("Roles", "Users", "WhatsApp"); + } + + @Test + void searchPagesAndCountsOnlyMatches() { + when(repository.findAllByArea(Area.A)).thenReturn(List.of( + msg(1, "A1", "a", "甲"), msg(2, "A2", "a", "甲"), msg(3, "A3", "a", "甲"), msg(4, "B1", "b", "乙"))); + + Page page = service.search(req("a", null, 1, 2)); + + assertThat(page.getTotalElements()).isEqualTo(3); + assertThat(codes(page)).containsExactly("A3"); + } + + @Test + void savingAnExistingLabelBumpsTheVersion() { + Message stored = msg(7, "Leads", "Leads", "线索"); + when(repository.findById(7L)).thenReturn(Optional.of(stored)); + Message edit = msg(7, "Leads", "Leads", "潜在客户"); + + service.save(edit); + + verify(repository).save(edit); + verify(catalogVersion).bump(); + } + + @Test + void changingALabelsCodeIsRefused() { + when(repository.findById(7L)).thenReturn(Optional.of(msg(7, "Leads", "Leads", "线索"))); + + assertRefused(() -> service.save(msg(7, "Contacts", "Leads", "线索")), "MsgsCodeAreaLocked"); + } + + @Test + void creatingADuplicateCodeIgnoringCaseIsRefused() { + when(repository.findByCodeAndArea("leads", Area.A)).thenReturn(msg(7, "Leads", "Leads", "线索")); + + assertRefused(() -> service.save(msg(0, "leads", "Leads", null)), "MsgsDuplicateCode"); + } + + @Test + void creatingANewCodeSavesAndBumps() { + when(repository.findByCodeAndArea("NewLabel", Area.A)).thenReturn(null); + Message created = msg(0, "NewLabel", "New label", "新标签"); + + service.save(created); + + verify(repository).save(created); + verify(catalogVersion).bump(); + } + + private void assertRefused(Runnable call, String reason) { + assertThatThrownBy(call::run).isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(e.getReason()).isEqualTo(reason); + }); + verify(repository, never()).save(any()); + verify(catalogVersion, never()).bump(); + } + + private static MessageSearchRequest req(String key, String missing, int page, int size) { + MessageSearchRequest r = new MessageSearchRequest(); + r.setSearchKey(key); + r.setMissingLocale(missing); + r.setArea(Area.A); + r.setPage(page); + r.setSize(size); + return r; + } + + private static List codes(Page page) { + return page.getContent().stream().map(Message::getCode).toList(); + } + + private static Message msg(long id, String code, String en, String zh) { + String content = zh == null ? "{\"en_US\":\"" + en + "\"}" : "{\"en_US\":\"" + en + "\",\"zh_CN\":\"" + zh + "\"}"; + Message m = new Message(code, content, Area.A, null); + m.setId(id); + return m; + } +} From 45bd81cdbb661efdee2039d7888a284609859807 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 12:44:38 +0800 Subject: [PATCH 06/15] fix(gateway): only label reads skip the user token, not message writes Any URL containing /message/ skipped the user token, saves included. Only the catalog reads that services and the sign-in page make stay open now, each an exact GET path, plus the enabled-language list. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs --- openspec/changes/add-zh-cn-messages/tasks.md | 2 +- .../solvway/gateway/filter/JWTAuthFilter.java | 12 ++- .../filter/JWTAuthFilterMessagePathTest.java | 89 +++++++++++++++++++ 3 files changed, 100 insertions(+), 3 deletions(-) create mode 100644 solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterMessagePathTest.java diff --git a/openspec/changes/add-zh-cn-messages/tasks.md b/openspec/changes/add-zh-cn-messages/tasks.md index 7a6c599..3f87952 100644 --- a/openspec/changes/add-zh-cn-messages/tasks.md +++ b/openspec/changes/add-zh-cn-messages/tasks.md @@ -24,7 +24,7 @@ Verify commands: ## 3. Gateway -- [ ] 3.1 Narrow the token bypass from any `/message/` URL to the exact read paths in use (grep the callers first), plus `/locale/findAllEnabled`. Tests cover open reads and token-gated writes. Security code: read the whole diff. +- [x] 3.1 Narrow the token bypass from any `/message/` URL to the exact read paths in use (grep the callers first), plus `/locale/findAllEnabled`. Tests cover open reads and token-gated writes. Security code: read the whole diff. - Verify: `mvn -T 1C -B -q -pl solvway-api-gateway -am verify` ## 4. mobile-api diff --git a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java index 24d8f9c..8d21843 100644 --- a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java +++ b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java @@ -59,7 +59,15 @@ public class JWTAuthFilter implements GlobalFilter, Ordered { // Password hint on public password screens: switched-on rule names and numbers only, no user data publicPath(HttpMethod.GET, "/passwordRule/adminActive"), // WhatsApp webhook forward from mobile-api: no user token; the service re-verifies Meta's signature itself - publicPath(HttpMethod.POST, "/whatsapp/webhook/ingest")); + publicPath(HttpMethod.POST, "/whatsapp/webhook/ingest"), + // Label catalog reads (services and the sign-in page have no user token). Saves, search and full listings need one. + publicPath(HttpMethod.GET, "/message/catalogVersion"), + publicPath(HttpMethod.GET, "/message/getAllMessages/[A-Z]+"), + publicPath(HttpMethod.GET, "/message/getMessageJsonByAreaAndLocale/[A-Z]+/[A-Za-z_]+"), + publicPath(HttpMethod.GET, "/message/getMessagesByCode/[^/]+"), + publicPath(HttpMethod.GET, "/message/getMessagesByCodeAndArea/[^/]+/[A-Z]+"), + publicPath(HttpMethod.GET, "/message/findByCodeAndLocale/[^/]+/[A-Za-z_]+"), + publicPath(HttpMethod.GET, "/locale/findAllEnabled")); private static Map.Entry publicPath(HttpMethod method, String regex) { return Map.entry(method, Pattern.compile(regex)); @@ -157,7 +165,7 @@ public class JWTAuthFilter implements GlobalFilter, Ordered { boolean bypassToken = (url.contains("/auth/") || url.contains("/auth/memberAutoLoginUpdate") || url.contains("/auth/fingerPrintLoginWithToken") - || url.contains("/actuator/") || url.contains("/message/") + || url.contains("/actuator/") || url.contains("/appInitialize/") || url.contains("/blockLoginPeriod/") || url.contains("/member/forgetPassword") // Co-Lite admin forgot password (public; answers the same whether or not details match) diff --git a/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterMessagePathTest.java b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterMessagePathTest.java new file mode 100644 index 0000000..61395c5 --- /dev/null +++ b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterMessagePathTest.java @@ -0,0 +1,89 @@ +package com.solvway.gateway.filter; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.gateway.model.AuthAppKey; +import com.solvway.gateway.model.AuthAppKeyMap; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.test.util.ReflectionTestUtils; +import reactor.core.publisher.Mono; + +import java.net.InetSocketAddress; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.assertj.core.api.Assertions.assertThat; + +/** Message and language reads that services and the sign-in page make stay open; saves, search and full listings need a user token. */ +class JWTAuthFilterMessagePathTest { + + private static final String KEY = "gateway-test-key"; + + private JWTAuthFilter filter; + + @BeforeEach + void setUp() throws Exception { + AuthAppKey key = new ObjectMapper().readValue( + "{\"key\":\"" + KEY + "\",\"type\":\"BO\",\"ipList\":[\"0.0.0.0/0\"],\"allowList\":[\"/\"]}", + AuthAppKey.class); + AuthAppKeyMap map = new AuthAppKeyMap(); + map.add(KEY, key); + filter = new JWTAuthFilter(); + ReflectionTestUtils.setField(filter, "authAppKeyMap", map); + } + + private MockServerWebExchange call(HttpMethod method, String path) { + return MockServerWebExchange.from(MockServerHttpRequest.method(method, path) + .header("api-key", KEY) + .remoteAddress(new InetSocketAddress("127.0.0.1", 40000))); + } + + private boolean passes(MockServerWebExchange exchange) { + AtomicBoolean called = new AtomicBoolean(false); + GatewayFilterChain chain = ex -> { + called.set(true); + return Mono.empty(); + }; + filter.filter(exchange, chain).block(); + return called.get(); + } + + @Test + void catalogReadsNeedNoUserToken() { + for (String path : new String[] { + "/message/catalogVersion", + "/message/getAllMessages/A", + "/message/getMessageJsonByAreaAndLocale/A/zh_CN", + "/message/getMessagesByCode/Leads", + "/message/getMessagesByCodeAndArea/Leads/A", + "/message/findByCodeAndLocale/Leads/zh_CN", + "/message/getMessageJsonForMobile/zh_CN", + "/locale/findAllEnabled" }) { + assertThat(passes(call(HttpMethod.GET, path))).as(path).isTrue(); + } + } + + @Test + void writesSearchAndFullListingsNeedAUserToken() { + for (String[] c : new String[][] { + {"POST", "/message/save"}, + {"POST", "/message/search"}, + {"GET", "/message/findAll"}, + {"GET", "/message/findById/7"}, + {"GET", "/message/findAllPageable"}, + {"POST", "/message/catalogVersion"}, + {"GET", "/message/catalogVersion/x"}, + {"POST", "/locale/save"}, + {"POST", "/locale/update"}, + {"GET", "/locale/findAll"}, + {"POST", "/locale/findAllEnabled"} }) { + MockServerWebExchange ex = call(HttpMethod.valueOf(c[0]), c[1]); + assertThat(passes(ex)).as(c[0] + " " + c[1]).isFalse(); + assertThat(ex.getResponse().getStatusCode()).as(c[0] + " " + c[1]).isEqualTo(HttpStatus.UNAUTHORIZED); + } + } +} From 27e0ec7bff8b25cd081b20e5a84c56f1f940e1d6 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 13:05:08 +0800 Subject: [PATCH 07/15] feat(mobile-api): admin translations and languages APIs Locales list, create and update; public enabled list; message catalog, version, search, detail, update, export and import. Refusals from services-system pass through as 409 with their reason code. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs --- openspec/changes/add-zh-cn-messages/tasks.md | 4 +- .../api/RestApiSystemServiceConstants.java | 9 + .../controller/PublicLocaleController.java | 26 +++ .../admin/AdminLocaleController.java | 50 +++++ .../admin/AdminMessageController.java | 87 +++++++++ .../api/service/AdminTranslationService.java | 173 +++++++++++++++++ .../AdminTranslationControllersTest.java | 92 +++++++++ .../service/AdminTranslationServiceTest.java | 178 ++++++++++++++++++ 8 files changed, 617 insertions(+), 2 deletions(-) create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/PublicLocaleController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLocaleController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminMessageController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminTranslationService.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminTranslationControllersTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminTranslationServiceTest.java diff --git a/openspec/changes/add-zh-cn-messages/tasks.md b/openspec/changes/add-zh-cn-messages/tasks.md index 3f87952..9ee66b5 100644 --- a/openspec/changes/add-zh-cn-messages/tasks.md +++ b/openspec/changes/add-zh-cn-messages/tasks.md @@ -29,8 +29,8 @@ Verify commands: ## 4. mobile-api -- [ ] 4.1 `AdminLocaleController` and the public `/api/public/locales`. Refusals pass through as 409 with the reason; locale writes are audited. -- [ ] 4.2 `AdminMessageController`: catalog and catalog-version (API key, no session); list and search; detail; `PUT` (the path id wins); export (audited as a sensitive read); import (match by code ignoring case, per-row summary, audited); module `BO_MESSAGES`; no create and no delete mapping. +- [x] 4.1 `AdminLocaleController` and the public `/api/public/locales`. Refusals pass through as 409 with the reason; locale writes are audited. +- [x] 4.2 `AdminMessageController`: catalog and catalog-version (API key, no session); list and search; detail; `PUT` (the path id wins); export (audited as a sensitive read); import (match by code ignoring case, per-row summary, audited); module `BO_MESSAGES`; no create and no delete mapping. - Verify (4.1 and 4.2): `mvn -T 1C -B -q -pl solvway-mobile-api -am verify` ## 5. Portal diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java index 79956e9..8242d1f 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java @@ -60,6 +60,15 @@ public class RestApiSystemServiceConstants { public static final String API_REST_SYSTEM_ADMIN_ACTIVE_PASSWORD_RULES = "/passwordRule/adminActive"; //Message + public static final String API_REST_SYSTEM_MESSAGE_SEARCH = "/message/search"; + public static final String API_REST_SYSTEM_MESSAGE_FIND_BY_ID = "/message/findById/{id}"; + public static final String API_REST_SYSTEM_MESSAGE_SAVE = "/message/save"; + public static final String API_REST_SYSTEM_MESSAGE_ALL_BY_AREA = "/message/getAllMessages/{area}"; + public static final String API_REST_SYSTEM_MESSAGE_CATALOG_VERSION = "/message/catalogVersion"; + public static final String API_REST_SYSTEM_LOCALE_FIND_ALL = "/locale/findAll"; + public static final String API_REST_SYSTEM_LOCALE_FIND_ALL_ENABLED = "/locale/findAllEnabled"; + public static final String API_REST_SYSTEM_LOCALE_SAVE = "/locale/save"; + public static final String API_REST_SYSTEM_LOCALE_UPDATE = "/locale/update"; public static final String API_REST_SYSTEM_MESSAGE_JSON_BY_AREA_AND_LOCALE = "/message/getMessageJsonByAreaAndLocale/{area}/{locale}"; //Nationality diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/PublicLocaleController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/PublicLocaleController.java new file mode 100644 index 0000000..cc0765f --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/PublicLocaleController.java @@ -0,0 +1,26 @@ +package com.solvway.mobile.api.controller; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.service.AdminTranslationService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.Map; + +/** Enabled languages for the sign-in page switcher: API key only, no session. */ +@RestController +@RequestMapping("/api/public") +@RequiredArgsConstructor +public class PublicLocaleController { + private final AdminTranslationService translations; + + @AppAuth(skipValidate = true) + @GetMapping("/locales") + public ResponseEntity>> enabled() { + return ResponseEntity.ok(translations.locales(true)); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLocaleController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLocaleController.java new file mode 100644 index 0000000..29fd4e1 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLocaleController.java @@ -0,0 +1,50 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.service.AdminTranslationService; +import com.solvway.mobile.api.useraccess.AdminModule; +import com.solvway.mobile.api.useraccess.Audited; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.Map; + +/** Languages, ported from babyboo. Any signed-in admin reads the list for the switcher; writes need BO_LOCALES. */ +@RestController +@RequestMapping("/api/admin") +@RequiredArgsConstructor +public class AdminLocaleController { + private final AdminTranslationService translations; + + @AppAuth + @AdminModule(AdminModule.ANY_ADMIN) + @GetMapping("/locales") + public ResponseEntity>> list() { + return ResponseEntity.ok(translations.locales(false)); + } + + @AppAuth + @AdminModule("BO_LOCALES") + @Audited(action = "LOCALE_CREATE") + @PostMapping("/locales") + public ResponseEntity> create(@RequestBody Map body) { + return ResponseEntity.ok(translations.createLocale(body)); + } + + /** The path id wins over any id in the body. */ + @AppAuth + @AdminModule("BO_LOCALES") + @Audited(action = "LOCALE_UPDATE") + @PutMapping("/locales/{id}") + public ResponseEntity> update(@PathVariable Long id, @RequestBody Map body) { + return ResponseEntity.ok(translations.updateLocale(id, body)); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminMessageController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminMessageController.java new file mode 100644 index 0000000..9ea75b2 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminMessageController.java @@ -0,0 +1,87 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.service.AdminTranslationService; +import com.solvway.mobile.api.service.SystemService; +import com.solvway.mobile.api.useraccess.AdminModule; +import com.solvway.mobile.api.useraccess.Audited; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.Map; + +/** + * Back-office labels (area A), ported from babyboo and trimmed: no area filter, no create, no delete. + * The catalog and its version need only the API key, because the sign-in page shows labels before a session exists. + */ +@RestController +@RequestMapping("/api/admin") +@RequiredArgsConstructor +public class AdminMessageController { + private final AdminTranslationService translations; + private final SystemService systemService; + + @AppAuth(skipValidate = true) + @GetMapping("/messages/catalog/{locale}") + public ResponseEntity> catalog(@PathVariable String locale) { + return ResponseEntity.ok(systemService.findMessageCatalog("A", locale)); + } + + @AppAuth(skipValidate = true) + @GetMapping("/messages/catalog-version") + public ResponseEntity> catalogVersion() { + return ResponseEntity.ok(translations.catalogVersion()); + } + + @AppAuth + @AdminModule("BO_MESSAGES") + @GetMapping("/messages") + public ResponseEntity> list(@RequestParam(required = false) String searchKey, + @RequestParam(required = false) String missingLocale, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "20") int size) { + return ResponseEntity.ok(translations.search(searchKey, missingLocale, page, size)); + } + + @AppAuth + @AdminModule("BO_MESSAGES") + @Audited(action = "MESSAGES_EXPORT") + @GetMapping("/messages/export") + public ResponseEntity>> export() { + return ResponseEntity.ok(translations.export()); + } + + @AppAuth + @AdminModule("BO_MESSAGES") + @GetMapping("/messages/{id}") + public ResponseEntity> detail(@PathVariable Long id) { + return ResponseEntity.ok(translations.message(id)); + } + + /** The path id wins; only the content changes. */ + @AppAuth + @AdminModule("BO_MESSAGES") + @Audited(action = "MESSAGE_UPDATE") + @PutMapping("/messages/{id}") + public ResponseEntity update(@PathVariable Long id, @RequestBody Map body) { + translations.updateMessage(id, body); + return ResponseEntity.noContent().build(); + } + + @AppAuth + @AdminModule("BO_MESSAGES") + @Audited(action = "MESSAGES_IMPORT") + @PostMapping("/messages/import") + public ResponseEntity> importMessages(@RequestBody List> rows) { + return ResponseEntity.ok(translations.importMessages(rows)); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminTranslationService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminTranslationService.java new file mode 100644 index 0000000..c56d0ec --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminTranslationService.java @@ -0,0 +1,173 @@ +package com.solvway.mobile.api.service; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import org.springframework.web.client.HttpClientErrorException; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** + * Translations (area A labels) and languages for the admin portal, ported from babyboo + * AdminMessageService and AdminLocaleService, trimmed to area A with no create or delete of labels. + */ +@Service +public class AdminTranslationService { + + static final String AREA = "A"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference>> MAP_LIST = new ParameterizedTypeReference<>() {}; + + private final RestTemplateCustomUtil rest; + + public AdminTranslationService(RestTemplateCustomUtil rest) { + this.rest = rest; + } + + // ---- languages + + public List> locales(boolean enabledOnly) { + String api = enabledOnly ? RestApiSystemServiceConstants.API_REST_SYSTEM_LOCALE_FIND_ALL_ENABLED + : RestApiSystemServiceConstants.API_REST_SYSTEM_LOCALE_FIND_ALL; + List> body = rest.getForEntity(url(api), MAP_LIST).getBody(); + return body == null ? List.of() : body; + } + + public Map createLocale(Map body) { + Map sent = new LinkedHashMap<>(body); + sent.remove("id"); + return relay(() -> rest.postForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_LOCALE_SAVE), MAP, sent).getBody()); + } + + public Map updateLocale(Long id, Map body) { + Map sent = new LinkedHashMap<>(body); + sent.put("id", id); + return relay(() -> rest.postForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_LOCALE_UPDATE), MAP, sent).getBody()); + } + + // ---- labels + + public Map catalogVersion() { + Map body = rest.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_MESSAGE_CATALOG_VERSION), MAP).getBody(); + return body == null ? Map.of("version", 0) : body; + } + + public Map search(String searchKey, String missingLocale, int page, int size) { + Map req = new HashMap<>(); + req.put("searchKey", searchKey); + req.put("missingLocale", missingLocale); + req.put("area", AREA); + req.put("page", page); + req.put("size", size); + return rest.postForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_MESSAGE_SEARCH), MAP, req).getBody(); + } + + /** Area A only: other areas belong to portals Co-Lite does not run, so they answer 404. */ + public Map message(Long id) { + Map row = rest.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_MESSAGE_FIND_BY_ID), MAP, id).getBody(); + if (row == null || !AREA.equals(row.get("area"))) { + throw new CodedResponseStatusException(HttpStatus.NOT_FOUND, "Translation not found", "MsgsNotFound"); + } + return row; + } + + /** The path id wins; code and area stay as stored, only content changes. */ + public void updateMessage(Long id, Map body) { + Map stored = message(id); + save(row(id, (String) stored.get("code"), body.get("content"), stored.get("description"))); + } + + public List> export() { + List> body = rest.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_MESSAGE_ALL_BY_AREA), MAP_LIST, AREA).getBody(); + return body == null ? List.of() : body; + } + + /** Matches rows by code ignoring case, never by the file's id; one failed row does not stop the rest. */ + public Map importMessages(List> rows) { + Map> byCode = new HashMap<>(); + for (Map m : export()) byCode.put(lower(m.get("code")), m); + int created = 0; + int updated = 0; + List> errors = new ArrayList<>(); + for (int i = 0; i < rows.size(); i++) { + Map r = rows.get(i); + Object code = r.get("code"); + if (!(code instanceof String c) || !StringUtils.hasText(c)) { + errors.add(Map.of("index", i, "code", "", "error", "MsgsCodeRequired")); + continue; + } + Map existing = byCode.get(lower(c)); + try { + if (existing == null) { + save(row(0L, c.trim(), r.get("content"), r.get("description"))); + created++; + } else { + Object description = r.containsKey("description") ? r.get("description") : existing.get("description"); + save(row(((Number) existing.get("id")).longValue(), (String) existing.get("code"), r.get("content"), description)); + updated++; + } + } catch (CodedResponseStatusException e) { + errors.add(Map.of("index", i, "code", c, "error", e.getCode())); + } + } + Map summary = new LinkedHashMap<>(); + summary.put("created", created); + summary.put("updated", updated); + summary.put("errors", errors); + return summary; + } + + private void save(Map row) { + relay(() -> rest.postForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_MESSAGE_SAVE), Void.class, row)); + } + + private static Map row(long id, String code, Object content, Object description) { + Map m = new LinkedHashMap<>(); + m.put("id", id); + m.put("code", code); + m.put("area", AREA); + m.put("content", content); + m.put("description", description); + return m; + } + + /** services-system refuses with a ProblemDetail whose detail is the reason code; pass it through as a 409. */ + private static T relay(java.util.function.Supplier call) { + try { + return call.get(); + } catch (HttpClientErrorException.Conflict | HttpClientErrorException.NotFound e) { + String reason = detail(e); + throw new CodedResponseStatusException(e.getStatusCode(), reason, reason); + } + } + + private static String detail(HttpClientErrorException e) { + try { + Object d = JSON.readValue(e.getResponseBodyAsString(), Map.class).get("detail"); + if (d != null) return String.valueOf(d); + } catch (JsonProcessingException ignored) { + // fall through to the generic reason + } + return e.getStatusCode().value() == 404 ? "NotFound" : "Conflict"; + } + + private static String lower(Object code) { + return code == null ? "" : code.toString().toLowerCase(Locale.ROOT); + } + + private String url(String api) { + return rest.getURLforApiService(api); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminTranslationControllersTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminTranslationControllersTest.java new file mode 100644 index 0000000..7537b1b --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminTranslationControllersTest.java @@ -0,0 +1,92 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.controller.PublicLocaleController; +import com.solvway.mobile.api.service.AdminTranslationService; +import com.solvway.mobile.api.service.SystemService; +import com.solvway.mobile.api.useraccess.AdminModule; +import com.solvway.mobile.api.useraccess.Audited; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PostMapping; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +class AdminTranslationControllersTest { + + private AdminTranslationService translations; + private SystemService system; + private MockMvc mvc; + + @BeforeEach + void setUp() { + translations = mock(AdminTranslationService.class); + system = mock(SystemService.class); + mvc = MockMvcBuilders.standaloneSetup(new AdminMessageController(translations, system), new AdminLocaleController(translations)).build(); + } + + @Test + void catalogAndVersionNeedOnlyTheApiKeyEverythingElseAModule() throws Exception { + for (Method m : AdminMessageController.class.getDeclaredMethods()) { + if (!m.isAnnotationPresent(AppAuth.class)) continue; + boolean open = m.getName().startsWith("catalog"); + assertThat(m.getAnnotation(AppAuth.class).skipValidate()).as(m.getName()).isEqualTo(open); + if (!open) assertThat(m.getAnnotation(AdminModule.class).value()).as(m.getName()).containsExactly("BO_MESSAGES"); + } + assertThat(AdminLocaleController.class.getMethod("list").getAnnotation(AdminModule.class).value()).containsExactly(AdminModule.ANY_ADMIN); + assertThat(AdminLocaleController.class.getMethod("create", Map.class).getAnnotation(AdminModule.class).value()).containsExactly("BO_LOCALES"); + assertThat(AdminLocaleController.class.getMethod("update", Long.class, Map.class).getAnnotation(AdminModule.class).value()).containsExactly("BO_LOCALES"); + } + + @Test + void labelsCannotBeAddedOrDeletedAndExportIsAudited() throws Exception { + assertThat(Arrays.stream(AdminMessageController.class.getDeclaredMethods()) + .filter(m -> m.isAnnotationPresent(DeleteMapping.class) + || (m.isAnnotationPresent(PostMapping.class) && !m.getName().equals("importMessages")))).isEmpty(); + assertThat(AdminMessageController.class.getMethod("export").getAnnotation(Audited.class)).isNotNull(); + } + + @Test + void listPassesFiltersWithFirstPageOfTwentyByDefault() throws Exception { + when(translations.search(null, "zh_CN", 0, 20)).thenReturn(Map.of("content", List.of(), "totalElements", 0)); + mvc.perform(get("/api/admin/messages").param("missingLocale", "zh_CN")).andExpect(status().isOk()).andExpect(jsonPath("$.totalElements").value(0)); + } + + @Test + void updateUsesThePathId() throws Exception { + mvc.perform(put("/api/admin/messages/7").contentType(MediaType.APPLICATION_JSON).content("{\"id\":9,\"content\":\"{}\"}")) + .andExpect(status().isNoContent()); + verify(translations).updateMessage(eq(7L), eq(Map.of("id", 9, "content", "{}"))); + } + + @Test + void publicLocalesAreEnabledOnlyAndNeedNoSession() throws Exception { + assertThat(PublicLocaleController.class.getMethod("enabled").getAnnotation(AppAuth.class).skipValidate()).isTrue(); + when(translations.locales(true)).thenReturn(List.of(Map.of("code", "zh_CN"))); + MockMvcBuilders.standaloneSetup(new PublicLocaleController(translations)).build() + .perform(get("/api/public/locales")).andExpect(status().isOk()).andExpect(jsonPath("$[0].code").value("zh_CN")); + } + + @Test + void catalogReadsAreaA() throws Exception { + when(system.findMessageCatalog("A", "zh_CN")).thenReturn(Map.of("Leads", "线索")); + mvc.perform(get("/api/admin/messages/catalog/zh_CN")).andExpect(status().isOk()).andExpect(jsonPath("$.Leads").value("线索")); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminTranslationServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminTranslationServiceTest.java new file mode 100644 index 0000000..87f2495 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminTranslationServiceTest.java @@ -0,0 +1,178 @@ +package com.solvway.mobile.api.service; + +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.server.ResponseStatusException; + +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Translations and languages admin rules ported from babyboo message-admin-api and locale-registry. */ +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminTranslationServiceTest { + + private RestTemplateCustomUtil rest; + private AdminTranslationService service; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + service = new AdminTranslationService(rest); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + } + + @Test + void updateUsesThePathIdAndKeepsTheStoredCodeAndArea() { + stored(7, "Leads", "A"); + Map body = new LinkedHashMap<>(); + body.put("id", 99); + body.put("code", "Contacts"); + body.put("content", "{\"en_US\":\"Leads\",\"zh_CN\":\"线索\"}"); + + service.updateMessage(7L, body); + + Map sent = savedBody(); + assertThat(sent).containsEntry("id", 7L).containsEntry("code", "Leads").containsEntry("area", "A") + .containsEntry("content", "{\"en_US\":\"Leads\",\"zh_CN\":\"线索\"}"); + } + + @Test + void aRefusalReachesThePortalWithItsCode() { + stored(7, "Leads", "A"); + doThrow(conflict("MsgsCodeAreaLocked")).when(rest).postForEntity(eq("/message/save"), eq(Void.class), any()); + + assertThatThrownBy(() -> service.updateMessage(7L, Map.of("content", "{}"))) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(e.getCode()).isEqualTo("MsgsCodeAreaLocked"); + }); + } + + @Test + void onlyBackOfficeLabelsCanBeReadOrEdited() { + stored(8, "Cart", "AP"); + + assertThatThrownBy(() -> service.message(8L)) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + assertThatThrownBy(() -> service.updateMessage(8L, Map.of("content", "{}"))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + } + + @Test + void searchAsksForBackOfficeLabelsWithTheFilters() { + when(rest.postForEntity(eq("/message/search"), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok(Map.of("content", List.of(), "totalElements", 0))); + + service.search("线索", "zh_CN", 2, 20); + + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq("/message/search"), any(ParameterizedTypeReference.class), body.capture()); + assertThat((Map) body.getValue()).containsEntry("searchKey", "线索").containsEntry("missingLocale", "zh_CN") + .containsEntry("area", "A").containsEntry("page", 2).containsEntry("size", 20); + } + + @Test + void importMatchesByCodeIgnoringCaseNeverByIdAndKeepsGoingAfterAFailure() { + when(rest.getForEntity(eq("/message/getAllMessages/{area}"), any(ParameterizedTypeReference.class), eq("A"))) + .thenReturn(ResponseEntity.ok(List.of(row(7, "Leads", "A")))); + when(rest.postForEntity(eq("/message/save"), eq(Void.class), any())).thenAnswer(i -> { + Map b = i.getArgument(2); + if ("Broken".equals(b.get("code"))) throw conflict("MsgsDuplicateCode"); + return ResponseEntity.ok().build(); + }); + List> rows = List.of( + Map.of("id", 123, "code", "leads", "content", "{\"zh_CN\":\"线索\"}"), + Map.of("code", "Broken", "content", "{}"), + Map.of("code", "NewLabel", "content", "{\"en_US\":\"New\"}")); + + Map summary = service.importMessages(rows); + + assertThat(summary).containsEntry("created", 1).containsEntry("updated", 1); + assertThat((List>) summary.get("errors")) + .containsExactly(Map.of("index", 1, "code", "Broken", "error", "MsgsDuplicateCode")); + ArgumentCaptor bodies = ArgumentCaptor.forClass(Object.class); + verify(rest, times(3)).postForEntity(eq("/message/save"), eq(Void.class), bodies.capture()); + Map first = (Map) bodies.getAllValues().get(0); + assertThat(first).containsEntry("id", 7L).containsEntry("code", "Leads").containsEntry("area", "A"); + assertThat((Map) bodies.getAllValues().get(2)).containsEntry("id", 0L).containsEntry("area", "A"); + } + + @Test + void aRowWithoutACodeIsReportedNotSent() { + when(rest.getForEntity(eq("/message/getAllMessages/{area}"), any(ParameterizedTypeReference.class), eq("A"))) + .thenReturn(ResponseEntity.ok(List.of())); + + Map summary = service.importMessages(List.of(Map.of("content", "{}"))); + + assertThat((List) summary.get("errors")).hasSize(1); + verify(rest, times(0)).postForEntity(eq("/message/save"), eq(Void.class), any()); + } + + @Test + void languageCreateRelaysADuplicate() { + when(rest.postForEntity(eq("/locale/save"), any(ParameterizedTypeReference.class), any())).thenThrow(conflict("LocalesDuplicateCode")); + + assertThatThrownBy(() -> service.createLocale(Map.of("code", "zh_CN", "label", "x"))) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getCode()).isEqualTo("LocalesDuplicateCode")); + } + + @Test + void languageUpdateUsesThePathId() { + when(rest.postForEntity(eq("/locale/update"), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of())); + Map body = new LinkedHashMap<>(); + body.put("id", 5); + body.put("enabled", false); + + service.updateLocale(2L, body); + + ArgumentCaptor sent = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq("/locale/update"), any(ParameterizedTypeReference.class), sent.capture()); + assertThat((Map) sent.getValue()).containsEntry("id", 2L).containsEntry("enabled", false); + } + + private void stored(long id, String code, String area) { + when(rest.getForEntity(eq("/message/findById/{id}"), any(ParameterizedTypeReference.class), eq(id))) + .thenReturn(ResponseEntity.ok(row(id, code, area))); + } + + private Map savedBody() { + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq("/message/save"), eq(Void.class), body.capture()); + return (Map) body.getValue(); + } + + private static Map row(long id, String code, String area) { + Map m = new LinkedHashMap<>(); + m.put("id", id); + m.put("code", code); + m.put("area", area); + m.put("content", "{\"en_US\":\"" + code + "\"}"); + m.put("description", null); + return m; + } + + private static HttpClientErrorException conflict(String reason) { + String body = "{\"type\":\"about:blank\",\"title\":\"Conflict\",\"status\":409,\"detail\":\"" + reason + "\"}"; + return HttpClientErrorException.create(HttpStatus.CONFLICT, "Conflict", new HttpHeaders(), body.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); + } +} From a8bfcf5f6d7c06840426482c5a2e170a97a97b24 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 13:17:54 +0800 Subject: [PATCH 08/15] 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 Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs --- openspec/changes/add-zh-cn-messages/tasks.md | 6 +- .../app/api/locales/[[...path]]/route.test.ts | 49 ++++ .../app/api/locales/[[...path]]/route.ts | 57 +++++ .../api/messages/[[...path]]/route.test.ts | 72 ++++++ .../app/api/messages/[[...path]]/route.ts | 57 +++++ .../app/components/app/icon-map.ts | 4 +- .../app/components/ui/textarea.tsx | 23 ++ solvway-admin-portal/app/lib/aclSidebar.ts | 2 +- .../app/lib/i18n/defaultMessages.ts | 64 +++++ .../app/lib/routeModules.test.ts | 2 +- solvway-admin-portal/app/lib/routeModules.ts | 2 + .../app/lib/services/translations.ts | 41 ++++ .../app/lib/translationText.test.ts | 33 +++ .../app/lib/translationText.ts | 64 +++++ .../app/lib/translationsNav.test.tsx | 28 +++ .../app/locales/page.test.tsx | 103 ++++++++ solvway-admin-portal/app/locales/page.tsx | 222 ++++++++++++++++++ .../app/messages/ImportMessagesDialog.tsx | 158 +++++++++++++ .../app/messages/MessageEditSheet.tsx | 121 ++++++++++ .../app/messages/page.test.tsx | 130 ++++++++++ solvway-admin-portal/app/messages/page.tsx | 169 +++++++++++++ 21 files changed, 1401 insertions(+), 6 deletions(-) create mode 100644 solvway-admin-portal/app/api/locales/[[...path]]/route.test.ts create mode 100644 solvway-admin-portal/app/api/locales/[[...path]]/route.ts create mode 100644 solvway-admin-portal/app/api/messages/[[...path]]/route.test.ts create mode 100644 solvway-admin-portal/app/api/messages/[[...path]]/route.ts create mode 100644 solvway-admin-portal/app/components/ui/textarea.tsx create mode 100644 solvway-admin-portal/app/lib/services/translations.ts create mode 100644 solvway-admin-portal/app/lib/translationText.test.ts create mode 100644 solvway-admin-portal/app/lib/translationText.ts create mode 100644 solvway-admin-portal/app/lib/translationsNav.test.tsx create mode 100644 solvway-admin-portal/app/locales/page.test.tsx create mode 100644 solvway-admin-portal/app/locales/page.tsx create mode 100644 solvway-admin-portal/app/messages/ImportMessagesDialog.tsx create mode 100644 solvway-admin-portal/app/messages/MessageEditSheet.tsx create mode 100644 solvway-admin-portal/app/messages/page.test.tsx create mode 100644 solvway-admin-portal/app/messages/page.tsx 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 ( +