افتتاحیهٔ Product Variant: حفظ تخصیص و واحد اصلی در همگامسازی حواله #69
6 changed files with 308 additions and 24 deletions
|
|
@ -1,14 +1,15 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import Any, Dict, List, Optional, Tuple
|
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
|
from typing import Any, Dict, List, Optional, Tuple
|
||||||
|
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from adapters.db.models.document import Document
|
||||||
|
from adapters.db.models.product import Product
|
||||||
from adapters.db.repositories.document_repository import DocumentRepository
|
from adapters.db.repositories.document_repository import DocumentRepository
|
||||||
from adapters.db.repositories.fiscal_year_repo import FiscalYearRepository
|
from adapters.db.repositories.fiscal_year_repo import FiscalYearRepository
|
||||||
from adapters.db.models.document import Document
|
|
||||||
from app.core.responses import ApiError
|
from app.core.responses import ApiError
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -264,6 +265,14 @@ def upsert_opening_balance(
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
from app.services.variant_allocation_service import opening_allocations_in_main_units
|
||||||
|
|
||||||
|
inventory_products = {
|
||||||
|
row.id: row for row in db.query(Product).filter(
|
||||||
|
Product.business_id == business_id,
|
||||||
|
Product.id.in_({int(line.get("product_id") or 0) for line in inventory_lines}),
|
||||||
|
)
|
||||||
|
} if inventory_lines else {}
|
||||||
# 2) Inventory lines (movement=in) + total valuation
|
# 2) Inventory lines (movement=in) + total valuation
|
||||||
inventory_total_value = Decimal(0)
|
inventory_total_value = Decimal(0)
|
||||||
for inv in inventory_lines:
|
for inv in inventory_lines:
|
||||||
|
|
@ -286,6 +295,10 @@ def upsert_opening_balance(
|
||||||
allocations = inv.get("allocations")
|
allocations = inv.get("allocations")
|
||||||
if isinstance(allocations, list) and allocations:
|
if isinstance(allocations, list) and allocations:
|
||||||
info["allocations"] = allocations
|
info["allocations"] = allocations
|
||||||
|
product = inventory_products.get(int(inv.get("product_id") or 0))
|
||||||
|
if product is None:
|
||||||
|
raise ApiError("PRODUCT_NOT_FOUND", "کالای افتتاحیه یافت نشد یا متعلق به کسبوکار نیست", http_status=404)
|
||||||
|
opening_allocations_in_main_units(db, business_id, product, qty, info, require_active=True)
|
||||||
lines.append(
|
lines.append(
|
||||||
{
|
{
|
||||||
"product_id": int(inv.get("product_id")),
|
"product_id": int(inv.get("product_id")),
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@ from __future__ import annotations
|
||||||
|
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple
|
from typing import Any, Dict, Iterable, List, Mapping, Optional
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from sqlalchemy import func
|
from sqlalchemy import func
|
||||||
|
|
@ -12,12 +12,27 @@ from sqlalchemy.orm import Session
|
||||||
from adapters.db.models.document import Document
|
from adapters.db.models.document import Document
|
||||||
from adapters.db.models.document_line import DocumentLine
|
from adapters.db.models.document_line import DocumentLine
|
||||||
from adapters.db.models.product import Product
|
from adapters.db.models.product import Product
|
||||||
|
from adapters.db.models.product_variant_allocation import WarehouseLineVariantAllocation
|
||||||
from adapters.db.models.warehouse_document import WarehouseDocument
|
from adapters.db.models.warehouse_document import WarehouseDocument
|
||||||
from adapters.db.models.warehouse_document_line import WarehouseDocumentLine
|
from adapters.db.models.warehouse_document_line import WarehouseDocumentLine
|
||||||
from app.core.responses import ApiError
|
from app.core.responses import ApiError
|
||||||
from app.services.invoice_unit_conversion_service import inventory_quantity_to_main
|
from app.services.invoice_unit_conversion_service import (
|
||||||
|
inventory_price_to_main,
|
||||||
|
inventory_quantity_to_main,
|
||||||
|
)
|
||||||
|
from app.services.product_variant_service import is_variant_inventory_product
|
||||||
|
from app.services.variant_allocation_service import (
|
||||||
|
opening_allocations_in_main_units,
|
||||||
|
validate_payload_for_product,
|
||||||
|
)
|
||||||
|
|
||||||
InventoryKey = Tuple[int, int]
|
InventoryKey = tuple[int, int] | tuple[int, int, int]
|
||||||
|
|
||||||
|
|
||||||
|
def _record_cost(costs: dict, key: InventoryKey, cost: Decimal) -> None:
|
||||||
|
if len(key) == 3 and key in costs and costs[key] != cost:
|
||||||
|
raise ApiError("OPENING_VARIANT_COST_AMBIGUOUS", "بهای ثبتشدهٔ این ترکیب یکتا نیست؛ همگامسازی خودکار مجاز نیست", http_status=409)
|
||||||
|
costs[key] = cost
|
||||||
|
|
||||||
|
|
||||||
def _decimal(value: Any) -> Decimal:
|
def _decimal(value: Any) -> Decimal:
|
||||||
|
|
@ -42,6 +57,7 @@ def build_opening_balance_warehouse_deltas(
|
||||||
|
|
||||||
def _desired_opening_inventory(
|
def _desired_opening_inventory(
|
||||||
db: Session,
|
db: Session,
|
||||||
|
business_id: int,
|
||||||
document_id: int,
|
document_id: int,
|
||||||
product_ids: List[int],
|
product_ids: List[int],
|
||||||
) -> tuple[Dict[InventoryKey, Decimal], Dict[InventoryKey, Decimal], Dict[InventoryKey, Dict[str, Any]]]:
|
) -> tuple[Dict[InventoryKey, Decimal], Dict[InventoryKey, Decimal], Dict[InventoryKey, Dict[str, Any]]]:
|
||||||
|
|
@ -56,7 +72,7 @@ def _desired_opening_inventory(
|
||||||
if product_ids:
|
if product_ids:
|
||||||
products_by_id = {
|
products_by_id = {
|
||||||
int(product.id): product
|
int(product.id): product
|
||||||
for product in db.query(Product).filter(Product.id.in_(product_ids)).all()
|
for product in db.query(Product).filter(Product.id.in_(product_ids), Product.business_id == business_id).all()
|
||||||
}
|
}
|
||||||
for row in rows:
|
for row in rows:
|
||||||
info = dict(row.extra_info or {})
|
info = dict(row.extra_info or {})
|
||||||
|
|
@ -71,9 +87,19 @@ def _desired_opening_inventory(
|
||||||
)
|
)
|
||||||
if warehouse_id is None or quantity <= 0:
|
if warehouse_id is None or quantity <= 0:
|
||||||
continue
|
continue
|
||||||
key = (int(row.product_id), int(warehouse_id))
|
product = products_by_id[int(row.product_id)]
|
||||||
desired[key] += quantity
|
native = is_variant_inventory_product(product)
|
||||||
costs[key] = _decimal(info.get("cost_price"))
|
if native:
|
||||||
|
quantities = [((int(row.product_id), int(warehouse_id), vid), qty)
|
||||||
|
for vid, qty, _price in opening_allocations_in_main_units(
|
||||||
|
db, business_id, product, row.quantity, info, require_active=True)]
|
||||||
|
cost = inventory_price_to_main(info.get("cost_price"), product, info, strict=True)
|
||||||
|
else:
|
||||||
|
quantities = [((int(row.product_id), int(warehouse_id)), quantity)]
|
||||||
|
cost = _decimal(info.get("cost_price"))
|
||||||
|
for key, qty in quantities:
|
||||||
|
desired[key] += qty
|
||||||
|
_record_cost(costs, key, cost)
|
||||||
lot_payload: Dict[str, Any] = {}
|
lot_payload: Dict[str, Any] = {}
|
||||||
if info.get("lot_allocations"):
|
if info.get("lot_allocations"):
|
||||||
lot_payload["lot_allocations"] = info.get("lot_allocations")
|
lot_payload["lot_allocations"] = info.get("lot_allocations")
|
||||||
|
|
@ -92,7 +118,8 @@ def _desired_opening_inventory(
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
if lot_payload:
|
if lot_payload:
|
||||||
lots[key] = lot_payload
|
for key, _qty in quantities:
|
||||||
|
lots[key] = lot_payload
|
||||||
return dict(desired), costs, lots
|
return dict(desired), costs, lots
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -101,8 +128,9 @@ def _linked_opening_inventory(
|
||||||
business_id: int,
|
business_id: int,
|
||||||
document_id: int,
|
document_id: int,
|
||||||
product_ids: List[int],
|
product_ids: List[int],
|
||||||
) -> Dict[InventoryKey, Decimal]:
|
) -> tuple[dict[InventoryKey, Decimal], dict[InventoryKey, Decimal]]:
|
||||||
linked: Dict[InventoryKey, Decimal] = defaultdict(Decimal)
|
linked: Dict[InventoryKey, Decimal] = defaultdict(Decimal)
|
||||||
|
costs: Dict[InventoryKey, Decimal] = {}
|
||||||
rows = (
|
rows = (
|
||||||
db.query(WarehouseDocumentLine)
|
db.query(WarehouseDocumentLine)
|
||||||
.join(
|
.join(
|
||||||
|
|
@ -122,23 +150,45 @@ def _linked_opening_inventory(
|
||||||
if product_ids:
|
if product_ids:
|
||||||
products_by_id = {
|
products_by_id = {
|
||||||
int(product.id): product
|
int(product.id): product
|
||||||
for product in db.query(Product).filter(Product.id.in_(product_ids)).all()
|
for product in db.query(Product).filter(Product.id.in_(product_ids), Product.business_id == business_id).all()
|
||||||
}
|
}
|
||||||
|
allocations_by_line = defaultdict(list)
|
||||||
|
if rows:
|
||||||
|
for allocation in db.query(WarehouseLineVariantAllocation).filter(
|
||||||
|
WarehouseLineVariantAllocation.warehouse_document_line_id.in_([row.id for row in rows])
|
||||||
|
):
|
||||||
|
allocations_by_line[allocation.warehouse_document_line_id].append(allocation)
|
||||||
for row in rows:
|
for row in rows:
|
||||||
if row.warehouse_id is None:
|
if row.warehouse_id is None:
|
||||||
continue
|
continue
|
||||||
key = (int(row.product_id), int(row.warehouse_id))
|
|
||||||
quantity = inventory_quantity_to_main(
|
quantity = inventory_quantity_to_main(
|
||||||
row.quantity,
|
row.quantity,
|
||||||
products_by_id.get(int(row.product_id)),
|
products_by_id.get(int(row.product_id)),
|
||||||
getattr(row, "extra_info", None),
|
getattr(row, "extra_info", None),
|
||||||
strict=False,
|
strict=False,
|
||||||
)
|
)
|
||||||
if str(row.movement or "").lower() == "in":
|
product = products_by_id[int(row.product_id)]
|
||||||
linked[key] += quantity
|
if is_variant_inventory_product(product):
|
||||||
elif str(row.movement or "").lower() == "out":
|
allocations = allocations_by_line[row.id]
|
||||||
linked[key] -= quantity
|
if any(a.business_id != business_id or a.product_id != row.product_id for a in allocations):
|
||||||
return dict(linked)
|
raise ApiError("OPENING_VARIANT_LINK_INVALID", "انتساب تخصیص حوالهٔ افتتاحیه نامعتبر است", http_status=409)
|
||||||
|
items = validate_payload_for_product(db, business_id, product, {"allocations": [
|
||||||
|
{"variant_id": a.variant_id, "quantity": a.quantity} for a in allocations
|
||||||
|
]}, quantity, require_active=False)
|
||||||
|
quantities = [((int(row.product_id), int(row.warehouse_id), vid), qty) for vid, qty, _price in items]
|
||||||
|
if "cost_price" not in (row.extra_info or {}):
|
||||||
|
raise ApiError("OPENING_VARIANT_COST_AMBIGUOUS", "بهای حوالهٔ افتتاحیه مشخص نیست", http_status=409)
|
||||||
|
cost = inventory_price_to_main(row.extra_info["cost_price"], product, row.extra_info, strict=True)
|
||||||
|
for key, _qty in quantities:
|
||||||
|
_record_cost(costs, key, cost)
|
||||||
|
else:
|
||||||
|
quantities = [((int(row.product_id), int(row.warehouse_id)), quantity)]
|
||||||
|
for key, qty in quantities:
|
||||||
|
if str(row.movement or "").lower() == "in":
|
||||||
|
linked[key] += qty
|
||||||
|
elif str(row.movement or "").lower() == "out":
|
||||||
|
linked[key] -= qty
|
||||||
|
return dict(linked), costs
|
||||||
|
|
||||||
|
|
||||||
def _assert_products_can_sync(
|
def _assert_products_can_sync(
|
||||||
|
|
@ -225,15 +275,16 @@ def _group_delta_lines(
|
||||||
receipts: Dict[int, List[Dict[str, Any]]] = defaultdict(list)
|
receipts: Dict[int, List[Dict[str, Any]]] = defaultdict(list)
|
||||||
issues: Dict[int, List[Dict[str, Any]]] = defaultdict(list)
|
issues: Dict[int, List[Dict[str, Any]]] = defaultdict(list)
|
||||||
lot_map = lots or {}
|
lot_map = lots or {}
|
||||||
for (product_id, warehouse_id), delta in sorted(deltas.items()):
|
for key, delta in sorted(deltas.items()):
|
||||||
|
product_id, warehouse_id = key[:2]
|
||||||
if not delta:
|
if not delta:
|
||||||
continue
|
continue
|
||||||
extra: Dict[str, Any] = {
|
extra: Dict[str, Any] = {
|
||||||
"opening_balance_sync": True,
|
"opening_balance_sync": True,
|
||||||
"cost_price": float(costs.get((product_id, warehouse_id), Decimal(0))),
|
"cost_price": float(costs.get(key, Decimal(0))),
|
||||||
}
|
}
|
||||||
if delta > 0:
|
if delta > 0:
|
||||||
lot_extra = dict(lot_map.get((product_id, warehouse_id)) or {})
|
lot_extra = dict(lot_map.get(key) or {})
|
||||||
allocs = [
|
allocs = [
|
||||||
dict(item)
|
dict(item)
|
||||||
for item in (lot_extra.get("lot_allocations") or [])
|
for item in (lot_extra.get("lot_allocations") or [])
|
||||||
|
|
@ -250,6 +301,9 @@ def _group_delta_lines(
|
||||||
"extra_info": extra,
|
"extra_info": extra,
|
||||||
"lot_allocations": extra.get("lot_allocations"),
|
"lot_allocations": extra.get("lot_allocations"),
|
||||||
}
|
}
|
||||||
|
if len(key) == 3:
|
||||||
|
extra["unit"] = "main"
|
||||||
|
extra["allocations"] = [{"variant_id": key[2], "quantity": str(abs(delta))}]
|
||||||
(receipts if delta > 0 else issues)[int(warehouse_id)].append(line)
|
(receipts if delta > 0 else issues)[int(warehouse_id)].append(line)
|
||||||
return dict(receipts), dict(issues)
|
return dict(receipts), dict(issues)
|
||||||
|
|
||||||
|
|
@ -278,15 +332,17 @@ def sync_opening_balance_warehouse_documents(
|
||||||
Document.id == int(opening_balance_document_id),
|
Document.id == int(opening_balance_document_id),
|
||||||
Document.business_id == int(business_id),
|
Document.business_id == int(business_id),
|
||||||
Document.document_type == "opening_balance",
|
Document.document_type == "opening_balance",
|
||||||
).first()
|
).with_for_update().first()
|
||||||
if opening_document is None:
|
if opening_document is None:
|
||||||
raise ApiError("OPENING_BALANCE_NOT_FOUND", "سند تراز افتتاحیه یافت نشد", http_status=404)
|
raise ApiError("OPENING_BALANCE_NOT_FOUND", "سند تراز افتتاحیه یافت نشد", http_status=404)
|
||||||
|
|
||||||
_assert_products_can_sync(db, business_id, product_ids)
|
_assert_products_can_sync(db, business_id, product_ids)
|
||||||
_assert_no_unrelated_posted_history(db, business_id, product_ids)
|
_assert_no_unrelated_posted_history(db, business_id, product_ids)
|
||||||
|
|
||||||
desired, costs, lots = _desired_opening_inventory(db, int(opening_document.id), product_ids)
|
desired, costs, lots = _desired_opening_inventory(db, business_id, int(opening_document.id), product_ids)
|
||||||
linked = _linked_opening_inventory(db, business_id, int(opening_document.id), product_ids)
|
linked, linked_costs = _linked_opening_inventory(db, business_id, int(opening_document.id), product_ids)
|
||||||
|
for key, cost in linked_costs.items():
|
||||||
|
_record_cost(costs, key, cost)
|
||||||
deltas = build_opening_balance_warehouse_deltas(desired, linked)
|
deltas = build_opening_balance_warehouse_deltas(desired, linked)
|
||||||
receipts, issues = _group_delta_lines(deltas, costs, lots)
|
receipts, issues = _group_delta_lines(deltas, costs, lots)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,7 @@ from adapters.db.models.warehouse_document_line import WarehouseDocumentLine
|
||||||
from app.core.responses import ApiError
|
from app.core.responses import ApiError
|
||||||
from app.services.invoice_unit_conversion_service import (
|
from app.services.invoice_unit_conversion_service import (
|
||||||
extra_info_dict,
|
extra_info_dict,
|
||||||
|
inventory_quantity_is_already_main,
|
||||||
quantity_line_to_main,
|
quantity_line_to_main,
|
||||||
)
|
)
|
||||||
from app.services.product_variant_service import (
|
from app.services.product_variant_service import (
|
||||||
|
|
@ -184,6 +185,19 @@ def convert_allocations_to_main(
|
||||||
return converted
|
return converted
|
||||||
|
|
||||||
|
|
||||||
|
def opening_allocations_in_main_units(
|
||||||
|
db: Session, business_id: int, product: Product, quantity: Any, extra_info: Any,
|
||||||
|
*, require_active: bool = False,
|
||||||
|
) -> list[tuple[int, Decimal, Decimal | None]]:
|
||||||
|
info = extra_info_dict(extra_info)
|
||||||
|
items = validate_payload_for_product(
|
||||||
|
db, business_id, product, {"extra_info": info, "quantity": quantity}, _d(quantity),
|
||||||
|
require_active=require_active,
|
||||||
|
)
|
||||||
|
unit = "main" if inventory_quantity_is_already_main(info) else info.get("unit")
|
||||||
|
return convert_allocations_to_main(product, items, unit)
|
||||||
|
|
||||||
|
|
||||||
def persist_warehouse_allocations(
|
def persist_warehouse_allocations(
|
||||||
db: Session,
|
db: Session,
|
||||||
business_id: int,
|
business_id: int,
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ from sqlalchemy import and_, case, func, or_
|
||||||
from sqlalchemy.orm import Session, aliased
|
from sqlalchemy.orm import Session, aliased
|
||||||
|
|
||||||
from adapters.db.models.document import Document
|
from adapters.db.models.document import Document
|
||||||
|
from adapters.db.models.document_line import DocumentLine
|
||||||
from adapters.db.models.inventory_variant_balance import InventoryVariantBalance
|
from adapters.db.models.inventory_variant_balance import InventoryVariantBalance
|
||||||
from adapters.db.models.invoice_item_line import InvoiceItemLine
|
from adapters.db.models.invoice_item_line import InvoiceItemLine
|
||||||
from adapters.db.models.product import Product
|
from adapters.db.models.product import Product
|
||||||
|
|
@ -151,6 +152,36 @@ def compute_available_variant_stock(
|
||||||
else:
|
else:
|
||||||
bal -= qty
|
bal -= qty
|
||||||
|
|
||||||
|
# Opening stock is financial stock, like the product-level reader; its warehouse mirror is excluded below.
|
||||||
|
if product is not None and is_variant_inventory_product(product) and product.track_inventory:
|
||||||
|
from app.services.variant_allocation_service import opening_allocations_in_main_units
|
||||||
|
|
||||||
|
opening_q = db.query(Document.id).filter(
|
||||||
|
Document.business_id == int(business_id), Document.document_type == "opening_balance",
|
||||||
|
Document.is_proforma == False, Document.document_date <= up_to_date, # noqa: E712
|
||||||
|
)
|
||||||
|
if exclude_document_id is not None:
|
||||||
|
opening_q = opening_q.filter(Document.id != int(exclude_document_id))
|
||||||
|
opening_ids = [row.id for row in opening_q]
|
||||||
|
opening_lines = db.query(DocumentLine).filter(
|
||||||
|
DocumentLine.document_id.in_(opening_ids), DocumentLine.product_id == int(product_id),
|
||||||
|
).all() if opening_ids else []
|
||||||
|
for line in opening_lines:
|
||||||
|
info = extra_info_dict(line.extra_info)
|
||||||
|
if (info.get("movement") or "in") != "in" or info.get("inventory_posted") is False or info.get("inventory_tracked") is False:
|
||||||
|
continue
|
||||||
|
if warehouse_id is not None:
|
||||||
|
try:
|
||||||
|
if int(info.get("warehouse_id")) != int(warehouse_id):
|
||||||
|
continue
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
continue
|
||||||
|
if _d(line.quantity) <= 0:
|
||||||
|
continue
|
||||||
|
for vid, qty, _price in opening_allocations_in_main_units(db, business_id, product, line.quantity, info):
|
||||||
|
if vid == int(variant_id):
|
||||||
|
bal += qty
|
||||||
|
|
||||||
wh_q = (
|
wh_q = (
|
||||||
db.query(WarehouseLineVariantAllocation, WarehouseDocumentLine, WarehouseDocument)
|
db.query(WarehouseLineVariantAllocation, WarehouseDocumentLine, WarehouseDocument)
|
||||||
.join(
|
.join(
|
||||||
|
|
|
||||||
29
hesabixAPI/tests/test_opening_variant_stock_readers.py
Normal file
29
hesabixAPI/tests/test_opening_variant_stock_readers.py
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.services.invoice_service import _compute_available_stock
|
||||||
|
from app.services.opening_balance_warehouse_sync_service import (
|
||||||
|
sync_opening_balance_warehouse_documents as synchronize,
|
||||||
|
)
|
||||||
|
from app.services.variant_inventory_service import compute_available_variant_stock
|
||||||
|
from tests.test_opening_variant_sync import DAY, payload, save
|
||||||
|
from tests.test_opening_variant_sync import opening_db as opening_db
|
||||||
|
from tests.test_warehouse_transfer_currency import transfer_db as transfer_db
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("unit", ["main", "each"])
|
||||||
|
def test_opening_is_counted_once_before_and_after_warehouse_mirror(opening_db, unit):
|
||||||
|
db = opening_db
|
||||||
|
did = save(db, payload(unit=unit))
|
||||||
|
for mirrored in (False, True):
|
||||||
|
if mirrored:
|
||||||
|
synchronize(db, 1, 1, did, [1])
|
||||||
|
db.commit()
|
||||||
|
quantities = [compute_available_variant_stock(db, 1, 1, 11, vid, DAY) for vid in (1, 2)]
|
||||||
|
assert quantities == [8, 12]
|
||||||
|
assert _compute_available_stock(db, 1, 1, 11, DAY) == sum(quantities) == 20
|
||||||
|
assert compute_available_variant_stock(db, 1, 1, 12, 1, DAY) == 0
|
||||||
|
assert compute_available_variant_stock(db, 2, 1, 11, 1, DAY) == 0
|
||||||
|
assert compute_available_variant_stock(db, 1, 1, 11, 1, DAY - timedelta(days=1)) == 0
|
||||||
|
assert compute_available_variant_stock(db, 1, 1, 11, 1, DAY, exclude_document_id=did) == 0
|
||||||
141
hesabixAPI/tests/test_opening_variant_sync.py
Normal file
141
hesabixAPI/tests/test_opening_variant_sync.py
Normal file
|
|
@ -0,0 +1,141 @@
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlalchemy import event
|
||||||
|
from sqlalchemy.schema import CreateTable
|
||||||
|
|
||||||
|
from adapters.db import models
|
||||||
|
from adapters.db.models.activity_log import ActivityLog
|
||||||
|
from adapters.db.models.product_variant import ProductVariant
|
||||||
|
from adapters.db.models.product_variant_allocation import WarehouseLineVariantAllocation
|
||||||
|
from app.core.responses import ApiError
|
||||||
|
from app.services.opening_balance_service import (
|
||||||
|
post_opening_balance,
|
||||||
|
unpost_opening_balance,
|
||||||
|
upsert_opening_balance,
|
||||||
|
)
|
||||||
|
from app.services.opening_balance_warehouse_sync_service import (
|
||||||
|
sync_opening_balance_warehouse_documents as synchronize,
|
||||||
|
)
|
||||||
|
from app.services.product_variant_service import list_variant_balances
|
||||||
|
from tests.test_warehouse_transfer_currency import DAY as DAY
|
||||||
|
from tests.test_warehouse_transfer_currency import transfer_db as transfer_db
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def opening_db(transfer_db):
|
||||||
|
db = transfer_db
|
||||||
|
event.listen(db.bind, "begin", lambda connection: connection.exec_driver_sql("BEGIN"))
|
||||||
|
with db.bind.begin() as connection:
|
||||||
|
for model in (models.Account, models.User, ActivityLog):
|
||||||
|
connection.execute(CreateTable(model.__table__, include_foreign_key_constraints=[]))
|
||||||
|
product = db.get(models.Product, 1)
|
||||||
|
product.variant_mode, product.track_inventory = "inventory", True
|
||||||
|
product.main_unit, product.secondary_unit, product.unit_conversion_factor = "carton", "each", Decimal(10)
|
||||||
|
db.add_all([
|
||||||
|
models.User(id=1, first_name="Test", password_hash="fixture", referral_code="OPENINGSYNC"),
|
||||||
|
models.Account(id=1, business_id=1, code="INV", name="Inventory", account_type="asset"),
|
||||||
|
models.Account(id=2, business_id=1, code="EQUITY", name="Equity", account_type="equity"),
|
||||||
|
models.Product(id=4, business_id=1, code="OTHER", name="Other", variant_mode="inventory"),
|
||||||
|
])
|
||||||
|
for vid, bid, pid in ((1, 1, 1), (2, 1, 1), (3, 2, 2), (4, 1, 4)):
|
||||||
|
db.add(ProductVariant(id=vid, business_id=bid, product_id=pid, combination_key=str(vid)))
|
||||||
|
db.commit()
|
||||||
|
return db
|
||||||
|
|
||||||
|
|
||||||
|
def payload(shares=(8, 12), unit="main", cost=None):
|
||||||
|
scale = 10 if unit == "each" else 1
|
||||||
|
return {
|
||||||
|
"fiscal_year_id": 1, "currency_id": 2, "inventory_account_id": 1, "equity_account_id": 2,
|
||||||
|
"auto_balance_to_equity": True,
|
||||||
|
"inventory_lines": [{"product_id": 1, "quantity": sum(shares) * scale,
|
||||||
|
"allocations": [{"variant_id": vid, "quantity": qty * scale} for vid, qty in zip((1, 2), shares, strict=True)],
|
||||||
|
"extra_info": {"warehouse_id": 11, "unit": unit,
|
||||||
|
"cost_price": (10 if scale == 10 else 100) if cost is None else cost}}],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def save(db, data):
|
||||||
|
result = upsert_opening_balance(db, 1, 1, data, auto_commit=False, return_details=False)
|
||||||
|
db.commit()
|
||||||
|
return result["id"]
|
||||||
|
|
||||||
|
|
||||||
|
def gl(db):
|
||||||
|
return [(r.id, r.quantity, r.debit, r.credit, r.extra_info) for r in db.query(models.DocumentLine).order_by(models.DocumentLine.id)]
|
||||||
|
|
||||||
|
|
||||||
|
def physical(db):
|
||||||
|
return {r["variant_id"]: Decimal(r["quantity"]) for r in list_variant_balances(db, 1, 1, 11)}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("unit", ["main", "each"])
|
||||||
|
def test_sync_and_legal_share_edit_preserve_variant_main_quantities(opening_db, unit):
|
||||||
|
db = opening_db
|
||||||
|
did = save(db, payload(unit=unit))
|
||||||
|
before_gl = gl(db)
|
||||||
|
first = synchronize(db, 1, 1, did, [1])
|
||||||
|
db.commit()
|
||||||
|
assert first["receipts_created"] == 1 and physical(db) == {1: 8, 2: 12}
|
||||||
|
assert gl(db) == before_gl
|
||||||
|
assert sorted((r.variant_id, r.quantity) for r in db.query(WarehouseLineVariantAllocation)) == [(1, 8), (2, 12)]
|
||||||
|
assert all(r.extra_info["cost_price"] == 100 for r in db.query(models.WarehouseDocumentLine))
|
||||||
|
again = synchronize(db, 1, 1, did, [1])
|
||||||
|
db.commit()
|
||||||
|
assert again["document_ids"] == [] and db.query(models.WarehouseDocument).count() == 1
|
||||||
|
post_opening_balance(db, 1, 1, 1)
|
||||||
|
with pytest.raises(ApiError) as error:
|
||||||
|
upsert_opening_balance(db, 1, 1, payload((7, 13), unit), auto_commit=False)
|
||||||
|
assert error.value.code == "OPENING_BALANCE_POSTED"
|
||||||
|
unpost_opening_balance(db, 1, 1, 1)
|
||||||
|
save(db, payload((7, 13), unit))
|
||||||
|
edited = synchronize(db, 1, 1, did, [1])
|
||||||
|
db.commit()
|
||||||
|
assert (edited["issues_created"], edited["receipts_created"]) == (1, 1)
|
||||||
|
assert physical(db) == {1: 7, 2: 13}
|
||||||
|
assert sum(r.debit for r in db.query(models.DocumentLine)) == 2000
|
||||||
|
assert sum(r.credit for r in db.query(models.DocumentLine)) == 2000
|
||||||
|
assert synchronize(db, 1, 1, did, [1])["document_ids"] == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("vid,qty,code", [(999, 20, "VARIANT_NOT_FOUND"), (3, 20, "VARIANT_NOT_FOUND"),
|
||||||
|
(4, 20, "VARIANT_NOT_FOUND"), (1, 19, "VARIANT_ALLOCATION_MISMATCH"),
|
||||||
|
(None, 0, "VARIANT_REQUIRED")])
|
||||||
|
def test_opening_financial_write_rejects_invalid_explicit_allocation(opening_db, vid, qty, code):
|
||||||
|
db = opening_db
|
||||||
|
data = payload()
|
||||||
|
data["inventory_lines"][0]["allocations"] = [{"variant_id": vid, "quantity": qty}] if vid else []
|
||||||
|
with pytest.raises(ApiError) as error:
|
||||||
|
upsert_opening_balance(db, 1, 1, data, auto_commit=False)
|
||||||
|
assert error.value.code == code
|
||||||
|
db.rollback()
|
||||||
|
assert db.query(models.Document).count() == db.query(models.WarehouseDocument).count() == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_sync_rollback_restores_allocations_balances_and_allows_retry(opening_db):
|
||||||
|
db = opening_db
|
||||||
|
did = save(db, payload())
|
||||||
|
before_gl = gl(db)
|
||||||
|
synchronize(db, 1, 1, did, [1])
|
||||||
|
assert physical(db) == {1: 8, 2: 12}
|
||||||
|
db.rollback()
|
||||||
|
assert db.query(models.WarehouseDocument).count() == db.query(WarehouseLineVariantAllocation).count() == 0
|
||||||
|
assert physical(db) == {} and gl(db) == before_gl
|
||||||
|
synchronize(db, 1, 1, did, [1])
|
||||||
|
db.commit()
|
||||||
|
assert physical(db) == {1: 8, 2: 12}
|
||||||
|
|
||||||
|
|
||||||
|
def test_changed_stock_cost_is_rejected_without_choosing_current_or_last_cost(opening_db):
|
||||||
|
db = opening_db
|
||||||
|
did = save(db, payload())
|
||||||
|
synchronize(db, 1, 1, did, [1])
|
||||||
|
db.commit()
|
||||||
|
before_gl = gl(db)
|
||||||
|
upsert_opening_balance(db, 1, 1, payload(cost=200), auto_commit=False)
|
||||||
|
with pytest.raises(ApiError) as error:
|
||||||
|
synchronize(db, 1, 1, did, [1])
|
||||||
|
assert (error.value.code, error.value.status_code) == ("OPENING_VARIANT_COST_AMBIGUOUS", 409)
|
||||||
|
db.rollback()
|
||||||
|
assert physical(db) == {1: 8, 2: 12} and gl(db) == before_gl
|
||||||
Loading…
Reference in a new issue