forked from Yara724/api
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:
@@ -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();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user