/** * 主子表(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('袋装'); });