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; + }) => ( + + + + {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 && ( +
+ +
+ )} + + +
+ + +
+ + + + + + 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/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/types.ts b/src/lib/firebase/types.ts index 51bd946..8ca179b 100644 --- a/src/lib/firebase/types.ts +++ b/src/lib/firebase/types.ts @@ -762,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"; +}