All files / routes/marketplace homepage.ts

94.48% Statements 120/127
84.33% Branches 70/83
94.44% Functions 17/18
94.64% Lines 106/112

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 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464                              1x                               2x                             1x 40x 40x 40x 40x 40x     40x 40x   36x               5x 2x   3x       35x 6x               35x   3x             36x 36x 36x     36x   35x 2x                             33x                                                                                                 32x 32x 31x         31x 31x 11x 3x 3x               32x 36x 1x       32x 32x 31x           31x 31x 8x 2x 2x           32x                     32x       32x   32x 32x 13x 13x   13x     13x 13x 10x     13x             13x 24x 24x 21x 24x       24x       13x 13x 13x 9x   13x 10x                 13x 10x 10x 8x 8x 7x 15x       1x   1x 1x           13x 5x 1x 1x 1x 3x       1x           13x                                       32x 32x   32x                                     32x                         32x   32x   32x                   32x 32x 13x             32x 32x   32x       5x                                                                                 5x         5x 4x 4x         32x               32x                            
// Consolidated Homepage Endpoint - Returns all homepage data in one call
import { type Context, Hono } from "hono";
import { eq, sql } from "drizzle-orm";
import { handleError, success } from "../../lib/response";
import { CACHE_KEYS, CACHE_TTL } from "../../lib/cache";
import type { ContextVariables } from "../../middleware";
import * as schema from "../../db/schema";
import { enrichProjectsWithTaxonomy } from "./project-enrichment";
import { resolvePortfolioCoversForPros } from "./pros/taxonomy-enrichment";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: ContextVariables;
};
 
const homepage = new Hono<Env>();
 
// Sentinel thrown by the cache fetcher when there are no published pros. We
// throw rather than return the empty payload so `cache.getOrSet` never reaches
// its `put` — the empty state is computed but NEVER persisted. Previously the
// empty payload was returned normally and cached to L1 (60s) + L2 KV (300s),
// so a single transient zero-result (D1 blip, mid-deploy, or a query error
// surfacing as an empty array) pinned a "no pros/projects" homepage for up to
// 5 min even after pros were present. Root cause of the empty-homepage
// incident. Cache HITS still short-circuit before the fetcher runs, so the hot
// path keeps its zero extra DB queries.
class EmptyHomepageError extends Error {}
 
// Factory (not a shared constant) so each empty response gets its own fresh
// arrays — a shared object with nested arrays could be mutated by an accidental
// push in a caller or test and leak across requests.
const createEmptyHomepage = () => ({
	featuredProject: null,
	featuredMedia: [] as Array<{ storageKey: string; roomName: string }>,
	latestProjects: [] as Awaited<ReturnType<typeof enrichProjectsWithTaxonomy>>,
	featuredPros: [] as Array<Record<string, unknown>>,
	roomCategories: [] as Array<{
		value: string;
		label: string;
		coverImage: string | null;
		projectCount: number;
	}>,
	stats: { prosCount: 0, projectsCount: 0 },
});
 
