add tests for v4/v5

This commit is contained in:
SepehrYahyaee
2026-10-05 16:40:54 +03:30
parent 2d532a7177
commit 5110721c62
2 changed files with 245 additions and 1 deletions
+3 -1
View File
@@ -10,6 +10,8 @@ For historical regular claims whose owner is the guilty party, mutation authoriz
The specialized expert/registrar creation and capture workflows retain their existing role and initiator checks, including the reorganized flows that create a claim before blame completion. The user creation rule is not imposed on those specialized endpoints.
For V4/V5 FileMaker files, the FileReviewer must retrieve the precreated claim with `GET /v4|v5/file-reviewer/blame-request-management/claim-id/:requestId`. This lookup verifies organization, branch/location, configured Fanavaran expertise code, sealed-file status, and reviewer assignment. `WAITING_FOR_FILE_REVIEWER` is a valid blame status during this handoff and part selection; blame becomes `COMPLETED` later in the capture workflow. The reviewer acts for the beneficiary through the specialized claim endpoints and must never use ordinary-user claim creation. Manually marking blame complete does not make the reviewer a user beneficiary.
The user UI stores one active identity. Successful OTP or expert login clears the previous party's token, active case IDs, per-case claim caches, Redux case state, and query data. A legacy browser containing both token keys must log in again. Creation requests are deduplicated per identity and blame case, and a rejected request cannot enable the claim-entry button or borrow an unrelated claim ID. Responses arriving after an account switch cannot overwrite the new account's active claim.
Regression coverage: `claim-beneficiary-access.spec.ts`, `request-management.user-progress.spec.ts`, and `ui-user/scripts/test-claim-session.cjs`. Run `npm test -- --runInBand` in `api` and `npm run test:ui` in each UI repository.
Regression coverage: `claim-beneficiary-access.spec.ts`, `request-management.user-progress.spec.ts`, `file-reviewer-claim-handoff.spec.ts`, and `ui-user/scripts/test-claim-session.cjs` / `test-claim-entry.cjs`. The handoff tests exercise both V4/V5 controllers, third-party/body files, linked claim lookup, part selection while blame is waiting, and lookup authorization failures. The entry tests execute the shared UI's effect with the actual FileReviewer API adapter, checking role/version routing, errors, and stale responses after account/case changes. Run `npm test -- --runInBand` in `api` and `npm run test:ui` in each UI repository.
@@ -0,0 +1,242 @@
import { Types } from "mongoose";
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
import { OtherCarPart } from "src/claim-request-management/dto/select-other-parts-v2.dto";
import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum";
import { CaseStatus } from "src/Types&Enums/blame-request-management/caseStatus.enum";
import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum";
import { ClaimWorkflowStep } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum";
import { RoleEnum } from "src/Types&Enums/role.enum";
import { CreationMethod } from "./entities/schema/request-management.schema";
import { FileReviewerBlameV4Controller } from "./file-reviewer-blame-v4.controller";
import { FileReviewerBlameV5Controller } from "./file-reviewer-blame-v5.controller";
import { RequestManagementService } from "./request-management.service";
function fixture(version = "v4", type = BlameRequestType.THIRD_PARTY) {
const makerId = new Types.ObjectId();
const reviewerId = new Types.ObjectId();
const clientId = new Types.ObjectId();
const firstId = new Types.ObjectId();
const secondId = new Types.ObjectId();
const reviewer = {
sub: String(reviewerId),
role: RoleEnum.FILE_REVIEWER,
clientKey: String(clientId),
};
const blame: any = {
_id: new Types.ObjectId(),
publicId: "BL-SEALED",
type,
status: CaseStatus.WAITING_FOR_FILE_REVIEWER,
isMadeByFileMaker: true,
requiresFileMakerApproval: version === "v5",
expertInitiated: true,
creationMethod: CreationMethod.IN_PERSON,
initiatedByFieldExpertId: makerId,
expert: {
decision: {
guiltyPartyId: firstId,
fields: { accidentWay: { id: "1", label: "تصادف" } },
},
},
parties: [
{
role: "FIRST",
person: { userId: firstId, clientId },
confirmation: { accepted: true, signature: { fileId: "first-sign" } },
},
...(type === BlameRequestType.CAR_BODY
? []
: [
{
role: "SECOND",
person: { userId: secondId },
confirmation: {
accepted: true,
signature: { fileId: "second-sign" },
},
},
]),
],
};
const beneficiary = type === BlameRequestType.CAR_BODY ? firstId : secondId;
const claim: any = {
_id: new Types.ObjectId(),
publicId: blame.publicId,
blameRequestId: blame._id,
initiatedByFieldExpertId: makerId,
owner: { userId: beneficiary, clientId },
damagedPartyUserId: beneficiary,
requiresFileMakerApproval: version === "v5",
status: ClaimCaseStatus.WAITING_FOR_FILE_REVIEWER,
workflow: {
currentStep: ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS,
completedSteps: [ClaimWorkflowStep.CLAIM_CREATED],
},
};
const blameDb = {
findById: jest.fn().mockResolvedValue(blame),
findOneAndUpdate: jest.fn().mockImplementation(async (_query, update) => {
Object.assign(blame, update.$set);
return blame;
}),
};
const claimDb = {
findOne: jest.fn().mockResolvedValue(claim),
findById: jest.fn().mockResolvedValue(claim),
create: jest.fn(),
findByIdAndUpdate: jest.fn().mockImplementation(async (_id, update) => {
for (const [key, value] of Object.entries(update.$set ?? update)) {
if (key.startsWith("$")) continue;
const keys = key.split(".");
const leaf = keys.pop()!;
const target = keys.reduce(
(parent, name) => (parent[name] ??= {}),
claim,
);
target[leaf] = value;
}
for (const [key, value] of Object.entries(update.$push ?? {})) {
const keys = key.split(".");
const leaf = keys.pop()!;
const target = keys.reduce((parent, name) => (parent[name] ??= {}), claim);
(target[leaf] ??= []).push(value);
}
return claim;
}),
};
const locations = {
assertMakerReviewerBranchCompatible: jest.fn().mockResolvedValue(undefined),
assertMakerReviewerLocationCompatible: jest
.fn()
.mockResolvedValue(undefined),
};
const requestService = Object.assign(
Object.create(RequestManagementService.prototype),
{
blameRequestDbService: blameDb,
claimCaseDbService: claimDb,
fileReviewerDbService: {
findById: jest
.fn()
.mockResolvedValue({
ThirdPartyExpertiseClaim: "101",
CarBodyExpertiseClaim: "102",
}),
},
fanavaranLocationService: locations,
},
);
const claimService = Object.assign(
Object.create(ClaimRequestManagementService.prototype),
{
blameRequestDbService: blameDb,
claimCaseDbService: claimDb,
userDbService: { findAllByPhone: jest.fn().mockResolvedValue([]) },
getLiveFanavaranCatalogItems: jest
.fn()
.mockResolvedValue([
{ id: 11, key: "front_bumper", side: "front", titleFa: "سپر جلو" },
]),
autoSubmitFanavaranDamageCaseOnOuterPartsSelected: jest
.fn()
.mockResolvedValue({ submitted: false }),
logger: { log: jest.fn(), error: jest.fn() },
},
);
const Controller =
version === "v5"
? FileReviewerBlameV5Controller
: FileReviewerBlameV4Controller;
const controller = new Controller(requestService, claimService, undefined);
return {
controller,
requestService,
claimService,
blame,
claim,
blameDb,
claimDb,
reviewer,
locations,
};
}
describe.each(["v4", "v5"])(
"%s sealed FileMaker → FileReviewer claim handoff",
(version) => {
it.each([BlameRequestType.THIRD_PARTY, BlameRequestType.CAR_BODY])(
"retrieves the precreated %s claim and selects parts while blame still awaits review",
async (type) => {
const f = fixture(version, type);
const linked = await f.controller.getLinkedClaimId(
String(f.blame._id),
f.reviewer,
);
expect(linked.claimRequestId).toBe(String(f.claim._id));
expect(String(f.blame.assignedFileReviewerId)).toBe(f.reviewer.sub);
expect(
f.locations.assertMakerReviewerBranchCompatible,
).toHaveBeenCalled();
expect(
f.locations.assertMakerReviewerLocationCompatible,
).toHaveBeenCalled();
const result = await f.controller.selectOuterParts(
linked.claimRequestId,
{ selectedPartIds: [11] },
f.reviewer,
);
expect(result.selectedPartIds).toEqual([11]);
expect(result.nextStep).toBe(ClaimWorkflowStep.CAPTURE_PART_DAMAGES);
await f.controller.selectOtherParts(
linked.claimRequestId,
{ otherParts: [OtherCarPart.ENGINE] },
f.reviewer,
);
expect(f.claim.workflow.currentStep).toBe(
ClaimWorkflowStep.CAPTURE_PART_DAMAGES,
);
expect(f.blame.status).toBe(CaseStatus.WAITING_FOR_FILE_REVIEWER);
expect(f.claim.requiresFileMakerApproval).toBe(version === "v5");
expect(f.claimDb.create).not.toHaveBeenCalled();
// Ordinary-user creation is still deliberately unavailable to the reviewer.
await expect(
f.claimService.createClaimFromBlameV2(
String(f.blame._id),
f.reviewer.sub,
),
).rejects.toThrow("Blame request must be completed");
f.blame.status = CaseStatus.COMPLETED;
await expect(
f.claimService.createClaimFromBlameV2(
String(f.blame._id),
f.reviewer.sub,
),
).rejects.toThrow("Only the damaged party can create a claim");
expect(f.claimDb.create).not.toHaveBeenCalled();
},
);
it.each(["tenant", "assignment", "unsealed", "branch"])(
"rejects an unauthorized %s lookup before returning a claim",
async (reason) => {
const f = fixture(version);
if (reason === "tenant")
f.reviewer.clientKey = String(new Types.ObjectId());
if (reason === "assignment")
f.blame.assignedFileReviewerId = new Types.ObjectId();
if (reason === "unsealed") f.blame.status = CaseStatus.OPEN;
if (reason === "branch")
f.locations.assertMakerReviewerBranchCompatible.mockRejectedValue(
new Error("Another branch"),
);
await expect(
f.controller.getLinkedClaimId(String(f.blame._id), f.reviewer),
).rejects.toThrow();
expect(f.claimDb.findOne).not.toHaveBeenCalled();
expect(f.blameDb.findOneAndUpdate).not.toHaveBeenCalled();
},
);
},
);