fix(api contract): trimmed user blame/claim lists and queues and removing unused data

This commit is contained in:
SepehrYahyaee
2026-10-03 12:11:44 +03:30
parent ecf44011f3
commit 6a724abaf7
31 changed files with 511 additions and 696 deletions
@@ -103,6 +103,7 @@ import {
ClaimListItemV2Dto,
} from "./dto/my-claims-v2.dto";
import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto";
import { toPublicListItems } from "src/helpers/public-list-response";
import {
applyListQueryV2,
isInListDateRange,
@@ -12764,7 +12765,7 @@ export class ClaimRequestManagementService {
);
return {
list: paged.list,
list: toPublicListItems(paged.list),
total: paged.total,
page: paged.page,
limit: paged.limit,
+2 -1
View File
@@ -159,6 +159,7 @@ import {
/** Configured V1 maximum sum of line `totalPayment` across the claim (Rial). */
import { getClaimV2TotalPaymentCapToman } from "src/constants/repair-amount-limits";
import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto";
import { toPublicListItems } from "src/helpers/public-list-response";
import {
UnifiedFileStatusReportDto,
UnifiedFileStatusReportQueryDto,
@@ -4228,7 +4229,7 @@ export class ExpertClaimService {
query,
);
return {
list: paged.list,
list: toPublicListItems(paged.list),
total: paged.total,
page: paged.page,
limit: paged.limit,
-21
View File
@@ -1,21 +0,0 @@
import { Body, Controller, Post } from "@nestjs/common";
import { AuthService } from "./auth.service";
import { Public } from "src/common/auth/decorators";
import { UserLoginDto, UserRegisterDto } from "../user/dtos";
@Controller("auth")
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Public()
@Post("user/send-otp")
async register(@Body() userRegisterDto: UserRegisterDto) {
return await this.authService.registerUser(userRegisterDto);
}
@Public()
@Post("user/login")
async login(@Body() userLoginDto: UserLoginDto) {
return await this.authService.loginUser(userLoginDto);
}
}
-33
View File
@@ -1,33 +0,0 @@
import { Module } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { APP_GUARD } from "@nestjs/core";
import { JwtModule } from "@nestjs/jwt";
import { StringValue } from "ms";
import { AuthGuard, RolesGuard } from "src/common/auth/guards";
import { HashService, OtpService } from "./providers";
import { AuthController } from "./auth.controller";
import { AuthService } from "./auth.service";
@Module({
imports: [
JwtModule.registerAsync({
global: true,
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
secret: configService.get<string>("JWT_SECRET"),
signOptions: {
expiresIn: configService.get<StringValue>("JWT_EXPIRY"),
},
}),
}),
],
controllers: [AuthController],
providers: [
{ provide: APP_GUARD, useClass: AuthGuard },
{ provide: APP_GUARD, useClass: RolesGuard },
AuthService,
HashService,
OtpService,
],
})
export class AuthModule {}
-98
View File
@@ -1,98 +0,0 @@
import {
BadRequestException,
ForbiddenException,
Injectable,
} from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { UserRepository } from "src/features/user/repositories";
import { HashService, OtpService } from "./providers";
import { UserLoginDto, UserRegisterDto } from "../user/dtos";
import { Otp } from "../user/schemas";
import { Environment } from "src/core/config/config.schema";
@Injectable()
export class AuthService {
otpDigits: number;
otpExpiryMinutes: number;
environment: Environment;
constructor(
private readonly userRepo: UserRepository,
private readonly hashService: HashService,
private readonly configService: ConfigService,
private readonly otpService: OtpService,
) {
this.otpDigits = this.configService.get<number>("DEFAULT_OTP_DIGITS") ?? 5;
this.otpExpiryMinutes =
(this.configService.get<number>("DEFAULT_OTP_EXPIRY_MINUTES") ?? 2) * 60;
this.environment = this.configService.get<Environment>("NODE_ENV");
}
async registerUser(dto: UserRegisterDto) {
let user = await this.userRepo.retrieveByCellPhoneNumber(
dto.cellphoneNumber,
);
if (user && new Date() < new Date(user.otp.expiresAt))
throw new BadRequestException("OTP_STILL_VALID");
if (!user) {
user = await this.userRepo.create(dto.cellphoneNumber);
}
const otpCode = this.otpService.generateOtp(this.otpDigits);
const hashedOtp = await this.hashService.hashOtp(otpCode);
const otp: Otp = {
hash: hashedOtp,
expiresAt: new Date(Date.now() + this.otpExpiryMinutes),
};
await this.userRepo.saveOtp(user.cellphoneNumber, otp);
if (this.environment === "development") {
return otpCode;
}
//TODO: Implement Integrations module and integrate with kavenegar, or whatever the provider is
//TODO: Send sms
return {};
}
async loginUser(userLoginDto: UserLoginDto) {
const user = await this.userRepo.retrieveByCellPhoneNumber(
userLoginDto.cellphoneNumber,
);
if (!user) throw new BadRequestException("USER_NOT_FOUND");
const storedOtp = (user as any).otp;
if (!storedOtp) {
throw new BadRequestException("OTP_NOT_REQUESTED");
}
// Check expiry first — don't increment attempts on expired OTP
if (new Date() > new Date(storedOtp.expiresAt)) {
throw new BadRequestException("OTP_EXPIRED");
}
// Check attempt count before verifying — prevent brute force
if (storedOtp.attempts >= this.otpService.maximum_otp_attemps) {
throw new ForbiddenException("OTP_MAX_ATTEMPTS_EXCEEDED");
}
const isValid = await this.hashService.verifyOtp(
userLoginDto.otp,
storedOtp.hash,
);
if (!isValid) {
await this.userRepo.incrementOtpAttempts(userLoginDto.cellphoneNumber);
throw new BadRequestException("OTP_INVALID");
}
// OTP is correct — clear it so it can't be reused
await this.userRepo.clearOtp(userLoginDto.cellphoneNumber);
//TODO: Generate access+refresh token and send it to user
return {};
}
}
@@ -1,167 +0,0 @@
import {
BinaryLike,
randomBytes,
scrypt,
ScryptOptions,
timingSafeEqual,
} from "node:crypto";
import { promisify } from "node:util";
import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import {
CURRENT_ALGORITHM,
CURRENT_VERSION,
KEY_LENGTH,
KEY_LENGTH_FOR_OTP,
SCRYPT_PARAMS,
SCRYPT_PARAMS_FOR_OTP,
} from "src/common/auth/constants";
import { PasswordHash } from "src/common/auth/types";
const scryptAsync = promisify<
BinaryLike,
BinaryLike,
number,
ScryptOptions,
Buffer
>(scrypt);
@Injectable()
export class HashService {
private readonly pepper: string;
private readonly current_alogrithm: string;
private readonly current_version: number;
constructor(private readonly configService: ConfigService) {
this.pepper = this.configService.get<string>("HASH_PEPPER") ?? "";
this.current_alogrithm = CURRENT_ALGORITHM;
this.current_version = CURRENT_VERSION;
}
private applyPepper(input: string): string {
return this.pepper ? `${input}${this.pepper}` : input;
}
private generateSalt(bytes: number = 16): string {
return randomBytes(bytes).toString("hex");
}
private isLegacyPasswordFormat(stored: unknown): stored is string {
return typeof stored === "string" && stored.includes(":");
}
private isVersionedPasswordFormat(stored: unknown): stored is PasswordHash {
return (
typeof stored === "object" &&
stored !== null &&
"hash" in stored &&
"salt" in stored &&
"algorithm" in stored &&
"version" in stored
);
}
private async scrypt(input: string): Promise<[string, string]> {
const salt = this.generateSalt();
const pepperedInput = this.applyPepper(input);
const derived = await scryptAsync(
pepperedInput,
salt,
KEY_LENGTH,
SCRYPT_PARAMS,
);
return [salt, derived.toString("hex")];
}
private async verifyScrypt(
password: string,
salt: string,
hashHex: string,
): Promise<boolean> {
try {
const pepperedInput = this.applyPepper(password);
const derived = await scryptAsync(
pepperedInput,
salt,
KEY_LENGTH,
SCRYPT_PARAMS,
);
const storedBuffer = Buffer.from(hashHex, "hex");
if (derived.length !== storedBuffer.length) return false;
return timingSafeEqual(derived, storedBuffer);
} catch {
return false;
}
}
async needsRehash(stored: string | PasswordHash): Promise<boolean> {
if (this.isLegacyPasswordFormat(stored)) return true;
if (!this.isVersionedPasswordFormat(stored)) return true;
return (
stored.algorithm !== this.current_alogrithm ||
stored.version !== this.current_version
);
}
async hashPassword(password: string): Promise<PasswordHash> {
const [salt, hash] = await this.scrypt(password);
return {
hash,
salt,
algorithm: CURRENT_ALGORITHM,
version: CURRENT_VERSION,
params: { ...SCRYPT_PARAMS, keyLength: KEY_LENGTH },
createdAt: new Date(),
};
}
async verifyPassword(
password: string,
stored: string | PasswordHash,
): Promise<boolean> {
if (this.isLegacyPasswordFormat(stored)) {
const [salt, hash] = stored.split(":");
return this.verifyScrypt(password, salt, hash);
}
if (!this.isVersionedPasswordFormat(stored)) return false;
switch (stored.algorithm) {
case "scrypt":
return this.verifyScrypt(password, stored.salt, stored.hash);
default:
return false;
}
}
async hashOtp(otp: string): Promise<string> {
const salt = this.generateSalt(8);
const derived = await scryptAsync(
otp,
salt,
KEY_LENGTH_FOR_OTP,
SCRYPT_PARAMS_FOR_OTP,
);
return `${salt}:${derived.toString("hex")}`;
}
async verifyOtp(otp: string, stored: string): Promise<boolean> {
const [salt, hashHex] = stored.split(":");
if (!salt || !hashHex) return false;
try {
const derived = await scryptAsync(
otp,
salt,
KEY_LENGTH_FOR_OTP,
SCRYPT_PARAMS_FOR_OTP,
);
const storedBuffer = Buffer.from(hashHex, "hex");
if (derived.length !== storedBuffer.length) return false;
return timingSafeEqual(derived, storedBuffer);
} catch {
return false;
}
}
}
-2
View File
@@ -1,2 +0,0 @@
export { HashService } from "./hash.provider";
export { OtpService } from "./otp.provider";
@@ -1,22 +0,0 @@
import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { Environment } from "src/core/config/config.schema";
@Injectable()
export class OtpService {
maximum_otp_attemps: number;
environment: Environment;
constructor(private readonly configService: ConfigService) {
this.maximum_otp_attemps =
this.configService.get<number>("MAX_OTP_ATTEMPTS");
this.environment = this.configService.get<Environment>("NODE_ENV");
}
generateOtp(digits: number): string {
if (this.environment === "development") {
return this.configService.get<string>("DEFAULT_MOCK_OTP") ?? "11111";
}
return String(Math.floor(Math.random() * 1_000_000)).padStart(digits, "0");
}
}
@@ -1,32 +0,0 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsEmail, IsNotEmpty, IsString } from "class-validator";
export class FieldExpertLoginDto {
@ApiProperty()
@IsEmail({ allow_underscores: true })
@IsString({
message: "email is not string",
context: {
errorCode: 4000,
note: "The validated email type must be string",
},
})
readonly email: string;
@ApiProperty()
@IsNotEmpty({
message: "password is empty",
context: {
errorCode: 4001,
note: "The validated password must not be empty",
},
})
@IsString({
message: "password is not string",
context: {
errorCode: 4002,
note: "The validated password type must be string",
},
})
readonly password: string;
}
@@ -1,17 +0,0 @@
import { Body, Controller, Post } from "@nestjs/common";
import { ApiBearerAuth, ApiExcludeController, ApiTags } from "@nestjs/swagger";
import { FieldExpertLoginDto } from "./dtos/login.dto";
import { FieldExpertService } from "./expert-initiated.service";
@ApiExcludeController()
@Controller("expert-initiated")
@ApiTags("Expert Initiated Flow (Field Expert)")
@ApiBearerAuth()
export class FieldExpertController {
constructor(private readonly fieldExpertService: FieldExpertService) {}
@Post("login")
async login(@Body() fieldExpertLoginDto: FieldExpertLoginDto) {
return await this.fieldExpertService.login(fieldExpertLoginDto);
}
}
@@ -1,25 +0,0 @@
import { Module } from "@nestjs/common";
import { MongooseModule } from "@nestjs/mongoose";
import { FieldExpert, FieldExpertSchema } from "./schemas/field-expert.schema";
import { FieldExpertController } from "./expert-initiated.controller";
import { FieldExpertService } from "./expert-initiated.service";
import { FieldExpertRepository } from "./repositories/field-expert.repository";
import { AuthModule } from "src/auth/auth.module";
import { JwtModule } from "@nestjs/jwt";
@Module({
imports: [
MongooseModule.forFeature([
{
name: FieldExpert.name,
schema: FieldExpertSchema,
},
]),
AuthModule,
JwtModule,
],
controllers: [FieldExpertController],
providers: [FieldExpertRepository, FieldExpertService],
exports: [],
})
export class ExpertInitiatedModule {}
@@ -1,32 +0,0 @@
import {
BadRequestException,
Injectable,
NotFoundException,
} from "@nestjs/common";
import { FieldExpertRepository } from "./repositories/field-expert.repository";
import { FieldExpertLoginDto } from "./dtos/login.dto";
import { UserAuthService } from "src/auth/auth-services/user.auth.service";
@Injectable()
export class FieldExpertService {
constructor(
private readonly fieldExpertRepository: FieldExpertRepository,
private readonly authService: UserAuthService,
) {}
async login(fieldExpertLoginDto: FieldExpertLoginDto) {
const user = await this.fieldExpertRepository.retrieveByEmail(
fieldExpertLoginDto.email,
);
if (!user) throw new NotFoundException("User not found");
const validate = await this.authService.validateUser(
user.email,
user.password,
);
if (!validate)
throw new BadRequestException("Username/Password does not match");
}
}
@@ -1,22 +0,0 @@
import { Injectable } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose";
import { Model } from "mongoose";
import { FieldExpert } from "../schemas/field-expert.schema";
@Injectable()
export class FieldExpertRepository {
constructor(
@InjectModel(FieldExpert.name)
private readonly fieldExpertModel: Model<FieldExpert>,
) {}
async retrieveById(id: string): Promise<FieldExpert> {
return await this.fieldExpertModel.findById(id).exec();
}
async retrieveByEmail(email: string): Promise<FieldExpert> {
return await this.fieldExpertModel.findOne({
email,
});
}
}
@@ -1,27 +0,0 @@
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { HydratedDocument, Types } from "mongoose";
export type FieldExpertDocument = HydratedDocument<FieldExpert>;
@Schema({
id: true,
timestamps: true,
})
export class FieldExpert {
@Prop({ unique: true })
email: string;
@Prop({ required: true })
password: string;
@Prop({ required: true })
firstName: string;
@Prop({ required: true })
lastName: string;
@Prop({ required: true })
cellphone: string;
}
export const FieldExpertSchema = SchemaFactory.createForClass(FieldExpert);
-2
View File
@@ -1,2 +0,0 @@
export { UserRegisterDto } from "./requests/user-register.dto";
export { UserLoginDto } from "./requests/user-login.dto";
@@ -1,16 +0,0 @@
import {
IsMobilePhone,
IsNumberString,
IsString,
Length,
} from "class-validator";
export class UserLoginDto {
@IsString({ message: "Cellphone number must be string" })
@IsMobilePhone("fa-IR")
cellphoneNumber: string;
@IsNumberString()
@Length(4, 6)
otp: string;
}
@@ -1,7 +0,0 @@
import { IsMobilePhone, IsString } from "class-validator";
export class UserRegisterDto {
@IsString({ message: "Cellphone number must be string" })
@IsMobilePhone("fa-IR")
cellphoneNumber: string;
}
-1
View File
@@ -1 +0,0 @@
export { UserRepository } from "./user.repository";
@@ -1,39 +0,0 @@
import { Injectable } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose";
import { Model } from "mongoose";
import { Otp, User } from "../schemas";
@Injectable()
export class UserRepository {
constructor(
@InjectModel(User.name)
private readonly model: Model<User>,
) {}
async create(cellphoneNumber: string): Promise<User> {
return this.model.create({ cellphoneNumber });
}
async retrieveByCellPhoneNumber(
cellphoneNumber: string,
): Promise<User | null> {
return await this.model.findOne({
cellphoneNumber,
});
}
async saveOtp(cellphoneNumber: string, otp: Otp): Promise<void> {
await this.model.updateOne({ cellphoneNumber }, { $set: { otp } });
}
async clearOtp(cellphoneNumber: string): Promise<void> {
await this.model.updateOne({ cellphoneNumber }, { $unset: { otp: "" } });
}
async incrementOtpAttempts(cellphoneNumber: string): Promise<void> {
await this.model.updateOne(
{ cellphoneNumber },
{ $inc: { "otp.attempts": 1 } },
);
}
}
-3
View File
@@ -1,3 +0,0 @@
export { OtpSchema, Otp, OtpDocument } from "./otp.schema";
export { ProfileSchema, Profile, ProfileDocument } from "./profile.schema";
export { UserSchema, User, UserDocument } from "./user.schema";
-21
View File
@@ -1,21 +0,0 @@
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { HydratedDocument } from "mongoose";
export type OtpDocument = HydratedDocument<Otp>;
@Schema({ _id: false })
export class Otp {
@Prop()
hash: string;
@Prop()
expiresAt: Date;
@Prop({ default: 0 })
attempts?: number;
@Prop({ default: Date.now })
generatedAt?: Date;
}
export const OtpSchema = SchemaFactory.createForClass(Otp);
@@ -1,18 +0,0 @@
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { HydratedDocument } from "mongoose";
export type ProfileDocument = HydratedDocument<Profile>;
@Schema({ _id: false })
export class Profile {
@Prop()
firstName?: string;
@Prop()
lastName?: string;
@Prop()
birthDate?: Date;
}
export const ProfileSchema = SchemaFactory.createForClass(Profile);
-22
View File
@@ -1,22 +0,0 @@
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { HydratedDocument, Types } from "mongoose";
import { Otp, OtpSchema, Profile, ProfileSchema } from "./index";
export type UserDocument = HydratedDocument<User>;
@Schema({
id: true,
timestamps: true,
})
export class User {
@Prop({ required: true, unique: true, index: true })
cellphoneNumber: string;
@Prop({ type: OtpSchema })
otp?: Otp;
@Prop({ type: ProfileSchema })
profile?: Profile;
}
export const UserSchema = SchemaFactory.createForClass(User);
-19
View File
@@ -1,19 +0,0 @@
import { Module } from "@nestjs/common";
import { MongooseModule } from "@nestjs/mongoose";
import { UserRepository } from "./repositories";
import { User, UserSchema } from "./schemas";
@Module({
imports: [
MongooseModule.forFeature([
{
name: User.name,
schema: UserSchema,
},
]),
],
controllers: [],
providers: [UserRepository],
exports: [UserRepository],
})
export class UserModule {}
+28
View File
@@ -0,0 +1,28 @@
export type BlameUserNextAction =
| "SIGN"
| "WAIT_FOR_OTHER_SIGNATURE"
| "CREATE_CLAIM"
| "CONTINUE_CLAIM"
| "VIEW_RESULT"
| null;
/** Viewer-specific guidance, without exposing the other party's private data. */
export function resolveBlameUserNextAction(
status: string,
party: { confirmation?: { accepted?: boolean } } | undefined,
claimCreation: { hasClaim: boolean; shouldGuideToCreateClaim: boolean },
): BlameUserNextAction {
if (!party) return null;
if (status === "WAITING_FOR_SIGNATURES") {
return party.confirmation?.accepted === true
? "WAIT_FOR_OTHER_SIGNATURE"
: "SIGN";
}
if (status === "COMPLETED") {
if (claimCreation.shouldGuideToCreateClaim) return "CREATE_CLAIM";
if (claimCreation.hasClaim) return "CONTINUE_CLAIM";
return "VIEW_RESULT";
}
if (status === "STOPPED") return "VIEW_RESULT";
return null;
}
+97
View File
@@ -0,0 +1,97 @@
import { toPublicListItems } from "./public-list-response";
import { applyListQueryV2 } from "./list-query-v2";
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
import { ExpertClaimService } from "src/expert-claim/expert-claim.service";
import { RoleEnum } from "src/Types&Enums/role.enum";
describe("public list payloads", () => {
it("filters full party snapshots before removing them, and preserves locks/workflow fields", () => {
const row = {
publicId: "A100",
status: "EXPERT_REVIEWING",
createdAt: "2026-10-03",
claimRequestId: "claim-id",
currentStep: "EXPERT_COST_EVALUATION",
locked: true,
lockedBy: { actorId: "expert-id" },
partyIdentities: [
{
person: { nationalCode: "1234567890" },
evidence: { secret: "large snapshot" },
},
],
};
const paged = applyListQueryV2(
[row],
{
publicId: (r) => r.publicId,
createdAt: (r) => r.createdAt,
status: (r) => r.status,
},
{ nationalCode: "۱۲۳۴۵۶۷۸۹۰" },
);
const result = toPublicListItems(paged.list);
expect(result).toHaveLength(1);
expect(result[0]).toMatchObject({
locked: true,
lockedBy: { actorId: "expert-id" },
currentStep: "EXPERT_COST_EVALUATION",
});
expect(result[0]).not.toHaveProperty("partyIdentities");
expect(row.partyIdentities).toHaveLength(1);
expect(toPublicListItems([])).toEqual([]);
});
it("removes identity snapshots at the actual user and expert list response boundaries", async () => {
const userService = Object.create(
ClaimRequestManagementService.prototype,
) as any;
userService.blameRequestDbService = {
find: jest.fn().mockResolvedValue([]),
};
userService.claimCaseDbService = {
find: jest.fn().mockResolvedValue([
{
_id: "claim-id",
publicId: "A100",
status: "WAITING_FOR_DAMAGE_EXPERT",
createdAt: "2026-10-03",
workflow: { currentStep: "EXPERT_COST_EVALUATION" },
snapshot: {
parties: [
{
person: { nationalCode: "1234567890" },
inquiries: { huge: "raw provider data" },
},
],
},
},
]),
};
const userResult = await userService.getMyClaimsV2(
"650000000000000000000001",
{ role: RoleEnum.FIELD_EXPERT },
{ nationalCode: "1234567890" },
);
expect(userResult.total).toBe(1);
expect(userResult.list[0]).not.toHaveProperty("partyIdentities");
const expertService = Object.create(ExpertClaimService.prototype) as any;
const expertResult = expertService.paginateClaimListV2(
[
{
claimRequestId: "claim-id",
publicId: "A100",
status: "WAITING_FOR_DAMAGE_EXPERT",
currentStep: "EXPERT_COST_EVALUATION",
locked: true,
lockedBy: { actorId: "expert-id" },
partyIdentities: [{ person: { nationalCode: "1234567890" } }],
},
],
{ nationalCode: "1234567890" },
);
expect(expertResult.total).toBe(1);
expect(expertResult.list[0]).not.toHaveProperty("partyIdentities");
expect(expertResult.list[0].lockedBy).toEqual({ actorId: "expert-id" });
});
});
+9
View File
@@ -0,0 +1,9 @@
/** Identity lookup material is used by list filters, never by list renderers. */
export function toPublicListItems<T extends object>(rows: T[]): T[] {
return rows.map((row) => {
const { partyIdentities: _searchOnly, ...publicRow } = row as T & {
partyIdentities?: unknown;
};
return publicRow as T;
});
}
@@ -70,6 +70,8 @@ import {
import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto";
import { GetUserBlameListV2ResponseDto } from "src/request-management/dto/blame-list-user-v2.dto";
import { resolveUnifiedFileStatus } from "src/helpers/unified-file-status";
import { resolveBlameUserNextAction } from "src/helpers/blame-user-progress";
import { toPublicListItems } from "src/helpers/public-list-response";
import { AutoCloseRequestService } from "src/utils/cron/cron.service";
import { SmsOrchestrationService } from "src/sms-orchestration/sms-orchestration.service";
import {
@@ -6620,7 +6622,7 @@ export class RequestManagementService {
: ({ $or: orConditions } as any),
{
select:
"publicId requestNo type status blameStatus createdAt updatedAt parties expertInitiated registrarInitiated initiatedByFieldExpertId initiatedByRegistrarId creationMethod",
"publicId requestNo type status blameStatus createdAt updatedAt parties expert.decision.guiltyPartyId expertInitiated registrarInitiated initiatedByFieldExpertId initiatedByRegistrarId creationMethod",
},
);
@@ -6637,53 +6639,75 @@ export class RequestManagementService {
.filter((claim) => claim?.blameRequestId && claim?.status)
.map((claim) => [String(claim.blameRequestId), claim.status]),
);
const claimByBlameId = new Map<string, any>(
claimsForStatus.map((claim) => [String(claim.blameRequestId), claim]),
);
const enriched = requests.map((req: any) => {
const isInitiator =
(user?.role === RoleEnum.FIELD_EXPERT &&
req.expertInitiated &&
String(req.initiatedByFieldExpertId) === String(user.sub)) ||
(user?.role === RoleEnum.REGISTRAR &&
req.registrarInitiated &&
String(req.initiatedByRegistrarId) === String(user.sub));
const enriched = await Promise.all(
requests.map(async (req: any) => {
const isInitiator =
(user?.role === RoleEnum.FIELD_EXPERT &&
req.expertInitiated &&
String(req.initiatedByFieldExpertId) === String(user.sub)) ||
(user?.role === RoleEnum.REGISTRAR &&
req.registrarInitiated &&
String(req.initiatedByRegistrarId) === String(user.sub));
const party = req.parties?.find((p: any) =>
partyPersonMatchesUser(p?.person, user, linkedUserIds),
);
const party = req.parties?.find((p: any) =>
partyPersonMatchesUser(p?.person, user, linkedUserIds),
);
const obj = req.toObject();
const partyIdentities = Array.isArray(req.parties)
? req.parties.map((entry: any) => ({
phoneNumber: entry?.person?.phoneNumber,
nationalCode: entry?.person?.nationalCode,
nationalCodeOfInsurer: entry?.person?.nationalCodeOfInsurer,
nationalCodeOfDriver: entry?.person?.nationalCodeOfDriver,
participants: (
Array.isArray(entry?.participants)
const claimCreation = await this.computeClaimCreationHintForViewer(
req,
user,
claimByBlameId.get(String(req._id)) ?? null,
);
const partyIdentities = Array.isArray(req.parties)
? req.parties.map((entry: any) => ({
phoneNumber: entry?.person?.phoneNumber,
nationalCode: entry?.person?.nationalCode,
nationalCodeOfInsurer: entry?.person?.nationalCodeOfInsurer,
nationalCodeOfDriver: entry?.person?.nationalCodeOfDriver,
participants: (Array.isArray(entry?.participants)
? entry.participants
: entry?.inquiryParticipants
)?.map((participant: any) => ({
phoneNumber: participant?.phoneNumber,
nationalCode: participant?.nationalCode,
nationalCodeOfInsurer: participant?.nationalCodeOfInsurer,
nationalCodeOfDriver: participant?.nationalCodeOfDriver,
})),
}))
: [];
)?.map((participant: any) => ({
phoneNumber: participant?.phoneNumber,
nationalCode: participant?.nationalCode,
nationalCodeOfInsurer: participant?.nationalCodeOfInsurer,
nationalCodeOfDriver: participant?.nationalCodeOfDriver,
})),
}))
: [];
delete obj.parties;
return {
...obj,
partyIdentities,
userSide: party?.role ?? null,
initiatedByMe: isInitiator,
unifiedFileStatus: resolveUnifiedFileStatus({
blameStatus: req.status,
claimStatus: claimStatusByBlameId.get(String(req._id)),
}),
};
});
return {
_id: String(req._id),
publicId: req.publicId,
requestNo: req.requestNo,
type: req.type,
status: req.status,
blameStatus: req.blameStatus,
createdAt: req.createdAt,
updatedAt: req.updatedAt,
creationMethod: req.creationMethod,
expertInitiated: req.expertInitiated,
registrarInitiated: req.registrarInitiated,
partyIdentities,
userSide: party?.role ?? null,
initiatedByMe: isInitiator,
claimCreation,
nextAction: resolveBlameUserNextAction(
req.status,
party,
claimCreation,
),
unifiedFileStatus: resolveUnifiedFileStatus({
blameStatus: req.status,
claimStatus: claimStatusByBlameId.get(String(req._id)),
}),
};
}),
);
let filtered = enriched;
if (query.unifiedStatus) {
@@ -6734,7 +6758,7 @@ export class RequestManagementService {
);
return {
list: paged.list,
list: toPublicListItems(paged.list),
total: paged.total,
page: paged.page,
limit: paged.limit,
@@ -6753,19 +6777,29 @@ export class RequestManagementService {
private async computeClaimCreationHintForViewer(
blame: any,
user: any,
): Promise<{ hasClaim: boolean; shouldGuideToCreateClaim: boolean }> {
knownClaim?: { _id: unknown } | null,
): Promise<{
hasClaim: boolean;
shouldGuideToCreateClaim: boolean;
claimRequestId?: string;
}> {
const none = { hasClaim: false, shouldGuideToCreateClaim: false };
if (!user?.sub || !Types.ObjectId.isValid(String(user.sub))) {
return none;
}
const currentUserId = String(user.sub);
const existingClaim = await this.claimCaseDbService.findOne({
blameRequestId: blame._id,
});
const existingClaim =
knownClaim === undefined
? await this.claimCaseDbService.findOne({ blameRequestId: blame._id })
: knownClaim;
const hasClaim = !!existingClaim;
if (hasClaim) {
return { hasClaim: true, shouldGuideToCreateClaim: false };
return {
hasClaim: true,
shouldGuideToCreateClaim: false,
claimRequestId: String(existingClaim._id),
};
}
if (blame.status !== CaseStatus.COMPLETED) {
@@ -7044,6 +7078,9 @@ export class RequestManagementService {
visibleParties.map((p: any) => this.sanitizePartyForBlameUserView(p)),
);
const expert = await this.buildExpertForBlameUserView(plain.expert);
const viewerParty = allParties.find((p: any) =>
partyPersonMatchesUser(p?.person, user, linkedUserIds),
);
return {
requestNo: plain.requestNo,
@@ -7057,6 +7094,12 @@ export class RequestManagementService {
expert,
carBodyInsuranceDetail: plain.carBodyInsuranceDetail,
claimCreation,
userSide: viewerParty?.role ?? null,
nextAction: resolveBlameUserNextAction(
plain.status,
viewerParty,
claimCreation,
),
};
}
@@ -0,0 +1,230 @@
import { Types } from "mongoose";
import { RequestManagementService } from "./request-management.service";
import { resolveBlameUserNextAction } from "src/helpers/blame-user-progress";
import { RoleEnum } from "src/Types&Enums/role.enum";
const guiltyId = "650000000000000000000001";
const damagedId = "650000000000000000000002";
const blameId = "650000000000000000000003";
const signed = { accepted: true, signature: { fileId: "signature" } };
const none = { hasClaim: false, shouldGuideToCreateClaim: false };
function blame(overrides: Record<string, unknown> = {}) {
return {
_id: new Types.ObjectId(blameId),
requestNo: "A100",
publicId: "A100",
type: "THIRD_PARTY",
status: "COMPLETED",
blameStatus: "AGREED",
createdAt: new Date(),
expert: { decision: { guiltyPartyId: guiltyId } },
parties: [
{
role: "FIRST",
person: { userId: guiltyId, phoneNumber: "09120000001" },
confirmation: signed,
},
{
role: "SECOND",
person: {
userId: damagedId,
phoneNumber: "09120000002",
nationalCode: "1234567890",
},
confirmation: signed,
},
],
...overrides,
};
}
function subject() {
const service = Object.create(RequestManagementService.prototype) as any;
service.claimCaseDbService = {
findOne: jest.fn().mockResolvedValue(null),
find: jest.fn().mockResolvedValue([]),
};
service.logger = { error: jest.fn() };
return service;
}
describe("user blame next action and claim eligibility", () => {
it("distinguishes an unsigned viewer from a viewer waiting for the other signature", () => {
expect(resolveBlameUserNextAction("WAITING_FOR_SIGNATURES", {}, none)).toBe(
"SIGN",
);
expect(
resolveBlameUserNextAction(
"WAITING_FOR_SIGNATURES",
{ confirmation: signed },
none,
),
).toBe("WAIT_FOR_OTHER_SIGNATURE");
expect(
resolveBlameUserNextAction("WAITING_FOR_SIGNATURES", undefined, none),
).toBeNull();
expect(
resolveBlameUserNextAction("WAITING_FOR_EXPERT", {}, none),
).toBeNull();
expect(resolveBlameUserNextAction("STOPPED", {}, none)).toBe("VIEW_RESULT");
});
it("permits a new third-party claim only for the damaged party after both accept", async () => {
const service = subject();
for (const [viewer, eligible] of [
[damagedId, true],
[guiltyId, false],
[blameId, false],
] as const) {
const hint = await service.computeClaimCreationHintForViewer(
blame(),
{ sub: viewer },
null,
);
expect(hint.shouldGuideToCreateClaim).toBe(eligible);
}
for (const status of [
"WAITING_FOR_SIGNATURES",
"WAITING_FOR_EXPERT",
"STOPPED",
]) {
expect(
(
await service.computeClaimCreationHintForViewer(
blame({ status }),
{ sub: damagedId },
null,
)
).shouldGuideToCreateClaim,
).toBe(false);
}
const missingSignature = blame();
delete (missingSignature.parties[0] as any).confirmation;
expect(
(
await service.computeClaimCreationHintForViewer(
missingSignature,
{ sub: damagedId },
null,
)
).shouldGuideToCreateClaim,
).toBe(false);
});
it("does not guide rejected or existing claims to duplicate creation", async () => {
const service = subject();
const rejected = blame();
rejected.parties[0].confirmation = { ...signed, accepted: false };
expect(
(
await service.computeClaimCreationHintForViewer(
rejected,
{ sub: damagedId },
null,
)
).shouldGuideToCreateClaim,
).toBe(false);
const hint = await service.computeClaimCreationHintForViewer(
blame(),
{ sub: damagedId },
{ _id: blameId },
);
expect(hint).toEqual({
hasClaim: true,
shouldGuideToCreateClaim: false,
claimRequestId: blameId,
});
expect(resolveBlameUserNextAction("COMPLETED", {}, hint)).toBe(
"CONTINUE_CLAIM",
);
expect(service.claimCaseDbService.findOne).not.toHaveBeenCalled();
});
it("permits a completed body-insurance claim only for its own party", async () => {
const service = subject();
const body = blame({
type: "CAR_BODY",
parties: [
{ role: "FIRST", person: { userId: damagedId }, confirmation: signed },
],
});
expect(
(
await service.computeClaimCreationHintForViewer(
body,
{ sub: damagedId },
null,
)
).shouldGuideToCreateClaim,
).toBe(true);
expect(
(
await service.computeClaimCreationHintForViewer(
body,
{ sub: guiltyId },
null,
)
).shouldGuideToCreateClaim,
).toBe(false);
});
it("keeps identity filters working but omits private/search-only fields in list responses", async () => {
const service = subject();
service.blameRequestDbService = {
find: jest
.fn()
.mockResolvedValue([
blame({
__v: 42,
inquiries: { raw: "private" },
initiatedByFieldExpertId: guiltyId,
}),
]),
};
const response = await service.getAllBlameRequestsV2(
{ sub: damagedId, role: RoleEnum.USER },
{ nationalCode: "۱۲۳۴۵۶۷۸۹۰", page: 1, limit: 10 },
);
expect(response.total).toBe(1);
expect(response.list[0]).toMatchObject({
_id: blameId,
nextAction: "CREATE_CLAIM",
userSide: "SECOND",
});
for (const key of [
"parties",
"partyIdentities",
"__v",
"inquiries",
"expert",
"initiatedByFieldExpertId",
]) {
expect(response.list[0]).not.toHaveProperty(key);
}
expect(JSON.stringify(response)).not.toContain("1234567890");
expect(service.claimCaseDbService.findOne).not.toHaveBeenCalled();
expect(service.claimCaseDbService.find).toHaveBeenCalledTimes(2);
});
it("provides signing guidance in detail without returning the other party", async () => {
const service = subject();
const record = blame({
status: "WAITING_FOR_SIGNATURES",
workflow: { currentStep: "WAITING_FOR_SIGNATURES" },
});
delete (record.parties[1] as any).confirmation;
service.blameRequestDbService = {
findById: jest.fn().mockResolvedValue(record),
};
const response = await service.getBlameRequestV2(blameId, {
sub: damagedId,
role: RoleEnum.USER,
});
expect(response.nextAction).toBe("SIGN");
expect(response.userSide).toBe("SECOND");
expect(response.parties).toHaveLength(1);
expect(response.parties[0].role).toBe("SECOND");
expect(JSON.stringify(response)).not.toContain("09120000001");
});
});