文件
hyb-oa/client/tests/e2e/workflow-action-confirm-ui.spec.ts
wangsli 1dd840655b 修复审批按钮布局测试跨帧测量(09-17-company-loan-principal-repayment)
两个同排按钮在同一次浏览器执行中测量,保留纵坐标严格相等及原高度差断言,不修改报销或资金业务规则。

定向审批浏览器验证 21/21 通过,零重试;任务与治理检查通过。原 7a48a1e7 正式门禁失败记录保留,新候选待重跑完整门禁。

真实建行材料、人员核实与独立业务验收仍待完成;本次仅本地提交,不推送、不部署。
2026-10-08 08:30:38 +08:00

832 行
38 KiB
TypeScript

import type { Page, Route } from "@playwright/test";
import { test, expect } from "./helpers/fixtures";
import { login, MANAGER } from "./helpers/auth";
import { TEST_IDS } from "./helpers/testIds";
test.use({ serviceWorkers: "block" });
function envelope<T>(data: T) {
return { requestId: "mock-workflow-confirm", data };
}
async function fulfillJson<T>(route: Route, data: T) {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(envelope(data)),
});
}
const mockMe = {
id: "employee-confirm-manager",
employeeNo: "M-confirm",
name: "李研发",
email: "[email protected]",
phone: null,
roleCodes: ["manager"],
profileCompleteness: {
hasEmergencyContact: true,
hasBankAccount: true,
hasAvatar: false,
hasIdNumber: false,
score: 70,
},
};
const pendingTaskCreatedAt = new Date().toISOString();
const pendingTask = {
id: "task-confirm-1",
instanceId: "instance-confirm-1",
stepId: "manager-review",
stepName: "主管审批",
assigneeId: mockMe.id,
assigneeRole: "manager",
status: "pending",
outcome: null,
createdAt: pendingTaskCreatedAt,
completedAt: null,
workflowInstance: {
entityType: "leave",
entityId: "leave-confirm-1",
currentStatus: "reviewing",
},
businessSummary: {
reference: "QJ-CONFIRM-001",
title: "R7E 审批确认测试",
applicantName: "Employee",
amount: null,
duration: "1 天",
businessStatus: "reviewing",
},
allowedActions: ["approve", "reject", "return", "transfer"],
};
const pendingTaskDetail = {
task: {
id: pendingTask.id,
instanceId: pendingTask.instanceId,
stepId: pendingTask.stepId,
stepName: pendingTask.stepName,
assigneeId: pendingTask.assigneeId,
assigneeRole: pendingTask.assigneeRole,
status: pendingTask.status,
outcome: null,
comment: null,
createdAt: pendingTask.createdAt,
completedAt: null,
},
workflowInstance: {
id: pendingTask.instanceId,
entityType: "leave",
currentStatus: "reviewing",
currentStepId: "manager-review",
contextData: { standardViolations: [] },
startedAt: pendingTaskCreatedAt,
completedAt: null,
},
reimbursement: null,
leaveRequest: {
id: "leave-confirm-1",
status: "reviewing",
startDate: "2026-06-01",
endDate: "2026-06-01",
startSession: "am",
endSession: "pm",
requestedDays: 1,
reason: "R7E 审批动作确认",
attachment: null,
leaveType: { id: "annual", code: "annual", name: "年假" },
owner: { id: "employee-confirm-applicant", employeeNo: "E-confirm", name: "陈工程" },
},
purchaseRequest: null,
travelRequest: null,
allowedActions: pendingTask.allowedActions,
history: [],
};
function navigationItem(key: string, href: string, label: string, icon: string, placement = "main") {
return { key, href, label, icon, placement, permissionCodes: [], featureFlagKey: null };
}
async function mockWorkflowConfirmApis(page: Page, options: {
taskDetail?: typeof pendingTaskDetail | Record<string, unknown>;
reimbursementDetail?: Record<string, unknown>;
reimbursementDetailFailure?: boolean;
} = {}) {
const actionCalls = {
approve: 0,
reject: 0,
return: 0,
};
await page.route((url) => url.pathname.startsWith("/api/"), async (route) => {
const request = route.request();
const url = new URL(request.url());
const path = url.pathname;
if (path === "/api/auth/sso/providers") {
await fulfillJson(route, []);
return;
}
if (path === "/api/auth/wecom/config") {
await fulfillJson(route, {
enabled: true,
entryEnabled: true,
oauthEnabled: true,
corpId: "wx-test-corp",
agentId: "1000002",
loginUrl: "/api/auth/wecom/login?returnTo=%2Fportal",
bindEnabled: true,
defaultReturnTo: "/portal",
status: "ready",
statusReasons: [],
});
return;
}
if (path === "/api/auth/login" || path === "/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-workflow-confirm-token",
expiresIn: 900,
mustChangePassword: false,
})),
});
return;
}
if (path === "/api/auth/logout") {
await route.fulfill({
status: 200,
contentType: "application/json",
headers: { "set-cookie": "has_session=; Path=/; Max-Age=0" },
body: JSON.stringify(envelope({})),
});
return;
}
if (path === "/api/me") {
await fulfillJson(route, mockMe);
return;
}
if (path === "/api/system/navigation") {
await fulfillJson(route, {
workspace: {
id: "workspace-confirm",
persisted: true,
profile: "small_team_internal",
orgMode: "single_company",
primaryEntryMode: "password",
notificationStrategy: "in_app",
devicePriority: "desktop",
moduleVisibility: {},
createdAt: null,
updatedAt: null,
updatedBy: null,
},
sections: {
main: [
navigationItem("portal", "/portal", "工作台", "home_app_logo"),
navigationItem("workflow", "/workflow/tasks", "待我审批", "fact_check"),
],
admin: [],
backup: [],
},
recommendedRolePresets: [],
});
return;
}
if (path === "/api/notifications") {
await fulfillJson(route, {
page: 1,
pageSize: Number(url.searchParams.get("pageSize") ?? 5),
total: 0,
unreadOnly: url.searchParams.get("unreadOnly") === "1",
unreadCount: 0,
items: [],
});
return;
}
if (path === "/api/portal/home") {
await fulfillJson(route, {
hero: { title: "工作台", subtitle: "审批动作确认测试" },
metrics: [],
todos: [],
notifications: [],
});
return;
}
if (path === "/api/workflow/tasks/summary") {
await fulfillJson(route, {
scope: "mine",
pendingTotal: actionCalls.approve > 0 ? 0 : 1,
overdueTotal: 0,
earliestPendingAt: pendingTask.createdAt,
averagePendingAgeHours: 1,
byEntityType: [],
byStep: [],
byAssigneeRole: [],
});
return;
}
if (path === "/api/workflow/tasks") {
const status = url.searchParams.get("status") ?? "pending";
const items = status === "pending" && actionCalls.approve === 0 ? [pendingTask] : [];
await fulfillJson(route, {
page: 1,
pageSize: Number(url.searchParams.get("pageSize") ?? 20),
total: items.length,
items,
});
return;
}
if (/^\/api\/reimbursements\/[^/]+$/.test(path)) {
if (options.reimbursementDetailFailure) {
await route.fulfill({
status: 500,
contentType: "application/json",
body: JSON.stringify({ requestId: "mock-workflow-confirm", error: { code: "SYS_001", message: "合成加载失败", details: null } }),
});
} else {
await fulfillJson(route, options.reimbursementDetail ?? {});
}
return;
}
const actionMatch = path.match(/^\/api\/workflow\/tasks\/[^/]+\/(approve|reject|return)$/);
if (actionMatch) {
const action = actionMatch[1] as keyof typeof actionCalls;
actionCalls[action] += 1;
await fulfillJson(route, { ok: true });
return;
}
if (/^\/api\/workflow\/tasks\/[^/]+$/.test(path)) {
await fulfillJson(route, options.taskDetail ?? pendingTaskDetail);
return;
}
if (path === "/api/workflow/approvers") {
await fulfillJson(route, {
page: 1,
pageSize: 100,
total: 1,
items: [{ id: "employee-transfer-1", employeeNo: "E-transfer", name: "周审批" }],
});
return;
}
await fulfillJson(route, {});
});
return actionCalls;
}
test.describe("R7E 审批动作二次确认", () => {
test("PC 列表页不提供企微主办请假快捷通过", async ({ page }) => {
const actionCalls = await mockWorkflowConfirmApis(page);
await login(page, MANAGER);
await page.goto("/workflow/tasks");
await expect(page.getByTestId(TEST_IDS.workflow.tasksTable)).toBeVisible();
const taskRow = page.getByTestId(TEST_IDS.workflow.taskRow).filter({ hasText: "QJ-CONFIRM-001" });
await expect(taskRow).toHaveCount(1);
await expect(taskRow.getByTestId(TEST_IDS.workflow.detailLink)).toBeVisible();
await expect(taskRow.getByTestId(TEST_IDS.workflow.quickApprove)).toHaveCount(0);
expect(actionCalls.approve).toBe(0);
});
test("PC 审批详情通过、驳回、退回都先解释动作后果", async ({ page }) => {
const actionCalls = await mockWorkflowConfirmApis(page);
await login(page, MANAGER);
await page.goto(`/workflow/tasks/${pendingTask.id}`);
await expect(page.getByTestId("workflow-task-overview")).toBeVisible();
await expect(page.getByTestId("workflow-action-consequence-help")).toHaveCount(0);
await page.getByTestId("workflow-task-approve").click();
await expect(page.getByTestId("workflow-action-confirm-dialog")).toContainText("确认后将进入下一审批节点");
await page.getByTestId("workflow-action-confirm-cancel").click();
expect(actionCalls.approve).toBe(0);
await page.getByTestId("workflow-task-reject-toggle").click();
await expect(page.getByTestId("workflow-action-consequence-help")).toContainText("流程");
await page.getByTestId("workflow-task-reject-comment").fill("资料不符合要求,请重新发起。");
await page.getByTestId("workflow-task-reject").click();
await expect(page.getByTestId("workflow-action-confirm-dialog")).toContainText("流程将终止");
await page.getByTestId("workflow-action-confirm-cancel").click();
expect(actionCalls.reject).toBe(0);
await page.getByTestId("workflow-task-transfer-menu-item").click();
await expect(page.getByTestId("workflow-task-transfer-disabled-reason")).toHaveText("请先选择目标审批人。");
await expect(page.getByTestId("workflow-task-transfer")).toBeDisabled();
const transferApprover = page.getByTestId("workflow-task-transfer-approver");
const transferReason = page.getByTestId("workflow-task-transfer-reason");
await transferApprover.focus();
await expect(transferApprover).toBeFocused();
await page.keyboard.press("Tab");
await expect(transferReason).toBeFocused();
await transferApprover.selectOption("employee-transfer-1");
await transferReason.fill("理由太短");
await expect(page.getByTestId("workflow-task-transfer-disabled-reason")).toContainText("至少 10 个字");
await expect(page.getByTestId("workflow-task-transfer")).toBeDisabled();
await transferReason.fill("当前事项需转交对应审批人继续处理");
await expect(page.getByTestId("workflow-task-transfer-disabled-reason")).toHaveText("转审理由已满足要求。");
await expect(page.getByTestId("workflow-task-transfer")).toBeEnabled();
await transferReason.focus();
await page.keyboard.press("Tab");
await expect(page.getByTestId("workflow-task-transfer")).toBeFocused();
await page.getByTestId("workflow-task-return-toggle").click();
await page.getByTestId("workflow-task-return-comment").fill("请补充附件后重新提交。");
await page.getByTestId("workflow-task-return").click();
await expect(page.getByTestId("workflow-action-confirm-dialog")).toContainText("回到申请人修改态");
await page.getByTestId("workflow-action-confirm-submit").click();
await expect.poll(() => actionCalls.return).toBe(1);
});
for (const scenario of [
{
entityType: "leave",
label: "请假",
detail: { leaveRequest: pendingTaskDetail.leaveRequest },
expectedText: "R7E 审批动作确认",
},
{
entityType: "attendance_correction",
label: "补卡",
detail: {
attendanceCorrection: {
id: "attendance-confirm-1", status: "reviewing", kind: "missed_punch", workDate: "2026-09-02",
missedPunchAt: "09:05", startAt: null, endAt: null, locationSummary: "公司", compensationPolicy: "按实际打卡修正",
reason: "忘记打卡", owner: { id: "employee-confirm-applicant", employeeNo: "E-confirm", name: "陈工程" },
},
},
expectedText: "忘记打卡",
},
{
entityType: "purchase_request",
label: "采购",
detail: {
purchaseRequest: {
id: "purchase-confirm-1", requestNo: "CG-CONFIRM-001", title: "办公用品采购", status: "reviewing",
totalAmount: "800.00", currencyCode: "CNY", expectedDeliveryDate: "2026-09-10", reason: "补充日常库存",
applicant: { id: "employee-confirm-applicant", employeeNo: "E-confirm", name: "陈工程" },
supplier: { id: "supplier-confirm", name: "合成供应商" }, legalEntity: { id: "entity-confirm", name: "示例公司" },
costCenter: { id: "cost-center-confirm", name: "研发中心" },
},
},
expectedText: "办公用品采购",
},
{
entityType: "travel_request",
label: "差旅",
detail: {
travelRequest: {
id: "travel-confirm-1", requestNo: "CL-CONFIRM-001", status: "reviewing", tripType: "domestic",
startDate: "2026-09-10", endDate: "2026-09-12", estimatedAmount: "1800.00", purpose: "客户现场交流",
applicant: { id: "employee-confirm-applicant", employeeNo: "E-confirm", name: "陈工程" },
legalEntity: { id: "entity-confirm", name: "示例公司" }, costCenter: { id: "cost-center-confirm", name: "研发中心" },
},
},
expectedText: "客户现场交流",
},
]) {
test(`1280px ${scenario.label}审批保持通用详情与动作可达`, async ({ page }) => {
const taskDetail = {
...pendingTaskDetail,
workflowInstance: { ...pendingTaskDetail.workflowInstance, entityType: scenario.entityType },
reimbursement: null,
leaveRequest: null,
attendanceCorrection: null,
purchaseRequest: null,
travelRequest: null,
...scenario.detail,
};
await mockWorkflowConfirmApis(page, { taskDetail });
await page.setViewportSize({ width: 1280, height: 800 });
await login(page, MANAGER);
await page.goto(`/workflow/tasks/${pendingTask.id}`);
await expect(page.getByTestId("workflow-task-summary")).toContainText(scenario.expectedText);
await expect(page.getByRole("heading", { name: "处理历史" })).toBeVisible();
await expect(page.getByTestId("workflow-task-action-panel")).toBeVisible();
await expect(page.getByTestId("workflow-task-approve")).toBeEnabled();
expect(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth + 2)).toBe(true);
});
}
test("PC 报销审批同屏展示证据、引用退回意见且不暴露维护动作", async ({ page }) => {
const reimbursementId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
const taskDetail = {
...pendingTaskDetail,
workflowInstance: {
...pendingTaskDetail.workflowInstance,
entityType: "reimbursement",
contextData: {
standardViolations: [{
itemId: "item-1", expenseTypeId: "type-1", expenseTypeName: "交通费", amount: "180.00",
standardId: "standard-1", standardName: "交通费标准", maxAmount: "120.00", perUnit: "item",
controlMode: "warn", scopeType: "global", scopeKey: null, exceeded: true, exceededAmount: "60.00",
}],
budgetCheck: null,
budgetCheckStatus: "missing",
parseStatus: "ready",
},
},
reimbursement: {
id: reimbursementId,
formNumber: "BX-APPROVAL-001",
status: "reviewing",
reimbursementDate: "2026-09-01",
totalAmount: "180.00",
description: "客户拜访交通费",
owner: { id: "owner", employeeNo: "E001", name: "申请人" },
submitter: { id: "owner", employeeNo: "E001", name: "申请人" },
},
leaveRequest: null,
allowedActions: ["approve", "return", "transfer"],
history: Array.from({ length: 6 }, (_, index) => ({
id: `history-${index + 1}`,
action: index === 0 ? "submit" : "approve",
actorName: index === 0 ? "申请人" : `审批人 ${index}`,
actorEmployeeNo: `E${index + 1}`,
comment: index === 5 ? "这是一条用于验证右栏长意见自然换行且不会把审批动作推到历史之后的合成长意见。".repeat(3) : `第 ${index + 1} 条处理意见`,
createdAt: pendingTaskCreatedAt,
})),
};
const reimbursementDetail = {
id: reimbursementId,
formNumber: "BX-APPROVAL-001",
status: "reviewing",
reimbursementDate: "2026-09-01",
totalAmount: "180.00",
description: "客户拜访交通费",
owner: { id: "owner", employeeNo: "E001", name: "申请人" },
items: [{
id: "item-1", expenseTypeId: "type-1", expenseDate: "2026-09-01", amount: "180.00",
description: "客户拜访打车", assetPriorApprovalBasis: null,
expenseType: { id: "type-1", code: "travel_taxi", name: "交通费", category: "travel", enabled: true, requiresInvoice: true },
}],
invoices: [
{
id: "invoice-1", status: "bound", invoiceCode: null, invoiceNumber: "FP-001", invoiceDate: "2026-09-01",
sellerName: "合成供应商", buyerName: null, documentCategory: "invoice", documentSubtype: null,
totalAmount: "120.00", originalName: "invoice.pdf", mimeType: "application/pdf", fileSize: 100,
linkedItemId: "item-1", amountEvidenceStatus: "verified",
},
{
id: "invoice-2", status: "bound", invoiceCode: null, invoiceNumber: "FP-002", invoiceDate: "2026-09-01",
sellerName: "合成供应商", buyerName: null, documentCategory: "invoice", documentSubtype: null,
totalAmount: null, originalName: "unlinked.pdf", mimeType: "application/pdf", fileSize: 100,
linkedItemId: null, amountEvidenceStatus: "manual_review",
},
],
attachments: [{ id: "attachment-1", originalName: "说明.pdf", mimeType: "application/pdf", fileSize: 100, createdAt: pendingTaskCreatedAt }],
};
await mockWorkflowConfirmApis(page, { taskDetail, reimbursementDetail });
await login(page, MANAGER);
await page.goto(`/workflow/tasks/${pendingTask.id}`);
await expect(page.getByRole("heading", { name: "报销单 BX-APPROVAL-001" })).toHaveCount(1);
await expect(page.getByText("客户拜访交通费", { exact: true })).toHaveCount(1);
await expect(page.getByTestId("reimbursement-approval-evidence")).toContainText("客户拜访打车");
await expect(page.getByTestId("reimbursement-amount-summary")).toContainText("明细合计");
await expect(page.getByTestId("reimbursement-amount-summary")).toContainText("¥180.00");
await expect(page.getByText("报销总额与明细汇总不一致,请联系管理员")).toHaveCount(0);
await expect(page.getByText("明细金额无法完整核对,请联系管理员")).toHaveCount(0);
const actionPanel = page.getByTestId("workflow-task-action-panel");
await expect(actionPanel.getByText("完整内容已就绪", { exact: true })).toHaveCount(0);
await expect(actionPanel.getByText(/^节点:/)).toHaveCount(0);
await expect(actionPanel.getByText(/^状态:/)).toHaveCount(0);
await expect(actionPanel.getByText(/^审批角色:/)).toHaveCount(0);
await expect(page.getByTestId("workflow-task-approve")).toBeEnabled();
await expect(page.getByTestId("workflow-task-return-toggle")).toBeEnabled();
await expect(page.getByTestId("workflow-task-reject-toggle")).toHaveCount(0);
await expect(page.getByTestId("workflow-task-transfer-menu-item")).toBeEnabled();
const primaryActions = page.getByTestId("reimbursement-approval-primary-actions");
await expect(primaryActions.getByRole("button")).toHaveCount(2);
await expect(primaryActions.getByRole("button", { name: "通过" })).toBeVisible();
await expect(primaryActions.getByRole("button", { name: "退回修改" })).toBeVisible();
// Read both rectangles in one browser task: page-reveal moves their shared
// ancestor, so sequential boundingBox calls can observe different frames.
const [approveBox, returnBox] = await primaryActions.evaluate((element) => (
["workflow-task-approve", "workflow-task-return-toggle"].map((testId) => {
const button = element.querySelector(`[data-testid="${testId}"]`);
if (!button) return null;
const { y, height } = button.getBoundingClientRect();
return { y, height };
})
));
expect(approveBox).not.toBeNull();
expect(returnBox).not.toBeNull();
expect(Math.abs(approveBox!.height - returnBox!.height)).toBeLessThanOrEqual(1);
expect(approveBox!.y).toBe(returnBox!.y);
await expect(page.getByTestId("reimbursement-workflow-history").locator(".detail-timeline-item")).toHaveCount(6);
await expect(page.getByRole("heading", { name: "处理历史" })).toHaveCount(1);
const actionBox = await actionPanel.boundingBox();
const historyBox = await page.getByTestId("reimbursement-workflow-history").boundingBox();
expect(actionBox).not.toBeNull();
expect(historyBox).not.toBeNull();
expect(actionBox!.y + actionBox!.height).toBeLessThanOrEqual(historyBox!.y);
expect(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth + 2)).toBe(true);
await expect(page.getByTestId("approval-unlinked-invoices")).toContainText("FP-002");
await expect(page.locator("#reimbursement-workspace-snapshot")).toContainText("该次提交未留存预算快照");
await expect(page.getByText("当前申报金额高于已读取的票面金额合计")).toBeVisible();
await expect(page.getByTestId("workflow-task-overview")).toHaveCount(0);
await expect(page.getByTestId("workflow-task-summary")).toHaveCount(0);
await expect(page.getByText("打开完整原始表单")).toHaveCount(0);
await expect(page.getByText(/0 条/)).toHaveCount(0);
await expect(page.getByTestId("approval-item-evidence").getByRole("button")).toHaveCount(0);
await expect(page.getByRole("button", { name: "删除明细" })).toHaveCount(0);
await expect(page.getByRole("button", { name: "选择明细" })).toHaveCount(0);
await expect(page.getByText("引用到退回意见")).toHaveCount(0);
await expect(page.getByTestId("reimbursement-return-reference-picker")).toHaveCount(0);
await page.getByTestId("workflow-task-return-toggle").click();
await expect(page.getByTestId("reimbursement-return-reference-picker")).toBeVisible();
await page.getByTestId("approval-reference-item").click();
await expect(page.getByTestId("workflow-task-return-comment")).toHaveValue(/【明细:交通费 · 2026-09-01 · ¥180\.00】/);
});
test("PC 报销内容加载失败时全部可见审批入口 fail closed", async ({ page }) => {
const taskDetail = {
...pendingTaskDetail,
workflowInstance: {
...pendingTaskDetail.workflowInstance,
entityType: "reimbursement",
contextData: { standardViolations: [], budgetCheck: null, budgetCheckStatus: "available", parseStatus: "ready" },
},
reimbursement: {
id: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", formNumber: "BX-FAIL-001", status: "reviewing",
reimbursementDate: "2026-09-01", totalAmount: "100.00", description: "合成失败场景",
owner: { id: "owner", employeeNo: "E001", name: "申请人" }, submitter: { id: "owner", employeeNo: "E001", name: "申请人" },
},
leaveRequest: null,
allowedActions: ["approve", "return", "transfer"],
};
await mockWorkflowConfirmApis(page, { taskDetail, reimbursementDetailFailure: true });
await login(page, MANAGER);
await page.goto(`/workflow/tasks/${pendingTask.id}`);
await expect(page.getByRole("alert")).toContainText("报销内容未加载完整,暂不能审批,请刷新后重试");
await expect(page.getByTestId("workflow-task-approve")).toBeDisabled();
await expect(page.getByTestId("workflow-task-return-toggle")).toBeDisabled();
await expect(page.getByTestId("workflow-task-reject-toggle")).toHaveCount(0);
await expect(page.getByTestId("workflow-task-transfer-menu-item")).toBeDisabled();
});
test("移动报销审批保留正文末尾历史且底部动作不遮挡", async ({ page }) => {
const reimbursementId = "reimbursement-mobile-history";
const taskDetail = {
...pendingTaskDetail,
workflowInstance: {
...pendingTaskDetail.workflowInstance,
entityType: "reimbursement",
contextData: { standardViolations: [], budgetCheck: null, budgetCheckStatus: "available", parseStatus: "ready" },
},
reimbursement: {
id: reimbursementId,
formNumber: "BX-MOBILE-HISTORY",
status: "reviewing",
reimbursementDate: "2026-09-01",
totalAmount: "100.00",
description: "移动端历史布局",
owner: { id: "owner", employeeNo: "E001", name: "申请人" },
submitter: { id: "owner", employeeNo: "E001", name: "申请人" },
},
leaveRequest: null,
allowedActions: ["approve", "return", "transfer"],
history: Array.from({ length: 6 }, (_, index) => ({
id: `mobile-history-${index + 1}`,
action: index === 0 ? "submit" : "approve",
actorName: index === 0 ? "申请人" : `审批人 ${index}`,
actorEmployeeNo: `M${index + 1}`,
comment: index === 5 ? "用于验证移动端长意见换行与底部安全区的合成长意见。".repeat(4) : `移动端第 ${index + 1} 条意见`,
createdAt: pendingTaskCreatedAt,
})),
};
const reimbursementDetail = {
id: reimbursementId,
formNumber: "BX-MOBILE-HISTORY",
status: "reviewing",
reimbursementDate: "2026-09-01",
totalAmount: "100.00",
description: "移动端历史布局",
owner: { id: "owner", employeeNo: "E001", name: "申请人" },
items: [{
id: "mobile-item",
expenseTypeId: "mobile-type",
expenseDate: "2026-09-01",
amount: "100.00",
description: "移动端合成明细",
assetPriorApprovalBasis: null,
expenseType: { id: "mobile-type", code: "travel_meal", name: "伙食补助费", category: "travel", enabled: true, requiresInvoice: false },
}],
invoices: [],
attachments: [],
};
await mockWorkflowConfirmApis(page, { taskDetail, reimbursementDetail });
await page.setViewportSize({ width: 375, height: 667 });
await login(page, MANAGER);
await page.goto(`/mobile/approvals/${pendingTask.id}`);
await expect(page.getByTestId("reimbursement-amount-summary")).toContainText("¥100.00");
await expect(page.locator("#reimbursement-workspace-snapshot")).toHaveCount(0);
await expect(page.getByTestId("reimbursement-workflow-history").locator(".detail-timeline-item")).toHaveCount(6);
const stickyActions = page.getByTestId("mobile-approvals-sticky-actions");
await expect(stickyActions.getByRole("button", { name: "退回修改" })).toBeVisible();
await expect(stickyActions.getByRole("button", { name: "通过" })).toBeVisible();
await expect(page.getByTestId("mobile-approvals-reject")).toHaveCount(0);
const assertMobileGeometry = async () => {
expect(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth + 2)).toBe(true);
const lastHistory = page.getByTestId("reimbursement-workflow-history").locator(".detail-timeline-item").last();
await page.evaluate(() => {
const scroller = document.querySelector<HTMLElement>(".hyb-mobile-shell .overflow-y-auto");
scroller?.scrollTo(0, scroller.scrollHeight);
});
const historyBox = await lastHistory.boundingBox();
const stickyBox = await page.getByTestId("mobile-approvals-sticky-actions").boundingBox();
expect(historyBox).not.toBeNull();
expect(stickyBox).not.toBeNull();
expect(historyBox!.y + historyBox!.height).toBeLessThanOrEqual(stickyBox!.y);
};
await assertMobileGeometry();
await page.setViewportSize({ width: 667, height: 375 });
await assertMobileGeometry();
});
for (const scenario of [
{
name: "权威总额与明细汇总不一致",
itemAmount: "99.99",
expectedMessage: "报销总额与明细汇总不一致,请联系管理员",
},
{
name: "明细金额无法解析",
itemAmount: "invalid",
expectedMessage: "明细金额无法完整核对,请联系管理员",
},
]) {
test(`PC 报销${scenario.name}时全部可见审批入口 fail closed`, async ({ page }) => {
const reimbursementId = `reimbursement-integrity-${scenario.itemAmount === "invalid" ? "unavailable" : "mismatch"}`;
const taskDetail = {
...pendingTaskDetail,
workflowInstance: {
...pendingTaskDetail.workflowInstance,
entityType: "reimbursement",
contextData: { standardViolations: [], budgetCheck: null, budgetCheckStatus: "not_applicable", parseStatus: "ready" },
},
reimbursement: {
id: reimbursementId,
formNumber: "BX-INTEGRITY-001",
status: "reviewing",
reimbursementDate: "2026-09-01",
totalAmount: "100.00",
description: "合成完整性场景",
owner: { id: "owner", employeeNo: "E001", name: "申请人" },
submitter: { id: "owner", employeeNo: "E001", name: "申请人" },
},
leaveRequest: null,
allowedActions: ["approve", "return", "transfer"],
};
const reimbursementDetail = {
id: reimbursementId,
formNumber: "BX-INTEGRITY-001",
status: "reviewing",
reimbursementDate: "2026-09-01",
totalAmount: "100.00",
description: "合成完整性场景",
owner: { id: "owner", employeeNo: "E001", name: "申请人" },
items: [{
id: "item-integrity",
expenseTypeId: "type-integrity",
expenseDate: "2026-09-01",
amount: scenario.itemAmount,
description: "完整性核对明细",
assetPriorApprovalBasis: null,
expenseType: { id: "type-integrity", code: "office_supplies", name: "办公用品", category: "office", enabled: true, requiresInvoice: false },
}],
invoices: [],
attachments: [],
};
await mockWorkflowConfirmApis(page, { taskDetail, reimbursementDetail });
await login(page, MANAGER);
await page.goto(`/workflow/tasks/${pendingTask.id}`);
await expect(page.getByTestId("reimbursement-amount-summary")).toContainText("¥100.00");
await expect(page.locator("#reimbursement-workspace-snapshot")).toHaveCount(0);
const blockReason = page.getByTestId("reimbursement-approval-block-reason");
await expect(blockReason).toHaveText(scenario.expectedMessage);
const primaryAction = page.getByTestId("workflow-task-approve");
const blockReasonBox = await blockReason.boundingBox();
const primaryActionBox = await primaryAction.boundingBox();
expect(blockReasonBox).not.toBeNull();
expect(primaryActionBox).not.toBeNull();
expect(blockReasonBox!.y + blockReasonBox!.height).toBeLessThanOrEqual(primaryActionBox!.y);
await expect(page.getByText("差额", { exact: true })).toHaveCount(0);
await expect(page.getByTestId("workflow-task-approve")).toBeDisabled();
await expect(page.getByTestId("workflow-task-return-toggle")).toBeDisabled();
await expect(page.getByTestId("workflow-task-reject-toggle")).toHaveCount(0);
await expect(page.getByTestId("workflow-task-transfer-menu-item")).toBeDisabled();
});
}
});
for (const mobile of [false, true]) {
for (const action of ["approve", "return", "transfer", "already_processed", "failed"] as const) {
test(`财务审批原地进度 ${mobile ? "手机" : "桌面"} ${action}`, async ({ page }) => {
const reimbursementId = "synthetic-finance-progress";
let changed = false;
let readsAfterAction = 0;
let writes = 0;
const expectedResult = action === "return" ? "已退回修改" : action === "transfer" ? "已转审" : "财务复核通过";
const source = {
id: reimbursementId, formNumber: "BX-20260917-0003", status: "reviewing",
reimbursementDate: "2026-09-17", totalAmount: "100.00", description: "合成审批进度验证",
owner: { id: "synthetic-owner", employeeNo: "SYN-1", name: "合成申请人" },
submitter: { id: "synthetic-owner", employeeNo: "SYN-1", name: "合成申请人" },
items: [{ id: "synthetic-item", expenseTypeId: "synthetic-type", expenseDate: "2026-09-17",
amount: "100.00", description: "合成明细", assetPriorApprovalBasis: null,
expenseType: { id: "synthetic-type", code: "synthetic", name: "合成费用", category: "office", enabled: true, requiresInvoice: false } }],
invoices: [], attachments: [],
};
await mockWorkflowConfirmApis(page);
await page.route("**/api/me", (route) => fulfillJson(route, { ...mockMe, roleCodes: action === "transfer" ? ["finance", "manager"] : ["finance"],
permissions: ["expense.approve", "expense.transfer", "expense.view_all"] }));
await page.route(`**/api/reimbursements/${reimbursementId}`, async (route) => {
if (changed) readsAfterAction++;
await fulfillJson(route, { ...source, status: changed && action !== "transfer" ? (action === "return" ? "draft" : "approved") : "reviewing",
processingProgress: { stages: [{ key: "synthetic-finance-task", label: "财务复核",
state: changed ? (action === "return" ? "exception" : action === "transfer" ? "current" : "completed") : "current", actorName: "合成财务", occurredAt: null,
result: changed ? expectedResult : "等待财务复核", comment: null, detail: null, targetHref: null }] } });
});
await page.route(`**/api/workflow/tasks/${pendingTask.id}`, (route) => fulfillJson(route, {
...pendingTaskDetail, task: { ...pendingTaskDetail.task, stepName: "财务复核", assigneeRole: "finance",
status: changed ? "completed" : "pending" },
workflowInstance: { ...pendingTaskDetail.workflowInstance, entityType: "reimbursement",
contextData: { standardViolations: [], budgetCheck: null, budgetCheckStatus: "available", parseStatus: "ready" } },
reimbursement: source, leaveRequest: null, history: [], allowedActions: changed ? [] : ["approve", "return", "transfer"],
}));
await page.route(`**/api/workflow/tasks/${pendingTask.id}/*`, async (route) => {
if (route.request().method() !== "POST") return route.fallback();
writes++;
changed = action !== "failed";
if (action === "already_processed" || action === "failed") {
await route.fulfill({ status: action === "failed" ? 500 : 409, contentType: "application/json",
body: JSON.stringify({ requestId: "synthetic-progress", error: { code: action === "failed" ? "SYS_001" : "VALID_001",
message: "合成失败", details: action === "already_processed" ? { task: "already_processed" } : {} } }) });
} else await fulfillJson(route, { ok: true });
});
await page.setViewportSize(mobile ? { width: 390, height: 844 } : { width: 1280, height: 900 });
await login(page, MANAGER);
await page.goto(`${mobile ? "/mobile/approvals" : "/workflow/tasks"}/${pendingTask.id}`);
const progress = page.getByTestId("reimbursement-approval-processing-progress");
await expect(progress).toContainText("等待财务复核");
const documentMarker = await page.evaluate(() => {
const marker = crypto.randomUUID(); document.documentElement.dataset.syntheticDocument = marker; return marker;
});
if (action === "transfer") {
await page.getByTestId(mobile ? "mobile-approvals-transfer" : "workflow-task-transfer-menu-item").click();
await page.getByTestId(mobile ? "mobile-approvals-transfer-to" : "workflow-task-transfer-approver").selectOption("employee-transfer-1");
await page.getByTestId(mobile ? "mobile-approvals-transfer-reason" : "workflow-task-transfer-reason").fill("合成转审理由用于验证处理进度刷新");
await page.getByTestId(mobile ? "mobile-approvals-transfer-submit" : "workflow-task-transfer").click();
await page.getByTestId("workflow-transfer-confirm-dialog").getByRole("button", { name: "确认转审", exact: true }).click();
} else {
if (action === "return") {
await page.getByTestId(mobile ? "mobile-approvals-return" : "workflow-task-return-toggle").click();
await page.getByTestId(mobile ? "mobile-approvals-comment" : "workflow-task-return-comment").fill("请补充合成资料");
await page.getByTestId(mobile ? "mobile-approvals-return-submit" : "workflow-task-return").click();
} else await page.getByTestId(mobile ? "mobile-approvals-approve" : "workflow-task-approve").click();
await page.getByTestId("workflow-action-confirm-submit").click();
}
await expect.poll(() => writes).toBe(1);
if (action === "failed") {
await expect(page.getByTestId(mobile ? "mobile-approvals-approve" : "workflow-task-approve")).toBeEnabled();
await expect(progress).toContainText("等待财务复核");
expect(readsAfterAction).toBe(0);
} else {
await expect(progress).toContainText(expectedResult);
await expect(progress.locator("li")).toHaveAttribute("data-state", action === "return" ? "exception" : action === "transfer" ? "current" : "completed");
expect(readsAfterAction).toBeGreaterThan(0);
}
expect(await page.evaluate(() => document.documentElement.dataset.syntheticDocument)).toBe(documentMarker);
});
}
}