audit fanavaran logs and missing fields null fixed

This commit is contained in:
2026-06-23 15:58:49 +03:30
parent bc70a8c930
commit 8bf3cfe5e9
7 changed files with 443 additions and 24 deletions

View File

@@ -169,6 +169,13 @@ import {
getFanavaranClientProfile,
resolveFanavaranClientKey,
} from "src/core/config/fanavaran-client.config";
import { FanavaranAuditService } from "src/fanavaran/fanavaran-audit.service";
import type { FanavaranAuditSession } from "src/fanavaran/fanavaran-audit.types";
import {
FanavaranAuditSource,
FanavaranAuditStatus,
FanavaranAuditStep,
} from "src/fanavaran/schema/fanavaran-audit-log.schema";
export interface FanavaranAutoSubmitResult {
attempted: boolean;
@@ -181,9 +188,6 @@ export interface FanavaranAutoSubmitResult {
fanavaranResponse?: unknown;
}
/** Placeholder for Fanavaran fields not yet mapped from claim/blame data. */
const FANAVARAN_UNMAPPED_FIELD = "empty";
@Injectable()
export class ClaimRequestManagementService {
private readonly logger = new Logger(ClaimRequestManagementService.name);
@@ -262,6 +266,7 @@ export class ClaimRequestManagementService {
private readonly publicIdService: PublicIdService,
private readonly sandHubService: SandHubService,
private readonly httpService: HttpService,
private readonly fanavaranAuditService: FanavaranAuditService,
) {}
private requiredDocumentKeysV2(isCarBody: boolean): string[] {
@@ -3358,15 +3363,15 @@ export class ClaimRequestManagementService {
}
private applyFanavaranDefaultFields(result: Record<string, unknown>): void {
result.ActualPremium = FANAVARAN_UNMAPPED_FIELD;
result.ArchiveNo = FANAVARAN_UNMAPPED_FIELD;
result.AuthorityCulpritId = FANAVARAN_UNMAPPED_FIELD;
result.ActualPremium = null;
result.ArchiveNo = null;
result.AuthorityCulpritId = null;
result.AccidentCulpritId = null;
result.ClaimCompletionDate = FANAVARAN_UNMAPPED_FIELD;
result.CostSeparationToDmgSections = FANAVARAN_UNMAPPED_FIELD;
result.ClaimCompletionDate = null;
result.CostSeparationToDmgSections = null;
result.CouponNo = null;
result.CourtArchiveNo = null;
result.CustomerFaultPercent = FANAVARAN_UNMAPPED_FIELD;
result.CustomerFaultPercent = null;
result.CulpritLicenceCityId = null;
result.CulpritLicenceCountryId = null;
result.CulpritLicenceForeignCityName = null;
@@ -3375,14 +3380,14 @@ export class ClaimRequestManagementService {
result.DamagedCount = 1;
result.DmgAssessorFirstCreationTime = null;
result.EntryDate = null;
result.GlassBreakReasonId = FANAVARAN_UNMAPPED_FIELD;
result.GlassBreakReasonId = null;
result.IsLicenseMatchWithVehicleKind = 1;
result.HasOtherCulprit = 0;
result.IsAccidentOutOfBorder = 0;
result.IsFatalAccident = 0;
result.IsOwnerChanged = FANAVARAN_UNMAPPED_FIELD;
result.IsOwnerChanged = null;
result.IsPlaqueChanged = 0;
result.IsSurplusArticleEighthLaw = FANAVARAN_UNMAPPED_FIELD;
result.IsSurplusArticleEighthLaw = null;
result.PlaqueCityId = null;
result.PlaqueKindId = null;
result.PlaqueLeftNo = null;
@@ -3397,7 +3402,7 @@ export class ClaimRequestManagementService {
result.PoliceReportSerial = null;
result.PolicyId = null;
result.PreviousPolicyEndDate = "";
result.StatusChangeDate = FANAVARAN_UNMAPPED_FIELD;
result.StatusChangeDate = null;
result.TrackingCode = null;
result.IsLicenseReplacement = 0;
result.UnknownCulpritCauseId = null;
@@ -3663,7 +3668,19 @@ export class ClaimRequestManagementService {
appName: string;
secret: string;
} = this.getTejaratnoFanavaranConfig(),
auditSession?: FanavaranAuditSession,
): Promise<string> {
const startedAt = Date.now();
if (auditSession) {
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.GET_APP_TOKEN,
status: FanavaranAuditStatus.STARTED,
requestUrl: this.GET_APP_TOKEN_URL,
requestMeta: { appName: config.appName },
});
}
try {
const requestHeaders: any = {
appname: config.appName,
@@ -3699,9 +3716,34 @@ export class ClaimRequestManagementService {
);
}
if (auditSession) {
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.GET_APP_TOKEN,
status: FanavaranAuditStatus.SUCCESS,
requestUrl: this.GET_APP_TOKEN_URL,
httpStatus: response.status,
responseMeta: { hasAppToken: true },
durationMs: Date.now() - startedAt,
});
}
this.logger.log(`Successfully obtained appToken`);
return appToken;
} catch (error) {
if (auditSession) {
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.GET_APP_TOKEN,
status: FanavaranAuditStatus.FAILURE,
requestUrl: this.GET_APP_TOKEN_URL,
httpStatus: isAxiosError(error) ? error.response?.status : undefined,
errorMessage: this.fanavaranAuditService.extractErrorMessage(error),
errorDetails: this.fanavaranAuditService.sanitizeErrorDetails(error),
durationMs: Date.now() - startedAt,
});
}
this.logger.error("Failed to get appToken", error);
if (isAxiosError(error)) {
const errorMessage =
@@ -3710,9 +3752,19 @@ export class ClaimRequestManagementService {
error.response?.data ||
error.message ||
"Failed to get appToken from external API";
throw new BadGatewayException(errorMessage);
throw new BadGatewayException(
this.fanavaranAuditService.formatErrorWithTrackingCode(
String(errorMessage),
auditSession?.trackingCode,
),
);
}
throw new BadGatewayException("Failed to get appToken from external API");
throw new BadGatewayException(
this.fanavaranAuditService.formatErrorWithTrackingCode(
"Failed to get appToken from external API",
auditSession?.trackingCode,
),
);
}
}
@@ -3725,7 +3777,19 @@ export class ClaimRequestManagementService {
username: string;
password: string;
} = this.getTejaratnoFanavaranConfig(),
auditSession?: FanavaranAuditSession,
): Promise<string> {
const startedAt = Date.now();
if (auditSession) {
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.LOGIN,
status: FanavaranAuditStatus.STARTED,
requestUrl: this.LOGIN_URL,
requestMeta: { userName: config.username },
});
}
try {
const requestHeaders: any = {
appToken: appToken,
@@ -3750,7 +3814,6 @@ export class ClaimRequestManagementService {
}),
);
// Check response headers first (authenticationToken is in headers)
const authenticationToken =
response.headers.authenticationtoken ||
response.headers.authenticationToken ||
@@ -3767,9 +3830,34 @@ export class ClaimRequestManagementService {
);
}
if (auditSession) {
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.LOGIN,
status: FanavaranAuditStatus.SUCCESS,
requestUrl: this.LOGIN_URL,
httpStatus: response.status,
responseMeta: { hasAuthenticationToken: true },
durationMs: Date.now() - startedAt,
});
}
this.logger.log(`Successfully obtained authenticationToken`);
return authenticationToken;
} catch (error) {
if (auditSession) {
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.LOGIN,
status: FanavaranAuditStatus.FAILURE,
requestUrl: this.LOGIN_URL,
httpStatus: isAxiosError(error) ? error.response?.status : undefined,
errorMessage: this.fanavaranAuditService.extractErrorMessage(error),
errorDetails: this.fanavaranAuditService.sanitizeErrorDetails(error),
durationMs: Date.now() - startedAt,
});
}
this.logger.error("Failed to login", error);
if (isAxiosError(error)) {
const errorMessage =
@@ -3778,9 +3866,19 @@ export class ClaimRequestManagementService {
error.response?.data ||
error.message ||
"Failed to login to external API";
throw new BadGatewayException(errorMessage);
throw new BadGatewayException(
this.fanavaranAuditService.formatErrorWithTrackingCode(
String(errorMessage),
auditSession?.trackingCode,
),
);
}
throw new BadGatewayException("Failed to login to external API");
throw new BadGatewayException(
this.fanavaranAuditService.formatErrorWithTrackingCode(
"Failed to login to external API",
auditSession?.trackingCode,
),
);
}
}
@@ -3796,12 +3894,31 @@ export class ClaimRequestManagementService {
location: string;
},
logPrefix: string,
auditSession?: FanavaranAuditSession,
): Promise<number | null> {
try {
const appToken = await this.getAppToken(config);
const authenticationToken = await this.login(appToken, config);
const policyInquiryUrl = `https://apimanager.iraneit.com/BimeApiManager/api/BimeApi/v2.0/common/Policies/inquiry-my-policies?InsuranceLineId=5&NationalCode=${nationalCodeOfInsurer}`;
const startedAt = Date.now();
const policyInquiryUrl = `https://apimanager.iraneit.com/BimeApiManager/api/BimeApi/v2.0/common/Policies/inquiry-my-policies?InsuranceLineId=5&NationalCode=${nationalCodeOfInsurer}`;
if (auditSession) {
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.POLICY_INQUIRY,
status: FanavaranAuditStatus.STARTED,
requestUrl: policyInquiryUrl,
requestMeta: {
corpId: config.corpId,
contractId: config.contractId,
location: config.location,
nationalCode: this.fanavaranAuditService.maskNationalCode(
nationalCodeOfInsurer,
),
},
});
}
try {
const appToken = await this.getAppToken(config, auditSession);
const authenticationToken = await this.login(appToken, config, auditSession);
this.logger.log(
`${logPrefix} Calling policy inquiry API for nationalCode: ${nationalCodeOfInsurer}`,
@@ -3827,15 +3944,55 @@ export class ClaimRequestManagementService {
this.logger.log(
`${logPrefix} Successfully retrieved PolicyId from last policy entry: ${policyId}`,
);
if (auditSession) {
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.POLICY_INQUIRY,
status: FanavaranAuditStatus.SUCCESS,
requestUrl: policyInquiryUrl,
httpStatus: response.status,
responseMeta: {
policyId,
policyCount: response.data.length,
},
durationMs: Date.now() - startedAt,
});
}
return policyId;
}
}
this.logger.warn(`${logPrefix} No PolicyId found in API response`);
if (auditSession) {
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.POLICY_INQUIRY,
status: FanavaranAuditStatus.SUCCESS,
requestUrl: policyInquiryUrl,
httpStatus: response.status,
responseMeta: {
policyId: null,
policyCount: Array.isArray(response.data) ? response.data.length : 0,
},
durationMs: Date.now() - startedAt,
});
}
return null;
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : "unknown policy inquiry error";
if (auditSession) {
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.POLICY_INQUIRY,
status: FanavaranAuditStatus.FAILURE,
requestUrl: policyInquiryUrl,
httpStatus: isAxiosError(error) ? error.response?.status : undefined,
errorMessage,
errorDetails: this.fanavaranAuditService.sanitizeErrorDetails(error),
durationMs: Date.now() - startedAt,
});
}
this.logger.warn(
`${logPrefix} Policy inquiry failed; continuing with empty PolicyId: ${errorMessage}`,
);
@@ -3956,10 +4113,28 @@ export class ClaimRequestManagementService {
async previewFanavaranSubmitV2(
claimCaseId: string,
clientKey: FanavaranClientKey,
options?: { debug?: boolean },
options?: {
debug?: boolean;
auditSession?: FanavaranAuditSession;
},
): Promise<any> {
const profile = getFanavaranClientProfile(clientKey);
const logPrefix = `[Fanavaran ${clientKey} V2] claimCaseId=${claimCaseId}`;
const auditSession =
options?.auditSession ??
({
trackingCode: this.fanavaranAuditService.generateTrackingCode(),
clientKey,
source: FanavaranAuditSource.PREVIEW,
claimCaseId,
} satisfies FanavaranAuditSession);
const buildStartedAt = Date.now();
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.BUILD_PAYLOAD,
status: FanavaranAuditStatus.STARTED,
});
try {
const debug = {
@@ -4088,6 +4263,7 @@ export class ClaimRequestManagementService {
nationalCodeOfInsurer,
profile.auth,
logPrefix,
auditSession,
);
debug.values.policyId = policyId;
debug.steps.policyInquirySucceeded = policyId !== null;