feat(resenas): reseñas anónimas múltiples por local (issue #6)
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
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).
This commit is contained in:
+14
-2
@@ -5,7 +5,7 @@ import {
|
||||
escucharAuth, loginAdmin, registrarAdmin, cerrarSesion,
|
||||
suscribirPendientes, aprobarPropuesta, rechazarPropuesta,
|
||||
suscribirLocales, deleteLocal,
|
||||
obtenerReportes, descartarReporte,
|
||||
obtenerReportes, descartarReporte, borrarResenaAdmin,
|
||||
obtenerPalabrasFiltradas, guardarPalabrasFiltradas,
|
||||
} from "./firebase.js";
|
||||
import { obtenerCategoria } from "./constants/categorias.js";
|
||||
@@ -165,6 +165,16 @@ function PanelAdmin({ email }) {
|
||||
const rechazar = async (id) => { if (!confirm("¿Rechazar y eliminar esta propuesta?")) return; try { await rechazarPropuesta(id); mostrarToast("Propuesta rechazada", "info"); } catch(e) { mostrarToast("Error: "+e.message, "error"); } };
|
||||
const eliminar = async (id) => { if (!confirm("¿Eliminar este local publicado?")) return; try { await deleteLocal(id); cargarReportes(); mostrarToast("Local eliminado", "info"); } catch(e) { mostrarToast("Error: "+e.message, "error"); } };
|
||||
const descartar = async (id) => { try { await descartarReporte(id); setReportes(r => r.filter(x => x.id !== id)); mostrarToast("Aviso descartado", "info"); } catch(e) { mostrarToast("Error: "+e.message, "error"); } };
|
||||
// Moderación de reseñas (issue #6): al borrar la reseña reportada se
|
||||
// descarta también el aviso (queda resuelto).
|
||||
const borrarResenaReportada = async (resenaId, reporteId) => {
|
||||
try {
|
||||
await borrarResenaAdmin(resenaId);
|
||||
await descartarReporte(reporteId);
|
||||
setReportes(r => r.filter(x => x.id !== reporteId));
|
||||
mostrarToast("Reseña eliminada", "exito");
|
||||
} catch(e) { mostrarToast("Error: "+e.message, "error"); }
|
||||
};
|
||||
|
||||
const addPalabra = () => {
|
||||
const p = nuevaP.trim().toLowerCase();
|
||||
@@ -279,13 +289,15 @@ function PanelAdmin({ email }) {
|
||||
<div style={{ display:"flex", alignItems:"center", gap:8, flexWrap:"wrap", marginBottom:6 }}>
|
||||
<span style={{ fontWeight:700, fontSize:16 }}>{r.localNombre || "(local ya eliminado)"}</span>
|
||||
<span style={S.badge("#C0392B", "#FDEDEC")}>{{ cerrado:"Ha cerrado", datos_incorrectos:"Datos incorrectos", inapropiado:"Contenido inapropiado", otro:"Otro motivo" }[r.motivo] || r.motivo}</span>
|
||||
{r.resenaId && <span style={S.badge("#8B4513", "#FDF2E9")}>Reseña</span>}
|
||||
</div>
|
||||
<p style={{ margin:0, fontSize:13, color:"#666" }}>📍 {r.localProvincia} {r.localDireccion ? `· ${r.localDireccion}` : ""}</p>
|
||||
{r.comentario && <p style={{ margin:"8px 0 0", fontSize:13, color:"#666", fontStyle:"italic", background:"#FAFAFA", padding:"8px 12px", borderRadius:8 }}>"{r.comentario}"</p>}
|
||||
<p style={{ margin:"6px 0 0", fontSize:11, color:"#AAA" }}>Reportado: {new Date(r.fecha).toLocaleDateString("es-ES", { day:"numeric", month:"short", hour:"2-digit", minute:"2-digit" })}</p>
|
||||
</div>
|
||||
<div style={{ display:"flex", gap:8, flexShrink:0 }}>
|
||||
{r.localId && <button onClick={() => eliminar(r.localId)} style={{ ...S.btn("#C0392B"), padding:"8px 16px", fontSize:13 }}>🗑 Eliminar local</button>}
|
||||
{r.resenaId && <button onClick={() => borrarResenaReportada(r.resenaId, r.id)} style={{ ...S.btn("#C0392B"), padding:"8px 16px", fontSize:13 }}>🗑 Borrar reseña</button>}
|
||||
{r.localId && !r.resenaId && <button onClick={() => eliminar(r.localId)} style={{ ...S.btn("#C0392B"), padding:"8px 16px", fontSize:13 }}>🗑 Eliminar local</button>}
|
||||
<button onClick={() => descartar(r.id)} style={{ ...S.btn("#EEE","#666"), padding:"8px 16px", fontSize:13 }}>Descartar aviso</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+45
-2
@@ -97,15 +97,58 @@ export async function confirmarLocal(id) {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function reportarLocal(id, motivo, comentario) {
|
||||
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 }),
|
||||
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();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from "react";
|
||||
import CategoriaBadge from "./CategoriaBadge.jsx";
|
||||
import StarRating from "./StarRating.jsx";
|
||||
import ResenasLocal from "./ResenasLocal.jsx";
|
||||
import ReportarLocal from "./ReportarLocal.jsx";
|
||||
import Toast from "./Toast.jsx";
|
||||
import useFavoritos from "../hooks/useFavoritos.js";
|
||||
@@ -134,7 +134,14 @@ export default function LocalCard({ local, distanciaKm }) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<StarRating value={local.puntuacion} readOnly />
|
||||
{/* Media de reseñas + sección desplegable "Reseñas (N)" (issue #6).
|
||||
totalResenas lo aporta GET /api/locales; tras escribir, la cabecera
|
||||
se actualiza en local y el listado general llega por el polling. */}
|
||||
<ResenasLocal
|
||||
localId={local.id}
|
||||
totalInicial={local.totalResenas || 0}
|
||||
mediaInicial={local.puntuacion || 0}
|
||||
/>
|
||||
|
||||
{local.descripcion && (
|
||||
<p style={{ fontSize: 13, color: "var(--color-text-secondary)", margin: 0, fontStyle: "italic" }}>"{local.descripcion}"</p>
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
import { useState } from "react";
|
||||
import StarRating from "./StarRating.jsx";
|
||||
import { borrarResena, enviarResena, listarResenas, reportarLocal } from "../firebase.js";
|
||||
import { obtenerDeviceId } from "../utils/dispositivo.js";
|
||||
|
||||
const MAX_COMENTARIO = 500;
|
||||
|
||||
function formatearFecha(fecha) {
|
||||
const d = new Date(fecha);
|
||||
return Number.isNaN(d.getTime()) ? "" : d.toLocaleDateString("es-ES", { day: "numeric", month: "short", year: "numeric" });
|
||||
}
|
||||
|
||||
// Sección desplegable de reseñas anónimas (issue #6): cabecera plegable
|
||||
// "Reseñas (N) · ★media" sobre la propia tarjeta, con carga perezosa de la
|
||||
// lista al expandir y formulario inline. Una reseña por dispositivo (el
|
||||
// servidor hace upsert): la propia se precarga y permite actualizar o
|
||||
// borrar; las ajenas se pueden reportar. Identidad anónima con huella corta
|
||||
// por local ("Anónimo #a3f"), sin datos personales.
|
||||
export default function ResenasLocal({ localId, totalInicial = 0, mediaInicial = 0 }) {
|
||||
const [abierto, setAbierto] = useState(false);
|
||||
const [resenas, setResenas] = useState(null); // null = aún sin cargar
|
||||
const [cargando, setCargando] = useState(false);
|
||||
const [total, setTotal] = useState(totalInicial);
|
||||
const [media, setMedia] = useState(mediaInicial);
|
||||
const [tienePropia, setTienePropia] = useState(false);
|
||||
const [puntuacion, setPuntuacion] = useState(0);
|
||||
const [comentario, setComentario] = useState("");
|
||||
const [enviando, setEnviando] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [reportada, setReportada] = useState(null);
|
||||
|
||||
const cargar = async () => {
|
||||
setCargando(true);
|
||||
setError("");
|
||||
try {
|
||||
const datos = await listarResenas(localId, obtenerDeviceId());
|
||||
setResenas(datos.resenas || []);
|
||||
setTotal(datos.total || 0);
|
||||
const propia = (datos.resenas || []).find((r) => r.esPropia);
|
||||
setTienePropia(!!propia);
|
||||
setPuntuacion(propia?.puntuacion || 0);
|
||||
setComentario(propia?.comentario || "");
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
setError("No se pudieron cargar las reseñas.");
|
||||
}
|
||||
setCargando(false);
|
||||
};
|
||||
|
||||
const alternar = () => {
|
||||
const nuevo = !abierto;
|
||||
setAbierto(nuevo);
|
||||
if (nuevo && resenas === null && !cargando) cargar();
|
||||
};
|
||||
|
||||
const enviar = async () => {
|
||||
if (puntuacion < 1) return;
|
||||
setEnviando(true);
|
||||
setError("");
|
||||
try {
|
||||
const datos = await enviarResena(localId, {
|
||||
deviceId: obtenerDeviceId(),
|
||||
puntuacion,
|
||||
comentario: comentario.trim(),
|
||||
});
|
||||
setMedia(datos.media ?? media);
|
||||
setTienePropia(true);
|
||||
await cargar();
|
||||
} catch (e) {
|
||||
setError(e.message || "No se pudo guardar la reseña.");
|
||||
}
|
||||
setEnviando(false);
|
||||
};
|
||||
|
||||
const borrar = async () => {
|
||||
setEnviando(true);
|
||||
setError("");
|
||||
try {
|
||||
const datos = await borrarResena(localId, obtenerDeviceId());
|
||||
setMedia(datos.media ?? media);
|
||||
setTienePropia(false);
|
||||
setPuntuacion(0);
|
||||
setComentario("");
|
||||
await cargar();
|
||||
} catch (e) {
|
||||
setError(e.message || "No se pudo borrar la reseña.");
|
||||
}
|
||||
setEnviando(false);
|
||||
};
|
||||
|
||||
const reportar = async (resena) => {
|
||||
try {
|
||||
await reportarLocal(localId, "inapropiado", "", resena.id);
|
||||
setReportada(resena.id);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
|
||||
{/* Cabecera plegable: media + número de reseñas */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={alternar}
|
||||
aria-expanded={abierto}
|
||||
style={{
|
||||
display: "flex", alignItems: "center", gap: 8, width: "fit-content",
|
||||
background: "none", border: "none", padding: 0, cursor: "pointer",
|
||||
fontSize: 12, color: "var(--color-text-secondary)",
|
||||
}}
|
||||
>
|
||||
<StarRating value={media} readOnly size={14} />
|
||||
<span>
|
||||
Reseñas ({total})
|
||||
<i
|
||||
className={`ti ${abierto ? "ti-chevron-up" : "ti-chevron-down"}`}
|
||||
aria-hidden="true"
|
||||
style={{ fontSize: 13, marginLeft: 4, color: "var(--color-text-tertiary)" }}
|
||||
/>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{abierto && (
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
|
||||
{cargando && resenas === null && (
|
||||
<p style={{ fontSize: 12, color: "var(--color-text-tertiary)", margin: 0 }}>Cargando reseñas…</p>
|
||||
)}
|
||||
|
||||
{/* Lista de reseñas */}
|
||||
{resenas !== null && resenas.length === 0 && (
|
||||
<p style={{ fontSize: 12, color: "var(--color-text-tertiary)", margin: 0 }}>
|
||||
Aún no hay reseñas. ¡Sé el primero!
|
||||
</p>
|
||||
)}
|
||||
{resenas !== null && resenas.map((r) => (
|
||||
<div key={r.id} style={{
|
||||
background: "var(--color-background-secondary)",
|
||||
borderRadius: "var(--border-radius-md)",
|
||||
padding: "8px 10px",
|
||||
border: r.esPropia ? "0.5px solid var(--color-border-secondary)" : "none",
|
||||
}}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 6 }}>
|
||||
<span style={{ fontSize: 12, color: "var(--color-text-secondary)" }}>
|
||||
Anónimo {r.huella} · {formatearFecha(r.fecha)}
|
||||
{r.fechaEdicion && <span style={{ color: "var(--color-text-tertiary)" }}> · editada</span>}
|
||||
</span>
|
||||
<span style={{ display: "flex", alignItems: "center", gap: 6 }}>
|
||||
{r.esPropia
|
||||
? <span style={{ fontSize: 11, color: "#8B0000", fontWeight: 500 }}>tu reseña</span>
|
||||
: reportada === r.id
|
||||
? <span style={{ fontSize: 11, color: "#1E8449" }}>✅ reportada</span>
|
||||
: (
|
||||
<button type="button" onClick={() => reportar(r)} title="Reportar esta reseña"
|
||||
style={{ background: "none", border: "none", padding: 0, cursor: "pointer", fontSize: 12, color: "var(--color-text-tertiary)" }}>
|
||||
<i className="ti ti-flag" aria-hidden="true"></i>
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ marginTop: 2 }}>
|
||||
<StarRating value={r.puntuacion} readOnly size={13} />
|
||||
</div>
|
||||
{r.comentario && (
|
||||
<p style={{ margin: "4px 0 0", fontSize: 13, color: "var(--color-text-secondary)" }}>{r.comentario}</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Formulario inline: crear o actualizar la reseña propia */}
|
||||
<div style={{
|
||||
background: "var(--color-background-primary)",
|
||||
border: "0.5px solid var(--color-border-tertiary)",
|
||||
borderRadius: "var(--border-radius-md)",
|
||||
padding: "8px 10px",
|
||||
display: "flex", flexDirection: "column", gap: 6,
|
||||
}}>
|
||||
<p style={{ margin: 0, fontSize: 12, fontWeight: 500 }}>
|
||||
{tienePropia ? "Tu reseña (anónima)" : "Deja tu reseña (anónima)"}
|
||||
</p>
|
||||
<StarRating value={puntuacion} onChange={setPuntuacion} size={20} />
|
||||
<textarea
|
||||
value={comentario}
|
||||
onChange={(e) => setComentario(e.target.value)}
|
||||
maxLength={MAX_COMENTARIO}
|
||||
rows={2}
|
||||
placeholder="Comentario opcional (máx. 500 caracteres)…"
|
||||
aria-label="Comentario de la reseña"
|
||||
style={{
|
||||
fontSize: 12, padding: "5px 8px", borderRadius: "var(--border-radius-md)",
|
||||
border: "0.5px solid var(--color-border-secondary)",
|
||||
background: "var(--color-background-primary)", color: "var(--color-text-primary)",
|
||||
resize: "vertical", fontFamily: "inherit",
|
||||
}}
|
||||
/>
|
||||
{error && (
|
||||
<p role="alert" style={{ margin: 0, fontSize: 12, color: "#922B21" }}>
|
||||
<i className="ti ti-alert-triangle" aria-hidden="true"></i> {error}
|
||||
</p>
|
||||
)}
|
||||
<div style={{ display: "flex", gap: 6, alignItems: "center" }}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={enviar}
|
||||
disabled={puntuacion < 1 || enviando}
|
||||
style={{
|
||||
fontSize: 12, background: puntuacion >= 1 ? "#8B0000" : "var(--color-background-secondary)",
|
||||
color: puntuacion >= 1 ? "white" : "var(--color-text-tertiary)",
|
||||
border: "none", borderRadius: "var(--border-radius-md)", padding: "5px 12px",
|
||||
cursor: puntuacion >= 1 && !enviando ? "pointer" : "not-allowed", fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
{enviando ? "Guardando…" : tienePropia ? "Actualizar" : "Publicar"}
|
||||
</button>
|
||||
{tienePropia && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={borrar}
|
||||
disabled={enviando}
|
||||
style={{
|
||||
fontSize: 12, background: "none", border: "0.5px solid var(--color-border-secondary)",
|
||||
borderRadius: "var(--border-radius-md)", padding: "5px 12px", cursor: "pointer",
|
||||
color: "var(--color-text-secondary)",
|
||||
}}
|
||||
>
|
||||
Borrar mi reseña
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -8,6 +8,11 @@ export {
|
||||
deleteLocal,
|
||||
confirmarLocal,
|
||||
reportarLocal,
|
||||
listarResenas,
|
||||
enviarResena,
|
||||
borrarResena,
|
||||
obtenerResenas,
|
||||
borrarResenaAdmin,
|
||||
obtenerReportes,
|
||||
descartarReporte,
|
||||
enviarPropuesta,
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
// Identidad anónima v1 para las reseñas (issue #6): un identificador de
|
||||
// dispositivo aleatorio persistido en localStorage. Sin datos personales y
|
||||
// sin cuentas ("estilo 4chan"); cuando lleguen las cuentas se migrará
|
||||
// deviceId -> userId (ver design de resenas-por-local).
|
||||
const CLAVE = "localesp_device_id";
|
||||
|
||||
export function obtenerDeviceId() {
|
||||
try {
|
||||
let id = localStorage.getItem(CLAVE);
|
||||
if (!id) {
|
||||
id = globalThis.crypto?.randomUUID?.() || `dev-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
localStorage.setItem(CLAVE, id);
|
||||
}
|
||||
return id;
|
||||
} catch {
|
||||
// Almacenamiento no disponible (p. ej. modo privado): identidad efímera.
|
||||
return `eph-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user