fix(inquiries): route all tenants through ESG and Fanavaran

This commit is contained in:
SepehrYahyaee
2026-11-21 15:27:06 +03:30
parent 61ef4faaf4
commit 1a38b98829
15 changed files with 675 additions and 860 deletions
+10 -4
View File
@@ -46,7 +46,16 @@ JWT_EXPIRY =
CAPTCHA_ENABLED = true 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_BASE_URL =
SANHUB_URL_LOGIN = SANHUB_URL_LOGIN =
@@ -101,9 +110,6 @@ AUTO_CLIENT_KEY_ENABLED =
# --------------------------------------------- # ---------------------------------------------
# 🔗 Other Internal Services # 🔗 Other Internal Services
# --------------------------------------------- # ---------------------------------------------
TEJARAT_INQUIRY_EMAIL =
TEJARAT_INQUIRY_PASSWORD =
PARSIAN_API_KEY = PARSIAN_API_KEY =
PARSIAN_BASIC_TOKEN = PARSIAN_BASIC_TOKEN =
PARSIAN_SMS_URL = PARSIAN_SMS_URL =
+1
View File
@@ -3,6 +3,7 @@
## Documentation ## Documentation
- [Fanavaran integration](docs/fanavaran/README.md) - [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) - [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). Insurer setup and staff/branch management: [guide](docs/insurer-staff-management.md).
+18 -120
View File
@@ -319,81 +319,21 @@ curl -X POST "$FANAVARAN_BIME_URL/car/third-party-car-financial-claims" \
--data @fanavaran-claim-submit.json --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="<response accessToken>"
```
### 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 ## 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 ```sh
ESG_URL="${ESG_URL:-http://192.168.20.22:8085}" ESG_URL="https://<gateway-host>/<optional-prefix>"
ESG_USERNAME="<gateway-username>"
ESG_PASSWORD="<gateway-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 ### Sequence
@@ -417,7 +357,7 @@ curl -X POST "$ESG_URL/auth/login" \
ESG_ACCESS_TOKEN="<response accessToken>" ESG_ACCESS_TOKEN="<response accessToken>"
``` ```
### Car By Plate (canonical Parsian third-party plate inquiry) ### Car By Plate (third-party inquiry for all tenants)
```sh ```sh
curl -X POST "$ESG_URL/inquiry/carByPlate" \ curl -X POST "$ESG_URL/inquiry/carByPlate" \
@@ -483,15 +423,18 @@ curl -X POST "$ESG_URL/inquiry/sheba" \
## SandHub Provider ## 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: Environment:
```sh ```sh
SANHUB_BASE_URL='http://82.99.202.245:3027' SANHUB_BASE_URL='https://<optional-check-provider>'
SANHUB_URL_LOGIN='http://82.99.202.245:3027/user/login' SANHUB_URL_LOGIN='https://<optional-check-provider>/<login-path>'
SANHUB_USERNAME='default@admin.com' SANHUB_USERNAME='<optional-check-username>'
SANHUB_PASSWORD='123321' SANHUB_PASSWORD='<optional-check-password>'
``` ```
### Sequence ### Sequence
@@ -515,37 +458,6 @@ curl -X POST "$SANHUB_URL_LOGIN" \
SANHUB_ACCESS_TOKEN="<response accessToken>" SANHUB_ACCESS_TOKEN="<response accessToken>"
``` ```
### 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 ### Driving License Check
```sh ```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 ## Map.ir Reverse Geocoding
Used by `src/claim-request-management/claim-request-management.service.ts`. Used by `src/claim-request-management/claim-request-management.service.ts`.
+84
View File
@@ -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://<gateway-host>/<optional-prefix>
ESG_USERNAME=<gateway-username>
ESG_PASSWORD=<gateway-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.
@@ -392,7 +392,7 @@ describe("buildInsurerFileReport", () => {
vehicle: { vehicle: {
isNew: true, isNew: true,
hasEndorsement: false, hasEndorsement: false,
source: "ESG_CAR_BODY_INQUIRY", source: "FANAVARAN_CAR_BODY_INQUIRY",
inquiry: { source: "TEJARAT_BLOCK_INQUIRY" }, inquiry: { source: "TEJARAT_BLOCK_INQUIRY" },
}, },
}, },
@@ -419,7 +419,7 @@ describe("buildInsurerFileReport", () => {
role: "FIRST", role: "FIRST",
person: { userId: "damaged", fullName: "بیمه‌گذار" }, person: { userId: "damaged", fullName: "بیمه‌گذار" },
vehicle: { vehicle: {
source: "ESG_CAR_BODY_INQUIRY", source: "FANAVARAN_CAR_BODY_INQUIRY",
inquiry: { source: "TEJARAT_BLOCK_INQUIRY" }, inquiry: { source: "TEJARAT_BLOCK_INQUIRY" },
}, },
}, },
@@ -218,6 +218,9 @@ export function resolveFanavaranClientKey(): FanavaranClientKey {
} }
// Optional deployment hint when FANAVARAN_CLIENT is not set. // 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') { if (String(process.env.CLIENT_ID ?? '') === '8') {
return 'parsian'; return 'parsian';
} }
@@ -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 () => { it("reselects and stores the earlier renewal for the supplied accident date", async () => {
const { service, party, inquiry } = setup("1401/01/02", "1402/01/02"); const { service, party, inquiry } = setup("1401/01/02", "1402/01/02");
inquiry.mockResolvedValue({ inquiry.mockResolvedValue({
source: "ESG_CAR_BODY_INQUIRY", source: "FANAVARAN_CAR_BODY_INQUIRY",
mapped: { mapped: {
policyId: 1, policyId: 1,
StartDate: "1400/01/01", StartDate: "1400/01/01",
@@ -236,7 +236,7 @@ export class InquiryRefreshService {
} else { } else {
await this.waitForRateLimit(); await this.waitForRateLimit();
try { try {
const inquiry = await this.sandHubService.getTejaratBlockInquiry( const inquiry = await this.sandHubService.getCarByPlateInquiry(
{ {
plate: { plate: {
...plate, ...plate,
@@ -50,7 +50,7 @@ describe("RequestManagementService policyholder inquiry routing", () => {
it("does not fall back from the current plate for third-party insurance", async () => { it("does not fall back from the current plate for third-party insurance", async () => {
const service = Object.create(RequestManagementService.prototype) as any; const service = Object.create(RequestManagementService.prototype) as any;
service.sandHubService = { service.sandHubService = {
getTejaratBlockInquiry: jest getCarByPlateInquiry: jest
.fn() .fn()
.mockResolvedValueOnce({ raw: {}, mapped: {} }) .mockResolvedValueOnce({ raw: {}, mapped: {} })
.mockResolvedValueOnce({ .mockResolvedValueOnce({
@@ -67,10 +67,10 @@ describe("RequestManagementService policyholder inquiry routing", () => {
"بیمه‌نامه معتبر و فعالی مطابق مشخصات خودرو و کد ملی واردشده یافت نشد.", "بیمه‌نامه معتبر و فعالی مطابق مشخصات خودرو و کد ملی واردشده یافت نشد.",
); );
expect(service.sandHubService.getTejaratBlockInquiry).toHaveBeenCalledTimes( expect(service.sandHubService.getCarByPlateInquiry).toHaveBeenCalledTimes(
1, 1,
); );
expect(service.sandHubService.getTejaratBlockInquiry).toHaveBeenCalledWith( expect(service.sandHubService.getCarByPlateInquiry).toHaveBeenCalledWith(
expect.objectContaining({ expect.objectContaining({
plate: currentPlate, plate: currentPlate,
nationalCodeOfInsurer: "0022222222", nationalCodeOfInsurer: "0022222222",
@@ -82,7 +82,7 @@ describe("RequestManagementService policyholder inquiry routing", () => {
it("contextualizes the mapped ESG not-found error for third-party insurance", async () => { it("contextualizes the mapped ESG not-found error for third-party insurance", async () => {
const service = Object.create(RequestManagementService.prototype) as any; const service = Object.create(RequestManagementService.prototype) as any;
service.sandHubService = { service.sandHubService = {
getTejaratBlockInquiry: jest.fn().mockResolvedValue({ getCarByPlateInquiry: jest.fn().mockResolvedValue({
raw: { raw: {
success: false, success: false,
error: { error: {
@@ -102,7 +102,7 @@ describe("RequestManagementService policyholder inquiry routing", () => {
await expect(service.getThirdPartyPlateInquiry(submission)).rejects.toThrow( await expect(service.getThirdPartyPlateInquiry(submission)).rejects.toThrow(
"بیمه‌نامه شخص ثالثی مطابق پلاک و کد ملی واردشده یافت نشد.", "بیمه‌نامه شخص ثالثی مطابق پلاک و کد ملی واردشده یافت نشد.",
); );
expect(service.sandHubService.getTejaratBlockInquiry).toHaveBeenCalledTimes( expect(service.sandHubService.getCarByPlateInquiry).toHaveBeenCalledTimes(
1, 1,
); );
}); });
@@ -177,7 +177,7 @@ describe("RequestManagementService policyholder inquiry routing", () => {
}); });
service.sandHubService = { service.sandHubService = {
getCarBodyInquiry: jest.fn().mockResolvedValue({ getCarBodyInquiry: jest.fn().mockResolvedValue({
source: "ESG_CAR_BODY_VIN_INQUIRY", source: "FANAVARAN_CAR_BODY_VIN_INQUIRY",
raw: { policyId: 123 }, raw: { policyId: 123 },
mapped: { mapped: {
policyNumber: "BODY-1", policyNumber: "BODY-1",
@@ -428,7 +428,7 @@ export class RequestManagementService {
currentPlate: submission.vehicle?.currentPlate ?? submission.dto.plate, currentPlate: submission.vehicle?.currentPlate ?? submission.dto.plate,
vin: submission.vehicle?.vin, vin: submission.vehicle?.vin,
query: (plate) => query: (plate) =>
this.sandHubService.getTejaratBlockInquiry( this.sandHubService.getCarByPlateInquiry(
{ {
plate: plate as any, plate: plate as any,
nationalCodeOfInsurer: subjects.thirdPartyPolicyNationalCode, nationalCodeOfInsurer: subjects.thirdPartyPolicyNationalCode,
@@ -2302,7 +2302,7 @@ export class RequestManagementService {
* 2. Personal identity inquiry (same as the plate path) * 2. Personal identity inquiry (same as the plate path)
* *
* The inquiry result is mapped through the same `mapEsgPolicyByPlateToOldFormat` * 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. * /insurance field assignments are identical.
*/ */
async initialFormVinV2( async initialFormVinV2(
@@ -7608,7 +7608,7 @@ export class RequestManagementService {
/** /**
* VIN variant of `runInquiriesV3`. * VIN variant of `runInquiriesV3`.
* Identical flow, but calls the two-factor `getCarByChassisInquiry` instead of * Identical flow, but calls the two-factor `getCarByChassisInquiry` instead of
* `getTejaratBlockInquiry` for the primary policy lookup. * `getCarByPlateInquiry` for the primary policy lookup.
*/ */
async runInquiriesVinV3( async runInquiriesVinV3(
requestId: string, requestId: string,
@@ -7751,7 +7751,7 @@ export class RequestManagementService {
/** /**
* VIN variant of `runPartyInquiriesV3Internal`. * VIN variant of `runPartyInquiriesV3Internal`.
* Calls `getCarByChassisInquiry` (ESG two-factor chassis lookup) instead of * 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. * driving licence, car-body for CAR_BODY) are unchanged.
*/ */
private async runPartyInquiriesVinV3Internal( private async runPartyInquiriesVinV3Internal(
@@ -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", () => { it("maps the processed CAR_BODY lookup while retaining useful policy, customer, and vehicle fields", () => {
const mapped = mapEsgCarBodyPolicyToInquiry({ const mapped = mapFanavaranCarBodyPolicyToInquiry({
product: "car-body", product: "car-body",
insuranceLine: "CAR_BODY", insuranceLine: "CAR_BODY",
insuranceLineId: 4, insuranceLineId: 4,
@@ -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. * into the same mapped contract used by the existing car-body inquiry flow.
* The original response is deliberately kept separately as `raw` by the * The original response is deliberately kept separately as `raw` by the
* caller, so newly exposed provider fields are never discarded. * caller, so newly exposed provider fields are never discarded.
*/ */
export function mapEsgCarBodyPolicyToInquiry( export function mapFanavaranCarBodyPolicyToInquiry(
response: Record<string, any>, response: Record<string, any>,
sourceCompany?: { companyId: string; companyName: string },
): Record<string, unknown> { ): Record<string, unknown> {
const policy = response.policy ?? {}; const policy = response.policy ?? {};
const customer = response.customer ?? {}; const customer = response.customer ?? {};
@@ -27,9 +28,9 @@ export function mapEsgCarBodyPolicyToInquiry(
insuranceLineId: response.insuranceLineId ?? 4, insuranceLineId: response.insuranceLineId ?? 4,
// Provider responses do not currently include an insurer company identity. // Provider responses do not currently include an insurer company identity.
companyId: policy.CompanyId ?? null, companyId: policy.CompanyId ?? sourceCompany?.companyId ?? null,
CompanyCode: policy.CompanyId ?? "8", CompanyCode: policy.CompanyId ?? sourceCompany?.companyId ?? null,
CompanyName: policy.CompanyName ?? "بیمه پارسیان", CompanyName: policy.CompanyName ?? sourceCompany?.companyName ?? null,
// The lookup's customer is the policyholder/owner, not the insurer. // The lookup's customer is the policyholder/owner, not the insurer.
insurerName: null, insurerName: null,
+316
View File
@@ -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,
);
});
});
+24 -53
View File
@@ -60,6 +60,7 @@ describe("SandHubService inquiry mocks", () => {
beforeEach(() => { beforeEach(() => {
jest.clearAllMocks(); jest.clearAllMocks();
process.env.CLIENT_ID = "8"; process.env.CLIENT_ID = "8";
process.env.ESG_URL = "http://esg.example.test";
delete process.env.FANAVARAN_CLIENT; delete process.env.FANAVARAN_CLIENT;
service = new SandHubService( service = new SandHubService(
httpService as any, httpService as any,
@@ -77,7 +78,7 @@ describe("SandHubService inquiry mocks", () => {
}); });
it("keeps disabled-live third-party mock policy usable", async () => { it("keeps disabled-live third-party mock policy usable", async () => {
const result = await service.getTejaratBlockInquiry(userDetail, { const result = await service.getCarByPlateInquiry(userDetail, {
enforceDeploymentClientMatch: true, enforceDeploymentClientMatch: true,
}); });
@@ -87,7 +88,7 @@ describe("SandHubService inquiry mocks", () => {
}); });
it("returns car-body mock without HTTP when carBodyPlate is off", async () => { 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(httpService.post).not.toHaveBeenCalled();
expect(externalInquirySettings.isInquiryLive).toHaveBeenCalledWith( expect(externalInquirySettings.isInquiryLive).toHaveBeenCalledWith(
@@ -107,7 +108,7 @@ describe("SandHubService inquiry mocks", () => {
expect(result.mapped.platePartThree).toBe(498); 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"; process.env.CLIENT_ID = "8";
externalInquirySettings.isInquiryLive.mockResolvedValue(true); externalInquirySettings.isInquiryLive.mockResolvedValue(true);
lookupsService.findLastProcessedCarPolicy.mockResolvedValue({ lookupsService.findLastProcessedCarPolicy.mockResolvedValue({
@@ -140,7 +141,7 @@ describe("SandHubService inquiry mocks", () => {
plaqueSerial: "60", 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.raw.policyId).toBe(15292336);
expect(result.mapped.policyNumber).toBe("70019846985"); expect(result.mapped.policyNumber).toBe("70019846985");
expect(httpService.post).not.toHaveBeenCalled(); expect(httpService.post).not.toHaveBeenCalled();
@@ -170,7 +171,7 @@ describe("SandHubService inquiry mocks", () => {
data: { PrntCmpDocNo: "REAL-ESG-POLICY" }, data: { PrntCmpDocNo: "REAL-ESG-POLICY" },
}); });
const result = await service.getTejaratBlockInquiry(userDetail); const result = await service.getCarByPlateInquiry(userDetail);
expect(esg).toHaveBeenCalled(); expect(esg).toHaveBeenCalled();
expect(result.raw).not.toEqual({ mocked: true }); expect(result.raw).not.toEqual({ mocked: true });
@@ -185,7 +186,7 @@ describe("SandHubService inquiry mocks", () => {
data: { PrntCmpDocNo: "ESG-PLATE-POLICY" }, data: { PrntCmpDocNo: "ESG-PLATE-POLICY" },
}); });
await service.getTejaratBlockInquiry(userDetail); await service.getCarByPlateInquiry(userDetail);
expect(esg).toHaveBeenCalledWith( expect(esg).toHaveBeenCalledWith(
expect.stringMatching(/\/inquiry\/carByPlate$/), 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, enforceDeploymentClientMatch: true,
}); });
@@ -271,14 +272,14 @@ describe("SandHubService inquiry mocks", () => {
it("rejects a guilty third-party policy issued by another insurer", async () => { it("rejects a guilty third-party policy issued by another insurer", async () => {
process.env.CLIENT_ID = "15"; process.env.CLIENT_ID = "15";
externalInquirySettings.isInquiryLive.mockResolvedValue(true); externalInquirySettings.isInquiryLive.mockResolvedValue(true);
jest.spyOn(service as any, "makeTejaratRequest").mockResolvedValue({ jest.spyOn(service as any, "makeEsgRequest").mockResolvedValue({
CompanyCode: "8", CompanyCode: "8",
CompanyName: "بیمه پارسیان", CompanyName: "بیمه پارسیان",
PrntPlcyCmpDocNo: "OTHER-INSURER-POLICY", PrntPlcyCmpDocNo: "OTHER-INSURER-POLICY",
}); });
await expect( await expect(
service.getTejaratBlockInquiry(userDetail, { service.getCarByPlateInquiry(userDetail, {
enforceDeploymentClientMatch: true, enforceDeploymentClientMatch: true,
} as any), } as any),
).rejects.toBeInstanceOf(ForbiddenException); ).rejects.toBeInstanceOf(ForbiddenException);
@@ -287,12 +288,12 @@ describe("SandHubService inquiry mocks", () => {
it("allows an unchecked third-party policy from another insurer", async () => { it("allows an unchecked third-party policy from another insurer", async () => {
process.env.CLIENT_ID = "15"; process.env.CLIENT_ID = "15";
externalInquirySettings.isInquiryLive.mockResolvedValue(true); externalInquirySettings.isInquiryLive.mockResolvedValue(true);
jest.spyOn(service as any, "makeTejaratRequest").mockResolvedValue({ jest.spyOn(service as any, "makeEsgRequest").mockResolvedValue({
CompanyCode: "8", CompanyCode: "8",
CompanyName: "بیمه پارسیان", CompanyName: "بیمه پارسیان",
}); });
await expect(service.getTejaratBlockInquiry(userDetail)).resolves.toEqual( await expect(service.getCarByPlateInquiry(userDetail)).resolves.toEqual(
expect.objectContaining({ expect.objectContaining({
mapped: expect.objectContaining({ CompanyCode: "8" }), 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 () => { it("does not accept a policy when CLIENT_ID is not configured", async () => {
delete process.env.CLIENT_ID; delete process.env.CLIENT_ID;
externalInquirySettings.isInquiryLive.mockResolvedValue(true); 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( await expect(service.getCarBodyInquiry(userDetail)).rejects.toBeInstanceOf(
ServiceUnavailableException, ServiceUnavailableException,
@@ -372,10 +370,8 @@ describe("SandHubService inquiry mocks", () => {
it("rejects a CAR_BODY policy from another insurer on the Tejarat lookup route", async () => { it("rejects a CAR_BODY policy from another insurer on the Tejarat lookup route", async () => {
process.env.CLIENT_ID = "15"; process.env.CLIENT_ID = "15";
externalInquirySettings.isInquiryLive.mockResolvedValue(true); externalInquirySettings.isInquiryLive.mockResolvedValue(true);
jest.spyOn(service, "getTejaratCarBodyInquiry").mockResolvedValue({ lookupsService.findLastProcessedCarPolicy.mockResolvedValue({ policy: { CompanyId: "8" }, customer: {}, vehicle: {} });
raw: { data: { companyId: "8" } },
mapped: { companyId: "8", CompanyCode: "8" },
});
await expect(service.getCarBodyInquiry(userDetail)).rejects.toBeInstanceOf( await expect(service.getCarBodyInquiry(userDetail)).rejects.toBeInstanceOf(
ForbiddenException, ForbiddenException,
@@ -393,7 +389,7 @@ describe("SandHubService inquiry mocks", () => {
await expect(service.getCarBodyInquiry(userDetail)).resolves.toEqual( await expect(service.getCarBodyInquiry(userDetail)).resolves.toEqual(
expect.objectContaining({ expect.objectContaining({
source: "ESG_CAR_BODY_INQUIRY", source: "FANAVARAN_CAR_BODY_INQUIRY",
mapped: expect.objectContaining({ companyId: 15 }), mapped: expect.objectContaining({ companyId: 15 }),
}), }),
); );
@@ -408,9 +404,7 @@ describe("SandHubService inquiry mocks", () => {
customer: {}, customer: {},
vehicle: {}, vehicle: {},
}); });
const tejarat = jest
.spyOn(service, "getTejaratCarBodyInquiry")
.mockResolvedValue({ raw: { mocked: true }, mapped: {} });
const result = await service.getCarBodyInquiry(userDetail); const result = await service.getCarBodyInquiry(userDetail);
@@ -418,22 +412,21 @@ describe("SandHubService inquiry mocks", () => {
"car-body", "car-body",
expect.objectContaining({ nationalCode: "1234567890" }), expect.objectContaining({ nationalCode: "1234567890" }),
); );
expect(tejarat).not.toHaveBeenCalled();
expect(result.raw).not.toEqual({ mocked: true }); 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"; process.env.CLIENT_ID = "8";
const result = await service.getCarBodyInquiry(userDetail); const result = await service.getCarBodyInquiry(userDetail);
expect(lookupsService.findLastProcessedCarPolicy).not.toHaveBeenCalled(); 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(result.raw?.isSuccess).toBe(true);
expect(httpService.post).not.toHaveBeenCalled(); 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"; process.env.CLIENT_ID = "8";
externalInquirySettings.isInquiryLive.mockResolvedValue(true); externalInquirySettings.isInquiryLive.mockResolvedValue(true);
lookupsService.findLastProcessedCarPolicy.mockResolvedValue({ lookupsService.findLastProcessedCarPolicy.mockResolvedValue({
@@ -451,7 +444,7 @@ describe("SandHubService inquiry mocks", () => {
"car-body", "car-body",
{ nationalCode: "1234567890", vin: "NAAR03HFFRDE07024" }, { 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 () => { it("uses the tenant Fanavaran VIN lookup for non-Parsian car-body inquiries", async () => {
@@ -463,7 +456,6 @@ describe("SandHubService inquiry mocks", () => {
customer: {}, customer: {},
vehicle: { VIN: "NAAR03HFFRDE07024" }, vehicle: { VIN: "NAAR03HFFRDE07024" },
}); });
const tejarat = jest.spyOn(service, "getTejaratCarBodyInquiry");
const result = await service.getCarBodyInquiry({ const result = await service.getCarBodyInquiry({
nationalCodeOfInsurer: "0012345678", nationalCodeOfInsurer: "0012345678",
@@ -474,47 +466,26 @@ describe("SandHubService inquiry mocks", () => {
"car-body", "car-body",
{ nationalCode: "0012345678", vin: "NAAR03HFFRDE07024" }, { nationalCode: "0012345678", vin: "NAAR03HFFRDE07024" },
); );
expect(tejarat).not.toHaveBeenCalled(); expect(result.source).toBe("FANAVARAN_CAR_BODY_VIN_INQUIRY");
expect(result.source).toBe("TEJARAT_CAR_BODY_VIN_INQUIRY");
}); });
it("returns a VIN-shaped car-body mock without invoking a plate adapter", async () => { it("returns a VIN-shaped car-body mock without invoking a plate adapter", async () => {
process.env.CLIENT_ID = "15"; process.env.CLIENT_ID = "15";
process.env.FANAVARAN_CLIENT = "tejaratno"; process.env.FANAVARAN_CLIENT = "tejaratno";
const tejarat = jest.spyOn(service, "getTejaratCarBodyInquiry");
const result = await service.getCarBodyInquiry({ const result = await service.getCarBodyInquiry({
nationalCodeOfInsurer: "0012345678", nationalCodeOfInsurer: "0012345678",
plate: "NAAR03HFFRDE07024", plate: "NAAR03HFFRDE07024",
}); });
expect(tejarat).not.toHaveBeenCalled();
expect(lookupsService.findLastProcessedCarPolicy).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.VinNumberField).toBe("NAAR03HFFRDE07024");
expect(result.mapped.insurerNationalCode).toBe("0012345678"); 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 () => { 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(httpService.post).not.toHaveBeenCalled();
expect(result.mapped?.CompanyName).toBe("بیمه پارسیان"); expect(result.mapped?.CompanyName).toBe("بیمه پارسیان");
+125 -616
View File
@@ -25,13 +25,12 @@ import {
type InquiryErrorContext, type InquiryErrorContext,
} from "src/common/utils/inquiry-error"; } from "src/common/utils/inquiry-error";
import { resolveFanavaranClientKey } from "src/core/config/fanavaran-client.config"; import { resolveFanavaranClientKey } from "src/core/config/fanavaran-client.config";
import { jalaliToGregorianDate } from "src/helpers/date-jalali";
import { LookupsService } from "src/lookups/lookups.service"; import { LookupsService } from "src/lookups/lookups.service";
import { OfflineInquiryService } from "src/offline-inquiry/offline-inquiry.service"; import { OfflineInquiryService } from "src/offline-inquiry/offline-inquiry.service";
import { PlateNormalizerService } from "src/utils/plate-normalizer/plate-normalizer.service"; import { PlateNormalizerService } from "src/utils/plate-normalizer/plate-normalizer.service";
import { SandHubDetailDto, SandHubInquiryOptions } from "./dto/sand-hub.dto"; 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<SandHubDetailDto, "plate"> & { type CarBodyInquiryDetail = Omit<SandHubDetailDto, "plate"> & {
plate: Plates | string; plate: Plates | string;
@@ -43,12 +42,7 @@ export class SandHubService {
private readonly logger = new Logger(SandHubService.name); private readonly logger = new Logger(SandHubService.name);
private loginToken: string | null = null; private loginToken: string | null = null;
private tokenExpiry: Date | null = null; private tokenExpiry: Date | null = null;
// ESG inquiry authentication shared by all deployment tenants.
// 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)
private esgAccessToken: string | null = null; private esgAccessToken: string | null = null;
private esgTokenExpiry: Date | 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 { private inquiryContext(type: ExternalInquiryType): InquiryErrorContext {
if (type === "vinChassis") return "thirdPartyVin"; if (type === "vinChassis") return "thirdPartyVin";
return type; 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. */ /** Fixed plate/insurance inquiry payload used everywhere we mock block-inquiry style APIs. */
private buildMockPlateInquiryRaw( private buildMockPlateInquiryRaw(
ctx: MockInquiryCompanyContext, ctx: MockInquiryCompanyContext,
@@ -254,33 +216,7 @@ export class SandHubService {
}; };
} }
/** Build {@link SandHubDetailDto} from Tejarat badane / block-inquiry request bodies. */ /** Mock shape retained for compatibility with stored car-body inquiry data. */
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,
},
};
}
private buildMockCarBodyInquiryRaw( private buildMockCarBodyInquiryRaw(
userDetail: CarBodyInquiryDetail, userDetail: CarBodyInquiryDetail,
ctx: MockInquiryCompanyContext, ctx: MockInquiryCompanyContext,
@@ -334,97 +270,6 @@ export class SandHubService {
}; };
} }
private buildMockInquiryRaw(
inquiryType: ExternalInquiryType,
ctx: MockInquiryCompanyContext,
payload?: unknown,
userDetail?: SandHubDetailDto,
): Record<string, unknown> {
if (inquiryType === "carBodyPlate") {
const detail =
userDetail ??
this.tejaratPayloadToSandHubDetail(
(payload ?? {}) as Record<string, unknown>,
);
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<string, unknown>,
): 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<string, unknown>,
),
{
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<string> { private async getAccessToken(): Promise<string> {
if (this.loginToken && this.tokenExpiry && this.tokenExpiry > new Date()) { if (this.loginToken && this.tokenExpiry && this.tokenExpiry > new Date()) {
return this.loginToken; return this.loginToken;
@@ -461,66 +306,24 @@ export class SandHubService {
} }
} }
private async getTejaratAccessToken(): Promise<string> { /** Only optional licence and legal-ownership checks still use their configured hub. */
if ( private buildMockSandHubResponseForUrl(url: string): any {
this.tejaratAccessToken && if (url.includes("driver-license-check"))
this.tejaratTokenExpiry && return { data: { IsSucceed: true, Message: "mock" } };
this.tejaratTokenExpiry > new Date() if (url.includes("ownership")) return { data: { IsSuccess: true } };
) { throw new ServiceUnavailableException(
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( private esgUrl(path: string): string {
"Tejarat inquiry token is missing or expired. Fetching a new one...", const baseUrl = process.env.ESG_URL?.trim().replace(/\/+$/, "");
); if (!baseUrl) {
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(
"احراز هویت سرویس استعلام تجارت نو انجام نشد.",
); );
} }
return `${baseUrl}${path}`;
} }
private async getEsgAccessToken(): Promise<string> { private async getEsgAccessToken(): Promise<string> {
@@ -532,11 +335,10 @@ export class SandHubService {
return this.esgAccessToken; return this.esgAccessToken;
} }
const baseUrl = process.env.ESG_URL;
const username = process.env.ESG_USERNAME; const username = process.env.ESG_USERNAME;
const password = process.env.ESG_PASSWORD; const password = process.env.ESG_PASSWORD;
if (!baseUrl || !username || !password) { if (!username || !password) {
throw new UnauthorizedException( throw new UnauthorizedException(
"اطلاعات اتصال به سرویس استعلام ESG تنظیم نشده است.", "اطلاعات اتصال به سرویس استعلام ESG تنظیم نشده است.",
); );
@@ -547,7 +349,7 @@ export class SandHubService {
try { try {
const response = await firstValueFrom( const response = await firstValueFrom(
this.httpService.post( this.httpService.post(
`${baseUrl}/auth/login`, this.esgUrl("/auth/login"),
{ username, password }, { username, password },
{ {
headers: { headers: {
@@ -606,7 +408,7 @@ export class SandHubService {
Message: "mock-sheba-ok", Message: "mock-sheba-ok",
}; };
} }
return this.buildMockInquiryRaw(inquiryType, ctx, payload); return this.buildMockPlateInquiryRaw(ctx);
} }
const INITIAL_DELAY = 500; const INITIAL_DELAY = 500;
@@ -671,7 +473,7 @@ export class SandHubService {
} }
// Real ESG response wraps payload in { success: true, data: { ... } }. // 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. // in that case use raw itself so CompanyName / CompanyCode are preserved.
const data = const data =
raw?.data != null && typeof raw?.data === "object" ? raw.data : raw; 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. * 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( private normalizeJalaliBirthDateForEsg(
input: string | number | null | undefined, 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. * 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, userDetail: SandHubDetailDto,
options?: SandHubInquiryOptions, options?: SandHubInquiryOptions,
): Promise<{ ): Promise<{
@@ -879,7 +621,7 @@ export class SandHubService {
}> { }> {
const live = await this.isInquiryLive("thirdPartyPlate", options); const live = await this.isInquiryLive("thirdPartyPlate", options);
// Offline records are a fallback for disabled inquiry mode only. They must // 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) { if (!live) {
const offlineHit = await this.offlineInquiryService.findPlateInquiry({ const offlineHit = await this.offlineInquiryService.findPlateInquiry({
clientKey: resolveFanavaranClientKey(), clientKey: resolveFanavaranClientKey(),
@@ -909,8 +651,6 @@ export class SandHubService {
} }
const ctx = await this.mockCompanyContext(options); const ctx = await this.mockCompanyContext(options);
if (this.shouldUseEsgInquiryProvider()) {
const baseUrl = process.env.ESG_URL ?? "http://192.168.20.22:8085";
const requestPayload = { const requestPayload = {
nationalCode: String(userDetail.nationalCodeOfInsurer), nationalCode: String(userDetail.nationalCodeOfInsurer),
plk1: String(userDetail.plate.leftDigits), plk1: String(userDetail.plate.leftDigits),
@@ -919,10 +659,9 @@ export class SandHubService {
plksrl: String(userDetail.plate.ir), plksrl: String(userDetail.plate.ir),
}; };
const requestUrl = `${baseUrl}/inquiry/carByPlate`;
const raw = live const raw = live
? await this.makeEsgRequest( ? await this.makeEsgRequest(
requestUrl, this.esgUrl("/inquiry/carByPlate"),
requestPayload, requestPayload,
"thirdPartyPlate", "thirdPartyPlate",
options, options,
@@ -933,136 +672,67 @@ export class SandHubService {
`[MOCK] getEsgPolicyByPlateInquiry plate=${JSON.stringify(requestPayload)}`, `[MOCK] getEsgPolicyByPlateInquiry plate=${JSON.stringify(requestPayload)}`,
); );
} }
const mapped = this.mapEsgPolicyByPlateToOldFormat( const mapped = this.mapEsgPolicyByPlateToOldFormat(raw, "thirdPartyPlate");
raw,
"thirdPartyPlate",
);
if (!mapped?.Error) { if (!mapped?.Error) {
this.enforceDeploymentClientMatch(mapped, "THIRD_PARTY", options); this.enforceDeploymentClientMatch(mapped, "THIRD_PARTY", options);
} }
return { raw, mapped }; return { raw, mapped };
} }
const baseUrl = /** Car-body policies always come from the deployment's Fanavaran profile. */
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,
};
const requestUrl = `${baseUrl}/block-inquiry-tejarat`;
const raw = live
? await this.makeTejaratRequest(
requestUrl,
requestPayload,
"thirdPartyPlate",
options,
)
: this.buildMockPlateInquiryRaw(ctx);
if (!live) {
this.logger.debug(
`[MOCK] getTejaratBlockInquiry plate=${JSON.stringify(requestPayload)}`,
);
}
const mapped = isInquiryFailurePayload(raw)
? {
Error: {
Message: getInquiryErrorMessage(raw, "thirdPartyPlate"),
},
}
: this.mapNewApiResponseToOldFormat(raw);
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.
*/
async getCarBodyInquiry( async getCarBodyInquiry(
userDetail: CarBodyInquiryDetail, userDetail: CarBodyInquiryDetail,
options?: SandHubInquiryOptions, options?: SandHubInquiryOptions,
): Promise<{ ): Promise<{
source: source: "FANAVARAN_CAR_BODY_INQUIRY" | "FANAVARAN_CAR_BODY_VIN_INQUIRY";
| "ESG_CAR_BODY_INQUIRY"
| "ESG_CAR_BODY_VIN_INQUIRY"
| "TEJARAT_CAR_BODY_INQUIRY"
| "TEJARAT_CAR_BODY_VIN_INQUIRY";
raw: any; raw: any;
mapped: Record<string, unknown>; mapped: Record<string, unknown>;
}> { }> {
const useParsianCarBodyLookup = this.shouldUseParsianCarBodyLookup(); const isVinInquiry = typeof userDetail.plate === "string";
const live = await this.isInquiryLive("carBodyPlate", options); const source = isVinInquiry
const plateOrVin = userDetail.plate; ? "FANAVARAN_CAR_BODY_VIN_INQUIRY"
const isVinInquiry = typeof plateOrVin === "string"; : "FANAVARAN_CAR_BODY_INQUIRY";
if (!(await this.isInquiryLive("carBodyPlate", options))) {
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 ctx = await this.mockCompanyContext(options); const ctx = await this.mockCompanyContext(options);
const raw = this.buildMockCarBodyInquiryRaw(userDetail, ctx); const raw = this.buildMockCarBodyInquiryRaw(userDetail, ctx);
const result = { raw, mapped: this.mapCarBodyInquiryResponse(raw) }; return { source, 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,
};
} }
if (isVinInquiry) { const clientCode = String(process.env.CLIENT_ID ?? "").trim();
let raw: any; if (!clientCode) {
try { throw new ServiceUnavailableException(
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,
); );
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 = { const query = {
nationalCode: String(userDetail.nationalCodeOfInsurer), nationalCode: String(userDetail.nationalCodeOfInsurer),
plaqueLeft: String(plateOrVin.leftDigits), ...(typeof plate === "string"
plaqueLetter: String(plateOrVin.centerAlphabet), ? { vin: plate }
plaqueRight: String(plateOrVin.centerDigits), : {
plaqueSerial: String(plateOrVin.ir), plaqueLeft: String(plate.leftDigits),
plaqueLetter: String(plate.centerAlphabet),
plaqueRight: String(plate.centerDigits),
plaqueSerial: String(plate.ir),
}),
...(userDetail.accidentDate != null ...(userDetail.accidentDate != null
? { accidentDate: userDetail.accidentDate } ? { accidentDate: userDetail.accidentDate }
: {}), : {}),
@@ -1074,63 +744,23 @@ export class SandHubService {
query, query,
); );
} catch (error) { } catch (error) {
this.throwInquiryError(error, "carBodyPlate"); this.throwInquiryError(
} error,
this.assertParsianCarBodyLookupMatchesDeployment(); isVinInquiry ? "carBodyVin" : "carBodyPlate",
return {
source: "ESG_CAR_BODY_INQUIRY",
raw,
mapped: mapEsgCarBodyPolicyToInquiry(raw),
};
}
async getTejaratCarBodyInquiry(
userDetail: SandHubDetailDto,
options?: SandHubInquiryOptions,
): Promise<{
raw: any;
mapped: Record<string, unknown>;
}> {
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)}`,
); );
} }
const ctx = await this.mockCompanyContext(options);
const raw = await this.makeTejaratRequest( const mapped = mapFanavaranCarBodyPolicyToInquiry(raw, {
requestUrl, companyId: clientCode,
requestPayload, companyName: ctx.companyName,
"carBodyPlate", });
options, this.assertInsuranceMatchesDeployment(mapped, "CAR_BODY");
); return { source, raw, mapped };
if (isInquiryFailurePayload(raw)) {
throw new BadRequestException(
getInquiryErrorMessage(raw, "carBodyPlate"),
);
}
const mapped = this.mapCarBodyInquiryResponse(raw);
return { raw, mapped };
} }
/** /**
* Maps the Tejarat car-body (badane) API response to a consistent * Maps the historical car-body shape retained by disabled-mode fixtures.
* shape that mirrors the third-party inquiry mapped format. * Live inquiries use the processed Fanavaran mapper instead.
* Callers should always use `mapped` for display; `raw` is kept for audit.
*/ */
private mapCarBodyInquiryResponse(raw: any): Record<string, unknown> { private mapCarBodyInquiryResponse(raw: any): Record<string, unknown> {
if (!raw) return {}; if (!raw) return {};
@@ -1205,8 +835,6 @@ export class SandHubService {
identity: { nationalCode: string; chassisNo: string }, identity: { nationalCode: string; chassisNo: string },
options?: SandHubInquiryOptions, options?: SandHubInquiryOptions,
): Promise<{ raw: any; mapped: any }> { ): Promise<{ raw: any; mapped: any }> {
const baseUrl = process.env.ESG_URL ?? "http://192.168.20.22:8085";
const requestUrl = `${baseUrl}/inquiry/carByChassis`;
const requestPayload = { const requestPayload = {
nationalCode: String(identity.nationalCode), nationalCode: String(identity.nationalCode),
chassisNo: String(identity.chassisNo), chassisNo: String(identity.chassisNo),
@@ -1228,7 +856,7 @@ export class SandHubService {
} }
const raw = await this.makeEsgRequest( const raw = await this.makeEsgRequest(
requestUrl, this.esgUrl("/inquiry/carByChassis"),
requestPayload, requestPayload,
"vinChassis", "vinChassis",
options, options,
@@ -1240,54 +868,6 @@ export class SandHubService {
return { raw, mapped }; 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 * Maps the new SandHub API response format to the old format expected by the application
*/ */
@@ -1450,56 +1030,12 @@ export class SandHubService {
userDetail: SandHubDetailDto, userDetail: SandHubDetailDto,
options?: SandHubInquiryOptions, options?: SandHubInquiryOptions,
) { ) {
try { const { mapped } = await this.getCarByPlateInquiry(userDetail, options);
const requestPayload = { return mapped;
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");
}
} }
/** /**
* Personal identity check. * Personal identity check for every tenant: ESG expects a Jalali birth date.
* - CLIENT_ID=8 (Parsian/ESG): Jalali birth date sent as-is to `/inquiry/person`.
* - Other tenants: Tejarat/SandHub hub with Gregorian conversion.
*/ */
async getPersonalInquiry( async getPersonalInquiry(
nationalCode: string, nationalCode: string,
@@ -1507,7 +1043,6 @@ export class SandHubService {
options?: SandHubInquiryOptions, options?: SandHubInquiryOptions,
) { ) {
try { try {
if (this.shouldUseEsgInquiryProvider()) {
const jalaliBirthDate = this.normalizeJalaliBirthDateForEsg(birthDate); const jalaliBirthDate = this.normalizeJalaliBirthDateForEsg(birthDate);
if (!jalaliBirthDate) { if (!jalaliBirthDate) {
throw new BadRequestException( throw new BadRequestException(
@@ -1515,13 +1050,11 @@ export class SandHubService {
); );
} }
const baseUrl = process.env.ESG_URL ?? "http://192.168.20.22:8085";
const requestPayload = { const requestPayload = {
nationalCode: String(nationalCode), nationalCode: String(nationalCode),
birthDate: jalaliBirthDate, birthDate: jalaliBirthDate,
dateHasPostfix: 0, dateHasPostfix: 0,
}; };
const requestUrl = `${baseUrl}/inquiry/person`;
const live = await this.isInquiryLive("personalIdentity", options); const live = await this.isInquiryLive("personalIdentity", options);
if (!live) { if (!live) {
@@ -1532,52 +1065,60 @@ export class SandHubService {
} }
const raw = await this.makeEsgRequest( const raw = await this.makeEsgRequest(
requestUrl, this.esgUrl("/inquiry/person"),
requestPayload, requestPayload,
"personalIdentity", "personalIdentity",
options, options,
); );
return this.mapEsgPersonInquiryToOldFormat(raw); return this.mapEsgPersonInquiryToOldFormat(raw);
}
const requestUrl = `${process.env.SANHUB_BASE_URL}/personal-inquiry/tejarat-no`;
const gregorianBirthdate = jalaliToGregorianDate(birthDate);
if (!gregorianBirthdate) {
throw new BadRequestException(
"تاریخ تولد واردشده برای استعلام هویت معتبر نیست.",
);
}
const requestPayload = {
nationalCode,
birthdate: gregorianBirthdate,
};
const response = await this.makeSandHubRequest(
requestUrl,
requestPayload,
"personalIdentity",
options,
);
if (response?.message?.includes("err.record.not.found")) {
throw new NotFoundException(
getInquiryErrorMessage(response, "personalIdentity"),
);
}
return response.data;
} catch (err) { } catch (err) {
if ( if (err instanceof BadRequestException) {
err instanceof BadRequestException ||
err instanceof NotFoundException
) {
throw err; throw err;
} }
this.throwInquiryError(err, "personalIdentity"); 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( async getDrivingLicenseInfo(
nationalCode: string, nationalCode: string,
driverLicenseNumber: string, driverLicenseNumber: string,
@@ -1661,15 +1202,12 @@ export class SandHubService {
options?: SandHubInquiryOptions, options?: SandHubInquiryOptions,
) { ) {
try { try {
if (this.shouldUseEsgInquiryProvider()) {
const baseUrl = process.env.ESG_URL ?? "http://192.168.20.22:8085";
const requestPayload = { const requestPayload = {
accountOwnerType: "1", accountOwnerType: "1",
nationalCode: String(nationalId), nationalCode: String(nationalId),
legalId: "", legalId: "",
sheba: String(shebaId), sheba: String(shebaId),
}; };
const requestUrl = `${baseUrl}/inquiry/sheba`;
const live = await this.isInquiryLive("sheba", options); const live = await this.isInquiryLive("sheba", options);
this.logger.log( this.logger.log(
@@ -1688,7 +1226,7 @@ export class SandHubService {
} }
const raw = await this.makeEsgRequest( const raw = await this.makeEsgRequest(
requestUrl, this.esgUrl("/inquiry/sheba"),
requestPayload, requestPayload,
"sheba", "sheba",
options, options,
@@ -1705,34 +1243,6 @@ export class SandHubService {
); );
} }
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,
requestPayload,
"sheba",
options,
);
if (response?.ReturnValue === false || response?.HasError === true) {
this.logger.warn(
`Sheba validation failed for national code ${nationalId}. Response:`,
response,
);
throw new BadRequestException(
"شماره شبا متعلق به کد ملی واردشده نیست.",
);
}
return response; return response;
} catch (err) { } catch (err) {
if (err instanceof BadRequestException) { if (err instanceof BadRequestException) {
@@ -1741,7 +1251,6 @@ export class SandHubService {
this.throwInquiryError(err, "sheba"); this.throwInquiryError(err, "sheba");
} }
} }
private handleSandHubError( private handleSandHubError(
err: any, err: any,
attempt: number, attempt: number,