BUG FIX
* admin.html: el filtro <select id="f-activo"> y el modal <input id="f-activo">
tenían el MISMO id. document.getElementById devolvía el select (primer en
DOM order) y la lectura .checked siempre era undefined → JSON enviaba el
valor stale del select. Renombré el filtro a `f-activo-filter`.
REFACTOR: drop apellido, usar Nombre Completo
* Migración 007: copia apellido→name para placeholders, migra
escrituras_tramites.abogado y tramites_legales.abogado a usar nombre
completo, DROP COLUMN apellido + índice.
* Lookups: abogadoApellidos() → abogadoNames() filtra socios+abogados
activos con name no vacío.
* Auth.php: drop método apellido(), agregado userName().
* tramites/api.php: visibilidad usa users.name = t.abogado.
* admin/api.php: drop apellido en create/update payloads.
* admin.html: drop columna y campo Apellido del table y form.
* Bootstrap envía window.DONNA.abogados con nombres completos.
LANDING (index.php)
* Gear icon en dash-header visible solo si Auth::isSocio() (chequeo
server-side, sin flash de JS).
CLEANUP
* Eliminado logging de debug en admin/api.php que se agregó para
diagnosticar el bug del activo.
PERMISOS (sin cambios — confirmación)
* Trámites Legales: solo socio/abogado pueden crear (canCreate() ya lo
enforza desde 2db8f23).
* Escrituras: cualquier rol autenticado puede crear (escrituras/api.php
nunca tuvo restricción).
131 lines
4.9 KiB
PHP
131 lines
4.9 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
require_once __DIR__ . '/../../src/Auth.php';
|
|
require_once __DIR__ . '/../../src/Db.php';
|
|
require_once __DIR__ . '/../../src/Lookups.php';
|
|
|
|
Auth::requireSocio();
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }
|
|
|
|
const ROLES = ['socio','abogado','usuario'];
|
|
|
|
function ok($data = null): void {
|
|
echo json_encode(['ok' => true, 'data' => $data, 'user' => Auth::user()], JSON_UNESCAPED_UNICODE);
|
|
exit;
|
|
}
|
|
function err(string $msg, int $code = 400): void {
|
|
http_response_code($code);
|
|
echo json_encode(['ok' => false, 'error' => $msg], JSON_UNESCAPED_UNICODE);
|
|
exit;
|
|
}
|
|
function body(): array {
|
|
return json_decode((string) file_get_contents('php://input'), true) ?? [];
|
|
}
|
|
|
|
$method = $_SERVER['REQUEST_METHOD'];
|
|
$action = $_GET['action'] ?? '';
|
|
$me = Auth::userId();
|
|
$pdo = Db::pdo();
|
|
|
|
try {
|
|
if ($method === 'GET' && $action === 'list_users') {
|
|
ok(Lookups::allUsers());
|
|
}
|
|
|
|
if ($method === 'POST' && $action === 'create_user') {
|
|
$b = body();
|
|
$email = strtolower(trim((string)($b['email'] ?? '')));
|
|
if ($email === '') err('email requerido');
|
|
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) err('email inválido');
|
|
|
|
$name = trim((string)($b['name'] ?? ''));
|
|
$role = in_array(($b['role'] ?? ''), ROLES, true) ? $b['role'] : 'usuario';
|
|
$activo = (int)($b['activo'] ?? 1) === 1 ? 1 : 0;
|
|
$orden = (int)($b['orden'] ?? 0);
|
|
|
|
$exists = $pdo->prepare('SELECT id FROM users WHERE email = :e');
|
|
$exists->execute([':e' => $email]);
|
|
if ($exists->fetch()) err('Ya existe un usuario con ese email', 409);
|
|
|
|
$ins = $pdo->prepare(
|
|
'INSERT INTO users (email, name, role, activo, orden, first_seen_at, last_login_at)
|
|
VALUES (:email, :name, :role, :activo, :orden, NULL, NULL)'
|
|
);
|
|
$ins->execute([
|
|
':email' => $email, ':name' => $name, ':role' => $role,
|
|
':activo' => $activo, ':orden' => $orden,
|
|
]);
|
|
$id = (int)$pdo->lastInsertId();
|
|
|
|
$sel = $pdo->prepare('SELECT id, email, name, role, activo, orden, first_seen_at, last_login_at FROM users WHERE id = :id');
|
|
$sel->execute([':id' => $id]);
|
|
$row = $sel->fetch();
|
|
$row['id'] = (int)$row['id'];
|
|
$row['activo'] = (int)$row['activo'];
|
|
$row['orden'] = (int)$row['orden'];
|
|
ok($row);
|
|
}
|
|
|
|
if ($method === 'PUT' && $action === 'update_user') {
|
|
$b = body();
|
|
$id = (int)($b['_id'] ?? 0);
|
|
if (!$id) err('id requerido');
|
|
|
|
$sel = $pdo->prepare('SELECT id, email, role, activo FROM users WHERE id = :id');
|
|
$sel->execute([':id' => $id]);
|
|
$existing = $sel->fetch();
|
|
if (!$existing) err('Usuario no encontrado', 404);
|
|
|
|
$newRole = in_array(($b['role'] ?? $existing['role']), ROLES, true) ? $b['role'] : $existing['role'];
|
|
$newActivo = isset($b['activo']) ? ((int)$b['activo'] === 1 ? 1 : 0) : (int)$existing['activo'];
|
|
|
|
// Salvaguardas: el socio no puede demoverse ni desactivarse a sí mismo
|
|
if ((int)$existing['id'] === $me) {
|
|
if ($newRole !== 'socio') err('No puedes quitarte el rol de Socio a ti mismo', 400);
|
|
if ($newActivo === 0) err('No puedes desactivarte a ti mismo', 400);
|
|
}
|
|
|
|
$newEmail = isset($b['email']) ? strtolower(trim((string)$b['email'])) : $existing['email'];
|
|
if (!filter_var($newEmail, FILTER_VALIDATE_EMAIL)) err('email inválido');
|
|
if ($newEmail !== $existing['email']) {
|
|
$chk = $pdo->prepare('SELECT id FROM users WHERE email = :e AND id != :id');
|
|
$chk->execute([':e' => $newEmail, ':id' => $id]);
|
|
if ($chk->fetch()) err('Otro usuario ya tiene ese email', 409);
|
|
}
|
|
|
|
$name = trim((string)($b['name'] ?? ''));
|
|
$orden = (int)($b['orden'] ?? 0);
|
|
|
|
$upd = $pdo->prepare(
|
|
'UPDATE users SET email = :email, name = :name, role = :role,
|
|
activo = :activo, orden = :orden
|
|
WHERE id = :id'
|
|
);
|
|
$upd->execute([
|
|
':email' => $newEmail, ':name' => $name, ':role' => $newRole,
|
|
':activo' => $newActivo, ':orden' => $orden,
|
|
':id' => $id,
|
|
]);
|
|
|
|
$sel = $pdo->prepare('SELECT id, email, name, role, activo, orden, first_seen_at, last_login_at FROM users WHERE id = :id');
|
|
$sel->execute([':id' => $id]);
|
|
$row = $sel->fetch();
|
|
$row['id'] = (int)$row['id'];
|
|
$row['activo'] = (int)$row['activo'];
|
|
$row['orden'] = (int)$row['orden'];
|
|
ok($row);
|
|
}
|
|
|
|
err('Acción no reconocida', 404);
|
|
|
|
} catch (PDOException $e) {
|
|
error_log('admin db error: ' . $e->getMessage());
|
|
err('Error de base de datos', 500);
|
|
} catch (Throwable $e) {
|
|
error_log('admin error: ' . $e->getMessage());
|
|
err('Error interno', 500);
|
|
}
|