demo seed change

This commit is contained in:
Urtzi Alfaro
2025-12-13 23:57:54 +01:00
parent f3688dfb04
commit ff830a3415
299 changed files with 20328 additions and 19485 deletions

View File

@@ -8,18 +8,21 @@ from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
import structlog
import uuid
from datetime import datetime, timezone
from datetime import datetime, timezone, timedelta
from typing import Optional
import os
import json
from pathlib import Path
from app.core.database import get_db
from app.models.tenants import Tenant, Subscription, TenantMember
from app.models.tenant_location import TenantLocation
from shared.utils.demo_dates import adjust_date_for_demo, BASE_REFERENCE_DATE
from app.core.config import settings
logger = structlog.get_logger()
router = APIRouter(prefix="/internal/demo", tags=["internal"])
router = APIRouter()
# Base demo tenant IDs
DEMO_TENANT_PROFESSIONAL = "a1b2c3d4-e5f6-47a8-b9c0-d1e2f3a4b5c6"
@@ -33,7 +36,7 @@ def verify_internal_api_key(x_internal_api_key: Optional[str] = Header(None)):
return True
@router.post("/clone")
@router.post("/internal/demo/clone")
async def clone_demo_data(
base_tenant_id: str,
virtual_tenant_id: str,
@@ -100,40 +103,96 @@ async def clone_demo_data(
virtual_tenant_id=virtual_tenant_id,
base_tenant_id=base_tenant_id)
# Get subscription from template tenant
base_uuid = uuid.UUID(base_tenant_id)
result = await db.execute(
select(Subscription).where(
Subscription.tenant_id == base_uuid,
Subscription.status == "active"
)
)
template_subscription = result.scalars().first()
# Load subscription from seed data instead of cloning from template
try:
from shared.utils.seed_data_paths import get_seed_data_path
if demo_account_type == "professional":
json_file = get_seed_data_path("professional", "01-tenant.json")
elif demo_account_type == "enterprise":
json_file = get_seed_data_path("enterprise", "01-tenant.json")
else:
raise ValueError(f"Invalid demo account type: {demo_account_type}")
if template_subscription:
# Clone subscription from template
except ImportError:
# Fallback to original path
seed_data_dir = Path(__file__).parent.parent.parent.parent / "infrastructure" / "seed-data"
if demo_account_type == "professional":
json_file = seed_data_dir / "professional" / "01-tenant.json"
elif demo_account_type == "enterprise":
json_file = seed_data_dir / "enterprise" / "parent" / "01-tenant.json"
else:
raise ValueError(f"Invalid demo account type: {demo_account_type}")
if json_file.exists():
import json
with open(json_file, 'r', encoding='utf-8') as f:
seed_data = json.load(f)
subscription_data = seed_data.get('subscription')
if subscription_data:
# Load subscription from seed data
subscription = Subscription(
tenant_id=virtual_uuid,
plan=subscription_data.get('plan', 'professional'),
status=subscription_data.get('status', 'active'),
monthly_price=subscription_data.get('monthly_price', 299.00),
max_users=subscription_data.get('max_users', 10),
max_locations=subscription_data.get('max_locations', 3),
max_products=subscription_data.get('max_products', 500),
features=subscription_data.get('features', {}),
trial_ends_at=adjust_date_for_demo(
datetime.fromisoformat(subscription_data['trial_ends_at'].replace('Z', '+00:00')),
session_time,
BASE_REFERENCE_DATE
) if subscription_data.get('trial_ends_at') else None,
next_billing_date=adjust_date_for_demo(
datetime.fromisoformat(subscription_data['next_billing_date'].replace('Z', '+00:00')),
session_time,
BASE_REFERENCE_DATE
) if subscription_data.get('next_billing_date') else None
)
db.add(subscription)
await db.commit()
logger.info("Subscription loaded from seed data successfully",
virtual_tenant_id=virtual_tenant_id,
plan=subscription.plan)
else:
logger.warning("No subscription found in seed data",
virtual_tenant_id=virtual_tenant_id)
else:
logger.warning("Seed data file not found, falling back to default subscription",
file_path=str(json_file))
# Create default subscription if seed data not available
subscription = Subscription(
tenant_id=virtual_uuid,
plan=template_subscription.plan,
status=template_subscription.status,
monthly_price=template_subscription.monthly_price,
max_users=template_subscription.max_users,
max_locations=template_subscription.max_locations,
max_products=template_subscription.max_products,
features=template_subscription.features.copy() if template_subscription.features else {},
trial_ends_at=template_subscription.trial_ends_at,
next_billing_date=datetime.now(timezone.utc) + timedelta(days=90) if template_subscription.next_billing_date else None
plan="professional" if demo_account_type == "professional" else "enterprise",
status="active",
monthly_price=299.00 if demo_account_type == "professional" else 799.00,
max_users=10 if demo_account_type == "professional" else 50,
max_locations=3 if demo_account_type == "professional" else -1,
max_products=500 if demo_account_type == "professional" else -1,
features={
"production_planning": True,
"procurement_management": True,
"inventory_management": True,
"sales_analytics": True,
"multi_location": True,
"advanced_reporting": True,
"api_access": True,
"priority_support": True
},
next_billing_date=datetime.now(timezone.utc) + timedelta(days=90)
)
db.add(subscription)
await db.commit()
logger.info("Subscription cloned successfully",
logger.info("Default subscription created",
virtual_tenant_id=virtual_tenant_id,
plan=subscription.plan)
else:
logger.warning("No subscription found on template tenant",
base_tenant_id=base_tenant_id)
# Return success - idempotent operation
duration_ms = int((datetime.now(timezone.utc) - start_time).total_seconds() * 1000)