feat: replace OpenAI pricing with AI assessment estimates

Extend durable image assessments with explicit Persian vehicle names, deployment severity settings and advisory market prices normalized to rials. Preserve case access and retry boundaries, and remove the retired OpenAI pricing module and routes.
This commit is contained in:
SepehrYahyaee
2026-11-08 10:52:45 +03:30
parent a8bb0d8e35
commit 755e921c08
32 changed files with 638 additions and 2702 deletions
+97 -1
View File
@@ -3,6 +3,9 @@ import { createReadStream } from "node:fs";
import { realpath, stat } from "node:fs/promises";
import { basename, resolve, sep } from "node:path";
import {
BadRequestException,
ConflictException,
ServiceUnavailableException,
Injectable,
Logger,
OnModuleDestroy,
@@ -21,6 +24,9 @@ export interface AiCapture {
path: string;
fileName?: string;
label?: string;
carName?: string;
includePrices?: boolean;
priceMinSeverity?: string;
}
export const aiImageKey = (path: string) =>
createHash("sha256").update(resolve(path)).digest("hex");
@@ -40,6 +46,12 @@ export class AiService implements OnModuleInit, OnModuleDestroy {
get enabled() {
return this.config.get<string>("AI_DAMAGE_ENABLED") === "true";
}
get priceMinSeverity(): string {
const value =
this.config.get<string>("AI_DAMAGE_PRICE_MIN_SEVERITY") ?? "severe";
return value === "null" ? "minor" : value;
}
private get timeout() {
return Math.min(
600000,
@@ -99,6 +111,7 @@ export class AiService implements OnModuleInit, OnModuleDestroy {
const byKey = new Map(rows.map((row) => [row.imageKey, row]));
return {
enabled: this.enabled,
priceMinSeverity: this.priceMinSeverity,
images: images.map((image) => {
const key = aiImageKey(image.path);
const job = byKey.get(key);
@@ -108,6 +121,9 @@ export class AiService implements OnModuleInit, OnModuleDestroy {
imageUrl: buildFileLink(image.path),
status: job?.status ?? (this.enabled ? "queued" : "disabled"),
attempts: job?.attempts ?? 0,
pricingRequested: job?.includePrices === true,
pricingCarName: job?.carName,
pricingMinSeverity: job?.priceMinSeverity,
completedAt: job?.completedAt,
error: job?.error,
errorCode: job?.errorCode,
@@ -118,13 +134,14 @@ export class AiService implements OnModuleInit, OnModuleDestroy {
};
}
async retry(claimId: string, images: AiCapture[]) {
async retry(claimId: string, images: AiCapture[], allowPricing = true) {
if (this.enabled)
await this.jobs.updateMany(
{
claimId,
imageKey: { $in: images.map((image) => aiImageKey(image.path)) },
status: "failed",
...(!allowPricing ? { includePrices: { $ne: true } } : {}),
},
{
$set: { status: "queued", attempts: 0, nextAttemptAt: new Date() },
@@ -140,6 +157,69 @@ export class AiService implements OnModuleInit, OnModuleDestroy {
return this.list(claimId, images);
}
/** Explicit advisory request: never maps AI part names or writes claim valuations. */
async requestPricing(
claimId: string,
images: AiCapture[],
input: { imageKey: string; carName: string },
) {
if (!this.enabled)
throw new ServiceUnavailableException(
"سرویس تحلیل هوش مصنوعی در این محیط غیرفعال است.",
);
const carName =
typeof input?.carName === "string" ? input.carName.trim() : "";
if (
carName.length < 2 ||
carName.length > 100 ||
!/[آ-ی]/.test(carName) ||
/[\r\n\x00-\x1f]/.test(carName)
)
throw new BadRequestException(
"نام و مدل خودروی زیان‌دیده را به فارسی و حداکثر در ۱۰۰ کاراکتر وارد کنید.",
);
const image = images.find(
(item) => aiImageKey(item.path) === input?.imageKey,
);
if (!image)
throw new BadRequestException(
"تصویر انتخاب‌شده متعلق به تصاویر فعلی این پرونده نیست. صفحه را تازه کنید.",
);
await this.enqueue(claimId, image);
const change = await this.jobs.updateOne(
{
claimId,
imageKey: input.imageKey,
status: { $ne: "processing" },
$or: [{ status: { $ne: "queued" } }, { includePrices: { $ne: true } }],
},
{
$set: {
status: "queued",
includePrices: true,
carName,
priceMinSeverity: this.priceMinSeverity,
attempts: 0,
nextAttemptAt: new Date(),
},
$unset: {
result: 1,
completedAt: 1,
error: 1,
errorCode: 1,
errorRequestId: 1,
leaseToken: 1,
leaseUntil: 1,
},
},
);
if (!change.matchedCount)
throw new ConflictException(
"تحلیل این تصویر در صف یا در حال اجراست. پس از پایان آن دوباره تلاش کنید.",
);
return this.list(claimId, images);
}
async aiRequestImage(file: AiCapture, signal?: AbortSignal) {
// Only local managed uploads; never fetch a supplied URL or arbitrary server file.
const root = await realpath(resolve("files"));
@@ -154,7 +234,23 @@ export class AiService implements OnModuleInit, OnModuleDestroy {
const base = this.config.get<string>("AI_DAMAGE_URL");
if (!base) throw new Error("AI_DAMAGE_URL is required");
const url = new URL("/api/v1/assessments", base);
url.searchParams.set("include_polygons", "false");
url.searchParams.set(
"include_prices",
file.includePrices ? "true" : "false",
);
if (file.includePrices) {
if (!file.carName)
throw new BadRequestException(
"نام فارسی خودرو برای برآورد قیمت لازم است.",
);
url.searchParams.set(
"price_min_severity",
file.priceMinSeverity || this.priceMinSeverity,
);
}
const form = new FormData();
if (file.includePrices) form.append("car", file.carName!);
const stream = createReadStream(path);
form.append("images", stream, {
filename: file.fileName || basename(path),