diff --git a/docs/user-blame-progress-contract.md b/docs/user-blame-progress-contract.md new file mode 100644 index 0000000..7759ddc --- /dev/null +++ b/docs/user-blame-progress-contract.md @@ -0,0 +1,52 @@ +# User signing and claim-start guidance + +The user UI v1 calls `/v2/blame-request-management`. Both its list and detail +responses now include a viewer-specific `nextAction`. This is computed from the +existing case, the viewer's party confirmation, and the existing claim. It does +not change persisted statuses, signatures, ownership, or workflow transitions. + +| nextAction | User interface behavior | +| --- | --- | +| `SIGN` | Open the signing screen. | +| `WAIT_FOR_OTHER_SIGNATURE` | Confirm that the viewer signed, explain the remaining signature, and refresh the case while waiting. | +| `CREATE_CLAIM` | Show “آماده ثبت درخواست خسارت” and a “ثبت درخواست خسارت” action. | +| `CONTINUE_CLAIM` | Open the claim list for the existing claim. | +| `VIEW_RESULT` | Show the completed or stopped result; do not offer unauthorized claim creation. | +| `null` | Continue the existing information-collection/review routing. | + +The detail response also includes `userSide`. `claimCreation` retains `hasClaim` +and `shouldGuideToCreateClaim`, with `claimRequestId` when a claim exists. +Third-party creation still requires completed blame, both accepted confirmations, +and the damaged party as viewer. Body-insurance creation retains its single-party +eligibility rule. A completed blame case means the user can start loss assessment; +it does not mean compensation has already been approved for payment. + +User details expose only the viewer's party. The frontend must use this guidance +rather than count signatures from that partial array. Signing acknowledgements +use `requestId`, not `_id`. After a successful signature, the frontend refreshes +the detail and invalidates case lists before presenting the next action. + +When the second-party description returns `workflow.currentStep = +WAITING_FOR_SIGNATURES`, route directly to signing. Cases waiting for an expert +continue to use the review-waiting screen. Reopening the waiting screen also +checks the current case and redirects to signing or completion when appropriate. + +## List response size + +`partyIdentities` is server-side filter material. It is removed after identity +filtering, sorting, and pagination from these response boundaries: + +- User/initiator blame list: `GET /v2/blame-request-management`. +- User/initiator claim list: `GET /v2/claim-request-management/requests`. +- Expert claim queues, including field experts, file makers, and file reviewers, + through `ExpertClaimService.paginateClaimListV2`. + +The blame list uses an explicit response field list instead of spreading Mongo +documents, so internal revision values and initiator IDs are not returned. +Claim lists retain the IDs, status, workflow, lock, vehicle, and role-specific +fields consumed by the two frontends. Detail, reporting, and integration payloads +retain the evidence and inquiry data needed by their callers. Identity filtering +continues to run on internal rows before the public response is constructed. + +Regression coverage is in `request-management.user-progress.spec.ts`, +`public-list-response.spec.ts`, and the user UI's `test-blame-progress.cjs`. diff --git a/src/claim-request-management/claim-request-management.service.ts b/src/claim-request-management/claim-request-management.service.ts index 1641e53..2929f65 100644 --- a/src/claim-request-management/claim-request-management.service.ts +++ b/src/claim-request-management/claim-request-management.service.ts @@ -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, diff --git a/src/expert-claim/expert-claim.service.ts b/src/expert-claim/expert-claim.service.ts index 312ff8f..d434f0c 100644 --- a/src/expert-claim/expert-claim.service.ts +++ b/src/expert-claim/expert-claim.service.ts @@ -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, diff --git a/src/features/auth/auth.controller.ts b/src/features/auth/auth.controller.ts deleted file mode 100644 index 2f3b1d9..0000000 --- a/src/features/auth/auth.controller.ts +++ /dev/null @@ -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); - } -} diff --git a/src/features/auth/auth.module.ts b/src/features/auth/auth.module.ts deleted file mode 100644 index cca86e8..0000000 --- a/src/features/auth/auth.module.ts +++ /dev/null @@ -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("JWT_SECRET"), - signOptions: { - expiresIn: configService.get("JWT_EXPIRY"), - }, - }), - }), - ], - controllers: [AuthController], - providers: [ - { provide: APP_GUARD, useClass: AuthGuard }, - { provide: APP_GUARD, useClass: RolesGuard }, - AuthService, - HashService, - OtpService, - ], -}) -export class AuthModule {} diff --git a/src/features/auth/auth.service.ts b/src/features/auth/auth.service.ts deleted file mode 100644 index 56fca0b..0000000 --- a/src/features/auth/auth.service.ts +++ /dev/null @@ -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("DEFAULT_OTP_DIGITS") ?? 5; - this.otpExpiryMinutes = - (this.configService.get("DEFAULT_OTP_EXPIRY_MINUTES") ?? 2) * 60; - this.environment = this.configService.get("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 {}; - } -} diff --git a/src/features/auth/providers/hash.provider.ts b/src/features/auth/providers/hash.provider.ts deleted file mode 100644 index b9c0aef..0000000 --- a/src/features/auth/providers/hash.provider.ts +++ /dev/null @@ -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("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 { - 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 { - 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 { - 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 { - 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 { - 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 { - 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; - } - } -} diff --git a/src/features/auth/providers/index.ts b/src/features/auth/providers/index.ts deleted file mode 100644 index 03284ce..0000000 --- a/src/features/auth/providers/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { HashService } from "./hash.provider"; -export { OtpService } from "./otp.provider"; diff --git a/src/features/auth/providers/otp.provider.ts b/src/features/auth/providers/otp.provider.ts deleted file mode 100644 index c0c60f3..0000000 --- a/src/features/auth/providers/otp.provider.ts +++ /dev/null @@ -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("MAX_OTP_ATTEMPTS"); - this.environment = this.configService.get("NODE_ENV"); - } - - generateOtp(digits: number): string { - if (this.environment === "development") { - return this.configService.get("DEFAULT_MOCK_OTP") ?? "11111"; - } - return String(Math.floor(Math.random() * 1_000_000)).padStart(digits, "0"); - } -} diff --git a/src/features/expert-initiated/dtos/login.dto.ts b/src/features/expert-initiated/dtos/login.dto.ts deleted file mode 100644 index 68b650b..0000000 --- a/src/features/expert-initiated/dtos/login.dto.ts +++ /dev/null @@ -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; -} diff --git a/src/features/expert-initiated/expert-initiated.controller.ts b/src/features/expert-initiated/expert-initiated.controller.ts deleted file mode 100644 index 01cab49..0000000 --- a/src/features/expert-initiated/expert-initiated.controller.ts +++ /dev/null @@ -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); - } -} diff --git a/src/features/expert-initiated/expert-initiated.module.ts b/src/features/expert-initiated/expert-initiated.module.ts deleted file mode 100644 index 2050ef1..0000000 --- a/src/features/expert-initiated/expert-initiated.module.ts +++ /dev/null @@ -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 {} diff --git a/src/features/expert-initiated/expert-initiated.service.ts b/src/features/expert-initiated/expert-initiated.service.ts deleted file mode 100644 index 2a88ce7..0000000 --- a/src/features/expert-initiated/expert-initiated.service.ts +++ /dev/null @@ -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"); - } -} diff --git a/src/features/expert-initiated/repositories/field-expert.repository.ts b/src/features/expert-initiated/repositories/field-expert.repository.ts deleted file mode 100644 index 2e4784d..0000000 --- a/src/features/expert-initiated/repositories/field-expert.repository.ts +++ /dev/null @@ -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, - ) {} - - async retrieveById(id: string): Promise { - return await this.fieldExpertModel.findById(id).exec(); - } - - async retrieveByEmail(email: string): Promise { - return await this.fieldExpertModel.findOne({ - email, - }); - } -} diff --git a/src/features/expert-initiated/schemas/field-expert.schema.ts b/src/features/expert-initiated/schemas/field-expert.schema.ts deleted file mode 100644 index cde1c7d..0000000 --- a/src/features/expert-initiated/schemas/field-expert.schema.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose"; -import { HydratedDocument, Types } from "mongoose"; - -export type FieldExpertDocument = HydratedDocument; - -@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); diff --git a/src/features/user/dtos/index.ts b/src/features/user/dtos/index.ts deleted file mode 100644 index 82c08c6..0000000 --- a/src/features/user/dtos/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { UserRegisterDto } from "./requests/user-register.dto"; -export { UserLoginDto } from "./requests/user-login.dto"; diff --git a/src/features/user/dtos/requests/user-login.dto.ts b/src/features/user/dtos/requests/user-login.dto.ts deleted file mode 100644 index a8eb9e5..0000000 --- a/src/features/user/dtos/requests/user-login.dto.ts +++ /dev/null @@ -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; -} diff --git a/src/features/user/dtos/requests/user-register.dto.ts b/src/features/user/dtos/requests/user-register.dto.ts deleted file mode 100644 index 089c2c7..0000000 --- a/src/features/user/dtos/requests/user-register.dto.ts +++ /dev/null @@ -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; -} diff --git a/src/features/user/repositories/index.ts b/src/features/user/repositories/index.ts deleted file mode 100644 index 51189d1..0000000 --- a/src/features/user/repositories/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { UserRepository } from "./user.repository"; diff --git a/src/features/user/repositories/user.repository.ts b/src/features/user/repositories/user.repository.ts deleted file mode 100644 index 06c303e..0000000 --- a/src/features/user/repositories/user.repository.ts +++ /dev/null @@ -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, - ) {} - - async create(cellphoneNumber: string): Promise { - return this.model.create({ cellphoneNumber }); - } - - async retrieveByCellPhoneNumber( - cellphoneNumber: string, - ): Promise { - return await this.model.findOne({ - cellphoneNumber, - }); - } - - async saveOtp(cellphoneNumber: string, otp: Otp): Promise { - await this.model.updateOne({ cellphoneNumber }, { $set: { otp } }); - } - - async clearOtp(cellphoneNumber: string): Promise { - await this.model.updateOne({ cellphoneNumber }, { $unset: { otp: "" } }); - } - - async incrementOtpAttempts(cellphoneNumber: string): Promise { - await this.model.updateOne( - { cellphoneNumber }, - { $inc: { "otp.attempts": 1 } }, - ); - } -} diff --git a/src/features/user/schemas/index.ts b/src/features/user/schemas/index.ts deleted file mode 100644 index d46cf20..0000000 --- a/src/features/user/schemas/index.ts +++ /dev/null @@ -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"; diff --git a/src/features/user/schemas/otp.schema.ts b/src/features/user/schemas/otp.schema.ts deleted file mode 100644 index 700a231..0000000 --- a/src/features/user/schemas/otp.schema.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose"; -import { HydratedDocument } from "mongoose"; - -export type OtpDocument = HydratedDocument; - -@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); diff --git a/src/features/user/schemas/profile.schema.ts b/src/features/user/schemas/profile.schema.ts deleted file mode 100644 index c8f4f61..0000000 --- a/src/features/user/schemas/profile.schema.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose"; -import { HydratedDocument } from "mongoose"; - -export type ProfileDocument = HydratedDocument; - -@Schema({ _id: false }) -export class Profile { - @Prop() - firstName?: string; - - @Prop() - lastName?: string; - - @Prop() - birthDate?: Date; -} - -export const ProfileSchema = SchemaFactory.createForClass(Profile); diff --git a/src/features/user/schemas/user.schema.ts b/src/features/user/schemas/user.schema.ts deleted file mode 100644 index 32de31a..0000000 --- a/src/features/user/schemas/user.schema.ts +++ /dev/null @@ -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; - -@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); diff --git a/src/features/user/user.controller.ts b/src/features/user/user.controller.ts deleted file mode 100644 index e69de29..0000000 diff --git a/src/features/user/user.module.ts b/src/features/user/user.module.ts deleted file mode 100644 index 8bc27e2..0000000 --- a/src/features/user/user.module.ts +++ /dev/null @@ -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 {} diff --git a/src/helpers/blame-user-progress.ts b/src/helpers/blame-user-progress.ts new file mode 100644 index 0000000..5e7e7a8 --- /dev/null +++ b/src/helpers/blame-user-progress.ts @@ -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; +} diff --git a/src/helpers/public-list-response.spec.ts b/src/helpers/public-list-response.spec.ts new file mode 100644 index 0000000..5d554aa --- /dev/null +++ b/src/helpers/public-list-response.spec.ts @@ -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" }); + }); +}); diff --git a/src/helpers/public-list-response.ts b/src/helpers/public-list-response.ts new file mode 100644 index 0000000..af0c0e8 --- /dev/null +++ b/src/helpers/public-list-response.ts @@ -0,0 +1,9 @@ +/** Identity lookup material is used by list filters, never by list renderers. */ +export function toPublicListItems(rows: T[]): T[] { + return rows.map((row) => { + const { partyIdentities: _searchOnly, ...publicRow } = row as T & { + partyIdentities?: unknown; + }; + return publicRow as T; + }); +} diff --git a/src/request-management/request-management.service.ts b/src/request-management/request-management.service.ts index b48d4d5..053efe8 100644 --- a/src/request-management/request-management.service.ts +++ b/src/request-management/request-management.service.ts @@ -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( + 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, + ), }; } diff --git a/src/request-management/request-management.user-progress.spec.ts b/src/request-management/request-management.user-progress.spec.ts new file mode 100644 index 0000000..9380731 --- /dev/null +++ b/src/request-management/request-management.user-progress.spec.ts @@ -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 = {}) { + 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"); + }); +});