Add 'Ver tablas' button to list Firebird tables
This commit is contained in:
+228
-193
@@ -1,193 +1,228 @@
|
||||
from fastapi import APIRouter, Request, Form, Depends
|
||||
from fastapi.responses import RedirectResponse, JSONResponse
|
||||
from app.database import get_connection
|
||||
from app.auth import get_current_user
|
||||
from app.models import QueryCreate
|
||||
|
||||
router = APIRouter(prefix="/queries", tags=["queries"])
|
||||
|
||||
QUERY_DEFAULTS = [
|
||||
{
|
||||
"name": "Terceros - Datos del paciente",
|
||||
"query_type": "terceros",
|
||||
"query_text": """SELECT
|
||||
p.TIPO_DOCUMENTO as tipo_documento,
|
||||
p.NUMERO_DOCUMENTO as numero_documento,
|
||||
p.PRIMER_NOMBRE as primer_nombre,
|
||||
p.SEGUNDO_NOMBRE as segundo_nombre,
|
||||
p.PRIMER_APELLIDO as primer_apellido,
|
||||
p.SEGUNDO_APELLIDO as segundo_apellido,
|
||||
p.FECHA_NACIMIENTO as fecha_nacimiento,
|
||||
p.SEXO as cod_sexo,
|
||||
p.COD_ENTIDAD as cod_entidad,
|
||||
p.TIPO_USUARIO as tipo_usuario,
|
||||
p.COD_MUNICIPIO as cod_municipio,
|
||||
p.ZONA as cod_zona,
|
||||
p.DIRECCION as direccion
|
||||
FROM USUAHOS p
|
||||
WHERE p.NUMERO_DOCUMENTO = :doc_num""",
|
||||
"description": "Consulta datos maestros del paciente por documento"
|
||||
},
|
||||
{
|
||||
"name": "Procedimientos por factura",
|
||||
"query_type": "transaccion",
|
||||
"query_text": """SELECT
|
||||
s.CODIGO_CUP as cod_procedimiento,
|
||||
s.FECHA_ATENCION as fecha_atencion,
|
||||
s.COD_DIAGNOSTICO as cod_diagnostico,
|
||||
s.FINALIDAD as finalidad,
|
||||
s.VIA_INGRESO as via_ingreso,
|
||||
s.MODALIDAD as modalidad,
|
||||
s.GRUPO_SERVICIO as grupo_servicio,
|
||||
s.COD_SERVICIO as cod_servicio,
|
||||
s.COD_PRESTADOR as cod_prestador,
|
||||
s.TIPO_DOC_PROFESIONAL as tipo_doc_profesional,
|
||||
s.NUM_DOC_PROFESIONAL as num_doc_profesional,
|
||||
s.VR_SERVICIO as vr_servicio,
|
||||
s.VALOR_PAGO_MODERADOR as valor_pago_moderador,
|
||||
s.CONCEPTO_RECAUDO as concepto_recaudo,
|
||||
s.NUM_AUTORIZACION as num_autorizacion
|
||||
FROM SERVICIOS s
|
||||
WHERE s.NUM_FACTURA = :factura
|
||||
AND s.FECHA_ATENCION BETWEEN :fecha_ini AND :fecha_fin""",
|
||||
"description": "Consulta procedimientos por factura y rango de fechas"
|
||||
},
|
||||
{
|
||||
"name": "Procedimientos por fecha",
|
||||
"query_type": "transaccion",
|
||||
"query_text": """SELECT
|
||||
s.FACTURA as num_factura,
|
||||
s.CODIGO_CUP as cod_procedimiento,
|
||||
s.FECHA_ATENCION as fecha_atencion,
|
||||
s.COD_DIAGNOSTICO as cod_diagnostico,
|
||||
s.FINALIDAD as finalidad,
|
||||
s.VIA_INGRESO as via_ingreso,
|
||||
s.MODALIDAD as modalidad,
|
||||
s.GRUPO_SERVICIO as grupo_servicio,
|
||||
s.COD_SERVICIO as cod_servicio,
|
||||
s.COD_PRESTADOR as cod_prestador,
|
||||
s.TIPO_DOC_PROFESIONAL as tipo_doc_profesional,
|
||||
s.NUM_DOC_PROFESIONAL as num_doc_profesional,
|
||||
s.VR_SERVICIO as vr_servicio,
|
||||
p.TIPO_DOCUMENTO as tipo_doc_paciente,
|
||||
p.NUMERO_DOCUMENTO as num_doc_paciente
|
||||
FROM SERVICIOS s
|
||||
JOIN USUAHOS p ON s.COD_PACIENTE = p.COD_PACIENTE
|
||||
WHERE s.FECHA_ATENCION BETWEEN :fecha_ini AND :fecha_fin""",
|
||||
"description": "Consulta todos los procedimientos en rango de fechas"
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def ensure_defaults():
|
||||
conn = get_connection()
|
||||
for q in QUERY_DEFAULTS:
|
||||
exists = conn.execute(
|
||||
"SELECT id FROM queries WHERE name = ?", (q["name"],)
|
||||
).fetchone()
|
||||
if not exists:
|
||||
conn.execute(
|
||||
"INSERT INTO queries (name, query_type, query_text, description) VALUES (?, ?, ?, ?)",
|
||||
(q["name"], q["query_type"], q["query_text"], q["description"]),
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def queries_page(request: Request, user: dict = Depends(get_current_user)):
|
||||
ensure_defaults()
|
||||
conn = get_connection()
|
||||
queries = conn.execute("SELECT * FROM queries ORDER BY query_type, name").fetchall()
|
||||
conn.close()
|
||||
return request.app.state.templates.TemplateResponse("queries.html", {
|
||||
"request": request, "user": user, "queries": queries
|
||||
})
|
||||
|
||||
|
||||
@router.post("/create")
|
||||
async def query_create(
|
||||
request: Request,
|
||||
user: dict = Depends(get_current_user),
|
||||
name: str = Form(...),
|
||||
query_type: str = Form(...),
|
||||
query_text: str = Form(...),
|
||||
description: str = Form(""),
|
||||
):
|
||||
conn = get_connection()
|
||||
conn.execute(
|
||||
"INSERT INTO queries (name, query_type, query_text, description) VALUES (?, ?, ?, ?)",
|
||||
(name, query_type, query_text, description),
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return RedirectResponse("/queries", status_code=302)
|
||||
|
||||
|
||||
@router.post("/update/{query_id}")
|
||||
async def query_update(
|
||||
query_id: int,
|
||||
request: Request,
|
||||
user: dict = Depends(get_current_user),
|
||||
name: str = Form(...),
|
||||
query_text: str = Form(...),
|
||||
description: str = Form(""),
|
||||
):
|
||||
conn = get_connection()
|
||||
conn.execute(
|
||||
"UPDATE queries SET name = ?, query_text = ?, description = ? WHERE id = ?",
|
||||
(name, query_text, description, query_id),
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return RedirectResponse("/queries", status_code=302)
|
||||
|
||||
|
||||
@router.post("/delete/{query_id}")
|
||||
async def query_delete(query_id: int, user: dict = Depends(get_current_user)):
|
||||
conn = get_connection()
|
||||
conn.execute("DELETE FROM queries WHERE id = ?", (query_id,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return RedirectResponse("/queries", status_code=302)
|
||||
|
||||
|
||||
@router.post("/test")
|
||||
async def query_test(
|
||||
request: Request,
|
||||
query_id: int = Form(...),
|
||||
user: dict = Depends(get_current_user),
|
||||
):
|
||||
from app.services.firebird_service import FirebirdService
|
||||
|
||||
conn = get_connection()
|
||||
q = conn.execute("SELECT * FROM queries WHERE id = ?", (query_id,)).fetchone()
|
||||
configs = {row["key"]: row["value"] for row in conn.execute("SELECT * FROM config").fetchall()}
|
||||
conn.close()
|
||||
|
||||
if not q:
|
||||
return JSONResponse({"error": "Consulta no encontrada"}, status_code=404)
|
||||
|
||||
fb = FirebirdService()
|
||||
fb_success, fb_msg = fb.connect(
|
||||
configs.get("firebird_host", "localhost"),
|
||||
int(configs.get("firebird_port", 3050)),
|
||||
configs.get("firebird_database", ""),
|
||||
configs.get("firebird_user", "SYSDBA"),
|
||||
configs.get("firebird_password", "masterkey"),
|
||||
)
|
||||
if not fb_success:
|
||||
return JSONResponse({"error": f"Error Firebird: {fb_msg}"}, status_code=400)
|
||||
|
||||
success, fb_err, rows = fb.execute_query(q["query_text"], {})
|
||||
fb.disconnect()
|
||||
|
||||
if not success:
|
||||
return JSONResponse({"error": fb_err}, status_code=400)
|
||||
|
||||
limit = rows[:20] if rows else []
|
||||
return JSONResponse({
|
||||
"rows": limit,
|
||||
"total": len(rows),
|
||||
"columns": list(limit[0].keys()) if limit else []
|
||||
})
|
||||
from fastapi import APIRouter, Request, Form, Depends␍
|
||||
from fastapi.responses import RedirectResponse, JSONResponse␍
|
||||
from app.database import get_connection␍
|
||||
from app.auth import get_current_user␍
|
||||
from app.models import QueryCreate␍
|
||||
␍
|
||||
router = APIRouter(prefix="/queries", tags=["queries"])␍
|
||||
␍
|
||||
QUERY_DEFAULTS = [␍
|
||||
{␍
|
||||
"name": "Terceros - Datos del paciente",␍
|
||||
"query_type": "terceros",␍
|
||||
"query_text": """SELECT␍
|
||||
p.TIPO_DOCUMENTO as tipo_documento,␍
|
||||
p.NUMERO_DOCUMENTO as numero_documento,␍
|
||||
p.PRIMER_NOMBRE as primer_nombre,␍
|
||||
p.SEGUNDO_NOMBRE as segundo_nombre,␍
|
||||
p.PRIMER_APELLIDO as primer_apellido,␍
|
||||
p.SEGUNDO_APELLIDO as segundo_apellido,␍
|
||||
p.FECHA_NACIMIENTO as fecha_nacimiento,␍
|
||||
p.SEXO as cod_sexo,␍
|
||||
p.COD_ENTIDAD as cod_entidad,␍
|
||||
p.TIPO_USUARIO as tipo_usuario,␍
|
||||
p.COD_MUNICIPIO as cod_municipio,␍
|
||||
p.ZONA as cod_zona,␍
|
||||
p.DIRECCION as direccion␍
|
||||
FROM USUAHOS p␍
|
||||
WHERE p.NUMERO_DOCUMENTO = :doc_num""",␍
|
||||
"description": "Consulta datos maestros del paciente por documento"␍
|
||||
},␍
|
||||
{␍
|
||||
"name": "Procedimientos por factura",␍
|
||||
"query_type": "transaccion",␍
|
||||
"query_text": """SELECT␍
|
||||
s.CODIGO_CUP as cod_procedimiento,␍
|
||||
s.FECHA_ATENCION as fecha_atencion,␍
|
||||
s.COD_DIAGNOSTICO as cod_diagnostico,␍
|
||||
s.FINALIDAD as finalidad,␍
|
||||
s.VIA_INGRESO as via_ingreso,␍
|
||||
s.MODALIDAD as modalidad,␍
|
||||
s.GRUPO_SERVICIO as grupo_servicio,␍
|
||||
s.COD_SERVICIO as cod_servicio,␍
|
||||
s.COD_PRESTADOR as cod_prestador,␍
|
||||
s.TIPO_DOC_PROFESIONAL as tipo_doc_profesional,␍
|
||||
s.NUM_DOC_PROFESIONAL as num_doc_profesional,␍
|
||||
s.VR_SERVICIO as vr_servicio,␍
|
||||
s.VALOR_PAGO_MODERADOR as valor_pago_moderador,␍
|
||||
s.CONCEPTO_RECAUDO as concepto_recaudo,␍
|
||||
s.NUM_AUTORIZACION as num_autorizacion␍
|
||||
FROM SERVICIOS s␍
|
||||
WHERE s.NUM_FACTURA = :factura␍
|
||||
AND s.FECHA_ATENCION BETWEEN :fecha_ini AND :fecha_fin""",␍
|
||||
"description": "Consulta procedimientos por factura y rango de fechas"␍
|
||||
},␍
|
||||
{␍
|
||||
"name": "Procedimientos por fecha",␍
|
||||
"query_type": "transaccion",␍
|
||||
"query_text": """SELECT␍
|
||||
s.FACTURA as num_factura,␍
|
||||
s.CODIGO_CUP as cod_procedimiento,␍
|
||||
s.FECHA_ATENCION as fecha_atencion,␍
|
||||
s.COD_DIAGNOSTICO as cod_diagnostico,␍
|
||||
s.FINALIDAD as finalidad,␍
|
||||
s.VIA_INGRESO as via_ingreso,␍
|
||||
s.MODALIDAD as modalidad,␍
|
||||
s.GRUPO_SERVICIO as grupo_servicio,␍
|
||||
s.COD_SERVICIO as cod_servicio,␍
|
||||
s.COD_PRESTADOR as cod_prestador,␍
|
||||
s.TIPO_DOC_PROFESIONAL as tipo_doc_profesional,␍
|
||||
s.NUM_DOC_PROFESIONAL as num_doc_profesional,␍
|
||||
s.VR_SERVICIO as vr_servicio,␍
|
||||
p.TIPO_DOCUMENTO as tipo_doc_paciente,␍
|
||||
p.NUMERO_DOCUMENTO as num_doc_paciente␍
|
||||
FROM SERVICIOS s␍
|
||||
JOIN USUAHOS p ON s.COD_PACIENTE = p.COD_PACIENTE␍
|
||||
WHERE s.FECHA_ATENCION BETWEEN :fecha_ini AND :fecha_fin""",␍
|
||||
"description": "Consulta todos los procedimientos en rango de fechas"␍
|
||||
},␍
|
||||
]␍
|
||||
␍
|
||||
␍
|
||||
def ensure_defaults():␍
|
||||
conn = get_connection()␍
|
||||
for q in QUERY_DEFAULTS:␍
|
||||
exists = conn.execute(␍
|
||||
"SELECT id FROM queries WHERE name = ?", (q["name"],)␍
|
||||
).fetchone()␍
|
||||
if not exists:␍
|
||||
conn.execute(␍
|
||||
"INSERT INTO queries (name, query_type, query_text, description) VALUES (?, ?, ?, ?)",␍
|
||||
(q["name"], q["query_type"], q["query_text"], q["description"]),␍
|
||||
)␍
|
||||
conn.commit()␍
|
||||
conn.close()␍
|
||||
␍
|
||||
␍
|
||||
@router.get("")␍
|
||||
async def queries_page(request: Request, user: dict = Depends(get_current_user)):␍
|
||||
ensure_defaults()␍
|
||||
conn = get_connection()␍
|
||||
queries = conn.execute("SELECT * FROM queries ORDER BY query_type, name").fetchall()␍
|
||||
conn.close()␍
|
||||
return request.app.state.templates.TemplateResponse("queries.html", {␍
|
||||
"request": request, "user": user, "queries": queries␍
|
||||
})␍
|
||||
␍
|
||||
␍
|
||||
@router.post("/create")␍
|
||||
async def query_create(␍
|
||||
request: Request,␍
|
||||
user: dict = Depends(get_current_user),␍
|
||||
name: str = Form(...),␍
|
||||
query_type: str = Form(...),␍
|
||||
query_text: str = Form(...),␍
|
||||
description: str = Form(""),␍
|
||||
):␍
|
||||
conn = get_connection()␍
|
||||
conn.execute(␍
|
||||
"INSERT INTO queries (name, query_type, query_text, description) VALUES (?, ?, ?, ?)",␍
|
||||
(name, query_type, query_text, description),␍
|
||||
)␍
|
||||
conn.commit()␍
|
||||
conn.close()␍
|
||||
return RedirectResponse("/queries", status_code=302)␍
|
||||
␍
|
||||
␍
|
||||
@router.post("/update/{query_id}")␍
|
||||
async def query_update(␍
|
||||
query_id: int,␍
|
||||
request: Request,␍
|
||||
user: dict = Depends(get_current_user),␍
|
||||
name: str = Form(...),␍
|
||||
query_text: str = Form(...),␍
|
||||
description: str = Form(""),␍
|
||||
):␍
|
||||
conn = get_connection()␍
|
||||
conn.execute(␍
|
||||
"UPDATE queries SET name = ?, query_text = ?, description = ? WHERE id = ?",␍
|
||||
(name, query_text, description, query_id),␍
|
||||
)␍
|
||||
conn.commit()␍
|
||||
conn.close()␍
|
||||
return RedirectResponse("/queries", status_code=302)␍
|
||||
␍
|
||||
␍
|
||||
@router.post("/delete/{query_id}")␍
|
||||
async def query_delete(query_id: int, user: dict = Depends(get_current_user)):␍
|
||||
conn = get_connection()␍
|
||||
conn.execute("DELETE FROM queries WHERE id = ?", (query_id,))␍
|
||||
conn.commit()␍
|
||||
conn.close()␍
|
||||
return RedirectResponse("/queries", status_code=302)␍
|
||||
␍
|
||||
␍
|
||||
@router.post("/tablas")␍
|
||||
async def listar_tablas(user: dict = Depends(get_current_user)):␍
|
||||
from app.services.firebird_service import FirebirdService␍
|
||||
conn = get_connection()␍
|
||||
configs = {row["key"]: row["value"] for row in conn.execute("SELECT * FROM config").fetchall()}␍
|
||||
conn.close()␍
|
||||
␍
|
||||
fb = FirebirdService()␍
|
||||
fb_success, fb_msg = fb.connect(␍
|
||||
configs.get("firebird_host", "localhost"),␍
|
||||
int(configs.get("firebird_port", 3050)),␍
|
||||
configs.get("firebird_database", ""),␍
|
||||
configs.get("firebird_user", "SYSDBA"),␍
|
||||
configs.get("firebird_password", "masterkey"),␍
|
||||
)␍
|
||||
if not fb_success:␍
|
||||
return JSONResponse({"error": f"Error Firebird: {fb_msg}"}, status_code=400)␍
|
||||
␍
|
||||
success, fb_err, rows = fb.execute_query("""␍
|
||||
SELECT RDB$RELATION_NAME as nombre␍
|
||||
FROM RDB$RELATIONS␍
|
||||
WHERE RDB$SYSTEM_FLAG = 0␍
|
||||
AND RDB$RELATION_NAME NOT LIKE 'RDB$%'␍
|
||||
ORDER BY 1␍
|
||||
""", {})␍
|
||||
fb.disconnect()␍
|
||||
␍
|
||||
if not success:␍
|
||||
return JSONResponse({"error": fb_err}, status_code=400)␍
|
||||
␍
|
||||
return JSONResponse({␍
|
||||
"tablas": [r["NOMBRE"].strip() for r in rows]␍
|
||||
})␍
|
||||
␍
|
||||
␍
|
||||
@router.post("/test")␍
|
||||
async def query_test(␍
|
||||
request: Request,␍
|
||||
query_id: int = Form(...),␍
|
||||
user: dict = Depends(get_current_user),␍
|
||||
):␍
|
||||
from app.services.firebird_service import FirebirdService␍
|
||||
␍
|
||||
conn = get_connection()␍
|
||||
q = conn.execute("SELECT * FROM queries WHERE id = ?", (query_id,)).fetchone()␍
|
||||
configs = {row["key"]: row["value"] for row in conn.execute("SELECT * FROM config").fetchall()}␍
|
||||
conn.close()␍
|
||||
␍
|
||||
if not q:␍
|
||||
return JSONResponse({"error": "Consulta no encontrada"}, status_code=404)␍
|
||||
␍
|
||||
fb = FirebirdService()␍
|
||||
fb_success, fb_msg = fb.connect(␍
|
||||
configs.get("firebird_host", "localhost"),␍
|
||||
int(configs.get("firebird_port", 3050)),␍
|
||||
configs.get("firebird_database", ""),␍
|
||||
configs.get("firebird_user", "SYSDBA"),␍
|
||||
configs.get("firebird_password", "masterkey"),␍
|
||||
)␍
|
||||
if not fb_success:␍
|
||||
return JSONResponse({"error": f"Error Firebird: {fb_msg}"}, status_code=400)␍
|
||||
␍
|
||||
success, fb_err, rows = fb.execute_query(q["query_text"], {})␍
|
||||
fb.disconnect()␍
|
||||
␍
|
||||
if not success:␍
|
||||
return JSONResponse({"error": fb_err}, status_code=400)␍
|
||||
␍
|
||||
limit = rows[:20] if rows else []␍
|
||||
return JSONResponse({␍
|
||||
"rows": limit,␍
|
||||
"total": len(rows),␍
|
||||
"columns": list(limit[0].keys()) if limit else []␍
|
||||
})␍
|
||||
|
||||
+172
-152
@@ -1,152 +1,172 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Consultas SQL{% endblock %}
|
||||
{% block header %}Consultas SQL{% endblock %}
|
||||
{% block content %}
|
||||
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
<div class="lg:col-span-1">
|
||||
<div class="bg-white rounded-xl shadow-sm border border-gray-200">
|
||||
<div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
|
||||
<h3 class="font-semibold text-gray-800"><i class="fas fa-list mr-2 text-blue-500"></i>Mis Consultas</h3>
|
||||
<button onclick="document.getElementById('modal-new-query').classList.remove('hidden')"
|
||||
class="text-blue-600 hover:text-blue-800"><i class="fas fa-plus"></i></button>
|
||||
</div>
|
||||
<div class="p-4 space-y-2">
|
||||
{% for q in queries %}
|
||||
<div class="p-3 rounded-lg border border-gray-200 hover:border-blue-300">
|
||||
<div onclick="editQuery({{ q.id }}, '{{ q.name }}', '{{ q.query_type }}', `{{ q.query_text|e }}`, `{{ q.description|e }}`)" class="cursor-pointer">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="font-medium text-sm text-gray-800">{{ q.name }}</span>
|
||||
<span class="px-2 py-0.5 rounded text-xs font-medium {% if q.query_type == 'terceros' %}bg-blue-100 text-blue-700{% else %}bg-purple-100 text-purple-700{% endif %}">
|
||||
{{ q.query_type }}
|
||||
</span>
|
||||
</div>
|
||||
<p class="text-xs text-gray-500 mt-1 truncate">{{ q.description or 'Sin descripción' }}</p>
|
||||
</div>
|
||||
<button onclick="ejecutarTest(this, {{ q.id }})" class="mt-2 text-xs text-green-600 hover:text-green-800">
|
||||
<i class="fas fa-play mr-1"></i> Probar
|
||||
</button>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="lg:col-span-2">
|
||||
<div class="bg-white rounded-xl shadow-sm border border-gray-200">
|
||||
<div class="px-6 py-4 border-b border-gray-200">
|
||||
<h3 class="font-semibold text-gray-800"><i class="fas fa-code mr-2 text-blue-500"></i>Editor SQL</h3>
|
||||
</div>
|
||||
<div class="p-6">
|
||||
<form method="POST" action="/queries/create" class="space-y-4">
|
||||
<input type="hidden" name="query_id" id="query_id" value="">
|
||||
<div class="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Nombre</label>
|
||||
<input type="text" name="name" id="q_name" required
|
||||
class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" placeholder="Nombre descriptivo">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Tipo</label>
|
||||
<select name="query_type" id="q_type"
|
||||
class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm">
|
||||
<option value="terceros">Terceros (datos paciente)</option>
|
||||
<option value="transaccion">Transacción (procedimientos)</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Consulta SQL</label>
|
||||
<textarea name="query_text" id="q_text" rows="10" required
|
||||
class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono bg-gray-50"
|
||||
placeholder="SELECT ... FROM ... WHERE ..."></textarea>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Descripción</label>
|
||||
<input type="text" name="description" id="q_desc"
|
||||
class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
|
||||
placeholder="¿Qué hace esta consulta?">
|
||||
</div>
|
||||
<div class="flex space-x-3">
|
||||
<button type="submit"
|
||||
class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium">
|
||||
<i class="fas fa-save mr-1"></i> Guardar
|
||||
</button>
|
||||
<button type="button" onclick="cancelEdit()"
|
||||
class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg text-sm font-medium hover:bg-gray-200 hidden" id="btn-cancel">
|
||||
<i class="fas fa-times mr-1"></i> Cancelar
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 bg-blue-50 rounded-xl border border-blue-200 p-4">
|
||||
<h4 class="text-sm font-medium text-blue-800"><i class="fas fa-info-circle mr-1"></i> Parámetros disponibles</h4>
|
||||
<p class="text-xs text-blue-600 mt-1">
|
||||
Usa <code class="bg-blue-100 px-1 rounded">:doc_num</code> para filtro por documento,
|
||||
<code class="bg-blue-100 px-1 rounded">:factura</code> para filtro por factura,
|
||||
<code class="bg-blue-100 px-1 rounded">:fecha_ini</code> y <code class="bg-blue-100 px-1 rounded">:fecha_fin</code> para rango de fechas.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function editQuery(id, name, type, text, desc) {
|
||||
document.getElementById('query_id').value = id;
|
||||
document.getElementById('q_name').value = name;
|
||||
document.getElementById('q_type').value = type;
|
||||
document.getElementById('q_text').value = text;
|
||||
document.getElementById('q_desc').value = desc;
|
||||
document.getElementById('btn-cancel').classList.remove('hidden');
|
||||
document.querySelector('form').action = '/queries/update/' + id;
|
||||
}
|
||||
|
||||
function cancelEdit() {
|
||||
document.getElementById('query_id').value = '';
|
||||
document.getElementById('q_name').value = '';
|
||||
document.getElementById('q_text').value = '';
|
||||
document.getElementById('q_desc').value = '';
|
||||
document.getElementById('btn-cancel').classList.add('hidden');
|
||||
document.querySelector('form').action = '/queries/create';
|
||||
}
|
||||
|
||||
async function ejecutarTest(btn, queryId) {
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i> Probando...';
|
||||
|
||||
try {
|
||||
const form = new FormData();
|
||||
form.append('query_id', queryId);
|
||||
const resp = await fetch('/queries/test', { method: 'POST', body: form });
|
||||
const data = await resp.json();
|
||||
|
||||
if (data.error) {
|
||||
showToast(data.error, 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
let html = '<table class="w-full text-xs border-collapse"><thead><tr class="bg-gray-100">';
|
||||
data.columns.forEach(c => { html += '<th class="p-2 border text-left font-semibold">' + c + '</th>'; });
|
||||
html += '</tr></thead><tbody>';
|
||||
data.rows.forEach(r => {
|
||||
html += '<tr class="hover:bg-gray-50">';
|
||||
data.columns.forEach(c => { html += '<td class="p-2 border">' + (r[c] ?? '') + '</td>'; });
|
||||
html += '</tr>';
|
||||
});
|
||||
html += '</tbody></table>';
|
||||
html += '<p class="text-xs text-gray-500 mt-2">Total: ' + data.total + ' registros (mostrando ' + data.rows.length + ')</p>';
|
||||
|
||||
const modal = document.createElement('div');
|
||||
modal.className = 'fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50';
|
||||
modal.innerHTML = '<div class="bg-white rounded-xl shadow-xl max-w-4xl w-full mx-4 max-h-[80vh] overflow-auto p-6"><div class="flex justify-between items-center mb-4"><h3 class="font-semibold text-lg">Resultado</h3><button onclick="this.closest(\'.fixed\').remove()" class="text-gray-400 hover:text-gray-600"><i class="fas fa-times text-xl"></i></button></div>' + html + '</div>';
|
||||
document.body.appendChild(modal);
|
||||
} catch(e) {
|
||||
showToast('Error: ' + e.message, 'error');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = '<i class="fas fa-play mr-1"></i> Probar';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
{% extends "base.html" %}␍
|
||||
{% block title %}Consultas SQL{% endblock %}␍
|
||||
{% block header %}Consultas SQL{% endblock %}␍
|
||||
{% block content %}␍
|
||||
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">␍
|
||||
<div class="lg:col-span-1">␍
|
||||
<div class="bg-white rounded-xl shadow-sm border border-gray-200">␍
|
||||
<div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">␍
|
||||
<h3 class="font-semibold text-gray-800"><i class="fas fa-list mr-2 text-blue-500"></i>Mis Consultas</h3>␍
|
||||
<button onclick="document.getElementById('modal-new-query').classList.remove('hidden')"␍
|
||||
class="text-blue-600 hover:text-blue-800"><i class="fas fa-plus"></i></button>␍
|
||||
</div>␍
|
||||
<div class="p-4 space-y-2">␍
|
||||
{% for q in queries %}␍
|
||||
<div class="p-3 rounded-lg border border-gray-200 hover:border-blue-300">␍
|
||||
<div onclick="editQuery({{ q.id }}, '{{ q.name }}', '{{ q.query_type }}', `{{ q.query_text|e }}`, `{{ q.description|e }}`)" class="cursor-pointer">␍
|
||||
<div class="flex items-center justify-between">␍
|
||||
<span class="font-medium text-sm text-gray-800">{{ q.name }}</span>␍
|
||||
<span class="px-2 py-0.5 rounded text-xs font-medium {% if q.query_type == 'terceros' %}bg-blue-100 text-blue-700{% else %}bg-purple-100 text-purple-700{% endif %}">␍
|
||||
{{ q.query_type }}␍
|
||||
</span>␍
|
||||
</div>␍
|
||||
<p class="text-xs text-gray-500 mt-1 truncate">{{ q.description or 'Sin descripción' }}</p>␍
|
||||
</div>␍
|
||||
<button onclick="ejecutarTest(this, {{ q.id }})" class="mt-2 text-xs text-green-600 hover:text-green-800">␍
|
||||
<i class="fas fa-play mr-1"></i> Probar␍
|
||||
</button>␍
|
||||
</div>␍
|
||||
{% endfor %}␍
|
||||
</div>␍
|
||||
</div>␍
|
||||
</div>␍
|
||||
␍
|
||||
<div class="lg:col-span-2">␍
|
||||
<div class="bg-white rounded-xl shadow-sm border border-gray-200">␍
|
||||
<div class="px-6 py-4 border-b border-gray-200">␍
|
||||
<h3 class="font-semibold text-gray-800"><i class="fas fa-code mr-2 text-blue-500"></i>Editor SQL</h3>␍
|
||||
</div>␍
|
||||
<div class="p-6">␍
|
||||
<form method="POST" action="/queries/create" class="space-y-4">␍
|
||||
<input type="hidden" name="query_id" id="query_id" value="">␍
|
||||
<div class="grid grid-cols-2 gap-4">␍
|
||||
<div>␍
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Nombre</label>␍
|
||||
<input type="text" name="name" id="q_name" required␍
|
||||
class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm" placeholder="Nombre descriptivo">␍
|
||||
</div>␍
|
||||
<div>␍
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Tipo</label>␍
|
||||
<select name="query_type" id="q_type"␍
|
||||
class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm">␍
|
||||
<option value="terceros">Terceros (datos paciente)</option>␍
|
||||
<option value="transaccion">Transacción (procedimientos)</option>␍
|
||||
</select>␍
|
||||
</div>␍
|
||||
</div>␍
|
||||
<div>␍
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Consulta SQL</label>␍
|
||||
<textarea name="query_text" id="q_text" rows="10" required␍
|
||||
class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono bg-gray-50"␍
|
||||
placeholder="SELECT ... FROM ... WHERE ..."></textarea>␍
|
||||
</div>␍
|
||||
<div>␍
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Descripción</label>␍
|
||||
<input type="text" name="description" id="q_desc"␍
|
||||
class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"␍
|
||||
placeholder="¿Qué hace esta consulta?">␍
|
||||
</div>␍
|
||||
<div class="flex space-x-3">␍
|
||||
<button type="submit"␍
|
||||
class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium">␍
|
||||
<i class="fas fa-save mr-1"></i> Guardar␍
|
||||
</button>␍
|
||||
<button type="button" onclick="cancelEdit()"␍
|
||||
class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg text-sm font-medium hover:bg-gray-200 hidden" id="btn-cancel">␍
|
||||
<i class="fas fa-times mr-1"></i> Cancelar␍
|
||||
</button>␍
|
||||
</div>␍
|
||||
</form>␍
|
||||
</div>␍
|
||||
</div>␍
|
||||
␍
|
||||
<div class="mt-4 bg-blue-50 rounded-xl border border-blue-200 p-4">␍
|
||||
<h4 class="text-sm font-medium text-blue-800"><i class="fas fa-info-circle mr-1"></i> Parámetros disponibles</h4>␍
|
||||
<p class="text-xs text-blue-600 mt-1">␍
|
||||
Usa <code class="bg-blue-100 px-1 rounded">:doc_num</code> para filtro por documento,␍
|
||||
<code class="bg-blue-100 px-1 rounded">:factura</code> para filtro por factura,␍
|
||||
<code class="bg-blue-100 px-1 rounded">:fecha_ini</code> y <code class="bg-blue-100 px-1 rounded">:fecha_fin</code> para rango de fechas.␍
|
||||
</p>␍
|
||||
<button onclick="listarTablas(this)" class="mt-3 px-3 py-1.5 bg-green-600 hover:bg-green-700 text-white text-xs rounded-lg">␍
|
||||
<i class="fas fa-table mr-1"></i> Ver tablas disponibles␍
|
||||
</button>␍
|
||||
<div id="tablas-list" class="mt-2 hidden"></div>␍
|
||||
</div>␍
|
||||
</div>␍
|
||||
</div>␍
|
||||
␍
|
||||
<script>␍
|
||||
function editQuery(id, name, type, text, desc) {␍
|
||||
document.getElementById('query_id').value = id;␍
|
||||
document.getElementById('q_name').value = name;␍
|
||||
document.getElementById('q_type').value = type;␍
|
||||
document.getElementById('q_text').value = text;␍
|
||||
document.getElementById('q_desc').value = desc;␍
|
||||
document.getElementById('btn-cancel').classList.remove('hidden');␍
|
||||
document.querySelector('form').action = '/queries/update/' + id;␍
|
||||
}␍
|
||||
␍
|
||||
function cancelEdit() {␍
|
||||
document.getElementById('query_id').value = '';␍
|
||||
document.getElementById('q_name').value = '';␍
|
||||
document.getElementById('q_text').value = '';␍
|
||||
document.getElementById('q_desc').value = '';␍
|
||||
document.getElementById('btn-cancel').classList.add('hidden');␍
|
||||
document.querySelector('form').action = '/queries/create';␍
|
||||
}␍
|
||||
␍
|
||||
async function listarTablas(btn) {␍
|
||||
btn.disabled = true;␍
|
||||
btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i> Cargando...';␍
|
||||
try {␍
|
||||
const resp = await fetch('/queries/tablas', { method: 'POST' });␍
|
||||
const data = await resp.json();␍
|
||||
if (data.error) { showToast(data.error, 'error'); return; }␍
|
||||
const div = document.getElementById('tablas-list');␍
|
||||
div.innerHTML = '<div class="max-h-40 overflow-y-auto mt-2"><div class="grid grid-cols-3 gap-1">' +␍
|
||||
data.tablas.map(t => '<code class="bg-white px-2 py-1 rounded border text-xs">' + t + '</code>').join('') +␍
|
||||
'</div></div>';␍
|
||||
div.classList.remove('hidden');␍
|
||||
} catch(e) { showToast('Error: ' + e.message, 'error'); }␍
|
||||
finally { btn.disabled = false; btn.innerHTML = '<i class="fas fa-table mr-1"></i> Ver tablas disponibles'; }␍
|
||||
}␍
|
||||
␍
|
||||
async function ejecutarTest(btn, queryId) {␍
|
||||
btn.disabled = true;␍
|
||||
btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i> Probando...';␍
|
||||
␍
|
||||
try {␍
|
||||
const form = new FormData();␍
|
||||
form.append('query_id', queryId);␍
|
||||
const resp = await fetch('/queries/test', { method: 'POST', body: form });␍
|
||||
const data = await resp.json();␍
|
||||
␍
|
||||
if (data.error) {␍
|
||||
showToast(data.error, 'error');␍
|
||||
return;␍
|
||||
}␍
|
||||
␍
|
||||
let html = '<table class="w-full text-xs border-collapse"><thead><tr class="bg-gray-100">';␍
|
||||
data.columns.forEach(c => { html += '<th class="p-2 border text-left font-semibold">' + c + '</th>'; });␍
|
||||
html += '</tr></thead><tbody>';␍
|
||||
data.rows.forEach(r => {␍
|
||||
html += '<tr class="hover:bg-gray-50">';␍
|
||||
data.columns.forEach(c => { html += '<td class="p-2 border">' + (r[c] ?? '') + '</td>'; });␍
|
||||
html += '</tr>';␍
|
||||
});␍
|
||||
html += '</tbody></table>';␍
|
||||
html += '<p class="text-xs text-gray-500 mt-2">Total: ' + data.total + ' registros (mostrando ' + data.rows.length + ')</p>';␍
|
||||
␍
|
||||
const modal = document.createElement('div');␍
|
||||
modal.className = 'fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50';␍
|
||||
modal.innerHTML = '<div class="bg-white rounded-xl shadow-xl max-w-4xl w-full mx-4 max-h-[80vh] overflow-auto p-6"><div class="flex justify-between items-center mb-4"><h3 class="font-semibold text-lg">Resultado</h3><button onclick="this.closest(\'.fixed\').remove()" class="text-gray-400 hover:text-gray-600"><i class="fas fa-times text-xl"></i></button></div>' + html + '</div>';␍
|
||||
document.body.appendChild(modal);␍
|
||||
} catch(e) {␍
|
||||
showToast('Error: ' + e.message, 'error');␍
|
||||
} finally {␍
|
||||
btn.disabled = false;␍
|
||||
btn.innerHTML = '<i class="fas fa-play mr-1"></i> Probar';␍
|
||||
}␍
|
||||
}␍
|
||||
</script>␍
|
||||
{% endblock %}␍
|
||||
|
||||
Reference in New Issue
Block a user