Initial commit - production deployment

This commit is contained in:
2026-01-21 17:17:16 +01:00
commit c23d00dd92
2289 changed files with 638440 additions and 0 deletions

View File

@@ -0,0 +1,149 @@
"""Alembic environment configuration for procurement service"""
import asyncio
import os
import sys
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config
from alembic import context
# Determine the project root (where the shared directory is located)
current_file_dir = os.path.dirname(os.path.abspath(__file__)) # migrations directory
service_dir = os.path.dirname(current_file_dir) # procurement service directory
project_root = os.path.dirname(os.path.dirname(service_dir)) # project root
# Add project root to Python path first
if project_root not in sys.path:
sys.path.insert(0, project_root)
# Add shared directory to Python path
shared_path = os.path.join(project_root, "shared")
if shared_path not in sys.path:
sys.path.insert(0, shared_path)
# Add service directory to Python path
if service_dir not in sys.path:
sys.path.insert(0, service_dir)
try:
from app.core.config import settings
from shared.database.base import Base
# Import all models to ensure they are registered with Base.metadata
from app.models import * # noqa: F401, F403
except ImportError as e:
print(f"Import error in migrations env.py: {e}")
print(f"Current Python path: {sys.path}")
raise
# this is the Alembic Config object
config = context.config
# Determine service name from file path
service_name = os.path.basename(os.path.dirname(os.path.dirname(__file__)))
service_name_upper = service_name.upper().replace('-', '_')
# Set database URL from environment variables with multiple fallback strategies
database_url = (
os.getenv(f'{service_name_upper}_DATABASE_URL') or # Service-specific
os.getenv('DATABASE_URL') # Generic fallback
)
# If DATABASE_URL is not set, construct from individual components
if not database_url:
# Try generic PostgreSQL environment variables first
postgres_host = os.getenv('POSTGRES_HOST')
postgres_port = os.getenv('POSTGRES_PORT', '5432')
postgres_db = os.getenv('POSTGRES_DB')
postgres_user = os.getenv('POSTGRES_USER')
postgres_password = os.getenv('POSTGRES_PASSWORD')
if all([postgres_host, postgres_db, postgres_user, postgres_password]):
database_url = f"postgresql+asyncpg://{postgres_user}:{postgres_password}@{postgres_host}:{postgres_port}/{postgres_db}"
else:
# Try service-specific environment variables
db_host = os.getenv(f'{service_name_upper}_DB_HOST', f'{service_name}-db-service')
db_port = os.getenv(f'{service_name_upper}_DB_PORT', '5432')
db_name = os.getenv(f'{service_name_upper}_DB_NAME', f'{service_name.replace("-", "_")}_db')
db_user = os.getenv(f'{service_name_upper}_DB_USER', f'{service_name.replace("-", "_")}_user')
db_password = os.getenv(f'{service_name_upper}_DB_PASSWORD')
if db_password:
database_url = f"postgresql+asyncpg://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}"
else:
# Final fallback: try to get from settings object
try:
database_url = getattr(settings, 'DATABASE_URL', None)
except Exception:
pass
if not database_url:
error_msg = f"ERROR: No database URL configured for {service_name} service"
print(error_msg)
raise Exception(error_msg)
config.set_main_option("sqlalchemy.url", database_url)
# Interpret the config file for Python logging
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# Set target metadata
target_metadata = Base.metadata
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode."""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
compare_type=True,
compare_server_default=True,
)
with context.begin_transaction():
context.run_migrations()
def do_run_migrations(connection: Connection) -> None:
"""Execute migrations with the given connection."""
context.configure(
connection=connection,
target_metadata=target_metadata,
compare_type=True,
compare_server_default=True,
)
with context.begin_transaction():
context.run_migrations()
async def run_async_migrations() -> None:
"""Run migrations in 'online' mode with async support."""
connectable = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode."""
asyncio.run(run_async_migrations())
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

View File

@@ -0,0 +1,26 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}

View File

