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

13
.env.example Normal file
View File

@@ -0,0 +1,13 @@
# Database
DATABASE_URL="postgresql://nfchub:strongpassword@postgres:5432/nfchub"
# NextAuth
NEXTAUTH_URL="http://localhost:3000"
NEXTAUTH_SECRET="change-me-with-openssl-rand-base64-32"
# Internal API security
INTERNAL_API_KEY="change-me-internal-key"
# Seed defaults (optional)
SEED_EMAIL="admin@nfchub.local"
SEED_PASSWORD="admin123"

37
.gitignore vendored Normal file
View File

@@ -0,0 +1,37 @@
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
# prisma
prisma/migrations/migration_lock.toml

53
Dockerfile Normal file
View File

@@ -0,0 +1,53 @@
FROM node:20-alpine AS base
# Install dependencies only when needed
FROM base AS deps
RUN apk add --no-cache libc6-compat openssl
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm ci
# Rebuild the source code only when needed
FROM base AS builder
RUN apk add --no-cache openssl
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NEXT_TELEMETRY_DISABLED 1
ENV DATABASE_URL="postgresql://placeholder:placeholder@placeholder:5432/placeholder"
RUN npx prisma generate
RUN npm run build
# Production image
FROM base AS runner
RUN apk add --no-cache openssl
WORKDIR /app
ENV NODE_ENV production
ENV NEXT_TELEMETRY_DISABLED 1
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
COPY --from=builder /app/prisma ./prisma
COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma
COPY --from=builder /app/node_modules/@prisma ./node_modules/@prisma
# Entrypoint script
COPY --chown=nextjs:nodejs docker-entrypoint.sh ./
RUN chmod +x docker-entrypoint.sh
USER nextjs
EXPOSE 3000
ENV PORT 3000
ENV HOSTNAME "0.0.0.0"
ENTRYPOINT ["./docker-entrypoint.sh"]
CMD ["node", "server.js"]

View File

