All files / dal homeowner-inquiries.dal.ts

100% Statements 19/19
100% Branches 5/5
100% Functions 11/11
100% Lines 19/19

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                                                              11x                 81x     4x                                   2x                           2x                     2x         2x                 2x                 1x       1x             2x                   2x               1x                                   2x                                       2x                               2x                     2x                 2x     11x    
// Data Access Layer — Homeowner inquiry list + inquiry↔pro matches.
// Backs the homeowner portal (basic_homeowner_portal / crm_homeowner_inquiry_list).
import { and, desc, eq, sql } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import type {
	HoCallbackRequest,
	HoCallbackSlot,
	Inquiry,
	InquiryProMatch,
	InquiryProStatus,
} from "../db/schema";
import * as schema from "../db/schema";
 
// Inquiry card shape for the homeowner list — inquiry fields + the contacted
// pro's public identity, resolved in one leftJoin (single join, D1-friendly).
export type HomeownerInquiryRow = {
	id: number;
	proId: string;
	proBusinessName: string | null;
	proSlug: string | null;
	homeownerStatus: Inquiry["homeownerStatus"];
	requirementType: string | null;
	requirement: string | null;
	customerLocation: string | null;
	prosNotifiedCount: number;
	isActive: boolean;
	dateCreated: Date;
	dateUpdated: Date;
	closedAt: Date | null;
};
 
const ACTIVE_STATUSES: Array<Inquiry["homeownerStatus"]> = [
	"submitted",
	"pros_notified",
	"quotes_requested",
	"comparison_ready",
	"on_hold",
];
 
export class HomeownerInquiriesDal {
	constructor(private db: DrizzleD1Database<typeof schema>) {}
 
	private cardSelect() {
		return {
			id: schema.inquiries.id,
			proId: schema.inquiries.proId,
			proBusinessName: schema.pros.businessName,
			proSlug: schema.pros.slug,
			homeownerStatus: schema.inquiries.homeownerStatus,
			requirementType: schema.inquiries.requirementType,
			requirement: schema.inquiries.requirement,
			customerLocation: schema.inquiries.customerLocation,
			prosNotifiedCount: schema.inquiries.prosNotifiedCount,
			isActive: schema.inquiries.isActive,
			dateCreated: schema.inquiries.dateCreated,
			dateUpdated: schema.inquiries.dateUpdated,
			closedAt: schema.inquiries.closedAt,
		};
	}
 
	async listByHomeowner(homeownerId: string): Promise<HomeownerInquiryRow[]> {
		return this.db
			.select(this.cardSelect())
			.from(schema.inquiries)
			.leftJoin(schema.pros, eq(schema.inquiries.proId, schema.pros.id))
			.where(eq(schema.inquiries.homeownerId, homeownerId))
			.orderBy(desc(schema.inquiries.dateUpdated));
	}
 
	// Detail fetch — enforces ownership by requiring the homeownerId to match.
	// Returns undefined if the inquiry doesn't exist or belongs to someone else.
	async getForHomeowner(
		inquiryId: number,
		homeownerId: string,
	): Promise<HomeownerInquiryRow | undefined> {
		const rows = await this.db
			.select(this.cardSelect())
			.from(schema.inquiries)
			.leftJoin(schema.pros, eq(schema.inquiries.proId, schema.pros.id))
			.where(
				and(
					eq(schema.inquiries.id, inquiryId),
					eq(schema.inquiries.homeownerId, homeownerId),
				),
			)
			.limit(1);
		return rows[0];
	}
 
	// Count of the homeowner's active inquiries — enforces the 3-inquiry cap.
	async countActive(homeownerId: string): Promise<number> {
		const rows = await this.db
			.select({ count: sql<number>`count(*)` })
			.from(schema.inquiries)
			.where(
				and(
					eq(schema.inquiries.homeownerId, homeownerId),
					eq(schema.inquiries.isActive, true),
				),
			);
		return rows[0]?.count ?? 0;
	}
 
	// ---- inquiry ↔ pro match lifecycle --------------------------------------
 
	async createMatch(
		inquiryId: number,
		proId: string,
	): Promise<InquiryProMatch> {
		const rows = await this.db
			.insert(schema.inquiryProMatches)
			.values({ inquiryId, proId, proStatus: "notified" })
			.returning();
		return rows[0];
	}
 
	async getMatch(
		inquiryId: number,
		proId: string,
	): Promise<InquiryProMatch | undefined> {
		const rows = await this.db
			.select()
			.from(schema.inquiryProMatches)
			.where(
				and(
					eq(schema.inquiryProMatches.inquiryId, inquiryId),
					eq(schema.inquiryProMatches.proId, proId),
				),
			)
			.limit(1);
		return rows[0];
	}
 
	async setMatchStatus(
		inquiryId: number,
		proId: string,
		proStatus: InquiryProStatus,
	): Promise<void> {
		await this.db
			.update(schema.inquiryProMatches)
			.set({ proStatus, proStatusUpdatedAt: new Date() })
			.where(
				and(
					eq(schema.inquiryProMatches.inquiryId, inquiryId),
					eq(schema.inquiryProMatches.proId, proId),
				),
			);
	}
 
	// ---- homeowner-facing status --------------------------------------------
 
	async setHomeownerStatus(
		inquiryId: number,
		homeownerStatus: Inquiry["homeownerStatus"],
		extra: { prosNotifiedCount?: number } = {},
	): Promise<void> {
		await this.db
			.update(schema.inquiries)
			.set({
				homeownerStatus,
				dateUpdated: new Date(),
				...(extra.prosNotifiedCount !== undefined && {
					prosNotifiedCount: extra.prosNotifiedCount,
				}),
			})
			.where(eq(schema.inquiries.id, inquiryId));
	}
 
	// Close an inquiry the homeowner owns — frees a slot against the 3-active cap
	// (spec: crm_homeowner_inquiry_list "Close inquiry"). Scoped by homeownerId so
	// one homeowner cannot close another's inquiry. Returns rows affected > 0.
	async closeForHomeowner(
		inquiryId: number,
		homeownerId: string,
		closeReason: NonNullable<Inquiry["closeReason"]>,
	): Promise<boolean> {
		const rows = await this.db
			.update(schema.inquiries)
			.set({
				isActive: false,
				closedAt: new Date(),
				closeReason,
				dateUpdated: new Date(),
			})
			.where(
				and(
					eq(schema.inquiries.id, inquiryId),
					eq(schema.inquiries.homeownerId, homeownerId),
					eq(schema.inquiries.isActive, true),
				),
			)
			.returning({ id: schema.inquiries.id });
		return rows.length > 0;
	}
 
	// ---- Request a Callback (spec: basic_homeowner_portal) ------------------
 
	async createCallback(data: {
		homeownerId: string;
		inquiryId?: number;
		slot: HoCallbackSlot;
		note?: string;
	}): Promise<HoCallbackRequest> {
		const rows = await this.db
			.insert(schema.hoCallbackRequests)
			.values({
				homeownerId: data.homeownerId,
				inquiryId: data.inquiryId,
				slot: data.slot,
				note: data.note,
			})
			.returning();
		return rows[0];
	}
 
	static readonly ACTIVE_STATUSES = ACTIVE_STATUSES;
}