Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion src/app/host/events/[id]/edit/actions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ vi.mock("next/navigation", () => ({
},
}));

import { updateEventAction } from "./actions";
import { deleteEventAction, updateEventAction } from "./actions";

let db: Db;
let eventId: string;
Expand Down Expand Up @@ -75,3 +75,18 @@ describe("updateEventAction", () => {
expect((await getHostEvent(db, "host-1", eventId)).title).toBe("Cookout");
});
});

describe("deleteEventAction", () => {
it("deletes the event and redirects to the dashboard with its title", async () => {
await expect(deleteEventAction(eventId)).rejects.toThrow(
`NEXT_REDIRECT:/host?deleted=${encodeURIComponent("Cookout")}`,
);
await expect(getHostEvent(db, "host-1", eventId)).rejects.toThrow();
});

it("a different signed-in host gets a 404 and the event stays", async () => {
session.hostId = "host-2";
await expect(deleteEventAction(eventId)).rejects.toThrow("NEXT_NOT_FOUND");
expect((await getHostEvent(db, "host-1", eventId)).title).toBe("Cookout");
});
});
18 changes: 16 additions & 2 deletions src/app/host/events/[id]/edit/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import type { EditEventState } from "@/components/EditEventForm";
import { getDb } from "@/db/client";
import { requireHost } from "@/server/auth";
import { NotFoundError, ValidationError } from "@/services/errors";
import { updateEvent } from "@/services/events";
import { deleteEvent, updateEvent } from "@/services/events";

// The host comes from the session. The event id arrives through `bind`, but in Next 16
// bound arguments are sent to the browser and can be altered, so they are NOT protected:
// this is safe only because updateEvent re-checks that the event belongs to the host.
// this is safe only because these services re-check that the event belongs to the host.

function text(formData: FormData, key: string): string {
const v = formData.get(key);
Expand Down Expand Up @@ -41,3 +41,17 @@ export async function updateEventAction(
revalidatePath("/host");
redirect(`/host/events/${encodeURIComponent(eventId)}`);
}

/** Deletes the event (and everything on it), then returns to the dashboard to confirm. */
export async function deleteEventAction(eventId: string): Promise<void> {
const host = await requireHost();
let title: string;
try {
({ title } = await deleteEvent(await getDb(), host.id, eventId));
} catch (error) {
if (error instanceof NotFoundError) notFound();
throw error;
}
revalidatePath("/host");
redirect(`/host?deleted=${encodeURIComponent(title)}`);
}
7 changes: 6 additions & 1 deletion src/app/host/events/[id]/edit/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { DeleteEventSection } from "@/components/DeleteEventSection";
import { EditEventForm } from "@/components/EditEventForm";
import { dateToZonedLocal } from "@/lib/zoned-time";
import { loadHostEvent } from "@/server/host-event";
import { updateEventAction } from "./actions";
import { deleteEventAction, updateEventAction } from "./actions";

// Reads the session and the database, so it must never be prerendered.
export const dynamic = "force-dynamic";
Expand All @@ -23,6 +24,10 @@ export default async function EditEventPage({ params }: PageProps<"/host/events/
action={updateEventAction.bind(null, event.id)}
backHref={`/host/events/${encodeURIComponent(event.id)}`}
/>
<DeleteEventSection
title={event.title}
action={deleteEventAction.bind(null, event.id)}
/>
</div>
);
}
19 changes: 18 additions & 1 deletion src/app/host/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,15 @@ import { listHostEvents } from "@/services/events";
// Reads the session and the database, so it must never be prerendered.
export const dynamic = "force-dynamic";