@@ -1,3 +1,92 @@
# nfc-attendance-hub
# NFC Attendance Hub
NFC Student Attendance SMS Notification Hub - Admin Control Center
A multi-tenant admin web app that acts as middleware between on-premise NFC student attendance apps and the [Semaphore](https://semaphore.co) SMS API.
## Features
- **Multi-tenant Client Management** — Register schools/orgs, each gets a unique API key
- **Semaphore SMS Integration** — Per-client Semaphore API key + sender name, credit balance display
- **DB-based SMS Queue** — Retry up to 3 attempts with exponential backoff, tracks failure reasons
- **Failed SMS Dashboard** — View failed messages with error details, manual retry button
- **Reports** — SMS stats per client, date filter, CSV export
- **Admin Auth** — Email/password login with NextAuth
## Tech Stack
- Next.js 14 (App Router) + TypeScript
- Tailwind CSS + shadcn/ui-compatible components
- Prisma ORM (v5) + PostgreSQL
- NextAuth.js (credentials provider)
## Quick Start (Docker)
```bash
cp .env.example .env
# Edit .env with your values
docker compose up -d
```
App available at: http://localhost:3000
Default admin: `admin@nfchub.local` / `admin123`
## Development
```bash
npm install
cp .env.example .env
# Edit .env to point to a local PostgreSQL
npx prisma generate
npx prisma db push
npm run db:seed
npm run dev
```
## SMS API Reference
On-premise NFC apps submit attendance events to:
```
POST /api/v1/sms/send
Header: X-API-Key: <client_api_key>
Content-Type: application/json
{
"student_name": "Juan Dela Cruz",
"student_id": "2024-001",
"parent_phone": "09171234567",
"event": "time_in", // "time_in" or "time_out"
"timestamp": "2024-01-15T08:30:00+08:00",
"message": "Optional custom message" // optional
}
```
### Response
```json
{ "success": true, "queueId": "...", "message": "SMS queued for delivery" }
```
### SMS Queue Behavior
1. Submission is accepted immediately (202 Accepted)
2. Processing is triggered asynchronously
3. Failed sends are retried up to 3 times with exponential backoff (2min, 4min, 8min)
4. After 3 failures, SMS is marked FAILED and visible in the Failed SMS dashboard
## Environment Variables
| Variable | Description | Required |
|----------|-------------|----------|
| `DATABASE_URL` | PostgreSQL connection string | Yes |
| `NEXTAUTH_URL` | Public app URL | Yes |
| `NEXTAUTH_SECRET` | Random secret for JWT | Yes |
| `INTERNAL_API_KEY` | Internal queue trigger key | Yes |
## Docker Services
| Service | Port | Description |
|---------|------|-------------|
| `app` | 3000 | Next.js application |
| `postgres` | 5433 (host) | PostgreSQL 16 |

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

69
components/sidebar.tsx Normal file
View File

@@ -0,0 +1,69 @@
'use client'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { signOut } from 'next-auth/react'
import { cn } from '@/lib/utils'
import {
LayoutDashboard,
Building2,
MessageSquare,
AlertTriangle,
BarChart3,
LogOut,
} from 'lucide-react'
const navItems = [
{ href: '/dashboard', label: 'Dashboard', icon: LayoutDashboard },
{ href: '/dashboard/clients', label: 'Clients', icon: Building2 },
{ href: '/dashboard/sms', label: 'SMS Queue', icon: MessageSquare },
{ href: '/dashboard/sms/failed', label: 'Failed SMS', icon: AlertTriangle },
{ href: '/dashboard/reports', label: 'Reports', icon: BarChart3 },
]
export function Sidebar() {
const pathname = usePathname()
return (
<aside className="w-64 bg-gray-900 text-white flex flex-col min-h-screen">
<div className="p-6 border-b border-gray-700">
<div className="flex items-center gap-3">
<span className="text-2xl">📡</span>
<div>
<h1 className="font-bold text-sm">NFC Attendance Hub</h1>
<p className="text-xs text-gray-400">Admin Portal</p>
</div>
</div>
</div>
<nav className="flex-1 p-4 space-y-1">
{navItems.map(item => {
const Icon = item.icon
const active = pathname === item.href || (item.href !== '/dashboard' && pathname.startsWith(item.href))
return (
<Link
key={item.href}
href={item.href}
className={cn(
'flex items-center gap-3 px-3 py-2 rounded-md text-sm transition-colors',
active
? 'bg-blue-600 text-white'
: 'text-gray-300 hover:bg-gray-800 hover:text-white'
)}
>
<Icon className="h-4 w-4" />
{item.label}
</Link>
)
})}
</nav>
<div className="p-4 border-t border-gray-700">
<button
onClick={() => signOut({ callbackUrl: '/login' })}
className="flex items-center gap-3 px-3 py-2 rounded-md text-sm text-gray-300 hover:bg-gray-800 hover:text-white w-full transition-colors"
>
<LogOut className="h-4 w-4" />
Sign Out
</button>
</div>
</aside>
)
}

30
components/ui/badge.tsx Normal file
View File

@@ -0,0 +1,30 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default: "border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive: "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
success: "border-transparent bg-green-100 text-green-800",
warning: "border-transparent bg-yellow-100 text-yellow-800",
},
},
defaultVariants: { variant: "default" },
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return <div className={cn(badgeVariants({ variant }), className)} {...props} />
}
export { Badge, badgeVariants }

45
components/ui/button.tsx Normal file
View File

@@ -0,0 +1,45 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline: "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: { variant: "default", size: "default" },
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} />
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }

46
components/ui/card.tsx Normal file
View File

@@ -0,0 +1,46 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("rounded-lg border bg-card text-card-foreground shadow-sm", className)} {...props} />
)
)
Card.displayName = "Card"
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />
)
)
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
({ className, ...props }, ref) => (
<h3 ref={ref} className={cn("text-2xl font-semibold leading-none tracking-tight", className)} {...props} />
)
)
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
({ className, ...props }, ref) => (
<p ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
)
)
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
)
)
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex items-center p-6 pt-0", className)} {...props} />
)
)
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }

21
components/ui/input.tsx Normal file
View File

@@ -0,0 +1,21 @@
import * as React from "react"
import { cn } from "@/lib/utils"
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
)
)
Input.displayName = "Input"
export { Input }

19
components/ui/label.tsx Normal file
View File

