forked from Yara724/api
Added AI damage helper
This commit is contained in:
@@ -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)) ??
|
||||
|
||||
Reference in New Issue
Block a user