All files / dal leads.dal.ts

100% Statements 58/58
100% Branches 26/26
100% Functions 17/17
100% Lines 56/56

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 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267                                  45x             8x   8x             8x       2x         2x             2x             2x       1x 1x       2x       2x       3x         3x       3x       3x             3x         3x           2x                                     3x 3x 1x     3x       3x       2x                             2x                                     4x   3x                             3x 3x 3x             3x           3x   2x                           2x 2x 2x   2x       4x   4x       4x   4x       12x   12x   12x 4x   12x 1x   12x 2x   12x 1x       12x 2x 2x         12x      
// Data Access Layer for Leads
import { eq, and, like, sql, desc, inArray } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../db/schema";
import type { Lead, NewLead } from "../db/schema";
import { sanitizeSearchInput } from "../lib/utils";
 
export type LeadFilters = {
	proId: string;
	stageId?: number;
	sourceId?: number;
	isArchived?: boolean;
	search?: string;
	projectType?: string;
};
 
export class LeadsDal {
	constructor(private db: DrizzleD1Database<typeof schema>) {}
 
	async findByProId(
		filters: LeadFilters,
		offset = 0,
		limit = 50,
	): Promise<Lead[]> {
		const conditions = this.buildConditions(filters);
 
		const query = this.db
			.select()
			.from(schema.leads)
			.orderBy(desc(schema.leads.dateUpdated))
			.limit(limit)
			.offset(offset);
 
		return query.where(and(...conditions));
	}
 
	async findById(id: number): Promise<Lead | undefined> {
		const result = await this.db
			.select()
			.from(schema.leads)
			.where(eq(schema.leads.id, id))
			.limit(1);
		return result[0];
	}
 
	async findByPhone(
		proId: string,
		phone: string,
	): Promise<Lead | undefined> {
		const result = await this.db
			.select()
			.from(schema.leads)
			.where(
				and(eq(schema.leads.proId, proId), eq(schema.leads.phone, phone)),
			)
			.limit(1);
		return result[0];
	}
 
	async create(data: NewLead): Promise<Lead> {
		const result = await this.db.insert(schema.leads).values(data).returning();
		return result[0];
	}
 
	async delete(id: number): Promise<boolean> {
		const result = await this.db
			.delete(schema.leads)
			.where(eq(schema.leads.id, id))
			.returning({ id: schema.leads.id });
		return result.length > 0;
	}
 
	async reassignStage(fromStageId: number, toStageId: number): Promise<number> {
		const result = await this.db
			.update(schema.leads)
			.set({ currentStageId: toStageId, dateUpdated: new Date() })
			.where(eq(schema.leads.currentStageId, fromStageId))
			.returning({ id: schema.leads.id });
		return result.length;
	}
 
	async countByStageId(stageId: number): Promise<number> {
		const result = await this.db
			.select({ count: sql<number>`count(*)` })
			.from(schema.leads)
			.where(eq(schema.leads.currentStageId, stageId));
		return result[0]?.count ?? 0;
	}
 
	async update(
		id: number,
		data: Partial<Omit<Lead, "id" | "dateCreated">>,
	): Promise<Lead | undefined> {
		const result = await this.db
			.update(schema.leads)
			.set({ ...data, dateUpdated: new Date() })
			.where(eq(schema.leads.id, id))
			.returning();
		return result[0];
	}
 
	async countByStage(
		proId: string,
	): Promise<{ stageId: number; count: number }[]> {
		return this.db
			.select({
				stageId: schema.leads.currentStageId,
				count: sql<number>`count(*)`,
			})
			.from(schema.leads)
			.where(
				and(
					eq(schema.leads.proId, proId),
					eq(schema.leads.isArchived, false),
				),
			)
			.groupBy(schema.leads.currentStageId);
	}
 
	async countByProId(
		proId: string,
		isArchived?: boolean,
	): Promise<number> {
		const conditions = [eq(schema.leads.proId, proId)];
		if (isArchived !== undefined) {
			conditions.push(eq(schema.leads.isArchived, isArchived));
		}
 
		const result = await this.db
			.select({ count: sql<number>`count(*)` })
			.from(schema.leads)
			.where(and(...conditions));
		return result[0]?.count ?? 0;
	}
 
