fix(claims): reuse saved Sheba across claim workflow steps

This commit is contained in:
SepehrYahyaee
2026-11-21 16:36:34 +03:30
parent be364d94fe
commit 90f290154c
10 changed files with 412 additions and 54 deletions
@@ -0,0 +1,247 @@
import {
BadRequestException,
ConflictException,
ForbiddenException,
} from "@nestjs/common";
import { validate } from "class-validator";
import { Types } from "mongoose";
import { ClaimRequestManagementService } from "./claim-request-management.service";
import { savedClaimBankInformation } from "./claim-bank-information";
import { SelectOtherPartsV2Dto } from "./dto/select-other-parts-v2.dto";
const claimId = "650000000000000000000001";
const userId = "650000000000000000000002";
const blameId = "650000000000000000000003";
const sheba = "IR" + "1".repeat(24);
const ownerCode = "0012345678";
function fixture(
money: any = undefined,
type = "CAR_BODY",
step = "SELECT_OTHER_PARTS",
) {
const claim: any = {
_id: new Types.ObjectId(claimId),
publicId: "TEST",
blameRequestId: blameId,
owner: { userId, fullName: "نمونه" },
money,
workflow: { currentStep: step },
};
const service = Object.create(ClaimRequestManagementService.prototype) as any;
service.claimCaseDbService = {
findById: jest.fn().mockResolvedValue(claim),
findByIdAndUpdate: jest.fn().mockResolvedValue(claim),
};
service.blameRequestDbService = {
findById: jest.fn().mockResolvedValue({ type }),
};
service.resolveClaimEffectiveUserId = jest.fn().mockResolvedValue(userId);
service.assertEffectiveUserIsDamagedPartyOnClaim = jest
.fn()
.mockResolvedValue(undefined);
service.resolveVehicleOwnerNationalCodeForClaim = jest
.fn()
.mockReturnValue(ownerCode);
service.resolveOwnershipPlateForClaim = jest
.fn()
.mockReturnValue({ leftDigits: 12 });
service.sandHubService = {
getShebaValidation: jest.fn().mockResolvedValue({ ReturnValue: true }),
};
service.logger = { log: jest.fn(), error: jest.fn() };
return { service, claim };
}
describe("single-entry claim bank information", () => {
it.each(["CAR_BODY", "THIRD_PARTY"])(
"reuses saved bank information for %s, including resend",
async (type) => {
for (const step of ["SELECT_OTHER_PARTS", "USER_EXPERT_RESEND"]) {
for (const storedSheba of [sheba, sheba.slice(2)]) {
const { service } = fixture(
{ sheba: storedSheba, nationalCodeOfInsurer: ownerCode },
type,
step,
);
const result = await service.selectOtherPartsV2(
claimId,
{ otherParts: ["engine"] },
userId,
);
expect(result.currentStep).toBe("CAPTURE_PART_DAMAGES");
expect(
service.claimCaseDbService.findByIdAndUpdate,
).toHaveBeenCalledWith(
claimId,
expect.objectContaining({
"money.sheba": sheba,
"money.nationalCodeOfInsurer": ownerCode,
"damage.otherParts": ["engine"],
}),
);
expect(
service.sandHubService.getShebaValidation,
).not.toHaveBeenCalled();
}
}
},
);
it.each(["sheba", "shebaNumber"])(
"collects a new %s once and derives the vehicle owner identity",
async (field) => {
const { service } = fixture();
await service.selectOtherPartsV2(claimId, { [field]: sheba }, userId);
expect(service.sandHubService.getShebaValidation).toHaveBeenCalledWith(
ownerCode,
sheba,
);
expect(service.claimCaseDbService.findByIdAndUpdate).toHaveBeenCalledWith(
claimId,
expect.objectContaining({
"money.sheba": sheba,
"money.nationalCodeOfInsurer": ownerCode,
}),
);
},
);
it("retains a saved Sheba when only the legacy owner identity was missing", async () => {
const { service } = fixture({ sheba });
await service.selectOtherPartsV2(claimId, {}, userId);
expect(service.sandHubService.getShebaValidation).toHaveBeenCalledWith(
ownerCode,
sheba,
);
});
it("accepts the same previously saved number with a different IR/whitespace representation", async () => {
const { service } = fixture({
sheba: sheba.slice(2),
nationalCodeOfInsurer: ownerCode,
});
await service.selectOtherPartsV2(
claimId,
{ sheba: " ir " + sheba.slice(2) },
userId,
);
expect(service.sandHubService.getShebaValidation).not.toHaveBeenCalled();
});
it("still requires and validates bank information when none was saved", async () => {
const { service } = fixture();
for (const value of [undefined, "IR", "invalid", "123"]) {
await expect(
service.selectOtherPartsV2(claimId, { sheba: value }, userId),
).rejects.toBeInstanceOf(BadRequestException);
}
expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled();
});
it("does not silently replace saved bank information outside an explicit resend", async () => {
const { service } = fixture({ sheba, nationalCodeOfInsurer: ownerCode });
await expect(
service.selectOtherPartsV2(
claimId,
{ sheba: "IR" + "2".repeat(24) },
userId,
),
).rejects.toBeInstanceOf(ConflictException);
expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled();
});
it("does not reuse another owner’s bank information", async () => {
const { service } = fixture({ sheba, nationalCodeOfInsurer: "0098765432" });
await expect(
service.selectOtherPartsV2(claimId, {}, userId),
).rejects.toBeInstanceOf(BadRequestException);
expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled();
expect(
savedClaimBankInformation(
{ sheba, nationalCodeOfInsurer: "0098765432" },
ownerCode,
),
).toMatchObject({
shebaProvided: false,
ownerNationalCodeProvided: true,
});
});
it("rejects a submitted national code that differs from the vehicle owner", async () => {
const { service } = fixture();
await expect(
service.selectOtherPartsV2(
claimId,
{ sheba, nationalCodeOfInsurer: "0098765432" },
userId,
),
).rejects.toBeInstanceOf(BadRequestException);
});
it("keeps beneficiary authorization before reusing saved bank information", async () => {
const { service } = fixture({ sheba, nationalCodeOfInsurer: ownerCode });
service.assertEffectiveUserIsDamagedPartyOnClaim.mockRejectedValue(
new ForbiddenException(),
);
await expect(
service.selectOtherPartsV2(claimId, {}, userId),
).rejects.toBeInstanceOf(ForbiddenException);
expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled();
});
it.each([sheba, sheba.slice(2)])(
"lets the expert continue with saved bank information (%s)",
async (storedSheba) => {
const { service } = fixture({
sheba: storedSheba,
nationalCodeOfInsurer: ownerCode,
});
service.assertFieldExpertInPersonBlameForClaimCase = jest
.fn()
.mockResolvedValue(undefined);
await service.expertCompleteClaimData(
claimId,
{ sub: userId },
{ otherParts: [] },
);
expect(service.claimCaseDbService.findByIdAndUpdate).toHaveBeenCalledWith(
claimId,
expect.objectContaining({
"money.sheba": sheba,
"workflow.currentStep": "CAPTURE_PART_DAMAGES",
}),
);
},
);
it("allows omitted bank fields through DTO validation but rejects malformed field types", async () => {
expect(
await validate(
Object.assign(new SelectOtherPartsV2Dto(), { otherParts: [] }),
),
).toHaveLength(0);
expect(
await validate(
Object.assign(new SelectOtherPartsV2Dto(), { sheba: 123 }),
),
).not.toHaveLength(0);
});
it("recognizes incomplete and malformed saved details without exposing them", () => {
expect(savedClaimBankInformation()).toMatchObject({
shebaProvided: false,
ownerNationalCodeProvided: false,
});
expect(
savedClaimBankInformation({
sheba: "IR123",
nationalCodeOfInsurer: "123",
}),
).toMatchObject({ shebaProvided: false, ownerNationalCodeProvided: false });
expect(savedClaimBankInformation({ sheba })).toMatchObject({
shebaProvided: true,
ownerNationalCodeProvided: false,
});
});
});
@@ -0,0 +1,30 @@
export function normalizeClaimSheba(value: unknown): string | undefined {
const digits = String(value ?? "")
.replace(/\s/g, "")
.replace(/^IR/i, "");
return /^\d{24}$/.test(digits) ? `IR${digits}` : undefined;
}
export function normalizeClaimNationalCode(value: unknown): string | undefined {
const code = String(value ?? "").replace(/\s/g, "");
return /^\d{10}$/.test(code) ? code : undefined;
}
/** Saved bank details belong to this claim's vehicle owner, never another party. */
export function savedClaimBankInformation(
money?: { sheba?: string; nationalCodeOfInsurer?: string } | null,
vehicleOwnerNationalCode?: string,
) {
const savedOwner = normalizeClaimNationalCode(money?.nationalCodeOfInsurer);
const currentOwner = normalizeClaimNationalCode(vehicleOwnerNationalCode);
const ownerChanged =
!!savedOwner && !!currentOwner && savedOwner !== currentOwner;
const sheba = ownerChanged ? undefined : normalizeClaimSheba(money?.sheba);
const nationalCode = currentOwner ?? savedOwner;
return {
sheba,
nationalCode,
shebaProvided: !!sheba,
ownerNationalCodeProvided: !!nationalCode,
};
}
@@ -230,6 +230,7 @@ describe("claim beneficiary authorization across shared user flows", () => {
owner: { userId: firstId },
damagedPartyUserId: secondId,
status: "SELECTING_OUTER_PARTS",
money: { sheba: "IR" + "1".repeat(24), nationalCodeOfInsurer: "0012345678" },
};
service.claimCaseDbService.findById = jest.fn().mockResolvedValue(claim);
service.blameRequestDbService.find = jest
@@ -246,6 +247,9 @@ describe("claim beneficiary authorization across shared user flows", () => {
role: RoleEnum.USER,
});
expect(damaged.canAct).toBe(true);
expect(damaged.bankInformation).toEqual({ shebaProvided: true, ownerNationalCodeProvided: true });
expect(damaged.money.sheba).toContain("*");
expect(damaged.money.sheba).not.toBe(claim.money.sheba);
expect(damaged.ownerGuidance).toBeDefined();
});
@@ -1,3 +1,8 @@
import {
normalizeClaimSheba,
normalizeClaimNationalCode,
savedClaimBankInformation,
} from './claim-bank-information';
import { UserClaimBranchService, usesUserClaimBranch } from "src/client/user-claim-branch.service";
import {
hasReviewedTejaratNotifier,
@@ -1227,7 +1232,7 @@ export class ClaimRequestManagementService {
);
}
const mergedSheba = dto.sheba != null ? dto.sheba : fresh.money?.sheba;
const mergedSheba = normalizeClaimSheba(dto.sheba ?? fresh.money?.sheba);
const mergedNational =
dto.nationalCodeOfInsurer != null
? dto.nationalCodeOfInsurer
@@ -1236,7 +1241,7 @@ export class ClaimRequestManagementService {
if (
fresh.money?.sheba &&
dto.sheba != null &&
dto.sheba !== fresh.money.sheba
normalizeClaimSheba(dto.sheba) !== normalizeClaimSheba(fresh.money.sheba)
) {
throw new ConflictException('Sheba is already set for this claim.');
}
@@ -1264,7 +1269,7 @@ export class ClaimRequestManagementService {
const bankComplete =
mergedSheba &&
mergedNational &&
/^[0-9]{24}$/.test(String(mergedSheba).replace(/\s/g, '')) &&
!!normalizeClaimSheba(mergedSheba) &&
/^[0-9]{10}$/.test(String(mergedNational).replace(/\s/g, ''));
if (bankComplete) {
@@ -9095,7 +9100,7 @@ export class ClaimRequestManagementService {
* - Claim case must exist
* - User must be the claim owner (damaged party)
* - Current workflow step must be SELECT_OTHER_PARTS (step 3)
* - Other parts and bank info must not have been submitted previously
* - Saved bank info is reused; only missing fields must be supplied
*/
async selectOtherPartsV2(
claimRequestId: string,
@@ -9138,17 +9143,6 @@ export class ClaimRequestManagementService {
);
}
// 4. Validate other parts and bank info haven't been submitted yet
if (
claimCase.money?.sheba &&
claimCase.money?.nationalCodeOfInsurer &&
claimCase.workflow?.currentStep !== ClaimWorkflowStep.USER_EXPERT_RESEND
) {
throw new ConflictException(
'Bank information has already been submitted for this claim',
);
}
// 5. Prepare data
// Backward compatibility aliases:
// - shebaNumber <- sheba
@@ -9168,22 +9162,12 @@ export class ClaimRequestManagementService {
otherParts = [];
}
}
const shebaInput = String(
((body as any).shebaNumber ?? (body as any).sheba ?? '') as string,
).replace(/\s/g, '');
const shebaDigits = shebaInput.replace(/^IR/i, '');
const shebaNumber = `IR${shebaDigits}`;
const submittedShebaInput = String(
body.shebaNumber ?? body.sheba ?? '',
).trim();
const submittedNationalCode = String(
((body as any).nationalCodeOfOwner ??
(body as any).nationalCodeOfInsurer ??
'') as string,
body.nationalCodeOfOwner ?? body.nationalCodeOfInsurer ?? '',
).replace(/\s/g, '');
if (!/^[0-9]{24}$/.test(shebaDigits)) {
throw new BadRequestException(
'shebaNumber is required and must be valid (IR + 24 digits or only 24 digits)',
);
}
const blameRequest = claimCase.blameRequestId
? await this.blameRequestDbService.findById(
claimCase.blameRequestId.toString(),
@@ -9200,10 +9184,34 @@ export class ClaimRequestManagementService {
'Submitted national code does not match the vehicle owner saved on the blame case.',
);
}
const nationalCode = storedOwnerNationalCode ?? submittedNationalCode;
if (!/^[0-9]{10}$/.test(nationalCode)) {
const savedBank = savedClaimBankInformation(
claimCase.money,
storedOwnerNationalCode,
);
const shebaNumber = submittedShebaInput
? normalizeClaimSheba(submittedShebaInput)
: savedBank.sheba;
if (!shebaNumber) {
throw new BadRequestException(
'Vehicle owner national code is unavailable; a 10-digit nationalCodeOfOwner is required only for legacy claims.',
'شماره شبا باید شامل IR و ۲۴ رقم یا فقط ۲۴ رقم باشد.',
);
}
if (
savedBank.sheba &&
submittedShebaInput &&
shebaNumber !== savedBank.sheba &&
claimCase.workflow?.currentStep !== ClaimWorkflowStep.USER_EXPERT_RESEND
) {
throw new ConflictException(
'شماره شبا قبلاً برای این پرونده ثبت شده است؛ نیازی به ورود مجدد آن نیست.',
);
}
const shebaDigits = shebaNumber.slice(2);
const nationalCode =
storedOwnerNationalCode ?? (submittedNationalCode || savedBank.nationalCode);
if (!normalizeClaimNationalCode(nationalCode)) {
throw new BadRequestException(
'کد ملی ۱۰ رقمی مالک خودرو برای ثبت اطلاعات حساب الزامی است.',
);
}
const ownershipPlate = this.resolveOwnershipPlateForClaim(
@@ -9216,13 +9224,17 @@ export class ClaimRequestManagementService {
);
}
let step = claimCase.workflow?.currentStep;
// External inquiry checks before moving workflow:
// 1) ownership check for nationalCode + plate
// await this.sandHubService.getCarOwnershipInfo(ownershipPlate, nationalCode);
// 2) sheba check for nationalCode + sheba
await this.sandHubService.getShebaValidation(nationalCode, shebaNumber);
const bankUnchanged =
normalizeClaimSheba(claimCase.money?.sheba) === shebaNumber &&
normalizeClaimNationalCode(claimCase.money?.nationalCodeOfInsurer) ===
nationalCode;
if (!bankUnchanged) {
await this.sandHubService.getShebaValidation(nationalCode, shebaNumber);
}
const updatePayload: any = {
'damage.otherParts': otherParts.length > 0 ? otherParts : undefined,
@@ -11613,7 +11625,7 @@ export class ClaimRequestManagementService {
? ((
await this.blameRequestDbService.find(
{ _id: new Types.ObjectId(claim.blameRequestId.toString()) },
{ lean: true, select: 'type creationMethod' },
{ lean: true, select: 'type creationMethod parties expert' },
)
)[0] ?? null)
: null;
@@ -11763,6 +11775,10 @@ export class ClaimRequestManagementService {
fullName: claim.owner.fullName,
}
: undefined;
const savedBank = savedClaimBankInformation(
claim.money,
this.resolveVehicleOwnerNationalCodeForClaim(blameForDetail),
);
const moneyForUser = claim.money
? {
sheba: maskSheba(claim.money.sheba),
@@ -11801,6 +11817,10 @@ export class ClaimRequestManagementService {
selectedParts: selectedNormDetails,
otherParts: claim.damage?.otherParts,
money: isExpertViewer ? moneyForExpert : moneyForUser,
bankInformation: {
shebaProvided: savedBank.shebaProvided,
ownerNationalCodeProvided: savedBank.ownerNationalCodeProvided,
},
requiredDocuments:
Object.keys(requiredDocumentsStatus).length > 0
? requiredDocumentsStatus
@@ -621,8 +621,8 @@ Optional: upload car green card file in the same step.
- Claim must exist
- User must be the claim owner (damaged party from blame case)
- Current workflow step must be SELECT_OTHER_PARTS
- Bank information must not have been submitted previously
- Sheba (sheba) accepted as IR + 24 digits or only 24 digits
- Previously saved bank information is reused when omitted
- Sheba (sheba) accepted as IR + 24 digits or only 24 digits; required only if not saved
- National code must be exactly 10 digits
**Valid Other Parts (Optional):**
@@ -656,7 +656,7 @@ Optional: upload car green card file in the same step.
)
@ApiBody({
description:
"Other parts + bank information. Use `sheba` and `nationalCodeOfInsurer` like THIRD_PARTY flow. Optional file can be uploaded as car green card.",
"Other parts + optional bank information. Saved Sheba and vehicle-owner identity are reused; supply missing fields only. Optional car green card file.",
schema: {
type: "object",
properties: {
@@ -671,7 +671,6 @@ Optional: upload car green card file in the same step.
nationalCodeOfInsurer: { type: "string", example: "1234567890" },
file: { type: "string", format: "binary" },
},
required: ["sheba", "nationalCodeOfInsurer"],
},
})
@ApiResponse({
@@ -693,7 +692,7 @@ Optional: upload car green card file in the same step.
})
@ApiResponse({
status: 409,
description: "Bank information already submitted",
description: "Conflicting bank information",
})
async selectOtherParts(
@Param("claimRequestId") claimRequestId: string,
@@ -182,6 +182,15 @@ export class ClaimDetailsV2ResponseDto {
nationalCodeOfOwner?: string;
};
@ApiPropertyOptional({
description: 'Whether bank fields can be reused from this claim or its vehicle-owner identity. Does not expose bank details.',
example: { shebaProvided: true, ownerNationalCodeProvided: true },
})
bankInformation?: {
shebaProvided: boolean;
ownerNationalCodeProvided: boolean;
};
@ApiPropertyOptional({
description: "Required documents status (link instead of id)",
})
@@ -1,5 +1,5 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsArray, IsEnum, IsNotEmpty, IsOptional, IsString, Matches, Length, ArrayMaxSize } from 'class-validator';
import { IsArray, IsEnum, IsOptional, IsString, Matches, Length, ArrayMaxSize } from 'class-validator';
/**
* Enum for valid other (non-body) car parts that can be damaged
@@ -40,13 +40,13 @@ export class SelectOtherPartsV2Dto {
})
otherParts?: OtherCarPart[];
@ApiProperty({
description: 'Sheba number (IBAN). Accepted: IR + 24 digits OR only 24 digits',
@ApiPropertyOptional({
description: 'Sheba number (IBAN). Required only if not already saved on this claim. Accepted: IR + 24 digits OR only 24 digits',
example: 'IR123456789012345678901234',
})
@IsNotEmpty({ message: 'sheba is required' })
@IsOptional()
@IsString({ message: 'sheba must be a string' })
sheba: string;
sheba?: string;
@ApiPropertyOptional({
description: 'Legacy alias of sheba for backward compatibility',
@@ -241,8 +241,8 @@ Optional: upload car green card file in the same step.
**Validations:**
- Claim must exist
- Current workflow step must be SELECT_OTHER_PARTS
- Bank information must not have been submitted previously
- Sheba (sheba) accepted as IR + 24 digits or only 24 digits
- Previously saved bank information is reused when omitted
- Sheba (sheba) accepted as IR + 24 digits or only 24 digits; required only if not saved
- National code must be exactly 10 digits
**Valid Other Parts (Optional):**
@@ -275,7 +275,7 @@ Optional: upload car green card file in the same step.
)
@ApiBody({
description:
"Other parts + bank information. Use `sheba` and `nationalCodeOfInsurer`. Optional file can be uploaded as car green card.",
"Other parts + optional bank information. Saved Sheba and vehicle-owner identity are reused; supply missing fields only. Optional car green card file.",
schema: {
type: "object",
properties: {
@@ -290,7 +290,6 @@ Optional: upload car green card file in the same step.
nationalCodeOfInsurer: { type: "string", example: "1234567890" },
file: { type: "string", format: "binary" },
},
required: ["sheba", "nationalCodeOfInsurer"],
},
})
@ApiResponse({
@@ -305,7 +304,7 @@ Optional: upload car green card file in the same step.
@ApiResponse({ status: 404, description: "Claim case not found" })
@ApiResponse({
status: 409,
description: "Bank information already submitted",
description: "Conflicting bank information",
})
async selectOtherParts(
@Param("claimRequestId") claimRequestId: string,
@@ -241,7 +241,7 @@ Optional: upload car green card file in the same step.
)
@ApiBody({
description:
"Other parts + bank information. Use `sheba` and `nationalCodeOfInsurer`. Optional file can be uploaded as car green card.",
"Other parts + optional bank information. Saved Sheba and vehicle-owner identity are reused; supply missing fields only. Optional car green card file.",
schema: {
type: "object",
properties: {
@@ -256,7 +256,6 @@ Optional: upload car green card file in the same step.
nationalCodeOfInsurer: { type: "string", example: "1234567890" },
file: { type: "string", format: "binary" },
},
required: ["sheba", "nationalCodeOfInsurer"],
},
})
@ApiResponse({
@@ -266,7 +265,7 @@ Optional: upload car green card file in the same step.
})
@ApiResponse({ status: 400, description: "Invalid workflow step or validation failed" })
@ApiResponse({ status: 404, description: "Claim case not found" })
@ApiResponse({ status: 409, description: "Bank information already submitted" })
@ApiResponse({ status: 409, description: "Conflicting bank information" })
async selectOtherParts(
@Param("claimRequestId") claimRequestId: string,
@Body() body: SelectOtherPartsV2Dto,