codex/team-base-04-line-total-v2 #46
4 changed files with 158 additions and 2 deletions
|
|
@ -17,8 +17,11 @@
|
|||
|---|---|---|---|---|---|
|
||||
| H15 | root-only drain Woo hook | codex/team-base-01-woocommerce-root-commit | 15fd8509 | ۲۰۲۶-۱۱-۰۶ | ✅ merge شده (#42) |
|
||||
| P01 | تفکیک cost_price | codex/team-base-02-cost-currency-basis | 1a003e17 | ۲۰۲۶-۱۱-۰۶ | ✅ merge شده (#43) |
|
||||
| C04 | حفظ صفر معلوم پس از لغو تنها حوالهٔ خروج | codex/team-base-03-zero-cost-cancel | 4867aaa3586c62794746c723c1cc4df61c19c9ad | ۲۰۲۶-۱۱-۱۱ | 🟢 PR ارسال شد |
|
||||
| C04 | حفظ صفر معلوم پس از لغو تنها حوالهٔ خروج | codex/team-base-03-zero-cost-cancel | 4867aaa3586c62794746c723c1cc4df61c19c9ad | ۲۰۲۶-۱۱-۱۱ | ✅ merge شده (#45) |
|
||||
| H35 | تخصیص هزینهٔ هر حواله برای لغو جزئیِ مبالغ متفاوت | — | — | — | ⏳ در انتظار (وابسته به فاز ۲ Native) |
|
||||
| H36 | ناسازگاری گرد کردن line_total در Mapper ووکامرس | — | — | — | ⏳ در انتظار |
|
||||
| H23 | اعتبارسنجی مبلغ خط فاکتور | codex/team-base-04-line-total-v2 | f35b3eff0f57f4752c5e0656b575cefe8d0e6d67 | ۲۰۲۶-۱۱-۱۱ | 🟢 PR ارسال شد |
|
||||
| H37 | تطبیق line_total با تخصیص تخفیف کلی در CREATE/UPDATE | — | — | — | ⏳ در انتظار |
|
||||
|
||||
## مرحلهٔ ۰۱ — H15: زمان ارسال موجودی ووکامرس
|
||||
|
||||
|
|
@ -87,6 +90,10 @@ 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 نبود.
|
||||
- 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 انجام دهد.
|
||||
- H21: پارامتر `allow_custom_line_total` به H21 موکول است و در H23 اضافه نمیشود.
|
||||
- ۸۹۴ آزمون تاریخی Unified، نتیجهٔ این شاخه نیستند و این مرحله حفظ/عبور آن مجموعه را ادعا نمیکند.
|
||||
- تست H15 روی Session واقعی SQLite و مرز جایگزینشدهٔ ارسال است؛ اجرای جدید PostgreSQL، Woo فعال، HTTP یا worker کامل انجام نشده است. proof تاریخی PostgreSQL در شاخهٔ قبلی، آزمون نسخهٔ ترکیبی امروز محسوب نمیشود.
|
||||
- صف حافظهای همچنان outbox پایدار نیست؛ توقف فرایند پس از commit و پیش از ارسال میتواند پیام را از دست بدهد. این مسئلهٔ مستقل در H15 بازطراحی نشده است.
|
||||
|
|
@ -98,3 +105,4 @@ python -m pytest -q -p no:cacheprovider tests/test_invoice_cost_currency_basis.p
|
|||
- ۲۰۲۶-۱۱-۰۶: مبنا به کد رسمی تیم تغییر کرد؛ master محلی تا `2b5c6a24` fast-forward شد. H15 بهعنوان اولین اصلاح مستقل با بازتولید قبل و ۱۵ آزمون موفق پس از اصلاح منتقل شد. شاخهٔ Unified قدیمی و تستهای آن تغییر نکردند.
|
||||
- ۲۰۲۶-۱۱-۰۷: H15 در `master` merge شد (#42). P01 (`cost_currency_basis` برای `cost_price`) پس از حل تداخل همین سند پیشرفت در `master` merge شد (#43).
|
||||
- ۲۰۲۶-۱۱-۱۱: C04 برای تکخروج اصلاح شد. H35 در C04 کشف شد؛ با معرفی `VariantCostConsumption` در فاز ۲ Native حل میشود. تا آن زمان، GL برای چند-خروجی همان رفتار قبلی را دارد؛ تغییر نمیکند.
|
||||
- ۲۰۲۶-۱۱-۱۱: H23 با اعتبارسنجی مبلغ و معافیت تخفیف کلی ثبت شد. H37 کشف شد. H36 باز است و مانع این مرحله نیست.
|
||||
|
|
|
|||
56
hesabixAPI/app/services/invoice_line_total_guard.py
Normal file
56
hesabixAPI/app/services/invoice_line_total_guard.py
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
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_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 _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
|
||||
places = currency.decimal_places
|
||||
quant = decimal_places_to_quant(places if places is not None else 2)
|
||||
for index, line in enumerate(lines, 1):
|
||||
info = extra_info_dict(line.get("extra_info"))
|
||||
sent = info.get("line_total", line.get("line_total"))
|
||||
if sent is None:
|
||||
continue
|
||||
try:
|
||||
quantity = Decimal(str(line.get("quantity") or 0))
|
||||
price, discount, tax = (
|
||||
Decimal(str(info.get(key, line.get(key)) or 0))
|
||||
for key in ("unit_price", "line_discount", "tax_amount")
|
||||
)
|
||||
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
|
||||
except DecimalException:
|
||||
pass
|
||||
raise ApiError(
|
||||
"INCONSISTENT_LINE_TOTAL",
|
||||
"مبلغ ردیف با تعداد، قیمت واحد، تخفیف و مالیات آن سازگار نیست",
|
||||
http_status=422, details={"line_index": index},
|
||||
)
|
||||
|
|
@ -36,6 +36,7 @@ from app.core.responses import ApiError, success_response
|
|||
from app.core.transaction_lock import acquire_transaction_lock
|
||||
from app.services.document_monetization_service import ensure_document_policy_allows_creation
|
||||
from app.services.credit_service import get_business_credit_settings
|
||||
from app.services.invoice_line_total_guard import validate_invoice_line_totals
|
||||
from app.services.invoice_unit_conversion_service import (
|
||||
INVENTORY_QUANTITY_UNIT_MAIN,
|
||||
extra_info_dict,
|
||||
|
|
@ -6863,6 +6864,7 @@ 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)
|
||||
_apply_expired_sale_confirm_permission(
|
||||
invoice_type,
|
||||
lines_input,
|
||||
|
|
@ -8596,7 +8598,6 @@ def update_invoice(
|
|||
from app.services.tax_reference_service import validate_invoice_type_change_for_tax
|
||||
|
||||
validate_invoice_type_change_for_tax(document, _old_document_type, inv_type)
|
||||
document.document_type = inv_type
|
||||
data["invoice_type"] = inv_type
|
||||
|
||||
if _invoice_payload_preserves_invoice_body(
|
||||
|
|
@ -8625,6 +8626,9 @@ 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)
|
||||
if inv_type != _old_document_type:
|
||||
document.document_type = inv_type
|
||||
document.document_date = document_date
|
||||
document.currency_id = int(currency_id)
|
||||
# بهروزرسانی وضعیت پیشفاکتور
|
||||
|
|
|
|||
88
hesabixAPI/tests/test_invoice_line_total_h23.py
Normal file
88
hesabixAPI/tests/test_invoice_line_total_h23.py
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
from copy import deepcopy
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.schema import CreateTable
|
||||
|
||||
from adapters.db import models
|
||||
from adapters.db.models.business import BusinessField, BusinessType
|
||||
from adapters.db.models.document_monetization import DocumentUsagePolicy
|
||||
from app.core import cache
|
||||
from app.core.responses import ApiError
|
||||
from app.services.invoice_service import create_invoice, update_invoice
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db(monkeypatch):
|
||||
for key, value in {"_redis_config": {"enabled": False}, "_redis_config_expires_at": float("inf"),
|
||||
"_redis_retry_at": float("inf"), "_redis_client": None, "_cache_service": None}.items():
|
||||
monkeypatch.setattr(cache, key, value)
|
||||
engine = create_engine("sqlite://")
|
||||
names = ("businesses", "currencies", "fiscal_years", "products", "documents", "document_lines",
|
||||
"invoice_item_lines", "document_usage_policies", "invoice_item_line_variant_allocations",
|
||||
"invoice_item_line_lot_allocations", "users", "accounts", "document_invoice_tag_links", "document_invoice_tags", "fa_assets")
|
||||
day = date(2026, 11, 11)
|
||||
with Session(engine, autoflush=False) as db:
|
||||
for name in names:
|
||||
db.execute(CreateTable(models.Base.metadata.tables[name]))
|
||||
db.add_all([
|
||||
models.Business(id=1, name="H23", owner_id=1, default_currency_id=1,
|
||||
business_type=BusinessType.SHOP, business_field=BusinessField.TRADING),
|
||||
models.FiscalYear(id=1, business_id=1, title="H23", start_date=day, end_date=day, is_last=True),
|
||||
DocumentUsagePolicy(business_id=1, policy_type="free", title="Test", is_active=True),
|
||||
*(models.Currency(id=i, name=str(i), title=str(i), symbol="X", code=f"X{i}", decimal_places=dp)
|
||||
for i, dp in [(1, 2), (2, 8)]),
|
||||
*(models.Product(id=i, business_id=1, code=str(i), name=str(i), track_inventory=False,
|
||||
main_unit="carton", secondary_unit="each", unit_conversion_factor=20) for i in (1, 2)),
|
||||
])
|
||||
db.commit()
|
||||
yield db
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def line(qty, price, total, product=1):
|
||||
return {"product_id": product, "quantity": qty, "extra_info": {
|
||||
"unit": "each", "unit_price": price, "line_total": total}}
|
||||
|
||||
|
||||
def create(db, lines, *, currency=1, discount=0):
|
||||
db.get(models.Business, 1).default_currency_id = currency
|
||||
payload = {"invoice_type": "invoice_sales", "document_date": "2026-11-11", "currency_id": currency,
|
||||
"code": "H23", "is_proforma": True, "global_discount_amount": discount,
|
||||
"extra_info": {"person_id": 1, "post_inventory": False}, "lines": deepcopy(lines)}
|
||||
return create_invoice(db, 1, 1, payload, commit=False)["data"]["id"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("qty,price,total,currency,discount", [
|
||||
(2, 250, 250, 1, 0), (2, 250, 500, 1, 0), (1, 100, 90, 1, 10), (7, 14.29, 100, 1, 0),
|
||||
(100, 0.07, 7.000000000000001, 1, 0),
|
||||
(3, "33333333.33666667", "100000000.01", 2, 0),
|
||||
])
|
||||
def test_create_line_totals(db, qty, price, total, currency, discount):
|
||||
if total == 250:
|
||||
with pytest.raises(ApiError) as error:
|
||||
create(db, [line(qty, price, total)], currency=currency)
|
||||
assert (error.value.code, error.value.status_code) == ("INCONSISTENT_LINE_TOTAL", 422)
|
||||
assert db.query(models.Document).count() == 0
|
||||
else:
|
||||
assert create(db, [line(qty, price, total)], currency=currency, discount=discount)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["reorder", "append", "unchanged", "discount", "bad_append"])
|
||||
def test_update_line_totals(db, mode):
|
||||
first, second = line(2, 250, 500), line(2, 250.01, 500.02, 2)
|
||||
original = [line(1, 100, 90)] if mode == "discount" else [first]
|
||||
did = create(db, [first, second] if mode == "reorder" else original, discount=10 if mode == "discount" else 0)
|
||||
db.commit()
|
||||
lines = {"reorder": [line(2, 250.01, 499.98, 2), first], "append": [first, line(3, 250, 750)],
|
||||
"bad_append": [first, line(3, 250, 500)]}.get(mode, original)
|
||||
data = {"lines": lines, **({"code": "H23-EDIT"} if mode == "discount" else {})}
|
||||
if mode in {"reorder", "bad_append"}:
|
||||
with pytest.raises(ApiError) as error:
|
||||
update_invoice(db, did, 1, data)
|
||||
assert (error.value.code, error.value.status_code) == ("INCONSISTENT_LINE_TOTAL", 422)
|
||||
else:
|
||||
result = update_invoice(db, did, 1, data)
|
||||
assert len(result["product_lines"]) == len(lines)
|
||||
Loading…
Reference in a new issue