From 4e0e6f83dc7af251d71d458051ab7c10d9ce248e Mon Sep 17 00:00:00 2001 From: SepehrYahyaee <7heycallmegray@gmail.com> Date: Tue, 24 Nov 2026 15:16:14 +0330 Subject: [PATCH] feat(claims): add insurer review referrals --- docs/insurer-staff-management.md | 10 + src/ai/ai-access.spec.ts | 1 + src/app.module.ts | 2 + .../claim-request-management.service.ts | 49 +- .../db-service/claim-case.db.service.ts | 68 ++- .../entites/schema/claim-cases.schema.ts | 33 +- .../fanavaran-location-headers.spec.ts | 1 + .../fanavaran-submit-overrides.spec.ts | 13 +- src/expert-claim/expert-claim.service.ts | 99 +++- .../expert-claim.v2.controller.ts | 2 + .../fanavaran-stage-fields.spec.ts | 1 + .../fanavaran-vehicle-review.spec.ts | 4 +- .../claim-review.interceptor.ts | 81 +++ .../review-referral/review-referral.spec.ts | 519 ++++++++++++++++++ .../review-referral/review-referral.ts | 127 +++++ .../claim-review-referral.service.ts | 264 +++++++++ .../dto/refer-claim-review.dto.ts | 12 + .../expert-insurer.controller.ts | 22 + src/expert-insurer/expert-insurer.module.ts | 3 +- src/expert-insurer/expert-insurer.service.ts | 8 + .../helper/timeline-fa-labels.ts | 10 + src/fanavaran/fanavaran-expert-signature.ts | 1 + src/fanavaran/fanavaran.controller.ts | 2 + ...file-maker-claim-approval-v5.controller.ts | 2 + .../db-service/damage-expert.db.service.ts | 8 + .../db-service/field-expert.db.service.ts | 8 + .../db-service/file-reviewer.db.service.ts | 8 + test/claim-review-referral.e2e-spec.ts | 236 ++++++++ test/contracts/api-routes.json | 24 + 29 files changed, 1581 insertions(+), 37 deletions(-) create mode 100644 src/expert-claim/review-referral/claim-review.interceptor.ts create mode 100644 src/expert-claim/review-referral/review-referral.spec.ts create mode 100644 src/expert-claim/review-referral/review-referral.ts create mode 100644 src/expert-insurer/claim-review-referral.service.ts create mode 100644 src/expert-insurer/dto/refer-claim-review.dto.ts create mode 100644 test/claim-review-referral.e2e-spec.ts diff --git a/docs/insurer-staff-management.md b/docs/insurer-staff-management.md index d8abb86..a293f7c 100644 --- a/docs/insurer-staff-management.md +++ b/docs/insurer-staff-management.md @@ -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. +## 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 `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. diff --git a/src/ai/ai-access.spec.ts b/src/ai/ai-access.spec.ts index ccf7a8e..5734dee 100644 --- a/src/ai/ai-access.spec.ts +++ b/src/ai/ai-access.spec.ts @@ -41,6 +41,7 @@ describe("AI analysis file access", () => { service as any, {} as any, ai as any, + {} as any, db as any, ); await expect(controller[method](actor, "other-tenant")).rejects.toThrow( diff --git a/src/app.module.ts b/src/app.module.ts index f79acab..af093ba 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -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 { EvidenceAccessModule } from "./evidence-access/evidence-access.module"; 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_INTERCEPTOR, useClass: PersianErrorInterceptor }, { provide: APP_INTERCEPTOR, useClass: CaseWorkingHoursInterceptor }, + { provide: APP_INTERCEPTOR, useClass: ClaimReviewInterceptor }, { provide: APP_INTERCEPTOR, useClass: UnicodeDigitsNormalizeInterceptor, diff --git a/src/claim-request-management/claim-request-management.service.ts b/src/claim-request-management/claim-request-management.service.ts index 88d0b47..9db7070 100644 --- a/src/claim-request-management/claim-request-management.service.ts +++ b/src/claim-request-management/claim-request-management.service.ts @@ -1,3 +1,4 @@ +import { REVIEW_REFERRAL_DENIED } from 'src/expert-claim/review-referral/review-referral'; import { assertFanavaranExpertSignature, fanavaranSignatureRevision, @@ -395,6 +396,7 @@ const FANAVARAN_ATTACHMENT_FORMAT_WAIVE_PREFIX = 'FANAVARAN_ATTACHMENT_FORMAT_WAIVED:'; interface FanavaranClaimExpertContext { + reviewReferral?: { assigneeId?: unknown }; initiatedByFieldExpertId?: unknown; evaluation?: object; workflow?: { assignedForReviewBy?: { actorId?: unknown } }; @@ -3623,7 +3625,7 @@ export class ClaimRequestManagementService { return this.fanavaranLocationService.resolveBusinessLocation({ clientKey, requireStaffLocation: true, - staffCandidateIds: [ + staffCandidateIds: (claimCase.reviewReferral ? [claimCase.reviewReferral.assigneeId] : [ claimCase.initiatedByFieldExpertId, blame?.initiatedByFieldExpertId, this.fanavaranDamageReplyActorId(claimCase), @@ -3631,7 +3633,7 @@ export class ClaimRequestManagementService { blame?.assignedFileReviewerId, blame?.expert?.assignedExpertId, 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 = [ ...new Set( [ + claimCase?.reviewReferral?.assigneeId, blame.initiatedByFieldExpertId, blame.expert?.assignedExpertId, blame.expert?.decision?.decidedByExpertId, @@ -3870,7 +3873,7 @@ export class ClaimRequestManagementService { type?: BlameRequestType; assignedFileReviewerId?: unknown; }, - claimCase: { evaluation?: Record } | null | undefined, + claimCase: FanavaranClaimExpertContext | null | undefined, ): Promise<{ claimExpertId: number | null; code: string | null; @@ -3892,7 +3895,8 @@ export class ClaimRequestManagementService { } if (blame.isMadeByFileMaker) { - if (!blame.assignedFileReviewerId) { + const reviewerId = claimCase?.reviewReferral?.assigneeId ?? blame.assignedFileReviewerId; + if (!reviewerId) { return { claimExpertId: null, code: 'FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING', @@ -3901,7 +3905,7 @@ export class ClaimRequestManagementService { candidatesTried: [], }; } - const fileReviewerId = String(blame.assignedFileReviewerId); + const fileReviewerId = String(reviewerId); const fileReviewer = await this.fileReviewerDbService.findById(fileReviewerId); 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() === '') { return { claimExpertId: null, @@ -3977,7 +3981,7 @@ export class ClaimRequestManagementService { type?: BlameRequestType; assignedFileReviewerId?: unknown; }, - claimCase: { evaluation?: Record } | null | undefined, + claimCase: FanavaranClaimExpertContext | null | undefined, options?: { required?: boolean }, ): Promise { const resolved = await this.tryResolveFanavaranExpertiseClaimExpertId( @@ -8193,6 +8197,21 @@ export class ClaimRequestManagementService { clientKey: FanavaranClientKey, bodyOverride?: Record, auditSource: FanavaranAuditSource = FanavaranAuditSource.AUTO_SUBMIT, + ): Promise { + 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 | undefined, + auditSource: FanavaranAuditSource, ): Promise { const logPrefix = `[Fanavaran ${clientKey} V2]`; @@ -12044,6 +12063,9 @@ export class ClaimRequestManagementService { claimCase: any, blame: any, ): Promise { + if (claimCase.reviewReferral) { + throw new ForbiddenException(REVIEW_REFERRAL_DENIED); + } if ( claimCase.workflow?.currentStep === ClaimWorkflowStep.SELECT_OUTER_PARTS ) { @@ -12084,14 +12106,23 @@ export class ClaimRequestManagementService { ); } - await this.claimCaseDbService.findByIdAndUpdate(String(claimCase._id), { + const update = { $set: { status: ClaimCaseStatus.SELECTING_OUTER_PARTS, claimStatus: ClaimStatus.PENDING, 'workflow.currentStep': ClaimWorkflowStep.SELECT_OUTER_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) { diff --git a/src/claim-request-management/entites/db-service/claim-case.db.service.ts b/src/claim-request-management/entites/db-service/claim-case.db.service.ts index 2fed47f..ae20174 100644 --- a/src/claim-request-management/entites/db-service/claim-case.db.service.ts +++ b/src/claim-request-management/entites/db-service/claim-case.db.service.ts @@ -1,10 +1,12 @@ -import { Injectable } from "@nestjs/common"; +import { Injectable, Logger } from "@nestjs/common"; import { InjectModel } from "@nestjs/mongoose"; +import { randomUUID } from "node:crypto"; import { FilterQuery, Model, Types } from "mongoose"; import { ClaimCase, ClaimCaseDocument } from "../schema/claim-cases.schema"; @Injectable() export class ClaimCaseDbService { + private readonly logger = new Logger(ClaimCaseDbService.name); constructor( @InjectModel(ClaimCase.name) private readonly claimCaseModel: Model, @@ -20,6 +22,70 @@ export class ClaimCaseDbService { 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 = {}, + ) { + 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) { return this.claimCaseModel.findById(id).select("+fanavaranExpertSignature"); } diff --git a/src/claim-request-management/entites/schema/claim-cases.schema.ts b/src/claim-request-management/entites/schema/claim-cases.schema.ts index 47707a5..567c164 100644 --- a/src/claim-request-management/entites/schema/claim-cases.schema.ts +++ b/src/claim-request-management/entites/schema/claim-cases.schema.ts @@ -254,6 +254,29 @@ export const FanavaranVehicleReviewSchema = SchemaFactory.createForClass( 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({ collection: "claimCases", timestamps: true, @@ -261,6 +284,7 @@ export const FanavaranVehicleReviewSchema = SchemaFactory.createForClass( versionKey: false, }) export class ClaimCase { + updatedAt?: Date; @Prop({ required: true, unique: true, index: true, trim: true }) requestNo: string; @@ -312,7 +336,7 @@ export class ClaimCase { @Prop({ type: Types.ObjectId, index: true }) 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 }) branchId?: Types.ObjectId; @@ -324,6 +348,12 @@ export class ClaimCase { @Prop({ type: Types.ObjectId, index: true }) damagedPartyUserId?: Types.ObjectId; + @Prop({ type: ClaimReviewReferralSchema }) + reviewReferral?: ClaimReviewReferral; + + @Prop({ type: [ClaimReviewWriteSchema], select: false, default: undefined }) + reviewWrites?: ClaimReviewWrite[]; + @Prop({ type: ClaimWorkflowSchema, default: () => ({}) }) workflow?: ClaimWorkflow; @@ -444,3 +474,4 @@ export class ClaimCase { export type ClaimCaseDocument = HydratedDocument; export const ClaimCaseSchema = SchemaFactory.createForClass(ClaimCase); ClaimCaseSchema.index({ status: 1, "workflow.locked": 1 }); +ClaimCaseSchema.index({ "reviewReferral.assigneeId": 1 }, { sparse: true }); diff --git a/src/claim-request-management/fanavaran-location-headers.spec.ts b/src/claim-request-management/fanavaran-location-headers.spec.ts index 871549c..4cf36ba 100644 --- a/src/claim-request-management/fanavaran-location-headers.spec.ts +++ b/src/claim-request-management/fanavaran-location-headers.spec.ts @@ -121,6 +121,7 @@ describe("Fanavaran outgoing Location headers", () => { ? { locations: [{ id: "110011", name: "Claim branch" }] } : null, ); + management.claimCaseDbService.acquireReviewWrite = async () => async () => {}; management.assertFanavaranVehicleReviewApproved = jest.fn(); management.previewFanavaranSubmitV2 = jest.fn().mockResolvedValue({ PolicyId: 1, diff --git a/src/claim-request-management/fanavaran-submit-overrides.spec.ts b/src/claim-request-management/fanavaran-submit-overrides.spec.ts index 9fc3951..b008549 100644 --- a/src/claim-request-management/fanavaran-submit-overrides.spec.ts +++ b/src/claim-request-management/fanavaran-submit-overrides.spec.ts @@ -4,7 +4,18 @@ import { toFanavaranHullBaseClaimPayload } from "./fanavaran-hull-base-claim"; function setup(product = "car-body") { const service = Object.create(ClaimRequestManagementService.prototype) as any; 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.fanavaranAuthService = { assertNotInBackoff: jest.fn() }; service.previewFanavaranSubmitV2 = jest.fn().mockResolvedValue({ diff --git a/src/expert-claim/expert-claim.service.ts b/src/expert-claim/expert-claim.service.ts index 535373b..1b1e6e9 100644 --- a/src/expert-claim/expert-claim.service.ts +++ b/src/expert-claim/expert-claim.service.ts @@ -1,5 +1,12 @@ "use strict"; +import { + assertReferredReviewer, + isOriginalFileMaker, + isReferredReviewer, + reviewReferralActorFilter, +} from "./review-referral/review-referral"; + import { hasReviewedTejaratNotifier } from "src/fanavaran/tejarat-notifier"; import { resolveFanavaranClientKey } from "src/core/config/fanavaran-client.config"; @@ -322,6 +329,10 @@ export class ExpertClaimService { claim: any, actor: any, ): Promise { + if (claim.reviewReferral) { + assertReferredReviewer(claim, actor); + return; + } 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 @@ -400,6 +411,8 @@ export class ExpertClaimService { ? String((damageExpert as any).branchId) : undefined; if (!actorBranchId) { + const referred = claims.filter((claim) => isReferredReviewer(claim, actor)); + if (referred.length) return referred; throw new ForbiddenException( "DamageExpert account is not assigned to a branch.", ); @@ -450,6 +463,7 @@ export class ExpertClaimService { ); return claims.filter((claim) => { + if (claim.reviewReferral) return isReferredReviewer(claim, actor); let caseBranchId = claim?.branchId ? String(claim.branchId) : undefined; if (!caseBranchId && 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 // damage-expert path below; assertExpertActorOnClaim will verify // 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) { throw new BadRequestException({ success: false, @@ -1470,7 +1484,8 @@ export class ExpertClaimService { const isFieldExpertOwner = (actor as any).role === RoleEnum.FIELD_EXPERT && - (await this.fieldExpertOwnsClaim(claim, actor)); + (isReferredReviewer(claim, actor) || + (await this.fieldExpertOwnsClaim(claim, actor))); const isFactorValidationLock = claimIsAwaitingExpertFactorValidationV2(claim); const isDamageReviewLock = @@ -1485,6 +1500,7 @@ export class ExpertClaimService { claim.status === ClaimCaseStatus.CANCELLED; const isFieldExpertPortfolioLock = isFieldExpertOwner && + !claim.reviewReferral && !isTerminalClaim && !isDamageReviewLock && !isFactorValidationLock && @@ -1633,6 +1649,7 @@ export class ExpertClaimService { const assignFilter: Record = { _id: new Types.ObjectId(claimRequestId), + "reviewReferral.referredAt": claim.reviewReferral?.referredAt ?? null, $and: [ { $or: [ @@ -2488,11 +2505,17 @@ export class ExpertClaimService { async getStatusReportBucketsV2(actor: any): Promise> { if (actor.role === RoleEnum.FIELD_EXPERT) { const rows = (await this.claimCaseDbService.find( - { initiatedByFieldExpertId: new Types.ObjectId(actor.sub) }, + { + $or: [ + { initiatedByFieldExpertId: new Types.ObjectId(actor.sub) }, + reviewReferralActorFilter(actor), + ], + }, { lean: true }, )) as any[]; const buckets = initialClaimExpertReportBuckets(); for (const doc of rows) { + if (doc.reviewReferral && !isReferredReviewer(doc, actor)) continue; const key = claimCaseStatusToReportBucket(String(doc.status ?? "")); buckets.all++; buckets[key] = (buckets[key] ?? 0) + 1; @@ -2520,6 +2543,7 @@ export class ExpertClaimService { expertPortfolioFileIdsFromActivityEvents(activityEvents); const orClauses: Record[] = [ + reviewReferralActorFilter(actor), { "workflow.lockedBy.actorId": expertOid }, { "evaluation.damageExpertReply.actorDetail.actorId": expertOid }, { "evaluation.damageExpertReplyFinal.actorDetail.actorId": expertOid }, @@ -2544,7 +2568,9 @@ export class ExpertClaimService { const id = String(doc._id ?? ""); if (seen.has(id)) continue; if ( - !claimDocInExpertPortfolio(doc, expertId, activityFileIds, clientKey) + doc.reviewReferral && actor.role !== RoleEnum.FILE_MAKER + ? !isReferredReviewer(doc, actor) + : !claimDocInExpertPortfolio(doc, expertId, activityFileIds, clientKey) ) { continue; } @@ -2630,6 +2656,7 @@ export class ExpertClaimService { ) .then((docs) => docs.map((d) => (d as { _id: unknown })._id)); const claimOr: Record[] = [ + reviewReferralActorFilter(actor), { initiatedByFieldExpertId: expertOid, requiresFileMakerApproval: { $ne: true }, @@ -2638,7 +2665,8 @@ export class ExpertClaimService { if (expertBlameIds.length > 0) { 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 { const clientKey = requireActorClientKey(actor); const expertId = String(actor.sub); @@ -2651,6 +2679,7 @@ export class ExpertClaimService { const activityFileIds = expertPortfolioFileIdsFromActivityEvents(activityEvents); const orClauses: Record[] = [ + reviewReferralActorFilter(actor), { "workflow.lockedBy.actorId": expertOid }, { "evaluation.damageExpertReply.actorDetail.actorId": expertOid }, { "evaluation.damageExpertReplyFinal.actorDetail.actorId": expertOid }, @@ -2672,7 +2701,9 @@ export class ExpertClaimService { const id = String(doc._id ?? ""); if (seen.has(id)) continue; if ( - !claimDocInExpertPortfolio(doc, expertId, activityFileIds, clientKey) + doc.reviewReferral && actor.role !== RoleEnum.FILE_MAKER + ? !isReferredReviewer(doc, actor) + : !claimDocInExpertPortfolio(doc, expertId, activityFileIds, clientKey) ) { continue; } @@ -2866,6 +2897,7 @@ export class ExpertClaimService { // Post-filter: remove files that belong to another expert after reconciliation const finalFiltered = filtered.filter((c) => { + if (c.reviewReferral) return isReferredReviewer(c, actor); const assignedId = String(c.workflow?.assignedForReviewBy?.actorId ?? ""); const lockEnforced = c.workflow?.locked && this.isClaimV2WorkflowLockCurrentlyEnforced(c); @@ -2989,6 +3021,7 @@ export class ExpertClaimService { .then((docs) => docs.map((d) => (d as { _id: unknown })._id)); const claimOr: Record[] = [ + reviewReferralActorFilter(actor), // Direct claim link: exclude V5 claims that require FileMaker approval { initiatedByFieldExpertId: expertOid, @@ -3025,7 +3058,10 @@ export class ExpertClaimService { 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 blame = c.blameRequestId ? blameById.get(c.blameRequestId.toString()) @@ -3093,6 +3129,15 @@ export class ExpertClaimService { const clientKey = requireActorClientKey(actor); 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 const blames = (await this.blameRequestDbService.find( { @@ -3100,6 +3145,7 @@ export class ExpertClaimService { expertInitiated: true, creationMethod: "IN_PERSON", $or: [ + { _id: { $in: referredBlameIds } }, // Open: sealed by FileMaker, not yet taken by any reviewer { status: "WAITING_FOR_FILE_REVIEWER", @@ -3125,11 +3171,12 @@ export class ExpertClaimService { // Scope to this reviewer's insurer via blame party clientId const tenantScopedBlames = blames.filter((b) => - blameCaseTouchesClient(b, clientKey), + referredBlames.has(String(b._id)) || blameCaseTouchesClient(b, clientKey), ); const scopedBlames = ( await Promise.all( tenantScopedBlames.map(async (blame) => { + if (referredBlames.has(String(blame._id))) return blame; try { await this.fanavaranLocationService.assertMakerReviewerBranchCompatible( { @@ -3161,7 +3208,10 @@ export class ExpertClaimService { 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 ? blameById.get(c.blameRequestId.toString()) : undefined; @@ -3171,8 +3221,9 @@ export class ExpertClaimService { c.workflow?.locked && this.isClaimV2WorkflowLockCurrentlyEnforced(c) ); const assignedToMe = - blame?.assignedFileReviewerId && - String(blame.assignedFileReviewerId) === actor.sub; + c.reviewReferral + ? isReferredReviewer(c, actor) + : String(blame?.assignedFileReviewerId ?? "") === actor.sub; return { claimRequestId: c._id.toString(), publicId: c.publicId, @@ -3202,9 +3253,10 @@ export class ExpertClaimService { createdAt: c.createdAt, awaitingFactorValidation: claimIsAwaitingExpertFactorValidationV2(c), needsFileReviewerCompletion: - String(blame?.status ?? "") === "WAITING_FOR_FILE_REVIEWER" || - (!!blame?.isMadeByFileMaker && - String(blame?.status ?? "") === "WAITING_FOR_EXPERT"), + !c.reviewReferral && + (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, @@ -3602,10 +3654,9 @@ export class ExpertClaimService { "workflow.preLockQueueSnapshot": "", }; - const assigneeToPersist = claimWorkflowAssigneeToPersistOnLockExpiry( - claim.workflow, - claim, - ); + const assigneeToPersist = claim.reviewReferral + ? claim.workflow?.assignedForReviewBy + : claimWorkflowAssigneeToPersistOnLockExpiry(claim.workflow, claim); const expireLockSet: Record = { "workflow.locked": false }; if (assigneeToPersist) { expireLockSet["workflow.assignedForReviewBy"] = assigneeToPersist; @@ -3676,10 +3727,12 @@ export class ExpertClaimService { // 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); + if (!claim.reviewReferral) { + 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 const isDamageExpertPhase = @@ -3690,7 +3743,9 @@ export class ExpertClaimService { // 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) { + if (claim.reviewReferral) { + if (!isOriginalFileMaker(claim, actor)) assertReferredReviewer(claim, actor); + } else if (actor.role === RoleEnum.FILE_MAKER) { const isOwn = claimCaseInitiatedByFieldExpert(claim, actor, linkedBlame); if (!isOwn) { throw new ForbiddenException( diff --git a/src/expert-claim/expert-claim.v2.controller.ts b/src/expert-claim/expert-claim.v2.controller.ts index c4c09c2..34e5961 100644 --- a/src/expert-claim/expert-claim.v2.controller.ts +++ b/src/expert-claim/expert-claim.v2.controller.ts @@ -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 { AiPricingRequestDto } from "src/ai/ai-pricing-request.dto"; import { ValidationPipe } from "@nestjs/common"; @@ -69,6 +70,7 @@ class InPersonVisitV2Dto { } @ApiTags("expert-claim-panel (v2)") +@GuardClaimReview("review") @EnforceCaseWorkingHours() @Controller("v2/expert-claim") @ApiBearerAuth() diff --git a/src/expert-claim/fanavaran-stage-fields.spec.ts b/src/expert-claim/fanavaran-stage-fields.spec.ts index ce76de8..ad9bd34 100644 --- a/src/expert-claim/fanavaran-stage-fields.spec.ts +++ b/src/expert-claim/fanavaran-stage-fields.spec.ts @@ -734,6 +734,7 @@ describe("Expert Fanavaran stage fields", () => { }); management.logger = { log: jest.fn() }; management.claimCaseDbService = { + acquireReviewWrite: async () => async () => {}, findById: jest.fn().mockResolvedValue(claim), }; management.previewFanavaranSubmitV2 = jest.fn(); diff --git a/src/expert-claim/fanavaran-vehicle-review.spec.ts b/src/expert-claim/fanavaran-vehicle-review.spec.ts index 313992c..7eb9b3e 100644 --- a/src/expert-claim/fanavaran-vehicle-review.spec.ts +++ b/src/expert-claim/fanavaran-vehicle-review.spec.ts @@ -148,7 +148,7 @@ describe("Fanavaran vehicle review", () => { it("blocks a new manual base submission before building or posting its payload", async () => { const service = Object.create(ClaimRequestManagementService.prototype) as any; service.logger = { log: jest.fn() }; - service.claimCaseDbService = { findById: jest.fn().mockResolvedValue({}) }; + service.claimCaseDbService = { acquireReviewWrite: async () => async () => {}, findById: jest.fn().mockResolvedValue({}) }; service.previewFanavaranSubmitV2 = jest.fn(); await expect(service.executeFanavaranV2Submit("case", "moallem", { PolicyId: 1 })) .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 () => { const service = Object.create(ClaimRequestManagementService.prototype) as any; 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")) .resolves.toMatchObject({ Id: 12378660 }); }); diff --git a/src/expert-claim/review-referral/claim-review.interceptor.ts b/src/expert-claim/review-referral/claim-review.interceptor.ts new file mode 100644 index 0000000..4292f75 --- /dev/null +++ b/src/expert-claim/review-referral/claim-review.interceptor.ts @@ -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, [ + 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(); + } + }); + } +} diff --git a/src/expert-claim/review-referral/review-referral.spec.ts b/src/expert-claim/review-referral/review-referral.spec.ts new file mode 100644 index 0000000..e239708 --- /dev/null +++ b/src/expert-claim/review-referral/review-referral.spec.ts @@ -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([]); + }, + ); +}); diff --git a/src/expert-claim/review-referral/review-referral.ts b/src/expert-claim/review-referral/review-referral.ts new file mode 100644 index 0000000..9ffb02e --- /dev/null +++ b/src/expert-claim/review-referral/review-referral.ts @@ -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, + }; +} diff --git a/src/expert-insurer/claim-review-referral.service.ts b/src/expert-insurer/claim-review-referral.service.ts new file mode 100644 index 0000000..bb330ef --- /dev/null +++ b/src/expert-insurer/claim-review-referral.service.ts @@ -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 { + 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, + 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 }; + } +} diff --git a/src/expert-insurer/dto/refer-claim-review.dto.ts b/src/expert-insurer/dto/refer-claim-review.dto.ts new file mode 100644 index 0000000..d0af62d --- /dev/null +++ b/src/expert-insurer/dto/refer-claim-review.dto.ts @@ -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; +} diff --git a/src/expert-insurer/expert-insurer.controller.ts b/src/expert-insurer/expert-insurer.controller.ts index 4335790..12bfd78 100644 --- a/src/expert-insurer/expert-insurer.controller.ts +++ b/src/expert-insurer/expert-insurer.controller.ts @@ -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 { currentAiCaptures } from "src/ai/ai-captures"; import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service"; @@ -7,11 +9,14 @@ import { Controller, Get, Param, + Patch, Post, Put, Query, UnauthorizedException, UseGuards, + UsePipes, + ValidationPipe, } from "@nestjs/common"; import { ApiBearerAuth, @@ -62,6 +67,7 @@ export class ExpertInsurerController { private readonly expertInsurerService: ExpertInsurerService, private readonly reportsService: ReportsService, private readonly aiService: AiService, + private readonly claimReviewReferralService: ClaimReviewReferralService, private readonly claimCaseDbService: ClaimCaseDbService, ) {} @@ -428,6 +434,22 @@ export class ExpertInsurerController { 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") @ApiParam({ name: "publicId" }) async getFileDetailsByPublicId(@CurrentUser() insurer, @Param("publicId") publicId: string) { diff --git a/src/expert-insurer/expert-insurer.module.ts b/src/expert-insurer/expert-insurer.module.ts index 41ee9db..0e937a0 100644 --- a/src/expert-insurer/expert-insurer.module.ts +++ b/src/expert-insurer/expert-insurer.module.ts @@ -1,3 +1,4 @@ +import { ClaimReviewReferralService } from "./claim-review-referral.service"; import { AiModule } from "src/ai/ai.module"; import { Module } from "@nestjs/common"; import { MongooseModule } from "@nestjs/mongoose"; @@ -48,7 +49,7 @@ import { HashModule } from "src/utils/hash/hash.module"; }, ]), ], - providers: [ExpertInsurerService], + providers: [ExpertInsurerService, ClaimReviewReferralService], controllers: [ExpertInsurerController], exports: [ExpertInsurerService], }) diff --git a/src/expert-insurer/expert-insurer.service.ts b/src/expert-insurer/expert-insurer.service.ts index 55820f6..f2ff67a 100644 --- a/src/expert-insurer/expert-insurer.service.ts +++ b/src/expert-insurer/expert-insurer.service.ts @@ -1,3 +1,4 @@ +import { referralIneligibility } from "src/expert-claim/review-referral/review-referral"; import { fanavaranSignatureRevision } from "src/fanavaran/fanavaran-expert-signature"; import { personDisplayName, meaningfulPersonName } from "src/helpers/person-display-name"; import { @@ -1921,6 +1922,11 @@ export class ExpertInsurerService { ? await this.buildInsurerClaimDetail(claimFull, blameForClaimContext) : undefined; + const reviewReferralAvailable = !!claimFull && !referralIneligibility(claimFull, blameForClaimContext); + const reviewBranch = claimFull?.reviewReferral && claimFull?.branchId + ? await this.branchDbService.findById(String(claimFull.branchId)) + : null; + const reportBlame = includeReportMedia ? blameDetails ?? (blameForClaimContext ? await this.buildInsurerBlameDetail(blameForClaimContext) : undefined) : undefined; @@ -1936,6 +1942,8 @@ export class ExpertInsurerService { overview, blame: blameDetails, claim: claimDetails, + reviewReferralAvailable, + reviewBranchName: reviewBranch?.name, ...(includeReportMedia ? { reportBlame } : {}), }; } diff --git a/src/expert-insurer/helper/timeline-fa-labels.ts b/src/expert-insurer/helper/timeline-fa-labels.ts index c95cd0c..a3dbb3f 100644 --- a/src/expert-insurer/helper/timeline-fa-labels.ts +++ b/src/expert-insurer/helper/timeline-fa-labels.ts @@ -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 * appear in a blame or claim history array. @@ -104,6 +105,7 @@ export const EVENT_TYPE_FA_LABELS: Record = { CLAIM_CREATED: "پرونده خسارت ایجاد شد", // Expert assignment (claim) + [CLAIM_REVIEW_REFERRED]: "ارجاع ارزیابی خسارت", CLAIM_ASSIGNED: "پرونده خسارت به کارشناس ارزیابی تخصیص داده شد", // Expert actions on claim @@ -263,6 +265,14 @@ export function getEventFaDescription(event: { type: string; metadata?: any; }): 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; if (stepKey && STEP_KEY_FA_DESCRIPTIONS[stepKey]) { return STEP_KEY_FA_DESCRIPTIONS[stepKey]; diff --git a/src/fanavaran/fanavaran-expert-signature.ts b/src/fanavaran/fanavaran-expert-signature.ts index 01461ce..a633b5d 100644 --- a/src/fanavaran/fanavaran-expert-signature.ts +++ b/src/fanavaran/fanavaran-expert-signature.ts @@ -47,6 +47,7 @@ export function fanavaranSignatureRevision(claim: any): string { snapshot, requiredDocuments, media, + ...(row.reviewReferral ? { reviewReferral: row.reviewReferral, branchId: row.branchId } : {}), }), ) .digest("hex"); diff --git a/src/fanavaran/fanavaran.controller.ts b/src/fanavaran/fanavaran.controller.ts index f94b69d..2a1445a 100644 --- a/src/fanavaran/fanavaran.controller.ts +++ b/src/fanavaran/fanavaran.controller.ts @@ -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 { BadRequestException, @@ -33,6 +34,7 @@ import { } from "src/core/config/fanavaran-client.config"; @ApiTags("fanavaran") +@GuardClaimReview("integration") @EnforceCaseWorkingHours() @Controller("v2/fanavaran") @ApiBearerAuth() diff --git a/src/request-management/file-maker-claim-approval-v5.controller.ts b/src/request-management/file-maker-claim-approval-v5.controller.ts index 1574d79..a3da696 100644 --- a/src/request-management/file-maker-claim-approval-v5.controller.ts +++ b/src/request-management/file-maker-claim-approval-v5.controller.ts @@ -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 { Body, Controller, Param, Post, UseGuards } from "@nestjs/common"; import { @@ -45,6 +46,7 @@ class FileMakerRejectDto { * the claimRequestId from the original blame request ID. */ @ApiTags("v5 FileMaker — claim approval before fanavaran") +@GuardClaimReview("approval") @EnforceCaseWorkingHours() @Controller("v5/file-maker/claim-approval") @ApiBearerAuth() diff --git a/src/users/entities/db-service/damage-expert.db.service.ts b/src/users/entities/db-service/damage-expert.db.service.ts index cad909e..d2faa69 100644 --- a/src/users/entities/db-service/damage-expert.db.service.ts +++ b/src/users/entities/db-service/damage-expert.db.service.ts @@ -21,6 +21,14 @@ export class DamageExpertDbService { 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 { return await this.damageExpertModel.findOne({ _id: new Types.ObjectId(userId), diff --git a/src/users/entities/db-service/field-expert.db.service.ts b/src/users/entities/db-service/field-expert.db.service.ts index 237ff3a..5cc8e20 100644 --- a/src/users/entities/db-service/field-expert.db.service.ts +++ b/src/users/entities/db-service/field-expert.db.service.ts @@ -38,6 +38,14 @@ export class FieldExpertDbService { 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 { return await this.fieldExpertModel.findOne({ _id: new Types.ObjectId(userId), diff --git a/src/users/entities/db-service/file-reviewer.db.service.ts b/src/users/entities/db-service/file-reviewer.db.service.ts index 5cd1f59..d0f42d5 100644 --- a/src/users/entities/db-service/file-reviewer.db.service.ts +++ b/src/users/entities/db-service/file-reviewer.db.service.ts @@ -38,6 +38,14 @@ export class FileReviewerDbService { 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 { return await this.fileReviewerModel.findOne({ _id: new Types.ObjectId(userId), diff --git a/test/claim-review-referral.e2e-spec.ts b/test/claim-review-referral.e2e-spec.ts new file mode 100644 index 0000000..335acc4 --- /dev/null +++ b/test/claim-review-referral.e2e-spec.ts @@ -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(); + 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, + }); + }); +}); diff --git a/test/contracts/api-routes.json b/test/contracts/api-routes.json index 046f7d4..757277d 100644 --- a/test/contracts/api-routes.json +++ b/test/contracts/api-routes.json @@ -301,6 +301,18 @@ "company" ] }, + { + "controller": "ExpertInsurerController", + "method": "GET", + "path": "/expert-insurer/files/:publicId/review-referral", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, { "controller": "ExpertInsurerController", "method": "GET", @@ -2042,6 +2054,18 @@ "expert" ] }, + { + "controller": "ExpertInsurerController", + "method": "PATCH", + "path": "/expert-insurer/files/:publicId/review-referral", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, { "controller": "InsurerManagementController", "method": "PATCH",