All files / dal projects.dal.ts

95.34% Statements 123/129
87.36% Branches 83/95
92% Functions 23/25
95.23% Lines 120/126

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 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569                                                                                              69x 69x                           23x   23x           23x         23x           3x             3x                         3x 2x     1x     20x                         20x 14x     6x       19x   19x         19x       3x       8x         8x                 3x   2x         2x 2x 3x   2x       2x         2x       1x               1x       1x             4x         4x                                   2x 2x     1x   1x                 5x 5x 5x             4x                     3x 5x 5x 5x     5x 5x   5x 5x         5x 5x   5x                                             5x                       1x   1x 1x               1x 1x                                   2x                         2x       2x       4x 4x 1x   4x       4x             1x                     42x   42x 5x   42x 2x           42x 1x           42x 2x       42x 2x 2x       2x           2x                         2x             42x         42x 5x     8x 8x   5x 4x   6x   4x 2x   2x         42x 2x       42x 4x     6x 4x 2x                 2x             38x 2x                 42x 4x     6x 4x 2x                 2x             38x 2x                   42x 2x               42x 1x       2x             42x 1x     42x      
// Data Access Layer for Projects
import { eq, like, sql, desc, and, inArray, or, getTableColumns, isNull, gt } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../db/schema";
import type { Project, NewProject } from "../db/schema";
import {
	sanitizeSearchInput,
	buildJsonArrayLikePatternSafe,
} from "../lib/utils";
import {
	computeQualityScore,
	weightsFromEnv,
	QualityScoreComputeError,
	type QualityScoreWeights,
} from "../services/quality-score";
 
export type ProjectFilters = {
	proId?: string;
	proIds?: string[];
	status?: string;
	search?: string;
	// Portfolio filters - support both single and multi-select (comma-separated)
	workedAreaIds?: string; // comma-separated for multi-select (matches any in array)
	localityId?: string;
	propertyType?: string;
	propertyTypes?: string; // comma-separated for multi-select
	budgetRange?: string;
	budgetRanges?: string; // comma-separated for multi-select
	cityId?: string;
	cityIds?: string; // comma-separated for multi-select
	// Room type filter
	roomTypes?: string; // comma-separated room type codes
	projectIds?: string[]; // for subquery results from room filtering (legacy — unsafe for large lists)
	searchProjectIds?: string[]; // project IDs inferred from search term matches (legacy — unsafe for large lists)
	// Safe predicate-style filters (preferred — avoid D1's 100-bind limit on unbounded ID lists).
	// See docs/error-reports/2026-04-20-int-prod-api-5day-analysis.md for the bug these replace.
	requirePublishedPro?: boolean; // replaces passing `proIds: publishedProIds`
	roomTypeCodes?: string[]; // replaces pre-computed project-id list from room-type join
	searchRoomTypeCodes?: string[]; // replaces pre-computed project-id list for search→room-type matching
	// Image filter
	hasCoverImage?: boolean;
	// Optional: include correlated photo count subquery
	includePhotoCount?: boolean;
};
 
export class ProjectsDal {
	constructor(
		private db: DrizzleD1Database<typeof schema>,
		private env?: Partial<{
			SCORE_WEIGHT_PHOTO: string;
			SCORE_WEIGHT_COVER: string;
			SCORE_WEIGHT_COMPLETE: string;
			SCORE_WEIGHT_RECENCY: string;
		}>,
	) {}
 
