fix(claims): validate invoice decisions before saving and explain resend limits

This commit is contained in:
SepehrYahyaee
2026-11-23 15:05:46 +03:30
parent 036d218ebd
commit 187a0ea3a9
6 changed files with 673 additions and 109 deletions
+136 -96
View File
@@ -989,7 +989,7 @@ export class ExpertClaimService {
if (!claimIsAwaitingExpertFactorValidationV2(claim)) {
throw new BadRequestException(
"Claim is not awaiting expert factor validation (UNDER_REVIEW at EXPERT_COST_EVALUATION).",
"پرونده در مرحله بررسی فاکتور توسط کارشناس نیست. وضعیت پرونده را دوباره دریافت کنید.",
);
}
@@ -1002,76 +1002,160 @@ export class ExpertClaimService {
: claim.evaluation?.damageExpertReply;
if (!finalReply?.parts?.length) {
throw new BadRequestException("No expert reply found in this claim.");
throw new BadRequestException("پاسخ کارشناسی برای بررسی فاکتور در این پرونده یافت نشد.");
}
const requiredFactors = finalReply.parts.filter((p) => p.factorNeeded);
if (requiredFactors.length === 0) {
throw new BadRequestException("No parts require factor validation.");
throw new BadRequestException("در این پاسخ کارشناسی قطعه‌ای نیازمند بررسی فاکتور نیست.");
}
if (!requiredFactors.every((p) => !!p.factorLink)) {
throw new BadRequestException(
"Not all required factors have been uploaded yet.",
"هنوز همه فاکتورهای موردنیاز بارگذاری نشده‌اند.",
);
}
if (!Array.isArray(body.decisions) || body.decisions.length === 0) {
throw new BadRequestException("حداقل یک فاکتور را بررسی کنید.");
}
const $set: Record<string, unknown> = {};
const seen = new Set<string>();
const proposedParts = finalReply.parts.map((part: any) => ({
...(typeof part.toObject === "function" ? part.toObject() : part),
}));
for (const decision of body.decisions) {
const partIndex = finalReply.parts.findIndex((p) =>
sameCatalogPartId(p.partId, decision.partId),
const partIndex = proposedParts.findIndex((part) =>
sameCatalogPartId(part.partId, decision.partId),
);
if (partIndex === -1) {
this.logger.warn(
`Part ${decision.partId} not found in claim ${claimRequestId}, skipping.`,
const id = String(decision.partId);
if (seen.has(id))
throw new BadRequestException(
"برای هر فاکتور فقط یک نتیجه بررسی ارسال کنید.",
);
continue;
}
const part = finalReply.parts[partIndex];
if (!part.factorNeeded) {
this.logger.warn(
`Part ${decision.partId} is not factor-needed, skipping.`,
seen.add(id);
if (partIndex < 0 || !proposedParts[partIndex].factorNeeded) {
throw new BadRequestException(
"قطعه انتخاب‌شده در فهرست فاکتورهای موردنیاز پرونده وجود ندارد.",
);
continue;
}
const base = `evaluation.${replyField}.parts.${partIndex}`;
$set[`${base}.factorStatus`] = decision.status;
$set[`${base}.rejectionReason`] = decision.rejectionReason ?? null;
if (decision.price !== undefined) {
$set[`${base}.price`] = decision.price;
}
if (decision.salary !== undefined) {
$set[`${base}.salary`] = decision.salary;
}
if (decision.totalPayment !== undefined) {
$set[`${base}.totalPayment`] = decision.totalPayment;
}
if (
decision.status === FactorStatus.APPROVED ||
decision.status === FactorStatus.REJECTED
![FactorStatus.APPROVED, FactorStatus.REJECTED].includes(
decision.status,
)
) {
if (!this.expertFactorValidationDecisionHasLinePricing(decision)) {
throw new BadRequestException(
"نتیجه بررسی فاکتور باید تأیید یا عدم تأیید باشد.",
);
}
if (
decision.status === FactorStatus.REJECTED &&
!String(decision.rejectionReason ?? "").trim()
) {
throw new BadRequestException("دلیل عدم تأیید فاکتور را وارد کنید.");
}
const providedTotal =
decision.totalPayment != null &&
String(decision.totalPayment).trim() !== "";
const price = parseMoneyAmountToman(decision.price);
const salary = parseMoneyAmountToman(decision.salary);
const lineTotal = providedTotal
? parseMoneyAmountToman(decision.totalPayment)
: price != null && salary != null
? price + salary
: NaN;
if (
!this.expertFactorValidationDecisionHasLinePricing(decision) ||
!Number.isSafeInteger(lineTotal) ||
lineTotal < 1_000_000 ||
lineTotal > 100_000_000_000
) {
throw new BadRequestException(
"مبلغ نهایی قطعه با احتساب اجرت باید بین ۱٬۰۰۰٬۰۰۰ و ۱۰۰٬۰۰۰٬۰۰۰٬۰۰۰ ریال باشد.",
);
}
const base = `evaluation.${replyField}.parts.${partIndex}`;
const updates: Record<string, unknown> = {
factorStatus: decision.status,
rejectionReason:
decision.status === FactorStatus.REJECTED
? decision.rejectionReason.trim()
: null,
totalPayment: String(lineTotal),
};
for (const field of ["price", "salary"] as const) {
if (decision[field] === undefined) continue;
const amount = parseMoneyAmountToman(decision[field]);
if (
!Number.isSafeInteger(amount) ||
amount < 0 ||
amount > 100_000_000_000
) {
throw new BadRequestException(
`Part ${decision.partId}: ${decision.status === FactorStatus.APPROVED ? "approved" : "rejected"} factor lines require expert totalPayment (or both price and salary).`,
"قیمت قطعه و اجرت باید مبلغ صحیح و نامنفی به ریال باشند.",
);
}
updates[field] = String(amount);
}
Object.assign(proposedParts[partIndex], updates);
for (const [field, value] of Object.entries(updates))
$set[`${base}.${field}`] = value;
}
const reqParts = proposedParts.filter((part) => part.factorNeeded);
const anyRejected = reqParts.some(
(part) => part.factorStatus === FactorStatus.REJECTED,
);
const anyStillPending = reqParts.some(
(part) =>
!part.factorStatus || part.factorStatus === FactorStatus.PENDING,
);
if (!anyStillPending) {
const configuredPriceCap = getClaimV2TotalPaymentCapToman();
const priceCap =
configuredPriceCap !== null &&
claimPriceCapAppliesToBlame(await this.loadBlameForClaim(claim))
? configuredPriceCap
: null;
if (priceCap !== null) {
let totalPrice = 0;
for (const part of proposedParts || []) {
const line = this.claimReplyPartLineTotalForCap(part);
if (isNaN(line)) {
throw new BadRequestException({
message: `مبلغ قطعه ${String(part.partId ?? "")} معتبر نیست. مبلغ نهایی یا قیمت قطعه و اجرت را ثبت کنید.`,
error: "PRICE_CAP_ERROR",
});
}
totalPrice += line;
}
if (totalPrice > priceCap) {
throw new BadRequestException({
message: `مجموع مبلغ قطعات و فاکتورها (${totalPrice.toLocaleString("fa-IR")} ریال) از سقف مجاز پرونده (${priceCap.toLocaleString("fa-IR")} ریال) بیشتر است.`,
error: "PRICE_CAP_ERROR",
totalPrice,
priceCap,
});
}
}
}
if (Object.keys($set).length === 0) {
throw new BadRequestException("No valid factor decisions to apply.");
}
if (factorValidationSnapshot) {
if (factorValidationSnapshot)
$set["evaluation.factorValidationExpertProfileSnapshot"] =
factorValidationSnapshot;
}
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set,
});
const updatedClaim = await this.claimCaseDbService.findOneAndUpdate(
{
_id: claim._id,
status: claim.status,
claimStatus: claim.claimStatus,
"workflow.currentStep": claim.workflow.currentStep,
...((claim as any).updatedAt != null
? { updatedAt: (claim as any).updatedAt }
: { [`evaluation.${replyField}.parts`]: finalReply.parts }),
},
{ $set },
);
if (!updatedClaim)
throw new ConflictException(
"اطلاعات فاکتورها هنگام بررسی تغییر کرده است. پرونده را دوباره دریافت و تلاش کنید.",
);
await this.recordClaimExpertActivity({
expertId: String(actor.sub),
tenantId: this.claimActivityTenantId(claim, actor),
@@ -1079,59 +1163,15 @@ export class ExpertClaimService {
eventType: ExpertFileActivityType.CHECKED,
idempotencyKey: `claim:${claimRequestId}:checked:${actor.sub}`,
});
const updatedClaim = await this.claimCaseDbService.findById(claimRequestId);
const updatedReply =
replyField === "damageExpertReplyFinal"
? updatedClaim!.evaluation!.damageExpertReplyFinal!
: updatedClaim!.evaluation!.damageExpertReply!;
const reqParts = updatedReply.parts.filter((p) => p.factorNeeded);
const anyRejected = reqParts.some(
(p) => p.factorStatus === FactorStatus.REJECTED,
);
const anyStillPending = reqParts.some(
(p) => !p.factorStatus || p.factorStatus === FactorStatus.PENDING,
);
const baseMessage = "Factor validation updated.";
if (anyStillPending) {
if (anyStillPending)
return {
message: `${baseMessage} Some factors are still pending review.`,
message:
"نتیجه بررسی فاکتور ثبت شد. فاکتورهای باقی‌مانده را نیز بررسی کنید.",
claimRequestId,
claimStatus: updatedClaim!.claimStatus,
caseStatus: updatedClaim!.status,
claimStatus: updatedClaim.claimStatus,
caseStatus: updatedClaim.status,
pendingFactorValidation: true,
};
}
const configuredPriceCap = getClaimV2TotalPaymentCapToman();
const priceCap =
configuredPriceCap !== null &&
claimPriceCapAppliesToBlame(await this.loadBlameForClaim(claim))
? configuredPriceCap
: null;
if (priceCap !== null) {
let totalPrice = 0;
for (const part of updatedReply.parts || []) {
const line = this.claimReplyPartLineTotalForCap(part);
if (isNaN(line)) {
throw new BadRequestException({
message: `Part ${String(part.partId ?? "")}: invalid amount for price total — use totalPayment or price and salary.`,
error: "PRICE_CAP_ERROR",
});
}
totalPrice += line;
}
if (totalPrice > priceCap) {
throw new BadRequestException({
message: `You have reached the maximum acceptable total price (Rial). The sum of priced parts and factor lines (${totalPrice.toLocaleString()}) exceeds the limit (${priceCap.toLocaleString()}).`,
error: "PRICE_CAP_ERROR",
totalPrice,
priceCap,
});
}
}
const historyActor = {
actorId: new Types.ObjectId(actor.sub),
@@ -1816,7 +1856,7 @@ export class ExpertClaimService {
if (existingResend?.fulfilledAt) {
throw new BusinessRuleException(
BusinessErrorCode.DAMAGE_EXPERT_RESEND_LIMIT_EXCEEDED,
"The owner has already fulfilled a damage-expert resend for this claim. You cannot request another resend.",
"کاربر درخواست قبلی تکمیل اطلاعات را انجام داده است. برای این پرونده امکان درخواست مجدد وجود ندارد؛ پاسخ کارشناسی را ثبت کنید یا مراجعه حضوری درخواست دهید.",
);
}