diff --git a/src/components/features/settings/email-delivery-control.tsx b/src/components/features/settings/email-delivery-control.tsx new file mode 100644 index 0000000..0c344dd --- /dev/null +++ b/src/components/features/settings/email-delivery-control.tsx @@ -0,0 +1,308 @@ +import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/components/ui/alert-dialog"; +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import type { WalletEmailDelivery } from "@/lib/firebase/types"; +import { LoaderCircle, Mail } from "lucide-react"; +import { type ReactNode, useEffect, useRef, useState } from "react"; +import { toast } from "sonner"; + +/** Run-status fields shared by every email delivery written by Functions-new. */ +export type EmailDeliveryState = WalletEmailDelivery; + +export interface EmailDeliveryBucket { + key: string; + label: string; + uids: string[]; + /** Optional per-uid note shown in the UID list, e.g. a skip reason or error. */ + details?: Record; +} + +export interface EmailDeliveryCopy { + idleLabel: string; + busyLabel: string; + retryLabel: string; + idleStatus: string; + loadingStatus: string; + preparingStatus: string; + sendingStatus: (processed: number, total: number) => string; + completedStatus: string; + confirmTitle: string; + countingSummary: string; + countErrorSummary: string; + emptySummary: string; + recipientSummary: (count: number) => string; + beforeYouSend: ReactNode; + countErrorFallback: string; + startedToast: string; + alreadyRunningToast: string; + startErrorFallback: string; +} + +/** + * Presentational send button, live status, and per-recipient counters for a + * server-side email delivery. Callers own all data fetching. + */ +export function EmailDeliveryControl({ + statusId, + delivery: state, + loading, + error, + buckets, + bucketsLoadingText, + bucketErrors = [], + countRecipients, + start, + copy, + disabled = false, + disabledReason, +}: { + statusId: string; + delivery: EmailDeliveryState | null; + loading: boolean; + error: string | null; + /** null hides the counters, e.g. while records load or after a read error. */ + buckets: EmailDeliveryBucket[] | null; + bucketsLoadingText?: string | null; + bucketErrors?: (string | null)[]; + countRecipients: () => Promise; + start: () => Promise<{ started: boolean }>; + copy: EmailDeliveryCopy; + disabled?: boolean; + disabledReason?: string | null; +}) { + const [starting, setStarting] = useState(false); + const [now, setNow] = useState(Date.now()); + const [confirmOpen, setConfirmOpen] = useState(false); + const [recipientCount, setRecipientCount] = useState(null); + const [countError, setCountError] = useState(null); + const [selectedBucket, setSelectedBucket] = useState(null); + const submitting = useRef(false); + const countRequest = useRef(0); + + useEffect(() => { + const timer = window.setInterval(() => setNow(Date.now()), 30000); + return () => window.clearInterval(timer); + }, []); + + const inProgress = !!state && ["preparing", "queued", "sending"].includes(state.status); + const interrupted = inProgress && now - state.updatedAt.toMillis() >= 60 * 60 * 1000; + const busy = starting || (inProgress && !interrupted); + const current = inProgress && !interrupted ? state?.currentProgress : undefined; + const sent = (state?.sent ?? 0) + (current?.sent ?? 0); + const skipped = (state?.skipped ?? 0) + (current?.skipped ?? 0); + const failed = (state?.failed ?? 0) + (current?.failed ?? 0); + const uncertain = (state?.uncertain ?? 0) + (current?.uncertain ?? 0); + const processed = Math.min( + state?.total ?? 0, + (state?.processed ?? 0) + + (current ? current.sent + current.skipped + current.failed + current.uncertain : 0), + ); + const needsRetry = + interrupted || state?.status === "failed" || state?.status === "completed-with-errors"; + const lastClicked = state?.lastClickedAt.toDate(); + + const openConfirm = () => { + if (submitting.current || busy || loading || error) return; + setRecipientCount(null); + setCountError(null); + setConfirmOpen(true); + const request = ++countRequest.current; + countRecipients() + .then((count) => { + if (countRequest.current === request) setRecipientCount(count); + }) + .catch((failure) => { + if (countRequest.current === request) { + setCountError(failure instanceof Error ? failure.message : copy.countErrorFallback); + } + }); + }; + + const handleConfirm = async () => { + if (submitting.current || busy || loading) return; + submitting.current = true; + setConfirmOpen(false); + setStarting(true); + try { + const result = await start(); + toast.success(result.started ? copy.startedToast : copy.alreadyRunningToast); + } catch (failure) { + toast.error(failure instanceof Error ? failure.message : copy.startErrorFallback); + } finally { + submitting.current = false; + setStarting(false); + } + }; + + let status = copy.idleStatus; + if (loading) status = copy.loadingStatus; + else if (interrupted) status = "Delivery was interrupted. Resume to check remaining emails."; + else if (state?.status === "preparing") status = copy.preparingStatus; + else if (state?.status === "queued") status = "Queued. Delivery continues in the background."; + else if (state?.status === "sending") status = copy.sendingStatus(processed, state.total); + else if (state?.status === "completed") status = copy.completedStatus; + else if (state?.status === "completed-with-errors") + status = "Delivery finished with emails that need attention."; + else if (state?.status === "failed") + status = state.error || "Delivery stopped. Retry to continue."; + + let recipientSummary = copy.countingSummary; + if (countError) recipientSummary = copy.countErrorSummary; + else if (recipientCount === 0) recipientSummary = copy.emptySummary; + else if (recipientCount !== null) recipientSummary = copy.recipientSummary(recipientCount); + + const activeBucket = buckets?.find((bucket) => bucket.key === selectedBucket); + + return ( +
+ + {buckets && ( +
+ {buckets.map((bucket) => ( + + ))} +
+ )} + {bucketsLoadingText &&

{bucketsLoadingText}

} + {bucketErrors.map( + (bucketError) => + bucketError && ( +

+ {bucketError} +

+ ), + )} + + {error || status} + {state && state.total > 0 && ( + + {sent} sent · {skipped} already sent or skipped · {failed} failed + {uncertain > 0 ? ` · ${uncertain} need review` : ""} + + )} + {uncertain > 0 && ( + + Check the sender mailbox for unconfirmed deliveries. They will not be sent again + automatically. + + )} + {lastClicked ? ( + + Last clicked{" "} + + {state?.startedByEmail ? ` by ${state.startedByEmail}` : ""}. + + ) : ( + !loading && Not sent yet. + )} + {busy && You can close this page. Delivery will continue.} + {disabled && disabledReason && {disabledReason}} + + + + + {copy.confirmTitle} + {recipientSummary} + + + Before you send + {copy.beforeYouSend} + + + Cancel + + Send emails + + + + + { + if (!open) setSelectedBucket(null); + }} + > + {activeBucket && ( + + + {activeBucket.label} UIDs + + {activeBucket.uids.length} applicant + {activeBucket.uids.length === 1 ? "" : "s"}. + + +
+ {activeBucket.uids.length === 0 ? ( +

No UIDs.

+ ) : ( +
    + {activeBucket.uids.map((uid) => ( +
  • + {uid} + {activeBucket.details?.[uid] && ( + + {activeBucket.details[uid]} + + )} +
  • + ))} +
+ )} +
+
+ )} +
+
+ ); +} diff --git a/src/components/features/settings/hackathon-settings-form.test.tsx b/src/components/features/settings/hackathon-settings-form.test.tsx index 0a867e4..9ff7b91 100644 --- a/src/components/features/settings/hackathon-settings-form.test.tsx +++ b/src/components/features/settings/hackathon-settings-form.test.tsx @@ -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; + }) => ( + - {showCounters && ( -
- {buckets.map((bucket) => ( - - ))} -
- )} - {!loading && state !== null && sends === null && !sendsError && ( -

Loading email send records…

- )} - {sendsError &&

{sendsError}

} - {recipientsError &&

{recipientsError}

} - - {error || status} - {state && state.total > 0 && ( - - {sent} sent · {skipped} already sent or skipped · {failed} failed - {uncertain > 0 ? ` · ${uncertain} need review` : ""} - - )} - {uncertain > 0 && ( - - Check the sender mailbox for unconfirmed deliveries. They will not be sent again - automatically. - - )} - {lastClicked ? ( - - Last clicked{" "} - - {state?.startedByEmail ? ` by ${state.startedByEmail}` : ""}. - - ) : ( - !loading && Not sent yet. - )} - {busy && You can close this page. Delivery will continue.} - {disabled && ( - Save or cancel your settings changes before sending. - )} - - - - - Send wallet emails? - {recipientSummary} - - - Before you send - - Make sure the Apple passes have been created and uploaded for every attending - applicant first. Delivery fails if any accepted applicant is missing a pass. - - - - Cancel - - Send emails - - - - - { - if (!open) setSelectedBucket(null); - }} - > - {activeBucket && ( - - - {BUCKET_LABELS[activeBucket.key]} UIDs - - {activeBucket.uids.length} applicant - {activeBucket.uids.length === 1 ? "" : "s"}. - - -
- {activeBucket.uids.length === 0 ? ( -

No UIDs.

- ) : ( -
    - {activeBucket.uids.map((uid) => ( -
  • - {uid} -
  • - ))} -
- )} -
-
- )} -
- + countWalletEmailRecipients(hackathonId)} + start={() => startWalletEmailDelivery(hackathonId)} + copy={copyFor(hackathonId)} + disabled={disabled} + disabledReason="Save or cancel your settings changes before sending." + /> ); } diff --git a/src/components/features/settings/wallet-settings-section.test.tsx b/src/components/features/settings/wallet-settings-section.test.tsx new file mode 100644 index 0000000..42055f2 --- /dev/null +++ b/src/components/features/settings/wallet-settings-section.test.tsx @@ -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()), + generateAppleWalletPasses: mocks.generateAppleWalletPasses, +})); +vi.mock("sonner", () => ({ + toast: { success: mocks.toastSuccess, error: mocks.toastError }, +})); + +const renderSection = (walletAvailable: boolean) => + render( + , + ); + +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( + , + ); + 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(); + }); +}); diff --git a/src/components/features/settings/wallet-settings-section.tsx b/src/components/features/settings/wallet-settings-section.tsx new file mode 100644 index 0000000..2d52d26 --- /dev/null +++ b/src/components/features/settings/wallet-settings-section.tsx @@ -0,0 +1,245 @@ +import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/components/ui/alert-dialog"; +import { Button } from "@/components/ui/button"; +import { Label } from "@/components/ui/label"; +import { Switch } from "@/components/ui/switch"; +import { useWalletEmailData } from "@/hooks/use-wallet-email-data"; +import { chunkArray, downloadCSV } from "@/lib/utils"; +import { buildWalletEmailCsv } from "@/lib/wallet-email-csv"; +import { getWalletEmailRecipients } from "@/services/wallet-email"; +import { generateAppleWalletPasses, getWalletPassesErrorMessage } from "@/services/wallet-passes"; +import { format } from "date-fns/format"; +import { AlertTriangle, Download, LoaderCircle, WalletCards } from "lucide-react"; +import { useState } from "react"; +import { toast } from "sonner"; +import { WalletEmailControl } from "./wallet-email-control"; + +const APPLE_PASS_CHUNK_SIZE = 25; + +interface WalletSettingsSectionProps { + hackathonId: string; + walletAvailable: boolean; + isEditing: boolean; + isSaving: boolean; + onWalletAvailableChange: (checked: boolean) => void; +} + +interface GenerationProgress { + processed: number; + total: number; + generated: number; +} + +export function WalletSettingsSection({ + hackathonId, + walletAvailable, + isEditing, + isSaving, + onWalletAvailableChange, +}: WalletSettingsSectionProps) { + const data = useWalletEmailData(hackathonId); + const [confirmOpen, setConfirmOpen] = useState(false); + const [generating, setGenerating] = useState(false); + const [exporting, setExporting] = useState(false); + const [progress, setProgress] = useState(null); + const [failures, setFailures] = useState<{ uid: string; error: string }[]>([]); + const [generationError, setGenerationError] = useState(null); + + const settingsBusy = isEditing || isSaving; + const dataLoaded = + data.sends !== null && data.recipientUids !== null && !data.sendsError && !data.recipientsError; + + const handleGenerate = async () => { + if (generating || settingsBusy) return; + setConfirmOpen(false); + setGenerating(true); + setProgress({ processed: 0, total: 0, generated: 0 }); + setFailures([]); + setGenerationError(null); + + try { + const recipients = await getWalletEmailRecipients(hackathonId); + const uids = recipients.map((recipient) => recipient.uid); + let processed = 0; + let generated = 0; + const failed: { uid: string; error: string }[] = []; + setProgress({ processed, total: uids.length, generated }); + + for (const chunk of chunkArray(uids, APPLE_PASS_CHUNK_SIZE)) { + const result = await generateAppleWalletPasses(hackathonId, chunk); + processed += chunk.length; + generated += result.generated; + failed.push(...result.failed); + setProgress({ processed, total: uids.length, generated }); + setFailures([...failed]); + } + + const noun = generated === 1 ? "pass" : "passes"; + if (failed.length > 0) { + toast.error(`Generated ${generated} Apple ${noun}; ${failed.length} failed`); + } else { + toast.success(`Generated ${generated} Apple ${noun}`); + } + } catch (error) { + console.error("Error generating Apple passes:", error); + const message = getWalletPassesErrorMessage(error); + setGenerationError(message); + toast.error(message); + } finally { + setGenerating(false); + } + }; + + const handleExport = async () => { + if (!data.sends || !data.recipientUids || exporting) return; + setExporting(true); + try { + const recipients = await getWalletEmailRecipients(hackathonId); + const csv = buildWalletEmailCsv(recipients, data.sends); + const date = format(new Date(), "yyyy-MM-dd"); + downloadCSV(csv, `wallet-email-${hackathonId}-${date}.csv`); + toast.success("Wallet email CSV exported"); + } catch (error) { + toast.error(error instanceof Error ? error.message : "Could not export wallet email CSV"); + } finally { + setExporting(false); + } + }; + + return ( +
+
+

