feat(claims): add insurer review referrals

This commit is contained in:
SepehrYahyaee
2026-11-24 15:16:14 +03:30
parent f29461fa67
commit 4e0e6f83dc
29 changed files with 1581 additions and 37 deletions
+10
View File
@@ -39,6 +39,16 @@ Schedules use Tehran time and allow one opening window per weekday. Omitted days
Case creation and updates use the liable insurer's hours once it is identified. At intake, staff use their own insurer's hours. For public intake before the case insurer is known, set the API's existing `CLIENT_ID` to the deployment insurer's numeric client code. If an intake has no known insurer and the deployment has no configured insurer, the schedule applies once the insurer is identified. Case reads, login and schedule settings are available outside those hours. Blocked case updates return HTTP 403 with `OUTSIDE_WORKING_HOURS` and the next opening. Case creation and updates use the liable insurer's hours once it is identified. At intake, staff use their own insurer's hours. For public intake before the case insurer is known, set the API's existing `CLIENT_ID` to the deployment insurer's numeric client code. If an intake has no known insurer and the deployment has no configured insurer, the schedule applies once the insurer is identified. Case reads, login and schedule settings are available outside those hours. Blocked case updates return HTTP 403 with `OUTSIDE_WORKING_HOURS` and the next opening.
## Refer a case for damage assessment
In the insurer case details, use **ارجاع پرونده** to choose an active expert in an active branch of the same company. The destination role follows the original workflow: damage expert for V1/V6, field expert for V2/V3, and file reviewer for V4/V5.
Referral becomes available once intake and evidence capture are complete and the claim is ready for damage assessment or factor validation. V4/V5 files still in the FileMaker or capture steps stay in those workflows. Any successful Fanavaran stage, including automatic base-claim registration, closes referral eligibility.
The referral updates the claim's review branch and clears the previous review lock. The new expert opens the case from the expert review list. The intake owner and branch remain in the linked blame case, and V5 approval stays with the original FileMaker. The case timeline records the insurer account and the previous and new experts and branches.
The insurer routes are `GET /expert-insurer/files/:publicId/review-referral` for eligible experts and the current revision, and `PATCH /expert-insurer/files/:publicId/review-referral` with `expertId` and `revision`. A concurrent write or submission can require refreshing the referral options.
## Fields ## Fields
`role` is one of `expert`, `damage_expert`, `field_expert`, `file_maker`, `file_reviewer`, or `call_center`, and is selected only during creation. These use the existing collections and actor login mechanism. `role` is one of `expert`, `damage_expert`, `field_expert`, `file_maker`, `file_reviewer`, or `call_center`, and is selected only during creation. These use the existing collections and actor login mechanism.
+1
View File
@@ -41,6 +41,7 @@ describe("AI analysis file access", () => {
service as any, service as any,
{} as any, {} as any,
ai as any, ai as any,
{} as any,
db as any, db as any,
); );
await expect(controller[method](actor, "other-tenant")).rejects.toThrow( await expect(controller[method](actor, "other-tenant")).rejects.toThrow(
+2
View File
@@ -1,3 +1,4 @@
import { ClaimReviewInterceptor } from "./expert-claim/review-referral/claim-review.interceptor";
import { CaseWorkingHoursInterceptor } from "./client/working-hours/case-working-hours.interceptor"; import { CaseWorkingHoursInterceptor } from "./client/working-hours/case-working-hours.interceptor";
import { EvidenceAccessModule } from "./evidence-access/evidence-access.module"; import { EvidenceAccessModule } from "./evidence-access/evidence-access.module";
import { PersianErrorFilter } from "./common/errors/persian-error.filter"; import { PersianErrorFilter } from "./common/errors/persian-error.filter";
@@ -70,6 +71,7 @@ import { createHttpModuleOptions } from "./core/config/http-proxy.factory";
{ provide: APP_FILTER, useClass: PersianErrorFilter }, { provide: APP_FILTER, useClass: PersianErrorFilter },
{ provide: APP_INTERCEPTOR, useClass: PersianErrorInterceptor }, { provide: APP_INTERCEPTOR, useClass: PersianErrorInterceptor },
{ provide: APP_INTERCEPTOR, useClass: CaseWorkingHoursInterceptor }, { provide: APP_INTERCEPTOR, useClass: CaseWorkingHoursInterceptor },
{ provide: APP_INTERCEPTOR, useClass: ClaimReviewInterceptor },
{ {
provide: APP_INTERCEPTOR, provide: APP_INTERCEPTOR,
useClass: UnicodeDigitsNormalizeInterceptor, useClass: UnicodeDigitsNormalizeInterceptor,
@@ -1,3 +1,4 @@
import { REVIEW_REFERRAL_DENIED } from 'src/expert-claim/review-referral/review-referral';
import { import {
assertFanavaranExpertSignature, assertFanavaranExpertSignature,
fanavaranSignatureRevision, fanavaranSignatureRevision,
@@ -395,6 +396,7 @@ const FANAVARAN_ATTACHMENT_FORMAT_WAIVE_PREFIX =
'FANAVARAN_ATTACHMENT_FORMAT_WAIVED:'; 'FANAVARAN_ATTACHMENT_FORMAT_WAIVED:';
interface FanavaranClaimExpertContext { interface FanavaranClaimExpertContext {
reviewReferral?: { assigneeId?: unknown };
initiatedByFieldExpertId?: unknown; initiatedByFieldExpertId?: unknown;
evaluation?: object; evaluation?: object;
workflow?: { assignedForReviewBy?: { actorId?: unknown } }; workflow?: { assignedForReviewBy?: { actorId?: unknown } };
@@ -3623,7 +3625,7 @@ export class ClaimRequestManagementService {
return this.fanavaranLocationService.resolveBusinessLocation({ return this.fanavaranLocationService.resolveBusinessLocation({
clientKey, clientKey,
requireStaffLocation: true, requireStaffLocation: true,
staffCandidateIds: [ staffCandidateIds: (claimCase.reviewReferral ? [claimCase.reviewReferral.assigneeId] : [
claimCase.initiatedByFieldExpertId, claimCase.initiatedByFieldExpertId,
blame?.initiatedByFieldExpertId, blame?.initiatedByFieldExpertId,
this.fanavaranDamageReplyActorId(claimCase), this.fanavaranDamageReplyActorId(claimCase),
@@ -3631,7 +3633,7 @@ export class ClaimRequestManagementService {
blame?.assignedFileReviewerId, blame?.assignedFileReviewerId,
blame?.expert?.assignedExpertId, blame?.expert?.assignedExpertId,
blame?.expert?.decision?.decidedByExpertId, blame?.expert?.decision?.decidedByExpertId,
].map((id) => (id == null ? undefined : String(id))), ]).map((id) => (id == null ? undefined : String(id))),
}); });
} }
@@ -3765,6 +3767,7 @@ export class ClaimRequestManagementService {
const candidateIds = [ const candidateIds = [
...new Set( ...new Set(
[ [
claimCase?.reviewReferral?.assigneeId,
blame.initiatedByFieldExpertId, blame.initiatedByFieldExpertId,
blame.expert?.assignedExpertId, blame.expert?.assignedExpertId,
blame.expert?.decision?.decidedByExpertId, blame.expert?.decision?.decidedByExpertId,
@@ -3870,7 +3873,7 @@ export class ClaimRequestManagementService {
type?: BlameRequestType; type?: BlameRequestType;
assignedFileReviewerId?: unknown; assignedFileReviewerId?: unknown;
}, },
claimCase: { evaluation?: Record<string, unknown> } | null | undefined, claimCase: FanavaranClaimExpertContext | null | undefined,
): Promise<{ ): Promise<{
claimExpertId: number | null; claimExpertId: number | null;
code: string | null; code: string | null;
@@ -3892,7 +3895,8 @@ export class ClaimRequestManagementService {
} }
if (blame.isMadeByFileMaker) { if (blame.isMadeByFileMaker) {
if (!blame.assignedFileReviewerId) { const reviewerId = claimCase?.reviewReferral?.assigneeId ?? blame.assignedFileReviewerId;
if (!reviewerId) {
return { return {
claimExpertId: null, claimExpertId: null,
code: 'FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING', code: 'FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING',
@@ -3901,7 +3905,7 @@ export class ClaimRequestManagementService {
candidatesTried: [], candidatesTried: [],
}; };
} }
const fileReviewerId = String(blame.assignedFileReviewerId); const fileReviewerId = String(reviewerId);
const fileReviewer = const fileReviewer =
await this.fileReviewerDbService.findById(fileReviewerId); await this.fileReviewerDbService.findById(fileReviewerId);
if (!fileReviewer) { if (!fileReviewer) {
@@ -3929,7 +3933,7 @@ export class ClaimRequestManagementService {
}; };
} }
const actorId = this.fanavaranDamageReplyActorId(claimCase); const actorId = claimCase?.reviewReferral?.assigneeId ?? this.fanavaranDamageReplyActorId(claimCase);
if (actorId == null || String(actorId).trim() === '') { if (actorId == null || String(actorId).trim() === '') {
return { return {
claimExpertId: null, claimExpertId: null,
@@ -3977,7 +3981,7 @@ export class ClaimRequestManagementService {
type?: BlameRequestType; type?: BlameRequestType;
assignedFileReviewerId?: unknown; assignedFileReviewerId?: unknown;
}, },
claimCase: { evaluation?: Record<string, unknown> } | null | undefined, claimCase: FanavaranClaimExpertContext | null | undefined,
options?: { required?: boolean }, options?: { required?: boolean },
): Promise<number | null> { ): Promise<number | null> {
const resolved = await this.tryResolveFanavaranExpertiseClaimExpertId( const resolved = await this.tryResolveFanavaranExpertiseClaimExpertId(
@@ -8193,6 +8197,21 @@ export class ClaimRequestManagementService {
clientKey: FanavaranClientKey, clientKey: FanavaranClientKey,
bodyOverride?: Record<string, unknown>, bodyOverride?: Record<string, unknown>,
auditSource: FanavaranAuditSource = FanavaranAuditSource.AUTO_SUBMIT, auditSource: FanavaranAuditSource = FanavaranAuditSource.AUTO_SUBMIT,
): Promise<any> {
const release = await this.claimCaseDbService.acquireReviewWrite(claimCaseId);
if (!release) throw new NotFoundException('Claim case not found');
try {
return await this.executeFanavaranBaseClaim(claimCaseId, clientKey, bodyOverride, auditSource);
} finally {
await release();
}
}
private async executeFanavaranBaseClaim(
claimCaseId: string,
clientKey: FanavaranClientKey,
bodyOverride: Record<string, unknown> | undefined,
auditSource: FanavaranAuditSource,
): Promise<any> { ): Promise<any> {
const logPrefix = `[Fanavaran ${clientKey} V2]`; const logPrefix = `[Fanavaran ${clientKey} V2]`;
@@ -12044,6 +12063,9 @@ export class ClaimRequestManagementService {
claimCase: any, claimCase: any,
blame: any, blame: any,
): Promise<void> { ): Promise<void> {
if (claimCase.reviewReferral) {
throw new ForbiddenException(REVIEW_REFERRAL_DENIED);
}
if ( if (
claimCase.workflow?.currentStep === ClaimWorkflowStep.SELECT_OUTER_PARTS claimCase.workflow?.currentStep === ClaimWorkflowStep.SELECT_OUTER_PARTS
) { ) {
@@ -12084,14 +12106,23 @@ export class ClaimRequestManagementService {
); );
} }
await this.claimCaseDbService.findByIdAndUpdate(String(claimCase._id), { const update = {
$set: { $set: {
status: ClaimCaseStatus.SELECTING_OUTER_PARTS, status: ClaimCaseStatus.SELECTING_OUTER_PARTS,
claimStatus: ClaimStatus.PENDING, claimStatus: ClaimStatus.PENDING,
'workflow.currentStep': ClaimWorkflowStep.SELECT_OUTER_PARTS, 'workflow.currentStep': ClaimWorkflowStep.SELECT_OUTER_PARTS,
'workflow.nextStep': ClaimWorkflowStep.SELECT_OTHER_PARTS, 'workflow.nextStep': ClaimWorkflowStep.SELECT_OTHER_PARTS,
}, },
}); };
if (isFileReviewerReentry || claimCase.status === ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT) {
const resumed = await this.claimCaseDbService.findOneAndUpdate(
{ _id: claimCase._id, status: claimCase.status, reviewReferral: null },
update,
);
if (!resumed) throw new ConflictException('پرونده تغییر کرده است. وضعیت پرونده را دوباره دریافت کنید.');
} else {
await this.claimCaseDbService.findByIdAndUpdate(String(claimCase._id), update);
}
} }
private async assertV3InPersonClaim(claimCase: any) { private async assertV3InPersonClaim(claimCase: any) {
@@ -1,10 +1,12 @@
import { Injectable } from "@nestjs/common"; import { Injectable, Logger } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose"; import { InjectModel } from "@nestjs/mongoose";
import { randomUUID } from "node:crypto";
import { FilterQuery, Model, Types } from "mongoose"; import { FilterQuery, Model, Types } from "mongoose";
import { ClaimCase, ClaimCaseDocument } from "../schema/claim-cases.schema"; import { ClaimCase, ClaimCaseDocument } from "../schema/claim-cases.schema";
@Injectable() @Injectable()
export class ClaimCaseDbService { export class ClaimCaseDbService {
private readonly logger = new Logger(ClaimCaseDbService.name);
constructor( constructor(
@InjectModel(ClaimCase.name) @InjectModel(ClaimCase.name)
private readonly claimCaseModel: Model<ClaimCaseDocument>, private readonly claimCaseModel: Model<ClaimCaseDocument>,
@@ -20,6 +22,70 @@ export class ClaimCaseDbService {
return this.claimCaseModel.findById(id); return this.claimCaseModel.findById(id);
} }
findReviewAccess(id: string) {
return this.claimCaseModel
.findById(id)
.select(
"reviewReferral owner.clientId owner.userClientKey fileMakerApprovalActorId initiatedByFieldExpertId status",
)
.lean()
.exec();
}
async acquireReviewWrite(
id: string,
filter: Record<string, Date | Types.ObjectId | null> = {},
) {
const token = randomUUID();
const now = new Date();
// Bounded recovery for abandoned requests after an API process stops.
const expiresAt = new Date(now.getTime() + 60 * 60_000);
const _id = new Types.ObjectId(id);
// Internal leases must not change the case's updatedAt or audit timestamp.
const acquired = await this.claimCaseModel.collection.findOneAndUpdate(
{ ...filter, _id },
[
{
$set: {
reviewWrites: {
$concatArrays: [
{
$filter: {
input: { $ifNull: ["$reviewWrites", []] },
as: "write",
cond: { $gt: ["$$write.expiresAt", now] },
},
},
[{ token, expiresAt }],
],
},
},
},
],
{ projection: { _id: 1 } },
);
if (!acquired) return null;
return async () => {
try {
await this.claimCaseModel.collection.updateOne({ _id }, [
{
$set: {
reviewWrites: {
$filter: {
input: { $ifNull: ["$reviewWrites", []] },
as: "write",
cond: { $ne: ["$$write.token", token] },
},
},
},
},
]);
} catch {
this.logger.warn("Could not release review write for claim " + id);
}
};
}
async findWithFanavaranSignature(id: string | Types.ObjectId) { async findWithFanavaranSignature(id: string | Types.ObjectId) {
return this.claimCaseModel.findById(id).select("+fanavaranExpertSignature"); return this.claimCaseModel.findById(id).select("+fanavaranExpertSignature");
} }
@@ -254,6 +254,29 @@ export const FanavaranVehicleReviewSchema = SchemaFactory.createForClass(
FanavaranVehicleReview, FanavaranVehicleReview,
); );
@Schema({ _id: false })
export class ClaimReviewReferral {
@Prop({ type: Types.ObjectId, required: true })
assigneeId: Types.ObjectId;
@Prop({ type: String, required: true })
assigneeRole: string;
@Prop({ type: Date, required: true })
referredAt: Date;
}
const ClaimReviewReferralSchema = SchemaFactory.createForClass(ClaimReviewReferral);
@Schema({ _id: false })
class ClaimReviewWrite {
@Prop({ type: String, required: true })
token: string;
@Prop({ type: Date, required: true })
expiresAt: Date;
}
const ClaimReviewWriteSchema = SchemaFactory.createForClass(ClaimReviewWrite);
@Schema({ @Schema({
collection: "claimCases", collection: "claimCases",
timestamps: true, timestamps: true,
@@ -261,6 +284,7 @@ export const FanavaranVehicleReviewSchema = SchemaFactory.createForClass(
versionKey: false, versionKey: false,
}) })
export class ClaimCase { export class ClaimCase {
updatedAt?: Date;
@Prop({ required: true, unique: true, index: true, trim: true }) @Prop({ required: true, unique: true, index: true, trim: true })
requestNo: string; requestNo: string;
@@ -312,7 +336,7 @@ export class ClaimCase {
@Prop({ type: Types.ObjectId, index: true }) @Prop({ type: Types.ObjectId, index: true })
initiatedByFieldExpertId?: Types.ObjectId; initiatedByFieldExpertId?: Types.ObjectId;
/** Routing branch inherited from the blame (user selection or expert-created branch). */ /** Current review branch, initially inherited from the originating blame branch. */
@Prop({ type: Types.ObjectId, index: true }) @Prop({ type: Types.ObjectId, index: true })
branchId?: Types.ObjectId; branchId?: Types.ObjectId;
@@ -324,6 +348,12 @@ export class ClaimCase {
@Prop({ type: Types.ObjectId, index: true }) @Prop({ type: Types.ObjectId, index: true })
damagedPartyUserId?: Types.ObjectId; damagedPartyUserId?: Types.ObjectId;
@Prop({ type: ClaimReviewReferralSchema })
reviewReferral?: ClaimReviewReferral;
@Prop({ type: [ClaimReviewWriteSchema], select: false, default: undefined })
reviewWrites?: ClaimReviewWrite[];
@Prop({ type: ClaimWorkflowSchema, default: () => ({}) }) @Prop({ type: ClaimWorkflowSchema, default: () => ({}) })
workflow?: ClaimWorkflow; workflow?: ClaimWorkflow;
@@ -444,3 +474,4 @@ export class ClaimCase {
export type ClaimCaseDocument = HydratedDocument<ClaimCase>; export type ClaimCaseDocument = HydratedDocument<ClaimCase>;
export const ClaimCaseSchema = SchemaFactory.createForClass(ClaimCase); export const ClaimCaseSchema = SchemaFactory.createForClass(ClaimCase);
ClaimCaseSchema.index({ status: 1, "workflow.locked": 1 }); ClaimCaseSchema.index({ status: 1, "workflow.locked": 1 });
ClaimCaseSchema.index({ "reviewReferral.assigneeId": 1 }, { sparse: true });
@@ -121,6 +121,7 @@ describe("Fanavaran outgoing Location headers", () => {
? { locations: [{ id: "110011", name: "Claim branch" }] } ? { locations: [{ id: "110011", name: "Claim branch" }] }
: null, : null,
); );
management.claimCaseDbService.acquireReviewWrite = async () => async () => {};
management.assertFanavaranVehicleReviewApproved = jest.fn(); management.assertFanavaranVehicleReviewApproved = jest.fn();
management.previewFanavaranSubmitV2 = jest.fn().mockResolvedValue({ management.previewFanavaranSubmitV2 = jest.fn().mockResolvedValue({
PolicyId: 1, PolicyId: 1,
@@ -4,7 +4,18 @@ import { toFanavaranHullBaseClaimPayload } from "./fanavaran-hull-base-claim";
function setup(product = "car-body") { function setup(product = "car-body") {
const service = Object.create(ClaimRequestManagementService.prototype) as any; const service = Object.create(ClaimRequestManagementService.prototype) as any;
service.logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn() }; service.logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn() };
service.claimCaseDbService = { findById: jest.fn().mockResolvedValue({}) }; service.claimCaseDbService = {
acquireReviewWrite: async () => async () => {},
findById: jest.fn().mockResolvedValue({
fanavaranVehicleReview: {
approved: true,
vehicleGroup: { id: 1 },
vehicleUseType: { id: 3 },
vehicleSystem: { id: 14 },
vehicleKind: { id: 7456 },
},
}),
};
service.fanavaranAuditService = { generateTrackingCode: () => "test" }; service.fanavaranAuditService = { generateTrackingCode: () => "test" };
service.fanavaranAuthService = { assertNotInBackoff: jest.fn() }; service.fanavaranAuthService = { assertNotInBackoff: jest.fn() };
service.previewFanavaranSubmitV2 = jest.fn().mockResolvedValue({ service.previewFanavaranSubmitV2 = jest.fn().mockResolvedValue({
+77 -22
View File
@@ -1,5 +1,12 @@
"use strict"; "use strict";
import {
assertReferredReviewer,
isOriginalFileMaker,
isReferredReviewer,
reviewReferralActorFilter,
} from "./review-referral/review-referral";
import { hasReviewedTejaratNotifier } from "src/fanavaran/tejarat-notifier"; import { hasReviewedTejaratNotifier } from "src/fanavaran/tejarat-notifier";
import { resolveFanavaranClientKey } from "src/core/config/fanavaran-client.config"; import { resolveFanavaranClientKey } from "src/core/config/fanavaran-client.config";
@@ -322,6 +329,10 @@ export class ExpertClaimService {
claim: any, claim: any,
actor: any, actor: any,
): Promise<void> { ): Promise<void> {
if (claim.reviewReferral) {
assertReferredReviewer(claim, actor);
return;
}
const blame = await this.loadBlameForClaim(claim); const blame = await this.loadBlameForClaim(claim);
// FILE_REVIEWER: by the time we reach this method the caller has already // FILE_REVIEWER: by the time we reach this method the caller has already
// verified that actor.sub === blame.assignedFileReviewerId (Phase 2 of // verified that actor.sub === blame.assignedFileReviewerId (Phase 2 of
@@ -400,6 +411,8 @@ export class ExpertClaimService {
? String((damageExpert as any).branchId) ? String((damageExpert as any).branchId)
: undefined; : undefined;
if (!actorBranchId) { if (!actorBranchId) {
const referred = claims.filter((claim) => isReferredReviewer(claim, actor));
if (referred.length) return referred;
throw new ForbiddenException( throw new ForbiddenException(
"DamageExpert account is not assigned to a branch.", "DamageExpert account is not assigned to a branch.",
); );
@@ -450,6 +463,7 @@ export class ExpertClaimService {
); );
return claims.filter((claim) => { return claims.filter((claim) => {
if (claim.reviewReferral) return isReferredReviewer(claim, actor);
let caseBranchId = claim?.branchId ? String(claim.branchId) : undefined; let caseBranchId = claim?.branchId ? String(claim.branchId) : undefined;
if (!caseBranchId && claim?.blameRequestId) { if (!caseBranchId && claim?.blameRequestId) {
const blame = blameById.get(String(claim.blameRequestId)); const blame = blameById.get(String(claim.blameRequestId));
@@ -1389,7 +1403,7 @@ export class ExpertClaimService {
// so they can perform damage assessment. Fall through to the // so they can perform damage assessment. Fall through to the
// damage-expert path below; assertExpertActorOnClaim will verify // damage-expert path below; assertExpertActorOnClaim will verify
// tenant scope via the reviewer's clientKey. // tenant scope via the reviewer's clientKey.
if ((actor as any).role === RoleEnum.FILE_REVIEWER) { if (actor.role === RoleEnum.FILE_REVIEWER && !claim.reviewReferral) {
if (!claim.blameRequestId) { if (!claim.blameRequestId) {
throw new BadRequestException({ throw new BadRequestException({
success: false, success: false,
@@ -1470,7 +1484,8 @@ export class ExpertClaimService {
const isFieldExpertOwner = const isFieldExpertOwner =
(actor as any).role === RoleEnum.FIELD_EXPERT && (actor as any).role === RoleEnum.FIELD_EXPERT &&
(await this.fieldExpertOwnsClaim(claim, actor)); (isReferredReviewer(claim, actor) ||
(await this.fieldExpertOwnsClaim(claim, actor)));
const isFactorValidationLock = const isFactorValidationLock =
claimIsAwaitingExpertFactorValidationV2(claim); claimIsAwaitingExpertFactorValidationV2(claim);
const isDamageReviewLock = const isDamageReviewLock =
@@ -1485,6 +1500,7 @@ export class ExpertClaimService {
claim.status === ClaimCaseStatus.CANCELLED; claim.status === ClaimCaseStatus.CANCELLED;
const isFieldExpertPortfolioLock = const isFieldExpertPortfolioLock =
isFieldExpertOwner && isFieldExpertOwner &&
!claim.reviewReferral &&
!isTerminalClaim && !isTerminalClaim &&
!isDamageReviewLock && !isDamageReviewLock &&
!isFactorValidationLock && !isFactorValidationLock &&
@@ -1633,6 +1649,7 @@ export class ExpertClaimService {
const assignFilter: Record<string, unknown> = { const assignFilter: Record<string, unknown> = {
_id: new Types.ObjectId(claimRequestId), _id: new Types.ObjectId(claimRequestId),
"reviewReferral.referredAt": claim.reviewReferral?.referredAt ?? null,
$and: [ $and: [
{ {
$or: [ $or: [
@@ -2488,11 +2505,17 @@ export class ExpertClaimService {
async getStatusReportBucketsV2(actor: any): Promise<Record<string, number>> { async getStatusReportBucketsV2(actor: any): Promise<Record<string, number>> {
if (actor.role === RoleEnum.FIELD_EXPERT) { if (actor.role === RoleEnum.FIELD_EXPERT) {
const rows = (await this.claimCaseDbService.find( const rows = (await this.claimCaseDbService.find(
{ initiatedByFieldExpertId: new Types.ObjectId(actor.sub) }, {
$or: [
{ initiatedByFieldExpertId: new Types.ObjectId(actor.sub) },
reviewReferralActorFilter(actor),
],
},
{ lean: true }, { lean: true },
)) as any[]; )) as any[];
const buckets = initialClaimExpertReportBuckets(); const buckets = initialClaimExpertReportBuckets();
for (const doc of rows) { for (const doc of rows) {
if (doc.reviewReferral && !isReferredReviewer(doc, actor)) continue;
const key = claimCaseStatusToReportBucket(String(doc.status ?? "")); const key = claimCaseStatusToReportBucket(String(doc.status ?? ""));
buckets.all++; buckets.all++;
buckets[key] = (buckets[key] ?? 0) + 1; buckets[key] = (buckets[key] ?? 0) + 1;
@@ -2520,6 +2543,7 @@ export class ExpertClaimService {
expertPortfolioFileIdsFromActivityEvents(activityEvents); expertPortfolioFileIdsFromActivityEvents(activityEvents);
const orClauses: Record<string, unknown>[] = [ const orClauses: Record<string, unknown>[] = [
reviewReferralActorFilter(actor),
{ "workflow.lockedBy.actorId": expertOid }, { "workflow.lockedBy.actorId": expertOid },
{ "evaluation.damageExpertReply.actorDetail.actorId": expertOid }, { "evaluation.damageExpertReply.actorDetail.actorId": expertOid },
{ "evaluation.damageExpertReplyFinal.actorDetail.actorId": expertOid }, { "evaluation.damageExpertReplyFinal.actorDetail.actorId": expertOid },
@@ -2544,7 +2568,9 @@ export class ExpertClaimService {
const id = String(doc._id ?? ""); const id = String(doc._id ?? "");
if (seen.has(id)) continue; if (seen.has(id)) continue;
if ( if (
!claimDocInExpertPortfolio(doc, expertId, activityFileIds, clientKey) doc.reviewReferral && actor.role !== RoleEnum.FILE_MAKER
? !isReferredReviewer(doc, actor)
: !claimDocInExpertPortfolio(doc, expertId, activityFileIds, clientKey)
) { ) {
continue; continue;
} }
@@ -2630,6 +2656,7 @@ export class ExpertClaimService {
) )
.then((docs) => docs.map((d) => (d as { _id: unknown })._id)); .then((docs) => docs.map((d) => (d as { _id: unknown })._id));
const claimOr: Record<string, unknown>[] = [ const claimOr: Record<string, unknown>[] = [
reviewReferralActorFilter(actor),
{ {
initiatedByFieldExpertId: expertOid, initiatedByFieldExpertId: expertOid,
requiresFileMakerApproval: { $ne: true }, requiresFileMakerApproval: { $ne: true },
@@ -2638,7 +2665,8 @@ export class ExpertClaimService {
if (expertBlameIds.length > 0) { if (expertBlameIds.length > 0) {
claimOr.push({ blameRequestId: { $in: expertBlameIds } }); claimOr.push({ blameRequestId: { $in: expertBlameIds } });
} }
claims = (await this.claimCaseDbService.find({ $or: claimOr })) as any[]; claims = (await this.claimCaseDbService.find({ $or: claimOr }))
.filter((c) => !c.reviewReferral || isReferredReviewer(c, actor));
} else { } else {
const clientKey = requireActorClientKey(actor); const clientKey = requireActorClientKey(actor);
const expertId = String(actor.sub); const expertId = String(actor.sub);
@@ -2651,6 +2679,7 @@ export class ExpertClaimService {
const activityFileIds = const activityFileIds =
expertPortfolioFileIdsFromActivityEvents(activityEvents); expertPortfolioFileIdsFromActivityEvents(activityEvents);
const orClauses: Record<string, unknown>[] = [ const orClauses: Record<string, unknown>[] = [
reviewReferralActorFilter(actor),
{ "workflow.lockedBy.actorId": expertOid }, { "workflow.lockedBy.actorId": expertOid },
{ "evaluation.damageExpertReply.actorDetail.actorId": expertOid }, { "evaluation.damageExpertReply.actorDetail.actorId": expertOid },
{ "evaluation.damageExpertReplyFinal.actorDetail.actorId": expertOid }, { "evaluation.damageExpertReplyFinal.actorDetail.actorId": expertOid },
@@ -2672,7 +2701,9 @@ export class ExpertClaimService {
const id = String(doc._id ?? ""); const id = String(doc._id ?? "");
if (seen.has(id)) continue; if (seen.has(id)) continue;
if ( if (
!claimDocInExpertPortfolio(doc, expertId, activityFileIds, clientKey) doc.reviewReferral && actor.role !== RoleEnum.FILE_MAKER
? !isReferredReviewer(doc, actor)
: !claimDocInExpertPortfolio(doc, expertId, activityFileIds, clientKey)
) { ) {
continue; continue;
} }
@@ -2866,6 +2897,7 @@ export class ExpertClaimService {
// Post-filter: remove files that belong to another expert after reconciliation // Post-filter: remove files that belong to another expert after reconciliation
const finalFiltered = filtered.filter((c) => { const finalFiltered = filtered.filter((c) => {
if (c.reviewReferral) return isReferredReviewer(c, actor);
const assignedId = String(c.workflow?.assignedForReviewBy?.actorId ?? ""); const assignedId = String(c.workflow?.assignedForReviewBy?.actorId ?? "");
const lockEnforced = const lockEnforced =
c.workflow?.locked && this.isClaimV2WorkflowLockCurrentlyEnforced(c); c.workflow?.locked && this.isClaimV2WorkflowLockCurrentlyEnforced(c);
@@ -2989,6 +3021,7 @@ export class ExpertClaimService {
.then((docs) => docs.map((d) => (d as { _id: unknown })._id)); .then((docs) => docs.map((d) => (d as { _id: unknown })._id));
const claimOr: Record<string, unknown>[] = [ const claimOr: Record<string, unknown>[] = [
reviewReferralActorFilter(actor),
// Direct claim link: exclude V5 claims that require FileMaker approval // Direct claim link: exclude V5 claims that require FileMaker approval
{ {
initiatedByFieldExpertId: expertOid, initiatedByFieldExpertId: expertOid,
@@ -3025,7 +3058,10 @@ export class ExpertClaimService {
blames.map((b) => [String(b._id), b]), blames.map((b) => [String(b._id), b]),
); );
const list = claims.map((c) => { const visibleClaims = claims.filter(
(claim) => !claim.reviewReferral || isReferredReviewer(claim, actor),
);
const list = visibleClaims.map((c) => {
const v = this.vehicleForExpertFromClaimAndBlameMap(c, blameById); const v = this.vehicleForExpertFromClaimAndBlameMap(c, blameById);
const blame = c.blameRequestId const blame = c.blameRequestId
? blameById.get(c.blameRequestId.toString()) ? blameById.get(c.blameRequestId.toString())
@@ -3093,6 +3129,15 @@ export class ExpertClaimService {
const clientKey = requireActorClientKey(actor); const clientKey = requireActorClientKey(actor);
const reviewerOid = new Types.ObjectId(actor.sub); const reviewerOid = new Types.ObjectId(actor.sub);
const referred = await this.claimCaseDbService.find(reviewReferralActorFilter(actor), {
lean: true,
select: "blameRequestId owner reviewReferral",
});
const referredBlameIds = referred
.filter((claim) => isReferredReviewer(claim, actor) && claim.blameRequestId)
.map((claim) => claim.blameRequestId);
const referredBlames = new Set(referredBlameIds.map(String));
// Find V4 and V5 blame files visible to this reviewer // Find V4 and V5 blame files visible to this reviewer
const blames = (await this.blameRequestDbService.find( const blames = (await this.blameRequestDbService.find(
{ {
@@ -3100,6 +3145,7 @@ export class ExpertClaimService {
expertInitiated: true, expertInitiated: true,
creationMethod: "IN_PERSON", creationMethod: "IN_PERSON",
$or: [ $or: [
{ _id: { $in: referredBlameIds } },
// Open: sealed by FileMaker, not yet taken by any reviewer // Open: sealed by FileMaker, not yet taken by any reviewer
{ {
status: "WAITING_FOR_FILE_REVIEWER", status: "WAITING_FOR_FILE_REVIEWER",
@@ -3125,11 +3171,12 @@ export class ExpertClaimService {
// Scope to this reviewer's insurer via blame party clientId // Scope to this reviewer's insurer via blame party clientId
const tenantScopedBlames = blames.filter((b) => const tenantScopedBlames = blames.filter((b) =>
blameCaseTouchesClient(b, clientKey), referredBlames.has(String(b._id)) || blameCaseTouchesClient(b, clientKey),
); );
const scopedBlames = ( const scopedBlames = (
await Promise.all( await Promise.all(
tenantScopedBlames.map(async (blame) => { tenantScopedBlames.map(async (blame) => {
if (referredBlames.has(String(blame._id))) return blame;
try { try {
await this.fanavaranLocationService.assertMakerReviewerBranchCompatible( await this.fanavaranLocationService.assertMakerReviewerBranchCompatible(
{ {
@@ -3161,7 +3208,10 @@ export class ExpertClaimService {
scopedBlames.map((b) => [String(b._id), b]), scopedBlames.map((b) => [String(b._id), b]),
); );
const list = claims.map((c) => { const visibleClaims = claims.filter(
(claim) => !claim.reviewReferral || isReferredReviewer(claim, actor),
);
const list = visibleClaims.map((c) => {
const blame = c.blameRequestId const blame = c.blameRequestId
? blameById.get(c.blameRequestId.toString()) ? blameById.get(c.blameRequestId.toString())
: undefined; : undefined;
@@ -3171,8 +3221,9 @@ export class ExpertClaimService {
c.workflow?.locked && this.isClaimV2WorkflowLockCurrentlyEnforced(c) c.workflow?.locked && this.isClaimV2WorkflowLockCurrentlyEnforced(c)
); );
const assignedToMe = const assignedToMe =
blame?.assignedFileReviewerId && c.reviewReferral
String(blame.assignedFileReviewerId) === actor.sub; ? isReferredReviewer(c, actor)
: String(blame?.assignedFileReviewerId ?? "") === actor.sub;
return { return {
claimRequestId: c._id.toString(), claimRequestId: c._id.toString(),
publicId: c.publicId, publicId: c.publicId,
@@ -3202,9 +3253,10 @@ export class ExpertClaimService {
createdAt: c.createdAt, createdAt: c.createdAt,
awaitingFactorValidation: claimIsAwaitingExpertFactorValidationV2(c), awaitingFactorValidation: claimIsAwaitingExpertFactorValidationV2(c),
needsFileReviewerCompletion: needsFileReviewerCompletion:
String(blame?.status ?? "") === "WAITING_FOR_FILE_REVIEWER" || !c.reviewReferral &&
(!!blame?.isMadeByFileMaker && (String(blame?.status ?? "") === "WAITING_FOR_FILE_REVIEWER" ||
String(blame?.status ?? "") === "WAITING_FOR_EXPERT"), (!!blame?.isMadeByFileMaker &&
String(blame?.status ?? "") === "WAITING_FOR_EXPERT")),
assignedToMe: !!assignedToMe, assignedToMe: !!assignedToMe,
requiresFileMakerApproval: !!(c as any).requiresFileMakerApproval, requiresFileMakerApproval: !!(c as any).requiresFileMakerApproval,
fileMakerRejectionCount: (c as any).fileMakerRejectionCount ?? 0, fileMakerRejectionCount: (c as any).fileMakerRejectionCount ?? 0,
@@ -3602,10 +3654,9 @@ export class ExpertClaimService {
"workflow.preLockQueueSnapshot": "", "workflow.preLockQueueSnapshot": "",
}; };
const assigneeToPersist = claimWorkflowAssigneeToPersistOnLockExpiry( const assigneeToPersist = claim.reviewReferral
claim.workflow, ? claim.workflow?.assignedForReviewBy
claim, : claimWorkflowAssigneeToPersistOnLockExpiry(claim.workflow, claim);
);
const expireLockSet: Record<string, unknown> = { "workflow.locked": false }; const expireLockSet: Record<string, unknown> = { "workflow.locked": false };
if (assigneeToPersist) { if (assigneeToPersist) {
expireLockSet["workflow.assignedForReviewBy"] = assigneeToPersist; expireLockSet["workflow.assignedForReviewBy"] = assigneeToPersist;
@@ -3676,10 +3727,12 @@ export class ExpertClaimService {
// FILE_REVIEWER access is validated by the role-specific gate below // FILE_REVIEWER access is validated by the role-specific gate below
// (isAssignedToMe || isOpen). Skip the generic tenant-scope assert which // (isAssignedToMe || isOpen). Skip the generic tenant-scope assert which
// would incorrectly reject them via the initiatedByFieldExpertId path. // would incorrectly reject them via the initiatedByFieldExpertId path.
if (actor.role !== RoleEnum.FILE_REVIEWER) { if (!claim.reviewReferral) {
assertClaimCaseForExpertActor(claim, actor, linkedBlame); if (actor.role !== RoleEnum.FILE_REVIEWER) {
assertClaimCaseForExpertActor(claim, actor, linkedBlame);
}
await this.assertActorBranchAccess(claim, actor, linkedBlame);
} }
await this.assertActorBranchAccess(claim, actor, linkedBlame);
// Variables used both in the gate block and in the detail-build section below // Variables used both in the gate block and in the detail-build section below
const isDamageExpertPhase = const isDamageExpertPhase =
@@ -3690,7 +3743,9 @@ export class ExpertClaimService {
// FileMaker: can view any file they created (both during filing and approval phase). // 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. // The list endpoint already filters to V5-only; detail access is scoped by ownership.
if (actor.role === RoleEnum.FILE_MAKER) { if (claim.reviewReferral) {
if (!isOriginalFileMaker(claim, actor)) assertReferredReviewer(claim, actor);
} else if (actor.role === RoleEnum.FILE_MAKER) {
const isOwn = claimCaseInitiatedByFieldExpert(claim, actor, linkedBlame); const isOwn = claimCaseInitiatedByFieldExpert(claim, actor, linkedBlame);
if (!isOwn) { if (!isOwn) {
throw new ForbiddenException( throw new ForbiddenException(
@@ -1,3 +1,4 @@
import { GuardClaimReview } from "src/expert-claim/review-referral/claim-review.interceptor";
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
import { AiPricingRequestDto } from "src/ai/ai-pricing-request.dto"; import { AiPricingRequestDto } from "src/ai/ai-pricing-request.dto";
import { ValidationPipe } from "@nestjs/common"; import { ValidationPipe } from "@nestjs/common";
@@ -69,6 +70,7 @@ class InPersonVisitV2Dto {
} }
@ApiTags("expert-claim-panel (v2)") @ApiTags("expert-claim-panel (v2)")
@GuardClaimReview("review")
@EnforceCaseWorkingHours() @EnforceCaseWorkingHours()
@Controller("v2/expert-claim") @Controller("v2/expert-claim")
@ApiBearerAuth() @ApiBearerAuth()
@@ -734,6 +734,7 @@ describe("Expert Fanavaran stage fields", () => {
}); });
management.logger = { log: jest.fn() }; management.logger = { log: jest.fn() };
management.claimCaseDbService = { management.claimCaseDbService = {
acquireReviewWrite: async () => async () => {},
findById: jest.fn().mockResolvedValue(claim), findById: jest.fn().mockResolvedValue(claim),
}; };
management.previewFanavaranSubmitV2 = jest.fn(); management.previewFanavaranSubmitV2 = jest.fn();
@@ -148,7 +148,7 @@ describe("Fanavaran vehicle review", () => {
it("blocks a new manual base submission before building or posting its payload", async () => { it("blocks a new manual base submission before building or posting its payload", async () => {
const service = Object.create(ClaimRequestManagementService.prototype) as any; const service = Object.create(ClaimRequestManagementService.prototype) as any;
service.logger = { log: jest.fn() }; service.logger = { log: jest.fn() };
service.claimCaseDbService = { findById: jest.fn().mockResolvedValue({}) }; service.claimCaseDbService = { acquireReviewWrite: async () => async () => {}, findById: jest.fn().mockResolvedValue({}) };
service.previewFanavaranSubmitV2 = jest.fn(); service.previewFanavaranSubmitV2 = jest.fn();
await expect(service.executeFanavaranV2Submit("case", "moallem", { PolicyId: 1 })) await expect(service.executeFanavaranV2Submit("case", "moallem", { PolicyId: 1 }))
.rejects.toMatchObject({ response: { code: "FANAVARAN_VEHICLE_REVIEW_REQUIRED" } }); .rejects.toMatchObject({ response: { code: "FANAVARAN_VEHICLE_REVIEW_REQUIRED" } });
@@ -159,7 +159,7 @@ describe("Fanavaran vehicle review", () => {
it("reuses the existing base without requiring review or creating another base", async () => { it("reuses the existing base without requiring review or creating another base", async () => {
const service = Object.create(ClaimRequestManagementService.prototype) as any; const service = Object.create(ClaimRequestManagementService.prototype) as any;
service.logger = { log: jest.fn() }; service.logger = { log: jest.fn() };
service.claimCaseDbService = { findById: jest.fn().mockResolvedValue({ claimId: 12378660 }) }; service.claimCaseDbService = { acquireReviewWrite: async () => async () => {}, findById: jest.fn().mockResolvedValue({ claimId: 12378660 }) };
await expect(service.executeFanavaranV2Submit("case", "moallem")) await expect(service.executeFanavaranV2Submit("case", "moallem"))
.resolves.toMatchObject({ Id: 12378660 }); .resolves.toMatchObject({ Id: 12378660 });
}); });
@@ -0,0 +1,81 @@
import {
CallHandler,
ConflictException,
ExecutionContext,
Injectable,
NestInterceptor,
SetMetadata,
} from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { Types } from "mongoose";
import { defer, lastValueFrom } from "rxjs";
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum";
import { RoleEnum } from "src/Types&Enums/role.enum";
import { claimCaseTouchesClient } from "src/helpers/tenant-scope";
import {
assertReferredReviewer,
isOriginalFileMaker,
REVIEW_REFERRAL_CONFLICT,
} from "./review-referral";
type Scope = "review" | "integration" | "approval";
const SCOPE = Symbol("claim-review");
export const GuardClaimReview = (scope: Scope) => SetMetadata(SCOPE, scope);
const writes = new Set(["POST", "PUT", "PATCH", "DELETE"]);
@Injectable()
export class ClaimReviewInterceptor implements NestInterceptor {
constructor(
private readonly reflector: Reflector,
private readonly claims: ClaimCaseDbService,
) {}
async intercept(context: ExecutionContext, next: CallHandler) {
const scope = this.reflector.getAllAndOverride<Scope>(SCOPE, [
context.getHandler(),
context.getClass(),
]);
if (!scope) return next.handle();
const req = context.switchToHttp().getRequest();
const id =
req.params?.claimRequestId ?? req.params?.claimCaseId ?? req.params?.id;
if (!Types.ObjectId.isValid(id) || !req.user?.sub) return next.handle();
const actor = req.user;
const claim = await this.claims.findReviewAccess(id);
if (!claim) return next.handle();
const mutating = writes.has(req.method);
const ownMaker = isOriginalFileMaker(claim, actor);
const retainsApprovalAccess =
ownMaker &&
(scope === "approval" ||
(scope === "review" && !mutating) ||
(scope === "integration" &&
claim.status === ClaimCaseStatus.COMPLETED));
const insurerIntegration =
scope === "integration" &&
(actor.role === RoleEnum.SUPER_ADMIN ||
(actor.role === RoleEnum.COMPANY &&
!!actor.clientKey &&
claimCaseTouchesClient(claim, actor.clientKey)));
if (!retainsApprovalAccess && !insurerIntegration)
assertReferredReviewer(claim, actor);
if (!mutating) return next.handle();
// A referral can interrupt a review session, but may not interleave with a
// write already accepted from that session. The database fence spans replicas.
return defer(async () => {
const release = await this.claims.acquireReviewWrite(id, {
"reviewReferral.referredAt": claim.reviewReferral?.referredAt ?? null,
"reviewReferral.assigneeId": claim.reviewReferral?.assigneeId ?? null,
});
if (!release) throw new ConflictException(REVIEW_REFERRAL_CONFLICT);
try {
return await lastValueFrom(next.handle());
} finally {
await release();
}
});
}
}
@@ -0,0 +1,519 @@
import {
ConflictException,
ForbiddenException,
NotFoundException,
} from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { ExecutionContextHost } from "@nestjs/core/helpers/execution-context-host";
import { Types } from "mongoose";
import { defer, lastValueFrom, of } from "rxjs";
import { ClaimCaseStatus as Status } from "src/Types&Enums/claim-request-management/claim-case-status.enum";
import { ClaimWorkflowStep as Step } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum";
import { ClaimStatus } from "src/Types&Enums/claim-request-management/claimStatus.enum";
import { RoleEnum } from "src/Types&Enums/role.enum";
import { ClaimReviewReferralService } from "src/expert-insurer/claim-review-referral.service";
import { getEventFaDescription } from "src/expert-insurer/helper/timeline-fa-labels";
import {
ClaimReviewInterceptor,
GuardClaimReview,
} from "./claim-review.interceptor";
import {
assertReferredReviewer,
isReferredReviewer,
referralIneligibility,
reviewReferralRole,
} from "./review-referral";
import { ExpertClaimService } from "../expert-claim.service";
import { fanavaranSignatureRevision } from "src/fanavaran/fanavaran-expert-signature";
const tenant = "650000000000000000000001";
const otherTenant = "650000000000000000000002";
const previousBranchId = "650000000000000000000003";
const nextBranchId = "650000000000000000000004";
const previousExpertId = "650000000000000000000005";
const nextExpertId = "650000000000000000000006";
const insurerId = "650000000000000000000007";
const makerId = "650000000000000000000008";
const claimId = "650000000000000000000009";
const blameId = "650000000000000000000010";
const readyClaim = {
_id: new Types.ObjectId(claimId),
publicId: "REF100",
updatedAt: new Date("2026-11-20T08:00:00Z"),
status: Status.WAITING_FOR_DAMAGE_EXPERT,
workflow: { currentStep: Step.USER_SUBMISSION_COMPLETE },
owner: { clientId: new Types.ObjectId(tenant) },
branchId: new Types.ObjectId(previousBranchId),
blameRequestId: new Types.ObjectId(blameId),
};
const complete = {
_id: readyClaim.blameRequestId,
status: "COMPLETED",
branchId: readyClaim.branchId,
};
const split = {
...complete,
isMadeByFileMaker: true,
expertInitiated: true,
initiatedByFieldExpertId: makerId,
assignedFileReviewerId: previousExpertId,
creationMethod: "IN_PERSON",
};
const cases = [
["v1", complete, RoleEnum.DAMAGE_EXPERT],
["v2", { ...complete, expertInitiated: true }, RoleEnum.FIELD_EXPERT],
["v3", { ...complete, expertInitiated: true }, RoleEnum.FIELD_EXPERT],
["v4", split, RoleEnum.FILE_REVIEWER],
["v5", { ...split, requiresFileMakerApproval: true }, RoleEnum.FILE_REVIEWER],
["v6", { ...complete, callCenterInitiated: true }, RoleEnum.DAMAGE_EXPERT],
] as const;
describe("review-only referral eligibility", () => {
it.each(cases)(
"%s can refer the completed intake to the role that runs assessment",
(_, blame, role) => {
expect(reviewReferralRole(readyClaim, blame)).toBe(role);
expect(referralIneligibility(readyClaim, blame)).toBeNull();
expect(
referralIneligibility(
{ ...readyClaim, status: Status.UPLOADING_REQUIRED_DOCUMENTS },
blame,
),
).toBeTruthy();
expect(
referralIneligibility(
{ ...readyClaim, status: Status.WAITING_FOR_USER_RESEND },
blame,
),
).toBeTruthy();
},
);
it.each(["baseClaim", "damageCase", "attachments", "expertise"])(
"blocks a successful %s stage",
(stage) => {
const claim = {
...readyClaim,
fanavaranSync: { [stage]: { status: "success" } },
};
expect(referralIneligibility(claim, complete)).toContain("فناوران");
},
);
it("blocks legacy remote IDs and successful attachment receipts, and permits a failed base submission", () => {
expect(
referralIneligibility({ ...readyClaim, claimNo: 12 }, complete),
).toContain("فناوران");
expect(
referralIneligibility(
{
...readyClaim,
fanavaranSync: { attachments: { files: [{ fileId: 4 }] } },
},
complete,
),
).toContain("فناوران");
expect(
referralIneligibility(
{ ...readyClaim, fanavaranSync: { baseClaim: { status: "failed" } } },
complete,
),
).toBeNull();
});
it("blocks sealed files still waiting for capture, and permits a V5 assessment correction", () => {
const waiting = {
...split,
status: "WAITING_FOR_FILE_REVIEWER",
requiresFileMakerApproval: true,
};
expect(referralIneligibility(readyClaim, waiting)).not.toBeNull();
expect(
referralIneligibility(
{
...readyClaim,
fileMakerRejectionCount: 1,
workflow: { currentStep: Step.EXPERT_DAMAGE_ASSESSMENT },
},
waiting,
),
).toBeNull();
expect(
referralIneligibility(
{ ...readyClaim, status: Status.WAITING_FOR_FILE_MAKER_APPROVAL },
complete,
),
).not.toBeNull();
});
it("allows mid-review and factor validation after all invoices have been uploaded", () => {
expect(
referralIneligibility(
{
...readyClaim,
status: Status.EXPERT_REVIEWING,
workflow: { currentStep: Step.EXPERT_DAMAGE_ASSESSMENT },
},
complete,
),
).toBeNull();
expect(
referralIneligibility(
{
...readyClaim,
status: Status.EXPERT_VALIDATING_REPAIR_FACTORS,
claimStatus: ClaimStatus.UNDER_REVIEW,
workflow: { currentStep: Step.EXPERT_COST_EVALUATION },
},
complete,
),
).toBeNull();
});
});
function setup() {
const previousActor = {
actorId: new Types.ObjectId(previousExpertId),
actorRole: RoleEnum.FILE_REVIEWER,
actorName: "سارا احمدی",
};
const claim = {
...readyClaim,
initiatedByFieldExpertId: new Types.ObjectId(makerId),
fileMakerApprovalActorId: new Types.ObjectId(makerId),
status: Status.EXPERT_REVIEWING,
workflow: {
currentStep: Step.EXPERT_DAMAGE_ASSESSMENT,
assignedForReviewBy: previousActor,
locked: true,
lockedBy: previousActor,
},
evaluation: { damageExpertReply: { description: "ارزیابی اولیه" } },
history: [],
};
const prevBranch = {
_id: previousBranchId,
name: "شعبه قبلی",
city: "تهران",
clientKey: tenant,
};
const nextBranch = {
_id: nextBranchId,
name: "شعبه جدید",
city: "کرج",
clientKey: tenant,
};
const nextExpert = {
_id: nextExpertId,
firstName: "رضا",
lastName: "کریمی",
clientKey: tenant,
branchId: new Types.ObjectId(nextBranchId),
isActive: true,
};
const repo = {
findOne: jest.fn(async (filter) =>
filter.publicId === claim.publicId &&
String(filter.$or[0]["owner.clientId"]) === tenant
? claim
: null,
),
findOneAndUpdate: jest.fn().mockResolvedValue(claim),
};
const reviewers = {
findById: jest.fn().mockResolvedValue(nextExpert),
findReviewCandidates: jest.fn().mockResolvedValue([nextExpert]),
};
const branches = {
findById: jest.fn(async (id) =>
[prevBranch, nextBranch].find((branch) => branch._id === id),
),
findAll: jest.fn().mockResolvedValue([prevBranch, nextBranch]),
};
const service = new ClaimReviewReferralService(
repo as any,
{ findById: async () => split } as any,
branches as any,
{} as any,
{} as any,
reviewers as any,
);
const insurer = { sub: insurerId, clientKey: tenant, fullName: "مدیر بیمه" };
const body = {
expertId: nextExpertId,
revision: String(claim.updatedAt.getTime()),
};
return {
claim,
repo,
reviewers,
service,
insurer,
body,
branches,
nextExpert,
nextBranch,
};
}
describe("insurer claim review referral", () => {
it("updates the assignee and review branch atomically with a before/after audit entry", async () => {
const { claim, repo, service, body, insurer } = setup();
const options = await service.options(tenant, claim.publicId);
expect(options.candidates).toEqual([
{
id: nextExpertId,
name: "رضا کریمی",
branchId: nextBranchId,
branchName: "شعبه جدید",
city: "کرج",
},
]);
await expect(service.refer(insurer, claim.publicId, body)).resolves.toEqual(
{
expertName: "رضا کریمی",
branchName: "شعبه جدید",
},
);
const [filter, update] = repo.findOneAndUpdate.mock.calls[0];
expect(filter).toMatchObject({
status: Status.EXPERT_REVIEWING,
updatedAt: claim.updatedAt,
claimId: null,
"fanavaranSync.baseClaim.status": { $ne: "success" },
reviewWrites: {
$not: { $elemMatch: { expiresAt: { $gt: expect.any(Date) } } },
},
});
expect(String(update.$set.branchId)).toBe(nextBranchId);
expect(String(update.$set.reviewReferral.assigneeId)).toBe(nextExpertId);
expect(update.$set["workflow.locked"]).toBe(false);
expect(update.$unset).toHaveProperty(["workflow.lockedBy"]);
expect(update.$push.history.metadata).toMatchObject({
previousExpertId,
previousExpertName: "سارا احمدی",
previousBranchId,
previousBranchName: "شعبه قبلی",
expertId: nextExpertId,
branchId: nextBranchId,
});
expect(getEventFaDescription(update.$push.history)).toContain("شعبه قبلی");
expect(getEventFaDescription(update.$push.history)).toContain("شعبه جدید");
expect(update.$set).not.toHaveProperty("status");
expect(update.$set).not.toHaveProperty("evaluation");
expect(update.$set).not.toHaveProperty("initiatedByFieldExpertId");
});
it("allows a same-branch reassignment", async () => {
const { claim, service, body, insurer, nextExpert } = setup();
nextExpert.branchId = new Types.ObjectId(previousBranchId);
await expect(
service.refer(insurer, claim.publicId, body),
).resolves.toMatchObject({ branchName: "شعبه قبلی" });
});
it("rejects another insurer, inactive experts or branches, and stale decisions", async () => {
const { claim, service, body, insurer, repo, nextExpert, nextBranch } =
setup();
await expect(
service.refer(
{ ...insurer, clientKey: otherTenant },
claim.publicId,
body,
),
).rejects.toBeInstanceOf(NotFoundException);
await expect(
service.refer(insurer, claim.publicId, { ...body, revision: "0" }),
).rejects.toBeInstanceOf(ConflictException);
nextExpert.isActive = false;
await expect(
service.refer(insurer, claim.publicId, body),
).rejects.toBeInstanceOf(NotFoundException);
nextExpert.isActive = true;
Object.assign(nextBranch, { isActive: false });
await expect(
service.refer(insurer, claim.publicId, body),
).rejects.toBeInstanceOf(ConflictException);
expect(repo.findOneAndUpdate).not.toHaveBeenCalled();
});
it("does not overwrite a concurrent review, referral, or Fanavaran submission", async () => {
const { claim, service, body, insurer, repo } = setup();
repo.findOneAndUpdate.mockResolvedValue(null);
await expect(
service.refer(insurer, claim.publicId, body),
).rejects.toBeInstanceOf(ConflictException);
});
});
@GuardClaimReview("review")
class TestReviewRoute {
review() {}
}
@GuardClaimReview("approval")
class TestMakerApprovalRoute {
review() {}
}
describe("referred expert review access", () => {
const newReviewer = {
sub: nextExpertId,
role: RoleEnum.FILE_REVIEWER,
clientKey: tenant,
};
const claim = {
...readyClaim,
fileMakerApprovalActorId: new Types.ObjectId(makerId),
reviewReferral: {
assigneeId: new Types.ObjectId(nextExpertId),
assigneeRole: RoleEnum.FILE_REVIEWER,
referredAt: new Date(),
},
};
const context = (actor: any, method = "PUT", route = TestReviewRoute) =>
new ExecutionContextHost(
[{ user: actor, method, params: { claimRequestId: claimId } }],
route,
route.prototype.review,
);
const release = jest.fn();
const repo = {
findReviewAccess: jest.fn().mockResolvedValue(claim),
acquireReviewWrite: jest.fn().mockResolvedValue(release),
};
const interceptor = new ClaimReviewInterceptor(new Reflector(), repo as any);
it("requires the exact expert, role and insurer", () => {
expect(isReferredReviewer(claim, newReviewer)).toBe(true);
for (const actor of [
{ ...newReviewer, sub: previousExpertId },
{ ...newReviewer, clientKey: otherTenant },
{ ...newReviewer, role: RoleEnum.DAMAGE_EXPERT },
])
expect(() => assertReferredReviewer(claim, actor)).toThrow(
ForbiddenException,
);
});
it("blocks the old expert before the handler and fences writes from the new expert", async () => {
const handle = jest.fn(() => of("done"));
await expect(
interceptor.intercept(
context({ ...newReviewer, sub: previousExpertId }),
{ handle },
),
).rejects.toBeInstanceOf(ForbiddenException);
expect(handle).not.toHaveBeenCalled();
const result = await interceptor.intercept(context(newReviewer), {
handle,
});
expect(await lastValueFrom(result)).toBe("done");
expect(repo.acquireReviewWrite).toHaveBeenCalledWith(claimId, {
"reviewReferral.referredAt": claim.reviewReferral.referredAt,
"reviewReferral.assigneeId": claim.reviewReferral.assigneeId,
});
expect(release).toHaveBeenCalled();
});
it("releases the write fence when the handler rejects", async () => {
release.mockClear();
const result = await interceptor.intercept(context(newReviewer), {
handle: () =>
defer(async () => {
throw new Error("write failed");
}),
});
await expect(lastValueFrom(result)).rejects.toThrow("write failed");
expect(release).toHaveBeenCalledTimes(1);
});
it("preserves the original FileMaker's approval, while restricting review writes", async () => {
const maker = {
sub: makerId,
role: RoleEnum.FILE_MAKER,
clientKey: tenant,
};
const handle = () => of("allowed");
await expect(
interceptor.intercept(context(maker), { handle }),
).rejects.toBeInstanceOf(ForbiddenException);
const reply = await interceptor.intercept(
context(maker, "POST", TestMakerApprovalRoute),
{ handle },
);
expect(await lastValueFrom(reply)).toBe("allowed");
});
it("admits the referred reviewer for assessment without granting original intake ownership", async () => {
const expert = Object.create(ExpertClaimService.prototype);
expert.loadBlameForClaim = jest.fn();
await expert.assertExpertActorOnClaim(claim, newReviewer);
await expect(
expert.assertExpertActorOnClaim(claim, {
...newReviewer,
sub: previousExpertId,
}),
).rejects.toBeInstanceOf(ForbiddenException);
expect(expert.loadBlameForClaim).not.toHaveBeenCalled();
expect(fanavaranSignatureRevision(claim)).not.toBe(
fanavaranSignatureRevision(readyClaim),
);
});
});
describe("expert queues after a referral", () => {
it.each([RoleEnum.FIELD_EXPERT, RoleEnum.FILE_REVIEWER])(
"lists the case for the %s destination and removes it from the original queue",
async (role) => {
const expert = Object.create(ExpertClaimService.prototype);
const ready = {
...readyClaim,
branchId: new Types.ObjectId(nextBranchId),
initiatedByFieldExpertId: new Types.ObjectId(previousExpertId),
reviewReferral: {
assigneeId: new Types.ObjectId(nextExpertId),
assigneeRole: role,
referredAt: new Date(),
},
};
const intake = {
...split,
_id: readyClaim.blameRequestId,
isMadeByFileMaker: role === RoleEnum.FILE_REVIEWER,
};
expert.blameRequestDbService = { find: async () => [intake] };
expert.claimCaseDbService = {
find: jest.fn(async (filter) => {
const filterId = filter["reviewReferral.assigneeId"];
return filterId && filterId !== nextExpertId ? [] : [ready];
}),
};
expert.fanavaranLocationService = {
assertMakerReviewerBranchCompatible: jest.fn(
async ({ fileReviewerId }) => {
if (fileReviewerId === nextExpertId)
throw new Error("different intake branch");
},
),
};
expert.vehicleForExpertFromClaimAndBlameMap = jest.fn();
expert.blameFileContextForExpert = jest.fn(() => ({}));
expert.paginateClaimListV2 = (rows) => rows;
const newQueue = await expert.getClaimListV2({
sub: nextExpertId,
clientKey: tenant,
role,
});
expect(newQueue).toHaveLength(1);
if (role === RoleEnum.FILE_REVIEWER) {
expect(newQueue[0].needsFileReviewerCompletion).toBe(false);
expect(newQueue[0].assignedToMe).toBe(true);
expect(
expert.fanavaranLocationService.assertMakerReviewerBranchCompatible,
).not.toHaveBeenCalled();
}
const previousQueue = await expert.getClaimListV2({
sub: previousExpertId,
clientKey: tenant,
role,
});
expect(previousQueue).toEqual([]);
},
);
});
@@ -0,0 +1,127 @@
import { ForbiddenException } from "@nestjs/common";
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 { RoleEnum } from "src/Types&Enums/role.enum";
import { claimIsAwaitingExpertFactorValidationV2 } from "src/helpers/claim-v2-expert-reply-workflow";
import { claimCaseTouchesClient } from "src/helpers/tenant-scope";
export const CLAIM_REVIEW_REFERRED = "CLAIM_REVIEW_REFERRED";
export const REVIEW_REFERRAL_CONFLICT =
"پرونده در حال تغییر است. اطلاعات ارجاع را دوباره دریافت کنید.";
export const REVIEW_REFERRAL_DENIED =
"بررسی این پرونده به کارشناس دیگری ارجاع شده است.";
export const REVIEW_REFERRAL_ROLES = [
RoleEnum.DAMAGE_EXPERT,
RoleEnum.FIELD_EXPERT,
RoleEnum.FILE_REVIEWER,
] as const;
export type ReviewReferralRole = (typeof REVIEW_REFERRAL_ROLES)[number];
const fanavaranStages = [
"baseClaim",
"damageCase",
"attachments",
"expertise",
] as const;
const remoteIds = ["claimId", "claimNo", "dmgCaseId", "expertiseId"] as const;
const remoteFields = [
...remoteIds,
...fanavaranStages.flatMap((stage) =>
remoteIds.map((id) => `fanavaranSync.${stage}.${id}`),
),
];
export const noFanavaranSubmission = {
...Object.fromEntries(remoteFields.map((field) => [field, null])),
...Object.fromEntries(
fanavaranStages.map((stage) => [
`fanavaranSync.${stage}.status`,
{ $ne: "success" },
]),
),
"fanavaranSync.attachments.files.0": { $exists: false },
};
export function referralIneligibility(claim: any, blame: any): string | null {
if (!claim) return "پرونده خسارت هنوز تشکیل نشده است.";
if (
remoteIds.some((id) => claim[id] != null) ||
fanavaranStages.some((stage) => {
const sync = claim.fanavaranSync?.[stage];
return (
sync?.status === "success" || remoteIds.some((id) => sync?.[id] != null)
);
}) ||
claim.fanavaranSync?.attachments?.files?.length
)
return "پرونده در فناوران ثبت شده و امکان ارجاع آن وجود ندارد.";
const step = claim.workflow?.currentStep;
const assessmentReady =
(claim.status === ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT &&
[
ClaimWorkflowStep.USER_SUBMISSION_COMPLETE,
ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT,
].includes(step)) ||
(claim.status === ClaimCaseStatus.EXPERT_REVIEWING &&
step === ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT) ||
claimIsAwaitingExpertFactorValidationV2(claim);
// A V5 correction reopens the blame record after the original capture was completed.
const v5Correction =
blame?.isMadeByFileMaker === true &&
blame.requiresFileMakerApproval === true &&
claim.fileMakerRejectionCount > 0 &&
blame.status === "WAITING_FOR_FILE_REVIEWER";
if (
!assessmentReady ||
!blame ||
(blame.status !== "COMPLETED" && !v5Correction)
) {
return "ارجاع پس از تکمیل اطلاعات و ورود پرونده به مرحله ارزیابی خسارت امکان‌پذیر است.";
}
return null;
}
export function reviewReferralRole(claim: any, blame: any): ReviewReferralRole {
if (blame?.isMadeByFileMaker === true) return RoleEnum.FILE_REVIEWER;
if (claim?.initiatedByFieldExpertId || blame?.expertInitiated === true)
return RoleEnum.FIELD_EXPERT;
return RoleEnum.DAMAGE_EXPERT;
}
export function isReferredReviewer(claim: any, actor: any): boolean {
const referral = claim?.reviewReferral;
return (
!!referral &&
referral.assigneeRole === actor?.role &&
String(referral.assigneeId) === String(actor?.sub) &&
!!actor?.clientKey &&
claimCaseTouchesClient(claim, String(actor.clientKey))
);
}
/** V5 approval remains with the file maker who created the case. */
export function isOriginalFileMaker(claim: any, actor: any) {
const makerId =
claim?.fileMakerApprovalActorId ?? claim?.initiatedByFieldExpertId;
return (
actor?.role === RoleEnum.FILE_MAKER &&
!!makerId &&
String(makerId) === String(actor?.sub)
);
}
export function assertReferredReviewer(claim: any, actor: any): void {
if (claim?.reviewReferral && !isReferredReviewer(claim, actor)) {
throw new ForbiddenException({
code: "CLAIM_REVIEW_REFERRED",
message: REVIEW_REFERRAL_DENIED,
});
}
}
export function reviewReferralActorFilter(actor: any) {
return {
"reviewReferral.assigneeId": actor.sub,
"reviewReferral.assigneeRole": actor.role,
};
}
@@ -0,0 +1,264 @@
import {
ConflictException,
Injectable,
NotFoundException,
} from "@nestjs/common";
import { Types } from "mongoose";
import { RoleEnum } from "src/Types&Enums/role.enum";
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
import { ClaimCaseDocument } from "src/claim-request-management/entites/schema/claim-cases.schema";
import { BranchDbService } from "src/client/entities/db-service/branch.db.service";
import {
CLAIM_REVIEW_REFERRED,
noFanavaranSubmission,
referralIneligibility,
REVIEW_REFERRAL_CONFLICT,
reviewReferralRole,
ReviewReferralRole,
} from "src/expert-claim/review-referral/review-referral";
import { personDisplayName } from "src/helpers/person-display-name";
import { BlameRequestDbService } from "src/request-management/entities/db-service/blame-request.db.service";
import { DamageExpertDbService } from "src/users/entities/db-service/damage-expert.db.service";
import { FieldExpertDbService } from "src/users/entities/db-service/field-expert.db.service";
import { FileReviewerDbService } from "src/users/entities/db-service/file-reviewer.db.service";
import { ReferClaimReviewDto } from "./dto/refer-claim-review.dto";
type InsurerActor = { sub: string; clientKey: string; fullName?: string };
type Staff = {
_id?: unknown;
branchId?: unknown;
firstName: string;
lastName: string;
};
type Branch = {
_id?: unknown;
name: string;
code?: string;
city: string;
isActive?: boolean;
};
const revision = (claim: ClaimCaseDocument) =>
String(claim.updatedAt?.getTime() ?? 0);
@Injectable()
export class ClaimReviewReferralService {
constructor(
private readonly claims: ClaimCaseDbService,
private readonly blames: BlameRequestDbService,
private readonly branches: BranchDbService,
private readonly damageExperts: DamageExpertDbService,
private readonly fieldExperts: FieldExpertDbService,
private readonly fileReviewers: FileReviewerDbService,
) {}
private async context(clientKey: string, publicId: string) {
if (!Types.ObjectId.isValid(clientKey))
throw new NotFoundException("پرونده خسارت یافت نشد.");
const tenantFilter = {
$or: [
{ "owner.clientId": new Types.ObjectId(clientKey) },
{ "owner.clientId": null, "owner.userClientKey": clientKey },
],
};
const claim = await this.claims.findOne({ publicId, ...tenantFilter });
if (!claim) throw new NotFoundException("پرونده خسارت یافت نشد.");
const blame = claim.blameRequestId
? await this.blames.findById(claim.blameRequestId)
: null;
const role = reviewReferralRole(claim, blame);
const current =
claim.workflow?.assignedForReviewBy ?? claim.workflow?.lockedBy;
const currentExpertId =
claim.reviewReferral?.assigneeId ??
current?.actorId ??
(role === RoleEnum.FILE_REVIEWER
? blame?.assignedFileReviewerId
: role === RoleEnum.FIELD_EXPERT
? (claim.initiatedByFieldExpertId ?? blame?.initiatedByFieldExpertId)
: undefined);
const branchId = claim.branchId ?? blame?.branchId;
return {
claim,
blame,
role,
current,
currentExpertId,
branchId,
tenantFilter,
};
}
private getStaff(role: ReviewReferralRole) {
if (role === RoleEnum.FILE_REVIEWER) return this.fileReviewers;
if (role === RoleEnum.FIELD_EXPERT) return this.fieldExperts;
return this.damageExperts;
}
private async getBranch(id?: unknown): Promise<Branch | null> {
return id ? this.branches.findById(String(id)) : null;
}
async options(clientKey: string, publicId: string) {
const c = await this.context(clientKey, publicId);
const reason = referralIneligibility(c.claim, c.blame);
const [branches, staff, currentStaff] = await Promise.all([
this.branches.findAll(clientKey) as Promise<Branch[]>,
reason ? [] : this.getStaff(c.role).findReviewCandidates(clientKey),
c.currentExpertId && !c.current?.actorName
? this.getStaff(c.role).findById(String(c.currentExpertId))
: null,
]);
const activeBranches = new Map(
branches
.filter((branch) => branch.isActive !== false)
.map((branch) => [String(branch._id), branch]),
);
const candidates = staff.flatMap((expert: Staff) => {
const id = String(expert._id);
const branchId = String(expert.branchId ?? "");
const branch = activeBranches.get(branchId);
if (
!branch ||
(id === String(c.currentExpertId) && branchId === String(c.branchId))
)
return [];
return [
{
id,
name: personDisplayName(expert),
branchId,
branchName: branch.name,
city: branch.city,
},
];
});
return {
eligible: !reason,
reason,
role: c.role,
revision: revision(c.claim),
current: {
expertName: c.current?.actorName || personDisplayName(currentStaff),
branchName: branches.find(
(branch) => String(branch._id) === String(c.branchId),
)?.name,
},
candidates,
};
}
async refer(
actor: InsurerActor,
publicId: string,
body: ReferClaimReviewDto,
) {
const c = await this.context(actor.clientKey, publicId);
const reason = referralIneligibility(c.claim, c.blame);
if (reason) throw new ConflictException(reason);
if (body.revision !== revision(c.claim))
throw new ConflictException(REVIEW_REFERRAL_CONFLICT);
const repo = this.getStaff(c.role);
const expert = await repo.findById(body.expertId);
if (
!expert ||
String(expert.clientKey) !== actor.clientKey ||
expert.isActive === false ||
!expert.branchId
) {
throw new NotFoundException("کارشناس فعال در این شرکت بیمه یافت نشد.");
}
const [branch, previousBranch, previousExpert] = await Promise.all([
this.branches.findById(String(expert.branchId)),
this.getBranch(c.branchId),
c.currentExpertId && !c.current?.actorName
? repo.findById(String(c.currentExpertId))
: null,
]);
if (
!branch ||
String(branch.clientKey) !== actor.clientKey ||
branch.isActive === false
) {
throw new ConflictException("شعبه کارشناس انتخاب‌شده فعال نیست.");
}
if (
String(c.currentExpertId) === body.expertId &&
String(c.branchId) === String(expert.branchId)
) {
throw new ConflictException(
"این پرونده در همین شعبه به کارشناس انتخاب‌شده ارجاع شده است.",
);
}
const now = new Date();
const expertId = new Types.ObjectId(body.expertId);
const name = personDisplayName(expert);
const updated = await this.claims.findOneAndUpdate(
{
_id: c.claim._id,
...c.tenantFilter,
...noFanavaranSubmission,
updatedAt: c.claim.updatedAt ?? null,
status: c.claim.status,
"workflow.currentStep": c.claim.workflow?.currentStep ?? null,
"workflow.assignedForReviewBy.actorId":
c.claim.workflow?.assignedForReviewBy?.actorId ?? null,
"reviewReferral.referredAt": c.claim.reviewReferral?.referredAt ?? null,
reviewWrites: { $not: { $elemMatch: { expiresAt: { $gt: now } } } },
},
{
$set: {
branchId: expert.branchId,
reviewReferral: {
assigneeId: expertId,
assigneeRole: c.role,
referredAt: now,
},
"workflow.assignedForReviewBy": {
actorId: expertId,
actorName: name,
actorRole: c.role,
},
"workflow.locked": false,
},
$unset: {
"workflow.lockedBy": "",
"workflow.lockedAt": "",
"workflow.expiredAt": "",
"workflow.preLockQueueSnapshot": "",
},
$push: {
history: {
type: CLAIM_REVIEW_REFERRED,
timestamp: now,
actor: {
actorId: new Types.ObjectId(actor.sub),
actorType: RoleEnum.COMPANY,
actorName: actor.fullName,
},
metadata: {
previousExpertId: c.currentExpertId
? String(c.currentExpertId)
: null,
previousExpertName:
c.current?.actorName ||
personDisplayName(previousExpert) ||
null,
previousBranchId: c.branchId ? String(c.branchId) : null,
previousBranchName: previousBranch?.name ?? null,
previousBranchCode: previousBranch?.code ?? null,
expertId: String(expertId),
expertName: name,
expertRole: c.role,
branchId: String(expert.branchId),
branchName: branch.name,
branchCode: branch.code,
},
},
},
},
);
if (!updated) throw new ConflictException(REVIEW_REFERRAL_CONFLICT);
return { expertName: name, branchName: branch.name };
}
}
@@ -0,0 +1,12 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsMongoId, Matches } from "class-validator";
export class ReferClaimReviewDto {
@ApiProperty()
@IsMongoId()
expertId: string;
@ApiProperty({ description: "Revision from the referral options endpoint." })
@Matches(/^\d{1,16}$/)
revision: string;
}
@@ -1,3 +1,5 @@
import { ClaimReviewReferralService } from "./claim-review-referral.service";
import { ReferClaimReviewDto } from "./dto/refer-claim-review.dto";
import { AiService } from "src/ai/ai.service"; import { AiService } from "src/ai/ai.service";
import { currentAiCaptures } from "src/ai/ai-captures"; import { currentAiCaptures } from "src/ai/ai-captures";
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service"; import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
@@ -7,11 +9,14 @@ import {
Controller, Controller,
Get, Get,
Param, Param,
Patch,
Post, Post,
Put, Put,
Query, Query,
UnauthorizedException, UnauthorizedException,
UseGuards, UseGuards,
UsePipes,
ValidationPipe,
} from "@nestjs/common"; } from "@nestjs/common";
import { import {
ApiBearerAuth, ApiBearerAuth,
@@ -62,6 +67,7 @@ export class ExpertInsurerController {
private readonly expertInsurerService: ExpertInsurerService, private readonly expertInsurerService: ExpertInsurerService,
private readonly reportsService: ReportsService, private readonly reportsService: ReportsService,
private readonly aiService: AiService, private readonly aiService: AiService,
private readonly claimReviewReferralService: ClaimReviewReferralService,
private readonly claimCaseDbService: ClaimCaseDbService, private readonly claimCaseDbService: ClaimCaseDbService,
) {} ) {}
@@ -428,6 +434,22 @@ export class ExpertInsurerController {
return this.aiService.retry(id, currentAiCaptures(claim), false); return this.aiService.retry(id, currentAiCaptures(claim), false);
} }
@Get("files/:publicId/review-referral")
getReviewReferral(@CurrentUser() insurer, @Param("publicId") publicId: string) {
return this.claimReviewReferralService.options(insurer.clientKey, publicId);
}
@Patch("files/:publicId/review-referral")
@UsePipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }))
@ApiBody({ type: ReferClaimReviewDto })
referClaimReview(
@CurrentUser() insurer,
@Param("publicId") publicId: string,
@Body() body: ReferClaimReviewDto,
) {
return this.claimReviewReferralService.refer(insurer, publicId, body);
}
@Get("files/:publicId") @Get("files/:publicId")
@ApiParam({ name: "publicId" }) @ApiParam({ name: "publicId" })
async getFileDetailsByPublicId(@CurrentUser() insurer, @Param("publicId") publicId: string) { async getFileDetailsByPublicId(@CurrentUser() insurer, @Param("publicId") publicId: string) {
+2 -1
View File
@@ -1,3 +1,4 @@
import { ClaimReviewReferralService } from "./claim-review-referral.service";
import { AiModule } from "src/ai/ai.module"; import { AiModule } from "src/ai/ai.module";
import { Module } from "@nestjs/common"; import { Module } from "@nestjs/common";
import { MongooseModule } from "@nestjs/mongoose"; import { MongooseModule } from "@nestjs/mongoose";
@@ -48,7 +49,7 @@ import { HashModule } from "src/utils/hash/hash.module";
}, },
]), ]),
], ],
providers: [ExpertInsurerService], providers: [ExpertInsurerService, ClaimReviewReferralService],
controllers: [ExpertInsurerController], controllers: [ExpertInsurerController],
exports: [ExpertInsurerService], exports: [ExpertInsurerService],
}) })
@@ -1,3 +1,4 @@
import { referralIneligibility } from "src/expert-claim/review-referral/review-referral";
import { fanavaranSignatureRevision } from "src/fanavaran/fanavaran-expert-signature"; import { fanavaranSignatureRevision } from "src/fanavaran/fanavaran-expert-signature";
import { personDisplayName, meaningfulPersonName } from "src/helpers/person-display-name"; import { personDisplayName, meaningfulPersonName } from "src/helpers/person-display-name";
import { import {
@@ -1921,6 +1922,11 @@ export class ExpertInsurerService {
? await this.buildInsurerClaimDetail(claimFull, blameForClaimContext) ? await this.buildInsurerClaimDetail(claimFull, blameForClaimContext)
: undefined; : undefined;
const reviewReferralAvailable = !!claimFull && !referralIneligibility(claimFull, blameForClaimContext);
const reviewBranch = claimFull?.reviewReferral && claimFull?.branchId
? await this.branchDbService.findById(String(claimFull.branchId))
: null;
const reportBlame = includeReportMedia const reportBlame = includeReportMedia
? blameDetails ?? (blameForClaimContext ? await this.buildInsurerBlameDetail(blameForClaimContext) : undefined) ? blameDetails ?? (blameForClaimContext ? await this.buildInsurerBlameDetail(blameForClaimContext) : undefined)
: undefined; : undefined;
@@ -1936,6 +1942,8 @@ export class ExpertInsurerService {
overview, overview,
blame: blameDetails, blame: blameDetails,
claim: claimDetails, claim: claimDetails,
reviewReferralAvailable,
reviewBranchName: reviewBranch?.name,
...(includeReportMedia ? { reportBlame } : {}), ...(includeReportMedia ? { reportBlame } : {}),
}; };
} }
@@ -1,3 +1,4 @@
import { CLAIM_REVIEW_REFERRED } from "src/expert-claim/review-referral/review-referral";
/** /**
* Persian (Farsi) display labels for every timeline event `type` that can * Persian (Farsi) display labels for every timeline event `type` that can
* appear in a blame or claim history array. * appear in a blame or claim history array.
@@ -104,6 +105,7 @@ export const EVENT_TYPE_FA_LABELS: Record<string, string> = {
CLAIM_CREATED: "پرونده خسارت ایجاد شد", CLAIM_CREATED: "پرونده خسارت ایجاد شد",
// Expert assignment (claim) // Expert assignment (claim)
[CLAIM_REVIEW_REFERRED]: "ارجاع ارزیابی خسارت",
CLAIM_ASSIGNED: "پرونده خسارت به کارشناس ارزیابی تخصیص داده شد", CLAIM_ASSIGNED: "پرونده خسارت به کارشناس ارزیابی تخصیص داده شد",
// Expert actions on claim // Expert actions on claim
@@ -263,6 +265,14 @@ export function getEventFaDescription(event: {
type: string; type: string;
metadata?: any; metadata?: any;
}): string { }): string {
if (event.type === CLAIM_REVIEW_REFERRED) {
const { previousExpertName, previousBranchName, expertName, branchName } = event.metadata ?? {};
const from = [previousExpertName, previousBranchName].filter(Boolean).join("، ");
const to = [expertName, branchName].filter(Boolean).join("، ");
if (to) return from
? `ارزیابی خسارت از ${from} به ${to} ارجاع شد.`
: `ارزیابی خسارت به ${to} ارجاع شد.`;
}
const stepKey: string | undefined = event.metadata?.stepKey; const stepKey: string | undefined = event.metadata?.stepKey;
if (stepKey && STEP_KEY_FA_DESCRIPTIONS[stepKey]) { if (stepKey && STEP_KEY_FA_DESCRIPTIONS[stepKey]) {
return STEP_KEY_FA_DESCRIPTIONS[stepKey]; return STEP_KEY_FA_DESCRIPTIONS[stepKey];
@@ -47,6 +47,7 @@ export function fanavaranSignatureRevision(claim: any): string {
snapshot, snapshot,
requiredDocuments, requiredDocuments,
media, media,
...(row.reviewReferral ? { reviewReferral: row.reviewReferral, branchId: row.branchId } : {}),
}), }),
) )
.digest("hex"); .digest("hex");
+2
View File
@@ -1,3 +1,4 @@
import { GuardClaimReview } from "src/expert-claim/review-referral/claim-review.interceptor";
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
import { import {
BadRequestException, BadRequestException,
@@ -33,6 +34,7 @@ import {
} from "src/core/config/fanavaran-client.config"; } from "src/core/config/fanavaran-client.config";
@ApiTags("fanavaran") @ApiTags("fanavaran")
@GuardClaimReview("integration")
@EnforceCaseWorkingHours() @EnforceCaseWorkingHours()
@Controller("v2/fanavaran") @Controller("v2/fanavaran")
@ApiBearerAuth() @ApiBearerAuth()
@@ -1,3 +1,4 @@
import { GuardClaimReview } from "src/expert-claim/review-referral/claim-review.interceptor";
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
import { Body, Controller, Param, Post, UseGuards } from "@nestjs/common"; import { Body, Controller, Param, Post, UseGuards } from "@nestjs/common";
import { import {
@@ -45,6 +46,7 @@ class FileMakerRejectDto {
* the claimRequestId from the original blame request ID. * the claimRequestId from the original blame request ID.
*/ */
@ApiTags("v5 FileMaker — claim approval before fanavaran") @ApiTags("v5 FileMaker — claim approval before fanavaran")
@GuardClaimReview("approval")
@EnforceCaseWorkingHours() @EnforceCaseWorkingHours()
@Controller("v5/file-maker/claim-approval") @Controller("v5/file-maker/claim-approval")
@ApiBearerAuth() @ApiBearerAuth()
@@ -21,6 +21,14 @@ export class DamageExpertDbService {
return await this.damageExpertModel.findOne(user); return await this.damageExpertModel.findOne(user);
} }
async findReviewCandidates(clientKey: string) {
return this.damageExpertModel.find({
clientKey,
isActive: { $ne: false },
branchId: { $ne: null },
}).select("firstName lastName branchId").sort({ firstName: 1, lastName: 1 }).lean().exec();
}
async findById(userId: string): Promise<DamageExpertModel> { async findById(userId: string): Promise<DamageExpertModel> {
return await this.damageExpertModel.findOne({ return await this.damageExpertModel.findOne({
_id: new Types.ObjectId(userId), _id: new Types.ObjectId(userId),
@@ -38,6 +38,14 @@ export class FieldExpertDbService {
return await this.fieldExpertModel.findOne({ $or: or }); return await this.fieldExpertModel.findOne({ $or: or });
} }
async findReviewCandidates(clientKey: string) {
return this.fieldExpertModel.find({
clientKey,
isActive: { $ne: false },
branchId: { $ne: null },
}).select("firstName lastName branchId").sort({ firstName: 1, lastName: 1 }).lean().exec();
}
async findById(userId: string): Promise<FieldExpertModel | null> { async findById(userId: string): Promise<FieldExpertModel | null> {
return await this.fieldExpertModel.findOne({ return await this.fieldExpertModel.findOne({
_id: new Types.ObjectId(userId), _id: new Types.ObjectId(userId),
@@ -38,6 +38,14 @@ export class FileReviewerDbService {
return await this.fileReviewerModel.findOne({ $or: or }); return await this.fileReviewerModel.findOne({ $or: or });
} }
async findReviewCandidates(clientKey: string) {
return this.fileReviewerModel.find({
clientKey,
isActive: { $ne: false },
branchId: { $ne: null },
}).select("firstName lastName branchId").sort({ firstName: 1, lastName: 1 }).lean().exec();
}
async findById(userId: string): Promise<FileReviewerModel | null> { async findById(userId: string): Promise<FileReviewerModel | null> {
return await this.fileReviewerModel.findOne({ return await this.fileReviewerModel.findOne({
_id: new Types.ObjectId(userId), _id: new Types.ObjectId(userId),
+236
View File
@@ -0,0 +1,236 @@
import { INestApplication } from "@nestjs/common";
import { APP_INTERCEPTOR } from "@nestjs/core";
import { JwtModule, JwtService } from "@nestjs/jwt";
import { Test } from "@nestjs/testing";
import { Types } from "mongoose";
import * as request from "supertest";
import { AiService } from "src/ai/ai.service";
import { ActorAuthService } from "src/auth/auth-services/actor.auth.service";
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
import { ExpertClaimService } from "src/expert-claim/expert-claim.service";
import { ExpertClaimV2Controller } from "src/expert-claim/expert-claim.v2.controller";
import { ClaimReviewInterceptor } from "src/expert-claim/review-referral/claim-review.interceptor";
import { ClaimReviewReferralService } from "src/expert-insurer/claim-review-referral.service";
import { ExpertInsurerController } from "src/expert-insurer/expert-insurer.controller";
import { ExpertInsurerService } from "src/expert-insurer/expert-insurer.service";
import { ReportsService } from "src/reports/reports.service";
const tenant = "650000000000000000000001";
const other = "650000000000000000000002";
const insurer = "650000000000000000000003";
const before = "650000000000000000000004";
const after = "650000000000000000000005";
const branch = "650000000000000000000006";
const priorBranch = "650000000000000000000007";
const claimId = "650000000000000000000008";
const blameId = "650000000000000000000009";
describe("insurer referral through HTTP", () => {
let app: INestApplication;
let jwt: JwtService;
const secretBefore = process.env.JWT_SECRET;
const secret = "local-referral-test-only";
const activeWrites = new Set<string>();
let claim: any;
const findClaim = async () => claim;
const repo = {
findOne: jest.fn(async (filter) =>
filter.publicId === claim.publicId &&
String(filter.$or[0]["owner.clientId"]) === tenant
? claim
: null,
),
findReviewAccess: findClaim,
acquireReviewWrite: jest.fn(async () => {
const marker = String(activeWrites.size + 1);
activeWrites.add(marker);
return async () => {
activeWrites.delete(marker);
};
}),
findOneAndUpdate: jest.fn(async (filter, update) => {
if (
activeWrites.size ||
filter.updatedAt !== claim.updatedAt ||
claim.claimId != null
)
return null;
claim = {
...claim,
branchId: update.$set.branchId,
reviewReferral: update.$set.reviewReferral,
updatedAt: new Date(claim.updatedAt.getTime() + 1),
history: [...claim.history, update.$push.history],
};
return claim;
}),
};
const staff = {
findById: async (id) =>
id === after
? {
_id: after,
clientKey: tenant,
branchId: branch,
firstName: "علی",
lastName: "کریمی",
}
: null,
findReviewCandidates: async () => [await staff.findById(after)],
};
const branches = {
findById: async (id) => ({
_id: id,
clientKey: tenant,
name: id === branch ? "کرج" : "تهران",
}),
findAll: async () =>
Promise.all([priorBranch, branch].map(branches.findById)),
};
const detail = jest.fn(async () => ({ claimRequestId: claimId }));
const reply = jest.fn(async () => ({ saved: true }));
beforeAll(async () => {
process.env.JWT_SECRET = secret;
const referrals = new ClaimReviewReferralService(
repo as any,
{
findById: async () => ({
status: "COMPLETED",
branchId: new Types.ObjectId(priorBranch),
}),
} as any,
branches as any,
staff as any,
{} as any,
{} as any,
);
const module = await Test.createTestingModule({
imports: [JwtModule.register({})],
controllers: [ExpertInsurerController, ExpertClaimV2Controller],
providers: [
{ provide: APP_INTERCEPTOR, useClass: ClaimReviewInterceptor },
{ provide: ClaimCaseDbService, useValue: repo },
{ provide: AiService, useValue: {} },
{
provide: ActorAuthService,
useValue: { assertActorActive: async () => {} },
},
{ provide: ClaimRequestManagementService, useValue: {} },
{
provide: ExpertClaimService,
useValue: { getClaimDetailV2: detail, submitExpertReplyV2: reply },
},
{ provide: ExpertInsurerService, useValue: {} },
{ provide: ClaimReviewReferralService, useValue: referrals },
{ provide: ReportsService, useValue: {} },
],
}).compile();
app = module.createNestApplication({ logger: false });
jwt = module.get(JwtService);
await app.init();
});
beforeEach(() => {
activeWrites.clear();
claim = {
_id: new Types.ObjectId(claimId),
publicId: "REF100",
owner: { clientId: tenant },
status: "EXPERT_REVIEWING",
blameRequestId: new Types.ObjectId(blameId),
branchId: new Types.ObjectId(priorBranch),
updatedAt: new Date(),
workflow: {
currentStep: "EXPERT_DAMAGE_ASSESSMENT",
assignedForReviewBy: { actorId: before, actorName: "کارشناس قبلی" },
},
history: [],
};
});
afterAll(async () => {
await app?.close();
if (secretBefore === undefined) delete process.env.JWT_SECRET;
else process.env.JWT_SECRET = secretBefore;
});
const referralUrl = "/expert-insurer/files/REF100/review-referral";
const reviewUrl = `/v2/expert-claim/request/${claimId}`;
const token = (sub, role, clientKey = tenant) =>
jwt.sign({ sub, role, clientKey }, { secret });
const authorize = (req, sub, role, clientKey = tenant) =>
req.auth(token(sub, role, clientKey), { type: "bearer" });
it("authorizes only the insurer, rejects a stale transfer, and switches review detail access", async () => {
const server = app.getHttpServer();
await authorize(
request(server).get(referralUrl),
before,
"damage_expert",
).expect(403);
await authorize(
request(server).get(referralUrl),
insurer,
"company",
other,
).expect(404);
const options = await authorize(
request(server).get(referralUrl),
insurer,
"company",
).expect(200);
const body = { expertId: after, revision: options.body.revision };
expect(options.body.candidates).toEqual([
expect.objectContaining({ id: after, branchId: branch }),
]);
await authorize(request(server).patch(referralUrl), insurer, "company")
.send({ ...body, branchId: priorBranch })
.expect(400);
activeWrites.add("review in progress");
await authorize(request(server).patch(referralUrl), insurer, "company")
.send(body)
.expect(409);
activeWrites.clear();
await authorize(request(server).patch(referralUrl), insurer, "company")
.send(body)
.expect(200);
await authorize(request(server).patch(referralUrl), insurer, "company")
.send(body)
.expect(409);
await authorize(
request(server).get(reviewUrl),
before,
"damage_expert",
).expect(403);
await authorize(
request(server).get(reviewUrl),
after,
"damage_expert",
other,
).expect(403);
await authorize(
request(server).get(reviewUrl),
after,
"damage_expert",
).expect(200);
await authorize(
request(server).put(`/v2/expert-claim/reply/submit/${claimId}`),
before,
"damage_expert",
)
.send({})
.expect(403);
expect(reply).not.toHaveBeenCalled();
expect(claim.history).toHaveLength(1);
expect(claim.history[0].metadata).toMatchObject({
previousBranchId: priorBranch,
branchId: branch,
previousExpertId: before,
expertId: after,
});
});
});
+24
View File
@@ -301,6 +301,18 @@
"company" "company"
] ]
}, },
{
"controller": "ExpertInsurerController",
"method": "GET",
"path": "/expert-insurer/files/:publicId/review-referral",
"guards": [
"LocalActorAuthGuard",
"RolesGuard"
],
"roles": [
"company"
]
},
{ {
"controller": "ExpertInsurerController", "controller": "ExpertInsurerController",
"method": "GET", "method": "GET",
@@ -2042,6 +2054,18 @@
"expert" "expert"
] ]
}, },
{
"controller": "ExpertInsurerController",
"method": "PATCH",
"path": "/expert-insurer/files/:publicId/review-referral",
"guards": [
"LocalActorAuthGuard",
"RolesGuard"
],
"roles": [
"company"
]
},
{ {
"controller": "InsurerManagementController", "controller": "InsurerManagementController",
"method": "PATCH", "method": "PATCH",