diff --git a/docs/PRODUCT_VARIANTS_TEAM_BASED_PROGRESS.fa.md b/docs/PRODUCT_VARIANTS_TEAM_BASED_PROGRESS.fa.md index 591d5b09..cb8571f5 100644 --- a/docs/PRODUCT_VARIANTS_TEAM_BASED_PROGRESS.fa.md +++ b/docs/PRODUCT_VARIANTS_TEAM_BASED_PROGRESS.fa.md @@ -15,8 +15,10 @@ | کد | عنوان | branch | commit | تاریخ | وضعیت | |---|---|---|---|---|---| -| H15 | root-only drain Woo hook | codex/team-base-01-woocommerce-root-commit | 15fd8509 | ۲۰۲۶-۱۱-۰۶ | ✅ در `master` merge شد (#42) | -| P01 | تفکیک cost_price | codex/team-base-02-cost-currency-basis | 1a003e17 | ۲۰۲۶-۱۱-۰۶ | ✅ در `master` merge شد (#43) | +| H15 | root-only drain Woo hook | codex/team-base-01-woocommerce-root-commit | 15fd8509 | ۲۰۲۶-۱۱-۰۶ | ✅ merge شده (#42) | +| P01 | تفکیک cost_price | codex/team-base-02-cost-currency-basis | 1a003e17 | ۲۰۲۶-۱۱-۰۶ | ✅ merge شده (#43) | +| C04 | حفظ صفر معلوم پس از لغو تنها حوالهٔ خروج | codex/team-base-03-zero-cost-cancel | 4867aaa3586c62794746c723c1cc4df61c19c9ad | ۲۰۲۶-۱۱-۱۱ | 🟢 PR ارسال شد | +| H35 | تخصیص هزینهٔ هر حواله برای لغو جزئیِ مبالغ متفاوت | — | — | — | ⏳ در انتظار (وابسته به فاز ۲ Native) | ## مرحلهٔ ۰۱ — H15: زمان ارسال موجودی ووکامرس @@ -64,6 +66,14 @@ python -m pytest -q -p no:cacheprovider tests/test_woocommerce_stock_push_transa python -m pytest -q -p no:cacheprovider tests/test_invoice_cost_currency_basis.py ``` +## مرحلهٔ ۰۳ — C04 + +- شاخه از `origin/master` در `3aee9afa388bbd942a639265b48d4ef143f3aba0` ساخته شد. P01 و H15 در تاریخچهٔ پایه هستند. +- در فاکتور فروش با تنها یک حوالهٔ خروج، لغو حواله سهم خطوط پیوندخورده از بهای شناسایی‌شده و دفتر کل را صفر می‌کند. صفر معلوم حفظ می‌شود و `None` اجازهٔ fallback به snapshot قبلی را می‌دهد. +- ۶۳ آزمون مرتبط موفق شدند، شامل لغو واقعی در SQLite، fallback برای `None`، صفر واقعی، حفظ رفتار چندخروجی و رگرسیون P01. برای تزریق `None` فقط خروجی محاسبهٔ تحلیلی جایگزین شد. +- اجرای کامل ۲۲۳۲ آزمون جمع‌آوری کرد و پس از ۳۰۰ ثانیه در `test_ai_channel_stream.py` متوقف شد. اجرای پایه نیز در همان آزمون به سقف رسید. +- شاخه به فورک ارسال شد. [صفحهٔ ایجاد PR در مخزن تیم](https://source.hesabix.ir/hesabix/arc/compare/master...Seyyed:codex/team-base-03-zero-cost-cancel). + ## موارد منتقل‌نشده و ترتیب بازبینی | دسته | وضعیت انتقال به مبنای تیم | اقدام لازم | @@ -87,3 +97,4 @@ python -m pytest -q -p no:cacheprovider tests/test_invoice_cost_currency_basis.p - ۲۰۲۶-۱۱-۰۶: مبنا به کد رسمی تیم تغییر کرد؛ master محلی تا `2b5c6a24` fast-forward شد. H15 به‌عنوان اولین اصلاح مستقل با بازتولید قبل و ۱۵ آزمون موفق پس از اصلاح منتقل شد. شاخهٔ Unified قدیمی و تست‌های آن تغییر نکردند. - ۲۰۲۶-۱۱-۰۷: H15 در `master` merge شد (#42). P01 (`cost_currency_basis` برای `cost_price`) پس از حل تداخل همین سند پیشرفت در `master` merge شد (#43). +- ۲۰۲۶-۱۱-۱۱: C04 برای تک‌خروج اصلاح شد. H35 در C04 کشف شد؛ با معرفی `VariantCostConsumption` در فاز ۲ Native حل می‌شود. تا آن زمان، GL برای چند-خروجی همان رفتار قبلی را دارد؛ تغییر نمی‌کند. diff --git a/hesabixAPI/app/services/invoice_cogs_gl_service.py b/hesabixAPI/app/services/invoice_cogs_gl_service.py index 73a5fb66..761c6100 100644 --- a/hesabixAPI/app/services/invoice_cogs_gl_service.py +++ b/hesabixAPI/app/services/invoice_cogs_gl_service.py @@ -22,8 +22,10 @@ from adapters.db.models.document_line import DocumentLine from app.services.invoice_profit_ledger_service import ( LEDGER_BASIS_SALES_INVOICE_DOCUMENT, LEDGER_BASIS_WAREHOUSE_DOCUMENT_POSTING, + apply_cancelled_issue_cost, document_has_any_posted_warehouse, normalize_invoice_profit_ledger_basis, + single_sales_issue_cost_scope, ) logger = logging.getLogger(__name__) @@ -97,27 +99,20 @@ def _evaluate_should_have_cogs_gl(db: Session, document: Document) -> bool: return False -def _total_cost_from_profit_data(profit_data: Dict[str, Any]) -> Decimal: - """استخراج بهای تمام‌شده کل از خروجی محاسبه سود (با fallback به جمع خطوط).""" +def _total_cost_from_profit_data(profit_data: dict[str, Any]) -> Decimal | None: + """Extract an explicitly known cost, preserving zero.""" raw_total = profit_data.get("total_cost") if raw_total is not None: - total_cost = Decimal(str(raw_total or 0)) - else: - total_cost = Decimal(0) - for line in profit_data.get("line_profits") or []: - total_cost += Decimal(str(line.get("total_cost", 0) or 0)) - if total_cost < 0: - total_cost = abs(total_cost) - return total_cost + return abs(Decimal(str(raw_total))) + costs = [ + Decimal(str(line["total_cost"])) for line in profit_data.get("line_profits") or () + if line.get("total_cost") is not None + ] + return abs(sum(costs, Decimal(0))) if costs else None def _recognized_ledger_cogs_total_from_document(db: Session, document_id: int) -> Decimal: - """ - جمع بهای تمام‌شده شناسایی‌شده روی خطوط فاکتور (ستون ledger_line_cogs). - - وقتی محاسبهٔ زندهٔ سود (مثلاً fifo_jbfn) مقدار صفر برمی‌گرداند ولی شناسایی قطعی - قبلاً روی خطوط ذخیره شده، مبنای ثبت COGS در دفتر کل همان مقادیر شناسایی‌شده است. - """ + """Sum previously recognized COGS for legacy fallback.""" from adapters.db.models.invoice_item_line import InvoiceItemLine rows = ( @@ -169,8 +164,10 @@ def _calculate_invoice_cogs_amount_for_gl( fifo_shortage_mode=getattr(biz, "invoice_profit_fifo_shortage_mode", None), ) + single_issue, cancelled_ids = single_sales_issue_cost_scope(db, document_id) + apply_cancelled_issue_cost(profit_data, cancelled_ids) calculated = _total_cost_from_profit_data(profit_data) - if calculated > 0: + if calculated is not None and (single_issue or calculated > 0): return calculated return _recognized_ledger_cogs_total_from_document(db, int(document_id)) @@ -411,6 +408,21 @@ def on_warehouse_invoice_cogs_gl_cancel_sync( if str(source_type or "").strip().lower() != "invoice" or not source_document_id: return try: + from adapters.db.models.invoice_item_line import InvoiceItemLine + + # The application Session has autoflush disabled. + db.flush() + _, cancelled_ids = single_sales_issue_cost_scope(db, int(source_document_id)) + if cancelled_ids: + rows = db.query(InvoiceItemLine).filter( + InvoiceItemLine.document_id == int(source_document_id), + InvoiceItemLine.id.in_(cancelled_ids), + ).all() + for row in rows: + if row.ledger_line_gross_profit is not None and row.ledger_line_cogs is not None: + row.ledger_line_gross_profit += row.ledger_line_cogs + row.ledger_unit_cogs = row.ledger_line_cogs = Decimal(0) + db.flush() resync_invoice_cogs_gl_lines(db, int(source_document_id)) except Exception as exc: logger.warning( diff --git a/hesabixAPI/app/services/invoice_profit_ledger_service.py b/hesabixAPI/app/services/invoice_profit_ledger_service.py index efcb51aa..67e298f6 100755 --- a/hesabixAPI/app/services/invoice_profit_ledger_service.py +++ b/hesabixAPI/app/services/invoice_profit_ledger_service.py @@ -59,6 +59,49 @@ def document_has_any_posted_warehouse(db: Session, *, document_id: int) -> bool: return q is not None +def single_sales_issue_cost_scope(db: Session, document_id: int) -> tuple[bool, set[int]]: + """Identify a single sales issue and its explicitly linked lines if cancelled.""" + from adapters.db.models.document import Document + from adapters.db.models.warehouse_document import WarehouseDocument + from app.services.warehouse_service import _payload_invoice_item_line_id + + issues = db.query(WarehouseDocument).join( + Document, Document.id == WarehouseDocument.source_document_id, + ).filter( + Document.id == document_id, + Document.document_type == "invoice_sales", + WarehouseDocument.business_id == Document.business_id, + WarehouseDocument.source_type == "invoice", + WarehouseDocument.doc_type == "issue", + WarehouseDocument.status.in_(("posted", "cancelled")), + ).limit(2).all() + if len(issues) != 1: + return False, set() + if issues[0].status != "cancelled": + return True, set() + return True, { + line_id for line in issues[0].lines if line.movement == "out" + if (line_id := _payload_invoice_item_line_id({"extra_info": line.extra_info})) is not None + } + + +def apply_cancelled_issue_cost(profit_data: dict[str, Any], cancelled_ids: set[int]) -> None: + for line in profit_data.get("line_profits") or (): + if line.get("line_id") in cancelled_ids: + line.update(cost_per_unit=0, total_cost=0, gross_profit=line["sales_amount"]) + profit_data.pop("total_cost", None) + + +def _write_profit_snapshot(row: Any, line: dict[str, Any]) -> bool: + unit_cost, total_cost, gross_profit = (line.get(key) for key in ("cost_per_unit", "total_cost", "gross_profit")) + if unit_cost is None or total_cost is None: + return False + row.ledger_unit_cogs = Decimal(str(unit_cost)) + row.ledger_line_cogs = Decimal(str(total_cost)) + row.ledger_line_gross_profit = Decimal(str(gross_profit)) if gross_profit is not None else None + return True + + def apply_recognized_profit_to_invoice_lines( db: Session, business_id: int, @@ -121,11 +164,13 @@ def apply_recognized_profit_to_invoice_lines( fifo_shortage_mode=getattr(biz, "invoice_profit_fifo_shortage_mode", None), ) + _, cancelled_ids = single_sales_issue_cost_scope(db, document_id) + apply_cancelled_issue_cost(profit_data, cancelled_ids) line_profits: List[Dict[str, Any]] = profit_data.get("line_profits") or [] if not line_profits: return False - recognized_at = datetime.utcnow() + recognized_at = None for lp in line_profits: lid = lp.get("line_id") @@ -135,16 +180,14 @@ def apply_recognized_profit_to_invoice_lines( InvoiceItemLine.id == int(lid), InvoiceItemLine.document_id == int(document_id), ).first() - if not row: + if not row or not _write_profit_snapshot(row, lp): continue - row.ledger_unit_cogs = Decimal(str(lp.get("cost_per_unit", 0) or 0)) - row.ledger_line_cogs = Decimal(str(lp.get("total_cost", 0) or 0)) - row.ledger_line_gross_profit = Decimal(str(lp.get("gross_profit", 0) or 0)) + recognized_at = recognized_at or datetime.utcnow() row.ledger_recognized_at = recognized_at row.ledger_recognition_event = recognition_event db.flush() - return True + return recognized_at is not None def sync_ledger_profit_from_analytical_for_document( @@ -188,11 +231,13 @@ def sync_ledger_profit_from_analytical_for_document( fifo_shortage_mode=getattr(biz, "invoice_profit_fifo_shortage_mode", None), ) + _, cancelled_ids = single_sales_issue_cost_scope(db, document_id) + apply_cancelled_issue_cost(profit_data, cancelled_ids) line_profits: List[Dict[str, Any]] = profit_data.get("line_profits") or [] if not line_profits: return False - recognized_at = datetime.utcnow() + recognized_at = None for lp in line_profits: lid = lp.get("line_id") @@ -202,16 +247,14 @@ def sync_ledger_profit_from_analytical_for_document( InvoiceItemLine.id == int(lid), InvoiceItemLine.document_id == int(document_id), ).first() - if not row: + if not row or not _write_profit_snapshot(row, lp): continue - row.ledger_unit_cogs = Decimal(str(lp.get("cost_per_unit", 0) or 0)) - row.ledger_line_cogs = Decimal(str(lp.get("total_cost", 0) or 0)) - row.ledger_line_gross_profit = Decimal(str(lp.get("gross_profit", 0) or 0)) + recognized_at = recognized_at or datetime.utcnow() row.ledger_recognized_at = recognized_at row.ledger_recognition_event = LEDGER_EVENT_INVENTORY_CHAIN_REFRESH db.flush() - return True + return recognized_at is not None def refresh_sales_ledgers_after_inventory_invoice_change( diff --git a/hesabixAPI/tests/test_invoice_cancel_zero_cost.py b/hesabixAPI/tests/test_invoice_cancel_zero_cost.py new file mode 100644 index 00000000..c5106bdc --- /dev/null +++ b/hesabixAPI/tests/test_invoice_cancel_zero_cost.py @@ -0,0 +1,97 @@ +from datetime import date, datetime +from decimal import Decimal + +import pytest +from sqlalchemy import create_engine +from sqlalchemy.orm import Session + +from adapters.db import models +from adapters.db.models.business import BusinessField, BusinessType +from adapters.db.models.invoice_item_line import InvoiceItemLine +from app.core import cache +from app.services import invoice_service +from app.services.invoice_cogs_gl_service import ( + _calculate_invoice_cogs_amount_for_gl, + _existing_cogs_gl_amount, +) +from app.services.invoice_profit_ledger_service import ( + apply_recognized_profit_to_invoice_lines, + sync_ledger_profit_from_analytical_for_document, +) +from app.services.warehouse_service import _compute_line_quantities_core, cancel_warehouse_document + + +@pytest.fixture +def sale(monkeypatch): + monkeypatch.setattr(cache, "_redis_config", {"enabled": False}) + monkeypatch.setattr(cache, "_redis_config_expires_at", float("inf")) + monkeypatch.setattr(cache, "_redis_client", None) + monkeypatch.setattr(cache, "_cache_service", None) + engine = create_engine("sqlite://") + tables = ("businesses", "currencies", "fiscal_years", "products", "documents", "document_lines", + "invoice_item_lines", "warehouse_documents", "warehouse_document_lines", + "warehouse_line_variant_allocations", "warehouse_line_lot_allocations", + "business_document_numbering_settings", "document_number_counters") + models.Base.metadata.create_all(engine, tables=[models.Base.metadata.tables[name] for name in tables]) + day = date(2026, 11, 11) + with Session(engine, autoflush=False) as db: + item = InvoiceItemLine(id=1, document_id=1, product_id=1, quantity=2, extra_info={"unit_price": 250}, + purchase_price_snapshot_unit_cost_base=100, purchase_price_snapshot_currency_id=1, + ledger_unit_cogs=100, ledger_line_cogs=200, ledger_recognized_at=datetime(2026, 11, 11)) + db.add_all([ + models.Business(id=1, name="Test", business_type=BusinessType.SHOP, business_field=BusinessField.TRADING, + owner_id=1, default_currency_id=1, invoice_profit_ledger_recognition_basis="sales_invoice_document"), + models.Currency(id=1, name="Base", title="Base", symbol="B", code="B"), + models.FiscalYear(id=1, business_id=1, title="2026", is_last=True, start_date=day, end_date=day), + models.Product(id=1, business_id=1, code="P", name="P"), + models.Document(id=1, code="SALE", business_id=1, fiscal_year_id=1, currency_id=1, created_by_user_id=1, + document_date=day, document_type="invoice_sales", extra_info={"links": {"warehouse_document_ids": [1]}}), + models.WarehouseDocument(id=1, business_id=1, fiscal_year_id=1, code="ISSUE", document_date=day, + status="posted", doc_type="issue", source_type="invoice", source_document_id=1), + models.WarehouseDocumentLine(warehouse_document_id=1, product_id=1, movement="out", quantity=2, + extra_info={"invoice_item_line_id": 1}), + models.DocumentLine(document_id=1, debit=200, credit=0, extra_info={"side": "gl_cogs"}), + models.DocumentLine(document_id=1, debit=0, credit=200, extra_info={"side": "gl_inventory_cogs"}), + item, + ]) + db.flush() + yield db, item + engine.dispose() + + +def test_cancel_only_issue_clears_snapshot_and_gl(sale): + db, item = sale + assert item.ledger_line_cogs == _calculate_invoice_cogs_amount_for_gl(db, 1, 1) == 200 + reversal = cancel_warehouse_document(db, 1, 1, 1) + issue = db.get(models.WarehouseDocument, 1) + assert (issue.status, reversal.status) == ("cancelled", "draft") + assert _compute_line_quantities_core("invoice_sales", [item], [issue, reversal])[0]["processed_quantity"] == 0 + assert item.ledger_unit_cogs == item.ledger_line_cogs == 0 + assert _existing_cogs_gl_amount(db.query(models.DocumentLine).all()) == 0 + assert _calculate_invoice_cogs_amount_for_gl(db, 1, 1) == 0 + assert sync_ledger_profit_from_analytical_for_document(db, 1, 1) + assert item.ledger_unit_cogs == item.ledger_line_cogs == 0 + assert item.purchase_price_snapshot_unit_cost_base == 100 + + +def test_unknown_cost_preserves_snapshot_and_falls_back(sale, monkeypatch): + db, item = sale + # The team calculator emits numeric costs. Inject the nullable producer result only. + monkeypatch.setattr(invoice_service, "_calculate_invoice_profit", + lambda *a, **kw: {"line_profits": [{"line_id": 1, "total_cost": None}]}) + assert not apply_recognized_profit_to_invoice_lines(db, 1, 1, recognition_event="sales_invoice_document") + assert item.ledger_line_cogs == 200 + assert not sync_ledger_profit_from_analytical_for_document(db, 1, 1) + assert item.ledger_line_cogs == _calculate_invoice_cogs_amount_for_gl(db, 1, 1) == 200 + + +@pytest.mark.parametrize("issue_count, expected", [(1, 0), (2, 200)]) +def test_known_zero_ignores_old_snapshot_only_for_single_issue(sale, issue_count, expected): + db, item = sale + item.purchase_price_snapshot_unit_cost_base = Decimal(0) + if issue_count == 2: + first = db.get(models.WarehouseDocument, 1) + db.add(models.WarehouseDocument(business_id=1, code="ISSUE-2", document_date=first.document_date, + status="posted", doc_type="issue", source_type="invoice", source_document_id=1)) + db.flush() + assert _calculate_invoice_cogs_amount_for_gl(db, 1, 1) == expected diff --git a/hesabixAPI/tests/test_invoice_cogs_gl_service.py b/hesabixAPI/tests/test_invoice_cogs_gl_service.py index 4e014a7a..1ef36670 100644 --- a/hesabixAPI/tests/test_invoice_cogs_gl_service.py +++ b/hesabixAPI/tests/test_invoice_cogs_gl_service.py @@ -253,8 +253,8 @@ class TestTotalCostFromProfitData: data = {"total_cost": -800000.0, "line_profits": []} assert _total_cost_from_profit_data(data) == Decimal("800000") - def test_empty_profit_data_returns_zero(self): - assert _total_cost_from_profit_data({}) == Decimal(0) + def test_empty_profit_data_has_unknown_cost(self): + assert _total_cost_from_profit_data({}) is None class TestRecognizedLedgerCogsTotal: