demo seed change
This commit is contained in:
@@ -1,330 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Demo Inventory Seeding Script for Inventory Service
|
||||
Creates realistic Spanish ingredients for demo template tenants
|
||||
|
||||
This script runs as a Kubernetes init job inside the inventory-service container.
|
||||
It populates the template tenants with a comprehensive catalog of ingredients.
|
||||
|
||||
Usage:
|
||||
python /app/scripts/demo/seed_demo_inventory.py
|
||||
|
||||
Environment Variables Required:
|
||||
INVENTORY_DATABASE_URL - PostgreSQL connection string for inventory database
|
||||
DEMO_MODE - Set to 'production' for production seeding
|
||||
LOG_LEVEL - Logging level (default: INFO)
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import uuid
|
||||
import sys
|
||||
import os
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
# Add app to path
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy import select
|
||||
import structlog
|
||||
|
||||
from app.models.inventory import Ingredient
|
||||
|
||||
# Configure logging
|
||||
structlog.configure(
|
||||
processors=[
|
||||
structlog.stdlib.add_log_level,
|
||||
structlog.processors.TimeStamper(fmt="iso"),
|
||||
structlog.dev.ConsoleRenderer()
|
||||
]
|
||||
)
|
||||
|
||||
logger = structlog.get_logger()
|
||||
|
||||
# Fixed Demo Tenant IDs (must match tenant service)
|
||||
DEMO_TENANT_PROFESSIONAL = uuid.UUID("a1b2c3d4-e5f6-47a8-b9c0-d1e2f3a4b5c6")
|
||||
DEMO_TENANT_ENTERPRISE_CHAIN = uuid.UUID("c3d4e5f6-a7b8-49c0-d1e2-f3a4b5c6d7e8") # Enterprise parent (Obrador)
|
||||
|
||||
|
||||
def load_ingredients_data():
|
||||
"""Load ingredients data from JSON file"""
|
||||
# Look for data file in the same directory as this script
|
||||
data_file = Path(__file__).parent / "ingredientes_es.json"
|
||||
|
||||
if not data_file.exists():
|
||||
raise FileNotFoundError(
|
||||
f"Ingredients data file not found: {data_file}. "
|
||||
"Make sure ingredientes_es.json is in the same directory as this script."
|
||||
)
|
||||
|
||||
logger.info("Loading ingredients data", file=str(data_file))
|
||||
|
||||
with open(data_file, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
|
||||
# Flatten all ingredient categories into a single list
|
||||
all_ingredients = []
|
||||
for category_name, ingredients in data.items():
|
||||
logger.debug(f"Loading category: {category_name} ({len(ingredients)} items)")
|
||||
all_ingredients.extend(ingredients)
|
||||
|
||||
logger.info(f"Loaded {len(all_ingredients)} ingredients from JSON")
|
||||
return all_ingredients
|
||||
|
||||
|
||||
async def seed_ingredients_for_tenant(
|
||||
db: AsyncSession,
|
||||
tenant_id: uuid.UUID,
|
||||
tenant_name: str,
|
||||
ingredients_data: list
|
||||
) -> dict:
|
||||
"""
|
||||
Seed ingredients for a specific tenant using pre-defined UUIDs
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
tenant_id: UUID of the tenant
|
||||
tenant_name: Name of the tenant (for logging)
|
||||
ingredients_data: List of ingredient dictionaries with pre-defined IDs
|
||||
|
||||
Returns:
|
||||
Dict with seeding statistics
|
||||
"""
|
||||
logger.info("─" * 80)
|
||||
logger.info(f"Seeding ingredients for: {tenant_name}")
|
||||
logger.info(f"Tenant ID: {tenant_id}")
|
||||
logger.info("─" * 80)
|
||||
|
||||
created_count = 0
|
||||
updated_count = 0
|
||||
skipped_count = 0
|
||||
|
||||
for ing_data in ingredients_data:
|
||||
sku = ing_data["sku"]
|
||||
name = ing_data["name"]
|
||||
|
||||
# Check if ingredient already exists for this tenant with this SKU
|
||||
result = await db.execute(
|
||||
select(Ingredient).where(
|
||||
Ingredient.tenant_id == tenant_id,
|
||||
Ingredient.sku == sku
|
||||
)
|
||||
)
|
||||
existing_ingredient = result.scalars().first()
|
||||
|
||||
if existing_ingredient:
|
||||
logger.debug(f" ⏭️ Skipping (exists): {sku} - {name}")
|
||||
skipped_count += 1
|
||||
continue
|
||||
|
||||
# Generate tenant-specific UUID by combining base UUID with tenant ID
|
||||
# This ensures each tenant has unique IDs but they're deterministic (same on re-run)
|
||||
base_id = uuid.UUID(ing_data["id"])
|
||||
# XOR the base ID with the tenant ID to create a tenant-specific ID
|
||||
tenant_int = int(tenant_id.hex, 16)
|
||||
base_int = int(base_id.hex, 16)
|
||||
ingredient_id = uuid.UUID(int=tenant_int ^ base_int)
|
||||
|
||||
# Create new ingredient
|
||||
ingredient = Ingredient(
|
||||
id=ingredient_id,
|
||||
tenant_id=tenant_id,
|
||||
name=name,
|
||||
sku=sku,
|
||||
barcode=None, # Could generate EAN-13 barcodes if needed
|
||||
product_type=ing_data["product_type"],
|
||||
ingredient_category=ing_data["ingredient_category"],
|
||||
product_category=ing_data["product_category"],
|
||||
subcategory=ing_data.get("subcategory"),
|
||||
description=ing_data["description"],
|
||||
brand=ing_data.get("brand"),
|
||||
unit_of_measure=ing_data["unit_of_measure"],
|
||||
package_size=None,
|
||||
average_cost=ing_data["average_cost"],
|
||||
last_purchase_price=ing_data["average_cost"],
|
||||
standard_cost=ing_data["average_cost"],
|
||||
low_stock_threshold=ing_data.get("low_stock_threshold", 10.0),
|
||||
reorder_point=ing_data.get("reorder_point", 20.0),
|
||||
reorder_quantity=ing_data.get("reorder_point", 20.0) * 2,
|
||||
max_stock_level=ing_data.get("reorder_point", 20.0) * 5,
|
||||
shelf_life_days=ing_data.get("shelf_life_days"),
|
||||
is_perishable=ing_data.get("is_perishable", False),
|
||||
is_active=True,
|
||||
allergen_info=ing_data.get("allergen_info") if ing_data.get("allergen_info") else None,
|
||||
# NEW: Local production support (Sprint 5)
|
||||
produced_locally=ing_data.get("produced_locally", False),
|
||||
recipe_id=uuid.UUID(ing_data["recipe_id"]) if ing_data.get("recipe_id") else None,
|
||||
created_at=datetime.now(timezone.utc),
|
||||
updated_at=datetime.now(timezone.utc)
|
||||
)
|
||||
|
||||
db.add(ingredient)
|
||||
created_count += 1
|
||||
|
||||
logger.debug(f" ✅ Created: {sku} - {name}")
|
||||
|
||||
# Commit all changes for this tenant
|
||||
await db.commit()
|
||||
|
||||
logger.info(f" 📊 Created: {created_count}, Skipped: {skipped_count}")
|
||||
logger.info("")
|
||||
|
||||
return {
|
||||
"tenant_id": str(tenant_id),
|
||||
"tenant_name": tenant_name,
|
||||
"created": created_count,
|
||||
"skipped": skipped_count,
|
||||
"total": len(ingredients_data)
|
||||
}
|
||||
|
||||
|
||||
async def seed_inventory(db: AsyncSession):
|
||||
"""
|
||||
Seed inventory for all demo template tenants
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
|
||||
Returns:
|
||||
Dict with overall seeding statistics
|
||||
"""
|
||||
logger.info("=" * 80)
|
||||
logger.info("📦 Starting Demo Inventory Seeding")
|
||||
logger.info("=" * 80)
|
||||
|
||||
# Load ingredients data once
|
||||
try:
|
||||
ingredients_data = load_ingredients_data()
|
||||
except FileNotFoundError as e:
|
||||
logger.error(str(e))
|
||||
raise
|
||||
|
||||
results = []
|
||||
|
||||
# Seed for Professional Bakery (single location)
|
||||
logger.info("")
|
||||
result_professional = await seed_ingredients_for_tenant(
|
||||
db,
|
||||
DEMO_TENANT_PROFESSIONAL,
|
||||
"Panadería Artesana Madrid (Professional)",
|
||||
ingredients_data
|
||||
)
|
||||
results.append(result_professional)
|
||||
|
||||
# Seed for Enterprise Parent (central production - Obrador)
|
||||
logger.info("")
|
||||
result_enterprise_parent = await seed_ingredients_for_tenant(
|
||||
db,
|
||||
DEMO_TENANT_ENTERPRISE_CHAIN,
|
||||
"Panadería Central - Obrador Madrid (Enterprise Parent)",
|
||||
ingredients_data
|
||||
)
|
||||
results.append(result_enterprise_parent)
|
||||
|
||||
# Calculate totals
|
||||
total_created = sum(r["created"] for r in results)
|
||||
total_skipped = sum(r["skipped"] for r in results)
|
||||
|
||||
logger.info("=" * 80)
|
||||
logger.info("✅ Demo Inventory Seeding Completed")
|
||||
logger.info("=" * 80)
|
||||
|
||||
return {
|
||||
"service": "inventory",
|
||||
"tenants_seeded": len(results),
|
||||
"total_created": total_created,
|
||||
"total_skipped": total_skipped,
|
||||
"results": results
|
||||
}
|
||||
|
||||
|
||||
async def main():
|
||||
"""Main execution function"""
|
||||
|
||||
logger.info("Demo Inventory Seeding Script Starting")
|
||||
logger.info("Mode: %s", os.getenv("DEMO_MODE", "development"))
|
||||
logger.info("Log Level: %s", os.getenv("LOG_LEVEL", "INFO"))
|
||||
|
||||
# Get database URL from environment
|
||||
database_url = os.getenv("INVENTORY_DATABASE_URL") or os.getenv("DATABASE_URL")
|
||||
if not database_url:
|
||||
logger.error("❌ INVENTORY_DATABASE_URL or DATABASE_URL environment variable must be set")
|
||||
return 1
|
||||
|
||||
# Convert to async URL if needed
|
||||
if database_url.startswith("postgresql://"):
|
||||
database_url = database_url.replace("postgresql://", "postgresql+asyncpg://", 1)
|
||||
|
||||
logger.info("Connecting to inventory database")
|
||||
|
||||
# Create engine and session
|
||||
engine = create_async_engine(
|
||||
database_url,
|
||||
echo=False,
|
||||
pool_pre_ping=True,
|
||||
pool_size=5,
|
||||
max_overflow=10
|
||||
)
|
||||
|
||||
async_session = sessionmaker(
|
||||
engine,
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False
|
||||
)
|
||||
|
||||
try:
|
||||
async with async_session() as session:
|
||||
result = await seed_inventory(session)
|
||||
|
||||
logger.info("")
|
||||
logger.info("📊 Seeding Summary:")
|
||||
logger.info(f" ✅ Tenants seeded: {result['tenants_seeded']}")
|
||||
logger.info(f" ✅ Total created: {result['total_created']}")
|
||||
logger.info(f" ⏭️ Total skipped: {result['total_skipped']}")
|
||||
logger.info("")
|
||||
|
||||
# Print per-tenant details
|
||||
for tenant_result in result['results']:
|
||||
logger.info(
|
||||
f" {tenant_result['tenant_name']}: "
|
||||
f"{tenant_result['created']} created, {tenant_result['skipped']} skipped"
|
||||
)
|
||||
|
||||
logger.info("")
|
||||
logger.info("🎉 Success! Ingredient catalog is ready for cloning.")
|
||||
logger.info("")
|
||||
logger.info("Ingredients by category:")
|
||||
logger.info(" • Harinas: 6 tipos (T55, T65, Fuerza, Integral, Centeno, Espelta)")
|
||||
logger.info(" • Lácteos: 4 tipos (Mantequilla, Leche, Nata, Huevos)")
|
||||
logger.info(" • Levaduras: 3 tipos (Fresca, Seca, Masa Madre)")
|
||||
logger.info(" • Básicos: 3 tipos (Sal, Azúcar, Agua)")
|
||||
logger.info(" • Especiales: 5 tipos (Chocolate, Almendras, etc.)")
|
||||
logger.info(" • Productos: 3 referencias")
|
||||
logger.info("")
|
||||
logger.info("Next steps:")
|
||||
logger.info(" 1. Run seed jobs for other services (recipes, suppliers, etc.)")
|
||||
logger.info(" 2. Verify ingredient data in database")
|
||||
logger.info(" 3. Test demo session creation with inventory cloning")
|
||||
logger.info("")
|
||||
|
||||
return 0
|
||||
|
||||
except Exception as e:
|
||||
logger.error("=" * 80)
|
||||
logger.error("❌ Demo Inventory Seeding Failed")
|
||||
logger.error("=" * 80)
|
||||
logger.error("Error: %s", str(e))
|
||||
logger.error("", exc_info=True)
|
||||
return 1
|
||||
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
exit_code = asyncio.run(main())
|
||||
sys.exit(exit_code)
|
||||
@@ -1,347 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Demo Inventory Retail Seeding Script for Inventory Service
|
||||
Creates finished product inventory for enterprise child tenants (retail outlets)
|
||||
|
||||
This script runs as a Kubernetes init job inside the inventory-service container.
|
||||
It populates the child retail tenants with FINISHED PRODUCTS ONLY (no raw ingredients).
|
||||
|
||||
Usage:
|
||||
python /app/scripts/demo/seed_demo_inventory_retail.py
|
||||
|
||||
Environment Variables Required:
|
||||
INVENTORY_DATABASE_URL - PostgreSQL connection string for inventory database
|
||||
DEMO_MODE - Set to 'production' for production seeding
|
||||
LOG_LEVEL - Logging level (default: INFO)
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import uuid
|
||||
import sys
|
||||
import os
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
# Add app to path
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
|
||||
# Add shared to path for demo utilities
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent.parent.parent))
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy import select
|
||||
import structlog
|
||||
|
||||
from shared.utils.demo_dates import BASE_REFERENCE_DATE
|
||||
|
||||
from app.models.inventory import Ingredient, ProductType
|
||||
|
||||
# Configure logging
|
||||
structlog.configure(
|
||||
processors=[
|
||||
structlog.stdlib.add_log_level,
|
||||
structlog.processors.TimeStamper(fmt="iso"),
|
||||
structlog.dev.ConsoleRenderer()
|
||||
]
|
||||
)
|
||||
|
||||
logger = structlog.get_logger()
|
||||
|
||||
# Fixed Demo Tenant IDs (must match tenant service)
|
||||
DEMO_TENANT_ENTERPRISE_CHAIN = uuid.UUID("c3d4e5f6-a7b8-49c0-d1e2-f3a4b5c6d7e8") # Enterprise parent (Obrador)
|
||||
DEMO_TENANT_CHILD_1 = uuid.UUID("d4e5f6a7-b8c9-40d1-e2f3-a4b5c6d7e8f9") # Madrid Centro
|
||||
DEMO_TENANT_CHILD_2 = uuid.UUID("e5f6a7b8-c9d0-41e2-f3a4-b5c6d7e8f9a0") # Barcelona Gràcia
|
||||
DEMO_TENANT_CHILD_3 = uuid.UUID("f6a7b8c9-d0e1-42f3-a4b5-c6d7e8f9a0b1") # Valencia Ruzafa
|
||||
|
||||
# Child tenant configurations
|
||||
CHILD_TENANTS = [
|
||||
(DEMO_TENANT_CHILD_1, "Madrid Centro"),
|
||||
(DEMO_TENANT_CHILD_2, "Barcelona Gràcia"),
|
||||
(DEMO_TENANT_CHILD_3, "Valencia Ruzafa")
|
||||
]
|
||||
|
||||
|
||||
def load_finished_products_data():
|
||||
"""Load ONLY finished products from JSON file (no raw ingredients)"""
|
||||
# Look for data file in the same directory as this script
|
||||
data_file = Path(__file__).parent / "ingredientes_es.json"
|
||||
|
||||
if not data_file.exists():
|
||||
raise FileNotFoundError(
|
||||
f"Ingredients data file not found: {data_file}. "
|
||||
"Make sure ingredientes_es.json is in the same directory as this script."
|
||||
)
|
||||
|
||||
logger.info("Loading finished products data", file=str(data_file))
|
||||
|
||||
with open(data_file, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
|
||||
# Extract ONLY finished products (not raw ingredients)
|
||||
finished_products = data.get("productos_terminados", [])
|
||||
|
||||
logger.info(f"Loaded {len(finished_products)} finished products from JSON")
|
||||
logger.info("NOTE: Raw ingredients (flour, yeast, etc.) are NOT seeded for retail outlets")
|
||||
|
||||
return finished_products
|
||||
|
||||
|
||||
async def seed_retail_inventory_for_tenant(
|
||||
db: AsyncSession,
|
||||
tenant_id: uuid.UUID,
|
||||
parent_tenant_id: uuid.UUID,
|
||||
tenant_name: str,
|
||||
products_data: list
|
||||
) -> dict:
|
||||
"""
|
||||
Seed finished product inventory for a child retail tenant using XOR ID transformation
|
||||
|
||||
This ensures retail outlets have the same product catalog as their parent (central production),
|
||||
using deterministic UUIDs that map correctly across tenants.
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
tenant_id: UUID of the child tenant
|
||||
parent_tenant_id: UUID of the parent tenant (for XOR transformation)
|
||||
tenant_name: Name of the tenant (for logging)
|
||||
products_data: List of finished product dictionaries with pre-defined IDs
|
||||
|
||||
Returns:
|
||||
Dict with seeding statistics
|
||||
"""
|
||||
logger.info("─" * 80)
|
||||
logger.info(f"Seeding retail inventory for: {tenant_name}")
|
||||
logger.info(f"Child Tenant ID: {tenant_id}")
|
||||
logger.info(f"Parent Tenant ID: {parent_tenant_id}")
|
||||
logger.info("─" * 80)
|
||||
|
||||
created_count = 0
|
||||
skipped_count = 0
|
||||
|
||||
for product_data in products_data:
|
||||
sku = product_data["sku"]
|
||||
name = product_data["name"]
|
||||
|
||||
# Check if product already exists for this tenant with this SKU
|
||||
result = await db.execute(
|
||||
select(Ingredient).where(
|
||||
Ingredient.tenant_id == tenant_id,
|
||||
Ingredient.sku == sku
|
||||
)
|
||||
)
|
||||
existing_product = result.scalars().first()
|
||||
|
||||
if existing_product:
|
||||
logger.debug(f" ⏭️ Skipping (exists): {sku} - {name}")
|
||||
skipped_count += 1
|
||||
continue
|
||||
|
||||
# Generate tenant-specific UUID using XOR transformation
|
||||
# This ensures the child's product IDs map to the parent's product IDs
|
||||
base_id = uuid.UUID(product_data["id"])
|
||||
tenant_int = int(tenant_id.hex, 16)
|
||||
base_int = int(base_id.hex, 16)
|
||||
product_id = uuid.UUID(int=tenant_int ^ base_int)
|
||||
|
||||
# Create new finished product for retail outlet
|
||||
product = Ingredient(
|
||||
id=product_id,
|
||||
tenant_id=tenant_id,
|
||||
name=name,
|
||||
sku=sku,
|
||||
barcode=None, # Could be set by retail outlet
|
||||
product_type=ProductType.FINISHED_PRODUCT, # CRITICAL: Only finished products
|
||||
ingredient_category=None, # Not applicable for finished products
|
||||
product_category=product_data["product_category"], # BREAD, CROISSANTS, PASTRIES, etc.
|
||||
subcategory=product_data.get("subcategory"),
|
||||
description=product_data["description"],
|
||||
brand=f"Obrador Madrid", # Branded from central production
|
||||
unit_of_measure=product_data["unit_of_measure"],
|
||||
package_size=None,
|
||||
average_cost=product_data["average_cost"], # Transfer price from central production
|
||||
last_purchase_price=product_data["average_cost"],
|
||||
standard_cost=product_data["average_cost"],
|
||||
# Retail outlets typically don't manage reorder points - they order from parent
|
||||
low_stock_threshold=None,
|
||||
reorder_point=None,
|
||||
reorder_quantity=None,
|
||||
max_stock_level=None,
|
||||
shelf_life_days=product_data.get("shelf_life_days"),
|
||||
is_perishable=product_data.get("is_perishable", True), # Bakery products are perishable
|
||||
is_active=True,
|
||||
allergen_info=product_data.get("allergen_info") if product_data.get("allergen_info") else None,
|
||||
# Retail outlets receive products, don't produce them locally
|
||||
produced_locally=False,
|
||||
recipe_id=None, # Recipes belong to central production, not retail
|
||||
created_at=BASE_REFERENCE_DATE,
|
||||
updated_at=BASE_REFERENCE_DATE
|
||||
)
|
||||
|
||||
db.add(product)
|
||||
created_count += 1
|
||||
|
||||
logger.debug(f" ✅ Created: {sku} - {name}")
|
||||
|
||||
# Commit all changes for this tenant
|
||||
await db.commit()
|
||||
|
||||
logger.info(f" 📊 Created: {created_count}, Skipped: {skipped_count}")
|
||||
logger.info("")
|
||||
|
||||
return {
|
||||
"tenant_id": str(tenant_id),
|
||||
"tenant_name": tenant_name,
|
||||
"created": created_count,
|
||||
"skipped": skipped_count,
|
||||
"total": len(products_data)
|
||||
}
|
||||
|
||||
|
||||
async def seed_retail_inventory(db: AsyncSession):
|
||||
"""
|
||||
Seed retail inventory for all child tenant templates
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
|
||||
Returns:
|
||||
Dict with overall seeding statistics
|
||||
"""
|
||||
logger.info("=" * 80)
|
||||
logger.info("🏪 Starting Demo Retail Inventory Seeding")
|
||||
logger.info("=" * 80)
|
||||
logger.info("NOTE: Seeding FINISHED PRODUCTS ONLY for child retail outlets")
|
||||
logger.info("Raw ingredients (flour, yeast, etc.) are NOT seeded for retail tenants")
|
||||
logger.info("")
|
||||
|
||||
# Load finished products data once
|
||||
try:
|
||||
products_data = load_finished_products_data()
|
||||
except FileNotFoundError as e:
|
||||
logger.error(str(e))
|
||||
raise
|
||||
|
||||
results = []
|
||||
|
||||
# Seed for each child retail outlet
|
||||
for child_tenant_id, child_tenant_name in CHILD_TENANTS:
|
||||
logger.info("")
|
||||
result = await seed_retail_inventory_for_tenant(
|
||||
db,
|
||||
child_tenant_id,
|
||||
DEMO_TENANT_ENTERPRISE_CHAIN,
|
||||
f"{child_tenant_name} (Retail Outlet)",
|
||||
products_data
|
||||
)
|
||||
results.append(result)
|
||||
|
||||
# Calculate totals
|
||||
total_created = sum(r["created"] for r in results)
|
||||
total_skipped = sum(r["skipped"] for r in results)
|
||||
|
||||
logger.info("=" * 80)
|
||||
logger.info("✅ Demo Retail Inventory Seeding Completed")
|
||||
logger.info("=" * 80)
|
||||
|
||||
return {
|
||||
"service": "inventory_retail",
|
||||
"tenants_seeded": len(results),
|
||||
"total_created": total_created,
|
||||
"total_skipped": total_skipped,
|
||||
"results": results
|
||||
}
|
||||
|
||||
|
||||
async def main():
|
||||
"""Main execution function"""
|
||||
|
||||
logger.info("Demo Retail Inventory Seeding Script Starting")
|
||||
logger.info("Mode: %s", os.getenv("DEMO_MODE", "development"))
|
||||
logger.info("Log Level: %s", os.getenv("LOG_LEVEL", "INFO"))
|
||||
|
||||
# Get database URL from environment
|
||||
database_url = os.getenv("INVENTORY_DATABASE_URL") or os.getenv("DATABASE_URL")
|
||||
if not database_url:
|
||||
logger.error("❌ INVENTORY_DATABASE_URL or DATABASE_URL environment variable must be set")
|
||||
return 1
|
||||
|
||||
# Convert to async URL if needed
|
||||
if database_url.startswith("postgresql://"):
|
||||
database_url = database_url.replace("postgresql://", "postgresql+asyncpg://", 1)
|
||||
|
||||
logger.info("Connecting to inventory database")
|
||||
|
||||
# Create engine and session
|
||||
engine = create_async_engine(
|
||||
database_url,
|
||||
echo=False,
|
||||
pool_pre_ping=True,
|
||||
pool_size=5,
|
||||
max_overflow=10
|
||||
)
|
||||
|
||||
async_session = sessionmaker(
|
||||
engine,
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False
|
||||
)
|
||||
|
||||
try:
|
||||
async with async_session() as session:
|
||||
result = await seed_retail_inventory(session)
|
||||
|
||||
logger.info("")
|
||||
logger.info("📊 Retail Inventory Seeding Summary:")
|
||||
logger.info(f" ✅ Retail outlets seeded: {result['tenants_seeded']}")
|
||||
logger.info(f" ✅ Total products created: {result['total_created']}")
|
||||
logger.info(f" ⏭️ Total skipped: {result['total_skipped']}")
|
||||
logger.info("")
|
||||
|
||||
# Print per-tenant details
|
||||
for tenant_result in result['results']:
|
||||
logger.info(
|
||||
f" {tenant_result['tenant_name']}: "
|
||||
f"{tenant_result['created']} products created, {tenant_result['skipped']} skipped"
|
||||
)
|
||||
|
||||
logger.info("")
|
||||
logger.info("🎉 Success! Retail inventory catalog is ready for cloning.")
|
||||
logger.info("")
|
||||
logger.info("Finished products seeded:")
|
||||
logger.info(" • Baguette Tradicional")
|
||||
logger.info(" • Croissant de Mantequilla")
|
||||
logger.info(" • Pan de Pueblo")
|
||||
logger.info(" • Napolitana de Chocolate")
|
||||
logger.info("")
|
||||
logger.info("Key points:")
|
||||
logger.info(" ✓ Only finished products seeded (no raw ingredients)")
|
||||
logger.info(" ✓ Product IDs use XOR transformation to match parent catalog")
|
||||
logger.info(" ✓ All products marked as produced_locally=False (received from parent)")
|
||||
logger.info(" ✓ Retail outlets will receive stock from central production via distribution")
|
||||
logger.info("")
|
||||
logger.info("Next steps:")
|
||||
logger.info(" 1. Seed retail stock levels (initial inventory)")
|
||||
logger.info(" 2. Seed retail sales history")
|
||||
logger.info(" 3. Seed customer data and orders")
|
||||
logger.info(" 4. Test enterprise demo session creation")
|
||||
logger.info("")
|
||||
|
||||
return 0
|
||||
|
||||
except Exception as e:
|
||||
logger.error("=" * 80)
|
||||
logger.error("❌ Demo Retail Inventory Seeding Failed")
|
||||
logger.error("=" * 80)
|
||||
logger.error("Error: %s", str(e))
|
||||
logger.error("", exc_info=True)
|
||||
return 1
|
||||
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
exit_code = asyncio.run(main())
|
||||
sys.exit(exit_code)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,394 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Demo Retail Stock Seeding Script for Inventory Service
|
||||
Creates realistic stock levels for finished products at child retail outlets
|
||||
|
||||
This script runs as a Kubernetes init job inside the inventory-service container.
|
||||
It populates child retail tenants with stock levels for FINISHED PRODUCTS ONLY.
|
||||
|
||||
Usage:
|
||||
python /app/scripts/demo/seed_demo_stock_retail.py
|
||||
|
||||
Environment Variables Required:
|
||||
INVENTORY_DATABASE_URL - PostgreSQL connection string for inventory database
|
||||
DEMO_MODE - Set to 'production' for production seeding
|
||||
LOG_LEVEL - Logging level (default: INFO)
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import uuid
|
||||
import sys
|
||||
import os
|
||||
import random
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from pathlib import Path
|
||||
from decimal import Decimal
|
||||
|
||||
# Add app to path
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
|
||||
# Add shared to path for demo utilities
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent.parent.parent))
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy import select
|
||||
import structlog
|
||||
|
||||
from shared.utils.demo_dates import BASE_REFERENCE_DATE
|
||||
|
||||
from app.models.inventory import Ingredient, Stock, ProductType
|
||||
|
||||
# Configure logging
|
||||
structlog.configure(
|
||||
processors=[
|
||||
structlog.stdlib.add_log_level,
|
||||
structlog.processors.TimeStamper(fmt="iso"),
|
||||
structlog.dev.ConsoleRenderer()
|
||||
]
|
||||
)
|
||||
|
||||
logger = structlog.get_logger()
|
||||
|
||||
# Fixed Demo Tenant IDs (must match tenant service)
|
||||
DEMO_TENANT_ENTERPRISE_CHAIN = uuid.UUID("c3d4e5f6-a7b8-49c0-d1e2-f3a4b5c6d7e8") # Enterprise parent (Obrador)
|
||||
DEMO_TENANT_CHILD_1 = uuid.UUID("d4e5f6a7-b8c9-40d1-e2f3-a4b5c6d7e8f9") # Madrid Centro
|
||||
DEMO_TENANT_CHILD_2 = uuid.UUID("e5f6a7b8-c9d0-41e2-f3a4-b5c6d7e8f9a0") # Barcelona Gràcia
|
||||
DEMO_TENANT_CHILD_3 = uuid.UUID("f6a7b8c9-d0e1-42f3-a4b5-c6d7e8f9a0b1") # Valencia Ruzafa
|
||||
|
||||
# Child tenant configurations
|
||||
CHILD_TENANTS = [
|
||||
(DEMO_TENANT_CHILD_1, "Madrid Centro", 1.2), # Larger store, 20% more stock
|
||||
(DEMO_TENANT_CHILD_2, "Barcelona Gràcia", 1.0), # Medium store, baseline stock
|
||||
(DEMO_TENANT_CHILD_3, "Valencia Ruzafa", 0.8) # Smaller store, 20% less stock
|
||||
]
|
||||
|
||||
# Retail stock configuration for finished products
|
||||
# Daily sales estimates (units per day) for each product type
|
||||
DAILY_SALES_BY_SKU = {
|
||||
"PRO-BAG-001": 80, # Baguette Tradicional - high volume
|
||||
"PRO-CRO-001": 50, # Croissant de Mantequilla - popular breakfast item
|
||||
"PRO-PUE-001": 30, # Pan de Pueblo - specialty item
|
||||
"PRO-NAP-001": 40 # Napolitana de Chocolate - pastry item
|
||||
}
|
||||
|
||||
# Storage locations for retail outlets
|
||||
RETAIL_STORAGE_LOCATIONS = ["Display Case", "Back Room", "Cooling Shelf", "Storage Area"]
|
||||
|
||||
|
||||
def generate_retail_batch_number(tenant_id: uuid.UUID, product_sku: str, days_ago: int) -> str:
|
||||
"""Generate a realistic batch number for retail stock"""
|
||||
tenant_short = str(tenant_id).split('-')[0].upper()[:4]
|
||||
date_code = (BASE_REFERENCE_DATE - timedelta(days=days_ago)).strftime("%Y%m%d")
|
||||
return f"RET-{tenant_short}-{product_sku}-{date_code}"
|
||||
|
||||
|
||||
def calculate_retail_stock_quantity(
|
||||
product_sku: str,
|
||||
size_multiplier: float,
|
||||
create_some_low_stock: bool = False
|
||||
) -> float:
|
||||
"""
|
||||
Calculate realistic retail stock quantity based on daily sales
|
||||
|
||||
Args:
|
||||
product_sku: SKU of the finished product
|
||||
size_multiplier: Store size multiplier (0.8 for small, 1.0 for medium, 1.2 for large)
|
||||
create_some_low_stock: If True, 20% chance of low stock scenario
|
||||
|
||||
Returns:
|
||||
Stock quantity in units
|
||||
"""
|
||||
daily_sales = DAILY_SALES_BY_SKU.get(product_sku, 20)
|
||||
|
||||
# Retail outlets typically stock 1-3 days worth (fresh bakery products)
|
||||
if create_some_low_stock and random.random() < 0.2:
|
||||
# Low stock: 0.3-0.8 days worth (need restock soon)
|
||||
days_of_supply = random.uniform(0.3, 0.8)
|
||||
else:
|
||||
# Normal: 1-2.5 days worth
|
||||
days_of_supply = random.uniform(1.0, 2.5)
|
||||
|
||||
quantity = daily_sales * days_of_supply * size_multiplier
|
||||
|
||||
# Add realistic variability
|
||||
quantity *= random.uniform(0.85, 1.15)
|
||||
|
||||
return max(5.0, round(quantity)) # Minimum 5 units
|
||||
|
||||
|
||||
async def seed_retail_stock_for_tenant(
|
||||
db: AsyncSession,
|
||||
tenant_id: uuid.UUID,
|
||||
tenant_name: str,
|
||||
size_multiplier: float
|
||||
) -> dict:
|
||||
"""
|
||||
Seed realistic stock levels for a child retail tenant
|
||||
|
||||
Creates multiple stock batches per product with varied freshness levels,
|
||||
simulating realistic retail bakery inventory with:
|
||||
- Fresh stock from today's/yesterday's delivery
|
||||
- Some expiring soon items
|
||||
- Varied batch sizes and locations
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
tenant_id: UUID of the child tenant
|
||||
tenant_name: Name of the tenant (for logging)
|
||||
size_multiplier: Store size multiplier for stock quantities
|
||||
|
||||
Returns:
|
||||
Dict with seeding statistics
|
||||
"""
|
||||
logger.info("─" * 80)
|
||||
logger.info(f"Seeding retail stock for: {tenant_name}")
|
||||
logger.info(f"Tenant ID: {tenant_id}")
|
||||
logger.info(f"Size Multiplier: {size_multiplier}x")
|
||||
logger.info("─" * 80)
|
||||
|
||||
# Get all finished products for this tenant
|
||||
result = await db.execute(
|
||||
select(Ingredient).where(
|
||||
Ingredient.tenant_id == tenant_id,
|
||||
Ingredient.product_type == ProductType.FINISHED_PRODUCT,
|
||||
Ingredient.is_active == True
|
||||
)
|
||||
)
|
||||
products = result.scalars().all()
|
||||
|
||||
if not products:
|
||||
logger.warning(f"No finished products found for tenant {tenant_id}")
|
||||
return {
|
||||
"tenant_id": str(tenant_id),
|
||||
"tenant_name": tenant_name,
|
||||
"stock_batches_created": 0,
|
||||
"products_stocked": 0
|
||||
}
|
||||
|
||||
created_batches = 0
|
||||
|
||||
for product in products:
|
||||
# Create 2-4 batches per product (simulating multiple deliveries/batches)
|
||||
num_batches = random.randint(2, 4)
|
||||
|
||||
for batch_index in range(num_batches):
|
||||
# Vary delivery dates (0-2 days ago for fresh bakery products)
|
||||
days_ago = random.randint(0, 2)
|
||||
received_date = BASE_REFERENCE_DATE - timedelta(days=days_ago)
|
||||
|
||||
# Calculate expiration based on shelf life
|
||||
shelf_life_days = product.shelf_life_days or 2 # Default 2 days for bakery
|
||||
expiration_date = received_date + timedelta(days=shelf_life_days)
|
||||
|
||||
# Calculate quantity for this batch
|
||||
# Split total quantity across batches with variation
|
||||
batch_quantity_factor = random.uniform(0.3, 0.7) # Each batch is 30-70% of average
|
||||
quantity = calculate_retail_stock_quantity(
|
||||
product.sku,
|
||||
size_multiplier,
|
||||
create_some_low_stock=(batch_index == 0) # First batch might be low
|
||||
) * batch_quantity_factor
|
||||
|
||||
# Determine if product is still good
|
||||
days_until_expiration = (expiration_date - BASE_REFERENCE_DATE).days
|
||||
is_expired = days_until_expiration < 0
|
||||
is_available = not is_expired
|
||||
quality_status = "expired" if is_expired else "good"
|
||||
|
||||
# Random storage location
|
||||
storage_location = random.choice(RETAIL_STORAGE_LOCATIONS)
|
||||
|
||||
# Create stock batch
|
||||
stock_batch = Stock(
|
||||
id=uuid.uuid4(),
|
||||
tenant_id=tenant_id,
|
||||
ingredient_id=product.id,
|
||||
supplier_id=DEMO_TENANT_ENTERPRISE_CHAIN, # Supplied by parent (Obrador)
|
||||
batch_number=generate_retail_batch_number(tenant_id, product.sku, days_ago),
|
||||
lot_number=f"LOT-{BASE_REFERENCE_DATE.strftime('%Y%m%d')}-{batch_index+1:02d}",
|
||||
supplier_batch_ref=f"OBRADOR-{received_date.strftime('%Y%m%d')}-{random.randint(1000, 9999)}",
|
||||
production_stage="fully_baked", # Retail receives fully baked products
|
||||
transformation_reference=None,
|
||||
current_quantity=quantity,
|
||||
reserved_quantity=0.0,
|
||||
available_quantity=quantity if is_available else 0.0,
|
||||
received_date=received_date,
|
||||
expiration_date=expiration_date,
|
||||
best_before_date=expiration_date - timedelta(hours=12) if shelf_life_days == 1 else None,
|
||||
original_expiration_date=None,
|
||||
transformation_date=None,
|
||||
final_expiration_date=expiration_date,
|
||||
unit_cost=Decimal(str(product.average_cost or 0.5)),
|
||||
total_cost=Decimal(str(product.average_cost or 0.5)) * Decimal(str(quantity)),
|
||||
storage_location=storage_location,
|
||||
warehouse_zone=None, # Retail outlets don't have warehouse zones
|
||||
shelf_position=None,
|
||||
requires_refrigeration=False, # Most bakery products don't require refrigeration
|
||||
requires_freezing=False,
|
||||
storage_temperature_min=None,
|
||||
storage_temperature_max=25.0 if product.is_perishable else None, # Room temp
|
||||
storage_humidity_max=65.0 if product.is_perishable else None,
|
||||
shelf_life_days=shelf_life_days,
|
||||
storage_instructions=product.storage_instructions if hasattr(product, 'storage_instructions') else None,
|
||||
is_available=is_available,
|
||||
is_expired=is_expired,
|
||||
quality_status=quality_status,
|
||||
created_at=received_date,
|
||||
updated_at=BASE_REFERENCE_DATE
|
||||
)
|
||||
|
||||
db.add(stock_batch)
|
||||
created_batches += 1
|
||||
|
||||
logger.debug(
|
||||
f" ✅ Created stock batch: {product.name} - "
|
||||
f"{quantity:.0f} units, expires in {days_until_expiration} days"
|
||||
)
|
||||
|
||||
# Commit all changes for this tenant
|
||||
await db.commit()
|
||||
|
||||
logger.info(f" 📊 Stock batches created: {created_batches} across {len(products)} products")
|
||||
logger.info("")
|
||||
|
||||
return {
|
||||
"tenant_id": str(tenant_id),
|
||||
"tenant_name": tenant_name,
|
||||
"stock_batches_created": created_batches,
|
||||
"products_stocked": len(products)
|
||||
}
|
||||
|
||||
|
||||
async def seed_retail_stock(db: AsyncSession):
|
||||
"""
|
||||
Seed retail stock for all child tenant templates
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
|
||||
Returns:
|
||||
Dict with overall seeding statistics
|
||||
"""
|
||||
logger.info("=" * 80)
|
||||
logger.info("📦 Starting Demo Retail Stock Seeding")
|
||||
logger.info("=" * 80)
|
||||
logger.info("Creating stock levels for finished products at retail outlets")
|
||||
logger.info("")
|
||||
|
||||
results = []
|
||||
|
||||
# Seed for each child retail outlet
|
||||
for child_tenant_id, child_tenant_name, size_multiplier in CHILD_TENANTS:
|
||||
logger.info("")
|
||||
result = await seed_retail_stock_for_tenant(
|
||||
db,
|
||||
child_tenant_id,
|
||||
f"{child_tenant_name} (Retail Outlet)",
|
||||
size_multiplier
|
||||
)
|
||||
results.append(result)
|
||||
|
||||
# Calculate totals
|
||||
total_batches = sum(r["stock_batches_created"] for r in results)
|
||||
total_products = sum(r["products_stocked"] for r in results)
|
||||
|
||||
logger.info("=" * 80)
|
||||
logger.info("✅ Demo Retail Stock Seeding Completed")
|
||||
logger.info("=" * 80)
|
||||
|
||||
return {
|
||||
"service": "inventory_stock_retail",
|
||||
"tenants_seeded": len(results),
|
||||
"total_batches_created": total_batches,
|
||||
"total_products_stocked": total_products,
|
||||
"results": results
|
||||
}
|
||||
|
||||
|
||||
async def main():
|
||||
"""Main execution function"""
|
||||
|
||||
logger.info("Demo Retail Stock Seeding Script Starting")
|
||||
logger.info("Mode: %s", os.getenv("DEMO_MODE", "development"))
|
||||
logger.info("Log Level: %s", os.getenv("LOG_LEVEL", "INFO"))
|
||||
|
||||
# Get database URL from environment
|
||||
database_url = os.getenv("INVENTORY_DATABASE_URL") or os.getenv("DATABASE_URL")
|
||||
if not database_url:
|
||||
logger.error("❌ INVENTORY_DATABASE_URL or DATABASE_URL environment variable must be set")
|
||||
return 1
|
||||
|
||||
# Convert to async URL if needed
|
||||
if database_url.startswith("postgresql://"):
|
||||
database_url = database_url.replace("postgresql://", "postgresql+asyncpg://", 1)
|
||||
|
||||
logger.info("Connecting to inventory database")
|
||||
|
||||
# Create engine and session
|
||||
engine = create_async_engine(
|
||||
database_url,
|
||||
echo=False,
|
||||
pool_pre_ping=True,
|
||||
pool_size=5,
|
||||
max_overflow=10
|
||||
)
|
||||
|
||||
async_session = sessionmaker(
|
||||
engine,
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False
|
||||
)
|
||||
|
||||
try:
|
||||
async with async_session() as session:
|
||||
result = await seed_retail_stock(session)
|
||||
|
||||
logger.info("")
|
||||
logger.info("📊 Retail Stock Seeding Summary:")
|
||||
logger.info(f" ✅ Retail outlets seeded: {result['tenants_seeded']}")
|
||||
logger.info(f" ✅ Total stock batches: {result['total_batches_created']}")
|
||||
logger.info(f" ✅ Products stocked: {result['total_products_stocked']}")
|
||||
logger.info("")
|
||||
|
||||
# Print per-tenant details
|
||||
for tenant_result in result['results']:
|
||||
logger.info(
|
||||
f" {tenant_result['tenant_name']}: "
|
||||
f"{tenant_result['stock_batches_created']} batches, "
|
||||
f"{tenant_result['products_stocked']} products"
|
||||
)
|
||||
|
||||
logger.info("")
|
||||
logger.info("🎉 Success! Retail stock levels are ready for cloning.")
|
||||
logger.info("")
|
||||
logger.info("Stock characteristics:")
|
||||
logger.info(" ✓ Multiple batches per product (2-4 batches)")
|
||||
logger.info(" ✓ Varied freshness levels (0-2 days old)")
|
||||
logger.info(" ✓ Realistic quantities based on store size")
|
||||
logger.info(" ✓ Some low-stock scenarios for demo alerts")
|
||||
logger.info(" ✓ Expiration tracking enabled")
|
||||
logger.info("")
|
||||
logger.info("Next steps:")
|
||||
logger.info(" 1. Seed retail sales history")
|
||||
logger.info(" 2. Seed customer data")
|
||||
logger.info(" 3. Test stock alerts and reorder triggers")
|
||||
logger.info("")
|
||||
|
||||
return 0
|
||||
|
||||
except Exception as e:
|
||||
logger.error("=" * 80)
|
||||
logger.error("❌ Demo Retail Stock Seeding Failed")
|
||||
logger.error("=" * 80)
|
||||
logger.error("Error: %s", str(e))
|
||||
logger.error("", exc_info=True)
|
||||
return 1
|
||||
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
exit_code = asyncio.run(main())
|
||||
sys.exit(exit_code)
|
||||
Reference in New Issue
Block a user