C07 — ثبت اولین خروج پیشفاکتور ووکامرس در واحد اصلی #64
3 changed files with 217 additions and 0 deletions
|
|
@ -8957,6 +8957,9 @@ def update_invoice(
|
||||||
validate_invoice_type_change_for_tax(document, _old_document_type, inv_type)
|
validate_invoice_type_change_for_tax(document, _old_document_type, inv_type)
|
||||||
data["invoice_type"] = inv_type
|
data["invoice_type"] = inv_type
|
||||||
|
|
||||||
|
from app.services.woo_proforma_service import prepare_woo_proforma_finalization
|
||||||
|
|
||||||
|
data = prepare_woo_proforma_finalization(db, document, data, inv_type)
|
||||||
preserve_issue = _woo_posted_issue_update(db, document, data, inv_type)
|
preserve_issue = _woo_posted_issue_update(db, document, data, inv_type)
|
||||||
if preserve_issue and isinstance(data.get("description"), str):
|
if preserve_issue and isinstance(data.get("description"), str):
|
||||||
document.description = data["description"]
|
document.description = data["description"]
|
||||||
|
|
|
||||||
110
hesabixAPI/app/services/woo_proforma_service.py
Normal file
110
hesabixAPI/app/services/woo_proforma_service.py
Normal file
|
|
@ -0,0 +1,110 @@
|
||||||
|
"""Use published Woo stock units for the first posting of a proven variant proforma."""
|
||||||
|
|
||||||
|
from sqlalchemy import and_, or_
|
||||||
|
|
||||||
|
from adapters.db.models.invoice_item_line import InvoiceItemLine
|
||||||
|
from adapters.db.models.product import Product
|
||||||
|
from adapters.db.models.product_variant_allocation import (
|
||||||
|
InvoiceItemLineVariantAllocation,
|
||||||
|
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.invoice_unit_conversion_service import extra_info_dict
|
||||||
|
from app.services.variant_allocation_service import (
|
||||||
|
parse_payload_allocations,
|
||||||
|
validate_payload_for_product,
|
||||||
|
)
|
||||||
|
from app.services.woo_return_source_service import _identity
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_woo_proforma_finalization(db, document, data, invoice_type):
|
||||||
|
previous = extra_info_dict(document.extra_info)
|
||||||
|
if (
|
||||||
|
document.document_type != "invoice_sales"
|
||||||
|
or invoice_type != "invoice_sales"
|
||||||
|
or not document.is_proforma
|
||||||
|
or data.get("is_proforma") is not False
|
||||||
|
or previous.get("source") != "woocommerce"
|
||||||
|
):
|
||||||
|
return data
|
||||||
|
|
||||||
|
def ambiguous():
|
||||||
|
return ApiError(
|
||||||
|
"WOO_PROFORMA_SOURCE_AMBIGUOUS",
|
||||||
|
"اولین تبدیل پیشفاکتور ووکامرس یا انتساب ردیف Variant قابل تأیید نیست. سند و حواله را بررسی کنید.",
|
||||||
|
http_status=409,
|
||||||
|
)
|
||||||
|
|
||||||
|
original_lines = db.query(InvoiceItemLine).filter_by(document_id=document.id).populate_existing().all()
|
||||||
|
allocations = db.query(InvoiceItemLineVariantAllocation).filter(
|
||||||
|
InvoiceItemLineVariantAllocation.invoice_item_line_id.in_([line.id for line in original_lines]),
|
||||||
|
).populate_existing().all()
|
||||||
|
lines = list(data.get("lines") or [])
|
||||||
|
if not allocations and not any(parse_payload_allocations(line) for line in lines):
|
||||||
|
return data
|
||||||
|
if not lines:
|
||||||
|
raise ambiguous()
|
||||||
|
header = extra_info_dict(data.get("extra_info"))
|
||||||
|
if any(
|
||||||
|
not previous.get(key) or str(header.get(key)) != str(previous[key])
|
||||||
|
for key in ("source", "wc_order_id", "person_id")
|
||||||
|
):
|
||||||
|
raise ambiguous()
|
||||||
|
|
||||||
|
# Check actual warehouse rows as well as header links before changing any invoice state.
|
||||||
|
linked_ids = (previous.get("links") or {}).get("warehouse_document_ids") or []
|
||||||
|
issued = db.query(WarehouseDocument).outerjoin(
|
||||||
|
WarehouseDocumentLine, WarehouseDocumentLine.warehouse_document_id == WarehouseDocument.id,
|
||||||
|
).outerjoin(
|
||||||
|
WarehouseLineVariantAllocation,
|
||||||
|
WarehouseLineVariantAllocation.warehouse_document_line_id == WarehouseDocumentLine.id,
|
||||||
|
).filter(
|
||||||
|
WarehouseDocument.business_id == document.business_id,
|
||||||
|
WarehouseDocument.status != "draft",
|
||||||
|
or_(
|
||||||
|
and_(WarehouseDocument.source_type == "invoice", WarehouseDocument.source_document_id == document.id),
|
||||||
|
WarehouseDocument.id.in_(linked_ids),
|
||||||
|
WarehouseLineVariantAllocation.source_document_allocation_id.in_([row.id for row in allocations]),
|
||||||
|
),
|
||||||
|
).first()
|
||||||
|
if issued is not None:
|
||||||
|
raise ambiguous()
|
||||||
|
|
||||||
|
projected = []
|
||||||
|
used = set()
|
||||||
|
for line in lines:
|
||||||
|
items = parse_payload_allocations(line)
|
||||||
|
info = extra_info_dict(line.get("extra_info"))
|
||||||
|
identity = _identity(info, line.get("product_id"))
|
||||||
|
matches = [old for old in original_lines if _identity(extra_info_dict(old.extra_info), old.product_id) == identity]
|
||||||
|
if not items:
|
||||||
|
if any(row.invoice_item_line_id == old.id for old in matches for row in allocations):
|
||||||
|
raise ambiguous()
|
||||||
|
projected.append(line)
|
||||||
|
continue
|
||||||
|
if len(matches) != 1 or not all(identity) or "0" in identity or len(items) != 1:
|
||||||
|
raise ambiguous()
|
||||||
|
old = matches[0]
|
||||||
|
persisted = [row for row in allocations if row.invoice_item_line_id == old.id]
|
||||||
|
if (
|
||||||
|
old.id in used
|
||||||
|
or len(persisted) != 1
|
||||||
|
or persisted[0].business_id != document.business_id
|
||||||
|
or persisted[0].product_id != old.product_id
|
||||||
|
or str(persisted[0].variant_id) != str(items[0].get("variant_id"))
|
||||||
|
or persisted[0].quantity != old.quantity
|
||||||
|
or old.quantity <= 0
|
||||||
|
):
|
||||||
|
raise ambiguous()
|
||||||
|
product = db.get(Product, old.product_id)
|
||||||
|
if product is None or product.business_id != document.business_id:
|
||||||
|
raise ambiguous()
|
||||||
|
if not product.track_inventory:
|
||||||
|
projected.append(line)
|
||||||
|
continue
|
||||||
|
validate_payload_for_product(db, document.business_id, product, line, line.get("quantity"))
|
||||||
|
used.add(old.id)
|
||||||
|
projected.append({**line, "extra_info": {**info, "unit": "main"}})
|
||||||
|
return {**data, "lines": projected}
|
||||||
104
hesabixAPI/tests/test_woo_proforma_main_unit.py
Normal file
104
hesabixAPI/tests/test_woo_proforma_main_unit.py
Normal file
|
|
@ -0,0 +1,104 @@
|
||||||
|
from copy import deepcopy
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlalchemy.schema import CreateTable
|
||||||
|
|
||||||
|
from adapters.db.models.document import Document
|
||||||
|
from adapters.db.models.invoice_item_line import InvoiceItemLine
|
||||||
|
from adapters.db.models.product import Product
|
||||||
|
from adapters.db.models.product_variant import ProductVariant
|
||||||
|
from adapters.db.models.product_variant_allocation import InvoiceItemLineVariantAllocation
|
||||||
|
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.woo_proforma_service import prepare_woo_proforma_finalization
|
||||||
|
from tests.test_woo_return_source_service import HEADER, IDENTITY
|
||||||
|
from tests.test_woo_return_source_service import db as db
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def proforma(db):
|
||||||
|
for model in (Product, ProductVariant):
|
||||||
|
db.execute(CreateTable(model.__table__, include_foreign_key_constraints=[]))
|
||||||
|
db.add_all([
|
||||||
|
Product(id=1, business_id=1, name="Carton", code="P", variant_mode="inventory", inventory_mode="bulk",
|
||||||
|
track_inventory=True, main_unit="کارتن", secondary_unit="عدد", unit_conversion_factor=10),
|
||||||
|
ProductVariant(id=1, business_id=1, product_id=1, combination_key="red", is_active=True),
|
||||||
|
])
|
||||||
|
document = db.get(Document, 1)
|
||||||
|
document.is_proforma = True
|
||||||
|
line = db.get(InvoiceItemLine, 1)
|
||||||
|
line.extra_info = {**IDENTITY, "unit": "عدد", "unit_price": 250, "tax_amount": 75, "line_total": 825}
|
||||||
|
db.get(WarehouseDocument, 1).status = "draft"
|
||||||
|
db.commit()
|
||||||
|
return document, {
|
||||||
|
"invoice_type": "invoice_sales", "is_proforma": False, "extra_info": dict(HEADER),
|
||||||
|
"lines": [{"product_id": 1, "quantity": 3, "extra_info": dict(line.extra_info),
|
||||||
|
"allocations": [{"variant_id": 1, "quantity": 3}]}],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("unit", ["عدد", "main"])
|
||||||
|
def test_first_posting_projects_only_unit_without_changing_input_or_persisted_proforma(db, proforma, unit):
|
||||||
|
document, payload = proforma
|
||||||
|
db.get(InvoiceItemLine, 1).extra_info = {**payload["lines"][0]["extra_info"], "unit": unit}
|
||||||
|
db.commit()
|
||||||
|
original = deepcopy(payload)
|
||||||
|
result = prepare_woo_proforma_finalization(db, document, payload, "invoice_sales")
|
||||||
|
assert result["lines"][0]["extra_info"]["unit"] == "main"
|
||||||
|
result["lines"][0]["extra_info"]["unit"] = "عدد"
|
||||||
|
assert result == original == payload
|
||||||
|
assert document.is_proforma and db.get(InvoiceItemLine, 1).extra_info["unit"] == unit
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("fault", ["order", "person", "item", "product", "variant", "duplicate", "unallocated", "missing",
|
||||||
|
"missing_lines",
|
||||||
|
"allocation_tenant", "posted", "partial", "cancelled"])
|
||||||
|
def test_unproven_conversion_is_rejected_before_any_change(db, proforma, fault):
|
||||||
|
document, payload = proforma
|
||||||
|
if fault in {"order", "person"}:
|
||||||
|
payload["extra_info"]["wc_order_id" if fault == "order" else "person_id"] = 2
|
||||||
|
elif fault == "item":
|
||||||
|
payload["lines"][0]["extra_info"]["wc_item_id"] = 999
|
||||||
|
elif fault == "product":
|
||||||
|
payload["lines"][0]["product_id"] = 2
|
||||||
|
elif fault == "variant":
|
||||||
|
payload["lines"][0]["allocations"][0]["variant_id"] = 2
|
||||||
|
elif fault == "duplicate":
|
||||||
|
payload["lines"].append(deepcopy(payload["lines"][0]))
|
||||||
|
elif fault == "unallocated":
|
||||||
|
db.query(InvoiceItemLineVariantAllocation).delete()
|
||||||
|
elif fault == "missing":
|
||||||
|
payload["lines"][0].pop("allocations")
|
||||||
|
elif fault == "missing_lines":
|
||||||
|
payload.pop("lines")
|
||||||
|
elif fault == "allocation_tenant":
|
||||||
|
db.get(InvoiceItemLineVariantAllocation, 1).business_id = 2
|
||||||
|
else:
|
||||||
|
db.get(WarehouseDocument, 1).status = "cancelled" if fault == "cancelled" else "posted"
|
||||||
|
if fault == "posted":
|
||||||
|
db.get(WarehouseDocumentLine, 1).quantity = 3
|
||||||
|
db.commit()
|
||||||
|
with pytest.raises(ApiError) as error:
|
||||||
|
prepare_woo_proforma_finalization(db, document, payload, "invoice_sales")
|
||||||
|
assert (error.value.code, error.value.status_code) == ("WOO_PROFORMA_SOURCE_AMBIGUOUS", 409)
|
||||||
|
assert document.is_proforma and db.get(InvoiceItemLine, 1).quantity == Decimal(3)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("outside_scope", ["manual", "posted_sale", "payment_only", "ordinary", "not_tracked"])
|
||||||
|
def test_other_invoice_paths_keep_their_existing_units(db, proforma, outside_scope):
|
||||||
|
document, payload = proforma
|
||||||
|
if outside_scope == "manual":
|
||||||
|
document.extra_info = {**HEADER, "source": "manual"}
|
||||||
|
elif outside_scope == "posted_sale":
|
||||||
|
document.is_proforma = False
|
||||||
|
elif outside_scope == "payment_only":
|
||||||
|
payload = {"payments": []}
|
||||||
|
elif outside_scope == "ordinary":
|
||||||
|
db.query(InvoiceItemLineVariantAllocation).delete()
|
||||||
|
payload["lines"][0].pop("allocations")
|
||||||
|
else:
|
||||||
|
db.get(Product, 1).track_inventory = False
|
||||||
|
db.commit()
|
||||||
|
assert prepare_woo_proforma_finalization(db, document, payload, "invoice_sales") == payload
|
||||||
Loading…
Reference in a new issue