forked from Yara724/api
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:
@@ -5,7 +5,7 @@ import { ExpertInsurerController } from "src/expert-insurer/expert-insurer.contr
|
||||
|
||||
describe("AI analysis file access", () => {
|
||||
const actor = { sub: "actor", clientKey: "tenant" };
|
||||
it.each(["getAiAnalysis", "retryAiAnalysis"])(
|
||||
it.each(["getAiAnalysis", "retryAiAnalysis", "estimateAiAnalysis"])(
|
||||
"expert %s uses the existing file access gate before reading results or scheduling work",
|
||||
async (method) => {
|
||||
const service = {
|
||||
|
||||
@@ -8,6 +8,9 @@ export class AiJob {
|
||||
@Prop({ required: true }) imageKey: string;
|
||||
@Prop({ required: true }) path: string;
|
||||
@Prop() fileName?: string;
|
||||
@Prop() carName?: string;
|
||||
@Prop({ default: false }) includePrices?: boolean;
|
||||
@Prop() priceMinSeverity?: string;
|
||||
@Prop({
|
||||
default: "queued",
|
||||
enum: ["queued", "processing", "completed", "failed"],
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { IsString, Matches, MaxLength, MinLength } from "class-validator";
|
||||
export class AiPricingRequestDto {
|
||||
@ApiProperty({
|
||||
description: "Current imageKey from the AI analysis response",
|
||||
})
|
||||
@IsString()
|
||||
@Matches(/^[a-f0-9]{64}$/, { message: "شناسه تصویر معتبر نیست." })
|
||||
imageKey: string;
|
||||
|
||||
@ApiProperty({
|
||||
example: "پژو ۲۰۶ تیپ ۲",
|
||||
description:
|
||||
"Expert-confirmed Persian make and model of the damaged vehicle",
|
||||
})
|
||||
@IsString({ message: "نام خودرو را به فارسی وارد کنید." })
|
||||
@MinLength(2, { message: "نام خودرو باید حداقل ۲ کاراکتر باشد." })
|
||||
@MaxLength(100, { message: "نام خودرو باید حداکثر ۱۰۰ کاراکتر باشد." })
|
||||
@Matches(/[آ-ی]/, { message: "نام خودرو را به فارسی وارد کنید." })
|
||||
carName: string;
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
import { validateSync } from "class-validator";
|
||||
import { EnvironmentVariables } from "src/core/config/config.schema";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
ServiceUnavailableException,
|
||||
} from "@nestjs/common";
|
||||
import { normalizePartPrice, normalizePricing } from "./ai-pricing";
|
||||
import { normalizeAiResult } from "./ai-result";
|
||||
import { AiService, aiImageKey } from "./ai.service";
|
||||
const raw = {
|
||||
status: "estimated",
|
||||
currency: "toman",
|
||||
totals: { overall: 120000, genuine: 200000, aftermarket: 100000 },
|
||||
components: [
|
||||
{
|
||||
name: "Mirror",
|
||||
overall: {
|
||||
count: 3,
|
||||
min: 100000,
|
||||
median: 120000,
|
||||
max: 200000,
|
||||
wide_spread: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
repair_estimate: { amount: 20000, is_llm_guess: true },
|
||||
confidence: "low",
|
||||
sources: [
|
||||
{ price: 120000, url: "https://shop.example/part", used: true },
|
||||
{ price: 100000, url: "javascript:alert(1)", used: false },
|
||||
],
|
||||
};
|
||||
describe("assessment market pricing", () => {
|
||||
it("converts every monetary field to rials once, including ranges, repair and sources", () => {
|
||||
const price = normalizePartPrice(raw)!;
|
||||
expect(price.currency).toBe("rial");
|
||||
expect(price.originalCurrency).toBe("toman");
|
||||
expect(price.totals).toEqual({
|
||||
overall: 1200000,
|
||||
genuine: 2000000,
|
||||
aftermarket: 1000000,
|
||||
});
|
||||
expect(price.components[0].overall).toEqual({
|
||||
count: 3,
|
||||
min: 1000000,
|
||||
median: 1200000,
|
||||
max: 2000000,
|
||||
wideSpread: true,
|
||||
});
|
||||
expect(price.repairEstimate).toEqual({ amount: 200000, isLlmGuess: true });
|
||||
expect(price.sources[0]).toMatchObject({ price: 1200000, used: true });
|
||||
expect(price.sources[1].url).toBeNull();
|
||||
expect(
|
||||
normalizePartPrice({ ...raw, currency: "rial" })!.totals.overall,
|
||||
).toBe(120000);
|
||||
});
|
||||
it("does not turn missing, unsafe or unsupported amounts into zero", () => {
|
||||
for (const value of [
|
||||
null,
|
||||
undefined,
|
||||
"100",
|
||||
-1,
|
||||
Infinity,
|
||||
Number.MAX_SAFE_INTEGER,
|
||||
])
|
||||
expect(
|
||||
normalizePartPrice({ ...raw, totals: { overall: value } })!.totals
|
||||
.overall,
|
||||
).toBeNull();
|
||||
expect(
|
||||
normalizePartPrice({ ...raw, currency: "usd" })!.totals.overall,
|
||||
).toBeNull();
|
||||
expect(
|
||||
normalizePartPrice({ ...raw, totals: { overall: 0 } })!.totals.overall,
|
||||
).toBe(0);
|
||||
});
|
||||
it("retains partial summary, detection boxes, pricing metadata and provider cost without converting dollars", () => {
|
||||
const pricing = {
|
||||
car: "پژو ۲۰۶",
|
||||
min_severity: "severe",
|
||||
currency: "toman",
|
||||
totals: { overall: 120000 },
|
||||
complete: false,
|
||||
priced_parts: 1,
|
||||
unpriced_parts: 2,
|
||||
model: "price-model",
|
||||
cost_usd: 0.05,
|
||||
duration_ms: 1200,
|
||||
};
|
||||
expect(normalizePricing(pricing)).toMatchObject({
|
||||
complete: false,
|
||||
pricedParts: 1,
|
||||
unpricedParts: 2,
|
||||
costUsd: 0.05,
|
||||
totals: { overall: 1200000 },
|
||||
});
|
||||
const result = normalizeAiResult({
|
||||
request_id: "r1",
|
||||
pipeline: { price_model: "p1" },
|
||||
damaged_parts: [
|
||||
{
|
||||
part: "Mirror",
|
||||
localized: true,
|
||||
evidence: [
|
||||
{
|
||||
image_index: 0,
|
||||
link_status: "linked",
|
||||
part: { box: { x1: 1, y1: 2, x2: 10, y2: 20 } },
|
||||
},
|
||||
],
|
||||
price: raw,
|
||||
},
|
||||
],
|
||||
case_report: "گزارش",
|
||||
pricing,
|
||||
});
|
||||
expect(result.parts[0].bbox).toEqual({ x1: 1, y1: 2, x2: 10, y2: 20 });
|
||||
expect(result.parts[0].price?.totals.overall).toBe(1200000);
|
||||
expect(result.pipeline?.price_model).toBe("p1");
|
||||
});
|
||||
});
|
||||
function setup(enabled = true, severity = "moderate") {
|
||||
const jobs = {
|
||||
updateMany: jest.fn().mockResolvedValue({}),
|
||||
updateOne: jest.fn().mockResolvedValue({ matchedCount: 1 }),
|
||||
find: jest.fn().mockReturnValue({ lean: async () => [] }),
|
||||
};
|
||||
const service = new AiService(
|
||||
new ConfigService({
|
||||
AI_DAMAGE_ENABLED: String(enabled),
|
||||
AI_DAMAGE_PRICE_MIN_SEVERITY: severity,
|
||||
}),
|
||||
jobs as any,
|
||||
);
|
||||
return { service, jobs };
|
||||
}
|
||||
const images = [{ path: "files/current.jpg" }];
|
||||
const input = { imageKey: aiImageKey(images[0].path), carName: "پژو ۲۰۶" };
|
||||
describe("explicit assessment pricing requests", () => {
|
||||
it("requires enabled service, a current photo and a usable Persian car name before queuing", async () => {
|
||||
await expect(
|
||||
setup(false).service.requestPricing("c1", images, input),
|
||||
).rejects.toThrow(ServiceUnavailableException);
|
||||
for (const carName of ["", "sedan", "FAW 111", "الف".repeat(50)])
|
||||
await expect(
|
||||
setup().service.requestPricing("c1", images, { ...input, carName }),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
await expect(
|
||||
setup().service.requestPricing("c1", images, {
|
||||
...input,
|
||||
imageKey: aiImageKey("files/removed.jpg"),
|
||||
}),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
});
|
||||
it("stores the input/threshold snapshot and atomically excludes running or already-priced queued jobs", async () => {
|
||||
const { service, jobs } = setup();
|
||||
await service.requestPricing("c1", images, input);
|
||||
expect(jobs.updateOne.mock.calls[1][0]).toMatchObject({
|
||||
claimId: "c1",
|
||||
imageKey: input.imageKey,
|
||||
status: { $ne: "processing" },
|
||||
$or: [{ status: { $ne: "queued" } }, { includePrices: { $ne: true } }],
|
||||
});
|
||||
expect(jobs.updateOne.mock.calls[1][1].$set).toMatchObject({
|
||||
carName: "پژو ۲۰۶",
|
||||
includePrices: true,
|
||||
priceMinSeverity: "moderate",
|
||||
status: "queued",
|
||||
});
|
||||
jobs.updateOne.mockResolvedValue({ matchedCount: 0 });
|
||||
await expect(service.requestPricing("c1", images, input)).rejects.toThrow(
|
||||
ConflictException,
|
||||
);
|
||||
});
|
||||
it("adapts deployment null to provider-supported minor", () =>
|
||||
expect(setup(true, "null").service.priceMinSeverity).toBe("minor"));
|
||||
});
|
||||
|
||||
describe("viewer pricing retry boundaries", () => {
|
||||
it("excludes price requests when an insurer/admin retries detection", async () => {
|
||||
const { service, jobs } = setup();
|
||||
await service.retry("c1", images, false);
|
||||
expect(jobs.updateMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ includePrices: { $ne: true } }),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("assessment severity environment", () => {
|
||||
it.each(["minor", "moderate", "severe", "null"])("accepts %s", (value) => {
|
||||
const errors = validateSync(
|
||||
Object.assign(new EnvironmentVariables(), {
|
||||
AI_DAMAGE_PRICE_MIN_SEVERITY: value,
|
||||
}),
|
||||
{ skipMissingProperties: true },
|
||||
);
|
||||
expect(
|
||||
errors.some((error) => error.property === "AI_DAMAGE_PRICE_MIN_SEVERITY"),
|
||||
).toBe(false);
|
||||
});
|
||||
it("rejects unrecognized severity before deployment starts", () => {
|
||||
const errors = validateSync(
|
||||
Object.assign(new EnvironmentVariables(), {
|
||||
AI_DAMAGE_PRICE_MIN_SEVERITY: "typo",
|
||||
}),
|
||||
{ skipMissingProperties: true },
|
||||
);
|
||||
expect(
|
||||
errors.some((error) => error.property === "AI_DAMAGE_PRICE_MIN_SEVERITY"),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
/** Market prices are normalized from the provider's tomans to the panel's rials. */
|
||||
export interface AiPriceTotals {
|
||||
overall: number | null;
|
||||
genuine: number | null;
|
||||
aftermarket: number | null;
|
||||
}
|
||||
export interface AiPriceStats {
|
||||
count: number | null;
|
||||
min: number | null;
|
||||
median: number | null;
|
||||
max: number | null;
|
||||
wideSpread: boolean;
|
||||
}
|
||||
export interface AiPartPrice {
|
||||
status: string;
|
||||
message: string | null;
|
||||
query: { car: string | null; part: string | null };
|
||||
currency: "rial";
|
||||
originalCurrency: string | null;
|
||||
totals: AiPriceTotals;
|
||||
components: Array<{
|
||||
name: string | null;
|
||||
overall: AiPriceStats;
|
||||
genuine: AiPriceStats;
|
||||
aftermarket: AiPriceStats;
|
||||
}>;
|
||||
repairEstimate: { amount: number | null; isLlmGuess: boolean } | null;
|
||||
confidence: string | null;
|
||||
notes: string | null;
|
||||
sources: Array<{
|
||||
component: string | null;
|
||||
kind: string | null;
|
||||
price: number | null;
|
||||
title: string | null;
|
||||
url: string | null;
|
||||
used: boolean;
|
||||
unusedReason: string | null;
|
||||
}>;
|
||||
cached: boolean;
|
||||
}
|
||||
export interface AiPricing {
|
||||
car: string | null;
|
||||
minSeverity: string | null;
|
||||
currency: "rial";
|
||||
originalCurrency: string | null;
|
||||
totals: AiPriceTotals;
|
||||
complete: boolean;
|
||||
pricedParts: number | null;
|
||||
unpricedParts: number | null;
|
||||
model: string | null;
|
||||
costUsd: number | null;
|
||||
durationMs: number | null;
|
||||
}
|
||||
const text = (value: unknown) =>
|
||||
typeof value === "string" ? value.trim().slice(0, 2000) : null;
|
||||
const nonnegative = (value: unknown): number | null =>
|
||||
typeof value === "number" && Number.isFinite(value) && value >= 0
|
||||
? value
|
||||
: null;
|
||||
const count = (value: unknown) =>
|
||||
Number.isSafeInteger(value) && (value as number) >= 0
|
||||
? (value as number)
|
||||
: null;
|
||||
const money = (value: unknown, currency: unknown) => {
|
||||
const n = nonnegative(value);
|
||||
if (n === null || !["toman", "rial"].includes(String(currency))) return null;
|
||||
const amount = currency === "toman" ? n * 10 : n;
|
||||
return amount <= Number.MAX_SAFE_INTEGER ? Math.round(amount) : null;
|
||||
};
|
||||
const totals = (value: any, currency: unknown): AiPriceTotals => ({
|
||||
overall: money(value?.overall, currency),
|
||||
genuine: money(value?.genuine, currency),
|
||||
aftermarket: money(value?.aftermarket, currency),
|
||||
});
|
||||
const stats = (value: any, currency: unknown): AiPriceStats => ({
|
||||
count: count(value?.count),
|
||||
min: money(value?.min, currency),
|
||||
median: money(value?.median, currency),
|
||||
max: money(value?.max, currency),
|
||||
wideSpread: value?.wide_spread === true,
|
||||
});
|
||||
const safeUrl = (value: unknown): string | null => {
|
||||
if (typeof value !== "string") return null;
|
||||
try {
|
||||
const u = new URL(value);
|
||||
return ["http:", "https:"].includes(u.protocol) &&
|
||||
!u.username &&
|
||||
!u.password
|
||||
? u.toString()
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
export function normalizePartPrice(raw: any): AiPartPrice | undefined {
|
||||
if (!raw || typeof raw !== "object" || typeof raw.status !== "string")
|
||||
return undefined;
|
||||
const currency = raw.currency;
|
||||
return {
|
||||
status: raw.status.slice(0, 100),
|
||||
message: text(raw.message),
|
||||
query: { car: text(raw.query?.car), part: text(raw.query?.part) },
|
||||
currency: "rial",
|
||||
originalCurrency: text(currency),
|
||||
totals: totals(raw.totals, currency),
|
||||
components: (Array.isArray(raw.components) ? raw.components : [])
|
||||
.slice(0, 100)
|
||||
.map((item: any) => ({
|
||||
name: text(item?.name),
|
||||
overall: stats(item?.overall, currency),
|
||||
genuine: stats(item?.genuine, currency),
|
||||
aftermarket: stats(item?.aftermarket, currency),
|
||||
})),
|
||||
repairEstimate: raw.repair_estimate
|
||||
? {
|
||||
amount: money(raw.repair_estimate.amount, currency),
|
||||
isLlmGuess: raw.repair_estimate.is_llm_guess === true,
|
||||
}
|
||||
: null,
|
||||
confidence: text(raw.confidence),
|
||||
notes: text(raw.notes),
|
||||
cached: raw.cached === true,
|
||||
sources: (Array.isArray(raw.sources) ? raw.sources : [])
|
||||
.slice(0, 200)
|
||||
.map((item: any) => ({
|
||||
component: text(item?.component),
|
||||
kind: text(item?.kind),
|
||||
price: money(item?.price, currency),
|
||||
title: text(item?.title),
|
||||
url: safeUrl(item?.url),
|
||||
used: item?.used === true,
|
||||
unusedReason: text(item?.unused_reason),
|
||||
})),
|
||||
};
|
||||
}
|
||||
export function normalizePricing(raw: any): AiPricing | undefined {
|
||||
if (!raw || typeof raw !== "object") return undefined;
|
||||
return {
|
||||
car: text(raw.car),
|
||||
minSeverity: text(raw.min_severity),
|
||||
currency: "rial",
|
||||
originalCurrency: text(raw.currency),
|
||||
totals: totals(raw.totals, raw.currency),
|
||||
complete: raw.complete === true,
|
||||
pricedParts: count(raw.priced_parts),
|
||||
unpricedParts: count(raw.unpriced_parts),
|
||||
model: text(raw.model),
|
||||
costUsd: nonnegative(raw.cost_usd),
|
||||
durationMs: nonnegative(raw.duration_ms),
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,11 @@
|
||||
import {
|
||||
AiPartPrice,
|
||||
AiPricing,
|
||||
normalizePartPrice,
|
||||
normalizePricing,
|
||||
} from "./ai-pricing";
|
||||
export interface AiPart {
|
||||
price?: AiPartPrice;
|
||||
name: string;
|
||||
severity: string | null;
|
||||
confidence: number | null;
|
||||
@@ -22,6 +29,7 @@ export interface AiEvidence {
|
||||
polygon: [number, number][] | null;
|
||||
}
|
||||
export interface AiResult {
|
||||
pricing?: AiPricing;
|
||||
parts: AiPart[];
|
||||
report: string;
|
||||
caseReport: string;
|
||||
@@ -131,6 +139,7 @@ function normalizeAssessment(raw: any): AiResult {
|
||||
const firstBox = evidence.find((item) => item.bbox);
|
||||
return {
|
||||
name,
|
||||
price: normalizePartPrice(part.price),
|
||||
severity: text(part.severity),
|
||||
confidence: firstBox?.confidence ?? null,
|
||||
side: text(part.side),
|
||||
@@ -147,10 +156,12 @@ function normalizeAssessment(raw: any): AiResult {
|
||||
report: "",
|
||||
caseReport: text(raw.case_report) ?? "",
|
||||
requestId: text(raw.request_id),
|
||||
pricing: normalizePricing(raw.pricing),
|
||||
pipeline: Object.fromEntries(
|
||||
[
|
||||
"version",
|
||||
"vlm_model",
|
||||
"price_model",
|
||||
"prompt_version",
|
||||
"part_model_sha256",
|
||||
"car_model_sha256",
|
||||
|
||||
@@ -5,7 +5,7 @@ import { AiAssessmentError } from "./ai-result";
|
||||
|
||||
const image = { path: "files/part.jpg", label: "گلگیر" };
|
||||
const result = { parts: [], report: "گزارش", caseReport: "گزارش کامل" };
|
||||
function setup(enabled = true) {
|
||||
function setup(enabled = true, severity = "severe") {
|
||||
const jobs = {
|
||||
updateOne: jest.fn().mockResolvedValue({}),
|
||||
updateMany: jest.fn().mockResolvedValue({}),
|
||||
@@ -18,6 +18,7 @@ function setup(enabled = true) {
|
||||
AI_DAMAGE_ENABLED: String(enabled),
|
||||
AI_DAMAGE_URL: "http://example.test",
|
||||
AI_DAMAGE_TIMEOUT_MS: 1000,
|
||||
AI_DAMAGE_PRICE_MIN_SEVERITY: severity,
|
||||
});
|
||||
return { service: new AiService(config, jobs as any), jobs };
|
||||
}
|
||||
@@ -236,12 +237,20 @@ describe("AI multipart transport", () => {
|
||||
path === resolve("files")
|
||||
? Promise.resolve(root)
|
||||
: realpath(path)) as any);
|
||||
let pricedRequest = false;
|
||||
const post = jest
|
||||
.spyOn(axios, "post")
|
||||
.mockImplementation(async (url, form: any, config) => {
|
||||
const parsed = new URL(String(url));
|
||||
expect(parsed.pathname).toBe("/api/v1/assessments");
|
||||
expect(parsed.search).toBe("");
|
||||
expect(parsed.searchParams.get("include_polygons")).toBe("false");
|
||||
expect(parsed.searchParams.get("include_prices")).toBe(
|
||||
pricedRequest ? "true" : "false",
|
||||
);
|
||||
if (pricedRequest)
|
||||
expect(parsed.searchParams.get("price_min_severity")).toBe(
|
||||
"moderate",
|
||||
);
|
||||
expect(config?.headers?.["content-type"]).toMatch(
|
||||
/^multipart\/form-data; boundary=/,
|
||||
);
|
||||
@@ -260,6 +269,10 @@ describe("AI multipart transport", () => {
|
||||
body.includes(Buffer.from('name="images"; filename="test.jpg"')),
|
||||
).toBe(true);
|
||||
expect(body.includes(bytes)).toBe(true);
|
||||
if (pricedRequest) {
|
||||
expect(body.includes(Buffer.from('name="car"'))).toBe(true);
|
||||
expect(body.includes(Buffer.from("پژو ۲۰۶"))).toBe(true);
|
||||
}
|
||||
return {
|
||||
data: {
|
||||
request_id: "req-123",
|
||||
@@ -286,6 +299,14 @@ describe("AI multipart transport", () => {
|
||||
|
||||
await fs.writeFile(file, bytes);
|
||||
const { AxiosError } = await import("axios");
|
||||
pricedRequest = true;
|
||||
await service.aiRequestImage({
|
||||
path: file,
|
||||
carName: "پژو ۲۰۶",
|
||||
includePrices: true,
|
||||
priceMinSeverity: "moderate",
|
||||
});
|
||||
pricedRequest = false;
|
||||
post.mockRejectedValueOnce(
|
||||
new AxiosError("Rejected", undefined, undefined, undefined, {
|
||||
status: 422,
|
||||
|
||||
+97
-1
@@ -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),
|
||||
|
||||
Reference in New Issue
Block a user