forked from Shared/esg
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:
@@ -1,27 +0,0 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { Model } from 'mongoose';
|
||||
import { CachedInquiryResult, CachedInquiryResultDocument } from '../schemas/cached-inquiry-result.schema';
|
||||
|
||||
@Injectable()
|
||||
export class CachedInquiryResultService {
|
||||
constructor(
|
||||
@InjectModel(CachedInquiryResult.name)
|
||||
private readonly cachedInquiryResultModel: Model<CachedInquiryResultDocument>,
|
||||
) {}
|
||||
|
||||
async findByNationalCodeAndBirthDate(
|
||||
nationalCode: string,
|
||||
birthDate: string,
|
||||
): Promise<CachedInquiryResultDocument | null> {
|
||||
return this.cachedInquiryResultModel
|
||||
.findOne({ nationalCode, birthDate })
|
||||
.exec();
|
||||
}
|
||||
|
||||
async create(
|
||||
data: Omit<CachedInquiryResult, 'createdAt'>,
|
||||
): Promise<CachedInquiryResultDocument> {
|
||||
return this.cachedInquiryResultModel.create(data);
|
||||
}
|
||||
}
|
||||
@@ -1,33 +1,151 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import axios from 'axios';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { Model } from 'mongoose';
|
||||
import { mergeOutboundAxiosConfig } from '../../common/helpers/http-client.helper';
|
||||
import {
|
||||
AUTH_MAX_ATTEMPTS,
|
||||
AUTH_RETRY_DELAY_MS,
|
||||
isAuthTransportRetryable,
|
||||
} from '../../common/helpers/provider-resilience.helper';
|
||||
import { withRetry } from '../../common/helpers/retry.helper';
|
||||
import { GeneralToken, GeneralTokenDocument } from '../schemas/general-token.schema';
|
||||
import { TejaratNouConfig } from '../interfaces/tejaratnou-config.interface';
|
||||
|
||||
export interface OAuthTokenResponse {
|
||||
accessToken: string;
|
||||
tokenType: string;
|
||||
scope: string;
|
||||
expiresIn: number;
|
||||
}
|
||||
|
||||
/** Refresh tokens this many seconds before actual expiry. */
|
||||
const TOKEN_EXPIRY_BUFFER_SECONDS = 60;
|
||||
|
||||
@Injectable()
|
||||
export class GeneralTokenService {
|
||||
private readonly logger = new Logger(GeneralTokenService.name);
|
||||
|
||||
constructor(
|
||||
@InjectModel(GeneralToken.name)
|
||||
private readonly generalTokenModel: Model<GeneralTokenDocument>,
|
||||
) {}
|
||||
|
||||
async getLatestToken(serviceProvider = 'TejaratNou'): Promise<GeneralTokenDocument | null> {
|
||||
return this.generalTokenModel
|
||||
.findOne({ serviceProvider })
|
||||
.sort({ createdAt: -1 })
|
||||
.exec();
|
||||
async getLatestToken(serviceProvider: string): Promise<GeneralTokenDocument | null> {
|
||||
return this.generalTokenModel.findOne({ serviceProvider }).sort({ createdAt: -1 }).exec();
|
||||
}
|
||||
|
||||
async create(
|
||||
data: Omit<GeneralToken, 'createdAt'>,
|
||||
): Promise<GeneralTokenDocument> {
|
||||
async isTokenExpired(
|
||||
token: GeneralTokenDocument,
|
||||
bufferSeconds = TOKEN_EXPIRY_BUFFER_SECONDS,
|
||||
): Promise<boolean> {
|
||||
if (!token.expiresAt) return true;
|
||||
const refreshAt = token.expiresAt.getTime() - bufferSeconds * 1000;
|
||||
return Date.now() >= refreshAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a valid access token — reuses MongoDB-stored token when not expired,
|
||||
* otherwise fetches a new one via the supplied OAuth fetcher.
|
||||
*/
|
||||
async getValidAccessToken(
|
||||
serviceProvider: string,
|
||||
fetchNewToken: () => Promise<OAuthTokenResponse>,
|
||||
persistContext: {
|
||||
url: string;
|
||||
clientId: string;
|
||||
username: string;
|
||||
},
|
||||
): Promise<string> {
|
||||
const latest = await this.getLatestToken(serviceProvider);
|
||||
if (latest && !(await this.isTokenExpired(latest))) {
|
||||
this.logger.debug(`Reusing ${serviceProvider} token ${latest._id}`);
|
||||
return latest.accessToken;
|
||||
}
|
||||
|
||||
const fresh = await fetchNewToken();
|
||||
const expiresAt = new Date(Date.now() + fresh.expiresIn * 1000);
|
||||
|
||||
await this.generalTokenModel.create({
|
||||
serviceProvider,
|
||||
tokenType: fresh.tokenType,
|
||||
url: persistContext.url,
|
||||
clientId: persistContext.clientId,
|
||||
username: persistContext.username,
|
||||
scope: fresh.scope,
|
||||
accessToken: fresh.accessToken,
|
||||
expiresIn: fresh.expiresIn,
|
||||
expiresAt,
|
||||
});
|
||||
|
||||
this.logger.log(`Stored new ${serviceProvider} token, expires at ${expiresAt.toISOString()}`);
|
||||
return fresh.accessToken;
|
||||
}
|
||||
|
||||
/** Persist a provider token (AMITIS and other non-OAuth flows). Credentials stay in env. */
|
||||
async persistToken(data: {
|
||||
serviceProvider: string;
|
||||
tokenType: string;
|
||||
url: string;
|
||||
clientId: string;
|
||||
username: string;
|
||||
scope: string;
|
||||
accessToken: string;
|
||||
refreshToken?: string;
|
||||
expiresIn: number;
|
||||
expiresAt: Date;
|
||||
}): Promise<GeneralTokenDocument> {
|
||||
return this.generalTokenModel.create(data);
|
||||
}
|
||||
|
||||
async isTokenExpired(token: GeneralTokenDocument): Promise<boolean> {
|
||||
if (!token.expiresAt) {
|
||||
return true;
|
||||
}
|
||||
const now = new Date();
|
||||
return now >= token.expiresAt;
|
||||
/** OAuth2 password grant for Tejarat No identity gateway. */
|
||||
async getTejaratNouAccessToken(config: TejaratNouConfig): Promise<string> {
|
||||
return this.getValidAccessToken(
|
||||
'TejaratNou',
|
||||
async () => {
|
||||
const response = await withRetry(
|
||||
() =>
|
||||
axios.post(
|
||||
`${config.baseUrl}/connect/token`,
|
||||
new URLSearchParams({
|
||||
grant_type: 'password',
|
||||
client_id: config.clientId,
|
||||
client_secret: config.clientSecret,
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
scope: 'api-gateway access-management',
|
||||
}),
|
||||
mergeOutboundAxiosConfig({
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
timeout: config.timeout,
|
||||
}),
|
||||
),
|
||||
{
|
||||
maxAttempts: AUTH_MAX_ATTEMPTS,
|
||||
delayMs: AUTH_RETRY_DELAY_MS,
|
||||
shouldRetry: isAuthTransportRetryable,
|
||||
},
|
||||
);
|
||||
|
||||
const body = response.data as {
|
||||
access_token: string;
|
||||
token_type: string;
|
||||
scope: string;
|
||||
expires_in: number;
|
||||
};
|
||||
|
||||
return {
|
||||
accessToken: body.access_token,
|
||||
tokenType: body.token_type,
|
||||
scope: body.scope,
|
||||
expiresIn: body.expires_in,
|
||||
};
|
||||
},
|
||||
{
|
||||
url: config.baseUrl,
|
||||
clientId: config.clientId,
|
||||
username: config.username,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { Model } from 'mongoose';
|
||||
import { InquiryType } from '../../common/enums/inquiry-type.enum';
|
||||
import { ProviderName } from '../../common/enums/provider-name.enum';
|
||||
import {
|
||||
InquiryResultCache,
|
||||
InquiryResultCacheDocument,
|
||||
} from '../schemas/inquiry-result-cache.schema';
|
||||
|
||||
export interface PersonInquiryCacheData {
|
||||
nationalCode: string;
|
||||
birthDate: string;
|
||||
birthDateGregorian?: string;
|
||||
name: string;
|
||||
family: string;
|
||||
fatherName: string;
|
||||
shenasnameSeri: string;
|
||||
shenasnameSerial: string;
|
||||
shenasnameNo: string;
|
||||
gender?: unknown;
|
||||
deathStatus?: unknown;
|
||||
deathDate?: string;
|
||||
zipcode: string;
|
||||
zipcodeDesc?: string;
|
||||
exceptionMessage?: string;
|
||||
message?: unknown;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class InquiryResultCacheService {
|
||||
constructor(
|
||||
@InjectModel(InquiryResultCache.name)
|
||||
private readonly cacheModel: Model<InquiryResultCacheDocument>,
|
||||
) {}
|
||||
|
||||
static personCacheKey(nationalCode: string, birthDate: string): string {
|
||||
return `${nationalCode}|${birthDate}`;
|
||||
}
|
||||
|
||||
async findPersonInquiry(
|
||||
nationalCode: string,
|
||||
birthDate: string,
|
||||
): Promise<PersonInquiryCacheData | null> {
|
||||
const entry = await this.cacheModel
|
||||
.findOne({
|
||||
inquiryType: InquiryType.PERSON,
|
||||
cacheKey: InquiryResultCacheService.personCacheKey(nationalCode, birthDate),
|
||||
})
|
||||
.exec();
|
||||
|
||||
if (!entry) return null;
|
||||
return entry.data as unknown as PersonInquiryCacheData;
|
||||
}
|
||||
|
||||
async savePersonInquiry(
|
||||
provider: ProviderName,
|
||||
data: PersonInquiryCacheData,
|
||||
): Promise<void> {
|
||||
await this.cacheModel.updateOne(
|
||||
{
|
||||
inquiryType: InquiryType.PERSON,
|
||||
cacheKey: InquiryResultCacheService.personCacheKey(data.nationalCode, data.birthDate),
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
inquiryType: InquiryType.PERSON,
|
||||
cacheKey: InquiryResultCacheService.personCacheKey(data.nationalCode, data.birthDate),
|
||||
provider,
|
||||
data,
|
||||
},
|
||||
},
|
||||
{ upsert: true },
|
||||
);
|
||||
}
|
||||
|
||||
/** Generic cache read for future inquiry types. */
|
||||
async find(
|
||||
inquiryType: InquiryType,
|
||||
cacheKey: string,
|
||||
): Promise<Record<string, unknown> | null> {
|
||||
const entry = await this.cacheModel.findOne({ inquiryType, cacheKey }).exec();
|
||||
return entry?.data ?? null;
|
||||
}
|
||||
|
||||
async save(
|
||||
inquiryType: InquiryType,
|
||||
cacheKey: string,
|
||||
provider: ProviderName,
|
||||
data: Record<string, unknown>,
|
||||
): Promise<void> {
|
||||
await this.cacheModel.updateOne(
|
||||
{ inquiryType, cacheKey },
|
||||
{ $set: { inquiryType, cacheKey, provider, data } },
|
||||
{ upsert: true },
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user