All files / routes/marketplace projects.routes.ts

99.34% Statements 152/153
97.29% Branches 72/74
100% Functions 25/25
100% Lines 147/147

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                                              1x                                       1x       1x 19x 19x 19x 19x 19x                   19x 19x 4x         19x 19x 4x 4x   4x 4x 4x   2x   4x 2x       19x                                     19x             18x               18x 18x 4x       4x 3x 3x   3x 3x   3x         3x 3x 2x     3x 3x 28x 28x 28x 28x 28x       3x 3x 3x 28x   22x             3x             18x 18x     5x 5x     19x   2x 2x       4x     2x       19x           1x           1x 10x 10x 10x 10x 10x     10x 10x   3x 3x   2x 1x     2x         8x     7x 1x       6x 6x 3x       3x 1x       3x                 3x       3x   1x                   1x 11x 11x 11x 11x 11x 11x                       11x 13x   12x 10x 1x     9x                       9x             9x                 9x 9x 6x 6x 7x   6x 5x 5x 7x   5x 7x 5x 5x 2x 7x 4x     5x 5x 5x 4x           9x           1x             1x 11x 11x 11x 11x 11x     11x 11x   3x 3x   2x 1x     2x         9x     8x 2x       6x 6x 3x       3x 1x       3x                 3x       3x   1x          
// Public Marketplace Project Routes (API Key Protected)
import { Hono } from "hono";
import {
	getCachedEnrichedProject,
	getCachedEnrichedProjectBySlug,
	precomputeEnrichedProject,
} from "../../lib/project-cache";
import {
	handleError,
	success,
	successWithPagination,
} from "../../lib/response";
import { buildPaginationMeta, getPagination } from "../../lib/utils";
import type { ContextVariables } from "../../middleware";
import { enrichProjectsWithTaxonomy } from "./project-enrichment";
import { logger } from "../../lib/logger";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: ContextVariables;
};
 
// Allowlist of fields that can be requested via ?fields= query parameter
const PROJECT_ALLOWED_FIELDS = new Set([
	"id",
	"status",
	"proId",
	"title",
	"slug",
	"description",
	"isFeatured",
	"coverImage",
	"workedAreaNames",
	"localityName",
	"pro",
	"propertyType",
	"propertySize",
	"budgetRange",
	"duration",
	"yearCompleted",
	"photos",
]);
 
const projects = new Hono<Env>();
 
