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/mobile-oa-information-dedupe-governance"); const IOS_WECOM_UA = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_2 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 RolePreset = "employee" | "manager"; 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-dg7-mobile-information-dedupe", 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(role: RolePreset) { return { id: `employee-dg7-${role}`, employeeNo: role === "manager" ? "M-DG7" : "E-DG7", name: role === "manager" ? "测试审批人" : "测试员工", phone: "13800000000", email: `${role}@hyinda.com`, departmentId: "dept-dg7", directManagerId: role === "manager" ? null : "employee-dg7-manager", status: "active", notificationPushEnabled: true, roleCodes: role === "manager" ? ["manager"] : ["employee"], profileCompleteness: { hasEmergencyContact: true, hasBankAccount: true, hasAvatar: false, hasIdNumber: false, score: 60, }, wecomBinding: { externalUserId: `wxwork-dg7-${role}`, createdAt: "2026-05-12T08:00:00.000Z", }, }; } function navigationItem(key: string, href: string, label: string, icon: string) { return { key, href, label, icon, placement: "main", permissionCodes: [], featureFlagKey: null }; } const leaveType = { id: "leave-type-dg7", code: "annual", name: "年假", description: null, enabled: true, requiresAttachment: false, attachmentMimeTypes: [], sortOrder: 1, policy: { id: "leave-policy-dg7", annualQuotaDays: 5, enabled: true, description: null, }, createdAt: null, updatedAt: null, }; const leaveDetail = { id: "leave-dg7-approved", ownerId: "employee-dg7-employee", departmentId: "dept-dg7", status: "approved", startDate: "2026-05-12", endDate: "2026-05-12", startSession: "am", endSession: "pm", requestedDays: 1, reason: "年假", attachment: null, leaveType: { id: leaveType.id, code: leaveType.code, name: leaveType.name, requiresAttachment: false, attachmentMimeTypes: [], }, owner: { id: "employee-dg7-employee", employeeNo: "E-DG7", name: "测试员工" }, pendingWorkflow: null, approvalHistory: [ { id: "history-leave-dg7", taskId: "task-leave-dg7", actorId: "employee-dg7-manager", actorName: "测试审批人", actorEmployeeNo: "M-DG7", action: "approve", comment: "同意", createdAt: "2026-05-12T09:00:00.000Z", }, ], createdAt: "2026-05-12T08:00:00.000Z", updatedAt: "2026-05-12T09:00:00.000Z", }; const purchaseDetail = { id: "purchase-dg7-approved", requestNo: "CG20260512001", applicantId: "employee-dg7-employee", submitterId: "employee-dg7-employee", departmentId: "dept-dg7", legalEntityId: "legal-dg7", costCenterId: "cost-dg7", supplierId: "supplier-dg7", documentCategoryId: null, budgetPoolId: null, title: "办公用品采购", reason: "补充办公用品", currencyCode: "CNY", totalAmount: "320.00", expectedDeliveryDate: "2026-05-20", status: "approved", createdAt: "2026-05-12T08:00:00.000Z", updatedAt: "2026-05-12T09:00:00.000Z", applicant: { id: "employee-dg7-employee", employeeNo: "E-DG7", name: "测试员工" }, submitter: { id: "employee-dg7-employee", employeeNo: "E-DG7", name: "测试员工" }, department: { id: "dept-dg7", name: "研发部" }, legalEntity: { id: "legal-dg7", code: "HYD", name: "海音达" }, costCenter: { id: "cost-dg7", code: "RD", name: "研发中心", legalEntityId: "legal-dg7" }, supplier: { id: "supplier-dg7", code: "SUP-DG7", name: "测试供应商" }, documentCategory: null, budgetPool: null, items: [ { id: "purchase-item-dg7", description: "键盘", specification: "无线", quantity: "2", unitPrice: "160.00", lineAmount: "320.00", isAssetCandidate: false, createdAt: null, updatedAt: null, }, ], attachments: [ { id: "attachment-dg7", originalName: "采购说明.pdf", mimeType: "application/pdf", fileSize: 10240, uploadedBy: "employee-dg7-employee", createdAt: "2026-05-12T08:10:00.000Z", uploader: { id: "employee-dg7-employee", employeeNo: "E-DG7", name: "测试员工" }, }, ], pendingWorkflow: null, approvalHistory: [ { id: "history-purchase-dg7", taskId: "task-purchase-dg7", actorId: "employee-dg7-manager", actorName: "测试审批人", actorEmployeeNo: "M-DG7", action: "approve", comment: "同意", createdAt: "2026-05-12T09:00:00.000Z", }, ], archiveOrder: null, permissions: { canEditDraft: false, canSubmit: false, canWithdraw: false, canArchiveOrder: false, }, riskFlags: [], }; function buildNotifications() { return [ { id: "notification-task-dg7", type: "workflow.task_assigned", title: "报销待审批", body: "报销单 BX20260512001 等待处理", targetType: "workflow_task", targetId: "task-dg7", readAt: null, createdAt: "2026-05-12T08:15:00.000Z", }, { id: "notification-purchase-dg7", type: "purchase_request.approved", title: "采购已通过", body: "采购单 CG20260512001 已通过", targetType: "purchase_request", targetId: purchaseDetail.id, readAt: null, createdAt: "2026-05-12T08:10:00.000Z", }, { id: "notification-leave-dg7", type: "leave.approved", title: "请假已通过", body: "年假申请已通过", targetType: "leave_request", targetId: leaveDetail.id, readAt: null, createdAt: "2026-05-12T08:05:00.000Z", }, ] satisfies MockNotification[]; } function workflowTaskSummary() { return { id: "task-dg7", instanceId: "instance-dg7", stepId: "step-dg7", stepName: "主管审批", assigneeId: "employee-dg7-manager", assigneeRole: null, status: "pending", outcome: null, createdAt: "2026-05-12T08:00:00.000Z", completedAt: null, workflowInstance: { entityType: "reimbursement", entityId: "reimbursement-dg7", currentStatus: "reviewing", }, businessSummary: { reference: "BX20260512001", title: "差旅报销", applicantName: "测试员工", amount: "168.00", duration: null, businessStatus: "reviewing", }, allowedActions: ["approve", "reject", "return", "transfer"], }; } function workflowTaskDetail() { return { task: { id: "task-dg7", instanceId: "instance-dg7", stepId: "step-dg7", stepName: "主管审批", assigneeId: "employee-dg7-manager", assigneeRole: null, status: "pending", outcome: null, comment: null, createdAt: "2026-05-12T08:00:00.000Z", completedAt: null, }, workflowInstance: { id: "instance-dg7", entityType: "reimbursement", currentStatus: "reviewing", currentStepId: "step-dg7", contextData: { standardViolations: [] }, startedAt: "2026-05-12T08:00:00.000Z", completedAt: null, }, reimbursement: { id: "reimbursement-dg7", formNumber: "BX20260512001", status: "reviewing", reimbursementDate: "2026-05-12", totalAmount: "168.00", description: "差旅报销", owner: { id: "employee-dg7-employee", employeeNo: "E-DG7", name: "测试员工" }, submitter: { id: "employee-dg7-employee", employeeNo: "E-DG7", name: "测试员工" }, }, leaveRequest: null, purchaseRequest: null, travelRequest: null, allowedActions: ["approve", "reject", "return", "transfer"], history: [], }; } function reimbursementListItem() { return { id: "reimbursement-dg7", formNumber: "BX20260512001", status: "reviewing", reimbursementDate: "2026-05-12", totalAmount: "168.00", description: "差旅报销", payment: { paymentVoucherNo: null, paymentDate: null, paymentChannel: null, paidAt: null, paidBy: null, }, owner: { id: "employee-dg7-employee", employeeNo: "E-DG7", name: "测试员工" }, submitter: { id: "employee-dg7-employee", employeeNo: "E-DG7", name: "测试员工" }, project: null, pendingWorkflow: { instanceId: "instance-dg7", stepId: "step-dg7", allowedActions: [], task: { id: "task-dg7", stepName: "主管审批", assigneeId: "employee-dg7-manager", assigneeRole: null, }, }, createdAt: "2026-05-12T08:00:00.000Z", updatedAt: "2026-05-12T08:00:00.000Z", }; } async function mockApis(page: Page, role: RolePreset, notifications: MockNotification[]) { 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-dg7-${role}-token`, expiresIn: 900, mustChangePassword: false })), }); return; } if (pathName === "/api/me") { await fulfillJson(route, buildMe(role)); return; } if (pathName === "/api/system/navigation") { await fulfillJson(route, { workspace: { id: "workspace-dg7", 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"), navigationItem("expense", "/reimbursements", "报销", "request_quote"), navigationItem("leave", "/leave-requests", "请假", "event_available"), ], admin: [], backup: [], }, recommendedRolePresets: [], }); return; } if (pathName === "/api/portal/home") { await fulfillJson(route, { workspace: { id: "workspace-dg7", persisted: true, profile: "small_team_internal" }, greeting: { name: buildMe(role).name }, cards: [], pendingTasks: { count: role === "manager" ? 1 : 0, href: "/workflow/tasks" }, myApplications: [], riskSummary: null, announcements: [], quickLinks: [], recentActivities: [], }); return; } if (pathName === "/api/attendance/me/today") { await fulfillJson(route, { workDate: "2026-05-12", needClockIn: false, exemptionReason: null, item: null }); return; } if (pathName === "/api/workflow/tasks/summary") { await fulfillJson(route, { scope: "mine", pendingTotal: role === "manager" ? 1 : 0, overdueTotal: 0, earliestPendingAt: role === "manager" ? "2026-05-12T08:00:00.000Z" : null, averagePendingAgeHours: role === "manager" ? 1 : 0, byEntityType: role === "manager" ? [{ key: "reimbursement", pendingTotal: 1, overdueTotal: 0 }] : [], byStep: role === "manager" ? [{ key: "主管审批", pendingTotal: 1, overdueTotal: 0 }] : [], byAssigneeRole: [], }); return; } if (pathName === "/api/workflow/tasks") { await fulfillJson(route, { page: 1, pageSize: Number(url.searchParams.get("pageSize") ?? 100), total: role === "manager" ? 1 : 0, items: role === "manager" ? [workflowTaskSummary()] : [], }); return; } if (pathName === "/api/workflow/tasks/task-dg7") { await fulfillJson(route, workflowTaskDetail()); 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 typeFilter = url.searchParams.get("type"); const types = typeFilter ? typeFilter.split(",") : null; const items = notifications.filter((item) => { if (unreadOnly && item.readAt) return false; if (types && !types.includes(item.type)) return false; return true; }); await fulfillJson(route, { page: 1, pageSize: Number(url.searchParams.get("pageSize") ?? 20), total: items.length, unreadOnly, unreadCount: notifications.filter((item) => !item.readAt).length, items, }); return; } const markReadMatch = pathName.match(/^\/api\/notifications\/([^/]+)\/mark-read$/); if (markReadMatch && request.method() === "POST") { const item = notifications.find((candidate) => candidate.id === markReadMatch[1]); if (item) { item.readAt = "2026-05-12T08: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 notifications) { item.readAt = item.readAt ?? "2026-05-12T08:20:00.000Z"; } await fulfillJson(route, { updatedCount: notifications.length }); return; } if (pathName === "/api/reimbursements" && request.method() === "GET") { await fulfillJson(route, { page: 1, pageSize: Number(url.searchParams.get("pageSize") ?? 20), total: 1, scope: "own", items: [reimbursementListItem()], }); return; } if (pathName === "/api/leave-types") { await fulfillJson(route, { items: [leaveType] }); return; } if (pathName === "/api/leave-balances") { await fulfillJson(route, { employeeId: "employee-dg7-employee", items: [ { leaveType, policy: leaveType.policy, granted: 5, adjusted: 0, reserved: 0, used: 1, available: 4, periodStart: "2026-01-01", periodEnd: "2026-12-31", }, ], }); return; } if (pathName === `/api/leave-requests/${leaveDetail.id}`) { await fulfillJson(route, leaveDetail); return; } if (pathName === "/api/leave-requests") { await fulfillJson(route, { page: 1, pageSize: Number(url.searchParams.get("pageSize") ?? 20), total: 1, scope: "own", items: [leaveDetail], }); return; } if (pathName === `/api/purchase-requests/${purchaseDetail.id}`) { await fulfillJson(route, purchaseDetail); return; } if (pathName === "/api/purchase-requests" && request.method() === "GET") { await fulfillJson(route, { page: 1, pageSize: Number(url.searchParams.get("pageSize") ?? 20), total: 1, mine: true, items: [purchaseDetail], }); return; } await fulfillJson(route, { message: `unhandled mock api: ${pathName}` }, 404); }); } async function loginForMobile(page: Page, role: RolePreset) { 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(`${role}@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 newMobilePage(browser: Browser, width = 390) { const context = await browser.newContext({ viewport: { width, height: width < 360 ? 568 : 844 }, isMobile: true, hasTouch: true, userAgent: IOS_WECOM_UA, locale: "zh-CN", serviceWorkers: "block", }); return { context, page: await context.newPage() }; } async function expectNoMobileShellRegression(page: Page) { await page.waitForLoadState("networkidle").catch(() => undefined); const metrics = await 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), visibleTables: Array.from(document.querySelectorAll("table")).filter(isVisible).length, pcShellGridCount: document.querySelectorAll(".page-shell-grid").length, }; }); expect(metrics.scrollWidth).toBeLessThanOrEqual(metrics.width + 2); expect(metrics.visibleTables).toBe(0); expect(metrics.pcShellGridCount).toBe(0); } async function expectActionTileGapStable(page: Page) { const gaps = await page.evaluate(() => Array.from(document.querySelectorAll("[data-testid='mobile-action-grid'] a")).map((tile) => { const icon = tile.querySelector("[data-testid$='-icon']"); const label = tile.querySelector("[data-testid$='-label']"); if (!icon || !label) return null; return label.getBoundingClientRect().top - icon.getBoundingClientRect().bottom; }).filter((value): value is number => value !== null), ); expect(gaps.length).toBeGreaterThan(0); for (const gap of gaps) { expect(gap).toBeGreaterThanOrEqual(5); } } test.describe("DG7 移动信息架构与展示去重治理", () => { test.skip(process.env.E2E_MODE === "live", "DG7 本地专项使用 mock 数据验证信息架构。"); test("普通员工底部入口变为进度视角,首页宫格间距在多视口稳定", async ({ browser }) => { for (const width of [320, 360, 375, 390, 393, 414, 430]) { const notifications = buildNotifications(); const mobile = await newMobilePage(browser, width); try { await mockApis(mobile.page, "employee", notifications); await loginForMobile(mobile.page, "employee"); await mobile.page.goto("/mobile"); await expect(mobile.page.getByTestId("mobile-nav-approvals-label")).toHaveText("进度"); await expect(mobile.page.getByTestId("mobile-action-approvals-label")).toHaveText("进度"); await expect(mobile.page.getByTestId("mobile-pending-summary")).toHaveCount(0); await expectActionTileGapStable(mobile.page); await expectNoMobileShellRegression(mobile.page); await mobile.page.getByTestId("mobile-nav-approvals").click(); await expect(mobile.page).toHaveURL(/\/mobile\/approvals$/); await expect(mobile.page.getByTestId("mobile-approvals-progress")).toBeVisible(); await expect(mobile.page.getByTestId("mobile-approvals-list")).toHaveCount(0); await expect(mobile.page.getByTestId("mobile-approvals-approve")).toHaveCount(0); await expect(mobile.page.getByTestId("mobile-approval-progress-card")).toHaveCount(3); await expectNoMobileShellRegression(mobile.page); await mobile.page.screenshot({ path: screenshotPath(`employee-progress-w${width}`), fullPage: true }); } finally { await mobile.context.close(); } } }); test("审批人首页只保留一处待办摘要,审批详情使用 Push 页并隐藏底部 Tab", async ({ browser }) => { const notifications = buildNotifications(); const mobile = await newMobilePage(browser, 390); try { await mockApis(mobile.page, "manager", notifications); await loginForMobile(mobile.page, "manager"); await mobile.page.goto("/mobile"); await expect(mobile.page.getByTestId("mobile-nav-approvals-label")).toHaveText("审批"); await expect(mobile.page.getByTestId("mobile-pending-summary")).toHaveCount(1); await expect(mobile.page.getByTestId("mobile-notifications")).not.toContainText("报销待审批"); await expect(mobile.page.getByTestId("mobile-action-approvals")).not.toContainText("待批"); const badgeMetrics = await mobile.page.evaluate(() => { const nav = document.querySelector("[data-testid='mobile-nav-approvals']"); const icon = nav?.querySelector("[aria-hidden='true']"); const badge = nav?.querySelector("[data-testid='mobile-nav-approvals-badge']"); if (!icon || !badge) return null; const iconRect = icon.getBoundingClientRect(); const badgeRect = badge.getBoundingClientRect(); return { iconLeft: iconRect.left, iconRight: iconRect.right, badgeLeft: badgeRect.left, badgeRight: badgeRect.right, }; }); expect(badgeMetrics).not.toBeNull(); expect(badgeMetrics!.badgeLeft).toBeLessThanOrEqual(badgeMetrics!.iconRight + 4); expect(badgeMetrics!.badgeRight).toBeGreaterThanOrEqual(badgeMetrics!.iconLeft - 14); await mobile.page.getByTestId("mobile-pending-summary").getByRole("link").first().click(); await expect(mobile.page).toHaveURL(/\/mobile\/approvals\/task-dg7$/); await expect(mobile.page.getByTestId("mobile-approvals-detail")).toBeVisible(); await expect(mobile.page.getByTestId("mobile-approvals-list")).toHaveCount(0); await expect(mobile.page.getByTestId("mobile-bottom-nav")).toHaveCount(0); await expect(mobile.page.getByTestId("mobile-approvals-detail")).not.toContainText("业务单号"); await expect(mobile.page.getByTestId("mobile-approvals-detail")).toContainText("报销单 BX20260512001"); await expectNoMobileShellRegression(mobile.page); await mobile.page.screenshot({ path: screenshotPath("manager-approval-push-detail"), fullPage: true }); } finally { await mobile.context.close(); } }); test("通知中心点击通知直达请假和采购详情,不再回到通知列表或首页", async ({ browser }) => { const notifications = buildNotifications(); const mobile = await newMobilePage(browser, 390); try { await mockApis(mobile.page, "employee", notifications); await loginForMobile(mobile.page, "employee"); await mobile.page.goto("/mobile/notifications"); await expect(mobile.page.getByTestId("mobile-notification-card")).toHaveCount(3); await mobile.page.getByTestId("mobile-notification-card").filter({ hasText: "采购已通过" }).click(); await expect(mobile.page).toHaveURL(/\/mobile\/purchase-requests\/purchase-dg7-approved$/); await expect(mobile.page.getByTestId("mobile-purchase-detail-summary")).toBeVisible(); await expect(mobile.page.getByTestId("mobile-bottom-nav")).toHaveCount(0); await expectNoMobileShellRegression(mobile.page); await mobile.page.goto("/mobile/notifications"); await mobile.page.getByTestId("mobile-notification-card").filter({ hasText: "请假已通过" }).click(); await expect(mobile.page).toHaveURL(/\/mobile\/leave\/leave-dg7-approved$/); await expect(mobile.page.getByTestId("mobile-leave-record-card")).toBeVisible(); await expect(mobile.page.getByTestId("mobile-leave-form")).toHaveCount(0); await expect(mobile.page.getByTestId("mobile-bottom-nav")).toHaveCount(0); await expectNoMobileShellRegression(mobile.page); await mobile.page.screenshot({ path: screenshotPath("notification-direct-leave-detail"), fullPage: true }); } finally { await mobile.context.close(); } }); });