@@ -0,0 +1,19 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> & VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root ref={ref} className={cn(labelVariants(), className)} {...props} />
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }

85
components/ui/select.tsx Normal file
View File

@@ -0,0 +1,85 @@
"use client"
import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select"
import { Check, ChevronDown, ChevronUp } from "lucide-react"
import { cn } from "@/lib/utils"
const Select = SelectPrimitive.Root
const SelectGroup = SelectPrimitive.Group
const SelectValue = SelectPrimitive.Value
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
))
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md",
className
)}
position={position}
{...props}
>
<SelectPrimitive.Viewport className="p-1">{children}</SelectPrimitive.Viewport>
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
))
SelectContent.displayName = SelectPrimitive.Content.displayName
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
))
SelectItem.displayName = SelectPrimitive.Item.displayName
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
{...props}
/>
))
SelectLabel.displayName = SelectPrimitive.Label.displayName
export { Select, SelectGroup, SelectValue, SelectTrigger, SelectContent, SelectItem, SelectLabel }

View File

@@ -0,0 +1,24 @@
"use client"
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import { cn } from "@/lib/utils"
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(({ className, orientation = "horizontal", decorative = true, ...props }, ref) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn(
"shrink-0 bg-border",
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
className
)}
{...props}
/>
))
Separator.displayName = SeparatorPrimitive.Root.displayName
export { Separator }

48
components/ui/table.tsx Normal file
View File

@@ -0,0 +1,48 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table ref={ref} className={cn("w-full caption-bottom text-sm", className)} {...props} />
</div>
)
)
Table.displayName = "Table"
const TableHeader = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => (
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
)
)
TableHeader.displayName = "TableHeader"
const TableBody = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => (
<tbody ref={ref} className={cn("[&_tr:last-child]:border-0", className)} {...props} />
)
)
TableBody.displayName = "TableBody"
const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(
({ className, ...props }, ref) => (
<tr ref={ref} className={cn("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted", className)} {...props} />
)
)
TableRow.displayName = "TableRow"
const TableHead = React.forwardRef<HTMLTableCellElement, React.ThHTMLAttributes<HTMLTableCellElement>>(
({ className, ...props }, ref) => (
<th ref={ref} className={cn("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0", className)} {...props} />
)
)
TableHead.displayName = "TableHead"
const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<HTMLTableCellElement>>(
({ className, ...props }, ref) => (
<td ref={ref} className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)} {...props} />
)
)
TableCell.displayName = "TableCell"
export { Table, TableHeader, TableBody, TableRow, TableHead, TableCell }

View File