	async findAll(
		filters: ProjectFilters = {},
		offset = 0,
		limit = 20,
		hour?: number,
	): Promise<Project[]> {
		const conditions = this.buildConditions(filters);
		// Resolve hour for deterministic tiebreaker: same hour → same order within tied score buckets.
		const h = hour ?? new Date().getUTCHours();
 
		// 1C+1D: window function provides max-2-per-pro diversity by ranking within
		// partitions; outer ORDER BY then sorts by featured > rank > quality > date
		// with hour-of-day tiebreaker. Items with materially different quality scores
		// never reorder; randomness only shuffles within the same score bucket.
		const rankExpr = sql<number>`ROW_NUMBER() OVER (
			PARTITION BY projects.pro_id
			ORDER BY projects.quality_score DESC, projects.date_created DESC
		)`;
 
		if (filters.includePhotoCount) {
			// NOTE: Column-ref interpolation inside raw sql`` templates emits the
			// column name WITHOUT a table qualifier (Drizzle limitation). Using
			// qualified literals (media.room_id, rooms.id, projects.id) is required
			// to disambiguate inside a correlated subquery against the outer
			// projects table.
			const photoCountSubquery = sql<number>`(
				SELECT COUNT(*) FROM ${schema.media}
				JOIN ${schema.rooms} ON media.room_id = rooms.id
				WHERE rooms.project_id = projects.id
				AND media.media_type = 'image'
			)`.as("photoCount");
 
			const query = this.db
				.select({ ...getTableColumns(schema.projects), photoCount: photoCountSubquery })
				.from(schema.projects)
				.orderBy(
					desc(schema.projects.isFeatured),
					rankExpr,
					desc(schema.projects.qualityScore),
					desc(schema.projects.dateCreated),
					sql`(unicode(substr(projects.id, 1, 1)) + ${h}) % 1000`,
				)
				.limit(limit)
				.offset(offset);
 
			if (conditions.length > 0) {
				return query.where(and(...conditions)) as Promise<Project[]>;
			}
 
			return query as Promise<Project[]>;
		}
 
		const query = this.db
			.select()
			.from(schema.projects)
			.orderBy(
				desc(schema.projects.isFeatured),
				rankExpr,
				desc(schema.projects.qualityScore),
				desc(schema.projects.dateCreated),
				sql`(unicode(substr(projects.id, 1, 1)) + ${h}) % 1000`,
			)
			.limit(limit)
			.offset(offset);
 
		if (conditions.length > 0) {
			return query.where(and(...conditions));
		}
 
		return query;
	}
 
	async count(filters: ProjectFilters = {}): Promise<number> {
		const conditions = this.buildConditions(filters);
 
		const query = this.db
			.select({ count: sql<number>`count(*)` })
			.from(schema.projects);
 
		const result =
			conditions.length > 0
				? await query.where(and(...conditions))
				: await query;
 
		return result[0]?.count ?? 0;
	}
 
	async findById(id: string): Promise<Project | undefined> {
		const result = await this.db
			.select()
			.from(schema.projects)
			.where(eq(schema.projects.id, id))
			.limit(1);
		return result[0];
	}
 
	/**
	 * Bulk fetch projects by IDs (N+1 optimization)
	 * @param ids Array of project IDs
	 * @returns Map of projectId -> Project
	 */
	async findByIds(ids: string[]): Promise<Map<string, Project>> {
		if (ids.length === 0) return new Map();
 
		const result = await this.db
			.select()
			.from(schema.projects)
			.where(inArray(schema.projects.id, ids));
 
		const map = new Map<string, Project>();
		for (const project of result) {
			map.set(project.id, project);
		}
		return map;
	}
 
	async findBySlug(slug: string): Promise<Project | undefined> {
		const result = await this.db
			.select()
			.from(schema.projects)
			.where(eq(schema.projects.slug, slug))
			.limit(1);
		return result[0];
	}
 
	async findByProId(proId: string): Promise<Project[]> {
		return this.db
			.select()
			.from(schema.projects)
			.where(eq(schema.projects.proId, proId))
			.orderBy(schema.projects.sort, desc(schema.projects.dateCreated));
	}
 
	async create(data: NewProject): Promise<Project> {
		const result = await this.db
			.insert(schema.projects)
			.values(data)
			.returning();
		return result[0];
	}
 
	async update(
		id: string,
		data: Partial<Omit<Project, "id" | "dateCreated">>,
	): Promise<Project | undefined> {
		const result = await this.db
			.update(schema.projects)
			.set({ ...data, dateUpdated: new Date() })
			.where(eq(schema.projects.id, id))
			.returning();
		return result[0];
	}
 
	/**
	 * Save funnel (1B): write data changes AND recompute quality score.
	 *
	 * All content mutations (title, description, status, photos, etc.) route
	 * through here so the score stays fresh automatically. On compute failure
	 * the data write still succeeds — the score stays stale and the cron picks
	 * it up on the next hourly tick (2B2).
	 *
	 * DO NOT call this from incrementViewCount (E1A exemption).
	 */
	async save(
		id: string,
		data: Partial<Omit<Project, "id" | "dateCreated">>,
	): Promise<Project | undefined> {
		// Write the content changes first.
		const updated = await this.update(id, data);
		if (!updated) return undefined;
 
		// Recompute quality score and persist. Failures are non-blocking.
		await this.computeAndSaveQualityScore(id);
		// Re-fetch after score update so caller sees the fresh qualityScore.
		return this.findById(id);
	}
 
