fix: make user branch selection and signature completion reliable

This commit is contained in:
SepehrYahyaee
2026-11-16 10:40:09 +03:30
parent 775934c056
commit e5c4b740e7
10 changed files with 406 additions and 118 deletions
+162 -1
View File
@@ -96,6 +96,22 @@ describe("v1/v6 branch routing through HTTP", () => {
}),
find: jest.fn(async () => [clone(blame)]),
};
const getPath = (row: any, key: string) => key.split(".").reduce((r, bit) => r?.[bit], row);
blameRepo["findOneAndUpdate"] = jest.fn(async (filter, update) => {
if (filter.status && blame.status !== filter.status) return null;
for (const key of Object.keys(filter).filter((key) => key.endsWith(".confirmation"))) {
if (getPath(blame, key) != null) return null;
}
if (filter.$and?.some((condition) => {
const expected = condition.parties.$elemMatch;
return !blame.parties.some((party) => party.role === expected.role &&
party.confirmation?.accepted === true && !!party.confirmation.signature?.fileId);
})) return null;
await blameRepo.findByIdAndUpdate(blame._id, update);
for (const [key, value] of Object.entries(update.$addToSet ?? {}))
setPath(blame, key, [...new Set([...(getPath(blame, key) ?? []), value])]);
return loadBlame();
});
const routing = new UserClaimBranchService({
findAllWithFilters: async (payerId, filter) =>
clone(
@@ -114,6 +130,7 @@ describe("v1/v6 branch routing through HTTP", () => {
userClaimBranchService: routing,
logger,
userSign: {
deleteById: async (id) => { signatures = signatures.filter((s) => s._id !== id); },
create: async (body) => {
const sign = { _id: String(new Types.ObjectId()), ...body };
signatures.push(sign);
@@ -172,7 +189,8 @@ describe("v1/v6 branch routing through HTTP", () => {
}).compile();
app = module.createNestApplication({ logger: false });
app.useGlobalFilters(new PersianErrorFilter(app.get(HttpAdapterHost)));
await app.init();
if (process.env.CLAIM_BRANCH_UI_URL) await app.listen(0, "127.0.0.1");
else await app.init();
jwt = app.get(JwtService);
});
afterAll(async () => {
@@ -479,4 +497,147 @@ describe("v1/v6 branch routing through HTTP", () => {
await create(ids.first).expect(400);
expect(claims).toHaveLength(0);
});
it.each(["v1", "v6"])("%s: simultaneous party signatures settle once and both responses agree with stored status", async (flow) => {
fixture(flow, "THIRD_PARTY", ids.first);
const responses = await Promise.all([sign(ids.first), sign(ids.second, ids.branch)]);
expect(responses.map((r) => r.status)).toEqual([200, 200]);
expect(blame.status).toBe("COMPLETED");
expect(blame.workflow.currentStep).toBe("COMPLETED");
expect(blame.workflow.completedSteps.filter((s) => s === "WAITING_FOR_SIGNATURES")).toHaveLength(1);
expect(signatures).toHaveLength(2);
expect(new Set(signatures.map((signature) => signature.path)).size).toBe(2);
const view = await request(app.getHttpServer()).get(url()).set("Authorization", auth(ids.second)).expect(200);
expect(view.body.nextAction).toBe("CREATE_CLAIM");
await create(ids.second).expect(201);
expect(claims).toHaveLength(1);
});
it.each(["v1", "v6"])("%s: duplicate submissions preserve the first signature and branch", async (flow) => {
fixture(flow, "CAR_BODY", ids.first);
const responses = await Promise.all([sign(ids.first, ids.branch), sign(ids.first, ids.otherBranch)]);
expect(responses.map((r) => r.status)).toEqual([200, 200]);
expect(signatures).toHaveLength(1);
const savedSignature = blame.parties[0].confirmation.signature.fileId;
const savedBranch = blame.branchId;
const retry = await sign(ids.first, ids.otherBranch).expect(200);
expect(retry.body).toMatchObject({status:"COMPLETED", nextAction:"CREATE_CLAIM", claimBranch:{branchId:savedBranch}});
expect(retry.body.confirmation.signature.fileId).toBe(savedSignature);
expect(blame.parties[0].confirmation.signature.fileId).toBe(savedSignature);
expect(blame.branchId).toBe(savedBranch);
expect(signatures).toHaveLength(1);
});
it.each(["v1", "v6"])("%s: signed records stuck waiting recover on reopen without another signature", async (flow) => {
fixture(flow, "THIRD_PARTY", ids.first);
blame.branchId = ids.branch;
for (const party of blame.parties) party.confirmation = { accepted:true, signature:{fileId:"existing-"+party.role} };
const view = await request(app.getHttpServer()).get(url()).set("Authorization", auth(ids.second)).expect(200);
expect(view.body).toMatchObject({status:"COMPLETED",workflow:{currentStep:"COMPLETED",nextStep:null},nextAction:"CREATE_CLAIM"});
expect(signatures).toHaveLength(0);
const retry = await sign(ids.second).expect(200);
expect(retry.body.nextAction).toBe("CREATE_CLAIM");
await create(ids.second).expect(201);
expect(signatures).toHaveLength(0);
});
it("does not complete a stopped file or an incomplete signature record", async () => {
fixture("v6", "THIRD_PARTY", ids.first);
for (const party of blame.parties) party.confirmation = {accepted:true, signature:{fileId:"historic"}};
blame.status = "STOPPED";
const stopped = await request(app.getHttpServer()).get(url()).set("Authorization", auth(ids.second)).expect(200);
expect(stopped.body).toMatchObject({status:"STOPPED",nextAction:"VIEW_RESULT"});
blame.status = "WAITING_FOR_SIGNATURES";
delete blame.parties[0].confirmation.signature.fileId;
const incomplete = await request(app.getHttpServer()).get(url()).set("Authorization", auth(ids.second)).expect(200);
expect(incomplete.body.status).toBe("WAITING_FOR_SIGNATURES");
await create(ids.second).expect(400);
});
it("branch loading uses authorization directly without full case/media hydration", async () => {
fixture("v6", "CAR_BODY", ids.first);
const fullDetail = jest.spyOn(userService, "getBlameRequestV2").mockRejectedValue(new Error("slow media detail must not be called"));
try {
await request(app.getHttpServer()).get(url()+"/claim-branches").set("Authorization",auth(ids.first)).expect(200);
expect(fullDetail).not.toHaveBeenCalled();
} finally {fullDetail.mockRestore();}
});
it("a failed notification cannot turn a persisted signature into a failed submission", async () => {
fixture("v6", "CAR_BODY", ids.first);
const notify = jest.spyOn(userService.smsOrchestrationService, "sendThirdPartyDamagedPartyClaimLinkNotice").mockRejectedValue(new Error("SMS unavailable"));
try {
const response = await sign(ids.first, ids.branch).expect(200);
expect(response.body).toMatchObject({status:"COMPLETED",nextAction:"CREATE_CLAIM"});
expect(blame.status).toBe("COMPLETED");
expect(signatures).toHaveLength(1);
} finally {notify.mockRestore();}
});
it("concurrent conflicting decisions cannot replace an existing confirmation", async () => {
fixture("v6", "CAR_BODY", ids.first);
const responses = await Promise.all([sign(ids.first, ids.branch), sign(ids.first, undefined, false)]);
expect(responses.filter((r) => r.status === 200)).toHaveLength(1);
// Multipart parsing may serialize the requests before the guarded write.
expect([400,409]).toContain(responses.find((r) => r.status !== 200)?.status);
expect(signatures).toHaveLength(1);
const confirmation = clone(blame.parties[0].confirmation);
await sign(ids.first, undefined, !confirmation.accepted).expect(400);
expect(blame.parties[0].confirmation).toEqual(confirmation);
expect(blame.status).toBe(confirmation.accepted ? "COMPLETED" : "STOPPED");
});
// Optional browser tier drives the real UI against these same HTTP services and fixtures.
const browserTest = process.env.CLAIM_BRANCH_UI_URL ? it : it.skip;
browserTest.each(["v1", "v6"].flatMap((flow) => ["CAR_BODY", "THIRD_PARTY"].map((type) => [flow, type])))(
"%s %s: real UI → authenticated HTTP → branch/sign/claim persistence and reload",
async (flow, type) => {
fixture(flow, type, ids.first);
const damaged = type === "CAR_BODY" ? ids.first : ids.second;
if (type === "THIRD_PARTY") await sign(ids.first).expect(200);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({
...(process.env.CLAIM_BRANCH_BROWSER_EXECUTABLE ? {executablePath:process.env.CLAIM_BRANCH_BROWSER_EXECUTABLE} : {}),
headless:true, args:["--no-sandbox", "--disable-dev-shm-usage"],
});
try {
const context = await browser.newContext({viewport:{width:375,height:812},isMobile:true,hasTouch:true});
await context.addInitScript(({token,id}) => {
localStorage.setItem("auth_token",token); localStorage.setItem("role","user"); localStorage.setItem("BlameID",id);
}, {token:auth(damaged).slice(7),id:blame._id});
const page = await context.newPage(), errors:string[] = [];
page.on("pageerror", (e) => errors.push(e.message));
const upstream = await app.getUrl();
await page.route("**/mock-api/**", async (route) => {
const path = new URL(route.request().url()).pathname.replace("/mock-api", "");
const response = await route.fetch({url:upstream+path,headers:{...route.request().headers(),authorization:auth(damaged)}});
await route.fulfill({response});
});
await page.goto(`${process.env.CLAIM_BRANCH_UI_URL}/${flow}/blame/sign`);
await page.getByRole("combobox",{name:/^شهر/}).selectOption(JSON.stringify(["تهران","تهران"]));
await page.getByRole("combobox",{name:/^شعبه/}).selectOption(ids.branch);
expect(await page.getByText("خطای ناشناخته‌ای رخ داده است",{exact:true}).count()).toBe(0);
const canvas = page.locator("canvas"); await canvas.scrollIntoViewIfNeeded();
const box = await canvas.boundingBox();
await page.mouse.move(box.x+30,box.y+30); await page.mouse.down();
await page.mouse.move(box.x+80,box.y+70,{steps:8});
await page.mouse.move(box.x+150,box.y+35,{steps:8}); await page.mouse.up();
await page.getByRole("button",{name:"تایید امضا",exact:true}).click();
await page.waitForURL(`**/${flow}/blame/final`);
await page.getByRole("heading",{name:"آماده ثبت درخواست خسارت",exact:true}).waitFor();
expect(await page.locator("select").count()).toBe(0);
await page.getByRole("button",{name:"ثبت درخواست خسارت",exact:true}).click();
await page.waitForURL(`**/${flow}/claim`);
await page.waitForFunction(() => !!localStorage.getItem("ClaimRequestId"));
expect(blame.status).toBe("COMPLETED"); expect(claims).toHaveLength(1);
expect(claims[0].branchId).toBe(ids.branch);
await page.reload();
await page.waitForFunction(() => {
const button = [...document.querySelectorAll("button")].find((b) => b.textContent?.trim() === "ثبت خسارت");
return button && !button.disabled;
});
expect(claims).toHaveLength(1); expect(errors).toEqual([]);
} finally {await browser.close();}
}, 45_000,
);
});