fix: recover saved photo uploads and lower car-body description minimum

Read saved document status from maps and plain objects, acknowledge verified document retries without replacing stored images, and preserve upload authorization and resend behavior. Lower the car-body narrative minimum to 30 characters with Persian errors and boundary regression coverage.
This commit is contained in:
SepehrYahyaee
2026-11-21 12:35:49 +03:30
parent 8f15040080
commit e33f5736a2
12 changed files with 202 additions and 29 deletions
@@ -9308,7 +9308,8 @@ export class ClaimRequestManagementService {
];
const requiredDocuments = requiredDocsDefinition.map((doc) => {
const docData = (claimCase.requiredDocuments as any)?.get?.(doc.key);
const docData = (claimCase.requiredDocuments as any)?.get?.(doc.key) ??
(claimCase.requiredDocuments as any)?.[doc.key];
return {
key: doc.key,
label_fa: doc.label_fa,
@@ -9546,9 +9547,31 @@ export class ClaimRequestManagementService {
};
}
/**
* V2 API: Upload required document
*/
/** Reuse a confirmed stored document, never an uploaded flag without file evidence. */
private existingDocumentUploadResult(
claim: any,
key: string,
): UploadRequiredDocumentV2ResponseDto | undefined {
const doc =
claim.requiredDocuments?.get?.(key) ?? claim.requiredDocuments?.[key];
if (!doc?.uploaded) return undefined;
const path = typeof doc.filePath === 'string' ? doc.filePath.trim() : '';
const url = typeof doc.fileUrl === 'string' ? doc.fileUrl.trim() : '';
if (!path && !url) return undefined;
return {
claimRequestId: String(claim._id),
documentKey: key,
fileUrl: path ? buildFileLink(path) : url,
alreadyUploaded: true,
allDocumentsUploaded: (claim.workflow?.completedSteps ?? []).includes(
ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS,
),
currentStep: claim.workflow?.currentStep ?? '',
message: 'تصویر این مدرک قبلاً ثبت شده است؛ می‌توانید ادامه دهید.',
};
}
/** V2 API: Upload required document. Initial-upload retries reuse stored evidence. */
async uploadRequiredDocumentV2(
claimRequestId: string,
body: UploadRequiredDocumentV2Dto,
@@ -9584,6 +9607,14 @@ export class ClaimRequestManagementService {
const step = claimCase.workflow?.currentStep;
const isResendUpload = step === ClaimWorkflowStep.USER_EXPERT_RESEND;
if (
!isResendUpload &&
claimCase.status !== ClaimCaseStatus.WAITING_FOR_USER_RESEND &&
!options?.v3InPersonFlow
) {
const existing = this.existingDocumentUploadResult(claimCase, body.documentKey);
if (existing) return existing;
}
const isOptionalDocument =
body.documentKey === ClaimRequiredDocumentType.ACCIDENT_SKETCH;
const isCapturePhaseDocUpload =
@@ -9678,17 +9709,8 @@ export class ClaimRequestManagementService {
);
}
// Initial flow: each document once. Expert resend and v3 in-person: allow replacement.
if (!isResendUpload && !options?.v3InPersonFlow) {
const existingDoc =
(claimCase.requiredDocuments as any)?.get?.(body.documentKey) ??
(claimCase.requiredDocuments as any)?.[body.documentKey];
if (existingDoc?.uploaded) {
throw new ConflictException(
`Document ${body.documentKey} has already been uploaded`,
);
}
}
// A confirmed initial upload was returned above. Incomplete references may
// be repaired here; expert-requested resends and in-person replacements remain allowed.
const fileUrl = buildFileLink(file.path);
@@ -12039,6 +12061,27 @@ export class ClaimRequestManagementService {
isCapturePhaseDamagedPartyDocKey(body.documentKey) ||
isGuiltyDamageAreaDoc;
// A response may have been lost after the last capture document advanced
// the workflow. Reuse that saved evidence after the usual owner/tenant checks.
if (
isCaptureDoc &&
claimCase.status !== ClaimCaseStatus.WAITING_FOR_USER_RESEND &&
claimCase.workflow?.currentStep !== ClaimWorkflowStep.CAPTURE_PART_DAMAGES &&
this.claimV3StepCompleted(claimCase, ClaimWorkflowStep.CAPTURE_PART_DAMAGES)
) {
const existing = this.existingDocumentUploadResult(claimCase, body.documentKey);
if (existing) {
const effectiveUserId = await this.resolveClaimEffectiveUserId(
claimCase, currentUserId, actor?.role,
);
await this.assertEffectiveUserIsDamagedPartyOnClaim(
claimCase, effectiveUserId, actor as { username?: string },
'Only the claim owner can upload documents',
);
return existing;
}
}
if (isCaptureDoc) {
this.assertV3ClaimPartsPhase(blame);
this.assertV3ClaimWorkflowStep(
@@ -850,17 +850,13 @@ Returns status of each item (uploaded/captured or not).
})
@ApiResponse({
status: 200,
description: "Document uploaded successfully",
description: "Document uploaded, or an earlier stored image acknowledged on retry",
type: UploadRequiredDocumentV2ResponseDto,
})
@ApiResponse({
status: 400,
description: "Invalid workflow step",
})
@ApiResponse({
status: 409,
description: "Document already uploaded",
})
async uploadDocument(
@Param("claimRequestId") claimRequestId: string,
@Body() body: UploadRequiredDocumentV2Dto,
@@ -29,6 +29,8 @@ export class UploadRequiredDocumentV2Dto {
* Response DTO for upload required document V2
*/
export class UploadRequiredDocumentV2ResponseDto {
@ApiPropertyOptional({ description: "An earlier saved image was reused without replacing it." })
alreadyUploaded?: boolean;
@ApiProperty({
description: "Claim request ID",
example: "507f1f77bcf86cd799439011",
@@ -429,11 +429,10 @@ Returns status of each item (uploaded/captured or not).
})
@ApiResponse({
status: 200,
description: "Document uploaded successfully",
description: "Document uploaded, or an earlier stored image acknowledged on retry",
type: UploadRequiredDocumentV2ResponseDto,
})
@ApiResponse({ status: 400, description: "Invalid workflow step" })
@ApiResponse({ status: 409, description: "Document already uploaded" })
async uploadDocument(
@Param("claimRequestId") claimRequestId: string,
@Body() body: UploadRequiredDocumentV2Dto,
@@ -0,0 +1,68 @@
import { BadRequestException, ForbiddenException } from "@nestjs/common";
import { Types } from "mongoose";
import { ClaimRequestManagementService } from "./claim-request-management.service";
import { ClaimRequiredDocumentType as Doc } from "src/Types&Enums/claim-request-management/required-document-type.enum";
import { ClaimWorkflowStep as Step } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum";
import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum";
const key = Doc.DAMAGED_CHASSIS_NUMBER;
const saved = { uploaded: true, filePath: "files/chassis-saved.jpg", fileName: "chassis-saved.jpg", fileId: new Types.ObjectId() };
function fixture(documents: any, step = Step.CAPTURE_PART_DAMAGES) {
const claim: any = { _id: new Types.ObjectId(), blameRequestId: new Types.ObjectId(), status: ClaimCaseStatus.CAPTURING_PART_DAMAGES,
owner: { userId: new Types.ObjectId() }, workflow: { currentStep: step, completedSteps: [] }, requiredDocuments: documents,
media: {}, damage: { selectedParts: [] }, vehicle: {},
};
const service: any = Object.create(ClaimRequestManagementService.prototype);
service.claimCaseDbService = { findById: jest.fn().mockResolvedValue(claim), findByIdAndUpdate: jest.fn() };
service.claimRequiredDocumentDbService = { create: jest.fn() };
service.blameRequestDbService = { findById: jest.fn().mockResolvedValue({ type: "CAR_BODY" }) };
service.resolveClaimEffectiveUserId = jest.fn().mockResolvedValue(String(claim.owner.userId));
service.assertEffectiveUserIsDamagedPartyOnClaim = jest.fn().mockResolvedValue(undefined);
service.autoSubmitFanavaranAttachment = jest.fn();
return { service, claim };
}
const file = { path: "files/retried-new.jpg", filename: "retried-new.jpg" } as Express.Multer.File;
describe("saved capture document recovery", () => {
it.each([false, true])("reports saved chassis documents from object/Map (%s)", async map => {
const docs = map ? new Map([[key, saved]]) : { [key]: saved };
const { service, claim } = fixture(docs);
const result = await service.getCaptureRequirementsV2(String(claim._id), String(claim.owner.userId));
expect(result.requiredDocuments.find((doc: any) => doc.key === key).uploaded).toBe(true);
expect(result.requiredDocuments.find((doc: any) => doc.key === Doc.DAMAGED_ENGINE_PHOTO).uploaded).toBe(false);
});
it.each([Step.CAPTURE_PART_DAMAGES, Step.UPLOAD_REQUIRED_DOCUMENTS, Step.USER_SUBMISSION_COMPLETE])("acknowledges a saved document at %s without replacing it", async step => {
const { service, claim } = fixture({ [key]: saved }, step);
const result = await service.uploadRequiredDocumentV2(String(claim._id), { documentKey: key }, file, String(claim.owner.userId));
expect(result).toMatchObject({ documentKey: key, alreadyUploaded: true, currentStep: step });
expect(result.fileUrl).toContain("chassis-saved.jpg");
expect(result.fileUrl).not.toContain("retried-new.jpg");
expect(service.assertEffectiveUserIsDamagedPartyOnClaim).toHaveBeenCalledTimes(1);
expect(service.claimRequiredDocumentDbService.create).not.toHaveBeenCalled();
expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled();
expect(service.autoSubmitFanavaranAttachment).not.toHaveBeenCalled();
});
it("does not bypass ownership on duplicate uploads", async () => {
const { service, claim } = fixture({ [key]: saved });
service.assertEffectiveUserIsDamagedPartyOnClaim.mockRejectedValue(new ForbiddenException());
await expect(service.uploadRequiredDocumentV2(String(claim._id), { documentKey: key }, file, "other-user")).rejects.toThrow(ForbiddenException);
expect(service.claimRequiredDocumentDbService.create).not.toHaveBeenCalled();
});
it("never acknowledges an uploaded flag without saved file evidence", () => {
const { service, claim } = fixture({ [key]: { uploaded: true } });
expect(service.existingDocumentUploadResult(claim, key)).toBeUndefined();
});
it("keeps expert-requested resends on their validation/replacement path", async () => {
const { service, claim } = fixture({ [key]: saved }, Step.USER_EXPERT_RESEND);
await expect(service.uploadRequiredDocumentV2(String(claim._id), { documentKey: key }, file, String(claim.owner.userId))).rejects.toThrow(BadRequestException);
});
it("recovers an expert capture-document retry after the capture phase advanced", async () => {
const { service, claim } = fixture({ [key]: saved }, Step.UPLOAD_REQUIRED_DOCUMENTS);
claim.workflow.completedSteps = [Step.CAPTURE_PART_DAMAGES];
service.assertV3InPersonClaim = jest.fn().mockResolvedValue({ type: "CAR_BODY", isMadeByFileMaker: true });
const result = await service.uploadRequiredDocumentV3(String(claim._id), { documentKey: key }, file, String(claim.owner.userId), { role: "file_reviewer" });
expect(result.alreadyUploaded).toBe(true);
expect(service.assertEffectiveUserIsDamagedPartyOnClaim).toHaveBeenCalledTimes(1);
expect(service.claimRequiredDocumentDbService.create).not.toHaveBeenCalled();
});
});
+2
View File
@@ -30,6 +30,8 @@ describe("public Persian error wording", () => {
"licenseType must be one of the following values: 1, 2, 3",
"نوع گواهینامه",
],
["description must be longer than or equal to 30 characters", "۳۰"],
["CAR_BODY description must contain at least 30 characters", "۳۰"],
["description must be longer than or equal to 100 characters", "۱۰۰"],
["CAR_BODY description must contain at least 100 characters", "۱۰۰"],
["latitude must not be greater than 90", "حداکثر ۹۰"],
+4 -2
View File
@@ -345,11 +345,13 @@ export function localizeErrorMessage(
const lower = message.toLowerCase();
if (wording[lower]) return wording[lower];
if (
/car_body.*description.*(?:100|۱۰۰)|description.*must.*(?:100|۱۰۰).*characters/i.test(
/car_body.*description.*(?:30|۳۰|100|۱۰۰)|description.*must.*(?:30|۳۰|100|۱۰۰).*characters/i.test(
message,
)
)
return "شرح حادثه باید حداقل ۱۰۰ کاراکتر باشد.";
return /(?:30|۳۰)/.test(message)
? "شرح حادثه باید حداقل ۳۰ کاراکتر باشد."
: "شرح حادثه باید حداقل ۱۰۰ کاراکتر باشد.";
const operation =
/^failed to (fetch|get|load|send|upload|submit|add|create|update|verify|delete|remove) (.+)$/i.exec(
message,
@@ -53,7 +53,7 @@ export class FirstPartyFileDto {
export class DescriptionDto {
@ApiPropertyOptional({
description:
"Accident description. Optional for THIRD_PARTY; CAR_BODY requires at least 100 non-whitespace characters.",
"Accident description. Optional for THIRD_PARTY; CAR_BODY requires at least 30 characters after trimming.",
})
@IsOptional()
@IsString()
@@ -101,7 +101,7 @@ export class DescriptionDto {
export class DescriptionV4Dto {
@ApiPropertyOptional({
description:
"Accident description. Optional for THIRD_PARTY; CAR_BODY requires at least 100 non-whitespace characters.",
"Accident description. Optional for THIRD_PARTY; CAR_BODY requires at least 30 characters after trimming.",
})
@IsOptional()
@IsString()
@@ -68,10 +68,15 @@ describe("RequestManagementService V4 FileMaker workflow", () => {
const prefix = party.role === PartyRole.FIRST ? "FIRST" : "SECOND";
expect(request.workflow.currentStep).toBe(`${prefix}_DESCRIPTION`);
const description = {
desc: "شرح حادثه ".repeat(15),
desc: type === BlameRequestType.CAR_BODY ? "ش".repeat(30) : "شرح حادثه ".repeat(15),
accidentDate: "2025-01-01",
accidentTime: "10:30",
};
if (flow === 4 && type === BlameRequestType.CAR_BODY) {
await expect(service.addPartyDescriptionV4(
String(request._id), actor, { ...description, desc: "ش".repeat(29) }, party.role,
)).rejects.toThrow("شرح حادثه باید حداقل ۳۰ کاراکتر باشد.");
}
if (flow === 4)
await service.addPartyDescriptionV4(
String(request._id),
@@ -23,3 +23,20 @@ describe("RequestManagementService CAR_BODY insurer client", () => {
});
});
});
describe("CAR_BODY description minimum", () => {
const service = Object.create(RequestManagementService.prototype) as any;
it.each([30, 31, 99, 100])("accepts %s trimmed characters", length => {
expect(() => service.assertCarBodyDescriptionMinimum("CAR_BODY", ` ${"ش".repeat(length)} `)).not.toThrow();
});
it.each([undefined, "", " ", "ش".repeat(29), ` ${"ش".repeat(29)} `])("rejects a short description with a Persian 30-character message", description => {
expect(() => service.assertCarBodyDescriptionMinimum("CAR_BODY", description)).toThrow("شرح حادثه باید حداقل ۳۰ کاراکتر باشد.");
});
it("preserves optional third-party descriptions", () => {
expect(() => service.assertCarBodyDescriptionMinimum("THIRD_PARTY", "")).not.toThrow();
});
});
@@ -220,9 +220,9 @@ export class RequestManagementService {
): void {
if (requestType !== BlameRequestType.CAR_BODY) return;
const length = String(description ?? "").trim().length;
if (length < 100) {
if (length < 30) {
throw new BadRequestException(
"CAR_BODY description must contain at least 100 non-whitespace characters.",
"شرح حادثه باید حداقل ۳۰ کاراکتر باشد.",
);
}
}
@@ -8627,6 +8627,8 @@ export class RequestManagementService {
const idx = this.getPartyIndex(req, role);
if (idx === -1) throw new BadRequestException(`${role} party not found`);
this.assertCarBodyDescriptionMinimum(req.type, body.desc);
const party = req.parties[idx];
if (!party.statement) party.statement = {} as any;
party.statement.description = body.desc;