import { chromium, request } from "playwright"; import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const stamp = new Date().toISOString().replace(/[:.]/g, "-"); const runId = `slice5-pilot-${Date.now()}`; const webBase = process.env.SLICE5_WEB_URL || "http://localhost:3000"; const apiBase = process.env.SLICE5_API_URL || "http://127.0.0.1:8010/api/v1"; const healthUrl = process.env.SLICE5_HEALTH_URL || "http://127.0.0.1:8010/health"; const adminPassword = process.env.AI_CONTRACT_ADMIN_PASSWORD || "123456"; const artifactDir = process.env.SLICE5_ARTIFACT_DIR || path.resolve(__dirname, "..", "..", "project-docs", "qa-artifacts", "slice5-pilot-shell-closed-loop", stamp); fs.mkdirSync(artifactDir, { recursive: true }); const results = []; const state = { api: null, browser: null, contexts: [], admin: null, requestId: null, companyName: `切片五试点企业-${Date.now()}`, contactName: "切片五联系人", email: `slice5-${Date.now()}@example.com`, }; function apiUrl(route) { return `${apiBase.replace(/\/$/, "")}${route}`; } function screenshotPath(name) { return path.join(artifactDir, `${name}.png`); } function assert(condition, message, details = undefined) { if (!condition) { const error = new Error(message); error.details = details; throw error; } } async function step(id, title, fn) { const startedAt = new Date().toISOString(); const started = Date.now(); try { const details = await fn(); const item = { id, title, status: "PASS", duration_ms: Date.now() - started, started_at: startedAt, details: details || {} }; results.push(item); console.log(`PASS ${id} ${title}`); return item; } catch (error) { const item = { id, title, status: "FAIL", duration_ms: Date.now() - started, started_at: startedAt, error: error.message, details: error.details || {}, }; results.push(item); console.error(`FAIL ${id} ${title}: ${error.message}`); return item; } } async function apiRequest(method, route, options = {}) { const headers = { ...(options.authToken ? { Authorization: `Bearer ${options.authToken}` } : {}), ...(options.headers || {}), }; const response = await state.api[method](apiUrl(route), { ...options, headers }); const text = await response.text(); let body = null; if (text) { try { body = JSON.parse(text); } catch { body = text; } } return { response, body, text }; } function expectOk(payload, label) { assert(payload.response.status() >= 200 && payload.response.status() < 300, `${label} HTTP ${payload.response.status()}`, { body: payload.body, }); if (payload.body && typeof payload.body === "object" && "code" in payload.body) { assert(payload.body.code === 0, `${label} API code ${payload.body.code}`, { body: payload.body }); } } async function login(account, password) { const payload = await apiRequest("post", "/auth/login", { data: { account, password } }); expectOk(payload, `login ${account}`); return payload.body.data; } async function attachApiProxy(context) { await context.route("**/api/v1/**", async (route) => { const browserRequest = route.request(); const browserUrl = new URL(browserRequest.url()); const targetUrl = apiUrl(browserUrl.pathname.replace(/^\/api\/v1/, "") + browserUrl.search); const headers = { ...browserRequest.headers() }; delete headers.host; const response = await state.api.fetch(targetUrl, { method: browserRequest.method(), headers, data: browserRequest.postDataBuffer() ?? undefined, }); await route.fulfill({ response }); }); } async function createAuthenticatedContext(userSession) { const context = await state.browser.newContext({ viewport: { width: 1440, height: 1100 } }); await context.addInitScript( ({ token, user }) => { window.localStorage.setItem("access_token", token); window.localStorage.setItem("auth-store", JSON.stringify({ state: { accessToken: token, currentUser: user }, version: 0 })); }, { token: userSession.access_token, user: userSession.user }, ); await attachApiProxy(context); state.contexts.push(context); return context; } async function createPublicContext() { const context = await state.browser.newContext({ viewport: { width: 1440, height: 1100 } }); await attachApiProxy(context); state.contexts.push(context); return context; } try { state.api = await request.newContext(); state.browser = await chromium.launch({ headless: true }); await step("ENV-001", "frontend and backend health", async () => { const [frontend, health] = await Promise.all([state.api.get(`${webBase}/`), state.api.get(healthUrl)]); assert(frontend.status() === 200, `frontend / status ${frontend.status()}`); assert(health.status() === 200, `backend /health status ${health.status()}`); return { webBase, apiBase, healthUrl, artifactDir }; }); await step("PUBLIC-001", "public demo request page submits pilot request", async () => { const context = await createPublicContext(); const page = await context.newPage(); await page.goto(`${webBase}/demo-request`, { waitUntil: "domcontentloaded" }); await page.getByPlaceholder("例如:张三").fill(state.contactName); await page.getByPlaceholder("例如:示例科技有限公司").fill(state.companyName); await page.getByPlaceholder("例如:法务负责人 / 业务负责人 / 信息化负责人").fill("法务负责人"); await page.getByPlaceholder("name@company.com").fill(state.email); await page.getByPlaceholder("选填,用于演示沟通").fill("13800000000"); await page.getByPlaceholder("例如:每月 100 份 / 每季度 500 份").fill("每月 200 份"); await page.getByLabel("最想先验证的目标").click(); await page.getByText("合同审查试点", { exact: true }).click(); await page.getByLabel("部署偏好").click(); await page.getByText("SaaS", { exact: true }).click(); await page.getByPlaceholder("例如:希望先验证采购合同的自动审查、风险提示和报告导出,后续再接入知识库问答。").fill( "希望先验证采购合同自动审查、风险提示和报告导出的试点能力。", ); await page.getByRole("button", { name: "提交演示申请" }).click(); await page.waitForTimeout(1200); await page.screenshot({ path: screenshotPath("demo-request-success"), fullPage: true }); const body = await page.locator("body").innerText(); const match = body.match(/pilot-[a-z0-9]+/i); assert(body.includes("申请已提交"), "demo request success message missing", body.slice(0, 2000)); assert(match, "pilot request id missing in success body", body.slice(0, 2000)); state.requestId = match[0]; return { request_id: state.requestId, company_name: state.companyName }; }); await step("AUTH-001", "admin seed and login", async () => { const seed = await apiRequest("post", "/auth/seed-admin"); expectOk(seed, "seed default admin"); state.admin = await login("admin@example.com", adminPassword); assert(state.admin.user.role === "admin", "admin role mismatch", state.admin.user); return { user: state.admin.user.username, role: state.admin.user.role }; }); await step("ADMIN-001", "admin APIs can see submitted pilot request", async () => { const [list, summary] = await Promise.all([ apiRequest("get", "/pilot-requests", { authToken: state.admin.access_token }), apiRequest("get", "/pilot-requests/summary", { authToken: state.admin.access_token }), ]); expectOk(list, "pilot request list"); expectOk(summary, "pilot request summary"); const matched = list.body.data.items.find((item) => item.id === state.requestId); assert(matched, "submitted pilot request missing from admin list", list.body.data.items); assert(summary.body.data.total >= 1, "pilot summary total should be >= 1", summary.body.data); return { total: summary.body.data.total, request_id: state.requestId }; }); await step("ADMIN-002", "admin pilot request page updates request status", async () => { const context = await createAuthenticatedContext(state.admin); const page = await context.newPage(); await page.goto(`${webBase}/pilot-requests`, { waitUntil: "domcontentloaded" }); await page.waitForTimeout(1800); const body = await page.locator("body").innerText(); assert(body.includes(state.companyName), "pilot request page missing submitted company", body.slice(0, 2600)); await page.getByRole("button", { name: "跟进状态" }).first().click(); await page.getByLabel("跟进状态").click(); await page.locator(".ant-select-dropdown .ant-select-item-option").filter({ hasText: "已排演示" }).first().click(); await page.getByLabel("管理员备注").fill("已安排本周四试点演示。"); await page.getByRole("button", { name: "保存状态" }).click(); await page.waitForTimeout(1600); await page.screenshot({ path: screenshotPath("pilot-requests-updated"), fullPage: true }); const updatedBody = await page.locator("body").innerText(); assert(updatedBody.includes("已排演示"), "scheduled status missing after update", updatedBody.slice(0, 2600)); return { request_id: state.requestId, updated_status: "scheduled" }; }); await step("BROWSER-001", "admin workspace exposes pilot request entry", async () => { const context = await createAuthenticatedContext(state.admin); const page = await context.newPage(); await page.goto(`${webBase}/admin`, { waitUntil: "domcontentloaded" }); await page.waitForTimeout(1200); const body = await page.locator("body").innerText(); assert(body.includes("试点申请"), "admin workspace missing pilot request entry", body.slice(0, 2000)); return { href: "/pilot-requests" }; }); } finally { for (const context of state.contexts) { await context.close().catch(() => {}); } if (state.browser) { await state.browser.close().catch(() => {}); } if (state.api) { await state.api.dispose().catch(() => {}); } const summary = { run_id: runId, artifact_dir: artifactDir, passed: results.filter((item) => item.status === "PASS").length, failed: results.filter((item) => item.status === "FAIL").length, results, }; fs.writeFileSync(path.join(artifactDir, "summary.json"), `${JSON.stringify(summary, null, 2)}\n`, "utf8"); console.log(`Wrote ${path.join(artifactDir, "summary.json")}`); if (summary.failed > 0) { process.exitCode = 1; } }