Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 48 additions & 1 deletion apps/web/src/server/service/guard-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof watchQuery>) {
const since = new Date(Date.now() - query.days * DAY_MS);
const teams = await db.team.findMany({
Expand All @@ -375,7 +379,12 @@ export async function listWatchedTeams(query: z.infer<typeof watchQuery>) {
select: {
email: true,
waitlistApplication: {
select: { website: true, description: true },
select: {
website: true,
description: true,
emailVolume: true,
listSource: true,
},
},
},
},
Expand Down Expand Up @@ -404,6 +413,37 @@ export async function listWatchedTeams(query: z.infer<typeof watchQuery>) {
});
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. 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") AS r(address)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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<number, typeof recentRows>();
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);
Expand All @@ -414,7 +454,14 @@ export async function listWatchedTeams(query: z.infer<typeof watchQuery>) {
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,
Expand Down
75 changes: 74 additions & 1 deletion apps/web/src/server/service/guard-service.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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() },
Expand Down Expand Up @@ -52,6 +53,7 @@ import {
isReviewHeld,
listActiveCampaigns,
listNewEmails,
listWatchedTeams,
newEmailsQuery,
abusePauseEmail,
teamActionBody,
Expand Down Expand Up @@ -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([
Expand Down
Loading