diff --git a/hesabixAPI/app/services/cross_currency_settlement_service.py b/hesabixAPI/app/services/cross_currency_settlement_service.py index 20f0836f..5278349e 100644 --- a/hesabixAPI/app/services/cross_currency_settlement_service.py +++ b/hesabixAPI/app/services/cross_currency_settlement_service.py @@ -342,6 +342,7 @@ def prepare_standalone_receipt_payment_cross_currency( data: Dict[str, Any], *, is_receipt: bool, + invoice_allocations: dict[int, dict[str, Any]] | None = None, ) -> Dict[str, Any]: """ V2-P4: اگر حساب‌ها با ارز سند (تسویه) فرق دارند، سند را به پایه (E2) بازنویسی می‌کند. @@ -482,6 +483,12 @@ def prepare_standalone_receipt_payment_cross_currency( for i, pl in enumerate(person_lines): if not isinstance(pl, dict): continue + if is_receipt and invoice_allocations is not None: + from app.services.receipt_invoice_allocation_service import capture_invoice_allocation + + allocation = capture_invoice_allocation(db, business_id, settle_cur, pl) + if allocation is not None: + invoice_allocations[i] = allocation native_p = _d(pl.get("amount")) p_base = quantize_money(native_p * r_settle, base_quant, round_on=round_on) extra = dict(pl.get("extra_info") or {}) if isinstance(pl.get("extra_info"), dict) else {} diff --git a/hesabixAPI/app/services/invoice_service.py b/hesabixAPI/app/services/invoice_service.py index 683af23e..84fe90f8 100755 --- a/hesabixAPI/app/services/invoice_service.py +++ b/hesabixAPI/app/services/invoice_service.py @@ -13514,6 +13514,11 @@ def _receipt_amount_for_invoice_balance( receipt: Document, invoice: Document, *, via_person_line: bool, ) -> Decimal: """Prefer explicit receivable allocations in the invoice's currency.""" + from app.services.receipt_invoice_allocation_service import exact_receipt_allocation + + exact = exact_receipt_allocation(receipt, invoice) + if exact is not None: + return exact extra = receipt.extra_info or {} if ( invoice.document_type == INVOICE_SALES diff --git a/hesabixAPI/app/services/receipt_invoice_allocation_service.py b/hesabixAPI/app/services/receipt_invoice_allocation_service.py new file mode 100644 index 00000000..d8662ef3 --- /dev/null +++ b/hesabixAPI/app/services/receipt_invoice_allocation_service.py @@ -0,0 +1,125 @@ +"""Exact invoice-currency shares, independent of rounded base-currency GL.""" +from decimal import Decimal, InvalidOperation +from typing import Any + +from sqlalchemy.orm import Session + +from adapters.db.models.document import Document +from app.core.responses import ApiError + +ALLOCATION_KEY = "receipt_invoice_allocation" +CONTRACT_KEY = "receipt_invoice_allocations_version" + + +def capture_invoice_allocation( + db: Session, business_id: int, currency_id: int, person_line: dict[str, Any], +) -> dict[str, Any] | None: + extra = person_line.get("extra_info") or {} + raw_id = extra.get("invoice_id") + if raw_id is None: + return None + try: + invoice_id = int(raw_id) + person_id = int(person_line.get("person_id")) + amount = Decimal(str(person_line.get("amount"))) + except (TypeError, ValueError, InvalidOperation): + raise ApiError("INVALID_INVOICE_ALLOCATION", "تخصیص فاکتور نامعتبر است", http_status=400) from None + invoice = db.get(Document, invoice_id) + if invoice is not None and invoice.business_id == business_id and invoice.document_type != "invoice_sales": + return None + if ( + invoice is None or invoice.business_id != business_id + or invoice.currency_id != currency_id + or str((invoice.extra_info or {}).get("person_id")) != str(person_id) + or not amount.is_finite() or amount <= 0 + ): + raise ApiError( + "INVALID_INVOICE_ALLOCATION", + "شخص، ارز یا فاکتور تخصیص با دریافت سازگار نیست", http_status=400, + ) + return {"invoice_id": invoice_id, "person_id": person_id, + "currency_id": currency_id, "amount": str(amount)} + + +def preserve_readback_allocations( + db: Session, document: Document, data: dict[str, Any], +) -> dict[int, dict[str, Any]]: + """A base-currency readback can preserve unchanged shares by persisted line ID. + + Changed shares must arrive in settlement currency; rounded GL cannot prove + their original amounts. Client-provided developer data is never consulted. + """ + if (document.developer_settings or {}).get(CONTRACT_KEY) != 1: + return {} + if int(data.get("currency_id") or document.currency_id) != document.currency_id: + return {} + stored = {line.id: line for line in document.lines} + allocations = {} + seen = set() + for index, incoming in enumerate(data.get("person_lines") or []): + invoice_id = (incoming.get("extra_info") or {}).get("invoice_id") + if invoice_id is None: + continue + try: + invoice = db.get(Document, int(invoice_id)) + except (TypeError, ValueError): + raise ApiError("INVALID_INVOICE_ALLOCATION", "شناسه فاکتور نامعتبر است", http_status=400) from None + if invoice is not None and invoice.currency_id == document.currency_id: + allocation = capture_invoice_allocation( + db, document.business_id, document.currency_id, incoming, + ) + if allocation is not None: + allocations[index] = allocation + continue + line = stored.get(incoming.get("id")) + allocation = (line.developer_data or {}).get(ALLOCATION_KEY) if line else None + try: + base_amount = Decimal(str(incoming.get("amount"))) + except InvalidOperation: + raise ApiError( + "INVOICE_ALLOCATION_CURRENCY_REQUIRED", "مبلغ تخصیص نامعتبر است", http_status=400, + ) from None + if ( + not isinstance(allocation, dict) + or str(allocation["invoice_id"]) != str(invoice_id) + or str(allocation["person_id"]) != str(incoming.get("person_id")) + or base_amount != line.credit + or line.id in seen + ): + raise ApiError( + "INVOICE_ALLOCATION_CURRENCY_REQUIRED", + "ویرایش سهم تخصیص باید با مبلغ دقیق در ارز فاکتور ارسال شود", http_status=400, + ) + allocations[index] = dict(allocation) + seen.add(line.id) + return allocations + + +def exact_receipt_allocation(receipt: Document, invoice: Document) -> Decimal | None: + """None selects the legacy reader; zero is authoritative for removed shares.""" + if (receipt.developer_settings or {}).get(CONTRACT_KEY) != 1: + return None + if receipt.document_type != "receipt" or invoice.document_type != "invoice_sales": + return None + total = Decimal(0) + seen = set() + for line in receipt.lines: + allocation = (line.developer_data or {}).get(ALLOCATION_KEY) + if not isinstance(allocation, dict) or line.id in seen: + continue + if ( + receipt.business_id != invoice.business_id + or allocation.get("invoice_id") != invoice.id + or allocation.get("currency_id") != invoice.currency_id + or allocation.get("person_id") != line.person_id + or str(line.person_id) != str((invoice.extra_info or {}).get("person_id")) + or str((line.extra_info or {}).get("invoice_id")) != str(invoice.id) + or line.account is None or line.account.code != "10401" + or line.debit != 0 or line.credit < 0 + ): + continue + amount = Decimal(allocation["amount"]) + if amount.is_finite() and amount > 0: + total += amount + seen.add(line.id) + return total diff --git a/hesabixAPI/app/services/receipt_payment_service.py b/hesabixAPI/app/services/receipt_payment_service.py index 9694238b..930d0a61 100755 --- a/hesabixAPI/app/services/receipt_payment_service.py +++ b/hesabixAPI/app/services/receipt_payment_service.py @@ -29,6 +29,9 @@ from adapters.db.models.fiscal_year import FiscalYear from app.core.responses import ApiError from app.services.document_monetization_service import ensure_document_policy_allows_creation from app.services.document_numbering_service import generate_document_code +from app.services.receipt_invoice_allocation_service import ( + ALLOCATION_KEY, CONTRACT_KEY, preserve_readback_allocations, +) import jdatetime # تنظیم لاگر @@ -431,6 +434,7 @@ def create_receipt_payment( is_receipt = (document_type == DOCUMENT_TYPE_RECEIPT) logger.info(f"آیا دریافت است: {is_receipt}") + invoice_allocations = {} # V2-P4: بازنویسی بین‌ارزی مستقل به ارز پایه (اگر لازم) try: @@ -439,12 +443,14 @@ def create_receipt_payment( ) data = prepare_standalone_receipt_payment_cross_currency( - db, business_id, data, is_receipt=is_receipt + db, business_id, data, is_receipt=is_receipt, + invoice_allocations=invoice_allocations, ) except ApiError: raise except Exception: logger.exception("prepare standalone cross-currency failed") + invoice_allocations.clear() # امکان override نوع حساب طرف‌شخص (دریافتنی/پرداختنی) برای سناریوهایی مثل برگشت فاکتور extra_info_all = data.get("extra_info") or {} @@ -557,6 +563,7 @@ def create_receipt_payment( is_proforma=False, description=data.get("description"), extra_info=data.get("extra_info"), + developer_settings={CONTRACT_KEY: 1} if invoice_allocations else None, project_id=project_id, ) try: @@ -701,7 +708,8 @@ def create_receipt_payment( amount = Decimal(str(person_line.get("amount", 0))) logger.info(f"مبلغ: {amount}") - if amount <= 0: + # A positive native share can round to zero in base; retain its metadata. + if amount <= 0 and i not in invoice_allocations: logger.warning(f"خط شخص {i+1}: مبلغ صفر یا منفی، رد می‌شود") continue @@ -762,7 +770,8 @@ def create_receipt_payment( debit=debit_amount, credit=credit_amount, description=description, - extra_info=line_extra_info + extra_info=line_extra_info, + developer_data={ALLOCATION_KEY: invoice_allocations[i]} if i in invoice_allocations else None, ) logger.info(f"خط سند شخص ایجاد شد: {line}") db.add(line) @@ -1869,18 +1878,24 @@ def update_receipt_payment( # 2) اعتبارسنجی ورودی‌ها (مشابه create) parsed_doc_date = _parse_iso_date(data.get("document_date", document.document_date)) is_receipt = (document.document_type == DOCUMENT_TYPE_RECEIPT) + invoice_allocations = {} try: from app.services.cross_currency_settlement_service import ( prepare_standalone_receipt_payment_cross_currency, ) data = prepare_standalone_receipt_payment_cross_currency( - db, int(document.business_id), data, is_receipt=is_receipt + db, int(document.business_id), data, is_receipt=is_receipt, + invoice_allocations=invoice_allocations, ) except ApiError: raise except Exception: logger.exception("prepare standalone cross-currency on update failed") + invoice_allocations.clear() + + if not invoice_allocations: + invoice_allocations = preserve_readback_allocations(db, document, data) currency_id = data.get("currency_id", document.currency_id) if not currency_id: @@ -1927,6 +1942,8 @@ def update_receipt_payment( # 3) اعمال تغییرات در سند (بدون تغییر code و document_type) document.document_date = document_date document.currency_id = int(currency_id) + if invoice_allocations: + document.developer_settings = {**(document.developer_settings or {}), CONTRACT_KEY: 1} if "extra_info" in data and ( isinstance(data.get("extra_info"), dict) or data.get("extra_info") is None ): @@ -1969,12 +1986,13 @@ def update_receipt_payment( db.query(DocumentLine).filter(DocumentLine.document_id == document.id).delete(synchronize_session=False) # خطوط شخص - for person_line in person_lines: + for i, person_line in enumerate(person_lines): person_id = person_line.get("person_id") if not person_id: continue amount = Decimal(str(person_line.get("amount", 0))) - if amount <= 0: + # Keep an exact native share even when its base GL amount rounds to zero. + if amount <= 0 and i not in invoice_allocations: continue description = (person_line.get("description") or "").strip() or None person_account = _get_person_account(db, document.business_id, int(person_id), is_receivable=is_person_receivable) @@ -2010,6 +2028,7 @@ def update_receipt_payment( credit=credit_amount, description=description, extra_info=line_extra_info, + developer_data={ALLOCATION_KEY: invoice_allocations[i]} if i in invoice_allocations else None, ) db.add(line) @@ -2699,6 +2718,9 @@ def document_to_dict(db: Session, document: Document) -> Dict[str, Any]: "description": line.description, "extra_info": line.extra_info, } + allocation = (line.developer_data or {}).get(ALLOCATION_KEY) + if (document.developer_settings or {}).get(CONTRACT_KEY) == 1 and allocation: + line_dict["extra_info"] = {**(line.extra_info or {}), ALLOCATION_KEY: dict(allocation)} # اضافه کردن اطلاعات اضافی از extra_info if line.extra_info: diff --git a/hesabixAPI/tests/test_invoice_shared_receipt_allocation.py b/hesabixAPI/tests/test_invoice_shared_receipt_allocation.py index 4431eb6e..c9338ac4 100644 --- a/hesabixAPI/tests/test_invoice_shared_receipt_allocation.py +++ b/hesabixAPI/tests/test_invoice_shared_receipt_allocation.py @@ -1,4 +1,4 @@ -from datetime import date +from datetime import UTC, date from decimal import Decimal import pytest @@ -10,15 +10,24 @@ from adapters.db import models from adapters.db.models.business import BusinessField, BusinessType from adapters.db.models.cash_register import CashRegister from adapters.db.models.document_monetization import DocumentUsagePolicy -from adapters.db.models.document_numbering import BusinessDocumentNumberingSetting, DocumentNumberCounter +from adapters.db.models.document_numbering import ( + BusinessDocumentNumberingSetting, + DocumentNumberCounter, +) from adapters.db.models.marketplace import BusinessPlugin, MarketplacePlugin from app.core import cache +from app.core.responses import ApiError from app.services.invoice_service import ( batch_calculate_invoices_remaining, calculate_invoice_remaining, create_invoice, ) -from app.services.receipt_payment_service import create_receipt_payment +from app.services.receipt_invoice_allocation_service import ALLOCATION_KEY, CONTRACT_KEY +from app.services.receipt_payment_service import ( + create_receipt_payment, + get_receipt_payment, + update_receipt_payment, +) DAY = date(2026, 11, 11) ACCOUNTS = ( @@ -64,9 +73,9 @@ def db(monkeypatch): engine.dispose() -def _sale(db, code): +def _sale(db, code, currency_id=1): result = create_invoice(db, 1, 1, { - "invoice_type": "invoice_sales", "document_date": DAY.isoformat(), "currency_id": 1, + "invoice_type": "invoice_sales", "document_date": DAY.isoformat(), "currency_id": currency_id, "code": code, "extra_info": {"person_id": 1, "post_inventory": False}, "lines": [{"product_id": 1, "quantity": 1, "extra_info": { "unit_price": 500, "tax_rate": 10, "tax_amount": 50, "line_total": 550, @@ -137,3 +146,140 @@ def test_single_invoice_receipt_preserves_existing_fallback(db, mode): "fx_settlement": {"settles_amount": "250", "settles_currency_id": 2}, }) _assert_balances(db, (invoice,), [(250, 300)]) + + +@pytest.fixture +def fx_db(db): + from datetime import datetime + + from adapters.db.models.business_currency_rate import BusinessCurrencyRate + from adapters.db.models.currency import BusinessCurrency + + db.execute(CreateTable(BusinessCurrencyRate.__table__)) + now = datetime(2026, 1, 1, tzinfo=UTC) + db.add(BusinessCurrency(business_id=1, currency_id=2)) + db.add(BusinessCurrencyRate(business_id=1, currency_id=2, rate=Decimal("0.1"), + effective_at=now, created_by_user_id=1, created_at=now, updated_at=now)) + db.get(models.Currency, 1).round_monetary_amounts = True + db.commit() + return db + + +def _fx_payload(invoices, shares): + return { + "document_type": "receipt", "document_date": DAY.isoformat(), "currency_id": 2, + "person_lines": [{"person_id": 1, "amount": str(amount), "extra_info": {"invoice_id": invoice.id}} + for invoice, amount in zip(invoices, shares, strict=True)], + "account_lines": [{"transaction_type": "cash_register", "cash_register_id": 1, + "amount": 25, "settles_amount": 250, "invoice_rate_to_base": "0.1"}], + } + + +@pytest.mark.parametrize("shares,expected", [ + (["100", "150"], [(100, 450), (150, 400)]), + (["100.01", "149.99"], [(100.01, 449.99), (149.99, 400.01)]), + (["0.01", "249.99"], [(0.01, 549.99), (249.99, 300.01)]), +]) +def test_fx_receipt_retains_exact_invoice_currency_before_base_rounding(fx_db, shares, expected): + db = fx_db + invoices = [_sale(db, "FX-A", 2), _sale(db, "FX-B", 2)] + result = create_receipt_payment(db, 1, 1, _fx_payload(invoices, shares)) + db.expire_all() + receipt = db.get(models.Document, result["id"]) + assert receipt.currency_id == 1 + assert [str(line.credit) for line in receipt.lines if line.person_id] == [ + str((Decimal(amount) / 10).quantize(Decimal(".01"))) for amount in shares] + assert sum(line.debit for line in receipt.lines) == sum(line.credit for line in receipt.lines) == 25 + readback = get_receipt_payment(db, receipt.id) + assert [line["extra_info"][ALLOCATION_KEY]["amount"] for line in readback["person_lines"]] == shares + _assert_balances(db, invoices, expected) + + +def test_fx_update_replaces_shares_and_removed_allocation_does_not_fall_back_to_header(fx_db): + db = fx_db + invoices = [_sale(db, "EDIT-A", 2), _sale(db, "EDIT-B", 2)] + rid = create_receipt_payment(db, 1, 1, _fx_payload(invoices, [100, 150]))["id"] + update_receipt_payment(db, rid, 1, _fx_payload(invoices, ["100.01", "149.99"])) + db.expire_all() + _assert_balances(db, invoices, [(100.01, 449.99), (149.99, 400.01)]) + body = _fx_payload(invoices[1:], [250]) + body["extra_info"] = {"invoice_id": invoices[0].id} + update_receipt_payment(db, rid, 1, body) + db.expire_all() + _assert_balances(db, invoices, [(0, 550), (250, 300)]) + create_receipt_payment(db, 1, 1, _fx_payload(invoices[1:], [250])) + db.expire_all() + _assert_balances(db, invoices, [(0, 550), (500, 50)]) + + +def test_fx_readback_update_uses_stored_identity_and_ignores_forged_metadata(fx_db): + db = fx_db + invoices = [_sale(db, "READ-A", 2), _sale(db, "READ-B", 2)] + body = _fx_payload(invoices, ["100.01", "149.99"]) + body["developer_settings"] = {CONTRACT_KEY: 999} + for line in body["person_lines"]: + line["developer_data"] = {ALLOCATION_KEY: {"amount": "9999"}} + line["extra_info"][ALLOCATION_KEY] = {"amount": "9999"} + rid = create_receipt_payment(db, 1, 1, body)["id"] + readback = get_receipt_payment(db, rid) + readback["developer_settings"] = {CONTRACT_KEY: 999} + for line in readback["person_lines"]: + line["extra_info"][ALLOCATION_KEY]["amount"] = "9999" + update_receipt_payment(db, rid, 1, readback) + db.expire_all() + _assert_balances(db, invoices, [(100.01, 449.99), (149.99, 400.01)]) + + +@pytest.mark.parametrize("invalid", ["currency", "person", "business", "missing", "nan"]) +def test_invalid_fx_invoice_allocation_is_rejected_before_writing(fx_db, invalid): + db = fx_db + invoice = _sale(db, "INVALID", 2) + body = _fx_payload([invoice], [250]) + if invalid in ("currency", "business"): + setattr(invoice, "currency_id" if invalid == "currency" else "business_id", 1 if invalid == "currency" else 2) + db.commit() + elif invalid == "person": + body["person_lines"][0]["person_id"] = 2 + elif invalid == "missing": + body["person_lines"][0]["extra_info"]["invoice_id"] = 999999 + else: + body["person_lines"][0]["amount"] = "NaN" + before = db.query(models.Document).count() + with pytest.raises(ApiError): + create_receipt_payment(db, 1, 1, body) + db.rollback() + assert db.query(models.Document).count() == before + + +def test_fx_receipt_rollback_discards_allocation_and_financial_lines(fx_db): + db = fx_db + invoices = [_sale(db, "ROLL-A", 2), _sale(db, "ROLL-B", 2)] + before = (db.query(models.Document).count(), db.query(models.DocumentLine).count()) + result = create_receipt_payment(db, 1, 1, _fx_payload(invoices, [100, 150]), commit=False) + assert db.get(models.Document, result["id"]).developer_settings[CONTRACT_KEY] == 1 + db.rollback() + assert (db.query(models.Document).count(), db.query(models.DocumentLine).count()) == before + _assert_balances(db, invoices, [(0, 550), (0, 550)]) + + +def test_fx_two_distinct_allocations_to_same_invoice_are_both_counted(fx_db): + db = fx_db + invoice = _sale(db, "TWO-LINES", 2) + body = _fx_payload([invoice, invoice], [100, 150]) + create_receipt_payment(db, 1, 1, body) + db.expire_all() + _assert_balances(db, [invoice], [(250, 300)]) + + +def test_fx_readback_with_changed_rounded_amount_is_rejected_without_writing(fx_db): + db = fx_db + invoices = [_sale(db, "REJECT-A", 2), _sale(db, "REJECT-B", 2)] + rid = create_receipt_payment(db, 1, 1, _fx_payload(invoices, ["100.01", "149.99"]))["id"] + body = get_receipt_payment(db, rid) + body["person_lines"][0]["amount"] = 11 + before = [(line.id, line.debit, line.credit) for line in db.get(models.Document, rid).lines] + with pytest.raises(ApiError, match="INVOICE_ALLOCATION_CURRENCY_REQUIRED"): + update_receipt_payment(db, rid, 1, body) + db.rollback() + assert [(line.id, line.debit, line.credit) for line in db.get(models.Document, rid).lines] == before + _assert_balances(db, invoices, [(100.01, 449.99), (149.99, 400.01)])