All files / routes/homeowner inquiries.routes.ts

97.43% Statements 76/78
100% Branches 24/24
100% Functions 9/9
97.36% Lines 74/76

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                                      1x     23x     1x 1x           1x                                 12x 12x       1x 4x 4x 4x 4x 10x 4x                       1x 6x 6x 6x 6x 3x   3x 3x 3x 1x   2x 2x         2x 2x           4x         1x       1x 5x 5x 5x 5x 2x   3x 3x   3x 3x 1x   2x           2x 2x               2x   3x             1x             1x 5x 5x 5x 5x 1x   4x 4x 4x         4x   1x   3x   2x         1x           1x 3x 3x 3x 3x     3x 2x       2x   3x           3x 1x 1x               3x                            
// Homeowner inquiry portal API (specs: basic_homeowner_portal,
// crm_homeowner_inquiry_list, communication_history_log).
//
// Mounted at /api/homeowner/inquiries behind hoAuthSessionMiddleware +
// requireHoAuth, so every handler has an authenticated homeowner.
 
import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";
import { z } from "zod";
import { createDal } from "../../dal";
import { getDb } from "../../db";
import type { Inquiry } from "../../db/schema";
import { NotFoundError } from "../../lib/errors";
import { handleError, success } from "../../lib/response";
import { CommunicationLogService } from "../../services/communication-log.service";
 
type HoUser = { id: string; name: string; email: string };
type Variables = { hoUser: HoUser | null };
 
const app = new Hono<{ Bindings: CloudflareBindings; Variables: Variables }>();
 
function getUser(c: { get(key: "hoUser"): HoUser | null }): HoUser {
	return c.get("hoUser") as HoUser;
}
 
const MAX_ACTIVE_INQUIRIES = 3;
const MAX_MESSAGE_LEN = 2000;
 
// Homeowner-facing status labels + the primary CTA per state (spec tables).
const STATUS_DISPLAY: Record<
	Inquiry["homeownerStatus"],
	{ label: string; cta: string | null }
> = {
	submitted: { label: "Submitted — Finding Pros", cta: null },
	pros_notified: { label: "Pros Notified", cta: null },
	quotes_requested: {
		label: "Quotes on the Way",
		cta: "Upload a quote you received",
	},
	comparison_ready: {
		label: "Your Comparison is Ready",
		cta: "View Comparison",
	},
	on_hold: { label: "On Hold — We'll Be in Touch", cta: "Request a Callback" },
};
 
function decorate<T extends { homeownerStatus: Inquiry["homeownerStatus"] }>(
	row: T,
) {
	const d = STATUS_DISPLAY[row.homeownerStatus];
	return { ...row, statusLabel: d.label, primaryCta: d.cta };
}
 
