All files / dal/whatsapp conversations.dal.ts

100% Statements 37/37
100% Branches 24/24
100% Functions 11/11
100% Lines 37/37

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                          41x         2x         2x       2x         2x               6x   6x             6x 4x   2x       4x   4x       4x 2x 2x   2x 2x       1x       1x             2x         2x       1x                   1x                     2x 2x   2x                                   2x               10x   10x 4x         10x 1x 1x 1x         10x 2x     10x      
import { eq, and, sql, desc, gt } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../../db/schema";
import type { WaConversation, NewWaConversation } from "../../db/schema";
import { sanitizeSearchInput } from "../../lib/utils";
 
export type WaConversationFilters = {
	contactType?: string;
	search?: string;
	hasUnread?: boolean;
};
 
export class WaConversationsDal {
	constructor(private db: DrizzleD1Database<typeof schema>) {}
 
	async findByPhoneNumber(
		phone: string,
	): Promise<WaConversation | undefined> {
		const result = await this.db
			.select()
			.from(schema.waConversations)
			.where(eq(schema.waConversations.phoneNumber, phone))
			.limit(1);
		return result[0];
	}
 
	async findById(id: number): Promise<WaConversation | undefined> {
		const result = await this.db
			.select()
			.from(schema.waConversations)
			.where(eq(schema.waConversations.id, id))
			.limit(1);
		return result[0];
	}
 
	async findAll(
		filters: WaConversationFilters = {},
		offset = 0,
		limit = 50,
	): Promise<WaConversation[]> {
		const conditions = this.buildConditions(filters);
 
		const query = this.db
			.select()
			.from(schema.waConversations)
			.orderBy(desc(schema.waConversations.lastMessageAt))
			.limit(limit)
			.offset(offset);
 
		if (conditions.length > 0) {
			return query.where(and(...conditions));
		}
		return query;
	}
 
	async count(filters: WaConversationFilters = {}): Promise<number> {
		const conditions = this.buildConditions(filters);
 
		const query = this.db
			.select({ count: sql<number>`count(*)` })
			.from(schema.waConversations);
 
		if (conditions.length > 0) {
			const result = await query.where(and(...conditions));
			return result[0]?.count ?? 0;
		}
		const result = await query;
		return result[0]?.count ?? 0;
	}
 
	async create(data: NewWaConversation): Promise<WaConversation> {
		const result = await this.db
			.insert(schema.waConversations)
			.values(data)
			.returning();
		return result[0];
	}
 
	async update(
		id: number,
		data: Partial<WaConversation>,
	): Promise<WaConversation | undefined> {
		const result = await this.db
			.update(schema.waConversations)
			.set({ ...data, dateUpdated: new Date() })
			.where(eq(schema.waConversations.id, id))
			.returning();
		return result[0];
	}
 
	async incrementUnread(id: number): Promise<void> {
		await this.db
			.update(schema.waConversations)
			.set({
				unreadCount: sql`${schema.waConversations.unreadCount} + 1`,
				dateUpdated: new Date(),
			})
			.where(eq(schema.waConversations.id, id));
	}
 
	async resetUnread(id: number): Promise<void> {
		await this.db
			.update(schema.waConversations)
			.set({ unreadCount: 0, dateUpdated: new Date() })
			.where(eq(schema.waConversations.id, id));
	}
 
	async getStats(): Promise<{
		total: number;
		unread: number;
		activeToday: number;
	}> {
		const todayStart = new Date();
		todayStart.setHours(0, 0, 0, 0);
 
		const [totalResult, unreadResult, activeTodayResult] = await Promise.all(
			[
				this.db
					.select({ count: sql<number>`count(*)` })
					.from(schema.waConversations),
				this.db
					.select({ count: sql<number>`count(*)` })
					.from(schema.waConversations)
					.where(gt(schema.waConversations.unreadCount, 0)),
				this.db
					.select({ count: sql<number>`count(*)` })
					.from(schema.waConversations)
					.where(
						gt(schema.waConversations.lastMessageAt, todayStart),
					),
			],
		);
 
		return {
			total: totalResult[0]?.count ?? 0,
			unread: unreadResult[0]?.count ?? 0,
			activeToday: activeTodayResult[0]?.count ?? 0,
		};
	}
 
	private buildConditions(filters: WaConversationFilters) {
		const conditions = [];
 
		if (filters.contactType) {
			conditions.push(
				eq(schema.waConversations.contactType, filters.contactType as WaConversation["contactType"]),
			);
		}
 
		if (filters.search) {
			const sanitized = sanitizeSearchInput(filters.search);
			const searchTerm = `%${sanitized}%`;
			conditions.push(
				sql`(${schema.waConversations.phoneNumber} LIKE ${searchTerm} OR ${schema.waConversations.contactName} LIKE ${searchTerm})`,
			);
		}
 
		if (filters.hasUnread) {
			conditions.push(gt(schema.waConversations.unreadCount, 0));
		}
 
		return conditions;
	}
}