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,141 @@
"""Alembic environment configuration for orders 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
# Add the service directory to the Python path
service_path = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if service_path not in sys.path:
sys.path.insert(0, service_path)
# Add shared modules to path
shared_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "shared"))
if shared_path not in sys.path:
sys.path.insert(0, shared_path)
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,268 @@
"""initial_schema_20251015_1229
Revision ID: 7f882c2ca25c
Revises:
Create Date: 2025-10-15 12:29:27.201743+02:00
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision: str = '7f882c2ca25c'
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('audit_logs',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('tenant_id', sa.UUID(), nullable=False),
sa.Column('user_id', sa.UUID(), nullable=False),
sa.Column('action', sa.String(length=100), nullable=False),
sa.Column('resource_type', sa.String(length=100), nullable=False),
sa.Column('resource_id', sa.String(length=255), nullable=True),
sa.Column('severity', sa.String(length=20), nullable=False),
sa.Column('service_name', sa.String(length=100), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('changes', postgresql.JSON(astext_type=sa.Text()), nullable=True),
sa.Column('audit_metadata', postgresql.JSON(astext_type=sa.Text()), nullable=True),
sa.Column('ip_address', sa.String(length=45), nullable=True),
sa.Column('user_agent', sa.Text(), nullable=True),
sa.Column('endpoint', sa.String(length=255), nullable=True),
sa.Column('method', sa.String(length=10), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_index('idx_audit_resource_type_action', 'audit_logs', ['resource_type', 'action'], unique=False)
op.create_index('idx_audit_service_created', 'audit_logs', ['service_name', 'created_at'], unique=False)
op.create_index('idx_audit_severity_created', 'audit_logs', ['severity', 'created_at'], unique=False)
op.create_index('idx_audit_tenant_created', 'audit_logs', ['tenant_id', 'created_at'], unique=False)
op.create_index('idx_audit_user_created', 'audit_logs', ['user_id', 'created_at'], unique=False)
op.create_index(op.f('ix_audit_logs_action'), 'audit_logs', ['action'], unique=False)
op.create_index(op.f('ix_audit_logs_created_at'), 'audit_logs', ['created_at'], unique=False)
op.create_index(op.f('ix_audit_logs_resource_id'), 'audit_logs', ['resource_id'], unique=False)
op.create_index(op.f('ix_audit_logs_resource_type'), 'audit_logs', ['resource_type'], unique=False)
op.create_index(op.f('ix_audit_logs_service_name'), 'audit_logs', ['service_name'], unique=False)
op.create_index(op.f('ix_audit_logs_severity'), 'audit_logs', ['severity'], unique=False)
op.create_index(op.f('ix_audit_logs_tenant_id'), 'audit_logs', ['tenant_id'], unique=False)
op.create_index(op.f('ix_audit_logs_user_id'), 'audit_logs', ['user_id'], unique=False)
op.create_table('customers',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('tenant_id', sa.UUID(), nullable=False),
sa.Column('customer_code', sa.String(length=50), nullable=False),
sa.Column('name', sa.String(length=200), nullable=False),
sa.Column('business_name', sa.String(length=200), nullable=True),
sa.Column('customer_type', sa.String(length=50), nullable=False),
sa.Column('email', sa.String(length=255), nullable=True),
sa.Column('phone', sa.String(length=50), nullable=True),
sa.Column('address_line1', sa.String(length=255), nullable=True),
sa.Column('address_line2', sa.String(length=255), nullable=True),
sa.Column('city', sa.String(length=100), nullable=True),
sa.Column('state', sa.String(length=100), nullable=True),
sa.Column('postal_code', sa.String(length=20), nullable=True),
sa.Column('country', sa.String(length=100), nullable=False),
sa.Column('tax_id', sa.String(length=50), nullable=True),
sa.Column('business_license', sa.String(length=100), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=False),
sa.Column('preferred_delivery_method', sa.String(length=50), nullable=False),
sa.Column('payment_terms', sa.String(length=50), nullable=False),
sa.Column('credit_limit', sa.Numeric(precision=10, scale=2), nullable=True),
sa.Column('discount_percentage', sa.Numeric(precision=5, scale=2), nullable=False),
sa.Column('customer_segment', sa.String(length=50), nullable=False),
sa.Column('priority_level', sa.String(length=20), nullable=False),
sa.Column('special_instructions', sa.Text(), nullable=True),
sa.Column('delivery_preferences', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column('product_preferences', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column('total_orders', sa.Integer(), nullable=False),
sa.Column('total_spent', sa.Numeric(precision=12, scale=2), nullable=False),
sa.Column('average_order_value', sa.Numeric(precision=10, scale=2), nullable=False),
sa.Column('last_order_date', sa.DateTime(timezone=True), 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', sa.UUID(), nullable=True),
sa.Column('updated_by', sa.UUID(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_customers_customer_code'), 'customers', ['customer_code'], unique=False)
op.create_index(op.f('ix_customers_tenant_id'), 'customers', ['tenant_id'], unique=False)
op.create_table('customer_contacts',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('customer_id', sa.UUID(), nullable=False),
sa.Column('name', sa.String(length=200), nullable=False),
sa.Column('title', sa.String(length=100), nullable=True),
sa.Column('department', sa.String(length=100), nullable=True),
sa.Column('email', sa.String(length=255), nullable=True),
sa.Column('phone', sa.String(length=50), nullable=True),
sa.Column('mobile', sa.String(length=50), nullable=True),
sa.Column('is_primary', sa.Boolean(), nullable=False),
sa.Column('contact_for_orders', sa.Boolean(), nullable=False),
sa.Column('contact_for_delivery', sa.Boolean(), nullable=False),
sa.Column('contact_for_billing', sa.Boolean(), nullable=False),
sa.Column('contact_for_support', sa.Boolean(), nullable=False),
sa.Column('preferred_contact_method', sa.String(length=50), nullable=False),
sa.Column('contact_time_preferences', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column('notes', sa.Text(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=False),
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.ForeignKeyConstraint(['customer_id'], ['customers.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
op.create_table('customer_orders',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('tenant_id', sa.UUID(), nullable=False),
sa.Column('order_number', sa.String(length=50), nullable=False),
sa.Column('customer_id', sa.UUID(), nullable=False),
sa.Column('status', sa.String(length=50), nullable=False),
sa.Column('order_type', sa.String(length=50), nullable=False),
sa.Column('priority', sa.String(length=20), nullable=False),
sa.Column('order_date', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('requested_delivery_date', sa.DateTime(timezone=True), nullable=False),
sa.Column('confirmed_delivery_date', sa.DateTime(timezone=True), nullable=True),
sa.Column('actual_delivery_date', sa.DateTime(timezone=True), nullable=True),
sa.Column('delivery_method', sa.String(length=50), nullable=False),
sa.Column('delivery_address', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column('delivery_instructions', sa.Text(), nullable=True),
sa.Column('delivery_window_start', sa.DateTime(timezone=True), nullable=True),
sa.Column('delivery_window_end', sa.DateTime(timezone=True), nullable=True),
sa.Column('subtotal', sa.Numeric(precision=10, scale=2), nullable=False),
sa.Column('discount_amount', sa.Numeric(precision=10, scale=2), nullable=False),
sa.Column('discount_percentage', sa.Numeric(precision=5, scale=2), nullable=False),
sa.Column('tax_amount', sa.Numeric(precision=10, scale=2), nullable=False),
sa.Column('delivery_fee', sa.Numeric(precision=10, scale=2), nullable=False),
sa.Column('total_amount', sa.Numeric(precision=10, scale=2), nullable=False),
sa.Column('payment_status', sa.String(length=50), nullable=False),
sa.Column('payment_method', sa.String(length=50), nullable=True),
sa.Column('payment_terms', sa.String(length=50), nullable=False),
sa.Column('payment_due_date', sa.DateTime(timezone=True), nullable=True),
sa.Column('special_instructions', sa.Text(), nullable=True),
sa.Column('custom_requirements', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column('allergen_warnings', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column('business_model', sa.String(length=50), nullable=True),
sa.Column('estimated_business_model', sa.String(length=50), nullable=True),
sa.Column('order_source', sa.String(length=50), nullable=False),
sa.Column('sales_channel', sa.String(length=50), nullable=False),
sa.Column('order_origin', sa.String(length=100), nullable=True),
sa.Column('production_batch_id', sa.UUID(), nullable=True),
sa.Column('fulfillment_location', sa.String(length=100), nullable=True),
sa.Column('estimated_preparation_time', sa.Integer(), nullable=True),
sa.Column('actual_preparation_time', sa.Integer(), nullable=True),
sa.Column('customer_notified_confirmed', sa.Boolean(), nullable=False),
sa.Column('customer_notified_ready', sa.Boolean(), nullable=False),
sa.Column('customer_notified_delivered', sa.Boolean(), nullable=False),
sa.Column('communication_preferences', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column('quality_score', sa.Numeric(precision=3, scale=1), nullable=True),
sa.Column('customer_rating', sa.Integer(), nullable=True),
sa.Column('customer_feedback', sa.Text(), nullable=True),
sa.Column('cancellation_reason', sa.String(length=200), nullable=True),
sa.Column('cancelled_at', sa.DateTime(timezone=True), nullable=True),
sa.Column('cancelled_by', sa.UUID(), nullable=True),
sa.Column('refund_amount', sa.Numeric(precision=10, scale=2), nullable=False),
sa.Column('refund_processed_at', sa.DateTime(timezone=True), 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', sa.UUID(), nullable=True),
sa.Column('updated_by', sa.UUID(), nullable=True),
sa.Column('order_metadata', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.ForeignKeyConstraint(['customer_id'], ['customers.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_customer_orders_customer_id'), 'customer_orders', ['customer_id'], unique=False)
op.create_index(op.f('ix_customer_orders_order_number'), 'customer_orders', ['order_number'], unique=True)
op.create_index(op.f('ix_customer_orders_status'), 'customer_orders', ['status'], unique=False)
op.create_index(op.f('ix_customer_orders_tenant_id'), 'customer_orders', ['tenant_id'], unique=False)
op.create_table('order_items',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('order_id', sa.UUID(), nullable=False),
sa.Column('product_id', sa.UUID(), nullable=False),
sa.Column('product_name', sa.String(length=200), nullable=False),
sa.Column('product_sku', sa.String(length=100), nullable=True),
sa.Column('product_category', sa.String(length=100), nullable=True),
sa.Column('quantity', sa.Numeric(precision=10, scale=3), nullable=False),
sa.Column('unit_of_measure', sa.String(length=50), nullable=False),
sa.Column('weight', sa.Numeric(precision=10, scale=3), nullable=True),
sa.Column('unit_price', sa.Numeric(precision=10, scale=2), nullable=False),
sa.Column('line_discount', sa.Numeric(precision=10, scale=2), nullable=False),
sa.Column('line_total', sa.Numeric(precision=10, scale=2), nullable=False),
sa.Column('product_specifications', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column('customization_details', sa.Text(), nullable=True),
sa.Column('special_instructions', sa.Text(), nullable=True),
sa.Column('recipe_id', sa.UUID(), nullable=True),
sa.Column('production_requirements', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column('estimated_production_time', sa.Integer(), nullable=True),
sa.Column('status', sa.String(length=50), nullable=False),
sa.Column('production_started_at', sa.DateTime(timezone=True), nullable=True),
sa.Column('production_completed_at', sa.DateTime(timezone=True), nullable=True),
sa.Column('quality_checked', sa.Boolean(), nullable=False),
sa.Column('quality_score', sa.Numeric(precision=3, scale=1), nullable=True),
sa.Column('ingredient_cost', sa.Numeric(precision=10, scale=2), nullable=True),
sa.Column('labor_cost', sa.Numeric(precision=10, scale=2), nullable=True),
sa.Column('overhead_cost', sa.Numeric(precision=10, scale=2), nullable=True),
sa.Column('total_cost', sa.Numeric(precision=10, scale=2), nullable=True),
sa.Column('margin', sa.Numeric(precision=10, scale=2), nullable=True),
sa.Column('reserved_inventory', sa.Boolean(), nullable=False),
sa.Column('inventory_allocated_at', sa.DateTime(timezone=True), 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('customer_metadata', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.ForeignKeyConstraint(['order_id'], ['customer_orders.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_order_items_product_id'), 'order_items', ['product_id'], unique=False)
op.create_table('order_status_history',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('order_id', sa.UUID(), nullable=False),
sa.Column('from_status', sa.String(length=50), nullable=True),
sa.Column('to_status', sa.String(length=50), nullable=False),
sa.Column('change_reason', sa.String(length=200), nullable=True),
sa.Column('event_type', sa.String(length=50), nullable=False),
sa.Column('event_description', sa.Text(), nullable=True),
sa.Column('event_data', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column('changed_by', sa.UUID(), nullable=True),
sa.Column('change_source', sa.String(length=50), nullable=False),
sa.Column('changed_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('customer_notified', sa.Boolean(), nullable=False),
sa.Column('notification_method', sa.String(length=50), nullable=True),
sa.Column('notification_sent_at', sa.DateTime(timezone=True), nullable=True),
sa.Column('notes', sa.Text(), nullable=True),
sa.ForeignKeyConstraint(['order_id'], ['customer_orders.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('order_status_history')
op.drop_index(op.f('ix_order_items_product_id'), table_name='order_items')
op.drop_table('order_items')
op.drop_index(op.f('ix_customer_orders_tenant_id'), table_name='customer_orders')
op.drop_index(op.f('ix_customer_orders_status'), table_name='customer_orders')
op.drop_index(op.f('ix_customer_orders_order_number'), table_name='customer_orders')
op.drop_index(op.f('ix_customer_orders_customer_id'), table_name='customer_orders')
op.drop_table('customer_orders')
op.drop_table('customer_contacts')
op.drop_index(op.f('ix_customers_tenant_id'), table_name='customers')
op.drop_index(op.f('ix_customers_customer_code'), table_name='customers')
op.drop_table('customers')
op.drop_index(op.f('ix_audit_logs_user_id'), table_name='audit_logs')
op.drop_index(op.f('ix_audit_logs_tenant_id'), table_name='audit_logs')
op.drop_index(op.f('ix_audit_logs_severity'), table_name='audit_logs')
op.drop_index(op.f('ix_audit_logs_service_name'), table_name='audit_logs')
op.drop_index(op.f('ix_audit_logs_resource_type'), table_name='audit_logs')
op.drop_index(op.f('ix_audit_logs_resource_id'), table_name='audit_logs')
op.drop_index(op.f('ix_audit_logs_created_at'), table_name='audit_logs')
op.drop_index(op.f('ix_audit_logs_action'), table_name='audit_logs')
op.drop_index('idx_audit_user_created', table_name='audit_logs')
op.drop_index('idx_audit_tenant_created', table_name='audit_logs')
op.drop_index('idx_audit_severity_created', table_name='audit_logs')
op.drop_index('idx_audit_service_created', table_name='audit_logs')
op.drop_index('idx_audit_resource_type_action', table_name='audit_logs')
op.drop_table('audit_logs')
# ### end Alembic commands ###