Settings + Admin redesign + Community Leader role

## New: Community Leader role
Who: Imam Yusuf, Sister Mariam, Uncle Tariq — the person who rallies
their mosque, WhatsApp group, neighbourhood to pledge.

Not an admin. Not a volunteer. A logged-in coordinator who needs
more than a live feed but less than full admin access.

/dashboard/community — their scoped dashboard:
- 'How are WE doing?' — their stats vs the whole appeal (dark hero section)
- Contribution percentage bar
- Their links with full share buttons (Copy/WhatsApp/Email/QR)
- Create new links (auto-tagged with their name)
- Leaderboard: 'How communities compare' with 'You' badge
- Read-only pledge list (no status changes, no bank details)

Navigation changes for community_leader role:
- Sees: My Community → Share Links → Reports (3 items)
- Does NOT see: Home, Money, Settings, New Appeal button
- Does NOT see: Bank details, WhatsApp config, reconciliation

## New: Team management API + UI
GET/POST/PATCH/DELETE /api/team — CRUD for team members
- Only org_admin/super_admin can invite
- Temp password generated on invite (shown once)
- Copy credentials or send via WhatsApp button
- Role selector with descriptions (Admin, Community Leader, Staff, Volunteer)
- Role change via dropdown, remove with trash icon
- Can't change own role or remove self

## Settings page redesign
Reordered by Aaisha's thinking:
1. WhatsApp (unchanged — most important)
2. Team (NEW — 'who has access? invite community leaders')
3. Bank account
4. Charity details
5. Direct Debit (collapsed in <details>)

Team section shows:
- All members with role icons (Crown/Users/Eye)
- Inline role change dropdown
- Remove button
- Invite form with role cards and descriptions
- Credentials shown once with copy + WhatsApp share buttons

## Admin page redesign
Brand-consistent: no more shadcn Card/Badge/Table
- Dark hero section with 7 platform stats
- Pipeline status breakdown (gap-px grid)
- Pill tab switcher (not shadcn Tabs)
- Grid tables matching the rest of the dashboard
- Role badges color-coded (blue super, green admin, amber leader)

6 files changed, 4 new routes/pages
This commit is contained in:
2026-03-04 21:48:10 +08:00
parent 9c7990e05c
commit b771858280
10 changed files with 2113 additions and 242 deletions

View File

