Files
yara724api/src/price-estimation/price-estimation-context.ts
T

194 lines
6.1 KiB
TypeScript

import { BadRequestException } from "@nestjs/common";
import {
coerceDamagedPartsMediaToArray,
normalizeDamageSelectedParts,
} from "src/helpers/outer-damage-parts";
import { resolveClaimVehicleSources } from "src/helpers/claim-vehicle-identity";
import {
CreatePriceEstimateDto,
EstimatePartQuality,
} from "./price-estimation.dto";
import {
EstimateContext,
EstimatePart,
EstimatePhoto,
} from "./price-estimation.types";
const text = (value: unknown, limit = 250): string | null =>
typeof value === "string" && value.trim()
? value.trim().slice(0, limit)
: null;
const positive = (value: unknown): number | null => {
if (value == null || value === "") return null;
const n = Number(value);
return Number.isSafeInteger(n) && n > 0 ? n : null;
};
export function estimateDate(date = new Date()): string {
const parts = new Intl.DateTimeFormat("en-CA", {
timeZone: "Asia/Tehran",
year: "numeric",
month: "2-digit",
day: "2-digit",
}).formatToParts(date);
const get = (name: string) => parts.find((part) => part.type === name)?.value;
return `${get("year")}-${get("month")}-${get("day")}`;
}
/** Project only price-relevant fields. Never forward raw inquiries, identity, VIN, plates, policy or payment data. */
export function buildEstimateContext(
claim: any,
blame: any,
options: CreatePriceEstimateDto,
now = new Date(),
): EstimateContext {
const { party, vehicle, inquiry, policy, snapshot, review, identity } =
resolveClaimVehicleSources(claim, blame);
const bodyType = text(snapshot.carType ?? vehicle.type);
const rawYear =
options.modelYear ??
positive(
inquiry.ModelField ??
inquiry.ModelCii ??
policy.ModelField ??
policy.ModelCii,
);
const year = rawYear && rawYear >= 1300 && rawYear <= 2100 ? rawYear : null;
const knownValue =
options.currentMarketValueRial ??
positive(claim?.fanavaranFieldReview?.values?.VehicleCurrentValue);
const normalized = normalizeDamageSelectedParts(
claim?.damage?.selectedParts,
claim?.vehicle?.carType,
claim?.damage?.selectedOuterParts,
);
const parts: EstimatePart[] = normalized.map((part, i) => ({
partKey: `outer:${i}`,
catalogId: part.id,
name: text(part.name) ?? "",
label: text(part.label_fa) ?? "",
side: text(part.side, 100) ?? "",
kind: "outer",
}));
for (const [i, name] of [
...new Set<string>(
(claim?.damage?.otherParts ?? []).filter(
(v: unknown) => typeof v === "string" && v.trim(),
),
),
].entries()) {
parts.push({
partKey: `other:${i}`,
catalogId: null,
name: text(name) ?? "",
label: text(name) ?? "",
side: "",
kind: "other",
});
}
if (!parts.length)
throw new BadRequestException(
"Select damaged parts before requesting a price estimate.",
);
if (parts.length > 40)
throw new BadRequestException(
"The MVP supports at most 40 damaged parts per estimate.",
);
const media = coerceDamagedPartsMediaToArray(
claim?.media?.damagedParts,
normalized,
);
const photos: EstimatePhoto[] = [];
for (const [i, part] of normalized.entries()) {
const row =
media.find(
(m) =>
(part.id != null && m.id === part.id) ||
(part.catalogKey && m.catalogKey === part.catalogKey) ||
(m.name === part.name && String(m.side ?? "") === part.side),
) ??
(media[i] && !media[i].id && !media[i].name && !media[i].catalogKey
? media[i]
: null);
if (typeof row?.path === "string" && row.path.trim())
photos.push({
path: row.path,
photoKey: `photo:${photos.length}`,
partKey: parts[i].partKey,
label: parts[i].label,
kind: "damage",
});
}
const angles = claim?.media?.carAngles;
for (const angle of ["front", "back", "left", "right"]) {
const row = angles instanceof Map ? angles.get(angle) : angles?.[angle];
if (
typeof row?.path === "string" &&
row.path.trim() &&
!photos.some((p) => p.path === row.path)
)
photos.push({
path: row.path,
photoKey: `photo:${photos.length}`,
partKey: null,
label: `vehicle-${angle}`,
kind: "angle",
});
}
const warnings: string[] = [];
if (!party)
warnings.push(
"هویت خودروی زیان‌دیده در اطلاعات طرفین مشخص نیست؛ نام یا مدل خودرو ممکن است ناقص باشد.",
);
if (identity.conflictingNames)
warnings.push(
"نام خودرو در فیلدهای استعلام هم‌خوان نیست؛ تیپ تأییدنشده ارسال نشد و اطلاعات خودرو نیاز به بررسی کارشناس دارد.",
);
if (
parts.some(
(part) => !photos.some((photo) => photo.partKey === part.partKey),
)
)
warnings.push(
"بعضی قطعات تصویر اختصاصی ندارند؛ شدت خسارت آن‌ها ممکن است به بازدید نیاز داشته باشد.",
);
return {
asOfDate: estimateDate(now),
market: {
country: "Iran",
currency: "IRR",
city: text(options.city, 100),
partQuality: options.partQuality ?? EstimatePartQuality.OEM,
},
vehicle: {
make: identity.name ?? null,
model: identity.model ?? null,
bodyType,
vehicleSystemId: positive(review.vehicleSystem?.id),
vehicleKindId: positive(review.vehicleKind?.id),
modelYear: year,
yearCalendar: year ? (year >= 1900 ? "gregorian" : "jalali") : null,
mileageKm: options.mileageKm ?? null,
currentMarketValueRial: knownValue ?? null,
valueSource:
options.currentMarketValueRial != null
? "request"
: knownValue
? "expert_record"
: null,
insuredValueRial: positive(snapshot.carPrice ?? policy.VehicleValue),
condition: text(options.vehicleCondition, 1000),
},
parts,
photos,
warnings,
};
}
export function publicEstimateContext(context: EstimateContext) {
return {
...context,
photos: context.photos.map(({ path, ...photo }) => photo),
};
}