fix(claim-pricing): keep invoice and repair states consistent

This commit is contained in:
SepehrYahyaee
2026-11-23 12:03:02 +03:30
parent c74b29337e
commit 036d218ebd
7 changed files with 160 additions and 43 deletions
@@ -19,7 +19,7 @@ Content-Type: application/json
## بدنه درخواست
تمام مبلغ‌ها باید **string** باشند. ارقام فارسی/انگلیسی و جداکننده هزارگان پذیرفته می‌شوند؛ برای نمونه هر دو مقدار `"100000"` و `"۱۰۰,۰۰۰"` معتبرند.
تمام مبلغ‌ها باید **string** باشند. ارقام فارسی/انگلیسی و جداکننده هزارگان پذیرفته می‌شوند؛ برای نمونه هر دو مقدار `"1000000"` و `"۱۰۰,۰۰۰"` معتبرند.
```json
{
@@ -29,12 +29,12 @@ Content-Type: application/json
"partId": 201,
"typeOfDamage": "تعویض",
"price": "2500000",
"salary": "400000",
"totalPayment": "2900000",
"salary": "1000000",
"totalPayment": "3500000",
"factorNeeded": false,
"daghi": {
"option": "ارزش لوازم بازیافتی",
"price": "300000"
"price": "1000000"
}
}
]
@@ -54,21 +54,29 @@ Content-Type: application/json
| --- | --- | --- |
| `partId` | بله | عدد صحیح؛ باید متعلق به قطعات آسیب‌دیده همان پرونده باشد. |
| `typeOfDamage` | بله | دقیقاً یکی از `"تعمیر"` یا `"تعویض"`. |
| `price` | برای `"تعویض"` بله؛ برای `"تعمیر"` اختیاری | در صورت ارسال، مبلغ بین 100,000 تا 10,000,000,000 تومان. |
| `salary` | بله | مبلغ بین 100,000 تا 10,000,000,000 تومان. |
| `price` | فقط تعویض با قیمت قطعی | برای ردیف `factorNeeded=true` قیمت قطعه ارسال نشود؛ متن `factor` یا `فاکتور` مبلغ نیست. در صورت ارسال مبلغ، بازه 1,000,000 تا 100,000,000,000 ریال معتبر است. |
| `salary` | بله | مبلغ بین 1,000,000 تا 100,000,000,000 ریال. |
| `totalPayment` | بله | مبلغ بین 1,000,000 تا 100,000,000,000 ریال. فقط در جریان V1، مجموع این فیلدها در کل پرونده نباید از 530,000,000 ریال بیشتر شود. |
| `factorNeeded` | بله | مقدار Boolean واقعی (`true` یا `false`)؛ رشته ارسال نکنید. |
| `factorNeeded` | بله | مقدار Boolean واقعی؛ فقط ردیف تعویض می‌تواند `true` باشد. در تعمیر باید `false` باشد. |
| `daghi` | برای `"تعویض"` بله | برای `"تعمیر"` لازم نیست و در ثبت نهایی حذف می‌شود. |
| `daghi.option` | در صورت وجود `daghi` بله | یکی از `"ارزش لوازم بازیافتی"`، `"تحویل داغی"`، `"فاقد ارزش"` یا `"با احتساب داغی"`. |
| `daghi.price` | فقط وقتی `option` برابر `"ارزش لوازم بازیافتی"` است | مبلغ بین 100,000 تا 10,000,000,000 تومان. |
| `daghi.price` | فقط وقتی `option` برابر `"ارزش لوازم بازیافتی"` است | مبلغ بین 1,000,000 تا 100,000,000,000 ریال. |
| `daghi.branchId` | فقط وقتی `option` برابر `"تحویل داغی"` است | Mongo ObjectId معتبرِ شعبه. |
نکته‌ها:
- مقدار `0` برای هیچ مبلغ ارسالی این endpoint معتبر نیست؛ حداقل مبلغ 100,000 تومان است.
- مقدار `0` برای هیچ مبلغ ارسالی این endpoint معتبر نیست؛ حداقل مبلغ 1,000,000 ریال است.
- محدودیت هر فیلد مبلغ مستقل است؛ سقف 530 میلیون ریال فقط برای **مجموع `totalPayment` تمام ردیف‌های پرونده V1** اعمال می‌شود. جریان‌های V2 تا V6 سقف مجموع ندارند.
- فیلدهای ناشناخته در body حذف می‌شوند. فرانت‌اند نباید برای انتقال داده به آن‌ها تکیه کند.
### تغییر روش قیمت‌گذاری و خطاها
- انتخاب فاکتور، قیمت قطعی قطعه را پاک می‌کند؛ `salary` و `totalPayment` همچنان مبلغ عددی معتبر لازم دارند.
- تبدیل تعویض به تعمیر، روش فاکتور، قیمت قطعه و اطلاعات داغی را یکجا پاک می‌کند و مجموع شناخته‌شده را از اجرت محاسبه می‌کند.
- تبدیل فاکتور به قیمت، `factorNeeded` را خاموش و انتخاب قیمت جدید را الزامی می‌کند؛ قیمت قدیمی به‌طور پنهان استفاده نمی‌شود.
- خطای اعتبارسنجی، پرچم فاکتور یا وضعیت ذخیره‌شده پرونده را تغییر نمی‌دهد. UI پیش از ذخیره تغییرات انتخاب قطعات، پیش‌اعتبارسنجی می‌کند و ارسال تکراری هم‌زمان را مسدود می‌کند.
- پیام‌های خطای این مسیر با واحد ریال نمایش داده می‌شوند.
## پاسخ موفق
پاسخ `200` شامل مسیر بعدی workflow است. نمونه:
@@ -106,7 +114,7 @@ Content-Type: application/json
"validationErrors": [
{
"field": "parts[0].salary",
"message": "باید مبلغ صحیح و غیرمنفی به تومان باشد."
"message": "باید مبلغ صحیح و غیرمنفی به ریال باشد."
},
{
"field": "parts[0].factorNeeded",
@@ -125,14 +133,14 @@ Content-Type: application/json
```json
{
"statusCode": 400,
"message": "قیمت قطعه 201 باید حداقل ۱۰۰٬۰۰۰ و حداکثر ۱۰٬۰۰۰٬۰۰۰٬۰۰۰ تومان باشد.",
"message": "قیمت قطعه 201 باید حداقل ۱٬۰۰۰٬۰۰۰ و حداکثر ۱۰۰٬۰۰۰٬۰۰۰٬۰۰۰ ریال باشد.",
"error": "EXPERT_REPLY_VALIDATION_ERROR",
"code": "EXPERT_REPLY_VALIDATION_ERROR",
"field": "parts[0].price",
"partId": "201",
"rule": "amount_out_of_range",
"minAmount": 100000,
"maxAmount": 10000000000
"minAmount": 1000000,
"maxAmount": 100000000000
}
```
@@ -142,7 +150,7 @@ Content-Type: application/json
| --- | --- |
| `required` | فیلد لازم ارسال نشده است. |
| `invalid_value` | مقدار enum یا شناسه معتبر نیست. |
| `invalid_amount` | مبلغ، عدد صحیح غیرمنفی به تومان نیست. |
| `invalid_amount` | مبلغ، عدد صحیح غیرمنفی به ریال نیست. |
| `amount_out_of_range` | مبلغ خارج از بازه `minAmount` و `maxAmount` است. |
در صورت `amount_out_of_range`، برای نمایش محدوده از اعداد `minAmount` و `maxAmount` استفاده کنید، نه از parse کردن متن `message`.
+4 -4
View File
@@ -50,7 +50,7 @@ export class PartPricingV2Dto {
@ApiProperty({
enum: TypeOfDamage,
description: "'change' requires price; 'repair' may omit it.",
description: "Replacement requires a part price unless factorNeeded=true. Repairs cannot request a part invoice.",
})
@IsEnum(TypeOfDamage)
typeOfDamage: TypeOfDamage;
@@ -58,11 +58,11 @@ export class PartPricingV2Dto {
@ApiPropertyOptional({
example: "5000000",
description:
"Required for change lines; omitted for repair lines. Every supplied amount must be between 1,000,000 and 100,000,000,000 Rial.",
"Required for priced replacement lines; omit for repair lines and replacement lines awaiting an invoice (factorNeeded=true). Every supplied amount must be between 1,000,000 and 100,000,000,000 Rial.",
})
@ValidateIf(
(part: PartPricingV2Dto) =>
part.typeOfDamage === TypeOfDamage.Change ||
(part.typeOfDamage === TypeOfDamage.Change && part.factorNeeded !== true) ||
(part.price != null &&
(typeof part.price !== 'string' || part.price.trim() !== '')),
)
@@ -106,7 +106,7 @@ export class PartPricingV2Dto {
@ApiProperty({
example: false,
description:
"If true, the owner must upload a repair factor image for this line; expert confirms cost later (validate-factors). Priced lines omit this or set false.",
"Replacement lines only: if true, the owner uploads the part invoice and the expert confirms its cost later (validate-factors). Omit price in this mode. Repair lines must set false.",
})
@IsBoolean()
factorNeeded: boolean;
@@ -84,6 +84,24 @@ const validV2Reply = {
};
describe("ExpertClaimService expert-reply pricing", () => {
it("saves a replacement invoice without a part price and enters the invoice upload workflow", async () => {
const { service, findByIdAndUpdate } = setupSuccessfulV2Submit(BlameRequestType.THIRD_PARTY);
const response = await service.submitExpertReplyV2("v2-claim", { parts: [{ partId: 1, typeOfDamage: TypeOfDamage.Change, salary: "1000000", totalPayment: "1000000", factorNeeded: true, daghi: { option: DaghiOption.NO_VALUE } }] }, { sub: V2_EXPERT_ID, role: RoleEnum.FIELD_EXPERT });
expect(response).toMatchObject({ factorNeeded: true, allPartsFactorNeeded: true, currentStep: "OWNER_UPLOAD_FACTOR_DOCUMENTS" });
const saved = findByIdAndUpdate.mock.calls[0][1]["evaluation.damageExpertReply"].parts[0];
expect(saved.factorNeeded).toBe(true);
expect(saved.price).toBeUndefined();
});
it("a failed invoice/repair submission cannot persist flags or poison a subsequent priced repair", async () => {
const { service, findByIdAndUpdate } = setupSuccessfulV2Submit(BlameRequestType.THIRD_PARTY);
const actor = { sub: V2_EXPERT_ID, role: RoleEnum.FIELD_EXPERT };
await expect(service.submitExpertReplyV2("v2-claim", { parts: [{ ...validV2Reply.parts[0], factorNeeded: true }] }, actor)).rejects.toMatchObject({ response: { field: "parts[0].factorNeeded" } });
expect(findByIdAndUpdate).not.toHaveBeenCalled();
const response = await service.submitExpertReplyV2("v2-claim", validV2Reply, actor);
expect(response.factorNeeded).toBe(false);
expect(findByIdAndUpdate.mock.calls[0][1]["evaluation.damageExpertReply"].parts[0].factorNeeded).toBe(false);
});
it("requires the current car price for a car-body expert reply", async () => {
const { service, findByIdAndUpdate } = setupSuccessfulV2Submit(
BlameRequestType.CAR_BODY,
@@ -3,6 +3,41 @@ import { TypeOfDamage } from "src/Types&Enums/claim-request-management/type-of-d
import { submitExpertReplyValidationPipe } from "./submit-expert-reply-validation.pipe";
describe("submitExpertReplyValidationPipe", () => {
const replacementInvoice = {
partId: 201,
typeOfDamage: TypeOfDamage.Change,
salary: "1000000",
totalPayment: "1000000",
factorNeeded: true,
daghi: { option: "فاقد ارزش" },
};
it("accepts replacement invoices without a numeric part quote", async () => {
const result = await submitExpertReplyValidationPipe.transform(
{ parts: [replacementInvoice] },
{ type: "body", metatype: SubmitExpertReplyV2Dto },
);
expect(result.parts[0].factorNeeded).toBe(true);
expect(result.parts[0].price).toBeUndefined();
});
it.each([{ factorNeeded: false }, { price: "factor" }, { price: "فاکتور" }])(
"continues rejecting absent priced quotes and nonnumeric price markers: %j",
async (invalid) => {
await expect(
submitExpertReplyValidationPipe.transform(
{ parts: [{ ...replacementInvoice, ...invalid }] },
{ type: "body", metatype: SubmitExpertReplyV2Dto },
),
).rejects.toMatchObject({
response: {
validationErrors: expect.arrayContaining([
expect.objectContaining({ field: "parts[0].price" }),
]),
},
});
},
);
it("converts DTO validation failures into Persian, field-addressable errors", async () => {
await expect(
submitExpertReplyValidationPipe.transform(
@@ -61,7 +96,7 @@ describe("submitExpertReplyValidationPipe", () => {
validationErrors: expect.arrayContaining([
{
field: "parts[0].salary",
message: "باید مبلغ صحیح و غیرمنفی به تومان باشد.",
message: "باید مبلغ صحیح و غیرمنفی به ریال باشد.",
},
]),
},
@@ -18,7 +18,7 @@ const constraintMessages: Record<string, string> = {
isInt: "باید یک عدد صحیح باشد.",
isEnum: "مقدار واردشده معتبر نیست.",
nestedValidation: "اطلاعات این بخش معتبر نیست.",
isMoneyAmountString: "باید مبلغ صحیح و غیرمنفی به تومان باشد.",
isMoneyAmountString: "باید مبلغ صحیح و غیرمنفی به ریال باشد.",
};
function flattenValidationErrors(
@@ -31,11 +31,16 @@ function flattenValidationErrors(
? `${parentPath}[${error.property}]`
: `${parentPath}.${error.property}`
: error.property;
const ownErrors = Object.keys(error.constraints ?? {}).map((constraint) => ({
field,
message: constraintMessages[constraint] ?? "مقدار واردشده معتبر نیست.",
}));
return [...ownErrors, ...flattenValidationErrors(error.children ?? [], field)];
const ownErrors = Object.keys(error.constraints ?? {}).map(
(constraint) => ({
field,
message: constraintMessages[constraint] ?? "مقدار واردشده معتبر نیست.",
}),
);
return [
...ownErrors,
...flattenValidationErrors(error.children ?? [], field),
];
});
}
+34
View File
@@ -7,6 +7,40 @@ import { TypeOfDamage } from "src/Types&Enums/claim-request-management/type-of-d
import { DaghiOption } from "src/Types&Enums/claim-request-management/daghi-option.enum";
describe("getExpertReplyPricingValidationError", () => {
const invoice = {
partId: 201,
typeOfDamage: TypeOfDamage.Change,
factorNeeded: true,
salary: "1000000",
totalPayment: "1000000",
daghi: { option: DaghiOption.NO_VALUE },
};
it("allows replacement invoices without a part price while validating known labor/total", () => {
expect(
getExpertReplyPricingValidationError([invoice], {
locale: "fa",
enforceAmountBounds: true,
}),
).toBeNull();
expect(
getExpertReplyPricingValidationError([{ ...invoice, salary: "bad" }], {
locale: "fa",
enforceAmountBounds: true,
}),
).toMatchObject({ field: "parts[0].salary" });
});
it("rejects repair plus invoice and non-boolean invoice flags", () => {
for (const part of [
{ ...invoice, typeOfDamage: TypeOfDamage.Repair },
{ ...invoice, factorNeeded: "true" },
])
expect(
getExpertReplyPricingValidationError([part], { locale: "fa" }),
).toMatchObject({
field: "parts[0].factorNeeded",
rule: "invalid_value",
});
});
it("rejects a blank pricing line", () => {
expect(
getExpertReplyPricingValidationError([
+35 -18
View File
@@ -5,6 +5,7 @@ import { parseMoneyAmountToman } from "src/utils/unicode-digits";
type ExpertReplyPricingPart = {
partId?: unknown;
typeOfDamage?: unknown;
factorNeeded?: unknown;
price?: unknown;
salary?: unknown;
totalPayment?: unknown;
@@ -20,11 +21,7 @@ export type ExpertReplyPricingValidationError = {
code: "EXPERT_REPLY_VALIDATION_ERROR";
field: string;
partId?: string | number;
rule:
| "required"
| "invalid_value"
| "invalid_amount"
| "amount_out_of_range";
rule: "required" | "invalid_value" | "invalid_amount" | "amount_out_of_range";
minAmount?: number;
maxAmount?: number;
};
@@ -102,6 +99,25 @@ export function getExpertReplyPricingValidationError(
);
}
if (part.factorNeeded != null && typeof part.factorNeeded !== "boolean") {
return localizedError(
"وضعیت نیاز به فاکتور باید درست یا نادرست باشد.",
`parts[${index}].factorNeeded`,
"invalid_value",
String(part.partId),
);
}
if (
part.typeOfDamage === TypeOfDamage.Repair &&
part.factorNeeded === true
) {
return localizedError(
"برای قطعه تعمیری نمی‌توان درخواست فاکتور قطعه ثبت کرد.",
`parts[${index}].factorNeeded`,
"invalid_value",
String(part.partId),
);
}
const daghi = part.daghi;
if (
part.typeOfDamage === TypeOfDamage.Change &&
@@ -125,13 +141,12 @@ export function getExpertReplyPricingValidationError(
(typeof part.price !== "string" || part.price.trim() !== "");
const amountIsValid = (amount: number | null) => amount !== null;
const priceIsRequired = part.typeOfDamage === TypeOfDamage.Change;
const priceIsRequired =
part.typeOfDamage === TypeOfDamage.Change && part.factorNeeded !== true;
const requiredAmountFields: Array<[
"price" | "salary" | "totalPayment",
number | null,
boolean,
]> = [
const requiredAmountFields: Array<
["price" | "salary" | "totalPayment", number | null, boolean]
> = [
["price", price, priceIsRequired || hasPrice],
["salary", salary, true],
["totalPayment", totalPayment, true],
@@ -160,11 +175,13 @@ export function getExpertReplyPricingValidationError(
}
if (options.enforceAmountBounds) {
const monetaryFields: Array<[
"price" | "salary" | "totalPayment" | "daghi.price",
number | null,
boolean,
]> = [
const monetaryFields: Array<
[
"price" | "salary" | "totalPayment" | "daghi.price",
number | null,
boolean,
]
> = [
["price", price, priceIsRequired || hasPrice],
["salary", salary, true],
["totalPayment", totalPayment, true],
@@ -192,7 +209,7 @@ export function getExpertReplyPricingValidationError(
? "مبلغ کل"
: "قیمت داغی";
return localizedError(
`${fieldName} قطعه ${String(part.partId)} باید حداقل ${toPersianAmount(EXPERT_REPLY_MIN_AMOUNT_TOMAN)} و حداکثر ${toPersianAmount(EXPERT_REPLY_MAX_AMOUNT_TOMAN)} تومان باشد.`,
`${fieldName} قطعه ${String(part.partId)} باید حداقل ${toPersianAmount(EXPERT_REPLY_MIN_AMOUNT_TOMAN)} و حداکثر ${toPersianAmount(EXPERT_REPLY_MAX_AMOUNT_TOMAN)} ریال باشد.`,
`parts[${index}].${field}`,
"amount_out_of_range",
String(part.partId),
@@ -210,7 +227,7 @@ export function getExpertReplyPricingValidationError(
) {
if (options.locale === "fa") {
return localizedError(
`قیمت داغی قطعه ${String(part.partId)} باید به‌صورت مبلغ صحیح و غیرمنفی (تومان) وارد شود.`,
`قیمت داغی قطعه ${String(part.partId)} باید به‌صورت مبلغ صحیح و غیرمنفی (ریال) وارد شود.`,
`parts[${index}].daghi.price`,
"invalid_amount",
String(part.partId),