All files / routes/marketplace homepage.ts

100% Statements 99/99
92.06% Branches 58/63
100% Functions 12/12
100% Lines 89/89

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                            1x     1x 33x 33x 33x 33x 33x   33x         29x   28x 1x                                                     27x                                                                         26x 26x 25x           25x 25x 8x 2x 2x           26x                 26x       26x   26x 8x   26x   8x 8x   8x         8x 8x 7x     8x             8x 17x 17x 14x 17x       17x       8x 8x 8x 5x   8x 7x                 8x 6x 6x 3x 9x       3x         8x 3x 3x 3x 3x 5x         3x             26x   26x                                     29x 29x 7x 6x 7x 5x 5x       26x                                     26x                         26x   26x   26x                     26x 26x 9x             26x 26x   26x       5x                                                                                 5x         5x 4x 4x         26x                 26x                               30x 6x         30x   3x          
// Consolidated Homepage Endpoint - Returns all homepage data in one call
import { Hono } from "hono";
import { eq, sql, inArray, and } 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";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: ContextVariables;
};
 
const homepage = new Hono<Env>();
 
// 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");
 
		const data = await cache.getOrSet(
			CACHE_KEYS.MARKETPLACE_HOMEPAGE,
			async () => {
				// Step 1: Get published pro IDs (needed for all queries)
				const publishedProIds =
					await dal.pros.findIdsByStatus("published");
 
				if (publishedProIds.length === 0) {
					return {
						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 },
					};
				}
 
				// Step 2: Run all independent queries in parallel
				const [
					latestProjectsResult,
					featuredProsResult,
					prosCountResult,
					projectsCountResult,
					allRoomTypes,
				] = await Promise.all([
					// Latest 12 published projects. 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,
						},
						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 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 latest projects with taxonomy data (includes pro info, covers)
				const enrichedProjects = await enrichProjectsWithTaxonomy(
					db,
					services,
					dal,
					latestProjectsResult.projects,
				);
 
				// Step 4: Find featured project (first project with 3+ media items)
				// Fetch rooms and media for the latest projects to find one with rich media
				let featuredProject = null;
				let featuredMedia: Array<{
					storageKey: string;
					roomName: string;
				}> = [];
 
				const projectIds = latestProjectsResult.projects.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,
						);
					}
 
					// Find first project with 3+ media items
					for (const project of enrichedProjects) {
						const projectMedia = mediaByProject.get(project.id);
						if (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
					if (!featuredProject && enrichedProjects.length > 0) {
						for (const project of enrichedProjects) {
							const projectMedia = mediaByProject.get(project.id);
							Eif (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
				const proIds = prosData.map((p) => p.id);
				const coverPhotos =
					proIds.length > 0
						? await db
								.select({
									proId: schema.projects.proId,
									coverImage: schema.projects.coverImage,
								})
								.from(schema.projects)
								.where(
									and(
										inArray(schema.projects.proId, proIds),
										eq(
											schema.projects.status,
											"published",
										),
									),
								)
								.limit(proIds.length * 4)
						: [];
 
				const coversByProId = new Map<string, string[]>();
				for (const row of coverPhotos) {
					if (!row.coverImage) continue;
					const existing = coversByProId.get(row.proId) ?? [];
					if (existing.length < 4) {
						existing.push(row.coverImage);
						coversByProId.set(row.proId, existing);
					}
				}
 
				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,
					},
				};
			},
			{ l1Ttl: CACHE_TTL.MARKETPLACE_HOMEPAGE_L1, l2Ttl: CACHE_TTL.MARKETPLACE_HOMEPAGE_L2 },
		);
 
		// 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);
	}
});
 
export default homepage;