import { test, expect } from '../fixtures/auth'; import { STORAGE_STATE_PATH } from '../fixtures/auth'; import { request as playwrightRequest, type APIRequestContext } from '@playwright/test'; import fs from 'node:fs'; /** * B2-FIX-1 Employee.Department 作用域校验 e2e 回归。 * * 安全契约: * - 所有测试数据使用 TEST_B2_ 前缀;afterAll 严格按 (子→主) 顺序删除。 * - 不修改任何非 TEST_B2_ 数据;A2 delete guard 保留,不绕过。 * - SCOPE_A=(1,1) 用作正向 master;SCOPE_B=(2,2) 用作 ScopeMiss 触发。 * - 任何 cleanup 失败立即 hard fail(不吞错)。 */ const RUN_ID = `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; const PREFIX = 'TEST_B2_'; const DEPT_CODE = `${PREFIX}DEPT_${RUN_ID}`; const DEPT_NOEXIST = `${PREFIX}NODEPT_${RUN_ID}`; const EMP_HAPPY = `${PREFIX}EMP_OK_${RUN_ID}`; const EMP_NOTFOUND = `${PREFIX}EMP_NF_${RUN_ID}`; const EMP_SCOPEMISS = `${PREFIX}EMP_SM_${RUN_ID}`; const SCOPE_A = { CompanyRefId: 1, FactoryRefId: 1 }; const SCOPE_B = { CompanyRefId: 2, FactoryRefId: 2 }; let api: APIRequestContext; let createdDeptId: number | null = null; let createdEmpId: number | null = null; function tokenFromStorageState(): string { if (!fs.existsSync(STORAGE_STATE_PATH)) { throw new Error(`storage-state.json not found at ${STORAGE_STATE_PATH}; global-setup must run first.`); } const raw = fs.readFileSync(STORAGE_STATE_PATH, 'utf8'); const state = JSON.parse(raw) as { origins?: Array<{ localStorage?: Array<{ name: string; value: string }> }> }; for (const origin of state.origins ?? []) { for (const item of origin.localStorage ?? []) { if (/access-token$/i.test(item.name) && !/x-access-token$/i.test(item.name)) { try { const parsed = JSON.parse(item.value); return typeof parsed === 'string' ? parsed : (parsed?.value ?? item.value); } catch { return item.value; } } } } throw new Error('access-token not found in storage-state.json'); } test.beforeAll(async () => { const baseURL = (process.env.AIDOP_E2E_BASE_URL ?? 'http://localhost:8888').replace(/\/+$/, ''); api = await playwrightRequest.newContext({ baseURL, extraHTTPHeaders: { Authorization: `Bearer ${tokenFromStorageState()}` }, }); const deptResp = await api.post('/api/s0/warehouse/departments', { data: { ...SCOPE_A, DomainCode: 'TEST', Department: DEPT_CODE, Descr: 'B2-TEST-1 fixture', IsActive: true }, }); expect(deptResp.status(), `setup: create TEST_B2_ Department failed: ${await deptResp.text()}`).toBe(200); const deptBody = await deptResp.json(); createdDeptId = deptBody?.recID ?? deptBody?.RecID ?? deptBody?.id ?? null; expect(createdDeptId, 'setup: TEST_B2_ Department rec id missing').not.toBeNull(); }); test.afterAll(async () => { const errors: string[] = []; try { if (createdEmpId !== null) { const r = await api.delete(`/api/s0/warehouse/employees/${createdEmpId}`); if (r.status() !== 200) errors.push(`employee delete ${createdEmpId} -> ${r.status()} ${await r.text()}`); } if (createdDeptId !== null) { const r = await api.delete(`/api/s0/warehouse/departments/${createdDeptId}`); if (r.status() !== 200) errors.push(`department delete ${createdDeptId} -> ${r.status()} ${await r.text()}`); } } finally { await api.dispose(); } expect(errors, `cleanup must succeed: ${errors.join('; ')}`).toEqual([]); }); test('B2-3 happy: employee 与 department 同 scope → 200', async () => { const r = await api.post('/api/s0/warehouse/employees', { data: { ...SCOPE_A, DomainCode: 'TEST', Employee: EMP_HAPPY, Name: 'TestB2', Department: DEPT_CODE, IsActive: true }, }); expect(r.status(), await r.text()).toBe(200); const body = await r.json(); createdEmpId = body?.recID ?? body?.RecID ?? body?.id ?? null; expect(createdEmpId).not.toBeNull(); }); test('B2-3 NotFound: employee 引用不存在的 department → 400 S01011', async () => { const r = await api.post('/api/s0/warehouse/employees', { data: { ...SCOPE_A, DomainCode: 'TEST', Employee: EMP_NOTFOUND, Name: 'TestB2', Department: DEPT_NOEXIST, IsActive: true }, }); expect(r.status()).toBe(400); const body = await r.json(); expect(body?.code ?? body?.Code).toBe('S01011'); }); test('B2-3 ScopeMiss: employee scope 与 department scope 不一致 → 400 S01012', async () => { const r = await api.post('/api/s0/warehouse/employees', { data: { ...SCOPE_B, DomainCode: 'TEST', Employee: EMP_SCOPEMISS, Name: 'TestB2', Department: DEPT_CODE, IsActive: true }, }); expect(r.status()).toBe(400); const body = await r.json(); expect(body?.code ?? body?.Code).toBe('S01012'); }); test('B2-3 Update ScopeMiss: 改 happy employee 到 SCOPE_B → 400 S01012(origin 非 0/0,不降级)', async () => { expect(createdEmpId, 'happy employee must exist before update test').not.toBeNull(); const r = await api.put(`/api/s0/warehouse/employees/${createdEmpId}`, { data: { ...SCOPE_B, DomainCode: 'TEST', Employee: EMP_HAPPY, Name: 'TestB2-updated', Department: DEPT_CODE, IsActive: true }, }); expect(r.status()).toBe(400); const body = await r.json(); expect(body?.code ?? body?.Code).toBe('S01012'); });