forked from Shared/esg
feat(providers): add asia person and real estate inquiries
Register Asia as a configurable inquiry provider. Use Asia JSON login and cached bearer tokens for person inquiries, and AMITIS credentials for real estate inquiries. Add credential-free environment examples and tests for request contracts, authentication failures, response validation, and routing.
This commit is contained in:
@@ -128,3 +128,17 @@ TEJARATNOU_USERNAME=your_username
|
||||
TEJARATNOU_PASSWORD=your_password
|
||||
TEJARATNOU_TIMEOUT=15000
|
||||
TEJARATNOU_ENABLED=true
|
||||
|
||||
# Asia: person uses Asia login; real estate uses CentInsur AMITIS login.
|
||||
ASIA_ENABLED=true
|
||||
ASIA_TIMEOUT=15000
|
||||
ASIA_MAX_RETRIES=3
|
||||
ASIA_LOGIN_URL=https://api.bimehasia.ir/v1/login
|
||||
ASIA_PERSON_URL=https://api.bimehasia.ir/v1/sanhab/sabtahval
|
||||
ASIA_PERSON_USERNAME=
|
||||
ASIA_PERSON_PASSWORD=
|
||||
ASIA_PERSON_AUTH_METHOD=ASIA
|
||||
ASIA_REAL_ESTATE_URL=https://apigw.services.centinsur.ir/amlakeskanservice/amlakeskan/inquiry
|
||||
ASIA_REAL_ESTATE_USERNAME=
|
||||
ASIA_REAL_ESTATE_PASSWORD=
|
||||
ASIA_REAL_ESTATE_AUTH_METHOD=AMITIS
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* Used by factory, configuration, and response normalization.
|
||||
*/
|
||||
export enum ProviderName {
|
||||
ASIA = 'ASIA',
|
||||
HAMTA = 'HAMTA',
|
||||
MOALLEM = 'MOALLEM',
|
||||
PARSIAN = 'PARSIAN',
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { InquiryType } from '../common/enums/inquiry-type.enum';
|
||||
import { ProviderName } from '../common/enums/provider-name.enum';
|
||||
|
||||
export type AuthMethod = 'AMITIS' | 'SOAP' | 'OAUTH2' | 'NONE';
|
||||
export type AuthMethod = 'AMITIS' | 'ASIA' | 'SOAP' | 'OAUTH2' | 'NONE';
|
||||
|
||||
export interface AsiaConfig extends ProviderEnvConfig {
|
||||
loginUrl: string;
|
||||
}
|
||||
|
||||
export interface InquiryConfig {
|
||||
url: string;
|
||||
@@ -80,6 +84,10 @@ export default () => ({
|
||||
timeout: parseInt(process.env.AMITIS_TIMEOUT ?? '10000', 10),
|
||||
enabled: process.env.AMITIS_ENABLED !== 'false',
|
||||
} satisfies AmitisAuthServiceConfig,
|
||||
asia: {
|
||||
...buildProviderConfig('ASIA'),
|
||||
loginUrl: process.env.ASIA_LOGIN_URL ?? 'https://api.bimehasia.ir/v1/login',
|
||||
} satisfies AsiaConfig,
|
||||
hamta: buildProviderConfig('HAMTA'),
|
||||
moallem: buildProviderConfig('MOALLEM'),
|
||||
parsian: buildProviderConfig('PARSIAN'),
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ProviderName } from '../../common/enums/provider-name.enum';
|
||||
import { InquiryProvider } from '../../common/interfaces/inquiry-provider.interface';
|
||||
import { InquiryRoutingConfig } from '../../config/configuration';
|
||||
import { HamtaProvider } from '../implementations/hamta.provider';
|
||||
import { AsiaProvider } from '../implementations/asia.provider';
|
||||
import { MoallemProvider } from '../implementations/moallem.provider';
|
||||
import { ParsianProvider } from '../implementations/parsian.provider';
|
||||
import { TejaratNouProvider } from '../implementations/tejaratnou.provider';
|
||||
@@ -25,8 +26,10 @@ export class ProviderFactory {
|
||||
moallem: MoallemProvider,
|
||||
parsian: ParsianProvider,
|
||||
tejaratnou: TejaratNouProvider,
|
||||
asia: AsiaProvider,
|
||||
) {
|
||||
this.registry = new Map<ProviderName, InquiryProvider>([
|
||||
[ProviderName.ASIA, asia],
|
||||
[ProviderName.HAMTA, hamta],
|
||||
[ProviderName.MOALLEM, moallem],
|
||||
[ProviderName.PARSIAN, parsian],
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { AxiosError } from 'axios';
|
||||
import { InquiryType } from '../../common/enums/inquiry-type.enum';
|
||||
import { ProviderName } from '../../common/enums/provider-name.enum';
|
||||
import { AsiaConfig } from '../../config/configuration';
|
||||
import { GeneralTokenService } from '../services/general-token.service';
|
||||
import {
|
||||
LegacyApiProvider,
|
||||
PersonInquiryPayload,
|
||||
PersonInquiryResult,
|
||||
} from '../shared/legacy-api.provider.abstract';
|
||||
import { AmitisProvider } from './amitis.provider';
|
||||
|
||||
interface AsiaResponse<T> {
|
||||
isSuccess?: boolean;
|
||||
message?: string;
|
||||
result?: T;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AsiaProvider extends LegacyApiProvider {
|
||||
readonly name = ProviderName.ASIA;
|
||||
readonly supportedInquiryTypes = [InquiryType.PERSON, InquiryType.REAL_ESTATE];
|
||||
private readonly asiaConfig: AsiaConfig;
|
||||
|
||||
constructor(
|
||||
configService: ConfigService,
|
||||
amitisProvider: AmitisProvider,
|
||||
private readonly generalTokenService: GeneralTokenService,
|
||||
) {
|
||||
const config = configService.get<AsiaConfig>('asia')!;
|
||||
super(config, (provider, inquiry, username, password, signal) =>
|
||||
amitisProvider.getAccessToken(provider, inquiry, username, password, signal),
|
||||
);
|
||||
this.asiaConfig = config;
|
||||
}
|
||||
|
||||
protected async inquirePerson(
|
||||
payload: PersonInquiryPayload,
|
||||
inquiryType: InquiryType,
|
||||
signal?: AbortSignal,
|
||||
): Promise<PersonInquiryResult> {
|
||||
const config = this.getInquiryConfig(inquiryType);
|
||||
if (config.authMethod !== 'ASIA') {
|
||||
throw this.formatProviderError('ASIA_PERSON_AUTH_METHOD must be ASIA');
|
||||
}
|
||||
if (!config.username || !config.password) {
|
||||
throw this.formatProviderError('Asia person credentials are missing');
|
||||
}
|
||||
const birthDate = payload.birthDate?.replace(/-/g, '');
|
||||
if (!/^\d{8}$/.test(birthDate ?? '') || !/^\d{10}$/.test(payload.nationalCode ?? '')) {
|
||||
throw this.formatProviderError('Asia requires a 10-digit national code and a full Jalali birth date');
|
||||
}
|
||||
|
||||
try {
|
||||
const token = await this.generalTokenService.getValidAccessToken(
|
||||
'ASIA_PERSON',
|
||||
async (requestSignal) => {
|
||||
const response = await this.httpClient.post<AsiaResponse<{ token?: string }>>(
|
||||
this.asiaConfig.loginUrl,
|
||||
{ userName: config.username, password: config.password },
|
||||
{ signal: requestSignal },
|
||||
);
|
||||
const body = response.data;
|
||||
const accessToken = body?.result?.token;
|
||||
if (body?.isSuccess !== true || typeof accessToken !== 'string' || !accessToken.trim()) {
|
||||
throw this.formatProviderError(body?.message || 'Asia login returned no valid token');
|
||||
}
|
||||
return {
|
||||
accessToken,
|
||||
tokenType: 'Bearer',
|
||||
scope: 'person',
|
||||
expiresIn: this.getTokenLifetime(accessToken),
|
||||
};
|
||||
},
|
||||
{ url: this.asiaConfig.loginUrl, clientId: config.username, username: config.username },
|
||||
signal,
|
||||
);
|
||||
const response = await this.httpClient.post<AsiaResponse<Record<string, unknown>>>(
|
||||
config.url,
|
||||
{ nin: Number(payload.nationalCode), birthDate: Number(birthDate), persianBirthDate: '' },
|
||||
{ headers: { Authorization: `Bearer ${token}` }, signal },
|
||||
);
|
||||
const body = response.data;
|
||||
// Reject empty or unrecognized responses rather than reporting an inquiry success.
|
||||
if (body?.isSuccess !== true || !body.result || typeof body.result !== 'object' || Array.isArray(body.result)) {
|
||||
throw this.formatProviderError(body?.message || 'Asia person inquiry returned no valid result');
|
||||
}
|
||||
return {
|
||||
nationalCode: payload.nationalCode,
|
||||
birthDate: payload.birthDate,
|
||||
fullName: [body.result.name, body.result.family]
|
||||
.filter((value): value is string => typeof value === 'string' && Boolean(value.trim()))
|
||||
.join(' ') || undefined,
|
||||
raw: { ...body.result, birthDate: payload.birthDate },
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof AxiosError) throw this.formatAxiosError(error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private getTokenLifetime(token: string): number {
|
||||
// The login returns a JWT with exp, but no separate expiry field. Use exp only
|
||||
// for cache lifetime; opaque tokens are used once without assuming an expiry.
|
||||
try {
|
||||
const claims = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8'));
|
||||
if (typeof claims.exp === 'number' && Number.isFinite(claims.exp)) {
|
||||
return Math.max(0, Math.floor(claims.exp - Date.now() / 1000));
|
||||
}
|
||||
} catch {
|
||||
// A token without readable expiry must not be reused from the cache.
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { ProviderFactory } from './factory/provider.factory';
|
||||
import { HamtaProvider } from './implementations/hamta.provider';
|
||||
import { AsiaProvider } from './implementations/asia.provider';
|
||||
import { MoallemProvider } from './implementations/moallem.provider';
|
||||
import { ParsianProvider } from './implementations/parsian.provider';
|
||||
import { TejaratNouProvider } from './implementations/tejaratnou.provider';
|
||||
@@ -25,6 +26,7 @@ import { DistributedLock } from './schemas/distributed-lock.schema';
|
||||
TypeOrmModule.forFeature([GeneralToken, InquiryResultCache, DistributedLock]),
|
||||
],
|
||||
providers: [
|
||||
AsiaProvider,
|
||||
HamtaProvider,
|
||||
MoallemProvider,
|
||||
ParsianProvider,
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { AxiosError, AxiosHeaders, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
|
||||
import configuration, { AsiaConfig } from '../../src/config/configuration';
|
||||
import { InquiryType } from '../../src/common/enums/inquiry-type.enum';
|
||||
import { ProviderName } from '../../src/common/enums/provider-name.enum';
|
||||
import { AsiaProvider } from '../../src/providers/implementations/asia.provider';
|
||||
import { AmitisProvider } from '../../src/providers/implementations/amitis.provider';
|
||||
import { GeneralTokenService } from '../../src/providers/services/general-token.service';
|
||||
import { ProviderFactory } from '../../src/providers/factory/provider.factory';
|
||||
|
||||
class TestAsiaProvider extends AsiaProvider {
|
||||
get client() { return this.httpClient; }
|
||||
}
|
||||
|
||||
const context = { requestId: 'asia-test', trackingCode: 'asia-test' };
|
||||
const payload = { nationalCode: '0012345678', birthDate: '1378-11-24' };
|
||||
|
||||
function setup() {
|
||||
const config: AsiaConfig = {
|
||||
enabled: true, timeout: 1000, maxRetries: 1, loginUrl: 'https://asia.test/login',
|
||||
inquiries: {
|
||||
[InquiryType.PERSON]: {
|
||||
url: 'https://asia.test/person', username: 'person-user', password: 'person-password',
|
||||
apiKey: '', authMethod: 'ASIA',
|
||||
},
|
||||
[InquiryType.REAL_ESTATE]: {
|
||||
url: 'https://centinsur.test/estate', username: 'estate-user', password: 'estate-password',
|
||||
apiKey: '', authMethod: 'AMITIS',
|
||||
},
|
||||
},
|
||||
};
|
||||
const amitis = { getAccessToken: jest.fn().mockResolvedValue('estate-token') };
|
||||
const tokens = { getValidAccessToken: jest.fn(async (_key, fetch, _persist, signal) => (await fetch(signal)).accessToken) };
|
||||
const provider = new TestAsiaProvider(
|
||||
new ConfigService({ asia: config }),
|
||||
amitis as unknown as AmitisProvider,
|
||||
tokens as unknown as GeneralTokenService,
|
||||
);
|
||||
const token = `header.${Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 600 })).toString('base64url')}.signature`;
|
||||
const requests: InternalAxiosRequestConfig[] = [];
|
||||
const responses: Array<{ status: number; data: unknown }> = [
|
||||
{ status: 200, data: { isSuccess: true, result: { token } } },
|
||||
{ status: 200, data: { isSuccess: true, result: { name: 'Test', family: 'Person', birthDate: 13781124 } } },
|
||||
];
|
||||
provider.client.defaults.adapter = async (request) => {
|
||||
requests.push(request);
|
||||
const next = responses.shift();
|
||||
if (!next) throw new Error('Unexpected outbound request');
|
||||
const response: AxiosResponse = { ...next, config: request, statusText: '', headers: new AxiosHeaders() };
|
||||
if (next.status >= 400) throw new AxiosError('Provider HTTP failure', 'ERR_BAD_RESPONSE', request, undefined, response);
|
||||
return response;
|
||||
};
|
||||
return { provider, config, amitis, tokens, token, requests, responses };
|
||||
}
|
||||
|
||||
describe('Asia provider', () => {
|
||||
it('logs in with Asia JSON credentials, sends the supplied person contract, and keeps the original national code', async () => {
|
||||
const { provider, requests, token, tokens, amitis } = setup();
|
||||
const signal = new AbortController().signal;
|
||||
const result = await provider.execute(InquiryType.PERSON, payload, { ...context, signal });
|
||||
expect(JSON.parse(requests[0].data)).toEqual({ userName: 'person-user', password: 'person-password' });
|
||||
expect(requests[0].url).toBe('https://asia.test/login');
|
||||
expect(JSON.parse(requests[1].data)).toEqual({ nin: 12345678, birthDate: 13781124, persianBirthDate: '' });
|
||||
expect(requests[1].headers.Authorization).toBe(`Bearer ${token}`);
|
||||
expect(requests[0].signal).toBeInstanceOf(AbortSignal);
|
||||
expect(requests[1].signal).toBe(requests[0].signal);
|
||||
expect(tokens.getValidAccessToken).toHaveBeenCalledWith('ASIA_PERSON', expect.any(Function),
|
||||
{ url: 'https://asia.test/login', clientId: 'person-user', username: 'person-user' }, requests[0].signal);
|
||||
expect(amitis.getAccessToken).not.toHaveBeenCalled();
|
||||
expect(result).toMatchObject({ ...payload, fullName: 'Test Person',
|
||||
raw: { name: 'Test', family: 'Person', birthDate: payload.birthDate } });
|
||||
});
|
||||
|
||||
it('uses the token expiry for caching', async () => {
|
||||
const { provider, tokens } = setup();
|
||||
tokens.getValidAccessToken.mockImplementationOnce(async (_key, fetch, _persist, signal) => {
|
||||
const fresh = await fetch(signal);
|
||||
expect(fresh.expiresIn).toBeGreaterThan(590);
|
||||
expect(fresh.expiresIn).toBeLessThanOrEqual(600);
|
||||
return fresh.accessToken;
|
||||
});
|
||||
await provider.execute(InquiryType.PERSON, payload, context);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ isSuccess: false, message: 'Login denied' },
|
||||
{ isSuccess: true, result: {} },
|
||||
])('stops before the inquiry when authentication fails: %j', async (data) => {
|
||||
const { provider, responses, requests } = setup();
|
||||
responses[0].data = data;
|
||||
await expect(provider.execute(InquiryType.PERSON, payload, context)).rejects.toThrow();
|
||||
expect(requests).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ status: 500, data: '' },
|
||||
{ status: 200, data: '' },
|
||||
{ status: 200, data: { isSuccess: false, message: 'Inquiry rejected' } },
|
||||
{ status: 200, data: { isSuccess: true, result: null } },
|
||||
])('does not treat a failed or malformed inquiry as success: %j', async response => {
|
||||
const { provider, responses } = setup();
|
||||
responses[1] = response;
|
||||
await expect(provider.execute(InquiryType.PERSON, payload, context)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('uses separate AMITIS credentials and the existing real estate contract', async () => {
|
||||
const { provider, responses, requests, amitis, tokens } = setup();
|
||||
responses.splice(0, responses.length, { status: 200, data: { IsSucceed: true, Result: { Result: true } } });
|
||||
const signal = new AbortController().signal;
|
||||
await expect(provider.execute(InquiryType.REAL_ESTATE,
|
||||
{ nationalCode: payload.nationalCode, postalCode: '1234567890' }, { ...context, signal },
|
||||
)).resolves.toMatchObject({ raw: { IsSucceed: true, Result: { Result: true } } });
|
||||
expect(amitis.getAccessToken).toHaveBeenCalledWith(ProviderName.ASIA, InquiryType.REAL_ESTATE,
|
||||
'estate-user', 'estate-password', signal);
|
||||
expect(tokens.getValidAccessToken).not.toHaveBeenCalled();
|
||||
expect(requests[0].headers.Authorization).toBe('Bearer estate-token');
|
||||
expect(JSON.parse(requests[0].data)).toEqual({ NationalId: payload.nationalCode, PostalCode: '1234567890' });
|
||||
});
|
||||
|
||||
it('rejects a year-only person date before login', async () => {
|
||||
const { provider, requests } = setup();
|
||||
await expect(provider.execute(InquiryType.PERSON, { ...payload, birthDate: '1378' }, context)).rejects.toThrow('full Jalali birth date');
|
||||
expect(requests).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('preserves real estate no-match errors', async () => {
|
||||
const { provider, responses } = setup();
|
||||
responses.splice(0, responses.length, { status: 200, data: { IsSucceed: true, Result: { Result: false } } });
|
||||
await expect(provider.execute(InquiryType.REAL_ESTATE,
|
||||
{ nationalCode: payload.nationalCode, postalCode: '1234567890' }, context,
|
||||
)).rejects.toMatchObject({ normalizedError: { code: 'INQUIRY_NO_MATCH' } });
|
||||
});
|
||||
|
||||
it('registers Asia for configured routing', () => {
|
||||
const { provider } = setup();
|
||||
const config = new ConfigService({ inquiryRouting: {
|
||||
[InquiryType.PERSON]: { defaultProvider: ProviderName.ASIA, fallbackEnabled: false, fallbackProviders: [] },
|
||||
} });
|
||||
const factory = new ProviderFactory(config, undefined!, undefined!, undefined!, undefined!, provider);
|
||||
expect(factory.getProvidersForInquiry(InquiryType.PERSON)).toEqual([provider]);
|
||||
});
|
||||
|
||||
it('loads ASIA as the person authentication method from the environment', () => {
|
||||
const before = { ...process.env };
|
||||
try {
|
||||
process.env.ASIA_PERSON_URL = 'https://asia.test/person';
|
||||
process.env.ASIA_PERSON_AUTH_METHOD = 'ASIA';
|
||||
expect(configuration().asia.inquiries[InquiryType.PERSON]?.authMethod).toBe('ASIA');
|
||||
} finally {
|
||||
process.env = before;
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user