from typing import Optional, List from models import db, Tenant, FormConfig, Submission, UserRole, TenantStatus from models import AuditLog import uuid import logging logger = logging.getLogger(__name__) class TenantAdminService: @staticmethod def get_tenants(user): if user.role == UserRole.ADMIN: return Tenant.query.order_by(Tenant.created_at.desc()).all() return user.tenants if user else [] @staticmethod def create_tenant(name, public_key, allowed_origins, status, user): tenant_id = f'tenant_{name.lower().replace(" ", "_")}_{str(uuid.uuid4())[:8]}' tenant = Tenant( id=tenant_id, name=name, public_key=public_key or str(uuid.uuid4()).hex[:32], allowed_origins=allowed_origins, status=TenantStatus(status) if status in [s.value for s in TenantStatus] else TenantStatus.ACTIVE ) db.session.add(tenant) db.session.commit() AuditLog.log_action( action='create', resource_type='tenant', user=user, resource_id=tenant.id, details={'name': name, 'public_key': public_key} ) return tenant @staticmethod def update_tenant(tenant, name, public_key, allowed_origins, status, user): tenant.name = name if name else tenant.name tenant.public_key = public_key if public_key else tenant.public_key tenant.allowed_origins = allowed_origins if allowed_origins else tenant.allowed_origins if status in [s.value for s in TenantStatus]: tenant.status = TenantStatus(status) db.session.commit() AuditLog.log_action( action='update', resource_type='tenant', user=user, resource_id=tenant.id, details={'name': tenant.name, 'status': tenant.status.value} ) @staticmethod def delete_tenant(tenant, user): db.session.delete(tenant) db.session.commit() AuditLog.log_action( action='delete', resource_type='tenant', user=user, resource_id=tenant.id, details={'name': tenant.name} )