H30 — تطبیق مبلغ قابل وصول فروش باشگاه با ثبت دریافتنی #54
5 changed files with 140 additions and 23 deletions
|
|
@ -694,8 +694,8 @@ def maybe_apply_loyalty_redemption_to_invoice_payload(
|
||||||
user_id: int,
|
user_id: int,
|
||||||
invoice_lines: Optional[List[Dict[str, Any]]] = None,
|
invoice_lines: Optional[List[Dict[str, Any]]] = None,
|
||||||
document_id: int | None = None,
|
document_id: int | None = None,
|
||||||
) -> None:
|
) -> bool:
|
||||||
"""قبل از ذخیره فاکتور: افزایش تخفیف و کاهش مالیات به نسبت مبنای جدید. extra_info.customer_club پر میشود."""
|
"""قبل از ذخیره فاکتور: افزایش تخفیف و کاهش مالیات به نسبت مبنای جدید. خروجی نشان میدهد کوپن یا امتیاز اعمال شد."""
|
||||||
cc = dict(header_extra.get("customer_club") or {})
|
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()
|
voucher_code = str(data.get("customer_club_voucher_code") or cc.get("voucher_code") or "").strip().upper()
|
||||||
if voucher_code:
|
if voucher_code:
|
||||||
|
|
@ -741,7 +741,7 @@ def maybe_apply_loyalty_redemption_to_invoice_payload(
|
||||||
header_extra["customer_club"] = cc
|
header_extra["customer_club"] = cc
|
||||||
raw_pts = data.get("loyalty_redemption_points")
|
raw_pts = data.get("loyalty_redemption_points")
|
||||||
if raw_pts is None:
|
if raw_pts is None:
|
||||||
return
|
return bool(voucher_code)
|
||||||
try:
|
try:
|
||||||
redeem_pts = Decimal(str(raw_pts))
|
redeem_pts = Decimal(str(raw_pts))
|
||||||
except Exception:
|
except Exception:
|
||||||
|
|
@ -760,7 +760,7 @@ def maybe_apply_loyalty_redemption_to_invoice_payload(
|
||||||
header_extra["customer_club"] = cc
|
header_extra["customer_club"] = cc
|
||||||
else:
|
else:
|
||||||
header_extra.pop("customer_club", None)
|
header_extra.pop("customer_club", None)
|
||||||
return
|
return bool(voucher_code)
|
||||||
if invoice_type != INVOICE_SALES or is_proforma:
|
if invoice_type != INVOICE_SALES or is_proforma:
|
||||||
raise ApiError(
|
raise ApiError(
|
||||||
"LOYALTY_REDEEM_NOT_ALLOWED",
|
"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_points_requested"] = float(redeem_pts)
|
||||||
cc["redeem_discount_amount"] = float(discount_add)
|
cc["redeem_discount_amount"] = float(discount_add)
|
||||||
header_extra["customer_club"] = cc
|
header_extra["customer_club"] = cc
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
def commit_loyalty_redemption_for_sales_invoice(db: Session, document: Document, user_id: int) -> None:
|
def commit_loyalty_redemption_for_sales_invoice(db: Session, document: Document, user_id: int) -> None:
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
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 typing import Any, Dict, List, Tuple, Optional
|
||||||
|
|
||||||
from sqlalchemy import or_
|
from sqlalchemy import or_
|
||||||
|
|
@ -16,6 +16,7 @@ from adapters.db.models.document_line import DocumentLine
|
||||||
from app.core.responses import ApiError
|
from app.core.responses import ApiError
|
||||||
|
|
||||||
INVOICE_ADJUSTMENTS_KEY = "invoice_adjustments"
|
INVOICE_ADJUSTMENTS_KEY = "invoice_adjustments"
|
||||||
|
SALES_RECEIVABLE_TOTAL_KEY = "_server_sales_receivable_total"
|
||||||
|
|
||||||
INVOICE_SALES = "invoice_sales"
|
INVOICE_SALES = "invoice_sales"
|
||||||
INVOICE_PURCHASE = "invoice_purchase"
|
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)
|
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:
|
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):
|
if not isinstance(totals, dict):
|
||||||
return Decimal(0)
|
return Decimal(0)
|
||||||
|
receivable = sales_receivable_total_from_totals(totals)
|
||||||
|
if receivable is not None:
|
||||||
|
return receivable
|
||||||
if "net" in totals:
|
if "net" in totals:
|
||||||
net = Decimal(str(totals.get("net", 0)))
|
net = Decimal(str(totals.get("net", 0)))
|
||||||
adj_n = Decimal(str(totals.get("adjustments_net", 0)))
|
adj_n = Decimal(str(totals.get("adjustments_net", 0)))
|
||||||
|
|
|
||||||
|
|
@ -36,6 +36,11 @@ from app.core.responses import ApiError, success_response
|
||||||
from app.core.transaction_lock import acquire_transaction_lock
|
from app.core.transaction_lock import acquire_transaction_lock
|
||||||
from app.services.document_monetization_service import ensure_document_policy_allows_creation
|
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.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_line_total_guard import validate_invoice_line_totals
|
||||||
from app.services.invoice_unit_conversion_service import (
|
from app.services.invoice_unit_conversion_service import (
|
||||||
INVENTORY_QUANTITY_UNIT_MAIN,
|
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"])))
|
return max(Decimal(0), Decimal(str(meta["payment_target"])))
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
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:
|
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:
|
try:
|
||||||
prior_debt = max(Decimal(0), Decimal(str(meta.get("prior_debt_amount", 0) or 0)))
|
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)))
|
credit_applied = max(Decimal(0), Decimal(str(meta.get("credit_applied_amount", 0) or 0)))
|
||||||
invoice_total = Decimal(
|
totals = (document.extra_info or {}).get("totals") or {}
|
||||||
str(((document.extra_info or {}).get("totals") or {}).get("net", 0) or 0)
|
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:
|
except Exception:
|
||||||
return total_paid
|
return total_paid
|
||||||
old_debt_settled = min(max(total_paid, Decimal(0)), prior_debt)
|
old_debt_settled = min(max(total_paid, Decimal(0)), prior_debt)
|
||||||
|
|
@ -7007,7 +7015,7 @@ def create_invoice(
|
||||||
try:
|
try:
|
||||||
from app.services.customer_club_service import maybe_apply_loyalty_redemption_to_invoice_payload
|
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,
|
db,
|
||||||
business_id,
|
business_id,
|
||||||
invoice_type,
|
invoice_type,
|
||||||
|
|
@ -7032,6 +7040,7 @@ def create_invoice(
|
||||||
|
|
||||||
header_extra = dict(data.get("extra_info") or {})
|
header_extra = dict(data.get("extra_info") or {})
|
||||||
totals = dict(header_extra.get("totals") or {})
|
totals = dict(header_extra.get("totals") or {})
|
||||||
|
total_with_tax = total_with_tax_from_totals_dict(totals)
|
||||||
|
|
||||||
if (
|
if (
|
||||||
invoice_type == INVOICE_SALES
|
invoice_type == INVOICE_SALES
|
||||||
|
|
@ -7046,7 +7055,7 @@ def create_invoice(
|
||||||
currency_id=int(currency_id),
|
currency_id=int(currency_id),
|
||||||
document_date=document_date,
|
document_date=document_date,
|
||||||
fiscal_year_id=int(fiscal_year.id),
|
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,
|
header_extra=header_extra,
|
||||||
)
|
)
|
||||||
data["extra_info"] = header_extra
|
data["extra_info"] = header_extra
|
||||||
|
|
@ -7122,10 +7131,6 @@ def create_invoice(
|
||||||
discount = Decimal(str(totals["discount"]))
|
discount = Decimal(str(totals["discount"]))
|
||||||
net = gross - discount
|
net = gross - discount
|
||||||
tax = Decimal(str(totals["tax"]))
|
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(
|
ensure_document_policy_allows_creation(
|
||||||
db,
|
db,
|
||||||
business_id,
|
business_id,
|
||||||
|
|
@ -7145,6 +7150,9 @@ def create_invoice(
|
||||||
"adjustments_tax": float(Decimal(str(totals.get("adjustments_tax", 0)))),
|
"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
|
from app.services.invoice_fx_revaluation import apply_fx_revaluation_to_invoice_extra
|
||||||
|
|
||||||
business_for_fx = db.get(Business, business_id)
|
business_for_fx = db.get(Business, business_id)
|
||||||
|
|
@ -8732,7 +8740,14 @@ def update_invoice(
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
# merge کردن: new_extra فیلدهای old_extra را override میکند؛ نرمالسازی برای ذخیره یکسان
|
# 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:
|
if inv_type != _old_document_type:
|
||||||
merged_extra = _sanitize_extra_info_for_invoice_type_change(
|
merged_extra = _sanitize_extra_info_for_invoice_type_change(
|
||||||
merged_extra, inv_type, _old_document_type
|
merged_extra, inv_type, _old_document_type
|
||||||
|
|
@ -9124,7 +9139,7 @@ def update_invoice(
|
||||||
from app.services.customer_club_service import maybe_apply_loyalty_redemption_to_invoice_payload
|
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})
|
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,
|
db,
|
||||||
int(document.business_id),
|
int(document.business_id),
|
||||||
inv_type,
|
inv_type,
|
||||||
|
|
@ -9142,11 +9157,12 @@ def update_invoice(
|
||||||
from app.services.invoice_adjustments_service import (
|
from app.services.invoice_adjustments_service import (
|
||||||
merge_invoice_adjustments_into_header_extra,
|
merge_invoice_adjustments_into_header_extra,
|
||||||
add_adjustment_document_lines,
|
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)
|
merge_invoice_adjustments_into_header_extra(db, int(document.business_id), inv_type, header_extra)
|
||||||
totals = dict(header_extra.get("totals") or {})
|
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)
|
_adj_extra_hdr = dict(header_extra)
|
||||||
ex_merge = dict(document.extra_info or {})
|
ex_merge = dict(document.extra_info or {})
|
||||||
if isinstance(header_extra, dict):
|
if isinstance(header_extra, dict):
|
||||||
|
|
@ -9159,6 +9175,8 @@ def update_invoice(
|
||||||
key: float(value) if isinstance(value, Decimal) else value
|
key: float(value) if isinstance(value, Decimal) else value
|
||||||
for key, value in totals.items()
|
for key, value in totals.items()
|
||||||
}
|
}
|
||||||
|
if club_discount_applied:
|
||||||
|
ex_merge["totals"][SALES_RECEIVABLE_TOTAL_KEY] = str(total_with_tax)
|
||||||
if "invoice_adjustments" in header_extra:
|
if "invoice_adjustments" in header_extra:
|
||||||
ex_merge["invoice_adjustments"] = header_extra["invoice_adjustments"]
|
ex_merge["invoice_adjustments"] = header_extra["invoice_adjustments"]
|
||||||
else:
|
else:
|
||||||
|
|
@ -9182,7 +9200,6 @@ def update_invoice(
|
||||||
discount = Decimal(str(totals.get("discount", 0)))
|
discount = Decimal(str(totals.get("discount", 0)))
|
||||||
net = gross - discount
|
net = gross - discount
|
||||||
tax = Decimal(str(totals.get("tax", 0)))
|
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 = _person_id_from_header({"extra_info": header_extra})
|
||||||
person_id = _resolve_and_validate_person_id(db, document.business_id, person_id)
|
person_id = _resolve_and_validate_person_id(db, document.business_id, person_id)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ from datetime import date
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from sqlalchemy import create_engine
|
from sqlalchemy import create_engine, select
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from sqlalchemy.schema import CreateTable
|
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.business import BusinessField, BusinessType
|
||||||
from adapters.db.models.customer_club import CustomerClubBalance, CustomerClubSettings, CustomerClubVoucher
|
from adapters.db.models.customer_club import CustomerClubBalance, CustomerClubSettings, CustomerClubVoucher
|
||||||
from adapters.db.models.document_monetization import DocumentUsagePolicy
|
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.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.core import cache
|
||||||
from app.services.customer_club_service import (
|
from app.services.customer_club_service import (
|
||||||
_apply_club_discount_to_totals,
|
_apply_club_discount_to_totals,
|
||||||
|
|
@ -18,10 +21,15 @@ from app.services.customer_club_service import (
|
||||||
maybe_apply_loyalty_redemption_to_invoice_payload,
|
maybe_apply_loyalty_redemption_to_invoice_payload,
|
||||||
)
|
)
|
||||||
from app.services.invoice_adjustments_service import (
|
from app.services.invoice_adjustments_service import (
|
||||||
|
SALES_RECEIVABLE_TOTAL_KEY,
|
||||||
payable_total_from_totals_dict,
|
payable_total_from_totals_dict,
|
||||||
total_with_tax_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
|
from app.services.person_share_link_service import _public_invoice_financials_from_extra_info
|
||||||
|
|
||||||
ACCOUNT_CODES = (
|
ACCOUNT_CODES = (
|
||||||
|
|
@ -54,13 +62,17 @@ def db(monkeypatch):
|
||||||
lambda *args, **kwargs: None,
|
lambda *args, **kwargs: None,
|
||||||
)
|
)
|
||||||
engine = create_engine("sqlite://")
|
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 = (
|
names = (
|
||||||
"businesses", "currencies", "fiscal_years", "products", "documents", "document_lines",
|
"businesses", "currencies", "fiscal_years", "products", "documents", "document_lines",
|
||||||
"invoice_item_lines", "document_usage_policies", "invoice_item_line_variant_allocations",
|
"invoice_item_lines", "document_usage_policies", "invoice_item_line_variant_allocations",
|
||||||
"invoice_item_line_lot_allocations", "users", "accounts", "persons", "fa_assets",
|
"invoice_item_line_lot_allocations", "users", "accounts", "persons", "fa_assets",
|
||||||
"customer_club_settings", "customer_club_balances", "customer_club_rewards",
|
"customer_club_settings", "customer_club_balances", "customer_club_rewards",
|
||||||
"customer_club_campaigns", "customer_club_vouchers", "customer_club_ledger",
|
"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)
|
day = date(2026, 11, 11)
|
||||||
with Session(engine, autoflush=False) as session:
|
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)
|
net_b, total_b = _basis_net_and_total_from_document(db, document)
|
||||||
assert net_b == Decimal("550")
|
assert net_b == Decimal("550")
|
||||||
assert total_b == Decimal("550.00")
|
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")
|
||||||
|
|
|
||||||
|
|
@ -22,6 +22,7 @@ from adapters.db.models.document_numbering import (
|
||||||
)
|
)
|
||||||
from app.core import cache
|
from app.core import cache
|
||||||
from app.services import customer_club_service, invoice_service
|
from app.services import customer_club_service, invoice_service
|
||||||
|
from app.services.invoice_adjustments_service import SALES_RECEIVABLE_TOTAL_KEY
|
||||||
|
|
||||||
DAY = date(2026, 11, 11)
|
DAY = date(2026, 11, 11)
|
||||||
|
|
||||||
|
|
@ -195,7 +196,11 @@ def read_invoice(db, document_id):
|
||||||
db.expire_all()
|
db.expire_all()
|
||||||
doc = db.get(models.Document, document_id)
|
doc = db.get(models.Document, document_id)
|
||||||
totals = doc.extra_info["totals"]
|
totals = doc.extra_info["totals"]
|
||||||
assert all(type(value) in (int, float) for value in totals.values())
|
assert all(
|
||||||
|
type(value) in (int, float)
|
||||||
|
for key, value in totals.items()
|
||||||
|
if key != SALES_RECEIVABLE_TOTAL_KEY
|
||||||
|
)
|
||||||
return totals, gl_lines(db, document_id)
|
return totals, gl_lines(db, document_id)
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -212,6 +217,7 @@ def test_invoice_rewrite_preserves_create_totals_and_gl(db, club):
|
||||||
"net": net,
|
"net": net,
|
||||||
"adjustments_net": 0,
|
"adjustments_net": 0,
|
||||||
"adjustments_tax": 0,
|
"adjustments_tax": 0,
|
||||||
|
**({SALES_RECEIVABLE_TOTAL_KEY: "594.00"} if club else {}),
|
||||||
}
|
}
|
||||||
assert expected[1] == [
|
assert expected[1] == [
|
||||||
("10401", net, 0, 1),
|
("10401", net, 0, 1),
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue