fix(workflows): resolve QA blockers and protect case evidence

Fix registrar signing, reviewer re-entry, replacement evidence freshness, owner decision and rating races, multipart objections, vehicle serialization and product reporting.

Validate uploaded media with FFmpeg, serve evidence through expiring signed links, and add targeted regressions plus a dry-run repair for prematurely completed visit cases.
This commit is contained in:
SepehrYahyaee
2026-11-22 12:50:22 +03:30
parent abc40df199
commit 6b968c0952
37 changed files with 1118 additions and 211 deletions
@@ -16,6 +16,7 @@ export enum ClaimCaseStatus {
// Expert flow
WAITING_FOR_DAMAGE_EXPERT = "WAITING_FOR_DAMAGE_EXPERT",
IN_PERSON_VISIT_PENDING = "IN_PERSON_VISIT_PENDING",
EXPERT_REVIEWING = "EXPERT_REVIEWING",
/**
* @deprecated Prefer specific post-expert statuses below. Kept for existing DB rows and reads.
+2 -9
View File
@@ -1,3 +1,4 @@
import { EvidenceAccessModule } from "./evidence-access/evidence-access.module";
import { PersianErrorFilter } from "./common/errors/persian-error.filter";
import { PersianErrorInterceptor } from "./common/errors/persian-error.interceptor";
import { ManagementModule } from "./management/management.module";
@@ -8,7 +9,6 @@ import { ConfigModule, ConfigService } from "@nestjs/config";
import { HttpModule } from "@nestjs/axios";
import { UnicodeDigitsNormalizeInterceptor } from "./common/interceptors/unicode-digits-normalize.interceptor";
import { MongooseModule } from "@nestjs/mongoose";
import { ServeStaticModule } from "@nestjs/serve-static";
import { AiModule } from "./ai/ai.module";
import { AuthModule } from "./auth/auth.module";
import { ClaimRequestManagementModule } from "./claim-request-management/claim-request-management.module";
@@ -44,14 +44,7 @@ import { createHttpModuleOptions } from "./core/config/http-proxy.factory";
AppConfigModule,
DatabaseModule,
CronModule,
ServeStaticModule.forRoot({
// process.cwd() is always the project/container root (/app in Docker),
// so the volume-mounted /app/files is resolved correctly regardless of
// where the compiled dist files live (__dirname would resolve to
// /app/dist/src because TypeScript preserves the src/ prefix in outDir).
rootPath: join(process.cwd(), "files"),
serveRoot: "/files",
}),
EvidenceAccessModule,
UsersModule,
AuthModule,
ClientModule,
@@ -1,3 +1,6 @@
import { unlink } from "node:fs/promises";
import { plainToInstance } from "class-transformer";
import { validateSync } from "class-validator";
import {
normalizeClaimSheba,
normalizeClaimNationalCode,
@@ -8416,6 +8419,9 @@ export class ClaimRequestManagementService {
fanavaran,
};
} catch (error) {
if ((error as {code?: number})?.code === 11000) {
throw new ConflictException('درخواست خسارت این پرونده قبلاً ثبت شده است. پرونده‌های من را باز کنید.');
}
if (error instanceof HttpException) throw error;
this.logger.error(
'createClaimFromBlameV2 failed',
@@ -9633,7 +9639,11 @@ export class ClaimRequestManagementService {
if (!claim || !canFinalizeExpertResend(claim)) {
return;
}
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
await this.claimCaseDbService.findOneAndUpdate({
_id: claim._id, status: ClaimCaseStatus.WAITING_FOR_USER_RESEND,
'workflow.currentStep': ClaimWorkflowStep.USER_EXPERT_RESEND,
'evaluation.damageExpertResend.fulfilledAt': null,
}, {
$set: {
status: ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT,
claimStatus: ClaimStatus.PENDING,
@@ -10813,6 +10823,12 @@ export class ClaimRequestManagementService {
'Only the claim owner can submit an objection',
);
// Multipart body fields are strings. This service is also called by
// mirror controllers, so normalize and validate here rather than relying
// on a global ValidationPipe (the app deliberately has none).
body = plainToInstance(UserObjectionV2Dto, body);
if (validateSync(body).length) throw new BadRequestException('اطلاعات اعتراض معتبر نیست. قطعه، توضیح اعتراض و مبالغ پیشنهادی را بررسی کنید.');
if (claimCase.evaluation?.objection?.submittedAt) {
throw new ConflictException(
'An objection has already been submitted for this claim.',
@@ -11075,7 +11091,10 @@ export class ClaimRequestManagementService {
createdAt: new Date(),
};
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
const saved = await this.claimCaseDbService.findOneAndUpdate({
_id: claimCase._id, status: ClaimCaseStatus.COMPLETED,
'userRating.createdAt': null,
}, {
$set: { userRating },
$push: {
history: {
@@ -11091,6 +11110,7 @@ export class ClaimRequestManagementService {
},
});
if (!saved) throw new ConflictException("امتیاز این پرونده قبلاً ثبت شده است یا وضعیت پرونده تغییر کرده است.");
return userRating;
}
@@ -11200,139 +11220,48 @@ export class ClaimRequestManagementService {
}
const signDoc = await this.claimSignDbService.create({
fileName: signFile.filename,
userId: effectiveUserId,
path: signFile.path,
fileName: signFile.filename, userId: effectiveUserId, path: signFile.path,
requestId: new Types.ObjectId(claimRequestId),
} as any);
const signId = new Types.ObjectId(String((signDoc as any)._id));
const signedAt = new Date();
const scopedApprovalPayload = {
agree,
signDetailId: signId,
signedAt,
};
const historyActor = {
actorId: new Types.ObjectId(effectiveUserId),
actorName: claimCase.owner?.fullName || 'User',
actorType: 'user',
};
/** Mixed reply: priced lines acceptance before factor uploads */
if (isMixedPartialGate) {
if (!agree) {
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: {
status: ClaimCaseStatus.REJECTED,
claimStatus: ClaimStatus.REJECTED,
'evaluation.ownerPricedPartsApproval': scopedApprovalPayload,
'workflow.nextStep': null,
},
$push: {
history: {
type: 'OWNER_REJECTED_PRICED_PARTS_BEFORE_FACTORS',
actor: historyActor,
timestamp: signedAt,
metadata: {},
},
},
});
return {
message:
'Your rejection has been recorded. This claim is marked rejected and will not proceed.',
claimRequestId,
status: ClaimCaseStatus.REJECTED,
claimStatus: ClaimStatus.REJECTED,
currentStep: claimCase.workflow?.currentStep,
accepted: false,
phase: 'PRICED_PARTS_FOR_FACTORS',
};
}
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: {
claimStatus: ClaimStatus.NEEDS_REVISION,
'evaluation.ownerPricedPartsApproval': scopedApprovalPayload,
'workflow.currentStep':
ClaimWorkflowStep.OWNER_UPLOAD_FACTOR_DOCUMENTS,
'workflow.nextStep': ClaimWorkflowStep.EXPERT_COST_EVALUATION,
},
$push: {
history: {
type: 'OWNER_SIGNED_PRICED_PARTS_PENDING_FACTOR_UPLOAD',
actor: historyActor,
timestamp: signedAt,
metadata: {},
},
},
});
return {
message:
'Priced repair lines accepted. Upload repair factor files for each factor-needed part; the claim will return to the damage expert for cost validation.',
claimRequestId,
status: claimCase.status,
claimStatus: ClaimStatus.NEEDS_REVISION,
currentStep: ClaimWorkflowStep.OWNER_UPLOAD_FACTOR_DOCUMENTS,
accepted: true,
phase: 'PRICED_PARTS_FOR_FACTORS',
};
}
/** Final accept / reject (no outstanding factor gate at this step) */
if (!agree) {
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: {
status: ClaimCaseStatus.REJECTED,
claimStatus: ClaimStatus.REJECTED,
'evaluation.ownerInsurerApproval': scopedApprovalPayload,
'workflow.nextStep': null,
},
$push: {
history: {
type: 'OWNER_REJECTED_INSURER_APPROVAL_PRICING',
actor: historyActor,
timestamp: signedAt,
metadata: {},
},
},
});
return {
message:
'Your rejection has been recorded. This claim is marked rejected and will not proceed.',
claimRequestId,
status: ClaimCaseStatus.REJECTED,
claimStatus: ClaimStatus.REJECTED,
currentStep: claimCase.workflow?.currentStep,
accepted: false,
phase: 'FINAL_APPROVAL',
};
}
// Submit Fanavaran expertise when owner accepts the expert reply
const fanavaranExpertise =
await this.autoSubmitFanavaranExpertiseOnExpertReply(claimRequestId);
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
const approvalField = isMixedPartialGate ? 'ownerPricedPartsApproval' : 'ownerInsurerApproval';
const nextStatus = !agree ? ClaimCaseStatus.REJECTED : isMixedPartialGate ? claimCase.status : ClaimCaseStatus.COMPLETED;
const nextStep = agree ? (isMixedPartialGate ? ClaimWorkflowStep.OWNER_UPLOAD_FACTOR_DOCUMENTS : ClaimWorkflowStep.CLAIM_COMPLETED) : claimCase.workflow.currentStep;
// The state change and decision are one compare-and-set. Only its winner may
// call external services; overlapping accept/reject requests cannot overwrite it.
const saved = await this.claimCaseDbService.findOneAndUpdate({
_id: claimCase._id, status: claimCase.status, claimStatus: claimCase.claimStatus,
'workflow.currentStep': ClaimWorkflowStep.INSURER_REVIEW,
[`evaluation.${approvalField}.signedAt`]: null,
'evaluation.ownerInsurerApproval.signedAt': null,
}, {
$set: {
status: ClaimCaseStatus.COMPLETED,
claimStatus: ClaimStatus.APPROVED,
'evaluation.ownerInsurerApproval': scopedApprovalPayload,
'workflow.currentStep': ClaimWorkflowStep.CLAIM_COMPLETED,
'workflow.nextStep': ClaimWorkflowStep.CLAIM_COMPLETED,
},
$push: {
'workflow.completedSteps': ClaimWorkflowStep.INSURER_REVIEW,
history: {
type: 'OWNER_SIGNED_INSURER_APPROVAL',
actor: historyActor,
timestamp: signedAt,
metadata: {},
},
status: nextStatus,
claimStatus: !agree ? ClaimStatus.REJECTED : isMixedPartialGate ? ClaimStatus.NEEDS_REVISION : ClaimStatus.APPROVED,
[`evaluation.${approvalField}`]: { agree, signDetailId: new Types.ObjectId(String((signDoc as any)._id)), signedAt },
'workflow.currentStep': nextStep,
'workflow.nextStep': !agree ? null : isMixedPartialGate ? ClaimWorkflowStep.EXPERT_COST_EVALUATION : ClaimWorkflowStep.CLAIM_COMPLETED,
},
$push: { history: {
type: isMixedPartialGate ? (agree ? 'OWNER_SIGNED_PRICED_PARTS_PENDING_FACTOR_UPLOAD' : 'OWNER_REJECTED_PRICED_PARTS_BEFORE_FACTORS') : (agree ? 'OWNER_SIGNED_INSURER_APPROVAL' : 'OWNER_REJECTED_INSURER_APPROVAL_PRICING'),
actor: { actorId: new Types.ObjectId(effectiveUserId), actorName: claimCase.owner?.fullName || 'User', actorType: 'user' },
timestamp: signedAt, metadata: {},
} },
...(!isMixedPartialGate && agree ? {$addToSet: {'workflow.completedSteps': ClaimWorkflowStep.INSURER_REVIEW}} : {}),
});
if (!saved) {
await this.claimSignDbService.deleteById(String((signDoc as any)._id));
await unlink(signFile.path).catch(() => undefined);
throw new ConflictException('تصمیم این پرونده قبلاً ثبت شده است یا وضعیت پرونده تغییر کرده است. پرونده را دوباره باز کنید.');
}
if (isMixedPartialGate || !agree) return {
message: !agree ? 'عدم تأیید شما ثبت شد. پرونده رد شده است.' : 'تأیید مبالغ ثبت شد. فاکتور قطعات درخواستی را بارگذاری کنید.',
claimRequestId, status: nextStatus,
claimStatus: !agree ? ClaimStatus.REJECTED : ClaimStatus.NEEDS_REVISION,
currentStep: nextStep, accepted: agree,
phase: isMixedPartialGate ? 'PRICED_PARTS_FOR_FACTORS' : 'FINAL_APPROVAL',
};
const fanavaranExpertise = await this.autoSubmitFanavaranExpertiseOnExpertReply(claimRequestId);
const fanavaran =
await this.autoSubmitToFanavaranV2OnClaimCompleted(claimRequestId);
@@ -11615,6 +11544,7 @@ export class ClaimRequestManagementService {
actor?: { sub: string; role?: string; username?: string },
): Promise<ClaimDetailsV2ResponseDto> {
try {
if (!Types.ObjectId.isValid(claimRequestId)) throw new BadRequestException("شناسه پرونده خسارت معتبر نیست.");
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) {
throw new NotFoundException('Claim request not found');
@@ -11743,7 +11673,7 @@ export class ClaimRequestManagementService {
: undefined;
const maskSheba = (s?: string) =>
s ? s.replace(/^(.{4})(.*)(.{4})$/, 'IR$1************$3') : undefined;
s ? s.replace(/^(.{4})(.*)(.{4})$/, '$1************$3') : undefined;
const maskNationalCode = (s?: string) =>
s ? s.replace(/^(.{2})(.*)(.{2})$/, '$1******$3') : undefined;
const isExpertViewer =
@@ -11829,6 +11759,7 @@ export class ClaimRequestManagementService {
damagedParts,
damagedPartsHistory,
expertResend,
visitLocation: claim.evaluation?.visitLocation,
fanavaran: fanavaranClaimReferences(claim),
evaluation: mappedEvaluation
? {
@@ -12235,6 +12166,7 @@ export class ClaimRequestManagementService {
`Claim case with ID ${claimRequestId} not found`,
);
}
await this.assertActorCanViewClaimV2(claimCase, currentUserId, actor);
const blame = await this.assertV3InPersonClaim(claimCase);
const skipMetalPlate = !!(blame as any).isMadeByFileMaker;
const isV4FileMaker =
@@ -12350,6 +12282,7 @@ export class ClaimRequestManagementService {
`Claim case with ID ${claimRequestId} not found`,
);
}
await this.assertActorCanViewClaimV2(claimCase, currentUserId, actor);
const blame = await this.assertV3InPersonClaim(claimCase);
if (this.isV3InitialDocumentsPhase(claimCase)) {
@@ -12382,6 +12315,7 @@ export class ClaimRequestManagementService {
`Claim case with ID ${claimRequestId} not found`,
);
}
await this.assertActorCanViewClaimV2(claimCase, currentUserId, actor);
const blame = await this.assertV3InPersonClaim(claimCase);
this.assertV3ClaimPartsPhase(blame);
await this.advanceV3ClaimToOuterPartsIfReady(claimCase, blame);
@@ -12415,6 +12349,7 @@ export class ClaimRequestManagementService {
`Claim case with ID ${claimRequestId} not found`,
);
}
await this.assertActorCanViewClaimV2(claimCase, currentUserId, actor);
const blame = await this.assertV3InPersonClaim(claimCase);
this.assertV3ClaimPartsPhase(blame);
this.assertV3ClaimWorkflowStep(
@@ -12492,7 +12427,7 @@ export class ClaimRequestManagementService {
? {
shebaNumber: String(shebaNumber).replace(
/^(.{4})(.*)(.{4})$/,
'IR$1************$3',
'$1************$3',
),
}
: {}),
@@ -12523,6 +12458,7 @@ export class ClaimRequestManagementService {
`Claim case with ID ${claimRequestId} not found`,
);
}
await this.assertActorCanViewClaimV2(claimCase, currentUserId, actor);
const blame = await this.assertV3InPersonClaim(claimCase);
const skipMetalPlate = !!(blame as any).isMadeByFileMaker;
@@ -12676,6 +12612,7 @@ export class ClaimRequestManagementService {
`Claim case with ID ${claimRequestId} not found`,
);
}
await this.assertActorCanViewClaimV2(claimCase, currentUserId, actor);
const blame = await this.assertV3InPersonClaim(claimCase);
this.assertV3ClaimPartsPhase(blame);
this.assertV3ClaimWorkflowStep(
@@ -1,3 +1,4 @@
import { randomUUID } from "node:crypto";
import {
Controller,
HttpException,
@@ -375,7 +376,7 @@ export class ClaimRequestManagementV2Controller {
storage: diskStorage({
destination: "./files/claim-sign",
filename: (req, file, callback) => {
const unique = Date.now();
const unique = randomUUID();
const ex = extname(file.originalname);
const base = file.originalname.split(/[.,\s-]/)[0] || "sign";
callback(null, `${base}-${unique}${ex}`);
@@ -263,6 +263,9 @@ export class ClaimDetailsV2ResponseDto {
})
expertResend?: ExpertResendDetailsV2Dto;
@ApiPropertyOptional()
visitLocation?: string;
@ApiPropertyOptional({
description:
"Fanavaran codes and image upload receipts. Claim codes appear on COMPLETED; fileIds and attachments upload status/errors are available earlier when recorded.",
@@ -0,0 +1,26 @@
import { plainToInstance } from "class-transformer";
import { validate } from "class-validator";
import { UserObjectionV2Dto } from "./user-objection-v2.dto";
describe("objection JSON and multipart parity", () => {
it.each([true, false])(
"validates nested entries for multipart=%s",
async (multipart) => {
const entries = [{ partId: 101, reason: "اعتراض به قیمت" }];
const dto = plainToInstance(UserObjectionV2Dto, {
objectionParts: multipart ? JSON.stringify(entries) : entries,
});
expect(await validate(dto)).toEqual([]);
},
);
it("still rejects invalid entries and malformed multipart JSON", async () => {
for (const raw of ["{", '[{"partId":"wrong"}]']) {
expect(
(
await validate(
plainToInstance(UserObjectionV2Dto, { objectionParts: raw }),
)
).length,
).toBeGreaterThan(0);
}
});
});
@@ -1,11 +1,6 @@
import { ApiPropertyOptional } from "@nestjs/swagger";
import { Type, Transform } from "class-transformer";
import {
IsArray,
IsOptional,
Validate,
ValidateNested,
} from "class-validator";
import { Type, Transform, plainToInstance } from "class-transformer";
import { IsArray, IsOptional, Validate, ValidateNested } from "class-validator";
import { HasObjectionEntriesConstraint } from "src/common/validators/has-objection-entries.validator";
import { NewPartDto, UserObjectionPartDto } from "./user-objection.dto";
@@ -28,7 +23,10 @@ export class UserObjectionV2Dto {
@Transform(({ value }) => {
if (typeof value === "string") {
try {
return JSON.parse(value);
const parsed = JSON.parse(value);
return Array.isArray(parsed)
? plainToInstance(UserObjectionPartDto, parsed)
: parsed;
} catch {
return value;
}
@@ -50,7 +48,10 @@ export class UserObjectionV2Dto {
@Transform(({ value }) => {
if (typeof value === "string") {
try {
return JSON.parse(value);
const parsed = JSON.parse(value);
return Array.isArray(parsed)
? plainToInstance(NewPartDto, parsed)
: parsed;
} catch {
return value;
}
@@ -14,6 +14,10 @@ export class ClaimSignDbService {
return await this.claimSignService.create(claimSign);
}
async deleteById(id: string): Promise<void> {
await this.claimSignService.findByIdAndDelete(id);
}
async findOne(filter: FilterQuery<ClaimSignModel>): Promise<ClaimSignModel> {
return await this.claimSignService.findOne(filter);
}
@@ -218,6 +218,8 @@ export const ClaimUserObjectionPayloadSchema =
@Schema({ _id: false })
export class ClaimResendRequest {
@Prop({ type: Date })
requestedAt?: Date;
@Prop({ type: String })
resendDescription?: string;
@@ -1,3 +1,4 @@
import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
import { extname } from "node:path";
import {
@@ -564,7 +565,7 @@ Returns status of each item (uploaded/captured or not).
storage: diskStorage({
destination: "./files/claim-sign",
filename: (req, file, callback) => {
const unique = Date.now();
const unique = randomUUID();
const ex = extname(file.originalname);
const base = file.originalname.split(/[.,\s-]/)[0] || "sign";
callback(null, `${base}-${unique}${ex}`);
@@ -8,7 +8,7 @@ describe("owner insurer approval without branch selection", () => {
const service = Object.create(
ClaimRequestManagementService.prototype,
) as ClaimRequestManagementService;
const findByIdAndUpdate = jest.fn().mockResolvedValue(undefined);
const findOneAndUpdate = jest.fn().mockResolvedValue({});
(service as any).claimCaseDbService = {
findById: jest.fn().mockResolvedValue({
@@ -21,7 +21,7 @@ describe("owner insurer approval without branch selection", () => {
damageExpertReply: { submittedAt: new Date(), parts: [] },
},
}),
findByIdAndUpdate,
findOneAndUpdate,
};
(service as any).resolveClaimEffectiveUserId = jest
.fn()
@@ -48,8 +48,8 @@ describe("owner insurer approval without branch selection", () => {
status: ClaimCaseStatus.REJECTED,
});
expect(findByIdAndUpdate).toHaveBeenCalledWith(
"507f1f77bcf86cd799439011",
expect(findOneAndUpdate).toHaveBeenCalledWith(
expect.objectContaining({_id: "507f1f77bcf86cd799439011", "evaluation.ownerInsurerApproval.signedAt": null}),
expect.objectContaining({
$set: expect.objectContaining({
"evaluation.ownerInsurerApproval": expect.not.objectContaining({
@@ -0,0 +1,105 @@
import { ClaimRequestManagementService } from "./claim-request-management.service";
const id = "507f1f77bcf86cd799439011",
uid = "507f1f77bcf86cd799439012";
/** Simulated shared document: each conditional update is atomic, as Mongo is. */
function serviceFor(initial: any) {
const s: any = Object.create(ClaimRequestManagementService.prototype);
const doc = { _id: id, owner: { userId: uid }, ...initial };
s.claimCaseDbService = {
findById: jest.fn(async () => ({
...doc,
workflow: { ...doc.workflow },
evaluation: { ...doc.evaluation },
})),
findOneAndUpdate: jest.fn(async (filter, update) => {
if (filter.status !== doc.status) return null;
if (filter["userRating.createdAt"] === null && doc.userRating)
return null;
if (
filter["evaluation.ownerInsurerApproval.signedAt"] === null &&
doc.evaluation.ownerInsurerApproval
)
return null;
for (const [k, v] of Object.entries(update.$set || {})) {
const parts = k.split(".");
let target = doc;
for (const key of parts.slice(0, -1)) target = target[key] ??= {};
target[parts.at(-1)!] = v;
}
return doc;
}),
};
s.resolveClaimEffectiveUserId = jest.fn(async () => uid);
s.assertEffectiveUserIsDamagedPartyOnClaim = jest.fn(async () => {});
s.claimSignDbService = {
create: jest.fn(async () => ({ _id: "507f1f77bcf86cd799439013" })),
deleteById: jest.fn(async () => {}),
};
s.autoSubmitFanavaranExpertiseOnExpertReply = jest.fn(async () => ({
submitted: false,
}));
s.autoSubmitToFanavaranV2OnClaimCompleted = jest.fn(async () => ({
submitted: false,
}));
return { s, doc };
}
describe("one winning owner action", () => {
it("never records contradictory final decisions or duplicate integration calls", async () => {
const { s, doc } = serviceFor({
status: "INSURER_REVIEW_AWAITING_OWNER_SIGN",
claimStatus: "APPROVED",
workflow: { currentStep: "INSURER_REVIEW" },
evaluation: { damageExpertReply: { submittedAt: new Date(), parts: [] } },
});
const results = await Promise.allSettled(
[true, false, true, false, true, false].map((agree) =>
s.submitOwnerInsurerApprovalSignV2(
id,
agree,
{ filename: "a.jpg", path: "files/a.jpg" },
uid,
),
),
);
expect(results.filter((r) => r.status === "fulfilled")).toHaveLength(1);
expect(s.claimSignDbService.deleteById).toHaveBeenCalledTimes(5);
expect(s.autoSubmitToFanavaranV2OnClaimCompleted).toHaveBeenCalledTimes(1);
expect(doc.status).toBe("COMPLETED");
expect(doc.evaluation.ownerInsurerApproval.agree).toBe(true);
});
it("allows exactly one satisfaction rating under concurrent submissions", async () => {
const { s } = serviceFor({
status: "COMPLETED",
workflow: {},
evaluation: {},
});
const results = await Promise.allSettled(
[0, 1, 2, 3, 4, 5].map((n) =>
s.addUserRatingV2(
id,
{ progressSpeed: n, registrationEase: n, overallEvaluation: n },
uid,
),
),
);
expect(results.filter((r) => r.status === "fulfilled")).toHaveLength(1);
expect(results.filter((r) => r.status === "rejected")).toHaveLength(5);
});
it("authorizes V3 selection before changing workflow or parts", async () => {
const { s } = serviceFor({
status: "SELECTING_OTHER_PARTS",
workflow: {},
evaluation: {},
});
s.assertActorCanViewClaimV2 = jest.fn(async () => {
throw Error("forbidden");
});
await expect(
s.selectOtherPartsV3(id, { otherParts: ["engine"] }, uid, {
sub: uid,
role: "field_expert",
}),
).rejects.toThrow("forbidden");
expect(s.claimCaseDbService.findOneAndUpdate).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,75 @@
import {
CallHandler,
Controller,
ExecutionContext,
Get,
Injectable,
Module,
NestInterceptor,
Param,
Query,
Res,
ForbiddenException,
} from "@nestjs/common";
import { APP_INTERCEPTOR } from "@nestjs/core";
import {
EvidenceAccessService,
evidenceRequestScope,
} from "./evidence-access.service";
export { EvidenceAccessService } from "./evidence-access.service";
import { realpath } from "node:fs/promises";
import { resolve, sep } from "node:path";
import { Response } from "express";
import { map, Observable } from "rxjs";
@Injectable()
class EvidenceLinksInterceptor implements NestInterceptor {
constructor(private readonly access: EvidenceAccessService) {}
intercept(context: ExecutionContext, next: CallHandler) {
const req = context.switchToHttp().getRequest();
if (!req.user?.sub) return next.handle();
return new Observable((observer) =>
evidenceRequestScope.run(true, () =>
next
.handle()
.pipe(map((value) => this.access.project(value)))
.subscribe(observer),
),
);
}
}
@Controller("files")
class EvidenceController {
constructor(private readonly access: EvidenceAccessService) {}
@Get("*path")
async read(
@Param("path") raw: string | string[],
@Query("expires") expires: string,
@Query("signature") signature: string,
@Res() res: Response,
) {
const path = Array.isArray(raw) ? raw.join("/") : raw;
this.access.verify(path, expires, signature);
const root = await realpath(resolve("files"));
let target: string;
try {
target = await realpath(resolve(root, path));
} catch {
res.status(404).end();
return;
}
if (!target.startsWith(root + sep)) throw new ForbiddenException();
res.setHeader("Cache-Control", "private, no-store");
res.setHeader("X-Content-Type-Options", "nosniff");
// sendFile retains Range/HEAD support needed by video players.
res.sendFile(target);
}
}
@Module({
controllers: [EvidenceController],
providers: [
EvidenceAccessService,
{ provide: APP_INTERCEPTOR, useClass: EvidenceLinksInterceptor },
],
})
export class EvidenceAccessModule {}
@@ -0,0 +1,118 @@
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { createHmac, timingSafeEqual } from "node:crypto";
import { AsyncLocalStorage } from "node:async_hooks";
/** Short-lived read capabilities, minted only inside authenticated API responses.
* Browser image/video/PDF elements cannot attach an Authorization header. */
@Injectable()
export class EvidenceAccessService {
private digest(path: string, expires: string): string {
const secret = process.env.JWT_SECRET;
if (!secret) throw new Error("JWT_SECRET is required for evidence access");
return createHmac("sha256", secret)
.update(`evidence\n${path}\n${expires}`)
.digest("hex");
}
sign(value: string): string {
const match = value.match(
/^(?:https?:\/\/[^/?#]+\/(?:[^?#]*\/)?|(?:\.?\/)?(?:[^\s/?#]+\/)*)files\/([^?#]+)(?:[?#].*)?$/,
);
if (!match || !/\.[a-z0-9]+$/i.test(match[1])) return value;
const path = match[1];
// Signing uses the same canonical URL path that Express decodes on read.
let decoded: string;
try {
decoded = decodeURIComponent(path);
} catch {
return value;
}
const expires = String(Math.floor(Date.now() / 1000) + 3600);
return `${value.split(/[?#]/)[0]}?expires=${expires}&signature=${this.digest(decoded, expires)}`;
}
verify(path: string, expires: string, signature: string): void {
if (
typeof path !== "string" ||
typeof expires !== "string" ||
typeof signature !== "string"
)
throw new UnauthorizedException("نشانی مدرک معتبر نیست.");
const exp = Number(expires);
if (
!Number.isSafeInteger(exp) ||
exp <= Date.now() / 1000 ||
exp > Date.now() / 1000 + 3660 ||
!/^[a-f0-9]{64}$/.test(signature || "")
)
throw new UnauthorizedException(
"نشانی مدرک معتبر نیست یا منقضی شده است. پرونده را دوباره باز کنید.",
);
if (
!timingSafeEqual(
Buffer.from(signature, "hex"),
Buffer.from(this.digest(path, expires), "hex"),
)
)
throw new UnauthorizedException("دسترسی به این مدرک مجاز نیست.");
}
/** Only mirror a capability already minted by the trusted file-link builder.
* Reflected form fields or arbitrary URL-shaped text cannot mint access. */
project(value: unknown): unknown {
const allowed = new Set<string>();
const walk = (
v: unknown,
convert: (text: string, field: string) => unknown,
field = "",
): unknown => {
if (v && typeof (v as any).toObject === "function")
return walk((v as any).toObject(), convert, field);
if (typeof v === "string") return convert(v, field);
if (Array.isArray(v)) return v.map((item) => walk(item, convert, field));
if (v instanceof Map)
return Object.fromEntries(
[...v].map(([k, item]) => [k, walk(item, convert, String(k))]),
);
if (
v &&
typeof v === "object" &&
Object.getPrototypeOf(v) === Object.prototype
)
return Object.fromEntries(
Object.entries(v).map(([k, item]) => [k, walk(item, convert, k)]),
);
return v;
};
walk(value, (text) => {
if (!text.includes("signature=")) return text;
try {
const url = new URL(text, "https://evidence.invalid");
const path = decodeURIComponent(url.pathname.split("/files/")[1] || "");
this.verify(
path,
url.searchParams.get("expires")!,
url.searchParams.get("signature")!,
);
allowed.add(path);
} catch {
/* Ordinary text and untrusted links never grant access. */
}
return text;
});
return walk(value, (text, field) => {
if (!/(?:url|urls|path|paths|link|links)$/i.test(field)) return text;
try {
const url = new URL(text, "https://evidence.invalid");
const path = decodeURIComponent(url.pathname.split("/files/")[1] || "");
return allowed.has(path) ? this.sign(text) : text;
} catch {
return text;
}
});
}
}
export const evidenceRequestScope = new AsyncLocalStorage<boolean>();
const links = new EvidenceAccessService();
/** Called only when constructing a link from server-owned file metadata. */
export function signAuthorizedEvidenceLink(value: string): string {
return evidenceRequestScope.getStore() ? links.sign(value) : value;
}
@@ -0,0 +1,65 @@
import { EvidenceAccessService } from "./evidence-access.module";
describe("evidence read capabilities", () => {
const secret = process.env.JWT_SECRET;
beforeEach(() => {
process.env.JWT_SECRET = "test-only-evidence-key";
});
afterEach(() => {
if (secret == null) delete process.env.JWT_SECRET;
else process.env.JWT_SECRET = secret;
});
it("rejects bare, expired, altered and cross-path links but accepts its own signature", () => {
const service = new EvidenceAccessService();
const signed = new URL(
service.sign("https://example.test/car-damage/api/files/signs/a.jpg"),
);
const exp = signed.searchParams.get("expires")!;
const sig = signed.searchParams.get("signature")!;
expect(() => service.verify("signs/a.jpg", exp, sig)).not.toThrow();
expect(() => service.verify("signs/b.jpg", exp, sig)).toThrow();
expect(() => service.verify("signs/a.jpg", "1", sig)).toThrow();
expect(() => service.verify("signs/a.jpg", exp, "")).toThrow();
expect(() => service.verify("signs/a.jpg", exp, [sig] as any)).toThrow();
expect(() => service.verify("signs/a.jpg", exp, "0".repeat(64))).toThrow();
});
it("signs nested evidence without changing ordinary links, dates, or policy text", () => {
const service = new EvidenceAccessService();
const projected: any = service.project({
files: [
{ url: service.sign("files/car/a.jpg"), path: "files/car/a.jpg" },
],
reflected: { url: "files/car/private.jpg" },
site: "https://example.test/auth",
note: "files/car/private.jpg",
description: "https://example.test/files/signs/private.png",
});
expect(projected.files[0].url).toContain("?expires=");
expect(projected.files[0].path).toContain("?expires=");
expect(projected.reflected.url).toBe("files/car/private.jpg");
expect(projected.site).toBe("https://example.test/auth");
expect(projected.note).toBe("files/car/private.jpg");
expect(projected.description).toBe(
"https://example.test/files/signs/private.png",
);
expect(service.sign("See https://example.test/files/private.jpg")).toBe(
"See https://example.test/files/private.jpg",
);
});
});
it("mints links only while an authenticated request constructs them from stored media", () => {
const { evidenceRequestScope } = require("./evidence-access.service");
const { buildFileLink } = require("src/helpers/urlCreator");
const secret = process.env.JWT_SECRET;
process.env.JWT_SECRET = "qa-test-only";
try {
expect(buildFileLink("files/car/a.jpg")).not.toContain("signature=");
expect(
evidenceRequestScope.run(true, () => buildFileLink("files/car/a.jpg")),
).toContain("signature=");
expect(buildFileLink("files/car/a.jpg")).not.toContain("signature=");
} finally {
if (secret == null) delete process.env.JWT_SECRET;
else process.env.JWT_SECRET = secret;
}
});
+21 -10
View File
@@ -1374,7 +1374,15 @@ export class ExpertClaimService {
: null;
const blameStatus = (reviewerBlame as any).status as string;
if (blameStatus === "WAITING_FOR_FILE_REVIEWER") {
const isReviewerCapturePhase = [
ClaimCaseStatus.CREATED,
ClaimCaseStatus.WAITING_FOR_FILE_REVIEWER,
ClaimCaseStatus.SELECTING_OUTER_PARTS,
ClaimCaseStatus.SELECTING_OTHER_PARTS,
ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS,
ClaimCaseStatus.CAPTURING_PART_DAMAGES,
].includes(claim.status as ClaimCaseStatus);
if (blameStatus === "WAITING_FOR_FILE_REVIEWER" && isReviewerCapturePhase) {
if (assignedReviewerId && assignedReviewerId === actor.sub) {
// Phase 1 is intentionally idempotent. The linked claim can still be
// in a data-capture status here, so falling through to the damage
@@ -1417,7 +1425,8 @@ export class ExpertClaimService {
const isFactorValidationLock =
claimIsAwaitingExpertFactorValidationV2(claim);
const isDamageReviewLock =
claim.status === ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT;
claim.status === ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT ||
claim.status === ClaimCaseStatus.IN_PERSON_VISIT_PENDING;
const isExpertReviewingReentry =
claim.status === ClaimCaseStatus.EXPERT_REVIEWING;
const isResendPending =
@@ -1612,7 +1621,7 @@ export class ExpertClaimService {
assignFilter.initiatedByFieldExpertId = expertOid;
assignFilter.status = claim.status;
} else {
assignFilter.status = ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT;
assignFilter.status = claim.status;
}
const updated = await this.claimCaseDbService.findOneAndUpdate(
@@ -1842,6 +1851,7 @@ export class ExpertClaimService {
"workflow.currentStep": ClaimWorkflowStep.USER_EXPERT_RESEND,
"workflow.nextStep": ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT,
"evaluation.damageExpertResend": {
requestedAt: new Date(),
resendDescription: desc || undefined,
resendDocuments: uniqueDocs,
resendCarParts: normalizedParts,
@@ -2338,7 +2348,7 @@ export class ExpertClaimService {
* - Status must be EXPERT_REVIEWING
*
* On success:
* - Sets status = EXPERT_REVIEWING (remains), claimStatus = NEEDS_REVISION
* - Sets status = IN_PERSON_VISIT_PENDING, claimStatus = NEEDS_REVISION
* - Sets evaluation.visitLocation (optional note)
* - Records history event IN_PERSON_VISIT_REQUESTED
* - Unlocks the workflow so user can act
@@ -2355,7 +2365,7 @@ export class ExpertClaimService {
throw new NotFoundException("Claim request not found");
}
assertClaimCaseForTenant(claim, actor);
await this.assertExpertActorOnClaim(claim, actor);
if (claim.status !== ClaimCaseStatus.EXPERT_REVIEWING) {
throw new BadRequestException(
@@ -2377,7 +2387,7 @@ export class ExpertClaimService {
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
claimStatus: ClaimStatus.NEEDS_REVISION,
status: ClaimCaseStatus.COMPLETED,
status: ClaimCaseStatus.IN_PERSON_VISIT_PENDING,
"workflow.locked": false,
$unset: {
"workflow.lockedAt": "",
@@ -2385,7 +2395,7 @@ export class ExpertClaimService {
"workflow.lockedBy": "",
"workflow.preLockQueueSnapshot": "",
},
...(note ? { "evaluation.visitLocation": note } : {}),
"evaluation.visitLocation": note?.trim() || "برای ادامه ارزیابی، به شعبه رسیدگی پرونده مراجعه کنید.",
...(visitSnapshot && {
"evaluation.inPersonVisitExpertProfileSnapshot": visitSnapshot,
}),
@@ -2415,7 +2425,7 @@ export class ExpertClaimService {
return {
claimRequestId,
status: ClaimCaseStatus.COMPLETED,
status: ClaimCaseStatus.IN_PERSON_VISIT_PENDING,
claimStatus: ClaimStatus.NEEDS_REVISION,
message: "In-person visit requested. User will be notified.",
};
@@ -2635,7 +2645,7 @@ export class ExpertClaimService {
{
_id: { $in: blameIds.map((id) => new Types.ObjectId(id)) },
},
{ lean: true, select: "status publicId" },
{ lean: true, select: "status publicId type" },
)) as any[])
: [];
const blameById = new Map<string, any>(
@@ -3856,7 +3866,8 @@ export class ExpertClaimService {
new Map(blameLean ? [[String(claim.blameRequestId), blameLean]] : []),
);
const vehiclePayload = {
...((claim.vehicle as any) ?? {}),
...(typeof (claim.vehicle as any)?.toObject === "function"
? (claim.vehicle as any).toObject() : (claim.vehicle ?? {})),
...resolvedVehicle,
};
@@ -173,11 +173,12 @@ describe("Expert Fanavaran stage fields", () => {
management.fanavaranLookupService = {
bodyPolicyById: jest.fn().mockResolvedValue({ TotalPremium: 123456 }),
};
const payload = await management.previewFanavaranSubmitV2(id, clientKey, {
const preview = await management.previewFanavaranSubmitV2(id, clientKey, {
persistPayload: false,
forceRefreshPolicy: false,
requireClaimExpertId: false,
});
const payload = preview.payload ?? preview;
expect(payload.ClaimExpertId).toBe(154);
expect(payload).toMatchObject({
AccidentLocationAddress: "نشانی واقعی",
+16 -2
View File
@@ -166,7 +166,7 @@ export class ExpertInsurerService {
carPlate: claim.vehicle?.plate,
claimStatus: claim.status,
rating: claim.evaluation?.rating,
userRating: claim.evaluation?.userRating,
userRating: claim.userRating ?? claim.evaluation?.userRating,
damageExpertReply: claim.evaluation?.damageExpertReply,
damageExpertReplyFinal: claim.evaluation?.damageExpertReplyFinal,
damageExpertResend: claim.evaluation?.damageExpertResend,
@@ -1065,6 +1065,19 @@ export class ExpertInsurerService {
range.toDate,
);
const blameTypes = new Map(blameFiles.map((file) => [String(file._id), file.type]));
// Roster-owned claims can belong to another party insurer. Resolve only the
// missing linked types in one batch, after claims have already been scoped.
const missingBlameIds = [...new Set(claimFiles.map((file) => String(file.blameRequestId || "")))]
.filter((id) => Types.ObjectId.isValid(id) && !blameTypes.has(id));
if (missingBlameIds.length) {
const linked = await this.blameRequestDbService.find(
{_id: {$in: missingBlameIds.map((id) => new Types.ObjectId(id))}},
{lean: true, select: "type"},
);
for (const file of linked) blameTypes.set(String(file._id), file.type);
}
const blameFilesInRange = blameFiles.filter((file) =>
this.isInDateRange(file?.createdAt, range.fromDate, range.toDate),
);
@@ -1098,7 +1111,8 @@ export class ExpertInsurerService {
.filter((expertId): expertId is string => !!expertId)
.filter((expertId) => rosterById.has(expertId));
const fileType = String(
file?.snapshot?.accident?.type ??
blameTypes.get(String(file.blameRequestId)) ??
file?.snapshot?.accident?.type ??
file?.blameFile?.type ??
BlameRequestType.THIRD_PARTY,
);
@@ -0,0 +1,61 @@
import { ExpertInsurerService } from "./expert-insurer.service";
import { Types } from "mongoose";
describe("QA reporting regressions", () => {
it("classifies a roster-owned claim by its linked blame even when that blame is outside the party-insurer list", async () => {
const s: any = Object.create(ExpertInsurerService.prototype);
const clientKey = String(new Types.ObjectId()),
expertId = new Types.ObjectId(),
blameId = new Types.ObjectId();
s.expertDbService = { findAll: jest.fn().mockResolvedValue([]) };
s.damageExpertDbService = {
findAll: jest
.fn()
.mockResolvedValue([
{ _id: expertId, firstName: "QA", lastName: "Expert" },
]),
};
s.fieldExpertDbService = { findAll: jest.fn().mockResolvedValue([]) };
s.getClientBlameFiles = jest.fn().mockResolvedValue([]);
s.getClientClaimFiles = jest
.fn()
.mockResolvedValue([
{
_id: new Types.ObjectId(),
blameRequestId: blameId,
createdAt: new Date(),
},
]);
s.expertFileActivityDbService = {
findByTenant: jest.fn().mockResolvedValue([]),
};
s.claimDamageExpertActorId = jest.fn().mockReturnValue(String(expertId));
s.blameRequestDbService = {
find: jest.fn().mockResolvedValue([{ _id: blameId, type: "CAR_BODY" }]),
};
const result = await s.buildExpertReportRows({ clientKey });
expect(result.experts[0]).toMatchObject({
totalFiles: 1,
carBodyFiles: 1,
thirdPartyFiles: 0,
});
expect(s.blameRequestDbService.find).toHaveBeenCalledWith(
{ _id: { $in: [blameId] } },
{ lean: true, select: "type" },
);
});
it("preserves current root user ratings and falls back to legacy nested ratings", () => {
const s: any = Object.create(ExpertInsurerService.prototype);
const current = { overallEvaluation: 5 },
legacy = { overallEvaluation: 1 };
expect(
s.normalizeClaimCase({
userRating: current,
evaluation: { userRating: legacy },
}).userRating,
).toBe(current);
expect(
s.normalizeClaimCase({ evaluation: { userRating: legacy } }).userRating,
).toBe(legacy);
});
});
@@ -103,6 +103,12 @@ export function buildClaimDetailsV2OwnerGuidance(
const objectionAllowed = ownerMaySubmitObjectionForClaimDetails(claim);
const objectionHint = objectionHintWhen(objectionAllowed);
if (claim.status === ClaimCaseStatus.IN_PERSON_VISIT_PENDING) return {
phaseKey: "IN_PERSON_VISIT_PENDING", headline: "مراجعه حضوری درخواست شده است",
detail: claim.evaluation?.visitLocation || "برای ادامه ارزیابی، به شعبه رسیدگی پرونده مراجعه کنید.",
nextActions: [], objectionAllowed: false,
};
if (claim.status === ClaimCaseStatus.COMPLETED) {
return {
phaseKey: "COMPLETED",
+58
View File
@@ -0,0 +1,58 @@
import { canFinalizeExpertResend } from "./claim-expert-resend";
describe("current resend evidence", () => {
it("requires every replacement to be newer than this request, without discarding original evidence", () => {
const c: any = {
status: "WAITING_FOR_USER_RESEND",
workflow: { currentStep: "USER_EXPERT_RESEND" },
evaluation: {
damageExpertResend: {
requestedAt: new Date("2026-11-22T10:00:00Z"),
resendDocuments: [
"damaged_driving_license_front",
"damaged_car_card_front",
],
resendCarParts: [{ id: 101, name: "101", catalogKey: "101" }],
},
},
damage: {
selectedParts: [
{ id: 101, name: "101", catalogKey: "101", label_fa: "سپر" },
],
},
requiredDocuments: {
damaged_driving_license_front: {
uploaded: true,
uploadedAt: new Date("2026-11-21"),
},
damaged_car_card_front: {
uploaded: true,
uploadedAt: new Date("2026-11-21"),
},
},
media: {
damagedParts: [
{
id: 101,
name: "101",
catalogKey: "101",
path: "files/old.jpg",
capturedAt: new Date("2026-11-21"),
},
],
},
};
expect(canFinalizeExpertResend(c)).toBe(false);
c.requiredDocuments.damaged_driving_license_front.uploadedAt = new Date(
"2026-11-22T10:01:00Z",
);
expect(canFinalizeExpertResend(c)).toBe(false);
c.requiredDocuments.damaged_car_card_front.uploadedAt = new Date(
"2026-11-22T10:02:00Z",
);
expect(canFinalizeExpertResend(c)).toBe(false);
c.media.damagedParts[0].capturedAt = new Date("2026-11-22T10:03:00Z");
expect(canFinalizeExpertResend(c)).toBe(true);
c.evaluation.damageExpertResend.fulfilledAt = new Date();
expect(canFinalizeExpertResend(c)).toBe(false);
});
});
+16 -15
View File
@@ -260,28 +260,18 @@ export function canFinalizeExpertResend(claim: any): boolean {
claim?.damage?.selectedParts,
);
console.log("[canFinalizeExpertResend]", {
docKeys,
partKeys,
docResults: docKeys.map((k) => ({
k,
uploaded: isRequiredDocumentUploaded(claim, k),
})),
partResults: partKeys.map((k) => ({
k,
captured: hasDamagedPartCapture(claim, k),
})),
});
if (docKeys.length === 0 && partKeys.length === 0) {
return String(r.resendDescription || "").trim() !== "";
}
for (const k of docKeys) {
if (!isRequiredDocumentUploaded(claim, k)) return false;
const entry = getRequiredDocEntry(claim, k) as {uploadedAt?: Date};
if (!isRequiredDocumentUploaded(claim, k) || !isCurrentResendEvidence(claim, entry?.uploadedAt)) return false;
}
for (const k of partKeys) {
if (!hasDamagedPartCapture(claim, k)) return false;
const norm = normalizeDamageSelectedParts(claim?.damage?.selectedParts, carType, claim?.damage?.selectedOuterParts);
const capture = getDamagedPartCaptureBlob(claim?.media?.damagedParts, k, norm) as {capturedAt?: Date};
if (!hasDamagedPartCapture(claim, k) || !isCurrentResendEvidence(claim, capture?.capturedAt)) return false;
}
return true;
}
@@ -334,3 +324,14 @@ export function partKeyAllowedForExpertResend(
return directMatch || (resolvedKey != null && allowedKeys.has(resolvedKey));
}
/** Legacy pending resends use their recorded request event as the cutoff. */
export function isCurrentResendEvidence(claim: any, uploadedAt: unknown): boolean {
const requestedAt = claim?.evaluation?.damageExpertResend?.requestedAt ??
[...(claim?.history ?? [])].reverse().find((h: any) => h.type === 'EXPERT_RESEND_REQUESTED')?.timestamp;
// Old rows without a cutoff must receive fresh uploads rather than implicitly
// satisfying a replacement request using evidence from initial submission.
const cutoff = new Date(requestedAt ?? claim?.updatedAt ?? 0).getTime();
const received = new Date(uploadedAt as string).getTime();
return Number.isFinite(received) && received >= cutoff;
}
+4
View File
@@ -44,3 +44,7 @@ describe("resolveUnifiedFileStatus", () => {
expect(counts.IN_PROGRESS).toBe(2);
});
});
it("keeps a pending in-person review out of completed/user-capture buckets", () => {
expect(resolveUnifiedFileStatus({blameStatus: CaseStatus.COMPLETED, claimStatus: ClaimCaseStatus.IN_PERSON_VISIT_PENDING})).toBe("EXPERT_REVIEWING");
});
+1 -1
View File
@@ -172,7 +172,7 @@ export function resolveUnifiedFileStatus(
return "WAITING_FOR_DOCUMENT_RESEND";
}
if (claim === ClaimCaseStatus.EXPERT_REVIEWING) return "EXPERT_REVIEWING";
if (claim === ClaimCaseStatus.EXPERT_REVIEWING || claim === ClaimCaseStatus.IN_PERSON_VISIT_PENDING) return "EXPERT_REVIEWING";
if (claim === ClaimCaseStatus.EXPERT_VALIDATING_REPAIR_FACTORS) {
return "EXPERT_VALIDATING_FACTORS";
}
+4 -2
View File
@@ -1,3 +1,5 @@
import { signAuthorizedEvidenceLink } from "src/evidence-access/evidence-access.service";
type StoredFileCapture = {
url?: string;
path?: string;
@@ -41,9 +43,9 @@ export function buildFileLink(path: string): string {
const baseUrl = (process.env.URL ?? "").replace(/\/+$/, "");
if (process.env.NODE_ENV === "local") {
return `${baseUrl}/${relative}`;
return signAuthorizedEvidenceLink(`${baseUrl}/${relative}`);
}
return `${baseUrl}/api/${relative}`;
return signAuthorizedEvidenceLink(`${baseUrl}/api/${relative}`);
}
/**
+13 -2
View File
@@ -1,3 +1,4 @@
import { validateMedia } from "./validate-media";
import { BadRequestException, Injectable, Logger } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose";
import { Model, Types } from "mongoose";
@@ -106,7 +107,7 @@ export class MediaPolicyService {
kind: MediaKind,
): Promise<void> {
const limits = await this.clientService.getMediaLimits(clientId, kind);
const violation = this.checkLimits(file, limits, kind);
const violation = this.checkLimits(file, limits, kind) ?? await this.contentViolation(file, kind);
if (!violation) return;
await this.tryDelete(file?.path);
@@ -133,7 +134,7 @@ export class MediaPolicyService {
const kind = fieldKindMap[field];
if (!kind) continue;
const limits = await getLimits(kind);
const violation = this.checkLimits(file, limits, kind, field);
const violation = this.checkLimits(file, limits, kind, field) ?? await this.contentViolation(file, kind);
if (!violation) continue;
// The request is being rejected — clean up all uploaded files so we
@@ -143,6 +144,16 @@ export class MediaPolicyService {
}
}
private async contentViolation(file: NonNullable<UploadedFileLike>, kind: MediaKind) {
try {
if (!file.path) throw new Error('Missing file');
await validateMedia(file.path, kind);
return null;
} catch {
return {code: 'MEDIA_CONTENT_INVALID', kind, message: 'محتوای فایل قابل خواندن نیست یا با نوع مدرک مطابقت ندارد. فایل سالم و مناسب را دوباره انتخاب کنید.'};
}
}
private checkLimits(
file: NonNullable<UploadedFileLike>,
{ minBytes, maxBytes }: MediaLimits,
+68
View File
@@ -0,0 +1,68 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { mkdtemp, writeFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { validateMedia } from "./validate-media";
describe("uploaded media content", () => {
it("rejects text spoofed as mp4 and accepts valid document PDFs", async () => {
const dir = await mkdtemp(join(tmpdir(), "media-test-"));
try {
const path = join(dir, "spoof.mp4");
await writeFile(path, "This is not a video.");
await expect(validateMedia(path, "video")).rejects.toThrow();
const pdf = join(dir, "document.pdf");
await writeFile(pdf, "%PDF-1.4\n1 0 obj\n<<>>\nendobj\n%%EOF");
await expect(validateMedia(pdf, "image")).resolves.toBeUndefined();
} finally {
await rm(dir, { recursive: true, force: true });
}
});
});
it("accepts real images, videos and audio but rejects a still image posing as a video", async () => {
const dir = await mkdtemp(join(tmpdir(), "media-content-"));
const run = promisify(execFile);
try {
const image = join(dir, "photo.png"),
video = join(dir, "clip.mp4"),
audio = join(dir, "voice.wav");
await run("ffmpeg", [
"-v",
"error",
"-f",
"lavfi",
"-i",
"color=s=32x32",
"-frames:v",
"1",
image,
]);
await run("ffmpeg", [
"-v",
"error",
"-f",
"lavfi",
"-i",
"color=s=32x32:d=0.2",
video,
]);
await run("ffmpeg", [
"-v",
"error",
"-f",
"lavfi",
"-i",
"sine=duration=0.2",
audio,
]);
await expect(validateMedia(image, "image")).resolves.toBeUndefined();
await expect(validateMedia(video, "video")).resolves.toBeUndefined();
await expect(validateMedia(audio, "voice")).resolves.toBeUndefined();
await expect(validateMedia(image, "video")).rejects.toThrow();
await expect(validateMedia(video, "image")).rejects.toThrow();
await expect(validateMedia(image, "voice")).rejects.toThrow();
} finally {
await rm(dir, { recursive: true, force: true });
}
});
+76
View File
@@ -0,0 +1,76 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { readFile } from "node:fs/promises";
import type { MediaKind } from "src/client/client.service";
const run = promisify(execFile);
/** Inspect bytes/streams, never the user-controlled filename or Content-Type. */
export async function validateMedia(
path: string,
kind: MediaKind,
): Promise<void> {
if (kind === "image" || kind === "chassisNumber" || kind === "carPlate") {
const bytes = await readFile(path);
// Documents also accept PDFs. Require both the header and end marker.
if (bytes.subarray(0, 5).toString() === "%PDF-") {
if (!bytes.subarray(-2048).includes(Buffer.from("%%EOF")))
throw new Error("Invalid PDF");
return;
}
}
const { stdout } = await run(
"ffprobe",
[
"-v",
"error",
"-protocol_whitelist",
"file,pipe",
"-show_streams",
"-show_format",
"-of",
"json",
path,
],
{ timeout: 15000, maxBuffer: 1024 * 1024 },
);
const metadata = JSON.parse(stdout);
const imageFormat = String(metadata.format?.format_name || "")
.split(",")
.some((f: string) =>
/^(?:image2|image2pipe|.*_pipe|gif|apng|ico|heif)$/.test(f),
);
if (
(kind === "video" && imageFormat) ||
((kind === "image" || kind === "chassisNumber" || kind === "carPlate") &&
!imageFormat)
)
throw new Error("Wrong media container");
const streams = metadata.streams as Array<{
codec_type?: string;
width?: number;
height?: number;
}>;
const type = kind === "voice" ? "audio" : "video";
if (!streams?.some((s) => s.codec_type === type))
throw new Error("Missing media stream");
if (type === "video" && !streams.some((s) => s.width > 0 && s.height > 0))
throw new Error("Invalid dimensions");
await run(
"ffmpeg",
[
"-v",
"error",
"-protocol_whitelist",
"file,pipe",
"-nostdin",
"-i",
path,
"-map",
`0:${type === "audio" ? "a" : "v"}:0`,
...(type === "audio" ? ["-t", "0.1"] : ["-frames:v", "1"]),
"-f",
"null",
"-",
],
{ timeout: 15000, maxBuffer: 1024 * 1024 },
);
}
@@ -234,9 +234,9 @@ describe("V6 call-center workflow", () => {
Object.assign(body, {
accidentDate: "1405/08/18",
accidentTime: "12:00",
weatherCondition: 1,
roadCondition: 1,
lightCondition: 1,
weatherCondition: "صاف",
roadCondition: "خشک",
lightCondition: "روز",
});
await service.addDescriptionV2(id, body, first);
if (type === Kind.THIRD_PARTY) {
@@ -1,3 +1,4 @@
import { randomUUID } from "node:crypto";
import { extname } from "node:path";
import {
BadRequestException,
@@ -382,7 +383,7 @@ export class FileReviewerBlameV4Controller {
storage: diskStorage({
destination: "./files/claim-sign",
filename: (req, file, callback) => {
const unique = Date.now();
const unique = randomUUID();
const ex = extname(file.originalname);
const base = file.originalname.split(/[.,\s-]/)[0] || "sign";
callback(null, `${base}-${unique}${ex}`);
@@ -1,3 +1,4 @@
import { randomUUID } from "node:crypto";
import { extname } from "node:path";
import {
Body,
@@ -380,7 +381,7 @@ export class FileReviewerBlameV5Controller {
storage: diskStorage({
destination: "./files/claim-sign",
filename: (req, file, callback) => {
const unique = Date.now();
const unique = randomUUID();
const ex = extname(file.originalname);
const base = file.originalname.split(/[.,\s-]/)[0] || "sign";
callback(null, `${base}-${unique}${ex}`);
@@ -393,18 +393,6 @@ export class RegistrarBlameMirrorController {
@CurrentUser() registrar: any,
@UploadedFile() sign: Express.Multer.File,
) {
// Guard: accident fields must be filled before signing to prevent the
// double-sign bug where add-accident-fields re-enters WAITING_FOR_SIGNATURES.
const requestData = await this.requestManagementService.getBlameRequestV2(
requestId,
registrar,
);
if (!(requestData?.expert?.decision as any)?.fields?.accidentWay) {
throw new BadRequestException(
"Accident fields (accidentWay, accidentReason, accidentType) must be submitted via add-accident-fields before signing.",
);
}
await this.mediaPolicyService.assertForBlame(sign, requestId, "image");
const partyRole =
body?.partyRole === "SECOND" ? PartyRole.SECOND : PartyRole.FIRST;
@@ -1,3 +1,4 @@
import { WeatherCondition, RoadCondition, LightCondition } from "src/Types&Enums/blame-request-management/accident-conditions.enum";
import { UserClaimBranchService, userClaimBranchContext, usesUserClaimBranch } from "src/client/user-claim-branch.service";
import { normalizeAccidentLocation } from "./accident-location";
import {
@@ -215,6 +216,13 @@ export class RequestManagementService {
}
/** Keep eligibility rejections distinct from an unavailable CAR_BODY provider. */
private assertAccidentConditions(body: {weatherCondition?: unknown; roadCondition?: unknown; lightCondition?: unknown}): void {
for (const [value, choices] of [[body.weatherCondition, WeatherCondition], [body.roadCondition, RoadCondition], [body.lightCondition, LightCondition]] as const) {
if (value != null && !Object.values(choices).includes(value as never))
throw new BadRequestException("شرایط آب‌وهوا، راه یا روشنایی حادثه معتبر نیست. گزینه‌های فرم را دوباره انتخاب کنید.");
}
}
private assertCarBodyDescriptionMinimum(
requestType: BlameRequestType | string | undefined,
description: unknown,
@@ -2910,6 +2918,7 @@ export class RequestManagementService {
);
this.assertCarBodyDescriptionMinimum(req.type, body.desc);
this.assertAccidentConditions(body as DescriptionDto);
// Set userId for party if not already set (important for second party)
if (!party.person) party.person = {} as any;
@@ -5075,6 +5084,7 @@ export class RequestManagementService {
formData?.expertDescription?.desc,
);
this.assertAccidentConditions(formData?.expertDescription ?? {});
const firstPartyUserId = await this.getOrCreateUserByPhoneNumber(
formData.firstPartyPhoneNumber,
);
@@ -5399,6 +5409,7 @@ export class RequestManagementService {
throw new BadRequestException("expertDescription.desc is required.");
}
this.assertAccidentConditions(formData?.expertDescription ?? {});
const firstPartyUserId = await this.getOrCreateUserByPhoneNumber(
formData.firstPartyPhoneNumber,
);
@@ -5846,7 +5857,7 @@ export class RequestManagementService {
const req = await this.blameRequestDbService.findById(requestId);
if (!req) throw new NotFoundException("Request not found");
if (
!req.expertInitiated ||
(!req.expertInitiated && !req.registrarInitiated) ||
req.creationMethod !== CreationMethod.IN_PERSON
) {
throw new BadRequestException(
@@ -5889,7 +5900,7 @@ export class RequestManagementService {
const signatureData = {
fileId: String((signDoc as any)._id),
fileName: signFile.filename,
fileUrl: signFile.path,
fileUrl: buildFileLink(signFile.path),
};
const updatePayload: any = {
$set: {
@@ -6578,7 +6589,7 @@ export class RequestManagementService {
const signatureData = {
fileId: String((signDoc as any)._id),
fileName: signFile.filename,
fileUrl: signFile.path,
fileUrl: buildFileLink(signFile.path),
};
const confirmationPayload = {
@@ -8203,7 +8214,7 @@ export class RequestManagementService {
const signatureData = {
fileId: String((signDoc as any)._id),
fileName: signFile.filename,
fileUrl: signFile.path,
fileUrl: buildFileLink(signFile.path),
};
await this.blameRequestDbService.findByIdAndUpdate(requestId, {
@@ -8700,6 +8711,7 @@ export class RequestManagementService {
const role = this.resolvePartyRoleV3(req, partyRole);
this.assertBlameV3PartyDetailPhase(req, role);
this.assertCarBodyDescriptionMinimum(req.type, body.desc);
this.assertAccidentConditions(body as DescriptionDto);
// accidentDate and accidentTime are only required for the first (guilty)
// party — the second (damaged) party can skip them.
@@ -8724,8 +8736,6 @@ 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);