forked from Yara724/api
644 lines
27 KiB
TypeScript
644 lines
27 KiB
TypeScript
/** Real HTTP controllers, JWT/role guards and services; in-memory DB and no external delivery. */
|
|
import "reflect-metadata";
|
|
import { Test } from "@nestjs/testing";
|
|
import { JwtModule, JwtService } from "@nestjs/jwt";
|
|
import { HttpAdapterHost } from "@nestjs/core";
|
|
import { INestApplication } from "@nestjs/common";
|
|
import * as request from "supertest";
|
|
import { unlink } from "node:fs/promises";
|
|
import { Types } from "mongoose";
|
|
import { GlobalGuard } from "src/auth/guards/global.guard";
|
|
import { RolesGuard } from "src/auth/guards/role.guard";
|
|
import { PersianErrorFilter } from "src/common/errors/persian-error.filter";
|
|
import { MediaPolicyService } from "src/media-policy/media-policy.service";
|
|
import { UserClaimBranchService } from "src/client/user-claim-branch.service";
|
|
import { RequestManagementV2Controller } from "src/request-management/request-management.v2.controller";
|
|
import { RequestManagementService } from "src/request-management/request-management.service";
|
|
import { ClaimRequestManagementV2Controller } from "src/claim-request-management/claim-request-management.v2.controller";
|
|
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
|
|
import { ExpertClaimService } from "src/expert-claim/expert-claim.service";
|
|
|
|
const ids = {
|
|
first: "650000000000000000000001",
|
|
second: "650000000000000000000002",
|
|
payer: "650000000000000000000003",
|
|
otherInsurer: "650000000000000000000004",
|
|
branch: "650000000000000000000005",
|
|
otherBranch: "650000000000000000000006",
|
|
foreignBranch: "650000000000000000000007",
|
|
inactiveBranch: "650000000000000000000008",
|
|
outsider: "650000000000000000000009",
|
|
expert: "650000000000000000000010",
|
|
};
|
|
const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value));
|
|
const png = Buffer.from(
|
|
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jTncAAAAASUVORK5CYII=",
|
|
"base64",
|
|
);
|
|
function setPath(target: any, path: string, value: any) {
|
|
const bits = path.split(".");
|
|
let current = target;
|
|
for (const bit of bits.slice(0, -1)) current = current[bit] ??= {};
|
|
current[bits[bits.length - 1]] = clone(value);
|
|
}
|
|
|
|
describe("v1/v6 branch routing through HTTP", () => {
|
|
let app: INestApplication, jwt: JwtService;
|
|
let blame: any, claims: any[], signatures: any[], branches: any[];
|
|
let userService: any, claimService: any, expertService: any;
|
|
const files: string[] = [];
|
|
const originalSecret = process.env.JWT_SECRET;
|
|
const logger = {
|
|
log: jest.fn(),
|
|
error: jest.fn(),
|
|
warn: jest.fn(),
|
|
debug: jest.fn(),
|
|
};
|
|
|
|
const loadBlame = async () => ({
|
|
...clone(blame),
|
|
save: async function () {
|
|
const { save, ...plain } = this;
|
|
blame = clone(plain);
|
|
},
|
|
});
|
|
const claimRepo = {
|
|
findOne: jest.fn(async (filter) =>
|
|
clone(
|
|
claims.find(
|
|
(c) => String(c.blameRequestId) === String(filter.blameRequestId),
|
|
) ?? null,
|
|
),
|
|
),
|
|
findById: jest.fn(async (id) =>
|
|
clone(claims.find((c) => c._id === String(id)) ?? null),
|
|
),
|
|
create: jest.fn(async (body) => {
|
|
const claim = clone({ _id: new Types.ObjectId(), ...body });
|
|
claims.push(claim);
|
|
return clone(claim);
|
|
}),
|
|
};
|
|
|
|
beforeAll(async () => {
|
|
process.env.JWT_SECRET = "branch-flow-integration-test-only";
|
|
const blameRepo = {
|
|
findById: jest.fn(loadBlame),
|
|
findByIdAndUpdate: jest.fn(async (_id, update) => {
|
|
for (const [key, value] of Object.entries(update.$set ?? {}))
|
|
setPath(blame, key, value);
|
|
for (const [key, value] of Object.entries(update.$push ?? {})) {
|
|
const old =
|
|
key.split(".").reduce((row, bit) => row?.[bit], blame) ?? [];
|
|
setPath(blame, key, [...old, value]);
|
|
}
|
|
return loadBlame();
|
|
}),
|
|
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(
|
|
branches.filter(
|
|
(b) => b.clientKey === payerId && b.isActive === filter.isActive,
|
|
),
|
|
),
|
|
findById: async (id) => clone(branches.find((b) => b._id === id) ?? null),
|
|
} as any);
|
|
const users = { findAllByPhone: async () => [] };
|
|
userService = Object.create(RequestManagementService.prototype);
|
|
Object.assign(userService, {
|
|
blameRequestDbService: blameRepo,
|
|
claimCaseDbService: claimRepo,
|
|
userDbService: users,
|
|
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);
|
|
return sign;
|
|
},
|
|
},
|
|
smsOrchestrationService: {
|
|
buildBlamePartyLink: (id, role, flow) =>
|
|
`https://test.invalid/${flow}/${role}?token=${id}`,
|
|
sendThirdPartyDamagedPartyClaimLinkNotice: async () => true,
|
|
},
|
|
});
|
|
claimService = Object.create(ClaimRequestManagementService.prototype);
|
|
Object.assign(claimService, {
|
|
blameRequestDbService: blameRepo,
|
|
claimCaseDbService: claimRepo,
|
|
userDbService: users,
|
|
userClaimBranchService: routing,
|
|
logger,
|
|
generateUniqueClaimNumber: async () => "TEST-CLAIM",
|
|
autoSubmitToFanavaranV2OnClaimCreated: jest.fn(async () => ({
|
|
attempted: false,
|
|
submitted: false,
|
|
})),
|
|
withFanavaranAutoSubmitMessage: (message) => message,
|
|
});
|
|
expertService = Object.create(ExpertClaimService.prototype);
|
|
Object.assign(expertService, {
|
|
blameRequestDbService: blameRepo,
|
|
damageExpertDbService: {
|
|
findById: async (id) => ({
|
|
branchId: id === ids.expert ? ids.branch : ids.otherBranch,
|
|
}),
|
|
},
|
|
});
|
|
const module = await Test.createTestingModule({
|
|
imports: [JwtModule.register({})],
|
|
controllers: [
|
|
RequestManagementV2Controller,
|
|
ClaimRequestManagementV2Controller,
|
|
],
|
|
providers: [
|
|
GlobalGuard,
|
|
RolesGuard,
|
|
{ provide: RequestManagementService, useValue: userService },
|
|
{ provide: ClaimRequestManagementService, useValue: claimService },
|
|
{
|
|
provide: MediaPolicyService,
|
|
useValue: {
|
|
assertForBlame: async (file) => {
|
|
if (file?.path) files.push(file.path);
|
|
},
|
|
},
|
|
},
|
|
],
|
|
}).compile();
|
|
app = module.createNestApplication({ logger: false });
|
|
app.useGlobalFilters(new PersianErrorFilter(app.get(HttpAdapterHost)));
|
|
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 () => {
|
|
await app?.close();
|
|
await Promise.all(files.map((file) => unlink(file).catch(() => {})));
|
|
if (originalSecret === undefined) delete process.env.JWT_SECRET;
|
|
else process.env.JWT_SECRET = originalSecret;
|
|
});
|
|
function fixture(flow: string, type: string, guilty: string) {
|
|
claims = [];
|
|
signatures = [];
|
|
branches = [
|
|
{
|
|
_id: ids.branch,
|
|
clientKey: ids.payer,
|
|
isActive: true,
|
|
name: "مرکزی",
|
|
city: "تهران",
|
|
state: "تهران",
|
|
code: "100",
|
|
address: "نشانی شعبه مرکزی",
|
|
},
|
|
{
|
|
_id: ids.otherBranch,
|
|
clientKey: ids.payer,
|
|
isActive: true,
|
|
name: "دوم",
|
|
city: "اصفهان",
|
|
state: "اصفهان",
|
|
code: "200",
|
|
address: "نشانی شعبه دوم",
|
|
},
|
|
{
|
|
_id: ids.foreignBranch,
|
|
clientKey: ids.otherInsurer,
|
|
isActive: true,
|
|
name: "شرکت دیگر",
|
|
city: "تهران",
|
|
state: "تهران",
|
|
},
|
|
{
|
|
_id: ids.inactiveBranch,
|
|
clientKey: ids.payer,
|
|
isActive: false,
|
|
name: "غیرفعال",
|
|
city: "تهران",
|
|
state: "تهران",
|
|
},
|
|
];
|
|
blame = {
|
|
_id: String(new Types.ObjectId()),
|
|
type,
|
|
publicId: "TEST-BLAME",
|
|
requestNo: "TEST-BLAME",
|
|
status: "WAITING_FOR_SIGNATURES",
|
|
blameStatus: "AGREED",
|
|
callCenterInitiated: flow === "v6",
|
|
workflow: {
|
|
currentStep: "WAITING_FOR_SIGNATURES",
|
|
completedSteps: ["FIRST_INITIAL_FORM"],
|
|
},
|
|
history: [],
|
|
...(type === "THIRD_PARTY"
|
|
? { expert: { decision: { guiltyPartyId: guilty } } }
|
|
: {}),
|
|
parties: [
|
|
{
|
|
role: "FIRST",
|
|
person: {
|
|
userId: ids.first,
|
|
phoneNumber: "09120000001",
|
|
clientId:
|
|
type === "CAR_BODY" || guilty === ids.first
|
|
? ids.payer
|
|
: ids.otherInsurer,
|
|
},
|
|
},
|
|
...(type === "CAR_BODY"
|
|
? []
|
|
: [
|
|
{
|
|
role: "SECOND",
|
|
person: {
|
|
userId: ids.second,
|
|
phoneNumber: "09120000002",
|
|
clientId:
|
|
guilty === ids.second ? ids.payer : ids.otherInsurer,
|
|
},
|
|
},
|
|
]),
|
|
],
|
|
};
|
|
claimRepo.create.mockClear();
|
|
claimService.autoSubmitToFanavaranV2OnClaimCreated.mockClear();
|
|
}
|
|
const auth = (id: string, role = "user") =>
|
|
"Bearer " +
|
|
jwt.sign(
|
|
{ sub: id, role },
|
|
{ secret: process.env.JWT_SECRET, expiresIn: "5m" },
|
|
);
|
|
const url = () => `/v2/blame-request-management/${blame._id}`;
|
|
const sign = (user: string, branch?: string, accept = true) => {
|
|
let req = request(app.getHttpServer())
|
|
.put(`/v2/blame-request-management/sign/${blame._id}`)
|
|
.set("Authorization", auth(user))
|
|
.field("isAccept", String(accept));
|
|
if (branch) req = req.field("branchId", branch);
|
|
return req.attach("sign", png, {
|
|
filename: "branch-http-test.png",
|
|
contentType: "image/png",
|
|
});
|
|
};
|
|
const create = (user: string) =>
|
|
request(app.getHttpServer())
|
|
.post(`/v2/claim-request-management/create-from-blame/${blame._id}`)
|
|
.set("Authorization", auth(user));
|
|
const scenarios = [
|
|
["v1", "CAR_BODY", ids.first, "damaged-first"],
|
|
["v6", "CAR_BODY", ids.first, "damaged-first"],
|
|
...["v1", "v6"].flatMap((flow) =>
|
|
(flow === "v1" ? [ids.first, ids.second] : [ids.first]).flatMap(
|
|
(guilty) =>
|
|
["damaged-first", "guilty-first"].map((order) => [
|
|
flow,
|
|
"THIRD_PARTY",
|
|
guilty,
|
|
order,
|
|
]),
|
|
),
|
|
),
|
|
];
|
|
it.each(scenarios)(
|
|
"%s %s (guilty=%s, %s): choose → sign → create → branch-scoped experts",
|
|
async (flow, type, guilty, order) => {
|
|
fixture(flow, type, guilty);
|
|
const damaged =
|
|
type === "CAR_BODY" || guilty === ids.second ? ids.first : ids.second;
|
|
const options = await request(app.getHttpServer())
|
|
.get(url() + "/claim-branches")
|
|
.set("Authorization", auth(damaged))
|
|
.expect(200);
|
|
expect(options.body.required).toBe(true);
|
|
expect(options.body.branches.map((b) => b.id)).toEqual(
|
|
expect.arrayContaining([ids.branch, ids.otherBranch]),
|
|
);
|
|
expect(options.body.branches).toHaveLength(2);
|
|
await sign(damaged).expect(400);
|
|
expect(signatures).toHaveLength(0);
|
|
await sign(damaged, ids.foreignBranch).expect(400);
|
|
expect(signatures).toHaveLength(0);
|
|
await sign(damaged, ids.inactiveBranch).expect(400);
|
|
expect(signatures).toHaveLength(0);
|
|
if (type === "THIRD_PARTY") {
|
|
const culpritOptions = await request(app.getHttpServer())
|
|
.get(url() + "/claim-branches")
|
|
.set("Authorization", auth(guilty))
|
|
.expect(200);
|
|
expect(culpritOptions.body.required).toBe(false);
|
|
expect(culpritOptions.body.branches).toHaveLength(0);
|
|
await request(app.getHttpServer())
|
|
.put(url() + "/claim-branch")
|
|
.set("Authorization", auth(guilty))
|
|
.send({ branchId: ids.branch })
|
|
.expect(403);
|
|
if (order === "guilty-first") await sign(guilty).expect(200);
|
|
}
|
|
await sign(damaged, ids.branch).expect(200);
|
|
if (type === "THIRD_PARTY" && order === "damaged-first") {
|
|
await create(damaged).expect(400);
|
|
expect(claims).toHaveLength(0);
|
|
await sign(guilty).expect(200);
|
|
}
|
|
expect(blame.status).toBe("COMPLETED");
|
|
expect(blame.branchId).toBe(ids.branch);
|
|
const view = await request(app.getHttpServer())
|
|
.get(url())
|
|
.set("Authorization", auth(damaged))
|
|
.expect(200);
|
|
expect(view.body.nextAction).toBe("CREATE_CLAIM");
|
|
if (type === "THIRD_PARTY") await create(guilty).expect(403);
|
|
const created = await create(damaged).expect(201);
|
|
expect(created.body.claimRequestId).toBe(claims[0]._id);
|
|
expect(claims[0]).toMatchObject({
|
|
branchId: ids.branch,
|
|
owner: { clientId: ids.payer, userId: damaged },
|
|
});
|
|
const claim = claims[0],
|
|
own = { sub: ids.expert, clientKey: ids.payer, role: "damage_expert" },
|
|
other = { ...own, sub: ids.outsider };
|
|
await expect(
|
|
expertService.assertExpertActorOnClaim(claim, own),
|
|
).resolves.toBeUndefined();
|
|
await expect(
|
|
expertService.assertExpertActorOnClaim(claim, other),
|
|
).rejects.toThrow();
|
|
await expect(
|
|
expertService.filterDamageExpertClaimsByBranch([claim], own),
|
|
).resolves.toHaveLength(1);
|
|
await expect(
|
|
expertService.filterDamageExpertClaimsByBranch([claim], other),
|
|
).resolves.toHaveLength(0);
|
|
await expect(
|
|
expertService.assertExpertActorOnClaim(claim, {
|
|
...own,
|
|
clientKey: ids.otherInsurer,
|
|
}),
|
|
).rejects.toThrow();
|
|
await request(app.getHttpServer())
|
|
.put(url() + "/claim-branch")
|
|
.set("Authorization", auth(damaged))
|
|
.send({ branchId: ids.otherBranch })
|
|
.expect(409);
|
|
expect(claims[0].branchId).toBe(ids.branch);
|
|
await create(damaged).expect(409);
|
|
expect(claims).toHaveLength(1);
|
|
},
|
|
);
|
|
|
|
it.each(
|
|
["v1", "v6"].flatMap((flow) =>
|
|
["CAR_BODY", "THIRD_PARTY"].map((type) => [flow, type]),
|
|
),
|
|
)(
|
|
"%s %s: already-signed case must choose an active branch before direct claim creation",
|
|
async (flow, type) => {
|
|
fixture(flow, type, ids.first);
|
|
blame.status = "COMPLETED";
|
|
const damaged = type === "CAR_BODY" ? ids.first : ids.second;
|
|
for (const party of blame.parties)
|
|
party.confirmation = {
|
|
accepted: true,
|
|
signature: { fileId: "historic-sign" },
|
|
};
|
|
await create(damaged).expect(400);
|
|
expect(claims).toHaveLength(0);
|
|
await request(app.getHttpServer())
|
|
.put(url() + "/claim-branch")
|
|
.set("Authorization", auth(damaged))
|
|
.send({ branchId: ids.branch })
|
|
.expect(200);
|
|
branches.find((b) => b._id === ids.branch).isActive = false;
|
|
await create(damaged).expect(400);
|
|
expect(claims).toHaveLength(0);
|
|
await request(app.getHttpServer())
|
|
.put(url() + "/claim-branch")
|
|
.set("Authorization", auth(damaged))
|
|
.send({ branchId: ids.otherBranch })
|
|
.expect(200);
|
|
await create(damaged).expect(201);
|
|
expect(claims[0].branchId).toBe(ids.otherBranch);
|
|
},
|
|
);
|
|
it("authentication, role and participant boundaries apply to branch endpoints", async () => {
|
|
fixture("v1", "CAR_BODY", ids.first);
|
|
await request(app.getHttpServer())
|
|
.get(url() + "/claim-branches")
|
|
.expect(401);
|
|
await request(app.getHttpServer())
|
|
.get(url() + "/claim-branches")
|
|
.set("Authorization", auth(ids.outsider))
|
|
.expect(403);
|
|
await request(app.getHttpServer())
|
|
.get(url() + "/claim-branches")
|
|
.set("Authorization", auth(ids.first, "field_expert"))
|
|
.expect(403);
|
|
expect(signatures).toHaveLength(0);
|
|
expect(claims).toHaveLength(0);
|
|
});
|
|
it("rejection needs no branch and does not permit claim creation", async () => {
|
|
fixture("v6", "CAR_BODY", ids.first);
|
|
await sign(ids.first, undefined, false).expect(200);
|
|
expect(blame.status).toBe("STOPPED");
|
|
await create(ids.first).expect(400);
|
|
expect(claims).toHaveLength(0);
|
|
});
|
|
it("an expert-created LINK case retains its originating branch without user selection", async () => {
|
|
fixture("v1", "CAR_BODY", ids.first);
|
|
blame.expertInitiated = true;
|
|
blame.initiatedByFieldExpertId = ids.expert;
|
|
blame.creationMethod = "LINK";
|
|
blame.branchId = ids.otherBranch;
|
|
const options = await request(app.getHttpServer())
|
|
.get(url() + "/claim-branches")
|
|
.set("Authorization", auth(ids.first))
|
|
.expect(200);
|
|
expect(options.body.required).toBe(false);
|
|
expect(options.body.branches).toHaveLength(0);
|
|
await sign(ids.first).expect(200);
|
|
await create(ids.first).expect(201);
|
|
expect(claims[0].branchId).toBe(ids.otherBranch);
|
|
});
|
|
it("no active branches means no signature acceptance or new claim", async () => {
|
|
fixture("v6", "CAR_BODY", ids.first);
|
|
for (const branch of branches) branch.isActive = false;
|
|
const options = await request(app.getHttpServer())
|
|
.get(url() + "/claim-branches")
|
|
.set("Authorization", auth(ids.first))
|
|
.expect(200);
|
|
expect(options.body.required).toBe(true);
|
|
expect(options.body.branches).toHaveLength(0);
|
|
await sign(ids.first, ids.branch).expect(400);
|
|
expect(signatures).toHaveLength(0);
|
|
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,
|
|
);
|
|
|
|
});
|