diff --git a/apps/api/backend/plugin/dict/api/v1/sys/dict_data.py b/apps/api/backend/plugin/dict/api/v1/sys/dict_data.py index 7a2425cd..e17fe9ec 100644 --- a/apps/api/backend/plugin/dict/api/v1/sys/dict_data.py +++ b/apps/api/backend/plugin/dict/api/v1/sys/dict_data.py @@ -2,6 +2,7 @@ from fastapi import APIRouter, BackgroundTasks, Depends, File, Path, Query, Request, UploadFile from fastapi.responses import Response +from pydantic import Field from backend.app.admin.schema.data_import import ( ImportCommitDetail, @@ -15,6 +16,7 @@ from backend.common.pagination import DependsPagination, PageData from backend.common.response.response_schema import ResponseModel, ResponseSchemaModel, response_base from backend.common.schema import SnowflakeIdIn +from backend.common.security.jwt import DependsJwtAuth from backend.common.security.permission import RequestPermission from backend.common.security.rbac import DependsRBAC from backend.database.db import CurrentSession, CurrentSessionTransaction @@ -23,6 +25,7 @@ CreateDictDataParam, DeleteDictDataParam, GetDictDataDetail, + GetDictOption, UpdateDictDataParam, ) from backend.plugin.dict.service.dict_data_service import dict_data_service @@ -44,6 +47,27 @@ async def get_all_dict_datas(db: CurrentSession) -> ResponseSchemaModel[list[Get return response_base.success(data=data) +@router.get( + '/options', + summary='批量获取字典选项(登录即可)', + description=( + '给下拉 / 标签用:只返回启用的选项、按排序升序;请求的每个编码都有一个键,没有选项的是空数组。' + '不要求字典管理权限 —— 普通页面的下拉得能读到它自己用的字典;字典**管理**接口照旧要 `dict:data:*`' + ), + dependencies=[DependsJwtAuth], +) +async def get_dict_options( + db: CurrentSession, + codes: Annotated[ + list[Annotated[str, Field(min_length=1, max_length=32)]], + Query(min_length=1, max_length=20, description='字典类型编码,可重复传多个(最多 20 个)'), + ], +) -> ResponseSchemaModel[dict[str, list[GetDictOption]]]: + # 🔴 必须声明在 `/{pk}` 之前:单段路径放在它后面会被当成 pk 解析,报 422「不是合法整数」 + data = await dict_data_service.get_options(db=db, codes=codes) + return response_base.success(data=data) + + @router.get( '/import/template', summary='下载字典数据导入模板', diff --git a/apps/api/backend/plugin/dict/crud/crud_dict_data.py b/apps/api/backend/plugin/dict/crud/crud_dict_data.py index 87ae5a92..be329fd0 100644 --- a/apps/api/backend/plugin/dict/crud/crud_dict_data.py +++ b/apps/api/backend/plugin/dict/crud/crud_dict_data.py @@ -43,6 +43,28 @@ async def get_by_type_code(self, db: AsyncSession, type_code: str) -> Sequence[D deleted=0, ) + async def get_options_by_type_codes(self, db: AsyncSession, type_codes: Sequence[str]) -> Sequence[DictData]: + """ + 给前端下拉 / 标签用的选项,**一条查询取多个类型**:只要启用的,按 `sort` **升序**(同值按 id,保证顺序稳定)。 + 调用方按 `type_code` 分组,组内顺序就是这里的顺序 + + ⚠️ 和 `get_by_type_code` 刻意不同:那个是上游遗留的 `sort` 降序,而字典管理页的分页列表是升序, + 下拉照它的顺序排就会和管理员在字典页看到的相反。老接口没有前端消费者,但不动它 —— + 改了会让装了这个插件的下游静默换顺序 + + :param db: 数据库会话 + :param type_codes: 字典类型编码 + :return: + """ + return await self.select_models_order( + db, + sort_columns=['sort', 'id'], + sort_orders=['asc', 'asc'], + type_code__in=list(type_codes), + status=StatusType.enable.value, + deleted=0, + ) + async def get_all(self, db: AsyncSession) -> Sequence[DictData]: """ 获取所有字典数据 diff --git a/apps/api/backend/plugin/dict/schema/dict_data.py b/apps/api/backend/plugin/dict/schema/dict_data.py index 4f30eb5d..59a20a82 100644 --- a/apps/api/backend/plugin/dict/schema/dict_data.py +++ b/apps/api/backend/plugin/dict/schema/dict_data.py @@ -37,6 +37,14 @@ class DeleteDictDataParam(SchemaBase): pks: list[int] = Field(description='字典数据 ID 列表') +class GetDictOption(SchemaBase): + """字典选项(给前端下拉 / 标签用,只带展示要用的字段)""" + + label: str = Field(description='字典标签') + value: str = Field(description='字典值(永远是字符串,数字类的字典也是)') + color: str | None = Field(None, description='标签颜色') + + class GetDictDataDetail(DictDataSchemaBase): """字典数据详情""" diff --git a/apps/api/backend/plugin/dict/service/dict_data_service.py b/apps/api/backend/plugin/dict/service/dict_data_service.py index f4ea6b5c..64aa0b4a 100644 --- a/apps/api/backend/plugin/dict/service/dict_data_service.py +++ b/apps/api/backend/plugin/dict/service/dict_data_service.py @@ -1,13 +1,17 @@ from collections.abc import Sequence from typing import Any +from msgspec import json as msgjson from sqlalchemy.ext.asyncio import AsyncSession from backend.common.cache.decorator import cache_invalidate, cached +from backend.common.cache.local import local_cache_manager from backend.common.exception import errors from backend.common.i18n import t +from backend.common.log import log from backend.common.pagination import paging_data from backend.core.conf import settings +from backend.database.redis import redis_client from backend.plugin.dict.crud.crud_dict_data import dict_data_dao from backend.plugin.dict.crud.crud_dict_type import dict_type_dao from backend.plugin.dict.model import DictData, DictType @@ -50,6 +54,82 @@ async def get_by_type_code(*, db: AsyncSession, code: str) -> Sequence[DictData] raise errors.NotFoundError(msg=t('error.dict.data_not_found')) return dict_datas + @staticmethod + async def get_options(*, db: AsyncSession, codes: Sequence[str]) -> dict[str, list[dict[str, str | None]]]: + """ + 批量取字典选项(`GET /dict-datas/options`):每个请求的编码都有一个键,没有选项的是 `[]` + + 和 `get_by_type_code` 的区别:后者对空 / 不存在 / 全停用一律抛 404,调用方分不出是哪一种, + 而「这个字典还没有选项」对一个下拉来说是正常状态(显示「暂无选项」),不是错误 + + 缓存(键 `:options:<编码>`,和 `@cached` 同一套 L1 + Redis、同样的序列化): + 本地缓存 → Redis `MGET` → **剩下没命中的编码合成一条 `IN` 查询**。不套 `@cached` 逐个调,是因为那样冷缓存时 + 20 个编码就是 20 次串行查询,而查无的编码(下面那条)每次请求都要重查 —— 任何登录用户反复请求 20 个乱写的编码, + 每次都是 20 条 SQL;合成一条之后最多一条。 + + 🔴 **查无(类型不存在 / 没有启用的项)的编码不写缓存。** 这个接口任何登录用户都能调、编码随便填, + 缓存空列表就等于让他往 Redis 里刷任意多个 `options:<随便写>` 键(每个活两小时)。 + 键在 `CACHE_DICT_REDIS_PREFIX` 命名空间下,字典数据 / 类型的增删改和导入 + 整个命名空间一起清(含提交之后那次),不用另接失效 + + :param db: 数据库会话 + :param codes: 字典类型编码 + :return: + """ + wanted = list(dict.fromkeys(codes)) # 去重、保序 + keys = {code: f'{settings.CACHE_DICT_REDIS_PREFIX}:options:{code}' for code in wanted} + found = await DictDataService._read_cached_options(keys) + missing = [code for code in wanted if code not in found] + if missing: + found.update(await DictDataService._load_and_cache_options(db, missing, keys)) + return {code: found.get(code, []) for code in wanted} + + @staticmethod + async def _read_cached_options(keys: dict[str, str]) -> dict[str, list[dict[str, str | None]]]: + """先本地缓存,剩下的一次 Redis `MGET`;Redis 出错按未命中处理(同 `@cached`)""" + found: dict[str, list[dict[str, str | None]]] = {} + if settings.CACHE_LOCAL_ENABLED: + for code, key in keys.items(): + value = local_cache_manager.get(key) + if value is not None: + found[code] = value + rest = [code for code in keys if code not in found] + if not rest: + return found + try: + raw = await redis_client.mget([keys[code] for code in rest]) + except Exception as e: + log.warning(f'[Cache] MGET error: {e}') + return found + for code, value in zip(rest, raw, strict=True): + if value is None: + continue + found[code] = msgjson.decode(value) + if settings.CACHE_LOCAL_ENABLED: + local_cache_manager.set(keys[code], found[code]) + return found + + @staticmethod + async def _load_and_cache_options( + db: AsyncSession, missing: list[str], keys: dict[str, str] + ) -> dict[str, list[dict[str, str | None]]]: + """没命中的编码合成**一条** `IN` 查询;只回填真有选项的编码(查无的不写缓存,见 `get_options`)""" + grouped: dict[str, list[dict[str, str | None]]] = {} + for row in await dict_data_dao.get_options_by_type_codes(db, missing): + grouped.setdefault(row.type_code, []).append({'label': row.label, 'value': row.value, 'color': row.color}) + for code, items in grouped.items(): + try: + encoded = msgjson.encode(items) + if settings.CACHE_REDIS_TTL: + await redis_client.set(keys[code], encoded, ex=settings.CACHE_REDIS_TTL) + else: + await redis_client.set(keys[code], encoded) + if settings.CACHE_LOCAL_ENABLED: + local_cache_manager.set(keys[code], items) + except Exception as e: + log.warning(f'[Cache] SET error: {e}') + return grouped + @staticmethod async def get_all(*, db: AsyncSession) -> Sequence[DictData]: """ diff --git a/apps/api/backend/plugin/dict/tests/test_dict_options.py b/apps/api/backend/plugin/dict/tests/test_dict_options.py new file mode 100644 index 00000000..188fb286 --- /dev/null +++ b/apps/api/backend/plugin/dict/tests/test_dict_options.py @@ -0,0 +1,226 @@ +"""`GET /sys/dict-datas/options`:给前端下拉 / 标签读字典用的「登录即可」批量接口。 + +原来前端读字典值只有 `/type-codes/{code}` 一条路,它挂着 `dict:data:list`、空类型 / 不存在 / 全停用一律 404、 +还按 `sort` **降序**返回 —— 普通用户的下拉读不到,管理员在字典页看到的顺序和下拉相反(2026-11-26 实测, +见 `packages/platform/src/pages/_shared/AGENTS.md` 的「字典」一节)。这里钉住新接口的形状。 +""" + +import uuid + +from collections.abc import Iterator +from typing import Self + +import pytest +import sqlalchemy as sa + +from starlette.testclient import TestClient + +from backend.core.conf import settings +from backend.database.redis import redis_client +from backend.plugin.dict.model import DictData, DictType +from backend.tests.utils.data_change import engine + +_RUN = uuid.uuid4().hex[:8] +TYPES = '/sys/dict-types' +DATAS = '/sys/dict-datas' +FULL = f'op{_RUN}' # 有四个启用项(其中两个同 sort)+ 一个停用项 +EMPTY = f'oe{_RUN}' # 类型存在、没有任何项 +OFF = f'of{_RUN}' # 只有停用项 +GHOST = f'og{_RUN}' # 根本不存在的类型 +ALL_CODES = (FULL, EMPTY, OFF, GHOST) + + +def _login(client: TestClient, username: str, password: str = '123456') -> dict[str, str]: + resp = client.post('/auth/login/swagger', params={'username': username, 'password': password}) + resp.raise_for_status() + body = resp.json() + return {'Authorization': f'{body["token_type"]} {body["access_token"]}'} + + +def _options(client: TestClient, headers: dict[str, str] | None, *codes: str): + return client.get(f'{DATAS}/options', headers=headers, params={'codes': list(codes)}) + + +def _key(code: str) -> str: + return f'{settings.CACHE_DICT_REDIS_PREFIX}:options:{code}' + + +@pytest.fixture(autouse=True) +def _purge(client: TestClient) -> Iterator[None]: + yield + for code in ALL_CODES: + client.portal.call(redis_client.delete, _key(code)) + with engine().begin() as conn: + conn.execute(sa.delete(DictData.__table__).where(DictData.__table__.c.type_code.in_(ALL_CODES))) + conn.execute(sa.delete(DictType.__table__).where(DictType.__table__.c.code.in_(ALL_CODES))) + + +@pytest.fixture +def seeded(client: TestClient, token_headers: dict[str, str]) -> dict[str, str]: + """造三类数据,返回 {编码: 类型 id}。项故意不按 sort 顺序创建,才能证明排序不是插入顺序""" + ids: dict[str, str] = {} + for code in (FULL, EMPTY, OFF): + assert ( + client.post(TYPES, headers=token_headers, json={'name': f'选项{code}', 'code': code}).json()['code'] == 200 + ) + ids[code] = client.get(TYPES, headers=token_headers, params={'code': code}).json()['data']['items'][0]['id'] + + def add(code: str, label: str, value: str, sort: int, status: int = 1, color: str | None = None) -> None: + body = {'type_id': ids[code], 'label': label, 'value': value, 'sort': sort, 'status': status, 'color': color} + assert client.post(DATAS, headers=token_headers, json=body).json()['code'] == 200 + + add(FULL, '丙', '3', 3, color='green') + add(FULL, '甲', '1', 1) + add(FULL, '乙停用', '2', 2, status=0) + add(FULL, '乙', '22', 2) + add(FULL, '乙二', '23', 2) # 和「乙」同 sort:靠 id 兜底,先创建的在前 + add(OFF, '全停用', '1', 1, status=0) + return ids + + +def test_a_user_without_dict_permission_can_read_options( + client: TestClient, token_headers: dict[str, str], seeded: dict[str, str] +) -> None: + """STAFF 没有任何 `dict:data:*`:管理接口 403(对照组),选项接口 200 —— 普通页面的下拉就靠这个""" + staff = _login(client, 'test') + assert client.get(DATAS, headers=staff).status_code == 403, '前提:管理接口照旧要权限' + assert client.get(f'{DATAS}/type-codes/{FULL}', headers=staff).status_code == 403, '前提:老的读接口也要权限' + + resp = _options(client, staff, FULL) + assert resp.status_code == 200, resp.text + assert [o['label'] for o in resp.json()['data'][FULL]] == ['甲', '乙', '乙二', '丙'] + + +def test_options_require_login(client: TestClient, seeded: dict[str, str]) -> None: + assert _options(client, None, FULL).status_code in (401, 403) + + +def test_options_are_ascending_enabled_only_and_carry_only_display_fields( + client: TestClient, token_headers: dict[str, str], seeded: dict[str, str] +) -> None: + # 先改一下「乙」:PostgreSQL 的 UPDATE 会把行挪到堆的后面,没有 id 兜底时同 sort 的两项就会反过来 —— + # 不这么做的话,数据库恰好按插入顺序吐出来,去掉兜底测试也照绿(变异实测过) + yi = client.get(DATAS, headers=token_headers, params={'type_code': FULL, 'label': '乙'}).json()['data']['items'] + yi = next(i for i in yi if i['label'] == '乙') + upd = {'type_id': seeded[FULL], 'label': '乙', 'value': '22', 'sort': 2, 'status': 1, 'color': 'primary'} + assert client.put(f'{DATAS}/{yi["id"]}', headers=token_headers, json=upd).json()['code'] == 200 + + data = _options(client, token_headers, FULL).json()['data'][FULL] + # sort 升序(和字典页分页列表一致);同 sort 的「乙」「乙二」按 id —— 创建顺序在前的在前 + assert [(o['label'], o['value']) for o in data] == [('甲', '1'), ('乙', '22'), ('乙二', '23'), ('丙', '3')] + assert 'status' not in data[0] and 'remark' not in data[0] and 'id' not in data[0], '只下发展示要用的字段' + assert data[3]['color'] == 'green' and data[0]['color'] is None + + # 对照:老接口是降序 —— 新接口存在的理由之一 + old = client.get(f'{DATAS}/type-codes/{FULL}', headers=token_headers).json()['data'] + assert [old[0]['label'], old[-1]['label']] == ['丙', '甲'] + + +def test_missing_empty_and_all_disabled_types_are_an_empty_list_not_404( + client: TestClient, token_headers: dict[str, str], seeded: dict[str, str] +) -> None: + resp = _options(client, token_headers, EMPTY, OFF, GHOST) + assert resp.status_code == 200, resp.text + assert resp.json()['data'] == {EMPTY: [], OFF: [], GHOST: []} + # 对照:老接口对这三种都是 404,调用方分不出区别 + for code in (EMPTY, OFF, GHOST): + assert client.get(f'{DATAS}/type-codes/{code}', headers=token_headers).json()['code'] == 404 + + +def test_multiple_codes_in_one_request_keep_a_key_each_and_dedupe( + client: TestClient, token_headers: dict[str, str], seeded: dict[str, str] +) -> None: + data = _options(client, token_headers, FULL, EMPTY, FULL).json()['data'] + assert list(data) == [FULL, EMPTY] + assert len(data[FULL]) == 4 and data[EMPTY] == [] + + +@pytest.mark.parametrize( + 'codes', + [[], [f'c{i}' for i in range(21)], ['x' * 33], ['']], + ids=['零个', '21个', '编码33位', '空串'], +) +def test_bad_code_lists_are_rejected(client: TestClient, token_headers: dict[str, str], codes: list[str]) -> None: + assert _options(client, token_headers, *codes).status_code == 422 + + +def test_unknown_codes_do_not_write_cache_keys( + client: TestClient, token_headers: dict[str, str], seeded: dict[str, str] +) -> None: + """🔴 任何登录用户都能调、编码随便填:查无的不能缓存,否则他能往 Redis 里刷任意多个键""" + _options(client, token_headers, FULL, EMPTY, OFF, GHOST) + assert client.portal.call(redis_client.exists, _key(FULL)), '前提:有选项的类型会缓存(不然下面的断言证明不了什么)' + for code in (EMPTY, OFF, GHOST): + assert not client.portal.call(redis_client.exists, _key(code)), f'{code} 不该有缓存键' + + +def test_writes_to_items_and_types_show_up_in_the_next_read( + client: TestClient, token_headers: dict[str, str], seeded: dict[str, str] +) -> None: + """缓存键在字典命名空间下,增 / 改 / 删都整个命名空间一起清 —— 先焐热再改,断言读到新值""" + assert len(_options(client, token_headers, FULL).json()['data'][FULL]) == 4 # 焐热 + + # 新增 + body = {'type_id': seeded[FULL], 'label': '丁', 'value': '4', 'sort': 4, 'status': 1} + assert client.post(DATAS, headers=token_headers, json=body).json()['code'] == 200 + assert [o['label'] for o in _options(client, token_headers, FULL).json()['data'][FULL]] == [ + '甲', + '乙', + '乙二', + '丙', + '丁', + ] + + # 停用一项 + jia = client.get(DATAS, headers=token_headers, params={'type_code': FULL, 'label': '甲'}).json()['data']['items'][0] + upd = {'type_id': seeded[FULL], 'label': '甲', 'value': '1', 'sort': 1, 'status': 0} + assert client.put(f'{DATAS}/{jia["id"]}', headers=token_headers, json=upd).json()['code'] == 200 + assert [o['label'] for o in _options(client, token_headers, FULL).json()['data'][FULL]] == [ + '乙', + '乙二', + '丙', + '丁', + ] + + # 删类型:选项跟着没 + assert client.request('DELETE', TYPES, headers=token_headers, json={'pks': [seeded[FULL]]}).json()['code'] == 200 + assert _options(client, token_headers, FULL).json()['data'] == {FULL: []} + + +class _CountDictSql: + """数这次请求里真正发到数据库、碰了 `sys_dict_data` 的语句(引擎级事件,异步引擎底下的同步引擎也算)""" + + def __init__(self) -> None: + self.statements: list[str] = [] + + def _on(self, _conn, _cursor, statement, _params, _context, _executemany) -> None: + if 'sys_dict_data' in statement: + self.statements.append(statement) + + def __enter__(self) -> Self: + sa.event.listen(sa.engine.Engine, 'before_cursor_execute', self._on) + return self + + def __exit__(self, *_exc: object) -> None: + sa.event.remove(sa.engine.Engine, 'before_cursor_execute', self._on) + + +def test_twenty_unknown_codes_cost_one_query(client: TestClient, token_headers: dict[str, str]) -> None: + """🔴 查无的编码不进缓存,所以每次都要查库 —— 逐个查的话 20 个乱写的编码就是 20 条 SQL,任何登录用户都能反复刷""" + ghosts = [f'gz{_RUN}{i}' for i in range(20)] + with _CountDictSql() as sql: + resp = _options(client, token_headers, *ghosts) + assert resp.status_code == 200, resp.text + assert resp.json()['data'] == {c: [] for c in ghosts} + assert len(sql.statements) == 1, f'应该合成一条 IN 查询,实际 {len(sql.statements)} 条' + + +def test_a_fully_cached_request_does_not_touch_the_table( + client: TestClient, token_headers: dict[str, str], seeded: dict[str, str] +) -> None: + first = _options(client, token_headers, FULL).json()['data'][FULL] # 焐热 + assert first, '前提:有选项(不然没有东西可缓存)' + with _CountDictSql() as sql: + again = _options(client, token_headers, FULL).json()['data'][FULL] + assert again == first + assert sql.statements == [], f'命中缓存还查了库:{sql.statements}' diff --git a/apps/docs/src/content/docs/en/features/config-dict.mdx b/apps/docs/src/content/docs/en/features/config-dict.mdx index dce8f05f..4bcab561 100644 --- a/apps/docs/src/content/docs/en/features/config-dict.mdx +++ b/apps/docs/src/content/docs/en/features/config-dict.mdx @@ -60,9 +60,30 @@ Two levels: - **Dictionary type**: name, code (unique), remark. - **Dictionary item**: its type's code, label, value, colour, sort order, status (normal / disabled), remark. Labels are unique within a type. -Business code fetches a type's options with `GET /api/v1/sys/dict-datas/type-codes/{code}`, which returns only enabled items, sorted by sort order **descending**; the result is cached in Redis for 2 hours and the cache is cleared when items change. Items can be [imported and exported](/en/features/import-export/), matched to existing items by type code + label. +### How does a business page read a dictionary? -⚠️ **None of the built-in pages read the dictionary yet**: labels like notice type or status are hard-coded in each page, and only the dictionary page itself calls the dictionary API. The dictionary is there for your own business pages, and the frontend has no ready-made "fetch a dictionary type" hook yet. +The frontend has three things in `_shared/dict.tsx`; you only pass the dictionary type code: + +```tsx +import { DictSelect, DictTag, useDict } from '../_shared/dict' + + {/* in a table: value → coloured tag */} + {/* form dropdown, the value is a string */} +const level = useDict('crm_level') // when you need the options yourself: level.options / level.labelOf(value) +``` + +They call `GET /api/v1/sys/dict-datas/options?codes=a&codes=b`: + +- **Sign-in is enough, no dictionary-management permission needed.** An ordinary page's dropdown must be able to read the dictionary it uses; the dictionary **management** endpoints still require `dict:data:*`. +- Up to 20 codes per request, and every code gets a key: **a type with no options returns `[]`, not 404** (the old endpoint returns 404 for "no such type", "type is empty" and "all items disabled" alike, so the caller cannot tell them apart). +- Only enabled items, sorted by sort order **ascending**, the same order the dictionary page shows. If a type has items with the same value (only labels are unique in the database), the frontend keeps the one sorted first. +- The result is cached in Redis for 2 hours, and adding, editing, deleting or importing items and editing or deleting types clears it. Codes that match nothing are not cached, so a caller cannot fill Redis with made-up codes; codes missing from the cache are fetched in a single query, so one request hits the database at most once. + +The old `GET /api/v1/sys/dict-datas/type-codes/{code}` is still there, but it needs the `dict:data:list` permission, returns 404 for an empty type and sorts **descending**; business pages should not use it. Items can be [imported and exported](/en/features/import-export/), matched to existing items by type code + label. + +⚠️ **Use the dictionary for enums that operators maintain themselves** (customer level, ticket category, …). The built-in pages' menu type, sign-in status and data-rule operators are **tied to enums in the backend code**; changing the dictionary would not change the backend, so they are not wired to it and stay in the page. + +⚠️ When loading fails, `DictTag` shows the raw value (dotted underline, click to retry) and `DictSelect` is disabled with "Failed to load · Retry" — never a blank. A value the dictionary does not have (item disabled or deleted, but still in old data) is shown as a grey tag with the raw value. ## Which settings are there? @@ -83,19 +104,22 @@ Rules and pitfalls are in [`pages/config/AGENTS.md`](https://github.com/yile2020 - **Password-like values are only hidden on screen**: keys whose name looks like a secret, such as the email password, are shown in a password box that can be revealed, but the API returns them in plain text, so anyone who can open the Config page can read them. Data change history records only that they changed, not the value. - Keys you add yourself have no validation and no generic accessor; the "visible to frontend" flag has no effect in the backend. -- Editing or deleting a dictionary **type** does not clear the dictionary cache, so the change can take up to 2 hours to show; changing a type's code does not update its items' type code. -- The dictionary page's colour options don't match the colours used in the seed data, so some seeded items show the default style. +- The dictionary has no "built-in, read-only" flag: an admin can delete or change seeded items (such as "Normal" in "General status"). No built-in page depends on them, but once your own business page reads one, a deleted value shows as a grey raw value. +- A label is one piece of Chinese text in the database; the English UI translates it by that text through the language pack: translated if the pack has that exact text, not translated if an admin typed it. +- **No per-type control over who can read**: any signed-in user can read every dictionary's labels and values through the endpoint above (the dictionary **management** endpoints still require permissions). Don't put categories that only some people should see in the dictionary. +- The dictionary page lets you pick only 7 canonical colours (default, primary, success, info, warning, danger, grey). The Ant Design colour names used in the seed data (`green`, `processing`, `magenta`, …) are mapped to these by meaning on the frontend, without changing what is stored; when you edit such an item the dropdown shows "Current value: …", and leaving the colour alone saves it unchanged. - Neither the Config page nor the dictionary page has a dedicated E2E test. ## Where is the code? - Config: [`plugin/config/`](https://github.com/yile2020/fastapi-react-admin/tree/main/apps/api/backend/plugin/config) · runtime loading and validation [`utils/dynamic_config.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/utils/dynamic_config.py) · frontend [`pages/config/`](https://github.com/yile2020/fastapi-react-admin/tree/main/packages/platform/src/pages/config) (`registry.ts` holds each item's metadata) -- Data dictionary: [`plugin/dict/`](https://github.com/yile2020/fastapi-react-admin/tree/main/apps/api/backend/plugin/dict) · frontend [`pages/dict/`](https://github.com/yile2020/fastapi-react-admin/tree/main/packages/platform/src/pages/dict) +- Data dictionary: [`plugin/dict/`](https://github.com/yile2020/fastapi-react-admin/tree/main/apps/api/backend/plugin/dict) · frontend [`pages/dict/`](https://github.com/yile2020/fastapi-react-admin/tree/main/packages/platform/src/pages/dict) · the hook and components business pages use to read a dictionary [`_shared/dict.tsx`](https://github.com/yile2020/fastapi-react-admin/blob/main/packages/platform/src/pages/_shared/dict.tsx), colour mapping [`_shared/dict-color.ts`](https://github.com/yile2020/fastapi-react-admin/blob/main/packages/platform/src/pages/_shared/dict-color.ts) ## How is it tested? - [`test_dynamic_config_bounds.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/tests/api_v1/test_dynamic_config_bounds.py): backend bounds reconciled with the frontend `registry.ts`, out-of-range writes refused. [`test_dynamic_config.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/tests/api_v1/test_dynamic_config.py): fallbacks on read. [`test_upload_policy_config.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/tests/api_v1/test_upload_policy_config.py): the file upload group. `test_mfa.py` covers "two-factor cannot be required without a key" and "the config list does not 500 because of one old value that no longer validates". - Dictionary import and export are covered in `test_import.py` and `test_export.py`. +- The read endpoint: [`test_dict_options.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/plugin/dict/tests/test_dict_options.py), 13 cases — an account without dictionary permission can read, empty / missing / all-disabled types return `[]`, ascending order, unmatched codes write no cache key, 20 unmatched codes cost one query, a cached read doesn't query, and the next read sees changes after an add / edit / delete. On the frontend, [`dict-color.test.ts`](https://github.com/yile2020/fastapi-react-admin/blob/main/packages/platform/src/pages/_shared/dict-color.test.ts) and [`dict.test.ts`](https://github.com/yile2020/fastapi-react-admin/blob/main/packages/platform/src/pages/_shared/dict.test.ts) have 23 cases between them; one reads the seed SQL and fails when the seed uses a colour name the frontend does not map. - No dedicated browser tests; the E2E global setup turns off the image captcha through the Config API. ## Try it on the demo diff --git a/apps/docs/src/content/docs/en/guides/first-module.md b/apps/docs/src/content/docs/en/guides/first-module.md index 0088c346..a9996bc9 100644 --- a/apps/docs/src/content/docs/en/guides/first-module.md +++ b/apps/docs/src/content/docs/en/guides/first-module.md @@ -1317,6 +1317,23 @@ Once all of these pass, sign in as the superuser: the sidebar shows 客户关系 All the commands above were actually run and passed. What it looks like in the browser (sidebar, form interaction) was not confirmed with screenshots during verification, so click through it yourself the first time. ::: +### Optional: let operators maintain the `level` options + +Options that operators change or extend, like `level` (normal / important / VIP), fit the [data dictionary](/en/features/config-dict/) better than values hard-coded in the page: create a type `crm_level` under "System → Data dictionary", add three items (values `0` / `1` / `2`), and the page only names the type code: + +```tsx +import { DictSelect, DictTag } from "../_shared/dict" + + {/* table column */} + form.setValue("level", Number(v))} /> {/* form: the value is a string */} +``` + +- The endpoint it reads needs **sign-in only**, not dictionary-management permission; a value the dictionary doesn't have (item disabled or deleted) shows as a grey raw value, and when loading fails the tag can be clicked to retry +- 🔴 **Don't use it for values tied to a backend enum.** `status` above (0 disabled / 1 normal) is validated by the backend's `StatusType`; changing the dictionary doesn't change the backend, so keep `StatusBadge` +- To **ship the items with the code**, do what step 7 does for menus: add them to both the seed SQL and a data migration (`utils/data_migration.py` only has the generic `insert_if_absent`, no dictionary-specific helper); to try it in your own environment, just create them in the UI +- This subsection has not been run against this page's "customer" example: there `level` is still three values hard-coded in the page. The tests and browser checks of the dictionary-reading layer itself are in [`pages/_shared/AGENTS.md`](https://github.com/yile2020/fastapi-react-admin/blob/main/packages/platform/src/pages/_shared/AGENTS.md) + ## Step 9: make data scopes take effect Data scopes need no code: they were wired in when the DAO inherited `DataScopedCRUD` in step 4. This step configures them in the UI and confirms they actually work. For how they work, see [Data permissions](/en/features/data-permissions/). diff --git a/apps/docs/src/content/docs/features/config-dict.mdx b/apps/docs/src/content/docs/features/config-dict.mdx index 357e63bb..e785cdb1 100644 --- a/apps/docs/src/content/docs/features/config-dict.mdx +++ b/apps/docs/src/content/docs/features/config-dict.mdx @@ -60,9 +60,30 @@ import ProductShot from '../../../components/ProductShot.astro' - **字典类型**:名称、编码(唯一)、备注。 - **字典项**:所属类型的编码、标签、值、颜色、排序、状态(正常 / 停用)、备注。同一类型下标签不能重复。 -业务代码按类型编码取选项:`GET /api/v1/sys/dict-datas/type-codes/{编码}`,只返回状态正常的项,按排序值**从大到小**排;结果在 Redis 里缓存 2 小时,改字典项时清缓存。字典项能[导入导出](/features/import-export/),按「类型编码 + 标签」匹配已有的项。 +### 业务页面怎么读字典? -⚠️ **目前内置的页面都没有读字典**:公告类型、状态这类标签是在各页面的代码里写死的,只有字典管理页自己在调字典接口。字典是留给你自己的业务页面用的,前端也还没有现成的「按类型取字典」的 hook。 +前端用 `_shared/dict.tsx` 里的三样,只写字典类型编码: + +```tsx +import { DictSelect, DictTag, useDict } from '../_shared/dict' + + {/* 表格里:值 → 带色的标签 */} + {/* 表单里的下拉,值是字符串 */} +const level = useDict('crm_level') // 要自己拿选项时:level.options / level.labelOf(value) +``` + +它们走 `GET /api/v1/sys/dict-datas/options?codes=a&codes=b`: + +- **登录即可,不要字典管理权限**。普通页面的下拉得能读到自己用的字典;字典**管理**接口照旧要 `dict:data:*`。 +- 一次最多 20 个编码,每个编码都有一个键:**没有选项的返回 `[]`,不是 404**(老接口对「没有这个类型 / 类型是空的 / 项全被停用」一律 404,调用方分不出是哪一种)。 +- 只返回状态正常的项,按排序值**从小到大**排,和字典页看到的顺序一致。同一类型里值重复的项(库里只约束标签唯一),前端只认排序靠前的那一项。 +- 结果在 Redis 里缓存 2 小时;增、改、删、导入字典项和改删类型都会清缓存。查无的编码不进缓存,所以调用方乱填编码刷不出缓存键;没命中缓存的编码合成一条查询,一次请求最多查一次库。 + +老接口 `GET /api/v1/sys/dict-datas/type-codes/{编码}` 还在,但要 `dict:data:list` 权限、空类型 404、按排序值**从大到小**排,业务页面不要用它。字典项能[导入导出](/features/import-export/),按「类型编码 + 标签」匹配已有的项。 + +⚠️ **该接字典的是「运营自己维护」的枚举**(客户级别、工单类别……)。内置页面里的菜单类型、登录状态、数据规则运算符这类值**和后端代码里的枚举绑在一起**,改字典不会让后端跟着变,所以没有接字典,仍然写在页面里。 + +⚠️ 取数失败时 `DictTag` 显示原值(虚线下划线,点一下重试),`DictSelect` 禁用并显示「加载失败 · 重试」,不会画成空白。字典里没有的值(项被停用或删除,历史数据里还带着)原样显示成灰色标签。 ## 有哪些开关? @@ -83,19 +104,22 @@ import ProductShot from '../../../components/ProductShot.astro' - **密码类的值只在界面上遮住**:邮件密码这类键名像密钥的项,界面上用密码框显示、可以点开看,但接口返回的是明文 —— 能打开参数配置页的人都能拿到。数据变更记录对这些项只记「改了」,不记内容。 - 自己加的键没有校验、没有通用读取方式;「是否前端可见」这个字段在后端没有任何作用。 -- 改或删字典**类型**时不清字典缓存,最多 2 小时后才看到变化;改类型编码不会同步改它下面字典项的类型编码。 -- 字典页的颜色选项和种子数据里用到的颜色对不上,部分种子字典项会显示成默认样式。 +- 字典没有「内置只读」标记:管理员能删掉或改掉种子里的项(比如「通用状态」的「正常」)。没有页面依赖它们,但你自己的业务页面一旦读了,被删的值会显示成灰色原值。 +- 标签是数据库里的一段中文,英文界面靠语言包按原文翻译:语言包里有这条原文就译,管理员自己敲的不会翻。 +- **没有按类型控制谁能读**:任何登录用户都能通过上面那个接口读到所有字典的标签和值(字典**管理**接口照旧要权限)。只该部分人看到的分类别放进字典。 +- 颜色在字典页里只能挑 7 个规范色(默认、主色、成功、信息、警告、危险、灰色)。种子里用的 Ant Design 色名(`green`、`processing`、`magenta`……)前端按语义映射到这几个,不改库里存的值;编辑这类项时下拉里显示「原值:…」,不动颜色就原样存回去。 - 参数配置页和字典页都没有专门的 E2E。 ## 代码在哪 - 参数配置:[`plugin/config/`](https://github.com/yile2020/fastapi-react-admin/tree/main/apps/api/backend/plugin/config) · 运行时加载与校验 [`utils/dynamic_config.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/utils/dynamic_config.py) · 前端 [`pages/config/`](https://github.com/yile2020/fastapi-react-admin/tree/main/packages/platform/src/pages/config)(`registry.ts` 是每一项的元数据) -- 数据字典:[`plugin/dict/`](https://github.com/yile2020/fastapi-react-admin/tree/main/apps/api/backend/plugin/dict) · 前端 [`pages/dict/`](https://github.com/yile2020/fastapi-react-admin/tree/main/packages/platform/src/pages/dict) +- 数据字典:[`plugin/dict/`](https://github.com/yile2020/fastapi-react-admin/tree/main/apps/api/backend/plugin/dict) · 前端 [`pages/dict/`](https://github.com/yile2020/fastapi-react-admin/tree/main/packages/platform/src/pages/dict) · 业务页面读字典的 hook 和组件 [`_shared/dict.tsx`](https://github.com/yile2020/fastapi-react-admin/blob/main/packages/platform/src/pages/_shared/dict.tsx),颜色映射 [`_shared/dict-color.ts`](https://github.com/yile2020/fastapi-react-admin/blob/main/packages/platform/src/pages/_shared/dict-color.ts) ## 怎么测的 - [`test_dynamic_config_bounds.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/tests/api_v1/test_dynamic_config_bounds.py):后端范围和前端 `registry.ts` 对账、越界写入被拒。[`test_dynamic_config.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/tests/api_v1/test_dynamic_config.py):读取时的回落。[`test_upload_policy_config.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/tests/api_v1/test_upload_policy_config.py):文件上传组。`test_mfa.py` 里有「没配密钥不能强制二次验证」「配置列表不因一个已不合法的旧值整个 500」。 - 字典的导入导出在 `test_import.py`、`test_export.py` 里。 +- 读字典的接口:[`test_dict_options.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/plugin/dict/tests/test_dict_options.py) 13 条,没有字典权限的账号能读、空 / 不存在 / 全停用都是 `[]`、顺序升序、查无的编码不写缓存、20 个查无的编码只查一次库、命中缓存不查库、增改删后下一次读到新值。前端的 [`dict-color.test.ts`](https://github.com/yile2020/fastapi-react-admin/blob/main/packages/platform/src/pages/_shared/dict-color.test.ts) 和 [`dict.test.ts`](https://github.com/yile2020/fastapi-react-admin/blob/main/packages/platform/src/pages/_shared/dict.test.ts) 共 23 条,其中一条会读种子 SQL,种子里出现前端没映射的色名就红。 - 浏览器端没有专门的用例;E2E 的全局准备阶段通过接口关掉图形验证码,用的就是参数配置。 ## 在演示站里试试 diff --git a/apps/docs/src/content/docs/guides/first-module.md b/apps/docs/src/content/docs/guides/first-module.md index a211fdfb..75938945 100644 --- a/apps/docs/src/content/docs/guides/first-module.md +++ b/apps/docs/src/content/docs/guides/first-module.md @@ -1317,6 +1317,23 @@ pnpm lint 上面这几条命令都实际跑过并通过了。浏览器里的效果(侧边栏、表单交互)没有在验证时截图确认,第一次跑的时候请自己点一遍。 ::: +### 可选:让运营自己维护 `level` 的选项 + +`level`(普通 / 重要 / VIP)这类**运营会改、会加**的选项,放进[数据字典](/features/config-dict/)比写死在页面里合适:在「系统管理 → 数据字典」建类型 `crm_level`,加三个字典项(值 `0` / `1` / `2`),页面里只写类型编码: + +```tsx +import { DictSelect, DictTag } from "../_shared/dict" + + {/* 表格列 */} + form.setValue("level", Number(v))} /> {/* 表单:值是字符串 */} +``` + +- 读字典的接口**登录即可**,不要字典管理权限;字典里没有的值(项被停用、删除)显示成灰色原值,取不到时标签可点击重试 +- 🔴 **不要拿它管和后端枚举绑死的值**。上面的 `status`(0 停用 / 1 正常)后端用 `StatusType` 校验,改字典不会让后端跟着变,仍用 `StatusBadge` +- 字典项要**随代码交付**的话,和第 7 步的菜单一样:种子 SQL 和数据迁移两边都要加(`utils/data_migration.py` 里只有通用的 `insert_if_absent`,没有专门的字典辅助函数);只在自己环境试,去页面里建就行 +- 这一小节的写法没有在本页的「客户管理」示例里跑过:示例里 `level` 仍是页面里写死的三个值。读字典这一层本身的测试和浏览器实测见 [`pages/_shared/AGENTS.md`](https://github.com/yile2020/fastapi-react-admin/blob/main/packages/platform/src/pages/_shared/AGENTS.md) + ## 第 9 步:让数据权限生效 数据权限本身不用写代码,第 4 步继承 `DataScopedCRUD` 时就已经接上了。这一步是用页面把它配出来,确认它真的在起作用。机制见[数据权限](/features/data-permissions/)。 diff --git a/packages/api/src/schema.d.ts b/packages/api/src/schema.d.ts index 9bbe224a..533c38d2 100644 --- a/packages/api/src/schema.d.ts +++ b/packages/api/src/schema.d.ts @@ -1806,6 +1806,26 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/sys/dict-datas/options": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * 批量获取字典选项(登录即可) + * @description 给下拉 / 标签用:只返回启用的选项、按排序升序;请求的每个编码都有一个键,没有选项的是空数组。不要求字典管理权限 —— 普通页面的下拉得能读到它自己用的字典;字典**管理**接口照旧要 `dict:data:*` + */ + get: operations["get_dict_options_api_v1_sys_dict_datas_options_get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/sys/dict-datas/import/template": { parameters: { query?: never; @@ -6938,6 +6958,27 @@ export interface components { */ updated_time?: string | null; }; + /** + * GetDictOption + * @description 字典选项(给前端下拉 / 标签用,只带展示要用的字段) + */ + GetDictOption: { + /** + * Label + * @description 字典标签 + */ + label: string; + /** + * Value + * @description 字典值(永远是字符串,数字类的字典也是) + */ + value: string; + /** + * Color + * @description 标签颜色 + */ + color?: string | null; + }; /** * GetDictTypeDetail * @description 字典类型详情 @@ -13073,6 +13114,25 @@ export interface components { [key: string]: unknown; }; }; + /** ResponseSchemaModel[dict[str, list[GetDictOption]]] */ + ResponseSchemaModel_dict_str__list_GetDictOption___: { + /** + * Code + * @description 返回状态码 + * @default 200 + */ + code: number; + /** + * Msg + * @description 返回信息 + * @default 请求成功 + */ + msg: string; + /** Data */ + data: { + [key: string]: components["schemas"]["GetDictOption"][]; + }; + }; /** ResponseSchemaModel[int] */ ResponseSchemaModel_int_: { /** @@ -19582,6 +19642,38 @@ export interface operations { }; }; }; + get_dict_options_api_v1_sys_dict_datas_options_get: { + parameters: { + query: { + /** @description 字典类型编码,可重复传多个(最多 20 个) */ + codes: string[]; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ResponseSchemaModel_dict_str__list_GetDictOption___"]; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; download_dict_data_import_template_api_v1_sys_dict_datas_import_template_get: { parameters: { query?: never; diff --git a/packages/i18n/src/locales/en-US.json b/packages/i18n/src/locales/en-US.json index eb916f3f..dbd488b7 100644 --- a/packages/i18n/src/locales/en-US.json +++ b/packages/i18n/src/locales/en-US.json @@ -789,6 +789,7 @@ "厂商配置": "Provider settings", "历史密码检查": "Password history check", "压缩包": "Archive", + "原值:{{value}}": "Current value: {{value}}", "原因": "Reason", "原始文件名": "Original name", "原生 SQL Server": "Native SQL Server", @@ -1083,7 +1084,9 @@ "如:本部门数据": "e.g. data of my department", "姓名或用户名": "Name or username", "子菜单展开方式": "Submenu behavior", + "字典加载失败,点击重试": "Failed to load the dictionary. Click to retry", "字典类型": "Dictionary types", + "字典里没有这个值": "This value is not in the dictionary", "字典项": "Dictionary item", "字段": "Field", "字段 ID": "Field ID", @@ -1822,6 +1825,7 @@ "暂无执行记录": "No execution records", "暂无数据": "No data", "暂无条件,点击此处添加": "No conditions yet — click to add one", + "暂无选项": "No options", "暂无通知": "No notifications yet", "暂无附件": "No attachments", "暂时连不上服务器": "Can't reach the server right now", diff --git a/packages/i18n/src/locales/zh-CN.json b/packages/i18n/src/locales/zh-CN.json index 5e80372f..9261acdf 100644 --- a/packages/i18n/src/locales/zh-CN.json +++ b/packages/i18n/src/locales/zh-CN.json @@ -789,6 +789,7 @@ "厂商配置": "厂商配置", "历史密码检查": "历史密码检查", "压缩包": "压缩包", + "原值:{{value}}": "原值:{{value}}", "原因": "原因", "原始文件名": "原始文件名", "原生 SQL Server": "原生 SQL Server", @@ -1083,7 +1084,9 @@ "如:本部门数据": "如:本部门数据", "姓名或用户名": "姓名或用户名", "子菜单展开方式": "子菜单展开方式", + "字典加载失败,点击重试": "字典加载失败,点击重试", "字典类型": "字典类型", + "字典里没有这个值": "字典里没有这个值", "字典项": "字典项", "字段": "字段", "字段 ID": "字段 ID", @@ -1822,6 +1825,7 @@ "暂无执行记录": "暂无执行记录", "暂无数据": "暂无数据", "暂无条件,点击此处添加": "暂无条件,点击此处添加", + "暂无选项": "暂无选项", "暂无通知": "暂无通知", "暂无附件": "暂无附件", "暂时连不上服务器": "暂时连不上服务器", diff --git a/packages/platform/src/pages/_shared/AGENTS.md b/packages/platform/src/pages/_shared/AGENTS.md index 38b51553..42f2b76a 100644 --- a/packages/platform/src/pages/_shared/AGENTS.md +++ b/packages/platform/src/pages/_shared/AGENTS.md @@ -174,3 +174,54 @@ 错误 + 重试 → 放行后数据回来,全过;把修复整体 stash 掉只留用例,7 条全红在「错误提示可见」那一句。 ego 浏览器逐处实测(CDP `Fetch` 回 502,带跨域头)八处都对,另外抓到两处只有看得见才发现的:侧边栏那行长提示被 `SidebarMenuButton` 自带的 `[&>span:last-child]:truncate` 截成「部分按钮暂不…」(文字容器改用 `div`);插件页失败时工具行还写着「共 0 / 0 个」(失败且没数据时不画)。 + +## 🔴 字典:业务页面读字典走 `options` 接口,颜色过 `dictColorClass`,别接和后端枚举绑死的值(2026-11-26) + +字典(`plugin/dict`)原来**前端零消费者**:字典页能增删改,全仓没有一个页面读它。要接之前先踩了四个坑,都是**静默**的 —— +在管理员账号、默认种子下一个都看不出来: + +| 症状 | 根因 | 修法 | +|---|---|---| +| 普通用户的下拉读不到字典(403) | 唯一的读接口 `GET /dict-datas/type-codes/{code}` 挂着 `dict:data:list`,那是**字典管理**权限 | 新增登录即可的 `GET /dict-datas/options?codes=…`(先例:`/data-rules/models` 只挂 `DependsJwtAuth`),管理接口不动 | +| 「这个字典还没有选项」和「编码写错了」一样是 404,下拉要么报错要么空着,分不出 | `get_by_type_code` 对空 / 不存在 / 全停用一律抛 `NotFoundError` | 新接口每个编码都有一个键,没有选项是 `[]` | +| 下拉顺序和字典页相反 | 老接口按 `sort` **降序**(上游遗留),字典页的分页列表是升序 | 新接口升序、同值按 id;老接口不动(下游可能依赖) | +| 字典页上「正常」本该是绿的、却和「停用」一样灰;种子 36 项里 **27 项**是灰的 | 种子里写的是 Ant Design 色名(`green` / `processing` / `magenta` / `volcano`…),前端 `COLOR_CLASS` 只有 6 个键,其余静默回落成默认 | `_shared/dict-color.ts`:规范色 7 个 + Ant Design 别名映射;**不改种子、不写迁移**(改了种子,已装好的库不会跟着变) | + +**用法**:`_shared/dict.tsx` 的 `useDict(code)` / `useDicts([…])`(一页要两个以上字典,一个请求)/ `DictTag`(表格单元格)/ `DictSelect`(表单下拉)。要点: + +- 🔴 **query key 必须挂在 `['sys', 'dict']` 下面**(`DICT_OPTIONS_ROOT`):字典页的增删改 `invalidateQueries({ queryKey: dictKeys.all })`,挂在别处,管理员改完字典、同一会话里的业务页面还是旧标签。`dict.test.ts` 钉着前缀 +- 🔴 **后端的查无必须返回 `None`,不能是 `[]`**(`_get_option_items`):`@cached` 对任何非 `None` 的结果都缓存,这个接口任何登录用户都能调、编码随便填,缓存空列表就等于让他往 Redis 里刷任意多个 `options:<随便写>` 键(每个活两小时)。缓存键放在 `CACHE_DICT_REDIS_PREFIX` 命名空间下,字典增改删整个命名空间一起清,不用另接失效 +- **字典值永远是字符串**(`'1'`、`'true'`),业务字段常是数字 / 布尔:`DictTag` / `labelOf` 比较前一律 `String()`;`DictSelect` 的 `onChange` 给字符串,要数字自己 `Number()`(ID 不要,硬纪律 6) +- **取不到不能画成空白**(硬纪律 9):`DictTag` 失败态是原值 + 虚线下划线的**按钮**,点一下重取(同一个编码共用一个 query,点一个整列恢复);`DictSelect` 禁用 + `OptionsError`;字典里没有的值(项被停用 / 删了,历史数据还带着)显示成灰色原值,编辑表单里把当前值补成一项,**不显示成空再被顺手存掉** +- ⚠️ `useDict().options` 喂 `QueryBar` 的 select 字段时,`FilterField` 只有 `optionsLoading`、**没有错误位**:取数失败会是个空下拉,页面要自己看 `isError` 提示(用 `OptionsError`),否则就是硬纪律 9 的老毛病 +- ⚠️ `filterItems()`(给 `SelectFilter`)里数字样的值(`'0'` / `'1'`)会被 JS 按数值顺序排,不跟 `sort`;要严格按 sort 排,用 `options` 喂 QueryBar +- 标签是库里的中文,渲染处 `t(label)`:语言包里有这条原文就译、没有(管理员自己敲的)原样;不用往 i18n 里补,`check.mjs` 只扫字面量 `t('…')` + +**该接哪些**:「运营自己维护」的枚举(客户级别、工单类别……)。🔴 **和后端代码里的枚举绑死的值不要接** —— 菜单类型、登录状态、数据规则运算符 / 表达式、任务策略 / 周期、插件类型、通用状态(12 类种子里约 8 类前端有写死的同义枚举):改字典不会让后端跟着变,后端校验照旧认原值,接了只会多出一种「界面显示和后端行为对不上」的静默错误;这些页面(`StatusBadge` / `MENU_TYPE_ITEMS`…)保持原样。字典还没有「内置只读」标记,管理员能删掉种子里的项 —— 这也是不接它们的理由之一。 + +**实测证据**(2026-11-26,PostgreSQL / Redis,种子账号): +- 接口:`plugin/dict/tests/test_dict_options.py` 11 条。变异各自当场红:查无也缓存(`test_unknown_codes_do_not_write_cache_keys`)· 排序改降序(3 条)· 同 sort 去掉 id 兜底 · 改回要权限(STAFF 403)· 不过滤停用项(6 条)。 + ⚠️ **同 sort 的兜底第一版测不出来**:PostgreSQL 对没有 `ORDER BY` 兜底的相同值恰好按插入顺序吐,去掉兜底测试照绿;改成创建后先 `UPDATE` 其中一项(UPDATE 会把行挪到堆后面)才变红 +- 前端:`dict-color.test.ts` / `dict.test.ts` 共 16 条。变异:删一个别名 · 缓存键挪出 `['sys','dict']` · 去掉 `enabled` 守卫,各自红;其中一条**读种子 SQL**(Vite `?raw`),种子里出现前端没映射的色名就红 +- 浏览器(ego,真实后端 + 前端):字典页「通用状态」的「正常」绿、「停用」红;「数据规则表达式」8 项各有颜色(原来除「等于」外全灰)。临时挂了一个不提交的消费者:数字 `1` → 正常、布尔 `true` → 开启、未知值 / 不存在的字典 → 灰色原值、过期值 `77` 保留、空字典下拉禁用写「暂无选项」;10 个组件、4 个编码,两次页面加载 API 日志里共 8 个 `options` 请求(不是 20 个;没逐次数,8 = 2 × 4 是对得上的推断);用 CDP 屏蔽 `options` 请求:标签变按钮、下拉禁用 + 「加载失败 · 重试」,放开后点标签整列恢复 +- 🔴 **验证手法踩的坑**:第一次「点重试没恢复」是我读错了对象 —— 重试按钮属于**下拉**,只重取它自己那个编码,而我读的是另一个编码的标签。真正的缺口是**标签的失败态原来没有任何重试入口**(只能靠重新挂载 / 窗口聚焦 / 刷新),所以改成了可点的按钮 +- 没做:`DictSelect` / `QueryBar` 接入没有 E2E(项目里还没有页面在用,临时消费者验证后已撤);**第一批真实使用者是 `first-module` 指南里「客户管理」的 `level` 字段** + +### 字典 · #452 评审跟进(2026-11-26) + +| 症状 | 根因 | 修法 | +|---|---|---| +| 🔴 已经显示好的标签,一次后台重取失败就整列退成原值、字典下拉被禁用 | TanStack 在「有数据、重取失败」时是 `status: 'error'` 且**保留 `data`**;组件先判 `isError`。字典页每次增删改都会让 `['sys','dict']` 失效重取 | `failedWithoutData`:失败**而且没有数据**才算取不到(`useDict` / `useDicts` 的 `isError` 都走它) | +| 🔴 色名为 `constructor` / `__proto__` 的字典项标签没颜色 | `c in ALIASES` / `ALIASES[c]` 走原型链。色名先转小写,所以只有全小写的原型属性撞得上(评审时举的 `toString` 例子是错的:它会变成 `tostring`) | `Object.hasOwn` | +| 🔴 编辑一个颜色不在 7 个规范色里的项(导入的 `teal`、种子的 `processing`),只改标签保存,颜色被静默改成 `default` / 规范名 | 第一版编辑时把色名规范化后放进表单 | 原样带回;下拉里给原值补一项「原值:…」(用 `Object.fromEntries` 一次建好 —— `items[color] = …` 在色名是 `__proto__` 时会被当成改原型) | +| 同一类型下值重复(库里只约束标签唯一)时,标签取后一项、下拉两项同 key | `new Map(items.map(...))` 后写覆盖 | 按值去重,留排序靠前的 | +| 值为 `all` 的项在筛选下拉里顶掉「全部」 | `all` 是 `SelectFilter` 的「不筛」哨兵,`filterItems` 先写了它 | 「全部」**最后写**(第一版另加的 `filter` 是等价变异,删了) | +| 20 个查无的编码每次请求 20 条 SQL | 逐个调 `@cached` 函数,查无的又不缓存 | L1 → Redis `MGET` → 剩下的一条 `IN` 查询;查无照旧不写缓存 | +| `useDicts` 遇到含 `|` 的编码会拆错 | 用 `join('\|')` 当 `useMemo` 依赖 | 依赖改成 `JSON.stringify(codes)` | + +没改的一条:**任何登录用户都能读所有字典的值**(这个接口的设计,文档站「它不做什么」里写明了)。要按类型控制得给 `sys_dict_type` 加列 + 迁移 + 三方言种子 + 审计登记 —— **维护者 2026-11-26 拍板:不加,保持现状**。字典定位是界面上的展示枚举,只该部分人看到的分类不放字典;以后真有需求再加标记,别把这个接口改回要管理权限(那样普通页面的下拉又读不到了)。 + +**实测证据**(同日):后端 `test_dict_options.py` 13 条(新增「20 个查无的编码只 1 条 SQL」「命中缓存 0 条 SQL」,按引擎事件数真实发出、碰了 `sys_dict_data` 的语句),变异:改回逐个查 · 不读缓存 · 查无也写缓存,各自红。 +前端 23 条,变异:退回 `in` 查找(4 条红)· 不去重 · 「全部」先写 · 失败只看 `isError`,各自红。 +⚠️ 第一版的原型链用例写的是 `toString` / `valueOf`,变异下 5 条只红 2 条 —— 它们转小写后根本不在原型链上,用例本身证明不了什么,换成了大小写混写的 `constructor` / `__proto__`。 +浏览器(ego,真实后端 + 前端):用接口造一个颜色 `teal` 的临时项 → 界面上编辑,颜色下拉显示「原值:teal」→ 只改标签保存 → 库里 `color` 仍是 `teal`(临时数据已硬删)。`failedWithoutData` 只有单测,组件层没有单独在浏览器里复现「有数据时重取失败」。 diff --git a/packages/platform/src/pages/_shared/dict-color.test.ts b/packages/platform/src/pages/_shared/dict-color.test.ts new file mode 100644 index 00000000..5a1d6bce --- /dev/null +++ b/packages/platform/src/pages/_shared/dict-color.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it } from 'vitest' +// 种子 SQL 用 Vite 的 `?raw` 读 —— platform 的 tsconfig 没有 node 类型,`node:fs` 过不了 typecheck +import seed from '../../../../../apps/api/backend/plugin/dict/sql/postgresql/init_snowflake.sql?raw' + +import { + canonicalDictColor, + DICT_COLORS, + DICT_COLOR_CLASS, + dictColorClass, + isKnownDictColor, +} from './dict-color' + +describe('canonicalDictColor', () => { + it('规范色名原样', () => { + for (const c of DICT_COLORS) expect(canonicalDictColor(c)).toBe(c) + }) + + it('Ant Design 色名按语义归到规范色', () => { + expect(canonicalDictColor('green')).toBe('success') + expect(canonicalDictColor('error')).toBe('red') + expect(canonicalDictColor('processing')).toBe('info') + expect(canonicalDictColor('cyan')).toBe('info') + expect(canonicalDictColor('purple')).toBe('primary') + expect(canonicalDictColor('magenta')).toBe('primary') + for (const warm of ['orange', 'gold', 'volcano']) expect(canonicalDictColor(warm)).toBe('warning') + }) + + it('大小写和空白不影响;空值与认不出的落回 default', () => { + expect(canonicalDictColor(' Green ')).toBe('success') + expect(canonicalDictColor(null)).toBe('default') + expect(canonicalDictColor(undefined)).toBe('default') + expect(canonicalDictColor('')).toBe('default') + expect(canonicalDictColor('chartreuse')).toBe('default') + }) +}) + +describe('isKnownDictColor', () => { + it('规范名 / 别名 / 空值认,其余不认', () => { + expect(isKnownDictColor('success')).toBe(true) + expect(isKnownDictColor('volcano')).toBe(true) + expect(isKnownDictColor(null)).toBe(true) + expect(isKnownDictColor('chartreuse')).toBe(false) + }) +}) + +describe('dictColorClass', () => { + it('每个规范色都有 class,语义色互不相同(不会全是灰)', () => { + const classes = DICT_COLORS.map((c) => DICT_COLOR_CLASS[c]) + expect(classes.every(Boolean)).toBe(true) + expect(new Set(classes).size).toBe(DICT_COLORS.length) + }) + + it('green 和 default 长得不一样 —— 修之前「正常」和「停用」都是灰色', () => { + expect(dictColorClass('green')).not.toBe(dictColorClass('default')) + expect(dictColorClass('green')).toBe(dictColorClass('success')) + }) +}) + +describe('种子字典里的色名', () => { + /** + * 🔴 种子 SQL 是后端那边的数据,前端的映射表是这边的:两边各自改、谁也不报错。 + * 种子里新写一个色名而这里没映射,字典页上它就悄悄变灰 —— 所以读种子核对。 + * (三个方言的种子同源,读 PostgreSQL 那份) + */ + const rows = [...seed.matchAll(/\(\d+, '(\w+)', '[^']*', '[^']*', '(\w+)', \d+, \d,/g)].map((m) => ({ + type: m[1]!, + color: m[2]!, + })) + + it('先断言「有」:真读到了种子里的字典项(正则失效时下面的循环天然通过)', () => { + expect(rows.length).toBeGreaterThanOrEqual(30) + }) + + it('每一个色名前端都认', () => { + const unknown = rows.filter((r) => !isKnownDictColor(r.color)) + expect(unknown).toEqual([]) + }) +}) + +describe('原型链上的键(#452 评审)', () => { + // color 是后端的自由文本,导入 xlsx 能写任意值;`'constructor' in {}` 是 true。 + // 色名先转小写,真正能撞上原型链的是全小写的 constructor / __proto__(大小写混写的也会被转成它们) + it.each(['constructor', '__proto__', 'Constructor', ' __PROTO__ '])('%s 不算认得的色名、落回 default', (c) => { + expect(isKnownDictColor(c)).toBe(false) + expect(canonicalDictColor(c)).toBe('default') + expect(dictColorClass(c)).toBe(DICT_COLOR_CLASS.default) + }) +}) diff --git a/packages/platform/src/pages/_shared/dict-color.ts b/packages/platform/src/pages/_shared/dict-color.ts new file mode 100644 index 00000000..3347153a --- /dev/null +++ b/packages/platform/src/pages/_shared/dict-color.ts @@ -0,0 +1,88 @@ +import { TONE_CLASS } from './status' + +/** + * 字典项的颜色。 + * + * 🔴 **后端的 `color` 是自由文本,种子里写的是 Ant Design 的色名,前端只有一套自己的色板。** + * 种子 36 个字典项里 27 个用的是 `green` / `processing` / `magenta` / `volcano` / `cyan` …, + * 原来的映射表只有 6 个键,其余一律查不到、静默回落成灰色 —— 字典页上「通用状态」的「正常」 + * 本该是绿的、却和「停用」一样是灰的(2026-11-26 读种子 SQL 统计)。 + * + * 做法:前端认一份**规范色名**(下拉里能挑的就是这些),再给 Ant Design 的色名做**别名**映射, + * 不改种子、不写迁移(改了种子,已经装好的库不会跟着变)。 + * 新增别名只加在 `ALIASES`;`dict-color.test.ts` 会读种子 SQL,种子里出现没映射的色名就红。 + */ +export const DICT_COLORS = ['default', 'primary', 'success', 'info', 'warning', 'red', 'gray'] as const +export type DictColor = (typeof DICT_COLORS)[number] + +const ALIASES: Record = { + // 成功 + green: 'success', + // 危险 + error: 'red', + danger: 'red', + // 警示(Ant Design 的暖色一律归到琥珀) + orange: 'warning', + gold: 'warning', + volcano: 'warning', + yellow: 'warning', + lime: 'warning', + // 信息(冷色) + cyan: 'info', + blue: 'info', + geekblue: 'info', + processing: 'info', + // 品牌紫 + purple: 'primary', + magenta: 'primary', + pink: 'primary', + // 灰 + grey: 'gray', +} + +const CANONICAL = new Set(DICT_COLORS) + +function normalize(color: string | null | undefined): string { + return (color ?? '').trim().toLowerCase() +} + +/** + * 🔴 **只认 `ALIASES` 自己的键,不能用 `in` / 直接下标。** `color` 是后端的自由文本(导入 xlsx 能写任意值), + * `'constructor' in ALIASES` 是 true、`ALIASES['constructor']` 是个函数 —— 原型链上的属性会被当成别名, + * 标签的 class 变成 `undefined`。色名先转了小写,所以能撞上的是 `constructor` / `__proto__` 这类全小写的原型属性 + * (`toString` 转成 `tostring` 就不在原型链上了) + */ +function alias(c: string): DictColor | undefined { + return Object.hasOwn(ALIASES, c) ? ALIASES[c] : undefined +} + +/** 这个色名前端认不认(规范名或别名)。空值算认 —— 空就是「默认」 */ +export function isKnownDictColor(color: string | null | undefined): boolean { + const c = normalize(color) + return c === '' || CANONICAL.has(c) || alias(c) !== undefined +} + +/** 任意色名 → 规范色名。认不出的落回 `default`(灰底),不会报错 */ +export function canonicalDictColor(color: string | null | undefined): DictColor { + const c = normalize(color) + if (CANONICAL.has(c)) return c as DictColor + return alias(c) ?? 'default' +} + +/** + * 药丸的 class。四个语义色直接取 `_shared/status` 的 `TONE_CLASS`(同一个语义在字典标签、 + * 状态药丸、提示条上得是同一个颜色),只有 default / primary 是字典自己的。 + */ +export const DICT_COLOR_CLASS: Record = { + default: 'bg-muted text-foreground ring-border', + primary: 'bg-primary/10 text-primary ring-primary/25', + success: TONE_CLASS.success, + info: TONE_CLASS.info, + warning: TONE_CLASS.warning, + red: TONE_CLASS.danger, + gray: TONE_CLASS.muted, +} + +export function dictColorClass(color: string | null | undefined): string { + return DICT_COLOR_CLASS[canonicalDictColor(color)] +} diff --git a/packages/platform/src/pages/_shared/dict.test.ts b/packages/platform/src/pages/_shared/dict.test.ts new file mode 100644 index 00000000..ff7487ff --- /dev/null +++ b/packages/platform/src/pages/_shared/dict.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, it } from 'vitest' + +import { dictKeys } from '../dict/api' +import { buildDict, dictOptionsKey, dictOptionsQuery, failedWithoutData, type DictOption } from './dict' + +const ITEMS: DictOption[] = [ + { label: '正常', value: '1', color: 'green' }, + { label: '停用', value: '0', color: 'red' }, + { label: '待定', value: 'true', color: null }, +] +const upper = (s: string) => `«${s}»` + +describe('缓存键', () => { + it('🔴 挂在字典页的失效前缀下 —— 管理员改完字典,同一会话里的业务页面才会刷新', () => { + const prefix = [...dictKeys.all] + expect(dictOptionsKey('sys_status').slice(0, prefix.length)).toEqual(prefix) + }) + + it('没传编码时查询不启用(不然会发一个必定 422 的请求)', () => { + expect(dictOptionsQuery('').enabled).toBe(false) + expect(dictOptionsQuery('sys_status').enabled).toBe(true) + }) +}) + +describe('buildDict', () => { + const d = buildDict(ITEMS, upper) + + it('options 的标签过翻译函数,items 保持原样', () => { + expect(d.options).toEqual([ + { value: '1', label: '«正常»' }, + { value: '0', label: '«停用»' }, + { value: 'true', label: '«待定»' }, + ]) + expect(d.items[0]!.label).toBe('正常') + }) + + it('业务字段是数字 / 布尔时照样命中(字典值永远是字符串)', () => { + expect(d.labelOf(1)).toBe('«正常»') + expect(d.labelOf(0)).toBe('«停用»') + expect(d.labelOf(true)).toBe('«待定»') + expect(d.find(1)?.color).toBe('green') + }) + + it('字典里没有的值原样返回,不是空串 —— 被停用 / 删掉的项,历史数据里还带着', () => { + expect(d.labelOf(9)).toBe('9') + expect(d.find(9)).toBeUndefined() + }) + + it('空值不命中也不炸', () => { + expect(d.labelOf(null)).toBe('') + expect(d.labelOf(undefined)).toBe('') + expect(d.find(null)).toBeUndefined() + }) + + it('filterItems:带「全部」和各项(标签已翻译)', () => { + // ⚠️ 不断言键的顺序:JS 对象里数字样的键('0' / '1')永远排在 'all' 前面, + // `SelectFilter` 靠 `orderedEntries()` 把 all 提前 —— 顺序不归这一层管(pages 分册「其他约定」) + const items = d.filterItems('全部状态') + expect(items.all).toBe('全部状态') + expect(items['1']).toBe('«正常»') + expect(items['0']).toBe('«停用»') + }) + + it('空字典:options 为空、labelOf 退回原值', () => { + const empty = buildDict([], upper) + expect(empty.options).toEqual([]) + expect(empty.labelOf('x')).toBe('x') + }) +}) + +describe('评审跟进(#452)', () => { + it('🔴 同值只留排序靠前的一项 —— 库里只约束「类型 + 标签」唯一,值可以重复', () => { + const d = buildDict( + [ + { label: '重要', value: '1', color: 'red' }, + { label: '重点', value: '1', color: 'green' }, + { label: '普通', value: '0', color: null }, + ], + upper + ) + expect(d.options.map((o) => o.value)).toEqual(['1', '0']) // 下拉里不再有两个同 key 的项 + expect(d.labelOf(1)).toBe('«重要»') // 不是后写的「重点」 + expect(d.find('1')?.color).toBe('red') + expect(d.items).toHaveLength(2) + }) + + it('filterItems 不放值为 all 的项 —— 那是 SelectFilter 的「不筛」哨兵,放进来会顶掉「全部」', () => { + const d = buildDict( + [ + { label: '全部门', value: 'all', color: null }, + { label: '本部门', value: 'mine', color: null }, + ], + upper + ) + const items = d.filterItems('全部') + expect(items.all).toBe('全部') + expect(items.mine).toBe('«本部门»') + expect(Object.keys(items)).toHaveLength(2) + expect(d.options).toHaveLength(2) // 下拉 / QueryBar 那边照常有它 + }) + + it('🔴 有数据时重取失败不算「取不到」—— 别把用户正在看的标签抽走', () => { + expect(failedWithoutData({ isError: true, data: undefined })).toBe(true) + expect(failedWithoutData({ isError: true, data: [] })).toBe(false) // 上次成功拿到的是空字典,也算有数据 + expect(failedWithoutData({ isError: true, data: ITEMS })).toBe(false) + expect(failedWithoutData({ isError: false, data: undefined })).toBe(false) + }) +}) diff --git a/packages/platform/src/pages/_shared/dict.tsx b/packages/platform/src/pages/_shared/dict.tsx new file mode 100644 index 00000000..6f811320 --- /dev/null +++ b/packages/platform/src/pages/_shared/dict.tsx @@ -0,0 +1,308 @@ +import * as React from 'react' +import { queryOptions, useQuery, useQueryClient } from '@tanstack/react-query' +import { useTranslation } from 'react-i18next' + +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@admin/ui/components/select' +import { Skeleton } from '@admin/ui/components/skeleton' +import { cn } from '@admin/ui/lib/utils' + +import { api } from '../../api-client/client' +import { EmptyCell } from './cells' +import { dictColorClass } from './dict-color' +import { OptionsError } from './options-error' + +/** + * 数据字典的**前端消费者**:业务页面里的状态 / 分类 / 级别这类枚举,值和标签由字典页维护, + * 页面只写字典类型编码。 + * + * 哪些该接、哪些不该接,见 [`_shared` 分册](AGENTS.md)「字典」一节 —— 先看那一节再用: + * **和后端代码里的枚举绑死的值(菜单类型、登录状态……)不要接**,改字典不会让后端跟着变。 + */ + +export type DictOption = { label: string; value: string; color: string | null } + +// ─── 取数 ───────────────────────────────────────────────────────────────────── + +/** + * 🔴 **必须挂在 `['sys', 'dict']` 下面**(`dict/api.ts` 的 `dictKeys.all`):字典页的增删改都 + * `invalidateQueries({ queryKey: dictKeys.all })`,挂在别处,管理员改完字典、同一会话里的业务页面还是旧标签。 + * `dict.test.ts` 钉着这个前缀。 + */ +export const DICT_OPTIONS_ROOT = ['sys', 'dict', 'options'] as const +export const dictOptionsKey = (code: string) => [...DICT_OPTIONS_ROOT, code] as const + +/** 字典几乎不变,5 分钟内不重取;字典页改了会按上面那个前缀主动失效 */ +const STALE_MS = 5 * 60_000 + +async function fetchDictOptions(codes: readonly string[]): Promise> { + const s = new URLSearchParams() + for (const c of codes) s.append('codes', c) + return api.GET>(`/api/v1/sys/dict-datas/options?${s}`) +} + +export const dictOptionsQuery = (code: string) => + queryOptions({ + queryKey: dictOptionsKey(code), + queryFn: async () => (await fetchDictOptions([code]))[code] ?? [], + staleTime: STALE_MS, + enabled: code !== '', + }) + +// ─── 模型(纯函数,好测) ───────────────────────────────────────────────────── + +export type Dict = { + /** 原样的选项(标签没翻译)。**同值只留排序靠前的那一项**,见 `buildDict` */ + items: readonly DictOption[] + /** 给下拉 / 查询区用:标签已经过 `t()` */ + options: { value: string; label: string }[] + /** 值 → 标签。**字典里没有这个值就原样返回值本身**(被停用 / 删掉的项,历史数据里还在) */ + labelOf: (value: string | number | boolean | null | undefined) => string + find: (value: string | number | boolean | null | undefined) => DictOption | undefined + /** + * `SelectFilter` 的 `items`:`{ all: 「全部…」, 值: 标签 }`。 + * ⚠️ 数字样的值会被 JS 按数值顺序排,不跟 `sort`;要严格按 sort 用 `options` 喂 QueryBar。 + * ⚠️ **值恰好是 `all` 的项不在里面**:`all` 是 `SelectFilter` 的「不筛」哨兵,放进来会顶掉「全部」、自己也永远筛不出来 + */ + filterItems: (allLabel: string) => Record +} + +/** `SelectFilter` 用来表示「不筛」的值(见 `_shared/filters.tsx`) */ +const FILTER_ALL = 'all' + +/** + * 字典值永远是**字符串**(`'1'`、`'true'`),而业务字段常常是数字 / 布尔 —— 比较前一律 `String()`, + * 调用方不用管。反过来,`DictSelect` 的 `onChange` 给的也是字符串,要数字自己 `Number()`(ID 不要,硬纪律 6) + */ +const key = (v: string | number | boolean | null | undefined): string => (v == null ? '' : String(v)) + +export function buildDict(items: readonly DictOption[], translate: (s: string) => string): Dict { + /* + * 🔴 **按值去重,留排序靠前的。** 库里只约束「类型 + 标签」唯一,值可以重复(「重要」=1、「重点」=1)。 + * 不去重的话:值 → 标签取的是**后一项**,而下拉里两个同 key 的选项(React 报 duplicate key),选哪个提交的都是 1。 + * 接口已经按 sort 升序给,第一次出现的就是排序靠前的那一项 + */ + const byValue = new Map() + for (const i of items) if (!byValue.has(i.value)) byValue.set(i.value, i) + const unique = [...byValue.values()] + // 标签是库里的中文:仓库里写的(种子)在语言包里有 → 译;管理员自己敲的没有 → 原样(见 i18n 分册「谁写的」判据) + const options = unique.map((i) => ({ value: i.value, label: translate(i.label) })) + return { + items: unique, + options, + find: (v) => byValue.get(key(v)), + labelOf: (v) => { + const hit = byValue.get(key(v)) + return hit ? translate(hit.label) : key(v) + }, + // 🔴 「全部」**最后写**:值恰好是 all 的字典项会被它覆盖掉,而不是反过来把「全部」顶掉 + filterItems: (allLabel) => ({ ...Object.fromEntries(options.map((o) => [o.value, o.label])), [FILTER_ALL]: allLabel }), + } +} + +// ─── hooks ─────────────────────────────────────────────────────────────────── + +export type DictState = { + isPending: boolean + isError: boolean + error: unknown + refetch: () => void +} + +/** + * 「取不到」= 失败**而且手上没有数据**。 + * + * 🔴 TanStack 在「已经有数据、后台重取失败」时是 `status: 'error'` 且**保留 `data`**。字典页的每次增删改都会让 + * `['sys','dict']` 下的查询失效重取,窗口重新聚焦超过 `STALE_MS` 也会重取 —— 只要其中一次失败,直接看 `isError` + * 的话整列标签会退成原值、下拉被禁用,而缓存里的选项明明还在。把用户正在看的数据抽走是 pages 分册明令不做的事 + */ +export const failedWithoutData = (q: { isError: boolean; data: unknown }): boolean => q.isError && q.data === undefined + +/** + * 一个字典。同一个编码在一页里用多少次都只发一次请求(同 query key)。 + * 取不到时 `isError` 为真、`options` 是空 —— **调用方要把失败画出来**(`DictTag` / `DictSelect` 已经画了; + * 自己拿 `options` 喂别的控件时配 `OptionsError`),别让它长得像「这个字典没有选项」(硬纪律 9)。 + * 有上一次成功的数据时重取失败**不算** `isError`(见 `failedWithoutData`)。 + */ +export function useDict(code: string): Dict & DictState { + const { t } = useTranslation() + const q = useQuery(dictOptionsQuery(code)) + const dict = React.useMemo(() => buildDict(q.data ?? [], (s) => t(s)), [q.data, t]) + return { + ...dict, + // 没传编码(enabled=false)时 isPending 永远是 true,不能让它转圈 + isPending: code !== '' && q.isPending, + isError: failedWithoutData(q), + error: q.error, + refetch: () => void q.refetch(), + } +} + +/** + * 一次取多个字典(**一个请求**),并把每个字典写进单个编码的缓存 —— 之后任何地方 `useDict(code)` 都是命中。 + * 一个页面要两个以上字典时用它。 + */ +export function useDicts(codes: readonly C[]): { dicts: Record } & DictState { + const { t } = useTranslation() + const qc = useQueryClient() + // 依赖用 JSON 签名,不用 `codes.join('|')`:字典编码只限长度、不限字符,含 `|` 的编码会被 split 拆成两个 + const sig = JSON.stringify(codes) + const requested = React.useMemo(() => (JSON.parse(sig) as string[]).filter(Boolean), [sig]) + const list = React.useMemo(() => [...new Set(requested)].sort(), [requested]) + const q = useQuery({ + queryKey: [...DICT_OPTIONS_ROOT, 'batch', ...list], + queryFn: async () => { + const data = await fetchDictOptions(list) + for (const c of list) qc.setQueryData(dictOptionsKey(c), data[c] ?? []) + return data + }, + staleTime: STALE_MS, + enabled: list.length > 0, + }) + const dicts = React.useMemo( + () => Object.fromEntries(requested.map((c) => [c, buildDict(q.data?.[c] ?? [], (s) => t(s))])) as Record, + [requested, q.data, t] + ) + return { + dicts, + isPending: list.length > 0 && q.isPending, + isError: failedWithoutData(q), + error: q.error, + refetch: () => void q.refetch(), + } +} + +// ─── 组件 ──────────────────────────────────────────────────────────────────── + +const PILL = 'inline-flex shrink-0 items-center rounded-full px-2 py-0.5 text-xs whitespace-nowrap ring-1' + +/** + * 表格单元格 / 详情里的字典标签:值 → 带色的药丸。 + * + * 三种「不是正常命中」的情形各自可见,**不会画成空白**: + * - 加载中:骨架 + * - 取数失败:原值 + 虚线下划线,悬停说明,**点一下重试**(整列都失败时是一排原值,不是一排空格; + * 同一个编码共用一个 query,点任意一个整列恢复) + * - 字典里没有这个值(项被停用 / 删了,历史数据还带着):原值的灰色药丸 + */ +export function DictTag({ + code, + value, + className, + testId, +}: { + code: string + value: string | number | boolean | null | undefined + className?: string + testId?: string +}) { + const { t } = useTranslation() + const dict = useDict(code) + const v = key(value) + if (v === '') return + if (dict.isPending) return + if (dict.isError) { + // 真按钮:整列都失败时,用户点任意一个就能重取(同一个编码共用一个 query,一次点击全列恢复)。 + // stopPropagation:它常在可点击的行 / 单元格里,不能连带触发「打开详情」 + return ( + + ) + } + const hit = dict.find(v) + if (!hit) { + return ( + + {v} + + ) + } + return ( + + {dict.labelOf(v)} + + ) +} + +/** + * 表单里的字典下拉。值是**字符串**(见 `key` 的说明)。 + * + * - 当前值不在选项里(项被停用 / 删了):补一条「原值」选项,**不让编辑表单把它显示成空**再被用户顺手存掉 + * - 取数失败:下拉禁用,下面一行 `OptionsError`(加载失败 · 重试);不是空下拉 + * - 字典还没有任何启用的选项:禁用,占位写「暂无选项」 + */ +export function DictSelect({ + code, + value, + onChange, + disabled, + placeholder, + className = 'w-full', + testId, + errorTestId, +}: { + code: string + value: string | number | boolean | null | undefined + onChange: (value: string) => void + disabled?: boolean + placeholder?: string + className?: string + testId?: string + errorTestId?: string +}) { + const { t } = useTranslation() + const dict = useDict(code) + const current = key(value) + + const options = React.useMemo(() => { + if (current === '' || dict.isPending || dict.isError || dict.options.some((o) => o.value === current)) { + return dict.options + } + return [...dict.options, { value: current, label: current }] + }, [dict.options, dict.isPending, dict.isError, current]) + const items = React.useMemo(() => Object.fromEntries(options.map((o) => [o.value, o.label])), [options]) + + const empty = !dict.isPending && !dict.isError && options.length === 0 + const hint = dict.isPending ? t('加载中…') : empty ? t('暂无选项') : (placeholder ?? t('请选择')) + + return ( +
+ + {dict.isError && } +
+ ) +} diff --git a/packages/platform/src/pages/dict/api.ts b/packages/platform/src/pages/dict/api.ts index 175ee594..f7b68fec 100644 --- a/packages/platform/src/pages/dict/api.ts +++ b/packages/platform/src/pages/dict/api.ts @@ -1,7 +1,7 @@ import { queryOptions, useMutation, useQueryClient } from '@tanstack/react-query' import { api, type PageData } from '../../api-client/client' -import { TONE_CLASS } from '../_shared/status' +import type { DictColor } from '../_shared/dict-color' export type DictType = { id: string @@ -126,20 +126,13 @@ export function useDeleteDictDatas(opts: { suppressErrorToast?: boolean } = {}) }) } -/** 字典项的颜色标记 —— 后端存的是颜色名,这里映射到样式 */ -export const COLOR_ITEMS: Record = { - default: '默认', primary: '主色', success: '成功', warning: '警告', red: '危险', gray: '灰色', -} /** - * 字典项的颜色(后端存的是色名,由用户在表单里挑)。 - * 与状态色同源 —— 三个重合的色板直接取 `_shared/status` 的 TONE_CLASS, - * 不再各写一份 emerald/amber/destructive。 + * 字典项「颜色标记」下拉里能挑的规范色名。类型写成 `Record`: + * `_shared/dict-color.ts` 新增一个规范色,这里不补就是类型错误。 + * + * 样式在 `_shared/dict-color.ts`(`dictColorClass`)—— 种子里是 Ant Design 的色名,那边有别名映射; + * 这里原来的 `COLOR_CLASS` 只认 6 个键,其余静默回落成灰色,已经删了。 */ -export const COLOR_CLASS: Record = { - default: 'bg-muted text-foreground ring-border', - primary: 'bg-primary/10 text-primary ring-primary/25', - success: TONE_CLASS.success, - warning: TONE_CLASS.warning, - red: TONE_CLASS.danger, - gray: TONE_CLASS.muted, +export const COLOR_ITEMS: Record = { + default: '默认', primary: '主色', success: '成功', info: '信息', warning: '警告', red: '危险', gray: '灰色', } diff --git a/packages/platform/src/pages/dict/forms.tsx b/packages/platform/src/pages/dict/forms.tsx index 86537651..21c607b9 100644 --- a/packages/platform/src/pages/dict/forms.tsx +++ b/packages/platform/src/pages/dict/forms.tsx @@ -18,8 +18,9 @@ import { Textarea } from '@admin/ui/components/textarea' import { ApiError } from '../../api-client/errors' import { useFieldError } from '../_shared/form-error' +import { dictColorClass } from '../_shared/dict-color' import { - COLOR_CLASS, COLOR_ITEMS, + COLOR_ITEMS, useCreateDictData, useCreateDictType, useUpdateDictData, useUpdateDictType, type DictData, type DictType, } from './api' @@ -154,6 +155,9 @@ export function DictDataSheet({ open, onOpenChange, editing, typeId, typeName }: setErr(null) form.reset(editing ? { + // 🔴 库里的色名**原样带回**,不规范化:种子里的 Ant Design 色名(processing / magenta…)和导入写进来的 + // 任意色名(teal / #ff0000)不在下拉的 7 个里,规范化之后只改了标签保存,颜色也被静默改写(认不出的直接变 default)。 + // 下拉里给原值补一项(见 colorItems),用户不碰颜色就原样存回去 label: editing.label, value: editing.value, color: editing.color ?? 'default', sort: editing.sort, status: editing.status, remark: editing.remark ?? '', } @@ -163,6 +167,13 @@ export function DictDataSheet({ open, onOpenChange, editing, typeId, typeName }: const pending = create.isPending || update.isPending const errs = form.formState.errors const color = form.watch('color') ?? 'default' + /** 7 个规范色;当前值不是其中之一时补一项「原值」,下拉不至于显示裸文字、保存也不改写它 */ + const colorItems = React.useMemo(() => { + const entries: [string, string][] = Object.entries(COLOR_ITEMS).map(([k, v]) => [k, t(v)]) + // 一次 fromEntries 建好,不写 `items[color] = …`:色名恰好是 `__proto__` 时赋值会被当成改原型、悄悄不生效 + if (color && !Object.hasOwn(COLOR_ITEMS, color)) entries.push([color, t('原值:{{value}}', { value: color })]) + return Object.fromEntries(entries) + }, [color, t]) const statusItems = React.useMemo( () => Object.fromEntries(Object.entries(STATUS_ITEMS).map(([v, l]) => [v, t(l)])), [t] @@ -202,14 +213,14 @@ export function DictDataSheet({ open, onOpenChange, editing, typeId, typeName }:
- form.setValue('color', v ?? undefined, { shouldValidate: true })}> - {Object.entries(COLOR_ITEMS).map(([v, l]) => {t(l)})} + {Object.entries(colorItems).map(([v, l]) => {l})} - + {form.watch('label') || t('预览')}
diff --git a/packages/platform/src/pages/dict/index.tsx b/packages/platform/src/pages/dict/index.tsx index 44875ed7..3813d66b 100644 --- a/packages/platform/src/pages/dict/index.tsx +++ b/packages/platform/src/pages/dict/index.tsx @@ -27,8 +27,9 @@ import { BulkBar, RefreshButton, ResetButton, TextFilter } from '../_shared/filt import { logFeatures as features } from '../_shared/log-features' import { buildSelectColumn } from '../_shared/select-column' import { StatusBadge } from '../_shared/status' +import { dictColorClass } from '../_shared/dict-color' import { - COLOR_CLASS, dictKeys, dictDatasQuery, dictTypesQuery, + dictKeys, dictDatasQuery, dictTypesQuery, useDeleteDictDatas, useDeleteDictTypes, type DictData, type DictType, } from './api' import { DictDataSheet, DictTypeSheet } from './forms' @@ -164,7 +165,7 @@ export function DictPage({ {getValue()} diff --git a/packages/platform/src/raw.d.ts b/packages/platform/src/raw.d.ts new file mode 100644 index 00000000..40d4ff91 --- /dev/null +++ b/packages/platform/src/raw.d.ts @@ -0,0 +1,9 @@ +/** + * 测试里用 Vite 的 `?raw` 读仓库里的 SQL 种子(`pages/_shared/dict-color.test.ts`:种子里的字典色名前端是否都认)。 + * tsc 解析不到这种 import;真正处理它的是 Vite(vitest 也走 Vite)。 + * 只声明 `*.sql?raw` 这一种:apps/web 带着 vite/client(声明了通配的 `*?raw`),两个模式名不同、互不冲突。 + */ +declare module '*.sql?raw' { + const content: string + export default content +}