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
# ---------------------------------------------
# 🧩 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 =
+1
View File
@@ -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).
+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
```
## 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
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://<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
@@ -417,7 +357,7 @@ curl -X POST "$ESG_URL/auth/login" \
ESG_ACCESS_TOKEN="<response accessToken>"
```
### 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://<optional-check-provider>'
SANHUB_URL_LOGIN='https://<optional-check-provider>/<login-path>'
SANHUB_USERNAME='<optional-check-username>'
SANHUB_PASSWORD='<optional-check-password>'
```
### Sequence
@@ -515,37 +458,6 @@ curl -X POST "$SANHUB_URL_LOGIN" \
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
```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`.
+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: {
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" },
},
},
@@ -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';
}
@@ -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",
@@ -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,
@@ -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",
@@ -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(
@@ -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,
@@ -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<string, any>,
sourceCompany?: { companyId: string; companyName: string },
): Record<string, unknown> {
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,
+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(() => {
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("بیمه پارسیان");
File diff suppressed because it is too large Load Diff