forked from Yara724/api
Added AI damage helper
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
import { SuperAdminController } from "src/super-admin/super-admin.controller";
|
||||
import { ForbiddenException } from "@nestjs/common";
|
||||
import { ExpertClaimV2Controller } from "src/expert-claim/expert-claim.v2.controller";
|
||||
import { ExpertInsurerController } from "src/expert-insurer/expert-insurer.controller";
|
||||
|
||||
describe("AI analysis file access", () => {
|
||||
const actor = { sub: "actor", clientKey: "tenant" };
|
||||
it.each(["getAiAnalysis", "retryAiAnalysis"])(
|
||||
"expert %s uses the existing file access gate before reading results or scheduling work",
|
||||
async (method) => {
|
||||
const service = {
|
||||
getClaimDetailV2: jest.fn().mockRejectedValue(new ForbiddenException()),
|
||||
};
|
||||
const ai = { list: jest.fn(), retry: jest.fn() },
|
||||
db = { findById: jest.fn() };
|
||||
const controller = new ExpertClaimV2Controller(
|
||||
service as any,
|
||||
ai as any,
|
||||
db as any,
|
||||
{} as any,
|
||||
);
|
||||
await expect(controller[method]("other-tenant", actor)).rejects.toThrow(
|
||||
ForbiddenException,
|
||||
);
|
||||
expect(db.findById).not.toHaveBeenCalled();
|
||||
expect(ai.list).not.toHaveBeenCalled();
|
||||
expect(ai.retry).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
it.each(["getAiAnalysis", "retryAiAnalysis"])(
|
||||
"insurer %s validates its public file identifier before resolving a claim",
|
||||
async (method) => {
|
||||
const service = {
|
||||
retrieveFileDetailsByPublicId: jest
|
||||
.fn()
|
||||
.mockRejectedValue(new ForbiddenException()),
|
||||
};
|
||||
const ai = { list: jest.fn(), retry: jest.fn() },
|
||||
db = { findById: jest.fn() };
|
||||
const controller = new ExpertInsurerController(
|
||||
service as any,
|
||||
{} as any,
|
||||
ai as any,
|
||||
db as any,
|
||||
);
|
||||
await expect(controller[method](actor, "other-tenant")).rejects.toThrow(
|
||||
ForbiddenException,
|
||||
);
|
||||
expect(service.retrieveFileDetailsByPublicId).toHaveBeenCalledWith(
|
||||
"tenant",
|
||||
"other-tenant",
|
||||
);
|
||||
expect(db.findById).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("admin AI tenant selection", () => {
|
||||
it.each(["getAiAnalysis", "retryAiAnalysis"])(
|
||||
"%s resolves the file inside the selected tenant before reading AI results",
|
||||
async (method) => {
|
||||
const insurer = {
|
||||
retrieveFileDetailsByPublicId: jest
|
||||
.fn()
|
||||
.mockRejectedValue(new ForbiddenException()),
|
||||
};
|
||||
const ai = { list: jest.fn(), retry: jest.fn() },
|
||||
db = { findById: jest.fn() };
|
||||
const controller = new SuperAdminController(
|
||||
{} as any,
|
||||
{} as any,
|
||||
insurer as any,
|
||||
ai as any,
|
||||
db as any,
|
||||
);
|
||||
await expect(
|
||||
controller[method]("selected-client", "other-client-file"),
|
||||
).rejects.toThrow(ForbiddenException);
|
||||
expect(insurer.retrieveFileDetailsByPublicId).toHaveBeenCalledWith(
|
||||
"selected-client",
|
||||
"other-client-file",
|
||||
);
|
||||
expect(db.findById).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { Types } from "mongoose";
|
||||
import { ForbiddenException } from "@nestjs/common";
|
||||
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
|
||||
import { ClaimWorkflowStep } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum";
|
||||
|
||||
function setup() {
|
||||
const id = new Types.ObjectId(),
|
||||
userId = new Types.ObjectId().toString();
|
||||
const claim = {
|
||||
_id: id,
|
||||
owner: { fullName: "تست" },
|
||||
workflow: { currentStep: ClaimWorkflowStep.CAPTURE_PART_DAMAGES },
|
||||
damage: {
|
||||
selectedParts: [
|
||||
{ id: 123, name: "Fender", side: "Left", label_fa: "گلگیر" },
|
||||
],
|
||||
},
|
||||
media: {
|
||||
damagedParts: [
|
||||
{
|
||||
id: 123,
|
||||
name: "Fender",
|
||||
path: "files/previous.jpg",
|
||||
url: "/files/previous.jpg",
|
||||
},
|
||||
],
|
||||
carAngles: {},
|
||||
},
|
||||
};
|
||||
const service = Object.create(ClaimRequestManagementService.prototype) as any;
|
||||
const db = {
|
||||
findById: jest.fn().mockResolvedValue(claim),
|
||||
findByIdAndUpdate: jest.fn().mockResolvedValue(claim),
|
||||
};
|
||||
const ai = { enqueue: jest.fn().mockResolvedValue(undefined) };
|
||||
Object.assign(service, {
|
||||
claimCaseDbService: db,
|
||||
aiService: ai,
|
||||
resolveClaimEffectiveUserId: jest.fn().mockResolvedValue(userId),
|
||||
assertEffectiveUserIsDamagedPartyOnClaim: jest
|
||||
.fn()
|
||||
.mockResolvedValue(undefined),
|
||||
autoSubmitFanavaranAttachment: jest.fn().mockResolvedValue({}),
|
||||
logger: { error: jest.fn() },
|
||||
});
|
||||
const file = {
|
||||
path: "files/current.jpg",
|
||||
filename: "current.jpg",
|
||||
} as Express.Multer.File;
|
||||
return { id: id.toString(), userId, service, db, ai, file };
|
||||
}
|
||||
describe("real capture flow AI scheduling", () => {
|
||||
it.each(["user", "field_expert", "file_maker", "file_reviewer"])(
|
||||
"%s capture persists the exact part photo before queueing without waiting for inference",
|
||||
async (role) => {
|
||||
const { id, userId, service, db, ai, file } = setup();
|
||||
const result = await service.capturePartV2(
|
||||
id,
|
||||
{ captureType: "part", captureKey: "123" },
|
||||
file,
|
||||
userId,
|
||||
{ sub: userId, role },
|
||||
);
|
||||
expect(
|
||||
db.findByIdAndUpdate.mock.calls[0][1]["media.damagedParts.0"],
|
||||
).toMatchObject({ path: file.path, fileName: file.filename });
|
||||
expect(ai.enqueue).toHaveBeenCalledWith(
|
||||
id,
|
||||
expect.objectContaining({ path: file.path, fileName: file.filename }),
|
||||
);
|
||||
expect(db.findByIdAndUpdate.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
ai.enqueue.mock.invocationCallOrder[0],
|
||||
);
|
||||
expect(result.captureKey).toBe("123");
|
||||
},
|
||||
);
|
||||
it("does not send car angle photos to the part-analysis queue", async () => {
|
||||
const { id, userId, service, ai, file } = setup();
|
||||
await service.capturePartV2(
|
||||
id,
|
||||
{ captureType: "angle", captureKey: "front" },
|
||||
file,
|
||||
userId,
|
||||
);
|
||||
expect(ai.enqueue).not.toHaveBeenCalled();
|
||||
});
|
||||
it("does not enqueue an unauthorized upload", async () => {
|
||||
const { id, userId, service, ai, file } = setup();
|
||||
service.assertEffectiveUserIsDamagedPartyOnClaim.mockRejectedValue(
|
||||
new ForbiddenException(),
|
||||
);
|
||||
await expect(
|
||||
service.capturePartV2(
|
||||
id,
|
||||
{ captureType: "part", captureKey: "123" },
|
||||
file,
|
||||
userId,
|
||||
),
|
||||
).rejects.toThrow(ForbiddenException);
|
||||
expect(ai.enqueue).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { AiCapture } from "./ai.service";
|
||||
|
||||
/** Use current media only: removed parts and replaced photos belong to history. */
|
||||
export function currentAiCaptures(claim: any): AiCapture[] {
|
||||
const parts = claim?.media?.damagedParts;
|
||||
const rows = Array.isArray(parts)
|
||||
? parts
|
||||
: Object.entries(parts ?? {})
|
||||
.filter(
|
||||
([key]) =>
|
||||
!["front", "back", "left", "right"].includes(key.toLowerCase()),
|
||||
)
|
||||
.map(([, row]) => row);
|
||||
const seen = new Set<string>();
|
||||
return rows.flatMap((row: any) => {
|
||||
if (typeof row?.path !== "string" || !row.path.trim() || seen.has(row.path))
|
||||
return [];
|
||||
seen.add(row.path);
|
||||
return [
|
||||
{
|
||||
path: row.path,
|
||||
fileName: row.fileName,
|
||||
label: row.label_fa || row.name || "تصویر خسارت",
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
|
||||
import { Schema as MongoSchema } from "mongoose";
|
||||
import { AiResult } from "./ai-result";
|
||||
|
||||
@Schema({ collection: "ai-damage-jobs", timestamps: true, versionKey: false })
|
||||
export class AiJob {
|
||||
@Prop({ required: true }) claimId: string;
|
||||
@Prop({ required: true }) imageKey: string;
|
||||
@Prop({ required: true }) path: string;
|
||||
@Prop() fileName?: string;
|
||||
@Prop({
|
||||
default: "queued",
|
||||
enum: ["queued", "processing", "completed", "failed"],
|
||||
})
|
||||
status: string;
|
||||
@Prop({ default: 0 }) attempts: number;
|
||||
@Prop({ default: () => new Date() }) nextAttemptAt: Date;
|
||||
@Prop() leaseUntil?: Date;
|
||||
@Prop() leaseToken?: string;
|
||||
@Prop() completedAt?: Date;
|
||||
@Prop() error?: string;
|
||||
@Prop({ type: MongoSchema.Types.Mixed }) result?: AiResult;
|
||||
}
|
||||
export const AiJobSchema = SchemaFactory.createForClass(AiJob);
|
||||
AiJobSchema.index({ claimId: 1, imageKey: 1 }, { unique: true });
|
||||
AiJobSchema.index({ status: 1, nextAttemptAt: 1, leaseUntil: 1 });
|
||||
@@ -0,0 +1,95 @@
|
||||
import { normalizeAiResult } from "./ai-result";
|
||||
import { currentAiCaptures } from "./ai-captures";
|
||||
|
||||
const response = () => ({
|
||||
distinct_damaged_parts_report: {
|
||||
parts: [
|
||||
{
|
||||
part_name: "Headlight",
|
||||
damage_severity: "Severe",
|
||||
part_bbox: { x1: 10.5, y1: 20, x2: 40, y2: 80 },
|
||||
confidence: 0.95,
|
||||
side: "Right",
|
||||
car_side: "front_right",
|
||||
},
|
||||
{
|
||||
part_name: "Headlight",
|
||||
damage_severity: null,
|
||||
part_bbox: null,
|
||||
confidence: null,
|
||||
},
|
||||
],
|
||||
report: "گزارش تصویر",
|
||||
},
|
||||
damaged_part_table: [{ name: "Headlight" }],
|
||||
case_report: "گزارش کامل",
|
||||
});
|
||||
|
||||
describe("AI response contract", () => {
|
||||
it("preserves distinct repeated detections, nullable fields and Persian reports without requiring a returned image", () => {
|
||||
const result = normalizeAiResult(response());
|
||||
expect(result.parts).toHaveLength(2);
|
||||
expect(result.parts[0]).toMatchObject({
|
||||
name: "Headlight",
|
||||
severity: "Severe",
|
||||
confidence: 0.95,
|
||||
bbox: { x1: 10.5, y1: 20, x2: 40, y2: 80 },
|
||||
});
|
||||
expect(result.parts[1]).toMatchObject({
|
||||
name: "Headlight",
|
||||
bbox: null,
|
||||
severity: null,
|
||||
confidence: null,
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
report: "گزارش تصویر",
|
||||
caseReport: "گزارش کامل",
|
||||
});
|
||||
});
|
||||
it("does not turn corrupt or failed responses into a successful empty analysis", () => {
|
||||
for (const value of [
|
||||
null,
|
||||
{},
|
||||
{ detail: "failure" },
|
||||
{ ...response(), case_report: null },
|
||||
])
|
||||
expect(() => normalizeAiResult(value)).toThrow();
|
||||
});
|
||||
it("accepts a legitimate zero-detection response", () => {
|
||||
const value = response();
|
||||
value.distinct_damaged_parts_report.parts = [];
|
||||
expect(normalizeAiResult(value).parts).toEqual([]);
|
||||
});
|
||||
it("omits corrupt boxes and out-of-range confidence without discarding the part", () => {
|
||||
const value = response();
|
||||
value.distinct_damaged_parts_report.parts[0].part_bbox.x2 = NaN;
|
||||
value.distinct_damaged_parts_report.parts[0].confidence = 1.2;
|
||||
expect(normalizeAiResult(value).parts[0]).toMatchObject({
|
||||
name: "Headlight",
|
||||
bbox: null,
|
||||
confidence: null,
|
||||
});
|
||||
});
|
||||
it("lists current photos only, deduplicates identical files and excludes history and unphotographed additions", () => {
|
||||
const images = currentAiCaptures({
|
||||
media: {
|
||||
damagedParts: [
|
||||
{ path: "files/new.jpg", label_fa: "گلگیر" },
|
||||
{ path: "files/new.jpg" },
|
||||
{ name: "door" },
|
||||
],
|
||||
},
|
||||
damage: {
|
||||
partSelectionHistory: [{ removedParts: [{ path: "files/old.jpg" }] }],
|
||||
},
|
||||
});
|
||||
expect(images).toEqual([
|
||||
{ path: "files/new.jpg", fileName: undefined, label: "گلگیر" },
|
||||
]);
|
||||
expect(
|
||||
currentAiCaptures({
|
||||
media: { damagedParts: { door: { path: "files/door.jpg" } } },
|
||||
}),
|
||||
).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
export interface AiPart {
|
||||
name: string;
|
||||
severity: string | null;
|
||||
confidence: number | null;
|
||||
side: string | null;
|
||||
carSide: string | null;
|
||||
bbox: { x1: number; y1: number; x2: number; y2: number } | null;
|
||||
}
|
||||
export interface AiResult {
|
||||
parts: AiPart[];
|
||||
report: string;
|
||||
caseReport: string;
|
||||
}
|
||||
const text = (v: unknown): string | null =>
|
||||
typeof v === "string" ? v.trim().slice(0, 20000) : null;
|
||||
|
||||
/** Preserve detections independently: repeated names may describe different boxes. */
|
||||
export function normalizeAiResult(value: unknown): AiResult {
|
||||
const raw = value as any;
|
||||
const report = raw?.distinct_damaged_parts_report;
|
||||
if (
|
||||
!report ||
|
||||
!Array.isArray(report.parts) ||
|
||||
typeof report.report !== "string" ||
|
||||
typeof raw.case_report !== "string"
|
||||
) {
|
||||
throw new Error("Invalid AI response");
|
||||
}
|
||||
if (report.parts.length > 500) throw new Error("Too many AI detections");
|
||||
const parts = report.parts.map((part: any): AiPart => {
|
||||
const name = text(part?.part_name);
|
||||
if (!name) throw new Error("Invalid AI part");
|
||||
const b = part.part_bbox;
|
||||
const bbox =
|
||||
b &&
|
||||
[b.x1, b.y1, b.x2, b.y2].every(
|
||||
(v) => typeof v === "number" && Number.isFinite(v),
|
||||
) &&
|
||||
b.x2 > b.x1 &&
|
||||
b.y2 > b.y1
|
||||
? { x1: b.x1, y1: b.y1, x2: b.x2, y2: b.y2 }
|
||||
: null;
|
||||
return {
|
||||
name,
|
||||
bbox,
|
||||
severity: text(part.damage_severity),
|
||||
confidence:
|
||||
typeof part.confidence === "number" &&
|
||||
Number.isFinite(part.confidence) &&
|
||||
part.confidence >= 0 &&
|
||||
part.confidence <= 1
|
||||
? part.confidence
|
||||
: null,
|
||||
side: text(part.side),
|
||||
carSide: text(part.car_side),
|
||||
};
|
||||
});
|
||||
return {
|
||||
parts,
|
||||
report: text(report.report) ?? "",
|
||||
caseReport: text(raw.case_report) ?? "",
|
||||
};
|
||||
}
|
||||
+5
-1
@@ -1,8 +1,12 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { MongooseModule } from "@nestjs/mongoose";
|
||||
import { AiService } from "./ai.service";
|
||||
import { AiJob, AiJobSchema } from "./ai-job.schema";
|
||||
|
||||
@Module({
|
||||
imports: [],
|
||||
imports: [
|
||||
MongooseModule.forFeature([{ name: AiJob.name, schema: AiJobSchema }]),
|
||||
],
|
||||
providers: [AiService],
|
||||
exports: [AiService],
|
||||
})
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { AiService, aiImageKey } from "./ai.service";
|
||||
import { AiJobSchema } from "./ai-job.schema";
|
||||
|
||||
const image = { path: "files/part.jpg", label: "گلگیر" };
|
||||
const result = { parts: [], report: "گزارش", caseReport: "گزارش کامل" };
|
||||
function setup(enabled = true) {
|
||||
const jobs = {
|
||||
updateOne: jest.fn().mockResolvedValue({}),
|
||||
updateMany: jest.fn().mockResolvedValue({}),
|
||||
find: jest.fn().mockReturnValue({ lean: jest.fn().mockResolvedValue([]) }),
|
||||
findOneAndUpdate: jest
|
||||
.fn()
|
||||
.mockReturnValue({ lean: jest.fn().mockResolvedValue(null) }),
|
||||
};
|
||||
const config = new ConfigService({
|
||||
AI_DAMAGE_ENABLED: String(enabled),
|
||||
AI_DAMAGE_URL: "http://example.test",
|
||||
AI_DAMAGE_TIMEOUT_MS: 1000,
|
||||
});
|
||||
return { service: new AiService(config, jobs as any), jobs };
|
||||
}
|
||||
function claimJob(
|
||||
jobs: ReturnType<typeof setup>["jobs"],
|
||||
fields: Record<string, unknown> = {},
|
||||
) {
|
||||
jobs.findOneAndUpdate.mockImplementation((_q: any, update: any) => ({
|
||||
lean: async () => ({
|
||||
_id: "job1",
|
||||
claimId: "claim1",
|
||||
imageKey: aiImageKey(image.path),
|
||||
...image,
|
||||
status: "processing",
|
||||
attempts: 1,
|
||||
leaseToken: update.$set.leaseToken,
|
||||
...fields,
|
||||
}),
|
||||
}));
|
||||
}
|
||||
describe("durable AI jobs", () => {
|
||||
it("is opt-in and does not send or enqueue photos when disabled", async () => {
|
||||
const { service, jobs } = setup(false);
|
||||
await service.enqueue("claim1", image);
|
||||
await service.work();
|
||||
expect(jobs.updateOne).not.toHaveBeenCalled();
|
||||
expect(jobs.findOneAndUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
it("uniquely queues each claim/photo and never resets a completed job on repeated uploads", async () => {
|
||||
const { service, jobs } = setup();
|
||||
await service.enqueue("claim1", image);
|
||||
expect(AiJobSchema.indexes()).toContainEqual([
|
||||
{ claimId: 1, imageKey: 1 },
|
||||
{ unique: true, background: true },
|
||||
]);
|
||||
expect(jobs.updateOne).toHaveBeenCalledWith(
|
||||
{ claimId: "claim1", imageKey: aiImageKey(image.path) },
|
||||
{
|
||||
$setOnInsert: expect.objectContaining({
|
||||
status: "queued",
|
||||
attempts: 0,
|
||||
}),
|
||||
},
|
||||
{ upsert: true },
|
||||
);
|
||||
});
|
||||
it("a persistence failure does not fail the photo upload", async () => {
|
||||
const { service, jobs } = setup();
|
||||
jobs.updateOne.mockRejectedValue(new Error("offline"));
|
||||
await expect(service.enqueue("claim1", image)).resolves.toBeUndefined();
|
||||
});
|
||||
it("leases pending and expired jobs atomically and persists only the owning worker's result", async () => {
|
||||
const { service, jobs } = setup();
|
||||
claimJob(jobs);
|
||||
jest.spyOn(service, "aiRequestImage").mockResolvedValue(result);
|
||||
await service.work();
|
||||
const [filter, update] = jobs.findOneAndUpdate.mock.calls[0];
|
||||
expect(filter.$or).toEqual([
|
||||
expect.objectContaining({ status: "queued" }),
|
||||
expect.objectContaining({
|
||||
status: "processing",
|
||||
leaseUntil: expect.any(Object),
|
||||
}),
|
||||
]);
|
||||
expect(update.$inc).toEqual({ attempts: 1 });
|
||||
expect(jobs.updateOne).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
_id: "job1",
|
||||
leaseToken: update.$set.leaseToken,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
$set: expect.objectContaining({ status: "completed", result }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
it("prevents overlapping processing in one instance", async () => {
|
||||
const { service, jobs } = setup();
|
||||
claimJob(jobs);
|
||||
let finish!: (v: typeof result) => void;
|
||||
jest.spyOn(service, "aiRequestImage").mockImplementation(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
finish = resolve;
|
||||
}),
|
||||
);
|
||||
const first = service.work();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await service.work();
|
||||
expect(jobs.findOneAndUpdate).toHaveBeenCalledTimes(1);
|
||||
finish(result);
|
||||
await first;
|
||||
});
|
||||
it("retries transient failures with delay, but stops after three attempts", async () => {
|
||||
for (const attempts of [1, 3]) {
|
||||
const { service, jobs } = setup();
|
||||
claimJob(jobs, { attempts });
|
||||
jest
|
||||
.spyOn(service, "aiRequestImage")
|
||||
.mockRejectedValue(new Error("timeout"));
|
||||
await service.work();
|
||||
expect(jobs.updateOne).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({
|
||||
$set: expect.objectContaining({
|
||||
status: attempts === 1 ? "queued" : "failed",
|
||||
nextAttemptAt: expect.any(Date),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
it("does not retry invalid/non-car images automatically", async () => {
|
||||
const { service, jobs } = setup();
|
||||
claimJob(jobs);
|
||||
jest
|
||||
.spyOn(service, "aiRequestImage")
|
||||
.mockRejectedValue({ response: { status: 400 } });
|
||||
await service.work();
|
||||
expect(jobs.updateOne).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({
|
||||
$set: expect.objectContaining({
|
||||
status: "failed",
|
||||
error: "خودرو در تصویر تشخیص داده نشد.",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
it("never sends another request after recovering a repeatedly crashed job beyond its limit", async () => {
|
||||
const { service, jobs } = setup();
|
||||
claimJob(jobs, { attempts: 4 });
|
||||
const send = jest.spyOn(service, "aiRequestImage");
|
||||
await service.work();
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
});
|
||||
it("only returns current photo results and never exposes storage paths or provider payloads", async () => {
|
||||
const { service, jobs } = setup();
|
||||
jobs.find.mockReturnValue({
|
||||
lean: jest.fn().mockResolvedValue([
|
||||
{
|
||||
imageKey: aiImageKey(image.path),
|
||||
status: "completed",
|
||||
result,
|
||||
path: "private",
|
||||
attempts: 1,
|
||||
},
|
||||
]),
|
||||
});
|
||||
const view = await service.list("claim1", [image]);
|
||||
expect(jobs.find).toHaveBeenCalledWith({
|
||||
claimId: "claim1",
|
||||
imageKey: { $in: [aiImageKey(image.path)] },
|
||||
});
|
||||
expect(view.images[0]).toMatchObject({
|
||||
label: "گلگیر",
|
||||
status: "completed",
|
||||
result,
|
||||
});
|
||||
expect(view.images[0]).not.toHaveProperty("path");
|
||||
});
|
||||
it("manual retry affects only failed jobs for current claim/photos", async () => {
|
||||
const { service, jobs } = setup();
|
||||
await service.retry("claim1", [image]);
|
||||
expect(jobs.updateMany).toHaveBeenCalledWith(
|
||||
{
|
||||
claimId: "claim1",
|
||||
imageKey: { $in: [aiImageKey(image.path)] },
|
||||
status: "failed",
|
||||
},
|
||||
expect.objectContaining({
|
||||
$set: expect.objectContaining({ status: "queued", attempts: 0 }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("AI multipart transport", () => {
|
||||
it("posts real image bytes under images with every pipeline flag and no returned-image dependency", async () => {
|
||||
const fs = await import("node:fs/promises");
|
||||
const { resolve, join } = await import("node:path");
|
||||
const axios = (await import("axios")).default;
|
||||
const root = await fs.mkdtemp("/tmp/yara-ai-jest-");
|
||||
const file = join(root, "test.jpg");
|
||||
const bytes = Buffer.from([0xff, 0xd8, 0xff, 0x00, 0x01, 0xff, 0xd9]);
|
||||
await fs.writeFile(file, bytes);
|
||||
const realpath = fs.realpath;
|
||||
const pathSpy = jest
|
||||
.spyOn(fs, "realpath")
|
||||
.mockImplementation(((path: string) =>
|
||||
path === resolve("files")
|
||||
? Promise.resolve(root)
|
||||
: realpath(path)) as any);
|
||||
const post = jest
|
||||
.spyOn(axios, "post")
|
||||
.mockImplementation(async (url, form: any, config) => {
|
||||
const parsed = new URL(String(url));
|
||||
expect(parsed.pathname).toBe("/pipeline/detect_parts_with_damages");
|
||||
for (const option of [
|
||||
"side",
|
||||
"segments",
|
||||
"bounding_box",
|
||||
"severity",
|
||||
"confidence",
|
||||
])
|
||||
expect(parsed.searchParams.get(option)).toBe("true");
|
||||
expect(config?.headers?.["content-type"]).toMatch(
|
||||
/^multipart\/form-data; boundary=/,
|
||||
);
|
||||
expect(config?.maxRedirects).toBe(0);
|
||||
const chunks: Buffer[] = [];
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
form.on("data", (chunk: string | Buffer) =>
|
||||
chunks.push(Buffer.from(chunk)),
|
||||
);
|
||||
form.on("end", resolve);
|
||||
form.on("error", reject);
|
||||
form.resume();
|
||||
});
|
||||
const body = Buffer.concat(chunks);
|
||||
expect(
|
||||
body.includes(Buffer.from('name="images"; filename="test.jpg"')),
|
||||
).toBe(true);
|
||||
expect(body.includes(bytes)).toBe(true);
|
||||
return {
|
||||
data: {
|
||||
distinct_damaged_parts_report: { parts: [], report: "گزارش" },
|
||||
case_report: "گزارش کامل",
|
||||
},
|
||||
} as any;
|
||||
});
|
||||
try {
|
||||
const { service } = setup();
|
||||
await expect(
|
||||
service.aiRequestImage({ path: file, fileName: "test.jpg" }),
|
||||
).resolves.toMatchObject({ parts: [], report: "گزارش" });
|
||||
await expect(
|
||||
service.aiRequestImage({ path: "/etc/hosts" }),
|
||||
).rejects.toThrow("outside upload storage");
|
||||
expect(post).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
pathSpy.mockRestore();
|
||||
post.mockRestore();
|
||||
await fs.rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
+220
-175
@@ -1,204 +1,249 @@
|
||||
import { createReadStream, existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { realpath, stat } from "node:fs/promises";
|
||||
import { basename, resolve, sep } from "node:path";
|
||||
import {
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
Logger,
|
||||
OnModuleDestroy,
|
||||
OnModuleInit,
|
||||
} from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { AxiosRequestConfig } from "axios"; // TODO: Change all axios usages to HttpModule
|
||||
import { InjectModel } from "@nestjs/mongoose";
|
||||
import { Model } from "mongoose";
|
||||
import axios from "axios";
|
||||
import FormData = require("form-data");
|
||||
import { AiJob } from "./ai-job.schema";
|
||||
import { normalizeAiResult } from "./ai-result";
|
||||
import { buildFileLink } from "src/helpers/urlCreator";
|
||||
|
||||
export interface AiCapture {
|
||||
path: string;
|
||||
fileName?: string;
|
||||
label?: string;
|
||||
}
|
||||
export const aiImageKey = (path: string) =>
|
||||
createHash("sha256").update(resolve(path)).digest("hex");
|
||||
|
||||
@Injectable()
|
||||
export class AiService implements OnModuleInit {
|
||||
private apiKey: string;
|
||||
private accessToken: string = null;
|
||||
export class AiService implements OnModuleInit, OnModuleDestroy {
|
||||
private readonly logger = new Logger(AiService.name);
|
||||
private timer?: NodeJS.Timeout;
|
||||
private busy = false;
|
||||
private stopping = false;
|
||||
private abort?: AbortController;
|
||||
constructor(
|
||||
private readonly config: ConfigService,
|
||||
@InjectModel(AiJob.name) private readonly jobs: Model<AiJob>,
|
||||
) {}
|
||||
|
||||
// These configurations are for authentication and getting the API key.
|
||||
private readonly loginOptions: AxiosRequestConfig = {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
url: `${this.configService.get<string>("AI_URL_V2")}/auth/login`,
|
||||
data: {
|
||||
username: this.configService.get<string>("AI_USERNAME"),
|
||||
password: this.configService.get<string>("AI_PASSWORD"),
|
||||
},
|
||||
timeout: 1000, // TODO: Make this ENV
|
||||
};
|
||||
|
||||
constructor(private readonly configService: ConfigService) {}
|
||||
|
||||
private get profileOptions(): AxiosRequestConfig {
|
||||
return {
|
||||
method: "GET",
|
||||
url: `${this.configService.get<string>("AI_URL_V2")}/auth/profile`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.accessToken}`,
|
||||
},
|
||||
};
|
||||
get enabled() {
|
||||
return this.config.get<string>("AI_DAMAGE_ENABLED") === "true";
|
||||
}
|
||||
private get timeout() {
|
||||
return Math.min(
|
||||
600000,
|
||||
Math.max(1000, Number(this.config.get("AI_DAMAGE_TIMEOUT_MS")) || 180000),
|
||||
);
|
||||
}
|
||||
|
||||
// This getter dynamically creates the base options for the image processing request.
|
||||
private get imageProcessOptions(): AxiosRequestConfig {
|
||||
return {
|
||||
method: "POST",
|
||||
url: `${process.env.AI_URL_V2}/services/car-damage/detector?version=ai-v7`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.accessToken}`,
|
||||
"gateway-api-key": `${this.apiKey}`,
|
||||
},
|
||||
};
|
||||
onModuleInit() {
|
||||
if (!this.enabled) return;
|
||||
this.timer = setInterval(() => {
|
||||
void this.work();
|
||||
}, 5000);
|
||||
this.timer.unref();
|
||||
void this.work();
|
||||
}
|
||||
onModuleDestroy() {
|
||||
this.stopping = true;
|
||||
clearInterval(this.timer);
|
||||
this.abort?.abort();
|
||||
}
|
||||
|
||||
async onModuleInit() {
|
||||
/** Only persist the job here; never wait for the AI in an upload request. */
|
||||
async enqueue(claimId: string, image: AiCapture): Promise<void> {
|
||||
if (!this.enabled || !image.path) return;
|
||||
try {
|
||||
const res = await this.login();
|
||||
// if (res?.accessToken) {
|
||||
// this.accessToken = res.accessToken;
|
||||
// await this.getApiKey();
|
||||
// }
|
||||
await this.jobs.updateOne(
|
||||
{ claimId, imageKey: aiImageKey(image.path) },
|
||||
{
|
||||
$setOnInsert: {
|
||||
claimId,
|
||||
imageKey: aiImageKey(image.path),
|
||||
path: image.path,
|
||||
fileName: image.fileName,
|
||||
status: "queued",
|
||||
attempts: 0,
|
||||
nextAttemptAt: new Date(),
|
||||
},
|
||||
},
|
||||
{ upsert: true },
|
||||
);
|
||||
} catch (error) {
|
||||
// Don't prevent app startup if AI service is temporarily unavailable
|
||||
// The service will attempt to re-authenticate when aiRequestImage is called
|
||||
// Reset tokens so re-authentication will be attempted
|
||||
this.accessToken = null;
|
||||
this.apiKey = null;
|
||||
// Concurrent duplicate uploads are already queued. A storage outage must not fail capture.
|
||||
if ((error as any)?.code !== 11000)
|
||||
this.logger.error(
|
||||
"Could not persist AI job; expert review will retry scheduling.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async login() {
|
||||
// const loginResponse = await axios.request(this.loginOptions);
|
||||
// return loginResponse.data;
|
||||
async list(claimId: string, images: AiCapture[]) {
|
||||
// Older captures and jobs missed during a database outage are scheduled on review.
|
||||
for (const image of images) await this.enqueue(claimId, image);
|
||||
const keys = images.map((image) => aiImageKey(image.path));
|
||||
const rows = await this.jobs
|
||||
.find({ claimId, imageKey: { $in: keys } })
|
||||
.lean();
|
||||
const byKey = new Map(rows.map((row) => [row.imageKey, row]));
|
||||
return {
|
||||
enabled: this.enabled,
|
||||
images: images.map((image) => {
|
||||
const key = aiImageKey(image.path);
|
||||
const job = byKey.get(key);
|
||||
return {
|
||||
imageKey: key,
|
||||
label: image.label ?? "تصویر خسارت",
|
||||
imageUrl: buildFileLink(image.path),
|
||||
status: job?.status ?? (this.enabled ? "queued" : "disabled"),
|
||||
attempts: job?.attempts ?? 0,
|
||||
completedAt: job?.completedAt,
|
||||
error: job?.error,
|
||||
result: job?.status === "completed" ? job.result : undefined,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
private async getApiKey() {
|
||||
// const profileResponse = await axios.request(this.profileOptions);
|
||||
// this.apiKey = profileResponse.data.apiKey.key;
|
||||
// return this.apiKey;
|
||||
async retry(claimId: string, images: AiCapture[]) {
|
||||
if (this.enabled)
|
||||
await this.jobs.updateMany(
|
||||
{
|
||||
claimId,
|
||||
imageKey: { $in: images.map((image) => aiImageKey(image.path)) },
|
||||
status: "failed",
|
||||
},
|
||||
{
|
||||
$set: { status: "queued", attempts: 0, nextAttemptAt: new Date() },
|
||||
$unset: { error: 1, leaseToken: 1, leaseUntil: 1 },
|
||||
},
|
||||
);
|
||||
return this.list(claimId, images);
|
||||
}
|
||||
|
||||
public async aiRequestImage(file: {
|
||||
path: string;
|
||||
fileName?: string;
|
||||
}): Promise<any> {
|
||||
// Ensure authentication is set up
|
||||
if (!this.accessToken || !this.apiKey) {
|
||||
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"));
|
||||
const path = await realpath(resolve(file.path));
|
||||
if (!path.startsWith(root + sep))
|
||||
throw new Error("Image outside upload storage");
|
||||
const info = await stat(path);
|
||||
if (!info.isFile() || info.size > 20 * 1024 * 1024)
|
||||
throw new Error("Invalid image size");
|
||||
const base = this.config.get<string>("AI_DAMAGE_URL");
|
||||
if (!base) throw new Error("AI_DAMAGE_URL is required");
|
||||
const url = new URL(
|
||||
"pipeline/detect_parts_with_damages",
|
||||
base.replace(/\/?$/, "/"),
|
||||
);
|
||||
for (const option of [
|
||||
"side",
|
||||
"segments",
|
||||
"bounding_box",
|
||||
"severity",
|
||||
"confidence",
|
||||
])
|
||||
url.searchParams.set(option, "true");
|
||||
const form = new FormData();
|
||||
const stream = createReadStream(path);
|
||||
form.append("images", stream, {
|
||||
filename: file.fileName || basename(path),
|
||||
knownLength: info.size,
|
||||
});
|
||||
try {
|
||||
const { data } = await axios.post(url.toString(), form, {
|
||||
headers: form.getHeaders(),
|
||||
timeout: this.timeout,
|
||||
signal,
|
||||
maxBodyLength: 21 * 1024 * 1024,
|
||||
maxContentLength: 2 * 1024 * 1024,
|
||||
maxRedirects: 0,
|
||||
});
|
||||
return normalizeAiResult(data);
|
||||
} finally {
|
||||
stream.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
/** Atomic leases make this safe across replicas and recover jobs after a restart. */
|
||||
async work() {
|
||||
if (!this.enabled || this.busy || this.stopping) return;
|
||||
this.busy = true;
|
||||
try {
|
||||
const now = new Date();
|
||||
const token = randomUUID();
|
||||
const job = await this.jobs
|
||||
.findOneAndUpdate(
|
||||
{
|
||||
$or: [
|
||||
{ status: "queued", nextAttemptAt: { $lte: now } },
|
||||
{ status: "processing", leaseUntil: { $lte: now } },
|
||||
],
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
status: "processing",
|
||||
leaseToken: token,
|
||||
leaseUntil: new Date(now.getTime() + this.timeout + 60000),
|
||||
},
|
||||
$inc: { attempts: 1 },
|
||||
},
|
||||
{ new: true, sort: { nextAttemptAt: 1 } },
|
||||
)
|
||||
.lean();
|
||||
if (!job) return;
|
||||
const owned = { _id: job._id, status: "processing", leaseToken: token };
|
||||
try {
|
||||
const res = await this.login();
|
||||
// if (res?.accessToken) {
|
||||
// this.accessToken = res.accessToken;
|
||||
// await this.getApiKey();
|
||||
// } else {
|
||||
// throw new HttpException(
|
||||
// "AI Service authentication failed",
|
||||
// HttpStatus.UNAUTHORIZED,
|
||||
// );
|
||||
// }
|
||||
if (job.attempts > 3) throw new Error("Retry limit reached");
|
||||
this.abort = new AbortController();
|
||||
const result = await this.aiRequestImage(job, this.abort.signal);
|
||||
await this.jobs.updateOne(owned, {
|
||||
$set: { status: "completed", result, completedAt: new Date() },
|
||||
$unset: { error: 1, leaseUntil: 1, leaseToken: 1 },
|
||||
});
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
"AI Service authentication failed",
|
||||
HttpStatus.UNAUTHORIZED,
|
||||
if (this.stopping) return; // Leave lease for another process after shutdown.
|
||||
const status = (error as any)?.response?.status;
|
||||
const terminal =
|
||||
job.attempts >= 3 ||
|
||||
[400, 401, 403, 404, 413, 415, 422].includes(status);
|
||||
await this.jobs.updateOne(owned, {
|
||||
$set: {
|
||||
status: terminal ? "failed" : "queued",
|
||||
error:
|
||||
status === 400
|
||||
? "خودرو در تصویر تشخیص داده نشد."
|
||||
: status === 422 || status === 415
|
||||
? "سرویس هوش مصنوعی این تصویر را نپذیرفت؛ یک تصویر JPEG واضح بارگذاری کنید."
|
||||
: "تحلیل تصویر انجام نشد. دوباره تلاش کنید.",
|
||||
nextAttemptAt: new Date(
|
||||
Date.now() + 30000 * 2 ** Math.min(job.attempts - 1, 3),
|
||||
),
|
||||
},
|
||||
$unset: { leaseUntil: 1, leaseToken: 1 },
|
||||
});
|
||||
this.logger.warn(
|
||||
`AI analysis failed (${status ?? "network/response"}); ${terminal ? "manual retry available" : "retry queued"}.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve relative paths to absolute paths
|
||||
const filePath = file.path.startsWith("/")
|
||||
? file.path
|
||||
: join(process.cwd(), file.path.replace(/^\.\//, ""));
|
||||
|
||||
// Check if file exists
|
||||
if (!existsSync(filePath)) {
|
||||
throw new HttpException(
|
||||
`File not found: ${file.path}`,
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
// const form = new FormData();
|
||||
const fileStream = createReadStream(filePath);
|
||||
|
||||
// Append file with filename if available
|
||||
if (file.fileName) {
|
||||
// form.append("images", fileStream, file.fileName);
|
||||
} else {
|
||||
// Extract filename from path if not provided
|
||||
const pathParts = filePath.split("/");
|
||||
const extractedFileName = pathParts[pathParts.length - 1];
|
||||
// form.append("images", fileStream, extractedFileName);
|
||||
}
|
||||
|
||||
try {
|
||||
const requestHeaders = {
|
||||
...this.imageProcessOptions.headers,
|
||||
// ...form.getHeaders(),
|
||||
};
|
||||
|
||||
const fs = require("fs");
|
||||
const stats = fs.statSync(filePath);
|
||||
|
||||
// const response = await axios.request({
|
||||
// ...this.imageProcessOptions,
|
||||
// headers: requestHeaders,
|
||||
// // data: form,
|
||||
// maxContentLength: Infinity,
|
||||
// maxBodyLength: Infinity,
|
||||
// });
|
||||
|
||||
// Validate response structure
|
||||
// if (!response.data) {
|
||||
// throw new HttpException(
|
||||
// "AI Service returned empty response",
|
||||
// HttpStatus.BAD_GATEWAY,
|
||||
// );
|
||||
// }
|
||||
|
||||
// // Check for error in response first (AI service returns 201 with error in body)
|
||||
// if (response.data.error) {
|
||||
// throw new HttpException(
|
||||
// `AI Service error: ${response.data.error}`,
|
||||
// HttpStatus.BAD_GATEWAY,
|
||||
// );
|
||||
// }
|
||||
|
||||
// // Check for processed image (downloadLink)
|
||||
// if (!response.data.downloadLink) {
|
||||
// throw new HttpException(
|
||||
// "AI Service did not return processed image (downloadLink missing)",
|
||||
// HttpStatus.BAD_GATEWAY,
|
||||
// );
|
||||
// }
|
||||
|
||||
// return response.data;
|
||||
} catch (er) {
|
||||
// Determine error source
|
||||
let errorSource = "UNKNOWN";
|
||||
let errorMessage = er.message;
|
||||
let errorDetails = "No error details available";
|
||||
|
||||
if (er.response) {
|
||||
errorSource = "AI_SERVICE_RESPONSE";
|
||||
errorMessage =
|
||||
er.response?.data?.message ||
|
||||
er.message ||
|
||||
`HTTP ${er.response.status}`;
|
||||
errorDetails = er.response?.data
|
||||
? JSON.stringify(er.response.data, null, 2)
|
||||
: `Status: ${er.response.status}, StatusText: ${er.response.statusText}`;
|
||||
} else if (er.request) {
|
||||
errorSource = "NETWORK_ERROR";
|
||||
errorMessage = "Network error - AI service did not respond";
|
||||
errorDetails = "Request was made but no response received";
|
||||
} else {
|
||||
errorSource = "REQUEST_SETUP_ERROR";
|
||||
errorMessage = er.message || "Error setting up request";
|
||||
}
|
||||
|
||||
// Re-throw with detailed error information
|
||||
throw new HttpException(
|
||||
`[${errorSource}] ${errorMessage}`,
|
||||
er.response?.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
} catch {
|
||||
this.logger.error(
|
||||
"AI worker storage unavailable; will retry on the next tick.",
|
||||
);
|
||||
} finally {
|
||||
this.abort = undefined;
|
||||
this.busy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -719,10 +719,6 @@ export class ClaimRequestManagementService {
|
||||
return nationalCode || undefined;
|
||||
}
|
||||
|
||||
private delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
/**
|
||||
* Outer-parts catalog returned to clients (user app + expert panel).
|
||||
*
|
||||
@@ -2110,224 +2106,6 @@ export class ClaimRequestManagementService {
|
||||
}
|
||||
}
|
||||
|
||||
private async processAiRequestQueue(
|
||||
tasks: (() => Promise<void>)[],
|
||||
delayMs = 200,
|
||||
): Promise<void> {
|
||||
for (const task of tasks) {
|
||||
await task();
|
||||
await this.delay(delayMs);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process AI requests in the background without blocking the response
|
||||
* This allows users to upload images quickly without waiting for AI processing
|
||||
*/
|
||||
private async processAiRequestQueueInBackground(
|
||||
tasks: (() => Promise<void>)[],
|
||||
requestId: string,
|
||||
partId: string,
|
||||
): Promise<void> {
|
||||
if (tasks.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.log(
|
||||
`[BACKGROUND AI] Starting background AI processing for ${tasks.length} image(s), part ${partId}, request ${requestId}`,
|
||||
);
|
||||
|
||||
// Process in background without blocking
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.processAiRequestQueue(tasks);
|
||||
this.logger.log(
|
||||
`[BACKGROUND AI] Completed AI processing for part ${partId}, request ${requestId}`,
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`[BACKGROUND AI] Failed to process AI requests for part ${partId}, request ${requestId}: ${error instanceof Error ? error.message : String(error)}`,
|
||||
error instanceof Error ? error.stack : undefined,
|
||||
);
|
||||
// Don't throw - we're in background processing
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async handleAiSuccess(
|
||||
response: any,
|
||||
key: string,
|
||||
partId: string,
|
||||
requestId: string,
|
||||
): Promise<void> {
|
||||
this.logger.log(
|
||||
`[STEP 4/4] Processing AI response for part ${partId}, requestId: ${requestId}`,
|
||||
);
|
||||
|
||||
// 1. Validate that we have the processed image
|
||||
if (!response?.downloadLink) {
|
||||
this.logger.error(
|
||||
`[ERROR] Missing processed image (downloadLink) in AI response`,
|
||||
);
|
||||
this.logger.error(`[ERROR] Part ID: ${partId}, Request ID: ${requestId}`);
|
||||
this.logger.error(
|
||||
`[ERROR] Response keys: ${JSON.stringify(response ? Object.keys(response) : "null")}`,
|
||||
);
|
||||
this.logger.error(
|
||||
`[ERROR] Full response: ${JSON.stringify(response, null, 2)}`,
|
||||
);
|
||||
throw new HttpException(
|
||||
`AI response missing processed image (downloadLink) for part ${partId}`,
|
||||
HttpStatus.BAD_GATEWAY,
|
||||
);
|
||||
}
|
||||
|
||||
this.logger.log(`[STEP 4/4] Processed image URL: ${response.downloadLink}`);
|
||||
|
||||
// 2. Safely access the nested properties.
|
||||
const reports = response?.reports;
|
||||
const reportText = reports?.distinct_damaged_parts_report?.report;
|
||||
|
||||
// 3. Log warning if reports are missing but continue with image
|
||||
if (!reports) {
|
||||
this.logger.warn(
|
||||
`[WARNING] AI response for part ${partId} is missing the 'reports' object, but downloadLink exists.`,
|
||||
);
|
||||
this.logger.warn(`[WARNING] Will save image but without AI report data.`);
|
||||
} else {
|
||||
this.logger.log(
|
||||
`[STEP 4/4] AI reports present: ${reports ? "yes" : "no"}`,
|
||||
);
|
||||
}
|
||||
|
||||
// 4. Build the update payload.
|
||||
const updatePayload = {
|
||||
$set: {
|
||||
[`imageRequired.${key}.$[elem].aiReport`]: reports || {},
|
||||
[`imageRequired.${key}.$[elem].aiImage`]: response.downloadLink,
|
||||
[`imageRequired.${key}.$[elem].aiReportText`]: reportText || "",
|
||||
[`imageRequired.aiReportText`]: response.reportsText || "",
|
||||
},
|
||||
};
|
||||
|
||||
// 5. Update the database using arrayFilters.
|
||||
try {
|
||||
const updateResult = await this.claimDbService.findOneAndUpdate(
|
||||
{ _id: new Types.ObjectId(requestId) },
|
||||
updatePayload,
|
||||
{
|
||||
arrayFilters: [{ "elem.partId": partId }],
|
||||
},
|
||||
);
|
||||
|
||||
if (!updateResult) {
|
||||
this.logger.error(
|
||||
`[ERROR] Database update failed - no document found or update failed`,
|
||||
);
|
||||
this.logger.error(
|
||||
`[ERROR] Request ID: ${requestId}, Part ID: ${partId}, Key: ${key}`,
|
||||
);
|
||||
throw new HttpException(
|
||||
`Failed to update database with AI results for part ${partId}`,
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
|
||||
this.logger.log(
|
||||
`[SUCCESS] Successfully updated AI report and image for part ${partId}`,
|
||||
);
|
||||
} catch (dbError) {
|
||||
const dbErrorMessage =
|
||||
dbError instanceof Error ? dbError.message : String(dbError);
|
||||
this.logger.error(`[ERROR] Database update error for part ${partId}:`);
|
||||
this.logger.error(`[ERROR] ${dbErrorMessage}`);
|
||||
this.logger.error(
|
||||
`[ERROR] Stack: ${dbError instanceof Error ? dbError.stack : undefined}`,
|
||||
);
|
||||
throw new HttpException(
|
||||
`Database update failed: ${dbErrorMessage}`,
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async retryAiRequest(
|
||||
newImageDoc: any,
|
||||
key: string,
|
||||
partId: string,
|
||||
requestId: string,
|
||||
retries = 3,
|
||||
): Promise<void> {
|
||||
const attemptNumber = 4 - retries; // Track which attempt this is
|
||||
this.logger.log(
|
||||
`[ATTEMPT ${attemptNumber}] Processing AI request for part ${partId}, requestId: ${requestId}`,
|
||||
);
|
||||
this.logger.log(
|
||||
`[ATTEMPT ${attemptNumber}] File path: ${newImageDoc.path}, File name: ${newImageDoc.fileName}`,
|
||||
);
|
||||
|
||||
try {
|
||||
// Use the new, robust AiService to send the request.
|
||||
// Pass both path and fileName to the AI service
|
||||
const response = await this.aiService.aiRequestImage({
|
||||
path: newImageDoc.path,
|
||||
fileName: newImageDoc.fileName,
|
||||
});
|
||||
|
||||
// If the request succeeds, handle the success.
|
||||
await this.handleAiSuccess(response, key, partId, requestId);
|
||||
this.logger.log(
|
||||
`[SUCCESS] AI processing completed successfully for part ${partId}`,
|
||||
);
|
||||
} catch (error) {
|
||||
// Extract error source from error message if available
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : String(error);
|
||||
const errorSource = errorMessage.includes("[ERROR]")
|
||||
? errorMessage.split("[ERROR]")[1]?.split("]")[0] || "UNKNOWN"
|
||||
: "UNKNOWN";
|
||||
|
||||
this.logger.error(
|
||||
`[ATTEMPT ${attemptNumber} FAILED] Error source: ${errorSource}`,
|
||||
);
|
||||
this.logger.error(
|
||||
`[ATTEMPT ${attemptNumber} FAILED] Part ID: ${partId}, Request ID: ${requestId}`,
|
||||
);
|
||||
this.logger.error(
|
||||
`[ATTEMPT ${attemptNumber} FAILED] Error: ${errorMessage}`,
|
||||
);
|
||||
|
||||
if (retries > 0) {
|
||||
this.logger.warn(
|
||||
`⚠️ Retrying AI request for part ${partId}... Attempts left: ${retries - 1}`,
|
||||
);
|
||||
await this.delay(1000); // Wait before retrying
|
||||
return this.retryAiRequest(
|
||||
newImageDoc,
|
||||
key,
|
||||
partId,
|
||||
requestId,
|
||||
retries - 1,
|
||||
);
|
||||
} else {
|
||||
this.logger.error(
|
||||
`🔴 [FINAL FAILURE] AI request failed after all retries`,
|
||||
);
|
||||
this.logger.error(`🔴 [FINAL FAILURE] Request ID: ${requestId}`);
|
||||
this.logger.error(`🔴 [FINAL FAILURE] Part ID: ${partId}`);
|
||||
this.logger.error(`🔴 [FINAL FAILURE] File path: ${newImageDoc.path}`);
|
||||
this.logger.error(`🔴 [FINAL FAILURE] Error source: ${errorSource}`);
|
||||
this.logger.error(`🔴 [FINAL FAILURE] Final error: ${errorMessage}`);
|
||||
if (error instanceof Error && error.stack) {
|
||||
this.logger.error(`🔴 [FINAL FAILURE] Stack trace: ${error.stack}`);
|
||||
}
|
||||
// Optional: Update the claim status to indicate an AI failure.
|
||||
// You could throw here if you want to fail the entire operation
|
||||
throw error; // Re-throw to propagate the error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async processDamageImages(
|
||||
document: any,
|
||||
requestId: string,
|
||||
@@ -2336,8 +2114,6 @@ export class ClaimRequestManagementService {
|
||||
imageRequiredKeys: string[],
|
||||
result: any[],
|
||||
) {
|
||||
const aiRequestQueue = [];
|
||||
|
||||
for (const key of imageRequiredKeys) {
|
||||
const images = document.imageRequired[key];
|
||||
for (const img of images) {
|
||||
@@ -2347,12 +2123,6 @@ export class ClaimRequestManagementService {
|
||||
requestId,
|
||||
);
|
||||
|
||||
// Queue AI request for background processing
|
||||
const aiRequestTask = () =>
|
||||
this.retryAiRequest(newImageDoc, key, partOfDamageId, requestId);
|
||||
|
||||
aiRequestQueue.push(aiRequestTask);
|
||||
|
||||
// Update the document immediately with the uploaded image
|
||||
await this.updateImageRequiredDocument(
|
||||
requestId,
|
||||
@@ -2360,6 +2130,9 @@ export class ClaimRequestManagementService {
|
||||
partOfDamageId,
|
||||
newImageDoc,
|
||||
);
|
||||
if (key === "selectPartOfCar") {
|
||||
await this.aiService.enqueue(requestId, newImageDoc);
|
||||
}
|
||||
const updatedDocs =
|
||||
await this.claimDbService.findOneDocument(requestId);
|
||||
this.handleImageUpdateResult(result, updatedDocs, requestId);
|
||||
@@ -2367,19 +2140,6 @@ export class ClaimRequestManagementService {
|
||||
}
|
||||
}
|
||||
|
||||
// Process AI requests in the background (fire and forget)
|
||||
// Don't await - let it run asynchronously so user doesn't have to wait
|
||||
this.processAiRequestQueueInBackground(
|
||||
aiRequestQueue,
|
||||
requestId,
|
||||
partOfDamageId,
|
||||
).catch((error) => {
|
||||
// Log errors but don't fail the upload
|
||||
this.logger.error(
|
||||
`[BACKGROUND AI] Error processing AI requests for part ${partOfDamageId}, request ${requestId}: ${error.message}`,
|
||||
error.stack,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
private async updateImageRequiredDocument(
|
||||
@@ -11728,6 +11488,9 @@ export class ClaimRequestManagementService {
|
||||
claimRequestId,
|
||||
updateData,
|
||||
);
|
||||
if (!treatAsAngle) {
|
||||
await this.aiService.enqueue(claimRequestId, captureData);
|
||||
}
|
||||
// Re-read so capture-progress sees sibling concurrent part/angle writes.
|
||||
const updatedClaim =
|
||||
(await this.claimCaseDbService.findById(claimRequestId)) ??
|
||||
|
||||
@@ -108,4 +108,17 @@ export class EnvironmentVariables {
|
||||
})
|
||||
CLAIM_V2_TOTAL_PAYMENT_CAP_TOMAN?: number;
|
||||
// --------------------------------------------------------- //
|
||||
@IsOptional()
|
||||
@IsBooleanString()
|
||||
AI_DAMAGE_ENABLED?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsUrl({ require_tld: false })
|
||||
AI_DAMAGE_URL?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(1000)
|
||||
@Max(600000)
|
||||
AI_DAMAGE_TIMEOUT_MS?: number;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,13 @@ export function validate(config: Record<string, unknown>) {
|
||||
enableImplicitConversion: true,
|
||||
});
|
||||
|
||||
if (
|
||||
validatedConfig.AI_DAMAGE_ENABLED === "true" &&
|
||||
!validatedConfig.AI_DAMAGE_URL
|
||||
) {
|
||||
throw new Error("AI_DAMAGE_URL is required when AI_DAMAGE_ENABLED=true");
|
||||
}
|
||||
|
||||
const errors = validateSync(validatedConfig, {
|
||||
skipMissingProperties: false,
|
||||
});
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { AiService } from "src/ai/ai.service";
|
||||
import { currentAiCaptures } from "src/ai/ai-captures";
|
||||
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import {
|
||||
Body,
|
||||
@@ -69,6 +72,8 @@ class InPersonVisitV2Dto {
|
||||
export class ExpertClaimV2Controller {
|
||||
constructor(
|
||||
private readonly expertClaimService: ExpertClaimService,
|
||||
private readonly aiService: AiService,
|
||||
private readonly claimCaseDbService: ClaimCaseDbService,
|
||||
private readonly claimRequestManagementService: ClaimRequestManagementService,
|
||||
) {}
|
||||
|
||||
@@ -182,6 +187,22 @@ export class ExpertClaimV2Controller {
|
||||
);
|
||||
}
|
||||
|
||||
@Get("request/:claimRequestId/ai-analysis")
|
||||
@ApiOperation({ summary: "AI damage analysis of current part photos (advisory only)" })
|
||||
async getAiAnalysis(@Param("claimRequestId") id: string, @CurrentUser() actor: any) {
|
||||
await this.expertClaimService.getClaimDetailV2(id, actor);
|
||||
const claim = await this.claimCaseDbService.findById(id);
|
||||
return this.aiService.list(id, currentAiCaptures(claim));
|
||||
}
|
||||
|
||||
@Post("request/:claimRequestId/ai-analysis/retry")
|
||||
@ApiOperation({ summary: "Retry failed AI analyses of current part photos" })
|
||||
async retryAiAnalysis(@Param("claimRequestId") id: string, @CurrentUser() actor: any) {
|
||||
await this.expertClaimService.getClaimDetailV2(id, actor);
|
||||
const claim = await this.claimCaseDbService.findById(id);
|
||||
return this.aiService.retry(id, currentAiCaptures(claim));
|
||||
}
|
||||
|
||||
@Get("request/:claimRequestId/fanavaran-vehicle-options")
|
||||
@ApiOperation({
|
||||
summary: "Get compatible Fanavaran vehicle classification options",
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { AiService } from "src/ai/ai.service";
|
||||
import { currentAiCaptures } from "src/ai/ai-captures";
|
||||
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
@@ -58,6 +61,8 @@ export class ExpertInsurerController {
|
||||
constructor(
|
||||
private readonly expertInsurerService: ExpertInsurerService,
|
||||
private readonly reportsService: ReportsService,
|
||||
private readonly aiService: AiService,
|
||||
private readonly claimCaseDbService: ClaimCaseDbService,
|
||||
) {}
|
||||
|
||||
// ─── Branch management ────────────────────────────────────────────────────
|
||||
@@ -403,6 +408,26 @@ export class ExpertInsurerController {
|
||||
return await this.expertInsurerService.getFileTimeline(insurer.clientKey, publicId);
|
||||
}
|
||||
|
||||
@Get("files/:publicId/ai-analysis")
|
||||
@ApiOperation({ summary: "AI damage analysis for an insurer's file" })
|
||||
async getAiAnalysis(@CurrentUser() insurer: any, @Param("publicId") publicId: string) {
|
||||
const detail = await this.expertInsurerService.retrieveFileDetailsByPublicId(insurer.clientKey, publicId);
|
||||
const id = typeof detail.claim?.claimRequestId === "string" ? detail.claim.claimRequestId : undefined;
|
||||
if (!id) return { enabled: this.aiService.enabled, images: [] };
|
||||
const claim = await this.claimCaseDbService.findById(id);
|
||||
return this.aiService.list(id, currentAiCaptures(claim));
|
||||
}
|
||||
|
||||
@Post("files/:publicId/ai-analysis/retry")
|
||||
@ApiOperation({ summary: "Retry failed AI analyses for an insurer's file" })
|
||||
async retryAiAnalysis(@CurrentUser() insurer: any, @Param("publicId") publicId: string) {
|
||||
const detail = await this.expertInsurerService.retrieveFileDetailsByPublicId(insurer.clientKey, publicId);
|
||||
const id = typeof detail.claim?.claimRequestId === "string" ? detail.claim.claimRequestId : undefined;
|
||||
if (!id) return { enabled: this.aiService.enabled, images: [] };
|
||||
const claim = await this.claimCaseDbService.findById(id);
|
||||
return this.aiService.retry(id, currentAiCaptures(claim));
|
||||
}
|
||||
|
||||
@Get("files/:publicId")
|
||||
@ApiParam({ name: "publicId" })
|
||||
async getFileDetailsByPublicId(@CurrentUser() insurer, @Param("publicId") publicId: string) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AiModule } from "src/ai/ai.module";
|
||||
import { Module } from "@nestjs/common";
|
||||
import { MongooseModule } from "@nestjs/mongoose";
|
||||
import { AuthModule } from "src/auth/auth.module";
|
||||
@@ -24,6 +25,7 @@ import { HashModule } from "src/utils/hash/hash.module";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
AiModule,
|
||||
ClaimRequestManagementModule,
|
||||
RequestManagementModule,
|
||||
AuthModule,
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { AiService } from "src/ai/ai.service";
|
||||
import { currentAiCaptures } from "src/ai/ai-captures";
|
||||
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
@@ -64,6 +67,8 @@ export class SuperAdminController {
|
||||
private readonly superAdminService: SuperAdminService,
|
||||
private readonly systemSettingsService: SystemSettingsService,
|
||||
private readonly expertInsurerService: ExpertInsurerService,
|
||||
private readonly aiService: AiService,
|
||||
private readonly claimCaseDbService: ClaimCaseDbService,
|
||||
) {}
|
||||
|
||||
// ── Super-admin account management ───────────────────────────────────────
|
||||
@@ -428,6 +433,28 @@ export class SuperAdminController {
|
||||
return this.expertInsurerService.getFileTimeline(clientId, publicId);
|
||||
}
|
||||
|
||||
@Get("insurer/files/:publicId/ai-analysis")
|
||||
@ApiOperation({ summary: "AI analysis for a file of the selected client" })
|
||||
@ApiQuery({ name: "clientId", required: true, type: String })
|
||||
async getAiAnalysis(@Query("clientId") clientId: string, @Param("publicId") publicId: string) {
|
||||
const detail = await this.expertInsurerService.retrieveFileDetailsByPublicId(clientId, publicId);
|
||||
const id = typeof detail.claim?.claimRequestId === "string" ? detail.claim.claimRequestId : undefined;
|
||||
if (!id) return { enabled: this.aiService.enabled, images: [] };
|
||||
const claim = await this.claimCaseDbService.findById(id);
|
||||
return this.aiService.list(id, currentAiCaptures(claim));
|
||||
}
|
||||
|
||||
@Post("insurer/files/:publicId/ai-analysis/retry")
|
||||
@ApiOperation({ summary: "Retry failed AI analyses for the selected client's file" })
|
||||
@ApiQuery({ name: "clientId", required: true, type: String })
|
||||
async retryAiAnalysis(@Query("clientId") clientId: string, @Param("publicId") publicId: string) {
|
||||
const detail = await this.expertInsurerService.retrieveFileDetailsByPublicId(clientId, publicId);
|
||||
const id = typeof detail.claim?.claimRequestId === "string" ? detail.claim.claimRequestId : undefined;
|
||||
if (!id) return { enabled: this.aiService.enabled, images: [] };
|
||||
const claim = await this.claimCaseDbService.findById(id);
|
||||
return this.aiService.retry(id, currentAiCaptures(claim));
|
||||
}
|
||||
|
||||
@Get("insurer/files/:publicId")
|
||||
@ApiOperation({ summary: "File details by publicId for a given client" })
|
||||
@ApiParam({ name: "publicId" })
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { AiModule } from "src/ai/ai.module";
|
||||
import { ClaimRequestManagementModule } from "src/claim-request-management/claim-request-management.module";
|
||||
import { Module } from "@nestjs/common";
|
||||
import { ClientModule } from "src/client/client.module";
|
||||
import { SystemSettingsModule } from "src/system-settings/system-settings.module";
|
||||
@@ -23,6 +25,8 @@ import { SuperAdminGuard } from "./guards/super-admin.guard";
|
||||
*/
|
||||
@Module({
|
||||
imports: [
|
||||
AiModule,
|
||||
ClaimRequestManagementModule,
|
||||
ClientModule,
|
||||
SystemSettingsModule,
|
||||
HashModule,
|
||||
|
||||
Reference in New Issue
Block a user