import { BadRequestException, ConflictException, NotFoundException, ValidationPipe, } from "@nestjs/common"; import { model, Types } from "mongoose"; import { ManagementService } from "./management.service"; import { InsurerManagementController } from "./management.controller"; import { STAFF_ROLES, CreateManagedStaffDto, UpdateManagedStaffDto, CreateManagedAccountDto, CreateManagedClientDto, UpdateManagedBranchDto, } from "./management.dto"; import { ClientDbSchema } from "src/client/entities/schema/client.schema"; import { BranchSchema } from "src/client/entities/schema/branch.schema"; import { ExpertDbSchema } from "src/users/entities/schema/expert.schema"; import { DamageExpertDbSchema } from "src/users/entities/schema/damage-expert.schema"; import { FieldExpertDbSchema } from "src/users/entities/schema/field-expert.schema"; import { FileMakerDbSchema } from "src/users/entities/schema/file-maker.schema"; import { FileReviewerDbSchema } from "src/users/entities/schema/file-reviewer.schema"; import { CallCenterAgentDbSchema } from "src/users/entities/schema/call-center-agent.schema"; import { InsurerExpertDbSchema } from "src/users/entities/schema/insurer-expert.schema"; const tenant = "aaaaaaaaaaaaaaaaaaaaaaaa"; const foreign = "bbbbbbbbbbbbbbbbbbbbbbbb"; const branchId = "cccccccccccccccccccccccc"; const mongoModels = [ ClientDbSchema, BranchSchema, ExpertDbSchema, DamageExpertDbSchema, FieldExpertDbSchema, FileMakerDbSchema, FileReviewerDbSchema, CallCenterAgentDbSchema, InsurerExpertDbSchema, ].map((schema, index) => model(`ManagementTest${index}`, schema)); const same = (a: any, b: any) => String(a) === String(b); function matches(record: any, filter: any): boolean { return Object.entries(filter).every(([key, value]: [string, any]) => { if (key === "$or") return value.some((clause: any) => matches(record, clause)); const actual = key.split(".").reduce((o, k) => o?.[k], record); if (value?.$in) return value.$in.some((item: any) => same(actual, item)); if (value?.$ne) return !same(actual, value.$ne); return same(actual, value); }); } function repository(index: number) { const records: any[] = []; const query = (fn: () => any) => ({ lean: async () => fn(), sort: () => query(fn), }); const persist = async (body: any) => { const doc = new mongoModels[index](body); await doc.validate(); return doc.toObject(); }; const repo = { records, findOne: jest.fn((filter) => query(() => records.find((row) => matches(row, filter)) ?? null), ), find: jest.fn((filter) => query(() => records.filter((row) => matches(row, filter))), ), create: jest.fn(async (body) => { const doc = await persist(body); records.push(doc); return doc; }), findOneAndUpdate: jest.fn((filter, update) => ({ lean: async () => { const i = records.findIndex((row) => matches(row, filter)); if (i < 0) return null; const copy = { ...records[i], ...update.$set }; for (const key of Object.keys(update.$unset ?? {})) delete copy[key]; records[i] = await persist(copy); return records[i]; }, })), }; return repo; } describe("management accounts, optional Fanavaran fields and tenant boundaries", () => { let repos: ReturnType[], service: ManagementService, hash: { hash: jest.Mock }; const staff = (role: any, extra: any = {}) => ({ role, firstName: "علی", lastName: "احمدی", nationalCode: "0012345678", email: "expert@example.com", mobile: "09123456789", password: "secret123", ...extra, }); beforeEach(() => { repos = mongoModels.map((_, i) => repository(i)); repos[0].records.push( { _id: new Types.ObjectId(tenant), clientName: { persian: "بیمه اول", english: "first" }, clientCode: 1, useExpertMode: "legal", }, { _id: new Types.ObjectId(foreign), clientName: { persian: "بیمه دوم", english: "second" }, clientCode: 2, useExpertMode: "legal", }, ); repos[1].records.push({ _id: new Types.ObjectId(branchId), clientKey: new Types.ObjectId(tenant), name: "تهران", code: "10", city: "تهران", state: "تهران", address: "نشانی", }); hash = { hash: jest.fn(async (text) => `hashed:${text}`) }; service = new ManagementService( ...([...repos, hash] as any as ConstructorParameters< typeof ManagementService >), ); }); it.each(STAFF_ROLES)( "creates a usable %s account with hashed credentials and optional branch", async (role) => { const saved = await service.createStaff(tenant, staff(role)); const stored = repos[2 + STAFF_ROLES.indexOf(role)].records[0]; expect(stored.role).toBe(role); expect(String(stored.clientKey)).toBe(tenant); expect(stored.password).toBe("hashed:secret123"); expect(saved).not.toHaveProperty("password"); expect(stored.branchId).toBeUndefined(); }, ); it.each(["field_expert", "file_maker", "file_reviewer", "call_center"])( "supports seed-style %s identity without email or mobile", async (role) => { const body = staff(role); delete body.email; delete body.mobile; const saved = await service.createStaff(tenant, body); const stored = repos[2 + STAFF_ROLES.indexOf(role as any)].records[0]; expect(saved.nationalCode).toBe(body.nationalCode); expect(stored.username).toBe(body.nationalCode); }, ); it.each(["expert", "damage_expert"])( "requires email and mobile for %s", async (role) => { await expect( service.createStaff(tenant, staff(role, { email: null })), ).rejects.toBeInstanceOf(BadRequestException); await expect( service.createStaff(tenant, staff(role, { mobile: null })), ).rejects.toBeInstanceOf(BadRequestException); }, ); it.each([ ["file_maker", "ThirdPartyClaimExpertId", "CarBodyClaimExpertId"], ["file_reviewer", "ThirdPartyExpertiseClaim", "CarBodyExpertiseClaim"], ])( "persists and edits %s Fanavaran IDs and locations using the real schemas", async (role, first, second) => { const row = await service.createStaff( tenant, staff(role, { [first]: "100", [second]: "200", expertCode: "12", locations: [{ id: "1", name: "تهران" }], branchId, }), ); expect(row[first]).toBe("100"); expect(row[second]).toBe("200"); const edited = await service.updateStaff(tenant, role, String(row._id), { [first]: "300", [second]: null, locations: [{ id: "2", name: "اصفهان" }], city: "اصفهان", expertCode: "13", }); expect(edited[first]).toBe("300"); expect(edited[second]).toBeUndefined(); expect(edited.locations).toMatchObject([{ id: "2", name: "اصفهان" }]); expect(edited.city).toBe("اصفهان"); expect(edited.expertCode).toBe("13"); const cleared = await service.updateStaff(tenant, role, String(row._id), { locations: [], branchId: null, }); expect(cleared.locations).toEqual([]); expect(cleared.branchId).toBeUndefined(); }, ); it.each(["expert", "damage_expert", "field_expert"])( "creates, lists, edits and clears all four Fanavaran codes for %s using its real schema", async (role) => { const codes = { ThirdPartyClaimExpertId: "101", CarBodyClaimExpertId: "102", ThirdPartyExpertiseClaim: "201", CarBodyExpertiseClaim: "202", }; const created = await service.createStaff(tenant, staff(role, codes)); expect(created).toMatchObject(codes); expect( repos[2 + STAFF_ROLES.indexOf(role as any)].records[0], ).toMatchObject(codes); const listed = await service.listStaff(tenant, { role: role as any }); expect(listed.list[0]).toMatchObject(codes); const changed = Object.fromEntries( Object.keys(codes).map((key, index) => [key, String(301 + index)]), ); const updated = await service.updateStaff( tenant, role, String(created._id), changed, ); expect(updated).toMatchObject(changed); expect(updated).not.toHaveProperty("password"); const cleared = await service.updateStaff( tenant, role, String(created._id), Object.fromEntries(Object.keys(codes).map((key) => [key, null])), ); for (const key of Object.keys(codes)) expect(cleared).not.toHaveProperty(key); }, ); it.each([ ["file_maker", "ThirdPartyExpertiseClaim"], ["file_maker", "CarBodyExpertiseClaim"], ["file_reviewer", "ThirdPartyClaimExpertId"], ["file_reviewer", "CarBodyClaimExpertId"], ...[ "ThirdPartyClaimExpertId", "CarBodyClaimExpertId", "ThirdPartyExpertiseClaim", "CarBodyExpertiseClaim", ].map((key) => ["call_center", key]), ])("rejects %s field %s on create and edit", async (role, key) => { await expect( service.createStaff(tenant, staff(role, { [key]: "100" })), ).rejects.toBeInstanceOf(BadRequestException); const created = await service.createStaff(tenant, staff(role)); await expect( service.updateStaff(tenant, role, String(created._id), { [key]: "100" }), ).rejects.toBeInstanceOf(BadRequestException); expect( repos[2 + STAFF_ROLES.indexOf(role as any)].records[0], ).not.toHaveProperty(key); }); it("never updates a staff member from a different tenant", async () => { const row = await service.createStaff(foreign, staff("file_maker")); await expect( service.updateStaff(tenant, "file_maker", String(row._id), { firstName: "Changed", }), ).rejects.toBeInstanceOf(NotFoundException); expect(repos[5].records[0].firstName).toBe("علی"); expect(repos[5].findOneAndUpdate).not.toHaveBeenCalled(); }); it("keeps the tenant predicate on the final atomic update", async () => { const row = await service.createStaff(tenant, staff("file_maker")); await service.updateStaff(tenant, "file_maker", String(row._id), { firstName: "رضا", }); expect( repos[5].findOneAndUpdate.mock.calls[0][0].clientKey.$in.map(String), ).toEqual([tenant, tenant]); }); it("rejects foreign-tenant branch assignment on both create and edit", async () => { await expect( service.createStaff(foreign, staff("file_maker", { branchId })), ).rejects.toBeInstanceOf(BadRequestException); const row = await service.createStaff(foreign, staff("file_maker")); await expect( service.updateStaff(foreign, "file_maker", String(row._id), { branchId }), ).rejects.toBeInstanceOf(BadRequestException); }); it.each([ { role: "company" }, { clientKey: foreign }, { isApproved: true }, { $set: { role: "super_admin" } }, ])("rejects protected update fields %j", async (body) => { const row = await service.createStaff(tenant, staff("file_maker")); await expect( service.updateStaff(tenant, "file_maker", String(row._id), body), ).rejects.toBeInstanceOf(BadRequestException); }); it("rejects Fanavaran fields for the wrong role and malformed IDs", async () => { await expect( service.createStaff( tenant, staff("file_maker", { ThirdPartyExpertiseClaim: "12" }), ), ).rejects.toBeInstanceOf(BadRequestException); for (const expertCode of ["0", "-1", "1.2", "9007199254740992", "abc"]) { await expect( service.createStaff(tenant, staff("file_maker", { expertCode })), ).rejects.toBeInstanceOf(BadRequestException); } await expect( service.createStaff( tenant, staff("file_maker", { locations: [ { id: "1", name: "A" }, { id: "1", name: "B" }, ], }), ), ).rejects.toBeInstanceOf(BadRequestException); }); it("rejects ambiguous login aliases without mutating an existing account", async () => { await service.createStaff(tenant, staff("file_maker")); await expect( service.createStaff( foreign, staff("file_reviewer", { email: "different@example.com" }), ), ).rejects.toBeInstanceOf(ConflictException); }); it("keeps the password unchanged unless a replacement is supplied", async () => { const row = await service.createStaff(tenant, staff("field_expert")); await service.updateStaff(tenant, "field_expert", String(row._id), { city: "تهران", }); expect(hash.hash).toHaveBeenCalledTimes(1); await service.updateStaff(tenant, "field_expert", String(row._id), { password: "replacement", }); expect(repos[4].records[0].password).toBe("hashed:replacement"); }); it("lists only the selected tenant and strips credentials, OTP and arbitrary fields", async () => { const row = await service.createStaff(tenant, staff("file_maker")); repos[5].records[0].otp = "sensitive"; repos[5].records[0].access_token = "sensitive"; await service.createStaff( foreign, staff("file_reviewer", { nationalCode: "0023456789", email: "other@example.com", }), ); const result = await service.listStaff(tenant, { search: "احمدی", limit: 1, }); expect(result.total).toBe(1); expect(result.list[0]._id).toEqual(row._id); expect(result.list[0]).not.toHaveProperty("otp"); expect(result.list[0]).not.toHaveProperty("password"); expect(result.list[0]).not.toHaveProperty("access_token"); }); it("creates insurer logins as COMPANY and prevents using the staff route for COMPANY", async () => { const { role, nationalCode, ...body } = staff("company"); const row = await service.createStaff(tenant, body, true); expect(row.role).toBe("company"); expect(repos[8].records[0].email).toBe(body.email); await expect( service.createStaff(tenant, staff("company")), ).rejects.toBeInstanceOf(BadRequestException); await expect( service.updateStaff( foreign, "company", String(row._id), { firstName: "Other" }, true, ), ).rejects.toBeInstanceOf(NotFoundException); }); it("creates and edits branch optional fields, false active status and preserves tenant", async () => { const row = await service.saveBranch(tenant, { code: "20", name: "شعبه", fullName: "نام کامل شعبه", city: "تهران", state: "تهران", address: "نشانی", phoneNumber: "02112345678", isActive: false, }); expect(row.fullName).toBe("نام کامل شعبه"); expect(row.isActive).toBe(false); const edited = await service.saveBranch( tenant, { fullName: "نام جدید", phoneNumber: "02188888888", isActive: true }, String(row._id), ); expect(edited.fullName).toBe("نام جدید"); expect(edited.phoneNumber).toBe("02188888888"); expect(String(edited.clientKey)).toBe(tenant); await expect( service.saveBranch(foreign, { name: "Wrong" }, String(row._id)), ).rejects.toBeInstanceOf(NotFoundException); }); it("rejects duplicate branch codes and clearing required fields", async () => { await expect( service.saveBranch(tenant, { code: "10", name: "Name", city: "A", state: "B", address: "C", }), ).rejects.toBeInstanceOf(ConflictException); for (const body of [{ name: null }, { code: " " }, { isActive: null }, {}]) await expect( service.saveBranch(tenant, body, branchId), ).rejects.toBeInstanceOf(BadRequestException); }); it("creates safe client metadata and preserves existing settings on edits", async () => { const row = await service.saveClient({ clientName: { persian: "بیمه جدید", english: "NEW" }, clientCode: 3, useExpertMode: "legal", }); expect(row.clientName.english).toBe("NEW"); const stored = repos[0].records.find((r) => same(r._id, row._id)); stored.settings = { carBodyAccidentMaxAgeDays: 10 }; stored.property = { smsApiKey: "sensitive" }; const edited = await service.saveClient( { clientName: { persian: "نام تازه", english: "NEW" } }, String(row._id), ); expect(edited).not.toHaveProperty("property"); expect(stored.settings.carBodyAccidentMaxAgeDays).toBe(10); const listed = await service.listClients(); expect(listed.clients.find((r) => same(r._id, row._id))).not.toHaveProperty( "property", ); await expect( service.saveClient({ clientName: { persian: "بیمه دیگر", english: "other" }, clientCode: 3, useExpertMode: "legal", }), ).rejects.toBeInstanceOf(ConflictException); }); it("rejects invalid or missing tenant identifiers before writes", async () => { await expect(service.listStaff("wrong")).rejects.toBeInstanceOf( BadRequestException, ); await expect( service.createStaff("dddddddddddddddddddddddd", staff("file_maker")), ).rejects.toBeInstanceOf(NotFoundException); }); it("always uses authenticated insurer scope, even if query requests a foreign tenant", async () => { const mocked = { listStaff: jest.fn(), createStaff: jest.fn(), updateStaff: jest.fn(), listBranches: jest.fn(), saveBranch: jest.fn(), }; const controller = new InsurerManagementController(mocked as any); const actor = { clientKey: tenant }; controller.staff(actor, { clientId: foreign }); controller.createStaff(actor, staff("file_maker")); controller.updateStaff(actor, "file_maker", branchId, {}); controller.branches(actor); controller.createBranch(actor, {} as any); controller.updateBranch(actor, branchId, {}); for (const method of Object.values(mocked)) expect(method.mock.calls[0][0]).toBe(tenant); }); }); describe("strict management DTO validation", () => { const pipe = new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true, }); const validate = (metatype: any, body: any) => pipe.transform(body, { type: "body", metatype }); it("accepts optional seed properties without email, mobile or branch", async () => { const body = { role: "file_maker", firstName: " علی ", lastName: "احمدی", nationalCode: "0012345678", password: "secret123", ThirdPartyClaimExpertId: "100", CarBodyClaimExpertId: "200", locations: [{ id: "1", name: "تهران" }], }; const dto = await validate(CreateManagedStaffDto, body); expect(dto.firstName).toBe("علی"); expect(dto.ThirdPartyClaimExpertId).toBe("100"); }); it.each([ { role: "company" }, { clientKey: foreign }, { locations: [{ id: "1", name: "A", admin: true }] }, ])("rejects hidden privilege or nested properties: %j", async (extra) => { await expect( validate(CreateManagedStaffDto, { role: "file_maker", firstName: "A", lastName: "B", nationalCode: "0012345678", password: "secret123", ...extra, }), ).rejects.toBeInstanceOf(BadRequestException); }); it("supports explicit optional clear while protecting role on edits", async () => { const dto = await validate(UpdateManagedStaffDto, { ThirdPartyClaimExpertId: " ", branchId: null, locations: [], }); expect(dto.ThirdPartyClaimExpertId).toBeNull(); expect(dto.locations).toEqual([]); await expect( validate(UpdateManagedStaffDto, { role: "super_admin" }), ).rejects.toBeInstanceOf(BadRequestException); }); it("limits company-account fields and validates branch booleans and client codes", async () => { await expect( validate(CreateManagedAccountDto, { firstName: "A", lastName: "B", email: "test@example.com", password: "secret123", role: "super_admin", }), ).rejects.toBeInstanceOf(BadRequestException); await expect( validate(UpdateManagedBranchDto, { isActive: "false" }), ).rejects.toBeInstanceOf(BadRequestException); await expect( validate(CreateManagedClientDto, { clientName: { persian: "A", english: "A" }, clientCode: 1.5, useExpertMode: "legal", }), ).rejects.toBeInstanceOf(BadRequestException); }); });