import { Types } from "mongoose"; import { canUserCreateClaim } from "src/helpers/blame-claim-eligibility"; import { RequestManagementService } from "./request-management.service"; import { WorkflowStep as Step } from "src/Types&Enums/blame-request-management/blameWorkflow-steps.enum"; import { BlameRequestType as Kind } from "src/Types&Enums/blame-request-management/blameRequestType.enum"; import { CaseStatus } from "src/Types&Enums/blame-request-management/caseStatus.enum"; import { BlameStatus } from "src/Types&Enums/blame-request-management/blameStatus.enum"; import { RoleEnum } from "src/Types&Enums/role.enum"; import { PartyRole } from "./entities/schema/partyRole.enum"; import { CreationMethod } from "./entities/schema/request-management.schema"; function setup(type = Kind.CAR_BODY) { const agent = { sub: String(new Types.ObjectId()), role: RoleEnum.CALL_CENTER, }; const first = { sub: String(new Types.ObjectId()), role: RoleEnum.USER, username: "09120000000", }; const second = { sub: String(new Types.ObjectId()), role: RoleEnum.USER, username: "09121111111", }; const req: any = { _id: new Types.ObjectId(), publicId: "V6-TEST", type, status: CaseStatus.OPEN, blameStatus: BlameStatus.UNKNOWN, callCenterInitiated: true, initiatedByCallCenterId: new Types.ObjectId(agent.sub), creationMethod: CreationMethod.LINK, parties: [{ role: PartyRole.FIRST, person: {} }], workflow: { currentStep: Step.CREATED, nextStep: type === Kind.CAR_BODY ? Step.CAR_BODY_ACCIDENT_TYPE : Step.FIRST_BLAME_CONFESSION, completedSteps: [Step.CREATED], }, history: [], save: jest.fn().mockResolvedValue(undefined), }; const service = new (RequestManagementService as any)() as RequestManagementService; const api = service as any; const chain = [ Step.CREATED, Step.FIRST_BLAME_CONFESSION, Step.FIRST_VIDEO, Step.FIRST_INITIAL_FORM, Step.FIRST_LOCATION, Step.FIRST_VOICE, Step.FIRST_DESCRIPTION, Step.FIRST_INVITE_SECOND, Step.SECOND_INITIAL_FORM, Step.SECOND_LOCATION, Step.SECOND_VOICE, Step.SECOND_DESCRIPTION, Step.WAITING_FOR_GUILT_DECISION, ]; const docs = chain.map((stepKey, i) => ({ stepKey, stepNumber: i + 1, nextPossibleSteps: chain[i + 1] ? [chain[i + 1]] : [], })); docs.push({ stepKey: Step.CAR_BODY_ACCIDENT_TYPE, stepNumber: 2, nextPossibleSteps: [Step.FIRST_VIDEO], }); const set = (key: string, value: any) => { const bits = key.split("."); let obj = req; for (const bit of bits.slice(0, -1)) obj = obj[bit] ??= {}; obj[bits[bits.length - 1]] = value; }; api.userClaimBranchService = { validate: jest.fn().mockResolvedValue("650000000000000000000099") }; api.publicIdService = { generateRequestPublicId: jest.fn().mockResolvedValue("V6-TEST"), }; api.blameRequestDbService = { create: jest.fn(async (body) => Object.assign(req, body)), findById: jest.fn().mockResolvedValue(req), findByIdAndUpdate: jest.fn(async (_id, update) => { for (const [key, value] of Object.entries(update.$set ?? {})) set(key, value); for (const [key, value] of Object.entries(update.$push ?? {})) { const old = key.split(".").reduce((obj, bit) => obj?.[bit], req) ?? []; set(key, [...old, value]); } return req; }), }; api.blameRequestDbService.findOneAndUpdate = jest.fn(async (filter, update) => { if (filter.status && req.status !== filter.status) return null; const pending = Object.keys(filter).find((key) => key.endsWith(".confirmation")); if (pending && pending.split(".").reduce((row, key) => row?.[key], req)) return null; await api.blameRequestDbService.findByIdAndUpdate(req._id, update); for (const [key, value] of Object.entries(update.$addToSet ?? {})) { const old = key.split(".").reduce((row, bit) => row?.[bit], req) ?? []; set(key, [...new Set([...old, value])]); } return req; }); api.workflowStepDbService = { findByStepNumber: jest.fn(async (n) => docs.find((d) => d.stepNumber === n), ), findByStepKey: jest.fn(async (key) => docs.find((d) => d.stepKey === key)), exists: jest.fn().mockResolvedValue(true), }; api.runPartyInquiriesV3Internal = jest.fn( async (_req, _dto, _role, party) => { party.person.clientId = new Types.ObjectId(); party.vehicle = { plateId: "12-ب-345-67" }; party.insurance = { policyNumber: "test-policy" }; }, ); api.runPartyInquiriesVinV3Internal = jest.fn( async (_req, _dto, _role, party) => { party.person.clientId = new Types.ObjectId(); party.vehicle = { vin: "TESTVIN00000000001" }; party.insurance = { policyNumber: "test-policy" }; }, ); api.getOrCreateUserByPhoneNumber = jest .fn() .mockResolvedValue(new Types.ObjectId(first.sub)); api.blameVideoDbService = { create: jest.fn().mockResolvedValue({ _id: new Types.ObjectId() }), }; api.blameVoiceDbService = { create: jest.fn().mockResolvedValue({ _id: new Types.ObjectId() }), }; api.userSign = { create: jest.fn().mockResolvedValue({ _id: new Types.ObjectId() }), }; api.userDbService = { findAllByPhone: jest.fn().mockResolvedValue([]) }; api.clientService = { findOne: jest.fn().mockResolvedValue({ clientCode: process.env.CLIENT_ID }), }; api.computeClaimCreationHintForViewer = jest .fn() .mockResolvedValue({ allowed: false }); api.sanitizePartyForBlameUserView = jest.fn(async (party) => party); api.buildExpertForBlameUserView = jest.fn(async (expert) => expert); api.assertCarBodyAccidentWithinWindow = jest .fn() .mockResolvedValue(undefined); api.smsOrchestrationService = { buildBlamePartyLink: jest.fn( (id, role, version) => `https://example.test/user/${version}/${role}?token=${id}`, ), buildInviteLink: jest.fn( (route, id, version) => `https://example.test/user/${version}/${route}?token=${id}`, ), sendFieldExpertLink: jest.fn().mockResolvedValue(true), sendInviteLink: jest.fn().mockResolvedValue(true), sendThirdPartyAgreementSignNotice: jest.fn().mockResolvedValue(true), sendThirdPartyDamagedPartyClaimLinkNotice: jest .fn() .mockResolvedValue(true), }; return { service, api, req, agent, first, second, id: String(req._id) }; } const media = { filename: "test.webm", path: "files/test.webm", } as Express.Multer.File; const completedInquiry = (req: any) => { req.parties[0].person.clientId = new Types.ObjectId(); req.history.push({ type: "CALL_CENTER_INQUIRY_COMPLETED", metadata: { partyRole: PartyRole.FIRST }, }); }; describe("V6 call-center workflow", () => { const originalUrl = process.env.URL; beforeEach(() => { process.env.URL = "https://example.test"; }); afterAll(() => { if (originalUrl === undefined) delete process.env.URL; else process.env.URL = originalUrl; }); it.each( [Kind.CAR_BODY, Kind.THIRD_PARTY].flatMap((type) => ["plate", "vin"].map((mode) => [type, mode]), ), )( "%s / %s: operator inquiry, link, login, required intro/video, narrative and signatures", async (type: Kind, mode) => { const { service, api, req, agent, first, second, id } = setup(type); await service.createCallCenterInitiatedBlameV6(agent, { type }); expect(req.callCenterInitiated).toBe(true); expect(req.workflow.completedSteps).not.toContain( Step.FIRST_INITIAL_FORM, ); if (mode === "plate") await service.runCallCenterInquiryV6(agent, id, {} as any); else await service.runCallCenterInquiryVinV6(agent, id, {} as any); expect(req.workflow.currentStep).toBe(Step.CREATED); expect(req.workflow.completedSteps).toContain(Step.FIRST_INITIAL_FORM); await service.sendCallCenterLinkV6(agent, id, { phoneNumber: first.username, }); const loggedIn = await service.getBlameRequestV2(id, first); expect(loggedIn.workflow.currentStep).toBe( type === Kind.CAR_BODY ? Step.CAR_BODY_ACCIDENT_TYPE : Step.FIRST_VIDEO, ); if (type === Kind.CAR_BODY) await service.carBodyAccidentTypeFormV2(id, { car: true }, first); expect(req.workflow.currentStep).toBe(Step.FIRST_VIDEO); expect(req.workflow.nextStep).toBe(Step.FIRST_LOCATION); await service.uploadFirstPartyVideoV2(id, media, first); expect(req.workflow.currentStep).toBe(Step.FIRST_LOCATION); const location = mode === "vin" ? { address: "تهران، خیابان آزادی، محل حادثه" } : { lat: 35, lon: 51 }; await service.addDetailLocationV2(id, location, first); expect(req.parties[0].location).toEqual(location); expect(req.workflow.currentStep).toBe(Step.FIRST_VOICE); await service.uploadVoiceV2(id, media, first); expect(req.workflow.currentStep).toBe(Step.FIRST_DESCRIPTION); const body: any = { desc: "شرح حادثه برای بررسی کارشناس ".repeat(6) }; if (type === Kind.CAR_BODY) Object.assign(body, { accidentDate: "1405/08/18", accidentTime: "12:00", weatherCondition: 1, roadCondition: 1, lightCondition: 1, }); await service.addDescriptionV2(id, body, first); if (type === Kind.THIRD_PARTY) { expect(req.workflow.currentStep).toBe(Step.FIRST_INVITE_SECOND); await service.addSecondPartyV2(id, second.username, "user2", first); expect(req.workflow.currentStep).toBe(Step.SECOND_INITIAL_FORM); expect( api.smsOrchestrationService.buildInviteLink, ).toHaveBeenLastCalledWith("user2", id, "v6"); // Second-party inquiry remains required; never consumed by first-party skip. expect(req.workflow.completedSteps).not.toContain( Step.SECOND_INITIAL_FORM, ); await expect( service.addDetailLocationV2(id, {} as any, second), ).rejects.toThrow(); // External second-party inquiry is independently required, then the standard narrative continues. req.parties[1].person.userId = new Types.ObjectId(second.sub); req.workflow.completedSteps.push(Step.SECOND_INITIAL_FORM); req.workflow.currentStep = Step.SECOND_LOCATION; req.workflow.nextStep = Step.SECOND_VOICE; await service.addDetailLocationV2( id, { address: "نشانی اعلام‌شده توسط طرف دوم حادثه" }, second, ); await service.uploadVoiceV2(id, media, second); await service.addDescriptionV2(id, { desc: body.desc }, second); expect( api.smsOrchestrationService.buildBlamePartyLink, ).toHaveBeenLastCalledWith(id, "SECOND", "v6"); } expect(req.workflow.currentStep).toBe(Step.WAITING_FOR_SIGNATURES); expect(req.status).toBe(CaseStatus.WAITING_FOR_SIGNATURES); expect(canUserCreateClaim(req, first.sub)).toBe(false); await service.userSignDecisionV2(id, first.sub, true, media); if (type === Kind.THIRD_PARTY) { expect(req.status).toBe(CaseStatus.WAITING_FOR_SIGNATURES); await service.userSignDecisionV2(id, second.sub, true, media); } expect(req.status).toBe(CaseStatus.COMPLETED); expect(canUserCreateClaim(req, first.sub)).toBe(type === Kind.CAR_BODY); if (type === Kind.THIRD_PARTY) expect(canUserCreateClaim(req, second.sub)).toBe(true); expect(req.workflow.currentStep).toBe(Step.COMPLETED); expect( api.smsOrchestrationService.buildBlamePartyLink, ).toHaveBeenLastCalledWith( id, type === Kind.CAR_BODY ? "FIRST" : "SECOND", "v6", ); await expect( service.userSignDecisionV2(id, first.sub, true, media), ).resolves.toMatchObject({ status: CaseStatus.COMPLETED }); }, ); it.each([Kind.CAR_BODY, Kind.THIRD_PARTY])( "repairs old %s on reopen, after access checks, and persists recovery", async (type) => { const { service, api, req, first, id } = setup(type); completedInquiry(req); req.parties[0].person.userId = new Types.ObjectId(first.sub); req.parties[0].evidence = { videoId: new Types.ObjectId() }; req.workflow.currentStep = Step.FIRST_INITIAL_FORM; req.workflow.nextStep = Step.FIRST_LOCATION; const view = await service.getBlameRequestV2(id, first); expect(view.workflow.currentStep).toBe(Step.FIRST_LOCATION); expect(view.workflow.nextStep).toBe(Step.FIRST_VOICE); expect(req.save).toHaveBeenCalled(); expect(api.runPartyInquiriesV3Internal).not.toHaveBeenCalled(); expect(api.runPartyInquiriesVinV3Internal).not.toHaveBeenCalled(); }, ); it("does not skip missing video during legacy recovery", () => { const { api, req } = setup(); completedInquiry(req); req.workflow.currentStep = Step.FIRST_INITIAL_FORM; api.reconcileCallCenterInquiryWorkflow(req); expect(req.workflow.currentStep).toBe(Step.FIRST_VIDEO); expect(req.workflow.nextStep).toBe(Step.FIRST_LOCATION); }); it.each([ Step.CREATED, Step.CAR_BODY_ACCIDENT_TYPE, Step.FIRST_LOCATION, Step.FIRST_VOICE, Step.FIRST_DESCRIPTION, Step.FIRST_INVITE_SECOND, Step.SECOND_INITIAL_FORM, Step.SECOND_LOCATION, Step.SECOND_VOICE, Step.SECOND_DESCRIPTION, Step.WAITING_FOR_SIGNATURES, Step.COMPLETED, ])("never rewinds %s when reopening", async (step) => { const { service, req, first, id } = setup(); completedInquiry(req); req.parties[0].person.userId = new Types.ObjectId(first.sub); req.workflow.currentStep = step; await service.getBlameRequestV2(id, first); expect(req.workflow.currentStep).toBe(step); }); it("failed inquiry with partially populated client does not permit sending a link", async () => { const { service, api, req, agent, first, id } = setup(); api.runPartyInquiriesV3Internal.mockImplementation(async () => { req.parties[0].person.clientId = new Types.ObjectId(); throw new Error("inquiry unavailable"); }); await expect( service.runCallCenterInquiryV6(agent, id, {} as any), ).rejects.toThrow("inquiry unavailable"); await expect( service.sendCallCenterLinkV6(agent, id, { phoneNumber: first.username }), ).rejects.toThrow(); expect(req.workflow.completedSteps).not.toContain(Step.FIRST_INITIAL_FORM); expect( api.smsOrchestrationService.sendFieldExpertLink, ).not.toHaveBeenCalled(); }); it("unauthorized users cannot trigger a repair", async () => { const { service, req, second, id } = setup(); completedInquiry(req); req.workflow.currentStep = Step.FIRST_INITIAL_FORM; await expect(service.getBlameRequestV2(id, second)).rejects.toThrow(); expect(req.workflow.currentStep).toBe(Step.FIRST_INITIAL_FORM); expect(req.save).not.toHaveBeenCalled(); }); it("does not skip inquiry for non-v6 files or mere skipInitialFormStep flags", () => { const { api, req } = setup(); req.skipInitialFormStep = true; expect(api.hasCompletedCallCenterInquiry(req)).toBe(false); completedInquiry(req); req.callCenterInitiated = false; expect(api.hasCompletedCallCenterInquiry(req)).toBe(false); }); it("repeated link sends do not rewind user progress", async () => { const { service, req, agent, first, id } = setup(); completedInquiry(req); req.workflow.currentStep = Step.FIRST_DESCRIPTION; await service.sendCallCenterLinkV6(agent, id, { phoneNumber: first.username, }); expect(req.workflow.currentStep).toBe(Step.FIRST_DESCRIPTION); }); it.each(["STOPPED", "CANCELLED", "COMPLETED"])( "does not repair or reopen a %s case", (status) => { const { api, req } = setup(); completedInquiry(req); req.status = status; req.workflow.currentStep = Step.FIRST_INITIAL_FORM; expect(api.reconcileCallCenterInquiryWorkflow(req)).toBe(false); expect(req.workflow.currentStep).toBe(Step.FIRST_INITIAL_FORM); }, ); it("another user cannot upload the caller's video", async () => { const { service, req, first, second, id } = setup(); completedInquiry(req); req.parties[0].person.userId = new Types.ObjectId(first.sub); req.workflow.currentStep = Step.FIRST_VIDEO; await expect( service.uploadFirstPartyVideoV2(id, media, second), ).rejects.toThrow(); expect(req.workflow.currentStep).toBe(Step.FIRST_VIDEO); }); it("signature rejection stops the car-body case without enabling completion", async () => { const { service, req, first, id } = setup(); req.parties[0].person.userId = new Types.ObjectId(first.sub); req.status = CaseStatus.WAITING_FOR_SIGNATURES; req.workflow.currentStep = Step.WAITING_FOR_SIGNATURES; const response = await service.userSignDecisionV2( id, first.sub, false, media, ); expect(response.status).toBe(CaseStatus.STOPPED); expect(req.status).toBe(CaseStatus.STOPPED); await expect( service.userSignDecisionV2(id, first.sub, true, media), ).rejects.toThrow(); }); it("call-center detail exposes completed inquiry and repaired workflow accurately", async () => { const { service, req, agent, id } = setup(); completedInquiry(req); req.workflow.currentStep = Step.FIRST_INITIAL_FORM; req.parties[0].evidence = { videoId: new Types.ObjectId() }; const detail = await service.getCallCenterBlameDetailV6(agent, id); expect(detail.parties[0].inquiryComplete).toBe(true); expect(detail.workflow.currentStep).toBe(Step.FIRST_LOCATION); }); it("a different operator cannot inquire or send the caller link", async () => { const { service, req, first, id } = setup(); const outsider = { sub: String(new Types.ObjectId()), role: RoleEnum.CALL_CENTER, }; await expect( service.runCallCenterInquiryV6(outsider, id, {} as any), ).rejects.toThrow(); completedInquiry(req); await expect( service.sendCallCenterLinkV6(outsider, id, { phoneNumber: first.username, }), ).rejects.toThrow(); }); it("locked cases are not repaired by a read", () => { const { api, req } = setup(); completedInquiry(req); req.workflow.locked = true; req.workflow.currentStep = Step.FIRST_INITIAL_FORM; expect(api.reconcileCallCenterInquiryWorkflow(req)).toBe(false); expect(req.workflow.currentStep).toBe(Step.FIRST_INITIAL_FORM); }); });