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
@@ -55,6 +55,7 @@ function serviceFor(blame: any): any {
findOne: jest.fn().mockResolvedValue(null),
create: jest.fn().mockResolvedValue({ _id: claimId }),
};
service.userClaimBranchService = { validate: jest.fn().mockResolvedValue("650000000000000000000099") };
service.userDbService = { findAllByPhone: jest.fn().mockResolvedValue([]) };
service.generateUniqueClaimNumber = jest.fn().mockResolvedValue("C100");
service.autoSubmitToFanavaranV2OnClaimCreated = jest
@@ -260,4 +261,18 @@ describe("claim beneficiary authorization across shared user flows", () => {
service.assertEffectiveUserIsDamagedPartyOnClaim(claim, effectiveId),
).resolves.toBeUndefined();
});
it("copies the validated branch into the claim and blocks creation when branch validation fails", async () => {
const blame = source();
blame.branchId = "650000000000000000000099";
const service = serviceFor(blame);
await service.createClaimFromBlameV2(blameId, secondId);
expect(service.userClaimBranchService.validate).toHaveBeenCalledWith(blame, blame.branchId);
expect(String(service.claimCaseDbService.create.mock.calls[0][0].branchId)).toBe(blame.branchId);
const blocked = serviceFor(source());
blocked.userClaimBranchService.validate.mockRejectedValue(new BadRequestException("شعبه را انتخاب کنید"));
await expect(blocked.createClaimFromBlameV2(blameId, secondId)).rejects.toBeInstanceOf(BadRequestException);
expect(blocked.claimCaseDbService.create).not.toHaveBeenCalled();
expect(blocked.autoSubmitToFanavaranV2OnClaimCreated).not.toHaveBeenCalled();
});
});
@@ -1,3 +1,4 @@
import { UserClaimBranchService, usesUserClaimBranch } from "src/client/user-claim-branch.service";
import {
hasReviewedTejaratNotifier,
isTejaratNotifierLookup,
@@ -505,6 +506,7 @@ export class ClaimRequestManagementService {
private readonly claimFactorsImageDbService: ClaimFactorsImageDbService,
private readonly branchDbService: BranchDbService,
private readonly userClaimBranchService: UserClaimBranchService,
private readonly claimRequiredDocumentDbService: ClaimRequiredDocumentDbService,
private readonly sandHubService: SandHubService,
@@ -8147,6 +8149,10 @@ export class ClaimRequestManagementService {
);
}
const selectedBranchId = usesUserClaimBranch(blameRequest)
? await this.userClaimBranchService.validate(blameRequest, (blameRequest as any).branchId?.toString())
: (blameRequest as any).branchId?.toString();
// 7. Generate claim number
const claimNo = await this.generateUniqueClaimNumber();
@@ -8163,6 +8169,7 @@ export class ClaimRequestManagementService {
publicId: blameRequest.publicId,
blameRequestId: new Types.ObjectId(blameRequestId),
blameRequestNo: blameRequest.requestNo,
...(selectedBranchId ? { branchId: new Types.ObjectId(selectedBranchId) } : {}),
status: ClaimCaseStatus.SELECTING_OUTER_PARTS,
claimStatus: ClaimStatus.PENDING,
inquiries: (blameRequest as any).inquiries ?? {},
@@ -304,7 +304,7 @@ export class ClaimCase {
@Prop({ type: Types.ObjectId, index: true })
initiatedByFieldExpertId?: Types.ObjectId;
/** Branch snapshot inherited from the originating expert-created blame. */
/** Routing branch inherited from the blame (user selection or expert-created branch). */
@Prop({ type: Types.ObjectId, index: true })
branchId?: Types.ObjectId;
@@ -10,7 +10,7 @@ function setup(accessories: unknown) {
"vehicle-hull-dmg-cost-kinds": [
{ Id: 8002, Caption: "مجموع لوازم", IsActive: 1 },
],
"car-components": [{ Id: 9 }, { Id: 13 }],
"car-components": [{ Id: 9 }, { Id: 13 }, { Id: 112 }],
})[name] ?? [],
);
service.fanavaranLookupService = {
@@ -34,6 +34,7 @@ function setup(accessories: unknown) {
priceDropTotal: 0,
priceDropCarPrice: null,
warnings: [],
infoWarnings: [],
});
return { service, build };
}
@@ -76,16 +77,17 @@ describe("hull expertise policy accessory mapping", () => {
AccessoryDesc: "کليه قطعات فابريک",
},
]);
const { payload, warnings } = await build();
const { payload, warnings, infoWarnings } = await build();
expect(
payload.DmgSections.map((row: any) => row.VehicleHullAccessoryId),
).toEqual([3061139, 3061139]);
expect(payload.DmgSections.map((row: any) => row.AccessoryKindId)).toEqual([
9, 13,
112, 112,
]);
expect(warnings).toEqual(
expect(warnings).toEqual([]);
expect(infoWarnings).toEqual(
expect.arrayContaining([
expect.stringContaining("using factory bundle VehicleHullAccessoryId=3061139"),
expect.stringContaining("mapped to factory bundle VehicleHullAccessoryId=3061139 AccessoryKindId=112"),
]),
);
});
@@ -85,7 +85,7 @@ describe("fanavaran hull base claim", () => {
expect(hull.PolicyId).toBe(13764408);
expect(hull.AccidentTypeId).toBeNull();
expect(hull.IsLicenseReplaced).toBeNull();
expect(hull.IsLicenseReplaced).toBe(0);
expect(hull.CostSeparationToDmgSections).toBe(0);
expect(hull.IsOwnerChanged).toBe(0);
expect(hull.CulpritTypeId).toBeNull();
@@ -125,7 +125,7 @@ export function toFanavaranHullBaseClaimPayload(
const next: Record<string, unknown> = {};
for (const key of FANAVARAN_HULL_BASE_CLAIM_KEYS) {
if (key === "IsLicenseReplaced") {
// Fanavaran conditional: >10y since issue → 1; else null (never 0).
// Preserve the server's conditional 0 / null / 1 mapping for licence age.
if (
Object.prototype.hasOwnProperty.call(built, key) &&
(built[key] === 1 || built[key] === 0 || built[key] === null)
@@ -74,7 +74,7 @@ describe("fanavaran-party-roles", () => {
expect(resolveFanavaranLicenceIssuDate(driver)).toBe(
FANAVARAN_DUMMY_LICENCE_ISSU_DATE,
);
expect(FANAVARAN_DUMMY_LICENCE_ISSU_DATE).toBe("1404/08/20");
expect(FANAVARAN_DUMMY_LICENCE_ISSU_DATE).toBe("1400/01/01");
});
it("marks licence replaced only when issue date is more than 10 years before accident", () => {
@@ -86,7 +86,19 @@ describe("fanavaran-party-roles", () => {
).toBeNull();
expect(
resolveFanavaranIsLicenseReplaced("1404/08/20", "1405/08/20"),
).toBeNull();
).toBe(0);
});
it.each([
["1402/08/21", 0],
["1402/08/20", 0],
["1402/08/19", null],
["1395/08/21", null],
["1395/08/20", null],
["1395/08/19", 1],
["1380/08/20", 1],
])("uses the exact anniversary for issue date %s", (issueDate, expected) => {
expect(resolveFanavaranIsLicenseReplaced(issueDate, "1405/08/20")).toBe(expected);
});
it("marks DriverIsOwner false when driver and owner differ", () => {
@@ -35,14 +35,11 @@ export function isJalaliDateOlderThanYears(
const issue = parseJalaliDateParts(issueDate);
const reference = parseJalaliDateParts(referenceDate);
if (!issue || !reference) return false;
let age = reference.year - issue.year;
if (
reference.month < issue.month ||
(reference.month === issue.month && reference.day < issue.day)
) {
age -= 1;
}
return age > years;
const anniversary =
(issue.year + years) * 10000 + issue.month * 100 + issue.day;
const referenceDay =
reference.year * 10000 + reference.month * 100 + reference.day;
return referenceDay > anniversary;
}
/**
+15 -2
View File
@@ -1,3 +1,4 @@
import { UserClaimBranchService } from "./user-claim-branch.service";
import { Module } from "@nestjs/common";
import { MongooseModule } from "@nestjs/mongoose";
import { SystemSettingsModule } from "src/system-settings/system-settings.module";
@@ -27,7 +28,19 @@ import { ClientDbSchema, ClientModel } from "./entities/schema/client.schema";
ClientPanelController,
ClientExternalInquiriesController,
],
providers: [ClientService, ClientDbService, BranchDbService, ExternalInquirySettingsService],
exports: [ClientService, ClientDbService, BranchDbService, ExternalInquirySettingsService],
providers: [
UserClaimBranchService,
ClientService,
ClientDbService,
BranchDbService,
ExternalInquirySettingsService,
],
exports: [
UserClaimBranchService,
ClientService,
ClientDbService,
BranchDbService,
ExternalInquirySettingsService,
],
})
export class ClientModule {}
@@ -0,0 +1,213 @@
import { Types } from "mongoose";
import {
UserClaimBranchService,
userClaimBranchContext,
usesUserClaimBranch,
} from "./user-claim-branch.service";
import { RequestManagementService } from "src/request-management/request-management.service";
const firstId = "650000000000000000000001",
secondId = "650000000000000000000002";
const payer = "650000000000000000000003",
otherInsurer = "650000000000000000000004";
const branchId = "650000000000000000000005";
function blame(type = "THIRD_PARTY", guiltyId = firstId): any {
return {
_id: new Types.ObjectId(),
type,
status: "WAITING_FOR_SIGNATURES",
branchId: undefined,
expert: { decision: { guiltyPartyId: guiltyId } },
parties: [
{
role: "FIRST",
person: {
userId: firstId,
clientId:
guiltyId === firstId || type === "CAR_BODY" ? payer : otherInsurer,
},
},
...(type === "CAR_BODY"
? []
: [
{
role: "SECOND",
person: {
userId: secondId,
clientId: guiltyId === secondId ? payer : otherInsurer,
},
},
]),
],
history: [],
workflow: {},
};
}
function setup(source = blame()) {
const branches: any = {
findAllWithFilters: jest
.fn()
.mockResolvedValue([
{
_id: branchId,
clientKey: payer,
isActive: true,
name: "شعبه مرکزی",
code: "100",
state: "تهران",
city: "تهران",
address: "نشانی",
secretInternal: "excluded",
},
]),
findById: jest
.fn()
.mockResolvedValue({ _id: branchId, clientKey: payer, isActive: true }),
};
const routing = new UserClaimBranchService(branches);
const api: any = Object.create(RequestManagementService.prototype);
api.sourceId = source._id;
api.userClaimBranchService = routing;
api.blameRequestDbService = {
findById: jest.fn().mockResolvedValue(source),
findByIdAndUpdate: jest.fn(async (_id, update) => {
for (const [path, value] of Object.entries(update.$set ?? {})) {
let obj = source;
const bits = path.split(".");
for (const bit of bits.slice(0, -1)) obj = obj[bit] ??= {};
obj[bits.at(-1)!] = value;
}
return source;
}),
};
api.userSign = { create: jest.fn().mockResolvedValue({ _id: "sign-id" }) };
api.claimCaseDbService = { findOne: jest.fn().mockResolvedValue(null) };
api.logger = { log: jest.fn() };
return { routing, branches, api, source };
}
const sign = { filename: "sign.png", path: "files/sign.png" };
describe("user-selected claim branch", () => {
it.each([false, true])(
"requires a branch only for the beneficiary in v1/v6 (%s)",
(callCenterInitiated) => {
const source = { ...blame(), callCenterInitiated };
expect(userClaimBranchContext(source, firstId).required).toBe(false);
expect(userClaimBranchContext(source, secondId).required).toBe(true);
expect(
userClaimBranchContext(blame("THIRD_PARTY", secondId), firstId)
.required,
).toBe(true);
expect(userClaimBranchContext(blame("CAR_BODY"), firstId).required).toBe(
true,
);
expect(userClaimBranchContext(source, "outsider").required).toBe(false);
},
);
it.each([
{ expertInitiated: true },
{ registrarInitiated: true },
{ isMadeByFileMaker: true },
{ creationMethod: "IN_PERSON" },
])("preserves expert-created flow %j", (flags) => {
expect(usesUserClaimBranch({ ...blame(), ...flags })).toBe(false);
});
it("lists only active branches of the paying insurer, with minimal public data", async () => {
const { routing, branches } = setup(blame("THIRD_PARTY", secondId));
const result = await routing.options(blame("THIRD_PARTY", secondId));
expect(branches.findAllWithFilters).toHaveBeenCalledWith(payer, {
isActive: true,
});
expect(result[0]).toMatchObject({
id: branchId,
city: "تهران",
address: "نشانی",
});
expect(result[0]).not.toHaveProperty("secretInternal");
});
it.each([undefined, "", "not-an-id", { id: branchId }])(
"rejects missing/malformed branch %j",
async (id) => {
const { routing } = setup();
await expect(routing.validate(blame(), id)).rejects.toThrow();
},
);
it.each([
null,
{ clientKey: payer, isActive: false },
{ clientKey: payer },
{ clientKey: otherInsurer, isActive: true },
])("rejects missing, inactive and foreign branches %j", async (branch) => {
const { routing, branches } = setup();
branches.findById.mockResolvedValue(branch);
await expect(routing.validate(blame(), branchId)).rejects.toThrow();
});
it.each([blame(), blame("CAR_BODY"), blame("THIRD_PARTY", secondId)])(
"validates branch against payer, not damaged vehicle insurer",
async (source) => {
const { routing } = setup(source);
await expect(routing.validate(source, branchId)).resolves.toBe(branchId);
},
);
it("blocks beneficiary signature before saving any signature if no branch is selected", async () => {
const { api } = setup();
await expect(
api.userSignDecisionV2(String(api.sourceId), secondId, true, sign),
).rejects.toThrow();
expect(api.userSign.create).not.toHaveBeenCalled();
expect(api.blameRequestDbService.findByIdAndUpdate).not.toHaveBeenCalled();
});
it("persists accepted beneficiary signature and validated branch together", async () => {
const { api, source } = setup();
await api.userSignDecisionV2(String(api.sourceId), secondId, true, sign, branchId);
expect(String(source.branchId)).toBe(branchId);
expect(source.parties[1].confirmation.accepted).toBe(true);
expect(api.blameRequestDbService.findByIdAndUpdate).toHaveBeenCalledWith(
String(source._id),
expect.objectContaining({
$set: expect.objectContaining({
branchId: new Types.ObjectId(branchId),
"parties.1.confirmation": expect.any(Object),
}),
}),
);
});
it("guilty party may sign without selecting a branch but cannot choose one", async () => {
const { api } = setup();
await expect(
api.userSignDecisionV2(String(api.sourceId), firstId, true, sign, branchId),
).rejects.toThrow();
await expect(
api.userSignDecisionV2(String(api.sourceId), firstId, true, sign),
).resolves.toMatchObject({ accepted: true });
});
it("rejecting does not require a branch", async () => {
const { api } = setup();
await expect(
api.userSignDecisionV2(String(api.sourceId), secondId, false, sign),
).resolves.toMatchObject({ status: "STOPPED" });
});
it("authorizes case reads before offering branch data", async () => {
const { api, branches } = setup();
api.getBlameRequestV2 = jest.fn().mockRejectedValue(new Error("forbidden"));
await expect(
api.getUserClaimBranches("case", { sub: secondId }),
).rejects.toThrow("forbidden");
expect(branches.findAllWithFilters).not.toHaveBeenCalled();
});
it("supports already signed cases, prevents culprit selection, and freezes branch after claim creation", async () => {
const { api, source } = setup();
api.getBlameRequestV2 = jest.fn().mockResolvedValue({});
source.status = "COMPLETED";
await expect(
api.selectUserClaimBranch("case", { sub: firstId }, branchId),
).rejects.toThrow();
await expect(
api.selectUserClaimBranch("case", { sub: secondId }, branchId),
).resolves.toEqual({ branchId });
api.claimCaseDbService.findOne.mockResolvedValue({ branchId });
await expect(
api.selectUserClaimBranch("case", { sub: secondId }, branchId),
).rejects.toThrow();
});
});
+84
View File
@@ -0,0 +1,84 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import { Types } from "mongoose";
import { BranchDbService } from "./entities/db-service/branch.db.service";
import { resolveClaimBeneficiary } from "src/helpers/blame-claim-eligibility";
import { resolveClaimOwnerParty } from "src/helpers/blame-damaged-party";
/** User-led v1/v6 only. Expert/registrar-created flows retain their ownership. */
export function usesUserClaimBranch(blame: any): boolean {
return (
!!blame.callCenterInitiated ||
(!blame.expertInitiated &&
!blame.registrarInitiated &&
!blame.isMadeByFileMaker &&
blame.creationMethod !== "IN_PERSON")
);
}
export function userClaimBranchContext(blame: any, userId: string) {
const beneficiary = resolveClaimBeneficiary(blame);
return {
required:
usesUserClaimBranch(blame) &&
!!beneficiary?.person?.userId &&
String(beneficiary.person.userId) === String(userId),
branchId: blame.branchId ? String(blame.branchId) : null,
};
}
@Injectable()
export class UserClaimBranchService {
constructor(private readonly branches: BranchDbService) {}
private payerId(blame: any): string {
const id = String(resolveClaimOwnerParty(blame)?.person?.clientId ?? "");
if (!Types.ObjectId.isValid(id)) {
throw new BadRequestException(
"شرکت بیمه پرداخت‌کننده خسارت مشخص نیست. اطلاعات بیمه‌نامه را بررسی کنید.",
);
}
return id;
}
async options(blame: any) {
const clientId = this.payerId(blame);
const branches = await this.branches.findAllWithFilters(clientId, {
isActive: true,
});
return branches
.map((branch: any) => ({
id: String(branch._id),
name: branch.fullName || branch.name,
code: branch.code,
city: branch.city,
state: branch.state,
address: branch.address,
phoneNumber: branch.phoneNumber,
}))
.sort(
(a, b) =>
a.city.localeCompare(b.city, "fa") ||
a.name.localeCompare(b.name, "fa"),
);
}
async validate(blame: any, branchId: unknown): Promise<string> {
const id = typeof branchId === "string" ? branchId.trim() : "";
if (!Types.ObjectId.isValid(id)) {
throw new BadRequestException(
"شهر و شعبه رسیدگی به خسارت را انتخاب کنید.",
);
}
const branch = await this.branches.findById(id);
if (
!branch ||
branch.isActive !== true ||
String(branch.clientKey) !== this.payerId(blame)
) {
throw new BadRequestException(
"شعبه انتخاب‌شده فعال نیست یا متعلق به شرکت بیمه پرداخت‌کننده خسارت نیست. شعبه دیگری انتخاب کنید.",
);
}
return id;
}
}
+34 -2
View File
@@ -471,7 +471,9 @@ describe("ExpertClaimService FileReviewer assignment", () => {
const blameId = new Types.ObjectId();
const claimId = new Types.ObjectId();
service.expireClaimWorkflowLockV2IfStale = jest.fn().mockResolvedValue(undefined);
service.expireClaimWorkflowLockV2IfStale = jest
.fn()
.mockResolvedValue(undefined);
service.claimCaseDbService = {
findById: jest.fn().mockResolvedValue({
_id: claimId,
@@ -494,7 +496,9 @@ describe("ExpertClaimService FileReviewer assignment", () => {
}),
};
service.fanavaranLocationService = {
assertMakerReviewerBranchCompatible: jest.fn().mockResolvedValue(undefined),
assertMakerReviewerBranchCompatible: jest
.fn()
.mockResolvedValue(undefined),
};
service.assertExpertActorOnClaim = jest.fn();
@@ -536,4 +540,32 @@ describe("ExpertClaimService branch-scoped claim views", () => {
),
).resolves.toEqual([inBranch, legacyUnscoped]);
});
it("denies direct access and assignment scope for an expert in another branch", async () => {
const service = createService() as any;
const branchId = new Types.ObjectId();
const otherBranch = new Types.ObjectId();
service.damageExpertDbService = {
findById: jest.fn().mockResolvedValue({ branchId: otherBranch }),
};
await expect(
service.assertActorBranchAccess(
{ branchId },
{ sub: V2_EXPERT_ID, role: RoleEnum.DAMAGE_EXPERT },
),
).rejects.toThrow();
service.damageExpertDbService.findById.mockResolvedValue({ branchId });
await expect(
service.assertActorBranchAccess(
{ branchId },
{ sub: V2_EXPERT_ID, role: RoleEnum.DAMAGE_EXPERT },
),
).resolves.toBeUndefined();
service.damageExpertDbService.findById.mockResolvedValue({});
await expect(
service.assertActorBranchAccess(
{ branchId },
{ sub: V2_EXPERT_ID, role: RoleEnum.DAMAGE_EXPERT },
),
).rejects.toThrow();
});
});
@@ -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,
);
}