Merge pull request 'fix: make user branch selection and signature completion reliable' (#399) from s.yahyaee/yara724-api:main into main

Reviewed-on: Yara724/api#399
This commit is contained in:
2026-11-16 10:41:30 +03:30
10 changed files with 406 additions and 118 deletions
+49 -2
View File
@@ -8,7 +8,7 @@ Expert/registrar/FileMaker-created flows retain their existing branch/ownership
All routes below use existing user authentication and the user-role guard:
- `GET /v2/blame-request-management/:requestId/claim-branches`: authorize case access, resolve the beneficiary/payer, and return `{required, branchId, locked, branches}`. Only the beneficiary receives branch options. Each option contains `id`, `name`, `code`, `city`, `state`, `address`, and optional `phoneNumber`. Options are active branches from the payer only; the client cannot supply an insurer ID.
- `GET /v2/blame-request-management/:requestId/claim-branches`: authorize case access, resolve the beneficiary/payer, and return `{required, branchId, locked, branches, claimRequestId?}`. `claimRequestId` is included when a claim already exists for the beneficiary so reloading claim entry can resume it. Locked claims do not fetch branch options. Only the beneficiary receives branch options. Each option contains `id`, `name`, `code`, `city`, `state`, `address`, and optional `phoneNumber`. Options are active branches from the payer only; the client cannot supply an insurer ID.
- `PUT /v2/blame-request-management/:requestId/claim-branch`: `{branchId}` saves a validated branch while waiting for signatures or after signing, before any claim exists. This supports historical cases that were already signed when the feature deployed. Other parties cannot select a branch. Existing claims freeze routing; this endpoint cannot move them to another branch.
- Existing `PUT /v2/blame-request-management/sign/:requestId` accepts an additional multipart `branchId`. When the damaged user accepts in a user-led flow, a valid branch is mandatory (either supplied now or previously saved). Branch validation occurs before creating the signature record. Confirmation and branch ID are saved in the same blame update. The guilty party signs normally without choosing a branch. Rejection does not require a branch.
@@ -28,7 +28,7 @@ Existing claims are not migrated or reassigned. Their current access/ownership r
The city and branch selectors appear above the signature canvas, only for the damaged user. A city change clears the branch selection. Same-named cities in different provinces have separate choices. The selected branch's address and phone are displayed. Loading, fetch failure/retry, empty lists and locked routing have explicit Persian states. Confirmation is disabled until the selection is valid. The signature dialog scrolls vertically on small screens.
The final screen reuses the selector for cases already signed before rollout; the backend selection rule also protects direct claim entry. Later v6 claim-result signing no longer asks for another branch, avoiding a competing choice. Existing expert-created flows retain their existing result-signing UI.
The final screen displays the saved branch by name. It only shows the selector for signed cases without a valid active selection (including historical cases); the backend selection rule also protects direct claim entry. Later v6 claim-result signing no longer asks for another branch, avoiding a competing choice. Existing expert-created flows retain their existing result-signing UI.
## Deployment and verification
@@ -55,3 +55,50 @@ The matrix covers v1 car-body, v6 car-body, both possible v1 third-party damaged
Browser tests draw a signature, verify its multipart request includes the selected branch, continue to claim creation once, and verify the claim can proceed. Changing city clears the previous branch. Existing signed cases entering `/claim` without a branch return to the branch picker. Separate v1/v6 guilty-party checks confirm no branch selection is requested and no claim-creation button appears. Existing suites cover the flow 2–5 ownership and file-maker/reviewer handoff rules.
No new application defect was found in this verification pass; the additional HTTP integration tests/configuration were retained as regression coverage. External-provider availability, production branch/staff configuration, real database connectivity/indexes and live SMS delivery were not exercised. Those still require deployment QA; these results do not claim an exhaustive proof of every possible application state.
## Reliability corrections — 2026-11-16
The original implementation hydrated the complete case (voice/video URLs, expert profile and claim hints) just to authorize branch loading, then loaded that case again. The branch endpoint now reuses the exact authorization, user binding and workflow recovery logic directly, with no media/profile hydration. Legacy branch city/state values are normalized before sorting.
The frontend branch query has a 15-second timeout and explicit retry. A disabled query no longer renders a loader; an unparseable local JWT no longer silently disables the query forever. Options are cached for 30 seconds by actor and case; every save/signature and claim creation still validates the selected branch on the server. Empty active-branch lists remain a real setup error, with an explicit Persian explanation. They cannot be bypassed by accepting an arbitrary branch.
Accepting a signature now returns the persisted status, the viewer's `nextAction`, their confirmation, `claimBranch`, and `claimCreation`. The frontend applies that acknowledgement to both the case and branch caches immediately. It does not wait for an additional case GET before navigating. That cache update is essential: without it the next screen still has the pre-signature `branchId: null` and asks for the same branch again. A normal signed case therefore has one city/branch selection, on the blame-signature screen. Later acceptance of the financial assessment remains a separate legal decision and does not ask v1/v6 users for another branch.
User-led signatures use conditional writes: the case must still be waiting and the viewer must not already have a confirmation. A repeated identical acceptance returns the stored confirmation and branch without replacing them. A conflicting decision cannot overwrite an existing signature. Signature upload filenames use UUIDs so two users uploading `signature.png` in the same millisecond cannot overwrite each other's image. Completing the case is conditional on the persisted required signatures and waiting status; it uses `$addToSet` for workflow history. The same completion logic recovers interrupted records where all required accepted signatures exist but status remains waiting, on detail/list/branch reads or a safe retry. Stopped files and expert-created flows are excluded from this recovery. A notification failure after saving cannot turn a persisted signature into a failed submission.
Case status polling continues while waiting for the other party, and the next action switches to claim creation only for the beneficiary. The culprit can sign without a branch and cannot create the claim. Case-detail requests are cancellable and bounded; intentional cancellation does not show a false error toast. Failed signing shows the actual Persian error and preserves the canvas while rechecking the saved state. Closing the signature dialog returns to a page with a signing link. Claim entry offers retry, and an existing claim returned by the branch preflight is resumed instead of creating a second claim.
### Regression commands
```bash
# API unit/regression suite, plus authenticated HTTP scenarios (mock repositories/providers).
npm test -- --runInBand
npm run test:e2e -- --runInBand
# In ui-user:
npm run test:ui
npx tsc --noEmit
```
The HTTP suite also has an optional combined browser tier. Start the user UI with a temporary test-only API URL, then run the test with Playwright installed. The browser forwards only that mock API prefix to the actual test HTTP controllers; JWT/role guards, case/branch/signature services and claim creation run normally. Database operations and SMS/Fanavaran remain isolated fixtures.
```bash
# ui-user terminal (use a separate dev build if another dev server is running):
NEXT_PUBLIC_BASE_URL=http://127.0.0.1:3217/mock-api NEXT_PUBLIC_BASE_PATH='' npm run dev -- --hostname 127.0.0.1 --port 3217
# api terminal; PLAYWRIGHT_MODULE may point to a locally installed Playwright package.
CLAIM_BRANCH_UI_URL=http://127.0.0.1:3217 PLAYWRIGHT_MODULE=/path/to/playwright npm run test:e2e -- --runInBand
# Optional: CLAIM_BRANCH_BROWSER_EXECUTABLE=/path/to/chrome-or-brave
```
Deploy API and ui-user together. No environment/schema migration is needed. Existing active branches and expert branch assignments are still required. No production data, real provider availability or live SMS delivery is exercised by these isolated tests.
### Verification of the corrections
- API: **97 suites / 874 tests passed**.
- Authenticated HTTP + combined mobile browser tier: **30 scenarios passed**, including four real UI → controller → persistence scenarios for v1/v6 × car-body/third-party. Database repositories and providers are mocked.
- Additional isolated browser matrix: **13 normal/legacy/error scenarios and 6 recovery scenarios passed**, covering desktop/mobile layouts, delayed GETs after signing, guilty-party access, historic signed cases, branch errors/timeouts, empty options, waiting for the other signature, failed signing, double-clicks and cancellation. These use Chromium/Brave with emulated desktop/mobile viewports and drawn canvas signatures.
- Complete user UI regression script, API/user TypeScript checks and whitespace checks passed.
- The default Next.js production build (`npm run build`) passed with normal build-worker permissions. The initial sandboxed compilation was stopped after stalling; no deployment configuration was changed.
The tests do not change production data or contact SMS/Fanavaran. The browser tier is intentionally opt-in so a developer without Playwright can still run all HTTP tests; use the command above to include it.
+16 -4
View File
@@ -80,7 +80,19 @@ function setup(source = blame()) {
return source;
}),
};
api.userSign = { create: jest.fn().mockResolvedValue({ _id: "sign-id" }) };
api.blameRequestDbService.findOneAndUpdate = jest.fn(async (filter, update) => {
if (filter.status && source.status !== filter.status) return null;
const pending = Object.keys(filter).find((key) => key.endsWith(".confirmation"));
if (pending && pending.split(".").reduce((row, key) => row?.[key], source)) return null;
await api.blameRequestDbService.findByIdAndUpdate(source._id, update);
for (const [key, value] of Object.entries(update.$addToSet ?? {})) {
const bits = key.split("."); let row = source;
for (const bit of bits.slice(0, -1)) row = row[bit] ??= {};
row[bits.at(-1)!] = [...new Set([...(row[bits.at(-1)!] ?? []), value])];
}
return source;
});
api.userSign = { create: jest.fn().mockResolvedValue({ _id: "sign-id" }), deleteById: jest.fn() };
api.claimCaseDbService = { findOne: jest.fn().mockResolvedValue(null) };
api.logger = { log: jest.fn() };
return { routing, branches, api, source };
@@ -162,8 +174,8 @@ describe("user-selected claim branch", () => {
await api.userSignDecisionV2(String(api.sourceId), secondId, true, sign, branchId);
expect(String(source.branchId)).toBe(branchId);
expect(source.parties[1].confirmation.accepted).toBe(true);
expect(api.blameRequestDbService.findByIdAndUpdate).toHaveBeenCalledWith(
String(source._id),
expect(api.blameRequestDbService.findOneAndUpdate).toHaveBeenCalledWith(
expect.objectContaining({ _id: source._id, status: "WAITING_FOR_SIGNATURES", "parties.1.confirmation": null }),
expect.objectContaining({
$set: expect.objectContaining({
branchId: new Types.ObjectId(branchId),
@@ -189,7 +201,7 @@ describe("user-selected claim branch", () => {
});
it("authorizes case reads before offering branch data", async () => {
const { api, branches } = setup();
api.getBlameRequestV2 = jest.fn().mockRejectedValue(new Error("forbidden"));
api.loadAccessibleBlameRequestV2 = jest.fn().mockRejectedValue(new Error("forbidden"));
await expect(
api.getUserClaimBranches("case", { sub: secondId }),
).rejects.toThrow("forbidden");
+5 -5
View File
@@ -48,11 +48,11 @@ export class UserClaimBranchService {
return branches
.map((branch: any) => ({
id: String(branch._id),
name: branch.fullName || branch.name,
code: branch.code,
city: branch.city,
state: branch.state,
address: branch.address,
name: String(branch.fullName || branch.name || branch.code || "شعبه").trim(),
code: String(branch.code ?? ""),
city: String(branch.city ?? "").trim(),
state: String(branch.state ?? "").trim(),
address: String(branch.address ?? ""),
phoneNumber: branch.phoneNumber,
}))
.sort(
@@ -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.";
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,
},
$push: {
"workflow.completedSteps": "WAITING_FOR_SIGNATURES",
},
$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",
);
try {
await this.smsOrchestrationService.sendThirdPartyDamagedPartyClaimLinkNotice(
{
receptor: targetPhone,
publicId,
link,
},
{ 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);
+162 -1
View File
@@ -96,6 +96,22 @@ describe("v1/v6 branch routing through HTTP", () => {
}),
find: jest.fn(async () => [clone(blame)]),
};
const getPath = (row: any, key: string) => key.split(".").reduce((r, bit) => r?.[bit], row);
blameRepo["findOneAndUpdate"] = jest.fn(async (filter, update) => {
if (filter.status && blame.status !== filter.status) return null;
for (const key of Object.keys(filter).filter((key) => key.endsWith(".confirmation"))) {
if (getPath(blame, key) != null) return null;
}
if (filter.$and?.some((condition) => {
const expected = condition.parties.$elemMatch;
return !blame.parties.some((party) => party.role === expected.role &&
party.confirmation?.accepted === true && !!party.confirmation.signature?.fileId);
})) return null;
await blameRepo.findByIdAndUpdate(blame._id, update);
for (const [key, value] of Object.entries(update.$addToSet ?? {}))
setPath(blame, key, [...new Set([...(getPath(blame, key) ?? []), value])]);
return loadBlame();
});
const routing = new UserClaimBranchService({
findAllWithFilters: async (payerId, filter) =>
clone(
@@ -114,6 +130,7 @@ describe("v1/v6 branch routing through HTTP", () => {
userClaimBranchService: routing,
logger,
userSign: {
deleteById: async (id) => { signatures = signatures.filter((s) => s._id !== id); },
create: async (body) => {
const sign = { _id: String(new Types.ObjectId()), ...body };
signatures.push(sign);
@@ -172,7 +189,8 @@ describe("v1/v6 branch routing through HTTP", () => {
}).compile();
app = module.createNestApplication({ logger: false });
app.useGlobalFilters(new PersianErrorFilter(app.get(HttpAdapterHost)));
await app.init();
if (process.env.CLAIM_BRANCH_UI_URL) await app.listen(0, "127.0.0.1");
else await app.init();
jwt = app.get(JwtService);
});
afterAll(async () => {
@@ -479,4 +497,147 @@ describe("v1/v6 branch routing through HTTP", () => {
await create(ids.first).expect(400);
expect(claims).toHaveLength(0);
});
it.each(["v1", "v6"])("%s: simultaneous party signatures settle once and both responses agree with stored status", async (flow) => {
fixture(flow, "THIRD_PARTY", ids.first);
const responses = await Promise.all([sign(ids.first), sign(ids.second, ids.branch)]);
expect(responses.map((r) => r.status)).toEqual([200, 200]);
expect(blame.status).toBe("COMPLETED");
expect(blame.workflow.currentStep).toBe("COMPLETED");
expect(blame.workflow.completedSteps.filter((s) => s === "WAITING_FOR_SIGNATURES")).toHaveLength(1);
expect(signatures).toHaveLength(2);
expect(new Set(signatures.map((signature) => signature.path)).size).toBe(2);
const view = await request(app.getHttpServer()).get(url()).set("Authorization", auth(ids.second)).expect(200);
expect(view.body.nextAction).toBe("CREATE_CLAIM");
await create(ids.second).expect(201);
expect(claims).toHaveLength(1);
});
it.each(["v1", "v6"])("%s: duplicate submissions preserve the first signature and branch", async (flow) => {
fixture(flow, "CAR_BODY", ids.first);
const responses = await Promise.all([sign(ids.first, ids.branch), sign(ids.first, ids.otherBranch)]);
expect(responses.map((r) => r.status)).toEqual([200, 200]);
expect(signatures).toHaveLength(1);
const savedSignature = blame.parties[0].confirmation.signature.fileId;
const savedBranch = blame.branchId;
const retry = await sign(ids.first, ids.otherBranch).expect(200);
expect(retry.body).toMatchObject({status:"COMPLETED", nextAction:"CREATE_CLAIM", claimBranch:{branchId:savedBranch}});
expect(retry.body.confirmation.signature.fileId).toBe(savedSignature);
expect(blame.parties[0].confirmation.signature.fileId).toBe(savedSignature);
expect(blame.branchId).toBe(savedBranch);
expect(signatures).toHaveLength(1);
});
it.each(["v1", "v6"])("%s: signed records stuck waiting recover on reopen without another signature", async (flow) => {
fixture(flow, "THIRD_PARTY", ids.first);
blame.branchId = ids.branch;
for (const party of blame.parties) party.confirmation = { accepted:true, signature:{fileId:"existing-"+party.role} };
const view = await request(app.getHttpServer()).get(url()).set("Authorization", auth(ids.second)).expect(200);
expect(view.body).toMatchObject({status:"COMPLETED",workflow:{currentStep:"COMPLETED",nextStep:null},nextAction:"CREATE_CLAIM"});
expect(signatures).toHaveLength(0);
const retry = await sign(ids.second).expect(200);
expect(retry.body.nextAction).toBe("CREATE_CLAIM");
await create(ids.second).expect(201);
expect(signatures).toHaveLength(0);
});
it("does not complete a stopped file or an incomplete signature record", async () => {
fixture("v6", "THIRD_PARTY", ids.first);
for (const party of blame.parties) party.confirmation = {accepted:true, signature:{fileId:"historic"}};
blame.status = "STOPPED";
const stopped = await request(app.getHttpServer()).get(url()).set("Authorization", auth(ids.second)).expect(200);
expect(stopped.body).toMatchObject({status:"STOPPED",nextAction:"VIEW_RESULT"});
blame.status = "WAITING_FOR_SIGNATURES";
delete blame.parties[0].confirmation.signature.fileId;
const incomplete = await request(app.getHttpServer()).get(url()).set("Authorization", auth(ids.second)).expect(200);
expect(incomplete.body.status).toBe("WAITING_FOR_SIGNATURES");
await create(ids.second).expect(400);
});
it("branch loading uses authorization directly without full case/media hydration", async () => {
fixture("v6", "CAR_BODY", ids.first);
const fullDetail = jest.spyOn(userService, "getBlameRequestV2").mockRejectedValue(new Error("slow media detail must not be called"));
try {
await request(app.getHttpServer()).get(url()+"/claim-branches").set("Authorization",auth(ids.first)).expect(200);
expect(fullDetail).not.toHaveBeenCalled();
} finally {fullDetail.mockRestore();}
});
it("a failed notification cannot turn a persisted signature into a failed submission", async () => {
fixture("v6", "CAR_BODY", ids.first);
const notify = jest.spyOn(userService.smsOrchestrationService, "sendThirdPartyDamagedPartyClaimLinkNotice").mockRejectedValue(new Error("SMS unavailable"));
try {
const response = await sign(ids.first, ids.branch).expect(200);
expect(response.body).toMatchObject({status:"COMPLETED",nextAction:"CREATE_CLAIM"});
expect(blame.status).toBe("COMPLETED");
expect(signatures).toHaveLength(1);
} finally {notify.mockRestore();}
});
it("concurrent conflicting decisions cannot replace an existing confirmation", async () => {
fixture("v6", "CAR_BODY", ids.first);
const responses = await Promise.all([sign(ids.first, ids.branch), sign(ids.first, undefined, false)]);
expect(responses.filter((r) => r.status === 200)).toHaveLength(1);
// Multipart parsing may serialize the requests before the guarded write.
expect([400,409]).toContain(responses.find((r) => r.status !== 200)?.status);
expect(signatures).toHaveLength(1);
const confirmation = clone(blame.parties[0].confirmation);
await sign(ids.first, undefined, !confirmation.accepted).expect(400);
expect(blame.parties[0].confirmation).toEqual(confirmation);
expect(blame.status).toBe(confirmation.accepted ? "COMPLETED" : "STOPPED");
});
// Optional browser tier drives the real UI against these same HTTP services and fixtures.
const browserTest = process.env.CLAIM_BRANCH_UI_URL ? it : it.skip;
browserTest.each(["v1", "v6"].flatMap((flow) => ["CAR_BODY", "THIRD_PARTY"].map((type) => [flow, type])))(
"%s %s: real UI → authenticated HTTP → branch/sign/claim persistence and reload",
async (flow, type) => {
fixture(flow, type, ids.first);
const damaged = type === "CAR_BODY" ? ids.first : ids.second;
if (type === "THIRD_PARTY") await sign(ids.first).expect(200);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({
...(process.env.CLAIM_BRANCH_BROWSER_EXECUTABLE ? {executablePath:process.env.CLAIM_BRANCH_BROWSER_EXECUTABLE} : {}),
headless:true, args:["--no-sandbox", "--disable-dev-shm-usage"],
});
try {
const context = await browser.newContext({viewport:{width:375,height:812},isMobile:true,hasTouch:true});
await context.addInitScript(({token,id}) => {
localStorage.setItem("auth_token",token); localStorage.setItem("role","user"); localStorage.setItem("BlameID",id);
}, {token:auth(damaged).slice(7),id:blame._id});
const page = await context.newPage(), errors:string[] = [];
page.on("pageerror", (e) => errors.push(e.message));
const upstream = await app.getUrl();
await page.route("**/mock-api/**", async (route) => {
const path = new URL(route.request().url()).pathname.replace("/mock-api", "");
const response = await route.fetch({url:upstream+path,headers:{...route.request().headers(),authorization:auth(damaged)}});
await route.fulfill({response});
});
await page.goto(`${process.env.CLAIM_BRANCH_UI_URL}/${flow}/blame/sign`);
await page.getByRole("combobox",{name:/^شهر/}).selectOption(JSON.stringify(["تهران","تهران"]));
await page.getByRole("combobox",{name:/^شعبه/}).selectOption(ids.branch);
expect(await page.getByText("خطای ناشناخته‌ای رخ داده است",{exact:true}).count()).toBe(0);
const canvas = page.locator("canvas"); await canvas.scrollIntoViewIfNeeded();
const box = await canvas.boundingBox();
await page.mouse.move(box.x+30,box.y+30); await page.mouse.down();
await page.mouse.move(box.x+80,box.y+70,{steps:8});
await page.mouse.move(box.x+150,box.y+35,{steps:8}); await page.mouse.up();
await page.getByRole("button",{name:"تایید امضا",exact:true}).click();
await page.waitForURL(`**/${flow}/blame/final`);
await page.getByRole("heading",{name:"آماده ثبت درخواست خسارت",exact:true}).waitFor();
expect(await page.locator("select").count()).toBe(0);
await page.getByRole("button",{name:"ثبت درخواست خسارت",exact:true}).click();
await page.waitForURL(`**/${flow}/claim`);
await page.waitForFunction(() => !!localStorage.getItem("ClaimRequestId"));
expect(blame.status).toBe("COMPLETED"); expect(claims).toHaveLength(1);
expect(claims[0].branchId).toBe(ids.branch);
await page.reload();
await page.waitForFunction(() => {
const button = [...document.querySelectorAll("button")].find((b) => b.textContent?.trim() === "ثبت خسارت");
return button && !button.disabled;
});
expect(claims).toHaveLength(1); expect(errors).toEqual([]);
} finally {await browser.close();}
}, 45_000,
);
});