From 1a38b98829db20497a57f8fb8da2640443865a9f Mon Sep 17 00:00:00 2001 From: SepehrYahyaee <7heycallmegray@gmail.com> Date: Sat, 21 Nov 2026 15:27:06 +0330 Subject: [PATCH] fix(inquiries): route all tenants through ESG and Fanavaran --- .env.example | 14 +- README.md | 1 + docs/external-api-curls.md | 138 +-- docs/inquiry-provider-routing.md | 84 ++ .../case-expert-report.builder.spec.ts | 4 +- src/core/config/fanavaran-client.config.ts | 3 + .../car-body-accident-coverage.spec.ts | 2 +- .../inquiry-refresh.service.ts | 2 +- ...st-management.policyholder-inquiry.spec.ts | 12 +- .../request-management.service.ts | 8 +- ...fanavaran-car-body-inquiry.mapper.spec.ts} | 32 +- ...s => fanavaran-car-body-inquiry.mapper.ts} | 11 +- src/sand-hub/sand-hub.esg-routing.spec.ts | 316 +++++++ src/sand-hub/sand-hub.service.spec.ts | 77 +- src/sand-hub/sand-hub.service.ts | 831 ++++-------------- 15 files changed, 675 insertions(+), 860 deletions(-) create mode 100644 docs/inquiry-provider-routing.md rename src/sand-hub/{esg-car-body-inquiry.mapper.spec.ts => fanavaran-car-body-inquiry.mapper.spec.ts} (61%) rename src/sand-hub/{esg-car-body-inquiry.mapper.ts => fanavaran-car-body-inquiry.mapper.ts} (88%) create mode 100644 src/sand-hub/sand-hub.esg-routing.spec.ts diff --git a/.env.example b/.env.example index 91243aa..94ecd08 100644 --- a/.env.example +++ b/.env.example @@ -46,7 +46,16 @@ JWT_EXPIRY = CAPTCHA_ENABLED = true # --------------------------------------------- -# 🧩 SanHub Microservice +# 🧩 ESG — third-party plate/VIN, personal identity and Sheba (all tenants) +# Include the gateway prefix in ESG_URL when one is required; no fallback URL. +# --------------------------------------------- +ESG_URL = +ESG_USERNAME = +ESG_PASSWORD = + +# --------------------------------------------- +# Optional driving-licence and legal vehicle-ownership inquiries only +# ESG does not currently expose equivalent endpoints for these two checks. # --------------------------------------------- SANHUB_BASE_URL = SANHUB_URL_LOGIN = @@ -101,9 +110,6 @@ AUTO_CLIENT_KEY_ENABLED = # --------------------------------------------- # 🔗 Other Internal Services # --------------------------------------------- -TEJARAT_INQUIRY_EMAIL = -TEJARAT_INQUIRY_PASSWORD = - PARSIAN_API_KEY = PARSIAN_BASIC_TOKEN = PARSIAN_SMS_URL = diff --git a/README.md b/README.md index cc92271..4e0e8f0 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,7 @@ ## Documentation - [Fanavaran integration](docs/fanavaran/README.md) +- [Inquiry providers — ESG for all tenants and Fanavaran car-body policies](docs/inquiry-provider-routing.md) - [AI damage detection and advisory prices — setup and testing](docs/ai-damage-companion.md) Insurer setup and staff/branch management: [guide](docs/insurer-staff-management.md). diff --git a/docs/external-api-curls.md b/docs/external-api-curls.md index 6c79924..15e181f 100644 --- a/docs/external-api-curls.md +++ b/docs/external-api-curls.md @@ -319,81 +319,21 @@ curl -X POST "$FANAVARAN_BIME_URL/car/third-party-car-financial-claims" \ --data @fanavaran-claim-submit.json ``` -## Tejarat Inquiry Provider - -Default base URL: - -```sh -TEJARAT_INQUIRY_BASE_URL="${TEJARAT_INQUIRY_BASE_URL:-http://82.99.202.245:3027}" -TEJARAT_INQUIRY_EMAIL='xxx@example.com' -TEJARAT_INQUIRY_PASSWORD='123321' -``` - -Used by `src/sand-hub/sand-hub.service.ts` for third-party plate and car-body plate inquiries when ESG is not selected. - -### Sequence - -1. Login to `/user/login`. -2. Use returned `accessToken` as `Authorization: Bearer ...`. -3. Call inquiry endpoint. - -### Login - -```sh -curl -X POST "$TEJARAT_INQUIRY_BASE_URL/user/login" \ - -H "Accept: */*" \ - -H "Content-Type: application/json" \ - --data '{ - "email": "'"$TEJARAT_INQUIRY_EMAIL"'", - "password": "'"$TEJARAT_INQUIRY_PASSWORD"'" - }' -``` - -```sh -TEJARAT_ACCESS_TOKEN="" -``` - -### Third-Party Plate / Policy Block Inquiry - -```sh -curl -X POST "$TEJARAT_INQUIRY_BASE_URL/block-inquiry-tejarat" \ - -H "Authorization: Bearer $TEJARAT_ACCESS_TOKEN" \ - -H "Content-Type: application/json" \ - -H "Accept: application/json" \ - --data '{ - "leftTwoDigits": "12", - "serialLetter": "ب", - "threeDigits": "345", - "rightTwoDigits": "67", - "nationalCode": "0012345678" - }' -``` - -### Car-Body Plate Inquiry - -```sh -curl -X POST "$TEJARAT_INQUIRY_BASE_URL/block-inquiry-tejarat/badane" \ - -H "Authorization: Bearer $TEJARAT_ACCESS_TOKEN" \ - -H "Content-Type: application/json" \ - -H "Accept: application/json" \ - --data '{ - "part1": 12, - "part2": "ب", - "part3": 345, - "part4": 67, - "nationalCode": "0012345678" - }' -``` - ## ESG Inquiry Provider -Default/fallback base URL in some call sites: +Used by `src/sand-hub/sand-hub.service.ts` for third-party plate/VIN, identity +and Sheba inquiries in **every tenant**, including Moalem (`CLIENT_ID=7`). ```sh -ESG_URL="${ESG_URL:-http://192.168.20.22:8085}" +ESG_URL="https:///" +ESG_USERNAME="" +ESG_PASSWORD="" ``` -Used by `src/sand-hub/sand-hub.service.ts` for selected tenants, for example when `CLIENT_ID=8`. +There is no fallback URL or fallback to the deprecated Tejarat provider. +Car-body plate and VIN inquiries use the tenant’s Fanavaran profile through +`LookupsService.findLastProcessedCarPolicy("car-body", query)`, not ESG. +See [inquiry provider routing](inquiry-provider-routing.md) for deployment notes. ### Sequence @@ -417,7 +357,7 @@ curl -X POST "$ESG_URL/auth/login" \ ESG_ACCESS_TOKEN="" ``` -### Car By Plate (canonical Parsian third-party plate inquiry) +### Car By Plate (third-party inquiry for all tenants) ```sh curl -X POST "$ESG_URL/inquiry/carByPlate" \ @@ -483,15 +423,18 @@ curl -X POST "$ESG_URL/inquiry/sheba" \ ## SandHub Provider -Used by `src/sand-hub/sand-hub.service.ts` for legacy inquiry flows. +Used only for the optional driving-licence and legal vehicle-ownership checks. +The current ESG API has no equivalent contract for these checks. Plate/VIN, +personal identity and Sheba inquiries do not use this adapter. Configure these +settings only when the optional checks are enabled. Environment: ```sh -SANHUB_BASE_URL='http://82.99.202.245:3027' -SANHUB_URL_LOGIN='http://82.99.202.245:3027/user/login' -SANHUB_USERNAME='default@admin.com' -SANHUB_PASSWORD='123321' +SANHUB_BASE_URL='https://' +SANHUB_URL_LOGIN='https:///' +SANHUB_USERNAME='' +SANHUB_PASSWORD='' ``` ### Sequence @@ -515,37 +458,6 @@ curl -X POST "$SANHUB_URL_LOGIN" \ SANHUB_ACCESS_TOKEN="" ``` -### Third-Party Plate / Policy Block Inquiry - -```sh -curl -X POST "$SANHUB_BASE_URL/block-inquiry-tejarat" \ - -H "Authorization: Bearer $SANHUB_ACCESS_TOKEN" \ - -H "Content-Type: application/json" \ - -H "Accept: application/json" \ - --data '{ - "leftTwoDigits": "12", - "serialLetter": "ب", - "threeDigits": "345", - "rightTwoDigits": "67", - "nationalCode": "0012345678" - }' -``` - -### Personal Inquiry - -The app converts Jalali birth dates to Gregorian before sending to SandHub. - -```sh -curl -X POST "$SANHUB_BASE_URL/personal-inquiry/tejarat-no" \ - -H "Authorization: Bearer $SANHUB_ACCESS_TOKEN" \ - -H "Content-Type: application/json" \ - -H "Accept: application/json" \ - --data '{ - "nationalCode": "0012345678", - "birthdate": "1999-02-13" - }' -``` - ### Driving License Check ```sh @@ -575,20 +487,6 @@ curl -X POST "$SANHUB_BASE_URL/ownership" \ }' ``` -### Sheba Validation - -```sh -curl -X POST "$SANHUB_BASE_URL/sheba/sheba-tejaratno" \ - -H "Authorization: Bearer $SANHUB_ACCESS_TOKEN" \ - -H "Content-Type: application/json" \ - -H "Accept: application/json" \ - --data '{ - "AccountOwnerType": "1", - "NationalId": "0012345678", - "ShebaId": "IR000000000000000000000000" - }' -``` - ## Map.ir Reverse Geocoding Used by `src/claim-request-management/claim-request-management.service.ts`. diff --git a/docs/inquiry-provider-routing.md b/docs/inquiry-provider-routing.md new file mode 100644 index 0000000..943a544 --- /dev/null +++ b/docs/inquiry-provider-routing.md @@ -0,0 +1,84 @@ +# Inquiry provider routing + +The running NestJS API routes inquiries through `src/sand-hub/sand-hub.service.ts`. +The class name remains for existing dependency injection; it does not select the +provider by tenant anymore. + +| Inquiry | Provider | Entry point | +| --- | --- | --- | +| Third-party policy by plate | ESG `/inquiry/carByPlate` | `getCarByPlateInquiry` | +| Third-party policy by national code + VIN | ESG `/inquiry/carByChassis` | `getCarByChassisInquiry` | +| Person identity | ESG `/inquiry/person` | `getPersonalInquiry` | +| Sheba ownership | ESG `/inquiry/sheba` | `getShebaValidation` | +| Car-body policy by plate or VIN | Tenant-specific Fanavaran processed policy lookup | `getCarBodyInquiry` | +| Optional driving-licence / legal vehicle ownership | Existing configured `SANHUB_*` adapter | `getDrivingLicenseInfo` / `getCarOwnershipInfo` | + +The ESG endpoints above apply to every tenant. Existing per-client live/mock +settings still apply. Disabled inquiries retain their mock behavior; offline +third-party plate records are consulted only in disabled mode. No mock or +deprecated provider is used as a fallback when a live ESG inquiry fails. + +## Why Moalem reached the retired login + +Previously only `CLIENT_ID=8` selected ESG. `CLIENT_ID=7` therefore selected the +old Tejarat transport for third-party plate inquiries, and the old configurable +hub for identity and Sheba. Car-body plate inquiries also used the Tejarat +transport unless the Fanavaran profile was Parsian. Car-body VIN inquiries +already used Fanavaran. + +The retired `getTejaratAccessToken`, `/user/login` transport and +`TEJARAT_INQUIRY_*` configuration have been removed from the running API. +Both car-body input formats now use the existing Fanavaran lookup. The mapper +uses the selected source insurer rather than assuming every car-body result +belongs to Parsian. Explicit conflicting insurer codes are rejected. + +## Deployment settings + +Supply these through the API environment, then restart the API: + +```dotenv +CLIENT_ID=7 +FANAVARAN_CLIENT=moallem +ESG_URL=https:/// +ESG_USERNAME= +ESG_PASSWORD= +``` + +`moallem` is the existing Fanavaran profile spelling. The explicit +`FANAVARAN_CLIENT` setting takes precedence; when absent, `CLIENT_ID=7` now +resolves to `moallem`, and `CLIENT_ID=8` still resolves to `parsian`. Other +deployments must select their own Fanavaran profile as before. The selected +profile must have its existing Fanavaran credentials/contracts configured. + +`ESG_URL` is the base **before** `/auth/login` and `/inquiry/...`; include any +gateway prefix in that value. Trailing slashes are normalized. No internal-IP +default is used. The ESG user needs access to all four inquiry types. Birth +dates are sent in Jalali `YYYY-MM-DD`, with `dateHasPostfix: 0`. The cached ESG +token is reused, and an inquiry HTTP 401 clears it before the existing retry. + +`TEJARAT_INQUIRY_BASE_URL`, `TEJARAT_INQUIRY_EMAIL` and +`TEJARAT_INQUIRY_PASSWORD` are no longer read by the running API and can be +removed from deployment configuration. Do not repoint `SANHUB_*` to ESG: their +optional licence/ownership payloads differ, and the ESG repository currently +has no matching endpoints. Those two checks keep their existing settings +until an explicit replacement contract is provided. + +## Compatibility and verification + +The mapped inquiry fields consumed by the UI remain unchanged. The old +`getSandHubResponse` entry point delegates to ESG and returns the mapped result. +New car-body audit records identify their source as +`FANAVARAN_CAR_BODY_INQUIRY` or `FANAVARAN_CAR_BODY_VIN_INQUIRY`. Historical raw +inquiries, audit records and database documents are not rewritten. + +`scripts/refresh-blame-inquiries.js` and `scripts/fanavaran-flow-ui-server.js` +are separate manually run diagnostic tools with their own legacy provider +settings. They are not invoked by the running application and have not been +migrated by this change; do not use their inquiry shortcuts as evidence of the +application's current routing. + +Regression tests in `sand-hub.esg-routing.spec.ts` cover tenant IDs 7, 8 and 15, +ESG token reuse/401 refresh, missing configuration, disabled inquiries, +Fanavaran plate/VIN routing, source-company checks and optional-check +compatibility. Provider HTTP calls in these tests are mocked; deployment still +requires valid gateway credentials and connectivity. diff --git a/src/case-expert-report/case-expert-report.builder.spec.ts b/src/case-expert-report/case-expert-report.builder.spec.ts index 4e21fde..b908409 100644 --- a/src/case-expert-report/case-expert-report.builder.spec.ts +++ b/src/case-expert-report/case-expert-report.builder.spec.ts @@ -392,7 +392,7 @@ describe("buildInsurerFileReport", () => { vehicle: { isNew: true, hasEndorsement: false, - source: "ESG_CAR_BODY_INQUIRY", + source: "FANAVARAN_CAR_BODY_INQUIRY", inquiry: { source: "TEJARAT_BLOCK_INQUIRY" }, }, }, @@ -419,7 +419,7 @@ describe("buildInsurerFileReport", () => { role: "FIRST", person: { userId: "damaged", fullName: "بیمه‌گذار" }, vehicle: { - source: "ESG_CAR_BODY_INQUIRY", + source: "FANAVARAN_CAR_BODY_INQUIRY", inquiry: { source: "TEJARAT_BLOCK_INQUIRY" }, }, }, diff --git a/src/core/config/fanavaran-client.config.ts b/src/core/config/fanavaran-client.config.ts index f86fc6d..7f7243e 100644 --- a/src/core/config/fanavaran-client.config.ts +++ b/src/core/config/fanavaran-client.config.ts @@ -218,6 +218,9 @@ export function resolveFanavaranClientKey(): FanavaranClientKey { } // Optional deployment hint when FANAVARAN_CLIENT is not set. + if (String(process.env.CLIENT_ID ?? '').trim() === '7') { + return 'moallem'; + } if (String(process.env.CLIENT_ID ?? '') === '8') { return 'parsian'; } diff --git a/src/request-management/car-body-accident-coverage.spec.ts b/src/request-management/car-body-accident-coverage.spec.ts index ebabc09..326e097 100644 --- a/src/request-management/car-body-accident-coverage.spec.ts +++ b/src/request-management/car-body-accident-coverage.spec.ts @@ -33,7 +33,7 @@ describe("car-body coverage when the accident date is collected after inquiry", it("reselects and stores the earlier renewal for the supplied accident date", async () => { const { service, party, inquiry } = setup("1401/01/02", "1402/01/02"); inquiry.mockResolvedValue({ - source: "ESG_CAR_BODY_INQUIRY", + source: "FANAVARAN_CAR_BODY_INQUIRY", mapped: { policyId: 1, StartDate: "1400/01/01", diff --git a/src/request-management/inquiry-refresh.service.ts b/src/request-management/inquiry-refresh.service.ts index 5513466..43fb4ca 100644 --- a/src/request-management/inquiry-refresh.service.ts +++ b/src/request-management/inquiry-refresh.service.ts @@ -236,7 +236,7 @@ export class InquiryRefreshService { } else { await this.waitForRateLimit(); try { - const inquiry = await this.sandHubService.getTejaratBlockInquiry( + const inquiry = await this.sandHubService.getCarByPlateInquiry( { plate: { ...plate, diff --git a/src/request-management/request-management.policyholder-inquiry.spec.ts b/src/request-management/request-management.policyholder-inquiry.spec.ts index dc9266f..dd2aaee 100644 --- a/src/request-management/request-management.policyholder-inquiry.spec.ts +++ b/src/request-management/request-management.policyholder-inquiry.spec.ts @@ -50,7 +50,7 @@ describe("RequestManagementService policyholder inquiry routing", () => { it("does not fall back from the current plate for third-party insurance", async () => { const service = Object.create(RequestManagementService.prototype) as any; service.sandHubService = { - getTejaratBlockInquiry: jest + getCarByPlateInquiry: jest .fn() .mockResolvedValueOnce({ raw: {}, mapped: {} }) .mockResolvedValueOnce({ @@ -67,10 +67,10 @@ describe("RequestManagementService policyholder inquiry routing", () => { "بیمه‌نامه معتبر و فعالی مطابق مشخصات خودرو و کد ملی واردشده یافت نشد.", ); - expect(service.sandHubService.getTejaratBlockInquiry).toHaveBeenCalledTimes( + expect(service.sandHubService.getCarByPlateInquiry).toHaveBeenCalledTimes( 1, ); - expect(service.sandHubService.getTejaratBlockInquiry).toHaveBeenCalledWith( + expect(service.sandHubService.getCarByPlateInquiry).toHaveBeenCalledWith( expect.objectContaining({ plate: currentPlate, nationalCodeOfInsurer: "0022222222", @@ -82,7 +82,7 @@ describe("RequestManagementService policyholder inquiry routing", () => { it("contextualizes the mapped ESG not-found error for third-party insurance", async () => { const service = Object.create(RequestManagementService.prototype) as any; service.sandHubService = { - getTejaratBlockInquiry: jest.fn().mockResolvedValue({ + getCarByPlateInquiry: jest.fn().mockResolvedValue({ raw: { success: false, error: { @@ -102,7 +102,7 @@ describe("RequestManagementService policyholder inquiry routing", () => { await expect(service.getThirdPartyPlateInquiry(submission)).rejects.toThrow( "بیمه‌نامه شخص ثالثی مطابق پلاک و کد ملی واردشده یافت نشد.", ); - expect(service.sandHubService.getTejaratBlockInquiry).toHaveBeenCalledTimes( + expect(service.sandHubService.getCarByPlateInquiry).toHaveBeenCalledTimes( 1, ); }); @@ -177,7 +177,7 @@ describe("RequestManagementService policyholder inquiry routing", () => { }); service.sandHubService = { getCarBodyInquiry: jest.fn().mockResolvedValue({ - source: "ESG_CAR_BODY_VIN_INQUIRY", + source: "FANAVARAN_CAR_BODY_VIN_INQUIRY", raw: { policyId: 123 }, mapped: { policyNumber: "BODY-1", diff --git a/src/request-management/request-management.service.ts b/src/request-management/request-management.service.ts index ed4797e..2f23fe2 100644 --- a/src/request-management/request-management.service.ts +++ b/src/request-management/request-management.service.ts @@ -428,7 +428,7 @@ export class RequestManagementService { currentPlate: submission.vehicle?.currentPlate ?? submission.dto.plate, vin: submission.vehicle?.vin, query: (plate) => - this.sandHubService.getTejaratBlockInquiry( + this.sandHubService.getCarByPlateInquiry( { plate: plate as any, nationalCodeOfInsurer: subjects.thirdPartyPolicyNationalCode, @@ -2302,7 +2302,7 @@ export class RequestManagementService { * 2. Personal identity inquiry (same as the plate path) * * The inquiry result is mapped through the same `mapEsgPolicyByPlateToOldFormat` - * normaliser used by `getTejaratBlockInquiry`, so all downstream party/vehicle + * normaliser used by `getCarByPlateInquiry`, so all downstream party/vehicle * /insurance field assignments are identical. */ async initialFormVinV2( @@ -7608,7 +7608,7 @@ export class RequestManagementService { /** * VIN variant of `runInquiriesV3`. * Identical flow, but calls the two-factor `getCarByChassisInquiry` instead of - * `getTejaratBlockInquiry` for the primary policy lookup. + * `getCarByPlateInquiry` for the primary policy lookup. */ async runInquiriesVinV3( requestId: string, @@ -7751,7 +7751,7 @@ export class RequestManagementService { /** * VIN variant of `runPartyInquiriesV3Internal`. * Calls `getCarByChassisInquiry` (ESG two-factor chassis lookup) instead of - * `getTejaratBlockInquiry` (plate-based). All other inquiries (personal, + * `getCarByPlateInquiry` (plate-based). All other inquiries (personal, * driving licence, car-body for CAR_BODY) are unchanged. */ private async runPartyInquiriesVinV3Internal( diff --git a/src/sand-hub/esg-car-body-inquiry.mapper.spec.ts b/src/sand-hub/fanavaran-car-body-inquiry.mapper.spec.ts similarity index 61% rename from src/sand-hub/esg-car-body-inquiry.mapper.spec.ts rename to src/sand-hub/fanavaran-car-body-inquiry.mapper.spec.ts index c9cce31..6df4ccf 100644 --- a/src/sand-hub/esg-car-body-inquiry.mapper.spec.ts +++ b/src/sand-hub/fanavaran-car-body-inquiry.mapper.spec.ts @@ -1,8 +1,34 @@ -import { mapEsgCarBodyPolicyToInquiry } from "./esg-car-body-inquiry.mapper"; +import { mapFanavaranCarBodyPolicyToInquiry } from "./fanavaran-car-body-inquiry.mapper"; + +describe("mapFanavaranCarBodyPolicyToInquiry", () => { + it("does not assume an insurer when neither the response nor the source identifies one", () => { + expect(mapFanavaranCarBodyPolicyToInquiry({})).toMatchObject({ + companyId: null, + CompanyCode: null, + CompanyName: null, + }); + }); + + it("uses the configured source without overwriting an explicit returned insurer", () => { + const source = { companyId: "7", companyName: "بیمه معلم" }; + expect(mapFanavaranCarBodyPolicyToInquiry({}, source)).toMatchObject({ + companyId: "7", + CompanyCode: "7", + CompanyName: "بیمه معلم", + }); + expect( + mapFanavaranCarBodyPolicyToInquiry( + { policy: { CompanyId: "8", CompanyName: "بیمه پارسیان" } }, + source, + ), + ).toMatchObject({ + CompanyCode: "8", + CompanyName: "بیمه پارسیان", + }); + }); -describe("mapEsgCarBodyPolicyToInquiry", () => { it("maps the processed CAR_BODY lookup while retaining useful policy, customer, and vehicle fields", () => { - const mapped = mapEsgCarBodyPolicyToInquiry({ + const mapped = mapFanavaranCarBodyPolicyToInquiry({ product: "car-body", insuranceLine: "CAR_BODY", insuranceLineId: 4, diff --git a/src/sand-hub/esg-car-body-inquiry.mapper.ts b/src/sand-hub/fanavaran-car-body-inquiry.mapper.ts similarity index 88% rename from src/sand-hub/esg-car-body-inquiry.mapper.ts rename to src/sand-hub/fanavaran-car-body-inquiry.mapper.ts index 1cdd263..dbde225 100644 --- a/src/sand-hub/esg-car-body-inquiry.mapper.ts +++ b/src/sand-hub/fanavaran-car-body-inquiry.mapper.ts @@ -1,11 +1,12 @@ /** - * Converts the processed CAR_BODY policy returned by the ESG/Fanavaran lookup + * Converts the processed CAR_BODY policy returned by the Fanavaran lookup * into the same mapped contract used by the existing car-body inquiry flow. * The original response is deliberately kept separately as `raw` by the * caller, so newly exposed provider fields are never discarded. */ -export function mapEsgCarBodyPolicyToInquiry( +export function mapFanavaranCarBodyPolicyToInquiry( response: Record, + sourceCompany?: { companyId: string; companyName: string }, ): Record { const policy = response.policy ?? {}; const customer = response.customer ?? {}; @@ -27,9 +28,9 @@ export function mapEsgCarBodyPolicyToInquiry( insuranceLineId: response.insuranceLineId ?? 4, // Provider responses do not currently include an insurer company identity. - companyId: policy.CompanyId ?? null, - CompanyCode: policy.CompanyId ?? "8", - CompanyName: policy.CompanyName ?? "بیمه پارسیان", + companyId: policy.CompanyId ?? sourceCompany?.companyId ?? null, + CompanyCode: policy.CompanyId ?? sourceCompany?.companyId ?? null, + CompanyName: policy.CompanyName ?? sourceCompany?.companyName ?? null, // The lookup's customer is the policyholder/owner, not the insurer. insurerName: null, diff --git a/src/sand-hub/sand-hub.esg-routing.spec.ts b/src/sand-hub/sand-hub.esg-routing.spec.ts new file mode 100644 index 0000000..f19206e --- /dev/null +++ b/src/sand-hub/sand-hub.esg-routing.spec.ts @@ -0,0 +1,316 @@ +import { + ForbiddenException, + ServiceUnavailableException, + UnauthorizedException, +} from "@nestjs/common"; +import { of, throwError } from "rxjs"; +import { resolveFanavaranClientKey } from "src/core/config/fanavaran-client.config"; +import { SandHubService } from "./sand-hub.service"; + +const keys = [ + "CLIENT_ID", + "FANAVARAN_CLIENT", + "ESG_URL", + "ESG_USERNAME", + "ESG_PASSWORD", + "TEJARAT_INQUIRY_BASE_URL", + "TEJARAT_INQUIRY_EMAIL", + "TEJARAT_INQUIRY_PASSWORD", + "SANHUB_URL_LOGIN", +]; +const before = Object.fromEntries(keys.map((key) => [key, process.env[key]])); +const detail: any = { + nationalCodeOfInsurer: "0012345678", + plate: { + leftDigits: "12", + centerAlphabet: "ب", + centerDigits: "345", + ir: "67", + }, +}; +function fixture(code = "7") { + process.env.CLIENT_ID = code; + process.env.ESG_URL = "http://esg.example.test/api/"; + process.env.ESG_USERNAME = "fixture-user"; + process.env.ESG_PASSWORD = "fixture-password"; + process.env.TEJARAT_INQUIRY_BASE_URL = "http://retired.example.test"; + process.env.TEJARAT_INQUIRY_EMAIL = "retired-fixture"; + process.env.TEJARAT_INQUIRY_PASSWORD = "retired-fixture"; + process.env.SANHUB_URL_LOGIN = "http://retired.example.test/user/login"; + delete process.env.FANAVARAN_CLIENT; + const http = { + post: jest.fn((url: string) => { + if (url.endsWith("/auth/login")) + return of({ data: { accessToken: "fixture-token", expiresIn: 900 } }); + if (url.endsWith("/inquiry/person")) + return of({ + data: { + success: true, + data: { Name: "نمونه", Family: "آزمایشی", Nin: "0012345678" }, + }, + }); + if (url.endsWith("/inquiry/sheba")) + return of({ + data: { success: true, data: { ReturnValue: true, HasError: false } }, + }); + if (/\/inquiry\/carBy(Plate|Chassis)$/.test(url)) + return of({ + data: { + success: true, + data: { + CmpCod: code, + CmpNam: "بیمه نمونه", + PrntCmpDocNo: "POLICY-TEST", + VIN: "NAAR03HFFRDE07024", + }, + }, + }); + throw new Error("Unexpected inquiry provider URL"); + }), + }; + const settings = { + isInquiryLive: jest.fn().mockResolvedValue(true), + getMockCompanyContext: jest + .fn() + .mockResolvedValue({ companyId: code, companyName: "بیمه نمونه" }), + }; + const lookups = { + findLastProcessedCarPolicy: jest.fn().mockResolvedValue({ + policy: { CINumber: "BODY-POLICY" }, + vehicle: { VIN: "NAAR03HFFRDE07024" }, + customer: {}, + }), + }; + const offline = { findPlateInquiry: jest.fn().mockResolvedValue(null) }; + const service = new SandHubService( + http as any, + settings as any, + { normalizePlateText: (text: string) => text } as any, + offline as any, + lookups as any, + ); + return { service, http, settings, lookups, offline }; +} +afterEach(() => { + for (const key of keys) { + if (before[key] === undefined) delete process.env[key]; + else process.env[key] = before[key]; + } +}); + +describe("tenant-independent ESG routing and Fanavaran car-body policies", () => { + it.each(["7", "8", "15"])( + "uses ESG for plate/VIN, person, Sheba and old mapped callers (CLIENT_ID=%s)", + async (code) => { + const { service, http, offline } = fixture(code); + const plate = await service.getCarByPlateInquiry(detail, { + enforceDeploymentClientMatch: true, + }); + const vin = await service.getCarByChassisInquiry({ + nationalCode: "0012345678", + chassisNo: "NAAR03HFFRDE07024", + }); + const person = await service.getPersonalInquiry("0012345678", "13770101"); + const sheba = await service.getShebaValidation( + "0012345678", + "IR000000000000000000000000", + ); + const legacyMapped = await service.getSandHubResponse(detail); + expect(plate.mapped.CompanyCode).toBe(code); + expect(vin.mapped.PrntPlcyCmpDocNo).toBe("POLICY-TEST"); + expect(person.firstName).toBe("نمونه"); + expect(sheba.ReturnValue).toBe(true); + expect(legacyMapped.PrntPlcyCmpDocNo).toBe("POLICY-TEST"); + expect( + http.post.mock.calls.filter(([url]) => url.endsWith("/auth/login")), + ).toHaveLength(1); + expect(http.post).toHaveBeenCalledWith( + "http://esg.example.test/api/inquiry/person", + { + nationalCode: "0012345678", + birthDate: "1377-01-01", + dateHasPostfix: 0, + }, + expect.objectContaining({ + headers: expect.objectContaining({ + Authorization: "Bearer fixture-token", + }), + }), + ); + expect(http.post).toHaveBeenCalledWith( + "http://esg.example.test/api/inquiry/carByPlate", + { + nationalCode: "0012345678", + plk1: "12", + plk2: "ب", + plk3: "345", + plksrl: "67", + }, + expect.any(Object), + ); + expect( + http.post.mock.calls.every(([url]) => + url.startsWith("http://esg.example.test/api/"), + ), + ).toBe(true); + expect(offline.findPlateInquiry).not.toHaveBeenCalled(); + }, + ); + + it("keeps disabled inquiry mocks independent of ESG credentials", async () => { + const { service, http, settings } = fixture(); + settings.isInquiryLive.mockResolvedValue(false); + delete process.env.ESG_URL; + delete process.env.ESG_USERNAME; + delete process.env.ESG_PASSWORD; + expect( + (await service.getCarByPlateInquiry(detail)).mapped.CompanyCode, + ).toBe("7"); + expect((await service.getPersonalInquiry("0012345678", 13770101)).nin).toBe( + "0012345678", + ); + expect( + (await service.getShebaValidation("0012345678", "IR00")).ReturnValue, + ).toBe(true); + expect((await service.getCarBodyInquiry(detail)).mapped.CompanyCode).toBe( + 7, + ); + expect(http.post).not.toHaveBeenCalled(); + }); + + it.each( + ["7", "8", "15"].flatMap((code) => + [detail.plate, "NAAR03HFFRDE07024"].map((plate) => ({ code, plate })), + ), + )( + "uses tenant Fanavaran for car-body without legacy login ($code, $plate)", + async ({ code, plate }) => { + const { service, http, lookups } = fixture(code); + expect(resolveFanavaranClientKey()).toBe( + code === "7" ? "moallem" : code === "8" ? "parsian" : "tejaratno", + ); + const result = await service.getCarBodyInquiry({ + ...detail, + plate, + accidentDate: "1405/08/01", + }); + expect(lookups.findLastProcessedCarPolicy).toHaveBeenCalledWith( + "car-body", + { + nationalCode: "0012345678", + accidentDate: "1405/08/01", + ...(typeof plate === "string" + ? { vin: plate } + : { + plaqueLeft: "12", + plaqueLetter: "ب", + plaqueRight: "345", + plaqueSerial: "67", + }), + }, + ); + expect(result.source).toBe( + typeof plate === "string" + ? "FANAVARAN_CAR_BODY_VIN_INQUIRY" + : "FANAVARAN_CAR_BODY_INQUIRY", + ); + expect(result.mapped.CompanyCode).toBe(code); + expect(result.mapped.CompanyName).toBe("بیمه نمونه"); + expect(http.post).not.toHaveBeenCalled(); + }, + ); + + it("preserves an explicit Fanavaran profile and rejects a mismatched car-body source", async () => { + const { service } = fixture(); + process.env.FANAVARAN_CLIENT = "parsian"; + expect(resolveFanavaranClientKey()).toBe("parsian"); + await expect(service.getCarBodyInquiry(detail)).rejects.toThrow( + ForbiddenException, + ); + }); + + it("does not label another insurer's body policy as Moalem", async () => { + const { service, lookups } = fixture(); + lookups.findLastProcessedCarPolicy.mockResolvedValue({ + policy: { CompanyId: "8" }, + customer: {}, + vehicle: {}, + }); + await expect(service.getCarBodyInquiry(detail)).rejects.toThrow( + ForbiddenException, + ); + }); + + it("fails locally for missing ESG configuration, without trying the old endpoint", async () => { + const { service, http } = fixture(); + delete process.env.ESG_URL; + await expect(service.getCarByPlateInquiry(detail)).rejects.toThrow( + ServiceUnavailableException, + ); + expect(http.post).not.toHaveBeenCalled(); + process.env.ESG_URL = "http://esg.example.test/api"; + delete process.env.ESG_PASSWORD; + await expect(service.getCarByPlateInquiry(detail)).rejects.toThrow( + UnauthorizedException, + ); + expect(http.post).not.toHaveBeenCalled(); + }); + + it("refreshes an ESG token once on 401 without switching providers", async () => { + const { service, http } = fixture(); + const normal = http.post.getMockImplementation()!; + let attempts = 0, + tokens = 0; + http.post.mockImplementation((url: string) => { + if (url.endsWith("/auth/login")) + return of({ + data: { accessToken: `fixture-token-${++tokens}`, expiresIn: 900 }, + }); + if (url.endsWith("/inquiry/person") && attempts++ === 0) + return throwError(() => ({ + response: { status: 401, data: { message: "expired" } }, + })); + return normal(url); + }); + expect( + (await service.getPersonalInquiry("0012345678", "13770101")).firstName, + ).toBe("نمونه"); + expect(tokens).toBe(2); + expect( + http.post.mock.calls.every(([url]) => + url.startsWith("http://esg.example.test/api/"), + ), + ).toBe(true); + }); + + it("preserves optional licence and ownership behavior until ESG has equivalent contracts", async () => { + const { service, http, settings } = fixture(); + settings.isInquiryLive.mockResolvedValue(false); + expect( + (await service.getDrivingLicenseInfo("0012345678", "123")).IsSucceed, + ).toBe(true); + expect( + (await service.getCarOwnershipInfo(detail.plate, "0012345678")).data + .IsSuccess, + ).toBe(true); + expect(http.post).not.toHaveBeenCalled(); + settings.isInquiryLive.mockResolvedValue(true); + const optionalHub = jest.spyOn(service as any, "makeSandHubRequest"); + optionalHub.mockResolvedValueOnce({ data: { IsSucceed: true } }); + await service.getDrivingLicenseInfo("0012345678", "123"); + expect(optionalHub).toHaveBeenCalledWith( + expect.stringContaining("/driver-license-check"), + { nationalCode: "0012345678", driverLicenseNumber: "123" }, + "drivingLicense", + undefined, + ); + optionalHub.mockResolvedValueOnce({ data: { IsSuccess: true } }); + await service.getCarOwnershipInfo(detail.plate, "0012345678"); + expect(optionalHub).toHaveBeenLastCalledWith( + expect.stringContaining("/ownership"), + expect.objectContaining({ nationalCode: "0012345678" }), + "carOwnership", + undefined, + ); + }); +}); diff --git a/src/sand-hub/sand-hub.service.spec.ts b/src/sand-hub/sand-hub.service.spec.ts index 0702be3..ea8c94f 100644 --- a/src/sand-hub/sand-hub.service.spec.ts +++ b/src/sand-hub/sand-hub.service.spec.ts @@ -60,6 +60,7 @@ describe("SandHubService inquiry mocks", () => { beforeEach(() => { jest.clearAllMocks(); process.env.CLIENT_ID = "8"; + process.env.ESG_URL = "http://esg.example.test"; delete process.env.FANAVARAN_CLIENT; service = new SandHubService( httpService as any, @@ -77,7 +78,7 @@ describe("SandHubService inquiry mocks", () => { }); it("keeps disabled-live third-party mock policy usable", async () => { - const result = await service.getTejaratBlockInquiry(userDetail, { + const result = await service.getCarByPlateInquiry(userDetail, { enforceDeploymentClientMatch: true, }); @@ -87,7 +88,7 @@ describe("SandHubService inquiry mocks", () => { }); it("returns car-body mock without HTTP when carBodyPlate is off", async () => { - const result = await service.getTejaratCarBodyInquiry(userDetail); + const result = await service.getCarBodyInquiry(userDetail); expect(httpService.post).not.toHaveBeenCalled(); expect(externalInquirySettings.isInquiryLive).toHaveBeenCalledWith( @@ -107,7 +108,7 @@ describe("SandHubService inquiry mocks", () => { expect(result.mapped.platePartThree).toBe(498); }); - it("uses the processed ESG CAR_BODY lookup and preserves it as raw data", async () => { + it("uses the processed Fanavaran CAR_BODY lookup and preserves it as raw data", async () => { process.env.CLIENT_ID = "8"; externalInquirySettings.isInquiryLive.mockResolvedValue(true); lookupsService.findLastProcessedCarPolicy.mockResolvedValue({ @@ -140,7 +141,7 @@ describe("SandHubService inquiry mocks", () => { plaqueSerial: "60", }, ); - expect(result.source).toBe("ESG_CAR_BODY_INQUIRY"); + expect(result.source).toBe("FANAVARAN_CAR_BODY_INQUIRY"); expect(result.raw.policyId).toBe(15292336); expect(result.mapped.policyNumber).toBe("70019846985"); expect(httpService.post).not.toHaveBeenCalled(); @@ -170,7 +171,7 @@ describe("SandHubService inquiry mocks", () => { data: { PrntCmpDocNo: "REAL-ESG-POLICY" }, }); - const result = await service.getTejaratBlockInquiry(userDetail); + const result = await service.getCarByPlateInquiry(userDetail); expect(esg).toHaveBeenCalled(); expect(result.raw).not.toEqual({ mocked: true }); @@ -185,7 +186,7 @@ describe("SandHubService inquiry mocks", () => { data: { PrntCmpDocNo: "ESG-PLATE-POLICY" }, }); - await service.getTejaratBlockInquiry(userDetail); + await service.getCarByPlateInquiry(userDetail); expect(esg).toHaveBeenCalledWith( expect.stringMatching(/\/inquiry\/carByPlate$/), @@ -236,7 +237,7 @@ describe("SandHubService inquiry mocks", () => { }, }); - const result = await service.getTejaratBlockInquiry(userDetail, { + const result = await service.getCarByPlateInquiry(userDetail, { enforceDeploymentClientMatch: true, }); @@ -271,14 +272,14 @@ describe("SandHubService inquiry mocks", () => { it("rejects a guilty third-party policy issued by another insurer", async () => { process.env.CLIENT_ID = "15"; externalInquirySettings.isInquiryLive.mockResolvedValue(true); - jest.spyOn(service as any, "makeTejaratRequest").mockResolvedValue({ + jest.spyOn(service as any, "makeEsgRequest").mockResolvedValue({ CompanyCode: "8", CompanyName: "بیمه پارسیان", PrntPlcyCmpDocNo: "OTHER-INSURER-POLICY", }); await expect( - service.getTejaratBlockInquiry(userDetail, { + service.getCarByPlateInquiry(userDetail, { enforceDeploymentClientMatch: true, } as any), ).rejects.toBeInstanceOf(ForbiddenException); @@ -287,12 +288,12 @@ describe("SandHubService inquiry mocks", () => { it("allows an unchecked third-party policy from another insurer", async () => { process.env.CLIENT_ID = "15"; externalInquirySettings.isInquiryLive.mockResolvedValue(true); - jest.spyOn(service as any, "makeTejaratRequest").mockResolvedValue({ + jest.spyOn(service as any, "makeEsgRequest").mockResolvedValue({ CompanyCode: "8", CompanyName: "بیمه پارسیان", }); - await expect(service.getTejaratBlockInquiry(userDetail)).resolves.toEqual( + await expect(service.getCarByPlateInquiry(userDetail)).resolves.toEqual( expect.objectContaining({ mapped: expect.objectContaining({ CompanyCode: "8" }), }), @@ -344,10 +345,7 @@ describe("SandHubService inquiry mocks", () => { it("does not accept a policy when CLIENT_ID is not configured", async () => { delete process.env.CLIENT_ID; externalInquirySettings.isInquiryLive.mockResolvedValue(true); - jest.spyOn(service, "getTejaratCarBodyInquiry").mockResolvedValue({ - raw: { data: { companyId: "15" } }, - mapped: { companyId: "15", CompanyCode: "15" }, - }); + await expect(service.getCarBodyInquiry(userDetail)).rejects.toBeInstanceOf( ServiceUnavailableException, @@ -372,10 +370,8 @@ describe("SandHubService inquiry mocks", () => { it("rejects a CAR_BODY policy from another insurer on the Tejarat lookup route", async () => { process.env.CLIENT_ID = "15"; externalInquirySettings.isInquiryLive.mockResolvedValue(true); - jest.spyOn(service, "getTejaratCarBodyInquiry").mockResolvedValue({ - raw: { data: { companyId: "8" } }, - mapped: { companyId: "8", CompanyCode: "8" }, - }); + lookupsService.findLastProcessedCarPolicy.mockResolvedValue({ policy: { CompanyId: "8" }, customer: {}, vehicle: {} }); + await expect(service.getCarBodyInquiry(userDetail)).rejects.toBeInstanceOf( ForbiddenException, @@ -393,7 +389,7 @@ describe("SandHubService inquiry mocks", () => { await expect(service.getCarBodyInquiry(userDetail)).resolves.toEqual( expect.objectContaining({ - source: "ESG_CAR_BODY_INQUIRY", + source: "FANAVARAN_CAR_BODY_INQUIRY", mapped: expect.objectContaining({ companyId: 15 }), }), ); @@ -408,9 +404,7 @@ describe("SandHubService inquiry mocks", () => { customer: {}, vehicle: {}, }); - const tejarat = jest - .spyOn(service, "getTejaratCarBodyInquiry") - .mockResolvedValue({ raw: { mocked: true }, mapped: {} }); + const result = await service.getCarBodyInquiry(userDetail); @@ -418,22 +412,21 @@ describe("SandHubService inquiry mocks", () => { "car-body", expect.objectContaining({ nationalCode: "1234567890" }), ); - expect(tejarat).not.toHaveBeenCalled(); expect(result.raw).not.toEqual({ mocked: true }); }); - it("keeps ESG car-body inquiry in mock mode when the per-client toggle is off", async () => { + it("keeps Fanavaran car-body inquiry in mock mode when the per-client toggle is off", async () => { process.env.CLIENT_ID = "8"; const result = await service.getCarBodyInquiry(userDetail); expect(lookupsService.findLastProcessedCarPolicy).not.toHaveBeenCalled(); - expect(result.source).toBe("ESG_CAR_BODY_INQUIRY"); + expect(result.source).toBe("FANAVARAN_CAR_BODY_INQUIRY"); expect(result.raw?.isSuccess).toBe(true); expect(httpService.post).not.toHaveBeenCalled(); }); - it("uses the VIN lookup and VIN audit source for ESG car-body VIN inquiries", async () => { + it("uses the VIN lookup and VIN audit source for Fanavaran car-body VIN inquiries", async () => { process.env.CLIENT_ID = "8"; externalInquirySettings.isInquiryLive.mockResolvedValue(true); lookupsService.findLastProcessedCarPolicy.mockResolvedValue({ @@ -451,7 +444,7 @@ describe("SandHubService inquiry mocks", () => { "car-body", { nationalCode: "1234567890", vin: "NAAR03HFFRDE07024" }, ); - expect(result.source).toBe("ESG_CAR_BODY_VIN_INQUIRY"); + expect(result.source).toBe("FANAVARAN_CAR_BODY_VIN_INQUIRY"); }); it("uses the tenant Fanavaran VIN lookup for non-Parsian car-body inquiries", async () => { @@ -463,7 +456,6 @@ describe("SandHubService inquiry mocks", () => { customer: {}, vehicle: { VIN: "NAAR03HFFRDE07024" }, }); - const tejarat = jest.spyOn(service, "getTejaratCarBodyInquiry"); const result = await service.getCarBodyInquiry({ nationalCodeOfInsurer: "0012345678", @@ -474,47 +466,26 @@ describe("SandHubService inquiry mocks", () => { "car-body", { nationalCode: "0012345678", vin: "NAAR03HFFRDE07024" }, ); - expect(tejarat).not.toHaveBeenCalled(); - expect(result.source).toBe("TEJARAT_CAR_BODY_VIN_INQUIRY"); + expect(result.source).toBe("FANAVARAN_CAR_BODY_VIN_INQUIRY"); }); it("returns a VIN-shaped car-body mock without invoking a plate adapter", async () => { process.env.CLIENT_ID = "15"; process.env.FANAVARAN_CLIENT = "tejaratno"; - const tejarat = jest.spyOn(service, "getTejaratCarBodyInquiry"); const result = await service.getCarBodyInquiry({ nationalCodeOfInsurer: "0012345678", plate: "NAAR03HFFRDE07024", }); - expect(tejarat).not.toHaveBeenCalled(); expect(lookupsService.findLastProcessedCarPolicy).not.toHaveBeenCalled(); - expect(result.source).toBe("TEJARAT_CAR_BODY_VIN_INQUIRY"); + expect(result.source).toBe("FANAVARAN_CAR_BODY_VIN_INQUIRY"); expect(result.mapped.VinNumberField).toBe("NAAR03HFFRDE07024"); expect(result.mapped.insurerNationalCode).toBe("0012345678"); }); - it("uses car-body mock shape in Tejarat helper when inquiry is off", async () => { - const raw = await (service as any).makeTejaratRequest( - "http://example/block-inquiry-tejarat/badane", - { - part1: 16, - part2: 12, - part3: 498, - part4: 60, - nationalCode: "1234567890", - }, - "carBodyPlate", - ); - - expect(httpService.post).not.toHaveBeenCalled(); - expect(raw?.data?.printNumber).toBe("1405/1143-70591/220/1/0"); - expect(raw?.data?.companyName).toBe("بیمه پارسیان"); - }); - it("returns third-party plate mock for block inquiry when inquiry is off", async () => { - const result = await service.getTejaratBlockInquiry(userDetail); + const result = await service.getCarByPlateInquiry(userDetail); expect(httpService.post).not.toHaveBeenCalled(); expect(result.mapped?.CompanyName).toBe("بیمه پارسیان"); diff --git a/src/sand-hub/sand-hub.service.ts b/src/sand-hub/sand-hub.service.ts index 6dec062..17d49bd 100644 --- a/src/sand-hub/sand-hub.service.ts +++ b/src/sand-hub/sand-hub.service.ts @@ -25,13 +25,12 @@ import { type InquiryErrorContext, } from "src/common/utils/inquiry-error"; import { resolveFanavaranClientKey } from "src/core/config/fanavaran-client.config"; -import { jalaliToGregorianDate } from "src/helpers/date-jalali"; import { LookupsService } from "src/lookups/lookups.service"; import { OfflineInquiryService } from "src/offline-inquiry/offline-inquiry.service"; import { PlateNormalizerService } from "src/utils/plate-normalizer/plate-normalizer.service"; import { SandHubDetailDto, SandHubInquiryOptions } from "./dto/sand-hub.dto"; -import { mapEsgCarBodyPolicyToInquiry } from "./esg-car-body-inquiry.mapper"; +import { mapFanavaranCarBodyPolicyToInquiry } from "./fanavaran-car-body-inquiry.mapper"; type CarBodyInquiryDetail = Omit & { plate: Plates | string; @@ -43,12 +42,7 @@ export class SandHubService { private readonly logger = new Logger(SandHubService.name); private loginToken: string | null = null; private tokenExpiry: Date | null = null; - - // Tejarat inquiry auth (82.99.202.245:3027) - private tejaratAccessToken: string | null = null; - private tejaratTokenExpiry: Date | null = null; - - // ESG inquiry auth (used for selected tenants, e.g. CLIENT_ID=8) + // ESG inquiry authentication shared by all deployment tenants. private esgAccessToken: string | null = null; private esgTokenExpiry: Date | null = null; @@ -83,19 +77,6 @@ export class SandHubService { ); } - private shouldUseEsgInquiryProvider(): boolean { - return String(process.env.CLIENT_ID ?? "") === "8"; - } - - /** - * The processed Fanavaran CAR_BODY lookup belongs only to the Parsian - * Fanavaran profile. Do not use the deployment-wide ESG selector here: - * `FANAVARAN_CLIENT=parsian` is valid even when CLIENT_ID is not 8. - */ - private shouldUseParsianCarBodyLookup(): boolean { - return resolveFanavaranClientKey() === "parsian"; - } - private inquiryContext(type: ExternalInquiryType): InquiryErrorContext { if (type === "vinChassis") return "thirdPartyVin"; return type; @@ -155,25 +136,6 @@ export class SandHubService { } } - /** - * The processed Fanavaran CAR_BODY endpoint is a Parsian-only source and its - * response does not contain a reliable insurer company code. Treat the source - * itself as proof that the returned policy is Parsian. - */ - private assertParsianCarBodyLookupMatchesDeployment(): void { - const expectedClientCode = String(process.env.CLIENT_ID ?? "").trim(); - if (!expectedClientCode) { - throw new ServiceUnavailableException( - "تنظیمات شرکت بیمه برای بررسی اعتبار بیمه‌نامه کامل نیست.", - ); - } - if (expectedClientCode === "8") return; - - throw new ForbiddenException( - "بیمه‌نامه یافت‌شده متعلق به شرکت بیمه این سامانه نیست.", - ); - } - /** Fixed plate/insurance inquiry payload used everywhere we mock block-inquiry style APIs. */ private buildMockPlateInquiryRaw( ctx: MockInquiryCompanyContext, @@ -254,33 +216,7 @@ export class SandHubService { }; } - /** Build {@link SandHubDetailDto} from Tejarat badane / block-inquiry request bodies. */ - private tejaratPayloadToSandHubDetail(payload: { - nationalCode?: string | number; - part1?: string | number; - part2?: string | number; - part3?: string | number; - part4?: string | number; - leftTwoDigits?: string | number; - serialLetter?: string | number; - threeDigits?: string | number; - rightTwoDigits?: string | number; - }): SandHubDetailDto { - const nationalCode = String(payload.nationalCode ?? ""); - return { - nationalCodeOfInsurer: nationalCode, - plate: { - leftDigits: Number(payload.part1 ?? payload.leftTwoDigits ?? 16), - centerAlphabet: this.plateNormalizer.normalizePlateText( - String(payload.part2 ?? payload.serialLetter ?? "12"), - ), - centerDigits: Number(payload.part3 ?? payload.threeDigits ?? 498), - ir: Number(payload.part4 ?? payload.rightTwoDigits ?? 60), - nationalCode, - }, - }; - } - + /** Mock shape retained for compatibility with stored car-body inquiry data. */ private buildMockCarBodyInquiryRaw( userDetail: CarBodyInquiryDetail, ctx: MockInquiryCompanyContext, @@ -334,97 +270,6 @@ export class SandHubService { }; } - private buildMockInquiryRaw( - inquiryType: ExternalInquiryType, - ctx: MockInquiryCompanyContext, - payload?: unknown, - userDetail?: SandHubDetailDto, - ): Record { - if (inquiryType === "carBodyPlate") { - const detail = - userDetail ?? - this.tejaratPayloadToSandHubDetail( - (payload ?? {}) as Record, - ); - return this.buildMockCarBodyInquiryRaw(detail, ctx); - } - return this.buildMockPlateInquiryRaw(ctx); - } - - /** - * Bodies returned from `makeSandHubRequest` in mock mode (same shape callers expect from real API). - */ - private buildMockSandHubResponseForUrl( - url: string, - payload?: unknown, - plateMock?: Record, - ): any { - const u = (url || "").toLowerCase(); - if (u.includes("personal-inquiry")) { - const p = payload as { nationalCode?: string } | undefined; - const nin = typeof p?.nationalCode === "string" ? p.nationalCode : "-"; - return { - message: "success", - data: { - firstName: "نام", - lastName: "خانوادگی", - fatherName: "-", - birthCertificateNumber: "-", - nin, - }, - }; - } - if (u.includes("driver-license-check")) { - return { - data: { - IsSucceed: true, - Message: "mock", - }, - }; - } - if (u.includes("ownership")) { - return { - data: { - IsSuccess: true, - }, - }; - } - if (u.includes("sheba")) { - return { - ReturnValue: true, - HasError: false, - Message: "mock-sheba-ok", - }; - } - if (u.includes("badane")) { - return ( - plateMock ?? - this.buildMockCarBodyInquiryRaw( - this.tejaratPayloadToSandHubDetail( - (payload ?? {}) as Record, - ), - { - companyId: process.env.CLIENT_ID ?? "15", - companyName: process.env.CLIENT_NAME ?? "بیمه سامان", - }, - ) - ); - } - if (u.includes("block-inquiry") || u.includes("tejarat")) { - return this.mapNewApiResponseToOldFormat( - plateMock ?? - this.buildMockPlateInquiryRaw({ - companyId: process.env.CLIENT_ID ?? "15", - companyName: process.env.CLIENT_NAME ?? "بیمه سامان", - }), - ); - } - this.logger.warn( - `[MOCK] Unrecognized SandHub URL; returning generic OK: ${url}`, - ); - return { data: {}, message: "mock-ok" }; - } - private async getAccessToken(): Promise { if (this.loginToken && this.tokenExpiry && this.tokenExpiry > new Date()) { return this.loginToken; @@ -461,66 +306,24 @@ export class SandHubService { } } - private async getTejaratAccessToken(): Promise { - if ( - this.tejaratAccessToken && - this.tejaratTokenExpiry && - this.tejaratTokenExpiry > new Date() - ) { - return this.tejaratAccessToken; - } - - const baseUrl = - process.env.TEJARAT_INQUIRY_BASE_URL ?? "http://82.99.202.245:3027"; - const email = process.env.TEJARAT_INQUIRY_EMAIL; - const password = process.env.TEJARAT_INQUIRY_PASSWORD; - - if (!email || !password) { - throw new UnauthorizedException( - "اطلاعات اتصال به سرویس استعلام تجارت نو تنظیم نشده است.", - ); - } - - this.logger.log( - "Tejarat inquiry token is missing or expired. Fetching a new one...", + /** Only optional licence and legal-ownership checks still use their configured hub. */ + private buildMockSandHubResponseForUrl(url: string): any { + if (url.includes("driver-license-check")) + return { data: { IsSucceed: true, Message: "mock" } }; + if (url.includes("ownership")) return { data: { IsSuccess: true } }; + throw new ServiceUnavailableException( + "نوع استعلام در سرویس فعلی پشتیبانی نمی‌شود.", ); + } - try { - const response = await firstValueFrom( - this.httpService.post( - `${baseUrl}/user/login`, - { email, password }, - { - headers: { - Accept: "*/*", - "Content-Type": "application/json", - }, - timeout: 30000, - }, - ), - ); - - const token = response.data?.accessToken; - if (!token) { - throw new Error("No access token returned from Tejarat login"); - } - - this.tejaratAccessToken = token; - // No explicit expiry in response; keep a conservative cache window. - this.tejaratTokenExpiry = new Date(Date.now() + 55 * 60 * 1000); - - return this.tejaratAccessToken; - } catch (er) { - this.logger.error( - "Failed to login to Tejarat inquiry:", - er?.message || er, - ); - this.tejaratAccessToken = null; - this.tejaratTokenExpiry = null; - throw new UnauthorizedException( - "احراز هویت سرویس استعلام تجارت نو انجام نشد.", + private esgUrl(path: string): string { + const baseUrl = process.env.ESG_URL?.trim().replace(/\/+$/, ""); + if (!baseUrl) { + throw new ServiceUnavailableException( + "نشانی سرویس یکپارچه استعلام تنظیم نشده است.", ); } + return `${baseUrl}${path}`; } private async getEsgAccessToken(): Promise { @@ -532,11 +335,10 @@ export class SandHubService { return this.esgAccessToken; } - const baseUrl = process.env.ESG_URL; const username = process.env.ESG_USERNAME; const password = process.env.ESG_PASSWORD; - if (!baseUrl || !username || !password) { + if (!username || !password) { throw new UnauthorizedException( "اطلاعات اتصال به سرویس استعلام ESG تنظیم نشده است.", ); @@ -547,7 +349,7 @@ export class SandHubService { try { const response = await firstValueFrom( this.httpService.post( - `${baseUrl}/auth/login`, + this.esgUrl("/auth/login"), { username, password }, { headers: { @@ -606,7 +408,7 @@ export class SandHubService { Message: "mock-sheba-ok", }; } - return this.buildMockInquiryRaw(inquiryType, ctx, payload); + return this.buildMockPlateInquiryRaw(ctx); } const INITIAL_DELAY = 500; @@ -671,7 +473,7 @@ export class SandHubService { } // Real ESG response wraps payload in { success: true, data: { ... } }. - // Mock data and Tejarat-format fallback are flat objects with no .data wrapper — + // Mock data and historical records are flat objects with no .data wrapper — // in that case use raw itself so CompanyName / CompanyCode are preserved. const data = raw?.data != null && typeof raw?.data === "object" ? raw.data : raw; @@ -708,7 +510,7 @@ export class SandHubService { /** * Normalises Jalali birth dates to `YYYY-MM-DD` for ESG person inquiry. - * Unlike Tejarat/SandHub personal inquiry, ESG expects Jalali — not Gregorian. + * ESG expects the Jalali date, not a Gregorian conversion. */ private normalizeJalaliBirthDateForEsg( input: string | number | null | undefined, @@ -799,72 +601,12 @@ export class SandHubService { }; } - private async makeTejaratRequest( - url: string, - payload: any, - inquiryType: ExternalInquiryType, - options?: SandHubInquiryOptions, - maxRetries = 2, - ) { - if (!(await this.isInquiryLive(inquiryType, options))) { - this.logger.log(`[MOCK] Tejarat POST skipped (${inquiryType}): ${url}`); - const ctx = await this.mockCompanyContext(options); - return this.buildMockInquiryRaw(inquiryType, ctx, payload); - } - const INITIAL_DELAY = 500; - const BACKOFF_FACTOR = 2; - - for (let attempt = 0; attempt < maxRetries; attempt++) { - const token = await this.getTejaratAccessToken(); - try { - const response = await firstValueFrom( - this.httpService.post(url, payload, { - headers: { - Authorization: `Bearer ${token}`, - "Content-Type": "application/json", - Accept: "application/json", - }, - timeout: 30000, - }), - ); - if (!response?.data) throw new Error("EMPTY_RESPONSE"); - return response.data; - } catch (err: any) { - const status = err?.response?.status; - const data = err?.response?.data; - - this.logger.error( - `Tejarat request failed (attempt ${attempt + 1}/${maxRetries}) to ${url} with status ${ - status ?? "NO_STATUS" - }`, - data ? JSON.stringify(data) : err?.message || err, - ); - - // If unauthorized, clear token and retry once - if (status === 401) { - this.tejaratAccessToken = null; - this.tejaratTokenExpiry = null; - } - - if ([400, 404, 409, 422].includes(status)) { - this.throwInquiryError(err, this.inquiryContext(inquiryType)); - } - - if (attempt === maxRetries - 1) { - this.throwInquiryError(err, this.inquiryContext(inquiryType)); - } - const delay = INITIAL_DELAY * Math.pow(BACKOFF_FACTOR, attempt); - await new Promise((resolve) => setTimeout(resolve, delay)); - } - } - } - /** - * Tejarat block inquiry (replaces SandHub call for V2 flows). + * ESG plate inquiry for every tenant. * Returns both raw + mapped (old-format) response. - * Offline seeded hits (per Fanavaran clientKey) are checked first. + * Offline seeded hits are used only when the live inquiry is disabled. */ - async getTejaratBlockInquiry( + async getCarByPlateInquiry( userDetail: SandHubDetailDto, options?: SandHubInquiryOptions, ): Promise<{ @@ -879,7 +621,7 @@ export class SandHubService { }> { const live = await this.isInquiryLive("thirdPartyPlate", options); // Offline records are a fallback for disabled inquiry mode only. They must - // never override a configured live ESG/Tejarat inquiry. + // never override a configured live ESG inquiry. if (!live) { const offlineHit = await this.offlineInquiryService.findPlateInquiry({ clientKey: resolveFanavaranClientKey(), @@ -909,54 +651,17 @@ export class SandHubService { } const ctx = await this.mockCompanyContext(options); - if (this.shouldUseEsgInquiryProvider()) { - const baseUrl = process.env.ESG_URL ?? "http://192.168.20.22:8085"; - const requestPayload = { - nationalCode: String(userDetail.nationalCodeOfInsurer), - plk1: String(userDetail.plate.leftDigits), - plk2: String(userDetail.plate.centerAlphabet), - plk3: String(userDetail.plate.centerDigits), - plksrl: String(userDetail.plate.ir), - }; - - const requestUrl = `${baseUrl}/inquiry/carByPlate`; - const raw = live - ? await this.makeEsgRequest( - requestUrl, - requestPayload, - "thirdPartyPlate", - options, - ) - : this.buildMockPlateInquiryRaw(ctx); - if (!live) { - this.logger.debug( - `[MOCK] getEsgPolicyByPlateInquiry plate=${JSON.stringify(requestPayload)}`, - ); - } - const mapped = this.mapEsgPolicyByPlateToOldFormat( - raw, - "thirdPartyPlate", - ); - if (!mapped?.Error) { - this.enforceDeploymentClientMatch(mapped, "THIRD_PARTY", options); - } - return { raw, mapped }; - } - - const baseUrl = - process.env.TEJARAT_INQUIRY_BASE_URL ?? "http://82.99.202.245:3027"; const requestPayload = { - leftTwoDigits: String(userDetail.plate.leftDigits), - serialLetter: String(userDetail.plate.centerAlphabet), - threeDigits: String(userDetail.plate.centerDigits), - rightTwoDigits: String(userDetail.plate.ir), - nationalCode: userDetail.nationalCodeOfInsurer, + nationalCode: String(userDetail.nationalCodeOfInsurer), + plk1: String(userDetail.plate.leftDigits), + plk2: String(userDetail.plate.centerAlphabet), + plk3: String(userDetail.plate.centerDigits), + plksrl: String(userDetail.plate.ir), }; - const requestUrl = `${baseUrl}/block-inquiry-tejarat`; const raw = live - ? await this.makeTejaratRequest( - requestUrl, + ? await this.makeEsgRequest( + this.esgUrl("/inquiry/carByPlate"), requestPayload, "thirdPartyPlate", options, @@ -964,105 +669,70 @@ export class SandHubService { : this.buildMockPlateInquiryRaw(ctx); if (!live) { this.logger.debug( - `[MOCK] getTejaratBlockInquiry plate=${JSON.stringify(requestPayload)}`, + `[MOCK] getEsgPolicyByPlateInquiry plate=${JSON.stringify(requestPayload)}`, ); } - const mapped = isInquiryFailurePayload(raw) - ? { - Error: { - Message: getInquiryErrorMessage(raw, "thirdPartyPlate"), - }, - } - : this.mapNewApiResponseToOldFormat(raw); + const mapped = this.mapEsgPolicyByPlateToOldFormat(raw, "thirdPartyPlate"); if (!mapped?.Error) { this.enforceDeploymentClientMatch(mapped, "THIRD_PARTY", options); } return { raw, mapped }; } - /** - * CAR_BODY is the only ESG product that uses the processed Fanavaran lookup. - * THIRD_PARTY remains on its established provider-specific inquiry path. - */ + /** Car-body policies always come from the deployment's Fanavaran profile. */ async getCarBodyInquiry( userDetail: CarBodyInquiryDetail, options?: SandHubInquiryOptions, ): Promise<{ - source: - | "ESG_CAR_BODY_INQUIRY" - | "ESG_CAR_BODY_VIN_INQUIRY" - | "TEJARAT_CAR_BODY_INQUIRY" - | "TEJARAT_CAR_BODY_VIN_INQUIRY"; + source: "FANAVARAN_CAR_BODY_INQUIRY" | "FANAVARAN_CAR_BODY_VIN_INQUIRY"; raw: any; mapped: Record; }> { - const useParsianCarBodyLookup = this.shouldUseParsianCarBodyLookup(); - const live = await this.isInquiryLive("carBodyPlate", options); - const plateOrVin = userDetail.plate; - const isVinInquiry = typeof plateOrVin === "string"; - - if (!live) { - // Mock results are generated for the active deployment. They must not be - // treated as evidence of a real insurer and therefore do not go through - // the live-policy insurer gate. + const isVinInquiry = typeof userDetail.plate === "string"; + const source = isVinInquiry + ? "FANAVARAN_CAR_BODY_VIN_INQUIRY" + : "FANAVARAN_CAR_BODY_INQUIRY"; + if (!(await this.isInquiryLive("carBodyPlate", options))) { const ctx = await this.mockCompanyContext(options); const raw = this.buildMockCarBodyInquiryRaw(userDetail, ctx); - const result = { raw, mapped: this.mapCarBodyInquiryResponse(raw) }; - return { - source: isVinInquiry - ? useParsianCarBodyLookup - ? "ESG_CAR_BODY_VIN_INQUIRY" - : "TEJARAT_CAR_BODY_VIN_INQUIRY" - : useParsianCarBodyLookup - ? "ESG_CAR_BODY_INQUIRY" - : "TEJARAT_CAR_BODY_INQUIRY", - ...result, - }; + return { source, raw, mapped: this.mapCarBodyInquiryResponse(raw) }; } - if (isVinInquiry) { - let raw: any; - try { - raw = await this.lookupsService.findLastProcessedCarPolicy("car-body", { - nationalCode: String(userDetail.nationalCodeOfInsurer), - vin: plateOrVin, - ...(userDetail.accidentDate != null - ? { accidentDate: userDetail.accidentDate } - : {}), - }); - } catch (error) { - this.throwInquiryError(error, "carBodyVin"); - } - if (useParsianCarBodyLookup) { - this.assertParsianCarBodyLookupMatchesDeployment(); - } - return { - source: useParsianCarBodyLookup - ? "ESG_CAR_BODY_VIN_INQUIRY" - : "TEJARAT_CAR_BODY_VIN_INQUIRY", - raw, - mapped: mapEsgCarBodyPolicyToInquiry(raw), - }; - } - - if (!useParsianCarBodyLookup) { - const result = await this.getTejaratCarBodyInquiry( - userDetail as SandHubDetailDto, - options, + const clientCode = String(process.env.CLIENT_ID ?? "").trim(); + if (!clientCode) { + throw new ServiceUnavailableException( + "تنظیمات شرکت بیمه برای بررسی اعتبار بیمه‌نامه کامل نیست.", ); - this.assertInsuranceMatchesDeployment(result.mapped, "CAR_BODY"); - return { - source: "TEJARAT_CAR_BODY_INQUIRY", - ...result, - }; } - + const clientKey = resolveFanavaranClientKey(); + // A scoped provider response must never be labelled as a different insurer. + const knownCode = + clientKey === "parsian" ? "8" : clientKey === "moallem" ? "7" : undefined; + const expectedKey = + clientCode === "7" + ? "moallem" + : clientCode === "8" + ? "parsian" + : undefined; + if ( + (knownCode && knownCode !== clientCode) || + (expectedKey && expectedKey !== clientKey) + ) { + throw new ForbiddenException( + "بیمه‌نامه یافت‌شده متعلق به شرکت بیمه این سامانه نیست.", + ); + } + const plate = userDetail.plate; const query = { nationalCode: String(userDetail.nationalCodeOfInsurer), - plaqueLeft: String(plateOrVin.leftDigits), - plaqueLetter: String(plateOrVin.centerAlphabet), - plaqueRight: String(plateOrVin.centerDigits), - plaqueSerial: String(plateOrVin.ir), + ...(typeof plate === "string" + ? { vin: plate } + : { + plaqueLeft: String(plate.leftDigits), + plaqueLetter: String(plate.centerAlphabet), + plaqueRight: String(plate.centerDigits), + plaqueSerial: String(plate.ir), + }), ...(userDetail.accidentDate != null ? { accidentDate: userDetail.accidentDate } : {}), @@ -1074,63 +744,23 @@ export class SandHubService { query, ); } catch (error) { - this.throwInquiryError(error, "carBodyPlate"); - } - this.assertParsianCarBodyLookupMatchesDeployment(); - - return { - source: "ESG_CAR_BODY_INQUIRY", - raw, - mapped: mapEsgCarBodyPolicyToInquiry(raw), - }; - } - - async getTejaratCarBodyInquiry( - userDetail: SandHubDetailDto, - options?: SandHubInquiryOptions, - ): Promise<{ - raw: any; - mapped: Record; - }> { - const baseUrl = - process.env.TEJARAT_INQUIRY_BASE_URL ?? "http://82.99.202.245:3027"; - - const requestPayload = { - part1: Number(userDetail.plate.leftDigits), - part2: String(userDetail.plate.centerAlphabet), - part3: Number(userDetail.plate.centerDigits), - part4: Number(userDetail.plate.ir), - nationalCode: String(userDetail.nationalCodeOfInsurer), - }; - - const requestUrl = `${baseUrl}/block-inquiry-tejarat/badane`; - const live = await this.isInquiryLive("carBodyPlate", options); - if (!live) { - this.logger.debug( - `[MOCK] getTejaratCarBodyInquiry plate=${JSON.stringify(requestPayload)}`, + this.throwInquiryError( + error, + isVinInquiry ? "carBodyVin" : "carBodyPlate", ); } - - const raw = await this.makeTejaratRequest( - requestUrl, - requestPayload, - "carBodyPlate", - options, - ); - - if (isInquiryFailurePayload(raw)) { - throw new BadRequestException( - getInquiryErrorMessage(raw, "carBodyPlate"), - ); - } - const mapped = this.mapCarBodyInquiryResponse(raw); - return { raw, mapped }; + const ctx = await this.mockCompanyContext(options); + const mapped = mapFanavaranCarBodyPolicyToInquiry(raw, { + companyId: clientCode, + companyName: ctx.companyName, + }); + this.assertInsuranceMatchesDeployment(mapped, "CAR_BODY"); + return { source, raw, mapped }; } /** - * Maps the Tejarat car-body (badane) API response to a consistent - * shape that mirrors the third-party inquiry mapped format. - * Callers should always use `mapped` for display; `raw` is kept for audit. + * Maps the historical car-body shape retained by disabled-mode fixtures. + * Live inquiries use the processed Fanavaran mapper instead. */ private mapCarBodyInquiryResponse(raw: any): Record { if (!raw) return {}; @@ -1205,8 +835,6 @@ export class SandHubService { identity: { nationalCode: string; chassisNo: string }, options?: SandHubInquiryOptions, ): Promise<{ raw: any; mapped: any }> { - const baseUrl = process.env.ESG_URL ?? "http://192.168.20.22:8085"; - const requestUrl = `${baseUrl}/inquiry/carByChassis`; const requestPayload = { nationalCode: String(identity.nationalCode), chassisNo: String(identity.chassisNo), @@ -1228,7 +856,7 @@ export class SandHubService { } const raw = await this.makeEsgRequest( - requestUrl, + this.esgUrl("/inquiry/carByChassis"), requestPayload, "vinChassis", options, @@ -1240,54 +868,6 @@ export class SandHubService { return { raw, mapped }; } - private async makeSandHubRequest( - url: string, - payload: any, - inquiryType: ExternalInquiryType, - options?: SandHubInquiryOptions, - maxRetries = 3, - ) { - if (!(await this.isInquiryLive(inquiryType, options))) { - this.logger.log(`[MOCK] SandHub POST skipped (${inquiryType}): ${url}`); - const ctx = await this.mockCompanyContext(options); - if (inquiryType === "carBodyPlate") { - return this.buildMockInquiryRaw(inquiryType, ctx, payload); - } - const plateMock = - inquiryType === "thirdPartyPlate" - ? this.buildMockPlateInquiryRaw(ctx) - : undefined; - return this.buildMockSandHubResponseForUrl(url, payload, plateMock); - } - const token = await this.getAccessToken(); - const INITIAL_DELAY = 1000; - const BACKOFF_FACTOR = 2; - - for (let attempt = 0; attempt < maxRetries; attempt++) { - try { - const response = await firstValueFrom( - this.httpService.post(url, payload, { - headers: { - Authorization: `Bearer ${token}`, - "Content-Type": "application/json", - Accept: "application/json", - }, - timeout: 50000, - }), - ); - if (!response?.data) throw new Error("EMPTY_RESPONSE"); - return response.data; - } catch (err) { - this.handleSandHubError(err, attempt, maxRetries); - const delay = INITIAL_DELAY * Math.pow(BACKOFF_FACTOR, attempt); - await new Promise((resolve) => setTimeout(resolve, delay)); - } - } - throw new BadGatewayException( - "سرویس استعلام پس از چند تلاش پاسخ نداد. لطفاً کمی بعد دوباره تلاش کنید.", - ); - } - /** * Maps the new SandHub API response format to the old format expected by the application */ @@ -1450,56 +1030,12 @@ export class SandHubService { userDetail: SandHubDetailDto, options?: SandHubInquiryOptions, ) { - try { - const requestPayload = { - leftTwoDigits: String(userDetail.plate.leftDigits), - serialLetter: String(userDetail.plate.centerAlphabet), - threeDigits: String(userDetail.plate.centerDigits), - rightTwoDigits: String(userDetail.plate.ir), - nationalCode: userDetail.nationalCodeOfInsurer, - }; - const base = process.env.SANHUB_BASE_URL ?? ""; - const requestUrl = `${base}/block-inquiry-tejarat`; - - let response: any; - if (await this.isInquiryLive("thirdPartyPlate", options)) { - response = await this.makeSandHubRequest( - requestUrl, - requestPayload, - "thirdPartyPlate", - options, - ); - } else { - this.logger.debug( - `[MOCK] getSandHubResponse plate=${JSON.stringify(requestPayload)}`, - ); - const ctx = await this.mockCompanyContext(options); - response = this.buildMockPlateInquiryRaw(ctx); - } - - const result = this.mapNewApiResponseToOldFormat(response); - this.enforceDeploymentClientMatch(result, "THIRD_PARTY", options); - - // if (result.usgCod !== "8") { - // throw new Error("خودرو شما شخصی / سواری نمی باشد") - // } - - return result; - } catch (err) { - if ( - err instanceof ForbiddenException || - err instanceof ServiceUnavailableException - ) { - throw err; - } - this.throwInquiryError(err, "thirdPartyPlate"); - } + const { mapped } = await this.getCarByPlateInquiry(userDetail, options); + return mapped; } /** - * Personal identity check. - * - CLIENT_ID=8 (Parsian/ESG): Jalali birth date sent as-is to `/inquiry/person`. - * - Other tenants: Tejarat/SandHub hub with Gregorian conversion. + * Personal identity check for every tenant: ESG expects a Jalali birth date. */ async getPersonalInquiry( nationalCode: string, @@ -1507,77 +1043,82 @@ export class SandHubService { options?: SandHubInquiryOptions, ) { try { - if (this.shouldUseEsgInquiryProvider()) { - const jalaliBirthDate = this.normalizeJalaliBirthDateForEsg(birthDate); - if (!jalaliBirthDate) { - throw new BadRequestException( - "تاریخ تولد واردشده برای استعلام هویت معتبر نیست.", - ); - } - - const baseUrl = process.env.ESG_URL ?? "http://192.168.20.22:8085"; - const requestPayload = { - nationalCode: String(nationalCode), - birthDate: jalaliBirthDate, - dateHasPostfix: 0, - }; - const requestUrl = `${baseUrl}/inquiry/person`; - const live = await this.isInquiryLive("personalIdentity", options); - - if (!live) { - this.logger.debug( - `[MOCK] getEsgPersonInquiry nationalCode=${nationalCode} birthDate=${jalaliBirthDate}`, - ); - return this.getDefaultMockPersonInquiry(String(nationalCode)); - } - - const raw = await this.makeEsgRequest( - requestUrl, - requestPayload, - "personalIdentity", - options, - ); - return this.mapEsgPersonInquiryToOldFormat(raw); - } - - const requestUrl = `${process.env.SANHUB_BASE_URL}/personal-inquiry/tejarat-no`; - - const gregorianBirthdate = jalaliToGregorianDate(birthDate); - if (!gregorianBirthdate) { + const jalaliBirthDate = this.normalizeJalaliBirthDateForEsg(birthDate); + if (!jalaliBirthDate) { throw new BadRequestException( "تاریخ تولد واردشده برای استعلام هویت معتبر نیست.", ); } const requestPayload = { - nationalCode, - birthdate: gregorianBirthdate, + nationalCode: String(nationalCode), + birthDate: jalaliBirthDate, + dateHasPostfix: 0, }; + const live = await this.isInquiryLive("personalIdentity", options); - const response = await this.makeSandHubRequest( - requestUrl, + if (!live) { + this.logger.debug( + `[MOCK] getEsgPersonInquiry nationalCode=${nationalCode} birthDate=${jalaliBirthDate}`, + ); + return this.getDefaultMockPersonInquiry(String(nationalCode)); + } + + const raw = await this.makeEsgRequest( + this.esgUrl("/inquiry/person"), requestPayload, "personalIdentity", options, ); - - if (response?.message?.includes("err.record.not.found")) { - throw new NotFoundException( - getInquiryErrorMessage(response, "personalIdentity"), - ); - } - return response.data; + return this.mapEsgPersonInquiryToOldFormat(raw); } catch (err) { - if ( - err instanceof BadRequestException || - err instanceof NotFoundException - ) { + if (err instanceof BadRequestException) { throw err; } this.throwInquiryError(err, "personalIdentity"); } } + private async makeSandHubRequest( + url: string, + payload: any, + inquiryType: ExternalInquiryType, + options?: SandHubInquiryOptions, + maxRetries = 3, + ) { + if (!(await this.isInquiryLive(inquiryType, options))) { + this.logger.log(`[MOCK] SandHub POST skipped (${inquiryType}): ${url}`); + return this.buildMockSandHubResponseForUrl(url); + } + const token = await this.getAccessToken(); + const INITIAL_DELAY = 1000; + const BACKOFF_FACTOR = 2; + + for (let attempt = 0; attempt < maxRetries; attempt++) { + try { + const response = await firstValueFrom( + this.httpService.post(url, payload, { + headers: { + Authorization: `Bearer ${token}`, + "Content-Type": "application/json", + Accept: "application/json", + }, + timeout: 50000, + }), + ); + if (!response?.data) throw new Error("EMPTY_RESPONSE"); + return response.data; + } catch (err) { + this.handleSandHubError(err, attempt, maxRetries); + const delay = INITIAL_DELAY * Math.pow(BACKOFF_FACTOR, attempt); + await new Promise((resolve) => setTimeout(resolve, delay)); + } + } + throw new BadGatewayException( + "سرویس استعلام پس از چند تلاش پاسخ نداد. لطفاً کمی بعد دوباره تلاش کنید.", + ); + } + async getDrivingLicenseInfo( nationalCode: string, driverLicenseNumber: string, @@ -1661,67 +1202,36 @@ export class SandHubService { options?: SandHubInquiryOptions, ) { try { - if (this.shouldUseEsgInquiryProvider()) { - const baseUrl = process.env.ESG_URL ?? "http://192.168.20.22:8085"; - const requestPayload = { - accountOwnerType: "1", - nationalCode: String(nationalId), - legalId: "", - sheba: String(shebaId), + const requestPayload = { + accountOwnerType: "1", + nationalCode: String(nationalId), + legalId: "", + sheba: String(shebaId), + }; + const live = await this.isInquiryLive("sheba", options); + + this.logger.log( + `Validating Sheba ID via ESG for national code: ${nationalId}`, + ); + + if (!live) { + this.logger.debug( + `[MOCK] getEsgShebaInquiry nationalCode=${nationalId} sheba=${shebaId}`, + ); + return { + ReturnValue: true, + HasError: false, + Message: "mock-sheba-ok", }; - const requestUrl = `${baseUrl}/inquiry/sheba`; - const live = await this.isInquiryLive("sheba", options); - - this.logger.log( - `Validating Sheba ID via ESG for national code: ${nationalId}`, - ); - - if (!live) { - this.logger.debug( - `[MOCK] getEsgShebaInquiry nationalCode=${nationalId} sheba=${shebaId}`, - ); - return { - ReturnValue: true, - HasError: false, - Message: "mock-sheba-ok", - }; - } - - const raw = await this.makeEsgRequest( - requestUrl, - requestPayload, - "sheba", - options, - ); - const response = this.mapEsgShebaInquiryToOldFormat(raw); - - if (response?.ReturnValue === false || response?.HasError === true) { - this.logger.warn( - `Sheba validation failed for national code ${nationalId}. Response:`, - response, - ); - throw new BadRequestException( - "شماره شبا متعلق به کد ملی واردشده نیست.", - ); - } - - return response; } - const requestUrl = `${process.env.SANHUB_BASE_URL}/sheba/sheba-tejaratno`; - const requestPayload = { - AccountOwnerType: "1", - NationalId: nationalId, - ShebaId: shebaId, - }; - - this.logger.log(`Validating Sheba ID for national code: ${nationalId}`); - const response = await this.makeSandHubRequest( - requestUrl, + const raw = await this.makeEsgRequest( + this.esgUrl("/inquiry/sheba"), requestPayload, "sheba", options, ); + const response = this.mapEsgShebaInquiryToOldFormat(raw); if (response?.ReturnValue === false || response?.HasError === true) { this.logger.warn( @@ -1741,7 +1251,6 @@ export class SandHubService { this.throwInquiryError(err, "sheba"); } } - private handleSandHubError( err: any, attempt: number,