Files
yara724-api/src/expert-claim/expert-claim.service.ts
T

5002 lines
179 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use strict";
import { hasReviewedTejaratNotifier } from "src/fanavaran/tejarat-notifier";
import { resolveFanavaranClientKey } from "src/core/config/fanavaran-client.config";
import {
BadRequestException,
ConflictException,
ForbiddenException,
HttpException,
HttpStatus,
Injectable,
Logger,
NotFoundException,
} from "@nestjs/common";
import { Types } from "mongoose";
import { resolveClaimVehicleSources } from "src/helpers/claim-vehicle-identity";
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
import { ClaimRequestManagementDbService } from "src/claim-request-management/entites/db-service/claim-request-management.db.service";
import { ClaimSignDbService } from "src/claim-request-management/entites/db-service/claim-sign.db.service";
import { ClaimFactorsImageDbService } from "src/claim-request-management/entites/db-service/factor-image.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 { BranchDbService } from "src/client/entities/db-service/branch.db.service";
import {
ExpertFileAssignResultDto,
ExpertFileAssignStatus,
} from "src/common/dto/expert-file-assign-result.dto";
import { FanavaranLocationService } from "src/fanavaran/fanavaran-location.service";
import {
buildMutualAgreementExpertDecision,
enrichBlamePartiesForAgreementView,
} from "src/helpers/blame-party-agreement-decision";
import {
getClaimCarAngleCaptureBlob,
getDamagedPartCaptureBlob,
hasDamagedPartCapture,
type ClaimCarAngleKey,
} from "src/helpers/claim-car-angle-media";
import {
buildDamagedPartSelectionRevision,
serializeDamagedPartSelectionHistory,
} from "src/helpers/claim-damaged-part-audit";
import {
normalizeResendCarPartsForStorage,
normalizeResendDocumentKeys,
resendRequestHasPayload,
} from "src/helpers/claim-expert-resend";
import {
buildCoefficientsFromPartSeverities,
buildDamagedPartsPriceDropLines,
buildPriceDropCatalogForApi,
calculateClaimPriceDrop,
calculatePriceDropForVehicleAge,
parsePriceDropNumber,
PRICE_DROP_SEVERITY_OPTIONS,
resolveVehicleModelYearFromBlame,
resolvePriceDropAccidentYear,
resolvePriceDropAccidentDate,
normalizePriceDropSelectedParts,
resolveClaimPriceDropAge,
buildAgeIneligiblePriceDrop,
PRICE_DROP_AGE_INELIGIBLE_MESSAGE,
} from "src/helpers/claim-price-drop";
import { FANAVARAN_PRICE_DROP_AGES, FANAVARAN_PRICE_DROP_VERSION, FANAVARAN_PRICE_DROP_AGE_EFFECTIVE_FROM } from "src/static/fanavaran-price-drop";
import {
claimCaseStatusAfterExpertReplyV2,
claimIsAwaitingExpertFactorValidationV2,
classifyV2ExpertPricingParts,
} from "src/helpers/claim-v2-expert-reply-workflow";
import { toJalaliDateAndTime } from "src/helpers/date-jalali";
import {
claimCaseStatusToReportBucket,
initialClaimExpertReportBuckets,
} from "src/helpers/expert-panel-status-report";
import {
claimDocInExpertPortfolio,
expertPortfolioFileIdsFromActivityEvents,
objectIdsFromStringSet,
} from "src/helpers/expert-portfolio";
import { snapshotFromDamageExpert } from "src/helpers/expert-profile-snapshot";
import { EXPERT_WORKFLOW_LOCK_TTL_MS } from "src/helpers/expert-workflow-lock";
import {
buildExpertAssignConflictForOtherReviewer,
CLAIM_REVIEW_ASSIGNED_HISTORY_TYPE,
claimWorkflowAssigneeToPersistOnLockExpiry,
resolvePersistentReviewAssigneeId,
} from "src/helpers/expert-workflow-review-assignee";
import {
catalogLikeKeyFromPart,
catalogPartIdFromCarPartDamage,
coerceDamagedPartsMediaToArray,
normalizeCarPartDamageForExpertReply,
normalizeDamageSelectedParts,
partLookupKey,
resolvePartForExpertReply,
sameCatalogPartId,
sanitizeDamageSelectedPartV2,
type DamageSelectedPartV2,
} from "src/helpers/outer-damage-parts";
import {
assertClaimCaseForExpertActor,
assertClaimCaseForTenant,
blameCaseTouchesClient,
claimCaseInitiatedByFieldExpert,
claimCaseTouchesClient,
requireActorClientKey,
} from "src/helpers/tenant-scope";
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 { sanitizeStoredInquiryParticipants } from "src/request-management/inquiry-participant-resolver";
import { SmsOrchestrationService } from "src/sms-orchestration/sms-orchestration.service";
import { ClaimVehicleTypeV2 } from "src/static/outer-car-parts-catalog";
import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum";
import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum";
import { ClaimWorkflowStep } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum";
import { ClaimStatus } from "src/Types&Enums/claim-request-management/claimStatus.enum";
import { DaghiOption } from "src/Types&Enums/claim-request-management/daghi-option.enum";
import { FactorStatus } from "src/Types&Enums/claim-request-management/factor-status.enum";
import { ClaimRequiredDocumentType } from "src/Types&Enums/claim-request-management/required-document-type.enum";
import { ReqClaimStatus } from "src/Types&Enums/claim-request-management/status.enum";
import { TypeOfDamage } from "src/Types&Enums/claim-request-management/type-of-damage.enum";
import { RoleEnum } from "src/Types&Enums/role.enum";
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 { UserDbService } from "src/users/entities/db-service/user.db.service";
import { DamageExpertModel } from "src/users/entities/schema/damage-expert.schema";
import {
ExpertFileActivityType,
ExpertFileKind,
} from "src/users/entities/schema/expert-file-activity.schema";
import { ClaimDetailV2ResponseDto } from "./dto/claim-detail-v2.dto";
import {
ClaimListItemV2Dto,
GetClaimListV2ResponseDto,
} from "./dto/claim-list-v2.dto";
import { UpsertClaimPriceDropV2Dto } from "./dto/claim-price-drop-v2.dto";
import { ClaimSubmitResendV2Dto } from "./dto/expert-claim-v2.dto";
import { FactorValidationV2Dto } from "./dto/factor-validation.dto";
import { UpdateClaimDamagedPartsV2Dto } from "./dto/update-claim-damaged-parts-v2.dto";
import {
BusinessErrorCode,
BusinessRuleException,
} from "./exceptions/business-rule.exception";
/** Configured V1 maximum sum of line `totalPayment` across the claim (Rial). */
/** Configured V1 maximum sum of line `totalPayment` across the claim (Rial). */
/** Configured V1 maximum sum of line `totalPayment` across the claim (Rial). */
/** Configured V1 maximum sum of line `totalPayment` across the claim (Rial). */
import {
fanavaranFieldStageSent,
type FanavaranFieldReview,
type FanavaranFieldValues,
} from "src/claim-request-management/fanavaran-stage-fields";
import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto";
import {
UnifiedFileStatusReportDto,
UnifiedFileStatusReportQueryDto,
} from "src/common/dto/unified-file-status-report.dto";
import { getClaimV2TotalPaymentCapToman } from "src/constants/repair-amount-limits";
import { claimPriceCapAppliesToBlame } from "src/helpers/claim-price-cap";
import { canonicalizeResendDocumentKey } from "src/helpers/claim-resend-document-keys";
import { getExpertReplyPricingValidationError } from "src/helpers/expert-reply-pricing";
import {
applyListQueryV2,
isInListDateRange,
parseListDateRange,
} from "src/helpers/list-query-v2";
import { toPublicListItems } from "src/helpers/public-list-response";
import {
countUnifiedFileStatuses,
getUnifiedFileStatusCatalog,
resolveUnifiedFileStatus,
} from "src/helpers/unified-file-status";
import { LookupsService } from "src/lookups/lookups.service";
import {
normalizeMoneyAmountString,
parseMoneyAmountToman,
} from "src/utils/unicode-digits";
import { buildEnrichedDamagedParts } from "./dto/claim-damaged-part.enricher";
import { UpdateFanavaranStageFieldsDto } from "./dto/fanavaran-stage-fields.dto";
import { ApproveFanavaranVehicleReviewDto } from "./dto/fanavaran-vehicle-review.dto";
import {
buildFanavaranVehicleSuggestion,
collectFanavaranVehicleInquiryRecords,
} from "./fanavaran-vehicle-suggestion";
@Injectable()
export class ExpertClaimService {
private readonly logger = new Logger(ExpertClaimService.name);
constructor(
private readonly blameVoiceDbService: BlameVoiceDbService,
private readonly claimRequestManagementDbService: ClaimRequestManagementDbService,
private readonly blameVideoDbService: BlameVideoDbService,
private readonly claimVideoCaptureDbService: VideoCaptureDbService,
private readonly claimCaseDbService: ClaimCaseDbService,
private readonly blameRequestDbService: BlameRequestDbService,
private readonly damageExpertDbService: DamageExpertDbService,
private readonly claimFactorsImageDbService: ClaimFactorsImageDbService,
private readonly branchDbService: BranchDbService,
private readonly smsOrchestrationService: SmsOrchestrationService,
private readonly userDbService: UserDbService,
private readonly expertFileActivityDbService: ExpertFileActivityDbService,
private readonly claimSignDbService: ClaimSignDbService,
private readonly claimRequestManagementService: ClaimRequestManagementService,
private readonly fanavaranLocationService: FanavaranLocationService,
private readonly lookupsService: LookupsService,
) {}
/**
* Resolve a `claim-sign` document id to a downloadable file URL.
* Mirrors the helper used in `ExpertInsurerService` so signature links are
* exposed identically across the two expert-facing detail endpoints.
*/
private async claimSignLinkFromId(
signDetailId: unknown,
): Promise<string | undefined> {
if (signDetailId == null || signDetailId === "") return undefined;
const id = String(signDetailId);
if (!Types.ObjectId.isValid(id)) return undefined;
const doc = await this.claimSignDbService.findOne({
_id: new Types.ObjectId(id),
});
const path = (doc as any)?.path;
return path ? buildFileLink(String(path)) : undefined;
}
/**
* Build a deep-cloned `evaluation` payload with resolved file URLs the
* front-end can render directly:
*
* - `damageExpertReply.userComment.signLink`
* - `damageExpertReplyFinal.userComment.signLink`
* - `ownerInsurerApproval.signLink`
* - `ownerPricedPartsApproval.signLink`
* - `damageExpertReply.parts[i].factorLink` (ObjectId → URL)
* - `damageExpertReplyFinal.parts[i].factorLink` (ObjectId → URL)
*
* Returns `undefined` when there's no evaluation to enrich.
*/
private async enrichClaimEvaluationForExpert(
evaluation: Record<string, unknown> | undefined | null,
): Promise<Record<string, unknown> | undefined> {
if (!evaluation || typeof evaluation !== "object") return undefined;
const ev = JSON.parse(JSON.stringify(evaluation)) as Record<
string,
unknown
>;
const enrichReply = async (key: string) => {
const reply = ev[key] as Record<string, unknown> | undefined;
if (!reply) return;
const uc = reply.userComment as Record<string, unknown> | undefined;
if (uc?.signDetailId != null) {
const signLink = await this.claimSignLinkFromId(uc.signDetailId);
reply.userComment = { ...uc, signLink };
}
// Resolve each `parts[].factorLink` ObjectId to a downloadable URL.
// `populateFactorLinks` mutates in place — safe here because `ev` was
// deep-cloned via JSON above, so we never touch the live mongoose doc.
await this.populateFactorLinks(reply);
};
await enrichReply("damageExpertReply");
await enrichReply("damageExpertReplyFinal");
const enrichApproval = async (key: string) => {
const o = ev[key] as Record<string, unknown> | undefined;
if (o?.signDetailId != null) {
const signLink = await this.claimSignLinkFromId(o.signDetailId);
ev[key] = { ...o, signLink };
}
};
await enrichApproval("ownerInsurerApproval");
await enrichApproval("ownerPricedPartsApproval");
// Resolve objection invoice paths to downloadable URLs.
const objection = ev.objection as Record<string, unknown> | undefined;
if (objection) {
const invoices = objection.invoices as
| Array<Record<string, unknown>>
| undefined;
if (Array.isArray(invoices) && invoices.length > 0) {
ev.objection = {
...objection,
invoices: invoices.map((inv) => ({
...inv,
url: inv.path ? buildFileLink(inv.path as string) : undefined,
})),
};
}
}
return ev;
}
/** Load linked blame when resolving field-expert ownership on a claim. */
private async loadBlameForClaim(
claim: { blameRequestId?: unknown } | null | undefined,
) {
const id = claim?.blameRequestId?.toString?.();
if (!id) return null;
return this.blameRequestDbService.findById(id);
}
private async assertExpertActorOnClaim(
claim: any,
actor: any,
): Promise<void> {
const blame = await this.loadBlameForClaim(claim);
// FILE_REVIEWER: by the time we reach this method the caller has already
// verified that actor.sub === blame.assignedFileReviewerId (Phase 2 of
// assignClaimForReviewV2). The generic tenant-scope check would incorrectly
// reject them because initiatedByFieldExpertId belongs to the FileMaker, not
// the reviewer. Skip it — the assignment check is the access proof.
if ((actor as any).role === RoleEnum.FILE_REVIEWER) {
await this.assertActorBranchAccess(claim, actor, blame);
return;
}
assertClaimCaseForExpertActor(claim, actor, blame);
await this.assertActorBranchAccess(claim, actor, blame);
}
private async assertActorBranchAccess(
claim: any,
actor: any,
blame?: any,
): Promise<void> {
const caseBranchId = claim?.branchId
? String(claim.branchId)
: blame?.branchId
? String(blame.branchId)
: undefined;
if (actor?.role === RoleEnum.FILE_REVIEWER) {
await this.fanavaranLocationService.assertMakerReviewerBranchCompatible({
fileMakerId: blame?.initiatedByFieldExpertId
? String(blame.initiatedByFieldExpertId)
: null,
fileReviewerId: String(actor.sub),
caseBranchId,
});
return;
}
if (actor?.role === RoleEnum.FILE_MAKER) {
const actorBranchId =
await this.fanavaranLocationService.fileMakerBranchId(
String(actor.sub),
);
if (!actorBranchId || (caseBranchId && caseBranchId !== actorBranchId)) {
throw new ForbiddenException("This file belongs to another branch.");
}
return;
}
if (actor?.role === RoleEnum.FIELD_EXPERT) return;
const damageExpert = await this.damageExpertDbService.findById(
String(actor.sub),
);
const actorBranchId = (damageExpert as any)?.branchId
? String((damageExpert as any).branchId)
: undefined;
if (!actorBranchId) {
throw new ForbiddenException(
"DamageExpert account is not assigned to a branch.",
);
}
// Ordinary user-created legacy claims have no branch snapshot. Preserve
// their existing tenant queue; branch-created claims must match exactly.
if (caseBranchId && caseBranchId !== actorBranchId) {
throw new ForbiddenException("This file belongs to another branch.");
}
}
private async filterDamageExpertClaimsByBranch(
claims: any[],
actor: any,
): Promise<any[]> {
const damageExpert = await this.damageExpertDbService.findById(
String(actor.sub),
);
const actorBranchId = (damageExpert as any)?.branchId
? String((damageExpert as any).branchId)
: undefined;
if (!actorBranchId) {
throw new ForbiddenException(
"DamageExpert account is not assigned to a branch.",
);
}
const missingBranchBlameIds = [
...new Set(
claims
.filter((claim) => !claim?.branchId && claim?.blameRequestId)
.map((claim) => String(claim.blameRequestId)),
),
];
const blames = missingBranchBlameIds.length
? ((await this.blameRequestDbService.find(
{
_id: {
$in: missingBranchBlameIds.map((id) => new Types.ObjectId(id)),
},
},
{
lean: true,
select: "_id branchId isMadeByFileMaker initiatedByFieldExpertId",
},
)) as any[])
: [];
const blameById = new Map(
blames.map((blame) => [String(blame._id), blame] as const),
);
const makerBranchById = new Map<string, string | undefined>();
await Promise.all(
[
...new Set(
blames
.filter(
(blame) =>
blame.isMadeByFileMaker &&
!blame.branchId &&
blame.initiatedByFieldExpertId,
)
.map((blame) => String(blame.initiatedByFieldExpertId)),
),
].map(async (makerId) => {
makerBranchById.set(
makerId,
await this.fanavaranLocationService.fileMakerBranchId(makerId),
);
}),
);
return claims.filter((claim) => {
let caseBranchId = claim?.branchId ? String(claim.branchId) : undefined;
if (!caseBranchId && claim?.blameRequestId) {
const blame = blameById.get(String(claim.blameRequestId));
caseBranchId = blame?.branchId
? String(blame.branchId)
: blame?.isMadeByFileMaker && blame?.initiatedByFieldExpertId
? makerBranchById.get(String(blame.initiatedByFieldExpertId))
: undefined;
}
return !caseBranchId || caseBranchId === actorBranchId;
});
}
private async fieldExpertOwnsClaim(
claim: any,
actor: { sub: string },
): Promise<boolean> {
const blame = await this.loadBlameForClaim(claim);
return claimCaseInitiatedByFieldExpert(claim, actor, blame);
}
/** Load immutable profile fields from `damage-expert` for the acting expert. */
private async snapshotDamageExpert(actorId: string) {
const doc = await this.damageExpertDbService.findById(actorId);
return snapshotFromDamageExpert(doc as DamageExpertModel);
}
private async recordClaimExpertActivity(args: {
expertId: string;
tenantId: string;
claimId: string;
eventType: ExpertFileActivityType;
idempotencyKey?: string;
}): Promise<void> {
if (
!Types.ObjectId.isValid(args.expertId) ||
!Types.ObjectId.isValid(args.tenantId) ||
!Types.ObjectId.isValid(args.claimId)
) {
return;
}
await this.expertFileActivityDbService.recordEvent({
expertId: args.expertId,
tenantId: args.tenantId,
fileId: args.claimId,
fileType: ExpertFileKind.CLAIM,
eventType: args.eventType,
idempotencyKey: args.idempotencyKey,
});
}
/**
* Insurer tenant id stored on claim file-activity rows. Prefer `owner.userClientKey`
* so V2 events line up with `expireClaimWorkflowLockV2IfStale` and insurer `findByTenant`.
*/
private claimActivityTenantId(
claim: { owner?: { userClientKey?: unknown } } | null | undefined,
actor: { clientKey?: string },
): string {
const fromOwner = claim?.owner?.userClientKey;
if (fromOwner != null && String(fromOwner).length > 0) {
return String(fromOwner);
}
return String(actor.clientKey ?? "");
}
/**
* `preLockQueueSnapshot` must only store {@link ClaimWorkflowStep} values.
* Legacy / mistaken data sometimes put {@link ClaimCaseStatus} (e.g. WAITING_FOR_DAMAGE_EXPERT)
* in `workflow.currentStep`, which would fail Mongoose enum validation when snapshotted.
*/
private normalizeClaimWorkflowStepForSnapshot(
value: unknown,
fallback: ClaimWorkflowStep,
): ClaimWorkflowStep {
if (
typeof value === "string" &&
(Object.values(ClaimWorkflowStep) as string[]).includes(value)
) {
return value as ClaimWorkflowStep;
}
return fallback;
}
/** Damaged-party mobile for claim SMS: prefer `damagedPartyUserId`, else `owner.userId`. */
private async resolveClaimOwnerPhone(
claim: any,
): Promise<string | undefined> {
const notifyUserId = claim?.damagedPartyUserId ?? claim?.owner?.userId;
if (!notifyUserId) return undefined;
const ownerUserId = String(notifyUserId);
if (claim.blameRequestId) {
const blame = await this.blameRequestDbService.findById(
claim.blameRequestId.toString(),
);
const ownerParty = (blame?.parties || []).find(
(p: any) =>
p?.person?.userId && String(p.person.userId) === ownerUserId,
);
const fromParty = ownerParty?.person?.phoneNumber;
if (fromParty && typeof fromParty === "string") return fromParty;
}
const user = await this.userDbService.findOne({
_id: new Types.ObjectId(ownerUserId),
});
const m = user?.mobile;
if (m && typeof m === "string") return m;
return undefined;
}
private vehicleForExpertFromClaimAndBlameMap(
claim: any,
blameById: Map<string, any>,
): {
carName?: string;
carModel?: string;
carType?: string;
plate?: { plateId?: string };
} {
const blame = blameById.get(String(claim?.blameRequestId ?? ""));
const { identity, vehicle, snapshot } = resolveClaimVehicleSources(
claim,
blame,
);
const plateId = vehicle?.plateId;
return {
carName: identity.name,
carModel: identity.model,
carType: claim?.vehicle?.carType ?? identity.type,
...(snapshot.plate
? { plate: snapshot.plate }
: plateId
? { plate: { plateId: String(plateId) } }
: {}),
};
}
/**
* Blame file kind for damage-expert UI: THIRD_PARTY vs CAR_BODY, and CAR_BODY first-step flags.
*/
private blameFileContextForExpert(blame: any): {
blameRequestType?: BlameRequestType;
creationMethod?: string;
carBodyFirstForm?: { car?: boolean; object?: boolean };
blameStatus?: string;
partyIdentities?: Array<Record<string, unknown>>;
} {
if (!blame?.type) return {};
const blameRequestType = blame.type as BlameRequestType;
const out: {
blameRequestType?: BlameRequestType;
creationMethod?: string;
carBodyFirstForm?: { car?: boolean; object?: boolean };
blameStatus?: string;
partyIdentities?: Array<Record<string, unknown>>;
} = { blameRequestType };
if (blame.creationMethod) out.creationMethod = blame.creationMethod;
out.blameStatus = blame.blameStatus;
const parties = blame.parties;
if (Array.isArray(parties) && parties.length > 0) {
out.partyIdentities = parties.map((party: any) => ({
phoneNumber: party?.person?.phoneNumber,
nationalCode: party?.person?.nationalCode,
nationalCodeOfInsurer: party?.person?.nationalCodeOfInsurer,
nationalCodeOfDriver: party?.person?.nationalCodeOfDriver,
participants: (Array.isArray(party?.participants)
? party.participants
: party?.inquiryParticipants
)?.map((participant: any) => ({
phoneNumber: participant?.phoneNumber,
nationalCode: participant?.nationalCode,
nationalCodeOfInsurer: participant?.nationalCodeOfInsurer,
nationalCodeOfDriver: participant?.nationalCodeOfDriver,
})),
}));
}
if (blameRequestType !== BlameRequestType.CAR_BODY) return out;
if (!Array.isArray(parties) || parties.length === 0) return out;
const first =
parties.find((p: any) => p?.role === PartyRole.FIRST) ?? parties[0];
const cbf = first?.carBodyFirstForm;
delete out.blameStatus;
if (cbf && typeof cbf === "object") {
out.carBodyFirstForm = {
...(typeof cbf.car === "boolean" ? { car: cbf.car } : {}),
...(typeof cbf.object === "boolean" ? { object: cbf.object } : {}),
};
}
return out;
}
parsePersianNumber(input: string): number {
return Number(
input
.replace(/[۰-۹]/g, (d) => String.fromCharCode(d.charCodeAt(0) - 1728))
.replace(/,/g, ""),
);
}
private expertReplySubmissionError(
message: string,
code: string,
details: Record<string, unknown> = {},
) {
return {
message,
error: "EXPERT_REPLY_SUBMISSION_ERROR",
code,
...details,
};
}
/** Factor validation: expert must send a line amount (OCR is not used for factor photos). */
private expertFactorValidationDecisionHasLinePricing(decision: {
totalPayment?: string;
price?: string;
salary?: string;
}): boolean {
const tp =
decision.totalPayment != null &&
String(decision.totalPayment).trim() !== "";
const pr = decision.price != null && String(decision.price).trim() !== "";
const sa = decision.salary != null && String(decision.salary).trim() !== "";
return tp || (pr && sa);
}
/** Price-cap total for one reply line: `totalPayment` if set, otherwise `price` + `salary`. */
private claimReplyPartLineTotalForCap(part: {
partId?: number | string;
totalPayment?: unknown;
price?: unknown;
salary?: unknown;
}): number {
const tpRaw =
part.totalPayment != null ? String(part.totalPayment).trim() : "";
if (tpRaw !== "") {
return this.parsePersianNumber(tpRaw);
}
const pr = this.parsePersianNumber(String(part.price ?? "0"));
const sa = this.parsePersianNumber(String(part.salary ?? "0"));
return pr + sa;
}
/** Same rules as V1 `submitReplyRequest`: daghi option plus conditional price. */
private validateAndNormalizeDaghiForExpertReplyV2(
parts: import("./dto/expert-claim-v2.dto").PartPricingV2Dto[],
) {
for (const [partIndex, part] of parts.entries()) {
if (part.typeOfDamage === TypeOfDamage.Repair) continue;
if (!part.daghi || !part.daghi.option) {
throw new BadRequestException(
this.expertReplySubmissionError(
`گزینه داغی برای قطعه ${part.partId} الزامی است.`,
"DAGHI_OPTION_REQUIRED",
{ field: `parts[${partIndex}].daghi.option`, partId: part.partId },
),
);
}
if (part.daghi.option === DaghiOption.RECYCLED_PARTS_VALUE) {
if (!part.daghi.price) {
throw new BadRequestException(
this.expertReplySubmissionError(
`قیمت داغی برای قطعه ${part.partId} الزامی است.`,
"DAGHI_PRICE_REQUIRED",
{
field: `parts[${partIndex}].daghi.price`,
partId: part.partId,
},
),
);
}
}
}
return parts.map((part) => {
if (part.typeOfDamage === TypeOfDamage.Repair) {
const { daghi: _daghi, ...repairPart } = part;
return repairPart;
}
return {
...part,
daghi: {
option: part.daghi!.option,
...(part.daghi!.price && { price: part.daghi!.price }),
},
};
});
}
async imageRequired(requestId, currentUser) {
const request =
await this.claimRequestManagementDbService.findOneDocument(requestId);
if (!request) {
throw new HttpException(
{ responseCode: 1006, message: "Request not found" },
HttpStatus.NOT_FOUND,
);
}
if (this.isCurrentUserAllowed(request, currentUser)) {
return (await this.claimRequestManagementDbService.findOne(requestId))
.imageRequired;
} else if (this.isRequestLocked(request, currentUser)) {
throw new HttpException(
{ responseCode: 1007, message: "Request is locked" },
HttpStatus.FORBIDDEN,
);
} else {
throw new HttpException(
{ responseCode: 1008, message: "notAllowed is locked" },
HttpStatus.FORBIDDEN,
);
}
}
private async populateFactorLinks(reply: any): Promise<void> {
if (!reply || !Array.isArray(reply.parts)) {
return;
}
for (const part of reply.parts) {
if (part.factorLink && Types.ObjectId.isValid(part.factorLink)) {
const factorDoc = await this.claimFactorsImageDbService.findById(
part.factorLink.toString(),
);
if (factorDoc) {
part.factorLink = buildFileLink(factorDoc.path);
}
}
}
}
private isCurrentUserAllowed(request: any, currentUser: any): boolean {
// Check if locked by current user and lock is still active
const isLockedByCurrentUser =
String(request?.actorLocked?.actorId) === currentUser.sub &&
request.lockFile;
if (!isLockedByCurrentUser) {
return false;
}
// Also check if lock has expired (unlockTime has passed)
if (request.unlockTime) {
const unlockTime = new Date(request.unlockTime).getTime();
const now = Date.now();
if (now >= unlockTime) {
// Lock has expired, but still allow access if they were the one who locked it
// The unlockApi will handle the cleanup
return true;
}
}
return true;
}
private isRequestLocked(request: any, currentUser?: any): boolean {
if (
!request.lockFile ||
request.claimStatus !== ReqClaimStatus.ReviewRequest
) {
return false;
}
// Check if lock has expired
if (request.unlockTime) {
const unlockTime = new Date(request.unlockTime).getTime();
const now = Date.now();
if (now >= unlockTime) {
// Lock has expired, treat as not locked
return false;
}
}
// If currentUser is provided, allow access if they are the one who locked it
if (currentUser) {
const isLockedByCurrentUser =
String(request?.actorLocked?.actorId) === currentUser.sub;
// Return false (not locked) if locked by current user, true if locked by someone else
return !isLockedByCurrentUser;
}
// If no currentUser provided, treat as locked
return true;
}
async streamServiceV2(requestId, query, res, header) {
const request = await this.claimCaseDbService.findById(requestId);
// const blameCase = await this.blameCaseDbService
return request;
// let videoPath: string = "";
// switch (query) {
// case "accident":
// videoPath = await this.getAccidentVideoPath(
// String(
// request?.blameFile?.firstPartyDetails?.firstPartyFile
// ?.firstPartyVideoId,
// ),
// );
// break;
// case "car-capture":
// videoPath = await this.getCarCapture(requestId);
// break;
// default:
// throw new NotFoundException("Invalid query type");
// }
// if (!videoPath) throw new NotFoundException("video_not_found");
// const absolutePath = join(process.cwd(), videoPath.replace(/^\/+/, ""));
// if (!existsSync(absolutePath)) {
// throw new NotFoundException(
// `Video file not found at path: ${absolutePath}`,
// );
// }
// const { size } = statSync(absolutePath);
// const range = header.range;
// if (range) {
// const [startStr, endStr] = range.replace(/bytes=/, "").split("-");
// const start = parseInt(startStr, 10);
// const end = endStr ? parseInt(endStr, 10) : size - 1;
// const chunkSize = end - start + 1;
// const file = createReadStream(absolutePath, { start, end });
// res.writeHead(206, {
// "Content-Range": `bytes ${start}-${end}/${size}`,
// "Accept-Ranges": "bytes",
// "Content-Length": chunkSize,
// "Content-Type": "video/mp4",
// });
// file.pipe(res);
// } else {
// res.writeHead(200, {
// "Content-Length": size,
// "Content-Type": "video/mp4",
// });
// createReadStream(absolutePath).pipe(res);
// }
}
async getVoiceLink(id: string): Promise<{ url: string }> {
const voice = await this.blameVoiceDbService.findOne(id);
if (!voice) {
throw new NotFoundException("Voice file not found");
}
const fileUrl = buildFileLink(voice.path);
return { url: fileUrl };
}
/**
* Close the claim after factor validation without a second insurer-review signature.
* Owner already uploaded factor files; mixed replies already have priced-line acceptance on file.
*/
private async completeClaimCaseAfterFactorValidationV2(
claimRequestId: string,
claimForTenant: any,
actor: { sub: string; fullName?: string; clientKey?: string },
historyType: string,
historyActor: {
actorId: Types.ObjectId;
actorName?: string;
actorType: string;
},
metadata: Record<string, unknown>,
): Promise<ClaimCaseStatus> {
// V5 retains the FileMaker approval gate, but no longer waits for a
// damaged-party final signature after that approval.
const completionStatus = (claimForTenant as any).requiresFileMakerApproval
? ClaimCaseStatus.WAITING_FOR_FILE_MAKER_APPROVAL
: ClaimCaseStatus.COMPLETED;
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: {
status: completionStatus,
claimStatus: ClaimStatus.APPROVED,
"workflow.currentStep": ClaimWorkflowStep.CLAIM_COMPLETED,
"workflow.nextStep": ClaimWorkflowStep.CLAIM_COMPLETED,
},
$push: {
"workflow.completedSteps": ClaimWorkflowStep.INSURER_REVIEW,
history: {
type: historyType,
actor: historyActor,
timestamp: new Date(),
metadata,
},
},
});
await this.recordClaimExpertActivity({
expertId: String(actor.sub),
tenantId: this.claimActivityTenantId(claimForTenant, actor),
claimId: String(claimRequestId),
eventType: ExpertFileActivityType.HANDLED,
idempotencyKey: `claim:${claimRequestId}:factor_validation:${historyType}:${actor.sub}`,
});
return completionStatus;
}
/**
* V2 (ClaimCase): validate user-uploaded repair factors on the active expert reply.
* Preconditions: all `factorNeeded` parts have `factorLink`; case is UNDER_REVIEW at EXPERT_COST_EVALUATION.
* — All approved → COMPLETED + APPROVED (expert-entered line totals; no extra owner signature).
* — Any rejected (repriced) → COMPLETED + APPROVED (auto-close for now; owner sign may be added later).
* For V1 user-created files, when enabled by env, the total of all repair
* lines must be no greater than the configured total-payment cap.
* Response: `claimStatus` = `ClaimStatus`; `caseStatus` = `ClaimCaseStatus`.
*/
async validateClaimFactorsV2(
claimRequestId: string,
body: FactorValidationV2Dto,
actor: { sub: string; fullName?: string; clientKey?: string },
) {
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) {
throw new NotFoundException(
this.expertReplySubmissionError(
"پرونده خسارت یافت نشد.",
"CLAIM_NOT_FOUND",
),
);
}
await this.assertExpertActorOnClaim(claim, actor);
const factorValidationSnapshot = await this.snapshotDamageExpert(actor.sub);
if (!claimIsAwaitingExpertFactorValidationV2(claim)) {
throw new BadRequestException(
"پرونده در مرحله بررسی فاکتور توسط کارشناس نیست. وضعیت پرونده را دوباره دریافت کنید.",
);
}
const replyField = claim.evaluation?.damageExpertReplyFinal
? "damageExpertReplyFinal"
: "damageExpertReply";
const finalReply =
replyField === "damageExpertReplyFinal"
? claim.evaluation?.damageExpertReplyFinal
: claim.evaluation?.damageExpertReply;
if (!finalReply?.parts?.length) {
throw new BadRequestException("پاسخ کارشناسی برای بررسی فاکتور در این پرونده یافت نشد.");
}
const requiredFactors = finalReply.parts.filter((p) => p.factorNeeded);
if (requiredFactors.length === 0) {
throw new BadRequestException("در این پاسخ کارشناسی قطعه‌ای نیازمند بررسی فاکتور نیست.");
}
if (!requiredFactors.every((p) => !!p.factorLink)) {
throw new BadRequestException(
"هنوز همه فاکتورهای موردنیاز بارگذاری نشده‌اند.",
);
}
if (!Array.isArray(body.decisions) || body.decisions.length === 0) {
throw new BadRequestException("حداقل یک فاکتور را بررسی کنید.");
}
const $set: Record<string, unknown> = {};
const seen = new Set<string>();
const proposedParts = finalReply.parts.map((part: any) => ({
...(typeof part.toObject === "function" ? part.toObject() : part),
}));
for (const decision of body.decisions) {
const partIndex = proposedParts.findIndex((part) =>
sameCatalogPartId(part.partId, decision.partId),
);
const id = String(decision.partId);
if (seen.has(id))
throw new BadRequestException(
"برای هر فاکتور فقط یک نتیجه بررسی ارسال کنید.",
);
seen.add(id);
if (partIndex < 0 || !proposedParts[partIndex].factorNeeded) {
throw new BadRequestException(
"قطعه انتخاب‌شده در فهرست فاکتورهای موردنیاز پرونده وجود ندارد.",
);
}
if (
![FactorStatus.APPROVED, FactorStatus.REJECTED].includes(
decision.status,
)
) {
throw new BadRequestException(
"نتیجه بررسی فاکتور باید تأیید یا عدم تأیید باشد.",
);
}
if (
decision.status === FactorStatus.REJECTED &&
!String(decision.rejectionReason ?? "").trim()
) {
throw new BadRequestException("دلیل عدم تأیید فاکتور را وارد کنید.");
}
const providedTotal =
decision.totalPayment != null &&
String(decision.totalPayment).trim() !== "";
const price = parseMoneyAmountToman(decision.price);
const salary = parseMoneyAmountToman(decision.salary);
const lineTotal = providedTotal
? parseMoneyAmountToman(decision.totalPayment)
: price != null && salary != null
? price + salary
: NaN;
if (
!this.expertFactorValidationDecisionHasLinePricing(decision) ||
!Number.isSafeInteger(lineTotal) ||
lineTotal < 1_000_000 ||
lineTotal > 100_000_000_000
) {
throw new BadRequestException(
"مبلغ نهایی قطعه با احتساب اجرت باید بین ۱٬۰۰۰٬۰۰۰ و ۱۰۰٬۰۰۰٬۰۰۰٬۰۰۰ ریال باشد.",
);
}
const base = `evaluation.${replyField}.parts.${partIndex}`;
const updates: Record<string, unknown> = {
factorStatus: decision.status,
rejectionReason:
decision.status === FactorStatus.REJECTED
? decision.rejectionReason.trim()
: null,
totalPayment: String(lineTotal),
};
for (const field of ["price", "salary"] as const) {
if (decision[field] === undefined) continue;
const amount = parseMoneyAmountToman(decision[field]);
if (
!Number.isSafeInteger(amount) ||
amount < 0 ||
amount > 100_000_000_000
) {
throw new BadRequestException(
"قیمت قطعه و اجرت باید مبلغ صحیح و نامنفی به ریال باشند.",
);
}
updates[field] = String(amount);
}
Object.assign(proposedParts[partIndex], updates);
for (const [field, value] of Object.entries(updates))
$set[`${base}.${field}`] = value;
}
const reqParts = proposedParts.filter((part) => part.factorNeeded);
const anyRejected = reqParts.some(
(part) => part.factorStatus === FactorStatus.REJECTED,
);
const anyStillPending = reqParts.some(
(part) =>
!part.factorStatus || part.factorStatus === FactorStatus.PENDING,
);
if (!anyStillPending) {
const configuredPriceCap = getClaimV2TotalPaymentCapToman();
const priceCap =
configuredPriceCap !== null &&
claimPriceCapAppliesToBlame(await this.loadBlameForClaim(claim))
? configuredPriceCap
: null;
if (priceCap !== null) {
let totalPrice = 0;
for (const part of proposedParts || []) {
const line = this.claimReplyPartLineTotalForCap(part);
if (isNaN(line)) {
throw new BadRequestException({
message: `مبلغ قطعه ${String(part.partId ?? "")} معتبر نیست. مبلغ نهایی یا قیمت قطعه و اجرت را ثبت کنید.`,
error: "PRICE_CAP_ERROR",
});
}
totalPrice += line;
}
if (totalPrice > priceCap) {
throw new BadRequestException({
message: `مجموع مبلغ قطعات و فاکتورها (${totalPrice.toLocaleString("fa-IR")} ریال) از سقف مجاز پرونده (${priceCap.toLocaleString("fa-IR")} ریال) بیشتر است.`,
error: "PRICE_CAP_ERROR",
totalPrice,
priceCap,
});
}
}
}
if (factorValidationSnapshot)
$set["evaluation.factorValidationExpertProfileSnapshot"] =
factorValidationSnapshot;
const updatedClaim = await this.claimCaseDbService.findOneAndUpdate(
{
_id: claim._id,
status: claim.status,
claimStatus: claim.claimStatus,
"workflow.currentStep": claim.workflow.currentStep,
...((claim as any).updatedAt != null
? { updatedAt: (claim as any).updatedAt }
: { [`evaluation.${replyField}.parts`]: finalReply.parts }),
},
{ $set },
);
if (!updatedClaim)
throw new ConflictException(
"اطلاعات فاکتورها هنگام بررسی تغییر کرده است. پرونده را دوباره دریافت و تلاش کنید.",
);
await this.recordClaimExpertActivity({
expertId: String(actor.sub),
tenantId: this.claimActivityTenantId(claim, actor),
claimId: String(claimRequestId),
eventType: ExpertFileActivityType.CHECKED,
idempotencyKey: `claim:${claimRequestId}:checked:${actor.sub}`,
});
if (anyStillPending)
return {
message:
"نتیجه بررسی فاکتور ثبت شد. فاکتورهای باقی‌مانده را نیز بررسی کنید.",
claimRequestId,
claimStatus: updatedClaim.claimStatus,
caseStatus: updatedClaim.status,
pendingFactorValidation: true,
};
const historyActor = {
actorId: new Types.ObjectId(actor.sub),
actorName: actor.fullName,
actorType: "damage_expert",
};
if (anyRejected) {
const completionStatus =
await this.completeClaimCaseAfterFactorValidationV2(
claimRequestId,
claim,
actor,
"FACTORS_REJECTED_REPRICED_AUTO_COMPLETED",
historyActor,
{ replyField },
);
return {
message:
completionStatus === ClaimCaseStatus.WAITING_FOR_FILE_MAKER_APPROVAL
? "Factors were reviewed with expert repricing. The claim is awaiting FileMaker approval."
: "Factors were reviewed with expert repricing. The claim is completed without a final owner signature.",
claimRequestId,
claimStatus: ClaimStatus.APPROVED,
caseStatus: completionStatus,
outcome: "REJECTED_REPRICED_AUTO_COMPLETED",
};
}
const completionStatus =
await this.completeClaimCaseAfterFactorValidationV2(
claimRequestId,
claim,
actor,
"FACTORS_VALIDATED_ALL_APPROVED_AUTO_COMPLETED",
historyActor,
{ replyField },
);
return {
message:
completionStatus === ClaimCaseStatus.WAITING_FOR_FILE_MAKER_APPROVAL
? "All factors were approved. The claim is awaiting FileMaker approval."
: "All factors were approved by the expert. The claim is completed without a final owner signature.",
claimRequestId,
claimStatus: ClaimStatus.APPROVED,
caseStatus: completionStatus,
outcome: "ALL_APPROVED_AUTO_COMPLETED",
};
}
/**
* V2: branches for the damage expert's insurer tenant (JWT `clientKey`).
* Same data as v1 `GET expert-claim/branches/:insuranceId` without passing client id.
*/
async retrieveInsuranceBranchesV2(actor: { clientKey?: string }) {
const clientKey = requireActorClientKey(actor);
return await this.branchDbService.findAll(clientKey);
}
/**
* FILE_REVIEWER path: atomically assign this reviewer to the linked V4 blame
* file. Operates on the blame document (not the claim workflow lock).
*
* Rules:
* - Blame must be isMadeByFileMaker, IN_PERSON, expertInitiated.
* - Status must be WAITING_FOR_FILE_REVIEWER.
* - No other reviewer may have taken it (assignedFileReviewerId absent/null).
* - Idempotent: same reviewer calling again gets "already_assigned_to_you".
*/
private async assignFileReviewerToV4Blame(
claimRequestId: string,
claim: any,
actor: { sub: string; fullName?: string; clientKey?: string },
): Promise<ExpertFileAssignResultDto> {
if (!claim.blameRequestId) {
throw new BadRequestException({
success: false,
status: "unavailable" satisfies ExpertFileAssignStatus,
message: "This claim has no linked blame file.",
});
}
const blame = await this.blameRequestDbService.findById(
String(claim.blameRequestId),
);
if (!blame) {
throw new NotFoundException("Linked blame file not found.");
}
const clientKey = requireActorClientKey(actor);
if (!blameCaseTouchesClient(blame, clientKey)) {
throw new ForbiddenException(
"This file does not belong to your organization.",
);
}
await this.fanavaranLocationService.assertMakerReviewerBranchCompatible({
fileMakerId: (blame as any)?.initiatedByFieldExpertId
? String((blame as any).initiatedByFieldExpertId)
: null,
fileReviewerId: actor.sub,
caseBranchId: (blame as any)?.branchId
? String((blame as any).branchId)
: null,
});
if (
!(blame as any).isMadeByFileMaker ||
!(blame as any).expertInitiated ||
(blame as any).creationMethod !== "IN_PERSON"
) {
throw new BadRequestException({
success: false,
status: "unavailable" satisfies ExpertFileAssignStatus,
message:
"Only V4/V5 FileMaker files can be assigned to a FileReviewer.",
});
}
if ((blame as any).status !== "WAITING_FOR_FILE_REVIEWER") {
throw new BadRequestException({
success: false,
status: "unavailable" satisfies ExpertFileAssignStatus,
message: `Blame file is not ready for FileReviewer. Status: ${(blame as any).status}`,
});
}
const existing = (blame as any).assignedFileReviewerId;
if (existing) {
if (String(existing) === actor.sub) {
return {
success: true,
status: "already_assigned_to_you",
message: "You have already taken this file.",
};
}
throw new ConflictException({
success: false,
status: "locked" satisfies ExpertFileAssignStatus,
message: "Another FileReviewer has already taken this file.",
});
}
// Atomically claim it — findOneAndUpdate with null/missing guard
const reviewerOid = new Types.ObjectId(actor.sub);
await this.fanavaranLocationService.assertMakerReviewerLocationCompatible({
fileMakerId: (blame as any)?.initiatedByFieldExpertId
? String((blame as any).initiatedByFieldExpertId)
: null,
fileReviewerId: actor.sub,
});
const updated = await this.blameRequestDbService.findOneAndUpdate(
{
_id: (blame as any)._id,
$or: [
{ assignedFileReviewerId: { $exists: false } },
{ assignedFileReviewerId: null },
],
},
{ $set: { assignedFileReviewerId: reviewerOid } },
{ new: true },
);
if (!updated) {
// Another reviewer won the race
throw new ConflictException({
success: false,
status: "locked" satisfies ExpertFileAssignStatus,
message: "Another FileReviewer has already taken this file.",
});
}
const now = new Date();
this.logger.log(
`FileReviewer ${actor.sub} assigned to V4 blame ${String((blame as any)._id)} / claim ${claimRequestId}`,
);
return {
success: true,
status: "assigned",
assignedAt: now.toISOString(),
message:
"File assigned to you. Proceed with accident fields and field capture.",
};
}
/**
* Assign the current damage expert to a claim for review (V2).
* Free cases are locked atomically; already-assigned-to-self is idempotent.
*/
async assignClaimForReviewV2(
claimRequestId: string,
actor: {
sub: string;
fullName?: string;
clientKey?: string;
role?: string;
},
): Promise<ExpertFileAssignResultDto> {
if (
(actor as any).role !== RoleEnum.FIELD_EXPERT &&
(actor as any).role !== RoleEnum.FILE_REVIEWER
)
requireActorClientKey(actor);
await this.expireClaimWorkflowLockV2IfStale(claimRequestId);
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) {
throw new NotFoundException("Claim request not found");
}
// FILE_REVIEWER: two-phase lock behaviour.
// Phase 1 — blame is WAITING_FOR_FILE_REVIEWER: atomically set
// assignedFileReviewerId on the blame document.
// Phase 2 — blame is already past WAITING_FOR_FILE_REVIEWER (i.e. the
// reviewer finished field work and blame moved to WAITING_FOR_EXPERT):
// the reviewer now needs the standard damage-expert workflow lock
// so they can perform damage assessment. Fall through to the
// damage-expert path below; assertExpertActorOnClaim will verify
// tenant scope via the reviewer's clientKey.
if ((actor as any).role === RoleEnum.FILE_REVIEWER) {
if (!claim.blameRequestId) {
throw new BadRequestException({
success: false,
status: "unavailable" satisfies ExpertFileAssignStatus,
message: "This claim has no linked blame file.",
});
}
const reviewerBlame = await this.blameRequestDbService.findById(
String(claim.blameRequestId),
);
if (!reviewerBlame) {
throw new NotFoundException("Linked blame file not found.");
}
const clientKey = requireActorClientKey(actor);
if (!blameCaseTouchesClient(reviewerBlame, clientKey)) {
throw new ForbiddenException(
"This file does not belong to your organization.",
);
}
await this.fanavaranLocationService.assertMakerReviewerBranchCompatible({
fileMakerId: (reviewerBlame as any).initiatedByFieldExpertId
? String((reviewerBlame as any).initiatedByFieldExpertId)
: null,
fileReviewerId: actor.sub,
caseBranchId: (reviewerBlame as any).branchId
? String((reviewerBlame as any).branchId)
: null,
});
const assignedReviewerId = (reviewerBlame as any).assignedFileReviewerId
? String((reviewerBlame as any).assignedFileReviewerId)
: null;
const blameStatus = (reviewerBlame as any).status as string;
const isReviewerCapturePhase = [
ClaimCaseStatus.CREATED,
ClaimCaseStatus.WAITING_FOR_FILE_REVIEWER,
ClaimCaseStatus.SELECTING_OUTER_PARTS,
ClaimCaseStatus.SELECTING_OTHER_PARTS,
ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS,
ClaimCaseStatus.CAPTURING_PART_DAMAGES,
].includes(claim.status as ClaimCaseStatus);
if (blameStatus === "WAITING_FOR_FILE_REVIEWER" && isReviewerCapturePhase) {
if (assignedReviewerId && assignedReviewerId === actor.sub) {
// Phase 1 is intentionally idempotent. The linked claim can still be
// in a data-capture status here, so falling through to the damage
// assessment status gate would incorrectly reject the same reviewer.
return {
success: true,
status: "already_assigned_to_you",
message: "You have already taken this file.",
};
} else {
// Phase 1: first-time blame assignment
return this.assignFileReviewerToV4Blame(claimRequestId, claim, actor);
}
} else {
// Phase 2: blame is past the initial assignment step.
// Only the reviewer who was assigned during Phase 1 may proceed.
if (!assignedReviewerId) {
throw new BadRequestException({
success: false,
status: "unavailable" satisfies ExpertFileAssignStatus,
message: "No reviewer has been assigned to this file yet.",
});
}
if (assignedReviewerId !== actor.sub) {
throw new ConflictException({
success: false,
status: "locked" satisfies ExpertFileAssignStatus,
message: "This file is assigned to another reviewer.",
});
}
}
// Fall through to the damage-expert workflow lock below.
}
await this.assertExpertActorOnClaim(claim, actor);
const isFieldExpertOwner =
(actor as any).role === RoleEnum.FIELD_EXPERT &&
(await this.fieldExpertOwnsClaim(claim, actor));
const isFactorValidationLock =
claimIsAwaitingExpertFactorValidationV2(claim);
const isDamageReviewLock =
claim.status === ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT ||
claim.status === ClaimCaseStatus.IN_PERSON_VISIT_PENDING;
const isExpertReviewingReentry =
claim.status === ClaimCaseStatus.EXPERT_REVIEWING;
const isResendPending =
claim.status === ClaimCaseStatus.WAITING_FOR_USER_RESEND;
const isTerminalClaim =
claim.status === ClaimCaseStatus.COMPLETED ||
claim.status === ClaimCaseStatus.CANCELLED;
const isFieldExpertPortfolioLock =
isFieldExpertOwner &&
!isTerminalClaim &&
!isDamageReviewLock &&
!isFactorValidationLock &&
!isExpertReviewingReentry &&
!isResendPending;
if (
!isDamageReviewLock &&
!isFactorValidationLock &&
!isExpertReviewingReentry &&
!isResendPending &&
!isFieldExpertPortfolioLock
) {
throw new BadRequestException({
success: false,
status: "unavailable" satisfies ExpertFileAssignStatus,
message: "Request is not available for expert review",
});
}
const expertOid = new Types.ObjectId(actor.sub);
const reviewAssigneeId = resolvePersistentReviewAssigneeId(
claim.workflow,
claim.history,
CLAIM_REVIEW_ASSIGNED_HISTORY_TYPE,
);
if (reviewAssigneeId && reviewAssigneeId !== actor.sub) {
throw new ConflictException(
buildExpertAssignConflictForOtherReviewer(
reviewAssigneeId,
claim.workflow,
),
);
}
const lockedById = String(claim.workflow?.lockedBy?.actorId ?? "");
const lockEnforced =
claim.workflow?.locked &&
this.isClaimV2WorkflowLockCurrentlyEnforced(claim);
if (lockEnforced && lockedById && lockedById !== actor.sub) {
throw new ConflictException(
buildExpertAssignConflictForOtherReviewer(lockedById, claim.workflow),
);
}
if (lockEnforced && lockedById === actor.sub) {
return {
success: true,
status: "already_assigned_to_you",
message: "You already started processing this request",
assignedAt: claim.workflow?.lockedAt
? new Date(claim.workflow.lockedAt as Date).toISOString()
: undefined,
};
}
const now = new Date();
const lockSnapshot = await this.snapshotDamageExpert(actor.sub);
const expiredAt = new Date(now.getTime() + EXPERT_WORKFLOW_LOCK_TTL_MS);
const actorType = isFieldExpertOwner
? "field_expert"
: (actor as any).role === RoleEnum.FILE_REVIEWER
? "file_reviewer"
: "damage_expert";
const actorRoleLabel = isFieldExpertOwner
? ("field_expert" as const)
: (actor as any).role === RoleEnum.FILE_REVIEWER
? ("file_reviewer" as const)
: ("damage_expert" as const);
const lockedByPayload = {
actorId: expertOid,
actorName: actor.fullName,
actorRole: actorRoleLabel,
...(lockSnapshot && { expertProfileSnapshot: lockSnapshot }),
};
const baseLockUpdate: Record<string, unknown> = {
"workflow.locked": true,
"workflow.lockedAt": now,
"workflow.expiredAt": expiredAt,
"workflow.lockedBy": lockedByPayload,
...(isDamageReviewLock || isExpertReviewingReentry || isResendPending
? {
"workflow.preLockQueueSnapshot": {
claimStatus: claim.claimStatus,
currentStep: this.normalizeClaimWorkflowStepForSnapshot(
claim.workflow?.currentStep,
ClaimWorkflowStep.USER_SUBMISSION_COMPLETE,
),
...(claim.workflow?.nextStep != null
? {
nextStep: this.normalizeClaimWorkflowStepForSnapshot(
claim.workflow.nextStep,
ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT,
),
}
: {}),
},
}
: {}),
$push: {
history: {
type: "CLAIM_ASSIGNED",
actor: {
actorId: expertOid,
actorName: actor.fullName,
actorType,
},
timestamp: now,
metadata: {
note: isFactorValidationLock
? "Expert assigned for factor validation review"
: isFieldExpertPortfolioLock
? "Field expert portfolio lock (no status change)"
: "Expert assigned via review assign endpoint",
...(isFactorValidationLock ? { phase: "factorValidation" } : {}),
},
},
},
};
// Update assignedForReviewBy whenever a FILE_REVIEWER re-locks after a
// FileMaker rejection — the stale payload (from a prior damage-expert cycle)
// must be replaced with the actual reviewer so submit checks pass.
if (
!claim.workflow?.assignedForReviewBy ||
(actor as any).role === RoleEnum.FILE_REVIEWER
) {
baseLockUpdate["workflow.assignedForReviewBy"] = lockedByPayload;
}
const lockUpdate: Record<string, unknown> =
isFactorValidationLock ||
isExpertReviewingReentry ||
isResendPending ||
isFieldExpertPortfolioLock
? baseLockUpdate
: {
...baseLockUpdate,
status: ClaimCaseStatus.EXPERT_REVIEWING,
claimStatus: ClaimStatus.UNDER_REVIEW,
"workflow.currentStep": ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT,
};
const assignFilter: Record<string, unknown> = {
_id: new Types.ObjectId(claimRequestId),
$and: [
{
$or: [
{ "workflow.locked": { $ne: true } },
{ "workflow.locked": false },
{ "workflow.expiredAt": { $lte: now } },
{ "workflow.lockedBy.actorId": expertOid },
],
},
{
$or: [
{ "workflow.assignedForReviewBy": { $exists: false } },
{ "workflow.assignedForReviewBy": null },
{ "workflow.assignedForReviewBy.actorId": expertOid },
],
},
],
};
if (isFactorValidationLock) {
assignFilter.claimStatus = ClaimStatus.UNDER_REVIEW;
assignFilter["workflow.currentStep"] =
ClaimWorkflowStep.EXPERT_COST_EVALUATION;
assignFilter.status = {
$in: [
ClaimCaseStatus.EXPERT_VALIDATING_REPAIR_FACTORS,
ClaimCaseStatus.WAITING_FOR_INSURER_APPROVAL,
],
};
} else if (isExpertReviewingReentry) {
assignFilter.status = ClaimCaseStatus.EXPERT_REVIEWING;
} else if (isResendPending) {
assignFilter.status = ClaimCaseStatus.WAITING_FOR_USER_RESEND;
} else if (isFieldExpertPortfolioLock) {
assignFilter.initiatedByFieldExpertId = expertOid;
assignFilter.status = claim.status;
} else {
assignFilter.status = claim.status;
}
const updated = await this.claimCaseDbService.findOneAndUpdate(
assignFilter as any,
lockUpdate,
{ new: true },
);
if (!updated) {
await this.expireClaimWorkflowLockV2IfStale(claimRequestId);
const latest = await this.claimCaseDbService.findById(claimRequestId);
const otherAssigneeId = resolvePersistentReviewAssigneeId(
latest?.workflow,
latest?.history,
CLAIM_REVIEW_ASSIGNED_HISTORY_TYPE,
);
if (otherAssigneeId && otherAssigneeId !== actor.sub) {
throw new ConflictException(
buildExpertAssignConflictForOtherReviewer(
otherAssigneeId,
latest?.workflow,
),
);
}
const otherId = String(latest?.workflow?.lockedBy?.actorId ?? "");
if (
latest?.workflow?.locked &&
this.isClaimV2WorkflowLockCurrentlyEnforced(latest) &&
otherId &&
otherId !== actor.sub
) {
throw new ConflictException(
buildExpertAssignConflictForOtherReviewer(otherId, latest?.workflow),
);
}
throw new BadRequestException({
success: false,
status: "unavailable" satisfies ExpertFileAssignStatus,
message: "Request could not be assigned",
});
}
await this.recordClaimExpertActivity({
expertId: String(actor.sub),
tenantId: this.claimActivityTenantId(updated, actor),
claimId: String(claimRequestId),
eventType: ExpertFileActivityType.CHECKED,
idempotencyKey: `claim:${claimRequestId}:checked:v2:${actor.sub}`,
});
const ownerPhone = await this.resolveClaimOwnerPhone(updated);
if (
ownerPhone &&
isDamageReviewLock &&
!isFieldExpertPortfolioLock &&
!isExpertReviewingReentry &&
!isResendPending
) {
const expertLastName =
actor?.fullName?.trim()?.split(/\s+/).pop() || "کارشناس";
await this.smsOrchestrationService.sendThirdPartyExpertStartedReviewNotice(
{
receptor: ownerPhone,
fileKind: "claim",
publicId: updated.publicId,
expertLastName,
},
);
}
this.logger.log(
`Claim ${claimRequestId} assigned to expert ${actor.sub} at ${now.toISOString()}`,
);
return {
success: true,
status: "assigned",
assignedAt: now.toISOString(),
};
}
/**
* V2: Lock a claim request for expert review.
*
* Validations:
* - Claim must exist
* - Status must be either:
* • `WAITING_FOR_DAMAGE_EXPERT` (initial damage review queue), OR
* • the factor-validation queue (`EXPERT_VALIDATING_REPAIR_FACTORS`,
* or legacy `WAITING_FOR_INSURER_APPROVAL`, with
* `claimStatus=UNDER_REVIEW` + `workflow.currentStep=EXPERT_COST_EVALUATION`).
* - Must not already be locked by another expert.
*
* On success:
* - Always sets `workflow.locked=true`, `workflow.lockedBy=actor`,
* `workflow.lockedAt/expiredAt`, and snapshots pre-lock queue state.
* - For the **damage review** path: status → `EXPERT_REVIEWING`,
* `claimStatus=UNDER_REVIEW`, `workflow.currentStep=EXPERT_DAMAGE_ASSESSMENT`.
* - For the **factor-validation** path: leaves `status`, `claimStatus`, and
* `workflow.currentStep` untouched so the claim stays in the factor-validation
* queue (so `expireClaimWorkflowLockV2IfStale` and the queue endpoint keep
* treating it correctly when the lock expires).
*
* Delegates to {@link assignClaimForReviewV2}; maps conflict to BadRequest for legacy clients.
*/
async lockClaimRequestV2(claimRequestId: string, actor: any) {
try {
const result = await this.assignClaimForReviewV2(claimRequestId, actor);
const response: Record<string, unknown> = {
claimRequestId,
locked: true,
message: result.message,
};
if (result.status === "assigned") {
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (claim?.status === ClaimCaseStatus.EXPERT_REVIEWING) {
response.status = ClaimCaseStatus.EXPERT_REVIEWING;
response.claimStatus = ClaimStatus.UNDER_REVIEW;
response.currentStep = ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT;
}
}
return response;
} catch (error) {
if (error instanceof ConflictException) {
const body = error.getResponse();
throw new BadRequestException(body);
}
if (error instanceof HttpException) throw error;
this.logger.error(
"lockClaimRequestV2 failed",
claimRequestId,
error instanceof Error ? error.stack : String(error),
);
throw new HttpException(
error instanceof Error ? error.message : "Failed to lock claim",
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
async submitResendDocsV2(
claimRequestId: string,
reply: ClaimSubmitResendV2Dto,
actor: any,
) {
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) {
throw new NotFoundException("Claim request not found");
}
await this.assertExpertActorOnClaim(claim, actor);
if (claim.status !== ClaimCaseStatus.EXPERT_REVIEWING) {
throw new BadRequestException(
`Claim is not in EXPERT_REVIEWING state. Current status: ${claim.status}`,
);
}
if (!claim.workflow?.locked) {
throw new ForbiddenException(
"You must lock the claim before submitting a resend request",
);
}
if (claim.workflow.lockedBy?.actorId?.toString() !== actor.sub) {
throw new ForbiddenException("This claim is locked by another expert");
}
// Block duplicate resend while a prior request is still unfinished (stale EXPERT_REVIEWING + pending resend).
// After a successful submit, status becomes WAITING_FOR_USER_RESEND so this endpoint is not callable until the owner finishes.
const existingResend = claim.evaluation?.damageExpertResend;
if (
existingResend &&
!existingResend.fulfilledAt &&
resendRequestHasPayload(existingResend)
) {
throw new ConflictException(
"A resend request is still open for this claim. Wait until the owner completes uploads or contact support if the case is stuck.",
);
}
if (existingResend?.fulfilledAt) {
throw new BusinessRuleException(
BusinessErrorCode.DAMAGE_EXPERT_RESEND_LIMIT_EXCEEDED,
"کاربر درخواست قبلی تکمیل اطلاعات را انجام داده است. برای این پرونده امکان درخواست مجدد وجود ندارد؛ پاسخ کارشناسی را ثبت کنید یا مراجعه حضوری درخواست دهید.",
);
}
const allowedDocTypes = new Set<string>(
Object.values(ClaimRequiredDocumentType),
);
const rawDocs = reply.resendDocuments ?? [];
const docs: ClaimRequiredDocumentType[] = [];
for (const x of rawDocs) {
const s = String(x).trim();
if (!allowedDocTypes.has(s)) {
throw new BadRequestException(
`Invalid resendDocuments value: "${String(x)}". Must be a ClaimRequiredDocumentType string (e.g. national_card, damaged_driving_license_front).`,
);
}
docs.push(s as ClaimRequiredDocumentType);
}
const uniqueDocs = [...new Set(docs)];
const carType = claim.vehicle?.carType as ClaimVehicleTypeV2 | undefined;
const normalizedParts = normalizeResendCarPartsForStorage(
reply.resendCarParts,
carType,
claim.damage?.selectedParts,
);
const desc = String(reply.resendDescription ?? "").trim();
if (!desc && uniqueDocs.length === 0 && normalizedParts.length === 0) {
throw new BadRequestException(
"Provide resendDescription and/or resendDocuments and/or resendCarParts.",
);
}
const resendSnapshot = await this.snapshotDamageExpert(actor.sub);
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: {
status: ClaimCaseStatus.WAITING_FOR_USER_RESEND,
claimStatus: ClaimStatus.NEEDS_REVISION,
"workflow.locked": false,
"workflow.currentStep": ClaimWorkflowStep.USER_EXPERT_RESEND,
"workflow.nextStep": ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT,
"evaluation.damageExpertResend": {
requestedAt: new Date(),
resendDescription: desc || undefined,
resendDocuments: uniqueDocs,
resendCarParts: normalizedParts,
requestedByExpertId: new Types.ObjectId(actor.sub),
...(resendSnapshot && { expertProfileSnapshot: resendSnapshot }),
},
},
$unset: {
"workflow.lockedAt": "",
"workflow.expiredAt": "",
"workflow.lockedBy": "",
"workflow.preLockQueueSnapshot": "",
},
$push: {
history: {
type: "EXPERT_RESEND_REQUESTED",
actor: {
actorId: new Types.ObjectId(actor.sub),
actorName: actor.fullName,
actorType: "damage_expert",
},
timestamp: new Date(),
metadata: {
documentCount: uniqueDocs.length,
carPartCount: normalizedParts.length,
},
},
},
});
const ownerPhoneResend = await this.resolveClaimOwnerPhone(claim);
if (ownerPhoneResend) {
await this.smsOrchestrationService.sendResendDocumentsNotice({
receptor: ownerPhoneResend,
fileKind: "claim",
publicId: claim.publicId,
link: this.smsOrchestrationService.buildClaimLink(
String(claim._id),
"v1",
),
});
}
await this.recordClaimExpertActivity({
expertId: String(actor.sub),
tenantId: this.claimActivityTenantId(claim, actor),
claimId: String(claimRequestId),
eventType: ExpertFileActivityType.HANDLED,
idempotencyKey: `claim:${claimRequestId}:handled:resend:${actor.sub}`,
});
return {
claimRequestId,
status: ClaimCaseStatus.WAITING_FOR_USER_RESEND,
claimStatus: ClaimStatus.NEEDS_REVISION,
currentStep: ClaimWorkflowStep.USER_EXPERT_RESEND,
nextStep: ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT,
message:
"Resend request recorded. The owner must upload the requested documents and/or part photos (or confirm if only instructions were given). The claim will return to the damage expert queue when complete.",
};
}
/**
* V2: Submit damage expert reply for a claim.
*
* Validations:
* - Claim must exist
* - Must be locked by this expert (workflow.lockedBy.actorId === actor.sub)
* - Must be in EXPERT_REVIEWING status
* - V1 only: total payment across all parts must not exceed the configured cap
* - Each part must include `daghi` (option + conditional price) like V1
*
* On success:
* - Stores reply; clears owner signature fields (`ownerInsurerApproval`, `ownerPricedPartsApproval`)
* - Unlocks the workflow
* - Pricing-only (`factorNeeded=false` everywhere): COMPLETED, APPROVED, CLAIM_COMPLETED — no final owner signature.
* - All lines `factorNeeded`: NEEDS_REVISION, OWNER_UPLOAD_FACTOR_DOCUMENTS → uploads → UNDER_REVIEW, EXPERT_COST_EVALUATION (validate factors).
* - Mixed priced + factor: NEEDS_REVISION, INSURER_REVIEW with next OWNER_UPLOAD_FACTOR_DOCUMENTS → owner signs priced lines first → upload factors → expert validates → complete.
*/
async submitExpertReplyV2(
claimRequestId: string,
reply: import("./dto/expert-claim-v2.dto").SubmitExpertReplyV2Dto,
actor: any,
) {
if (actor.role !== RoleEnum.FIELD_EXPERT) requireActorClientKey(actor);
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) {
throw new NotFoundException(
this.expertReplySubmissionError(
"پرونده خسارت یافت نشد.",
"CLAIM_NOT_FOUND",
),
);
}
const blame = await this.blameRequestDbService.findById(
claim.blameRequestId,
);
if (!blame) {
throw new NotFoundException(
this.expertReplySubmissionError(
"پرونده تعیین خسارت مرتبط یافت نشد.",
"BLAME_NOT_FOUND",
),
);
}
await this.assertExpertActorOnClaim(claim, actor);
if (claim.status !== ClaimCaseStatus.EXPERT_REVIEWING) {
throw new BadRequestException(
this.expertReplySubmissionError(
"پرونده در وضعیت قابل بررسی برای ثبت پاسخ کارشناسی نیست.",
"CLAIM_NOT_REVIEWABLE",
{ currentStatus: claim.status },
),
);
}
if (!claim.workflow?.locked) {
throw new ForbiddenException(
this.expertReplySubmissionError(
"پیش از ثبت پاسخ کارشناسی باید پرونده را قفل کنید.",
"CLAIM_NOT_LOCKED",
),
);
}
if (claim.workflow.lockedBy?.actorId?.toString() !== actor.sub) {
throw new ForbiddenException(
this.expertReplySubmissionError(
"این پرونده توسط کارشناس دیگری قفل شده است.",
"CLAIM_LOCKED_BY_ANOTHER_EXPERT",
),
);
}
const carPriceWasProvided = reply.carPrice != null;
let normalizedCurrentCarPrice: string | undefined;
let parsedCurrentCarPrice: number | undefined;
if (blame.type === BlameRequestType.CAR_BODY) {
parsedCurrentCarPrice =
parseMoneyAmountToman(reply.carPrice) ?? undefined;
if (
parsedCurrentCarPrice == null ||
!Number.isSafeInteger(parsedCurrentCarPrice) ||
parsedCurrentCarPrice <= 0
) {
throw new BadRequestException(
this.expertReplySubmissionError(
"قیمت روز خودرو در پرونده بدنه الزامی است و باید مبلغی صحیح و بیشتر از صفر باشد.",
"CAR_PRICE_REQUIRED",
{ field: "carPrice" },
),
);
}
normalizedCurrentCarPrice = normalizeMoneyAmountString(reply.carPrice!);
} else if (carPriceWasProvided) {
throw new ForbiddenException(
this.expertReplySubmissionError(
"قیمت روز خودرو فقط برای پرونده بدنه قابل ثبت است.",
"CAR_PRICE_NOT_ALLOWED",
{ field: "carPrice" },
),
);
}
const pricingValidationError = getExpertReplyPricingValidationError(
reply.parts,
{ locale: "fa", enforceAmountBounds: true },
);
if (pricingValidationError) {
throw new BadRequestException(pricingValidationError);
}
// The configured total cap is enforced only for V1 user-created files.
const configuredPriceCap = getClaimV2TotalPaymentCapToman();
const priceCap =
configuredPriceCap !== null && claimPriceCapAppliesToBlame(blame)
? configuredPriceCap
: null;
if (priceCap !== null) {
let totalPrice = 0;
for (const part of reply.parts || []) {
const parsed = this.parsePersianNumber(
String(part.totalPayment ?? "0"),
);
if (!isNaN(parsed)) totalPrice += parsed;
}
if (totalPrice > priceCap) {
throw new BadRequestException({
message: `مجموع مبلغ قطعات (${totalPrice.toLocaleString("fa-IR")}) از سقف مجاز (${priceCap.toLocaleString("fa-IR")}) ریال بیشتر است.`,
error: "PRICE_CAP_ERROR",
code: "PRICE_CAP_ERROR",
totalPrice,
priceCap,
});
}
}
const carTypeSubmit = claim.vehicle?.carType as
| ClaimVehicleTypeV2
| undefined;
const daghiNormalized =
reply.parts?.length > 0
? this.validateAndNormalizeDaghiForExpertReplyV2(reply.parts)
: [];
const ownerSelectedParts = normalizeDamageSelectedParts(
(claim as any)?.damage?.selectedParts,
carTypeSubmit,
(claim as any)?.damage?.selectedOuterParts,
);
const seenCatalogIds = new Set<number>();
const expertAddedParts: DamageSelectedPartV2[] = [];
const processedParts = daghiNormalized.map((p) => {
const selected = resolvePartForExpertReply(
p.partId,
ownerSelectedParts,
carTypeSubmit,
);
if (!selected) {
throw new BadRequestException(
this.expertReplySubmissionError(
`قطعه با شناسه ${p.partId} در فهرست قطعات آسیب‌دیده پرونده وجود ندارد.`,
"PART_NOT_ON_CLAIM",
{ field: "partId", partId: p.partId },
),
);
}
let carPartDamage: Record<string, unknown>;
try {
carPartDamage = normalizeCarPartDamageForExpertReply(
{
id: selected.id,
name: selected.name,
side: selected.side,
label_fa: selected.label_fa,
...(selected.catalogKey ? { catalogKey: selected.catalogKey } : {}),
},
carTypeSubmit,
);
} catch (err) {
throw new BadRequestException(
this.expertReplySubmissionError(
`اطلاعات قطعه ${p.partId} معتبر نیست.`,
"PART_INVALID",
{ field: "partId", partId: p.partId },
),
);
}
const catalogId = catalogPartIdFromCarPartDamage(carPartDamage);
if (catalogId == null) {
throw new BadRequestException(
this.expertReplySubmissionError(
`شناسه قطعه ${p.partId} معتبر نیست.`,
"PART_ID_INVALID",
{ field: "partId", partId: p.partId },
),
);
}
if (seenCatalogIds.has(catalogId)) {
throw new BadRequestException(
this.expertReplySubmissionError(
`قطعه ${catalogId} بیش از یک‌بار ارسال شده است.`,
"DUPLICATE_PART",
{ field: "partId", partId: catalogId },
),
);
}
seenCatalogIds.add(catalogId);
const wasOnClaim = ownerSelectedParts.some(
(op) => partLookupKey(op) === partLookupKey(selected),
);
if (!wasOnClaim) {
expertAddedParts.push(selected);
}
return {
...p,
partId: catalogId,
carPartDamage,
};
});
const { mixedFactorAndPrice, allFactorLines } =
classifyV2ExpertPricingParts(processedParts);
const needsFactorUpload =
reply.parts?.some((p) => p.factorNeeded === true) ?? false;
const objectionSubmitted = !!claim.evaluation?.objection?.submittedAt;
const hasFinalReply = !!claim.evaluation?.damageExpertReplyFinal;
if (objectionSubmitted && hasFinalReply) {
throw new ConflictException(
this.expertReplySubmissionError(
"پاسخ نهایی کارشناسی پس از اعتراض، پیش‌تر برای این پرونده ثبت شده است.",
"FINAL_REPLY_ALREADY_SUBMITTED",
),
);
}
const isFinalReplyAfterObjection = objectionSubmitted && !hasFinalReply;
const replyField = isFinalReplyAfterObjection
? "damageExpertReplyFinal"
: "damageExpertReply";
const completedStep = isFinalReplyAfterObjection
? ClaimWorkflowStep.EXPERT_FINAL_REPLY
: ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT;
const expertProfileSnapshot = await this.snapshotDamageExpert(actor.sub);
const replyPayload = {
description: reply.description,
parts: processedParts,
submittedAt: new Date(),
actorDetail: {
actorId: actor.sub,
actorName: actor.fullName,
},
...(expertProfileSnapshot && { expertProfileSnapshot }),
};
let currentStep = ClaimWorkflowStep.INSURER_REVIEW;
let nextWorkflowStep = ClaimWorkflowStep.CLAIM_COMPLETED;
const blameForFlow = claim.blameRequestId
? await this.blameRequestDbService.findById(String(claim.blameRequestId))
: undefined;
const skipsFinalOwnerSignature =
!!(blameForFlow as any)?.expertInitiated &&
(blameForFlow as any)?.creationMethod === "IN_PERSON";
const nextCaseStatus = claimCaseStatusAfterExpertReplyV2(
processedParts,
skipsFinalOwnerSignature,
);
let nextClaimStatus = ClaimStatus.APPROVED;
// V5 retains a FileMaker approval gate after expert work. Expert-initiated
// in-person V2–V5 flows do not request a final damaged-party signature.
const isV5Claim = !!(claim as any).requiresFileMakerApproval;
const completesWithoutFactors =
!needsFactorUpload && !isV5Claim && skipsFinalOwnerSignature;
if (needsFactorUpload) {
nextClaimStatus = ClaimStatus.NEEDS_REVISION;
if (mixedFactorAndPrice) {
currentStep = ClaimWorkflowStep.INSURER_REVIEW;
nextWorkflowStep = ClaimWorkflowStep.OWNER_UPLOAD_FACTOR_DOCUMENTS;
} else {
currentStep = ClaimWorkflowStep.OWNER_UPLOAD_FACTOR_DOCUMENTS;
nextWorkflowStep = ClaimWorkflowStep.EXPERT_COST_EVALUATION;
}
} else if (isV5Claim) {
// V5, no factors: hold at WAITING_FOR_FILE_MAKER_APPROVAL
currentStep = ClaimWorkflowStep.CLAIM_COMPLETED;
nextWorkflowStep = ClaimWorkflowStep.CLAIM_COMPLETED;
} else if (completesWithoutFactors) {
currentStep = ClaimWorkflowStep.CLAIM_COMPLETED;
nextWorkflowStep = ClaimWorkflowStep.CLAIM_COMPLETED;
}
const mergedSelectedParts = [...ownerSelectedParts];
if (expertAddedParts.length > 0) {
const mergedKeys = new Set(
mergedSelectedParts.map((sp) => partLookupKey(sp)),
);
for (const sp of expertAddedParts) {
const k = partLookupKey(sp);
if (!mergedKeys.has(k)) {
mergedKeys.add(k);
mergedSelectedParts.push(sp);
}
}
}
const persistedCaseStatus =
isV5Claim && !needsFactorUpload
? ClaimCaseStatus.WAITING_FOR_FILE_MAKER_APPROVAL
: nextCaseStatus;
const updatePayload: Record<string, unknown> = {
status: persistedCaseStatus,
claimStatus: nextClaimStatus,
...(expertAddedParts.length > 0
? { "damage.selectedParts": mergedSelectedParts }
: {}),
"workflow.locked": false,
$unset: {
"workflow.lockedAt": "",
"workflow.expiredAt": "",
"workflow.lockedBy": "",
"workflow.preLockQueueSnapshot": "",
"evaluation.ownerInsurerApproval": "",
"evaluation.ownerPricedPartsApproval": "",
},
...(normalizedCurrentCarPrice && parsedCurrentCarPrice != null
? {
"vehicle.price": normalizedCurrentCarPrice,
"vehicle.carPrice": parsedCurrentCarPrice,
}
: {}),
"workflow.currentStep": currentStep,
"workflow.nextStep": nextWorkflowStep,
[`evaluation.${replyField}`]: replyPayload,
$push: {
"workflow.completedSteps": completedStep,
history: {
type: isFinalReplyAfterObjection
? "EXPERT_FINAL_REPLY_SUBMITTED"
: "EXPERT_REPLY_SUBMITTED",
actor: {
actorId: new Types.ObjectId(actor.sub),
actorName: actor.fullName,
actorType: "damage_expert",
},
timestamp: new Date(),
metadata: {
factorNeeded: needsFactorUpload,
mixedFactorAndPrice,
allFactorLines,
partsCount: processedParts.length,
isFinalReplyAfterObjection,
replyField,
},
},
},
};
await this.claimCaseDbService.findByIdAndUpdate(
claimRequestId,
updatePayload,
);
await this.recordClaimExpertActivity({
expertId: String(actor.sub),
tenantId: this.claimActivityTenantId(claim, actor),
claimId: String(claimRequestId),
eventType: ExpertFileActivityType.HANDLED,
idempotencyKey: `claim:${claimRequestId}:handled:${actor.sub}`,
});
// V1 retains its existing final owner-signature notification. V2–V5 do not
// send this notification because their completion policy is manual Fanavaran
// submission after expert work (and FileMaker approval for V5).
if (!needsFactorUpload && !isV5Claim && !skipsFinalOwnerSignature) {
const ownerPhoneNotify = await this.resolveClaimOwnerPhone(claim);
if (ownerPhoneNotify) {
const expertLastName =
actor?.fullName?.trim()?.split(/\s+/).pop() || "کارشناس";
await this.smsOrchestrationService.sendSignatureReviewNotice({
receptor: ownerPhoneNotify,
fileKind: "claim",
publicId: claim.publicId,
expertLastName,
link: this.smsOrchestrationService.buildClaimLink(
String(claim._id),
"v2",
),
});
}
}
// V2–V5 completion and FileMaker approval do not trigger a Fanavaran
// submission; the expert submits manually when ready.
return {
claimRequestId,
status: persistedCaseStatus,
claimStatus: nextClaimStatus,
currentStep,
workflowNextStep: nextWorkflowStep,
factorNeeded: needsFactorUpload,
mixedPricingAndFactors: mixedFactorAndPrice,
allPartsFactorNeeded: !!needsFactorUpload && !!allFactorLines,
isFinalReplyAfterObjection,
};
}
/**
* V2: Expert marks claim for in-person visit.
*
* This is used when the expert decides the user must attend in person
* before a final assessment can be made.
*
* Validations:
* - Claim must exist
* - Must be locked by this expert
* - Status must be EXPERT_REVIEWING
*
* On success:
* - Sets status = IN_PERSON_VISIT_PENDING, claimStatus = NEEDS_REVISION
* - Sets evaluation.visitLocation (optional note)
* - Records history event IN_PERSON_VISIT_REQUESTED
* - Unlocks the workflow so user can act
*/
async requestInPersonVisitV2(
claimRequestId: string,
actor: any,
note?: string,
) {
requireActorClientKey(actor);
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) {
throw new NotFoundException("Claim request not found");
}
await this.assertExpertActorOnClaim(claim, actor);
if (claim.status !== ClaimCaseStatus.EXPERT_REVIEWING) {
throw new BadRequestException(
`Claim is not in EXPERT_REVIEWING state. Current status: ${claim.status}`,
);
}
if (!claim.workflow?.locked) {
throw new ForbiddenException(
"You must lock the claim before requesting an in-person visit",
);
}
if (claim.workflow.lockedBy?.actorId?.toString() !== actor.sub) {
throw new ForbiddenException("This claim is locked by another expert");
}
const visitSnapshot = await this.snapshotDamageExpert(actor.sub);
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
claimStatus: ClaimStatus.NEEDS_REVISION,
status: ClaimCaseStatus.IN_PERSON_VISIT_PENDING,
"workflow.locked": false,
$unset: {
"workflow.lockedAt": "",
"workflow.expiredAt": "",
"workflow.lockedBy": "",
"workflow.preLockQueueSnapshot": "",
},
"evaluation.visitLocation": note?.trim() || "برای ادامه ارزیابی، به شعبه رسیدگی پرونده مراجعه کنید.",
...(visitSnapshot && {
"evaluation.inPersonVisitExpertProfileSnapshot": visitSnapshot,
}),
$push: {
history: {
type: "IN_PERSON_VISIT_REQUESTED",
actor: {
actorId: new Types.ObjectId(actor.sub),
actorName: actor.fullName,
actorType: "damage_expert",
},
timestamp: new Date(),
metadata: {
note: note || "Expert requested in-person visit",
},
},
},
});
await this.recordClaimExpertActivity({
expertId: String(actor.sub),
tenantId: this.claimActivityTenantId(claim, actor),
claimId: String(claimRequestId),
eventType: ExpertFileActivityType.HANDLED,
idempotencyKey: `claim:${claimRequestId}:handled:inperson:${actor.sub}`,
});
return {
claimRequestId,
status: ClaimCaseStatus.IN_PERSON_VISIT_PENDING,
claimStatus: ClaimStatus.NEEDS_REVISION,
message: "In-person visit requested. User will be notified.",
};
}
/**
* V2: Count claim cases in this damage expert’s portfolio, grouped for dashboard.
* Includes files the expert locked, replied on, or has CHECKED/HANDLED in expertFileActivities.
* Does not include the open tenant queue (`WAITING_FOR_DAMAGE_EXPERT`) unless this expert touched the file.
*/
async getStatusReportBucketsV2(actor: any): Promise<Record<string, number>> {
if (actor.role === RoleEnum.FIELD_EXPERT) {
const rows = (await this.claimCaseDbService.find(
{ initiatedByFieldExpertId: new Types.ObjectId(actor.sub) },
{ lean: true },
)) as any[];
const buckets = initialClaimExpertReportBuckets();
for (const doc of rows) {
const key = claimCaseStatusToReportBucket(String(doc.status ?? ""));
buckets.all++;
buckets[key] = (buckets[key] ?? 0) + 1;
}
buckets["PENDING_ON_USER"] =
(buckets[ClaimCaseStatus.WAITING_FOR_USER_RESEND] ?? 0) +
(buckets[ClaimCaseStatus.WAITING_FOR_INSURER_APPROVAL] ?? 0) +
(buckets[ClaimCaseStatus.INSURER_REVIEW_AWAITING_OWNER_SIGN] ?? 0) +
(buckets[ClaimCaseStatus.INSURER_REVIEW_MIXED_FACTORS_PENDING] ?? 0) +
(buckets[ClaimCaseStatus.OWNER_REPAIR_FACTOR_UPLOAD_PENDING] ?? 0);
buckets["CHECK_NEEDED"] =
buckets["PENDING_ON_USER"] +
(buckets[ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT] ?? 0);
return buckets;
}
const clientKey = requireActorClientKey(actor);
const expertId = String(actor.sub);
const expertOid = new Types.ObjectId(expertId);
const activityEvents = await this.expertFileActivityDbService.findByExpert(
expertId,
ExpertFileKind.CLAIM,
);
const activityFileIds =
expertPortfolioFileIdsFromActivityEvents(activityEvents);
const orClauses: Record<string, unknown>[] = [
{ "workflow.lockedBy.actorId": expertOid },
{ "evaluation.damageExpertReply.actorDetail.actorId": expertOid },
{ "evaluation.damageExpertReplyFinal.actorDetail.actorId": expertOid },
{ "evaluation.damageExpertResend.requestedByExpertId": expertOid },
];
const activityOids = objectIdsFromStringSet(activityFileIds);
if (activityOids.length > 0) {
orClauses.push({ _id: { $in: activityOids } });
}
const rows =
orClauses.length === 0
? []
: await this.claimCaseDbService.find(
{ $or: orClauses },
{ lean: true },
);
const buckets = initialClaimExpertReportBuckets();
const seen = new Set<string>();
for (const doc of rows as Record<string, unknown>[]) {
const id = String(doc._id ?? "");
if (seen.has(id)) continue;
if (
!claimDocInExpertPortfolio(doc, expertId, activityFileIds, clientKey)
) {
continue;
}
seen.add(id);
const key = claimCaseStatusToReportBucket(String(doc.status ?? ""));
buckets.all++;
buckets[key] = (buckets[key] ?? 0) + 1;
}
// Add new calculated fields for front-end
buckets["PENDING_ON_USER"] =
buckets[ClaimCaseStatus.WAITING_FOR_USER_RESEND] +
buckets[ClaimCaseStatus.WAITING_FOR_INSURER_APPROVAL] +
buckets[ClaimCaseStatus.INSURER_REVIEW_AWAITING_OWNER_SIGN] +
buckets[ClaimCaseStatus.INSURER_REVIEW_MIXED_FACTORS_PENDING] +
buckets[ClaimCaseStatus.OWNER_REPAIR_FACTOR_UPLOAD_PENDING];
buckets["CHECK_NEEDED"] =
buckets["PENDING_ON_USER"] +
buckets[ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT];
return buckets;
}
async getUnifiedFileStatusReportV2(
actor: any,
query: UnifiedFileStatusReportQueryDto = {},
): Promise<UnifiedFileStatusReportDto> {
const { claims, blameById } =
await this.collectClaimPortfolioWithBlame(actor);
const { fromDate, toDate } = parseListDateRange(query.from, query.to);
const filteredClaims = claims.filter((c) => {
if (
!isInListDateRange(
c.createdAt as Date | string | undefined,
fromDate,
toDate,
)
) {
return false;
}
if (!query.fileType) return true;
const blame = c.blameRequestId
? blameById.get(String(c.blameRequestId))
: undefined;
const type =
blame?.type ??
(c as { snapshot?: { accident?: { type?: string } } })?.snapshot
?.accident?.type;
return type === query.fileType;
});
return {
statuses: getUnifiedFileStatusCatalog(),
counts: countUnifiedFileStatuses(
filteredClaims.map((c) => {
const blame = c.blameRequestId
? blameById.get(String(c.blameRequestId))
: undefined;
return {
blameStatus: blame?.status,
claimStatus: c.status,
};
}),
),
};
}
private async collectClaimPortfolioWithBlame(actor: any): Promise<{
claims: any[];
blameById: Map<string, any>;
}> {
let claims: any[] = [];
if (actor.role === RoleEnum.FIELD_EXPERT) {
const expertOid = new Types.ObjectId(actor.sub);
// Exclude V4/V5 blame files — same rule as getFieldExpertClaimListV2.
const expertBlameIds = await this.blameRequestDbService
.find(
{
expertInitiated: true,
initiatedByFieldExpertId: expertOid,
isMadeByFileMaker: { $ne: true },
},
{ select: "_id", lean: true },
)
.then((docs) => docs.map((d) => (d as { _id: unknown })._id));
const claimOr: Record<string, unknown>[] = [
{
initiatedByFieldExpertId: expertOid,
requiresFileMakerApproval: { $ne: true },
},
];
if (expertBlameIds.length > 0) {
claimOr.push({ blameRequestId: { $in: expertBlameIds } });
}
claims = (await this.claimCaseDbService.find({ $or: claimOr })) as any[];
} else {
const clientKey = requireActorClientKey(actor);
const expertId = String(actor.sub);
const expertOid = new Types.ObjectId(expertId);
const activityEvents =
await this.expertFileActivityDbService.findByExpert(
expertId,
ExpertFileKind.CLAIM,
);
const activityFileIds =
expertPortfolioFileIdsFromActivityEvents(activityEvents);
const orClauses: Record<string, unknown>[] = [
{ "workflow.lockedBy.actorId": expertOid },
{ "evaluation.damageExpertReply.actorDetail.actorId": expertOid },
{ "evaluation.damageExpertReplyFinal.actorDetail.actorId": expertOid },
{ "evaluation.damageExpertResend.requestedByExpertId": expertOid },
];
const activityOids = objectIdsFromStringSet(activityFileIds);
if (activityOids.length > 0) {
orClauses.push({ _id: { $in: activityOids } });
}
const rows =
orClauses.length === 0
? []
: await this.claimCaseDbService.find(
{ $or: orClauses },
{ lean: true },
);
const seen = new Set<string>();
for (const doc of rows as Record<string, unknown>[]) {
const id = String(doc._id ?? "");
if (seen.has(id)) continue;
if (
!claimDocInExpertPortfolio(doc, expertId, activityFileIds, clientKey)
) {
continue;
}
seen.add(id);
claims.push(doc);
}
}
const blameIds = [
...new Set(
claims
.map((c) => c.blameRequestId?.toString())
.filter((id): id is string => !!id),
),
];
const blames =
blameIds.length > 0
? ((await this.blameRequestDbService.find(
{
_id: { $in: blameIds.map((id) => new Types.ObjectId(id)) },
},
{ lean: true, select: "status publicId type" },
)) as any[])
: [];
const blameById = new Map<string, any>(
blames.map((b) => [String(b._id), b]),
);
return { claims, blameById };
}
private paginateClaimListV2(
list: ClaimListItemV2Dto[],
query: ListQueryV2Dto,
): GetClaimListV2ResponseDto {
let filtered = list;
if (query.unifiedStatus) {
filtered = list.filter(
(item) => item.unifiedFileStatus === query.unifiedStatus,
);
}
const { fromDate, toDate } = parseListDateRange(
query.startDate,
query.endDate,
);
if (fromDate || toDate) {
filtered = filtered.filter((item) =>
isInListDateRange(item.createdAt, fromDate, toDate),
);
}
const paged = applyListQueryV2(
filtered,
{
publicId: (r) => r.publicId,
createdAt: (r) => r.createdAt,
requestNo: (r) => r.publicId,
status: (r) => r.unifiedFileStatus ?? r.status,
fileType: (r) => r.blameRequestType,
searchExtras: (r) =>
[
r.claimRequestId,
r.currentStep,
r.vehicle?.carName,
r.vehicle?.carModel,
r.blameRequestType,
r.unifiedFileStatus,
r.status,
].filter(Boolean) as string[],
},
query,
);
return {
list: toPublicListItems(paged.list),
total: paged.total,
page: paged.page,
limit: paged.limit,
totalPages: paged.totalPages,
};
}
/**
* V2: Get claim list for damage expert
*
* Returns claims that are (then filtered to the actor's insurer via `claimCaseTouchesClient`):
* 1. WAITING_FOR_DAMAGE_EXPERT and not locked (open queue)
* 2. Locked by this expert (in-progress)
* 3. EXPERT_VALIDATING_REPAIR_FACTORS (or legacy WAITING_FOR_INSURER_APPROVAL) + UNDER_REVIEW at EXPERT_COST_EVALUATION (factor validation queue)
*/
async getClaimListV2(
actor: any,
query: ListQueryV2Dto = {},
): Promise<GetClaimListV2ResponseDto> {
if (actor.role === RoleEnum.FIELD_EXPERT) {
return this.getFieldExpertClaimListV2(actor, query);
}
if (actor.role === RoleEnum.FILE_REVIEWER) {
return this.getFileReviewerClaimListV2(actor, query);
}
if (actor.role === RoleEnum.FILE_MAKER) {
return this.getFileMakerClaimListV2(actor, query);
}
requireActorClientKey(actor);
const actorId = actor.sub;
const clientKey = actor.clientKey as string;
await this.reconcileStaleExpertReviewingClaimLocksForTenant(actor);
const claims = await this.claimCaseDbService.find({
$or: [
// Available: waiting, not locked
{
status: ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT,
"workflow.locked": { $ne: true },
// No persistent assignee (or expired without decision)
$or: [
{ "workflow.assignedForReviewBy": { $exists: false } },
{ "workflow.assignedForReviewBy": null },
],
},
// This expert's locked/in-progress claims
{
"workflow.locked": true,
"workflow.lockedBy.actorId": new Types.ObjectId(actorId),
},
// This expert's persistently assigned claims (decided or resend/objection follow-up)
{
"workflow.assignedForReviewBy.actorId": new Types.ObjectId(actorId),
},
// Factor validation queue (open to all tenant experts — no lock needed)
{
$or: [
{
status: ClaimCaseStatus.EXPERT_VALIDATING_REPAIR_FACTORS,
claimStatus: ClaimStatus.UNDER_REVIEW,
"workflow.currentStep": ClaimWorkflowStep.EXPERT_COST_EVALUATION,
},
{
status: ClaimCaseStatus.WAITING_FOR_INSURER_APPROVAL,
claimStatus: ClaimStatus.UNDER_REVIEW,
"workflow.currentStep": ClaimWorkflowStep.EXPERT_COST_EVALUATION,
},
],
},
// WAITING_FOR_USER_RESEND assigned to this expert
{
status: ClaimCaseStatus.WAITING_FOR_USER_RESEND,
"workflow.assignedForReviewBy.actorId": new Types.ObjectId(actorId),
},
// EXPERT_REVIEWING with stale lock (reconciliation will fix status, show in meantime)
{
status: ClaimCaseStatus.EXPERT_REVIEWING,
"workflow.locked": { $ne: true },
},
],
});
const tenantFiltered = (claims as any[]).filter((c) =>
claimCaseTouchesClient(c, clientKey),
);
const filtered = await this.filterDamageExpertClaimsByBranch(
tenantFiltered,
actor,
);
// Reconcile stale locks — if no decision was made, also clear assignedForReviewBy
const staleLockToReconcile = filtered.filter(
(c) =>
c.workflow?.locked && !this.isClaimV2WorkflowLockCurrentlyEnforced(c),
);
const touchedIds = (
await Promise.all(
staleLockToReconcile.map(async (c) => {
const updated = await this.expireClaimWorkflowLockV2IfStale(
String(c._id),
);
return updated ? String(c._id) : null;
}),
)
).filter((id): id is string => id != null);
if (touchedIds.length > 0) {
const refreshed = await this.claimCaseDbService.find({
_id: { $in: touchedIds.map((id) => new Types.ObjectId(id)) },
});
const byId = new Map(refreshed.map((r) => [String(r._id), r] as const));
for (const c of filtered) {
const r = byId.get(String(c._id));
if (r) Object.assign(c, r);
}
}
// Post-filter: remove files that belong to another expert after reconciliation
const finalFiltered = filtered.filter((c) => {
const assignedId = String(c.workflow?.assignedForReviewBy?.actorId ?? "");
const lockEnforced =
c.workflow?.locked && this.isClaimV2WorkflowLockCurrentlyEnforced(c);
const lockedById = String(c.workflow?.lockedBy?.actorId ?? "");
const isFactorValidation = claimIsAwaitingExpertFactorValidationV2(c);
// Factor validation is open to all tenant experts
if (isFactorValidation) return true;
// Available: no assignee, not locked by someone else
const isAvailable =
c.status === ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT &&
!assignedId &&
(!lockEnforced || lockedById === actorId);
// Mine: assigned to me (covers decided, resend, objection follow-up)
const isAssignedToMe = !!assignedId && assignedId === actorId;
// Mine: currently locked by me
const isLockedByMe = lockEnforced && lockedById === actorId;
// Mine: resend pending and I'm the assigned expert
const isResendMine =
c.status === ClaimCaseStatus.WAITING_FOR_USER_RESEND && isAssignedToMe;
return isAvailable || isAssignedToMe || isLockedByMe || isResendMine;
});
const blameIds = [
...new Set(
finalFiltered
.map((c) => c.blameRequestId?.toString())
.filter((id): id is string => !!id),
),
];
const blames =
blameIds.length > 0
? ((await this.blameRequestDbService.find(
{ _id: { $in: blameIds.map((id) => new Types.ObjectId(id)) } },
{
lean: true,
select:
"type creationMethod parties expert.decision blameStatus status isMadeByFileMaker",
},
)) as any[])
: [];
const blameById = new Map<string, any>(
blames.map((b) => [String(b._id), b]),
);
const list = finalFiltered.map((c) => {
const awaitingFactorValidation =
claimIsAwaitingExpertFactorValidationV2(c);
const v = this.vehicleForExpertFromClaimAndBlameMap(c, blameById);
const blame = c.blameRequestId
? blameById.get(c.blameRequestId.toString())
: undefined;
const fileCtx = blame ? this.blameFileContextForExpert(blame) : {};
const lockActive = !!(
c.workflow?.locked && this.isClaimV2WorkflowLockCurrentlyEnforced(c)
);
const statusForList =
c.status === ClaimCaseStatus.EXPERT_REVIEWING
? ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT
: c.status;
return {
claimRequestId: c._id.toString(),
publicId: c.publicId,
status: statusForList,
unifiedFileStatus: resolveUnifiedFileStatus({
blameStatus: blame?.status,
claimStatus: c.status,
}),
currentStep: c.workflow?.currentStep || "",
locked: lockActive,
lockedBy:
lockActive && c.workflow?.lockedBy
? {
actorId: c.workflow.lockedBy.actorId?.toString(),
actorName: c.workflow.lockedBy.actorName,
lockedAt: (c.workflow as any).lockedAt?.toISOString?.(),
expiredAt: (c.workflow as any).expiredAt?.toISOString?.(),
}
: undefined,
vehicle: v
? { carName: v.carName, carModel: v.carModel, carType: v.carType }
: undefined,
...fileCtx,
partyIdentities:
fileCtx.partyIdentities ?? c.parties ?? c.snapshot?.parties,
blameRequestId: c.blameRequestId?.toString(),
createdAt: c.createdAt,
awaitingFactorValidation,
};
}) as ClaimListItemV2Dto[];
return this.paginateClaimListV2(list, query);
}
/**
* Claim list for a FIELD_EXPERT — returns only the claims they personally
* initiated (expert-initiated IN_PERSON blame → createClaimFromBlameForExpertV2).
*/
private async getFieldExpertClaimListV2(
actor: any,
query: ListQueryV2Dto = {},
): Promise<GetClaimListV2ResponseDto> {
const expertOid = new Types.ObjectId(actor.sub);
// Exclude V4/V5 blame files (isMadeByFileMaker=true) — those belong to
// the FILE_MAKER/FILE_REVIEWER flows, not the V3 field-expert flow.
const expertBlameIds = await this.blameRequestDbService
.find(
{
expertInitiated: true,
initiatedByFieldExpertId: expertOid,
isMadeByFileMaker: { $ne: true },
},
{ select: "_id", lean: true },
)
.then((docs) => docs.map((d) => (d as { _id: unknown })._id));
const claimOr: Record<string, unknown>[] = [
// Direct claim link: exclude V5 claims that require FileMaker approval
{
initiatedByFieldExpertId: expertOid,
requiresFileMakerApproval: { $ne: true },
},
];
if (expertBlameIds.length > 0) {
claimOr.push({ blameRequestId: { $in: expertBlameIds } });
}
const claims = (await this.claimCaseDbService.find({
$or: claimOr,
})) as any[];
const blameIds = [
...new Set(
claims
.map((c) => c.blameRequestId?.toString())
.filter((id): id is string => !!id),
),
];
const blames =
blameIds.length > 0
? ((await this.blameRequestDbService.find(
{ _id: { $in: blameIds.map((id) => new Types.ObjectId(id)) } },
{
lean: true,
select:
"type creationMethod parties expert.decision blameStatus status",
},
)) as any[])
: [];
const blameById = new Map<string, any>(
blames.map((b) => [String(b._id), b]),
);
const list = claims.map((c) => {
const v = this.vehicleForExpertFromClaimAndBlameMap(c, blameById);
const blame = c.blameRequestId
? blameById.get(c.blameRequestId.toString())
: undefined;
const fileCtx = blame ? this.blameFileContextForExpert(blame) : {};
const lockActive = !!(
c.workflow?.locked && this.isClaimV2WorkflowLockCurrentlyEnforced(c)
);
return {
claimRequestId: c._id.toString(),
publicId: c.publicId,
status: c.status,
unifiedFileStatus: resolveUnifiedFileStatus({
blameStatus: blame?.status,
claimStatus: c.status,
}),
currentStep: c.workflow?.currentStep || "",
locked: lockActive,
lockedBy:
lockActive && c.workflow?.lockedBy
? {
actorId: c.workflow.lockedBy.actorId?.toString(),
actorName: c.workflow.lockedBy.actorName,
lockedAt: (c.workflow as any).lockedAt?.toISOString?.(),
expiredAt: (c.workflow as any).expiredAt?.toISOString?.(),
}
: undefined,
vehicle: v
? { carName: v.carName, carModel: v.carModel, carType: v.carType }
: undefined,
...fileCtx,
partyIdentities:
fileCtx.partyIdentities ?? c.parties ?? c.snapshot?.parties,
blameRequestId: c.blameRequestId?.toString(),
createdAt: c.createdAt,
awaitingFactorValidation: claimIsAwaitingExpertFactorValidationV2(c),
needsFileReviewerCompletion:
String(blame?.status ?? "") === "WAITING_FOR_FILE_REVIEWER" ||
(!!blame?.isMadeByFileMaker &&
String(blame?.status ?? "") === "WAITING_FOR_EXPERT"),
};
}) as ClaimListItemV2Dto[];
return this.paginateClaimListV2(list, query);
}
/**
* Claim list for FILE_REVIEWER.
*
* Visibility rules (both V4 and V5 files):
* - WAITING_FOR_FILE_REVIEWER files made by a FileMaker that are either:
* (a) not yet assigned to any reviewer, OR
* (b) already assigned to THIS reviewer
* - Files already assigned to THIS reviewer (any post-assignment status)
*
* V4: isMadeByFileMaker=true, requiresFileMakerApproval=false
* V5: isMadeByFileMaker=true, requiresFileMakerApproval=true
*
* All scoped to this reviewer's insurance company via blame party clientId.
*/
private async getFileReviewerClaimListV2(
actor: any,
query: ListQueryV2Dto = {},
): Promise<GetClaimListV2ResponseDto> {
const clientKey = requireActorClientKey(actor);
const reviewerOid = new Types.ObjectId(actor.sub);
// Find V4 and V5 blame files visible to this reviewer
const blames = (await this.blameRequestDbService.find(
{
isMadeByFileMaker: true,
expertInitiated: true,
creationMethod: "IN_PERSON",
$or: [
// Open: sealed by FileMaker, not yet taken by any reviewer
{
status: "WAITING_FOR_FILE_REVIEWER",
$or: [
{ assignedFileReviewerId: { $exists: false } },
{ assignedFileReviewerId: null },
],
},
// Taken by this reviewer (any post-assignment status)
{ assignedFileReviewerId: reviewerOid },
],
},
{
lean: true,
select:
"_id branchId initiatedByFieldExpertId type creationMethod parties blameStatus status expert.decision assignedFileReviewerId requiresFileMakerApproval",
},
)) as any[];
if (blames.length === 0) {
return this.paginateClaimListV2([], query);
}
// Scope to this reviewer's insurer via blame party clientId
const tenantScopedBlames = blames.filter((b) =>
blameCaseTouchesClient(b, clientKey),
);
const scopedBlames = (
await Promise.all(
tenantScopedBlames.map(async (blame) => {
try {
await this.fanavaranLocationService.assertMakerReviewerBranchCompatible(
{
fileMakerId: blame.initiatedByFieldExpertId
? String(blame.initiatedByFieldExpertId)
: null,
fileReviewerId: actor.sub,
caseBranchId: blame.branchId ? String(blame.branchId) : null,
},
);
return blame;
} catch {
return null;
}
}),
)
).filter((blame): blame is any => blame != null);
if (scopedBlames.length === 0) {
return this.paginateClaimListV2([], query);
}
const scopedBlameIds = scopedBlames.map((b) => b._id);
const claims = (await this.claimCaseDbService.find({
blameRequestId: { $in: scopedBlameIds },
})) as any[];
const blameById = new Map<string, any>(
scopedBlames.map((b) => [String(b._id), b]),
);
const list = claims.map((c) => {
const blame = c.blameRequestId
? blameById.get(c.blameRequestId.toString())
: undefined;
const v = this.vehicleForExpertFromClaimAndBlameMap(c, blameById);
const fileCtx = blame ? this.blameFileContextForExpert(blame) : {};
const lockActive = !!(
c.workflow?.locked && this.isClaimV2WorkflowLockCurrentlyEnforced(c)
);
const assignedToMe =
blame?.assignedFileReviewerId &&
String(blame.assignedFileReviewerId) === actor.sub;
return {
claimRequestId: c._id.toString(),
publicId: c.publicId,
status: c.status,
unifiedFileStatus: resolveUnifiedFileStatus({
blameStatus: blame?.status,
claimStatus: c.status,
}),
currentStep: c.workflow?.currentStep || "",
locked: lockActive,
lockedBy:
lockActive && c.workflow?.lockedBy
? {
actorId: c.workflow.lockedBy.actorId?.toString(),
actorName: c.workflow.lockedBy.actorName,
lockedAt: (c.workflow as any).lockedAt?.toISOString?.(),
expiredAt: (c.workflow as any).expiredAt?.toISOString?.(),
}
: undefined,
vehicle: v
? { carName: v.carName, carModel: v.carModel, carType: v.carType }
: undefined,
...fileCtx,
partyIdentities:
fileCtx.partyIdentities ?? c.parties ?? c.snapshot?.parties,
blameRequestId: c.blameRequestId?.toString(),
createdAt: c.createdAt,
awaitingFactorValidation: claimIsAwaitingExpertFactorValidationV2(c),
needsFileReviewerCompletion:
String(blame?.status ?? "") === "WAITING_FOR_FILE_REVIEWER" ||
(!!blame?.isMadeByFileMaker &&
String(blame?.status ?? "") === "WAITING_FOR_EXPERT"),
assignedToMe: !!assignedToMe,
requiresFileMakerApproval: !!(c as any).requiresFileMakerApproval,
fileMakerRejectionCount: (c as any).fileMakerRejectionCount ?? 0,
fileMakerRejectionReason:
(c as any).fileMakerRejectionReason ?? undefined,
};
}) as ClaimListItemV2Dto[];
return this.paginateClaimListV2(list, query);
}
/**
* Claim list for FILE_MAKER — returns claims linked to blame files they
* personally created (V4 and V5 flows).
* V4: requiresFileMakerApproval=false · V5: requiresFileMakerApproval=true
*/
private async getFileMakerClaimListV2(
actor: any,
query: ListQueryV2Dto = {},
): Promise<GetClaimListV2ResponseDto> {
const makerOid = new Types.ObjectId(actor.sub);
const ownMakerBlames = (await this.blameRequestDbService.find(
{ isMadeByFileMaker: true, initiatedByFieldExpertId: makerOid },
{
lean: true,
select:
"_id branchId type creationMethod parties blameStatus status expert.decision assignedFileReviewerId requiresFileMakerApproval",
},
)) as any[];
const hasBranchScopedFiles = ownMakerBlames.some(
(blame) => !!blame.branchId,
);
const makerBranchId = hasBranchScopedFiles
? await this.fanavaranLocationService.fileMakerBranchId(actor.sub)
: undefined;
if (hasBranchScopedFiles && !makerBranchId) {
throw new ForbiddenException(
"FileMaker account is not assigned to a branch.",
);
}
const makerBlames = ownMakerBlames.filter(
(blame) => !blame.branchId || String(blame.branchId) === makerBranchId,
);
if (makerBlames.length === 0) {
return this.paginateClaimListV2([], query);
}
const blameIds = makerBlames.map((b) => b._id);
// Include all claims linked to this maker's blames — both V4 (requiresFileMakerApproval=false)
// and V5 (requiresFileMakerApproval=true).
const claims = (await this.claimCaseDbService.find({
blameRequestId: { $in: blameIds },
})) as any[];
const blameById = new Map<string, any>(
makerBlames.map((b) => [String(b._id), b]),
);
const list = claims.map((c) => {
const blame = c.blameRequestId
? blameById.get(c.blameRequestId.toString())
: undefined;
const v = this.vehicleForExpertFromClaimAndBlameMap(c, blameById);
const fileCtx = blame ? this.blameFileContextForExpert(blame) : {};
const lockActive = !!(
c.workflow?.locked && this.isClaimV2WorkflowLockCurrentlyEnforced(c)
);
return {
claimRequestId: c._id.toString(),
publicId: c.publicId,
status: c.status,
unifiedFileStatus: resolveUnifiedFileStatus({
blameStatus: blame?.status,
claimStatus: c.status,
}),
currentStep: c.workflow?.currentStep || "",
locked: lockActive,
lockedBy:
lockActive && c.workflow?.lockedBy
? {
actorId: c.workflow.lockedBy.actorId?.toString(),
actorName: c.workflow.lockedBy.actorName,
lockedAt: (c.workflow as any).lockedAt?.toISOString?.(),
expiredAt: (c.workflow as any).expiredAt?.toISOString?.(),
}
: undefined,
vehicle: v
? { carName: v.carName, carModel: v.carModel, carType: v.carType }
: undefined,
...fileCtx,
partyIdentities:
fileCtx.partyIdentities ?? c.parties ?? c.snapshot?.parties,
blameRequestId: c.blameRequestId?.toString(),
createdAt: c.createdAt,
awaitingFactorValidation: claimIsAwaitingExpertFactorValidationV2(c),
requiresFileMakerApproval: !!(c as any).requiresFileMakerApproval,
fileMakerRejectionCount: (c as any).fileMakerRejectionCount ?? 0,
fileMakerRejectionReason:
(c as any).fileMakerRejectionReason ?? undefined,
needsFileReviewerCompletion:
String(blame?.status ?? "") === "WAITING_FOR_FILE_REVIEWER" ||
(!!blame?.isMadeByFileMaker &&
String(blame?.status ?? "") === "WAITING_FOR_EXPERT"),
assignedFileReviewerId: blame?.assignedFileReviewerId
? String(blame.assignedFileReviewerId)
: undefined,
};
}) as ClaimListItemV2Dto[];
return this.paginateClaimListV2(list, query);
}
/**
* Load linked blame case for damage-expert claim detail (same enrichment as expert-blame `findOneV2`:
* party evidence `videoUrl` / `voiceUrls`, Jalali date strings).
*/
private async buildBlameCaseSnapshotForClaimDetail(
blameRequestId: string,
): Promise<Record<string, unknown> | null> {
const doc =
await this.blameRequestDbService.findByIdWithoutHistory(blameRequestId);
if (!doc) {
return null;
}
const docRec = doc as Record<string, unknown>;
const built = buildMutualAgreementExpertDecision(docRec);
const existingDecision = (
docRec.expert as Record<string, unknown> | undefined
)?.decision as Record<string, unknown> | undefined;
if (built && !existingDecision?.guiltyPartyId) {
const prevExpert =
typeof docRec.expert === "object" && docRec.expert !== null
? { ...(docRec.expert as Record<string, unknown>) }
: {};
const expert = { ...prevExpert, decision: built };
await this.blameRequestDbService.findByIdAndUpdate(blameRequestId, {
$set: { expert },
});
docRec.expert = expert;
}
const parties = (doc.parties ?? []) as Array<{
evidence?: {
videoId?: string | number;
voices?: (string | number)[];
videoUrl?: string;
voiceUrls?: string[];
};
}>;
for (const party of parties) {
if (!party.evidence) continue;
const evidence = party.evidence as Record<string, unknown>;
if (evidence.videoId) {
const videoDoc = await this.blameVideoDbService.findById(
String(evidence.videoId),
);
if (videoDoc?.path) {
evidence.videoUrl = buildFileLink(videoDoc.path);
}
}
if (evidence.voices && Array.isArray(evidence.voices)) {
const voiceUrls: string[] = [];
for (const voiceId of evidence.voices) {
const voiceDoc = await this.blameVoiceDbService.findById(
String(voiceId),
);
if (voiceDoc?.path) {
voiceUrls.push(buildFileLink(voiceDoc.path));
}
}
evidence.voiceUrls = voiceUrls;
}
}
const createdAt = doc.createdAt
? new Date(doc.createdAt as string | number)
: new Date();
const updatedAt = doc.updatedAt
? new Date(doc.updatedAt as string | number)
: new Date();
const [createdDate, createdTime] = toJalaliDateAndTime(createdAt);
const [updatedDate, updatedTime] = toJalaliDateAndTime(updatedAt);
(doc as Record<string, unknown>).createdAtFormatted =
`${createdDate} ${createdTime}`;
(doc as Record<string, unknown>).updatedAtFormatted =
`${updatedDate} ${updatedTime}`;
docRec.parties = enrichBlamePartiesForAgreementView(docRec).map(
(party) => ({
...party,
participants: sanitizeStoredInquiryParticipants(party.participants),
}),
);
return docRec;
}
/** Strip bulky insurer-inquiry payloads (`raw` / `mapped`) from vehicle.inquiry. */
private sanitizeVehicleInquiryForApi(vehicle: any) {
if (!vehicle || typeof vehicle !== "object") return vehicle;
const inquiry = vehicle.inquiry;
if (!inquiry || typeof inquiry !== "object") return vehicle;
const { raw, mapped, ...safeInquiry } = inquiry as Record<string, unknown>;
return {
...vehicle,
inquiry: safeInquiry,
};
}
/** Linked blame snapshot for damage-expert detail: keep API response lean. */
private sanitizeBlameCaseForClaimDetailApi(
blame: Record<string, unknown>,
): Record<string, unknown> {
const out = { ...blame };
const parties = out.parties;
if (Array.isArray(parties)) {
out.parties = parties.map((p: any) =>
p && typeof p === "object"
? {
...p,
participants: sanitizeStoredInquiryParticipants(p.participants),
vehicle: this.sanitizeVehicleInquiryForApi(p.vehicle),
}
: p,
);
}
return out;
}
/** JSON-safe `expert.decision` for API responses (ObjectIds → string). */
private serializeBlameExpertDecisionForClaimDetail(
decision: unknown,
): Record<string, unknown> | undefined {
if (!decision || typeof decision !== "object") {
return undefined;
}
const d = decision as Record<string, unknown>;
const guilty = d.guiltyPartyId;
const decidedBy = d.decidedByExpertId;
const decidedAt = d.decidedAt;
return {
...d,
guiltyPartyId:
guilty != null &&
typeof (guilty as { toString?: () => string }).toString === "function"
? String(guilty)
: guilty,
decidedByExpertId:
decidedBy != null &&
typeof (decidedBy as { toString?: () => string }).toString ===
"function"
? String(decidedBy)
: decidedBy,
decidedAt:
decidedAt instanceof Date ? decidedAt.toISOString() : decidedAt,
};
}
/**
* True while a workflow lock is still within its window (`expiredAt` when set, else lockedAt + TTL).
* Missing both timestamps on old documents: treat lock as enforced until cleared.
*/
private isClaimV2WorkflowLockCurrentlyEnforced(claim: any): boolean {
if (!claim?.workflow?.locked) return false;
const exp = claim.workflow?.expiredAt;
if (exp) {
return Date.now() < new Date(exp as Date).getTime();
}
const la = claim.workflow?.lockedAt as Date | string | undefined;
if (!la) return true;
return Date.now() < new Date(la).getTime() + EXPERT_WORKFLOW_LOCK_TTL_MS;
}
/**
* EXPERT_REVIEWING + expired lock is not listed until status is reverted. Run expire for this tenant
* so the next query returns those cases as WAITING_FOR_DAMAGE_EXPERT.
*/
private async reconcileStaleExpertReviewingClaimLocksForTenant(actor: {
sub: string;
clientKey?: string;
role?: string;
}): Promise<void> {
if (
(actor as any).role === RoleEnum.FIELD_EXPERT ||
(actor as any).role === RoleEnum.FILE_REVIEWER ||
(actor as any).role === RoleEnum.FILE_MAKER
)
return;
const clientKey = requireActorClientKey(actor);
const lockTtlMs = EXPERT_WORKFLOW_LOCK_TTL_MS;
const now = new Date();
const candidates = (await this.claimCaseDbService.find(
{
status: ClaimCaseStatus.EXPERT_REVIEWING,
"workflow.locked": true,
$or: [
{ "workflow.expiredAt": { $lte: now } },
{
$expr: {
$and: [
{ $eq: ["$workflow.locked", true] },
{
$lte: [{ $add: ["$workflow.lockedAt", lockTtlMs] }, now],
},
],
},
},
],
},
{ lean: true, select: "_id owner" },
)) as Array<{ _id: unknown; owner?: unknown }>;
const relevant = candidates.filter((c) =>
claimCaseTouchesClient(c, clientKey),
);
await Promise.all(
relevant.map((c) => this.expireClaimWorkflowLockV2IfStale(String(c._id))),
);
}
/**
* Persist unlock when claim V2 workflow lock TTL has passed.
* When the case was in {@link ClaimCaseStatus.EXPERT_REVIEWING}, restores queue fields from
* `workflow.preLockQueueSnapshot` (or defaults) and sets status back to WAITING_FOR_DAMAGE_EXPERT
* so the claim reappears in the open expert queue (same intent as blame list expiry + in-memory unlock).
*/
private async expireClaimWorkflowLockV2IfStale(
claimRequestId: string,
): Promise<boolean> {
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim?.workflow?.locked) return false;
const expiredAt = claim.workflow?.expiredAt;
const lockedAt = claim.workflow?.lockedAt;
const now = Date.now();
const ttl = EXPERT_WORKFLOW_LOCK_TTL_MS;
if (expiredAt && now < new Date(expiredAt as Date).getTime()) return false;
if (
!expiredAt &&
lockedAt &&
now < new Date(lockedAt as Date).getTime() + ttl
) {
return false;
}
const lockedById = claim.workflow.lockedBy?.actorId;
const filter: Record<string, unknown> = {
_id: new Types.ObjectId(claimRequestId),
"workflow.locked": true,
};
if (expiredAt) {
filter["workflow.expiredAt"] = expiredAt;
} else if (lockedAt) {
filter["workflow.lockedAt"] = lockedAt;
} else if (lockedById) {
filter["workflow.lockedBy.actorId"] = new Types.ObjectId(
String(lockedById),
);
}
const needsQueueRestore = claim.status === ClaimCaseStatus.EXPERT_REVIEWING;
const snap = claim.workflow?.preLockQueueSnapshot as
| {
claimStatus?: ClaimStatus;
currentStep?: ClaimWorkflowStep;
nextStep?: ClaimWorkflowStep;
}
| undefined;
const restoreClaimStatus = snap?.claimStatus ?? ClaimStatus.PENDING;
const restoreCurrent = this.normalizeClaimWorkflowStepForSnapshot(
snap?.currentStep,
ClaimWorkflowStep.USER_SUBMISSION_COMPLETE,
);
const restoreNext =
snap?.nextStep != null
? this.normalizeClaimWorkflowStepForSnapshot(
snap.nextStep,
ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT,
)
: ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT;
const lockFieldsUnset = {
"workflow.lockedAt": "",
"workflow.expiredAt": "",
"workflow.lockedBy": "",
"workflow.preLockQueueSnapshot": "",
};
const assigneeToPersist = claimWorkflowAssigneeToPersistOnLockExpiry(
claim.workflow,
claim,
);
const expireLockSet: Record<string, unknown> = { "workflow.locked": false };
if (assigneeToPersist) {
expireLockSet["workflow.assignedForReviewBy"] = assigneeToPersist;
}
const update = needsQueueRestore
? {
$set: {
...expireLockSet,
status: ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT,
claimStatus: restoreClaimStatus,
"workflow.currentStep": restoreCurrent,
"workflow.nextStep": restoreNext,
},
$unset: lockFieldsUnset,
}
: {
$set: expireLockSet,
$unset: lockFieldsUnset,
};
const cleared = await this.claimCaseDbService.findOneAndUpdate(
filter as any,
update as any,
{ new: false },
);
if (cleared && lockedById && claim.owner?.userClientKey) {
await this.recordClaimExpertActivity({
expertId: String(lockedById),
tenantId: String(claim.owner.userClientKey),
claimId: String(claimRequestId),
eventType: ExpertFileActivityType.UNCHECKED,
idempotencyKey: `claim:${claimRequestId}:unchecked:expired:${lockedById}`,
});
}
return !!cleared;
}
/**
* V2: Get claim detail for damage expert
*
* Validations:
* - Claim must exist and belong to the actor's insurer (`assertClaimCaseForTenant`)
* - Allowed when: WAITING_FOR_DAMAGE_EXPERT (queue), or EXPERT_REVIEWING (after lock — same expert must be able to reopen detail),
* or factor-validation queue (EXPERT_VALIDATING_REPAIR_FACTORS / legacy WAITING_FOR_INSURER_APPROVAL + UNDER_REVIEW + EXPERT_COST_EVALUATION)
* - If an active workflow lock exists (30 min from lockedAt): only the locking expert; after expiry, any expert (tenant) may view
*/
async getClaimDetailV2(
claimRequestId: string,
actor: any,
): Promise<ClaimDetailV2ResponseDto> {
const actorId = actor.sub;
if (
actor.role !== RoleEnum.FIELD_EXPERT &&
actor.role !== RoleEnum.FILE_MAKER &&
actor.role !== RoleEnum.FILE_REVIEWER
) {
await this.reconcileStaleExpertReviewingClaimLocksForTenant(actor);
}
await this.expireClaimWorkflowLockV2IfStale(claimRequestId);
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) {
throw new NotFoundException("Claim request not found");
}
const linkedBlame = await this.loadBlameForClaim(claim);
// FILE_REVIEWER access is validated by the role-specific gate below
// (isAssignedToMe || isOpen). Skip the generic tenant-scope assert which
// would incorrectly reject them via the initiatedByFieldExpertId path.
if (actor.role !== RoleEnum.FILE_REVIEWER) {
assertClaimCaseForExpertActor(claim, actor, linkedBlame);
}
await this.assertActorBranchAccess(claim, actor, linkedBlame);
// Variables used both in the gate block and in the detail-build section below
const isDamageExpertPhase =
claim.status === ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT ||
claim.status === ClaimCaseStatus.EXPERT_REVIEWING;
const isFactorValidationPending =
claimIsAwaitingExpertFactorValidationV2(claim);
// FileMaker: can view any file they created (both during filing and approval phase).
// The list endpoint already filters to V5-only; detail access is scoped by ownership.
if (actor.role === RoleEnum.FILE_MAKER) {
const isOwn = claimCaseInitiatedByFieldExpert(claim, actor, linkedBlame);
if (!isOwn) {
throw new ForbiddenException(
"FileMakers can only view files they created.",
);
}
// Fall through to the detail build below
} else if (
// Field experts and FileReviewers can view IN_PERSON expert-initiated claims
// regardless of claim status (they work across multiple non-standard steps).
actor.role === RoleEnum.FIELD_EXPERT ||
actor.role === RoleEnum.FILE_REVIEWER
) {
if (actor.role === RoleEnum.FILE_REVIEWER) {
// FILE_REVIEWER: must be a V4/V5 file AND (they are the assigned reviewer OR
// the file is still open — WAITING_FOR_FILE_REVIEWER with no reviewer yet).
const isV4V5Blame =
(linkedBlame as any)?.isMadeByFileMaker &&
linkedBlame?.expertInitiated &&
linkedBlame?.creationMethod === "IN_PERSON";
if (!isV4V5Blame) {
throw new ForbiddenException(
"FileReviewers can only access V4/V5 FileMaker files.",
);
}
const clientKey = requireActorClientKey(actor);
if (!blameCaseTouchesClient(linkedBlame, clientKey)) {
throw new ForbiddenException(
"This file does not belong to your organization.",
);
}
const assignedReviewerId = (linkedBlame as any)?.assignedFileReviewerId
? String((linkedBlame as any).assignedFileReviewerId)
: null;
const isAssignedToMe =
assignedReviewerId && assignedReviewerId === actorId;
const isOpen =
!assignedReviewerId &&
String(linkedBlame?.status ?? "") === "WAITING_FOR_FILE_REVIEWER";
if (!isAssignedToMe && !isOpen) {
throw new ForbiddenException(
"This file has been taken by another reviewer.",
);
}
} else {
// FIELD_EXPERT: V3 flow only. Reject V4/V5 files (isMadeByFileMaker)
// even if their ID matches initiatedByFieldExpertId on the blame —
// those are FILE_MAKER files, accessible via the FILE_MAKER role only.
const isV4V5Blame = !!(linkedBlame as any)?.isMadeByFileMaker;
if (isV4V5Blame) {
throw new ForbiddenException(
"Field experts can only access V3 expert-initiated files.",
);
}
if (!claimCaseInitiatedByFieldExpert(claim, actor, linkedBlame)) {
throw new ForbiddenException("This claim is not accessible to you.");
}
}
// Fall through to the detail build below (skip the damage-expert gate)
} else if (actor.role !== RoleEnum.FILE_MAKER) {
const isResendPending =
claim.status === ClaimCaseStatus.WAITING_FOR_USER_RESEND;
const assignedForReviewById = String(
(claim.workflow as any)?.assignedForReviewBy?.actorId ?? "",
);
const lockEnforced = this.isClaimV2WorkflowLockCurrentlyEnforced(claim);
const lockedById = String(claim.workflow?.lockedBy?.actorId ?? "");
const isAssignedToMe =
!!assignedForReviewById && assignedForReviewById === actorId;
// Gate: must satisfy at least one bucket
if (
!isDamageExpertPhase &&
!isFactorValidationPending &&
!isResendPending &&
!isAssignedToMe
) {
throw new ForbiddenException(
`This claim is not available for expert review. Current status: ${claim.status}`,
);
}
const isAvailable =
isDamageExpertPhase && !assignedForReviewById && !lockEnforced;
const isLockedByMe = lockEnforced && lockedById === actorId;
const isFactorValidationOpen = isFactorValidationPending;
if (
!isAvailable &&
!isAssignedToMe &&
!isLockedByMe &&
!isFactorValidationOpen
) {
if (lockEnforced && lockedById && lockedById !== actorId) {
throw new ForbiddenException(
`This claim is locked by another expert: ${claim.workflow?.lockedBy?.actorName}`,
);
}
if (assignedForReviewById && assignedForReviewById !== actorId) {
throw new ForbiddenException(
"This claim has been assigned to another expert.",
);
}
throw new ForbiddenException(
"You do not have permission to view this claim.",
);
}
} // end damage-expert gate (else block)
// Build requiredDocuments map
const requiredDocs = claim.requiredDocuments as any;
const requiredDocumentsStatus: Record<string, any> = {};
// Resend documents requested by expert — normalize to canonical keys for comparison
const resendDocumentKeys = new Set(
normalizeResendDocumentKeys(
(claim as any).evaluation?.damageExpertResend?.resendDocuments,
),
);
const resendFulfilled = !!(claim as any).evaluation?.damageExpertResend
?.fulfilledAt;
if (requiredDocs) {
const keys =
requiredDocs instanceof Map
? Array.from(requiredDocs.keys())
: Object.keys(requiredDocs);
for (const k of keys as string[]) {
const doc =
requiredDocs instanceof Map ? requiredDocs.get(k) : requiredDocs[k];
const canonicalKey = canonicalizeResendDocumentKey(k) ?? k;
const wasResendRequested = resendDocumentKeys.has(canonicalKey);
requiredDocumentsStatus[k] = {
uploaded: !!doc?.uploaded,
fileId: doc?.fileId?.toString(),
fileName: doc?.fileName,
filePath: doc?.filePath ? buildFileLink(doc.filePath) : undefined,
resend: {
wasRequested: wasResendRequested,
isFulfilled: wasResendRequested && resendFulfilled,
},
};
}
}
// Build car angles map
const carAnglesData = claim.media?.carAngles as any;
const damagedPartsDataForAngles = claim.media?.damagedParts as any;
const carAngles: Record<string, { captured: boolean; url?: string }> = {};
for (const k of ["front", "back", "left", "right"]) {
const cap = getClaimCarAngleCaptureBlob(
carAnglesData,
damagedPartsDataForAngles,
k as ClaimCarAngleKey,
) as { url?: string; path?: string } | undefined;
carAngles[k] = {
captured: !!cap,
url: resolveStoredFileUrl(cap),
};
}
// Build enriched damaged parts
const carTypeExpert = claim.vehicle?.carType as
| ClaimVehicleTypeV2
| undefined;
const selectedNormExpert = normalizeDamageSelectedParts(
claim.damage?.selectedParts,
carTypeExpert,
(claim.damage as any)?.selectedOuterParts,
);
const damagedPartsDataExpert = claim.media?.damagedParts as any;
const damagedParts = buildEnrichedDamagedParts({
selectedParts: selectedNormExpert,
damagedPartsData: damagedPartsDataExpert,
evaluationBlock: (claim as any).evaluation,
expertAddedParts: (claim.damage as any)?.expertAddedParts ?? [],
getDamagedPartCaptureBlob,
hasDamagedPartCapture,
catalogLikeKeyFromPart,
buildFileLink,
resolveStoredFileUrl,
});
const damagedPartsHistory = serializeDamagedPartSelectionHistory({
history: (claim.damage as any)?.partSelectionHistory,
currentSelectedParts: selectedNormExpert,
});
let blameLean: any = null;
const videoCaptureIdRaw = (claim.media as any)?.videoCaptureId;
const blameRequestIdStr = claim.blameRequestId?.toString();
const [videoCaptureRow, blameCase, blameLeanRows] = await Promise.all([
videoCaptureIdRaw
? this.claimVideoCaptureDbService.findById(String(videoCaptureIdRaw))
: Promise.resolve(null),
blameRequestIdStr
? this.buildBlameCaseSnapshotForClaimDetail(blameRequestIdStr)
: Promise.resolve(null),
claim.blameRequestId
? this.blameRequestDbService.find(
{ _id: new Types.ObjectId(claim.blameRequestId.toString()) },
{
lean: true,
select:
"type parties expert.decision creationMethod expertInitiated registrarInitiated callCenterInitiated initiatedByFieldExpertId initiatedByRegistrarId initiatedByCallCenterId",
},
)
: Promise.resolve([]),
]);
if (Array.isArray(blameLeanRows) && blameLeanRows.length) {
blameLean = blameLeanRows[0] ?? null;
}
// Use the same damaged-party identity resolution as price estimation and list rows.
const resolvedVehicle = this.vehicleForExpertFromClaimAndBlameMap(
claim,
new Map(blameLean ? [[String(claim.blameRequestId), blameLean]] : []),
);
const vehiclePayload = {
...(typeof (claim.vehicle as any)?.toObject === "function"
? (claim.vehicle as any).toObject() : (claim.vehicle ?? {})),
...resolvedVehicle,
};
const blameFileContext = blameLean
? this.blameFileContextForExpert(blameLean)
: {};
const configuredPriceCap = getClaimV2TotalPaymentCapToman();
const priceCap =
configuredPriceCap !== null && claimPriceCapAppliesToBlame(linkedBlame)
? configuredPriceCap
: null;
let videoCapture: ClaimDetailV2ResponseDto["videoCapture"] = undefined;
if (videoCaptureRow) {
const vc = videoCaptureRow as any;
videoCapture = {
id: String(vc._id ?? videoCaptureIdRaw),
fileName: vc.fileName,
path: vc.path,
url: vc.path ? buildFileLink(vc.path) : undefined,
};
}
const blameExpertDecision = blameCase
? this.serializeBlameExpertDecisionForClaimDetail(
(blameCase.expert as Record<string, unknown> | undefined)?.decision,
)
: undefined;
const money = (
claim as { money?: { sheba?: string; nationalCodeOfInsurer?: string } }
).money;
const moneyPayload =
money && (money.sheba != null || money.nationalCodeOfInsurer != null)
? {
sheba: money.sheba,
nationalCodeOfInsurer: money.nationalCodeOfInsurer,
}
: undefined;
const statusForExpertApi =
claim.status === ClaimCaseStatus.EXPERT_REVIEWING
? ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT
: claim.status;
const blameCaseForApi = blameCase
? this.sanitizeBlameCaseForClaimDetailApi(
blameCase as Record<string, unknown>,
)
: undefined;
const claimEvaluationRaw = (claim as any).evaluation as
| Record<string, unknown>
| undefined;
const enrichedEvaluation =
await this.enrichClaimEvaluationForExpert(claimEvaluationRaw);
let evaluationForApi: Record<string, unknown> | undefined;
if (enrichedEvaluation) {
if (blameFileContext.blameRequestType === BlameRequestType.CAR_BODY) {
delete enrichedEvaluation.priceDrop;
}
evaluationForApi = {};
// damageExpertReply / damageExpertReplyFinal: include whenever present.
// Previously these were gated on isFactorValidationPending, which hid the
// expert assessment once the claim moved to user-side statuses such as
// INSURER_REVIEW_AWAITING_OWNER_SIGN. Historical assessment data should
// always be visible once submitted.
if (enrichedEvaluation.damageExpertReply !== undefined) {
evaluationForApi.damageExpertReply =
enrichedEvaluation.damageExpertReply;
}
if (enrichedEvaluation.damageExpertReplyFinal !== undefined) {
evaluationForApi.damageExpertReplyFinal =
enrichedEvaluation.damageExpertReplyFinal;
}
if (enrichedEvaluation.ownerInsurerApproval !== undefined) {
evaluationForApi.ownerInsurerApproval =
enrichedEvaluation.ownerInsurerApproval;
}
if (enrichedEvaluation.ownerPricedPartsApproval !== undefined) {
evaluationForApi.ownerPricedPartsApproval =
enrichedEvaluation.ownerPricedPartsApproval;
}
// priceDrop: include whenever present, not only during the expert phase.
if (enrichedEvaluation.priceDrop !== undefined) {
evaluationForApi.priceDrop = enrichedEvaluation.priceDrop;
}
// objection: include when present so experts can see the disputed parts and any attached invoices.
if (enrichedEvaluation.objection !== undefined) {
evaluationForApi.objection = enrichedEvaluation.objection;
}
if (Object.keys(evaluationForApi).length === 0) {
evaluationForApi = undefined;
}
}
return {
claimRequestId: claim._id.toString(),
publicId: claim.publicId,
status: statusForExpertApi,
claimStatus: claim.claimStatus || "PENDING",
currentStep: claim.workflow?.currentStep || "",
nextStep: claim.workflow?.nextStep,
locked: claim.workflow?.locked || false,
lockedBy: claim.workflow?.lockedBy
? {
actorId: claim.workflow.lockedBy.actorId?.toString(),
actorName: claim.workflow.lockedBy.actorName,
lockedAt: (claim.workflow as any).lockedAt?.toISOString(),
expiredAt: (claim.workflow as any).expiredAt?.toISOString(),
}
: undefined,
owner: claim.owner
? {
userId: claim.owner.userId?.toString(),
fullName: claim.owner.fullName,
}
: undefined,
vehicle: vehiclePayload
? this.sanitizeVehicleInquiryForApi(vehiclePayload)
: undefined,
vehiclePartyRole: resolveClaimVehicleSources(claim, blameLean).party?.role,
...blameFileContext,
priceCap,
blameRequestId: claim.blameRequestId?.toString(),
blameRequestNo: claim.blameRequestNo,
money: moneyPayload,
otherParts: claim.damage?.otherParts,
requiredDocuments:
Object.keys(requiredDocumentsStatus).length > 0
? requiredDocumentsStatus
: undefined,
carAngles,
damagedParts,
damagedPartsHistory,
awaitingFactorValidation: isFactorValidationPending,
requiresFileMakerApproval: !!(claim as any).requiresFileMakerApproval,
fileMakerRejectionCount: (claim as any).fileMakerRejectionCount ?? 0,
fileMakerRejectionReason:
(claim as any).fileMakerRejectionReason ?? undefined,
fileMakerApprovalActorId: (claim as any).fileMakerApprovalActorId
? String((claim as any).fileMakerApprovalActorId)
: undefined,
fanavaran: fanavaranClaimReferences(claim),
fanavaranVehicleReview: (claim as any).fanavaranVehicleReview,
evaluation:
(evaluationForApi as
| ClaimDetailV2ResponseDto["evaluation"]
| undefined) || (enrichedEvaluation as any),
videoCapture,
blameCase: blameCaseForApi,
blameExpertDecision,
createdAt: (claim as any).createdAt,
updatedAt: (claim as any).updatedAt,
};
}
async assertCanSignFanavaranClaim(id: string, actor: any) {
if (!Types.ObjectId.isValid(id)) throw new BadRequestException("شناسه پرونده معتبر نیست.");
const roles = [
RoleEnum.DAMAGE_EXPERT, RoleEnum.FIELD_EXPERT, RoleEnum.FILE_MAKER,
RoleEnum.FILE_REVIEWER, RoleEnum.REGISTRAR,
];
if (!actor?.sub || !roles.includes(actor.role)) {
throw new ForbiddenException("فقط کارشناس مجاز پرونده می‌تواند آن را امضا کند.");
}
await this.getClaimDetailV2(id, actor);
}
private asFanavaranLookupRows(value: unknown): Array<Record<string, any>> {
if (Array.isArray(value)) return value as Array<Record<string, any>>;
if (value && typeof value === "object") {
const data = (value as { data?: unknown }).data;
if (Array.isArray(data)) return data as Array<Record<string, any>>;
if (data && typeof data === "object") {
const nested = (data as { data?: unknown }).data;
if (Array.isArray(nested)) return nested as Array<Record<string, any>>;
}
}
return [];
}
private async tejaratNotifierAllowedIds(): Promise<
{ types: number[]; relations: number[] } | undefined
> {
if (resolveFanavaranClientKey() !== "tejaratno") return undefined;
const ids = (raw: unknown) =>
this.asFanavaranLookupRows(raw)
.map((row) => Number(row.Id))
.filter((id) => Number.isInteger(id) && id > 0);
try {
const [typesRaw, relationsRaw] = await Promise.all([
this.lookupsService.getClientRemoteLookup("notifier-type"),
this.lookupsService.getClientRemoteLookup("notifier-relation"),
]);
return { types: ids(typesRaw), relations: ids(relationsRaw) };
} catch {
return { types: [], relations: [] };
}
}
private activeFanavaranLookupRows(value: unknown) {
return this.asFanavaranLookupRows(value)
.filter((row) => row.IsActive !== 0 && Number(row.Id) > 0)
.sort((a, b) =>
String(a.Caption ?? "").localeCompare(String(b.Caption ?? ""), "fa"),
);
}
async getFanavaranVehicleOptionsV2(
claimRequestId: string,
actor: any,
vehicleGroupId?: number,
) {
await this.getClaimDetailV2(claimRequestId, actor);
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) throw new NotFoundException("Claim request not found");
const [groupsRaw, useTypesRaw, systemsRaw, blame] = await Promise.all([
this.lookupsService.getClientRemoteLookup("vehicle-groups"),
this.lookupsService.getClientRemoteLookup("vehicle-use-types"),
this.lookupsService.getClientRemoteLookup("vehicle-systems"),
claim.blameRequestId
? this.blameRequestDbService.findById(String(claim.blameRequestId))
: Promise.resolve(null),
]);
const groups = this.activeFanavaranLookupRows(groupsRaw);
const useTypes = this.activeFanavaranLookupRows(useTypesRaw);
const systems = this.activeFanavaranLookupRows(systemsRaw);
const suggestion = await buildFanavaranVehicleSuggestion({
records: collectFanavaranVehicleInquiryRecords(claim, blame),
groups,
useTypes,
systems,
getVehicleKindById: (id) =>
this.lookupsService.getActiveVehicleKindById(id),
searchVehicleKinds: (input) =>
this.lookupsService.searchVehicleKindsList(input),
});
const groupId =
vehicleGroupId != null &&
Number.isInteger(vehicleGroupId) &&
vehicleGroupId > 0
? vehicleGroupId
: null;
const filterByGroup = (rows: Array<Record<string, any>>) =>
groupId == null
? []
: rows.filter((row) => Number(row.VehicleGroupId) === groupId);
return {
vehicleGroups: groups,
vehicleUseTypes: filterByGroup(useTypes),
vehicleSystems: filterByGroup(systems),
suggestion,
};
}
async approveFanavaranVehicleReviewV2(
claimRequestId: string,
body: ApproveFanavaranVehicleReviewDto,
actor: any,
) {
await this.getClaimDetailV2(claimRequestId, actor);
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) throw new NotFoundException("Claim request not found");
const baseSent = claim.claimId != null || claim.claimNo != null;
// Recover cases created before base submission required vehicle approval.
// Never change an approved snapshot or classification already sent downstream.
if (baseSent && ((claim as any).fanavaranVehicleReview?.approved === true ||
claim.dmgCaseId != null || claim.expertiseId != null)) {
throw new ConflictException(
"مشخصات تأییدشده خودرو پس از ارسال به فناوران قابل تغییر نیست.",
);
}
const fields =
body.stageFields !== undefined
? await this.prepareFanavaranStageFieldReview(
claim,
{
values: body.stageFields,
expectedVersion: body.stageFieldsVersion,
confirmed: body.confirmed,
},
actor,
)
: undefined;
if (
!hasReviewedTejaratNotifier(
fields?.review.values ?? claim.fanavaranFieldReview?.values,
resolveFanavaranClientKey(),
await this.tejaratNotifierAllowedIds(),
)
) {
throw new BadRequestException(
"نوع و نسبت اعلام‌کننده را پیش از تایید و ارسال پرونده انتخاب کنید.",
);
}
const [groupsRaw, useTypesRaw, systemsRaw, vehicleKind] = await Promise.all(
[
this.lookupsService.getClientRemoteLookup("vehicle-groups"),
this.lookupsService.getClientRemoteLookup("vehicle-use-types"),
this.lookupsService.getClientRemoteLookup("vehicle-systems"),
this.lookupsService.getActiveVehicleKindById(body.vehicleKindId),
],
);
const group = this.activeFanavaranLookupRows(groupsRaw).find(
(row) => Number(row.Id) === body.vehicleGroupId,
);
const useType = this.activeFanavaranLookupRows(useTypesRaw).find(
(row) => Number(row.Id) === body.vehicleUseTypeId,
);
const system = this.activeFanavaranLookupRows(systemsRaw).find(
(row) => Number(row.Id) === body.vehicleSystemId,
);
if (!group || !useType || !system || !vehicleKind) {
throw new BadRequestException(
"One or more selected Fanavaran vehicle values are inactive or invalid.",
);
}
if (
Number(useType.VehicleGroupId) !== body.vehicleGroupId ||
Number(system.VehicleGroupId) !== body.vehicleGroupId ||
Number(vehicleKind.VehicleGroupId) !== body.vehicleGroupId ||
Number(vehicleKind.VehicleSystemId) !== body.vehicleSystemId
) {
throw new BadRequestException(
"The selected vehicle group, use type, system, and kind are not compatible.",
);
}
const value = (row: Record<string, any>) => ({
id: Number(row.Id),
caption: String(row.Caption ?? ""),
...(row.Name != null ? { name: String(row.Name) } : {}),
...(row.VehicleGroupId != null
? { vehicleGroupId: Number(row.VehicleGroupId) }
: {}),
...(row.VehicleSystemId != null
? { vehicleSystemId: Number(row.VehicleSystemId) }
: {}),
...(row.VehicleSystemCaption != null
? { vehicleSystemCaption: String(row.VehicleSystemCaption) }
: {}),
});
const review = {
vehicleGroup: value(group),
vehicleUseType: value(useType),
vehicleSystem: value(system),
vehicleKind: value(vehicleKind as unknown as Record<string, any>),
approved: true,
approvedAt: new Date(),
approvedByActorId: new Types.ObjectId(String(actor.sub)),
approvedByActorName: actor.fullName,
approvedByRole: String(actor.role),
version: Number((claim as any).fanavaranVehicleReview?.version ?? 0) + 1,
};
const updated = await this.claimCaseDbService.findOneAndUpdate(
{
_id: claimRequestId,
claimId: claim.claimId ?? null,
claimNo: claim.claimNo ?? null,
dmgCaseId: claim.dmgCaseId ?? null,
expertiseId: claim.expertiseId ?? null,
fanavaranVehicleReview: (claim as any).fanavaranVehicleReview ?? null,
...(fields?.filter ?? {}),
},
{
$set: {
fanavaranVehicleReview: review,
...(fields ? { fanavaranFieldReview: fields.review } : {}),
},
$push: {
history: {
$each: [
{
type: "FANAVARAN_VEHICLE_REVIEW_APPROVED",
actor: {
actorId: new Types.ObjectId(String(actor.sub)),
actorName: actor.fullName,
actorType: actor.role,
},
timestamp: review.approvedAt,
metadata: {
version: review.version,
vehicleGroupId: body.vehicleGroupId,
vehicleUseTypeId: body.vehicleUseTypeId,
vehicleSystemId: body.vehicleSystemId,
vehicleKindId: body.vehicleKindId,
},
},
...(fields ? [fields.history] : []),
],
},
},
},
);
if (!updated)
throw new ConflictException(
"The case changed during review. Refresh before saving.",
);
const baseClaim =
await this.claimRequestManagementService.autoSubmitToFanavaranV2OnClaimCreated(
claimRequestId,
);
const selectedParts = updated?.damage?.selectedParts ?? [];
const damageCase = selectedParts.length
? await this.claimRequestManagementService.autoSubmitFanavaranDamageCaseOnOuterPartsSelected(
claimRequestId,
selectedParts,
)
: undefined;
return {
review: (updated as any)?.fanavaranVehicleReview ?? review,
fanavaranSync: { baseClaim, damageCase },
};
}
async getFanavaranStageFieldsV2(claimRequestId: string, actor: any) {
await this.getClaimDetailV2(claimRequestId, actor);
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) throw new NotFoundException("Claim request not found");
const blame = await this.loadBlameForClaim(claim);
return this.claimRequestManagementService.getFanavaranStageFieldsContext(
claim,
blame,
);
}
private async prepareFanavaranStageFieldReview(
claim: any,
body: UpdateFanavaranStageFieldsDto,
actor: any,
) {
if (
body.confirmed !== true ||
!body.values ||
typeof body.values !== "object" ||
Array.isArray(body.values)
) {
throw new BadRequestException(
"Explicit confirmation and field values are required.",
);
}
const version = claim.fanavaranFieldReview?.version ?? 0;
if (
!Number.isSafeInteger(body.expectedVersion) ||
body.expectedVersion !== version
) {
throw new ConflictException(
"The Fanavaran fields changed. Refresh before saving.",
);
}
const context =
await this.claimRequestManagementService.getFanavaranStageFieldsContext(
claim,
await this.loadBlameForClaim(claim),
);
const values: FanavaranFieldValues = {};
const captions: FanavaranFieldReview["captions"] = {};
const stages = new Set<string>();
const before: FanavaranFieldValues = {};
for (const [key, raw] of Object.entries(body.values)) {
const field = context.fields.find((field) => field.key === key);
if (!field)
throw new BadRequestException(
`Field ${key} does not apply to this case type.`,
);
if (fanavaranFieldStageSent(claim, field.stage)) {
throw new ConflictException(
`Field ${key} has already been sent to Fanavaran and cannot be changed.`,
);
}
let value: string | number = raw;
if (field.type === "text") {
if (
typeof raw !== "string" ||
!raw.trim() ||
raw.trim().length > 1000
) {
throw new BadRequestException(
`${key} must be a non-empty address of at most 1000 characters.`,
);
}
value = raw.trim();
} else {
if (
typeof raw !== "number" ||
!Number.isSafeInteger(raw) ||
raw < (field.min ?? 1) ||
(field.max != null && raw > field.max)
) {
throw new BadRequestException(
`Field ${key} is out of range or invalid.`,
);
}
if (field.type === "lookup") {
const row = field.options?.find((row) => row.Id === raw);
if (!row)
throw new BadRequestException(
`Field ${key} must use an active Fanavaran lookup value. Reload the options and try again.`,
);
captions[field.key] = row.Caption;
}
}
values[field.key] = value;
before[field.key] = field.value;
stages.add(field.stage);
}
if (!Object.keys(values).length)
throw new BadRequestException("No Fanavaran fields were supplied.");
const review: FanavaranFieldReview = {
values: { ...claim.fanavaranFieldReview?.values, ...values },
captions: { ...claim.fanavaranFieldReview?.captions, ...captions },
version: version + 1,
reviewedAt: new Date(),
reviewedByActorId: String(actor.sub),
reviewedByActorName: actor.fullName,
reviewedByRole: String(actor.role),
};
const conditions: Record<string, unknown>[] = [
version === 0
? {
$or: [
{ "fanavaranFieldReview.version": { $exists: false } },
{ "fanavaranFieldReview.version": 0 },
],
}
: { "fanavaranFieldReview.version": version },
];
for (const stage of stages) {
const id = {
baseClaim: "claimId",
damageCase: "dmgCaseId",
expertise: "expertiseId",
}[stage];
conditions.push({
[id]: null,
[`fanavaranSync.${stage}.${id}`]: null,
[`fanavaranSync.${stage}.status`]: { $ne: "success" },
});
if (stage === "baseClaim") conditions.push({ claimNo: null });
}
return {
review,
filter: { $and: conditions },
history: {
type: "FANAVARAN_FIELDS_REVIEWED",
actor: {
actorId: new Types.ObjectId(String(actor.sub)),
actorName: actor.fullName,
actorType: actor.role,
},
timestamp: review.reviewedAt,
metadata: { version: review.version, before, after: values, captions },
},
};
}
async updateFanavaranStageFieldsV2(
claimRequestId: string,
body: UpdateFanavaranStageFieldsDto,
actor: any,
) {
await this.getClaimDetailV2(claimRequestId, actor);
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) throw new NotFoundException("Claim request not found");
const fields = await this.prepareFanavaranStageFieldReview(
claim,
body,
actor,
);
const updated = await this.claimCaseDbService.findOneAndUpdate(
{ _id: claimRequestId, ...fields.filter },
{
$set: { fanavaranFieldReview: fields.review },
$push: { history: fields.history },
},
);
if (!updated)
throw new ConflictException(
"The case changed or its stage was sent. Refresh before saving.",
);
return { version: fields.review.version };
}
private assertPriceDropProduct(type: unknown) {
if (type === BlameRequestType.CAR_BODY) {
throw new BadRequestException("افت قیمت برای پرونده بیمه بدنه قابل ثبت نیست.");
}
}
/** V2 price-drop: claim locked by this expert during damage assessment. */
private async assertExpertCanEditClaimDuringReviewV2(
claim: any,
actor: any,
): Promise<void> {
if (actor.role !== RoleEnum.FIELD_EXPERT) requireActorClientKey(actor);
await this.assertExpertActorOnClaim(claim, actor);
if (claim.status !== ClaimCaseStatus.EXPERT_REVIEWING) {
throw new BadRequestException(
`Claim must be EXPERT_REVIEWING to edit price drop. Current status: ${claim.status}`,
);
}
if (!claim.workflow?.locked) {
throw new ForbiddenException(
"You must lock the claim before entering price-drop data",
);
}
if (claim.workflow.lockedBy?.actorId?.toString() !== String(actor.sub)) {
throw new ForbiddenException("This claim is locked by another expert");
}
}
/**
* V2: Context for manual price-drop (vehicle, inquiry year, catalog, damaged parts).
*/
async getPriceDropContextV2(claimRequestId: string, actor: any) {
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) {
throw new NotFoundException("Claim request not found");
}
await this.assertExpertCanEditClaimDuringReviewV2(claim, actor);
const carType = claim.vehicle?.carType as ClaimVehicleTypeV2 | undefined;
const selectedNorm = normalizePriceDropSelectedParts(
claim.damage?.selectedParts,
carType,
(claim.damage as any)?.selectedOuterParts,
);
let suggestedCarModelYear: number | null = null;
let accidentYear: number | null = null;
let calculationUnavailableReason: string | null = null;
if (claim.blameRequestId) {
const blameRows = await this.blameRequestDbService.find(
{ _id: new Types.ObjectId(claim.blameRequestId.toString()) },
{
lean: true,
select: "type expert.decision.guiltyPartyId parties.role parties.person.userId parties.vehicle parties.statement.accidentDate",
},
);
const blame = blameRows[0] as Record<string, unknown> | undefined;
this.assertPriceDropProduct(blame?.type);
suggestedCarModelYear = resolveVehicleModelYearFromBlame(
claim,
blame as Parameters<typeof resolveVehicleModelYearFromBlame>[1],
);
accidentYear = resolvePriceDropAccidentYear(blame);
const accidentDate = resolvePriceDropAccidentDate(blame);
if (accidentDate && accidentDate < FANAVARAN_PRICE_DROP_AGE_EFFECTIVE_FROM) {
calculationUnavailableReason = "جدول سن ارسالی فناوران از ۱۴۰۴/۰۵/۲۸ معتبر است. برای حادثه پیش از این تاریخ مبلغ افت قیمت را دستی ثبت کنید.";
}
}
const existing = (claim as any).evaluation?.priceDrop;
const knownAges = [existing?.vehicleAge, suggestedCarModelYear != null && accidentYear != null ? accidentYear - suggestedCarModelYear : null]
.filter(age => Number.isInteger(age) && age >= 0);
const vehicleAge = knownAges.some(age => age > 10) ? Math.max(...knownAges) : existing?.vehicleAge ?? knownAges[0] ?? null;
return {
claimRequestId: String(claim._id),
vehicle: {
carName: claim.vehicle?.carName,
carModel: claim.vehicle?.carModel,
carType: claim.vehicle?.carType,
},
suggestedCarModelYear,
accidentYear,
suggestedVehicleAge: vehicleAge,
inquiryVehicleAge: suggestedCarModelYear != null && accidentYear != null ? accidentYear - suggestedCarModelYear : null,
depreciationEligible: vehicleAge == null ? null : vehicleAge <= 10,
ineligibilityReason: vehicleAge != null && vehicleAge > 10 ? PRICE_DROP_AGE_INELIGIBLE_MESSAGE : null,
calculationVersion: FANAVARAN_PRICE_DROP_VERSION,
ageTableEffectiveFrom: FANAVARAN_PRICE_DROP_AGE_EFFECTIVE_FROM,
calculationUnavailableReason,
ageCatalog: FANAVARAN_PRICE_DROP_AGES.map(row => ({
vehicleAge: row.age, fanavaranAgeId: row.id, coefficient: row.coefficient,
})),
priceDrop: existing ?? null,
severityOptions: PRICE_DROP_SEVERITY_OPTIONS,
priceDropCatalog: buildPriceDropCatalogForApi(),
damagedParts: buildDamagedPartsPriceDropLines(selectedNorm),
};
}
/**
* V2: Expert enters vehicle + per-part severities; persists `vehicle` and `evaluation.priceDrop`.
*/
async upsertPriceDropV2(
claimRequestId: string,
body: UpsertClaimPriceDropV2Dto,
actor: any,
) {
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) {
throw new NotFoundException("Claim request not found");
}
await this.assertExpertCanEditClaimDuringReviewV2(claim, actor);
const vehicleSet: Record<string, string> = {};
if (body.carName != null && String(body.carName).trim()) {
vehicleSet["vehicle.carName"] = String(body.carName).trim();
}
if (body.carModel != null && String(body.carModel).trim()) {
vehicleSet["vehicle.carModel"] = String(body.carModel).trim();
}
let carModelYear = body.carModelYear;
if (carModelYear != null && (!Number.isInteger(carModelYear) || carModelYear < 1300 || carModelYear >= 1500)) {
throw new BadRequestException("سال ساخت باید یک سال شمسی معتبر باشد؛ برای سال میلادی، سن خودرو در زمان حادثه را وارد کنید.");
}
let accidentYear: number | null = null;
let blame: any = null;
let accidentDate: string | null = null;
if (claim.blameRequestId) {
const blameRows = await this.blameRequestDbService.find(
{ _id: new Types.ObjectId(claim.blameRequestId.toString()) },
{
lean: true,
select: "type expert.decision.guiltyPartyId parties.role parties.person.userId parties.vehicle parties.statement.accidentDate",
},
);
this.assertPriceDropProduct(blameRows[0]?.type);
carModelYear ??=
resolveVehicleModelYearFromBlame(
claim,
blameRows[0] as Parameters<
typeof resolveVehicleModelYearFromBlame
>[1],
) ?? undefined;
blame = blameRows[0];
accidentYear = resolvePriceDropAccidentYear(blame);
accidentDate = resolvePriceDropAccidentDate(blame);
}
if (body.vehicleAge != null && (!Number.isInteger(body.vehicleAge) || body.vehicleAge < 0)) {
throw new BadRequestException("سن خودرو در زمان حادثه باید عددی صحیح و نامنفی باشد.");
}
const enteredAge = body.vehicleAge ?? (carModelYear != null && accidentYear != null ? accidentYear - carModelYear : undefined);
const vehicleAge = resolveClaimPriceDropAge(claim, blame, enteredAge);
if (vehicleAge != null && vehicleAge > 10) {
if (body.manualPriceDrop != null && body.manualPriceDrop !== 0) {
throw new BadRequestException(PRICE_DROP_AGE_INELIGIBLE_MESSAGE);
}
const priceDrop = {
...buildAgeIneligiblePriceDrop(vehicleAge, body.carPrice ?? (claim as any).evaluation?.priceDrop?.carPrice),
manualOverride: false,
partLines: [],
...(accidentYear != null ? { accidentYear } : {}),
...(carModelYear != null ? { carModel: carModelYear } : {}),
};
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: { ...vehicleSet, "evaluation.priceDrop": priceDrop },
});
return { claimRequestId, vehicle: claim.vehicle, priceDrop, partLines: [] };
}
// Manual override path — expert knows the number, skip calculation entirely
if (body.manualPriceDrop != null) {
if (!Number.isSafeInteger(body.manualPriceDrop) || body.manualPriceDrop < 0) {
throw new BadRequestException(
"مبلغ افت قیمت باید عددی صحیح و نامنفی به ریال باشد.",
);
}
if (body.manualPriceDrop > 0 && vehicleAge == null) {
throw new BadRequestException("برای ثبت افت قیمت، سن خودرو در زمان حادثه را مشخص کنید.");
}
const manualPayload = {
...(vehicleAge != null ? { vehicleAge, eligible: true } : {}),
manualOverride: true,
total: parsePriceDropNumber(body.manualPriceDrop),
carPrice: body.carPrice != null ? parsePriceDropNumber(body.carPrice)
: (claim as any).evaluation?.priceDrop?.carPrice,
partLines: [],
};
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: {
...vehicleSet,
"evaluation.priceDrop": manualPayload,
},
});
const updated = await this.claimCaseDbService.findById(claimRequestId);
return {
claimRequestId,
vehicle: {
carName: updated?.vehicle?.carName,
carModel: updated?.vehicle?.carModel,
carType: updated?.vehicle?.carType,
},
priceDrop: manualPayload,
partLines: [],
};
}
if (accidentDate && accidentDate < FANAVARAN_PRICE_DROP_AGE_EFFECTIVE_FROM) {
throw new BadRequestException("جدول سن ارسالی فناوران از ۱۴۰۴/۰۵/۲۸ معتبر است. برای حادثه پیش از این تاریخ مبلغ افت قیمت را دستی ثبت کنید.");
}
// An explicit part list is required when replacing a manual correction.
const existingPriceDrop = (claim as any).evaluation?.priceDrop;
if (
existingPriceDrop?.manualOverride === true &&
!body.partSeverities?.length
) {
throw new BadRequestException(
"This claim has a manual price-drop correction. " +
"To recalculate, provide partSeverities explicitly — this will replace the manual correction.",
);
}
const carType = claim.vehicle?.carType as ClaimVehicleTypeV2 | undefined;
const selectedNorm = normalizePriceDropSelectedParts(
claim.damage?.selectedParts,
carType,
(claim.damage as any)?.selectedOuterParts,
);
if (!Array.isArray(body.partSeverities) || !body.partSeverities.length) {
throw new BadRequestException(
"شدت آسیب حداقل یک قطعه را انتخاب کنید یا مبلغ نهایی افت قیمت را دستی ثبت کنید.",
);
}
if (body.partSeverities.some(p => !p || typeof p !== "object")) {
throw new BadRequestException("فهرست قطعات افت قیمت معتبر نیست. گروه قطعات و شدت آسیب را دوباره انتخاب کنید.");
}
if (body.vehicleAge == null && (carModelYear == null || accidentYear == null)) {
throw new BadRequestException(
"سن خودرو در زمان حادثه را وارد کنید؛ سال ساخت یا تاریخ حادثه برای محاسبه سن در دسترس نیست.",
);
}
const { coefficients, lines, errors } = buildCoefficientsFromPartSeverities(
selectedNorm,
body.partSeverities.map((p) => ({
partId: p.partId,
severity: p.severity,
fanavaranPartId: p.fanavaranPartId,
})),
carType,
);
if (errors.length > 0) {
throw new BadRequestException(errors.join(" "));
}
if (coefficients.length === 0) {
throw new BadRequestException(
"No valid severity coefficients could be derived from partSeverities.",
);
}
const calculated = body.vehicleAge != null
? {
...calculatePriceDropForVehicleAge(body.carPrice, body.vehicleAge, coefficients),
...(carModelYear != null ? { carModel: carModelYear } : {}),
...(accidentYear != null ? { accidentYear } : {}),
}
: calculateClaimPriceDrop(body.carPrice, carModelYear!, coefficients, accidentYear!);
const priceDropPayload = {
...calculated,
manualOverride: false,
partLines: lines,
};
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: {
...vehicleSet,
"evaluation.priceDrop": priceDropPayload,
},
});
const updated = await this.claimCaseDbService.findById(claimRequestId);
return {
claimRequestId,
vehicle: {
carName: updated?.vehicle?.carName,
carModel: updated?.vehicle?.carModel,
carType: updated?.vehicle?.carType,
},
priceDrop: priceDropPayload,
partLines: lines,
};
}
/**
* V2: Damage expert can modify selected damaged parts before final submit.
* Allowed only when claim is EXPERT_REVIEWING and locked by this expert.
*/
async updateClaimDamagedPartsV2(
claimRequestId: string,
body: UpdateClaimDamagedPartsV2Dto,
actor: any,
) {
if (actor.role !== RoleEnum.FIELD_EXPERT) requireActorClientKey(actor);
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) {
throw new NotFoundException("Claim request not found");
}
await this.assertExpertActorOnClaim(claim, actor);
if (claim.status !== ClaimCaseStatus.EXPERT_REVIEWING) {
throw new BadRequestException(
`Claim is not in EXPERT_REVIEWING state. Current status: ${claim.status}`,
);
}
if (!claim.workflow?.locked) {
throw new ForbiddenException(
"You must lock the claim before modifying damaged parts",
);
}
if (claim.workflow.lockedBy?.actorId?.toString() !== actor.sub) {
throw new ForbiddenException("This claim is locked by another expert");
}
const damagedPartsEditSnapshot = await this.snapshotDamageExpert(actor.sub);
const carType = claim.vehicle?.carType as ClaimVehicleTypeV2 | undefined;
const previousNorm = normalizeDamageSelectedParts(
(claim as any).damage?.selectedParts,
carType,
(claim as any).damage?.selectedOuterParts,
);
const prevMedia = coerceDamagedPartsMediaToArray(
(claim as any).media?.damagedParts,
previousNorm,
);
const nextNormRaw = body.selectedParts.map((p) =>
sanitizeDamageSelectedPartV2(
{
id: p.id ?? null,
name: String(p.name || "").trim(),
side: String(p.side || ""),
label_fa:
String(p.label_fa || "").trim() || String(p.name || "").trim(),
...(p.catalogKey?.trim() ? { catalogKey: p.catalogKey.trim() } : {}),
},
carType,
),
);
// Drop ghost entries: internal parts with neither a catalog id nor a name
// (these are frontend artifacts from uninitialised form rows).
const nextNorm = nextNormRaw.filter((p) => {
if (p.id != null) return true;
return String(p.name ?? "").trim().length > 0;
});
if (nextNorm.length === 0) {
throw new BadRequestException(
"selectedParts must contain at least one identifiable part. " +
"Each entry must have a numeric catalog id or a non-empty name.",
);
}
const matchPreviousIndex = (
next: (typeof nextNorm)[0],
previous: typeof previousNorm,
): number => {
if (next.id != null) {
const byId = previous.findIndex((x) => x.id === next.id);
if (byId >= 0) return byId;
}
if (next.catalogKey) {
const byCk = previous.findIndex(
(x) => x.catalogKey === next.catalogKey,
);
if (byCk >= 0) return byCk;
}
return previous.findIndex(
(x) => x.name === next.name && x.side === next.side,
);
};
const nextMedia = nextNorm.map((sp) => {
const j = matchPreviousIndex(sp, previousNorm);
const row =
j >= 0 && prevMedia[j] && typeof prevMedia[j] === "object"
? (prevMedia[j] as Record<string, unknown>)
: {};
return {
...(sp.id != null ? { id: sp.id } : {}),
name: sp.name,
side: sp.side,
label_fa: sp.label_fa,
...(sp.catalogKey ? { catalogKey: sp.catalogKey } : {}),
...(row.path ? { path: row.path } : {}),
...(row.fileName ? { fileName: row.fileName } : {}),
...(row.url ? { url: row.url } : {}),
...(row.capturedAt ? { capturedAt: row.capturedAt } : {}),
};
});
const previous = Array.isArray((claim as any).damage?.selectedParts)
? [...(claim as any).damage.selectedParts]
: [];
// Diff to find parts the expert is adding that weren't in the original selection
const previousPartIds = new Set(
previousNorm.map((p) => p.id ?? `${p.name}::${p.side}`),
);
const expertAddedNow = nextNorm.filter(
(p) => !previousPartIds.has(p.id ?? `${p.name}::${p.side}`),
);
// Merge with parts the expert added in any previous edits on this claim (idempotent)
const existingExpertAdded: any[] =
(claim.damage as any)?.expertAddedParts ?? [];
const existingExpertAddedIds = new Set(
existingExpertAdded.map((p: any) => p.id ?? `${p.name}::${p.side}`),
);
const expertAddedToAppend = expertAddedNow.filter(
(p) => !existingExpertAddedIds.has(p.id ?? `${p.name}::${p.side}`),
);
const mergedExpertAdded = [...existingExpertAdded, ...expertAddedToAppend];
const changedAt = new Date();
const partSelectionRevision = buildDamagedPartSelectionRevision({
revisionId: new Types.ObjectId().toString(),
changedAt,
changedBy: {
actorId: actor.sub,
actorName: actor.fullName,
actorType: "damage_expert",
},
expertProfileSnapshot: damagedPartsEditSnapshot,
previousParts: previousNorm,
selectedParts: nextNorm,
previousMedia: prevMedia,
});
const $set: Record<string, unknown> = {
"damage.selectedParts": nextNorm,
"media.damagedParts": nextMedia,
"damage.expertAddedParts": mergedExpertAdded,
};
const push: Record<string, unknown> = {
history: {
type: "EXPERT_DAMAGED_PARTS_UPDATED",
actor: {
actorId: new Types.ObjectId(actor.sub),
actorName: actor.fullName,
actorType: "damage_expert",
},
timestamp: changedAt,
metadata: {
previousSelectedParts: previous,
selectedParts: nextNorm,
expertAddedParts: mergedExpertAdded,
...(partSelectionRevision && {
partSelectionRevisionId: partSelectionRevision.revisionId,
removedParts: partSelectionRevision.removedParts,
addedParts: partSelectionRevision.addedParts,
}),
...(damagedPartsEditSnapshot && {
expertProfileSnapshot: damagedPartsEditSnapshot,
}),
},
},
};
if (partSelectionRevision) {
push["damage.partSelectionHistory"] = partSelectionRevision;
}
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set,
$push: push,
});
return {
claimRequestId: claim._id.toString(),
selectedParts: nextNorm,
previousSelectedParts: previous,
expertAddedParts: mergedExpertAdded,
partSelectionRevision,
message: "Damaged parts updated successfully.",
};
}
}