Files
plantillas-proyectos/backend/alembic/versions/7937209f9718_seed_initial_data.py

745 lines
30 KiB
Python

"""seed_initial_data
Revision ID: 7937209f9718
Revises:
Create Date: 2025-10-19 18:23:55.258800
"""
# pylint: disable=no-member
from typing import Sequence, Union
from alembic import op
from api.v1.modules.public.reference_data.code_pedimento_regimens.seed import (
seed as code_pedimento_regimens_seed,
)
from api.v1.modules.public.reference_data.containers.seed import (
seed as container_types_seed,
)
from api.v1.modules.public.reference_data.countries.seed import seed as countries_seed
from api.v1.modules.public.reference_data.currency_types.seed import (
seed as currency_types_seed,
)
from api.v1.modules.public.reference_data.customs_sections.seed import (
seed as customs_sections_seed,
)
from api.v1.modules.public.reference_data.customs_warehouses.seed import (
seed as customs_warehouses_seed,
)
from api.v1.modules.public.reference_data.incoterms.seed import seed as incoterms_seed
from api.v1.modules.public.reference_data.invoice_types.seed import (
seed as invoice_types_seed,
)
from api.v1.modules.public.reference_data.material_types.seed import (
seed as material_types_seed,
)
from api.v1.modules.public.reference_data.payment_methods.seed import (
seed as payment_methods_seed,
)
from api.v1.modules.public.reference_data.pedimento_codes.seed import (
seed as pedimento_codes_seed,
)
from api.v1.modules.public.reference_data.pedimento_regimens.seed import (
seed as pedimento_regimens_seed,
)
from api.v1.modules.public.reference_data.sectors.seed import seed as sectors_seed
from api.v1.modules.public.reference_data.states.seed import seed as states_seed
from api.v1.modules.public.reference_data.transport_modes.seed import (
seed as transport_modes_seed,
)
from api.v1.modules.public.reference_data.transport_types.seed import (
seed as transport_types_seed,
)
from api.v1.modules.public.reference_data.valuation_methods.seed import (
seed as valuation_methods_seed,
)
from api.v1.modules.a76.general_catalogs.units_of_measure.seed import (
seed as units_of_measure_seed,
)
from api.v1.modules.a76.general_catalogs.units_of_measure.seed_ace import (
seed as ace_seed,
)
from api.v1.modules.a76.general_catalogs.units_of_measure.seed_oma import (
seed as oma_seed,
)
from api.v1.modules.a76.general_catalogs.units_of_measure.seed_ame import (
seed as ame_seed,
)
from api.v1.modules.a76.general_catalogs.units_of_measure.seed_adua import (
seed as adua_seed,
)
from api.v1.modules.a76.general_catalogs.fractions.tariff_fractions.seed import (
seed as tariff_fractions_seed,
)
from api.v1.modules.a76.general_catalogs.fractions.historical_tariff_fractions.seed import (
seed as historical_tariff_fractions_seed,
)
from api.v1.modules.public.reference_data.trailer_types.seed import (
seed as trailer_types_seed,
)
from api.v1.modules.core.permissions.seed import (
seed_invoices,
seed_user,
seed_report,
seed_roles,
)
# revision identifiers, used by Alembic.
revision: str = "7937209f9718"
down_revision: Union[str, Sequence[str], None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# --- CREAR TABLA fraccion canadienses ---
op.create_table('canadian_tariff_fractions',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('fraction', sa.String(length=13), nullable=False),
sa.Column('ad_valorem', sa.Numeric(precision=5, scale=2), nullable=True),
sa.Column('unit_of_measure', sa.String(length=5), nullable=True),
sa.Column('country_code', sa.String(length=3), nullable=False),
sa.Column('description', sa.String(length=1000), nullable=True),
# Tenant Scoped Mixin
sa.Column('tenant_id', sa.Integer(), nullable=False),
sa.Column('company_id', sa.Integer(), nullable=False),
# Timestamp Mixin
sa.Column('created_at', sa.TIMESTAMP(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('updated_at', sa.TIMESTAMP(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('deleted_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.ForeignKeyConstraint(['tenant_id'], ['core.tenants.id'], source_schema='a76', referent_schema='core'),
sa.ForeignKeyConstraint(['company_id'], ['a76.company.id'], source_schema='a76', referent_schema='a76'),
sa.UniqueConstraint('fraction', 'country_code', 'company_id', name='uq_canadian_fraction_country_company'),
schema='a76'
)
op.create_index(op.f('ix_a76_canadian_tariff_fractions_country_code'), 'canadian_tariff_fractions', ['country_code'], unique=False, schema='a76')
op.create_index(op.f('ix_a76_canadian_tariff_fractions_fraction'), 'canadian_tariff_fractions', ['fraction'], unique=False, schema='a76')
op.create_index(op.f('ix_a76_canadian_tariff_fractions_id'), 'canadian_tariff_fractions', ['id'], unique=False, schema='a76')
op.create_index(op.f('ix_a76_canadian_tariff_fractions_company_id'), 'canadian_tariff_fractions', ['company_id'], unique=False, schema='a76')
op.create_index(op.f('ix_a76_canadian_tariff_fractions_tenant_id'), 'canadian_tariff_fractions', ['tenant_id'], unique=False, schema='a76')
# --- CREAR TABLA fraccion americana ---
op.create_table('us_tariff_fractions',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('code', sa.String(length=16), nullable=False, comment='Código de fracción americana'),
sa.Column('prefix', sa.String(length=10), nullable=True, comment='Prefijo de clasificación'),
sa.Column('type_code', sa.String(length=10), nullable=True, comment='Código de tipo'),
sa.Column('ad_valorem', sa.Numeric(precision=10, scale=2), nullable=True, comment='Porcentaje ad valorem'),
sa.Column('fixed_cost', sa.Numeric(precision=15, scale=8), nullable=True, comment='Tasa fija'),
sa.Column('unit_of_measure', sa.String(length=10), nullable=True, comment='Unidad de medida'),
sa.Column('description', sa.String(), nullable=True, comment='Descripción de la fracción'),
# Tenant Scoped Mixin
sa.Column('tenant_id', sa.Integer(), nullable=False),
sa.Column('company_id', sa.Integer(), nullable=False),
# Timestamp Mixin
sa.Column('created_at', sa.TIMESTAMP(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('updated_at', sa.TIMESTAMP(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('deleted_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.ForeignKeyConstraint(['tenant_id'], ['core.tenants.id'], source_schema='a76', referent_schema='core'),
sa.ForeignKeyConstraint(['company_id'], ['a76.company.id'], source_schema='a76', referent_schema='a76'),
schema='a76'
)
op.create_index(op.f('ix_a76_us_tariff_fractions_id'), 'us_tariff_fractions', ['id'], unique=False, schema='a76')
op.create_index(op.f('ix_a76_us_tariff_fractions_company_id'), 'us_tariff_fractions', ['company_id'], unique=False, schema='a76')
op.create_index(op.f('ix_a76_us_tariff_fractions_tenant_id'), 'us_tariff_fractions', ['tenant_id'], unique=False, schema='a76')
# --- CREAR TABLA fraccion historico ---
op.create_table('historical_tariff_fractions',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('historical_fraction', sa.String(length=8), nullable=True),
sa.Column('unit_of_measure_code', sa.String(), nullable=True),
sa.Column('country', sa.String(), nullable=True),
sa.Column('fraction_type', sa.String(length=7), nullable=True),
sa.Column('sector', sa.String(length=5), nullable=True),
sa.Column('import_tax_rate', sa.Numeric(precision=7, scale=2), nullable=True),
sa.Column('export_tax_rate', sa.Numeric(precision=7, scale=2), nullable=True),
sa.Column('publication_date', sa.DateTime(), nullable=True),
sa.Column('is_immex', sa.Boolean(), nullable=True),
sa.Column('normal_temporality', sa.Boolean(), nullable=True),
sa.Column('services_temporality', sa.Boolean(), nullable=True),
sa.Column('certified_temporality', sa.Boolean(), nullable=True),
sa.Column('by_log', sa.Boolean(), nullable=True),
sa.Column('end_date', sa.DateTime(), nullable=True),
# Tenant Scoped Mixin
sa.Column('tenant_id', sa.Integer(), nullable=False),
sa.Column('company_id', sa.Integer(), nullable=False),
# Timestamp Mixin
sa.Column('created_at', sa.TIMESTAMP(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('updated_at', sa.TIMESTAMP(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('deleted_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.ForeignKeyConstraint(['tenant_id'], ['core.tenants.id'], source_schema='a76', referent_schema='core'),
sa.ForeignKeyConstraint(['company_id'], ['a76.company.id'], source_schema='a76', referent_schema='a76'),
# Foreign Keys to other tables (assuming they exist or are created before/simultaneously, referencing explicit schemas)
sa.ForeignKeyConstraint(['unit_of_measure_code'], ['a76.unit_of_measure_customs.code'], source_schema='a76', referent_schema='a76'),
sa.ForeignKeyConstraint(['country'], ['public.countries.m3_key'], source_schema='a76', referent_schema='public'),
schema='a76'
)
op.create_index(op.f('ix_a76_historical_tariff_fractions_id'), 'historical_tariff_fractions', ['id'], unique=False, schema='a76')
op.create_index(op.f('ix_a76_historical_tariff_fractions_company_id'), 'historical_tariff_fractions', ['company_id'], unique=False, schema='a76')
op.create_index(op.f('ix_a76_historical_tariff_fractions_tenant_id'), 'historical_tariff_fractions', ['tenant_id'], unique=False, schema='a76')
# --- CREAR TABLA fraccion americana ---
op.create_table('us_tariff_fractions',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('code', sa.String(length=16), nullable=False, comment='Código de fracción americana'),
sa.Column('prefix', sa.String(length=10), nullable=True, comment='Prefijo de clasificación'),
sa.Column('type_code', sa.String(length=10), nullable=True, comment='Código de tipo'),
sa.Column('ad_valorem', sa.Numeric(precision=10, scale=2), nullable=True, comment='Porcentaje ad valorem'),
sa.Column('fixed_cost', sa.Numeric(precision=15, scale=8), nullable=True, comment='Tasa fija'),
sa.Column('unit_of_measure', sa.String(length=10), nullable=True, comment='Unidad de medida'),
sa.Column('description', sa.String(), nullable=True, comment='Descripción de la fracción'),
# Tenant Scoped Mixin
sa.Column('tenant_id', sa.Integer(), nullable=False),
sa.Column('company_id', sa.Integer(), nullable=False),
# Timestamp Mixin
sa.Column('created_at', sa.TIMESTAMP(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('updated_at', sa.TIMESTAMP(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('deleted_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.ForeignKeyConstraint(['tenant_id'], ['core.tenants.id'], source_schema='a76', referent_schema='core'),
sa.ForeignKeyConstraint(['company_id'], ['a76.company.id'], source_schema='a76', referent_schema='a76'),
schema='a76'
)
op.create_index(op.f('ix_a76_us_tariff_fractions_id'), 'us_tariff_fractions', ['id'], unique=False, schema='a76')
op.create_index(op.f('ix_a76_us_tariff_fractions_company_id'), 'us_tariff_fractions', ['company_id'], unique=False, schema='a76')
op.create_index(op.f('ix_a76_us_tariff_fractions_tenant_id'), 'us_tariff_fractions', ['tenant_id'], unique=False, schema='a76')
# --- CREAR TABLA fraccion historico ---
op.create_table('historical_tariff_fractions',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('historical_fraction', sa.String(length=8), nullable=True),
sa.Column('unit_of_measure_code', sa.String(), nullable=True),
sa.Column('country', sa.String(), nullable=True),
sa.Column('fraction_type', sa.String(length=7), nullable=True),
sa.Column('sector', sa.String(length=5), nullable=True),
sa.Column('import_tax_rate', sa.Numeric(precision=7, scale=2), nullable=True),
sa.Column('export_tax_rate', sa.Numeric(precision=7, scale=2), nullable=True),
sa.Column('publication_date', sa.DateTime(), nullable=True),
sa.Column('is_immex', sa.Boolean(), nullable=True),
sa.Column('normal_temporality', sa.Boolean(), nullable=True),
sa.Column('services_temporality', sa.Boolean(), nullable=True),
sa.Column('certified_temporality', sa.Boolean(), nullable=True),
sa.Column('by_log', sa.Boolean(), nullable=True),
sa.Column('end_date', sa.DateTime(), nullable=True),
# Tenant Scoped Mixin
sa.Column('tenant_id', sa.Integer(), nullable=False),
sa.Column('company_id', sa.Integer(), nullable=False),
# Timestamp Mixin
sa.Column('created_at', sa.TIMESTAMP(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('updated_at', sa.TIMESTAMP(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('deleted_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.ForeignKeyConstraint(['tenant_id'], ['core.tenants.id'], source_schema='a76', referent_schema='core'),
sa.ForeignKeyConstraint(['company_id'], ['a76.company.id'], source_schema='a76', referent_schema='a76'),
# Foreign Keys to other tables (assuming they exist or are created before/simultaneously, referencing explicit schemas)
sa.ForeignKeyConstraint(['unit_of_measure_code'], ['a76.unit_of_measure_customs.code'], source_schema='a76', referent_schema='a76'),
sa.ForeignKeyConstraint(['country'], ['public.countries.m3_key'], source_schema='a76', referent_schema='public'),
schema='a76'
)
op.create_index(op.f('ix_a76_historical_tariff_fractions_id'), 'historical_tariff_fractions', ['id'], unique=False, schema='a76')
op.create_index(op.f('ix_a76_historical_tariff_fractions_company_id'), 'historical_tariff_fractions', ['company_id'], unique=False, schema='a76')
op.create_index(op.f('ix_a76_historical_tariff_fractions_tenant_id'), 'historical_tariff_fractions', ['tenant_id'], unique=False, schema='a76')
# --- UTILIDAD DE FORMATEO ---
def format_value(val):
if val is None or str(val).strip() == "" or str(val).upper() == "NONE":
return "NULL"
return f"'{str(val).replace(chr(39), chr(39)*2)}'"
# --- SEEDS PUBLIC (Tablas base) ---
# Seeds
values_pc = ", ".join(
[
f"('{code}', '{desc.replace(chr(39), chr(39)*2)}')"
for code, desc in pedimento_codes_seed
]
)
op.execute(
f"""
INSERT INTO pedimento_codes (code, description) VALUES
{values_pc}
ON CONFLICT (code) DO NOTHING;
"""
)
values_pr = ", ".join(
[
f"('{code}', '{desc.replace(chr(39), chr(39)*2)}')"
for code, desc in pedimento_regimens_seed
]
)
op.execute(
f"""
INSERT INTO public.pedimento_regimens (code, description) VALUES
{values_pr}
ON CONFLICT (code) DO NOTHING;
"""
)
values_cpr = ", ".join(
[
f"('{ped_code}', '{reg_code}', '{type_code}')"
for ped_code, reg_code, type_code in code_pedimento_regimens_seed
]
)
op.execute(
f"""
INSERT INTO public.code_pedimento_regimens (pedimento_code, regimen_code, type_code) VALUES
{values_cpr}
"""
)
values_c = ", ".join(
[
f"('{key}', '{desc.replace(chr(39), chr(39)*2)}')"
for key, desc in container_types_seed
]
)
op.execute(
f"""
INSERT INTO public.containers (key, description) VALUES
{values_c}
ON CONFLICT (key) DO NOTHING;
"""
)
values_country = ", ".join(
[
f"('{m3_key}', '{mex_key}', '{ame_key}', '{desc_es.replace(chr(39), chr(39)*2)}', '{desc_en.replace(chr(39), chr(39)*2)}')"
for m3_key, mex_key, ame_key, desc_es, desc_en in countries_seed
]
)
op.execute(
f"""
INSERT INTO public.countries (m3_key, mex_key, ame_key, description_es, description_en) VALUES
{values_country}
ON CONFLICT (m3_key) DO NOTHING;
"""
)
values_ct = ", ".join(
[
f"('{code}', '{currency_name.replace(chr(39), chr(39)*2)}', '{country_desc.replace(chr(39), chr(39)*2)}')"
for code, currency_name, country_desc in currency_types_seed
]
)
op.execute(
f"""
INSERT INTO public.currency_types (code, currency_name, country_description) VALUES
{values_ct}
ON CONFLICT (code) DO NOTHING;
"""
)
values_cs = ", ".join(
[
f"('{code}', '{name.replace(chr(39), chr(39)*2)}')"
for code, name in customs_sections_seed
]
)
op.execute(
f"""
INSERT INTO public.customs_sections (customs_code, section_name) VALUES
{values_cs}
ON CONFLICT (customs_code) DO NOTHING;
"""
)
values_cw = ", ".join(
[
f"('{key}', '{customs.replace(chr(39), chr(39)*2)}', '{fiscalized_warehouse.replace(chr(39), chr(39)*2)}')"
for key, customs, fiscalized_warehouse in customs_warehouses_seed
]
)
op.execute(
f"""
INSERT INTO public.customs_warehouses (key, customs, fiscalized_warehouse)
VALUES
{values_cw}
ON CONFLICT (key, customs) DO NOTHING;
"""
)
values_incoterms = ", ".join(
[
f"('{code}', '{desc_es.replace(chr(39), chr(39)*2)}', '{desc_en.replace(chr(39), chr(39)*2)}')"
for code, desc_es, desc_en in incoterms_seed
]
)
op.execute(
f"""
INSERT INTO public.incoterms (code, description_es, description_en) VALUES
{values_incoterms}
ON CONFLICT (code) DO NOTHING;
"""
)
values_it = ", ".join(
[
f"('{key}', '{desc.replace(chr(39), chr(39)*2)}', '{note.replace(chr(39), chr(39)*2)}', '{type.replace(chr(39), chr(39)*2)}', '{operation.replace(chr(39), chr(39)*2)}')"
for key, desc, note, type, operation in invoice_types_seed
]
)
op.execute(
f"""
INSERT INTO public.invoice_types (key, description, note, type, operation) VALUES
{values_it}
ON CONFLICT (key) DO NOTHING;
"""
)
values_mt = ", ".join(
[
f"('{key}', '{desc.replace(chr(39), chr(39)*2)}', '{category.replace(chr(39), chr(39)*2)}')"
for key, desc, category in material_types_seed
]
)
op.execute(
f"""
INSERT INTO public.material_types (key, description, type) VALUES
{values_mt}
ON CONFLICT (key) DO NOTHING;
"""
)
values_pm = ", ".join(
[
f"('{key}', '{desc.replace(chr(39), chr(39)*2)}')"
for key, desc in payment_methods_seed
]
)
op.execute(
f"""
INSERT INTO public.payment_methods (key, description) VALUES
{values_pm}
ON CONFLICT (key) DO NOTHING;
"""
)
values_sectors = ", ".join(
[
f"('{key}', '{desc.replace(chr(39), chr(39)*2)}', '{authorized}')"
for key, desc, authorized in sectors_seed
]
)
op.execute(
f"""
INSERT INTO public.sectors (key, description, authorized) VALUES
{values_sectors}
ON CONFLICT (key) DO NOTHING;
"""
)
values_tm = ", ".join(
[
f"('{key}', '{name.replace(chr(39), chr(39)*2)}')"
for key, name in transport_modes_seed
]
)
op.execute(
f"""
INSERT INTO public.transport_modes (key, name) VALUES
{values_tm}
ON CONFLICT (key) DO NOTHING;
"""
)
values_tt = ", ".join(
[
f"('{code}', '{desc.replace(chr(39), chr(39)*2)}')"
for code, desc in transport_types_seed
]
)
op.execute(
f"""
INSERT INTO public.transport_types (transport_code, description) VALUES
{values_tt}
ON CONFLICT (transport_code) DO NOTHING;
"""
)
values_trailer = ", ".join(
[
f"('{code}', '{desc.replace(chr(39), chr(39)*2)}')"
for code, desc in trailer_types_seed
]
)
op.execute(
f"""
INSERT INTO public.trailer_type (trailer_type_key, description) VALUES
{values_trailer}
ON CONFLICT (trailer_type_key) DO NOTHING;
"""
)
values_vm = ", ".join(
[
f"('{key}', '{desc.replace(chr(39), chr(39)*2)}')"
for key, desc in valuation_methods_seed
]
)
op.execute(
f"""
INSERT INTO public.valuation_methods (key, description) VALUES
{values_vm}
ON CONFLICT (key) DO NOTHING;
"""
)
# --- SEEDS A76 (Unidades de Medida) ---
# ACE
val_ace = ", ".join(
[f"({format_value(c)}, {format_value(d)})" for c, d in ace_seed]
)
op.execute(
f"INSERT INTO a76.unit_of_measure_ace (code, description) VALUES {val_ace} ON CONFLICT ON CONSTRAINT uq_uom_ace_code DO NOTHING;"
)
# OMA
val_oma = ", ".join(
[f"({format_value(c)}, {format_value(d)})" for c, d in oma_seed]
)
op.execute(
f"INSERT INTO a76.unit_of_measure_oma (code, description) VALUES {val_oma} ON CONFLICT ON CONSTRAINT uq_uom_oma_code DO NOTHING;"
)
# AME
val_ame = ", ".join(
[f"({format_value(c)}, {format_value(d)})" for c, d in ame_seed]
)
op.execute(
f"INSERT INTO a76.unit_of_measure_american (code, description) VALUES {val_ame} ON CONFLICT ON CONSTRAINT uq_uom_american_code DO NOTHING;"
)
# ADUA (Customs)
val_adua = ", ".join(
[f"({format_value(c)}, {format_value(d)})" for c, d in adua_seed]
)
op.execute(
f"INSERT INTO a76.unit_of_measure_customs (code, description) VALUES {val_adua} ON CONFLICT ON CONSTRAINT uq_uom_customs_code DO NOTHING;"
)
# Recolectar códigos adicionales que faltan en los catálogos
additional_customs = set()
additional_american = set()
additional_ace = set()
additional_oma = set()
existing_customs = {c for c, d in adua_seed}
existing_american = {c for c, d in ame_seed}
existing_ace = {c for c, d in ace_seed}
existing_oma = {c for c, d in oma_seed}
for code, desc, desc_en, customs, american, ace, oma in units_of_measure_seed:
if customs and customs.strip() and customs not in existing_customs:
additional_customs.add((customs, f"Auto-generated from {code}"))
if american and american.strip() and american not in existing_american:
additional_american.add((american, f"Auto-generated from {code}"))
if ace and ace.strip() and ace not in existing_ace:
additional_ace.add((ace, f"Auto-generated from {code}"))
if oma and oma.strip() and oma not in existing_oma:
additional_oma.add((oma, f"Auto-generated from {code}"))
# Insertar códigos adicionales
if additional_customs:
val_add_customs = ", ".join(
[f"({format_value(c)}, {format_value(d)})" for c, d in additional_customs]
)
op.execute(
f"INSERT INTO a76.unit_of_measure_customs (code, description, a76_unit_code) VALUES {val_add_customs} ON CONFLICT ON CONSTRAINT uq_uom_customs_code DO NOTHING;"
)
if additional_american:
val_add_american = ", ".join(
[f"({format_value(c)}, {format_value(d)})" for c, d in additional_american]
)
op.execute(
f"INSERT INTO a76.unit_of_measure_american (code, description) VALUES {val_add_american} ON CONFLICT ON CONSTRAINT uq_uom_american_code DO NOTHING;"
)
if additional_ace:
val_add_ace = ", ".join(
[f"({format_value(c)}, {format_value(d)})" for c, d in additional_ace]
)
op.execute(
f"INSERT INTO a76.unit_of_measure_ace (code, description) VALUES {val_add_ace} ON CONFLICT ON CONSTRAINT uq_uom_ace_code DO NOTHING;"
)
if additional_oma:
val_add_oma = ", ".join(
[f"({format_value(c)}, {format_value(d)})" for c, d in additional_oma]
)
op.execute(
f"INSERT INTO a76.unit_of_measure_oma (code, description) VALUES {val_add_oma} ON CONFLICT ON CONSTRAINT uq_uom_oma_code DO NOTHING;"
)
# TABLA MAESTRA UOM
# TODO: Generar tenant_id y company_id correctos
val_uom = ", ".join(
[
f"({format_value(code)}, {format_value(desc)}, {format_value(desc_en)}, "
f"{format_value(customs)}, {format_value(american)}, {format_value(ace)}, {format_value(oma)}, 1, 1)"
for code, desc, desc_en, customs, american, ace, oma in units_of_measure_seed
]
)
op.execute("ALTER TABLE a76.units_of_measure DISABLE TRIGGER ALL;")
op.execute(
f"""
INSERT INTO a76.units_of_measure
(code, description, description_en, customs_code, american_code, ace_code, oma_code, tenant_id, company_id)
VALUES {val_uom}
ON CONFLICT (code, tenant_id, company_id) DO NOTHING;
"""
)
op.execute("ALTER TABLE a76.units_of_measure ENABLE TRIGGER ALL;")
# --- SEEDS CORE (Permissions) ---
# Combinar todas las seeds de permisos
all_permissions = seed_invoices + seed_user + seed_report + seed_roles
values_permissions = ", ".join(
[
f"({format_value(code)}, {format_value(desc)}, {format_value(module)}, {format_value(action)})"
for code, desc, module, action in all_permissions
]
)
if values_permissions:
op.execute(
f"""
INSERT INTO core.permissions (code, description, module, action)
VALUES {values_permissions}
ON CONFLICT (code) DO NOTHING;
"""
)
# --- SEEDS PUBLIC (States) ---
values_states = ", ".join(
[
f"('{m3_key}', '{description.replace(chr(39), chr(39)*2)}', {format_value(mex_key)})"
for m3_key, description, mex_key in states_seed
]
)
op.execute(
f"""
INSERT INTO public.states (m3_key, description, mex_key)
VALUES {values_states}
ON CONFLICT (m3_key, description) DO NOTHING;
"""
)
# --- SEEDS A76 (Tariff Fractions - Fracciones Arancelarias Mexicanas) ---
values_tariff_fractions = ", ".join(
[
f"({format_value(code)}, {format_value(fraction)}, {format_value(description)}, "
f"{format_value(nico)}, {format_value(umt)}, {format_value(adv_impo)}, {format_value(adv_expo)})"
for code, fraction, description, nico, umt, adv_impo, adv_expo in tariff_fractions_seed
]
)
op.execute(
f"""
INSERT INTO a76.tariff_fractions (code, fraction, description, nico, umt, adv_impo, adv_expo)
VALUES {values_tariff_fractions}
ON CONFLICT (code) DO NOTHING;
"""
)
def format_bool(val):
"""Convert boolean string to SQL boolean."""
if val is None or str(val).strip() == "" or str(val).upper() == "NONE":
return "NULL"
return "TRUE" if str(val).upper() == "TRUE" else "FALSE"
def format_timestamp(val):
"""Format timestamp for PostgreSQL."""
if val is None or str(val).strip() == "" or str(val).upper() == "NONE":
return "NULL"
# El valor ya viene en formato 'YYYY-MM-DD HH:MM:SS'
return f"'{str(val)}'"
values_historical_fractions = ", ".join(
[
f"({format_value(historical_fraction)}, {format_value(unit_measure)}, {format_value(country)}, "
f"{format_value(fraction_type)}, {format_value(sector)}, {format_value(import_tax)}, "
f"{format_value(export_tax)}, {format_timestamp(pub_date)}, {format_bool(is_immex)}, "
f"{format_bool(normal_temp)}, {format_bool(services_temp)}, {format_bool(certified_temp)}, "
f"{format_bool(by_log)}, {format_timestamp(end_date)}, "
f"1, 1, 'NOW()', 'NOW()')" # tenant_id=1, company_id=1, created_at=NOW(), updated_at=NOW()
for historical_fraction, unit_measure, country, fraction_type, sector, import_tax, export_tax, pub_date, is_immex, normal_temp, services_temp, certified_temp, by_log, end_date in historical_tariff_fractions_seed
]
)
if values_historical_fractions:
op.execute(
f"""
INSERT INTO a76.historical_tariff_fractions
(historical_fraction, unit_of_measure_code, country, fraction_type, sector,
import_tax_rate, export_tax_rate, publication_date, is_immex,
normal_temporality, services_temporality, certified_temporality, by_log, end_date,
tenant_id, company_id, created_at, updated_at)
VALUES {values_historical_fractions}
ON CONFLICT DO NOTHING;
"""
)
def downgrade() -> None:
"""Downgrade schema."""
op.drop_table("us_tariff_fractions", schema="a76")
op.drop_table("historical_tariff_fractions", schema="a76")
op.drop_table("canadian_tariff_fractions", schema="a76")
op.drop_table("valuation_methods", schema="public")
op.drop_table("transport_types", schema="public")
op.drop_table("trailer_types", schema="public")
op.drop_table("transport_modes", schema="public")
op.drop_table("sectors", schema="public")
op.drop_table("payment_methods", schema="public")
op.drop_table("material_types", schema="public")
op.drop_table("invoice_types", schema="public")
op.drop_table("incoterms", schema="public")
op.drop_table("customs_warehouses", schema="public")
op.drop_table("customs_sections", schema="public")
op.drop_table("currency_types", schema="public")
op.drop_table("countries", schema="public")
op.drop_table("containers", schema="public")
op.drop_table("code_pedimento_regimens", schema="public")
op.drop_table("pedimento_regimens", schema="public")
op.drop_table("pedimento_codes", schema="public")
op.drop_table("user_client_permissions", schema="core")
op.drop_table("user_client_roles", schema="core")
op.drop_table("role_permissions", schema="core")
op.drop_table("client_roles", schema="core")
op.drop_table("permissions", schema="core")
op.drop_table("units_of_measure", schema="a76")
op.drop_table("unit_of_measure_customs", schema="a76")
op.drop_table("unit_of_measure_american", schema="a76")
op.drop_table("unit_of_measure_oma", schema="a76")
op.drop_table("unit_of_measure_ace", schema="a76")