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