diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..f870d15 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,144 @@ +name: CI + +# Checks only — completely separate from deploy.yml (which SSHes to the droplet +# on push to main). This never deploys; it runs typecheck, lint, unit tests, and +# the DB-backed integration + Playwright e2e suites on every PR and on main after +# merge, so a regression is caught before (and independently of) a deploy. +on: + pull_request: + push: + branches: [main] + +# Don't pile up redundant runs on a busy branch. +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + # Fast, hermetic gate: no DB, no browser. + check: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + + - name: Install pnpm + uses: pnpm/action-setup@v4 + with: + version: 10 + + - name: Install Node + uses: actions/setup-node@v4 + with: + node-version: 20 + cache: pnpm + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Typecheck + run: pnpm run typecheck + + - name: Lint + run: pnpm run lint + + - name: Unit tests + run: pnpm run test:run + + # DB-backed gate: brings up the Supabase CLI stack, applies the canonical + # schema, then runs the integration suite (shipped SQL: RPCs / RLS / triggers / + # constraints, driven through psql) and the Playwright e2e suite against the + # app wired to that stack. + integration-e2e: + runs-on: ubuntu-latest + timeout-minutes: 25 + env: + DB_URL: postgresql://postgres:postgres@127.0.0.1:54322/postgres + steps: + - uses: actions/checkout@v4 + + - name: Install pnpm + uses: pnpm/action-setup@v4 + with: + version: 10 + + - name: Install Node + uses: actions/setup-node@v4 + with: + node-version: 20 + cache: pnpm + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + # The integration harness (integration/db.ts) drives the DB through a + # host `psql`, so it must be on PATH. + - name: Install psql client + run: | + sudo apt-get update + sudo apt-get install -y postgresql-client + + - name: Setup Supabase CLI + uses: supabase/setup-cli@v1 + with: + version: 2.98.2 + + - name: Start Supabase stack + run: | + # Auto-seed on first start would fail: seed.sql needs tables that + # schema.sql (applied below, not via a migration) hasn't created yet. + # Disable it for this ephemeral CI checkout; schema + seed are applied + # explicitly in the next step. (Local dev is unaffected.) + sed -i '/^\[db\.seed\]/,/^\[/ s/^enabled = true/enabled = false/' supabase/config.toml + supabase start + + - name: Apply canonical schema + seed + run: | + psql "$DB_URL" -v ON_ERROR_STOP=1 -f scripts/schema.sql + psql "$DB_URL" -v ON_ERROR_STOP=1 -f scripts/seed.sql + + # Guard: if the DB is unreachable the integration suite self-skips and + # would pass with zero coverage. Fail loudly here first. + - name: Verify DB is reachable + run: psql "$DB_URL" -tAc 'select 1' + + - name: Integration tests + run: > + pnpm exec vitest run --config vitest.integration.config.ts + --reporter=default --reporter=json --outputFile=integration-result.json + + # Belt-and-suspenders: even with a reachable DB, refuse to pass if the + # suite executed 0 tests (a glob miss, an all-skipped run, etc.). + - name: Fail if the integration suite executed 0 tests + run: | + node -e ' + const r = require("./integration-result.json"); + const ran = (r.numPassedTests || 0) + (r.numFailedTests || 0); + console.log(`integration tests executed: ${ran} (passed ${r.numPassedTests}, failed ${r.numFailedTests}, skipped ${r.numPendingTests})`); + if (ran < 1) { + console.error("::error::integration suite executed 0 tests — the DB was unreachable and the suite self-skipped. Refusing to pass."); + process.exit(1); + } + ' + + - name: Install Playwright browser (chromium) + run: pnpm exec playwright install --with-deps chromium + + - name: E2E (Playwright) + run: | + eval "$(supabase status -o env 2>/dev/null)" + export NEXT_PUBLIC_SUPABASE_URL="$API_URL" + export NEXT_PUBLIC_SUPABASE_ANON_KEY="$ANON_KEY" + export SUPABASE_SERVICE_ROLE_KEY="$SERVICE_ROLE_KEY" + export NEXT_PUBLIC_APP_URL="http://localhost:3000" + # Playwright's webServer boots `npm run dev` (see playwright.config.ts) + # and inherits these env vars. + pnpm exec playwright test --project=chromium + + - name: Upload Playwright report + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v4 + with: + name: playwright-report + path: playwright-report/ + retention-days: 7 diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 0000000..face067 --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,134 @@ +# Architecture + +hackerspace-management is a **Next.js 16 App Router** app (TypeScript, Turbopack) on **Supabase** +(Postgres + Auth). Every space is a tenant; the product is single-space-per-user today (see Known +limitations). This document describes the layers and the exact recipe for adding a feature. + +## Request & auth flow + +1. **`proxy.ts`** (repo root) is the middleware (Next 16 renamed `middleware` → `proxy`). It refreshes + the Supabase session and gates every route: anything not in its `PUBLIC_ROUTES` allowlist requires an + authenticated user, else redirect to `/login`. Public routes (webhooks, cron, `/f/*` public forms, + `/track`, the resources subsite) each **self-authenticate** (signature/secret/token) — they do not + rely on a session. +2. **`app/(app)/layout.tsx`** is the second gate (defense in depth): it re-checks the user, loads the + active `space_members` row, and redirects to signup/onboarding when appropriate. Everything under + `app/(app)/` renders inside it. + +## Layers + +Data flows **UI → server action → (validation, guard, domain logic) → data access → Postgres**. Each +layer has one job: + +| Layer | Where | Responsibility | +|---|---|---| +| **Generated types** | `types/database.ts` | Supabase-generated row/enum types. **Never hand-edited** — regenerate with `supabase gen types typescript --schema public > types/database.ts`. | +| **Domain types** | `types/domain/*` | Hand-written friendly aliases (`Space = Tables<'spaces'>`), composites, and result shapes. Import via `@/types/domain`. | +| **Validation** | `lib/validations/*` | Zod schemas, one file per feature + `primitives.ts`, re-exported from `lib/validations/index.ts`. Import via `@/lib/validations`. | +| **Domain logic** | `lib/-logic.ts`, `lib//logic.ts` | Pure, side-effect-free decision functions. Unit-tested with no DB (e.g. `dues-payments-logic`, `door-logic`, `invite-claim`). | +| **Guards** | `lib/auth-helpers.ts`, `lib/-guard.ts`, `lib/actions//_guard.ts` | `requireMember` / `requireMemberWithRole` / `parseInput` / `logActivity`; per-feature permission gates returning a `Gate` discriminated union. | +| **Data access** | `lib/supabase/{server,client,admin,proxy}.ts` | Supabase clients. `server`/`client` are **RLS-bound**. `admin` uses the service role and **bypasses RLS**. | +| **Server actions** | `lib/actions/[.ts \| /]` | `'use server'` mutations/queries. Re-exported through `lib/actions/index.ts`. Client code imports from `@/lib/actions`. | +| **UI** | `app/(app)//` | `page.tsx` (server: fetch + guard) → `-client.tsx` (thin orchestrator) → `panels/` + `components/` + `types.ts`. | + +### The server-action contract (memorize this) + +Every action follows the same shape — see `lib/actions/members.ts` for the canonical example: + +```ts +'use server' +export async function doThing(input: {...}) { + const v = parseInput(thingSchema, input) // 1. validate (Zod) + if (!v.ok) return { error: v.error } + const supabase = await createClient() + const auth = await requireMemberWithRole(supabase, ADMIN_ROLES, 'Admin access required') // 2. authorize + if (!auth.ok) return { error: auth.error } + const { member } = auth + const { error } = await supabase + .from('things').update(v.data) + .eq('id', id) + .eq('space_id', member.space_id) // 3. SCOPE to the caller's space (mandatory) + if (error) return { error: error.message } + await logActivity(supabase, member, 'updated', 'thing', id) // 4. audit + revalidatePath('/things') // 5. revalidate + return { success: true as const } +} +``` + +**The critical invariant:** whenever you use `createAdminClient()` (service role, RLS off), *every* read, +update, and delete **must** be scoped with `.eq('space_id', member.space_id)` (or an id already proven to +belong to that space). RLS will not save you there — the scope is the only thing preventing a cross-tenant +(IDOR) leak. `__tests__/actions.test.ts` locks this in; `__tests__/auth-helpers.test.ts` covers the gates. + +## Feature-folder conventions + +A large feature is a folder, not a file. The pattern already exists in the tree: + +- **Actions**: `lib/actions//` with `'use server'` sub-files split by capability, plain + `_guard.ts`/`_helpers.ts` (NOT `'use server'` — they export non-async values), and a plain `index.ts` + barrel. Examples: `lib/actions/{classes,door,forms}/`. +- **UI**: `app/(app)//` = `page.tsx` + a thin `-client.tsx` orchestrator + `panels/` + (one per tab/section) + `components/` (modals, rows) + `types.ts`. Exemplars: + `app/(app)/{customize,ops,settings,members}/`. + +Everything is wired through four barrels so features stay decoupled: `@/lib/validations`, +`@/types/domain`, `@/lib/actions`, and `lib/permissions-catalog.ts`. + +## Adding a feature (extension) — step by step + +A correct feature touches **one file per layer** and imports cross-feature code only through the barrels. + +1. **Migration** — add `scripts/0NN_.sql` (table + RLS policies + any RPC). Enable RLS and write + per-operation policies scoped by space membership. Then regenerate `types/database.ts`. +2. **Validation** — `lib/validations/.ts` with `createSchema` etc., reusing + `lib/validations/primitives.ts`. Add `export * from './'` to `lib/validations/index.ts`. +3. **Domain types** — `types/domain/.ts`: `export type Feature = Tables<'features'>` + composites. + Barrel from `types/domain/index.ts`. +4. **Domain logic** — `lib//logic.ts`: pure decision functions, unit-tested (no DB). +5. **Guard** — `lib/actions//_guard.ts`: `requireManager()` returning the `Gate` union + (copy `lib/actions/classes/_guard.ts` and swap the permission string). Register the permission in + `lib/permissions-catalog.ts`. +6. **Actions** — `lib/actions//.ts` (`'use server'`). Follow the contract above: + validate → authorize → **space-scope every query** → `logActivity` → `revalidatePath`. Barrel via + `lib/actions//index.ts`, then `export * from './'` in `lib/actions/index.ts`. +7. **UI** — `app/(app)//page.tsx` (server: fetch + guard, pass data as props) + + `-client.tsx` (thin orchestrator) + `panels/` + `components/` + `types.ts`. Client components + call server actions from `@/lib/actions` — **never write to the DB from the browser client** (that + skips validation, the authz gate, the activity log, and — for encrypted data — encryption). +8. **Tests** — pure-logic unit tests in `__tests__/`; an action-layer test asserting the space-scope and + the guard rejection (mirror `__tests__/actions.test.ts`). + +## Security model (summary) + +- **Two enforcement layers**: Postgres RLS (all 50 tables) *and* explicit code-side authz + + `space_id` scoping in every action. The admin (service-role) client bypasses RLS, so code-side scoping + is mandatory there. +- **Roles/statuses** live in `lib/permissions.ts`. `PRIVILEGE_STATUSES` excludes `unverified` — a member + pending approval in a `require_approval` space holds no privileged capability. +- **Secrets** are AES-256-GCM encrypted at rest (`lib/secrets/*`); always write them via the + `createSecret`/`updateSecret` server actions (the key is server-only). +- **Public endpoints** self-authenticate: Stripe (per-space signing secret + replay guard), door inbound + (per-connection vault bearer, `timingSafeEqual`), crons (`CRON_SECRET`), `/track` (192-bit token). + +## Build & CI + +- `pnpm run typecheck` (`tsc --noEmit`), `pnpm run lint` (ESLint 9 flat config, `eslint.config.mjs`), + `pnpm run test:run` (Vitest). `.github/workflows/ci.yml` runs all three on PRs and `main`. +- `next build` type-checks (no `ignoreBuildErrors`). **`main` deploys to production on every push** + (`.github/workflows/deploy.yml` → SSH → the droplet's `deploy.sh`). + +## Known limitations / follow-ups + +- **Single active space per user** (`getAuthMember` uses `.single()`, fail-closed). Multi-space needs an + explicit active-space selector before that changes. +- **Regenerate `types/database.ts`** to drop the hand-added RPC entries and the `// TODO(types)` join + casts, and to de-duplicate the governance row types in `types/domain/governance.ts` into `Tables<>`. +- **`markOnboardingStepDone`** read-modify-writes a JSON column; a concurrent double-submit can drop a + step. A DB-side atomic append (RPC / jsonb operator) is the fix. +- Integration + e2e suites need a DB service wired into CI (only unit tests + typecheck + lint run today). +- **Full authenticated UI testing** hasn't run in this environment (no local Docker/Supabase). The public + surface + routing were browser-smoke-tested; the authed screens are verified by `next build` + tsc + tests. + +All client-component DB writes now go through server actions (the ops area-lead and comms message writes +were the last direct-browser-write holdouts). The only browser-client usage that remains is auth +(login/signup) and the comms realtime read, which the postgres_changes subscription requires. diff --git a/__tests__/actions.test.ts b/__tests__/actions.test.ts index f40045e..d596292 100644 --- a/__tests__/actions.test.ts +++ b/__tests__/actions.test.ts @@ -1,430 +1,342 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' -// ─── Mock Supabase Client ───────────────────────────────────────────────────── -const mockSupabase = { - auth: { - getUser: vi.fn(), - signInWithPassword: vi.fn(), - signOut: vi.fn(), - }, - from: vi.fn(() => mockSupabase), - select: vi.fn(() => mockSupabase), - insert: vi.fn(() => mockSupabase), - update: vi.fn(() => mockSupabase), - delete: vi.fn(() => mockSupabase), - upsert: vi.fn(() => mockSupabase), - eq: vi.fn(() => mockSupabase), - in: vi.fn(() => mockSupabase), - single: vi.fn(), +/** + * Real server-action authorization + tenant-scoping tests. + * + * The previous version of this file asserted on string literals it defined + * itself (e.g. `expect(".eq('space_id', ...)").toContain('space_id')`) and + * never invoked a single action — it stayed green no matter what the code did. + * These tests drive the ACTUAL actions through a recording mock Supabase client + * and assert the authz gate and the `.eq('space_id', …)` scoping that stop + * cross-tenant (IDOR) writes. Remove the scope or the role gate in a real + * action and one of these fails. + */ + +// ─── Recording mock Supabase client ────────────────────────────────────────── +type QueueItem = { data?: unknown; error?: unknown } + +function makeClient(opts: { user?: { id: string; email?: string } | null; queue?: QueueItem[] }) { + const calls: Array<{ method: string; args: unknown[] }> = [] + const queue = [...(opts.queue ?? [])] + const next = (): QueueItem => (queue.length ? queue.shift()! : { data: null, error: null }) + + // A single chainable/awaitable recorder shared across every query on this + // client. Chain methods record their args and return the builder; terminal + // `.single()/.maybeSingle()` and awaiting the chain pull the next queued + // result, so a test scripts results in call order. + const builder: Record = new Proxy( + {}, + { + get(_t, prop: string) { + if (prop === 'then') { + return (resolve: (v: QueueItem) => void) => resolve(next()) + } + if (prop === 'single' || prop === 'maybeSingle') { + return (...args: unknown[]) => { + calls.push({ method: prop, args }) + return Promise.resolve(next()) + } + } + return (...args: unknown[]) => { + calls.push({ method: prop, args }) + return builder + } + }, + }, + ) + + const client = { + auth: { + getUser: vi.fn(() => Promise.resolve({ data: { user: opts.user ?? null } })), + }, + from: (...args: unknown[]) => { + calls.push({ method: 'from', args }) + return builder + }, + _calls: calls, + } + return client } +let currentClient: ReturnType + vi.mock('@/lib/supabase/server', () => ({ - createClient: vi.fn(() => Promise.resolve(mockSupabase)), + createClient: () => Promise.resolve(currentClient), })) +vi.mock('@/lib/supabase/admin', () => ({ + // Permissive stand-in; the tests below avoid code paths that use it. + createAdminClient: () => makeClient({ user: null, queue: [] }), +})) +vi.mock('next/cache', () => ({ revalidatePath: vi.fn() })) -// ─── Test Data ──────────────────────────────────────────────────────────────── -const VALID_STATUSES = ['current', 'unverified', 'late'] -const INVALID_STATUSES = ['inactive', 'suspended', 'banned'] +import { updateMember, removeMember } from '@/lib/actions/members' +import { logCashPayment, linkPaymentToMember } from '@/lib/actions/payments' +import { sendMessage } from '@/lib/actions/comms' +import { createAreaLead, updateAreaLead, deleteAreaLead } from '@/lib/actions/area-leads' -const mockUser = { id: 'user-123', email: 'test@example.com' } -const mockMember = { - id: 'member-123', - space_id: 'space-123', - display_name: 'Test User', - role: 'member', +const UUID = '11111111-1111-1111-1111-111111111111' +const user = { id: 'user-A', email: 'a@example.com' } +const memberRow = (role: string, space_id = 'space-A') => ({ + id: 'member-A', + space_id, + user_id: user.id, + role, status: 'current', -} -const mockAdminMember = { ...mockMember, role: 'admin' } -const mockBoardMember = { ...mockMember, role: 'board' } -const mockTreasurer = { ...mockMember, role: 'treasurer' } + display_name: 'Admin A', + handle: 'admin-a', +}) -// ─── Auth Tests ─────────────────────────────────────────────────────────────── -describe('Authentication', () => { - beforeEach(() => { - vi.clearAllMocks() +/** Find recorded `.eq(col, val)` calls. */ +const eqCalls = (c: ReturnType) => + c._calls.filter(x => x.method === 'eq').map(x => x.args) + +beforeEach(() => { + vi.clearAllMocks() +}) + +describe('server-action authorization', () => { + it('rejects an unauthenticated caller and performs no write', async () => { + currentClient = makeClient({ user: null, queue: [] }) + const res = await updateMember(UUID, { display_name: 'x' }) + expect(res).toHaveProperty('error') + // No space_members UPDATE reached the client (only the auth lookup, if any). + expect(eqCalls(currentClient).some(a => a[0] === 'space_id')).toBe(false) }) - it('should return user on successful authentication', async () => { - mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } }) - const result = await mockSupabase.auth.getUser() - expect(result.data.user).toEqual(mockUser) + it('rejects a non-privileged member from updating members', async () => { + currentClient = makeClient({ user, queue: [{ data: memberRow('member') }] }) + const res = await updateMember(UUID, { display_name: 'x' }) + expect(res).toHaveProperty('error') + expect((res as { error: string }).error).toMatch(/admin/i) + expect(eqCalls(currentClient).some(a => a[0] === 'space_id')).toBe(false) }) - it('should return null when not authenticated', async () => { - mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } }) - const result = await mockSupabase.auth.getUser() - expect(result.data.user).toBeNull() + it('rejects a board member from REMOVING a member (admin-only)', async () => { + currentClient = makeClient({ user, queue: [{ data: memberRow('board') }] }) + const res = await removeMember(UUID) + expect(res).toHaveProperty('error') + expect(eqCalls(currentClient).some(a => a[0] === 'space_id')).toBe(false) }) - it('should handle sign-in errors', async () => { - mockSupabase.auth.signInWithPassword.mockResolvedValue({ - error: { message: 'Invalid credentials' }, - }) - const result = await mockSupabase.auth.signInWithPassword({ - email: 'test@test.com', - password: 'wrong', - }) - expect(result.error.message).toBe('Invalid credentials') + it('rejects a plain member from logging a cash payment (treasurer-gated)', async () => { + currentClient = makeClient({ user, queue: [{ data: memberRow('member') }] }) + const res = await logCashPayment({ amount: 10, from_note: 'cash' }) + expect(res).toHaveProperty('error') }) }) -// ─── Member Status Tests ────────────────────────────────────────────────────── -describe('Member Status Validation', () => { - it('should allow current members to perform actions', () => { - expect(VALID_STATUSES).toContain('current') +describe('server-action tenant scoping (IDOR guard)', () => { + it('scopes an admin updateMember to the caller’s space_id', async () => { + currentClient = makeClient({ + user, + queue: [{ data: memberRow('admin', 'space-A') }, { error: null }], + }) + // Attacker-style call: a valid member id that might belong to another space. + const res = await updateMember(UUID, { display_name: 'x' }) + expect(res).not.toHaveProperty('error') + // The UPDATE must be pinned to the caller's own space, so a row in another + // space can never be touched. + expect(eqCalls(currentClient)).toContainEqual(['space_id', 'space-A']) + expect(eqCalls(currentClient)).toContainEqual(['id', UUID]) }) - it('should allow unverified members to perform actions', () => { - expect(VALID_STATUSES).toContain('unverified') + it('scopes an admin removeMember to the caller’s space_id', async () => { + currentClient = makeClient({ + user, + queue: [{ data: memberRow('admin', 'space-A') }, { error: null }], + }) + const res = await removeMember(UUID) + expect(res).not.toHaveProperty('error') + expect(eqCalls(currentClient)).toContainEqual(['space_id', 'space-A']) }) - it('should allow late members to perform actions', () => { - expect(VALID_STATUSES).toContain('late') + it('stamps a treasurer cash payment with the caller’s space_id', async () => { + currentClient = makeClient({ + user, + queue: [ + { data: memberRow('treasurer', 'space-A') }, // requireMember + { data: { id: 'pay-1' } }, // payments insert().select().single() + { error: null }, // activity_log insert + ], + }) + const res = await logCashPayment({ amount: 25, from_note: 'dues' }) + expect(res).not.toHaveProperty('error') + const inserts = currentClient._calls.filter(x => x.method === 'insert').map(x => x.args[0]) + const paymentInsert = inserts.find( + (o): o is Record => !!o && typeof o === 'object' && 'platform' in o, + ) + expect(paymentInsert?.space_id).toBe('space-A') + expect(paymentInsert?.platform).toBe('cash') }) - it('should NOT allow inactive members to perform actions', () => { - expect(VALID_STATUSES).not.toContain('inactive') + it('rejects a cash payment whose member_id belongs to another space', async () => { + currentClient = makeClient({ + user, + queue: [ + { data: memberRow('treasurer', 'space-A') }, // requireMember + { data: null }, // space_members scope lookup: foreign member -> not found + ], + }) + const res = await logCashPayment({ amount: 25, from_note: 'dues', member_id: UUID }) + expect(res).toHaveProperty('error') + expect((res as { error: string }).error).toMatch(/not found in this space/i) + // The IDOR write must never reach the payments table. + const inserts = currentClient._calls.filter(x => x.method === 'insert').map(x => x.args[0]) + expect(inserts.some(o => !!o && typeof o === 'object' && 'platform' in (o as object))).toBe(false) + // The scope lookup was pinned to the caller's own space. + expect(eqCalls(currentClient)).toContainEqual(['space_id', 'space-A']) + expect(eqCalls(currentClient)).toContainEqual(['id', UUID]) }) - it('getMember helper should use .in() for status check', () => { - // This validates the fix was applied correctly - const statusCheck = `.in('status', ['current', 'unverified', 'late'])` - expect(statusCheck).toContain('unverified') - expect(statusCheck).toContain('late') + it('rejects linking a payment to a member_id from another space', async () => { + currentClient = makeClient({ + user, + queue: [ + { data: memberRow('treasurer', 'space-A') }, // requireMember + { data: null }, // space_members scope lookup: foreign member -> not found + ], + }) + const res = await linkPaymentToMember(UUID, UUID) + expect(res).toHaveProperty('error') + expect((res as { error: string }).error).toMatch(/not found in this space/i) + // No payments UPDATE was recorded (the guard returns before the link write). + expect(currentClient._calls.some(x => x.method === 'update')).toBe(false) + expect(eqCalls(currentClient)).toContainEqual(['space_id', 'space-A']) }) }) -// ─── Task Management Tests ──────────────────────────────────────────────────── -describe('Task Management', () => { - beforeEach(() => { - vi.clearAllMocks() - mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } }) +describe('comms sendMessage anti-impersonation', () => { + const CHANNEL = '22222222-2222-2222-2222-222222222222' + + it('stamps the message with session identity, ignoring client-supplied fields', async () => { + currentClient = makeClient({ + user, // user-A — the authenticated sender + queue: [ + { data: memberRow('member', 'space-A') }, // requireMember + { data: { id: CHANNEL } }, // channel scope lookup: belongs to space-A + { data: { id: 'msg-1' } }, // comms_messages insert().select().single() + { error: null }, // activity_log insert + ], + }) + // Attacker tries to spoof identity + tenant through the input. The action + // types forbid these keys, so cast through unknown to simulate a hand-rolled + // client payload; Zod strips them and identity is derived from the session. + const spoofed = { + channel_id: CHANNEL, + content: 'hello', + user_id: 'attacker', + display_name: 'Someone Else', + handle: 'imposter', + space_id: 'space-VICTIM', + } as unknown as Parameters[0] + const res = await sendMessage(spoofed) + expect(res).not.toHaveProperty('error') + + const inserts = currentClient._calls.filter(x => x.method === 'insert').map(x => x.args[0]) + const msgInsert = inserts.find( + (o): o is Record => !!o && typeof o === 'object' && 'content' in o, + ) + // Identity + tenant come from the session/member, NOT the input. + expect(msgInsert?.user_id).toBe('user-A') + expect(msgInsert?.space_id).toBe('space-A') + expect(msgInsert?.display_name).toBe('Admin A') + expect(msgInsert?.handle).toBe('admin-a') + // The spoofed values must never survive. + expect(msgInsert?.user_id).not.toBe('attacker') + expect(msgInsert?.space_id).not.toBe('space-VICTIM') + expect(msgInsert?.display_name).not.toBe('Someone Else') }) - describe('Task Creation', () => { - it('should create a task with required fields', () => { - const taskData = { - title: 'Test Task', - type: 'task', - space_id: 'space-123', - } - expect(taskData.title).toBeDefined() - expect(taskData.type).toBe('task') - }) - - it('should default task_type to "task" if not provided', () => { - const formData = { title: 'Test' } - const taskType = (formData as any).type || 'task' - expect(taskType).toBe('task') - }) - - it('should default recurrence to "none" if not provided', () => { - const formData = { title: 'Test' } - const recurrence = (formData as any).recurrence || 'none' - expect(recurrence).toBe('none') - }) - - it('should set status to "open" on creation', () => { - const newTask = { status: 'open' } - expect(newTask.status).toBe('open') - }) - }) - - describe('Task Claiming', () => { - it('should update claimed_by on claim', () => { - const claimUpdate = { - claimed_by: mockUser.id, - claimed_by_name: mockMember.display_name, - status: 'claimed', - } - expect(claimUpdate.claimed_by).toBe(mockUser.id) - expect(claimUpdate.status).toBe('claimed') - }) - }) - - describe('Task Completion', () => { - it('should set status to completed and add timestamps', () => { - const now = new Date().toISOString() - const completeUpdate = { - status: 'completed', - completed_at: now, - last_done_at: now, - } - expect(completeUpdate.status).toBe('completed') - expect(completeUpdate.completed_at).toBeDefined() - }) - }) - - describe('Task Filtering', () => { - const tasks = [ - { id: '1', task_type: 'task', status: 'open', recurrence: 'none' }, - { id: '2', task_type: 'chore', status: 'open', recurrence: 'weekly' }, - { id: '3', task_type: 'task', status: 'completed', recurrence: 'none' }, - { id: '4', task_type: 'task', status: 'open', recurrence: 'daily' }, - { id: '5', task_type: 'chore', status: 'open', recurrence: 'none' }, - ] - - const isDone = (t: any) => t.status === 'done' || t.status === 'completed' - const isOpen = (t: any) => !isDone(t) - - it('should identify open tasks correctly', () => { - const openTasks = tasks.filter(isOpen) - expect(openTasks).toHaveLength(4) - }) - - it('should identify done tasks correctly', () => { - const doneTasks = tasks.filter(isDone) - expect(doneTasks).toHaveLength(1) - }) - - it('should filter open non-recurring tasks (Open Tasks tab)', () => { - const openNonRecurring = tasks.filter( - t => isOpen(t) && (!t.recurrence || t.recurrence === 'none') - ) - expect(openNonRecurring).toHaveLength(2) - expect(openNonRecurring.map(t => t.id)).toEqual(['1', '5']) - }) - - it('should filter recurring tasks (Ongoing tab)', () => { - const ongoing = tasks.filter( - t => t.recurrence && t.recurrence !== 'none' && isOpen(t) - ) - expect(ongoing).toHaveLength(2) - expect(ongoing.map(t => t.id)).toEqual(['2', '4']) - }) - - it('should filter tasks by assignee (My Tasks tab)', () => { - const userId = 'user-123' - const myTasks = [ - { ...tasks[0], claimed_by: userId }, - { ...tasks[1], assigned_to: 'other-user' }, - ] - const mine = myTasks.filter( - t => (t.claimed_by === userId || t.assigned_to === userId) && isOpen(t) - ) - expect(mine).toHaveLength(1) + it('rejects posting to a channel_id from another space and writes nothing', async () => { + currentClient = makeClient({ + user, + queue: [ + { data: memberRow('member', 'space-A') }, // requireMember + { data: null }, // channel scope lookup: foreign channel -> not found + ], }) + const res = await sendMessage({ channel_id: CHANNEL, content: 'hello' }) + expect(res).toHaveProperty('error') + // No message ever reached comms_messages. + const inserts = currentClient._calls.filter(x => x.method === 'insert').map(x => x.args[0]) + expect(inserts.some(o => !!o && typeof o === 'object' && 'content' in (o as object))).toBe(false) + // The channel lookup was pinned to the caller's own space. + expect(eqCalls(currentClient)).toContainEqual(['space_id', 'space-A']) + expect(eqCalls(currentClient)).toContainEqual(['id', CHANNEL]) }) }) -// ─── Project Management Tests ───────────────────────────────────────────────── -describe('Project Management', () => { - it('should create project with default status "backlog"', () => { - const newProject = { status: 'backlog' } - expect(newProject.status).toBe('backlog') +describe('area-leads roster actions (admin-gated, space-scoped)', () => { + const fields = { area_name: 'Woodshop', lead_handle: 'alice', description: null } + + it('rejects a non-admin from creating an area lead and writes nothing', async () => { + currentClient = makeClient({ user, queue: [{ data: memberRow('member') }] }) + const res = await createAreaLead(fields) + expect(res).toHaveProperty('error') + expect((res as { error: string }).error).toMatch(/admin/i) + // The insert must never reach area_leads. + const inserts = currentClient._calls.filter(x => x.method === 'insert').map(x => x.args[0]) + expect(inserts.some(o => !!o && typeof o === 'object' && 'area_name' in (o as object))).toBe(false) }) - it('should support all project statuses', () => { - const statuses = ['backlog', 'active', 'paused', 'completed', 'cancelled'] - expect(statuses).toHaveLength(5) + it('stamps a created area lead with the caller’s space_id', async () => { + currentClient = makeClient({ + user, + queue: [ + { data: memberRow('admin', 'space-A') }, // requireMemberWithRole + { data: { id: 'al-1' } }, // area_leads insert().select().single() + { error: null }, // activity_log insert + ], + }) + const res = await createAreaLead(fields) + expect(res).not.toHaveProperty('error') + const inserts = currentClient._calls.filter(x => x.method === 'insert').map(x => x.args[0]) + const leadInsert = inserts.find( + (o): o is Record => !!o && typeof o === 'object' && 'area_name' in o, + ) + // Tenant is derived from the session member, never the client. + expect(leadInsert?.space_id).toBe('space-A') + expect(leadInsert?.area_name).toBe('Woodshop') + // area_code stays null for this roster interface. + expect(leadInsert?.area_code).toBeUndefined() }) - it('should update project status and timestamp', () => { - const update = { - status: 'active', - updated_at: new Date().toISOString(), - } - expect(update.status).toBe('active') - expect(update.updated_at).toBeDefined() - }) -}) - -// ─── Member Management Tests ────────────────────────────────────────────────── -describe('Member Management', () => { - describe('Role-Based Access', () => { - it('should allow admin to add members', () => { - const adminRoles = ['admin', 'board'] - expect(adminRoles).toContain(mockAdminMember.role) - }) - - it('should allow board to add members', () => { - const adminRoles = ['admin', 'board'] - expect(adminRoles).toContain(mockBoardMember.role) - }) - - it('should deny regular members from adding members', () => { - const adminRoles = ['admin', 'board'] - expect(adminRoles).not.toContain('member') - }) - - it('should only allow admin to remove members', () => { - expect(mockAdminMember.role).toBe('admin') - }) - }) - - describe('Member Approval', () => { - it('should set status to current on approval', () => { - const approveUpdate = { status: 'current', approved: true } - expect(approveUpdate.status).toBe('current') - expect(approveUpdate.approved).toBe(true) - }) - }) - - describe('Member Data', () => { - it('should create member with required fields', () => { - const memberData = { - display_name: 'New Member', - email: 'new@example.com', - tier: 'regular', - role: 'member', - status: 'current', - } - expect(memberData.display_name).toBeDefined() - expect(memberData.email).toBeDefined() - }) - }) -}) - -// ─── Payment Management Tests ───────────────────────────────────────────────── -describe('Payment Management', () => { - describe('Role-Based Access', () => { - const treasurerRoles = ['admin', 'board', 'treasurer'] - - it('should allow admin to log payments', () => { - expect(treasurerRoles).toContain('admin') - }) - - it('should allow board to log payments', () => { - expect(treasurerRoles).toContain('board') - }) - - it('should allow treasurer to log payments', () => { - expect(treasurerRoles).toContain('treasurer') - }) - - it('should deny regular members from logging payments', () => { - expect(treasurerRoles).not.toContain('member') - }) - }) - - describe('Cash Payment Logging', () => { - it('should create cash payment with correct platform', () => { - const payment = { platform: 'cash', amount: 100 } - expect(payment.platform).toBe('cash') - }) - - it('should link payment to member when member_id provided', () => { - const payment = { - member_id: 'member-123', - link_status: 'linked', - } - expect(payment.link_status).toBe('linked') - }) - - it('should leave unlinked when no member_id', () => { - const payment = { - member_id: null, - link_status: 'unlinked', - } - expect(payment.link_status).toBe('unlinked') - }) - }) - - describe('Payment Linking', () => { - it('should update member payment status on link', () => { - const memberUpdate = { - last_paid_at: new Date().toISOString(), - payment_status: 'current', - } - expect(memberUpdate.payment_status).toBe('current') - }) - }) -}) - -// ─── Contact Management Tests ───────────────────────────────────────────────── -describe('Contact Management', () => { - it('should generate contact code from name', () => { - const name = 'John Doe' - const code = name.slice(0, 3).toUpperCase() + Math.floor(Math.random() * 900 + 100) - expect(code).toMatch(/^JOH\d{3}$/) - }) - - it('should support all contact types', () => { - const types = ['vendor', 'landlord', 'utility', 'service', 'emergency', 'other'] - expect(types.length).toBeGreaterThan(0) - }) -}) - -// ─── Knowledge Base Tests ───────────────────────────────────────────────────── -describe('Knowledge Base', () => { - it('should create KB entry with default visibility', () => { - const entry = { - visibility: 'all_members', - } - expect(entry.visibility).toBe('all_members') - }) - - it('should support visibility levels', () => { - const levels = ['all_members', 'board_only', 'admin_only'] - expect(levels).toHaveLength(3) - }) -}) - -// ─── Secrets Management Tests ───────────────────────────────────────────────── -describe('Secrets Management', () => { - describe('Role-Based Access', () => { - it('should only allow admin/board to create secrets', () => { - const secretRoles = ['admin', 'board'] - expect(secretRoles).toContain('admin') - expect(secretRoles).toContain('board') - expect(secretRoles).not.toContain('member') - }) - - it('should only allow admin to delete secrets', () => { - expect(mockAdminMember.role).toBe('admin') - }) - }) - - it('should encrypt secret values', () => { - // Secrets should be stored securely - const secret = { label: 'API Key', value: 'sk-xxx' } - expect(secret.value).toBeDefined() - }) -}) - -// ─── Settings Management Tests ───────────────────────────────────────────────── -describe('Settings Management', () => { - it('should only allow admin to update space settings', () => { - expect(mockAdminMember.role).toBe('admin') - }) - - it('should update space settings', () => { - const settings = { - name: 'New Space Name', - timezone: 'America/New_York', - } - expect(settings.name).toBeDefined() - }) -}) - -// ─── Activity Logging Tests ─────────────────────────────────────────────────── -describe('Activity Logging', () => { - it('should log task creation activity', () => { - const activity = { - action: 'created', - entity_type: 'task', - } - expect(activity.action).toBe('created') - expect(activity.entity_type).toBe('task') - }) - - it('should log all action types', () => { - const actions = ['created', 'claimed', 'completed', 'approved', 'logged'] - expect(actions.length).toBeGreaterThan(0) - }) -}) - -// ─── RLS Policy Tests ───────────────────────────────────────────────────────── -describe('Row Level Security', () => { - it('should scope all queries to space_id', () => { - // Every table query should include space_id filter - const query = `.eq('space_id', member.space_id)` - expect(query).toContain('space_id') - }) - - it('should use user space membership for authorization', () => { - const member = { space_id: 'space-123', user_id: 'user-123' } - expect(member.space_id).toBeDefined() - expect(member.user_id).toBeDefined() + it('scopes an admin updateAreaLead to the caller’s space_id and id', async () => { + currentClient = makeClient({ + user, + queue: [ + { data: memberRow('admin', 'space-A') }, // requireMemberWithRole + { data: { id: UUID } }, // area_leads update().select().single() + { error: null }, // activity_log insert + ], + }) + // Attacker-style call: a lead id that might belong to another space. + const res = await updateAreaLead(UUID, { area_name: 'Metal', lead_handle: 'bob' }) + expect(res).not.toHaveProperty('error') + expect(eqCalls(currentClient)).toContainEqual(['space_id', 'space-A']) + expect(eqCalls(currentClient)).toContainEqual(['id', UUID]) + }) + + it('scopes an admin deleteAreaLead to the caller’s space_id', async () => { + currentClient = makeClient({ + user, + queue: [ + { data: memberRow('admin', 'space-A') }, // requireMemberWithRole + { error: null }, // area_leads delete({ count: 'exact' }) -> row deleted + { error: null }, // activity_log insert + ], + }) + const res = await deleteAreaLead(UUID) + expect(res).not.toHaveProperty('error') + expect(eqCalls(currentClient)).toContainEqual(['space_id', 'space-A']) + expect(eqCalls(currentClient)).toContainEqual(['id', UUID]) + }) + + it('rejects a non-admin from deleting an area lead and writes nothing', async () => { + currentClient = makeClient({ user, queue: [{ data: memberRow('member') }] }) + const res = await deleteAreaLead(UUID) + expect(res).toHaveProperty('error') + // No space-scoped delete ever ran. + expect(eqCalls(currentClient).some(a => a[0] === 'space_id')).toBe(false) }) }) diff --git a/__tests__/auth-helpers.test.ts b/__tests__/auth-helpers.test.ts index b0f8004..adc92c5 100644 --- a/__tests__/auth-helpers.test.ts +++ b/__tests__/auth-helpers.test.ts @@ -1,6 +1,44 @@ import { describe, it, expect } from 'vitest' import { z } from 'zod' -import { parseInput } from '@/lib/auth-helpers' +import { + parseInput, + getAuthMember, + requireMember, + requireMemberWithRole, + type ServerSupabase, +} from '@/lib/auth-helpers' +import { ADMIN_ROLES } from '@/lib/permissions' + +/** + * Minimal mock of the query the auth helpers issue: + * supabase.auth.getUser() + * supabase.from('space_members').select(...).eq(...).in(...).single() + */ +function mockClient(opts: { + user?: { id: string } | null + member?: Record | null +}): ServerSupabase { + const chain = { + select: () => chain, + eq: () => chain, + in: () => chain, + single: () => Promise.resolve({ data: opts.member ?? null }), + } + return { + auth: { getUser: () => Promise.resolve({ data: { user: opts.user ?? null } }) }, + from: () => chain, + } as unknown as ServerSupabase +} + +const activeMember = (role: string, status = 'current') => ({ + id: 'm1', + space_id: 'space-A', + user_id: 'u1', + role, + status, + display_name: 'M', + handle: 'm', +}) describe('parseInput', () => { const schema = z.object({ @@ -41,3 +79,66 @@ describe('parseInput', () => { } }) }) + +describe('getAuthMember', () => { + it('returns null when there is no authenticated user', async () => { + expect(await getAuthMember(mockClient({ user: null }))).toBeNull() + }) + + it('returns null when the user has no active membership', async () => { + expect(await getAuthMember(mockClient({ user: { id: 'u1' }, member: null }))).toBeNull() + }) + + it('returns the active member for an authenticated user', async () => { + const m = await getAuthMember(mockClient({ user: { id: 'u1' }, member: activeMember('member') })) + expect(m?.space_id).toBe('space-A') + expect(m?.role).toBe('member') + }) +}) + +describe('requireMember', () => { + it('errors when unauthenticated', async () => { + const r = await requireMember(mockClient({ user: null })) + expect(r.ok).toBe(false) + }) + + it('ok for an active member', async () => { + const r = await requireMember(mockClient({ user: { id: 'u1' }, member: activeMember('member') })) + expect(r.ok).toBe(true) + }) +}) + +describe('requireMemberWithRole', () => { + it('rejects an unverified member even with an admin role (require_approval gate)', async () => { + const r = await requireMemberWithRole( + mockClient({ user: { id: 'u1' }, member: activeMember('admin', 'unverified') }), + ADMIN_ROLES, + ) + expect(r.ok).toBe(false) + if (!r.ok) expect(r.error).toMatch(/pending approval/i) + }) + + it('rejects a current member whose role is not allowed', async () => { + const r = await requireMemberWithRole( + mockClient({ user: { id: 'u1' }, member: activeMember('member') }), + ADMIN_ROLES, + ) + expect(r.ok).toBe(false) + }) + + it('allows a current admin', async () => { + const r = await requireMemberWithRole( + mockClient({ user: { id: 'u1' }, member: activeMember('admin') }), + ADMIN_ROLES, + ) + expect(r.ok).toBe(true) + }) + + it('allows a late member to keep their privileged role (dues lapse is not an authz downgrade)', async () => { + const r = await requireMemberWithRole( + mockClient({ user: { id: 'u1' }, member: activeMember('board', 'late') }), + ADMIN_ROLES, + ) + expect(r.ok).toBe(true) + }) +}) diff --git a/__tests__/door-log-logic.test.ts b/__tests__/door-log-logic.test.ts index 2981b69..a512088 100644 Binary files a/__tests__/door-log-logic.test.ts and b/__tests__/door-log-logic.test.ts differ diff --git a/__tests__/door-logic.test.ts b/__tests__/door-logic.test.ts index a09ea01..268edff 100644 --- a/__tests__/door-logic.test.ts +++ b/__tests__/door-logic.test.ts @@ -44,6 +44,18 @@ describe('isBlockedDoorIp (resolved-IP DNS-rebind guard)', () => { expect(isBlockedDoorIp(ip)).toBe(true) } }) + it('blocks the HEX IPv4-mapped form (::ffff:HHHH:HHHH) too', () => { + // ::ffff:a9fe:a9fe == 169.254.169.254 (IMDS); ::ffff:7f00:1 == 127.0.0.1 + for (const ip of ['::ffff:a9fe:a9fe', '::ffff:7f00:1', '::ffff:7f00:0001', '::ffff:a9fe:0102', '[::ffff:7f00:1]']) { + expect(isBlockedDoorIp(ip)).toBe(true) + } + }) + it('ALLOWS non-blocked ranges in HEX IPv4-mapped form', () => { + // ::ffff:c0a8:0109 == 192.168.1.9 ; ::ffff:cb00:7107 == 203.0.113.7 + for (const ip of ['::ffff:c0a8:0109', '::ffff:cb00:7107']) { + expect(isBlockedDoorIp(ip)).toBe(false) + } + }) it('ALLOWS RFC1918 / LAN / ULA / public (door controllers live there)', () => { for (const ip of ['10.0.0.5', '172.16.4.4', '192.168.1.50', '203.0.113.7', 'fd12:3456::1', '2001:db8::1', '::ffff:192.168.1.9']) { expect(isBlockedDoorIp(ip)).toBe(false) diff --git a/__tests__/dues-payments-logic.test.ts b/__tests__/dues-payments-logic.test.ts index b6284e4..2660933 100644 --- a/__tests__/dues-payments-logic.test.ts +++ b/__tests__/dues-payments-logic.test.ts @@ -4,6 +4,7 @@ import { DUES_PLATFORM_LABEL, isDuesLinkPlatform, isSafeDuesUrl, + resolveDuesAdvance, } from '@/lib/dues-payments-logic' describe('DUES_LINK_PLATFORMS', () => { @@ -57,3 +58,47 @@ describe('isSafeDuesUrl', () => { expect(isSafeDuesUrl('https://')).toBe(false) }) }) + +describe('resolveDuesAdvance', () => { + const older = '2026-01-01T00:00:00.000Z' + const newer = '2026-06-01T00:00:00.000Z' + + it('advances when there is no prior payment and marks current', () => { + expect(resolveDuesAdvance(null, newer)).toEqual({ + last_paid_at: newer, + payment_status: 'current', + }) + }) + + it('advances (and marks current) when the new payment is more recent', () => { + expect(resolveDuesAdvance(older, newer)).toEqual({ + last_paid_at: newer, + payment_status: 'current', + }) + }) + + it('advances (and marks current) when dates are equal — the common re-pay case', () => { + expect(resolveDuesAdvance(newer, newer)).toEqual({ + last_paid_at: newer, + payment_status: 'current', + }) + }) + + it('does NOT regress: a backdated payment keeps the newer date and omits payment_status', () => { + const result = resolveDuesAdvance(newer, older) + expect(result.last_paid_at).toBe(newer) + expect(result).not.toHaveProperty('payment_status') + }) + + it('compares by instant, so a +00:00 offset and a Z suffix for the same time still advance', () => { + // existing came back from PostgREST with an offset; incoming is toISOString() + expect(resolveDuesAdvance('2026-06-01T00:00:00+00:00', newer)).toEqual({ + last_paid_at: newer, + payment_status: 'current', + }) + // and a backdated one expressed with an offset still does not regress + const back = resolveDuesAdvance(newer, '2026-01-01T00:00:00+00:00') + expect(back.last_paid_at).toBe(newer) + expect(back).not.toHaveProperty('payment_status') + }) +}) diff --git a/__tests__/email-send.test.ts b/__tests__/email-send.test.ts index 340e254..ceb5633 100644 --- a/__tests__/email-send.test.ts +++ b/__tests__/email-send.test.ts @@ -4,7 +4,7 @@ import { sendEmail } from '@/lib/email/send' const OLD = { ...process.env } function mockFetch(status: number, body: unknown) { - return vi.fn(async () => + return vi.fn(async (_input?: Request | string | URL, _init?: RequestInit) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' }, diff --git a/__tests__/equipment-reserve.test.ts b/__tests__/equipment-reserve.test.ts new file mode 100644 index 0000000..cf82381 --- /dev/null +++ b/__tests__/equipment-reserve.test.ts @@ -0,0 +1,130 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' + +/** + * Cross-tenant guard for reserveEquipment's manager "book on behalf" path. + * + * When a manager passes a target `memberId`, the action must verify that member + * belongs to the caller's space (mirroring signUpForClass) BEFORE inserting a + * reservation stamped with the target's membership. Without the guard a manager + * could pass a member id from another space and create a reservation there. + * + * These drive the ACTUAL action through recording mock Supabase clients: one + * RLS client (createClient) whose results are scripted in call order, and a + * separate admin client (createAdminClient) for the space_members lookup. + */ + +type QueueItem = { data?: unknown; error?: unknown } + +function makeClient(opts: { user?: { id: string; email?: string } | null; queue?: QueueItem[] }) { + const calls: Array<{ method: string; args: unknown[] }> = [] + const queue = [...(opts.queue ?? [])] + const next = (): QueueItem => (queue.length ? queue.shift()! : { data: null, error: null }) + + const builder: Record = new Proxy( + {}, + { + get(_t, prop: string) { + if (prop === 'then') { + return (resolve: (v: QueueItem) => void) => resolve(next()) + } + if (prop === 'single' || prop === 'maybeSingle') { + return (...args: unknown[]) => { + calls.push({ method: prop, args }) + return Promise.resolve(next()) + } + } + return (...args: unknown[]) => { + calls.push({ method: prop, args }) + return builder + } + }, + }, + ) + + const client = { + auth: { + getUser: vi.fn(() => Promise.resolve({ data: { user: opts.user ?? null } })), + }, + from: (...args: unknown[]) => { + calls.push({ method: 'from', args }) + return builder + }, + // rpc returns the (thenable) builder, so `await rpc(...)` pulls the next + // queued result — used for the user_has_permission manager check. + rpc: (...args: unknown[]) => { + calls.push({ method: 'rpc', args }) + return builder + }, + _calls: calls, + } + return client +} + +let currentClient: ReturnType +let currentAdmin: ReturnType + +vi.mock('@/lib/supabase/server', () => ({ + createClient: () => Promise.resolve(currentClient), +})) +vi.mock('@/lib/supabase/admin', () => ({ + createAdminClient: () => currentAdmin, +})) +vi.mock('next/cache', () => ({ revalidatePath: vi.fn() })) + +import { reserveEquipment } from '@/lib/actions/equipment' + +const user = { id: 'user-A', email: 'a@example.com' } +const managerRow = { + id: 'member-A', + space_id: 'space-A', + user_id: user.id, + role: 'manager', + status: 'current', + display_name: 'Manager A', + handle: 'manager-a', +} +const equipRow = { + id: '22222222-2222-2222-2222-222222222222', + name: 'Laser Cutter', + location: 'Lab', + space_id: 'space-A', + status: 'available', + is_active: true, + required_certification_id: null, +} +const FOREIGN_MEMBER = '33333333-3333-3333-3333-333333333333' +const baseInput = { + equipmentId: equipRow.id, + starts_at: '2026-09-01T10:00:00Z', + ends_at: '2026-09-01T11:00:00Z', +} + +beforeEach(() => { + vi.clearAllMocks() +}) + +describe('reserveEquipment cross-space target guard', () => { + it('rejects a manager booking for a member from another space', async () => { + currentClient = makeClient({ + user, + queue: [ + { data: managerRow }, // requireMember (space_members .single) + { data: true }, // user_has_permission rpc -> manager + { data: equipRow }, // equipment .maybeSingle + ], + }) + // Admin client's space_members lookup finds nothing: the target belongs to + // another space (or does not exist). + currentAdmin = makeClient({ user: null, queue: [{ data: null }] }) + + const res = await reserveEquipment({ ...baseInput, memberId: FOREIGN_MEMBER }) + + expect(res).toEqual({ error: 'That member was not found in this space.' }) + // The guard ran: a space_members lookup pinned to the caller's space. + const eqArgs = currentAdmin._calls.filter(c => c.method === 'eq').map(c => c.args) + expect(eqArgs).toContainEqual(['id', FOREIGN_MEMBER]) + expect(eqArgs).toContainEqual(['space_id', 'space-A']) + // No reservation was inserted. + expect(currentAdmin._calls.some(c => c.method === 'insert')).toBe(false) + }) +}) diff --git a/__tests__/import-logic.test.ts b/__tests__/import-logic.test.ts new file mode 100644 index 0000000..d68e7c8 --- /dev/null +++ b/__tests__/import-logic.test.ts @@ -0,0 +1,44 @@ +import { describe, it, expect } from 'vitest' +import { parsePaymentRow } from '@/lib/import-logic' + +describe('parsePaymentRow', () => { + it('parses a well-formed row into a normalized payment', () => { + const r = parsePaymentRow( + { amount: '$1,200.50', from_identifier: 'Ada', from_note: 'dues', transaction_date: '2026-01-15', platform: 'venmo' }, + 2, + ) + expect(r.ok).toBe(true) + if (r.ok) { + expect(r.value.amount).toBe(1200.5) + expect(r.value.platform).toBe('venmo') + expect(r.value.from_identifier).toBe('Ada') + expect(r.value.transaction_date).toBe(new Date('2026-01-15').toISOString()) + } + }) + + it('defaults platform to csv when unmapped', () => { + const r = parsePaymentRow({ amount: '10', from_identifier: 'Bo', transaction_date: '2026-02-01' }, 3) + expect(r.ok).toBe(true) + if (r.ok) expect(r.value.platform).toBe('csv') + }) + + // The bug: a non-empty but unparseable date passed presence validation, then + // new Date(str).toISOString() threw RangeError mid-map, wedging the import. + it('reports an error (never throws) for a non-empty unparseable date', () => { + expect(() => + parsePaymentRow({ amount: '10', from_identifier: 'Cy', transaction_date: 'N/A' }, 4), + ).not.toThrow() + const r = parsePaymentRow({ amount: '10', from_identifier: 'Cy', transaction_date: 'N/A' }, 4) + expect(r.ok).toBe(false) + if (!r.ok) expect(r.error).toBe('Row 4: unparseable date "N/A"') + }) + + it('reports missing required fields', () => { + expect(parsePaymentRow({ amount: 'nope', from_identifier: 'Di', transaction_date: '2026-01-01' }, 5)).toEqual({ + ok: false, + error: 'Row 5: missing required fields', + }) + expect(parsePaymentRow({ amount: '10', from_identifier: '', transaction_date: '2026-01-01' }, 6).ok).toBe(false) + expect(parsePaymentRow({ amount: '10', from_identifier: 'Di', transaction_date: '' }, 7).ok).toBe(false) + }) +}) diff --git a/__tests__/incident-appeal.test.ts b/__tests__/incident-appeal.test.ts new file mode 100644 index 0000000..63ea3c9 --- /dev/null +++ b/__tests__/incident-appeal.test.ts @@ -0,0 +1,157 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' + +/** + * Authorization + orphan-proposal guard for appealIncident. + * + * The incident UPDATE inside appealIncident is RLS-restricted to admin/board. + * Before the fix the action was gated by requireMember (ANY member): a plain + * member/reporter would insert a draft proposal, update ZERO incident rows, and + * still get `{ data: proposal }` back — an orphan proposal the incident never + * links to. These tests drive the REAL action through a recording mock client + * and assert (a) a non-admin/board caller is rejected with NO proposal created, + * and (b) on the admin path the proposal survives only when the incident update + * actually affects a row, otherwise it is rolled back. + */ + +// ─── Recording mock Supabase client (shared style with actions.test.ts) ─────── +type QueueItem = { data?: unknown; error?: unknown } + +function makeClient(opts: { user?: { id: string; email?: string } | null; queue?: QueueItem[] }) { + const calls: Array<{ method: string; args: unknown[] }> = [] + const queue = [...(opts.queue ?? [])] + const next = (): QueueItem => (queue.length ? queue.shift()! : { data: null, error: null }) + + const builder: Record = new Proxy( + {}, + { + get(_t, prop: string) { + if (prop === 'then') { + return (resolve: (v: QueueItem) => void) => resolve(next()) + } + if (prop === 'single' || prop === 'maybeSingle') { + return (...args: unknown[]) => { + calls.push({ method: prop, args }) + return Promise.resolve(next()) + } + } + return (...args: unknown[]) => { + calls.push({ method: prop, args }) + return builder + } + }, + }, + ) + + const client = { + auth: { + getUser: vi.fn(() => Promise.resolve({ data: { user: opts.user ?? null } })), + }, + from: (...args: unknown[]) => { + calls.push({ method: 'from', args }) + return builder + }, + _calls: calls, + } + return client +} + +let currentClient: ReturnType + +vi.mock('@/lib/supabase/server', () => ({ + createClient: () => Promise.resolve(currentClient), +})) +vi.mock('@/lib/supabase/admin', () => ({ + createAdminClient: () => makeClient({ user: null, queue: [] }), +})) +vi.mock('next/cache', () => ({ revalidatePath: vi.fn() })) + +import { appealIncident } from '@/lib/actions/incidents' + +const INCIDENT_ID = '22222222-2222-2222-2222-222222222222' +const user = { id: 'user-A', email: 'a@example.com' } +const memberRow = (role: string, space_id = 'space-A') => ({ + id: 'member-A', + space_id, + user_id: user.id, + role, + status: 'current', + display_name: 'Admin A', + handle: 'admin-a', +}) + +/** Recorded `.from(table)` targets, in order. */ +const fromTables = (c: ReturnType) => + c._calls.filter(x => x.method === 'from').map(x => x.args[0]) + +/** Recorded `.insert(payload)` calls into a given table are hard to attribute + * to a table directly, so detect the proposal insert by its shape. */ +const proposalInserts = (c: ReturnType) => + c._calls + .filter(x => x.method === 'insert') + .map(x => x.args[0]) + .filter( + (o): o is Record => + !!o && typeof o === 'object' && (o as Record).proposal_type === 'membership_vote', + ) + +const deleteCalls = (c: ReturnType) => + c._calls.filter(x => x.method === 'delete') + +beforeEach(() => { + vi.clearAllMocks() +}) + +describe('appealIncident authorization', () => { + it('rejects a plain member with an admin/board message and creates NO proposal', async () => { + currentClient = makeClient({ user, queue: [{ data: memberRow('member') }] }) + const res = await appealIncident({ incidentId: INCIDENT_ID, title: 'Appeal' }) + expect(res).toHaveProperty('error') + expect((res as { error: string }).error).toMatch(/admin/i) + // The action must bail before ever touching incidents or proposals. + expect(proposalInserts(currentClient)).toHaveLength(0) + expect(fromTables(currentClient)).not.toContain('proposals') + }) +}) + +describe('appealIncident orphan-proposal guard', () => { + it('links the incident and returns the proposal when the update affects a row', async () => { + currentClient = makeClient({ + user, + queue: [ + { data: memberRow('admin', 'space-A') }, // requireMember + { data: { id: INCIDENT_ID, status: 'decided', space_id: 'space-A' } }, // incident lookup + { data: { id: 'proposal-1' } }, // proposal insert().select().single() + { data: [{ id: INCIDENT_ID }] }, // incident update().select() → 1 row affected + { error: null }, // activity_log insert + ], + }) + const res = await appealIncident({ incidentId: INCIDENT_ID, title: 'Appeal' }) + expect(res).not.toHaveProperty('error') + expect((res as { data: { id: string } }).data.id).toBe('proposal-1') + expect(proposalInserts(currentClient)).toHaveLength(1) + // A successful update must NOT roll the proposal back. + expect(deleteCalls(currentClient)).toHaveLength(0) + }) + + it('rolls the draft proposal back (no orphan) when the incident update affects zero rows', async () => { + currentClient = makeClient({ + user, + queue: [ + { data: memberRow('admin', 'space-A') }, // requireMember + { data: { id: INCIDENT_ID, status: 'decided', space_id: 'space-A' } }, // incident lookup + { data: { id: 'proposal-1' } }, // proposal insert().select().single() + { data: [], error: null }, // incident update().select() → RLS-silent 0 rows + ], + }) + const res = await appealIncident({ incidentId: INCIDENT_ID, title: 'Appeal' }) + expect(res).toHaveProperty('error') + // The orphan draft proposal must be deleted, not left dangling. + expect(proposalInserts(currentClient)).toHaveLength(1) + const deletes = deleteCalls(currentClient) + expect(deletes.length).toBeGreaterThan(0) + // And the incident-linking UPDATE must be scoped and asserted via .select(). + const eqCols = currentClient._calls.filter(x => x.method === 'eq').map(x => x.args[0]) + expect(eqCols).toContain('space_id') + expect(currentClient._calls.some(x => x.method === 'select')).toBe(true) + }) +}) diff --git a/__tests__/invite-claim.test.ts b/__tests__/invite-claim.test.ts new file mode 100644 index 0000000..f974c3e --- /dev/null +++ b/__tests__/invite-claim.test.ts @@ -0,0 +1,136 @@ +import { describe, it, expect } from 'vitest' +import { claimInviteUse } from '@/lib/invite-claim' + +/** + * Builds a mock admin client whose `space_invites` UPDATE ... .eq('uses_count', n) + * behaves like a real compare-and-swap: it only "affects a row" when the guarded + * `uses_count` equals the row's current value, incrementing it on success. This + * lets us simulate concurrent redemptions deterministically. + */ +function makeAdmin(initial: { uses_count: number; max_uses: number | null }) { + const row = { ...initial } + const client = { + from(_table: string) { + return { + // UPDATE path: .update(patch).eq('id',..).eq('uses_count',guard).select('id') + update(patch: { uses_count: number }) { + let guard: number | null = null + const builder: Record = { + eq(col: string, val: number) { + if (col === 'uses_count') guard = val + return builder + }, + select() { + // CAS: apply only if the guard matches the live value. + if (guard === row.uses_count) { + row.uses_count = patch.uses_count + return Promise.resolve({ data: [{ id: 'inv-1' }] }) + } + return Promise.resolve({ data: [] }) + }, + } + return builder + }, + // SELECT path: .select('uses_count').eq('id',..).maybeSingle() + select() { + const builder: Record = { + eq() { + return builder + }, + maybeSingle() { + return Promise.resolve({ data: { uses_count: row.uses_count } }) + }, + } + return builder + }, + } + }, + _row: row, + } + return client as unknown as Parameters[0] & { _row: typeof row } +} + +describe('claimInviteUse (invite max_uses TOCTOU fix)', () => { + it('claims a use when under the cap and returns the new count', async () => { + const admin = makeAdmin({ uses_count: 0, max_uses: 1 }) + const result = await claimInviteUse(admin, 'inv-1', 0, 1) + expect(result).toEqual({ ok: true, count: 1 }) + expect(admin._row.uses_count).toBe(1) + }) + + it('rejects a single-use invite already at cap (no over-issue)', async () => { + const admin = makeAdmin({ uses_count: 1, max_uses: 1 }) + // Second redeemer read uses_count=0 stale, but the row is already at 1. + const result = await claimInviteUse(admin, 'inv-1', 0, 1) + expect(result).toEqual({ ok: false, reason: 'cap_reached' }) + expect(admin._row.uses_count).toBe(1) // unchanged — not incremented past cap + }) + + it('lets the loser of a race retry into remaining multi-use capacity', async () => { + // max_uses=5, another redeemer already bumped it to 1 after our stale read of 0. + const admin = makeAdmin({ uses_count: 1, max_uses: 5 }) + const result = await claimInviteUse(admin, 'inv-1', 0, 5) + expect(result).toEqual({ ok: true, count: 2 }) // re-read to 1, then CAS-claimed to 2 + expect(admin._row.uses_count).toBe(2) + }) + + it('treats an unlimited invite (max_uses null) as always claimable', async () => { + const admin = makeAdmin({ uses_count: 99, max_uses: null }) + const result = await claimInviteUse(admin, 'inv-1', 99, null) + expect(result).toEqual({ ok: true, count: 100 }) + }) + + it('reports contention (not cap_reached) when it loses the CAS every attempt under a high cap', async () => { + // A perpetually-contended invite with plenty of headroom (cap 1000): every + // CAS loses because a competing writer keeps advancing the row between our + // re-read and our next update, so we never win within the attempt budget. + // The row stays well under cap, so the failure is contention — a false + // 'cap_reached' here would wrongly turn away a legitimate joiner. + const row = { uses_count: 5, max_uses: 1000 as number | null } + const admin = { + from() { + return { + update() { + const builder: Record = { + eq() { + return builder + }, + select() { + // Always lose the CAS: a competitor also bumped the row. + row.uses_count += 1 + return Promise.resolve({ data: [] }) + }, + } + return builder + }, + select() { + const builder: Record = { + eq() { + return builder + }, + maybeSingle() { + return Promise.resolve({ data: { uses_count: row.uses_count } }) + }, + } + return builder + }, + } + }, + } as unknown as Parameters[0] + + const result = await claimInviteUse(admin, 'inv-1', 5, 1000, 5) + expect(result).toEqual({ ok: false, reason: 'contention' }) + expect(row.uses_count).toBeLessThan(1000) // never hit the cap + }) + + it('gives up (contention) if it cannot win the CAS within the attempt budget', async () => { + // Caller's known count (0) is behind the live row (3), so the first CAS + // guard misses; with a 1-attempt budget it re-reads and then gives up + // rather than looping — proving the retry is bounded, not infinite. Cap is + // far off (10), so this is contention, not a reached cap. + const admin = makeAdmin({ uses_count: 3, max_uses: 10 }) + const result = await claimInviteUse(admin, 'inv-1', 0, 10, 1) + expect(result).toEqual({ ok: false, reason: 'contention' }) + expect(admin._row.uses_count).toBe(3) // untouched + }) +}) diff --git a/__tests__/invite-rearm.test.ts b/__tests__/invite-rearm.test.ts new file mode 100644 index 0000000..ac7c089 --- /dev/null +++ b/__tests__/invite-rearm.test.ts @@ -0,0 +1,152 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' + +/** + * Regression: a board member must not be able to re-arm an admin-granting + * invite by updating privilege-affecting fields (is_enabled / max_uses / + * expires_at) WITHOUT touching `role`. Because updateInviteSchema makes `role` + * optional, the old role gate ran only when `role` was in the payload, so + * `updateInvite(adminInviteId, { is_enabled: true, max_uses: 5 })` sailed + * through and re-distributed admin access the board caller could never mint. + * + * These drive the real action through a recording mock Supabase client that + * scripts the requireMember lookup and the existing-invite load, then assert + * whether the tenant-scoped UPDATE reached the client. + */ + +type QueueItem = { data?: unknown; error?: unknown } + +function makeClient(opts: { user?: { id: string; email?: string } | null; queue?: QueueItem[] }) { + const calls: Array<{ method: string; args: unknown[] }> = [] + const queue = [...(opts.queue ?? [])] + const next = (): QueueItem => (queue.length ? queue.shift()! : { data: null, error: null }) + + const builder: Record = new Proxy( + {}, + { + get(_t, prop: string) { + if (prop === 'then') { + return (resolve: (v: QueueItem) => void) => resolve(next()) + } + if (prop === 'single' || prop === 'maybeSingle') { + return (...args: unknown[]) => { + calls.push({ method: prop, args }) + return Promise.resolve(next()) + } + } + return (...args: unknown[]) => { + calls.push({ method: prop, args }) + return builder + } + }, + }, + ) + + const client = { + auth: { + getUser: vi.fn(() => Promise.resolve({ data: { user: opts.user ?? null } })), + }, + from: (...args: unknown[]) => { + calls.push({ method: 'from', args }) + return builder + }, + _calls: calls, + } + return client +} + +let currentClient: ReturnType + +vi.mock('@/lib/supabase/server', () => ({ + createClient: () => Promise.resolve(currentClient), +})) +vi.mock('@/lib/supabase/admin', () => ({ + createAdminClient: () => makeClient({ user: null, queue: [] }), +})) +vi.mock('next/cache', () => ({ revalidatePath: vi.fn() })) + +import { updateInvite } from '@/lib/actions/invites' + +const INVITE_ID = '22222222-2222-2222-2222-222222222222' +const user = { id: 'user-A', email: 'a@example.com' } + +const memberRow = (role: string, space_id = 'space-A') => ({ + id: 'member-A', + space_id, + user_id: user.id, + role, + status: 'current', + display_name: 'Caller', + handle: 'caller', +}) + +/** An exhausted + disabled admin invite in space-A. */ +const adminInvite = { + role: 'admin', + is_enabled: false, + max_uses: 1, + expires_at: null, +} + +const memberInvite = { + role: 'member', + is_enabled: false, + max_uses: 1, + expires_at: null, +} + +const eqCalls = (c: ReturnType) => + c._calls.filter(x => x.method === 'eq').map(x => x.args) +const updateReached = (c: ReturnType) => + c._calls.some(x => x.method === 'update') + +beforeEach(() => { + vi.clearAllMocks() +}) + +describe('updateInvite privilege re-arm guard', () => { + it('blocks a BOARD member from re-enabling/extending an admin invite with no role field', async () => { + currentClient = makeClient({ + user, + queue: [ + { data: memberRow('board') }, // requireMemberWithRole + { data: adminInvite }, // existing-invite load (maybeSingle) + ], + }) + const res = await updateInvite(INVITE_ID, { is_enabled: true, max_uses: 5 }) + expect(res).toHaveProperty('error') + expect((res as { error: string }).error).toMatch(/admin/i) + // The re-arming UPDATE must never reach the database. + expect(updateReached(currentClient)).toBe(false) + }) + + it('allows an ADMIN member to re-enable/extend an admin invite', async () => { + currentClient = makeClient({ + user, + queue: [ + { data: memberRow('admin') }, // requireMemberWithRole + { data: adminInvite }, // existing-invite load + { error: null }, // update + ], + }) + const res = await updateInvite(INVITE_ID, { is_enabled: true, max_uses: 5 }) + expect(res).not.toHaveProperty('error') + expect(updateReached(currentClient)).toBe(true) + // Still tenant-scoped. + expect(eqCalls(currentClient)).toContainEqual(['space_id', 'space-A']) + }) + + it('lets a BOARD member still edit a member-role invite', async () => { + currentClient = makeClient({ + user, + queue: [ + { data: memberRow('board') }, // requireMemberWithRole + { data: memberInvite }, // existing-invite load + { error: null }, // update + ], + }) + const res = await updateInvite(INVITE_ID, { is_enabled: true, max_uses: 5 }) + expect(res).not.toHaveProperty('error') + expect(updateReached(currentClient)).toBe(true) + expect(eqCalls(currentClient)).toContainEqual(['space_id', 'space-A']) + }) +}) diff --git a/__tests__/markdown-anchors.test.ts b/__tests__/markdown-anchors.test.ts index df3411f..db13e3c 100644 --- a/__tests__/markdown-anchors.test.ts +++ b/__tests__/markdown-anchors.test.ts @@ -1,4 +1,5 @@ import { describe, it, expect } from 'vitest' +import type { ReactNode } from 'react' import { headingText, slugifyHeading, @@ -13,7 +14,7 @@ describe('headingText', () => { }) it('flattens arrays and element children', () => { expect(headingText(['Get ', 'started'])).toBe('Get started') - expect(headingText({ props: { children: ['Bold ', { props: { children: 'bit' } }] } })).toBe('Bold bit') + expect(headingText({ props: { children: ['Bold ', { props: { children: 'bit' } }] } } as ReactNode)).toBe('Bold bit') }) it('ignores null/boolean', () => { expect(headingText(null)).toBe('') diff --git a/__tests__/notifications-enqueue.test.ts b/__tests__/notifications-enqueue.test.ts index 85d691e..92313a1 100644 --- a/__tests__/notifications-enqueue.test.ts +++ b/__tests__/notifications-enqueue.test.ts @@ -90,7 +90,7 @@ describe('enqueueNotification', () => { const admin = mockAdmin({ upsertResult: { error: null } }) await enqueueNotification(admin as never, params) expect(admin.from).toHaveBeenCalledWith('notifications') - const [row, opts] = admin.upsert.mock.calls[0] as [Row, Row] + const [row, opts] = admin.upsert.mock.calls[0] as unknown as [Row, Row] expect(row).toMatchObject({ space_id: 'space-1', member_id: 'member-1', diff --git a/__tests__/proposals-authz.test.ts b/__tests__/proposals-authz.test.ts new file mode 100644 index 0000000..37e9898 --- /dev/null +++ b/__tests__/proposals-authz.test.ts @@ -0,0 +1,136 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' + +/** + * Authorization tests for governance proposal actions. + * + * `require_approval` spaces keep a freshly-joined member at status + * 'unverified' until an admin approves them. requireMember admits + * 'unverified' (it's an ACTIVE_STATUS), so the proposal actions must add the + * privilege-eligible gate themselves — otherwise a pending member could + * create and vote on proposals. These tests drive the real actions through a + * recording mock Supabase client and assert the gate blocks 'unverified' + * while a 'current' member is allowed. + */ + +// ─── Recording mock Supabase client (mirrors __tests__/actions.test.ts) ────── +type QueueItem = { data?: unknown; error?: unknown } + +function makeClient(opts: { user?: { id: string; email?: string } | null; queue?: QueueItem[] }) { + const calls: Array<{ method: string; args: unknown[] }> = [] + const queue = [...(opts.queue ?? [])] + const next = (): QueueItem => (queue.length ? queue.shift()! : { data: null, error: null }) + + const builder: Record = new Proxy( + {}, + { + get(_t, prop: string) { + if (prop === 'then') { + return (resolve: (v: QueueItem) => void) => resolve(next()) + } + if (prop === 'single' || prop === 'maybeSingle') { + return (...args: unknown[]) => { + calls.push({ method: prop, args }) + return Promise.resolve(next()) + } + } + return (...args: unknown[]) => { + calls.push({ method: prop, args }) + return builder + } + }, + }, + ) + + const client = { + auth: { + getUser: vi.fn(() => Promise.resolve({ data: { user: opts.user ?? null } })), + }, + from: (...args: unknown[]) => { + calls.push({ method: 'from', args }) + return builder + }, + _calls: calls, + } + return client +} + +let currentClient: ReturnType + +vi.mock('@/lib/supabase/server', () => ({ + createClient: () => Promise.resolve(currentClient), +})) +vi.mock('@/lib/supabase/admin', () => ({ + createAdminClient: () => makeClient({ user: null, queue: [] }), +})) +vi.mock('next/cache', () => ({ revalidatePath: vi.fn() })) + +import { createProposal, castVote } from '@/lib/actions/proposals' + +const UUID = '11111111-2222-3333-4444-555555555555' +const user = { id: 'user-A', email: 'a@example.com' } +const memberRow = (status: string, space_id = 'space-A') => ({ + id: 'member-A', + space_id, + user_id: user.id, + role: 'member', + status, + display_name: 'Pat Member', + handle: 'pat', +}) + +/** True if any recorded insert/upsert wrote to the given table. */ +const wroteTo = (c: ReturnType, table: string) => + c._calls.some(x => x.method === 'from' && x.args[0] === table) + +beforeEach(() => { + vi.clearAllMocks() +}) + +describe('proposal actions block unverified (pending-approval) members', () => { + it('rejects an unverified member from createProposal and performs no insert', async () => { + currentClient = makeClient({ user, queue: [{ data: memberRow('unverified') }] }) + const res = await createProposal({ title: 'Buy a new laser' }) + expect(res).toHaveProperty('error') + expect((res as { error: string }).error).toMatch(/pending approval/i) + // No proposals row was inserted. + expect(currentClient._calls.some(x => x.method === 'insert')).toBe(false) + }) + + it('rejects an unverified member from castVote and casts no vote', async () => { + currentClient = makeClient({ user, queue: [{ data: memberRow('unverified') }] }) + const res = await castVote({ proposalId: UUID, position: 'yes' }) + expect(res).toHaveProperty('error') + expect((res as { error: string }).error).toMatch(/pending approval/i) + // The gate fires before the proposal lookup / upsert, so nothing is written. + expect(wroteTo(currentClient, 'proposal_votes')).toBe(false) + }) + + it('allows a current member to createProposal', async () => { + currentClient = makeClient({ + user, + queue: [ + { data: memberRow('current') }, // requireMember + { data: { id: 'prop-1', title: 'Buy a new laser' } }, // insert().select().single() + { error: null }, // activity_log insert + ], + }) + const res = await createProposal({ title: 'Buy a new laser' }) + expect(res).not.toHaveProperty('error') + expect(wroteTo(currentClient, 'proposals')).toBe(true) + }) + + it('allows a current member to castVote', async () => { + currentClient = makeClient({ + user, + queue: [ + { data: memberRow('current') }, // requireMember + { data: { id: UUID, status: 'open' } }, // proposal lookup maybeSingle + { error: null }, // proposal_votes upsert + { error: null }, // activity_log insert + ], + }) + const res = await castVote({ proposalId: UUID, position: 'yes' }) + expect(res).not.toHaveProperty('error') + expect(wroteTo(currentClient, 'proposal_votes')).toBe(true) + }) +}) diff --git a/__tests__/utils.test.ts b/__tests__/utils.test.ts index a95b5ad..461521c 100644 --- a/__tests__/utils.test.ts +++ b/__tests__/utils.test.ts @@ -74,7 +74,7 @@ describe('String Utilities', () => { }) it('should handle empty name', () => { - const name = '' + const name: string = '' const initials = name ? name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2) : '??' expect(initials).toBe('??') }) diff --git a/app/(app)/comms/comms-client.tsx b/app/(app)/comms/comms-client.tsx index 8ee964c..b264763 100644 --- a/app/(app)/comms/comms-client.tsx +++ b/app/(app)/comms/comms-client.tsx @@ -5,7 +5,7 @@ import { useRouter } from 'next/navigation' import { toast } from 'sonner' import { createClient } from '@/lib/supabase/client' import { Hash, Users2, Send, ChevronLeft, Plus } from 'lucide-react' -import { createChannel } from '@/lib/actions' +import { createChannel, sendMessage as sendMessageAction } from '@/lib/actions' import type { Tables } from '@/types/database' import { PageTitle } from '@/components/ui/page-title' import { Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription } from '@/components/ui/empty' @@ -85,11 +85,11 @@ export default function CommsClient({ member, space, channels }: Props) { m.id.startsWith('temp-') && m.user_id === payload.new.user_id && m.content === payload.new.content - ? payload.new + ? (payload.new as Message) : m, ) } - return [...prev, payload.new] + return [...prev, payload.new as Message] }) }, ) @@ -105,6 +105,11 @@ export default function CommsClient({ member, space, channels }: Props) { }, [messages]) async function loadMessages() { + if (!selectedChannel) return + // Intentional read-only exception: reads stay on the browser client so the + // postgres_changes realtime subscription above shares the same session. + // Writes go through the sendMessage server action (identity is derived + // server-side there). const supabase = createClient() const { data } = await supabase .from('comms_messages') @@ -119,6 +124,7 @@ export default function CommsClient({ member, space, channels }: Props) { e.preventDefault() const content = newMessage.trim() if (!content || sending) return + if (!selectedChannel) return setSending(true) // Optimistic insert — message appears immediately for the sender @@ -133,30 +139,22 @@ export default function CommsClient({ member, space, channels }: Props) { content, created_at: new Date().toISOString(), } - setMessages(prev => [...prev, optimisticMsg]) + setMessages(prev => [...prev, optimisticMsg as Message]) setNewMessage('') - const supabase = createClient() - const { data, error } = await supabase - .from('comms_messages') - .insert({ - channel_id: selectedChannel.id, - space_id: space?.id ?? member.space_id, - user_id: member.user_id, - display_name: member.display_name, - handle: member.handle, - content, - }) - .select() - .single() + // Sender identity + space_id are derived server-side from the session; the + // browser only supplies the channel and text. The realtime subscription + // still delivers the persisted row (temp-id dedup handles it), so latency + // is unchanged. + const result = await sendMessageAction({ channel_id: selectedChannel.id, content }) - if (error) { + if ('error' in result && result.error) { // Roll back optimistic message on failure setMessages(prev => prev.filter(m => m.id !== tempId)) setNewMessage(content) - } else if (data) { + } else if ('data' in result && result.data) { // Replace temp with confirmed message (realtime may also fire — dedup handles it) - setMessages(prev => prev.map(m => (m.id === tempId ? data : m))) + setMessages(prev => prev.map(m => (m.id === tempId ? result.data : m))) } setSending(false) diff --git a/app/(app)/comms/page.tsx b/app/(app)/comms/page.tsx index 2b2bcf2..9079d6f 100644 --- a/app/(app)/comms/page.tsx +++ b/app/(app)/comms/page.tsx @@ -1,4 +1,5 @@ import { createClient } from '@/lib/supabase/server' +import type { Tables } from '@/types/database' import CommsClient from './comms-client' export default async function CommsPage() { @@ -17,5 +18,5 @@ export default async function CommsPage() { .order('channel_type') .order('name') - return + return } channels={channels ?? []} /> } diff --git a/app/(app)/contacts/contacts-client.tsx b/app/(app)/contacts/contacts-client.tsx index 82fafe0..e8b1c12 100644 --- a/app/(app)/contacts/contacts-client.tsx +++ b/app/(app)/contacts/contacts-client.tsx @@ -81,7 +81,7 @@ export function ContactsClient({ contacts: initialContacts }: { contacts: Contac tags: form.tags ? form.tags.split(',').map(t => t.trim()).filter(Boolean) : [], }) if (result.error) { setError(result.error); setLoading(false); return } - setContacts(prev => prev.map(c => c.id === editContact.id ? { ...c, ...form } : c)) + setContacts(prev => prev.map(c => c.id === editContact.id ? { ...c, ...form } as unknown as Contact : c)) setEditContact(null) setLoading(false) } diff --git a/app/(app)/customize/panels/tiers-panel.tsx b/app/(app)/customize/panels/tiers-panel.tsx index 098eafc..fc39635 100644 --- a/app/(app)/customize/panels/tiers-panel.tsx +++ b/app/(app)/customize/panels/tiers-panel.tsx @@ -26,7 +26,7 @@ export function TiersPanel({ isAdmin, tiers: initial }: { isAdmin: boolean; tier onSubmit={async e => { e.preventDefault() const cents = Math.round(parseFloat(d.dollars || '0') * 100) - const result = await createTier({ slug: d.slug.trim().toLowerCase(), name: d.name.trim(), description: d.description.trim() || undefined, monthly_price_cents: isNaN(cents) ? 0 : cents, billing_cadence: d.cadence }) + const result = await createTier({ slug: d.slug.trim().toLowerCase(), name: d.name.trim(), description: d.description.trim() || undefined, monthly_price_cents: isNaN(cents) ? 0 : cents, billing_cadence: d.cadence as 'monthly' | 'quarterly' | 'annual' | 'one_time' | 'custom' }) if ('error' in result && result.error) { toast.error(result.error); return } toast.success('Tier created') setTiers(prev => [...prev, { id: (result as { id: string }).id, slug: d.slug.trim().toLowerCase(), name: d.name.trim(), description: d.description.trim() || null, monthly_price_cents: isNaN(cents) ? 0 : cents, billing_cadence: d.cadence, is_system: false, is_archived: false, sort_order: 100 }]) diff --git a/app/(app)/financials/page.tsx b/app/(app)/financials/page.tsx index 774b10f..f11684a 100644 --- a/app/(app)/financials/page.tsx +++ b/app/(app)/financials/page.tsx @@ -1,7 +1,7 @@ import { redirect } from 'next/navigation' import Link from 'next/link' import { createClient } from '@/lib/supabase/server' -import type { FinancialVisibility, Payment, Space } from '@/lib/types' +import type { FinancialVisibility, Payment, Space } from '@/types/domain' import { Receipt } from 'lucide-react' import { PageTitle } from '@/components/ui/page-title' import { Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription } from '@/components/ui/empty' diff --git a/app/(app)/forms/[id]/results/page.tsx b/app/(app)/forms/[id]/results/page.tsx index a2bc01d..0870487 100644 --- a/app/(app)/forms/[id]/results/page.tsx +++ b/app/(app)/forms/[id]/results/page.tsx @@ -30,7 +30,16 @@ export default async function FormResultsPage({ params }: { params: Promise<{ id formId={form.id} title={form.title} fields={parseFormSchema(form.schema)} - submissions={submissions ?? []} + submissions={ + (submissions ?? []) as { + id: string + member_id: string | null + submitter_email: string | null + answers: Record | null + form_version: number + created_at: string + }[] + } /> ) } diff --git a/app/(app)/forms/[id]/results/results-client.tsx b/app/(app)/forms/[id]/results/results-client.tsx index c06ad23..8678ba9 100644 --- a/app/(app)/forms/[id]/results/results-client.tsx +++ b/app/(app)/forms/[id]/results/results-client.tsx @@ -51,6 +51,7 @@ export function ResultsClient({ toast.error(res.error || 'Export failed') return } + if (!res.data) return const { filename, csv } = res.data const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' }) const url = URL.createObjectURL(blob) diff --git a/app/(app)/import/import-client.tsx b/app/(app)/import/import-client.tsx index d8414bd..76eb492 100644 --- a/app/(app)/import/import-client.tsx +++ b/app/(app)/import/import-client.tsx @@ -4,6 +4,7 @@ import { useState, useRef, useCallback, useMemo } from 'react' import { Upload, CheckCircle, AlertCircle, X, ChevronDown, ArrowRight, FileText, RefreshCcw } from 'lucide-react' import { toast } from 'sonner' import { importPaymentsCsv, importMembers } from '@/lib/actions' +import { parsePaymentRow, type ParsedPaymentRow } from '@/lib/import-logic' // ─── Lightweight CSV parser (handles quoted fields, no external deps) ────────── function parseCSV(text: string): { headers: string[]; rows: string[][] } { @@ -196,85 +197,81 @@ export default function ImportClient({ role }: Props) { const errors: string[] = [] let success = 0 - if (mode === 'payments') { - const paymentRows = rows.map((row, i) => { - const obj: Record = {} - headers.forEach((h, j) => { - if (columnMap[h] && columnMap[h] !== 'skip') obj[columnMap[h]] = row[j] ?? '' + // try/finally so a thrown error can never leave the button wedged on + // 'Importing...' — setImporting(false) always runs. + try { + if (mode === 'payments') { + const paymentRows: ParsedPaymentRow[] = [] + rows.forEach((row, i) => { + const obj: Record = {} + headers.forEach((h, j) => { + if (columnMap[h] && columnMap[h] !== 'skip') obj[columnMap[h]] = row[j] ?? '' + }) + // Row 1 is the header, so rows[i] is spreadsheet row i + 2. The parse + // guards the date: 'N/A' and friends become a skipped row, not a throw. + const parsed = parsePaymentRow(obj, i + 2) + if (parsed.ok) paymentRows.push(parsed.value) + else errors.push(parsed.error) }) - const amount = parseFloat((obj.amount ?? '').replace(/[$,\s]/g, '')) - if (isNaN(amount) || !obj.from_identifier || !obj.transaction_date) { - errors.push(`Row ${i + 2}: missing required fields`) - return null - } - return { - platform: (obj.platform || 'csv') as any, - amount, - from_identifier: obj.from_identifier, - from_note: obj.from_note, - transaction_date: new Date(obj.transaction_date).toISOString(), - } - }).filter(Boolean) as any[] - const result = await importPaymentsCsv(paymentRows) - if ('error' in result && result.error) { - toast.error(result.error) - setImporting(false) - return - } - success = (result as any).count ?? paymentRows.length - - } else { - // Members import goes through the validated, admin-gated server action - // (Zod per row, batched upsert on (space_id,email), user_id left NULL - // for offline members). No direct client DB writes. - const tierMap: Record = { - plus: 'plus', premium: 'plus', full: 'plus', - basic: 'basic', member: 'basic', standard: 'basic', - associate: 'associate', visitor: 'associate', guest: 'associate', - } - const memberRows = rows.map((row, i) => { - const obj: Record = {} - headers.forEach((h, j) => { - if (columnMap[h] && columnMap[h] !== 'skip') obj[columnMap[h]] = row[j] ?? '' - }) - if (!obj.display_name || !obj.email) { - errors.push(`Row ${i + 2}: missing name or email`) - return null + const result = await importPaymentsCsv(paymentRows) + if ('error' in result && result.error) { + toast.error(result.error) + return } - return { - display_name: obj.display_name, - email: obj.email, - phone: obj.phone || null, - tier: tierMap[(obj.tier || '').toLowerCase()] || 'basic', - joined_at: obj.joined_at || undefined, - last_paid_at: obj.last_paid_at || undefined, - has_card_access: /yes|true|1|y/i.test(obj.has_card_access ?? ''), - } - }).filter(Boolean) as Array> + success = result.count ?? paymentRows.length - if (memberRows.length === 0) { - toast.error('No valid rows to import') - setImporting(false) - return + } else { + // Members import goes through the validated, admin-gated server action + // (Zod per row, batched upsert on (space_id,email), user_id left NULL + // for offline members). No direct client DB writes. + const tierMap: Record = { + plus: 'plus', premium: 'plus', full: 'plus', + basic: 'basic', member: 'basic', standard: 'basic', + associate: 'associate', visitor: 'associate', guest: 'associate', + } + const memberRows = rows.map((row, i) => { + const obj: Record = {} + headers.forEach((h, j) => { + if (columnMap[h] && columnMap[h] !== 'skip') obj[columnMap[h]] = row[j] ?? '' + }) + if (!obj.display_name || !obj.email) { + errors.push(`Row ${i + 2}: missing name or email`) + return null + } + return { + display_name: obj.display_name, + email: obj.email, + phone: obj.phone || null, + tier: tierMap[(obj.tier || '').toLowerCase()] || 'basic', + joined_at: obj.joined_at || undefined, + last_paid_at: obj.last_paid_at || undefined, + has_card_access: /yes|true|1|y/i.test(obj.has_card_access ?? ''), + } + }).filter(Boolean) as Array> + + if (memberRows.length === 0) { + toast.error('No valid rows to import') + return + } + + const result = await importMembers(memberRows) + if ('error' in result && result.error) { + toast.error(result.error) + return + } + const r = result as { count: number; skipped: number } + success = r.count + if (r.skipped > 0) errors.push(`${r.skipped} row(s) skipped (invalid email, name, tier, or date)`) } - const result = await importMembers(memberRows) - if ('error' in result && result.error) { - toast.error(result.error) - setImporting(false) - return - } - const r = result as { count: number; skipped: number } - success = r.count - if (r.skipped > 0) errors.push(`${r.skipped} row(s) skipped (invalid email, name, tier, or date)`) + setResult({ success, failed: errors.length, errors }) + setStep(3) + if (success > 0) toast.success(`Imported ${success} ${mode === 'members' ? 'members' : 'payments'}`) + if (errors.length > 0) toast.error(`${errors.length} rows failed`) + } finally { + setImporting(false) } - - setImporting(false) - setResult({ success, failed: errors.length, errors }) - setStep(3) - if (success > 0) toast.success(`Imported ${success} ${mode === 'members' ? 'members' : 'payments'}`) - if (errors.length > 0) toast.error(`${errors.length} rows failed`) } function reset() { diff --git a/app/(app)/incidents/[id]/incident-actions.tsx b/app/(app)/incidents/[id]/incident-actions.tsx index 47af991..b347c6e 100644 --- a/app/(app)/incidents/[id]/incident-actions.tsx +++ b/app/(app)/incidents/[id]/incident-actions.tsx @@ -8,7 +8,7 @@ import { addIncidentUpdate, appealIncident, } from '@/lib/actions' -import type { IncidentStatus } from '@/lib/types' +import type { IncidentStatus } from '@/types/domain' import { incidentStatuses, incidentUpdateVisibilities } from '@/lib/validations' type Props = { diff --git a/app/(app)/incidents/[id]/page.tsx b/app/(app)/incidents/[id]/page.tsx index 0d5ccaa..b8e0720 100644 --- a/app/(app)/incidents/[id]/page.tsx +++ b/app/(app)/incidents/[id]/page.tsx @@ -1,7 +1,7 @@ import Link from 'next/link' import { redirect, notFound } from 'next/navigation' import { createClient } from '@/lib/supabase/server' -import type { Incident, IncidentUpdateRow } from '@/lib/types' +import type { Incident, IncidentUpdateRow } from '@/types/domain' import { IncidentActions } from './incident-actions' import { MarkdownBody } from '@/components/markdown' import { CommentThread } from '@/components/comments/comment-thread' diff --git a/app/(app)/incidents/page.tsx b/app/(app)/incidents/page.tsx index 170d6c4..1d9e068 100644 --- a/app/(app)/incidents/page.tsx +++ b/app/(app)/incidents/page.tsx @@ -2,7 +2,7 @@ import Link from 'next/link' import { redirect } from 'next/navigation' import { ShieldCheck } from 'lucide-react' import { createClient } from '@/lib/supabase/server' -import type { Incident, IncidentStatus } from '@/lib/types' +import type { Incident, IncidentStatus } from '@/types/domain' import { PageTitle } from '@/components/ui/page-title' import { Empty, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty' diff --git a/app/(app)/me/page.tsx b/app/(app)/me/page.tsx index 16b4a3d..b1d6a86 100644 --- a/app/(app)/me/page.tsx +++ b/app/(app)/me/page.tsx @@ -98,10 +98,10 @@ export default async function MePage() { })) const signupRes = await getMyClassSignups() - const classSignups: ClassSignup[] = 'data' in signupRes ? (signupRes.data as ClassSignup[]) : [] + const classSignups: ClassSignup[] = 'data' in signupRes ? (signupRes.data ?? []) : [] const reservationRes = await getMyReservations() - const reservations: Reservation[] = 'data' in reservationRes ? (reservationRes.data as Reservation[]) : [] + const reservations: Reservation[] = 'data' in reservationRes ? (reservationRes.data ?? []) : [] const cardsRes = await getMyCards() const myCards: MyCard[] = 'data' in cardsRes ? (cardsRes.data as MyCard[]) : [] @@ -121,7 +121,7 @@ export default async function MePage() { const notifsRes = await getMyNotifications() const notifs: MyNotif[] = 'data' in notifsRes ? (notifsRes.data as MyNotif[]) : [] - const unreadNotifs = 'unreadCount' in notifsRes ? notifsRes.unreadCount : 0 + const unreadNotifs = 'unreadCount' in notifsRes ? (notifsRes.unreadCount ?? 0) : 0 const notifPrefsRes = await getMyNotificationPreferences() const notifPrefs: PrefMap = 'data' in notifPrefsRes ? notifPrefsRes.data : {} diff --git a/app/(app)/members/components/member-form-dialog.tsx b/app/(app)/members/components/member-form-dialog.tsx new file mode 100644 index 0000000..56b5044 --- /dev/null +++ b/app/(app)/members/components/member-form-dialog.tsx @@ -0,0 +1,109 @@ +'use client' + +import type { Dispatch, SetStateAction } from 'react' +import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import type { MemberForm } from '../types' + +// Top-level (NOT defined inside the render body): keeping this stable is what +// preserves input focus across keystrokes. The add and edit dialogs both render it. +function MemberFormFields({ form, setForm }: { form: MemberForm; setForm: Dispatch> }) { + return ( + <> +
+
+ + setForm(f => ({ ...f, display_name: e.target.value }))} + className="w-full bg-background border border-border rounded px-3 py-2 font-sans text-sm text-foreground focus:outline-none focus:border-primary transition" /> +
+
+ + setForm(f => ({ ...f, email: e.target.value }))} + className="w-full bg-background border border-border rounded px-3 py-2 font-sans text-sm text-foreground focus:outline-none focus:border-primary transition" /> +
+
+
+
+ + setForm(f => ({ ...f, phone: e.target.value }))} + className="w-full bg-background border border-border rounded px-3 py-2 font-sans text-sm text-foreground focus:outline-none focus:border-primary transition" /> +
+
+ + setForm(f => ({ ...f, handle: e.target.value }))} + className="w-full bg-background border border-border rounded px-3 py-2 font-mono text-sm text-foreground focus:outline-none focus:border-primary transition" /> +
+
+
+
+ + +
+
+ + +
+
+
+
+ + setForm(f => ({ ...f, joined_at: e.target.value }))} + className="w-full bg-background border border-border rounded px-3 py-2 font-sans text-sm text-foreground focus:outline-none focus:border-primary" /> +
+
+ +
+
+ + ) +} + +interface MemberFormDialogProps { + open: boolean + // Drives title + submit-button copy; add and edit share one form-state shape. + isEdit: boolean + memberName?: string | null + form: MemberForm + setForm: Dispatch> + loading: boolean + error: string + onSubmit: (e: React.FormEvent) => void + onClose: () => void +} + +export function MemberFormDialog({ open, isEdit, memberName, form, setForm, loading, error, onSubmit, onClose }: MemberFormDialogProps) { + return ( + { if (!o) onClose() }}> + + + {isEdit ? <>Edit {memberName} : 'Add Member'} + +
+ + {error &&

{error}

} +
+ + +
+ +
+
+ ) +} diff --git a/app/(app)/members/components/members-table.tsx b/app/(app)/members/components/members-table.tsx new file mode 100644 index 0000000..a359470 --- /dev/null +++ b/app/(app)/members/components/members-table.tsx @@ -0,0 +1,344 @@ +'use client' + +import { useState, type Dispatch, type SetStateAction } from 'react' +import { Users } from 'lucide-react' +import { Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription } from '@/components/ui/empty' +import type { Member, SortKey, AreaLeadRole } from '../types' + +const TIER_COLORS: Record = { + plus: 'text-blue-600 bg-blue-50 border-blue-200', + basic: 'text-muted-foreground bg-muted border-border', + associate: 'text-purple-600 bg-purple-50 border-purple-200', + admin: 'text-primary bg-primary/5 border-primary/20', +} + +interface MembersTableProps { + // Already filtered by the orchestrator; the table owns only its sort order. + members: Member[] + isAdmin: boolean + canGrantCerts: boolean + canManageCards: boolean + canViewForms: boolean + areaLeadRoles: AreaLeadRole[] + selected: Set + setSelected: Dispatch>> + toggleSel: (id: string) => void + onApprove: (memberId: string) => void + onRemove: (memberId: string) => void + onEdit: (m: Member) => void + onCerts: (m: Member) => void + onCards: (m: Member) => void + onForms: (m: Member) => void + onMakeAreaLead: (memberId: string, areaLeadRoleId: string) => void +} + +export function MembersTable({ + members: filteredMembers, + isAdmin, + canGrantCerts, + canManageCards, + canViewForms, + areaLeadRoles, + selected, + setSelected, + toggleSel, + onApprove, + onRemove, + onEdit, + onCerts, + onCards, + onForms, + onMakeAreaLead, +}: MembersTableProps) { + const [sort, setSort] = useState<{ key: SortKey; dir: 'asc' | 'desc' } | null>(null) + + const sortedMembers = sort + ? [...filteredMembers].sort((a, b) => { + const dir = sort.dir === 'asc' ? 1 : -1 + const val = (m: Member): string => { + switch (sort.key) { + case 'name': return (m.display_name ?? '').toLowerCase() + case 'tier': return m.tier ?? '' + case 'status': return m.status ?? '' + case 'joined': return m.joined_at ?? '' + case 'last_payment': return (m.last_paid_at || m.last_payment_at || '') as string + default: return '' + } + } + return val(a).localeCompare(val(b)) * dir + }) + : filteredMembers + + function toggleSort(key: SortKey) { + setSort(s => + s && s.key === key + ? (s.dir === 'asc' ? { key, dir: 'desc' } : null) + : { key, dir: 'asc' }, + ) + } + const caret = (key: SortKey) => (sort?.key === key ? (sort.dir === 'asc' ? ' ↑' : ' ↓') : '') + + return ( +
+
+ + + + {isAdmin && ( + + )} + {([ + ['name', 'MEMBER', ''], + ['tier', 'TIER', ''], + ['joined', 'JOINED', 'hidden md:table-cell'], + ['last_payment', 'LAST PAYMENT', 'hidden lg:table-cell'], + ['status', 'STATUS', ''], + ] as [SortKey, string, string][]).map(([key, label, cls]) => ( + + ))} + {canGrantCerts && ( + + )} + {canManageCards && ( + + )} + {canViewForms && ( + + )} + {isAdmin && ( + + )} + + + + {sortedMembers.length > 0 ? sortedMembers.map(m => { + const initials = (m.display_name || 'U').split(' ').map((n: string) => n[0]).join('').toUpperCase().slice(0, 2) + const hasIssue = m.payment_status && m.payment_status !== 'current' + return ( + + {isAdmin && ( + + )} + + + + + + {canGrantCerts && ( + + )} + {canManageCards && ( + + )} + {canViewForms && ( + + )} + {isAdmin && ( + + )} + + ) + }) : ( + + + + )} + +
+ 0 && sortedMembers.every(m => selected.has(m.id))} + onChange={e => + setSelected(e.target.checked ? new Set(sortedMembers.map(m => m.id)) : new Set()) + } + /> + + + CERTSCARDSFORMSACTIONS
+ toggleSel(m.id)} + /> + +
+
+ {initials} +
+
+

