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:
@@ -0,0 +1,108 @@
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
|
||||
// Mock del cliente API (firebase.js re-exporta api.js: el mock intercepta la
|
||||
// resolución del módulo y cubre ambas vías).
|
||||
vi.mock("../../src/api.js", () => ({
|
||||
listarResenas: vi.fn(),
|
||||
enviarResena: vi.fn(),
|
||||
borrarResena: vi.fn(),
|
||||
reportarLocal: vi.fn(),
|
||||
}));
|
||||
|
||||
import ResenasLocal from "../../src/components/ResenasLocal.jsx";
|
||||
import { borrarResena, enviarResena, listarResenas, reportarLocal } from "../../src/api.js";
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
localStorage.clear();
|
||||
});
|
||||
afterEach(cleanup);
|
||||
|
||||
const RESENA_AJENA = {
|
||||
id: "res-1111", huella: "#a1b2c3", puntuacion: 4, comentario: "Genial",
|
||||
fecha: "2026-10-11T10:00:00.000Z", fechaEdicion: null, esPropia: false,
|
||||
};
|
||||
const RESENA_PROPIA = {
|
||||
id: "res-2222", huella: "#d4e5f6", puntuacion: 5, comentario: "Mi favorito",
|
||||
fecha: "2026-10-10T10:00:00.000Z", fechaEdicion: null, esPropia: true,
|
||||
};
|
||||
|
||||
const abrir = () => fireEvent.click(screen.getByRole("button", { name: /reseñas/i }));
|
||||
|
||||
describe("ResenasLocal (sección desplegable en la tarjeta)", () => {
|
||||
it("plegado muestra media y número, sin cargar nada; aria-expanded refleja el estado", () => {
|
||||
render(<ResenasLocal localId="loc-1" totalInicial={3} mediaInicial={4} />);
|
||||
const cabecera = screen.getByRole("button", { name: /reseñas \(3\)/i });
|
||||
expect(cabecera.getAttribute("aria-expanded")).toBe("false");
|
||||
expect(listarResenas).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("al expandir carga perezosamente la lista (huella anónima, estrellas, comentario)", async () => {
|
||||
listarResenas.mockResolvedValue({ resenas: [RESENA_AJENA], total: 1 });
|
||||
render(<ResenasLocal localId="loc-1" totalInicial={1} mediaInicial={4} />);
|
||||
|
||||
abrir();
|
||||
await waitFor(() => expect(listarResenas).toHaveBeenCalledWith("loc-1", expect.any(String)));
|
||||
expect(await screen.findByText(/anónimo #a1b2c3/i)).toBeTruthy();
|
||||
expect(screen.getByText("Genial")).toBeTruthy();
|
||||
// estrellas de la reseña (la cabecera también es role=img con la media)
|
||||
expect(screen.getAllByRole("img", { name: /valoración: 4 de 5/i }).length).toBeGreaterThan(0);
|
||||
// el deviceId se genera y persiste en localStorage
|
||||
expect(localStorage.getItem("localesp_device_id")).toMatch(/./);
|
||||
});
|
||||
|
||||
it("formulario: elegir estrellas y publicar llama a enviarResena con el deviceId", async () => {
|
||||
listarResenas.mockResolvedValue({ resenas: [], total: 0 });
|
||||
enviarResena.mockResolvedValue({ ok: true, media: 5, total: 1 });
|
||||
render(<ResenasLocal localId="loc-1" />);
|
||||
|
||||
abrir();
|
||||
fireEvent.click(await screen.findByRole("radio", { name: "4 estrellas" }));
|
||||
fireEvent.change(screen.getByLabelText(/comentario de la reseña/i), { target: { value: "Muy bien" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: /publicar/i }));
|
||||
|
||||
await waitFor(() => expect(enviarResena).toHaveBeenCalledWith("loc-1", {
|
||||
deviceId: expect.any(String),
|
||||
puntuacion: 4,
|
||||
comentario: "Muy bien",
|
||||
}));
|
||||
});
|
||||
|
||||
it("la reseña propia se precarga: botón Actualizar y Borrar mi reseña", async () => {
|
||||
listarResenas.mockResolvedValue({ resenas: [RESENA_PROPIA], total: 1 });
|
||||
borrarResena.mockResolvedValue({ ok: true, media: 0, total: 0 });
|
||||
render(<ResenasLocal localId="loc-1" totalInicial={1} mediaInicial={5} />);
|
||||
|
||||
abrir();
|
||||
expect(await screen.findByText(/tu reseña/i)).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: /actualizar/i })).toBeTruthy();
|
||||
expect(screen.getByLabelText(/comentario de la reseña/i).value).toBe("Mi favorito");
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /borrar mi reseña/i }));
|
||||
await waitFor(() => expect(borrarResena).toHaveBeenCalledWith("loc-1", expect.any(String)));
|
||||
});
|
||||
|
||||
it("las reseñas ajenas se pueden reportar (reportarLocal con resenaId)", async () => {
|
||||
listarResenas.mockResolvedValue({ resenas: [RESENA_AJENA], total: 1 });
|
||||
reportarLocal.mockResolvedValue({ ok: true });
|
||||
render(<ResenasLocal localId="loc-1" />);
|
||||
|
||||
abrir();
|
||||
fireEvent.click(await screen.findByTitle(/reportar esta reseña/i));
|
||||
await waitFor(() => expect(reportarLocal).toHaveBeenCalledWith("loc-1", "inapropiado", "", "res-1111"));
|
||||
expect(await screen.findByText(/✅ reportada/i)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("errores del servidor (palabras no permitidas, 429) se muestran como aviso", async () => {
|
||||
listarResenas.mockResolvedValue({ resenas: [], total: 0 });
|
||||
enviarResena.mockRejectedValue(new Error("El comentario contiene palabras no permitidas"));
|
||||
render(<ResenasLocal localId="loc-1" />);
|
||||
|
||||
abrir();
|
||||
fireEvent.click(await screen.findByRole("radio", { name: "3 estrellas" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: /publicar/i }));
|
||||
expect((await screen.findByRole("alert")).textContent).toMatch(/no permitidas/i);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { expect, beforeAll, describe, it } from "vitest";
|
||||
import request from "supertest";
|
||||
|
||||
// Rate-limit de reseñas con su PROPIA instancia de app y un máximo bajo,
|
||||
// para poder agotar la cuota sin interferir en otras suites (vitest aísla
|
||||
// los módulos por fichero).
|
||||
process.env.LOCALESP_DB = ":memory:";
|
||||
process.env.LOCALESP_ADMIN_PREFIX = "/prefijo-admin-rl";
|
||||
process.env.LOCALESP_RESENAS_RATELIMIT_MAX = "2";
|
||||
|
||||
const server = (await import("../../server/index.js")).default;
|
||||
const PREFIX = "/prefijo-admin-rl";
|
||||
|
||||
let localId;
|
||||
|
||||
beforeAll(async () => {
|
||||
const propuesta = await request(server)
|
||||
.post("/api/propuestas")
|
||||
.send({ nombre: "Bar Limitado", provincia: "Madrid" })
|
||||
.expect(201);
|
||||
await request(server).post(`${PREFIX}/aprobar/${propuesta.body.id}`).expect(200);
|
||||
const locales = (await request(server).get("/api/locales").expect(200)).body;
|
||||
localId = locales.find((l) => l.nombre === "Bar Limitado").id;
|
||||
});
|
||||
|
||||
describe("Rate limit de escrituras de reseñas (anti-boicot base)", () => {
|
||||
it("las dos primeras escrituras pasan y la tercera recibe 429", async () => {
|
||||
await request(server)
|
||||
.post(`/api/locales/${localId}/resenas`)
|
||||
.send({ deviceId: "device-rl-aaaa-0001", puntuacion: 5 })
|
||||
.expect(201);
|
||||
|
||||
await request(server)
|
||||
.post(`/api/locales/${localId}/resenas`)
|
||||
.send({ deviceId: "device-rl-aaaa-0001", puntuacion: 4 }) // edición
|
||||
.expect(200);
|
||||
|
||||
const tercera = await request(server)
|
||||
.post(`/api/locales/${localId}/resenas`)
|
||||
.send({ deviceId: "device-rl-bbbb-0002", puntuacion: 3 });
|
||||
expect(tercera.status).toBe(429);
|
||||
expect(tercera.body.error).toBeTruthy();
|
||||
expect(tercera.headers["retry-after"]).toBeTruthy();
|
||||
|
||||
// el DELETE también está limitado…
|
||||
const borrado = await request(server)
|
||||
.delete(`/api/locales/${localId}/resenas?deviceId=device-rl-aaaa-0001`);
|
||||
expect(borrado.status).toBe(429);
|
||||
|
||||
// …pero la LECTURA sigue disponible
|
||||
const lista = await request(server).get(`/api/locales/${localId}/resenas`).expect(200);
|
||||
expect(lista.body.total).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,170 @@
|
||||
import request from "supertest";
|
||||
|
||||
// BD en memoria, prefijo admin y rate-limit holgado para las pruebas de
|
||||
// comportamiento (el límite se prueba aparte, con su propio proceso):
|
||||
// deben configurarse ANTES de importar la app.
|
||||
process.env.LOCALESP_DB = ":memory:";
|
||||
process.env.LOCALESP_ADMIN_PREFIX = "/prefijo-admin-test";
|
||||
process.env.LOCALESP_RESENAS_RATELIMIT_MAX = "100";
|
||||
|
||||
// Se importa después de fijar las variables de entorno.
|
||||
const server = (await import("../../server/index.js")).default;
|
||||
|
||||
const PREFIX = "/prefijo-admin-test";
|
||||
const DEV_A = "device-aaaaaaaa-1111";
|
||||
const DEV_B = "device-bbbbbbbb-2222";
|
||||
|
||||
let localId;
|
||||
|
||||
beforeAll(async () => {
|
||||
// Publicar un local (propuesta → aprobación) para tener dónde reseñar.
|
||||
const propuesta = await request(server)
|
||||
.post("/api/propuestas")
|
||||
.send({ nombre: "Bar Reseñable", provincia: "Madrid", categoria: "Restauración" })
|
||||
.expect(201);
|
||||
await request(server).post(`${PREFIX}/aprobar/${propuesta.body.id}`).expect(200);
|
||||
const locales = (await request(server).get("/api/locales").expect(200)).body;
|
||||
localId = locales.find((l) => l.nombre === "Bar Reseñable").id;
|
||||
});
|
||||
|
||||
describe("Reseñas — creación, upsert y listado público", () => {
|
||||
it("GET /api/locales incluye totalResenas por local", async () => {
|
||||
const locales = (await request(server).get("/api/locales").expect(200)).body;
|
||||
const bar = locales.find((l) => l.id === localId);
|
||||
expect(bar.totalResenas).toBe(0);
|
||||
});
|
||||
|
||||
it("POST crea la reseña (201) y recalcula la media; GET lista con huella y sin deviceId", async () => {
|
||||
const res = await request(server)
|
||||
.post(`/api/locales/${localId}/resenas`)
|
||||
.send({ deviceId: DEV_A, puntuacion: 5, comentario: " Pan excelente " })
|
||||
.expect(201);
|
||||
expect(res.body.creada).toBe(true);
|
||||
expect(res.body.media).toBe(5);
|
||||
expect(res.body.total).toBe(1);
|
||||
|
||||
const lista = (await request(server).get(`/api/locales/${localId}/resenas`).expect(200)).body;
|
||||
expect(lista.total).toBe(1);
|
||||
const [r] = lista.resenas;
|
||||
expect(r.huella).toMatch(/^#[0-9a-f]{3}$/);
|
||||
expect(r.puntuacion).toBe(5);
|
||||
expect(r.comentario).toBe("Pan excelente"); // trim
|
||||
expect(r.deviceId).toBeUndefined(); // nunca se expone
|
||||
expect(r.esPropia).toBe(false); // sin ?deviceId=
|
||||
|
||||
// con ?deviceId= se marca la propia
|
||||
const propia = (await request(server).get(`/api/locales/${localId}/resenas?deviceId=${DEV_A}`).expect(200)).body;
|
||||
expect(propia.resenas[0].esPropia).toBe(true);
|
||||
|
||||
// y la media queda en el local
|
||||
const local = (await request(server).get("/api/locales").expect(200)).body.find((l) => l.id === localId);
|
||||
expect(local.puntuacion).toBe(5);
|
||||
expect(local.totalResenas).toBe(1);
|
||||
});
|
||||
|
||||
it("POST del mismo dispositivo edita (200, fechaEdicion) sin duplicar", async () => {
|
||||
const res = await request(server)
|
||||
.post(`/api/locales/${localId}/resenas`)
|
||||
.send({ deviceId: DEV_A, puntuacion: 4, comentario: "Bajó algo el nivel" })
|
||||
.expect(200);
|
||||
expect(res.body.creada).toBe(false);
|
||||
expect(res.body.total).toBe(1); // sigue habiendo UNA reseña
|
||||
|
||||
const lista = (await request(server).get(`/api/locales/${localId}/resenas?deviceId=${DEV_A}`)).body;
|
||||
expect(lista.resenas).toHaveLength(1);
|
||||
expect(lista.resenas[0].fechaEdicion).toBeTruthy();
|
||||
expect(lista.resenas[0].comentario).toBe("Bajó algo el nivel");
|
||||
});
|
||||
|
||||
it("la media se recalcula al crear, editar y borrar (ROUND de SQLite)", async () => {
|
||||
// estado: DEV_A=4 → añade DEV_B=5 → media ROUND(4.5)=5
|
||||
await request(server).post(`/api/locales/${localId}/resenas`)
|
||||
.send({ deviceId: DEV_B, puntuacion: 5 }).expect(201);
|
||||
expect((await request(server).get("/api/locales")).body.find((l) => l.id === localId).puntuacion).toBe(5);
|
||||
|
||||
// edita DEV_B a 1 → media ROUND(2.5)=3 (round half away from zero)
|
||||
await request(server).post(`/api/locales/${localId}/resenas`)
|
||||
.send({ deviceId: DEV_B, puntuacion: 1 }).expect(200);
|
||||
expect((await request(server).get("/api/locales")).body.find((l) => l.id === localId).puntuacion).toBe(3);
|
||||
|
||||
// borra DEV_B → solo queda DEV_A=4
|
||||
await request(server).delete(`/api/locales/${localId}/resenas?deviceId=${DEV_B}`).expect(200);
|
||||
expect((await request(server).get("/api/locales")).body.find((l) => l.id === localId).puntuacion).toBe(4);
|
||||
});
|
||||
|
||||
it("DELETE de la propia reseña inexistente → 404; sin deviceId → 400", async () => {
|
||||
await request(server).delete(`/api/locales/${localId}/resenas?deviceId=${DEV_B}`).expect(404);
|
||||
await request(server).delete(`/api/locales/${localId}/resenas`).expect(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Reseñas — validaciones del contrato", () => {
|
||||
it("400: puntuacion ausente, 0, 6, no entera", async () => {
|
||||
for (const puntuacion of [undefined, 0, 6, 3.5, "cuatro"]) {
|
||||
await request(server).post(`/api/locales/${localId}/resenas`)
|
||||
.send({ deviceId: DEV_B, puntuacion }).expect(400);
|
||||
}
|
||||
});
|
||||
|
||||
it("400: deviceId ausente/corto/largo y comentario >500", async () => {
|
||||
await request(server).post(`/api/locales/${localId}/resenas`)
|
||||
.send({ deviceId: "", puntuacion: 3 }).expect(400);
|
||||
await request(server).post(`/api/locales/${localId}/resenas`)
|
||||
.send({ puntuacion: 3 }).expect(400);
|
||||
await request(server).post(`/api/locales/${localId}/resenas`)
|
||||
.send({ deviceId: "x".repeat(65), puntuacion: 3 }).expect(400);
|
||||
await request(server).post(`/api/locales/${localId}/resenas`)
|
||||
.send({ deviceId: DEV_B, puntuacion: 3, comentario: "y".repeat(501) }).expect(400);
|
||||
});
|
||||
|
||||
it("404: local inexistente en GET/POST", async () => {
|
||||
const idFantasma = "00000000-0000-4000-8000-000000000000";
|
||||
await request(server).get(`/api/locales/${idFantasma}/resenas`).expect(404);
|
||||
await request(server).post(`/api/locales/${idFantasma}/resenas`)
|
||||
.send({ deviceId: DEV_B, puntuacion: 3 }).expect(404);
|
||||
});
|
||||
|
||||
it("400: comentario con palabra prohibida (filtro de palabras)", async () => {
|
||||
await request(server).post("/api/config/filtro_palabras")
|
||||
.send({ palabras: ["timonestro"] }).expect(200);
|
||||
const res = await request(server).post(`/api/locales/${localId}/resenas`)
|
||||
.send({ deviceId: DEV_B, puntuacion: 1, comentario: "Sitio timonestro" }).expect(400);
|
||||
expect(res.body.error).toMatch(/no permitidas/i);
|
||||
// la reseña no se creó ni modificó
|
||||
const lista = (await request(server).get(`/api/locales/${localId}/resenas`)).body;
|
||||
expect(lista.resenas.some((r) => r.comentario?.includes("timonestro"))).toBe(false);
|
||||
await request(server).post("/api/config/filtro_palabras").send({ palabras: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Reseñas — reportes y moderación admin", () => {
|
||||
it("reportar una reseña concreta (resenaId) llega a la lista admin", async () => {
|
||||
const lista = (await request(server).get(`/api/locales/${localId}/resenas`)).body;
|
||||
const objetivo = lista.resenas[0];
|
||||
|
||||
await request(server).post(`/api/locales/${localId}/reportar`)
|
||||
.send({ motivo: "inapropiado", comentario: "", resenaId: objetivo.id })
|
||||
.expect(201);
|
||||
|
||||
const reportes = (await request(server).get(`${PREFIX}/reportes`).expect(200)).body;
|
||||
const reporte = reportes.find((r) => r.resenaId === objetivo.id);
|
||||
expect(reporte).toBeDefined();
|
||||
expect(reporte.localNombre).toBe("Bar Reseñable");
|
||||
|
||||
// resenaId que no existe → 404
|
||||
await request(server).post(`/api/locales/${localId}/reportar`)
|
||||
.send({ resenaId: "no-existe" }).expect(404);
|
||||
});
|
||||
|
||||
it("admin: listado completo y borrado con recálculo de media", async () => {
|
||||
const resenas = (await request(server).get(`${PREFIX}/resenas`).expect(200)).body;
|
||||
expect(resenas).toHaveLength(1);
|
||||
expect(resenas[0].localNombre).toBe("Bar Reseñable");
|
||||
|
||||
await request(server).delete(`${PREFIX}/resenas/${resenas[0].id}`).expect(200);
|
||||
// sin reseñas → media 0
|
||||
expect((await request(server).get("/api/locales")).body.find((l) => l.id === localId).puntuacion).toBe(0);
|
||||
// borrar de nuevo → 404
|
||||
await request(server).delete(`${PREFIX}/resenas/${resenas[0].id}`).expect(404);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user