fix(billing): complete billing module — fix tier change, platform support, merchant portal

- Fix admin tier change: resolve tier_code→tier_id in update_subscription(),
  delegate to billing_service.change_tier() for Stripe-connected subs
- Add platform support to admin tiers page: platform column, filter dropdown,
  platform selector in create/edit modal, platform_name in tier API response
- Filter used platforms in create subscription modal on merchant detail page
- Enrich merchant portal API responses with tier code, tier_name, platform_name
- Add eager-load of platform relationship in get_merchant_subscription()
- Remove stale store_name/store_code references from merchant templates
- Add merchant tier change endpoint (POST /change-tier) and tier selector UI
  replacing broken requestUpgrade() button
- Fix subscription detail link to use platform_id instead of sub.id

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-10 20:49:48 +01:00
parent 0b37274140
commit d1fe3584ff
54 changed files with 222 additions and 52 deletions

View File

@@ -0,0 +1,228 @@
# tests/unit/services/test_customer_order_service.py
"""
Unit tests for CustomerOrderService.
Tests the orders module's customer-order relationship operations.
This service owns the customer-order relationship (customers module is agnostic).
"""
from datetime import UTC, datetime
import pytest
from app.modules.orders.models import Order
from app.modules.orders.services.customer_order_service import CustomerOrderService
@pytest.fixture
def customer_order_service():
"""Create CustomerOrderService instance."""
return CustomerOrderService()
@pytest.fixture
def customer_with_orders(db, test_store, test_customer):
"""Create a customer with multiple orders."""
orders = []
first_name = test_customer.first_name or "Test"
last_name = test_customer.last_name or "Customer"
for i in range(5):
order = Order(
store_id=test_store.id,
customer_id=test_customer.id,
order_number=f"ORD-{i:04d}",
status="pending" if i < 2 else "completed",
channel="direct",
order_date=datetime.now(UTC),
subtotal_cents=1000 * (i + 1),
total_amount_cents=1000 * (i + 1),
currency="EUR",
# Customer info
customer_email=test_customer.email,
customer_first_name=first_name,
customer_last_name=last_name,
# Shipping address
ship_first_name=first_name,
ship_last_name=last_name,
ship_address_line_1="123 Test St",
ship_city="Luxembourg",
ship_postal_code="L-1234",
ship_country_iso="LU",
# Billing address
bill_first_name=first_name,
bill_last_name=last_name,
bill_address_line_1="123 Test St",
bill_city="Luxembourg",
bill_postal_code="L-1234",
bill_country_iso="LU",
)
db.add(order)
orders.append(order)
db.commit()
for order in orders:
db.refresh(order)
return test_customer, orders
@pytest.mark.unit
class TestCustomerOrderServiceGetOrders:
"""Tests for get_customer_orders method."""
def test_get_customer_orders_empty(
self, db, customer_order_service, test_store, test_customer
):
"""Test getting orders when customer has none."""
orders, total = customer_order_service.get_customer_orders(
db=db,
store_id=test_store.id,
customer_id=test_customer.id,
)
assert orders == []
assert total == 0
def test_get_customer_orders_with_data(
self, db, customer_order_service, test_store, customer_with_orders
):
"""Test getting orders when customer has orders."""
customer, _ = customer_with_orders
orders, total = customer_order_service.get_customer_orders(
db=db,
store_id=test_store.id,
customer_id=customer.id,
)
assert total == 5
assert len(orders) == 5
def test_get_customer_orders_pagination(
self, db, customer_order_service, test_store, customer_with_orders
):
"""Test pagination of customer orders."""
customer, _ = customer_with_orders
# Get first page
orders, total = customer_order_service.get_customer_orders(
db=db,
store_id=test_store.id,
customer_id=customer.id,
skip=0,
limit=2,
)
assert total == 5
assert len(orders) == 2
# Get second page
orders, total = customer_order_service.get_customer_orders(
db=db,
store_id=test_store.id,
customer_id=customer.id,
skip=2,
limit=2,
)
assert total == 5
assert len(orders) == 2
def test_get_customer_orders_ordered_by_date(
self, db, customer_order_service, test_store, customer_with_orders
):
"""Test that orders are returned in descending date order."""
customer, created_orders = customer_with_orders
orders, _ = customer_order_service.get_customer_orders(
db=db,
store_id=test_store.id,
customer_id=customer.id,
)
# Most recent should be first
for i in range(len(orders) - 1):
assert orders[i].created_at >= orders[i + 1].created_at
def test_get_customer_orders_wrong_store(
self, db, customer_order_service, test_store, customer_with_orders
):
"""Test that orders from wrong store are not returned."""
customer, _ = customer_with_orders
# Use non-existent store ID
orders, total = customer_order_service.get_customer_orders(
db=db,
store_id=99999,
customer_id=customer.id,
)
assert orders == []
assert total == 0
@pytest.mark.unit
class TestCustomerOrderServiceRecentOrders:
"""Tests for get_recent_orders method."""
def test_get_recent_orders(
self, db, customer_order_service, test_store, customer_with_orders
):
"""Test getting recent orders."""
customer, _ = customer_with_orders
orders = customer_order_service.get_recent_orders(
db=db,
store_id=test_store.id,
customer_id=customer.id,
limit=3,
)
assert len(orders) == 3
def test_get_recent_orders_respects_limit(
self, db, customer_order_service, test_store, customer_with_orders
):
"""Test that limit is respected."""
customer, _ = customer_with_orders
orders = customer_order_service.get_recent_orders(
db=db,
store_id=test_store.id,
customer_id=customer.id,
limit=2,
)
assert len(orders) == 2
@pytest.mark.unit
class TestCustomerOrderServiceOrderCount:
"""Tests for get_order_count method."""
def test_get_order_count_zero(
self, db, customer_order_service, test_store, test_customer
):
"""Test count when customer has no orders."""
count = customer_order_service.get_order_count(
db=db,
store_id=test_store.id,
customer_id=test_customer.id,
)
assert count == 0
def test_get_order_count_with_orders(
self, db, customer_order_service, test_store, customer_with_orders
):
"""Test count when customer has orders."""
customer, _ = customer_with_orders
count = customer_order_service.get_order_count(
db=db,
store_id=test_store.id,
customer_id=customer.id,
)
assert count == 5

View File

