droboticflow/tests/browser/supplier-acceptance.mjs

287 lines
14 KiB
JavaScript

// Opt-in localhost synthetic API/Mongo fixture: TestSupplierAcceptanceBrowser.
import assert from "node:assert/strict";
import fs from "node:fs/promises";
import { chromium } from "playwright";
const base = "http://127.0.0.1:5173";
const out = "local-data/verification/supplier-acceptance";
await fs.mkdir(out, { recursive: true });
const browser = await chromium.launch({
executablePath: process.env.BROWSER_EXECUTABLE || "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
headless: true,
args: ["--no-proxy-server"],
});
const reports = [],
errors = [];
async function actor(phone) {
const ctx = await browser.newContext({ viewport: { width: 1600, height: 1000 } });
const res = await ctx.request.post(base + "/api/auth/login", {
data: { phone, password: process.env.ACCEPTANCE_QA_PASSWORD },
});
assert.equal(res.status(), 200, "isolated login");
const page = await ctx.newPage();
page.setDefaultTimeout(20000);
page.on("pageerror", (e) => errors.push(e.message));
return { ctx, page };
}
async function request(ctx, method, path, data) {
const csrf = (await ctx.cookies()).find((c) => c.name === "droboticflow_csrf")?.value;
const res = await ctx.request.fetch(base + path, {
method,
data,
headers: { "X-Droboticflow-CSRF-Token": csrf || "" },
});
return { status: res.status(), body: await res.json() };
}
let active;
try {
const admin = await actor("13900009001");
active = admin.page;
await admin.page.goto(base + "/users");
await admin.page.getByRole("button", { name: /^验收供应商/ }).click();
const toggle = admin.page.getByRole("switch", { name: /允许最终验收/ });
await toggle.waitFor();
await admin.page.waitForFunction(() => !document.querySelector("[role=switch]")?.disabled);
assert.equal(await toggle.isChecked(), false);
await admin.page.getByRole("button", { name: "创建账号", exact: true }).click();
assert.equal(await admin.page.locator('option[value="acceptance_reviewer"]').isDisabled(), true);
await admin.page.getByRole("button", { name: "取消", exact: true }).click();
const blocked = await request(admin.ctx, "POST", "/api/users", {
name: "禁止越权",
phone: "13900009100",
supplierId: "local-reviewer",
role: "acceptance_reviewer",
password: process.env.ACCEPTANCE_QA_PASSWORD,
});
assert.equal(blocked.status, 403);
await toggle.click();
await admin.page.waitForFunction(
() => document.querySelector("[role=switch]")?.checked && !document.querySelector("[role=switch]")?.disabled,
);
await admin.page.screenshot({ path: out + "/authorization.png", fullPage: true });
const created = await request(admin.ctx, "POST", "/api/users", {
name: "创建验收员",
phone: "13900009100",
supplierId: "local-reviewer",
role: "acceptance_reviewer",
password: process.env.ACCEPTANCE_QA_PASSWORD,
});
assert.equal(created.status, 201);
const worker = await request(admin.ctx, "POST", "/api/users", {
name: "角色切换验证",
phone: "13900009101",
supplierId: "local-reviewer",
role: "annotator",
password: process.env.ACCEPTANCE_QA_PASSWORD,
});
assert.equal(worker.status, 201);
assert.equal(
(await request(admin.ctx, "PUT", "/api/users/" + worker.body.id, { role: "acceptance_reviewer" })).status,
200,
);
const manager = await actor("13900009002");
await manager.page.goto(base + "/users");
await manager.page.getByRole("switch").waitFor();
assert.equal(await manager.page.getByRole("switch").isDisabled(), true);
assert.equal(
(
await request(manager.ctx, "PUT", "/api/suppliers/local-reviewer/acceptance-authorization", {
enabled: false,
version: 1,
})
).status,
403,
);
reports.push("default-off; admin switch; create/role change; manager read-only; server enforcement");
const review = await actor("13900009003");
const p = review.page;
active = p;
const calls = [];
p.on("request", (r) => {
if (r.method() === "POST" && r.url().endsWith("/review-continuation")) calls.push(r.postDataJSON());
});
await p.goto(base + "/plugins/annotation-qa/workflows/all/acceptance");
await p.getByLabel("1. 项目", { exact: true }).waitFor();
assert.ok(
(await p.getByLabel("1. 项目", { exact: true }).locator("option").allTextContents()).includes(
"acceptance-project-b",
),
);
await p
.getByTestId("acceptance-task-card")
.filter({ hasText: "source-0-0" })
.getByRole("button", { name: "领取任务", exact: true })
.click();
await p.getByRole("button", { name: /^我的任务/ }).click();
await p.getByTestId("acceptance-task-card").first().getByRole("button", { name: "继续处理", exact: true }).click();
await p.getByText("本页可编辑审查意见", { exact: true }).waitFor();
await p.waitForFunction(() => [...document.querySelectorAll("video")].some((v) => v.readyState >= 2));
await p.screenshot({ path: out + "/normal.png", fullPage: true });
await p.getByRole("button", { name: "进入专注审查", exact: true }).click();
await p.waitForFunction(() => document.querySelector('[data-review-focused="true"]'));
await p.waitForFunction(() =>
[...document.querySelectorAll("video")].some((v) => v.readyState >= 2 && v.getBoundingClientRect().height > 250),
);
const before = new URL(p.url()).searchParams.get("acceptanceId");
assert.ok(before);
await p.screenshot({ path: out + "/focused.png", fullPage: true });
const videoResult = await p
.locator("video")
.first()
.evaluate(async (v) => {
await v.play();
return new Promise((resolve) =>
setTimeout(() => {
v.pause();
resolve({ time: v.currentTime, error: v.error?.code || null });
}, 500),
);
});
assert.ok(videoResult.time > 0);
assert.equal(videoResult.error, null);
// Current-round revoke keeps evidence and drafts, and stops the next shared claim.
const grant = await request(admin.ctx, "GET", "/api/suppliers/local-reviewer/acceptance-authorization");
assert.ok(grant.body.claimedCount >= 1);
assert.equal(
(
await request(admin.ctx, "PUT", "/api/suppliers/local-reviewer/acceptance-authorization", {
enabled: false,
version: grant.body.version,
})
).status,
200,
);
const panel = p.getByRole("region", { name: "审查问题草稿" });
await panel.locator('[data-opinion-scope="task"]').click();
const input = p.getByRole("textbox", { name: "审查问题说明", exact: true });
await input.fill("撤权后保留的隔离测试意见");
await input.press("Control+Enter");
await input.waitFor({ state: "hidden" });
const draft = await request(review.ctx, "GET", "/api/human-items/" + before + "/review-draft");
assert.equal(draft.status, 200);
assert.equal(draft.body.draft.problems.length, 1);
await p.screenshot({ path: out + "/revoked-draft.png", fullPage: true });
await panel.locator('[data-opinion-scope="task"]').click();
await p
.getByRole("button", { name: /清除.*意见/ })
.first()
.click();
await p.getByRole("button", { name: "确认清除", exact: true }).click();
await input.waitFor({ state: "hidden" });
// Re-enable so completed decision can continue across projects.
const off = await request(admin.ctx, "GET", "/api/suppliers/local-reviewer/acceptance-authorization");
assert.equal(
(
await request(admin.ctx, "PUT", "/api/suppliers/local-reviewer/acceptance-authorization", {
enabled: true,
version: off.body.version,
})
).status,
200,
);
const start = p.getByRole("button", { name: "开始/继续审查", exact: true });
if (await start.isVisible()) await start.click();
await p.getByRole("button", { name: "验收通过", exact: true }).click();
await p.getByRole("dialog", { name: "确认审查决定", exact: true }).waitFor();
await p.keyboard.press("Enter");
await p.waitForFunction((id) => new URL(location.href).searchParams.get("acceptanceId") !== id, before);
await p.getByText("本页可编辑审查意见", { exact: true }).waitFor();
const after = new URL(p.url()).searchParams.get("acceptanceId");
const current = await request(review.ctx, "GET", "/api/human-items/" + after);
assert.equal(current.body.item.projectId, "acceptance-project-b");
assert.ok(calls.some((c) => c.scope === "all" && c.action === "next"));
reports.push("normal/focused playback; revoked current-round draft; approve then cross-project continuation");
// Refresh must pause. Selecting a project constrains the new queue.
await p.reload();
await p.getByRole("button", { name: "开始/继续审查", exact: true }).waitFor();
await p.getByRole("button", { name: "返回任务池", exact: true }).click();
await p.getByLabel("1. 项目", { exact: true }).selectOption("acceptance-project-a");
await p.getByRole("button", { name: /^可领取/ }).click();
await p.getByTestId("acceptance-task-card").first().getByRole("button", { name: "领取任务", exact: true }).click();
await p.getByRole("button", { name: /^我的任务/ }).click();
await p.getByTestId("acceptance-task-card").first().getByRole("button", { name: "继续处理", exact: true }).click();
await p.getByText("本页可编辑审查意见", { exact: true }).waitFor();
await p.waitForFunction(() => [...document.querySelectorAll("video")].some((v) => v.readyState >= 2));
const selectedA = new URL(p.url()).searchParams.get("acceptanceId");
await p.getByLabel("1. 项目", { exact: true }).selectOption("acceptance-project-b");
await p.waitForFunction((id) => new URL(location.href).searchParams.get("acceptanceId") === id, after);
await p.getByText("本页可编辑审查意见", { exact: true }).waitFor();
await p.getByLabel("1. 项目", { exact: true }).selectOption("acceptance-project-a");
await p.waitForFunction((id) => new URL(location.href).searchParams.get("acceptanceId") === id, selectedA);
await p.getByText("本页可编辑审查意见", { exact: true }).waitFor();
reports.push("active filter changes stop the old queue and resume the new project, preferring existing claims");
await p.getByRole("region", { name: "审查问题草稿" }).locator('[data-opinion-scope="task"]').click();
await input.fill("隔离测试退回原生产质检");
await input.press("Control+Enter");
await input.waitFor({ state: "hidden" });
const rejected = new URL(p.url()).searchParams.get("acceptanceId");
await p.getByRole("button", { name: "打回质检", exact: true }).click();
await p.getByRole("dialog", { name: "确认审查决定", exact: true }).waitFor();
await p.keyboard.press("Enter");
await p.waitForFunction((id) => new URL(location.href).searchParams.get("acceptanceId") !== id, rejected);
await p.getByText("本页可编辑审查意见", { exact: true }).waitFor();
const third = await request(
review.ctx,
"GET",
"/api/human-items/" + new URL(p.url()).searchParams.get("acceptanceId"),
);
assert.equal(third.body.item.projectId, "acceptance-project-a");
assert.ok(calls.some((c) => c.scope === "project" && c.projectId === "acceptance-project-a" && c.action === "next"));
reports.push("refresh pause; specific-project queue; save opinion and reject; continue within filter");
const history = await review.ctx.newPage();
await history.goto(base + "/plugins/annotation-qa/workflows/all/acceptance");
await history.getByTestId("human-task-pool-reviewed").click();
const approvedCard = history.locator(`[data-item-id="${before}"]`);
const rejectedCard = history.locator(`[data-item-id="${rejected}"]`);
await approvedCard.waitFor();
await rejectedCard.waitFor();
assert.match(await approvedCard.innerText(), /已完成/);
assert.match(await rejectedCard.innerText(), /已打回/);
active = history;
await rejectedCard.getByRole("button", { name: "查看结果", exact: true }).click();
await history.getByTestId("review-current-slice").waitFor();
assert.ok((await history.getByTestId("review-current-slice").innerText()).trim());
for (const name of ["验收通过", "打回质检"]) {
const buttons = history.getByRole("button", { name, exact: true });
for (const button of await buttons.all()) assert.equal(await button.isDisabled(), true);
}
await history.getByRole("button", { name: "文件清单", exact: true }).click();
assert.equal(await history.getByTestId("review-current-slice").isVisible(), true);
await history.screenshot({ path: out + "/acceptance-history.png", fullPage: true });
await history.close();
active = p;
reports.push("own approved/rejected history, read-only results, current slice remains visible in file view");
// Revoke through the actual admin confirmation, then finish the current
// round. The queue must explain why it will not claim another task.
await admin.page.reload();
await admin.page.getByRole("button", { name: /^验收供应商/ }).click();
await admin.page.waitForFunction(() => !document.querySelector("[role=switch]")?.disabled);
let revocationPrompt = "";
admin.page.once("dialog", async (d) => {
revocationPrompt = d.message();
await d.accept();
});
await admin.page.getByRole("switch", { name: /允许最终验收/ }).click();
await admin.page.waitForFunction(
() => !document.querySelector("[role=switch]")?.checked && !document.querySelector("[role=switch]")?.disabled,
);
assert.match(revocationPrompt, /已领取的 [1-9][0-9]* 条共享任务/);
await p.waitForFunction(() => [...document.querySelectorAll("video")].some((v) => v.readyState >= 2));
await p.getByRole("button", { name: "验收通过", exact: true }).click();
await p.getByRole("dialog", { name: "确认审查决定", exact: true }).waitFor();
await p.keyboard.press("Enter");
await p.getByText("当前验收已完成,供应商授权已关闭,连续验收已停止。", { exact: true }).waitFor();
await p.screenshot({ path: out + "/revoked-continuation.png", fullPage: true });
reports.push("revocation confirmation counts; current-round approve succeeds; clear stop message, no new claim");
assert.deepEqual(errors, []);
await fs.writeFile(out + "/result.json", JSON.stringify({ reports, calls, errors }, null, 2));
console.log(JSON.stringify({ reports, errors }));
} catch (e) {
if (active) {
await active.screenshot({ path: out + "/failure.png", fullPage: true });
console.log((await active.locator("body").innerText()).slice(-12000));
}
throw e;
} finally {
await browser.close();
}