feat: initial NFC Attendance Hub implementation

- Multi-tenant client management with unique API keys
- Semaphore SMS integration (per-client key + sender name + credit balance)
- DB-based SMS queue with 3-attempt retry and exponential backoff
- Failed SMS dashboard with manual retry button
- Reports page with date/client filter and CSV export
- Admin auth via NextAuth (email/password)
- Docker Compose setup (app + PostgreSQL 16)
- Prisma 5 schema with SmsQueue, SmsLog, Client, User models

Tech: Next.js 14 App Router + TypeScript + Tailwind CSS + Prisma + PostgreSQL
This commit is contained in:
Nemo
2026-03-12 08:49:13 +00:00
parent bb3f8d0ef2
commit b273f1a573
53 changed files with 6000 additions and 2 deletions

View File

@@ -0,0 +1,164 @@
'use client'
import { useState, useEffect } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import Link from 'next/link'
import { ArrowLeft, RefreshCw, Copy, Check } from 'lucide-react'
export default function ClientSettingsPage() {
const params = useParams()
const router = useRouter()
const [client, setClient] = useState<any>(null)
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [copied, setCopied] = useState(false)
const [error, setError] = useState('')
const [success, setSuccess] = useState('')
const [form, setForm] = useState({ name: '', semaphoreKey: '', senderName: '', isActive: true })
useEffect(() => {
fetch(`/api/clients/${params.id}`)
.then(r => r.json())
.then(data => {
setClient(data)
setForm({
name: data.name,
semaphoreKey: data.semaphoreKey || '',
senderName: data.senderName || 'NFC-HUB',
isActive: data.isActive,
})
setLoading(false)
})
}, [params.id])
async function handleSave(e: React.FormEvent) {
e.preventDefault()
setSaving(true)
setError('')
setSuccess('')
const res = await fetch(`/api/clients/${params.id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(form),
})
if (res.ok) {
setSuccess('Settings saved successfully')
const updated = await res.json()
setClient((prev: any) => ({ ...prev, ...updated }))
} else {
const data = await res.json()
setError(data.error || 'Save failed')
}
setSaving(false)
}
async function copyApiKey() {
await navigator.clipboard.writeText(client.apiKey)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
}
if (loading) return <div className="text-gray-500">Loading...</div>
if (!client) return <div className="text-red-500">Client not found</div>
return (
<div className="space-y-6">
<div className="flex items-center gap-4">
<Link href="/dashboard/clients">
<Button variant="ghost" size="sm">
<ArrowLeft className="h-4 w-4 mr-2" />
Back
</Button>
</Link>
<div>
<h1 className="text-3xl font-bold text-gray-900">{client.name}</h1>
<p className="text-gray-500">Client settings and API configuration</p>
</div>
</div>
{/* API Key Card */}
<Card>
<CardHeader>
<CardTitle>API Key</CardTitle>
<CardDescription>Use this key in the X-API-Key header for SMS submissions.</CardDescription>
</CardHeader>
<CardContent>
<div className="flex items-center gap-2">
<code className="flex-1 bg-gray-100 px-4 py-2 rounded-md text-sm font-mono">{client.apiKey}</code>
<Button variant="outline" size="sm" onClick={copyApiKey}>
{copied ? <Check className="h-4 w-4 text-green-600" /> : <Copy className="h-4 w-4" />}
</Button>
</div>
</CardContent>
</Card>
{/* Credit Balance */}
{client.semaphoreKey && (
<Card>
<CardHeader>
<CardTitle>Semaphore Credits</CardTitle>
</CardHeader>
<CardContent>
<div className="text-3xl font-bold text-green-600">
{client.balance !== null ? client.balance.toLocaleString() : 'N/A'}
</div>
<p className="text-sm text-gray-500 mt-1">Available SMS credits</p>
</CardContent>
</Card>
)}
{/* Settings Form */}
<Card className="max-w-2xl">
<CardHeader>
<CardTitle>Settings</CardTitle>
</CardHeader>
<CardContent>
<form onSubmit={handleSave} className="space-y-4">
{error && <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md text-sm">{error}</div>}
{success && <div className="bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-md text-sm">{success}</div>}
<div className="space-y-2">
<Label>Organization Name</Label>
<Input value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} required />
</div>
<div className="space-y-2">
<Label>Semaphore API Key</Label>
<Input
value={form.semaphoreKey}
onChange={e => setForm(f => ({ ...f, semaphoreKey: e.target.value }))}
placeholder="Enter Semaphore API key"
type="password"
/>
</div>
<div className="space-y-2">
<Label>SMS Sender Name</Label>
<Input
value={form.senderName}
onChange={e => setForm(f => ({ ...f, senderName: e.target.value }))}
maxLength={11}
/>
</div>
<div className="flex items-center gap-3">
<input
type="checkbox"
id="isActive"
checked={form.isActive}
onChange={e => setForm(f => ({ ...f, isActive: e.target.checked }))}
className="h-4 w-4"
/>
<Label htmlFor="isActive">Client is active</Label>
</div>
<Button type="submit" disabled={saving}>
{saving ? 'Saving...' : 'Save Settings'}
</Button>
</form>
</CardContent>
</Card>
</div>
)
}

View File

@@ -0,0 +1,112 @@
'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import Link from 'next/link'
import { ArrowLeft } from 'lucide-react'
export default function NewClientPage() {
const router = useRouter()
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const [form, setForm] = useState({
name: '',
semaphoreKey: '',
senderName: 'NFC-HUB',
})
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
setLoading(true)
setError('')
const res = await fetch('/api/clients', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(form),
})
if (res.ok) {
router.push('/dashboard/clients')
} else {
const data = await res.json()
setError(data.error || 'Failed to create client')
setLoading(false)
}
}
return (
<div className="space-y-6">
<div className="flex items-center gap-4">
<Link href="/dashboard/clients">
<Button variant="ghost" size="sm">
<ArrowLeft className="h-4 w-4 mr-2" />
Back
</Button>
</Link>
<div>
<h1 className="text-3xl font-bold text-gray-900">Add Client</h1>
<p className="text-gray-500">Register a new school or organization</p>
</div>
</div>
<Card className="max-w-2xl">
<CardHeader>
<CardTitle>Client Details</CardTitle>
<CardDescription>
Each client gets a unique API key for their on-premise NFC attendance app.
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md text-sm">{error}</div>
)}
<div className="space-y-2">
<Label htmlFor="name">Organization Name *</Label>
<Input
id="name"
value={form.name}
onChange={e => setForm(f => ({ ...f, name: e.target.value }))}
placeholder="e.g. San Jose Elementary School"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="semaphoreKey">Semaphore API Key</Label>
<Input
id="semaphoreKey"
value={form.semaphoreKey}
onChange={e => setForm(f => ({ ...f, semaphoreKey: e.target.value }))}
placeholder="Your Semaphore API key"
/>
<p className="text-xs text-gray-500">You can add this later in client settings.</p>
</div>
<div className="space-y-2">
<Label htmlFor="senderName">SMS Sender Name</Label>
<Input
id="senderName"
value={form.senderName}
onChange={e => setForm(f => ({ ...f, senderName: e.target.value }))}
placeholder="NFC-HUB"
maxLength={11}
/>
<p className="text-xs text-gray-500">Max 11 characters. Must be registered with Semaphore.</p>
</div>
<div className="flex gap-3 pt-2">
<Button type="submit" disabled={loading}>
{loading ? 'Creating...' : 'Create Client'}
</Button>
<Link href="/dashboard/clients">
<Button type="button" variant="outline">Cancel</Button>
</Link>
</div>
</form>
</CardContent>
</Card>
</div>
)
}

View File

@@ -0,0 +1,86 @@
import Link from 'next/link'
import { prisma } from '@/lib/prisma'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Plus, Settings } from 'lucide-react'
export default async function ClientsPage() {
const clients = await prisma.client.findMany({
orderBy: { createdAt: 'desc' },
include: {
_count: { select: { smsQueue: true, smsLogs: true } },
},
})
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold text-gray-900">Clients</h1>
<p className="text-gray-500 mt-1">Manage schools and organizations</p>
</div>
<Link href="/dashboard/clients/new">
<Button>
<Plus className="h-4 w-4 mr-2" />
Add Client
</Button>
</Link>
</div>
{clients.length === 0 ? (
<Card>
<CardContent className="text-center py-16">
<p className="text-gray-500 mb-4">No clients yet</p>
<Link href="/dashboard/clients/new">
<Button>
<Plus className="h-4 w-4 mr-2" />
Add Your First Client
</Button>
</Link>
</CardContent>
</Card>
) : (
<div className="grid gap-4">
{clients.map(client => (
<Card key={client.id}>
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div className="flex-1">
<div className="flex items-center gap-3">
<h3 className="font-semibold text-lg">{client.name}</h3>
<Badge variant={client.isActive ? 'success' : 'secondary'}>
{client.isActive ? 'Active' : 'Inactive'}
</Badge>
{client.semaphoreKey ? (
<Badge variant="outline" className="text-xs">SMS Configured</Badge>
) : (
<Badge variant="warning" className="text-xs"> No SMS Key</Badge>
)}
</div>
<div className="mt-2 space-y-1">
<p className="text-sm text-gray-500">
<span className="font-medium">API Key:</span>{' '}
<code className="bg-gray-100 px-2 py-0.5 rounded text-xs">{client.apiKey}</code>
</p>
<p className="text-sm text-gray-500">
<span className="font-medium">Sender:</span> {client.senderName || 'NFC-HUB'} ·{' '}
<span className="font-medium">SMS sent:</span> {client._count.smsLogs}
</p>
</div>
</div>
<Link href={`/dashboard/clients/${client.id}`}>
<Button variant="outline" size="sm">
<Settings className="h-4 w-4 mr-2" />
Settings
</Button>
</Link>
</div>
</CardContent>
</Card>
))}
</div>
)}
</div>
)
}

18
app/dashboard/layout.tsx Normal file
View File

@@ -0,0 +1,18 @@
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { redirect } from 'next/navigation'
import { Sidebar } from '@/components/sidebar'
export default async function DashboardLayout({ children }: { children: React.ReactNode }) {
const session = await getServerSession(authOptions)
if (!session) redirect('/login')
return (
<div className="flex min-h-screen bg-gray-50">
<Sidebar />
<main className="flex-1 overflow-auto">
<div className="p-8">{children}</div>
</main>
</div>
)
}

92
app/dashboard/page.tsx Normal file
View File

@@ -0,0 +1,92 @@
import { prisma } from '@/lib/prisma'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Building2, MessageSquare, CheckCircle, XCircle, Clock } from 'lucide-react'
export default async function DashboardPage() {
const [totalClients, activeClients, pendingCount, sentCount, failedCount] = await Promise.all([
prisma.client.count(),
prisma.client.count({ where: { isActive: true } }),
prisma.smsQueue.count({ where: { status: { in: ['PENDING', 'RETRYING'] } } }),
prisma.smsQueue.count({ where: { status: 'SENT' } }),
prisma.smsQueue.count({ where: { status: 'FAILED' } }),
])
const recentLogs = await prisma.smsLog.findMany({
take: 10,
orderBy: { sentAt: 'desc' },
include: { client: { select: { name: true } }, queue: true },
})
const stats = [
{ title: 'Total Clients', value: totalClients, sub: `${activeClients} active`, icon: Building2, color: 'text-blue-600' },
{ title: 'Pending SMS', value: pendingCount, sub: 'In queue', icon: Clock, color: 'text-yellow-600' },
{ title: 'SMS Sent', value: sentCount, sub: 'All time', icon: CheckCircle, color: 'text-green-600' },
{ title: 'Failed SMS', value: failedCount, sub: 'Needs attention', icon: XCircle, color: 'text-red-600' },
]
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
<p className="text-gray-500 mt-1">Overview of your NFC Attendance Hub</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
{stats.map(stat => {
const Icon = stat.icon
return (
<Card key={stat.title}>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium text-gray-600">{stat.title}</CardTitle>
<Icon className={`h-5 w-5 ${stat.color}`} />
</CardHeader>
<CardContent>
<div className="text-3xl font-bold">{stat.value}</div>
<p className="text-xs text-gray-500 mt-1">{stat.sub}</p>
</CardContent>
</Card>
)
})}
</div>
<Card>
<CardHeader>
<CardTitle>Recent SMS Activity</CardTitle>
</CardHeader>
<CardContent>
{recentLogs.length === 0 ? (
<p className="text-gray-500 text-sm text-center py-8">No SMS activity yet</p>
) : (
<div className="space-y-2">
{recentLogs.map(log => (
<div key={log.id} className="flex items-center justify-between py-2 border-b last:border-0">
<div className="flex-1">
<span className="font-medium text-sm">{log.queue.studentName}</span>
<span className="text-gray-500 text-xs ml-2">({log.queue.studentId})</span>
<span className="text-xs text-gray-400 ml-2">via {log.client.name}</span>
</div>
<div className="flex items-center gap-2">
<span className={`text-xs px-2 py-1 rounded-full font-medium ${
log.queue.event === 'time_in'
? 'bg-green-100 text-green-700'
: 'bg-orange-100 text-orange-700'
}`}>
{log.queue.event === 'time_in' ? '✅ Time In' : '🔴 Time Out'}
</span>
<span className={`text-xs px-2 py-1 rounded-full ${
log.status === 'SUCCESS'
? 'bg-green-100 text-green-700'
: 'bg-red-100 text-red-700'
}`}>
{log.status}
</span>
</div>
</div>
))}
</div>
)}
</CardContent>
</Card>
</div>
)
}

View File

@@ -0,0 +1,191 @@
'use client'
import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Download, Search, BarChart3 } from 'lucide-react'
export default function ReportsPage() {
const [clients, setClients] = useState<any[]>([])
const [logs, setLogs] = useState<any[]>([])
const [stats, setStats] = useState<any>(null)
const [loading, setLoading] = useState(false)
const [filters, setFilters] = useState({ clientId: '', from: '', to: '' })
useEffect(() => {
fetch('/api/clients').then(r => r.json()).then(setClients)
loadReports()
}, [])
async function loadReports() {
setLoading(true)
const params = new URLSearchParams()
if (filters.clientId) params.append('clientId', filters.clientId)
if (filters.from) params.append('from', filters.from)
if (filters.to) params.append('to', filters.to)
const res = await fetch(`/api/reports?${params}`)
const data = await res.json()
setStats(data)
setLogs(data.logs || [])
setLoading(false)
}
async function handleExportCsv() {
const params = new URLSearchParams({ format: 'csv' })
if (filters.clientId) params.append('clientId', filters.clientId)
if (filters.from) params.append('from', filters.from)
if (filters.to) params.append('to', filters.to)
const res = await fetch(`/api/reports?${params}`)
const blob = await res.blob()
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `sms-report-${Date.now()}.csv`
a.click()
URL.revokeObjectURL(url)
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold text-gray-900">Reports</h1>
<p className="text-gray-500 mt-1">SMS delivery statistics and logs</p>
</div>
<Button onClick={handleExportCsv} variant="outline">
<Download className="h-4 w-4 mr-2" />
Export CSV
</Button>
</div>
{/* Filters */}
<Card>
<CardHeader><CardTitle className="text-base">Filters</CardTitle></CardHeader>
<CardContent>
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
<div className="space-y-1">
<Label>Client</Label>
<select
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
value={filters.clientId}
onChange={e => setFilters(f => ({ ...f, clientId: e.target.value }))}
>
<option value="">All Clients</option>
{clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
</select>
</div>
<div className="space-y-1">
<Label>From Date</Label>
<Input
type="date"
value={filters.from}
onChange={e => setFilters(f => ({ ...f, from: e.target.value }))}
/>
</div>
<div className="space-y-1">
<Label>To Date</Label>
<Input
type="date"
value={filters.to}
onChange={e => setFilters(f => ({ ...f, to: e.target.value }))}
/>
</div>
<div className="flex items-end">
<Button onClick={loadReports} disabled={loading} className="w-full">
<Search className="h-4 w-4 mr-2" />
{loading ? 'Loading...' : 'Search'}
</Button>
</div>
</div>
</CardContent>
</Card>
{/* Stats */}
{stats && (
<div className="grid grid-cols-3 gap-4">
<Card>
<CardContent className="pt-6">
<div className="text-3xl font-bold">{stats.total}</div>
<p className="text-sm text-gray-500">Total SMS</p>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="text-3xl font-bold text-green-600">{stats.success}</div>
<p className="text-sm text-gray-500">Delivered</p>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="text-3xl font-bold text-red-600">{stats.failed}</div>
<p className="text-sm text-gray-500">Failed</p>
</CardContent>
</Card>
</div>
)}
{/* Logs table */}
<Card>
<CardHeader><CardTitle>SMS Logs</CardTitle></CardHeader>
<CardContent className="p-0">
{loading ? (
<p className="text-center text-gray-500 py-8">Loading...</p>
) : logs.length === 0 ? (
<p className="text-center text-gray-500 py-8">No records found</p>
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead className="bg-gray-50 border-b">
<tr>
<th className="text-left px-4 py-3 font-medium text-gray-600">Date</th>
<th className="text-left px-4 py-3 font-medium text-gray-600">Client</th>
<th className="text-left px-4 py-3 font-medium text-gray-600">Student</th>
<th className="text-left px-4 py-3 font-medium text-gray-600">Phone</th>
<th className="text-left px-4 py-3 font-medium text-gray-600">Event</th>
<th className="text-left px-4 py-3 font-medium text-gray-600">Status</th>
<th className="text-left px-4 py-3 font-medium text-gray-600">Error</th>
</tr>
</thead>
<tbody className="divide-y">
{logs.map((log: any) => (
<tr key={log.id} className="hover:bg-gray-50">
<td className="px-4 py-3 text-xs text-gray-500">
{new Date(log.sentAt).toLocaleString('en-PH', { timeZone: 'Asia/Manila' })}
</td>
<td className="px-4 py-3 text-gray-600">{log.client.name}</td>
<td className="px-4 py-3">
<div className="font-medium">{log.queue.studentName}</div>
<div className="text-xs text-gray-500">{log.queue.studentId}</div>
</td>
<td className="px-4 py-3 text-gray-600">{log.phone}</td>
<td className="px-4 py-3">
<span className={`px-2 py-1 rounded-full text-xs font-medium ${
log.queue.event === 'time_in'
? 'bg-green-100 text-green-700'
: 'bg-orange-100 text-orange-700'
}`}>
{log.queue.event === 'time_in' ? '✅ In' : '🔴 Out'}
</span>
</td>
<td className="px-4 py-3">
<span className={`px-2 py-1 rounded-full text-xs font-medium ${
log.status === 'SUCCESS'
? 'bg-green-100 text-green-700'
: 'bg-red-100 text-red-700'
}`}>
{log.status}
</span>
</td>
<td className="px-4 py-3 text-xs text-red-500">{log.errorReason || '-'}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
</div>
)
}

View File

@@ -0,0 +1,125 @@
'use client'
import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { RefreshCw, AlertTriangle } from 'lucide-react'
export default function FailedSmsPage() {
const [failed, setFailed] = useState<any[]>([])
const [loading, setLoading] = useState(true)
const [retrying, setRetrying] = useState<string | null>(null)
const [message, setMessage] = useState('')
async function loadFailed() {
setLoading(true)
const res = await fetch('/api/sms/failed')
const data = await res.json()
setFailed(data)
setLoading(false)
}
useEffect(() => { loadFailed() }, [])
async function handleRetry(id: string) {
setRetrying(id)
setMessage('')
const res = await fetch(`/api/sms/${id}/retry`, { method: 'POST' })
const data = await res.json()
setMessage(data.message || (res.ok ? 'Queued for retry' : 'Retry failed'))
setRetrying(null)
if (res.ok) {
setTimeout(() => loadFailed(), 2000)
}
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold text-gray-900">Failed SMS</h1>
<p className="text-gray-500 mt-1">SMS messages that failed after 3 attempts</p>
</div>
<Button variant="outline" onClick={loadFailed} disabled={loading}>
<RefreshCw className={`h-4 w-4 mr-2 ${loading ? 'animate-spin' : ''}`} />
Refresh
</Button>
</div>
{message && (
<div className="bg-blue-50 border border-blue-200 text-blue-700 px-4 py-3 rounded-md text-sm">{message}</div>
)}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-red-500" />
Failed Messages ({failed.length})
</CardTitle>
</CardHeader>
<CardContent className="p-0">
{loading ? (
<p className="text-center text-gray-500 py-8">Loading...</p>
) : failed.length === 0 ? (
<p className="text-center text-green-600 py-8">🎉 No failed messages!</p>
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead className="bg-gray-50 border-b">
<tr>
<th className="text-left px-4 py-3 font-medium text-gray-600">Student</th>
<th className="text-left px-4 py-3 font-medium text-gray-600">Client</th>
<th className="text-left px-4 py-3 font-medium text-gray-600">Phone</th>
<th className="text-left px-4 py-3 font-medium text-gray-600">Event</th>
<th className="text-left px-4 py-3 font-medium text-gray-600">Error</th>
<th className="text-left px-4 py-3 font-medium text-gray-600">Failed At</th>
<th className="text-left px-4 py-3 font-medium text-gray-600">Action</th>
</tr>
</thead>
<tbody className="divide-y">
{failed.map(item => (
<tr key={item.id} className="hover:bg-gray-50">
<td className="px-4 py-3">
<div className="font-medium">{item.studentName}</div>
<div className="text-xs text-gray-500">{item.studentId}</div>
</td>
<td className="px-4 py-3 text-gray-600">{item.client.name}</td>
<td className="px-4 py-3 text-gray-600">{item.parentPhone}</td>
<td className="px-4 py-3">
<span className={`px-2 py-1 rounded-full text-xs font-medium ${
item.event === 'time_in'
? 'bg-green-100 text-green-700'
: 'bg-orange-100 text-orange-700'
}`}>
{item.event === 'time_in' ? '✅ In' : '🔴 Out'}
</span>
</td>
<td className="px-4 py-3">
<span className="text-red-600 text-xs bg-red-50 px-2 py-1 rounded max-w-xs block truncate" title={item.lastError}>
{item.lastError || 'Unknown error'}
</span>
</td>
<td className="px-4 py-3 text-gray-500 text-xs">
{new Date(item.updatedAt).toLocaleString('en-PH', { timeZone: 'Asia/Manila' })}
</td>
<td className="px-4 py-3">
<Button
size="sm"
variant="outline"
onClick={() => handleRetry(item.id)}
disabled={retrying === item.id}
>
<RefreshCw className={`h-3 w-3 mr-1 ${retrying === item.id ? 'animate-spin' : ''}`} />
Retry
</Button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
</div>
)
}

101
app/dashboard/sms/page.tsx Normal file
View File

@@ -0,0 +1,101 @@
import { prisma } from '@/lib/prisma'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
const statusColors: Record<string, string> = {
PENDING: 'bg-yellow-100 text-yellow-700',
PROCESSING: 'bg-blue-100 text-blue-700',
SENT: 'bg-green-100 text-green-700',
FAILED: 'bg-red-100 text-red-700',
RETRYING: 'bg-orange-100 text-orange-700',
}
export default async function SmsQueuePage() {
const queue = await prisma.smsQueue.findMany({
orderBy: { createdAt: 'desc' },
take: 100,
include: { client: { select: { name: true } } },
})
const counts = {
PENDING: queue.filter(q => q.status === 'PENDING').length,
PROCESSING: queue.filter(q => q.status === 'PROCESSING').length,
SENT: queue.filter(q => q.status === 'SENT').length,
FAILED: queue.filter(q => q.status === 'FAILED').length,
RETRYING: queue.filter(q => q.status === 'RETRYING').length,
}
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold text-gray-900">SMS Queue</h1>
<p className="text-gray-500 mt-1">Monitor SMS delivery status</p>
</div>
<div className="flex gap-3 flex-wrap">
{Object.entries(counts).map(([status, count]) => (
<div key={status} className={`px-4 py-2 rounded-full text-sm font-medium ${statusColors[status]}`}>
{status}: {count}
</div>
))}
</div>
<Card>
<CardHeader>
<CardTitle>Recent Queue (last 100)</CardTitle>
</CardHeader>
<CardContent className="p-0">
{queue.length === 0 ? (
<p className="text-center text-gray-500 py-8">No SMS in queue</p>
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead className="bg-gray-50 border-b">
<tr>
<th className="text-left px-4 py-3 font-medium text-gray-600">Student</th>
<th className="text-left px-4 py-3 font-medium text-gray-600">Client</th>
<th className="text-left px-4 py-3 font-medium text-gray-600">Phone</th>
<th className="text-left px-4 py-3 font-medium text-gray-600">Event</th>
<th className="text-left px-4 py-3 font-medium text-gray-600">Status</th>
<th className="text-left px-4 py-3 font-medium text-gray-600">Attempts</th>
<th className="text-left px-4 py-3 font-medium text-gray-600">Created</th>
</tr>
</thead>
<tbody className="divide-y">
{queue.map(item => (
<tr key={item.id} className="hover:bg-gray-50">
<td className="px-4 py-3">
<div className="font-medium">{item.studentName}</div>
<div className="text-xs text-gray-500">{item.studentId}</div>
</td>
<td className="px-4 py-3 text-gray-600">{item.client.name}</td>
<td className="px-4 py-3 text-gray-600">{item.parentPhone}</td>
<td className="px-4 py-3">
<span className={`px-2 py-1 rounded-full text-xs font-medium ${
item.event === 'time_in'
? 'bg-green-100 text-green-700'
: 'bg-orange-100 text-orange-700'
}`}>
{item.event === 'time_in' ? '✅ In' : '🔴 Out'}
</span>
</td>
<td className="px-4 py-3">
<span className={`px-2 py-1 rounded-full text-xs font-medium ${statusColors[item.status]}`}>
{item.status}
</span>
</td>
<td className="px-4 py-3 text-center">{item.attempts}/3</td>
<td className="px-4 py-3 text-gray-500 text-xs">
{new Date(item.createdAt).toLocaleString('en-PH', { timeZone: 'Asia/Manila' })}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
</div>
)
}