fix(invoice): enforce purchase price profit contracts #37
23 changed files with 1071 additions and 76 deletions
|
|
@ -822,6 +822,10 @@ class BusinessUpdateRequest(BaseModel):
|
|||
"lifo, weighted_average, moving_weighted_average (WMA دائمی), standard_cost, actual_cost"
|
||||
),
|
||||
)
|
||||
invoice_profit_missing_purchase_price_policy: Optional[str] = Field(
|
||||
default=None,
|
||||
description="رفتار قیمت خرید نامشخص: zero_cost, use_line_cost_price, block_calculation",
|
||||
)
|
||||
invoice_profit_include_overhead: Optional[bool] = Field(default=None, description="آیا هزینههای سربار در محاسبه سود لحاظ شود؟")
|
||||
invoice_profit_overhead_type: Optional[str] = Field(default=None, description="نوع هزینههای سربار: none, production_overhead, all_overhead, custom_percent")
|
||||
invoice_profit_overhead_percent: Optional[float] = Field(default=None, ge=0, le=100, description="درصد هزینههای سربار (0-100) - فقط برای custom_percent")
|
||||
|
|
@ -851,6 +855,10 @@ class BusinessUpdateRequest(BaseModel):
|
|||
default=None,
|
||||
description="مبنای محاسبه: unit_price | net_after_line_discount | net_with_tax | cost_price",
|
||||
)
|
||||
invoice_sync_purchase_price_multi_line_policy: Optional[str] = Field(
|
||||
default=None,
|
||||
description="سیاست چند ردیف خرید یک محصول: weighted_average, last_line, highest_price, lowest_price",
|
||||
)
|
||||
invoice_warehouse_release_mode: Optional[str] = Field(
|
||||
default=None,
|
||||
description="حواله پس از ثبت فاکتور: none (بدون حواله)، draft (پیشنویس)، posted (قطعی فوری)",
|
||||
|
|
@ -1098,6 +1106,26 @@ class BusinessUpdateRequest(BaseModel):
|
|||
raise ValueError("مبنای محاسبه سود نامعتبر است")
|
||||
return value
|
||||
|
||||
@validator("invoice_profit_missing_purchase_price_policy")
|
||||
def _validate_invoice_profit_missing_purchase_price_policy(cls, v): # noqa: N805
|
||||
if v is None or v == "":
|
||||
return None
|
||||
value = str(v).strip().lower()
|
||||
allowed = {"zero_cost", "use_line_cost_price", "block_calculation"}
|
||||
if value not in allowed:
|
||||
raise ValueError("سیاست قیمت خرید نامشخص نامعتبر است")
|
||||
return value
|
||||
|
||||
@validator("invoice_sync_purchase_price_multi_line_policy")
|
||||
def _validate_invoice_sync_purchase_price_multi_line_policy(cls, v): # noqa: N805
|
||||
if v is None or v == "":
|
||||
return None
|
||||
value = str(v).strip().lower()
|
||||
allowed = {"weighted_average", "last_line", "highest_price", "lowest_price"}
|
||||
if value not in allowed:
|
||||
raise ValueError("سیاست چند ردیف قیمت خرید نامعتبر است")
|
||||
return value
|
||||
|
||||
@validator("invoice_profit_overhead_type")
|
||||
def _validate_invoice_profit_overhead_type(cls, v): # noqa: N805
|
||||
if v is None or v == "":
|
||||
|
|
@ -1182,6 +1210,7 @@ class BusinessResponse(BaseModel):
|
|||
# تنظیمات محاسبه سود فاکتور
|
||||
invoice_profit_calculation_method: Optional[str] = Field(default=None, description="روش محاسبه سود فاکتور")
|
||||
invoice_profit_calculation_basis: Optional[str] = Field(default=None, description="مبنای محاسبه سود")
|
||||
invoice_profit_missing_purchase_price_policy: str = Field(default="zero_cost", description="سیاست قیمت خرید نامشخص")
|
||||
invoice_profit_include_overhead: Optional[bool] = Field(default=None, description="آیا هزینههای سربار در محاسبه سود لحاظ میشود")
|
||||
invoice_profit_overhead_type: Optional[str] = Field(default=None, description="نوع هزینههای سربار")
|
||||
invoice_profit_overhead_percent: Optional[float] = Field(default=None, description="درصد هزینههای سربار")
|
||||
|
|
@ -1198,6 +1227,7 @@ class BusinessResponse(BaseModel):
|
|||
invoice_sync_update_purchase_price_enabled: bool = Field(default=False, description="همگامسازی قیمت خرید از فاکتور")
|
||||
invoice_sync_sales_price_basis: Optional[str] = Field(default=None, description="مبنای قیمت فروش")
|
||||
invoice_sync_purchase_price_basis: Optional[str] = Field(default=None, description="مبنای قیمت خرید")
|
||||
invoice_sync_purchase_price_multi_line_policy: str = Field(default="weighted_average", description="سیاست چند ردیف خرید یک محصول")
|
||||
invoice_warehouse_release_mode: str = Field(
|
||||
default="draft",
|
||||
description="حواله پس از ثبت فاکتور: none، draft، posted",
|
||||
|
|
|
|||
|
|
@ -76,6 +76,13 @@ class Business(Base):
|
|||
server_default="purchase_price",
|
||||
comment="مبنای محاسبه سود: purchase_price, cost_price, average_cost, fifo, lifo, weighted_average, moving_weighted_average, standard_cost, actual_cost",
|
||||
)
|
||||
invoice_profit_missing_purchase_price_policy: Mapped[str] = mapped_column(
|
||||
String(40),
|
||||
nullable=False,
|
||||
default="zero_cost",
|
||||
server_default="zero_cost",
|
||||
comment="رفتار قیمت خرید نامشخص: zero_cost, use_line_cost_price, block_calculation",
|
||||
)
|
||||
invoice_profit_include_overhead: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default="0", comment="آیا هزینههای سربار در محاسبه سود لحاظ شود؟")
|
||||
invoice_profit_overhead_type: Mapped[str | None] = mapped_column(String(30), nullable=True, default="none", server_default="none", comment="نوع هزینههای سربار: none, production_overhead, all_overhead, custom_percent")
|
||||
invoice_profit_overhead_percent: Mapped[float | None] = mapped_column(Numeric(5, 2), nullable=True, default=0, server_default="0", comment="درصد هزینههای سربار (در صورت انتخاب custom_percent)")
|
||||
|
|
@ -116,6 +123,13 @@ class Business(Base):
|
|||
String(40), nullable=True, default="net_after_line_discount", server_default="net_after_line_discount",
|
||||
comment="مبنای قیمت خرید: unit_price, net_after_line_discount, net_with_tax, cost_price",
|
||||
)
|
||||
invoice_sync_purchase_price_multi_line_policy: Mapped[str] = mapped_column(
|
||||
String(40),
|
||||
nullable=False,
|
||||
default="weighted_average",
|
||||
server_default="weighted_average",
|
||||
comment="سیاست چند ردیف خرید یک محصول: weighted_average, last_line, highest_price, lowest_price",
|
||||
)
|
||||
# حواله انبار پس از ثبت فاکتور: none (بدون حواله)، draft (پیشنویس)، posted (قطعی فوری)
|
||||
invoice_warehouse_release_mode: Mapped[str] = mapped_column(
|
||||
String(20),
|
||||
|
|
|
|||
|
|
@ -23,4 +23,12 @@ class InvoiceItemLine(Base):
|
|||
ledger_recognized_at = Column(DateTime, nullable=True, comment="زمان شناسایی قطعی")
|
||||
ledger_recognition_event = Column(String(40), nullable=True, comment="warehouse_document_posting | sales_invoice_document")
|
||||
|
||||
# Snapshot مبنای purchase_price در لحظه ثبت/ویرایش فروش؛ مبلغ به ارز پایه و روی واحد ردیف است.
|
||||
purchase_price_snapshot_unit_cost_base = Column(Numeric(18, 6), nullable=True)
|
||||
purchase_price_snapshot_currency_id = Column(Integer, nullable=True)
|
||||
purchase_price_snapshot_unit = Column(String(32), nullable=True)
|
||||
purchase_price_snapshot_factor = Column(Numeric(18, 6), nullable=True)
|
||||
purchase_price_snapshot_source = Column(String(40), nullable=True)
|
||||
purchase_price_snapshot_at = Column(DateTime, nullable=True)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -75,6 +75,11 @@ class Product(Base):
|
|||
base_sales_note: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
base_purchase_price: Mapped[Decimal | None] = mapped_column(Numeric(18, 2), nullable=True)
|
||||
base_purchase_note: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
base_purchase_price_sync_meta: Mapped[dict | None] = mapped_column(
|
||||
JSON,
|
||||
nullable=True,
|
||||
comment="منبع و سیاست آخرین همگامسازی قیمت خرید از فاکتور",
|
||||
)
|
||||
|
||||
# قیمت ارزی (P6 — فقط کسبوکار چندارزی استفاده میکند)
|
||||
sales_price_fx: Mapped[Decimal | None] = mapped_column(
|
||||
|
|
|
|||
|
|
@ -364,6 +364,7 @@ class ProductRepository(BaseRepository[Product]):
|
|||
"default_warehouse_id",
|
||||
"base_sales_price",
|
||||
"base_purchase_price",
|
||||
"base_purchase_price_sync_meta",
|
||||
"general_barcodes",
|
||||
"sales_tax_rate",
|
||||
"purchase_tax_rate",
|
||||
|
|
|
|||
|
|
@ -315,6 +315,7 @@ def apply_bulk_price_update(db: Session, business_id: int, request: BulkPriceUpd
|
|||
product.base_purchase_price = calculate_new_price(
|
||||
product.base_purchase_price, request.update_type, request.direction, request.value
|
||||
)
|
||||
product.base_purchase_price_sync_meta = None
|
||||
|
||||
if _affects_price_list_items(request):
|
||||
q = (
|
||||
|
|
|
|||
|
|
@ -86,9 +86,11 @@ def apply_bulk_product_price_sheet(
|
|||
|
||||
if row.clear_base_purchase_price:
|
||||
product.base_purchase_price = None
|
||||
product.base_purchase_price_sync_meta = None
|
||||
product_touched = True
|
||||
elif row.base_purchase_price is not None:
|
||||
product.base_purchase_price = _quantize_non_negative_integer(Decimal(row.base_purchase_price))
|
||||
product.base_purchase_price_sync_meta = None
|
||||
product_touched = True
|
||||
|
||||
for piu in row.price_item_updates:
|
||||
|
|
|
|||
|
|
@ -1679,6 +1679,9 @@ def _business_to_dict(business: Business) -> Dict[str, Any]:
|
|||
# تنظیمات محاسبه سود فاکتور
|
||||
"invoice_profit_calculation_method": getattr(business, "invoice_profit_calculation_method", None),
|
||||
"invoice_profit_calculation_basis": getattr(business, "invoice_profit_calculation_basis", None),
|
||||
"invoice_profit_missing_purchase_price_policy": getattr(
|
||||
business, "invoice_profit_missing_purchase_price_policy", "zero_cost"
|
||||
),
|
||||
"invoice_profit_include_overhead": bool(getattr(business, "invoice_profit_include_overhead", False)),
|
||||
"invoice_profit_overhead_type": getattr(business, "invoice_profit_overhead_type", None),
|
||||
"invoice_profit_overhead_percent": float(business.invoice_profit_overhead_percent) if getattr(business, "invoice_profit_overhead_percent", None) is not None else None,
|
||||
|
|
@ -1693,6 +1696,9 @@ def _business_to_dict(business: Business) -> Dict[str, Any]:
|
|||
"invoice_sync_update_purchase_price_enabled": bool(getattr(business, "invoice_sync_update_purchase_price_enabled", False)),
|
||||
"invoice_sync_sales_price_basis": getattr(business, "invoice_sync_sales_price_basis", None),
|
||||
"invoice_sync_purchase_price_basis": getattr(business, "invoice_sync_purchase_price_basis", None),
|
||||
"invoice_sync_purchase_price_multi_line_policy": getattr(
|
||||
business, "invoice_sync_purchase_price_multi_line_policy", "weighted_average"
|
||||
),
|
||||
"invoice_warehouse_release_mode": _normalize_invoice_warehouse_release_mode(
|
||||
getattr(business, "invoice_warehouse_release_mode", None),
|
||||
),
|
||||
|
|
|
|||
|
|
@ -91,7 +91,8 @@ def _evaluate_should_have_cogs_gl(db: Session, document: Document) -> bool:
|
|||
return True
|
||||
# اگر ثبت انبار از فاکتور غیرفعال است، حوالهای برای شناسایی وجود ندارد؛
|
||||
# COGS باید همزمان با ثبت فاکتور قطعی در دفتر کل بیاید.
|
||||
extra_info = document.extra_info if isinstance(document.extra_info, dict) else {}
|
||||
raw_extra_info = getattr(document, "extra_info", None)
|
||||
extra_info = raw_extra_info if isinstance(raw_extra_info, dict) else {}
|
||||
return not bool(extra_info.get("post_inventory", True))
|
||||
return False
|
||||
|
||||
|
|
@ -190,6 +191,31 @@ def _amounts_close(a: Decimal, b: Decimal, tolerance: Decimal = Decimal("0.01"))
|
|||
return abs(a - b) <= tolerance
|
||||
|
||||
|
||||
def _base_cogs_to_document_currency(
|
||||
db: Session,
|
||||
document: Document,
|
||||
amount_base: Decimal,
|
||||
) -> Decimal:
|
||||
from app.core.responses import ApiError
|
||||
from app.services.currency_quant import get_currency_quant_and_round
|
||||
from app.services.document_line_fx_service import quantize_money, resolve_document_fx_rate
|
||||
|
||||
rate, _source = resolve_document_fx_rate(
|
||||
db,
|
||||
document,
|
||||
allow_infer=True,
|
||||
fallback_one_on_missing=False,
|
||||
)
|
||||
if rate is None or rate <= 0:
|
||||
raise ApiError(
|
||||
"INVOICE_FX_RATE_REQUIRED_FOR_COGS",
|
||||
"نرخ تبدیل ارز سند برای ثبت بهای تمامشده موجود نیست",
|
||||
http_status=409,
|
||||
)
|
||||
quant, round_on = get_currency_quant_and_round(db, int(document.currency_id))
|
||||
return quantize_money(amount_base / rate, quant, round_on=round_on)
|
||||
|
||||
|
||||
def _post_cogs_gl_lines(
|
||||
db: Session,
|
||||
document: Document,
|
||||
|
|
@ -269,15 +295,17 @@ def resync_invoice_cogs_gl_lines(db: Session, document_id: int) -> bool:
|
|||
remove_invoice_cogs_gl_lines(db, int(document_id))
|
||||
return False
|
||||
|
||||
new_amount = _calculate_invoice_cogs_amount_for_gl(
|
||||
new_amount_base = _calculate_invoice_cogs_amount_for_gl(
|
||||
db, int(document.business_id), int(document.id)
|
||||
)
|
||||
|
||||
if new_amount <= 0:
|
||||
if new_amount_base <= 0:
|
||||
if existing_amount > 0:
|
||||
remove_invoice_cogs_gl_lines(db, int(document_id))
|
||||
return False
|
||||
|
||||
new_amount = _base_cogs_to_document_currency(db, document, new_amount_base)
|
||||
|
||||
if _amounts_close(existing_amount, new_amount):
|
||||
return True
|
||||
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ from adapters.db.models.price_list import PriceItem, PriceList
|
|||
from adapters.db.models.product import Product, ProductItemType
|
||||
from app.core.responses import ApiError
|
||||
from app.services.currency_quant import get_currency_quant_and_round
|
||||
from app.services.invoice_unit_conversion_service import price_main_to_line
|
||||
|
||||
# انواع فاکتوری که قیمتگذاری از کالا/لیست قیمت قابل کنترل است (نه تولید/ضایعات/مصرف مستقیم)
|
||||
_INVOICE_TYPES_UNIT_PRICE_LOCK = frozenset(
|
||||
|
|
@ -41,21 +42,11 @@ def _convert_main_unit_price_to_line_unit(
|
|||
selected_unit: Optional[str],
|
||||
quant: Decimal,
|
||||
) -> Decimal:
|
||||
"""همتراز با منطق Flutter: قیمت روی واحد اصلی → قیمت روی واحد انتخابشده."""
|
||||
main_u = (product.main_unit or "").strip() or None
|
||||
sec_u = (product.secondary_unit or "").strip() or None
|
||||
factor = _dec(product.unit_conversion_factor)
|
||||
if factor <= 0:
|
||||
factor = Decimal(1)
|
||||
sel = (selected_unit or "").strip() or None
|
||||
if not sel:
|
||||
sel = main_u
|
||||
is_main = main_u is None or sel is None or sel == main_u
|
||||
if is_main:
|
||||
return _quantize_money(price_on_main, quant)
|
||||
if sec_u and sel == sec_u:
|
||||
return _quantize_money(price_on_main * factor, quant)
|
||||
return _quantize_money(price_on_main, quant)
|
||||
"""قیمت واحد اصلی → قیمت واحد انتخابی، با قرارداد ۱ اصلی = factor فرعی."""
|
||||
return _quantize_money(
|
||||
price_main_to_line(price_on_main, product, selected_unit),
|
||||
quant,
|
||||
)
|
||||
|
||||
|
||||
def _base_price_on_main_for_invoice(product: Product, invoice_type: str) -> Decimal:
|
||||
|
|
|
|||
|
|
@ -5,8 +5,9 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from decimal import Decimal, ROUND_HALF_UP
|
||||
from typing import Any, Dict, Optional
|
||||
from datetime import datetime
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
|
|
@ -14,6 +15,10 @@ from adapters.db.models.business import Business
|
|||
from adapters.db.models.document import Document
|
||||
from adapters.db.models.invoice_item_line import InvoiceItemLine
|
||||
from adapters.db.models.product import Product
|
||||
from app.services.invoice_unit_conversion_service import (
|
||||
price_line_to_main,
|
||||
quantity_line_to_main,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
|
@ -32,23 +37,39 @@ ALLOWED_BASES = frozenset({
|
|||
BASIS_COST_PRICE,
|
||||
})
|
||||
|
||||
POLICY_WEIGHTED_AVERAGE = "weighted_average"
|
||||
POLICY_LAST_LINE = "last_line"
|
||||
POLICY_HIGHEST_PRICE = "highest_price"
|
||||
POLICY_LOWEST_PRICE = "lowest_price"
|
||||
ALLOWED_MULTI_LINE_POLICIES = frozenset({
|
||||
POLICY_WEIGHTED_AVERAGE,
|
||||
POLICY_LAST_LINE,
|
||||
POLICY_HIGHEST_PRICE,
|
||||
POLICY_LOWEST_PRICE,
|
||||
})
|
||||
|
||||
|
||||
def _q2(d: Decimal) -> Decimal:
|
||||
return d.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||||
|
||||
|
||||
def _normalize_basis(raw: Optional[str], default: str) -> str:
|
||||
def _normalize_basis(raw: str | None, default: str) -> str:
|
||||
if not raw or str(raw).strip() not in ALLOWED_BASES:
|
||||
return default
|
||||
return str(raw).strip()
|
||||
|
||||
|
||||
def _normalize_multi_line_policy(raw: str | None) -> str:
|
||||
value = str(raw or POLICY_WEIGHTED_AVERAGE).strip().lower()
|
||||
return value if value in ALLOWED_MULTI_LINE_POLICIES else POLICY_WEIGHTED_AVERAGE
|
||||
|
||||
|
||||
def _per_unit_line_currency(
|
||||
info: Dict[str, Any],
|
||||
info: dict[str, Any],
|
||||
qty: Decimal,
|
||||
basis: str,
|
||||
invoice_type: str,
|
||||
) -> Optional[Decimal]:
|
||||
) -> Decimal | None:
|
||||
if qty <= 0:
|
||||
return None
|
||||
unit_price = Decimal(str(info.get("unit_price", 0) or 0))
|
||||
|
|
@ -81,22 +102,78 @@ def _per_unit_line_currency(
|
|||
def _to_main_unit_price(
|
||||
price_on_line_unit: Decimal,
|
||||
product: Product,
|
||||
line_unit_label: Optional[str],
|
||||
line_unit_label: str | None,
|
||||
) -> Decimal:
|
||||
"""قیمت هر واحد را به واحد اصلی کالا میبرد (همتراز با منطق فاکتور در UI)."""
|
||||
main_u = (product.main_unit or "").strip()
|
||||
sec_u = (product.secondary_unit or "").strip()
|
||||
factor_raw = product.unit_conversion_factor
|
||||
factor = Decimal(str(factor_raw)) if factor_raw is not None else Decimal(1)
|
||||
if factor <= 0:
|
||||
factor = Decimal(1)
|
||||
"""Convert a line-unit price to the product main-unit price."""
|
||||
return _q2(price_line_to_main(price_on_line_unit, product, line_unit_label))
|
||||
|
||||
lu = (line_unit_label or "").strip()
|
||||
is_secondary = sec_u and lu and lu == sec_u and main_u and lu != main_u
|
||||
if is_secondary:
|
||||
# price(secondary) = price(main) * factor => price(main) = price(secondary) / factor
|
||||
return _q2(price_on_line_unit / factor)
|
||||
return _q2(price_on_line_unit)
|
||||
|
||||
def _select_multi_line_price(
|
||||
candidates: list[tuple[int, Decimal, Decimal]],
|
||||
policy: str,
|
||||
) -> Decimal:
|
||||
if policy == POLICY_LAST_LINE:
|
||||
return max(candidates, key=lambda item: item[0])[1]
|
||||
if policy == POLICY_HIGHEST_PRICE:
|
||||
return max(candidates, key=lambda item: item[1])[1]
|
||||
if policy == POLICY_LOWEST_PRICE:
|
||||
return min(candidates, key=lambda item: item[1])[1]
|
||||
total_qty = sum((item[2] for item in candidates), Decimal(0))
|
||||
if total_qty <= 0:
|
||||
return max(candidates, key=lambda item: item[0])[1]
|
||||
return _q2(sum((item[1] * item[2] for item in candidates), Decimal(0)) / total_qty)
|
||||
|
||||
|
||||
def _document_order_key(document: Document) -> tuple[str, str, int]:
|
||||
document_date = getattr(document, "document_date", None)
|
||||
registered_at = getattr(document, "registered_at", None)
|
||||
return (
|
||||
document_date.isoformat() if document_date is not None else "",
|
||||
registered_at.isoformat() if registered_at is not None else "",
|
||||
int(getattr(document, "id", 0) or 0),
|
||||
)
|
||||
|
||||
|
||||
def _source_is_newer_than_document(product: Product, document: Document) -> bool:
|
||||
"""Prevent editing an older purchase invoice from replacing a newer synced price."""
|
||||
meta = dict(getattr(product, "base_purchase_price_sync_meta", None) or {})
|
||||
source_id = meta.get("document_id")
|
||||
if source_id is None or int(source_id) == int(document.id):
|
||||
return False
|
||||
source_key = (
|
||||
str(meta.get("document_date") or ""),
|
||||
str(meta.get("registered_at") or ""),
|
||||
int(source_id),
|
||||
)
|
||||
return source_key > _document_order_key(document)
|
||||
|
||||
|
||||
def mark_deleted_purchase_price_source(
|
||||
db: Session,
|
||||
*,
|
||||
business_id: int,
|
||||
document_id: int,
|
||||
product_ids: list[int],
|
||||
) -> int:
|
||||
"""Mark prices whose originating purchase invoice was deleted for explicit review."""
|
||||
if not product_ids:
|
||||
return 0
|
||||
products = db.query(Product).filter(
|
||||
Product.business_id == int(business_id),
|
||||
Product.id.in_(sorted({int(pid) for pid in product_ids})),
|
||||
).all()
|
||||
marked = 0
|
||||
for product in products:
|
||||
meta = dict(product.base_purchase_price_sync_meta or {})
|
||||
if int(meta.get("document_id") or 0) != int(document_id):
|
||||
continue
|
||||
meta["source_document_deleted"] = True
|
||||
meta["needs_review"] = True
|
||||
meta["source_deleted_at"] = datetime.utcnow().isoformat()
|
||||
product.base_purchase_price_sync_meta = meta
|
||||
marked += 1
|
||||
db.flush()
|
||||
return marked
|
||||
|
||||
|
||||
def apply_invoice_product_price_sync(
|
||||
|
|
@ -146,11 +223,22 @@ def apply_invoice_product_price_sync(
|
|||
lines = (
|
||||
db.query(InvoiceItemLine)
|
||||
.filter(InvoiceItemLine.document_id == document.id)
|
||||
.order_by(InvoiceItemLine.id.asc())
|
||||
.all()
|
||||
)
|
||||
if not lines:
|
||||
return
|
||||
|
||||
product_ids = sorted({int(row.product_id) for row in lines if row.product_id})
|
||||
products = {
|
||||
int(product.id): product
|
||||
for product in db.query(Product).filter(
|
||||
Product.business_id == business.id,
|
||||
Product.id.in_(product_ids),
|
||||
).all()
|
||||
}
|
||||
candidates_by_product: dict[int, list[tuple[int, Decimal, Decimal]]] = {}
|
||||
|
||||
for row in lines:
|
||||
pid = row.product_id
|
||||
if not pid:
|
||||
|
|
@ -159,7 +247,12 @@ def apply_invoice_product_price_sync(
|
|||
if qty <= 0:
|
||||
continue
|
||||
info = dict(row.extra_info or {})
|
||||
per_line = _per_unit_line_currency(info, qty, basis, invoice_type)
|
||||
per_line = _per_unit_line_currency(
|
||||
info,
|
||||
qty,
|
||||
basis,
|
||||
invoice_type,
|
||||
)
|
||||
if per_line is None or per_line < 0:
|
||||
continue
|
||||
|
||||
|
|
@ -167,19 +260,44 @@ def apply_invoice_product_price_sync(
|
|||
if line_unit is not None:
|
||||
line_unit = str(line_unit).strip() or None
|
||||
|
||||
product = (
|
||||
db.query(Product)
|
||||
.filter(Product.id == int(pid), Product.business_id == business.id)
|
||||
.first()
|
||||
)
|
||||
product = products.get(int(pid))
|
||||
if not product:
|
||||
continue
|
||||
|
||||
price_main = _to_main_unit_price(per_line, product, line_unit)
|
||||
qty_main = quantity_line_to_main(qty, product, line_unit)
|
||||
candidates_by_product.setdefault(int(pid), []).append(
|
||||
(int(row.id), price_main, qty_main)
|
||||
)
|
||||
|
||||
purchase_policy = _normalize_multi_line_policy(
|
||||
getattr(business, "invoice_sync_purchase_price_multi_line_policy", None)
|
||||
)
|
||||
for pid, candidates in candidates_by_product.items():
|
||||
product = products[pid]
|
||||
if invoice_type == INVOICE_SALES and update_sales:
|
||||
product.base_sales_price = price_main
|
||||
product.base_sales_price = _select_multi_line_price(candidates, POLICY_LAST_LINE)
|
||||
elif invoice_type == INVOICE_PURCHASE and update_purchase:
|
||||
product.base_purchase_price = price_main
|
||||
if _source_is_newer_than_document(product, document):
|
||||
logger.info(
|
||||
"invoice_product_price_sync skipped older purchase document %s for product %s",
|
||||
document.id,
|
||||
product.id,
|
||||
)
|
||||
continue
|
||||
product.base_purchase_price = _select_multi_line_price(candidates, purchase_policy)
|
||||
product.base_purchase_price_sync_meta = {
|
||||
"document_id": int(document.id),
|
||||
"document_date": document.document_date.isoformat(),
|
||||
"registered_at": (
|
||||
document.registered_at.isoformat()
|
||||
if document.registered_at is not None
|
||||
else None
|
||||
),
|
||||
"line_ids": [int(item[0]) for item in candidates],
|
||||
"basis": basis,
|
||||
"multi_line_policy": purchase_policy,
|
||||
"synced_at": datetime.utcnow().isoformat(),
|
||||
}
|
||||
|
||||
db.flush()
|
||||
|
|
|
|||
|
|
@ -0,0 +1,185 @@
|
|||
"""Snapshot and resolve the purchase-price profit basis in base currency."""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from adapters.db.models.business import Business
|
||||
from adapters.db.models.document import Document
|
||||
from adapters.db.models.invoice_item_line import InvoiceItemLine
|
||||
from adapters.db.models.product import Product
|
||||
from app.core.responses import ApiError
|
||||
from app.services.invoice_unit_conversion_service import (
|
||||
effective_line_unit,
|
||||
is_secondary_line_unit,
|
||||
price_main_to_line,
|
||||
)
|
||||
|
||||
POLICY_ZERO_COST = "zero_cost"
|
||||
POLICY_USE_LINE_COST = "use_line_cost_price"
|
||||
POLICY_BLOCK = "block_calculation"
|
||||
ALLOWED_MISSING_PURCHASE_PRICE_POLICIES = frozenset(
|
||||
{POLICY_ZERO_COST, POLICY_USE_LINE_COST, POLICY_BLOCK}
|
||||
)
|
||||
|
||||
|
||||
def normalize_missing_purchase_price_policy(value: str | None) -> str:
|
||||
policy = str(value or POLICY_ZERO_COST).strip().lower()
|
||||
return policy if policy in ALLOWED_MISSING_PURCHASE_PRICE_POLICIES else POLICY_ZERO_COST
|
||||
|
||||
|
||||
def _missing_cost_for_line(line: Any, policy: str) -> tuple[Decimal, str]:
|
||||
normalized = normalize_missing_purchase_price_policy(policy)
|
||||
info = dict(getattr(line, "extra_info", None) or {})
|
||||
if normalized == POLICY_USE_LINE_COST:
|
||||
# قرارداد این گزینه: extra_info.cost_price بهای واحد ردیف در ارز پایه است.
|
||||
raw = info.get("cost_price")
|
||||
if raw is not None:
|
||||
return Decimal(str(raw)), "line_cost_price"
|
||||
raise ApiError(
|
||||
"PURCHASE_PRICE_AND_LINE_COST_REQUIRED",
|
||||
"قیمت خرید محصول و بهای ثبتشده روی ردیف هر دو نامشخص هستند",
|
||||
http_status=409,
|
||||
)
|
||||
if normalized == POLICY_BLOCK:
|
||||
raise ApiError(
|
||||
"PURCHASE_PRICE_REQUIRED",
|
||||
"برای محاسبه سود، قیمت خرید محصول باید تعیین شود",
|
||||
http_status=409,
|
||||
)
|
||||
return Decimal(0), "zero_cost_policy"
|
||||
|
||||
|
||||
def resolve_missing_purchase_price_unit_cost(line: Any, policy: str) -> Decimal:
|
||||
return _missing_cost_for_line(line, policy)[0]
|
||||
|
||||
|
||||
def _snapshot_value_for_line(
|
||||
product: Product,
|
||||
line: InvoiceItemLine,
|
||||
policy: str,
|
||||
) -> tuple[Decimal, str, str | None, Decimal]:
|
||||
info = dict(line.extra_info or {})
|
||||
line_unit = effective_line_unit(product, info.get("unit"))
|
||||
raw_factor = product.unit_conversion_factor
|
||||
factor = Decimal(str(raw_factor if raw_factor is not None else 1))
|
||||
if is_secondary_line_unit(product, line_unit):
|
||||
if factor <= 0:
|
||||
raise ApiError(
|
||||
"INVALID_UNIT_CONVERSION",
|
||||
"ضریب تبدیل واحد محصول باید بزرگتر از صفر باشد",
|
||||
http_status=409,
|
||||
)
|
||||
else:
|
||||
factor = Decimal(1)
|
||||
|
||||
if product.base_purchase_price is None:
|
||||
value, source = _missing_cost_for_line(line, policy)
|
||||
return value, source, line_unit, factor
|
||||
|
||||
value = price_main_to_line(product.base_purchase_price, product, line_unit)
|
||||
return value, "product_base_purchase_price", line_unit, factor
|
||||
|
||||
|
||||
def stamp_document_purchase_price_snapshots(
|
||||
db: Session,
|
||||
document: Document,
|
||||
*,
|
||||
overwrite: bool = False,
|
||||
) -> int:
|
||||
"""Capture base-currency unit costs for finalized sales/production lines."""
|
||||
if document.is_proforma or document.document_type not in {"invoice_sales", "invoice_production"}:
|
||||
return 0
|
||||
business = db.get(Business, int(document.business_id))
|
||||
if not business or str(business.invoice_profit_calculation_basis or "purchase_price") != "purchase_price":
|
||||
return 0
|
||||
if business.default_currency_id is None:
|
||||
raise ApiError(
|
||||
"BASE_CURRENCY_REQUIRED",
|
||||
"برای ثبت snapshot قیمت خرید، ارز پایه کسبوکار باید تعیین شده باشد",
|
||||
http_status=409,
|
||||
)
|
||||
policy = normalize_missing_purchase_price_policy(
|
||||
getattr(business, "invoice_profit_missing_purchase_price_policy", None)
|
||||
)
|
||||
lines = (
|
||||
db.query(InvoiceItemLine)
|
||||
.filter(InvoiceItemLine.document_id == int(document.id))
|
||||
.order_by(InvoiceItemLine.id.asc())
|
||||
.all()
|
||||
)
|
||||
products = {
|
||||
int(p.id): p
|
||||
for p in db.query(Product).filter(
|
||||
Product.business_id == int(document.business_id),
|
||||
Product.id.in_([int(x.product_id) for x in lines if x.product_id]),
|
||||
).all()
|
||||
}
|
||||
captured = 0
|
||||
captured_at = datetime.utcnow()
|
||||
for line in lines:
|
||||
if document.document_type == "invoice_production" and (line.extra_info or {}).get("movement") != "out":
|
||||
continue
|
||||
if not overwrite and line.purchase_price_snapshot_unit_cost_base is not None:
|
||||
continue
|
||||
product = products.get(int(line.product_id))
|
||||
if product is None:
|
||||
raise ApiError("PRODUCT_NOT_FOUND", "محصول ردیف فاکتور یافت نشد", http_status=409)
|
||||
value, source, unit, factor = _snapshot_value_for_line(product, line, policy)
|
||||
line.purchase_price_snapshot_unit_cost_base = value
|
||||
line.purchase_price_snapshot_currency_id = int(business.default_currency_id)
|
||||
line.purchase_price_snapshot_unit = unit
|
||||
line.purchase_price_snapshot_factor = factor
|
||||
line.purchase_price_snapshot_source = source
|
||||
line.purchase_price_snapshot_at = captured_at
|
||||
captured += 1
|
||||
db.flush()
|
||||
return captured
|
||||
|
||||
|
||||
def purchase_price_unit_cost_base_from_snapshot(
|
||||
line: Any,
|
||||
*,
|
||||
missing_policy: str,
|
||||
allow_legacy_ledger: bool = True,
|
||||
expected_base_currency_id: int | None = None,
|
||||
) -> Decimal:
|
||||
raw = getattr(line, "purchase_price_snapshot_unit_cost_base", None)
|
||||
if raw is not None:
|
||||
snapshot_currency_id = getattr(line, "purchase_price_snapshot_currency_id", None)
|
||||
if expected_base_currency_id is not None and snapshot_currency_id is None:
|
||||
raise ApiError(
|
||||
"PURCHASE_PRICE_SNAPSHOT_CURRENCY_MISSING",
|
||||
"ارز snapshot قیمت خرید ثبت نشده است",
|
||||
http_status=409,
|
||||
)
|
||||
if (
|
||||
expected_base_currency_id is not None
|
||||
and int(snapshot_currency_id) != int(expected_base_currency_id)
|
||||
):
|
||||
raise ApiError(
|
||||
"PURCHASE_PRICE_SNAPSHOT_CURRENCY_MISMATCH",
|
||||
"ارز snapshot قیمت خرید با ارز پایه فعلی کسبوکار یکسان نیست",
|
||||
http_status=409,
|
||||
)
|
||||
return Decimal(str(raw))
|
||||
if allow_legacy_ledger:
|
||||
legacy = getattr(line, "ledger_unit_cogs", None)
|
||||
if legacy is not None:
|
||||
return Decimal(str(legacy))
|
||||
return resolve_missing_purchase_price_unit_cost(line, missing_policy)
|
||||
|
||||
|
||||
def preview_purchase_price_unit_cost_base(
|
||||
product: Product,
|
||||
line: Any,
|
||||
*,
|
||||
missing_policy: str,
|
||||
) -> Decimal:
|
||||
if product.base_purchase_price is None:
|
||||
return resolve_missing_purchase_price_unit_cost(line, missing_policy)
|
||||
info = dict(getattr(line, "extra_info", None) or {})
|
||||
return price_main_to_line(product.base_purchase_price, product, info.get("unit"))
|
||||
|
|
@ -4406,6 +4406,9 @@ def _iter_profit_movements_from_invoice_lines(
|
|||
product_id: int,
|
||||
as_of_date: date,
|
||||
warehouse_id: Optional[int] = None,
|
||||
*,
|
||||
include_untracked: bool = False,
|
||||
normalize_quantity_to_main: bool = False,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
حرکات کالا برای محاسبه هزینه سود (FIFO/LIFO) از روی اقلام فاکتور.
|
||||
|
|
@ -4433,7 +4436,7 @@ def _iter_profit_movements_from_invoice_lines(
|
|||
movements: List[Dict[str, Any]] = []
|
||||
for line, doc in rows:
|
||||
info = line.extra_info or {}
|
||||
if info.get("inventory_tracked") is False:
|
||||
if info.get("inventory_tracked") is False and not include_untracked:
|
||||
continue
|
||||
movement = (info.get("movement") or None)
|
||||
if movement is None:
|
||||
|
|
@ -4441,6 +4444,12 @@ def _iter_profit_movements_from_invoice_lines(
|
|||
if movement not in ("in", "out"):
|
||||
continue
|
||||
qty = Decimal(str(line.quantity or 0))
|
||||
if normalize_quantity_to_main:
|
||||
from app.services.invoice_unit_conversion_service import quantity_line_to_main
|
||||
|
||||
movement_product = db.get(Product, int(product_id))
|
||||
if movement_product is not None:
|
||||
qty = quantity_line_to_main(qty, movement_product, info.get("unit"))
|
||||
if qty <= 0:
|
||||
continue
|
||||
wh_id_raw = info.get("warehouse_id")
|
||||
|
|
@ -4563,10 +4572,28 @@ def _historical_sale_line_unit_cost(
|
|||
qty = Decimal(str(ln.quantity or 0))
|
||||
|
||||
if nb == "purchase_price":
|
||||
base_cost = product.base_purchase_price or 0
|
||||
if base_cost == 0 and extra_info.get("cost_price") is not None:
|
||||
base_cost = extra_info.get("cost_price")
|
||||
return Decimal(str(base_cost))
|
||||
from app.services.invoice_purchase_price_snapshot_service import (
|
||||
purchase_price_unit_cost_base_from_snapshot,
|
||||
)
|
||||
|
||||
biz = db.get(Business, int(business_id))
|
||||
policy = getattr(biz, "invoice_profit_missing_purchase_price_policy", "zero_cost") if biz else "zero_cost"
|
||||
unit_cost_line = purchase_price_unit_cost_base_from_snapshot(
|
||||
ln,
|
||||
missing_policy=policy,
|
||||
allow_legacy_ledger=True,
|
||||
expected_base_currency_id=(
|
||||
int(biz.default_currency_id)
|
||||
if biz and biz.default_currency_id is not None
|
||||
else None
|
||||
),
|
||||
)
|
||||
snapshot_factor = getattr(ln, "purchase_price_snapshot_factor", None)
|
||||
if snapshot_factor is not None:
|
||||
return unit_cost_line * Decimal(str(snapshot_factor))
|
||||
from app.services.invoice_unit_conversion_service import price_line_to_main
|
||||
|
||||
return price_line_to_main(unit_cost_line, product, extra_info.get("unit"))
|
||||
|
||||
if nb == "cost_price":
|
||||
if extra_info.get("cost_price") is not None:
|
||||
|
|
@ -4700,6 +4727,8 @@ def _restoration_unit_cost_sales_return_match_prior_sales(
|
|||
return_mv_idx: int,
|
||||
return_document_as_of_date: date,
|
||||
prior_adjust_end_idx_exclusive: Optional[int],
|
||||
fallback_line: Optional[Any] = None,
|
||||
missing_purchase_price_policy: str = "zero_cost",
|
||||
) -> Decimal:
|
||||
"""
|
||||
واحد بازگشت جریمهٔ COGS برای برگشت از فروش: تخصیص LIFO نسبت به مقادیر باقیماندهٔ
|
||||
|
|
@ -4776,8 +4805,33 @@ def _restoration_unit_cost_sales_return_match_prior_sales(
|
|||
j -= 1
|
||||
|
||||
if qty_left > 0:
|
||||
avg_fallback = _calculate_average_purchase_cost(db, business_id, product_id, return_document_as_of_date)
|
||||
sum_cost += qty_left * avg_fallback
|
||||
if _normalize_invoice_profit_basis(normalized_basis) == "purchase_price":
|
||||
from app.services.invoice_purchase_price_snapshot_service import (
|
||||
resolve_missing_purchase_price_unit_cost,
|
||||
)
|
||||
|
||||
fallback_line_unit = resolve_missing_purchase_price_unit_cost(
|
||||
fallback_line,
|
||||
missing_purchase_price_policy,
|
||||
)
|
||||
from app.services.invoice_unit_conversion_service import price_line_to_main
|
||||
|
||||
fallback_product = db.get(Product, int(product_id))
|
||||
fallback_info = dict(getattr(fallback_line, "extra_info", None) or {})
|
||||
fallback = (
|
||||
price_line_to_main(
|
||||
fallback_line_unit,
|
||||
fallback_product,
|
||||
fallback_info.get("unit"),
|
||||
)
|
||||
if fallback_product is not None
|
||||
else fallback_line_unit
|
||||
)
|
||||
else:
|
||||
fallback = _calculate_average_purchase_cost(
|
||||
db, business_id, product_id, return_document_as_of_date
|
||||
)
|
||||
sum_cost += qty_left * fallback
|
||||
qty_left = Decimal(0)
|
||||
|
||||
return sum_cost / qty_need if qty_need > 0 else Decimal(0)
|
||||
|
|
@ -5112,7 +5166,22 @@ def _get_cost_per_unit_by_basis(
|
|||
sm = _normalize_invoice_profit_fifo_shortage_mode(fifo_shortage_mode)
|
||||
|
||||
if normalized_basis == "purchase_price":
|
||||
return Decimal(str(product.base_purchase_price or 0))
|
||||
from app.services.invoice_purchase_price_snapshot_service import (
|
||||
purchase_price_unit_cost_base_from_snapshot,
|
||||
)
|
||||
|
||||
biz = db.get(Business, int(business_id))
|
||||
policy = getattr(biz, "invoice_profit_missing_purchase_price_policy", "zero_cost") if biz else "zero_cost"
|
||||
return purchase_price_unit_cost_base_from_snapshot(
|
||||
line,
|
||||
missing_policy=policy,
|
||||
allow_legacy_ledger=True,
|
||||
expected_base_currency_id=(
|
||||
int(biz.default_currency_id)
|
||||
if biz and biz.default_currency_id is not None
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
elif normalized_basis == "cost_price":
|
||||
if extra_info.get("cost_price") is not None:
|
||||
|
|
@ -5242,15 +5311,32 @@ def _invoice_profit_line_sale_cost_per_unit(
|
|||
warehouse_id: Any,
|
||||
document_id_hdr: int,
|
||||
fifo_sm: str,
|
||||
*,
|
||||
missing_purchase_price_policy: str = "zero_cost",
|
||||
allow_current_purchase_price_preview: bool = False,
|
||||
expected_base_currency_id: int | None = None,
|
||||
) -> Decimal:
|
||||
"""بهای هر واحد در ردیف فاکتور فروش یا خدمت (مسیر عمومی)، بدون منطق خاص بازگشت کالای ورودی."""
|
||||
extra_info = item_line.extra_info or {}
|
||||
|
||||
if normalized_basis == "purchase_price":
|
||||
base_cost = product.base_purchase_price or 0
|
||||
if base_cost == 0 and extra_info.get("cost_price") is not None:
|
||||
base_cost = extra_info.get("cost_price")
|
||||
return Decimal(str(base_cost))
|
||||
from app.services.invoice_purchase_price_snapshot_service import (
|
||||
preview_purchase_price_unit_cost_base,
|
||||
purchase_price_unit_cost_base_from_snapshot,
|
||||
)
|
||||
|
||||
if allow_current_purchase_price_preview:
|
||||
return preview_purchase_price_unit_cost_base(
|
||||
product,
|
||||
item_line,
|
||||
missing_policy=missing_purchase_price_policy,
|
||||
)
|
||||
return purchase_price_unit_cost_base_from_snapshot(
|
||||
item_line,
|
||||
missing_policy=missing_purchase_price_policy,
|
||||
allow_legacy_ledger=True,
|
||||
expected_base_currency_id=expected_base_currency_id,
|
||||
)
|
||||
|
||||
if normalized_basis == "cost_price":
|
||||
if extra_info.get("cost_price") is not None:
|
||||
|
|
@ -5471,6 +5557,32 @@ def _calculate_invoice_profit(
|
|||
if document.document_type not in ["invoice_sales", "invoice_sales_return", "invoice_production"]:
|
||||
return _empty_profit_response()
|
||||
|
||||
business = db.get(Business, int(business_id))
|
||||
if not business or business.default_currency_id is None:
|
||||
raise ApiError(
|
||||
"BASE_CURRENCY_REQUIRED",
|
||||
"برای محاسبه سود، ارز پایه کسبوکار باید تعیین شده باشد",
|
||||
http_status=409,
|
||||
)
|
||||
from app.services.document_line_fx_service import resolve_document_fx_rate
|
||||
|
||||
profit_fx_rate, _profit_fx_source = resolve_document_fx_rate(
|
||||
db,
|
||||
document,
|
||||
business=business,
|
||||
allow_infer=True,
|
||||
fallback_one_on_missing=False,
|
||||
)
|
||||
if profit_fx_rate is None or profit_fx_rate <= 0:
|
||||
raise ApiError(
|
||||
"INVOICE_FX_RATE_REQUIRED_FOR_PROFIT",
|
||||
"نرخ تبدیل ارز سند به ارز پایه برای محاسبه سود موجود نیست",
|
||||
http_status=409,
|
||||
)
|
||||
missing_purchase_price_policy = getattr(
|
||||
business, "invoice_profit_missing_purchase_price_policy", "zero_cost"
|
||||
)
|
||||
|
||||
total_gross_profit = Decimal(0)
|
||||
total_net_profit = Decimal(0)
|
||||
total_sales = Decimal(0)
|
||||
|
|
@ -5517,8 +5629,10 @@ def _calculate_invoice_profit(
|
|||
if line.product_id:
|
||||
product = db.query(Product).filter(Product.id == line.product_id).first()
|
||||
if unit_price <= 0 and product is not None:
|
||||
unit_price = Decimal(str(product.base_sales_price or 0))
|
||||
sales_amt = qty * unit_price
|
||||
# base_sales_price در ارز پایه است؛ unit_price پاسخ باید در ارز سند بماند.
|
||||
unit_price = Decimal(str(product.base_sales_price or 0)) / profit_fx_rate
|
||||
sales_amt_document = qty * unit_price
|
||||
sales_amt = sales_amt_document * profit_fx_rate
|
||||
pname = (product.name if product else None) or (line.description or "").strip() or "—"
|
||||
pcode = product.code if product else None
|
||||
pid_i = int(product.id) if product else (int(line.product_id) if line.product_id else None)
|
||||
|
|
@ -5526,6 +5640,8 @@ def _calculate_invoice_profit(
|
|||
"line": line,
|
||||
"qty": qty,
|
||||
"unit_price": unit_price,
|
||||
"unit_price_base": unit_price * profit_fx_rate,
|
||||
"sales_amount_document": sales_amt_document,
|
||||
"sales_amount": sales_amt,
|
||||
"product_code": pcode,
|
||||
"product_name": pname,
|
||||
|
|
@ -5562,6 +5678,8 @@ def _calculate_invoice_profit(
|
|||
"product_name": spec["product_name"],
|
||||
"quantity": float(qty),
|
||||
"unit_price": float(unit_price),
|
||||
"unit_price_base": float(spec["unit_price_base"]),
|
||||
"sales_amount_document": float(spec["sales_amount_document"]),
|
||||
"cost_per_unit": float(line_cost / qty) if qty > 0 else 0,
|
||||
"sales_amount": float(sales_amount),
|
||||
"total_cost": float(line_cost),
|
||||
|
|
@ -5601,12 +5719,14 @@ def _calculate_invoice_profit(
|
|||
int(pid_v),
|
||||
document.document_date,
|
||||
warehouse_id=wh_key,
|
||||
include_untracked=(normalized_basis == "purchase_price"),
|
||||
normalize_quantity_to_main=(normalized_basis == "purchase_price"),
|
||||
)
|
||||
return mv_cache[cache_k]
|
||||
|
||||
gd_amt = _document_global_discount_amount_for_profit(document, item_lines)
|
||||
gd_alloc = _allocate_global_discount_to_lines(item_lines, gd_amt, is_sales_return=is_sales_return)
|
||||
adjustments_net_total = _document_adjustments_net_for_profit(document)
|
||||
adjustments_net_total = _document_adjustments_net_for_profit(document) * profit_fx_rate
|
||||
|
||||
profit_rows: List[Dict[str, Any]] = []
|
||||
|
||||
|
|
@ -5629,11 +5749,12 @@ def _calculate_invoice_profit(
|
|||
|
||||
if is_sales_return:
|
||||
if raw_after_global > 0:
|
||||
sales_amount = -raw_after_global
|
||||
sales_amount_document = -raw_after_global
|
||||
else:
|
||||
sales_amount = raw_after_global
|
||||
sales_amount_document = raw_after_global
|
||||
else:
|
||||
sales_amount = raw_after_global
|
||||
sales_amount_document = raw_after_global
|
||||
sales_amount = sales_amount_document * profit_fx_rate
|
||||
|
||||
product = None
|
||||
if item_line.product_id:
|
||||
|
|
@ -5654,17 +5775,28 @@ def _calculate_invoice_profit(
|
|||
|
||||
if product:
|
||||
inbound_return_goods = (
|
||||
bool(is_sales_return) and (effective_move == "in") and inv_tracked_ok is not False
|
||||
bool(is_sales_return)
|
||||
and (effective_move == "in")
|
||||
and (inv_tracked_ok is not False or normalized_basis == "purchase_price")
|
||||
)
|
||||
|
||||
if inbound_return_goods:
|
||||
cp_raw = extra_info.get("cost_price")
|
||||
if cp_raw is not None:
|
||||
if cp_raw is not None and normalized_basis != "purchase_price":
|
||||
cost_per_unit = Decimal(str(cp_raw))
|
||||
else:
|
||||
mvl = _mv_list_pid_wh(product.id, wh_iter)
|
||||
idx_ln = _find_profit_movement_index_for_line(mvl, int(item_line.id))
|
||||
if idx_ln is not None:
|
||||
restoration_qty_for_match = qty
|
||||
if normalized_basis == "purchase_price":
|
||||
from app.services.invoice_unit_conversion_service import quantity_line_to_main
|
||||
|
||||
restoration_qty_for_match = quantity_line_to_main(
|
||||
qty,
|
||||
product,
|
||||
extra_info.get("unit"),
|
||||
)
|
||||
cost_per_unit = _restoration_unit_cost_sales_return_match_prior_sales(
|
||||
db,
|
||||
business_id,
|
||||
|
|
@ -5672,11 +5804,31 @@ def _calculate_invoice_profit(
|
|||
wh_iter,
|
||||
normalized_basis=normalized_basis,
|
||||
fifo_sm=fifo_sm,
|
||||
restoration_qty=qty,
|
||||
restoration_qty=restoration_qty_for_match,
|
||||
movements=mvl,
|
||||
return_mv_idx=int(idx_ln),
|
||||
return_document_as_of_date=document.document_date,
|
||||
prior_adjust_end_idx_exclusive=int(idx_ln),
|
||||
fallback_line=item_line,
|
||||
missing_purchase_price_policy=missing_purchase_price_policy,
|
||||
)
|
||||
if normalized_basis == "purchase_price":
|
||||
from app.services.invoice_unit_conversion_service import price_main_to_line
|
||||
|
||||
cost_per_unit = price_main_to_line(
|
||||
cost_per_unit,
|
||||
product,
|
||||
extra_info.get("unit"),
|
||||
)
|
||||
else:
|
||||
if normalized_basis == "purchase_price":
|
||||
from app.services.invoice_purchase_price_snapshot_service import (
|
||||
resolve_missing_purchase_price_unit_cost,
|
||||
)
|
||||
|
||||
cost_per_unit = resolve_missing_purchase_price_unit_cost(
|
||||
item_line,
|
||||
missing_purchase_price_policy,
|
||||
)
|
||||
else:
|
||||
cost_per_unit = _calculate_average_purchase_cost(
|
||||
|
|
@ -5696,6 +5848,9 @@ def _calculate_invoice_profit(
|
|||
warehouse_id,
|
||||
int(document.id),
|
||||
fifo_sm,
|
||||
missing_purchase_price_policy=missing_purchase_price_policy,
|
||||
allow_current_purchase_price_preview=bool(document.is_proforma),
|
||||
expected_base_currency_id=int(business.default_currency_id),
|
||||
)
|
||||
total_line_cost = qty * cost_per_unit
|
||||
line_gross_profit = sales_amount - total_line_cost
|
||||
|
|
@ -5722,6 +5877,8 @@ def _calculate_invoice_profit(
|
|||
"product_name": pname,
|
||||
"quantity": float(qty),
|
||||
"unit_price": float(unit_price),
|
||||
"unit_price_base": float(unit_price * profit_fx_rate),
|
||||
"sales_amount_document": float(sales_amount_document),
|
||||
"cost_per_unit": float(cost_per_unit),
|
||||
"sales_amount": sales_amount,
|
||||
"total_line_cost": total_line_cost,
|
||||
|
|
@ -5769,6 +5926,8 @@ def _calculate_invoice_profit(
|
|||
"product_name": pr["product_name"],
|
||||
"quantity": pr["quantity"],
|
||||
"unit_price": pr["unit_price"],
|
||||
"unit_price_base": pr["unit_price_base"],
|
||||
"sales_amount_document": pr["sales_amount_document"],
|
||||
"cost_per_unit": pr["cost_per_unit"],
|
||||
"sales_amount": float(pr["sales_amount"]),
|
||||
"total_cost": float(tlc),
|
||||
|
|
@ -5802,6 +5961,9 @@ def _calculate_invoice_profit(
|
|||
"total_cost": float(total_cost),
|
||||
"total_sales": float(total_sales),
|
||||
"line_profits": line_profits,
|
||||
"profit_currency_id": int(business.default_currency_id),
|
||||
"document_currency_id": int(document.currency_id) if document.currency_id else None,
|
||||
"document_to_base_rate": float(profit_fx_rate),
|
||||
}
|
||||
|
||||
if normalized_type in ["gross", "both"]:
|
||||
|
|
@ -6743,6 +6905,15 @@ def create_invoice(
|
|||
description="تعدیل هزینه پورسانت",
|
||||
))
|
||||
|
||||
# snapshot قیمت خرید فروش/مصرف تولید قبل از هر محاسبه ledger یا تغییر بعدی قیمت کالا
|
||||
if not document.is_proforma:
|
||||
db.flush()
|
||||
from app.services.invoice_purchase_price_snapshot_service import (
|
||||
stamp_document_purchase_price_snapshots,
|
||||
)
|
||||
|
||||
stamp_document_purchase_price_snapshots(db, document, overwrite=False)
|
||||
|
||||
# همگامسازی قیمت پایه کالا (ارز پیشفرض کسبوکار) از فاکتور قطعی
|
||||
# Session با autoflush=False است؛ بدون flush، کوئری invoice_item_lines خالی میماند.
|
||||
if not document.is_proforma:
|
||||
|
|
@ -8140,6 +8311,14 @@ def update_invoice(
|
|||
http_status=409,
|
||||
) from cost_ex
|
||||
|
||||
if not document.is_proforma:
|
||||
db.flush()
|
||||
from app.services.invoice_purchase_price_snapshot_service import (
|
||||
stamp_document_purchase_price_snapshots,
|
||||
)
|
||||
|
||||
stamp_document_purchase_price_snapshots(db, document, overwrite=False)
|
||||
|
||||
if not document.is_proforma:
|
||||
db.flush()
|
||||
from adapters.db.models.business import Business as _BizForPriceSyncU
|
||||
|
|
@ -8341,6 +8520,10 @@ def delete_invoice(db: Session, document_id: int, *, commit: bool = True) -> boo
|
|||
logger.error(f"[DELETE_INVOICE] Invoice {document_id}: Invalid document type {document.document_type}")
|
||||
raise ApiError("INVALID_DOCUMENT_TYPE", "Document is not an invoice", http_status=400)
|
||||
|
||||
_deleted_invoice_product_ids = _distinct_product_ids_for_invoice(
|
||||
db, int(document.id)
|
||||
)
|
||||
|
||||
_deleted_production_order_id: Optional[int] = None
|
||||
if document.document_type == INVOICE_PRODUCTION:
|
||||
raw_order_id = (document.extra_info or {}).get("production_order_id")
|
||||
|
|
@ -8574,6 +8757,18 @@ def delete_invoice(db: Session, document_id: int, *, commit: bool = True) -> boo
|
|||
document_type = document.document_type
|
||||
project_id = document.project_id
|
||||
|
||||
if document_type == INVOICE_PURCHASE and _deleted_invoice_product_ids:
|
||||
from app.services.invoice_product_price_sync_service import (
|
||||
mark_deleted_purchase_price_source,
|
||||
)
|
||||
|
||||
mark_deleted_purchase_price_source(
|
||||
db,
|
||||
business_id=int(business_id),
|
||||
document_id=int(document_id),
|
||||
product_ids=_deleted_invoice_product_ids,
|
||||
)
|
||||
|
||||
# برگشت امتیاز باشگاه مشتریان (قبل از حذف سند)
|
||||
try:
|
||||
from app.services.customer_club_service import reverse_customer_club_on_invoice_delete
|
||||
|
|
@ -8851,6 +9046,23 @@ def invoice_document_to_dict(
|
|||
row_dict["ledger_recognized_at"] = it.ledger_recognized_at.isoformat()
|
||||
if getattr(it, "ledger_recognition_event", None):
|
||||
row_dict["ledger_recognition_event"] = it.ledger_recognition_event
|
||||
if getattr(it, "purchase_price_snapshot_unit_cost_base", None) is not None:
|
||||
row_dict["purchase_price_snapshot"] = {
|
||||
"unit_cost_base": float(it.purchase_price_snapshot_unit_cost_base),
|
||||
"currency_id": it.purchase_price_snapshot_currency_id,
|
||||
"unit": it.purchase_price_snapshot_unit,
|
||||
"unit_conversion_factor": (
|
||||
float(it.purchase_price_snapshot_factor)
|
||||
if it.purchase_price_snapshot_factor is not None
|
||||
else None
|
||||
),
|
||||
"source": it.purchase_price_snapshot_source,
|
||||
"captured_at": (
|
||||
it.purchase_price_snapshot_at.isoformat()
|
||||
if it.purchase_price_snapshot_at is not None
|
||||
else None
|
||||
),
|
||||
}
|
||||
product_lines.append(row_dict)
|
||||
|
||||
# سطرهای حسابداری از document_lines خوانده میشوند
|
||||
|
|
@ -8960,6 +9172,8 @@ def invoice_document_to_dict(
|
|||
result["total_cost"] = profit_data.get("total_cost", 0.0)
|
||||
result["total_sales"] = profit_data.get("total_sales", 0.0)
|
||||
result["line_profits"] = profit_data.get("line_profits", [])
|
||||
result["profit_currency_id"] = profit_data.get("profit_currency_id")
|
||||
result["document_to_base_rate"] = profit_data.get("document_to_base_rate")
|
||||
# پسزمینه: gross_profit / line_profits = محاسبه تحلیلی زنده (تنظیمات جاری)
|
||||
result["profit_calculation_context"] = "analytical_live"
|
||||
|
||||
|
|
@ -11783,6 +11997,8 @@ def invoice_documents_to_list_dicts(
|
|||
if "total_profit" in profit_data:
|
||||
item["total_profit"] = profit_data["total_profit"]
|
||||
item["total_profit_percent"] = profit_data["total_profit_percent"]
|
||||
item["profit_currency_id"] = profit_data.get("profit_currency_id")
|
||||
item["document_to_base_rate"] = profit_data.get("document_to_base_rate")
|
||||
|
||||
return results
|
||||
|
||||
|
|
|
|||
83
hesabixAPI/app/services/invoice_unit_conversion_service.py
Normal file
83
hesabixAPI/app/services/invoice_unit_conversion_service.py
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
"""Canonical invoice unit conversions.
|
||||
|
||||
Contract: ``Product.unit_conversion_factor`` is the number of secondary units
|
||||
contained in one main unit. Example: main=carton, secondary=item, factor=20.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from app.core.responses import ApiError
|
||||
|
||||
|
||||
def _d(value: Any) -> Decimal:
|
||||
return Decimal(str(value if value is not None else 0))
|
||||
|
||||
|
||||
def _labels(product: Any) -> tuple[str | None, str | None]:
|
||||
main = str(getattr(product, "main_unit", None) or "").strip() or None
|
||||
secondary = str(getattr(product, "secondary_unit", None) or "").strip() or None
|
||||
return main, secondary
|
||||
|
||||
|
||||
def _factor(product: Any) -> Decimal:
|
||||
raw = getattr(product, "unit_conversion_factor", None)
|
||||
factor = _d(raw)
|
||||
if factor <= 0:
|
||||
raise ApiError(
|
||||
"INVALID_UNIT_CONVERSION",
|
||||
"ضریب تبدیل واحد محصول باید بزرگتر از صفر باشد",
|
||||
http_status=409,
|
||||
)
|
||||
return factor
|
||||
|
||||
|
||||
def is_secondary_line_unit(product: Any, line_unit: str | None) -> bool:
|
||||
main, secondary = _labels(product)
|
||||
selected = str(line_unit or "").strip() or main
|
||||
if selected is None or main is None or selected == main:
|
||||
return False
|
||||
if secondary is not None and selected == secondary:
|
||||
return True
|
||||
raise ApiError(
|
||||
"INVALID_LINE_UNIT",
|
||||
"واحد ردیف با واحد اصلی یا فرعی محصول مطابقت ندارد",
|
||||
http_status=409,
|
||||
)
|
||||
|
||||
|
||||
def quantity_line_to_main(quantity: Any, product: Any, line_unit: str | None) -> Decimal:
|
||||
qty = _d(quantity)
|
||||
if is_secondary_line_unit(product, line_unit):
|
||||
return qty / _factor(product)
|
||||
return qty
|
||||
|
||||
|
||||
def price_main_to_line(price_on_main: Any, product: Any, line_unit: str | None) -> Decimal:
|
||||
price = _d(price_on_main)
|
||||
if is_secondary_line_unit(product, line_unit):
|
||||
return price / _factor(product)
|
||||
return price
|
||||
|
||||
|
||||
def price_line_to_main(price_on_line: Any, product: Any, line_unit: str | None) -> Decimal:
|
||||
price = _d(price_on_line)
|
||||
if is_secondary_line_unit(product, line_unit):
|
||||
return price * _factor(product)
|
||||
return price
|
||||
|
||||
|
||||
def effective_line_unit(product: Any, line_unit: str | None) -> str | None:
|
||||
main, secondary = _labels(product)
|
||||
selected = str(line_unit or "").strip() or main
|
||||
if selected is None or selected == main:
|
||||
return main
|
||||
if secondary is not None and selected == secondary:
|
||||
return secondary
|
||||
raise ApiError(
|
||||
"INVALID_LINE_UNIT",
|
||||
"واحد ردیف با واحد اصلی یا فرعی محصول مطابقت ندارد",
|
||||
http_status=409,
|
||||
)
|
||||
|
|
@ -214,6 +214,7 @@ def apply_fx_prices_to_base_for_product(
|
|||
new_purch = quantize_money(purchase_fx * rate, base_quant, round_on=round_on)
|
||||
if product.base_purchase_price != new_purch:
|
||||
product.base_purchase_price = new_purch
|
||||
product.base_purchase_price_sync_meta = None
|
||||
changed = True
|
||||
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -907,6 +907,7 @@ def update_product(
|
|||
price_update_kwargs["base_sales_note"] = payload.base_sales_note
|
||||
if "base_purchase_price" in fields_set:
|
||||
price_update_kwargs["base_purchase_price"] = payload.base_purchase_price
|
||||
price_update_kwargs["base_purchase_price_sync_meta"] = None
|
||||
if "base_purchase_note" in fields_set:
|
||||
price_update_kwargs["base_purchase_note"] = payload.base_purchase_note
|
||||
if "sales_price_fx" in fields_set:
|
||||
|
|
@ -1455,6 +1456,7 @@ def _to_dict(obj: Product, db: Optional[Session] = None) -> Dict[str, Any]:
|
|||
"base_sales_price": obj.base_sales_price,
|
||||
"base_sales_note": obj.base_sales_note,
|
||||
"base_purchase_price": obj.base_purchase_price,
|
||||
"base_purchase_price_sync_meta": getattr(obj, "base_purchase_price_sync_meta", None),
|
||||
"base_purchase_note": obj.base_purchase_note,
|
||||
"sales_price_fx": getattr(obj, "sales_price_fx", None),
|
||||
"purchase_price_fx": getattr(obj, "purchase_price_fx", None),
|
||||
|
|
|
|||
|
|
@ -0,0 +1,54 @@
|
|||
"""Purchase-price profit contracts and line snapshots.
|
||||
|
||||
Revision ID: 20261026_000001_purchase_price_profit_contracts
|
||||
Revises: 20261025_000001_customer_club_rewards_campaigns
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "20261026_000001_purchase_price_profit_contracts"
|
||||
down_revision = "20261025_000001_customer_club_rewards_campaigns"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column(
|
||||
"businesses",
|
||||
sa.Column(
|
||||
"invoice_profit_missing_purchase_price_policy",
|
||||
sa.String(length=40),
|
||||
nullable=False,
|
||||
server_default="zero_cost",
|
||||
),
|
||||
)
|
||||
op.add_column(
|
||||
"businesses",
|
||||
sa.Column(
|
||||
"invoice_sync_purchase_price_multi_line_policy",
|
||||
sa.String(length=40),
|
||||
nullable=False,
|
||||
server_default="weighted_average",
|
||||
),
|
||||
)
|
||||
op.add_column("invoice_item_lines", sa.Column("purchase_price_snapshot_unit_cost_base", sa.Numeric(18, 6), nullable=True))
|
||||
op.add_column("invoice_item_lines", sa.Column("purchase_price_snapshot_currency_id", sa.Integer(), nullable=True))
|
||||
op.add_column("invoice_item_lines", sa.Column("purchase_price_snapshot_unit", sa.String(length=32), nullable=True))
|
||||
op.add_column("invoice_item_lines", sa.Column("purchase_price_snapshot_factor", sa.Numeric(18, 6), nullable=True))
|
||||
op.add_column("invoice_item_lines", sa.Column("purchase_price_snapshot_source", sa.String(length=40), nullable=True))
|
||||
op.add_column("invoice_item_lines", sa.Column("purchase_price_snapshot_at", sa.DateTime(), nullable=True))
|
||||
op.add_column("products", sa.Column("base_purchase_price_sync_meta", sa.JSON(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("products", "base_purchase_price_sync_meta")
|
||||
op.drop_column("invoice_item_lines", "purchase_price_snapshot_at")
|
||||
op.drop_column("invoice_item_lines", "purchase_price_snapshot_source")
|
||||
op.drop_column("invoice_item_lines", "purchase_price_snapshot_factor")
|
||||
op.drop_column("invoice_item_lines", "purchase_price_snapshot_unit")
|
||||
op.drop_column("invoice_item_lines", "purchase_price_snapshot_currency_id")
|
||||
op.drop_column("invoice_item_lines", "purchase_price_snapshot_unit_cost_base")
|
||||
op.drop_column("businesses", "invoice_sync_purchase_price_multi_line_policy")
|
||||
op.drop_column("businesses", "invoice_profit_missing_purchase_price_policy")
|
||||
|
|
@ -9,6 +9,7 @@ from app.services.invoice_cogs_gl_service import (
|
|||
COGS_GL_SIDE,
|
||||
INVENTORY_COGS_GL_SIDE,
|
||||
_amounts_close,
|
||||
_base_cogs_to_document_currency,
|
||||
_evaluate_should_have_cogs_gl,
|
||||
_existing_cogs_gl_amount,
|
||||
_is_cogs_gl_line,
|
||||
|
|
@ -48,6 +49,24 @@ class TestCogsGlLineHelpers:
|
|||
assert _amounts_close(Decimal("100"), Decimal("100.005"))
|
||||
assert not _amounts_close(Decimal("100"), Decimal("100.02"))
|
||||
|
||||
@patch(
|
||||
"app.services.document_line_fx_service.resolve_document_fx_rate",
|
||||
return_value=(Decimal("2"), "snapshot"),
|
||||
)
|
||||
@patch(
|
||||
"app.services.currency_quant.get_currency_quant_and_round",
|
||||
return_value=(Decimal("0.01"), True),
|
||||
)
|
||||
def test_base_cogs_is_converted_back_to_document_currency(
|
||||
self,
|
||||
_mock_quant,
|
||||
_mock_rate,
|
||||
):
|
||||
document = SimpleNamespace(currency_id=2)
|
||||
assert _base_cogs_to_document_currency(
|
||||
MagicMock(), document, Decimal("1000")
|
||||
) == Decimal("500.00")
|
||||
|
||||
|
||||
class TestEvaluateShouldHaveCogsGl:
|
||||
def test_proforma_never(self):
|
||||
|
|
@ -106,6 +125,7 @@ class TestEvaluateShouldHaveCogsGl:
|
|||
|
||||
|
||||
class TestResyncInvoiceCogsGlLines:
|
||||
@patch("app.services.invoice_cogs_gl_service._base_cogs_to_document_currency")
|
||||
@patch("app.services.invoice_cogs_gl_service._post_cogs_gl_lines")
|
||||
@patch("app.services.invoice_cogs_gl_service._resolve_cogs_gl_accounts")
|
||||
@patch("app.services.invoice_cogs_gl_service._calculate_invoice_cogs_amount_for_gl")
|
||||
|
|
@ -118,6 +138,7 @@ class TestResyncInvoiceCogsGlLines:
|
|||
mock_calc,
|
||||
mock_resolve,
|
||||
mock_post,
|
||||
mock_convert,
|
||||
):
|
||||
db = MagicMock()
|
||||
document = SimpleNamespace(
|
||||
|
|
@ -130,12 +151,16 @@ class TestResyncInvoiceCogsGlLines:
|
|||
cogs_line = _line(COGS_GL_SIDE, debit=0)
|
||||
db.query.return_value.filter.return_value.all.side_effect = [
|
||||
[cogs_line],
|
||||
[],
|
||||
[
|
||||
SimpleNamespace(account_id=1, debit=250000, credit=0),
|
||||
SimpleNamespace(account_id=2, debit=0, credit=250000),
|
||||
],
|
||||
]
|
||||
db.query.return_value.filter.return_value.first.return_value = document
|
||||
|
||||
mock_should.return_value = True
|
||||
mock_calc.return_value = Decimal("250000")
|
||||
mock_convert.return_value = Decimal("250000")
|
||||
mock_resolve.return_value = (
|
||||
SimpleNamespace(id=1, code="40001"),
|
||||
SimpleNamespace(id=2, code="10102"),
|
||||
|
|
@ -174,6 +199,7 @@ class TestResyncInvoiceCogsGlLines:
|
|||
mock_remove.assert_called_once_with(db, 7)
|
||||
mock_calc.assert_not_called()
|
||||
|
||||
@patch("app.services.invoice_cogs_gl_service._base_cogs_to_document_currency")
|
||||
@patch("app.services.invoice_cogs_gl_service._post_cogs_gl_lines")
|
||||
@patch("app.services.invoice_cogs_gl_service._resolve_cogs_gl_accounts")
|
||||
@patch("app.services.invoice_cogs_gl_service._calculate_invoice_cogs_amount_for_gl")
|
||||
|
|
@ -186,6 +212,7 @@ class TestResyncInvoiceCogsGlLines:
|
|||
mock_calc,
|
||||
mock_resolve,
|
||||
mock_post,
|
||||
mock_convert,
|
||||
):
|
||||
db = MagicMock()
|
||||
document = SimpleNamespace(
|
||||
|
|
@ -201,6 +228,7 @@ class TestResyncInvoiceCogsGlLines:
|
|||
|
||||
mock_should.return_value = True
|
||||
mock_calc.return_value = Decimal("1000")
|
||||
mock_convert.return_value = Decimal("1000")
|
||||
|
||||
assert resync_invoice_cogs_gl_lines(db, 99) is True
|
||||
mock_remove.assert_not_called()
|
||||
|
|
|
|||
139
hesabixAPI/tests/test_invoice_purchase_price_contracts.py
Normal file
139
hesabixAPI/tests/test_invoice_purchase_price_contracts.py
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from adapters.api.v1.schemas import BusinessUpdateRequest
|
||||
from app.core.responses import ApiError
|
||||
from app.services.invoice_product_price_sync_service import (
|
||||
POLICY_HIGHEST_PRICE,
|
||||
POLICY_LAST_LINE,
|
||||
POLICY_LOWEST_PRICE,
|
||||
POLICY_WEIGHTED_AVERAGE,
|
||||
_select_multi_line_price,
|
||||
_source_is_newer_than_document,
|
||||
_to_main_unit_price,
|
||||
)
|
||||
from app.services.invoice_purchase_price_snapshot_service import (
|
||||
_snapshot_value_for_line,
|
||||
purchase_price_unit_cost_base_from_snapshot,
|
||||
resolve_missing_purchase_price_unit_cost,
|
||||
)
|
||||
from app.services.invoice_unit_conversion_service import (
|
||||
price_line_to_main,
|
||||
price_main_to_line,
|
||||
quantity_line_to_main,
|
||||
)
|
||||
|
||||
|
||||
def _product(*, purchase_price=Decimal("2000")):
|
||||
return SimpleNamespace(
|
||||
main_unit="کارتن",
|
||||
secondary_unit="عدد",
|
||||
unit_conversion_factor=Decimal("20"),
|
||||
base_purchase_price=purchase_price,
|
||||
)
|
||||
|
||||
|
||||
def _line(*, unit="عدد", cost_price=None):
|
||||
info = {"unit": unit}
|
||||
if cost_price is not None:
|
||||
info["cost_price"] = cost_price
|
||||
return SimpleNamespace(extra_info=info)
|
||||
|
||||
|
||||
def test_unit_conversion_contract_is_secondary_units_per_main_unit():
|
||||
product = _product()
|
||||
assert quantity_line_to_main(Decimal("20"), product, "عدد") == Decimal("1")
|
||||
assert price_main_to_line(Decimal("2000"), product, "عدد") == Decimal("100")
|
||||
assert price_line_to_main(Decimal("100"), product, "عدد") == Decimal("2000")
|
||||
assert _to_main_unit_price(Decimal("100"), product, "عدد") == Decimal("2000.00")
|
||||
|
||||
|
||||
def test_purchase_price_snapshot_is_base_currency_price_on_line_unit():
|
||||
value, source, unit, factor = _snapshot_value_for_line(
|
||||
_product(),
|
||||
_line(unit="عدد"),
|
||||
"block_calculation",
|
||||
)
|
||||
assert value == Decimal("100")
|
||||
assert source == "product_base_purchase_price"
|
||||
assert unit == "عدد"
|
||||
assert factor == Decimal("20")
|
||||
|
||||
|
||||
def test_missing_purchase_price_policies_are_explicit():
|
||||
assert resolve_missing_purchase_price_unit_cost(_line(), "zero_cost") == Decimal("0")
|
||||
assert resolve_missing_purchase_price_unit_cost(
|
||||
_line(cost_price="125.5"), "use_line_cost_price"
|
||||
) == Decimal("125.5")
|
||||
with pytest.raises(ApiError):
|
||||
resolve_missing_purchase_price_unit_cost(_line(), "use_line_cost_price")
|
||||
with pytest.raises(ApiError):
|
||||
resolve_missing_purchase_price_unit_cost(_line(), "block_calculation")
|
||||
|
||||
|
||||
def test_snapshot_currency_must_match_current_business_base_currency():
|
||||
line = SimpleNamespace(
|
||||
purchase_price_snapshot_unit_cost_base=Decimal("100"),
|
||||
purchase_price_snapshot_currency_id=1,
|
||||
)
|
||||
assert purchase_price_unit_cost_base_from_snapshot(
|
||||
line,
|
||||
missing_policy="zero_cost",
|
||||
expected_base_currency_id=1,
|
||||
) == Decimal("100")
|
||||
with pytest.raises(ApiError):
|
||||
purchase_price_unit_cost_base_from_snapshot(
|
||||
line,
|
||||
missing_policy="zero_cost",
|
||||
expected_base_currency_id=2,
|
||||
)
|
||||
|
||||
|
||||
def test_purchase_multi_line_policies_are_deterministic():
|
||||
candidates = [
|
||||
(10, Decimal("100"), Decimal("2")),
|
||||
(11, Decimal("200"), Decimal("1")),
|
||||
]
|
||||
assert _select_multi_line_price(candidates, POLICY_WEIGHTED_AVERAGE) == Decimal("133.33")
|
||||
assert _select_multi_line_price(candidates, POLICY_LAST_LINE) == Decimal("200")
|
||||
assert _select_multi_line_price(candidates, POLICY_HIGHEST_PRICE) == Decimal("200")
|
||||
assert _select_multi_line_price(candidates, POLICY_LOWEST_PRICE) == Decimal("100")
|
||||
|
||||
|
||||
def test_older_purchase_invoice_cannot_replace_newer_synced_source():
|
||||
product = SimpleNamespace(
|
||||
base_purchase_price_sync_meta={
|
||||
"document_id": 20,
|
||||
"document_date": "2026-10-20",
|
||||
"registered_at": "2026-10-20T12:00:00",
|
||||
}
|
||||
)
|
||||
older = SimpleNamespace(
|
||||
id=10,
|
||||
document_date=date(2026, 10, 19),
|
||||
registered_at=datetime(2026, 10, 19, 12, 0),
|
||||
)
|
||||
same_source = SimpleNamespace(
|
||||
id=20,
|
||||
document_date=date(2026, 10, 20),
|
||||
registered_at=datetime(2026, 10, 20, 12, 0),
|
||||
)
|
||||
assert _source_is_newer_than_document(product, older) is True
|
||||
assert _source_is_newer_than_document(product, same_source) is False
|
||||
|
||||
|
||||
def test_business_settings_validate_new_policies():
|
||||
payload = BusinessUpdateRequest(
|
||||
invoice_profit_missing_purchase_price_policy="block_calculation",
|
||||
invoice_sync_purchase_price_multi_line_policy="weighted_average",
|
||||
)
|
||||
assert payload.invoice_profit_missing_purchase_price_policy == "block_calculation"
|
||||
assert payload.invoice_sync_purchase_price_multi_line_policy == "weighted_average"
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
BusinessUpdateRequest(invoice_profit_missing_purchase_price_policy="guess")
|
||||
with pytest.raises(ValueError):
|
||||
BusinessUpdateRequest(invoice_sync_purchase_price_multi_line_policy="random")
|
||||
|
|
@ -366,6 +366,7 @@ class BusinessResponse {
|
|||
// تنظیمات محاسبه سود فاکتور
|
||||
final String? invoiceProfitCalculationMethod;
|
||||
final String? invoiceProfitCalculationBasis;
|
||||
final String invoiceProfitMissingPurchasePricePolicy;
|
||||
final bool invoiceProfitIncludeOverhead;
|
||||
final String? invoiceProfitOverheadType;
|
||||
final double? invoiceProfitOverheadPercent;
|
||||
|
|
@ -378,6 +379,7 @@ class BusinessResponse {
|
|||
final bool invoiceSyncUpdatePurchasePriceEnabled;
|
||||
final String? invoiceSyncSalesPriceBasis;
|
||||
final String? invoiceSyncPurchasePriceBasis;
|
||||
final String invoiceSyncPurchasePriceMultiLinePolicy;
|
||||
/// none | draft | posted
|
||||
final String invoiceWarehouseReleaseMode;
|
||||
/// direct_inventory | grni_two_step | grni_legacy
|
||||
|
|
@ -448,6 +450,7 @@ class BusinessResponse {
|
|||
this.displayTimezone,
|
||||
this.invoiceProfitCalculationMethod,
|
||||
this.invoiceProfitCalculationBasis,
|
||||
this.invoiceProfitMissingPurchasePricePolicy = 'zero_cost',
|
||||
this.invoiceProfitIncludeOverhead = false,
|
||||
this.invoiceProfitOverheadType,
|
||||
this.invoiceProfitOverheadPercent,
|
||||
|
|
@ -458,6 +461,7 @@ class BusinessResponse {
|
|||
this.invoiceSyncUpdatePurchasePriceEnabled = false,
|
||||
this.invoiceSyncSalesPriceBasis,
|
||||
this.invoiceSyncPurchasePriceBasis,
|
||||
this.invoiceSyncPurchasePriceMultiLinePolicy = 'weighted_average',
|
||||
this.invoiceWarehouseReleaseMode = 'draft',
|
||||
this.invoicePurchaseAccountingMode = 'direct_inventory',
|
||||
this.invoiceMissingLineWarehousePolicy = 'reject',
|
||||
|
|
@ -540,6 +544,8 @@ class BusinessResponse {
|
|||
displayTimezone: json['display_timezone'] as String?,
|
||||
invoiceProfitCalculationMethod: json['invoice_profit_calculation_method'] as String?,
|
||||
invoiceProfitCalculationBasis: json['invoice_profit_calculation_basis'] as String?,
|
||||
invoiceProfitMissingPurchasePricePolicy:
|
||||
(json['invoice_profit_missing_purchase_price_policy'] as String?) ?? 'zero_cost',
|
||||
invoiceProfitIncludeOverhead: (json['invoice_profit_include_overhead'] as bool?) ?? false,
|
||||
invoiceProfitOverheadType: json['invoice_profit_overhead_type'] as String?,
|
||||
invoiceProfitOverheadPercent: (json['invoice_profit_overhead_percent'] as num?)?.toDouble(),
|
||||
|
|
@ -555,6 +561,8 @@ class BusinessResponse {
|
|||
(json['invoice_sync_update_purchase_price_enabled'] as bool?) ?? false,
|
||||
invoiceSyncSalesPriceBasis: json['invoice_sync_sales_price_basis'] as String?,
|
||||
invoiceSyncPurchasePriceBasis: json['invoice_sync_purchase_price_basis'] as String?,
|
||||
invoiceSyncPurchasePriceMultiLinePolicy:
|
||||
(json['invoice_sync_purchase_price_multi_line_policy'] as String?) ?? 'weighted_average',
|
||||
invoiceWarehouseReleaseMode: _normalizeInvoiceWarehouseReleaseMode(
|
||||
json['invoice_warehouse_release_mode'] as String?,
|
||||
),
|
||||
|
|
|
|||
|
|
@ -64,6 +64,7 @@ class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
|||
// تنظیمات محاسبه سود فاکتور
|
||||
String? _invoiceProfitCalculationMethod;
|
||||
String? _invoiceProfitCalculationBasis;
|
||||
String _invoiceProfitMissingPurchasePricePolicy = 'zero_cost';
|
||||
bool _invoiceProfitIncludeOverhead = false;
|
||||
String? _invoiceProfitOverheadType;
|
||||
final _invoiceProfitOverheadPercentController = TextEditingController();
|
||||
|
|
@ -79,6 +80,7 @@ class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
|||
bool _invoiceSyncUpdatePurchasePriceEnabled = false;
|
||||
String? _invoiceSyncSalesPriceBasis;
|
||||
String? _invoiceSyncPurchasePriceBasis;
|
||||
String _invoiceSyncPurchasePriceMultiLinePolicy = 'weighted_average';
|
||||
/// none | draft | posted
|
||||
String _invoiceWarehouseReleaseMode = 'draft';
|
||||
/// direct_inventory | grni_two_step | grni_legacy
|
||||
|
|
@ -203,6 +205,7 @@ class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
|||
// تنظیمات محاسبه سود
|
||||
_invoiceProfitCalculationMethod = resp.invoiceProfitCalculationMethod ?? 'automatic';
|
||||
_invoiceProfitCalculationBasis = resp.invoiceProfitCalculationBasis ?? 'purchase_price';
|
||||
_invoiceProfitMissingPurchasePricePolicy = resp.invoiceProfitMissingPurchasePricePolicy;
|
||||
_invoiceProfitIncludeOverhead = resp.invoiceProfitIncludeOverhead;
|
||||
_invoiceProfitOverheadType = resp.invoiceProfitOverheadType ?? 'none';
|
||||
_invoiceProfitOverheadPercentController.text = (resp.invoiceProfitOverheadPercent ?? 0).toStringAsFixed(2);
|
||||
|
|
@ -214,6 +217,7 @@ class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
|||
_invoiceSyncUpdatePurchasePriceEnabled = resp.invoiceSyncUpdatePurchasePriceEnabled;
|
||||
_invoiceSyncSalesPriceBasis = resp.invoiceSyncSalesPriceBasis ?? 'net_after_line_discount';
|
||||
_invoiceSyncPurchasePriceBasis = resp.invoiceSyncPurchasePriceBasis ?? 'net_after_line_discount';
|
||||
_invoiceSyncPurchasePriceMultiLinePolicy = resp.invoiceSyncPurchasePriceMultiLinePolicy;
|
||||
_invoiceWarehouseReleaseMode = resp.invoiceWarehouseReleaseMode;
|
||||
_invoicePurchaseAccountingMode = resp.invoicePurchaseAccountingMode;
|
||||
_invoiceGlobalDiscountPercentBasis = resp.invoiceGlobalDiscountPercentBasis;
|
||||
|
|
@ -361,6 +365,9 @@ class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
|||
if (_invoiceProfitCalculationBasis != null && _invoiceProfitCalculationBasis != orig.invoiceProfitCalculationBasis) {
|
||||
payload['invoice_profit_calculation_basis'] = _invoiceProfitCalculationBasis;
|
||||
}
|
||||
if (_invoiceProfitMissingPurchasePricePolicy != orig.invoiceProfitMissingPurchasePricePolicy) {
|
||||
payload['invoice_profit_missing_purchase_price_policy'] = _invoiceProfitMissingPurchasePricePolicy;
|
||||
}
|
||||
if (_invoiceProfitIncludeOverhead != orig.invoiceProfitIncludeOverhead) {
|
||||
payload['invoice_profit_include_overhead'] = _invoiceProfitIncludeOverhead;
|
||||
}
|
||||
|
|
@ -396,6 +403,9 @@ class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
|||
if (_invoiceSyncPurchasePriceBasis != null && _invoiceSyncPurchasePriceBasis != orig.invoiceSyncPurchasePriceBasis) {
|
||||
payload['invoice_sync_purchase_price_basis'] = _invoiceSyncPurchasePriceBasis;
|
||||
}
|
||||
if (_invoiceSyncPurchasePriceMultiLinePolicy != orig.invoiceSyncPurchasePriceMultiLinePolicy) {
|
||||
payload['invoice_sync_purchase_price_multi_line_policy'] = _invoiceSyncPurchasePriceMultiLinePolicy;
|
||||
}
|
||||
if (_invoiceWarehouseReleaseMode != orig.invoiceWarehouseReleaseMode) {
|
||||
payload['invoice_warehouse_release_mode'] = _invoiceWarehouseReleaseMode;
|
||||
}
|
||||
|
|
@ -1413,6 +1423,35 @@ class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
|||
},
|
||||
),
|
||||
],
|
||||
if (_invoiceProfitCalculationBasis == 'purchase_price') ...[
|
||||
const SizedBox(height: 16),
|
||||
DropdownButtonFormField<String>(
|
||||
initialValue: _invoiceProfitMissingPurchasePricePolicy,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'رفتار قیمت خرید نامشخص',
|
||||
helperText: 'اگر هنگام ثبت فروش، قیمت خرید محصول تعریف نشده باشد چه رفتاری انجام شود؟',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
items: const [
|
||||
DropdownMenuItem(
|
||||
value: 'block_calculation',
|
||||
child: Text('جلوگیری از ثبت/محاسبه تا تعیین قیمت خرید'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: 'use_line_cost_price',
|
||||
child: Text('استفاده از بهای پایه ثبتشده روی ردیف؛ در نبود آن توقف'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: 'zero_cost',
|
||||
child: Text('محاسبه با هزینه صفر (رفتار سازگار قبلی)'),
|
||||
),
|
||||
],
|
||||
onChanged: (value) {
|
||||
if (value == null) return;
|
||||
setState(() => _invoiceProfitMissingPurchasePricePolicy = value);
|
||||
},
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 16),
|
||||
// نوع محاسبه سود
|
||||
DropdownButtonFormField<String>(
|
||||
|
|
@ -2063,6 +2102,37 @@ class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
|||
items: _invoiceSyncBasisItems,
|
||||
onChanged: (value) => setState(() => _invoiceSyncPurchasePriceBasis = value),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
DropdownButtonFormField<String>(
|
||||
initialValue: _invoiceSyncPurchasePriceMultiLinePolicy,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'سیاست چند ردیف یک محصول در فاکتور خرید',
|
||||
helperText: 'اگر یک محصول با چند قیمت در یک فاکتور باشد، قیمت پایه چگونه تعیین شود؟',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
items: const [
|
||||
DropdownMenuItem(
|
||||
value: 'weighted_average',
|
||||
child: Text('میانگین وزنی بر اساس مقدار'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: 'last_line',
|
||||
child: Text('آخرین ردیف واردشده'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: 'highest_price',
|
||||
child: Text('بیشترین قیمت'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: 'lowest_price',
|
||||
child: Text('کمترین قیمت'),
|
||||
),
|
||||
],
|
||||
onChanged: (value) {
|
||||
if (value == null) return;
|
||||
setState(() => _invoiceSyncPurchasePriceMultiLinePolicy = value);
|
||||
},
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
|
|
|
|||
|
|
@ -1150,9 +1150,8 @@ class _InvoiceLineItemsTableState extends State<InvoiceLineItemsTable> {
|
|||
if (isMainSelected) {
|
||||
return priceOnMainUnit;
|
||||
}
|
||||
// در حالت انتخاب واحد فرعی: قیمت واحد باید در ضریب تبدیل ضرب شود
|
||||
// تعریف: 1 main = factor * secondary => price(secondary) = price(main) * factor
|
||||
return priceOnMainUnit * factor;
|
||||
// قرارداد: 1 main = factor × secondary؛ پس قیمت هر secondary برابر main / factor است.
|
||||
return priceOnMainUnit / factor;
|
||||
}
|
||||
|
||||
num _defaultTaxRateFromProduct(Map<String, dynamic> p) {
|
||||
|
|
|
|||
|
|
@ -407,7 +407,10 @@ class _ProductBasicInfoSectionState extends State<ProductBasicInfoSection> {
|
|||
SizedBox(height: spacing),
|
||||
TextFormField(
|
||||
initialValue: widget.formData.unitConversionFactor.toString(),
|
||||
decoration: InputDecoration(labelText: t.unitConversionFactor),
|
||||
decoration: InputDecoration(
|
||||
labelText: t.unitConversionFactor,
|
||||
helperText: '۱ واحد اصلی = ضریب × واحد فرعی؛ مثال: ۱ کارتن = ۲۰ عدد، ضریب ۲۰',
|
||||
),
|
||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
inputFormatters: [
|
||||
const EnglishDigitsFormatter(),
|
||||
|
|
@ -455,7 +458,10 @@ class _ProductBasicInfoSectionState extends State<ProductBasicInfoSection> {
|
|||
Expanded(
|
||||
child: TextFormField(
|
||||
initialValue: widget.formData.unitConversionFactor.toString(),
|
||||
decoration: InputDecoration(labelText: t.unitConversionFactor),
|
||||
decoration: InputDecoration(
|
||||
labelText: t.unitConversionFactor,
|
||||
helperText: '۱ واحد اصلی = ضریب × واحد فرعی؛ مثال: ۱ کارتن = ۲۰ عدد، ضریب ۲۰',
|
||||
),
|
||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
inputFormatters: [
|
||||
const EnglishDigitsFormatter(),
|
||||
|
|
|
|||
Loading…
Reference in a new issue