/** * User administration data layer — the read/write half of the People panel. * * `src/db/admin.ts` keeps the light roster read model; this module owns the * full records an admin edits, plus the two facts the removal rules need * (whether the person has served, and how many other active admins exist). * * Writes are partial: `updateUser` only writes the keys it is given, so a * patch that omits a field (say, the phone) never nulls it out. */ import { and, asc, eq, isNotNull, isNull, ne, or, sql } from "drizzle-orm"; import { db } from "@/db"; import { assignments, userSkills, users } from "@/db/schema"; import type { SystemRole } from "@/auth/roles"; import { normalizeUsername } from "@/auth/password"; import { CHURCH_TIMEZONE } from "@/lib/tz"; import { uuidv7 } from "@/lib/uuid"; import { displayNameFor, normalizeUserEmail } from "@/domain/users"; const userName = sql`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`; export interface ManagedUserRow { id: string; email: string; username: string; firstName: string; lastName: string; displayName: string; systemRole: string; status: string; phoneE164: string | null; timezone: string; emergencyContact: string | null; notes: string | null; deactivatedAt: Date | null; createdAt: Date; /** Never expose the hash itself to an admin list or page. */ passwordSet: boolean; } /** Every user, with the ones that need attention first (pending, then active…). */ export async function listUsersForAdmin(): Promise { const statusRank = sql`CASE ${users.status} WHEN 'pending_approval' THEN 0 WHEN 'invited' THEN 1 WHEN 'active' THEN 2 WHEN 'inactive' THEN 3 ELSE 4 END`; return db .select({ id: users.id, email: users.email, username: users.username, firstName: users.firstName, lastName: users.lastName, displayName: userName, systemRole: users.systemRole, status: users.status, phoneE164: users.phoneE164, timezone: users.timezone, emergencyContact: users.emergencyContact, notes: users.notes, deactivatedAt: users.deactivatedAt, createdAt: users.createdAt, passwordSet: sql`${users.passwordHash} is not null`, }) .from(users) .orderBy(statusRank, asc(users.lastName), asc(users.firstName)); } export async function getUserById(id: string): Promise { const [row] = await db .select({ id: users.id, email: users.email, username: users.username, firstName: users.firstName, lastName: users.lastName, displayName: userName, systemRole: users.systemRole, status: users.status, phoneE164: users.phoneE164, timezone: users.timezone, emergencyContact: users.emergencyContact, notes: users.notes, deactivatedAt: users.deactivatedAt, createdAt: users.createdAt, passwordSet: sql`${users.passwordHash} is not null`, }) .from(users) .where(eq(users.id, id)) .limit(1); return row ?? null; } /** The fields credential checks need. Never send this row to a client. */ export interface UserCredentialRow { id: string; email: string; username: string; displayName: string | null; passwordHash: string | null; systemRole: SystemRole; status: string; deactivatedAt: Date | null; } /** * Resolve a login identifier. Usernames and emails are both accepted, and both * are stored lowercased. The default username is the person's email, so most * people can sign in with either interchangeably. */ export async function getUserByLogin(login: string): Promise { const normalized = normalizeUsername(login); if (!normalized) return null; const [row] = await db .select({ id: users.id, email: users.email, username: users.username, displayName: users.displayName, passwordHash: users.passwordHash, systemRole: users.systemRole, status: users.status, deactivatedAt: users.deactivatedAt, }) .from(users) .where(or(eq(users.username, normalized), eq(users.email, normalized))) .limit(1); return row ?? null; } /** The signed-in user's own credential state for setup and password changes. */ export async function getUserSecurity(id: string): Promise { const [row] = await db .select({ id: users.id, email: users.email, username: users.username, displayName: users.displayName, passwordHash: users.passwordHash, systemRole: users.systemRole, status: users.status, deactivatedAt: users.deactivatedAt, }) .from(users) .where(eq(users.id, id)) .limit(1); return row ?? null; } /** A username cannot collide with another account's username or email. */ export async function credentialTaken( username: string, excludeUserId?: string, ): Promise { const normalized = normalizeUsername(username); if (!normalized) return false; const matches = or( eq(users.username, normalized), eq(users.email, normalized), ); const [row] = await db .select({ id: users.id }) .from(users) .where(excludeUserId ? and(matches, ne(users.id, excludeUserId)) : matches) .limit(1); return Boolean(row); } export async function updateUserCredentials( id: string, patch: { username?: string; passwordHash?: string }, ) { const values: Record = { updatedAt: new Date() }; if (patch.username !== undefined) values.username = normalizeUsername(patch.username); if (patch.passwordHash !== undefined) values.passwordHash = patch.passwordHash; const [row] = await db .update(users) .set(values) .where(eq(users.id, id)) .returning({ id: users.id, username: users.username }); return row ?? null; } /** Has this person ever held a slot? Assignment rows restrict deletion. */ export async function hasAssignmentHistory(userId: string): Promise { const [row] = await db .select({ id: assignments.id }) .from(assignments) .where(eq(assignments.userId, userId)) .limit(1); return Boolean(row); } /** * Whether any admin has real credentials. Once this is true, public * magic-link sign-in is closed: anyone who knew an admin's email could * otherwise mint a full admin session from the login page. New-account and * recovery links remain available to signed-in admins. */ export async function hasPasswordProtectedAdmin(): Promise { const [row] = await db .select({ id: users.id }) .from(users) .where( and( eq(users.systemRole, "admin"), isNotNull(users.passwordHash), ), ) .limit(1); return Boolean(row); } /** Active admins who could still sign in, excluding the person being changed. */ export async function countOtherActiveAdmins(excludeUserId: string): Promise { const [row] = await db .select({ count: sql`count(*)::int` }) .from(users) .where( and( eq(users.systemRole, "admin"), eq(users.status, "active"), isNull(users.deactivatedAt), ne(users.id, excludeUserId), ), ); return row?.count ?? 0; } export interface CreateUserInput { email: string; username?: string; firstName: string; lastName?: string; displayName?: string | null; phoneE164?: string | null; systemRole: SystemRole; status?: "invited" | "pending_approval" | "active" | "inactive" | "denied"; timezone?: string; emergencyContact?: string | null; notes?: string | null; } export async function createUser(input: CreateUserInput) { const status = input.status ?? "active"; const [row] = await db .insert(users) .values({ id: uuidv7(), email: normalizeUserEmail(input.email), username: normalizeUsername(input.username ?? input.email), firstName: input.firstName, lastName: input.lastName ?? "", displayName: displayNameFor({ firstName: input.firstName, lastName: input.lastName, displayName: input.displayName, }), phoneE164: input.phoneE164 ?? null, systemRole: input.systemRole, status, // An account created directly as active is approved by definition; keep // the audit column truthful so approval history is not blank. approvedAt: status === "active" ? new Date() : null, timezone: input.timezone ?? CHURCH_TIMEZONE, emergencyContact: input.emergencyContact ?? null, notes: input.notes ?? null, createdAt: new Date(), }) .returning(); return row!; } export interface UpdateUserInput { email?: string; username?: string; firstName?: string; lastName?: string; displayName?: string | null; phoneE164?: string | null; systemRole?: SystemRole; status?: "invited" | "pending_approval" | "active" | "inactive" | "denied"; timezone?: string; emergencyContact?: string | null; notes?: string | null; deactivatedAt?: Date | null; } /** * Patch the given fields only. `undefined` means "leave it alone", `null` means * "clear it" — the distinction the profile update (B2) had to learn. */ export async function updateUser(id: string, patch: UpdateUserInput) { const values: Record = { updatedAt: new Date() }; if (patch.email !== undefined) values.email = normalizeUserEmail(patch.email); if (patch.username !== undefined) values.username = normalizeUsername(patch.username); if (patch.firstName !== undefined) values.firstName = patch.firstName; if (patch.lastName !== undefined) values.lastName = patch.lastName; if (patch.displayName !== undefined) values.displayName = patch.displayName; if (patch.phoneE164 !== undefined) values.phoneE164 = patch.phoneE164; if (patch.systemRole !== undefined) values.systemRole = patch.systemRole; if (patch.status !== undefined) { values.status = patch.status; // Keep `approved_at` aligned with an admin status transition. Approval is // still derived from `status` at read time, but the audit trail should // show when the account was activated. values.approvedAt = patch.status === "active" ? new Date() : null; } if (patch.timezone !== undefined) values.timezone = patch.timezone; if (patch.emergencyContact !== undefined) values.emergencyContact = patch.emergencyContact; if (patch.notes !== undefined) values.notes = patch.notes; if (patch.deactivatedAt !== undefined) values.deactivatedAt = patch.deactivatedAt; const [row] = await db .update(users) .set(values) .where(eq(users.id, id)) .returning(); return row ?? null; } /** * Hard delete. Callers must check the removal rules first. * * The person's skill-level rows go with them — both explicitly here and via * `ON DELETE CASCADE`, so removal never leaves competency entries behind for an * account that no longer exists. Both writes share one transaction: if the * user row cannot be deleted, the skill rows are not touched either. */ export async function deleteUser(id: string) { return db.transaction(async (tx) => { await tx.delete(userSkills).where(eq(userSkills.userId, id)); const [row] = await tx .delete(users) .where(eq(users.id, id)) .returning({ id: users.id }); return row ?? null; }); }