forked from Yara724/api
fix(claims): validate invoice decisions before saving and explain resend limits
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
# Claim resend and invoice workflow regressions — 2026-11-23
|
||||
|
||||
## Reported failures and causes
|
||||
|
||||
- **Resend PUT returned a generic 422.** The exact reported body (part ID 15, no documents and a non-empty description) is accepted for a first resend cycle. The service explicitly returns `DAMAGE_EXPERT_RESEND_LIMIT_EXCEEDED` after an earlier resend was fulfilled. The expert proxy discarded that code, and the English explanation fell through to a generic Persian form-validation message. The one-completed-resend policy remains unchanged. The API now gives a specific Persian explanation; the expert proxy retains the code; the sidebar explains and disables a completed resend when its case detail is available, and displays server errors inline.
|
||||
- **Invoice approval shared the assessment submission UI.** Its decisions lived under user opinions and depended on globally initialized factor drafts. It could reach assessment selection/pricing validation and demand damaged parts. Review now belongs to each saved assessment part, beside its invoice viewer. The independent action calls `PATCH /v2/expert-claim/validate-factors/:id` with one decision; it does not update selected damaged parts or resubmit the assessment.
|
||||
- **Mixed replies required a refresh after signing.** The owner page delayed dispatching the pre-signature step by three seconds, the upload callback captured old case state, and the part list also read a stale Redux step. The mutation response now immediately updates the case query, the current API step drives upload permissions, and signature/upload operations invalidate the case query. Pending invoice work also stays visible in in-person flows rather than being hidden by a completion summary.
|
||||
- **Invoice validation could persist changes before rejecting a total.** The service now validates the proposed decisions and the completed-batch V1 total before persistence. The update checks the original case phase and update timestamp (or the parts snapshot for legacy fixtures) to reject a stale write. Invalid/duplicate/unrelated decisions cause no writes. A rejected invoice needs a reason and an expert amount.
|
||||
|
||||
## UI behavior
|
||||
|
||||
- Review actions appear only on `/requests/check`, for claim, field and file-reviewer experts, in the invoice review phase and after all required invoices are uploaded. Insurers and file makers retain viewing access.
|
||||
- Each pending invoice can be approved or repriced/rejected in its own dialog. Enter the **whole line total including labor, in rials**. This is not an additional amount to add to the existing line.
|
||||
- Local validation and server failures keep the dialog/draft available for correction and retry. Cancelling does not save a decision. Saved decisions disappear from the pending controls; case queries refresh. Completing the batch uses `caseStatus` to return to the list, including V5 FileMaker approval.
|
||||
- Signing a mixed reply enables invoice upload on the current page. Every upload refreshes the case. Once all invoices arrive, upload controls and the signature action are replaced by the expert-review waiting state.
|
||||
- The live claim query and in-person query take precedence over the original detail snapshot so refreshed decisions are visible.
|
||||
- The previous invoice controls under user opinions and their unused validation component were removed.
|
||||
|
||||
## Verification
|
||||
|
||||
`test/claim-invoice-resend.e2e-spec.ts` exercises the real Nest controllers, JWT/role guards, DTO validation and workflow services with in-memory persistence. It covers v1–v6 × THIRD_PARTY/CAR_BODY × mixed/all-factor/priced assessments, mixed signing before upload, sequential uploads, duplicate upload rejection, per-invoice partial batches, completion/V5 handoff, malformed/duplicate/unknown decisions, Persian amounts, rejected invoice reasons, cap failure with no writes followed by a corrected retry, stale writes, and the exact resend payload followed by the documented 422 rule.
|
||||
|
||||
The full HTTP suite passes 72 tests with four pre-existing skips. The general API suite retains the ten previously documented failures in `fanavaran-submit-overrides.spec.ts`; they fail at its vehicle-review prerequisite and are unrelated to these changes.
|
||||
|
||||
Both UI suites include invoice regressions. Browser checks at 1440×1100 and 390×844 exercise the rendered expert invoice viewer/review action, required amount validation, an HTTP error with retry, and the actual user result page with canvas signing and two successive invoice uploads without a reload. Browser API replies are intercepted synthetic fixtures; no production case, SMS, Fanavaran or object storage is used. Test artifacts live under `/tmp/invoice-review-*`, and temporary preview routes are removed.
|
||||
|
||||
These are targeted workflow tests, not a claim that every production integration or every application route was manually exercised. Deploy **API, expert UI and user UI together**; there is no environment or database migration requirement.
|
||||
@@ -2,13 +2,15 @@ import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { Type } from "class-transformer";
|
||||
import {
|
||||
IsArray,
|
||||
ArrayMinSize,
|
||||
ArrayUnique,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsOptional,
|
||||
IsString,
|
||||
ValidateNested,
|
||||
} from "class-validator";
|
||||
import { IsRepairLineAmountToman } from "src/common/validators/repair-line-amount-toman.validator";
|
||||
import { IsMoneyAmountString } from "src/common/validators/money-amount-string.validator";
|
||||
import { FactorStatus } from "src/Types&Enums/claim-request-management/factor-status.enum";
|
||||
|
||||
class FactorDecisionDto {
|
||||
@@ -51,35 +53,36 @@ class FactorDecisionV2Dto {
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
"Part price (Toman). With totalPayment or price+salary for APPROVED/REJECTED factor lines. Use 0 if unused.",
|
||||
"Part price (Rial). With totalPayment or price+salary for APPROVED/REJECTED factor lines. Use 0 if unused.",
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsRepairLineAmountToman({ allowZero: true })
|
||||
@IsMoneyAmountString()
|
||||
price?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
"Salary in Toman. Send with price when not using only totalPayment. Use 0 if unused.",
|
||||
"Salary in Rial. Send with price when not using only totalPayment. Use 0 if unused.",
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsRepairLineAmountToman({ allowZero: true })
|
||||
@IsMoneyAmountString()
|
||||
salary?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
"Line total in Toman; or send both price and salary.",
|
||||
description: "Line total in Rial; or send both price and salary.",
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsRepairLineAmountToman()
|
||||
@IsMoneyAmountString()
|
||||
totalPayment?: string;
|
||||
}
|
||||
|
||||
export class FactorValidationV2Dto {
|
||||
@ApiProperty({ type: [FactorDecisionV2Dto] })
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
@ArrayUnique((decision: FactorDecisionV2Dto) => decision.partId)
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => FactorDecisionV2Dto)
|
||||
decisions: FactorDecisionV2Dto[];
|
||||
|
||||
@@ -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.",
|
||||
"کاربر درخواست قبلی تکمیل اطلاعات را انجام داده است. برای این پرونده امکان درخواست مجدد وجود ندارد؛ پاسخ کارشناسی را ثبت کنید یا مراجعه حضوری درخواست دهید.",
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -455,7 +455,7 @@ export class ExpertClaimV2Controller {
|
||||
@ApiBody({ type: FactorValidationV2Dto })
|
||||
async validateClaimFactorsV2(
|
||||
@Param("claimRequestId") claimRequestId: string,
|
||||
@Body() body: FactorValidationV2Dto,
|
||||
@Body(submitExpertReplyValidationPipe) body: FactorValidationV2Dto,
|
||||
@CurrentUser() actor,
|
||||
) {
|
||||
return await this.expertClaimService.validateClaimFactorsV2(
|
||||
|
||||
@@ -34,7 +34,11 @@ function flattenValidationErrors(
|
||||
const ownErrors = Object.keys(error.constraints ?? {}).map(
|
||||
(constraint) => ({
|
||||
field,
|
||||
message: constraintMessages[constraint] ?? "مقدار واردشده معتبر نیست.",
|
||||
message: field === "decisions" && constraint === "arrayMinSize"
|
||||
? "حداقل یک فاکتور را بررسی کنید."
|
||||
: field === "decisions" && constraint === "arrayUnique"
|
||||
? "برای هر فاکتور فقط یک نتیجه بررسی ارسال کنید."
|
||||
: constraintMessages[constraint] ?? "مقدار واردشده معتبر نیست.",
|
||||
}),
|
||||
);
|
||||
return [
|
||||
@@ -54,10 +58,12 @@ export const submitExpertReplyValidationPipe = new ValidationPipe({
|
||||
whitelist: true,
|
||||
exceptionFactory: (errors: ValidationError[]) => {
|
||||
const validationErrors = flattenValidationErrors(errors);
|
||||
const invoiceReview = errors.some(error => error.property === "decisions");
|
||||
const code = invoiceReview ? "FACTOR_VALIDATION_ERROR" : "EXPERT_REPLY_VALIDATION_ERROR";
|
||||
return new BadRequestException({
|
||||
message: "اطلاعات ارسالی پاسخ کارشناسی معتبر نیست.",
|
||||
error: "EXPERT_REPLY_VALIDATION_ERROR",
|
||||
code: "EXPERT_REPLY_VALIDATION_ERROR",
|
||||
message: invoiceReview ? "اطلاعات بررسی فاکتور معتبر نیست. فیلدهای مشخصشده را بررسی کنید." : "اطلاعات ارسالی پاسخ کارشناسی معتبر نیست.",
|
||||
error: code,
|
||||
code,
|
||||
validationErrors,
|
||||
});
|
||||
},
|
||||
|
||||
@@ -0,0 +1,488 @@
|
||||
/** HTTP regression suite from expert assessment through owner signing/uploads and invoice review.
|
||||
* Real controllers, guards, validation pipes and workflow services; in-memory persistence and no external delivery.
|
||||
*/
|
||||
import "reflect-metadata";
|
||||
import { Test } from "@nestjs/testing";
|
||||
import { JwtModule, JwtService } from "@nestjs/jwt";
|
||||
import { INestApplication } from "@nestjs/common";
|
||||
import { HttpAdapterHost } from "@nestjs/core";
|
||||
import * as request from "supertest";
|
||||
import { mkdir, unlink } from "node:fs/promises";
|
||||
import { Types } from "mongoose";
|
||||
import { ExpertClaimV2Controller } from "src/expert-claim/expert-claim.v2.controller";
|
||||
import { ExpertClaimService } from "src/expert-claim/expert-claim.service";
|
||||
import { ClaimRequestManagementV2Controller } from "src/claim-request-management/claim-request-management.v2.controller";
|
||||
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
|
||||
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
|
||||
import { MediaPolicyService } from "src/media-policy/media-policy.service";
|
||||
import { AiService } from "src/ai/ai.service";
|
||||
import { ActorAuthService } from "src/auth/auth-services/actor.auth.service";
|
||||
import { GlobalGuard } from "src/auth/guards/global.guard";
|
||||
import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard";
|
||||
import { RolesGuard } from "src/auth/guards/role.guard";
|
||||
import { PersianErrorFilter } from "src/common/errors/persian-error.filter";
|
||||
|
||||
const id = "650000000000000000000001",
|
||||
actorId = "650000000000000000000002",
|
||||
ownerId = "650000000000000000000003",
|
||||
tenant = "650000000000000000000004";
|
||||
const clone = (v: any) => (v == null ? v : JSON.parse(JSON.stringify(v)));
|
||||
const png = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jTncAAAAASUVORK5CYII=",
|
||||
"base64",
|
||||
);
|
||||
function get(obj: any, path: string) {
|
||||
return path.split(".").reduce((o, k) => o?.[k], obj);
|
||||
}
|
||||
function set(obj: any, path: string, value: any) {
|
||||
const keys = path.split(".");
|
||||
const last = keys.pop();
|
||||
const parent = keys.reduce(
|
||||
(o, k) => (o[k] ??= /^\d+$/.test(k) ? [] : {}),
|
||||
obj,
|
||||
);
|
||||
parent[last] = clone(value);
|
||||
}
|
||||
function unset(obj: any, path: string) {
|
||||
const keys = path.split(".");
|
||||
const last = keys.pop();
|
||||
const parent = keys.reduce((o, k) => o?.[k], obj);
|
||||
if (parent) delete parent[last];
|
||||
}
|
||||
|
||||
describe("claim resend and invoice lifecycle through HTTP", () => {
|
||||
let app: INestApplication,
|
||||
jwt: JwtService,
|
||||
claim: any,
|
||||
blame: any,
|
||||
expert: any,
|
||||
owner: any;
|
||||
let forceStale = false;
|
||||
const writes: any[] = [];
|
||||
const files: string[] = [];
|
||||
const priorSecret = process.env.JWT_SECRET,
|
||||
priorCap = process.env.CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED;
|
||||
const repo = {
|
||||
findById: jest.fn(async () => clone(claim)),
|
||||
findByIdAndUpdate: jest.fn(async (_id, update) => apply(update)),
|
||||
findOneAndUpdate: jest.fn(async (filter, update) => {
|
||||
if (forceStale) {
|
||||
forceStale = false;
|
||||
return null;
|
||||
}
|
||||
for (const [key, value] of Object.entries(filter)) {
|
||||
if (key.endsWith(".partId")) continue;
|
||||
const actual = get(claim, key);
|
||||
if (
|
||||
value === null
|
||||
? actual != null
|
||||
: JSON.stringify(actual) !== JSON.stringify(clone(value))
|
||||
)
|
||||
return null;
|
||||
}
|
||||
let normalized = clone(update);
|
||||
if (Object.keys(filter).some((k) => k.endsWith(".partId"))) {
|
||||
const key = Object.keys(filter).find((k) => k.endsWith(".partId"));
|
||||
const path = key.slice(0, -7);
|
||||
const index = get(claim, path).findIndex(
|
||||
(p) => String(p.partId) === String(filter[key]),
|
||||
);
|
||||
normalized.$set = Object.fromEntries(
|
||||
Object.entries(normalized.$set).map(([k, v]) => [
|
||||
k.replace(".$.", `.${index}.`),
|
||||
v,
|
||||
]),
|
||||
);
|
||||
}
|
||||
return apply(normalized);
|
||||
}),
|
||||
};
|
||||
function apply(update: any) {
|
||||
writes.push(clone(update));
|
||||
for (const [key, value] of Object.entries({
|
||||
...Object.fromEntries(
|
||||
Object.entries(update).filter(([k]) => !k.startsWith("$")),
|
||||
),
|
||||
...update.$set,
|
||||
}))
|
||||
set(claim, key, value);
|
||||
for (const key of Object.keys(update.$unset ?? {})) unset(claim, key);
|
||||
for (const [key, value] of Object.entries(update.$push ?? {})) {
|
||||
let list = get(claim, key);
|
||||
if (!list) {
|
||||
set(claim, key, []);
|
||||
list = get(claim, key);
|
||||
}
|
||||
list.push(clone(value));
|
||||
}
|
||||
return clone(claim);
|
||||
}
|
||||
const actorToken = (flow = "v1") =>
|
||||
jwt.sign(
|
||||
{
|
||||
sub: actorId,
|
||||
role: ["v1", "v6"].includes(flow)
|
||||
? "damage_expert"
|
||||
: ["v2", "v3"].includes(flow)
|
||||
? "field_expert"
|
||||
: "file_reviewer",
|
||||
clientKey: tenant,
|
||||
fullName: "کارشناس آزمایشی",
|
||||
},
|
||||
{ secret: process.env.JWT_SECRET },
|
||||
);
|
||||
const userToken = () =>
|
||||
jwt.sign(
|
||||
{ sub: ownerId, role: "user", fullName: "مالک آزمایشی" },
|
||||
{ secret: process.env.JWT_SECRET },
|
||||
);
|
||||
const act = (method: "put" | "patch", path: string, flow = "v1") =>
|
||||
request(app.getHttpServer())
|
||||
[method](path)
|
||||
.set("Authorization", `Bearer ${actorToken(flow)}`);
|
||||
const user = (method: "put" | "patch", path: string) =>
|
||||
request(app.getHttpServer())
|
||||
[method](path)
|
||||
.set("Authorization", `Bearer ${userToken()}`);
|
||||
beforeAll(async () => {
|
||||
process.env.JWT_SECRET = "invoice-regression-test-secret";
|
||||
delete process.env.CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED;
|
||||
await mkdir("files/claim-sign", { recursive: true });
|
||||
await mkdir("files/claim-factors", { recursive: true });
|
||||
expert = Object.create(ExpertClaimService.prototype);
|
||||
owner = Object.create(ClaimRequestManagementService.prototype);
|
||||
Object.assign(expert, {
|
||||
claimCaseDbService: repo,
|
||||
blameRequestDbService: { findById: async () => clone(blame) },
|
||||
assertExpertActorOnClaim: jest.fn(async () => {}),
|
||||
snapshotDamageExpert: jest.fn(async () => undefined),
|
||||
recordClaimExpertActivity: jest.fn(async () => {}),
|
||||
resolveClaimOwnerPhone: jest.fn(async () => null),
|
||||
logger: { warn: jest.fn(), error: jest.fn(), log: jest.fn() },
|
||||
loadBlameForClaim: async () => clone(blame),
|
||||
});
|
||||
Object.assign(owner, {
|
||||
claimCaseDbService: repo,
|
||||
resolveClaimEffectiveUserId: async () => ownerId,
|
||||
assertEffectiveUserIsDamagedPartyOnClaim: async () => {},
|
||||
autoSubmitFanavaranExpertiseOnExpertReply: async () => ({submitted:false,attempted:false}),
|
||||
autoSubmitToFanavaranV2OnClaimCompleted: async () => ({submitted:false,attempted:false}),
|
||||
claimSignDbService: {
|
||||
create: async () => ({ _id: new Types.ObjectId() }),
|
||||
},
|
||||
claimFactorsImageDbService: {
|
||||
create: async () => ({ _id: new Types.ObjectId() }),
|
||||
},
|
||||
logger: { warn: jest.fn(), error: jest.fn(), log: jest.fn() },
|
||||
});
|
||||
const module = await Test.createTestingModule({
|
||||
imports: [JwtModule.register({})],
|
||||
controllers: [
|
||||
ExpertClaimV2Controller,
|
||||
ClaimRequestManagementV2Controller,
|
||||
],
|
||||
providers: [
|
||||
LocalActorAuthGuard,
|
||||
GlobalGuard,
|
||||
RolesGuard,
|
||||
{
|
||||
provide: ActorAuthService,
|
||||
useValue: { assertActorActive: async () => {} },
|
||||
},
|
||||
{ provide: ExpertClaimService, useValue: expert },
|
||||
{ provide: ClaimRequestManagementService, useValue: owner },
|
||||
{ provide: ClaimCaseDbService, useValue: repo },
|
||||
{ provide: AiService, useValue: {} },
|
||||
{
|
||||
provide: MediaPolicyService,
|
||||
useValue: {
|
||||
assertForClaim: async (file) => {
|
||||
if (file?.path) files.push(file.path);
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
app = module.createNestApplication({ logger: false });
|
||||
app.useGlobalFilters(new PersianErrorFilter(app.get(HttpAdapterHost)));
|
||||
await app.init();
|
||||
jwt = app.get(JwtService);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await app?.close();
|
||||
await Promise.all(files.map((file) => unlink(file).catch(() => {})));
|
||||
if (priorSecret === undefined) delete process.env.JWT_SECRET;
|
||||
else process.env.JWT_SECRET = priorSecret;
|
||||
if (priorCap === undefined)
|
||||
delete process.env.CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED;
|
||||
else process.env.CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED = priorCap;
|
||||
});
|
||||
function fixture(flow = "v1", type = "THIRD_PARTY") {
|
||||
writes.length = 0;
|
||||
forceStale = false;
|
||||
blame = {
|
||||
type,
|
||||
flowVersion: flow,
|
||||
expertInitiated: ["v2", "v3"].includes(flow),
|
||||
registrarInitiated: ["v4", "v5"].includes(flow),
|
||||
callCenterInitiated: flow === "v6",
|
||||
creationMethod:
|
||||
flow === "v1" ? "NORMAL" : flow === "v6" ? "LINK" : "IN_PERSON",
|
||||
};
|
||||
claim = {
|
||||
_id: id,
|
||||
publicId: "QA-1",
|
||||
blameRequestId: "650000000000000000000005",
|
||||
status: "EXPERT_REVIEWING",
|
||||
owner: { userId: ownerId, clientId: tenant },
|
||||
requiresFileMakerApproval: flow === "v5",
|
||||
workflow: {
|
||||
locked: true,
|
||||
lockedBy: { actorId },
|
||||
currentStep: "EXPERT_DAMAGE_ASSESSMENT",
|
||||
},
|
||||
vehicle: { carType: "sedan" },
|
||||
evaluation: {},
|
||||
damage: {
|
||||
selectedParts: [30, 31, 15].map((part) => ({
|
||||
id: part,
|
||||
name: String(part),
|
||||
side: "",
|
||||
label_fa: String(part),
|
||||
catalogKey: String(part),
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
function quote(partId: number, factorNeeded: boolean) {
|
||||
return {
|
||||
partId,
|
||||
typeOfDamage: "تعویض",
|
||||
...(factorNeeded ? {} : { price: "1000000" }),
|
||||
salary: "1000000",
|
||||
totalPayment: factorNeeded ? "1000000" : "2000000",
|
||||
factorNeeded,
|
||||
daghi: { option: "فاقد ارزش" },
|
||||
};
|
||||
}
|
||||
function readyForReview() {
|
||||
fixture();
|
||||
claim.status = "EXPERT_VALIDATING_REPAIR_FACTORS";
|
||||
claim.claimStatus = "UNDER_REVIEW";
|
||||
claim.workflow.currentStep = "EXPERT_COST_EVALUATION";
|
||||
claim.evaluation.damageExpertReply = {
|
||||
submittedAt: new Date().toISOString(),
|
||||
parts: [
|
||||
{
|
||||
...quote(30, true),
|
||||
factorLink: "test-factor",
|
||||
factorStatus: "PENDING",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
for (const flow of ["v1", "v2", "v3", "v4", "v5", "v6"])
|
||||
for (const type of ["THIRD_PARTY", "CAR_BODY"])
|
||||
for (const shape of ["mixed", "all-factor", "priced"]) {
|
||||
it(`${flow} ${type} ${shape}: assessment → signature if needed → uploads → per-invoice review`, async () => {
|
||||
fixture(flow, type);
|
||||
const parts = [
|
||||
quote(30, shape !== "priced"),
|
||||
quote(31, shape === "all-factor"),
|
||||
];
|
||||
const reply = await act(
|
||||
"put",
|
||||
`/v2/expert-claim/reply/submit/${id}`,
|
||||
flow,
|
||||
).send({
|
||||
parts,
|
||||
...(type === "CAR_BODY" ? { carPrice: "1000000000" } : {}),
|
||||
});
|
||||
expect(reply.status).toBe(200);
|
||||
if (shape === "priced") {
|
||||
if (claim.status === "INSURER_REVIEW_AWAITING_OWNER_SIGN") {
|
||||
const signature = await user("put", `/v2/claim-request-management/request/${id}/owner-insurer-approval/sign`)
|
||||
.field("agree", "true").attach("sign", png, {filename:"signature.png",contentType:"image/png"});
|
||||
expect(signature.status).toBe(200);
|
||||
}
|
||||
expect(claim.status).toBe(flow === "v5" ? "WAITING_FOR_FILE_MAKER_APPROVAL" : "COMPLETED");
|
||||
return;
|
||||
}
|
||||
const upload = (part: number) =>
|
||||
user(
|
||||
"patch",
|
||||
`/v2/claim-request-management/request/reply/${id}/${part}/upload-factor`,
|
||||
).attach("file", png, {
|
||||
filename: "factor.png",
|
||||
contentType: "image/png",
|
||||
});
|
||||
if (shape === "mixed") {
|
||||
expect((await upload(30)).status).toBe(400);
|
||||
const sign = await user(
|
||||
"put",
|
||||
`/v2/claim-request-management/request/${id}/owner-insurer-approval/sign`,
|
||||
)
|
||||
.field("agree", "true")
|
||||
.attach("sign", png, {
|
||||
filename: "signature.png",
|
||||
contentType: "image/png",
|
||||
});
|
||||
expect(sign.status).toBe(200);
|
||||
expect(sign.body.currentStep).toBe("OWNER_UPLOAD_FACTOR_DOCUMENTS");
|
||||
} else
|
||||
expect(claim.workflow.currentStep).toBe(
|
||||
"OWNER_UPLOAD_FACTOR_DOCUMENTS",
|
||||
);
|
||||
expect((await upload(30)).status).toBe(200);
|
||||
expect((await upload(30)).status).toBe(409);
|
||||
if (shape === "all-factor")
|
||||
expect((await upload(31)).status).toBe(200);
|
||||
expect(claim.status).toBe("EXPERT_VALIDATING_REPAIR_FACTORS");
|
||||
for (const part of parts.filter((p) => p.factorNeeded)) {
|
||||
const result = await act(
|
||||
"patch",
|
||||
`/v2/expert-claim/validate-factors/${id}`,
|
||||
flow,
|
||||
).send({
|
||||
decisions: [
|
||||
{
|
||||
partId: part.partId,
|
||||
status: "APPROVED",
|
||||
totalPayment: "3000000",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(result.status).toBe(200);
|
||||
}
|
||||
expect(claim.status).toBe(
|
||||
flow === "v5" ? "WAITING_FOR_FILE_MAKER_APPROVAL" : "COMPLETED",
|
||||
);
|
||||
expect(
|
||||
claim.evaluation.damageExpertReply.parts
|
||||
.filter((p) => p.factorNeeded)
|
||||
.every((p) => p.factorStatus === "APPROVED"),
|
||||
).toBe(true);
|
||||
});
|
||||
}
|
||||
it("accepts the exact reported resend body on its first cycle and exposes the Persian rule on a second cycle", async () => {
|
||||
fixture();
|
||||
const body = {
|
||||
resendDescription: "gjjjjjjg",
|
||||
resendDocuments: [],
|
||||
resendCarParts: [
|
||||
{
|
||||
key: "چراغ عقب چپ",
|
||||
label_fa: "چراغ عقب چپ",
|
||||
label_en: "15",
|
||||
side: "",
|
||||
id: 15,
|
||||
captured: false,
|
||||
name: "15",
|
||||
},
|
||||
],
|
||||
};
|
||||
const first = await act("put", `/v2/expert-claim/reply/resend/${id}`).send(
|
||||
body,
|
||||
);
|
||||
expect(first.status).toBe(200);
|
||||
expect(claim.evaluation.damageExpertResend.resendCarParts[0].id).toBe(15);
|
||||
claim.status = "EXPERT_REVIEWING";
|
||||
claim.workflow.locked = true;
|
||||
claim.workflow.lockedBy = { actorId };
|
||||
claim.evaluation.damageExpertResend.fulfilledAt = new Date().toISOString();
|
||||
const before = clone(claim);
|
||||
const second = await act("put", `/v2/expert-claim/reply/resend/${id}`).send(
|
||||
body,
|
||||
);
|
||||
expect(second.status).toBe(422);
|
||||
expect(second.body.errorCode).toBe("DAMAGE_EXPERT_RESEND_LIMIT_EXCEEDED");
|
||||
expect(second.body.message).toContain("درخواست قبلی");
|
||||
expect(claim).toEqual(before);
|
||||
});
|
||||
it.each(
|
||||
[
|
||||
[],
|
||||
[{ partId: 30, status: "PENDING", totalPayment: "3000000" }],
|
||||
[{ partId: 30, status: "APPROVED", totalPayment: "factor" }],
|
||||
[{ partId: 30, status: "APPROVED" }],
|
||||
[{ partId: 30, status: "REJECTED", totalPayment: "3000000" }],
|
||||
[{ partId: 99, status: "APPROVED", totalPayment: "3000000" }],
|
||||
[
|
||||
{ partId: 30, status: "APPROVED", totalPayment: "3000000" },
|
||||
{
|
||||
partId: 30,
|
||||
status: "REJECTED",
|
||||
totalPayment: "3000000",
|
||||
rejectionReason: "خطا",
|
||||
},
|
||||
],
|
||||
].map((decisions) => [decisions]),
|
||||
)("invalid invoice decision makes no writes: %j", async (decisions) => {
|
||||
readyForReview();
|
||||
const before = clone(claim);
|
||||
const res = await act(
|
||||
"patch",
|
||||
`/v2/expert-claim/validate-factors/${id}`,
|
||||
).send({ decisions });
|
||||
expect(res.status).toBe(400);
|
||||
expect(claim).toEqual(before);
|
||||
expect(writes).toHaveLength(0);
|
||||
});
|
||||
it("a cap failure preserves pending invoice data and a corrected retry completes", async () => {
|
||||
readyForReview();
|
||||
blame.expertInitiated = false;
|
||||
blame.registrarInitiated = false;
|
||||
blame.creationMethod = "NORMAL";
|
||||
process.env.CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED = "true";
|
||||
const before = clone(claim);
|
||||
const res = await act(
|
||||
"patch",
|
||||
`/v2/expert-claim/validate-factors/${id}`,
|
||||
).send({
|
||||
decisions: [
|
||||
{ partId: 30, status: "APPROVED", totalPayment: "600000000" },
|
||||
],
|
||||
});
|
||||
expect(res.status).toBe(400);
|
||||
expect(claim).toEqual(before);
|
||||
expect(writes).toHaveLength(0);
|
||||
expect(
|
||||
(
|
||||
await act("patch", `/v2/expert-claim/validate-factors/${id}`).send({
|
||||
decisions: [
|
||||
{ partId: 30, status: "APPROVED", totalPayment: "3000000" },
|
||||
],
|
||||
})
|
||||
).status,
|
||||
).toBe(200);
|
||||
delete process.env.CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED;
|
||||
});
|
||||
it("rejecting an invoice with a corrected amount completes with its reason, and stale writes return 409", async () => {
|
||||
readyForReview();
|
||||
forceStale = true;
|
||||
const body = {
|
||||
decisions: [
|
||||
{
|
||||
partId: 30,
|
||||
status: "REJECTED",
|
||||
totalPayment: "۳٬۰۰۰٬۰۰۰",
|
||||
rejectionReason: "اصلاح مبلغ فاکتور",
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(
|
||||
(await act("patch", `/v2/expert-claim/validate-factors/${id}`).send(body))
|
||||
.status,
|
||||
).toBe(409);
|
||||
expect(writes).toHaveLength(0);
|
||||
expect(
|
||||
(await act("patch", `/v2/expert-claim/validate-factors/${id}`).send(body))
|
||||
.status,
|
||||
).toBe(200);
|
||||
expect(claim.evaluation.damageExpertReply.parts[0]).toMatchObject({
|
||||
factorStatus: "REJECTED",
|
||||
totalPayment: "3000000",
|
||||
rejectionReason: "اصلاح مبلغ فاکتور",
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user