From 815562bdb6a68ecfe17e32a520ebf610442644f5 Mon Sep 17 00:00:00 2001 From: Seyyed Date: Thu, 12 Nov 2026 18:31:42 +0330 Subject: [PATCH] fix(invoices): use posted sales receivable as club payable (H30) --- .../app/services/customer_club_service.py | 9 +- .../services/invoice_adjustments_service.py | 17 +++- hesabixAPI/app/services/invoice_service.py | 47 +++++++---- .../tests/test_invoice_net_contract_h30.py | 84 ++++++++++++++++++- 4 files changed, 134 insertions(+), 23 deletions(-) diff --git a/hesabixAPI/app/services/customer_club_service.py b/hesabixAPI/app/services/customer_club_service.py index fb2c98f7..caa347a1 100755 --- a/hesabixAPI/app/services/customer_club_service.py +++ b/hesabixAPI/app/services/customer_club_service.py @@ -694,8 +694,8 @@ def maybe_apply_loyalty_redemption_to_invoice_payload( user_id: int, invoice_lines: Optional[List[Dict[str, Any]]] = None, document_id: int | None = None, -) -> None: - """قبل از ذخیره فاکتور: افزایش تخفیف و کاهش مالیات به نسبت مبنای جدید. extra_info.customer_club پر می‌شود.""" +) -> bool: + """قبل از ذخیره فاکتور: افزایش تخفیف و کاهش مالیات به نسبت مبنای جدید. خروجی نشان می‌دهد کوپن یا امتیاز اعمال شد.""" cc = dict(header_extra.get("customer_club") or {}) voucher_code = str(data.get("customer_club_voucher_code") or cc.get("voucher_code") or "").strip().upper() if voucher_code: @@ -741,7 +741,7 @@ def maybe_apply_loyalty_redemption_to_invoice_payload( header_extra["customer_club"] = cc raw_pts = data.get("loyalty_redemption_points") if raw_pts is None: - return + return bool(voucher_code) try: redeem_pts = Decimal(str(raw_pts)) except Exception: @@ -760,7 +760,7 @@ def maybe_apply_loyalty_redemption_to_invoice_payload( header_extra["customer_club"] = cc else: header_extra.pop("customer_club", None) - return + return bool(voucher_code) if invoice_type != INVOICE_SALES or is_proforma: raise ApiError( "LOYALTY_REDEEM_NOT_ALLOWED", @@ -838,6 +838,7 @@ def maybe_apply_loyalty_redemption_to_invoice_payload( cc["redeem_points_requested"] = float(redeem_pts) cc["redeem_discount_amount"] = float(discount_add) header_extra["customer_club"] = cc + return True def commit_loyalty_redemption_for_sales_invoice(db: Session, document: Document, user_id: int) -> None: diff --git a/hesabixAPI/app/services/invoice_adjustments_service.py b/hesabixAPI/app/services/invoice_adjustments_service.py index f8829d88..a002e439 100755 --- a/hesabixAPI/app/services/invoice_adjustments_service.py +++ b/hesabixAPI/app/services/invoice_adjustments_service.py @@ -5,7 +5,7 @@ """ from __future__ import annotations -from decimal import Decimal, ROUND_HALF_UP +from decimal import Decimal, InvalidOperation, ROUND_HALF_UP from typing import Any, Dict, List, Tuple, Optional from sqlalchemy import or_ @@ -16,6 +16,7 @@ from adapters.db.models.document_line import DocumentLine from app.core.responses import ApiError INVOICE_ADJUSTMENTS_KEY = "invoice_adjustments" +SALES_RECEIVABLE_TOTAL_KEY = "_server_sales_receivable_total" INVOICE_SALES = "invoice_sales" INVOICE_PURCHASE = "invoice_purchase" @@ -39,6 +40,17 @@ def total_with_tax_from_totals_dict(totals: Dict[str, Any]) -> Decimal: return _money_quant(gross - discount + tax + adj_n + adj_t) +def sales_receivable_total_from_totals(totals: dict[str, Any]) -> Decimal | None: + stored = totals.get(SALES_RECEIVABLE_TOTAL_KEY) + if not isinstance(stored, str): + return None + try: + amount = Decimal(stored) + except InvalidOperation: + return None + return amount if amount.is_finite() else None + + def payable_total_from_totals_dict(totals: Dict[str, Any]) -> Decimal: """ مبلغ قابل پرداخت/دریافت فاکتور (مبنای مانده و سقف تخصیص دریافت/پرداخت). @@ -48,6 +60,9 @@ def payable_total_from_totals_dict(totals: Dict[str, Any]) -> Decimal: """ if not isinstance(totals, dict): return Decimal(0) + receivable = sales_receivable_total_from_totals(totals) + if receivable is not None: + return receivable if "net" in totals: net = Decimal(str(totals.get("net", 0))) adj_n = Decimal(str(totals.get("adjustments_net", 0))) diff --git a/hesabixAPI/app/services/invoice_service.py b/hesabixAPI/app/services/invoice_service.py index cda95cf9..bd03bdc4 100755 --- a/hesabixAPI/app/services/invoice_service.py +++ b/hesabixAPI/app/services/invoice_service.py @@ -36,6 +36,11 @@ 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_adjustments_service import ( + SALES_RECEIVABLE_TOTAL_KEY, + sales_receivable_total_from_totals, + total_with_tax_from_totals_dict, +) from app.services.invoice_line_total_guard import validate_invoice_line_totals from app.services.invoice_unit_conversion_service import ( INVENTORY_QUANTITY_UNIT_MAIN, @@ -3957,7 +3962,9 @@ def _quick_sale_payment_target(document: Document) -> Decimal: return max(Decimal(0), Decimal(str(meta["payment_target"]))) except Exception: pass - return Decimal(str(((document.extra_info or {}).get("totals") or {}).get("net", 0) or 0)) + totals = (document.extra_info or {}).get("totals") or {} + receivable = sales_receivable_total_from_totals(totals) + return receivable if receivable is not None else Decimal(str(totals.get("net", 0) or 0)) def _adjust_quick_sale_invoice_paid(document: Document, total_paid: Decimal) -> Decimal: @@ -3968,9 +3975,10 @@ def _adjust_quick_sale_invoice_paid(document: Document, total_paid: Decimal) -> try: prior_debt = max(Decimal(0), Decimal(str(meta.get("prior_debt_amount", 0) or 0))) credit_applied = max(Decimal(0), Decimal(str(meta.get("credit_applied_amount", 0) or 0))) - invoice_total = Decimal( - str(((document.extra_info or {}).get("totals") or {}).get("net", 0) or 0) - ) + totals = (document.extra_info or {}).get("totals") or {} + invoice_total = sales_receivable_total_from_totals(totals) + if invoice_total is None: + invoice_total = Decimal(str(totals.get("net", 0) or 0)) except Exception: return total_paid old_debt_settled = min(max(total_paid, Decimal(0)), prior_debt) @@ -7007,7 +7015,7 @@ def create_invoice( try: from app.services.customer_club_service import maybe_apply_loyalty_redemption_to_invoice_payload - maybe_apply_loyalty_redemption_to_invoice_payload( + club_discount_applied = maybe_apply_loyalty_redemption_to_invoice_payload( db, business_id, invoice_type, @@ -7032,6 +7040,7 @@ def create_invoice( header_extra = dict(data.get("extra_info") or {}) totals = dict(header_extra.get("totals") or {}) + total_with_tax = total_with_tax_from_totals_dict(totals) if ( invoice_type == INVOICE_SALES @@ -7046,7 +7055,7 @@ def create_invoice( currency_id=int(currency_id), document_date=document_date, fiscal_year_id=int(fiscal_year.id), - invoice_total=Decimal(str(totals.get("net", 0) or 0)), + invoice_total=total_with_tax if club_discount_applied else Decimal(str(totals.get("net", 0) or 0)), header_extra=header_extra, ) data["extra_info"] = header_extra @@ -7122,10 +7131,6 @@ def create_invoice( discount = Decimal(str(totals["discount"])) net = gross - discount tax = Decimal(str(totals["tax"])) - from app.services.invoice_adjustments_service import total_with_tax_from_totals_dict - - total_with_tax = total_with_tax_from_totals_dict(totals) - ensure_document_policy_allows_creation( db, business_id, @@ -7145,6 +7150,9 @@ def create_invoice( "adjustments_tax": float(Decimal(str(totals.get("adjustments_tax", 0)))), } + if club_discount_applied: + new_extra_info["totals"][SALES_RECEIVABLE_TOTAL_KEY] = str(total_with_tax) + from app.services.invoice_fx_revaluation import apply_fx_revaluation_to_invoice_extra business_for_fx = db.get(Business, business_id) @@ -8728,7 +8736,14 @@ def update_invoice( except Exception: pass # merge کردن: new_extra فیلدهای old_extra را override می‌کند؛ نرمال‌سازی برای ذخیره یکسان - merged_extra = _normalize_document_extra_info_for_storage({**old_extra, **new_extra}) + header_for_storage = {**old_extra, **new_extra} + incoming_totals = header_for_storage.get("totals") + if isinstance(incoming_totals, dict) and SALES_RECEIVABLE_TOTAL_KEY in incoming_totals: + header_for_storage["totals"] = { + key: value for key, value in incoming_totals.items() + if key != SALES_RECEIVABLE_TOTAL_KEY + } + merged_extra = _normalize_document_extra_info_for_storage(header_for_storage) if inv_type != _old_document_type: merged_extra = _sanitize_extra_info_for_invoice_type_change( merged_extra, inv_type, _old_document_type @@ -9118,7 +9133,7 @@ def update_invoice( from app.services.customer_club_service import maybe_apply_loyalty_redemption_to_invoice_payload pid_for_club = _person_id_from_header({"extra_info": header_extra}) - maybe_apply_loyalty_redemption_to_invoice_payload( + club_discount_applied = maybe_apply_loyalty_redemption_to_invoice_payload( db, int(document.business_id), inv_type, @@ -9136,11 +9151,12 @@ def update_invoice( from app.services.invoice_adjustments_service import ( merge_invoice_adjustments_into_header_extra, add_adjustment_document_lines, - total_with_tax_from_totals_dict, ) merge_invoice_adjustments_into_header_extra(db, int(document.business_id), inv_type, header_extra) totals = dict(header_extra.get("totals") or {}) + totals.pop(SALES_RECEIVABLE_TOTAL_KEY, None) + total_with_tax = total_with_tax_from_totals_dict(totals) _adj_extra_hdr = dict(header_extra) ex_merge = dict(document.extra_info or {}) if isinstance(header_extra, dict): @@ -9148,7 +9164,9 @@ def update_invoice( ex_merge["global_discount"] = header_extra["global_discount"] else: ex_merge.pop("global_discount", None) - ex_merge["totals"] = totals + ex_merge["totals"] = dict(totals) + if club_discount_applied: + ex_merge["totals"][SALES_RECEIVABLE_TOTAL_KEY] = str(total_with_tax) if "invoice_adjustments" in header_extra: ex_merge["invoice_adjustments"] = header_extra["invoice_adjustments"] else: @@ -9172,7 +9190,6 @@ def update_invoice( discount = Decimal(str(totals.get("discount", 0))) net = gross - discount tax = Decimal(str(totals.get("tax", 0))) - total_with_tax = total_with_tax_from_totals_dict(totals) person_id = _person_id_from_header({"extra_info": header_extra}) person_id = _resolve_and_validate_person_id(db, document.business_id, person_id) diff --git a/hesabixAPI/tests/test_invoice_net_contract_h30.py b/hesabixAPI/tests/test_invoice_net_contract_h30.py index 6db372b6..2bd43c6f 100644 --- a/hesabixAPI/tests/test_invoice_net_contract_h30.py +++ b/hesabixAPI/tests/test_invoice_net_contract_h30.py @@ -2,7 +2,7 @@ from datetime import date from decimal import Decimal import pytest -from sqlalchemy import create_engine +from sqlalchemy import create_engine, select from sqlalchemy.orm import Session from sqlalchemy.schema import CreateTable @@ -10,7 +10,10 @@ from adapters.db import models from adapters.db.models.business import BusinessField, BusinessType from adapters.db.models.customer_club import CustomerClubBalance, CustomerClubSettings, CustomerClubVoucher from adapters.db.models.document_monetization import DocumentUsagePolicy +from adapters.db.models.invoice_item_line import InvoiceItemLine from adapters.db.models.person import Person, PersonType +from adapters.db.models.product_variant import ProductVariant +from adapters.db.models.product_variant_allocation import InvoiceItemLineVariantAllocation from app.core import cache from app.services.customer_club_service import ( _apply_club_discount_to_totals, @@ -18,10 +21,15 @@ from app.services.customer_club_service import ( maybe_apply_loyalty_redemption_to_invoice_payload, ) from app.services.invoice_adjustments_service import ( + SALES_RECEIVABLE_TOTAL_KEY, payable_total_from_totals_dict, total_with_tax_from_totals_dict, ) -from app.services.invoice_service import create_invoice +from app.services.invoice_service import ( + batch_calculate_invoices_remaining, + calculate_invoice_remaining, + create_invoice, +) from app.services.person_share_link_service import _public_invoice_financials_from_extra_info ACCOUNT_CODES = ( @@ -54,13 +62,17 @@ def db(monkeypatch): lambda *args, **kwargs: None, ) engine = create_engine("sqlite://") + # SQLite autogenerates a primary key only when declared INTEGER. + monkeypatch.setattr(engine.dialect.type_compiler_instance, "visit_BIGINT", + lambda *args, **kwargs: "INTEGER") 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", "persons", "fa_assets", "customer_club_settings", "customer_club_balances", "customer_club_rewards", "customer_club_campaigns", "customer_club_vouchers", "customer_club_ledger", - "customer_club_point_lots", + "customer_club_point_lots", "product_variants", "product_variant_values", + "product_attributes", "product_attribute_options", "warehouse_documents", ) day = date(2026, 11, 11) with Session(engine, autoflush=False) as session: @@ -168,3 +180,69 @@ def test_loyalty_earn_total_with_tax_does_not_add_tax_twice(db): net_b, total_b = _basis_net_and_total_from_document(db, document) assert net_b == Decimal("550") assert total_b == Decimal("550.00") + +@pytest.mark.parametrize("variant", [False, True], ids=["simple", "variant"]) +def test_high_precision_sale_uses_posted_receivable(db, variant): + currency = db.get(models.Currency, 1) + currency.decimal_places = 8 + product = db.get(models.Product, 1) + if variant: + product.variant_mode = "inventory" + product.inventory_mode = "bulk" + product.track_inventory = True + db.add(ProductVariant(id=1, business_id=1, product_id=1, combination_key="1:1")) + db.commit() + + line = { + "product_id": 1, + "quantity": 1, + "extra_info": { + "unit_price": "100000000.00499999", + "tax_rate": 10, + "tax_amount": "10000000", + "line_total": "110000000.00499999", + }, + } + if variant: + line["allocations"] = [{"variant_id": 1, "quantity": 1}] + payload = { + "invoice_type": "invoice_sales", + "document_date": "2026-11-11", + "currency_id": 1, + "code": "H30-PRECISION", + "customer_club_voucher_code": "C50", + "loyalty_redemption_points": 10, + "extra_info": { + "person_id": 1, + "post_inventory": False, + "totals": {SALES_RECEIVABLE_TOTAL_KEY: "1.00"}, + }, + "lines": [line], + } + document_id = create_invoice(db, 1, 1, payload, commit=False)["data"]["id"] + db.commit() + db.expire_all() + document = db.get(models.Document, document_id) + item = db.scalars(select(InvoiceItemLine).filter_by(document_id=document_id)).one() + allocations = db.scalars( + select(InvoiceItemLineVariantAllocation).filter_by(invoice_item_line_id=item.id) + ).all() + assert [(row.variant_id, row.quantity) for row in allocations] == ([(1, 1)] if variant else []) + + ar = next(row.debit for row in document.lines if row.account.code == "10401" and row.person_id == 1) + assert ar == Decimal("109999934.00") + totals = document.extra_info["totals"] + assert totals["net"] == 109999934.005 + assert totals[SALES_RECEIVABLE_TOTAL_KEY] == "109999934.00" + assert payable_total_from_totals_dict(totals) == ar + single = calculate_invoice_remaining(db, 1, document_id) + assert Decimal(str(single["remaining"])) == ar + assert batch_calculate_invoices_remaining(db, 1, [document])[document_id] == single + + +def test_zero_snapshot_and_historical_totals_are_distinct(): + historical = {"gross": 500, "discount": 60, "tax": 44, "net": 440} + assert payable_total_from_totals_dict(historical) == Decimal("440.00") + assert payable_total_from_totals_dict( + {**historical, SALES_RECEIVABLE_TOTAL_KEY: "0.00"} + ) == Decimal("0.00") -- 2.43.0