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
58 changes: 54 additions & 4 deletions src/components/features/settings/hackathon-settings-form.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,26 @@ vi.mock("@/services/hackathon-settings", () => ({
updateHackathonConfig: settings.updateHackathonConfig,
}));

vi.mock("@/components/features/settings/wallet-email-control", () => ({
WalletEmailControl: () => null,
vi.mock("@/components/features/settings/wallet-settings-section", () => ({
WalletSettingsSection: ({
walletAvailable,
onWalletAvailableChange,
}: {
walletAvailable: boolean;
onWalletAvailableChange: (checked: boolean) => void;
}) => (
<button
type="button"
role="switch"
aria-checked={walletAvailable}
aria-label="Wallet Available"
onClick={() => onWalletAvailableChange(!walletAvailable)}
/>
),
}));

vi.mock("@/components/features/settings/wrapped-settings", () => ({
WrappedSettings: () => null,
}));

vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
Expand All @@ -29,15 +47,18 @@ const timeline = {
hackingEnd: { hackcamp: "2026-11-08T19:00:00.000Z" },
};

const toggleCtfAndSave = async () => {
const toggleAndSave = async (toggleName: string) => {
render(<HackathonSettingsForm hackathonId="HackCamp2026" />);
fireEvent.click(screen.getByRole("button", { name: "Edit" }));
fireEvent.click(screen.getByRole("switch", { name: "CTF Open" }));
fireEvent.click(screen.getByRole("switch", { name: toggleName }));
fireEvent.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(settings.updateHackathonConfig).toHaveBeenCalledOnce());
return settings.updateHackathonConfig.mock.calls[0][0] as HackathonConfig;
};

const toggleCtfAndSave = () => toggleAndSave("CTF Open");
const toggleWalletAndSave = () => toggleAndSave("Wallet Available");

describe("HackathonSettingsForm CTF Open", () => {
beforeEach(() => {
settings.updateHackathonConfig.mockReset();
Expand Down Expand Up @@ -66,3 +87,32 @@ describe("HackathonSettingsForm CTF Open", () => {
expect(saved.ctfOpen).toEqual({ hackcamp: true, nwhacks: true });
});
});

describe("HackathonSettingsForm Wallet Available", () => {
beforeEach(() => {
settings.updateHackathonConfig.mockReset();
});

it("creates the walletAvailable map when the doc doesn't have one yet", async () => {
settings.config = {
...timeline,
portalLive: { hackcamp: false },
} as unknown as HackathonConfig;

const saved = await toggleWalletAndSave();

expect(saved.walletAvailable).toEqual({ hackcamp: true });
expect(saved.portalLive).toEqual({ hackcamp: false });
});

it("only changes this hackathon's wallet flag", async () => {
settings.config = {
...timeline,
walletAvailable: { hackcamp: false, nwhacks: true },
} as unknown as HackathonConfig;

const saved = await toggleWalletAndSave();

expect(saved.walletAvailable).toEqual({ hackcamp: true, nwhacks: true });
});
});
31 changes: 16 additions & 15 deletions src/components/features/settings/hackathon-settings-form.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { WalletEmailControl } from "@/components/features/settings/wallet-email-control";
import { WalletSettingsSection } from "@/components/features/settings/wallet-settings-section";
import { WrappedSettings } from "@/components/features/settings/wrapped-settings";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
Expand Down Expand Up @@ -270,20 +270,13 @@ export function HackathonSettingsForm({ hackathonId }: { hackathonId: string })
placeholder="e.g., March 8-9"
/>
</div>
<div className="flex flex-wrap items-start justify-between gap-6">
<div className="flex items-center gap-4 pt-2">
<Label htmlFor="portalLive">Portal Live</Label>
<Switch
id="portalLive"
checked={getBooleanValue("portalLive")}
onCheckedChange={(checked) => handleFieldChange("portalLive", checked)}
disabled={!isEditing}
/>
</div>
<WalletEmailControl
key={hackathonId}
hackathonId={hackathonId}
disabled={isEditing || isSaving}
<div className="flex items-center gap-4 pt-2">
<Label htmlFor="portalLive">Portal Live</Label>
<Switch
id="portalLive"
checked={getBooleanValue("portalLive")}
onCheckedChange={(checked) => handleFieldChange("portalLive", checked)}
disabled={!isEditing}
/>
</div>
<div className="flex items-center justify-between">
Expand All @@ -303,6 +296,14 @@ export function HackathonSettingsForm({ hackathonId }: { hackathonId: string })
</div>
</div>

<WalletSettingsSection
hackathonId={hackathonId}
walletAvailable={getBooleanValue("walletAvailable")}
isEditing={isEditing}
isSaving={isSaving}
onWalletAvailableChange={(checked) => handleFieldChange("walletAvailable", checked)}
/>

<WrappedSettings
key={hackathonId}
hackathonId={hackathonId}
Expand Down
100 changes: 41 additions & 59 deletions src/components/features/settings/wallet-email-control.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,9 @@ import {
EmailDeliveryControl,
type EmailDeliveryCopy,
} from "@/components/features/settings/email-delivery-control";
import type { WalletEmailDelivery, WalletEmailSend } from "@/lib/firebase/types";
import {
countWalletEmailRecipients,
startWalletEmailDelivery,
subscribeToWalletEmailDelivery,
subscribeToWalletEmailRecipients,
subscribeToWalletEmailSends,
} from "@/services/wallet-email";
import { useEffect, useState } from "react";
import { type WalletEmailData, useWalletEmailData } from "@/hooks/use-wallet-email-data";
import type { WalletEmailSend } from "@/lib/firebase/types";
import { countWalletEmailRecipients, startWalletEmailDelivery } from "@/services/wallet-email";

const copyFor = (hackathonId: string): EmailDeliveryCopy => ({
idleLabel: "Send wallet emails",
Expand All @@ -36,61 +30,49 @@ const copyFor = (hackathonId: string): EmailDeliveryCopy => ({
startErrorFallback: "Could not start wallet emails",
});

type WalletEmailControlProps = {
hackathonId: string;
disabled?: boolean;
data?: WalletEmailData;
};

export function WalletEmailControl({
hackathonId,
disabled = false,
}: { hackathonId: string; disabled?: boolean }) {
const [state, setState] = useState<WalletEmailDelivery | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [sends, setSends] = useState<WalletEmailSend[] | null>(null);
const [recipientUids, setRecipientUids] = useState<string[] | null>(null);
const [sendsError, setSendsError] = useState<string | null>(null);
const [recipientsError, setRecipientsError] = useState<string | null>(null);
data,
}: WalletEmailControlProps) {
if (data) {
return <WalletEmailControlView hackathonId={hackathonId} disabled={disabled} data={data} />;
}
return <WalletEmailControlSubscribed hackathonId={hackathonId} disabled={disabled} />;
}

useEffect(() => {
setState(null);
setLoading(true);
setError(null);
const unsubscribe = subscribeToWalletEmailDelivery(
hackathonId,
(next) => {
setState(next);
setLoading(false);
setError(null);
},
(failure) => {
setError(`Could not load wallet email status: ${failure.message}`);
setLoading(false);
},
);
setSends(null);
setRecipientUids(null);
setSendsError(null);
setRecipientsError(null);
const unsubscribeSends = subscribeToWalletEmailSends(
hackathonId,
(next) => {
setSends(next);
setSendsError(null);
},
(failure) => setSendsError(`Could not load email send records: ${failure.message}`),
);
const unsubscribeRecipients = subscribeToWalletEmailRecipients(
hackathonId,
(uids) => {
setRecipientUids(uids);
setRecipientsError(null);
},
(failure) => setRecipientsError(`Could not load accepted applicants: ${failure.message}`),
);
return () => {
unsubscribe();
unsubscribeSends();
unsubscribeRecipients();
};
}, [hackathonId]);
function WalletEmailControlSubscribed({
hackathonId,
disabled = false,
}: { hackathonId: string; disabled?: boolean }) {
const data = useWalletEmailData(hackathonId);
return <WalletEmailControlView hackathonId={hackathonId} disabled={disabled} data={data} />;
}

function WalletEmailControlView({
hackathonId,
disabled = false,
data,
}: {
hackathonId: string;
disabled?: boolean;
data: WalletEmailData;
}) {
const {
delivery: state,
loading,
error,
sends,
recipientUids,
sendsError,
recipientsError,
} = data;
const sendDocs = sends ?? [];
const uidsForStatus = (status: WalletEmailSend["status"]) =>
sendDocs
Expand Down
119 changes: 119 additions & 0 deletions src/components/features/settings/wallet-settings-section.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { WalletSettingsSection } from "./wallet-settings-section";

const mocks = vi.hoisted(() => ({
getWalletEmailRecipients: vi.fn(),
generateAppleWalletPasses: vi.fn(),
subscribeToWalletEmailDelivery: vi.fn(),
subscribeToWalletEmailSends: vi.fn(),
subscribeToWalletEmailRecipients: vi.fn(),
countWalletEmailRecipients: vi.fn(),
startWalletEmailDelivery: vi.fn(),
toastError: vi.fn(),
toastSuccess: vi.fn(),
}));

vi.mock("@/services/wallet-email", () => ({
getWalletEmailRecipients: mocks.getWalletEmailRecipients,
subscribeToWalletEmailDelivery: mocks.subscribeToWalletEmailDelivery,
subscribeToWalletEmailSends: mocks.subscribeToWalletEmailSends,
subscribeToWalletEmailRecipients: mocks.subscribeToWalletEmailRecipients,
countWalletEmailRecipients: mocks.countWalletEmailRecipients,
startWalletEmailDelivery: mocks.startWalletEmailDelivery,
}));
vi.mock("@/services/wallet-passes", async (importOriginal) => ({
...(await importOriginal<typeof import("@/services/wallet-passes")>()),
generateAppleWalletPasses: mocks.generateAppleWalletPasses,
}));
vi.mock("sonner", () => ({
toast: { success: mocks.toastSuccess, error: mocks.toastError },
}));

const renderSection = (walletAvailable: boolean) =>
render(
<WalletSettingsSection
hackathonId="HackCamp2099"
walletAvailable={walletAvailable}
isEditing={false}
isSaving={false}
onWalletAvailableChange={vi.fn()}
/>,
);

beforeEach(() => {
vi.clearAllMocks();
mocks.subscribeToWalletEmailDelivery.mockReturnValue(() => {});
mocks.subscribeToWalletEmailSends.mockReturnValue(() => {});
mocks.subscribeToWalletEmailRecipients.mockReturnValue(() => {});
mocks.countWalletEmailRecipients.mockResolvedValue(0);
mocks.startWalletEmailDelivery.mockResolvedValue({ runId: "fixture", started: true });
});
afterEach(cleanup);

describe("WalletSettingsSection", () => {
it("warns that wallet buttons are hidden when Wallet Available is off", () => {
const view = renderSection(false);

expect(screen.getByRole("heading", { name: "Wallet" })).toBeTruthy();
expect(screen.getByText(/buttons are hidden on hacker tickets/i)).toBeTruthy();
expect(screen.getByText(/wallet emails and email links still work/i)).toBeTruthy();

view.rerender(
<WalletSettingsSection
hackathonId="HackCamp2099"
walletAvailable
isEditing={false}
isSaving={false}
onWalletAvailableChange={vi.fn()}
/>,
);
expect(screen.queryByText(/buttons are hidden on hacker tickets/i)).toBeNull();
});

it("generates Apple passes in chunks of 25 and reports progress", async () => {
const recipients = Array.from({ length: 30 }, (_, index) => ({
uid: `uid-${index}`,
email: `user-${index}@example.com`,
}));
mocks.getWalletEmailRecipients.mockResolvedValue(recipients);
mocks.generateAppleWalletPasses.mockImplementation(async (_id, uids: string[]) => ({
generated: uids.length,
failed: [],
}));

renderSection(true);
fireEvent.click(screen.getByRole("button", { name: "Generate / regenerate Apple passes" }));
fireEvent.click(await screen.findByRole("button", { name: "Generate passes" }));

await waitFor(() => expect(mocks.generateAppleWalletPasses).toHaveBeenCalledTimes(2));
expect(mocks.generateAppleWalletPasses.mock.calls[0]).toEqual([
"HackCamp2099",
recipients.slice(0, 25).map((recipient) => recipient.uid),
]);
expect(mocks.generateAppleWalletPasses.mock.calls[1]).toEqual([
"HackCamp2099",
recipients.slice(25).map((recipient) => recipient.uid),
]);
expect(await screen.findByText(/30 of 30 processed · 30 generated/)).toBeTruthy();
});

it("explains a generic internal callable error instead of only showing the raw code", async () => {
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
mocks.getWalletEmailRecipients.mockResolvedValue([{ uid: "uid-0" }]);
mocks.generateAppleWalletPasses.mockRejectedValue(
Object.assign(new Error("internal"), { code: "internal" }),
);

renderSection(true);
fireEvent.click(screen.getByRole("button", { name: "Generate / regenerate Apple passes" }));
fireEvent.click(await screen.findByRole("button", { name: "Generate passes" }));

expect(await screen.findByText(/confirm generateAppleWalletPasses is deployed/i)).toBeTruthy();
expect(mocks.toastError).toHaveBeenCalledWith(
expect.stringContaining("generateAppleWalletPasses is deployed"),
);
expect(await screen.findByText(/Stopped after 0 of 1 processed/)).toBeTruthy();
consoleError.mockRestore();
});
});
Loading
Loading