deploy-branch / deploy (push) Successful in 2m56s
deploy-branch / teardown (push) Skipped
tests / Unitarias + componente + build (push) Failing after 3m14s
tests / Integración (Nominatim real, opt-in) (push) Skipped
tests / Unitarias + componente + build (pull_request) Failing after 3m6s
tests / Integración (Nominatim real, opt-in) (pull_request) Skipped
Una reseña por dispositivo (UNIQUE localId+deviceId, upsert editable), puntuación 1-5 + comentario ≤500, publicación directa con filtro de palabras server-side y reportes con resenaId; borrado admin desde el panel. locales.puntuacion pasa a ser la media (ROUND) recalculada en cada escritura; GET /api/locales añade totalResenas. Identidad v1 anónima estilo 4chan: deviceId en localStorage, huella corta por local (sha256(deviceId:localId)), nunca se expone el deviceId. Anti-boicot base: rate-limit por IP (10/h, configurable con LOCALESP_RESENAS_RATELIMIT_MAX, 429+Retry-After). UI: sección plegable "Reseñas (N) · ★media" en la tarjeta con formulario inline. Suite: 132/132 (+18 tests: rutas, rate-limit y componente).
235 lines
7.5 KiB
JavaScript
235 lines
7.5 KiB
JavaScript
// Local SQLite API instead of Firebase
|
|
|
|
const API_URL = "/api";
|
|
// Prefijo de las rutas de administración: la MISMA variable que usa el
|
|
// servidor (LOCALESP_ADMIN_PREFIX), expuesta al frontend por Vite mediante
|
|
// `envPrefix` (dev/build la recogen de .env o del entorno; el build falla si
|
|
// falta). El fallback "/api" solo aplica fuera de un build real (p. ej. tests).
|
|
const rawAdmin = String(import.meta.env.LOCALESP_ADMIN_PREFIX || "").trim().replace(/\/+$/, "");
|
|
const ADMIN_URL = rawAdmin ? (rawAdmin.startsWith("/") ? rawAdmin : `/${rawAdmin}`) : "/api";
|
|
|
|
export async function suscribirLocales(onData, onError) {
|
|
try {
|
|
const response = await fetch(`${API_URL}/locales`);
|
|
const data = await response.json();
|
|
onData(data);
|
|
// Simulate real-time by polling every 5 seconds
|
|
const interval = setInterval(async () => {
|
|
try {
|
|
const res = await fetch(`${API_URL}/locales`);
|
|
const newData = await res.json();
|
|
onData(newData);
|
|
} catch (err) {
|
|
console.error(err);
|
|
}
|
|
}, 5000);
|
|
return () => clearInterval(interval);
|
|
} catch (err) {
|
|
onError(err);
|
|
}
|
|
}
|
|
|
|
export async function suscribirPendientes(onData, onError) {
|
|
try {
|
|
const response = await fetch(`${ADMIN_URL}/pendientes`);
|
|
const data = await response.json();
|
|
onData(data);
|
|
// Simulate real-time by polling every 5 seconds
|
|
const interval = setInterval(async () => {
|
|
try {
|
|
const res = await fetch(`${ADMIN_URL}/pendientes`);
|
|
const newData = await res.json();
|
|
onData(newData);
|
|
} catch (err) {
|
|
console.error(err);
|
|
}
|
|
}, 5000);
|
|
return () => clearInterval(interval);
|
|
} catch (err) {
|
|
onError(err);
|
|
}
|
|
}
|
|
|
|
export async function enviarPropuesta(local) {
|
|
const { id: _x, ...datos } = local;
|
|
const response = await fetch(`${API_URL}/propuestas`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(datos),
|
|
});
|
|
return response.json();
|
|
}
|
|
|
|
export async function comprobarDuplicado({ nombre, provincia, lat, lng }) {
|
|
const response = await fetch(`${API_URL}/check-duplicado`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ nombre, provincia, lat, lng }),
|
|
});
|
|
return response.json();
|
|
}
|
|
|
|
export async function aprobarPropuesta(p) {
|
|
const response = await fetch(`${ADMIN_URL}/aprobar/${p.id}`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
return response.json();
|
|
}
|
|
|
|
export async function rechazarPropuesta(id) {
|
|
const response = await fetch(`${ADMIN_URL}/rechazar/${id}`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
return response.json();
|
|
}
|
|
|
|
export async function deleteLocal(id) {
|
|
const response = await fetch(`${ADMIN_URL}/locales/${id}`, {
|
|
method: "DELETE",
|
|
});
|
|
return response.json();
|
|
}
|
|
|
|
export async function confirmarLocal(id) {
|
|
const response = await fetch(`${API_URL}/locales/${id}/confirmar`, { method: "POST" });
|
|
return response.json();
|
|
}
|
|
|
|
export async function reportarLocal(id, motivo, comentario, resenaId) {
|
|
const response = await fetch(`${API_URL}/locales/${id}/reportar`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ motivo, comentario, resenaId }),
|
|
});
|
|
return response.json();
|
|
}
|
|
|
|
// --- Reseñas anónimas por local (issue #6) ---
|
|
// Identidad v1: deviceId del navegador. Con ?deviceId= el servidor marca
|
|
// esPropia en cada reseña (para precargar el formulario) sin exponer el
|
|
// deviceId completo (solo la huella corta por local).
|
|
export async function listarResenas(localId, deviceId) {
|
|
const q = deviceId ? `?deviceId=${encodeURIComponent(deviceId)}` : "";
|
|
const response = await fetch(`${API_URL}/locales/${localId}/resenas${q}`);
|
|
return response.json();
|
|
}
|
|
|
|
// Crear o editar (upsert) la reseña del dispositivo en el local.
|
|
export async function enviarResena(localId, { deviceId, puntuacion, comentario }) {
|
|
const response = await fetch(`${API_URL}/locales/${localId}/resenas`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ deviceId, puntuacion, comentario }),
|
|
});
|
|
const datos = await response.json().catch(() => ({}));
|
|
if (!response.ok) throw new Error(datos.error || "No se pudo guardar la reseña");
|
|
return datos;
|
|
}
|
|
|
|
// Borrar la reseña propia del dispositivo en el local.
|
|
export async function borrarResena(localId, deviceId) {
|
|
const response = await fetch(`${API_URL}/locales/${localId}/resenas?deviceId=${encodeURIComponent(deviceId)}`, {
|
|
method: "DELETE",
|
|
});
|
|
const datos = await response.json().catch(() => ({}));
|
|
if (!response.ok) throw new Error(datos.error || "No se pudo borrar la reseña");
|
|
return datos;
|
|
}
|
|
|
|
// Moderación: listado completo y borrado de cualquier reseña (admin).
|
|
export async function obtenerResenas() {
|
|
const response = await fetch(`${ADMIN_URL}/resenas`);
|
|
return response.json();
|
|
}
|
|
|
|
export async function borrarResenaAdmin(id) {
|
|
const response = await fetch(`${ADMIN_URL}/resenas/${id}`, { method: "DELETE" });
|
|
return response.json();
|
|
}
|
|
|
|
export async function obtenerReportes() {
|
|
const response = await fetch(`${ADMIN_URL}/reportes`);
|
|
return response.json();
|
|
}
|
|
|
|
export async function descartarReporte(id) {
|
|
const response = await fetch(`${ADMIN_URL}/reportes/${id}/descartar`, { method: "POST" });
|
|
return response.json();
|
|
}
|
|
|
|
export async function obtenerPalabrasFiltradas() {
|
|
try {
|
|
const response = await fetch(`${API_URL}/config/filtro_palabras`);
|
|
const data = await response.json();
|
|
return data.palabras || [];
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
export async function guardarPalabrasFiltradas(palabras) {
|
|
const response = await fetch(`${API_URL}/config/filtro_palabras`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ palabras }),
|
|
});
|
|
return response.json();
|
|
}
|
|
|
|
export function contienepalabrasProhibidas(texto, lista) {
|
|
if (!lista?.length) return false;
|
|
const norm = s => s.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "");
|
|
const t = norm(texto);
|
|
return lista.some(p => t.includes(norm(p)));
|
|
}
|
|
|
|
// Auth helpers (local implementation)
|
|
let currentUser = null;
|
|
|
|
export function escucharAuth(cb) {
|
|
// Simple localStorage-based auth
|
|
// Robusto ante valores corruptos/legados: si el JSON no parsea, se limpia y
|
|
// se trata como sesión cerrada (antes esto rompía /admin en blanco).
|
|
let user = null;
|
|
try {
|
|
const raw = localStorage.getItem("user");
|
|
user = raw ? JSON.parse(raw) : null;
|
|
} catch {
|
|
try { localStorage.removeItem("user"); } catch { /* almacenamiento no disponible */ }
|
|
user = null;
|
|
}
|
|
currentUser = user;
|
|
cb(currentUser);
|
|
|
|
// Listen for storage changes
|
|
const handleStorageChange = () => {
|
|
const user = localStorage.getItem("user");
|
|
currentUser = user ? JSON.parse(user) : null;
|
|
cb(currentUser);
|
|
};
|
|
window.addEventListener("storage", handleStorageChange);
|
|
return () => window.removeEventListener("storage", handleStorageChange);
|
|
}
|
|
|
|
export async function loginAdmin(email, password) {
|
|
// Simple email/password check (in production use proper auth)
|
|
if (email && password) {
|
|
const user = { email, uid: email };
|
|
localStorage.setItem("user", JSON.stringify(user));
|
|
currentUser = user;
|
|
return user;
|
|
}
|
|
throw new Error("Invalid email or password");
|
|
}
|
|
|
|
export async function registrarAdmin(email, password) {
|
|
return loginAdmin(email, password);
|
|
}
|
|
|
|
export async function cerrarSesion() {
|
|
localStorage.removeItem("user");
|
|
currentUser = null;
|
|
}
|