Co-authored-by: Azareth-Tr <Azareth-Tr@users.noreply.github.com> Co-authored-by: eddgranados12 <eddgranados12@users.noreply.github.com> configuracion inicial para supoabase y endpoints
107 lines
3.7 KiB
Python
107 lines
3.7 KiB
Python
import json
|
|
import os
|
|
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")
|
|
|
|
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:
|
|
return json.load(f)
|
|
|
|
def main():
|
|
print("Iniciando proceso de seeding...")
|
|
load_env(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")
|
|
|
|
supabase: Client = create_client(URL, KEY)
|
|
|
|
rutas_data = load_json("rutas.json")
|
|
colonias_data = load_json("colonias-rutas.json")
|
|
|
|
# 1. Poblar UNITS (Dependencia raíz)
|
|
print("1. Poblando tabla 'units'...")
|
|
units_to_insert = []
|
|
truck_ids = set()
|
|
for r in rutas_data:
|
|
tid = r.get("truckId")
|
|
if tid and tid not in truck_ids:
|
|
truck_ids.add(tid)
|
|
units_to_insert.append({
|
|
"id": tid,
|
|
"plate": f"GTO-{tid}", # Simulado
|
|
"status": "active"
|
|
})
|
|
if units_to_insert:
|
|
supabase.table("units").upsert(units_to_insert).execute()
|
|
|
|
# 2. Poblar ROUTES (Depende de units)
|
|
print("2. Poblando tabla 'routes'...")
|
|
routes_to_insert = []
|
|
for r in rutas_data:
|
|
routes_to_insert.append({
|
|
"id": r["routeId"],
|
|
"name": f"Ruta {r['routeId'].split('-')[1]}",
|
|
"truck_id": r["truckId"],
|
|
"turno": r.get("turno", "matutino"),
|
|
"status": r.get("status", "pendiente"),
|
|
"current_position_id": 1
|
|
})
|
|
if routes_to_insert:
|
|
supabase.table("routes").upsert(routes_to_insert).execute()
|
|
|
|
# 3. Poblar ROUTE_POSITIONS (Depende de routes)
|
|
print("3. Poblando tabla 'route_positions'...")
|
|
positions_to_insert = []
|
|
for r in rutas_data:
|
|
for pos in r.get("positions", []):
|
|
positions_to_insert.append({
|
|
"route_id": r["routeId"],
|
|
"position_id": pos["positionId"],
|
|
"lat": pos["lat"],
|
|
"lng": pos["lng"],
|
|
"speed": pos.get("speed", 0),
|
|
"ts": pos.get("ts")
|
|
})
|
|
if positions_to_insert:
|
|
supabase.table("route_positions").upsert(positions_to_insert).execute()
|
|
|
|
# 4. Poblar COLONIAS (Depende de routes)
|
|
print("4. Poblando tabla 'colonias'...")
|
|
if colonias_data:
|
|
colonias_to_insert = []
|
|
for c in colonias_data:
|
|
colonias_to_insert.append({
|
|
"nombre": c["colonia"],
|
|
"route_id": c["routeId"],
|
|
"turno": c["turno"],
|
|
"horario_estimado": c["horario_estimado"]
|
|
})
|
|
supabase.table("colonias").upsert(colonias_to_insert).execute()
|
|
|
|
print("✅ Seed completado con éxito. Base de datos operativa para la app.")
|
|
|
|
if __name__ == "__main__":
|
|
main() |