Files
minecraft-account-manager/apps/web/src/app/admin/(console)/groups/[groupId]/page.tsx
T
dmg 6fa33c9f7b
CI / validate (push) Successful in 6m9s
Release / release (push) Successful in 7m51s
feat(admin): show group schedule status
2026-08-02 14:26:24 -04:00

151 lines
11 KiB
TypeScript

import { groupAccessWindows, groups, minecraftAccounts, userGroupMemberships, users } from "@minecraft-account-manager/database";
import { and, asc, desc, eq, isNull, sql } from "drizzle-orm";
import type { ReactNode } from "react";
import Link from "next/link";
import { notFound } from "next/navigation";
import { AdminModalForm } from "@/components/admin-modal-form";
import { AdminUserTable } from "@/components/admin-user-table";
import { GroupPolicyControl } from "@/components/group-policy-control";
import { GroupScheduleEditor, GroupScheduleSummary } from "@/components/group-schedule-editor";
import { db } from "@/lib/database";
import { isEffectiveGroupMember } from "@/lib/group-management";
import { assignUserGroupFromRegistry } from "../../users/actions";
import { deleteGroup, replaceGroupSchedule, setGroupAccess, setGroupAnonymizedNetworkAccess, updateGroupDetails } from "../actions";
const savedMessages: Record<string, string> = {
created: "Group created.",
details: "Group details updated.",
access: "Minecraft access policy updated.",
"network-access": "VPN, proxy, and Tor policy updated.",
schedule: "Weekly access schedule updated.",
group: "Member group updated.",
};
const errorMessages: Record<string, string> = {
"invalid-group": "Enter a valid name and a description of no more than 500 characters.",
"duplicate-group": "A group with that name already exists.",
"invalid-group-assignment": "The user or destination group no longer exists. No membership change was applied.",
"invalid-schedule": "Use valid, non-overlapping weekly access windows. Start and end cannot be identical.",
};
export const dynamic = "force-dynamic";
export default async function GroupPage({
params,
searchParams,
}: {
params: Promise<{ groupId: string }>;
searchParams: Promise<{ error?: string; saved?: string }>;
}) {
const { groupId } = await params;
const query = await searchParams;
const [group] = await db.select().from(groups).where(eq(groups.id, groupId)).limit(1);
if (!group) notFound();
const [allUsers, allGroups, memberships, accessWindows] = await Promise.all([
db.select({
id: users.id,
firstName: users.firstName,
discordUsername: users.discordUsername,
discordGlobalName: users.discordGlobalName,
discordUserId: users.discordUserId,
onboardingCompletedAt: users.onboardingCompletedAt,
primaryUsername: minecraftAccounts.username,
accountCount: sql<number>`(
select count(*)::int from ${minecraftAccounts} account_count
where account_count.user_id = ${users.id}
and account_count.deleted_at is null
)`,
})
.from(users)
.leftJoin(minecraftAccounts, and(
eq(minecraftAccounts.userId, users.id),
eq(minecraftAccounts.isPrimary, true),
isNull(minecraftAccounts.deletedAt),
))
.orderBy(users.firstName, users.discordUsername),
db.select({ id: groups.id, name: groups.name, isDefault: groups.isDefault })
.from(groups).orderBy(desc(groups.isDefault), asc(groups.name)),
db.select({ userId: userGroupMemberships.userId, groupId: userGroupMemberships.groupId })
.from(userGroupMemberships),
db.select({
startMinuteOfWeek: groupAccessWindows.startMinuteOfWeek,
endMinuteOfWeek: groupAccessWindows.endMinuteOfWeek,
}).from(groupAccessWindows).where(eq(groupAccessWindows.groupId, group.id))
.orderBy(groupAccessWindows.startMinuteOfWeek),
]);
const assignmentByUser = Object.fromEntries(memberships.map((membership) => [membership.userId, membership.groupId]));
const memberUsers = allUsers.filter((user) => isEffectiveGroupMember(user.id, assignmentByUser, group));
const returnTo = `/admin/groups/${group.id}`;
return (
<main className="mx-auto max-w-6xl px-6 py-12">
<Link className="font-mono text-[10px] font-bold uppercase tracking-widest text-muted underline underline-offset-4" href="/admin/groups"> All groups</Link>
<header className="mt-7 flex flex-col gap-6 border-b border-line pb-8 lg:flex-row lg:items-end lg:justify-between">
<div>
<p className="font-mono text-xs font-bold uppercase tracking-[0.25em] text-accent">Access group</p>
<div className="mt-4 flex flex-wrap items-center gap-3"><h1 className="font-display text-5xl font-black uppercase sm:text-7xl">{group.name}</h1>{group.isDefault && <span className="bg-ink px-3 py-2 font-mono text-[9px] font-bold uppercase text-canvas">Default</span>}</div>
<p className="mt-3 max-w-2xl whitespace-pre-line text-sm leading-6 text-muted">{group.description ?? "No description."}</p>
</div>
<AdminModalForm
action={updateGroupDetails}
description={group.isDefault ? "Update the protected default group's description. Its name remains everyone." : "Update the administrator-facing name and description. The internal slug remains stable."}
submitLabel="Save details"
title={`Edit ${group.name}`}
triggerClassName="border border-ink px-5 py-3 font-mono text-[10px] font-bold uppercase tracking-wider"
triggerLabel="Edit group"
>
<input name="groupId" type="hidden" value={group.id} />
<div className="space-y-5">
<label className="block text-sm font-bold">Name<input className="mt-2 w-full border border-line bg-canvas px-4 py-3 font-normal outline-none focus:border-accent read-only:cursor-not-allowed read-only:text-muted" defaultValue={group.name} maxLength={50} name="name" readOnly={group.isDefault} required /></label>
<label className="block text-sm font-bold">Description<textarea className="mt-2 min-h-32 w-full resize-y border border-line bg-canvas px-4 py-3 font-normal outline-none focus:border-accent" defaultValue={group.description ?? ""} maxLength={500} name="description" /></label>
</div>
</AdminModalForm>
</header>
{query.saved && <p className="mt-7 border-l-2 border-signal bg-panel px-5 py-4 text-sm" role="status">{savedMessages[query.saved] ?? "Group updated."}</p>}
{query.error && <p className="mt-7 border-l-2 border-accent bg-panel px-5 py-4 text-sm text-accent" role="alert">{errorMessages[query.error] ?? "The group operation failed."}</p>}
<section aria-labelledby="group-policy-heading" className="mt-10 border border-line bg-panel p-6 shadow-[6px_6px_0_var(--color-shadow)]">
<div className="border-b border-line pb-4"><p className="font-mono text-[9px] font-bold uppercase tracking-widest text-muted">Admission controls</p><h2 className="mt-2 font-display text-3xl font-black uppercase" id="group-policy-heading">Group policies</h2></div>
<div className="mt-6 grid gap-6 sm:grid-cols-2">
<PolicyDetail description="Controls whether members can connect to Minecraft. Disabled access always overrides the schedule." label="Minecraft access"><GroupPolicyControl action={setGroupAccess} enabled={group.accessEnabled} groupId={group.id} groupName={group.name} memberCount={memberUsers.length} policy="Minecraft access" returnLocation="detail" /></PolicyDetail>
<PolicyDetail description="Allows confirmed VPN, proxy, and Tor connections after access and schedule checks pass." label="VPN / proxy / Tor"><GroupPolicyControl action={setGroupAnonymizedNetworkAccess} enabled={group.anonymizedNetworksAllowed} groupId={group.id} groupName={group.name} memberCount={memberUsers.length} policy="VPN / proxy / Tor" returnLocation="detail" /></PolicyDetail>
</div>
<div className="mt-7 scroll-mt-6 border-t border-line pt-6" id="group-schedule">
<div className="flex flex-col gap-5 sm:flex-row sm:items-start sm:justify-between">
<div className="max-w-2xl"><h3 className="font-mono text-xs font-bold uppercase">Weekly access schedule</h3><p className="mt-2 text-xs leading-5 text-muted">When Minecraft access is enabled, members may log in only during these recurring UTC windows. Existing sessions are not disconnected when a window ends.</p><div className="mt-4"><GroupScheduleSummary windows={accessWindows} /></div></div>
<AdminModalForm action={replaceGroupSchedule} description={`Replace the complete weekly access schedule for ${group.name}. Minecraft access must still be enabled.`} submitLabel="Save schedule" title={`Schedule ${group.name}`} triggerClassName="shrink-0 border border-ink px-4 py-3 font-mono text-[10px] font-bold uppercase tracking-wider" triggerLabel="Edit schedule">
<input name="groupId" type="hidden" value={group.id} />
<GroupScheduleEditor windows={accessWindows} />
</AdminModalForm>
</div>
</div>
</section>
<section className="mt-10" aria-labelledby="group-members-heading">
<div className="flex items-end justify-between border-b border-line pb-4">
<div><p className="font-mono text-[9px] font-bold uppercase tracking-widest text-muted">Effective membership</p><h2 className="mt-2 font-display text-3xl font-black uppercase" id="group-members-heading">Members</h2></div>
<span className="font-mono text-xs text-muted">{memberUsers.length} {memberUsers.length === 1 ? "member" : "members"}</span>
</div>
<p className="border-x border-line bg-panel px-5 py-4 text-sm text-muted">{group.isDefault ? <>These users have no explicit assignment and therefore use <strong className="text-ink">everyone</strong>.</> : <>Choose another group to move a member, or choose <strong className="text-ink">everyone</strong> to remove the member from {group.name}. Every change requires confirmation.</>}</p>
<div className="mt-5"><AdminUserTable action={assignUserGroupFromRegistry} assignmentByUser={assignmentByUser} emptyMessage="This group has no effective members." groups={allGroups} returnTo={returnTo} users={memberUsers} /></div>
</section>
{!group.isDefault && (
<section className="mt-12 flex flex-col gap-5 border border-accent bg-panel p-6 sm:flex-row sm:items-center sm:justify-between">
<div><p className="font-mono text-[10px] font-bold uppercase tracking-widest text-accent">Danger zone</p><h2 className="mt-2 font-display text-2xl font-black uppercase">Delete {group.name}</h2><p className="mt-2 max-w-2xl text-sm leading-6 text-muted">All {memberUsers.length} effective {memberUsers.length === 1 ? "member" : "members"} will return to everyone.</p></div>
<AdminModalForm action={deleteGroup} description={`Permanently delete ${group.name} and return ${memberUsers.length} ${memberUsers.length === 1 ? "member" : "members"} to everyone. This cannot be undone.`} intent="danger" submitLabel="Delete group" title={`Delete ${group.name}?`} triggerClassName="bg-accent px-5 py-3 font-mono text-[10px] font-bold uppercase tracking-wider text-canvas" triggerLabel="Delete group">
<input name="groupId" type="hidden" value={group.id} />
<input name="confirmDelete" type="hidden" value="yes" />
</AdminModalForm>
</section>
)}
</main>
);
}
function PolicyDetail({ children, description, label }: { children: ReactNode; description: string; label: string }) {
return <div className="flex items-center justify-between gap-5 border-l-2 border-accent pl-5"><div><h3 className="font-mono text-xs font-bold uppercase">{label}</h3><p className="mt-2 text-xs leading-5 text-muted">{description}</p></div>{children}</div>;
}