Added extra fanavaran fields

This commit is contained in:
SepehrYahyaee
2026-10-04 12:01:45 +03:30
parent 91074ca1e5
commit 268258a23c
13 changed files with 1216 additions and 38 deletions
@@ -0,0 +1,97 @@
import { Type } from "class-transformer";
import {
Equals,
IsInt,
IsOptional,
IsString,
Max,
MaxLength,
Min,
ValidateNested,
} from "class-validator";
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
export class FanavaranStageFieldValuesDto {
@ApiPropertyOptional()
@IsOptional()
@IsString()
@MaxLength(1000)
AccidentLocationAddress?: string;
@ApiPropertyOptional()
@IsOptional()
@IsInt()
@Min(1)
AccidentCityId?: number;
@ApiPropertyOptional()
@IsOptional()
@IsInt()
@Min(1)
AccidentReportTypeId?: number;
@ApiPropertyOptional()
@IsOptional()
@IsInt()
@Min(1)
DmgHistoryStatus?: number;
@ApiPropertyOptional()
@IsOptional()
@IsInt()
@Min(1)
InspectionPlaceId?: number;
@ApiPropertyOptional()
@IsOptional()
@IsInt()
@Min(1)
AccidentTypeId?: number;
@ApiPropertyOptional()
@IsOptional()
@IsInt()
@Min(1)
CulpritTypeId?: number;
@ApiPropertyOptional()
@IsOptional()
@IsInt()
@Min(1)
AuthorityCulpritId?: number;
@ApiPropertyOptional()
@IsOptional()
@IsInt()
@Min(0)
@Max(100)
CustomerFaultPercent?: number;
@ApiPropertyOptional()
@IsOptional()
@IsInt()
@Min(1)
RepairDuration?: number;
@ApiPropertyOptional({ description: "Fanavaran amount in rials" })
@IsOptional()
@IsInt()
@Min(1)
VehicleCurrentValue?: number;
}
export class UpdateFanavaranStageFieldsDto {
@ApiProperty({ type: FanavaranStageFieldValuesDto })
@ValidateNested()
@Type(() => FanavaranStageFieldValuesDto)
values: FanavaranStageFieldValuesDto;
@ApiProperty({ description: "Current field-review version; 0 when absent" })
@IsInt()
@Min(0)
expectedVersion: number;
@ApiProperty()
@Equals(true)
confirmed: true;
}
@@ -1,7 +1,27 @@
import { ApiProperty } from "@nestjs/swagger";
import { Equals, IsInt, Min } from "class-validator";
import {
Equals,
IsInt,
IsOptional,
Min,
ValidateNested,
} from "class-validator";
import { Type } from "class-transformer";
import { FanavaranStageFieldValuesDto } from "./fanavaran-stage-fields.dto";
export class ApproveFanavaranVehicleReviewDto {
@ApiProperty({ required: false, type: FanavaranStageFieldValuesDto })
@IsOptional()
@ValidateNested()
@Type(() => FanavaranStageFieldValuesDto)
stageFields?: FanavaranStageFieldValuesDto;
@ApiProperty({ required: false, description: "Current field-review version" })
@IsOptional()
@IsInt()
@Min(0)
stageFieldsVersion?: number;
@ApiProperty({ example: 1, description: "Fanavaran vehicle-groups Id" })
@IsInt()
@Min(1)
+219 -17
View File
@@ -184,6 +184,11 @@ import {
import { claimPriceCapAppliesToBlame } from "src/helpers/claim-price-cap";
import { LookupsService } from "src/lookups/lookups.service";
import { ApproveFanavaranVehicleReviewDto } from "./dto/fanavaran-vehicle-review.dto";
import { UpdateFanavaranStageFieldsDto } from "./dto/fanavaran-stage-fields.dto";
import {
fanavaranFieldStageSent, type FanavaranFieldReview,
type FanavaranFieldValues,
} from "src/claim-request-management/fanavaran-stage-fields";
import {
buildFanavaranVehicleSuggestion,
collectFanavaranVehicleInquiryRecords,
@@ -5677,6 +5682,18 @@ export class ExpertClaimService {
"Vehicle classification cannot be changed after the claim was sent to Fanavaran.",
);
}
const fields =
body.stageFields !== undefined
? await this.prepareFanavaranStageFieldReview(
claim,
{
values: body.stageFields,
expectedVersion: body.stageFieldsVersion,
confirmed: body.confirmed,
},
actor,
)
: undefined;
const [groupsRaw, useTypesRaw, systemsRaw, vehicleKind] = await Promise.all(
[
this.lookupsService.getClientRemoteLookup("vehicle-groups"),
@@ -5735,30 +5752,47 @@ export class ExpertClaimService {
approvedByRole: String(actor.role),
version: Number((claim as any).fanavaranVehicleReview?.version ?? 0) + 1,
};
const updated = await this.claimCaseDbService.findByIdAndUpdate(
claimRequestId,
const updated = await this.claimCaseDbService.findOneAndUpdate(
{
$set: { fanavaranVehicleReview: review },
_id: claimRequestId,
claimId: null,
claimNo: null,
...(fields?.filter ?? {}),
},
{
$set: {
fanavaranVehicleReview: review,
...(fields ? { fanavaranFieldReview: fields.review } : {}),
},
$push: {
history: {
type: "FANAVARAN_VEHICLE_REVIEW_APPROVED",
actor: {
actorId: new Types.ObjectId(String(actor.sub)),
actorName: actor.fullName,
actorType: actor.role,
},
timestamp: review.approvedAt,
metadata: {
version: review.version,
vehicleGroupId: body.vehicleGroupId,
vehicleUseTypeId: body.vehicleUseTypeId,
vehicleSystemId: body.vehicleSystemId,
vehicleKindId: body.vehicleKindId,
},
$each: [
{
type: "FANAVARAN_VEHICLE_REVIEW_APPROVED",
actor: {
actorId: new Types.ObjectId(String(actor.sub)),
actorName: actor.fullName,
actorType: actor.role,
},
timestamp: review.approvedAt,
metadata: {
version: review.version,
vehicleGroupId: body.vehicleGroupId,
vehicleUseTypeId: body.vehicleUseTypeId,
vehicleSystemId: body.vehicleSystemId,
vehicleKindId: body.vehicleKindId,
},
},
...(fields ? [fields.history] : []),
],
},
},
},
);
if (!updated)
throw new ConflictException(
"The case changed during review. Refresh before saving.",
);
const baseClaim =
await this.claimRequestManagementService.autoSubmitToFanavaranV2OnClaimCreated(
claimRequestId,
@@ -5776,6 +5810,174 @@ export class ExpertClaimService {
};
}
async getFanavaranStageFieldsV2(claimRequestId: string, actor: any) {
await this.getClaimDetailV2(claimRequestId, actor);
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) throw new NotFoundException("Claim request not found");
const blame = await this.loadBlameForClaim(claim);
return this.claimRequestManagementService.getFanavaranStageFieldsContext(
claim,
blame,
);
}
private async prepareFanavaranStageFieldReview(
claim: any,
body: UpdateFanavaranStageFieldsDto,
actor: any,
) {
if (
body.confirmed !== true ||
!body.values ||
typeof body.values !== "object" ||
Array.isArray(body.values)
) {
throw new BadRequestException(
"Explicit confirmation and field values are required.",
);
}
const version = claim.fanavaranFieldReview?.version ?? 0;
if (
!Number.isSafeInteger(body.expectedVersion) ||
body.expectedVersion !== version
) {
throw new ConflictException(
"The Fanavaran fields changed. Refresh before saving.",
);
}
const context =
await this.claimRequestManagementService.getFanavaranStageFieldsContext(
claim,
await this.loadBlameForClaim(claim),
);
const values: FanavaranFieldValues = {};
const captions: FanavaranFieldReview["captions"] = {};
const stages = new Set<string>();
const before: FanavaranFieldValues = {};
for (const [key, raw] of Object.entries(body.values)) {
const field = context.fields.find((field) => field.key === key);
if (!field)
throw new BadRequestException(
`Field ${key} does not apply to this case type.`,
);
if (fanavaranFieldStageSent(claim, field.stage)) {
throw new ConflictException(
`Field ${key} has already been sent to Fanavaran and cannot be changed.`,
);
}
let value: string | number = raw;
if (field.type === "text") {
if (
typeof raw !== "string" ||
!raw.trim() ||
raw.trim().length > 1000
) {
throw new BadRequestException(
`${key} must be a non-empty address of at most 1000 characters.`,
);
}
value = raw.trim();
} else {
if (
typeof raw !== "number" ||
!Number.isSafeInteger(raw) ||
raw < (field.min ?? 1) ||
(field.max != null && raw > field.max)
) {
throw new BadRequestException(
`Field ${key} is out of range or invalid.`,
);
}
if (field.type === "lookup") {
const row = field.options?.find((row) => row.Id === raw);
if (!row)
throw new BadRequestException(
`Field ${key} must use an active Fanavaran lookup value. Reload the options and try again.`,
);
captions[field.key] = row.Caption;
}
}
values[field.key] = value;
before[field.key] = field.value;
stages.add(field.stage);
}
if (!Object.keys(values).length)
throw new BadRequestException("No Fanavaran fields were supplied.");
const review: FanavaranFieldReview = {
values: { ...claim.fanavaranFieldReview?.values, ...values },
captions: { ...claim.fanavaranFieldReview?.captions, ...captions },
version: version + 1,
reviewedAt: new Date(),
reviewedByActorId: String(actor.sub),
reviewedByActorName: actor.fullName,
reviewedByRole: String(actor.role),
};
const conditions: Record<string, unknown>[] = [
version === 0
? {
$or: [
{ "fanavaranFieldReview.version": { $exists: false } },
{ "fanavaranFieldReview.version": 0 },
],
}
: { "fanavaranFieldReview.version": version },
];
for (const stage of stages) {
const id = {
baseClaim: "claimId",
damageCase: "dmgCaseId",
expertise: "expertiseId",
}[stage];
conditions.push({
[id]: null,
[`fanavaranSync.${stage}.${id}`]: null,
[`fanavaranSync.${stage}.status`]: { $ne: "success" },
});
if (stage === "baseClaim") conditions.push({ claimNo: null });
}
return {
review,
filter: { $and: conditions },
history: {
type: "FANAVARAN_FIELDS_REVIEWED",
actor: {
actorId: new Types.ObjectId(String(actor.sub)),
actorName: actor.fullName,
actorType: actor.role,
},
timestamp: review.reviewedAt,
metadata: { version: review.version, before, after: values, captions },
},
};
}
async updateFanavaranStageFieldsV2(
claimRequestId: string,
body: UpdateFanavaranStageFieldsDto,
actor: any,
) {
await this.getClaimDetailV2(claimRequestId, actor);
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) throw new NotFoundException("Claim request not found");
const fields = await this.prepareFanavaranStageFieldReview(
claim,
body,
actor,
);
const updated = await this.claimCaseDbService.findOneAndUpdate(
{ _id: claimRequestId, ...fields.filter },
{
$set: { fanavaranFieldReview: fields.review },
$push: { history: fields.history },
},
);
if (!updated)
throw new ConflictException(
"The case changed or its stage was sent. Refresh before saving.",
);
return { version: fields.review.version };
}
/** V2 price-drop: claim locked by this expert during damage assessment. */
private async assertExpertCanEditClaimDuringReviewV2(
claim: any,
@@ -56,6 +56,7 @@ import { ClaimRequestManagementService } from "src/claim-request-management/clai
import { OuterPartCatalogItemDto } from "src/claim-request-management/dto/select-outer-parts-v2.dto";
import { submitExpertReplyValidationPipe } from "./pipes/submit-expert-reply-validation.pipe";
import { ApproveFanavaranVehicleReviewDto } from "./dto/fanavaran-vehicle-review.dto";
import { UpdateFanavaranStageFieldsDto } from "./dto/fanavaran-stage-fields.dto";
class InPersonVisitV2Dto {
@ApiPropertyOptional({ example: "Paint damage requires physical inspection" })
@@ -245,6 +246,19 @@ export class ExpertClaimV2Controller {
);
}
@Get("request/:claimRequestId/fanavaran-stage-fields")
@ApiOperation({ summary: "Case-specific Fanavaran fields, active lookup options and per-stage editability" })
async getFanavaranStageFieldsV2(@Param("claimRequestId") id: string, @CurrentUser() actor: any) {
return this.expertClaimService.getFanavaranStageFieldsV2(id, actor);
}
@Patch("request/:claimRequestId/fanavaran-stage-fields")
@ApiOperation({ summary: "Validate and save expert edits for unsent Fanavaran stages" })
@ApiBody({ type: UpdateFanavaranStageFieldsDto })
async updateFanavaranStageFieldsV2(@Param("claimRequestId") id: string, @Body() body: UpdateFanavaranStageFieldsDto, @CurrentUser() actor: any) {
return this.expertClaimService.updateFanavaranStageFieldsV2(id, body, actor);
}
@Get("request/:claimRequestId/price-drop")
@ApiOperation({
summary: "Price-drop context for manual expert entry (V2)",
@@ -0,0 +1,494 @@
import {
BadRequestException,
ConflictException,
ForbiddenException,
} from "@nestjs/common";
import { ExpertClaimService } from "./expert-claim.service";
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
import {
activeStageLookupRows,
applyFanavaranStageFieldReview,
fanavaranStageFields,
} from "src/claim-request-management/fanavaran-stage-fields";
const actor = {
sub: "507f1f77bcf86cd799439011",
role: "damage_expert",
fullName: "کارشناس",
};
const id = "507f1f77bcf86cd799439012";
const vehicleBody = {
vehicleGroupId: 1,
vehicleUseTypeId: 1,
vehicleSystemId: 14,
vehicleKindId: 7456,
confirmed: true as const,
};
function setup(product = "third-party", extra: any = {}) {
const claim = {
_id: id,
blameRequestId: "blame",
damage: { selectedParts: [] },
...extra,
};
const management = Object.create(
ClaimRequestManagementService.prototype,
) as any;
management.getFanavaranLookupRows = jest
.fn()
.mockImplementation(async (_client, name) => {
const ids = {
cities: 702,
"accident-report-type": 156,
"dmg-history-status": 5215,
"inspection-place": 283,
"vehicle-hull-accident-types": 4,
"vehicle-hull-accident-culprit-type": 301,
"detection-accident-culprits": 8,
};
return [
{ Id: ids[name], Caption: "گزینه معتبر", IsActive: 1 },
{ Id: 999, Caption: "غیرفعال", IsActive: 0 },
];
});
management.resolveHullVehicleCurrentValueFromPolicy = jest
.fn()
.mockResolvedValue(1000000000);
management.autoSubmitToFanavaranV2OnClaimCreated = jest
.fn()
.mockImplementation(async () => {
expect(claim.fanavaranFieldReview).toBeDefined();
return { submitted: false };
});
management.autoSubmitFanavaranDamageCaseOnOuterPartsSelected = jest.fn();
const service = Object.create(ExpertClaimService.prototype) as any;
service.getClaimDetailV2 = jest.fn().mockResolvedValue({});
service.blameRequestDbService = {
findById: jest
.fn()
.mockResolvedValue({
type: product === "car-body" ? "CAR_BODY" : "THIRD_PARTY",
}),
};
service.claimCaseDbService = {
findById: jest.fn().mockResolvedValue(claim),
findOneAndUpdate: jest
.fn()
.mockImplementation(async (_filter, update) =>
Object.assign(claim, update.$set),
),
};
service.claimRequestManagementService = management;
service.lookupsService = {
getClientRemoteLookup: jest.fn().mockImplementation(async (name) => {
if (name === "vehicle-groups") return [{ Id: 1, Caption: "سواری" }];
if (name === "vehicle-use-types")
return [{ Id: 1, Caption: "شخصی", VehicleGroupId: 1 }];
return [{ Id: 14, Caption: "پراید", VehicleGroupId: 1 }];
}),
getActiveVehicleKindById: jest
.fn()
.mockResolvedValue({
Id: 7456,
Caption: "پراید",
VehicleGroupId: 1,
VehicleSystemId: 14,
}),
};
return { service, management, claim };
}
describe("Expert Fanavaran stage fields", () => {
it.each(["third-party", "car-body"])(
"puts reviewed base fields into the actual %s preview after derived/default enrichment",
async (product) => {
const { management, claim } = setup(product, {
fanavaranFieldReview: {
values: {
AccidentLocationAddress: "نشانی واقعی",
AccidentCityId: 702,
AccidentReportTypeId: 156,
AccidentTypeId: 4,
CulpritTypeId: 301,
AuthorityCulpritId: 8,
CustomerFaultPercent: 0,
},
},
fanavaranVehicleReview: { vehicleUseType: { id: 1 } },
fanavaranSync: { baseClaim: { policyId: 123 } },
});
management.logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn() };
management.fanavaranAuditService = {
generateTrackingCode: jest.fn().mockReturnValue("test"),
};
management.claimCaseDbService = {
findById: jest.fn().mockResolvedValue(claim),
findByIdAndUpdate: jest.fn(),
};
management.blameRequestDbService = {
findById: jest
.fn()
.mockResolvedValue({
type: product === "car-body" ? "CAR_BODY" : "THIRD_PARTY",
parties: [{ role: "FIRST" }],
createdAt: new Date(),
}),
};
management.resolveAccidentVehicleUsedFromApis = jest
.fn()
.mockResolvedValue({ usedId: 1 });
management.resolveFanavaranFileRoleExpertIdsForBlame = jest
.fn()
.mockResolvedValue(null);
management.enrichCarBodyHullBaseClaimPayload = jest
.fn()
.mockImplementation(async ({ payload }) => {
payload.CustomerFaultPercent = 100;
payload.AuthorityCulpritId = 1;
});
const payload = await management.previewFanavaranSubmitV2(id, "parsian", {
persistPayload: false,
forceRefreshPolicy: false,
});
expect(payload).toMatchObject({
AccidentLocationAddress: "نشانی واقعی",
AccidentCityId: 702,
AccidentReportTypeId: 156,
});
if (product === "car-body") {
expect(payload).toMatchObject({
AccidentTypeId: 4,
CulpritTypeId: 301,
AuthorityCulpritId: 8,
CustomerFaultPercent: 0,
IsLicenseReplaced: null,
});
expect(payload.DamagedCount).toBeUndefined();
expect(payload.IsLicenseReplacement).toBeUndefined();
} else expect(payload.AuthorityCulpritId).toBeNull();
},
);
it("puts reviewed repair duration and rial value into actual hull assessment payload", async () => {
const { management, claim } = setup("car-body", {
vehicle: { carPrice: "3000000000" },
fanavaranFieldReview: {
values: { RepairDuration: 12, VehicleCurrentValue: 12000000000 },
},
});
const result = await management.buildCarBodyFanavaranExpertisePayload({
claimCase: claim,
blame: { parties: [] },
clientKey: "parsian",
profile: {},
parts: [],
claimExpertId: 29,
submittedAt: new Date(),
priceDropTotal: 0,
priceDropCarPrice: "5000000000",
warnings: [],
});
expect(result.payload).toMatchObject({
RepairDuration: 12,
VehicleCurrentValue: 12000000000,
});
expect(result.payload.InspectionPlaceId).toBeUndefined();
expect(result.payload.DmgCaseId).toBeUndefined();
});
it("puts the reviewed inspection place into actual third-party assessment payload", async () => {
const { management, claim } = setup("third-party", {
dmgCaseId: 20,
fanavaranFieldReview: { values: { InspectionPlaceId: 283 } },
});
management.blameRequestDbService = {
findById: jest.fn().mockResolvedValue({ type: "THIRD_PARTY" }),
};
management.resolveFanavaranFileRoleExpertIdsForBlame = jest
.fn()
.mockResolvedValue(null);
management.resolveFanavaranClaimProduct = jest
.fn()
.mockResolvedValue("third-party");
const result = await management.buildFanavaranExpertisePayload({
claimCase: claim,
clientKey: "parsian",
});
expect(result.payload).toMatchObject({
InspectionPlaceId: 283,
DmgCaseId: 20,
});
});
it("puts reviewed damage history into the actual third-party damage-case payload", async () => {
const { management, claim } = setup("third-party", {
fanavaranFieldReview: { values: { DmgHistoryStatus: 5215 } },
fanavaranVehicleReview: {
vehicleKind: { id: 7456 },
vehicleUseType: { id: 1 },
},
});
management.logger = { log: jest.fn(), warn: jest.fn() };
management.claimCaseDbService = { findByIdAndUpdate: jest.fn() };
management.pickDamagedPartyForFanavaran = jest
.fn()
.mockReturnValue({ person: {} });
management.resolveOwnershipPlateForClaim = jest.fn().mockReturnValue(null);
management.fetchFanavaranVehicleByVinCandidates = jest
.fn()
.mockResolvedValue(null);
management.resolveDriverFanavaranIdFromBlameCase = jest
.fn()
.mockResolvedValue(null);
management.fanavaranLookupService = {
resolveInsuranceCorpId: jest.fn().mockResolvedValue(1),
};
const payload = await management.buildFanavaranDamageCasePayload({
claimCase: claim,
blameCase: { type: "THIRD_PARTY" },
selectedParts: ["سپر"],
clientKey: "parsian",
defaults: {
DmgHistoryStatus: 5214,
AccidentVehicleUsedId: 1,
CulpritLicenceTypeId: 2,
DmgCaseTypeId: 175,
FaultPercent: 100,
},
});
expect(payload.DmgHistoryStatus).toBe(5215);
expect(payload.LicenceCountryId).toBeNull();
});
it("uses the car-body codebooks and preserves submitted values in read-only base fields", async () => {
const { service } = setup("car-body", {
claimId: 10,
fanavaranSync: { baseClaim: { lastPayload: { AccidentCityId: 703 } } },
});
const context = await service.getFanavaranStageFieldsV2(id, actor);
expect(context.fields).toHaveLength(9);
expect(
context.fields.find((field) => field.key === "CulpritTypeId").lookup,
).toBe("vehicle-hull-accident-culprit-type");
expect(
context.fields.find((field) => field.key === "AccidentCityId"),
).toMatchObject({ value: 703, editable: false, source: "submitted" });
expect(
context.fields.find((field) => field.key === "RepairDuration").editable,
).toBe(true);
expect(
context.fields.find((field) => field.key === "VehicleCurrentValue"),
).toMatchObject({ value: 1000000000, unit: "ریال" });
});
it("saves fields atomically before vehicle approval releases automatic submission", async () => {
const { service, management } = setup();
await service.approveFanavaranVehicleReviewV2(
id,
{
...vehicleBody,
stageFieldsVersion: 0,
stageFields: {
AccidentLocationAddress: " نشانی واقعی ",
AccidentCityId: 702,
AccidentReportTypeId: 156,
DmgHistoryStatus: 5215,
InspectionPlaceId: 283,
},
},
actor,
);
const [, update] =
service.claimCaseDbService.findOneAndUpdate.mock.calls[0];
expect(update.$set.fanavaranFieldReview.values).toMatchObject({
AccidentLocationAddress: "نشانی واقعی",
InspectionPlaceId: 283,
});
expect(update.$set.fanavaranFieldReview.captions.AccidentCityId).toBe(
"گزینه معتبر",
);
expect(update.$push.history.$each.map((event) => event.type)).toEqual([
"FANAVARAN_VEHICLE_REVIEW_APPROVED",
"FANAVARAN_FIELDS_REVIEWED",
]);
expect(
management.autoSubmitToFanavaranV2OnClaimCreated,
).toHaveBeenCalledTimes(1);
});
it.each([
["third-party", { AccidentCityId: 999 }],
["third-party", { AccidentTypeId: 4 }],
["third-party", { AccidentLocationAddress: " " }],
["car-body", { CulpritTypeId: 337 }],
["car-body", { DmgHistoryStatus: 5215 }],
["car-body", { CustomerFaultPercent: 101 }],
["car-body", { RepairDuration: -1 }],
["car-body", { VehicleCurrentValue: null }],
["car-body", { VehicleCurrentValue: Number.MAX_SAFE_INTEGER + 1 }],
])(
"rejects invalid or inapplicable values for %s",
async (product, values) => {
const { service } = setup(product);
await expect(
service.updateFanavaranStageFieldsV2(
id,
{ values, expectedVersion: 0, confirmed: true },
actor,
),
).rejects.toBeInstanceOf(BadRequestException);
expect(
service.claimCaseDbService.findOneAndUpdate,
).not.toHaveBeenCalled();
},
);
it("preserves zero fault percentage and raw rial amounts", async () => {
const { service, claim } = setup("car-body");
await service.updateFanavaranStageFieldsV2(
id,
{
values: {
CustomerFaultPercent: 0,
VehicleCurrentValue: 12000000000,
RepairDuration: 9,
},
expectedVersion: 0,
confirmed: true,
},
actor,
);
expect(claim.fanavaranFieldReview.values).toMatchObject({
CustomerFaultPercent: 0,
VehicleCurrentValue: 12000000000,
RepairDuration: 9,
});
});
it.each([
[{ claimId: 10 }, { AccidentCityId: 702 }],
[
{ fanavaranSync: { baseClaim: { status: "success" } } },
{ AccidentCityId: 702 },
],
[{ dmgCaseId: 20 }, { DmgHistoryStatus: 5215 }],
[{ expertiseId: 30 }, { InspectionPlaceId: 283 }],
])(
"rejects edits once the relevant stage has been sent",
async (extra, values) => {
const { service } = setup("third-party", extra);
await expect(
service.updateFanavaranStageFieldsV2(
id,
{ values, expectedVersion: 0, confirmed: true },
actor,
),
).rejects.toBeInstanceOf(ConflictException);
},
);
it("allows remaining-stage edits after base creation and adds version/stage guards to the database write", async () => {
const { service } = setup("third-party", { claimId: 10 });
await service.updateFanavaranStageFieldsV2(
id,
{
values: { DmgHistoryStatus: 5215, InspectionPlaceId: 283 },
expectedVersion: 0,
confirmed: true,
},
actor,
);
const [filter] = service.claimCaseDbService.findOneAndUpdate.mock.calls[0];
expect(filter.$and).toContainEqual({
dmgCaseId: null,
"fanavaranSync.damageCase.dmgCaseId": null,
"fanavaranSync.damageCase.status": { $ne: "success" },
});
expect(filter.$and).toContainEqual({
expertiseId: null,
"fanavaranSync.expertise.expertiseId": null,
"fanavaranSync.expertise.status": { $ne: "success" },
});
});
it("rejects stale versions and a stage sent while lookups were loading", async () => {
const { service } = setup("car-body", {
fanavaranFieldReview: { version: 2 },
});
await expect(
service.updateFanavaranStageFieldsV2(
id,
{ values: { RepairDuration: 4 }, expectedVersion: 1, confirmed: true },
actor,
),
).rejects.toBeInstanceOf(ConflictException);
service.claimCaseDbService.findOneAndUpdate.mockResolvedValue(null);
await expect(
service.updateFanavaranStageFieldsV2(
id,
{ values: { RepairDuration: 4 }, expectedVersion: 2, confirmed: true },
actor,
),
).rejects.toBeInstanceOf(ConflictException);
});
it("enforces existing claim access before reading or writing fields", async () => {
const { service, management } = setup();
service.getClaimDetailV2.mockRejectedValue(new ForbiddenException());
await expect(
service.getFanavaranStageFieldsV2(id, actor),
).rejects.toBeInstanceOf(ForbiddenException);
await expect(
service.updateFanavaranStageFieldsV2(
id,
{
values: { AccidentCityId: 702 },
expectedVersion: 0,
confirmed: true,
},
actor,
),
).rejects.toBeInstanceOf(ForbiddenException);
expect(management.getFanavaranLookupRows).not.toHaveBeenCalled();
});
it("normalizes cached lookup envelopes without admitting inactive/legacy IDs", () => {
expect(
activeStageLookupRows({
data: {
data: [
{ Id: "7", Caption: "فعال", IsActive: "1" },
{ Id: 8, Caption: "غیرفعال", IsActive: "0" },
{ Code: 9, Caption: "کد قدیمی" },
],
},
}),
).toEqual([{ Id: 7, Caption: "فعال" }]);
});
it("keeps third-party keys out of hull stage payloads and existing nulls intact", () => {
const payload = { ArchiveNo: null };
applyFanavaranStageFieldReview(
payload,
{
fanavaranFieldReview: {
values: {
DmgHistoryStatus: 5215,
CustomerFaultPercent: 0,
InspectionPlaceId: 283,
AccidentCityId: 702,
},
},
},
"car-body",
"baseClaim",
);
expect(payload).toEqual({
ArchiveNo: null,
CustomerFaultPercent: 0,
AccidentCityId: 702,
});
expect(fanavaranStageFields("third-party")).toHaveLength(5);
});
});
@@ -29,7 +29,7 @@ function makeService(overrides?: { kind?: typeof kind }) {
service.getClaimDetailV2 = jest.fn().mockResolvedValue({});
service.claimCaseDbService = {
findById: jest.fn().mockResolvedValue(claim),
findByIdAndUpdate: jest.fn().mockImplementation((_id, update) =>
findOneAndUpdate: jest.fn().mockImplementation((_id, update) =>
Promise.resolve({
...claim,
fanavaranVehicleReview: update.$set.fanavaranVehicleReview,
@@ -103,7 +103,7 @@ describe("Fanavaran vehicle review", () => {
actor,
),
).rejects.toBeInstanceOf(BadRequestException);
expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled();
expect(service.claimCaseDbService.findOneAndUpdate).not.toHaveBeenCalled();
});
it("blocks outbound stages until all four values are approved", () => {