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, }); }); });