All files / dal notification-delivery-log.dal.ts

97.22% Statements 35/36
100% Branches 18/18
90.9% Functions 10/11
97.14% Lines 34/35

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203                                                    43x         3x       1x           1x       1x                             2x         2x           17x 17x 17x   17x             17x 14x   3x               1x                                                                         2x         2x           5x   5x         5x                       22x   22x 2x       22x 3x       22x 1x       22x 1x       22x         12x 12x 12x                   22x      
import { and, desc, eq, gt, like, or, sql } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import type {
	COMMUNICATION_CHANNELS,
	COMMUNICATION_EVENT_TYPES,
	COMMUNICATION_LOG_STATUSES,
	NewNotificationDeliveryLogEntry,
	NotificationDeliveryLogEntry,
} from "../db/schema";
import * as schema from "../db/schema";
 
type LogStatus = (typeof COMMUNICATION_LOG_STATUSES)[number];
type Channel = (typeof COMMUNICATION_CHANNELS)[number];
type EventType = (typeof COMMUNICATION_EVENT_TYPES)[number];
 
export type NotificationDeliveryLogFilters = {
	channel?: Channel;
	status?: LogStatus;
	eventType?: EventType;
	environment?: string;
	search?: string;
	limit?: number;
	offset?: number;
};
 
export class NotificationDeliveryLogDal {
	constructor(private db: DrizzleD1Database<typeof schema>) {}
 
	async insert(
		data: NewNotificationDeliveryLogEntry,
	): Promise<NotificationDeliveryLogEntry> {
		const result = await this.db
			.insert(schema.notificationDeliveryLog)
			.values(data)
			.returning();
		return result[0];
	}
 
	async batchInsert(
		data: NewNotificationDeliveryLogEntry[],
	): Promise<NotificationDeliveryLogEntry[]> {
		const result = await this.db
			.insert(schema.notificationDeliveryLog)
			.values(data)
			.returning();
		return result;
	}
 
	async updateStatus(
		id: number,
		updates: {
			status: LogStatus;
			actualRecipient?: string;
			provider?: string;
			externalId?: string;
			previewHtml?: string;
			previewText?: string;
			errorMessage?: string;
		},
	): Promise<NotificationDeliveryLogEntry | undefined> {
		const result = await this.db
			.update(schema.notificationDeliveryLog)
			.set({ ...updates, dateUpdated: new Date() })
			.where(eq(schema.notificationDeliveryLog.id, id))
			.returning();
		return result[0];
	}
 
	async findAll(
		filters?: NotificationDeliveryLogFilters,
	): Promise<NotificationDeliveryLogEntry[]> {
		const conditions = this.buildConditions(filters);
		const limit = filters?.limit ?? 50;
		const offset = filters?.offset ?? 0;
 
		const query = this.db
			.select()
			.from(schema.notificationDeliveryLog)
			.orderBy(desc(schema.notificationDeliveryLog.dateCreated))
			.limit(limit)
			.offset(offset);
 
		if (conditions.length > 0) {
			return query.where(and(...conditions));
		}
		return query;
	}
 
	async findRecentByEventAndMetadata(
		eventType: EventType,
		sinceDate: Date,
		metadataContains: string,
	): Promise<NotificationDeliveryLogEntry[]> {
		return this.db
			.select()
			.from(schema.notificationDeliveryLog)
			.where(
				and(
					eq(schema.notificationDeliveryLog.eventType, eventType),
					gt(schema.notificationDeliveryLog.dateCreated, sinceDate),
					like(
						schema.notificationDeliveryLog.metadataJson,
						`%${metadataContains}%`,
					),
				),
			)
			.orderBy(desc(schema.notificationDeliveryLog.dateCreated))
			.limit(10);
	}
 
	async findAllRecentByEvent(
		eventType: EventType,
		sinceDate: Date,
	): Promise<NotificationDeliveryLogEntry[]> {
		return this.db
			.select()
			.from(schema.notificationDeliveryLog)
			.where(
				and(
					eq(schema.notificationDeliveryLog.eventType, eventType),
					gt(schema.notificationDeliveryLog.dateCreated, sinceDate),
				),
			)
			.orderBy(desc(schema.notificationDeliveryLog.dateCreated))
			.limit(1000);
	}
 
	async findById(
		id: number,
	): Promise<NotificationDeliveryLogEntry | undefined> {
		const result = await this.db
			.select()
			.from(schema.notificationDeliveryLog)
			.where(eq(schema.notificationDeliveryLog.id, id))
			.limit(1);
		return result[0];
	}
 
	async countAll(
		filters?: Omit<NotificationDeliveryLogFilters, "limit" | "offset">,
	): Promise<number> {
		const conditions = this.buildConditions(filters);
 
		const query = this.db
			.select({ count: sql<number>`count(*)` })
			.from(schema.notificationDeliveryLog);
 
		const result =
			conditions.length > 0
				? await query.where(and(...conditions))
				: await query;
 
		/* v8 ignore start -- V8 artifact: ?? fallback never reached */
		return result[0]?.count ?? 0;
		/* v8 ignore stop */
	}
 
	private buildConditions(
		filters?: Omit<NotificationDeliveryLogFilters, "limit" | "offset">,
	) {
		const conditions = [];
 
		if (filters?.channel) {
			conditions.push(
				eq(schema.notificationDeliveryLog.channel, filters.channel),
			);
		}
		if (filters?.status) {
			conditions.push(
				eq(schema.notificationDeliveryLog.status, filters.status),
			);
		}
		if (filters?.eventType) {
			conditions.push(
				eq(schema.notificationDeliveryLog.eventType, filters.eventType),
			);
		}
		if (filters?.environment) {
			conditions.push(
				eq(schema.notificationDeliveryLog.environment, filters.environment),
			);
		}
		if (filters?.search) {
			// The box promises "recipient, event type…": an event type such as
			// `landing_lead_internal` (how the #1085 QA checklist finds support
			// emails), or a subject naming the lead. `_` is a LIKE wildcard and
			// common in event types, so the term is matched literally.
			const term = `%${filters.search.replace(/[\\%_]/g, (ch) => `\\${ch}`)}%`;
			const log = schema.notificationDeliveryLog;
			conditions.push(
				or(
					sql`${log.recipient} LIKE ${term} ESCAPE '\\'`,
					sql`${log.actualRecipient} LIKE ${term} ESCAPE '\\'`,
					sql`${log.eventType} LIKE ${term} ESCAPE '\\'`,
					sql`${log.subject} LIKE ${term} ESCAPE '\\'`,
				),
			);
		}
 
		return conditions;
	}
}