import { ForbiddenException, ValidationPipe } from "@nestjs/common"; import { ConfigService } from "@nestjs/config"; import { Test } from "@nestjs/testing"; import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger"; import { Types } from "mongoose"; import { of } from "rxjs"; import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard"; import { RolesGuard } from "src/auth/guards/role.guard"; import { RoleEnum } from "src/Types&Enums/role.enum"; import { validate } from "src/core/config/config.validation"; import { buildEstimateContext, estimateDate, publicEstimateContext, } from "./price-estimation-context"; import { normalizeEstimate } from "./estimate-output"; import { OpenAiPriceProvider, PRICE_ESTIMATE_INSTRUCTIONS, PRICE_ESTIMATE_PROMPT_VERSION, } from "./openai-price-provider"; import { PriceEstimationService } from "./price-estimation.service"; import { CreatePriceEstimateDto } from "./price-estimation.dto"; import { EstimateObjectIdPipe, PriceEstimationController, } from "./price-estimation.controller"; const claimId = "670000000000000000000001", firstId = "670000000000000000000002", secondId = "670000000000000000000003"; const actor = { sub: "670000000000000000000004", role: RoleEnum.DAMAGE_EXPERT, clientKey: "tenant", }; const sourceUrl = "https://shop.example/peugeot-206/bumper"; const r = (n: number) => ({ low: n, likely: n, high: n }); function source() { const blame: any = { _id: new Types.ObjectId(), type: "THIRD_PARTY", expert: { decision: { guiltyPartyId: firstId } }, parties: [ { role: "FIRST", person: { userId: firstId, fullName: "PRIVATE-NAME", nationalCode: "PRIVATE-NATIONAL", }, vehicle: { name: "CULPRIT-CAR", model: "CULPRIT-MODEL" }, }, { role: "SECOND", person: { userId: secondId }, vehicle: { name: "پژو", model: "۲۰۶ تیپ ۲", vin: "PRIVATE-VIN", plateId: "PRIVATE-PLATE", inquiry: { mapped: { ModelField: 1402, SystemField: "پژو", TypeField: "۲۰۶", ColorField: "سفید", NationalCode: "PRIVATE-INQUIRY", }, }, }, }, ], }; const claim: any = { _id: claimId, blameRequestId: blame._id, owner: { userId: firstId }, damagedPartyUserId: secondId, vehicle: { carName: "WRONG-OWNER-CAR", carModel: "sedan", carType: "sedan", carPrice: 200000, }, inquiries: { thirdParty: { data: { FIRST: { mapped: { SystemField: "CULPRIT-INQUIRY" } }, SECOND: { mapped: { SystemField: "پژو", TypeField: "۲۰۶", VehicleValue: 1000000, }, }, }, }, }, damage: { selectedParts: [ { id: 11, name: "bumper", side: "front", label_fa: "سپر جلو" }, ], }, money: { sheba: "PRIVATE-SHEBA" }, media: { damagedParts: [ { id: 11, name: "bumper", side: "front", path: "files/claim-captures/photo.jpg", }, ], }, }; return { claim, blame }; } function context(options: CreatePriceEstimateDto = {}) { const f = source(); return buildEstimateContext( f.claim, f.blame, options, new Date("2026-10-06T12:00:00Z"), ); } function output(): any { return { summary: "برآورد اولیه", vehicleValue: { rangeRial: r(10000), confidence: "medium", sourceUrls: [sourceUrl], explanation: "خودرو مشابه", }, parts: [ { partKey: "outer:0", severity: "severe", recommendation: "replace", replacementPriceRial: r(400), laborPriceRial: r(100), paintPriceRial: r(0), confidence: "medium", sourceUrls: [sourceUrl], explanation: "نیاز به تعویض", }, ], depreciation: { percent: r(3), confidence: "low", sourceUrls: [], explanation: "افت بازار؛ تخمین اولیه", }, sources: [ { url: sourceUrl, title: "سپر پژو", evidence: "قیمت پیشنهادی فروشنده", originalPrice: 40, originalCurrency: "IRT", partKeys: ["outer:0"], }, ], assumptions: ["بدون تصادف قبلی"], warnings: [], }; } function response(data = output()): any { return { id: "resp-test", model: "gpt-5.4", status: "completed", usage: { input_tokens: 200, output_tokens: 100, total_tokens: 300 }, output: [ { type: "web_search_call", status: "completed", action: { sources: [{ type: "url", url: sourceUrl }] }, }, { type: "message", role: "assistant", content: [ { type: "output_text", text: JSON.stringify(data), annotations: [] }, ], }, ], }; } function serviceHarness(enabled = true) { const f = source(), rows: any[] = []; const configValues = { OPENAI_PRICE_ESTIMATION_ENABLED: String(enabled), OPENAI_PRICE_ESTIMATION_API_KEY: "test-key", }; const config = { get: jest.fn((key) => configValues[key]) }; const query = (value: any) => ({ lean: async () => value, sort: function () { return this; }, select: function () { return this; }, }); const jobs = { findOneAndUpdate: jest.fn((filter, update, options) => { let row: any; if (filter.$or) { row = rows.find( (entry) => entry.status === "queued" || (entry.status === "processing" && entry.leaseUntil <= new Date()), ); } else if (options?.upsert) { row = rows.find( (entry) => entry.claimId === filter.claimId && entry.fingerprint === filter.fingerprint, ); if (!row) { row = { _id: String(new Types.ObjectId()), createdAt: new Date(), ...update.$setOnInsert, }; rows.push(row); } } else row = rows.find( (entry) => String(entry._id) === String(filter._id) && entry.claimId === filter.claimId && entry.status === filter.status, ); if (row) { Object.assign(row, update.$set); for (const [key, amount] of Object.entries(update.$inc ?? {})) row[key] = (row[key] ?? 0) + Number(amount); for (const key of Object.keys(update.$unset ?? {})) delete row[key]; } return query(row ? { ...row } : null); }), findOne: jest.fn((filter) => query( rows .filter( (entry) => (!filter.claimId || entry.claimId === filter.claimId) && (!filter._id || String(entry._id) === String(filter._id)) && (!filter.fingerprint || entry.fingerprint === filter.fingerprint), ) .at(-1) ?? null, ), ), updateOne: jest.fn(async (filter, update) => { const row = rows.find( (entry) => entry._id === filter._id && entry.leaseToken === filter.leaseToken && entry.status === filter.status, ); if (row) { Object.assign(row, update.$set); for (const key of Object.keys(update.$unset ?? {})) delete row[key]; } }), }; const claims = { findById: jest.fn().mockResolvedValue(f.claim) }; const blames = { findById: jest.fn().mockResolvedValue(f.blame) }; const access = { getClaimDetailV2: jest.fn().mockResolvedValue({}) }; const provider = { timeout: 240000, estimate: jest.fn().mockResolvedValue({ result: { advisoryOnly: true }, provider: { responseId: "resp" }, }), }; const images = { read: jest.fn().mockResolvedValue({ buffer: Buffer.from("photo"), sha256: "photo-hash", }), }; const detections = { find: jest.fn(() => query([])) }; const service = new PriceEstimationService( config as any, jobs as any, claims as any, blames as any, access as any, provider as any, images as any, detections as any, ); (service as any).logger = { warn: jest.fn(), error: jest.fn() }; return { service, f, rows, configValues, jobs, claims, blames, access, provider, images, }; } describe("price estimate input isolation", () => { it("uses the damaged SECOND vehicle even when historical owner is FIRST and excludes identity/inquiry secrets", () => { const input = context(); expect(input.vehicle.make).toBe("پژو"); expect(input.vehicle.model).toBe("۲۰۶ تیپ ۲"); expect(input.vehicle.modelYear).toBe(1402); expect(input.vehicle.yearCalendar).toBe("jalali"); expect(input.vehicle.currentMarketValueRial).toBeNull(); expect(input.photos).toHaveLength(1); const safe = JSON.stringify(publicEstimateContext(input)); expect(safe).not.toMatch(/PRIVATE|CULPRIT|WRONG-OWNER|files\/claim/); }); it("does not send the unrelated 111SE variant from a conflicting FAW inquiry", () => { const { claim, blame } = source(); blame.parties[1].vehicle = { name: "فائو ( FAW )", model: "111SE", inquiry: { mapped: { MapTypNam: "فائو ( FAW )", SystemField: "سايپا", TypeField: "111SE", }, }, }; const input = buildEstimateContext(claim, blame, {}); expect(input.vehicle.make).toBe("فائو ( FAW )"); expect(input.vehicle.model).toBeNull(); expect(input.warnings.join(" ")).toContain("هم‌خوان نیست"); expect(JSON.stringify(publicEstimateContext(input))).not.toContain("111SE"); }); it("uses body insurance FIRST, expert-approved vehicle names and supplied current market value", () => { const { claim, blame } = source(); blame.type = "CAR_BODY"; blame.parties[0].vehicle = { name: "ایران خودرو", model: "دنا پلاس" }; blame.parties[1].vehicle = { name: "OTHER-CAR", model: "OTHER-MODEL" }; claim.owner.userId = firstId; claim.fanavaranVehicleReview = { approved: true, vehicleSystem: { caption: "ایران خودرو" }, vehicleKind: { caption: "دنا پلاس" }, }; claim.fanavaranFieldReview = { values: { VehicleCurrentValue: 500000 } }; const input = buildEstimateContext(claim, blame, { currentMarketValueRial: 800000, modelYear: 2023, mileageKm: 0, }); expect(input.vehicle).toMatchObject({ make: "ایران خودرو", model: "دنا پلاس", currentMarketValueRial: 800000, valueSource: "request", insuredValueRial: 200000, yearCalendar: "gregorian", mileageKm: 0, }); expect(buildEstimateContext(claim, blame, {}).vehicle).toMatchObject({ currentMarketValueRial: 500000, valueSource: "expert_record", }); expect(JSON.stringify(publicEstimateContext(input))).not.toContain( "OTHER-", ); }); it("uses FIRST when SECOND is guilty, without merging the second car's details", () => { const { claim, blame } = source(); blame.expert.decision.guiltyPartyId = secondId; blame.parties[0].vehicle = { name: "مزدا", model: "۳", inquiry: { mapped: { ModelField: 1399 } }, }; blame.parties[1].vehicle = { name: "OTHER-CAR", model: "OTHER-MODEL", }; claim.damagedPartyUserId = firstId; claim.owner.userId = secondId; claim.inquiries.thirdParty.data.FIRST.mapped = { SystemField: "مزدا", VehicleValue: 300000, }; claim.inquiries.thirdParty.data.SECOND.mapped.SystemField = "OTHER-INQUIRY"; const input = buildEstimateContext(claim, blame, {}); expect(input.vehicle).toMatchObject({ make: "مزدا", model: "۳", modelYear: 1399, insuredValueRial: 300000, }); expect(JSON.stringify(publicEstimateContext(input))).not.toMatch( /OTHER-|WRONG-OWNER/, ); }); it("uses the persisted damaged party for expert-created claims before a blame decision exists", () => { const { claim, blame } = source(); blame.expert = {}; blame.status = "WAITING_FOR_FILE_REVIEWER"; expect(buildEstimateContext(claim, blame, {}).vehicle).toMatchObject({ make: "پژو", model: "۲۰۶ تیپ ۲", modelYear: 1402, }); }); it("uses only the persisted beneficiary's snapshot when the blame is unavailable", () => { const { claim, blame } = source(); claim.snapshot = { parties: blame.parties }; expect(buildEstimateContext(claim, null, {}).vehicle).toMatchObject({ make: "پژو", model: "۲۰۶ تیپ ۲", modelYear: 1402, }); expect(buildEstimateContext(claim, { parties: [] }, {}).vehicle.make).toBe( "پژو", ); }); it.each([secondId, undefined])( "does not use an unverified historical owner when blame and party snapshots are missing (%s)", (damagedPartyUserId) => { const { claim } = source(); claim.damagedPartyUserId = damagedPartyUserId; const input = buildEstimateContext(claim, null, {}); expect(input.vehicle).toMatchObject({ make: null, model: null, modelYear: null, insuredValueRial: null, }); expect(JSON.stringify(publicEstimateContext(input))).not.toMatch( /CULPRIT|WRONG-OWNER/, ); }, ); it("retains a verified damaged owner's vehicle and standalone legacy vehicle", () => { const { claim } = source(); claim.owner.userId = secondId; claim.vehicle.carName = "پژو"; claim.vehicle.carModel = "۲۰۶"; expect(buildEstimateContext(claim, null, {}).vehicle.make).toBe("پژو"); delete claim.blameRequestId; delete claim.damagedPartyUserId; expect(buildEstimateContext(claim, null, {}).vehicle.make).toBe("پژو"); }); it("does not attach removed photos and keeps newly added unphotographed/internal parts", () => { const { claim, blame } = source(); claim.damage.selectedParts.push({ id: 12, name: "door", side: "left", label_fa: "درب", }); claim.damage.otherParts = ["engine", "engine"]; claim.media.damagedParts.push({ id: 99, name: "removed", path: "files/removed.jpg", }); claim.media.carAngles = new Map([["front", { path: "files/front.jpg" }]]); const input = buildEstimateContext(claim, blame, {}); expect(input.parts).toHaveLength(3); expect(input.photos.map((photo) => photo.path)).toEqual([ "files/claim-captures/photo.jpg", "files/front.jpg", ]); expect(input.warnings.length).toBeGreaterThan(0); }); it("refuses empty part lists and uses Tehran's research day across UTC midnight", () => { const { claim, blame } = source(); claim.damage.selectedParts = []; expect(() => buildEstimateContext(claim, blame, {})).toThrow( "Select damaged parts", ); expect(estimateDate(new Date("2026-10-05T21:00:00Z"))).toBe("2026-10-06"); }); }); describe("price estimate evidence and arithmetic", () => { it("keeps a sourced vehicle-market quote separate from a part purchase quote", () => { const value = output(); const vehicleUrl = "https://cars.example/peugeot-206"; value.vehicleValue.sourceUrls = [vehicleUrl]; value.sources.push({ url: vehicleUrl, title: "پژو ۲۰۶", evidence: "خودرو مشابه", originalPrice: 1000, originalCurrency: "IRT", partKeys: [], }); const result = normalizeEstimate(value, context(), [sourceUrl, vehicleUrl]); expect(result.vehicleValue.rangeRial).toEqual(r(10000)); expect(result.depreciation.amountRial).toEqual(r(300)); }); it.each(["unknown-unit", "missing-price", "different-part"])( "does not accept a purchase quote with %s", (kind) => { const value = output(); if (kind === "unknown-unit") value.sources[0].originalCurrency = "unknown"; if (kind === "missing-price") value.sources[0].originalPrice = null; if (kind === "different-part") value.sources[0].partKeys = []; const result = normalizeEstimate(value, context(), [sourceUrl]); expect(result.parts[0].replacementPriceRial).toBeNull(); expect(result.totals.complete).toBe(false); }, ); it("normalizes quoted tomans to rials and computes repair/depreciation deterministically", () => { const result = normalizeEstimate( output(), context({ currentMarketValueRial: 20000 }), [sourceUrl], ); expect(result.sources[0].listedPriceRial).toBe(400); expect(result.parts[0].recommendedCostRial).toEqual(r(500)); expect(result.totals).toMatchObject({ knownRepairCostRial: r(500), complete: true, }); expect(result.vehicleValue.rangeRial).toEqual(r(20000)); expect(result.vehicleValue.basis).toBe("request"); expect(result.depreciation.amountRial).toEqual(r(600)); expect(result.advisoryOnly).toBe(true); }); it("removes invented links and refuses unsourced purchase/vehicle values instead of inventing zero", () => { const result = normalizeEstimate(output(), context(), []); expect(result.sources).toEqual([]); expect(result.parts[0].replacementPriceRial).toBeNull(); expect(result.parts[0].recommendedCostRial).toBeNull(); expect(result.vehicleValue.rangeRial).toBeNull(); expect(result.depreciation.amountRial).toBeNull(); expect(result.totals).toMatchObject({ knownRepairCostRial: null, complete: false, missingPartKeys: ["outer:0"], }); }); it.each([ "negative", "reversed", "unknown-part", "duplicate", "overflow", "extra-field", ])("rejects invalid model output: %s", (kind) => { const value = output(); if (kind === "negative") value.parts[0].laborPriceRial.low = -1; if (kind === "reversed") value.parts[0].replacementPriceRial.low = 999; if (kind === "unknown-part") value.parts[0].partKey = "outer:999"; if (kind === "duplicate") value.parts.push(value.parts[0]); if (kind === "overflow") value.parts[0].laborPriceRial = r(Number.MAX_SAFE_INTEGER); if (kind === "extra-field") value.overwriteExpertPrice = true; expect(() => normalizeEstimate(value, context(), [sourceUrl])).toThrow( "INVALID_OUTPUT", ); }); it("keeps every selected part when the model omits a line and marks the budget incomplete", () => { const value = output(); value.parts = []; const result = normalizeEstimate(value, context(), [sourceUrl]); expect(result.parts[0]).toMatchObject({ partKey: "outer:0", catalogId: 11, recommendation: "inspect", severity: "unknown", replacementPriceRial: null, }); expect(result.totals.complete).toBe(false); }); }); describe("OpenAI Responses request/response adapter", () => { function provider(data = response()) { const http = { post: jest.fn().mockReturnValue(of({ data })) }; const images = { read: jest.fn().mockResolvedValue({ buffer: Buffer.from("jpeg-bytes"), mime: "image/jpeg", }), }; const service = new OpenAiPriceProvider( new ConfigService({ OPENAI_PRICE_ESTIMATION_API_KEY: "separate-key" }), http as any, images as any, ); return { service, http, images }; } it("sends exact image bytes with required live search, a strict schema and store=false", async () => { const h = provider(); const result = await h.service.estimate(context(), "gpt-5.4"); const [url, body, options] = h.http.post.mock.calls[0] as any; expect(url).toBe("https://api.openai.com/v1/responses"); expect(body).toMatchObject({ model: "gpt-5.4", store: false, tools: [{ type: "web_search" }], tool_choice: "required", text: { format: { type: "json_schema", strict: true } }, }); expect( body.input[0].content.find((part) => part.type === "input_image") .image_url, ).toBe( `data:image/jpeg;base64,${Buffer.from("jpeg-bytes").toString("base64")}`, ); expect(body.input[0].content[0].text).not.toContain("files/claim-captures"); const supplied = JSON.parse(body.input[0].content[0].text); expect(supplied.assessmentScope).toBe("damaged_party_vehicle_only"); expect(supplied.vehicle).toMatchObject({ make: "پژو", model: "۲۰۶ تیپ ۲", }); expect(body.input[0].content[0].text).not.toMatch( /CULPRIT|WRONG-OWNER|PRIVATE/, ); expect(body.instructions).toBe(PRICE_ESTIMATE_INSTRUCTIONS); expect(body.instructions).toContain("exactly ONE vehicle"); expect(body.instructions).toContain("including the culprit's car"); expect(body.instructions).toContain("leave unsupported estimates null"); expect(PRICE_ESTIMATE_PROMPT_VERSION).toBe( "iran-parts-v2-damaged-vehicle-only", ); expect(options).toMatchObject({ timeout: 240000, maxRedirects: 0, headers: { Authorization: "Bearer separate-key" }, }); expect(result.provider.usage.totalTokens).toBe(300); expect(result.result.parts[0].replacementPriceRial).toEqual(r(400)); }); it.each(["incomplete", "refusal", "no-search", "invalid-json"])( "rejects provider %s responses", async (kind) => { const data = response(); if (kind === "incomplete") data.status = "incomplete"; if (kind === "refusal") data.output[1].content = [ { type: "refusal", refusal: "Cannot respond" }, ]; if (kind === "no-search") data.output.shift(); if (kind === "invalid-json") data.output[1].content[0].text = "not-json"; await expect( provider(data).service.estimate(context(), "gpt-5.4"), ).rejects.toThrow(); }, ); }); describe("persisted price estimate jobs", () => { it.each(["request", "get", "retry"])( "authorizes %s before accessing jobs/photos or scheduling chargeable work", async (method) => { const h = serviceHarness(); h.access.getClaimDetailV2.mockRejectedValue(new ForbiddenException()); const action = method === "request" ? h.service.request(claimId, actor, {}) : method === "get" ? h.service.get(claimId, actor) : h.service.retry(claimId, "job", actor); await expect(action).rejects.toThrow(ForbiddenException); expect(h.jobs.findOneAndUpdate).not.toHaveBeenCalled(); expect(h.jobs.findOne).not.toHaveBeenCalled(); expect(h.images.read).not.toHaveBeenCalled(); expect(h.provider.estimate).not.toHaveBeenCalled(); }, ); it("does nothing while disabled and permits already stored reads", async () => { const h = serviceHarness(false); h.service.onModuleInit(); await h.service.work(); await expect(h.service.request(claimId, actor, {})).rejects.toThrow( "disabled", ); expect(h.jobs.findOneAndUpdate).not.toHaveBeenCalled(); h.rows.push({ _id: "job", claimId, status: "completed", context: context(), result: { advisoryOnly: true }, }); expect((await h.service.get(claimId, actor)).enabled).toBe(false); h.service.onModuleDestroy(); }); it("deduplicates parallel identical requests and changes the snapshot for changed photos/vehicle values", async () => { const h = serviceHarness(); const before = JSON.stringify(h.f.claim); const [a, b] = await Promise.all([ h.service.request(claimId, actor, {}), h.service.request(claimId, actor, {}), ]); expect(a.estimateId).toBe(b.estimateId); expect(h.rows).toHaveLength(1); expect(JSON.stringify(a.input)).not.toContain("files/claim-captures"); expect(h.provider.estimate).not.toHaveBeenCalled(); h.images.read.mockResolvedValue({ buffer: Buffer.from("changed-photo"), sha256: "changed-hash", }); expect((await h.service.request(claimId, actor, {})).estimateId).not.toBe( a.estimateId, ); await h.service.request(claimId, actor, { currentMarketValueRial: 7000000, }); expect(h.rows).toHaveLength(3); expect(JSON.stringify(h.f.claim)).toBe(before); }); it("atomically leases a job and guards completion with its lease token", async () => { const h = serviceHarness(); await h.service.request(claimId, actor, {}); await h.service.work(); expect(h.rows[0].status).toBe("completed"); const [filter] = h.jobs.updateOne.mock.calls[0]; expect(filter).toMatchObject({ _id: h.rows[0]._id, status: "processing" }); expect(filter.leaseToken).toEqual(expect.any(String)); expect(h.provider.estimate).toHaveBeenCalledTimes(1); }); it("recovers an expired processing lease after restart", async () => { const h = serviceHarness(); await h.service.request(claimId, actor, {}); Object.assign(h.rows[0], { status: "processing", leaseUntil: new Date(0), leaseToken: "dead", attempts: 1, }); await h.service.work(); expect(h.rows[0].status).toBe("completed"); expect(h.rows[0].attempts).toBe(2); }); it("bounds automatic retries, hides upstream secrets and allows explicit failed-job retry", async () => { const h = serviceHarness(); const job = await h.service.request(claimId, actor, {}); h.provider.estimate.mockRejectedValue({ response: { status: 429, data: { secret: "PRIVATE-KEY" } }, config: { headers: { Authorization: "PRIVATE-KEY" } }, }); await h.service.work(); expect(h.rows[0].status).toBe("queued"); await h.service.work(); expect(h.rows[0].status).toBe("failed"); expect(JSON.stringify(await h.service.get(claimId, actor))).not.toContain( "PRIVATE-KEY", ); expect((await h.service.retry(claimId, job.estimateId, actor)).status).toBe( "queued", ); expect(h.rows[0].attempts).toBe(0); }); it("does not retry invalid output automatically or expose another claim's job", async () => { const h = serviceHarness(); const job = await h.service.request(claimId, actor, {}); h.provider.estimate.mockRejectedValue(new Error("INVALID_OUTPUT")); await h.service.work(); expect(h.rows[0].status).toBe("failed"); await expect( h.service.get("another-claim", actor, job.estimateId), ).rejects.toThrow("No price estimate"); await expect( h.service.retry("another-claim", job.estimateId, actor), ).rejects.toThrow("No price estimate"); }); it("retains the processing lease on shutdown and prevents stale-worker writes", async () => { const h = serviceHarness(); await h.service.request(claimId, actor, {}); h.provider.estimate.mockImplementation(async (_context, _model, signal) => { h.service.onModuleDestroy(); expect(signal.aborted).toBe(true); throw new Error("aborted"); }); await h.service.work(); expect(h.rows[0].status).toBe("processing"); expect(h.jobs.updateOne).not.toHaveBeenCalled(); }); }); describe("Swagger and local validation", () => { it("keeps the new endpoint unavailable to user/company tokens", () => { const { Reflector } = require("@nestjs/core"); const guard = new RolesGuard(new Reflector()); for (const [role, allowed] of [ [RoleEnum.USER, false], [RoleEnum.COMPANY, false], [RoleEnum.DAMAGE_EXPERT, true], [RoleEnum.FILE_REVIEWER, true], ]) { const execution = { getHandler: () => PriceEstimationController.prototype.request, getClass: () => PriceEstimationController, switchToHttp: () => ({ getRequest: () => ({ user: { role } }) }), }; expect(guard.canActivate(execution as any)).toBe(allowed); } }); it("publishes all four authenticated operations with body examples and a 202 job response", async () => { const module = await Test.createTestingModule({ controllers: [PriceEstimationController], providers: [{ provide: PriceEstimationService, useValue: {} }], }) .overrideGuard(LocalActorAuthGuard) .useValue({ canActivate: () => true }) .overrideGuard(RolesGuard) .useValue({ canActivate: () => true }) .compile(); const app = module.createNestApplication(); const document = SwaggerModule.createDocument( app, new DocumentBuilder().addBearerAuth().build(), ); const path = document.paths["/v2/price-estimation/claims/{claimRequestId}"]; expect(path.post.responses["202"]).toBeDefined(); expect(path.post.security).toEqual([{ bearer: [] }]); expect( (path.post.requestBody as any).content["application/json"].examples .automatic.value, ).toEqual({}); expect( document.paths[ "/v2/price-estimation/claims/{claimRequestId}/{estimateId}/retry" ].post, ).toBeDefined(); expect(Object.keys(document.paths)).toHaveLength(3); await app.close(); }); it("validates Swagger body amounts, types, bounds and unknown fields", async () => { const pipe = new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true, }); const metadata = { type: "body" as const, metatype: CreatePriceEstimateDto, }; await expect(pipe.transform({}, metadata)).resolves.toBeInstanceOf( CreatePriceEstimateDto, ); for (const invalid of [ { currentMarketValueRial: -1 }, { currentMarketValueRial: "10000" }, { modelYear: 900 }, { partQuality: "fake" }, { ignored: "instruction" }, ]) await expect(pipe.transform(invalid, metadata)).rejects.toThrow(); expect(new EstimateObjectIdPipe().transform(claimId)).toBe(claimId); expect(() => new EstimateObjectIdPipe().transform("$where")).toThrow(); }); it("requires the separate key only when enabled and bounds timeout", () => { const base = { NODE_ENV: "development", PORT: 9001, MONGO_URI: "mongodb://localhost/test", MONGO_TLS: "false", MONGO_TLS_ALLOW_INVALID_CERTS: "false", JWT_SECRET: "x".repeat(32), JWT_EXPIRY: "1h", }; expect(() => validate({ ...base, OPENAI_PRICE_ESTIMATION_ENABLED: "false", OPENAI_PRICE_ESTIMATION_API_KEY: "", }), ).not.toThrow(); expect(() => validate({ ...base, OPENAI_PRICE_ESTIMATION_ENABLED: "true" }), ).toThrow("API_KEY is required"); expect(() => validate({ ...base, OPENAI_PRICE_ESTIMATION_TIMEOUT_MS: 600001 }), ).toThrow(); }); });