diff --git a/AGENTS.md b/AGENTS.md index 326fb316..38b08eb9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ What the app is and how to run it: [`README.md`](README.md). UI rules: [`docs/de ## Architecture -- **Routes** (`src/routes/`): `/dashboard` loads `me.access` via the BFF and requires `admin:access`. The route context +- **Routes** (`src/routes/`): `/dashboard` loads a fresh `me.access` via the BFF. Authenticated applicants can open Associazioni; internal areas retain their exact permissions. The route context carries display user data and permissions, never tokens. Navigation and mutation controls use exact permissions. - **Auth**: `/auth/login`, `/auth/callback` and POST `/auth/logout` implement OIDC with PKCE/state/nonce through `openid-client`. ID tokens are signature-checked. Tokens remain in the dedicated Redis server session store. @@ -52,6 +52,8 @@ What the app is and how to run it: [`README.md`](README.md). UI rules: [`docs/de from a server function, never a token. UI copy is Italian. Details: `docs/regulations/README.md`. - **Shared UI**: `src/components/shell`, `src/components/primitives`, `src/components/ui`. +- **Associazioni** (`src/features/association-portal/`): register, representatives and review; see `docs/associations/README.md`. The shell admits every signed-in account with a fresh `me.access`, so any function using `dashboardUserMiddleware` must add its own permission check; `associationSelfMiddleware` grants none. Operator commands (`operatorActions` in `portal.contract.ts`) go through `reviewPortalAssociation` (`web:content:write`); `changePortalAssociation` accepts only `applicantActions`. The backend checks membership on every call. UI copy is Italian. + ## Conventions `pnpm test` enforces the items marked (test); its failure messages name what to add. diff --git a/README.md b/README.md index 7b7dd9d8..3bafab47 100644 --- a/README.md +++ b/README.md @@ -114,3 +114,7 @@ Logout deletes the server session, attempts refresh revocation, and redirects to requests require an `Origin` exactly equal to `APP_URL`'s configured origin. Sessions and identity responses are not cacheable. Production cookies are host-only, `Secure`, `HttpOnly`, `SameSite=Lax`; tokens and client keys never appear in browser storage or route loader output. + +## Associazioni + +Registro, accesso dei referenti e pubblicazione moderata: [flussi e rilascio](docs/associations/README.md). diff --git a/docs/associations/README.md b/docs/associations/README.md new file mode 100644 index 00000000..82bde089 --- /dev/null +++ b/docs/associations/README.md @@ -0,0 +1,42 @@ +# Registro e portale delle associazioni + +Ogni persona accede a `admin.polinetwork.org` con il proprio account. Non riceve permessi amministrativi globali: il backend verifica a ogni operazione il collegamento alla singola associazione. Gli operatori PoliNetwork che possiedono insieme `admin:access` e `web:content:write` gestiscono registro e approvazioni. + +## Tre decisioni distinte + +1. **Registrazione**: la persona propone nome, sigla, informazioni e motivazione privata del proprio ruolo. PoliNetwork verifica e approva l'associazione e il primo responsabile. Una registrazione inserita direttamente da un operatore può rimanere senza referenti. +2. **Rappresentanza**: una persona richiede accesso a un'associazione esistente, oppure riceve un invito. L'invito si accetta con un account personale e PoliNetwork approva esattamente quell'account. Nome ed email non assegnano mai automaticamente accesso. +3. **Pubblicazione**: responsabili e collaboratori preparano una proposta; il responsabile la invia. Solo l'approvazione PoliNetwork cambia la scheda pubblicata. Registrare un'associazione non la pubblica. + +Una richiesta duplicata di registrazione può essere trasferita da PoliNetwork al record esistente come richiesta di accesso, senza attribuire automaticamente alcun ruolo. + +## Ruoli e schermate + +| Persona | Funzioni | +| ------------------------------ | ---------------------------------------------------------------------------------------------------------- | +| Autenticata senza collegamenti | Registra un'associazione, cerca il registro per nome, chiede accesso, segue le proprie richieste | +| Collaboratore | Legge la propria associazione e prepara modifiche della scheda | +| Responsabile | Anche invio per pubblicazione, inviti e proposte di modifica dei referenti | +| Operatore PoliNetwork | Registro completo, richieste, approvazioni, note interne, sospensione, oscuramento, archiviazione e revoca | + +`/dashboard/associations` presenta le associazioni accessibili, le richieste e la ricerca per chiedere accesso. Il dettaglio separa scheda, richieste, referenti e attività. L'invito atterra su `/associations/invite`, conserva il ritorno dopo il login e mostra l'account prima dell'accettazione. + +La scheda comprende nome, sigla, descrizioni italiana e inglese, email pubblica, logo e fino a 30 link con piattaforma, etichetta e URL. Si possono inserire più link Telegram, Twitch o altri canali della stessa piattaforma. Il logo può essere un URL HTTP/S oppure un PNG/JPEG fino a 1 MiB caricato dopo il salvataggio iniziale. Motivazioni di rappresentanza, email degli inviti e note interne non finiscono sul sito pubblico. + +## Stati e gestione dei referenti + +Le richieste passano per bozza, invio, eventuali integrazioni, approvazione/rifiuto o ritiro. Le modifiche inviate restano separate dalla versione pubblicata, anche durante un rifiuto. La scheda richiede entrambe le descrizioni per essere pubblicata. + +Gli inviti scadono dopo 14 giorni, sono monouso e sono invalidati dal ritiro. Ogni nuovo collegamento e ogni cambio di ruolo richiede approvazione. La rimozione ordinaria dell'ultimo responsabile richiede prima un sostituto; l'abbandono personale o una revoca esplicita PoliNetwork sono immediati e lasciano il record segnalato come privo di responsabile. + +La sospensione blocca le modifiche dei referenti e può mantenere visibile la scheda; l'oscuramento la rimuove dal sito. L'archiviazione conserva registro e storico, blocca la gestione e oscura la scheda. Le note interne sono visibili solo agli operatori. Ogni richiedente vede soltanto le proprie evidenze; i referenti vedono anche le proposte di contenuto della propria associazione. + +## Contratto e rilascio + +Il backend espone `associationPortal.*`. Il BFF valida tutte le risposte con `portal.contract.ts`, copia del contratto backend. Login OIDC, sessioni Redis e controllo Origin restano quelli esistenti. L'accesso alla shell è aperto agli account autenticati con una risposta fresca di `me.access`; i singoli servizi interni continuano a richiedere i propri permessi. + +Il backend conserva registro, richieste, storico e collegamenti in un aggregato transazionale PostgreSQL. Revisioni ottimistiche, blocchi di riga e chiavi di idempotenza proteggono da approvazioni concorrenti e retry. Le email usano una coda durevole con retry; lo stato è consultabile anche nel portale. Nessuna modifica deve essere ripetuta solo perché il successivo aggiornamento della pagina fallisce. + +Le tre PR vanno coordinate: migrazione e backend, poi admin; il sito supporta sia la vecchia risposta sia `extraLinks`. Durante il breve intervallo tra backend e admin, il vecchio editor rifiuta le scritture. La migrazione conserva identificativi e schede pubbliche esistenti, senza assegnare referenti. Verificare `ESIGN_DASHBOARD_URL=https://admin.polinetwork.org`, configurazione email e storage Azure del backend. Non sono richieste nuove autorizzazioni globali nel repository Auth. + +Il rilascio richiede backup e normale procedura di migrazione del backend. Queste PR non eseguono migrazioni né deployment in produzione. Dopo il rilascio verificare login reale, consegna invito via email e caricamento logo contro i servizi configurati; la prova automatizzata locale usa account e recapiti fittizi. diff --git a/src/components/shell/nav.ts b/src/components/shell/nav.ts index 269caea7..8c955d59 100644 --- a/src/components/shell/nav.ts +++ b/src/components/shell/nav.ts @@ -48,6 +48,7 @@ export type DashboardPath = Extract export type ServiceId = | "overview" + | "associations" | "people" | "telegram" | "whatsapp" @@ -115,6 +116,8 @@ export type Service = { export type PageMatch = | { kind: "overview" } + | { kind: "association-portal" } + | { kind: "association-detail"; id: string } | { kind: "account" } | { kind: "account-me" } | { kind: "people-overview" } @@ -357,13 +360,6 @@ const web: Service = { path: "/dashboard/web/projects", sections: [ { id: "projects", title: "Projects", icon: FolderKanban, path: "/dashboard/web/projects" }, - { - id: "associations", - title: "Associations", - icon: Users, - path: "/dashboard/web/associations", - searchPlaceholder: "Search associations…", - }, { id: "freshman", title: "Freshman", icon: BookOpen, path: "/dashboard/web/freshman" }, { id: "faqs", @@ -456,6 +452,23 @@ const regulations: Service = { ], } +const associations: Service = { + id: "associations", + title: "Associazioni", + short: "Associazioni", + icon: UsersRound, + path: "/dashboard/associations", + sections: [ + { + id: "portal", + title: "Le mie associazioni", + icon: UsersRound, + path: "/dashboard/associations", + selfService: true, + }, + ], +} + const reports: Service = { id: "reports", title: "Reports", @@ -485,6 +498,7 @@ const reports: Service = { /** Rail order: Overview, services with sections, then Account. */ export const services: Service[] = [ overview, + associations, people, telegram, whatsapp, @@ -553,6 +567,8 @@ export function matchPath(pathname: string): PageMatch { const [head, second, third, ...rest] = segments if (head === undefined) return { kind: "overview" } + if (head === "associations" && third === undefined) + return second ? { kind: "association-detail", id: second } : { kind: "association-portal" } if (head === "account" && second === undefined) return { kind: "account" } if (head === "account" && second === "me" && third === undefined && rest.length === 0) return { kind: "account-me" } @@ -647,6 +663,9 @@ export function matchPath(pathname: string): PageMatch { export function serviceFor(match: PageMatch): Service { switch (match.kind) { + case "association-portal": + case "association-detail": + return associations case "overview": case "not-found": return overview @@ -711,6 +730,9 @@ export function serviceFor(match: PageMatch): Service { /** The panel section a page belongs to. Deep pages return their parent section (see `isDeepPage`). */ export function sectionFor(match: PageMatch): Section | null { switch (match.kind) { + case "association-portal": + case "association-detail": + return section(associations, "portal") case "overview": case "not-found": return null @@ -797,6 +819,7 @@ export function sectionFor(match: PageMatch): Section | null { /** Deep pages are reached from a section but are not themselves in the panel. */ export function isDeepPage(match: PageMatch): boolean { return ( + match.kind === "association-detail" || match.kind === "telegram-user" || match.kind === "web-category" || match.kind === "web-tag" || diff --git a/src/features/association-portal/portal-detail.tsx b/src/features/association-portal/portal-detail.tsx new file mode 100644 index 00000000..f788f546 --- /dev/null +++ b/src/features/association-portal/portal-detail.tsx @@ -0,0 +1,676 @@ +import { Link, useRouteContext, useRouter } from "@tanstack/react-router" +import { useServerFn } from "@tanstack/react-start" +import { useState } from "react" + +import { + FormDialog, + FormField, + InlineAlert, + RecordHeader, + SegmentedControl, + SelectField, +} from "@/components/primitives" +import { appToast, PageBar, PageContent } from "@/components/shell" +import { Button } from "@/components/ui/button" +import { formatDate, formatDateTime } from "@/lib/format" + +import { eventLabel } from "./portal-events" +import { reviewPortalAssociation } from "./portal-review.functions" +import { + cleanProfile, + panelClass, + parseForm, + ProfileFields, + ProfilePreview, + ReasonDialog, + roleOptions, + statusLabel, + TextField, +} from "./portal-ui" +import { + commandSchema, + isOperatorAction, + type Command, + type Detail, + type Profile, + type Request, +} from "./portal.contract" +import { changePortalAssociation, getPortalDirectory } from "./portal.functions" + +type Action = Command extends infer T ? (T extends Command ? Omit : never) : never +export function PortalDetail({ association: a }: { association: Detail }) { + const router = useRouter() + const { user } = useRouteContext({ from: "/dashboard" }) + const change = useServerFn(changePortalAssociation) + const directory = useServerFn(getPortalDirectory) + const [destinations, setDestinations] = useState<{ id: string; name: string }[]>([]) + const [redirecting, setRedirecting] = useState(null) + const [destination, setDestination] = useState(null) + const [redirectReason, setRedirectReason] = useState("") + const review = useServerFn(reviewPortalAssociation) + const [tab, setTab] = useState<"profile" | "requests" | "members" | "activity">("profile") + const [edit, setEdit] = useState<{ requestId: string | null; profile: Profile; explanation: string } | null>(null) + const [reasonAction, setReasonAction] = useState<{ + title: string + description?: string + danger?: boolean + initial?: string + required?: boolean + action: (reason: string) => Action + } | null>(null) + const [inviting, setInviting] = useState(false) + const [email, setEmail] = useState("") + const [role, setRole] = useState<"responsible" | "collaborator">("collaborator") + const [explanation, setExplanation] = useState("") + const [notes, setNotes] = useState(a.notes ?? "") + const [syncedNotes, setSyncedNotes] = useState(a.notes ?? "") + // Another operator may have saved notes since this page loaded: follow the loader unless there are unsaved edits. + if ((a.notes ?? "") !== syncedNotes) { + if (notes === syncedNotes) setNotes(a.notes ?? "") + setSyncedNotes(a.notes ?? "") + } + const [busy, setBusy] = useState(false) + async function run(action: Action) { + const command = parseForm(commandSchema, { + ...action, + id: a.id, + revision: a.revision, + commandId: crypto.randomUUID(), + }) + if (isOperatorAction(action.action)) await review({ data: command }) + else await change({ data: command }) + try { + await router.invalidate({ sync: true }) + } catch (error) { + console.error(error) + appToast.warning( + "La modifica è salvata, ma la pagina non si è aggiornata. Ricaricala senza ripetere l’operazione." + ) + return + } + appToast.success("Modifica salvata.") + } + async function immediate(action: Action) { + if (busy) return + setBusy(true) + try { + await run(action) + } catch (error) { + console.error(error) + appToast.error(error instanceof Error ? error.message : "Operazione non riuscita") + } finally { + setBusy(false) + } + } + const working = a.requests.find((q) => q.kind === "content" && ["draft", "changes", "submitted"].includes(q.status)) + const registration = a.requests.find( + (q) => q.kind === "registration" && q.by === user.sub && ["draft", "changes"].includes(q.status) + ) + function askReview(q: Request, decision: "approve" | "changes" | "reject") { + setReasonAction({ + title: + decision === "approve" + ? `Approva ${statusLabel[q.kind].toLowerCase()}` + : decision === "changes" + ? "Richiedi integrazioni" + : "Rifiuta richiesta", + description: + q.kind === "registration" + ? "L’approvazione crea il collegamento al primo responsabile. La scheda non viene pubblicata." + : q.kind === "content" + ? "L’approvazione sostituisce la versione pubblicata con questa proposta." + : "Verifica la persona e il suo ruolo prima di concedere o cambiare l’accesso.", + danger: decision === "reject", + action: (reason) => ({ action: "review", requestId: q.id, decision, reason }), + }) + } + return ( + <> + + +
+ + {a.canEdit && (!working || working.status !== "submitted") && ( + + )} + {registration && ( + + )} + + } + /> + {a.unrepresented && a.registered && a.operator && ( +

+ Nessun responsabile attivo. Invita un referente o esamina una richiesta di accesso. +

+ )} + {a.status === "suspended" && ( +

+ La gestione è sospesa. Le richieste restano consultabili; contatta PoliNetwork per la riattivazione. +

+ )} +
+ +
+ {tab === "profile" && ( +
+
+

Sul sito

+ +
+
+

+ {working ? `Proposta · ${statusLabel[working.status]}` : "Dati nel registro"} +

+ + {working && ( + + )} +
+
+ )} + {tab === "requests" && ( +
+ {!a.requests.length &&

Non ci sono richieste.

} + {[...a.requests].reverse().map((q) => ( +
+
+

{statusLabel[q.kind]}

+ {statusLabel[q.status]} +
+

+ {q.byName} · {formatDate(new Date(q.createdAt))} +

+

{q.explanation}

+ {(q.kind === "membership" || q.kind === "access") && ( +

+ {q.targetName ?? q.email} · {statusLabel[q.role]} + {q.remove ? " · Rimozione richiesta" : ""} + {!q.accepted ? " · In attesa di accettazione" : " · Account confermato"} +

+ )} + {q.kind === "membership" && q.targetEmail && ( +

+ Invito inviato a {q.email} · accettato dall’account {q.targetEmail} +

+ )} + {q.kind === "membership" && + q.targetEmail && + q.targetEmail.toLowerCase() !== q.email.toLowerCase() && ( + + L’invito è stato accettato da un account con un indirizzo diverso da quello invitato. Verifica + l’identità prima di approvare. + + )} + {q.response && ( +
+

Risposta di PoliNetwork · {q.decidedBy}

+

{q.response}

+
+ )} + {q.profile && ( +
+ + {q.kind === "content" ? "Confronta versione pubblicata e proposta" : "Dati della richiesta"} + +
+ {q.kind === "content" && ( +
+

Pubblicata

+ +
+ )} +
+

Proposta

+ +
+
+
+ )} + {q.redirectId && ( + + Apri la richiesta sul record esistente + + )} +
+ {a.operator && q.kind === "registration" && q.status === "submitted" && ( + + )} + {a.operator && q.status === "submitted" && ( + <> + + + + + )} + {q.kind === "content" && a.canSubmit && q.status === "draft" && ( + + )} + {q.kind === "registration" && q.by === user.sub && ["draft", "changes"].includes(q.status) && ( + + )} + {q.status === "changes" && q.by === user.sub && ( + + )} + {q.kind === "content" && a.canSubmit && q.status === "changes" && ( + + )} + {["draft", "submitted", "changes"].includes(q.status) && + (q.by === user.sub || a.operator || (q.kind === "content" && a.canSubmit)) && ( + + )} +
+
+ ))} +
+ )} + {tab === "members" && ( +
+
+

Referenti autorizzati

+ {a.canManage && a.registered && } +
+

+ Ogni nuovo referente accetta con il proprio account; PoliNetwork approva poi il collegamento. I + collaboratori preparano le schede, i responsabili le inviano. +

+ {a.members + .filter((m) => m.active) + .map((m) => ( +
+
+

{m.name}

+

{statusLabel[m.role]}

+
+
+ {a.canManage && ( + <> + + + + )} + {a.operator && ( + + )} + {m.sub === user.sub && ( + + )} +
+
+ ))} +
+ )} + {tab === "activity" && ( +
+
+

Storico

+ {[...a.events].reverse().map((e) => ( +
+

{eventLabel(e.action)}

+

+ {e.actor} · {formatDateTime(new Date(e.at))} +

+ {e.detail &&

{e.detail}

} +
+ ))} +
+ {a.operator && ( +
+

Note riservate a PoliNetwork

+ + +
+ )} +
+ )} + {a.operator && a.registered && ( +
+

Gestione PoliNetwork

+
+ {a.status !== "active" && ( + + )} + {a.status === "active" && ( + <> + + + + )} + {a.published && ( + + )} + {a.status !== "archived" && ( + + )} +
+
+ )} +
+ {edit && ( + { + if (!open) setEdit(null) + }} + title="Modifica proposta" + description="La versione pubblicata resta invariata fino all’approvazione." + noun="scheda" + locale="it" + size="lg" + dirty + submitLabel="Salva bozza" + onSubmit={async () => { + await run({ + action: "save", + requestId: edit.requestId, + profile: cleanProfile(edit.profile), + explanation: edit.explanation, + }) + setEdit(null) + }} + > + setEdit({ ...edit, profile })} + /> + setEdit({ ...edit, explanation })} + multiline + /> + + )} + { + if (!open) setRedirecting(null) + }} + title="Associazione già nel registro" + description="La registrazione verrà chiusa e diventerà una richiesta di accesso al record esistente, da approvare separatamente." + noun="richiesta" + locale="it" + dirty={!!destination || !!redirectReason} + submitLabel="Trasferisci richiesta" + canSubmit={!!destination && !!redirectReason.trim()} + onSubmit={async () => { + if (!redirecting || !destination) return + await run({ + action: "redirect", + requestId: redirecting.id, + destinationId: destination, + reason: redirectReason, + }) + setRedirecting(null) + }} + > + + d.id !== a.id).map((d) => ({ value: d.id, label: d.name }))} + /> + + + + {reasonAction && ( + setReasonAction(null)} + onSubmit={(reason) => run(reasonAction.action(reason))} + /> + )} + { + await run({ action: "invite", email, role, explanation }) + setInviting(false) + }} + > + + + + + + +
+ + ) +} diff --git a/src/features/association-portal/portal-events.ts b/src/features/association-portal/portal-events.ts new file mode 100644 index 00000000..6416fabe --- /dev/null +++ b/src/features/association-portal/portal-events.ts @@ -0,0 +1,35 @@ +/** + * The backend records history events with fixed English labels (`service.ts` in the backend's associations module). + * The portal is in Italian, so known labels are translated here; an unknown one is shown as is rather than hidden. + */ +const eventLabels = new Map([ + ["Association registered by PoliNetwork", "Associazione registrata da PoliNetwork"], + ["Registration submitted", "Richiesta di registrazione inviata"], + ["Registration draft saved", "Bozza di registrazione salvata"], + ["Registration redirected", "Registrazione trasferita a un’associazione già nel registro"], + [ + "Access request received from an existing application", + "Richiesta di accesso ricevuta da una registrazione trasferita", + ], + ["Draft saved", "Bozza salvata"], + ["Requested information supplied", "Integrazioni inviate"], + ["Request submitted", "Richiesta inviata"], + ["Request withdrawn", "Richiesta ritirata"], + ["Request approved", "Richiesta approvata"], + ["Request changes", "Integrazioni richieste"], + ["Request rejected", "Richiesta respinta"], + ["Access requested", "Accesso richiesto"], + ["Representative change requested", "Modifica dei referenti richiesta"], + ["Invitation accepted; awaiting PoliNetwork", "Invito accettato, in attesa di PoliNetwork"], + ["Representative left", "Il referente ha lasciato l’associazione"], + ["Representative revoked", "Referente revocato"], + ["Association active", "Associazione riattivata"], + ["Association suspended", "Associazione sospesa"], + ["Association archived", "Associazione archiviata"], + ["Profile unpublished", "Scheda rimossa dal sito"], + ["Internal note updated", "Nota interna aggiornata"], +]) + +export function eventLabel(action: string) { + return eventLabels.get(action) ?? action +} diff --git a/src/features/association-portal/portal-index.tsx b/src/features/association-portal/portal-index.tsx new file mode 100644 index 00000000..a042fa9b --- /dev/null +++ b/src/features/association-portal/portal-index.tsx @@ -0,0 +1,249 @@ +import { Link, useRouter } from "@tanstack/react-router" +import { useServerFn } from "@tanstack/react-start" +import { UsersRound } from "lucide-react" +import { useState } from "react" +import type { z } from "zod" + +import { EmptyState, FormDialog, SegmentedControl } from "@/components/primitives" +import { appToast, PageBar, PageContent, Toolbar } from "@/components/shell" +import { Button } from "@/components/ui/button" + +import { + cleanProfile, + EMPTY_PROFILE, + panelClass, + parseForm, + ProfileFields, + ReasonDialog, + statusLabel, + TextField, +} from "./portal-ui" +import { createSchema, type dashboardSchema, type directorySchema } from "./portal.contract" +import { createPortalAssociation, changePortalAssociation } from "./portal.functions" + +export function PortalIndex({ + portal, + directory, +}: { + portal: z.infer + directory: z.infer +}) { + const router = useRouter() + const create = useServerFn(createPortalAssociation) + const change = useServerFn(changePortalAssociation) + const [view, setView] = useState<"registry" | "requests" | "directory">("registry") + const [query, setQuery] = useState("") + const [creating, setCreating] = useState(false) + const [profile, setProfile] = useState(EMPTY_PROFILE) + const [explanation, setExplanation] = useState("") + const [commandId, setCommandId] = useState(() => crypto.randomUUID()) + const [claim, setClaim] = useState<(typeof directory)[number] | null>(null) + async function reload() { + try { + await router.invalidate({ sync: true }) + } catch (error) { + console.error(error) + appToast.warning("Salvato. Non è stato possibile aggiornare la pagina: ricaricala.") + } + } + async function save(submit: boolean) { + const data = parseForm(createSchema, { profile: cleanProfile(profile), explanation, submit, commandId }) + const result = await create({ data }) + // The command is spent: a further save would be a new one, never a replay of this idempotency key. + setCommandId(crypto.randomUUID()) + await reload() + setCreating(false) + await router.navigate({ to: "/dashboard/associations/$id", params: { id: result.id } }) + } + const matches = (name: string) => name.toLocaleLowerCase().includes(query.toLocaleLowerCase()) + return ( + <> + } + right={ + + } + /> + +
+
+ r.status === "submitted").length, + }, + { value: "directory", label: "Richiedi accesso" }, + ]} + /> +
+ {view === "registry" && + (portal.associations.length ? ( +
+ {portal.associations + .filter((a) => matches(a.name)) + .map((a) => ( + +

{a.name}

+

+ {statusLabel[a.status]} · {a.published ? "Pubblicata" : "Non pubblicata"} + {a.role ? ` · ${statusLabel[a.role]}` : ""} +

+ {a.unrepresented && a.registered && portal.operator && ( +

Nessun responsabile attivo

+ )} + {!!a.pending &&

{a.pending} richieste in revisione

} + + ))} +
+ ) : ( + setView("directory")}> + Cerca nel registro + + } + /> + ))} + {view === "requests" && ( +
+ {portal.requests.length ? ( + portal.requests + .filter((r) => matches(r.associationName)) + .map((r) => ( + +

+ {r.associationName} · {statusLabel[r.kind]} +

+

+ {statusLabel[r.status]} · {r.byName} +

+ {r.response &&

{r.response}

} + + )) + ) : ( +

Non ci sono richieste.

+ )} +
+ )} + {view === "directory" && ( +
+

+ Richiedi il collegamento al record esistente. PoliNetwork verificherà il tuo ruolo prima di concedere + accesso. +

+ {directory + .filter((a) => matches(a.name)) + .map((a) => ( +
+ {a.name} + +
+ ))} + {!directory.length &&

Il registro non contiene ancora associazioni attive.

} +
+ )} +
+ save(true)} + footerStart={ + + } + > + + + + {claim && ( + setClaim(null)} + onSubmit={async (reason) => { + const result = await change({ + data: { + id: claim.id, + revision: claim.revision, + commandId: crypto.randomUUID(), + action: "access", + explanation: reason, + }, + }) + await reload() + await router.navigate({ to: "/dashboard/associations/$id", params: { id: result.id } }) + }} + /> + )} +
+ + ) +} diff --git a/src/features/association-portal/portal-review.functions.ts b/src/features/association-portal/portal-review.functions.ts new file mode 100644 index 00000000..e04689d1 --- /dev/null +++ b/src/features/association-portal/portal-review.functions.ts @@ -0,0 +1,11 @@ +import { createServerFn } from "@tanstack/react-start" + +import { webContentWriteMiddleware } from "@/server/auth.middleware" + +import { portalApi } from "./portal.api.server" +import { commandSchema } from "./portal.contract" + +export const reviewPortalAssociation = createServerFn({ method: "POST" }) + .middleware([webContentWriteMiddleware]) + .validator(commandSchema) + .handler(({ context, data }) => portalApi(context).command(data)) diff --git a/src/features/association-portal/portal-ui.tsx b/src/features/association-portal/portal-ui.tsx new file mode 100644 index 00000000..b7972aac --- /dev/null +++ b/src/features/association-portal/portal-ui.tsx @@ -0,0 +1,369 @@ +import { useServerFn } from "@tanstack/react-start" +import { useId, useState } from "react" +import type { z } from "zod" + +import { FileButton, FormDialog, FormField, SelectField, fieldControl } from "@/components/primitives" +import { Button } from "@/components/ui/button" +import { Input } from "@/components/ui/input" +import { Textarea } from "@/components/ui/textarea" + +import { LOGO_MAX_BYTES, type Profile } from "./portal.contract" +import { uploadPortalLogo } from "./portal.functions" + +export const EMPTY_PROFILE: Profile = { + name: "", + acronym: "", + descriptionIt: "", + descriptionEn: "", + email: "", + logo: null, + links: [], +} +export const roleOptions = [ + { value: "responsible", label: "Responsabile" }, + { value: "collaborator", label: "Collaboratore" }, +] as const +export const statusLabel = { + pending: "Da registrare", + active: "Attiva", + suspended: "Sospesa", + archived: "Archiviata", + draft: "Bozza", + submitted: "In revisione", + changes: "Integrazioni richieste", + approved: "Approvata", + rejected: "Rifiutata", + withdrawn: "Ritirata", + registration: "Registrazione", + access: "Accesso", + membership: "Referenti", + content: "Scheda pubblica", + responsible: "Responsabile", + collaborator: "Collaboratore", +} +export const platformLabel = { + website: "Sito web", + facebook: "Facebook", + instagram: "Instagram", + tiktok: "TikTok", + x: "X", + youtube: "YouTube", + telegram: "Telegram", + linkedin: "LinkedIn", + spotify: "Spotify", + twitch: "Twitch", + other: "Altro", +} satisfies Record +type Platform = Profile["links"][number]["platform"] +// SAFETY: `platformLabel` satisfies Record, so its keys are exactly the contract's platforms. +const platforms = Object.keys(platformLabel) as Platform[] + +/** Drops link rows the user added but left empty, so they don't fail validation. */ +export function cleanProfile(profile: Profile): Profile { + return { ...profile, links: profile.links.filter((link) => link.label.trim() || link.url.trim()) } +} + +const fieldLabel = new Map([ + ["name", "Nome ufficiale"], + ["acronym", "Acronimo"], + ["descriptionIt", "Descrizione italiana"], + ["descriptionEn", "Descrizione inglese"], + ["email", "Email"], + ["logo", "URL del logo"], + ["label", "Etichetta"], + ["url", "Indirizzo"], + ["platform", "Piattaforma"], + ["explanation", "Motivazione"], + ["reason", "Motivazione"], + ["note", "Note"], + ["token", "Invito"], +]) + +/** Parses user input and throws an Italian message naming the field, never the raw Zod issue list. */ +export function parseForm(schema: T, value: z.input): z.output { + const result = schema.safeParse(value) + if (result.success) return result.data + const issue = result.error.issues[0] + const path = issue?.path ?? [] + const linkAt = path.indexOf("links") + const linkIndex = linkAt >= 0 ? Number(path[linkAt + 1]) : Number.NaN + const key = String(path.at(-1) ?? "") + const label = fieldLabel.get(key) + const where = Number.isInteger(linkIndex) + ? `Collegamento ${linkIndex + 1}${label ? ` · ${label}` : ""}` + : (label ?? "Dati inseriti") + const problem = + issue?.code === "too_big" + ? "è troppo lungo" + : issue?.code === "too_small" + ? "è obbligatorio" + : key === "email" + ? "non è un indirizzo email valido" + : key === "url" || key === "logo" + ? "deve essere un indirizzo HTTP o HTTPS valido" + : "non è valido" + throw new Error(`${where} ${problem}.`) +} + +export const panelClass = "rounded-xl border border-(--pn-line) bg-(--pn-surface) p-5 space-y-4" + +export function TextField({ + label, + value, + onChange, + multiline = false, + hint, + type = "text", + maxLength = 20000, +}: { + label: string + value: string + onChange: (value: string) => void + multiline?: boolean + hint?: string + type?: string + maxLength?: number +}) { + const id = useId() + return ( + + {multiline ? ( +