	/**
	 * Gather inputs, compute quality score, and write it back in one DB round-trip.
	 * Called from save() and from the recompute cron service.
	 * Logs failures but does NOT rethrow — keeps the parent call unaffected.
	 */
	async computeAndSaveQualityScore(id: string): Promise<void> {
		try {
			const project = await this.findById(id);
			if (!project) return;
 
			// Gemini review #1: consolidated 3 queries (media stats, room count,
			// materials presence) into a single LEFT JOIN. Photos counted with
			// COUNT(DISTINCT) on a CASE expression so non-image media doesn't
			// inflate the count; rooms counted with COUNT(DISTINCT id) so each
			// room is counted exactly once even when joined to multiple media.
			const stats = await this.db
				.select({
					photoCount: sql<number>`COUNT(DISTINCT CASE WHEN ${schema.media.mediaType} = 'image' THEN ${schema.media.id} END)`,
					hasCover: sql<number>`MAX(CASE WHEN ${schema.media.isCover} = 1 THEN 1 ELSE 0 END)`,
					roomCount: sql<number>`COUNT(DISTINCT ${schema.rooms.id})`,
					hasMaterials: sql<number>`MAX(CASE WHEN ${schema.rooms.materials} IS NOT NULL AND json_array_length(${schema.rooms.materials}) > 0 THEN 1 ELSE 0 END)`,
				})
				.from(schema.rooms)
				.leftJoin(schema.media, eq(schema.rooms.id, schema.media.roomId))
				.where(eq(schema.rooms.projectId, id));
 
			const photoCount = stats[0]?.photoCount ?? 0;
			const hasCover = (stats[0]?.hasCover ?? 0) > 0;
			const roomCount = stats[0]?.roomCount ?? 0;
			const hasMaterials = (stats[0]?.hasMaterials ?? 0) > 0;
 
			// Sanitize description for log output (3C1).
			const descRaw = project.description ?? "";
			const descriptionLength = descRaw.length;
 
			const now = new Date();
			const daysSinceUpdate = Math.floor(
				(now.getTime() - (project.dateUpdated ?? project.dateCreated).getTime()) /
					(1000 * 60 * 60 * 24),
			);
 
			const weights: QualityScoreWeights = weightsFromEnv(this.env ?? {});
			const clampEvents: Array<{ fieldName: string; originalValue: unknown; clampedValue: number }> = [];
 
			const { score } = computeQualityScore(
				{
					projectId: id,
					photoCount,
					hasCover,
					descriptionLength,
					roomCount,
					hasMaterials,
					daysSinceUpdate,
				},
				weights,
				(event) => {
					clampEvents.push(event);
					console.log(JSON.stringify({
						event: "quality_score.input.clamped",
						projectId: event.projectId,
						fieldName: event.fieldName,
						originalValue: event.originalValue,
						clampedValue: event.clampedValue,
					}));
				},
			);
 
			await this.db
				.update(schema.projects)
				.set({
					qualityScore: score,
					qualityScoreComputedAt: now,
				})
				.where(eq(schema.projects.id, id));
		} catch (err) {
			// 3C1: truncate + strip control chars from error message before logging.
			// Same regex pattern as search.routes.ts:72 — biome-ignore is intentional
			// because we genuinely want to strip control chars from user-derived strings
			// before they hit the log infrastructure.
			const sanitize = (s: string) =>
				// biome-ignore lint/suspicious/noControlCharactersInRegex: deliberately stripping control chars from user-derived error messages
				s.replace(/[\x00-\x1f]/g, "").slice(0, 200);
			Iif (err instanceof QualityScoreComputeError) {
				console.error(JSON.stringify({
					event: "quality_score.compute.failed",
					projectId: id,
					errorClass: err.name,
					errorMessage: sanitize(err.message),
				}));
			} else {
				const msg = err instanceof Error ? err.message : String(err);
				console.error(JSON.stringify({
					event: "quality_score.compute.failed",
					projectId: id,
					errorClass: err instanceof Error ? err.name : "Error",
					errorMessage: sanitize(msg),
				}));
			}
			// Non-blocking: save() continues with stale score.
		}
	}
 
