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,5 @@
import NextAuth from 'next-auth'
import { authOptions } from '@/lib/auth'
const handler = NextAuth(authOptions)
export { handler as GET, handler as POST }

View File

@@ -0,0 +1,51 @@
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { getBalance } from '@/lib/semaphore'
export async function GET(req: NextRequest, { params }: { params: { id: string } }) {
const session = await getServerSession(authOptions)
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const client = await prisma.client.findUnique({
where: { id: params.id },
include: { _count: { select: { smsQueue: true, smsLogs: true } } },
})
if (!client) return NextResponse.json({ error: 'Not found' }, { status: 404 })
let balance: number | null = null
if (client.semaphoreKey) {
balance = await getBalance(client.semaphoreKey)
}
return NextResponse.json({ ...client, balance })
}
export async function PATCH(req: NextRequest, { params }: { params: { id: string } }) {
const session = await getServerSession(authOptions)
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const body = await req.json()
const { name, semaphoreKey, senderName, isActive } = body
const client = await prisma.client.update({
where: { id: params.id },
data: {
...(name !== undefined && { name }),
...(semaphoreKey !== undefined && { semaphoreKey }),
...(senderName !== undefined && { senderName }),
...(isActive !== undefined && { isActive }),
},
})
return NextResponse.json(client)
}
export async function DELETE(req: NextRequest, { params }: { params: { id: string } }) {
const session = await getServerSession(authOptions)
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
await prisma.client.delete({ where: { id: params.id } })
return NextResponse.json({ success: true })
}

37
app/api/clients/route.ts Normal file
View File

@@ -0,0 +1,37 @@
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { generateApiKey, slugify } from '@/lib/utils'
export async function GET() {
const session = await getServerSession(authOptions)
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const clients = await prisma.client.findMany({
orderBy: { createdAt: 'desc' },
include: {
_count: { select: { smsQueue: true, smsLogs: true } },
},
})
return NextResponse.json(clients)
}
export async function POST(req: NextRequest) {
const session = await getServerSession(authOptions)
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const body = await req.json()
const { name, semaphoreKey, senderName } = body
if (!name) return NextResponse.json({ error: 'Name is required' }, { status: 400 })
const slug = slugify(name)
const apiKey = generateApiKey()
const client = await prisma.client.create({
data: { name, slug, apiKey, semaphoreKey, senderName: senderName || 'NFC-HUB' },
})
return NextResponse.json(client, { status: 201 })
}

View File

@@ -0,0 +1,17 @@
import { NextRequest, NextResponse } from 'next/server'
import { processQueue } from '@/lib/queue-processor'
export async function POST(req: NextRequest) {
const internalKey = req.headers.get('x-internal-key')
if (internalKey !== (process.env.INTERNAL_API_KEY || '')) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
try {
const result = await processQueue()
return NextResponse.json({ success: true, ...result })
} catch (err: any) {
console.error('[Queue Process]', err)
return NextResponse.json({ error: 'Processing failed' }, { status: 500 })
}
}

61
app/api/reports/route.ts Normal file
View File

@@ -0,0 +1,61 @@
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
export async function GET(req: NextRequest) {
const session = await getServerSession(authOptions)
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { searchParams } = new URL(req.url)
const clientId = searchParams.get('clientId')
const from = searchParams.get('from')
const to = searchParams.get('to')
const format = searchParams.get('format')
const where: any = {}
if (clientId) where.clientId = clientId
if (from || to) {
where.sentAt = {}
if (from) where.sentAt.gte = new Date(from)
if (to) where.sentAt.lte = new Date(to + 'T23:59:59Z')
}
const logs = await prisma.smsLog.findMany({
where,
include: { client: { select: { name: true } }, queue: true },
orderBy: { sentAt: 'desc' },
take: format === 'csv' ? 10000 : 500,
})
if (format === 'csv') {
const headers = ['Date', 'Client', 'Student Name', 'Student ID', 'Phone', 'Event', 'Status', 'Error']
const rows = logs.map(l => [
new Date(l.sentAt).toISOString(),
l.client.name,
l.queue.studentName,
l.queue.studentId,
l.phone,
l.queue.event,
l.status,
l.errorReason || '',
])
const csv = [headers, ...rows].map(r => r.map(v => `"${String(v).replace(/"/g, '""')}"`).join(',')).join('\n')
return new NextResponse(csv, {
headers: {
'Content-Type': 'text/csv',
'Content-Disposition': `attachment; filename="sms-report-${Date.now()}.csv"`,
},
})
}
// Stats summary
const stats = {
total: logs.length,
success: logs.filter(l => l.status === 'SUCCESS').length,
failed: logs.filter(l => l.status === 'FAILED').length,
logs,
}
return NextResponse.json(stats)
}

View File

@@ -0,0 +1,25 @@
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
export async function POST(req: NextRequest, { params }: { params: { id: string } }) {
const session = await getServerSession(authOptions)
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const queue = await prisma.smsQueue.findUnique({ where: { id: params.id } })
if (!queue) return NextResponse.json({ error: 'Not found' }, { status: 404 })
await prisma.smsQueue.update({
where: { id: params.id },
data: { status: 'PENDING', attempts: 0, lastError: null, scheduledAt: new Date() },
})
// Trigger processing
fetch(`${process.env.NEXTAUTH_URL}/api/queue/process`, {
method: 'POST',
headers: { 'x-internal-key': process.env.INTERNAL_API_KEY || '' },
}).catch(() => {})
return NextResponse.json({ success: true, message: 'Queued for retry' })
}

