diff --git a/apps/web/src/server/service/guard-service.ts b/apps/web/src/server/service/guard-service.ts index 3c7d8601..0e5e8184 100644 --- a/apps/web/src/server/service/guard-service.ts +++ b/apps/web/src/server/service/guard-service.ts @@ -352,6 +352,10 @@ export const watchQuery = z.object({ }); /** Teams created in the last `days`, with their sending numbers, paged. */ +/** The window and size of each team's `recentMessages`. */ +const RECENT_MESSAGES_MS = 2 * 60 * 60 * 1000; +const RECENT_MESSAGES_MAX = 5; + export async function listWatchedTeams(query: z.infer) { const since = new Date(Date.now() - query.days * DAY_MS); const teams = await db.team.findMany({ @@ -375,7 +379,12 @@ export async function listWatchedTeams(query: z.infer) { select: { email: true, waitlistApplication: { - select: { website: true, description: true }, + select: { + website: true, + description: true, + emailVolume: true, + listSource: true, + }, }, }, }, @@ -404,6 +413,41 @@ export async function listWatchedTeams(query: z.infer) { }); const usageByTeam = new Map(usage.map((row) => [row.teamId, row._sum])); + // Each recent API message (sender + subject pattern) and how many different + // people it went to: one message blasted to thousands of strangers only + // shows up as a pattern. Scoped to the last 2 hours so it describes a + // burst, not the whole day. Recipients include cc and bcc. Every attempt + // counts (even suppressed or failed): trying to blast a list is the signal. + // Counts only; no addresses leave the database. + const recentRows = await db.$queryRaw< + Array<{ + teamId: number; + from: string; + subject: string; + emails: number; + recipients: number; + }> + >` + SELECT e."teamId" AS "teamId", e."from" AS "from", + regexp_replace(e.subject, '[0-9]+', '#', 'g') AS subject, + COUNT(DISTINCT e.id)::int AS emails, + COUNT(DISTINCT lower(r.address))::int AS recipients + FROM "Email" e + CROSS JOIN LATERAL unnest( + e."to" || coalesce(e.cc, '{}') || coalesce(e.bcc, '{}') + ) AS r(address) + WHERE e."teamId" = ANY(${page.map((team) => team.id)}) + AND e."createdAt" > ${new Date(Date.now() - RECENT_MESSAGES_MS)} + AND e."campaignId" IS NULL + GROUP BY 1, 2, 3 + ORDER BY emails DESC`; + const recentByTeam = new Map(); + for (const row of recentRows) { + const rows = recentByTeam.get(row.teamId) ?? []; + if (rows.length < RECENT_MESSAGES_MAX) rows.push(row); + recentByTeam.set(row.teamId, rows); + } + return { items: page.map(({ teamUsers, ...team }) => { const sums = usageByTeam.get(team.id); @@ -414,7 +458,14 @@ export async function listWatchedTeams(query: z.infer) { email: user.email, website: user.waitlistApplication?.website ?? null, description: user.waitlistApplication?.description ?? null, + // What they said they'd send, so the Guard can compare it with + // what they actually send. + emailVolume: user.waitlistApplication?.emailVolume ?? null, + listSource: user.waitlistApplication?.listSource ?? null, })), + recentMessages: (recentByTeam.get(team.id) ?? []).map( + ({ teamId: _teamId, ...message }) => message, + ), usage: { sent: sums?.sent ?? 0, delivered: sums?.delivered ?? 0, diff --git a/apps/web/src/server/service/guard-service.unit.test.ts b/apps/web/src/server/service/guard-service.unit.test.ts index cea26cf2..adea88ae 100644 --- a/apps/web/src/server/service/guard-service.unit.test.ts +++ b/apps/web/src/server/service/guard-service.unit.test.ts @@ -6,7 +6,8 @@ const { mockEnv, mockDb, mockRefreshTeamCache, mockRedis } = vi.hoisted(() => ({ mockDb: { $transaction: vi.fn(), $queryRaw: vi.fn(), - team: { findUnique: vi.fn(), updateMany: vi.fn() }, + team: { findUnique: vi.fn(), updateMany: vi.fn(), findMany: vi.fn() }, + dailyEmailUsage: { groupBy: vi.fn() }, campaign: { findMany: vi.fn(), updateMany: vi.fn() }, teamAction: { create: vi.fn() }, email: { findMany: vi.fn() }, @@ -52,6 +53,7 @@ import { isReviewHeld, listActiveCampaigns, listNewEmails, + listWatchedTeams, newEmailsQuery, abusePauseEmail, teamActionBody, @@ -428,6 +430,77 @@ describe("recordTeamAction", () => { }); }); +describe("listWatchedTeams", () => { + it("includes what each member applied with, to compare with their sending", async () => { + mockDb.team.findMany.mockResolvedValue([ + { + id: 453, + name: "New team", + createdAt: new Date(), + domains: [], + teamUsers: [ + { + role: "ADMIN", + user: { + email: "owner@example.com", + waitlistApplication: { + website: "https://example.com", + description: "A weekly digest", + emailVolume: "Close to zero for now", + listSource: "Signup form with double opt-in", + }, + }, + }, + ], + }, + ]); + mockDb.dailyEmailUsage.groupBy.mockResolvedValue([ + { + teamId: 453, + _sum: { + sent: 2952, + delivered: 2933, + bounced: 17, + hardBounced: 17, + complained: 2, + }, + }, + ]); + + mockDb.$queryRaw.mockResolvedValueOnce([ + { + teamId: 453, + from: "info@example.com", + subject: "Successful registration", + emails: 1932, + recipients: 1930, + }, + ]); + + const { items } = await listWatchedTeams({ days: 14, limit: 100 }); + + expect(items[0]!.members).toEqual([ + { + role: "ADMIN", + email: "owner@example.com", + website: "https://example.com", + description: "A weekly digest", + emailVolume: "Close to zero for now", + listSource: "Signup form with double opt-in", + }, + ]); + expect(items[0]!.usage.sent).toBe(2952); + expect(items[0]!.recentMessages).toEqual([ + { + from: "info@example.com", + subject: "Successful registration", + emails: 1932, + recipients: 1930, + }, + ]); + }); +}); + describe("sampleTeamEmails", () => { it("returns content but only the recipients' domains", async () => { mockDb.email.findMany.mockResolvedValue([