修正企微主办边界与工作台摘要(portal-task-first-redesign)

这个提交包含在:
2026-05-29 23:30:30 +08:00
父节点 86f887afa5
当前提交 8bd184f0b3
共修改 9 个文件,包含 296 行新增和 264 行删除
+214 -92
查看文件
@@ -1,110 +1,232 @@
import type { Locator, Page } from "@playwright/test";
import type { Page, Route } from "@playwright/test";
import { test, expect } from "./helpers/fixtures";
import { EMPLOYEE, MANAGER, apiPostData, createAuthenticatedApiClient, login, logout } from "./helpers/auth";
import { openNavLink } from "./helpers/navigation";
import { MANAGER, login } from "./helpers/auth";
import { TEST_IDS } from "./helpers/testIds";
function formatDate(offsetDays: number) {
const value = new Date();
value.setUTCDate(value.getUTCDate() + offsetDays);
return value.toISOString().slice(0, 10);
test.use({ serviceWorkers: "block" });
function envelope<T>(data: T) {
return { requestId: "mock-workflow-boundary", data };
}
async function selectFirstEnabledOption(locator: Locator) {
await expect
.poll(async () => {
const optionValues = await locator.locator("option").evaluateAll((options) =>
options
.map((option) => ({
value: (option as HTMLOptionElement).value,
disabled: (option as HTMLOptionElement).disabled,
}))
.filter((option) => option.value && !option.disabled)
.map((option) => option.value),
);
return optionValues[0] ?? "";
})
.not.toBe("");
const [firstValue] = await locator.locator("option").evaluateAll((options) =>
options
.map((option) => ({
value: (option as HTMLOptionElement).value,
disabled: (option as HTMLOptionElement).disabled,
}))
.filter((option) => option.value && !option.disabled)
.map((option) => option.value),
);
await locator.selectOption(firstValue);
async function fulfillJson<T>(route: Route, data: T) {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(envelope(data)),
});
}
async function createLeaveDraft(page: Page, startDate: string, endDate: string, reason: string) {
const createResponsePromise = page.waitForResponse(
(response) => response.request().method() === "POST" && new URL(response.url()).pathname === "/api/leave-requests" && response.ok(),
);
const manager = {
id: "manager-wecom-boundary",
employeeNo: "M-WECOM",
name: "Manager",
email: "[email protected]",
phone: null,
roleCodes: ["manager"],
profileCompleteness: {
hasEmergencyContact: true,
hasBankAccount: true,
hasAvatar: false,
hasIdNumber: false,
score: 70,
},
};
await selectFirstEnabledOption(page.locator("#leave-type"));
await page.locator("#leave-start-date").fill(startDate);
await page.locator("#leave-end-date").fill(endDate);
await page.locator("#leave-start-session").selectOption("am");
await page.locator("#leave-end-session").selectOption("pm");
await page.locator("#leave-reason").fill(reason);
await page.getByRole("button", { name: "创建草稿" }).click();
const pendingLeaveTask = {
id: "task-wecom-leave-1",
instanceId: "instance-wecom-leave-1",
stepId: "manager-review",
stepName: "主管审批",
assigneeId: manager.id,
assigneeRole: "manager",
status: "pending",
outcome: null,
createdAt: new Date().toISOString(),
completedAt: null,
workflowInstance: {
entityType: "leave",
entityId: "leave-wecom-1",
currentStatus: "reviewing",
},
businessSummary: {
reference: "QJ-WECOM-001",
title: "企微主办请假镜像",
applicantName: "Employee",
amount: null,
duration: "1 天",
businessStatus: "reviewing",
},
allowedActions: ["approve", "reject", "return"],
};
const createPayload = (await (await createResponsePromise).json()) as { data?: { id?: string } };
const leaveRequestId = createPayload.data?.id;
if (!leaveRequestId) {
throw new Error(`创建请假草稿后未返回 id: ${JSON.stringify(createPayload)}`);
}
return leaveRequestId;
function navigationItem(key: string, href: string, label: string, icon: string, placement = "main") {
return { key, href, label, icon, placement, permissionCodes: [], featureFlagKey: null };
}
async function submitLeave(api: Awaited<ReturnType<typeof createAuthenticatedApiClient>>["api"], leaveRequestId: string) {
return apiPostData<{ leaveRequestId: string; currentTaskId: string }>(api, `/api/leave-requests/${leaveRequestId}/submit`, {});
async function mockWorkflowBoundaryApis(page: Page) {
const actionCalls = { approve: 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-boundary-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, manager);
return;
}
if (path === "/api/system/navigation") {
await fulfillJson(route, {
workspace: {
id: "workspace-wecom-boundary",
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"),
navigationItem("leave", "/leave-requests", "请假记录", "event_available"),
],
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: 1,
overdueTotal: 0,
earliestPendingAt: pendingLeaveTask.createdAt,
averagePendingAgeHours: 1,
byEntityType: [{ key: "leave", pendingTotal: 1 }],
byStep: [],
byAssigneeRole: [],
});
return;
}
if (path === "/api/workflow/tasks") {
const status = url.searchParams.get("status") ?? "pending";
const items = status === "pending" ? [pendingLeaveTask] : [];
await fulfillJson(route, {
page: 1,
pageSize: Number(url.searchParams.get("pageSize") ?? 20),
total: items.length,
items,
});
return;
}
if (/^\/api\/workflow\/tasks\/[^/]+\/approve$/.test(path)) {
actionCalls.approve += 1;
await fulfillJson(route, { ok: true });
return;
}
await fulfillJson(route, {});
});
return actionCalls;
}
test("E2E 审批列表快捷通过:经理可在待办列表行内直接通过请假申请", async ({ page }) => {
const employeeClient = await createAuthenticatedApiClient(EMPLOYEE);
const startDate = formatDate(400 + (Date.now() % 3000));
const reason = `Playwright 快捷通过 ${Date.now()}`;
test("审批列表边界:企微主办请假只进入查看处理", async ({ page }) => {
const actionCalls = await mockWorkflowBoundaryApis(page);
try {
await login(page, EMPLOYEE);
await (await openNavLink(page, "请假记录")).click();
await expect(page.getByRole("heading", { name: "请假申请" })).toBeVisible();
await login(page, MANAGER);
await page.goto("/workflow/tasks");
await expect(page.getByTestId(TEST_IDS.workflow.tasksTable)).toBeVisible();
const leaveRequestId = await createLeaveDraft(page, startDate, startDate, reason);
const submitResult = await submitLeave(employeeClient.api, leaveRequestId);
const taskRow = page.getByTestId(TEST_IDS.workflow.taskRow).filter({ hasText: "QJ-WECOM-001" });
await expect(taskRow).toHaveCount(1);
await expect(taskRow).toContainText("请假");
await expect(taskRow).toContainText("企微主办请假镜像");
await expect(taskRow.getByTestId(TEST_IDS.workflow.quickApprove)).toHaveCount(0);
await logout(page, EMPLOYEE.name);
await login(page, MANAGER);
await (await openNavLink(page, "待我处理")).click();
await expect(page.getByTestId(TEST_IDS.workflow.tasksTable)).toBeVisible();
const taskRows = page.locator(
`[data-testid="${TEST_IDS.workflow.taskRow}"]:has(a[href="/workflow/tasks/${submitResult.currentTaskId}"])`,
);
await expect(taskRows).toHaveCount(1, { timeout: 30_000 });
const taskRow = taskRows.first();
await expect(taskRow).not.toContainText(submitResult.currentTaskId);
await expect(taskRow.getByTestId(TEST_IDS.workflow.quickApprove)).toBeVisible();
await expect(taskRow.getByTestId(TEST_IDS.workflow.detailLink)).toBeVisible();
await taskRow.getByTestId(TEST_IDS.workflow.quickApprove).click();
await expect(page.getByTestId("workflow-action-confirm-dialog")).toContainText("确认后将进入下一审批节点");
await page.getByTestId("workflow-action-confirm-submit").click();
await expect(taskRows).toHaveCount(0, { timeout: 30_000 });
await logout(page, MANAGER.name);
await login(page, EMPLOYEE);
await page.goto("/leave-requests");
await expect(page.getByRole("row").filter({ hasText: startDate }).first()).toContainText("已通过", { timeout: 30_000 });
} finally {
await employeeClient.dispose();
}
const detailLink = taskRow.getByTestId(TEST_IDS.workflow.detailLink);
await expect(detailLink).toBeVisible();
await expect(detailLink).toHaveAttribute("href", "/workflow/tasks/task-wecom-leave-1");
expect(actionCalls.approve).toBe(0);
});