forked from Yara724/api
Added AI damage estimation
This commit is contained in:
@@ -0,0 +1,233 @@
|
||||
import { BadRequestException } from "@nestjs/common";
|
||||
import {
|
||||
coerceDamagedPartsMediaToArray,
|
||||
normalizeDamageSelectedParts,
|
||||
} from "src/helpers/outer-damage-parts";
|
||||
import { resolveClaimBeneficiary } from "src/helpers/blame-claim-eligibility";
|
||||
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 beneficiary = blame ? resolveClaimBeneficiary(blame) : null;
|
||||
const beneficiaryId =
|
||||
beneficiary?.person?.userId ?? claim?.damagedPartyUserId;
|
||||
const sourceParties = blame?.parties?.length
|
||||
? blame.parties
|
||||
: claim?.snapshot?.parties;
|
||||
const party =
|
||||
beneficiary ??
|
||||
sourceParties?.find(
|
||||
(p: any) =>
|
||||
beneficiaryId && String(p.person?.userId) === String(beneficiaryId),
|
||||
);
|
||||
const vehicle = party?.vehicle ?? {};
|
||||
const inquiry = vehicle.inquiry?.mapped ?? vehicle.inquiry ?? {};
|
||||
// FIRST inquiry on a third-party claim belongs to the culprit. Use only the resolved damaged party's role.
|
||||
const policy = party?.role
|
||||
? (claim?.inquiries?.carBody?.data?.[party.role]?.mapped ??
|
||||
claim?.inquiries?.thirdParty?.data?.[party.role]?.mapped ??
|
||||
{})
|
||||
: {};
|
||||
const review = claim?.fanavaranVehicleReview?.approved
|
||||
? claim.fanavaranVehicleReview
|
||||
: {};
|
||||
const isBeneficiaryOwner =
|
||||
beneficiaryId && String(claim?.owner?.userId) === String(beneficiaryId);
|
||||
// An absent blame record does not make a historical culprit-owned snapshot safe.
|
||||
// Only standalone legacy claims can use their owner as the beneficiary fallback.
|
||||
const standaloneOwner =
|
||||
!claim?.blameRequestId &&
|
||||
!blame &&
|
||||
!claim?.snapshot?.parties?.length &&
|
||||
!beneficiaryId &&
|
||||
!!claim?.owner?.userId;
|
||||
const snapshot =
|
||||
isBeneficiaryOwner || standaloneOwner ? (claim?.vehicle ?? {}) : {};
|
||||
const bodyType = text(snapshot.carType ?? vehicle.type);
|
||||
const cleanName = (raw: unknown) =>
|
||||
text(raw) === bodyType ? null : text(raw);
|
||||
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 (
|
||||
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:
|
||||
text(review.vehicleSystem?.caption) ??
|
||||
cleanName(vehicle.name) ??
|
||||
text(inquiry.SystemField ?? inquiry.MapTypNam) ??
|
||||
text(policy.SystemField ?? policy.MapTypNam) ??
|
||||
cleanName(snapshot.carName),
|
||||
model:
|
||||
text(review.vehicleKind?.caption) ??
|
||||
cleanName(vehicle.model) ??
|
||||
text(inquiry.TypeField ?? policy.TypeField) ??
|
||||
cleanName(snapshot.carModel),
|
||||
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),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user