#!/usr/bin/env python3 """ Seed script to update CostCategory visibility and accounting_code values. Also drops the old 'cost_category' column from asset_costs table. Usage: docker compose exec sf_api python3 /app/backend/scripts/seed_cost_category_visibility.py """ import asyncio import logging from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession from sqlalchemy.orm import sessionmaker from sqlalchemy import text from app.core.config import settings logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Visibility rules: # - FUEL, MAINTENANCE, SERVICE, TIRE, INSURANCE, PARKING, TOLL, OTHER -> 'both' # - FINANCE, ADMIN -> 'b2b' VISIBILITY_MAP = { "FUEL": "both", "MAINTENANCE": "both", "SERVICE": "both", "TIRE": "both", "INSURANCE": "both", "PARKING": "both", "TOLL": "both", "OTHER": "both", "FINANCE": "b2b", "ADMIN": "b2b", } async def main(): engine = create_async_engine(str(settings.SQLALCHEMY_DATABASE_URI)) async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) async with async_session() as session: # 1. Update visibility for existing categories logger.info("🔄 Updating visibility for existing cost categories...") for code, visibility in VISIBILITY_MAP.items(): result = await session.execute( text(""" UPDATE vehicle.cost_categories SET visibility = :visibility WHERE code = :code AND (visibility IS NULL OR visibility = 'both') """), {"code": code, "visibility": visibility} ) if result.rowcount > 0: logger.info(f" ✅ {code} -> {visibility}") # 2. Set default visibility for any categories without it result = await session.execute( text(""" UPDATE vehicle.cost_categories SET visibility = 'both' WHERE visibility IS NULL """) ) if result.rowcount > 0: logger.info(f" ✅ Set default 'both' for {result.rowcount} categories") # 3. Drop the old cost_category column from asset_costs logger.info("🔄 Dropping old 'cost_category' column from asset_costs...") # Check if the column still exists check = await session.execute( text(""" SELECT column_name FROM information_schema.columns WHERE table_schema = 'vehicle' AND table_name = 'asset_costs' AND column_name = 'cost_category' """) ) if check.scalar(): await session.execute( text("ALTER TABLE vehicle.asset_costs DROP COLUMN cost_category") ) logger.info(" ✅ Dropped old 'cost_category' column from vehicle.asset_costs") else: logger.info(" ⏭️ Column 'cost_category' already removed") await session.commit() logger.info("✅ All updates completed successfully!") await engine.dispose() if __name__ == "__main__": asyncio.run(main())