From 80a297ad7925ca13e8d71d10fc96f9eae6e0ebf0 Mon Sep 17 00:00:00 2001 From: Bianca Date: Fri, 20 Nov 2026 11:25:36 +0100 Subject: [PATCH 1/5] docs(people): record socio lifecycle implementation and next steps --- docs/people/plan.md | 68 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/docs/people/plan.md b/docs/people/plan.md index 059f686..dfd1d5f 100644 --- a/docs/people/plan.md +++ b/docs/people/plan.md @@ -150,6 +150,59 @@ The design is agreed (9 November 2026). Each item is an issue under #144, in ord - [ ] Admin: End status, Restore, Soci › Deletion pending; remove the mockups and `mockup-data.ts` - [ ] Production: register the existing soci, mark the 2026/27 payments, then switch on `SOCI_AUTO_LAPSE` +### Next implementation: socio lifecycle (#124 / #157) + +Planning checkpoint, 19 November 2026. The live GitHub issues are the status source: backend #123 and #125 and admin +#156 are completed; backend #124 and admin #157 remain open. The older checklist above does not establish whether +production configuration or existing-member registration is complete. The existing rules in `soci.md` still apply. + +The first implementation slice is manual ending and restore in the backend, implemented on 19 November 2026 and +submitted for review in [backend #151](https://github.com/PoliNetworkOrg/backend/pull/151) on 20 November. The remaining +slices below are pending. Production activation is a separate operation. + +1. **Manual lifecycle API — backend #124.** Add `soci.members.end` and `restore` to the existing contract, service and + router. Reuse `endedOn`, `endReason`, `endNote`, `accountState`, the activity history, the current member-write + serialization, and the idempotent directory operations. Ending removes Soci membership and records + `pending_deletion`; it does not delete the account. Restore requires a reason, an existing account and no other + active record with the same codice fiscale, re-adds Soci membership and clears the end. The actions take effect + when confirmed; scheduled resignations are outside this scope. Keep `soci:write` and the existing admin policy. + Verify permission denials, repeated requests, conflicting active records, history, directory errors and persistence + failures. If a directory write fails, do not record success. If persistence fails after a reversible group change, + compensate the directory change and surface/log a failed compensation as a mismatch, using the existing failure + handling pattern. + **Implemented in backend #151, pending review:** the manual reasons exclude `lapsed`, restore needs a nonblank reason and an existing + account, and duplicate or conflicting requests fail without adding another history entry. The existing PostgreSQL + transaction stores the status and history together. Compensation preserves the membership observed before the + operation, including existing mismatches. No schema or dependency change was needed. The copied admin contract + and dashboard actions remain part of slice 4. +2. **Preview and automatic lapse — backend #124, after the manual transitions.** Add `soci.lapse.preview` under + `soci:read` and a daily lapse job guarded by `SOCI_AUTO_LAPSE`, default false. From 1 January, evaluate the fee year + whose renewal deadline has passed: only active records with a Due fee lapse, with the previous 31 December as + their end date. Uploaded receipts awaiting review, Paid and Exempt fees are protected. Reuse the ending operation + and enqueue one Italian lapse email in the existing outbox, using the approved email design. Verify the disabled + switch, deadline boundaries, pending review, rejection after the deadline, repeated runs, mail deduplication and + Graph failure followed by retry. Do not infer non-payment from a missing register entry or missing fee row. +3. **Deletion API — backend #124, after ending.** Add `soci.accounts.pendingDeletion` under `soci:read` and + `accounts.delete` under `soci:delete`. Accept one pending account per call; refuse active accounts. Keep the register, + historical numbers, mailbox snapshot and deletion date. Directory deletion is idempotent: retrying after Graph + succeeded but persistence failed must be able to finish the bookkeeping. No bulk deletion. Verify permissions, + wrong-state refusals, an already missing directory user and persistence retries. +4. **Dashboard — admin #157, against the completed backend contract.** Update the copied contract, API/server + functions, permission checks and agent-mode fixtures. Add End status / Restore to the socio page, Deletion pending + with a count and per-account deletion confirmation naming the mailbox, and the lapse preview in Register when + automatic lapse is enabled. Use the existing form/confirmation primitives and preserve the current layout. + Test unauthorized roles, loading/error/empty states, mutation success followed by a failed reload, and sample + pending/deleted accounts. Run the repository checks and inspect mobile/desktop, light/dark. + +Backend verification uses the existing Vitest service, router, in-memory directory and PostgreSQL fixture patterns; +run typecheck, Biome, tests and build with the Bun lockfile. Admin verification uses its existing pnpm commands. +No new dependency or infrastructure is planned. No schema migration is expected for the existing lifecycle fields; +verify transactional state/history/outbox writes while implementing the store changes. + +Production activation is a separate operation: populate and review the register, reconcile existing payments, review +`lapse.preview`, and only then explicitly enable automatic lapse. Real account deletion is never part of development +verification. + ## Progress log Newest last. One line per commit or session: date, what was done, what is next. @@ -243,3 +296,18 @@ Newest last. One line per commit or session: date, what was done, what is next. shell: sign in, "Link this account to ?", confirm, then the roles as they arrive (applied, waiting, refused with Auth's reason), or "being applied" while the account can't read My area yet. The old My area invite link redirects there, and My area no longer accepts invites. + +- 2026-11-19: inspected the remaining lifecycle issues and existing directory/schema support; recorded the next + backend and dashboard implementation slices above. No production code or production configuration changed. +- 2026-11-19: implemented manual ending and restore locally in the backend (#124), with permission, input, concurrent + request, Microsoft 365 failure, compensation and PostgreSQL transaction coverage. Typecheck, Biome and build pass + with a frozen Bun installation. The full suite has 393 passing tests, 2 skipped and one pre-existing Secret Santa + failure (`tests/secret-santa-email.test.ts:61`, HTTP 401 instead of 413), reproduced on the unchanged HEAD in an + isolated copy. Microsoft 365 was mocked; PostgreSQL used a disposable local container and synthetic data. No Git + publication, deployment, real account changes or email delivery. Next: lapse preview and the disabled automatic + lapse job (slice 2); dashboard wiring follows the completed backend contract. +- 2026-11-20: prepared the manual lifecycle change for review in backend #151 on the current `main`. The full backend + suite with disposable PostgreSQL 18 passes: 446 tests passed, 3 skipped; typecheck, Biome and build also pass. The + Secret Santa failure recorded above does not reproduce on the current `main`, which already includes its fix. + No production accounts, data or configuration were changed. The next implementation slice remains lapse preview + and the automatic lapse job, disabled by default. From 3cf7aa76a01cc1ebbbef9d9d0a6325fb1d484a82 Mon Sep 17 00:00:00 2001 From: Bianca Date: Fri, 20 Nov 2026 12:07:04 +0100 Subject: [PATCH 2/5] feat(soci): connect lifecycle actions and pending deletion --- AGENTS.md | 3 + docs/people/plan.md | 26 +++- src/components/shell/nav.ts | 16 +++ src/features/soci/deletion-page.tsx | 121 ++++++++++++++++ src/features/soci/fee-dialogs.tsx | 2 +- src/features/soci/lapse-warning.tsx | 34 +++++ src/features/soci/lifecycle-dialogs.tsx | 154 +++++++++++++++++++++ src/features/soci/register-page.tsx | 13 +- src/features/soci/soci-delete.functions.ts | 11 ++ src/features/soci/soci-write.functions.ts | 12 ++ src/features/soci/soci.api.server.ts | 17 +++ src/features/soci/soci.contract.ts | 34 +++++ src/features/soci/soci.fake.server.ts | 79 ++++++++++- src/features/soci/soci.functions.ts | 13 +- src/features/soci/socio-page.tsx | 31 +++++ src/routeTree.gen.ts | 21 +++ src/routes/dashboard.tsx | 9 +- src/routes/dashboard/people/deletion.tsx | 19 +++ src/routes/dashboard/people/soci/index.tsx | 4 +- src/server/auth.middleware.ts | 8 ++ src/server/permissions.ts | 1 + tests/people-navigation.test.mjs | 18 +++ tests/server-security.test.mjs | 6 +- tests/soci.test.mjs | 16 +++ 24 files changed, 658 insertions(+), 10 deletions(-) create mode 100644 src/features/soci/deletion-page.tsx create mode 100644 src/features/soci/lapse-warning.tsx create mode 100644 src/features/soci/lifecycle-dialogs.tsx create mode 100644 src/features/soci/soci-delete.functions.ts create mode 100644 src/routes/dashboard/people/deletion.tsx diff --git a/AGENTS.md b/AGENTS.md index 326fb31..dc7d37f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,6 +39,9 @@ What the app is and how to run it: [`README.md`](README.md). UI rules: [`docs/de Members. Soci › Fees reviews uploaded transfer receipts (Confirm, Reject) and marks fees as paid, also from the socio page. My area's Socio card (`soci.me.*`, `people:self`, `soci-self.functions.ts`) shows the signed-in socio's fee, bank details, Upload transfer receipt and Complete your details; a socio without a People record sees only that card. + End status and Restore require `soci:write`. Deletion pending and its count require `soci:read`; permanent account + deletion uses `sociDeleteMiddleware` and `soci:delete`, one mailbox per confirmation. Confirmed changes cannot be + repeated when only the following reload failed. Register shows the backend lapse preview when enabled. `AGENT_SOCIO` picks the socio My area shows in agent mode. Design: `docs/people/soci.md`. - **Regolamenti** (`src/features/regulations/`): the governance documents (v1: the RRI), through `regulationsApi(context)`, which parses the backend's `regulations.*` responses with `regulations.contract.ts` (a copy diff --git a/docs/people/plan.md b/docs/people/plan.md index dfd1d5f..85dc0d7 100644 --- a/docs/people/plan.md +++ b/docs/people/plan.md @@ -158,7 +158,8 @@ production configuration or existing-member registration is complete. The existi The first implementation slice is manual ending and restore in the backend, implemented on 19 November 2026 and submitted for review in [backend #151](https://github.com/PoliNetworkOrg/backend/pull/151) on 20 November. The remaining -slices below are pending. Production activation is a separate operation. +slices below are also implemented for review in backend #151 and admin #169 as of 20 November. Production +activation is a separate operation. 1. **Manual lifecycle API — backend #124.** Add `soci.members.end` and `restore` to the existing contract, service and router. Reuse `endedOn`, `endReason`, `endNote`, `accountState`, the activity history, the current member-write @@ -182,17 +183,26 @@ slices below are pending. Production activation is a separate operation. and enqueue one Italian lapse email in the existing outbox, using the approved email design. Verify the disabled switch, deadline boundaries, pending review, rejection after the deadline, repeated runs, mail deduplication and Graph failure followed by retry. Do not infer non-payment from a missing register entry or missing fee row. + **Implemented locally:** the job evaluates the most recent renewal deadline; preview evaluates 1 January during + December. Receipts, payments and lifecycle writes share the existing lock. Status, history and the Italian lapse + email commit in one transaction. The configuration remains false by default; no production activation. 3. **Deletion API — backend #124, after ending.** Add `soci.accounts.pendingDeletion` under `soci:read` and `accounts.delete` under `soci:delete`. Accept one pending account per call; refuse active accounts. Keep the register, historical numbers, mailbox snapshot and deletion date. Directory deletion is idempotent: retrying after Graph succeeded but persistence failed must be able to finish the bookkeeping. No bulk deletion. Verify permissions, wrong-state refusals, an already missing directory user and persistence retries. + **Implemented locally:** the list reads the register, deletion accepts one pending object ID, and retrying after + directory success can finish a failed database update. The account snapshot, fees and number history remain. 4. **Dashboard — admin #157, against the completed backend contract.** Update the copied contract, API/server functions, permission checks and agent-mode fixtures. Add End status / Restore to the socio page, Deletion pending with a count and per-account deletion confirmation naming the mailbox, and the lapse preview in Register when automatic lapse is enabled. Use the existing form/confirmation primitives and preserve the current layout. Test unauthorized roles, loading/error/empty states, mutation success followed by a failed reload, and sample pending/deleted accounts. Run the repository checks and inspect mobile/desktop, light/dark. + **Implemented locally:** End status and Restore on the socio record; Deletion pending with a sidebar count, + search and a per-account confirmation naming its mailbox; December lapse preview; scoped server functions and + agent fixtures. Confirmed changes remain non-repeatable if reload fails. Browser checks cover desktop/light + mutations, required reasons, keyboard focus after deletion, failed reloads and mobile/dark read-only access. Backend verification uses the existing Vitest service, router, in-memory directory and PostgreSQL fixture patterns; run typecheck, Biome, tests and build with the Bun lockfile. Admin verification uses its existing pnpm commands. @@ -311,3 +321,17 @@ Newest last. One line per commit or session: date, what was done, what is next. Secret Santa failure recorded above does not reproduce on the current `main`, which already includes its fix. No production accounts, data or configuration were changed. The next implementation slice remains lapse preview and the automatic lapse job, disabled by default. + +- 2026-11-20: implemented the remaining lifecycle slices locally in the isolated backend/admin worktrees. Backend: + guarded lapse preview/job, atomic Italian lapse mail, serialized receipt/payment/lifecycle writes, and single-account + pending deletion. Dashboard: lifecycle dialogs, pending-deletion page and count, permission gates, lapse preview and + matching agent fixtures. Backend full suite: 461 passed, 3 skipped, including disposable PostgreSQL 18. Browser + checks passed for end/restore/delete, correction validation, focus recovery, confirmed mutations with failed reloads, + and mobile/dark read-only permissions and layout. No real mail, account changes or production activation; + `SOCI_AUTO_LAPSE` remains false by default. + +- 2026-11-20: prepared the complete lifecycle implementation for publication in backend #151 and admin #169. Backend + verification: 461 passed, 3 skipped, typecheck, Biome and build. Dashboard verification: 209 passed, 4 skipped, check, + typecheck, build and browser flows. The next rollout step requires review of both PRs and a production-readiness + check of the register/payments before any activation. Merge, deployment, production reads and account mutations + remain separate operations. diff --git a/src/components/shell/nav.ts b/src/components/shell/nav.ts index 269caea..caec5bf 100644 --- a/src/components/shell/nav.ts +++ b/src/components/shell/nav.ts @@ -122,6 +122,7 @@ export type PageMatch = | { kind: "people-soci" } | { kind: "people-socio"; number: number } | { kind: "people-fees" } + | { kind: "people-deletion" } | { kind: "people-admins" } | { kind: "people-teams" } | { kind: "people-team"; teamId: string } @@ -263,6 +264,15 @@ const people: Service = { group: "Soci", searchPlaceholder: "Search by name, number or mailbox…", }, + { + id: "deletion", + title: "Deletion pending", + icon: UserRound, + path: "/dashboard/people/deletion", + permission: "soci:read", + group: "Soci", + searchPlaceholder: "Search by name, number or mailbox…", + }, ], } @@ -573,6 +583,7 @@ export function matchPath(pathname: string): PageMatch { if (second === undefined) return { kind: "people-overview" } if (third === undefined) { if (second === "soci") return { kind: "people-soci" } + if (second === "deletion") return { kind: "people-deletion" } if (second === "fees") return { kind: "people-fees" } if (second === "admins") return { kind: "people-admins" } if (second === "teams") return { kind: "people-teams" } @@ -658,6 +669,7 @@ export function serviceFor(match: PageMatch): Service { case "people-soci": case "people-socio": case "people-fees": + case "people-deletion": case "people-admins": case "people-teams": case "people-team": @@ -726,6 +738,8 @@ export function sectionFor(match: PageMatch): Section | null { return section(people, "soci") case "people-fees": return section(people, "fees") + case "people-deletion": + return section(people, "deletion") case "people-admins": return section(people, "admins") case "people-teams": @@ -831,6 +845,7 @@ export type PendingCounts = { reports: Promise signatures: Promise fees: Promise + deletion: Promise } const NO_COUNT: Promise = Promise.resolve(null) @@ -853,6 +868,7 @@ export function sectionPending( ): Promise { if (serviceId === "reports" && sectionId === "open") return pending.reports if (serviceId === "esign" && sectionId === "inbox") return pending.signatures + if (serviceId === "people" && sectionId === "deletion") return pending.deletion if (serviceId === "people" && sectionId === "fees") return pending.fees return NO_COUNT } diff --git a/src/features/soci/deletion-page.tsx b/src/features/soci/deletion-page.tsx new file mode 100644 index 0000000..b1f0bb9 --- /dev/null +++ b/src/features/soci/deletion-page.tsx @@ -0,0 +1,121 @@ +import { Trash2 } from "lucide-react" +import { useDeferredValue, useState } from "react" + +import { DataTable, type DataTableColumn, EmptyState, IconButton, useFocusAfterRemoval } from "@/components/primitives" +import { Count, PageBar, PageContent, Toolbar, useCan } from "@/components/shell" +import { formatDay } from "@/features/people/people-format" +import { useDialog } from "@/features/people/people-hooks" + +import { DeleteAccountDialog } from "./lifecycle-dialogs" +import { END_REASON, formatMemberNumber, socioName } from "./soci-format" +import type { SocioRow } from "./soci.contract" + +const columns: DataTableColumn[] = [ + { + id: "name", + label: "Name", + fill: true, + mobile: "main", + cell: (s) => ( + <> + {socioName(s)} + + {formatMemberNumber(s.number)} · {s.mailbox} + + + {s.endedOn ? formatDay(s.endedOn) : "—"} · {s.endReason ? END_REASON[s.endReason] : "—"} + + + ), + }, + { + id: "endedOn", + label: "Ended on", + width: 150, + mobile: "hidden", + cell: (s) => (s.endedOn ? formatDay(s.endedOn) : "—"), + }, + { + id: "reason", + label: "Reason", + width: 140, + mobile: "hidden", + cell: (s) => (s.endReason ? END_REASON[s.endReason] : "—"), + }, +] + +export function DeletionPage({ accounts }: { accounts: SocioRow[] }) { + const canDelete = useCan("soci:delete") + const dialog = useDialog() + const focus = useFocusAfterRemoval("tbody tr") + const [query, setQuery] = useState("") + const [deleted, setDeleted] = useState>(() => new Set()) + const search = useDeferredValue(query.trim().toLocaleLowerCase()) + const pending = accounts.filter((s) => !deleted.has(s.entraObjectId)) + const rows = pending.filter((s) => + [socioName(s), s.mailbox, String(s.number), formatMemberNumber(s.number)].some((v) => + v.toLocaleLowerCase().includes(search) + ) + ) + return ( + <> + } + /> + } + /> + +
+ s.number} + rowHref={(s) => `/dashboard/people/soci/${s.number}`} + rowLabel={(s) => socioName(s)} + actions={ + canDelete + ? (s) => ( + { + focus.capture(event.currentTarget) + dialog.show(s) + }} + /> + ) + : undefined + } + empty={ + + } + /> +
+
+ {canDelete && dialog.target ? ( + setDeleted((current) => new Set([...current, id]))} + /> + ) : null} + + ) +} diff --git a/src/features/soci/fee-dialogs.tsx b/src/features/soci/fee-dialogs.tsx index 416f5ca..244cb35 100644 --- a/src/features/soci/fee-dialogs.tsx +++ b/src/features/soci/fee-dialogs.tsx @@ -131,7 +131,7 @@ export function ReviewFeeDialog({ open, onOpenChange, socio, fee }: DialogProps rejecting && late ? ( The renewal deadline, {formatDay(renewalDeadline(fee.year))}, has passed: once rejected, the fee is Due - again and {name} lapses at the next daily run unless it's paid. + again. If automatic lapse is enabled, {name} lapses at the next daily run unless it's paid. ) : undefined } diff --git a/src/features/soci/lapse-warning.tsx b/src/features/soci/lapse-warning.tsx new file mode 100644 index 0000000..0396c39 --- /dev/null +++ b/src/features/soci/lapse-warning.tsx @@ -0,0 +1,34 @@ +import { Link } from "@tanstack/react-router" + +import { InlineAlert } from "@/components/primitives" +import { formatDay } from "@/features/people/people-format" + +import { socioName } from "./soci-format" +import type { LapsePreview } from "./soci.contract" + +export function LapseWarning({ preview }: { preview: LapsePreview }) { + if (!preview.enabled || !preview.members.length) return null + return ( + +
+ + {preview.members.length} soci would lapse in the preview for {formatDay(preview.evaluatedOn)} if their fees + remain unpaid. + +
    + {preview.members.map((s) => ( +
  • + + {socioName(s)} + + {" · "} + {s.mailbox} + {" · end date: "} + {formatDay(s.endedOn)} +
  • + ))} +
+
+
+ ) +} diff --git a/src/features/soci/lifecycle-dialogs.tsx b/src/features/soci/lifecycle-dialogs.tsx new file mode 100644 index 0000000..920b192 --- /dev/null +++ b/src/features/soci/lifecycle-dialogs.tsx @@ -0,0 +1,154 @@ +import { useServerFn } from "@tanstack/react-start" +import { Ban } from "lucide-react" +import { useState } from "react" + +import { + ConfirmDialog, + DateField, + fieldControl, + fieldHintId, + FormDialog, + FormField, + InlineAlert, + SelectField, +} from "@/components/primitives" +import { Textarea } from "@/components/ui/textarea" +import { todayIso } from "@/features/people/people-format" +import { useRefreshAfter } from "@/features/people/people-hooks" +import { cn } from "@/lib/utils" + +import { deleteSocioAccount } from "./soci-delete.functions" +import { END_REASON, socioName } from "./soci-format" +import { endSocio, restoreSocio } from "./soci-write.functions" +import { endInputSchema, restoreInputSchema, type EndInput, type SocioRow } from "./soci.contract" + +type Props = { open: boolean; onOpenChange: (open: boolean) => void; socio: SocioRow } +const REASONS = ["resigned", "expelled", "deceased", "other"] as const + +export function MembershipStatusDialog({ open, onOpenChange, socio, onChanged }: Props & { onChanged: () => void }) { + const end = useServerFn(endSocio) + const restore = useServerFn(restoreSocio) + const refresh = useRefreshAfter() + const restoring = !!socio.endedOn + const [endedOn, setEndedOn] = useState(todayIso()) + const [endReason, setEndReason] = useState(null) + const [note, setNote] = useState("") + const [errors, setErrors] = useState>({}) + + async function submit() { + const parsed = restoring + ? restoreInputSchema.safeParse({ number: socio.number, reason: note }) + : endInputSchema.safeParse({ number: socio.number, endedOn, endReason, endNote: note }) + if (!parsed.success) { + setErrors(Object.fromEntries(parsed.error.issues.map((issue) => [String(issue.path[0]), issue.message]))) + return + } + if ("reason" in parsed.data) await restore({ data: parsed.data }) + else await end({ data: parsed.data }) + onChanged() + await refresh(restoring ? "Membership restored." : "Membership ended. The account is pending deletion.") + onOpenChange(false) + } + + return ( + + + {restoring + ? "Use Restore only to correct a mistake. The account will regain the Socio role. Unpaid fees remain due and may end the membership again if automatic lapse is enabled." + : "The account loses the Socio role immediately and becomes pending deletion. The account itself is kept."} + + {!restoring ? ( + <> + + { + setEndedOn(value) + setErrors((current) => ({ ...current, endedOn: "" })) + }} + invalid={!!errors.endedOn} + describedBy={errors.endedOn ? fieldHintId("membership-ended-on") : undefined} + /> + + + { + setEndReason(value) + setErrors((current) => ({ ...current, endReason: "" })) + }} + options={REASONS.map((value) => ({ value, label: END_REASON[value] }))} + placeholder="Choose a reason" + invalid={!!errors.endReason} + describedBy={errors.endReason ? fieldHintId("membership-end-reason") : undefined} + /> + + + ) : null} + +