@@ -0,0 +1,20 @@
import * as React from "react"
import { cn } from "@/lib/utils"
export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, ...props }, ref) => (
<textarea
className={cn(
"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
)
)
Textarea.displayName = "Textarea"
export { Textarea }

40
docker-compose.yml Normal file
View File

@@ -0,0 +1,40 @@
version: '3.9'
services:
postgres:
image: postgres:16-alpine
container_name: nfchub-postgres
restart: unless-stopped
environment:
POSTGRES_DB: nfchub
POSTGRES_USER: nfchub
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-nfchubpass}
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5433:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U nfchub"]
interval: 10s
timeout: 5s
retries: 5
app:
build:
context: .
dockerfile: Dockerfile
container_name: nfchub-app
restart: unless-stopped
depends_on:
postgres:
condition: service_healthy
environment:
DATABASE_URL: postgresql://nfchub:${POSTGRES_PASSWORD:-nfchubpass}@postgres:5432/nfchub
NEXTAUTH_URL: ${NEXTAUTH_URL:-http://localhost:3000}
NEXTAUTH_SECRET: ${NEXTAUTH_SECRET:-change-me-in-production}
INTERNAL_API_KEY: ${INTERNAL_API_KEY:-change-me-internal}
ports:
- "3000:3000"
volumes:
postgres_data:

25
docker-entrypoint.sh Executable file
View File

@@ -0,0 +1,25 @@
#!/bin/sh
set -e
echo "🚀 Running database migrations..."
npx prisma migrate deploy || npx prisma db push --accept-data-loss
echo "🌱 Seeding initial data..."
node -e "
const { PrismaClient } = require('@prisma/client');
const bcrypt = require('bcryptjs');
const prisma = new PrismaClient();
async function seed() {
const email = process.env.SEED_EMAIL || 'admin@nfchub.local';
const pass = process.env.SEED_PASSWORD || 'admin123';
const existing = await prisma.user.findUnique({ where: { email } });
if (!existing) {
const hashed = await bcrypt.hash(pass, 12);
await prisma.user.create({ data: { email, password: hashed, name: 'Admin', role: 'ADMIN' } });
console.log('Admin user created:', email);
}
}
seed().catch(console.error).finally(() => prisma.\$disconnect());
" || true
exec "$@"

54
lib/auth.ts Normal file
View File

@@ -0,0 +1,54 @@
import { NextAuthOptions } from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials'
import { prisma } from '@/lib/prisma'
import bcrypt from 'bcryptjs'
export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
name: 'credentials',
credentials: {
email: { label: 'Email', type: 'email' },
password: { label: 'Password', type: 'password' },
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) return null
const user = await prisma.user.findUnique({
where: { email: credentials.email },
})
if (!user) return null
const passwordMatch = await bcrypt.compare(credentials.password, user.password)
if (!passwordMatch) return null
return {
id: user.id,
email: user.email,
name: user.name,
role: user.role,
}
},
}),
],
session: { strategy: 'jwt' },
pages: { signIn: '/login' },
callbacks: {
async jwt({ token, user }) {
if (user) {
token.id = user.id
token.role = (user as any).role
}
return token
},
async session({ session, token }) {
if (session.user) {
(session.user as any).id = token.id as string
;(session.user as any).role = token.role as string
}
return session
},
},
secret: process.env.NEXTAUTH_SECRET,
}

15
lib/prisma.ts Normal file
View File

@@ -0,0 +1,15 @@
import { PrismaClient } from '@prisma/client'
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined
}
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
})
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma
export default prisma

107
lib/queue-processor.ts Normal file
View File

@@ -0,0 +1,107 @@
import { prisma } from '@/lib/prisma'
import { sendSms } from '@/lib/semaphore'
import { formatPhone } from '@/lib/utils'
const MAX_ATTEMPTS = 3
export async function processQueue(): Promise<{ processed: number; failed: number }> {
let processed = 0
let failed = 0
const jobs = await prisma.smsQueue.findMany({
where: {
status: { in: ['PENDING', 'RETRYING'] },
attempts: { lt: MAX_ATTEMPTS },
scheduledAt: { lte: new Date() },
},
include: { client: true },
orderBy: { scheduledAt: 'asc' },
take: 50,
})
for (const job of jobs) {
await prisma.smsQueue.update({
where: { id: job.id },
data: { status: 'PROCESSING' },
})
const client = job.client
if (!client.semaphoreKey || !client.isActive) {
await prisma.smsQueue.update({
where: { id: job.id },
data: {
status: 'FAILED',
lastError: 'Client has no Semaphore API key configured',
processedAt: new Date(),
},
})
await createLog(job.id, client.id, job.parentPhone, job.message || '', 'FAILED', null, 'No Semaphore key')
failed++
continue
}
const message =
job.message ||
`${job.event === 'time_in' ? '✅ Time In' : '🔴 Time Out'}: ${job.studentName} (ID: ${job.studentId}) at ${new Date(job.timestamp).toLocaleString('en-PH', { timeZone: 'Asia/Manila' })}`
const phone = formatPhone(job.parentPhone)
const result = await sendSms(client.semaphoreKey, client.senderName || 'NFC-HUB', phone, message)
const newAttempts = job.attempts + 1
if (result.success) {
await prisma.smsQueue.update({
where: { id: job.id },
data: { status: 'SENT', attempts: newAttempts, processedAt: new Date(), lastError: null },
})
await createLog(job.id, client.id, phone, message, 'SUCCESS', result.messageId, null)
processed++
} else {
const nextStatus = newAttempts >= MAX_ATTEMPTS ? 'FAILED' : 'RETRYING'
const retryDelay = Math.pow(2, newAttempts) * 60 * 1000
const scheduledAt = nextStatus === 'RETRYING' ? new Date(Date.now() + retryDelay) : new Date()
await prisma.smsQueue.update({
where: { id: job.id },
data: {
status: nextStatus,
attempts: newAttempts,
lastError: result.error,
scheduledAt,
processedAt: nextStatus === 'FAILED' ? new Date() : undefined,
},
})
if (nextStatus === 'FAILED') {
await createLog(job.id, client.id, phone, message, 'FAILED', null, result.error || 'Max retries reached')
failed++
}
}
}
return { processed, failed }
}
async function createLog(
queueId: string,
clientId: string,
phone: string,
message: string,
status: 'SUCCESS' | 'FAILED',
semaphoreId: string | null | undefined,
errorReason: string | null | undefined
) {
const existing = await prisma.smsLog.findUnique({ where: { queueId } })
if (existing) return
await prisma.smsLog.create({
data: {
queueId,
clientId,
phone,
message,
status,
semaphoreId: semaphoreId ?? null,
errorReason: errorReason ?? null,
},
})
}

