diff --git a/.env b/.env index 6891bfd..0bc4185 100644 --- a/.env +++ b/.env @@ -1,2 +1,3 @@ -# 后端反代目标。后端默认 8084(local profile);若 8084 被占改为 8090,此处同步改。 -VITE_BACKEND_TARGET=http://localhost:8084 +# 后端反代目标。dev profile 默认 8093(本机联调跑这个口)。 +# 若端口冲突,复制本文件为 .env.local 并改 VITE_BACKEND_TARGET(.env.local 已 gitignore,不入库)。 +VITE_BACKEND_TARGET=http://localhost:8093 diff --git a/e2e/five-ring.spec.ts b/e2e/five-ring.spec.ts new file mode 100644 index 0000000..d06c022 --- /dev/null +++ b/e2e/five-ring.spec.ts @@ -0,0 +1,114 @@ +/** + * 人走五环建新功能 · 浏览器全程点穿 e2e(实施计划 Section 6 / Task 24 的 UI 补全) + * + * NewFeatureShell 现为 amis wizard。本 spec 用真实浏览器走完整链路: + * 登录 → 设计中心「+ 新建功能」→ amis wizard:①建实体(combo 字段) → ②生成页(recipe+标题) → ③发布 + * → 经后端 API 断言:发布后 /api/menu 树出现该实体的 design- 模板节点。 + * + * 后端走 8094(含本特性新代码,不碰 dev 默认 8093)。运行: + * 先 java -jar platform-app...jar --spring.profiles.active=dev --server.port=8094 + * 再 npx playwright test -c playwright.fivering.config.ts + * 数据纪律:afterAll DELETE 测试实体(EIP4 前缀门);net-new 页/菜单/流无运行时删除端点(§F),由跑后 psql 清。 + */ +import { expect, test } from '@playwright/test'; +import http from 'node:http'; + +const BACKEND_PORT = 8094; +const TABLE = `EIP4PT_PW${Date.now()}`; +const TPL_PREFIX = `design-${TABLE.toLowerCase().replace(/_/g, '-')}`; + +function apiJson(method: string, path: string, token?: string, body?: unknown): Promise<{ status: number; json: any }> { + return new Promise((resolve, reject) => { + const data = body ? JSON.stringify(body) : undefined; + const req = http.request( + { + hostname: 'localhost', port: BACKEND_PORT, path, method, + headers: { + 'Content-Type': 'application/json', + ...(token ? { Authorization: `Bearer ${token}` } : {}), + ...(data ? { 'Content-Length': Buffer.byteLength(data) } : {}), + }, + }, + (res) => { + let buf = ''; + res.on('data', (c) => (buf += c)); + res.on('end', () => { + try { resolve({ status: res.statusCode ?? 0, json: buf ? JSON.parse(buf) : null }); } + catch { resolve({ status: res.statusCode ?? 0, json: buf }); } + }); + }, + ); + req.on('error', reject); + if (data) req.write(data); + req.end(); + }); +} + +async function adminToken(): Promise { + const r = await apiJson('POST', '/api/auth/login', undefined, { account: 'admin', password: '111111' }); + return r.json.token as string; +} + +test.afterAll(async () => { + try { + const tok = await adminToken(); + await apiJson('DELETE', `/api/meta/entity/${TABLE}`, tok); + } catch { /* 清理尽力而为 */ } +}); + +test('人走五环 · 浏览器全程点穿(amis wizard:建实体 → 生成页 → 发布 → 菜单可见)', async ({ page }) => { + test.setTimeout(120_000); + + // ── 登录(真实 React 表单)── + await page.goto('/login'); + await page.getByRole('textbox').first().fill('admin'); + await page.locator('input[type="password"]').fill('111111'); + await page.getByRole('button', { name: '登录' }).click(); + await page.waitForURL((u) => !u.pathname.endsWith('/login'), { timeout: 15_000 }); + + // ── 设计中心 → + 新建功能 ── + await page.goto('/design-center'); + await page.getByTestId('dc-new-feature').click(); + await expect(page.getByTestId('new-feature-shell')).toBeVisible(); + // 先选页面类型 = 维护型 CRUD(统一入口的类型选择卡),再进向导。 + await page.getByTestId('dc-recipe-maintenance').click(); + + // ── 环①②·amis wizard 步1 建实体(combo minLength=1 自带一行字段)── + await expect(page.getByPlaceholder('OA_DEMO')).toBeVisible({ timeout: 15_000 }); + await page.getByPlaceholder('OA_DEMO').fill(TABLE); + // 所属分类(amis select,必填):点开下拉 → 选第一个分类 + await page.locator('.cxd-Select').first().click(); + await page.locator('.cxd-Select-option').first().click(); + // combo 默认不带行(显示「<空>」),先点「加字段」再填 + await page.getByRole('button', { name: '加字段' }).click(); + await expect(page.getByPlaceholder('TITLE').first()).toBeVisible({ timeout: 10_000 }); + await page.getByPlaceholder('TITLE').first().fill('NAME'); // combo 行·列名 + await page.getByPlaceholder('标题').first().fill('名称'); // combo 行·显示名 + await page.getByRole('button', { name: '保存并下一步' }).click(); + + // ── 环③·步2 选 recipe + 标题 → compile ── + await expect(page.getByPlaceholder('如:客户等级维护')).toBeVisible({ timeout: 20_000 }); + await page.getByPlaceholder('如:客户等级维护').fill('PW五环演示'); + await page.getByRole('button', { name: '保存并下一步' }).click(); + + // ── 环④·步3 发布(菜单名已由 ${title} 预填)── + await page.getByRole('button', { name: '完成' }).click(); + + // ── 后端断言:发布后 /api/menu 树出现该实体的 design-
模板节点 ── + const tok = await adminToken(); + await expect.poll(async () => { + const r = await apiJson('GET', '/api/menu', tok); + const hit: string[] = []; + const walk = (ns: any[]) => (ns || []).forEach((n) => { + if ((n.templateId || '').startsWith(TPL_PREFIX)) hit.push(n.name); + walk(n.children); + }); + walk(r.json?.roots || []); + return hit.length; + }, { timeout: 20_000, message: '发布后菜单树应出现 design-
节点' }).toBeGreaterThan(0); +}); + +// 注:AI ①面 amis form 的渲染已人工 live 验证(截图 + 提交按钮),其 READY_FOR_HUMAN_REVIEW +// 后端链路由 curl e2e 证(status=READY + PAGE_SCHEMA.targetId,见 scripts/five-ring-acceptance.sh)。 +// 不在此自动化 AI 全程:auto-develop 的 localApply/smoke 以 baseUrl 回调,dev 经 5174→8094 代理回跳时 +// SPA 路由会干扰 smoke(生产同源无此问题),属测试环境工件,故不纳入 Playwright 断言。 diff --git a/e2e/linkage-probe.spec.ts b/e2e/linkage-probe.spec.ts new file mode 100644 index 0000000..79b34a0 --- /dev/null +++ b/e2e/linkage-probe.spec.ts @@ -0,0 +1,271 @@ +/** + * 隔离验证 · amis input-table 行内联动机制(真 Playwright 事件)。 + * + * 交接首要指令:上一会话「引用驱动联动」后端方案做了但手搓浏览器 fill 没验成功(疑 `.click()` 没触发 + * React onEvent / `${index}` componentId 替换)→ 全部回退。本 probe 不碰后端,用 page.evaluate 直接 + * amis.embed 注入「手写最小 schema」,再用真 Playwright 鼠标/键盘事件驱动,钉死正确 schema 形态: + * ① 对照组:input-number → setValue componentId=amount_${index}(amis 官方范式 input-table.md:2536)。 + * ② select(物料带 PRICE/SPEC 整行)→ onEvent.change → setValue price_${index}/spec_${index} + * = ${event.data.selectedItems[0].PRICE/SPEC}。 + * 验证兄弟列是否真被填充。结论决定后端编译器怎么发 schema(id 挂列上 vs quickEdit)。 + * + * 纯前端:select 用 static options 不打后端,故任意 vite(默认 config 反代 8093 即可,不依赖 8094)。 + */ +import { test, expect } from '@playwright/test'; + +test('amis input-table 行内联动:input-number 与 select 都应填充兄弟列', async ({ page }) => { + const consoleErrors: string[] = []; + page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()); }); + + await page.goto('/login'); + await page.waitForFunction(() => typeof (window as Window & { amisRequire?: unknown }).amisRequire === 'function', + null, { timeout: 30_000 }); + + // 注入一个覆盖层 host(不抹掉 React root,避免 React reconciliation 报错),embed 手写 schema。 + await page.evaluate(() => { + const w = window as unknown as { amisRequire: (p: string) => any }; + const host = document.createElement('div'); + host.id = 'probe-host'; + host.style.cssText = + 'position:fixed;inset:0;z-index:99999;background:#fff;padding:24px;overflow:auto'; + document.body.appendChild(host); + const amis = w.amisRequire('amis/embed'); + const schema = { + type: 'page', + data: { rows: [{}] }, // 预置一行,免去点「新增」 + body: { + type: 'form', + title: '行内联动验证', + wrapWithPanel: false, + body: [ + { + type: 'input-table', + name: 'rows', + id: 'eg-rows', + addable: true, + removable: true, + needConfirm: false, + columns: [ + { + type: 'input-number', + name: 'qty', + label: '数量', + onEvent: { + change: { + actions: [ + { actionType: 'setValue', componentId: 'amount_${index}', args: { value: '${qty * 10}' } }, + ], + }, + }, + }, + // 目标列带「真实 type」(经 quickEdit),且 id 挂在列上 —— 镜像后端编译器对普通子列的渲染形态, + // 验证 id-on-column + 显式 quickEdit type 仍能被 setValue componentId 命中。 + { name: 'amount', id: 'amount_${index}', label: '金额', quickEdit: { type: 'input-number', name: 'amount' } }, + { + type: 'select', + name: 'material', + label: '物料', + // 整行 option(PRICE/SPEC 作为额外列),模拟 picker/list 的 items(responseData options:${items}) + options: [ + { label: '水泥', value: 'C1', PRICE: '10', SPEC: '袋装' }, + { label: '钢筋', value: 'S1', PRICE: '20', SPEC: '12mm' }, + ], + onEvent: { + change: { + // 单选 select 的 change 事件 selectedItems = 被选 Option 对象本身(非数组),故 .PRICE 直取。 + // (Select.tsx changeValue: dispatchEvent('change',{value,options,items,selectedItems:value})) + actions: [ + { actionType: 'setValue', componentId: 'price_${index}', args: { value: '${event.data.selectedItems.PRICE}' } }, + { actionType: 'setValue', componentId: 'spec_${index}', args: { value: '${event.data.selectedItems.SPEC}' } }, + ], + }, + }, + }, + { name: 'price', id: 'price_${index}', label: '单价' }, + { name: 'spec', id: 'spec_${index}', label: '规格' }, + ], + }, + { + type: 'tpl', + id: 'probe-out', + tpl: 'PROBEOUT amount=[${rows[0].amount}] price=[${rows[0].price}] spec=[${rows[0].spec}]', + className: 'probe-out-marker', + }, + ], + }, + }; + amis.embed(host, schema, {}, {}); + }); + + const host = page.locator('#probe-host'); + await expect(host.locator('table')).toBeVisible({ timeout: 15_000 }); + await expect(page.getByText(/PROBEOUT/)).toBeVisible({ timeout: 10_000 }); + + const probe = page.getByText(/PROBEOUT/); + + // ---- ① 对照组:input-number qty → amount = qty*10 ---- + // input-number 的输入框:取第一行第一列的数字输入。用 .cxd-Number 更稳。 + const numberCell = host.locator('.cxd-Number input').first(); + await numberCell.click(); + await numberCell.fill('5'); + await numberCell.press('Tab'); // 失焦触发 change + // tpl 重渲染有批处理延迟,用 toContainText 自动重试(非一次性读)。 + await expect(probe, 'input-number 联动应把 amount 填成 50').toContainText('amount=[50]', { timeout: 8_000 }); + console.log('[probe] after input-number qty=5 →', await probe.textContent()); + + // ---- ② select 物料 水泥 → price=10 spec=袋装 ---- + const sel = host.locator('.cxd-Select').first(); + await sel.click(); + await page.waitForTimeout(300); + await page.getByText('水泥', { exact: true }).click(); + await expect(probe, 'select 联动应把 price 填成 10').toContainText('price=[10]', { timeout: 8_000 }); + await expect(probe, 'select 联动应把 spec 填成 袋装').toContainText('spec=[袋装]', { timeout: 8_000 }); + console.log('[probe] after select 水泥 →', await probe.textContent()); + + console.log('[probe] console errors:', JSON.stringify(consoleErrors.slice(0, 20))); +}); + +test('amis select source(远程 picker) 选项仍携带整行额外列 → 联动填充', async ({ page }) => { + // 真实后端场景:子表引用列 select 用 source=/api/picker/{ref}/list(responseData options:${items}), + // items 是整行(含 PRICE/SPEC + _id/_label)。验证远程 source 选项被选中后 selectedItems 仍带额外列。 + await page.goto('/login'); + await page.waitForFunction(() => typeof (window as Window & { amisRequire?: unknown }).amisRequire === 'function', + null, { timeout: 30_000 }); + + await page.evaluate(() => { + const w = window as unknown as { amisRequire: (p: string) => any }; + const host = document.createElement('div'); + host.id = 'probe-host2'; + host.style.cssText = 'position:fixed;inset:0;z-index:99999;background:#fff;padding:24px;overflow:auto'; + document.body.appendChild(host); + const amis = w.amisRequire('amis/embed'); + // mock fetcher:模拟 picker/list 返回整行 items(每行带 PRICE/SPEC/_id/_label/value/label)。 + const fetcher = (opt: { url: string }) => { + if (opt.url.includes('/api/picker/')) { + const items = [ + { _id: 'C1', _label: '水泥', value: 'C1', label: '水泥', PRICE: '10', SPEC: '袋装' }, + { _id: 'S1', _label: '钢筋', value: 'S1', label: '钢筋', PRICE: '20', SPEC: '12mm' }, + ]; + return Promise.resolve({ status: 200, headers: {}, data: { status: 0, msg: '', data: { items, options: items, total: 2 } } }); + } + return Promise.resolve({ status: 200, headers: {}, data: { status: 0, msg: '', data: {} } }); + }; + const schema = { + type: 'page', + data: { rows: [{}] }, + body: { + type: 'form', + title: '远程 source 联动验证', + wrapWithPanel: false, + body: [ + { + type: 'input-table', + name: 'rows', + id: 'eg-rows2', + addable: true, + removable: true, + needConfirm: false, + columns: [ + { + type: 'select', + name: 'material', + label: '物料', + source: { method: 'get', url: '/api/picker/MATERIAL/list', responseData: { options: '${items}' } }, + labelField: '_label', + valueField: '_id', + onEvent: { + change: { + actions: [ + { actionType: 'setValue', componentId: 'price_${index}', args: { value: '${event.data.selectedItems.PRICE}' } }, + { actionType: 'setValue', componentId: 'spec_${index}', args: { value: '${event.data.selectedItems.SPEC}' } }, + ], + }, + }, + }, + { name: 'price', id: 'price_${index}', label: '单价' }, + { name: 'spec', id: 'spec_${index}', label: '规格' }, + ], + }, + { type: 'tpl', id: 'probe-out2', tpl: 'PROBEOUT2 price=[${rows[0].price}] spec=[${rows[0].spec}]' }, + ], + }, + }; + amis.embed(host, schema, {}, { fetcher }); + }); + + const host = page.locator('#probe-host2'); + await expect(host.locator('table')).toBeVisible({ timeout: 15_000 }); + const probe = page.getByText(/PROBEOUT2/); + + const sel = host.locator('.cxd-Select').first(); + await sel.click(); + await page.waitForTimeout(400); // 等远程 options 加载 + await page.getByText('水泥', { exact: true }).click(); + await expect(probe, '远程 source 选项联动应填 price=10').toContainText('price=[10]', { timeout: 8_000 }); + await expect(probe, '远程 source 选项联动应填 spec=袋装').toContainText('spec=[袋装]', { timeout: 8_000 }); + console.log('[probe2] after remote select 水泥 →', await probe.textContent()); +}); + +test('amis 多行 input-table:componentId=col_${index} 按行隔离填充(行0选水泥/行1选钢筋, 互不串台)', async ({ page }) => { + // ★ 关键回归(对抗评审 HIGH 揪出):联动靠 ${index} 让 componentId 逐行展开。单行测覆盖不到「选第 2 行 + // 是否误填第 0 行」的串台风险(属红线「绝不写错值」)。本测 seed 两行,分别选不同物料,断言各行各填各的。 + await page.goto('/login'); + await page.waitForFunction(() => typeof (window as Window & { amisRequire?: unknown }).amisRequire === 'function', + null, { timeout: 30_000 }); + + await page.evaluate(() => { + const w = window as unknown as { amisRequire: (p: string) => any }; + const host = document.createElement('div'); + host.id = 'probe-host3'; + host.style.cssText = 'position:fixed;inset:0;z-index:99999;background:#fff;padding:24px;overflow:auto'; + document.body.appendChild(host); + const amis = w.amisRequire('amis/embed'); + const schema = { + type: 'page', + data: { rows: [{}, {}] }, // 两行 + body: { + type: 'form', title: '多行联动隔离验证', wrapWithPanel: false, + body: [ + { + type: 'input-table', name: 'rows', id: 'eg-rows3', + addable: true, removable: true, needConfirm: false, + columns: [ + { + type: 'select', name: 'material', label: '物料', + options: [ + { label: '水泥', value: 'C1', PRICE: '10' }, + { label: '钢筋', value: 'S1', PRICE: '20' }, + ], + onEvent: { change: { actions: [ + { actionType: 'setValue', componentId: 'price_${index}', args: { value: '${event.data.selectedItems.PRICE}' } }, + ] } }, + }, + { name: 'price', id: 'price_${index}', label: '单价' }, + ], + }, + { type: 'tpl', tpl: 'MULTI r0=[${rows[0].price}] r1=[${rows[1].price}]' }, + ], + }, + }; + amis.embed(host, schema, {}, {}); + }); + + const host = page.locator('#probe-host3'); + await expect(host.locator('table')).toBeVisible({ timeout: 15_000 }); + const probe = page.getByText(/MULTI/); + + // 行0 选水泥(10) + await host.locator('.cxd-Select').nth(0).click(); + await page.waitForTimeout(200); + await page.getByText('水泥', { exact: true }).click(); + await expect(probe, '行0选水泥应填 r0=10').toContainText('r0=[10]', { timeout: 8_000 }); + + // 行1 选钢筋(20):必须只填 r1,绝不串改 r0。 + await host.locator('.cxd-Select').nth(1).click(); + await page.waitForTimeout(200); + await page.getByText('钢筋', { exact: true }).click(); + await expect(probe, '行1选钢筋应填 r1=20').toContainText('r1=[20]', { timeout: 8_000 }); + // 串台守卫:r0 仍须是 10(行1的选择没污染行0)。 + await expect(probe, '行0不应被行1串改').toContainText('r0=[10] r1=[20]', { timeout: 8_000 }); + console.log('[probe3] multi-row →', await probe.textContent()); +}); diff --git a/e2e/master-detail.spec.ts b/e2e/master-detail.spec.ts new file mode 100644 index 0000000..877ff12 --- /dev/null +++ b/e2e/master-detail.spec.ts @@ -0,0 +1,385 @@ +/** + * 主子表(master-detail)· 浏览器全程点穿 e2e —— 走统一「新建功能」向导。 + * 设计中心「+ 新建功能」→ amis wizard:① 建实体(选「主子表」页面类型) → ②【主子表才出现】建子表 + * → ③ 生成主子页(compile master-detail-v1) → ④ 发布。 + * 断言:发布后经 API 对主表 _ADD 提交主+子行,引擎按主 LIST 列级联落库(status 0);_LOAD 回读子行。 + * 后端走 8094(playwright.fivering.config 反代)。数据纪律:afterAll 删主/子实体;其余跑后 psql 清。 + */ +import { expect, test, type Page } from '@playwright/test'; +import http from 'node:http'; + +const BACKEND_PORT = 8094; +const TS = Date.now(); +const MASTER = `EIP4PT_MDW${TS}M`; +const CHILD = `EIP4PT_MDW${TS}C`; +// 第二个用例(派生+汇总)专用表 +const MASTER2 = `EIP4PT_MDD${TS}M`; +const CHILD2 = `EIP4PT_MDD${TS}C`; +// 第三个用例(引用驱动联动)专用表:物料引用实体 + 主表 + 子表(含引用列) +const MAT = `EIP4PT_MTL${TS}`; +const MASTER3 = `EIP4PT_LKM${TS}`; +const CHILD3 = `EIP4PT_LKC${TS}`; + +function api(method: string, path: string, token?: string, body?: unknown): Promise<{ status: number; json: any }> { + return new Promise((resolve, reject) => { + const data = body ? JSON.stringify(body) : undefined; + const req = http.request({ hostname: 'localhost', port: BACKEND_PORT, path, method, + headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}), + ...(data ? { 'Content-Length': Buffer.byteLength(data) } : {}) } }, + (res) => { let b = ''; res.on('data', (c) => (b += c)); res.on('end', () => { + try { resolve({ status: res.statusCode ?? 0, json: b ? JSON.parse(b) : null }); } + catch { resolve({ status: res.statusCode ?? 0, json: b }); } }); }); + req.on('error', reject); if (data) req.write(data); req.end(); + }); +} +async function adminToken(): Promise { + const r = await api('POST', '/api/auth/login', undefined, { account: 'admin', password: '111111' }); + return r.json.token as string; +} + +// 在 schema 任意层的 input-table 里按列名找子列(不依赖 JSON 键序,标准层会重序列化打乱键序)。 +function findInputTableColumn(node: any, colName: string): any { + if (Array.isArray(node)) { + for (const n of node) { const r = findInputTableColumn(n, colName); if (r) return r; } + return null; + } + if (node && typeof node === 'object') { + if (node.type === 'input-table' && Array.isArray(node.columns)) { + const c = node.columns.find((x: any) => x?.name === colName); + if (c) return c; + } + for (const k of Object.keys(node)) { const r = findInputTableColumn(node[k], colName); if (r) return r; } + } + return null; +} + +// 登录 + 进统一新建功能向导 + 选「主子表」页面类型(使②建子表步出现)。 +async function openWizardAsMasterDetail(page: Page) { + await page.goto('/login'); + await page.getByRole('textbox').first().fill('admin'); + await page.locator('input[type="password"]').fill('111111'); + await page.getByRole('button', { name: '登录' }).click(); + await page.waitForURL((u) => !u.pathname.endsWith('/login'), { timeout: 15_000 }); + + await page.goto('/design-center'); + await page.getByTestId('dc-new-feature').click(); + await expect(page.getByTestId('new-feature-shell')).toBeVisible(); + // 先选页面类型 = 主子表(统一入口的类型选择卡)→ 进主子表向导(含②建子表步)。 + await page.getByTestId('dc-recipe-master-detail').click(); + await expect(page.getByPlaceholder('OA_DEMO')).toBeVisible({ timeout: 15_000 }); +} + +test.afterAll(async () => { + try { const tok = await adminToken(); + await api('DELETE', `/api/meta/entity/${CHILD}`, tok); + await api('DELETE', `/api/meta/entity/${MASTER}`, tok); + await api('DELETE', `/api/meta/entity/${CHILD2}`, tok); + await api('DELETE', `/api/meta/entity/${MASTER2}`, tok); + // 子表引用物料,先删子/主,再删物料引用实体。 + await api('DELETE', `/api/meta/entity/${CHILD3}`, tok); + await api('DELETE', `/api/meta/entity/${MASTER3}`, tok); + await api('DELETE', `/api/meta/entity/${MAT}`, tok); + } catch { /* best effort */ } +}); + +// 建实体 → 取 entityId。attributes 见各列 {column,display,type,referenceTable?,mandatory?}。 +async function createEntity(tok: string, table: string, name: string, etype: string, + attributes: Record[], masterTable?: string): Promise { + const body: Record = { tablename: table, name, entitytype: etype, attributes }; + if (masterTable) body.masterTable = masterTable; + const r = await api('POST', '/api/meta/entity', tok, body); + if (r.json?.status !== 0) throw new Error(`createEntity ${table} 失败: ${JSON.stringify(r.json)}`); + return r.json.data.entityId as string; +} + +// 编译 maintenance-crud + 发布(建默认流),供物料实体可 _ADD 行(picker 读真实数据)。 +// menuName 须 ≤ sys_menu.name varchar(20);本测不走菜单导航(直接 embed schema),故用短名即可。 +async function compileAndPublish(tok: string, table: string, entityId: string, menuName: string): Promise { + const c = await api('POST', '/api/design/recipe/compile', tok, + { tableName: table, recipe: 'maintenance-crud-v1', title: `${table}页` }); + const tid = c.json?.data?.templateId; + if (!tid) throw new Error(`compile ${table} 失败: ${JSON.stringify(c.json)}`); + const p = await api('POST', '/api/design/publish', tok, + { entityId, tableName: table, templateId: tid, menuName, generateDeploymentPackage: false }); + if (p.json?.status !== 0) throw new Error(`publish ${table} 失败: ${JSON.stringify(p.json)}`); +} + +test('主子表 · 统一向导全程点穿(选主子表 → 建主+子 → 生成主子页 → 发布 → 级联保存子行)', async ({ page }) => { + test.setTimeout(120_000); + await openWizardAsMasterDetail(page); + + // 步① 建主实体 + await page.getByPlaceholder('OA_DEMO').fill(MASTER); + await page.getByPlaceholder('演示(可选)').fill('采购申请'); + await page.locator('.cxd-Select').first().click(); // 所属分类 + await page.locator('.cxd-Select-option').first().click(); + await page.getByRole('button', { name: '加字段' }).click(); + await expect(page.getByPlaceholder('TITLE').first()).toBeVisible({ timeout: 10_000 }); + await page.getByPlaceholder('TITLE').first().fill('TITLE'); + await page.getByPlaceholder('标题').first().fill('标题'); + await page.getByRole('button', { name: '保存并下一步' }).click(); + + // 步② 建子表(选主子表后才出现) + await expect(page.getByPlaceholder('OA_PURCHASE_ITEM')).toBeVisible({ timeout: 15_000 }); + await page.getByPlaceholder('OA_PURCHASE_ITEM').fill(CHILD); + await page.getByPlaceholder('采购明细').fill('采购明细'); + await page.getByRole('button', { name: '加子表字段' }).click(); + await expect(page.getByPlaceholder('TITLE').first()).toBeVisible({ timeout: 10_000 }); + await page.getByPlaceholder('TITLE').first().fill('ITEMNAME'); + await page.getByPlaceholder('标题').first().fill('物料'); + await page.getByRole('button', { name: '保存并下一步' }).click(); + + // 步③ 生成主子页 + await expect(page.getByPlaceholder('如:客户等级维护')).toBeVisible({ timeout: 20_000 }); + await page.getByPlaceholder('如:客户等级维护').fill('采购申请主子'); + await page.getByRole('button', { name: '保存并下一步' }).click(); + + // 步④ 发布 + await page.getByRole('button', { name: '完成(发布)' }).click(); + + // ★ 后端断言:发布后主表 _ADD 主+2子行级联落库(LIST 列经引擎自动回填子表外键) + const tok = await adminToken(); + await expect.poll(async () => { + const r = await api('POST', `/api/flow/${MASTER}_ADD`, tok, + { TITLE: '采购单A', DETAILS: [{ ITEMNAME: '水泥' }, { ITEMNAME: '钢筋' }] }); + return r.json?.status; + }, { timeout: 25_000, message: '发布后主表 _ADD(含 DETAILS 子行)应级联成功' }).toBe(0); + + const s = await api('POST', `/api/flow/${MASTER}_SEARCH`, tok, {}); + expect(s.json?.status).toBe(0); + // 子行经 _LOAD 回读,实证级联真落库(_SEARCH 列表不嵌充子数组,_LOAD 才填充)。 + const rowA = (s.json?.data?.items ?? []).find((r: any) => r.TITLE === '采购单A'); + expect(rowA, '应查到采购单A').toBeTruthy(); + const pk = `${MASTER}_ID`; + const loaded = await api('POST', `/api/flow/${MASTER}_LOAD`, tok, { [pk]: String(rowA[pk]).trim() }); + const names = (loaded.json?.data?.result?.DETAILS ?? []).map((d: any) => d.ITEMNAME).sort(); + expect(names, '子行水泥/钢筋应级联落库').toEqual(['水泥', '钢筋']); +}); + +test('主子表派生字段+父级汇总 · 统一向导加派生/汇总 → 发布页 tpl+SUM预览+__derive+__rollup → _ADD 服务端派生再聚合', async ({ page }) => { + test.setTimeout(120_000); + await openWizardAsMasterDetail(page); + + // 步① 建主实体(含 TOTAL 汇总目标列) + await page.getByPlaceholder('OA_DEMO').fill(MASTER2); + await page.getByPlaceholder('演示(可选)').fill('派生采购'); + await page.locator('.cxd-Select').first().click(); + await page.locator('.cxd-Select-option').first().click(); + await page.getByRole('button', { name: '加字段' }).click(); + await expect(page.getByPlaceholder('TITLE').first()).toBeVisible({ timeout: 10_000 }); + await page.getByPlaceholder('TITLE').first().fill('TITLE'); + await page.getByPlaceholder('标题').first().fill('标题'); + await page.getByRole('button', { name: '加字段' }).click(); + await expect(page.getByPlaceholder('TITLE').nth(1)).toBeVisible({ timeout: 10_000 }); + await page.getByPlaceholder('TITLE').nth(1).fill('TOTAL'); + await page.getByPlaceholder('标题').nth(1).fill('总额'); + await page.getByRole('button', { name: '保存并下一步' }).click(); + + // 步② 建子表:4 列 ITEMNAME/ITEMQTY/ITEMPRICE/AMOUNT(默认 string,求值器会数字强转) + await expect(page.getByPlaceholder('OA_PURCHASE_ITEM')).toBeVisible({ timeout: 15_000 }); + await page.getByPlaceholder('OA_PURCHASE_ITEM').fill(CHILD2); + await page.getByPlaceholder('采购明细').fill('派生明细'); + const childCols = ['ITEMNAME', 'ITEMQTY', 'ITEMPRICE', 'AMOUNT']; + for (let i = 0; i < childCols.length; i++) { + await page.getByRole('button', { name: '加子表字段' }).click(); + await expect(page.getByPlaceholder('TITLE').nth(i)).toBeVisible({ timeout: 10_000 }); + await page.getByPlaceholder('TITLE').nth(i).fill(childCols[i]); + } + await page.getByRole('button', { name: '保存并下一步' }).click(); + + // 步③ 生成主子页 + 派生字段 AMOUNT=ITEMQTY*ITEMPRICE + 汇总 TOTAL=SUM(AMOUNT) + await expect(page.getByPlaceholder('如:客户等级维护')).toBeVisible({ timeout: 20_000 }); + await page.getByPlaceholder('如:客户等级维护').fill('派生采购主子'); + await page.getByRole('button', { name: '加派生字段' }).click(); + await expect(page.getByPlaceholder('MONEY')).toBeVisible({ timeout: 10_000 }); + await page.getByPlaceholder('MONEY').fill('AMOUNT'); + await page.getByPlaceholder('QTY*PRICE').fill('ITEMQTY*ITEMPRICE'); + await page.getByRole('button', { name: '加汇总字段' }).click(); + await expect(page.getByPlaceholder('TOTAL')).toBeVisible({ timeout: 10_000 }); + await page.getByPlaceholder('TOTAL').fill('TOTAL'); + await page.getByPlaceholder('AMOUNT').fill('AMOUNT'); + + // 捕获 compile 响应拿 templateId(验 UI→编译产物) + const compileResp = page.waitForResponse( + (r) => r.url().includes('/api/design/recipe/compile') && r.request().method() === 'POST'); + await page.getByRole('button', { name: '保存并下一步' }).click(); + const tid = (await (await compileResp).json())?.data?.templateId as string; + expect(tid, 'compile 应返回 templateId').toBeTruthy(); + + // 步④ 发布 + await page.getByRole('button', { name: '完成(发布)' }).click(); + + const tok = await adminToken(); + + // ★ 断言1:子表 AMOUNT 列只读 tpl 实时预览 + 表单 api 透传 __derive + const schema = (await api('GET', `/api/page/schema/${tid}`, tok)).json; + expect(JSON.stringify(schema), '表单 api 应透传 __derive').toContain('__derive'); + const amountCol = findInputTableColumn(schema, 'AMOUNT'); + expect(amountCol, 'AMOUNT 列应存在于 input-table').toBeTruthy(); + expect(amountCol.type).toBe('tpl'); + expect(amountCol.tpl).toBe('${ITEMQTY*ITEMPRICE}'); + expect(amountCol.quickEdit, '派生列 quickEdit 必须显式 false 才保留只读 tpl 预览').toBe(false); + + // ★ 断言1b:主表 TOTAL 汇总列只读 static + SUM 实时预览 + 表单 api 透传 __rollup + expect(JSON.stringify(schema), '表单 api 应透传 __rollup').toContain('__rollup'); + expect(JSON.stringify(schema), '主表 TOTAL 应为 SUM(ARRAYMAP) 实时预览') + .toContain('SUM(ARRAYMAP(DETAILS, item => item.ITEMQTY*item.ITEMPRICE))'); + + // ★ 断言2:_ADD 带 __derive+__rollup,子行不带 AMOUNT、主体不带 TOTAL,服务端逐行派生再聚合 + await expect.poll(async () => { + const r = await api('POST', + `/api/flow/${MASTER2}_ADD?__derive=${encodeURIComponent('DETAILS|AMOUNT=ITEMQTY*ITEMPRICE')}` + + `&__rollup=${encodeURIComponent('TOTAL=SUM:DETAILS:AMOUNT')}`, tok, + { TITLE: '派生单A', DETAILS: [ + { ITEMNAME: '水泥', ITEMQTY: 3, ITEMPRICE: 10 }, + { ITEMNAME: '钢筋', ITEMQTY: 2, ITEMPRICE: '12.5' }] }); + return r.json?.status; + }, { timeout: 25_000, message: '派生+汇总 _ADD 应成功' }).toBe(0); + + const s = await api('POST', `/api/flow/${MASTER2}_SEARCH`, tok, {}); + expect(s.json?.status).toBe(0); + const rows: any[] = s.json?.data?.items ?? []; + const rowA = rows.find((r) => r.TITLE === '派生单A'); + expect(rowA, '应查到派生单A').toBeTruthy(); + const pk = `${MASTER2}_ID`; + const loaded = await api('POST', `/api/flow/${MASTER2}_LOAD`, tok, { [pk]: String(rowA[pk]).trim() }); + const details: any[] = loaded.json?.data?.result?.DETAILS ?? []; + const amts = details.map((d) => Number(d.AMOUNT)).sort((a, b) => a - b); + expect(amts, '服务端派生 AMOUNT=数量×单价(3×10=30,2×12.5=25)').toEqual([25, 30]); + expect(Number(loaded.json?.data?.result?.TOTAL), '服务端聚合 TOTAL=55').toBe(55); +}); + +test('引用驱动联动 · 子表选物料(真 Playwright 事件)→带出单价/规格, 校验 schema + 真实填充 + 提交落库', async ({ page }) => { + test.setTimeout(120_000); + const tok = await adminToken(); + + // 取一个实体分类 id + const types = await api('GET', '/api/meta/entity-types', tok); + const etype = (types.json?.data ?? [])[0]?.id; + expect(etype, '应有可用实体分类').toBeTruthy(); + + // ── 设置(API):物料引用实体(含 PRICE/SPEC)+ 发布建流 + 2 行(picker 读真实数据)── + const matId = await createEntity(tok, MAT, '物料', etype, [ + { column: 'MATNAME', display: '物料名', type: 'string', mandatory: true }, + { column: 'PRICE', display: '单价', type: 'number' }, + { column: 'SPEC', display: '规格', type: 'string' }, + ]); + await compileAndPublish(tok, MAT, matId, '物料联动'); + expect((await api('POST', `/api/flow/${MAT}_ADD`, tok, + { MATNAME: '水泥', PRICE: 10, SPEC: '袋装' })).json?.status, '物料水泥 _ADD').toBe(0); + expect((await api('POST', `/api/flow/${MAT}_ADD`, tok, + { MATNAME: '钢筋', PRICE: 20, SPEC: '12mm' })).json?.status, '物料钢筋 _ADD').toBe(0); + + // ── 设置(API):主表 + 子表(子表含引用列 ITEMID→物料、被带出列 ITEMPRICE/ITEMSPEC)── + const masterId = await createEntity(tok, MASTER3, '采购联动', etype, [ + { column: 'TITLE', display: '标题', type: 'string', mandatory: true }, + ]); + await createEntity(tok, CHILD3, '采购联动明细', etype, [ + { column: 'ITEMNAME', display: '明细名', type: 'string' }, + { column: 'ITEMID', display: '物料', type: 'reference', referenceTable: MAT }, + { column: 'ITEMPRICE', display: '单价', type: 'number' }, + { column: 'ITEMSPEC', display: '规格', type: 'string' }, + ], MASTER3); + + // ── 编译 master-detail + 引用驱动联动(ITEMID 选中→带出 ITEMPRICE←PRICE / ITEMSPEC←SPEC)── + const compileResp = await api('POST', '/api/design/recipe/compile', tok, { + tableName: MASTER3, recipe: 'master-detail-v1', title: '采购联动单', + childTable: CHILD3, linkColumn: 'MASTERID', listColumn: 'DETAILS', listLabel: '明细', + childLinkage: [{ refColumn: 'ITEMID', fills: [ + { target: 'ITEMPRICE', source: 'PRICE' }, { target: 'ITEMSPEC', source: 'SPEC' }] }], + }); + const tid = compileResp.json?.data?.templateId; + expect(tid, 'master-detail compile 应返回 templateId').toBeTruthy(); + await api('POST', '/api/design/publish', tok, + { entityId: masterId, tableName: MASTER3, templateId: tid, menuName: '采购联动单', generateDeploymentPackage: false }); + + // ── 断言 1:生成的 schema 形态正确(select source=picker + onEvent setValue selectedItems.,无 [0])── + const schema = (await api('GET', `/api/page/schema/${tid}`, tok)).json; + const sj = JSON.stringify(schema); + expect(sj, 'ITEMID 列应为 picker select 取物料').toContain(`/api/picker/${MAT}/list`); + expect(sj, '联动应发 setValue 带出 PRICE').toContain('${event.data.selectedItems.PRICE}'); + expect(sj, '联动目标列 ITEMPRICE 应挂 id=ITEMPRICE_${index}').toContain('ITEMPRICE_${index}'); + // 联动 onEvent 里单选 select 的 selectedItems 是对象非数组,绝不能写 event.data.selectedItems[0] + // (这是上一会话 fill 失败的真因)。注意 CRUD 编辑按钮的 ${selectedItems[0]}=选中主行(数组)是另一回事,合法。 + expect(sj, '联动取值绝不能含 event.data.selectedItems[0]').not.toContain('event.data.selectedItems[0]'); + + // 取 picker 真实选项:找出「水泥」行的显示标签(_label 可能是显示名也可能是裸 id)与其 PRICE, + // UI 按真实 _label 文本点选(不假设显示名=MATNAME,规避新实体无显示列时 _label=裸 id 的情况)。 + const picker = await api('GET', `/api/picker/${MAT}/list`, tok); + const pickerItems: any[] = picker.json?.data?.items ?? []; + const cement = pickerItems.find((i) => i.MATNAME === '水泥'); + expect(cement, 'picker 应返回水泥行').toBeTruthy(); + expect(String(cement.PRICE), 'picker items 应携带整行 PRICE 列(联动源)').toBe('10'); + const cementLabel = String(cement._label).trim(); + + // ── 断言 2:真实渲染 + 真 Playwright 事件填充 ── + // 取真实 schema 的「新增」表单(含真实 input-table 引用列 select),seed 一行 + 探针 tpl,amis.embed + // 用「真后端 token fetcher」渲染(picker 打真实 8094)。不是手写 schema——是后端真产物。 + await page.goto('/login'); + await page.waitForFunction(() => typeof (window as Window & { amisRequire?: unknown }).amisRequire === 'function', + null, { timeout: 30_000 }); + + await page.evaluate(([realSchema, token, masterTable]) => { + const w = window as unknown as { amisRequire: (p: string) => any }; + const host = document.createElement('div'); + host.id = 'lk-host'; + host.style.cssText = 'position:fixed;inset:0;z-index:99999;background:#fff;padding:24px;overflow:auto'; + document.body.appendChild(host); + // 真后端 fetcher:复用 vite /api 代理到 8094,带 admin Bearer。 + const fetcher = async (opt: { url: string; method?: string; data?: unknown }) => { + const method = (opt.method || 'get').toLowerCase(); + const res = await fetch(opt.url, { + method, + headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` }, + body: method === 'get' ? undefined : JSON.stringify(opt.data || {}), + }); + const json = await res.json().catch(() => ({})); + return { status: res.status, headers: {}, data: json }; + }; + // 从真实 schema 取「新增」按钮的对话框表单(含真 input-table)。 + const hb = (realSchema as any).body.headerToolbar as any[]; + const addBtn = hb.find((b) => b && b.id === '新增'); + const form = addBtn.dialog.body; + // 探针 tpl 放进表单内(数据域含 DETAILS),实时反映联动填充结果。 + form.body.push({ type: 'tpl', + tpl: 'PROBELK price=[${DETAILS[0].ITEMPRICE}] spec=[${DETAILS[0].ITEMSPEC}]' }); + const pageSchema = { type: 'page', + data: { TITLE: '联动单A', DETAILS: [{}] }, // seed 一行免点「新增行」 + body: [form] }; + void masterTable; + w.amisRequire('amis/embed').embed(host, pageSchema, {}, { fetcher }); + }, [schema, tok, MASTER3] as const); + + const host = page.locator('#lk-host'); + await expect(host.locator('table')).toBeVisible({ timeout: 15_000 }); + const probe = page.getByText(/PROBELK/); + + // 真事件:打开子表行内 ITEMID select → 选「水泥」。 + const sel = host.locator('.cxd-Select').first(); + await sel.click(); + // 等真实 picker options 渲染(替固定 sleep),再在下拉里(scoped .cxd-Select-option)按 _label 点选—— + // 避免 getByText 误命中全屏 host 上的其它同文本节点。 + await page.locator('.cxd-Select-option').first().waitFor({ timeout: 8_000 }); + await page.locator('.cxd-Select-option', { hasText: cementLabel }).first().click(); + + // ★ 联动填充:选物料→自动带出单价 10 / 规格 袋装(真后端 schema + 真事件,非手写)。 + await expect(probe, '选水泥应带出 ITEMPRICE=10').toContainText('price=[10]', { timeout: 8_000 }); + await expect(probe, '选水泥应带出 ITEMSPEC=袋装').toContainText('spec=[袋装]', { timeout: 8_000 }); + + // ── 断言 3:提交 → 落库(_LOAD 回读子行 ITEMPRICE=10,证明填充值真随主表 _ADD 级联落库)── + await host.getByRole('button', { name: '提交' }).click(); + await expect.poll(async () => { + const s = await api('POST', `/api/flow/${MASTER3}_SEARCH`, tok, {}); + return (s.json?.data?.items ?? []).find((r: any) => r.TITLE === '联动单A') ? 'ok' : 'wait'; + }, { timeout: 20_000, message: '提交后主表应查到联动单A' }).toBe('ok'); + const s = await api('POST', `/api/flow/${MASTER3}_SEARCH`, tok, {}); + const rowA = (s.json?.data?.items ?? []).find((r: any) => r.TITLE === '联动单A'); + const pk = `${MASTER3}_ID`; + const loaded = await api('POST', `/api/flow/${MASTER3}_LOAD`, tok, { [pk]: String(rowA[pk]).trim() }); + const child = (loaded.json?.data?.result?.DETAILS ?? [])[0]; + expect(child, '应级联落子行').toBeTruthy(); + // 所选物料(引用列 FK=_id)本身应落库——证明 select valueField=_id 绑定生效(fill 之外的主契约)。 + expect(String(child.ITEMID).trim(), '所选物料引用FK应落库').toBe(String(cement._id).trim()); + expect(Number(child.ITEMPRICE), '联动带出的单价应随提交落库=10(用户未手填)').toBe(10); + expect(String(child.ITEMSPEC).trim(), '联动带出的规格应随提交落库=袋装').toBe('袋装'); +}); diff --git a/e2e/recipe-render-smoke.spec.ts b/e2e/recipe-render-smoke.spec.ts new file mode 100644 index 0000000..ab206e6 --- /dev/null +++ b/e2e/recipe-render-smoke.spec.ts @@ -0,0 +1,169 @@ +/** + * AI recipe 渲染冒烟门(M-Gate 的可执行化)。 + * + * 把「手动用浏览器验 AI 生成页是否真渲染成 house-style」codify 成一条可复用断言: + * 给定一个 templateId,从【已生成并 served】的页面 schema 自推期望(列/动作),再断言 + * amis 真把它渲染成无错 DOM——补上 critic 点名「playwright-render 名实不符(从不真渲染)」的缺口。 + * + * 断言(schema 驱动,recipe 无关): + * ① amis-host 可见 且 无 schema-error-card → 渲染无致命错 + * ② body=crud,且 schema 每个数据列 label 出现在表头 → 列真渲染 + * ③ schema 里每个 {type:button} 的 label 出现在页面 → 工具栏/节点动作真渲染 + * ④ tbody 无裸 true/false、无裸 ISO 时间串 → 列渲染类型(是/否、日期格式)生效 + * ⑤ 0 pageerror + 0 console.error → 无运行时报错 + * + * 入参(env):RECIPE_SMOKE_TEMPLATE(必填,templateId)。 + * 前置:localhost:5174(前端 dev)+ localhost:8093(后端 dev)。页面须已 served。 + * 运行:RECIPE_SMOKE_TEMPLATE= npx playwright test --config=playwright.recipe-smoke.config.ts + */ +import { expect, test, type Page, type ConsoleMessage } from '@playwright/test'; +import * as http from 'node:http'; +import * as path from 'node:path'; +import * as fs from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +const TEMPLATE_ID = process.env.RECIPE_SMOKE_TEMPLATE ?? ''; +const ARTIFACT_DIR = path.join(__dirname, 'artifacts', 'recipe-render-smoke'); + +let _tokenCache: string | null = null; + +function getJson(reqPath: string, body?: string): Promise { + return new Promise((resolve, reject) => { + const req = http.request( + { + hostname: 'localhost', + port: 8093, + path: reqPath, + method: body ? 'POST' : 'GET', + headers: body + ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } + : {}, + }, + (res) => { + let data = ''; + res.on('data', (c) => (data += c)); + res.on('end', () => { + try { + resolve(JSON.parse(data) as T); + } catch (e) { + reject(new Error(`非 JSON 响应 ${reqPath}: ${data.slice(0, 200)}`)); + } + }); + }, + ); + req.on('error', reject); + if (body) req.write(body); + req.end(); + }); +} + +async function getToken(): Promise { + if (_tokenCache) return _tokenCache; + const parsed = await getJson<{ success: boolean; token: string }>( + '/api/auth/login', + JSON.stringify({ account: 'admin', password: '111111' }), + ); + if (!parsed.success) throw new Error('登录失败'); + _tokenCache = parsed.token; + return parsed.token; +} + +async function seedAuth(page: Page) { + const token = await getToken(); + await page.addInitScript( + ({ t }: { t: string }) => { + localStorage.setItem('eip4_token', t); + localStorage.setItem( + 'eip4_profile', + JSON.stringify({ userId: 'ADMIN', account: 'admin', name: '系统管理员', roles: [] }), + ); + }, + { t: token }, + ); +} + +/** 递归收集 schema 中所有 {type:'button'} 节点的 label —— 工具栏 + 节点操作动作。 */ +function collectButtonLabels(node: unknown, out: Set): void { + if (Array.isArray(node)) { + node.forEach((n) => collectButtonLabels(n, out)); + return; + } + if (node && typeof node === 'object') { + const obj = node as Record; + if (obj.type === 'button' && typeof obj.label === 'string' && obj.label.trim()) { + out.add(obj.label.trim()); + } + Object.values(obj).forEach((v) => collectButtonLabels(v, out)); + } +} + +test.beforeAll(() => { + fs.mkdirSync(ARTIFACT_DIR, { recursive: true }); + if (!TEMPLATE_ID) throw new Error('缺 env RECIPE_SMOKE_TEMPLATE'); +}); + +test(`AI recipe 页 ${TEMPLATE_ID} 渲染成无错 house-style DOM`, async ({ page }) => { + // 0 console.error / pageerror 收集(house-style 页应零报错)。 + const consoleErrors: string[] = []; + page.on('console', (m: ConsoleMessage) => { + if (m.type() === 'error') consoleErrors.push(m.text()); + }); + page.on('pageerror', (e) => consoleErrors.push(`pageerror: ${e.message}`)); + + // 自推期望:从 served schema 拿数据列 label 与所有按钮 label。 + const schema = await getJson<{ + body?: { type?: string; columns?: Array<{ name?: string; label?: string; type?: string }> }; + }>(`/api/page/schema/${TEMPLATE_ID}`); + expect(schema.body?.type, 'body.type 应为 crud').toBe('crud'); + const dataColumnLabels = (schema.body?.columns ?? []) + .filter((c) => c.name && c.label && c.type !== 'operation') + .map((c) => c.label!) as string[]; + const buttonLabels = new Set(); + collectButtonLabels(schema, buttonLabels); + + await seedAuth(page); + await page.goto(`/page/${TEMPLATE_ID}`); + + // ① 渲染完成且无致命错卡。 + await expect(page.locator('[data-testid="amis-host"]')).toBeVisible({ timeout: 45_000 }); + await expect(page.locator('[data-testid="schema-error-card"]')).not.toBeVisible(); + await page + .waitForSelector( + '[data-testid="amis-host"] table, [data-testid="amis-host"] .cxd-CRUD', + { timeout: 20_000 }, + ) + .catch(() => {/* 空表也算渲染成功,继续 */}); + + await page.screenshot({ + path: path.join(ARTIFACT_DIR, `${TEMPLATE_ID}-full.png`), + fullPage: true, + }); + + const bodyText = (await page.textContent('body')) ?? ''; + + // ② 每个数据列 label 出现在页面(表头)。 + for (const label of dataColumnLabels) { + expect(bodyText, `列「${label}」应渲染`).toContain(label); + } + + // ③ 每个按钮 label 出现在页面(工具栏/节点动作真渲染)。 + for (const label of Array.from(buttonLabels)) { + expect(bodyText, `动作「${label}」应渲染`).toContain(label); + } + + // ④ 列渲染类型生效:表体无裸 true/false、无裸 ISO 时间串。 + const tbodyText = await page + .evaluate(() => document.querySelector('tbody')?.textContent ?? '') + .catch(() => ''); + if (tbodyText.trim()) { + expect(tbodyText, '布尔列应渲染为 是/否,而非裸 true').not.toMatch(/\btrue\b/); + expect(tbodyText, '布尔列应渲染为 是/否,而非裸 false').not.toMatch(/\bfalse\b/); + expect(tbodyText, '日期列应格式化,而非裸 ISO 串').not.toMatch(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/); + } + + // ⑤ 0 console.error / pageerror。 + expect(consoleErrors, `控制台报错:\n${consoleErrors.join('\n')}`).toHaveLength(0); +}); diff --git a/editor.html b/editor.html index c6c61c6..e08a2ff 100644 --- a/editor.html +++ b/editor.html @@ -5,12 +5,15 @@ EIP4 页面设计器 - - - - + diff --git a/playwright.fivering.config.ts b/playwright.fivering.config.ts new file mode 100644 index 0000000..e3765d4 --- /dev/null +++ b/playwright.fivering.config.ts @@ -0,0 +1,26 @@ +import { defineConfig, devices } from '@playwright/test'; + +// 人走五环 UI 点穿 e2e 专用配置:webServer 反代到 8094(含本特性新代码), +// 与默认 playwright.config.ts(反代 8093 dev)隔离,不影响你正在跑的 8093。 +// 先单独启动 8094 后端,再 `npx playwright test -c playwright.fivering.config.ts`。 +export default defineConfig({ + testDir: './e2e', + testMatch: /(five-ring|master-detail)\.spec\.ts/, + fullyParallel: false, + workers: 1, + timeout: 120_000, + reporter: [['list']], + use: { + baseURL: 'http://localhost:5174', + trace: 'off', + screenshot: 'only-on-failure', + }, + projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], + webServer: { + command: + 'NODE_OPTIONS=--max-http-header-size=65536 VITE_BACKEND_TARGET=http://localhost:8094 npx vite --port 5174 --strictPort', + url: 'http://localhost:5174', + reuseExistingServer: false, + timeout: 120_000, + }, +}); diff --git a/playwright.recipe-smoke.config.ts b/playwright.recipe-smoke.config.ts new file mode 100644 index 0000000..5351a06 --- /dev/null +++ b/playwright.recipe-smoke.config.ts @@ -0,0 +1,30 @@ +import { defineConfig, devices } from '@playwright/test'; + +// ──────────────────────────────────────────────────────────────────────────── +// AI recipe 渲染冒烟门专属配置(M-Gate 可执行化)。 +// +// 与默认 playwright.config.ts 的区别(关键): +// - 复用【已在跑】的 5174 dev server,不自拉 webServer(不重启任何服务)。 +// - 仅匹配 recipe-render-smoke.spec.ts。 +// +// 一键跑(含生成/清理):见 recipe-render-smoke.sh +// 单跑某页:RECIPE_SMOKE_TEMPLATE= npx playwright test --config=playwright.recipe-smoke.config.ts +// 前置:localhost:5174(前端 dev)+ localhost:8093(后端 dev/eip4dev)。 +// ──────────────────────────────────────────────────────────────────────────── +export default defineConfig({ + testDir: './e2e', + testMatch: /recipe-render-smoke\.spec\.ts/, + fullyParallel: false, + workers: 1, + timeout: 90_000, + reporter: [['list']], + outputDir: './e2e/artifacts/recipe-render-smoke/_pw-output', + use: { + baseURL: 'http://localhost:5174', + trace: 'retain-on-failure', + screenshot: 'only-on-failure', + video: 'off', + }, + projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], + // 故意不配置 webServer —— 复用已在跑的 5174,不重启。 +}); diff --git a/recipe-render-smoke.sh b/recipe-render-smoke.sh new file mode 100755 index 0000000..1d3a1d7 --- /dev/null +++ b/recipe-render-smoke.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# ───────────────────────────────────────────────────────────────────────────── +# AI recipe 渲染冒烟门 —— 一键端到端(M-Gate 可执行化)。 +# +# 把「手动用浏览器验 AI 生成页渲染成 house-style」codify 成一条命令: +# 1) 登录拿 admin token +# 2) 经 AI pipeline 生成 1 个 maintenance + 1 个 tree 隔离样例(auto-develop) +# 3) 用 recipe-render-smoke.spec 断言两页真渲染成无错 house-style DOM +# 4) DROP 表 + 删三真相行清理(trap 保证失败也清,sys_ai_* 审计保留) +# +# 前置:localhost:8093(后端 dev/eip4dev)+ localhost:5174(前端 dev)+ psql:5433。 +# 跑: cd eip4-web && ./recipe-render-smoke.sh +# ───────────────────────────────────────────────────────────────────────────── +set -uo pipefail + +BACKEND="${BACKEND:-http://localhost:8093}" +PGHOST="${PGHOST:-localhost}"; PGPORT="${PGPORT:-5433}"; PGUSER="${PGUSER:-zhengwr}"; PGDB="${PGDB:-eip4dev}" +export PGPASSWORD="${PGPASSWORD:-}" +SMOKE_TABLES=(EIP4AI_SMOKE_M EIP4AI_SMOKE_T) + +psql_run() { psql -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" -d "$PGDB" -v ON_ERROR_STOP=1 -At "$@"; } + +cleanup() { + for t in "${SMOKE_TABLES[@]}"; do + local tpl tbl + tpl="$(echo "$t" | tr 'A-Z_' 'a-z-')" # EIP4AI_SMOKE_M → eip4ai-smoke-m (templateId) + tbl="$(echo "$t" | tr 'A-Z' 'a-z')" # EIP4AI_SMOKE_M → eip4ai_smoke_m (物理表,PG 折叠小写) + psql_run -c "DROP TABLE IF EXISTS eip3.${tbl}; + DELETE FROM eip3.sys_entity WHERE upper(tablename)='${t}'; + DELETE FROM eip3.sys_page_schema WHERE template_id='${tpl}'; + DELETE FROM eip3.sys_serviceflow WHERE upper(sys_serviceflow_id) LIKE '${t}\\_%'; + DELETE FROM eip3.sys_menu WHERE view_templateid='${tpl}';" >/dev/null 2>&1 + done + echo "🧹 清理完成(${SMOKE_TABLES[*]})" +} +trap cleanup EXIT + +login() { + curl -s -X POST "$BACKEND/api/auth/login" -H 'Content-Type: application/json' \ + -d '{"account":"admin","password":"111111"}' \ + | python3 -c "import sys,json;print(json.load(sys.stdin).get('token',''))" +} + +# auto_dev
+auto_dev() { + local table="$1" tpl="$2" name="$3" recipe="$4" + curl -s -X POST "$BACKEND/api/ai/features/auto-develop" \ + -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" \ + -d "{\"feature\":{\"objective\":\"render-smoke\",\"featureName\":\"${name}维护\",\"tableName\":\"${table}\",\"entityName\":\"${name}\",\"templateId\":\"${tpl}\",\"menuName\":\"${name}\",\"fields\":[{\"column\":\"NAME\",\"label\":\"名称\",\"type\":\"string\",\"length\":100,\"required\":true},{\"column\":\"ENABLED\",\"label\":\"启用\",\"type\":\"boolean\",\"required\":false}],\"pageRecipe\":\"${recipe}\"},\"baseUrl\":\"${BACKEND}\",\"generateDeploymentPackage\":true,\"maxRepairAttempts\":2}" \ + | python3 -c "import sys,json;d=json.load(sys.stdin);print((d.get('applyRun') or {}).get('status','?'))" +} + +echo "🔑 登录…"; TOKEN="$(login)" +[ -n "$TOKEN" ] || { echo "❌ 登录失败"; exit 1; } + +echo "🏗 生成 maintenance 样例…"; [ "$(auto_dev EIP4AI_SMOKE_M eip4ai-smoke-m 列渲染样例 maintenance-crud-v1)" = "PASSED" ] || { echo "❌ maintenance apply 未 PASSED"; exit 1; } +echo "🌲 生成 tree 样例…"; [ "$(auto_dev EIP4AI_SMOKE_T eip4ai-smoke-t 树样例 tree-crud-v1)" = "PASSED" ] || { echo "❌ tree apply 未 PASSED"; exit 1; } + +rc=0 +for tpl in eip4ai-smoke-m eip4ai-smoke-t; do + echo "🖥 渲染断言 $tpl …" + RECIPE_SMOKE_TEMPLATE="$tpl" npx playwright test --config=playwright.recipe-smoke.config.ts || rc=1 +done + +[ "$rc" = 0 ] && echo "✅ recipe 渲染冒烟全绿" || echo "❌ recipe 渲染冒烟有失败" +exit "$rc" diff --git a/src/App.routes.test.tsx b/src/App.routes.test.tsx new file mode 100644 index 0000000..31f1b5e --- /dev/null +++ b/src/App.routes.test.tsx @@ -0,0 +1,47 @@ +import '@testing-library/jest-dom'; +import { render, screen, waitFor } from '@testing-library/react'; +import { MemoryRouter, Routes, Route } from 'react-router-dom'; +import { vi, describe, it, expect } from 'vitest'; +import { NewFeatureShell } from './pages/NewFeatureShell'; +import { AiFeatureForm } from './pages/AiFeatureForm'; + +vi.mock('./auth/token', () => ({ + getProfile: () => ({ userId: 'ADMIN', account: 'admin', name: 'x', roles: [] }), +})); +vi.mock('./api/meta', () => ({ listEntities: vi.fn().mockResolvedValue([]), createEntity: vi.fn() })); +vi.mock('./api/recipe', () => ({ + listRecipes: () => [{ id: 'maintenance-crud-v1', label: '维护型 CRUD' }], + compileRecipe: vi.fn(), +})); +vi.mock('./api/publish', () => ({ publishFeature: vi.fn() })); +vi.mock('./api/menu', () => ({ fetchMenu: vi.fn().mockResolvedValue({ roots: [] }), collectLeaves: vi.fn() })); +vi.mock('./api/ai', async (io) => { + const actual = await io(); + return { ...actual, autoDevelop: vi.fn() }; +}); + +describe('新路由可达', () => { + it('/new-feature 渲染 NewFeatureShell', async () => { + render( + + + } /> + } /> + + , + ); + await waitFor(() => expect(screen.getByTestId('new-feature-shell')).toBeInTheDocument()); + }); + + it('/ai-feature 渲染 AiFeatureForm', () => { + render( + + + } /> + } /> + + , + ); + expect(screen.getByTestId('ai-feature-form')).toBeInTheDocument(); + }); +}); diff --git a/src/App.tsx b/src/App.tsx index abf6e3a..4c4e1dc 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -8,6 +8,9 @@ import { PageRenderPage } from './pages/PageRenderPage'; import { TodoPage } from './pages/TodoPage'; import { WorkbenchPage } from './pages/WorkbenchPage'; import { DesignCenterPage } from './pages/DesignCenterPage'; +import { NewFeatureShell } from './pages/NewFeatureShell'; +import { AiFeatureForm } from './pages/AiFeatureForm'; +import { ModelerPage } from './pages/ModelerPage'; // 把 401 跳登录的 handler 注入 http 层(在路由上下文内,可用 navigate) function UnauthorizedBridge() { @@ -40,6 +43,11 @@ export default function App() { } /> {/* 设计中心(管理员集中式低代码设计入口,替代每页设计按钮)*/} } /> + {/* 人走五环统一编排壳(向导内选页面类型:单表/树/主子表)+ AI ①面入口(admin-gated)*/} + } /> + } /> + {/* 建模器(五环第①环·元数据→表,仅管理员)*/} + } /> {/* 根路径默认跳工作台 */} } /> diff --git a/src/api/ai.test.ts b/src/api/ai.test.ts new file mode 100644 index 0000000..4686360 --- /dev/null +++ b/src/api/ai.test.ts @@ -0,0 +1,33 @@ +import { describe, it, expect } from 'vitest'; +import { extractPageSchemaTemplateId } from './ai'; +import type { AiAutoDevelopRun } from './ai'; + +describe('extractPageSchemaTemplateId', () => { + it('从 PAGE_SCHEMA draft 取 targetId', () => { + const run: AiAutoDevelopRun = { + taskId: 't1', + status: 'READY_FOR_HUMAN_REVIEW', + development: { + drafts: [ + { artifactType: 'FLOW', targetId: 'OA_X_ADD' }, + { artifactType: 'PAGE_SCHEMA', targetId: 'TPL-AI-9' }, + ], + }, + }; + expect(extractPageSchemaTemplateId(run)).toBe('TPL-AI-9'); + }); + + it('无 PAGE_SCHEMA draft 时返回 undefined', () => { + const run: AiAutoDevelopRun = { + taskId: 't2', + status: 'READY_FOR_HUMAN_REVIEW', + development: { drafts: [{ artifactType: 'FLOW', targetId: 'X' }] }, + }; + expect(extractPageSchemaTemplateId(run)).toBeUndefined(); + }); + + it('development 缺失时安全返回 undefined', () => { + const run: AiAutoDevelopRun = { taskId: 't3', status: 'FAILED' }; + expect(extractPageSchemaTemplateId(run)).toBeUndefined(); + }); +}); diff --git a/src/api/ai.ts b/src/api/ai.ts new file mode 100644 index 0000000..c325a0a --- /dev/null +++ b/src/api/ai.ts @@ -0,0 +1,67 @@ +// AI ①面加速器入口 —— POST /api/ai/features/auto-develop(admin)。 +// 平台进程内不内置生成 LLM:实际起草由外部 agent + Skills 完成,本接口只是确定性编排+人审门禁。 +// 终端良态 status === 'READY_FOR_HUMAN_REVIEW'(红线:永不自动发布)。 +// +// ⚠️ 端口约束:后端 auto-develop 会以 baseUrl 回调写后端。dev 默认 8084 已死, +// 本前端透传 baseUrl = window.location.origin(经 vite 代理 /api → 8093)。 +// 若省略 baseUrl,则要求后端 dev profile 自身的 baseUrl 指向 8093(根因修在后端 Section)。 +import { http } from './http'; + +export interface AiFeatureField { + column: string; + label: string; + type: string; + length?: number; + required?: boolean; +} + +export interface AiAutoDevelopBody { + feature: { + objective: string; + featureName: string; + tableName: string; + entityName: string; + templateId?: string; + menuName?: string; + fields: AiFeatureField[]; + pageRecipe: 'maintenance-crud-v1' | 'tree-crud-v1'; + }; + baseUrl?: string; + generateDeploymentPackage?: boolean; + maxRepairAttempts?: number; +} + +export interface AiDraft { + artifactType: string; // 'PAGE_SCHEMA' | 'FLOW' | ... + targetId: string; + payload?: unknown; +} + +export interface AiAutoDevelopRun { + taskId: string; + status: string; // 'READY_FOR_HUMAN_REVIEW' = 终端良态 + development?: { drafts?: AiDraft[] }; + applyRun?: unknown; + deploymentPackage?: unknown; + messages?: string[]; +} + +/** 终端良态判定(红线:AI 入口产物恒此状态才可人审进设计器)。 */ +export const READY_STATUS = 'READY_FOR_HUMAN_REVIEW'; + +/** 从 run 提取 PAGE_SCHEMA draft 的 targetId(即写入 standard 层的 templateId)。 */ +export function extractPageSchemaTemplateId(run: AiAutoDevelopRun): string | undefined { + return run.development?.drafts?.find((d) => d.artifactType === 'PAGE_SCHEMA')?.targetId; +} + +export async function autoDevelop(body: AiAutoDevelopBody): Promise { + // §B.9-10:默认值放后、用 ?? 兜底,避免显式传入的 undefined 覆盖默认; + // 透传 baseUrl=当前前端 origin,让后端回调经 vite 代理打到正在跑的 8093(而非死的 8084)。 + const payload: AiAutoDevelopBody = { + ...body, + baseUrl: body.baseUrl ?? window.location.origin, + generateDeploymentPackage: body.generateDeploymentPackage ?? true, + }; + const { data } = await http.post('/api/ai/features/auto-develop', payload); + return data; +} diff --git a/src/api/meta.test.ts b/src/api/meta.test.ts new file mode 100644 index 0000000..d4dc963 --- /dev/null +++ b/src/api/meta.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it, vi, beforeEach } from 'vitest'; +import { http } from './http'; +import { createEntity, listEntities, listEntityColumns } from './meta'; + +vi.mock('./http', () => ({ + http: { get: vi.fn(), post: vi.fn() }, +})); + +const mGet = vi.mocked(http.get); +const mPost = vi.mocked(http.post); + +beforeEach(() => { + mGet.mockReset(); + mPost.mockReset(); +}); + +describe('meta api', () => { + it('createEntity POST /api/meta/entity 并解包 data', async () => { + mPost.mockResolvedValue({ + data: { status: 0, data: { entityId: 'E1', tablename: 'OA_DEMO', attributeCount: 4, indexCount: 1, listApi: '/api/entity/OA_DEMO/list' } }, + } as never); + const r = await createEntity({ tablename: 'OA_DEMO', name: '演示', attributes: [{ column: 'TITLE', type: 'string', length: 200, mandatory: true }] }); + expect(mPost).toHaveBeenCalledWith('/api/meta/entity', { + tablename: 'OA_DEMO', + name: '演示', + attributes: [{ column: 'TITLE', type: 'string', length: 200, mandatory: true }], + }); + expect(r.entityId).toBe('E1'); + expect(r.listApi).toBe('/api/entity/OA_DEMO/list'); + }); + + it('listEntities GET /api/meta/entities 并解包数组', async () => { + mGet.mockResolvedValue({ data: { status: 0, data: [{ entityId: 'E1', tablename: 'OA_DEMO', name: '演示' }] } } as never); + const r = await listEntities(); + expect(mGet).toHaveBeenCalledWith('/api/meta/entities'); + expect(r).toHaveLength(1); + expect(r[0].tablename).toBe('OA_DEMO'); + }); + + it('listEntityColumns GET /api/meta/entity/{table}/attributes 并解包', async () => { + mGet.mockResolvedValue({ + data: { status: 0, data: { tablename: 'SYS_DEPART', displayColumn: 'DEPARTNAME', columns: [{ column: 'DEPARTNAME', display: '部门名', type: 'string' }] } }, + } as never); + const r = await listEntityColumns('SYS_DEPART'); + expect(mGet).toHaveBeenCalledWith('/api/meta/entity/SYS_DEPART/attributes'); + expect(r.displayColumn).toBe('DEPARTNAME'); + expect(r.columns[0].column).toBe('DEPARTNAME'); + }); +}); diff --git a/src/api/meta.ts b/src/api/meta.ts new file mode 100644 index 0000000..499863d --- /dev/null +++ b/src/api/meta.ts @@ -0,0 +1,72 @@ +// 元数据建模 API —— 实体目录 / 实体属性 / 建表。 +// 后端信封统一 {status:0,data:...},本模块解包返回内层 data(镜像 auth.ts 用法)。 +import { http } from './http'; + +export type AttrType = 'string' | 'integer' | 'number' | 'date' | 'datetime' | 'boolean' | 'reference'; + +export interface EntityAttr { + column: string; + type: AttrType; + length?: number; + display?: string; + mandatory?: boolean; + /** type==='reference' 时必填:外键目标表名(DECISION-1)。 */ + referenceTable?: string; +} + +export interface CreateEntityBody { + tablename: string; + name?: string; + attributes: EntityAttr[]; +} + +export interface CreateEntityResult { + entityId: string; + tablename: string; + attributeCount: number; + indexCount: number; + /** 引擎遗留返回 '/api/entity/
/list';recipe 页不消费它(recipe 列表走 /api/flow/
_SEARCH,见 §B.2/§B.9-11)。 */ + listApi: string; +} + +export interface EntitySummary { + entityId: string; + tablename: string; + name: string; +} + +export interface EntityColumn { + column: string; + display: string; + type: string; + referenceTable?: string; +} + +export interface EntityColumns { + tablename: string; + displayColumn: string; + columns: EntityColumn[]; +} + +interface Envelope { + status: number; + data: T; +} + +/** POST /api/meta/entity —— 建表(标准列由后端自动追加)。 */ +export async function createEntity(body: CreateEntityBody): Promise { + const resp = await http.post>('/api/meta/entity', body); + return resp.data.data; +} + +/** GET /api/meta/entities —— 实体目录(供引用列选择器)。 */ +export async function listEntities(): Promise { + const resp = await http.get>('/api/meta/entities'); + return resp.data.data; +} + +/** GET /api/meta/entity/{table}/attributes —— 某表的列定义(含 displayColumn)。 */ +export async function listEntityColumns(table: string): Promise { + const resp = await http.get>(`/api/meta/entity/${encodeURIComponent(table)}/attributes`); + return resp.data.data; +} diff --git a/src/api/publish.test.ts b/src/api/publish.test.ts new file mode 100644 index 0000000..e84b919 --- /dev/null +++ b/src/api/publish.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it, vi, beforeEach } from 'vitest'; +import { http } from './http'; +import { publishFeature } from './publish'; + +vi.mock('./http', () => ({ http: { get: vi.fn(), post: vi.fn() } })); +const mPost = vi.mocked(http.post); +beforeEach(() => { mPost.mockReset(); }); + +describe('publish api', () => { + it('publishFeature POST /api/design/publish 并解包', async () => { + mPost.mockResolvedValue({ data: { status: 0, data: { menuId: 'M1', flows: ['OA_DEMO_ADD'], deploymentPackage: { id: 'pkg-1' } } } } as never); + const r = await publishFeature({ entityId: 'E1', tableName: 'OA_DEMO', templateId: 'tpl-uuid', menuName: '演示', generateDeploymentPackage: true }); + expect(mPost).toHaveBeenCalledWith('/api/design/publish', { + entityId: 'E1', tableName: 'OA_DEMO', templateId: 'tpl-uuid', menuName: '演示', generateDeploymentPackage: true, + }); + expect(r.menuId).toBe('M1'); + expect(r.flows).toContain('OA_DEMO_ADD'); + }); +}); diff --git a/src/api/publish.ts b/src/api/publish.ts new file mode 100644 index 0000000..10813b4 --- /dev/null +++ b/src/api/publish.ts @@ -0,0 +1,26 @@ +// 发布 API —— 五环终点:触发 5 条默认流 + 注册菜单 + 可选生产部署包(DECISION-2)。 +// 发布恒人审:本端点只做「本环境即用 + 生产部署包生成」,生产上线仍走人工人审流程。 +import { http } from './http'; + +export interface PublishFeatureBody { + entityId: string; + tableName: string; + templateId: string; + menuName: string; + parentMenuId?: string; + generateDeploymentPackage?: boolean; +} + +export interface PublishFeatureResult { + menuId: string; + flows: string[]; + deploymentPackage?: unknown; +} + +interface Envelope { status: number; data: T; } + +/** POST /api/design/publish。 */ +export async function publishFeature(body: PublishFeatureBody): Promise { + const resp = await http.post>('/api/design/publish', body); + return resp.data.data; +} diff --git a/src/api/recipe.test.ts b/src/api/recipe.test.ts new file mode 100644 index 0000000..81029c0 --- /dev/null +++ b/src/api/recipe.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it, vi, beforeEach } from 'vitest'; +import { http } from './http'; +import { compileRecipe, listRecipes } from './recipe'; + +vi.mock('./http', () => ({ http: { get: vi.fn(), post: vi.fn() } })); +const mGet = vi.mocked(http.get); +const mPost = vi.mocked(http.post); +beforeEach(() => { mGet.mockReset(); mPost.mockReset(); }); + +describe('recipe api', () => { + it('compileRecipe POST /api/design/recipe/compile 并解包', async () => { + mPost.mockResolvedValue({ data: { status: 0, data: { templateId: 'tpl-uuid', etag: 'W/"1"' } } } as never); + const r = await compileRecipe({ tableName: 'OA_DEMO', recipe: 'maintenance-crud-v1', title: '演示维护', displayField: 'TITLE' }); + expect(mPost).toHaveBeenCalledWith('/api/design/recipe/compile', { + tableName: 'OA_DEMO', recipe: 'maintenance-crud-v1', title: '演示维护', displayField: 'TITLE', + }); + expect(r.templateId).toBe('tpl-uuid'); + expect(r.etag).toBe('W/"1"'); + }); + + // §B.9-2:listRecipes 改静态常量(非 async、不调 /api/ai/page-recipes)。 + it('listRecipes 返回 v1 固定两 recipe(静态 {id,label})', () => { + const r = listRecipes(); + expect(r).toEqual([ + { id: 'maintenance-crud-v1', label: '维护型 CRUD' }, + { id: 'tree-crud-v1', label: '树形 CRUD' }, + ]); + // 不触网:listRecipes 是同步数组,不调 http.get + expect(mGet).not.toHaveBeenCalled(); + }); +}); diff --git a/src/api/recipe.ts b/src/api/recipe.ts new file mode 100644 index 0000000..481dbce --- /dev/null +++ b/src/api/recipe.ts @@ -0,0 +1,40 @@ +// recipe 编译 API —— 把实体 + recipe 编译为标准页(templateId 由服务端生成)。 +import { http } from './http'; + +export type RecipeId = 'maintenance-crud-v1' | 'tree-crud-v1'; + +export interface CompileRecipeBody { + tableName: string; + recipe: RecipeId; + title: string; + displayField?: string; + pageSize?: number; +} + +export interface CompileRecipeResult { + templateId: string; + etag: string; +} + +export interface RecipeOption { + id: string; + label: string; +} + +interface Envelope { status: number; data: T; } + +/** POST /api/design/recipe/compile —— 服务端建蓝图→编译→校验→PageSchemaWriter.upsertStandard。 */ +export async function compileRecipe(body: CompileRecipeBody): Promise { + const resp = await http.post>('/api/design/recipe/compile', body); + return resp.data.data; +} + +// §B.9-2:v1 固定两 recipe(YAGNI),无需调 /api/ai/page-recipes +// (其裸数组 {recipe,schemaVersion,title,...} 形状与本前端 {id,label} 契约不符)。 +// recipe id 全程统一 *-v1 形(normalizePageRecipe 只接受 *-v1,见 §B.8/§B.9-1)。 +export function listRecipes(): RecipeOption[] { + return [ + { id: 'maintenance-crud-v1', label: '维护型 CRUD' }, + { id: 'tree-crud-v1', label: '树形 CRUD' }, + ]; +} diff --git a/src/editor/main.tsx b/src/editor/main.tsx index 497c99f..c767cda 100644 --- a/src/editor/main.tsx +++ b/src/editor/main.tsx @@ -1,14 +1,25 @@ // F4-L1 设计器独立入口(editor.html 多页应用) // 与主应用 React 实例完全隔离,amis 用 npm 包版,不依赖 sdk-local -import React from 'react'; +// +// ⚠️ 不能包 :amis-editor 用 mobx-state-tree 维护 EditorRoot store, +// StrictMode 在 dev 下故意 mount→unmount→remount,会销毁第一个 EditorRoot,而其 pending +// 异步(markReady / calculateHighlightBox)随后打到已死实例 → 抛 +// 「[mobx-state-tree] object no longer part of a state tree」→ 编辑器整片空白。 +// 主应用 main.tsx 跑 amis SDK(运行时渲染器,容忍 StrictMode),唯独 amis-editor 不行。 +// +// CSS 由此处 import 引入(不再用 editor.html 的 /node_modules 绝对 link): +// vite dev 直接转译、vite build 由 rollup 收集进 dist 的 css 产物, +// 修掉「dist/editor.html 三条 /node_modules link 在 preview/静态托管下 404」。 +// 注:amis-ui/amis-editor-core 的 package.json exports 字段不暴露这些 css 子路径, +// 用裸包名 import 会被 rollup 拒绝解析(同 vite.config 注释里 amis 栈无 exports 之坑), +// 故以相对 node_modules 路径直引这三个真实 css 文件,绕开包解析。 +import '../../node_modules/amis-editor-core/lib/style.css'; +import '../../node_modules/amis-ui/lib/themes/default.css'; +import '../../node_modules/amis-ui/lib/helper.css'; import { createRoot } from 'react-dom/client'; import { DesignerPage } from './DesignerPage'; const root = document.getElementById('editor-root'); if (root) { - createRoot(root).render( - - - , - ); + createRoot(root).render(); } diff --git a/src/pages/AiFeatureForm.test.tsx b/src/pages/AiFeatureForm.test.tsx new file mode 100644 index 0000000..7df7f8a --- /dev/null +++ b/src/pages/AiFeatureForm.test.tsx @@ -0,0 +1,37 @@ +import '@testing-library/jest-dom'; +import { render, screen } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { vi, describe, it, expect } from 'vitest'; + +// AiFeatureForm 现以 amis form 渲染()。amis 内部(auto-develop 提交、ARRAYFILTER 取 +// 草稿 targetId、审阅按钮)由 Playwright e2e 覆盖;单测仅守 admin 守卫 + 容器/amis 挂载点。 +let mockProfile: { userId: string; account: string; name: string; roles: string[] } | null = null; +vi.mock('../auth/token', () => ({ getProfile: () => mockProfile })); +vi.mock('../components/AmisRenderer', () => ({ AmisRenderer: () =>
})); + +import { AiFeatureForm } from './AiFeatureForm'; + +function renderForm() { + return render( + + + , + ); +} + +describe('AiFeatureForm(amis form)', () => { + it('非管理员:降级提示', () => { + mockProfile = { userId: 'U1', account: 'user', name: 'u', roles: [] }; + renderForm(); + expect(screen.getByText(/仅管理员可用/)).toBeInTheDocument(); + expect(screen.queryByTestId('ai-feature-form')).toBeNull(); + }); + + it('管理员:渲染容器 + 标题 + amis 挂载点', () => { + mockProfile = { userId: 'ADMIN', account: 'admin', name: 'x', roles: [] }; + renderForm(); + expect(screen.getByTestId('ai-feature-form')).toBeInTheDocument(); + expect(screen.getByText('⚡ AI 建功能')).toBeInTheDocument(); + expect(screen.getByTestId('amis-mount')).toBeInTheDocument(); + }); +}); diff --git a/src/pages/AiFeatureForm.tsx b/src/pages/AiFeatureForm.tsx new file mode 100644 index 0000000..e40d6e9 --- /dev/null +++ b/src/pages/AiFeatureForm.tsx @@ -0,0 +1,114 @@ +// AI ①面加速器入口 —— amis form 渲染(与全站一致)。填需求 → 外部 agent 起草, +// 产物恒 READY_FOR_HUMAN_REVIEW,人点「审阅草稿」进 editor.html(edit-only)。 +// 红线:永不自动发布;平台进程内不内置生成 LLM。 +// 注意:/api/ai/features/auto-develop 直接返回 run 对象(status 为字符串,非 amis 的 {status:0}), +// 故 api 用 adaptor 包成 {status:0,data:payload},再以 ARRAYFILTER 取 PAGE_SCHEMA 草稿 targetId。 +import { useMemo } from 'react'; +import { useNavigate } from 'react-router-dom'; +import { getProfile } from '../auth/token'; +import { AmisRenderer } from '../components/AmisRenderer'; + +const TYPE_OPTIONS = [ + { label: '文本', value: 'string' }, + { label: '整数', value: 'integer' }, + { label: '小数', value: 'number' }, + { label: '日期', value: 'date' }, + { label: '日期时间', value: 'datetime' }, + { label: '布尔', value: 'boolean' }, +]; + +function buildSchema(): Record { + // 进设计器用的 templateId = development.drafts 里 artifactType==PAGE_SCHEMA 的 targetId + const reviewTpl = '${ARRAYFILTER(development.drafts, item.artifactType === "PAGE_SCHEMA")[0].targetId}'; + return { + type: 'page', + body: { + type: 'form', + title: '', + mode: 'horizontal', + actions: [{ type: 'submit', label: '开始 AI 起草', level: 'primary' }], + // baseUrl=当前源(dev 经 vite 代理到后端);恒人审,故只产草稿 + api: { + method: 'post', + url: '/api/ai/features/auto-develop', + data: { + feature: { + objective: '${objective}', featureName: '${featureName}', tableName: '${tableName}', + entityName: '${entityName}', pageRecipe: '${pageRecipe}', fields: '${fields}', + }, + baseUrl: window.location.origin, + generateDeploymentPackage: true, + }, + // auto-develop 返回裸 run 对象 → 包成 amis 信封,使 ${status}/${development}/${taskId} 进数据域 + adaptor: 'return { status: 0, msg: "", data: payload };', + }, + messages: { saveSuccess: 'AI 起草完成,请看下方状态' }, + body: [ + { type: 'textarea', name: 'objective', label: '需求目标', required: true, minRows: 2, placeholder: '如:新增客户等级维护功能' }, + { type: 'input-text', name: 'featureName', label: '功能名', required: true, placeholder: '客户等级维护' }, + { + type: 'input-text', name: 'tableName', label: '表名', required: true, placeholder: 'EIP4AI_CUSTOMER_LEVEL', + validations: { matchRegexp: '/^[A-Z][A-Z0-9_]{2,40}$/' }, + validationErrors: { matchRegexp: '大写字母开头,3–41 位' }, + }, + { type: 'input-text', name: 'entityName', label: '实体名', required: true, placeholder: '客户等级' }, + { + type: 'radios', name: 'pageRecipe', label: '页面模板', value: 'maintenance-crud-v1', + options: [ + { label: '维护型 CRUD', value: 'maintenance-crud-v1' }, + { label: '树形 CRUD', value: 'tree-crud-v1' }, + ], + }, + { + type: 'combo', name: 'fields', label: '字段', multiple: true, addable: true, removable: true, + addButtonText: '加字段', minLength: 1, + items: [ + { type: 'input-text', name: 'column', label: '列名', required: true, placeholder: 'NAME' }, + { type: 'input-text', name: 'label', label: '显示名', placeholder: '名称' }, + { type: 'select', name: 'type', label: '类型', value: 'string', options: TYPE_OPTIONS }, + { type: 'switch', name: 'required', label: '必填' }, + ], + }, + { + type: 'alert', level: 'info', visibleOn: '${status}', + body: 'AI 起草状态:${status}(taskId=${taskId})。产物恒人审,平台不自动发布。', + }, + { + type: 'button', label: '审阅草稿(进设计器)', level: 'primary', className: 'mt-2', + visibleOn: '${status === "READY_FOR_HUMAN_REVIEW"}', + actionType: 'url', url: '/editor.html?templateId=' + reviewTpl, blank: true, + }, + { + type: 'alert', level: 'warning', visibleOn: '${status && status !== "READY_FOR_HUMAN_REVIEW"}', + body: '未达人审就绪状态(${status})。运行信息:${JOIN(messages, ";")}', + }, + ], + }, + }; +} + +export function AiFeatureForm() { + const navigate = useNavigate(); + const profile = getProfile(); + const isAdmin = profile?.account === 'admin' || profile?.userId === 'ADMIN'; + const schema = useMemo(buildSchema, []); + + if (!isAdmin) { + return
AI 建功能仅管理员可用。
; + } + + return ( +
+
+ +

⚡ AI 建功能

+
+
+ 外部 AI agent 起草,产物恒人审;点「审阅草稿」进设计器,平台不自动发布。 +
+
+ +
+
+ ); +} diff --git a/src/pages/DesignCenterPage.entrances.test.tsx b/src/pages/DesignCenterPage.entrances.test.tsx new file mode 100644 index 0000000..5507c84 --- /dev/null +++ b/src/pages/DesignCenterPage.entrances.test.tsx @@ -0,0 +1,47 @@ +import '@testing-library/jest-dom'; +import { render, screen, waitFor } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { vi, describe, it, expect, beforeEach } from 'vitest'; +import { DesignCenterPage } from './DesignCenterPage'; + +// menu 走真实 http → mock 掉,避免网络 +vi.mock('../api/menu', () => ({ + fetchMenu: vi.fn().mockResolvedValue({ roots: [] }), + collectLeaves: vi.fn().mockReturnValue([]), +})); + +// 受控 profile:默认 admin +const profileMock = vi.fn(); +vi.mock('../auth/token', () => ({ + getProfile: () => profileMock(), +})); + +function renderPage() { + return render( + + + , + ); +} + +describe('DesignCenterPage 入口按钮', () => { + beforeEach(() => { + profileMock.mockReset(); + }); + + it('admin 看到 [+ 新建功能] 与 [⚡ AI 建功能]', async () => { + profileMock.mockReturnValue({ userId: 'ADMIN', account: 'admin', name: 'x', roles: [] }); + renderPage(); + await waitFor(() => { + expect(screen.getByTestId('dc-new-feature')).toBeInTheDocument(); + expect(screen.getByTestId('dc-ai-feature')).toBeInTheDocument(); + }); + }); + + it('非 admin 不渲染入口(整页降级)', () => { + profileMock.mockReturnValue({ userId: 'U1', account: 'zhangsan', name: 'z', roles: [] }); + renderPage(); + expect(screen.queryByTestId('dc-new-feature')).not.toBeInTheDocument(); + expect(screen.queryByTestId('dc-ai-feature')).not.toBeInTheDocument(); + }); +}); diff --git a/src/pages/DesignCenterPage.tsx b/src/pages/DesignCenterPage.tsx index dee7b62..9385043 100644 --- a/src/pages/DesignCenterPage.tsx +++ b/src/pages/DesignCenterPage.tsx @@ -2,6 +2,7 @@ // 列出全部功能页(按菜单分组、可搜索),每页一个「设计」入口打开 editor.html。 // 仅管理员可见(路由在 AppShell 下,入口在 Topbar admin-only 按钮)。 import { useEffect, useMemo, useState } from 'react'; +import { useNavigate } from 'react-router-dom'; import { fetchMenu, collectLeaves, type MenuLeaf } from '../api/menu'; import { getProfile } from '../auth/token'; @@ -19,6 +20,7 @@ export function DesignCenterPage() { const [error, setError] = useState(''); const [loading, setLoading] = useState(true); const [q, setQ] = useState(''); + const navigate = useNavigate(); const profile = getProfile(); const isAdmin = profile?.account === 'admin' || profile?.userId === 'ADMIN'; @@ -71,6 +73,22 @@ export function DesignCenterPage() {
+ +
({ listEntities: vi.fn(), listEntityColumns: vi.fn() })); + +describe('buildAttribute 映射', () => { + it('文本→string,带 length/display/mandatory', () => { + const r: FieldRow = { column: 'TITLE', display: '标题', type: '文本', length: 200, mandatory: true }; + expect(buildAttribute(r)).toEqual({ column: 'TITLE', type: 'string', length: 200, display: '标题', mandatory: true }); + }); + it('整数→integer,无 length', () => { + const r: FieldRow = { column: 'QTY', display: '数量', type: '整数' }; + expect(buildAttribute(r)).toEqual({ column: 'QTY', type: 'integer', display: '数量' }); + }); + it('小数→number / 日期→date / 日期时间→datetime / 布尔→boolean', () => { + expect(buildAttribute({ column: 'A', display: 'a', type: '小数' }).type).toBe('number'); + expect(buildAttribute({ column: 'B', display: 'b', type: '日期' }).type).toBe('date'); + expect(buildAttribute({ column: 'C', display: 'c', type: '日期时间' }).type).toBe('datetime'); + expect(buildAttribute({ column: 'D', display: 'd', type: '布尔' }).type).toBe('boolean'); + }); + it('引用→reference,带 referenceTable', () => { + const r: FieldRow = { column: 'DEPARTID', display: '部门', type: '引用', referenceTable: 'SYS_DEPART' }; + expect(buildAttribute(r)).toEqual({ column: 'DEPARTID', type: 'reference', display: '部门', referenceTable: 'SYS_DEPART' }); + }); + it('mandatory=false 不输出该键', () => { + const r: FieldRow = { column: 'X', display: 'x', type: '文本', length: 50, mandatory: false }; + expect('mandatory' in buildAttribute(r)).toBe(false); + }); +}); + +function Harness() { + const [rows, setRows] = useState([]); + return ( +
+ +
{rows.length}
+
+ ); +} + +describe('FieldTable 交互', () => { + beforeEach(() => { /* no-op */ }); + + it('加字段:填列名/显示名/选类型→提交→出现在表里', () => { + render(); + fireEvent.click(screen.getByTestId('field-add')); + fireEvent.change(screen.getByTestId('field-column'), { target: { value: 'TITLE' } }); + fireEvent.change(screen.getByTestId('field-display'), { target: { value: '标题' } }); + fireEvent.change(screen.getByTestId('field-type'), { target: { value: '文本' } }); + fireEvent.change(screen.getByTestId('field-length'), { target: { value: '200' } }); + fireEvent.click(screen.getByTestId('field-submit')); + expect(screen.getByText('TITLE')).toBeInTheDocument(); + expect(screen.getByTestId('count').textContent).toBe('1'); + }); + + it('文本类型显示 length 输入,整数类型隐藏', () => { + render(); + fireEvent.click(screen.getByTestId('field-add')); + fireEvent.change(screen.getByTestId('field-type'), { target: { value: '文本' } }); + expect(screen.getByTestId('field-length')).toBeInTheDocument(); + fireEvent.change(screen.getByTestId('field-type'), { target: { value: '整数' } }); + expect(screen.queryByTestId('field-length')).not.toBeInTheDocument(); + }); +}); diff --git a/src/pages/ModelerFields.tsx b/src/pages/ModelerFields.tsx new file mode 100644 index 0000000..3d87118 --- /dev/null +++ b/src/pages/ModelerFields.tsx @@ -0,0 +1,166 @@ +// 字段表 + 加字段 Dialog + UI 类型↔api 类型映射。 +// 纯 HTML
(本仓无可复用表格组件)+ components/ui/Dialog。 +import { useState } from 'react'; +import type { Dispatch, SetStateAction } from 'react'; +import { Dialog } from '../components/ui/Dialog'; +import type { EntityAttr, AttrType } from '../api/meta'; +import { ReferencePicker } from './ReferencePicker'; + +export type UiType = '文本' | '整数' | '小数' | '日期' | '日期时间' | '布尔' | '引用'; + +export interface FieldRow { + column: string; + display: string; + type: UiType; + length?: number; + mandatory?: boolean; + referenceTable?: string; +} + +const UI_TYPES: UiType[] = ['文本', '整数', '小数', '日期', '日期时间', '布尔', '引用']; + +const TYPE_MAP: Record = { + 文本: 'string', + 整数: 'integer', + 小数: 'number', + 日期: 'date', + 日期时间: 'datetime', + 布尔: 'boolean', + 引用: 'reference', +}; + +/** UI 行 → api EntityAttr。length 仅文本有意义;mandatory=false 不输出;引用带 referenceTable。 */ +export function buildAttribute(row: FieldRow): EntityAttr { + const attr: EntityAttr = { column: row.column, type: TYPE_MAP[row.type] }; + if (row.display) attr.display = row.display; + if (row.type === '文本' && typeof row.length === 'number') attr.length = row.length; + if (row.mandatory) attr.mandatory = true; + if (row.type === '引用' && row.referenceTable) attr.referenceTable = row.referenceTable; + return attr; +} + +interface FieldTableProps { + rows: FieldRow[]; + onChange: Dispatch>; +} + +export function FieldTable({ rows, onChange }: FieldTableProps) { + const [adding, setAdding] = useState(false); + // 加字段草稿 + const [column, setColumn] = useState(''); + const [display, setDisplay] = useState(''); + const [type, setType] = useState('文本'); + const [length, setLength] = useState('200'); + const [mandatory, setMandatory] = useState(false); + const [refTable, setRefTable] = useState(''); + + function openAdd() { + setColumn(''); + setDisplay(''); + setType('文本'); + setLength('200'); + setMandatory(false); + setRefTable(''); + setAdding(true); + } + + const columnValid = /^[A-Z][A-Z0-9_]{0,40}$/.test(column); + const refOk = type !== '引用' || !!refTable; + const canAdd = columnValid && !!display && refOk; + + function submitField() { + const row: FieldRow = { column, display, type }; + if (type === '文本') row.length = Number(length) || undefined; + if (mandatory) row.mandatory = true; + if (type === '引用') row.referenceTable = refTable; + onChange((prev) => [...prev, row]); + setAdding(false); + } + + function removeRow(i: number) { + onChange((prev) => prev.filter((_, idx) => idx !== i)); + } + + return ( +
+
+ 字段(标准列由后端自动追加,无需在此添加 ID/创建人等) + +
+
+ + + + + + + + + + {rows.length === 0 ? ( + + ) : ( + rows.map((r, i) => ( + + + + + + + + )) + )} + +
列名显示名类型必填 +
尚无字段
{r.column}{r.display} + {r.type}{r.type === '引用' && r.referenceTable ? `→${r.referenceTable}` : ''} + {r.mandatory ? '是' : ''} + removeRow(i)}>删除 +
+ + {adding ? ( + setAdding(false)} + foot={ + <> + + + + } + > +
+ + + + {type === '文本' ? ( + + ) : null} + {type === '引用' ? ( + + ) : null} + +
+
+ ) : null} + + ); +} diff --git a/src/pages/ModelerPage.test.tsx b/src/pages/ModelerPage.test.tsx new file mode 100644 index 0000000..3e04087 --- /dev/null +++ b/src/pages/ModelerPage.test.tsx @@ -0,0 +1,61 @@ +import { describe, expect, it, vi, beforeEach } from 'vitest'; +import { render, screen, fireEvent, waitFor } from '@testing-library/react'; +import { ModelerPage, validateTableName } from './ModelerPage'; + +vi.mock('../api/meta', () => ({ + listEntities: vi.fn(), + listEntityColumns: vi.fn(), + createEntity: vi.fn(), +})); +vi.mock('../auth/token', () => ({ getProfile: vi.fn() })); + +import { listEntities, createEntity } from '../api/meta'; +import { getProfile } from '../auth/token'; + +const mList = vi.mocked(listEntities); +const mCreate = vi.mocked(createEntity); +const mProfile = vi.mocked(getProfile); + +beforeEach(() => { + mList.mockReset(); + mCreate.mockReset(); + mProfile.mockReset(); + mProfile.mockReturnValue({ userId: 'ADMIN', account: 'admin', name: '管理员', roles: [] }); + mList.mockResolvedValue([{ entityId: 'E1', tablename: 'OA_DEMO', name: '演示' }]); +}); + +describe('validateTableName', () => { + it('合法表名通过', () => { + expect(validateTableName('OA_DEMO')).toBe(true); + expect(validateTableName('ABC')).toBe(true); + }); + it('非法表名拒绝', () => { + expect(validateTableName('ab')).toBe(false); // 太短 + 小写 + expect(validateTableName('1ABC')).toBe(false); // 数字开头 + expect(validateTableName('OA-DEMO')).toBe(false); // 含非法字符 + }); +}); + +describe('ModelerPage', () => { + it('非管理员显示无权访问', () => { + mProfile.mockReturnValue({ userId: 'U9', account: 'zhang', name: '张三', roles: [] }); + render(); + expect(screen.getByText(/仅管理员可用/)).toBeInTheDocument(); + }); + + it('管理员加载并展示已有实体', async () => { + render(); + await waitFor(() => expect(screen.getByText('OA_DEMO')).toBeInTheDocument()); + expect(mList).toHaveBeenCalled(); + }); + + it('点新建实体打开 Dialog,非法表名禁用提交', async () => { + render(); + fireEvent.click(screen.getByTestId('modeler-new-entity')); + expect(screen.getByTestId('modeler-tablename')).toBeInTheDocument(); + fireEvent.change(screen.getByTestId('modeler-tablename'), { target: { value: 'ab' } }); + expect(screen.getByTestId('modeler-submit')).toBeDisabled(); + fireEvent.change(screen.getByTestId('modeler-tablename'), { target: { value: 'OA_NEW' } }); + expect(screen.getByTestId('modeler-submit')).not.toBeDisabled(); + }); +}); diff --git a/src/pages/ModelerPage.tsx b/src/pages/ModelerPage.tsx new file mode 100644 index 0000000..df00732 --- /dev/null +++ b/src/pages/ModelerPage.tsx @@ -0,0 +1,165 @@ +// 建模器 —— NocoBase 式实体建模入口(五环第①环:元数据→表)。 +// 仅管理员可用。展示已有实体清单 + 「新建实体」Dialog(表名/显示名/字段表)。 +// v1 只建新不改表(DECISION:no ALTER)。字段表与引用列选择器见同文件下方组件。 +import { useEffect, useState } from 'react'; +import { Dialog } from '../components/ui/Dialog'; +import { getProfile } from '../auth/token'; +import { + listEntities, + createEntity, + type EntitySummary, + type EntityAttr, +} from '../api/meta'; +import { FieldTable, buildAttribute, type FieldRow } from './ModelerFields'; + +export function validateTableName(t: string): boolean { + return /^[A-Z][A-Z0-9_]{2,40}$/.test(t); +} + +export function ModelerPage() { + const profile = getProfile(); + const isAdmin = profile?.account === 'admin' || profile?.userId === 'ADMIN'; + + const [entities, setEntities] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(''); + const [open, setOpen] = useState(false); + + // 新建表单态 + const [tablename, setTablename] = useState(''); + const [name, setName] = useState(''); + const [rows, setRows] = useState([]); + const [submitting, setSubmitting] = useState(false); + const [submitErr, setSubmitErr] = useState(''); + + function reload() { + setLoading(true); + listEntities() + .then((es) => setEntities(es)) + .catch((e: Error) => setError(e.message ?? '实体加载失败')) + .finally(() => setLoading(false)); + } + + useEffect(() => { + if (!isAdmin) return; + reload(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [isAdmin]); + + if (!isAdmin) { + return
建模器仅管理员可用。
; + } + + const tableValid = validateTableName(tablename); + // 引用行必须选了目标表才合法(Task 17 填充 referenceTable) + const rowsValid = rows.every((r) => r.type !== '引用' || !!r.referenceTable); + const canSubmit = tableValid && rowsValid && !submitting; + + function openDialog() { + setTablename(''); + setName(''); + setRows([]); + setSubmitErr(''); + setOpen(true); + } + + async function submit() { + setSubmitting(true); + setSubmitErr(''); + try { + const attributes: EntityAttr[] = rows.map(buildAttribute); + await createEntity({ tablename, name: name || undefined, attributes }); + setOpen(false); + reload(); + } catch (e) { + setSubmitErr((e as Error).message ?? '建表失败'); + } finally { + setSubmitting(false); + } + } + + return ( +
+
+
+

建模器

+
+ 新建实体(建表)。v1 只建新不改表 · 标准列由后端自动追加 +
+
+
+ +
+ + {loading ? ( +
加载中…
+ ) : error ? ( +
实体加载失败:{error}
+ ) : entities.length === 0 ? ( +
尚无实体,点「新建实体」开始
+ ) : ( +
+ + + + + + + + + + {entities.map((e) => ( + + + + + + ))} + +
表名显示名实体ID
{e.tablename}{e.name}{e.entityId}
+
+ )} + + {open ? ( + setOpen(false)} + foot={ + <> + + + + } + > +
+ + + + + + {submitErr ?
{submitErr}
: null} +
+
+ ) : null} +
+ ); +} diff --git a/src/pages/NewFeatureShell.test.tsx b/src/pages/NewFeatureShell.test.tsx new file mode 100644 index 0000000..55e7108 --- /dev/null +++ b/src/pages/NewFeatureShell.test.tsx @@ -0,0 +1,53 @@ +import '@testing-library/jest-dom'; +import { render, screen, fireEvent } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { vi, describe, it, expect } from 'vitest'; + +// NewFeatureShell 现以「先选页面类型卡 → 进 amis wizard」两段渲染(c735f24 合并入口)。amis SDK(amisRequire) +// 是 index.html 注入的全局 UMD,jsdom 下不存在 → wizard 内部不在单测渲染;其端到端行为由 Playwright +// (e2e/five-ring.spec、master-detail.spec) 覆盖。单测仅守:① admin 守卫;② admin 下先渲染页面类型选择卡; +// ③ 选一种类型后渲染 amis 挂载点(wizard 壳)。 +let mockProfile: { userId: string; account: string; name: string; roles: string[] } | null = null; +vi.mock('../auth/token', () => ({ getProfile: () => mockProfile })); +vi.mock('../components/AmisRenderer', () => ({ AmisRenderer: () =>
})); + +import { NewFeatureShell } from './NewFeatureShell'; + +function renderShell() { + return render( + + + , + ); +} + +describe('NewFeatureShell(amis wizard 壳)', () => { + it('非管理员:降级提示,不渲染壳', () => { + mockProfile = { userId: 'U1', account: 'user', name: 'u', roles: [] }; + renderShell(); + expect(screen.getByText(/仅管理员可用/)).toBeInTheDocument(); + expect(screen.queryByTestId('new-feature-shell')).toBeNull(); + }); + + it('管理员:先渲染壳容器 + 返回设计中心 + 页面类型选择卡(含主子表)', () => { + mockProfile = { userId: 'ADMIN', account: 'admin', name: 'x', roles: [] }; + renderShell(); + expect(screen.getByTestId('new-feature-shell')).toBeInTheDocument(); + expect(screen.getByText('新建功能 · 人走五环')).toBeInTheDocument(); + expect(screen.getByText('← 返回设计中心')).toBeInTheDocument(); + // 先出页面类型选择卡(未选类型时不渲 wizard)。 + expect(screen.getByTestId('recipe-chooser')).toBeInTheDocument(); + expect(screen.getByTestId('dc-recipe-maintenance')).toBeInTheDocument(); + expect(screen.getByTestId('dc-recipe-master-detail')).toBeInTheDocument(); + expect(screen.queryByTestId('amis-mount')).toBeNull(); + }); + + it('管理员:选页面类型后渲染 amis wizard 挂载点', () => { + mockProfile = { userId: 'ADMIN', account: 'admin', name: 'x', roles: [] }; + renderShell(); + fireEvent.click(screen.getByTestId('dc-recipe-master-detail')); + expect(screen.getByTestId('amis-mount')).toBeInTheDocument(); + // 选类型后头部按钮变为「重选页面类型」。 + expect(screen.getByText('← 重选页面类型')).toBeInTheDocument(); + }); +}); diff --git a/src/pages/NewFeatureShell.tsx b/src/pages/NewFeatureShell.tsx new file mode 100644 index 0000000..94e46e0 --- /dev/null +++ b/src/pages/NewFeatureShell.tsx @@ -0,0 +1,310 @@ +// 人走五环 · 统一「新建功能」入口。先选页面类型(维护型CRUD / 树形 / 主子表),再进对应向导。 +// 关键:页面类型在进向导前由 React 状态确定,向导步骤按类型在【构建时(JS)】分支(主子表才有「建子表」步 +// 及派生/汇总字段)——不依赖 amis 运行时 step hiddenOn(amis Wizard.normalizeSteps 只在 props.data 变时 +// 重算,向导内选择改的是 store.data 不触发重算,故 step 级动态跳步不可靠;构建时分支才健壮)。 +// 各类型向导:① 建实体(post /api/meta/entity) →【主子表】② 建子表 → ③ 生成页面(post /api/design/recipe/compile) +// → ④ 发布(post /api/design/publish)。主实体 id/表名经 responseData remap 到 masterEntityId/masterTable。 +// 红线:发布恒人审;standard 写入恒走后端 PageSchemaWriter(前端只调 /api/design/recipe/compile)。 +import { useMemo, useState } from 'react'; +import { useNavigate } from 'react-router-dom'; +import { getProfile } from '../auth/token'; +import { AmisRenderer } from '../components/AmisRenderer'; + +const TYPE_OPTIONS = [ + { label: '文本', value: 'string' }, + { label: '整数', value: 'integer' }, + { label: '小数', value: 'number' }, + { label: '日期', value: 'date' }, + { label: '日期时间', value: 'datetime' }, + { label: '布尔', value: 'boolean' }, + { label: '引用(外键)', value: 'reference' }, +]; + +const RECIPE_CARDS = [ + { recipe: 'maintenance-crud-v1', testid: 'dc-recipe-maintenance', title: '维护型 CRUD', + desc: '单表:列表 + 查询 + 增删改。最常见的基础数据/业务维护页。' }, + { recipe: 'tree-crud-v1', testid: 'dc-recipe-tree', title: '树形 CRUD', + desc: '自引用层级(需含 PARENTID 列)。组织/分类/菜单等树状数据。' }, + { recipe: 'master-detail-v1', testid: 'dc-recipe-master-detail', title: '主子表', + desc: '主表 + 子表 EditGrid,子行随主记录级联保存。支持派生字段(金额=数量×单价)与父级汇总(总额=之和)。' }, +]; + +/** 字段 combo(含引用列:type=引用 → 选 referenceTable,源 /api/meta/entities)。 */ +function attrCombo(name: string, addButtonText: string): Record { + return { + type: 'combo', name, label: '字段', multiple: true, addable: true, removable: true, + addButtonText, minLength: 1, + items: [ + { + type: 'input-text', name: 'column', label: '列名', required: true, placeholder: 'TITLE', + columnClassName: 'w-sm', validations: { matchRegexp: '/^[A-Z][A-Z0-9_]{0,40}$/' }, + validationErrors: { matchRegexp: '大写字母开头' }, + }, + { type: 'input-text', name: 'display', label: '显示名', placeholder: '标题' }, + { type: 'select', name: 'type', label: '类型', value: 'string', options: TYPE_OPTIONS, columnClassName: 'w-xs' }, + { + type: 'select', name: 'referenceTable', label: '引用目标实体', + source: 'get:/api/meta/entities', labelField: 'tablename', valueField: 'tablename', + searchable: true, visibleOn: '${type === "reference"}', + description: '渲染时显该实体的显示列而非裸 id', + }, + { type: 'switch', name: 'mandatory', label: '必填', value: false }, + ], + }; +} + +/** 按页面类型构建向导 amis schema(类型已由 React 状态固定,步骤构建时 JS 分支)。 */ +function buildWizardSchema(recipe: string): Record { + const isMD = recipe === 'master-detail-v1'; + const isTree = recipe === 'tree-crud-v1'; + + const steps: Record[] = []; + + // ① 建实体(主子表则为主实体) + steps.push({ + title: '① 建实体', + subTitle: isMD ? '主表元数据' : '元数据 + 物理表', + hint: isTree + ? '树形请在字段里加 PARENTID 列(自引用父节点);标准列后端自动补。' + : '标准列(主键/审计/版本)后端自动补齐,无需在此添加。', + api: { method: 'post', url: '/api/meta/entity', responseData: { masterEntityId: '${entityId}', masterTable: '${tablename}' } }, + body: [ + { + type: 'input-text', name: 'tablename', label: isMD ? '主表名' : '表名', required: true, placeholder: 'OA_DEMO', + description: '大写字母开头,仅大写字母/数字/下划线,3–41 位', + validations: { matchRegexp: '/^[A-Z][A-Z0-9_]{2,40}$/' }, + validationErrors: { matchRegexp: '表名格式不合法(大写字母开头,3–41 位)' }, + }, + { type: 'input-text', name: 'name', label: '显示名', placeholder: '演示(可选)' }, + { + type: 'select', name: 'entitytype', label: '所属分类', required: true, + source: 'get:/api/meta/entity-types', labelField: 'name', valueField: 'id', + searchable: true, clearable: true, + description: isMD ? '主表与子表共用此分类' : '实体归类(SYS_ENTITYTYPE),决定新功能挂在哪个功能域', + }, + attrCombo('attributes', '加字段'), + ], + }); + + // ② 建子表(仅主子表) + if (isMD) { + steps.push({ + title: '② 建子表', + subTitle: '明细', + hint: '子表自动加一列 MASTERID 指向主表(回链外键),无需手动添加。', + api: { + method: 'post', url: '/api/meta/entity', + data: { + tablename: '${childTablename}', name: '${childName}', entitytype: '${entitytype}', + tabletype: 1, masterTable: '${masterTable}', attributes: '${childAttributes}', + }, + }, + body: [ + { type: 'static', name: 'masterTable', label: '主表' }, + { + type: 'input-text', name: 'childTablename', label: '子表名', required: true, placeholder: 'OA_PURCHASE_ITEM', + validations: { matchRegexp: '/^[A-Z][A-Z0-9_]{2,40}$/' }, validationErrors: { matchRegexp: '表名格式不合法' }, + }, + { type: 'input-text', name: 'childName', label: '子表显示名', placeholder: '采购明细' }, + attrCombo('childAttributes', '加子表字段'), + ], + }); + } + + // ③ 生成页面(主子表多派生/汇总字段) + const genBody: Record[] = [ + { type: 'static', name: 'masterTable', label: isMD ? '主表' : '实体表' }, + ]; + if (isMD) { + genBody.push({ type: 'static', label: '子表', tpl: '${childTablename}' }); + } + genBody.push( + { type: 'input-text', name: 'title', label: '页面标题', required: true, placeholder: '如:客户等级维护' }, + { type: 'input-text', name: 'displayField', label: '显示字段', placeholder: '可选,默认取实体显示列' }, + ); + if (!isMD) { + genBody.push({ type: 'input-number', name: 'pageSize', label: '每页条数', placeholder: '可选,默认 20', min: 1, max: 200 }); + } + if (isMD) { + genBody.push( + { + type: 'static', label: '可用子表列', tpl: '${childAttributes|pick:column|join:"、"}', + visibleOn: '${childAttributes && childAttributes.length}', + }, + { + type: 'combo', name: 'childDerived', label: '派生字段', multiple: true, + addable: true, removable: true, addButtonText: '加派生字段', minLength: 0, + description: '可选。如 金额=数量×单价:目标列填 MONEY、公式填 QTY*PRICE。' + + '公式仅用子表列名与 + - * / ( ),落库前服务端逐行权威求算,单元格实时预览。', + items: [ + { type: 'input-text', name: 'column', label: '目标列', required: true, placeholder: 'MONEY', + validations: { matchRegexp: '/^[A-Z][A-Z0-9_]{0,40}$/' }, + validationErrors: { matchRegexp: '须为大写字母开头的子表真实列' } }, + { type: 'input-text', name: 'formula', label: '公式', required: true, placeholder: 'QTY*PRICE' }, + ], + }, + { + type: 'combo', name: 'childRollup', label: '汇总字段', multiple: true, + addable: true, removable: true, addButtonText: '加汇总字段', minLength: 0, + description: '可选。如 申请总额=明细金额之和:主表列填 TOTAL、子表列填 AMOUNT、函数选 SUM。' + + '主表列须为主实体真实列、子表列须为子表真实列;落库前服务端权威聚合,主表单只读实时预览。', + items: [ + { type: 'input-text', name: 'masterColumn', label: '主表列', required: true, placeholder: 'TOTAL', + validations: { matchRegexp: '/^[A-Z][A-Z0-9_]{0,40}$/' }, + validationErrors: { matchRegexp: '须为大写字母开头的主表真实列' } }, + { type: 'input-text', name: 'childColumn', label: '子表列', required: true, placeholder: 'AMOUNT', + validations: { matchRegexp: '/^[A-Z][A-Z0-9_]{0,40}$/' }, + validationErrors: { matchRegexp: '须为大写字母开头的子表真实列' } }, + { type: 'select', name: 'agg', label: '函数', value: 'SUM', options: [ + { label: '求和 SUM', value: 'SUM' }, { label: '计数 COUNT', value: 'COUNT' }, + { label: '平均 AVG', value: 'AVG' }, { label: '最小 MIN', value: 'MIN' }, + { label: '最大 MAX', value: 'MAX' }] }, + ], + }, + { + type: 'combo', name: 'childLinkage', label: '引用联动', multiple: true, + addable: true, removable: true, addButtonText: '加引用联动', minLength: 0, + description: '可选。子表「引用列」(类型=引用)选中某条记录时,自动带出该记录的其它列到同行子列。' + + '如 选物料→带出单价/规格:引用列填 ITEMID(须为引用类型子列);带出映射 目标子列 ITEMPRICE ← 源列 PRICE。' + + '选中时实时填充,提交保存所填值。', + items: [ + { type: 'input-text', name: 'refColumn', label: '引用列', required: true, placeholder: 'ITEMID', + columnClassName: 'w-sm', validations: { matchRegexp: '/^[A-Z][A-Z0-9_]{0,40}$/' }, + validationErrors: { matchRegexp: '须为大写字母开头的引用类型子列' } }, + { + type: 'combo', name: 'fills', label: '带出映射', multiple: true, + addable: true, removable: true, addButtonText: '加带出', minLength: 1, + items: [ + { type: 'input-text', name: 'target', label: '目标子列', required: true, placeholder: 'ITEMPRICE', + validations: { matchRegexp: '/^[A-Z][A-Z0-9_]{0,40}$/' }, + validationErrors: { matchRegexp: '须为大写字母开头的子表真实列' } }, + { type: 'input-text', name: 'source', label: '源列(引用实体)', required: true, placeholder: 'PRICE', + validations: { matchRegexp: '/^[A-Z][A-Z0-9_]{0,40}$/' }, + validationErrors: { matchRegexp: '须为大写字母开头的引用实体列' } }, + ], + }, + ], + }, + ); + } + const compileData: Record = { + tableName: '${masterTable}', recipe, title: '${title}', displayField: '${displayField}', + }; + if (isMD) { + Object.assign(compileData, { + childTable: '${childTablename}', linkColumn: 'MASTERID', listColumn: 'DETAILS', listLabel: '${childName}', + childDerived: '${childDerived}', childRollup: '${childRollup}', childLinkage: '${childLinkage}', + }); + } else { + compileData.pageSize = '${pageSize}'; + } + steps.push({ + title: isMD ? '③ 生成主子页' : '③ 生成页面', + subTitle: '编译落标准层', + api: { method: 'post', url: '/api/design/recipe/compile', data: compileData, responseData: { templateId: '${templateId}' } }, + body: genBody, + }); + + // ④ 发布 + steps.push({ + title: '④ 发布', + subTitle: '五流 + 菜单 + 部署包', + api: { + method: 'post', url: '/api/design/publish', + data: { + entityId: '${masterEntityId}', tableName: '${masterTable}', templateId: '${templateId}', + menuName: '${menuName}', generateDeploymentPackage: true, + }, + }, + body: [ + { type: 'static', name: 'templateId', label: '已生成模板' }, + { type: 'input-text', name: 'menuName', label: '菜单名', required: true, value: '${title}' }, + { + type: 'button', label: '进设计器微调', level: 'enhance', className: 'mb-2', + actionType: 'url', url: '/editor.html?templateId=${templateId}', blank: true, visibleOn: '${templateId}', + }, + { + type: 'alert', level: 'info', + body: '发布 = 写标准页 + 触发默认服务流 + 注册菜单(当前环境立即可用),并生成生产部署包供人审上线(发布恒人审)。' + + (isMD ? '主子表的子行经主表 _ADD 流随主记录级联落库。' : ''), + }, + ], + }); + + return { + type: 'page', + className: 'h-full', + data: { childDerived: [], childRollup: [], childLinkage: [] }, + body: { + type: 'wizard', + mode: 'horizontal', + actionPrevLabel: '上一步', + actionNextLabel: '下一步', + actionNextSaveLabel: '保存并下一步', + actionFinishLabel: '完成(发布)', + renderStepIndicator: true, + steps, + onEvent: { + finished: { + actions: [{ actionType: 'toast', args: { msgType: 'success', msg: '已发布:菜单已注册,可在左侧菜单查看新功能。' } }], + }, + }, + }, + }; +} + +/** 页面类型选择卡。 */ +function RecipeChooser({ onPick }: { onPick: (recipe: string) => void }) { + return ( +
+ {RECIPE_CARDS.map((c) => ( + + ))} +
+ ); +} + +export function NewFeatureShell() { + const navigate = useNavigate(); + const profile = getProfile(); + const isAdmin = profile?.account === 'admin' || profile?.userId === 'ADMIN'; + const [recipe, setRecipe] = useState(null); + const schema = useMemo(() => (recipe ? buildWizardSchema(recipe) : null), [recipe]); + + if (!isAdmin) { + return
新建功能仅管理员可用。
; + } + + return ( +
+
+ +

新建功能 · 人走五环

+
+
+ {schema ? ( + + ) : ( + <> +
先选页面类型,再走「建实体 → 生成页面 → 发布」。
+ + + )} +
+
+ ); +} diff --git a/src/pages/ReferencePicker.test.tsx b/src/pages/ReferencePicker.test.tsx new file mode 100644 index 0000000..8fea1b9 --- /dev/null +++ b/src/pages/ReferencePicker.test.tsx @@ -0,0 +1,47 @@ +import { describe, expect, it, vi, beforeEach } from 'vitest'; +import { render, screen, fireEvent, waitFor } from '@testing-library/react'; +import { ReferencePicker } from './ReferencePicker'; + +vi.mock('../api/meta', () => ({ listEntities: vi.fn(), listEntityColumns: vi.fn() })); +import { listEntities, listEntityColumns } from '../api/meta'; +const mList = vi.mocked(listEntities); +const mCols = vi.mocked(listEntityColumns); + +beforeEach(() => { + mList.mockReset(); + mCols.mockReset(); + mList.mockResolvedValue([ + { entityId: 'E1', tablename: 'SYS_DEPART', name: '部门' }, + { entityId: 'E2', tablename: 'SYS_ORG', name: '组织' }, + ]); + mCols.mockResolvedValue({ + tablename: 'SYS_DEPART', + displayColumn: 'DEPARTNAME', + columns: [ + { column: 'DEPARTNAME', display: '部门名', type: 'string' }, + { column: 'DEPARTCODE', display: '部门编码', type: 'string' }, + ], + }); +}); + +describe('ReferencePicker', () => { + it('加载目标实体清单', async () => { + render( {}} />); + await waitFor(() => expect(screen.getByTestId('ref-target')).toBeInTheDocument()); + expect(mList).toHaveBeenCalled(); + // 选项含 SYS_DEPART + expect(screen.getByRole('option', { name: /SYS_DEPART/ })).toBeInTheDocument(); + }); + + it('选目标实体→回写 referenceTable + 加载其列', async () => { + const onChange = vi.fn(); + render(); + await waitFor(() => expect(screen.getByTestId('ref-target')).toBeInTheDocument()); + fireEvent.change(screen.getByTestId('ref-target'), { target: { value: 'SYS_DEPART' } }); + expect(onChange).toHaveBeenCalledWith('SYS_DEPART'); + await waitFor(() => expect(mCols).toHaveBeenCalledWith('SYS_DEPART')); + // 显示列下拉默认选中 displayColumn + await waitFor(() => expect(screen.getByTestId('ref-display-col')).toBeInTheDocument()); + expect((screen.getByTestId('ref-display-col') as HTMLSelectElement).value).toBe('DEPARTNAME'); + }); +}); diff --git a/src/pages/ReferencePicker.tsx b/src/pages/ReferencePicker.tsx new file mode 100644 index 0000000..a19943f --- /dev/null +++ b/src/pages/ReferencePicker.tsx @@ -0,0 +1,83 @@ +// 引用列选择器(DECISION-1)。type=引用时选目标实体 + 显示列。 +// 父级只需 referenceTable;显示列默认取目标表 displayColumn,仅做预览, +// 实际渲染时由 recipe 按目标表 displayColumn 解析显示名(非裸 id)。 +import { useEffect, useState } from 'react'; +import { listEntities, listEntityColumns, type EntitySummary, type EntityColumn } from '../api/meta'; + +interface ReferencePickerProps { + value: string; // 已选目标表名(父级权威) + onChange: (referenceTable: string) => void; +} + +export function ReferencePicker({ value, onChange }: ReferencePickerProps) { + const [entities, setEntities] = useState([]); + const [cols, setCols] = useState([]); + const [displayCol, setDisplayCol] = useState(''); + const [err, setErr] = useState(''); + // 内部选中态:以父级 value 为初值,select onChange 即时更新,驱动列加载 + // (父级 onChange 不一定立刻回写 value,故列加载不能只依赖 value)。 + const [selected, setSelected] = useState(value); + + useEffect(() => { + setSelected(value); + }, [value]); + + useEffect(() => { + let alive = true; + listEntities() + .then((es) => alive && setEntities(es)) + .catch((e: Error) => alive && setErr(e.message ?? '实体清单加载失败')); + return () => { alive = false; }; + }, []); + + useEffect(() => { + if (!selected) { + setCols([]); + setDisplayCol(''); + return; + } + let alive = true; + listEntityColumns(selected) + .then((c) => { + if (!alive) return; + setCols(c.columns); + setDisplayCol(c.displayColumn || c.columns[0]?.column || ''); + }) + .catch((e: Error) => alive && setErr(e.message ?? '目标列加载失败')); + return () => { alive = false; }; + }, [selected]); + + function handleSelect(table: string) { + setSelected(table); + onChange(table); + } + + return ( +
+ + {selected ? ( + + ) : null} + {err ?
{err}
: null} +
+ ); +} diff --git a/src/setupTests.ts b/src/setupTests.ts new file mode 100644 index 0000000..fdba8ec --- /dev/null +++ b/src/setupTests.ts @@ -0,0 +1,9 @@ +// vitest 全局测试基建:注册 jest-dom 断言匹配器 + 每个用例后自动卸载组件树。 +// 在 vitest.config.ts 的 test.setupFiles 里登记,所有 *.test.tsx 共享。 +import '@testing-library/jest-dom/vitest'; +import { afterEach } from 'vitest'; +import { cleanup } from '@testing-library/react'; + +afterEach(() => { + cleanup(); +}); diff --git a/src/shell/AppShell.tsx b/src/shell/AppShell.tsx index a2a42fa..d71ee84 100644 --- a/src/shell/AppShell.tsx +++ b/src/shell/AppShell.tsx @@ -44,6 +44,12 @@ const TODO_POLL_INTERVAL = 60_000; // 初始 Tab:「工作台」作为保底 Tab,不可关闭 const TODO_TAB: Tab = { key: '/workbench', title: '工作台' }; +// 非 /page/:id 的单例功能路由 → Tab 标题。navigate 到这些路由时自动开成独立 Tab, +// 避免「盖」在当前选中 Tab 上(见下方地址同步 useEffect)。 +const SINGLETON_TAB_TITLES: Record = { + '/design-center': '设计中心', +}; + function loadTabs(): Tab[] { try { const raw = localStorage.getItem(TABS_KEY); @@ -105,6 +111,18 @@ export function AppShell() { return [...prev, { key: path, title: templateId }]; }); setActiveKey(path); + } else { + // 非 /page/ 的单例功能路由(如顶栏「设计中心」入口):也自动开成独立 Tab, + // 否则 navigate() 只换 Outlet 内容、不建 Tab → 设计中心「盖」在当前选中 Tab 上、 + // Tab 条仍高亮旧页(用户反馈「覆盖当前选中 tab」)。 + const title = SINGLETON_TAB_TITLES[path]; + if (title) { + setTabs((prev) => { + if (prev.some((t) => t.key === path)) return prev; + return [...prev, { key: path, title }]; + }); + setActiveKey(path); + } } }, [location.pathname, tabs]); diff --git a/src/shell/theme.css b/src/shell/theme.css index 607a764..f2e7ca2 100644 --- a/src/shell/theme.css +++ b/src/shell/theme.css @@ -136,10 +136,17 @@ body { margin: 0; } -/* 滚动条 */ -::-webkit-scrollbar { width: 6px; height: 6px; } -::-webkit-scrollbar-track { background: transparent; } -::-webkit-scrollbar-thumb { background: var(--line-strong); border-radius: 4px; } +/* 滚动条 —— 做成清晰可见(原 6px 透明轨道+浅灰 thumb 在 macOS overlay 下近乎隐形, + 用户误以为「没有滚动条/滚不动」)。10px 宽 + 浅底轨道 + 可见 thumb + hover 加深; + Firefox 用 scrollbar-* 同口径。 */ +* { scrollbar-width: thin; scrollbar-color: var(--line-strong) transparent; } +::-webkit-scrollbar { width: 10px; height: 10px; } +::-webkit-scrollbar-track { background: var(--surface-2); } +::-webkit-scrollbar-thumb { + background: var(--line-strong); border-radius: 6px; + border: 2px solid var(--surface-2); background-clip: padding-box; +} +::-webkit-scrollbar-thumb:hover { background: var(--text-3); } /* ============================================================================ 通用工具类(全局可用) diff --git a/vite.config.ts b/vite.config.ts index 3d2a1eb..05618f4 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -2,7 +2,7 @@ import { defineConfig, loadEnv } from 'vite'; import react from '@vitejs/plugin-react'; import { resolve } from 'path'; -// 开发期 dev server 把 /api 反代到后端(默认 8084,端口被占时改 8090)。 +// 开发期 dev server 把 /api 反代到后端(dev profile 默认 8093,端口被占时用 .env.local 覆盖)。 // 后端地址经 .env 的 VITE_BACKEND_TARGET 配置;生产由 Nginx 反代,前端只发相对 /api。 // // F4-L1 多页应用(MPA): @@ -16,7 +16,7 @@ import { resolve } from 'path'; // CSS 由 editor.html 直接引用 /node_modules/... 路径,server.fs.allow 放开目录。 export default defineConfig(({ mode }) => { const env = loadEnv(mode, process.cwd(), ''); - const backendTarget = env.VITE_BACKEND_TARGET || 'http://localhost:8084'; + const backendTarget = env.VITE_BACKEND_TARGET || 'http://localhost:8093'; return { plugins: [react()], resolve: { @@ -38,6 +38,16 @@ export default defineConfig(({ mode }) => { allow: ['..'], }, }, + // `npm run preview` 托管 dist 产物时也把 /api 反代到后端,便于本地验证生产构建 + // (生产真部署由 Nginx 反代 /api;此处仅本地 prod-build 验证用,与 server.proxy 同口径)。 + preview: { + proxy: { + '/api': { + target: backendTarget, + changeOrigin: true, + }, + }, + }, build: { // 产物直接交 Nginx 托管;amis 本地 SDK 在 public/ 下原样拷贝,不参与打包。 outDir: 'dist', diff --git a/vitest.config.ts b/vitest.config.ts index ddc15c0..f4e01da 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -8,6 +8,7 @@ export default defineConfig({ test: { environment: 'jsdom', globals: true, + setupFiles: ['./src/setupTests.ts'], include: ['src/**/*.test.ts', 'src/**/*.test.tsx'], }, });