View File

@@ -0,0 +1,24 @@
import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
export async function GET(req: NextRequest) {
const session = await getServerSession(authOptions)
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { searchParams } = new URL(req.url)
const clientId = searchParams.get('clientId')
const failed = await prisma.smsQueue.findMany({
where: {
status: 'FAILED',
...(clientId ? { clientId } : {}),
},
include: { client: { select: { name: true } } },
orderBy: { updatedAt: 'desc' },
take: 200,
})
return NextResponse.json(failed)
}

View File

@@ -0,0 +1,58 @@
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
export async function POST(req: NextRequest) {
try {
const apiKey = req.headers.get('x-api-key')
if (!apiKey) {
return NextResponse.json({ error: 'Missing X-API-Key header' }, { status: 401 })
}
const client = await prisma.client.findUnique({ where: { apiKey } })
if (!client || !client.isActive) {
return NextResponse.json({ error: 'Invalid or inactive API key' }, { status: 403 })
}
const body = await req.json()
const { student_name, student_id, parent_phone, event, timestamp, message } = body
if (!student_name || !student_id || !parent_phone || !event || !timestamp) {
return NextResponse.json(
{ error: 'Missing required fields: student_name, student_id, parent_phone, event, timestamp' },
{ status: 400 }
)
}
if (!['time_in', 'time_out'].includes(event)) {
return NextResponse.json({ error: 'event must be "time_in" or "time_out"' }, { status: 400 })
}
const queueEntry = await prisma.smsQueue.create({
data: {
clientId: client.id,
studentName: student_name,
studentId: student_id,
parentPhone: parent_phone,
event,
timestamp: new Date(timestamp),
message: message || null,
status: 'PENDING',
},
})
// Trigger queue processing in background (fire and forget)
fetch(`${process.env.NEXTAUTH_URL}/api/queue/process`, {
method: 'POST',
headers: { 'x-internal-key': process.env.INTERNAL_API_KEY || '' },
}).catch(() => {})
return NextResponse.json({
success: true,
queueId: queueEntry.id,
message: 'SMS queued for delivery',
}, { status: 202 })
} catch (err: any) {
console.error('[SMS Send]', err)
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
}

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>
)
}

BIN
app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

BIN
app/fonts/GeistMonoVF.woff Normal file

Binary file not shown.

BIN
app/fonts/GeistVF.woff Normal file

Binary file not shown.

37
app/globals.css Normal file
View File

@@ -0,0 +1,37 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
--card: 0 0% 100%;
--card-foreground: 222.2 84% 4.9%;
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
--primary: 221.2 83.2% 53.3%;
--primary-foreground: 210 40% 98%;
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 46.9%;
--accent: 210 40% 96.1%;
--accent-foreground: 222.2 47.4% 11.2%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 210 40% 98%;
--border: 214.3 31.8% 91.4%;
--input: 214.3 31.8% 91.4%;
--ring: 221.2 83.2% 53.3%;
--radius: 0.5rem;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}

21
app/layout.tsx Normal file
View File

@@ -0,0 +1,21 @@
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import './globals.css'
import { Providers } from './providers'
const inter = Inter({ subsets: ['latin'] })
export const metadata: Metadata = {
title: 'NFC Attendance Hub',
description: 'Multi-tenant SMS gateway for NFC student attendance systems',
}
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body className={inter.className}>
<Providers>{children}</Providers>
</body>
</html>
)
}

81
app/login/page.tsx Normal file
View File

@@ -0,0 +1,81 @@
'use client'
import { useState } from 'react'
import { signIn } from 'next-auth/react'
import { useRouter } from 'next/navigation'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
export default function LoginPage() {
const router = useRouter()
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
setLoading(true)
setError('')
const result = await signIn('credentials', {
email,
password,
redirect: false,
})
if (result?.error) {
setError('Invalid email or password')
setLoading(false)
} else {
router.push('/dashboard')
}
}
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<Card className="w-full max-w-md">
<CardHeader className="text-center">
<div className="mx-auto mb-4 text-4xl">📡</div>
<CardTitle className="text-2xl">NFC Attendance Hub</CardTitle>
<CardDescription>Sign in to your admin account</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="email">Email</Label>
<Input
id="email"
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
placeholder="admin@example.com"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="password">Password</Label>
<Input
id="password"
type="password"
value={password}
onChange={e => setPassword(e.target.value)}
placeholder="••••••••"
required
/>
</div>
<Button type="submit" className="w-full" disabled={loading}>
{loading ? 'Signing in...' : 'Sign In'}
</Button>
</form>
</CardContent>
</Card>
</div>
)
}

9
app/page.tsx Normal file
View File

@@ -0,0 +1,9 @@
import { redirect } from 'next/navigation'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
export default async function Home() {
const session = await getServerSession(authOptions)
if (session) redirect('/dashboard')
redirect('/login')
}

6
app/providers.tsx Normal file
View File

@@ -0,0 +1,6 @@
'use client'
import { SessionProvider } from 'next-auth/react'
export function Providers({ children }: { children: React.ReactNode }) {
return <SessionProvider>{children}</SessionProvider>
}