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:
SepehrYahyaee
2026-11-14 12:24:14 +03:30
parent f021793b00
commit a15c54d017
28 changed files with 1403 additions and 42 deletions
@@ -79,6 +79,7 @@ function setup(type = Kind.CAR_BODY) {
for (const bit of bits.slice(0, -1)) obj = obj[bit] ??= {};
obj[bits[bits.length - 1]] = value;
};
api.userClaimBranchService = { validate: jest.fn().mockResolvedValue("650000000000000000000099") };
api.publicIdService = {
generateRequestPublicId: jest.fn().mockResolvedValue("V6-TEST"),
};
@@ -94,7 +94,7 @@ export class BlameRequest {
@Prop({ type: Types.ObjectId })
initiatedByFieldExpertId?: Types.ObjectId;
/** Branch snapshot of the expert/FileMaker who created this file. */
/** Routing branch: user selection in v1/v6, or originating expert/FileMaker in other flows. */
@Prop({ type: Types.ObjectId, index: true })
branchId?: Types.ObjectId;
@@ -18,19 +18,20 @@ import {
} from "./inquiry-participant-resolver";
describe("inquiry participant resolver", () => {
it("accepts a driver licence date within the ten-year window", () => {
expect(validateDriverLicenseDate("2016-09-26", "2026-09-26")).toBe(
"2016-09-26",
);
});
it.each(["2016-09-26", "2016-09-25", "1995-01-01", "1374/01/01", 13740101])(
"accepts a past driver licence date without a ten-year cutoff: %s",
(date) => {
expect(validateDriverLicenseDate(date, "2026-09-26")).toBe(String(date));
},
);
it("rejects future and older-than-ten-year driver licence dates", () => {
it("still rejects future and malformed driver licence dates", () => {
expect(() =>
validateDriverLicenseDate("2026-09-27", "2026-09-26"),
).toThrow("نمی‌تواند در آینده");
expect(() =>
validateDriverLicenseDate("2016-09-25", "2026-09-26"),
).toThrow("بیشتر از ۱۰ سال قبل");
validateDriverLicenseDate("invalid", "2026-09-26"),
).toThrow("نامعتبر است");
});
it("requires the date only for a licensed driver", () => {
@@ -267,20 +267,11 @@ export function validateDriverLicenseDate(
throw new BadRequestException("تاریخ صدور گواهینامه راننده نامعتبر است.");
}
const today = jalaliToGregorianDate(todayGregorian) ?? todayGregorian;
const todayDate = new Date(`${today}T00:00:00Z`);
const minimumDate = new Date(todayDate);
minimumDate.setUTCFullYear(minimumDate.getUTCFullYear() - 10);
const minimum = minimumDate.toISOString().slice(0, 10);
if (parsed > today) {
throw new BadRequestException(
"تاریخ صدور گواهینامه راننده نمی‌تواند در آینده باشد.",
);
}
if (parsed < minimum) {
throw new BadRequestException(
"تاریخ صدور گواهینامه راننده نباید بیشتر از ۱۰ سال قبل باشد.",
);
}
return raw;
}
@@ -1,3 +1,4 @@
import { UserClaimBranchService, userClaimBranchContext } from "src/client/user-claim-branch.service";
import {
BadRequestException,
ConflictException,
@@ -1144,6 +1145,7 @@ export class RequestManagementService {
private readonly fileMakerDbService: FileMakerDbService,
private readonly fileReviewerDbService: FileReviewerDbService,
private readonly lookupsService: LookupsService,
private readonly userClaimBranchService: UserClaimBranchService,
) {}
async assertFileReviewerBranchAccess(
@@ -4861,6 +4863,7 @@ export class RequestManagementService {
carBodyInsuranceDetail: plain.carBodyInsuranceDetail,
claimCreation,
userSide: viewerParty?.role ?? null,
claimBranch: userClaimBranchContext(plain, String(user?.sub ?? "")),
nextAction: resolveBlameUserNextAction(
plain.status,
viewerParty,
@@ -6341,6 +6344,41 @@ export class RequestManagementService {
};
}
/** Same access boundary as the user case detail; never accept an insurer id from the browser. */
async getUserClaimBranches(requestId: string, user: any) {
await this.getBlameRequestV2(requestId, user);
const req = await this.blameRequestDbService.findById(requestId);
if (!req) throw new NotFoundException("پرونده پیدا نشد.");
const context = userClaimBranchContext(req, String(user.sub));
if (!context.required) return { ...context, branches: [], locked: true };
const claim = await this.claimCaseDbService.findOne({ blameRequestId: req._id });
return {
...context,
branchId: claim?.branchId ? String(claim.branchId) : context.branchId,
locked: !!claim,
branches: await this.userClaimBranchService.options(req),
};
}
/** Also supports already-signed legacy cases, before their first claim is created. */
async selectUserClaimBranch(requestId: string, user: any, branchId: unknown) {
await this.getBlameRequestV2(requestId, user);
const req = await this.blameRequestDbService.findById(requestId);
if (!req) throw new NotFoundException("پرونده پیدا نشد.");
if (!userClaimBranchContext(req, String(user.sub)).required) {
throw new ForbiddenException("فقط طرف زیان‌دیده می‌تواند شعبه رسیدگی به خسارت را انتخاب کند.");
}
if (![CaseStatus.WAITING_FOR_SIGNATURES, CaseStatus.COMPLETED].includes(req.status)) {
throw new BadRequestException("انتخاب شعبه در مرحله امضا یا پیش از ثبت درخواست خسارت امکان‌پذیر است.");
}
if (await this.claimCaseDbService.findOne({ blameRequestId: req._id })) {
throw new ConflictException("درخواست خسارت ایجاد شده است و شعبه آن قابل تغییر نیست.");
}
const id = await this.userClaimBranchService.validate(req, branchId);
await this.blameRequestDbService.findByIdAndUpdate(requestId, { $set: { branchId: new Types.ObjectId(id) } });
return { branchId: id };
}
/**
* V2: User signs and accepts/rejects (expert decision for THIRD_PARTY, or final acknowledgment for CAR_BODY).
*/
@@ -6349,6 +6387,7 @@ export class RequestManagementService {
userId: string,
isAccept: boolean,
signFile: Express.Multer.File,
branchId?: string,
): Promise<UserSignatureResponseDto> {
if (!signFile) {
throw new BadRequestException("A signature file is required");
@@ -6393,6 +6432,17 @@ export class RequestManagementService {
throw new BadRequestException("You have already signed this decision");
}
const branchContext = userClaimBranchContext(request, userId);
let selectedBranchId: string | undefined;
if (branchId && !branchContext.required) {
throw new ForbiddenException("انتخاب شعبه فقط برای طرف زیان‌دیده در پرونده‌های کاربرمحور مجاز است.");
}
if (isAccept && branchContext.required) {
selectedBranchId = await this.userClaimBranchService.validate(
request, branchId ?? branchContext.branchId,
);
}
// Create signature document
const signDoc = await this.userSign.create({
fileName: signFile.filename,
@@ -6449,6 +6499,7 @@ export class RequestManagementService {
await this.blameRequestDbService.findByIdAndUpdate(requestId, {
$set: {
[`parties.${partyIndex}.confirmation`]: confirmationPayload,
...(selectedBranchId ? { branchId: new Types.ObjectId(selectedBranchId) } : {}),
},
});
@@ -349,6 +349,19 @@ export class RequestManagementV2Controller {
/**
* V2: User signs/accepts or rejects expert decision
*/
@Get(":requestId/claim-branches")
@ApiOperation({ summary: "Active paying-insurer branches for the damaged user (v1/v6)" })
getUserClaimBranches(@Param("requestId") id: string, @CurrentUser() user: any) {
return this.requestManagementService.getUserClaimBranches(id, user);
}
@Put(":requestId/claim-branch")
@ApiOperation({ summary: "Choose claim branch before a user-led claim is created" })
@ApiBody({ schema: { type: "object", required: ["branchId"], properties: { branchId: { type: "string" } } } })
selectUserClaimBranch(@Param("requestId") id: string, @CurrentUser() user: any, @Body("branchId") branchId: string) {
return this.requestManagementService.selectUserClaimBranch(id, user, branchId);
}
@Put("sign/:requestId")
@ApiParam({ name: "requestId", description: "Blame request ID" })
@ApiConsumes("multipart/form-data")
@@ -363,6 +376,7 @@ export class RequestManagementV2Controller {
format: "binary",
description: "Signature image file",
},
branchId: { type: "string", description: "Required when the damaged user accepts in v1/v6; active branch of the paying insurer" },
isAccept: {
type: "boolean",
description: "true to accept expert decision, false to reject",
@@ -389,6 +403,7 @@ export class RequestManagementV2Controller {
async userSignDecision(
@Param("requestId") requestId: string,
@Body("isAccept") isAccept: string | boolean,
@Body("branchId") branchId: string,
@CurrentUser() user: any,
@UploadedFile() sign: Express.Multer.File,
) {
@@ -403,6 +418,7 @@ export class RequestManagementV2Controller {
user.sub,
acceptDecision,
sign,
branchId,
);
}