395 lines
14 KiB
Python
395 lines
14 KiB
Python
#!/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)
|