{m.display_name}

+

+ {m.email}{m.handle ? ` · @${m.handle}` : ''}{m.payment_note ? ` — ${m.payment_note}` : ''} +

+
+
+
+ + {m.tier?.toUpperCase()} + + + {m.joined_at ? new Date(m.joined_at).toLocaleDateString('en-US', { month: 'short', year: 'numeric' }) : '-'} + + {(m.last_paid_at || m.last_payment_at) ? new Date((m.last_paid_at || m.last_payment_at)!).toLocaleDateString('en-US', { month: 'short', year: 'numeric' }) : '-'} + + {m.status === 'unverified' ? ( + + unverified + + ) : m.payment_status === 'current' ? ( + + current + + ) : m.payment_status ? ( + + {m.payment_status} + + ) : ( + {m.status} + )} + + + + + + + +
+ {m.status === 'unverified' && ( + + )} + + + {areaLeadRoles.length > 0 && ( + + )} +
+
+ + + + No members match this filter + Try a different tab, clear the search, or change the tier filter. + + +
+
+ + {/* Mobile: stacked cards (the table is unusable on phones). */} +
+ {sortedMembers.length > 0 ? sortedMembers.map(m => { + const hasIssue = m.payment_status && m.payment_status !== 'current' + return ( +
+
+
+ {isAdmin && ( + toggleSel(m.id)} + /> + )} +
+

{m.display_name}

+

{m.email}

+
+
+ + {m.tier?.toUpperCase()} + +
+

+ {m.status === 'unverified' ? 'unverified' : (m.payment_status || m.status)} + {m.joined_at ? ` · joined ${new Date(m.joined_at).toLocaleDateString('en-US', { month: 'short', year: 'numeric' })}` : ''} +

+
+ {isAdmin && m.status === 'unverified' && ( + + )} + {isAdmin && ( + + )} + {canGrantCerts && ( + + )} + {canManageCards && ( + + )} + {canViewForms && ( + + )} + {isAdmin && ( + + )} +
+
+ ) + }) : ( + + + + No members match this filter + Try a different tab, clear the search, or change the tier filter. + + + )} +
+
+ ) +} diff --git a/app/(app)/members/components/members-toolbar.tsx b/app/(app)/members/components/members-toolbar.tsx new file mode 100644 index 0000000..b5106f1 --- /dev/null +++ b/app/(app)/members/components/members-toolbar.tsx @@ -0,0 +1,97 @@ +'use client' + +import type { Dispatch, SetStateAction } from 'react' +import type { MemberTab } from '../types' + +interface MembersTabsProps { + activeTab: MemberTab + setActiveTab: Dispatch> + total: number + paymentIssues: number + unverified: number +} + +// Full-bleed tab bar (sits directly under the page header, outside the padded +// content region), so it is its own component rather than part of the filters. +export function MembersTabs({ activeTab, setActiveTab, total, paymentIssues, unverified }: MembersTabsProps) { + return ( +
+ {[ + { key: 'all', label: `All ${total}` }, + { key: 'payment_issues', label: `Payment Issues ${paymentIssues}` }, + { key: 'unverified', label: `Pending Approval ${unverified}` }, + { key: 'inactive', label: 'Inactive' }, + ].map(({ key, label }) => ( + + ))} +
+ ) +} + +interface MembersToolbarProps { + search: string + setSearch: Dispatch> + tierFilter: string + setTierFilter: Dispatch> + canBulk: boolean + selectedCount: number + onBulkApprove: () => void + onClearSelection: () => void +} + +// Search + tier filter row, plus the bulk-actions bar shown when a selection +// exists. Renders as a fragment so the surrounding padded content div is +// unchanged. +export function MembersToolbar({ search, setSearch, tierFilter, setTierFilter, canBulk, selectedCount, onBulkApprove, onClearSelection }: MembersToolbarProps) { + return ( + <> +
+
+ + + + setSearch(e.target.value)} + className="w-full bg-card border border-border rounded pl-9 pr-4 py-2 font-sans text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:border-primary transition" + /> +
+ +
+ + {canBulk && selectedCount > 0 && ( +
+ {selectedCount} selected + + + + +
+ )} + + ) +} diff --git a/app/(app)/members/members-client.tsx b/app/(app)/members/members-client.tsx index dce777f..840b66c 100644 --- a/app/(app)/members/members-client.tsx +++ b/app/(app)/members/members-client.tsx @@ -1,59 +1,54 @@ 'use client' -import { useState, type ReactNode } from 'react' -import { Plus, ChevronDown, Users } from 'lucide-react' -import { Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription } from '@/components/ui/empty' -import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { useState } from 'react' +import { Plus } from 'lucide-react' import { addMember, updateMember, approveMember, bulkApproveMembers, removeMember, assignAreaLead } from '@/lib/actions' import { toast } from 'sonner' import { useRouter } from 'next/navigation' -import type { Tables } from '@/types/database' import { PageTitle } from '@/components/ui/page-title' import { useConfirm } from '@/components/ui/confirm' import { MemberCertificationsDialog } from '@/components/certifications/member-certifications-dialog' import { MemberCardsDialog } from '@/components/door/member-cards-dialog' import { MemberFormsDialog } from '@/components/forms/member-forms-dialog' - -type Member = Tables<'space_members'> -type SortKey = 'name' | 'tier' | 'joined' | 'last_payment' | 'status' -type AreaLeadRole = { id: string; area_name: string; lead_id: string | null } - -interface Props { - members: Member[] - currentRole: string - areaLeadRoles?: AreaLeadRole[] - // Composed by the server page for admin/board: the existing InvitesPanel, - // so the members page is a real place to create and share a join link - // (the first-run "Invite or add members" step lands here). - inviteSlot?: ReactNode - // True when the viewer holds certifications.grant (the Instructor - // capability), independent of admin/board. Adds a per-member - // certifications panel reachable by non-admin instructors. - canGrantCerts?: boolean - // True when the viewer holds door.manage. Adds a per-member access-cards - // panel (card UID is a credential; managers only). - canManageCards?: boolean - // True when the viewer holds forms.manage. Adds a per-member panel - // listing the forms that member has submitted. - canViewForms?: boolean -} - -const TIER_COLORS: Record = { - plus: 'text-blue-600 bg-blue-50 border-blue-200', - basic: 'text-muted-foreground bg-muted border-border', - associate: 'text-purple-600 bg-purple-50 border-purple-200', - admin: 'text-primary bg-primary/5 border-primary/20', -} +import { MembersTabs, MembersToolbar } from './components/members-toolbar' +import { MembersTable } from './components/members-table' +import { MemberFormDialog } from './components/member-form-dialog' +import type { Member, MemberForm, MemberTab, MembersClientProps } from './types' const isAdmin = (role: string) => role === 'admin' || role === 'board' -export function MembersClient({ members: initialMembers, currentRole, areaLeadRoles = [], inviteSlot, canGrantCerts = false, canManageCards = false, canViewForms = false }: Props) { +export function MembersClient({ members: initialMembers, currentRole, areaLeadRoles = [], inviteSlot, canGrantCerts = false, canManageCards = false, canViewForms = false }: MembersClientProps) { const router = useRouter() + const confirm = useConfirm() + const admin = isAdmin(currentRole) + + const [members, setMembers] = useState(initialMembers) const [certMember, setCertMember] = useState(null) const [cardMember, setCardMember] = useState(null) const [formsMember, setFormsMember] = useState(null) - const confirm = useConfirm() - const [members, setMembers] = useState(initialMembers) + + const [activeTab, setActiveTab] = useState('all') + const [search, setSearch] = useState('') + const [tierFilter, setTierFilter] = useState('') + const [selected, setSelected] = useState>(new Set()) + + const [showAdd, setShowAdd] = useState(false) + const [editMember, setEditMember] = useState(null) + const [loading, setLoading] = useState(false) + const [error, setError] = useState('') + + // Add/Edit form + const [form, setForm] = useState({ + display_name: '', email: '', phone: '', handle: '', + tier: 'basic', role: 'member', joined_at: '', has_card_access: false, + }) + + const toggleSel = (id: string) => + setSelected(prev => { + const n = new Set(prev) + n.has(id) ? n.delete(id) : n.add(id) + return n + }) async function makeAreaLead(memberId: string, areaLeadRoleId: string) { if (!areaLeadRoleId) return @@ -62,18 +57,7 @@ export function MembersClient({ members: initialMembers, currentRole, areaLeadRo toast.success('Assigned as area lead') router.refresh() } - const [activeTab, setActiveTab] = useState<'all' | 'payment_issues' | 'unverified' | 'inactive'>('all') - const [search, setSearch] = useState('') - const [tierFilter, setTierFilter] = useState('') - const [sort, setSort] = useState<{ key: SortKey; dir: 'asc' | 'desc' } | null>(null) - const [selected, setSelected] = useState>(new Set()) - const canBulk = isAdmin(currentRole) - const toggleSel = (id: string) => - setSelected(prev => { - const n = new Set(prev) - n.has(id) ? n.delete(id) : n.add(id) - return n - }) + async function bulkApprove() { const ids = [...selected] if (ids.length === 0) return @@ -84,16 +68,6 @@ export function MembersClient({ members: initialMembers, currentRole, areaLeadRo setSelected(new Set()) toast.success(n > 0 ? `Approved ${n} member(s)` : 'No unverified members in the selection') } - const [showAdd, setShowAdd] = useState(false) - const [editMember, setEditMember] = useState(null) - const [loading, setLoading] = useState(false) - const [error, setError] = useState('') - - // Add/Edit form - const [form, setForm] = useState({ - display_name: '', email: '', phone: '', handle: '', - tier: 'basic', role: 'member', joined_at: '', has_card_access: false, - }) const total = members.length const paymentIssues = members.filter(m => m.status === 'current' && m.payment_status && m.payment_status !== 'current').length @@ -106,42 +80,20 @@ export function MembersClient({ members: initialMembers, currentRole, areaLeadRo activeTab === 'unverified' ? m.status === 'unverified' : m.status === 'inactive' + // display_name and email are both nullable (e.g. imported members), so + // guard before .toLowerCase() — an unguarded access crashed the whole list + // the moment an admin typed into the search box. + const q = search.toLowerCase() const matchesSearch = !search || - m.display_name.toLowerCase().includes(search.toLowerCase()) || - m.email.toLowerCase().includes(search.toLowerCase()) || - (m.handle?.toLowerCase().includes(search.toLowerCase()) ?? false) + (m.display_name?.toLowerCase().includes(q) ?? false) || + (m.email?.toLowerCase().includes(q) ?? false) || + (m.handle?.toLowerCase().includes(q) ?? false) const matchesTier = !tierFilter || m.tier === tierFilter return matchesTab && matchesSearch && matchesTier }) - const sortedMembers = sort - ? [...filteredMembers].sort((a, b) => { - const dir = sort.dir === 'asc' ? 1 : -1 - const val = (m: Member): string => { - switch (sort.key) { - case 'name': return (m.display_name ?? '').toLowerCase() - case 'tier': return m.tier ?? '' - case 'status': return m.status ?? '' - case 'joined': return m.joined_at ?? '' - case 'last_payment': return (m.last_paid_at || m.last_payment_at || '') as string - default: return '' - } - } - return val(a).localeCompare(val(b)) * dir - }) - : filteredMembers - - function toggleSort(key: SortKey) { - setSort(s => - s && s.key === key - ? (s.dir === 'asc' ? { key, dir: 'desc' } : null) - : { key, dir: 'asc' }, - ) - } - const caret = (key: SortKey) => (sort?.key === key ? (sort.dir === 'asc' ? ' ↑' : ' ↓') : '') - async function handleAdd(e: React.FormEvent) { e.preventDefault() setLoading(true) @@ -161,7 +113,7 @@ export function MembersClient({ members: initialMembers, currentRole, areaLeadRo setError('') const result = await updateMember(editMember.id, form) if (result.error) { setError(result.error); setLoading(false); return } - setMembers(prev => prev.map(m => m.id === editMember.id ? { ...m, ...form } : m)) + setMembers(prev => prev.map(m => m.id === editMember.id ? { ...m, ...form } as Member : m)) setEditMember(null) setLoading(false) } @@ -182,8 +134,8 @@ export function MembersClient({ members: initialMembers, currentRole, areaLeadRo function openEdit(m: Member) { setEditMember(m) setForm({ - display_name: m.display_name, - email: m.email, + display_name: m.display_name ?? '', + email: m.email ?? '', phone: m.phone ?? '', handle: m.handle ?? '', tier: m.tier, @@ -194,71 +146,6 @@ export function MembersClient({ members: initialMembers, currentRole, areaLeadRo setError('') } - const MemberFormFields = () => ( - <> -
-
- - setForm(f => ({ ...f, display_name: e.target.value }))} - className="w-full bg-background border border-border rounded px-3 py-2 font-sans text-sm text-foreground focus:outline-none focus:border-primary transition" /> -
-
- - setForm(f => ({ ...f, email: e.target.value }))} - className="w-full bg-background border border-border rounded px-3 py-2 font-sans text-sm text-foreground focus:outline-none focus:border-primary transition" /> -
-
-
-
- - setForm(f => ({ ...f, phone: e.target.value }))} - className="w-full bg-background border border-border rounded px-3 py-2 font-sans text-sm text-foreground focus:outline-none focus:border-primary transition" /> -
-
- - setForm(f => ({ ...f, handle: e.target.value }))} - className="w-full bg-background border border-border rounded px-3 py-2 font-mono text-sm text-foreground focus:outline-none focus:border-primary transition" /> -
-
-
-
- - -
-
- - -
-
-
-
- - setForm(f => ({ ...f, joined_at: e.target.value }))} - className="w-full bg-background border border-border rounded px-3 py-2 font-sans text-sm text-foreground focus:outline-none focus:border-primary" /> -
-
- -
-
- - ) - return (
@@ -266,7 +153,7 @@ export function MembersClient({ members: initialMembers, currentRole, areaLeadRo Members {total} total
- {isAdmin(currentRole) && ( + {admin && (
-
- {[ - { key: 'all', label: `All ${total}` }, - { key: 'payment_issues', label: `Payment Issues ${paymentIssues}` }, - { key: 'unverified', label: `Pending Approval ${unverified}` }, - { key: 'inactive', label: 'Inactive' }, - ].map(({ key, label }) => ( - - ))} -
+
{inviteSlot &&
{inviteSlot}
} -
-
- - - - setSearch(e.target.value)} - className="w-full bg-card border border-border rounded pl-9 pr-4 py-2 font-sans text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:border-primary transition" - /> -
- -
- {canBulk && selected.size > 0 && ( -
- {selected.size} selected - - - - -
- )} + setSelected(new Set())} + /> -
-
- - - - {canBulk && ( - - )} - {([ - ['name', 'MEMBER', ''], - ['tier', 'TIER', ''], - ['joined', 'JOINED', 'hidden md:table-cell'], - ['last_payment', 'LAST PAYMENT', 'hidden lg:table-cell'], - ['status', 'STATUS', ''], - ] as [SortKey, string, string][]).map(([key, label, cls]) => ( - - ))} - {canGrantCerts && ( - - )} - {canManageCards && ( - - )} - {canViewForms && ( - - )} - {isAdmin(currentRole) && ( - - )} - - - - {sortedMembers.length > 0 ? sortedMembers.map(m => { - const initials = (m.display_name || 'U').split(' ').map((n: string) => n[0]).join('').toUpperCase().slice(0, 2) - const hasIssue = m.payment_status && m.payment_status !== 'current' - return ( - - {canBulk && ( - - )} - - - - - - {canGrantCerts && ( - - )} - {canManageCards && ( - - )} - {canViewForms && ( - - )} - {isAdmin(currentRole) && ( - - )} - - ) - }) : ( - - - - )} - -
- 0 && sortedMembers.every(m => selected.has(m.id))} - onChange={e => - setSelected(e.target.checked ? new Set(sortedMembers.map(m => m.id)) : new Set()) - } - /> - - - CERTSCARDSFORMSACTIONS
- toggleSel(m.id)} - /> - -
-
- {initials} -
-
-

{m.display_name}

-

- {m.email}{m.handle ? ` · @${m.handle}` : ''}{m.payment_note ? ` — ${m.payment_note}` : ''} -

-
-
-
- - {m.tier?.toUpperCase()} - - - {m.joined_at ? new Date(m.joined_at).toLocaleDateString('en-US', { month: 'short', year: 'numeric' }) : '-'} - - {(m.last_paid_at || m.last_payment_at) ? new Date((m.last_paid_at || m.last_payment_at)!).toLocaleDateString('en-US', { month: 'short', year: 'numeric' }) : '-'} - - {m.status === 'unverified' ? ( - - unverified - - ) : m.payment_status === 'current' ? ( - - current - - ) : m.payment_status ? ( - - {m.payment_status} - - ) : ( - {m.status} - )} - - - - - - - -
- {m.status === 'unverified' && ( - - )} - - - {areaLeadRoles.length > 0 && ( - - )} -
-
- - - - No members match this filter - Try a different tab, clear the search, or change the tier filter. - - -
-
- - {/* Mobile: stacked cards (the table is unusable on phones). */} -
- {sortedMembers.length > 0 ? sortedMembers.map(m => { - const hasIssue = m.payment_status && m.payment_status !== 'current' - return ( -
-
-
- {canBulk && ( - toggleSel(m.id)} - /> - )} -
-

{m.display_name}

-

{m.email}

-
-
- - {m.tier?.toUpperCase()} - -
-

- {m.status === 'unverified' ? 'unverified' : (m.payment_status || m.status)} - {m.joined_at ? ` · joined ${new Date(m.joined_at).toLocaleDateString('en-US', { month: 'short', year: 'numeric' })}` : ''} -

-
- {isAdmin(currentRole) && m.status === 'unverified' && ( - - )} - {isAdmin(currentRole) && ( - - )} - {canGrantCerts && ( - - )} - {canManageCards && ( - - )} - {canViewForms && ( - - )} - {isAdmin(currentRole) && ( - - )} -
-
- ) - }) : ( - - - - No members match this filter - Try a different tab, clear the search, or change the tier filter. - - - )} -
-
+
{/* Add Member Modal */} - { if (!o) setShowAdd(false) }}> - - - Add Member - -
- - {error &&

{error}

} -
- - -
- -
-
+ setShowAdd(false)} + /> {/* Edit Member Modal */} - { if (!o) setEditMember(null) }}> - - - Edit {editMember?.display_name} - -
- - {error &&

{error}

} -
- - -
- -
-
+ setEditMember(null)} + /> {canGrantCerts && ( + +export type SortKey = 'name' | 'tier' | 'joined' | 'last_payment' | 'status' + +export type MemberTab = 'all' | 'payment_issues' | 'unverified' | 'inactive' + +export type AreaLeadRole = { id: string; area_name: string; lead_id: string | null } + +// The add/edit form shares one state shape; both dialogs write into it. +export interface MemberForm { + display_name: string + email: string + phone: string + handle: string + tier: string + role: string + joined_at: string + has_card_access: boolean +} + +export interface MembersClientProps { + members: Member[] + currentRole: string + areaLeadRoles?: AreaLeadRole[] + // Composed by the server page for admin/board: the existing InvitesPanel, + // so the members page is a real place to create and share a join link + // (the first-run "Invite or add members" step lands here). + inviteSlot?: ReactNode + // True when the viewer holds certifications.grant (the Instructor + // capability), independent of admin/board. Adds a per-member + // certifications panel reachable by non-admin instructors. + canGrantCerts?: boolean + // True when the viewer holds door.manage. Adds a per-member access-cards + // panel (card UID is a credential; managers only). + canManageCards?: boolean + // True when the viewer holds forms.manage. Adds a per-member panel + // listing the forms that member has submitted. + canViewForms?: boolean +} diff --git a/app/(app)/ops/[id]/kb-entry-editor.tsx b/app/(app)/ops/[id]/kb-entry-editor.tsx index 445415c..40821ac 100644 --- a/app/(app)/ops/[id]/kb-entry-editor.tsx +++ b/app/(app)/ops/[id]/kb-entry-editor.tsx @@ -96,7 +96,7 @@ export default function KbEntryEditor({ entry, member }: Props) { setAreaName(e.target.value)} className="w-full bg-background border border-border rounded px-3 py-2 font-sans text-sm text-foreground focus:outline-none focus:border-primary transition" placeholder="e.g. Woodshop" required /> + +
+ + setMemberName(e.target.value)} className="w-full bg-background border border-border rounded px-3 py-2 font-sans text-sm text-foreground focus:outline-none focus:border-primary transition" placeholder="e.g. Alice Smith" required /> +
+
+ + setContactInfo(e.target.value)} className="w-full bg-background border border-border rounded px-3 py-2 font-sans text-sm text-foreground focus:outline-none focus:border-primary transition" placeholder="e.g. alice@example.com or Slack @alice" /> +
+
+ + +
+ + + + ) +} diff --git a/app/(app)/ops/components/kb-entry-row.tsx b/app/(app)/ops/components/kb-entry-row.tsx new file mode 100644 index 0000000..bd580cd --- /dev/null +++ b/app/(app)/ops/components/kb-entry-row.tsx @@ -0,0 +1,129 @@ +'use client' + +import { useState } from 'react' +import { Pin, Pencil, Trash2 } from 'lucide-react' +import { SafeMarkdown } from '@/components/safe-markdown' +import { deleteKbEntry } from '@/lib/actions' +import { OpsAclEditor } from '@/components/ops/ops-acl-editor' +import { toast } from 'sonner' +import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { useConfirm } from '@/components/ui/confirm' +import type { AclRoleOption, KbEntry } from '../types' +import { VISIBILITY_LABELS, VISIBILITY_COLORS } from '../types' + +// ─── KB Entry Row ────────────────────────────────────────────────────────────── +export function KbEntryRow({ + entry, + onEdit, + onDelete, + canManageAcl, + aclRoleOptions, + aclByEntity, +}: { + entry: KbEntry + onEdit: (e: KbEntry) => void + onDelete: (id: string) => void + canManageAcl?: boolean + aclRoleOptions?: AclRoleOption[] + aclByEntity?: Record +}) { + const confirm = useConfirm() + const [viewing, setViewing] = useState(false) + const aclEntityType: 'kb' | 'process' = entry.tags?.includes('process') ? 'process' : 'kb' + const aclInitial = aclByEntity?.[`${aclEntityType}:${entry.id}`] ?? [] + + async function handleDelete(e: React.MouseEvent) { + e.stopPropagation() + if (!(await confirm({ title: 'Delete entry', description: `"${entry.title}" will be permanently removed.`, confirmText: 'Delete', destructive: true }))) return + const result = await deleteKbEntry(entry.id) + if ('error' in result && result.error) { toast.error(result.error); return } + toast.success('Entry deleted') + onDelete(entry.id) + } + + function handleEdit(e: React.MouseEvent) { + e.stopPropagation() + onEdit(entry) + } + + return ( + <> +
setViewing(true)} + className={`flex items-start gap-3 px-4 py-4 hover:bg-muted/20 transition group border-l-4 cursor-pointer ${ + entry.is_pinned + ? entry.visibility === 'admin_only' ? 'border-l-red-400' : entry.visibility === 'board' ? 'border-l-amber-400' : 'border-l-primary' + : 'border-l-transparent' + }`} + > +
+ {entry.icon || ( + + + + )} +
+
+
+

