Co-authored-by: MENDOZA BALLARDO GAEL RICARDO <gael-meb123@users.noreply.github.com>
Co-authored-by: Azareth-Tr <Azareth-Tr@users.noreply.githu b.com> correcion de errores en llenado de tablas, primeras vistas frontend
This commit is contained in:
@@ -1,40 +1,28 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from dotenv import load_dotenv
|
||||
from supabase import create_client, Client
|
||||
|
||||
# Configuración de directorios base
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
DATA_DIR = os.path.join(BASE_DIR, "data")
|
||||
ENV_PATH = os.path.join(os.path.dirname(BASE_DIR), ".env")
|
||||
BASE_DIR = Path(__file__).parent.parent # backend/app/
|
||||
DATA_DIR = BASE_DIR / "data"
|
||||
ENV_PATH = BASE_DIR.parent / ".env" # backend/.env
|
||||
|
||||
def load_env(path: str):
|
||||
"""Carga variables de entorno de forma manual sin depender de python-dotenv"""
|
||||
if not os.path.exists(path):
|
||||
print(f"Advertencia: No se encontró el archivo {path}")
|
||||
return
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if line and not line.startswith('#'):
|
||||
# Separa por el primer '=' y limpia espacios y comillas
|
||||
key, val = line.split('=', 1)
|
||||
os.environ[key.strip()] = val.strip().strip("'").strip('"')
|
||||
|
||||
def load_json(filename: str):
|
||||
path = os.path.join(DATA_DIR, filename)
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
with open(DATA_DIR / filename, encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
def main():
|
||||
print("Iniciando proceso de seeding...")
|
||||
load_env(ENV_PATH)
|
||||
load_dotenv(ENV_PATH)
|
||||
|
||||
# Es crucial usar SUPABASE_SERVICE_ROLE_KEY para saltar el RLS durante el Seed
|
||||
URL = os.environ.get("SUPABASE_URL")
|
||||
KEY = os.environ.get("SUPABASE_SERVICE_ROLE_KEY")
|
||||
|
||||
if not URL or not KEY:
|
||||
raise ValueError("Error: Asegúrate de tener SUPABASE_URL y SUPABASE_SERVICE_ROLE_KEY en el .env")
|
||||
raise ValueError("Falta SUPABASE_URL o SUPABASE_SERVICE_ROLE_KEY en el .env")
|
||||
|
||||
supabase: Client = create_client(URL, KEY)
|
||||
|
||||
@@ -99,7 +87,7 @@ def main():
|
||||
"turno": c["turno"],
|
||||
"horario_estimado": c["horario_estimado"]
|
||||
})
|
||||
supabase.table("colonias").upsert(colonias_to_insert).execute()
|
||||
supabase.table("colonias").upsert(colonias_to_insert, on_conflict="nombre").execute()
|
||||
|
||||
print("✅ Seed completado con éxito. Base de datos operativa para la app.")
|
||||
|
||||
|
||||
93
backend/app/db/tables.sql
Normal file
93
backend/app/db/tables.sql
Normal file
@@ -0,0 +1,93 @@
|
||||
-- ============================================================
|
||||
-- Tablas del dominio — Sistema de Recolección Inteligente
|
||||
-- Ejecutar ANTES que rls_policies.sql
|
||||
-- Supabase > SQL Editor
|
||||
-- ============================================================
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 1. UNITS (camiones recolectores)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS public.units (
|
||||
id INT PRIMARY KEY, -- truckId del JSON (101, 103, …)
|
||||
plate TEXT,
|
||||
status TEXT DEFAULT 'active'
|
||||
CHECK (status IN ('active', 'inactive', 'maintenance'))
|
||||
);
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 2. ROUTES (6 rutas MVP)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS public.routes (
|
||||
id TEXT PRIMARY KEY, -- 'RUTA-01' … 'RUTA-13'
|
||||
name TEXT,
|
||||
truck_id INT REFERENCES public.units(id),
|
||||
turno TEXT CHECK (turno IN ('matutino', 'vespertino', 'Matutino', 'Vespertino')),
|
||||
status TEXT DEFAULT 'pendiente'
|
||||
CHECK (status IN ('pendiente','en_ruta','completada','diferida','reasignada')),
|
||||
current_position_id INT DEFAULT 1 CHECK (current_position_id BETWEEN 1 AND 8)
|
||||
);
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 3. ROUTE_POSITIONS (8 posiciones por ruta — solo admin)
|
||||
-- ⚠️ Contiene lat/lng. NUNCA se devuelve al ciudadano.
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS public.route_positions (
|
||||
route_id TEXT REFERENCES public.routes(id) ON DELETE CASCADE,
|
||||
position_id INT,
|
||||
lat DOUBLE PRECISION,
|
||||
lng DOUBLE PRECISION,
|
||||
speed INT,
|
||||
ts TIMESTAMPTZ,
|
||||
PRIMARY KEY (route_id, position_id)
|
||||
);
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 4. COLONIAS (mapeo colonia → ruta; sin coordenadas)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS public.colonias (
|
||||
id SERIAL PRIMARY KEY,
|
||||
nombre TEXT NOT NULL,
|
||||
route_id TEXT REFERENCES public.routes(id),
|
||||
turno TEXT,
|
||||
horario_estimado TEXT
|
||||
);
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 5. DRIVERS (chofer → unidad; 1:1)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS public.drivers (
|
||||
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
|
||||
user_id UUID REFERENCES public.users(id) ON DELETE CASCADE,
|
||||
unit_id INT REFERENCES public.units(id)
|
||||
);
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 6. COLLECTION_EVENTS (registro de recolección por domicilio)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS public.collection_events (
|
||||
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
|
||||
route_id TEXT REFERENCES public.routes(id),
|
||||
address_id UUID REFERENCES public.addresses(id) ON DELETE CASCADE,
|
||||
status TEXT,
|
||||
collected_at TIMESTAMPTZ DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 7. ROUTE_CHANGES (historial de reasignaciones / retrasos)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS public.route_changes (
|
||||
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
|
||||
route_id TEXT REFERENCES public.routes(id),
|
||||
from_unit INT REFERENCES public.units(id),
|
||||
to_unit INT REFERENCES public.units(id),
|
||||
reason TEXT,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- Índices de rendimiento
|
||||
-- ------------------------------------------------------------
|
||||
CREATE INDEX IF NOT EXISTS idx_route_positions_route ON public.route_positions(route_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_colonias_route ON public.colonias(route_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_drivers_user ON public.drivers(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_collection_route ON public.collection_events(route_id);
|
||||
Reference in New Issue
Block a user