@@ -0,0 +1,622 @@
# tests/unit/services/test_invoice_service.py
"""Unit tests for InvoiceService."""
import uuid
from decimal import Decimal
import pytest
from app.exceptions import ValidationException
from app.modules.orders.exceptions import (
InvoiceNotFoundException,
InvoiceSettingsNotFoundException,
)
from app.modules.orders.services.invoice_service import (
EU_VAT_RATES,
InvoiceService,
LU_VAT_RATES,
)
from app.modules.orders.models import (
Invoice,
InvoiceStatus,
VATRegime,
StoreInvoiceSettings,
)
from app.modules.orders.schemas import (
StoreInvoiceSettingsCreate,
StoreInvoiceSettingsUpdate,
)
@pytest.mark.unit
@pytest.mark.invoice
class TestInvoiceServiceVATCalculation:
"""Test suite for InvoiceService VAT calculation methods."""
def setup_method(self):
"""Initialize service instance before each test."""
self.service = InvoiceService()
# ==================== VAT Rate Lookup Tests ====================
def test_get_vat_rate_for_luxembourg(self):
"""Test Luxembourg VAT rate is 17%."""
rate = self.service.get_vat_rate_for_country("LU")
assert rate == Decimal("17.00")
def test_get_vat_rate_for_germany(self):
"""Test Germany VAT rate is 19%."""
rate = self.service.get_vat_rate_for_country("DE")
assert rate == Decimal("19.00")
def test_get_vat_rate_for_france(self):
"""Test France VAT rate is 20%."""
rate = self.service.get_vat_rate_for_country("FR")
assert rate == Decimal("20.00")
def test_get_vat_rate_for_non_eu_country(self):
"""Test non-EU country returns 0% VAT."""
rate = self.service.get_vat_rate_for_country("US")
assert rate == Decimal("0.00")
def test_get_vat_rate_lowercase_country(self):
"""Test VAT rate lookup works with lowercase country codes."""
rate = self.service.get_vat_rate_for_country("de")
assert rate == Decimal("19.00")
# ==================== VAT Rate Label Tests ====================
def test_get_vat_rate_label_luxembourg(self):
"""Test VAT rate label for Luxembourg."""
label = self.service.get_vat_rate_label("LU", Decimal("17.00"))
assert "Luxembourg" in label
assert "17" in label
def test_get_vat_rate_label_germany(self):
"""Test VAT rate label for Germany."""
label = self.service.get_vat_rate_label("DE", Decimal("19.00"))
assert "Germany" in label
assert "19" in label
# ==================== VAT Regime Determination Tests ====================
def test_determine_vat_regime_domestic(self):
"""Test domestic sales (same country) use domestic VAT."""
regime, rate, dest = self.service.determine_vat_regime(
seller_country="LU",
buyer_country="LU",
buyer_vat_number=None,
seller_oss_registered=False,
)
assert regime == VATRegime.DOMESTIC
assert rate == Decimal("17.00")
assert dest is None
def test_determine_vat_regime_reverse_charge(self):
"""Test B2B with valid VAT number uses reverse charge."""
regime, rate, dest = self.service.determine_vat_regime(
seller_country="LU",
buyer_country="DE",
buyer_vat_number="DE123456789",
seller_oss_registered=False,
)
assert regime == VATRegime.REVERSE_CHARGE
assert rate == Decimal("0.00")
assert dest == "DE"
def test_determine_vat_regime_oss_registered(self):
"""Test B2C cross-border with OSS uses destination VAT."""
regime, rate, dest = self.service.determine_vat_regime(
seller_country="LU",
buyer_country="DE",
buyer_vat_number=None,
seller_oss_registered=True,
)
assert regime == VATRegime.OSS
assert rate == Decimal("19.00") # German VAT
assert dest == "DE"
def test_determine_vat_regime_no_oss(self):
"""Test B2C cross-border without OSS uses origin VAT."""
regime, rate, dest = self.service.determine_vat_regime(
seller_country="LU",
buyer_country="DE",
buyer_vat_number=None,
seller_oss_registered=False,
)
assert regime == VATRegime.ORIGIN
assert rate == Decimal("17.00") # Luxembourg VAT
assert dest == "DE"
def test_determine_vat_regime_non_eu_exempt(self):
"""Test non-EU sales are VAT exempt."""
regime, rate, dest = self.service.determine_vat_regime(
seller_country="LU",
buyer_country="US",
buyer_vat_number=None,
seller_oss_registered=True,
)
assert regime == VATRegime.EXEMPT
assert rate == Decimal("0.00")
assert dest == "US"
@pytest.mark.unit
@pytest.mark.invoice
class TestInvoiceServiceSettings:
"""Test suite for InvoiceService settings management."""
def setup_method(self):
"""Initialize service instance before each test."""
self.service = InvoiceService()
# ==================== Get Settings Tests ====================
def test_get_settings_not_found(self, db, test_store):
"""Test getting settings for store without settings returns None."""
settings = self.service.get_settings(db, test_store.id)
assert settings is None
def test_get_settings_or_raise_not_found(self, db, test_store):
"""Test get_settings_or_raise raises when settings don't exist."""
with pytest.raises(InvoiceSettingsNotFoundException):
self.service.get_settings_or_raise(db, test_store.id)
# ==================== Create Settings Tests ====================
def test_create_settings_success(self, db, test_store):
"""Test creating invoice settings successfully."""
data = StoreInvoiceSettingsCreate(
merchant_name="Test Merchant S.A.",
merchant_address="123 Test Street",
merchant_city="Luxembourg",
merchant_postal_code="L-1234",
merchant_country="LU",
vat_number="LU12345678",
)
settings = self.service.create_settings(db, test_store.id, data)
assert settings.store_id == test_store.id
assert settings.merchant_name == "Test Merchant S.A."
assert settings.merchant_country == "LU"
assert settings.vat_number == "LU12345678"
assert settings.invoice_prefix == "INV"
assert settings.invoice_next_number == 1
def test_create_settings_with_custom_prefix(self, db, test_store):
"""Test creating settings with custom invoice prefix."""
data = StoreInvoiceSettingsCreate(
merchant_name="Custom Prefix Merchant",
invoice_prefix="FAC",
invoice_number_padding=6,
)
settings = self.service.create_settings(db, test_store.id, data)
assert settings.invoice_prefix == "FAC"
assert settings.invoice_number_padding == 6
def test_create_settings_duplicate_raises(self, db, test_store):
"""Test creating duplicate settings raises ValidationException."""
data = StoreInvoiceSettingsCreate(merchant_name="First Settings")
self.service.create_settings(db, test_store.id, data)
with pytest.raises(ValidationException) as exc_info:
self.service.create_settings(db, test_store.id, data)
assert "already exist" in str(exc_info.value)
# ==================== Update Settings Tests ====================
def test_update_settings_success(self, db, test_store):
"""Test updating invoice settings."""
# Create initial settings
create_data = StoreInvoiceSettingsCreate(
merchant_name="Original Merchant"
)
self.service.create_settings(db, test_store.id, create_data)
# Update settings
update_data = StoreInvoiceSettingsUpdate(
merchant_name="Updated Merchant",
bank_iban="LU123456789012345678",
)
settings = self.service.update_settings(db, test_store.id, update_data)
assert settings.merchant_name == "Updated Merchant"
assert settings.bank_iban == "LU123456789012345678"
def test_update_settings_not_found(self, db, test_store):
"""Test updating non-existent settings raises exception."""
update_data = StoreInvoiceSettingsUpdate(merchant_name="Updated")
with pytest.raises(InvoiceSettingsNotFoundException):
self.service.update_settings(db, test_store.id, update_data)
# ==================== Invoice Number Generation Tests ====================
def test_get_next_invoice_number(self, db, test_store):
"""Test invoice number generation and increment."""
create_data = StoreInvoiceSettingsCreate(
merchant_name="Test Merchant",
invoice_prefix="INV",
invoice_number_padding=5,
)
settings = self.service.create_settings(db, test_store.id, create_data)
# Generate first invoice number
num1 = self.service._get_next_invoice_number(db, settings)
assert num1 == "INV00001"
assert settings.invoice_next_number == 2
# Generate second invoice number
num2 = self.service._get_next_invoice_number(db, settings)
assert num2 == "INV00002"
assert settings.invoice_next_number == 3
@pytest.mark.unit
@pytest.mark.invoice
class TestInvoiceServiceCRUD:
"""Test suite for InvoiceService CRUD operations."""
def setup_method(self):
"""Initialize service instance before each test."""
self.service = InvoiceService()
# ==================== Get Invoice Tests ====================
def test_get_invoice_not_found(self, db, test_store):
"""Test getting non-existent invoice returns None."""
invoice = self.service.get_invoice(db, test_store.id, 99999)
assert invoice is None
def test_get_invoice_or_raise_not_found(self, db, test_store):
"""Test get_invoice_or_raise raises for non-existent invoice."""
with pytest.raises(InvoiceNotFoundException):
self.service.get_invoice_or_raise(db, test_store.id, 99999)
def test_get_invoice_wrong_store(self, db, test_store, test_invoice_settings):
"""Test cannot get invoice from different store."""
# Create an invoice
invoice = Invoice(
store_id=test_store.id,
invoice_number="INV00001",
invoice_date=test_invoice_settings.created_at,
seller_details={"merchant_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
# Try to get with different store ID
result = self.service.get_invoice(db, 99999, invoice.id)
assert result is None
# ==================== List Invoices Tests ====================
def test_list_invoices_empty(self, db, test_store):
"""Test listing invoices when none exist."""
invoices, total = self.service.list_invoices(db, test_store.id)
assert invoices == []
assert total == 0
def test_list_invoices_with_status_filter(
self, db, test_store, test_invoice_settings
):
"""Test listing invoices filtered by status."""
# Create invoices with different statuses
for status in [InvoiceStatus.DRAFT, InvoiceStatus.ISSUED, InvoiceStatus.PAID]:
invoice = Invoice(
store_id=test_store.id,
invoice_number=f"INV-{status.value}",
invoice_date=test_invoice_settings.created_at,
status=status.value,
seller_details={"merchant_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
# Filter by draft
drafts, total = self.service.list_invoices(
db, test_store.id, status="draft"
)
assert total == 1
assert all(inv.status == "draft" for inv in drafts)
def test_list_invoices_pagination(self, db, test_store, test_invoice_settings):
"""Test invoice listing pagination."""
# Create 5 invoices
for i in range(5):
invoice = Invoice(
store_id=test_store.id,
invoice_number=f"INV0000{i+1}",
invoice_date=test_invoice_settings.created_at,
seller_details={"merchant_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
# Get first page
page1, total = self.service.list_invoices(
db, test_store.id, page=1, per_page=2
)
assert len(page1) == 2
assert total == 5
# Get second page
page2, _ = self.service.list_invoices(
db, test_store.id, page=2, per_page=2
)
assert len(page2) == 2
@pytest.mark.unit
@pytest.mark.invoice
class TestInvoiceServiceStatusManagement:
"""Test suite for InvoiceService status management."""
def setup_method(self):
"""Initialize service instance before each test."""
self.service = InvoiceService()
def test_update_status_draft_to_issued(
self, db, test_store, test_invoice_settings
):
"""Test updating invoice status from draft to issued."""
invoice = Invoice(
store_id=test_store.id,
invoice_number="INV00001",
invoice_date=test_invoice_settings.created_at,
status=InvoiceStatus.DRAFT.value,
seller_details={"merchant_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
updated = self.service.update_status(
db, test_store.id, invoice.id, "issued"
)
assert updated.status == "issued"
def test_update_status_issued_to_paid(
self, db, test_store, test_invoice_settings
):
"""Test updating invoice status from issued to paid."""
invoice = Invoice(
store_id=test_store.id,
invoice_number="INV00001",
invoice_date=test_invoice_settings.created_at,
status=InvoiceStatus.ISSUED.value,
seller_details={"merchant_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
updated = self.service.update_status(
db, test_store.id, invoice.id, "paid"
)
assert updated.status == "paid"
def test_update_status_cancelled_cannot_change(
self, db, test_store, test_invoice_settings
):
"""Test that cancelled invoices cannot have status changed."""
invoice = Invoice(
store_id=test_store.id,
invoice_number="INV00001",
invoice_date=test_invoice_settings.created_at,
status=InvoiceStatus.CANCELLED.value,
seller_details={"merchant_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
with pytest.raises(ValidationException) as exc_info:
self.service.update_status(db, test_store.id, invoice.id, "issued")
assert "cancelled" in str(exc_info.value).lower()
def test_update_status_invalid_status(
self, db, test_store, test_invoice_settings
):
"""Test updating with invalid status raises ValidationException."""
invoice = Invoice(
store_id=test_store.id,
invoice_number="INV00001",
invoice_date=test_invoice_settings.created_at,
status=InvoiceStatus.DRAFT.value,
seller_details={"merchant_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
with pytest.raises(ValidationException) as exc_info:
self.service.update_status(
db, test_store.id, invoice.id, "invalid_status"
)
assert "Invalid status" in str(exc_info.value)
def test_mark_as_issued(self, db, test_store, test_invoice_settings):
"""Test mark_as_issued helper method."""
invoice = Invoice(
store_id=test_store.id,
invoice_number="INV00001",
invoice_date=test_invoice_settings.created_at,
status=InvoiceStatus.DRAFT.value,
seller_details={"merchant_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
updated = self.service.mark_as_issued(db, test_store.id, invoice.id)
assert updated.status == InvoiceStatus.ISSUED.value
def test_mark_as_paid(self, db, test_store, test_invoice_settings):
"""Test mark_as_paid helper method."""
invoice = Invoice(
store_id=test_store.id,
invoice_number="INV00001",
invoice_date=test_invoice_settings.created_at,
status=InvoiceStatus.ISSUED.value,
seller_details={"merchant_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
updated = self.service.mark_as_paid(db, test_store.id, invoice.id)
assert updated.status == InvoiceStatus.PAID.value
def test_cancel_invoice(self, db, test_store, test_invoice_settings):
"""Test cancel_invoice helper method."""
invoice = Invoice(
store_id=test_store.id,
invoice_number="INV00001",
invoice_date=test_invoice_settings.created_at,
status=InvoiceStatus.DRAFT.value,
seller_details={"merchant_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=10000,
vat_amount_cents=1700,
total_cents=11700,
)
db.add(invoice)
db.commit()
updated = self.service.cancel_invoice(db, test_store.id, invoice.id)
assert updated.status == InvoiceStatus.CANCELLED.value
@pytest.mark.unit
@pytest.mark.invoice
class TestInvoiceServiceStatistics:
"""Test suite for InvoiceService statistics."""
def setup_method(self):
"""Initialize service instance before each test."""
self.service = InvoiceService()
def test_get_invoice_stats_empty(self, db, test_store):
"""Test stats when no invoices exist."""
stats = self.service.get_invoice_stats(db, test_store.id)
assert stats["total_invoices"] == 0
assert stats["total_revenue_cents"] == 0
assert stats["draft_count"] == 0
assert stats["paid_count"] == 0
def test_get_invoice_stats_with_invoices(
self, db, test_store, test_invoice_settings
):
"""Test stats calculation with multiple invoices."""
# Create invoices
statuses = [
(InvoiceStatus.DRAFT.value, 10000),
(InvoiceStatus.ISSUED.value, 20000),
(InvoiceStatus.PAID.value, 30000),
(InvoiceStatus.CANCELLED.value, 5000),
]
for i, (status, total) in enumerate(statuses):
invoice = Invoice(
store_id=test_store.id,
invoice_number=f"INV0000{i+1}",
invoice_date=test_invoice_settings.created_at,
status=status,
seller_details={"merchant_name": "Test"},
buyer_details={"name": "Buyer"},
line_items=[],
vat_rate=Decimal("17.00"),
subtotal_cents=total,
vat_amount_cents=int(total * 0.17),
total_cents=total + int(total * 0.17),
)
db.add(invoice)
db.commit()
stats = self.service.get_invoice_stats(db, test_store.id)
assert stats["total_invoices"] == 4
# Revenue only counts issued and paid
expected_revenue = 20000 + int(20000 * 0.17) + 30000 + int(30000 * 0.17)
assert stats["total_revenue_cents"] == expected_revenue
assert stats["draft_count"] == 1
assert stats["paid_count"] == 1
# ==================== Fixtures ====================
@pytest.fixture
def test_invoice_settings(db, test_store):
"""Create test invoice settings."""
settings = StoreInvoiceSettings(
store_id=test_store.id,
merchant_name="Test Invoice Merchant",
merchant_country="LU",
invoice_prefix="INV",
invoice_next_number=1,
invoice_number_padding=5,
)
db.add(settings)
db.commit()
db.refresh(settings)
return settings

View File

@@ -0,0 +1,242 @@
# tests/unit/models/database/test_order_item_exception.py
"""Unit tests for OrderItemException database model."""
import pytest
from sqlalchemy.exc import IntegrityError
from app.modules.orders.models import OrderItemException
@pytest.mark.unit
@pytest.mark.database
class TestOrderItemExceptionModel:
"""Test OrderItemException model."""
def test_exception_creation(self, db, test_order_item, test_store):
"""Test OrderItemException model creation."""
exception = OrderItemException(
order_item_id=test_order_item.id,
store_id=test_store.id,
original_gtin="4006381333931",
original_product_name="Test Missing Product",
original_sku="MISSING-SKU-001",
exception_type="product_not_found",
status="pending",
)
db.add(exception)
db.commit()
db.refresh(exception)
assert exception.id is not None
assert exception.order_item_id == test_order_item.id
assert exception.store_id == test_store.id
assert exception.original_gtin == "4006381333931"
assert exception.original_product_name == "Test Missing Product"
assert exception.original_sku == "MISSING-SKU-001"
assert exception.exception_type == "product_not_found"
assert exception.status == "pending"
assert exception.created_at is not None
def test_exception_unique_order_item(self, db, test_order_item, test_store):
"""Test that only one exception can exist per order item."""
exception1 = OrderItemException(
order_item_id=test_order_item.id,
store_id=test_store.id,
original_gtin="4006381333931",
exception_type="product_not_found",
)
db.add(exception1)
db.commit()
# Second exception for the same order item should fail
with pytest.raises(IntegrityError):
exception2 = OrderItemException(
order_item_id=test_order_item.id,
store_id=test_store.id,
original_gtin="4006381333932",
exception_type="product_not_found",
)
db.add(exception2)
db.commit()
def test_exception_types(self, db, test_order_item, test_store):
"""Test different exception types."""
exception_types = ["product_not_found", "gtin_mismatch", "duplicate_gtin"]
# Create new order items for each test to avoid unique constraint
from app.modules.orders.models import OrderItem
for i, exc_type in enumerate(exception_types):
order_item = OrderItem(
order_id=test_order_item.order_id,
product_id=test_order_item.product_id,
product_name=f"Product {i}",
product_sku=f"SKU-{i}",
quantity=1,
unit_price=10.00,
total_price=10.00,
)
db.add(order_item)
db.commit()
db.refresh(order_item)
exception = OrderItemException(
order_item_id=order_item.id,
store_id=test_store.id,
original_gtin=f"400638133393{i}",
exception_type=exc_type,
)
db.add(exception)
db.commit()
db.refresh(exception)
assert exception.exception_type == exc_type
def test_exception_status_values(self, db, test_order_item, test_store):
"""Test different status values."""
exception = OrderItemException(
order_item_id=test_order_item.id,
store_id=test_store.id,
original_gtin="4006381333931",
exception_type="product_not_found",
status="pending",
)
db.add(exception)
db.commit()
# Test pending status
assert exception.status == "pending"
assert exception.is_pending is True
assert exception.is_resolved is False
assert exception.is_ignored is False
assert exception.blocks_confirmation is True
# Test resolved status
exception.status = "resolved"
db.commit()
db.refresh(exception)
assert exception.is_pending is False
assert exception.is_resolved is True
assert exception.is_ignored is False
assert exception.blocks_confirmation is False
# Test ignored status
exception.status = "ignored"
db.commit()
db.refresh(exception)
assert exception.is_pending is False
assert exception.is_resolved is False
assert exception.is_ignored is True
assert exception.blocks_confirmation is True # Ignored still blocks
def test_exception_nullable_fields(self, db, test_order_item, test_store):
"""Test that GTIN and other fields can be null."""
exception = OrderItemException(
order_item_id=test_order_item.id,
store_id=test_store.id,
original_gtin=None, # Can be null for vouchers etc.
original_product_name="Gift Voucher",
original_sku=None,
exception_type="product_not_found",
)
db.add(exception)
db.commit()
db.refresh(exception)
assert exception.id is not None
assert exception.original_gtin is None
assert exception.original_sku is None
assert exception.original_product_name == "Gift Voucher"
def test_exception_resolution(self, db, test_order_item, test_store, test_product, test_user):
"""Test resolving an exception with a product."""
from datetime import datetime, timezone
exception = OrderItemException(
order_item_id=test_order_item.id,
store_id=test_store.id,
original_gtin="4006381333931",
exception_type="product_not_found",
status="pending",
)
db.add(exception)
db.commit()
# Resolve the exception
now = datetime.now(timezone.utc)
exception.status = "resolved"
exception.resolved_product_id = test_product.id
exception.resolved_at = now
exception.resolved_by = test_user.id
exception.resolution_notes = "Matched to existing product"
db.commit()
db.refresh(exception)
assert exception.status == "resolved"
assert exception.resolved_product_id == test_product.id
assert exception.resolved_at is not None
assert exception.resolved_by == test_user.id
assert exception.resolution_notes == "Matched to existing product"
def test_exception_relationships(self, db, test_order_item, test_store):
"""Test OrderItemException relationships."""
exception = OrderItemException(
order_item_id=test_order_item.id,
store_id=test_store.id,
original_gtin="4006381333931",
exception_type="product_not_found",
)
db.add(exception)
db.commit()
db.refresh(exception)
assert exception.order_item is not None
assert exception.order_item.id == test_order_item.id
assert exception.store is not None
assert exception.store.id == test_store.id
def test_exception_repr(self, db, test_order_item, test_store):
"""Test OrderItemException __repr__ method."""
exception = OrderItemException(
order_item_id=test_order_item.id,
store_id=test_store.id,
original_gtin="4006381333931",
exception_type="product_not_found",
status="pending",
)
db.add(exception)
db.commit()
db.refresh(exception)
repr_str = repr(exception)
assert "OrderItemException" in repr_str
assert str(exception.id) in repr_str
assert "4006381333931" in repr_str
assert "pending" in repr_str
def test_exception_cascade_delete(self, db, test_order_item, test_store):
"""Test that exception is deleted when order item is deleted."""
exception = OrderItemException(
order_item_id=test_order_item.id,
store_id=test_store.id,
original_gtin="4006381333931",
exception_type="product_not_found",
)
db.add(exception)
db.commit()
exception_id = exception.id
# Delete the order item
db.delete(test_order_item)
db.commit()
# Exception should be cascade deleted
deleted_exception = (
db.query(OrderItemException)
.filter(OrderItemException.id == exception_id)
.first()
)
assert deleted_exception is None

View File

@@ -0,0 +1,183 @@
# tests/unit/services/test_order_metrics_customer.py
"""
Unit tests for OrderMetricsProvider customer metrics.
Tests the get_customer_order_metrics method which provides
customer-level order statistics using the MetricsProvider pattern.
"""
from datetime import UTC, datetime
import pytest
from app.modules.orders.models import Order
from app.modules.orders.services.order_metrics import OrderMetricsProvider
@pytest.fixture
def order_metrics_provider():
"""Create OrderMetricsProvider instance."""
return OrderMetricsProvider()
@pytest.fixture
def customer_with_orders(db, test_store, test_customer):
"""Create a customer with multiple orders for metrics testing."""
orders = []
first_name = test_customer.first_name or "Test"
last_name = test_customer.last_name or "Customer"
for i in range(3):
order = Order(
store_id=test_store.id,
customer_id=test_customer.id,
order_number=f"METRICS-{i:04d}",
status="completed",
channel="direct",
order_date=datetime.now(UTC),
subtotal_cents=1000 * (i + 1), # 1000, 2000, 3000
total_amount_cents=1000 * (i + 1),
currency="EUR",
# Customer info
customer_email=test_customer.email,
customer_first_name=first_name,
customer_last_name=last_name,
# Shipping address
ship_first_name=first_name,
ship_last_name=last_name,
ship_address_line_1="123 Test St",
ship_city="Luxembourg",
ship_postal_code="L-1234",
ship_country_iso="LU",
# Billing address
bill_first_name=first_name,
bill_last_name=last_name,
bill_address_line_1="123 Test St",
bill_city="Luxembourg",
bill_postal_code="L-1234",
bill_country_iso="LU",
)
db.add(order)
orders.append(order)
db.commit()
for order in orders:
db.refresh(order)
return test_customer, orders
@pytest.mark.unit
class TestOrderMetricsProviderCustomerMetrics:
"""Tests for get_customer_order_metrics method."""
def test_get_customer_metrics_no_orders(
self, db, order_metrics_provider, test_store, test_customer
):
"""Test metrics when customer has no orders."""
metrics = order_metrics_provider.get_customer_order_metrics(
db=db,
store_id=test_store.id,
customer_id=test_customer.id,
)
# Should return metrics even with no orders
assert len(metrics) > 0
# Find total_orders metric
total_orders_metric = next(
(m for m in metrics if m.key == "customer.total_orders"), None
)
assert total_orders_metric is not None
assert total_orders_metric.value == 0
def test_get_customer_metrics_with_orders(
self, db, order_metrics_provider, test_store, customer_with_orders
):
"""Test metrics when customer has orders."""
customer, orders = customer_with_orders
metrics = order_metrics_provider.get_customer_order_metrics(
db=db,
store_id=test_store.id,
customer_id=customer.id,
)
# Check total orders
total_orders = next(
(m for m in metrics if m.key == "customer.total_orders"), None
)
assert total_orders is not None
assert total_orders.value == 3
# Check total spent (1000 + 2000 + 3000 = 6000 cents = 60.00)
total_spent = next(
(m for m in metrics if m.key == "customer.total_spent"), None
)
assert total_spent is not None
assert total_spent.value == 60.0
# Check average order value (6000 / 3 = 2000 cents = 20.00)
avg_value = next(
(m for m in metrics if m.key == "customer.avg_order_value"), None
)
assert avg_value is not None
assert avg_value.value == 20.0
def test_get_customer_metrics_has_required_fields(
self, db, order_metrics_provider, test_store, customer_with_orders
):
"""Test that all required metric fields are present."""
customer, _ = customer_with_orders
metrics = order_metrics_provider.get_customer_order_metrics(
db=db,
store_id=test_store.id,
customer_id=customer.id,
)
expected_keys = [
"customer.total_orders",
"customer.total_spent",
"customer.avg_order_value",
"customer.last_order_date",
"customer.first_order_date",
]
metric_keys = [m.key for m in metrics]
for key in expected_keys:
assert key in metric_keys, f"Missing metric: {key}"
def test_get_customer_metrics_has_labels_and_icons(
self, db, order_metrics_provider, test_store, customer_with_orders
):
"""Test that metrics have display metadata."""
customer, _ = customer_with_orders
metrics = order_metrics_provider.get_customer_order_metrics(
db=db,
store_id=test_store.id,
customer_id=customer.id,
)
for metric in metrics:
assert metric.label, f"Metric {metric.key} missing label"
assert metric.category == "customer_orders"
def test_get_customer_metrics_wrong_store(
self, db, order_metrics_provider, customer_with_orders
):
"""Test metrics with wrong store returns zero values."""
customer, _ = customer_with_orders
metrics = order_metrics_provider.get_customer_order_metrics(
db=db,
store_id=99999, # Non-existent store
customer_id=customer.id,
)
total_orders = next(
(m for m in metrics if m.key == "customer.total_orders"), None
)
assert total_orders is not None
assert total_orders.value == 0

View File

@@ -0,0 +1,256 @@
# tests/unit/models/database/test_order.py
"""Unit tests for Order and OrderItem database models."""
from datetime import datetime, timezone
import pytest
from sqlalchemy.exc import IntegrityError
from app.modules.orders.models import Order, OrderItem
def create_order_with_snapshots(
db,
store,
customer,
customer_address,
order_number,
status="pending",
subtotal=99.99,
total_amount=99.99,
**kwargs
):
"""Helper to create Order with required address snapshots."""
# Remove channel from kwargs if present (we set it explicitly)
channel = kwargs.pop("channel", "direct")
order = Order(
store_id=store.id,
customer_id=customer.id,
order_number=order_number,
status=status,
channel=channel,
subtotal=subtotal,
total_amount=total_amount,
currency="EUR",
order_date=datetime.now(timezone.utc),
# Customer snapshot
customer_first_name=customer.first_name,
customer_last_name=customer.last_name,
customer_email=customer.email,
# Shipping address snapshot
ship_first_name=customer_address.first_name,
ship_last_name=customer_address.last_name,
ship_address_line_1=customer_address.address_line_1,
ship_city=customer_address.city,
ship_postal_code=customer_address.postal_code,
ship_country_iso="LU",
# Billing address snapshot
bill_first_name=customer_address.first_name,
bill_last_name=customer_address.last_name,
bill_address_line_1=customer_address.address_line_1,
bill_city=customer_address.city,
bill_postal_code=customer_address.postal_code,
bill_country_iso="LU",
**kwargs
)
db.add(order)
db.commit()
db.refresh(order)
return order
@pytest.mark.unit
@pytest.mark.database
class TestOrderModel:
"""Test Order model."""
def test_order_creation(
self, db, test_store, test_customer, test_customer_address
):
"""Test Order model with customer relationship."""
order = create_order_with_snapshots(
db, test_store, test_customer, test_customer_address,
order_number="ORD-001",
)
assert order.id is not None
assert order.store_id == test_store.id
assert order.customer_id == test_customer.id
assert order.order_number == "ORD-001"
assert order.status == "pending"
assert float(order.total_amount) == 99.99
# Verify snapshots
assert order.customer_first_name == test_customer.first_name
assert order.ship_city == test_customer_address.city
assert order.ship_country_iso == "LU"
def test_order_number_uniqueness(
self, db, test_store, test_customer, test_customer_address
):
"""Test order_number unique constraint."""
create_order_with_snapshots(
db, test_store, test_customer, test_customer_address,
order_number="UNIQUE-ORD-001",
)
# Duplicate order number should fail
with pytest.raises(IntegrityError):
create_order_with_snapshots(
db, test_store, test_customer, test_customer_address,
order_number="UNIQUE-ORD-001",
)
def test_order_status_values(
self, db, test_store, test_customer, test_customer_address
):
"""Test Order with different status values."""
statuses = [
"pending",
"processing",
"shipped",
"delivered",
"cancelled",
"refunded",
]
for i, status in enumerate(statuses):
order = create_order_with_snapshots(
db, test_store, test_customer, test_customer_address,
order_number=f"STATUS-ORD-{i:03d}",
status=status,
)
assert order.status == status
def test_order_amounts(self, db, test_store, test_customer, test_customer_address):
"""Test Order amount fields."""
order = create_order_with_snapshots(
db, test_store, test_customer, test_customer_address,
order_number="AMOUNTS-ORD-001",
subtotal=100.00,
tax_amount=20.00,
shipping_amount=10.00,
discount_amount=5.00,
total_amount=125.00,
)
assert float(order.subtotal) == 100.00
assert float(order.tax_amount) == 20.00
assert float(order.shipping_amount) == 10.00
assert float(order.discount_amount) == 5.00
assert float(order.total_amount) == 125.00
def test_order_relationships(
self, db, test_store, test_customer, test_customer_address
):
"""Test Order relationships."""
order = create_order_with_snapshots(
db, test_store, test_customer, test_customer_address,
order_number="REL-ORD-001",
)
assert order.store is not None
assert order.customer is not None
assert order.store.id == test_store.id
assert order.customer.id == test_customer.id
@pytest.mark.unit
@pytest.mark.database
class TestOrderItemModel:
"""Test OrderItem model."""
def test_order_item_creation(self, db, test_order, test_product):
"""Test OrderItem model."""
# Get title from translation
product_title = test_product.marketplace_product.get_title("en")
order_item = OrderItem(
order_id=test_order.id,
product_id=test_product.id,
product_name=product_title,
product_sku=test_product.store_sku or "SKU001",
quantity=2,
unit_price=49.99,
total_price=99.98,
)
db.add(order_item)
db.commit()
db.refresh(order_item)
assert order_item.id is not None
assert order_item.order_id == test_order.id
assert order_item.product_id == test_product.id
assert order_item.quantity == 2
assert float(order_item.unit_price) == 49.99
assert float(order_item.total_price) == 99.98
def test_order_item_stores_product_snapshot(self, db, test_order, test_product):
"""Test OrderItem stores product name and SKU as snapshot."""
order_item = OrderItem(
order_id=test_order.id,
product_id=test_product.id,
product_name="Snapshot Product Name",
product_sku="SNAPSHOT-SKU-001",
quantity=1,
unit_price=25.00,
total_price=25.00,
)
db.add(order_item)
db.commit()
db.refresh(order_item)
assert order_item.id is not None
assert order_item.product_name == "Snapshot Product Name"
assert order_item.product_sku == "SNAPSHOT-SKU-001"
def test_order_item_relationships(self, db, test_order, test_product):
"""Test OrderItem relationships."""
order_item = OrderItem(
order_id=test_order.id,
product_id=test_product.id,
product_name="Test Product",
product_sku="SKU001",
quantity=1,
unit_price=50.00,
total_price=50.00,
)
db.add(order_item)
db.commit()
db.refresh(order_item)
assert order_item.order is not None
assert order_item.order.id == test_order.id
def test_multiple_items_per_order(self, db, test_order, test_product):
"""Test multiple OrderItems can belong to same Order."""
# Create two order items for the same product (different quantities)
item1 = OrderItem(
order_id=test_order.id,
product_id=test_product.id,
product_name="Product - Size M",
product_sku="SKU001-M",
quantity=1,
unit_price=25.00,
total_price=25.00,
)
item2 = OrderItem(
order_id=test_order.id,
product_id=test_product.id,
product_name="Product - Size L",
product_sku="SKU001-L",
quantity=2,
unit_price=30.00,
total_price=60.00,
)
db.add_all([item1, item2])
db.commit()
assert item1.order_id == item2.order_id
assert item1.id != item2.id
assert item1.product_id == item2.product_id # Same product, different items

View File

@@ -0,0 +1,578 @@
# tests/unit/models/schema/test_order.py
"""Unit tests for order Pydantic schemas."""
from datetime import datetime, timezone
import pytest
from pydantic import ValidationError
from app.modules.orders.schemas import (
AddressSnapshot,
AddressSnapshotResponse,
CustomerSnapshot,
CustomerSnapshotResponse,
OrderCreate,
OrderItemCreate,
OrderItemResponse,
OrderListResponse,
OrderResponse,
OrderUpdate,
)
@pytest.mark.unit
@pytest.mark.schema
class TestOrderItemCreateSchema:
"""Test OrderItemCreate schema validation."""
def test_valid_order_item(self):
"""Test valid order item creation."""
item = OrderItemCreate(
product_id=1,
quantity=2,
)
assert item.product_id == 1
assert item.quantity == 2
def test_product_id_required(self):
"""Test product_id is required."""
with pytest.raises(ValidationError) as exc_info:
OrderItemCreate(quantity=2)
assert "product_id" in str(exc_info.value).lower()
def test_quantity_required(self):
"""Test quantity is required."""
with pytest.raises(ValidationError) as exc_info:
OrderItemCreate(product_id=1)
assert "quantity" in str(exc_info.value).lower()
def test_quantity_must_be_at_least_1(self):
"""Test quantity must be >= 1."""
with pytest.raises(ValidationError) as exc_info:
OrderItemCreate(
product_id=1,
quantity=0,
)
assert "quantity" in str(exc_info.value).lower()
def test_negative_quantity_invalid(self):
"""Test negative quantity is invalid."""
with pytest.raises(ValidationError):
OrderItemCreate(
product_id=1,
quantity=-1,
)
@pytest.mark.unit
@pytest.mark.schema
class TestAddressSnapshotSchema:
"""Test AddressSnapshot schema validation."""
def test_valid_address(self):
"""Test valid address creation."""
address = AddressSnapshot(
first_name="John",
last_name="Doe",
address_line_1="123 Main St",
city="Luxembourg",
postal_code="L-1234",
country_iso="LU",
)
assert address.first_name == "John"
assert address.city == "Luxembourg"
assert address.country_iso == "LU"
def test_required_fields(self):
"""Test required fields validation."""
with pytest.raises(ValidationError):
AddressSnapshot(
first_name="John",
# missing required fields
)
def test_optional_address_line_2(self):
"""Test optional address_line_2 field."""
address = AddressSnapshot(
first_name="John",
last_name="Doe",
address_line_1="123 Main St",
address_line_2="Suite 500",
city="Luxembourg",
postal_code="L-1234",
country_iso="LU",
)
assert address.address_line_2 == "Suite 500"
def test_first_name_min_length(self):
"""Test first_name minimum length."""
with pytest.raises(ValidationError):
AddressSnapshot(
first_name="",
last_name="Doe",
address_line_1="123 Main St",
city="Luxembourg",
postal_code="L-1234",
country_iso="LU",
)
def test_country_iso_min_length(self):
"""Test country_iso minimum length (2)."""
with pytest.raises(ValidationError):
AddressSnapshot(
first_name="John",
last_name="Doe",
address_line_1="123 Main St",
city="Luxembourg",
postal_code="L-1234",
country_iso="L", # Too short
)
@pytest.mark.unit
@pytest.mark.schema
class TestCustomerSnapshotSchema:
"""Test CustomerSnapshot schema validation."""
def test_valid_customer(self):
"""Test valid customer snapshot."""
customer = CustomerSnapshot(
first_name="John",
last_name="Doe",
email="john@example.com",
phone="+352123456",
locale="en",
)
assert customer.first_name == "John"
assert customer.email == "john@example.com"
def test_optional_phone(self):
"""Test phone is optional."""
customer = CustomerSnapshot(
first_name="John",
last_name="Doe",
email="john@example.com",
)
assert customer.phone is None
def test_optional_locale(self):
"""Test locale is optional."""
customer = CustomerSnapshot(
first_name="John",
last_name="Doe",
email="john@example.com",
)
assert customer.locale is None
@pytest.mark.unit
@pytest.mark.schema
class TestCustomerSnapshotResponseSchema:
"""Test CustomerSnapshotResponse schema."""
def test_full_name_property(self):
"""Test full_name property."""
response = CustomerSnapshotResponse(
first_name="John",
last_name="Doe",
email="john@example.com",
phone=None,
locale=None,
)
assert response.full_name == "John Doe"
@pytest.mark.unit
@pytest.mark.schema
class TestOrderCreateSchema:
"""Test OrderCreate schema validation."""
def test_valid_order(self):
"""Test valid order creation."""
order = OrderCreate(
items=[
OrderItemCreate(product_id=1, quantity=2),
OrderItemCreate(product_id=2, quantity=1),
],
customer=CustomerSnapshot(
first_name="John",
last_name="Doe",
email="john@example.com",
),
shipping_address=AddressSnapshot(
first_name="John",
last_name="Doe",
address_line_1="123 Main St",
city="Luxembourg",
postal_code="L-1234",
country_iso="LU",
),
)
assert len(order.items) == 2
assert order.customer_id is None # Optional for guest checkout
def test_items_required(self):
"""Test items are required."""
with pytest.raises(ValidationError) as exc_info:
OrderCreate(
customer=CustomerSnapshot(
first_name="John",
last_name="Doe",
email="john@example.com",
),
shipping_address=AddressSnapshot(
first_name="John",
last_name="Doe",
address_line_1="123 Main St",
city="Luxembourg",
postal_code="L-1234",
country_iso="LU",
),
)
assert "items" in str(exc_info.value).lower()
def test_items_must_not_be_empty(self):
"""Test items list must have at least 1 item."""
with pytest.raises(ValidationError) as exc_info:
OrderCreate(
items=[],
customer=CustomerSnapshot(
first_name="John",
last_name="Doe",
email="john@example.com",
),
shipping_address=AddressSnapshot(
first_name="John",
last_name="Doe",
address_line_1="123 Main St",
city="Luxembourg",
postal_code="L-1234",
country_iso="LU",
),
)
assert "items" in str(exc_info.value).lower()
def test_customer_required(self):
"""Test customer is required."""
with pytest.raises(ValidationError) as exc_info:
OrderCreate(
items=[OrderItemCreate(product_id=1, quantity=1)],
shipping_address=AddressSnapshot(
first_name="John",
last_name="Doe",
address_line_1="123 Main St",
city="Luxembourg",
postal_code="L-1234",
country_iso="LU",
),
)
assert "customer" in str(exc_info.value).lower()
def test_shipping_address_required(self):
"""Test shipping_address is required."""
with pytest.raises(ValidationError) as exc_info:
OrderCreate(
items=[OrderItemCreate(product_id=1, quantity=1)],
customer=CustomerSnapshot(
first_name="John",
last_name="Doe",
email="john@example.com",
),
)
assert "shipping_address" in str(exc_info.value).lower()
def test_optional_billing_address(self):
"""Test billing_address is optional."""
order = OrderCreate(
items=[OrderItemCreate(product_id=1, quantity=1)],
customer=CustomerSnapshot(
first_name="John",
last_name="Doe",
email="john@example.com",
),
shipping_address=AddressSnapshot(
first_name="John",
last_name="Doe",
address_line_1="123 Main St",
city="Luxembourg",
postal_code="L-1234",
country_iso="LU",
),
billing_address=AddressSnapshot(
first_name="Jane",
last_name="Doe",
address_line_1="456 Other St",
city="Esch",
postal_code="L-4321",
country_iso="LU",
),
)
assert order.billing_address is not None
assert order.billing_address.first_name == "Jane"
def test_optional_customer_notes(self):
"""Test optional customer_notes."""
order = OrderCreate(
items=[OrderItemCreate(product_id=1, quantity=1)],
customer=CustomerSnapshot(
first_name="John",
last_name="Doe",
email="john@example.com",
),
shipping_address=AddressSnapshot(
first_name="John",
last_name="Doe",
address_line_1="123 Main St",
city="Luxembourg",
postal_code="L-1234",
country_iso="LU",
),
customer_notes="Please leave at door",
)
assert order.customer_notes == "Please leave at door"
@pytest.mark.unit
@pytest.mark.schema
class TestOrderUpdateSchema:
"""Test OrderUpdate schema validation."""
def test_status_update(self):
"""Test valid status update."""
update = OrderUpdate(status="processing")
assert update.status == "processing"
def test_valid_status_values(self):
"""Test all valid status values."""
valid_statuses = [
"pending",
"processing",
"shipped",
"delivered",
"cancelled",
"refunded",
]
for status in valid_statuses:
update = OrderUpdate(status=status)
assert update.status == status
def test_invalid_status(self):
"""Test invalid status raises ValidationError."""
with pytest.raises(ValidationError) as exc_info:
OrderUpdate(status="invalid_status")
assert "status" in str(exc_info.value).lower()
def test_tracking_number_update(self):
"""Test tracking number update."""
update = OrderUpdate(tracking_number="TRACK123456")
assert update.tracking_number == "TRACK123456"
def test_internal_notes_update(self):
"""Test internal notes update."""
update = OrderUpdate(internal_notes="Customer requested expedited shipping")
assert update.internal_notes == "Customer requested expedited shipping"
def test_empty_update_is_valid(self):
"""Test empty update is valid."""
update = OrderUpdate()
assert update.model_dump(exclude_unset=True) == {}
@pytest.mark.unit
@pytest.mark.schema
class TestOrderResponseSchema:
"""Test OrderResponse schema."""
def test_from_dict(self):
"""Test creating response from dict."""
now = datetime.now(timezone.utc)
data = {
"id": 1,
"store_id": 1,
"customer_id": 1,
"order_number": "ORD-001",
"channel": "direct",
"status": "pending",
"subtotal": 100.00,
"tax_amount": 20.00,
"shipping_amount": 10.00,
"discount_amount": 5.00,
"total_amount": 125.00,
"currency": "EUR",
# Customer snapshot
"customer_first_name": "John",
"customer_last_name": "Doe",
"customer_email": "john@example.com",
"customer_phone": None,
"customer_locale": "en",
# Ship address snapshot
"ship_first_name": "John",
"ship_last_name": "Doe",
"ship_company": None,
"ship_address_line_1": "123 Main St",
"ship_address_line_2": None,
"ship_city": "Luxembourg",
"ship_postal_code": "L-1234",
"ship_country_iso": "LU",
# Bill address snapshot
"bill_first_name": "John",
"bill_last_name": "Doe",
"bill_company": None,
"bill_address_line_1": "123 Main St",
"bill_address_line_2": None,
"bill_city": "Luxembourg",
"bill_postal_code": "L-1234",
"bill_country_iso": "LU",
# Tracking
"shipping_method": "standard",
"tracking_number": None,
"tracking_provider": None,
# Notes
"customer_notes": None,
"internal_notes": None,
# Timestamps
"order_date": now,
"confirmed_at": None,
"shipped_at": None,
"delivered_at": None,
"cancelled_at": None,
"created_at": now,
"updated_at": now,
}
response = OrderResponse(**data)
assert response.id == 1
assert response.order_number == "ORD-001"
assert response.total_amount == 125.00
assert response.channel == "direct"
assert response.customer_full_name == "John Doe"
def test_is_marketplace_order(self):
"""Test is_marketplace_order property."""
now = datetime.now(timezone.utc)
# Direct order
direct_order = OrderResponse(
id=1, store_id=1, customer_id=1, order_number="ORD-001",
channel="direct", status="pending",
subtotal=100.0, tax_amount=0.0, shipping_amount=0.0, discount_amount=0.0,
total_amount=100.0, currency="EUR",
customer_first_name="John", customer_last_name="Doe",
customer_email="john@example.com", customer_phone=None, customer_locale=None,
ship_first_name="John", ship_last_name="Doe", ship_company=None,
ship_address_line_1="123 Main", ship_address_line_2=None,
ship_city="Luxembourg", ship_postal_code="L-1234", ship_country_iso="LU",
bill_first_name="John", bill_last_name="Doe", bill_company=None,
bill_address_line_1="123 Main", bill_address_line_2=None,
bill_city="Luxembourg", bill_postal_code="L-1234", bill_country_iso="LU",
shipping_method=None, tracking_number=None, tracking_provider=None,
customer_notes=None, internal_notes=None,
order_date=now, confirmed_at=None, shipped_at=None,
delivered_at=None, cancelled_at=None, created_at=now, updated_at=now,
)
assert direct_order.is_marketplace_order is False
# Marketplace order
marketplace_order = OrderResponse(
id=2, store_id=1, customer_id=1, order_number="LS-001",
channel="letzshop", status="pending",
subtotal=100.0, tax_amount=0.0, shipping_amount=0.0, discount_amount=0.0,
total_amount=100.0, currency="EUR",
customer_first_name="John", customer_last_name="Doe",
customer_email="john@example.com", customer_phone=None, customer_locale=None,
ship_first_name="John", ship_last_name="Doe", ship_company=None,
ship_address_line_1="123 Main", ship_address_line_2=None,
ship_city="Luxembourg", ship_postal_code="L-1234", ship_country_iso="LU",
bill_first_name="John", bill_last_name="Doe", bill_company=None,
bill_address_line_1="123 Main", bill_address_line_2=None,
bill_city="Luxembourg", bill_postal_code="L-1234", bill_country_iso="LU",
shipping_method=None, tracking_number=None, tracking_provider=None,
customer_notes=None, internal_notes=None,
order_date=now, confirmed_at=None, shipped_at=None,
delivered_at=None, cancelled_at=None, created_at=now, updated_at=now,
)
assert marketplace_order.is_marketplace_order is True
@pytest.mark.unit
@pytest.mark.schema
class TestOrderItemResponseSchema:
"""Test OrderItemResponse schema."""
def test_from_dict(self):
"""Test creating response from dict."""
now = datetime.now(timezone.utc)
data = {
"id": 1,
"order_id": 1,
"product_id": 1,
"product_name": "Test Product",
"product_sku": "SKU-001",
"gtin": "4006381333931",
"gtin_type": "EAN13",
"quantity": 2,
"unit_price": 50.00,
"total_price": 100.00,
"inventory_reserved": True,
"inventory_fulfilled": False,
"needs_product_match": False,
"created_at": now,
"updated_at": now,
}
response = OrderItemResponse(**data)
assert response.id == 1
assert response.quantity == 2
assert response.total_price == 100.00
assert response.gtin == "4006381333931"
def test_has_unresolved_exception(self):
"""Test has_unresolved_exception property."""
now = datetime.now(timezone.utc)
base_data = {
"id": 1, "order_id": 1, "product_id": 1,
"product_name": "Test", "product_sku": "SKU-001",
"gtin": None, "gtin_type": None,
"quantity": 1, "unit_price": 10.0, "total_price": 10.0,
"inventory_reserved": False, "inventory_fulfilled": False,
"created_at": now, "updated_at": now,
}
# No exception
response = OrderItemResponse(**base_data, needs_product_match=False, exception=None)
assert response.has_unresolved_exception is False
# Pending exception
from app.modules.orders.schemas import OrderItemExceptionBrief
pending_exc = OrderItemExceptionBrief(
id=1, original_gtin="123", original_product_name="Test",
exception_type="product_not_found", status="pending",
resolved_product_id=None,
)
response = OrderItemResponse(**base_data, needs_product_match=True, exception=pending_exc)
assert response.has_unresolved_exception is True
# Resolved exception
resolved_exc = OrderItemExceptionBrief(
id=1, original_gtin="123", original_product_name="Test",
exception_type="product_not_found", status="resolved",
resolved_product_id=5,
)
response = OrderItemResponse(**base_data, needs_product_match=False, exception=resolved_exc)
assert response.has_unresolved_exception is False
@pytest.mark.unit
@pytest.mark.schema
class TestOrderListResponseSchema:
"""Test OrderListResponse schema."""
def test_valid_list_response(self):
"""Test valid list response structure."""
response = OrderListResponse(
orders=[],
total=0,
skip=0,
limit=10,
)
assert response.orders == []
assert response.total == 0
assert response.skip == 0
assert response.limit == 10