2025-10-12 18:47:33 +02:00
|
|
|
"""
|
|
|
|
|
Internal Demo Cloning API for Sales Service
|
|
|
|
|
Service-to-service endpoint for cloning sales data
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Header
|
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
2025-10-24 13:05:04 +02:00
|
|
|
from sqlalchemy import select, delete, func
|
2025-10-12 18:47:33 +02:00
|
|
|
import structlog
|
|
|
|
|
import uuid
|
|
|
|
|
from datetime import datetime, timezone, timedelta
|
|
|
|
|
from typing import Optional
|
|
|
|
|
import os
|
|
|
|
|
from decimal import Decimal
|
2025-11-27 15:52:40 +01:00
|
|
|
import sys
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
|
|
sys.path.insert(0, str(Path(__file__).parent.parent.parent.parent))
|
|
|
|
|
from shared.utils.demo_dates import adjust_date_for_demo, BASE_REFERENCE_DATE
|
2025-10-12 18:47:33 +02:00
|
|
|
|
|
|
|
|
from app.core.database import get_db
|
|
|
|
|
from app.models.sales import SalesData
|
|
|
|
|
|
|
|
|
|
logger = structlog.get_logger()
|
|
|
|
|
router = APIRouter(prefix="/internal/demo", tags=["internal"])
|
|
|
|
|
|
|
|
|
|
# Internal API key for service-to-service auth
|
|
|
|
|
INTERNAL_API_KEY = os.getenv("INTERNAL_API_KEY", "dev-internal-key-change-in-production")
|
|
|
|
|
|
|
|
|
|
# Base demo tenant IDs
|
|
|
|
|
DEMO_TENANT_SAN_PABLO = "a1b2c3d4-e5f6-47a8-b9c0-d1e2f3a4b5c6"
|
|
|
|
|
DEMO_TENANT_LA_ESPIGA = "b2c3d4e5-f6a7-48b9-c0d1-e2f3a4b5c6d7"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def verify_internal_api_key(x_internal_api_key: Optional[str] = Header(None)):
|
|
|
|
|
"""Verify internal API key for service-to-service communication"""
|
|
|
|
|
if x_internal_api_key != INTERNAL_API_KEY:
|
|
|
|
|
logger.warning("Unauthorized internal API access attempted")
|
|
|
|
|
raise HTTPException(status_code=403, detail="Invalid internal API key")
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.post("/clone")
|
|
|
|
|
async def clone_demo_data(
|
|
|
|
|
base_tenant_id: str,
|
|
|
|
|
virtual_tenant_id: str,
|
|
|
|
|
demo_account_type: str,
|
|
|
|
|
session_id: Optional[str] = None,
|
2025-11-27 15:52:40 +01:00
|
|
|
session_created_at: Optional[str] = None,
|
2025-10-12 18:47:33 +02:00
|
|
|
db: AsyncSession = Depends(get_db),
|
|
|
|
|
_: bool = Depends(verify_internal_api_key)
|
|
|
|
|
):
|
|
|
|
|
"""
|
|
|
|
|
Clone sales service data for a virtual demo tenant
|
|
|
|
|
|
|
|
|
|
Clones:
|
|
|
|
|
- Sales history records from template tenant
|
|
|
|
|
- Adjusts dates to recent timeframe
|
|
|
|
|
- Updates product references to new virtual tenant
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
base_tenant_id: Template tenant UUID to clone from
|
|
|
|
|
virtual_tenant_id: Target virtual tenant UUID
|
|
|
|
|
demo_account_type: Type of demo account
|
|
|
|
|
session_id: Originating session ID for tracing
|
2025-11-27 15:52:40 +01:00
|
|
|
session_created_at: ISO timestamp when demo session was created (for date adjustment)
|
2025-10-12 18:47:33 +02:00
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
Cloning status and record counts
|
|
|
|
|
"""
|
|
|
|
|
start_time = datetime.now(timezone.utc)
|
|
|
|
|
|
2025-11-27 15:52:40 +01:00
|
|
|
# Parse session_created_at or fallback to now
|
|
|
|
|
if session_created_at:
|
|
|
|
|
try:
|
|
|
|
|
session_time = datetime.fromisoformat(session_created_at.replace('Z', '+00:00'))
|
|
|
|
|
except (ValueError, AttributeError) as e:
|
|
|
|
|
logger.warning(
|
|
|
|
|
"Invalid session_created_at format, using current time",
|
|
|
|
|
session_created_at=session_created_at,
|
|
|
|
|
error=str(e)
|
|
|
|
|
)
|
|
|
|
|
session_time = datetime.now(timezone.utc)
|
|
|
|
|
else:
|
|
|
|
|
logger.warning("session_created_at not provided, using current time")
|
|
|
|
|
session_time = datetime.now(timezone.utc)
|
|
|
|
|
|
2025-10-12 18:47:33 +02:00
|
|
|
logger.info(
|
|
|
|
|
"Starting sales data cloning",
|
|
|
|
|
base_tenant_id=base_tenant_id,
|
|
|
|
|
virtual_tenant_id=virtual_tenant_id,
|
|
|
|
|
demo_account_type=demo_account_type,
|
2025-11-27 15:52:40 +01:00
|
|
|
session_id=session_id,
|
|
|
|
|
session_time=session_time.isoformat()
|
2025-10-12 18:47:33 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
# Validate UUIDs
|
|
|
|
|
base_uuid = uuid.UUID(base_tenant_id)
|
|
|
|
|
virtual_uuid = uuid.UUID(virtual_tenant_id)
|
|
|
|
|
|
|
|
|
|
# Track cloning statistics
|
|
|
|
|
stats = {
|
|
|
|
|
"sales_records": 0,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
# Clone Sales Data
|
|
|
|
|
result = await db.execute(
|
|
|
|
|
select(SalesData).where(SalesData.tenant_id == base_uuid)
|
|
|
|
|
)
|
|
|
|
|
base_sales = result.scalars().all()
|
|
|
|
|
|
|
|
|
|
logger.info(
|
|
|
|
|
"Found sales records to clone",
|
|
|
|
|
count=len(base_sales),
|
|
|
|
|
base_tenant=str(base_uuid)
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
for sale in base_sales:
|
2025-11-27 15:52:40 +01:00
|
|
|
# Adjust date using the shared utility
|
|
|
|
|
adjusted_date = adjust_date_for_demo(
|
|
|
|
|
sale.date,
|
|
|
|
|
session_time,
|
|
|
|
|
BASE_REFERENCE_DATE
|
|
|
|
|
) if sale.date else None
|
|
|
|
|
|
2025-10-12 18:47:33 +02:00
|
|
|
# Create new sales record with adjusted date
|
|
|
|
|
new_sale = SalesData(
|
|
|
|
|
id=uuid.uuid4(),
|
|
|
|
|
tenant_id=virtual_uuid,
|
2025-11-27 15:52:40 +01:00
|
|
|
date=adjusted_date,
|
2025-10-12 18:47:33 +02:00
|
|
|
inventory_product_id=sale.inventory_product_id, # Keep same product refs
|
|
|
|
|
quantity_sold=sale.quantity_sold,
|
|
|
|
|
unit_price=sale.unit_price,
|
|
|
|
|
revenue=sale.revenue,
|
|
|
|
|
cost_of_goods=sale.cost_of_goods,
|
|
|
|
|
discount_applied=sale.discount_applied,
|
|
|
|
|
location_id=sale.location_id,
|
|
|
|
|
sales_channel=sale.sales_channel,
|
|
|
|
|
source="demo_clone", # Mark as cloned
|
|
|
|
|
is_validated=sale.is_validated,
|
|
|
|
|
validation_notes=sale.validation_notes,
|
|
|
|
|
notes=sale.notes,
|
|
|
|
|
weather_condition=sale.weather_condition,
|
|
|
|
|
is_holiday=sale.is_holiday,
|
|
|
|
|
is_weekend=sale.is_weekend,
|
2025-11-27 15:52:40 +01:00
|
|
|
created_at=session_time,
|
|
|
|
|
updated_at=session_time
|
2025-10-12 18:47:33 +02:00
|
|
|
)
|
|
|
|
|
db.add(new_sale)
|
|
|
|
|
stats["sales_records"] += 1
|
|
|
|
|
|
|
|
|
|
# Commit all changes
|
|
|
|
|
await db.commit()
|
|
|
|
|
|
|
|
|
|
total_records = sum(stats.values())
|
|
|
|
|
duration_ms = int((datetime.now(timezone.utc) - start_time).total_seconds() * 1000)
|
|
|
|
|
|
|
|
|
|
logger.info(
|
|
|
|
|
"Sales data cloning completed",
|
|
|
|
|
virtual_tenant_id=virtual_tenant_id,
|
|
|
|
|
total_records=total_records,
|
|
|
|
|
stats=stats,
|
|
|
|
|
duration_ms=duration_ms
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
"service": "sales",
|
|
|
|
|
"status": "completed",
|
|
|
|
|
"records_cloned": total_records,
|
|
|
|
|
"duration_ms": duration_ms,
|
|
|
|
|
"details": stats
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
except ValueError as e:
|
|
|
|
|
logger.error("Invalid UUID format", error=str(e))
|
|
|
|
|
raise HTTPException(status_code=400, detail=f"Invalid UUID: {str(e)}")
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.error(
|
|
|
|
|
"Failed to clone sales data",
|
|
|
|
|
error=str(e),
|
|
|
|
|
virtual_tenant_id=virtual_tenant_id,
|
|
|
|
|
exc_info=True
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# Rollback on error
|
|
|
|
|
await db.rollback()
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
"service": "sales",
|
|
|
|
|
"status": "failed",
|
|
|
|
|
"records_cloned": 0,
|
|
|
|
|
"duration_ms": int((datetime.now(timezone.utc) - start_time).total_seconds() * 1000),
|
|
|
|
|
"error": str(e)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.get("/clone/health")
|
|
|
|
|
async def clone_health_check(_: bool = Depends(verify_internal_api_key)):
|
|
|
|
|
"""
|
|
|
|
|
Health check for internal cloning endpoint
|
|
|
|
|
Used by orchestrator to verify service availability
|
|
|
|
|
"""
|
|
|
|
|
return {
|
|
|
|
|
"service": "sales",
|
|
|
|
|
"clone_endpoint": "available",
|
|
|
|
|
"version": "2.0.0"
|
|
|
|
|
}
|
2025-10-24 13:05:04 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@router.delete("/tenant/{virtual_tenant_id}")
|
|
|
|
|
async def delete_demo_data(
|
|
|
|
|
virtual_tenant_id: str,
|
|
|
|
|
db: AsyncSession = Depends(get_db),
|
|
|
|
|
_: bool = Depends(verify_internal_api_key)
|
|
|
|
|
):
|
|
|
|
|
"""Delete all sales data for a virtual demo tenant"""
|
|
|
|
|
logger.info("Deleting sales data for virtual tenant", virtual_tenant_id=virtual_tenant_id)
|
|
|
|
|
start_time = datetime.now(timezone.utc)
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
virtual_uuid = uuid.UUID(virtual_tenant_id)
|
|
|
|
|
|
|
|
|
|
# Count records
|
|
|
|
|
sales_count = await db.scalar(select(func.count(SalesData.id)).where(SalesData.tenant_id == virtual_uuid))
|
|
|
|
|
|
|
|
|
|
# Delete sales data
|
|
|
|
|
await db.execute(delete(SalesData).where(SalesData.tenant_id == virtual_uuid))
|
|
|
|
|
await db.commit()
|
|
|
|
|
|
|
|
|
|
duration_ms = int((datetime.now(timezone.utc) - start_time).total_seconds() * 1000)
|
|
|
|
|
logger.info("Sales data deleted successfully", virtual_tenant_id=virtual_tenant_id, duration_ms=duration_ms)
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
"service": "sales",
|
|
|
|
|
"status": "deleted",
|
|
|
|
|
"virtual_tenant_id": virtual_tenant_id,
|
|
|
|
|
"records_deleted": {
|
|
|
|
|
"sales": sales_count,
|
|
|
|
|
"total": sales_count
|
|
|
|
|
},
|
|
|
|
|
"duration_ms": duration_ms
|
|
|
|
|
}
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.error("Failed to delete sales data", error=str(e), exc_info=True)
|
|
|
|
|
await db.rollback()
|
|
|
|
|
raise HTTPException(status_code=500, detail=str(e))
|