// GET /api/marketplace/homepage — all homepage data in one call
homepage.get("/", async (c) => {
	try {
		const services = c.get("services");
		const dal = c.get("dal");
		const db = c.get("db");
		const cache = c.get("cache");
 
		let data: Awaited<ReturnType<typeof buildHomepageData>>;
		try {
			data = await cache.getOrSet(
				CACHE_KEYS.MARKETPLACE_HOMEPAGE,
				() => buildHomepageData(c),
				{
					l1Ttl: CACHE_TTL.MARKETPLACE_HOMEPAGE_L1,
					l2Ttl: CACHE_TTL.MARKETPLACE_HOMEPAGE_L2,
				},
			);
		} catch (err) {
			// No published pros — return the empty homepage WITHOUT caching it.
			if (err instanceof EmptyHomepageError) {
				return success(c, createEmptyHomepage());
			}
			throw err;
		}
 
		// Pre-warm room-categories cache from homepage data (background, non-blocking)
		if (data.roomCategories?.length > 0) {
			c.executionCtx.waitUntil(
				cache.put(CACHE_KEYS.MARKETPLACE_ROOM_CATEGORIES, data.roomCategories, {
					l1Ttl: CACHE_TTL.MARKETPLACE_ROOM_CATEGORIES_L1,
					l2Ttl: CACHE_TTL.MARKETPLACE_ROOM_CATEGORIES_L2,
				}),
			);
		}
 
		return success(c, data);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Builds the populated homepage payload. Throws EmptyHomepageError when no
// pros are published so the caller can return an uncached empty response.
async function buildHomepageData(c: Context<Env>) {
	const services = c.get("services");
	const dal = c.get("dal");
	const db = c.get("db");
 
	// Step 1: Get published pro IDs (needed for all queries)
	const publishedProIds = await dal.pros.findIdsByStatus("published");
 
	if (publishedProIds.length === 0) {
		throw new EmptyHomepageError();
	}
 
	// Step 2: Run all independent queries in parallel.
	// Curation flow:
	//   - heroResult           — admin-pinned singleton; null fallback below.
	//   - latestProjectsResult — prefer isFeatured=true first; backfilled
	//     below if fewer than 12 featured projects exist.
	const [
		heroResult,
		latestProjectsResult,
		featuredProsResult,
		prosCountResult,
		projectsCountResult,
		allRoomTypes,
	] = await Promise.all([
		// Admin-pinned hero (singleton). Falls back to algorithm if empty.
		services.project.list(
			{
				status: "published",
				requirePublishedPro: true,
				isHero: true,
			},
			1,
			1,
		),
		// Featured projects first; backfill with latest below if < 12.
		// Use requirePublishedPro instead of passing publishedProIds as
		// a bind list so this filter stays safe as the pro roster grows
		// past D1's 100-parameter limit (see error-reports/2026-04-20).
		services.project.list(
			{
				status: "published",
				requirePublishedPro: true,
				isFeatured: true,
			},
			1,
			12,
		),
		// Featured pros: 6 published pros, preferring isFeatured=true
		services.pro.list(
			{
				status: "published",
				isFeatured: true,
			},
			1,
			6,
		),
		// Stats: total published pros
		db
			.select({ count: sql<number>`count(*)` })
			.from(schema.pros)
			.where(eq(schema.pros.status, "published")),
		// Stats: total published projects
		db
			.select({ count: sql<number>`count(*)` })
			.from(schema.projects)
			.where(eq(schema.projects.status, "published")),
		// All room types for categories
		db.select().from(schema.roomTypes),
	]);
 
	// If we didn't get 12 featured projects, backfill with non-featured
	// (latest-by-date). Mirrors the featured-pros backfill below.
	const projectsData = latestProjectsResult.projects;
	if (projectsData.length < 12) {
		const backfill = await services.project.list(
			{ status: "published", requirePublishedPro: true },
			1,
			12,
		);
		const seenIds = new Set(projectsData.map((p) => p.id));
		for (const project of backfill.projects) {
			if (!seenIds.has(project.id) && projectsData.length < 12) {
				projectsData.push(project);
				seenIds.add(project.id);
			}
		}
	}
 
	// Admin hero override (singleton). Ensure the hero row is enriched
	// + present in the rooms/media fetch even when it would otherwise
	// fall outside the latest-12 window.
	const adminHero = heroResult.projects[0] ?? null;
	if (adminHero && !projectsData.some((p) => p.id === adminHero.id)) {
		projectsData.unshift(adminHero);
	}
 
	// If we didn't get 6 featured pros, backfill with non-featured
	const prosData = featuredProsResult.pros;
	if (prosData.length < 6) {
		const backfillResult = await services.pro.list(
			{ status: "published" },
			1,
			6,
		);
		// Merge: featured first, then non-featured, deduplicated
		const seenIds = new Set(prosData.map((p) => p.id));
		for (const pro of backfillResult.pros) {
			if (!seenIds.has(pro.id) && prosData.length < 6) {
				prosData.push(pro);
				seenIds.add(pro.id);
			}
		}
	}
 
	// Step 3: Enrich projects with taxonomy data (includes pro info, covers)
	const enrichedProjects = await enrichProjectsWithTaxonomy(
		db,
		services,
		dal,
		projectsData,
	);
 
	// Step 4: Find featured project.
	// If admin pinned a hero, prefer it (no minimum-media gate — the
	// admin chose explicitly). Otherwise fall back to the algorithm:
	// first project with 3+ media items, then any project with media.
	let featuredProject = null;
	let featuredMedia: Array<{
		storageKey: string;
		roomName: string;
	}> = [];
 
	const projectIds = projectsData.map((p) => p.id);
	if (projectIds.length > 0) {
		const allRooms = await dal.rooms.findByProjectIds(projectIds);
		const allRoomIds = allRooms.map((r) => r.id);
		const allMedia =
			allRoomIds.length > 0 ? await dal.media.findByRoomIds(allRoomIds) : [];
 
		// Group media by project (via rooms)
		const roomToProject = new Map<number, string>();
		for (const room of allRooms) {
			roomToProject.set(room.id, room.projectId);
		}
 
		const mediaByProject = new Map<
			string,
			Array<{
				storageKey: string;
				roomId: number;
			}>
		>();
		for (const m of allMedia) {
			const projId = roomToProject.get(m.roomId);
			if (!projId) continue;
			const existing = mediaByProject.get(projId) ?? [];
			existing.push({
				storageKey: m.storageKey,
				roomId: m.roomId,
			});
			mediaByProject.set(projId, existing);
		}
 
		// Build room name lookup
		const roomNameMap = new Map<number, string>();
		const roomTypeMap = new Map<string, string>();
		for (const rt of allRoomTypes) {
			roomTypeMap.set(rt.code, rt.displayName);
		}
		for (const room of allRooms) {
			roomNameMap.set(
				room.id,
				room.name ?? roomTypeMap.get(room.roomType) ?? room.roomType,
			);
		}
 
		// Admin hero override: prefer room media; fall back to
		// project.coverImage when no rooms exist (e.g. seed data,
		// freshly-created projects). Admin intent always wins.
		if (adminHero) {
			const enrichedHero = enrichedProjects.find((p) => p.id === adminHero.id);
			if (enrichedHero) {
				const heroMedia = mediaByProject.get(adminHero.id);
				if (heroMedia && heroMedia.length > 0) {
					featuredProject = enrichedHero;
					featuredMedia = heroMedia.map((m) => ({
						storageKey: m.storageKey,
						roomName: roomNameMap.get(m.roomId) ?? "",
					}));
				E} else if (adminHero.coverImage) {
					// No room media — use the project cover image directly.
					featuredProject = enrichedHero;
					featuredMedia = [{ storageKey: adminHero.coverImage, roomName: "" }];
				}
			}
		}
 
		// Algorithm fallback: first project with 3+ media items.
		if (!featuredProject) {
			for (const project of enrichedProjects) {
				const projectMedia = mediaByProject.get(project.id);
				Eif (projectMedia && projectMedia.length >= 3) {
					featuredProject = project;
					featuredMedia = projectMedia.map((m) => ({
						storageKey: m.storageKey,
						roomName: roomNameMap.get(m.roomId) ?? "",
					}));
					break;
				}
			}
		}
 
		// Fallback: use first project with any media
		Iif (!featuredProject && enrichedProjects.length > 0) {
			for (const project of enrichedProjects) {
				const projectMedia = mediaByProject.get(project.id);
				if (projectMedia && projectMedia.length > 0) {
					featuredProject = project;
					featuredMedia = projectMedia.map((m) => ({
						storageKey: m.storageKey,
						roomName: roomNameMap.get(m.roomId) ?? "",
					}));
					break;
				}
			}
		}
	}
 
	// Step 5: Build featured pros with portfolio covers.
	// Uses the same rooms→media cascade as `/api/marketplace/pros`
	// so pros whose photos live only in rooms/media (NULL
	// `projects.coverImage`) still render a hero instead of the
	// "No portfolio yet" placeholder. See PR #740.
	const proIds = prosData.map((p) => p.id);
	const coversByProId = await resolvePortfolioCoversForPros(db, dal, proIds);
 
	const featuredPros = prosData.map((pro) => ({
		id: pro.id,
		businessName: pro.businessName,
		slug: pro.slug,
		profileImage: pro.profileImage,
		logoUrl: pro.logoUrl,
		isFeatured: pro.isFeatured,
		portfolioCovers: coversByProId.get(pro.id) ?? [],
	}));
 
	// Step 6: Build room categories with cover images and project counts.
	// Constrain rooms to those whose project belongs to a published
	// pro via a correlated EXISTS subquery — the prior
	// implementation materialized every published project ID into
	// an `inArray()` bind list which, combined with the
	// `roomType IN (...)` list below, blew past D1's 100-parameter
	// statement limit once the catalog grew (93 projects × 14 room
	// types = 107 binds). Matches the predicate pattern PR #395
	// introduced for `/api/marketplace/projects`.
	const publishedProjectExists = sql`EXISTS (
					SELECT 1 FROM ${schema.projects}
					INNER JOIN ${schema.pros} ON ${schema.pros.id} = ${schema.projects.proId}
					WHERE ${schema.projects.id} = ${schema.rooms.projectId}
					  AND ${schema.projects.status} = 'published'
					  AND ${schema.pros.status} = 'published'
				)`;
 
	let roomCategories: Array<{
		value: string;
		label: string;
		coverImage: string | null;
		projectCount: number;
	}> = [];
 
	Eif (publishedProIds.length > 0) {
		// Get room type stats: count distinct projects per room type
		const roomStats = await db
			.select({
				roomType: schema.rooms.roomType,
				projectCount: sql<number>`count(distinct ${schema.rooms.projectId})`,
			})
			.from(schema.rooms)
			.where(publishedProjectExists)
			.groupBy(schema.rooms.roomType);
 
		// Build room type label map
		const roomTypeLabelMap = new Map<string, string>();
		for (const rt of allRoomTypes) {
			roomTypeLabelMap.set(rt.code, rt.displayName);
		}
 
		// For each room type, get a cover image using the 3-tier priority:
		// 1. room_types.coverMediaId (admin-curated, plan §4 + 1A)
		// 2. media.isCover = true from any room of this type
		// 3. First media by sortOrder from any room of this type
		const roomTypeCodes = roomStats.map((rs) => rs.roomType);
		const coverByRoomType = new Map<string, string | null>();
 
		if (roomTypeCodes.length > 0) {
			// Single query: for each room type, resolve cover via COALESCE
			// over the three tiers. Uses LEFT JOINs so all room types are
			// returned even if no cover is found (NULL = no cover).
			const coverRows = await db.all<{
				roomType: string;
				storageKey: string | null;
			}>(sql`
							SELECT
								rt.code AS roomType,
								COALESCE(
									-- Tier 1: admin-curated cover media
									(SELECT m1.storage_key FROM media m1
									 WHERE m1.id = rt.cover_media_id
									 LIMIT 1),
									-- Tier 2: any isCover=true media from a room of this type
									(SELECT m2.storage_key FROM media m2
									 JOIN rooms r2 ON m2.room_id = r2.id
									 WHERE r2.room_type = rt.code
									   AND m2.is_cover = 1
									   AND EXISTS (
									     SELECT 1 FROM projects p2
									     INNER JOIN pros pr2 ON pr2.id = p2.pro_id
									     WHERE p2.id = r2.project_id
									       AND p2.status = 'published'
									       AND pr2.status = 'published'
									   )
									 ORDER BY m2.sort_order ASC
									 LIMIT 1),
									-- Tier 3: first media by sortOrder from any room of this type
									(SELECT m3.storage_key FROM media m3
									 JOIN rooms r3 ON m3.room_id = r3.id
									 WHERE r3.room_type = rt.code
									   AND EXISTS (
									     SELECT 1 FROM projects p3
									     INNER JOIN pros pr3 ON pr3.id = p3.pro_id
									     WHERE p3.id = r3.project_id
									       AND p3.status = 'published'
									       AND pr3.status = 'published'
									   )
									 ORDER BY m3.sort_order ASC
									 LIMIT 1)
								) AS storageKey
							FROM room_types rt
							WHERE rt.code IN (${sql.join(
								roomTypeCodes.map((c) => sql`${c}`),
								sql`, `,
							)})
						`);
 
			for (const row of coverRows) {
				Eif (!coverByRoomType.has(row.roomType)) {
					coverByRoomType.set(row.roomType, row.storageKey ?? null);
				}
			}
		}
 
		roomCategories = roomStats.map((rs) => ({
			value: rs.roomType,
			label: roomTypeLabelMap.get(rs.roomType) ?? rs.roomType,
			coverImage: coverByRoomType.get(rs.roomType) ?? null,
			projectCount: rs.projectCount,
		}));
	}
 
	return {
		featuredProject,
		featuredMedia,
		latestProjects: enrichedProjects,
		featuredPros,
		roomCategories,
		stats: {
			prosCount: prosCountResult[0]?.count ?? 0,
			projectsCount: projectsCountResult[0]?.count ?? 0,
		},
	};
}
 
export default homepage;