import { BadRequestException, ConflictException, Injectable, NotFoundException, } from "@nestjs/common"; import { InjectModel } from "@nestjs/mongoose"; import { Model, Types } from "mongoose"; import { ClientModel } from "src/client/entities/schema/client.schema"; import { BranchModel } from "src/client/entities/schema/branch.schema"; import { ExpertModel } from "src/users/entities/schema/expert.schema"; import { DamageExpertModel } from "src/users/entities/schema/damage-expert.schema"; import { FieldExpertModel } from "src/users/entities/schema/field-expert.schema"; import { FileMakerModel } from "src/users/entities/schema/file-maker.schema"; import { FileReviewerModel } from "src/users/entities/schema/file-reviewer.schema"; import { CallCenterAgentModel } from "src/users/entities/schema/call-center-agent.schema"; import { InsurerExpertModel } from "src/users/entities/schema/insurer-expert.schema"; import { HashService } from "src/utils/hash/hash.service"; import { UserType } from "src/Types&Enums/userType.enum"; import { RoleEnum } from "src/Types&Enums/role.enum"; import { STAFF_ROLES, StaffRole, CreateManagedStaffDto, CreateManagedClientDto, ManagedListQueryDto, } from "./management.dto"; const STAFF_FIELDS = [ "firstName", "lastName", "nationalCode", "email", "mobile", "branchId", "phone", "city", "state", "address", "expertCode", "locations", "ThirdPartyClaimExpertId", "CarBodyClaimExpertId", "ThirdPartyExpertiseClaim", "CarBodyExpertiseClaim", ]; const BRANCH_FIELDS = [ "name", "fullName", "code", "city", "state", "address", "phoneNumber", "isActive", "activityStartDate", ]; const FAN_IDS = [ "expertCode", "ThirdPartyClaimExpertId", "CarBodyClaimExpertId", "ThirdPartyExpertiseClaim", "CarBodyExpertiseClaim", ]; @Injectable() export class ManagementService { constructor( @InjectModel(ClientModel.name) private clients: Model, @InjectModel(BranchModel.name) private branches: Model, @InjectModel(ExpertModel.name) private blame: Model, @InjectModel(DamageExpertModel.name) private claim: Model, @InjectModel(FieldExpertModel.name) private field: Model, @InjectModel(FileMakerModel.name) private maker: Model, @InjectModel(FileReviewerModel.name) private reviewer: Model, @InjectModel(CallCenterAgentModel.name) private callCenter: Model, @InjectModel(InsurerExpertModel.name) private company: Model, private hash: HashService, ) {} private objectId(id: string) { if (!id || !/^[a-f\d]{24}$/i.test(String(id))) throw new BadRequestException("Invalid identifier"); return new Types.ObjectId(id); } private async client(id: string) { const key = this.objectId(id); const record = await this.clients.findOne({ _id: key }).lean(); if (!record) throw new NotFoundException("Insurance company not found"); return key; } private repository(role: string): Model { const repositories = { [RoleEnum.EXPERT]: this.blame, [RoleEnum.DAMAGE_EXPERT]: this.claim, [RoleEnum.FIELD_EXPERT]: this.field, [RoleEnum.FILE_MAKER]: this.maker, [RoleEnum.FILE_REVIEWER]: this.reviewer, [RoleEnum.CALL_CENTER]: this.callCenter, [RoleEnum.COMPANY]: this.company, }; const model = repositories[role]; if (!model) throw new BadRequestException("Unsupported staff role"); return model; } private scope(key: Types.ObjectId) { return { clientKey: { $in: [key, String(key)] } }; } private pick(record: any, fields: string[]): Record { const source = record?.toObject ? record.toObject() : record; return Object.fromEntries( ["_id", "role", "clientKey", "createdAt", ...fields] .filter((k) => source?.[k] !== undefined) .map((k) => [k, source[k]]), ); } private async uniqueLogin(role: string, values: any, ownId?: string) { // The selected role already disambiguates cross-role identities. There is // no tenant selector, so aliases must remain unique within each role. const filters: any[] = []; if (values.email) filters.push({ email: values.email }, { username: values.email }); if (values.nationalCode) filters.push({ nationalCode: values.nationalCode }); if (!filters.length) return; const existing = await this.repository(role) .findOne({ $or: filters, ...(ownId ? { _id: { $ne: this.objectId(ownId) } } : {}), }) .lean(); if (existing) throw new ConflictException( "این ایمیل یا کد ملی قبلاً برای همین نقش ثبت شده است.", ); } private async staffValues( role: string, body: any, key: Types.ObjectId, creating: boolean, current?: any, ) { const allowed = role === RoleEnum.COMPANY ? STAFF_FIELDS.filter( (k) => ![ "nationalCode", "branchId", "expertCode", "locations", ...FAN_IDS.slice(1), ].includes(k), ) : STAFF_FIELDS; const values: any = {}; for (const field of Object.keys(body)) { if (field === "role" && creating) continue; if (field === "password") continue; if (!allowed.includes(field)) throw new BadRequestException(`Field ${field} cannot be edited`); let value = body[field]; if (typeof value === "string") value = value.trim(); if (field === "email" && value) value = value.toLowerCase(); if ( FAN_IDS.includes(field) && value != null && value !== "" && (!/^\d+$/.test(String(value)) || !Number.isSafeInteger(Number(value)) || Number(value) <= 0) ) throw new BadRequestException( "Fanavaran expert identifiers must be positive integers", ); if (FAN_IDS.slice(1).includes(field)) { const fullCodeRole = [ RoleEnum.EXPERT, RoleEnum.DAMAGE_EXPERT, RoleEnum.FIELD_EXPERT, ].includes(role as RoleEnum); const allowed = fullCodeRole || (role === RoleEnum.FILE_MAKER && ["ThirdPartyClaimExpertId", "CarBodyClaimExpertId"].includes( field, )) || (role === RoleEnum.FILE_REVIEWER && ["ThirdPartyExpertiseClaim", "CarBodyExpertiseClaim"].includes( field, )); if (!allowed) throw new BadRequestException( "این شناسه فناوران برای نقش انتخاب‌شده قابل ثبت نیست.", ); } if (field === "locations") { if ( ![ RoleEnum.EXPERT, RoleEnum.DAMAGE_EXPERT, RoleEnum.FIELD_EXPERT, RoleEnum.FILE_MAKER, RoleEnum.FILE_REVIEWER, ].includes(role as RoleEnum) ) throw new BadRequestException( "Locations apply only to expert staff roles", ); if (!Array.isArray(value)) throw new BadRequestException("Locations must be an array"); const entries = value.map((v) => ({ id: String(v.id || "").trim(), name: String(v.name || "").trim(), })); if ( entries.some((v) => !v.id || !v.name) || new Set(entries.map((v) => v.id)).size !== entries.length ) throw new BadRequestException( "Location IDs and names are required and IDs must be unique", ); value = entries; } if (field === "branchId" && value) { value = this.objectId(value); if ( !(await this.branches.findOne({ _id: value, clientKey: key }).lean()) ) throw new BadRequestException( "Selected branch does not belong to this insurance company", ); } values[field] = value === "" ? null : value; } const merged = { ...current, ...values }; if ( creating && (!merged.firstName || !merged.lastName || (role !== RoleEnum.COMPANY && !/^\d{10}$/.test(merged.nationalCode || ""))) ) throw new BadRequestException("Required identity fields are missing"); if ( creating && (typeof body.password !== "string" || body.password.length < 6) ) throw new BadRequestException( "Password must contain at least six characters", ); if ( [RoleEnum.EXPERT, RoleEnum.COMPANY].includes(role as RoleEnum) && !merged.email ) throw new BadRequestException("Email is required for this role"); if (role === RoleEnum.EXPERT && !merged.mobile) throw new BadRequestException( "Mobile is required for blame and claim experts", ); if ( !creating && ["firstName", "lastName", "nationalCode"].some( (k) => Object.prototype.hasOwnProperty.call(values, k) && !values[k], ) ) throw new BadRequestException( "Required identity fields cannot be cleared", ); return values; } async listClients() { return { clients: (await this.clients.find({}).lean()).map((c) => ({ _id: c._id, clientName: c.clientName, clientCode: c.clientCode, useExpertMode: c.useExpertMode, })), }; } async saveClient(body: Partial, id?: string) { const key = id ? await this.client(id) : undefined; const current = key ? await this.clients.findOne({ _id: key }).lean() : {}; if ( Object.keys(body).some( (field) => !["clientName", "clientCode", "useExpertMode"].includes(field), ) ) throw new BadRequestException("Unsupported client field"); if (!Object.keys(body).length) throw new BadRequestException("No changes supplied"); const values: any = {}; if ( Object.prototype.hasOwnProperty.call(body, "clientName") && !body.clientName ) throw new BadRequestException("Client names cannot be cleared"); if (body.clientName) values.clientName = { persian: body.clientName.persian?.trim(), english: body.clientName.english?.trim(), }; if (body.clientCode !== undefined) values.clientCode = body.clientCode; if (body.useExpertMode !== undefined) values.useExpertMode = body.useExpertMode; const merged = { ...current, ...values }; if ( !merged.clientName?.persian || !merged.clientName?.english || !["legal", "genuine"].includes(merged.useExpertMode) || !Number.isSafeInteger(merged.clientCode) || merged.clientCode < 1 ) throw new BadRequestException( "Client names and a positive client code are required", ); const duplicate = await this.clients .findOne({ ...(key ? { _id: { $ne: key } } : {}), $or: [ { clientCode: merged.clientCode }, { "clientName.english": merged.clientName.english }, { "clientName.persian": merged.clientName.persian }, ], }) .lean(); if (duplicate) throw new ConflictException( "شرکت بیمه با این کد یا نام قبلاً ثبت شده است.", ); const saved = key ? await this.clients .findOneAndUpdate( { _id: key }, { $set: values }, { new: true, runValidators: true }, ) .lean() : await this.clients.create({ ...values, settings: {} }); return this.pick(saved, ["clientName", "clientCode", "useExpertMode"]); } async listStaff( clientId: string, query: ManagedListQueryDto = {}, account = false, ) { const key = await this.client(clientId); const roles = account ? [RoleEnum.COMPANY] : query.role ? [query.role] : STAFF_ROLES; const groups = await Promise.all( roles.map(async (role) => (await this.repository(role).find(this.scope(key)).lean()).map( (row) => ({ ...this.pick(row, STAFF_FIELDS), role, ...(!account ? { isActive: row.isActive !== false } : {}), }), ), ), ); let list: Array> = groups.flat(); if (query.search?.trim()) { const search = query.search.trim().toLowerCase(); list = list.filter((row) => [ row.firstName, row.lastName, row.nationalCode, row.email, row.mobile, ].some((v) => String(v || "") .toLowerCase() .includes(search), ), ); } list.sort( (a, b) => String(a.firstName || "").localeCompare( String(b.firstName || ""), "fa", ) || String(a._id).localeCompare(String(b._id)), ); const page = query.page || 1; const limit = Math.min(query.limit || 20, 100); return { list: list.slice((page - 1) * limit, page * limit), total: list.length, page, limit, }; } async createStaff( clientId: string, body: CreateManagedStaffDto | any, account = false, ) { const key = await this.client(clientId); const role = account ? RoleEnum.COMPANY : body.role; if (!account && !STAFF_ROLES.includes(role)) throw new BadRequestException("Unsupported staff role"); const values = await this.staffValues(role, body, key, true); await this.uniqueLogin(role, values); const password = await this.hash.hash(body.password); const payload: any = { ...Object.fromEntries( Object.entries(values).filter(([, v]) => v != null), ), password, role, clientKey: role === RoleEnum.EXPERT ? String(key) : key, username: values.email || values.nationalCode, }; if ( [RoleEnum.EXPERT, RoleEnum.DAMAGE_EXPERT, RoleEnum.COMPANY].includes(role) ) { payload.userType = account ? UserType.INSURER : UserType.LEGAL; if (!account) payload.insuActivityCo = String(key); } try { return this.pick( await this.repository(role).create(payload), STAFF_FIELDS, ); } catch (error) { if (error.code === 11000) throw new ConflictException("Account identity is already registered"); throw error; } } async updateStaff( clientId: string, role: string, id: string, body: any, account = false, ) { const key = await this.client(clientId); const identifier = this.objectId(id); if ( account ? role !== RoleEnum.COMPANY : !STAFF_ROLES.includes(role as StaffRole) ) throw new BadRequestException("Unsupported staff role"); const model = this.repository(role); const filter = { _id: identifier, ...this.scope(key) }; const current: any = await model.findOne(filter).lean(); if (!current) throw new NotFoundException( "Staff account not found in this insurance company", ); const values = await this.staffValues(role, body, key, false, current); const merged = { ...current, ...values }; if ( merged.email !== current.email || merged.nationalCode !== current.nationalCode ) await this.uniqueLogin(role, merged, id); const $set: any = {}, $unset: any = {}; for (const [field, value] of Object.entries(values)) { if (value == null) $unset[field] = 1; else $set[field] = value; } if ( Object.prototype.hasOwnProperty.call(values, "email") || Object.prototype.hasOwnProperty.call(values, "nationalCode") ) $set.username = merged.email || merged.nationalCode; if (body.password) $set.password = await this.hash.hash(body.password); if (!Object.keys($set).length && !Object.keys($unset).length) throw new BadRequestException("No changes supplied"); try { const saved = await model .findOneAndUpdate( filter, { ...(Object.keys($set).length ? { $set } : {}), ...(Object.keys($unset).length ? { $unset } : {}), }, { new: true, runValidators: true }, ) .lean(); if (!saved) throw new NotFoundException("Staff account not found"); return this.pick(saved, STAFF_FIELDS); } catch (error) { if (error.code === 11000) throw new ConflictException("Account identity is already registered"); throw error; } } /** Only exposed by the super-admin controller, never by insurer/self edits. */ async setStaffActive( clientId: string, role: string, id: string, isActive: boolean, ) { if (!STAFF_ROLES.includes(role as StaffRole)) throw new BadRequestException("نقش کارشناس معتبر نیست."); if (typeof isActive !== "boolean") throw new BadRequestException("وضعیت فعالیت باید فعال یا غیرفعال باشد."); const key = await this.client(clientId); const saved: any = await this.repository(role) .findOneAndUpdate( { _id: this.objectId(id), ...this.scope(key) }, { $set: { isActive } }, { new: true, runValidators: true }, ) .lean(); if (!saved) throw new NotFoundException("حساب کارشناس در این شرکت بیمه یافت نشد."); return { ...this.pick(saved, STAFF_FIELDS), isActive: saved.isActive !== false, }; } async listBranches(clientId: string) { const key = await this.client(clientId); return { list: await this.branches .find({ clientKey: key }) .sort({ name: 1 }) .lean(), }; } async saveBranch(clientId: string, body: any, id?: string) { const key = await this.client(clientId); const filter = id ? { _id: this.objectId(id), clientKey: key } : undefined; if (filter && !(await this.branches.findOne(filter).lean())) throw new NotFoundException("Branch not found in this insurance company"); const values: any = {}; for (const [field, value] of Object.entries(body)) { if (!BRANCH_FIELDS.includes(field)) throw new BadRequestException(`Field ${field} cannot be edited`); values[field] = typeof value === "string" ? value.trim() : value; } if (!Object.keys(values).length) throw new BadRequestException("No changes supplied"); for (const field of ["name", "code", "city", "state", "address"]) { if ( (!id || Object.prototype.hasOwnProperty.call(values, field)) && !values[field] ) throw new BadRequestException("Required branch fields cannot be empty"); } if (values.isActive === null) throw new BadRequestException("Branch active status must be a boolean"); if ( values.code && (await this.branches .findOne({ clientKey: key, code: values.code, ...(id ? { _id: { $ne: this.objectId(id) } } : {}), }) .lean()) ) throw new ConflictException("کد شعبه در این شرکت بیمه تکراری است."); try { return filter ? await this.branches .findOneAndUpdate( filter, { $set: values }, { new: true, runValidators: true }, ) .lean() : await this.branches.create({ ...values, clientKey: key }); } catch (error) { if (error.code === 11000) throw new ConflictException("Branch code already exists"); throw error; } } }