	async getKanbanData(proId: string): Promise<Lead[]> {
		return this.db
			.select()
			.from(schema.leads)
			.where(
				and(
					eq(schema.leads.proId, proId),
					eq(schema.leads.isArchived, false),
				),
			)
			.orderBy(desc(schema.leads.dateUpdated));
	}
 
	async getStageValueSums(
		proId: string,
	): Promise<{ stageId: number; totalQuoteValue: number }[]> {
		return this.db
			.select({
				stageId: schema.leads.currentStageId,
				totalQuoteValue: sql<number>`coalesce(sum(${schema.leads.quoteValuePaise}), 0)`,
			})
			.from(schema.leads)
			.where(
				and(
					eq(schema.leads.proId, proId),
					eq(schema.leads.isArchived, false),
				),
			)
			.groupBy(schema.leads.currentStageId);
	}
 
	async getReminderStatsForLeads(
		_proId: string,
		leadIds: number[],
	): Promise<Map<number, { count: number; nextDueAt: string | null }>> {
		if (leadIds.length === 0) return new Map();
 
		const results = await this.db
			.select({
				leadId: schema.leadReminders.leadId,
				count: sql<number>`count(*)`,
				nextDueAt: sql<number | null>`min(${schema.leadReminders.dueAt})`,
			})
			.from(schema.leadReminders)
			.where(
				and(
					inArray(schema.leadReminders.leadId, leadIds),
					sql`${schema.leadReminders.status} IN ('upcoming', 'overdue')`,
				),
			)
			.groupBy(schema.leadReminders.leadId);
 
		const map = new Map<number, { count: number; nextDueAt: string | null }>();
		for (const row of results) {
			map.set(row.leadId, {
				count: row.count,
				nextDueAt: row.nextDueAt
					? new Date(row.nextDueAt * 1000).toISOString()
					: null,
			});
		}
		return map;
	}
 
	async getDocumentCountsForLeads(
		leadIds: number[],
	): Promise<Map<number, number>> {
		if (leadIds.length === 0) return new Map();
 
		const results = await this.db
			.select({
				leadId: schema.leadDocuments.leadId,
				count: sql<number>`count(*)`,
			})
			.from(schema.leadDocuments)
			.where(
				and(
					inArray(schema.leadDocuments.leadId, leadIds),
					sql`${schema.leadDocuments.deletedAt} IS NULL`,
				),
			)
			.groupBy(schema.leadDocuments.leadId);
 
		const map = new Map<number, number>();
		for (const row of results) {
			map.set(row.leadId, row.count);
		}
		return map;
	}
 
	async count(filters: LeadFilters): Promise<number> {
		const conditions = this.buildConditions(filters);
 
		const query = this.db
			.select({ count: sql<number>`count(*)` })
			.from(schema.leads);
 
		const result = await query.where(and(...conditions));
 
		return result[0]?.count ?? 0;
	}
 
	private buildConditions(filters: LeadFilters) {
		const conditions = [];
 
		conditions.push(eq(schema.leads.proId, filters.proId));
 
		if (filters.stageId !== undefined) {
			conditions.push(eq(schema.leads.currentStageId, filters.stageId));
		}
		if (filters.sourceId !== undefined) {
			conditions.push(eq(schema.leads.leadSourceId, filters.sourceId));
		}
		if (filters.isArchived !== undefined) {
			conditions.push(eq(schema.leads.isArchived, filters.isArchived));
		}
		if (filters.projectType) {
			conditions.push(
				sql`${schema.leads.projectType} = ${filters.projectType}`,
			);
		}
		if (filters.search) {
			const sanitized = sanitizeSearchInput(filters.search);
			conditions.push(
				sql`(${like(schema.leads.customerName, `%${sanitized}%`)} OR ${like(schema.leads.phone, `%${sanitized}%`)})`,
			);
		}
 
		return conditions;
	}
}