forked from Yara724/api
fix(claims): validate invoice decisions before saving and explain resend limits
This commit is contained in:
@@ -0,0 +1,488 @@
|
||||
/** HTTP regression suite from expert assessment through owner signing/uploads and invoice review.
|
||||
* Real controllers, guards, validation pipes and workflow services; in-memory persistence and no external delivery.
|
||||
*/
|
||||
import "reflect-metadata";
|
||||
import { Test } from "@nestjs/testing";
|
||||
import { JwtModule, JwtService } from "@nestjs/jwt";
|
||||
import { INestApplication } from "@nestjs/common";
|
||||
import { HttpAdapterHost } from "@nestjs/core";
|
||||
import * as request from "supertest";
|
||||
import { mkdir, unlink } from "node:fs/promises";
|
||||
import { Types } from "mongoose";
|
||||
import { ExpertClaimV2Controller } from "src/expert-claim/expert-claim.v2.controller";
|
||||
import { ExpertClaimService } from "src/expert-claim/expert-claim.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 { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
|
||||
import { MediaPolicyService } from "src/media-policy/media-policy.service";
|
||||
import { AiService } from "src/ai/ai.service";
|
||||
import { ActorAuthService } from "src/auth/auth-services/actor.auth.service";
|
||||
import { GlobalGuard } from "src/auth/guards/global.guard";
|
||||
import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard";
|
||||
import { RolesGuard } from "src/auth/guards/role.guard";
|
||||
import { PersianErrorFilter } from "src/common/errors/persian-error.filter";
|
||||
|
||||
const id = "650000000000000000000001",
|
||||
actorId = "650000000000000000000002",
|
||||
ownerId = "650000000000000000000003",
|
||||
tenant = "650000000000000000000004";
|
||||
const clone = (v: any) => (v == null ? v : JSON.parse(JSON.stringify(v)));
|
||||
const png = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jTncAAAAASUVORK5CYII=",
|
||||
"base64",
|
||||
);
|
||||
function get(obj: any, path: string) {
|
||||
return path.split(".").reduce((o, k) => o?.[k], obj);
|
||||
}
|
||||
function set(obj: any, path: string, value: any) {
|
||||
const keys = path.split(".");
|
||||
const last = keys.pop();
|
||||
const parent = keys.reduce(
|
||||
(o, k) => (o[k] ??= /^\d+$/.test(k) ? [] : {}),
|
||||
obj,
|
||||
);
|
||||
parent[last] = clone(value);
|
||||
}
|
||||
function unset(obj: any, path: string) {
|
||||
const keys = path.split(".");
|
||||
const last = keys.pop();
|
||||
const parent = keys.reduce((o, k) => o?.[k], obj);
|
||||
if (parent) delete parent[last];
|
||||
}
|
||||
|
||||
describe("claim resend and invoice lifecycle through HTTP", () => {
|
||||
let app: INestApplication,
|
||||
jwt: JwtService,
|
||||
claim: any,
|
||||
blame: any,
|
||||
expert: any,
|
||||
owner: any;
|
||||
let forceStale = false;
|
||||
const writes: any[] = [];
|
||||
const files: string[] = [];
|
||||
const priorSecret = process.env.JWT_SECRET,
|
||||
priorCap = process.env.CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED;
|
||||
const repo = {
|
||||
findById: jest.fn(async () => clone(claim)),
|
||||
findByIdAndUpdate: jest.fn(async (_id, update) => apply(update)),
|
||||
findOneAndUpdate: jest.fn(async (filter, update) => {
|
||||
if (forceStale) {
|
||||
forceStale = false;
|
||||
return null;
|
||||
}
|
||||
for (const [key, value] of Object.entries(filter)) {
|
||||
if (key.endsWith(".partId")) continue;
|
||||
const actual = get(claim, key);
|
||||
if (
|
||||
value === null
|
||||
? actual != null
|
||||
: JSON.stringify(actual) !== JSON.stringify(clone(value))
|
||||
)
|
||||
return null;
|
||||
}
|
||||
let normalized = clone(update);
|
||||
if (Object.keys(filter).some((k) => k.endsWith(".partId"))) {
|
||||
const key = Object.keys(filter).find((k) => k.endsWith(".partId"));
|
||||
const path = key.slice(0, -7);
|
||||
const index = get(claim, path).findIndex(
|
||||
(p) => String(p.partId) === String(filter[key]),
|
||||
);
|
||||
normalized.$set = Object.fromEntries(
|
||||
Object.entries(normalized.$set).map(([k, v]) => [
|
||||
k.replace(".$.", `.${index}.`),
|
||||
v,
|
||||
]),
|
||||
);
|
||||
}
|
||||
return apply(normalized);
|
||||
}),
|
||||
};
|
||||
function apply(update: any) {
|
||||
writes.push(clone(update));
|
||||
for (const [key, value] of Object.entries({
|
||||
...Object.fromEntries(
|
||||
Object.entries(update).filter(([k]) => !k.startsWith("$")),
|
||||
),
|
||||
...update.$set,
|
||||
}))
|
||||
set(claim, key, value);
|
||||
for (const key of Object.keys(update.$unset ?? {})) unset(claim, key);
|
||||
for (const [key, value] of Object.entries(update.$push ?? {})) {
|
||||
let list = get(claim, key);
|
||||
if (!list) {
|
||||
set(claim, key, []);
|
||||
list = get(claim, key);
|
||||
}
|
||||
list.push(clone(value));
|
||||
}
|
||||
return clone(claim);
|
||||
}
|
||||
const actorToken = (flow = "v1") =>
|
||||
jwt.sign(
|
||||
{
|
||||
sub: actorId,
|
||||
role: ["v1", "v6"].includes(flow)
|
||||
? "damage_expert"
|
||||
: ["v2", "v3"].includes(flow)
|
||||
? "field_expert"
|
||||
: "file_reviewer",
|
||||
clientKey: tenant,
|
||||
fullName: "کارشناس آزمایشی",
|
||||
},
|
||||
{ secret: process.env.JWT_SECRET },
|
||||
);
|
||||
const userToken = () =>
|
||||
jwt.sign(
|
||||
{ sub: ownerId, role: "user", fullName: "مالک آزمایشی" },
|
||||
{ secret: process.env.JWT_SECRET },
|
||||
);
|
||||
const act = (method: "put" | "patch", path: string, flow = "v1") =>
|
||||
request(app.getHttpServer())
|
||||
[method](path)
|
||||
.set("Authorization", `Bearer ${actorToken(flow)}`);
|
||||
const user = (method: "put" | "patch", path: string) =>
|
||||
request(app.getHttpServer())
|
||||
[method](path)
|
||||
.set("Authorization", `Bearer ${userToken()}`);
|
||||
beforeAll(async () => {
|
||||
process.env.JWT_SECRET = "invoice-regression-test-secret";
|
||||
delete process.env.CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED;
|
||||
await mkdir("files/claim-sign", { recursive: true });
|
||||
await mkdir("files/claim-factors", { recursive: true });
|
||||
expert = Object.create(ExpertClaimService.prototype);
|
||||
owner = Object.create(ClaimRequestManagementService.prototype);
|
||||
Object.assign(expert, {
|
||||
claimCaseDbService: repo,
|
||||
blameRequestDbService: { findById: async () => clone(blame) },
|
||||
assertExpertActorOnClaim: jest.fn(async () => {}),
|
||||
snapshotDamageExpert: jest.fn(async () => undefined),
|
||||
recordClaimExpertActivity: jest.fn(async () => {}),
|
||||
resolveClaimOwnerPhone: jest.fn(async () => null),
|
||||
logger: { warn: jest.fn(), error: jest.fn(), log: jest.fn() },
|
||||
loadBlameForClaim: async () => clone(blame),
|
||||
});
|
||||
Object.assign(owner, {
|
||||
claimCaseDbService: repo,
|
||||
resolveClaimEffectiveUserId: async () => ownerId,
|
||||
assertEffectiveUserIsDamagedPartyOnClaim: async () => {},
|
||||
autoSubmitFanavaranExpertiseOnExpertReply: async () => ({submitted:false,attempted:false}),
|
||||
autoSubmitToFanavaranV2OnClaimCompleted: async () => ({submitted:false,attempted:false}),
|
||||
claimSignDbService: {
|
||||
create: async () => ({ _id: new Types.ObjectId() }),
|
||||
},
|
||||
claimFactorsImageDbService: {
|
||||
create: async () => ({ _id: new Types.ObjectId() }),
|
||||
},
|
||||
logger: { warn: jest.fn(), error: jest.fn(), log: jest.fn() },
|
||||
});
|
||||
const module = await Test.createTestingModule({
|
||||
imports: [JwtModule.register({})],
|
||||
controllers: [
|
||||
ExpertClaimV2Controller,
|
||||
ClaimRequestManagementV2Controller,
|
||||
],
|
||||
providers: [
|
||||
LocalActorAuthGuard,
|
||||
GlobalGuard,
|
||||
RolesGuard,
|
||||
{
|
||||
provide: ActorAuthService,
|
||||
useValue: { assertActorActive: async () => {} },
|
||||
},
|
||||
{ provide: ExpertClaimService, useValue: expert },
|
||||
{ provide: ClaimRequestManagementService, useValue: owner },
|
||||
{ provide: ClaimCaseDbService, useValue: repo },
|
||||
{ provide: AiService, useValue: {} },
|
||||
{
|
||||
provide: MediaPolicyService,
|
||||
useValue: {
|
||||
assertForClaim: 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 (priorSecret === undefined) delete process.env.JWT_SECRET;
|
||||
else process.env.JWT_SECRET = priorSecret;
|
||||
if (priorCap === undefined)
|
||||
delete process.env.CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED;
|
||||
else process.env.CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED = priorCap;
|
||||
});
|
||||
function fixture(flow = "v1", type = "THIRD_PARTY") {
|
||||
writes.length = 0;
|
||||
forceStale = false;
|
||||
blame = {
|
||||
type,
|
||||
flowVersion: flow,
|
||||
expertInitiated: ["v2", "v3"].includes(flow),
|
||||
registrarInitiated: ["v4", "v5"].includes(flow),
|
||||
callCenterInitiated: flow === "v6",
|
||||
creationMethod:
|
||||
flow === "v1" ? "NORMAL" : flow === "v6" ? "LINK" : "IN_PERSON",
|
||||
};
|
||||
claim = {
|
||||
_id: id,
|
||||
publicId: "QA-1",
|
||||
blameRequestId: "650000000000000000000005",
|
||||
status: "EXPERT_REVIEWING",
|
||||
owner: { userId: ownerId, clientId: tenant },
|
||||
requiresFileMakerApproval: flow === "v5",
|
||||
workflow: {
|
||||
locked: true,
|
||||
lockedBy: { actorId },
|
||||
currentStep: "EXPERT_DAMAGE_ASSESSMENT",
|
||||
},
|
||||
vehicle: { carType: "sedan" },
|
||||
evaluation: {},
|
||||
damage: {
|
||||
selectedParts: [30, 31, 15].map((part) => ({
|
||||
id: part,
|
||||
name: String(part),
|
||||
side: "",
|
||||
label_fa: String(part),
|
||||
catalogKey: String(part),
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
function quote(partId: number, factorNeeded: boolean) {
|
||||
return {
|
||||
partId,
|
||||
typeOfDamage: "تعویض",
|
||||
...(factorNeeded ? {} : { price: "1000000" }),
|
||||
salary: "1000000",
|
||||
totalPayment: factorNeeded ? "1000000" : "2000000",
|
||||
factorNeeded,
|
||||
daghi: { option: "فاقد ارزش" },
|
||||
};
|
||||
}
|
||||
function readyForReview() {
|
||||
fixture();
|
||||
claim.status = "EXPERT_VALIDATING_REPAIR_FACTORS";
|
||||
claim.claimStatus = "UNDER_REVIEW";
|
||||
claim.workflow.currentStep = "EXPERT_COST_EVALUATION";
|
||||
claim.evaluation.damageExpertReply = {
|
||||
submittedAt: new Date().toISOString(),
|
||||
parts: [
|
||||
{
|
||||
...quote(30, true),
|
||||
factorLink: "test-factor",
|
||||
factorStatus: "PENDING",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
for (const flow of ["v1", "v2", "v3", "v4", "v5", "v6"])
|
||||
for (const type of ["THIRD_PARTY", "CAR_BODY"])
|
||||
for (const shape of ["mixed", "all-factor", "priced"]) {
|
||||
it(`${flow} ${type} ${shape}: assessment → signature if needed → uploads → per-invoice review`, async () => {
|
||||
fixture(flow, type);
|
||||
const parts = [
|
||||
quote(30, shape !== "priced"),
|
||||
quote(31, shape === "all-factor"),
|
||||
];
|
||||
const reply = await act(
|
||||
"put",
|
||||
`/v2/expert-claim/reply/submit/${id}`,
|
||||
flow,
|
||||
).send({
|
||||
parts,
|
||||
...(type === "CAR_BODY" ? { carPrice: "1000000000" } : {}),
|
||||
});
|
||||
expect(reply.status).toBe(200);
|
||||
if (shape === "priced") {
|
||||
if (claim.status === "INSURER_REVIEW_AWAITING_OWNER_SIGN") {
|
||||
const signature = await user("put", `/v2/claim-request-management/request/${id}/owner-insurer-approval/sign`)
|
||||
.field("agree", "true").attach("sign", png, {filename:"signature.png",contentType:"image/png"});
|
||||
expect(signature.status).toBe(200);
|
||||
}
|
||||
expect(claim.status).toBe(flow === "v5" ? "WAITING_FOR_FILE_MAKER_APPROVAL" : "COMPLETED");
|
||||
return;
|
||||
}
|
||||
const upload = (part: number) =>
|
||||
user(
|
||||
"patch",
|
||||
`/v2/claim-request-management/request/reply/${id}/${part}/upload-factor`,
|
||||
).attach("file", png, {
|
||||
filename: "factor.png",
|
||||
contentType: "image/png",
|
||||
});
|
||||
if (shape === "mixed") {
|
||||
expect((await upload(30)).status).toBe(400);
|
||||
const sign = await user(
|
||||
"put",
|
||||
`/v2/claim-request-management/request/${id}/owner-insurer-approval/sign`,
|
||||
)
|
||||
.field("agree", "true")
|
||||
.attach("sign", png, {
|
||||
filename: "signature.png",
|
||||
contentType: "image/png",
|
||||
});
|
||||
expect(sign.status).toBe(200);
|
||||
expect(sign.body.currentStep).toBe("OWNER_UPLOAD_FACTOR_DOCUMENTS");
|
||||
} else
|
||||
expect(claim.workflow.currentStep).toBe(
|
||||
"OWNER_UPLOAD_FACTOR_DOCUMENTS",
|
||||
);
|
||||
expect((await upload(30)).status).toBe(200);
|
||||
expect((await upload(30)).status).toBe(409);
|
||||
if (shape === "all-factor")
|
||||
expect((await upload(31)).status).toBe(200);
|
||||
expect(claim.status).toBe("EXPERT_VALIDATING_REPAIR_FACTORS");
|
||||
for (const part of parts.filter((p) => p.factorNeeded)) {
|
||||
const result = await act(
|
||||
"patch",
|
||||
`/v2/expert-claim/validate-factors/${id}`,
|
||||
flow,
|
||||
).send({
|
||||
decisions: [
|
||||
{
|
||||
partId: part.partId,
|
||||
status: "APPROVED",
|
||||
totalPayment: "3000000",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(result.status).toBe(200);
|
||||
}
|
||||
expect(claim.status).toBe(
|
||||
flow === "v5" ? "WAITING_FOR_FILE_MAKER_APPROVAL" : "COMPLETED",
|
||||
);
|
||||
expect(
|
||||
claim.evaluation.damageExpertReply.parts
|
||||
.filter((p) => p.factorNeeded)
|
||||
.every((p) => p.factorStatus === "APPROVED"),
|
||||
).toBe(true);
|
||||
});
|
||||
}
|
||||
it("accepts the exact reported resend body on its first cycle and exposes the Persian rule on a second cycle", async () => {
|
||||
fixture();
|
||||
const body = {
|
||||
resendDescription: "gjjjjjjg",
|
||||
resendDocuments: [],
|
||||
resendCarParts: [
|
||||
{
|
||||
key: "چراغ عقب چپ",
|
||||
label_fa: "چراغ عقب چپ",
|
||||
label_en: "15",
|
||||
side: "",
|
||||
id: 15,
|
||||
captured: false,
|
||||
name: "15",
|
||||
},
|
||||
],
|
||||
};
|
||||
const first = await act("put", `/v2/expert-claim/reply/resend/${id}`).send(
|
||||
body,
|
||||
);
|
||||
expect(first.status).toBe(200);
|
||||
expect(claim.evaluation.damageExpertResend.resendCarParts[0].id).toBe(15);
|
||||
claim.status = "EXPERT_REVIEWING";
|
||||
claim.workflow.locked = true;
|
||||
claim.workflow.lockedBy = { actorId };
|
||||
claim.evaluation.damageExpertResend.fulfilledAt = new Date().toISOString();
|
||||
const before = clone(claim);
|
||||
const second = await act("put", `/v2/expert-claim/reply/resend/${id}`).send(
|
||||
body,
|
||||
);
|
||||
expect(second.status).toBe(422);
|
||||
expect(second.body.errorCode).toBe("DAMAGE_EXPERT_RESEND_LIMIT_EXCEEDED");
|
||||
expect(second.body.message).toContain("درخواست قبلی");
|
||||
expect(claim).toEqual(before);
|
||||
});
|
||||
it.each(
|
||||
[
|
||||
[],
|
||||
[{ partId: 30, status: "PENDING", totalPayment: "3000000" }],
|
||||
[{ partId: 30, status: "APPROVED", totalPayment: "factor" }],
|
||||
[{ partId: 30, status: "APPROVED" }],
|
||||
[{ partId: 30, status: "REJECTED", totalPayment: "3000000" }],
|
||||
[{ partId: 99, status: "APPROVED", totalPayment: "3000000" }],
|
||||
[
|
||||
{ partId: 30, status: "APPROVED", totalPayment: "3000000" },
|
||||
{
|
||||
partId: 30,
|
||||
status: "REJECTED",
|
||||
totalPayment: "3000000",
|
||||
rejectionReason: "خطا",
|
||||
},
|
||||
],
|
||||
].map((decisions) => [decisions]),
|
||||
)("invalid invoice decision makes no writes: %j", async (decisions) => {
|
||||
readyForReview();
|
||||
const before = clone(claim);
|
||||
const res = await act(
|
||||
"patch",
|
||||
`/v2/expert-claim/validate-factors/${id}`,
|
||||
).send({ decisions });
|
||||
expect(res.status).toBe(400);
|
||||
expect(claim).toEqual(before);
|
||||
expect(writes).toHaveLength(0);
|
||||
});
|
||||
it("a cap failure preserves pending invoice data and a corrected retry completes", async () => {
|
||||
readyForReview();
|
||||
blame.expertInitiated = false;
|
||||
blame.registrarInitiated = false;
|
||||
blame.creationMethod = "NORMAL";
|
||||
process.env.CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED = "true";
|
||||
const before = clone(claim);
|
||||
const res = await act(
|
||||
"patch",
|
||||
`/v2/expert-claim/validate-factors/${id}`,
|
||||
).send({
|
||||
decisions: [
|
||||
{ partId: 30, status: "APPROVED", totalPayment: "600000000" },
|
||||
],
|
||||
});
|
||||
expect(res.status).toBe(400);
|
||||
expect(claim).toEqual(before);
|
||||
expect(writes).toHaveLength(0);
|
||||
expect(
|
||||
(
|
||||
await act("patch", `/v2/expert-claim/validate-factors/${id}`).send({
|
||||
decisions: [
|
||||
{ partId: 30, status: "APPROVED", totalPayment: "3000000" },
|
||||
],
|
||||
})
|
||||
).status,
|
||||
).toBe(200);
|
||||
delete process.env.CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED;
|
||||
});
|
||||
it("rejecting an invoice with a corrected amount completes with its reason, and stale writes return 409", async () => {
|
||||
readyForReview();
|
||||
forceStale = true;
|
||||
const body = {
|
||||
decisions: [
|
||||
{
|
||||
partId: 30,
|
||||
status: "REJECTED",
|
||||
totalPayment: "۳٬۰۰۰٬۰۰۰",
|
||||
rejectionReason: "اصلاح مبلغ فاکتور",
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(
|
||||
(await act("patch", `/v2/expert-claim/validate-factors/${id}`).send(body))
|
||||
.status,
|
||||
).toBe(409);
|
||||
expect(writes).toHaveLength(0);
|
||||
expect(
|
||||
(await act("patch", `/v2/expert-claim/validate-factors/${id}`).send(body))
|
||||
.status,
|
||||
).toBe(200);
|
||||
expect(claim.evaluation.damageExpertReply.parts[0]).toMatchObject({
|
||||
factorStatus: "REJECTED",
|
||||
totalPayment: "3000000",
|
||||
rejectionReason: "اصلاح مبلغ فاکتور",
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user