From aa5e020831712a9ba0f3f8eb9f8ca4f79254916e Mon Sep 17 00:00:00 2001 From: SURYANSH-RAI Date: Mon, 19 Oct 2026 02:42:58 +0530 Subject: [PATCH 01/39] Track invitations, claims and revoked access per event (R12 part 1) - Migration 0006: event_participants gains invited_at, invite_count, invite_error, claimed_at and revoked_at; existing profiles count as claimed - Revoked attendees lose event sign-in (isParticipant), page and action access (hasEventAccess, so existing sessions too), matching (participantIds) and every results path (ELIGIBLE_CANDIDATE). Re-importing the roster does not silently restore them - The first signed-in visit to the event records the claim time - sendInvitations e-mails everyone never invited, or one attendee as a resend (at most every 10 minutes, never after claiming or removal); each attempt is recorded, failures with their reason - setAttendeeAccess removes or restores access - Invitation e-mail template and NotificationPort.invitation - Analytics count invited, claimed and removed attendees separately --- .../src/application/ports/event-repository.ts | 10 ++- .../web/src/application/ports/notification.ts | 1 + .../use-cases/manage-invitations.ts | 56 ++++++++++++ apps/web/src/domain/participant/invitation.ts | 32 +++++++ .../notifications/realtime.notifier.ts | 6 +- .../src/infrastructure/postgres/event.repo.ts | 28 +++++- .../postgres/participant.repo.ts | 6 +- apps/web/src/lib/auth.ts | 1 + packages/db/migrations/0006_invitations.sql | 18 ++++ packages/db/src/repositories/events.ts | 76 +++++++++++++++- packages/email/src/index.ts | 1 + .../email/src/templates/invitation-email.ts | 34 +++++++ tests/integration/invitations.test.ts | 90 +++++++++++++++++++ tests/unit/invitations.test.ts | 84 +++++++++++++++++ 14 files changed, 434 insertions(+), 9 deletions(-) create mode 100644 apps/web/src/application/use-cases/manage-invitations.ts create mode 100644 apps/web/src/domain/participant/invitation.ts create mode 100644 packages/db/migrations/0006_invitations.sql create mode 100644 packages/email/src/templates/invitation-email.ts create mode 100644 tests/integration/invitations.test.ts create mode 100644 tests/unit/invitations.test.ts diff --git a/apps/web/src/application/ports/event-repository.ts b/apps/web/src/application/ports/event-repository.ts index c902136..e13dfb4 100644 --- a/apps/web/src/application/ports/event-repository.ts +++ b/apps/web/src/application/ports/event-repository.ts @@ -38,5 +38,13 @@ export interface EventRepository { attachRoster(eventId: string, attendeeIds: string[]): Promise; participantIds(eventId: string): Promise; importRoster(eventId: string, records: RosterAttendeeInput[]): Promise<{ upserted: number; attached: number }>; - analytics(eventId: string): Promise<{ roster: number; profiles: number; matches: number; pendingIntros: number; acceptedIntros: number }>; + analytics(eventId: string): Promise<{ + roster: number; invited: number; claimed: number; profiles: number; removed: number; + matches: number; pendingIntros: number; acceptedIntros: number; + }>; + invitationTargets(eventId: string, attendeeId: string | null, resendAfterMinutes: number): Promise>; + recordInvitation(eventId: string, attendeeId: string, error: string | null): Promise; + markClaimed(eventId: string, attendeeId: string): Promise; + setRevoked(eventId: string, attendeeId: string, revoked: boolean): Promise; + rosterState(eventId: string, attendeeId: string): Promise<"active" | "revoked" | null>; } diff --git a/apps/web/src/application/ports/notification.ts b/apps/web/src/application/ports/notification.ts index bd84477..7db58ee 100644 --- a/apps/web/src/application/ports/notification.ts +++ b/apps/web/src/application/ports/notification.ts @@ -1,4 +1,5 @@ export interface NotificationPort { + invitation(input: { email: string; name: string | null; eventName: string; organizationName: string; eventUrl: string }): Promise; introRequested(input: { recipientEmail: string; recipientName: string; requesterName: string; eventName: string; introId: string }): Promise; introResponded(input: { recipientEmail: string; recipientName: string; requesterName: string; eventName: string; accepted: boolean }): Promise; } diff --git a/apps/web/src/application/use-cases/manage-invitations.ts b/apps/web/src/application/use-cases/manage-invitations.ts new file mode 100644 index 0000000..56b67c9 --- /dev/null +++ b/apps/web/src/application/use-cases/manage-invitations.ts @@ -0,0 +1,56 @@ +import { RESEND_AFTER_MINUTES } from "../../domain/participant/invitation"; +import type { EventRepository } from "../ports/event-repository"; +import type { NotificationPort } from "../ports/notification"; + +export interface InvitationResult { + sent: number; + failed: number; +} + +/** + * E-mails invitations: to one attendee (a resend), or to everyone on the + * roster never invited. Each attempt is recorded, so a failed delivery shows + * up on the roster instead of disappearing. + */ +export async function sendInvitations( + input: { eventId: string; eventName: string; organizationName: string; eventUrl: string; attendeeId?: string }, + dependencies: { events: EventRepository; notifications: NotificationPort } +): Promise { + const targets = await dependencies.events.invitationTargets(input.eventId, input.attendeeId ?? null, RESEND_AFTER_MINUTES); + if (input.attendeeId && !targets.length) { + throw new Error(`This attendee cannot be invited right now: they may have signed in already, been removed, or been invited in the last ${RESEND_AFTER_MINUTES} minutes.`); + } + const result: InvitationResult = { sent: 0, failed: 0 }; + for (const target of targets) { + try { + await dependencies.notifications.invitation({ + email: target.email, + name: target.name, + eventName: input.eventName, + organizationName: input.organizationName, + eventUrl: input.eventUrl, + }); + await dependencies.events.recordInvitation(input.eventId, target.attendee_id, null); + result.sent += 1; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + await dependencies.events.recordInvitation(input.eventId, target.attendee_id, message.slice(0, 300)); + result.failed += 1; + } + } + return result; +} + +/** + * Removes or restores one attendee's access. Removal takes effect on their + * next request (existing sessions included) and drops them from matching and + * everyone's results; their history stays for the organizer. + */ +export async function setAttendeeAccess( + input: { eventId: string; attendeeId: string; revoked: boolean }, + dependencies: { events: EventRepository } +): Promise { + if (!(await dependencies.events.setRevoked(input.eventId, input.attendeeId, input.revoked))) { + throw new Error("This attendee is not on the event roster"); + } +} diff --git a/apps/web/src/domain/participant/invitation.ts b/apps/web/src/domain/participant/invitation.ts new file mode 100644 index 0000000..93509cc --- /dev/null +++ b/apps/web/src/domain/participant/invitation.ts @@ -0,0 +1,32 @@ +/** + * Where an invited attendee stands for one event, as the organizer sees it. + * Removed overrides everything; otherwise the furthest step reached wins. + */ +export type InvitationState = "removed" | "complete" | "claimed" | "invited" | "failed" | "not_invited"; + +/** A resend for the same attendee is refused until this much time has passed. */ +export const RESEND_AFTER_MINUTES = 10; + +export interface InvitationFacts { + revokedAt: Date | null; + profileUpdatedAt: Date | null; + claimedAt: Date | null; + invitedAt: Date | null; + inviteError: string | null; +} + +export function invitationState(facts: InvitationFacts): InvitationState { + if (facts.revokedAt) return "removed"; + if (facts.profileUpdatedAt) return "complete"; + if (facts.claimedAt) return "claimed"; + if (facts.inviteError) return "failed"; + if (facts.invitedAt) return "invited"; + return "not_invited"; +} + +/** Whether the organizer can send this attendee an invitation now. */ +export function canInvite(facts: InvitationFacts, now = Date.now()): boolean { + const state = invitationState(facts); + if (state === "removed" || state === "claimed" || state === "complete") return false; + return !facts.invitedAt || now - facts.invitedAt.getTime() >= RESEND_AFTER_MINUTES * 60_000; +} diff --git a/apps/web/src/infrastructure/notifications/realtime.notifier.ts b/apps/web/src/infrastructure/notifications/realtime.notifier.ts index ab37a8f..b5ca8fa 100644 --- a/apps/web/src/infrastructure/notifications/realtime.notifier.ts +++ b/apps/web/src/infrastructure/notifications/realtime.notifier.ts @@ -1,7 +1,11 @@ -import { sendNotificationEmail } from "@match-maker/email"; +import { renderInvitationEmail, sendNotificationEmail } from "@match-maker/email"; import type { NotificationPort } from "../../application/ports/notification"; export class RealtimeNotifier implements NotificationPort { + async invitation(input: { email: string; name: string | null; eventName: string; organizationName: string; eventUrl: string }): Promise { + await sendNotificationEmail({ to: input.email, ...renderInvitationEmail(input) }); + } + async introRequested(input: { recipientEmail: string; recipientName: string; requesterName: string; eventName: string; introId: string }): Promise { const subject = `${input.requesterName} would like to meet at ${input.eventName}`; const text = `Hi ${input.recipientName},\n\n${input.requesterName} requested an introduction at ${input.eventName}. Sign in to Mr. Bridge to respond.`; diff --git a/apps/web/src/infrastructure/postgres/event.repo.ts b/apps/web/src/infrastructure/postgres/event.repo.ts index 821ebbf..cc1f2a7 100644 --- a/apps/web/src/infrastructure/postgres/event.repo.ts +++ b/apps/web/src/infrastructure/postgres/event.repo.ts @@ -37,6 +37,21 @@ export class PostgresEventRepository implements EventRepository { participantIds(eventId: string) { return events.participantIds(eventId); } + invitationTargets(eventId: string, attendeeId: string | null, resendAfterMinutes: number) { + return events.invitationTargets(eventId, attendeeId, resendAfterMinutes); + } + recordInvitation(eventId: string, attendeeId: string, error: string | null) { + return events.recordInvitation(eventId, attendeeId, error); + } + markClaimed(eventId: string, attendeeId: string) { + return events.markClaimed(eventId, attendeeId); + } + setRevoked(eventId: string, attendeeId: string, revoked: boolean) { + return events.setRevoked(eventId, attendeeId, revoked); + } + rosterState(eventId: string, attendeeId: string) { + return events.rosterState(eventId, attendeeId); + } async importRoster(eventId: string, records: Parameters[1]) { let upserted = 0; @@ -51,14 +66,20 @@ export class PostgresEventRepository implements EventRepository { async analytics(eventId: string) { const { rows } = await query<{ roster: string; + invited: string; + claimed: string; + removed: string; profiles: string; matches: string; pending_intros: string; accepted_intros: string; }>( `select - (select count(*) from event_participants where event_id = $1) as roster, - (select count(*) from event_participants where event_id = $1 and profile_updated_at is not null) as profiles, + (select count(*) from event_participants where event_id = $1 and revoked_at is null) as roster, + (select count(*) from event_participants where event_id = $1 and revoked_at is null and invited_at is not null) as invited, + (select count(*) from event_participants where event_id = $1 and revoked_at is null and claimed_at is not null) as claimed, + (select count(*) from event_participants where event_id = $1 and revoked_at is not null) as removed, + (select count(*) from event_participants where event_id = $1 and revoked_at is null and profile_updated_at is not null) as profiles, (select count(*) from event_matches where event_id = $1) as matches, (select count(*) from intro_requests where event_id = $1 and status = 'pending') as pending_intros, (select count(*) from intro_requests where event_id = $1 and status = 'accepted') as accepted_intros`, @@ -66,6 +87,9 @@ export class PostgresEventRepository implements EventRepository { ); return { roster: Number(rows[0]?.roster ?? 0), + invited: Number(rows[0]?.invited ?? 0), + claimed: Number(rows[0]?.claimed ?? 0), + removed: Number(rows[0]?.removed ?? 0), profiles: Number(rows[0]?.profiles ?? 0), matches: Number(rows[0]?.matches ?? 0), pendingIntros: Number(rows[0]?.pending_intros ?? 0), diff --git a/apps/web/src/infrastructure/postgres/participant.repo.ts b/apps/web/src/infrastructure/postgres/participant.repo.ts index c93ed7a..54ce014 100644 --- a/apps/web/src/infrastructure/postgres/participant.repo.ts +++ b/apps/web/src/infrastructure/postgres/participant.repo.ts @@ -39,7 +39,7 @@ const PROFILE_FROM = `from event_participants p * join), visible, named, and with a saved event profile. Every results path — * fresh retrieval, cached ids, saved matches — applies this same rule. */ -export const ELIGIBLE_CANDIDATE = `p.visible = true and a.name is not null and p.profile_updated_at is not null`; +export const ELIGIBLE_CANDIDATE = `p.visible = true and a.name is not null and p.profile_updated_at is not null and p.revoked_at is null`; export class PostgresParticipantRepository implements ParticipantRepository { async findProfile(eventId: string, attendeeId: string): Promise { @@ -118,7 +118,9 @@ export class PostgresParticipantRepository implements ParticipantRepository { async hasEventAccess(eventId: string, attendeeId: string): Promise { const { rows } = await query<{ allowed: boolean }>( - `select exists(select 1 from event_participants where event_id = $1 and attendee_id = $2) as allowed`, + `select exists( + select 1 from event_participants where event_id = $1 and attendee_id = $2 and revoked_at is null + ) as allowed`, [eventId, attendeeId] ); return rows[0]?.allowed ?? false; diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.ts index e95b9fd..0259401 100644 --- a/apps/web/src/lib/auth.ts +++ b/apps/web/src/lib/auth.ts @@ -13,6 +13,7 @@ export async function requireParticipantEvent(eventSlug: string, returnPath?: st if (!event) notFound(); const registered = await container.participants.hasEventAccess(event.id, session.attendeeId); if (!registered) notFound(); + await container.events.markClaimed(event.id, session.attendeeId); if (action && !eventAllows(event.status, action)) redirect(`/e/${eventSlug}`); return { session, event, container }; } diff --git a/packages/db/migrations/0006_invitations.sql b/packages/db/migrations/0006_invitations.sql new file mode 100644 index 0000000..b5daed9 --- /dev/null +++ b/packages/db/migrations/0006_invitations.sql @@ -0,0 +1,18 @@ +-- Invited account lifecycle per event. +-- +-- The roster row is the invitation. These columns record whether the +-- invitation e-mail went out (and why it failed), when the attendee first +-- signed in to the event (claimed), and whether the organizer removed their +-- access. A revoked row keeps its history but grants nothing: no sign-in to +-- the event, no matching, no appearance in anyone's results. + +alter table event_participants add column if not exists invited_at timestamptz; +alter table event_participants add column if not exists invite_count integer not null default 0; +alter table event_participants add column if not exists invite_error text; +alter table event_participants add column if not exists claimed_at timestamptz; +alter table event_participants add column if not exists revoked_at timestamptz; + +-- Anyone who already saved a profile has evidently claimed their invitation. +update event_participants + set claimed_at = profile_updated_at + where claimed_at is null and profile_updated_at is not null; diff --git a/packages/db/src/repositories/events.ts b/packages/db/src/repositories/events.ts index 55e88db..a2023e2 100644 --- a/packages/db/src/repositories/events.ts +++ b/packages/db/src/repositories/events.ts @@ -113,7 +113,9 @@ export async function isOrganizer(eventId: string, attendeeId: string): Promise< export async function isParticipant(eventId: string, attendeeId: string): Promise { const { rows } = await query<{ allowed: boolean }>( - `select exists(select 1 from event_participants where event_id = $1 and attendee_id = $2) as allowed`, + `select exists( + select 1 from event_participants where event_id = $1 and attendee_id = $2 and revoked_at is null + ) as allowed`, [eventId, attendeeId] ); return rows[0]?.allowed ?? false; @@ -131,7 +133,8 @@ export async function hasOrganizationAccess(organizationSlug: string, attendeeId export async function participantIds(eventId: string): Promise { const { rows } = await query<{ attendee_id: string }>( - `select attendee_id from event_participants where event_id = $1 and profile_updated_at is not null`, [eventId] + `select attendee_id from event_participants + where event_id = $1 and profile_updated_at is not null and revoked_at is null`, [eventId] ); return rows.map((row) => row.attendee_id); } @@ -155,9 +158,76 @@ export async function roster(eventId: string): Promise { + const { rows } = await query( + `select a.id as attendee_id, a.email, a.name + from event_participants p join registered_attendees a on a.id = p.attendee_id + where p.event_id = $1 and p.revoked_at is null and p.claimed_at is null and a.email is not null + and ($2::uuid is null and p.invited_at is null + or a.id = $2::uuid and (p.invited_at is null or p.invited_at < now() - make_interval(mins => $3))) + order by a.name nulls last`, + [eventId, attendeeId, resendAfterMinutes] + ); + return rows; +} + +/** Records one delivery attempt; a failure keeps the last successful send time. */ +export async function recordInvitation(eventId: string, attendeeId: string, error: string | null): Promise { + await query( + `update event_participants + set invited_at = case when $3::text is null then now() else invited_at end, + invite_count = invite_count + case when $3::text is null then 1 else 0 end, + invite_error = $3, updated_at = now() + where event_id = $1 and attendee_id = $2`, + [eventId, attendeeId, error] + ); +} + +/** The first signed-in visit to the event claims the invitation. */ +export async function markClaimed(eventId: string, attendeeId: string): Promise { + await query( + `update event_participants set claimed_at = now() + where event_id = $1 and attendee_id = $2 and claimed_at is null and revoked_at is null`, + [eventId, attendeeId] + ); +} + +/** Removes or restores an attendee's access; returns false when they are not on the roster. */ +export async function setRevoked(eventId: string, attendeeId: string, revoked: boolean): Promise { + const { rowCount } = await query( + `update event_participants + set revoked_at = case when $3 then coalesce(revoked_at, now()) else null end, updated_at = now() + where event_id = $1 and attendee_id = $2`, + [eventId, attendeeId, revoked] + ); + return (rowCount ?? 0) > 0; +} + +/** Whether an attendee is on the roster, and if so whether access was removed. */ +export async function rosterState(eventId: string, attendeeId: string): Promise<"active" | "revoked" | null> { + const { rows } = await query<{ revoked: boolean }>( + `select revoked_at is not null as revoked from event_participants where event_id = $1 and attendee_id = $2`, + [eventId, attendeeId] + ); + if (!rows[0]) return null; + return rows[0].revoked ? "revoked" : "active"; +} diff --git a/packages/email/src/index.ts b/packages/email/src/index.ts index c48847d..461b011 100644 --- a/packages/email/src/index.ts +++ b/packages/email/src/index.ts @@ -1,4 +1,5 @@ export { sendLoginEmail, sendNotificationEmail, type SendResult } from "./client"; +export { renderInvitationEmail, type InvitationEmailInput } from "./templates/invitation-email"; export { renderLoginEmail, type LoginEmailInput, diff --git a/packages/email/src/templates/invitation-email.ts b/packages/email/src/templates/invitation-email.ts new file mode 100644 index 0000000..e9f6384 --- /dev/null +++ b/packages/email/src/templates/invitation-email.ts @@ -0,0 +1,34 @@ +/** The invitation an organizer sends to everyone on an event roster. */ +export interface InvitationEmailInput { + name: string | null; + eventName: string; + organizationName: string; + /** The event page, where the attendee signs in and claims the invitation. */ + eventUrl: string; +} + +export function renderInvitationEmail(input: InvitationEmailInput): { subject: string; html: string; text: string } { + const greeting = input.name ? `Hi ${input.name},` : "Hi,"; + const subject = `You're invited to ${input.eventName} on Mr. Bridge`; + const text = [ + greeting, + "", + `${input.organizationName} added you to ${input.eventName}. Sign in with this e-mail address to claim your invitation, complete your profile, and see who you should meet.`, + "", + input.eventUrl, + "", + "If you did not expect this, you can ignore this e-mail.", + ].join("\n"); + const html = `
+

Mr. Bridge

+

${escapeHtml(greeting)}

+

${escapeHtml(input.organizationName)} added you to ${escapeHtml(input.eventName)}. Sign in with this e-mail address to claim your invitation, complete your profile, and see who you should meet.

+

Claim your invitation

+

If you did not expect this, you can ignore this e-mail.

+
`; + return { subject, html, text }; +} + +function escapeHtml(value: string): string { + return value.replace(/[&<>"']/g, (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]!); +} diff --git a/tests/integration/invitations.test.ts b/tests/integration/invitations.test.ts new file mode 100644 index 0000000..b48d3f5 --- /dev/null +++ b/tests/integration/invitations.test.ts @@ -0,0 +1,90 @@ +/** + * Invitation lifecycle against a real Postgres: who gets invited, claims, + * and what removing access takes away. Uses its own organization, event and + * attendees. Skipped when DATABASE_URL is unset. + */ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { query, closePool, attendees, events } from "@match-maker/db"; +import { migrate } from "../../packages/db/src/migrate"; +import { PostgresParticipantRepository } from "../../apps/web/src/infrastructure/postgres/participant.repo"; + +const describeDb = process.env.DATABASE_URL ? describe : describe.skip; +const ORG = "integration-invitations"; +const KEYS = ["new", "invited", "claimed", "removed", "viewer"] as const; +const emailOf = (key: string) => `invite-${key}@example.com`; + +describeDb("invitation lifecycle", () => { + const participants = new PostgresParticipantRepository(); + let eventId: string; + let ids: Record; + + beforeAll(async () => { + await migrate(); + await attendees.upsertMany(KEYS.map((key) => ({ name: `Invite ${key}`, email: emailOf(key) }))); + const found = await attendees.findIdsByEmails(KEYS.map(emailOf)); + ids = Object.fromEntries(KEYS.map((key) => [key, found.find((row) => row.email === emailOf(key))!.id])); + const { rows: [org] } = await query<{ id: string }>( + `insert into organizations (name, slug) values ('Invitations', $1) + on conflict (slug) do update set name = excluded.name returning id`, [ORG]); + const { rows: [event] } = await query<{ id: string }>( + `insert into events (organization_id, name, slug, status) values ($1, $2, $2, 'open') + on conflict (organization_id, slug) do update set status = 'open' returning id`, [org.id, ORG]); + eventId = event.id; + await query(`delete from event_participants where event_id = $1`, [eventId]); + await events.attachRoster(eventId, Object.values(ids)); + await query( + `update event_participants set profile_updated_at = now(), designation = 'Engineer', domain = 'AI', about_me = 'Builds things' + where event_id = $1 and attendee_id = any($2::uuid[])`, [eventId, [ids.removed, ids.viewer]]); + await query(`update event_participants set invited_at = now() - interval '2 minutes', invite_count = 1 where event_id = $1 and attendee_id = $2`, [eventId, ids.invited]); + await events.markClaimed(eventId, ids.claimed); + await events.setRevoked(eventId, ids.removed, true); + }); + + afterAll(async () => { + await query(`delete from organizations where slug = $1`, [ORG]); + await query(`delete from registered_attendees where email = any($1::text[])`, [KEYS.map(emailOf)]); + await closePool(); + }); + + it("invites only people never invited, never claimed and not removed", async () => { + const targets = await events.invitationTargets(eventId, null, 10); + expect(targets.map((target) => target.email).sort()).toEqual([emailOf("new"), emailOf("viewer")]); + }); + + it("throttles a resend to the same person", async () => { + expect(await events.invitationTargets(eventId, ids.invited, 10)).toEqual([]); + expect(await events.invitationTargets(eventId, ids.invited, 1)).toHaveLength(1); + expect(await events.invitationTargets(eventId, ids.claimed, 0)).toEqual([]); + }); + + it("records a failure without pretending the e-mail went out", async () => { + await events.recordInvitation(eventId, ids.new, "Resend rejected the address"); + await events.recordInvitation(eventId, ids.invited, null); + const rows = await events.roster(eventId); + const byId = new Map(rows.map((row) => [row.id, row])); + expect(byId.get(ids.new)).toMatchObject({ invited_at: null, invite_count: 0, invite_error: "Resend rejected the address" }); + expect(byId.get(ids.invited)).toMatchObject({ invite_count: 2, invite_error: null }); + }); + + it("keeps the first claim time", async () => { + const before = (await events.roster(eventId)).find((row) => row.id === ids.claimed)!.claimed_at; + await events.markClaimed(eventId, ids.claimed); + expect((await events.roster(eventId)).find((row) => row.id === ids.claimed)!.claimed_at).toEqual(before); + }); + + it("removes every kind of access from a revoked attendee", async () => { + expect(await events.isParticipant(eventId, ids.removed)).toBe(false); + expect(await participants.hasEventAccess(eventId, ids.removed)).toBe(false); + expect(await events.participantIds(eventId)).not.toContain(ids.removed); + expect(await events.rosterState(eventId, ids.removed)).toBe("revoked"); + const candidates = await participants.findCandidatesByIds(eventId, [ids.removed, ids.viewer]); + expect(candidates.map((candidate) => candidate.attendeeId)).toEqual([ids.viewer]); + }); + + it("restores access explicitly, and re-importing does not do it silently", async () => { + await events.attachRoster(eventId, [ids.removed]); + expect(await events.rosterState(eventId, ids.removed)).toBe("revoked"); + await events.setRevoked(eventId, ids.removed, false); + expect(await participants.hasEventAccess(eventId, ids.removed)).toBe(true); + }); +}); diff --git a/tests/unit/invitations.test.ts b/tests/unit/invitations.test.ts new file mode 100644 index 0000000..6eb09e5 --- /dev/null +++ b/tests/unit/invitations.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it, vi } from "vitest"; +import { canInvite, invitationState, RESEND_AFTER_MINUTES, type InvitationFacts } from "@/src/domain/participant/invitation"; +import { sendInvitations, setAttendeeAccess } from "@/src/application/use-cases/manage-invitations"; +import { renderInvitationEmail } from "@match-maker/email"; + +const NOW = Date.parse("2026-10-19T12:00:00Z"); +const facts = (overrides: Partial): InvitationFacts => ({ + revokedAt: null, profileUpdatedAt: null, claimedAt: null, invitedAt: null, inviteError: null, ...overrides, +}); +const at = (minutesAgo: number) => new Date(NOW - minutesAgo * 60_000); + +describe("invitationState", () => { + it.each([ + [facts({}), "not_invited"], + [facts({ invitedAt: at(1) }), "invited"], + [facts({ inviteError: "bounced" }), "failed"], + [facts({ invitedAt: at(5), claimedAt: at(1) }), "claimed"], + [facts({ claimedAt: at(5), profileUpdatedAt: at(1) }), "complete"], + [facts({ profileUpdatedAt: at(5), revokedAt: at(1) }), "removed"], + ] as const)("%o is %s", (input, state) => { + expect(invitationState(input)).toBe(state); + }); + + it("allows a resend only after the waiting period, and never after claiming or removal", () => { + expect(canInvite(facts({}), NOW)).toBe(true); + expect(canInvite(facts({ invitedAt: at(RESEND_AFTER_MINUTES - 1) }), NOW)).toBe(false); + expect(canInvite(facts({ invitedAt: at(RESEND_AFTER_MINUTES) }), NOW)).toBe(true); + expect(canInvite(facts({ claimedAt: at(1) }), NOW)).toBe(false); + expect(canInvite(facts({ revokedAt: at(1) }), NOW)).toBe(false); + }); +}); + +function ports(targets: Array<{ attendee_id: string; email: string; name: string | null }>, fail: string[] = []) { + const events = { + invitationTargets: vi.fn().mockResolvedValue(targets), + recordInvitation: vi.fn().mockResolvedValue(undefined), + setRevoked: vi.fn().mockResolvedValue(true), + }; + const notifications = { + invitation: vi.fn(async ({ email }: { email: string }) => { + if (fail.includes(email)) throw new Error("Resend rejected the address"); + }), + }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return { events: events as any, notifications: notifications as any, raw: { events, notifications } }; +} + +const event = { eventId: "event", eventName: "Summit", organizationName: "Acme", eventUrl: "https://bridge.example.com/e/summit" }; + +describe("sendInvitations", () => { + it("sends to every target and records successes and failures separately", async () => { + const { events, notifications, raw } = ports([ + { attendee_id: "a", email: "a@example.com", name: "A" }, + { attendee_id: "b", email: "bad@example.com", name: null }, + ], ["bad@example.com"]); + await expect(sendInvitations(event, { events, notifications })).resolves.toEqual({ sent: 1, failed: 1 }); + expect(raw.events.invitationTargets).toHaveBeenCalledWith("event", null, RESEND_AFTER_MINUTES); + expect(raw.events.recordInvitation).toHaveBeenCalledWith("event", "a", null); + expect(raw.events.recordInvitation).toHaveBeenCalledWith("event", "b", "Resend rejected the address"); + }); + + it("explains why a single resend is refused", async () => { + const { events, notifications } = ports([]); + await expect(sendInvitations({ ...event, attendeeId: "a" }, { events, notifications })).rejects.toThrow(/cannot be invited right now/); + }); +}); + +describe("setAttendeeAccess", () => { + it("refuses someone not on the roster", async () => { + const { events, raw } = ports([]); + raw.events.setRevoked.mockResolvedValue(false); + await expect(setAttendeeAccess({ eventId: "event", attendeeId: "x", revoked: true }, { events })).rejects.toThrow(/not on the event roster/); + }); +}); + +describe("renderInvitationEmail", () => { + it("links to the event and escapes names in the HTML", () => { + const mail = renderInvitationEmail({ name: "