// List published projects with filters and pagination
// Only shows projects from published pros
projects.get("/", async (c) => {
	try {
		const services = c.get("services");
		const dal = c.get("dal");
		const db = c.get("db");
		const { page, limit } = getPagination(
			Number(c.req.query("page") || 1),
			Number(c.req.query("limit") || 20),
		);
 
		// Room type filter — pass codes straight to the DAL, which resolves them
		// via a correlated subquery on the rooms table. We used to pre-fetch the
		// matching project-id list here and pass it back as an IN (?, ?, …)
		// bind list, which broke once the list crossed D1's 100-parameter limit
		// for broad filter combinations (see error-reports/2026-04-20).
		const roomTypesFilter = c.req.query("roomTypes");
		const roomTypeCodes = roomTypesFilter
			? roomTypesFilter.split(",").map((r) => r.trim()).filter(Boolean)
			: undefined;
 
		// Expand search to room-type names (e.g. searching "bedroom" finds projects with bedroom rooms)
		let searchRoomTypeCodes: string[] | undefined;
		const searchTerm = c.req.query("search")?.trim().toLowerCase();
		if (searchTerm && searchTerm.length >= 2) {
			const roomTypes = await dal.roomTypes.findAll();
			const matchingCodes = roomTypes
				.filter((roomType) => {
					const displayName = roomType.displayName.toLowerCase();
					const normalizedCode = roomType.code.replace(/_/g, " ").toLowerCase();
					return displayName.includes(searchTerm) || normalizedCode.includes(searchTerm);
				})
				.map((roomType) => roomType.code);
 
			if (matchingCodes.length > 0) {
				searchRoomTypeCodes = matchingCodes;
			}
		}
 
		const filters = {
			proId: c.req.query("proId"),
			requirePublishedPro: true, // only projects whose pro is published (subquery, not id-list)
			status: "published", // Only show published projects
			search: c.req.query("search"),
			searchRoomTypeCodes,
			// Multi-select taxonomy filters
			workedAreaIds: c.req.query("workedAreaIds"),
			propertyTypes: c.req.query("propertyTypes"),
			budgetRanges: c.req.query("budgetRanges"),
			// Room type filter → EXISTS subquery in DAL
			roomTypeCodes,
			// Marketplace only lists projects that will actually render — the
			// enrichment step below drops projects without a cover image, so
			// applying the filter at the DB level keeps meta.total honest
			// (matches the delivered item count).
			hasCoverImage: true,
		};
 
		const { projects: data, total } = await services.project.list(
			filters,
			page,
			limit,
		);
 
		// Enrich projects with taxonomy data and cover images
		const enrichedProjects = await enrichProjectsWithTaxonomy(
			db,
			services,
			dal,
			data,
		);
 
		// Optional: include first N photos per project (excludes cover image)
		const includePhotosParam = c.req.query("includePhotos");
		if (includePhotosParam) {
			const maxPhotos = Math.min(
				Math.max(Number.parseInt(includePhotosParam, 10) || 0, 0),
				20,
			);
			if (maxPhotos > 0) {
				const projectIds = enrichedProjects.map((p) => p.id);
				Eif (projectIds.length > 0) {
					// Batch fetch rooms and media for all projects
					const allRooms = await dal.rooms.findByProjectIds(projectIds);
					const roomIds = allRooms.map((r) => r.id);
					const allMedia =
						roomIds.length > 0
							? await dal.media.findByRoomIds(roomIds)
							: [];
 
					// Group media by project ID (via room mapping)
					const roomToProject = new Map<number, string>();
					for (const room of allRooms) {
						roomToProject.set(room.id, room.projectId);
					}
 
					const mediaByProjectId = new Map<string, typeof allMedia>();
					for (const m of allMedia) {
						const projectId = roomToProject.get(m.roomId);
						Iif (!projectId) continue;
						const existing = mediaByProjectId.get(projectId) || [];
						existing.push(m);
						mediaByProjectId.set(projectId, existing);
					}
 
					// Attach photos to each project (skip media used as cover image)
					for (const project of enrichedProjects) {
						const projectMedia = mediaByProjectId.get(project.id) || [];
						const photos = projectMedia
							.filter((m) => m.storageKey !== project.coverImage)
							.slice(0, maxPhotos)
							.map((m) => ({
								id: m.id,
								storageKey: m.storageKey,
								mediaType: m.mediaType,
								isCover: m.isCover,
								roomId: m.roomId,
							}));
						(project as Record<string, unknown>).photos = photos;
					}
				}
			}
		}
 
		// Optional field selection for payload reduction
		const fieldsParam = c.req.query("fields");
		const fields = fieldsParam
			? fieldsParam
					.split(",")
					.map((f) => f.trim())
					.filter((f) => PROJECT_ALLOWED_FIELDS.has(f))
					.slice(0, 20)
			: null;
		const responseData = fields?.length
			? enrichedProjects.map((p) => {
					const picked: Record<string, unknown> = {};
					for (const field of fields) {
						/* v8 ignore start -- defensive guard: fields pre-filtered to allowed set */
						if (field in p) {
						/* v8 ignore stop */
							picked[field] = p[field as keyof typeof p];
						}
					}
					return picked;
				})
			: enrichedProjects;
 
		return successWithPagination(
			c,
			responseData,
			buildPaginationMeta(total, page, limit),
		);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Get single published project by slug with rooms and media
// Only returns project if pro is also published
projects.get("/by-slug/:slug", async (c) => {
	try {
		const services = c.get("services");
		const dal = c.get("dal");
		const db = c.get("db");
		const slug = c.req.param("slug");
 
		// Check cache first for pre-computed enriched project
		const cached = await getCachedEnrichedProjectBySlug(slug);
		if (cached) {
			// Still need to verify pro is published (cheap single query)
			const pro = await dal.pros.findById(cached.proId);
			if (pro?.status === "published") {
				// Increment view count (fire and forget)
				services.project.incrementViewCount(cached.id).catch((err) => {
					logger.error("Failed to increment project view count:", err);
				});
 
				return success(c, { ...cached, photos: [] });
			}
		}
 
		// Cache miss - fall through to normal enrichment
		const project = await services.project.getBySlug(slug);
 
		// Only return if project is published
		if (project.status !== "published") {
			return c.json({ error: "Project not found" }, 404);
		}
 
		// Check if pro is published
		const pro = await dal.pros.findById(project.proId);
		if (!pro || pro.status !== "published") {
			return c.json({ error: "Project not found" }, 404);
		}
 
		// Increment view count (fire and forget - don't block response)
		services.project.incrementViewCount(project.id).catch((err) => {
			logger.error("Failed to increment project view count:", err);
		});
 
		// Enrich with taxonomy data (includes rooms and media)
		const [enrichedProject] = await enrichProjectsWithTaxonomy(
			db,
			services,
			dal,
			[project],
			true,
		);
 
		// Populate cache for next request (non-blocking)
		c.executionCtx.waitUntil(
			precomputeEnrichedProject(project.id, db, dal, services),
		);
 
		return success(c, { ...enrichedProject, photos: [] });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Browse projects by room type
// @deprecated Use GET /api/marketplace/projects?roomTypes=<code> instead.
//             This route is kept functional for backward compatibility.
// NOTE: This route must be registered BEFORE /:id to avoid being shadowed by the catch-all
// Only shows projects from published pros
// Accepts comma-separated room type codes, e.g. /by-room-type/master_bedroom,kids_bedroom
projects.get("/by-room-type/:roomTypeCode", async (c) => {
	try {
		const services = c.get("services");
		const dal = c.get("dal");
		const db = c.get("db");
		const roomTypeCodes = c.req.param("roomTypeCode").split(",").filter(Boolean);
		const { page, limit } = getPagination(
			Number(c.req.query("page") || 1),
			Number(c.req.query("limit") || 20),
		);
 
		/* v8 ignore start -- defensive guard: roomTypeCodes always populated in tests */
		if (roomTypeCodes.length === 0) {
			return c.json({ error: "Room type not found" }, 404);
		}
		/* v8 ignore stop */
 
		// Verify at least one room type exists
		const existChecks = await Promise.all(
			roomTypeCodes.map((code) => dal.roomTypes.exists(code)),
		);
		const validCodes = roomTypeCodes.filter((_, i) => existChecks[i]);
		if (validCodes.length === 0) {
			return c.json({ error: "Room type not found" }, 404);
		}
 
		const filters = {
			status: "published",
			// "pro is published" + "project has matching room" are resolved as
			// correlated subqueries inside the DAL so we don't materialize the
			// pro-id list or the project-id list as IN-clause binds (D1 caps at
			// 100 binds per statement). See error-reports/2026-04-20.
			requirePublishedPro: true,
			roomTypeCodes: validCodes,
			// Keep meta.total honest — enrichment below drops coverless projects.
			hasCoverImage: true,
		};
 
		const { projects: data, total } = await services.project.list(
			filters,
			page,
			limit,
		);
 
		// Enrich projects with taxonomy data
		const enrichedProjects = await enrichProjectsWithTaxonomy(
			db,
			services,
			dal,
			data,
		);
 
		// Override coverImage with room-specific cover media so each room type
		// shows a distinct image (not the same project cover for every room)
		const projectIdsInResult = enrichedProjects.map((p) => p.id);
		if (projectIdsInResult.length > 0) {
			const rooms = await dal.rooms.findByProjectIds(projectIdsInResult);
			const matchingRooms = rooms.filter((r) =>
				validCodes.includes(r.roomType),
			);
			if (matchingRooms.length > 0) {
				const roomMediaMap = new Map<string, string>(); // projectId → storageKey
				const allMedia = await dal.media.findByRoomIds(
					matchingRooms.map((r) => r.id),
				);
				for (const room of matchingRooms) {
					if (roomMediaMap.has(room.projectId)) continue;
					const cover = allMedia.find(
						(m) => m.roomId === room.id && m.isCover,
					) ?? allMedia.find((m) => m.roomId === room.id);
					if (cover) {
						roomMediaMap.set(room.projectId, cover.storageKey);
					}
				}
				for (const project of enrichedProjects) {
					const roomImage = roomMediaMap.get(project.id);
					if (roomImage) {
						(project as Record<string, unknown>).coverImage = roomImage;
					}
				}
			}
		}
 
		return successWithPagination(
			c,
			enrichedProjects,
			buildPaginationMeta(total, page, limit),
		);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Get single published project by ID with rooms and media
// NOTE: This catch-all route must be registered AFTER more specific routes like /by-room-type/:roomTypeCode
// Only returns project if pro is also published
projects.get("/:id", async (c) => {
	try {
		const services = c.get("services");
		const dal = c.get("dal");
		const db = c.get("db");
		const projectId = c.req.param("id");
 
		// Check cache first for pre-computed enriched project
		const cached = await getCachedEnrichedProject(projectId);
		if (cached) {
			// Still need to verify pro is published (cheap single query)
			const pro = await dal.pros.findById(cached.proId);
			if (pro?.status === "published") {
				// Increment view count (fire and forget)
				services.project.incrementViewCount(cached.id).catch((err) => {
					logger.error("Failed to increment project view count:", err);
				});
 
				return success(c, { ...cached, photos: [] });
			}
		}
 
		// Cache miss - fall through to normal enrichment
		const project = await services.project.getById(projectId);
 
		// Only return if project is published
		if (project.status !== "published") {
			return c.json({ error: "Project not found" }, 404);
		}
 
		// Check if pro is published
		const pro = await dal.pros.findById(project.proId);
		if (!pro || pro.status !== "published") {
			return c.json({ error: "Project not found" }, 404);
		}
 
		// Increment view count (fire and forget - don't block response)
		services.project.incrementViewCount(project.id).catch((err) => {
			logger.error("Failed to increment project view count:", err);
		});
 
		// Enrich with taxonomy data (includes rooms and media)
		const [enrichedProject] = await enrichProjectsWithTaxonomy(
			db,
			services,
			dal,
			[project],
			true,
		);
 
		// Populate cache for next request (non-blocking)
		c.executionCtx.waitUntil(
			precomputeEnrichedProject(project.id, db, dal, services),
		);
 
		return success(c, { ...enrichedProject, photos: [] });
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default projects;