forked from Yara724/api
Compare commits
3
Commits
ab3ae53ec0
...
83d7351310
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
83d7351310 | ||
|
|
bc78bface0 | ||
|
|
e33f5736a2 |
@@ -0,0 +1,37 @@
|
||||
# Recovering already-saved photos during capture
|
||||
|
||||
The capture-requirements endpoint now reads `requiredDocuments` from both
|
||||
Mongoose Maps and ordinary objects. The object case previously returned
|
||||
`uploaded: false` even for a saved chassis/engine photo, causing the UI to
|
||||
request it again and encounter the duplicate-document conflict.
|
||||
|
||||
Initial `upload-document` retries now acknowledge an existing uploaded document
|
||||
when a saved file path/URL is present. The response contains the existing
|
||||
`fileUrl`, the current persisted workflow step and `alreadyUploaded: true`.
|
||||
Ownership/tenant checks still run first. This does not replace the saved image,
|
||||
create a second document reference, append duplicate history, or resend the
|
||||
attachment to Fanavaran. A flag without file evidence is not acknowledged.
|
||||
Expert resends and active in-person replacement uploads keep their existing
|
||||
validation paths. Expert capture-document retries after the capture phase
|
||||
advanced can reuse confirmed evidence after the same ownership checks.
|
||||
|
||||
The user camera and gallery pages read saved part/angle/document flags, offer
|
||||
Continue for those slots without requiring another photo, and keep locally
|
||||
successful photo uploads separate from video completion. If the last photo
|
||||
saves but video upload fails, retrying completion only retries the video; it
|
||||
cannot re-upload the chassis image and encounter a duplicate error. Local photo
|
||||
receipts are scoped to the claim, and field-expert uploads await the selected
|
||||
API promise before recording success or advancing. The version was previously
|
||||
awaited instead of the upload promise in several conditional API calls.
|
||||
|
||||
The camera still records and submits the required walk-around video. Missing
|
||||
images and actual API failures remain blocking; error text or HTTP 409 alone is
|
||||
never treated as evidence of a successful upload.
|
||||
|
||||
Verification:
|
||||
|
||||
- API: `upload-document-idempotency.spec.ts`, `capture-part-concurrency.spec.ts`,
|
||||
`claim-capture-phase.spec.ts`, `ai-capture-integration.spec.ts`.
|
||||
- UI: `scripts/test-capture-upload-recovery.cjs`, included in `npm run test:ui`;
|
||||
covers saved chassis/parts, failed-video retry, awaited/rejected expert
|
||||
requests, case isolation and camera/gallery implementations.
|
||||
@@ -9435,7 +9435,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,
|
||||
@@ -9673,9 +9674,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,
|
||||
@@ -9711,6 +9734,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 =
|
||||
@@ -9805,17 +9836,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);
|
||||
|
||||
@@ -12166,6 +12188,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();
|
||||
});
|
||||
});
|
||||
@@ -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", "حداکثر ۹۰"],
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -221,9 +221,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.",
|
||||
"شرح حادثه باید حداقل ۳۰ کاراکتر باشد.",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -8724,6 +8724,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 (req.type === BlameRequestType.CAR_BODY && role === PartyRole.FIRST) {
|
||||
await this.validateCarBodyAccidentCoverage(party, body.accidentDate);
|
||||
|
||||
Reference in New Issue
Block a user