Files
orion/models/schema/vendor.py
Samir Boulahtit b8a46e1746 fix: protect critical re-export imports from linter removal
Problem:
- Ruff removed 'from app.core.database import Base' from models/database/base.py
- Import appeared "unused" (F401) but was actually a critical re-export
- Caused ImportError: cannot import name 'Base' at runtime
- Re-export pattern: import in one file to export from package

Solution:
1. Added F401 ignore for models/database/base.py in pyproject.toml
2. Created scripts/verify_critical_imports.py verification script
3. Integrated verification into make check and CI pipeline
4. Updated documentation with explanation

New Verification Script:
- Checks all critical re-export imports exist
- Detects import variations (parentheses, 'as' clauses)
- Handles SQLAlchemy declarative_base alternatives
- Runs as part of make check automatically

Protected Files:
- models/database/base.py - Re-exports Base for all models
- models/__init__.py - Exports Base for Alembic
- models/database/__init__.py - Exports Base from package
- All __init__.py files (already protected)

Makefile Changes:
- make verify-imports - Run import verification
- make check - Now includes verify-imports
- make ci - Includes verify-imports in pipeline

Documentation Updated:
- Code quality guide explains re-export protection
- Pre-commit workflow includes verification
- Examples of why re-exports matter

This prevents future issues where linters remove seemingly
"unused" imports that are actually critical for application structure.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 20:10:22 +01:00

270 lines
7.8 KiB
Python

