Merge pull request 'Added AI damage estimation helper' (#351) from s.yahyaee/yara724-api:main into main

Reviewed-on: Yara724/api#351
This commit is contained in:
2026-10-03 16:50:53 +03:30
22 changed files with 1085 additions and 442 deletions
+3 -4
View File
@@ -53,10 +53,9 @@ SANHUB_PASSWORD =
# --------------------------------------------- # ---------------------------------------------
# 🤖 AI Services # 🤖 AI Services
# --------------------------------------------- # ---------------------------------------------
AI_URL = AI_DAMAGE_ENABLED=false
AI_URL_V2 = AI_DAMAGE_URL=http://79.132.207.77:30527
AI_USERNAME = AI_DAMAGE_TIMEOUT_MS=180000
AI_PASSWORD =
# --------------------------------------------- # ---------------------------------------------
# 📩 SMS # 📩 SMS
Binary file not shown.
Binary file not shown.
+75
View File
@@ -0,0 +1,75 @@
# AI damage companion
This opt-in integration supplements the expert's claim review. It never changes workflow status, damage selection/history, prices, severity entered by experts, or compensation decisions. The pipeline currently returns no price estimates and no image. The expert UI draws boxes on the captured photo.
## Enable in development
Set these **API environment variables** and restart the API:
```dotenv
AI_DAMAGE_ENABLED=true
AI_DAMAGE_URL=http://79.132.207.77:30527
AI_DAMAGE_TIMEOUT_MS=180000
```
The integration is off when `AI_DAMAGE_ENABLED` is missing or false. Enabling it requires a valid URL. Keep it off in production during this development rollout. No frontend environment variable or credential is needed. The supplied pipeline has no authentication header.
Each API instance must have access to the same persistent `files` storage as the capture API. Jobs are stored in the existing MongoDB database's new `ai-damage-jobs` collection. Development creates the schema indexes automatically. If enabling in an environment with `autoIndex=false`, create both indexes first:
```javascript
db.getCollection('ai-damage-jobs').createIndex({ claimId: 1, imageKey: 1 }, { unique: true });
db.getCollection('ai-damage-jobs').createIndex({ status: 1, nextAttemptAt: 1, leaseUntil: 1 });
```
No existing claim documents are migrated or rewritten. The old login/profile/downloadLink adapter and in-memory queue have been removed. Historical legacy `aiImage`/`aiReport` values remain intact but are not used by the new companion.
## Capture and processing
- All current user, field expert, registrar, FileMaker and FileReviewer capture routes delegate to `capturePartV2`. Once a damaged-part photo is saved, it queues the exact local file. Car-angle captures, invoices, identity documents and signatures are excluded.
- Legacy part uploads also enqueue analysis separately from their existing image records.
- Enqueueing waits only for a Mongo upsert, never for inference; a persistence error is logged without failing upload. Viewing the tab re-schedules a missed current photo.
- One worker per instance polls every five seconds and claims one job atomically. A lease token guards completion writes across replicas. Expired leases recover after restart; leases last the configured HTTP timeout plus 60 seconds. Storage must be shared across replicas.
- Each claim/photo has one job. Repeated reads/uploads do not reset successful or failed analysis. Transient network/server/invalid-response failures retry up to three claims, with 30/60-second delays. Terminal 4xx image errors require explicit retry. A retry exhausted by process crashes is also marked failed.
- The worker sends one multipart `images` file to `/pipeline/detect_parts_with_damages`, with `side`, `segments`, `bounding_box`, `severity`, `confidence` all `true`. Managed local files only; no URL fetching, redirects or arbitrary file paths. Maximum file size 20 MiB and response size 2 MiB.
- The provider's OpenAPI describes JPEG inputs. Current camera/compression flows emit JPEG; a rejected older format stays visible with a recoverable analysis error.
- Current media determines the displayed photos. Replaced and removed photos' job results are retained separately, but never attached to a newer photo or inserted into the live carousel. Existing parts revision history is untouched.
## JSON and coordinates
The verified provider OpenAPI declares top-level `distinct_damaged_parts_report` (`parts`, `report`), `damaged_part_table`, and `case_report`. Each part includes `part_name` and optional nullable `damage_severity`, `part_bbox`, `confidence`, `side`, `car_side`.
The adapter validates this envelope, bounds response/detection sizes and stores a compact result: `parts[{name,severity,bbox,confidence,side,carSide}]`, `report`, `caseReport`. The duplicated `damaged_part_table` is unnecessary for rendering and is not stored. Repeated part names remain separate detections. Missing/invalid boxes or confidence do not produce guessed values. Invalid envelopes are failures, not successful empty analyses.
The drawing contract is **pixel coordinates in the uploaded image's displayed intrinsic orientation/dimensions**: `x1,y1,x2,y2`, origin top-left. The UI uses the original image's natural dimensions as the SVG viewBox, scales image and boxes together without letterboxing, and clips boxes to the image. If the provider instead emits resized-image coordinates or uses a different EXIF orientation, its contract must provide those dimensions/orientation before conversion; the UI does not infer them from the largest detection. Validate alignment using a known annotated photo supplied by the AI team before rollout.
No segmentation polygon is fabricated from a bounding box. The provider's current response has no usable mask/polygon field, despite `segments=true`.
## Expert UI and access
Open **گزارش خسارت → تحلیل هوش مصنوعی**. Select a photo, inspect numbered boxes, toggle overlays or select a detected part to highlight its box. Severity, confidence and side are shown next to the detection; Persian image summary and full report are available below. Unknown provider labels remain readable rather than being mapped to a guessed catalog ID.
Pending images poll every five seconds while the tab is mounted and inference is enabled. Failed images offer **تحلیل دوباره تصاویر ناموفق**. Empty, disabled, image-load failure, fetch failure and retry failure states have separate feedback. Existing successful results remain visible when inference is disabled.
Endpoints:
- `GET /v2/expert-claim/request/:claimRequestId/ai-analysis`
- `POST /v2/expert-claim/request/:claimRequestId/ai-analysis/retry`
- `GET /expert-insurer/files/:publicId/ai-analysis`
- `POST /expert-insurer/files/:publicId/ai-analysis/retry`
- Admin equivalents: `GET /super-admin/insurer/files/:publicId/ai-analysis?clientId=...` and `POST /super-admin/insurer/files/:publicId/ai-analysis/retry?clientId=...`
Expert endpoints reuse the exact existing claim-detail gate (role, organization, branch, ownership/reviewer assignment and workflow visibility). Insurer endpoints first resolve the existing tenant-scoped public file detail; callers cannot supply a different underlying claim ID. Admin equivalents retain `SuperAdminGuard` and resolve the file inside the explicitly selected client. No public or user endpoint exposes AI results. Responses expose image URLs, status, localized errors and completed compact results; no local paths, raw upstream response or credentials.
## Development acceptance checks
1. Enable the environment above; capture two damaged-part JPEGs through any current creation flow. Confirm immediate capture responses and queued/processing jobs.
2. Open claim review and its AI tab. Confirm each response belongs to its source photo, repeated detections remain distinct, and boxes line up on desktop/mobile. Confirm JSON severity/confidence and Persian reports match the provider.
3. Replace one photo via an allowed resend. Confirm the old result is not shown on the replacement. Remove a part through existing expert editing; confirm its image/result disappears from current analysis while selection history stays intact.
4. Stop/restart an API worker during analysis: after lease expiry, a worker must reclaim it. Repeat with two replicas sharing storage; completion must be guarded by the lease token.
5. Make the provider unavailable: capture and pricing must still work; retries should stop and the tab should offer retry. Try another tenant/unauthorized claim ID: analysis read/retry must be denied by existing file access controls.
## Implementation verification
On 2026-10-03 the real multipart adapter successfully called the development pipeline with [Front bumper broken.jpg](https://commons.wikimedia.org/wiki/File:Front_bumper_broken.jpg), a public photograph by Tiia Monto (CC BY-SA 3.0). It returned HTTP 200 and six detections, with Persian reports, severity, confidence and bounding boxes. Rendering was checked against the source JPEG's actual 2121×1188 dimensions. No customer photo was used for this probe. A separate synthetic blank JPEG returned HTTP 500; that failure is handled by the existing bounded retry/error path.
Backend checks cover upload-to-queue integration, immutable per-photo association, atomic job leases/recovery, retry limits, real multipart bytes/options, response validation, and expert/insurer/admin file-access gates. Frontend checks cover clipping/scaling, readable 24px number badges, report toggles, pending polling, retry, disabled cached results, empty images, fetch recovery and desktop/mobile overflow.
+12 -19
View File
@@ -422,28 +422,21 @@
</div> </div>
<!-- ═══════════════════════════════════════════════════════════ --> <!-- ═══════════════════════════════════════════════════════════ -->
<h2 id="ai">7 — AI Service <span class="status-badge status-disabled">disabled (code present)</span></h2> <h2 id="ai">7 — AI Damage Companion <span class="status-badge status-partial">opt-in development rollout</span></h2>
<p class="section-intro"> <p class="section-intro">
An image-based car damage detection service is integrated in the Damaged-part uploads schedule persisted background analysis in <code>ai-damage-jobs</code>.
codebase but its HTTP calls are <strong>fully commented out</strong>. Expert review shows the original photo with client-drawn bounding boxes, per-detection severity,
The module initialises on startup, attempts a login (silently swallowed confidence, side and Persian reports. The AI does not set prices, change selected parts,
if it fails), and exposes an <code>aiRequestImage</code> method — but advance workflow steps, or replace the expert decision.
the underlying axios calls are disabled. The service does not affect
any production flow.
</p> </p>
<div class="card card-yellow"> <div class="card card-yellow">
<h3>Intended interface (when re-enabled)</h3> <h3>Development pipeline</h3>
<table> <table>
<tr><th style="width:70px">Method</th><th>Path</th><th>What it does</th></tr> <tr><th style="width:70px">Method</th><th>Path</th><th>What it does</th></tr>
<tr><td><span class="method post">POST</span></td><td><code>{AI_URL_V2}/auth/login</code></td><td>Authenticate with username + password. Returns <code>accessToken</code>.</td></tr> <tr><td><span class="method post">POST</span></td><td><code>{AI_DAMAGE_URL}/pipeline/detect_parts_with_damages?side=true&amp;segments=true&amp;bounding_box=true&amp;severity=true&amp;confidence=true</code></td><td>One JPEG per multipart <code>images</code> request. Returns JSON detections and reports; no image URL or pricing.</td></tr>
<tr><td><span class="method get">GET</span></td><td><code>{AI_URL_V2}/auth/profile</code></td><td>Fetch <code>apiKey.key</code> needed as the <code>gateway-api-key</code> request header.</td></tr>
<tr><td><span class="method post">POST</span></td><td><code>{AI_URL_V2}/services/car-damage/detector?version=ai-v7</code></td><td>Submit a car part image (multipart). Returns <code>downloadLink</code> with annotated result.</td></tr>
</table> </table>
<p class="warn" style="margin-top:8px;"> <p class="note">Disabled unless <code>AI_DAMAGE_ENABLED=true</code>. Atomic leases recover jobs after restart; transient errors receive bounded retries. Uploads and expert review continue when AI is unavailable. Replaced or removed photos are excluded from the live AI tab. Older current captures are scheduled when an authorized reviewer opens the tab.</p>
Status: all three calls are wrapped in commented-out <code>axios.request(…)</code> blocks. <p><a href="ai-damage-companion.md">Configuration, result contract, access controls and rollout checks</a></p>
<code>CW_URL</code> is not in <code>.env.example</code>. To re-enable, uncomment the login, getApiKey, and aiRequestImage axios calls, and configure <code>AI_URL_V2</code>, <code>AI_USERNAME</code>, <code>AI_PASSWORD</code>.
</p>
</div> </div>
<!-- ═══════════════════════════════════════════════════════════ --> <!-- ═══════════════════════════════════════════════════════════ -->
@@ -563,9 +556,9 @@
<h3>AI service</h3> <h3>AI service</h3>
<table class="env-table"> <table class="env-table">
<tr><th>Variable</th><th>Description</th></tr> <tr><th>Variable</th><th>Description</th></tr>
<tr><td><code>AI_URL_V2</code></td><td>AI gateway base URL. Default: <code>https://ai-gw.ittalie.ir</code> (unused — service is disabled)</td></tr> <tr><td><code>AI_DAMAGE_ENABLED</code></td><td>Explicit opt-in (<code>true</code>); defaults to disabled.</td></tr>
<tr><td><code>AI_USERNAME</code></td><td>AI service login username (unused)</td></tr> <tr><td><code>AI_DAMAGE_URL</code></td><td>Development base URL: <code>http://79.132.207.77:30527</code>. Required when enabled.</td></tr>
<tr><td><code>AI_PASSWORD</code></td><td>AI service login password (unused)</td></tr> <tr><td><code>AI_DAMAGE_TIMEOUT_MS</code></td><td>Request timeout; default 180000 ms (1000–600000).</td></tr>
</table> </table>
</div> </div>
+86
View File
@@ -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();
},
);
});
+102
View File
@@ -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();
});
});
+27
View File
@@ -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 || "تصویر خسارت",
},
];
});
}
+26
View File
@@ -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 });
+95
View File
@@ -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);
});
});
+63
View File
@@ -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
View File
@@ -1,8 +1,12 @@
import { Module } from "@nestjs/common"; import { Module } from "@nestjs/common";
import { MongooseModule } from "@nestjs/mongoose";
import { AiService } from "./ai.service"; import { AiService } from "./ai.service";
import { AiJob, AiJobSchema } from "./ai-job.schema";
@Module({ @Module({
imports: [], imports: [
MongooseModule.forFeature([{ name: AiJob.name, schema: AiJobSchema }]),
],
providers: [AiService], providers: [AiService],
exports: [AiService], exports: [AiService],
}) })
+266
View File
@@ -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 });
}
});
});
+228 -183
View File
@@ -1,204 +1,249 @@
import { createReadStream, existsSync } from "node:fs"; import { createHash, randomUUID } from "node:crypto";
import { join } from "node:path"; import { createReadStream } from "node:fs";
import { realpath, stat } from "node:fs/promises";
import { basename, resolve, sep } from "node:path";
import { import {
HttpException,
HttpStatus,
Injectable, Injectable,
Logger,
OnModuleDestroy,
OnModuleInit, OnModuleInit,
} from "@nestjs/common"; } from "@nestjs/common";
import { ConfigService } from "@nestjs/config"; 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";
@Injectable() export interface AiCapture {
export class AiService implements OnModuleInit {
private apiKey: string;
private accessToken: string = null;
// 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}`,
},
};
}
// 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}`,
},
};
}
async onModuleInit() {
try {
const res = await this.login();
// if (res?.accessToken) {
// this.accessToken = res.accessToken;
// await this.getApiKey();
// }
} 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;
}
}
private async login() {
// const loginResponse = await axios.request(this.loginOptions);
// return loginResponse.data;
}
private async getApiKey() {
// const profileResponse = await axios.request(this.profileOptions);
// this.apiKey = profileResponse.data.apiKey.key;
// return this.apiKey;
}
public async aiRequestImage(file: {
path: string; path: string;
fileName?: string; fileName?: string;
}): Promise<any> { label?: string;
// Ensure authentication is set up }
if (!this.accessToken || !this.apiKey) { export const aiImageKey = (path: string) =>
createHash("sha256").update(resolve(path)).digest("hex");
@Injectable()
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>,
) {}
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),
);
}
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();
}
/** 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 { try {
const res = await this.login(); await this.jobs.updateOne(
// if (res?.accessToken) { { claimId, imageKey: aiImageKey(image.path) },
// this.accessToken = res.accessToken; {
// await this.getApiKey(); $setOnInsert: {
// } else { claimId,
// throw new HttpException( imageKey: aiImageKey(image.path),
// "AI Service authentication failed", path: image.path,
// HttpStatus.UNAUTHORIZED, fileName: image.fileName,
// ); status: "queued",
// } attempts: 0,
nextAttemptAt: new Date(),
},
},
{ upsert: true },
);
} catch (error) { } catch (error) {
throw new HttpException( // Concurrent duplicate uploads are already queued. A storage outage must not fail capture.
"AI Service authentication failed", if ((error as any)?.code !== 11000)
HttpStatus.UNAUTHORIZED, this.logger.error(
"Could not persist AI job; expert review will retry scheduling.",
); );
} }
} }
// Resolve relative paths to absolute paths async list(claimId: string, images: AiCapture[]) {
const filePath = file.path.startsWith("/") // Older captures and jobs missed during a database outage are scheduled on review.
? file.path for (const image of images) await this.enqueue(claimId, image);
: join(process.cwd(), file.path.replace(/^\.\//, "")); const keys = images.map((image) => aiImageKey(image.path));
const rows = await this.jobs
// Check if file exists .find({ claimId, imageKey: { $in: keys } })
if (!existsSync(filePath)) { .lean();
throw new HttpException( const byKey = new Map(rows.map((row) => [row.imageKey, row]));
`File not found: ${file.path}`, return {
HttpStatus.NOT_FOUND, enabled: this.enabled,
); images: images.map((image) => {
} const key = aiImageKey(image.path);
const job = byKey.get(key);
// const form = new FormData(); return {
const fileStream = createReadStream(filePath); imageKey: key,
label: image.label ?? "تصویر خسارت",
// Append file with filename if available imageUrl: buildFileLink(image.path),
if (file.fileName) { status: job?.status ?? (this.enabled ? "queued" : "disabled"),
// form.append("images", fileStream, file.fileName); attempts: job?.attempts ?? 0,
} else { completedAt: job?.completedAt,
// Extract filename from path if not provided error: job?.error,
const pathParts = filePath.split("/"); result: job?.status === "completed" ? job.result : undefined,
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 async retry(claimId: string, images: AiCapture[]) {
throw new HttpException( if (this.enabled)
`[${errorSource}] ${errorMessage}`, await this.jobs.updateMany(
er.response?.status || HttpStatus.INTERNAL_SERVER_ERROR, {
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);
}
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 {
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) {
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"}.`,
);
}
} 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; 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). * 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( private async processDamageImages(
document: any, document: any,
requestId: string, requestId: string,
@@ -2336,8 +2114,6 @@ export class ClaimRequestManagementService {
imageRequiredKeys: string[], imageRequiredKeys: string[],
result: any[], result: any[],
) { ) {
const aiRequestQueue = [];
for (const key of imageRequiredKeys) { for (const key of imageRequiredKeys) {
const images = document.imageRequired[key]; const images = document.imageRequired[key];
for (const img of images) { for (const img of images) {
@@ -2347,12 +2123,6 @@ export class ClaimRequestManagementService {
requestId, 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 // Update the document immediately with the uploaded image
await this.updateImageRequiredDocument( await this.updateImageRequiredDocument(
requestId, requestId,
@@ -2360,6 +2130,9 @@ export class ClaimRequestManagementService {
partOfDamageId, partOfDamageId,
newImageDoc, newImageDoc,
); );
if (key === "selectPartOfCar") {
await this.aiService.enqueue(requestId, newImageDoc);
}
const updatedDocs = const updatedDocs =
await this.claimDbService.findOneDocument(requestId); await this.claimDbService.findOneDocument(requestId);
this.handleImageUpdateResult(result, updatedDocs, 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( private async updateImageRequiredDocument(
@@ -11728,6 +11488,9 @@ export class ClaimRequestManagementService {
claimRequestId, claimRequestId,
updateData, updateData,
); );
if (!treatAsAngle) {
await this.aiService.enqueue(claimRequestId, captureData);
}
// Re-read so capture-progress sees sibling concurrent part/angle writes. // Re-read so capture-progress sees sibling concurrent part/angle writes.
const updatedClaim = const updatedClaim =
(await this.claimCaseDbService.findById(claimRequestId)) ?? (await this.claimCaseDbService.findById(claimRequestId)) ??
+13
View File
@@ -108,4 +108,17 @@ export class EnvironmentVariables {
}) })
CLAIM_V2_TOTAL_PAYMENT_CAP_TOMAN?: number; 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
View File
@@ -7,6 +7,13 @@ export function validate(config: Record<string, unknown>) {
enableImplicitConversion: true, 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, { const errors = validateSync(validatedConfig, {
skipMissingProperties: false, 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 { readFile } from "node:fs/promises";
import { import {
Body, Body,
@@ -69,6 +72,8 @@ class InPersonVisitV2Dto {
export class ExpertClaimV2Controller { export class ExpertClaimV2Controller {
constructor( constructor(
private readonly expertClaimService: ExpertClaimService, private readonly expertClaimService: ExpertClaimService,
private readonly aiService: AiService,
private readonly claimCaseDbService: ClaimCaseDbService,
private readonly claimRequestManagementService: ClaimRequestManagementService, 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") @Get("request/:claimRequestId/fanavaran-vehicle-options")
@ApiOperation({ @ApiOperation({
summary: "Get compatible Fanavaran vehicle classification options", 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 { import {
BadRequestException, BadRequestException,
Body, Body,
@@ -58,6 +61,8 @@ export class ExpertInsurerController {
constructor( constructor(
private readonly expertInsurerService: ExpertInsurerService, private readonly expertInsurerService: ExpertInsurerService,
private readonly reportsService: ReportsService, private readonly reportsService: ReportsService,
private readonly aiService: AiService,
private readonly claimCaseDbService: ClaimCaseDbService,
) {} ) {}
// ─── Branch management ──────────────────────────────────────────────────── // ─── Branch management ────────────────────────────────────────────────────
@@ -403,6 +408,26 @@ export class ExpertInsurerController {
return await this.expertInsurerService.getFileTimeline(insurer.clientKey, publicId); 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") @Get("files/:publicId")
@ApiParam({ name: "publicId" }) @ApiParam({ name: "publicId" })
async getFileDetailsByPublicId(@CurrentUser() insurer, @Param("publicId") publicId: string) { 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 { Module } from "@nestjs/common";
import { MongooseModule } from "@nestjs/mongoose"; import { MongooseModule } from "@nestjs/mongoose";
import { AuthModule } from "src/auth/auth.module"; import { AuthModule } from "src/auth/auth.module";
@@ -24,6 +25,7 @@ import { HashModule } from "src/utils/hash/hash.module";
@Module({ @Module({
imports: [ imports: [
AiModule,
ClaimRequestManagementModule, ClaimRequestManagementModule,
RequestManagementModule, RequestManagementModule,
AuthModule, AuthModule,
+27
View File
@@ -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 { import {
BadRequestException, BadRequestException,
Body, Body,
@@ -64,6 +67,8 @@ export class SuperAdminController {
private readonly superAdminService: SuperAdminService, private readonly superAdminService: SuperAdminService,
private readonly systemSettingsService: SystemSettingsService, private readonly systemSettingsService: SystemSettingsService,
private readonly expertInsurerService: ExpertInsurerService, private readonly expertInsurerService: ExpertInsurerService,
private readonly aiService: AiService,
private readonly claimCaseDbService: ClaimCaseDbService,
) {} ) {}
// ── Super-admin account management ─────────────────────────────────────── // ── Super-admin account management ───────────────────────────────────────
@@ -428,6 +433,28 @@ export class SuperAdminController {
return this.expertInsurerService.getFileTimeline(clientId, publicId); 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") @Get("insurer/files/:publicId")
@ApiOperation({ summary: "File details by publicId for a given client" }) @ApiOperation({ summary: "File details by publicId for a given client" })
@ApiParam({ name: "publicId" }) @ApiParam({ name: "publicId" })
+4
View File
@@ -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 { Module } from "@nestjs/common";
import { ClientModule } from "src/client/client.module"; import { ClientModule } from "src/client/client.module";
import { SystemSettingsModule } from "src/system-settings/system-settings.module"; import { SystemSettingsModule } from "src/system-settings/system-settings.module";
@@ -23,6 +25,8 @@ import { SuperAdminGuard } from "./guards/super-admin.guard";
*/ */
@Module({ @Module({
imports: [ imports: [
AiModule,
ClaimRequestManagementModule,
ClientModule, ClientModule,
SystemSettingsModule, SystemSettingsModule,
HashModule, HashModule,