import { mkdirSync } from "node:fs"; import path from "node:path"; import { expect, test, type Browser, type Page, type Route } from "@playwright/test"; const ROOT_DIR = path.resolve(process.cwd(), ".."); const SCREENSHOT_DIR = path.join(ROOT_DIR, "output/playwright/r124-mobile-entry-matrix"); const WECOM_UA = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 wxwork/4.1.20 MicroMessenger/8.0.1 Language/zh_CN"; type MockReimbursement = { id: string; formNumber: string; status: "draft" | "reviewing"; reimbursementDate: string; totalAmount: string; description: string; }; type MockNotification = { id: string; type: string; title: string; body: string | null; targetType: string | null; targetId: string | null; readAt: string | null; createdAt: string; }; function envelope(data: unknown) { return { requestId: "mock-r124-mobile-entry-matrix", data }; } async function fulfillJson(route: Route, data: unknown, status = 200) { await route.fulfill({ status, contentType: "application/json", body: JSON.stringify(envelope(data)), }); } function screenshotPath(fileName: string) { mkdirSync(SCREENSHOT_DIR, { recursive: true }); return path.join(SCREENSHOT_DIR, fileName.endsWith(".png") ? fileName : `${fileName}.png`); } function buildMe() { return { id: "employee-r124", employeeNo: "E124", name: "测试员工", phone: "13800000000", email: "employee@hyinda.com", departmentId: "dept-r124", directManagerId: null, status: "active", notificationPushEnabled: true, roleCodes: ["manager", "finance"], profileCompleteness: { hasEmergencyContact: true, hasBankAccount: true, hasAvatar: false, hasIdNumber: false, score: 60, }, wecomBinding: { externalUserId: "wxwork-r124-user", createdAt: "2026-05-08T08:00:00.000Z", }, }; } function navigationItem(key: string, href: string, label: string, icon: string) { return { key, href, label, icon, placement: "main", permissionCodes: [], featureFlagKey: null }; } function buildState() { return { reimbursements: [ { id: "r124-draft", formNumber: "BX20260508024", status: "draft", reimbursementDate: "2026-05-08", totalAmount: "168.00", description: "R124 删除草稿", }, { id: "r124-reviewing", formNumber: "BX20260508025", status: "reviewing", reimbursementDate: "2026-05-08", totalAmount: "266.00", description: "R124 审批中不可删除", }, ] satisfies MockReimbursement[], notifications: [ { id: "notification-r124-1", type: "workflow.task_assigned", title: "报销待审批", body: "BX20260508025 等待处理", targetType: "workflow_task", targetId: "task-r124", readAt: null, createdAt: "2026-05-08T08:00:00.000Z", }, { id: "notification-r124-2", type: "reimbursement.approved", title: "报销已通过", body: "BX20260508024 已通过", targetType: "reimbursement_form", targetId: "r124-draft", readAt: "2026-05-08T08:10:00.000Z", createdAt: "2026-05-08T07:50:00.000Z", }, ] satisfies MockNotification[], }; } function reimbursementItem(item: MockReimbursement) { return { ...item, payment: { paymentVoucherNo: null, paymentDate: null, paymentChannel: null, paidAt: null, paidBy: null, }, owner: { id: "employee-r124", employeeNo: "E124", name: "测试员工" }, submitter: { id: "employee-r124", employeeNo: "E124", name: "测试员工" }, project: null, pendingWorkflow: null, createdAt: "2026-05-08T08:00:00.000Z", updatedAt: "2026-05-08T08:00:00.000Z", }; } async function mockApis(page: Page, state: ReturnType) { await page.route((url) => url.pathname.startsWith("/api/"), async (route) => { const request = route.request(); const url = new URL(request.url()); const pathName = url.pathname; if (pathName === "/api/auth/sso/providers") { await fulfillJson(route, []); return; } if (pathName === "/api/auth/wecom/config") { await fulfillJson(route, { enabled: true, entryEnabled: true, oauthEnabled: true, corpId: "ww-test", agentId: "1000002", loginUrl: "/api/auth/wecom/login?returnTo=%2Fmobile", bindEnabled: true, defaultReturnTo: "/mobile", status: "ready", statusReasons: [], }); return; } if (pathName === "/api/auth/login" || pathName === "/api/auth/refresh") { await route.fulfill({ status: 200, contentType: "application/json", headers: { "set-cookie": "has_session=1; Path=/; SameSite=Lax" }, body: JSON.stringify(envelope({ accessToken: "mock-r124-token", expiresIn: 900, mustChangePassword: false })), }); return; } if (pathName === "/api/me") { await fulfillJson(route, buildMe()); return; } if (pathName === "/api/me/notification-preferences") { await fulfillJson(route, { notificationPushEnabled: true }); return; } if (pathName === "/api/system/navigation") { await fulfillJson(route, { workspace: { id: "workspace-r124", persisted: true, profile: "small_team_internal", orgMode: "single_company", primaryEntryMode: "wecom", notificationStrategy: "in_app", devicePriority: "mobile", moduleVisibility: {}, createdAt: null, updatedAt: null, updatedBy: null, }, sections: { main: [ navigationItem("portal", "/portal", "工作台", "home_app_logo"), navigationItem("expense", "/reimbursements", "报销", "request_quote"), navigationItem("invoice", "/invoice-pool", "票据", "receipt_long"), ], admin: [], backup: [], }, recommendedRolePresets: [], }); return; } if (pathName === "/api/portal/home") { await fulfillJson(route, { workspace: { id: "workspace-r124", persisted: true, profile: "small_team_internal" }, greeting: { name: "测试员工" }, cards: [], pendingTasks: { count: 1, href: "/workflow/tasks" }, myApplications: [], riskSummary: null, announcements: [], quickLinks: [{ key: "expense", title: "新建报销", href: "/reimbursements" }], todayPresence: null, teamPresence: null, weeklyReport: null, weeklySummary: null, todoSummary: null, projectSummary: null, financeSummary: { paymentBatchEnabled: false, href: "/mobile#finance", pendingBatchCount: 0, failedItemCount: 0, riskCount: 0, }, peopleLifecycle: null, adoptionSummary: null, recentActivities: [], teamStatusBoard: [], }); return; } if (pathName === "/api/attendance/me/today") { await fulfillJson(route, { workDate: "2026-05-08", needClockIn: false, exemptionReason: null, item: null }); return; } if (pathName === "/api/workflow/tasks/summary") { await fulfillJson(route, { scope: "mine", pendingTotal: 1, overdueTotal: 0, earliestPendingAt: "2026-05-08T08:00:00.000Z", averagePendingAgeHours: 1, byEntityType: [{ key: "reimbursement", pendingTotal: 1, overdueTotal: 0 }], byStep: [{ key: "主管审批", pendingTotal: 1, overdueTotal: 0 }], byAssigneeRole: [], }); return; } if (pathName === "/api/workflow/tasks") { await fulfillJson(route, { page: 1, pageSize: 100, total: 1, items: [ { id: "task-r124", instanceId: "instance-r124", stepId: "step-r124", stepName: "主管审批", assigneeId: "employee-r124", assigneeRole: null, status: "pending", outcome: null, createdAt: "2026-05-08T08:00:00.000Z", completedAt: null, entityType: "reimbursement", entityId: "r124-reviewing", reference: "BX20260508025", allowedActions: ["approve", "reject", "return", "transfer"], }, ], }); return; } if (pathName === "/api/workflow/approvers") { await fulfillJson(route, { page: 1, pageSize: 100, total: 0, items: [] }); return; } if (pathName === "/api/notifications" && request.method() === "GET") { const unreadOnly = url.searchParams.get("unreadOnly") === "1" || url.searchParams.get("unreadOnly") === "true"; const items = state.notifications.filter((item) => !unreadOnly || !item.readAt); await fulfillJson(route, { page: 1, pageSize: Number(url.searchParams.get("pageSize") ?? 20), total: items.length, unreadOnly, unreadCount: state.notifications.filter((item) => !item.readAt).length, items, }); return; } const markReadMatch = pathName.match(/^\/api\/notifications\/([^/]+)\/mark-read$/); if (markReadMatch && request.method() === "POST") { const item = state.notifications.find((candidate) => candidate.id === markReadMatch[1]); if (item) { item.readAt = "2026-05-08T08:20:00.000Z"; } await fulfillJson(route, { id: markReadMatch[1], readAt: item?.readAt ?? null }); return; } if (pathName === "/api/notifications/mark-all-read" && request.method() === "POST") { for (const item of state.notifications) { item.readAt = item.readAt ?? "2026-05-08T08:20:00.000Z"; } await fulfillJson(route, { updatedCount: state.notifications.length }); return; } if (pathName === "/api/reimbursements" && request.method() === "GET") { const status = url.searchParams.get("status"); const items = state.reimbursements.filter((item) => !status || item.status === status).map(reimbursementItem); await fulfillJson(route, { page: 1, pageSize: Number(url.searchParams.get("pageSize") ?? 20), total: items.length, scope: "own", items, }); return; } const reimbursementDeleteMatch = pathName.match(/^\/api\/reimbursements\/([^/]+)$/); if (reimbursementDeleteMatch && request.method() === "DELETE") { state.reimbursements = state.reimbursements.filter((item) => item.id !== reimbursementDeleteMatch[1]); await fulfillJson(route, { reimbursementId: reimbursementDeleteMatch[1], outcome: "deleted", unboundInvoiceCount: 0, }); return; } if (pathName === "/api/leave-types") { await fulfillJson(route, { items: [ { id: "leave-type-r124", code: "annual", name: "年假", description: null, enabled: true, requiresAttachment: false, attachmentMimeTypes: [], sortOrder: 1, annualQuotaDays: 5, policyDescription: null, }, ], }); return; } if (pathName === "/api/leave-balances") { await fulfillJson(route, { items: [ { employeeId: "employee-r124", leaveType: { id: "leave-type-r124", name: "年假" }, annualQuotaDays: 5, used: 1, reserved: 0, available: 4, }, ], }); return; } if (pathName === "/api/leave-requests") { await fulfillJson(route, { page: 1, pageSize: 20, total: 0, items: [] }); return; } if (pathName === "/api/employees/employee-r124/profile") { await fulfillJson(route, { employee: { id: "employee-r124", employeeNo: "E124", name: "测试员工", phone: "13800000000", email: "employee@hyinda.com", status: "active", departmentId: "dept-r124", department: { id: "dept-r124", name: "研发部" }, directManagerId: null, directManager: null, title: "工程师", employmentStatus: "active", hireDate: "2026-01-01", avatarUrl: null, roleCodes: ["manager"], createdAt: null, updatedAt: null, }, }); return; } await fulfillJson(route, { message: `unhandled mock api: ${pathName}` }, 404); }); } async function loginForMobile(page: Page) { await page.goto("/login"); const accountLoginButton = page.getByRole("button", { name: "使用账号密码登录" }); if (await accountLoginButton.isVisible({ timeout: 1_000 }).catch(() => false)) { await accountLoginButton.click(); } await expect(page.getByTestId("login-identifier")).toBeVisible(); await page.getByTestId("login-identifier").fill("employee@hyinda.com"); await page.getByTestId("login-password").fill("password"); await page.getByTestId("login-submit").click(); await page.waitForURL(/\/(portal|mobile)/, { timeout: 30_000 }); await page.waitForLoadState("networkidle").catch(() => undefined); } async function newWecomPage(browser: Browser) { const context = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true, userAgent: WECOM_UA, locale: "zh-CN", serviceWorkers: "block", }); return { context, page: await context.newPage() }; } async function collectMobileMetrics(page: Page) { return page.evaluate(() => { function isVisible(element: Element) { const rect = element.getBoundingClientRect(); const style = getComputedStyle(element); return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden" && style.display !== "none"; } return { width: window.innerWidth, scrollWidth: Math.max(document.documentElement.scrollWidth, document.body?.scrollWidth ?? 0), tableCount: Array.from(document.querySelectorAll("table")).filter(isVisible).length, pcShellGridCount: document.querySelectorAll(".page-shell-grid").length, clippedStatusSlots: Array.from(document.querySelectorAll(".mobile-status-slot")) .filter(isVisible) .filter((slot) => slot.scrollWidth > slot.clientWidth + 1) .map((slot) => slot.innerText.trim()), text: document.body?.innerText ?? "", }; }); } async function expectMobilePageContract(page: Page) { await page.waitForLoadState("networkidle").catch(() => undefined); const metrics = await collectMobileMetrics(page); expect(metrics.scrollWidth).toBeLessThanOrEqual(metrics.width + 2); expect(metrics.tableCount).toBe(0); expect(metrics.pcShellGridCount).toBe(0); expect(metrics.clippedStatusSlots).toEqual([]); expect(metrics.text).not.toContain("返回仪表盘"); } test.describe("R124 企业微信移动入口矩阵", () => { test.skip(process.env.E2E_MODE === "live", "R124 本地移动专项只在临时本地环境运行"); test("底部入口、我的二级入口、PDF 上传和草稿删除不回退到 PC 体验", async ({ browser }) => { const state = buildState(); const mobile = await newWecomPage(browser); try { await mockApis(mobile.page, state); await loginForMobile(mobile.page); await mobile.page.goto("/mobile"); await expect(mobile.page.getByTestId("mobile-nav-home")).toBeVisible(); await expect(mobile.page.getByTestId("mobile-finance-summary")).toHaveCount(0); await expectMobilePageContract(mobile.page); await mobile.page.getByTestId("mobile-nav-reimbursements").click(); await expect(mobile.page).toHaveURL(/\/mobile\/reimbursements$/); await expect(mobile.page.getByTestId("mobile-reimbursements-list")).toBeVisible(); await expect(mobile.page.getByLabel("当前列表搜索")).toBeVisible(); await expectMobilePageContract(mobile.page); await mobile.page.goto("/mobile/capture"); await expect(mobile.page).toHaveURL(/\/mobile\/capture$/); await expect(mobile.page.getByTestId("mobile-capture-camera-file")).toHaveCount(0); await expect(mobile.page.getByTestId("mobile-capture-image-file")).toHaveCount(0); await expect(mobile.page.getByTestId("mobile-capture-pdf-file")).toBeAttached(); await expect(mobile.page.getByTestId("mobile-capture-pdf-file")).toHaveAttribute("accept", ".pdf,application/pdf"); await expect(mobile.page.getByTestId("mobile-capture-pdf-file")).not.toHaveAttribute("capture", /.+/); await mobile.page.getByTestId("mobile-capture-pdf-file").setInputFiles({ name: "camera.jpg", mimeType: "image/jpeg", buffer: Buffer.from("r124-image"), }); await expect(mobile.page.getByRole("main").getByText(/发票上传仅支持 PDF,已忽略 camera.jpg/)).toBeVisible(); await mobile.page.getByTestId("mobile-capture-pdf-file").setInputFiles({ name: "r124-invoice.pdf", mimeType: "application/pdf", buffer: Buffer.from("r124-pdf"), }); await expect(mobile.page.getByText("r124-invoice.pdf")).toBeVisible(); await mobile.page.screenshot({ path: screenshotPath("mobile-capture") }); await expectMobilePageContract(mobile.page); await mobile.page.getByTestId("mobile-nav-approvals").click(); await expect(mobile.page).toHaveURL(/\/mobile\/approvals$/); await expect(mobile.page.getByRole("heading", { level: 1, name: "待我审批", exact: true })).toBeVisible(); await expect(mobile.page.locator(".mobile-status-slot--approval").first()).toContainText("待处理"); await expectMobilePageContract(mobile.page); await mobile.page.getByTestId("mobile-nav-me").click(); await expect(mobile.page).toHaveURL(/\/mobile\/me$/); await expect(mobile.page.getByTestId("mobile-more-links")).toBeVisible(); await expect(mobile.page.getByText("管理入口")).toHaveCount(0); await expect(mobile.page.getByRole("link", { name: /账号资料/ })).toHaveCount(0); await expect(mobile.page.getByRole("link", { name: /人员管理/ })).toHaveCount(0); await expect(mobile.page.getByRole("link", { name: /组织架构/ })).toHaveCount(0); await expect(mobile.page.getByRole("link", { name: /系统设置/ })).toHaveCount(0); await mobile.page.screenshot({ path: screenshotPath("mobile-me") }); await expectMobilePageContract(mobile.page); await expect(mobile.page.getByRole("link", { name: /财务/ })).toHaveCount(0); await mobile.page.goto("/mobile#finance"); await expect(mobile.page.getByTestId("mobile-finance-summary")).toHaveCount(0); await expectMobilePageContract(mobile.page); await mobile.page.goto("/mobile/me"); await mobile.page.getByRole("link", { name: /个人设置/ }).click(); await expect(mobile.page).toHaveURL(/\/mobile\/profile$/); await expect(mobile.page.getByTestId("mobile-profile-page")).toBeVisible(); await expect(mobile.page.getByTestId("mobile-profile-wecom-card")).toBeVisible(); await expect(mobile.page.getByRole("heading", { name: "账号安全" })).toBeVisible(); await expect(mobile.page.getByRole("heading", { name: "组织与角色摘要" })).toBeVisible(); await expect(mobile.page.getByText("active", { exact: true })).toHaveCount(0); await expect(mobile.page.getByText("manager", { exact: true })).toHaveCount(0); await mobile.page.getByText("查看组织和角色").click(); await expect(mobile.page.getByText("审批人、财务")).toBeVisible(); await mobile.page.screenshot({ path: screenshotPath("mobile-profile") }); await expectMobilePageContract(mobile.page); await mobile.page.goto("/mobile/me"); await mobile.page.getByRole("link", { name: /通知中心/ }).click(); await expect(mobile.page).toHaveURL(/\/mobile\/notifications/); await expect(mobile.page.getByTestId("mobile-notifications-page")).toBeVisible(); await expect(mobile.page.getByTestId("mobile-notification-card")).toHaveCount(2); await mobile.page.screenshot({ path: screenshotPath("mobile-notifications") }); await expectMobilePageContract(mobile.page); await mobile.page.goto("/mobile/me"); await mobile.page.getByRole("link", { name: /请假/ }).click(); await expect(mobile.page).toHaveURL(/\/mobile\/leave$/); await expect(mobile.page.getByTestId("mobile-leave-records")).toBeVisible(); await expect(mobile.page.getByTestId("mobile-leave-balances")).toBeVisible(); await expect(mobile.page.getByTestId("mobile-leave-balances")).toContainText("企业微信主办"); await expect(mobile.page.getByTestId("mobile-leave-balance-summary")).toContainText("4.0"); await expectMobilePageContract(mobile.page); await mobile.page.goto("/mobile/me"); await mobile.page.getByRole("link", { name: /报销/ }).click(); await expect(mobile.page).toHaveURL(/\/mobile\/reimbursements$/); await expect(mobile.page.getByTestId("mobile-reimbursements-list")).toBeVisible(); await expect(mobile.page.getByLabel("当前列表搜索")).toBeVisible(); const draftCard = mobile.page.getByTestId("mobile-reimbursement-card").filter({ hasText: "R124 删除草稿" }).first(); await expect(draftCard).toBeVisible(); await draftCard.locator("summary").click(); await expect(draftCard.getByTestId("mobile-reimbursement-delete")).toBeVisible(); await mobile.page.getByTestId("mobile-reimbursements-tab-reviewing").click(); const reviewingCard = mobile.page.getByTestId("mobile-reimbursement-card").filter({ hasText: "R124 审批中不可删除" }).first(); await expect(reviewingCard).toBeVisible(); await expect(reviewingCard.getByTestId("mobile-reimbursement-delete")).toHaveCount(0); await mobile.page.getByTestId("mobile-reimbursements-tab-draft").click(); await draftCard.locator("summary").click(); await draftCard.getByTestId("mobile-reimbursement-delete").click(); await expect(mobile.page.getByRole("dialog")).toBeVisible(); await mobile.page.getByRole("dialog").getByRole("button", { name: "删除报销单", exact: true }).click(); await expect(mobile.page.getByTestId("mobile-reimbursement-card").filter({ hasText: "R124 删除草稿" })).toHaveCount(0); await mobile.page.screenshot({ path: screenshotPath("mobile-reimbursements-after-delete") }); await expectMobilePageContract(mobile.page); } finally { await mobile.context.close(); } }); });