Enforce claim beneficiary access and retire unused legacy APIs

This commit is contained in:
SepehrYahyaee
2026-10-05 14:39:51 +03:30
parent 0735333467
commit a3f9aab8fb
104 changed files with 6864 additions and 13223 deletions
+170 -207
View File
@@ -7,8 +7,69 @@ import {
} from "@nestjs/common";
import { Types } from "mongoose";
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
import { ClaimSignDbService } from "src/claim-request-management/entites/db-service/claim-sign.db.service";
import { VideoCaptureDbService } from "src/claim-request-management/entites/db-service/video-capture.db.service";
import { fanavaranClaimReferences } from "src/claim-request-management/fanavaran-claim-references";
import { CreateBranchDto } from "src/client/dto/create-branch.dto";
import { BranchDbService } from "src/client/entities/db-service/branch.db.service";
import { ClientDbService } from "src/client/entities/db-service/client.db.service";
import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto";
import {
UnifiedFileStatusReportDto,
UnifiedFileStatusReportQueryDto,
} from "src/common/dto/unified-file-status-report.dto";
import { buildEnrichedDamagedParts } from "src/expert-claim/dto/claim-damaged-part.enricher";
import { enrichBlamePartiesForAgreementView } from "src/helpers/blame-party-agreement-decision";
import {
getClaimCarAngleCaptureBlob,
getDamagedPartCaptureBlob,
hasDamagedPartCapture,
type ClaimCarAngleKey,
} from "src/helpers/claim-car-angle-media";
import { serializeDamagedPartSelectionHistory } from "src/helpers/claim-damaged-part-audit";
import { toJalaliDateAndTime } from "src/helpers/date-jalali";
import {
applyListQueryV2,
isInListDateRange,
parseListDateRange,
} from "src/helpers/list-query-v2";
import {
catalogLikeKeyFromPart,
normalizeDamageSelectedParts,
} from "src/helpers/outer-damage-parts";
import {
blameCaseTouchesClient,
claimCaseTouchesClient,
} from "src/helpers/tenant-scope";
import {
countUnifiedFileStatuses,
getUnifiedFileStatusCatalog,
resolveUnifiedFileStatus,
} from "src/helpers/unified-file-status";
import { buildFileLink, resolveStoredFileUrl } from "src/helpers/urlCreator";
import { BlameRequestDbService } from "src/request-management/entities/db-service/blame-request.db.service";
import { BlameVideoDbService } from "src/request-management/entities/db-service/blame-video.db.service";
import { BlameVoiceDbService } from "src/request-management/entities/db-service/blame.voice.db.service";
import { PartyRole } from "src/request-management/entities/schema/partyRole.enum";
import { FileRating } from "src/request-management/entities/schema/request-management.schema";
import { sanitizeStoredInquiryParticipants } from "src/request-management/inquiry-participant-resolver";
import { ClaimVehicleTypeV2 } from "src/static/outer-car-parts-catalog";
import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum";
import { CaseStatus } from "src/Types&Enums/blame-request-management/caseStatus.enum";
import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum";
import { RoleEnum } from "src/Types&Enums/role.enum";
import { UserType } from "src/Types&Enums/userType.enum";
import { CallCenterAgentDbService } from "src/users/entities/db-service/call-center-agent.db.service";
import { DamageExpertDbService } from "src/users/entities/db-service/damage-expert.db.service";
import { ExpertFileActivityDbService } from "src/users/entities/db-service/expert-file-activity.db.service";
import { ExpertDbService } from "src/users/entities/db-service/expert.db.service";
import { FieldExpertDbService } from "src/users/entities/db-service/field-expert.db.service";
import { FileMakerDbService } from "src/users/entities/db-service/file-maker.db.service";
import { FileReviewerDbService } from "src/users/entities/db-service/file-reviewer.db.service";
import { RegistrarDbService } from "src/users/entities/db-service/registrar.db.service";
import { UserDbService } from "src/users/entities/db-service/user.db.service";
import { ExpertFileActivityType } from "src/users/entities/schema/expert-file-activity.schema";
import { HashService } from "src/utils/hash/hash.service";
import {
CreateBlameExpertByInsurerDto,
CreateClaimExpertByInsurerDto,
@@ -16,65 +77,6 @@ import {
CreateFileReviewerByInsurerDto,
CreateInsurerExpertDto,
} from "./dto/create-insurer-expert.dto";
import {
blameCaseTouchesClient,
claimCaseTouchesClient,
} from "src/helpers/tenant-scope";
import { BlameRequestDbService } from "src/request-management/entities/db-service/blame-request.db.service";
import { FileRating } from "src/request-management/entities/schema/request-management.schema";
import { CaseStatus } from "src/Types&Enums/blame-request-management/caseStatus.enum";
import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum";
import { DamageExpertDbService } from "src/users/entities/db-service/damage-expert.db.service";
import { ExpertDbService } from "src/users/entities/db-service/expert.db.service";
import { FieldExpertDbService } from "src/users/entities/db-service/field-expert.db.service";
import { FileMakerDbService } from "src/users/entities/db-service/file-maker.db.service";
import { FileReviewerDbService } from "src/users/entities/db-service/file-reviewer.db.service";
import { RegistrarDbService } from "src/users/entities/db-service/registrar.db.service";
import { CallCenterAgentDbService } from "src/users/entities/db-service/call-center-agent.db.service";
import { UserDbService } from "src/users/entities/db-service/user.db.service";
import { ExpertFileActivityDbService } from "src/users/entities/db-service/expert-file-activity.db.service";
import { ExpertFileActivityType } from "src/users/entities/schema/expert-file-activity.schema";
import { HashService } from "src/utils/hash/hash.service";
import { RoleEnum } from "src/Types&Enums/role.enum";
import { UserType } from "src/Types&Enums/userType.enum";
import { BlameVideoDbService } from "src/request-management/entities/db-service/blame-video.db.service";
import { BlameVoiceDbService } from "src/request-management/entities/db-service/blame.voice.db.service";
import { VideoCaptureDbService } from "src/claim-request-management/entites/db-service/video-capture.db.service";
import { ClientDbService } from "src/client/entities/db-service/client.db.service";
import { buildFileLink, resolveStoredFileUrl } from "src/helpers/urlCreator";
import { toJalaliDateAndTime } from "src/helpers/date-jalali";
import { enrichBlamePartiesForAgreementView } from "src/helpers/blame-party-agreement-decision";
import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum";
import { PartyRole } from "src/request-management/entities/schema/partyRole.enum";
import { sanitizeStoredInquiryParticipants } from "src/request-management/inquiry-participant-resolver";
import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto";
import {
UnifiedFileStatusReportDto,
UnifiedFileStatusReportQueryDto,
} from "src/common/dto/unified-file-status-report.dto";
import {
applyListQueryV2,
isInListDateRange,
parseListDateRange,
} from "src/helpers/list-query-v2";
import {
countUnifiedFileStatuses,
getUnifiedFileStatusCatalog,
resolveUnifiedFileStatus,
} from "src/helpers/unified-file-status";
import {
getClaimCarAngleCaptureBlob,
getDamagedPartCaptureBlob,
hasDamagedPartCapture,
type ClaimCarAngleKey,
} from "src/helpers/claim-car-angle-media";
import {
catalogLikeKeyFromPart,
normalizeDamageSelectedParts,
type DamageSelectedPartV2,
} from "src/helpers/outer-damage-parts";
import { ClaimVehicleTypeV2 } from "src/static/outer-car-parts-catalog";
import { ClaimSignDbService } from "src/claim-request-management/entites/db-service/claim-sign.db.service";
import {
extractExpertNamesFromBlame,
extractExpertNamesFromClaim,
@@ -84,9 +86,6 @@ import {
getEventFaLabel,
localizeTimelineMetadata,
} from "./helper/timeline-fa-labels";
import { buildEnrichedDamagedParts } from "src/expert-claim/dto/claim-damaged-part.enricher";
import { serializeDamagedPartSelectionHistory } from "src/helpers/claim-damaged-part-audit";
import { fanavaranClaimReferences } from "src/claim-request-management/fanavaran-claim-references";
@Injectable()
export class ExpertInsurerService {
@@ -150,54 +149,6 @@ export class ExpertInsurerService {
return { $or: [{ clientKey: oid }, { clientKey: str }] };
}
private async buildExpertActivityStatsMap(
tenantId: Types.ObjectId,
expertIds: string[],
): Promise<Record<string, { totalHandled: number; totalChecked: number }>> {
const events =
await this.expertFileActivityDbService.findByTenantAndExperts(
tenantId,
expertIds,
);
const stateByExpertFile = new Map<
string,
{ checked: boolean; handled: boolean }
>();
for (const e of events) {
const key = `${String(e.expertId)}:${String(e.fileId)}`;
const prev = stateByExpertFile.get(key) ?? {
checked: false,
handled: false,
};
if (e.eventType === ExpertFileActivityType.CHECKED) {
if (!prev.handled) prev.checked = true;
} else if (e.eventType === ExpertFileActivityType.UNCHECKED) {
prev.checked = false;
} else if (e.eventType === ExpertFileActivityType.HANDLED) {
prev.handled = true;
prev.checked = false;
}
stateByExpertFile.set(key, prev);
}
const result: Record<
string,
{ totalHandled: number; totalChecked: number }
> = {};
for (const expertId of expertIds) {
result[expertId] = { totalHandled: 0, totalChecked: 0 };
}
for (const [key, st] of stateByExpertFile.entries()) {
const [expertId] = key.split(":");
if (!result[expertId])
result[expertId] = { totalHandled: 0, totalChecked: 0 };
if (st.handled) result[expertId].totalHandled += 1;
else if (st.checked) result[expertId].totalChecked += 1;
}
return result;
}
private parseObjectId(value: string, label: string): Types.ObjectId {
if (!Types.ObjectId.isValid(value)) {
throw new BadRequestException(`Invalid ${label}`);
@@ -338,14 +289,6 @@ export class ExpertInsurerService {
};
}
private sanitizePartyForInsurerView(party: any) {
if (!party || typeof party !== "object") return party;
return {
...party,
vehicle: this.sanitizeVehicleInquiry(party.vehicle),
};
}
private serializeBlameExpertDecisionForInsurer(
decision: unknown,
): Record<string, unknown> | undefined {
@@ -488,39 +431,6 @@ export class ExpertInsurerService {
}
}
private insurerDamagedPartRowFromCapture(
sp: DamageSelectedPartV2,
index: number,
damagedPartsDataExpert: unknown,
selectedNormExpert: DamageSelectedPartV2[],
) {
const ck = sp.catalogKey ?? catalogLikeKeyFromPart(sp);
const cap = getDamagedPartCaptureBlob(
damagedPartsDataExpert,
ck,
selectedNormExpert,
) as { url?: string; path?: string; fileName?: string } | undefined;
const url = resolveStoredFileUrl(cap);
const link = url;
return {
index,
id: sp.id,
name: sp.name,
side: sp.side,
label_fa: sp.label_fa,
catalogKey: sp.catalogKey,
captured: hasDamagedPartCapture(
damagedPartsDataExpert,
ck,
selectedNormExpert,
),
path: cap?.path,
fileName: cap?.fileName,
url,
link,
};
}
private sanitizeDamageForInsurerDetail(damage: unknown): unknown {
if (!damage || typeof damage !== "object") return damage;
const d = { ...(damage as Record<string, unknown>) };
@@ -945,12 +855,15 @@ export class ExpertInsurerService {
};
}
private resolveReportDateRange(opts: {
from?: string;
to?: string;
periodDays?: string | number;
} = {}) {
const hasFrom = typeof opts.from === "string" && opts.from.trim().length > 0;
private resolveReportDateRange(
opts: {
from?: string;
to?: string;
periodDays?: string | number;
} = {},
) {
const hasFrom =
typeof opts.from === "string" && opts.from.trim().length > 0;
const hasTo = typeof opts.to === "string" && opts.to.trim().length > 0;
const periodDays = this.parseReportPeriodDays(opts.periodDays);
const now = new Date();
@@ -1020,7 +933,8 @@ export class ExpertInsurerService {
}))
.filter(
(event) =>
!Number.isNaN(event.occurredAt.getTime()) && event.occurredAt <= cutoff,
!Number.isNaN(event.occurredAt.getTime()) &&
event.occurredAt <= cutoff,
)
.sort((a, b) => a.occurredAt.getTime() - b.occurredAt.getTime());
@@ -1097,15 +1011,21 @@ export class ExpertInsurerService {
const clientObjectId = this.getClientId(actor);
const ckFilter = this.clientKeyScopeFilter(clientObjectId);
const range = this.resolveReportDateRange(opts);
const [experts, damageExperts, fieldExperts, blameFiles, claimFiles, activityEvents] =
await Promise.all([
this.expertDbService.findAll(ckFilter as never),
this.damageExpertDbService.findAll(ckFilter as never),
this.fieldExpertDbService.findAll(ckFilter as never),
this.getClientBlameFiles(clientObjectId),
this.getClientClaimFiles(clientObjectId),
this.expertFileActivityDbService.findByTenant(clientObjectId),
]);
const [
experts,
damageExperts,
fieldExperts,
blameFiles,
claimFiles,
activityEvents,
] = await Promise.all([
this.expertDbService.findAll(ckFilter as never),
this.damageExpertDbService.findAll(ckFilter as never),
this.fieldExpertDbService.findAll(ckFilter as never),
this.getClientBlameFiles(clientObjectId),
this.getClientClaimFiles(clientObjectId),
this.expertFileActivityDbService.findByTenant(clientObjectId),
]);
const roster = [
...(experts as any[]).map((expert) => ({
@@ -1135,9 +1055,15 @@ export class ExpertInsurerService {
];
const rosterById = new Map(
roster.map((expert) => [expert._id, { ...expert, ...this.emptyExpertCaseBreakdown() }]),
roster.map((expert) => [
expert._id,
{ ...expert, ...this.emptyExpertCaseBreakdown() },
]),
);
const fileState = this.buildExpertFileStateMap(
activityEvents as any[],
range.toDate,
);
const fileState = this.buildExpertFileStateMap(activityEvents as any[], range.toDate);
const blameFilesInRange = blameFiles.filter((file) =>
this.isInDateRange(file?.createdAt, range.fromDate, range.toDate),
@@ -1147,8 +1073,8 @@ export class ExpertInsurerService {
);
for (const file of blameFilesInRange as any[]) {
const expertIds = this.blameFieldExpertIdCandidates(file).filter((expertId) =>
rosterById.has(expertId),
const expertIds = this.blameFieldExpertIdCandidates(file).filter(
(expertId) => rosterById.has(expertId),
);
for (const expertId of new Set(expertIds)) {
const row = rosterById.get(expertId);
@@ -1295,14 +1221,18 @@ export class ExpertInsurerService {
async getTopFilesForClient(
insurerId: string,
opts: { from?: string; to?: string; periodDays?: string | number } = {},
): Promise<Array<{
publicId: string;
createdAt: string;
combinedScore: number;
userRating: { comment: string | null; overallEvaluation: number | null };
}>> {
): Promise<
Array<{
publicId: string;
createdAt: string;
combinedScore: number;
userRating: { comment: string | null; overallEvaluation: number | null };
}>
> {
const range = this.resolveReportDateRange(opts);
let claimFiles = await this.getClientClaimFiles(this.getClientId(insurerId));
let claimFiles = await this.getClientClaimFiles(
this.getClientId(insurerId),
);
claimFiles = claimFiles.filter((file) =>
this.isInDateRange(file.createdAt, range.fromDate, range.toDate),
@@ -1403,7 +1333,11 @@ export class ExpertInsurerService {
}
const handledAt = this.portfolioFileHandledAt(file, handledAtByFileId);
if (!handledAt || handledAt < range.fromDate || handledAt > range.toDate) {
if (
!handledAt ||
handledAt < range.fromDate ||
handledAt > range.toDate
) {
continue;
}
if (Number.isNaN(createdAt.getTime())) continue;
@@ -1512,9 +1446,11 @@ export class ExpertInsurerService {
// files they handled is the correct scope.
const [allBlames, allClaims] = await Promise.all([
onBlameRoster
? (this.blameRequestDbService.find({}, { lean: true }) as Promise<any[]>)
? (this.blameRequestDbService.find({}, { lean: true }) as Promise<
any[]
>)
: Promise.resolve([] as any[]),
(this.claimCaseDbService.find({}, { lean: true }) as Promise<any[]>),
this.claimCaseDbService.find({}, { lean: true }) as Promise<any[]>,
]);
const result: any[] = [];
@@ -1801,11 +1737,12 @@ export class ExpertInsurerService {
let files = await this.buildMergedInsurerFiles(id);
if (query.unifiedStatus) {
files = files.filter(
(f) => f.unifiedFileStatus === query.unifiedStatus,
);
files = files.filter((f) => f.unifiedFileStatus === query.unifiedStatus);
}
const { fromDate, toDate } = parseListDateRange(query.startDate, query.endDate);
const { fromDate, toDate } = parseListDateRange(
query.startDate,
query.endDate,
);
if (fromDate || toDate) {
files = files.filter((f) =>
isInListDateRange(f.createdAt, fromDate, toDate),
@@ -2167,7 +2104,9 @@ export class ExpertInsurerService {
const email = payload.email.trim().toLowerCase();
const existing = await this.fileMakerDbService.findOne({ email });
if (existing) {
throw new ConflictException("A FileMaker with this email already exists.");
throw new ConflictException(
"A FileMaker with this email already exists.",
);
}
const nationalCode = payload.nationalCode.trim();
@@ -2304,8 +2243,9 @@ export class ExpertInsurerService {
thirdPartyFiles: summary.thirdPartyFiles,
carBodyFiles: summary.carBodyFiles,
totalFiles: summary.totalFiles,
activeExperts: expertReport.experts.filter((expert) => expert.totalFiles > 0)
.length,
activeExperts: expertReport.experts.filter(
(expert) => expert.totalFiles > 0,
).length,
reviewedFiles: summary.reviewedFiles,
unreviewedFiles: summary.unreviewedFiles,
thirdPartyReviewedFiles: summary.thirdPartyReviewedFiles,
@@ -2501,17 +2441,18 @@ export class ExpertInsurerService {
};
}
private static readonly TIMELINE_PERFORMER_FA_LABELS: Record<string, string> = {
user: "کاربر",
field_expert: "کارشناس میدانی",
damage_expert: "کارشناس خسارت",
file_maker: "پرونده‌ساز",
file_reviewer: "بازبین پرونده",
registrar: "ثبت‌کننده",
call_center: "اپراتور کال‌سنتر",
system: "سیستم",
expert: "کارشناس",
};
private static readonly TIMELINE_PERFORMER_FA_LABELS: Record<string, string> =
{
user: "کاربر",
field_expert: "کارشناس میدانی",
damage_expert: "کارشناس خسارت",
file_maker: "پرونده‌ساز",
file_reviewer: "بازبین پرونده",
registrar: "ثبت‌کننده",
call_center: "اپراتور کال‌سنتر",
system: "سیستم",
expert: "کارشناس",
};
/**
* Returns the most specific actor role recorded in history so the frontend can
@@ -2527,7 +2468,8 @@ export class ExpertInsurerService {
private static resolveTimelinePerformedByCategory(
actorType: string | undefined,
): "user" | "expert" | "staff" | "system" | null {
const performedBy = ExpertInsurerService.resolveTimelinePerformedBy(actorType);
const performedBy =
ExpertInsurerService.resolveTimelinePerformedBy(actorType);
if (!performedBy) return null;
if (performedBy === "user") return "user";
if (performedBy === "system") return "system";
@@ -2544,7 +2486,8 @@ export class ExpertInsurerService {
private static resolveTimelinePerformedByFaLabel(
actorType: string | undefined,
): string | null {
const performedBy = ExpertInsurerService.resolveTimelinePerformedBy(actorType);
const performedBy =
ExpertInsurerService.resolveTimelinePerformedBy(actorType);
if (!performedBy) return null;
return (
ExpertInsurerService.TIMELINE_PERFORMER_FA_LABELS[performedBy] ??
@@ -2581,7 +2524,9 @@ export class ExpertInsurerService {
return combined || null;
}
private static isMeaningfulTimelineActorName(name: string | undefined): boolean {
private static isMeaningfulTimelineActorName(
name: string | undefined,
): boolean {
const trimmed = typeof name === "string" ? name.trim() : "";
if (!trimmed) return false;
return !ExpertInsurerService.TIMELINE_PLACEHOLDER_ACTOR_NAMES.has(
@@ -2589,7 +2534,10 @@ export class ExpertInsurerService {
);
}
private static resolveBlamePartyName(sourceDoc: any, partyRole?: string): string | null {
private static resolveBlamePartyName(
sourceDoc: any,
partyRole?: string,
): string | null {
const parties = Array.isArray(sourceDoc?.parties) ? sourceDoc.parties : [];
const normalizedPartyRole =
typeof partyRole === "string" ? partyRole.trim().toUpperCase() : "";
@@ -2597,7 +2545,9 @@ export class ExpertInsurerService {
const matchedParty = normalizedPartyRole
? parties.find(
(party: any) =>
String(party?.role ?? "").trim().toUpperCase() === normalizedPartyRole,
String(party?.role ?? "")
.trim()
.toUpperCase() === normalizedPartyRole,
)
: null;
@@ -2629,7 +2579,16 @@ export class ExpertInsurerService {
}
const objectId = new Types.ObjectId(actorId);
const [fileMaker, fileReviewer, registrar, callCenter, fieldExpert, damageExpert, expert, user] = await Promise.all([
const [
fileMaker,
fileReviewer,
registrar,
callCenter,
fieldExpert,
damageExpert,
expert,
user,
] = await Promise.all([
this.fileMakerDbService.findById(actorId),
this.fileReviewerDbService.findById(actorId),
this.registrarDbService.findById(actorId),
@@ -2861,7 +2820,9 @@ export class ExpertInsurerService {
actorName,
performedBy,
performedByCategory:
ExpertInsurerService.resolveTimelinePerformedByCategory(performedBy),
ExpertInsurerService.resolveTimelinePerformedByCategory(
performedBy,
),
performedByFaLabel:
ExpertInsurerService.resolveTimelinePerformedByFaLabel(performedBy),
metadata: localizeTimelineMetadata(ev),
@@ -2899,7 +2860,9 @@ export class ExpertInsurerService {
actorName,
performedBy,
performedByCategory:
ExpertInsurerService.resolveTimelinePerformedByCategory(performedBy),
ExpertInsurerService.resolveTimelinePerformedByCategory(
performedBy,
),
performedByFaLabel:
ExpertInsurerService.resolveTimelinePerformedByFaLabel(performedBy),
metadata: localizeTimelineMetadata(ev),