diff --git a/docs/PRODUCT_VARIANTS_TEAM_BASED_PROGRESS.fa.md b/docs/PRODUCT_VARIANTS_TEAM_BASED_PROGRESS.fa.md index 989b1437..42d59c1e 100644 --- a/docs/PRODUCT_VARIANTS_TEAM_BASED_PROGRESS.fa.md +++ b/docs/PRODUCT_VARIANTS_TEAM_BASED_PROGRESS.fa.md @@ -101,6 +101,13 @@ python -m pytest -q -p no:cacheprovider tests/test_invoice_cost_currency_basis.p - **برای بررسی بعدی:** پس از commit در `remove_linked` گروهی، حوالهٔ اصلی `cancelled` و حوالهٔ معکوس `posted` بود. Session تازه جمع خام حواله‌های قطعی را ۱۲ و ۱۳، موجودی قابل‌دسترس را ۸ و ۷ و جدول مانده و قرارگیری را ۱۰ و ۱۰ خواند. در لغو تکیِ حوالهٔ فاکتور نیز موجودی قابل‌دسترس ۸ و ۷ ماند، درحالی‌که جمع خام و جدول مانده ۱۰ و ۱۰ بودند. بلافاصله پس از قطعی‌سازی خروج دستی نیز جدول مانده ۱۰ و ۱۰ ماند، درحالی‌که جمع خام و موجودی قابل‌دسترس ۸ و ۷ بودند. بازسازی صریح در Session بعدی جدول را به ۸ و ۷ رساند. قرارداد مانده و سیاست لغو در این اصلاح تغییر نکرد. - اجرای PostgreSQL در سطح سرویس و بدنهٔ endpointها بود. شواهد در `C:/dev/hesabix/VariantBalance-team17-before.log` و `C:/dev/hesabix/VariantBalance-team17-after.log` ثبت شدند. +## H17 — انبارگردانی Variant + +- مبنا: `efc056cb0bc2da9434f3f29d7d6bfb1a7d43b233`. در PostgreSQL، برای دو Variant با موجودی ۸ و ۱۲، شمارش‌های ۷، ۸ و ۹ با جمع کالا یعنی ۲۰ مقایسه می‌شدند. اختلاف‌های −۱۳، −۱۲ و −۱۱ در تعدیل فیزیکی با `VARIANT_REQUIRED` رد می‌شدند و در مسیر کالاهای هزینه/درآمد پیش‌نویس کسری نادرست می‌ساختند. قطعی‌سازی کسری ۱۳ واحدی، بدون تخصیص Variant، هزینه و کاهش حساب موجودی به مبلغ ۱۳۰۰ ثبت کرد. +- با اصلاح، ردیف دارای `variant_id` بدون لات یا واحد یونیک از گردش فیزیکی همان Variant در تاریخ و انبار شمارش خوانده می‌شود. در آزمون، موجودی مبنا ۸ و اختلاف‌ها −۱، صفر و +۱ بود. هر دو مسیر کسری و مازاد را با شناسهٔ Variant ۱ و مقدار یک قطعی کردند و Variant ۲ روی ۱۲ ماند. شمارش ۸ سند تعدیل نساخت. دریافت روز بعد مبنای تاریخی را تغییر نداد و تعهد فروش دو واحدی فقط موجودی قابل‌فروش را به ۶ رساند. +- آزمون کامل قطعی‌سازی در worktree جدا با #55 روی `d9dc31a04392dd57865446dc15d6ebd15941fac7` و #56 روی `68706e4a4195abd114d48b96d3b67d337b174b0f` انجام شد. قطعی‌سازی دارای تخصیص برای بازسازی مانده به #55 وابسته است. #56 برای به‌روز شدن ماندهٔ نمایشی ورود/خروج عادی در آزمون ترکیبی استفاده شد. پس از تعدیل فیزیکی مستقیم، گردش فیزیکی درست بود اما جدول مانده مقدار قبلی را نگه داشت. این ایراد نمایش جداگانه باز است. +- مسیر شروع شمارش برای کالای عادی بدون لات ردیف کالا می‌سازد. شناسهٔ Variant در ردیف‌های دارای لات از همان لات می‌آید. تقدم موجود `instance_id` و سپس `lot_id` حفظ شد. قرارداد جدیدی برای ترکیب این شناسه‌ها تعریف نشد. ۹۰ آزمون منتخب پاس شدند. شواهد در `C:/dev/hesabix/H17-team20-before.log`، `C:/dev/hesabix/H17-team20-after.log` و `C:/dev/hesabix/H17-team20-pytest.log` ثبت شدند. + ## مشکلات High باز | کد | عنوان | وضعیت | شاهد و وابستگی | diff --git a/hesabixAPI/app/services/goods_expense_income_service.py b/hesabixAPI/app/services/goods_expense_income_service.py index 19d9657f..d6583afa 100644 --- a/hesabixAPI/app/services/goods_expense_income_service.py +++ b/hesabixAPI/app/services/goods_expense_income_service.py @@ -1004,6 +1004,17 @@ def _create_warehouse_and_post( "extra_info": extra, "lot_allocations": line_extra.get("lot_allocations") or extra.get("lot_allocations"), } + if ( + (doc.extra_info or {}).get("source") == "stock_count" + and line_extra.get("variant_id") is not None + and not payload["lot_allocations"] + ): + from app.services.variant_allocation_service import attach_warehouse_line_from_payload + + attach_warehouse_line_from_payload( + db, business_id, wline, product, payload, + document=wh, source_line_unit=line_extra.get("unit"), + ) attach_warehouse_line_lots_from_payload( db, business_id, diff --git a/hesabixAPI/app/services/warehouse_service.py b/hesabixAPI/app/services/warehouse_service.py index 26e6e8fc..61cacd68 100755 --- a/hesabixAPI/app/services/warehouse_service.py +++ b/hesabixAPI/app/services/warehouse_service.py @@ -5041,6 +5041,51 @@ def start_stock_count( } +def _get_stock_count_variant_quantity( + db: Session, + business_id: int, + product_id: int, + warehouse_id: Optional[int], + variant_id: Any, + as_of_date: date, +) -> Decimal: + from adapters.db.models.product_variant_allocation import WarehouseLineVariantAllocation + from app.services.invoice_service import _warehouse_doc_is_cancel_reversal_of_cancelled + from app.services.variant_allocation_service import validate_payload_for_product + + product = db.query(Product).filter_by(id=product_id, business_id=business_id).first() + if product is None: + raise ApiError("PRODUCT_NOT_FOUND", "کالا یافت نشد", http_status=404) + [(resolved_variant_id, _, _)] = validate_payload_for_product( + db, business_id, product, {"variant_id": variant_id, "quantity": 1}, Decimal(1) + ) + rows = ( + db.query(WarehouseLineVariantAllocation.quantity, WarehouseDocumentLine.movement, WarehouseDocument) + .join(WarehouseDocumentLine, WarehouseDocumentLine.id == WarehouseLineVariantAllocation.warehouse_document_line_id) + .join(WarehouseDocument, WarehouseDocument.id == WarehouseDocumentLine.warehouse_document_id) + .filter( + WarehouseLineVariantAllocation.business_id == business_id, + WarehouseLineVariantAllocation.product_id == product_id, + WarehouseLineVariantAllocation.variant_id == resolved_variant_id, + WarehouseDocumentLine.product_id == product_id, + WarehouseDocument.business_id == business_id, + WarehouseDocument.status == "posted", + WarehouseDocument.document_date <= as_of_date, + WarehouseDocumentLine.movement.in_(("in", "out")), + ) + ) + if warehouse_id is not None: + rows = rows.filter(WarehouseDocumentLine.warehouse_id == warehouse_id) + return sum( + ( + quantity if movement == "in" else -quantity + for quantity, movement, document in rows + if not _warehouse_doc_is_cancel_reversal_of_cancelled(db, business_id, document) + ), + Decimal(0), + ) + + def calculate_stock_count_differences( db: Session, business_id: int, @@ -5069,13 +5114,7 @@ def calculate_stock_count_differences( lot_id = item.get("lot_id") instance_id = item.get("instance_id") - system_quantity = get_physical_stock( - db, - business_id, - int(product_id), - wh_id, - as_of_date, - ) + variant_id = item.get("variant_id") if instance_id is not None: from adapters.db.models.product_instance import ProductInstance @@ -5109,7 +5148,13 @@ def calculate_stock_count_differences( db, business_id, int(product_id), wh_id, int(lot_id), as_of_date ) except (TypeError, ValueError): - pass + system_quantity = get_physical_stock(db, business_id, int(product_id), wh_id, as_of_date) + elif variant_id is not None: + system_quantity = _get_stock_count_variant_quantity( + db, business_id, int(product_id), wh_id, variant_id, as_of_date, + ) + else: + system_quantity = get_physical_stock(db, business_id, int(product_id), wh_id, as_of_date) try: physical_quantity = Decimal(str(item.get("physical_quantity", 0))) except Exception: @@ -5270,10 +5315,11 @@ def create_stock_count_adjustment( instance.status = "sold" instance.warehouse_id = None instance.last_movement_date = stock_count_date - if item.get("lot_id") or item.get("lot_allocations") or item.get("lot_code"): + has_lot = item.get("lot_id") or item.get("lot_allocations") or item.get("lot_code") + if item.get("variant_id") is not None and (has_lot or item.get("instance_id") is None): + stamped_extra["variant_id"] = item["variant_id"] + if has_lot: stamped_extra = dict(stamped_extra or {}) - if item.get("variant_id") is not None: - stamped_extra["variant_id"] = item.get("variant_id") if item.get("lot_allocations"): stamped_extra["lot_allocations"] = item.get("lot_allocations") elif item.get("lot_id") or item.get("lot_code"): diff --git a/hesabixAPI/tests/test_variant_stock_count_h17.py b/hesabixAPI/tests/test_variant_stock_count_h17.py new file mode 100644 index 00000000..54f09df9 --- /dev/null +++ b/hesabixAPI/tests/test_variant_stock_count_h17.py @@ -0,0 +1,196 @@ +from datetime import date +from decimal import Decimal + +import pytest +from sqlalchemy import Integer, create_engine, select +from sqlalchemy.orm import Session +from sqlalchemy.schema import CreateTable + +from adapters.db.models.fiscal_year import FiscalYear +from adapters.db.models.inventory_lot import WarehouseLineLotAllocation +from adapters.db.models.product import Product +from adapters.db.models.product_instance import ProductInstance +from adapters.db.models.product_variant import ProductVariant +from adapters.db.models.product_variant_allocation import WarehouseLineVariantAllocation +from adapters.db.models.warehouse_document import WarehouseDocument +from adapters.db.models.warehouse_document_line import WarehouseDocumentLine +from app.core.responses import ApiError +from app.services import inventory_lot_service +from app.services.warehouse_service import ( + calculate_stock_count_differences, + create_stock_count_adjustment, +) + +DAY = date(2026, 11, 11) +LATER = date(2026, 11, 12) + + +@pytest.fixture +def db(monkeypatch): + engine = create_engine("sqlite://") + allocation_id = WarehouseLineVariantAllocation.__table__.c.id + monkeypatch.setattr(allocation_id, "type", allocation_id.type.with_variant(Integer, "sqlite")) + with engine.begin() as connection: + for model in ( + FiscalYear, + Product, + ProductInstance, + ProductVariant, + WarehouseDocument, + WarehouseDocumentLine, + WarehouseLineVariantAllocation, + WarehouseLineLotAllocation, + ): + connection.execute(CreateTable(model.__table__, include_foreign_key_constraints=[])) + from app.services import warehouse_service + + monkeypatch.setattr(warehouse_service, "_generate_warehouse_document_code", lambda *_: "H17") + with Session(engine, autoflush=False) as session: + session.add_all( + [ + FiscalYear( + id=1, business_id=1, title="FY", is_last=True, start_date=DAY, end_date=LATER + ), + Product(id=1, business_id=1, code="P", name="Variant", variant_mode="inventory"), + Product(id=2, business_id=1, code="U", name="Unique", inventory_mode="unique"), + ProductInstance( + id=1, + business_id=1, + product_id=2, + warehouse_id=1, + serial_number="U1", + status="available", + entry_date=DAY, + ), + ProductVariant(id=1, business_id=1, product_id=1, combination_key="red"), + ProductVariant(id=2, business_id=1, product_id=1, combination_key="blue"), + ] + ) + for key, (variant, qty, date_, warehouse, status) in enumerate( + ( + (1, 8, DAY, 1, "posted"), + (2, 12, DAY, 1, "posted"), + (1, 3, LATER, 1, "posted"), + (1, 5, DAY, 2, "posted"), + (1, 30, DAY, 1, "draft"), + ), + 1, + ): + session.add_all( + [ + WarehouseDocument( + id=key, + business_id=1, + code=str(key), + status=status, + doc_type="receipt", + document_date=date_, + ), + WarehouseDocumentLine( + id=key, + warehouse_document_id=key, + product_id=1, + warehouse_id=warehouse, + movement="in", + quantity=qty, + ), + WarehouseLineVariantAllocation( + id=key, + business_id=1, + product_id=1, + warehouse_document_line_id=key, + variant_id=variant, + quantity=qty, + ), + ] + ) + session.commit() + yield session + engine.dispose() + + +def calculate(db, count, **selector): + row = {"product_id": 1, "warehouse_id": 1, "physical_quantity": count, **selector} + return calculate_stock_count_differences(db, 1, [row], as_of_date=DAY)["items"][0] + + +@pytest.mark.parametrize(("count", "movement"), [(7, "out"), (8, None), (9, "in")]) +def test_count_uses_historical_variant_stock_and_keeps_adjustment_allocation(db, count, movement): + row = calculate(db, count, variant_id=1) + assert (row["system_quantity"], row["difference"], row["movement"]) == (8, count - 8, movement) + if movement is None: + with pytest.raises(ApiError) as error: + create_stock_count_adjustment(db, 1, None, "COUNT", DAY, [row]) + assert error.value.code == "NO_DIFFERENCES" + assert db.scalar(select(WarehouseDocument.id).filter_by(doc_type="adjustment")) is None + return + + document = create_stock_count_adjustment(db, 1, None, "COUNT", DAY, [row]) + line = db.scalars( + select(WarehouseDocumentLine).filter_by(warehouse_document_id=document.id) + ).one() + allocation = db.scalars( + select(WarehouseLineVariantAllocation).filter_by(warehouse_document_line_id=line.id) + ).one() + assert (line.movement, line.quantity, allocation.variant_id, allocation.quantity) == ( + movement, + 1, + 1, + 1, + ) + + +def test_existing_stock_count_selectors_keep_their_basis(db, monkeypatch): + assert calculate(db, 20)["system_quantity"] == 20 + monkeypatch.setattr(inventory_lot_service, "compute_available_lot_stock", lambda *_: Decimal(4)) + assert calculate(db, 4, lot_id=1, variant_id=2)["difference"] == 0 + assert calculate(db, 1, product_id=2, instance_id=1)["difference"] == 0 + + +def test_stock_count_rejects_unknown_variant(db): + with pytest.raises(ApiError) as error: + calculate(db, 8, variant_id=999) + assert error.value.code == "VARIANT_NOT_FOUND" + + +def test_stock_count_does_not_count_posted_reversal_of_cancelled_issue(db): + db.add_all( + [ + WarehouseDocument( + id=6, + business_id=1, + code="ISSUE", + status="cancelled", + doc_type="issue", + document_date=DAY, + ), + WarehouseDocument( + id=7, + business_id=1, + code="REVERSE", + status="posted", + doc_type="receipt", + document_date=DAY, + source_document_id=6, + extra_info={"cancels_warehouse_document_id": 6}, + ), + WarehouseDocumentLine( + id=7, + warehouse_document_id=7, + product_id=1, + warehouse_id=1, + movement="in", + quantity=2, + ), + WarehouseLineVariantAllocation( + id=7, + business_id=1, + product_id=1, + warehouse_document_line_id=7, + variant_id=1, + quantity=2, + ), + ] + ) + db.flush() + assert calculate(db, 8, variant_id=1)["difference"] == 0