5 Commits
Author SHA1 Message Date
davideandClaude Sonnet 5 c1744d4087 Sposta avatar e documenti profilo su PocketBase (file field)
Sostituisce i due bucket Supabase Storage con campi file PocketBase:

- avatar-giocatori: nuova collection avatar_giocatori separata da
  giocatori_squadra, perché la policy originale ("chiunque autenticato
  carica/sostituisce/elimina qualsiasi avatar, nessun controllo
  proprietario") è più permissiva delle regole di giocatori_squadra —
  mescolarle avrebbe indebolito le une o bloccato l'altra. File pubblico,
  come il bucket originale;
- profili-giocatore: campi file su profili_giocatore stesso, con
  protected: true (vedi sotto).

Trovato e corretto un problema di sicurezza reale: PocketBase rende i
file pubblici di default (si affida solo alla casualità del nome file),
a meno di impostare esplicitamente protected: true sul campo — i
documenti d'identità e i certificati medici sarebbero stati raggiungibili
senza autenticazione, in violazione di DD-016 regola 4. Verificato che
ora servono un token valido (404 senza, 200 con).

La scrittura dei campi testuali del profilo e il caricamento dei file
sono due operazioni separate (PocketBase rifiuta una stringa dove si
aspetta un file): verificato che caricare un documento non cancella i
dati testuali già salvati.

Rimossi da profili-core.ts RigaProfilo/daRigaProfilo/aRigaProfilo
(shape Postgres non più usata da nessun modulo di produzione) e
rimuoviFile (mai chiamato da nessun componente). Avatar.tsx non usa più
un URL deterministico per giocatore: PocketBase genera nomi file
casuali, quindi legge la mappa avatar tramite una query React Query
condivisa tra tutte le istanze del componente.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-11 14:58:54 +02:00
davideandClaude Sonnet 5 d125bdfb6a Sposta le route di notifiche push su PocketBase
Le route server in src/routes/api/public/ (promemoria-palloni,
sollecita-presenze, apri-sondaggio, push-subscribe, notifiche-attive)
usano pbAdmin al posto di supabaseAdmin per leggere/scrivere
push_subscriptions e i dati necessari a comporre gli avvisi.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-11 14:58:40 +02:00
davideandClaude Sonnet 5 689468141d Sposta roster, eventi, presenze, voti, scout e palloni su PocketBase
Riscrive i moduli dati che parlavano con Supabase per usare l'SDK
PocketBase, mantenendo invariate le firme degli hook React Query così i
componenti a valle non cambiano: giocatori-squadra, eventi, presenze,
cacche, pagelle, mvp-voti, badge-social, scout (store/live/stato),
palloni.

Aggiunge due helper condivisi in src/integrations/pocketbase/:
- upsert.ts: PocketBase non ha upsert nativo, questi replicano il
  pattern onConflict di Supabase (per id significativo o per filtro su
  combinazione di campi), verificati contro un'istanza reale così da non
  duplicare record sulla stessa scrittura ripetuta;
- formato.ts: normalizza le date PocketBase ("AAAA-MM-GG HH:MM:SS.sssZ",
  spazio non "T") a ISO stretto, altrimenti Date.parse e i confronti
  testuali con altre date si comportano in modo incoerente.

Corregge anche due problemi trovati testando contro un'istanza reale:
- alcune API rule confrontavano un campo relazione con @request.auth.id
  senza richiedere l'autenticazione, lasciando passare richieste anonime
  quando entrambi i lati erano vuoti;
- gli hook non riconoscevano il superuser PocketBase (solo il ruolo
  admin applicativo), bloccando le operazioni fatte con pbAdmin.

Aggiunta la colonna "casa" mancante su eventi_app e i campi di sistema
created/updated (non generati automaticamente da PocketBase per le
collection create via migration, a differenza di quanto assunto
inizialmente).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-11 14:58:27 +02:00
davideandClaude Sonnet 5 0f5a27ed5f Sposta l'autenticazione da Supabase a PocketBase
Login Google via PocketBase invece che Supabase Auth: nuovi client
in src/integrations/pocketbase/ (browser, server con superuser, attacher
del bearer token per le server function). Il ruolo admin/user vive ora
come campo diretto sul record utente PocketBase invece che nella tabella
separata user_roles, quindi ruoli.ts e la verifica in auth-route.server.ts
non hanno più bisogno di una query aggiuntiva.

requireSupabaseAuth/auth-middleware.ts non viene riportato: non era
importato da nessun file, era codice morto.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-11 14:58:09 +02:00
davideandClaude Sonnet 5 15885f32c7 Aggiunge infrastruttura PocketBase locale (Docker, schema, hook)
Introduce PocketBase come sostituto di Supabase solo per l'ambiente di
sviluppo locale (docs/PORTABILITA.md): docker-compose.pocketbase.yml,
schema iniziale in pocketbase/pb_migrations/ (collection equivalenti alle
tabelle Supabase, con le stesse API rule dove esprimibili) e la logica
procedurale che in Postgres viveva in trigger/funzioni riscritta come
hook JS in pocketbase/pb_hooks/ (claim slot giocatore, blocco autovoto,
convocati/pagelle chiuse, immutabilità di risposto_il).

Il superuser e il provider Google OAuth2 si ricreano da soli a ogni
avvio da variabili d'ambiente (script scripts/pocketbase-reset.sh),
così un reset non richiede passaggi manuali da dashboard.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-11 14:57:55 +02:00
51 changed files with 1862 additions and 629 deletions
+4
View File
@@ -41,3 +41,7 @@ dist-ssr
.vercel
# Supabase CLI local state
supabase/.temp/
# PocketBase locale (dati e log runtime, non lo schema in pb_migrations/pb_hooks)
pocketbase/pb_data/*
!pocketbase/pb_data/.gitkeep
+9
View File
@@ -55,6 +55,15 @@ Il progetto richiede le seguenti variabili:
- `VITE_SUPABASE_URL`
- `VITE_SUPABASE_PUBLISHABLE_KEY`
Solo per lo sviluppo locale con PocketBase al posto di Supabase (vedi
[docs/PORTABILITA.md](docs/PORTABILITA.md)):
- `VITE_POCKETBASE_URL` / `POCKETBASE_URL``http://127.0.0.1:8090` con
`docker-compose.pocketbase.yml`
- `POCKETBASE_SUPERUSER_EMAIL` / `POCKETBASE_SUPERUSER_PASSWORD` — credenziali del
superuser creato al primo avvio, usate solo dalle route server che oggi usano
`supabaseAdmin`
## Documentazione
Indice in [docs/README.md](docs/README.md). Le regole per gli assistenti AI stanno in
+3
View File
@@ -15,6 +15,7 @@
"clsx": "^2.1.1",
"lucide-react": "^0.575.0",
"motion": "^13.2.0",
"pocketbase": "^0.28.1",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"sonner": "^2.0.7",
@@ -651,6 +652,8 @@
"picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="],
"pocketbase": ["pocketbase@0.28.1", "", {}, "sha512-/3ihkq+rvfcs0MQgrK4sEElOg6gfenHW9S/O+3BSO+V1yT+4B10+9aT22uTQUPqze9ItwNtwWyY5ZmdgVCTdVA=="],
"postcss": ["postcss@8.5.24", "", { "dependencies": { "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-8RyVklq0owXUTa4xlpzu4l9AaVKIdQvAcOHZWaMh98HgySsUtxRVf/chRe3dsSLqb6i40BzGRzEUddRaI+9TSw=="],
"prelude-ls": ["prelude-ls@1.2.1", "", {}, "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g=="],
+38
View File
@@ -0,0 +1,38 @@
# PocketBase locale per lo sviluppo (sostituisce "npx supabase start" solo in locale,
# vedi docs/PORTABILITA.md e la voce DD relativa). La produzione resta su Supabase.
#
# Uso:
# docker compose -f docker-compose.pocketbase.yml up -d # avvia
# docker compose -f docker-compose.pocketbase.yml down # ferma
# docker compose -f docker-compose.pocketbase.yml down -v # ferma e azzera i dati locali
#
# Dashboard admin: http://127.0.0.1:8090/_/
# API: http://127.0.0.1:8090/api/
services:
pocketbase:
image: ghcr.io/muchobien/pocketbase:latest
container_name: crapp-pocketbase
restart: unless-stopped
# --automigrate=0: le modifiche fatte da dashboard (es. abilitare un provider OAuth2,
# con relativo client secret) NON devono finire come file di migration versionati in
# git. Le migration restano solo quelle scritte a mano in pocketbase/pb_migrations/.
command: ["--automigrate=0"]
env_file:
- .env
environment:
# L'immagine crea il superuser da queste variabili a ogni avvio (idempotente):
# sopravvive a "npm run pocketbase:reset" senza passaggi manuali.
PB_ADMIN_EMAIL: ${POCKETBASE_SUPERUSER_EMAIL:-}
PB_ADMIN_PASSWORD: ${POCKETBASE_SUPERUSER_PASSWORD:-}
ports:
- "8090:8090"
volumes:
- ./pocketbase/pb_data:/pb_data
- ./pocketbase/pb_migrations:/pb_migrations
- ./pocketbase/pb_hooks:/pb_hooks
healthcheck:
test: ["CMD", "wget", "--spider", "-q", "http://127.0.0.1:8090/api/health"]
interval: 5s
timeout: 3s
retries: 5
+1 -1
View File
@@ -6,7 +6,7 @@ import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint";
export default tseslint.config(
{ ignores: ["dist", ".output", ".vinxi"] },
{ ignores: ["dist", ".output", ".vinxi", "pocketbase/pb_data"] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ["**/*.{ts,tsx}"],
+5 -1
View File
@@ -14,7 +14,10 @@
"test": "bun test/run.ts",
"test:integration": "bun test/run.ts integration",
"test:e2e": "bun test/run.ts e2e",
"test:all": "bun test/run.ts all"
"test:all": "bun test/run.ts all",
"pocketbase:start": "docker compose -f docker-compose.pocketbase.yml up -d",
"pocketbase:stop": "docker compose -f docker-compose.pocketbase.yml down",
"pocketbase:reset": "bash scripts/pocketbase-reset.sh"
},
"dependencies": {
"@supabase/supabase-js": "^2.111.0",
@@ -27,6 +30,7 @@
"clsx": "^2.1.1",
"lucide-react": "^0.575.0",
"motion": "^13.2.0",
"pocketbase": "^0.28.1",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"sonner": "^2.0.7",
View File
@@ -0,0 +1,49 @@
/// <reference path="../pb_data/types.d.ts" />
//
// Equivalente del trigger enforce_giocatori_squadra_update (M1/M5/M8, DD-016/DD-018):
// un non-admin può aggiornare uno slot di giocatori_squadra solo per reclamarlo (slot
// libero, email dell'account uguale a quella registrata sulla riga), senza cambiare nessun
// altro campo. La updateRule della collection apre la porta solo quando auth_user_id è
// vuoto o l'utente è admin; qui si valida il resto.
onRecordUpdateRequest((e) => {
// Superuser (pbAdmin lato server, dashboard, script di migrazione dati) e admin
// applicativi (role="admin" sulla collection users) bypassano il vincolo di claim.
const isAdmin = e.hasSuperuserAuth() || (e.auth && e.auth.get("role") === "admin");
if (isAdmin) {
e.next();
return;
}
const originale = e.app.findRecordById("giocatori_squadra", e.record.id);
const campiBloccati = [
"nome",
"cognome",
"numero",
"ruolo",
"attivo",
"email",
"numero_tessera",
"data_tessera",
];
for (const campo of campiBloccati) {
if (String(e.record.get(campo)) !== String(originale.get(campo))) {
throw new BadRequestError("Aggiornamento non autorizzato su giocatori_squadra");
}
}
const utenteId = e.auth ? e.auth.id : "";
const emailAccount = (e.auth ? e.auth.get("email") || "" : "").toLowerCase();
const emailSlot = (originale.get("email") || "").toLowerCase();
const slotLibero = !originale.get("auth_user_id");
const claimSuAccountCorrente = e.record.get("auth_user_id") === utenteId;
const emailCombacia = emailSlot !== "" && emailSlot === emailAccount;
if (!slotLibero || !claimSuAccountCorrente || !emailCombacia) {
throw new BadRequestError("Aggiornamento non autorizzato su giocatori_squadra");
}
e.next();
}, "giocatori_squadra");
+23
View File
@@ -0,0 +1,23 @@
/// <reference path="../pb_data/types.d.ts" />
//
// Il Client ID/Secret di Google OAuth2 configurati da dashboard vivono in pb_data e
// andrebbero persi a ogni "npm run pocketbase:reset" (azzera pb_data). Questo hook li
// reimposta a ogni avvio da variabili d'ambiente (mai committate, solo in .env), così
// sopravvivono al reset senza reinserirli a mano ogni volta dalla dashboard.
onBootstrap((e) => {
e.next();
const clientId = $os.getenv("GOOGLE_OAUTH_CLIENT_ID");
const clientSecret = $os.getenv("GOOGLE_OAUTH_CLIENT_SECRET");
if (!clientId || !clientSecret) {
return;
}
const collection = e.app.findCollectionByNameOrId("users");
collection.oauth2.enabled = true;
collection.oauth2.providers = [
{ name: "google", clientId: clientId, clientSecret: clientSecret },
];
e.app.save(collection);
});
@@ -0,0 +1,16 @@
/// <reference path="../pb_data/types.d.ts" />
//
// Equivalente del trigger risposte_presenze_risposto_il_immutabile (M9): risposto_il è
// l'istante della PRIMA risposta, scritto una sola volta e mai più modificabile — serve
// per la serie "Conferme 24h" (confronto con eventi_app.created).
onRecordCreateRequest((e) => {
e.record.set("risposto_il", new Date().toISOString());
e.next();
}, "risposte_presenze");
onRecordUpdateRequest((e) => {
const originale = e.app.findRecordById("risposte_presenze", e.record.id);
e.record.set("risposto_il", originale.get("risposto_il"));
e.next();
}, "risposte_presenze");
+137
View File
@@ -0,0 +1,137 @@
/// <reference path="../pb_data/types.d.ts" />
//
// Equivalente di evento_permette_voto() + i CHECK "no autovoto" (M12/M13): applicato a
// mvp_voti, pagelle_voti, badge_social_voti su create/update. Gli admin non hanno questi
// vincoli (possono correggere un voto anche fuori convocazione/dopo la chiusura pagelle).
// convocati vuoto = "tutta la rosa" (stessa convenzione di convocatiEvento() in eventi.ts).
//
// La validazione è ripetuta in ciascun callback (non estratta in una funzione condivisa a
// livello di file): ogni hook di PocketBase viene eseguito nel proprio contesto JS isolato,
// che non vede le funzioni dichiarate fuori dal callback stesso (verificato empiricamente:
// una funzione condivisa causa "ReferenceError: ... is not defined" a runtime).
onRecordCreateRequest((e) => {
const isAdmin = e.hasSuperuserAuth() || (e.auth && e.auth.get("role") === "admin");
if (!isAdmin) {
const votanteId = e.record.get("votante");
const votatoId = e.record.get("votato");
if (votanteId === votatoId) {
throw new BadRequestError("Non puoi votare te stesso");
}
const evento = e.app.findRecordById("eventi_app", e.record.get("evento"));
const convocati = evento.get("convocati") || [];
if (
convocati.length > 0 &&
(convocati.indexOf(votanteId) === -1 || convocati.indexOf(votatoId) === -1)
) {
throw new BadRequestError("Votante e votato devono essere convocati all'evento");
}
}
e.next();
}, "mvp_voti");
onRecordUpdateRequest((e) => {
const isAdmin = e.hasSuperuserAuth() || (e.auth && e.auth.get("role") === "admin");
if (!isAdmin) {
const votanteId = e.record.get("votante");
const votatoId = e.record.get("votato");
if (votanteId === votatoId) {
throw new BadRequestError("Non puoi votare te stesso");
}
const evento = e.app.findRecordById("eventi_app", e.record.get("evento"));
const convocati = evento.get("convocati") || [];
if (
convocati.length > 0 &&
(convocati.indexOf(votanteId) === -1 || convocati.indexOf(votatoId) === -1)
) {
throw new BadRequestError("Votante e votato devono essere convocati all'evento");
}
}
e.next();
}, "mvp_voti");
onRecordCreateRequest((e) => {
const isAdmin = e.hasSuperuserAuth() || (e.auth && e.auth.get("role") === "admin");
if (!isAdmin) {
const votanteId = e.record.get("votante");
const votatoId = e.record.get("votato");
if (votanteId === votatoId) {
throw new BadRequestError("Non puoi votare te stesso");
}
const evento = e.app.findRecordById("eventi_app", e.record.get("evento"));
const convocati = evento.get("convocati") || [];
if (
convocati.length > 0 &&
(convocati.indexOf(votanteId) === -1 || convocati.indexOf(votatoId) === -1)
) {
throw new BadRequestError("Votante e votato devono essere convocati all'evento");
}
if (evento.get("pagelle_chiuse")) {
throw new BadRequestError("Le pagelle per questo evento sono chiuse");
}
}
e.next();
}, "pagelle_voti");
onRecordUpdateRequest((e) => {
const isAdmin = e.hasSuperuserAuth() || (e.auth && e.auth.get("role") === "admin");
if (!isAdmin) {
const votanteId = e.record.get("votante");
const votatoId = e.record.get("votato");
if (votanteId === votatoId) {
throw new BadRequestError("Non puoi votare te stesso");
}
const evento = e.app.findRecordById("eventi_app", e.record.get("evento"));
const convocati = evento.get("convocati") || [];
if (
convocati.length > 0 &&
(convocati.indexOf(votanteId) === -1 || convocati.indexOf(votatoId) === -1)
) {
throw new BadRequestError("Votante e votato devono essere convocati all'evento");
}
if (evento.get("pagelle_chiuse")) {
throw new BadRequestError("Le pagelle per questo evento sono chiuse");
}
}
e.next();
}, "pagelle_voti");
onRecordCreateRequest((e) => {
const isAdmin = e.hasSuperuserAuth() || (e.auth && e.auth.get("role") === "admin");
if (!isAdmin) {
const votanteId = e.record.get("votante");
const votatoId = e.record.get("votato");
if (votanteId === votatoId) {
throw new BadRequestError("Non puoi votare te stesso");
}
const evento = e.app.findRecordById("eventi_app", e.record.get("evento"));
const convocati = evento.get("convocati") || [];
if (
convocati.length > 0 &&
(convocati.indexOf(votanteId) === -1 || convocati.indexOf(votatoId) === -1)
) {
throw new BadRequestError("Votante e votato devono essere convocati all'evento");
}
}
e.next();
}, "badge_social_voti");
onRecordUpdateRequest((e) => {
const isAdmin = e.hasSuperuserAuth() || (e.auth && e.auth.get("role") === "admin");
if (!isAdmin) {
const votanteId = e.record.get("votante");
const votatoId = e.record.get("votato");
if (votanteId === votatoId) {
throw new BadRequestError("Non puoi votare te stesso");
}
const evento = e.app.findRecordById("eventi_app", e.record.get("evento"));
const convocati = evento.get("convocati") || [];
if (
convocati.length > 0 &&
(convocati.indexOf(votanteId) === -1 || convocati.indexOf(votatoId) === -1)
) {
throw new BadRequestError("Votante e votato devono essere convocati all'evento");
}
}
e.next();
}, "badge_social_voti");
@@ -0,0 +1,665 @@
/// <reference path="../pb_data/types.d.ts" />
//
// Schema iniziale PocketBase per CrAPP — solo ambiente locale (Docker).
//
// Non è la riproduzione 1:1 delle 27 migration Supabase in supabase/migrations/: rappresenta
// lo STATO FINALE attuale dello schema (fonte: docs/DATABASE.md + lettura diretta delle
// migration Supabase più recenti), riscritto nel modello PocketBase (collection + campi +
// API rules). Le tabelle Supabase non più usate dal codice (`giocatori`, `eventi`/`presenze`
// "nuovo modello" mai adottato, `promemoria_push` deprecata) non vengono portate.
//
// `user_roles` non diventa una collection: il ruolo admin/user è un campo diretto sulla
// collection auth nativa `users` (decisione 3 del piano di migrazione).
//
// La logica procedurale che in Postgres viveva in trigger/funzioni (claim-slot su
// giocatori_squadra, blocco autovoto, convocati/pagelle_chiuse, cascata su cancellazione
// evento, risposto_il immutabile) NON sta qui: è in pb_hooks/*.pb.js, perché le API rules di
// PocketBase sono espressioni, non codice procedurale.
migrate(
(app) => {
// ---------------------------------------------------------------------------------------
// users (collection auth nativa): aggiunge il campo ruolo che sostituisce user_roles.
// ---------------------------------------------------------------------------------------
const users = app.findCollectionByNameOrId("users");
users.fields.add(
new Field({
name: "role",
type: "select",
required: true,
values: ["user", "admin"],
maxSelect: 1,
}),
);
// Ogni utente autenticato legge il proprio record; l'admin (verificato lato hook al primo
// login, poi qui) può leggere tutti. Il ruolo lo scrive solo chi è già admin.
users.listRule = "id = @request.auth.id || @request.auth.role = 'admin'";
users.viewRule = "id = @request.auth.id || @request.auth.role = 'admin'";
users.updateRule = "id = @request.auth.id";
app.save(users);
// ---------------------------------------------------------------------------------------
// giocatori_squadra — anagrafica operativa della squadra (DD-015, DD-016, DD-018)
// ---------------------------------------------------------------------------------------
const giocatori = new Collection({
name: "giocatori_squadra",
type: "base",
fields: [
// Id testuali corti (g1..gN, come in Supabase): il vincolo di default di PocketBase
// (minimo 15 caratteri) va rilassato esplicitamente.
{ name: "id", type: "text", min: 1, max: 40, pattern: "^g[0-9]+$" },
{ name: "nome", type: "text", required: true },
{ name: "cognome", type: "text", required: true },
{ name: "numero", type: "number", required: true, min: 1 },
{ name: "ruolo", type: "text", required: true },
{
name: "auth_user_id",
type: "relation",
required: false,
collectionId: users.id,
maxSelect: 1,
},
{ name: "email", type: "email", required: false },
{ name: "attivo", type: "bool", required: false },
{ name: "numero_tessera", type: "text", required: false },
{ name: "data_tessera", type: "date", required: false },
{ name: "created", type: "autodate", onCreate: true },
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
],
indexes: [
"CREATE UNIQUE INDEX idx_giocatori_squadra_auth_user ON giocatori_squadra (auth_user_id) WHERE auth_user_id != ''",
"CREATE UNIQUE INDEX idx_giocatori_squadra_email ON giocatori_squadra (email) WHERE email != ''",
],
// Lettura: rosa attiva a tutti gli autenticati, tutta la rosa agli admin (DD-015/M1).
listRule: "@request.auth.id != '' && (attivo = true || @request.auth.role = 'admin')",
viewRule: "@request.auth.id != '' && (attivo = true || @request.auth.role = 'admin')",
// Creazione slot: solo admin.
createRule: "@request.auth.role = 'admin'",
// Aggiornamento: admin senza vincoli, oppure claim di uno slot libero — il resto
// (che il claim tocchi solo auth_user_id e rispetti l'email) lo valida l'hook
// giocatori_squadra_claim.pb.js, la rule qui apre solo la porta.
updateRule: "@request.auth.role = 'admin' || (@request.auth.id != '' && auth_user_id = '')",
deleteRule: "@request.auth.role = 'admin'",
});
app.save(giocatori);
// ---------------------------------------------------------------------------------------
// profili_giocatore — dati personali/documento/certificato, 1:1 con giocatori_squadra
// ---------------------------------------------------------------------------------------
const profili = new Collection({
name: "profili_giocatore",
type: "base",
fields: [
{
name: "giocatore",
type: "relation",
required: true,
collectionId: giocatori.id,
maxSelect: 1,
cascadeDelete: true,
},
{ name: "data_nascita", type: "date", required: false },
{ name: "luogo_nascita", type: "text", required: false },
{ name: "indirizzo", type: "text", required: false },
{ name: "telefono", type: "text", required: false },
{ name: "email", type: "email", required: false },
{
name: "documento_tipo",
type: "select",
required: false,
maxSelect: 1,
values: ["Carta d'identità", "Passaporto", "Patente"],
},
{ name: "documento_numero", type: "text", required: false },
{ name: "documento_rilasciato_da", type: "text", required: false },
{ name: "documento_emissione", type: "date", required: false },
{ name: "documento_scadenza", type: "date", required: false },
{
name: "documento_fronte",
type: "file",
required: false,
protected: true,
maxSelect: 1,
maxSize: 10485760,
mimeTypes: ["image/jpeg", "image/png", "image/webp", "application/pdf"],
},
{
name: "documento_retro",
type: "file",
required: false,
protected: true,
maxSelect: 1,
maxSize: 10485760,
mimeTypes: ["image/jpeg", "image/png", "image/webp", "application/pdf"],
},
{ name: "certificato_scadenza", type: "date", required: false },
{
name: "certificato",
type: "file",
required: false,
protected: true,
maxSelect: 1,
maxSize: 10485760,
mimeTypes: ["image/jpeg", "image/png", "image/webp", "application/pdf"],
},
{
name: "foto",
type: "file",
required: false,
protected: true,
maxSelect: 1,
maxSize: 10485760,
mimeTypes: ["image/jpeg", "image/png", "image/webp"],
},
{ name: "created", type: "autodate", onCreate: true },
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
],
indexes: [
"CREATE UNIQUE INDEX idx_profili_giocatore_giocatore ON profili_giocatore (giocatore)",
],
// Documenti sanitari/identità: mai pubblici (DD-016 regola 4). Solo il giocatore
// proprietario o un admin, sia per i campi sia per i file allegati (le API rules
// governano anche il download dei file in PocketBase, non serve un bucket a parte).
listRule:
"@request.auth.id != '' && (giocatore.auth_user_id = @request.auth.id || @request.auth.role = 'admin')",
viewRule:
"@request.auth.id != '' && (giocatore.auth_user_id = @request.auth.id || @request.auth.role = 'admin')",
createRule:
"@request.auth.id != '' && (giocatore.auth_user_id = @request.auth.id || @request.auth.role = 'admin')",
updateRule:
"@request.auth.id != '' && (giocatore.auth_user_id = @request.auth.id || @request.auth.role = 'admin')",
deleteRule: "@request.auth.role = 'admin'",
});
app.save(profili);
// ---------------------------------------------------------------------------------------
// avatar_giocatori — foto profilo pubbliche (M6 avatar-giocatori). Collection separata
// da giocatori_squadra: la policy è "chiunque autenticato carica/sostituisce/elimina
// qualsiasi avatar" (nessun controllo per-proprietario, DD in docs/DATABASE.md), molto
// più permissiva delle regole di giocatori_squadra — mescolarle avrebbe o indebolito
// quelle o impedito il caricamento a chi non è admin.
// ---------------------------------------------------------------------------------------
const avatar = new Collection({
name: "avatar_giocatori",
type: "base",
fields: [
{
name: "giocatore",
type: "relation",
required: true,
collectionId: giocatori.id,
maxSelect: 1,
cascadeDelete: true,
},
{
name: "foto",
type: "file",
required: false,
maxSelect: 1,
maxSize: 5242880,
mimeTypes: ["image/jpeg"],
},
{ name: "created", type: "autodate", onCreate: true },
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
],
indexes: [
"CREATE UNIQUE INDEX idx_avatar_giocatori_giocatore ON avatar_giocatori (giocatore)",
],
// Bucket pubblico in Supabase: leggibile da chiunque, anche senza login.
listRule: "",
viewRule: "",
createRule: "@request.auth.id != ''",
updateRule: "@request.auth.id != ''",
deleteRule: "@request.auth.id != ''",
});
app.save(avatar);
// ---------------------------------------------------------------------------------------
// eventi_app — eventi gestionali (partite/allenamenti/eventi squadra)
// ---------------------------------------------------------------------------------------
const eventi = new Collection({
name: "eventi_app",
type: "base",
fields: [
// Id testuali corti (e1..eN, come in Supabase).
{ name: "id", type: "text", min: 1, max: 40, pattern: "^e[0-9]+$" },
{
name: "tipo",
type: "select",
required: true,
maxSelect: 1,
values: ["partita", "allenamento", "evento"],
},
{ name: "titolo", type: "text", required: true },
{ name: "luogo", type: "text", required: false },
{ name: "data", type: "date", required: true },
{ name: "ora", type: "text", required: false },
{ name: "note", type: "text", required: false },
{
name: "convocati",
type: "relation",
required: false,
collectionId: giocatori.id,
maxSelect: 999,
},
{ name: "campionato", type: "bool", required: false },
{ name: "casa", type: "bool", required: false },
{ name: "pagelle_chiuse", type: "bool", required: false },
{ name: "created", type: "autodate", onCreate: true },
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
],
// Lettura aperta a tutti gli autenticati; scrittura solo admin (rotta /eventi già
// riservata — M11/DD-023).
listRule: "@request.auth.id != ''",
viewRule: "@request.auth.id != ''",
createRule: "@request.auth.role = 'admin'",
updateRule: "@request.auth.role = 'admin'",
deleteRule: "@request.auth.role = 'admin'",
});
app.save(eventi);
// ---------------------------------------------------------------------------------------
// risposte_presenze — risposte dei giocatori agli eventi
// ---------------------------------------------------------------------------------------
const presenze = new Collection({
name: "risposte_presenze",
type: "base",
fields: [
{
name: "evento",
type: "relation",
required: true,
collectionId: eventi.id,
maxSelect: 1,
cascadeDelete: true,
},
{
name: "giocatore",
type: "relation",
required: true,
collectionId: giocatori.id,
maxSelect: 1,
},
{ name: "stato", type: "text", required: true },
// Istante della PRIMA risposta (M9): valorizzato e reso immutabile dall'hook
// risposte_presenze_immutabili.pb.js, non scrivibile direttamente dal client.
{ name: "risposto_il", type: "date", required: false },
{ name: "created", type: "autodate", onCreate: true },
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
],
indexes: [
"CREATE UNIQUE INDEX idx_risposte_presenze_evento_giocatore ON risposte_presenze (evento, giocatore)",
],
listRule: "@request.auth.id != ''",
viewRule: "@request.auth.id != ''",
createRule:
"@request.auth.role = 'admin' || (@request.auth.id != '' && giocatore.auth_user_id = @request.auth.id)",
updateRule:
"@request.auth.role = 'admin' || (@request.auth.id != '' && giocatore.auth_user_id = @request.auth.id)",
deleteRule:
"@request.auth.role = 'admin' || (@request.auth.id != '' && giocatore.auth_user_id = @request.auth.id)",
});
app.save(presenze);
// ---------------------------------------------------------------------------------------
// cacche_partita — sondaggio pre-partita (statistiche/badge segreti)
// ---------------------------------------------------------------------------------------
const cacche = new Collection({
name: "cacche_partita",
type: "base",
fields: [
{
name: "evento",
type: "relation",
required: true,
collectionId: eventi.id,
maxSelect: 1,
cascadeDelete: true,
},
{
name: "giocatore",
type: "relation",
required: true,
collectionId: giocatori.id,
maxSelect: 1,
},
{ name: "quantita", type: "number", required: true, min: 0, max: 10 },
{ name: "created", type: "autodate", onCreate: true },
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
],
indexes: [
"CREATE UNIQUE INDEX idx_cacche_partita_evento_giocatore ON cacche_partita (evento, giocatore)",
],
listRule: "@request.auth.id != ''",
viewRule: "@request.auth.id != ''",
createRule:
"@request.auth.role = 'admin' || (@request.auth.id != '' && giocatore.auth_user_id = @request.auth.id)",
updateRule:
"@request.auth.role = 'admin' || (@request.auth.id != '' && giocatore.auth_user_id = @request.auth.id)",
deleteRule:
"@request.auth.role = 'admin' || (@request.auth.id != '' && giocatore.auth_user_id = @request.auth.id)",
});
app.save(cacche);
// ---------------------------------------------------------------------------------------
// mvp_voti / pagelle_voti / badge_social_voti — votazioni tra compagni
//
// Ownership (votante = chi scrive) è espressa qui via API rule. Autovoto e vincoli
// "convocato all'evento" / "pagelle non chiuse" (M12/M13) NON sono esprimibili in modo
// sicuro come semplice espressione di rule su relazioni multiple: li applica l'hook
// pb_hooks/voti_convocati.pb.js su create/update, per tutte e tre le collection.
// ---------------------------------------------------------------------------------------
const mvpVoti = new Collection({
name: "mvp_voti",
type: "base",
fields: [
{
name: "evento",
type: "relation",
required: true,
collectionId: eventi.id,
maxSelect: 1,
cascadeDelete: true,
},
{
name: "votante",
type: "relation",
required: true,
collectionId: giocatori.id,
maxSelect: 1,
},
{
name: "votato",
type: "relation",
required: true,
collectionId: giocatori.id,
maxSelect: 1,
},
{ name: "votato_nome", type: "text", required: true },
{ name: "created", type: "autodate", onCreate: true },
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
],
indexes: ["CREATE UNIQUE INDEX idx_mvp_voti_evento_votante ON mvp_voti (evento, votante)"],
listRule: "@request.auth.id != ''",
viewRule: "@request.auth.id != ''",
createRule:
"@request.auth.role = 'admin' || (@request.auth.id != '' && votante.auth_user_id = @request.auth.id)",
updateRule:
"@request.auth.role = 'admin' || (@request.auth.id != '' && votante.auth_user_id = @request.auth.id)",
deleteRule:
"@request.auth.role = 'admin' || (@request.auth.id != '' && votante.auth_user_id = @request.auth.id)",
});
app.save(mvpVoti);
const pagelleVoti = new Collection({
name: "pagelle_voti",
type: "base",
fields: [
{
name: "evento",
type: "relation",
required: true,
collectionId: eventi.id,
maxSelect: 1,
cascadeDelete: true,
},
{
name: "votante",
type: "relation",
required: true,
collectionId: giocatori.id,
maxSelect: 1,
},
{
name: "votato",
type: "relation",
required: true,
collectionId: giocatori.id,
maxSelect: 1,
},
{ name: "voto", type: "number", required: true, min: 1, max: 10 },
{ name: "created", type: "autodate", onCreate: true },
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
],
indexes: [
"CREATE UNIQUE INDEX idx_pagelle_voti_evento_votante_votato ON pagelle_voti (evento, votante, votato)",
],
listRule: "@request.auth.id != ''",
viewRule: "@request.auth.id != ''",
createRule:
"@request.auth.role = 'admin' || (@request.auth.id != '' && votante.auth_user_id = @request.auth.id)",
updateRule:
"@request.auth.role = 'admin' || (@request.auth.id != '' && votante.auth_user_id = @request.auth.id)",
deleteRule:
"@request.auth.role = 'admin' || (@request.auth.id != '' && votante.auth_user_id = @request.auth.id)",
});
app.save(pagelleVoti);
const badgeSocialVoti = new Collection({
name: "badge_social_voti",
type: "base",
fields: [
{
name: "evento",
type: "relation",
required: true,
collectionId: eventi.id,
maxSelect: 1,
cascadeDelete: true,
},
{ name: "categoria", type: "text", required: true },
{
name: "votante",
type: "relation",
required: true,
collectionId: giocatori.id,
maxSelect: 1,
},
{
name: "votato",
type: "relation",
required: true,
collectionId: giocatori.id,
maxSelect: 1,
},
{ name: "votato_nome", type: "text", required: true },
{ name: "created", type: "autodate", onCreate: true },
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
],
indexes: [
"CREATE UNIQUE INDEX idx_badge_social_voti_evento_categoria_votante ON badge_social_voti (evento, categoria, votante)",
],
listRule: "@request.auth.id != ''",
viewRule: "@request.auth.id != ''",
createRule:
"@request.auth.role = 'admin' || (@request.auth.id != '' && votante.auth_user_id = @request.auth.id)",
updateRule:
"@request.auth.role = 'admin' || (@request.auth.id != '' && votante.auth_user_id = @request.auth.id)",
deleteRule:
"@request.auth.role = 'admin' || (@request.auth.id != '' && votante.auth_user_id = @request.auth.id)",
});
app.save(badgeSocialVoti);
// ---------------------------------------------------------------------------------------
// turni_palloni / scout_sessioni / scout_live / scout_partite — nessun gate in UI,
// aperte a qualsiasi autenticato (invariato da Supabase, vedi docs/DATABASE.md).
// ---------------------------------------------------------------------------------------
const turniPalloni = new Collection({
name: "turni_palloni",
type: "base",
fields: [
{
name: "evento",
type: "relation",
required: true,
collectionId: eventi.id,
maxSelect: 1,
cascadeDelete: true,
},
{
name: "giocatore",
type: "relation",
required: true,
collectionId: giocatori.id,
maxSelect: 1,
},
{ name: "aggiornato_da", type: "text", required: false },
{ name: "created", type: "autodate", onCreate: true },
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
],
indexes: ["CREATE UNIQUE INDEX idx_turni_palloni_evento ON turni_palloni (evento)"],
listRule: "@request.auth.id != ''",
viewRule: "@request.auth.id != ''",
createRule: "@request.auth.id != ''",
updateRule: "@request.auth.id != ''",
deleteRule: "@request.auth.id != ''",
});
app.save(turniPalloni);
const scoutSessioni = new Collection({
name: "scout_sessioni",
type: "base",
fields: [
{
name: "evento",
type: "relation",
required: true,
collectionId: eventi.id,
maxSelect: 1,
cascadeDelete: true,
},
{
name: "giocatore",
type: "relation",
required: true,
collectionId: giocatori.id,
maxSelect: 1,
},
{ name: "giocatore_nome", type: "text", required: true },
{ name: "created", type: "autodate", onCreate: true },
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
],
indexes: ["CREATE UNIQUE INDEX idx_scout_sessioni_evento ON scout_sessioni (evento)"],
listRule: "@request.auth.id != ''",
viewRule: "@request.auth.id != ''",
createRule: "@request.auth.id != ''",
updateRule: "@request.auth.id != ''",
deleteRule: "@request.auth.id != ''",
});
app.save(scoutSessioni);
const scoutLive = new Collection({
name: "scout_live",
type: "base",
fields: [
{
name: "evento",
type: "relation",
required: true,
collectionId: eventi.id,
maxSelect: 1,
cascadeDelete: true,
},
{ name: "stato", type: "json", required: false },
{ name: "created", type: "autodate", onCreate: true },
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
],
indexes: ["CREATE UNIQUE INDEX idx_scout_live_evento ON scout_live (evento)"],
listRule: "@request.auth.id != ''",
viewRule: "@request.auth.id != ''",
createRule: "@request.auth.id != ''",
updateRule: "@request.auth.id != ''",
deleteRule: "@request.auth.id != ''",
});
app.save(scoutLive);
const scoutPartite = new Collection({
name: "scout_partite",
type: "base",
fields: [
// Id libero (come in Supabase, "id text PRIMARY KEY", generato dal client).
{ name: "id", type: "text", min: 1, max: 60 },
{
name: "evento",
type: "relation",
required: false,
collectionId: eventi.id,
maxSelect: 1,
cascadeDelete: true,
},
{ name: "data", type: "date", required: true },
{ name: "avversario", type: "text", required: true },
{ name: "casa", type: "bool", required: false },
{ name: "set_nostri", type: "number", required: true, min: 0 },
{ name: "set_loro", type: "number", required: true, min: 0 },
{ name: "parziali", type: "json", required: false },
{ name: "azioni", type: "json", required: false },
{ name: "created", type: "autodate", onCreate: true },
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
],
listRule: "@request.auth.id != ''",
viewRule: "@request.auth.id != ''",
createRule: "@request.auth.id != ''",
updateRule: "@request.auth.id != ''",
deleteRule: "@request.auth.id != ''",
});
app.save(scoutPartite);
// ---------------------------------------------------------------------------------------
// push_subscriptions — dispositivi registrati per le notifiche push
// ---------------------------------------------------------------------------------------
const pushSubscriptions = new Collection({
name: "push_subscriptions",
type: "base",
fields: [
{
name: "giocatore",
type: "relation",
required: false,
collectionId: giocatori.id,
maxSelect: 1,
},
{ name: "endpoint", type: "text", required: true },
{ name: "p256dh", type: "text", required: true },
{ name: "auth", type: "text", required: true },
{ name: "created", type: "autodate", onCreate: true },
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
],
indexes: [
"CREATE UNIQUE INDEX idx_push_subscriptions_endpoint ON push_subscriptions (endpoint)",
],
listRule: "@request.auth.id != ''",
viewRule: "@request.auth.id != ''",
createRule: "@request.auth.id != ''",
updateRule: "@request.auth.id != ''",
deleteRule: "@request.auth.id != ''",
});
app.save(pushSubscriptions);
},
(app) => {
const names = [
"push_subscriptions",
"scout_partite",
"scout_live",
"scout_sessioni",
"turni_palloni",
"badge_social_voti",
"pagelle_voti",
"mvp_voti",
"cacche_partita",
"risposte_presenze",
"eventi_app",
"avatar_giocatori",
"profili_giocatore",
"giocatori_squadra",
];
for (const name of names) {
const collection = app.findCollectionByNameOrId(name);
if (collection) app.delete(collection);
}
const users = app.findCollectionByNameOrId("users");
users.fields.removeByName("role");
app.save(users);
},
);
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
# Ricrea da zero il PocketBase locale (equivalente di "npx supabase db reset").
# Ferma il container, azzera pb_data (le migration in pocketbase/pb_migrations/ vengono
# riapplicate all'avvio) e riavvia. Il superuser (da POCKETBASE_SUPERUSER_EMAIL/PASSWORD
# in .env) e il provider Google OAuth2 (da GOOGLE_OAUTH_CLIENT_ID/SECRET) si ricreano da
# soli all'avvio, senza passaggi manuali.
set -euo pipefail
cd "$(dirname "$0")/.."
docker compose -f docker-compose.pocketbase.yml down
# Alcuni file (avatar, thumbnail) li scrive il container con un utente diverso da quello
# host: un semplice "rm -rf" da host può fallire per permessi, quindi si pulisce da dentro
# un container usa-e-getta.
docker run --rm -v "$(pwd)/pocketbase/pb_data:/pb_data" alpine sh -c 'rm -rf /pb_data/* /pb_data/.[!.]* 2>/dev/null || true'
mkdir -p pocketbase/pb_data
touch pocketbase/pb_data/.gitkeep
docker compose -f docker-compose.pocketbase.yml up -d
echo "PocketBase locale ricreato. Dashboard: http://127.0.0.1:8090/_/"
+7 -3
View File
@@ -1,6 +1,6 @@
import { useEffect, useState } from "react";
import { cn } from "@/lib/utils";
import { urlAvatar } from "@/lib/avatar-store";
import { urlAvatarDaRiga, useAvatarMap } from "@/lib/avatar-store";
export function Avatar({
id,
@@ -19,8 +19,12 @@ export function Avatar({
const [errore, setErrore] = useState(false);
useEffect(() => setErrore(false), [id, bust]);
if (!errore) {
const src = bust ? `${urlAvatar(id)}?v=${bust}` : urlAvatar(id);
const { data: mappa } = useAvatarMap();
const riga = mappa?.[id];
if (riga && !errore) {
const base = urlAvatarDaRiga(riga);
const src = bust ? `${base}?v=${bust}` : base;
return (
<img
src={src}
+14 -6
View File
@@ -34,15 +34,17 @@ function Intestazione({ titolo, completa }: { titolo: string; completa: boolean
function CampoFile({
label,
path,
recordId,
sezione,
giocatoreId,
onCaricato,
}: {
label: string;
path: string | null;
recordId: string | null;
sezione: SezioneFile;
giocatoreId: string;
onCaricato: (path: string) => Promise<void>;
onCaricato: (risultato: { id: string; filename: string }) => Promise<void>;
}) {
const input = useRef<HTMLInputElement>(null);
const [inCorso, setInCorso] = useState(false);
@@ -53,7 +55,7 @@ function CampoFile({
if (!file) return;
setInCorso(true);
try {
const nuovo = await caricaFile(giocatoreId, sezione, file, path);
const nuovo = await caricaFile(giocatoreId, sezione, file);
await onCaricato(nuovo);
toast.success(`${label} caricato`);
} catch (errore) {
@@ -77,10 +79,10 @@ function CampoFile({
<span className="truncate">{label}</span>
</span>
<span className="flex shrink-0 items-center gap-2">
{path ? (
{path && recordId ? (
<button
type="button"
onClick={() => void scaricaFile(path)}
onClick={() => void scaricaFile(recordId, path)}
className="premi rounded-xl bg-secondary p-2 text-muted-foreground"
aria-label={`Vedi ${label}`}
>
@@ -287,8 +289,10 @@ export function ProfiloAmministrativo({
}
// Un file caricato va persistito subito, insieme a quello che si stava scrivendo.
const caricato = (campo: keyof Profilo) => async (path: string) =>
scrivi({ ...corrente, [campo]: path });
const caricato =
(campo: "documentoFrontePath" | "documentoRetroPath" | "certificatoPath" | "fotoPath") =>
async (risultato: { id: string; filename: string }) =>
scrivi({ ...corrente, id: risultato.id, [campo]: risultato.filename });
const corpo = (
<div className="space-y-3 rounded-3xl bg-card p-4 shadow-card">
@@ -313,6 +317,7 @@ export function ProfiloAmministrativo({
<CampoFile
label="Foto fronte"
path={corrente.documentoFrontePath}
recordId={corrente.id}
sezione="documento-fronte"
giocatoreId={giocatoreId}
onCaricato={caricato("documentoFrontePath")}
@@ -320,6 +325,7 @@ export function ProfiloAmministrativo({
<CampoFile
label="Foto retro"
path={corrente.documentoRetroPath}
recordId={corrente.id}
sezione="documento-retro"
giocatoreId={giocatoreId}
onCaricato={caricato("documentoRetroPath")}
@@ -330,6 +336,7 @@ export function ProfiloAmministrativo({
<CampoFile
label="Certificato medico"
path={corrente.certificatoPath}
recordId={corrente.id}
sezione="certificato"
giocatoreId={giocatoreId}
onCaricato={caricato("certificatoPath")}
@@ -341,6 +348,7 @@ export function ProfiloAmministrativo({
<CampoFile
label="Foto tessera"
path={corrente.fotoPath}
recordId={corrente.id}
sezione="foto"
giocatoreId={giocatoreId}
onCaricato={caricato("fotoPath")}
@@ -0,0 +1,13 @@
import { createMiddleware } from "@tanstack/react-start";
import { pb } from "./client";
// Deve essere registrato come `functionMiddleware` globale in `src/start.ts`; altrimenti
// il browser non allega il bearer token alle RPC delle server function.
export const attachPocketBaseAuth = createMiddleware({ type: "function" }).client(
async ({ next }) => {
const token = pb.authStore.token;
return next({
headers: token ? { Authorization: `Bearer ${token}` } : {},
});
},
);
@@ -0,0 +1,39 @@
// Client server-side con privilegi superuser - bypassa le API rules delle collection
// (equivalente del service role Supabase, con una differenza: PocketBase non ha una
// chiave statica, l'autenticazione è email+password contro la collection _superusers e
// va rinnovata quando il token scade).
//
// SECURITY: usare solo per operazioni server-side fidate, mai esporre al client.
// Carica dentro gli handler server: const { pbAdmin } = await import("@/integrations/pocketbase/client.server");
// L'import a livello di modulo è sicuro solo in altri moduli *.server.ts - le route e le
// server function finiscono nel bundle client.
import PocketBase from "pocketbase";
let _pb: PocketBase | undefined;
export async function pbAdmin(): Promise<PocketBase> {
const POCKETBASE_URL = process.env["POCKETBASE_URL"];
const POCKETBASE_SUPERUSER_EMAIL = process.env["POCKETBASE_SUPERUSER_EMAIL"];
const POCKETBASE_SUPERUSER_PASSWORD = process.env["POCKETBASE_SUPERUSER_PASSWORD"];
if (!POCKETBASE_URL || !POCKETBASE_SUPERUSER_EMAIL || !POCKETBASE_SUPERUSER_PASSWORD) {
const missing = [
...(!POCKETBASE_URL ? ["POCKETBASE_URL"] : []),
...(!POCKETBASE_SUPERUSER_EMAIL ? ["POCKETBASE_SUPERUSER_EMAIL"] : []),
...(!POCKETBASE_SUPERUSER_PASSWORD ? ["POCKETBASE_SUPERUSER_PASSWORD"] : []),
];
const message = `Variabili d'ambiente PocketBase mancanti: ${missing.join(", ")}.`;
console.error(`[PocketBase] ${message}`);
throw new Error(message);
}
if (!_pb) _pb = new PocketBase(POCKETBASE_URL);
if (!_pb.authStore.isValid) {
await _pb
.collection("_superusers")
.authWithPassword(POCKETBASE_SUPERUSER_EMAIL, POCKETBASE_SUPERUSER_PASSWORD);
}
return _pb;
}
+28
View File
@@ -0,0 +1,28 @@
import PocketBase from "pocketbase";
function createPocketBaseClient(): PocketBase {
// Use import.meta.env for client-side (Vite build-time replacement)
// Fall back to process.env for SSR (server-side rendering)
const POCKETBASE_URL = import.meta.env["VITE_POCKETBASE_URL"] || process.env["POCKETBASE_URL"];
if (!POCKETBASE_URL) {
const message = "Manca la variabile d'ambiente POCKETBASE_URL (o VITE_POCKETBASE_URL).";
console.error(`[PocketBase] ${message}`);
throw new Error(message);
}
// PocketBase persiste la sessione in localStorage lato browser e in memoria lato SSR
// di default: nessuna configurazione aggiuntiva serve (a differenza del client Supabase).
return new PocketBase(POCKETBASE_URL);
}
let _pb: PocketBase | undefined;
// Import the PocketBase client like this:
// import { pb } from "@/integrations/pocketbase/client";
export const pb = new Proxy({} as PocketBase, {
get(_, prop, receiver) {
if (!_pb) _pb = createPocketBaseClient();
return Reflect.get(_pb, prop, receiver);
},
});
+8
View File
@@ -0,0 +1,8 @@
/**
* PocketBase restituisce i campi data/ora come "AAAA-MM-GG HH:MM:SS.sssZ" (spazio, non
* "T"): `Date.parse` su questo formato non è garantito coerente su tutti i motori JS.
* Normalizza a ISO 8601 stretto prima di qualsiasi confronto/calcolo di date.
*/
export function pbISO(v: string): string {
return v.includes("T") ? v : v.replace(" ", "T");
}
+52
View File
@@ -0,0 +1,52 @@
import PocketBase, { ClientResponseError, type RecordModel } from "pocketbase";
import { pb } from "./client";
/**
* PocketBase non ha un upsert nativo. Per le collection con id significativo (es. `e1`,
* `g1`, dove l'id stesso è la chiave di unicità che prima era gestita da
* `onConflict: "id"`): aggiorna se il record esiste, altrimenti lo crea con quell'id.
*
* `client` di default è il client browser (`pb`): passare esplicitamente `pbAdmin()` nei
* moduli server-side che oggi usano `supabaseAdmin`.
*/
export async function upsertById<T = RecordModel>(
collection: string,
id: string,
dati: Record<string, unknown>,
client: PocketBase = pb,
): Promise<T> {
try {
return await client.collection(collection).update<T>(id, dati);
} catch (errore) {
if (errore instanceof ClientResponseError && errore.status === 404) {
return await client.collection(collection).create<T>({ id, ...dati });
}
throw errore;
}
}
/**
* Per le collection dove l'unicità è su una combinazione di campi (es.
* `evento_id,giocatore_id`, prima gestita da un indice UNIQUE + `onConflict`) e l'id del
* record è generato da PocketBase, non ha significato applicativo: cerca il record che
* combacia col filtro e lo aggiorna, altrimenti ne crea uno nuovo.
*/
export async function upsertByFilter<T = RecordModel>(
collection: string,
filtro: string,
parametri: Record<string, unknown>,
dati: Record<string, unknown>,
client: PocketBase = pb,
): Promise<T> {
try {
const esistente = await client
.collection(collection)
.getFirstListItem<T>(client.filter(filtro, parametri));
return await client.collection(collection).update<T>((esistente as RecordModel).id, dati);
} catch (errore) {
if (errore instanceof ClientResponseError && errore.status === 404) {
return await client.collection(collection).create<T>(dati);
}
throw errore;
}
}
+26 -19
View File
@@ -2,18 +2,19 @@
* Controllo di accesso per le route in `src/routes/api/public/` che inviano notifiche
* a tutta la squadra (DD-024).
*
* Quelle route usano la service role e saltano la RLS: senza un controllo qui, chiunque
* conosca l'URL può far suonare i telefoni di tutti. L'id di un evento non è un segreto —
* è un timestamp in base 36 e compare negli URL che la squadra si scambia — quindi non
* può fare da credenziale.
* Quelle route usano il superuser PocketBase e saltano le API rules: senza un controllo
* qui, chiunque conosca l'URL può far suonare i telefoni di tutti. L'id di un evento non
* è un segreto — è un timestamp in base 36 e compare negli URL che la squadra si scambia —
* quindi non può fare da credenziale.
*
* Tutte e tre le route che mandano notifiche partono da un pulsante riservato agli
* amministratori, quindi il controllo è uno solo: `richiediAdmin` verifica il token della
* sessione Supabase e poi il ruolo in `user_roles`. Torna `null` quando la richiesta può
* proseguire, altrimenti la `Response` di rifiuto già pronta.
* sessione PocketBase e il campo `role` sul record utente. Torna `null` quando la
* richiesta può proseguire, altrimenti la `Response` di rifiuto già pronta.
*/
import PocketBase from "pocketbase";
/** Il token della sessione Supabase, se la richiesta ne porta uno ben formato. */
/** Il token della sessione PocketBase, se la richiesta ne porta uno ben formato. */
function tokenDaRichiesta(request: Request): string | null {
const intestazione = request.headers.get("authorization");
if (!intestazione?.startsWith("Bearer ")) return null;
@@ -31,19 +32,25 @@ export async function richiediAdmin(request: Request): Promise<Response | null>
const token = tokenDaRichiesta(request);
if (!token) return new Response("Autenticazione richiesta", { status: 401 });
const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
const POCKETBASE_URL = process.env["POCKETBASE_URL"];
if (!POCKETBASE_URL) {
console.error("[PocketBase] Manca la variabile d'ambiente POCKETBASE_URL.");
return new Response("Configurazione server non valida", { status: 500 });
}
const { data: utente, error } = await supabaseAdmin.auth.getUser(token);
if (error || !utente?.user) return new Response("Sessione non valida", { status: 401 });
// Client "vuoto" con il token dell'utente allegato: authRefresh() lo valida e restituisce
// il record aggiornato in un'unica chiamata, ruolo incluso (con Supabase servivano due
// round trip: getUser() più una query separata su user_roles).
const pb = new PocketBase(POCKETBASE_URL);
pb.authStore.save(token, null);
// Stessa fonte di `src/lib/ruoli.ts`: i permessi stanno solo in `user_roles` (DD-011).
const { data: ruolo } = await supabaseAdmin
.from("user_roles")
.select("role")
.eq("user_id", utente.user.id)
.eq("role", "admin")
.maybeSingle();
if (!ruolo) return new Response("Riservato agli amministratori", { status: 403 });
try {
const { record } = await pb.collection("users").authRefresh();
if (record["role"] !== "admin") {
return new Response("Riservato agli amministratori", { status: 403 });
}
return null;
} catch {
return new Response("Sessione non valida", { status: 401 });
}
}
+23 -34
View File
@@ -1,49 +1,39 @@
import { useEffect, useState } from "react";
import type { Session } from "@supabase/supabase-js";
import { supabase } from "@/integrations/supabase/client";
import type { AuthRecord } from "pocketbase";
import { pb } from "@/integrations/pocketbase/client";
/**
* Autenticazione reale con Google (DD-011). Il login ha sostituito la selezione del
* giocatore: senza sessione non si entra, e i permessi di amministrazione arrivano solo
* da `user_roles` (vedi `ruoli.ts`).
* dal campo `role` sul record utente (vedi `ruoli.ts`).
*/
export function useSessione() {
const [sessione, setSessione] = useState<Session | null>(null);
const [utente, setUtente] = useState<AuthRecord>(null);
const [pronta, setPronta] = useState(false);
useEffect(() => {
let attivo = true;
// Il client Supabase esplode alla costruzione se mancano le variabili d'ambiente:
// qui va assorbito, altrimenti la schermata di accesso non si disegna proprio e
// resta irraggiungibile anche la selezione del giocatore.
// Il client PocketBase esplode alla costruzione se manca la variabile d'ambiente: qui
// va assorbito, altrimenti la schermata di accesso non si disegna proprio e resta
// irraggiungibile anche la selezione del giocatore.
try {
supabase.auth
.getSession()
.then(({ data }) => {
if (!attivo) return;
setSessione(data.session);
setUtente(pb.authStore.record);
setPronta(true);
})
.catch(() => attivo && setPronta(true));
const { data } = supabase.auth.onAuthStateChange((_evento, nuova) => setSessione(nuova));
return () => {
attivo = false;
data.subscription.unsubscribe();
};
// A differenza di Supabase, l'authStore di PocketBase è già popolato in modo
// sincrono all'avvio (legge localStorage nel costruttore): non serve una chiamata
// asincrona equivalente a getSession().
return pb.authStore.onChange((_token, record) => setUtente(record));
} catch (errore) {
console.error("[auth] Supabase non disponibile", errore);
console.error("[auth] PocketBase non disponibile", errore);
setPronta(true);
return () => {
attivo = false;
};
return undefined;
}
}, []);
return {
sessione,
sessione: utente,
pronta,
utenteId: sessione?.user.id ?? null,
emailUtente: sessione?.user.email ?? null,
utenteId: utente?.id ?? null,
emailUtente: (utente?.["email"] as string | undefined) ?? null,
};
}
@@ -53,20 +43,19 @@ export function useSessione() {
* un token già scaduto.
*/
export async function intestazioniAutenticate(): Promise<Record<string, string>> {
const { data } = await supabase.auth.getSession();
const token = data.session?.access_token;
const token = pb.authStore.token;
return token ? { Authorization: `Bearer ${token}` } : {};
}
export async function accediConGoogle(): Promise<void> {
const { error } = await supabase.auth.signInWithOAuth({
// createData copre il primo accesso: PocketBase crea il record utente al volo se non
// esiste ancora per questa identità Google, e il campo `role` è obbligatorio.
await pb.collection("users").authWithOAuth2({
provider: "google",
options: { redirectTo: window.location.origin },
createData: { role: "user" },
});
if (error) throw error;
}
export async function esci(): Promise<void> {
const { error } = await supabase.auth.signOut();
if (error) throw error;
pb.authStore.clear();
}
+48 -31
View File
@@ -1,41 +1,54 @@
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { pb } from "@/integrations/pocketbase/client";
import { upsertByFilter } from "@/integrations/pocketbase/upsert";
const BUCKET = "avatar-giocatori";
const NOME_FILE = "avatar.jpg";
/**
* Foto profilo pubbliche (M6 avatar-giocatori): collection separata da giocatori_squadra,
* chiunque autenticato può caricare/sostituire/eliminare l'avatar di chiunque (nessun
* controllo per-proprietario, come il vecchio bucket pubblico Supabase).
*/
type RigaAvatar = { id: string; giocatore: string; foto: string };
function percorso(id: string) {
return `${id}/${NOME_FILE}`;
export const AVATAR_KEY = ["avatar-giocatori"] as const;
async function fetchAvatarMap(): Promise<Record<string, RigaAvatar>> {
const righe = await pb.collection("avatar_giocatori").getFullList<RigaAvatar>();
const mappa: Record<string, RigaAvatar> = {};
for (const r of righe) if (r.foto) mappa[r.giocatore] = r;
return mappa;
}
/** URL pubblico e stabile: il bucket è pubblico, nessuna richiesta di rete. */
export function urlAvatar(id: string): string {
return supabase.storage.from(BUCKET).getPublicUrl(percorso(id)).data.publicUrl;
/** Una lettura per sessione, condivisa da tutte le istanze di <Avatar>: react-query la
* deduplica anche se il componente compare decine di volte nella stessa pagina (rosa). */
export function useAvatarMap() {
return useQuery({ queryKey: AVATAR_KEY, queryFn: fetchAvatarMap, staleTime: 30 * 60_000 });
}
const chiaveEsiste = (id: string) => ["avatar-esiste", id] as const;
/** URL pubblico e stabile: il campo non è protetto, nessuna richiesta di rete aggiuntiva. */
export function urlAvatarDaRiga(riga: RigaAvatar): string {
return pb.files.getURL({ id: riga.id, collectionName: "avatar_giocatori" }, riga.foto);
}
/** Solo per il proprio profilo: sapere se mostrare "rimuovi immagine". */
export function useAvatarEsiste(id: string | undefined) {
return useQuery({
queryKey: chiaveEsiste(id ?? ""),
enabled: !!id,
staleTime: 60_000,
queryFn: async () => {
const { data, error } = await supabase.storage.from(BUCKET).list(id!, { search: NOME_FILE });
if (error) throw error;
return (data ?? []).some((f) => f.name === NOME_FILE);
},
});
const query = useAvatarMap();
return { ...query, data: id ? !!query.data?.[id] : false };
}
/**
* Dopo un caricamento o una rimozione lo stato è noto: si scrive in cache invece di
* rileggere l'elenco del bucket (una richiesta in meno per ogni cambio foto).
* rileggere l'elenco (una richiesta in meno per ogni cambio foto).
*/
export function useImpostaAvatarEsiste() {
const qc = useQueryClient();
return (id: string, esiste: boolean) => qc.setQueryData(chiaveEsiste(id), esiste);
return (id: string, riga: RigaAvatar | null) => {
qc.setQueryData<Record<string, RigaAvatar>>(AVATAR_KEY, (prec) => {
const nuova = { ...(prec ?? {}) };
if (riga) nuova[id] = riga;
else delete nuova[id];
return nuova;
});
};
}
/** Ridimensiona e comprime l'immagine scelta in un quadrato JPEG. */
@@ -77,17 +90,21 @@ function fileToBlob(file: File, size = 256): Promise<Blob> {
}
/** Ridimensiona, comprime e carica la foto profilo: sovrascrive quella precedente. */
export async function caricaAvatar(id: string, file: File) {
export async function caricaAvatar(id: string, file: File): Promise<RigaAvatar> {
const blob = await fileToBlob(file);
const { error } = await supabase.storage.from(BUCKET).upload(percorso(id), blob, {
contentType: "image/jpeg",
upsert: true,
cacheControl: "0",
});
if (error) throw error;
const foto = new File([blob], "avatar.jpg", { type: "image/jpeg" });
return upsertByFilter<RigaAvatar>(
"avatar_giocatori",
"giocatore = {:giocatore}",
{ giocatore: id },
{ giocatore: id, foto },
);
}
export async function rimuoviAvatar(id: string) {
const { error } = await supabase.storage.from(BUCKET).remove([percorso(id)]);
if (error) throw error;
export async function rimuoviAvatar(id: string): Promise<void> {
const esistente = await pb
.collection("avatar_giocatori")
.getFirstListItem(pb.filter("giocatore = {:giocatore}", { giocatore: id }))
.catch(() => null);
if (esistente) await pb.collection("avatar_giocatori").delete(esistente.id);
}
+31 -10
View File
@@ -1,7 +1,8 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { HandHeart, Handshake, Laugh, Scale, Users } from "lucide-react";
import type { LucideIcon } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { pb } from "@/integrations/pocketbase/client";
import { upsertByFilter } from "@/integrations/pocketbase/upsert";
export type CategoriaSocial = {
id: string;
@@ -58,6 +59,14 @@ export type VotoSocial = {
votato_nome: string;
};
type RigaSocialPocketBase = {
evento: string;
categoria: string;
votante: string;
votato: string;
votato_nome: string;
};
const CHIAVE = ["badge-social-voti"] as const;
/** Tutti i voti social (poche righe): nessun polling, cache lunga. */
@@ -66,11 +75,14 @@ export function useVotiSocial() {
queryKey: CHIAVE,
staleTime: 10 * 60_000,
queryFn: async (): Promise<VotoSocial[]> => {
const { data, error } = await supabase
.from("badge_social_voti")
.select("match_id, categoria, votante_id, votato_id, votato_nome");
if (error) throw error;
return (data ?? []) as VotoSocial[];
const righe = await pb.collection("badge_social_voti").getFullList<RigaSocialPocketBase>();
return righe.map((r) => ({
match_id: r.evento,
categoria: r.categoria,
votante_id: r.votante,
votato_id: r.votato,
votato_nome: r.votato_nome,
}));
},
});
}
@@ -79,10 +91,19 @@ export function useVotaSocial() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (voto: VotoSocial) => {
const { error } = await supabase
.from("badge_social_voti")
.upsert(voto, { onConflict: "match_id,categoria,votante_id" });
if (error) throw error;
// No autovoto e convocazione li valida l'hook voti_convocati.pb.js.
await upsertByFilter(
"badge_social_voti",
"evento = {:evento} && categoria = {:categoria} && votante = {:votante}",
{ evento: voto.match_id, categoria: voto.categoria, votante: voto.votante_id },
{
evento: voto.match_id,
categoria: voto.categoria,
votante: voto.votante_id,
votato: voto.votato_id,
votato_nome: voto.votato_nome,
},
);
return voto;
},
// Aggiornamento locale della cache: zero riletture.
+20 -10
View File
@@ -1,5 +1,6 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { pb } from "@/integrations/pocketbase/client";
import { upsertByFilter } from "@/integrations/pocketbase/upsert";
import { oggiISO } from "./palloni-core";
/** Ora di apertura del sondaggio, il giorno stesso della partita. */
@@ -48,6 +49,12 @@ export type RigaCacche = {
quantita: number;
};
type RigaCacchePocketBase = {
evento: string;
giocatore: string;
quantita: number;
};
export const CACCHE_KEY = ["cacche"] as const;
export function useCacche() {
@@ -55,11 +62,12 @@ export function useCacche() {
queryKey: CACCHE_KEY,
staleTime: 10 * 60_000,
queryFn: async (): Promise<RigaCacche[]> => {
const { data, error } = await supabase
.from("cacche_partita")
.select("evento_id, giocatore_id, quantita");
if (error) throw error;
return (data ?? []) as RigaCacche[];
const righe = await pb.collection("cacche_partita").getFullList<RigaCacchePocketBase>();
return righe.map((r) => ({
evento_id: r.evento,
giocatore_id: r.giocatore,
quantita: r.quantita,
}));
},
});
return { ...query, righe: query.data ?? [] };
@@ -69,10 +77,12 @@ export function useSalvaCacche() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (riga: RigaCacche) => {
const { error } = await supabase
.from("cacche_partita")
.upsert(riga, { onConflict: "evento_id,giocatore_id" });
if (error) throw error;
await upsertByFilter(
"cacche_partita",
"evento = {:evento} && giocatore = {:giocatore}",
{ evento: riga.evento_id, giocatore: riga.giocatore_id },
{ evento: riga.evento_id, giocatore: riga.giocatore_id, quantita: riga.quantita },
);
return riga;
},
onSuccess: (riga) => {
+4 -6
View File
@@ -1,11 +1,9 @@
import { daRiga, type Evento, type RigaEvento } from "./eventi";
const COLONNE =
"id, tipo, titolo, luogo, data, ora, note, convocati, campionato, casa, pagelle_chiuse";
/** Lettura eventi lato server (route API): stessa conversione del client. */
export async function leggiEventi(): Promise<Evento[]> {
const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
const { data } = await supabaseAdmin.from("eventi_app").select(COLONNE).order("data");
return ((data ?? []) as RigaEvento[]).map(daRiga);
const { pbAdmin } = await import("@/integrations/pocketbase/client.server");
const admin = await pbAdmin();
const righe = await admin.collection("eventi_app").getFullList<RigaEvento>({ sort: "data" });
return righe.map(daRiga);
}
+25 -27
View File
@@ -1,5 +1,7 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { pb } from "@/integrations/pocketbase/client";
import { pbISO } from "@/integrations/pocketbase/formato";
import { upsertById } from "@/integrations/pocketbase/upsert";
import type { Giocatore } from "./crapp-data";
export type EventoTipo = "partita" | "allenamento" | "evento" | "compleanno";
@@ -25,6 +27,7 @@ export type Evento = {
creatoIl?: string | undefined;
};
/** Riga così come la restituisce PocketBase. */
export type RigaEvento = {
id: string;
tipo: string;
@@ -32,35 +35,37 @@ export type RigaEvento = {
luogo: string;
data: string;
ora: string;
note: string | null;
convocati: string[] | null;
note: string;
convocati: string[];
campionato: boolean;
casa: boolean | null;
casa: boolean;
pagelle_chiuse: boolean;
creato_il?: string;
created?: string;
};
/** I campi "date" di PocketBase tornano come datetime completo: qui serve solo "YYYY-MM-DD". */
function soloData(v: string): string {
return v.slice(0, 10);
}
/** Conversione riga database -> modello applicativo (riusabile anche lato server). */
export function daRiga(r: RigaEvento): Evento {
return {
id: r.id,
tipo: (r.tipo as EventoTipo) ?? "evento",
tipo: (r.tipo as EventoTipo) || "evento",
titolo: r.titolo,
luogo: r.luogo ?? "",
data: r.data,
ora: r.ora ?? "",
note: r.note ?? "",
luogo: r.luogo || "",
data: soloData(r.data),
ora: r.ora || "",
note: r.note || "",
convocati: r.convocati ?? [],
campionato: !!r.campionato,
casa: r.casa ?? true,
casa: r.casa,
pagelleChiuse: !!r.pagelle_chiuse,
creatoIl: r.creato_il,
creatoIl: r.created ? pbISO(r.created) : undefined,
};
}
const COLONNE =
"id, tipo, titolo, luogo, data, ora, note, convocati, campionato, casa, pagelle_chiuse, creato_il";
/** Categoria mostrata in interfaccia: le amichevoli sono partite fuori campionato. */
export type CategoriaEvento = "allenamento" | "partita" | "amichevole" | "evento";
@@ -79,9 +84,8 @@ export function daCategoria(c: CategoriaEvento): Pick<Evento, "tipo" | "campiona
export const EVENTI_KEY = ["eventi"] as const;
async function fetchEventi(): Promise<Evento[]> {
const { data, error } = await supabase.from("eventi_app").select(COLONNE).order("data");
if (error) throw error;
return ((data ?? []) as RigaEvento[]).map(daRiga);
const righe = await pb.collection("eventi_app").getFullList<RigaEvento>({ sort: "data" });
return righe.map(daRiga);
}
/** Una lettura per sessione: il calendario cambia raramente. */
@@ -119,9 +123,7 @@ export function useSalvaEvento() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (evento: Evento) => {
const { error } = await supabase.from("eventi_app").upsert(
{
id: evento.id,
await upsertById("eventi_app", evento.id, {
tipo: evento.tipo,
titolo: evento.titolo,
luogo: evento.luogo,
@@ -132,10 +134,7 @@ export function useSalvaEvento() {
campionato: evento.campionato,
casa: evento.casa,
pagelle_chiuse: evento.pagelleChiuse,
},
{ onConflict: "id" },
);
if (error) throw error;
});
return evento;
},
// Aggiornamento locale della cache: nessuna rilettura dal database.
@@ -152,8 +151,7 @@ export function useEliminaEvento() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (id: string) => {
const { error } = await supabase.from("eventi_app").delete().eq("id", id);
if (error) throw error;
await pb.collection("eventi_app").delete(id);
return id;
},
onSuccess: (id) => {
+8 -12
View File
@@ -1,20 +1,16 @@
import type { SupabaseClient } from "@supabase/supabase-js";
import {
COLONNE_SQUADRA,
daRigaSquadra,
type GiocatoreSquadra,
type RigaGiocatoreSquadra,
} from "./giocatori-squadra";
/** Lettura squadra lato server (route API): stessa conversione del client. */
/** Lettura squadra lato server (route API): usa il superuser per non dipendere dalla
* sessione del chiamante, stessa conversione del client. */
export async function leggiGiocatoriSquadra(): Promise<GiocatoreSquadra[]> {
const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
// `types.ts` non include ancora `giocatori_squadra` con le colonne di M8 (vedi client-nuove-tabelle.ts).
const client = supabaseAdmin as unknown as SupabaseClient;
const { data } = await client
.from("giocatori_squadra")
.select(COLONNE_SQUADRA)
.order("cognome")
.order("nome");
return ((data ?? []) as RigaGiocatoreSquadra[]).map(daRigaSquadra);
const { pbAdmin } = await import("@/integrations/pocketbase/client.server");
const admin = await pbAdmin();
const righe = await admin.collection("giocatori_squadra").getFullList<RigaGiocatoreSquadra>({
sort: "cognome,nome",
});
return righe.map(daRigaSquadra);
}
+59 -65
View File
@@ -1,5 +1,5 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { supabaseNuoveTabelle } from "@/integrations/supabase/client-nuove-tabelle";
import { pb } from "@/integrations/pocketbase/client";
import { dividiNome, giocatori } from "./crapp-data";
/**
@@ -20,17 +20,18 @@ export type GiocatoreSquadra = {
dataTessera: string | null;
};
/** Riga così come la restituisce PocketBase: le relazioni/campi vuoti sono "", mai null. */
export type RigaGiocatoreSquadra = {
id: string;
nome: string;
cognome: string;
numero: number;
ruolo: string;
auth_user_id: string | null;
auth_user_id: string;
attivo: boolean;
email: string | null;
numero_tessera: string | null;
data_tessera: string | null;
email: string;
numero_tessera: string;
data_tessera: string;
};
/** Ruoli ammessi in campo (pallavolo): usati per il menu a tendina del profilo squadra. */
@@ -76,10 +77,18 @@ export function slotPerEmail(
return righe.find((g) => !g.authUserId && g.email?.trim().toLowerCase() === cercata) ?? null;
}
export const COLONNE_SQUADRA =
"id, nome, cognome, numero, ruolo, auth_user_id, attivo, email, numero_tessera, data_tessera";
/** "" -> null: PocketBase non ha un concetto di colonna NULL, i campi vuoti sono stringa vuota. */
function vuotoANull(v: string): string | null {
return v ? v : null;
}
/** Conversione riga database -> modello applicativo (riusabile anche lato server). */
/** I campi "date" di PocketBase tornano come datetime completo ("2026-01-01 00:00:00.000Z"):
* qui serve solo "YYYY-MM-DD" (input HTML type="date", confronti testuali con altre date). */
function soloData(v: string): string | null {
return v ? v.slice(0, 10) : null;
}
/** Conversione riga PocketBase -> modello applicativo (riusabile anche lato server). */
export function daRigaSquadra(r: RigaGiocatoreSquadra): GiocatoreSquadra {
return {
id: r.id,
@@ -87,22 +96,18 @@ export function daRigaSquadra(r: RigaGiocatoreSquadra): GiocatoreSquadra {
cognome: r.cognome,
numero: r.numero,
ruolo: r.ruolo,
authUserId: r.auth_user_id,
authUserId: vuotoANull(r.auth_user_id),
attivo: r.attivo,
email: r.email,
numeroTessera: r.numero_tessera,
dataTessera: r.data_tessera,
email: vuotoANull(r.email),
numeroTessera: vuotoANull(r.numero_tessera),
dataTessera: soloData(r.data_tessera),
};
}
async function fetchSquadra(): Promise<GiocatoreSquadra[]> {
const { data, error } = await supabaseNuoveTabelle
.from("giocatori_squadra")
.select(COLONNE_SQUADRA)
.order("cognome")
.order("nome");
if (error) throw error;
const righe = (data ?? []) as RigaGiocatoreSquadra[];
const righe = await pb.collection("giocatori_squadra").getFullList<RigaGiocatoreSquadra>({
sort: "cognome,nome",
});
return righe.map(daRigaSquadra);
}
@@ -118,8 +123,8 @@ export function useGiocatoriSquadra() {
export type DatiSquadra = Pick<GiocatoreSquadra, "nome" | "cognome" | "numero" | "ruolo" | "email">;
/**
* Controlli che rispecchiano i vincoli della tabella (`numero > 0`, campi obbligatori):
* meglio dirlo qui che far tornare un errore Postgres all'utente.
* Controlli che rispecchiano i vincoli della collection (`numero > 0`, campi obbligatori):
* meglio dirlo qui che far tornare un errore di PocketBase all'utente.
* Restituisce il messaggio da mostrare, oppure `null` se va bene.
*/
export function validaDatiSquadra(dati: DatiSquadra): string | null {
@@ -132,7 +137,7 @@ export function validaDatiSquadra(dati: DatiSquadra): string | null {
return null;
}
/** Il prossimo id libero nel formato `g<N>` richiesto dal vincolo della tabella. */
/** Il prossimo id libero nel formato `g<N>` richiesto dal vincolo della collection. */
export function prossimoIdGiocatore(righe: GiocatoreSquadra[]): string {
const max = righe.reduce((acc, g) => {
const n = Number(g.id.slice(1));
@@ -150,7 +155,7 @@ export function numeroGiaUsato(
return righe.some((g) => g.id !== giocatoreId && g.attivo && g.numero === numero);
}
/** Modifica dei dati squadra. Solo un admin passa le policy di M1. */
/** Modifica dei dati squadra. Solo un admin passa le API rules di M1. */
export function useSalvaDatiSquadra() {
const queryClient = useQueryClient();
return useMutation({
@@ -160,14 +165,10 @@ export function useSalvaDatiSquadra() {
cognome: input.dati.cognome.trim(),
numero: input.dati.numero,
ruolo: input.dati.ruolo.trim(),
email: input.dati.email?.trim() || null,
email: input.dati.email?.trim() || "",
};
const { error } = await supabaseNuoveTabelle
.from("giocatori_squadra")
.update(dati)
.eq("id", input.giocatoreId);
if (error) throw error;
return { giocatoreId: input.giocatoreId, dati };
await pb.collection("giocatori_squadra").update(input.giocatoreId, dati);
return { giocatoreId: input.giocatoreId, dati: { ...dati, email: dati.email || null } };
},
onSuccess: (input) => {
queryClient.setQueryData<GiocatoreSquadra[]>(SQUADRA_KEY, (prec) =>
@@ -182,7 +183,7 @@ export type DatiTesseramento = Pick<GiocatoreSquadra, "numeroTessera" | "dataTes
/**
* Registra numero e data della tessera CSI (roadmap v1.1). Campo puramente amministrativo:
* il trigger di M8 lo rende scrivibile solo da un admin, il giocatore non può autodichiararsi
* l'hook di M8 lo rende scrivibile solo da un admin, il giocatore non può autodichiararsi
* tesserato.
*/
export function useSalvaTesseramento() {
@@ -190,17 +191,16 @@ export function useSalvaTesseramento() {
return useMutation({
mutationFn: async (input: { giocatoreId: string; dati: DatiTesseramento }) => {
const dati = {
numero_tessera: input.dati.numeroTessera?.trim() || null,
data_tessera: input.dati.dataTessera || null,
numero_tessera: input.dati.numeroTessera?.trim() || "",
data_tessera: input.dati.dataTessera || "",
};
const { error } = await supabaseNuoveTabelle
.from("giocatori_squadra")
.update(dati)
.eq("id", input.giocatoreId);
if (error) throw error;
await pb.collection("giocatori_squadra").update(input.giocatoreId, dati);
return {
giocatoreId: input.giocatoreId,
dati: { numeroTessera: dati.numero_tessera, dataTessera: dati.data_tessera },
dati: {
numeroTessera: vuotoANull(dati.numero_tessera),
dataTessera: vuotoANull(dati.data_tessera),
},
};
},
onSuccess: (input) => {
@@ -212,7 +212,7 @@ export function useSalvaTesseramento() {
}
/**
* Aggiunge un giocatore alla rosa (DD-017). Solo un admin passa le policy di M1.
* Aggiunge un giocatore alla rosa (DD-017). Solo un admin passa le API rules di M1.
* L'id (`g<N>`) non è generato dal database: va calcolato con `prossimoIdGiocatore`
* prima di chiamare questa mutazione.
*/
@@ -226,15 +226,20 @@ export function useAggiungiGiocatore() {
cognome: input.dati.cognome.trim(),
numero: input.dati.numero,
ruolo: input.dati.ruolo.trim(),
email: input.dati.email?.trim() || null,
email: input.dati.email?.trim() || "",
attivo: true,
};
await pb.collection("giocatori_squadra").create(riga);
return {
...riga,
email: riga.email || null,
authUserId: null,
numeroTessera: null,
dataTessera: null,
};
const { error } = await supabaseNuoveTabelle.from("giocatori_squadra").insert(riga);
if (error) throw error;
// Le colonne non inviate hanno i default della tabella (M1): `attivo` true, il resto NULL.
return { ...riga, authUserId: null, attivo: true, numeroTessera: null, dataTessera: null };
},
// Aggiornamento locale della cache: nessuna rilettura, stesso ordine della query
// (`.order("cognome").order("nome")`).
// (sort "cognome,nome").
onSuccess: (nuovo) => {
queryClient.setQueryData<GiocatoreSquadra[]>(SQUADRA_KEY, (prec) =>
[...(prec ?? []), nuovo].sort(
@@ -253,11 +258,7 @@ export function useImpostaAttivo() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (input: { giocatoreId: string; attivo: boolean }) => {
const { error } = await supabaseNuoveTabelle
.from("giocatori_squadra")
.update({ attivo: input.attivo })
.eq("id", input.giocatoreId);
if (error) throw error;
await pb.collection("giocatori_squadra").update(input.giocatoreId, { attivo: input.attivo });
return input;
},
onSuccess: (input) => {
@@ -276,11 +277,7 @@ export function useScollegaAccount() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (giocatoreId: string) => {
const { error } = await supabaseNuoveTabelle
.from("giocatori_squadra")
.update({ auth_user_id: null })
.eq("id", giocatoreId);
if (error) throw error;
await pb.collection("giocatori_squadra").update(giocatoreId, { auth_user_id: "" });
return giocatoreId;
},
onSuccess: (giocatoreId) => {
@@ -292,20 +289,17 @@ export function useScollegaAccount() {
}
/**
* Collega l'account al giocatore scelto. Il trigger di M1 accetta l'operazione solo se
* lo slot è libero e se nessun altro campo cambia (DD-016 regola 2): il vincolo vive nel
* database, non qui.
* Collega l'account al giocatore scelto. L'hook giocatori_squadra_claim.pb.js accetta
* l'operazione solo se lo slot è libero, l'email combacia e nessun altro campo cambia
* (DD-016 regola 2): il vincolo vive nel database, non qui.
*/
export function useCollegaGiocatore() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (input: { giocatoreId: string; utenteId: string }) => {
const { error } = await supabaseNuoveTabelle
.from("giocatori_squadra")
.update({ auth_user_id: input.utenteId })
.eq("id", input.giocatoreId)
.is("auth_user_id", null);
if (error) throw error;
await pb
.collection("giocatori_squadra")
.update(input.giocatoreId, { auth_user_id: input.utenteId });
return input;
},
onSuccess: (input) => {
+28 -10
View File
@@ -1,5 +1,6 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { pb } from "@/integrations/pocketbase/client";
import { upsertByFilter } from "@/integrations/pocketbase/upsert";
export type VotoMvp = {
match_id: string;
@@ -8,6 +9,13 @@ export type VotoMvp = {
votato_nome: string;
};
type RigaMvpPocketBase = {
evento: string;
votante: string;
votato: string;
votato_nome: string;
};
const CHIAVE = ["mvp-voti"] as const;
/** Ore da aspettare dall'inizio della partita prima di poter votare l'MVP. */
@@ -27,11 +35,13 @@ export function useVotiMvp() {
queryKey: CHIAVE,
staleTime: 10 * 60_000,
queryFn: async (): Promise<VotoMvp[]> => {
const { data, error } = await supabase
.from("mvp_voti")
.select("match_id, votante_id, votato_id, votato_nome");
if (error) throw error;
return (data ?? []) as VotoMvp[];
const righe = await pb.collection("mvp_voti").getFullList<RigaMvpPocketBase>();
return righe.map((r) => ({
match_id: r.evento,
votante_id: r.votante,
votato_id: r.votato,
votato_nome: r.votato_nome,
}));
},
});
}
@@ -40,10 +50,18 @@ export function useVotaMvp() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (voto: VotoMvp) => {
const { error } = await supabase
.from("mvp_voti")
.upsert(voto, { onConflict: "match_id,votante_id" });
if (error) throw error;
// No autovoto e convocazione li valida l'hook voti_convocati.pb.js.
await upsertByFilter(
"mvp_voti",
"evento = {:evento} && votante = {:votante}",
{ evento: voto.match_id, votante: voto.votante_id },
{
evento: voto.match_id,
votante: voto.votante_id,
votato: voto.votato_id,
votato_nome: voto.votato_nome,
},
);
return voto;
},
// Aggiorna la cache localmente: nessuna rilettura dal database.
+28 -10
View File
@@ -1,5 +1,6 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { pb } from "@/integrations/pocketbase/client";
import { upsertByFilter } from "@/integrations/pocketbase/upsert";
import { VOTI_MINIMI_PAGELLA } from "./badges";
/** Voto anonimo da 1 a 10 dato a un compagno per una partita. */
@@ -10,6 +11,13 @@ export type VotoPagella = {
voto: number;
};
type RigaPagellaPocketBase = {
evento: string;
votante: string;
votato: string;
voto: number;
};
export const PAGELLE_KEY = ["pagelle"] as const;
/** Poche righe per stagione: una lettura per sessione basta. */
@@ -18,11 +26,13 @@ export function usePagelle() {
queryKey: PAGELLE_KEY,
staleTime: 10 * 60_000,
queryFn: async (): Promise<VotoPagella[]> => {
const { data, error } = await supabase
.from("pagelle_voti")
.select("match_id, votante_id, votato_id, voto");
if (error) throw error;
return (data ?? []) as VotoPagella[];
const righe = await pb.collection("pagelle_voti").getFullList<RigaPagellaPocketBase>();
return righe.map((r) => ({
match_id: r.evento,
votante_id: r.votante,
votato_id: r.votato,
voto: r.voto,
}));
},
});
return { ...query, voti: query.data ?? [] };
@@ -32,10 +42,18 @@ export function useVotaPagella() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (voto: VotoPagella) => {
const { error } = await supabase
.from("pagelle_voti")
.upsert(voto, { onConflict: "match_id,votante_id,votato_id" });
if (error) throw error;
// Convocazione e "pagelle non chiuse" li valida l'hook voti_convocati.pb.js.
await upsertByFilter(
"pagelle_voti",
"evento = {:evento} && votante = {:votante} && votato = {:votato}",
{ evento: voto.match_id, votante: voto.votante_id, votato: voto.votato_id },
{
evento: voto.match_id,
votante: voto.votante_id,
votato: voto.votato_id,
voto: voto.voto,
},
);
return voto;
},
// Cache aggiornata localmente: nessuna rilettura.
+14 -16
View File
@@ -1,5 +1,6 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { pb } from "@/integrations/pocketbase/client";
import { upsertByFilter } from "@/integrations/pocketbase/upsert";
import { completaTurni } from "./palloni-core";
import { useEventi } from "./eventi";
import { nomeCompleto, useGiocatoriSquadra } from "./giocatori-squadra";
@@ -7,18 +8,15 @@ import { nomeCompleto, useGiocatoriSquadra } from "./giocatori-squadra";
export const TURNI_KEY = ["turni-palloni"] as const;
type RigaTurno = {
evento_id: string;
giocatore_id: string;
aggiornato_da: string | null;
evento: string;
giocatore: string;
aggiornato_da: string;
};
async function fetchTurni(): Promise<Record<string, string>> {
const { data, error } = await supabase
.from("turni_palloni")
.select("evento_id, giocatore_id, aggiornato_da");
if (error) throw error;
const righe = await pb.collection("turni_palloni").getFullList<RigaTurno>();
const mappa: Record<string, string> = {};
for (const riga of (data ?? []) as RigaTurno[]) mappa[riga.evento_id] = riga.giocatore_id;
for (const riga of righe) mappa[riga.evento] = riga.giocatore;
return mappa;
}
@@ -37,16 +35,16 @@ export function useAssegnaTurno() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (input: { eventoId: string; giocatoreId: string; da: string | null }) => {
const { error } = await supabase.from("turni_palloni").upsert(
await upsertByFilter(
"turni_palloni",
"evento = {:evento}",
{ evento: input.eventoId },
{
evento_id: input.eventoId,
giocatore_id: input.giocatoreId,
aggiornato_da: input.da,
aggiornato_il: new Date().toISOString(),
evento: input.eventoId,
giocatore: input.giocatoreId,
aggiornato_da: input.da ?? "",
},
{ onConflict: "evento_id" },
);
if (error) throw error;
return input;
},
// Scrittura unica + aggiornamento cache locale, senza rilettura.
+32 -24
View File
@@ -1,5 +1,7 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { pb } from "@/integrations/pocketbase/client";
import { pbISO } from "@/integrations/pocketbase/formato";
import { upsertByFilter } from "@/integrations/pocketbase/upsert";
import type { Stato } from "./crapp-data";
import type { Evento } from "./eventi";
import { aggiornaSerie } from "./serie";
@@ -13,6 +15,14 @@ export type MappaPresenze = Record<string, Record<string, Stato>>;
/** eventoId -> giocatoreId -> istante della prima risposta (ISO). */
export type MappaTempiRisposta = Record<string, Record<string, string>>;
type RigaPresenza = {
id: string;
evento: string;
giocatore: string;
stato: string;
risposto_il: string;
};
/** Allenamenti e partite CrAPP già passati, che contano per le statistiche di presenza. */
function eventiContanoPresenze(
eventi: Evento[],
@@ -158,15 +168,12 @@ function serieSu(
type LetturaPresenze = { presenze: MappaPresenze; tempi: MappaTempiRisposta };
async function fetchPresenze(): Promise<LetturaPresenze> {
const { data, error } = await supabase
.from("risposte_presenze")
.select("evento_id, giocatore_id, stato, risposto_il");
if (error) throw error;
const righe = await pb.collection("risposte_presenze").getFullList<RigaPresenza>();
const presenze: MappaPresenze = {};
const tempi: MappaTempiRisposta = {};
for (const riga of data ?? []) {
(presenze[riga.evento_id] ??= {})[riga.giocatore_id] = riga.stato as Stato;
(tempi[riga.evento_id] ??= {})[riga.giocatore_id] = riga.risposto_il;
for (const riga of righe) {
(presenze[riga.evento] ??= {})[riga.giocatore] = riga.stato as Stato;
(tempi[riga.evento] ??= {})[riga.giocatore] = pbISO(riga.risposto_il);
}
return { presenze, tempi };
}
@@ -188,7 +195,7 @@ export function usePresenzeEvento(eventoId: string) {
* Due dettagli non sono cosmetici e non vanno persi (vedi `docs/modules/serie-presenze.md`):
*
* - l'istante si scrive **solo se manca** (`??=`), come fa il database, dove `risposto_il`
* non viene inviato sull'upsert e un trigger lo congela: è la prima risposta, non l'ultima,
* non viene inviato sulla scrittura e un hook lo congela: è la prima risposta, non l'ultima,
* e un ripensamento non deve far ripartire il cronometro della serie "Conferme 24h";
* - cancellare la risposta (`stato: null`) elimina **anche** l'istante, così se il giocatore
* risponde di nuovo il cronometro riparte davvero — ha ritirato la risposta.
@@ -219,23 +226,24 @@ export function useSalvaPresenza() {
return useMutation({
mutationFn: async (input: { eventoId: string; giocatoreId: string; stato: Stato | null }) => {
if (input.stato === null) {
const { error } = await supabase
.from("risposte_presenze")
.delete()
.eq("evento_id", input.eventoId)
.eq("giocatore_id", input.giocatoreId);
if (error) throw error;
const esistente = await pb
.collection("risposte_presenze")
.getFirstListItem(
pb.filter("evento = {:evento} && giocatore = {:giocatore}", {
evento: input.eventoId,
giocatore: input.giocatoreId,
}),
)
.catch(() => null);
if (esistente) await pb.collection("risposte_presenze").delete(esistente.id);
} else {
const { error } = await supabase.from("risposte_presenze").upsert(
{
evento_id: input.eventoId,
giocatore_id: input.giocatoreId,
stato: input.stato,
aggiornato_il: new Date().toISOString(),
},
{ onConflict: "evento_id,giocatore_id" },
// risposto_il NON va inviato: lo valorizza/congela l'hook risposte_presenze_immutabili.pb.js.
await upsertByFilter(
"risposte_presenze",
"evento = {:evento} && giocatore = {:giocatore}",
{ evento: input.eventoId, giocatore: input.giocatoreId },
{ evento: input.eventoId, giocatore: input.giocatoreId, stato: input.stato },
);
if (error) throw error;
}
return input;
},
+7 -72
View File
@@ -2,10 +2,14 @@ import { rigaCsv } from "./scout-export";
import { nomeCompleto, type GiocatoreSquadra } from "./giocatori-squadra";
/**
* Profilo amministrativo di un giocatore (DD-016). I file veri stanno nel bucket privato
* `profili-giocatore`: qui viaggiano solo i path.
* Profilo amministrativo di un giocatore (DD-016). I file veri sono campi file su
* PocketBase (`profili_giocatore`, protetti mai URL pubblici): qui viaggia il nome del
* file caricato (usato anche come semplice marcatore "presente/assente"). `id` è l'id del
* record PocketBase (non quello del giocatore): serve a costruire l'URL dei file, `null`
* finché il profilo non è mai stato salvato.
*/
export type Profilo = {
id: string | null;
giocatoreId: string;
dataNascita: string | null;
luogoNascita: string | null;
@@ -24,30 +28,9 @@ export type Profilo = {
fotoPath: string | null;
};
export type RigaProfilo = {
giocatore_id: string;
data_nascita: string | null;
luogo_nascita: string | null;
indirizzo: string | null;
telefono: string | null;
email: string | null;
documento_tipo: string | null;
documento_numero: string | null;
documento_rilasciato_da: string | null;
documento_emissione: string | null;
documento_scadenza: string | null;
documento_fronte_path: string | null;
documento_retro_path: string | null;
certificato_scadenza: string | null;
certificato_path: string | null;
foto_path: string | null;
};
export const COLONNE_PROFILO =
"giocatore_id, data_nascita, luogo_nascita, indirizzo, telefono, email, documento_tipo, documento_numero, documento_rilasciato_da, documento_emissione, documento_scadenza, documento_fronte_path, documento_retro_path, certificato_scadenza, certificato_path, foto_path";
export function profiloVuoto(giocatoreId: string): Profilo {
return {
id: null,
giocatoreId,
dataNascita: null,
luogoNascita: null,
@@ -67,54 +50,6 @@ export function profiloVuoto(giocatoreId: string): Profilo {
};
}
export function daRigaProfilo(r: RigaProfilo): Profilo {
return {
giocatoreId: r.giocatore_id,
dataNascita: r.data_nascita,
luogoNascita: r.luogo_nascita,
indirizzo: r.indirizzo,
telefono: r.telefono,
email: r.email,
documentoTipo: r.documento_tipo,
documentoNumero: r.documento_numero,
documentoRilasciatoDa: r.documento_rilasciato_da,
documentoEmissione: r.documento_emissione,
documentoScadenza: r.documento_scadenza,
documentoFrontePath: r.documento_fronte_path,
documentoRetroPath: r.documento_retro_path,
certificatoScadenza: r.certificato_scadenza,
certificatoPath: r.certificato_path,
fotoPath: r.foto_path,
};
}
/** I campi vuoti tornano al database come NULL, non come stringa vuota. */
function oNull(valore: string | null): string | null {
const pulito = valore?.trim();
return pulito ? pulito : null;
}
export function aRigaProfilo(p: Profilo): RigaProfilo {
return {
giocatore_id: p.giocatoreId,
data_nascita: oNull(p.dataNascita),
luogo_nascita: oNull(p.luogoNascita),
indirizzo: oNull(p.indirizzo),
telefono: oNull(p.telefono),
email: oNull(p.email),
documento_tipo: oNull(p.documentoTipo),
documento_numero: oNull(p.documentoNumero),
documento_rilasciato_da: oNull(p.documentoRilasciatoDa),
documento_emissione: oNull(p.documentoEmissione),
documento_scadenza: oNull(p.documentoScadenza),
documento_fronte_path: oNull(p.documentoFrontePath),
documento_retro_path: oNull(p.documentoRetroPath),
certificato_scadenza: oNull(p.certificatoScadenza),
certificato_path: oNull(p.certificatoPath),
foto_path: oNull(p.fotoPath),
};
}
/** Pesi delle sezioni del profilo (docs/modules/profilo-giocatore.md). */
export const PESI = { dati: 30, documento: 30, certificato: 30, foto: 10 } as const;
+115 -58
View File
@@ -1,29 +1,71 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { supabaseNuoveTabelle } from "@/integrations/supabase/client-nuove-tabelle";
import {
aRigaProfilo,
COLONNE_PROFILO,
daRigaProfilo,
type Profilo,
type RigaProfilo,
} from "./profili-core";
import { pb } from "@/integrations/pocketbase/client";
import { upsertByFilter } from "@/integrations/pocketbase/upsert";
import type { Profilo } from "./profili-core";
export const PROFILI_KEY = ["profili-giocatore"] as const;
export const BUCKET = "profili-giocatore";
type RigaProfiloPocketBase = {
id: string;
giocatore: string;
data_nascita: string;
luogo_nascita: string;
indirizzo: string;
telefono: string;
email: string;
documento_tipo: string;
documento_numero: string;
documento_rilasciato_da: string;
documento_emissione: string;
documento_scadenza: string;
documento_fronte: string;
documento_retro: string;
certificato_scadenza: string;
certificato: string;
foto: string;
};
/** "" -> null: PocketBase non ha un concetto di colonna NULL, i campi vuoti sono stringa vuota. */
function vuotoANull(v: string): string | null {
return v ? v : null;
}
/** I campi "date" di PocketBase tornano come datetime completo: qui serve solo "YYYY-MM-DD". */
function soloData(v: string): string | null {
return v ? v.slice(0, 10) : null;
}
function daRiga(r: RigaProfiloPocketBase): Profilo {
return {
id: r.id,
giocatoreId: r.giocatore,
dataNascita: soloData(r.data_nascita),
luogoNascita: vuotoANull(r.luogo_nascita),
indirizzo: vuotoANull(r.indirizzo),
telefono: vuotoANull(r.telefono),
email: vuotoANull(r.email),
documentoTipo: vuotoANull(r.documento_tipo),
documentoNumero: vuotoANull(r.documento_numero),
documentoRilasciatoDa: vuotoANull(r.documento_rilasciato_da),
documentoEmissione: soloData(r.documento_emissione),
documentoScadenza: soloData(r.documento_scadenza),
documentoFrontePath: vuotoANull(r.documento_fronte),
documentoRetroPath: vuotoANull(r.documento_retro),
certificatoScadenza: soloData(r.certificato_scadenza),
certificatoPath: vuotoANull(r.certificato),
fotoPath: vuotoANull(r.foto),
};
}
async function fetchProfili(): Promise<Record<string, Profilo>> {
const { data, error } = await supabaseNuoveTabelle
.from("profili_giocatore")
.select(COLONNE_PROFILO);
if (error) throw error;
const righe = await pb.collection("profili_giocatore").getFullList<RigaProfiloPocketBase>();
const mappa: Record<string, Profilo> = {};
for (const r of (data ?? []) as RigaProfilo[]) mappa[r.giocatore_id] = daRigaProfilo(r);
for (const r of righe) mappa[r.giocatore] = daRiga(r);
return mappa;
}
/**
* Profili visibili all'utente corrente: le policy RLS decidono quanti sono il proprio
* Profili visibili all'utente corrente: le API rule decidono quanti sono il proprio
* per un giocatore, tutti per un admin. Una lettura per sessione.
*/
export function useProfili() {
@@ -32,33 +74,55 @@ export function useProfili() {
}
/**
* I documenti stanno in un bucket privato e non hanno URL permanenti (DD-016 regola 4):
* ogni download passa da una signed URL che scade in un minuto.
* I documenti sono un campo file protetto e non hanno URL permanenti (DD-016 regola 4):
* ogni download passa da un token che scade a breve, l'equivalente PocketBase della
* signed URL Supabase.
*/
export async function urlFirmato(path: string): Promise<string> {
const { data, error } = await supabase.storage.from(BUCKET).createSignedUrl(path, 60);
if (error) throw error;
return data.signedUrl;
export async function urlFirmato(recordId: string, filename: string): Promise<string> {
const token = await pb.files.getToken();
return pb.files.getURL({ id: recordId, collectionName: "profili_giocatore" }, filename, {
token,
});
}
export async function scaricaFile(path: string): Promise<void> {
const url = await urlFirmato(path);
export async function scaricaFile(recordId: string, filename: string): Promise<void> {
const url = await urlFirmato(recordId, filename);
window.open(url, "_blank", "noopener,noreferrer");
}
/**
* Salva il profilo del giocatore. Le policy RLS lasciano scrivere solo la propria riga:
* Salva i campi testuali del profilo. Le API rule lasciano scrivere solo la propria riga:
* il vincolo vive nel database, qui non serve ricontrollarlo.
*
* I campi file NON passano da qui: PocketBase si aspetta un file in quei campi, non una
* stringa, quindi mandarli in questo upsert testuale fallirebbe la validazione. Li scrive
* `caricaFile` con una richiesta multipart dedicata ometterli qui li lascia semplicemente
* invariati, esattamente il comportamento voluto.
*/
export function useSalvaProfilo() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (profilo: Profilo) => {
const { error } = await supabaseNuoveTabelle
.from("profili_giocatore")
.upsert(aRigaProfilo(profilo), { onConflict: "giocatore_id" });
if (error) throw error;
return profilo;
const riga = await upsertByFilter<RigaProfiloPocketBase>(
"profili_giocatore",
"giocatore = {:giocatore}",
{ giocatore: profilo.giocatoreId },
{
giocatore: profilo.giocatoreId,
data_nascita: profilo.dataNascita?.trim() || "",
luogo_nascita: profilo.luogoNascita?.trim() || "",
indirizzo: profilo.indirizzo?.trim() || "",
telefono: profilo.telefono?.trim() || "",
email: profilo.email?.trim() || "",
documento_tipo: profilo.documentoTipo?.trim() || "",
documento_numero: profilo.documentoNumero?.trim() || "",
documento_rilasciato_da: profilo.documentoRilasciatoDa?.trim() || "",
documento_emissione: profilo.documentoEmissione || "",
documento_scadenza: profilo.documentoScadenza || "",
certificato_scadenza: profilo.certificatoScadenza || "",
},
);
return daRiga(riga);
},
// Scrittura unica e cache aggiornata a mano, senza rilettura.
onSuccess: (profilo) => {
@@ -72,46 +136,39 @@ export function useSalvaProfilo() {
export type SezioneFile = "documento-fronte" | "documento-retro" | "certificato" | "foto";
const CAMPO_SEZIONE: Record<SezioneFile, keyof RigaProfiloPocketBase> = {
"documento-fronte": "documento_fronte",
"documento-retro": "documento_retro",
certificato: "certificato",
foto: "foto",
};
const MAX_BYTE = 8 * 1024 * 1024;
const TIPI_AMMESSI = ["image/jpeg", "image/png", "image/webp", "application/pdf"];
function estensione(nome: string): string {
const punto = nome.lastIndexOf(".");
const est = punto > 0 ? nome.slice(punto + 1).toLowerCase() : "";
return /^[a-z0-9]{1,5}$/.test(est) ? est : "bin";
}
/**
* Carica un file nella cartella del giocatore e restituisce il path da salvare sul profilo.
* Il controllo su tipo e dimensione sta qui perché è il confine con un file scelto
* dall'utente; le policy dello Storage impediscono comunque di scrivere fuori dalla
* propria cartella.
* Carica un file nel campo giusto del profilo del giocatore (crea il profilo se non
* esiste ancora) e restituisce id del record e nome del file, da salvare nella bozza
* locale. Il controllo su tipo e dimensione sta qui perché è il confine con un file scelto
* dall'utente; le API rule della collection impediscono comunque di scrivere sul profilo
* di qualcun altro.
*/
export async function caricaFile(
giocatoreId: string,
sezione: SezioneFile,
file: File,
pathPrecedente?: string | null,
): Promise<string> {
): Promise<{ id: string; filename: string }> {
if (!TIPI_AMMESSI.includes(file.type)) {
throw new Error("Formato non ammesso: usa JPG, PNG, WEBP o PDF.");
}
if (file.size > MAX_BYTE) throw new Error("File troppo grande: massimo 8 MB.");
const path = `${giocatoreId}/${sezione}.${estensione(file.name)}`;
const { error } = await supabase.storage
.from(BUCKET)
.upload(path, file, { upsert: true, contentType: file.type });
if (error) throw error;
// Cambiando estensione il vecchio file resterebbe orfano nel bucket.
if (pathPrecedente && pathPrecedente !== path) {
await supabase.storage.from(BUCKET).remove([pathPrecedente]);
}
return path;
}
export async function rimuoviFile(path: string): Promise<void> {
const { error } = await supabase.storage.from(BUCKET).remove([path]);
if (error) throw error;
const campo = CAMPO_SEZIONE[sezione];
const riga = await upsertByFilter<RigaProfiloPocketBase>(
"profili_giocatore",
"giocatore = {:giocatore}",
{ giocatore: giocatoreId },
{ giocatore: giocatoreId, [campo]: file },
);
return { id: riga.id, filename: riga[campo] };
}
+9 -28
View File
@@ -1,34 +1,15 @@
import { useQuery } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { useSessione } from "./auth";
export const RUOLI_KEY = ["ruolo-admin"] as const;
/**
* Permessi di amministrazione: unica fonte è `user_roles` nel database (DD-011).
* Nessuna lista di nomi, altrimenti basterebbe scegliere il nome giusto per amministrare.
* Permessi di amministrazione: unica fonte è il campo `role` sul record utente
* PocketBase (DD-011). Nessuna lista di nomi, altrimenti basterebbe scegliere il nome
* giusto per amministrare.
*
* A differenza di Supabase (dove il ruolo stava nella tabella separata `user_roles` e
* richiedeva una query dedicata), qui il ruolo arriva già con la sessione: nessuna
* richiesta di rete o cache aggiuntiva serve.
*/
/** `null` = nessuna sessione, quindi il database non ha una risposta da dare. */
async function fetchRuoloAdmin(utenteId: string | null): Promise<boolean | null> {
if (!utenteId) return null;
const { data, error } = await supabase
.from("user_roles")
.select("role")
.eq("user_id", utenteId)
.eq("role", "admin")
.maybeSingle();
if (error) throw error;
return !!data;
}
export function useIsAdmin(): boolean {
const { utenteId } = useSessione();
// Il ruolo cambia solo quando un admin lo assegna: una lettura per sessione basta.
const query = useQuery({
queryKey: [...RUOLI_KEY, utenteId],
queryFn: () => fetchRuoloAdmin(utenteId),
staleTime: 30 * 60_000,
});
return query.data === true;
const { sessione } = useSessione();
return sessione?.["role"] === "admin";
}
+63 -29
View File
@@ -1,6 +1,9 @@
import { useEffect, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { ClientResponseError } from "pocketbase";
import { pb } from "@/integrations/pocketbase/client";
import { pbISO } from "@/integrations/pocketbase/formato";
import { upsertByFilter } from "@/integrations/pocketbase/upsert";
import { useEventi, type Evento } from "./eventi";
/** Minuti dopo i quali una sessione scout inattiva viene considerata libera. */
@@ -29,6 +32,23 @@ export type SessioneScout = {
aggiornato_il: string;
};
type RigaSessionePocketBase = {
id: string;
evento: string;
giocatore: string;
giocatore_nome: string;
updated: string;
};
function daRigaSessione(r: RigaSessionePocketBase): SessioneScout {
return {
evento_id: r.evento,
giocatore_id: r.giocatore,
giocatore_nome: r.giocatore_nome,
aggiornato_il: pbISO(r.updated),
};
}
export function sessioneScaduta(s: SessioneScout | null): boolean {
if (!s) return true;
const aggiornato = new Date(s.aggiornato_il).getTime();
@@ -41,13 +61,17 @@ export const SESSIONE_KEY = (eventoId: string) => ["scout-sessione", eventoId] a
/** Sessione condivisa: chi la tiene aperta lo vede chiunque, su qualsiasi dispositivo. */
async function leggiSessione(eventoId: string): Promise<SessioneScout | null> {
const { data, error } = await supabase
.from("scout_sessioni")
.select("evento_id, giocatore_id, giocatore_nome, aggiornato_il")
.eq("evento_id", eventoId)
.maybeSingle();
if (error) throw error;
return data;
try {
const riga = await pb
.collection("scout_sessioni")
.getFirstListItem<RigaSessionePocketBase>(
pb.filter("evento = {:evento}", { evento: eventoId }),
);
return daRigaSessione(riga);
} catch (errore) {
if (errore instanceof ClientResponseError && errore.status === 404) return null;
throw errore;
}
}
export function useSessioneScout(eventoId: string | null) {
@@ -70,16 +94,12 @@ export function useApriSessioneScout() {
if (attuale && !sessioneScaduta(attuale) && attuale.giocatore_id !== input.giocatoreId) {
return false;
}
const { error } = await supabase.from("scout_sessioni").upsert(
{
evento_id: input.eventoId,
giocatore_id: input.giocatoreId,
giocatore_nome: input.nome,
aggiornato_il: new Date().toISOString(),
},
{ onConflict: "evento_id" },
await upsertByFilter(
"scout_sessioni",
"evento = {:evento}",
{ evento: input.eventoId },
{ evento: input.eventoId, giocatore: input.giocatoreId, giocatore_nome: input.nome },
);
if (error) throw error;
return true;
},
onSuccess: (_ok, input) => {
@@ -92,13 +112,17 @@ export function useChiudiSessioneScout() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (input: { eventoId: string; giocatoreId: string }) => {
const attuale = await leggiSessione(input.eventoId);
if (attuale && attuale.giocatore_id === input.giocatoreId) {
const { error } = await supabase
.from("scout_sessioni")
.delete()
.eq("evento_id", input.eventoId);
if (error) throw error;
const attuale = await pb
.collection("scout_sessioni")
.getFirstListItem<RigaSessionePocketBase>(
pb.filter("evento = {:evento}", { evento: input.eventoId }),
)
.catch((errore) => {
if (errore instanceof ClientResponseError && errore.status === 404) return null;
throw errore;
});
if (attuale && attuale.giocatore === input.giocatoreId) {
await pb.collection("scout_sessioni").delete(attuale.id);
}
},
onSuccess: (_d, input) => {
@@ -116,11 +140,21 @@ export function useHeartbeatScout(
useEffect(() => {
if (!attivo || !eventoId || !giocatoreId) return;
const id = window.setInterval(() => {
void supabase
.from("scout_sessioni")
.update({ aggiornato_il: new Date().toISOString() })
.eq("evento_id", eventoId)
.eq("giocatore_id", giocatoreId);
// Solo aggiornamento, mai creazione: se la sessione è stata chiusa o presa da un
// altro giocatore nel frattempo, il filtro non trova nulla e il battito è un no-op
// (stesso comportamento dell'update Supabase originale). Riscrivere `giocatore` con
// lo stesso valore basta a PocketBase per aggiornare `updated`, che qui fa le veci
// di `aggiornato_il`.
void pb
.collection("scout_sessioni")
.getFirstListItem<RigaSessionePocketBase>(
pb.filter("evento = {:evento} && giocatore = {:giocatore}", {
evento: eventoId,
giocatore: giocatoreId,
}),
)
.then((riga) => pb.collection("scout_sessioni").update(riga.id, { giocatore: giocatoreId }))
.catch(() => {});
}, 60_000);
return () => window.clearInterval(id);
}, [attivo, eventoId, giocatoreId]);
+28 -18
View File
@@ -1,5 +1,7 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { ClientResponseError } from "pocketbase";
import { pb } from "@/integrations/pocketbase/client";
import { upsertByFilter } from "@/integrations/pocketbase/upsert";
import type { Azione } from "./scout-store";
/** Stato condiviso di uno scout in corso: chi prende il controllo riparte da qui. */
@@ -19,6 +21,8 @@ export const statoIniziale = (avversario: string, casa: boolean): StatoScout =>
export const SCOUT_STATO_KEY = (eventoId: string) => ["scout-stato", eventoId] as const;
type RigaScoutLive = { evento: string; stato: unknown };
export function useStatoScout(eventoId: string | null) {
return useQuery({
queryKey: SCOUT_STATO_KEY(eventoId ?? "-"),
@@ -26,13 +30,14 @@ export function useStatoScout(eventoId: string | null) {
staleTime: Infinity,
queryFn: async (): Promise<StatoScout | null> => {
if (!eventoId) return null;
const { data, error } = await supabase
.from("scout_live")
.select("stato")
.eq("evento_id", eventoId)
.maybeSingle();
if (error) throw error;
const stato = data?.stato as StatoScout | undefined;
const riga = await pb
.collection("scout_live")
.getFirstListItem<RigaScoutLive>(pb.filter("evento = {:evento}", { evento: eventoId }))
.catch((errore) => {
if (errore instanceof ClientResponseError && errore.status === 404) return null;
throw errore;
});
const stato = riga?.stato as StatoScout | undefined;
if (!stato || !Array.isArray(stato.azioni)) return null;
return stato;
},
@@ -43,15 +48,12 @@ export function useSalvaStatoScout() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (input: { eventoId: string; stato: StatoScout }) => {
const { error } = await supabase.from("scout_live").upsert(
{
evento_id: input.eventoId,
stato: JSON.parse(JSON.stringify(input.stato)),
aggiornato_il: new Date().toISOString(),
},
{ onConflict: "evento_id" },
await upsertByFilter(
"scout_live",
"evento = {:evento}",
{ evento: input.eventoId },
{ evento: input.eventoId, stato: JSON.parse(JSON.stringify(input.stato)) },
);
if (error) throw error;
return input;
},
onSuccess: (input) => {
@@ -64,8 +66,16 @@ export function useCancellaStatoScout() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (eventoId: string) => {
const { error } = await supabase.from("scout_live").delete().eq("evento_id", eventoId);
if (error) throw error;
const riga = await pb
.collection("scout_live")
.getFirstListItem<RigaScoutLive & { id: string }>(
pb.filter("evento = {:evento}", { evento: eventoId }),
)
.catch((errore) => {
if (errore instanceof ClientResponseError && errore.status === 404) return null;
throw errore;
});
if (riga) await pb.collection("scout_live").delete(riga.id);
return eventoId;
},
onSuccess: (eventoId) => {
+10 -14
View File
@@ -1,5 +1,5 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { pb } from "@/integrations/pocketbase/client";
import { giocatori, type Giocatore } from "./crapp-data";
export type AzioneTipo = "attacco" | "ace" | "muro" | "errore" | "punto_avv" | "errore_avv";
@@ -85,7 +85,7 @@ type RigaScoutPartita = {
function daRiga(r: RigaScoutPartita): ScoutMatch {
return {
id: r.id,
data: r.data,
data: r.data.slice(0, 10),
avversario: r.avversario,
casa: r.casa,
setNostri: r.set_nostri,
@@ -98,12 +98,10 @@ function daRiga(r: RigaScoutPartita): ScoutMatch {
export const SCOUT_MATCHES_KEY = ["scout-partite"] as const;
async function fetchScoutMatches(): Promise<ScoutMatch[]> {
const { data, error } = await supabase
.from("scout_partite")
.select("id, data, avversario, casa, set_nostri, set_loro, parziali, azioni")
.order("creato_il", { ascending: false });
if (error) throw error;
return (data ?? []).map(daRiga);
const righe = await pb.collection("scout_partite").getFullList<RigaScoutPartita>({
sort: "-created",
});
return righe.map(daRiga);
}
/** Partite scoutate condivise con tutta la squadra: chi scoutizza le vede da qualsiasi
@@ -121,9 +119,9 @@ export function useSalvaScoutMatch() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (input: { eventoId: string | null; match: ScoutMatch }) => {
const { error } = await supabase.from("scout_partite").insert({
await pb.collection("scout_partite").create({
id: input.match.id,
evento_id: input.eventoId,
evento: input.eventoId ?? "",
data: input.match.data,
avversario: input.match.avversario,
casa: input.match.casa,
@@ -132,10 +130,9 @@ export function useSalvaScoutMatch() {
parziali: JSON.parse(JSON.stringify(input.match.parziali)),
azioni: JSON.parse(JSON.stringify(input.match.azioni)),
});
if (error) throw error;
return input.match;
},
// La query ordina per `creato_il` decrescente: la partita appena salvata è la più recente.
// La query ordina per creazione decrescente: la partita appena salvata è la più recente.
onSuccess: (match) =>
queryClient.setQueryData<ScoutMatch[]>(SCOUT_MATCHES_KEY, (prec) => [
match,
@@ -148,8 +145,7 @@ export function useEliminaScoutMatch() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (id: string) => {
const { error } = await supabase.from("scout_partite").delete().eq("id", id);
if (error) throw error;
await pb.collection("scout_partite").delete(id);
return id;
},
onSuccess: (id) =>
+9 -3
View File
@@ -338,19 +338,21 @@ function Documento({
label,
stato,
path,
recordId,
}: {
icona: React.ReactNode;
label: string;
stato: StatoScadenza | "presente" | "assente";
path: string | null;
recordId: string | null;
}) {
const [inCorso, setInCorso] = useState(false);
async function scarica() {
if (!path || inCorso) return;
if (!path || !recordId || inCorso) return;
setInCorso(true);
try {
await scaricaFile(path);
await scaricaFile(recordId, path);
} catch (error) {
toast.error(error instanceof Error ? error.message : "Download non riuscito");
} finally {
@@ -362,7 +364,7 @@ function Documento({
<button
type="button"
onClick={scarica}
disabled={!path || inCorso}
disabled={!path || !recordId || inCorso}
className={cn(
"premi flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-bold uppercase disabled:opacity-60",
statoClasse[stato],
@@ -431,24 +433,28 @@ function SchedaGiocatore({
label="Doc fronte"
stato={fronte}
path={profilo?.documentoFrontePath ?? null}
recordId={profilo?.id ?? null}
/>
<Documento
icona={<IdCard className="h-3.5 w-3.5" />}
label="Doc retro"
stato={retro}
path={profilo?.documentoRetroPath ?? null}
recordId={profilo?.id ?? null}
/>
<Documento
icona={<FileText className="h-3.5 w-3.5" />}
label="Certificato"
stato={certificato}
path={profilo?.certificatoPath ?? null}
recordId={profilo?.id ?? null}
/>
<Documento
icona={<Image className="h-3.5 w-3.5" />}
label="Foto"
stato={sezioni.foto ? "presente" : "assente"}
path={profilo?.fotoPath ?? null}
recordId={profilo?.id ?? null}
/>
<span
className={cn(
+10 -10
View File
@@ -6,6 +6,8 @@ import { inviaPush } from "@/lib/webpush.server";
const schema = z.object({ eventoId: z.string().min(1).max(50) });
type RigaIscrizione = { id: string; endpoint: string; p256dh: string; auth: string };
/** Avviso "sondaggio pre-partita aperto": lo fa partire un admin dalla pagina partita. */
export const Route = createFileRoute("/api/public/apri-sondaggio")({
server: {
@@ -21,23 +23,21 @@ export const Route = createFileRoute("/api/public/apri-sondaggio")({
const partita = eventi.find((e) => e.id === parsed.data.eventoId);
if (!partita) return new Response("Evento non trovato", { status: 404 });
const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
const { data: iscrizioni } = await supabaseAdmin
.from("push_subscriptions")
.select("endpoint, p256dh, auth");
const { pbAdmin } = await import("@/integrations/pocketbase/client.server");
const admin = await pbAdmin();
const iscrizioni = await admin
.collection("push_subscriptions")
.getFullList<RigaIscrizione>();
const titolo = "💩 Sondaggio pre-partita aperto";
const testo = `${partita.titolo} · ore ${partita.ora}. Quante cacche hai fatto? Rispondi prima del fischio d'inizio.`;
let inviate = 0;
for (const iscrizione of iscrizioni ?? []) {
for (const iscrizione of iscrizioni) {
try {
const { stato } = await inviaPush(iscrizione, titolo, testo);
if (stato === 404 || stato === 410) {
await supabaseAdmin
.from("push_subscriptions")
.delete()
.eq("endpoint", iscrizione.endpoint);
await admin.collection("push_subscriptions").delete(iscrizione.id);
} else if (stato >= 200 && stato < 300) {
inviate += 1;
}
@@ -46,7 +46,7 @@ export const Route = createFileRoute("/api/public/apri-sondaggio")({
}
}
return Response.json({ inviate, destinatari: (iscrizioni ?? []).length });
return Response.json({ inviate, destinatari: iscrizioni.length });
},
},
},
+11 -7
View File
@@ -9,16 +9,20 @@ export const Route = createFileRoute("/api/public/notifiche-attive")({
const negato = await richiediAdmin(request);
if (negato) return negato;
const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
const { data, error } = await supabaseAdmin
.from("push_subscriptions")
.select("giocatore_id");
if (error) {
const { pbAdmin } = await import("@/integrations/pocketbase/client.server");
const admin = await pbAdmin();
try {
const righe = await admin
.collection("push_subscriptions")
.getFullList<{ giocatore: string }>();
return Response.json({
giocatoreIds: idsConNotificheAttive(righe.map((r) => ({ giocatore_id: r.giocatore }))),
});
} catch (error) {
console.error("notifiche-attive", error);
return new Response("Errore lettura", { status: 500 });
}
return Response.json({ giocatoreIds: idsConNotificheAttive(data ?? []) });
},
},
},
+23 -19
View File
@@ -9,6 +9,15 @@ import { leggiEventi } from "@/lib/eventi.server";
const schema = z.object({ eventoId: z.string().min(1).max(50) });
type RigaTurno = { evento: string; giocatore: string };
type RigaIscrizione = {
id: string;
endpoint: string;
giocatore: string;
p256dh: string;
auth: string;
};
/**
* Promemoria del turno palloni per un evento: lo fa partire un admin dalla pagina
* dell'evento (DD-025). Il testo viaggia cifrato dentro la push.
@@ -27,13 +36,12 @@ export const Route = createFileRoute("/api/public/promemoria-palloni")({
const evento = eventi.find((e) => e.id === parsed.data.eventoId);
if (!evento) return new Response("Evento non trovato", { status: 404 });
const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
const { pbAdmin } = await import("@/integrations/pocketbase/client.server");
const admin = await pbAdmin();
const { data: righe } = await supabaseAdmin
.from("turni_palloni")
.select("evento_id, giocatore_id");
const righeTurni = await admin.collection("turni_palloni").getFullList<RigaTurno>();
const salvati: Record<string, string> = {};
for (const riga of righe ?? []) salvati[riga.evento_id] = riga.giocatore_id;
for (const riga of righeTurni) salvati[riga.evento] = riga.giocatore;
const squadra = await leggiGiocatoriSquadra();
const rosa = squadra
@@ -44,25 +52,21 @@ 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 });
const { data: iscrizioni } = await supabaseAdmin
.from("push_subscriptions")
.select("endpoint, giocatore_id, p256dh, auth")
.in(
"giocatore_id",
avvisi.map((a) => a.giocatoreId),
);
const idsFiltro = avvisi.map((a) => a.giocatoreId);
const filtro = idsFiltro.map((_, i) => `giocatore = {:g${i}}`).join(" || ");
const parametri = Object.fromEntries(idsFiltro.map((id, i) => [`g${i}`, id]));
const iscrizioni = await admin
.collection("push_subscriptions")
.getFullList<RigaIscrizione>({ filter: admin.filter(filtro, parametri) });
let inviate = 0;
for (const iscrizione of iscrizioni ?? []) {
const avviso = avvisi.find((a) => a.giocatoreId === iscrizione.giocatore_id);
for (const iscrizione of iscrizioni) {
const avviso = avvisi.find((a) => a.giocatoreId === iscrizione.giocatore);
if (!avviso) continue;
try {
const { stato } = await inviaPush(iscrizione, avviso.titolo, avviso.testo);
if (stato === 404 || stato === 410) {
await supabaseAdmin
.from("push_subscriptions")
.delete()
.eq("endpoint", iscrizione.endpoint);
await admin.collection("push_subscriptions").delete(iscrizione.id);
} else if (stato >= 200 && stato < 300) {
inviate += 1;
}
@@ -71,7 +75,7 @@ export const Route = createFileRoute("/api/public/promemoria-palloni")({
}
}
return Response.json({ inviate, destinatari: (iscrizioni ?? []).length });
return Response.json({ inviate, destinatari: iscrizioni.length });
},
},
},
+21 -10
View File
@@ -17,17 +17,24 @@ export const Route = createFileRoute("/api/public/push-subscribe")({
const parsed = schemaIscrizione.safeParse(await request.json());
if (!parsed.success) return new Response("Dati non validi", { status: 400 });
const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
const { error } = await supabaseAdmin.from("push_subscriptions").upsert(
const { pbAdmin } = await import("@/integrations/pocketbase/client.server");
const { upsertByFilter } = await import("@/integrations/pocketbase/upsert");
const admin = await pbAdmin();
try {
await upsertByFilter(
"push_subscriptions",
"endpoint = {:endpoint}",
{ endpoint: parsed.data.endpoint },
{
endpoint: parsed.data.endpoint,
giocatore_id: parsed.data.giocatoreId,
giocatore: parsed.data.giocatoreId,
p256dh: parsed.data.p256dh,
auth: parsed.data.auth,
},
{ onConflict: "endpoint" },
admin,
);
if (error) {
} catch (error) {
console.error("push-subscribe", error);
return new Response("Errore salvataggio", { status: 500 });
}
@@ -37,11 +44,15 @@ export const Route = createFileRoute("/api/public/push-subscribe")({
const parsed = schemaCancellazione.safeParse(await request.json());
if (!parsed.success) return new Response("Dati non validi", { status: 400 });
const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
await supabaseAdmin
.from("push_subscriptions")
.delete()
.eq("endpoint", parsed.data.endpoint);
const { pbAdmin } = await import("@/integrations/pocketbase/client.server");
const admin = await pbAdmin();
const esistente = await admin
.collection("push_subscriptions")
.getFirstListItem(
admin.filter("endpoint = {:endpoint}", { endpoint: parsed.data.endpoint }),
)
.catch(() => null);
if (esistente) await admin.collection("push_subscriptions").delete(esistente.id);
return Response.json({ ok: true });
},
},
+19 -15
View File
@@ -12,6 +12,9 @@ const schema = z.object({
da: z.string().min(1).max(60).optional(),
});
type RigaPresenza = { giocatore: string; stato: string };
type RigaIscrizione = { id: string; endpoint: string; p256dh: string; auth: string };
export const Route = createFileRoute("/api/public/sollecita-presenze")({
server: {
handlers: {
@@ -26,22 +29,26 @@ export const Route = createFileRoute("/api/public/sollecita-presenze")({
const evento = eventi.find((e) => e.id === parsed.data.eventoId);
if (!evento) return new Response("Evento non trovato", { status: 404 });
const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
const { pbAdmin } = await import("@/integrations/pocketbase/client.server");
const admin = await pbAdmin();
const { data: righe } = await supabaseAdmin
.from("risposte_presenze")
.select("giocatore_id, stato")
.eq("evento_id", evento.id);
const righe = await admin.collection("risposte_presenze").getFullList<RigaPresenza>({
filter: admin.filter("evento = {:evento}", { evento: evento.id }),
});
const squadra = await leggiGiocatoriSquadra();
const destinatari = destinatariSollecito(squadra, righe ?? []);
const destinatari = destinatariSollecito(
squadra,
righe.map((r) => ({ giocatore_id: r.giocatore, stato: r.stato })),
);
if (destinatari.length === 0) return Response.json({ inviate: 0, destinatari: 0 });
const { data: iscrizioni } = await supabaseAdmin
.from("push_subscriptions")
.select("endpoint, p256dh, auth")
.in("giocatore_id", destinatari);
const filtro = destinatari.map((_, i) => `giocatore = {:g${i}}`).join(" || ");
const parametri = Object.fromEntries(destinatari.map((id, i) => [`g${i}`, id]));
const iscrizioni = await admin
.collection("push_subscriptions")
.getFullList<RigaIscrizione>({ filter: admin.filter(filtro, parametri) });
const titolo = "Manca la tua risposta";
const testo = `${evento.titolo} · ${formatData(evento.data)} ore ${evento.ora}. ${
@@ -49,14 +56,11 @@ export const Route = createFileRoute("/api/public/sollecita-presenze")({
} una conferma: presente, assente o in ritardo?`;
let inviate = 0;
for (const iscrizione of iscrizioni ?? []) {
for (const iscrizione of iscrizioni) {
try {
const { stato } = await inviaPush(iscrizione, titolo, testo);
if (stato === 404 || stato === 410) {
await supabaseAdmin
.from("push_subscriptions")
.delete()
.eq("endpoint", iscrizione.endpoint);
await admin.collection("push_subscriptions").delete(iscrizione.id);
} else if (stato >= 200 && stato < 300) {
inviate += 1;
}
+3 -3
View File
@@ -119,9 +119,9 @@ function Profilo() {
e.target.value = "";
if (!file || !g) return;
try {
await caricaAvatar(g.id, file);
const riga = await caricaAvatar(g.id, file);
setBust(Date.now());
impostaAvatarEsiste(g.id, true);
impostaAvatarEsiste(g.id, riga);
toast.success("Immagine profilo aggiornata");
} catch {
toast.error("Non sono riuscito a caricare l'immagine");
@@ -169,7 +169,7 @@ function Profilo() {
try {
await rimuoviAvatar(g.id);
setBust(Date.now());
impostaAvatarEsiste(g.id, false);
impostaAvatarEsiste(g.id, null);
toast.success("Immagine rimossa");
} catch {
toast.error("Non sono riuscito a rimuovere l'immagine");
+2 -2
View File
@@ -1,7 +1,7 @@
import { createStart, createCsrfMiddleware, createMiddleware } from "@tanstack/react-start";
import { renderErrorPage } from "./lib/error-page";
import { attachSupabaseAuth } from "@/integrations/supabase/auth-attacher";
import { attachPocketBaseAuth } from "@/integrations/pocketbase/auth-attacher";
const errorMiddleware = createMiddleware().server(async ({ next }) => {
try {
@@ -26,6 +26,6 @@ const csrfMiddleware = createCsrfMiddleware({
});
export const startInstance = createStart(() => ({
functionMiddleware: [attachSupabaseAuth],
functionMiddleware: [attachPocketBaseAuth],
requestMiddleware: [errorMiddleware, csrfMiddleware],
}));
+6 -1
View File
@@ -9,8 +9,13 @@
* M2 non è ancora applicata a quel database: sono stati dell'ambiente, non difetti.
*/
import assert from "node:assert/strict";
import { COLONNE_PROFILO } from "@/lib/profili-core";
import { envDaFile } from "../helpers/server";
// Elenco storico delle colonne Supabase di profili_giocatore (M2/DD-016). Non più importato
// da src/lib/profili-core.ts da quando il livello dati è passato a PocketBase (Fase 4 della
// migrazione): questo test valida ancora lo schema Supabase, quindi lo tiene qui in locale.
const COLONNE_PROFILO =
"giocatore_id, data_nascita, luogo_nascita, indirizzo, telefono, email, documento_tipo, documento_numero, documento_rilasciato_da, documento_emissione, documento_scadenza, documento_fronte_path, documento_retro_path, certificato_scadenza, certificato_path, foto_path";
import { prova, riepilogo, salta } from "../helpers/prova";
const env = { ...envDaFile(), ...process.env };
+19 -8
View File
@@ -1,16 +1,27 @@
/**
* Check dell'avatar giocatore: `bun test/unit/avatar-store.test.ts`.
* `urlAvatar` è puro (il bucket è pubblico, nessuna richiesta di rete): qui
* verifichiamo solo la forma dell'URL, non serve un database.
* `urlAvatarDaRiga` è puro (il campo non è protetto, nessuna richiesta di rete): qui
* verifichiamo solo la forma dell'URL a partire da una riga finta, non serve un database.
*/
import assert from "node:assert/strict";
import { urlAvatar } from "@/lib/avatar-store";
import { urlAvatarDaRiga } from "@/lib/avatar-store";
const url = urlAvatar("g1");
const riga = { id: "rec1", giocatore: "g1", foto: "avatar_abc123.jpg" };
assert.ok(url.includes("avatar-giocatori"), "punta al bucket degli avatar");
assert.ok(url.includes("g1/avatar.jpg"), "il percorso è <id>/avatar.jpg");
assert.equal(urlAvatar("g1"), url, "deterministico: nessuna chiamata di rete coinvolta");
assert.notEqual(urlAvatar("g2"), url, "id diversi -> percorsi diversi");
const url = urlAvatarDaRiga(riga);
assert.ok(url.includes("avatar_giocatori"), "punta alla collection degli avatar");
assert.ok(url.includes("rec1"), "contiene l'id del record");
assert.ok(url.includes("avatar_abc123.jpg"), "contiene il nome del file");
assert.equal(
urlAvatarDaRiga(riga),
url,
"deterministico a parità di riga: nessuna chiamata di rete",
);
assert.notEqual(
urlAvatarDaRiga({ ...riga, foto: "altro.jpg" }),
url,
"file diverso -> URL diverso",
);
console.log("avatar-store: ok");
+10 -14
View File
@@ -23,10 +23,10 @@ const riga: RigaEvento = {
campionato: true,
casa: true,
pagelle_chiuse: false,
creato_il: "2026-08-20T09:00:00Z",
created: "2026-08-20 09:00:00.000Z",
};
// --- daRiga: i NULL del database diventano valori sicuri ---------------------
// --- daRiga: normalizza data/creato_il, PocketBase non ha NULL (solo "", [], false) -----
assert.deepEqual(daRiga(riga), {
id: "e1",
tipo: "partita",
@@ -39,20 +39,20 @@ assert.deepEqual(daRiga(riga), {
campionato: true,
casa: true,
pagelleChiuse: false,
creatoIl: "2026-08-20T09:00:00Z",
creatoIl: "2026-08-20T09:00:00.000Z",
});
const vuota = daRiga({
...riga,
note: null,
convocati: null,
casa: null,
note: "",
convocati: [],
casa: false,
campionato: false,
pagelle_chiuse: false,
});
assert.equal(vuota.note, "", "note NULL → stringa vuota");
assert.deepEqual(vuota.convocati, [], "convocati NULL → tutta la rosa (array vuoto)");
assert.equal(vuota.casa, true, "casa NULL → si gioca in casa");
assert.equal(vuota.note, "", "note vuota resta vuota");
assert.deepEqual(vuota.convocati, [], "convocati vuoti → tutta la rosa (array vuoto)");
assert.equal(vuota.casa, false, "casa è quello che c'è in database, nessun default implicito");
assert.equal(vuota.pagelleChiuse, false);
// --- categoriaEvento: l'amichevole è una partita fuori campionato ------------
@@ -100,11 +100,7 @@ assert.deepEqual(
["g2"],
"con i convocati indicati si filtra",
);
assert.deepEqual(
convocatiEvento(daRiga({ ...riga, convocati: null }), rosa),
rosa,
"vuoto = tutti",
);
assert.deepEqual(convocatiEvento(daRiga({ ...riga, convocati: [] }), rosa), rosa, "vuoto = tutti");
assert.deepEqual(convocatiEvento(null, rosa), rosa, "senza evento restano tutti");
assert.deepEqual(
convocatiEvento(daRiga({ ...riga, convocati: ["ignoto"] }), rosa),
+1 -13
View File
@@ -1,10 +1,8 @@
/** Check dei profili giocatore: `bun test/unit/profili-core.test.ts`. */
import assert from "node:assert/strict";
import {
aRigaProfilo,
completamento,
csvTesseramento,
daRigaProfilo,
sezioniComplete,
statoScadenza,
type Profilo,
@@ -19,6 +17,7 @@ import {
import { dividiNome } from "@/lib/crapp-data";
const vuoto: Profilo = {
id: null,
giocatoreId: "g1",
dataNascita: null,
luogoNascita: null,
@@ -77,17 +76,6 @@ assert.equal(
);
assert.equal(sezioniComplete({ ...completo, documentoFrontePath: null }).documento, false);
// --- aRigaProfilo ------------------------------------------------------------
const riga = aRigaProfilo({ ...completo, luogoNascita: " ", telefono: " 333 " });
assert.equal(riga.luogo_nascita, null, "i campi solo-spazi tornano NULL, non stringa vuota");
assert.equal(riga.telefono, "333", "il resto viene ripulito ai bordi");
assert.equal(riga.documento_fronte_path, "g1/documento-fronte.jpg");
assert.deepEqual(
daRigaProfilo(aRigaProfilo(completo)),
completo,
"modello -> riga -> modello non perde niente",
);
// --- statoScadenza -----------------------------------------------------------
const oggi = "2026-08-30";
assert.equal(statoScadenza(null, null, oggi), "mancante");