Files
hackerspace.sh/scripts/019_proposal_expiry.sql
T
Moheeb Zara ea8d7a5f91 feat: governance kernel, deployment hardening, local-dev stack
Adds proposals + proposal_votes + policies + incidents + incident_updates
tables with full RLS, async voting flow, dismissal-appeal pathway,
versioned policies with provenance, and an anonymous-incident token mode.
Adds per-space configurable areas, financial visibility settings, member
self-profile + COI disclosure, and a mission statement that renders in
the app footer.

Reorganises lib/actions.ts into per-domain files (tasks, projects,
members, payments, contacts, knowledge-base, secrets, area-leads,
settings, imports, proposals, incidents, policies, areas) plus a barrel.
Adds lib/permissions.ts and lib/auth-helpers.ts so action bodies stop
duplicating the user-to-member-to-role check. Wires every action that has
a Zod schema; introduces a flexibleDateTime preprocessor so HTML date
pickers no longer hit "Invalid datetime".

Hardens RLS: drops NOT NULL on space_members.user_id for offline members,
adds a privilege-escalation trigger that blocks self-edits to role / tier
/ status / approved / has_card_access / space_id, closes four
cross-tenant holes in the governance kernel, and adds a partial unique
index so two admins cannot concurrently activate two drafts of the same
policy slug.

Ships every deployment artifact: Dockerfile, docker-compose,
.do/app.yaml, .env.example, /api/health, plus a managed-Supabase guide
(docs/DEPLOYMENT.md), an end-to-end self-hosted Droplet guide
(docs/DEPLOY_DO_SELFHOSTED.md), and a Supabase-CLI local-dev quickstart
(docs/LOCAL_DEV.md). Replaces middleware.ts with proxy.ts for Next.js 16.
Adds scripts/schema.sql as the canonical idempotent full deploy plus
fourteen numbered incremental migrations.

Adds scripts/seed.sql so a fresh local DB renders something instead of
empty pages: a demo space, five members across all roles, a v1 code of
conduct, three proposals in different states with seven votes already
cast, an open incident, a project, three tasks, a KB entry, and matching
activity-log rows.

Replaces v0-generated test scaffolding with 266 real tests across
__tests__/{actions,auth-helpers,components,governance,permissions,
security,utils,validations}.test.ts. Adds react-markdown + remark-gfm
for proposal / incident / policy body rendering. Deletes four dead v0
fix-* scripts, the unused components/app-shell.tsx, and the duplicate
app/auth/login/page.tsx.

Routes (31 total): /api/health, /api/paypal/sync, /auth/callback, /,
/login, /signup, /signup/confirm, /dashboard, /tasks, /projects,
/members, /payments, /financials, /contacts, /ops, /ops/[id], /ops/new,
/proposals, /proposals/[id], /proposals/new, /incidents, /incidents/[id],
/incidents/new, /policies, /policies/[slug], /policies/new, /profile,
/recruitment, /settings, /comms, /import.

Full pass-by-pass history is in docs/HANDOFF.md; the roadmap is in
docs/GOVERNANCE_FEATURES.md.
2026-05-14 04:52:11 -07:00

84 lines
3.0 KiB
PL/PgSQL

-- =============================================================================
-- 019: Auto-expire open proposals whose voting window has closed
-- =============================================================================
-- Pass 5's open item: when `voting_closes_at < now()` on an `open` proposal,
-- nothing flips the status. Admins have to click "Mark decided" manually.
--
-- This migration adds two pieces:
--
-- 1. A SECURITY DEFINER function `public.expire_proposals()` that finds
-- every open proposal with a passed deadline and updates it:
-- - If quorum is met, status becomes 'decided' and decided_at = now()
-- (the trigger has already computed `passed`, so the result is final).
-- - If quorum is NOT met, status becomes 'expired'.
-- Returns the number of proposals it touched, so callers can monitor.
--
-- 2. An "on-read" optimisation: nothing here yet, deliberately. Polling
-- `SELECT public.expire_proposals()` on a schedule is the recommended
-- pattern. From a Next.js cron job, from pg_cron on Supabase, or from
-- a /api/cron route guarded by a CRON_SECRET header.
--
-- Safe to re-run: CREATE OR REPLACE FUNCTION.
-- =============================================================================
CREATE OR REPLACE FUNCTION public.expire_proposals()
RETURNS integer
LANGUAGE plpgsql SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
v_decided integer;
v_expired integer;
BEGIN
-- Quorum met -> decide.
WITH updated AS (
UPDATE public.proposals
SET status = 'decided',
decided_at = now()
WHERE status = 'open'
AND voting_closes_at IS NOT NULL
AND voting_closes_at < now()
AND quorum_met = true
RETURNING 1
)
SELECT count(*) INTO v_decided FROM updated;
-- Quorum not met -> expire.
WITH updated AS (
UPDATE public.proposals
SET status = 'expired'
WHERE status = 'open'
AND voting_closes_at IS NOT NULL
AND voting_closes_at < now()
AND COALESCE(quorum_met, false) = false
RETURNING 1
)
SELECT count(*) INTO v_expired FROM updated;
RETURN v_decided + v_expired;
END;
$$;
-- Optional: schedule with pg_cron if available. Self-hosted Supabase enables
-- the extension by default; managed Supabase requires the user to enable it
-- from Database → Extensions. The DO block below is best-effort and fails
-- silently when pg_cron is not present.
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_cron') THEN
-- Unschedule any prior job with the same name (idempotent).
PERFORM cron.unschedule(jobid)
FROM cron.job
WHERE jobname = 'expire-proposals-hourly';
PERFORM cron.schedule(
'expire-proposals-hourly',
'0 * * * *',
$cron$SELECT public.expire_proposals();$cron$
);
END IF;
EXCEPTION WHEN OTHERS THEN
-- pg_cron not installed or insufficient privileges. The function still
-- exists; the operator can run it on whatever schedule they want.
NULL;
END $$;