Aggiunge il centro notifiche in-app accanto al profilo

Icona a campana con badge delle non lette, indipendente dal canale push:
copre messaggio libero admin, promemoria evento (24h/3h prima), turno
palloni e sollecito presenze. Ogni notifica si rimuove con uno swipe o
la ×, non c'è pulizia automatica delle vecchie (DD-030).

Migration m17_notifiche_utente non ancora applicata in produzione.

Co-Authored-By: Claude Mythos <noreply@anthropic.com>
This commit is contained in:
davideandClaude Mythos committed 2026-09-15 11:19:07 +02:00
1 parent 0314560885
commit 4d036f532d
15 files changed
+1184 -11

No files matched your search

+158 -3
View File
@@ -1,10 +1,27 @@
import { useId, useState, type ComponentPropsWithoutRef, type ReactNode } from "react";
import {
useEffect,
useId,
useRef,
useState,
type ComponentPropsWithoutRef,
type ReactNode,
} from "react";
import { Link } from "@tanstack/react-router";
import { ChevronDown } from "lucide-react";
import { AnimatePresence, motion } from "motion/react";
import { Bell, ChevronDown, X } from "lucide-react";
import { cn } from "@/lib/utils";
import { inizialiDa, statoMeta, type Stato } from "@/lib/crapp-data";
import { nomeCompleto } from "@/lib/giocatori-squadra";
import { useGiocatoreBase } from "@/lib/user-store";
import { useMotoRidotto } from "@/lib/motion";
import { molla, proietta } from "@/lib/molla";
import {
contatoreBadge,
useEliminaNotifica,
useNotificheMie,
useSegnaLette,
type NotificaUtente,
} from "@/lib/notifiche-utente";
import { Avatar } from "@/components/crapp/Avatar";
import { Reveal } from "@/components/motion/Reveal";
import { Numero } from "@/components/motion/Numero";
@@ -72,6 +89,139 @@ export function LinkProfilo() {
);
}
/** "or ora" / "tra 3 ore" / "2 giorni fa" — così basta guardare senza fare i conti. */
function tempoRelativo(dataIso: string): string {
const rtf = new Intl.RelativeTimeFormat("it", { numeric: "auto" });
const minuti = Math.round((new Date(dataIso).getTime() - Date.now()) / 60_000);
if (Math.abs(minuti) < 60) return rtf.format(minuti, "minute");
const ore = Math.round(minuti / 60);
if (Math.abs(ore) < 24) return rtf.format(ore, "hour");
return rtf.format(Math.round(ore / 24), "day");
}
/**
* Una riga del pannello notifiche, eliminabile con uno swipe a sinistra o con la ×: non
* c'è pulizia automatica delle notifiche vecchie (M17), quindi è l'unico modo per un
* giocatore di togliersele di torno. Soglia e proiezione della velocità di rilascio come
* lo swipe del calendario (`src/routes/calendario.tsx`), ma qui in una sola direzione: non
* c'è "indietro", solo "via".
*/
function RigaNotifica({
notifica,
onElimina,
}: {
notifica: NotificaUtente;
onElimina: (id: string) => void;
}) {
const ridotto = useMotoRidotto();
return (
<motion.li
layout={!ridotto}
initial={false}
exit={{ opacity: 0, height: 0, marginTop: 0, marginBottom: 0 }}
transition={molla.ui}
className="relative overflow-hidden rounded-xl"
>
<motion.div
drag={ridotto ? false : "x"}
dragConstraints={{ left: -80, right: 0 }}
dragElastic={{ left: 0.2, right: 0 }}
dragMomentum={false}
onDragEnd={(_, info) => {
const arrivo = info.offset.x + proietta(info.velocity.x);
if (arrivo < -60) onElimina(notifica.id);
}}
className="touch-pan-y bg-card p-3 pr-8 text-sm"
>
<p className="font-semibold">{notifica.titolo}</p>
{notifica.corpo ? <p className="mt-0.5 text-muted-foreground">{notifica.corpo}</p> : null}
<p className="mt-1 text-xs text-muted-foreground">{tempoRelativo(notifica.creataIl)}</p>
</motion.div>
<button
type="button"
onClick={() => onElimina(notifica.id)}
aria-label="Rimuovi notifica"
className="absolute right-1 top-1 rounded-full p-1.5 text-muted-foreground active:scale-90"
>
<X className="h-3.5 w-3.5" />
</button>
</motion.li>
);
}
/**
* Campanella accanto al profilo (M17): badge con le notifiche non lette, pannello con
* l'elenco al click. Copre quattro sorgenti generate lato database (mai dal client):
* messaggi admin, promemoria automatici, turno palloni, sollecito presenze — vedi
* `src/lib/notifiche-utente.ts`.
*
* Nel progetto non c'è una libreria dropdown: il pannello è un `div` posizionato a mano,
* chiuso al click fuori o con Escape. Aprirlo segna tutte le notifiche come lette; per
* toglierle di mezzo per sempre serve lo swipe o la × di `RigaNotifica`.
*/
export function IconaNotifiche() {
const { notifiche, nonLette } = useNotificheMie();
const segnaLette = useSegnaLette();
const eliminaNotifica = useEliminaNotifica();
const [aperto, setAperto] = useState(false);
const riquadro = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!aperto) return;
const chiudiSeFuori = (e: MouseEvent) => {
if (riquadro.current && !riquadro.current.contains(e.target as Node)) setAperto(false);
};
const chiudiConEsc = (e: KeyboardEvent) => {
if (e.key === "Escape") setAperto(false);
};
document.addEventListener("mousedown", chiudiSeFuori);
document.addEventListener("keydown", chiudiConEsc);
return () => {
document.removeEventListener("mousedown", chiudiSeFuori);
document.removeEventListener("keydown", chiudiConEsc);
};
}, [aperto]);
function alClick() {
const stavaChiuso = !aperto;
setAperto(stavaChiuso);
if (stavaChiuso && nonLette > 0) segnaLette.mutate();
}
return (
<div ref={riquadro} className="relative shrink-0">
<button
type="button"
onClick={alClick}
aria-label={nonLette > 0 ? `Notifiche, ${nonLette} da leggere` : "Notifiche"}
className="premi relative flex h-12 w-12 items-center justify-center rounded-2xl text-primary-foreground ring-2 ring-primary-foreground/30"
>
<Bell className="h-5 w-5" />
{nonLette > 0 ? (
<span className="bg-accent-grad absolute -right-1 -top-1 flex h-5 min-w-5 items-center justify-center rounded-full px-1 text-[11px] font-bold text-accent-foreground shadow-pop">
{contatoreBadge(nonLette)}
</span>
) : null}
</button>
{aperto ? (
<div className="absolute right-0 top-14 z-50 w-72 max-w-[calc(100vw-2.5rem)] rounded-2xl bg-card p-2 text-foreground shadow-card">
{notifiche.length === 0 ? (
<p className="p-3 text-sm text-muted-foreground">Nessuna notifica</p>
) : (
<ul className="max-h-80 overflow-y-auto">
<AnimatePresence initial={false}>
{notifiche.map((n) => (
<RigaNotifica key={n.id} notifica={n} onElimina={eliminaNotifica.mutate} />
))}
</AnimatePresence>
</ul>
)}
</div>
) : null}
</div>
);
}
export function PageHeader({
titolo,
sottotitolo,
@@ -91,7 +241,12 @@ export function PageHeader({
<p className="mt-1 truncate text-sm text-primary-foreground/80">{sottotitolo}</p>
) : null}
</div>
{azione ?? <LinkProfilo />}
{azione ?? (
<div className="flex shrink-0 items-center gap-2">
<IconaNotifiche />
<LinkProfilo />
</div>
)}
</div>
</header>
);
+131
View File
@@ -0,0 +1,131 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { supabaseNuoveTabelle } from "@/integrations/supabase/client-nuove-tabelle";
import { useGiocatoreId } from "./user-store";
/**
* Centro notifiche in-app (M17): icona a campana accanto al profilo, con badge delle non
* lette. Quattro sorgenti riempiono `notifiche_utente` (lato database, mai dal client): un
* messaggio libero dell'admin, un promemoria automatico prima di un evento (24h e 3h), il
* turno palloni e il sollecito presenze (questi due avviati a mano da un admin, in
* parallelo alla push esistente). Qui si legge e si segna come letto, con
* `supabaseNuoveTabelle` perché `types.ts` non include ancora questa tabella (vedi
* client-nuove-tabelle.ts).
*/
export type TipoNotifica =
| "admin"
| "evento_promemoria_24h"
| "evento_promemoria_3h"
| "turno_palloni"
| "sollecita_presenze";
export type NotificaUtente = {
id: string;
tipo: TipoNotifica;
titolo: string;
corpo: string;
eventoId: string | null;
letta: boolean;
creataIl: string;
};
export type RigaNotifica = {
id: string;
tipo: TipoNotifica;
titolo: string;
corpo: string;
evento_id: string | null;
letta: boolean;
creato_il: string;
};
const COLONNE = "id, tipo, titolo, corpo, evento_id, letta, creato_il";
/** Conversione riga database -> modello applicativo. */
export function daRiga(r: RigaNotifica): NotificaUtente {
return {
id: r.id,
tipo: r.tipo,
titolo: r.titolo,
corpo: r.corpo,
eventoId: r.evento_id,
letta: r.letta,
creataIl: r.creato_il,
};
}
function chiaveNotifiche(giocatoreId: string | null) {
return ["notifiche-utente", giocatoreId] as const;
}
/** Ultime notifiche del giocatore selezionato, più recenti per prime. */
export function useNotificheMie() {
const giocatoreId = useGiocatoreId();
const query = useQuery({
queryKey: chiaveNotifiche(giocatoreId),
queryFn: async (): Promise<NotificaUtente[]> => {
const { data, error } = await supabaseNuoveTabelle
.from("notifiche_utente")
.select(COLONNE)
.eq("giocatore_id", giocatoreId)
.order("creato_il", { ascending: false })
.limit(30);
if (error) throw error;
return ((data ?? []) as RigaNotifica[]).map(daRiga);
},
enabled: !!giocatoreId,
staleTime: 30_000,
refetchInterval: 60_000,
});
const notifiche = query.data ?? [];
return { ...query, notifiche, nonLette: notifiche.filter((n) => !n.letta).length };
}
/** Segna come lette tutte le notifiche non lette del giocatore selezionato. */
export function useSegnaLette() {
const giocatoreId = useGiocatoreId();
const qc = useQueryClient();
return useMutation({
mutationFn: async () => {
if (!giocatoreId) return;
const { error } = await supabaseNuoveTabelle
.from("notifiche_utente")
.update({ letta: true })
.eq("giocatore_id", giocatoreId)
.eq("letta", false);
if (error) throw error;
},
onSuccess: () => {
qc.setQueryData<NotificaUtente[]>(chiaveNotifiche(giocatoreId), (prec) =>
(prec ?? []).map((n) => ({ ...n, letta: true })),
);
},
});
}
/**
* Elimina una notifica del giocatore selezionato (swipe o pulsante nel pannello). A
* differenza di "segna come letta" qui la riga sparisce anche dal database, non solo
* dalla vista: non c'è pulizia automatica delle notifiche vecchie, quindi eliminarla è
* l'unico modo per un giocatore di toglierla di mezzo per sempre.
*/
export function useEliminaNotifica() {
const giocatoreId = useGiocatoreId();
const qc = useQueryClient();
return useMutation({
mutationFn: async (id: string) => {
const { error } = await supabaseNuoveTabelle.from("notifiche_utente").delete().eq("id", id);
if (error) throw error;
return id;
},
onSuccess: (id) => {
qc.setQueryData<NotificaUtente[]>(chiaveNotifiche(giocatoreId), (prec) =>
(prec ?? []).filter((n) => n.id !== id),
);
},
});
}
/** Testo del badge: il conteggio esatto fino a 9, poi "9+" per non farlo esplodere. */
export function contatoreBadge(nonLette: number): string {
return nonLette > 9 ? "9+" : String(nonLette);
}
@@ -1,4 +1,5 @@
import { createFileRoute } from "@tanstack/react-router";
import type { SupabaseClient } from "@supabase/supabase-js";
import { z } from "zod";
import { richiediAdmin } from "@/lib/auth-route.server";
import { inviaPush } from "@/lib/webpush.server";
@@ -19,6 +20,9 @@ export const Route = createFileRoute("/api/public/notifica-personalizzata")({
if (!parsed.success) return new Response("Dati non validi", { status: 400 });
const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
// `types.ts` non include ancora `notifiche_utente` (M17): stesso aggiramento di
// `giocatori-squadra.server.ts` finché non viene rigenerato.
const client = supabaseAdmin as unknown as SupabaseClient;
let query = supabaseAdmin.from("push_subscriptions").select("endpoint, p256dh, auth");
if (parsed.data.giocatoreId) {
@@ -46,6 +50,29 @@ export const Route = createFileRoute("/api/public/notifica-personalizzata")({
}
}
// Storico in-app (M17): indipendente dall'esito della push, e non limitato a chi ha
// un dispositivo iscritto. Senza `giocatoreId` va a tutta la rosa attiva.
let destinatariNotifica: string[];
if (parsed.data.giocatoreId) {
destinatariNotifica = [parsed.data.giocatoreId];
} else {
const { data: rosa } = await client
.from("giocatori_squadra")
.select("id")
.eq("attivo", true);
destinatariNotifica = ((rosa ?? []) as Array<{ id: string }>).map((r) => r.id);
}
if (destinatariNotifica.length > 0) {
await client.from("notifiche_utente").insert(
destinatariNotifica.map((giocatoreId) => ({
giocatore_id: giocatoreId,
tipo: "admin",
titolo,
corpo: testo,
})),
);
}
return Response.json({ inviate, destinatari: iscrizioni?.length ?? 0 });
},
},
@@ -1,4 +1,5 @@
import { createFileRoute } from "@tanstack/react-router";
import type { SupabaseClient } from "@supabase/supabase-js";
import { z } from "zod";
import { richiediAdmin } from "@/lib/auth-route.server";
import { nomeCompleto } from "@/lib/giocatori-squadra";
@@ -44,6 +45,24 @@ export const Route = createFileRoute("/api/public/promemoria-palloni")({
const avvisi = avvisiPalloniEvento(turni, eventi, evento.id);
if (avvisi.length === 0) return Response.json({ inviate: 0, destinatari: 0 });
// Storico in-app (M17): un upsert perché ripremere il pulsante deve riportare la
// notifica a non letta con il testo aggiornato, non fallire per il vincolo UNIQUE.
// `types.ts` non include ancora `notifiche_utente`, stesso aggiramento di
// `giocatori-squadra.server.ts`.
const client = supabaseAdmin as unknown as SupabaseClient;
await client.from("notifiche_utente").upsert(
avvisi.map((a) => ({
giocatore_id: a.giocatoreId,
tipo: "turno_palloni",
titolo: a.titolo,
corpo: a.testo,
evento_id: evento.id,
letta: false,
creato_il: new Date().toISOString(),
})),
{ onConflict: "giocatore_id,evento_id,tipo" },
);
const { data: iscrizioni } = await supabaseAdmin
.from("push_subscriptions")
.select("endpoint, giocatore_id, p256dh, auth")
@@ -1,4 +1,5 @@
import { createFileRoute } from "@tanstack/react-router";
import type { SupabaseClient } from "@supabase/supabase-js";
import { z } from "zod";
import { richiediAdmin } from "@/lib/auth-route.server";
import { formatData } from "@/lib/crapp-data";
@@ -48,6 +49,23 @@ export const Route = createFileRoute("/api/public/sollecita-presenze")({
parsed.data.da ? `${parsed.data.da} chiede` : "Serve"
} una conferma: presente, assente o in ritardo?`;
// Storico in-app (M17): un upsert perché ripremere il pulsante deve riportare la
// notifica a non letta, non fallire per il vincolo UNIQUE. `types.ts` non include
// ancora `notifiche_utente`, stesso aggiramento di `giocatori-squadra.server.ts`.
const client = supabaseAdmin as unknown as SupabaseClient;
await client.from("notifiche_utente").upsert(
destinatari.map((giocatoreId) => ({
giocatore_id: giocatoreId,
tipo: "sollecita_presenze",
titolo,
corpo: testo,
evento_id: evento.id,
letta: false,
creato_il: new Date().toISOString(),
})),
{ onConflict: "giocatore_id,evento_id,tipo" },
);
let inviate = 0;
for (const iscrizione of iscrizioni ?? []) {
try {
+12 -2
View File
@@ -2,7 +2,14 @@ import { createFileRoute, Link } from "@tanstack/react-router";
import { Flame, ChevronRight } from "lucide-react";
import { EventoCard, linkPerEvento } from "@/components/crapp/EventoCard";
import { PromemoriaPalloni } from "@/components/crapp/PromemoriaPalloni";
import { Card, LinkProfilo, Section, StatTile, TeamLogo } from "@/components/crapp/ui-bits";
import {
Card,
IconaNotifiche,
LinkProfilo,
Section,
StatTile,
TeamLogo,
} from "@/components/crapp/ui-bits";
import { CompletaProfilo } from "@/components/crapp/ProfiloAmministrativo";
import { Reveal } from "@/components/motion/Reveal";
import { Barra } from "@/components/motion/Barra";
@@ -83,7 +90,10 @@ function Index() {
<h1 className="font-display-lg text-4xl uppercase leading-none">CRAP Volley</h1>
</div>
</div>
<LinkProfilo />
<div className="flex shrink-0 items-center gap-2">
<IconaNotifiche />
<LinkProfilo />
</div>
</div>
<div className="mt-6 grid grid-cols-3 gap-2 text-center">