Wallet

+

+ Apple Wallet passes and wallet emails for attending hackers. +

+
+
+
+
+ +

+ Shows the Add to Apple/Google Wallet buttons on hacker tickets +

+
+ +
+ + {!walletAvailable && ( + + + )} + +
+ +
+ + +
+ {progress && ( + + {generationError + ? `Stopped after ${progress.processed} of ${progress.total} processed` + : `${generating ? "Generating" : "Finished"} ${progress.processed} of ${progress.total} processed`}{" "} + · {progress.generated} generated + {failures.length > 0 ? ` · ${failures.length} failed` : ""} + + )} + {generationError &&

{generationError}

} + {failures.length > 0 && ( +
+
    + {failures.map((failure, index) => ( +
  • + {failure.uid}: {failure.error} +
  • + ))} +
+
+ )} +
+ +
+ + +
+
+ + + + + Generate Apple passes? + + This will generate or regenerate Apple Wallet passes for every applicant marked + accepted and attending, in batches of {APPLE_PASS_CHUNK_SIZE}. It may take a few + minutes. + + + + Cancel + + Generate passes + + + + +
+ ); +} diff --git a/src/components/features/settings/wrapped-email-control.test.tsx b/src/components/features/settings/wrapped-email-control.test.tsx new file mode 100644 index 0000000..e079be2 --- /dev/null +++ b/src/components/features/settings/wrapped-email-control.test.tsx @@ -0,0 +1,149 @@ +import type { WrappedEmailLedger } from "@/lib/firebase/types"; +import { + countWrappedEmailRecipients, + loadWrappedEmailRecipientUids, + startWrappedEmailDelivery, + subscribeToWrappedEmailLedger, +} from "@/services/wrapped-email"; +import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { Timestamp } from "firebase/firestore"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { WrappedEmailControl } from "./wrapped-email-control"; + +// No Firebase client, callable, or delivery service is loaded by this test. +vi.mock("@/services/wrapped-email", () => ({ + countWrappedEmailRecipients: vi.fn(), + loadWrappedEmailRecipientUids: vi.fn(), + startWrappedEmailDelivery: vi.fn(), + subscribeToWrappedEmailLedger: vi.fn(), +})); +vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } })); + +let publish: (ledger: WrappedEmailLedger | null) => void; +const unsubscribe = vi.fn(); +const ready = { isReady: true, bannerUrl: "https://example.invalid/banner.png" }; +const fixture = (overrides: Partial = {}): WrappedEmailLedger => ({ + runId: "fixture", + status: "sending", + lastClickedAt: Timestamp.fromMillis(Date.now()), + updatedAt: Timestamp.fromMillis(Date.now()), + startedByEmail: "admin@example.invalid", + total: 6, + processed: 5, + sent: 2, + skipped: 2, + failed: 1, + uncertain: 0, + recipients: { + a: { s: "sent" }, + b: { s: "sent" }, + c: { s: "skipped", r: "no-wrapped-doc" }, + d: { s: "skipped", r: "opted-out" }, + e: { s: "failed", e: "Mailbox full" }, + }, + ...overrides, +}); +const sendButton = () => + screen.getByRole("button", { name: /Wrapped emails|Retry remaining/ }) as HTMLButtonElement; + +beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(subscribeToWrappedEmailLedger).mockImplementation((_id, onChange) => { + publish = onChange; + return unsubscribe; + }); + vi.mocked(loadWrappedEmailRecipientUids).mockResolvedValue(["a", "b", "c", "d", "e", "f"]); + vi.mocked(countWrappedEmailRecipients).mockResolvedValue(42); + vi.mocked(startWrappedEmailDelivery).mockResolvedValue({ runId: "fixture", started: true }); +}); +afterEach(cleanup); + +describe("WrappedEmailControl", () => { + it("builds counters from the ledger recipients map, including not sent", async () => { + render(); + act(() => publish(fixture())); + expect(await screen.findByRole("button", { name: "Not sent 1" })).toBeTruthy(); + expect(screen.getByRole("button", { name: "Sent 2" })).toBeTruthy(); + expect(screen.getByRole("button", { name: "Skipped 2" })).toBeTruthy(); + expect(screen.getByRole("button", { name: "Failed 1" })).toBeTruthy(); + expect(screen.getByRole("button", { name: "Uncertain 0" })).toBeTruthy(); + + fireEvent.click(screen.getByRole("button", { name: "Not sent 1" })); + expect(screen.getByRole("heading", { name: "Not sent UIDs" })).toBeTruthy(); + expect(screen.getByText("f")).toBeTruthy(); + }); + + it("shows skip reasons and errors in the UID dialog", async () => { + render(); + act(() => publish(fixture())); + await screen.findByRole("button", { name: "Not sent 1" }); + fireEvent.click(screen.getByRole("button", { name: "Skipped 2" })); + expect(screen.getByText("c")).toBeTruthy(); + expect(screen.getByText("No Wrapped doc")).toBeTruthy(); + expect(screen.getByText("Opted out")).toBeTruthy(); + + fireEvent.click(screen.getByRole("button", { name: "Close" })); + fireEvent.click(screen.getByRole("button", { name: "Failed 1" })); + expect(screen.getByText("Mailbox full")).toBeTruthy(); + }); + + it("asks for confirmation with the recipient count before starting", async () => { + render(); + act(() => publish(null)); + fireEvent.click(screen.getByRole("button", { name: "Send Wrapped emails" })); + expect(countWrappedEmailRecipients).toHaveBeenCalledExactlyOnceWith("HackCamp2099"); + expect(screen.getByRole("heading", { name: "Send Wrapped emails?" })).toBeTruthy(); + expect( + await screen.findByText( + "This will email up to 42 checked-in hackers not yet emailed. Hackers without a Wrapped or who opted out are skipped.", + ), + ).toBeTruthy(); + expect(screen.getByText(/pnpm wrapped write/)).toBeTruthy(); + expect(startWrappedEmailDelivery).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole("button", { name: "Send emails" })); + await waitFor(() => + expect(startWrappedEmailDelivery).toHaveBeenCalledExactlyOnceWith("HackCamp2099"), + ); + }); + + it("reloads recipient uids once when a run finishes", async () => { + render(); + await waitFor(() => expect(loadWrappedEmailRecipientUids).toHaveBeenCalledOnce()); + act(() => publish(fixture())); + act(() => publish(fixture({ processed: 6 }))); + expect(loadWrappedEmailRecipientUids).toHaveBeenCalledOnce(); + + vi.mocked(loadWrappedEmailRecipientUids).mockResolvedValue(["a", "b", "c", "d", "e", "f", "g"]); + act(() => publish(fixture({ status: "completed-with-errors", processed: 6 }))); + await waitFor(() => expect(loadWrappedEmailRecipientUids).toHaveBeenCalledTimes(2)); + expect(await screen.findByRole("button", { name: "Not sent 2" })).toBeTruthy(); + act(() => publish(fixture({ status: "completed-with-errors", processed: 6 }))); + expect(loadWrappedEmailRecipientUids).toHaveBeenCalledTimes(2); + }); + + it("does not reload on the first snapshot of an already finished run", async () => { + render(); + act(() => publish(fixture({ status: "completed" }))); + await screen.findByRole("button", { name: "Not sent 1" }); + expect(loadWrappedEmailRecipientUids).toHaveBeenCalledOnce(); + }); + + it("is disabled until Wrapped is released and has a banner, and while editing", () => { + vi.mocked(loadWrappedEmailRecipientUids).mockReturnValue(new Promise(() => {})); + const view = render(); + act(() => publish(null)); + expect(sendButton().disabled).toBe(true); + expect(screen.getByText("Release Hacker Wrapped before sending emails.")).toBeTruthy(); + + view.rerender(); + expect(sendButton().disabled).toBe(true); + expect(screen.getByText("Upload a Wrapped banner before sending emails.")).toBeTruthy(); + + view.rerender(); + expect(sendButton().disabled).toBe(true); + expect(screen.getByText("Save or cancel your settings changes before sending.")).toBeTruthy(); + + view.rerender(); + expect(sendButton().disabled).toBe(false); + }); +}); diff --git a/src/components/features/settings/wrapped-email-control.tsx b/src/components/features/settings/wrapped-email-control.tsx new file mode 100644 index 0000000..c3ef6e3 --- /dev/null +++ b/src/components/features/settings/wrapped-email-control.tsx @@ -0,0 +1,185 @@ +import { + type EmailDeliveryBucket, + EmailDeliveryControl, + type EmailDeliveryCopy, +} from "@/components/features/settings/email-delivery-control"; +import type { WrappedEmailLedger, WrappedEmailRecipient } from "@/lib/firebase/types"; +import { + type WrappedSettings, + countWrappedEmailRecipients, + loadWrappedEmailRecipientUids, + startWrappedEmailDelivery, + subscribeToWrappedEmailLedger, +} from "@/services/wrapped-email"; +import { useEffect, useRef, useState } from "react"; + +const FINISHED: WrappedEmailLedger["status"][] = ["completed", "completed-with-errors", "failed"]; + +const SKIP_REASONS: Record, string> = { + "no-wrapped-doc": "No Wrapped doc", + "opted-out": "Opted out", +}; + +const copyFor = (hackathonId: string): EmailDeliveryCopy => ({ + idleLabel: "Send Wrapped emails", + busyLabel: "Sending Wrapped emails…", + retryLabel: "Retry remaining emails", + idleStatus: "Wrapped docs and the banner must be ready. Sends to checked-in hackers.", + loadingStatus: "Loading Wrapped email status…", + preparingStatus: "Preparing recipients…", + sendingStatus: (processed, total) => + `Sending Wrapped emails: ${processed} of ${total} processed.`, + completedStatus: "Wrapped email delivery complete.", + confirmTitle: "Send Wrapped emails?", + countingSummary: "Counting checked-in hackers…", + countErrorSummary: "Could not count checked-in hackers.", + emptySummary: + "No hackers are marked accepted, attending, and checked in, so there is nobody to email.", + recipientSummary: (count) => + `This will email up to ${count} checked-in hacker${ + count === 1 ? "" : "s" + } not yet emailed. Hackers without a Wrapped or who opted out are skipped.`, + beforeYouSend: ( + <> + Make sure every hacker's Wrapped doc has already been written (run{" "} + pnpm wrapped write in portal-v2) and the banner is + uploaded. Hackers without a Wrapped doc are skipped. + + ), + countErrorFallback: "Could not count Wrapped email recipients", + startedToast: `Wrapped emails started for ${hackathonId}`, + alreadyRunningToast: "Wrapped emails are already running", + startErrorFallback: "Could not start Wrapped emails", +}); + +export function WrappedEmailControl({ + hackathonId, + settings, + disabled = false, +}: { + hackathonId: string; + /** Saved Hackathons/{id}.wrapped; sending requires a release and a banner. */ + settings: WrappedSettings; + /** True while a settings form on the page is being edited or saved. */ + disabled?: boolean; +}) { + const [ledger, setLedger] = useState(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [recipientUids, setRecipientUids] = useState(null); + const [recipientsError, setRecipientsError] = useState(null); + const [reloadRecipients, setReloadRecipients] = useState(0); + // undefined until the first snapshot, so the mount load is not repeated for a finished run. + const previousRun = useRef(undefined); + + useEffect(() => { + setLedger(null); + setLoading(true); + setError(null); + previousRun.current = undefined; + return subscribeToWrappedEmailLedger( + hackathonId, + (next) => { + const run = next ? `${next.runId}:${next.status}` : null; + if ( + previousRun.current !== undefined && + previousRun.current !== run && + next && + FINISHED.includes(next.status) + ) { + setReloadRecipients((count) => count + 1); + } + previousRun.current = run; + setLedger(next); + setLoading(false); + setError(null); + }, + (failure) => { + setError(`Could not load Wrapped email status: ${failure.message}`); + setLoading(false); + }, + ); + }, [hackathonId]); + + // Recipients are read once per mount and after each finished run instead of live. + // biome-ignore lint/correctness/useExhaustiveDependencies: reloadRecipients only triggers a reload + useEffect(() => { + let active = true; + setRecipientsError(null); + loadWrappedEmailRecipientUids(hackathonId) + .then((uids) => { + if (active) setRecipientUids(uids); + }) + .catch((failure) => { + if (active) { + setRecipientsError( + `Could not load checked-in hackers: ${ + failure instanceof Error ? failure.message : String(failure) + }`, + ); + } + }); + return () => { + active = false; + }; + }, [hackathonId, reloadRecipients]); + + const recipients = Object.entries(ledger?.recipients ?? {}); + const bucketFor = ( + key: string, + label: string, + status: WrappedEmailRecipient["s"], + detail?: (recipient: WrappedEmailRecipient) => string | undefined, + ): EmailDeliveryBucket => { + const matching = recipients.filter(([, recipient]) => recipient.s === status); + const details: Record = {}; + for (const [uid, recipient] of matching) { + const text = detail?.(recipient); + if (text) details[uid] = text; + } + return { key, label, uids: matching.map(([uid]) => uid).sort(), details }; + }; + const buckets = [ + bucketFor("sent", "Sent", "sent"), + bucketFor("skipped", "Skipped", "skipped", (recipient) => + recipient.r ? SKIP_REASONS[recipient.r] : recipient.e, + ), + bucketFor("failed", "Failed", "failed", (recipient) => recipient.e), + bucketFor("uncertain", "Uncertain", "uncertain", (recipient) => recipient.e), + ]; + if (recipientUids !== null) { + const recorded = new Set(recipients.map(([uid]) => uid)); + buckets.push({ + key: "notSent", + label: "Not sent", + uids: recipientUids.filter((uid) => !recorded.has(uid)).sort(), + }); + } + + let disabledReason: string | null = null; + if (disabled) disabledReason = "Save or cancel your settings changes before sending."; + else if (settings.isReady !== true) + disabledReason = "Release Hacker Wrapped before sending emails."; + else if (!settings.bannerUrl) disabledReason = "Upload a Wrapped banner before sending emails."; + + return ( + countWrappedEmailRecipients(hackathonId)} + start={() => startWrappedEmailDelivery(hackathonId)} + copy={copyFor(hackathonId)} + disabled={disabledReason !== null} + disabledReason={disabledReason} + /> + ); +} diff --git a/src/components/features/settings/wrapped-settings.test.tsx b/src/components/features/settings/wrapped-settings.test.tsx new file mode 100644 index 0000000..cc1b78b --- /dev/null +++ b/src/components/features/settings/wrapped-settings.test.tsx @@ -0,0 +1,172 @@ +import { uploadWrappedBanner } from "@/lib/firebase/storage"; +import { + type WrappedSettings as WrappedSettingsData, + subscribeToWrappedSettings, + updateWrappedSettings, +} from "@/services/wrapped-email"; +import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import type { Timestamp } from "firebase/firestore"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { WrappedSettings } from "./wrapped-settings"; + +// No Firebase client, Storage, or Firestore writes are loaded by this test. +vi.mock("@/services/wrapped-email", () => ({ + getDefaultWrappedUrl: (id: string) => `https://portal.example.invalid/${id}/wrapped`, + subscribeToWrappedSettings: vi.fn(), + updateWrappedSettings: vi.fn(), +})); +vi.mock("@/lib/firebase/storage", () => ({ uploadWrappedBanner: vi.fn() })); +vi.mock("./wrapped-email-control", () => ({ + WrappedEmailControl: ({ disabled }: { disabled?: boolean }) => ( +

