Files
bakery-ia/services/tenant/app/models/tenants.py

184 lines
8.0 KiB
Python
Raw Normal View History

2025-07-20 08:22:17 +02:00
# services/tenant/app/models/tenants.py - FIXED VERSION
2025-07-19 17:49:03 +02:00
"""
2025-07-20 08:22:17 +02:00
Tenant models for bakery management - FIXED
Removed cross-service User relationship to eliminate circular dependencies
2025-07-19 17:49:03 +02:00
"""
2025-09-01 19:21:12 +02:00
from sqlalchemy import Column, String, Boolean, DateTime, Float, ForeignKey, Text, Integer, JSON
2025-07-19 17:49:03 +02:00
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
2025-07-20 08:22:17 +02:00
from datetime import datetime, timezone
2025-07-19 17:49:03 +02:00
import uuid
from shared.database.base import Base
class Tenant(Base):
"""Tenant/Bakery model"""
__tablename__ = "tenants"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
name = Column(String(200), nullable=False)
subdomain = Column(String(100), unique=True)
business_type = Column(String(100), default="bakery")
2025-08-14 13:26:59 +02:00
business_model = Column(String(100), default="individual_bakery") # individual_bakery, central_baker_satellite, retail_bakery, hybrid_bakery
2025-07-19 17:49:03 +02:00
# Location info
address = Column(Text, nullable=False)
city = Column(String(100), default="Madrid")
postal_code = Column(String(10), nullable=False)
latitude = Column(Float)
longitude = Column(Float)
2025-10-09 18:01:24 +02:00
# Timezone configuration for accurate scheduling
timezone = Column(String(50), default="Europe/Madrid", nullable=False)
2025-07-19 17:49:03 +02:00
# Contact info
phone = Column(String(20))
email = Column(String(255))
# Status
is_active = Column(Boolean, default=True)
2025-10-03 14:09:34 +02:00
# Demo account flags
is_demo = Column(Boolean, default=False, index=True)
is_demo_template = Column(Boolean, default=False, index=True)
base_demo_tenant_id = Column(UUID(as_uuid=True), nullable=True, index=True)
demo_session_id = Column(String(100), nullable=True, index=True)
demo_expires_at = Column(DateTime(timezone=True), nullable=True)
2025-07-19 17:49:03 +02:00
# ML status
2025-09-30 21:58:10 +02:00
ml_model_trained = Column(Boolean, default=False)
2025-07-20 08:22:17 +02:00
last_training_date = Column(DateTime(timezone=True))
2025-10-03 14:09:34 +02:00
# Additional metadata (JSON field for flexible data storage)
metadata_ = Column(JSON, nullable=True)
2025-07-20 08:22:17 +02:00
# Ownership (user_id without FK - cross-service reference)
2025-07-19 17:49:03 +02:00
owner_id = Column(UUID(as_uuid=True), nullable=False, index=True)
2025-11-30 09:12:40 +01:00
# Enterprise tier hierarchy fields
parent_tenant_id = Column(UUID(as_uuid=True), ForeignKey("tenants.id", ondelete="RESTRICT"), nullable=True, index=True)
tenant_type = Column(String(50), default="standalone", nullable=False) # standalone, parent, child
hierarchy_path = Column(String(500), nullable=True) # Materialized path for queries
2025-07-19 17:49:03 +02:00
# Timestamps
2025-07-20 08:22:17 +02:00
created_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))
updated_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
2025-07-19 21:16:25 +02:00
2025-07-20 08:22:17 +02:00
# Relationships - only within tenant service
2025-07-19 21:16:25 +02:00
members = relationship("TenantMember", back_populates="tenant", cascade="all, delete-orphan")
2025-10-29 06:58:05 +01:00
subscriptions = relationship("Subscription", back_populates="tenant", cascade="all, delete-orphan")
2025-11-30 09:12:40 +01:00
locations = relationship("TenantLocation", back_populates="tenant", cascade="all, delete-orphan")
child_tenants = relationship("Tenant", back_populates="parent_tenant", remote_side=[id])
parent_tenant = relationship("Tenant", back_populates="child_tenants", remote_side=[parent_tenant_id])
2025-10-29 06:58:05 +01:00
2025-07-20 08:22:17 +02:00
# REMOVED: users relationship - no cross-service SQLAlchemy relationships
2025-10-29 06:58:05 +01:00
@property
def subscription_tier(self):
"""
Get current subscription tier from active subscription
Note: This is a computed property that requires subscription relationship to be loaded.
For performance-critical operations, use the subscription cache service directly.
"""
# Find active subscription
for subscription in self.subscriptions:
if subscription.status == 'active':
return subscription.plan
return "starter" # Default fallback
2025-07-19 17:49:03 +02:00
def __repr__(self):
return f"<Tenant(id={self.id}, name={self.name})>"
class TenantMember(Base):
2025-11-01 21:35:03 +01:00
"""
Tenant membership model for team access.
This model represents TENANT-SPECIFIC roles, which are distinct from global user roles.
TENANT ROLES (stored here):
- owner: Full control of the tenant, can transfer ownership, manage all aspects
- admin: Tenant administrator, can manage team members and most operations
- member: Standard team member, regular operational access
- viewer: Read-only observer, view-only access to tenant data
ROLE MAPPING TO GLOBAL ROLES:
When users are created through tenant management (pilot phase), their tenant role
is mapped to a global user role in the Auth service:
- tenant 'admin' global 'admin' (system-wide admin access)
- tenant 'member' global 'manager' (management-level access)
- tenant 'viewer' global 'user' (basic user access)
- tenant 'owner' No automatic global role (owner is tenant-specific)
This mapping is implemented in app/api/tenant_members.py lines 68-76.
Note: user_id is a cross-service reference (no FK) to avoid circular dependencies.
User enrichment is handled at the service layer via Auth service calls.
"""
2025-07-19 17:49:03 +02:00
__tablename__ = "tenant_members"
2025-11-01 21:35:03 +01:00
2025-07-19 17:49:03 +02:00
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
tenant_id = Column(UUID(as_uuid=True), ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
2025-07-20 08:22:17 +02:00
user_id = Column(UUID(as_uuid=True), nullable=False, index=True) # No FK - cross-service reference
2025-11-01 21:35:03 +01:00
2025-07-19 21:16:25 +02:00
# Role and permissions specific to this tenant
2025-11-30 09:12:40 +01:00
# Valid values: 'owner', 'admin', 'member', 'viewer', 'network_admin'
2025-11-01 21:35:03 +01:00
role = Column(String(50), default="member")
2025-07-19 17:49:03 +02:00
permissions = Column(Text) # JSON string of permissions
# Status
is_active = Column(Boolean, default=True)
2025-07-20 08:22:17 +02:00
invited_by = Column(UUID(as_uuid=True)) # No FK - cross-service reference
invited_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))
joined_at = Column(DateTime(timezone=True))
2025-07-19 17:49:03 +02:00
2025-07-20 08:22:17 +02:00
created_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))
2025-07-19 21:16:25 +02:00
2025-07-20 08:22:17 +02:00
# Relationships - only within tenant service
2025-07-19 21:16:25 +02:00
tenant = relationship("Tenant", back_populates="members")
2025-07-20 08:22:17 +02:00
# REMOVED: user relationship - no cross-service SQLAlchemy relationships
def __repr__(self):
return f"<TenantMember(tenant_id={self.tenant_id}, user_id={self.user_id}, role={self.role})>"
# Additional models for subscriptions, plans, etc.
class Subscription(Base):
"""Subscription model for tenant billing"""
__tablename__ = "subscriptions"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
tenant_id = Column(UUID(as_uuid=True), ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
2025-09-01 19:21:12 +02:00
plan = Column(String(50), default="starter") # starter, professional, enterprise
2025-10-16 07:28:04 +02:00
status = Column(String(50), default="active") # active, pending_cancellation, inactive, suspended
2025-07-20 08:22:17 +02:00
# Billing
monthly_price = Column(Float, default=0.0)
billing_cycle = Column(String(20), default="monthly") # monthly, yearly
next_billing_date = Column(DateTime(timezone=True))
trial_ends_at = Column(DateTime(timezone=True))
2025-10-16 07:28:04 +02:00
cancelled_at = Column(DateTime(timezone=True), nullable=True)
cancellation_effective_date = Column(DateTime(timezone=True), nullable=True)
stripe_subscription_id = Column(String(255), nullable=True)
stripe_customer_id = Column(String(255), nullable=True)
2025-07-20 08:22:17 +02:00
# Limits
2025-09-01 19:21:12 +02:00
max_users = Column(Integer, default=5)
2025-07-20 08:22:17 +02:00
max_locations = Column(Integer, default=1)
max_products = Column(Integer, default=50)
2025-09-01 19:21:12 +02:00
# Features - Store plan features as JSON
features = Column(JSON)
2025-07-20 08:22:17 +02:00
# Timestamps
created_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))
updated_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
# Relationships
tenant = relationship("Tenant")
2025-07-19 17:49:03 +02:00
def __repr__(self):
2025-09-30 21:58:10 +02:00
return f"<Subscription(tenant_id={self.tenant_id}, plan={self.plan}, status={self.status})>"