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:
@@ -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