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:
@@ -183,7 +183,9 @@ export class ActorAuthService {
|
||||
dbService: { findOne: (filter: any) => Promise<any> },
|
||||
identifier: string,
|
||||
) {
|
||||
const id = identifier.trim();
|
||||
const id = identifier.includes("@")
|
||||
? identifier.trim().toLowerCase()
|
||||
: identifier.trim();
|
||||
const or: Record<string, string>[] = [{ email: id }, { username: id }];
|
||||
if (/^\d{10}$/.test(id)) {
|
||||
or.push({ nationalCode: id });
|
||||
@@ -234,9 +236,47 @@ export class ActorAuthService {
|
||||
if (!(await this.hashService.compare(pass, user.password))) {
|
||||
throw new UnauthorizedException("نام کاربری یا رمز عبور اشتباه است");
|
||||
}
|
||||
this.assertActive(user);
|
||||
return user;
|
||||
}
|
||||
|
||||
private assertActive(actor: { isActive?: boolean }) {
|
||||
// Legacy accounts have no flag and remain active.
|
||||
if (actor.isActive === false)
|
||||
throw new UnauthorizedException(
|
||||
"حساب کاری شما غیرفعال شده است. با مدیر سامانه تماس بگیرید.",
|
||||
);
|
||||
}
|
||||
|
||||
/** Recheck persisted status so a disabled account cannot reuse an old JWT. */
|
||||
async assertActorActive(payload: { role?: string; sub?: string }) {
|
||||
if (
|
||||
![
|
||||
RoleEnum.EXPERT,
|
||||
RoleEnum.DAMAGE_EXPERT,
|
||||
RoleEnum.FIELD_EXPERT,
|
||||
RoleEnum.FILE_MAKER,
|
||||
RoleEnum.FILE_REVIEWER,
|
||||
RoleEnum.CALL_CENTER,
|
||||
].includes(payload?.role as RoleEnum)
|
||||
)
|
||||
return;
|
||||
if (!payload.sub || !Types.ObjectId.isValid(payload.sub))
|
||||
throw new UnauthorizedException(
|
||||
"حساب کاربری معتبر نیست. دوباره وارد شوید.",
|
||||
);
|
||||
const actor = await this.dynamicDbController(
|
||||
payload.role,
|
||||
null,
|
||||
payload.sub,
|
||||
);
|
||||
if (!actor)
|
||||
throw new UnauthorizedException(
|
||||
"حساب کاربری یافت نشد. دوباره وارد شوید.",
|
||||
);
|
||||
this.assertActive(actor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticates an actor from a login request body (role, username/email, password).
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
import { ExecutionContext, UnauthorizedException } from "@nestjs/common";
|
||||
import { Types } from "mongoose";
|
||||
import { ActorAuthService } from "./actor.auth.service";
|
||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
import { GlobalGuard } from "../guards/global.guard";
|
||||
import { LocalActorAuthGuard } from "../guards/actor-local.guard";
|
||||
import { SettingsJwtGuard } from "../guards/settings-jwt.guard";
|
||||
import { AuthGuard } from "src/common/auth/guards/auth.guard";
|
||||
import { ClaimAccessGuard } from "../guards/claim-access.guard";
|
||||
import { ExpertInsurerService } from "src/expert-insurer/expert-insurer.service";
|
||||
|
||||
const roles = [
|
||||
RoleEnum.EXPERT,
|
||||
RoleEnum.DAMAGE_EXPERT,
|
||||
RoleEnum.FIELD_EXPERT,
|
||||
RoleEnum.FILE_MAKER,
|
||||
RoleEnum.FILE_REVIEWER,
|
||||
RoleEnum.CALL_CENTER,
|
||||
];
|
||||
const dbNames = [
|
||||
"expertDbService",
|
||||
"damageExpertDbService",
|
||||
"fieldExpertDbService",
|
||||
"fileMakerDbService",
|
||||
"fileReviewerDbService",
|
||||
"callCenterAgentDbService",
|
||||
];
|
||||
|
||||
function setup() {
|
||||
const service = new (ActorAuthService as any)() as ActorAuthService;
|
||||
const actors = roles.map((role) => ({
|
||||
_id: new Types.ObjectId(),
|
||||
role,
|
||||
email: "person@example.test",
|
||||
nationalCode: "0012345678",
|
||||
password: "hash:shared-password",
|
||||
}));
|
||||
const dbs = actors.map((actor, index) => {
|
||||
const db = {
|
||||
findOne: jest.fn().mockResolvedValue(actor),
|
||||
findByLoginIdentifier: jest.fn().mockResolvedValue(actor),
|
||||
};
|
||||
(service as any)[dbNames[index]] = db;
|
||||
return db;
|
||||
});
|
||||
(service as any).hashService = {
|
||||
compare: jest.fn(async (plain, hashed) => `hash:${plain}` === hashed),
|
||||
};
|
||||
return { service, actors, dbs };
|
||||
}
|
||||
|
||||
describe("expert role identities and activation", () => {
|
||||
it.each(["person@example.test", "0012345678"])(
|
||||
"authenticates the same %s and password in every assigned role",
|
||||
async (identifier) => {
|
||||
const { service, actors, dbs } = setup();
|
||||
for (const [index, role] of roles.entries()) {
|
||||
expect(
|
||||
await service.validateActor(identifier, "shared-password", role),
|
||||
).toBe(actors[index]);
|
||||
expect(
|
||||
dbs[index].findOne.mock.calls.length +
|
||||
dbs[index].findByLoginIdentifier.mock.calls.length,
|
||||
).toBe(1);
|
||||
}
|
||||
for (const db of dbs)
|
||||
expect(
|
||||
db.findOne.mock.calls.length +
|
||||
db.findByLoginIdentifier.mock.calls.length,
|
||||
).toBe(1);
|
||||
},
|
||||
);
|
||||
it.each(roles)(
|
||||
"blocks inactive %s login and tokens, with legacy-active and reactivation support",
|
||||
async (role) => {
|
||||
const { service, actors } = setup();
|
||||
const actor: any = actors[roles.indexOf(role)];
|
||||
const token = { role, sub: String(actor._id) };
|
||||
await expect(
|
||||
service.validateActor(actor.email, "shared-password", role),
|
||||
).resolves.toBe(actor);
|
||||
await expect(service.assertActorActive(token)).resolves.toBeUndefined();
|
||||
actor.isActive = false;
|
||||
await expect(
|
||||
service.validateActor(actor.email, "shared-password", role),
|
||||
).rejects.toThrow("غیرفعال");
|
||||
await expect(service.assertActorActive(token)).rejects.toThrow("غیرفعال");
|
||||
actor.isActive = true;
|
||||
await expect(
|
||||
service.validateActor(actor.nationalCode, "shared-password", role),
|
||||
).resolves.toBe(actor);
|
||||
},
|
||||
);
|
||||
it("disabling the maker leaves the reviewer's credentials and access intact", async () => {
|
||||
const { service, actors } = setup();
|
||||
(actors[3] as any).isActive = false;
|
||||
await expect(
|
||||
service.validateActor(
|
||||
"0012345678",
|
||||
"shared-password",
|
||||
RoleEnum.FILE_MAKER,
|
||||
),
|
||||
).rejects.toThrow("غیرفعال");
|
||||
await expect(
|
||||
service.validateActor(
|
||||
"0012345678",
|
||||
"shared-password",
|
||||
RoleEnum.FILE_REVIEWER,
|
||||
),
|
||||
).resolves.toBe(actors[4]);
|
||||
await expect(
|
||||
service.validateActor(
|
||||
"0012345678",
|
||||
"wrong-password",
|
||||
RoleEnum.FILE_REVIEWER,
|
||||
),
|
||||
).rejects.toBeInstanceOf(UnauthorizedException);
|
||||
});
|
||||
it("does not resolve ordinary user, insurer or super-admin JWTs through expert storage", async () => {
|
||||
const { service, dbs } = setup();
|
||||
for (const role of [RoleEnum.USER, RoleEnum.COMPANY, RoleEnum.SUPER_ADMIN])
|
||||
await service.assertActorActive({ role, sub: "existing-subject" });
|
||||
for (const db of dbs) expect(db.findOne).not.toHaveBeenCalled();
|
||||
});
|
||||
it("rejects missing/deleted expert subjects", async () => {
|
||||
const { service, dbs } = setup();
|
||||
await expect(
|
||||
service.assertActorActive({ role: RoleEnum.EXPERT, sub: "bad-id" }),
|
||||
).rejects.toBeInstanceOf(UnauthorizedException);
|
||||
dbs[0].findOne.mockResolvedValue(null);
|
||||
await expect(
|
||||
service.assertActorActive({
|
||||
role: RoleEnum.EXPERT,
|
||||
sub: String(new Types.ObjectId()),
|
||||
}),
|
||||
).rejects.toBeInstanceOf(UnauthorizedException);
|
||||
});
|
||||
});
|
||||
|
||||
describe("expert access status at every JWT entry point", () => {
|
||||
it.each(["actor", "user-panel", "settings", "common", "claim"])(
|
||||
"checks current account state in %s guard",
|
||||
async (entry) => {
|
||||
const auth = { assertActorActive: jest.fn() };
|
||||
const payload = {
|
||||
role: entry === "claim" ? RoleEnum.DAMAGE_EXPERT : RoleEnum.FILE_MAKER,
|
||||
sub: String(new Types.ObjectId()),
|
||||
};
|
||||
const jwt = { verifyAsync: jest.fn().mockResolvedValue(payload) };
|
||||
const guard =
|
||||
entry === "actor"
|
||||
? new LocalActorAuthGuard(auth as any, jwt as any)
|
||||
: entry === "user-panel"
|
||||
? new GlobalGuard(jwt as any, auth as any)
|
||||
: entry === "settings"
|
||||
? new SettingsJwtGuard(jwt as any, auth as any)
|
||||
: entry === "claim"
|
||||
? new ClaimAccessGuard(jwt as any, {} as any, auth as any)
|
||||
: new AuthGuard(jwt as any, auth as any);
|
||||
const request = {
|
||||
headers: { authorization: "Bearer existing-token" },
|
||||
url: "/protected",
|
||||
};
|
||||
const context = {
|
||||
switchToHttp: () => ({ getRequest: () => request }),
|
||||
} as ExecutionContext;
|
||||
await expect(guard.canActivate(context)).resolves.toBe(true);
|
||||
expect(auth.assertActorActive).toHaveBeenCalledWith(payload);
|
||||
auth.assertActorActive.mockRejectedValue(
|
||||
new UnauthorizedException("حساب کاری غیرفعال است."),
|
||||
);
|
||||
await expect(guard.canActivate(context)).rejects.toThrow("غیرفعال");
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("older insurer expert-creation endpoints", () => {
|
||||
it.each([RoleEnum.EXPERT, RoleEnum.DAMAGE_EXPERT])(
|
||||
"limits duplicate checks to the selected %s role",
|
||||
async (role) => {
|
||||
const service = new (ExpertInsurerService as any)() as any;
|
||||
const key = new Types.ObjectId();
|
||||
service.getClientId = () => key;
|
||||
service.assertBranchBelongsToClient = async () => ({
|
||||
_id: new Types.ObjectId(),
|
||||
name: "شعبه",
|
||||
});
|
||||
service.hashService = { hash: async () => "hash:password" };
|
||||
service.sanitizeExpertResponse = (value) => ({ role: value.role });
|
||||
const makeDb = () => ({
|
||||
findOne: jest.fn().mockResolvedValue(null),
|
||||
create: jest.fn(async (body) => body),
|
||||
});
|
||||
service.expertDbService = makeDb();
|
||||
service.damageExpertDbService = makeDb();
|
||||
const selected =
|
||||
role === RoleEnum.EXPERT
|
||||
? service.expertDbService
|
||||
: service.damageExpertDbService;
|
||||
const other =
|
||||
role === RoleEnum.EXPERT
|
||||
? service.damageExpertDbService
|
||||
: service.expertDbService;
|
||||
other.findOne.mockResolvedValue({
|
||||
nationalCode: "0012345678",
|
||||
email: "person@example.test",
|
||||
});
|
||||
await service.createExpertForInsurer(
|
||||
String(key),
|
||||
{
|
||||
email: "person@example.test",
|
||||
nationalCode: "0012345678",
|
||||
password: "password",
|
||||
branchId: String(new Types.ObjectId()),
|
||||
firstName: "علی",
|
||||
lastName: "احمدی",
|
||||
},
|
||||
role,
|
||||
);
|
||||
expect(selected.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ role, email: "person@example.test" }),
|
||||
);
|
||||
expect(other.findOne).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -4,15 +4,17 @@ import { LocalActorAuthGuard } from "./actor-local.guard";
|
||||
|
||||
describe("LocalActorAuthGuard", () => {
|
||||
const credentials = { username: "new-account", password: "test-password" };
|
||||
let auth: { loginFromCredentials: jest.Mock };
|
||||
let auth: { loginFromCredentials: jest.Mock; assertActorActive: jest.Mock };
|
||||
let jwt: { verifyAsync: jest.Mock };
|
||||
let guard: LocalActorAuthGuard;
|
||||
|
||||
const context = (request: Record<string, unknown>) =>
|
||||
({ switchToHttp: () => ({ getRequest: () => request }) }) as ExecutionContext;
|
||||
({
|
||||
switchToHttp: () => ({ getRequest: () => request }),
|
||||
}) as ExecutionContext;
|
||||
|
||||
beforeEach(() => {
|
||||
auth = { loginFromCredentials: jest.fn() };
|
||||
auth = { loginFromCredentials: jest.fn(), assertActorActive: jest.fn() };
|
||||
jwt = { verifyAsync: jest.fn() };
|
||||
guard = new LocalActorAuthGuard(auth as any, jwt as any);
|
||||
});
|
||||
@@ -38,14 +40,19 @@ describe("LocalActorAuthGuard", () => {
|
||||
|
||||
it("does not let a previous token bypass failed credentials or captcha", async () => {
|
||||
auth.loginFromCredentials.mockRejectedValue(new UnauthorizedException());
|
||||
jwt.verifyAsync.mockResolvedValue({ sub: "old-account", role: RoleEnum.EXPERT });
|
||||
jwt.verifyAsync.mockResolvedValue({
|
||||
sub: "old-account",
|
||||
role: RoleEnum.EXPERT,
|
||||
});
|
||||
|
||||
await expect(
|
||||
guard.canActivate(context({
|
||||
route: { path: "/actor/login" },
|
||||
headers: { authorization: "Bearer previous-session" },
|
||||
body: credentials,
|
||||
})),
|
||||
guard.canActivate(
|
||||
context({
|
||||
route: { path: "/actor/login" },
|
||||
headers: { authorization: "Bearer previous-session" },
|
||||
body: credentials,
|
||||
}),
|
||||
),
|
||||
).rejects.toBeInstanceOf(UnauthorizedException);
|
||||
expect(jwt.verifyAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -58,9 +65,31 @@ describe("LocalActorAuthGuard", () => {
|
||||
headers: { authorization: "Bearer current-session" },
|
||||
};
|
||||
await expect(guard.canActivate(context(request))).resolves.toBe(true);
|
||||
expect(jwt.verifyAsync).toHaveBeenCalledWith("current-session", expect.any(Object));
|
||||
expect(jwt.verifyAsync).toHaveBeenCalledWith(
|
||||
"current-session",
|
||||
expect.any(Object),
|
||||
);
|
||||
expect(auth.loginFromCredentials).not.toHaveBeenCalled();
|
||||
expect(request["user"]).toBe(payload);
|
||||
expect(auth.assertActorActive).toHaveBeenCalledWith(payload);
|
||||
});
|
||||
|
||||
it("rejects a previously issued token after the account is disabled", async () => {
|
||||
jwt.verifyAsync.mockResolvedValue({
|
||||
sub: "expert-id",
|
||||
role: RoleEnum.EXPERT,
|
||||
});
|
||||
auth.assertActorActive.mockRejectedValue(
|
||||
new UnauthorizedException("حساب کاری شما غیرفعال شده است."),
|
||||
);
|
||||
const request = {
|
||||
url: "/actor/profile",
|
||||
headers: { authorization: "Bearer old-session" },
|
||||
};
|
||||
await expect(guard.canActivate(context(request))).rejects.toThrow(
|
||||
"غیرفعال",
|
||||
);
|
||||
expect(request).not.toHaveProperty("user");
|
||||
});
|
||||
|
||||
it("rejects protected actor routes without a token", async () => {
|
||||
@@ -73,10 +102,12 @@ describe("LocalActorAuthGuard", () => {
|
||||
it("rejects expired tokens on protected routes", async () => {
|
||||
jwt.verifyAsync.mockRejectedValue(new Error("expired"));
|
||||
await expect(
|
||||
guard.canActivate(context({
|
||||
url: "/actor/profile",
|
||||
headers: { authorization: "Bearer expired-session" },
|
||||
})),
|
||||
guard.canActivate(
|
||||
context({
|
||||
url: "/actor/profile",
|
||||
headers: { authorization: "Bearer expired-session" },
|
||||
}),
|
||||
),
|
||||
).rejects.toBeInstanceOf(UnauthorizedException);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -55,9 +55,11 @@ export class LocalActorAuthGuard implements CanActivate {
|
||||
throw new UnauthorizedException("User role is not authorized");
|
||||
}
|
||||
|
||||
await this.actorAuthService.assertActorActive(payload);
|
||||
request.user = payload;
|
||||
request.identity = request.user;
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (error instanceof UnauthorizedException) throw error;
|
||||
throw new UnauthorizedException("Invalid token");
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import { JwtService } from "@nestjs/jwt";
|
||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
import { ClaimRequestManagementDbService } from "src/claim-request-management/entites/db-service/claim-request-management.db.service";
|
||||
import { Types } from "mongoose";
|
||||
import { ActorAuthService } from "src/auth/auth-services/actor.auth.service";
|
||||
|
||||
/**
|
||||
* Guard that allows:
|
||||
@@ -20,6 +21,7 @@ export class ClaimAccessGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly claimDbService: ClaimRequestManagementDbService,
|
||||
private readonly actorAuthService: ActorAuthService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
@@ -33,6 +35,7 @@ export class ClaimAccessGuard implements CanActivate {
|
||||
const payload = await this.jwtService.verifyAsync(token, {
|
||||
secret: `${process.env.JWT_SECRET}`,
|
||||
});
|
||||
await this.actorAuthService.assertActorActive(payload);
|
||||
|
||||
// Allow users to pass through (they will be checked by service methods)
|
||||
if (payload.role === RoleEnum.USER) {
|
||||
|
||||
@@ -7,18 +7,22 @@ import {
|
||||
import { JwtService } from "@nestjs/jwt";
|
||||
import { Request } from "express";
|
||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
import { ActorAuthService } from "src/auth/auth-services/actor.auth.service";
|
||||
|
||||
const GLOBAL_GUARD_ROLES = new Set<string>([
|
||||
RoleEnum.USER,
|
||||
RoleEnum.FIELD_EXPERT,
|
||||
RoleEnum.REGISTRAR,
|
||||
RoleEnum.FILE_MAKER,
|
||||
RoleEnum.FILE_REVIEWER
|
||||
RoleEnum.FILE_REVIEWER,
|
||||
]);
|
||||
|
||||
@Injectable()
|
||||
export class GlobalGuard implements CanActivate {
|
||||
constructor(private readonly jwtService: JwtService) {}
|
||||
constructor(
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly actorAuthService: ActorAuthService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
@@ -39,6 +43,7 @@ export class GlobalGuard implements CanActivate {
|
||||
);
|
||||
}
|
||||
|
||||
await this.actorAuthService.assertActorActive(payload);
|
||||
request.user = payload;
|
||||
request.identity = request.user;
|
||||
} catch (error) {
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
} from "@nestjs/common";
|
||||
import { JwtService } from "@nestjs/jwt";
|
||||
import { Request } from "express";
|
||||
import { ActorAuthService } from "src/auth/auth-services/actor.auth.service";
|
||||
|
||||
/**
|
||||
* Verifies Bearer JWT for platform settings routes. Does not restrict by role;
|
||||
@@ -13,7 +14,10 @@ import { Request } from "express";
|
||||
*/
|
||||
@Injectable()
|
||||
export class SettingsJwtGuard implements CanActivate {
|
||||
constructor(private readonly jwtService: JwtService) {}
|
||||
constructor(
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly actorAuthService: ActorAuthService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
@@ -26,10 +30,12 @@ export class SettingsJwtGuard implements CanActivate {
|
||||
const payload = await this.jwtService.verifyAsync(token, {
|
||||
secret: `${process.env.JWT_SECRET}`,
|
||||
});
|
||||
await this.actorAuthService.assertActorActive(payload);
|
||||
(request as any).user = payload;
|
||||
(request as any).identity = payload;
|
||||
return true;
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (error instanceof UnauthorizedException) throw error;
|
||||
throw new UnauthorizedException("Invalid token");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,10 +7,14 @@ import {
|
||||
import { JwtService } from "@nestjs/jwt";
|
||||
import { Request } from "express";
|
||||
import { JwtPayload } from "../types/payload.types";
|
||||
import { ActorAuthService } from "src/auth/auth-services/actor.auth.service";
|
||||
|
||||
@Injectable()
|
||||
export class AuthGuard implements CanActivate {
|
||||
constructor(private readonly jwtService: JwtService) {}
|
||||
constructor(
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly actorAuthService: ActorAuthService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
@@ -19,12 +23,16 @@ export class AuthGuard implements CanActivate {
|
||||
throw new UnauthorizedException("No token provided");
|
||||
}
|
||||
try {
|
||||
const payload: JwtPayload =
|
||||
await this.jwtService.verifyAsync<JwtPayload>(token, {
|
||||
const payload: JwtPayload = await this.jwtService.verifyAsync<JwtPayload>(
|
||||
token,
|
||||
{
|
||||
secret: `${process.env.JWT_SECRET}`,
|
||||
});
|
||||
},
|
||||
);
|
||||
await this.actorAuthService.assertActorActive(payload);
|
||||
request["user"] = payload;
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (error instanceof UnauthorizedException) throw error;
|
||||
throw new UnauthorizedException("Invalid or expired token");
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -2016,26 +2016,11 @@ export class ExpertInsurerService {
|
||||
);
|
||||
|
||||
const email = payload.email.trim().toLowerCase();
|
||||
const existingByEmail = await this.expertDbService.findOne({ email });
|
||||
const existingDamageByEmail = await this.damageExpertDbService.findOne({
|
||||
email,
|
||||
});
|
||||
if (existingByEmail || existingDamageByEmail) {
|
||||
throw new ConflictException("An expert with this email already exists.");
|
||||
}
|
||||
|
||||
const nationalCode = payload.nationalCode.trim();
|
||||
const existingByNational = await this.expertDbService.findOne({
|
||||
nationalCode,
|
||||
});
|
||||
const existingDamageByNational = await this.damageExpertDbService.findOne({
|
||||
nationalCode,
|
||||
});
|
||||
if (existingByNational || existingDamageByNational) {
|
||||
throw new ConflictException(
|
||||
"An expert with this national code already exists.",
|
||||
);
|
||||
}
|
||||
const repository = role === RoleEnum.EXPERT
|
||||
? this.expertDbService : this.damageExpertDbService;
|
||||
if (await repository.findOne({ $or: [{ email }, { nationalCode }] }))
|
||||
throw new ConflictException("این ایمیل یا کد ملی قبلاً برای همین نقش ثبت شده است.");
|
||||
|
||||
const hashedPassword = await this.hashService.hash(payload.password);
|
||||
const locations = this.normalizeExpertLocations(payload.locations);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { ProfileController } from "./profile.controller";
|
||||
import { ProfileService } from "./profile.service";
|
||||
import { JwtService } from "@nestjs/jwt";
|
||||
import { ActorAuthService } from "src/auth/auth-services/actor.auth.service";
|
||||
|
||||
describe("ProfileController", () => {
|
||||
let controller: ProfileController;
|
||||
@@ -12,6 +13,7 @@ describe("ProfileController", () => {
|
||||
providers: [
|
||||
{ provide: ProfileService, useValue: {} },
|
||||
{ provide: JwtService, useValue: {} },
|
||||
{ provide: ActorAuthService, useValue: Object.create(ActorAuthService.prototype) },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
|
||||
@@ -10,6 +10,133 @@ import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-
|
||||
import { ClaimWorkflowStep } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum";
|
||||
|
||||
describe("RequestManagementService V4 FileMaker workflow", () => {
|
||||
it.each([
|
||||
[4, BlameRequestType.CAR_BODY],
|
||||
[4, BlameRequestType.THIRD_PARTY],
|
||||
[5, BlameRequestType.CAR_BODY],
|
||||
[5, BlameRequestType.THIRD_PARTY],
|
||||
])(
|
||||
"completes v%s %s narratives and signatures without voice",
|
||||
async (flow, type) => {
|
||||
const actor = {
|
||||
sub: String(new Types.ObjectId()),
|
||||
role: RoleEnum.FILE_MAKER,
|
||||
};
|
||||
const request: any = {
|
||||
_id: new Types.ObjectId(),
|
||||
type,
|
||||
expertInitiated: true,
|
||||
isMadeByFileMaker: true,
|
||||
requiresFileMakerApproval: flow === 5,
|
||||
initiatedByFieldExpertId: new Types.ObjectId(actor.sub),
|
||||
creationMethod: CreationMethod.IN_PERSON,
|
||||
status: CaseStatus.OPEN,
|
||||
parties: [
|
||||
PartyRole.FIRST,
|
||||
...(type === BlameRequestType.THIRD_PARTY ? [PartyRole.SECOND] : []),
|
||||
].map((role) => ({
|
||||
role,
|
||||
person: { userId: new Types.ObjectId() },
|
||||
evidence: {},
|
||||
})),
|
||||
workflow: {
|
||||
currentStep: WorkflowStep.FIRST_INITIAL_FORM,
|
||||
completedSteps: [],
|
||||
},
|
||||
history: [],
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const service: any = new (RequestManagementService as any)();
|
||||
service.verifyExpertAccessForBlameV2 = jest
|
||||
.fn()
|
||||
.mockResolvedValue(undefined);
|
||||
service.blameRequestDbService = {
|
||||
findById: async () => request,
|
||||
findByIdAndUpdate: async (_id, update) => {
|
||||
for (const [key, value] of Object.entries(update.$set)) {
|
||||
const [, index] = key.split(".");
|
||||
request.parties[Number(index)].confirmation = value;
|
||||
}
|
||||
},
|
||||
};
|
||||
service.userSign = {
|
||||
create: jest.fn(async () => ({ _id: new Types.ObjectId() })),
|
||||
};
|
||||
service.blameVoiceDbService = { create: jest.fn() };
|
||||
for (const party of request.parties) {
|
||||
service.markPartyInquiriesCompleteOnBlame(request, party.role, actor);
|
||||
const prefix = party.role === PartyRole.FIRST ? "FIRST" : "SECOND";
|
||||
expect(request.workflow.currentStep).toBe(`${prefix}_DESCRIPTION`);
|
||||
const description = {
|
||||
desc: "شرح حادثه ".repeat(15),
|
||||
accidentDate: "2025-01-01",
|
||||
accidentTime: "10:30",
|
||||
};
|
||||
if (flow === 4)
|
||||
await service.addPartyDescriptionV4(
|
||||
String(request._id),
|
||||
actor,
|
||||
description,
|
||||
party.role,
|
||||
);
|
||||
else
|
||||
await service.addPartyDescriptionV3(
|
||||
String(request._id),
|
||||
actor,
|
||||
description,
|
||||
party.role,
|
||||
);
|
||||
expect(request.workflow.currentStep).toBe(`${prefix}_SIGN`);
|
||||
await service.expertUploadPartySignatureV3(
|
||||
actor,
|
||||
String(request._id),
|
||||
party.role,
|
||||
true,
|
||||
{ filename: "signature.png", path: "files/signature.png" },
|
||||
);
|
||||
expect(party.confirmation.accepted).toBe(true);
|
||||
expect(request.workflow.completedSteps).not.toContain(
|
||||
`${prefix}_VOICE`,
|
||||
);
|
||||
}
|
||||
expect(service.blameVoiceDbService.create).not.toHaveBeenCalled();
|
||||
expect(request.workflow.currentStep).toBe(
|
||||
type === BlameRequestType.CAR_BODY
|
||||
? WorkflowStep.FIRST_COMPLETED
|
||||
: WorkflowStep.SECOND_COMPLETED,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([WorkflowStep.FIRST_VOICE, WorkflowStep.SECOND_VOICE])(
|
||||
"repairs legacy %s resume values without erasing existing recordings or history",
|
||||
(step) => {
|
||||
const service: any = new (RequestManagementService as any)();
|
||||
const file = {
|
||||
workflow: {
|
||||
currentStep: step,
|
||||
nextStep: step.replace("VOICE", "DESCRIPTION"),
|
||||
completedSteps: [step],
|
||||
},
|
||||
parties: [{ evidence: { voices: ["existing-recording"] } }],
|
||||
history: [{ type: "V3_PARTY_VOICE_UPLOADED" }],
|
||||
};
|
||||
const before = JSON.stringify(file);
|
||||
expect(service.fileMakerWorkflowProjection(file).currentStep).toBe(
|
||||
step.replace("VOICE", "DESCRIPTION"),
|
||||
);
|
||||
expect(service.fileMakerWorkflowProjection(file).nextStep).toBe(step.replace("VOICE", "SIGN"));
|
||||
expect(JSON.stringify(file)).toBe(before);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps voice in the non-FileMaker in-person inquiry workflow", () => {
|
||||
const service: any = new (RequestManagementService as any)();
|
||||
const request: any = { workflow: { completedSteps: [] }, parties: [] };
|
||||
service.markPartyInquiriesCompleteOnBlame(request, PartyRole.FIRST, {});
|
||||
expect(request.workflow.currentStep).toBe(WorkflowStep.FIRST_LOCATION);
|
||||
expect(request.workflow.nextStep).toBe(WorkflowStep.FIRST_VOICE);
|
||||
});
|
||||
it("persists FIRST_INITIAL_FORM after the first party OTP is verified", async () => {
|
||||
const fileMakerId = new Types.ObjectId();
|
||||
const userId = new Types.ObjectId();
|
||||
@@ -87,7 +214,7 @@ describe("RequestManagementService V4 FileMaker workflow", () => {
|
||||
|
||||
expect(request.workflow.currentStep).toBe(WorkflowStep.FIRST_INITIAL_FORM);
|
||||
expect(request.workflow.currentStep).not.toBe(WorkflowStep.FIRST_VIDEO);
|
||||
expect(request.workflow.nextStep).toBe(WorkflowStep.FIRST_VOICE);
|
||||
expect(request.workflow.nextStep).toBe(WorkflowStep.FIRST_DESCRIPTION);
|
||||
expect(request.workflow.completedSteps).not.toContain(
|
||||
WorkflowStep.FIRST_VIDEO,
|
||||
);
|
||||
@@ -169,7 +296,7 @@ describe("RequestManagementService V4 FileMaker workflow", () => {
|
||||
);
|
||||
|
||||
expect(request.workflow.currentStep).toBe(WorkflowStep.FIRST_INITIAL_FORM);
|
||||
expect(request.workflow.nextStep).toBe(WorkflowStep.FIRST_VOICE);
|
||||
expect(request.workflow.nextStep).toBe(WorkflowStep.FIRST_DESCRIPTION);
|
||||
expect(request.workflow.completedSteps).not.toContain(
|
||||
WorkflowStep.FIRST_VIDEO,
|
||||
);
|
||||
@@ -212,7 +339,7 @@ describe("RequestManagementService V4 FileMaker workflow", () => {
|
||||
expect(reopened.workflow).toEqual(
|
||||
expect.objectContaining({
|
||||
currentStep: WorkflowStep.FIRST_INITIAL_FORM,
|
||||
nextStep: WorkflowStep.FIRST_VOICE,
|
||||
nextStep: WorkflowStep.FIRST_DESCRIPTION,
|
||||
}),
|
||||
);
|
||||
expect(reopened.workflow.completedSteps).not.toContain(
|
||||
|
||||
@@ -31,7 +31,10 @@ import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
import { CreationMethod } from "./entities/schema/request-management.schema";
|
||||
import { CreateExpertInitiatedFileDto } from "./dto/expert-initiated.dto";
|
||||
import { SendPartyOtpDto, VerifyPartyOtpDto } from "./dto/party-otp.dto";
|
||||
import { RunInquiriesV3Dto, RunInquiriesVinV3Dto } from "./dto/run-inquiries-v3.dto";
|
||||
import {
|
||||
RunInquiriesV3Dto,
|
||||
RunInquiriesVinV3Dto,
|
||||
} from "./dto/run-inquiries-v3.dto";
|
||||
import {
|
||||
CarBodyFormDto,
|
||||
DescriptionV4Dto,
|
||||
@@ -57,11 +60,11 @@ import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto";
|
||||
* THIRD_PARTY sequence:
|
||||
* create → send-party-otp (guilty) → verify-party-otp (guilty)
|
||||
* → [car-body-form if CAR_BODY] → run-inquiries (guilty + auto claim)
|
||||
* → add-detail-location / add-detail-description / upload-voice (guilty)
|
||||
* → add-detail-description (voice optional) (guilty)
|
||||
* → sign (guilty)
|
||||
* → send-party-otp (damaged) → verify-party-otp (damaged)
|
||||
* → run-inquiries (damaged)
|
||||
* → add-detail-location / add-detail-description / upload-voice (damaged)
|
||||
* → add-detail-description (voice optional) (damaged)
|
||||
* → sign (damaged) ← FileMaker job done here
|
||||
*
|
||||
* CAR_BODY sequence: same but single party — omit second-party steps.
|
||||
@@ -91,14 +94,19 @@ export class FileMakerBlameV4Controller {
|
||||
fileMaker,
|
||||
// requiresFileMakerApproval is V5-only; explicitly exclude it from V4 so
|
||||
// a client that accidentally sends the field cannot poison the blame record.
|
||||
{ ...dto, creationMethod: CreationMethod.IN_PERSON, requiresFileMakerApproval: false },
|
||||
{
|
||||
...dto,
|
||||
creationMethod: CreationMethod.IN_PERSON,
|
||||
requiresFileMakerApproval: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@Get("my-files")
|
||||
@ApiOperation({
|
||||
summary: "List all blame files created by this FileMaker",
|
||||
description: "Returns V4 FileMaker blame files using the shared search, sort, filter, and pagination query contract.",
|
||||
description:
|
||||
"Returns V4 FileMaker blame files using the shared search, sort, filter, and pagination query contract.",
|
||||
})
|
||||
async getMyFiles(
|
||||
@CurrentUser() fileMaker: any,
|
||||
@@ -111,13 +119,17 @@ export class FileMakerBlameV4Controller {
|
||||
@ApiParam({ name: "requestId", description: "Blame request ID" })
|
||||
@ApiOperation({
|
||||
summary: "Get a single blame file created by this FileMaker",
|
||||
description: "Returns full detail — parties, workflow, linked claim ID — for one V4 FileMaker blame file.",
|
||||
description:
|
||||
"Returns full detail — parties, workflow, linked claim ID — for one V4 FileMaker blame file.",
|
||||
})
|
||||
async getMyFileDetail(
|
||||
@Param("requestId") requestId: string,
|
||||
@CurrentUser() fileMaker: any,
|
||||
) {
|
||||
return this.requestManagementService.getMyFileMakerFileDetail(fileMaker, requestId);
|
||||
return this.requestManagementService.getMyFileMakerFileDetail(
|
||||
fileMaker,
|
||||
requestId,
|
||||
);
|
||||
}
|
||||
|
||||
@Get("claim-id/:requestId")
|
||||
@@ -312,7 +324,7 @@ export class FileMakerBlameV4Controller {
|
||||
)
|
||||
@Post("upload-voice/:requestId")
|
||||
@ApiParam({ name: "requestId" })
|
||||
@ApiOperation({ summary: "Upload voice for current party" })
|
||||
@ApiOperation({ summary: "Upload optional voice for current party" })
|
||||
async uploadVoice(
|
||||
@Param("requestId") requestId: string,
|
||||
@CurrentUser() fileMaker: any,
|
||||
|
||||
@@ -31,7 +31,10 @@ import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
import { CreationMethod } from "./entities/schema/request-management.schema";
|
||||
import { CreateExpertInitiatedFileDto } from "./dto/expert-initiated.dto";
|
||||
import { SendPartyOtpDto, VerifyPartyOtpDto } from "./dto/party-otp.dto";
|
||||
import { RunInquiriesV3Dto, RunInquiriesVinV3Dto } from "./dto/run-inquiries-v3.dto";
|
||||
import {
|
||||
RunInquiriesV3Dto,
|
||||
RunInquiriesVinV3Dto,
|
||||
} from "./dto/run-inquiries-v3.dto";
|
||||
import {
|
||||
CarBodyFormDto,
|
||||
DescriptionDto,
|
||||
@@ -60,11 +63,11 @@ import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto";
|
||||
* THIRD_PARTY sequence:
|
||||
* create → send-party-otp (guilty) → verify-party-otp (guilty)
|
||||
* → [car-body-form if CAR_BODY] → run-inquiries (guilty + auto claim)
|
||||
* → add-detail-location / add-detail-description / upload-voice (guilty)
|
||||
* → add-detail-description (voice optional) (guilty)
|
||||
* → sign (guilty)
|
||||
* → send-party-otp (damaged) → verify-party-otp (damaged)
|
||||
* → run-inquiries (damaged)
|
||||
* → add-detail-location / add-detail-description / upload-voice (damaged)
|
||||
* → add-detail-description (voice optional) (damaged)
|
||||
* → sign (damaged) ← FileMaker job done here
|
||||
*/
|
||||
@ApiTags("v5 FileMaker — blame file creation (with FinancialExpert approval)")
|
||||
@@ -90,14 +93,19 @@ export class FileMakerBlameV5Controller {
|
||||
) {
|
||||
return this.requestManagementService.createExpertInitiatedBlameV2(
|
||||
fileMaker,
|
||||
{ ...dto, creationMethod: CreationMethod.IN_PERSON, requiresFileMakerApproval: true },
|
||||
{
|
||||
...dto,
|
||||
creationMethod: CreationMethod.IN_PERSON,
|
||||
requiresFileMakerApproval: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@Get("my-files")
|
||||
@ApiOperation({
|
||||
summary: "List all blame files created by this FileMaker",
|
||||
description: "Returns V5 FileMaker blame files using the shared search, sort, filter, and pagination query contract.",
|
||||
description:
|
||||
"Returns V5 FileMaker blame files using the shared search, sort, filter, and pagination query contract.",
|
||||
})
|
||||
async getMyFiles(
|
||||
@CurrentUser() fileMaker: any,
|
||||
@@ -110,13 +118,17 @@ export class FileMakerBlameV5Controller {
|
||||
@ApiParam({ name: "requestId", description: "Blame request ID" })
|
||||
@ApiOperation({
|
||||
summary: "Get a single blame file created by this FileMaker",
|
||||
description: "Returns full detail — parties, workflow, linked claim ID — for one V5 FileMaker blame file.",
|
||||
description:
|
||||
"Returns full detail — parties, workflow, linked claim ID — for one V5 FileMaker blame file.",
|
||||
})
|
||||
async getMyFileDetail(
|
||||
@Param("requestId") requestId: string,
|
||||
@CurrentUser() fileMaker: any,
|
||||
) {
|
||||
return this.requestManagementService.getMyFileMakerFileDetail(fileMaker, requestId);
|
||||
return this.requestManagementService.getMyFileMakerFileDetail(
|
||||
fileMaker,
|
||||
requestId,
|
||||
);
|
||||
}
|
||||
|
||||
@Get("claim-id/:requestId")
|
||||
@@ -306,7 +318,7 @@ export class FileMakerBlameV5Controller {
|
||||
)
|
||||
@Post("upload-voice/:requestId")
|
||||
@ApiParam({ name: "requestId" })
|
||||
@ApiOperation({ summary: "Upload voice for current party" })
|
||||
@ApiOperation({ summary: "Upload optional voice for current party" })
|
||||
async uploadVoice(
|
||||
@Param("requestId") requestId: string,
|
||||
@CurrentUser() fileMaker: any,
|
||||
|
||||
@@ -4261,7 +4261,7 @@ export class RequestManagementService {
|
||||
if (isFileMakerFlow) {
|
||||
advancedTo = WorkflowStep.FIRST_INITIAL_FORM;
|
||||
req.workflow.currentStep = advancedTo;
|
||||
req.workflow.nextStep = WorkflowStep.FIRST_VOICE;
|
||||
req.workflow.nextStep = WorkflowStep.FIRST_DESCRIPTION;
|
||||
} else {
|
||||
const step3 = await this.getWorkflowStep({ stepNumber: 3 }); // FIRST_VIDEO
|
||||
advancedTo = step3.stepKey as WorkflowStep;
|
||||
@@ -7089,10 +7089,10 @@ export class RequestManagementService {
|
||||
: [WorkflowStep.CREATED, WorkflowStep.FIRST_INITIAL_FORM];
|
||||
this.pushWorkflowSteps(req, completedSteps);
|
||||
req.workflow.currentStep = skipLocation
|
||||
? WorkflowStep.FIRST_VOICE
|
||||
? WorkflowStep.FIRST_DESCRIPTION
|
||||
: WorkflowStep.FIRST_LOCATION;
|
||||
req.workflow.nextStep = skipLocation
|
||||
? WorkflowStep.FIRST_DESCRIPTION
|
||||
? WorkflowStep.FIRST_SIGN
|
||||
: WorkflowStep.FIRST_VOICE;
|
||||
|
||||
const firstIdx = this.getPartyIndex(req, PartyRole.FIRST);
|
||||
@@ -7113,14 +7113,28 @@ export class RequestManagementService {
|
||||
: [WorkflowStep.SECOND_INITIAL_FORM];
|
||||
this.pushWorkflowSteps(req, completedSteps);
|
||||
req.workflow.currentStep = skipLocation
|
||||
? WorkflowStep.SECOND_VOICE
|
||||
? WorkflowStep.SECOND_DESCRIPTION
|
||||
: WorkflowStep.SECOND_LOCATION;
|
||||
req.workflow.nextStep = skipLocation
|
||||
? WorkflowStep.SECOND_DESCRIPTION
|
||||
? WorkflowStep.SECOND_SIGN
|
||||
: WorkflowStep.SECOND_VOICE;
|
||||
}
|
||||
}
|
||||
|
||||
private completeFileMakerPartyDescription(req: any, role: PartyRole): void {
|
||||
if (!req.isMadeByFileMaker) return;
|
||||
const firstParty = role === PartyRole.FIRST;
|
||||
this.pushWorkflowSteps(req, [
|
||||
firstParty ? WorkflowStep.FIRST_DESCRIPTION : WorkflowStep.SECOND_DESCRIPTION,
|
||||
]);
|
||||
req.workflow.currentStep = firstParty
|
||||
? WorkflowStep.FIRST_SIGN
|
||||
: WorkflowStep.SECOND_SIGN;
|
||||
req.workflow.nextStep = firstParty
|
||||
? WorkflowStep.FIRST_COMPLETED
|
||||
: WorkflowStep.SECOND_COMPLETED;
|
||||
}
|
||||
|
||||
private async createV3ClaimFromBlame(
|
||||
req: any,
|
||||
actor: any,
|
||||
@@ -8109,7 +8123,7 @@ export class RequestManagementService {
|
||||
if (partyRole === PartyRole.FIRST) {
|
||||
this.pushWorkflowSteps(fresh, [
|
||||
WorkflowStep.FIRST_LOCATION,
|
||||
WorkflowStep.FIRST_VOICE,
|
||||
...(isFileMakerActor ? [] : [WorkflowStep.FIRST_VOICE]),
|
||||
WorkflowStep.FIRST_DESCRIPTION,
|
||||
WorkflowStep.FIRST_SIGN,
|
||||
WorkflowStep.FIRST_COMPLETED,
|
||||
@@ -8127,7 +8141,7 @@ export class RequestManagementService {
|
||||
} else {
|
||||
this.pushWorkflowSteps(fresh, [
|
||||
WorkflowStep.SECOND_LOCATION,
|
||||
WorkflowStep.SECOND_VOICE,
|
||||
...(isFileMakerActor ? [] : [WorkflowStep.SECOND_VOICE]),
|
||||
WorkflowStep.SECOND_DESCRIPTION,
|
||||
WorkflowStep.SECOND_SIGN,
|
||||
WorkflowStep.SECOND_COMPLETED,
|
||||
@@ -8559,6 +8573,8 @@ export class RequestManagementService {
|
||||
metadata: { partyRole: role },
|
||||
} as any);
|
||||
|
||||
this.completeFileMakerPartyDescription(req, role);
|
||||
|
||||
await (req as any).save();
|
||||
return { requestId: req._id, publicId: req.publicId, partyRole: role };
|
||||
}
|
||||
@@ -8630,6 +8646,8 @@ export class RequestManagementService {
|
||||
},
|
||||
} as any);
|
||||
|
||||
this.completeFileMakerPartyDescription(req, role);
|
||||
|
||||
await (req as any).save();
|
||||
return { requestId: req._id, publicId: req.publicId, partyRole: role };
|
||||
}
|
||||
@@ -8670,7 +8688,7 @@ export class RequestManagementService {
|
||||
this.pushWorkflowSteps(req, [WorkflowStep.CAR_BODY_ACCIDENT_TYPE]);
|
||||
if ((req as any).isMadeByFileMaker) {
|
||||
req.workflow.currentStep = WorkflowStep.FIRST_INITIAL_FORM;
|
||||
req.workflow.nextStep = WorkflowStep.FIRST_VOICE;
|
||||
req.workflow.nextStep = WorkflowStep.FIRST_DESCRIPTION;
|
||||
} else {
|
||||
req.workflow.currentStep = WorkflowStep.CAR_BODY_ACCIDENT_TYPE;
|
||||
req.workflow.nextStep = WorkflowStep.FIRST_INITIAL_FORM;
|
||||
@@ -9678,7 +9696,7 @@ export class RequestManagementService {
|
||||
return {
|
||||
...workflow,
|
||||
currentStep: WorkflowStep.FIRST_INITIAL_FORM,
|
||||
nextStep: WorkflowStep.FIRST_VOICE,
|
||||
nextStep: WorkflowStep.FIRST_DESCRIPTION,
|
||||
completedSteps,
|
||||
};
|
||||
}
|
||||
@@ -9695,7 +9713,18 @@ export class RequestManagementService {
|
||||
};
|
||||
}
|
||||
|
||||
return { ...workflow, completedSteps };
|
||||
const withoutVoice = (step: WorkflowStep) => {
|
||||
if (step === WorkflowStep.FIRST_VOICE) return WorkflowStep.FIRST_DESCRIPTION;
|
||||
if (step === WorkflowStep.SECOND_VOICE) return WorkflowStep.SECOND_DESCRIPTION;
|
||||
return step;
|
||||
};
|
||||
const currentStep = withoutVoice(workflow.currentStep);
|
||||
let nextStep = withoutVoice(workflow.nextStep);
|
||||
if (currentStep === WorkflowStep.FIRST_DESCRIPTION && nextStep === currentStep)
|
||||
nextStep = WorkflowStep.FIRST_SIGN;
|
||||
if (currentStep === WorkflowStep.SECOND_DESCRIPTION && nextStep === currentStep)
|
||||
nextStep = WorkflowStep.SECOND_SIGN;
|
||||
return { ...workflow, currentStep, nextStep, completedSteps };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -29,7 +29,9 @@ export class CallCenterAgentDbService {
|
||||
async findByLoginIdentifier(
|
||||
identifier: string,
|
||||
): Promise<CallCenterAgentModel | null> {
|
||||
const id = identifier.trim();
|
||||
const id = identifier.includes("@")
|
||||
? identifier.trim().toLowerCase()
|
||||
: identifier.trim();
|
||||
const or: FilterQuery<CallCenterAgentModel>[] = [
|
||||
{ email: id },
|
||||
{ username: id },
|
||||
|
||||
@@ -25,7 +25,9 @@ export class FieldExpertDbService {
|
||||
async findByLoginIdentifier(
|
||||
identifier: string,
|
||||
): Promise<FieldExpertModel | null> {
|
||||
const id = identifier.trim();
|
||||
const id = identifier.includes("@")
|
||||
? identifier.trim().toLowerCase()
|
||||
: identifier.trim();
|
||||
const or: FilterQuery<FieldExpertModel>[] = [
|
||||
{ email: id },
|
||||
{ username: id },
|
||||
|
||||
@@ -25,7 +25,9 @@ export class FileMakerDbService {
|
||||
async findByLoginIdentifier(
|
||||
identifier: string,
|
||||
): Promise<FileMakerModel | null> {
|
||||
const id = identifier.trim();
|
||||
const id = identifier.includes("@")
|
||||
? identifier.trim().toLowerCase()
|
||||
: identifier.trim();
|
||||
const or: FilterQuery<FileMakerModel>[] = [{ email: id }, { username: id }];
|
||||
if (/^\d{10}$/.test(id)) {
|
||||
or.push({ nationalCode: id });
|
||||
|
||||
@@ -25,7 +25,9 @@ export class FileReviewerDbService {
|
||||
async findByLoginIdentifier(
|
||||
identifier: string,
|
||||
): Promise<FileReviewerModel | null> {
|
||||
const id = identifier.trim();
|
||||
const id = identifier.includes("@")
|
||||
? identifier.trim().toLowerCase()
|
||||
: identifier.trim();
|
||||
const or: FilterQuery<FileReviewerModel>[] = [
|
||||
{ email: id },
|
||||
{ username: id },
|
||||
|
||||
@@ -14,6 +14,9 @@ import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
export class CallCenterAgentModel {
|
||||
_id?: Types.ObjectId;
|
||||
|
||||
@Prop({ type: Boolean, default: true })
|
||||
isActive?: boolean;
|
||||
|
||||
@Prop({ required: true })
|
||||
firstName: string;
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
import { UserType } from "src/Types&Enums/userType.enum";
|
||||
|
||||
|
||||
@Schema({ _id: false, versionKey: false })
|
||||
export class DamageExpertLocationModel {
|
||||
@Prop({ type: String, required: true })
|
||||
@@ -100,6 +99,9 @@ const FinancialInfoSchema = SchemaFactory.createForClass(FinancialInfo);
|
||||
|
||||
@Schema({ collection: "damage-expert", versionKey: false, timestamps: true })
|
||||
export class DamageExpertModel {
|
||||
@Prop({ type: Boolean, default: true })
|
||||
isActive?: boolean;
|
||||
|
||||
@Prop({ required: true })
|
||||
userType: UserType;
|
||||
|
||||
@@ -115,8 +117,8 @@ export class DamageExpertModel {
|
||||
@Prop({ unique: true })
|
||||
nationalCode: string;
|
||||
|
||||
@Prop({ type: "string", unique: true })
|
||||
email: string;
|
||||
@Prop({ type: String, unique: true, sparse: true })
|
||||
email?: string;
|
||||
|
||||
@Prop({ type: "string" })
|
||||
username: string;
|
||||
@@ -124,8 +126,8 @@ export class DamageExpertModel {
|
||||
@Prop({ required: true })
|
||||
password: string;
|
||||
|
||||
@Prop({ required: true })
|
||||
mobile: string;
|
||||
@Prop({ required: false })
|
||||
mobile?: string;
|
||||
|
||||
@Prop({ required: false })
|
||||
phone?: string;
|
||||
@@ -175,7 +177,7 @@ export class DamageExpertModel {
|
||||
@Prop({ type: "string" })
|
||||
city: string;
|
||||
|
||||
@Prop({type: "string", required: false})
|
||||
@Prop({ type: "string", required: false })
|
||||
expertCode?: string;
|
||||
|
||||
@Prop({ type: String, required: false })
|
||||
@@ -198,7 +200,7 @@ export const DamageExpertDbSchema =
|
||||
|
||||
DamageExpertDbSchema.pre("save", function (next) {
|
||||
if (!this.username) {
|
||||
this.username = this.email;
|
||||
this.username = this.email || this.nationalCode;
|
||||
}
|
||||
next();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -18,6 +18,9 @@ export const ExpertLocationDbSchema =
|
||||
|
||||
@Schema({ collection: "expert", versionKey: false, timestamps: true })
|
||||
export class ExpertModel {
|
||||
@Prop({ type: Boolean, default: true })
|
||||
isActive?: boolean;
|
||||
|
||||
@Prop({})
|
||||
firstName: string;
|
||||
|
||||
@@ -87,7 +90,7 @@ export class ExpertModel {
|
||||
@Prop({ type: "string" })
|
||||
otp: string;
|
||||
|
||||
@Prop({type: "string", required: false})
|
||||
@Prop({ type: "string", required: false })
|
||||
expertCode?: string;
|
||||
|
||||
@Prop({ type: String, required: false })
|
||||
|
||||
@@ -23,6 +23,9 @@ export const FieldExpertLocationDbSchema = SchemaFactory.createForClass(
|
||||
export class FieldExpertModel {
|
||||
_id?: Types.ObjectId;
|
||||
|
||||
@Prop({ type: Boolean, default: true })
|
||||
isActive?: boolean;
|
||||
|
||||
@Prop({ required: true })
|
||||
firstName: string;
|
||||
|
||||
@@ -71,7 +74,7 @@ export class FieldExpertModel {
|
||||
@Prop({ type: "string", default: "" })
|
||||
otp: string;
|
||||
|
||||
@Prop({type: "string", required: false})
|
||||
@Prop({ type: "string", required: false })
|
||||
expertCode?: string;
|
||||
|
||||
@Prop({ type: String, required: false })
|
||||
|
||||
@@ -23,6 +23,9 @@ export const FileMakerLocationDbSchema = SchemaFactory.createForClass(
|
||||
export class FileMakerModel {
|
||||
_id?: Types.ObjectId;
|
||||
|
||||
@Prop({ type: Boolean, default: true })
|
||||
isActive?: boolean;
|
||||
|
||||
@Prop({ required: true })
|
||||
firstName: string;
|
||||
|
||||
|
||||
@@ -23,6 +23,9 @@ export const FileReviewerLocationDbSchema = SchemaFactory.createForClass(
|
||||
export class FileReviewerModel {
|
||||
_id?: Types.ObjectId;
|
||||
|
||||
@Prop({ type: Boolean, default: true })
|
||||
isActive?: boolean;
|
||||
|
||||
@Prop({ required: true })
|
||||
firstName: string;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user