// GET /api/homeowner/inquiries — the homeowner's inquiry list (default portal view)
app.get("/", async (c) => {
	try {
		const user = getUser(c);
		const dal = createDal(getDb(c.env.DB));
		const rows = await dal.homeownerInquiries.listByHomeowner(user.id);
		const activeCount = rows.filter((r) => r.isActive).length;
		return success(c, {
			inquiries: rows.map(decorate),
			activeCount,
			maxActive: MAX_ACTIVE_INQUIRIES,
			canCreate: activeCount < MAX_ACTIVE_INQUIRIES,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// GET /api/homeowner/inquiries/:id — detail with communication timeline + thread
app.get("/:id", async (c) => {
	try {
		const user = getUser(c);
		const id = Number.parseInt(c.req.param("id"), 10);
		if (!Number.isFinite(id) || id <= 0) {
			throw new NotFoundError("Inquiry", c.req.param("id"));
		}
		const dal = createDal(getDb(c.env.DB));
		const row = await dal.homeownerInquiries.getForHomeowner(id, user.id);
		if (!row) {
			throw new NotFoundError("Inquiry", String(id));
		}
		const commLog = new CommunicationLogService(dal);
		const [timeline, messages] = await Promise.all([
			commLog.getTimeline(id, "homeowner"),
			dal.inquiryMessages.listByInquiry(id),
		]);
		// Opening the thread clears the homeowner's unread count of pro messages.
		await dal.inquiryMessages.markRead(id, "homeowner").catch(() => {});
		return success(c, {
			inquiry: decorate(row),
			timeline,
			messages,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// POST /api/homeowner/inquiries/:id/messages — homeowner replies on-platform
const messageSchema = z.object({
	body: z.string().trim().min(1).max(MAX_MESSAGE_LEN),
});
 
app.post("/:id/messages", zValidator("json", messageSchema), async (c) => {
	try {
		const user = getUser(c);
		const id = Number.parseInt(c.req.param("id"), 10);
		if (!Number.isFinite(id) || id <= 0) {
			throw new NotFoundError("Inquiry", c.req.param("id"));
		}
		const { body } = c.req.valid("json");
		const dal = createDal(getDb(c.env.DB));
		// Ownership check — getForHomeowner returns undefined for other homeowners.
		const row = await dal.homeownerInquiries.getForHomeowner(id, user.id);
		if (!row) {
			throw new NotFoundError("Inquiry", String(id));
		}
		const message = await dal.inquiryMessages.create({
			inquiryId: id,
			senderType: "homeowner",
			senderId: user.id,
			body,
		});
		const commLog = new CommunicationLogService(dal);
		await commLog.logEventSafe({
			inquiryId: id,
			eventType: "message_sent",
			actorType: "homeowner",
			actorId: user.id,
			metadata: { messageId: message.id },
		});
		// TODO(Phase 3): notify the pro of the new message via CommunicationGateway.
		return success(c, message, 201);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// POST /api/homeowner/inquiries/:id/close — close an inquiry (frees a slot
// against the 3-active cap; spec: crm_homeowner_inquiry_list "Close inquiry").
// Without this the cap is a permanent lockout: nothing else sets isActive=false.
const closeSchema = z.object({
	reason: z
		.enum(["found_pro", "project_cancelled", "ops_closed"])
		.optional()
		.default("found_pro"),
});
 
app.post("/:id/close", zValidator("json", closeSchema), async (c) => {
	try {
		const user = getUser(c);
		const id = Number.parseInt(c.req.param("id"), 10);
		if (!Number.isFinite(id) || id <= 0) {
			throw new NotFoundError("Inquiry", c.req.param("id"));
		}
		const { reason } = c.req.valid("json");
		const dal = createDal(getDb(c.env.DB));
		const closed = await dal.homeownerInquiries.closeForHomeowner(
			id,
			user.id,
			reason,
		);
		if (!closed) {
			// Not owned, doesn't exist, or already closed.
			throw new NotFoundError("Inquiry", String(id));
		}
		return success(c, { closed: true });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// POST /api/homeowner/inquiries/callback — Request a Callback (spec: basic_homeowner_portal)
const callbackSchema = z.object({
	slot: z.enum(["morning", "afternoon", "evening"]),
	note: z.string().trim().max(500).optional(),
	inquiryId: z.number().int().positive().optional(),
});
 
app.post("/callback", zValidator("json", callbackSchema), async (c) => {
	try {
		const user = getUser(c);
		const { slot, note, inquiryId } = c.req.valid("json");
		const dal = createDal(getDb(c.env.DB));
		// If tied to an inquiry, confirm ownership before logging against it.
		let validInquiryId: number | undefined;
		if (inquiryId) {
			const row = await dal.homeownerInquiries.getForHomeowner(
				inquiryId,
				user.id,
			);
			if (row) validInquiryId = inquiryId;
		}
		await dal.homeownerInquiries.createCallback({
			homeownerId: user.id,
			inquiryId: validInquiryId,
			slot,
			note,
		});
		if (validInquiryId) {
			const commLog = new CommunicationLogService(dal);
			await commLog.logEventSafe({
				inquiryId: validInquiryId,
				eventType: "callback_requested",
				actorType: "homeowner",
				actorId: user.id,
				metadata: { slot },
			});
		}
		return success(
			c,
			{
				requested: true,
				message: `We'll call you ${slot}. You'll get a WhatsApp confirmation shortly.`,
			},
			201,
		);
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default app;