Initial commit - production deployment
This commit is contained in:
141
services/notification/migrations/env.py
Normal file
141
services/notification/migrations/env.py
Normal file
@@ -0,0 +1,141 @@
|
||||
"""Alembic environment configuration for notification 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()
|
||||
26
services/notification/migrations/script.py.mako
Normal file
26
services/notification/migrations/script.py.mako
Normal 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"}
|
||||
@@ -0,0 +1,230 @@
|
||||
"""initial_schema_20251015_1230
|
||||
|
||||
Revision ID: 359991e24ea2
|
||||
Revises:
|
||||
Create Date: 2025-10-15 12:30:17.568404+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 = '359991e24ea2'
|
||||
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('email_templates',
|
||||
sa.Column('id', sa.UUID(), nullable=False),
|
||||
sa.Column('tenant_id', sa.UUID(), nullable=True),
|
||||
sa.Column('template_key', sa.String(length=100), nullable=False),
|
||||
sa.Column('name', sa.String(length=255), nullable=False),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('subject', sa.String(length=255), nullable=False),
|
||||
sa.Column('html_body', sa.Text(), nullable=False),
|
||||
sa.Column('text_body', sa.Text(), nullable=True),
|
||||
sa.Column('from_email', sa.String(length=255), nullable=True),
|
||||
sa.Column('from_name', sa.String(length=255), nullable=True),
|
||||
sa.Column('reply_to', sa.String(length=255), nullable=True),
|
||||
sa.Column('variables', sa.JSON(), nullable=True),
|
||||
sa.Column('sample_data', sa.JSON(), nullable=True),
|
||||
sa.Column('language', sa.String(length=2), nullable=True),
|
||||
sa.Column('is_active', sa.Boolean(), nullable=True),
|
||||
sa.Column('is_system', sa.Boolean(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('template_key')
|
||||
)
|
||||
op.create_index(op.f('ix_email_templates_tenant_id'), 'email_templates', ['tenant_id'], unique=False)
|
||||
op.create_table('notification_logs',
|
||||
sa.Column('id', sa.UUID(), nullable=False),
|
||||
sa.Column('notification_id', sa.UUID(), nullable=False),
|
||||
sa.Column('attempt_number', sa.Integer(), nullable=False),
|
||||
sa.Column('status', sa.Enum('PENDING', 'SENT', 'DELIVERED', 'FAILED', 'CANCELLED', name='notificationstatus'), nullable=False),
|
||||
sa.Column('provider', sa.String(length=50), nullable=True),
|
||||
sa.Column('provider_message_id', sa.String(length=255), nullable=True),
|
||||
sa.Column('provider_response', sa.JSON(), nullable=True),
|
||||
sa.Column('attempted_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('response_time_ms', sa.Integer(), nullable=True),
|
||||
sa.Column('error_code', sa.String(length=50), nullable=True),
|
||||
sa.Column('error_message', sa.Text(), nullable=True),
|
||||
sa.Column('log_metadata', sa.JSON(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_notification_logs_notification_id'), 'notification_logs', ['notification_id'], unique=False)
|
||||
op.create_table('notification_preferences',
|
||||
sa.Column('id', sa.UUID(), nullable=False),
|
||||
sa.Column('user_id', sa.UUID(), nullable=False),
|
||||
sa.Column('tenant_id', sa.UUID(), nullable=False),
|
||||
sa.Column('email_enabled', sa.Boolean(), nullable=True),
|
||||
sa.Column('email_alerts', sa.Boolean(), nullable=True),
|
||||
sa.Column('email_marketing', sa.Boolean(), nullable=True),
|
||||
sa.Column('email_reports', sa.Boolean(), nullable=True),
|
||||
sa.Column('whatsapp_enabled', sa.Boolean(), nullable=True),
|
||||
sa.Column('whatsapp_alerts', sa.Boolean(), nullable=True),
|
||||
sa.Column('whatsapp_reports', sa.Boolean(), nullable=True),
|
||||
sa.Column('push_enabled', sa.Boolean(), nullable=True),
|
||||
sa.Column('push_alerts', sa.Boolean(), nullable=True),
|
||||
sa.Column('push_reports', sa.Boolean(), nullable=True),
|
||||
sa.Column('quiet_hours_start', sa.String(length=5), nullable=True),
|
||||
sa.Column('quiet_hours_end', sa.String(length=5), nullable=True),
|
||||
sa.Column('timezone', sa.String(length=50), nullable=True),
|
||||
sa.Column('digest_frequency', sa.String(length=20), nullable=True),
|
||||
sa.Column('max_emails_per_day', sa.Integer(), nullable=True),
|
||||
sa.Column('language', sa.String(length=2), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_notification_preferences_tenant_id'), 'notification_preferences', ['tenant_id'], unique=False)
|
||||
op.create_index(op.f('ix_notification_preferences_user_id'), 'notification_preferences', ['user_id'], unique=True)
|
||||
op.create_table('notification_templates',
|
||||
sa.Column('id', sa.UUID(), nullable=False),
|
||||
sa.Column('tenant_id', sa.UUID(), nullable=True),
|
||||
sa.Column('template_key', sa.String(length=100), nullable=False),
|
||||
sa.Column('name', sa.String(length=255), nullable=False),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('category', sa.String(length=50), nullable=False),
|
||||
sa.Column('type', sa.Enum('EMAIL', 'WHATSAPP', 'PUSH', 'SMS', name='notificationtype'), nullable=False),
|
||||
sa.Column('subject_template', sa.String(length=255), nullable=True),
|
||||
sa.Column('body_template', sa.Text(), nullable=False),
|
||||
sa.Column('html_template', sa.Text(), nullable=True),
|
||||
sa.Column('language', sa.String(length=2), nullable=True),
|
||||
sa.Column('is_active', sa.Boolean(), nullable=True),
|
||||
sa.Column('is_system', sa.Boolean(), nullable=True),
|
||||
sa.Column('default_priority', sa.Enum('LOW', 'NORMAL', 'HIGH', 'URGENT', name='notificationpriority'), nullable=True),
|
||||
sa.Column('required_variables', sa.JSON(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('template_key')
|
||||
)
|
||||
op.create_index(op.f('ix_notification_templates_tenant_id'), 'notification_templates', ['tenant_id'], unique=False)
|
||||
op.create_table('notifications',
|
||||
sa.Column('id', sa.UUID(), nullable=False),
|
||||
sa.Column('tenant_id', sa.UUID(), nullable=False),
|
||||
sa.Column('sender_id', sa.UUID(), nullable=False),
|
||||
sa.Column('recipient_id', sa.UUID(), nullable=True),
|
||||
sa.Column('type', sa.Enum('EMAIL', 'WHATSAPP', 'PUSH', 'SMS', name='notificationtype'), nullable=False),
|
||||
sa.Column('status', sa.Enum('PENDING', 'SENT', 'DELIVERED', 'FAILED', 'CANCELLED', name='notificationstatus'), nullable=True),
|
||||
sa.Column('priority', sa.Enum('LOW', 'NORMAL', 'HIGH', 'URGENT', name='notificationpriority'), nullable=True),
|
||||
sa.Column('subject', sa.String(length=255), nullable=True),
|
||||
sa.Column('message', sa.Text(), nullable=False),
|
||||
sa.Column('html_content', sa.Text(), nullable=True),
|
||||
sa.Column('template_id', sa.String(length=100), nullable=True),
|
||||
sa.Column('template_data', sa.JSON(), nullable=True),
|
||||
sa.Column('recipient_email', sa.String(length=255), nullable=True),
|
||||
sa.Column('recipient_phone', sa.String(length=20), nullable=True),
|
||||
sa.Column('delivery_channel', sa.String(length=50), nullable=True),
|
||||
sa.Column('scheduled_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('sent_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('delivered_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('log_metadata', sa.JSON(), nullable=True),
|
||||
sa.Column('error_message', sa.Text(), nullable=True),
|
||||
sa.Column('retry_count', sa.Integer(), nullable=True),
|
||||
sa.Column('max_retries', sa.Integer(), nullable=True),
|
||||
sa.Column('broadcast', sa.Boolean(), nullable=True),
|
||||
sa.Column('read', sa.Boolean(), nullable=True),
|
||||
sa.Column('read_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_notifications_created_at'), 'notifications', ['created_at'], unique=False)
|
||||
op.create_index(op.f('ix_notifications_status'), 'notifications', ['status'], unique=False)
|
||||
op.create_index(op.f('ix_notifications_tenant_id'), 'notifications', ['tenant_id'], unique=False)
|
||||
op.create_table('whatsapp_templates',
|
||||
sa.Column('id', sa.UUID(), nullable=False),
|
||||
sa.Column('tenant_id', sa.UUID(), nullable=True),
|
||||
sa.Column('template_key', sa.String(length=100), nullable=False),
|
||||
sa.Column('name', sa.String(length=255), nullable=False),
|
||||
sa.Column('whatsapp_template_name', sa.String(length=255), nullable=False),
|
||||
sa.Column('whatsapp_template_id', sa.String(length=255), nullable=True),
|
||||
sa.Column('language_code', sa.String(length=10), nullable=True),
|
||||
sa.Column('header_text', sa.String(length=60), nullable=True),
|
||||
sa.Column('body_text', sa.Text(), nullable=False),
|
||||
sa.Column('footer_text', sa.String(length=60), nullable=True),
|
||||
sa.Column('parameter_count', sa.Integer(), nullable=True),
|
||||
sa.Column('parameters', sa.JSON(), nullable=True),
|
||||
sa.Column('approval_status', sa.String(length=20), nullable=True),
|
||||
sa.Column('is_active', sa.Boolean(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('template_key')
|
||||
)
|
||||
op.create_index(op.f('ix_whatsapp_templates_tenant_id'), 'whatsapp_templates', ['tenant_id'], unique=False)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_index(op.f('ix_whatsapp_templates_tenant_id'), table_name='whatsapp_templates')
|
||||
op.drop_table('whatsapp_templates')
|
||||
op.drop_index(op.f('ix_notifications_tenant_id'), table_name='notifications')
|
||||
op.drop_index(op.f('ix_notifications_status'), table_name='notifications')
|
||||
op.drop_index(op.f('ix_notifications_created_at'), table_name='notifications')
|
||||
op.drop_table('notifications')
|
||||
op.drop_index(op.f('ix_notification_templates_tenant_id'), table_name='notification_templates')
|
||||
op.drop_table('notification_templates')
|
||||
op.drop_index(op.f('ix_notification_preferences_user_id'), table_name='notification_preferences')
|
||||
op.drop_index(op.f('ix_notification_preferences_tenant_id'), table_name='notification_preferences')
|
||||
op.drop_table('notification_preferences')
|
||||
op.drop_index(op.f('ix_notification_logs_notification_id'), table_name='notification_logs')
|
||||
op.drop_table('notification_logs')
|
||||
op.drop_index(op.f('ix_email_templates_tenant_id'), table_name='email_templates')
|
||||
op.drop_table('email_templates')
|
||||
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 ###
|
||||
@@ -0,0 +1,159 @@
|
||||
"""add_whatsapp_business_tables
|
||||
|
||||
Revision ID: whatsapp001
|
||||
Revises: 359991e24ea2
|
||||
Create Date: 2025-11-13 12:00:00.000000+01: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 = 'whatsapp001'
|
||||
down_revision: Union[str, None] = '359991e24ea2'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# Create ENUMs using raw SQL to avoid double-creation issues
|
||||
conn = op.get_bind()
|
||||
|
||||
# Create WhatsApp message status enum if it doesn't exist
|
||||
conn.execute(sa.text("""
|
||||
DO $$ BEGIN
|
||||
CREATE TYPE whatsappmessagestatus AS ENUM ('PENDING', 'SENT', 'DELIVERED', 'READ', 'FAILED');
|
||||
EXCEPTION
|
||||
WHEN duplicate_object THEN null;
|
||||
END $$;
|
||||
"""))
|
||||
|
||||
# Create WhatsApp message type enum if it doesn't exist
|
||||
conn.execute(sa.text("""
|
||||
DO $$ BEGIN
|
||||
CREATE TYPE whatsappmessagetype AS ENUM ('TEMPLATE', 'TEXT', 'IMAGE', 'DOCUMENT', 'INTERACTIVE');
|
||||
EXCEPTION
|
||||
WHEN duplicate_object THEN null;
|
||||
END $$;
|
||||
"""))
|
||||
|
||||
# Create whatsapp_messages table
|
||||
op.create_table(
|
||||
'whatsapp_messages',
|
||||
sa.Column('id', sa.UUID(), nullable=False),
|
||||
sa.Column('tenant_id', sa.UUID(), nullable=False),
|
||||
sa.Column('notification_id', sa.UUID(), nullable=True),
|
||||
sa.Column('whatsapp_message_id', sa.String(length=255), nullable=True),
|
||||
sa.Column('recipient_phone', sa.String(length=20), nullable=False),
|
||||
sa.Column('recipient_name', sa.String(length=255), nullable=True),
|
||||
sa.Column('message_type', postgresql.ENUM('TEMPLATE', 'TEXT', 'IMAGE', 'DOCUMENT', 'INTERACTIVE', name='whatsappmessagetype', create_type=False), nullable=False),
|
||||
sa.Column('status', postgresql.ENUM('PENDING', 'SENT', 'DELIVERED', 'READ', 'FAILED', name='whatsappmessagestatus', create_type=False), nullable=False),
|
||||
sa.Column('template_name', sa.String(length=255), nullable=True),
|
||||
sa.Column('template_language', sa.String(length=10), nullable=True),
|
||||
sa.Column('template_parameters', postgresql.JSON(astext_type=sa.Text()), nullable=True),
|
||||
sa.Column('message_body', sa.Text(), nullable=True),
|
||||
sa.Column('media_url', sa.String(length=512), nullable=True),
|
||||
sa.Column('sent_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('delivered_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('read_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('failed_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('error_code', sa.String(length=50), nullable=True),
|
||||
sa.Column('error_message', sa.Text(), nullable=True),
|
||||
sa.Column('provider_response', postgresql.JSON(astext_type=sa.Text()), nullable=True),
|
||||
sa.Column('additional_data', postgresql.JSON(astext_type=sa.Text()), nullable=True),
|
||||
sa.Column('conversation_id', sa.String(length=255), nullable=True),
|
||||
sa.Column('conversation_category', sa.String(length=50), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
|
||||
# Create indexes for whatsapp_messages
|
||||
op.create_index(op.f('ix_whatsapp_messages_tenant_id'), 'whatsapp_messages', ['tenant_id'], unique=False)
|
||||
op.create_index(op.f('ix_whatsapp_messages_notification_id'), 'whatsapp_messages', ['notification_id'], unique=False)
|
||||
op.create_index(op.f('ix_whatsapp_messages_whatsapp_message_id'), 'whatsapp_messages', ['whatsapp_message_id'], unique=False)
|
||||
op.create_index(op.f('ix_whatsapp_messages_recipient_phone'), 'whatsapp_messages', ['recipient_phone'], unique=False)
|
||||
op.create_index(op.f('ix_whatsapp_messages_status'), 'whatsapp_messages', ['status'], unique=False)
|
||||
op.create_index(op.f('ix_whatsapp_messages_conversation_id'), 'whatsapp_messages', ['conversation_id'], unique=False)
|
||||
op.create_index(op.f('ix_whatsapp_messages_created_at'), 'whatsapp_messages', ['created_at'], unique=False)
|
||||
|
||||
# Create composite indexes for common queries
|
||||
op.create_index('idx_whatsapp_tenant_status', 'whatsapp_messages', ['tenant_id', 'status'], unique=False)
|
||||
op.create_index('idx_whatsapp_tenant_created', 'whatsapp_messages', ['tenant_id', 'created_at'], unique=False)
|
||||
|
||||
# Drop existing whatsapp_templates table if it exists (schema change)
|
||||
# This drops the old schema version from the initial migration
|
||||
conn.execute(sa.text("DROP TABLE IF EXISTS whatsapp_templates CASCADE"))
|
||||
|
||||
# Create whatsapp_templates table with new schema
|
||||
op.create_table(
|
||||
'whatsapp_templates',
|
||||
sa.Column('id', sa.UUID(), nullable=False),
|
||||
sa.Column('tenant_id', sa.UUID(), nullable=True),
|
||||
sa.Column('template_name', sa.String(length=255), nullable=False),
|
||||
sa.Column('template_key', sa.String(length=100), nullable=False),
|
||||
sa.Column('display_name', sa.String(length=255), nullable=False),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('category', sa.String(length=50), nullable=False),
|
||||
sa.Column('language', sa.String(length=10), nullable=True),
|
||||
sa.Column('status', sa.String(length=20), nullable=True),
|
||||
sa.Column('header_type', sa.String(length=20), nullable=True),
|
||||
sa.Column('header_text', sa.String(length=60), nullable=True),
|
||||
sa.Column('body_text', sa.Text(), nullable=False),
|
||||
sa.Column('footer_text', sa.String(length=60), nullable=True),
|
||||
sa.Column('parameters', postgresql.JSON(astext_type=sa.Text()), nullable=True),
|
||||
sa.Column('parameter_count', sa.Integer(), nullable=True),
|
||||
sa.Column('buttons', postgresql.JSON(astext_type=sa.Text()), nullable=True),
|
||||
sa.Column('is_active', sa.Boolean(), nullable=True),
|
||||
sa.Column('is_system', sa.Boolean(), nullable=True),
|
||||
sa.Column('sent_count', sa.Integer(), nullable=True),
|
||||
sa.Column('last_used_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('whatsapp_template_id', sa.String(length=255), nullable=True),
|
||||
sa.Column('approved_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('rejected_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('rejection_reason', sa.Text(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('template_key')
|
||||
)
|
||||
|
||||
# Create indexes for whatsapp_templates
|
||||
op.create_index(op.f('ix_whatsapp_templates_tenant_id'), 'whatsapp_templates', ['tenant_id'], unique=False)
|
||||
op.create_index(op.f('ix_whatsapp_templates_template_name'), 'whatsapp_templates', ['template_name'], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# Drop tables
|
||||
op.drop_index(op.f('ix_whatsapp_templates_template_name'), table_name='whatsapp_templates', if_exists=True)
|
||||
op.drop_index(op.f('ix_whatsapp_templates_tenant_id'), table_name='whatsapp_templates', if_exists=True)
|
||||
op.drop_table('whatsapp_templates', if_exists=True)
|
||||
|
||||
op.drop_index('idx_whatsapp_tenant_created', table_name='whatsapp_messages', if_exists=True)
|
||||
op.drop_index('idx_whatsapp_tenant_status', table_name='whatsapp_messages', if_exists=True)
|
||||
op.drop_index(op.f('ix_whatsapp_messages_created_at'), table_name='whatsapp_messages', if_exists=True)
|
||||
op.drop_index(op.f('ix_whatsapp_messages_conversation_id'), table_name='whatsapp_messages', if_exists=True)
|
||||
op.drop_index(op.f('ix_whatsapp_messages_status'), table_name='whatsapp_messages', if_exists=True)
|
||||
op.drop_index(op.f('ix_whatsapp_messages_recipient_phone'), table_name='whatsapp_messages', if_exists=True)
|
||||
op.drop_index(op.f('ix_whatsapp_messages_whatsapp_message_id'), table_name='whatsapp_messages', if_exists=True)
|
||||
op.drop_index(op.f('ix_whatsapp_messages_notification_id'), table_name='whatsapp_messages', if_exists=True)
|
||||
op.drop_index(op.f('ix_whatsapp_messages_tenant_id'), table_name='whatsapp_messages', if_exists=True)
|
||||
op.drop_table('whatsapp_messages', if_exists=True)
|
||||
|
||||
# Drop enums if they exist
|
||||
conn = op.get_bind()
|
||||
|
||||
result = conn.execute(sa.text(
|
||||
"SELECT 1 FROM pg_type WHERE typname = 'whatsappmessagetype'"
|
||||
))
|
||||
if result.fetchone():
|
||||
conn.execute(sa.text("DROP TYPE whatsappmessagetype"))
|
||||
|
||||
result = conn.execute(sa.text(
|
||||
"SELECT 1 FROM pg_type WHERE typname = 'whatsappmessagestatus'"
|
||||
))
|
||||
if result.fetchone():
|
||||
conn.execute(sa.text("DROP TYPE whatsappmessagestatus"))
|
||||
Reference in New Issue
Block a user