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:
@@ -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, {
|
||||
|
||||
Reference in New Issue
Block a user