feat: implement company-based ownership architecture
- Add database migration to make vendor.owner_user_id nullable - Update Vendor model to support company-based ownership (DEPRECATED vendor.owner_user_id) - Implement company_service with singleton pattern (consistent with vendor_service) - Create Company model with proper relationships to vendors and users - Add company exception classes for proper error handling - Refactor companies API to use singleton service pattern Architecture Change: - OLD: Each vendor has its own owner (vendor.owner_user_id) - NEW: Vendors belong to a company, company has one owner (company.owner_user_id) - This allows one company owner to manage multiple vendor brands Technical Details: - Company service uses singleton pattern (not factory) - Company service accepts db: Session as parameter (follows SVC-003) - Uses AuthManager for password hashing (consistent with admin_service) - Added _generate_temp_password() helper method
This commit is contained in:
106
models/database/company.py
Normal file
106
models/database/company.py
Normal file
@@ -0,0 +1,106 @@
|
||||
# models/database/company.py
|
||||
"""
|
||||
Company model representing the business entity that owns one or more vendor brands.
|
||||
|
||||
A Company represents the legal/business entity with contact information,
|
||||
while Vendors represent the individual brands/storefronts operated by that company.
|
||||
"""
|
||||
|
||||
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, Text
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from app.core.database import Base
|
||||
from models.database.base import TimestampMixin
|
||||
|
||||
|
||||
class Company(Base, TimestampMixin):
|
||||
"""
|
||||
Represents a company (business entity) in the system.
|
||||
|
||||
A company owns one or more vendor brands. All business/contact information
|
||||
is stored at the company level to avoid duplication.
|
||||
"""
|
||||
|
||||
__tablename__ = "companies"
|
||||
|
||||
# ========================================================================
|
||||
# Basic Information
|
||||
# ========================================================================
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
"""Unique identifier for the company."""
|
||||
|
||||
name = Column(String, nullable=False, index=True)
|
||||
"""Company legal/business name."""
|
||||
|
||||
description = Column(Text)
|
||||
"""Optional description of the company."""
|
||||
|
||||
# ========================================================================
|
||||
# Ownership
|
||||
# ========================================================================
|
||||
owner_user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||
"""Foreign key to the user who owns this company."""
|
||||
|
||||
# ========================================================================
|
||||
# Contact Information
|
||||
# ========================================================================
|
||||
contact_email = Column(String, nullable=False)
|
||||
"""Primary business contact email."""
|
||||
|
||||
contact_phone = Column(String)
|
||||
"""Business phone number."""
|
||||
|
||||
website = Column(String)
|
||||
"""Company website URL."""
|
||||
|
||||
# ========================================================================
|
||||
# Business Details
|
||||
# ========================================================================
|
||||
business_address = Column(Text)
|
||||
"""Physical business address."""
|
||||
|
||||
tax_number = Column(String)
|
||||
"""Tax/VAT registration number."""
|
||||
|
||||
# ========================================================================
|
||||
# Status Flags
|
||||
# ========================================================================
|
||||
is_active = Column(Boolean, default=True, nullable=False)
|
||||
"""Whether the company is active. Affects all associated vendors."""
|
||||
|
||||
is_verified = Column(Boolean, default=False, nullable=False)
|
||||
"""Whether the company has been verified by platform admins."""
|
||||
|
||||
# ========================================================================
|
||||
# Relationships
|
||||
# ========================================================================
|
||||
owner = relationship("User", back_populates="owned_companies")
|
||||
"""The user who owns this company."""
|
||||
|
||||
vendors = relationship(
|
||||
"Vendor",
|
||||
back_populates="company",
|
||||
cascade="all, delete-orphan",
|
||||
order_by="Vendor.name",
|
||||
)
|
||||
"""All vendor brands operated by this company."""
|
||||
|
||||
def __repr__(self):
|
||||
"""String representation of the Company object."""
|
||||
return f"<Company(id={self.id}, name='{self.name}', vendors={len(self.vendors) if self.vendors else 0})>"
|
||||
|
||||
# ========================================================================
|
||||
# Helper Properties
|
||||
# ========================================================================
|
||||
|
||||
@property
|
||||
def vendor_count(self) -> int:
|
||||
"""Get the number of vendors belonging to this company."""
|
||||
return len(self.vendors) if self.vendors else 0
|
||||
|
||||
@property
|
||||
def active_vendor_count(self) -> int:
|
||||
"""Get the number of active vendors belonging to this company."""
|
||||
if not self.vendors:
|
||||
return 0
|
||||
return sum(1 for v in self.vendors if v.is_active)
|
||||
@@ -35,48 +35,47 @@ class Vendor(Base, TimestampMixin):
|
||||
id = Column(
|
||||
Integer, primary_key=True, index=True
|
||||
) # Primary key and indexed column for vendor ID
|
||||
|
||||
# Company relationship
|
||||
company_id = Column(
|
||||
Integer, ForeignKey("companies.id"), nullable=False, index=True
|
||||
) # Foreign key to the parent company
|
||||
|
||||
vendor_code = Column(
|
||||
String, unique=True, index=True, nullable=False
|
||||
) # Unique, indexed, non-nullable vendor code column
|
||||
subdomain = Column(
|
||||
String(100), unique=True, nullable=False, index=True
|
||||
) # Unique, non-nullable subdomain column with indexing
|
||||
name = Column(String, nullable=False) # Non-nullable name column for the vendor
|
||||
name = Column(String, nullable=False) # Non-nullable name column for the vendor (brand name)
|
||||
description = Column(Text) # Optional text description column for the vendor
|
||||
|
||||
owner_user_id = Column(
|
||||
Integer, ForeignKey("users.id"), nullable=False
|
||||
) # Foreign key to user ID of the vendor's owner
|
||||
Integer, ForeignKey("users.id"), nullable=True
|
||||
) # Foreign key to user ID of the vendor's owner (DEPRECATED - use company.owner_user_id instead)
|
||||
|
||||
# Contact information
|
||||
contact_email = Column(String) # Optional email column for contact information
|
||||
contact_phone = Column(String) # Optional phone column for contact information
|
||||
website = Column(String) # Optional website column for contact information
|
||||
|
||||
# Letzshop URLs - multi-language support
|
||||
# Letzshop URLs - multi-language support (brand-specific marketplace feeds)
|
||||
letzshop_csv_url_fr = Column(String) # URL for French CSV in Letzshop
|
||||
letzshop_csv_url_en = Column(String) # URL for English CSV in Letzshop
|
||||
letzshop_csv_url_de = Column(String) # URL for German CSV in Letzshop
|
||||
|
||||
# Business information
|
||||
business_address = Column(
|
||||
Text
|
||||
) # Optional text address column for business information
|
||||
tax_number = Column(String) # Optional tax number column for business information
|
||||
|
||||
# Status
|
||||
# Status (vendor-specific, can differ from company status)
|
||||
is_active = Column(
|
||||
Boolean, default=True
|
||||
) # Boolean to indicate if the vendor is active
|
||||
) # Boolean to indicate if the vendor brand is active
|
||||
is_verified = Column(
|
||||
Boolean, default=False
|
||||
) # Boolean to indicate if the vendor is verified
|
||||
) # Boolean to indicate if the vendor brand is verified
|
||||
|
||||
# ========================================================================
|
||||
# Relationships
|
||||
# ========================================================================
|
||||
company = relationship(
|
||||
"Company", back_populates="vendors"
|
||||
) # Relationship with Company model for the parent company
|
||||
owner = relationship(
|
||||
"User", back_populates="owned_vendors"
|
||||
) # Relationship with User model for the vendor's owner
|
||||
) # Relationship with User model for the vendor's owner (legacy)
|
||||
vendor_users = relationship(
|
||||
"VendorUser", back_populates="vendor"
|
||||
) # Relationship with VendorUser model for users in this vendor
|
||||
|
||||
155
models/schema/company.py
Normal file
155
models/schema/company.py
Normal file
@@ -0,0 +1,155 @@
|
||||
# models/schema/company.py
|
||||
"""
|
||||
Pydantic schemas for Company model.
|
||||
|
||||
These schemas are used for API request/response validation and serialization.
|
||||
"""
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, EmailStr, Field, field_validator
|
||||
|
||||
|
||||
class CompanyBase(BaseModel):
|
||||
"""Base schema for company with common fields."""
|
||||
|
||||
name: str = Field(..., min_length=2, max_length=200, description="Company name")
|
||||
description: str | None = Field(None, description="Company description")
|
||||
contact_email: EmailStr = Field(..., description="Business contact email")
|
||||
contact_phone: str | None = Field(None, description="Business phone number")
|
||||
website: str | None = Field(None, description="Company website URL")
|
||||
business_address: str | None = Field(None, description="Physical business address")
|
||||
tax_number: str | None = Field(None, description="Tax/VAT registration number")
|
||||
|
||||
@field_validator("contact_email")
|
||||
@classmethod
|
||||
def normalize_email(cls, v):
|
||||
"""Normalize email to lowercase."""
|
||||
return v.lower() if v else v
|
||||
|
||||
|
||||
class CompanyCreate(CompanyBase):
|
||||
"""
|
||||
Schema for creating a new company.
|
||||
|
||||
Requires owner_email to create the associated owner user account.
|
||||
"""
|
||||
|
||||
owner_email: EmailStr = Field(
|
||||
..., description="Email for the company owner account"
|
||||
)
|
||||
|
||||
@field_validator("owner_email")
|
||||
@classmethod
|
||||
def normalize_owner_email(cls, v):
|
||||
"""Normalize owner email to lowercase."""
|
||||
return v.lower() if v else v
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
class CompanyUpdate(BaseModel):
|
||||
"""
|
||||
Schema for updating company information.
|
||||
|
||||
All fields are optional to support partial updates.
|
||||
"""
|
||||
|
||||
name: str | None = Field(None, min_length=2, max_length=200)
|
||||
description: str | None = None
|
||||
contact_email: EmailStr | None = None
|
||||
contact_phone: str | None = None
|
||||
website: str | None = None
|
||||
business_address: str | None = None
|
||||
tax_number: str | None = None
|
||||
|
||||
# Status (Admin only)
|
||||
is_active: bool | None = None
|
||||
is_verified: bool | None = None
|
||||
|
||||
@field_validator("contact_email")
|
||||
@classmethod
|
||||
def normalize_email(cls, v):
|
||||
"""Normalize email to lowercase."""
|
||||
return v.lower() if v else v
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
class CompanyResponse(BaseModel):
|
||||
"""Standard schema for company response data."""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
name: str
|
||||
description: str | None
|
||||
|
||||
# Owner information
|
||||
owner_user_id: int
|
||||
|
||||
# Contact Information
|
||||
contact_email: str
|
||||
contact_phone: str | None
|
||||
website: str | None
|
||||
|
||||
# Business Information
|
||||
business_address: str | None
|
||||
tax_number: str | None
|
||||
|
||||
# Status Flags
|
||||
is_active: bool
|
||||
is_verified: bool
|
||||
|
||||
# Timestamps
|
||||
created_at: str
|
||||
updated_at: str
|
||||
|
||||
|
||||
class CompanyDetailResponse(CompanyResponse):
|
||||
"""
|
||||
Detailed company response including vendor count.
|
||||
|
||||
Used for company detail pages and admin views.
|
||||
"""
|
||||
|
||||
vendor_count: int = Field(0, description="Number of vendors under this company")
|
||||
active_vendor_count: int = Field(
|
||||
0, description="Number of active vendors under this company"
|
||||
)
|
||||
|
||||
|
||||
class CompanyListResponse(BaseModel):
|
||||
"""Schema for paginated company list."""
|
||||
|
||||
companies: list[CompanyResponse]
|
||||
total: int
|
||||
skip: int
|
||||
limit: int
|
||||
|
||||
|
||||
class CompanyCreateResponse(BaseModel):
|
||||
"""
|
||||
Response after creating a company with owner account.
|
||||
|
||||
Includes temporary password for the owner (shown only once).
|
||||
"""
|
||||
|
||||
company: CompanyResponse
|
||||
owner_user_id: int
|
||||
owner_username: str
|
||||
owner_email: str
|
||||
temporary_password: str = Field(
|
||||
..., description="Temporary password for owner (SHOWN ONLY ONCE)"
|
||||
)
|
||||
login_url: str | None = Field(None, description="URL for company owner to login")
|
||||
|
||||
|
||||
class CompanySummary(BaseModel):
|
||||
"""Lightweight company summary for dropdowns and quick references."""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
name: str
|
||||
is_active: bool
|
||||
is_verified: bool
|
||||
vendor_count: int = 0
|
||||
Reference in New Issue
Block a user