C07 — ثبت برگشت Variant ووکامرس بر اساس خروج قطعی فروش مبدأ #62
5 changed files with 439 additions and 17 deletions
|
|
@ -5186,6 +5186,8 @@ def _iter_profit_movements_from_invoice_lines(
|
|||
movement_product = db.get(Product, int(product_id))
|
||||
business = db.get(Business, int(business_id))
|
||||
rate_cache: Dict[int, Decimal] = {}
|
||||
from app.services.woo_return_source_service import return_quantity_main
|
||||
|
||||
for line, doc in rows:
|
||||
info = extra_info_dict(line.extra_info)
|
||||
if invoice_line_skips_inventory_kardex(info):
|
||||
|
|
@ -5197,7 +5199,7 @@ def _iter_profit_movements_from_invoice_lines(
|
|||
movement, _ = _movement_from_type(doc.document_type)
|
||||
if movement not in ("in", "out"):
|
||||
continue
|
||||
qty = inventory_quantity_to_main(
|
||||
qty = return_quantity_main(doc, line.id) or inventory_quantity_to_main(
|
||||
line.quantity, movement_product, info, strict=False
|
||||
)
|
||||
if qty <= 0:
|
||||
|
|
@ -6682,7 +6684,10 @@ def _calculate_invoice_profit(
|
|||
mvl = _mv_list_pid_wh(product.id, wh_iter)
|
||||
idx_ln = _find_profit_movement_index_for_line(mvl, int(item_line.id))
|
||||
if idx_ln is not None:
|
||||
restoration_qty_for_match = quantity_line_to_main(
|
||||
from app.services.woo_return_source_service import return_quantity_main
|
||||
|
||||
posted_return_qty = return_quantity_main(document, item_line.id)
|
||||
restoration_qty_for_match = posted_return_qty or quantity_line_to_main(
|
||||
qty,
|
||||
product,
|
||||
extra_info.get("unit"),
|
||||
|
|
@ -6703,12 +6708,12 @@ def _calculate_invoice_profit(
|
|||
fallback_line=item_line,
|
||||
missing_purchase_price_policy=missing_purchase_price_policy,
|
||||
)
|
||||
cost_per_unit = price_main_to_line(
|
||||
cost_per_unit,
|
||||
product,
|
||||
extra_info.get("unit"),
|
||||
strict=False,
|
||||
)
|
||||
if posted_return_qty is not None:
|
||||
cost_per_unit = cost_per_unit * posted_return_qty / qty
|
||||
else:
|
||||
cost_per_unit = price_main_to_line(
|
||||
cost_per_unit, product, extra_info.get("unit"), strict=False,
|
||||
)
|
||||
else:
|
||||
if normalized_basis == "purchase_price":
|
||||
from app.services.invoice_purchase_price_snapshot_service import (
|
||||
|
|
@ -6965,6 +6970,9 @@ def create_invoice(
|
|||
lines_input: List[Dict[str, Any]] = list(data.get("lines") or [])
|
||||
if not isinstance(lines_input, list) or len(lines_input) == 0:
|
||||
raise ApiError("LINES_REQUIRED", "At least one line is required", http_status=400)
|
||||
from app.services.woo_return_source_service import STOCK_KEY, prepare_woo_return_stock
|
||||
|
||||
woo_return_stock = prepare_woo_return_stock(db, business_id, data, lines_input, invoice_type)
|
||||
validate_invoice_line_totals(
|
||||
data, lines_input, currency, db=db, business_id=business_id, invoice_type=invoice_type,
|
||||
prepare_discount_lines=(
|
||||
|
|
@ -7443,6 +7451,11 @@ def create_invoice(
|
|||
created_invoice_lines.append((item_line, line))
|
||||
db.flush()
|
||||
_persist_invoice_variant_allocations(db, business_id, created_invoice_lines)
|
||||
if woo_return_stock:
|
||||
document.developer_settings = {
|
||||
**(document.developer_settings or {}),
|
||||
STOCK_KEY: {str(created_invoice_lines[index][0].id): stock for index, stock in woo_return_stock.items()},
|
||||
}
|
||||
|
||||
# Accounting lines for finalized invoices (COGS/Inventory در invoice_cogs_gl_service ثبت میشود)
|
||||
if not document.is_proforma:
|
||||
|
|
@ -8875,6 +8888,19 @@ def update_invoice(
|
|||
if document is None or document.document_type not in SUPPORTED_INVOICE_TYPES:
|
||||
raise ApiError("DOCUMENT_NOT_FOUND", "Invoice document not found", http_status=404)
|
||||
|
||||
from app.services.woo_return_source_service import STOCK_KEY
|
||||
|
||||
if (
|
||||
document.document_type == INVOICE_SALES_RETURN
|
||||
and (document.developer_settings or {}).get(STOCK_KEY)
|
||||
and any(key not in {"payments", "tag_ids"} for key in data)
|
||||
):
|
||||
raise ApiError(
|
||||
"WOO_RETURN_STOCK_REWRITE_REQUIRED",
|
||||
"بازنویسی برگشت ووکامرس با حوالهٔ مبدأ ثبتشده مجاز نیست.",
|
||||
http_status=409,
|
||||
)
|
||||
|
||||
_pre_links_wh = (document.extra_info or {}).get("links") or {}
|
||||
_old_warehouse_document_ids = list(_pre_links_wh.get("warehouse_document_ids") or [])
|
||||
_old_is_proforma = bool(document.is_proforma)
|
||||
|
|
|
|||
|
|
@ -252,6 +252,8 @@ def copy_invoice_allocations_to_warehouse_line(
|
|||
warehouse_line: WarehouseDocumentLine,
|
||||
product: Product,
|
||||
invoice_line: InvoiceItemLine,
|
||||
*,
|
||||
return_quantity_main: Decimal | None = None,
|
||||
) -> List[WarehouseLineVariantAllocation]:
|
||||
src_rows = (
|
||||
db.query(InvoiceItemLineVariantAllocation)
|
||||
|
|
@ -262,8 +264,10 @@ def copy_invoice_allocations_to_warehouse_line(
|
|||
unit = extra.get("unit")
|
||||
converted: List[Tuple[int, Decimal, Optional[Decimal]]] = []
|
||||
source_map: Dict[int, int] = {}
|
||||
if return_quantity_main is not None and len(src_rows) != 1:
|
||||
raise ApiError("WOO_RETURN_SOURCE_AMBIGUOUS", "تخصیص ردیف برگشت ووکامرس قابل تطبیق نیست.", http_status=409)
|
||||
for row in src_rows:
|
||||
qty_main = quantity_line_to_main(row.quantity, product, unit, strict=True)
|
||||
qty_main = return_quantity_main or quantity_line_to_main(row.quantity, product, unit, strict=True)
|
||||
converted.append((int(row.variant_id), qty_main, row.unit_price))
|
||||
source_map[int(row.variant_id)] = int(row.id)
|
||||
if is_variant_inventory_product(product) and not converted:
|
||||
|
|
|
|||
|
|
@ -47,6 +47,7 @@ def _attach_variant_allocations_for_warehouse_line(
|
|||
wline: WarehouseDocumentLine,
|
||||
product: Product,
|
||||
payload: Dict[str, Any],
|
||||
*, return_quantity_main: Decimal | None = None,
|
||||
) -> None:
|
||||
from adapters.db.models.invoice_item_line import InvoiceItemLine
|
||||
from app.services.variant_allocation_service import (
|
||||
|
|
@ -63,7 +64,7 @@ def _attach_variant_allocations_for_warehouse_line(
|
|||
invoice_line = None
|
||||
if invoice_line is not None:
|
||||
copy_invoice_allocations_to_warehouse_line(
|
||||
db, int(business_id), wline, product, invoice_line
|
||||
db, int(business_id), wline, product, invoice_line, return_quantity_main=return_quantity_main
|
||||
)
|
||||
from app.services.inventory_lot_allocation_service import copy_invoice_lot_allocations_to_warehouse_line
|
||||
|
||||
|
|
@ -1455,6 +1456,9 @@ def create_from_invoice(
|
|||
if wh is None:
|
||||
raise ApiError("WAREHOUSE_CODE_CONFLICT", "Failed to generate unique warehouse document code", http_status=500)
|
||||
|
||||
from app.services.woo_return_source_service import return_quantity_main
|
||||
from app.services.invoice_unit_conversion_service import stamp_inventory_quantity_as_main
|
||||
|
||||
validate_invoice_warehouse_lines_quantities(db, business_id, invoice, lines)
|
||||
|
||||
lines_added = 0
|
||||
|
|
@ -1663,12 +1667,25 @@ def create_from_invoice(
|
|||
if instance_count > int(qty):
|
||||
raise ApiError("INSTANCE_COUNT_EXCEEDS_QUANTITY", f"خط با product_id {pid}: تعداد کالاهای یونیک ({instance_count}) نمیتواند از تعداد وارد شده ({int(qty)}) بیشتر باشد", http_status=400)
|
||||
|
||||
qty, extra = _normalize_warehouse_line_quantity(
|
||||
product,
|
||||
qty,
|
||||
extra,
|
||||
payload_line_unit(ln, extra),
|
||||
)
|
||||
line_id = ln.get("invoice_item_line_id") or extra.get("invoice_item_line_id")
|
||||
frozen_return = return_quantity_main(invoice, line_id) if wh_doc_type == "receipt" else None
|
||||
if frozen_return is not None:
|
||||
from adapters.db.models.invoice_item_line import InvoiceItemLine
|
||||
|
||||
invoice_line = db.get(InvoiceItemLine, int(line_id))
|
||||
if invoice_line is None or invoice_line.document_id != invoice.id or qty != invoice_line.quantity:
|
||||
raise ApiError("WOO_RETURN_SOURCE_AMBIGUOUS", "مقدار ردیف برگشت باید با مقدار ثبتشده منطبق باشد.", http_status=409)
|
||||
extra = stamp_inventory_quantity_as_main(
|
||||
extra, product, source_line_unit=payload_line_unit(ln, extra), source_line_quantity=qty,
|
||||
)
|
||||
qty = frozen_return
|
||||
else:
|
||||
qty, extra = _normalize_warehouse_line_quantity(
|
||||
product,
|
||||
qty,
|
||||
extra,
|
||||
payload_line_unit(ln, extra),
|
||||
)
|
||||
|
||||
line_wh_loc = _warehouse_location_id_from_payload(
|
||||
{"warehouse_location_id": ln.get("warehouse_location_id"), "extra_info": extra}
|
||||
|
|
@ -1685,7 +1702,7 @@ def create_from_invoice(
|
|||
)
|
||||
db.add(wline)
|
||||
db.flush()
|
||||
_attach_variant_allocations_for_warehouse_line(db, business_id, wh, wline, product, ln)
|
||||
_attach_variant_allocations_for_warehouse_line(db, business_id, wh, wline, product, ln, return_quantity_main=frozen_return)
|
||||
lines_added += 1
|
||||
|
||||
if lines_added == 0:
|
||||
|
|
@ -3484,6 +3501,22 @@ def post_warehouse_document(
|
|||
lines = db.query(WarehouseDocumentLine).filter(WarehouseDocumentLine.warehouse_document_id == wh.id).all()
|
||||
if not lines:
|
||||
raise ApiError("NO_LINES", "حواله باید حداقل یک خط داشته باشد", http_status=400)
|
||||
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
|
||||
|
||||
invoice = db.get(Document, wh.source_document_id)
|
||||
if invoice and invoice.business_id == wh.business_id and (invoice.developer_settings or {}).get(STOCK_KEY):
|
||||
db.query(Document.id).filter_by(id=invoice.id).with_for_update().one()
|
||||
db.refresh(wh)
|
||||
if wh.status == "posted":
|
||||
return {"id": wh.id, "status": wh.status}
|
||||
if wh.status != "draft":
|
||||
raise ApiError("NOT_POSTABLE", "حوالهٔ برگشت در وضعیت قابل قطعیسازی نیست.", http_status=409)
|
||||
lines = db.query(WarehouseDocumentLine).filter_by(warehouse_document_id=wh.id).populate_existing().all()
|
||||
if not lines:
|
||||
raise ApiError("NO_LINES", "حواله باید حداقل یک خط داشته باشد", http_status=400)
|
||||
validate_woo_return_receipt(db, invoice, wh, lines)
|
||||
|
||||
production_order_ids: set[int] = set()
|
||||
for line in lines:
|
||||
try:
|
||||
|
|
|
|||
258
hesabixAPI/app/services/woo_return_source_service.py
Normal file
258
hesabixAPI/app/services/woo_return_source_service.py
Normal file
|
|
@ -0,0 +1,258 @@
|
|||
"""Resolve the physical quantity of a WooCommerce variant return before recording it."""
|
||||
|
||||
from decimal import ROUND_HALF_UP, Decimal, DecimalException
|
||||
|
||||
from sqlalchemy import String, cast, or_
|
||||
|
||||
from adapters.db.models.document import Document
|
||||
from adapters.db.models.invoice_item_line import InvoiceItemLine
|
||||
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
|
||||
|
||||
SOURCE_FIELDS = ("returned_from_invoice_id", "source_invoice_id", "copy_from_invoice_id")
|
||||
STOCK_KEY = "woo_return_stock"
|
||||
QUANT = Decimal("0.000001")
|
||||
|
||||
|
||||
def _ambiguous():
|
||||
return ApiError(
|
||||
"WOO_RETURN_SOURCE_AMBIGUOUS",
|
||||
"ردیف و تخصیص قطعی فروش مبدأ برگشت ووکامرس قابل تطبیق نیست.",
|
||||
http_status=409,
|
||||
)
|
||||
|
||||
|
||||
def _number(value):
|
||||
try:
|
||||
number = Decimal(str(value))
|
||||
if number.is_finite() and number > 0:
|
||||
return number
|
||||
except DecimalException:
|
||||
pass
|
||||
raise _ambiguous()
|
||||
|
||||
|
||||
def _identity(line, product_id):
|
||||
return (
|
||||
str(line.get("wc_item_id") or ""),
|
||||
str(line.get("wc_product_id") or ""),
|
||||
str(line.get("wc_variation_id") or ""),
|
||||
str(product_id or ""),
|
||||
)
|
||||
|
||||
|
||||
def _posted_rows(db, business_id, document_id, kind, movement):
|
||||
return (
|
||||
db.query(WarehouseDocumentLine, WarehouseLineVariantAllocation)
|
||||
.join(WarehouseDocument, WarehouseDocument.id == WarehouseDocumentLine.warehouse_document_id)
|
||||
.outerjoin(
|
||||
WarehouseLineVariantAllocation,
|
||||
WarehouseLineVariantAllocation.warehouse_document_line_id == WarehouseDocumentLine.id,
|
||||
)
|
||||
.filter(
|
||||
WarehouseDocument.business_id == business_id,
|
||||
WarehouseDocument.source_type == "invoice",
|
||||
WarehouseDocument.source_document_id == document_id,
|
||||
WarehouseDocument.status == "posted",
|
||||
WarehouseDocument.doc_type == kind,
|
||||
WarehouseDocumentLine.movement == movement,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
def prepare_woo_return_stock(db, business_id, data, lines, invoice_type):
|
||||
"""Return a server-generated projection aligned with the input invoice lines."""
|
||||
if invoice_type != "invoice_sales_return":
|
||||
return {}
|
||||
header = extra_info_dict(data.get("extra_info"))
|
||||
if header.get("source") != "woocommerce":
|
||||
return {}
|
||||
selected = [(i, row, parse_payload_allocations(row)) for i, row in enumerate(lines)]
|
||||
selected = [(i, row, allocs) for i, row, allocs in selected if allocs]
|
||||
if not selected:
|
||||
return {}
|
||||
if data.get("is_proforma") or not header.get("post_inventory", True):
|
||||
raise _ambiguous()
|
||||
|
||||
refs = {str(header[name]) for name in SOURCE_FIELDS if header.get(name) is not None}
|
||||
if len(refs) != 1 or not (source_ref := next(iter(refs))).isdigit() or not header.get("wc_order_id"):
|
||||
raise _ambiguous()
|
||||
origin = (
|
||||
db.query(Document)
|
||||
.filter_by(id=int(source_ref), business_id=business_id, document_type="invoice_sales", is_proforma=False)
|
||||
.with_for_update()
|
||||
.populate_existing()
|
||||
.first()
|
||||
)
|
||||
if origin is None:
|
||||
raise _ambiguous()
|
||||
origin_header = extra_info_dict(origin.extra_info)
|
||||
if (
|
||||
origin_header.get("source") != "woocommerce"
|
||||
or str(origin_header.get("wc_order_id")) != str(header["wc_order_id"])
|
||||
or not origin_header.get("person_id")
|
||||
or str(origin_header["person_id"]) != str(header.get("person_id"))
|
||||
):
|
||||
raise _ambiguous()
|
||||
|
||||
source_lines = db.query(InvoiceItemLine).filter_by(document_id=origin.id).all()
|
||||
issued = _posted_rows(db, business_id, origin.id, "issue", "out")
|
||||
prior = (
|
||||
db.query(InvoiceItemLine, Document)
|
||||
.join(Document, Document.id == InvoiceItemLine.document_id)
|
||||
.filter(
|
||||
Document.business_id == business_id,
|
||||
Document.document_type == "invoice_sales_return",
|
||||
or_(*(cast(Document.extra_info[field].as_string(), String) == source_ref for field in SOURCE_FIELDS)),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
projected = {}
|
||||
used_lines = set()
|
||||
for index, row, allocations in selected:
|
||||
info = extra_info_dict(row.get("extra_info"))
|
||||
identity = _identity(info, row.get("product_id"))
|
||||
matches = [ln for ln in source_lines if _identity(extra_info_dict(ln.extra_info), ln.product_id) == identity]
|
||||
if len(matches) != 1 or not all(identity) or "0" in identity or len(allocations) != 1:
|
||||
raise _ambiguous()
|
||||
source = matches[0]
|
||||
if source.id in used_lines:
|
||||
raise _ambiguous()
|
||||
used_lines.add(source.id)
|
||||
variant = str(allocations[0].get("variant_id"))
|
||||
ordered = _number(source.quantity)
|
||||
take = _number(row.get("quantity"))
|
||||
if take != take.quantize(QUANT) or _number(allocations[0].get("quantity")) != take:
|
||||
raise _ambiguous()
|
||||
source_allocs = db.query(InvoiceItemLineVariantAllocation).filter_by(
|
||||
invoice_item_line_id=source.id, business_id=business_id, product_id=source.product_id,
|
||||
).all()
|
||||
if len(source_allocs) != 1 or str(source_allocs[0].variant_id) != variant or source_allocs[0].quantity != ordered:
|
||||
raise _ambiguous()
|
||||
|
||||
posted = [
|
||||
(line, alloc) for line, alloc in issued
|
||||
if str(extra_info_dict(line.extra_info).get("invoice_item_line_id")) == str(source.id)
|
||||
]
|
||||
if len(posted) != 1:
|
||||
raise _ambiguous()
|
||||
issue, issued_alloc = posted[0]
|
||||
issue_info = extra_info_dict(issue.extra_info)
|
||||
if (
|
||||
issued_alloc is None
|
||||
or issued_alloc.source_document_allocation_id != source_allocs[0].id
|
||||
or issued_alloc.business_id != business_id
|
||||
or issue.product_id != source.product_id
|
||||
or issued_alloc.product_id != source.product_id
|
||||
or str(issued_alloc.variant_id) != variant
|
||||
or issue.quantity != issued_alloc.quantity
|
||||
or issue_info.get("inventory_quantity_unit") != "main"
|
||||
or _number(issue_info.get("source_line_quantity")) != ordered
|
||||
or not issue.warehouse_id
|
||||
or str(info.get("warehouse_id")) != str(issue.warehouse_id)
|
||||
):
|
||||
raise _ambiguous()
|
||||
|
||||
returned_lines = Decimal(0)
|
||||
returned_main = Decimal(0)
|
||||
for earlier, previous in prior:
|
||||
if earlier.product_id != source.product_id:
|
||||
continue
|
||||
earlier_info = extra_info_dict(earlier.extra_info)
|
||||
if _identity(earlier_info, earlier.product_id) != identity:
|
||||
# A different proven Woo item does not consume this source line.
|
||||
if earlier_info.get("wc_item_id") and earlier_info["wc_item_id"] != info["wc_item_id"]:
|
||||
continue
|
||||
raise _ambiguous()
|
||||
reserved = extra_info_dict(previous.developer_settings).get(STOCK_KEY, {}).get(str(earlier.id))
|
||||
if reserved is not None:
|
||||
if reserved["source_allocation_id"] != issued_alloc.id:
|
||||
raise _ambiguous()
|
||||
returned_main += _number(reserved["quantity_main"])
|
||||
else:
|
||||
receipts = [
|
||||
(line, alloc) for line, alloc in _posted_rows(db, business_id, previous.id, "receipt", "in")
|
||||
if str(extra_info_dict(line.extra_info).get("invoice_item_line_id")) == str(earlier.id)
|
||||
]
|
||||
if len(receipts) != 1:
|
||||
raise _ambiguous()
|
||||
receipt, alloc = receipts[0]
|
||||
if (
|
||||
alloc is None or str(alloc.variant_id) != variant or receipt.quantity != alloc.quantity
|
||||
or receipt.product_id != source.product_id or alloc.product_id != source.product_id
|
||||
or alloc.business_id != business_id or receipt.warehouse_id != issue.warehouse_id
|
||||
):
|
||||
raise _ambiguous()
|
||||
returned_main += _number(alloc.quantity)
|
||||
returned_lines += _number(earlier.quantity)
|
||||
|
||||
main = issued_alloc.quantity
|
||||
if returned_lines + take > ordered or returned_main >= main:
|
||||
raise ApiError("WOO_RETURN_EXCEEDS_ISSUE", "مقدار برگشت از ماندهٔ خروج قطعی فروش بیشتر است.", http_status=409)
|
||||
cumulative = (main * (returned_lines + take) / ordered).quantize(QUANT, rounding=ROUND_HALF_UP)
|
||||
expected_prior = (main * returned_lines / ordered).quantize(QUANT, rounding=ROUND_HALF_UP)
|
||||
if returned_main != expected_prior or cumulative <= returned_main:
|
||||
raise _ambiguous()
|
||||
projected[index] = {
|
||||
"quantity_main": str(cumulative - returned_main),
|
||||
"source_allocation_id": int(issued_alloc.id),
|
||||
"variant_id": int(issued_alloc.variant_id),
|
||||
"product_id": int(issue.product_id),
|
||||
"warehouse_id": int(issue.warehouse_id),
|
||||
}
|
||||
return projected
|
||||
|
||||
|
||||
def return_quantity_main(document, line_id):
|
||||
if document.document_type != "invoice_sales_return":
|
||||
return None
|
||||
row = extra_info_dict(getattr(document, "developer_settings", None)).get(STOCK_KEY, {}).get(str(line_id))
|
||||
return Decimal(row["quantity_main"]) if row is not None else None
|
||||
|
||||
|
||||
def validate_woo_return_receipt(db, document, warehouse_document, lines):
|
||||
"""A delayed or manually edited receipt may only post the reserved allocation."""
|
||||
reserved = extra_info_dict(document.developer_settings).get(STOCK_KEY, {})
|
||||
if not reserved:
|
||||
return
|
||||
previous = _posted_rows(db, document.business_id, document.id, "receipt", "in")
|
||||
already_posted = {str(extra_info_dict(line.extra_info).get("invoice_item_line_id")) for line, _ in previous}
|
||||
allocations = {
|
||||
line.id: []
|
||||
for line in lines
|
||||
}
|
||||
for row in db.query(WarehouseLineVariantAllocation).filter(
|
||||
WarehouseLineVariantAllocation.warehouse_document_line_id.in_(allocations)
|
||||
).all():
|
||||
allocations[row.warehouse_document_line_id].append(row)
|
||||
seen = set()
|
||||
for line in lines:
|
||||
invoice_line_id = str(extra_info_dict(line.extra_info).get("invoice_item_line_id"))
|
||||
expected = reserved.get(invoice_line_id)
|
||||
if not expected:
|
||||
if allocations[line.id]:
|
||||
raise _ambiguous()
|
||||
continue
|
||||
rows = allocations[line.id]
|
||||
if (
|
||||
invoice_line_id in seen
|
||||
or invoice_line_id in already_posted
|
||||
or warehouse_document.doc_type != "receipt"
|
||||
or line.movement != "in"
|
||||
or line.product_id != expected["product_id"]
|
||||
or line.warehouse_id != expected["warehouse_id"]
|
||||
or line.quantity != Decimal(expected["quantity_main"])
|
||||
or len(rows) != 1
|
||||
or rows[0].variant_id != expected["variant_id"]
|
||||
or rows[0].quantity != line.quantity
|
||||
):
|
||||
raise _ambiguous()
|
||||
seen.add(invoice_line_id)
|
||||
101
hesabixAPI/tests/test_woo_return_source_service.py
Normal file
101
hesabixAPI/tests/test_woo_return_source_service.py
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session
|
||||
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_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.woo_return_source_service import STOCK_KEY, prepare_woo_return_stock
|
||||
|
||||
DAY = date(2026, 11, 11)
|
||||
HEADER = {"source": "woocommerce", "wc_order_id": 100, "person_id": 1}
|
||||
IDENTITY = {"wc_item_id": 77, "wc_product_id": 1, "wc_variation_id": 22, "warehouse_id": 1}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db():
|
||||
engine = create_engine("sqlite://")
|
||||
with engine.begin() as connection:
|
||||
for model in (
|
||||
Document, InvoiceItemLine, InvoiceItemLineVariantAllocation, WarehouseDocument, WarehouseDocumentLine,
|
||||
WarehouseLineVariantAllocation,
|
||||
):
|
||||
connection.execute(CreateTable(model.__table__, include_foreign_key_constraints=[]))
|
||||
with Session(engine) as session:
|
||||
session.add_all([
|
||||
Document(
|
||||
id=1, business_id=1, fiscal_year_id=1, currency_id=1, created_by_user_id=1, code="SALE",
|
||||
document_type="invoice_sales", document_date=DAY, extra_info=HEADER,
|
||||
),
|
||||
InvoiceItemLine(id=1, document_id=1, product_id=1, quantity=3, extra_info=IDENTITY),
|
||||
InvoiceItemLineVariantAllocation(
|
||||
id=1, invoice_item_line_id=1, business_id=1, product_id=1, variant_id=1,
|
||||
quantity=3, attributes_snapshot={},
|
||||
),
|
||||
WarehouseDocument(
|
||||
id=1, business_id=1, document_date=DAY, code="ISSUE", status="posted",
|
||||
doc_type="issue", source_type="invoice", source_document_id=1,
|
||||
),
|
||||
WarehouseDocumentLine(
|
||||
id=1, warehouse_document_id=1, warehouse_id=1, product_id=1, movement="out", quantity=1,
|
||||
extra_info={"invoice_item_line_id": 1, "inventory_quantity_unit": "main", "source_line_quantity": 3},
|
||||
),
|
||||
WarehouseLineVariantAllocation(
|
||||
id=1, warehouse_document_line_id=1, source_document_allocation_id=1,
|
||||
business_id=1, product_id=1, variant_id=1, quantity=1,
|
||||
),
|
||||
])
|
||||
session.commit()
|
||||
yield session
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def _project(db, *, business_id=1, quantity=1, variant_id=1):
|
||||
return prepare_woo_return_stock(
|
||||
db, business_id, {"extra_info": {**HEADER, "returned_from_invoice_id": 1}},
|
||||
[{"product_id": 1, "quantity": quantity, "extra_info": IDENTITY,
|
||||
"allocations": [{"variant_id": variant_id, "quantity": quantity}]}],
|
||||
"invoice_sales_return",
|
||||
)[0]
|
||||
|
||||
|
||||
def test_partial_returns_use_posted_quantity_and_carry_rounding_remainder(db):
|
||||
pieces = []
|
||||
for return_id in (2, 3, 4):
|
||||
projection = _project(db)
|
||||
pieces.append(Decimal(projection["quantity_main"]))
|
||||
db.add_all([
|
||||
Document(
|
||||
id=return_id, business_id=1, fiscal_year_id=1, currency_id=1, created_by_user_id=1,
|
||||
code=f"RETURN-{return_id}", document_type="invoice_sales_return", document_date=DAY,
|
||||
extra_info={**HEADER, "returned_from_invoice_id": 1},
|
||||
developer_settings={STOCK_KEY: {str(return_id): projection}},
|
||||
),
|
||||
InvoiceItemLine(id=return_id, document_id=return_id, product_id=1, quantity=1, extra_info=IDENTITY),
|
||||
])
|
||||
db.commit()
|
||||
assert pieces == list(map(Decimal, ("0.333333", "0.333334", "0.333333")))
|
||||
with pytest.raises(ApiError) as error:
|
||||
_project(db)
|
||||
assert error.value.code == "WOO_RETURN_EXCEEDS_ISSUE"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["tenant", "variant", "unlinked"])
|
||||
def test_ambiguous_source_is_rejected_before_recording_return(db, mode):
|
||||
if mode == "unlinked":
|
||||
db.get(WarehouseLineVariantAllocation, 1).source_document_allocation_id = None
|
||||
db.commit()
|
||||
with pytest.raises(ApiError) as error:
|
||||
_project(db, business_id=2 if mode == "tenant" else 1, variant_id=2 if mode == "variant" else 1)
|
||||
assert error.value.code == "WOO_RETURN_SOURCE_AMBIGUOUS"
|
||||
assert db.query(Document).count() == 1
|
||||
Loading…
Reference in a new issue