انتقال Product Variant: حفظ تخصیص دو سمت و انتخاب ارز پایهٔ کسبوکار #66
4 changed files with 299 additions and 19 deletions
|
|
@ -2,6 +2,7 @@
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections import Counter
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
|
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
|
||||||
|
|
||||||
|
|
@ -342,6 +343,24 @@ def assert_transfer_allocations_match(
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def assert_transfer_document_allocations_match(db: Session, lines: Sequence[WarehouseDocumentLine]) -> None:
|
||||||
|
"""Match the multiset of line quantities and Variant allocations, not product alone."""
|
||||||
|
sides = {"in": Counter(), "out": Counter()}
|
||||||
|
for line in lines:
|
||||||
|
rows = list_warehouse_line_allocations(db, int(line.id))
|
||||||
|
signature = (
|
||||||
|
int(line.product_id), _d(line.quantity),
|
||||||
|
tuple(sorted((int(row.variant_id), _d(row.quantity)) for row in rows)),
|
||||||
|
)
|
||||||
|
sides[str(line.movement)][signature] += 1
|
||||||
|
if sides["in"] != sides["out"]:
|
||||||
|
raise ApiError(
|
||||||
|
"TRANSFER_VARIANT_MISMATCH",
|
||||||
|
"مقدار و تخصیص ویژگی دو سمت حواله انتقال یکسان نیست",
|
||||||
|
http_status=422,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def allocations_as_payload(rows: Iterable[WarehouseLineVariantAllocation]) -> List[Dict[str, Any]]:
|
def allocations_as_payload(rows: Iterable[WarehouseLineVariantAllocation]) -> List[Dict[str, Any]]:
|
||||||
return [
|
return [
|
||||||
{"variant_id": int(row.variant_id), "quantity": str(row.quantity)}
|
{"variant_id": int(row.variant_id), "quantity": str(row.quantity)}
|
||||||
|
|
|
||||||
|
|
@ -2014,6 +2014,7 @@ def create_manual_warehouse_document(
|
||||||
if wh is None:
|
if wh is None:
|
||||||
raise ApiError("WAREHOUSE_CODE_CONFLICT", "Failed to generate unique warehouse document code", http_status=500)
|
raise ApiError("WAREHOUSE_CODE_CONFLICT", "Failed to generate unique warehouse document code", http_status=500)
|
||||||
|
|
||||||
|
transfer_pairs = []
|
||||||
# ایجاد خطوط
|
# ایجاد خطوط
|
||||||
for i, ln in enumerate(lines_data, start=1):
|
for i, ln in enumerate(lines_data, start=1):
|
||||||
pid = ln.get("product_id")
|
pid = ln.get("product_id")
|
||||||
|
|
@ -2281,6 +2282,14 @@ def create_manual_warehouse_document(
|
||||||
instance_ids=final_instance_ids if final_instance_ids else None,
|
instance_ids=final_instance_ids if final_instance_ids else None,
|
||||||
)
|
)
|
||||||
db.add(wline_in)
|
db.add(wline_in)
|
||||||
|
db.flush()
|
||||||
|
_attach_variant_allocations_for_warehouse_line(db, business_id, wh, wline_out, product, ln)
|
||||||
|
from app.services.variant_allocation_service import (
|
||||||
|
copy_warehouse_allocations_to_reverse_line,
|
||||||
|
)
|
||||||
|
|
||||||
|
copy_warehouse_allocations_to_reverse_line(db, business_id, wline_out, wline_in)
|
||||||
|
transfer_pairs.append((wline_out, wline_in))
|
||||||
else:
|
else:
|
||||||
# برای سایر انواع: movement بر اساس doc_type
|
# برای سایر انواع: movement بر اساس doc_type
|
||||||
# منطق fallback برای انبار:
|
# منطق fallback برای انبار:
|
||||||
|
|
@ -2359,15 +2368,7 @@ def create_manual_warehouse_document(
|
||||||
copy_warehouse_lot_allocations_to_reverse_line,
|
copy_warehouse_lot_allocations_to_reverse_line,
|
||||||
)
|
)
|
||||||
|
|
||||||
posted_lines = (
|
for out_line, in_line in transfer_pairs:
|
||||||
db.query(WarehouseDocumentLine)
|
|
||||||
.filter(WarehouseDocumentLine.warehouse_document_id == int(wh.id))
|
|
||||||
.all()
|
|
||||||
)
|
|
||||||
outs = [ln for ln in posted_lines if ln.movement == "out"]
|
|
||||||
ins = [ln for ln in posted_lines if ln.movement == "in"]
|
|
||||||
for out_line in outs:
|
|
||||||
in_line = next((x for x in ins if int(x.product_id) == int(out_line.product_id)), None)
|
|
||||||
if in_line is not None:
|
if in_line is not None:
|
||||||
assert_transfer_allocations_match(db, out_line, in_line)
|
assert_transfer_allocations_match(db, out_line, in_line)
|
||||||
from adapters.db.models.inventory_lot import WarehouseLineLotAllocation
|
from adapters.db.models.inventory_lot import WarehouseLineLotAllocation
|
||||||
|
|
@ -3332,6 +3333,15 @@ def update_warehouse_document(
|
||||||
|
|
||||||
db.flush()
|
db.flush()
|
||||||
|
|
||||||
|
if wh.doc_type == "transfer" and not is_posted and "lines" in data:
|
||||||
|
from app.services.variant_allocation_service import (
|
||||||
|
assert_transfer_document_allocations_match,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert_transfer_document_allocations_match(
|
||||||
|
db, db.query(WarehouseDocumentLine).filter_by(warehouse_document_id=wh.id).all()
|
||||||
|
)
|
||||||
|
|
||||||
# دریافت اطلاعات قبل از بهروزرسانی برای invalidation
|
# دریافت اطلاعات قبل از بهروزرسانی برای invalidation
|
||||||
old_fiscal_year_id = wh.fiscal_year_id
|
old_fiscal_year_id = wh.fiscal_year_id
|
||||||
old_doc_type = wh.doc_type
|
old_doc_type = wh.doc_type
|
||||||
|
|
@ -3457,6 +3467,14 @@ def update_warehouse_document_line(
|
||||||
validate_warehouse_location_for_line(db, business_id, int(wline.warehouse_id), lid)
|
validate_warehouse_location_for_line(db, business_id, int(wline.warehouse_id), lid)
|
||||||
wline.warehouse_location_id = lid
|
wline.warehouse_location_id = lid
|
||||||
|
|
||||||
|
if wh.doc_type == "transfer" and any(key in data for key in ("quantity", "allocations", "variant_id")):
|
||||||
|
product = db.query(Product).filter_by(id=wline.product_id, business_id=business_id).first()
|
||||||
|
if product is None:
|
||||||
|
raise ApiError("PRODUCT_NOT_FOUND", "محصول یافت نشد", http_status=404)
|
||||||
|
payload = dict(data)
|
||||||
|
payload.setdefault("quantity", wline.quantity)
|
||||||
|
_attach_variant_allocations_for_warehouse_line(db, business_id, wh, wline, product, payload)
|
||||||
|
|
||||||
wh.touch()
|
wh.touch()
|
||||||
db.flush()
|
db.flush()
|
||||||
return wline
|
return wline
|
||||||
|
|
@ -3497,10 +3515,23 @@ def post_warehouse_document(
|
||||||
)
|
)
|
||||||
|
|
||||||
assert_cancel_reversal_postable(db, wh)
|
assert_cancel_reversal_postable(db, wh)
|
||||||
|
transfer_currency = None
|
||||||
|
if wh.doc_type == "transfer":
|
||||||
|
from app.services.business_currency_rate_service import _get_business_default_currency_id
|
||||||
|
|
||||||
|
transfer_currency = db.get(Currency, _get_business_default_currency_id(db, int(wh.business_id)))
|
||||||
|
if transfer_currency is None:
|
||||||
|
raise ApiError("CURRENCY_NOT_FOUND", "ارز پایه کسبوکار یافت نشد", http_status=404)
|
||||||
|
|
||||||
lines = db.query(WarehouseDocumentLine).filter(WarehouseDocumentLine.warehouse_document_id == wh.id).all()
|
lines = db.query(WarehouseDocumentLine).filter(WarehouseDocumentLine.warehouse_document_id == wh.id).all()
|
||||||
if not lines:
|
if not lines:
|
||||||
raise ApiError("NO_LINES", "حواله باید حداقل یک خط داشته باشد", http_status=400)
|
raise ApiError("NO_LINES", "حواله باید حداقل یک خط داشته باشد", http_status=400)
|
||||||
|
if wh.doc_type == "transfer":
|
||||||
|
from app.services.variant_allocation_service import (
|
||||||
|
assert_transfer_document_allocations_match,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert_transfer_document_allocations_match(db, lines)
|
||||||
if wh.source_type == "invoice" and wh.doc_type == "receipt" and wh.source_document_id:
|
if wh.source_type == "invoice" and wh.doc_type == "receipt" and wh.source_document_id:
|
||||||
from app.services.woo_return_source_service import STOCK_KEY, validate_woo_return_receipt
|
from app.services.woo_return_source_service import STOCK_KEY, validate_woo_return_receipt
|
||||||
|
|
||||||
|
|
@ -3724,7 +3755,7 @@ def post_warehouse_document(
|
||||||
wh.status = "posted"
|
wh.status = "posted"
|
||||||
from app.services.variant_inventory_service import rebuild_balances_for_warehouse_document
|
from app.services.variant_inventory_service import rebuild_balances_for_warehouse_document
|
||||||
|
|
||||||
if doc_type in ("issue", "receipt", "adjustment") and not (wh.extra_info or {}).get("cancels_warehouse_document_id"):
|
if doc_type in ("issue", "receipt", "adjustment", "transfer") and not (wh.extra_info or {}).get("cancels_warehouse_document_id"):
|
||||||
# The balance query filters on the persisted posted status.
|
# The balance query filters on the persisted posted status.
|
||||||
db.flush([wh])
|
db.flush([wh])
|
||||||
rebuild_balances_for_warehouse_document(db, wh)
|
rebuild_balances_for_warehouse_document(db, wh)
|
||||||
|
|
@ -3769,14 +3800,6 @@ def post_warehouse_document(
|
||||||
|
|
||||||
# اگر doc_type='transfer' باشد، یک سند حسابداری ایجاد کن
|
# اگر doc_type='transfer' باشد، یک سند حسابداری ایجاد کن
|
||||||
if wh.doc_type == "transfer":
|
if wh.doc_type == "transfer":
|
||||||
# دریافت currency_id (از business یا default)
|
|
||||||
currency = db.query(Currency).filter(Currency.business_id == wh.business_id).first()
|
|
||||||
if not currency:
|
|
||||||
# استفاده از currency پیشفرض
|
|
||||||
currency = db.query(Currency).filter(Currency.code == "IRR").first()
|
|
||||||
if not currency:
|
|
||||||
raise ApiError("CURRENCY_NOT_FOUND", "Currency not found", http_status=404)
|
|
||||||
|
|
||||||
fiscal_year = _get_current_fiscal_year(db, wh.business_id)
|
fiscal_year = _get_current_fiscal_year(db, wh.business_id)
|
||||||
|
|
||||||
# ساخت کد سند (مشابه inventory_transfer_service)
|
# ساخت کد سند (مشابه inventory_transfer_service)
|
||||||
|
|
@ -3814,7 +3837,7 @@ def post_warehouse_document(
|
||||||
code=doc_code,
|
code=doc_code,
|
||||||
document_type="inventory_transfer",
|
document_type="inventory_transfer",
|
||||||
document_date=wh.document_date,
|
document_date=wh.document_date,
|
||||||
currency_id=currency.id,
|
currency_id=transfer_currency.id,
|
||||||
created_by_user_id=wh.created_by_user_id,
|
created_by_user_id=wh.created_by_user_id,
|
||||||
registered_at=datetime.utcnow(),
|
registered_at=datetime.utcnow(),
|
||||||
is_proforma=False,
|
is_proforma=False,
|
||||||
|
|
|
||||||
140
hesabixAPI/tests/test_variant_transfer_posting.py
Normal file
140
hesabixAPI/tests/test_variant_transfer_posting.py
Normal file
|
|
@ -0,0 +1,140 @@
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from adapters.db import models
|
||||||
|
from adapters.db.models.product_variant_allocation import WarehouseLineVariantAllocation
|
||||||
|
from app.core.responses import ApiError
|
||||||
|
from app.services.product_variant_service import list_variant_balances
|
||||||
|
from app.services.warehouse_service import (
|
||||||
|
create_manual_warehouse_document,
|
||||||
|
post_warehouse_document,
|
||||||
|
update_warehouse_document,
|
||||||
|
update_warehouse_document_line,
|
||||||
|
)
|
||||||
|
from tests.test_warehouse_transfer_currency import DAY
|
||||||
|
from tests.test_warehouse_transfer_currency import transfer_db as transfer_db
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def native_db(transfer_db):
|
||||||
|
db = transfer_db
|
||||||
|
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(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, 1, 4), (4, 2, 2)):
|
||||||
|
db.add(models.ProductVariant(id=vid, business_id=bid, product_id=pid, combination_key=str(vid)))
|
||||||
|
db.commit()
|
||||||
|
receipt = create_manual_warehouse_document(db, 1, 1, {
|
||||||
|
"doc_type": "receipt", "document_date": DAY.isoformat(), "warehouse_id_to": 11,
|
||||||
|
"lines": [line(1, 10), line(2, 12)],
|
||||||
|
})
|
||||||
|
post_warehouse_document(db, receipt.id)
|
||||||
|
db.commit()
|
||||||
|
return db
|
||||||
|
|
||||||
|
|
||||||
|
def line(variant, qty, unit="main", **fields):
|
||||||
|
return {"product_id": 1, "quantity": qty, "allocations": [{"variant_id": variant, "quantity": qty}],
|
||||||
|
"extra_info": {"unit": unit, "unit_cost": 100}, **fields}
|
||||||
|
|
||||||
|
|
||||||
|
def transfer(db, entries):
|
||||||
|
doc = create_manual_warehouse_document(db, 1, 1, {
|
||||||
|
"doc_type": "transfer", "document_date": DAY.isoformat(),
|
||||||
|
"warehouse_id_from": 11, "warehouse_id_to": 12, "lines": entries,
|
||||||
|
})
|
||||||
|
db.commit()
|
||||||
|
return doc
|
||||||
|
|
||||||
|
|
||||||
|
def allocations(db, did):
|
||||||
|
return sorted((r.movement, r.quantity, a.variant_id, a.quantity) for r, a in
|
||||||
|
db.query(models.WarehouseDocumentLine, WarehouseLineVariantAllocation).join(
|
||||||
|
WarehouseLineVariantAllocation,
|
||||||
|
WarehouseLineVariantAllocation.warehouse_document_line_id == models.WarehouseDocumentLine.id,
|
||||||
|
).filter(models.WarehouseDocumentLine.warehouse_document_id == did))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("unit,quantities", [("main", (2, 3)), ("each", (20, 30))])
|
||||||
|
@pytest.mark.parametrize("edit", [False, True])
|
||||||
|
def test_official_transfer_preserves_main_unit_allocations_and_balances(native_db, unit, quantities, edit):
|
||||||
|
db = native_db
|
||||||
|
doc = transfer(db, [line(1, quantities[0], unit), line(2, quantities[1], unit)])
|
||||||
|
if edit:
|
||||||
|
update_warehouse_document(db, 1, doc.id, 1, {"lines": [
|
||||||
|
line(vid, qty, unit, movement=movement, warehouse_id=wid)
|
||||||
|
for vid, qty in zip((1, 2), quantities, strict=True)
|
||||||
|
for movement, wid in (("out", 11), ("in", 12))
|
||||||
|
]})
|
||||||
|
db.commit()
|
||||||
|
expected = sorted((movement, q, vid, q) for vid, q in ((1, 2), (2, 3)) for movement in ("in", "out"))
|
||||||
|
assert allocations(db, doc.id) == expected
|
||||||
|
post_warehouse_document(db, doc.id)
|
||||||
|
db.commit()
|
||||||
|
db.expire_all()
|
||||||
|
assert allocations(db, doc.id) == expected
|
||||||
|
for wid, expected_balances in ((11, {1: 8, 2: 9}), (12, {1: 2, 2: 3})):
|
||||||
|
assert {r["variant_id"]: Decimal(r["quantity"]) for r in list_variant_balances(db, 1, 1, wid)} == expected_balances
|
||||||
|
assert doc.status == "posted"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("vid,allocated,code", [(999, 2, "VARIANT_NOT_FOUND"), (3, 2, "VARIANT_NOT_FOUND"),
|
||||||
|
(4, 2, "VARIANT_NOT_FOUND"), (1, 1, "VARIANT_ALLOCATION_MISMATCH")])
|
||||||
|
def test_transfer_rejects_invalid_variant_or_quantity(native_db, vid, allocated, code):
|
||||||
|
db = native_db
|
||||||
|
payload = line(vid, 2)
|
||||||
|
payload["allocations"][0]["quantity"] = allocated
|
||||||
|
with pytest.raises(ApiError) as error:
|
||||||
|
transfer(db, [payload])
|
||||||
|
assert error.value.code == code
|
||||||
|
db.rollback()
|
||||||
|
assert {r["variant_id"]: Decimal(r["quantity"]) for r in list_variant_balances(db, 1, 1, 11)} == {1: 10, 2: 12}
|
||||||
|
|
||||||
|
|
||||||
|
def test_draft_edit_cannot_change_only_one_side_variant(native_db):
|
||||||
|
db = native_db
|
||||||
|
doc = transfer(db, [line(1, 2), line(2, 3)])
|
||||||
|
before = allocations(db, doc.id)
|
||||||
|
with pytest.raises(ApiError) as error:
|
||||||
|
update_warehouse_document(db, 1, doc.id, 1, {"lines": [
|
||||||
|
line(1, 2, movement="out", warehouse_id=11), line(2, 2, movement="in", warehouse_id=12),
|
||||||
|
]})
|
||||||
|
assert error.value.code == "TRANSFER_VARIANT_MISMATCH"
|
||||||
|
db.rollback()
|
||||||
|
db.expire_all()
|
||||||
|
assert doc.status == "draft" and allocations(db, doc.id) == before
|
||||||
|
|
||||||
|
|
||||||
|
def test_transfer_rollback_restores_balances_and_accounting(native_db):
|
||||||
|
db = native_db
|
||||||
|
doc = transfer(db, [line(1, 2), line(2, 3)])
|
||||||
|
post_warehouse_document(db, doc.id)
|
||||||
|
db.rollback()
|
||||||
|
db.expire_all()
|
||||||
|
assert doc.status == "draft"
|
||||||
|
assert db.query(models.Document).count() == db.query(models.DocumentLine).count() == 0
|
||||||
|
assert {r["variant_id"]: Decimal(r["quantity"]) for r in list_variant_balances(db, 1, 1, 11)} == {1: 10, 2: 12}
|
||||||
|
assert list_variant_balances(db, 1, 1, 12) == []
|
||||||
|
post_warehouse_document(db, doc.id)
|
||||||
|
db.commit()
|
||||||
|
assert doc.status == "posted"
|
||||||
|
|
||||||
|
|
||||||
|
def test_draft_line_edits_validate_allocations_before_transfer_post(native_db):
|
||||||
|
db = native_db
|
||||||
|
doc = transfer(db, [line(1, 2)])
|
||||||
|
rows = db.query(models.WarehouseDocumentLine).filter_by(warehouse_document_id=doc.id).all()
|
||||||
|
update_warehouse_document_line(db, 1, doc.id, rows[0].id, line(1, 40, "each"))
|
||||||
|
db.commit()
|
||||||
|
with pytest.raises(ApiError) as error:
|
||||||
|
post_warehouse_document(db, doc.id)
|
||||||
|
assert error.value.code == "TRANSFER_VARIANT_MISMATCH"
|
||||||
|
db.rollback()
|
||||||
|
update_warehouse_document_line(db, 1, doc.id, rows[1].id, line(1, 40, "each"))
|
||||||
|
db.commit()
|
||||||
|
assert allocations(db, doc.id) == [("in", 4, 1, 4), ("out", 4, 1, 4)]
|
||||||
|
post_warehouse_document(db, doc.id)
|
||||||
|
db.commit()
|
||||||
|
assert {r["variant_id"]: Decimal(r["quantity"]) for r in list_variant_balances(db, 1, 1, 11)} == {1: 6, 2: 12}
|
||||||
98
hesabixAPI/tests/test_warehouse_transfer_currency.py
Normal file
98
hesabixAPI/tests/test_warehouse_transfer_currency.py
Normal file
|
|
@ -0,0 +1,98 @@
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlalchemy import BigInteger, Integer, MetaData, create_engine, select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from sqlalchemy.schema import CreateTable
|
||||||
|
|
||||||
|
from adapters.db import models
|
||||||
|
from adapters.db.models.business import BusinessField, BusinessType
|
||||||
|
from adapters.db.models.document_monetization import DocumentUsagePolicy
|
||||||
|
from adapters.db.models.invoice_item_line import InvoiceItemLine
|
||||||
|
from app.core import business_calendar, cache
|
||||||
|
from app.core.responses import ApiError
|
||||||
|
from app.services import woocommerce_stock_push_hook
|
||||||
|
from app.services.warehouse_service import create_manual_warehouse_document, post_warehouse_document
|
||||||
|
|
||||||
|
DAY = date(2026, 11, 11)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def transfer_db(monkeypatch):
|
||||||
|
monkeypatch.setattr(cache, "get_redis_client", lambda *args, **kwargs: None)
|
||||||
|
monkeypatch.setattr(cache, "_cache_service", None)
|
||||||
|
monkeypatch.setattr(business_calendar, "business_today", lambda *args: DAY)
|
||||||
|
monkeypatch.setattr(woocommerce_stock_push_hook, "_execute_stock_push", lambda *args: None)
|
||||||
|
engine = create_engine("sqlite://")
|
||||||
|
names = [
|
||||||
|
"businesses", "currencies", "business_currencies", "fiscal_years", "products", "warehouses",
|
||||||
|
"documents", "document_lines", "warehouse_documents", "warehouse_document_lines",
|
||||||
|
"warehouse_line_variant_allocations", "warehouse_line_lot_allocations", "product_instances",
|
||||||
|
"product_variants", "inventory_variant_balances", InvoiceItemLine.__table__.name,
|
||||||
|
"invoice_item_line_variant_allocations", "document_usage_policies", "workflows",
|
||||||
|
"warehouse_product_placements", "warehouse_locations", "business_document_numbering_settings",
|
||||||
|
"document_code_reservations", "document_number_counters",
|
||||||
|
]
|
||||||
|
with engine.begin() as connection:
|
||||||
|
for name in names:
|
||||||
|
table = models.Base.metadata.tables[name].to_metadata(MetaData())
|
||||||
|
for column in table.primary_key:
|
||||||
|
if isinstance(column.type, BigInteger):
|
||||||
|
column.type = Integer() # SQLite autoincrement requires the literal INTEGER type.
|
||||||
|
connection.execute(CreateTable(table, include_foreign_key_constraints=[]))
|
||||||
|
with Session(engine, autoflush=False, expire_on_commit=False) as db:
|
||||||
|
db.add_all([models.Currency(id=idx, name=code, title=code, symbol=code, code=code)
|
||||||
|
for idx, code in ((1, "IRR"), (2, "USD"), (3, "EUR"))])
|
||||||
|
for bid, cid in ((1, 2), (2, 3), (3, None)):
|
||||||
|
db.add_all([
|
||||||
|
models.Business(id=bid, name=str(bid), owner_id=1, default_currency_id=cid,
|
||||||
|
business_type=BusinessType.SHOP, business_field=BusinessField.TRADING),
|
||||||
|
models.FiscalYear(id=bid, business_id=bid, title="FY", start_date=DAY, end_date=DAY, is_last=True),
|
||||||
|
models.Product(id=bid, business_id=bid, code="P", name="P", main_unit="each",
|
||||||
|
inventory_mode="bulk", variant_mode="none", track_inventory=False),
|
||||||
|
models.Warehouse(id=bid * 10 + 1, business_id=bid, name="From", code="FROM"),
|
||||||
|
models.Warehouse(id=bid * 10 + 2, business_id=bid, name="To", code="TO"),
|
||||||
|
DocumentUsagePolicy(business_id=bid, policy_type="free", title="Test", is_active=True),
|
||||||
|
])
|
||||||
|
db.commit()
|
||||||
|
yield db
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def draft_transfer(db, bid):
|
||||||
|
doc = create_manual_warehouse_document(db, bid, 1, {
|
||||||
|
"doc_type": "transfer", "document_date": DAY.isoformat(),
|
||||||
|
"warehouse_id_from": bid * 10 + 1, "warehouse_id_to": bid * 10 + 2,
|
||||||
|
"lines": [{"product_id": bid, "quantity": 2, "extra_info": {"unit": "main"}}],
|
||||||
|
})
|
||||||
|
db.commit()
|
||||||
|
return doc
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("bid,expected_currency", [(1, 2), (2, 3)])
|
||||||
|
def test_transfer_ledger_uses_business_base_currency(transfer_db, bid, expected_currency):
|
||||||
|
db = transfer_db
|
||||||
|
doc = draft_transfer(db, bid)
|
||||||
|
post_warehouse_document(db, doc.id)
|
||||||
|
db.commit()
|
||||||
|
db.expire_all()
|
||||||
|
ledger = db.scalars(select(models.Document).where(models.Document.business_id == bid)).one()
|
||||||
|
assert ledger.currency_id == expected_currency
|
||||||
|
assert ledger.document_type == "inventory_transfer" and doc.status == "posted"
|
||||||
|
assert [(r.quantity, r.debit, r.credit) for r in db.query(models.DocumentLine).all()] == [(2, 0, 0)] * 2
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("currency_id,code,status", [(None, "BUSINESS_CURRENCY", 400), (999, "CURRENCY_NOT_FOUND", 404)])
|
||||||
|
def test_transfer_without_valid_base_currency_has_no_posting_effects(transfer_db, currency_id, code, status):
|
||||||
|
db = transfer_db
|
||||||
|
db.get(models.Business, 3).default_currency_id = currency_id
|
||||||
|
db.commit()
|
||||||
|
doc = draft_transfer(db, 3)
|
||||||
|
with pytest.raises(ApiError) as error:
|
||||||
|
post_warehouse_document(db, doc.id)
|
||||||
|
assert (error.value.code, error.value.status_code) == (code, status)
|
||||||
|
db.rollback()
|
||||||
|
db.expire_all()
|
||||||
|
assert doc.status == "draft"
|
||||||
|
assert db.query(models.Document).count() == db.query(models.DocumentLine).count() == 0
|
||||||
|
assert db.query(models.Base.metadata.tables["inventory_variant_balances"]).count() == 0
|
||||||
Loading…
Reference in a new issue