forked from Yara724/api
Fixed Lock for Field expert + user view of files
This commit is contained in:
@@ -59,6 +59,7 @@ import {
|
||||
} from "./dto/my-claims-v2.dto";
|
||||
import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto";
|
||||
import { applyListQueryV2 } from "src/helpers/list-query-v2";
|
||||
import { partyPersonMatchesUser } from "src/helpers/iran-mobile";
|
||||
import { ClaimDetailsV2ResponseDto } from "./dto/claim-details-v2.dto";
|
||||
import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum";
|
||||
import { ClaimRequiredDocumentType } from "src/Types&Enums/claim-request-management/required-document-type.enum";
|
||||
@@ -4786,6 +4787,26 @@ export class ClaimRequestManagementService {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
(!actor?.role || actor.role === RoleEnum.USER) &&
|
||||
claim.blameRequestId
|
||||
) {
|
||||
const blame = await this.blameRequestDbService.findById(
|
||||
claim.blameRequestId.toString(),
|
||||
);
|
||||
const isParty =
|
||||
Array.isArray(blame?.parties) &&
|
||||
blame.parties.some((p: any) =>
|
||||
partyPersonMatchesUser(p?.person, {
|
||||
sub: currentUserId,
|
||||
username: (actor as { username?: string })?.username,
|
||||
}),
|
||||
);
|
||||
if (isParty) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (actor?.role === RoleEnum.FIELD_EXPERT) {
|
||||
if (claim.initiatedByFieldExpertId?.toString() === currentUserId) {
|
||||
return;
|
||||
@@ -7223,8 +7244,25 @@ export class ClaimRequestManagementService {
|
||||
{ lean: true },
|
||||
);
|
||||
} else {
|
||||
const partyBlameIds = await this.blameRequestDbService
|
||||
.find(
|
||||
{
|
||||
$or: [
|
||||
{ "parties.person.userId": new Types.ObjectId(currentUserId) },
|
||||
],
|
||||
},
|
||||
{ select: "_id", lean: true },
|
||||
)
|
||||
.then((docs) => docs.map((d) => (d as any)._id));
|
||||
claims = await this.claimCaseDbService.find(
|
||||
{ "owner.userId": new Types.ObjectId(currentUserId) },
|
||||
{
|
||||
$or: [
|
||||
{ "owner.userId": new Types.ObjectId(currentUserId) },
|
||||
...(partyBlameIds.length
|
||||
? [{ blameRequestId: { $in: partyBlameIds } }]
|
||||
: []),
|
||||
],
|
||||
},
|
||||
{ lean: true },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import {
|
||||
assertBlameCaseForExpertTenant,
|
||||
blameCaseAccessibleToExpert,
|
||||
blameCaseInitiatedByFieldExpert,
|
||||
requireActorClientKey,
|
||||
} from "src/helpers/tenant-scope";
|
||||
import {
|
||||
@@ -436,8 +437,9 @@ export class ExpertBlameService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Blame review inbox for FIELD_EXPERT — expert-initiated DISAGREEMENT files only.
|
||||
* IN_PERSON flows are AGREED and handled outside this panel; completed blames appear in expert-claim.
|
||||
* Blame review inbox for FIELD_EXPERT — expert-initiated DISAGREEMENT files.
|
||||
* Covers LINK flows (parties complete via link → WAITING_FOR_EXPERT) and in-progress
|
||||
* disputes while parties are still filling. IN_PERSON AGREED blames use expert-claim instead.
|
||||
*/
|
||||
private async getFieldExpertBlameListV2(
|
||||
actor: { sub: string },
|
||||
@@ -448,9 +450,25 @@ export class ExpertBlameService {
|
||||
|
||||
const visibleCases = (await this.blameRequestDbService.find(
|
||||
{
|
||||
blameStatus: BlameStatus.DISAGREEMENT,
|
||||
expertInitiated: true,
|
||||
initiatedByFieldExpertId: expertOid,
|
||||
blameStatus: BlameStatus.DISAGREEMENT,
|
||||
type: { $ne: BlameRequestType.CAR_BODY },
|
||||
$or: [
|
||||
{ status: CaseStatus.WAITING_FOR_EXPERT },
|
||||
{
|
||||
status: {
|
||||
$in: [
|
||||
CaseStatus.OPEN,
|
||||
CaseStatus.WAITING_FOR_SECOND_PARTY,
|
||||
CaseStatus.WAITING_FOR_DOCUMENT_RESEND,
|
||||
],
|
||||
},
|
||||
},
|
||||
{ "workflow.lockedBy.actorId": expertOid },
|
||||
{ "workflow.assignedForReviewBy.actorId": expertOid },
|
||||
{ "expert.decision.decidedByExpertId": expertOid },
|
||||
],
|
||||
},
|
||||
{ lean: true },
|
||||
)) as Record<string, unknown>[];
|
||||
@@ -966,6 +984,8 @@ export class ExpertBlameService {
|
||||
);
|
||||
}
|
||||
|
||||
const isFieldExpertOwner = blameCaseInitiatedByFieldExpert(doc, actor);
|
||||
|
||||
const decision = (doc.expert as any)?.decision;
|
||||
const decidedByExpertId = decision?.decidedByExpertId
|
||||
? String(decision.decidedByExpertId)
|
||||
@@ -978,6 +998,7 @@ export class ExpertBlameService {
|
||||
(doc.workflow as any)?.assignedForReviewBy?.actorId ?? "",
|
||||
);
|
||||
|
||||
if (!isFieldExpertOwner) {
|
||||
// Access gates — must satisfy at least one bucket
|
||||
const isAvailable =
|
||||
doc.status === CaseStatus.WAITING_FOR_EXPERT && !decidedByExpertId;
|
||||
@@ -1002,6 +1023,7 @@ export class ExpertBlameService {
|
||||
"You do not have permission to view this request.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Build evidence URLs
|
||||
const parties = Array.isArray(doc.parties) ? doc.parties : [];
|
||||
@@ -1158,7 +1180,12 @@ export class ExpertBlameService {
|
||||
*/
|
||||
async assignBlameCaseForReviewV2(
|
||||
requestId: string,
|
||||
actor: { sub: string; fullName?: string; clientKey?: string },
|
||||
actor: {
|
||||
sub: string;
|
||||
fullName?: string;
|
||||
clientKey?: string;
|
||||
role?: string;
|
||||
},
|
||||
): Promise<ExpertFileAssignResultDto> {
|
||||
await this.expireBlameCaseWorkflowLockV2IfStale(requestId);
|
||||
|
||||
@@ -1169,6 +1196,8 @@ export class ExpertBlameService {
|
||||
|
||||
assertBlameCaseForExpertTenant(request, actor);
|
||||
|
||||
const isFieldExpertOwner = blameCaseInitiatedByFieldExpert(request, actor);
|
||||
|
||||
if (request.type === BlameRequestType.CAR_BODY) {
|
||||
throw new BadRequestException({
|
||||
success: false,
|
||||
@@ -1177,9 +1206,17 @@ export class ExpertBlameService {
|
||||
});
|
||||
}
|
||||
|
||||
if (request.blameStatus !== BlameStatus.DISAGREEMENT) {
|
||||
throw new BadRequestException({
|
||||
success: false,
|
||||
status: "unavailable" satisfies ExpertFileAssignStatus,
|
||||
message: "Request is not available for expert review",
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
request.status !== CaseStatus.WAITING_FOR_EXPERT ||
|
||||
request.blameStatus !== BlameStatus.DISAGREEMENT
|
||||
!isFieldExpertOwner &&
|
||||
request.status !== CaseStatus.WAITING_FOR_EXPERT
|
||||
) {
|
||||
throw new BadRequestException({
|
||||
success: false,
|
||||
@@ -1188,6 +1225,26 @@ export class ExpertBlameService {
|
||||
});
|
||||
}
|
||||
|
||||
if (isFieldExpertOwner && request.expert?.decision) {
|
||||
throw new BadRequestException({
|
||||
success: false,
|
||||
status: "unavailable" satisfies ExpertFileAssignStatus,
|
||||
message: "This request already has an expert decision",
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
isFieldExpertOwner &&
|
||||
request.status !== CaseStatus.WAITING_FOR_EXPERT
|
||||
) {
|
||||
throw new BadRequestException({
|
||||
success: false,
|
||||
status: "unavailable" satisfies ExpertFileAssignStatus,
|
||||
message:
|
||||
"Parties are still completing this file. Lock and review become available when status is WAITING_FOR_EXPERT (e.g. after both parties finish via link).",
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
request.expertInitiated &&
|
||||
request.initiatedByFieldExpertId &&
|
||||
@@ -1272,7 +1329,6 @@ export class ExpertBlameService {
|
||||
|
||||
const assignFilter: Record<string, unknown> = {
|
||||
_id: new Types.ObjectId(requestId),
|
||||
status: CaseStatus.WAITING_FOR_EXPERT,
|
||||
blameStatus: BlameStatus.DISAGREEMENT,
|
||||
$and: [
|
||||
{
|
||||
@@ -1293,8 +1349,11 @@ export class ExpertBlameService {
|
||||
],
|
||||
};
|
||||
|
||||
if (request.expertInitiated) {
|
||||
if (isFieldExpertOwner) {
|
||||
assignFilter.initiatedByFieldExpertId = expertOid;
|
||||
assignFilter.status = CaseStatus.WAITING_FOR_EXPERT;
|
||||
} else {
|
||||
assignFilter.status = CaseStatus.WAITING_FOR_EXPERT;
|
||||
}
|
||||
|
||||
const updated = await this.blameRequestDbService.findOneAndUpdate(
|
||||
|
||||
@@ -43,7 +43,7 @@ export class ExpertBlameV2Controller {
|
||||
summary: "List blame cases for expert review (V2)",
|
||||
description:
|
||||
"Damage experts (`expert`): tenant-scoped **DISAGREEMENT** queue (available, locked, or decided by you). " +
|
||||
"Field experts (`field_expert`): only **DISAGREEMENT** files they initiated that need expert review (e.g. LINK disputes). " +
|
||||
"Field experts (`field_expert`): expert-initiated **DISAGREEMENT** files — including **LINK** flows where parties complete via link and the case moves to `WAITING_FOR_EXPERT` for your review. " +
|
||||
"IN_PERSON expert-initiated blames are usually `AGREED` and are managed via expert-initiated / request-management APIs; after completion, use expert-claim. " +
|
||||
"Optional query: `search`, `sortBy` (publicId | createdAt | requestNo | status), `sortOrder`, `page`, `limit`.",
|
||||
})
|
||||
|
||||
@@ -2437,12 +2437,35 @@ export class ExpertClaimService {
|
||||
|
||||
assertClaimCaseForExpertActor(claim, actor);
|
||||
|
||||
const isFieldExpertOwner =
|
||||
(actor as any).role === RoleEnum.FIELD_EXPERT &&
|
||||
claimCaseInitiatedByFieldExpert(claim, actor);
|
||||
const isFactorValidationLock =
|
||||
claimIsAwaitingExpertFactorValidationV2(claim);
|
||||
const isDamageReviewLock =
|
||||
claim.status === ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT;
|
||||
const isExpertReviewingReentry =
|
||||
claim.status === ClaimCaseStatus.EXPERT_REVIEWING;
|
||||
const isResendPending =
|
||||
claim.status === ClaimCaseStatus.WAITING_FOR_USER_RESEND;
|
||||
const isTerminalClaim =
|
||||
claim.status === ClaimCaseStatus.COMPLETED ||
|
||||
claim.status === ClaimCaseStatus.CANCELLED;
|
||||
const isFieldExpertPortfolioLock =
|
||||
isFieldExpertOwner &&
|
||||
!isTerminalClaim &&
|
||||
!isDamageReviewLock &&
|
||||
!isFactorValidationLock &&
|
||||
!isExpertReviewingReentry &&
|
||||
!isResendPending;
|
||||
|
||||
if (!isDamageReviewLock && !isFactorValidationLock) {
|
||||
if (
|
||||
!isDamageReviewLock &&
|
||||
!isFactorValidationLock &&
|
||||
!isExpertReviewingReentry &&
|
||||
!isResendPending &&
|
||||
!isFieldExpertPortfolioLock
|
||||
) {
|
||||
throw new BadRequestException({
|
||||
success: false,
|
||||
status: "unavailable" satisfies ExpertFileAssignStatus,
|
||||
@@ -2490,11 +2513,15 @@ export class ExpertClaimService {
|
||||
const now = new Date();
|
||||
const lockSnapshot = await this.snapshotDamageExpert(actor.sub);
|
||||
const expiredAt = new Date(now.getTime() + this.claimV2WorkflowLockTtlMs);
|
||||
const actorType = isFieldExpertOwner ? "field_expert" : "damage_expert";
|
||||
const actorRoleLabel = isFieldExpertOwner
|
||||
? ("field_expert" as const)
|
||||
: ("damage_expert" as const);
|
||||
|
||||
const lockedByPayload = {
|
||||
actorId: expertOid,
|
||||
actorName: actor.fullName,
|
||||
actorRole: "damage_expert" as const,
|
||||
actorRole: actorRoleLabel,
|
||||
...(lockSnapshot && { expertProfileSnapshot: lockSnapshot }),
|
||||
};
|
||||
|
||||
@@ -2503,34 +2530,40 @@ export class ExpertClaimService {
|
||||
"workflow.lockedAt": now,
|
||||
"workflow.expiredAt": expiredAt,
|
||||
"workflow.lockedBy": lockedByPayload,
|
||||
"workflow.preLockQueueSnapshot": {
|
||||
claimStatus: claim.claimStatus,
|
||||
currentStep: this.normalizeClaimWorkflowStepForSnapshot(
|
||||
claim.workflow?.currentStep,
|
||||
ClaimWorkflowStep.USER_SUBMISSION_COMPLETE,
|
||||
),
|
||||
...(claim.workflow?.nextStep != null
|
||||
? {
|
||||
nextStep: this.normalizeClaimWorkflowStepForSnapshot(
|
||||
claim.workflow.nextStep,
|
||||
ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT,
|
||||
...(isDamageReviewLock || isExpertReviewingReentry || isResendPending
|
||||
? {
|
||||
"workflow.preLockQueueSnapshot": {
|
||||
claimStatus: claim.claimStatus,
|
||||
currentStep: this.normalizeClaimWorkflowStepForSnapshot(
|
||||
claim.workflow?.currentStep,
|
||||
ClaimWorkflowStep.USER_SUBMISSION_COMPLETE,
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
...(claim.workflow?.nextStep != null
|
||||
? {
|
||||
nextStep: this.normalizeClaimWorkflowStepForSnapshot(
|
||||
claim.workflow.nextStep,
|
||||
ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT,
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
$push: {
|
||||
history: {
|
||||
type: "CLAIM_ASSIGNED",
|
||||
actor: {
|
||||
actorId: expertOid,
|
||||
actorName: actor.fullName,
|
||||
actorType: "damage_expert",
|
||||
actorType,
|
||||
},
|
||||
timestamp: now,
|
||||
metadata: {
|
||||
note: isFactorValidationLock
|
||||
? "Expert assigned for factor validation review"
|
||||
: "Expert assigned via review assign endpoint",
|
||||
: isFieldExpertPortfolioLock
|
||||
? "Field expert portfolio lock (no status change)"
|
||||
: "Expert assigned via review assign endpoint",
|
||||
...(isFactorValidationLock ? { phase: "factorValidation" } : {}),
|
||||
},
|
||||
},
|
||||
@@ -2541,14 +2574,18 @@ export class ExpertClaimService {
|
||||
baseLockUpdate["workflow.assignedForReviewBy"] = lockedByPayload;
|
||||
}
|
||||
|
||||
const lockUpdate: Record<string, unknown> = isFactorValidationLock
|
||||
? baseLockUpdate
|
||||
: {
|
||||
...baseLockUpdate,
|
||||
status: ClaimCaseStatus.EXPERT_REVIEWING,
|
||||
claimStatus: ClaimStatus.UNDER_REVIEW,
|
||||
"workflow.currentStep": ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT,
|
||||
};
|
||||
const lockUpdate: Record<string, unknown> =
|
||||
isFactorValidationLock ||
|
||||
isExpertReviewingReentry ||
|
||||
isResendPending ||
|
||||
isFieldExpertPortfolioLock
|
||||
? baseLockUpdate
|
||||
: {
|
||||
...baseLockUpdate,
|
||||
status: ClaimCaseStatus.EXPERT_REVIEWING,
|
||||
claimStatus: ClaimStatus.UNDER_REVIEW,
|
||||
"workflow.currentStep": ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT,
|
||||
};
|
||||
|
||||
const assignFilter: Record<string, unknown> = {
|
||||
_id: new Types.ObjectId(claimRequestId),
|
||||
@@ -2581,6 +2618,13 @@ export class ExpertClaimService {
|
||||
ClaimCaseStatus.WAITING_FOR_INSURER_APPROVAL,
|
||||
],
|
||||
};
|
||||
} else if (isExpertReviewingReentry) {
|
||||
assignFilter.status = ClaimCaseStatus.EXPERT_REVIEWING;
|
||||
} else if (isResendPending) {
|
||||
assignFilter.status = ClaimCaseStatus.WAITING_FOR_USER_RESEND;
|
||||
} else if (isFieldExpertPortfolioLock) {
|
||||
assignFilter.initiatedByFieldExpertId = expertOid;
|
||||
assignFilter.status = claim.status;
|
||||
} else {
|
||||
assignFilter.status = ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT;
|
||||
}
|
||||
@@ -2634,7 +2678,13 @@ export class ExpertClaimService {
|
||||
});
|
||||
|
||||
const ownerPhone = await this.resolveClaimOwnerPhone(updated);
|
||||
if (ownerPhone) {
|
||||
if (
|
||||
ownerPhone &&
|
||||
isDamageReviewLock &&
|
||||
!isFieldExpertPortfolioLock &&
|
||||
!isExpertReviewingReentry &&
|
||||
!isResendPending
|
||||
) {
|
||||
const expertLastName =
|
||||
actor?.fullName?.trim()?.split(/\s+/).pop() || "کارشناس";
|
||||
await this.smsOrchestrationService.sendThirdPartyExpertStartedReviewNotice(
|
||||
|
||||
@@ -44,3 +44,28 @@ export function buildUserLookupByPhone(
|
||||
$or: variants.flatMap((v) => [{ username: v }, { mobile: v }]),
|
||||
};
|
||||
}
|
||||
|
||||
/** True when a blame party person row belongs to the authenticated user. */
|
||||
export function partyPersonMatchesUser(
|
||||
person:
|
||||
| { userId?: unknown; phoneNumber?: string }
|
||||
| null
|
||||
| undefined,
|
||||
user: { sub?: string; username?: string } | null | undefined,
|
||||
): boolean {
|
||||
if (!person || !user) return false;
|
||||
if (
|
||||
person.userId != null &&
|
||||
user.sub &&
|
||||
String(person.userId) === String(user.sub)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (!person.phoneNumber || !user.username) return false;
|
||||
const stored =
|
||||
normalizeIranMobile(person.phoneNumber) ?? person.phoneNumber;
|
||||
const variants = iranMobileLookupVariants(user.username);
|
||||
return variants.some(
|
||||
(v) => v === stored || v === person.phoneNumber,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { BadRequestException, ForbiddenException } from "@nestjs/common";
|
||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
|
||||
/** Insurance company tenant id on the actor JWT (Mongo ObjectId string). */
|
||||
export function requireActorClientKey(actor: { clientKey?: string }): string {
|
||||
@@ -64,6 +65,19 @@ export function blameCaseAccessibleToExpert(
|
||||
return blameCaseTouchesClient(doc, ck);
|
||||
}
|
||||
|
||||
/** True when the acting field expert created this expert-initiated blame file. */
|
||||
export function blameCaseInitiatedByFieldExpert(
|
||||
doc: any,
|
||||
actor: { sub: string; role?: string },
|
||||
): boolean {
|
||||
return (
|
||||
actor.role === RoleEnum.FIELD_EXPERT &&
|
||||
!!doc?.expertInitiated &&
|
||||
!!doc?.initiatedByFieldExpertId &&
|
||||
String(doc.initiatedByFieldExpertId) === String(actor.sub)
|
||||
);
|
||||
}
|
||||
|
||||
export function assertBlameCaseForExpertTenant(
|
||||
doc: any,
|
||||
actor: { sub: string; clientKey?: string },
|
||||
|
||||
@@ -91,6 +91,12 @@ import {
|
||||
MUTUAL_AGREEMENT_EXPERT_DECISION_FIELDS,
|
||||
} from "src/helpers/blame-party-agreement-decision";
|
||||
import { buildFileLink } from "src/helpers/urlCreator";
|
||||
import {
|
||||
buildUserLookupByPhone,
|
||||
iranMobileLookupVariants,
|
||||
normalizeIranMobile,
|
||||
partyPersonMatchesUser,
|
||||
} from "src/helpers/iran-mobile";
|
||||
|
||||
@Injectable()
|
||||
export class RequestManagementService {
|
||||
@@ -209,14 +215,8 @@ export class RequestManagementService {
|
||||
private assertPartyOwner(party: any, user: any, errMsg: string, req?: any) {
|
||||
// The initiating field-expert/registrar fills steps on behalf of parties.
|
||||
if (req && this.isBlameOnBehalfActor(req, user)) return;
|
||||
const partyUserId = party?.person?.userId
|
||||
? String(party.person.userId)
|
||||
: null;
|
||||
const ok =
|
||||
(partyUserId && partyUserId === String(user?.sub)) ||
|
||||
(party?.person?.phoneNumber &&
|
||||
party.person.phoneNumber === user?.username);
|
||||
if (!ok) throw new ForbiddenException(errMsg);
|
||||
if (partyPersonMatchesUser(party?.person, user)) return;
|
||||
throw new ForbiddenException(errMsg);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -4434,7 +4434,8 @@ export class RequestManagementService {
|
||||
throw new BadRequestException("First party not found on request");
|
||||
const userId = await this.getOrCreateUserByPhoneNumber(phone);
|
||||
if (!req.parties[firstIdx].person) req.parties[firstIdx].person = {} as any;
|
||||
req.parties[firstIdx].person.phoneNumber = phone;
|
||||
req.parties[firstIdx].person.phoneNumber =
|
||||
normalizeIranMobile(phone) ?? phone;
|
||||
req.parties[firstIdx].person.userId = userId;
|
||||
|
||||
const expertName = `${expert?.lastName || ""}`.trim() || "کارشناس";
|
||||
@@ -4591,7 +4592,9 @@ export class RequestManagementService {
|
||||
throw new BadRequestException("First party not found on request");
|
||||
if (!req.parties[firstIdx].person) req.parties[firstIdx].person = {} as any;
|
||||
req.parties[firstIdx].person.userId = firstUserId;
|
||||
req.parties[firstIdx].person.phoneNumber = dto.firstPartyPhoneNumber;
|
||||
req.parties[firstIdx].person.phoneNumber =
|
||||
normalizeIranMobile(dto.firstPartyPhoneNumber) ??
|
||||
dto.firstPartyPhoneNumber;
|
||||
|
||||
if (
|
||||
req.type === BlameRequestType.THIRD_PARTY &&
|
||||
@@ -4617,7 +4620,9 @@ export class RequestManagementService {
|
||||
if (!req.parties[secondIdx].person)
|
||||
req.parties[secondIdx].person = {} as any;
|
||||
req.parties[secondIdx].person.userId = secondUserId;
|
||||
req.parties[secondIdx].person.phoneNumber = dto.secondPartyPhoneNumber;
|
||||
req.parties[secondIdx].person.phoneNumber =
|
||||
normalizeIranMobile(dto.secondPartyPhoneNumber) ??
|
||||
dto.secondPartyPhoneNumber;
|
||||
}
|
||||
} else if (
|
||||
req.type === BlameRequestType.THIRD_PARTY &&
|
||||
@@ -4794,6 +4799,7 @@ export class RequestManagementService {
|
||||
const valid = await this.hashService.compare(otp, u.otp);
|
||||
if (!valid) throw new BadRequestException(`Invalid OTP for ${phone}`);
|
||||
const userId = u._id as Types.ObjectId;
|
||||
const canonicalPhone = normalizeIranMobile(phone) ?? phone;
|
||||
|
||||
if (role === PartyRole.FIRST) {
|
||||
if (firstIdx === -1)
|
||||
@@ -4801,13 +4807,21 @@ export class RequestManagementService {
|
||||
if (!req.parties[firstIdx].person)
|
||||
req.parties[firstIdx].person = {} as any;
|
||||
req.parties[firstIdx].person.userId = userId;
|
||||
req.parties[firstIdx].person.phoneNumber = phone;
|
||||
req.parties[firstIdx].person.phoneNumber = canonicalPhone;
|
||||
} else {
|
||||
const firstPhone =
|
||||
firstIdx !== -1
|
||||
? (req.parties[firstIdx]?.person as any)?.phoneNumber
|
||||
: undefined;
|
||||
if (firstPhone && firstPhone === phone) {
|
||||
const firstVariants = firstPhone
|
||||
? iranMobileLookupVariants(firstPhone)
|
||||
: [];
|
||||
if (
|
||||
firstPhone &&
|
||||
(firstPhone === phone ||
|
||||
firstVariants.includes(phone) ||
|
||||
firstVariants.includes(canonicalPhone))
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
"Second party phone number cannot be the same as first party.",
|
||||
);
|
||||
@@ -4816,13 +4830,13 @@ export class RequestManagementService {
|
||||
if (secondIdx === -1) {
|
||||
req.parties.push({
|
||||
role: PartyRole.SECOND,
|
||||
person: { userId, phoneNumber: phone },
|
||||
person: { userId, phoneNumber: canonicalPhone },
|
||||
} as any);
|
||||
} else {
|
||||
if (!req.parties[secondIdx].person)
|
||||
req.parties[secondIdx].person = {} as any;
|
||||
req.parties[secondIdx].person.userId = userId;
|
||||
req.parties[secondIdx].person.phoneNumber = phone;
|
||||
req.parties[secondIdx].person.phoneNumber = canonicalPhone;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5018,9 +5032,16 @@ export class RequestManagementService {
|
||||
user?.sub && Types.ObjectId.isValid(user.sub)
|
||||
? { "parties.person.userId": new Types.ObjectId(user.sub) }
|
||||
: null;
|
||||
const phoneFilter = user?.username
|
||||
? { "parties.person.phoneNumber": user.username }
|
||||
: null;
|
||||
const phoneVariants =
|
||||
user?.role === RoleEnum.USER && user?.username
|
||||
? iranMobileLookupVariants(user.username)
|
||||
: user?.username
|
||||
? [user.username]
|
||||
: [];
|
||||
const phoneFilter =
|
||||
phoneVariants.length > 0
|
||||
? { "parties.person.phoneNumber": { $in: phoneVariants } }
|
||||
: null;
|
||||
|
||||
const orConditions: Record<string, unknown>[] = [];
|
||||
if (userIdFilter) orConditions.push(userIdFilter);
|
||||
@@ -5061,11 +5082,8 @@ export class RequestManagementService {
|
||||
req.registrarInitiated &&
|
||||
String(req.initiatedByRegistrarId) === String(user.sub));
|
||||
|
||||
const party = req.parties?.find(
|
||||
(p: any) =>
|
||||
(p?.person?.userId &&
|
||||
String(p.person.userId) === String(user.sub)) ||
|
||||
(p?.person?.phoneNumber && p.person.phoneNumber === user?.username),
|
||||
const party = req.parties?.find((p: any) =>
|
||||
partyPersonMatchesUser(p?.person, user),
|
||||
);
|
||||
|
||||
const obj = req.toObject();
|
||||
@@ -5340,14 +5358,7 @@ export class RequestManagementService {
|
||||
String(req.initiatedByRegistrarId) === String(user?.sub);
|
||||
const isParty =
|
||||
Array.isArray(req.parties) &&
|
||||
req.parties.some((p: any) => {
|
||||
const pid = p?.person?.userId ? String(p.person.userId) : null;
|
||||
const phone = p?.person?.phoneNumber;
|
||||
return (
|
||||
(pid && pid === String(user?.sub)) ||
|
||||
(phone && phone === user?.username)
|
||||
);
|
||||
});
|
||||
req.parties.some((p: any) => partyPersonMatchesUser(p?.person, user));
|
||||
if (!isFieldExpertOwner && !isRegistrarOwner && !isParty) {
|
||||
throw new ForbiddenException("You do not have access to this request");
|
||||
}
|
||||
@@ -5359,10 +5370,22 @@ export class RequestManagementService {
|
||||
Types.ObjectId.isValid(user.sub)
|
||||
) {
|
||||
let updated = false;
|
||||
const phoneVariants = iranMobileLookupVariants(user?.username);
|
||||
for (const p of req.parties || []) {
|
||||
if (p?.person?.phoneNumber === user?.username && !p.person?.userId) {
|
||||
const person = p?.person;
|
||||
if (!person) continue;
|
||||
const phoneMatch =
|
||||
person.phoneNumber &&
|
||||
phoneVariants.some(
|
||||
(v) => v === person.phoneNumber || v === normalizeIranMobile(person.phoneNumber),
|
||||
);
|
||||
if (phoneMatch && !person?.userId) {
|
||||
p.person = p.person || {};
|
||||
(p.person as any).userId = new Types.ObjectId(user.sub);
|
||||
if (user?.username) {
|
||||
(p.person as any).phoneNumber =
|
||||
normalizeIranMobile(user.username) ?? user.username;
|
||||
}
|
||||
updated = true;
|
||||
}
|
||||
}
|
||||
@@ -5384,14 +5407,9 @@ export class RequestManagementService {
|
||||
const visibleParties =
|
||||
isFieldExpertOwner || isRegistrarOwner
|
||||
? allParties
|
||||
: allParties.filter((p: any) => {
|
||||
const pid = p?.person?.userId ? String(p.person.userId) : null;
|
||||
const phone = p?.person?.phoneNumber;
|
||||
return (
|
||||
(pid && pid === String(user?.sub)) ||
|
||||
(phone && phone === user?.username)
|
||||
);
|
||||
});
|
||||
: allParties.filter((p: any) =>
|
||||
partyPersonMatchesUser(p?.person, user),
|
||||
);
|
||||
const parties = await Promise.all(
|
||||
visibleParties.map((p: any) => this.sanitizePartyForBlameUserView(p)),
|
||||
);
|
||||
@@ -7288,19 +7306,18 @@ export class RequestManagementService {
|
||||
private async getOrCreateUserByPhoneNumber(
|
||||
phoneNumber: string,
|
||||
): Promise<Types.ObjectId> {
|
||||
// Try to find existing user by phone number (username or mobile)
|
||||
let user = await this.userDbService.findOne({
|
||||
$or: [{ username: phoneNumber }, { mobile: phoneNumber }],
|
||||
});
|
||||
const canonical = normalizeIranMobile(phoneNumber) ?? phoneNumber.trim();
|
||||
let user = await this.userDbService.findOne(
|
||||
buildUserLookupByPhone(canonical),
|
||||
);
|
||||
|
||||
if (user) {
|
||||
return new Types.ObjectId((user as any)._id);
|
||||
}
|
||||
|
||||
// User doesn't exist, create a new one
|
||||
const newUser = await this.userDbService.createUser({
|
||||
mobile: phoneNumber,
|
||||
username: phoneNumber,
|
||||
mobile: canonical,
|
||||
username: canonical,
|
||||
otp: "",
|
||||
tokens: {
|
||||
token: "",
|
||||
|
||||
Reference in New Issue
Block a user