Compare commits

...
3 Commits
Author SHA1 Message Date
s.yahyaee 06985855e2 Merge pull request 'Add tenant-scoped insurer, staff and branch management APIs' (#361) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#361
2026-10-11 10:43:53 +03:30
SepehrYahyaee 0c272f1e86 Add tenant-scoped insurer, staff and branch management APIs
Support all six staff roles and editable Fanavaran codes, insurer login accounts and optional branch details. Enforce tenant boundaries and role-specific fields, document setup and extend regression coverage.
2026-10-11 10:42:44 +03:30
s.hajizadeh 4302be8595 Merge pull request 'fanavaran V15 tejaratno' (#360) from s.hajizadeh/yara724api:main into main
Reviewed-on: Yara724/api#360
2026-10-10 16:04:48 +03:30
19 changed files with 1930 additions and 7 deletions
+2
View File
@@ -4,3 +4,5 @@
- [Fanavaran integration](docs/fanavaran/README.md)
- [AI market price estimation MVP — setup and Swagger testing](docs/ai-market-price-estimation.md)
Insurer setup and staff/branch management: [guide](docs/insurer-staff-management.md).
+76
View File
@@ -0,0 +1,76 @@
# Insurer, staff and branch management
The expert panel now supports setting up a fresh deployment without creating insurer/staff accounts through Swagger. No existing case, assignment, Fanavaran or reporting routes were removed.
## Starting with only a super-admin
1. Sign in through the existing super-admin login.
2. Open **شرکت‌های بیمه** (`/insurers`), and add the Persian/English insurer names, numeric client code and expert collaboration mode.
3. Add a **حساب بیمه** with name, email and password. This creates an existing `company` actor attached to that insurer; its login identifier is its email.
4. Use the insurer's **شعبه‌ها** and **اعضا** actions to select the insurer and create branches and staff.
5. The insurer's own account can manage its branches and all six staff roles. It cannot create or edit insurers or insurer login accounts.
The **مدیریت** tabs in `/branches` and `/expert-list` provide creation and editing. Existing date/search filters and performance tables remain under **آمار عملکرد**. The super-admin's existing insurer selector remains available.
## API surface
All endpoints require bearer authentication and strictly validate their DTOs. Swagger groups are `super-admin-management` and `insurer-management`.
| Operation | Super-admin | Insurer |
| --- | --- | --- |
| List/create insurers | `GET/POST /super-admin/management/clients` | Unavailable |
| Edit insurer metadata | `PATCH /super-admin/management/clients/:id` | Unavailable |
| List/create insurer login accounts | `GET/POST /super-admin/management/clients/:clientId/accounts` | Unavailable |
| Edit insurer login account | `PATCH /super-admin/management/clients/:clientId/accounts/:id` | Unavailable |
| List/create staff | `GET/POST /super-admin/management/staff?clientId=...` | `GET/POST /expert-insurer/management/staff` |
| Edit staff | `PATCH /super-admin/management/staff/:role/:id?clientId=...` | `PATCH /expert-insurer/management/staff/:role/:id` |
| List/create branches | `GET/POST /super-admin/management/branches?clientId=...` | `GET/POST /expert-insurer/management/branches` |
| Edit branch | `PATCH /super-admin/management/branches/:id?clientId=...` | `PATCH /expert-insurer/management/branches/:id` |
Staff list queries accept `search`, `role`, `page` and `limit` (default 20, capped at 100). Responses contain `list`, `total`, `page` and `limit`. Branch responses contain `list`; clients contain `clients`. Account lists share the staff pagination contract.
## 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.
Staff creation requires `firstName`, `lastName`, a ten-digit `nationalCode` and a password of at least six characters. Email and mobile are optional for field experts, file makers, file reviewers and call-center agents, matching the seed format. Blame and claim experts require email and mobile to match their existing account contracts. Seed-style accounts without email log in using their national code. National-code and email aliases cannot be duplicated across new managed accounts.
Common optional properties are `branchId`, `phone`, `mobile`, `email`, `city`, `state`, `address` and `expertCode`. A branch, when supplied, must belong to the account's insurer. `expertCode` and the role-specific Fanavaran IDs are positive integer strings, matching existing persistence and mapping contracts.
| Role | Additional optional fields |
| --- | --- |
| Blame, claim and field expert | All four Fanavaran codes below |
| FileMaker | `ThirdPartyClaimExpertId`, `CarBodyClaimExpertId`, `locations` |
| FileReviewer | `ThirdPartyExpertiseClaim`, `CarBodyExpertiseClaim`, `locations` |
| Call-center agent | None of the four product/stage codes |
| Field | Persian label in the panel |
| --- | --- |
| `ThirdPartyClaimExpertId` | کارشناس مسئول پرونده مالی |
| `CarBodyClaimExpertId` | کارشناس مسئول پرونده بدنه |
| `ThirdPartyExpertiseClaim` | کارشناس ارزیاب خسارت ثالث مالی |
| `CarBodyExpertiseClaim` | کارشناس ارزیاب خسارت بدنه |
All four codes are optional, editable and clearable for blame, claim and field experts. FileMaker accounts accept only the first two, FileReviewer accounts accept only the last two, and call-center accounts reject all four through the API. The panel presents these four named fields rather than the legacy generic `expertCode` input; existing `expertCode` values are preserved.
`locations` is an editable array of `{id, name}`. Both properties must be nonempty, and IDs must be unique within the array. These are Fanavaran location IDs, rather than branch codes. Shared locations participate in the existing FileMaker/FileReviewer matching; management does not alter that matching logic.
Branches require `code`, `name`, `city`, `state`, and `address`. `fullName`, `phoneNumber`, `isActive` (default true) and `activityStartDate` are optional and editable. Branch codes remain unique within an insurer. Insurer login accounts support name, email, password and optional contact/address fields; their role and tenant are assigned by the server.
PATCH sends only changed fields. Omit `password` to preserve it; supply a replacement to change it. Nullable optional staff properties can be cleared with `null`; send `locations: []` to clear locations. Required identity and branch properties cannot be cleared. The form preserves the full stored activity timestamp when its date is unchanged.
## Access and compatibility
- An insurer's scope is taken from the authenticated actor's `clientKey`. A supplied tenant identifier never overrides it.
- Super-admin changes require an existing selected insurer. Foreign branch IDs and cross-tenant account/branch edits are rejected. The tenant predicate is retained on the final atomic update.
- Staff roles, client association, arbitrary fields and MongoDB update operators cannot be edited through these endpoints.
- Passwords are hashed through the existing `HashService`; passwords, OTPs, tokens and insurer SMS credentials are excluded from management responses.
- Existing client settings and integrations are preserved when editing client metadata. This UI does not replace the existing system/settings or inquiry configuration screens.
- Existing insurer-create DTOs also accept `expertCode` and the four Fanavaran codes, restricted to the applicable fields for FileMaker/FileReviewer DTOs. The branch schema and existing create DTO accept `fullName`.
- No migration, deletion, mass reassignment or change to case workflow is required.
## Verification
`npm test -- --runInBand` includes schema-backed management tests for all six roles, optional seed fields, role-specific IDs, locations, tenant isolation, branch updates, account passwords, protected fields and strict DTO validation. The route contract keeps the 383 existing routes and adds 18 guarded management routes.
The expert UI's `npm run test:ui` includes management proxy and payload regression checks. Desktop/mobile browser checks use mocked local API responses, rather than modifying a real insurer. Live credential login, database indexes under concurrent writes and outbound Fanavaran submission remain integration QA responsibilities.
+2
View File
@@ -1,3 +1,4 @@
import { ManagementModule } from "./management/management.module";
import { join } from "node:path";
import { APP_INTERCEPTOR, APP_PIPE } from "@nestjs/core";
import { Module } from "@nestjs/common";
@@ -33,6 +34,7 @@ import { PriceEstimationModule } from "./price-estimation/price-estimation.modul
@Module({
imports: [
ManagementModule,
HttpModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
+5
View File
@@ -8,6 +8,11 @@ import {
} from "class-validator";
export class CreateBranchDto {
@ApiProperty({ required: false, description: "Full official branch name" })
@IsOptional()
@IsString()
fullName?: string;
@ApiProperty({ example: "شهرک غرب" })
@IsString()
@IsNotEmpty()
@@ -11,6 +11,9 @@ export class BranchModel {
@Prop({ required: true })
name: string;
@Prop({ type: String })
fullName?: string;
@Prop({ required: true })
code: string;
@@ -170,12 +170,15 @@ describe("Expert Fanavaran stage fields", () => {
AccidentCityId: 702,
AccidentReportTypeId: 156,
});
if (clientKey === "tejaratno")
expect(payload).toMatchObject({
if (clientKey === "tejaratno") {
// Hull claims use root fields; third-party claims notify through DmgNotifications.
const notification =
product === "car-body" ? payload : payload.DmgNotifications?.[0];
expect(notification).toMatchObject({
NotifierTypeId: 5517,
NotifierRelationId: 5523,
});
else {
} else {
expect(payload).not.toHaveProperty("NotifierTypeId");
expect(payload).not.toHaveProperty("NotifierRelationId");
}
@@ -189,6 +192,8 @@ describe("Expert Fanavaran stage fields", () => {
});
expect(payload.DamagedCount).toBeUndefined();
expect(payload.IsLicenseReplacement).toBeUndefined();
} else if (clientKey === "tejaratno") {
expect(payload).not.toHaveProperty("AuthorityCulpritId");
} else expect(payload.AuthorityCulpritId).toBeNull();
},
);
@@ -1,10 +1,11 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { ApiProperty, ApiPropertyOptional, OmitType } from "@nestjs/swagger";
import { Type } from "class-transformer";
import {
IsArray,
IsEmail,
IsEnum,
IsMongoId,
Matches,
IsNotEmpty,
IsOptional,
IsString,
@@ -14,7 +15,10 @@ import { RoleEnum } from "src/Types&Enums/role.enum";
import { UserType } from "src/Types&Enums/userType.enum";
export class ExpertLocationDto {
@ApiProperty({ example: "210050", description: "Fanavaran Location / OpBUId" })
@ApiProperty({
example: "210050",
description: "Fanavaran Location / OpBUId",
})
@IsString()
@IsNotEmpty()
id: string;
@@ -26,6 +30,36 @@ export class ExpertLocationDto {
}
export class CreateInsurerExpertDto {
@ApiPropertyOptional()
@IsOptional()
@IsString()
@Matches(/^\d+$/)
expertCode?: string;
@ApiPropertyOptional({ description: "کارشناس مسئول پرونده مالی" })
@IsOptional()
@IsString()
@Matches(/^\d+$/)
ThirdPartyClaimExpertId?: string;
@ApiPropertyOptional({ description: "کارشناس مسئول پرونده بدنه" })
@IsOptional()
@IsString()
@Matches(/^\d+$/)
CarBodyClaimExpertId?: string;
@ApiPropertyOptional({ description: "کارشناس ارزیاب خسارت ثالث مالی" })
@IsOptional()
@IsString()
@Matches(/^\d+$/)
ThirdPartyExpertiseClaim?: string;
@ApiPropertyOptional({ description: "کارشناس ارزیاب خسارت بدنه" })
@IsOptional()
@IsString()
@Matches(/^\d+$/)
CarBodyExpertiseClaim?: string;
@ApiProperty({ example: "Ali" })
@IsString()
@IsNotEmpty()
@@ -104,7 +138,10 @@ export class CreateClaimExpertByInsurerDto extends CreateInsurerExpertDto {
role?: RoleEnum.DAMAGE_EXPERT;
}
export class CreateFileMakerByInsurerDto extends CreateInsurerExpertDto {
export class CreateFileMakerByInsurerDto extends OmitType(
CreateInsurerExpertDto,
["ThirdPartyExpertiseClaim", "CarBodyExpertiseClaim"] as const,
) {
@ApiPropertyOptional({
enum: [RoleEnum.FILE_MAKER],
default: RoleEnum.FILE_MAKER,
@@ -123,7 +160,10 @@ export class CreateFileMakerByInsurerDto extends CreateInsurerExpertDto {
locations?: ExpertLocationDto[];
}
export class CreateFileReviewerByInsurerDto extends CreateInsurerExpertDto {
export class CreateFileReviewerByInsurerDto extends OmitType(
CreateInsurerExpertDto,
["ThirdPartyClaimExpertId", "CarBodyClaimExpertId"] as const,
) {
@ApiPropertyOptional({
enum: [RoleEnum.FILE_REVIEWER],
default: RoleEnum.FILE_REVIEWER,
+160
View File
@@ -0,0 +1,160 @@
import {
Body,
Controller,
Get,
Param,
Patch,
Post,
Query,
UseGuards,
UsePipes,
ValidationPipe,
} from "@nestjs/common";
import { ApiBearerAuth, ApiTags } from "@nestjs/swagger";
import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard";
import { RolesGuard } from "src/auth/guards/role.guard";
import { Roles } from "src/decorators/roles.decorator";
import { CurrentUser } from "src/decorators/user.decorator";
import { RoleEnum } from "src/Types&Enums/role.enum";
import { SuperAdminGuard } from "src/super-admin/guards/super-admin.guard";
import { CreateBranchDto } from "src/client/dto/create-branch.dto";
import {
CreateManagedAccountDto,
CreateManagedClientDto,
CreateManagedStaffDto,
ManagedListQueryDto,
UpdateManagedAccountDto,
UpdateManagedBranchDto,
UpdateManagedClientDto,
UpdateManagedStaffDto,
} from "./management.dto";
import { ManagementService } from "./management.service";
const validation = new ValidationPipe({
transform: true,
whitelist: true,
forbidNonWhitelisted: true,
});
@ApiTags("super-admin-management")
@ApiBearerAuth()
@UseGuards(SuperAdminGuard)
@UsePipes(validation)
@Controller("super-admin/management")
export class SuperAdminManagementController {
constructor(private management: ManagementService) {}
@Get("clients") clients() {
return this.management.listClients();
}
@Post("clients") createClient(@Body() body: CreateManagedClientDto) {
return this.management.saveClient(body);
}
@Patch("clients/:id") updateClient(
@Param("id") id: string,
@Body() body: UpdateManagedClientDto,
) {
return this.management.saveClient(body, id);
}
@Get("clients/:clientId/accounts") accounts(
@Param("clientId") id: string,
@Query() query: ManagedListQueryDto,
) {
return this.management.listStaff(id, query, true);
}
@Post("clients/:clientId/accounts") createAccount(
@Param("clientId") id: string,
@Body() body: CreateManagedAccountDto,
) {
return this.management.createStaff(id, body, true);
}
@Patch("clients/:clientId/accounts/:id") updateAccount(
@Param("clientId") client: string,
@Param("id") id: string,
@Body() body: UpdateManagedAccountDto,
) {
return this.management.updateStaff(
client,
RoleEnum.COMPANY,
id,
body,
true,
);
}
@Get("staff") staff(@Query() query: ManagedListQueryDto) {
return this.management.listStaff(query.clientId, query);
}
@Post("staff") createStaff(
@Query("clientId") client: string,
@Body() body: CreateManagedStaffDto,
) {
return this.management.createStaff(client, body);
}
@Patch("staff/:role/:id") updateStaff(
@Query("clientId") client: string,
@Param("role") role: string,
@Param("id") id: string,
@Body() body: UpdateManagedStaffDto,
) {
return this.management.updateStaff(client, role, id, body);
}
@Get("branches") branches(@Query("clientId") client: string) {
return this.management.listBranches(client);
}
@Post("branches") createBranch(
@Query("clientId") client: string,
@Body() body: CreateBranchDto,
) {
return this.management.saveBranch(client, body);
}
@Patch("branches/:id") updateBranch(
@Query("clientId") client: string,
@Param("id") id: string,
@Body() body: UpdateManagedBranchDto,
) {
return this.management.saveBranch(client, body, id);
}
}
@ApiTags("insurer-management")
@ApiBearerAuth()
@UseGuards(LocalActorAuthGuard, RolesGuard)
@Roles(RoleEnum.COMPANY)
@UsePipes(validation)
@Controller("expert-insurer/management")
export class InsurerManagementController {
constructor(private management: ManagementService) {}
@Get("staff") staff(
@CurrentUser() actor,
@Query() query: ManagedListQueryDto,
) {
return this.management.listStaff(actor.clientKey, query);
}
@Post("staff") createStaff(
@CurrentUser() actor,
@Body() body: CreateManagedStaffDto,
) {
return this.management.createStaff(actor.clientKey, body);
}
@Patch("staff/:role/:id") updateStaff(
@CurrentUser() actor,
@Param("role") role: string,
@Param("id") id: string,
@Body() body: UpdateManagedStaffDto,
) {
return this.management.updateStaff(actor.clientKey, role, id, body);
}
@Get("branches") branches(@CurrentUser() actor) {
return this.management.listBranches(actor.clientKey);
}
@Post("branches") createBranch(
@CurrentUser() actor,
@Body() body: CreateBranchDto,
) {
return this.management.saveBranch(actor.clientKey, body);
}
@Patch("branches/:id") updateBranch(
@CurrentUser() actor,
@Param("id") id: string,
@Body() body: UpdateManagedBranchDto,
) {
return this.management.saveBranch(actor.clientKey, body, id);
}
}
+187
View File
@@ -0,0 +1,187 @@
import {
ApiProperty,
ApiPropertyOptional,
OmitType,
PartialType,
PickType,
} from "@nestjs/swagger";
import { Transform, Type } from "class-transformer";
import {
ArrayMaxSize,
IsArray,
IsEmail,
IsIn,
IsInt,
IsMongoId,
IsNotEmpty,
IsOptional,
IsString,
Matches,
MaxLength,
Min,
MinLength,
ValidateNested,
} from "class-validator";
import { RoleEnum } from "src/Types&Enums/role.enum";
import { ClientDto } from "src/client/dto/create-client.dto";
import { CreateBranchDto } from "src/client/dto/create-branch.dto";
import { ExpertLocationDto } from "src/expert-insurer/dto/create-insurer-expert.dto";
export const STAFF_ROLES = [
RoleEnum.EXPERT,
RoleEnum.DAMAGE_EXPERT,
RoleEnum.FIELD_EXPERT,
RoleEnum.FILE_MAKER,
RoleEnum.FILE_REVIEWER,
RoleEnum.CALL_CENTER,
] as const;
export type StaffRole = (typeof STAFF_ROLES)[number];
const trim = ({ value }: { value: unknown }) =>
typeof value === "string" ? value.trim() : value;
const optionalText = ({ value }: { value: unknown }) =>
typeof value === "string" && !value.trim() ? null : trim({ value });
export class CreateManagedStaffDto {
@ApiProperty({ enum: STAFF_ROLES }) @IsIn(STAFF_ROLES) role: StaffRole;
@ApiProperty()
@Transform(trim)
@IsString()
@IsNotEmpty()
@MaxLength(100)
firstName: string;
@ApiProperty()
@Transform(trim)
@IsString()
@IsNotEmpty()
@MaxLength(100)
lastName: string;
@ApiProperty() @Transform(trim) @Matches(/^\d{10}$/) nationalCode: string;
@ApiPropertyOptional()
@Transform(optionalText)
@IsOptional()
@IsEmail()
email?: string;
@ApiProperty({ minLength: 6 })
@IsString()
@MinLength(6)
@MaxLength(200)
password: string;
@ApiPropertyOptional()
@Transform(optionalText)
@IsOptional()
@Matches(/^09\d{9}$/)
mobile?: string;
@ApiPropertyOptional()
@Transform(optionalText)
@IsOptional()
@IsMongoId()
branchId?: string;
@ApiPropertyOptional()
@Transform(optionalText)
@IsOptional()
@IsString()
@MaxLength(30)
phone?: string;
@ApiPropertyOptional()
@Transform(optionalText)
@IsOptional()
@IsString()
@MaxLength(100)
city?: string;
@ApiPropertyOptional()
@Transform(optionalText)
@IsOptional()
@IsString()
@MaxLength(100)
state?: string;
@ApiPropertyOptional()
@Transform(optionalText)
@IsOptional()
@IsString()
@MaxLength(1000)
address?: string;
@ApiPropertyOptional()
@Transform(optionalText)
@IsOptional()
@Matches(/^\d+$/)
expertCode?: string;
@ApiPropertyOptional({ type: [ExpertLocationDto] })
@IsOptional()
@IsArray()
@ArrayMaxSize(100)
@ValidateNested({ each: true })
@Type(() => ExpertLocationDto)
locations?: ExpertLocationDto[];
@ApiPropertyOptional({ description: "کارشناس مسئول پرونده مالی" })
@Transform(optionalText)
@IsOptional()
@Matches(/^\d+$/)
ThirdPartyClaimExpertId?: string;
@ApiPropertyOptional({ description: "کارشناس مسئول پرونده بدنه" })
@Transform(optionalText)
@IsOptional()
@Matches(/^\d+$/)
CarBodyClaimExpertId?: string;
@ApiPropertyOptional({ description: "کارشناس ارزیاب خسارت ثالث مالی" })
@Transform(optionalText)
@IsOptional()
@Matches(/^\d+$/)
ThirdPartyExpertiseClaim?: string;
@ApiPropertyOptional({ description: "کارشناس ارزیاب خسارت بدنه" })
@Transform(optionalText)
@IsOptional()
@Matches(/^\d+$/)
CarBodyExpertiseClaim?: string;
}
export class UpdateManagedStaffDto extends PartialType(
OmitType(CreateManagedStaffDto, ["role"] as const),
) {}
export class CreateManagedAccountDto extends PickType(CreateManagedStaffDto, [
"firstName",
"lastName",
"email",
"password",
"mobile",
"phone",
"city",
"state",
"address",
] as const) {}
export class UpdateManagedAccountDto extends PartialType(
CreateManagedAccountDto,
) {}
export class UpdateManagedBranchDto extends PartialType(CreateBranchDto) {}
export class CreateManagedClientDto extends PickType(ClientDto, [
"clientName",
"clientCode",
"useExpertMode",
] as const) {
@ApiProperty() @IsInt() @Min(1) clientCode: number;
}
export class UpdateManagedClientDto extends PartialType(
CreateManagedClientDto,
) {}
export class ManagedListQueryDto {
@ApiPropertyOptional() @IsOptional() @IsMongoId() clientId?: string;
@ApiPropertyOptional({ enum: STAFF_ROLES })
@IsOptional()
@IsIn(STAFF_ROLES)
role?: StaffRole;
@ApiPropertyOptional()
@IsOptional()
@IsString()
@MaxLength(100)
search?: string;
@ApiPropertyOptional({ default: 1 })
@Type(() => Number)
@IsOptional()
@IsInt()
@Min(1)
page?: number;
@ApiPropertyOptional({ default: 20 })
@Type(() => Number)
@IsOptional()
@IsInt()
@Min(1)
limit?: number;
}
+67
View File
@@ -0,0 +1,67 @@
import { Module } from "@nestjs/common";
import { MongooseModule } from "@nestjs/mongoose";
import { AuthModule } from "src/auth/auth.module";
import { HashModule } from "src/utils/hash/hash.module";
import {
ClientModel,
ClientDbSchema,
} from "src/client/entities/schema/client.schema";
import {
BranchModel,
BranchSchema,
} from "src/client/entities/schema/branch.schema";
import {
ExpertModel,
ExpertDbSchema,
} from "src/users/entities/schema/expert.schema";
import {
DamageExpertModel,
DamageExpertDbSchema,
} from "src/users/entities/schema/damage-expert.schema";
import {
FieldExpertModel,
FieldExpertDbSchema,
} from "src/users/entities/schema/field-expert.schema";
import {
FileMakerModel,
FileMakerDbSchema,
} from "src/users/entities/schema/file-maker.schema";
import {
FileReviewerModel,
FileReviewerDbSchema,
} from "src/users/entities/schema/file-reviewer.schema";
import {
CallCenterAgentModel,
CallCenterAgentDbSchema,
} from "src/users/entities/schema/call-center-agent.schema";
import {
InsurerExpertModel,
InsurerExpertDbSchema,
} from "src/users/entities/schema/insurer-expert.schema";
import { SuperAdminGuard } from "src/super-admin/guards/super-admin.guard";
import { ManagementService } from "./management.service";
import {
InsurerManagementController,
SuperAdminManagementController,
} from "./management.controller";
@Module({
imports: [
AuthModule,
HashModule,
MongooseModule.forFeature([
{ name: ClientModel.name, schema: ClientDbSchema },
{ name: BranchModel.name, schema: BranchSchema },
{ name: ExpertModel.name, schema: ExpertDbSchema },
{ name: DamageExpertModel.name, schema: DamageExpertDbSchema },
{ name: FieldExpertModel.name, schema: FieldExpertDbSchema },
{ name: FileMakerModel.name, schema: FileMakerDbSchema },
{ name: FileReviewerModel.name, schema: FileReviewerDbSchema },
{ name: CallCenterAgentModel.name, schema: CallCenterAgentDbSchema },
{ name: InsurerExpertModel.name, schema: InsurerExpertDbSchema },
]),
],
controllers: [InsurerManagementController, SuperAdminManagementController],
providers: [ManagementService, SuperAdminGuard],
exports: [ManagementService],
})
export class ManagementModule {}
+561
View File
@@ -0,0 +1,561 @@
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<typeof repository>[],
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);
});
});
+557
View File
@@ -0,0 +1,557 @@
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<any>,
@InjectModel(BranchModel.name) private branches: Model<any>,
@InjectModel(ExpertModel.name) private blame: Model<any>,
@InjectModel(DamageExpertModel.name) private claim: Model<any>,
@InjectModel(FieldExpertModel.name) private field: Model<any>,
@InjectModel(FileMakerModel.name) private maker: Model<any>,
@InjectModel(FileReviewerModel.name) private reviewer: Model<any>,
@InjectModel(CallCenterAgentModel.name) private callCenter: Model<any>,
@InjectModel(InsurerExpertModel.name) private company: Model<any>,
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<any> {
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<string, any> {
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) {
const national = values.nationalCode;
const email = values.email;
for (const otherRole of [...STAFF_ROLES, RoleEnum.COMPANY]) {
const filters: any[] = [];
if (email) filters.push({ email }, { username: email });
// National-code login has no tenant selector: never introduce an ambiguous identifier.
if (national) filters.push({ nationalCode: national });
if (!filters.length) continue;
const existing = await this.repository(otherRole)
.findOne({
$or: filters,
...(ownId && otherRole === role
? { _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.FILE_MAKER, RoleEnum.FILE_REVIEWER].includes(
role as RoleEnum,
)
)
throw new BadRequestException(
"Locations apply only to file makers and reviewers",
);
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.DAMAGE_EXPERT, RoleEnum.COMPANY].includes(
role as RoleEnum,
) &&
!merged.email
)
throw new BadRequestException("Email is required for this role");
if (
[RoleEnum.EXPERT, RoleEnum.DAMAGE_EXPERT].includes(role as RoleEnum) &&
!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<CreateManagedClientDto>, 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 }),
),
),
);
let list: Array<Record<string, any>> = 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;
}
}
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;
}
}
}
@@ -41,6 +41,21 @@ export class CallCenterAgentModel {
@Prop({ required: false })
phone?: string;
@Prop({ type: String })
city?: string;
@Prop({ type: String })
state?: string;
@Prop({ type: String })
address?: string;
@Prop({ type: Types.ObjectId, index: true })
branchId?: Types.ObjectId;
@Prop({ type: String })
expertCode?: string;
@Prop({ default: RoleEnum.CALL_CENTER })
role: RoleEnum;
@@ -162,6 +162,18 @@ export class DamageExpertModel {
@Prop({type: "string", required: false})
expertCode?: string;
@Prop({ type: String, required: false })
ThirdPartyClaimExpertId?: string;
@Prop({ type: String, required: false })
CarBodyClaimExpertId?: string;
@Prop({ type: String, required: false })
ThirdPartyExpertiseClaim?: string;
@Prop({ type: String, required: false })
CarBodyExpertiseClaim?: string;
createdAt: Date;
}
@@ -75,6 +75,18 @@ export class ExpertModel {
@Prop({type: "string", required: false})
expertCode?: string;
@Prop({ type: String, required: false })
ThirdPartyClaimExpertId?: string;
@Prop({ type: String, required: false })
CarBodyClaimExpertId?: string;
@Prop({ type: String, required: false })
ThirdPartyExpertiseClaim?: string;
@Prop({ type: String, required: false })
CarBodyExpertiseClaim?: string;
createdAt: Date;
}
@@ -40,6 +40,15 @@ export class FieldExpertModel {
@Prop({ required: false })
phone?: string;
@Prop({ type: String })
city?: string;
@Prop({ type: String })
state?: string;
@Prop({ type: String })
address?: string;
@Prop({ default: RoleEnum.FIELD_EXPERT })
role: RoleEnum;
@@ -49,6 +58,18 @@ export class FieldExpertModel {
@Prop({type: "string", required: false})
expertCode?: string;
@Prop({ type: String, required: false })
ThirdPartyClaimExpertId?: string;
@Prop({ type: String, required: false })
CarBodyClaimExpertId?: string;
@Prop({ type: String, required: false })
ThirdPartyExpertiseClaim?: string;
@Prop({ type: String, required: false })
CarBodyExpertiseClaim?: string;
createdAt: Date;
}
@@ -56,6 +56,15 @@ export class FileMakerModel {
@Prop({ required: false })
phone?: string;
@Prop({ type: String })
city?: string;
@Prop({ type: String })
state?: string;
@Prop({ type: String })
address?: string;
@Prop({ default: RoleEnum.FILE_MAKER })
role: RoleEnum;
@@ -56,6 +56,15 @@ export class FileReviewerModel {
@Prop({ required: false })
phone?: string;
@Prop({ type: String })
city?: string;
@Prop({ type: String })
state?: string;
@Prop({ type: String })
address?: string;
@Prop({ default: RoleEnum.FILE_REVIEWER })
role: RoleEnum;
+180
View File
@@ -313,6 +313,30 @@
"company"
]
},
{
"controller": "InsurerManagementController",
"method": "GET",
"path": "/expert-insurer/management/branches",
"guards": [
"LocalActorAuthGuard",
"RolesGuard"
],
"roles": [
"company"
]
},
{
"controller": "InsurerManagementController",
"method": "GET",
"path": "/expert-insurer/management/staff",
"guards": [
"LocalActorAuthGuard",
"RolesGuard"
],
"roles": [
"company"
]
},
{
"controller": "ExpertInsurerController",
"method": "GET",
@@ -1012,6 +1036,42 @@
],
"roles": []
},
{
"controller": "SuperAdminManagementController",
"method": "GET",
"path": "/super-admin/management/branches",
"guards": [
"SuperAdminGuard"
],
"roles": []
},
{
"controller": "SuperAdminManagementController",
"method": "GET",
"path": "/super-admin/management/clients",
"guards": [
"SuperAdminGuard"
],
"roles": []
},
{
"controller": "SuperAdminManagementController",
"method": "GET",
"path": "/super-admin/management/clients/:clientId/accounts",
"guards": [
"SuperAdminGuard"
],
"roles": []
},
{
"controller": "SuperAdminManagementController",
"method": "GET",
"path": "/super-admin/management/staff",
"guards": [
"SuperAdminGuard"
],
"roles": []
},
{
"controller": "SuperAdminController",
"method": "GET",
@@ -1943,6 +2003,30 @@
"expert"
]
},
{
"controller": "InsurerManagementController",
"method": "PATCH",
"path": "/expert-insurer/management/branches/:id",
"guards": [
"LocalActorAuthGuard",
"RolesGuard"
],
"roles": [
"company"
]
},
{
"controller": "InsurerManagementController",
"method": "PATCH",
"path": "/expert-insurer/management/staff/:role/:id",
"guards": [
"LocalActorAuthGuard",
"RolesGuard"
],
"roles": [
"company"
]
},
{
"controller": "SuperAdminController",
"method": "PATCH",
@@ -1952,6 +2036,42 @@
],
"roles": []
},
{
"controller": "SuperAdminManagementController",
"method": "PATCH",
"path": "/super-admin/management/branches/:id",
"guards": [
"SuperAdminGuard"
],
"roles": []
},
{
"controller": "SuperAdminManagementController",
"method": "PATCH",
"path": "/super-admin/management/clients/:clientId/accounts/:id",
"guards": [
"SuperAdminGuard"
],
"roles": []
},
{
"controller": "SuperAdminManagementController",
"method": "PATCH",
"path": "/super-admin/management/clients/:id",
"guards": [
"SuperAdminGuard"
],
"roles": []
},
{
"controller": "SuperAdminManagementController",
"method": "PATCH",
"path": "/super-admin/management/staff/:role/:id",
"guards": [
"SuperAdminGuard"
],
"roles": []
},
{
"controller": "SuperAdminController",
"method": "PATCH",
@@ -2468,6 +2588,30 @@
"company"
]
},
{
"controller": "InsurerManagementController",
"method": "POST",
"path": "/expert-insurer/management/branches",
"guards": [
"LocalActorAuthGuard",
"RolesGuard"
],
"roles": [
"company"
]
},
{
"controller": "InsurerManagementController",
"method": "POST",
"path": "/expert-insurer/management/staff",
"guards": [
"LocalActorAuthGuard",
"RolesGuard"
],
"roles": [
"company"
]
},
{
"controller": "SuperAdminController",
"method": "POST",
@@ -2567,6 +2711,42 @@
],
"roles": []
},
{
"controller": "SuperAdminManagementController",
"method": "POST",
"path": "/super-admin/management/branches",
"guards": [
"SuperAdminGuard"
],
"roles": []
},
{
"controller": "SuperAdminManagementController",
"method": "POST",
"path": "/super-admin/management/clients",
"guards": [
"SuperAdminGuard"
],
"roles": []
},
{
"controller": "SuperAdminManagementController",
"method": "POST",
"path": "/super-admin/management/clients/:clientId/accounts",
"guards": [
"SuperAdminGuard"
],
"roles": []
},
{
"controller": "SuperAdminManagementController",
"method": "POST",
"path": "/super-admin/management/staff",
"guards": [
"SuperAdminGuard"
],
"roles": []
},
{
"controller": "SuperAdminController",
"method": "POST",