feat: add car inquiries with resilience, ownership privacy, and retry visibility

Introduce plate, chassis, and third-party car endpoints, a wall-clock inquiry
deadline with transport-only retries, and ownership-safe no-match errors so
another person's identity never leaks.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-09-05 17:21:16 +03:30
co-authored by Cursor
parent b4be98b156
commit 61098f1bf4
40 changed files with 2595 additions and 374 deletions
@@ -12,6 +12,12 @@ import {
AppErrorCode,
buildNormalizedError,
} from '../../common/constants/error-messages';
import {
AUTH_MAX_ATTEMPTS,
AUTH_RETRY_DELAY_MS,
isAuthTransportRetryable,
} from '../../common/helpers/provider-resilience.helper';
import { withRetry } from '../../common/helpers/retry.helper';
import { AmitisAuthServiceConfig } from '../../config/configuration';
import { GeneralTokenDocument } from '../schemas/general-token.schema';
import { GeneralTokenService } from '../services/general-token.service';
@@ -124,14 +130,16 @@ export class AmitisProvider {
`AMITIS login → POST ${loginUrl} | provider=${providerName} | inquiry=${inquiryType} | username=${username.toLowerCase()}`,
);
const response = await this.httpClient.post<CentInsurTokenResponse>(
this.config.loginPath,
loginBody.toString(),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
const response = await this.withGentleAuthRetry(() =>
this.httpClient.post<CentInsurTokenResponse>(
this.config.loginPath,
loginBody.toString(),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
},
},
),
);
if (isOutboundHttpDebugEnabled()) {
@@ -142,7 +150,7 @@ export class AmitisProvider {
const token = this.extractToken(response.data);
await this.saveToken(token, providerName, inquiryType, username, password, 'login');
await this.saveToken(token, providerName, inquiryType, username, 'login');
return token.accessToken;
} catch (error) {
throw this.toAuthError(`AMITIS login failed for ${providerName}/${inquiryType}`, error);
@@ -155,10 +163,12 @@ export class AmitisProvider {
inquiryType: InquiryType,
): Promise<string> {
try {
const response = await this.httpClient.post<CentInsurTokenResponse>(this.config.refreshPath, {
Token: latestToken.accessToken,
RefreshToken: latestToken.refreshToken,
});
const response = await this.withGentleAuthRetry(() =>
this.httpClient.post<CentInsurTokenResponse>(this.config.refreshPath, {
Token: latestToken.accessToken,
RefreshToken: latestToken.refreshToken,
}),
);
const token = this.extractToken(response.data, latestToken.refreshToken);
await this.saveToken(
@@ -166,7 +176,6 @@ export class AmitisProvider {
providerName,
inquiryType,
latestToken.username,
latestToken.clientSecret,
'refresh',
);
return token.accessToken;
@@ -178,20 +187,27 @@ export class AmitisProvider {
}
}
/** One gentle retry on timeout/network only — never on 401/403/429/auth rejects. */
private async withGentleAuthRetry<T>(fn: () => Promise<T>): Promise<T> {
return withRetry(fn, {
maxAttempts: AUTH_MAX_ATTEMPTS,
delayMs: AUTH_RETRY_DELAY_MS,
shouldRetry: isAuthTransportRetryable,
});
}
private async saveToken(
token: AmitisAuthToken,
providerName: ProviderName,
inquiryType: InquiryType,
username: string,
password: string,
scope: string,
): Promise<void> {
await this.generalTokenService.create({
await this.generalTokenService.persistToken({
serviceProvider: this.getTokenKey(providerName, inquiryType),
tokenType: token.tokenType,
url: this.config.baseUrl,
clientId: username.toLowerCase(),
clientSecret: password,
username: username.toLowerCase(),
scope,
accessToken: token.accessToken,
@@ -21,6 +21,11 @@ import { ProviderName } from '../../common/enums/provider-name.enum';
import { ProviderEnvConfig } from '../../config/configuration';
import { ProviderExecutionContext } from '../../common/interfaces/inquiry-provider.interface';
import { AmitisProvider } from './amitis.provider';
import {
CentInsurCarProviderSupport,
CarChassisPayload,
CarPlatePayload,
} from '../shared/centinsur-car-provider.support';
import {
LegacyApiProvider,
LegacyInquiryPayload,
@@ -68,11 +73,18 @@ export class MoallemProvider extends LegacyApiProvider {
InquiryType.SHAHKAR,
InquiryType.POSTAL_CODE,
InquiryType.REAL_ESTATE,
InquiryType.CAR_BY_PLATE,
InquiryType.CAR_BY_CHASSIS,
InquiryType.THIRD_PARTY_CAR,
];
private readonly moallemConfig: ProviderEnvConfig;
constructor(configService: ConfigService, private readonly amitisProvider: AmitisProvider) {
constructor(
configService: ConfigService,
private readonly amitisProvider: AmitisProvider,
private readonly centInsurCarSupport: CentInsurCarProviderSupport,
) {
const config = configService.get<ProviderEnvConfig>('moallem')!;
super(
config,
@@ -103,6 +115,33 @@ export class MoallemProvider extends LegacyApiProvider {
return this.inquireSayah(payload as SayahPayload);
}
if (inquiryType === InquiryType.CAR_BY_PLATE) {
return this.centInsurCarSupport.inquireCarByPlate(
this.moallemConfig,
payload as CarPlatePayload,
(message, code, fallback, extras) =>
this.formatProviderError(message, code, fallback, extras as never),
);
}
if (inquiryType === InquiryType.CAR_BY_CHASSIS) {
return this.centInsurCarSupport.inquireCarByChassis(
this.moallemConfig,
payload as CarChassisPayload,
(message, code, fallback, extras) =>
this.formatProviderError(message, code, fallback, extras as never),
);
}
if (inquiryType === InquiryType.THIRD_PARTY_CAR) {
return this.centInsurCarSupport.inquireThirdPartyCar(
this.moallemConfig,
payload as CarPlatePayload,
(message, code, fallback, extras) =>
this.formatProviderError(message, code, fallback, extras as never),
);
}
return super.callProvider(inquiryType, payload, context);
}
@@ -12,12 +12,18 @@ import {
parseFirstCarPolicy,
} from '../../common/helpers/soap-car-policy.helper';
import { getSayahProviderError, SayahApiResponse } from '../../common/helpers/sayah-response.helper';
import { assertCarPolicyOwnedBy } from '../../common/helpers/car-inquiry-safety.helper';
import { InquiryType } from '../../common/enums/inquiry-type.enum';
import { ProviderName } from '../../common/enums/provider-name.enum';
import { ProviderExecutionContext } from '../../common/interfaces/inquiry-provider.interface';
import { ProviderEnvConfig } from '../../config/configuration';
import { BaseProvider } from '../base/base-provider.abstract';
import { AmitisProvider } from './amitis.provider';
import {
CentInsurCarProviderSupport,
CarChassisPayload,
CarPlatePayload,
} from '../shared/centinsur-car-provider.support';
import {
LegacyInquiryPayload,
LegacyInquiryResult,
@@ -95,6 +101,9 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
InquiryType.PERSON,
InquiryType.SHAHKAR,
InquiryType.SHEBA,
InquiryType.CAR_BY_PLATE,
InquiryType.CAR_BY_CHASSIS,
InquiryType.THIRD_PARTY_CAR,
InquiryType.POLICY_BY_CHASSIS,
InquiryType.POLICY_BY_PLATE,
InquiryType.POLICY_BY_NATIONAL_CODE,
@@ -103,6 +112,7 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
constructor(
configService: ConfigService,
private readonly amitisProvider: AmitisProvider,
private readonly centInsurCarSupport: CentInsurCarProviderSupport,
) {
super(configService.get<ProviderEnvConfig>('parsian')!);
}
@@ -125,7 +135,9 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
Boolean(shebaConfig?.password)) ||
this.hasSoapCredentials(policyByChassisConfig) ||
this.hasSoapCredentials(policyByPlateConfig) ||
this.hasSoapCredentials(policyByNationalCodeConfig))
this.hasSoapCredentials(policyByNationalCodeConfig) ||
this.centInsurCarSupport.hasCarPolicyConfig(this.config, InquiryType.CAR_BY_PLATE) ||
this.centInsurCarSupport.hasCarPolicyConfig(this.config, InquiryType.THIRD_PARTY_CAR))
);
}
@@ -146,6 +158,33 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
return this.inquireSayah(payload as ParsianSayahPayload);
}
if (inquiryType === InquiryType.CAR_BY_PLATE) {
return this.centInsurCarSupport.inquireCarByPlate(
this.config,
payload as CarPlatePayload,
(message, code, fallback, extras) =>
this.formatProviderError(message, code, fallback, extras as never),
);
}
if (inquiryType === InquiryType.CAR_BY_CHASSIS) {
return this.centInsurCarSupport.inquireCarByChassis(
this.config,
payload as CarChassisPayload,
(message, code, fallback, extras) =>
this.formatProviderError(message, code, fallback, extras as never),
);
}
if (inquiryType === InquiryType.THIRD_PARTY_CAR) {
return this.centInsurCarSupport.inquireThirdPartyCar(
this.config,
payload as CarPlatePayload,
(message, code, fallback, extras) =>
this.formatProviderError(message, code, fallback, extras as never),
);
}
if (inquiryType === InquiryType.POLICY_BY_CHASSIS) {
return this.inquirePolicyByChassis(payload as ParsianPolicyByChassisPayload);
}
@@ -346,20 +385,9 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
{ Plk1: plk1, Plk2: plk2, Plk3: plk3, PlkSrl: plksrl },
);
const policyNationalId = policy.NtnlId?.trim() ?? '';
if (!policyNationalId || !this.nationalIdsMatch(nationalCode, policyNationalId)) {
throw this.formatProviderError(
'عدم تطابق اطلاعات',
'INQUIRY_NO_MATCH',
undefined,
{
conflict: {
nationalCode,
NtnlId: policyNationalId,
},
},
);
}
assertCarPolicyOwnedBy(nationalCode, policy, (message, code, fallback, extras) =>
this.formatProviderError(message, code, fallback, extras as never),
);
return {
raw: {
@@ -373,10 +401,6 @@ export class ParsianProvider extends BaseProvider<LegacyInquiryPayload, LegacyIn
};
}
private nationalIdsMatch(requested: string, fromPolicy: string): boolean {
return requested.trim().padStart(10, '0') === fromPolicy.trim().padStart(10, '0');
}
private async callCarPolicySoap(
inquiryType: InquiryType,
methodName: string,
@@ -1,19 +1,38 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios, { AxiosError, AxiosInstance } from 'axios';
import { createOutboundAxiosInstance, mergeOutboundAxiosConfig } from '../../common/helpers/http-client.helper';
import { AxiosError, AxiosInstance } from 'axios';
import { createOutboundAxiosInstance } from '../../common/helpers/http-client.helper';
import {
CentInsurApiResponse,
getCentInsurProviderError,
} from '../../common/helpers/centinsur-response.helper';
import { InquiryType } from '../../common/enums/inquiry-type.enum';
import { ProviderName } from '../../common/enums/provider-name.enum';
import { jalaliDateToGregorianDate } from '../../common/helpers/jalali-date.helper';
import { InquiryProvider, ProviderExecutionContext } from '../../common/interfaces/inquiry-provider.interface';
import { resolveProviderPublicMessage } from '../../common/constants/error-messages';
import {
PROVIDER_DEFAULT_MAX_ATTEMPTS,
runWithProviderResilience,
} from '../../common/helpers/provider-resilience.helper';
import {
InquiryProvider,
ProviderExecutionContext,
} from '../../common/interfaces/inquiry-provider.interface';
import { TejaratNouConfig } from '../interfaces/tejaratnou-config.interface';
import { GeneralTokenService } from '../services/general-token.service';
import { CachedInquiryResultService } from '../services/cached-inquiry-result.service';
import { PersonInquiryPayload, PersonInquiryResult } from '../shared/legacy-api.provider.abstract';
import {
InquiryResultCacheService,
PersonInquiryCacheData,
} from '../services/inquiry-result-cache.service';
import {
LegacyInquiryPayload,
LegacyInquiryResult,
PersonInquiryPayload,
PersonInquiryResult,
} from '../shared/legacy-api.provider.abstract';
interface TejaratNouPersonInquiryResponse {
data?: TejaratNouPersonInquiryData;
interface TejaratNouGatewayResponse<T = unknown> {
data?: T;
isSuccess?: boolean;
statusCode?: number;
message?: string;
@@ -39,10 +58,23 @@ interface TejaratNouPersonInquiryData {
message?: unknown;
}
/**
* Tejarat No gateway provider.
*
* OAuth token (accounts host) + REST calls on inquiry gateway host.
*/
@Injectable()
export class TejaratNouProvider implements InquiryProvider<PersonInquiryPayload, PersonInquiryResult> {
export class TejaratNouProvider implements InquiryProvider<LegacyInquiryPayload, LegacyInquiryResult> {
readonly name = ProviderName.TEJARATNOU;
readonly supportedInquiryTypes = [InquiryType.PERSON];
readonly supportedInquiryTypes = [
InquiryType.PERSON,
InquiryType.SHAHKAR,
InquiryType.REAL_ESTATE,
InquiryType.CAR_BY_PLATE,
InquiryType.CAR_BY_CHASSIS,
InquiryType.THIRD_PARTY_CAR,
];
private readonly logger = new Logger(TejaratNouProvider.name);
private readonly httpClient: AxiosInstance;
private readonly config: TejaratNouConfig;
@@ -50,162 +82,509 @@ export class TejaratNouProvider implements InquiryProvider<PersonInquiryPayload,
constructor(
private readonly configService: ConfigService,
private readonly generalTokenService: GeneralTokenService,
private readonly cachedInquiryResultService: CachedInquiryResultService,
private readonly inquiryResultCacheService: InquiryResultCacheService,
) {
this.config = this.configService.get<TejaratNouConfig>('tejaratnou')!;
this.httpClient = createOutboundAxiosInstance({
baseURL: this.config.inquiryBaseUrl,
timeout: this.config.timeout,
headers: {
'Content-Type': 'application/json',
},
headers: { 'Content-Type': 'application/json' },
});
}
isEnabled(): boolean {
return this.config.enabled && Boolean(this.config.baseUrl) && Boolean(this.config.inquiryBaseUrl);
return (
this.config.enabled &&
Boolean(this.config.baseUrl) &&
Boolean(this.config.inquiryBaseUrl) &&
Boolean(this.config.clientSecret) &&
Boolean(this.config.username) &&
Boolean(this.config.password)
);
}
async execute(
inquiryType: InquiryType,
payload: PersonInquiryPayload,
payload: LegacyInquiryPayload,
context: ProviderExecutionContext,
): Promise<PersonInquiryResult> {
if (inquiryType !== InquiryType.PERSON) {
throw new Error(`Unsupported inquiry type: ${inquiryType}`);
): Promise<LegacyInquiryResult> {
switch (inquiryType) {
case InquiryType.PERSON:
return this.inquirePerson(
{
nationalCode: this.getRequiredString(payload.nationalCode, 'nationalCode'),
birthDate: this.getRequiredString(payload.birthDate, 'birthDate'),
dateHasPostfix:
typeof payload.dateHasPostfix === 'number' ? payload.dateHasPostfix : undefined,
},
context,
);
case InquiryType.SHAHKAR:
return this.inquireShahkar(payload, context);
case InquiryType.REAL_ESTATE:
return this.inquireRealEstate(payload, context);
case InquiryType.CAR_BY_PLATE:
return this.inquireCarByPlate(payload, context);
case InquiryType.CAR_BY_CHASSIS:
return this.inquireCarByChassis(payload, context);
case InquiryType.THIRD_PARTY_CAR:
return this.inquireThirdPartyCar(payload, context);
default:
throw this.createProviderError(`Unsupported inquiry type: ${inquiryType}`, 'UNSUPPORTED_INQUIRY');
}
}
private async inquireCarByPlate(
payload: LegacyInquiryPayload,
context: ProviderExecutionContext,
): Promise<{ raw: unknown }> {
const input = this.parseCarPlatePayload(payload);
return this.withResilience(
async () => ({
raw: await this.fetchCarByPlate(input, context),
}),
context,
'car by plate inquiry',
);
}
private async inquireCarByChassis(
payload: LegacyInquiryPayload,
context: ProviderExecutionContext,
): Promise<{ raw: unknown }> {
const nationalCode = this.getRequiredString(payload.nationalCode, 'nationalCode');
const chassisNo = this.getRequiredString(payload.chassisNo, 'chassisNo');
return this.withResilience(
async () => {
const data = await this.authenticatedRequest<unknown>(
'GET',
`/api/central-insurance-car-inquiry/vin/${encodeURIComponent(chassisNo)}/national-code/${nationalCode}`,
undefined,
context,
);
return {
raw: {
nationalCode,
chassisNo,
...(typeof data === 'object' && data !== null ? (data as Record<string, unknown>) : { data }),
},
};
},
context,
'car by chassis inquiry',
);
}
/** Tejarat applies third-party selection rules server-side — passthrough car-by-plate API. */
private async inquireThirdPartyCar(
payload: LegacyInquiryPayload,
context: ProviderExecutionContext,
): Promise<{ raw: unknown }> {
const input = this.parseCarPlatePayload(payload);
return this.withResilience(
async () => ({
raw: {
...(await this.fetchCarByPlate(input, context)),
selectionMode: 'provider',
},
}),
context,
'third-party car inquiry',
);
}
private parseCarPlatePayload(payload: LegacyInquiryPayload): {
nationalCode: string;
plk1: string;
plk2: string;
plk3: string;
plksrl: string;
} {
return {
nationalCode: this.getRequiredString(payload.nationalCode, 'nationalCode'),
plk1: this.getRequiredString(payload.plk1, 'plk1'),
plk2: this.getRequiredString(payload.plk2, 'plk2'),
plk3: this.getRequiredString(payload.plk3, 'plk3'),
plksrl: this.getRequiredString(payload.plksrl, 'plksrl'),
};
}
private async fetchCarByPlate(
input: {
nationalCode: string;
plk1: string;
plk2: string;
plk3: string;
plksrl: string;
},
context: ProviderExecutionContext,
): Promise<Record<string, unknown>> {
const data = await this.authenticatedRequest<unknown>(
'POST',
'/api/central-insurance-car-inquiry',
{
Part1: input.plk1,
Part2: input.plk2,
Part3: input.plk3,
Part4: input.plksrl,
NationalCode: input.nationalCode,
},
context,
);
const raw = {
nationalCode: input.nationalCode,
plk1: input.plk1,
plk2: input.plk2,
plk3: input.plk3,
plksrl: input.plksrl,
...(typeof data === 'object' && data !== null ? (data as Record<string, unknown>) : { data }),
};
this.assertTejaratOwnerMatch(input.nationalCode, raw);
return raw;
}
/**
* If Tejarat echoes a different owner national code, fail as generic no-match.
* Do not put that owner code on the error — the caller must not learn who the plate belongs to.
*/
private assertTejaratOwnerMatch(requestedNationalCode: string, raw: Record<string, unknown>): void {
const owner = this.findOwnerNationalCode(raw, requestedNationalCode);
if (!owner) {
return;
}
return this.inquirePerson(payload, context);
const pad = (value: string) => value.trim().padStart(10, '0');
if (pad(requestedNationalCode) !== pad(owner)) {
throw this.createProviderError(
'Inquiry returned no matching result',
'INQUIRY_NO_MATCH',
);
}
}
private findOwnerNationalCode(
value: unknown,
requestedNationalCode: string,
depth = 0,
): string | undefined {
if (depth > 4 || value == null) {
return undefined;
}
if (typeof value === 'string' || typeof value === 'number') {
return undefined;
}
if (Array.isArray(value)) {
for (const item of value) {
const found = this.findOwnerNationalCode(item, requestedNationalCode, depth + 1);
if (found) return found;
}
return undefined;
}
if (typeof value === 'object') {
const record = value as Record<string, unknown>;
for (const key of ['NtnlId', 'ntnlId', 'NationalId', 'nationalId']) {
const candidate = record[key];
if (typeof candidate === 'string' || typeof candidate === 'number') {
const text = String(candidate).trim();
if (/^\d{10}$/.test(text)) {
return text;
}
}
}
for (const nested of Object.values(record)) {
const found = this.findOwnerNationalCode(nested, requestedNationalCode, depth + 1);
if (found) return found;
}
}
return undefined;
}
private async inquirePerson(
payload: PersonInquiryPayload,
_context: ProviderExecutionContext,
context: ProviderExecutionContext,
): Promise<PersonInquiryResult> {
const cachedResult = await this.cachedInquiryResultService.findByNationalCodeAndBirthDate(
const cached = await this.inquiryResultCacheService.findPersonInquiry(
payload.nationalCode,
payload.birthDate,
);
if (cachedResult) {
this.logger.log(`Cache hit for nationalCode: ${payload.nationalCode}`);
return {
nationalCode: cachedResult.nationalCode,
birthDate: cachedResult.birthDate,
fullName: `${cachedResult.name} ${cachedResult.family}`,
raw: cachedResult as any,
};
if (cached) {
this.logger.log(
`Cache hit for person inquiry | nationalCode=${payload.nationalCode} | requestId=${context.requestId}`,
);
return this.toPersonResult(cached, payload.birthDate);
}
const token = await this.getTniToken();
if (!token) {
throw new Error('Failed to retrieve TNI token');
}
return this.withResilience(
() => this.fetchPersonLive(payload, context),
context,
'person inquiry',
);
}
private async fetchPersonLive(
payload: PersonInquiryPayload,
context: ProviderExecutionContext,
): Promise<PersonInquiryResult> {
const providerBirthDate = jalaliDateToGregorianDate(payload.birthDate);
const response = await this.authenticatedRequest<TejaratNouPersonInquiryData>(
'POST',
`/api/identity-inquiry/national-code/${payload.nationalCode}/birthdate/${encodeURIComponent(providerBirthDate)}`,
{},
context,
);
const cacheData = this.toCacheData(response, payload);
await this.persistCache(cacheData);
return this.toPersonResult(cacheData, payload.birthDate);
}
private async inquireShahkar(
payload: LegacyInquiryPayload,
context: ProviderExecutionContext,
): Promise<{ raw: unknown }> {
const nationalCode = this.getRequiredString(
payload.nationalCode ?? payload.nationalCod ?? payload.NationalCod,
'nationalCode',
);
const mobileNo = this.getRequiredString(
payload.mobileNo ?? payload.MobileNo ?? payload.mobileNumber ?? payload.MobileNumber,
'mobileNo',
);
return this.withResilience(
async () => {
const data = await this.authenticatedRequest<unknown>(
'POST',
'/api/compliance-inquiry/compatibility',
{ nationalCode, mobileNo },
context,
);
return {
raw: {
nationalCode,
mobileNo,
...(typeof data === 'object' && data !== null ? (data as Record<string, unknown>) : { data }),
},
};
},
context,
'shahkar inquiry',
);
}
private async inquireRealEstate(
payload: LegacyInquiryPayload,
context: ProviderExecutionContext,
): Promise<{ raw: unknown }> {
const nationalCode = this.getRequiredString(
payload.nationalCode ?? payload.nationalId ?? payload.NationalId,
'nationalCode',
);
const postalCode = this.getRequiredString(
payload.postalCode ?? payload.PostalCode,
'postalCode',
);
return this.withResilience(
async () => {
const data = await this.authenticatedRequest<CentInsurApiResponse | Record<string, unknown>>(
'POST',
'/api/central-insurance-amlak-inquiry',
{
nationalId: nationalCode,
postalCode: Number(postalCode),
},
context,
);
const centInsurError = this.getCentInsurBusinessError(data);
if (centInsurError) {
throw this.createProviderError(centInsurError.message, centInsurError.code);
}
return {
raw: {
nationalCode,
postalCode,
...(typeof data === 'object' && data !== null ? (data as Record<string, unknown>) : { data }),
},
};
},
context,
'real estate inquiry',
);
}
private async withResilience<T>(
fn: () => Promise<T>,
context: ProviderExecutionContext,
label: string,
): Promise<T> {
const maxAttempts = Math.max(1, this.config.maxRetries || PROVIDER_DEFAULT_MAX_ATTEMPTS);
return runWithProviderResilience(fn, {
providerName: this.name,
maxAttempts,
timeoutMs: this.config.timeout,
context,
label: `${this.name} ${label}`,
});
}
private async authenticatedRequest<T>(
method: 'GET' | 'POST',
path: string,
body: Record<string, unknown> | undefined,
context: ProviderExecutionContext,
): Promise<T> {
const token = await this.generalTokenService.getTejaratNouAccessToken(this.config);
try {
const providerBirthDate = jalaliDateToGregorianDate(payload.birthDate);
const response = await this.httpClient.post<TejaratNouPersonInquiryResponse>(
`/api/identity-inquiry/national-code/${payload.nationalCode}/birthdate/${encodeURIComponent(providerBirthDate)}`,
{},
{
headers: {
Authorization: `Bearer ${token}`,
Accept: 'text/plain',
},
const response = await this.httpClient.request<TejaratNouGatewayResponse<T>>({
method,
url: path,
data: method === 'POST' ? body : undefined,
headers: {
Authorization: `Bearer ${token}`,
Accept: 'text/plain',
},
);
});
if (!response.data.isSuccess || !response.data.data) {
const envelope = response.data;
if (envelope?.isSuccess === false || (envelope?.statusCode && envelope.statusCode >= 400)) {
throw this.createProviderError(
response.data.message ?? 'TejaratNou person inquiry failed',
String(response.data.statusCode ?? 'PROVIDER_ERROR'),
envelope.message ?? 'TejaratNou inquiry failed',
String(envelope.statusCode ?? 'PROVIDER_ERROR'),
);
}
const inquiryData = response.data.data;
const nationalCode = this.getNationalCode(inquiryData);
if (envelope?.data !== undefined) {
return envelope.data;
}
await this.cacheInquiryResult(inquiryData, payload.birthDate);
return {
nationalCode,
birthDate: payload.birthDate,
fullName: this.getFullName(inquiryData),
raw: inquiryData,
};
return envelope as T;
} catch (error) {
if (error instanceof AxiosError) {
this.logger.error(
`TejaratNou person inquiry failed: ${error.response?.status ?? 'NETWORK_ERROR'} ${error.message}`,
`TejaratNou ${path} failed | status=${error.response?.status ?? 'NETWORK'} | requestId=${context.requestId}`,
);
const responseBody = error.response?.data as TejaratNouGatewayResponse | { message?: string } | undefined;
const message = responseBody?.message ?? error.message;
throw this.createProviderError(
message,
String(error.code ?? error.response?.status ?? 'NETWORK_ERROR'),
);
} else {
this.logger.error(`TejaratNou person inquiry failed: ${error}`);
}
throw error;
}
}
private async cacheInquiryResult(
inquiryData: TejaratNouPersonInquiryData,
gatewayBirthDate: string,
): Promise<void> {
private getCentInsurBusinessError(
data: CentInsurApiResponse | Record<string, unknown>,
): { message: string; code: string } | null {
if (!data || typeof data !== 'object' || !('IsSucceed' in data)) {
return null;
}
const providerError = getCentInsurProviderError(data as CentInsurApiResponse, InquiryType.REAL_ESTATE);
return providerError ? { message: providerError.message, code: providerError.code } : null;
}
private getRequiredString(value: unknown, field: string): string {
if (typeof value !== 'string' || !value.trim()) {
throw this.createProviderError(`${field} is required`, 'VALIDATION_ERROR');
}
return value.trim();
}
private toCacheData(
data: TejaratNouPersonInquiryData,
payload: PersonInquiryPayload,
): PersonInquiryCacheData {
return {
nationalCode: String(data.nationalCodeString ?? data.nationalCode ?? payload.nationalCode),
birthDate: payload.birthDate,
birthDateGregorian: data.birthDateGregorian,
name: String(data.name ?? ''),
family: String(data.family ?? ''),
fatherName: String(data.fatherName ?? ''),
shenasnameSeri: String(data.shenasnameSeri ?? ''),
shenasnameSerial: String(data.shenasnameSerial ?? ''),
shenasnameNo: String(data.shenasnameNo ?? ''),
gender: data.gender,
deathStatus: data.deathStatus,
deathDate: data.deathDate ? String(data.deathDate) : undefined,
zipcode: String(data.zipcode ?? ''),
zipcodeDesc: data.zipcodeDesc,
exceptionMessage: data.exceptionMessage ? String(data.exceptionMessage) : undefined,
message: data.message,
};
}
private toPersonResult(data: PersonInquiryCacheData, birthDate: string): PersonInquiryResult {
return {
nationalCode: data.nationalCode,
birthDate,
fullName: [data.name, data.family].filter(Boolean).join(' '),
raw: data,
};
}
private async persistCache(data: PersonInquiryCacheData): Promise<void> {
try {
await this.cachedInquiryResultService.create({
nationalCode: this.getNationalCode(inquiryData),
name: String(inquiryData.name ?? ''),
family: String(inquiryData.family ?? ''),
fatherName: String(inquiryData.fatherName ?? ''),
shenasnameSeri: String(inquiryData.shenasnameSeri ?? ''),
shenasnameSerial: String(inquiryData.shenasnameSerial ?? ''),
shenasnameNo: String(inquiryData.shenasnameNo ?? ''),
birthDate: gatewayBirthDate,
birthDateGregorian: inquiryData.birthDateGregorian,
gender: inquiryData.gender,
deathStatus: inquiryData.deathStatus,
deathDate:
inquiryData.deathDate === undefined || inquiryData.deathDate === null
? undefined
: String(inquiryData.deathDate),
zipcode: String(inquiryData.zipcode ?? ''),
zipcodeDesc: inquiryData.zipcodeDesc,
exceptionMessage:
inquiryData.exceptionMessage === undefined || inquiryData.exceptionMessage === null
? undefined
: String(inquiryData.exceptionMessage),
message: inquiryData.message,
});
await this.inquiryResultCacheService.savePersonInquiry(ProviderName.TEJARATNOU, data);
} catch (error) {
this.logger.warn(
`TejaratNou inquiry succeeded, but cache write failed: ${
`TejaratNou inquiry succeeded but cache write failed: ${
error instanceof Error ? error.message : String(error)
}`,
);
}
}
private getNationalCode(inquiryData: TejaratNouPersonInquiryData): string {
return String(inquiryData.nationalCodeString ?? inquiryData.nationalCode ?? '');
}
private getFullName(inquiryData: TejaratNouPersonInquiryData): string {
return [inquiryData.name, inquiryData.family].filter(Boolean).join(' ');
}
private createProviderError(providerMessage: string, providerCode: string): Error {
const publicMessage = resolveProviderPublicMessage(providerMessage);
const code =
providerCode === 'ETIMEDOUT' || providerCode === 'ECONNABORTED'
? 'PROVIDER_TIMEOUT'
: providerCode === 'NETWORK_ERROR' || providerCode === 'ECONNRESET'
? 'PROVIDER_NETWORK_ERROR'
: providerCode === 'VALIDATION_ERROR'
? 'VALIDATION_ERROR'
: providerCode === 'INQUIRY_NO_MATCH'
? 'INQUIRY_NO_MATCH'
: providerCode === 'UNSUPPORTED_INQUIRY'
? 'UNSUPPORTED_INQUIRY'
: 'PROVIDER_ERROR';
const publicMessage =
code === 'PROVIDER_ERROR'
? resolveProviderPublicMessage(providerMessage)
: {
message:
code === 'INQUIRY_NO_MATCH'
? 'Inquiry returned no matching result'
: providerMessage,
messageFa: undefined as string | undefined,
};
const error = new Error(providerMessage);
(
error as Error & {
normalizedError: {
code: string;
message: string;
messageFa: string;
messageFa?: string;
providerMessage: string;
providerCode: string;
};
}
).normalizedError = {
code: 'PROVIDER_ERROR',
code,
message: publicMessage.message,
messageFa: publicMessage.messageFa,
providerMessage,
@@ -213,55 +592,4 @@ export class TejaratNouProvider implements InquiryProvider<PersonInquiryPayload,
};
return error;
}
private async getTniToken(): Promise<string | null> {
const latestToken = await this.generalTokenService.getLatestToken();
if (latestToken && !(await this.generalTokenService.isTokenExpired(latestToken))) {
this.logger.log(`Using existing token: ${latestToken._id}`);
return latestToken.accessToken;
}
try {
const response = await axios.post(
`${this.config.baseUrl}/connect/token`,
new URLSearchParams({
grant_type: 'password',
client_id: this.config.clientId,
client_secret: this.config.clientSecret,
username: this.config.username,
password: this.config.password,
scope: 'api-gateway access-management',
}),
mergeOutboundAxiosConfig({
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Cookie: 'cookiesession1=678A8C5D2222753B93723D81AA53FF8C',
},
timeout: this.config.timeout,
}),
);
const jsonData = response.data;
const expiresIn = jsonData.expires_in;
const expiresAt = new Date(Date.now() + expiresIn * 1000);
await this.generalTokenService.create({
serviceProvider: 'TejaratNou',
tokenType: jsonData.token_type,
url: this.config.baseUrl,
clientId: this.config.clientId,
clientSecret: this.config.clientSecret,
username: this.config.username,
scope: jsonData.scope,
accessToken: jsonData.access_token,
expiresIn: expiresIn,
expiresAt: expiresAt,
});
return jsonData.access_token;
} catch (err) {
this.logger.error(`Failed to get TNI token: ${err}`);
return null;
}
}
}