{disabled ? "email control disabled" : "email control enabled"}

+ ), +})); +vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } })); + +let publish: (settings: WrappedSettingsData) => void; +const saved = { isReady: false, bannerUrl: "https://example.invalid/old.png" }; +const released = () => screen.getByRole("switch", { name: "Released" }); +const timestamp = (local: string) => ({ toDate: () => new Date(local) }) as Timestamp; + +beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(subscribeToWrappedSettings).mockImplementation((_id, onChange) => { + publish = onChange; + return vi.fn(); + }); + vi.mocked(updateWrappedSettings).mockResolvedValue(undefined); + vi.mocked(uploadWrappedBanner).mockResolvedValue("https://example.invalid/new.png"); +}); +afterEach(cleanup); + +const renderLoaded = (settings: WrappedSettingsData = saved) => { + const view = render(); + act(() => publish(settings)); + return view; +}; + +describe("WrappedSettings", () => { + it("saves only the changed link override", async () => { + renderLoaded(); + fireEvent.click(screen.getByRole("button", { name: "Edit" })); + fireEvent.change(screen.getByLabelText("Wrapped Link Override"), { + target: { value: " https://example.invalid/wrapped " }, + }); + fireEvent.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => + expect(updateWrappedSettings).toHaveBeenCalledExactlyOnceWith("HackCamp2099", { + url: "https://example.invalid/wrapped", + }), + ); + expect(uploadWrappedBanner).not.toHaveBeenCalled(); + }); + + it("removes a cleared link override", async () => { + renderLoaded({ ...saved, url: "https://example.invalid/wrapped" }); + fireEvent.click(screen.getByRole("button", { name: "Edit" })); + fireEvent.change(screen.getByLabelText("Wrapped Link Override"), { target: { value: "" } }); + fireEvent.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => + expect(updateWrappedSettings).toHaveBeenCalledExactlyOnceWith("HackCamp2099", { url: null }), + ); + }); + + it("confirms before releasing Wrapped to hackers", async () => { + renderLoaded(); + expect((released() as HTMLButtonElement).disabled).toBe(true); + fireEvent.click(screen.getByRole("button", { name: "Edit" })); + + fireEvent.click(released()); + expect(screen.getByRole("heading", { name: "Release Hacker Wrapped?" })).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Cancel" })); + expect(released().getAttribute("aria-checked")).toBe("false"); + + fireEvent.click(released()); + fireEvent.click(screen.getByRole("button", { name: "Release" })); + expect(released().getAttribute("aria-checked")).toBe("true"); + expect(updateWrappedSettings).not.toHaveBeenCalled(); + + fireEvent.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => + expect(updateWrappedSettings).toHaveBeenCalledExactlyOnceWith("HackCamp2099", { + isReady: true, + }), + ); + }); + + it("turns Wrapped off without confirmation", async () => { + renderLoaded({ ...saved, isReady: true }); + fireEvent.click(screen.getByRole("button", { name: "Edit" })); + fireEvent.click(released()); + expect(screen.queryByRole("heading", { name: "Release Hacker Wrapped?" })).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => + expect(updateWrappedSettings).toHaveBeenCalledExactlyOnceWith("HackCamp2099", { + isReady: false, + }), + ); + }); + + it("uploads a new banner on save and stores only its url", async () => { + renderLoaded(); + fireEvent.click(screen.getByRole("button", { name: "Edit" })); + const banner = new File(["png"], "banner.png", { type: "image/png" }); + fireEvent.change(screen.getByLabelText("Email Banner"), { target: { files: [banner] } }); + expect(uploadWrappedBanner).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => + expect(updateWrappedSettings).toHaveBeenCalledExactlyOnceWith("HackCamp2099", { + bannerUrl: "https://example.invalid/new.png", + }), + ); + expect(uploadWrappedBanner).toHaveBeenCalledExactlyOnceWith("HackCamp2099", banner); + }); + + it("rejects banners that are not PNG or JPEG", () => { + renderLoaded(); + fireEvent.click(screen.getByRole("button", { name: "Edit" })); + const gif = new File(["gif"], "banner.gif", { type: "image/gif" }); + fireEvent.change(screen.getByLabelText("Email Banner"), { target: { files: [gif] } }); + expect(screen.getByText("The banner must be a PNG or JPEG image.")).toBeTruthy(); + }); + + it("saves a changed check-in time as a Date and clears it when blanked", async () => { + renderLoaded({ ...saved, checkInOpensAt: timestamp("2099-01-10T08:00") }); + expect((screen.getByLabelText("Check-in Opens") as HTMLInputElement).value).toBe( + "2099-01-10T08:00", + ); + fireEvent.click(screen.getByRole("button", { name: "Edit" })); + fireEvent.change(screen.getByLabelText("Check-in Opens"), { + target: { value: "2099-01-10T07:30" }, + }); + fireEvent.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => + expect(updateWrappedSettings).toHaveBeenCalledExactlyOnceWith("HackCamp2099", { + checkInOpensAt: new Date("2099-01-10T07:30"), + }), + ); + }); + + it("clears a blanked check-in time", async () => { + renderLoaded({ ...saved, checkInOpensAt: timestamp("2099-01-10T08:00") }); + fireEvent.click(screen.getByRole("button", { name: "Edit" })); + fireEvent.change(screen.getByLabelText("Check-in Opens"), { target: { value: "" } }); + fireEvent.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => + expect(updateWrappedSettings).toHaveBeenCalledExactlyOnceWith("HackCamp2099", { + checkInOpensAt: null, + }), + ); + }); + + it("disables sending while this section or the main form is being edited", () => { + const view = renderLoaded(); + expect(screen.getByText("email control enabled")).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Edit" })); + expect(screen.getByText("email control disabled")).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Cancel" })); + expect(screen.getByText("email control enabled")).toBeTruthy(); + view.rerender(); + expect(screen.getByText("email control disabled")).toBeTruthy(); + }); +}); diff --git a/src/components/features/settings/wrapped-settings.tsx b/src/components/features/settings/wrapped-settings.tsx new file mode 100644 index 0000000..b0f62e5 --- /dev/null +++ b/src/components/features/settings/wrapped-settings.tsx @@ -0,0 +1,326 @@ +import { WrappedEmailControl } from "@/components/features/settings/wrapped-email-control"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/components/ui/alert-dialog"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Switch } from "@/components/ui/switch"; +import { uploadWrappedBanner } from "@/lib/firebase/storage"; +import { + type WrappedSettings as WrappedSettingsData, + getDefaultWrappedUrl, + subscribeToWrappedSettings, + updateWrappedSettings, +} from "@/services/wrapped-email"; +import { format, parseISO } from "date-fns"; +import type { Timestamp } from "firebase/firestore"; +import { ImageIcon, Pencil, Save, X } from "lucide-react"; +import { useEffect, useState } from "react"; +import { toast } from "sonner"; + +const BANNER_TYPES = ["image/png", "image/jpeg"]; + +const TIME_FIELDS = [ + { + key: "checkInOpensAt", + label: "Check-in Opens", + description: "Optional. Early Bird measures from the earliest check-in when blank.", + }, +] as const; + +type TimeField = (typeof TIME_FIELDS)[number]["key"]; + +/** Timestamp → datetime-local input value, in the browser's time zone. */ +const toDateTimeLocal = (timestamp?: Timestamp) => + timestamp ? format(timestamp.toDate(), "yyyy-MM-dd'T'HH:mm") : ""; + +const toTimeDraft = (settings: WrappedSettingsData | null) => + Object.fromEntries( + TIME_FIELDS.map(({ key }) => [key, toDateTimeLocal(settings?.[key])]), + ) as Record; + +/** + * Hacker Wrapped release, check-in time, banner, and email settings stored on Hackathons/{id}.wrapped. + * Saved independently of the InternalWebsites/Portal settings form. + */ +export function WrappedSettings({ + hackathonId, + formBusy = false, +}: { + hackathonId: string; + /** True while the main settings form is being edited or saved. */ + formBusy?: boolean; +}) { + const [settings, setSettings] = useState(null); + const [loadError, setLoadError] = useState(null); + const [isEditing, setIsEditing] = useState(false); + const [isSaving, setIsSaving] = useState(false); + const [isReady, setIsReady] = useState(false); + const [url, setUrl] = useState(""); + const [times, setTimes] = useState>(() => toTimeDraft(null)); + const [bannerFile, setBannerFile] = useState(null); + const [bannerPreview, setBannerPreview] = useState(null); + const [bannerError, setBannerError] = useState(null); + const [releaseConfirmOpen, setReleaseConfirmOpen] = useState(false); + + useEffect( + () => + subscribeToWrappedSettings( + hackathonId, + (next) => { + setSettings(next); + setLoadError(null); + }, + (failure) => setLoadError(`Could not load Wrapped settings: ${failure.message}`), + ), + [hackathonId], + ); + + const defaultUrl = getDefaultWrappedUrl(hackathonId); + + const resetDraft = () => { + setIsReady(settings?.isReady === true); + setUrl(settings?.url ?? ""); + setTimes(toTimeDraft(settings)); + setBannerFile(null); + setBannerPreview(null); + setBannerError(null); + }; + + const handleEdit = () => { + resetDraft(); + setIsEditing(true); + }; + + const handleCancel = () => { + resetDraft(); + setIsEditing(false); + }; + + const handleReleaseChange = (checked: boolean) => { + if (checked) setReleaseConfirmOpen(true); + else setIsReady(false); + }; + + const handleBannerSelect = (e: React.ChangeEvent) => { + const file = e.target.files?.[0]; + if (!file) return; + if (!BANNER_TYPES.includes(file.type)) { + setBannerError("The banner must be a PNG or JPEG image."); + return; + } + setBannerError(null); + setBannerFile(file); + const reader = new FileReader(); + reader.onload = (event) => setBannerPreview(event.target?.result as string); + reader.readAsDataURL(file); + }; + + const handleSave = async () => { + if (!settings || isSaving) return; + const trimmedUrl = url.trim(); + if (trimmedUrl && !/^https:\/\/\S+$/.test(trimmedUrl)) { + toast.error("The Wrapped link must start with https://"); + return; + } + + setIsSaving(true); + try { + const changes: Parameters[1] = {}; + if (isReady !== (settings.isReady === true)) changes.isReady = isReady; + if (trimmedUrl !== (settings.url ?? "")) changes.url = trimmedUrl || null; + for (const { key } of TIME_FIELDS) { + if (times[key] !== toDateTimeLocal(settings[key])) { + changes[key] = times[key] ? parseISO(times[key]) : null; + } + } + if (bannerFile) { + const bannerUrl = await uploadWrappedBanner(hackathonId, bannerFile); + if (!bannerUrl) { + toast.error("Failed to upload the Wrapped banner"); + return; + } + changes.bannerUrl = bannerUrl; + } + await updateWrappedSettings(hackathonId, changes); + setIsEditing(false); + setBannerFile(null); + setBannerPreview(null); + toast.success(`${hackathonId} Wrapped settings updated successfully`); + } catch (error) { + console.error("Error saving Wrapped settings:", error); + toast.error("Failed to save Wrapped settings"); + } finally { + setIsSaving(false); + } + }; + + const released = isEditing ? isReady : settings?.isReady === true; + const preview = bannerPreview ?? settings?.bannerUrl ?? null; + + return ( +
+
+
+

Hacker Wrapped

+

Saved separately from the form

+
+ {settings && ( +
+ {isEditing ? ( + <> + + + + ) : ( + + )} +
+ )} +
+
+ {loadError ? ( +

{loadError}

+ ) : !settings ? ( +

Loading Wrapped settings...

+ ) : ( + <> +
+
+ +

+ Shows Hacker Wrapped to hackers in the portal. +

+
+ +
+ {TIME_FIELDS.map(({ key, label, description }) => ( +
+ + setTimes({ ...times, [key]: e.target.value })} + disabled={!isEditing || isSaving} + /> +

{description}

+
+ ))} +
+ +
+ {preview ? ( + Wrapped email banner preview + ) : ( +
+
+ )} +
+ +

PNG or JPEG. Uploaded on save.

+ {bannerError &&

{bannerError}

} + {settings.bannerUrl ? ( + + {settings.bannerUrl} + + ) : ( +

No banner uploaded.

+ )} +
+
+
+
+ + setUrl(e.target.value)} + disabled={!isEditing || isSaving} + placeholder={defaultUrl} + /> +

+ Leave blank to link hackers to {defaultUrl}. +

+
+ + + )} +
+ + + + Release Hacker Wrapped? + + Once saved, hackers can see their Wrapped in the portal. Make sure every Wrapped doc + has been written first. + + + + Cancel + setIsReady(true)}>Release + + + +
+ ); +} diff --git a/src/hooks/use-wallet-email-data.ts b/src/hooks/use-wallet-email-data.ts new file mode 100644 index 0000000..1e5a4df --- /dev/null +++ b/src/hooks/use-wallet-email-data.ts @@ -0,0 +1,78 @@ +import type { WalletEmailDelivery, WalletEmailSend } from "@/lib/firebase/types"; +import { + subscribeToWalletEmailDelivery, + subscribeToWalletEmailRecipients, + subscribeToWalletEmailSends, +} from "@/services/wallet-email"; +import { useEffect, useState } from "react"; + +export interface WalletEmailData { + delivery: WalletEmailDelivery | null; + loading: boolean; + error: string | null; + sends: WalletEmailSend[] | null; + sendsError: string | null; + recipientUids: string[] | null; + recipientsError: string | null; +} + +/** + * Shares the wallet email delivery, send, and recipient subscriptions between the + * wallet settings section and the email control so only one listener set is opened. + */ +export function useWalletEmailData(hackathonId: string): WalletEmailData { + const [delivery, setDelivery] = useState(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [sends, setSends] = useState(null); + const [sendsError, setSendsError] = useState(null); + const [recipientUids, setRecipientUids] = useState(null); + const [recipientsError, setRecipientsError] = useState(null); + + useEffect(() => { + setDelivery(null); + setLoading(true); + setError(null); + setSends(null); + setRecipientUids(null); + setSendsError(null); + setRecipientsError(null); + + const unsubscribe = subscribeToWalletEmailDelivery( + hackathonId, + (next) => { + setDelivery(next); + setLoading(false); + setError(null); + }, + (failure) => { + setError(`Could not load wallet email status: ${failure.message}`); + setLoading(false); + }, + ); + 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]); + + return { delivery, loading, error, sends, sendsError, recipientUids, recipientsError }; +} diff --git a/src/lib/firebase/storage.ts b/src/lib/firebase/storage.ts index 35426a9..f1b4349 100644 --- a/src/lib/firebase/storage.ts +++ b/src/lib/firebase/storage.ts @@ -112,6 +112,27 @@ export const uploadSponsorImage = async (hackathon: string, sponsorId: string, f } }; +/** + * Uploads the Hacker Wrapped email banner, replacing any previous one + * @param hackathonId - The hackathon the banner belongs to + * @param file - A PNG or JPEG image + * @returns a downloadable url of the banner just uploaded, or null on failure + */ +export const uploadWrappedBanner = async (hackathonId: string, file: File) => { + if (file.type !== "image/png" && file.type !== "image/jpeg") { + console.error("Wrapped banner must be a PNG or JPEG", hackathonId, file.type); + return null; + } + try { + const imageRef = ref(storage, `wrapped/${hackathonId}/banner`); // we LIKE overwrites + await uploadBytes(imageRef, file, { contentType: file.type }); + return await getDownloadURL(imageRef); + } catch (error) { + console.error("Error uploading Wrapped banner", hackathonId, error); + return null; + } +}; + export const deleteSponsorImage = async (hackathon: string, sponsorId: string) => { try { const imageRef = ref(storage, `sponsor/${hackathon}/${sponsorId}`); diff --git a/src/lib/firebase/types.ts b/src/lib/firebase/types.ts index 386a462..8ca179b 100644 --- a/src/lib/firebase/types.ts +++ b/src/lib/firebase/types.ts @@ -77,6 +77,16 @@ export interface Hackathon { test?: boolean; }; sponsorPrizes?: string[]; + /** Hacker Wrapped release settings; read by portal-v2 and Functions-new. */ + wrapped?: { + isReady?: boolean; + /** Download URL of the email banner uploaded to Storage at wrapped/{hackathon}/banner. */ + bannerUrl?: string; + /** Overrides the default {portal}/{slug}/wrapped link in the email. */ + url?: string; + /** When check-in opened; Early Bird measures from the earliest check-in without it. */ + checkInOpensAt?: Timestamp; + }; } /** @@ -712,6 +722,22 @@ export interface WalletEmailDelivery { currentProgress?: { sent: number; failed: number; skipped: number; uncertain: number }; } +export type WrappedEmailRecipientStatus = "sent" | "failed" | "skipped" | "uncertain"; + +/** Per-hacker entry in WrappedEmailLedger.recipients, keyed by uid. */ +export interface WrappedEmailRecipient { + s: WrappedEmailRecipientStatus; + /** Why a hacker was skipped. */ + r?: "no-wrapped-doc" | "opted-out"; + /** Last error message, if any. */ + e?: string; +} + +/** Stored on Hackathons/{collection}/wrappedEmail/ledger; written by Functions-new. */ +export interface WrappedEmailLedger extends WalletEmailDelivery { + recipients?: Record; +} + export interface HackathonConfig { _id?: string; applicationDeadline: HackathonConfigMap; @@ -736,6 +762,7 @@ export interface HackathonConfig { waiversAndForms: WaiversAndFormsMap; hackathonTheme: HackathonThemeMap; waitlistSignupDeadline: HackathonConfigMap; + walletAvailable?: HackathonBooleanMap; } /** diff --git a/src/lib/wallet-email-csv.test.ts b/src/lib/wallet-email-csv.test.ts new file mode 100644 index 0000000..785611a --- /dev/null +++ b/src/lib/wallet-email-csv.test.ts @@ -0,0 +1,56 @@ +import { Timestamp } from "firebase/firestore"; +import { describe, expect, it } from "vitest"; +import { buildWalletEmailCsv } from "./wallet-email-csv"; + +const header = "uid,email,status,attempts,lastAttemptedAt,sentAt,updatedAt,error,batchId,sentBy"; + +describe("buildWalletEmailCsv", () => { + it("includes applicants without a send record as notSent", () => { + const timestamp = Timestamp.fromDate(new Date("2026-11-01T12:00:00.000Z")); + const csv = buildWalletEmailCsv( + [ + { uid: "a", email: "a@example.com" }, + { uid: "b", email: "b@example.com" }, + ], + [ + { + uid: "a", + email: "a@example.com", + status: "sent", + attempts: 1, + sentAt: timestamp, + updatedAt: timestamp, + batchId: "batch-1", + sentBy: "admin@example.com", + }, + ], + ); + const [headerRow, first, second] = csv.split("\n"); + + expect(headerRow).toBe(header); + expect(first).toBe( + "a,a@example.com,sent,1,,2026-11-01T12:00:00.000Z,2026-11-01T12:00:00.000Z,,batch-1,admin@example.com", + ); + expect(second).toBe("b,b@example.com,notSent,0,,,,,,"); + }); + + it("escapes commas, quotes, and newlines", () => { + const csv = buildWalletEmailCsv( + [{ uid: "a", email: 'weird,"email"@example.com' }], + [ + { + uid: "a", + status: "failed", + error: 'Line one\nLine "two", comma', + batchId: "batch,1", + sentBy: 'Admin "A"', + }, + ], + ); + + expect(csv).toContain('"weird,""email""@example.com"'); + expect(csv).toContain('"Line one\nLine ""two"", comma"'); + expect(csv).toContain('"batch,1"'); + expect(csv).toContain('"Admin ""A"""'); + }); +}); diff --git a/src/lib/wallet-email-csv.ts b/src/lib/wallet-email-csv.ts new file mode 100644 index 0000000..2cf006a --- /dev/null +++ b/src/lib/wallet-email-csv.ts @@ -0,0 +1,53 @@ +import type { WalletEmailSend } from "@/lib/firebase/types"; +import type { WalletEmailRecipient } from "@/services/wallet-email"; +import type { Timestamp } from "firebase/firestore"; + +const CSV_COLUMNS = [ + "uid", + "email", + "status", + "attempts", + "lastAttemptedAt", + "sentAt", + "updatedAt", + "error", + "batchId", + "sentBy", +] as const; + +const escapeCsvField = (value: unknown): string => { + if (value === undefined || value === null) return ""; + const text = String(value); + return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text; +}; + +const formatTimestampValue = (value?: Timestamp): string => + value ? value.toDate().toISOString() : ""; + +/** + * Builds the wallet email CSV with one row per accepted and attending applicant. + * Applicants without an email send record are reported as `notSent`. + */ +export function buildWalletEmailCsv( + recipients: WalletEmailRecipient[], + sends: WalletEmailSend[], +): string { + const sendsByUid = new Map(sends.map((send) => [send.uid, send])); + const rows = recipients.map((recipient) => { + const send = sendsByUid.get(recipient.uid); + return [ + recipient.uid, + send?.email ?? recipient.email ?? "", + send?.status ?? "notSent", + send?.attempts ?? 0, + formatTimestampValue(send?.lastAttemptedAt), + formatTimestampValue(send?.sentAt), + formatTimestampValue(send?.updatedAt), + send?.error ?? "", + send?.batchId ?? "", + send?.sentBy ?? "", + ]; + }); + + return [CSV_COLUMNS, ...rows].map((row) => row.map(escapeCsvField).join(",")).join("\n"); +} diff --git a/src/services/wallet-email.ts b/src/services/wallet-email.ts index f76f1aa..d72086f 100644 --- a/src/services/wallet-email.ts +++ b/src/services/wallet-email.ts @@ -1,6 +1,14 @@ import { db } from "@/lib/firebase/client"; import type { WalletEmailDelivery, WalletEmailSend } from "@/lib/firebase/types"; -import { collection, doc, getCountFromServer, onSnapshot, query, where } from "firebase/firestore"; +import { + collection, + doc, + getCountFromServer, + getDocs, + onSnapshot, + query, + where, +} from "firebase/firestore"; import { getFunctions, httpsCallable } from "firebase/functions"; const recipientsQuery = (hackathonId: string) => @@ -55,6 +63,24 @@ export function subscribeToWalletEmailDelivery( ); } +export interface WalletEmailRecipient { + uid: string; + email?: string; +} + +export async function getWalletEmailRecipients( + hackathonId: string, +): Promise { + const snapshot = await getDocs(recipientsQuery(hackathonId)); + return snapshot.docs.map((applicant) => { + const email = applicant.data().basicInfo?.email; + return { + uid: applicant.id, + email: typeof email === "string" ? email : undefined, + }; + }); +} + export async function countWalletEmailRecipients(hackathonId: string) { const snapshot = await getCountFromServer(recipientsQuery(hackathonId)); return snapshot.data().count; diff --git a/src/services/wallet-passes.ts b/src/services/wallet-passes.ts new file mode 100644 index 0000000..622a106 --- /dev/null +++ b/src/services/wallet-passes.ts @@ -0,0 +1,52 @@ +import type { FirebaseError } from "firebase/app"; +import { getFunctions, httpsCallable } from "firebase/functions"; + +export interface GenerateAppleWalletPassesFailure { + uid: string; + error: string; +} + +export interface GenerateAppleWalletPassesResult { + generated: number; + failed: GenerateAppleWalletPassesFailure[]; +} + +interface GenerateAppleWalletPassesInput { + dbCollectionName: string; + uids: string[]; +} + +export async function generateAppleWalletPasses( + hackathonId: string, + uids: string[], +): Promise { + const generate = httpsCallable( + getFunctions(), + "generateAppleWalletPasses", + { timeout: 300000 }, + ); + + const result = await generate({ dbCollectionName: hackathonId, uids }); + return result.data; +} + +/** + * Firebase hides server details behind the generic "internal" error. Point admins + * at the likely missing deployment or signer configuration instead of the raw code. + */ +export function getWalletPassesErrorMessage(error: unknown): string { + const failure = error as Partial | null; + const code = typeof failure?.code === "string" ? failure.code : undefined; + const message = typeof failure?.message === "string" ? failure.message : ""; + + if ( + code === "not-found" || + code === "unavailable" || + (code === "internal" && (!message || message === "internal")) + ) { + return "Apple pass generation failed. Confirm generateAppleWalletPasses is deployed for this project with its Apple signer secrets, then check the Functions logs."; + } + if (message && message !== "internal") return message; + if (code) return `Apple pass generation failed (${code}).`; + return "Could not generate Apple passes"; +} diff --git a/src/services/wrapped-email.ts b/src/services/wrapped-email.ts new file mode 100644 index 0000000..915e004 --- /dev/null +++ b/src/services/wrapped-email.ts @@ -0,0 +1,105 @@ +import { db } from "@/lib/firebase/client"; +import type { Hackathon, WrappedEmailLedger } from "@/lib/firebase/types"; +import { + Timestamp, + collection, + deleteField, + doc, + getCountFromServer, + getDocs, + onSnapshot, + query, + updateDoc, + where, +} from "firebase/firestore"; +import { getFunctions, httpsCallable } from "firebase/functions"; + +export type WrappedSettings = NonNullable; + +// Must match the Functions-new recipient query. +const recipientsQuery = (hackathonId: string) => + query( + collection(db, "Hackathons", hackathonId, "Applicants"), + where("status.applicationStatus", "==", "acceptedAndAttending"), + where("dayOf.checkedIn", "==", true), + ); + +/** + * Default link to a hacker's Wrapped in the portal, e.g. HackCamp2025 → {portal}/hackcamp/wrapped + * @param hackathonId - the hackathon document ID + * @param projectId - the Firebase project ID; production uses the live portal + */ +export const getDefaultWrappedUrl = ( + hackathonId: string, + projectId: string | undefined = import.meta.env.VITE_FIREBASE_PROJECT_ID, +) => { + const origin = + projectId === "nwplus-ubc" ? "https://portal.nwplus.io" : "https://dev-nwplus-portal.web.app"; + return `${origin}/${hackathonId.replace(/\d{4}$/, "").toLowerCase()}/wrapped`; +}; + +export function subscribeToWrappedEmailLedger( + hackathonId: string, + onChange: (ledger: WrappedEmailLedger | null) => void, + onError: (error: Error) => void, +) { + return onSnapshot( + doc(db, "Hackathons", hackathonId, "wrappedEmail", "ledger"), + (snapshot) => onChange((snapshot.data() as WrappedEmailLedger | undefined) ?? null), + onError, + ); +} + +/** One-time read; the ledger already carries live per-recipient results. */ +export async function loadWrappedEmailRecipientUids(hackathonId: string) { + const snapshot = await getDocs(recipientsQuery(hackathonId)); + return snapshot.docs.map((applicant) => applicant.id); +} + +export async function countWrappedEmailRecipients(hackathonId: string) { + const snapshot = await getCountFromServer(recipientsQuery(hackathonId)); + return snapshot.data().count; +} + +export async function startWrappedEmailDelivery(hackathonId: string) { + const start = httpsCallable<{ dbCollectionName: string }, { runId: string; started: boolean }>( + getFunctions(), + "startWrappedEmailDelivery", + { timeout: 120000 }, + ); + return (await start({ dbCollectionName: hackathonId })).data; +} + +export function subscribeToWrappedSettings( + hackathonId: string, + onChange: (settings: WrappedSettings) => void, + onError: (error: Error) => void, +) { + return onSnapshot( + doc(db, "Hackathons", hackathonId), + (snapshot) => onChange((snapshot.data() as Hackathon | undefined)?.wrapped ?? {}), + onError, + ); +} + +export interface WrappedSettingsChanges { + isReady?: boolean; + bannerUrl?: string; + url?: string | null; + checkInOpensAt?: Date | null; +} + +/** + * Updates only the given wrapped.* fields on Hackathons/{id}, leaving siblings untouched + * @param changes - fields to set; null removes the field, Dates are stored as Timestamps + */ +export async function updateWrappedSettings(hackathonId: string, changes: WrappedSettingsChanges) { + const update: Record = {}; + for (const [key, value] of Object.entries(changes)) { + if (value === undefined) continue; + update[`wrapped.${key}`] = + value === null ? deleteField() : value instanceof Date ? Timestamp.fromDate(value) : value; + } + if (Object.keys(update).length === 0) return; + await updateDoc(doc(db, "Hackathons", hackathonId), update); +}