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
@@ -58,6 +58,11 @@ import {
fanavaranHullNestedClaimId,
toFanavaranHullBaseClaimPayload,
} from "./fanavaran-hull-base-claim";
import {
activeStageLookupRows, applyFanavaranStageFieldReview,
fanavaranFieldStageSent, fanavaranStageFields,
type FanavaranFieldValues,
} from "./fanavaran-stage-fields";
import {
collectFanavaranExpertiseReadinessWarnings,
hullExpertiseAssertFields,
@@ -4395,7 +4400,8 @@ export class ClaimRequestManagementService {
vehicleCurrentValue = vehicleCurrentValueFromHullPolicyRecord(policy);
}
const repairDuration = FANAVARAN_DEFAULT_HULL_REPAIR_DURATION;
vehicleCurrentValue = input.claimCase?.fanavaranFieldReview?.values?.VehicleCurrentValue ?? vehicleCurrentValue;
const repairDuration = input.claimCase?.fanavaranFieldReview?.values?.RepairDuration ?? FANAVARAN_DEFAULT_HULL_REPAIR_DURATION;
return {
replyKey: input.replyKey,
@@ -4757,7 +4763,7 @@ export class ClaimRequestManagementService {
"shsNam",
]) ??
(typeof apiVehicle?.ChassisNo === "string" ? apiVehicle.ChassisNo : null),
DmgHistoryStatus: input.defaults.DmgHistoryStatus,
DmgHistoryStatus: input.claimCase?.fanavaranFieldReview?.values?.DmgHistoryStatus ?? input.defaults.DmgHistoryStatus,
Desc: this.formatFanavaranSelectedPartsDesc(input.selectedParts),
DmgCaseTypeId: input.defaults.DmgCaseTypeId,
DriverId: driverFanavaranId ?? null,
@@ -6189,12 +6195,17 @@ export class ClaimRequestManagementService {
logPrefix,
claimCaseId,
});
applyFanavaranStageFieldReview(payload, claimCase, "car-body", "baseClaim");
delete payload.IsLicenseReplacement;
const hull = toFanavaranHullBaseClaimPayload(payload);
for (const key of Object.keys(payload)) delete payload[key];
Object.assign(payload, hull);
}
if (fanavaranClaimProductFromBlameType(blameCase.type) === "third-party") {
applyFanavaranStageFieldReview(payload, claimCase, "third-party", "baseClaim");
}
const fileRoleExpertIds =
await this.resolveFanavaranFileRoleExpertIdsForBlame(blameCase);
if (fileRoleExpertIds) {
@@ -6983,6 +6994,93 @@ export class ClaimRequestManagementService {
return definition;
}
/** Read-only panel context. Does not create a remote claim or persist a preview. */
async getFanavaranStageFieldsContext(claim: any, blame: any) {
if (!blame || !isFanavaranSubmitSupportedBlameType(blame.type)) {
throw new BadRequestException(
"Fanavaran field review only applies to third-party and car-body claims.",
);
}
const product = fanavaranClaimProductFromBlameType(blame.type);
const clientKey = resolveFanavaranClientKey();
const defaults = getFanavaranClientProfile(clientKey).defaults;
const definitions = fanavaranStageFields(product);
const options = new Map<string, ReturnType<typeof activeStageLookupRows>>();
await Promise.all(
definitions
.filter((field) => field.lookup)
.map(async (field) => {
options.set(
field.lookup,
activeStageLookupRows(
await this.getFanavaranLookupRows(clientKey, field.lookup),
),
);
}),
);
const initial: FanavaranFieldValues = {
AccidentLocationAddress: FANAVARAN_ACCIDENT_LOCATION_ADDRESS,
AccidentCityId: defaults.AccidentCityId,
AccidentReportTypeId: defaults.AccidentReportTypeId,
DmgHistoryStatus: defaults.DmgHistoryStatus,
InspectionPlaceId: 282,
AccidentTypeId: 2,
CulpritTypeId: 300,
AuthorityCulpritId: authorityCulpritIdFromDetectionRows(
options.get("detection-accident-culprits") ?? [],
),
CustomerFaultPercent: FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT,
RepairDuration: FANAVARAN_DEFAULT_HULL_REPAIR_DURATION,
};
if (product === "car-body") {
const price =
this.parseFanavaranMoney(claim?.vehicle?.carPrice) ||
this.parseFanavaranMoney(claim?.vehicle?.price) ||
this.parseFanavaranMoney(claim?.evaluation?.priceDrop?.carPrice) ||
(await this.resolveHullVehicleCurrentValueFromPolicy(clientKey, claim));
if (price > 0) initial.VehicleCurrentValue = price;
}
return {
product,
version: claim.fanavaranFieldReview?.version ?? 0,
reviewedAt: claim.fanavaranFieldReview?.reviewedAt,
reviewedByActorName: claim.fanavaranFieldReview?.reviewedByActorName,
fields: definitions.map((field) => {
const sent = fanavaranFieldStageSent(claim, field.stage);
const sentValue = sent
? claim.fanavaranSync?.[field.stage]?.lastPayload?.[field.key]
: undefined;
const reviewedValue = claim.fanavaranFieldReview?.values?.[field.key];
const value = sentValue ?? reviewedValue ?? initial[field.key] ?? null;
const rows = field.lookup
? (options.get(field.lookup) ?? [])
: undefined;
return {
...field,
value,
source:
sentValue != null
? "submitted"
: reviewedValue != null
? "reviewed"
: "default",
editable: !sent,
...(field.lookup
? {
options: rows,
lookupUnavailable: !rows.length,
caption:
rows.find((row) => row.Id === value)?.Caption ??
(reviewedValue === value
? claim.fanavaranFieldReview?.captions?.[field.key]
: undefined),
}
: {}),
};
}),
};
}
private async getFanavaranLookupRows(
clientKey: FanavaranClientKey,
name: string,
@@ -6994,7 +7092,11 @@ export class ClaimRequestManagementService {
definition.url,
definition.cacheFile,
);
return Array.isArray(data) ? data : [];
let rows: unknown = data;
for (let level = 0; level < 3 && rows && !Array.isArray(rows) && typeof rows === "object"; level++) {
rows = (rows as { data?: unknown }).data;
}
return Array.isArray(rows) ? rows : [];
} catch {
this.logger.warn(
`Lookup "${name}" unavailable for ${clientKey}; returning empty.`,
@@ -7239,7 +7341,7 @@ export class ClaimRequestManagementService {
const priceDrop = input.claimCase.evaluation?.priceDrop ?? {};
const priceDropTotal = this.parseFanavaranMoney(priceDrop?.total);
const inspectionPlaceId = 282;
const inspectionPlaceId = input.claimCase?.fanavaranFieldReview?.values?.InspectionPlaceId ?? 282;
const dropAmountStatus = 5458;
const dmgSections = parts.map((part) =>
@@ -33,6 +33,7 @@ import {
ClaimWorkflowSchema,
} from "./claim-case.workflow.schema";
import { UserClaimRating } from "./claim-request-management.schema";
import type { FanavaranFieldReview } from "../../fanavaran-stage-fields";
import {
CaseInquiries,
CaseInquiriesSchema,
@@ -342,6 +343,10 @@ export class ClaimCase {
@Prop({ type: FanavaranVehicleReviewSchema })
fanavaranVehicleReview?: FanavaranVehicleReview;
/** Validated expert edits; separate stages lock after their remote creation. */
@Prop({ type: MongooseSchema.Types.Mixed })
fanavaranFieldReview?: FanavaranFieldReview;
@Prop({ type: ClaimDamageSelectionSchema, default: () => ({}) })
damage?: ClaimDamageSelection;
@@ -0,0 +1,197 @@
import type { FanavaranClaimProduct } from "./fanavaran-claim-product";
export type FanavaranFieldStage = "baseClaim" | "damageCase" | "expertise";
export type FanavaranFieldValues = Partial<
Record<FanavaranFieldKey, string | number>
>;
export type FanavaranFieldKey =
| "AccidentLocationAddress"
| "AccidentCityId"
| "AccidentReportTypeId"
| "DmgHistoryStatus"
| "InspectionPlaceId"
| "AccidentTypeId"
| "CulpritTypeId"
| "AuthorityCulpritId"
| "CustomerFaultPercent"
| "RepairDuration"
| "VehicleCurrentValue";
export interface FanavaranFieldReview {
values: FanavaranFieldValues;
captions: Partial<Record<FanavaranFieldKey, string>>;
version: number;
reviewedAt: Date;
reviewedByActorId: string;
reviewedByActorName?: string;
reviewedByRole: string;
}
export interface FanavaranStageFieldDefinition {
key: FanavaranFieldKey;
label: string;
stage: FanavaranFieldStage;
type: "text" | "lookup" | "number";
lookup?: string;
min?: number;
max?: number;
unit?: string;
optional?: boolean;
}
const common: FanavaranStageFieldDefinition[] = [
{
key: "AccidentLocationAddress",
label: "نشانی محل حادثه",
stage: "baseClaim",
type: "text",
},
{
key: "AccidentCityId",
label: "شهر محل حادثه",
stage: "baseClaim",
type: "lookup",
lookup: "cities",
},
{
key: "AccidentReportTypeId",
label: "نحوه اعلام حادثه",
stage: "baseClaim",
type: "lookup",
lookup: "accident-report-type",
},
];
export function fanavaranStageFields(
product: FanavaranClaimProduct,
): FanavaranStageFieldDefinition[] {
return product === "car-body"
? [
...common,
{
key: "AccidentTypeId",
label: "نوع حادثه بدنه",
stage: "baseClaim",
type: "lookup",
lookup: "vehicle-hull-accident-types",
},
{
key: "CulpritTypeId",
label: "نوع مقصر بدنه",
stage: "baseClaim",
type: "lookup",
lookup: "vehicle-hull-accident-culprit-type",
},
{
key: "AuthorityCulpritId",
label: "مرجع تعیین مقصر",
stage: "baseClaim",
type: "lookup",
lookup: "detection-accident-culprits",
},
{
key: "CustomerFaultPercent",
label: "درصد تقصیر بیمه‌گذار",
stage: "baseClaim",
type: "number",
min: 0,
max: 100,
unit: "درصد",
},
{
key: "RepairDuration",
label: "مدت تعمیر",
stage: "expertise",
type: "number",
min: 1,
unit: "روز",
},
{
key: "VehicleCurrentValue",
label: "ارزش روز خودرو",
stage: "expertise",
type: "number",
min: 1,
unit: "ریال",
optional: true,
},
]
: [
...common,
{
key: "DmgHistoryStatus",
label: "وضعیت سابقه خسارت",
stage: "damageCase",
type: "lookup",
lookup: "dmg-history-status",
},
{
key: "InspectionPlaceId",
label: "محل بازدید",
stage: "expertise",
type: "lookup",
lookup: "inspection-place",
},
];
}
export function fanavaranFieldStageSent(
claim: any,
stage: FanavaranFieldStage,
): boolean {
const id = {
baseClaim: "claimId",
damageCase: "dmgCaseId",
expertise: "expertiseId",
}[stage];
return (
claim?.[id] != null ||
claim?.fanavaranSync?.[stage]?.[id] != null ||
claim?.fanavaranSync?.[stage]?.status === "success" ||
(stage === "baseClaim" && claim?.claimNo != null)
);
}
/** Strict codebook IDs, never provider legacy codes or guessed captions. */
export function activeStageLookupRows(
raw: unknown,
): Array<{ Id: number; Caption: string }> {
let value = raw;
for (
let level = 0;
level < 3 && value && !Array.isArray(value) && typeof value === "object";
level++
) {
value = (value as { data?: unknown }).data;
}
if (!Array.isArray(value)) return [];
return value
.filter(
(row) =>
row &&
typeof row === "object" &&
row.IsActive !== false &&
Number(row.IsActive) !== 0 &&
Number.isSafeInteger(Number(row.Id)) &&
Number(row.Id) > 0 &&
typeof row.Caption === "string" &&
row.Caption.trim(),
)
.map((row) => ({ Id: Number(row.Id), Caption: row.Caption.trim() }))
.sort((a, b) => a.Caption.localeCompare(b.Caption, "fa"));
}
/** Apply only applicable, reviewed fields at their own outbound stage. */
export function applyFanavaranStageFieldReview(
payload: Record<string, unknown>,
claim: any,
product: FanavaranClaimProduct,
stage: FanavaranFieldStage,
): void {
const values = claim?.fanavaranFieldReview?.values;
if (!values) return;
for (const field of fanavaranStageFields(product)) {
const value = values[field.key];
if (field.stage === stage && value != null) payload[field.key] = value;
}
}
@@ -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", () => {