All files / dal lead-documents.dal.ts

100% Statements 15/15
100% Branches 6/6
100% Functions 7/7
100% Lines 15/15

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              16x           4x         4x 2x         4x               2x         2x       1x       1x       2x         2x       3x                 3x       3x                       3x      
// Data Access Layer for Lead Documents
import { eq, and, isNull, sql, desc } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../db/schema";
import type { LeadDocument, NewLeadDocument } from "../db/schema";
 
export class LeadDocumentsDal {
	constructor(private db: DrizzleD1Database<typeof schema>) {}
 
	async findByLeadId(
		leadId: number,
		documentType?: string,
	): Promise<LeadDocument[]> {
		const conditions = [
			eq(schema.leadDocuments.leadId, leadId),
			isNull(schema.leadDocuments.deletedAt),
		];
 
		if (documentType) {
			conditions.push(
				sql`${schema.leadDocuments.documentType} = ${documentType}`,
			);
		}
 
		return this.db
			.select()
			.from(schema.leadDocuments)
			.where(and(...conditions))
			.orderBy(desc(schema.leadDocuments.dateCreated));
	}
 
	async findById(id: number): Promise<LeadDocument | undefined> {
		const result = await this.db
			.select()
			.from(schema.leadDocuments)
			.where(eq(schema.leadDocuments.id, id))
			.limit(1);
		return result[0];
	}
 
	async create(data: NewLeadDocument): Promise<LeadDocument> {
		const result = await this.db
			.insert(schema.leadDocuments)
			.values(data)
			.returning();
		return result[0];
	}
 
	async softDelete(id: number): Promise<LeadDocument | undefined> {
		const result = await this.db
			.update(schema.leadDocuments)
			.set({ deletedAt: new Date() })
			.where(eq(schema.leadDocuments.id, id))
			.returning();
		return result[0];
	}
 
	async countByLeadId(leadId: number): Promise<number> {
		const result = await this.db
			.select({ count: sql<number>`count(*)` })
			.from(schema.leadDocuments)
			.where(
				and(
					eq(schema.leadDocuments.leadId, leadId),
					isNull(schema.leadDocuments.deletedAt),
				),
			);
		return result[0]?.count ?? 0;
	}
 
	async getMaxQuoteRevision(leadId: number): Promise<number> {
		const result = await this.db
			.select({
				maxRevision: sql<number>`coalesce(max(${schema.leadDocuments.quoteRevisionNumber}), 0)`,
			})
			.from(schema.leadDocuments)
			.where(
				and(
					eq(schema.leadDocuments.leadId, leadId),
					sql`${schema.leadDocuments.documentType} = 'quote'`,
					isNull(schema.leadDocuments.deletedAt),
				),
			);
		return result[0]?.maxRevision ?? 0;
	}
}