Add notification preferences and alternate dues payment options

Notification preferences (migration 048):
- Per-member opt-out of muteable categories (bookings, classes, forms,
  admin alerts); billing is always-on. Opt-out model, default on.
- Dispatcher reads prefs and marks muted outbox rows 'skipped' instead
  of sending; pure isMuted logic, fail-open on a prefs lookup error.
- notification_preferences table (default-deny RLS); /me toggles and
  self-view via validated service-client actions.

Alternate dues payment methods (migration 049):
- Admin sets external pay-here URLs per platform (PayPal/Zeffy/Venmo)
  in /settings; members see active ones on /me and pay off-platform;
  the treasurer reconciles manually (platform pre-tagged). https-only.
- dues_payment_methods table (SELECT space member, write admin/board).

/me visual pass:
- Restore the chip/preset profile editor (skills/interests/willing-to/
  affiliations); promote ChipInput and presets to shared modules.
- Gate the Stripe pay-dues button on whether the space has Stripe
  configured; show external links or a contact-admin note otherwise.
This commit is contained in:
Moheeb Zara
2026-05-19 20:26:32 -07:00
parent addedfdb0f
commit ab8c22ae1d
29 changed files with 1281 additions and 124 deletions
+124
View File
@@ -0,0 +1,124 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import { requireMember, requireMemberWithRole, parseInput } from '@/lib/auth-helpers'
import { ADMIN_ROLES } from '@/lib/permissions'
import { duesPaymentMethodSchema } from '@/lib/validations'
export type DuesPaymentMethod = {
platform: string
url: string
instructions: string | null
isActive: boolean
sortOrder: number
}
// Member-facing: the ACTIVE external dues payment links for the caller's space,
// in display order. RLS (SELECT = space member) scopes this; we still pin
// space_id for clarity. Used by the /me dues UI to render click-out buttons.
export async function listActiveDuesPaymentMethods(): Promise<
{ data: DuesPaymentMethod[] } | { error: string }
> {
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { data } = await supabase
.from('dues_payment_methods')
.select('platform, url, instructions, is_active, sort_order')
.eq('space_id', member.space_id)
.eq('is_active', true)
.order('sort_order', { ascending: true })
return { data: (data ?? []).map(toMethod) }
}
// Admin-facing: every configured method (active + inactive) for the management
// UI in /settings.
export async function listDuesPaymentMethods(): Promise<
{ data: DuesPaymentMethod[] } | { error: string }
> {
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 } = await supabase
.from('dues_payment_methods')
.select('platform, url, instructions, is_active, sort_order')
.eq('space_id', member.space_id)
.order('sort_order', { ascending: true })
return { data: (data ?? []).map(toMethod) }
}
// Admin: create or update the link for one platform (idempotent on
// (space_id, platform)). The RLS write policies re-check the admin/board role.
export async function upsertDuesPaymentMethod(
input: unknown,
): Promise<{ ok: true } | { error: string }> {
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 v = parseInput(duesPaymentMethodSchema, input)
if (!v.ok) return { error: v.error }
const s = v.data
const { error } = await supabase.from('dues_payment_methods').upsert(
{
space_id: member.space_id,
platform: s.platform,
url: s.url,
instructions: s.instructions ?? null,
is_active: s.is_active ?? true,
sort_order: s.sort_order ?? 0,
},
{ onConflict: 'space_id,platform' },
)
if (error) return { error: 'Could not save the payment method.' }
revalidatePath('/settings')
revalidatePath('/me')
return { ok: true }
}
// Admin: remove the link for one platform entirely.
export async function deleteDuesPaymentMethod(input: {
platform: string
}): Promise<{ ok: true } | { error: string }> {
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 { error } = await supabase
.from('dues_payment_methods')
.delete()
.eq('space_id', member.space_id)
.eq('platform', input.platform)
if (error) return { error: 'Could not remove the payment method.' }
revalidatePath('/settings')
revalidatePath('/me')
return { ok: true }
}
function toMethod(r: {
platform: string
url: string
instructions: string | null
is_active: boolean
sort_order: number
}): DuesPaymentMethod {
return {
platform: r.platform,
url: r.url,
instructions: r.instructions ?? null,
isActive: r.is_active,
sortOrder: r.sort_order,
}
}
+3
View File
@@ -71,3 +71,6 @@ export * from './stripe'
// Transactional notifications outbox (product spine Phase 2)
export * from './notifications'
// Alternate dues payment methods (admin-configured external links)
export * from './dues-payments'
+67
View File
@@ -1,8 +1,15 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import { createAdminClient } from '@/lib/supabase/admin'
import { requireMember } from '@/lib/auth-helpers'
import { notificationPreferenceSchema } from '@/lib/validations'
import {
MUTEABLE_CATEGORIES,
type NotificationCategory,
type PrefMap,
} from '@/lib/notifications-prefs-logic'
// The caller's own notification history. The notifications RLS SELECT is
// admin/board/treasurer only (mirrors member_billing), so the member
@@ -32,3 +39,63 @@ export async function getMyNotifications() {
})),
}
}
// The caller's own notification preferences as a category -> enabled map.
// notification_preferences has no client policy (same convention as
// notifications / member_billing), so the read goes through the service client
// scoped to the caller's own member row. Absent categories are the default
// (enabled); only muteable categories are ever stored or returned.
export async function getMyNotificationPreferences(): Promise<{ data: PrefMap } | { error: string }> {
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { data } = await createAdminClient()
.from('notification_preferences')
.select('category, enabled')
.eq('space_id', member.space_id)
.eq('member_id', member.id)
const prefs: PrefMap = {}
for (const c of MUTEABLE_CATEGORIES) prefs[c] = true
for (const row of data ?? []) {
const cat = row.category as NotificationCategory
if ((MUTEABLE_CATEGORIES as readonly NotificationCategory[]).includes(cat)) {
prefs[cat] = row.enabled as boolean
}
}
return { data: prefs }
}
// Set one muteable category on/off for the caller. Billing is never settable
// (the Zod enum excludes it). Upserts the caller's own row through the service
// client; the (space_id, member_id, category) PK makes a re-toggle idempotent.
export async function setMyNotificationPreference(input: {
category: string
enabled: boolean
}): Promise<{ ok: true } | { error: string }> {
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const parsed = notificationPreferenceSchema.safeParse(input)
if (!parsed.success) return { error: 'Invalid notification preference' }
const { error } = await createAdminClient()
.from('notification_preferences')
.upsert(
{
space_id: member.space_id,
member_id: member.id,
category: parsed.data.category,
enabled: parsed.data.enabled,
},
{ onConflict: 'space_id,member_id,category' },
)
if (error) return { error: 'Could not save preference' }
revalidatePath('/me')
return { ok: true }
}
+13 -8
View File
@@ -220,20 +220,25 @@ export async function getMyBilling() {
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { data } = await createAdminClient()
const admin = createAdminClient()
// Whether the space has Stripe dues set up at all, so the /me UI can hide the
// "Pay dues" (Stripe Checkout) button when there is no Stripe to check out to.
const cfg = await getStripeConfig(admin, member.space_id)
const configured = isStripeConfigured(cfg ?? {})
const { data } = await admin
.from('member_billing')
.select('subscription_status, current_period_end, stripe_customer_id')
.eq('space_id', member.space_id)
.eq('member_id', member.id)
.maybeSingle()
return {
data: data
? {
status: (data.subscription_status as string | null) ?? null,
currentPeriodEnd: (data.current_period_end as string | null) ?? null,
hasCustomer: !!data.stripe_customer_id,
}
: null,
data: {
status: (data?.subscription_status as string | null) ?? null,
currentPeriodEnd: (data?.current_period_end as string | null) ?? null,
hasCustomer: !!data?.stripe_customer_id,
configured,
},
}
}
+36
View File
@@ -0,0 +1,36 @@
// Pure logic for admin-configured alternate dues payment methods. These are
// external pay-here links (PayPal, Zeffy, Venmo) a member clicks to pay dues
// off-platform; a treasurer reconciles the payment manually later through the
// existing payments flow, which is why each method carries a payment_platform
// tag. No I/O here: the platform set + labels are shared by the admin settings
// UI and the member /me UI; URL validation is exercised by the Zod schema.
// The url-based subset of the payment_platform enum. 'cash' has no link and
// 'stripe' is the in-app integration, so neither is an external dues link.
export const DUES_LINK_PLATFORMS = ['paypal', 'zeffy', 'venmo'] as const
export type DuesLinkPlatform = (typeof DUES_LINK_PLATFORMS)[number]
export const DUES_PLATFORM_LABEL: Record<DuesLinkPlatform, string> = {
paypal: 'PayPal',
zeffy: 'Zeffy',
venmo: 'Venmo',
}
export function isDuesLinkPlatform(p: string): p is DuesLinkPlatform {
return (DUES_LINK_PLATFORMS as readonly string[]).includes(p)
}
// A payment link is only safe to render as a member-clickable anchor if it is
// an absolute https URL. http (plaintext) and any non-web scheme
// (javascript:, data:, mailto:, etc.) are rejected so an admin-entered value
// cannot become an XSS or a downgrade vector when shown to members.
export function isSafeDuesUrl(url: string): boolean {
let u: URL
try {
u = new URL(url)
} catch {
return false
}
return u.protocol === 'https:'
}
+93
View File
@@ -0,0 +1,93 @@
// Member notification preferences: the pure category model plus the single
// mute decision. No I/O, no Supabase. The dispatcher consumes isMuted to decide
// whether to send an outbox row; the /me UI consumes CATEGORY_META to render the
// toggles. The notifications.type column stays free text, so adding a new event
// type only needs a line in TYPE_CATEGORY here (and a renderer) -- the prefs
// storage and the dispatcher do not change.
export type NotificationCategory =
| 'billing'
| 'bookings'
| 'classes'
| 'forms'
| 'admin_alerts'
// Categories a member can mute. 'billing' is deliberately excluded: dues
// renewed / payment-failed / lapsed are membership-critical financial notices
// (a muted lapse notice would let a member silently lose access for
// non-payment), so they always send and never render a toggle.
export const MUTEABLE_CATEGORIES = [
'bookings',
'classes',
'forms',
'admin_alerts',
] as const satisfies readonly NotificationCategory[]
// Maps every emitted notification type to its category. A type with no entry
// here is treated as always-on by isMuted (fail-open: a member should still
// receive a newly added kind of mail rather than have it silently dropped by a
// missing mapping). Keep in sync with the renderers in notifications-logic.ts.
export const TYPE_CATEGORY: Record<string, NotificationCategory> = {
dues_renewed: 'billing',
dues_payment_failed: 'billing',
dues_lapsed: 'billing',
booking_confirmed: 'bookings',
booking_cancelled: 'bookings',
class_signup_registered: 'classes',
class_signup_waitlisted: 'classes',
class_signup_promoted: 'classes',
class_session_cancelled: 'classes',
form_submission_received: 'forms',
form_submission_admin: 'admin_alerts',
}
export function categoryForType(type: string): NotificationCategory | null {
return TYPE_CATEGORY[type] ?? null
}
export function isMuteableCategory(cat: NotificationCategory): boolean {
return (MUTEABLE_CATEGORIES as readonly NotificationCategory[]).includes(cat)
}
// Display order + copy for the /me toggles. Only muteable categories appear.
export const CATEGORY_META: Array<{
category: NotificationCategory
label: string
description: string
}> = [
{
category: 'bookings',
label: 'Equipment bookings',
description: 'Reservation confirmations and cancellations.',
},
{
category: 'classes',
label: 'Classes',
description: 'Signups, waitlist moves, and session cancellations.',
},
{
category: 'forms',
label: 'Your form submissions',
description: 'Receipts when you submit a form or waiver.',
},
{
category: 'admin_alerts',
label: 'Admin alerts',
description: 'New form submissions you can manage.',
},
]
// A member's stored preferences as a category -> enabled map. An absent
// category means the default (enabled): this is an opt-out model. Only
// muteable categories are ever stored; billing is never written.
export type PrefMap = Partial<Record<NotificationCategory, boolean>>
// The mute decision for one outbox row. Returns true (suppress the send) only
// when the type maps to a muteable category the member has explicitly disabled.
// Always-on categories (billing) and unmapped types never mute.
export function isMuted(prefs: PrefMap, type: string): boolean {
const cat = categoryForType(type)
if (!cat) return false
if (!isMuteableCategory(cat)) return false
return prefs[cat] === false
}
+12
View File
@@ -0,0 +1,12 @@
// Suggested values offered as click-to-add chips in the member profile editor.
// "Willing to" feeds the board-only recruitment view, so the suggestions are
// the governance/volunteer roles that view groups by.
export const WILLING_TO_SUGGESTIONS = [
'board_candidate',
'treasurer_candidate',
'host_volunteer',
'area_lead_candidate',
'event_organizer',
'safety_committee',
'docs_steward',
]
+30
View File
@@ -1,5 +1,7 @@
import { z } from 'zod'
import { INVITE_ROLES } from './invite-logic'
import { MUTEABLE_CATEGORIES } from './notifications-prefs-logic'
import { DUES_LINK_PLATFORMS, isSafeDuesUrl } from './dues-payments-logic'
/**
* Accepts every date-ish string the app produces and normalizes to a
@@ -1021,6 +1023,34 @@ export const stripeSettingsSchema = z.object({
prices: z.record(z.string().trim().max(255)).optional().default({}),
})
// ─── Notification preferences ────────────────────────────────────────────────
// Only muteable categories are settable; billing is membership-critical and
// never user-controllable, so it is excluded from the enum (a request to set
// it is rejected at the boundary).
export const notificationPreferenceSchema = z.object({
category: z.enum(MUTEABLE_CATEGORIES as unknown as [string, ...string[]]),
enabled: z.boolean(),
})
// ─── Dues payment methods (admin-configured external links) ──────────────────
// One external pay-here URL per platform. url must be absolute https (no
// http downgrade, no javascript:/data: scheme) since it is rendered as a
// member-clickable anchor. instructions is an optional memo hint (e.g. "put
// your member name in the note") to help the treasurer reconcile later.
export const duesPaymentMethodSchema = z.object({
platform: z.enum(DUES_LINK_PLATFORMS as unknown as [string, ...string[]]),
url: z
.string()
.trim()
.max(500)
.refine(isSafeDuesUrl, 'Enter an absolute https:// URL'),
instructions: z.string().trim().max(300).optional().nullable(),
is_active: z.boolean().optional().default(true),
sort_order: z.number().int().min(0).max(999).optional().default(0),
})
// Helper type exports
export type CreateTaskInput = z.infer<typeof createTaskSchema>
export type CreateProjectInput = z.infer<typeof createProjectSchema>