{entry.title}

+ {entry.is_pinned && } +
+

{entry.content?.slice(0, 120)}

+

+ {entry.area && {entry.area} · } + updated {new Date(entry.updated_at).toLocaleDateString()} by {entry.updated_by_name} +

+
+
+ + {VISIBILITY_LABELS[entry.visibility] ?? entry.visibility} + +
+ + +
+
+
+ + { if (!o) setViewing(false) }}> + + +
+
+
+ {entry.icon && {entry.icon}} + {entry.title} + {entry.is_pinned && } +
+

+ {entry.area && {entry.area} · } + {VISIBILITY_LABELS[entry.visibility] ?? entry.visibility} + {' · '} + updated {new Date(entry.updated_at).toLocaleDateString()} by {entry.updated_by_name ?? 'unknown'} +

+
+ +
+
+
+ {entry.content ?? ''} + {canManageAcl && ( + + )} +
+
+
+ + ) +} diff --git a/app/(app)/ops/components/kb-modal.tsx b/app/(app)/ops/components/kb-modal.tsx new file mode 100644 index 0000000..9b853a1 --- /dev/null +++ b/app/(app)/ops/components/kb-modal.tsx @@ -0,0 +1,142 @@ +'use client' + +import { useState } from 'react' +import { createKbEntry, updateKbEntry } from '@/lib/actions' +import { toast } from 'sonner' +import type { Enums } from '@/types/database' +import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import type { KbEntry } from '../types' + +// ─── KB Entry Modal ──────────────────────────────────────────────────────────── +export function KbModal({ + entry, + onClose, + onSaved, +}: { + entry: KbEntry | null + onClose: () => void + onSaved: (entry: KbEntry) => void +}) { + const isEdit = !!entry + const [title, setTitle] = useState(entry?.title ?? '') + const [content, setContent] = useState(entry?.content ?? '') + const [area, setArea] = useState(entry?.area ?? '') + const [visibility, setVisibility] = useState(entry?.visibility ?? 'all_members') + const [isPinned, setIsPinned] = useState(entry?.is_pinned ?? false) + const [isProcess, setIsProcess] = useState(entry?.tags?.includes('process') ?? false) + const [saving, setSaving] = useState(false) + + async function handleSave(e: React.FormEvent) { + e.preventDefault() + if (!title.trim() || !content.trim()) return + setSaving(true) + const tags = isProcess ? ['process'] : [] + let result + if (isEdit) { + result = await updateKbEntry(entry.id, { title, content, area, visibility, is_pinned: isPinned, tags }) + } else { + result = await createKbEntry({ title, content, area, visibility, is_pinned: isPinned, tags }) + } + setSaving(false) + if ('error' in result && result.error) { + toast.error(result.error) + return + } + toast.success(isEdit ? 'Entry updated' : 'Entry created') + if (!isEdit && 'data' in result && result.data) onSaved(result.data as KbEntry) + else if (isEdit) onSaved({ ...entry, title, content, area, visibility, is_pinned: isPinned, tags }) + onClose() + } + + return ( + { if (!o) onClose() }}> + + + {isEdit ? 'Edit Entry' : 'New KB Entry'} + +
+
+ + setTitle(e.target.value)} + className="w-full bg-background border border-border rounded px-3 py-2 font-sans text-sm text-foreground focus:outline-none focus:border-primary transition" + placeholder="e.g. How to open the space" + required + /> +
+
+ +