@@ -0,0 +1,152 @@
import { NextRequest, NextResponse } from "next/server"
import prisma from "@/lib/prisma"
import { getUser, getOrgId } from "@/lib/session"
import { hash } from "bcryptjs"
import { customAlphabet } from "nanoid"
const generateTempPassword = customAlphabet("23456789abcdefghjkmnpqrstuvwxyz", 12)
/**
* GET /api/team — List team members for the current org
*/
export async function GET() {
try {
if (!prisma) return NextResponse.json({ members: [] })
const orgId = await getOrgId(null)
if (!orgId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const members = await prisma.user.findMany({
where: { organizationId: orgId },
select: { id: true, email: true, name: true, role: true, createdAt: true },
orderBy: { createdAt: "asc" },
})
return NextResponse.json({ members })
} catch (error) {
console.error("Team GET error:", error)
return NextResponse.json({ members: [] })
}
}
/**
* POST /api/team — Invite a new team member
* Only org_admin can invite. Creates a user with a temp password.
*/
export async function POST(request: NextRequest) {
try {
if (!prisma) return NextResponse.json({ error: "DB not configured" }, { status: 503 })
const user = await getUser()
if (!user || (user.role !== "org_admin" && user.role !== "super_admin")) {
return NextResponse.json({ error: "Only admins can invite team members" }, { status: 403 })
}
const { email, name, role } = await request.json()
if (!email) return NextResponse.json({ error: "Email is required" }, { status: 400 })
const cleanEmail = email.toLowerCase().trim()
const validRoles = ["org_admin", "community_leader", "staff", "volunteer"]
const memberRole = validRoles.includes(role) ? role : "staff"
// Check if already exists
const existing = await prisma.user.findUnique({ where: { email: cleanEmail } })
if (existing) {
return NextResponse.json({ error: "A user with this email already exists" }, { status: 409 })
}
// Create with temp password
const tempPassword = generateTempPassword()
const hashedPassword = await hash(tempPassword, 12)
const newUser = await prisma.user.create({
data: {
email: cleanEmail,
name: name?.trim() || null,
hashedPassword,
role: memberRole,
organizationId: user.orgId,
},
})
return NextResponse.json({
id: newUser.id,
email: newUser.email,
name: newUser.name,
role: newUser.role,
tempPassword, // Show once so admin can share it
}, { status: 201 })
} catch (error) {
console.error("Team POST error:", error)
return NextResponse.json({ error: "Failed to invite" }, { status: 500 })
}
}
/**
* PATCH /api/team — Update a team member's role
*/
export async function PATCH(request: NextRequest) {
try {
if (!prisma) return NextResponse.json({ error: "DB not configured" }, { status: 503 })
const user = await getUser()
if (!user || (user.role !== "org_admin" && user.role !== "super_admin")) {
return NextResponse.json({ error: "Only admins can change roles" }, { status: 403 })
}
const { userId, role } = await request.json()
if (!userId || !role) return NextResponse.json({ error: "userId and role required" }, { status: 400 })
const validRoles = ["org_admin", "community_leader", "staff", "volunteer"]
if (!validRoles.includes(role)) {
return NextResponse.json({ error: "Invalid role" }, { status: 400 })
}
// Don't let admin demote themselves
if (userId === user.id) {
return NextResponse.json({ error: "You can't change your own role" }, { status: 400 })
}
// Ensure target user is in the same org
const target = await prisma.user.findFirst({
where: { id: userId, organizationId: user.orgId },
})
if (!target) return NextResponse.json({ error: "User not found" }, { status: 404 })
await prisma.user.update({ where: { id: userId }, data: { role } })
return NextResponse.json({ success: true })
} catch (error) {
console.error("Team PATCH error:", error)
return NextResponse.json({ error: "Failed to update" }, { status: 500 })
}
}
/**
* DELETE /api/team — Remove a team member
*/
export async function DELETE(request: NextRequest) {
try {
if (!prisma) return NextResponse.json({ error: "DB not configured" }, { status: 503 })
const user = await getUser()
if (!user || (user.role !== "org_admin" && user.role !== "super_admin")) {
return NextResponse.json({ error: "Only admins can remove members" }, { status: 403 })
}
const { userId } = await request.json()
if (!userId) return NextResponse.json({ error: "userId required" }, { status: 400 })
if (userId === user.id) return NextResponse.json({ error: "You can't remove yourself" }, { status: 400 })
const target = await prisma.user.findFirst({
where: { id: userId, organizationId: user.orgId },
})
if (!target) return NextResponse.json({ error: "User not found" }, { status: 404 })
await prisma.user.delete({ where: { id: userId } })
return NextResponse.json({ success: true })
} catch (error) {
console.error("Team DELETE error:", error)
return NextResponse.json({ error: "Failed to remove" }, { status: 500 })
}
}

View File

@@ -2,23 +2,42 @@
import { useState, useEffect } from "react"
import { useSession } from "next-auth/react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table"
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"
import {
Shield, Building2, Users, Banknote, Calendar, TrendingUp, Loader2, AlertTriangle
} from "lucide-react"
import { formatPence } from "@/lib/utils"
import { Shield, Loader2, AlertTriangle, Building2, Users, Banknote } from "lucide-react"
/**
* /dashboard/admin — Platform-wide super admin view
*
* Brand-consistent redesign. No shadcn Card/Badge/Table.
* Sharp edges, gap-px grids, left-border accents.
*
* This is Omair's view — the platform owner.
* He thinks: "How many orgs are using this? Who's stuck? Where's the money?"
*/
interface AdminData {
platform: { orgs: number; users: number; events: number; pledges: number; totalPledgedPence: number; totalCollectedPence: number; collectionRate: number }
orgs: Array<{ id: string; name: string; slug: string; hasBank: boolean; users: number; events: number; pledges: number; createdAt: string }>
users: Array<{ id: string; email: string; name: string | null; role: string; orgName: string; createdAt: string }>
byStatus: Record<string, { count: number; amount: number }>
recentPledges: Array<{ id: string; reference: string; amountPence: number; status: string; donorName: string | null; eventName: string; orgName: string; dueDate: string | null; createdAt: string }>
recentPledges: Array<{ id: string; reference: string; amountPence: number; status: string; donorName: string | null; eventName: string; orgName: string; createdAt: string }>
}
const fmt = (p: number) => `£${(p / 100).toLocaleString("en-GB", { minimumFractionDigits: 0 })}`
const STATUS: Record<string, { label: string; color: string; bg: string }> = {
new: { label: "Waiting", color: "text-gray-600", bg: "bg-gray-100" },
initiated: { label: "Said paid", color: "text-[#F59E0B]", bg: "bg-[#F59E0B]/10" },
paid: { label: "Received", color: "text-[#16A34A]", bg: "bg-[#16A34A]/10" },
overdue: { label: "Overdue", color: "text-[#DC2626]", bg: "bg-[#DC2626]/10" },
cancelled: { label: "Cancelled", color: "text-gray-400", bg: "bg-gray-50" },
}
const ROLE_LABELS: Record<string, string> = {
super_admin: "Super Admin",
org_admin: "Admin",
community_leader: "Community Leader",
staff: "Staff",
volunteer: "Volunteer",
}
export default function AdminPage() {
const { data: session } = useSession()
@@ -27,7 +46,7 @@ export default function AdminPage() {
const [data, setData] = useState<AdminData | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState("")
const [tab, setTab] = useState("orgs")
const [tab, setTab] = useState<"orgs" | "users" | "pledges">("orgs")
useEffect(() => {
fetch("/api/admin")
@@ -40,180 +59,177 @@ export default function AdminPage() {
if (user?.role !== "super_admin") {
return (
<div className="text-center py-20 space-y-3">
<Shield className="h-10 w-10 text-danger-red mx-auto" />
<h2 className="text-xl font-bold">Access Denied</h2>
<p className="text-sm text-muted-foreground">Super admin access required.</p>
<Shield className="h-10 w-10 text-[#DC2626] mx-auto" />
<h2 className="text-xl font-black text-[#111827]">Access Denied</h2>
<p className="text-sm text-gray-500">Super admin access required.</p>
</div>
)
}
if (loading) return <div className="flex items-center justify-center py-20"><Loader2 className="h-8 w-8 text-trust-blue animate-spin" /></div>
if (error || !data) return <div className="text-center py-20"><AlertTriangle className="h-8 w-8 text-danger-red mx-auto mb-2" /><p className="text-muted-foreground">{error}</p></div>
if (loading) return <div className="flex items-center justify-center py-20"><Loader2 className="h-6 w-6 text-[#1E40AF] animate-spin" /></div>
if (error || !data) return <div className="text-center py-20"><AlertTriangle className="h-8 w-8 text-[#DC2626] mx-auto mb-2" /><p className="text-sm text-gray-500">{error}</p></div>
const p = data.platform
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-center gap-3">
<Shield className="h-6 w-6 text-trust-blue" />
<div className="w-10 h-10 bg-[#1E40AF]/10 flex items-center justify-center">
<Shield className="h-5 w-5 text-[#1E40AF]" />
</div>
<div>
<h1 className="text-2xl font-black text-gray-900">Super Admin</h1>
<p className="text-xs text-muted-foreground">Platform-wide view · {user?.email}</p>
<h1 className="text-3xl font-black text-[#111827] tracking-tight">Platform Admin</h1>
<p className="text-xs text-gray-500">{user?.email}</p>
</div>
</div>
{/* Platform stats */}
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-3">
{[
{ label: "Orgs", value: p.orgs, icon: Building2, color: "text-trust-blue" },
{ label: "Users", value: p.users, icon: Users, color: "text-warm-amber" },
{ label: "Events", value: p.events, icon: Calendar, color: "text-purple-500" },
{ label: "Pledges", value: p.pledges, icon: TrendingUp, color: "text-success-green" },
{ label: "Pledged", value: fmt(p.totalPledgedPence), icon: Banknote, color: "text-trust-blue" },
{ label: "Collected", value: fmt(p.totalCollectedPence), icon: Banknote, color: "text-success-green" },
{ label: "Rate", value: `${p.collectionRate}%`, icon: TrendingUp, color: p.collectionRate > 50 ? "text-success-green" : "text-warm-amber" },
].map(s => (
<Card key={s.label}>
<CardContent className="pt-4 pb-3">
<div className="flex items-center gap-1.5">
<s.icon className={`h-3.5 w-3.5 ${s.color}`} />
<span className="text-[10px] text-muted-foreground">{s.label}</span>
</div>
<p className="text-lg font-black mt-0.5">{s.value}</p>
</CardContent>
</Card>
))}
<div className="bg-[#111827] p-6">
<p className="text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-4">Platform overview</p>
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-px bg-gray-700">
{[
{ value: String(p.orgs), label: "Charities" },
{ value: String(p.users), label: "Users" },
{ value: String(p.events), label: "Appeals" },
{ value: String(p.pledges), label: "Pledges" },
{ value: formatPence(p.totalPledgedPence), label: "Promised" },
{ value: formatPence(p.totalCollectedPence), label: "Received", color: "text-[#4ADE80]" },
{ value: `${p.collectionRate}%`, label: "Rate", color: p.collectionRate >= 50 ? "text-[#4ADE80]" : "text-[#FBBF24]" },
].map(s => (
<div key={s.label} className="bg-[#111827] p-3 text-center">
<p className={`text-lg font-black ${s.color || "text-white"}`}>{s.value}</p>
<p className="text-[9px] text-gray-500 mt-0.5">{s.label}</p>
</div>
))}
</div>
</div>
{/* Pipeline */}
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm">Pipeline</CardTitle>
</CardHeader>
<CardContent>
<div className="flex gap-3 overflow-x-auto">
{Object.entries(data.byStatus).map(([status, { count, amount }]) => (
<div key={status} className="flex-shrink-0 rounded-lg bg-muted/50 px-4 py-2 text-center min-w-[100px]">
<Badge variant={status === "paid" ? "success" : status === "overdue" ? "destructive" : "secondary"} className="text-[10px]">{status}</Badge>
<p className="text-lg font-bold mt-1">{count}</p>
<p className="text-[10px] text-muted-foreground">{fmt(amount)}</p>
</div>
))}
<div className="grid grid-cols-2 md:grid-cols-5 gap-px bg-gray-200">
{Object.entries(data.byStatus).map(([status, { count, amount }]) => {
const sl = STATUS[status] || STATUS.new
return (
<div key={status} className="bg-white p-4 text-center">
<span className={`text-[10px] font-bold px-1.5 py-0.5 ${sl.bg} ${sl.color}`}>{sl.label}</span>
<p className="text-xl font-black text-[#111827] mt-2">{count}</p>
<p className="text-[10px] text-gray-500">{formatPence(amount)}</p>
</div>
)
})}
</div>
{/* Tab switcher */}
<div className="flex gap-1.5">
{[
{ key: "orgs" as const, label: `Charities (${data.orgs.length})`, icon: Building2 },
{ key: "users" as const, label: `Users (${data.users.length})`, icon: Users },
{ key: "pledges" as const, label: "Recent Pledges", icon: Banknote },
].map(t => (
<button
key={t.key}
onClick={() => setTab(t.key)}
className={`px-4 py-2 text-xs font-bold flex items-center gap-1.5 transition-colors ${
tab === t.key ? "bg-[#111827] text-white" : "border border-gray-200 text-gray-600 hover:bg-gray-50"
}`}
>
<t.icon className="h-3.5 w-3.5" /> {t.label}
</button>
))}
</div>
{/* ── Orgs tab ── */}
{tab === "orgs" && (
<div className="bg-white border border-gray-200">
<div className="hidden md:grid grid-cols-12 gap-2 px-5 py-2.5 border-b border-gray-100 text-[10px] font-bold text-gray-400 uppercase tracking-wide">
<div className="col-span-4">Charity</div>
<div className="col-span-1">Bank</div>
<div className="col-span-1">Users</div>
<div className="col-span-2">Appeals</div>
<div className="col-span-2">Pledges</div>
<div className="col-span-2">Created</div>
</div>
</CardContent>
</Card>
{data.orgs.map(o => (
<div key={o.id} className="grid grid-cols-12 gap-2 px-5 py-3 border-b border-gray-50 items-center hover:bg-gray-50/50">
<div className="col-span-4">
<p className="text-sm font-medium text-[#111827]">{o.name}</p>
<p className="text-[10px] text-gray-400 font-mono">{o.slug}</p>
</div>
<div className="col-span-1">
<span className={`text-[9px] font-bold px-1.5 py-0.5 ${o.hasBank ? "bg-[#16A34A]/10 text-[#16A34A]" : "bg-[#F59E0B]/10 text-[#F59E0B]"}`}>
{o.hasBank ? "Set" : "Missing"}
</span>
</div>
<div className="col-span-1 text-sm text-[#111827]">{o.users}</div>
<div className="col-span-2 text-sm text-[#111827]">{o.events}</div>
<div className="col-span-2 text-sm font-bold text-[#111827]">{o.pledges}</div>
<div className="col-span-2 text-xs text-gray-500">{new Date(o.createdAt).toLocaleDateString("en-GB", { day: "numeric", month: "short" })}</div>
</div>
))}
{data.orgs.length === 0 && <div className="px-5 py-8 text-center text-sm text-gray-400">No charities yet</div>}
</div>
)}
<Tabs value={tab} onValueChange={setTab}>
<TabsList>
<TabsTrigger value="orgs">Organisations ({data.orgs.length})</TabsTrigger>
<TabsTrigger value="users">Users ({data.users.length})</TabsTrigger>
<TabsTrigger value="pledges">Recent Pledges</TabsTrigger>
</TabsList>
{/* ── Users tab ── */}
{tab === "users" && (
<div className="bg-white border border-gray-200">
<div className="hidden md:grid grid-cols-12 gap-2 px-5 py-2.5 border-b border-gray-100 text-[10px] font-bold text-gray-400 uppercase tracking-wide">
<div className="col-span-4">Email</div>
<div className="col-span-2">Name</div>
<div className="col-span-2">Role</div>
<div className="col-span-2">Charity</div>
<div className="col-span-2">Joined</div>
</div>
{data.users.map(u => (
<div key={u.id} className="grid grid-cols-12 gap-2 px-5 py-3 border-b border-gray-50 items-center hover:bg-gray-50/50">
<div className="col-span-4 text-xs font-mono text-gray-600 truncate">{u.email}</div>
<div className="col-span-2 text-sm text-[#111827]">{u.name || "—"}</div>
<div className="col-span-2">
<span className={`text-[9px] font-bold px-1.5 py-0.5 ${
u.role === "super_admin" ? "bg-[#1E40AF]/10 text-[#1E40AF]" :
u.role === "org_admin" ? "bg-[#16A34A]/10 text-[#16A34A]" :
u.role === "community_leader" ? "bg-[#F59E0B]/10 text-[#F59E0B]" :
"bg-gray-100 text-gray-500"
}`}>
{ROLE_LABELS[u.role] || u.role}
</span>
</div>
<div className="col-span-2 text-xs text-gray-600 truncate">{u.orgName}</div>
<div className="col-span-2 text-xs text-gray-500">{new Date(u.createdAt).toLocaleDateString("en-GB", { day: "numeric", month: "short" })}</div>
</div>
))}
</div>
)}
<TabsContent value="orgs">
<Card>
<CardContent className="p-0">
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Bank</TableHead>
<TableHead>Users</TableHead>
<TableHead>Events</TableHead>
<TableHead>Pledges</TableHead>
<TableHead>Created</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.orgs.map(o => (
<TableRow key={o.id}>
<TableCell>
<p className="font-medium text-sm">{o.name}</p>
<p className="text-[10px] text-muted-foreground font-mono">{o.slug}</p>
</TableCell>
<TableCell>
{o.hasBank ? <Badge variant="success" className="text-[10px]"> Set</Badge> : <Badge variant="warning" className="text-[10px]">Missing</Badge>}
</TableCell>
<TableCell className="font-medium">{o.users}</TableCell>
<TableCell className="font-medium">{o.events}</TableCell>
<TableCell className="font-medium">{o.pledges}</TableCell>
<TableCell className="text-xs text-muted-foreground">{new Date(o.createdAt).toLocaleDateString("en-GB", { day: "numeric", month: "short" })}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="users">
<Card>
<CardContent className="p-0">
<Table>
<TableHeader>
<TableRow>
<TableHead>Email</TableHead>
<TableHead>Name</TableHead>
<TableHead>Role</TableHead>
<TableHead>Organisation</TableHead>
<TableHead>Joined</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.users.map(u => (
<TableRow key={u.id}>
<TableCell className="font-mono text-xs">{u.email}</TableCell>
<TableCell className="text-sm">{u.name || "—"}</TableCell>
<TableCell>
<Badge variant={u.role === "super_admin" ? "default" : u.role === "org_admin" ? "success" : "secondary"} className="text-[10px]">
{u.role === "super_admin" ? "🛡️ Super" : u.role === "org_admin" ? "Admin" : u.role}
</Badge>
</TableCell>
<TableCell className="text-sm">{u.orgName}</TableCell>
<TableCell className="text-xs text-muted-foreground">{new Date(u.createdAt).toLocaleDateString("en-GB", { day: "numeric", month: "short" })}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="pledges">
<Card>
<CardContent className="p-0">
<Table>
<TableHeader>
<TableRow>
<TableHead>Reference</TableHead>
<TableHead>Donor</TableHead>
<TableHead>Amount</TableHead>
<TableHead>Status</TableHead>
<TableHead>Event</TableHead>
<TableHead>Org</TableHead>
<TableHead>Date</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.recentPledges.map(p => (
<TableRow key={p.id}>
<TableCell className="font-mono text-xs">{p.reference}</TableCell>
<TableCell className="text-sm">{p.donorName || "Anon"}</TableCell>
<TableCell className="font-bold text-sm">{fmt(p.amountPence)}</TableCell>
<TableCell>
<Badge variant={p.status === "paid" ? "success" : p.status === "overdue" ? "destructive" : "secondary"} className="text-[10px]">{p.status}</Badge>
</TableCell>
<TableCell className="text-xs truncate max-w-[120px]">{p.eventName}</TableCell>
<TableCell className="text-xs text-muted-foreground">{p.orgName}</TableCell>
<TableCell className="text-xs text-muted-foreground">{new Date(p.createdAt).toLocaleDateString("en-GB", { day: "numeric", month: "short" })}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
</TabsContent>
</Tabs>
{/* ── Recent pledges tab ── */}
{tab === "pledges" && (
<div className="bg-white border border-gray-200">
<div className="hidden md:grid grid-cols-12 gap-2 px-5 py-2.5 border-b border-gray-100 text-[10px] font-bold text-gray-400 uppercase tracking-wide">
<div className="col-span-2">Reference</div>
<div className="col-span-2">Donor</div>
<div className="col-span-1">Amount</div>
<div className="col-span-2">Status</div>
<div className="col-span-2">Appeal</div>
<div className="col-span-1">Charity</div>
<div className="col-span-2">Date</div>
</div>
{data.recentPledges.map(pledge => {
const sl = STATUS[pledge.status] || STATUS.new
return (
<div key={pledge.id} className="grid grid-cols-12 gap-2 px-5 py-3 border-b border-gray-50 items-center hover:bg-gray-50/50">
<div className="col-span-2 text-xs font-mono text-gray-500">{pledge.reference}</div>
<div className="col-span-2 text-sm text-[#111827]">{pledge.donorName || "Anon"}</div>
<div className="col-span-1 text-sm font-black text-[#111827]">{formatPence(pledge.amountPence)}</div>
<div className="col-span-2"><span className={`text-[9px] font-bold px-1.5 py-0.5 ${sl.bg} ${sl.color}`}>{sl.label}</span></div>
<div className="col-span-2 text-xs text-gray-600 truncate">{pledge.eventName}</div>
<div className="col-span-1 text-xs text-gray-500 truncate">{pledge.orgName}</div>
<div className="col-span-2 text-xs text-gray-500">{new Date(pledge.createdAt).toLocaleDateString("en-GB", { day: "numeric", month: "short" })}</div>
</div>
)
})}
</div>
)}
</div>
)
}

View File

@@ -0,0 +1,350 @@
"use client"
import { useState, useEffect, useCallback } from "react"
import { useSession } from "next-auth/react"
import { formatPence } from "@/lib/utils"
import {
Loader2, Copy, Check, MessageCircle, Mail, Trophy,
Plus, Link2, Download, QrCode as QrCodeIcon
} from "lucide-react"
import { QRCodeCanvas } from "@/components/qr-code"
/**
* /dashboard/community — Community Leader's dashboard
*
* Who is the Community Leader?
* Imam Yusuf. Sister Mariam. Uncle Tariq. The person who rallies
* their mosque, WhatsApp group, neighbourhood to pledge.
*
* Their mental model:
* 1. "How are WE doing?" → their community's stats vs the whole appeal
* 2. "I need to share the link" → share buttons, front and center
* 3. "Who from my group has pledged?" → simple donor list
* 4. "How do we compare?" → leaderboard across all communities
*
* What they DON'T see:
* - Bank details, WhatsApp settings, charity config
* - Other communities' donor details
* - Ability to confirm payments or change statuses
* - Full reconciliation
*
* This is a SCOPED, READ-MOSTLY view.
* They can create new links and share. That's it.
*/
interface EventSummary {
id: string; name: string; totalPledged: number; totalCollected: number; pledgeCount: number
}
interface SourceInfo {
id: string; label: string; code: string; volunteerName: string | null
scanCount: number; pledgeCount: number; totalPledged: number; totalCollected?: number
}
interface PledgeInfo {
id: string; donorName: string | null; amountPence: number; status: string; createdAt: string
}
const STATUS: Record<string, { label: string; color: string; bg: string }> = {
new: { label: "Waiting", color: "text-gray-600", bg: "bg-gray-100" },
initiated: { label: "Said paid", color: "text-[#F59E0B]", bg: "bg-[#F59E0B]/10" },
paid: { label: "Received ✓", color: "text-[#16A34A]", bg: "bg-[#16A34A]/10" },
overdue: { label: "Overdue", color: "text-[#DC2626]", bg: "bg-[#DC2626]/10" },
cancelled: { label: "Cancelled", color: "text-gray-400", bg: "bg-gray-50" },
}
export default function CommunityPage() {
const { data: session } = useSession()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const user = session?.user as any
const [events, setEvents] = useState<EventSummary[]>([])
const [allSources, setAllSources] = useState<SourceInfo[]>([])
const [mySources, setMySources] = useState<SourceInfo[]>([])
const [myPledges, setMyPledges] = useState<PledgeInfo[]>([])
const [loading, setLoading] = useState(true)
const [copiedCode, setCopiedCode] = useState<string | null>(null)
const [showQr, setShowQr] = useState<string | null>(null)
// Create link
const [newLinkName, setNewLinkName] = useState("")
const [creating, setCreating] = useState(false)
const [showCreate, setShowCreate] = useState(false)
const baseUrl = typeof window !== "undefined" ? window.location.origin : ""
const userName = user?.name || user?.email?.split("@")[0] || ""
const loadData = useCallback(async () => {
try {
const [evRes, dashRes] = await Promise.all([
fetch("/api/events").then(r => r.json()),
fetch("/api/dashboard").then(r => r.json()),
])
if (Array.isArray(evRes)) {
setEvents(evRes)
// Load sources for first event
if (evRes.length > 0) {
const srcRes = await fetch(`/api/events/${evRes[0].id}/qr`).then(r => r.json())
if (Array.isArray(srcRes)) {
setAllSources(srcRes)
// Filter to "my" sources — those with this user's name or created by this user
const mine = srcRes.filter((s: SourceInfo) =>
s.volunteerName?.toLowerCase().includes(userName.toLowerCase()) ||
s.label.toLowerCase().includes(userName.toLowerCase())
)
setMySources(mine.length > 0 ? mine : srcRes.slice(0, 3)) // fallback: show first 3
}
}
}
// Get pledges (scoped view — show recent)
if (dashRes.pledges) {
setMyPledges(dashRes.pledges.slice(0, 20))
}
} catch { /* */ }
setLoading(false)
}, [userName])
useEffect(() => { loadData() }, [loadData])
// Actions
const copyLink = async (code: string) => {
await navigator.clipboard.writeText(`${baseUrl}/p/${code}`)
setCopiedCode(code)
setTimeout(() => setCopiedCode(null), 2000)
}
const shareWhatsApp = (code: string, label: string) => {
window.open(`https://wa.me/?text=${encodeURIComponent(`Assalamu Alaikum! Please pledge here 🤲\n\n${label}\n${baseUrl}/p/${code}`)}`, "_blank")
}
const createLink = async () => {
if (!newLinkName.trim() || events.length === 0) return
setCreating(true)
try {
const res = await fetch(`/api/events/${events[0].id}/qr`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ label: newLinkName.trim(), volunteerName: userName }),
})
if (res.ok) {
const src = await res.json()
const newSrc = { ...src, scanCount: 0, pledgeCount: 0, totalPledged: 0, totalCollected: 0 }
setMySources(prev => [newSrc, ...prev])
setAllSources(prev => [newSrc, ...prev])
setNewLinkName("")
setShowCreate(false)
}
} catch { /* */ }
setCreating(false)
}
if (loading) return <div className="flex items-center justify-center py-20"><Loader2 className="h-6 w-6 text-[#1E40AF] animate-spin" /></div>
const activeEvent = events[0]
const myTotal = mySources.reduce((s, l) => s + l.totalPledged, 0)
const myPledgeCount = mySources.reduce((s, l) => s + l.pledgeCount, 0)
const appealTotal = activeEvent?.totalPledged || 0
const myPct = appealTotal > 0 ? Math.round((myTotal / appealTotal) * 100) : 0
// Leaderboard (all sources, sorted by amount)
const leaderboard = [...allSources].sort((a, b) => b.totalPledged - a.totalPledged)
return (
<div className="space-y-6">
{/* ── Header: "How are WE doing?" ── */}
<div>
<p className="text-[10px] font-bold text-gray-400 uppercase tracking-widest">
{activeEvent?.name || "Your community"}
</p>
<h1 className="text-3xl font-black text-[#111827] tracking-tight">
Welcome back, {userName.split(" ")[0] || "Leader"}
</h1>
</div>
{/* ── My community's stats vs the whole appeal ── */}
<div className="bg-[#111827] p-6">
<div className="grid grid-cols-2 gap-px bg-gray-700">
<div className="bg-[#111827] p-4">
<p className="text-[10px] text-gray-500">Your community</p>
<p className="text-3xl font-black text-white tracking-tight">{formatPence(myTotal)}</p>
<p className="text-xs text-gray-400">{myPledgeCount} pledges from {mySources.length} links</p>
</div>
<div className="bg-[#111827] p-4">
<p className="text-[10px] text-gray-500">Whole appeal</p>
<p className="text-3xl font-black text-gray-400 tracking-tight">{formatPence(appealTotal)}</p>
<p className="text-xs text-gray-400">{activeEvent?.pledgeCount || 0} total pledges</p>
</div>
</div>
{appealTotal > 0 && (
<div className="mt-4 pt-3 border-t border-gray-800">
<div className="flex justify-between text-xs text-gray-500 mb-2">
<span>Your contribution</span>
<span className="font-bold text-white">{myPct}%</span>
</div>
<div className="h-2 bg-gray-800 overflow-hidden">
<div className="h-full bg-[#4ADE80] transition-all duration-700" style={{ width: `${myPct}%` }} />
</div>
</div>
)}
</div>
{/* ── Your links + share ── */}
<div className="flex items-center justify-between">
<h2 className="text-sm font-bold text-[#111827]">Your links ({mySources.length})</h2>
<button
onClick={() => setShowCreate(true)}
className="bg-[#111827] px-3 py-1.5 text-xs font-bold text-white hover:bg-gray-800 transition-colors flex items-center gap-1.5"
>
<Plus className="h-3.5 w-3.5" /> New link
</button>
</div>
{showCreate && (
<div className="bg-white border-2 border-[#1E40AF] p-4 space-y-3">
<p className="text-sm font-bold text-[#111827]">Create a link for your community</p>
<div className="flex gap-2">
<input
value={newLinkName}
onChange={e => setNewLinkName(e.target.value)}
placeholder='e.g. "Friday Halaqa", "Sisters WhatsApp", "Youth Group"'
autoFocus
onKeyDown={e => e.key === "Enter" && createLink()}
className="flex-1 h-11 px-4 border-2 border-gray-200 text-sm placeholder:text-gray-300 focus:border-[#1E40AF] outline-none"
/>
<button onClick={createLink} disabled={!newLinkName.trim() || creating} className="bg-[#111827] px-5 h-11 text-sm font-bold text-white hover:bg-gray-800 disabled:opacity-40">
{creating ? <Loader2 className="h-4 w-4 animate-spin" /> : "Create"}
</button>
</div>
<button onClick={() => { setShowCreate(false); setNewLinkName("") }} className="text-xs text-gray-400 hover:text-gray-600">Cancel</button>
</div>
)}
{mySources.length === 0 ? (
<div className="border-2 border-dashed border-gray-200 p-8 text-center">
<Link2 className="h-8 w-8 text-gray-300 mx-auto mb-3" />
<p className="text-sm font-bold text-[#111827]">No links yet</p>
<p className="text-xs text-gray-500 mt-1">Create a link to start collecting pledges for your community</p>
</div>
) : (
<div className="space-y-3">
{mySources.map(src => {
const url = `${baseUrl}/p/${src.code}`
const isCopied = copiedCode === src.code
const isQrOpen = showQr === src.code
return (
<div key={src.id} className="bg-white border border-gray-200">
<div className="p-4">
<div className="flex items-start justify-between gap-3 mb-3">
<p className="text-sm font-bold text-[#111827]">{src.label}</p>
<div className="flex gap-px bg-gray-200 shrink-0">
<div className="bg-white px-2.5 py-1.5 text-center">
<p className="text-sm font-black text-[#111827]">{src.pledgeCount}</p>
<p className="text-[8px] text-gray-500">pledges</p>
</div>
<div className="bg-white px-2.5 py-1.5 text-center">
<p className="text-sm font-black text-[#16A34A]">{formatPence(src.totalPledged)}</p>
<p className="text-[8px] text-gray-500">raised</p>
</div>
</div>
</div>
<div className="bg-[#F9FAFB] px-3 py-2 mb-3">
<p className="text-xs font-mono text-gray-500 truncate">{url}</p>
</div>
<div className="grid grid-cols-4 gap-1.5">
<button onClick={() => copyLink(src.code)} className={`py-2.5 text-xs font-bold transition-colors flex items-center justify-center gap-1.5 ${isCopied ? "bg-[#16A34A] text-white" : "bg-[#111827] text-white hover:bg-gray-800"}`}>
{isCopied ? <><Check className="h-3.5 w-3.5" /> Copied</> : <><Copy className="h-3.5 w-3.5" /> Copy</>}
</button>
<button onClick={() => shareWhatsApp(src.code, src.label)} className="bg-[#25D366] text-white py-2.5 text-xs font-bold hover:bg-[#25D366]/90 transition-colors flex items-center justify-center gap-1.5">
<MessageCircle className="h-3.5 w-3.5" /> WhatsApp
</button>
<button onClick={() => window.open(`mailto:?subject=${encodeURIComponent(`Pledge: ${src.label}`)}&body=${encodeURIComponent(`Pledge here:\n${url}`)}`)} className="border border-gray-200 py-2.5 text-xs font-bold hover:bg-gray-50 transition-colors flex items-center justify-center gap-1.5">
<Mail className="h-3.5 w-3.5" /> Email
</button>
<button onClick={() => setShowQr(isQrOpen ? null : src.code)} className="border border-gray-200 py-2.5 text-xs font-bold hover:bg-gray-50 transition-colors flex items-center justify-center gap-1.5">
<QrCodeIcon className="h-3.5 w-3.5" /> QR
</button>
</div>
{isQrOpen && (
<div className="mt-3 pt-3 border-t border-gray-100 flex flex-col items-center gap-2">
<div className="bg-white p-2 border border-gray-100"><QRCodeCanvas url={url} size={160} /></div>
<a href={`/api/events/${events[0]?.id}/qr/${src.id}/download?code=${src.code}`} download className="text-[10px] font-semibold text-[#1E40AF] hover:underline flex items-center gap-1">
<Download className="h-3 w-3" /> Download QR image
</a>
</div>
)}
</div>
</div>
)
})}
</div>
)}
{/* ── Leaderboard — how do we compare? ── */}
{leaderboard.filter(s => s.pledgeCount > 0).length >= 2 && (
<div className="bg-white border border-gray-200">
<div className="border-b border-gray-100 px-5 py-3">
<h3 className="text-sm font-bold text-[#111827] flex items-center gap-1.5">
<Trophy className="h-4 w-4 text-[#F59E0B]" /> How communities compare
</h3>
</div>
<div className="divide-y divide-gray-50">
{leaderboard.filter(s => s.pledgeCount > 0).slice(0, 10).map((src, i) => {
const isMine = mySources.some(m => m.id === src.id)
const medals = ["bg-[#F59E0B]", "bg-gray-400", "bg-[#CD7F32]"]
return (
<div key={src.id} className={`px-5 py-3 flex items-center gap-3 ${isMine ? "bg-[#1E40AF]/5" : ""}`}>
<div className={`w-6 h-6 flex items-center justify-center text-[10px] font-black text-white ${medals[i] || "bg-gray-200 text-gray-500"}`}>
{i + 1}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<p className="text-sm font-medium text-[#111827] truncate">{src.volunteerName || src.label}</p>
{isMine && <span className="text-[9px] font-bold text-[#1E40AF] bg-[#1E40AF]/10 px-1 py-0.5">You</span>}
</div>
<p className="text-[10px] text-gray-500">{src.pledgeCount} pledges</p>
</div>
<p className="text-sm font-black text-[#111827]">{formatPence(src.totalPledged)}</p>
</div>
)
})}
</div>
</div>
)}
{/* ── Recent pledges (read-only, no actions) ── */}
{myPledges.length > 0 && (
<div className="bg-white border border-gray-200">
<div className="border-b border-gray-100 px-5 py-3">
<h3 className="text-sm font-bold text-[#111827]">Recent pledges</h3>
</div>
<div className="divide-y divide-gray-50">
{myPledges.slice(0, 10).map(p => {
const sl = STATUS[p.status] || STATUS.new
const days = Math.floor((Date.now() - new Date(p.createdAt).getTime()) / 86400000)
const when = days === 0 ? "Today" : days === 1 ? "Yesterday" : `${days}d ago`
return (
<div key={p.id} className="px-5 py-3 flex items-center gap-3">
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-[#111827] truncate">{p.donorName || "Anonymous"}</p>
<p className="text-[10px] text-gray-500">{when}</p>
</div>
<div className="text-right shrink-0">
<p className="text-sm font-black text-[#111827]">{formatPence(p.amountPence)}</p>
<span className={`text-[9px] font-bold px-1.5 py-0.5 ${sl.bg} ${sl.color}`}>{sl.label}</span>
</div>
</div>
)
})}
</div>
</div>
)}
</div>
)
}

View File

@@ -4,18 +4,16 @@ import Link from "next/link"
import { usePathname } from "next/navigation"
import { useSession, signOut } from "next-auth/react"
import { useState, useEffect } from "react"
import { Home, Megaphone, Banknote, FileText, Settings, Plus, LogOut, Shield, AlertTriangle, MessageCircle } from "lucide-react"
import { Home, Megaphone, Banknote, FileText, Settings, Plus, LogOut, Shield, AlertTriangle, MessageCircle, Users } from "lucide-react"
import { cn } from "@/lib/utils"
/**
* Navigation: goal-oriented, not feature-oriented
* "Home" — where am I at?
* "Collect" — I want people to pledge
* "Money" — where's the money?
* "Reports" — my treasurer needs numbers
* "Settings" — connect WhatsApp, bank details
* Different nav for different roles:
* - Admin/Staff: Full nav (Home, Collect, Money, Reports, Settings)
* - Community Leader: Scoped nav (My Community, Collect, Reports)
*/
const navItems = [
const adminNavItems = [
{ href: "/dashboard", label: "Home", icon: Home },
{ href: "/dashboard/collect", label: "Collect", icon: Megaphone },
{ href: "/dashboard/money", label: "Money", icon: Banknote },
@@ -23,7 +21,13 @@ const navItems = [
{ href: "/dashboard/settings", label: "Settings", icon: Settings },
]
const adminNav = { href: "/dashboard/admin", label: "Super Admin", icon: Shield }
const communityNavItems = [
{ href: "/dashboard/community", label: "My Community", icon: Users },
{ href: "/dashboard/collect", label: "Share Links", icon: Megaphone },
{ href: "/dashboard/reports", label: "Reports", icon: FileText },
]
const superAdminNav = { href: "/dashboard/admin", label: "Platform Admin", icon: Shield }
export default function DashboardLayout({ children }: { children: React.ReactNode }) {
const pathname = usePathname()
@@ -31,9 +35,13 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const user = session?.user as any
const isCommunityLeader = user?.role === "community_leader"
const navItems = isCommunityLeader ? communityNavItems : adminNavItems
// Map old routes to new ones for active state
const isActive = (href: string) => {
if (href === "/dashboard") return pathname === "/dashboard"
if (href === "/dashboard/community") return pathname === "/dashboard/community" || pathname === "/dashboard"
if (href === "/dashboard/collect") return pathname.startsWith("/dashboard/collect") || pathname.startsWith("/dashboard/events")
if (href === "/dashboard/money") return pathname.startsWith("/dashboard/money") || pathname.startsWith("/dashboard/pledges") || pathname.startsWith("/dashboard/reconcile")
if (href === "/dashboard/reports") return pathname.startsWith("/dashboard/reports") || pathname.startsWith("/dashboard/exports")
@@ -54,11 +62,13 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
</div>
</Link>
<div className="flex-1" />
<Link href="/dashboard/collect">
<button className="hidden md:inline-flex items-center gap-1.5 bg-[#111827] px-3.5 py-1.5 text-xs font-bold text-white hover:bg-gray-800 transition-colors">
<Plus className="h-3 w-3" /> New Appeal
</button>
</Link>
{!isCommunityLeader && (
<Link href="/dashboard/collect">
<button className="hidden md:inline-flex items-center gap-1.5 bg-[#111827] px-3.5 py-1.5 text-xs font-bold text-white hover:bg-gray-800 transition-colors">
<Plus className="h-3 w-3" /> New Appeal
</button>
</Link>
)}
{session && (
<button
onClick={() => signOut({ callbackUrl: "/login" })}
@@ -97,16 +107,16 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
<>
<div className="my-3 border-t border-gray-100" />
<Link
href={adminNav.href}
href={superAdminNav.href}
className={cn(
"flex items-center gap-2.5 px-3 py-2.5 text-[13px] font-medium transition-colors",
pathname === adminNav.href
pathname === superAdminNav.href
? "bg-[#1E40AF]/5 text-[#1E40AF] border-l-2 border-[#1E40AF] -ml-[2px] pl-[14px]"
: "text-gray-500 hover:bg-gray-50 hover:text-[#111827]"
)}
>
<adminNav.icon className="h-4 w-4" />
{adminNav.label}
<superAdminNav.icon className="h-4 w-4" />
{superAdminNav.label}
</Link>
</>
)}

View File

@@ -1,31 +1,76 @@
"use client"
import { useState, useEffect, useCallback } from "react"
import { useSession } from "next-auth/react"
import { Input } from "@/components/ui/input"
import {
Check, Loader2, AlertCircle,
MessageCircle, Radio, RefreshCw, Smartphone, Wifi, WifiOff, QrCode
Check, Loader2, AlertCircle, MessageCircle, Radio, RefreshCw,
Smartphone, Wifi, WifiOff, QrCode, UserPlus, Trash2, Copy,
Users, Crown, Eye
} from "lucide-react"
/**
* /dashboard/settings — Aaisha's control panel
*
* Organised by what she's thinking, not by system concept:
* 1. WhatsApp — "I need to connect" (or see it's connected)
* 2. Team — "Who has access? I need to invite Imam Yusuf"
* 3. Bank — "Where donors send money"
* 4. Your charity — name, brand colour
* 5. Direct Debit — advanced, for later
*
* Team management is NEW — the missing feature.
* This is how community leaders get invited.
*/
interface OrgSettings {
name: string; bankName: string; bankSortCode: string; bankAccountNo: string
bankAccountName: string; refPrefix: string; primaryColor: string
gcAccessToken: string; gcEnvironment: string; orgType: string
}
interface TeamMember {
id: string; email: string; name: string | null; role: string; createdAt: string
}
const ROLE_LABELS: Record<string, { label: string; desc: string; icon: typeof Crown }> = {
org_admin: { label: "Admin", desc: "Full access to everything", icon: Crown },
community_leader: { label: "Community Leader", desc: "Can see their links, pledges, and share. Can't change settings.", icon: Users },
staff: { label: "Staff", desc: "Can view pledges and reports", icon: Eye },
volunteer: { label: "Volunteer", desc: "Read-only access", icon: Eye },
}
export default function SettingsPage() {
const { data: session } = useSession()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const currentUser = session?.user as any
const [settings, setSettings] = useState<OrgSettings | null>(null)
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState<string | null>(null)
const [saved, setSaved] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null)
// Team
const [team, setTeam] = useState<TeamMember[]>([])
const [showInvite, setShowInvite] = useState(false)
const [inviteEmail, setInviteEmail] = useState("")
const [inviteName, setInviteName] = useState("")
const [inviteRole, setInviteRole] = useState("community_leader")
const [inviting, setInviting] = useState(false)
const [inviteResult, setInviteResult] = useState<{ email: string; tempPassword: string } | null>(null)
const [copiedCred, setCopiedCred] = useState(false)
useEffect(() => {
fetch("/api/settings")
.then(r => r.json())
.then(data => { if (data.name) setSettings(data) })
.catch(() => setError("Failed to load settings"))
.finally(() => setLoading(false))
Promise.all([
fetch("/api/settings").then(r => r.json()),
fetch("/api/team").then(r => r.json()).catch(() => ({ members: [] })),
]).then(([settingsData, teamData]) => {
if (settingsData.name) setSettings(settingsData)
if (teamData.members) setTeam(teamData.members)
})
.catch(() => setError("Failed to load settings"))
.finally(() => setLoading(false))
}, [])
const save = async (section: string, data: Record<string, string>) => {
@@ -38,10 +83,61 @@ export default function SettingsPage() {
setSaving(null)
}
const inviteMember = async () => {
if (!inviteEmail.trim()) return
setInviting(true)
try {
const res = await fetch("/api/team", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: inviteEmail.trim(), name: inviteName.trim(), role: inviteRole }),
})
const data = await res.json()
if (res.ok) {
setTeam(prev => [...prev, { id: data.id, email: data.email, name: data.name, role: data.role, createdAt: new Date().toISOString() }])
setInviteResult({ email: data.email, tempPassword: data.tempPassword })
setInviteEmail(""); setInviteName("")
} else {
setError(data.error || "Failed to invite")
}
} catch { setError("Failed to invite") }
setInviting(false)
}
const changeRole = async (userId: string, role: string) => {
try {
await fetch("/api/team", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId, role }),
})
setTeam(prev => prev.map(m => m.id === userId ? { ...m, role } : m))
} catch { setError("Failed to update role") }
}
const removeMember = async (userId: string) => {
if (!confirm("Remove this team member? They'll lose access immediately.")) return
try {
await fetch("/api/team", {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId }),
})
setTeam(prev => prev.filter(m => m.id !== userId))
} catch { setError("Failed to remove") }
}
const copyCredentials = (email: string, password: string) => {
navigator.clipboard.writeText(`Email: ${email}\nPassword: ${password}\nLogin: ${window.location.origin}/login`)
setCopiedCred(true)
setTimeout(() => setCopiedCred(false), 2000)
}
if (loading) return <div className="flex items-center justify-center py-20"><Loader2 className="h-6 w-6 text-[#1E40AF] animate-spin" /></div>
if (!settings) return <div className="text-center py-20"><AlertCircle className="h-6 w-6 text-[#DC2626] mx-auto mb-2" /><p className="text-sm text-gray-500">Failed to load settings</p></div>
const update = (key: keyof OrgSettings, value: string) => setSettings(s => s ? { ...s, [key]: value } : s)
const isAdmin = currentUser?.role === "org_admin" || currentUser?.role === "super_admin"
const SaveButton = ({ section, data }: { section: string; data: Record<string, string> }) => (
<button
@@ -57,19 +153,152 @@ export default function SettingsPage() {
<div className="space-y-8 max-w-2xl">
<div>
<h1 className="text-3xl font-black text-[#111827] tracking-tight">Settings</h1>
<p className="text-sm text-gray-500 mt-0.5">Your charity details, bank account, and connections</p>
<p className="text-sm text-gray-500 mt-0.5">WhatsApp, team, bank account, and charity details</p>
</div>
{error && <div className="border-l-2 border-[#DC2626] bg-[#DC2626]/5 p-3 text-sm text-[#DC2626]">{error}</div>}
{/* WhatsApp — most important, always first */}
{/* ── 1. WhatsApp ── */}
<WhatsAppPanel />
{/* Bank account */}
{/* ── 2. Team management ── */}
{isAdmin && (
<div className="bg-white border border-gray-200">
<div className="p-6 pb-4">
<div className="flex items-center justify-between mb-1">
<h3 className="text-base font-bold text-[#111827]">Team</h3>
<button
onClick={() => { setShowInvite(!showInvite); setInviteResult(null) }}
className="bg-[#111827] px-3 py-1.5 text-xs font-bold text-white hover:bg-gray-800 transition-colors flex items-center gap-1.5"
>
<UserPlus className="h-3.5 w-3.5" /> Invite
</button>
</div>
<p className="text-xs text-gray-500">People who can access your dashboard. Invite community leaders to track their pledges.</p>
</div>
{/* Invite form */}
{showInvite && !inviteResult && (
<div className="mx-6 mb-4 border-2 border-[#1E40AF] p-4 space-y-3">
<p className="text-sm font-bold text-[#111827]">Invite a team member</p>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="text-[10px] font-bold text-gray-500 block mb-1">Email</label>
<input value={inviteEmail} onChange={e => setInviteEmail(e.target.value)} placeholder="imam@mosque.org" className="w-full h-9 px-3 border-2 border-gray-200 text-sm focus:border-[#1E40AF] outline-none" />
</div>
<div>
<label className="text-[10px] font-bold text-gray-500 block mb-1">Name <span className="font-normal text-gray-400">(optional)</span></label>
<input value={inviteName} onChange={e => setInviteName(e.target.value)} placeholder="Imam Yusuf" className="w-full h-9 px-3 border-2 border-gray-200 text-sm focus:border-[#1E40AF] outline-none" />
</div>
</div>
<div>
<label className="text-[10px] font-bold text-gray-500 block mb-2">Role</label>
<div className="grid grid-cols-2 gap-2">
{Object.entries(ROLE_LABELS).filter(([k]) => k !== "org_admin" || currentUser?.role === "super_admin").map(([key, r]) => (
<button
key={key}
onClick={() => setInviteRole(key)}
className={`border-2 p-3 text-left transition-all ${inviteRole === key ? "border-[#1E40AF] bg-[#1E40AF]/5" : "border-gray-200"}`}
>
<p className="text-xs font-bold text-[#111827]">{r.label}</p>
<p className="text-[10px] text-gray-500 mt-0.5">{r.desc}</p>
</button>
))}
</div>
</div>
<div className="flex gap-2">
<button onClick={() => setShowInvite(false)} className="flex-1 border border-gray-200 py-2 text-xs font-bold text-[#111827] hover:bg-gray-50">Cancel</button>
<button onClick={inviteMember} disabled={!inviteEmail.trim() || inviting} className="flex-1 bg-[#111827] py-2 text-xs font-bold text-white hover:bg-gray-800 disabled:opacity-40 flex items-center justify-center gap-1.5">
{inviting ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : "Send invite"}
</button>
</div>
</div>
)}
{/* Invite result — show credentials once */}
{inviteResult && (
<div className="mx-6 mb-4 bg-[#16A34A]/5 border border-[#16A34A]/20 p-4 space-y-3">
<div className="flex items-center gap-2">
<Check className="h-4 w-4 text-[#16A34A]" />
<p className="text-sm font-bold text-[#111827]">Invited!</p>
</div>
<p className="text-xs text-gray-600">Share these login details with them. The password is shown only once.</p>
<div className="bg-white border border-gray-200 p-3 font-mono text-xs space-y-1">
<p>Email: <strong>{inviteResult.email}</strong></p>
<p>Password: <strong>{inviteResult.tempPassword}</strong></p>
<p>Login: <strong>{typeof window !== "undefined" ? window.location.origin : ""}/login</strong></p>
</div>
<div className="flex gap-2">
<button
onClick={() => copyCredentials(inviteResult.email, inviteResult.tempPassword)}
className="flex-1 bg-[#111827] py-2 text-xs font-bold text-white hover:bg-gray-800 flex items-center justify-center gap-1.5"
>
{copiedCred ? <><Check className="h-3 w-3" /> Copied</> : <><Copy className="h-3 w-3" /> Copy credentials</>}
</button>
<button
onClick={() => {
const text = `Your login for ${settings?.name || "Pledge Now Pay Later"}:\n\nEmail: ${inviteResult.email}\nPassword: ${inviteResult.tempPassword}\nLogin: ${window.location.origin}/login`
window.open(`https://wa.me/?text=${encodeURIComponent(text)}`, "_blank")
}}
className="bg-[#25D366] py-2 px-4 text-xs font-bold text-white hover:bg-[#25D366]/90 flex items-center gap-1.5"
>
<MessageCircle className="h-3 w-3" /> WhatsApp
</button>
</div>
<button onClick={() => { setInviteResult(null); setShowInvite(false) }} className="text-xs text-gray-400 hover:text-gray-600">Done</button>
</div>
)}
{/* Team list */}
<div className="divide-y divide-gray-50">
{team.map(m => {
const r = ROLE_LABELS[m.role] || ROLE_LABELS.staff
const isCurrentUser = m.id === currentUser?.id
const RoleIcon = r.icon
return (
<div key={m.id} className="px-6 py-3 flex items-center gap-3">
<div className="w-8 h-8 bg-[#1E40AF]/10 flex items-center justify-center shrink-0">
<RoleIcon className="h-4 w-4 text-[#1E40AF]" />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<p className="text-sm font-medium text-[#111827] truncate">{m.name || m.email}</p>
{isCurrentUser && <span className="text-[9px] font-bold text-gray-400">You</span>}
</div>
<p className="text-[10px] text-gray-500">{m.email}</p>
</div>
<div className="flex items-center gap-2 shrink-0">
{isAdmin && !isCurrentUser ? (
<select
value={m.role}
onChange={e => changeRole(m.id, e.target.value)}
className="text-[10px] font-bold border border-gray-200 px-2 py-1 bg-white"
>
{Object.entries(ROLE_LABELS).map(([key, v]) => (
<option key={key} value={key}>{v.label}</option>
))}
</select>
) : (
<span className="text-[10px] font-bold px-2 py-0.5 bg-gray-100 text-gray-600">{r.label}</span>
)}
{isAdmin && !isCurrentUser && (
<button onClick={() => removeMember(m.id)} className="text-gray-300 hover:text-[#DC2626] p-1 transition-colors">
<Trash2 className="h-3.5 w-3.5" />
</button>
)}
</div>
</div>
)
})}
</div>
</div>
)}
{/* ── 3. Bank account ── */}
<div className="bg-white border border-gray-200 p-6 space-y-4">
<div>
<h3 className="text-base font-bold text-[#111827]">Bank account</h3>
<p className="text-xs text-gray-500 mt-0.5">These details are shown to donors so they can transfer money to you. Each pledge gets a unique reference code.</p>
<p className="text-xs text-gray-500 mt-0.5">Shown to donors so they know where to transfer. Each pledge gets a unique reference.</p>
</div>
<div className="grid grid-cols-2 gap-3">
<div><label className="text-[10px] font-bold text-gray-500 block mb-1">Bank name</label><Input value={settings.bankName} onChange={e => update("bankName", e.target.value)} placeholder="e.g. Barclays" /></div>
@@ -80,41 +309,18 @@ export default function SettingsPage() {
<div><label className="text-[10px] font-bold text-gray-500 block mb-1">Account number</label><Input value={settings.bankAccountNo} onChange={e => update("bankAccountNo", e.target.value)} placeholder="12345678" /></div>
</div>
<div>
<label className="text-[10px] font-bold text-gray-500 block mb-1">Reference code prefix</label>
<label className="text-[10px] font-bold text-gray-500 block mb-1">Reference prefix</label>
<Input value={settings.refPrefix} onChange={e => update("refPrefix", e.target.value)} maxLength={4} className="w-24" />
<p className="text-[10px] text-gray-400 mt-1">Donors will see references like <strong>{settings.refPrefix}-XXXX-50</strong></p>
<p className="text-[10px] text-gray-400 mt-1">Donors see references like <strong>{settings.refPrefix}-XXXX-50</strong></p>
</div>
<SaveButton section="bank" data={{ bankName: settings.bankName, bankSortCode: settings.bankSortCode, bankAccountNo: settings.bankAccountNo, bankAccountName: settings.bankAccountName, refPrefix: settings.refPrefix }} />
</div>
{/* Direct Debit */}
<div className="bg-white border border-gray-200 p-6 space-y-4">
<div>
<h3 className="text-base font-bold text-[#111827]">Direct Debit</h3>
<p className="text-xs text-gray-500 mt-0.5">Accept Direct Debit payments via GoCardless. Donors set up a mandate and payments are collected automatically.</p>
</div>
<div>
<label className="text-[10px] font-bold text-gray-500 block mb-1">GoCardless access token</label>
<Input type="password" value={settings.gcAccessToken} onChange={e => update("gcAccessToken", e.target.value)} placeholder="sandbox_xxxxx or live_xxxxx" />
</div>
<div>
<label className="text-[10px] font-bold text-gray-500 block mb-1">Mode</label>
<div className="flex gap-2 mt-1">
{["sandbox", "live"].map(env => (
<button key={env} onClick={() => update("gcEnvironment", env)} className={`px-3 py-1.5 text-xs font-bold border-2 transition-colors ${settings.gcEnvironment === env ? env === "live" ? "border-[#DC2626] bg-[#DC2626]/5 text-[#DC2626]" : "border-[#1E40AF] bg-[#1E40AF]/5 text-[#1E40AF]" : "border-gray-200 text-gray-400"}`}>
{env === "sandbox" ? "Test mode" : "Live mode"}
</button>
))}
</div>
</div>
<SaveButton section="gc" data={{ gcAccessToken: settings.gcAccessToken, gcEnvironment: settings.gcEnvironment }} />
</div>
{/* Branding */}
{/* ── 4. Charity details ── */}
<div className="bg-white border border-gray-200 p-6 space-y-4">
<div>
<h3 className="text-base font-bold text-[#111827]">Your charity</h3>
<p className="text-xs text-gray-500 mt-0.5">This name and colour appear on pledge pages and WhatsApp messages.</p>
<p className="text-xs text-gray-500 mt-0.5">Name and colour shown on pledge pages and WhatsApp messages.</p>
</div>
<div><label className="text-[10px] font-bold text-gray-500 block mb-1">Charity name</label><Input value={settings.name} onChange={e => update("name", e.target.value)} /></div>
<div>
@@ -126,11 +332,36 @@ export default function SettingsPage() {
</div>
<SaveButton section="brand" data={{ name: settings.name, primaryColor: settings.primaryColor }} />
</div>
{/* ── 5. Direct Debit (collapsed) ── */}
<details className="bg-white border border-gray-200">
<summary className="p-6 text-base font-bold text-[#111827] cursor-pointer hover:bg-gray-50 transition-colors">
Direct Debit <span className="text-xs font-normal text-gray-400 ml-2">GoCardless integration</span>
</summary>
<div className="px-6 pb-6 space-y-4 border-t border-gray-100 pt-4">
<p className="text-xs text-gray-500">Accept Direct Debit payments via GoCardless. Donors set up a mandate and payments are collected automatically.</p>
<div>
<label className="text-[10px] font-bold text-gray-500 block mb-1">GoCardless access token</label>
<Input type="password" value={settings.gcAccessToken} onChange={e => update("gcAccessToken", e.target.value)} placeholder="sandbox_xxxxx or live_xxxxx" />
</div>
<div>
<label className="text-[10px] font-bold text-gray-500 block mb-1">Mode</label>
<div className="flex gap-2 mt-1">
{["sandbox", "live"].map(env => (
<button key={env} onClick={() => update("gcEnvironment", env)} className={`px-3 py-1.5 text-xs font-bold border-2 transition-colors ${settings.gcEnvironment === env ? env === "live" ? "border-[#DC2626] bg-[#DC2626]/5 text-[#DC2626]" : "border-[#1E40AF] bg-[#1E40AF]/5 text-[#1E40AF]" : "border-gray-200 text-gray-400"}`}>
{env === "sandbox" ? "Test mode" : "Live mode"}
</button>
))}
</div>
</div>
<SaveButton section="gc" data={{ gcAccessToken: settings.gcAccessToken, gcEnvironment: settings.gcEnvironment }} />
</div>
</details>
</div>
)
}
// ─── WhatsApp Connection Panel ───────────────────────────────
// ─── WhatsApp Connection Panel (unchanged) ───────────────────
function WhatsAppPanel() {
const [status, setStatus] = useState<string>("loading")
@@ -167,10 +398,7 @@ function WhatsAppPanel() {
</div>
<div className="flex items-center gap-4">
<div className="w-10 h-10 bg-[#25D366]/10 flex items-center justify-center"><Smartphone className="h-5 w-5 text-[#25D366]" /></div>
<div>
<p className="text-sm font-medium text-[#111827]">{pushName || "WhatsApp"}</p>
<p className="text-xs text-gray-500">+{phone}</p>
</div>
<div><p className="text-sm font-medium text-[#111827]">{pushName || "WhatsApp"}</p><p className="text-xs text-gray-500">+{phone}</p></div>
<Wifi className="h-5 w-5 text-[#25D366] ml-auto" />
</div>
<div className="mt-4 pt-3 border-t border-[#25D366]/10 grid grid-cols-3 gap-3">
@@ -178,12 +406,7 @@ function WhatsAppPanel() {
{ label: "Receipts", desc: "Auto-sends when someone pledges" },
{ label: "Reminders", desc: "4-step reminder sequence" },
{ label: "Chatbot", desc: "Donors reply PAID, HELP, etc." },
].map(f => (
<div key={f.label} className="text-center">
<p className="text-xs font-bold text-[#111827]">{f.label}</p>
<p className="text-[9px] text-gray-500 mt-0.5">{f.desc}</p>
</div>
))}
].map(f => (<div key={f.label} className="text-center"><p className="text-xs font-bold text-[#111827]">{f.label}</p><p className="text-[9px] text-gray-500 mt-0.5">{f.desc}</p></div>))}
</div>
</div>
)
@@ -194,7 +417,7 @@ function WhatsAppPanel() {
<div className="bg-white border border-[#F59E0B]/30 p-6">
<div className="flex items-center gap-2 mb-4">
<h3 className="text-base font-bold text-[#111827]">WhatsApp</h3>
<span className="text-[10px] font-bold px-1.5 py-0.5 bg-[#F59E0B]/10 text-[#F59E0B] flex items-center gap-1"><QrCode className="h-2.5 w-2.5" /> Scan QR code</span>
<span className="text-[10px] font-bold px-1.5 py-0.5 bg-[#F59E0B]/10 text-[#F59E0B] flex items-center gap-1"><QrCode className="h-2.5 w-2.5" /> Scan QR</span>
</div>
<div className="flex flex-col items-center gap-4">
{qrImage ? (
@@ -203,18 +426,13 @@ function WhatsAppPanel() {
<img src={qrImage} alt="WhatsApp QR Code" className="w-[200%] h-auto max-w-none" style={{ marginLeft: "-30%", marginTop: "-35%" }} />
</div>
) : (
<div className="w-64 h-64 border-2 border-dashed border-gray-200 flex items-center justify-center">
<Loader2 className="h-6 w-6 text-gray-400 animate-spin" />
</div>
<div className="w-64 h-64 border-2 border-dashed border-gray-200 flex items-center justify-center"><Loader2 className="h-6 w-6 text-gray-400 animate-spin" /></div>
)}
<div className="text-center space-y-1">
<p className="text-sm font-bold text-[#111827]">Scan with your phone</p>
<p className="text-xs text-gray-500">Open WhatsApp Settings Linked Devices Link a Device</p>
<p className="text-[10px] text-gray-400">Auto-refreshes every 5 seconds</p>
<p className="text-xs text-gray-500">WhatsApp Settings Linked Devices Link a Device</p>
</div>
<button onClick={checkStatus} className="border border-gray-200 px-3 py-1.5 text-xs font-semibold text-gray-600 hover:bg-gray-50 flex items-center gap-1.5">
<RefreshCw className="h-3 w-3" /> Refresh
</button>
<button onClick={checkStatus} className="border border-gray-200 px-3 py-1.5 text-xs font-semibold text-gray-600 hover:bg-gray-50 flex items-center gap-1.5"><RefreshCw className="h-3 w-3" /> Refresh</button>
</div>
</div>
)
@@ -233,15 +451,11 @@ function WhatsAppPanel() {
<p className="font-medium text-gray-600"> Pledge receipts with bank details</p>
<p className="font-medium text-gray-600"> Payment reminders on a 4-step schedule</p>
<p className="font-medium text-gray-600"> A chatbot (they reply PAID, HELP, or CANCEL)</p>
<p className="font-medium text-gray-600"> Volunteer notifications on each pledge</p>
</div>
</div>
<button onClick={startSession} disabled={starting} className="mt-4 w-full bg-[#25D366] px-4 py-2.5 text-sm font-bold text-white hover:bg-[#25D366]/90 disabled:opacity-50 transition-colors flex items-center justify-center gap-2">
{starting ? <><Loader2 className="h-4 w-4 animate-spin" /> Starting...</> : <><MessageCircle className="h-4 w-4" /> Connect WhatsApp</>}
</button>
<p className="text-[10px] text-gray-400 text-center mt-2">
Free no WhatsApp Business API required
</p>
</div>
)
}