	/**
	 * Find up to `limit` projects whose qualityScore is stale:
	 * never computed (qualityScoreComputedAt IS NULL) or computed before the
	 * last content edit (dateUpdated > qualityScoreComputedAt).
	 * Used by the recompute cron (2B2).
	 */
	async findStale(limit = 100): Promise<Array<{ id: string }>> {
		return this.db
			.select({ id: schema.projects.id })
			.from(schema.projects)
			.where(
				or(
					isNull(schema.projects.qualityScoreComputedAt),
					gt(schema.projects.dateUpdated, schema.projects.qualityScoreComputedAt),
				),
			)
			.limit(limit);
	}
 
	async delete(id: string): Promise<boolean> {
		const result = await this.db
			.delete(schema.projects)
			.where(eq(schema.projects.id, id))
			.returning();
		return result.length > 0;
	}
 
	async slugExists(slug: string, excludeId?: string): Promise<boolean> {
		const conditions = [eq(schema.projects.slug, slug)];
		if (excludeId) {
			conditions.push(sql`${schema.projects.id} != ${excludeId}`);
		}
		const result = await this.db
			.select({ count: sql<number>`count(*)` })
			.from(schema.projects)
			.where(and(...conditions));
		return (result[0]?.count ?? 0) > 0;
	}
 
	// E1A: viewCount is NOT a quality score input. This method DOES NOT trigger
	// recompute and DOES NOT bump qualityScoreComputedAt. Future stat fields
	// must follow the same pattern: stat writes bypass the save funnel.
	async incrementViewCount(id: string): Promise<void> {
		await this.db
			.update(schema.projects)
			.set({
				viewCount: sql`${schema.projects.viewCount} + 1`,
				lastViewedAt: new Date(),
			})
			.where(eq(schema.projects.id, id));
	}
 
