forked from Yara724/api
feat: manage expert access and merge Parsian expert seeds
Allow role-specific identities and admin account activation, support national-code-only claim experts, and remove required voice from v4/v5. Add a combined, resumable Parsian seed that preserves existing accounts and merges locations and product codes.
This commit is contained in:
@@ -23,6 +23,7 @@ import {
|
||||
CreateManagedClientDto,
|
||||
CreateManagedStaffDto,
|
||||
ManagedListQueryDto,
|
||||
SetManagedStaffActiveDto,
|
||||
UpdateManagedAccountDto,
|
||||
UpdateManagedBranchDto,
|
||||
UpdateManagedClientDto,
|
||||
@@ -99,6 +100,14 @@ export class SuperAdminManagementController {
|
||||
@Get("branches") branches(@Query("clientId") client: string) {
|
||||
return this.management.listBranches(client);
|
||||
}
|
||||
@Patch("staff/:role/:id/status") setStaffActive(
|
||||
@Query("clientId") client: string,
|
||||
@Param("role") role: string,
|
||||
@Param("id") id: string,
|
||||
@Body() body: SetManagedStaffActiveDto,
|
||||
) {
|
||||
return this.management.setStaffActive(client, role, id, body.isActive);
|
||||
}
|
||||
@Post("branches") createBranch(
|
||||
@Query("clientId") client: string,
|
||||
@Body() body: CreateBranchDto,
|
||||
|
||||
@@ -9,6 +9,7 @@ import { Transform, Type } from "class-transformer";
|
||||
import {
|
||||
ArrayMaxSize,
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsEmail,
|
||||
IsIn,
|
||||
IsInt,
|
||||
@@ -136,6 +137,11 @@ export class CreateManagedStaffDto {
|
||||
export class UpdateManagedStaffDto extends PartialType(
|
||||
OmitType(CreateManagedStaffDto, ["role"] as const),
|
||||
) {}
|
||||
export class SetManagedStaffActiveDto {
|
||||
@ApiProperty({ description: "وضعیت دسترسی کارشناس به سامانه" })
|
||||
@IsBoolean({ message: "وضعیت فعالیت باید فعال یا غیرفعال باشد." })
|
||||
isActive: boolean;
|
||||
}
|
||||
export class CreateManagedAccountDto extends PickType(CreateManagedStaffDto, [
|
||||
"firstName",
|
||||
"lastName",
|
||||
|
||||
@@ -6,7 +6,18 @@ import {
|
||||
} from "@nestjs/common";
|
||||
import { model, Types } from "mongoose";
|
||||
import { ManagementService } from "./management.service";
|
||||
import { InsurerManagementController } from "./management.controller";
|
||||
import {
|
||||
InsurerManagementController,
|
||||
SuperAdminManagementController,
|
||||
} from "./management.controller";
|
||||
import { Test } from "@nestjs/testing";
|
||||
import { JwtModule, JwtService } from "@nestjs/jwt";
|
||||
import * as request from "supertest";
|
||||
import { ActorAuthService } from "src/auth/auth-services/actor.auth.service";
|
||||
import { ActorAuthController } from "src/auth/auth-controllers/actor/actor.auth.controller";
|
||||
import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard";
|
||||
import { CaptchaChallengeService } from "src/captcha/captcha-challenge.service";
|
||||
import { SuperAdminGuard } from "src/super-admin/guards/super-admin.guard";
|
||||
import {
|
||||
STAFF_ROLES,
|
||||
CreateManagedStaffDto,
|
||||
@@ -14,6 +25,7 @@ import {
|
||||
CreateManagedAccountDto,
|
||||
CreateManagedClientDto,
|
||||
UpdateManagedBranchDto,
|
||||
SetManagedStaffActiveDto,
|
||||
} from "./management.dto";
|
||||
import { ClientDbSchema } from "src/client/entities/schema/client.schema";
|
||||
import { BranchSchema } from "src/client/entities/schema/branch.schema";
|
||||
@@ -146,7 +158,13 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries",
|
||||
expect(stored.branchId).toBeUndefined();
|
||||
},
|
||||
);
|
||||
it.each(["field_expert", "file_maker", "file_reviewer", "call_center"])(
|
||||
it.each([
|
||||
"damage_expert",
|
||||
"field_expert",
|
||||
"file_maker",
|
||||
"file_reviewer",
|
||||
"call_center",
|
||||
])(
|
||||
"supports seed-style %s identity without email or mobile",
|
||||
async (role) => {
|
||||
const body = staff(role);
|
||||
@@ -158,17 +176,14 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries",
|
||||
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(["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"],
|
||||
@@ -339,10 +354,252 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries",
|
||||
await expect(
|
||||
service.createStaff(
|
||||
foreign,
|
||||
staff("file_reviewer", { email: "different@example.com" }),
|
||||
staff("file_maker", { email: "different@example.com" }),
|
||||
),
|
||||
).rejects.toBeInstanceOf(ConflictException);
|
||||
});
|
||||
it("allows one person's email, national code and password across all six staff roles", async () => {
|
||||
const rows = [];
|
||||
for (const role of STAFF_ROLES)
|
||||
rows.push(await service.createStaff(tenant, staff(role)));
|
||||
expect(new Set(rows.map((row) => String(row._id))).size).toBe(6);
|
||||
for (const repo of repos.slice(2, 8)) {
|
||||
expect(repo.records[0]).toMatchObject({
|
||||
nationalCode: "0012345678",
|
||||
email: "expert@example.com",
|
||||
password: "hashed:secret123",
|
||||
});
|
||||
}
|
||||
// Same-role aliases must remain unique even for a different tenant.
|
||||
for (const role of STAFF_ROLES)
|
||||
await expect(
|
||||
service.createStaff(foreign, staff(role)),
|
||||
).rejects.toBeInstanceOf(ConflictException);
|
||||
});
|
||||
it("allows editing an alias to match another role without changing either assignment", async () => {
|
||||
const first = await service.createStaff(tenant, staff("file_maker"));
|
||||
const second = await service.createStaff(
|
||||
tenant,
|
||||
staff("file_reviewer", {
|
||||
email: "reviewer@example.com",
|
||||
nationalCode: "0098765432",
|
||||
}),
|
||||
);
|
||||
const edited = await service.updateStaff(
|
||||
tenant,
|
||||
"file_reviewer",
|
||||
String(second._id),
|
||||
{
|
||||
nationalCode: first.nationalCode,
|
||||
email: first.email,
|
||||
},
|
||||
);
|
||||
expect(edited.email).toBe(first.email);
|
||||
expect(edited.role).toBe("file_reviewer");
|
||||
expect(String(edited._id)).not.toBe(String(first._id));
|
||||
});
|
||||
it.each(STAFF_ROLES)(
|
||||
"disables and reactivates only the selected %s assignment",
|
||||
async (role) => {
|
||||
const row = await service.createStaff(tenant, staff(role));
|
||||
const repo = repos[2 + STAFF_ROLES.indexOf(role)];
|
||||
delete repo.records[0].isActive; // Production records predate the flag.
|
||||
expect((await service.listStaff(tenant, { role })).list[0].isActive).toBe(
|
||||
true,
|
||||
);
|
||||
const before = { ...repo.records[0] };
|
||||
const disabled = await service.setStaffActive(
|
||||
tenant,
|
||||
role,
|
||||
String(row._id),
|
||||
false,
|
||||
);
|
||||
expect(disabled.isActive).toBe(false);
|
||||
expect(disabled).not.toHaveProperty("password");
|
||||
expect(repo.records[0]).toMatchObject({ ...before, isActive: false });
|
||||
expect((await service.listStaff(tenant, { role })).list[0].isActive).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
(await service.setStaffActive(tenant, role, String(row._id), true))
|
||||
.isActive,
|
||||
).toBe(true);
|
||||
},
|
||||
);
|
||||
it("protects status changes against foreign tenants, unsupported roles and malformed values", async () => {
|
||||
const row = await service.createStaff(tenant, staff("file_maker"));
|
||||
await expect(
|
||||
service.setStaffActive(foreign, "file_maker", String(row._id), false),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
await expect(
|
||||
service.setStaffActive(tenant, "super_admin", String(row._id), false),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
await expect(
|
||||
service.setStaffActive(tenant, "file_maker", String(row._id), null),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
await expect(
|
||||
service.updateStaff(tenant, "file_maker", String(row._id), {
|
||||
isActive: false,
|
||||
}),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(repos[5].records[0].isActive).toBe(true);
|
||||
});
|
||||
it("enforces role-specific login, admin-only status, session revocation and reactivation over HTTP", async () => {
|
||||
const actorAuth: any = Object.create(ActorAuthService.prototype);
|
||||
const jwt = new JwtService();
|
||||
actorAuth.jwtService = jwt;
|
||||
actorAuth.hashService = {
|
||||
compare: async (plain, hashed) => hashed === `hashed:${plain}`,
|
||||
};
|
||||
actorAuth.captchaChallengeService = {
|
||||
verify: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
for (const [index, name] of [
|
||||
"expertDbService",
|
||||
"damageExpertDbService",
|
||||
"fieldExpertDbService",
|
||||
"fileMakerDbService",
|
||||
"fileReviewerDbService",
|
||||
"callCenterAgentDbService",
|
||||
].entries()) {
|
||||
const repo = repos[index + 2];
|
||||
actorAuth[name] = {
|
||||
findOne: async (filter) => repo.findOne(filter).lean(),
|
||||
findByLoginIdentifier: async (identifier) =>
|
||||
repo
|
||||
.findOne({
|
||||
$or: [
|
||||
{ email: identifier },
|
||||
{ nationalCode: identifier },
|
||||
{ username: identifier },
|
||||
],
|
||||
})
|
||||
.lean(),
|
||||
};
|
||||
}
|
||||
actorAuth.clientDbService = { findOne: async () => repos[0].records[0] };
|
||||
const module = await Test.createTestingModule({
|
||||
imports: [JwtModule.register({})],
|
||||
controllers: [
|
||||
SuperAdminManagementController,
|
||||
InsurerManagementController,
|
||||
ActorAuthController,
|
||||
],
|
||||
providers: [
|
||||
SuperAdminGuard,
|
||||
LocalActorAuthGuard,
|
||||
{ provide: ManagementService, useValue: service },
|
||||
{ provide: ActorAuthService, useValue: actorAuth },
|
||||
{
|
||||
provide: CaptchaChallengeService,
|
||||
useValue: actorAuth.captchaChallengeService,
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
const app = module.createNestApplication({ logger: false });
|
||||
const secretBefore = process.env.JWT_SECRET;
|
||||
process.env.JWT_SECRET = "expert-access-http-test-only";
|
||||
try {
|
||||
await app.init();
|
||||
const adminToken = jwt.sign(
|
||||
{ sub: String(new Types.ObjectId()), role: "super_admin" },
|
||||
{ secret: process.env.JWT_SECRET },
|
||||
);
|
||||
const companyToken = jwt.sign(
|
||||
{
|
||||
sub: String(new Types.ObjectId()),
|
||||
role: "company",
|
||||
clientKey: tenant,
|
||||
},
|
||||
{ secret: process.env.JWT_SECRET },
|
||||
);
|
||||
const staffUrl = `/super-admin/management/staff?clientId=${tenant}`;
|
||||
const maker = (
|
||||
await request(app.getHttpServer())
|
||||
.post(staffUrl)
|
||||
.auth(adminToken, { type: "bearer" })
|
||||
.send(staff("file_maker"))
|
||||
.expect(201)
|
||||
).body;
|
||||
const reviewer = (
|
||||
await request(app.getHttpServer())
|
||||
.post(staffUrl)
|
||||
.auth(adminToken, { type: "bearer" })
|
||||
.send(staff("file_reviewer"))
|
||||
.expect(201)
|
||||
).body;
|
||||
const login = (
|
||||
role: string,
|
||||
identifier: Record<string, string> = { nationalCode: "0012345678" },
|
||||
) =>
|
||||
request(app.getHttpServer())
|
||||
.post("/actor/login")
|
||||
.send({
|
||||
role,
|
||||
...identifier,
|
||||
password: "secret123",
|
||||
captchaId: "test",
|
||||
captcha: "test",
|
||||
});
|
||||
const makerToken = (await login("file_maker").expect(201)).body
|
||||
.access_token;
|
||||
const reviewerToken = (
|
||||
await login("file_reviewer", { email: "expert@example.com" }).expect(
|
||||
201,
|
||||
)
|
||||
).body.access_token;
|
||||
expect(jwt.decode(makerToken).sub).toBe(maker._id);
|
||||
expect(jwt.decode(reviewerToken).sub).toBe(reviewer._id);
|
||||
const statusUrl = `/super-admin/management/staff/file_maker/${maker._id}/status?clientId=${tenant}`;
|
||||
await request(app.getHttpServer())
|
||||
.patch(statusUrl)
|
||||
.auth(companyToken, { type: "bearer" })
|
||||
.send({ isActive: false })
|
||||
.expect(401);
|
||||
await request(app.getHttpServer())
|
||||
.patch(statusUrl)
|
||||
.auth(makerToken, { type: "bearer" })
|
||||
.send({ isActive: false })
|
||||
.expect(401);
|
||||
await request(app.getHttpServer())
|
||||
.patch(`/expert-insurer/management/staff/file_maker/${maker._id}`)
|
||||
.auth(companyToken, { type: "bearer" })
|
||||
.send({ isActive: false })
|
||||
.expect(400);
|
||||
await request(app.getHttpServer())
|
||||
.patch(statusUrl)
|
||||
.auth(adminToken, { type: "bearer" })
|
||||
.send({ isActive: "false" })
|
||||
.expect(400);
|
||||
const disabled = await request(app.getHttpServer())
|
||||
.patch(statusUrl)
|
||||
.auth(adminToken, { type: "bearer" })
|
||||
.send({ isActive: false })
|
||||
.expect(200);
|
||||
expect(disabled.body.isActive).toBe(false);
|
||||
expect(disabled.body).not.toHaveProperty("password");
|
||||
await login("file_maker").expect(401);
|
||||
await request(app.getHttpServer())
|
||||
.get("/actor/profile")
|
||||
.auth(makerToken, { type: "bearer" })
|
||||
.expect(401);
|
||||
await request(app.getHttpServer())
|
||||
.get("/actor/profile")
|
||||
.auth(reviewerToken, { type: "bearer" })
|
||||
.expect(200);
|
||||
await login("file_reviewer").expect(201);
|
||||
await request(app.getHttpServer())
|
||||
.patch(statusUrl)
|
||||
.auth(adminToken, { type: "bearer" })
|
||||
.send({ isActive: true })
|
||||
.expect(200);
|
||||
await login("file_maker", { email: "expert@example.com" }).expect(201);
|
||||
} finally {
|
||||
await app.close();
|
||||
if (secretBefore === undefined) delete process.env.JWT_SECRET;
|
||||
else process.env.JWT_SECRET = secretBefore;
|
||||
}
|
||||
});
|
||||
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), {
|
||||
@@ -541,6 +798,23 @@ describe("strict management DTO validation", () => {
|
||||
validate(UpdateManagedStaffDto, { role: "super_admin" }),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
it("accepts only a boolean on the dedicated status endpoint", async () => {
|
||||
expect(
|
||||
(await validate(SetManagedStaffActiveDto, { isActive: false })).isActive,
|
||||
).toBe(false);
|
||||
for (const body of [
|
||||
{},
|
||||
{ isActive: null },
|
||||
{ isActive: "false" },
|
||||
{ isActive: true, role: "super_admin" },
|
||||
])
|
||||
await expect(
|
||||
validate(SetManagedStaffActiveDto, body),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
await expect(
|
||||
validate(UpdateManagedStaffDto, { isActive: true }),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
it("limits company-account fields and validates branch booleans and client codes", async () => {
|
||||
await expect(
|
||||
validate(CreateManagedAccountDto, {
|
||||
|
||||
@@ -114,27 +114,24 @@ export class ManagementService {
|
||||
);
|
||||
}
|
||||
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(
|
||||
"این ایمیل یا شناسه ورود قبلاً برای یک حساب ثبت شده است.",
|
||||
);
|
||||
}
|
||||
// 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,
|
||||
@@ -253,16 +250,11 @@ export class ManagementService {
|
||||
"Password must contain at least six characters",
|
||||
);
|
||||
if (
|
||||
[RoleEnum.EXPERT, RoleEnum.DAMAGE_EXPERT, RoleEnum.COMPANY].includes(
|
||||
role as RoleEnum,
|
||||
) &&
|
||||
[RoleEnum.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
|
||||
)
|
||||
if (role === RoleEnum.EXPERT && !merged.mobile)
|
||||
throw new BadRequestException(
|
||||
"Mobile is required for blame and claim experts",
|
||||
);
|
||||
@@ -363,7 +355,11 @@ export class ManagementService {
|
||||
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 }),
|
||||
(row) => ({
|
||||
...this.pick(row, STAFF_FIELDS),
|
||||
role,
|
||||
...(!account ? { isActive: row.isActive !== false } : {}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -500,6 +496,33 @@ export class ManagementService {
|
||||
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 {
|
||||
|
||||
Reference in New Issue
Block a user