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();
});
});