@@ -0,0 +1,182 @@
"""
Initial schema for Distribution Service
Revision ID: 001
Revises:
Create Date: 2024-12-01 13:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '001'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# Create enum types
op.execute("CREATE TYPE deliveryroutestatus AS ENUM ('planned', 'in_progress', 'completed', 'cancelled')")
op.execute("CREATE TYPE shipmentstatus AS ENUM ('pending', 'packed', 'in_transit', 'delivered', 'failed')")
op.execute("CREATE TYPE deliveryschedulefrequency AS ENUM ('daily', 'weekly', 'biweekly', 'monthly')")
# Create delivery_routes table
op.create_table('delivery_routes',
sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('route_number', sa.String(length=50), nullable=False),
sa.Column('route_date', sa.DateTime(timezone=True), nullable=False),
sa.Column('vehicle_id', sa.String(length=100), nullable=True),
sa.Column('driver_id', postgresql.UUID(as_uuid=True), nullable=True),
sa.Column('total_distance_km', sa.Float(), nullable=True),
sa.Column('estimated_duration_minutes', sa.Integer(), nullable=True),
sa.Column('route_sequence', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column('notes', sa.Text(), nullable=True),
sa.Column('status', postgresql.ENUM('planned', 'in_progress', 'completed', 'cancelled', name='deliveryroutestatus', create_type=False), nullable=False, server_default='planned'),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('created_by', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('updated_by', postgresql.UUID(as_uuid=True), nullable=False),
# VRP Optimization Metrics
sa.Column('vrp_optimization_savings', sa.JSON(), nullable=True),
sa.Column('vrp_algorithm_version', sa.String(length=50), nullable=True),
sa.Column('vrp_optimization_timestamp', sa.DateTime(timezone=True), nullable=True),
sa.Column('vrp_constraints_satisfied', sa.Boolean(), nullable=True),
sa.Column('vrp_objective_value', sa.Float(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('route_number')
)
# Create indexes for delivery_routes
op.create_index('ix_delivery_routes_tenant_id', 'delivery_routes', ['tenant_id'])
op.create_index('ix_delivery_routes_route_date', 'delivery_routes', ['route_date'])
op.create_index('ix_delivery_routes_route_number', 'delivery_routes', ['route_number'])
op.create_index('ix_delivery_routes_status', 'delivery_routes', ['status'])
op.create_index('ix_delivery_routes_driver_id', 'delivery_routes', ['driver_id'])
op.create_index('ix_delivery_routes_tenant_date', 'delivery_routes', ['tenant_id', 'route_date'])
op.create_index('ix_delivery_routes_date_tenant_status', 'delivery_routes', ['route_date', 'tenant_id', 'status'])
# VRP Optimization Index
op.create_index('ix_delivery_routes_vrp_optimization', 'delivery_routes', ['vrp_optimization_timestamp'], unique=False)
# Create shipments table
op.create_table('shipments',
sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('parent_tenant_id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('child_tenant_id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('purchase_order_id', postgresql.UUID(as_uuid=True), nullable=True),
sa.Column('delivery_route_id', postgresql.UUID(as_uuid=True), nullable=True),
sa.Column('shipment_number', sa.String(length=50), nullable=False),
sa.Column('shipment_date', sa.DateTime(timezone=True), nullable=False),
sa.Column('current_location_lat', sa.Float(), nullable=True),
sa.Column('current_location_lng', sa.Float(), nullable=True),
sa.Column('last_tracked_at', sa.DateTime(timezone=True), nullable=True),
sa.Column('status', postgresql.ENUM('pending', 'packed', 'in_transit', 'delivered', 'failed', name='shipmentstatus', create_type=False), nullable=False, server_default='pending'),
sa.Column('actual_delivery_time', sa.DateTime(timezone=True), nullable=True),
sa.Column('signature', sa.Text(), nullable=True),
sa.Column('photo_url', sa.String(length=500), nullable=True),
sa.Column('received_by_name', sa.String(length=200), nullable=True),
sa.Column('delivery_notes', sa.Text(), nullable=True),
sa.Column('total_weight_kg', sa.Float(), nullable=True),
sa.Column('total_volume_m3', sa.Float(), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('created_by', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('updated_by', postgresql.UUID(as_uuid=True), nullable=False),
sa.ForeignKeyConstraint(['delivery_route_id'], ['delivery_routes.id'], ondelete='SET NULL'),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('shipment_number')
)
# Create indexes for shipments
op.create_index('ix_shipments_tenant_id', 'shipments', ['tenant_id'])
op.create_index('ix_shipments_parent_tenant_id', 'shipments', ['parent_tenant_id'])
op.create_index('ix_shipments_child_tenant_id', 'shipments', ['child_tenant_id'])
op.create_index('ix_shipments_purchase_order_id', 'shipments', ['purchase_order_id'])
op.create_index('ix_shipments_delivery_route_id', 'shipments', ['delivery_route_id'])
op.create_index('ix_shipments_shipment_number', 'shipments', ['shipment_number'])
op.create_index('ix_shipments_shipment_date', 'shipments', ['shipment_date'])
op.create_index('ix_shipments_status', 'shipments', ['status'])
op.create_index('ix_shipments_tenant_status', 'shipments', ['tenant_id', 'status'])
op.create_index('ix_shipments_parent_child', 'shipments', ['parent_tenant_id', 'child_tenant_id'])
op.create_index('ix_shipments_date_tenant', 'shipments', ['shipment_date', 'tenant_id'])
# Create delivery_schedules table
op.create_table('delivery_schedules',
sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('name', sa.String(length=200), nullable=False),
sa.Column('delivery_days', sa.String(length=200), nullable=False),
sa.Column('delivery_time', sa.String(length=20), nullable=False),
sa.Column('frequency', postgresql.ENUM('daily', 'weekly', 'biweekly', 'monthly', name='deliveryschedulefrequency', create_type=False), nullable=False, server_default='weekly'),
sa.Column('auto_generate_orders', sa.Boolean(), nullable=False, server_default='false'),
sa.Column('lead_time_days', sa.Integer(), nullable=False, server_default='1'),
sa.Column('target_parent_tenant_id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('target_child_tenant_ids', postgresql.JSONB(astext_type=sa.Text()), nullable=False),
sa.Column('is_active', sa.Boolean(), nullable=False, server_default='true'),
sa.Column('notes', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('created_by', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('updated_by', postgresql.UUID(as_uuid=True), nullable=False),
sa.PrimaryKeyConstraint('id')
)
# Create indexes for delivery_schedules
op.create_index('ix_delivery_schedules_tenant_id', 'delivery_schedules', ['tenant_id'])
op.create_index('ix_delivery_schedules_target_parent_tenant_id', 'delivery_schedules', ['target_parent_tenant_id'])
op.create_index('ix_delivery_schedules_is_active', 'delivery_schedules', ['is_active'])
op.create_index('ix_delivery_schedules_tenant_active', 'delivery_schedules', ['tenant_id', 'is_active'])
op.create_index('ix_delivery_schedules_parent_tenant', 'delivery_schedules', ['target_parent_tenant_id'])
def downgrade():
# Drop indexes for delivery_schedules
op.drop_index('ix_delivery_schedules_parent_tenant', table_name='delivery_schedules')
op.drop_index('ix_delivery_schedules_tenant_active', table_name='delivery_schedules')
op.drop_index('ix_delivery_schedules_is_active', table_name='delivery_schedules')
op.drop_index('ix_delivery_schedules_target_parent_tenant_id', table_name='delivery_schedules')
op.drop_index('ix_delivery_schedules_tenant_id', table_name='delivery_schedules')
# Drop delivery_schedules table
op.drop_table('delivery_schedules')
# Drop indexes for shipments
op.drop_index('ix_shipments_date_tenant', table_name='shipments')
op.drop_index('ix_shipments_parent_child', table_name='shipments')
op.drop_index('ix_shipments_tenant_status', table_name='shipments')
op.drop_index('ix_shipments_status', table_name='shipments')
op.drop_index('ix_shipments_shipment_date', table_name='shipments')
op.drop_index('ix_shipments_shipment_number', table_name='shipments')
op.drop_index('ix_shipments_delivery_route_id', table_name='shipments')
op.drop_index('ix_shipments_purchase_order_id', table_name='shipments')
op.drop_index('ix_shipments_child_tenant_id', table_name='shipments')
op.drop_index('ix_shipments_parent_tenant_id', table_name='shipments')
op.drop_index('ix_shipments_tenant_id', table_name='shipments')
# Drop shipments table
op.drop_table('shipments')
# Drop indexes for delivery_routes
op.drop_index('ix_delivery_routes_vrp_optimization', table_name='delivery_routes')
op.drop_index('ix_delivery_routes_date_tenant_status', table_name='delivery_routes')
op.drop_index('ix_delivery_routes_tenant_date', table_name='delivery_routes')
op.drop_index('ix_delivery_routes_driver_id', table_name='delivery_routes')
op.drop_index('ix_delivery_routes_status', table_name='delivery_routes')
op.drop_index('ix_delivery_routes_route_number', table_name='delivery_routes')
op.drop_index('ix_delivery_routes_route_date', table_name='delivery_routes')
op.drop_index('ix_delivery_routes_tenant_id', table_name='delivery_routes')
# Drop delivery_routes table
op.drop_table('delivery_routes')
# Drop enum types
op.execute("DROP TYPE IF EXISTS deliveryschedulefrequency")
op.execute("DROP TYPE IF EXISTS shipmentstatus")
op.execute("DROP TYPE IF EXISTS deliveryroutestatus")