feat: governance kernel, deployment hardening, local-dev stack

Adds proposals + proposal_votes + policies + incidents + incident_updates
tables with full RLS, async voting flow, dismissal-appeal pathway,
versioned policies with provenance, and an anonymous-incident token mode.
Adds per-space configurable areas, financial visibility settings, member
self-profile + COI disclosure, and a mission statement that renders in
the app footer.

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

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

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

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

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

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

Full pass-by-pass history is in docs/HANDOFF.md; the roadmap is in
docs/GOVERNANCE_FEATURES.md.
This commit is contained in:
Moheeb Zara
2026-05-14 04:52:11 -07:00
parent 8b9128704b
commit ea8d7a5f91
99 changed files with 13823 additions and 1940 deletions
+44
View File
@@ -0,0 +1,44 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import { requireMemberWithRole, parseInput } from '@/lib/auth-helpers'
import { ADMIN_ROLES } from '@/lib/permissions'
import { upsertAreaLeadSchema } from '@/lib/validations'
export async function upsertAreaLead(formData: {
area_code: string
area_name: string
lead_id?: string
lead_handle?: string
status?: string
}) {
const v = parseInput(upsertAreaLeadSchema, formData)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ADMIN_ROLES, 'Admin access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { data, error } = await supabase
.from('area_leads')
.upsert(
{
space_id: member.space_id,
area_code: v.data.area_code,
area_name: v.data.area_name,
lead_id: v.data.lead_id ?? null,
lead_handle: v.data.lead_handle ?? null,
status: v.data.status,
updated_at: new Date().toISOString(),
},
{ onConflict: 'space_id,area_code' },
)
.select()
.single()
if (error) return { error: error.message }
revalidatePath('/ops')
return { data }
}
+111
View File
@@ -0,0 +1,111 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import { requireMemberWithRole, parseInput } from '@/lib/auth-helpers'
import { ADMIN_ROLES } from '@/lib/permissions'
import { createAreaSchema, updateAreaSchema, uuidSchema } from '@/lib/validations'
/**
* Add a new area to the current space. Admin / board only.
* `code` is the stable identifier (slug); `name` is what shows up in
* dropdowns. Renames change the name but keep the code, so existing
* tasks tagged with the old name will not auto-rename — admins re-tag
* if they care.
*/
export async function createArea(formData: {
code: string
name: string
icon?: string | null
sort_order?: number
}) {
const v = parseInput(createAreaSchema, formData)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ADMIN_ROLES, 'Admin or board access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { data, error } = await supabase
.from('space_areas')
.insert({
space_id: member.space_id,
code: v.data.code,
name: v.data.name,
icon: v.data.icon ?? null,
sort_order: v.data.sort_order ?? 100,
})
.select()
.single()
if (error) return { error: error.message }
revalidatePath('/settings')
revalidatePath('/tasks')
revalidatePath('/projects')
revalidatePath('/ops')
return { data }
}
/**
* Edit an area's name, icon, sort order, or archive state.
*/
export async function updateArea(formData: {
areaId: string
name?: string
icon?: string | null
sort_order?: number
is_archived?: boolean
}) {
const v = parseInput(updateAreaSchema, formData)
if (!v.ok) return { error: v.error }
const { areaId, ...patch } = v.data
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ADMIN_ROLES, 'Admin or board access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('space_areas')
.update(patch)
.eq('id', areaId)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
revalidatePath('/settings')
revalidatePath('/tasks')
revalidatePath('/projects')
revalidatePath('/ops')
return { success: true as const }
}
/**
* Delete an area entirely. Admin-only. Prefer archiving via
* `updateArea({ is_archived: true })` unless the area has never been used.
*/
export async function deleteArea(areaId: string) {
const v = parseInput(uuidSchema, areaId)
if (!v.ok) return { error: 'Invalid area ID' }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ['admin'], 'Admin access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('space_areas')
.delete()
.eq('id', v.data)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
revalidatePath('/settings')
revalidatePath('/tasks')
revalidatePath('/projects')
revalidatePath('/ops')
return { success: true as const }
}
+109
View File
@@ -0,0 +1,109 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import { requireMember, parseInput } from '@/lib/auth-helpers'
import {
createContactSchema,
updateContactSchema,
uuidSchema,
} from '@/lib/validations'
function generateContactCode(name: string): string {
const prefix = name.slice(0, 3).toUpperCase().replace(/[^A-Z]/g, 'X').padEnd(3, 'X')
const suffix = Math.floor(Math.random() * 900 + 100).toString()
return `${prefix}${suffix}`
}
export async function createContact(formData: {
name: string
contact_type: string
email?: string
phone?: string
details?: string
note?: string
group_label?: string
tags?: string[]
}) {
const v = parseInput(createContactSchema, formData)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { data, error } = await supabase
.from('contacts')
.insert({
space_id: member.space_id,
name: v.data.name,
contact_type: v.data.contact_type,
email: v.data.email ?? null,
phone: v.data.phone ?? null,
details: v.data.details ?? v.data.note ?? null,
note: v.data.note ?? null,
group_label: v.data.group_label ?? null,
tags: v.data.tags ?? [],
code: v.data.code ?? generateContactCode(v.data.name),
})
.select()
.single()
if (error) return { error: error.message }
revalidatePath('/contacts')
return { data }
}
export async function updateContact(
contactId: string,
updates: {
name?: string
contact_type?: string
email?: string
phone?: string
details?: string
note?: string
group_label?: string
tags?: string[]
},
) {
const v = parseInput(updateContactSchema, { contactId, ...updates })
if (!v.ok) return { error: v.error }
const { contactId: id, ...patch } = v.data
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('contacts')
.update({ ...patch, updated_at: new Date().toISOString() })
.eq('id', id)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
revalidatePath('/contacts')
return { success: true as const }
}
export async function deleteContact(contactId: string) {
const v = parseInput(uuidSchema, contactId)
if (!v.ok) return { error: 'Invalid contact ID' }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('contacts')
.delete()
.eq('id', v.data)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
revalidatePath('/contacts')
return { success: true as const }
}
+57
View File
@@ -0,0 +1,57 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import { requireMemberWithRole } from '@/lib/auth-helpers'
import { ADMIN_ROLES } from '@/lib/permissions'
export async function importMembers(
rows: Array<{
display_name: string
email: string
phone?: string
tier?: string
joined_at?: string
last_paid_at?: string
has_card_access?: boolean
}>,
) {
if (!Array.isArray(rows) || rows.length === 0) {
return { error: 'No rows to import' }
}
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ADMIN_ROLES, 'Admin access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const inserts = rows
.filter(r => typeof r.display_name === 'string' && typeof r.email === 'string')
.map(r => ({
space_id: member.space_id,
display_name: r.display_name,
email: r.email,
phone: r.phone ?? null,
tier: r.tier ?? 'basic',
role: 'member',
status: 'current',
approved: true,
joined_at: r.joined_at ?? new Date().toISOString(),
last_paid_at: r.last_paid_at ?? null,
has_card_access: r.has_card_access ?? false,
}))
if (inserts.length === 0) {
return { error: 'No valid rows to import' }
}
// Upsert by (space_id, email) to dedupe re-imports.
const { data, error } = await supabase
.from('space_members')
.upsert(inserts, { onConflict: 'space_id,email', ignoreDuplicates: false })
.select()
if (error) return { error: error.message }
revalidatePath('/members')
return { data, count: data.length }
}
+236
View File
@@ -0,0 +1,236 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import {
requireMember,
requireMemberWithRole,
logActivity,
parseInput,
} from '@/lib/auth-helpers'
import { ADMIN_ROLES } from '@/lib/permissions'
import {
fileIncidentSchema,
updateIncidentStatusSchema,
addIncidentUpdateSchema,
appealIncidentSchema,
} from '@/lib/validations'
/**
* Generate a short opaque tracking token for anonymous reports.
* 24 bytes of randomness, base64url-encoded. Reporter receives this once;
* server never reverses it to a member.
*/
function generateReporterToken(): string {
const bytes = crypto.getRandomValues(new Uint8Array(24))
return Array.from(bytes)
.map(b => b.toString(16).padStart(2, '0'))
.join('')
}
/**
* File an incident (CoC complaint, safety report, conflict). When
* is_anonymous=true the reporter_id is omitted and an opaque tracking
* token is generated; the caller MUST surface the token to the reporter
* because it is the only way to look the case up later.
*/
export async function fileIncident(formData: {
title: string
body: string
category?: string
severity?: string
subjects?: string[]
is_anonymous?: boolean
}) {
const v = parseInput(fileIncidentSchema, formData)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const isAnonymous = v.data.is_anonymous === true
const reporterToken = isAnonymous ? generateReporterToken() : null
const { data, error } = await supabase
.from('incidents')
.insert({
space_id: member.space_id,
reporter_id: isAnonymous ? null : member.id,
reporter_token: reporterToken,
is_anonymous: isAnonymous,
subjects: v.data.subjects ?? [],
category: v.data.category,
severity: v.data.severity,
title: v.data.title,
body: v.data.body,
status: 'received',
})
.select()
.single()
if (error) return { error: error.message }
// Don't include the reporter's identity in the activity log if anonymous.
await logActivity(
supabase,
isAnonymous
? { space_id: member.space_id, user_id: null, display_name: 'Anonymous' }
: member,
'filed',
'incident',
data.id,
v.data.title,
)
revalidatePath('/incidents')
return { data, token: reporterToken }
}
/**
* Admin/board action: transition an incident's status and (optionally)
* record a disposition. Stamps acknowledged_at / decided_at / closed_at
* as appropriate.
*/
export async function updateIncidentStatus(
incidentId: string,
status: string,
disposition?: string | null,
) {
const v = parseInput(updateIncidentStatusSchema, { incidentId, status, disposition })
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ADMIN_ROLES, 'Admin or board access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const patch: Record<string, unknown> = { status: v.data.status }
if (v.data.disposition !== undefined) patch.disposition = v.data.disposition
const now = new Date().toISOString()
if (v.data.status === 'under_review') patch.acknowledged_at = now
if (v.data.status === 'decided') patch.decided_at = now
if (v.data.status === 'closed') patch.closed_at = now
// Track decision makers when deciding.
if (v.data.status === 'decided') {
const { data: current } = await supabase
.from('incidents')
.select('decision_maker_ids')
.eq('id', v.data.incidentId)
.single()
const existing: string[] = (current as { decision_maker_ids?: string[] } | null)?.decision_maker_ids ?? []
if (!existing.includes(member.id)) {
patch.decision_maker_ids = [...existing, member.id]
}
}
const { error } = await supabase
.from('incidents')
.update(patch)
.eq('id', v.data.incidentId)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
await logActivity(supabase, member, v.data.status, 'incident', v.data.incidentId)
revalidatePath('/incidents')
revalidatePath(`/incidents/${v.data.incidentId}`)
return { success: true as const }
}
/**
* Add an update / note to an incident. Reporter and admin/board can post.
* Visibility controls who can read the note via RLS.
*/
export async function addIncidentUpdate(formData: {
incidentId: string
body: string
visibility?: string
}) {
const v = parseInput(addIncidentUpdateSchema, formData)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('incident_updates')
.insert({
incident_id: v.data.incidentId,
author_id: member.id,
author_name: member.display_name,
body: v.data.body,
visibility: v.data.visibility,
})
if (error) return { error: error.message }
revalidatePath(`/incidents/${v.data.incidentId}`)
return { success: true as const }
}
/**
* Appeal a dismissed incident by spawning a membership-vote proposal.
* The reporter or admin/board can trigger the appeal; the proposal goes
* to draft status so the petitioner (or board) can review before opening.
*/
export async function appealIncident(formData: {
incidentId: string
title: string
body?: string
}) {
const v = parseInput(appealIncidentSchema, formData)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
// Confirm the incident exists and is closeable-into-appeal (status='decided' or 'closed').
const { data: incident, error: incidentErr } = await supabase
.from('incidents')
.select('id, status, space_id')
.eq('id', v.data.incidentId)
.single()
if (incidentErr || !incident) return { error: 'Incident not found' }
if (incident.space_id !== member.space_id) return { error: 'Cross-space appeal not allowed' }
// Create the appeal proposal as a draft.
const { data: proposal, error: proposalErr } = await supabase
.from('proposals')
.insert({
space_id: member.space_id,
proposer_id: member.id,
proposer_name: member.display_name,
title: v.data.title,
body: v.data.body,
proposal_type: 'membership_vote',
threshold: 'simple_majority',
parent_incident_id: v.data.incidentId,
status: 'draft',
})
.select()
.single()
if (proposalErr) return { error: proposalErr.message }
// Mark the incident as appealed and link it to the proposal.
const { error: linkErr } = await supabase
.from('incidents')
.update({ status: 'appealed', appeal_proposal_id: proposal.id })
.eq('id', v.data.incidentId)
if (linkErr) return { error: linkErr.message }
await logActivity(supabase, member, 'appealed', 'incident', v.data.incidentId)
revalidatePath('/incidents')
revalidatePath(`/incidents/${v.data.incidentId}`)
revalidatePath(`/proposals/${proposal.id}`)
return { data: proposal }
}
+29
View File
@@ -0,0 +1,29 @@
/**
* Barrel re-export for server actions.
*
* Client components and pages import action functions via `@/lib/actions`.
* Each domain lives in its own file in this directory; this barrel keeps
* the import path stable as the directory grows.
*
* Do NOT add `'use server'` here. The directive lives on the domain files
* themselves; re-exports preserve the marking.
*/
export * from './tasks'
export * from './projects'
export * from './members'
export * from './contacts'
export * from './payments'
export * from './knowledge-base'
export * from './secrets'
export * from './area-leads'
export * from './settings'
export * from './imports'
// Governance kernel (Tier 1)
export * from './proposals'
export * from './incidents'
export * from './policies'
// Per-space configurable taxonomies
export * from './areas'
+106
View File
@@ -0,0 +1,106 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import { requireMember, parseInput } from '@/lib/auth-helpers'
import {
createKbEntrySchema,
updateKbEntrySchema,
uuidSchema,
} from '@/lib/validations'
export async function createKbEntry(formData: {
title: string
content: string
description?: string
area?: string
visibility?: string
is_pinned?: boolean
tags?: string[]
icon?: string
}) {
const v = parseInput(createKbEntrySchema, formData)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { data, error } = await supabase
.from('knowledge_base')
.insert({
space_id: member.space_id,
title: v.data.title,
content: v.data.content,
area: v.data.area ?? null,
visibility: v.data.visibility,
is_pinned: v.data.is_pinned,
tags: v.data.tags ?? [],
icon: v.data.icon ?? null,
updated_by_id: member.id,
updated_by_name: member.display_name,
})
.select()
.single()
if (error) return { error: error.message }
revalidatePath('/ops')
return { data }
}
export async function updateKbEntry(
entryId: string,
updates: {
title?: string
content?: string
area?: string
visibility?: string
is_pinned?: boolean
tags?: string[]
},
) {
const v = parseInput(updateKbEntrySchema, { entryId, ...updates })
if (!v.ok) return { error: v.error }
const { entryId: id, ...patch } = v.data
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('knowledge_base')
.update({
...patch,
updated_by_id: member.id,
updated_by_name: member.display_name,
updated_at: new Date().toISOString(),
})
.eq('id', id)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
revalidatePath('/ops')
return { success: true as const }
}
export async function deleteKbEntry(entryId: string) {
const v = parseInput(uuidSchema, entryId)
if (!v.ok) return { error: 'Invalid entry ID' }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('knowledge_base')
.delete()
.eq('id', v.data)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
revalidatePath('/ops')
return { success: true as const }
}
+200
View File
@@ -0,0 +1,200 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import {
requireMember,
requireMemberWithRole,
logActivity,
parseInput,
} from '@/lib/auth-helpers'
import { ADMIN_ROLES } from '@/lib/permissions'
import {
addMemberSchema,
updateMemberSchema,
updateMyProfileSchema,
discloseAffiliationsSchema,
uuidSchema,
} from '@/lib/validations'
export async function addMember(formData: {
display_name: string
email: string
phone?: string
handle?: string
tier: string
role: string
joined_at?: string
has_card_access?: boolean
}) {
const v = parseInput(addMemberSchema, formData)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ADMIN_ROLES, 'Admin access required')
if (!auth.ok) return { error: auth.error }
const { member: self } = auth
const { data, error } = await supabase
.from('space_members')
.insert({
space_id: self.space_id,
display_name: v.data.display_name,
email: v.data.email,
phone: v.data.phone ?? null,
handle: v.data.handle ?? null,
tier: v.data.tier,
role: v.data.role,
status: 'current',
approved: true,
joined_at: v.data.joined_at ?? new Date().toISOString(),
has_card_access: v.data.has_card_access ?? false,
})
.select()
.single()
if (error) return { error: error.message }
revalidatePath('/members')
return { data }
}
export async function updateMember(
memberId: string,
updates: {
display_name?: string
email?: string
phone?: string
handle?: string
tier?: string
role?: string
status?: string
has_card_access?: boolean
payment_status?: string
payment_note?: string
},
) {
const v = parseInput(updateMemberSchema, { memberId, ...updates })
if (!v.ok) return { error: v.error }
const { memberId: id, ...patch } = v.data
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ADMIN_ROLES, 'Admin access required')
if (!auth.ok) return { error: auth.error }
const { member: self } = auth
const { error } = await supabase
.from('space_members')
.update(patch)
.eq('id', id)
.eq('space_id', self.space_id)
if (error) return { error: error.message }
revalidatePath('/members')
return { success: true as const }
}
export async function approveMember(memberId: string) {
const v = parseInput(uuidSchema, memberId)
if (!v.ok) return { error: 'Invalid member ID' }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ADMIN_ROLES, 'Admin access required')
if (!auth.ok) return { error: auth.error }
const { member: self } = auth
const { error } = await supabase
.from('space_members')
.update({ status: 'current', approved: true })
.eq('id', v.data)
.eq('space_id', self.space_id)
if (error) return { error: error.message }
await logActivity(supabase, self, 'approved', 'member', v.data)
revalidatePath('/members')
return { success: true as const }
}
/**
* Self-edit profile fields: display_name, handle, phone, skills, interests,
* willing_to. The privilege-escalation trigger (migration 015) blocks
* non-privileged members from touching role/tier/status/approved/
* has_card_access/space_id. RLS allows self-update generally.
*/
export async function updateMyProfile(updates: {
display_name?: string
handle?: string | null
phone?: string | null
skills?: string[]
interests?: string[]
willing_to?: string[]
}) {
const v = parseInput(updateMyProfileSchema, updates)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('space_members')
.update(v.data)
.eq('id', member.id)
if (error) return { error: error.message }
revalidatePath('/members')
return { success: true as const }
}
/**
* Disclose conflict-of-interest affiliations. Records the disclosure
* timestamp so the dashboard can remind privileged roles to refresh
* disclosures annually.
*/
export async function discloseAffiliations(formData: { affiliations: string[] }) {
const v = parseInput(discloseAffiliationsSchema, formData)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('space_members')
.update({
affiliations: v.data.affiliations,
coi_last_disclosed_at: new Date().toISOString(),
})
.eq('id', member.id)
if (error) return { error: error.message }
await logActivity(supabase, member, 'disclosed', 'coi', member.id)
revalidatePath('/members')
return { success: true as const }
}
export async function removeMember(memberId: string) {
const v = parseInput(uuidSchema, memberId)
if (!v.ok) return { error: 'Invalid member ID' }
const supabase = await createClient()
// Admin-only (per RLS members_delete policy).
const auth = await requireMemberWithRole(supabase, ['admin'], 'Admin access required')
if (!auth.ok) return { error: auth.error }
const { member: self } = auth
const { error } = await supabase
.from('space_members')
.delete()
.eq('id', v.data)
.eq('space_id', self.space_id)
if (error) return { error: error.message }
revalidatePath('/members')
return { success: true as const }
}
+155
View File
@@ -0,0 +1,155 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import {
requireMemberWithRole,
logActivity,
parseInput,
} from '@/lib/auth-helpers'
import { TREASURER_ROLES } from '@/lib/permissions'
import {
logCashPaymentSchema,
linkPaymentSchema,
} from '@/lib/validations'
import type { Enums } from '@/types/database'
type PaymentPlatform = Enums<'payment_platform'>
export async function logCashPayment(formData: {
amount: number
from_note: string
member_id?: string
transaction_date?: string
}) {
const v = parseInput(logCashPaymentSchema, formData)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, TREASURER_ROLES, 'Treasurer access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const transactionDate = v.data.transaction_date ?? new Date().toISOString()
const { data, error } = await supabase
.from('payments')
.insert({
space_id: member.space_id,
platform: 'cash',
amount: v.data.amount,
from_identifier: 'Cash',
from_note: v.data.from_note,
member_id: v.data.member_id ?? null,
link_status: v.data.member_id ? 'linked' : 'unlinked',
transaction_date: transactionDate,
})
.select()
.single()
if (error) return { error: error.message }
if (v.data.member_id) {
await supabase
.from('space_members')
.update({
last_paid_at: transactionDate,
payment_status: 'current',
})
.eq('id', v.data.member_id)
.eq('space_id', member.space_id)
}
await logActivity(
supabase,
member,
'logged',
'payment',
data.id,
`$${v.data.amount} cash, ${v.data.from_note}`,
)
revalidatePath('/payments')
revalidatePath('/dashboard')
return { data }
}
export async function linkPaymentToMember(paymentId: string, memberId: string) {
const v = parseInput(linkPaymentSchema, { paymentId, memberId })
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, TREASURER_ROLES, 'Treasurer access required')
if (!auth.ok) return { error: auth.error }
const { member: self } = auth
const { data: payment } = await supabase
.from('payments')
.select('amount, transaction_date')
.eq('id', v.data.paymentId)
.single()
const { error } = await supabase
.from('payments')
.update({ member_id: v.data.memberId, link_status: 'linked' })
.eq('id', v.data.paymentId)
.eq('space_id', self.space_id)
if (error) return { error: error.message }
if (payment) {
await supabase
.from('space_members')
.update({
last_paid_at: payment.transaction_date,
payment_status: 'current',
})
.eq('id', v.data.memberId)
.eq('space_id', self.space_id)
}
revalidatePath('/payments')
revalidatePath('/members')
revalidatePath('/dashboard')
return { success: true as const }
}
export async function importPaymentsCsv(
rows: Array<{
platform: string
amount: number
from_identifier: string
from_note?: string
transaction_date: string
}>,
) {
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, TREASURER_ROLES, 'Treasurer access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const validPlatforms: PaymentPlatform[] = ['paypal', 'zeffy', 'venmo', 'cash']
const inserts = rows
.filter(r => validPlatforms.includes(r.platform as PaymentPlatform))
.map(r => ({
space_id: member.space_id,
platform: r.platform as PaymentPlatform,
amount: r.amount,
from_identifier: r.from_identifier,
from_note: r.from_note ?? null,
link_status: 'unlinked' as const,
transaction_date: r.transaction_date,
}))
if (inserts.length === 0) {
return { error: 'No valid rows to import' }
}
const { data, error } = await supabase.from('payments').insert(inserts).select()
if (error) return { error: error.message }
revalidatePath('/payments')
revalidatePath('/dashboard')
return { data, count: data.length }
}
+177
View File
@@ -0,0 +1,177 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import { requireMemberWithRole, logActivity, parseInput } from '@/lib/auth-helpers'
import { ADMIN_ROLES } from '@/lib/permissions'
import {
createPolicySchema,
supersedePolicySchema,
updatePolicyStatusSchema,
} from '@/lib/validations'
/**
* Create a new policy at version 1, in draft status. Admin/board only.
* To activate it, call updatePolicyStatus(id, 'active').
*/
export async function createPolicy(formData: {
slug: string
title: string
section_ref?: string | null
parent_policy_id?: string | null
body_formal?: string
body_plain?: string | null
effective_at?: string | null
}) {
const v = parseInput(createPolicySchema, formData)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ADMIN_ROLES, 'Admin or board access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
// Ensure (space_id, slug) is unique for v1 by checking for existing rows.
const { data: existing } = await supabase
.from('policies')
.select('id')
.eq('space_id', member.space_id)
.eq('slug', v.data.slug)
.limit(1)
if (existing && existing.length > 0) {
return { error: 'A policy with that slug already exists. Use supersedePolicy to publish a new version.' }
}
const { data, error } = await supabase
.from('policies')
.insert({
space_id: member.space_id,
slug: v.data.slug,
title: v.data.title,
section_ref: v.data.section_ref ?? null,
parent_policy_id: v.data.parent_policy_id ?? null,
body_formal: v.data.body_formal,
body_plain: v.data.body_plain ?? null,
version: 1,
status: 'draft',
effective_at: v.data.effective_at ?? null,
})
.select()
.single()
if (error) return { error: error.message }
await logActivity(supabase, member, 'created', 'policy', data.id, v.data.title)
revalidatePath('/policies')
return { data }
}
/**
* Supersede a policy by inserting a new version. The new row has
* prior_version_id=<old policy id>, version=<old.version+1>, status='draft'.
* Activating it (via updatePolicyStatus -> 'active') marks the prior version
* as 'superseded' atomically inside this function.
*/
export async function supersedePolicy(formData: {
policyId: string
body_formal?: string
body_plain?: string | null
section_ref?: string | null
title?: string
adopted_by_proposal_id?: string | null
effective_at?: string | null
}) {
const v = parseInput(supersedePolicySchema, formData)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ADMIN_ROLES, 'Admin or board access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { data: prior, error: priorErr } = await supabase
.from('policies')
.select('id, space_id, slug, title, section_ref, parent_policy_id, body_formal, body_plain, version, status')
.eq('id', v.data.policyId)
.single()
if (priorErr || !prior) return { error: 'Prior policy not found' }
if (prior.space_id !== member.space_id) return { error: 'Cross-space supersede not allowed' }
const { data, error } = await supabase
.from('policies')
.insert({
space_id: member.space_id,
slug: prior.slug,
title: v.data.title ?? prior.title,
section_ref: v.data.section_ref ?? prior.section_ref,
parent_policy_id: prior.parent_policy_id,
body_formal: v.data.body_formal,
body_plain: v.data.body_plain ?? null,
version: prior.version + 1,
prior_version_id: prior.id,
status: 'draft',
effective_at: v.data.effective_at ?? null,
adopted_by_proposal_id: v.data.adopted_by_proposal_id ?? null,
})
.select()
.single()
if (error) return { error: error.message }
await logActivity(supabase, member, 'superseded', 'policy', data.id, `v${prior.version} -> v${prior.version + 1}`)
revalidatePath('/policies')
revalidatePath(`/policies/${prior.slug}`)
return { data }
}
/**
* Flip a policy's status. Activating supersedes any prior active version
* (same slug) atomically.
*/
export async function updatePolicyStatus(policyId: string, status: string) {
const v = parseInput(updatePolicyStatusSchema, { policyId, status })
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ADMIN_ROLES, 'Admin or board access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { data: policy, error: pErr } = await supabase
.from('policies')
.select('id, slug, space_id, version, prior_version_id')
.eq('id', v.data.policyId)
.single()
if (pErr || !policy) return { error: 'Policy not found' }
if (policy.space_id !== member.space_id) return { error: 'Cross-space policy edit not allowed' }
const now = new Date().toISOString()
// When activating, supersede the prior active version (if any) of the same slug.
if (v.data.status === 'active') {
await supabase
.from('policies')
.update({ status: 'superseded' })
.eq('space_id', member.space_id)
.eq('slug', policy.slug)
.eq('status', 'active')
}
const patch: Record<string, unknown> = { status: v.data.status }
if (v.data.status === 'active') patch.effective_at = now
const { error } = await supabase
.from('policies')
.update(patch)
.eq('id', v.data.policyId)
if (error) return { error: error.message }
await logActivity(supabase, member, v.data.status, 'policy', v.data.policyId)
revalidatePath('/policies')
revalidatePath(`/policies/${policy.slug}`)
return { success: true as const }
}
+88
View File
@@ -0,0 +1,88 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import { requireMember, logActivity, parseInput } from '@/lib/auth-helpers'
import {
createProjectSchema,
updateProjectStatusSchema,
uuidSchema,
} from '@/lib/validations'
export async function createProject(formData: {
title: string
description?: string
area?: string
tags?: string[]
due_date?: string
}) {
const v = parseInput(createProjectSchema, formData)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { data, error } = await supabase
.from('projects')
.insert({
space_id: member.space_id,
title: v.data.title,
description: v.data.description,
area: v.data.area,
tags: v.data.tags ?? [],
due_date: v.data.due_date ?? null,
status: 'backlog',
})
.select()
.single()
if (error) return { error: error.message }
await logActivity(supabase, member, 'created', 'project', data.id, v.data.title)
revalidatePath('/projects')
return { data }
}
export async function updateProjectStatus(projectId: string, status: string) {
const v = parseInput(updateProjectStatusSchema, { projectId, status })
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('projects')
.update({ status: v.data.status, updated_at: new Date().toISOString() })
.eq('id', v.data.projectId)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
revalidatePath('/projects')
revalidatePath('/dashboard')
return { success: true as const }
}
export async function deleteProject(projectId: string) {
const v = parseInput(uuidSchema, projectId)
if (!v.ok) return { error: 'Invalid project ID' }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('projects')
.delete()
.eq('id', v.data)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
revalidatePath('/projects')
return { success: true as const }
}
+231
View File
@@ -0,0 +1,231 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import {
requireMember,
requireMemberWithRole,
logActivity,
parseInput,
} from '@/lib/auth-helpers'
import { ADMIN_ROLES } from '@/lib/permissions'
import {
createProposalSchema,
openProposalSchema,
castVoteSchema,
decideProposalSchema,
withdrawProposalSchema,
uuidSchema,
} from '@/lib/validations'
/**
* Create a proposal. Defaults to draft status. Pass `open_immediately: true`
* to skip the draft step and go straight to voting (trigger computes quorum
* and voting window from space defaults).
*/
export async function createProposal(formData: {
title: string
body?: string
proposal_type?: string
threshold?: string
policy_ref_id?: string | null
parent_incident_id?: string | null
voting_opens_at?: string | null
voting_closes_at?: string | null
open_immediately?: boolean
}) {
const v = parseInput(createProposalSchema, formData)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const status = v.data.open_immediately ? 'open' : 'draft'
const { data, error } = await supabase
.from('proposals')
.insert({
space_id: member.space_id,
proposer_id: member.id,
proposer_name: member.display_name,
title: v.data.title,
body: v.data.body,
proposal_type: v.data.proposal_type,
threshold: v.data.threshold ?? 'simple_majority',
policy_ref_id: v.data.policy_ref_id ?? null,
parent_incident_id: v.data.parent_incident_id ?? null,
voting_opens_at: v.data.voting_opens_at ?? null,
voting_closes_at: v.data.voting_closes_at ?? null,
status,
})
.select()
.single()
if (error) return { error: error.message }
await logActivity(supabase, member, 'created', 'proposal', data.id, v.data.title)
revalidatePath('/proposals')
return { data }
}
/**
* Move a draft proposal to open. Trigger computes quorum_required and the
* voting window from the space's defaults if voting_closes_at is null.
*/
export async function openProposal(proposalId: string, voting_closes_at?: string | null) {
const v = parseInput(openProposalSchema, { proposalId, voting_closes_at })
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const updates: Record<string, unknown> = { status: 'open' }
if (v.data.voting_closes_at) updates.voting_closes_at = v.data.voting_closes_at
const { error } = await supabase
.from('proposals')
.update(updates)
.eq('id', v.data.proposalId)
.eq('space_id', member.space_id)
.eq('status', 'draft')
if (error) return { error: error.message }
await logActivity(supabase, member, 'opened', 'proposal', v.data.proposalId)
revalidatePath('/proposals')
revalidatePath(`/proposals/${v.data.proposalId}`)
return { success: true as const }
}
/**
* Withdraw a proposal. Proposer can withdraw their own (any status pre-decided);
* admin/board can withdraw any. Status becomes 'withdrawn'.
*/
export async function withdrawProposal(proposalId: string) {
const v = parseInput(withdrawProposalSchema, { proposalId })
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('proposals')
.update({ status: 'withdrawn' })
.eq('id', v.data.proposalId)
.eq('space_id', member.space_id)
.in('status', ['draft', 'open'])
if (error) return { error: error.message }
await logActivity(supabase, member, 'withdrew', 'proposal', v.data.proposalId)
revalidatePath('/proposals')
revalidatePath(`/proposals/${v.data.proposalId}`)
return { success: true as const }
}
/**
* Cast or update a vote. Upserts on (proposal_id, member_id). The DB-level
* trigger refreshes the proposal's tally on every change. Voting window is
* enforced by RLS, not here.
*/
export async function castVote(formData: {
proposalId: string
position: string
recusal_reason?: string | null
comment?: string | null
}) {
const v = parseInput(castVoteSchema, formData)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('proposal_votes')
.upsert(
{
proposal_id: v.data.proposalId,
member_id: member.id,
position: v.data.position,
recusal_reason: v.data.recusal_reason ?? null,
comment: v.data.comment ?? null,
voted_at: new Date().toISOString(),
},
{ onConflict: 'proposal_id,member_id' },
)
if (error) return { error: error.message }
await logActivity(supabase, member, 'voted', 'proposal', v.data.proposalId, v.data.position)
revalidatePath('/proposals')
revalidatePath(`/proposals/${v.data.proposalId}`)
return { success: true as const }
}
/**
* Decide a proposal: flip status to 'decided' and freeze the outcome. The
* tally is already maintained live by the refresh_proposal_tally trigger;
* this just commits the decision and stamps decided_at.
*/
export async function decideProposal(proposalId: string) {
const v = parseInput(decideProposalSchema, { proposalId })
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ADMIN_ROLES, 'Admin or board access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('proposals')
.update({ status: 'decided', decided_at: new Date().toISOString() })
.eq('id', v.data.proposalId)
.eq('space_id', member.space_id)
.eq('status', 'open')
if (error) return { error: error.message }
await logActivity(supabase, member, 'decided', 'proposal', v.data.proposalId)
revalidatePath('/proposals')
revalidatePath(`/proposals/${v.data.proposalId}`)
return { success: true as const }
}
/**
* Delete a proposal. Admin/board only. Use sparingly; prefer withdraw.
*/
export async function deleteProposal(proposalId: string) {
const v = parseInput(uuidSchema, proposalId)
if (!v.ok) return { error: 'Invalid proposal ID' }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ADMIN_ROLES, 'Admin or board access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('proposals')
.delete()
.eq('id', v.data)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
await logActivity(supabase, member, 'deleted', 'proposal', v.data)
revalidatePath('/proposals')
return { success: true as const }
}
+62
View File
@@ -0,0 +1,62 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import { requireMemberWithRole, parseInput } from '@/lib/auth-helpers'
import { ADMIN_ROLES } from '@/lib/permissions'
import { createSecretSchema, uuidSchema } from '@/lib/validations'
export async function createSecret(formData: {
title: string
value: string
description?: string
area?: string
icon?: string
}) {
const v = parseInput(createSecretSchema, formData)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ADMIN_ROLES, 'Admin access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { data, error } = await supabase
.from('secrets')
.insert({
space_id: member.space_id,
title: v.data.title,
label: v.data.title,
value: v.data.value,
description: v.data.description ?? null,
area: v.data.area ?? null,
icon: v.data.icon ?? null,
})
.select()
.single()
if (error) return { error: error.message }
revalidatePath('/ops')
return { data }
}
export async function deleteSecret(secretId: string) {
const v = parseInput(uuidSchema, secretId)
if (!v.ok) return { error: 'Invalid secret ID' }
const supabase = await createClient()
// Admin-only per RLS secrets_delete.
const auth = await requireMemberWithRole(supabase, ['admin'], 'Admin access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('secrets')
.delete()
.eq('id', v.data)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
revalidatePath('/ops')
return { success: true as const }
}
+144
View File
@@ -0,0 +1,144 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import { requireMemberWithRole, parseInput } from '@/lib/auth-helpers'
import {
updateSpaceSettingsSchema,
saveIntegrationSchema,
updateSpaceVisibilitySchema,
} from '@/lib/validations'
const ADMIN_ONLY = ['admin'] as const
export async function updateSpaceSettings(updates: {
name?: string
slug?: string
city?: string
require_approval?: boolean
public_member_directory?: boolean
}) {
const v = parseInput(updateSpaceSettingsSchema, updates)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ADMIN_ONLY, 'Admin access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('spaces')
.update({ ...v.data, updated_at: new Date().toISOString() })
.eq('id', member.space_id)
if (error) return { error: error.message }
revalidatePath('/settings')
return { success: true as const }
}
export async function rotateWebhookSecret() {
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ADMIN_ONLY, 'Admin access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const bytes = crypto.getRandomValues(new Uint8Array(24))
const newSecret =
'whsec_' +
Array.from(bytes)
.map(b => b.toString(16).padStart(2, '0'))
.join('')
const { error } = await supabase
.from('spaces')
.update({ webhook_secret: newSecret, updated_at: new Date().toISOString() })
.eq('id', member.space_id)
if (error) return { error: error.message }
revalidatePath('/settings')
return { secret: newSecret }
}
export async function saveIntegration(platform: string, config: Record<string, string>) {
const v = parseInput(saveIntegrationSchema, { platform, config })
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ADMIN_ONLY, 'Admin access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
// Store provided values; also store boolean "_set" flags so the UI can show
// a "connected" state without leaking the secret back to the client.
const safeConfig: Record<string, string> = {}
for (const [key, value] of Object.entries(v.data.config)) {
safeConfig[key] = value ?? ''
safeConfig[`${key}_set`] = value && value.length > 0 ? 'true' : 'false'
}
const { error } = await supabase.from('integrations').upsert(
{
space_id: member.space_id,
platform: v.data.platform,
name: v.data.platform,
is_connected: Object.values(v.data.config).some(value => value && value.length > 0),
config: safeConfig,
updated_at: new Date().toISOString(),
},
{ onConflict: 'space_id,platform' },
)
if (error) return { error: error.message }
revalidatePath('/settings')
return { success: true as const }
}
/**
* Per-space visibility flags. Lets admins decide whether financial data is
* visible to all members, board only, or treasurer-only; and whether the
* member directory is fully visible, count-only, or board-only.
*/
export async function updateSpaceVisibility(updates: {
financial_visibility?: string
member_directory_visibility?: string
}) {
const v = parseInput(updateSpaceVisibilitySchema, updates)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ADMIN_ONLY, 'Admin access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('spaces')
.update({ ...v.data, updated_at: new Date().toISOString() })
.eq('id', member.space_id)
if (error) return { error: error.message }
revalidatePath('/settings')
revalidatePath('/financials')
revalidatePath('/members')
return { success: true as const }
}
export async function disconnectIntegration(platform: string) {
if (typeof platform !== 'string' || platform.length === 0 || platform.length > 50) {
return { error: 'Invalid platform' }
}
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ADMIN_ONLY, 'Admin access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('integrations')
.update({ is_connected: false, config: {}, updated_at: new Date().toISOString() })
.eq('space_id', member.space_id)
.eq('platform', platform)
if (error) return { error: error.message }
revalidatePath('/settings')
return { success: true as const }
}
+125
View File
@@ -0,0 +1,125 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import { requireMember, logActivity, parseInput } from '@/lib/auth-helpers'
import { createTaskSchema, taskIdSchema } from '@/lib/validations'
export async function createTask(formData: {
title: string
description?: string
type: string
area?: string
recurrence?: string
due_date?: string
}) {
const v = parseInput(createTaskSchema, formData)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { data, error } = await supabase
.from('tasks')
.insert({
space_id: member.space_id,
title: v.data.title,
description: v.data.description,
task_type: v.data.type,
area: v.data.area,
recurrence: v.data.recurrence,
due_date: v.data.due_date ?? null,
status: 'open',
requested_by: member.user_id,
requested_by_name: member.display_name,
})
.select()
.single()
if (error) return { error: error.message }
await logActivity(supabase, member, 'created', 'task', data.id, v.data.title)
revalidatePath('/tasks')
revalidatePath('/dashboard')
return { data }
}
export async function claimTask(taskId: string) {
const v = parseInput(taskIdSchema, taskId)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('tasks')
.update({
claimed_by: member.user_id,
claimed_by_name: member.display_name,
status: 'claimed',
})
.eq('id', v.data)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
await logActivity(supabase, member, 'claimed', 'task', v.data)
revalidatePath('/tasks')
revalidatePath('/dashboard')
return { success: true as const }
}
export async function completeTask(taskId: string) {
const v = parseInput(taskIdSchema, taskId)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const now = new Date().toISOString()
const { error } = await supabase
.from('tasks')
.update({
status: 'completed',
completed_at: now,
last_done_at: now,
})
.eq('id', v.data)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
await logActivity(supabase, member, 'completed', 'task', v.data)
revalidatePath('/tasks')
revalidatePath('/dashboard')
return { success: true as const }
}
export async function deleteTask(taskId: string) {
const v = parseInput(taskIdSchema, taskId)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('tasks')
.delete()
.eq('id', v.data)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
revalidatePath('/tasks')
return { success: true as const }
}