forked from Yara724/api
fix: make user branch selection and signature completion reliable
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { UserClaimBranchService, userClaimBranchContext } from "src/client/user-claim-branch.service";
|
||||
import { UserClaimBranchService, userClaimBranchContext, usesUserClaimBranch } from "src/client/user-claim-branch.service";
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
@@ -4428,7 +4428,7 @@ export class RequestManagementService {
|
||||
: ({ $or: orConditions } as any),
|
||||
{
|
||||
select:
|
||||
"publicId requestNo type status blameStatus createdAt updatedAt parties expert.decision.guiltyPartyId expertInitiated registrarInitiated initiatedByFieldExpertId initiatedByRegistrarId creationMethod",
|
||||
"publicId requestNo type status blameStatus createdAt updatedAt parties expert.decision.guiltyPartyId expertInitiated registrarInitiated initiatedByFieldExpertId initiatedByRegistrarId creationMethod callCenterInitiated isMadeByFileMaker",
|
||||
},
|
||||
);
|
||||
|
||||
@@ -4450,7 +4450,8 @@ export class RequestManagementService {
|
||||
);
|
||||
|
||||
const enriched = await Promise.all(
|
||||
requests.map(async (req: any) => {
|
||||
requests.map(async (record: any) => {
|
||||
const req = await this.settleUserSignatures(record);
|
||||
const isInitiator =
|
||||
(user?.role === RoleEnum.FIELD_EXPERT &&
|
||||
req.expertInitiated &&
|
||||
@@ -4759,11 +4760,48 @@ export class RequestManagementService {
|
||||
return { ...out, expertName };
|
||||
}
|
||||
|
||||
/**
|
||||
* V2: Get one blame request by id. Access allowed if current user is a party (by userId or phone)
|
||||
* or the initiating field expert. For expert-initiated LINK, party access by phone is sufficient.
|
||||
*/
|
||||
async getBlameRequestV2(requestId: string, user: any): Promise<any> {
|
||||
/** Finish an interrupted user signature transition without reopening stopped/expert-led files. */
|
||||
private async settleUserSignatures(req: any): Promise<any> {
|
||||
if (!usesUserClaimBranch(req) || req.status !== CaseStatus.WAITING_FOR_SIGNATURES) return req;
|
||||
if (req.type === BlameRequestType.THIRD_PARTY && !req.expert?.decision?.guiltyPartyId) return req;
|
||||
const roles = req.type === BlameRequestType.CAR_BODY
|
||||
? [PartyRole.FIRST]
|
||||
: req.type === BlameRequestType.THIRD_PARTY ? [PartyRole.FIRST, PartyRole.SECOND] : [];
|
||||
if (!roles.length || req.parties?.length !== roles.length || roles.some((role) => {
|
||||
const party = req.parties.find((p: any) => p.role === role);
|
||||
return !party?.person?.userId || party.confirmation?.accepted !== true || !party.confirmation.signature?.fileId;
|
||||
})) return req;
|
||||
|
||||
const completed = await this.blameRequestDbService.findOneAndUpdate(
|
||||
{
|
||||
_id: req._id,
|
||||
status: CaseStatus.WAITING_FOR_SIGNATURES,
|
||||
$and: roles.map((role) => ({ parties: { $elemMatch: {
|
||||
role, "confirmation.accepted": true,
|
||||
"confirmation.signature.fileId": { $exists: true, $nin: [null, ""] },
|
||||
} } })),
|
||||
},
|
||||
{
|
||||
$set: { status: CaseStatus.COMPLETED, "workflow.currentStep": "COMPLETED", "workflow.nextStep": null },
|
||||
$addToSet: { "workflow.completedSteps": WorkflowStep.WAITING_FOR_SIGNATURES },
|
||||
},
|
||||
);
|
||||
return completed ?? await this.blameRequestDbService.findById(req._id) ?? req;
|
||||
}
|
||||
|
||||
private async userSignatureResult(req: any, userId: string, message: string): Promise<UserSignatureResponseDto> {
|
||||
const party = req.parties.find((p: any) => String(p.person?.userId) === String(userId));
|
||||
const claimCreation = await this.computeClaimCreationHintForViewer(req, { sub: userId });
|
||||
return {
|
||||
requestId: String(req._id), accepted: party?.confirmation?.accepted === true,
|
||||
status: req.status, message, confirmation: party?.confirmation,
|
||||
claimBranch: userClaimBranchContext(req, userId), claimCreation,
|
||||
nextAction: resolveBlameUserNextAction(req.status, party, claimCreation),
|
||||
};
|
||||
}
|
||||
|
||||
/** Shared case authorization/binding without hydrating media or the expert profile. */
|
||||
private async loadAccessibleBlameRequestV2(requestId: string, user: any) {
|
||||
const req = await this.blameRequestDbService.findById(requestId);
|
||||
if (!req) {
|
||||
throw new NotFoundException("Request not found");
|
||||
@@ -4826,6 +4864,14 @@ export class RequestManagementService {
|
||||
}
|
||||
}
|
||||
|
||||
const settled = await this.settleUserSignatures(req);
|
||||
return { req: settled, linkedUserIds, isFieldExpertOwner, isRegistrarOwner };
|
||||
}
|
||||
|
||||
async getBlameRequestV2(requestId: string, user: any): Promise<any> {
|
||||
const { req, linkedUserIds, isFieldExpertOwner, isRegistrarOwner } =
|
||||
await this.loadAccessibleBlameRequestV2(requestId, user);
|
||||
|
||||
const claimCreation = await this.computeClaimCreationHintForViewer(
|
||||
req,
|
||||
user,
|
||||
@@ -6346,9 +6392,7 @@ export class RequestManagementService {
|
||||
|
||||
/** Same access boundary as the user case detail; never accept an insurer id from the browser. */
|
||||
async getUserClaimBranches(requestId: string, user: any) {
|
||||
await this.getBlameRequestV2(requestId, user);
|
||||
const req = await this.blameRequestDbService.findById(requestId);
|
||||
if (!req) throw new NotFoundException("پرونده پیدا نشد.");
|
||||
const { req } = await this.loadAccessibleBlameRequestV2(requestId, user);
|
||||
const context = userClaimBranchContext(req, String(user.sub));
|
||||
if (!context.required) return { ...context, branches: [], locked: true };
|
||||
const claim = await this.claimCaseDbService.findOne({ blameRequestId: req._id });
|
||||
@@ -6356,15 +6400,14 @@ export class RequestManagementService {
|
||||
...context,
|
||||
branchId: claim?.branchId ? String(claim.branchId) : context.branchId,
|
||||
locked: !!claim,
|
||||
branches: await this.userClaimBranchService.options(req),
|
||||
...(claim ? { claimRequestId: String(claim._id) } : {}),
|
||||
branches: claim ? [] : await this.userClaimBranchService.options(req),
|
||||
};
|
||||
}
|
||||
|
||||
/** Also supports already-signed legacy cases, before their first claim is created. */
|
||||
async selectUserClaimBranch(requestId: string, user: any, branchId: unknown) {
|
||||
await this.getBlameRequestV2(requestId, user);
|
||||
const req = await this.blameRequestDbService.findById(requestId);
|
||||
if (!req) throw new NotFoundException("پرونده پیدا نشد.");
|
||||
const { req } = await this.loadAccessibleBlameRequestV2(requestId, user);
|
||||
if (!userClaimBranchContext(req, String(user.sub)).required) {
|
||||
throw new ForbiddenException("فقط طرف زیاندیده میتواند شعبه رسیدگی به خسارت را انتخاب کند.");
|
||||
}
|
||||
@@ -6393,44 +6436,30 @@ export class RequestManagementService {
|
||||
throw new BadRequestException("A signature file is required");
|
||||
}
|
||||
|
||||
const request = await this.blameRequestDbService.findById(requestId);
|
||||
let request = await this.blameRequestDbService.findById(requestId);
|
||||
if (!request) {
|
||||
throw new NotFoundException("Request not found");
|
||||
}
|
||||
|
||||
// Validate status is WAITING_FOR_SIGNATURES
|
||||
if (request.status !== CaseStatus.WAITING_FOR_SIGNATURES) {
|
||||
throw new BadRequestException(
|
||||
"Request is not waiting for signatures. Current status: " +
|
||||
request.status,
|
||||
);
|
||||
}
|
||||
|
||||
// THIRD_PARTY: blame expert must have issued a guilt decision before signatures.
|
||||
// CAR_BODY: single-party flow; no blame expert / no expert.decision by design.
|
||||
if (
|
||||
request.type !== BlameRequestType.CAR_BODY &&
|
||||
!request.expert?.decision
|
||||
) {
|
||||
throw new BadRequestException("Expert has not made a decision yet");
|
||||
}
|
||||
|
||||
// Find user's party
|
||||
const parties = request.parties || [];
|
||||
const partyIndex = parties.findIndex(
|
||||
// Authorize before treating an already-persisted signature as a safe retry.
|
||||
const partyIndex = (request.parties || []).findIndex(
|
||||
(p) => String(p.person?.userId) === String(userId),
|
||||
);
|
||||
|
||||
if (partyIndex === -1) {
|
||||
throw new ForbiddenException("You are not a party in this request");
|
||||
}
|
||||
|
||||
const userParty = parties[partyIndex];
|
||||
|
||||
// Check if user already signed
|
||||
if (partyIndex === -1) throw new ForbiddenException("You are not a party in this request");
|
||||
request = await this.settleUserSignatures(request);
|
||||
const userParty = request.parties[partyIndex];
|
||||
if (userParty.confirmation) {
|
||||
if (userParty.confirmation.accepted === isAccept && userParty.confirmation.signature?.fileId) {
|
||||
return this.userSignatureResult(request, userId, "امضای شما قبلاً ثبت شده است.");
|
||||
}
|
||||
throw new BadRequestException("You have already signed this decision");
|
||||
}
|
||||
if (request.status !== CaseStatus.WAITING_FOR_SIGNATURES) {
|
||||
throw new BadRequestException("Request is not waiting for signatures. Current status: " + request.status);
|
||||
}
|
||||
if (request.type !== BlameRequestType.CAR_BODY && !request.expert?.decision) {
|
||||
throw new BadRequestException("Expert has not made a decision yet");
|
||||
}
|
||||
|
||||
const branchContext = userClaimBranchContext(request, userId);
|
||||
let selectedBranchId: string | undefined;
|
||||
@@ -6463,45 +6492,35 @@ export class RequestManagementService {
|
||||
signature: signatureData,
|
||||
};
|
||||
|
||||
// Any single rejection stops the case immediately (in-person resolution required).
|
||||
if (!isAccept) {
|
||||
await this.blameRequestDbService.findByIdAndUpdate(requestId, {
|
||||
$set: {
|
||||
status: CaseStatus.STOPPED,
|
||||
[`parties.${partyIndex}.confirmation`]: confirmationPayload,
|
||||
"workflow.nextStep": null,
|
||||
},
|
||||
$push: {
|
||||
history: {
|
||||
type: "PARTY_REJECTED_EXPERT_DECISION",
|
||||
timestamp: new Date(),
|
||||
metadata: {
|
||||
userId,
|
||||
partyRole: userParty.role,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
this.logger.log(
|
||||
`Party rejected expert decision for request ${requestId}; status STOPPED.`,
|
||||
);
|
||||
|
||||
return {
|
||||
requestId: String(request._id),
|
||||
accepted: false,
|
||||
status: CaseStatus.STOPPED,
|
||||
message:
|
||||
"You rejected the expert decision. This case is stopped and requires in-person resolution.",
|
||||
};
|
||||
}
|
||||
|
||||
await this.blameRequestDbService.findByIdAndUpdate(requestId, {
|
||||
const update = {
|
||||
$set: {
|
||||
[`parties.${partyIndex}.confirmation`]: confirmationPayload,
|
||||
...(selectedBranchId ? { branchId: new Types.ObjectId(selectedBranchId) } : {}),
|
||||
...(!isAccept ? { status: CaseStatus.STOPPED, "workflow.nextStep": null } : {}),
|
||||
},
|
||||
});
|
||||
...(!isAccept ? { $push: { history: {
|
||||
type: "PARTY_REJECTED_EXPERT_DECISION", timestamp: new Date(),
|
||||
metadata: { userId, partyRole: userParty.role },
|
||||
} } } : {}),
|
||||
};
|
||||
const saved = usesUserClaimBranch(request)
|
||||
? await this.blameRequestDbService.findOneAndUpdate({
|
||||
_id: request._id, status: CaseStatus.WAITING_FOR_SIGNATURES,
|
||||
[`parties.${partyIndex}.confirmation`]: null,
|
||||
}, update)
|
||||
: await this.blameRequestDbService.findByIdAndUpdate(requestId, update);
|
||||
if (!saved) {
|
||||
await this.userSign.deleteById(String((signDoc as any)._id));
|
||||
const fresh = await this.blameRequestDbService.findById(requestId);
|
||||
const confirmation = fresh?.parties?.[partyIndex]?.confirmation;
|
||||
if (confirmation?.accepted === isAccept && confirmation.signature?.fileId) {
|
||||
return this.userSignatureResult(await this.settleUserSignatures(fresh), userId, "امضای شما قبلاً ثبت شده است.");
|
||||
}
|
||||
throw new ConflictException("وضعیت پرونده تغییر کرده است. پرونده را دوباره باز کنید.");
|
||||
}
|
||||
if (!isAccept) {
|
||||
return this.userSignatureResult(saved, userId, "گزارش تأیید نشد و پرونده برای رسیدگی حضوری متوقف شد.");
|
||||
}
|
||||
|
||||
const updatedRequest = await this.blameRequestDbService.findById(requestId);
|
||||
const allPartiesSigned = updatedRequest.parties.every(
|
||||
@@ -6523,20 +6542,20 @@ export class RequestManagementService {
|
||||
? "Case completed successfully."
|
||||
: "Both parties have accepted. Case completed successfully.";
|
||||
|
||||
await this.blameRequestDbService.findByIdAndUpdate(requestId, {
|
||||
$set: {
|
||||
status: CaseStatus.COMPLETED,
|
||||
"workflow.currentStep": "COMPLETED",
|
||||
"workflow.nextStep": null,
|
||||
},
|
||||
$push: {
|
||||
"workflow.completedSteps": "WAITING_FOR_SIGNATURES",
|
||||
},
|
||||
});
|
||||
if (usesUserClaimBranch(updatedRequest)) {
|
||||
const settled = await this.settleUserSignatures(updatedRequest);
|
||||
finalStatus = settled.status;
|
||||
} else {
|
||||
await this.blameRequestDbService.findByIdAndUpdate(requestId, {
|
||||
$set: { status: CaseStatus.COMPLETED, "workflow.currentStep": "COMPLETED", "workflow.nextStep": null },
|
||||
$addToSet: { "workflow.completedSteps": WorkflowStep.WAITING_FOR_SIGNATURES },
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
finalStatus === CaseStatus.COMPLETED && (
|
||||
updatedRequest.type === BlameRequestType.THIRD_PARTY ||
|
||||
updatedRequest.type === BlameRequestType.CAR_BODY
|
||||
updatedRequest.type === BlameRequestType.CAR_BODY)
|
||||
) {
|
||||
let targetPhone: string | undefined;
|
||||
|
||||
@@ -6568,13 +6587,13 @@ export class RequestManagementService {
|
||||
: "SECOND",
|
||||
request.callCenterInitiated ? "v6" : "v1",
|
||||
);
|
||||
await this.smsOrchestrationService.sendThirdPartyDamagedPartyClaimLinkNotice(
|
||||
{
|
||||
receptor: targetPhone,
|
||||
publicId,
|
||||
link,
|
||||
},
|
||||
);
|
||||
try {
|
||||
await this.smsOrchestrationService.sendThirdPartyDamagedPartyClaimLinkNotice(
|
||||
{ receptor: targetPhone, publicId, link },
|
||||
);
|
||||
} catch {
|
||||
this.logger.warn(`Claim-link SMS failed after signature was saved for request ${requestId}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -6602,12 +6621,8 @@ export class RequestManagementService {
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
requestId: String(request._id),
|
||||
accepted: isAccept,
|
||||
status: finalStatus,
|
||||
message,
|
||||
};
|
||||
const persisted = await this.blameRequestDbService.findById(requestId);
|
||||
return this.userSignatureResult(persisted, userId, message);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user