From 83bd440afbbcfdc15b626963b93087d001bd25bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriele=20Vigan=C3=B2?= Date: Tue, 17 Nov 2026 15:41:49 +0100 Subject: [PATCH 1/6] feat(associations): add personal association portal and staff review --- src/components/shell/nav.ts | 30 + .../association-portal/portal-detail.tsx | 633 ++++++++++++++++++ .../association-portal/portal-index.tsx | 237 +++++++ .../portal-review.functions.ts | 11 + src/features/association-portal/portal-ui.tsx | 314 +++++++++ .../association-portal/portal.api.server.ts | 25 + .../association-portal/portal.contract.ts | 151 +++++ .../association-portal/portal.functions.ts | 43 ++ src/routes/associations/invite.tsx | 87 +++ src/routes/dashboard.tsx | 2 +- src/routes/dashboard/associations/$id.tsx | 13 + src/routes/dashboard/associations/index.tsx | 12 + src/routes/dashboard/web/associations.tsx | 25 +- src/server/auth.middleware.ts | 5 + src/server/auth.server.ts | 22 +- tests/server-security.test.mjs | 8 + 16 files changed, 1578 insertions(+), 40 deletions(-) create mode 100644 src/features/association-portal/portal-detail.tsx create mode 100644 src/features/association-portal/portal-index.tsx create mode 100644 src/features/association-portal/portal-review.functions.ts create mode 100644 src/features/association-portal/portal-ui.tsx create mode 100644 src/features/association-portal/portal.api.server.ts create mode 100644 src/features/association-portal/portal.contract.ts create mode 100644 src/features/association-portal/portal.functions.ts create mode 100644 src/routes/associations/invite.tsx create mode 100644 src/routes/dashboard/associations/$id.tsx create mode 100644 src/routes/dashboard/associations/index.tsx diff --git a/src/components/shell/nav.ts b/src/components/shell/nav.ts index 269caea7..d1ba5eab 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" } @@ -456,6 +459,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 +505,7 @@ const reports: Service = { /** Rail order: Overview, services with sections, then Account. */ export const services: Service[] = [ overview, + associations, people, telegram, whatsapp, @@ -553,6 +574,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 +670,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 +737,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 +826,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..b6b1ad49 --- /dev/null +++ b/src/features/association-portal/portal-detail.tsx @@ -0,0 +1,633 @@ +import { Link, useRouteContext, useRouter } from "@tanstack/react-router" +import { useServerFn } from "@tanstack/react-start" +import { useState } from "react" + +import { FormDialog, FormField, RecordHeader, SegmentedControl, SelectField } from "@/components/primitives" +import { appToast, PageBar, PageContent } from "@/components/shell" +import { Button } from "@/components/ui/button" + +import { reviewPortalAssociation } from "./portal-review.functions" +import { + panelClass, + ProfileFields, + ProfilePreview, + ReasonDialog, + roleOptions, + statusLabel, + TextField, +} from "./portal-ui" +import { profileSchema, 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 + 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 [busy, setBusy] = useState(false) + async function run(action: Action) { + const command = { ...action, id: a.id, revision: a.revision, commandId: crypto.randomUUID() } as Command + if (["redirect", "review", "status", "unpublish", "note", "revoke"].includes(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} · {new Date(q.createdAt).toLocaleDateString("it-IT")} +

+

{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.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 && q.status === "draft" && ( + + )} + {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) => ( +
+

{e.action}

+

+ {e.actor} · {new Date(e.at).toLocaleString("it-IT")} +

+ {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: profileSchema.parse(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-index.tsx b/src/features/association-portal/portal-index.tsx new file mode 100644 index 00000000..47e5afaa --- /dev/null +++ b/src/features/association-portal/portal-index.tsx @@ -0,0 +1,237 @@ +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 { EMPTY_PROFILE, panelClass, ProfileFields, ReasonDialog, statusLabel, TextField } from "./portal-ui" +import { profileSchema, 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 result = await create({ data: { profile: profileSchema.parse(profile), explanation, submit, commandId } }) + 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..eff6e449 --- /dev/null +++ b/src/features/association-portal/portal-ui.tsx @@ -0,0 +1,314 @@ +import { useServerFn } from "@tanstack/react-start" +import { useId, useState } from "react" + +import { 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 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: Record = { + 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 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 ? ( +