All files / dal notifications.dal.ts

100% Statements 34/34
94.44% Branches 17/18
100% Functions 10/10
100% Lines 33/33

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            53x     2x       2x       2x                       7x 7x     7x         7x 2x     7x 2x 2x       2x     7x     7x                       7x         7x     7x                     7x   7x       3x                   3x       3x                   3x       2x             3x           3x 1x     3x         3x       2x             2x                 2x      
import { eq, and, desc, isNull, sql, like, or, inArray } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../db/schema";
import type { Notification, NewNotification } from "../db/schema";
 
export class NotificationsDal {
	constructor(private db: DrizzleD1Database<typeof schema>) {}
 
	async create(data: NewNotification): Promise<Notification> {
		const result = await this.db
			.insert(schema.notifications)
			.values(data)
			.returning();
		return result[0];
	}
 
	async createMany(data: NewNotification[]): Promise<void> {
		await this.db.insert(schema.notifications).values(data);
	}
 
	async findByUser(
		userId: string,
		filters?: {
			category?: (typeof schema.NOTIFICATION_CATEGORIES)[number];
			search?: string;
			limit?: number;
			offset?: number;
		},
	): Promise<{ notifications: Notification[]; total: number; unreadCount: number }> {
		const limit = filters?.limit ?? 20;
		const offset = filters?.offset ?? 0;
 
		// Base conditions for the query (with category/search filters)
		const conditions = [
			eq(schema.notifications.userId, userId),
			isNull(schema.notifications.deletedAt),
		];
 
		if (filters?.category) {
			conditions.push(eq(schema.notifications.category, filters.category));
		}
 
		if (filters?.search) {
			const searchPattern = `%${filters.search}%`;
			const searchCondition = or(
				like(schema.notifications.title, searchPattern),
				like(schema.notifications.body, searchPattern),
			);
			Eif (searchCondition) conditions.push(searchCondition);
		}
 
		const whereClause = and(...conditions);
 
		// Fetch notifications with ordering: unread first, then date_created DESC
		const notifications = await this.db
			.select()
			.from(schema.notifications)
			.where(whereClause)
			.orderBy(
				sql`CASE WHEN ${schema.notifications.readAt} IS NULL THEN 0 ELSE 1 END`,
				desc(schema.notifications.dateCreated),
			)
			.limit(limit)
			.offset(offset);
 
		// Total count with filters applied
		const totalResult = await this.db
			.select({ count: sql<number>`count(*)` })
			.from(schema.notifications)
			.where(whereClause);
 
		const total = totalResult[0]?.count ?? 0;
 
		// Unread count: ALWAYS total unread for user, ignoring category/search filters
		const unreadCountResult = await this.db
			.select({ count: sql<number>`count(*)` })
			.from(schema.notifications)
			.where(
				and(
					eq(schema.notifications.userId, userId),
					isNull(schema.notifications.deletedAt),
					isNull(schema.notifications.readAt),
				),
			);
 
		const unreadCount = unreadCountResult[0]?.count ?? 0;
 
		return { notifications, total, unreadCount };
	}
 
	async getUnreadCount(userId: string): Promise<number> {
		const result = await this.db
			.select({ count: sql<number>`count(*)` })
			.from(schema.notifications)
			.where(
				and(
					eq(schema.notifications.userId, userId),
					isNull(schema.notifications.deletedAt),
					isNull(schema.notifications.readAt),
				),
			);
		return result[0]?.count ?? 0;
	}
 
	async findById(id: string): Promise<Notification | undefined> {
		const result = await this.db
			.select()
			.from(schema.notifications)
			.where(
				and(
					eq(schema.notifications.id, id),
					isNull(schema.notifications.deletedAt),
				),
			)
			.limit(1);
		return result[0];
	}
 
	async markAsRead(id: string): Promise<void> {
		await this.db
			.update(schema.notifications)
			.set({ readAt: new Date() })
			.where(eq(schema.notifications.id, id));
	}
 
	async markAllAsRead(userId: string, category?: (typeof schema.NOTIFICATION_CATEGORIES)[number]): Promise<number> {
		const conditions = [
			eq(schema.notifications.userId, userId),
			isNull(schema.notifications.deletedAt),
			isNull(schema.notifications.readAt),
		];
 
		if (category) {
			conditions.push(eq(schema.notifications.category, category));
		}
 
		const result = await this.db
			.update(schema.notifications)
			.set({ readAt: new Date() })
			.where(and(...conditions));
 
		return result.meta.changes;
	}
 
	async softDelete(id: string): Promise<void> {
		await this.db
			.update(schema.notifications)
			.set({ deletedAt: new Date() })
			.where(eq(schema.notifications.id, id));
	}
 
	async softDeleteMany(ids: string[], userId: string): Promise<number> {
		const result = await this.db
			.update(schema.notifications)
			.set({ deletedAt: new Date() })
			.where(
				and(
					inArray(schema.notifications.id, ids),
					eq(schema.notifications.userId, userId),
				),
			);
		return result.meta.changes;
	}
}