export default async function HostDashboardPage() {
export default async function HostDashboardPage({ searchParams }: PageProps<"/host">) {
const host = await requireHost();
const [events, baseUrl] = await Promise.all([
getDb().then((db) => listHostEvents(db, host.id)),
getBaseUrl(),
]);
// Set by deleteEventAction; the notice stays until the host follows the Dismiss link.
const deleted = (await searchParams).deleted;
const deletedTitle = typeof deleted === "string" && deleted.trim() ? deleted : null;

return (
<main className="page-shell flex-1">
Expand All @@ -38,6 +41,20 @@ export default async function HostDashboardPage() {
</Link>
</div>

{deletedTitle ? (
<div
role="status"
className="ticket-surface mt-6 flex flex-wrap items-center justify-between gap-x-4 gap-y-1 rounded-2xl bg-paper px-4 py-2"
>
<p className="text-sm font-semibold">
Deleted <strong className="font-bold">“{deletedTitle}”</strong>.
</p>
<Link href="/host" className="quiet-link">
Dismiss
</Link>
</div>
) : null}

{events.length === 0 ? (
<div className="mt-8 max-w-2xl">
<Card className="flex flex-col gap-2">
Expand Down
47 changes: 47 additions & 0 deletions src/components/DeleteEventSection.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { DeleteEventSection } from "./DeleteEventSection";

const renderSection = () =>
render(<DeleteEventSection title="Burger Night" action={vi.fn()} />);

describe("DeleteEventSection", () => {
it("shows only the Delete event button until it is clicked", () => {
renderSection();
expect(screen.getByRole("button", { name: "Delete event" })).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Yes, delete it" })).not.toBeInTheDocument();
expect(screen.queryByText(/permanently removes/)).not.toBeInTheDocument();
});

it("reveals a confirmation naming the event, with focus on the confirm button", () => {
renderSection();
fireEvent.click(screen.getByRole("button", { name: "Delete event" }));

expect(
screen.getByText(/permanently removes all RSVPs, the menu, shopping and split data/),
).toBeInTheDocument();
expect(screen.getByText("Burger Night")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Yes, delete it" })).toHaveFocus();
expect(screen.queryByRole("button", { name: "Delete event" })).not.toBeInTheDocument();
});

it("hides the confirmation again when Cancel is pressed", () => {
renderSection();
fireEvent.click(screen.getByRole("button", { name: "Delete event" }));
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));

expect(screen.queryByRole("button", { name: "Yes, delete it" })).not.toBeInTheDocument();
expect(screen.queryByText(/permanently removes/)).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Delete event" })).toBeInTheDocument();
});

it("submits the bound delete action from the confirmation", async () => {
const action = vi.fn();
render(<DeleteEventSection title="Burger Night" action={action} />);
fireEvent.click(screen.getByRole("button", { name: "Delete event" }));
fireEvent.click(screen.getByRole("button", { name: "Yes, delete it" }));

await waitFor(() => expect(action).toHaveBeenCalledTimes(1));
expect(action.mock.calls[0][0]).toBeInstanceOf(FormData);
});
});
77 changes: 77 additions & 0 deletions src/components/DeleteEventSection.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"use client";

import { useEffect, useId, useRef, useState, type RefObject } from "react";
import { useFormStatus } from "react-dom";
import { Button } from "./ui/Button";
import { Card } from "./ui/Card";

/** A server action already bound to the event id (see deleteEventAction). */
export type DeleteEventAction = (formData: FormData) => void | Promise<void>;

/** The two confirm buttons; inside the form so useFormStatus sees its pending state. */
function DeleteActions({
confirmRef,
describedBy,
onCancel,
}: {
confirmRef: RefObject<HTMLButtonElement | null>;
describedBy: string;
onCancel: () => void;
}) {
const { pending } = useFormStatus();
return (
<div className="flex flex-wrap items-center gap-2">
<Button
ref={confirmRef}
variant="red"
type="submit"
disabled={pending}
aria-describedby={describedBy}
>
{pending ? "Deleting..." : "Yes, delete it"}
</Button>
<Button variant="outline" type="button" disabled={pending} onClick={onCancel}>
Cancel
</Button>
</div>
);
}

/** "Danger zone": Delete event reveals an inline confirmation, then submits the action. */
export function DeleteEventSection({ title, action }: { title: string; action: DeleteEventAction }) {
const [confirming, setConfirming] = useState(false);
const confirmRef = useRef<HTMLButtonElement>(null);
const questionId = useId();

// The confirm step replaces the button that was pressed, so put focus on its first action.
useEffect(() => {
if (confirming) confirmRef.current?.focus();
}, [confirming]);

return (
<Card className="mt-4 border-[1.5px] border-ketchup/25">
<h2 className="text-lg font-bold text-ketchup">Danger zone</h2>
<p className="mt-1 text-sm leading-relaxed text-ink-muted">
Deleting an event can’t be undone.
</p>

{confirming ? (
<form action={action} className="mt-3 flex flex-col gap-3">
<p id={questionId} className="text-sm leading-relaxed">
Delete <strong className="font-bold">{title}</strong>? This permanently removes all
RSVPs, the menu, shopping and split data.
</p>
<DeleteActions
confirmRef={confirmRef}
describedBy={questionId}
onCancel={() => setConfirming(false)}
/>
</form>
) : (
<Button variant="danger" onClick={() => setConfirming(true)} className="mt-3">
Delete event
</Button>
)}
</Card>
);
}
6 changes: 4 additions & 2 deletions src/components/ui/Button.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import type { ButtonHTMLAttributes } from "react";
import type { ComponentPropsWithRef } from "react";

const variants = {
red: "bg-ketchup text-paper shadow-[inset_0_-3px_0_rgb(0_0_0/0.18)] hover:bg-ketchup-deep",
mustard: "bg-mustard text-ink shadow-[inset_0_-3px_0_rgb(0_0_0/0.12)] hover:bg-mustard-deep",
outline:
"border-[1.5px] border-ink/70 bg-paper text-ink hover:border-ink hover:bg-cream/40",
danger:
"border-[1.5px] border-ketchup bg-paper text-ketchup hover:border-ketchup-deep hover:bg-ketchup/5 hover:text-ketchup-deep",
} as const;

export type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
export type ButtonProps = ComponentPropsWithRef<"button"> & {
variant: keyof typeof variants;
};

Expand Down
34 changes: 34 additions & 0 deletions src/services/events.test.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
// @vitest-environment node
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { Db } from "@/db/client";
import { eventDishes, events, guests, invitees, plusOnes } from "@/db/schema";
import { seedStarterRecipes } from "@/db/seed";
import { createTestDb } from "@/db/test-db";
import { formatWhen } from "@/lib/format";
import { zonedLocalToDate } from "@/lib/zoned-time";
import { NotFoundError, ValidationError } from "./errors";
import {
addInvitees,
createEvent,
deleteEvent,
getHostEvent,
headcountForEvents,
listHostEvents,
noReplyNames,
updateEvent,
} from "./events";
import { addDishToEvent } from "./menu";
import { getPublicEvent, submitRsvp } from "./rsvp";

let db: Db;
Expand Down Expand Up @@ -235,6 +239,36 @@ describe("updateEvent", () => {
});
});

describe("deleteEvent", () => {
it("deletes the host's event and cascades its guests, plus-ones, invitees and dishes", async () => {
await seedStarterRecipes(db);
const { id, shareCode } = await createEvent(db, "host-1", input);
await submitRsvp(db, { shareCode, name: "Alex", status: "yes", plusOneNames: ["Sam", "Jo"] });
await addInvitees(db, "host-1", id, ["Bea"]);
await addDishToEvent(db, "host-1", id, "starter-burgers");
await createEvent(db, "host-2", { ...input, title: "Not mine" });

expect(await deleteEvent(db, "host-1", id)).toEqual({ title: "Fourth of July" });

expect((await db.select().from(events)).map((e) => e.title)).toEqual(["Not mine"]);
expect(await db.select().from(guests)).toHaveLength(0);
expect(await db.select().from(plusOnes)).toHaveLength(0);
expect(await db.select().from(invitees)).toHaveLength(0);
expect(await db.select().from(eventDishes)).toHaveLength(0);
await expect(getPublicEvent(db, shareCode)).rejects.toBeInstanceOf(NotFoundError);
});

it("is a NotFoundError for another host's event and leaves it in place", async () => {
const { id } = await createEvent(db, "host-1", input);
await expect(deleteEvent(db, "host-2", id)).rejects.toBeInstanceOf(NotFoundError);
expect((await getHostEvent(db, "host-1", id)).title).toBe("Fourth of July");
});

it("is a NotFoundError for an unknown id", async () => {
await expect(deleteEvent(db, "host-1", "missing")).rejects.toBeInstanceOf(NotFoundError);
});
});

describe("event time zone", () => {
const originalTz = process.env.TZ;

Expand Down
18 changes: 18 additions & 0 deletions src/services/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,24 @@ export async function updateEvent(
.where(and(eq(events.id, eventId), eq(events.hostId, hostId)));
}

/**
* Deletes the host's event and returns its title (for a confirmation message).
* Every table that hangs off an event — guests and their plus-ones, dishes,
* invitees, shopping ticks, extra costs — cascades in the database.
*/
export async function deleteEvent(
db: Db,
hostId: string,
eventId: string,
): Promise<{ title: string }> {
const [deleted] = await db
.delete(events)
.where(and(eq(events.id, eventId), eq(events.hostId, hostId)))
.returning({ title: events.title });
if (!deleted) throw new NotFoundError("Event not found");
return deleted;
}

/** The host's events, soonest first, each with its planning headcount. */
export async function listHostEvents(db: Db, hostId: string): Promise<EventSummary[]> {
const rows = await db
Expand Down
Loading