1
0
forked from Yara724/api

YARA-1035

This commit is contained in:
SepehrYahyaee
2026-06-20 14:51:01 +03:30
parent 2e4b10455b
commit 4fabed77e5
27 changed files with 1329 additions and 74 deletions

View File

@@ -1,7 +1,18 @@
import { ApiProperty } from "@nestjs/swagger";
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { PlatesDto } from "src/plates/dto/plate.dto";
import { Plates } from "src/Types&Enums/plate.interface";
/** Optional insurer scope for per-client inquiry toggles and mock company fields. */
export class SandHubInquiryOptionsDto {
@ApiPropertyOptional({
description:
"Insurer client Mongo ObjectId. When omitted, resolves from deployment CLIENT_ID env.",
})
clientId?: string;
}
export type SandHubInquiryOptions = SandHubInquiryOptionsDto;
export class SandHubLoginDtoRs {
public loginToken: string;
constructor(token: string) {

View File

@@ -1,6 +1,7 @@
import { HttpModule } from "@nestjs/axios";
import { Module } from "@nestjs/common";
import { HttpModule } from "@nestjs/axios";
import { MongooseModule } from "@nestjs/mongoose";
import { ClientModule } from "src/client/client.module";
import { SystemSettingsModule } from "src/system-settings/system-settings.module";
import { SandHubDbService } from "src/sand-hub/entity/db-service/sand-hub.db.service";
import { SandHubModel, SandHubSchema } from "./entity/schema/sand-hub.schema";
@@ -10,6 +11,7 @@ import { SandHubService } from "./sand-hub.service";
imports: [
HttpModule,
SystemSettingsModule,
ClientModule,
MongooseModule.forFeature([
{ name: SandHubModel.name, schema: SandHubSchema },
]),

View File

@@ -11,8 +11,10 @@ import {
} from "@nestjs/common";
import { SandHubDbService } from "src/sand-hub/entity/db-service/sand-hub.db.service";
import { SandHubModel } from "src/sand-hub/entity/schema/sand-hub.schema";
import { SystemSettingsService } from "src/system-settings/system-settings.service";
import { SandHubDetailDto } from "./dto/sand-hub.dto";
import { ExternalInquirySettingsService } from "src/client/external-inquiry-settings.service";
import type { ExternalInquiryType } from "src/common/types/external-inquiry.types";
import type { MockInquiryCompanyContext } from "src/common/types/external-inquiry.types";
import { SandHubDetailDto, SandHubInquiryOptions } from "./dto/sand-hub.dto";
import { jalaliToGregorianDate } from "src/helpers/date-jalali";
import { firstValueFrom } from "rxjs";
@@ -33,32 +35,39 @@ export class SandHubService {
constructor(
private readonly httpService: HttpService,
private readonly sandHubDbService: SandHubDbService,
private readonly systemSettingsService: SystemSettingsService,
private readonly externalInquirySettings: ExternalInquirySettingsService,
) {}
/**
* When false, no outbound HTTP to SandHub/Tejarat — inquiries use permissive mocks.
* Controlled by `system_settings.externalApis.sandHubUseLiveApi` (PATCH /system-settings).
*/
private async useLiveSandHubApis(): Promise<boolean> {
return this.systemSettingsService.isSandHubLiveEnabled();
private clientRefFrom(options?: SandHubInquiryOptions): string | undefined {
return options?.clientId;
}
/** Tenant-specific company fields for mocked external inquiries (MOCK_INQUIRY_COMPANY_*). */
private getMockInquiryCompanyId(): string {
return process.env.CLIENT_ID ?? "15";
private async isInquiryLive(
type: ExternalInquiryType,
options?: SandHubInquiryOptions,
): Promise<boolean> {
return this.externalInquirySettings.isInquiryLive(
type,
this.clientRefFrom(options),
);
}
private async mockCompanyContext(
options?: SandHubInquiryOptions,
): Promise<MockInquiryCompanyContext> {
return this.externalInquirySettings.getMockCompanyContext(
this.clientRefFrom(options),
);
}
private shouldUseEsgInquiryProvider(): boolean {
return String(process.env.CLIENT_ID ?? "") === "8";
}
private getMockInquiryCompanyName(): string {
return process.env.CLIENT_NAME ?? "بیمه سامان";
}
/** Fixed plate/insurance inquiry payload used everywhere we mock block-inquiry style APIs. */
private getDefaultMockPlateInquiryRaw(): Record<string, unknown> {
private buildMockPlateInquiryRaw(
ctx: MockInquiryCompanyContext,
): Record<string, unknown> {
return {
PrntPlcyCmpDocNo: "1404/1143-70591/200/123",
MapTypNam: "فائو ( FAW )",
@@ -107,8 +116,8 @@ export class SandHubService {
InstallDateField: "1403/03/01",
AxelNumberField: "2",
WheelNumberField: "4",
CompanyName: process.env.CLIENT_NAME ?? "بیمه سامان",
CompanyCode: `${process.env.CLIENT_ID ?? 15}`,
CompanyName: ctx.companyName,
CompanyCode: ctx.companyId,
IssueDate: "1403/04/06",
SatrtDate: "1403/04/06",
EndDate: "1404/04/06",
@@ -133,17 +142,18 @@ export class SandHubService {
};
}
private getDefaultMockCarBodyInquiryRaw(
private buildMockCarBodyInquiryRaw(
userDetail: SandHubDetailDto,
ctx: MockInquiryCompanyContext,
): Record<string, unknown> {
const companyId = Number(this.getMockInquiryCompanyId());
const companyId = Number(ctx.companyId);
return {
data: {
id: 70016075946,
printNumber: "1405/1143-70591/220/1/0",
companyId: Number.isNaN(companyId) ? 15 : companyId,
companyName: this.getMockInquiryCompanyName(),
companyName: ctx.companyName,
beginDate: "1405/01/17",
endDate: "1406/01/17",
issueDate: "1405/01/16",
@@ -177,7 +187,11 @@ export class SandHubService {
/**
* Bodies returned from `makeSandHubRequest` in mock mode (same shape callers expect from real API).
*/
private buildMockSandHubResponseForUrl(url: string, payload?: unknown): any {
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;
@@ -217,7 +231,10 @@ export class SandHubService {
}
if (u.includes("block-inquiry") || u.includes("tejarat")) {
return this.mapNewApiResponseToOldFormat(
this.getDefaultMockPlateInquiryRaw(),
plateMock ?? this.buildMockPlateInquiryRaw({
companyId: process.env.CLIENT_ID ?? "15",
companyName: process.env.CLIENT_NAME ?? "بیمه سامان",
}),
);
}
this.logger.warn(
@@ -227,9 +244,6 @@ export class SandHubService {
}
private async getAccessToken(): Promise<string> {
if (!(await this.useLiveSandHubApis())) {
return "mock-sandhub-access-token";
}
if (this.loginToken && this.tokenExpiry && this.tokenExpiry > new Date()) {
return this.loginToken;
}
@@ -266,9 +280,6 @@ export class SandHubService {
}
private async getTejaratAccessToken(): Promise<string> {
if (!(await this.useLiveSandHubApis())) {
return "mock-tejarat-access-token";
}
if (
this.tejaratAccessToken &&
this.tejaratTokenExpiry &&
@@ -329,9 +340,6 @@ export class SandHubService {
}
private async getEsgAccessToken(): Promise<string> {
if (!(await this.useLiveSandHubApis())) {
return "mock-esg-access-token";
}
if (this.esgAccessToken && this.esgTokenExpiry && this.esgTokenExpiry > new Date()) {
return this.esgAccessToken;
}
@@ -384,10 +392,34 @@ export class SandHubService {
}
}
private async makeEsgRequest(url: string, payload: any, maxRetries = 2) {
if (!(await this.useLiveSandHubApis())) {
this.logger.log(`[MOCK] ESG POST skipped: ${url}`);
return this.getDefaultMockPlateInquiryRaw();
private async makeEsgRequest(
url: string,
payload: any,
inquiryType: ExternalInquiryType,
options?: SandHubInquiryOptions,
maxRetries = 2,
) {
if (!(await this.isInquiryLive(inquiryType, options))) {
this.logger.log(`[MOCK] ESG POST skipped (${inquiryType}): ${url}`);
const ctx = await this.mockCompanyContext(options);
if (inquiryType === "thirdPartyPlate") {
return this.buildMockPlateInquiryRaw(ctx);
}
if (inquiryType === "personalIdentity") {
const nin =
typeof payload?.nationalCode === "string"
? payload.nationalCode
: "-";
return this.getDefaultMockPersonInquiry(nin);
}
if (inquiryType === "sheba") {
return {
ReturnValue: true,
HasError: false,
Message: "mock-sheba-ok",
};
}
return this.buildMockPlateInquiryRaw(ctx);
}
const INITIAL_DELAY = 500;
@@ -571,10 +603,17 @@ export class SandHubService {
};
}
private async makeTejaratRequest(url: string, payload: any, maxRetries = 2) {
if (!(await this.useLiveSandHubApis())) {
this.logger.log(`[MOCK] Tejarat POST skipped: ${url}`);
return this.getDefaultMockPlateInquiryRaw();
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.buildMockPlateInquiryRaw(ctx);
}
const INITIAL_DELAY = 500;
const BACKOFF_FACTOR = 2;
@@ -624,10 +663,14 @@ export class SandHubService {
* Tejarat block inquiry (replaces SandHub call for V2 flows).
* Returns both raw + mapped (old-format) response.
*/
async getTejaratBlockInquiry(userDetail: SandHubDetailDto): Promise<{
async getTejaratBlockInquiry(
userDetail: SandHubDetailDto,
options?: SandHubInquiryOptions,
): Promise<{
raw: any;
mapped: any;
}> {
const ctx = await this.mockCompanyContext(options);
if (this.shouldUseEsgInquiryProvider()) {
const baseUrl = process.env.ESG_URL ?? "http://192.168.20.22:8085";
const requestPayload = {
@@ -639,10 +682,15 @@ export class SandHubService {
};
const requestUrl = `${baseUrl}/inquiry/policyByPlate`;
const live = await this.useLiveSandHubApis();
const live = await this.isInquiryLive("thirdPartyPlate", options);
const raw = live
? await this.makeEsgRequest(requestUrl, requestPayload)
: this.getDefaultMockPlateInquiryRaw();
? await this.makeEsgRequest(
requestUrl,
requestPayload,
"thirdPartyPlate",
options,
)
: this.buildMockPlateInquiryRaw(ctx);
if (!live) {
this.logger.debug(
`[MOCK] getEsgPolicyByPlateInquiry plate=${JSON.stringify(requestPayload)}`,
@@ -663,10 +711,15 @@ export class SandHubService {
};
const requestUrl = `${baseUrl}/block-inquiry-tejarat`;
const live = await this.useLiveSandHubApis();
const live = await this.isInquiryLive("thirdPartyPlate", options);
const raw = live
? await this.makeTejaratRequest(requestUrl, requestPayload)
: this.getDefaultMockPlateInquiryRaw();
? await this.makeTejaratRequest(
requestUrl,
requestPayload,
"thirdPartyPlate",
options,
)
: this.buildMockPlateInquiryRaw(ctx);
if (!live) {
this.logger.debug(
`[MOCK] getTejaratBlockInquiry plate=${JSON.stringify(requestPayload)}`,
@@ -680,7 +733,10 @@ export class SandHubService {
return await this.sandHubDbService.findOneBySandHubId(sandHubId);
}
async getTejaratCarBodyInquiry(userDetail: SandHubDetailDto): Promise<{
async getTejaratCarBodyInquiry(
userDetail: SandHubDetailDto,
options?: SandHubInquiryOptions,
): Promise<{
raw: any;
mapped: Record<string, unknown>;
}> {
@@ -696,7 +752,8 @@ export class SandHubService {
};
const requestUrl = `${baseUrl}/block-inquiry-tejarat/badane`;
const live = await this.useLiveSandHubApis();
const live = await this.isInquiryLive("carBodyPlate", options);
const ctx = await this.mockCompanyContext(options);
let raw: any;
@@ -722,11 +779,10 @@ export class SandHubService {
throw error;
}
} else {
// Mock — reuse the default mock and adapt it to the car-body shape
this.logger.debug(
`[MOCK] getTejaratCarBodyInquiry plate=${JSON.stringify(requestPayload)}`,
);
raw = this.getDefaultMockCarBodyInquiryRaw(userDetail);
raw = this.buildMockCarBodyInquiryRaw(userDetail, ctx);
}
const mapped = this.mapCarBodyInquiryResponse(raw);
@@ -797,10 +853,21 @@ export class SandHubService {
};
}
private async makeSandHubRequest(url: string, payload: any, maxRetries = 3) {
if (!(await this.useLiveSandHubApis())) {
this.logger.log(`[MOCK] SandHub POST skipped: ${url}`);
return this.buildMockSandHubResponseForUrl(url, payload);
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);
const plateMock =
inquiryType === "thirdPartyPlate" || inquiryType === "carBodyPlate"
? this.buildMockPlateInquiryRaw(ctx)
: undefined;
return this.buildMockSandHubResponseForUrl(url, payload, plateMock);
}
const token = await this.getAccessToken();
const INITIAL_DELAY = 1000;
@@ -909,7 +976,10 @@ export class SandHubService {
};
}
async getSandHubResponse(userDetail: SandHubDetailDto) {
async getSandHubResponse(
userDetail: SandHubDetailDto,
options?: SandHubInquiryOptions,
) {
try {
const requestPayload = {
leftTwoDigits: String(userDetail.plate.leftDigits),
@@ -922,13 +992,19 @@ export class SandHubService {
const requestUrl = `${base}/block-inquiry-tejarat`;
let response: any;
if (await this.useLiveSandHubApis()) {
response = await this.makeSandHubRequest(requestUrl, requestPayload);
if (await this.isInquiryLive("thirdPartyPlate", options)) {
response = await this.makeSandHubRequest(
requestUrl,
requestPayload,
"thirdPartyPlate",
options,
);
} else {
this.logger.debug(
`[MOCK] getSandHubResponse plate=${JSON.stringify(requestPayload)}`,
);
response = this.getDefaultMockPlateInquiryRaw();
const ctx = await this.mockCompanyContext(options);
response = this.buildMockPlateInquiryRaw(ctx);
}
const result = this.mapNewApiResponseToOldFormat(response);
@@ -948,7 +1024,11 @@ export class SandHubService {
* - CLIENT_ID=8 (Parsian/ESG): Jalali birth date sent as-is to `/inquiry/person`.
* - Other tenants: Tejarat/SandHub hub with Gregorian conversion.
*/
async getPersonalInquiry(nationalCode: string, birthDate: number | string) {
async getPersonalInquiry(
nationalCode: string,
birthDate: number | string,
options?: SandHubInquiryOptions,
) {
try {
if (this.shouldUseEsgInquiryProvider()) {
const jalaliBirthDate = this.normalizeJalaliBirthDateForEsg(birthDate);
@@ -965,7 +1045,7 @@ export class SandHubService {
dateHasPostfix: 0,
};
const requestUrl = `${baseUrl}/inquiry/person`;
const live = await this.useLiveSandHubApis();
const live = await this.isInquiryLive("personalIdentity", options);
if (!live) {
this.logger.debug(
@@ -974,7 +1054,12 @@ export class SandHubService {
return this.getDefaultMockPersonInquiry(String(nationalCode));
}
const raw = await this.makeEsgRequest(requestUrl, requestPayload);
const raw = await this.makeEsgRequest(
requestUrl,
requestPayload,
"personalIdentity",
options,
);
return this.mapEsgPersonInquiryToOldFormat(raw);
}
@@ -995,6 +1080,8 @@ export class SandHubService {
const response = await this.makeSandHubRequest(
requestUrl,
requestPayload,
"personalIdentity",
options,
);
if (response?.message?.includes("err.record.not.found")) {
@@ -1017,6 +1104,7 @@ export class SandHubService {
async getDrivingLicenseInfo(
nationalCode: string,
driverLicenseNumber: string,
options?: SandHubInquiryOptions,
) {
const requestUrl = `${process.env.SANHUB_BASE_URL}/driver-license-check`;
const requestPayload = {
@@ -1032,6 +1120,8 @@ export class SandHubService {
const response = await this.makeSandHubRequest(
requestUrl,
requestPayload,
"drivingLicense",
options,
);
if (response?.data?.IsSucceed === false) {
@@ -1055,7 +1145,11 @@ export class SandHubService {
}
}
async getCarOwnershipInfo(plate: any, nationalCode: string) {
async getCarOwnershipInfo(
plate: any,
nationalCode: string,
options?: SandHubInquiryOptions,
) {
try {
const requestUrl = `${process.env.SANHUB_BASE_URL}/ownership`;
const requestPayload = {
@@ -1072,6 +1166,8 @@ export class SandHubService {
const response = await this.makeSandHubRequest(
requestUrl,
requestPayload,
"carOwnership",
options,
);
// Check the 'IsSuccess' field in the nested 'data' object.
@@ -1091,7 +1187,11 @@ export class SandHubService {
}
}
async getShebaValidation(nationalId: string, shebaId: string) {
async getShebaValidation(
nationalId: string,
shebaId: string,
options?: SandHubInquiryOptions,
) {
try {
if (this.shouldUseEsgInquiryProvider()) {
const baseUrl = process.env.ESG_URL ?? "http://192.168.20.22:8085";
@@ -1102,7 +1202,7 @@ export class SandHubService {
sheba: String(shebaId),
};
const requestUrl = `${baseUrl}/inquiry/sheba`;
const live = await this.useLiveSandHubApis();
const live = await this.isInquiryLive("sheba", options);
this.logger.log(
`Validating Sheba ID via ESG for national code: ${nationalId}`,
@@ -1119,7 +1219,12 @@ export class SandHubService {
};
}
const raw = await this.makeEsgRequest(requestUrl, requestPayload);
const raw = await this.makeEsgRequest(
requestUrl,
requestPayload,
"sheba",
options,
);
const response = this.mapEsgShebaInquiryToOldFormat(raw);
if (response?.ReturnValue === false || response?.HasError === true) {
@@ -1146,6 +1251,8 @@ export class SandHubService {
const response = await this.makeSandHubRequest(
requestUrl,
requestPayload,
"sheba",
options,
);
if (response?.ReturnValue === false || response?.HasError === true) {