feat: replace OpenAI pricing with AI assessment estimates

Extend durable image assessments with explicit Persian vehicle names, deployment severity settings and advisory market prices normalized to rials. Preserve case access and retry boundaries, and remove the retired OpenAI pricing module and routes.
This commit is contained in:
SepehrYahyaee
2026-11-08 10:52:45 +03:30
parent a8bb0d8e35
commit 755e921c08
32 changed files with 638 additions and 2702 deletions
+71 -3
View File
@@ -1,6 +1,6 @@
# 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.
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 returns structured detections and optional advisory market prices, but no rendered image. The expert UI draws boxes on the captured photo.
## Enable in development
@@ -9,7 +9,8 @@ Set these **API environment variables** and restart the API:
```dotenv
AI_DAMAGE_ENABLED=true
AI_DAMAGE_URL=http://79.132.207.77:30531
AI_DAMAGE_TIMEOUT_MS=180000
AI_DAMAGE_TIMEOUT_MS=600000
AI_DAMAGE_PRICE_MIN_SEVERITY=severe
```
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.
@@ -30,7 +31,7 @@ No existing claim documents are migrated or rewritten. The old login/profile/dow
- 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 `POST /api/v1/assessments`, without the retired pipeline query flags. The provider also accepts batches of up to 12 images; this adapter intentionally keeps one photo per durable job, using the supported single-image request so results and retries stay tied to their source capture. Managed local files only; no URL fetching, redirects or arbitrary file paths. Maximum file size 15 MiB (enforced before upload), multipart body 16 MiB and response size 2 MiB.
- The worker sends one multipart `images` file to `POST /api/v1/assessments`, with `include_polygons=false` and `include_prices=false` for automatic capture analysis. Explicit expert pricing requests use `include_prices=true`, the configured `price_min_severity`, and a multipart `car` field. The provider also accepts batches of up to 12 images; this adapter intentionally keeps one photo per durable job, using the supported single-image request so results and retries stay tied to their source capture. Managed local files only; no URL fetching, redirects or arbitrary file paths. Maximum file size 15 MiB (enforced before upload), multipart body 16 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.
@@ -77,3 +78,70 @@ The historical live probe below used the retired pipeline. The assessment API mi
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.
## Unified advisory pricing
The OpenAI prompt/module, its routes under `/v2/price-estimation`, and the separate
expert price tab have been removed. No OpenAI key is needed in this API. Remove
`OPENAI_PRICE_ESTIMATION_*` from deployment settings. Existing price-estimate
collections are left intact; there is no database deletion or migration.
The existing AI tab now shows detection and market evidence together. Automatic
uploads continue to request detection only. An authorized reviewing expert confirms
or enters the damaged vehicle's Persian make/model, selects a current photo, then
requests **تحلیل و برآورد قیمت همین تصویر**. The input is prefilled from the panel's
resolved damaged-car identity when that name is Persian; missing or English-only
names require manual entry. The expert can correct an inquiry name before sending.
`POST /v2/expert-claim/request/:claimRequestId/ai-analysis/estimate` accepts:
```json
{"imageKey":"<64-character imageKey from the GET response>","carName":"پژو ۲۰۶ تیپ ۲"}
```
It uses the existing claim-detail authorization gate and accepts only a photo from
the current case's damage media. It queues work immediately rather than waiting on
the upstream model. Failed pricing can use the existing retry endpoint. A running
analysis or an already-queued pricing request returns 409 instead of queuing another
chargeable request. An explicit request after completion starts a fresh estimate.
The submitted car name and severity are stored with that image's job; polling
exposes these values while work is pending. Company/super-admin viewers may read
saved results and retry detection-only jobs but cannot submit or retry priced analyses.
The existing backend remains the authorized image transport, durable queue and
response adapter. Detection and pricing both come from the same assessment service;
there is no separate price-model prompt or market-research orchestration here.
### Deployment threshold
`AI_DAMAGE_PRICE_MIN_SEVERITY` accepts `minor`, `moderate`, `severe` (default) or
literal `null`. `minor` prices all damaged parts; `moderate` includes moderate and
severe parts; `severe` includes only severe parts. The provider's live OpenAPI
accepts only the three non-null enum strings, so the `null` setting is adapted to
`minor`, meaning all severities. Restart the API after changing configuration.
The threshold is recorded per requested job, including on retries.
### Units, completeness and interpretation
Provider monetary fields in tomans are converted to rials **once** by the response
normalizer: overall/genuine/aftermarket totals, component min/median/max, repair
estimates and individual listing prices. Missing/invalid/unsafe numbers remain null,
not zero. Unsupported currencies do not acquire a guessed conversion. Provider
processing cost remains in USD and duration remains milliseconds. The UI explicitly
labels monetary values as rials and identifies an LLM repair guess separately.
Each job uses one photo, so the provider's `pricing` summary is **that photo's**
summary, never a whole-claim total. The UI warns against summing photos: the same
physical part may appear in multiple photos. Incomplete results keep their partial
warning, priced/unpriced counts and available evidence. No algorithm maps the AI's
names to Fanavaran parts or writes prices/repair choices/price drop into the claim.
The expert selects the matching catalogue part and enters the final valuation.
Sources show used/unused status; only absolute HTTP(S) links without credentials
are clickable. Price ranges, sample count, spread warning, original/aftermarket
alternatives, notes, cache status, model, date, cost and duration remain available.
Legacy detection-only results still render normally. Opening the AI tab does not
start paid pricing. No real claim images were sent during implementation tests;
transport and UI tests use local fixtures. Validate actual market quality with the
AI team before relying on the estimates.