feat(medicos): módulo CRUD de médicos con tabla, búsqueda y modal edición
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
665fee99a9
commit
1574f12275
@@ -0,0 +1,12 @@
|
||||
CREATE TABLE IF NOT EXISTS medicos (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
codigo VARCHAR(20) NOT NULL UNIQUE,
|
||||
nombres VARCHAR(100) NOT NULL,
|
||||
apellidos VARCHAR(100) NOT NULL,
|
||||
cod_especialidad VARCHAR(50) DEFAULT NULL,
|
||||
docidmedico VARCHAR(30) DEFAULT NULL,
|
||||
activo TINYINT(1) NOT NULL DEFAULT 1,
|
||||
creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
actualizado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../../../config/config.php';
|
||||
if (!isUserLoggedIn()) { http_response_code(401); echo json_encode(['ok'=>false,'error'=>'No autorizado']); exit; }
|
||||
|
||||
header('Content-Type: application/json');
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
echo json_encode(['ok'=>false,'error'=>'Método no permitido']); exit;
|
||||
}
|
||||
|
||||
$datos = json_decode(file_get_contents('php://input'), true) ?? [];
|
||||
$id = !empty($datos['id']) ? (int)$datos['id'] : 0;
|
||||
|
||||
if (!$id) { echo json_encode(['ok'=>false,'error'=>'ID inválido.']); exit; }
|
||||
|
||||
$pdo = Database::getInstance()->getConnection();
|
||||
$stmt = $pdo->prepare("DELETE FROM medicos WHERE id = ?");
|
||||
$stmt->execute([$id]);
|
||||
|
||||
if ($stmt->rowCount()) {
|
||||
echo json_encode(['ok'=>true,'mensaje'=>'Médico eliminado.']);
|
||||
} else {
|
||||
echo json_encode(['ok'=>false,'error'=>'Médico no encontrado.']);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../../../config/config.php';
|
||||
if (!isUserLoggedIn()) { http_response_code(401); echo json_encode(['ok'=>false,'error'=>'No autorizado']); exit; }
|
||||
|
||||
header('Content-Type: application/json');
|
||||
|
||||
$pdo = Database::getInstance()->getConnection();
|
||||
$buscar = trim($_GET['q'] ?? '');
|
||||
|
||||
if ($buscar !== '') {
|
||||
$like = '%' . $buscar . '%';
|
||||
$stmt = $pdo->prepare(
|
||||
"SELECT id, codigo, nombres, apellidos, cod_especialidad, docidmedico, activo
|
||||
FROM medicos
|
||||
WHERE nombres LIKE ? OR apellidos LIKE ? OR codigo LIKE ? OR docidmedico LIKE ?
|
||||
ORDER BY apellidos, nombres"
|
||||
);
|
||||
$stmt->execute([$like, $like, $like, $like]);
|
||||
} else {
|
||||
$stmt = $pdo->query(
|
||||
"SELECT id, codigo, nombres, apellidos, cod_especialidad, docidmedico, activo
|
||||
FROM medicos ORDER BY apellidos, nombres"
|
||||
);
|
||||
}
|
||||
|
||||
echo json_encode(['ok' => true, 'data' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../../../config/config.php';
|
||||
if (!isUserLoggedIn()) { http_response_code(401); echo json_encode(['ok'=>false,'error'=>'No autorizado']); exit; }
|
||||
|
||||
header('Content-Type: application/json');
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
echo json_encode(['ok'=>false,'error'=>'Método no permitido']); exit;
|
||||
}
|
||||
|
||||
$datos = json_decode(file_get_contents('php://input'), true) ?? [];
|
||||
$id = !empty($datos['id']) ? (int) $datos['id'] : null;
|
||||
$codigo = strtoupper(trim($datos['codigo'] ?? ''));
|
||||
$nombres = trim($datos['nombres'] ?? '');
|
||||
$apellidos = trim($datos['apellidos'] ?? '');
|
||||
$especialidad = trim($datos['cod_especialidad'] ?? '');
|
||||
$docid = trim($datos['docidmedico'] ?? '');
|
||||
|
||||
if (!$codigo) { echo json_encode(['ok'=>false,'error'=>'El código es obligatorio.']); exit; }
|
||||
if (!$nombres) { echo json_encode(['ok'=>false,'error'=>'Los nombres son obligatorios.']); exit; }
|
||||
if (!$apellidos) { echo json_encode(['ok'=>false,'error'=>'Los apellidos son obligatorios.']); exit; }
|
||||
|
||||
$pdo = Database::getInstance()->getConnection();
|
||||
|
||||
if ($id) {
|
||||
// Editar
|
||||
$stmt = $pdo->prepare(
|
||||
"UPDATE medicos SET codigo=?, nombres=?, apellidos=?, cod_especialidad=?, docidmedico=?
|
||||
WHERE id=?"
|
||||
);
|
||||
$stmt->execute([$codigo, $nombres, $apellidos, $especialidad ?: null, $docid ?: null, $id]);
|
||||
echo json_encode(['ok'=>true,'mensaje'=>'Médico actualizado correctamente.']);
|
||||
} else {
|
||||
// Crear — verificar código único
|
||||
$existe = $pdo->prepare("SELECT id FROM medicos WHERE codigo = ?");
|
||||
$existe->execute([$codigo]);
|
||||
if ($existe->fetch()) {
|
||||
echo json_encode(['ok'=>false,'error'=>"El código '$codigo' ya existe."]); exit;
|
||||
}
|
||||
$stmt = $pdo->prepare(
|
||||
"INSERT INTO medicos (codigo, nombres, apellidos, cod_especialidad, docidmedico)
|
||||
VALUES (?, ?, ?, ?, ?)"
|
||||
);
|
||||
$stmt->execute([$codigo, $nombres, $apellidos, $especialidad ?: null, $docid ?: null]);
|
||||
echo json_encode(['ok'=>true,'id'=>(int)$pdo->lastInsertId(),'mensaje'=>'Médico creado correctamente.']);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php return [
|
||||
'slug' => 'medicos',
|
||||
'name' => 'Médicos',
|
||||
'icon' => 'fas fa-user-md',
|
||||
'category' => 'clinico',
|
||||
'route' => '/erp.php?m=medicos&v=index',
|
||||
'is_active' => true,
|
||||
'sort_order' => 51,
|
||||
'oleada' => 0,
|
||||
'description' => 'Gestión del catálogo de médicos',
|
||||
'links' => [
|
||||
['name' => 'Médicos', 'icon' => 'fas fa-user-md', 'route' => '/erp.php?m=medicos&v=index'],
|
||||
],
|
||||
];
|
||||
@@ -0,0 +1,271 @@
|
||||
<?php
|
||||
require_once APP_ROOT . '/config/config.php';
|
||||
if (!isUserLoggedIn()) { header('Location: ' . BASE_URL . 'login.php'); exit; }
|
||||
|
||||
Layout::open('Médicos', 'fas fa-user-md');
|
||||
$API = BASE_URL . 'modules/medicos/api/';
|
||||
?>
|
||||
<style>
|
||||
body { background: #f1f5f9; }
|
||||
.page-header {
|
||||
background: #fff; border-bottom: 1px solid #e2e8f0;
|
||||
padding: 14px 24px; display: flex; align-items: center; gap: 12px; flex-wrap: wrap;
|
||||
}
|
||||
.page-header h1 { font-size: 1.18rem; font-weight: 700; color: #1e293b; margin: 0; flex: 1; }
|
||||
.content-wrap { max-width: 1100px; margin: 24px auto; padding: 0 16px 48px; }
|
||||
.card-box { background: #fff; border: 1px solid #e2e8f0; border-radius: 12px; overflow: hidden; }
|
||||
.card-box .toolbar {
|
||||
padding: 14px 16px; display: flex; gap: 10px; align-items: center;
|
||||
border-bottom: 1px solid #e2e8f0; flex-wrap: wrap;
|
||||
}
|
||||
.card-box .toolbar input { max-width: 260px; }
|
||||
table { width: 100%; border-collapse: collapse; font-size: .9rem; }
|
||||
thead th { background: #f8fafc; padding: 10px 14px; font-size: .72rem; text-transform: uppercase;
|
||||
letter-spacing: .07em; color: #64748b; border-bottom: 1px solid #e2e8f0; text-align: left; }
|
||||
tbody td { padding: 10px 14px; border-bottom: 1px solid #f1f5f9; color: #1e293b; vertical-align: middle; }
|
||||
tbody tr:last-child td { border-bottom: none; }
|
||||
tbody tr:hover td { background: #f8fafc; }
|
||||
.badge-esp { background: #eff6ff; color: #1d4ed8; border-radius: 20px; padding: 2px 10px;
|
||||
font-size: .75rem; font-weight: 600; }
|
||||
.acciones { display: flex; gap: 6px; }
|
||||
#tbl-empty { text-align: center; padding: 3rem; color: #94a3b8; }
|
||||
</style>
|
||||
|
||||
<div class="page-header">
|
||||
<i class="fas fa-user-md" style="font-size:1.3rem;color:#6366f1"></i>
|
||||
<h1>Médicos</h1>
|
||||
<button class="btn btn-primary btn-sm ms-auto" onclick="abrirModal()">
|
||||
<i class="fas fa-plus me-1"></i>Nuevo médico
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="content-wrap">
|
||||
<div class="card-box">
|
||||
<div class="toolbar">
|
||||
<input type="search" id="inp-buscar" class="form-control form-control-sm"
|
||||
placeholder="Buscar por nombre, código o documento…" oninput="buscar()">
|
||||
<span class="text-muted small ms-auto" id="lbl-total"></span>
|
||||
</div>
|
||||
<div style="overflow-x:auto">
|
||||
<table id="tbl-medicos">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Código</th>
|
||||
<th>Nombres</th>
|
||||
<th>Apellidos</th>
|
||||
<th>Especialidad</th>
|
||||
<th>Doc. ID</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="tbl-body">
|
||||
<tr id="tbl-empty"><td colspan="6">Cargando…</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ══ Modal agregar / editar ══════════════════════════════════════ -->
|
||||
<div class="modal fade" id="modalMedico" tabindex="-1">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="modal-titulo">Nuevo médico</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div id="modal-alert" class="alert alert-danger d-none py-2"></div>
|
||||
<input type="hidden" id="med-id">
|
||||
<div class="row g-3">
|
||||
<div class="col-4">
|
||||
<label class="form-label small fw-semibold">Código <span class="text-danger">*</span></label>
|
||||
<input type="text" id="med-codigo" class="form-control form-control-sm"
|
||||
placeholder="Ej: MED001" maxlength="20">
|
||||
</div>
|
||||
<div class="col-8">
|
||||
<label class="form-label small fw-semibold">Doc. ID Médico</label>
|
||||
<input type="text" id="med-docid" class="form-control form-control-sm"
|
||||
placeholder="Número de documento" maxlength="30">
|
||||
</div>
|
||||
<div class="col-6">
|
||||
<label class="form-label small fw-semibold">Nombres <span class="text-danger">*</span></label>
|
||||
<input type="text" id="med-nombres" class="form-control form-control-sm"
|
||||
placeholder="Nombres" maxlength="100">
|
||||
</div>
|
||||
<div class="col-6">
|
||||
<label class="form-label small fw-semibold">Apellidos <span class="text-danger">*</span></label>
|
||||
<input type="text" id="med-apellidos" class="form-control form-control-sm"
|
||||
placeholder="Apellidos" maxlength="100">
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<label class="form-label small fw-semibold">Código especialidad</label>
|
||||
<input type="text" id="med-esp" class="form-control form-control-sm"
|
||||
placeholder="Ej: MED, PED, GIN…" maxlength="50">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancelar</button>
|
||||
<button type="button" class="btn btn-primary btn-sm" id="btn-guardar" onclick="guardar()">
|
||||
<i class="fas fa-save me-1"></i>Guardar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ══ Modal confirmar eliminar ══════════════════════════════════════ -->
|
||||
<div class="modal fade" id="modalEliminar" tabindex="-1">
|
||||
<div class="modal-dialog modal-sm">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header border-0 pb-0">
|
||||
<h5 class="modal-title text-danger"><i class="fas fa-trash me-1"></i>Eliminar médico</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
¿Eliminar a <strong id="del-nombre"></strong>? Esta acción no se puede deshacer.
|
||||
</div>
|
||||
<div class="modal-footer border-0 pt-0">
|
||||
<button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancelar</button>
|
||||
<button type="button" class="btn btn-danger btn-sm" id="btn-confirmar-del" onclick="confirmarEliminar()">
|
||||
Eliminar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const API = '<?= $API ?>';
|
||||
let _modal, _modalDel, _pendingDelId, _buscarTimer;
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
_modal = new bootstrap.Modal(document.getElementById('modalMedico'));
|
||||
_modalDel = new bootstrap.Modal(document.getElementById('modalEliminar'));
|
||||
cargar();
|
||||
});
|
||||
|
||||
async function cargar(q = '') {
|
||||
const url = API + 'list.php' + (q ? '?q=' + encodeURIComponent(q) : '');
|
||||
const res = await fetch(url);
|
||||
const json = await res.json();
|
||||
if (!json.ok) return;
|
||||
renderTabla(json.data);
|
||||
}
|
||||
|
||||
function buscar() {
|
||||
clearTimeout(_buscarTimer);
|
||||
_buscarTimer = setTimeout(() => cargar(document.getElementById('inp-buscar').value.trim()), 280);
|
||||
}
|
||||
|
||||
function renderTabla(rows) {
|
||||
const body = document.getElementById('tbl-body');
|
||||
document.getElementById('lbl-total').textContent = rows.length + ' médico(s)';
|
||||
if (!rows.length) {
|
||||
body.innerHTML = '<tr id="tbl-empty"><td colspan="6">Sin resultados.</td></tr>';
|
||||
return;
|
||||
}
|
||||
body.innerHTML = rows.map(m => `
|
||||
<tr>
|
||||
<td><code>${esc(m.codigo)}</code></td>
|
||||
<td>${esc(m.nombres)}</td>
|
||||
<td>${esc(m.apellidos)}</td>
|
||||
<td>${m.cod_especialidad ? `<span class="badge-esp">${esc(m.cod_especialidad)}</span>` : '<span class="text-muted">—</span>'}</td>
|
||||
<td>${esc(m.docidmedico || '—')}</td>
|
||||
<td>
|
||||
<div class="acciones">
|
||||
<button class="btn btn-outline-primary btn-sm py-0 px-2" onclick='abrirEditar(${JSON.stringify(m)})'>
|
||||
<i class="fas fa-pencil-alt"></i>
|
||||
</button>
|
||||
<button class="btn btn-outline-danger btn-sm py-0 px-2" onclick="pedirEliminar(${m.id}, '${esc(m.nombres)} ${esc(m.apellidos)}')">
|
||||
<i class="fas fa-trash"></i>
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>`).join('');
|
||||
}
|
||||
|
||||
function abrirModal(m = null) {
|
||||
document.getElementById('modal-titulo').textContent = m ? 'Editar médico' : 'Nuevo médico';
|
||||
document.getElementById('modal-alert').classList.add('d-none');
|
||||
document.getElementById('med-id').value = m?.id ?? '';
|
||||
document.getElementById('med-codigo').value = m?.codigo ?? '';
|
||||
document.getElementById('med-nombres').value = m?.nombres ?? '';
|
||||
document.getElementById('med-apellidos').value = m?.apellidos ?? '';
|
||||
document.getElementById('med-esp').value = m?.cod_especialidad ?? '';
|
||||
document.getElementById('med-docid').value = m?.docidmedico ?? '';
|
||||
_modal.show();
|
||||
setTimeout(() => document.getElementById('med-codigo').focus(), 300);
|
||||
}
|
||||
|
||||
function abrirEditar(m) { abrirModal(m); }
|
||||
|
||||
async function guardar() {
|
||||
const alerta = document.getElementById('modal-alert');
|
||||
alerta.classList.add('d-none');
|
||||
|
||||
const payload = {
|
||||
id: document.getElementById('med-id').value || null,
|
||||
codigo: document.getElementById('med-codigo').value.trim(),
|
||||
nombres: document.getElementById('med-nombres').value.trim(),
|
||||
apellidos: document.getElementById('med-apellidos').value.trim(),
|
||||
cod_especialidad: document.getElementById('med-esp').value.trim(),
|
||||
docidmedico: document.getElementById('med-docid').value.trim(),
|
||||
};
|
||||
|
||||
const btn = document.getElementById('btn-guardar');
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Guardando…';
|
||||
|
||||
try {
|
||||
const res = await fetch(API + 'save.php', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const json = await res.json();
|
||||
if (!json.ok) {
|
||||
alerta.textContent = json.error;
|
||||
alerta.classList.remove('d-none');
|
||||
return;
|
||||
}
|
||||
_modal.hide();
|
||||
cargar(document.getElementById('inp-buscar').value.trim());
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = '<i class="fas fa-save me-1"></i>Guardar';
|
||||
}
|
||||
}
|
||||
|
||||
function pedirEliminar(id, nombre) {
|
||||
_pendingDelId = id;
|
||||
document.getElementById('del-nombre').textContent = nombre;
|
||||
_modalDel.show();
|
||||
}
|
||||
|
||||
async function confirmarEliminar() {
|
||||
const btn = document.getElementById('btn-confirmar-del');
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const res = await fetch(API + 'delete.php', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ id: _pendingDelId }),
|
||||
});
|
||||
const json = await res.json();
|
||||
if (json.ok) {
|
||||
_modalDel.hide();
|
||||
cargar(document.getElementById('inp-buscar').value.trim());
|
||||
}
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
function esc(str) {
|
||||
if (!str) return '';
|
||||
return String(str).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
|
||||
}
|
||||
</script>
|
||||
<?php Layout::close(); ?>
|
||||
Reference in New Issue
Block a user