fix(D8): grid slots render, per-cell optimistic revert, shared E2E helpers, admin reset endpoint
- src/db/grid.ts: key role map by ID (was slug, causing all cells to show '—') - src/components/app/schedule-grid-editor.tsx: revert only failed cell, not entire grid - src/db/audit.ts: fix import path ./db → @/db - src/db/seed.ts: add resetAndSeed(), assign Audio only (leave Livestream/Slides open) - src/auth/config.ts: carry id/email on JWT for audit actor - e2e/dev.ts: shared signInAs + resetDb helpers - e2e/schedule-grid.spec.ts: use shared helpers, reset DB beforeAll - e2e/assign-mutations.spec.ts: E2E for assign/clear with optimistic update + rollback - src/app/api/dev/reset/route.ts: admin-only DB reset endpoint - playwright.config.ts: workers: 1 (serial, suites share one Postgres)
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
import { auth } from "@/auth/config";
|
||||
import { AuthError, requirePermission } from "@/auth/permissions";
|
||||
import type { SystemRole } from "@/auth/roles";
|
||||
import { resetAndSeed } from "@/db/seed";
|
||||
|
||||
const JSON_HEADERS = { "content-type": "application/json" };
|
||||
|
||||
/**
|
||||
* Dev console reset. Admin-only (admin.settings): truncates the seed-owned
|
||||
* tables and repopulates them, so E2E tests start from a known-clean state on
|
||||
* every run instead of accumulating the mutations of prior runs. Not wired into
|
||||
* any UI — it exists only for test harnesses.
|
||||
*/
|
||||
export const POST = async () => {
|
||||
try {
|
||||
const session = await auth();
|
||||
requirePermission(
|
||||
(session?.user as { systemRole: SystemRole } | null | undefined),
|
||||
"admin.settings",
|
||||
);
|
||||
await resetAndSeed();
|
||||
return new Response(JSON.stringify({ ok: true }), {
|
||||
status: 200,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof AuthError) {
|
||||
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
|
||||
status: e.status,
|
||||
headers: JSON_HEADERS,
|
||||
});
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
+14
-2
@@ -48,13 +48,25 @@ export const authConfig = {
|
||||
callbacks: {
|
||||
async jwt({ token, user }) {
|
||||
if (user) {
|
||||
(token as { systemRole?: SystemRole }).systemRole =
|
||||
// Carry the stable identity + role onto the JWT so the session (which
|
||||
// only receives `user` on the first callback) can expose `id`/`email`
|
||||
// for the audit actor. Without this, `session.user.id` is undefined and
|
||||
// every assign/clear 500s on the audit_log actor_id NOT NULL constraint.
|
||||
(token as { id?: string; email?: string; systemRole?: SystemRole }).id =
|
||||
(user as { id?: string }).id;
|
||||
(token as { id?: string; email?: string; systemRole?: SystemRole }).email =
|
||||
(user as { email?: string }).email;
|
||||
(token as { id?: string; email?: string; systemRole?: SystemRole }).systemRole =
|
||||
(user as { systemRole?: SystemRole }).systemRole ?? "volunteer";
|
||||
}
|
||||
return token;
|
||||
},
|
||||
async session({ session, token }) {
|
||||
(session.user as { systemRole?: SystemRole }).systemRole =
|
||||
(session.user as { id?: string; email?: string; systemRole?: SystemRole }).id =
|
||||
(token as { id?: string }).id;
|
||||
(session.user as { id?: string; email?: string; systemRole?: SystemRole }).email =
|
||||
(token as { email?: string }).email;
|
||||
(session.user as { id?: string; email?: string; systemRole?: SystemRole }).systemRole =
|
||||
(token as { systemRole?: SystemRole }).systemRole ?? "volunteer";
|
||||
return session;
|
||||
},
|
||||
|
||||
@@ -61,7 +61,13 @@ export function ScheduleGridEditor({
|
||||
// non-JSON body — fall through to the default message
|
||||
}
|
||||
if (!res.ok) {
|
||||
setDisplay(committed.current);
|
||||
// Revert only the cell that failed, leaving other optimistic changes intact
|
||||
const committedSlot = committed.current.instances
|
||||
.flatMap((i) => i.slots)
|
||||
.find((s) => s.id === payload.slotId);
|
||||
setDisplay((prev) =>
|
||||
withSlotAssignments(prev, payload.slotId, committedSlot?.assignments ?? []),
|
||||
);
|
||||
setToast({ message: error ?? "Could not save. Please try again.", kind: "error" });
|
||||
} else {
|
||||
committed.current = display;
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@ export function auditRow(input: AuditInput): AuditRow {
|
||||
|
||||
/** Insert an audit row via the injected Drizzle client. */
|
||||
export async function writeAudit(
|
||||
db: typeof import("./db").db,
|
||||
db: typeof import("@/db").db,
|
||||
input: AuditInput,
|
||||
): Promise<AuditRow> {
|
||||
const row = auditRow(input);
|
||||
|
||||
+2
-2
@@ -108,7 +108,7 @@ export async function gridForWeek(weekStart: string): Promise<GridWeek> {
|
||||
name: r.name,
|
||||
colorHex: r.colorHex,
|
||||
}));
|
||||
const roleBySlug = new Map(positions.map((p) => [p.slug, p]));
|
||||
const roleById = new Map(roleRows.map((r) => [r.id, r]));
|
||||
|
||||
const serviceById = new Map(
|
||||
(await db.select().from(services)).map((s) => [s.id, s.name]),
|
||||
@@ -124,7 +124,7 @@ export async function gridForWeek(weekStart: string): Promise<GridWeek> {
|
||||
|
||||
const slotsOut: GridSlot[] = [];
|
||||
for (const slot of slotRows) {
|
||||
const role = roleBySlug.get(slot.roleId);
|
||||
const role = roleById.get(slot.roleId);
|
||||
const assignRows = await db
|
||||
.select()
|
||||
.from(assignments)
|
||||
|
||||
+50
-11
@@ -10,6 +10,7 @@
|
||||
*/
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { db } from "./index";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import {
|
||||
users,
|
||||
notificationPreferences,
|
||||
@@ -24,7 +25,20 @@ import { localToUtc, nextSundaysInTz } from "../lib/tz";
|
||||
|
||||
const CHURCH_TZ = "America/New_York";
|
||||
|
||||
async function main() {
|
||||
// Tables the seed owns. Truncating these (and cascading) gives a clean slate
|
||||
// for E2E resets without touching schema/migration tables.
|
||||
const RESET_TABLES = [
|
||||
"users",
|
||||
"roles",
|
||||
"services",
|
||||
"service_instances",
|
||||
"slots",
|
||||
"assignments",
|
||||
"notification_preferences",
|
||||
] as const;
|
||||
|
||||
/** Populate the core scheduling tables (idempotent: ON CONFLICT DO NOTHING). */
|
||||
export async function seed() {
|
||||
/* 1. Roles — production positions (audio, livestream, slides) */
|
||||
const roleRows: (typeof roles.$inferInsert)[] = [
|
||||
{
|
||||
@@ -173,14 +187,20 @@ async function main() {
|
||||
console.log(`notification_preferences: ${prefRows.length} seeded`);
|
||||
|
||||
|
||||
/* 6. Assignments — one confirmed volunteer per slot (round-robin) */
|
||||
/* 6. Assignments — one confirmed volunteer per instance (Audio only),
|
||||
* round-robin across instances. Livestream + Slides are left OPEN so the
|
||||
* assign picker (unit D8) has open cells and free volunteers to exercise; a
|
||||
* real published schedule also has open positions. */
|
||||
const volunteers = userRows2.filter((u) => u.systemRole === "volunteer");
|
||||
const assignedRows: (typeof assignments.$inferInsert)[] = [];
|
||||
for (let i = 0; i < slotRows2.length; i++) {
|
||||
const vol = volunteers[i % volunteers.length];
|
||||
let volIndex = 0;
|
||||
for (const slot of slotRows2) {
|
||||
if (slot.slotIndex !== 1) continue; // Audio only — leave the rest open
|
||||
const vol = volunteers[volIndex % volunteers.length];
|
||||
volIndex++;
|
||||
assignedRows.push({
|
||||
id: uuidv7(),
|
||||
slotId: slotRows2[i].id,
|
||||
slotId: slot.id,
|
||||
userId: vol.id,
|
||||
status: "confirmed",
|
||||
source: "manual",
|
||||
@@ -209,9 +229,28 @@ async function main() {
|
||||
console.log("seed complete");
|
||||
}
|
||||
|
||||
main()
|
||||
.then(() => process.exit(0))
|
||||
.catch((err) => {
|
||||
console.error("seed failed:", err);
|
||||
process.exit(1);
|
||||
});
|
||||
/** Truncate the seed-owned tables, then populate them from scratch. */
|
||||
export async function resetAndSeed(): Promise<void> {
|
||||
// The postgres.js driver exposes no typed `.truncate()`, and `sql.ident`
|
||||
// isn't available on its sql builder, so run TRUNCATE as raw SQL. The table
|
||||
// names are a hardcoded safe list, so string interpolation is fine. RESTART
|
||||
// IDENTITY resets sequences; CASCADE drops dependent rows.
|
||||
const list = RESET_TABLES.join(", ");
|
||||
await db.execute(sql`TRUNCATE TABLE ${sql.raw(list)} RESTART IDENTITY CASCADE`);
|
||||
await seed();
|
||||
}
|
||||
|
||||
// Only run the CLI when this file is the entry point (e.g. `pnpm db:seed`),
|
||||
// not when imported by the app (the /api/dev/reset route). Without this guard
|
||||
// importing the module would execute the seed and exit the server process.
|
||||
const isMain =
|
||||
process.argv[1] !== undefined &&
|
||||
process.argv[1] === fileURLToPath(import.meta.url);
|
||||
if (isMain) {
|
||||
void seed()
|
||||
.then(() => process.exit(0))
|
||||
.catch((err) => {
|
||||
console.error("seed failed:", err);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user