fix: make user branch selection and signature completion reliable

This commit is contained in:
SepehrYahyaee
2026-11-16 10:40:09 +03:30
parent 775934c056
commit e5c4b740e7
10 changed files with 406 additions and 118 deletions
@@ -96,6 +96,17 @@ function setup(type = Kind.CAR_BODY) {
return req;
}),
};
api.blameRequestDbService.findOneAndUpdate = jest.fn(async (filter, update) => {
if (filter.status && req.status !== filter.status) return null;
const pending = Object.keys(filter).find((key) => key.endsWith(".confirmation"));
if (pending && pending.split(".").reduce((row, key) => row?.[key], req)) return null;
await api.blameRequestDbService.findByIdAndUpdate(req._id, update);
for (const [key, value] of Object.entries(update.$addToSet ?? {})) {
const old = key.split(".").reduce((row, bit) => row?.[bit], req) ?? [];
set(key, [...new Set([...old, value])]);
}
return req;
});
api.workflowStepDbService = {
findByStepNumber: jest.fn(async (n) =>
docs.find((d) => d.stepNumber === n),
@@ -278,7 +289,7 @@ describe("V6 call-center workflow", () => {
);
await expect(
service.userSignDecisionV2(id, first.sub, true, media),
).rejects.toThrow();
).resolves.toMatchObject({ status: CaseStatus.COMPLETED });
},
);
@@ -1,4 +1,5 @@
import { ApiProperty } from "@nestjs/swagger";
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import type { BlameUserNextAction } from "src/helpers/blame-user-progress";
export class UserSignatureResponseDto {
@ApiProperty({
@@ -24,4 +25,24 @@ export class UserSignatureResponseDto {
description: "Result message",
})
message: string;
@ApiPropertyOptional({ description: "Next action for the signing user" })
nextAction?: BlameUserNextAction;
@ApiPropertyOptional({ type: Object })
confirmation?: {
accepted?: boolean;
signature?: { fileId?: string; fileName?: string; fileUrl?: string };
};
@ApiPropertyOptional({ type: Object })
claimBranch?: { required: boolean; branchId: string | null };
@ApiPropertyOptional({ type: Object })
claimCreation?: {
hasClaim: boolean;
shouldGuideToCreateClaim: boolean;
claimRequestId?: string;
canContinueClaim?: boolean;
};
}
@@ -16,4 +16,8 @@ export class UserSignDbService {
// Use your correct Model type
return this.blameVoiceModel.findById(id).lean();
}
async deleteById(id: string): Promise<void> {
await this.blameVoiceModel.findByIdAndDelete(id);
}
}
@@ -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);
}
// ---------------------------------------------------------------------------
@@ -249,4 +249,20 @@ describe("user blame next action and claim eligibility", () => {
expect(response.parties[0].role).toBe("SECOND");
expect(JSON.stringify(response)).not.toContain("09120000001");
});
it("repairs interrupted signatures in the case list before calculating the next page", async () => {
const service = subject();
const record = blame({status:"WAITING_FOR_SIGNATURES",workflow:{currentStep:"WAITING_FOR_SIGNATURES"}});
service.blameRequestDbService = {
find: jest.fn().mockResolvedValue([record]),
findOneAndUpdate: jest.fn(async (filter,update) => {
expect(filter.status).toBe("WAITING_FOR_SIGNATURES");
expect(filter.$and).toHaveLength(2);
return {...record,status:update.$set.status,workflow:{currentStep:"COMPLETED"}};
}),
};
const response = await service.getAllBlameRequestsV2({sub:damagedId,role:RoleEnum.USER});
expect(response.list[0]).toMatchObject({status:"COMPLETED",nextAction:"CREATE_CLAIM"});
expect(service.blameRequestDbService.findOneAndUpdate).toHaveBeenCalledTimes(1);
});
});
@@ -1,4 +1,5 @@
import { extname } from "node:path";
import { randomUUID } from "node:crypto";
import { mkdirSync } from "node:fs";
import {
Body,
@@ -392,7 +393,7 @@ export class RequestManagementV2Controller {
storage: diskStorage({
destination: "./files/signs",
filename: (req, file, callback) => {
const unique = Date.now();
const unique = randomUUID();
const ext = extname(file.originalname);
const filename = `${file.originalname.split(/[.,\s-]/)[0]}-${unique}${ext}`;
callback(null, filename);