# models/schema/vendor.py
"""
Pydantic schemas for Vendor-related operations.
Schemas include:
- VendorCreate: For creating vendors with owner accounts
- VendorUpdate: For updating vendor information (Admin only)
- VendorResponse: Standard vendor response
- VendorDetailResponse: Vendor response with owner details
- VendorCreateResponse: Response after vendor creation (includes credentials)
- VendorListResponse: Paginated vendor list
- VendorSummary: Lightweight vendor info
- VendorTransferOwnership: For transferring vendor ownership
"""
import re
from datetime import datetime
from typing import Any
from pydantic import BaseModel, ConfigDict, Field, field_validator
class VendorCreate(BaseModel):
"""Schema for creating a new vendor with owner account."""
# Basic Information
vendor_code: str = Field(
...,
description="Unique vendor identifier (e.g., TECHSTORE)",
min_length=2,
max_length=50,
)
subdomain: str = Field(
..., description="Unique subdomain for the vendor", min_length=2, max_length=100
)
name: str = Field(
..., description="Display name of the vendor", min_length=2, max_length=255
)
description: str | None = Field(None, description="Vendor description")
# Owner Information (Creates User Account)
owner_email: str = Field(
...,
description="Email for the vendor owner (used for login and authentication)",
)
# Business Contact Information (Vendor Fields)
contact_email: str | None = Field(
None,
description="Public business contact email (defaults to owner_email if not provided)",
)
contact_phone: str | None = Field(None, description="Contact phone number")
website: str | None = Field(None, description="Website URL")
# Business Details
business_address: str | None = Field(None, description="Business address")
tax_number: str | None = Field(None, description="Tax/VAT number")
# Marketplace URLs (multi-language support)
letzshop_csv_url_fr: str | None = Field(None, description="French CSV URL")
letzshop_csv_url_en: str | None = Field(None, description="English CSV URL")
letzshop_csv_url_de: str | None = Field(None, description="German CSV URL")
@field_validator("owner_email", "contact_email")
@classmethod
def validate_emails(cls, v):
"""Validate email format and normalize to lowercase."""
if v and ("@" not in v or "." not in v):
raise ValueError("Invalid email format")
return v.lower() if v else v
@field_validator("subdomain")
@classmethod
def validate_subdomain(cls, v):
"""Validate subdomain format: lowercase alphanumeric with hyphens."""
if v and not re.match(r"^[a-z0-9][a-z0-9-]*[a-z0-9]$", v):
raise ValueError(
"Subdomain must contain only lowercase letters, numbers, and hyphens"
)
return v.lower() if v else v
@field_validator("vendor_code")
@classmethod
def validate_vendor_code(cls, v):
"""Ensure vendor code is uppercase for consistency."""
return v.upper() if v else v
class VendorUpdate(BaseModel):
"""
Schema for updating vendor information (Admin only).
Note: owner_email is NOT included here. To change the owner,
use the transfer-ownership endpoint instead.
"""
# Basic Information
name: str | None = Field(None, min_length=2, max_length=255)
description: str | None = None
subdomain: str | None = Field(None, min_length=2, max_length=100)
# Business Contact Information (Vendor Fields)
contact_email: str | None = Field(None, description="Public business contact email")
contact_phone: str | None = None
website: str | None = None
# Business Details
business_address: str | None = None
tax_number: str | None = None
# Marketplace URLs
letzshop_csv_url_fr: str | None = None
letzshop_csv_url_en: str | None = None
letzshop_csv_url_de: str | None = None
# Status (Admin only)
is_active: bool | None = None
is_verified: bool | None = None
@field_validator("subdomain")
@classmethod
def subdomain_lowercase(cls, v):
"""Normalize subdomain to lowercase."""
return v.lower().strip() if v else v
@field_validator("contact_email")
@classmethod
def validate_contact_email(cls, v):
"""Validate contact email format."""
if v and ("@" not in v or "." not in v):
raise ValueError("Invalid email format")
return v.lower() if v else v
model_config = ConfigDict(from_attributes=True)
class VendorResponse(BaseModel):
"""Standard schema for vendor response data."""
model_config = ConfigDict(from_attributes=True)
id: int
vendor_code: str
subdomain: str
name: str
description: str | None
owner_user_id: int
# Contact Information (Business)
contact_email: str | None
contact_phone: str | None
website: str | None
# Business Information
business_address: str | None
tax_number: str | None
# Marketplace URLs
letzshop_csv_url_fr: str | None
letzshop_csv_url_en: str | None
letzshop_csv_url_de: str | None
# Status Flags
is_active: bool
is_verified: bool
# Timestamps
created_at: datetime
updated_at: datetime
class VendorDetailResponse(VendorResponse):
"""
Extended vendor response including owner information.
Includes both:
- contact_email (business contact)
- owner_email (owner's authentication email)
"""
owner_email: str = Field(
..., description="Email of the vendor owner (for login/authentication)"
)
owner_username: str = Field(..., description="Username of the vendor owner")
class VendorCreateResponse(VendorDetailResponse):
"""
Response after creating vendor - includes generated credentials.
IMPORTANT: temporary_password is shown only once!
"""
temporary_password: str = Field(
..., description="Temporary password for owner (SHOWN ONLY ONCE)"
)
login_url: str | None = Field(None, description="URL for vendor owner to login")
class VendorListResponse(BaseModel):
"""Schema for paginated vendor list."""
vendors: list[VendorResponse]
total: int
skip: int
limit: int
class VendorSummary(BaseModel):
"""Lightweight vendor summary for dropdowns and quick references."""
model_config = ConfigDict(from_attributes=True)
id: int
vendor_code: str
subdomain: str
name: str
is_active: bool
class VendorTransferOwnership(BaseModel):
"""
Schema for transferring vendor ownership to another user.
This is a critical operation that requires:
- Confirmation flag
- Reason for audit trail (optional)
"""
new_owner_user_id: int = Field(
..., description="ID of the user who will become the new owner", gt=0
)
confirm_transfer: bool = Field(
..., description="Must be true to confirm ownership transfer"
)
transfer_reason: str | None = Field(
None,
max_length=500,
description="Reason for ownership transfer (for audit logs)",
)
@field_validator("confirm_transfer")
@classmethod
def validate_confirmation(cls, v):
"""Ensure confirmation is explicitly true."""
if not v:
raise ValueError("Ownership transfer requires explicit confirmation")
return v
class VendorTransferOwnershipResponse(BaseModel):
"""Response after successful ownership transfer."""
message: str
vendor_id: int
vendor_code: str
vendor_name: str
old_owner: dict[str, Any] = Field(
..., description="Information about the previous owner"
)
new_owner: dict[str, Any] = Field(
..., description="Information about the new owner"
)
transferred_at: datetime
transfer_reason: str | None