195 lines
7.9 KiB
Python
195 lines
7.9 KiB
Python
"""Tenant, Membership, and Transaction Audit Models.
|
|
|
|
Fulfills FR-TENANTLIFECYCLE-001 (UC-018), FR-TENANTMEMBERSHIPCONTEXT-001/002 (UC-019),
|
|
and FR-TENANTSECURITYAUDIT-001/003 (UC-017).
|
|
Adheres to LLD-002, Database Design, and UP-AI v1.5 standards.
|
|
"""
|
|
from datetime import datetime, timezone
|
|
import json
|
|
from typing import Any, Dict, List, Optional
|
|
import uuid
|
|
|
|
# Permitted PRD Business Roles per BRD-FR-040 & LLD-002
|
|
PRD_BUSINESS_ROLES: List[str] = [
|
|
"Tenant Administrator",
|
|
"Mandi Buyer",
|
|
"Purchase Manager",
|
|
"Yard Supervisor",
|
|
"Quality Officer",
|
|
"Sales Executive",
|
|
"Sales Manager",
|
|
"Logistics Coordinator",
|
|
"Accounts Executive",
|
|
"Partner / MD",
|
|
"System Administrator",
|
|
]
|
|
|
|
# Valid FSM Lifecycle States
|
|
LIFECYCLE_STATES = {"ACTIVE", "SUSPENDED", "CLOSED"}
|
|
|
|
# Valid FSM Lifecycle State Transitions (Terminal state: CLOSED)
|
|
VALID_LIFECYCLE_TRANSITIONS = {
|
|
"ACTIVE": {"SUSPENDED", "CLOSED"},
|
|
"SUSPENDED": {"ACTIVE", "CLOSED"},
|
|
"CLOSED": set(), # Terminal state: cannot transition out
|
|
}
|
|
|
|
|
|
def validate_lifecycle_transition(current_status: str, new_status: str) -> None:
|
|
"""Validates lifecycle transition invariant.
|
|
|
|
Raises ValueError on illegal state machine progression.
|
|
"""
|
|
if current_status not in LIFECYCLE_STATES:
|
|
raise ValueError(f"Invalid current tenant status: '{current_status}'")
|
|
if new_status not in LIFECYCLE_STATES:
|
|
raise ValueError(f"Invalid target tenant status: '{new_status}'")
|
|
if new_status == current_status:
|
|
return
|
|
allowed = VALID_LIFECYCLE_TRANSITIONS.get(current_status, set())
|
|
if new_status not in allowed:
|
|
raise ValueError(
|
|
f"Illegal tenant lifecycle transition from '{current_status}' to '{new_status}'. "
|
|
f"Allowed transitions: {list(allowed) if allowed else 'None (terminal state)'}."
|
|
)
|
|
|
|
|
|
try:
|
|
from sqlalchemy import Column, String, DateTime, Text
|
|
from backend.app.models.user import Base
|
|
except ImportError:
|
|
class Base:
|
|
pass
|
|
|
|
def Column(*args, **kwargs):
|
|
return None
|
|
|
|
def String(*args, **kwargs):
|
|
return None
|
|
|
|
def DateTime(*args, **kwargs):
|
|
return None
|
|
|
|
def Text(*args, **kwargs):
|
|
return None
|
|
|
|
class Tenant(Base):
|
|
__tablename__ = "tenants"
|
|
|
|
tenant_id = Column(String(64), primary_key=True)
|
|
business_name = Column(String(255), nullable=False)
|
|
legal_identifier = Column(String(32), nullable=False)
|
|
contact_email = Column(String(255), nullable=False)
|
|
primary_mandi = Column(String(64), nullable=False)
|
|
status = Column(String(32), default="ACTIVE", nullable=False)
|
|
created_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
|
|
updated_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc), nullable=False)
|
|
|
|
def __init__(self, tenant_id: str, business_name: str, legal_identifier: str,
|
|
contact_email: str, primary_mandi: str, status: str = "ACTIVE",
|
|
created_at: Optional[datetime] = None, updated_at: Optional[datetime] = None):
|
|
self.tenant_id = tenant_id
|
|
self.business_name = business_name
|
|
self.legal_identifier = legal_identifier
|
|
self.contact_email = contact_email
|
|
self.primary_mandi = primary_mandi
|
|
self.status = status
|
|
self.created_at = created_at or datetime.now(timezone.utc)
|
|
self.updated_at = updated_at or datetime.now(timezone.utc)
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
return {
|
|
"tenant_id": self.tenant_id,
|
|
"business_name": self.business_name,
|
|
"legal_identifier": self.legal_identifier,
|
|
"contact_email": self.contact_email,
|
|
"primary_mandi": self.primary_mandi,
|
|
"status": self.status,
|
|
"created_at": self.created_at.isoformat() if hasattr(self.created_at, "isoformat") else str(self.created_at),
|
|
"updated_at": self.updated_at.isoformat() if hasattr(self.updated_at, "isoformat") else str(self.updated_at),
|
|
}
|
|
|
|
|
|
class TenantMembership(Base):
|
|
__tablename__ = "tenant_memberships"
|
|
|
|
membership_id = Column(String(64), primary_key=True, default=lambda: f"mem_{uuid.uuid4().hex[:12]}")
|
|
tenant_id = Column(String(64), nullable=False, index=True)
|
|
user_id = Column(String(128), nullable=False, index=True)
|
|
email = Column(String(255), nullable=False)
|
|
role = Column(String(64), nullable=False)
|
|
status = Column(String(32), default="ACTIVE", nullable=False)
|
|
created_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
|
|
updated_at = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc), nullable=False)
|
|
|
|
def __init__(self, tenant_id: str, user_id: str, email: str, role: str,
|
|
status: str = "ACTIVE", membership_id: Optional[str] = None,
|
|
created_at: Optional[datetime] = None, updated_at: Optional[datetime] = None):
|
|
self.membership_id = membership_id or f"mem_{uuid.uuid4().hex[:12]}"
|
|
self.tenant_id = tenant_id
|
|
self.user_id = user_id
|
|
self.email = email
|
|
self.role = role
|
|
self.status = status
|
|
self.created_at = created_at or datetime.now(timezone.utc)
|
|
self.updated_at = updated_at or datetime.now(timezone.utc)
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
return {
|
|
"membership_id": self.membership_id,
|
|
"tenant_id": self.tenant_id,
|
|
"user_id": self.user_id,
|
|
"email": self.email,
|
|
"role": self.role,
|
|
"status": self.status,
|
|
"created_at": self.created_at.isoformat() if hasattr(self.created_at, "isoformat") else str(self.created_at),
|
|
"updated_at": self.updated_at.isoformat() if hasattr(self.updated_at, "isoformat") else str(self.updated_at),
|
|
}
|
|
|
|
|
|
class TransactionAuditLog(Base):
|
|
__tablename__ = "transaction_audit_logs"
|
|
|
|
audit_id = Column(String(64), primary_key=True, default=lambda: f"aud_{uuid.uuid4().hex}")
|
|
tenant_id = Column(String(64), nullable=False, index=True)
|
|
actor_id = Column(String(128), nullable=False)
|
|
entity_type = Column(String(64), nullable=False)
|
|
entity_id = Column(String(128), nullable=False)
|
|
action = Column(String(32), nullable=False)
|
|
timestamp = Column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
|
|
correlation_id = Column(String(64), nullable=True)
|
|
field_diff_json = Column(Text, nullable=True)
|
|
|
|
def __init__(self, tenant_id: str, actor_id: str, entity_type: str, entity_id: str,
|
|
action: str, correlation_id: Optional[str] = None,
|
|
field_diff_json: Optional[str] = None, audit_id: Optional[str] = None,
|
|
timestamp: Optional[datetime] = None):
|
|
self.audit_id = audit_id or f"aud_{uuid.uuid4().hex}"
|
|
self.tenant_id = tenant_id
|
|
self.actor_id = actor_id
|
|
self.entity_type = entity_type
|
|
self.entity_id = entity_id
|
|
self.action = action
|
|
self.correlation_id = correlation_id
|
|
self.field_diff_json = field_diff_json
|
|
self.timestamp = timestamp or datetime.now(timezone.utc)
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
diff = {}
|
|
if self.field_diff_json:
|
|
try:
|
|
diff = json.loads(self.field_diff_json)
|
|
except Exception:
|
|
diff = {"raw": self.field_diff_json}
|
|
return {
|
|
"audit_id": self.audit_id,
|
|
"tenant_id": self.tenant_id,
|
|
"actor_id": self.actor_id,
|
|
"entity_type": self.entity_type,
|
|
"entity_id": self.entity_id,
|
|
"action": self.action,
|
|
"timestamp": self.timestamp.isoformat() if hasattr(self.timestamp, "isoformat") else str(self.timestamp),
|
|
"correlation_id": self.correlation_id,
|
|
"field_diff": diff,
|
|
}
|