From 40fcf228bc78a01de8f4d2a17b881fe0d36e5bec Mon Sep 17 00:00:00 2001 From: Seyyed Date: Thu, 12 Nov 2026 13:42:27 +0330 Subject: [PATCH] fix(invoices): validate line totals with global discounts (H37) --- ...PRODUCT_VARIANTS_TEAM_BASED_PROGRESS.fa.md | 8 +- .../app/services/invoice_line_total_guard.py | 56 ++++---- hesabixAPI/app/services/invoice_service.py | 21 ++- .../tests/test_invoice_global_discount_h37.py | 125 ++++++++++++++++++ 4 files changed, 179 insertions(+), 31 deletions(-) create mode 100644 hesabixAPI/tests/test_invoice_global_discount_h37.py diff --git a/docs/PRODUCT_VARIANTS_TEAM_BASED_PROGRESS.fa.md b/docs/PRODUCT_VARIANTS_TEAM_BASED_PROGRESS.fa.md index c36bb183..f8e29635 100644 --- a/docs/PRODUCT_VARIANTS_TEAM_BASED_PROGRESS.fa.md +++ b/docs/PRODUCT_VARIANTS_TEAM_BASED_PROGRESS.fa.md @@ -19,9 +19,9 @@ | P01 | تفکیک cost_price | codex/team-base-02-cost-currency-basis | 1a003e17 | ۲۰۲۶-۱۱-۰۶ | ✅ merge شده (#43) | | C04 | حفظ صفر معلوم پس از لغو تنها حوالهٔ خروج | codex/team-base-03-zero-cost-cancel | 4867aaa3586c62794746c723c1cc4df61c19c9ad | ۲۰۲۶-۱۱-۱۱ | ✅ merge شده (#45) | | H35 | تخصیص هزینهٔ هر حواله برای لغو جزئیِ مبالغ متفاوت | — | — | — | ⏳ در انتظار (وابسته به فاز ۲ Native) | -| H36 | ناسازگاری گرد کردن line_total در Mapper ووکامرس | — | — | — | ⏳ در انتظار | +| H36 | ناسازگاری گرد کردن line_total در Mapper ووکامرس | — | — | — | ⏳ نیازمند تعیین نمایش ده‌دهی و مبلغ مرجع | | H23 | اعتبارسنجی مبلغ خط فاکتور | codex/team-base-04-line-total-v2 | f35b3eff0f57f4752c5e0656b575cefe8d0e6d67 | ۲۰۲۶-۱۱-۱۱ | ✅ merge شده (#46) | -| H37 | تطبیق line_total با تخصیص تخفیف کلی در CREATE/UPDATE | — | — | — | ⏳ در انتظار | +| H37 | تطبیق line_total با تخصیص تخفیف کلی در CREATE/UPDATE | codex/team-base-11-line-total-validation | — | ۲۰۲۶-۱۱-۱۲ | اصلاح و آزمون‌شده در شاخه | | H10 | تاریخ مالی سفارش ووکامرس و سال مالی فعال | codex/team-base-06-financial-date | b2e9b9fb | ۲۰۲۶-۱۱-۱۱ | ✅ characterization، سیاست فعلی = keep در افزونه، validation سروری در فاز ۲ | | H30 | قرارداد net باشگاه با GL | master | — | ۲۰۲۶-۱۱-۱۱ | ✅ کوپن و امتیاز net را شامل مالیات می‌نویسند؛ payable با دریافتنی یکی شد | | H38 | نمایش شخص و مبنای امتیاز net+tax | master | — | ۲۰۲۶-۱۱-۱۱ | ✅ جمع نمایشی و total_with_tax از gross−discount+tax است، نه net+tax | @@ -106,9 +106,9 @@ python -m pytest -q -p no:cacheprovider tests/test_invoice_cost_currency_basis.p ## محدودیت‌ها -- H36: تلرانس بر اساس تعداد ارسالی هر سه نمونهٔ عملی بررسی‌شده را می‌پذیرد. بازپخش محاسبهٔ Mapper برای ۷ واحد، مبلغ خط 999999999.99 و ارز ۸رقمی، اختلاف 1E-7 را در برابر تلرانس 7E-8 نشان داد. بررسی اصلاح Mapper در PHP یا محاسبهٔ مبلغ خط در backend در H36 باز است. این بازپخش، اجرای PHP نبود. +- H36: **باز در مبنای `2354c27d`.** بازپخش محاسبات PHP Mapper با float و سریال‌سازی عددی Python برای تعداد ۷ و جمع `999999999.99`، قیمت `142857142.8557143` و اختلاف `1E-7` در برابر تلرانس `7E-8` را نشان داد. دو float مجاور نیز بیرون تلرانس‌اند. WordPress و PHP اجرا نشدند. رفع نیازمند تعیین مرجع مبلغ سفارش و نمایش ده‌دهی دقیق در payload، شامل مسیر تعدیل گردکردن است. تلرانس H23 تغییر نکرد. - H23: در CREATE و بازنویسی UPDATE، مبلغ ارسالی خط با Decimal و تلرانس تعداد ارسالی در دقت ارز بررسی می‌شود. شاخه به فورک ارسال شد و ۹۷ آزمون مرتبط در SQLite پاس شدند. PostgreSQL اجرا نشد. اجرای کامل با سقف ۳۰۰ ثانیه در `test_ai_channel_stream.py` متوقف شد. -- H37: تخفیف کلی سربرگ به خطوط تخصیص می‌یابد و line_total نهایی با q × p − line_discount تفاوت دارد. در UPDATE تخفیف با ارسال خطوط در مسیر بازنویسی دوباره محاسبه می‌شود. تغییر صرف فیلد تخفیف بالادست در مسیر بدنهٔ ثابت ممکن است نادیده گرفته شود. H23 در حضور تخفیف در payload یا DB، اعتبارسنجی را اجرا نمی‌کند. مسیر فعلی UPDATE با بدنهٔ ثابت حفظ شده است. H37 باید تطبیق مبلغ خط با تخصیص را در CREATE و UPDATE انجام دهد. +- H37: **اصلاح در شاخهٔ `codex/team-base-11-line-total-validation`.** CREATE و بازنویسی UPDATE مبلغ قبل از تخصیص را با فرمول H23 می‌پذیرند. برای مبلغ تخصیص‌یافته، همان تخصیص‌دهندهٔ سرور روی کپی ورودی پیش از تغییر سند اجرا می‌شود. مبلغی که با هیچ‌کدام سازگار نباشد، ۴۲۲ می‌گیرد. مسیر بدنهٔ ثابت و فقط پرداخت همچنان از مسیر فعلی می‌گذرد. تست SQLite ارسال ۱۰۰ و ۹۰ با تخفیف ۱۰، باقیماندهٔ گردکردن چندخطی و رد مبلغ ناسازگار را پوشش می‌دهد. - H21: پارامتر `allow_custom_line_total` به H21 موکول است و در H23 اضافه نمی‌شود. - ۸۹۴ آزمون تاریخی Unified، نتیجهٔ این شاخه نیستند و این مرحله حفظ/عبور آن مجموعه را ادعا نمی‌کند. - تست H15 روی Session واقعی SQLite و مرز جایگزین‌شدهٔ ارسال است؛ اجرای جدید PostgreSQL، Woo فعال، HTTP یا worker کامل انجام نشده است. proof تاریخی PostgreSQL در شاخهٔ قبلی، آزمون نسخهٔ ترکیبی امروز محسوب نمی‌شود. diff --git a/hesabixAPI/app/services/invoice_line_total_guard.py b/hesabixAPI/app/services/invoice_line_total_guard.py index 96053bc7..476d9063 100644 --- a/hesabixAPI/app/services/invoice_line_total_guard.py +++ b/hesabixAPI/app/services/invoice_line_total_guard.py @@ -2,35 +2,34 @@ from decimal import Decimal, DecimalException from app.core.responses import ApiError from app.services.currency_quant import decimal_places_to_quant +from app.services.invoice_global_discount_service import apply_global_discount_to_invoice_payload from app.services.invoice_unit_conversion_service import extra_info_dict -def _positive(value): - try: - number = Decimal(str(value or 0)) - return number.is_finite() and number > 0 - except DecimalException: - return False +def _allocated_line_totals(db, business_id, invoice_type, data, lines, prepare_discount_lines): + # The allocator replaces extra_info on its inputs. Preview on copies so the + # validation happens before document/GL changes and saving still applies it once. + if ( + not any(key in data for key in ("global_discount_amount", "global_discount_percent")) + and not isinstance(extra_info_dict(data.get("extra_info")).get("global_discount"), dict) + ): + return [] + preview = dict(data) + preview_lines = [dict(line) for line in lines] + if prepare_discount_lines is not None: + prepare_discount_lines(preview_lines) + if not apply_global_discount_to_invoice_payload(db, business_id, invoice_type, preview_lines, preview): + return [] + return [Decimal(str(line["extra_info"]["line_total"])) for line in preview_lines] -def _has_global_discount(payload): - keys = ("header_discount", "global_discount_amount", "global_discount_percent") - if any(_positive(payload.get(key)) for key in keys): - return True - discount = extra_info_dict(payload.get("extra_info")).get("global_discount") - if not isinstance(discount, dict): - return _positive(discount) - return _positive(discount.get("amount")) or _positive(discount.get("value")) - - -def validate_invoice_line_totals(data, lines, currency, *, document=None): - """Validate client amounts before an invoice is written; H37 owns global discount.""" - stored = {"extra_info": getattr(document, "extra_info", None), - "global_discount_amount": getattr(document, "global_discount_amount", None)} - if any(_has_global_discount(entry) for entry in (data, stored, *lines)): - return +def validate_invoice_line_totals( + data, lines, currency, *, db, business_id, invoice_type, prepare_discount_lines=None, +): + """Accept the line before header discount or as calculated by the allocator.""" places = currency.decimal_places quant = decimal_places_to_quant(places if places is not None else 2) + allocated = None for index, line in enumerate(lines, 1): info = extra_info_dict(line.get("extra_info")) sent = info.get("line_total", line.get("line_total")) @@ -44,9 +43,16 @@ def validate_invoice_line_totals(data, lines, currency, *, document=None): ) supplied = Decimal(str(sent)) expected = quantity * price - discount + tax - if (all(value.is_finite() for value in (supplied, expected, quantity)) - and abs(supplied - expected) <= max(abs(quantity) * quant, quant)): - continue + if all(value.is_finite() for value in (supplied, expected, quantity)): + tolerance = max(abs(quantity) * quant, quant) + if abs(supplied - expected) <= tolerance: + continue + if allocated is None: + allocated = _allocated_line_totals( + db, business_id, invoice_type, data, lines, prepare_discount_lines, + ) + if allocated and abs(supplied - allocated[index - 1]) <= tolerance: + continue except DecimalException: pass raise ApiError( diff --git a/hesabixAPI/app/services/invoice_service.py b/hesabixAPI/app/services/invoice_service.py index 32af77b0..acb3b17a 100755 --- a/hesabixAPI/app/services/invoice_service.py +++ b/hesabixAPI/app/services/invoice_service.py @@ -6902,7 +6902,13 @@ def create_invoice( lines_input: List[Dict[str, Any]] = list(data.get("lines") or []) if not isinstance(lines_input, list) or len(lines_input) == 0: raise ApiError("LINES_REQUIRED", "At least one line is required", http_status=400) - validate_invoice_line_totals(data, lines_input, currency) + validate_invoice_line_totals( + data, lines_input, currency, db=db, business_id=business_id, invoice_type=invoice_type, + prepare_discount_lines=( + _canonicalize_quick_sale_line_amounts + if extra_info_dict(data.get("extra_info")).get("quick_sale") is True else None + ), + ) _apply_expired_sale_confirm_permission( invoice_type, lines_input, @@ -8669,7 +8675,18 @@ def update_invoice( if not currency: raise ApiError("CURRENCY_NOT_FOUND", "Currency not found", http_status=404) - validate_invoice_line_totals(data, data.get("lines") or [], currency, document=document) + discount_input = data + if not isinstance(data.get("extra_info"), dict): + discount_input = { + **data, + "extra_info": _sanitize_extra_info_for_invoice_type_change( + document.extra_info or {}, inv_type, _old_document_type, + ), + } + validate_invoice_line_totals( + discount_input, data.get("lines") or [], currency, + db=db, business_id=int(document.business_id), invoice_type=inv_type, + ) if inv_type != _old_document_type: document.document_type = inv_type document.document_date = document_date diff --git a/hesabixAPI/tests/test_invoice_global_discount_h37.py b/hesabixAPI/tests/test_invoice_global_discount_h37.py new file mode 100644 index 00000000..99af8985 --- /dev/null +++ b/hesabixAPI/tests/test_invoice_global_discount_h37.py @@ -0,0 +1,125 @@ +from copy import deepcopy +from decimal import Decimal + +import pytest + +from adapters.db import models +from adapters.db.models.invoice_item_line import InvoiceItemLine +from app.core.responses import ApiError +from app.services.invoice_service import create_invoice, update_invoice +from tests.test_invoice_line_total_h23 import create, db as db, line +from tests.test_invoice_net_contract_h30 import db as finalized_db + +D = Decimal + + +def _stored(db, document_id): + doc = db.get(models.Document, document_id) + lines = db.query(InvoiceItemLine).filter_by(document_id=document_id).order_by(InvoiceItemLine.id) + print(f"stored totals for {doc.code}: {doc.extra_info['totals']}") + return [ + (D(str(row.extra_info["line_total"])), D(str(row.extra_info.get("tax_amount", 0)))) + for row in lines + ], doc.extra_info["totals"] + + +@pytest.mark.parametrize("sent", [100, 90]) +def test_create_accepts_pre_discount_and_server_allocated_amount(db, sent): + did = create(db, [line(1, 100, sent)], discount=10) + assert _stored(db, did) == ([(D(90), D(0))], {"gross": 100, "discount": 10, "tax": 0, + "net": 90, "adjustments_net": 0, "adjustments_tax": 0}) + + +def test_create_rejects_mismatched_line_before_writing(db): + with pytest.raises(ApiError) as error: + create(db, [line(1, 100, 91)], discount=10) + assert (error.value.code, error.value.status_code) == ("INCONSISTENT_LINE_TOTAL", 422) + assert db.query(models.Document).count() == 0 + assert db.query(models.DocumentLine).count() == 0 + + +@pytest.mark.parametrize("discount_payload", [{"header_discount": 10}, {"global_discount_amount": 10}]) +def test_discount_fields_do_not_exempt_unsupported_invoice_type(db, discount_payload): + payload = {"invoice_type": "invoice_waste", "currency_id": 1, "code": "NO-DISCOUNT", "is_proforma": True, "lines": [line(1, 100, 91)], + **discount_payload} + with pytest.raises(ApiError) as error: + create_invoice(db, 1, 1, payload, commit=False) + assert (error.value.code, error.value.status_code) == ("INCONSISTENT_LINE_TOTAL", 422) + assert db.query(models.Document).count() == 0 + + +def test_update_validates_before_mutation_and_accepts_allocated_total(db): + did = create(db, [line(1, 100, 100)], discount=10) + db.commit() + doc = db.get(models.Document, did) + original = _stored(db, did) + original_date = doc.document_date + with pytest.raises(ApiError) as error: + update_invoice(db, did, 1, {"document_date": "2026-11-12", "lines": [line(1, 100, 91)]}) + assert (error.value.code, error.value.status_code) == ("INCONSISTENT_LINE_TOTAL", 422) + assert doc.document_date == original_date + assert doc.code == "H23" + assert _stored(db, did) == original + + update_invoice(db, did, 1, {"code": "H37-EDIT", "lines": [line(1, 100, 90)]}) + assert doc.code == "H37-EDIT" + assert _stored(db, did) == original + + +def test_uses_server_allocation_rounding_remainder_and_tax(db): + items = [line(1, 1, 1.1, product) for product in (1, 2, 2)] + for item in items: + item["extra_info"].update(tax_rate=10, tax_amount=0.1) + did = create(db, items, discount=0.01) + db.commit() + observed, totals = _stored(db, did) + assert observed == [(D("1.09"), D("0.10")), (D("1.10"), D("0.10")), (D("1.10"), D("0.10"))] + assert (totals["discount"], totals["tax"], totals["net"]) == (0.01, 0.3, 3.29) + + wrong = deepcopy(items) + wrong[1]["extra_info"]["line_total"] = 1.07 + with pytest.raises(ApiError) as error: + update_invoice(db, did, 1, {"code": "INVALID", "currency_id": 1, "lines": wrong}) + assert (error.value.code, error.value.status_code) == ("INCONSISTENT_LINE_TOTAL", 422) + assert error.value.detail["error"]["details"]["line_index"] == 2 + assert _stored(db, did) == (observed, totals) + + for item, (total, tax) in zip(items, observed): + item["extra_info"].update(line_total=float(total), tax_amount=float(tax)) + update_invoice(db, did, 1, {"code": "ROUNDTRIP", "currency_id": 1, "lines": items}) + assert _stored(db, did) == (observed, totals) + +def test_finalized_update_rejects_before_rebuilding_receivable(finalized_db): + db = finalized_db + item = line(1, 100, 110) + item["extra_info"].pop("unit") + item["extra_info"].update(tax_rate=10, tax_amount=10) + result = create_invoice(db, 1, 1, { + "invoice_type": "invoice_sales", "document_date": "2026-11-11", "currency_id": 1, + "code": "H37-GL", "global_discount_amount": 10, + "extra_info": {"person_id": 1, "post_inventory": False}, "lines": [item], + }, commit=False) + db.commit() + did = result["data"]["id"] + doc = db.get(models.Document, did) + gl = db.query(models.DocumentLine).filter_by(document_id=did).order_by(models.DocumentLine.id) + + def posted(): + return [(row.id, row.account.code, row.debit, row.credit) for row in gl] + + before = posted() + assert [(code, debit, credit) for _, code, debit, credit in before] == [ + ("10401", 99, 0), ("50001", 0, 100), ("50003", 10, 0), ("20101", 0, 9), + ] + body_before = _stored(db, did) + assert body_before[0] == [(D(99), D(9))] + bad = line(1, 100, 101) + bad["extra_info"].pop("unit") + bad["extra_info"].update(tax_rate=10, tax_amount=10) + with pytest.raises(ApiError) as error: + update_invoice(db, did, 1, {"code": "H37-GL-BAD", "currency_id": 1, "lines": [bad]}) + assert (error.value.code, error.value.status_code) == ("INCONSISTENT_LINE_TOTAL", 422) + assert doc.code == "H37-GL" + assert posted() == before + assert _stored(db, did) == body_before + print(f"persisted GL after rejected update: {posted()}") -- 2.43.0