import { redirect } from "next/navigation"; import { auth } from "@/auth/config"; import { hasPermission } from "@/auth/permissions"; import type { SystemRole } from "@/auth/roles"; import { listUsersForAdmin } from "@/db/users"; import { listSkillsMatrix } from "@/db/assessments"; import { getPositionSkills, listPositions, listSkills } from "@/db/positions"; import { listServices } from "@/db/services"; import { listNotifications } from "@/db/outbox"; import { listRules } from "@/db/reminders"; import { getEmailSettings } from "@/db/settings"; import { ASSESSMENT_KINDS, USER_STATUSES } from "@/db/schema"; import { SYSTEM_ROLES } from "@/auth/roles"; import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card"; import { PeoplePanel, type ManagedUser, } from "@/components/app/admin/people-panel"; import { ServicesPanel } from "@/components/app/admin/services-panel"; import { RemindersPanel } from "@/components/app/admin/reminders-panel"; import { NotificationsPanel, type NotificationRow, } from "@/components/app/admin/notifications-panel"; import { EmailPanel } from "@/components/app/admin/email-panel"; import { BackupPanel } from "@/components/app/admin/backup-panel"; import { SkillsMatrixPanel, type MatrixRow, } from "@/components/app/admin/skills-matrix-panel"; import { PositionsPanel, type PositionSummary, type RequirementDraft, } from "@/components/app/admin/positions-panel"; import { listGrowthQueue } from "@/db/growthGoals"; import { retentionSummary } from "@/db/retention"; import { RetentionPanel, type RetentionSummaryView, } from "@/components/app/admin/retention-panel"; import { MentorQueuePanel, type QueueGoalView, } from "@/components/app/growth/mentor-queue-panel"; export const metadata = { title: "Admin" }; function stamp(date: Date): string { return formatInTimezone(date, CHURCH_TIMEZONE, { timeZone: CHURCH_TIMEZONE, month: "short", day: "numeric", hour: "numeric", minute: "2-digit", }); } /** * Admin hub. Server-rendered data, client action panels: * - People: invite + approve/deny (B1) * - Skill levels: the competency matrix + verify-level form (C3) * - Positions: seats and their requirements editor (B4) * - Services: recurring templates + the idempotent instance generator (D1/D2) * - Reminder rules: offset sends used at publish time (E7) * - Notification log: outbox state, retry, send-test (E6) * * Guarded by `admin.settings`, the admin-only permission; coordinators and * volunteers are sent back to the schedule. */ export default async function AdminPage() { const session = await auth(); const role = (session?.user as { systemRole?: SystemRole } | undefined)?.systemRole; if (!hasPermission(role, "admin.settings")) redirect("/schedule"); const [ users, rules, log, services, matrix, positions, skillRows, emailSettings, growthQueue, retention, ] = await Promise.all([ listUsersForAdmin(), listRules(), listNotifications({ limit: 25 }), listServices({ active: false }), listSkillsMatrix(), listPositions({ active: false }), listSkills({ active: true }), getEmailSettings(), listGrowthQueue(), retentionSummary(), ]); const requirementSets = await Promise.all( positions.map((position) => getPositionSkills(position.id)), ); const requirementsByPosition: Record = {}; positions.forEach((position, index) => { requirementsByPosition[position.id] = requirementSets[index].map((row) => ({ skillId: row.skillId, weight: row.weight, requiredLevel: row.requiredLevel, isCore: row.isCore, })); }); const matrixRows: MatrixRow[] = matrix.map((row) => ({ userId: row.userId, userName: row.userName, email: row.email, skillId: row.skillId, skillName: row.skillName, categoryName: row.categoryName ?? "Uncategorized", selfComfort: row.selfComfort, verifiedLevel: row.verifiedLevel, lastServedOn: row.lastServedOn ?? null, })); const retentionView: RetentionSummaryView = retention; const queueGoals: QueueGoalView[] = growthQueue.map((goal) => ({ id: goal.id, userName: goal.userName, email: goal.email, skillName: goal.skillName, targetLevel: goal.targetLevel, targetDate: goal.targetDate, status: goal.status, mentorUserId: goal.mentorUserId, mentorName: goal.mentorName, shadowCount: goal.shadowCount, verifiedLevel: goal.verifiedLevel, mentorCandidates: goal.mentorCandidates.map((candidate) => ({ userId: candidate.userId, displayName: candidate.displayName, verifiedLevel: candidate.verifiedLevel, })), })); const managedUsers: ManagedUser[] = users.map((user) => ({ id: user.id, email: user.email, username: user.username, firstName: user.firstName, lastName: user.lastName, displayName: user.displayName, systemRole: user.systemRole, status: user.status, phoneE164: user.phoneE164, timezone: user.timezone, emergencyContact: user.emergencyContact, notes: user.notes, deactivatedAt: user.deactivatedAt ? user.deactivatedAt.toISOString() : null, passwordSet: user.passwordSet, })); const positionRows: PositionSummary[] = positions.map((position) => ({ id: position.id, name: position.name, defaultHeadcount: position.defaultHeadcount, callTimeOffsetMinutes: position.callTimeOffsetMinutes, active: position.active, })); const rows: NotificationRow[] = log.map((n) => ({ id: n.id, templateKey: n.templateKey, subject: typeof n.payload.subject === "string" ? n.payload.subject : null, toAddress: n.toAddress, status: n.status, attempts: n.attempts, scheduledFor: stamp(n.scheduledFor), sentAt: n.sentAt ? stamp(n.sentAt) : null, error: n.error, })); return (

Admin

People, competency, positions, and outbound messages for the media team.

People Add people, approve pending sign-ups, and edit every profile and access field. Deactivate to keep a person's history; delete only removes accounts with no scheduling history. ({ id: skill.id, name: skill.name }))} /> Skill levels Who is signed off on what. Verifying records who moved the level and why; the volunteer's own comfort rating is never changed here. Mentor queue Volunteers asking to grow. Assign a mentor who is already mentor-ready for that skill, then log shadows and sign the goal off. Levels themselves are verified in the matrix above. Positions & requirements The seats each service needs and the skills they require. A position saved as publishable needs at least one core skill. ({ id: skill.id, name: skill.name }))} requirementsByPosition={requirementsByPosition} /> Services & schedule Recurring service templates, and instance generation for the weeks volunteers will be scheduled into. ({ id: service.id, name: service.name, startTimeLocal: service.startTimeLocal, durationMinutes: service.durationMinutes, location: service.location ?? null, active: service.active, }))} /> Reminder rules Offsets are relative to each service or event start; negative days are before. Service reminders are queued when a week is published, event reminders by the notification cron. Every offset and time is editable. Email delivery Send through the team's Gmail account with an app password. Nothing is stored in plain text, and the password is never shown again after saving. Retention & storage What the database and the upload volume are holding, and what the next sweep would remove. Sent mail and used tokens past their window are deleted; queued mail never is. Backup & restore Download every database record and uploaded file in one portable ZIP, or restore a backup after a redeploy. Restores are admin-only and require an explicit confirmation. Notifications The outbox log, newest first, with retry for anything that failed.
); }