1
0
forked from Yara724/api
Files
yara724-api/src/fanavaran/fanavaran-lookup.service.ts

397 lines
12 KiB
TypeScript

import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { HttpService } from "@nestjs/axios";
import {
BadGatewayException,
Injectable,
Logger,
NotFoundException,
} from "@nestjs/common";
import { firstValueFrom } from "rxjs";
import { isAxiosError } from "axios";
import {
getFanavaranClientProfile,
type FanavaranClientKey,
} from "src/core/config/fanavaran-client.config";
import {
FANAVARAN_LOOKUP_BASE_URL,
fanavaranLookupCacheDir,
tejaratStaticAccidentFilePath,
} from "./fanavaran-lookup.config";
@Injectable()
export class FanavaranLookupService {
private readonly logger = new Logger(FanavaranLookupService.name);
private readonly getAppTokenUrl =
"https://apimanager.iraneit.com/BimeApiManager/api/EITAuthentication/GetAppToken";
private readonly loginUrl =
"https://apimanager.iraneit.com/BimeApiManager/api/EITAuthentication/Login";
constructor(private readonly httpService: HttpService) {}
private cacheFilePath(clientKey: FanavaranClientKey, fileName: string): string {
return join(fanavaranLookupCacheDir(clientKey), fileName);
}
async readCacheFile<T>(
clientKey: FanavaranClientKey,
fileName: string,
): Promise<T | null> {
try {
const content = await readFile(
this.cacheFilePath(clientKey, fileName),
"utf-8",
);
return JSON.parse(content) as T;
} catch {
return null;
}
}
async writeCacheFile(
clientKey: FanavaranClientKey,
fileName: string,
data: unknown,
): Promise<void> {
const dir = fanavaranLookupCacheDir(clientKey);
await mkdir(dir, { recursive: true });
await writeFile(
join(dir, fileName),
`${JSON.stringify(data, null, 2)}\n`,
"utf-8",
);
this.logger.log(
`Cached Fanavaran lookup ${fileName} for client ${clientKey}`,
);
}
async readTejaratStaticAccidentFile<T>(fileName: string): Promise<T> {
const cached = await readFile(tejaratStaticAccidentFilePath(fileName), "utf-8");
return JSON.parse(cached) as T;
}
private async getAppToken(config: {
appName: string;
secret: string;
}): Promise<string> {
const response = await firstValueFrom(
this.httpService.post(this.getAppTokenUrl, "", {
headers: {
appname: config.appName,
secret: config.secret,
"Content-Length": "0",
},
transformRequest: [
(_data, headers) => {
if (headers) {
delete headers["Content-Type"];
delete headers["content-type"];
}
return _data;
},
],
}),
);
const appToken =
response.headers.apptoken ||
response.headers.appToken ||
response.headers["apptoken"] ||
response.headers["appToken"];
if (!appToken) {
throw new BadGatewayException("Failed to get Fanavaran appToken");
}
return appToken;
}
private async login(
appToken: string,
config: { username: string; password: string },
): Promise<string> {
const response = await firstValueFrom(
this.httpService.post(this.loginUrl, "", {
headers: {
appToken,
userName: config.username,
password: config.password,
"Content-Length": "0",
},
transformRequest: [
(_data, headers) => {
if (headers) {
delete headers["Content-Type"];
delete headers["content-type"];
}
return _data;
},
],
}),
);
const authenticationToken =
response.headers.authenticationtoken ||
response.headers.authenticationToken ||
response.headers["authenticationtoken"] ||
response.headers["authenticationToken"] ||
response.data?.authenticationtoken ||
response.data?.authenticationToken ||
response.data?.authentication_token;
if (!authenticationToken) {
throw new BadGatewayException("Failed to get Fanavaran authenticationToken");
}
return authenticationToken;
}
async fetchFromFanavaran(
clientKey: FanavaranClientKey,
url: string,
): Promise<unknown> {
const profile = getFanavaranClientProfile(clientKey);
try {
const appToken = await this.getAppToken(profile.auth);
const authenticationToken = await this.login(appToken, profile.auth);
this.logger.log(
`[${clientKey}] Calling Fanavaran lookup API: ${url}`,
);
const response = await firstValueFrom(
this.httpService.get(url, {
headers: {
authenticationToken,
CorpId: profile.auth.corpId,
ContractId: profile.auth.contractId,
Location: profile.auth.location,
"Content-Type": "application/json",
},
timeout: 20000,
}),
);
const dataCount = Array.isArray(response.data)
? response.data.length
: typeof response.data === "object" && response.data !== null
? Object.keys(response.data).length
: 0;
this.logger.log(
`[${clientKey}] Fanavaran lookup response status=${response.status} dataCount=${dataCount}`,
);
return response.data;
} catch (error) {
const message = isAxiosError(error)
? error.response?.data?.Message ||
error.response?.data?.message ||
error.message
: error instanceof Error
? error.message
: "Fanavaran lookup request failed";
this.logger.error(
`Fanavaran lookup fetch failed for ${clientKey} (${url}): ${message}`,
);
throw new BadGatewayException(String(message));
}
}
async getRemoteLookup(
clientKey: FanavaranClientKey,
url: string,
cacheFile: string,
fallback?: () => Promise<unknown>,
): Promise<unknown> {
const cached = await this.readCacheFile(clientKey, cacheFile);
if (cached !== null) {
return cached;
}
try {
const data = await this.fetchFromFanavaran(clientKey, url);
await this.writeCacheFile(clientKey, cacheFile, data);
return data;
} catch (error) {
if (fallback) {
this.logger.warn(
`Fanavaran lookup fetch failed for ${clientKey}/${cacheFile}; using fallback`,
);
const data = await fallback();
await this.writeCacheFile(clientKey, cacheFile, data);
return data;
}
throw error;
}
}
async inquiryByVin(
clientKey: FanavaranClientKey,
vin: string,
): Promise<unknown> {
const url = `${FANAVARAN_LOOKUP_BASE_URL}/car/vehicles/inquiry-by-vin?vin=${encodeURIComponent(vin)}`;
return this.fetchFromFanavaran(clientKey, url);
}
async myPolicies(
clientKey: FanavaranClientKey,
nationalCode: string,
insuranceLineId: number = 5,
): Promise<unknown> {
const url =
`${FANAVARAN_LOOKUP_BASE_URL}/common/Policies/inquiry-my-policies` +
`?InsuranceLineId=${insuranceLineId}` +
`&NationalCode=${encodeURIComponent(nationalCode)}`;
return this.fetchFromFanavaran(clientKey, url);
}
async thirdPartyPolicyById(
clientKey: FanavaranClientKey,
policyId: number,
): Promise<unknown> {
const url = `${FANAVARAN_LOOKUP_BASE_URL}/car/third-party-car-policies/${policyId}`;
return this.fetchFromFanavaran(clientKey, url);
}
async bodyPolicyById(
clientKey: FanavaranClientKey,
policyId: number,
): Promise<unknown> {
const url = `${FANAVARAN_LOOKUP_BASE_URL}/car/vehicle-hull-policies/${policyId}`;
return this.fetchFromFanavaran(clientKey, url);
}
async inquiryByUniqueIdentifier(
clientKey: FanavaranClientKey,
params: {
nationalCode: string;
birthYear: number;
birthMonth: number;
birthDay: number;
},
): Promise<unknown> {
const url =
`${FANAVARAN_LOOKUP_BASE_URL}/common/parties/inquiry-by-unique-identifier` +
`?NationalCode=${encodeURIComponent(params.nationalCode)}` +
`&BirthYear=${params.birthYear}` +
`&BirthMonth=${params.birthMonth}` +
`&BirthDay=${params.birthDay}`;
return this.fetchFromFanavaran(clientKey, url);
}
async resolveInsuranceCorpId(
clientKey: FanavaranClientKey,
): Promise<number | null> {
const caption = process.env.INSURANCE_CORP_ID?.trim();
if (!caption) {
this.logger.warn("resolveInsuranceCorpId: INSURANCE_CORP_ID env not set");
return null;
}
// Check resolved cache first
const cachedId = await this.readCacheFile<number>(clientKey, "insurance-corp-id-resolved.json");
if (cachedId !== null) {
this.logger.log(`resolveInsuranceCorpId: using cached id=${cachedId} for "${caption}"`);
return cachedId;
}
// Try fetching the full list directly from Fanavaran
let companies: unknown;
const url = `${FANAVARAN_LOOKUP_BASE_URL}/common/code-list/insurance-corp`;
try {
companies = await this.fetchFromFanavaran(clientKey, url);
} catch (error) {
this.logger.warn(
`resolveInsuranceCorpId: Fanavaran fetch failed, trying local lookup endpoint`,
);
// Fallback: call our own local lookup endpoint
try {
const localPort = process.env.PORT || 3000;
const response = await firstValueFrom(
this.httpService.get(`http://localhost:${localPort}/lookups/fanavaran/insurance-corp`, {
timeout: 10000,
}),
);
companies = response.data;
} catch (localError) {
this.logger.error(
`resolveInsuranceCorpId: both Fanavaran and local lookup failed`,
);
return null;
}
}
if (!Array.isArray(companies)) {
this.logger.warn(
`resolveInsuranceCorpId: insurance-corp response is not an array, type=${typeof companies}`,
);
return null;
}
this.logger.log(
`resolveInsuranceCorpId: got ${companies.length} companies, searching for "${caption}"`,
);
const normalizedCaption = caption
.replace(/\s+/g, " ")
.toLowerCase()
.trim();
const match = companies.find((c: any) => {
if (c?.IsActive !== 1) return false;
if (typeof c?.Id !== "number") return false;
const cCaption = typeof c?.Caption === "string" ? c.Caption : "";
const normalized = cCaption.replace(/\s+/g, " ").toLowerCase().trim();
return normalized.includes(normalizedCaption) || normalizedCaption.includes(normalized);
});
if (!match) {
this.logger.warn(
`resolveInsuranceCorpId: no active company matching "${caption}". Available: ` +
companies
.filter((c: any) => c?.IsActive === 1)
.map((c: any) => `${c.Caption} (${c.Id})`)
.join(", "),
);
return null;
}
const corpId = match.Id as number;
// Cache both the resolved id and the full list for future use
await this.writeCacheFile(clientKey, "insurance-corp-id-resolved.json", corpId);
await this.writeCacheFile(clientKey, "insurance-corp.json", companies);
this.logger.log(`resolveInsuranceCorpId: resolved id=${corpId} for "${caption}"`);
return corpId;
}
mapFanavaranAccidentCausesToReasonOptions(
causes: unknown,
): { id: number; label: string; fanavaran: number }[] {
if (!Array.isArray(causes)) {
throw new NotFoundException("Fanavaran accident-causes response is invalid");
}
return causes
.filter(
(item) =>
item &&
typeof item === "object" &&
(item as { IsActive?: number }).IsActive === 1 &&
typeof (item as { Id?: unknown }).Id === "number",
)
.map((item) => {
const row = item as { Id: number; Caption?: string };
return {
id: row.Id,
label: row.Caption ?? String(row.Id),
fanavaran: row.Id,
};
});
}
}