forked from Yara724/api
feat: route user claims by branch and align licence issue dates
Require the damaged party in user flows to select an active insurer branch and preserve branch access rules. Accept older licence issue dates, correct anniversary boundaries, and update Fanavaran audit documentation and regression coverage.
This commit is contained in:
@@ -0,0 +1,482 @@
|
||||
/** 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 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: {
|
||||
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)));
|
||||
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);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user