import { query } from "./db"; export type StatusCount = { status: string; count: string }; export async function dashboardStats() { const { rows } = await query( `select status, count(*)::text as count from messages where created_at >= now() - interval '24 hours' group by status`, ); const counts = Object.fromEntries(rows.map((row) => [row.status, Number(row.count)])); const recent = await query<{ id: string; app: string; subject: string; to_emails: string[]; status: string; created_at: string; }>( `select id, app, subject, to_emails, status, created_at from messages order by created_at desc limit 8`, ); const suppressed = await query<{ count: string }>(`select count(*)::text as count from suppressions`); return { counts, recent: recent.rows, suppressed: Number(suppressed.rows[0]?.count ?? 0) }; } export type MessageFilters = { status?: string; q?: string; days?: number; keyId?: string; limit?: number; }; export async function listMessages(filters: MessageFilters = {}) { const params: unknown[] = []; const where: string[] = []; if (filters.status) { params.push(filters.status); where.push(`status = $${params.length}`); } if (filters.keyId) { params.push(filters.keyId); where.push(`api_key_id = $${params.length}`); } if (filters.q) { params.push(`%${filters.q}%`); const n = params.length; where.push( `(subject ILIKE $${n} OR from_email ILIKE $${n} OR array_to_string(to_emails, ' ') ILIKE $${n} OR id::text ILIKE $${n} OR provider_message_id ILIKE $${n})`, ); } if (filters.days && filters.days > 0) { params.push(filters.days); where.push(`created_at >= now() - ($${params.length} || ' days')::interval`); } const limit = Math.min(Math.max(filters.limit ?? 100, 1), 10000); params.push(limit); const { rows } = await query<{ id: string; app: string; subject: string; from_email: string; to_emails: string[]; status: string; attempts: number; created_at: string; completed_at: string | null; error: string | null; }>( `select id, app, subject, from_email, to_emails, status, attempts, created_at, completed_at, error from messages ${where.length ? `where ${where.join(" and ")}` : ""} order by created_at desc limit $${params.length}`, params, ); return rows; } export async function messageDetail(id: string) { const { rows } = await query<{ id: string; app: string; provider: string | null; provider_message_id: string | null; from_email: string; from_name: string | null; to_emails: string[]; cc_emails: string[]; bcc_emails: string[]; reply_to: string[]; subject: string; status: string; error: string | null; attempts: number; created_at: string; sent_at: string | null; completed_at: string | null; payload: unknown; }>(`select * from messages where id = $1`, [id]); const message = rows[0]; if (!message) return null; const events = await query<{ id: string; type: string; payload: unknown; created_at: string }>( `select id, type, payload, created_at from message_events where message_id = $1 order by created_at`, [id], ); return { message, events: events.rows }; } export async function listApiKeys() { const { rows } = await query<{ id: string; app: string; name: string; prefix: string; from_domain: string; provider: string | null; allowed_from: string[] | null; daily_limit: number; monthly_limit: number; revoked_at: string | null; last_used_at: string | null; created_at: string; }>(`select * from api_keys order by created_at desc`); return rows; } export async function listSuppressions(q?: string, limit = 200) { const params: unknown[] = []; let where = ""; if (q) { params.push(`%${q}%`); where = `where email ILIKE $1 or reason ILIKE $1`; } params.push(limit); const { rows } = await query<{ email: string; reason: string; created_at: string }>( `select email, reason, created_at from suppressions ${where} order by created_at desc limit $${params.length}`, params, ); return rows; } export type DailyMetric = { day: string; total: number; delivered: number; bounced: number; complained: number; failed: number; }; export async function dailyMetrics(days = 14, keyId = ""): Promise { const span = Math.min(Math.max(days, 1), 90); const { rows } = await query( `with days as ( select generate_series(current_date - ($1::int - 1), current_date, interval '1 day')::date as day ) select to_char(d.day, 'YYYY-MM-DD') as day, count(m.id)::int as total, count(m.id) filter (where m.status = 'delivered')::int as delivered, count(m.id) filter (where m.status = 'bounced')::int as bounced, count(m.id) filter (where m.status = 'complained')::int as complained, count(m.id) filter (where m.status = 'failed')::int as failed from days d left join messages m on m.created_at >= d.day and m.created_at < d.day + interval '1 day' and ($2::uuid is null or m.api_key_id = $2) group by d.day order by d.day`, [span, keyId || null], ); return rows; } export async function monthlyVolume(): Promise<{ month: number; last30: number }> { const { rows } = await query<{ month: number; last30: number }>( `select count(*) filter (where created_at >= date_trunc('month', now()))::int as month, count(*) filter (where created_at >= now() - interval '30 days')::int as last30 from messages`, ); return rows[0] ?? { month: 0, last30: 0 }; }