	/** Builds Drizzle WHERE conditions from filter params. Shared by findAll() and count(). */
	private buildConditions(filters: ProjectFilters) {
		const conditions = [];
 
		if (filters.proId) {
			conditions.push(eq(schema.projects.proId, filters.proId));
		}
		if (filters.proIds && filters.proIds.length > 0) {
			conditions.push(inArray(schema.projects.proId, filters.proIds));
		}
		// Safe predicate equivalent of "only projects whose pro is published".
		// Uses a correlated subquery so we don't pass the pro-id list as binds
		// (which grows every time a new pro is published and eventually hits
		// D1's 100-parameter limit).
		if (filters.requirePublishedPro) {
			conditions.push(sql`EXISTS (
				SELECT 1 FROM ${schema.pros}
				WHERE ${schema.pros.id} = ${schema.projects.proId}
				  AND ${schema.pros.status} = 'published'
			)`);
		}
		if (filters.status) {
			conditions.push(
				eq(schema.projects.status, filters.status as Project["status"]),
			);
		}
		if (filters.search) {
			const sanitized = sanitizeSearchInput(filters.search);
			const searchConditions = [
				like(schema.projects.title, `%${sanitized}%`),
				like(schema.projects.description, `%${sanitized}%`),
			];
			Iif (filters.searchProjectIds && filters.searchProjectIds.length > 0) {
				searchConditions.push(inArray(schema.projects.id, filters.searchProjectIds));
			}
			// Safe equivalent of searchProjectIds: "any project whose room types
			// match the search term" — resolved server-side via subquery instead
			// of materializing an id list in app code.
			Iif (
				filters.searchRoomTypeCodes &&
				filters.searchRoomTypeCodes.length > 0
			) {
				searchConditions.push(sql`EXISTS (
					SELECT 1 FROM ${schema.rooms}
					WHERE ${schema.rooms.projectId} = ${schema.projects.id}
					  AND ${schema.rooms.roomType} IN (${sql.join(
						filters.searchRoomTypeCodes.map((c) => sql`${c}`),
						sql`, `,
					)})
				)`);
			}
			conditions.push(or(...searchConditions));
		}
 
		// Cap each comma-separated multi-select filter to 20 values. Without
		// this, a caller could send `?propertyTypes=a,b,c,...` with thousands
		// of values, blowing up WHERE clauses and burning Worker CPU. 20 is
		// well above any reasonable user-facing filter list.
		const MAX_MULTI_SELECT = 20;
 
		// Portfolio filters - support both single and multi-select
		// Worked Areas filter (JSON array field - matches any of the provided IDs)
		// Uses buildJsonArrayLikePatternSafe to support non-UUID values like 'full_home', 'kitchen'
		if (filters.workedAreaIds) {
			const areaPatterns = filters.workedAreaIds
				.split(",")
				.slice(0, MAX_MULTI_SELECT)
				.map((id) => buildJsonArrayLikePatternSafe(id.trim()))
				.filter((pattern): pattern is string => pattern !== null);
 
			if (areaPatterns.length > 0) {
				const areaConditions = areaPatterns.map(
					(pattern) =>
						sql`json_extract(${schema.projects.workedAreaIds}, '$') LIKE ${pattern} ESCAPE '\\'`,
				);
				if (areaConditions.length === 1) {
					conditions.push(areaConditions[0]);
				} else {
					conditions.push(or(...areaConditions));
				}
			}
		}
 
		if (filters.localityId) {
			conditions.push(eq(schema.projects.localityId, filters.localityId));
		}
 
		// Property Type filter
		if (filters.propertyTypes) {
			const types = filters.propertyTypes
				.split(",")
				.slice(0, MAX_MULTI_SELECT)
				.map((t) => t.trim());
			if (types.length === 1) {
				conditions.push(
					eq(
						schema.projects.propertyType,
						types[0] as NonNullable<Project["propertyType"]>,
					),
				);
			/* v8 ignore start -- V8 artifact: else-if always matches */
			} else if (types.length > 1) {
			/* v8 ignore stop */
				conditions.push(
					inArray(
						schema.projects.propertyType,
						types as NonNullable<Project["propertyType"]>[],
					),
				);
			}
		} else if (filters.propertyType) {
			conditions.push(
				eq(
					schema.projects.propertyType,
					filters.propertyType as NonNullable<Project["propertyType"]>,
				),
			);
		}
 
		// Budget Range filter
		if (filters.budgetRanges) {
			const ranges = filters.budgetRanges
				.split(",")
				.slice(0, MAX_MULTI_SELECT)
				.map((r) => r.trim());
			if (ranges.length === 1) {
				conditions.push(
					eq(
						schema.projects.budgetRange,
						ranges[0] as NonNullable<Project["budgetRange"]>,
					),
				);
			/* v8 ignore start -- V8 artifact: else-if always matches */
			} else if (ranges.length > 1) {
			/* v8 ignore stop */
				conditions.push(
					inArray(
						schema.projects.budgetRange,
						ranges as NonNullable<Project["budgetRange"]>[],
					),
				);
			}
		} else if (filters.budgetRange) {
			conditions.push(
				eq(
					schema.projects.budgetRange,
					filters.budgetRange as NonNullable<Project["budgetRange"]>,
				),
			);
		}
 
		// Project IDs filter (for room type filtering via subquery) — legacy path.
		// Safe for small lists (< ~60 ids); larger lists should use roomTypeCodes.
		if (filters.projectIds && filters.projectIds.length > 0) {
			conditions.push(inArray(schema.projects.id, filters.projectIds));
		}
 
		// Safe equivalent of the projectIds+rooms pre-computation: "project has
		// at least one room matching these codes". Resolved via correlated
		// subquery using the rooms.room_type index, so bind count is bounded by
		// the number of room-type codes (≤ ~15 from the closed enum) instead of
		// the number of matching projects (unbounded).
		if (filters.roomTypeCodes && filters.roomTypeCodes.length > 0) {
			conditions.push(sql`EXISTS (
				SELECT 1 FROM ${schema.rooms}
				WHERE ${schema.rooms.projectId} = ${schema.projects.id}
				  AND ${schema.rooms.roomType} IN (${sql.join(
					filters.roomTypeCodes.map((c) => sql`${c}`),
					sql`, `,
				)})
			)`);
		}
 
		// Cover image filter
		if (filters.hasCoverImage) {
			conditions.push(sql`${schema.projects.coverImage} IS NOT NULL`);
		}
 
		return conditions;
	}
}