58
lib/semaphore.ts Normal file
View File

@@ -0,0 +1,58 @@
import axios from 'axios'
const SEMAPHORE_API_URL = 'https://api.semaphore.co/api/v4'
export interface SemaphoreResponse {
success: boolean
messageId?: string
error?: string
}
export async function sendSms(
apiKey: string,
senderName: string,
phone: string,
message: string
): Promise<SemaphoreResponse> {
try {
const response = await axios.post(
`${SEMAPHORE_API_URL}/messages`,
{
apikey: apiKey,
number: phone,
message,
sendername: senderName,
},
{ timeout: 15000 }
)
const data = response.data
if (Array.isArray(data) && data.length > 0) {
const msg = data[0]
if (msg.status === 'Queued' || msg.status === 'Sent') {
return { success: true, messageId: String(msg.message_id) }
}
return { success: false, error: msg.status || 'Unknown status' }
}
return { success: false, error: 'Empty response from Semaphore' }
} catch (err: any) {
const errorMsg =
err.response?.data?.message ||
err.response?.data ||
err.message ||
'SMS send failed'
return { success: false, error: String(errorMsg) }
}
}
export async function getBalance(apiKey: string): Promise<number | null> {
try {
const response = await axios.get(`${SEMAPHORE_API_URL}/account`, {
params: { apikey: apiKey },
timeout: 10000,
})
return response.data?.credit_balance ?? null
} catch {
return null
}
}

32
lib/utils.ts Normal file
View File

@@ -0,0 +1,32 @@
import { type ClassValue, clsx } from 'clsx'
import { twMerge } from 'tailwind-merge'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export function generateApiKey(): string {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
let result = 'nfc_'
for (let i = 0; i < 32; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length))
}
return result
}
export function slugify(text: string): string {
return text
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/(^-|-$)/g, '')
}
export function formatPhone(phone: string): string {
const cleaned = phone.replace(/\D/g, '')
if (cleaned.startsWith('0') && cleaned.length === 11) {
return '63' + cleaned.slice(1)
}
if (cleaned.startsWith('63') && cleaned.length === 12) return cleaned
if (cleaned.length === 10) return '63' + cleaned
return cleaned
}

9
next.config.mjs Normal file
View File

@@ -0,0 +1,9 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'standalone',
experimental: {
serverComponentsExternalPackages: ['@prisma/client', 'bcryptjs'],
},
};
export default nextConfig;

3480
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

54
package.json Normal file
View File

@@ -0,0 +1,54 @@
{
"name": "nfc-build",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"db:generate": "prisma generate",
"db:push": "prisma db push",
"db:migrate": "prisma migrate deploy",
"db:seed": "ts-node --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts",
"db:studio": "prisma studio"
},
"dependencies": {
"@auth/prisma-adapter": "^2.11.1",
"@prisma/client": "^5.22.0",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-select": "^2.2.6",
"@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-tabs": "^1.1.13",
"@radix-ui/react-toast": "^1.2.15",
"axios": "^1.13.6",
"bcryptjs": "^3.0.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.577.0",
"next": "14.2.35",
"next-auth": "^4.24.13",
"prisma": "^5.22.0",
"react": "^18",
"react-dom": "^18",
"tailwind-merge": "^3.5.0",
"uuid": "^13.0.0"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.6",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"@types/uuid": "^10.0.0",
"postcss": "^8",
"tailwindcss": "^3.4.1",
"ts-node": "^10.9.2",
"typescript": "^5"
},
"prisma": {
"seed": "ts-node --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts"
}
}

