import { tejaratNotifierLookup } from "src/fanavaran/tejarat-notifier"; import { BadRequestException, ConflictException, ForbiddenException, } from "@nestjs/common"; import { ExpertClaimService } from "./expert-claim.service"; import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service"; import { activeStageLookupRows, applyFanavaranStageFieldReview, fanavaranStageFields, } from "src/claim-request-management/fanavaran-stage-fields"; const actor = { sub: "507f1f77bcf86cd799439011", role: "damage_expert", fullName: "کارشناس", }; const id = "507f1f77bcf86cd799439012"; const vehicleBody = { vehicleGroupId: 1, vehicleUseTypeId: 1, vehicleSystemId: 14, vehicleKindId: 7456, confirmed: true as const, }; function setup(product = "third-party", extra: any = {}) { const claim = { _id: id, blameRequestId: "blame", damage: { selectedParts: [] }, ...extra, }; const management = Object.create( ClaimRequestManagementService.prototype, ) as any; management.getFanavaranLookupRows = jest .fn() .mockImplementation(async (_client, name) => { const notifier = tejaratNotifierLookup(name); if (notifier) return notifier; const ids = { cities: 702, "accident-report-type": 156, "dmg-history-status": 5215, "inspection-place": 283, "vehicle-hull-accident-types": 4, "vehicle-hull-accident-culprit-type": 301, "detection-accident-culprits": 8, }; return [ { Id: ids[name], Caption: "گزینه معتبر", IsActive: 1 }, { Id: 999, Caption: "غیرفعال", IsActive: 0 }, ]; }); management.resolveHullVehicleCurrentValueFromPolicy = jest .fn() .mockResolvedValue(1000000000); management.autoSubmitToFanavaranV2OnClaimCreated = jest .fn() .mockImplementation(async () => { expect(claim.fanavaranFieldReview).toBeDefined(); return { submitted: false }; }); management.autoSubmitFanavaranDamageCaseOnOuterPartsSelected = jest.fn(); const service = Object.create(ExpertClaimService.prototype) as any; service.getClaimDetailV2 = jest.fn().mockResolvedValue({}); service.blameRequestDbService = { findById: jest.fn().mockResolvedValue({ type: product === "car-body" ? "CAR_BODY" : "THIRD_PARTY", }), }; service.claimCaseDbService = { findById: jest.fn().mockResolvedValue(claim), findOneAndUpdate: jest .fn() .mockImplementation(async (_filter, update) => Object.assign(claim, update.$set), ), }; service.claimRequestManagementService = management; service.lookupsService = { getClientRemoteLookup: jest.fn().mockImplementation(async (name) => { const notifier = tejaratNotifierLookup(name); if (notifier) return notifier; if (name === "vehicle-groups") return [{ Id: 1, Caption: "سواری" }]; if (name === "vehicle-use-types") return [{ Id: 1, Caption: "شخصی", VehicleGroupId: 1 }]; return [{ Id: 14, Caption: "پراید", VehicleGroupId: 1 }]; }), getActiveVehicleKindById: jest.fn().mockResolvedValue({ Id: 7456, Caption: "پراید", VehicleGroupId: 1, VehicleSystemId: 14, }), }; return { service, management, claim }; } describe("Expert Fanavaran stage fields", () => { const originalClient = process.env.FANAVARAN_CLIENT; beforeEach(() => { process.env.FANAVARAN_CLIENT = "parsian"; }); afterEach(() => { if (originalClient === undefined) delete process.env.FANAVARAN_CLIENT; else process.env.FANAVARAN_CLIENT = originalClient; }); it.each([ ["third-party", "parsian"], ["car-body", "parsian"], ["third-party", "tejaratno"], ["car-body", "tejaratno"], ] as const)( "puts reviewed base fields into the actual %s/%s preview after derived/default enrichment", async (product, clientKey) => { const { management, claim } = setup(product, { fanavaranFieldReview: { values: { AccidentLocationAddress: "نشانی واقعی", AccidentCityId: 702, AccidentReportTypeId: 156, AccidentTypeId: 4, CulpritTypeId: 301, AuthorityCulpritId: 8, CustomerFaultPercent: 0, NotifierTypeId: 5517, NotifierRelationId: 5523, }, }, fanavaranVehicleReview: { vehicleUseType: { id: 1 } }, fanavaranSync: { baseClaim: { policyId: 123 } }, }); management.logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn() }; management.fanavaranAuditService = { generateTrackingCode: jest.fn().mockReturnValue("test"), }; management.claimCaseDbService = { findById: jest.fn().mockResolvedValue(claim), findByIdAndUpdate: jest.fn(), }; management.blameRequestDbService = { findById: jest.fn().mockResolvedValue({ type: product === "car-body" ? "CAR_BODY" : "THIRD_PARTY", parties: [{ role: "FIRST" }], createdAt: new Date(), }), }; management.resolveAccidentVehicleUsedFromApis = jest .fn() .mockResolvedValue({ usedId: 1 }); management.resolveFanavaranFileRoleExpertIdsForBlame = jest .fn() .mockResolvedValue(null); management.enrichCarBodyHullBaseClaimPayload = jest .fn() .mockImplementation(async ({ payload }) => { payload.CustomerFaultPercent = 100; payload.AuthorityCulpritId = 1; }); const payload = await management.previewFanavaranSubmitV2(id, clientKey, { persistPayload: false, forceRefreshPolicy: false, }); expect(payload).toMatchObject({ AccidentLocationAddress: "نشانی واقعی", AccidentCityId: 702, AccidentReportTypeId: 156, }); if (clientKey === "tejaratno") { // Hull claims use root fields; third-party claims notify through DmgNotifications. const notification = product === "car-body" ? payload : payload.DmgNotifications?.[0]; expect(notification).toMatchObject({ NotifierTypeId: 5517, NotifierRelationId: 5523, }); } else { expect(payload).not.toHaveProperty("NotifierTypeId"); expect(payload).not.toHaveProperty("NotifierRelationId"); } if (product === "car-body") { expect(payload).toMatchObject({ AccidentTypeId: 4, CulpritTypeId: 301, AuthorityCulpritId: 8, CustomerFaultPercent: 0, IsLicenseReplaced: null, }); expect(payload.DamagedCount).toBeUndefined(); expect(payload.IsLicenseReplacement).toBeUndefined(); } else if (clientKey === "tejaratno") { expect(payload).not.toHaveProperty("AuthorityCulpritId"); } else expect(payload.AuthorityCulpritId).toBeNull(); }, ); it("puts reviewed repair duration and rial value into actual hull assessment payload", async () => { const { management, claim } = setup("car-body", { vehicle: { carPrice: "3000000000" }, fanavaranFieldReview: { values: { RepairDuration: 12, VehicleCurrentValue: 12000000000 }, }, }); const result = await management.buildCarBodyFanavaranExpertisePayload({ claimCase: claim, blame: { parties: [] }, clientKey: "parsian", profile: {}, parts: [], claimExpertId: 29, submittedAt: new Date(), priceDropTotal: 0, priceDropCarPrice: "5000000000", warnings: [], }); expect(result.payload).toMatchObject({ RepairDuration: 12, VehicleCurrentValue: 12000000000, }); expect(result.payload.InspectionPlaceId).toBeUndefined(); expect(result.payload.DmgCaseId).toBeUndefined(); }); it("puts the reviewed inspection place into actual third-party assessment payload", async () => { const { management, claim } = setup("third-party", { dmgCaseId: 20, fanavaranFieldReview: { values: { InspectionPlaceId: 283 } }, }); management.blameRequestDbService = { findById: jest.fn().mockResolvedValue({ type: "THIRD_PARTY" }), }; management.resolveFanavaranFileRoleExpertIdsForBlame = jest .fn() .mockResolvedValue(null); management.resolveFanavaranClaimProduct = jest .fn() .mockResolvedValue("third-party"); const result = await management.buildFanavaranExpertisePayload({ claimCase: claim, clientKey: "parsian", }); expect(result.payload).toMatchObject({ InspectionPlaceId: 283, DmgCaseId: 20, }); }); it("puts reviewed damage history into the actual third-party damage-case payload", async () => { const { management, claim } = setup("third-party", { fanavaranFieldReview: { values: { DmgHistoryStatus: 5215 } }, fanavaranVehicleReview: { vehicleKind: { id: 7456 }, vehicleUseType: { id: 1 }, }, }); management.logger = { log: jest.fn(), warn: jest.fn() }; management.claimCaseDbService = { findByIdAndUpdate: jest.fn() }; management.pickDamagedPartyForFanavaran = jest .fn() .mockReturnValue({ person: {} }); management.resolveOwnershipPlateForClaim = jest.fn().mockReturnValue(null); management.fetchFanavaranVehicleByVinCandidates = jest .fn() .mockResolvedValue(null); management.resolveDriverFanavaranIdFromBlameCase = jest .fn() .mockResolvedValue(null); management.fanavaranLookupService = { resolveInsuranceCorpId: jest.fn().mockResolvedValue(1), }; const payload = await management.buildFanavaranDamageCasePayload({ claimCase: claim, blameCase: { type: "THIRD_PARTY" }, selectedParts: ["سپر"], clientKey: "parsian", defaults: { DmgHistoryStatus: 5214, AccidentVehicleUsedId: 1, CulpritLicenceTypeId: 2, DmgCaseTypeId: 175, FaultPercent: 100, }, }); expect(payload.DmgHistoryStatus).toBe(5215); expect(payload.LicenceCountryId).toBeNull(); }); it("uses the car-body codebooks and preserves submitted values in read-only base fields", async () => { const { service } = setup("car-body", { claimId: 10, fanavaranSync: { baseClaim: { lastPayload: { AccidentCityId: 703 } } }, }); const context = await service.getFanavaranStageFieldsV2(id, actor); expect(context.fields).toHaveLength(9); expect( context.fields.find((field) => field.key === "CulpritTypeId").lookup, ).toBe("vehicle-hull-accident-culprit-type"); expect( context.fields.find((field) => field.key === "AccidentCityId"), ).toMatchObject({ value: 703, editable: false, source: "submitted" }); expect( context.fields.find((field) => field.key === "RepairDuration").editable, ).toBe(true); expect( context.fields.find((field) => field.key === "VehicleCurrentValue"), ).toMatchObject({ value: 1000000000, unit: "ریال" }); }); it("saves fields atomically before vehicle approval releases automatic submission", async () => { const { service, management } = setup(); await service.approveFanavaranVehicleReviewV2( id, { ...vehicleBody, stageFieldsVersion: 0, stageFields: { AccidentLocationAddress: " نشانی واقعی ", AccidentCityId: 702, AccidentReportTypeId: 156, DmgHistoryStatus: 5215, InspectionPlaceId: 283, }, }, actor, ); const [, update] = service.claimCaseDbService.findOneAndUpdate.mock.calls[0]; expect(update.$set.fanavaranFieldReview.values).toMatchObject({ AccidentLocationAddress: "نشانی واقعی", InspectionPlaceId: 283, }); expect(update.$set.fanavaranFieldReview.captions.AccidentCityId).toBe( "گزینه معتبر", ); expect(update.$push.history.$each.map((event) => event.type)).toEqual([ "FANAVARAN_VEHICLE_REVIEW_APPROVED", "FANAVARAN_FIELDS_REVIEWED", ]); expect( management.autoSubmitToFanavaranV2OnClaimCreated, ).toHaveBeenCalledTimes(1); }); it.each([ ["third-party", { AccidentCityId: 999 }], ["third-party", { AccidentTypeId: 4 }], ["third-party", { AccidentLocationAddress: " " }], ["car-body", { CulpritTypeId: 337 }], ["car-body", { DmgHistoryStatus: 5215 }], ["car-body", { CustomerFaultPercent: 101 }], ["car-body", { RepairDuration: -1 }], ["car-body", { VehicleCurrentValue: null }], ["car-body", { VehicleCurrentValue: Number.MAX_SAFE_INTEGER + 1 }], ])( "rejects invalid or inapplicable values for %s", async (product, values) => { const { service } = setup(product); await expect( service.updateFanavaranStageFieldsV2( id, { values, expectedVersion: 0, confirmed: true }, actor, ), ).rejects.toBeInstanceOf(BadRequestException); expect( service.claimCaseDbService.findOneAndUpdate, ).not.toHaveBeenCalled(); }, ); it("preserves zero fault percentage and raw rial amounts", async () => { const { service, claim } = setup("car-body"); await service.updateFanavaranStageFieldsV2( id, { values: { CustomerFaultPercent: 0, VehicleCurrentValue: 12000000000, RepairDuration: 9, }, expectedVersion: 0, confirmed: true, }, actor, ); expect(claim.fanavaranFieldReview.values).toMatchObject({ CustomerFaultPercent: 0, VehicleCurrentValue: 12000000000, RepairDuration: 9, }); }); it.each([ [{ claimId: 10 }, { AccidentCityId: 702 }], [ { fanavaranSync: { baseClaim: { status: "success" } } }, { AccidentCityId: 702 }, ], [{ dmgCaseId: 20 }, { DmgHistoryStatus: 5215 }], [{ expertiseId: 30 }, { InspectionPlaceId: 283 }], ])( "rejects edits once the relevant stage has been sent", async (extra, values) => { const { service } = setup("third-party", extra); await expect( service.updateFanavaranStageFieldsV2( id, { values, expectedVersion: 0, confirmed: true }, actor, ), ).rejects.toBeInstanceOf(ConflictException); }, ); it("allows remaining-stage edits after base creation and adds version/stage guards to the database write", async () => { const { service } = setup("third-party", { claimId: 10 }); await service.updateFanavaranStageFieldsV2( id, { values: { DmgHistoryStatus: 5215, InspectionPlaceId: 283 }, expectedVersion: 0, confirmed: true, }, actor, ); const [filter] = service.claimCaseDbService.findOneAndUpdate.mock.calls[0]; expect(filter.$and).toContainEqual({ dmgCaseId: null, "fanavaranSync.damageCase.dmgCaseId": null, "fanavaranSync.damageCase.status": { $ne: "success" }, }); expect(filter.$and).toContainEqual({ expertiseId: null, "fanavaranSync.expertise.expertiseId": null, "fanavaranSync.expertise.status": { $ne: "success" }, }); }); it("rejects stale versions and a stage sent while lookups were loading", async () => { const { service } = setup("car-body", { fanavaranFieldReview: { version: 2 }, }); await expect( service.updateFanavaranStageFieldsV2( id, { values: { RepairDuration: 4 }, expectedVersion: 1, confirmed: true }, actor, ), ).rejects.toBeInstanceOf(ConflictException); service.claimCaseDbService.findOneAndUpdate.mockResolvedValue(null); await expect( service.updateFanavaranStageFieldsV2( id, { values: { RepairDuration: 4 }, expectedVersion: 2, confirmed: true }, actor, ), ).rejects.toBeInstanceOf(ConflictException); }); it("enforces existing claim access before reading or writing fields", async () => { const { service, management } = setup(); service.getClaimDetailV2.mockRejectedValue(new ForbiddenException()); await expect( service.getFanavaranStageFieldsV2(id, actor), ).rejects.toBeInstanceOf(ForbiddenException); await expect( service.updateFanavaranStageFieldsV2( id, { values: { AccidentCityId: 702 }, expectedVersion: 0, confirmed: true, }, actor, ), ).rejects.toBeInstanceOf(ForbiddenException); expect(management.getFanavaranLookupRows).not.toHaveBeenCalled(); }); it("normalizes cached lookup envelopes without admitting inactive/legacy IDs", () => { expect( activeStageLookupRows({ data: { data: [ { Id: "7", Caption: "فعال", IsActive: "1" }, { Id: 8, Caption: "غیرفعال", IsActive: "0" }, { Code: 9, Caption: "کد قدیمی" }, ], }, }), ).toEqual([{ Id: 7, Caption: "فعال" }]); }); it("keeps third-party keys out of hull stage payloads and existing nulls intact", () => { const payload = { ArchiveNo: null }; applyFanavaranStageFieldReview( payload, { fanavaranFieldReview: { values: { DmgHistoryStatus: 5215, CustomerFaultPercent: 0, InspectionPlaceId: 283, AccidentCityId: 702, }, }, }, "car-body", "baseClaim", ); expect(payload).toEqual({ ArchiveNo: null, CustomerFaultPercent: 0, AccidentCityId: 702, }); expect(fanavaranStageFields("third-party")).toHaveLength(5); }); it.each(["third-party", "car-body"])( "shows only the supplied TejaratNo notifier options for %s", async (product) => { process.env.FANAVARAN_CLIENT = "TejaratNo"; const { service } = setup(product); const context = await service.getFanavaranStageFieldsV2(id, actor); expect(context.clientKey).toBe("tejaratno"); const fields = context.fields.filter((field) => field.key.startsWith("Notifier"), ); expect(fields.map((field) => field.key)).toEqual([ "NotifierTypeId", "NotifierRelationId", ]); expect( fields.every( (field) => field.value === null && field.editable && field.requiredBeforeSubmit, ), ).toBe(true); expect(fields[0].options.map((row) => row.Id).sort()).toEqual([ 5516, 5517, ]); expect(fields[1].options.map((row) => row.Id).sort()).toEqual([ 5519, 5520, 5521, 5522, 5523, 5524, 5525, 5526, ]); }, ); it.each(["parsian", "moallem"])( "hides and rejects notifier edits for %s", async (tenant) => { process.env.FANAVARAN_CLIENT = tenant; const { service } = setup(); const context = await service.getFanavaranStageFieldsV2(id, actor); expect( context.fields.some((field) => field.key.startsWith("Notifier")), ).toBe(false); await expect( service.updateFanavaranStageFieldsV2( id, { values: { NotifierTypeId: 5516 }, expectedVersion: 0, confirmed: true, }, actor, ), ).rejects.toBeInstanceOf(BadRequestException); expect( service.claimCaseDbService.findOneAndUpdate, ).not.toHaveBeenCalled(); }, ); it.each([ { NotifierTypeId: 5518 }, { NotifierTypeId: 5519 }, { NotifierRelationId: 5516 }, { NotifierRelationId: 5527 }, { NotifierTypeId: "5516" }, { NotifierRelationId: null }, ])("rejects excluded or invalid notifier values: %j", async (values) => { process.env.FANAVARAN_CLIENT = "tejaratno"; const { service } = setup(); await expect( service.updateFanavaranStageFieldsV2( id, { values, expectedVersion: 0, confirmed: true }, actor, ), ).rejects.toBeInstanceOf(BadRequestException); expect(service.claimCaseDbService.findOneAndUpdate).not.toHaveBeenCalled(); }); it("persists notifier IDs, captions and audit history with the existing version guard", async () => { process.env.FANAVARAN_CLIENT = "tejaratno"; const { service, claim } = setup(); await service.updateFanavaranStageFieldsV2( id, { values: { NotifierTypeId: 5516, NotifierRelationId: 5521 }, expectedVersion: 0, confirmed: true, }, actor, ); expect(claim.fanavaranFieldReview).toMatchObject({ values: { NotifierTypeId: 5516, NotifierRelationId: 5521 }, captions: { NotifierTypeId: "آسيب ديده", NotifierRelationId: "مالک" }, version: 1, }); const [filter, update] = service.claimCaseDbService.findOneAndUpdate.mock.calls[0]; expect(filter.$and).toContainEqual({ claimId: null, "fanavaranSync.baseClaim.claimId": null, "fanavaranSync.baseClaim.status": { $ne: "success" }, }); expect(update.$push.history.metadata.after).toMatchObject({ NotifierTypeId: 5516, NotifierRelationId: 5521, }); }); it("saves both notifier choices atomically before combined approval starts submission", async () => { process.env.FANAVARAN_CLIENT = "tejaratno"; const { service, claim, management } = setup(); await service.approveFanavaranVehicleReviewV2( id, { ...vehicleBody, stageFieldsVersion: 0, stageFields: { NotifierTypeId: 5517, NotifierRelationId: 5526 }, }, actor, ); expect(claim.fanavaranFieldReview.values).toMatchObject({ NotifierTypeId: 5517, NotifierRelationId: 5526, }); expect( management.autoSubmitToFanavaranV2OnClaimCreated, ).toHaveBeenCalledTimes(1); }); it.each([undefined, { NotifierTypeId: 5516 }, { NotifierRelationId: 5523 }])( "does not approve a TejaratNo vehicle with incomplete notifier selection: %j", async (stageFields) => { process.env.FANAVARAN_CLIENT = "tejaratno"; const { service, management } = setup(); await expect( service.approveFanavaranVehicleReviewV2( id, { ...vehicleBody, stageFieldsVersion: 0, stageFields }, actor, ), ).rejects.toBeInstanceOf(BadRequestException); expect( service.claimCaseDbService.findOneAndUpdate, ).not.toHaveBeenCalled(); expect( management.autoSubmitToFanavaranV2OnClaimCreated, ).not.toHaveBeenCalled(); }, ); it("locks notifier fields after initial submission and shows the submitted selection", async () => { process.env.FANAVARAN_CLIENT = "tejaratno"; const { service } = setup("third-party", { claimId: 10, fanavaranSync: { baseClaim: { lastPayload: { NotifierTypeId: 5517, NotifierRelationId: 5523 }, }, }, }); const context = await service.getFanavaranStageFieldsV2(id, actor); expect( context.fields.find((field) => field.key === "NotifierTypeId"), ).toMatchObject({ editable: false, value: 5517, source: "submitted", caption: "مقصر حادثه", }); await expect( service.updateFanavaranStageFieldsV2( id, { values: { NotifierTypeId: 5516 }, expectedVersion: 0, confirmed: true, }, actor, ), ).rejects.toBeInstanceOf(ConflictException); }); it("blocks manual initial submission without notifier review before remote work", async () => { const { management, claim } = setup("third-party", { fanavaranVehicleReview: { approved: true, vehicleGroup: { id: 1 }, vehicleUseType: { id: 1 }, vehicleSystem: { id: 14 }, vehicleKind: { id: 7456 }, }, }); management.logger = { log: jest.fn() }; management.claimCaseDbService = { findById: jest.fn().mockResolvedValue(claim), }; management.previewFanavaranSubmitV2 = jest.fn(); await expect( management.executeFanavaranV2Submit(id, "tejaratno"), ).rejects.toMatchObject({ response: { code: "FANAVARAN_NOTIFIER_REVIEW_REQUIRED" }, }); expect(management.previewFanavaranSubmitV2).not.toHaveBeenCalled(); }); it("soft-skips automatic TejaratNo submission until both choices are saved", async () => { process.env.FANAVARAN_CLIENT = "tejaratno"; const { management, claim } = setup("third-party", { fanavaranVehicleReview: { approved: true }, }); management.blameRequestDbService = { findById: jest.fn().mockResolvedValue({ type: "THIRD_PARTY" }), }; expect(await management.getFanavaranAutoSubmitSkipReason(claim)).toContain( "اعلام‌کننده", ); claim.fanavaranFieldReview = { values: { NotifierTypeId: 5516, NotifierRelationId: 5519 }, }; expect(await management.getFanavaranAutoSubmitSkipReason(claim)).toBeNull(); delete claim.fanavaranFieldReview; claim.claimId = 10; expect(await management.getFanavaranAutoSubmitSkipReason(claim)).toBe( "Already submitted to Fanavaran", ); }); it("reuses notifier selections from a submitted base payload and preserves legacy records without them", () => { const payload = {}; applyFanavaranStageFieldReview( payload, { claimId: 10, fanavaranSync: { baseClaim: { lastPayload: { NotifierTypeId: 5517, NotifierRelationId: 5523 }, }, }, }, "car-body", "baseClaim", "tejaratno", ); expect(payload).toEqual({ NotifierTypeId: 5517, NotifierRelationId: 5523 }); const legacy = {}; applyFanavaranStageFieldReview( legacy, { claimId: 10 }, "car-body", "baseClaim", "tejaratno", ); expect(legacy).toEqual({}); }); });