Merge pull request 'feat: Co-Lite labels only filter on Translations' (#50) from add-messages-colite-filter into main
CI / build-and-publish (push) Failing after 0s
CI / build-and-publish (push) Failing after 0s
This commit was merged in pull request #50.
This commit is contained in:
commit
05344d848d
23 files changed
+311
-7
No files matched your search
+2
-1
@@ -139,6 +139,7 @@ Run both before `service-whatsapp` starts. Give the services' database user the
|
||||
| `openspec/changes/archive/<date>-add-zh-cn-messages/sql/01-locales.sql` | Creates `service-system`.`supported_locale` (the languages staff can pick: English and 简体中文 on; Malay, Traditional Chinese and Indonesian off) and `catalog_meta` (the label catalog version). DDL. |
|
||||
| `openspec/changes/archive/<date>-add-zh-cn-messages/sql/02-modules.sql` | Adds the back-office modules `BO_MESSAGES` (Translations) and `BO_LOCALES` (Languages) under System. No role gets them; super admins grant them under Roles. |
|
||||
| `openspec/changes/archive/<date>-add-zh-cn-messages/sql/03-zh-cn-messages.sql` | Loads the first-pass Chinese for every back-office label into `service-system`.`message`: inserts the labels that are missing, sets their Chinese, gives four rows (`LogIn`, `Member`, `Tree`, `Wallet`) the back office's English, and bumps the catalog version. Generated; run it once. |
|
||||
| `openspec/changes/archive/<date>-add-messages-colite-filter/sql/01-colite-filter-labels.sql` | Adds the "Co-Lite labels only" label. Run it only where the 03 file above already ran before this change; the regenerated 03 already includes it. |
|
||||
|
||||
Run the three in order before the new services-system, gateway and mobile-api go live. `01` needs a user that may create tables. Run `03` once only: it overwrites the Chinese of every back-office label, so running it again after staff have edited translations undoes their edits. `99-rollback.sql` in the same folder drops the two tables and removes the modules; the Chinese stays in `message`, which the previous images never read.
|
||||
|
||||
@@ -385,7 +386,7 @@ data:
|
||||
- **Other Tastefully defaults.** The sender addresses in `service-email` and the `CUSTOMER_PORTAL_BASE_URL` fallback point at Tastefully. Override them as described in section 6.
|
||||
- **Leaked SMS key.** An SMS360 API key from Tastefully was in `service-email`'s config and is in git history. It has been removed from the config, but it must be rotated with SMS360 before go-live, by whoever owns that Tastefully account.
|
||||
- **Deploy by SHA, not `latest`.** CI pushes the images one by one, so if a push fails halfway, `latest` can differ between images.
|
||||
- **Chinese labels.** Staff switch the back office to 简体中文 with the language switcher, including on the sign-in page. The Chinese is a first pass, not checked by a native speaker. Grant `BO_MESSAGES` to the reviewer's role: under **Translations**, the **Missing Chinese** filter lists labels with no Chinese or with English copied in, and a saved change shows on the next page load. The list also holds about 3,400 labels inherited from Tastefully that Co-Lite never shows, so the filter lists about 1,700 rows; every label Co-Lite shows already has Chinese. A filter for Co-Lite's own labels is a planned follow-up. Export and Import move all labels through a JSON file for review offline; import matches labels by code and never adds or removes languages. Grant `BO_LOCALES` only to whoever decides which languages staff can pick: English cannot be switched off. Only the back office is translated; visitor pages and emails keep their own wording.
|
||||
- **Chinese labels.** Staff switch the back office to 简体中文 with the language switcher, including on the sign-in page. The Chinese is a first pass, not checked by a native speaker. Grant `BO_MESSAGES` to the reviewer's role: under **Translations**, the **Missing Chinese** filter lists labels with no Chinese or with English copied in, and a saved change shows on the next page load. The list also holds about 3,400 labels inherited from Tastefully that Co-Lite never shows; the **Co-Lite labels only** box, ticked by default, hides them, and unticking it lists every label. Export and Import move all labels through a JSON file for review offline; import matches labels by code and never adds or removes languages. Grant `BO_LOCALES` only to whoever decides which languages staff can pick: English cannot be switched off. Only the back office is translated; visitor pages and emails keep their own wording.
|
||||
- **Gateway paths for labels.** The gateway used to let every `/message/` path through without a user token. It now lets through only the label reads (`/message/catalogVersion`, `/message/getAllMessages/<area>`, `/message/getMessageJsonByAreaAndLocale/<area>/<locale>`, `/message/getMessageJsonForMobile/...`, the code lookups) and `GET /locale/findAllEnabled`. Saving, searching and the language writes need the user token mobile-api forwards. The gateway also gains a `/locale/**` route to services-system.
|
||||
- **WhatsApp roles.** Staff need `BO_WHATSAPP` to see the inbox and their own chats. A WhatsApp admin needs both `BO_WHATSAPP` and `BO_WHATSAPP_ADMIN`: the menu entry and the page need the first, and the second adds every chat of the company, owner changes and template sync. A chat's owner is set automatically to the salesperson of the newest lead with that mobile number; an admin can set an owner by hand, which sticks until "Automatic" is chosen again. A user who is disabled or loses `BO_WHATSAPP` loses their chats to Unassigned.
|
||||
- **WhatsApp limits at go-live.**
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
# Translations: Co-Lite Labels Only
|
||||
|
||||
Approved by the owner on 2026-12-02. Follow-up to `add-zh-cn-messages` (PR #49).
|
||||
|
||||
## Why
|
||||
|
||||
The Translations screen lists every area-A label, and about 3,400 of them were inherited from Tastefully. Co-Lite never shows those labels. The Missing Chinese filter therefore lists about 1,739 rows, almost none of which matter. This hides the few labels a Chinese reviewer needs to find.
|
||||
|
||||
## Goal
|
||||
|
||||
- The screen shows only the labels Co-Lite uses by default.
|
||||
- A reviewer can turn that off and see every label, as the screen works today.
|
||||
|
||||
Non-goals:
|
||||
|
||||
- No labels are deleted.
|
||||
- Export and import are unchanged and still cover every label.
|
||||
|
||||
## Approaches
|
||||
|
||||
1. **The portal sends its list of keys (chosen).** The portal's built-in English list (`defaultMessages.ts`, 706 keys) already defines the labels Co-Lite uses. The portal's server sends those keys with the search, and services-system filters on them in its existing in-memory search. This needs no schema change, and the list stays in the one place it already lives.
|
||||
2. **A "used by Co-Lite" flag on each row.** The Chinese SQL generator would set the flag. This needs DDL in every environment, and the flag goes stale whenever a label is added without rerunning the SQL.
|
||||
3. **Filter in the browser.** The page loads all labels and pages through them itself. That means a page rewrite for no extra benefit.
|
||||
|
||||
## Design
|
||||
|
||||
- **Portal page:** a **Co-Lite labels only** checkbox, on by default. Its state lives in the URL filters like the existing filters, so the default URL shows Co-Lite labels only. Search, Missing Chinese and the totals all respect the checkbox.
|
||||
- **Portal route:** the list route turns the request into `POST /api/admin/messages/search` on mobile-api. It does this because 706 codes do not fit in a query string.
|
||||
- The body is `{searchKey, missingLocale, page, size, codes}`.
|
||||
- The route fills `codes` from `DEFAULT_MESSAGES` on the server; the browser never sends codes.
|
||||
- The route sends no codes when the checkbox is off.
|
||||
- **mobile-api:** `POST /api/admin/messages/search` (module `BO_MESSAGES`) passes the filters and `codes` to services-system with area A.
|
||||
- `codes` must be a list of strings, at most 5,000 entries; otherwise the request is refused with 400.
|
||||
- The existing `GET /api/admin/messages` stays as it is.
|
||||
- **services-system:** `MessageSearchRequest.codes`. When it is present, only rows whose code matches one of the codes, ignoring case, are kept. Case is ignored because the database's unique code index ignores case.
|
||||
|
||||
## Left to the builder
|
||||
|
||||
The exact label wording, in English and Chinese, for the checkbox.
|
||||
@@ -1355,6 +1355,8 @@ INSERT INTO message (code, content, area) SELECT 'MsgsSearchPlaceholder', JSON_O
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '代码、英文或中文') WHERE LOWER(code) = LOWER('MsgsSearchPlaceholder') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'MsgsMissingChineseFilter', JSON_OBJECT('en_US', 'Missing Chinese', 'zh_CN', '缺少中文'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('MsgsMissingChineseFilter') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '缺少中文') WHERE LOWER(code) = LOWER('MsgsMissingChineseFilter') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'MsgsOwnLabelsFilter', JSON_OBJECT('en_US', 'Co-Lite labels only', 'zh_CN', '仅 Co-Lite 标签'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('MsgsOwnLabelsFilter') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '仅 Co-Lite 标签') WHERE LOWER(code) = LOWER('MsgsOwnLabelsFilter') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'MsgsBadgeMissing', JSON_OBJECT('en_US', 'Missing', 'zh_CN', '缺少'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('MsgsBadgeMissing') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '缺少') WHERE LOWER(code) = LOWER('MsgsBadgeMissing') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'MsgsBadgeSameAsEnglish', JSON_OBJECT('en_US', 'Same as English', 'zh_CN', '与英文相同'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('MsgsBadgeSameAsEnglish') AND area = 'A');
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-12-02
|
||||
@@ -0,0 +1,36 @@
|
||||
## Why
|
||||
|
||||
The Translations screen lists about 3,400 area-A labels inherited from Tastefully that Co-Lite never shows. Because of them, the Missing Chinese filter lists about 1,739 rows, which hides the few labels a Chinese reviewer needs to find. The owner decided on 2026-12-02 to ship `add-zh-cn-messages` first and add this filter as a follow-up.
|
||||
|
||||
## What Changes
|
||||
|
||||
- **Translations page:** a "Co-Lite labels only" checkbox, on by default. It limits the list, the search and the Missing Chinese filter to the labels in the portal's built-in English list (`DEFAULT_MESSAGES`). Turning it off shows every label, as before.
|
||||
- **Portal route:** the route builds the code list on the server and calls a new search endpoint in mobile-api.
|
||||
- **mobile-api:** `POST /api/admin/messages/search` (module `BO_MESSAGES`) takes the filters and an optional list of codes.
|
||||
- **services-system:** the message search takes an optional list of codes and matches them ignoring case.
|
||||
- Export and import are unchanged. No label is deleted, and no schema changes.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
None.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `ui-translations`: the Translations page can be limited to the labels Co-Lite uses. This capability is introduced by `add-zh-cn-messages`, which is merged but not yet archived, so this change adds a requirement instead of modifying one.
|
||||
|
||||
## Impact
|
||||
|
||||
- **services-system:** `MessageSearchRequest` and `MessageService.search`.
|
||||
- **mobile-api:**
|
||||
- `AdminMessageController`: a new POST mapping;
|
||||
- `AdminTranslationService.search`: a new codes parameter.
|
||||
- **Portal:**
|
||||
- `app/api/messages/[[...path]]/route.ts`;
|
||||
- `app/lib/services/translations.ts`;
|
||||
- `app/messages/page.tsx`;
|
||||
- one new label in `defaultMessages.ts` and `zh_CN.seed.json`, so the Chinese SQL is regenerated.
|
||||
- **Deploy:** `add-zh-cn-messages/sql/03-zh-cn-messages.sql` is regenerated and now also includes the new label. An environment that has already run 03 must not run it again, because it would overwrite reviewed Chinese. It runs this change's `sql/01-colite-filter-labels.sql` instead, which holds only the new label and is built by the same generator. The deployment doc states which file to run.
|
||||
|
||||
Design: `docs/superpowers/specs/2026-12-02-messages-colite-filter-design.md`.
|
||||
@@ -0,0 +1,32 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Translations Can Be Limited To Co-Lite Labels
|
||||
|
||||
The Translations page SHALL offer a "Co-Lite labels only" checkbox, on by default, that limits the list, the search and the "Missing Chinese" filter to the labels in the portal's built-in English list. Codes SHALL match ignoring case. Turning the checkbox off SHALL list every back-office label.
|
||||
|
||||
#### Scenario: Inherited labels hidden by default
|
||||
|
||||
- **GIVEN** a back-office label "OrderPayment" that is not in the portal's built-in list, and a label "Leads" that is
|
||||
- **WHEN** the user opens the Translations page
|
||||
- **THEN** "Leads" is listed and "OrderPayment" is not
|
||||
- **AND** "Co-Lite labels only" is checked
|
||||
|
||||
#### Scenario: Missing Chinese counts only Co-Lite labels
|
||||
|
||||
- **GIVEN** every label in the built-in list has Chinese and some inherited labels have none
|
||||
- **WHEN** the user turns on "Missing Chinese" with "Co-Lite labels only" checked
|
||||
- **THEN** no label is listed
|
||||
|
||||
#### Scenario: Every label on request
|
||||
|
||||
- **WHEN** the user unchecks "Co-Lite labels only"
|
||||
- **THEN** "OrderPayment" is listed too
|
||||
|
||||
### Requirement: The Co-Lite Code List Comes From The Portal Server
|
||||
|
||||
The portal's server SHALL build the Co-Lite code list from its built-in list and SHALL NOT take codes from the browser. mobile-api SHALL refuse with 400 a code list that is not a list of strings or holds more than 5,000 entries. Export and import SHALL keep covering every back-office label.
|
||||
|
||||
#### Scenario: Code list too long
|
||||
|
||||
- **WHEN** mobile-api receives a search with 5,001 codes
|
||||
- **THEN** it answers 400 and does not call services-system
|
||||
@@ -0,0 +1,6 @@
|
||||
-- The label added by add-messages-colite-filter, cut from the output of `npm run i18n:sql`. Run it only in an environment that already ran add-zh-cn-messages/sql/03-zh-cn-messages.sql; otherwise run that 03 file, which includes this label.
|
||||
SET NAMES utf8mb4;
|
||||
USE `service-system`;
|
||||
INSERT INTO message (code, content, area) SELECT 'MsgsOwnLabelsFilter', JSON_OBJECT('en_US', 'Co-Lite labels only', 'zh_CN', '仅 Co-Lite 标签'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('MsgsOwnLabelsFilter') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '仅 Co-Lite 标签') WHERE LOWER(code) = LOWER('MsgsOwnLabelsFilter') AND area = 'A';
|
||||
UPDATE catalog_meta SET version = version + 1, updated_at = NOW() WHERE id = 1;
|
||||
@@ -0,0 +1,34 @@
|
||||
# Tasks: add-messages-colite-filter
|
||||
|
||||
Design: `docs/superpowers/specs/2026-12-02-messages-colite-filter-design.md`. Every task is TDD. The owner said no workers, so everything runs serially in the main session with a self-review per task.
|
||||
|
||||
## 1. services-system
|
||||
|
||||
- [x] 1.1 `MessageSearchRequest.codes`; when present, `MessageService.search` keeps only rows whose code matches one of the codes, ignoring case. Existing filters and paging still apply.
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-services-system -am verify`
|
||||
|
||||
## 2. mobile-api
|
||||
|
||||
- [x] 2.1 `POST /api/admin/messages/search` (module `BO_MESSAGES`) with the body `{searchKey, missingLocale, page, size, codes}`. `AdminTranslationService.search` forwards `codes` with area A. A `codes` value that is not a list of strings, or that holds more than 5,000 entries, gets 400 without calling services-system.
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||
|
||||
## 3. Portal
|
||||
|
||||
- [x] 3.1 The list route posts to the new endpoint. It sends `codes` built on the server from `DEFAULT_MESSAGES` keys, unless the request asks for all labels.
|
||||
- [x] 3.2 Translations page: a "Co-Lite labels only" checkbox, on by default, kept in the list filters. Add its label to `defaultMessages.ts` and `zh_CN.seed.json`, then regenerate the Chinese SQL. Write this change's `sql/01-colite-filter-labels.sql` with the new label only.
|
||||
- Verify (3.1 and 3.2): `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint`
|
||||
|
||||
## 4. Release
|
||||
|
||||
- [x] 4.1 `docs/deployment.md`: replace the follow-up note with the checkbox, and say which SQL file to run.
|
||||
- [x] 4.2 Live Playwright check on the local stack: the default list hides inherited labels, Missing Chinese shows close to zero, and unchecking the box shows every label.
|
||||
- Done 2026-12-02 on port 3013 as the local super admin, at 1280 px and at 360 px in Chinese.
|
||||
- The box is ticked by default: 707 labels.
|
||||
- Missing Chinese with the box ticked: 5 labels, all deliberately the same as English (Co-Lite, WhatsApp, QR, IP and the Malay consent wording).
|
||||
- Unticked: 1,739 missing and 4,097 in all, as before.
|
||||
- The Chinese label 仅 Co-Lite 标签 shows in the phone filter panel.
|
||||
- [x] 4.3 Self-review, the PR to main and the merge.
|
||||
|
||||
## Workflow follow-up
|
||||
|
||||
- Archive after `add-zh-cn-messages`, because this change adds a requirement to the `ui-translations` capability that change introduces.
|
||||
@@ -1355,6 +1355,8 @@ INSERT INTO message (code, content, area) SELECT 'MsgsSearchPlaceholder', JSON_O
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '代码、英文或中文') WHERE LOWER(code) = LOWER('MsgsSearchPlaceholder') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'MsgsMissingChineseFilter', JSON_OBJECT('en_US', 'Missing Chinese', 'zh_CN', '缺少中文'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('MsgsMissingChineseFilter') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '缺少中文') WHERE LOWER(code) = LOWER('MsgsMissingChineseFilter') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'MsgsOwnLabelsFilter', JSON_OBJECT('en_US', 'Co-Lite labels only', 'zh_CN', '仅 Co-Lite 标签'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('MsgsOwnLabelsFilter') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '仅 Co-Lite 标签') WHERE LOWER(code) = LOWER('MsgsOwnLabelsFilter') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'MsgsBadgeMissing', JSON_OBJECT('en_US', 'Missing', 'zh_CN', '缺少'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('MsgsBadgeMissing') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '缺少') WHERE LOWER(code) = LOWER('MsgsBadgeMissing') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'MsgsBadgeSameAsEnglish', JSON_OBJECT('en_US', 'Same as English', 'zh_CN', '与英文相同'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('MsgsBadgeSameAsEnglish') AND area = 'A');
|
||||
|
||||
@@ -5,6 +5,7 @@ vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileAp
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import { GET, POST, PUT } from "./route";
|
||||
import { DEFAULT_MESSAGES } from "@/app/lib/i18n/defaultMessages";
|
||||
|
||||
type Req = Parameters<typeof GET>[0];
|
||||
const req = (url: string, init?: RequestInit) => new Request(url, init) as unknown as Req;
|
||||
@@ -29,6 +30,24 @@ describe("/api/messages", () => {
|
||||
`/api/admin/messages?searchKey=${encodeURIComponent("线索")}&missingLocale=zh_CN&page=0&size=20`, { token: "jwt" });
|
||||
});
|
||||
|
||||
it("own=1 searches the portal's own label codes, built on the server", async () => {
|
||||
await GET(req("http://localhost/api/messages?own=1&searchKey=lead&missingLocale=zh_CN&page=2&size=50&codes=Evil"), ctx());
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/messages/search", {
|
||||
method: "POST",
|
||||
body: { searchKey: "lead", missingLocale: "zh_CN", page: 2, size: 50, codes: Object.keys(DEFAULT_MESSAGES) },
|
||||
token: "jwt",
|
||||
});
|
||||
});
|
||||
|
||||
it("own=1 without filters sends page defaults and no empty filters", async () => {
|
||||
await GET(req("http://localhost/api/messages?own=1"), ctx());
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/messages/search", {
|
||||
method: "POST",
|
||||
body: { page: 0, size: 20, codes: Object.keys(DEFAULT_MESSAGES) },
|
||||
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" });
|
||||
|
||||
@@ -2,9 +2,10 @@ 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";
|
||||
import { DEFAULT_MESSAGES } from "@/app/lib/i18n/defaultMessages";
|
||||
|
||||
// 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.
|
||||
// Reads: list (own=1 limits it to the portal's own label codes), /{id}, /export. Writes: PUT /{id} (content only), POST /import. No create, no delete.
|
||||
type Ctx = { params: Promise<{ path?: string[] }> };
|
||||
const ID = /^\d+$/;
|
||||
|
||||
@@ -14,6 +15,18 @@ export async function GET(req: NextRequest, { params }: Ctx) {
|
||||
const { path = [] } = await params;
|
||||
if (path.length === 0) {
|
||||
const q = new URL(req.url).searchParams;
|
||||
if (q.get("own") === "1") {
|
||||
// Co-Lite labels only: the codes come from the built-in list here, never from the browser.
|
||||
const body: Record<string, unknown> = {};
|
||||
for (const key of ["searchKey", "missingLocale"]) {
|
||||
const v = q.get(key);
|
||||
if (v) body[key] = v;
|
||||
}
|
||||
body.page = Number(q.get("page")) || 0;
|
||||
body.size = Number(q.get("size")) || 20;
|
||||
body.codes = Object.keys(DEFAULT_MESSAGES);
|
||||
return forward("/api/admin/messages/search", { method: "POST", body, token });
|
||||
}
|
||||
const out = new URLSearchParams();
|
||||
for (const key of ["searchKey", "missingLocale"]) {
|
||||
const v = q.get(key);
|
||||
|
||||
@@ -688,6 +688,7 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
MsgsSearchLabel: "Search translations",
|
||||
MsgsSearchPlaceholder: "Code, English or Chinese",
|
||||
MsgsMissingChineseFilter: "Missing Chinese",
|
||||
MsgsOwnLabelsFilter: "Co-Lite labels only",
|
||||
MsgsBadgeMissing: "Missing",
|
||||
MsgsBadgeSameAsEnglish: "Same as English",
|
||||
MsgsEmpty: "No translations yet.",
|
||||
|
||||
@@ -674,6 +674,7 @@
|
||||
"MsgsSearchLabel": "搜索翻译",
|
||||
"MsgsSearchPlaceholder": "代码、英文或中文",
|
||||
"MsgsMissingChineseFilter": "缺少中文",
|
||||
"MsgsOwnLabelsFilter": "仅 Co-Lite 标签",
|
||||
"MsgsBadgeMissing": "缺少",
|
||||
"MsgsBadgeSameAsEnglish": "与英文相同",
|
||||
"MsgsEmpty": "还没有翻译。",
|
||||
|
||||
@@ -25,8 +25,9 @@ export const updateLocale = (id: number, patch: Partial<Pick<LocaleRow, "label"
|
||||
apiPut<LocaleRow>(`/api/locales/${id}`, patch);
|
||||
|
||||
/** `page` is 1-based like the other list pages; mobile-api is 0-based. */
|
||||
export async function listMessages(p: { searchKey?: string; missingChinese?: boolean; page: number; pageSize: number }) {
|
||||
export async function listMessages(p: { searchKey?: string; missingChinese?: boolean; ownOnly?: boolean; page: number; pageSize: number }) {
|
||||
const qs = new URLSearchParams();
|
||||
if (p.ownOnly) qs.set("own", "1");
|
||||
if (p.searchKey) qs.set("searchKey", p.searchKey);
|
||||
if (p.missingChinese) qs.set("missingLocale", "zh_CN");
|
||||
qs.set("page", String(Math.max(0, p.page - 1)));
|
||||
|
||||
@@ -57,6 +57,18 @@ describe("MessagesPage", () => {
|
||||
await waitFor(() => expect(lastListCall()).toContain(`searchKey=${encodeURIComponent("线索")}`));
|
||||
});
|
||||
|
||||
it("lists only Co-Lite labels by default, and every label once unchecked", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MessagesPage />);
|
||||
await screen.findByText("线索");
|
||||
expect(lastListCall()).toContain("own=1");
|
||||
const own = screen.getByRole("checkbox", { name: /co-lite labels only/i });
|
||||
expect(own).toBeChecked();
|
||||
await user.click(own);
|
||||
await waitFor(() => expect(lastListCall()).not.toContain("own="));
|
||||
expect(lastListCall()).toContain("page=0");
|
||||
});
|
||||
|
||||
it("edits Chinese and saves the content to the row's id, keeping other languages", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MessagesPage />);
|
||||
|
||||
@@ -22,7 +22,8 @@ import { MessageEditSheet } from "./MessageEditSheet";
|
||||
|
||||
// /messages, ported from babyboo and trimmed to back-office labels (area A): no area filter, no add, no delete.
|
||||
// Labels arrive with releases; staff only translate them.
|
||||
const DEFAULTS = { q: "", missing: "" };
|
||||
// all="1" lists inherited Tastefully labels too; the default lists only the portal's own labels.
|
||||
const DEFAULTS = { q: "", missing: "", all: "" };
|
||||
|
||||
function MessagesPageContent() {
|
||||
const t = useT();
|
||||
@@ -46,7 +47,7 @@ function MessagesPageContent() {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error ahead of the fetch below.
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
listMessages({ searchKey: filters.q || undefined, missingChinese: filters.missing === "zh_CN", page, pageSize })
|
||||
listMessages({ searchKey: filters.q || undefined, missingChinese: filters.missing === "zh_CN", ownOnly: filters.all !== "1", page, pageSize })
|
||||
.then((result) => !cancelled && setData(result))
|
||||
.catch((err: unknown) => !cancelled && setError(err instanceof Error ? err.message : "MsgsLoadFailed"))
|
||||
.finally(() => !cancelled && setLoading(false));
|
||||
@@ -139,6 +140,10 @@ function MessagesPageContent() {
|
||||
<Checkbox checked={filters.missing === "zh_CN"} onCheckedChange={(on) => set({ missing: on === true ? "zh_CN" : "" })} />
|
||||
{t("MsgsMissingChineseFilter")}
|
||||
</label>
|
||||
<label className="flex items-center gap-2 self-end pb-2 text-sm">
|
||||
<Checkbox checked={filters.all !== "1"} onCheckedChange={(on) => set({ all: on === true ? "" : "1" })} />
|
||||
{t("MsgsOwnLabelsFilter")}
|
||||
</label>
|
||||
</FilterPanel>
|
||||
<DataTable
|
||||
label={t("MsgsTitle")}
|
||||
|
||||
+26
@@ -1,11 +1,13 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
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.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
@@ -27,6 +29,7 @@ import java.util.Map;
|
||||
@RequestMapping("/api/admin")
|
||||
@RequiredArgsConstructor
|
||||
public class AdminMessageController {
|
||||
private static final int MAX_CODES = 5000;
|
||||
private final AdminTranslationService translations;
|
||||
private final SystemService systemService;
|
||||
|
||||
@@ -52,6 +55,29 @@ public class AdminMessageController {
|
||||
return ResponseEntity.ok(translations.search(searchKey, missingLocale, page, size));
|
||||
}
|
||||
|
||||
/** Same as the list, plus an optional code list; a POST because the portal sends its ~700 label codes. */
|
||||
@AppAuth
|
||||
@AdminModule("BO_MESSAGES")
|
||||
@PostMapping("/messages/search")
|
||||
public ResponseEntity<Map<String, Object>> search(@RequestBody Map<String, Object> body) {
|
||||
Object codes = body.get("codes");
|
||||
if (codes != null && !(codes instanceof List<?> list && list.size() <= MAX_CODES && list.stream().allMatch(String.class::isInstance))) {
|
||||
throw new CodedResponseStatusException(HttpStatus.BAD_REQUEST, "codes must be a list of at most " + MAX_CODES + " strings", "MsgsInvalidCodes");
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
List<String> codeList = (List<String>) codes;
|
||||
return ResponseEntity.ok(translations.search(text(body.get("searchKey")), text(body.get("missingLocale")),
|
||||
number(body.get("page"), 0), number(body.get("size"), 20), codeList));
|
||||
}
|
||||
|
||||
private static String text(Object v) {
|
||||
return v instanceof String s ? s : null;
|
||||
}
|
||||
|
||||
private static int number(Object v, int fallback) {
|
||||
return v instanceof Number n ? n.intValue() : fallback;
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_MESSAGES")
|
||||
@Audited(action = "MESSAGES_EXPORT")
|
||||
|
||||
+6
@@ -65,7 +65,13 @@ public class AdminTranslationService {
|
||||
}
|
||||
|
||||
public Map<String, Object> search(String searchKey, String missingLocale, int page, int size) {
|
||||
return search(searchKey, missingLocale, page, size, null);
|
||||
}
|
||||
|
||||
/** codes, when set, limits the list to those codes (ignoring case); null lists every area-A label. */
|
||||
public Map<String, Object> search(String searchKey, String missingLocale, int page, int size, List<String> codes) {
|
||||
Map<String, Object> req = new HashMap<>();
|
||||
req.put("codes", codes);
|
||||
req.put("searchKey", searchKey);
|
||||
req.put("missingLocale", missingLocale);
|
||||
req.put("area", AREA);
|
||||
|
||||
+29
-1
@@ -16,6 +16,7 @@ import org.springframework.web.bind.annotation.PostMapping;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -23,8 +24,10 @@ 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.verifyNoInteractions;
|
||||
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.post;
|
||||
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;
|
||||
@@ -59,7 +62,7 @@ class AdminTranslationControllersTest {
|
||||
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();
|
||||
|| (m.isAnnotationPresent(PostMapping.class) && !List.of("importMessages", "search").contains(m.getName())))).isEmpty();
|
||||
assertThat(AdminMessageController.class.getMethod("export").getAnnotation(Audited.class)).isNotNull();
|
||||
}
|
||||
|
||||
@@ -69,6 +72,31 @@ class AdminTranslationControllersTest {
|
||||
mvc.perform(get("/api/admin/messages").param("missingLocale", "zh_CN")).andExpect(status().isOk()).andExpect(jsonPath("$.totalElements").value(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void searchPassesTheCodesAndFilters() throws Exception {
|
||||
when(translations.search("lead", "zh_CN", 1, 50, List.of("Leads", "Users"))).thenReturn(Map.of("content", List.of(), "totalElements", 2));
|
||||
mvc.perform(post("/api/admin/messages/search").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"searchKey\":\"lead\",\"missingLocale\":\"zh_CN\",\"page\":1,\"size\":50,\"codes\":[\"Leads\",\"Users\"]}"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.totalElements").value(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void searchWithoutCodesListsEveryLabel() throws Exception {
|
||||
when(translations.search(null, null, 0, 20, null)).thenReturn(Map.of("content", List.of(), "totalElements", 9));
|
||||
mvc.perform(post("/api/admin/messages/search").contentType(MediaType.APPLICATION_JSON).content("{}"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.totalElements").value(9));
|
||||
}
|
||||
|
||||
@Test
|
||||
void searchRefusesABadCodeList() throws Exception {
|
||||
String tooMany = "[" + String.join(",", Collections.nCopies(5001, "\"A\"")) + "]";
|
||||
for (String codes : List.of(tooMany, "\"Leads\"", "[1,2]", "[null]")) {
|
||||
mvc.perform(post("/api/admin/messages/search").contentType(MediaType.APPLICATION_JSON).content("{\"codes\":" + codes + "}"))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
verifyNoInteractions(translations);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUsesThePathId() throws Exception {
|
||||
mvc.perform(put("/api/admin/messages/7").contentType(MediaType.APPLICATION_JSON).content("{\"id\":9,\"content\":\"{}\"}"))
|
||||
|
||||
+12
@@ -91,6 +91,18 @@ class AdminTranslationServiceTest {
|
||||
.containsEntry("area", "A").containsEntry("page", 2).containsEntry("size", 20);
|
||||
}
|
||||
|
||||
@Test
|
||||
void searchForwardsTheCodes() {
|
||||
when(rest.postForEntity(eq("/message/search"), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(Map.of("content", List.of(), "totalElements", 0)));
|
||||
|
||||
service.search(null, null, 0, 20, List.of("Leads"));
|
||||
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq("/message/search"), any(ParameterizedTypeReference.class), body.capture());
|
||||
assertThat((Map<String, Object>) body.getValue()).containsEntry("codes", List.of("Leads")).containsEntry("area", "A");
|
||||
}
|
||||
|
||||
@Test
|
||||
void importMatchesByCodeIgnoringCaseNeverByIdAndKeepsGoingAfterAFailure() {
|
||||
when(rest.getForEntity(eq("/message/getAllMessages/{area}"), any(ParameterizedTypeReference.class), eq("A")))
|
||||
|
||||
+4
-1
@@ -4,13 +4,16 @@ 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. */
|
||||
import java.util.List;
|
||||
|
||||
/** Translations search: searchKey over the code, English and Chinese text; missingLocale lists labels lacking that language; codes, when set, limits to those codes ignoring case. */
|
||||
@Getter
|
||||
@Setter
|
||||
public class MessageSearchRequest {
|
||||
private String searchKey;
|
||||
private Area area;
|
||||
private String missingLocale;
|
||||
private List<String> codes;
|
||||
private int page;
|
||||
private int size;
|
||||
}
|
||||
+6
@@ -24,6 +24,8 @@ import java.util.Objects;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class MessageService {
|
||||
@@ -86,8 +88,12 @@ public class MessageService {
|
||||
List<Message> 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();
|
||||
Set<String> codes = req.getCodes() == null ? null : req.getCodes().stream().map(MessageService::lower).collect(Collectors.toSet());
|
||||
List<Message> hits = new ArrayList<>();
|
||||
for (Message m : rows) {
|
||||
if (codes != null && !codes.contains(lower(m.getCode()))) {
|
||||
continue;
|
||||
}
|
||||
Map<String, String> 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;
|
||||
|
||||
+17
@@ -85,6 +85,23 @@ class MessageServiceTranslationsTest {
|
||||
assertThat(codes(page)).containsExactly("A3");
|
||||
}
|
||||
|
||||
@Test
|
||||
void codesLimitTheListIgnoringCaseAndCombineWithTheOtherFilters() {
|
||||
when(repository.findAllByArea(Area.A)).thenReturn(List.of(
|
||||
msg(1, "Leads", "Leads", "线索"), msg(2, "OrderPayment", "Order payment", null), msg(3, "Users", "Users", null)));
|
||||
|
||||
MessageSearchRequest own = req(null, null, 0, 10);
|
||||
own.setCodes(List.of("leads", "USERS"));
|
||||
assertThat(codes(service.search(own))).containsExactly("Leads", "Users");
|
||||
|
||||
own.setMissingLocale("zh_CN");
|
||||
Page<Message> missing = service.search(own);
|
||||
assertThat(codes(missing)).containsExactly("Users");
|
||||
assertThat(missing.getTotalElements()).isEqualTo(1);
|
||||
|
||||
assertThat(codes(service.search(req(null, "zh_CN", 0, 10)))).containsExactly("OrderPayment", "Users");
|
||||
}
|
||||
|
||||
@Test
|
||||
void savingAnExistingLabelBumpsTheVersion() {
|
||||
Message stored = msg(7, "Leads", "Leads", "线索");
|
||||
|
||||
Reference in new issue
Block a user