8
postcss.config.mjs Normal file
View File

@@ -0,0 +1,8 @@
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
},
};
export default config;

90
prisma/schema.prisma Normal file
View File

@@ -0,0 +1,90 @@
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id String @id @default(cuid())
email String @unique
password String
name String?
role Role @default(ADMIN)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Client {
id String @id @default(cuid())
name String
slug String @unique
apiKey String @unique @default(cuid())
isActive Boolean @default(true)
semaphoreKey String?
senderName String? @default("NFC-HUB")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
smsLogs SmsLog[]
smsQueue SmsQueue[]
}
model SmsQueue {
id String @id @default(cuid())
clientId String
client Client @relation(fields: [clientId], references: [id])
studentName String
studentId String
parentPhone String
event EventType
timestamp DateTime
message String?
status SmsStatus @default(PENDING)
attempts Int @default(0)
lastError String?
scheduledAt DateTime @default(now())
processedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
smsLog SmsLog?
}
model SmsLog {
id String @id @default(cuid())
clientId String
client Client @relation(fields: [clientId], references: [id])
queueId String @unique
queue SmsQueue @relation(fields: [queueId], references: [id])
phone String
message String
status LogStatus
semaphoreId String?
errorReason String?
sentAt DateTime @default(now())
createdAt DateTime @default(now())
}
enum Role {
ADMIN
VIEWER
}
enum EventType {
time_in
time_out
}
enum SmsStatus {
PENDING
PROCESSING
SENT
FAILED
RETRYING
}
enum LogStatus {
SUCCESS
FAILED
}

24
prisma/seed.ts Normal file
View File

@@ -0,0 +1,24 @@
import { PrismaClient } from '@prisma/client'
import bcrypt from 'bcryptjs'
const prisma = new PrismaClient()
async function main() {
const email = process.env.SEED_EMAIL || 'admin@nfchub.local'
const password = process.env.SEED_PASSWORD || 'admin123'
const existing = await prisma.user.findUnique({ where: { email } })
if (!existing) {
const hashed = await bcrypt.hash(password, 12)
await prisma.user.create({
data: { email, password: hashed, name: 'Admin', role: 'ADMIN' },
})
console.log(`✅ Created admin user: ${email}`)
} else {
console.log(` Admin user already exists: ${email}`)
}
}
main()
.catch(e => { console.error(e); process.exit(1) })
.finally(() => prisma.$disconnect())

56
tailwind.config.ts Normal file
View File

@@ -0,0 +1,56 @@
import type { Config } from "tailwindcss";
const config: Config = {
darkMode: ["class"],
content: [
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
colors: {
border: "hsl(var(--border))",
input: "hsl(var(--input))",
ring: "hsl(var(--ring))",
background: "hsl(var(--background))",
foreground: "hsl(var(--foreground))",
primary: {
DEFAULT: "hsl(var(--primary))",
foreground: "hsl(var(--primary-foreground))",
},
secondary: {
DEFAULT: "hsl(var(--secondary))",
foreground: "hsl(var(--secondary-foreground))",
},
destructive: {
DEFAULT: "hsl(var(--destructive))",
foreground: "hsl(var(--destructive-foreground))",
},
muted: {
DEFAULT: "hsl(var(--muted))",
foreground: "hsl(var(--muted-foreground))",
},
accent: {
DEFAULT: "hsl(var(--accent))",
foreground: "hsl(var(--accent-foreground))",
},
popover: {
DEFAULT: "hsl(var(--popover))",
foreground: "hsl(var(--popover-foreground))",
},
card: {
DEFAULT: "hsl(var(--card))",
foreground: "hsl(var(--card-foreground))",
},
},
borderRadius: {
lg: "var(--radius)",
md: "calc(var(--radius) - 2px)",
sm: "calc(var(--radius) - 4px)",
},
},
},
plugins: [],
};
export default config;

26
tsconfig.json Normal file
View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}