All files / dal projects-helpers.ts

91.37% Statements 53/58
88.46% Branches 46/52
87.5% Functions 7/8
91.37% Lines 53/58

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                                                                                              42x   42x 5x   42x 2x           42x 1x           42x 2x       42x 2x 2x       2x               2x                   2x           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     42x       42x    
// Pure types, constants, and condition builder shared by ProjectsDal.
 
import { and, eq, inArray, like, or, sql } from "drizzle-orm";
import type { Project } from "../db/schema";
import * as schema from "../db/schema";
import {
	buildJsonArrayLikePatternSafe,
	sanitizeSearchInput,
} from "../lib/utils";
// Shared cap for comma-separated multi-select filters (see pros-helpers for
// rationale). Imported rather than redefined to keep a single source of truth.
import { MAX_MULTI_SELECT } from "./pros-helpers";
 
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;
	// Curation filters (marketplace homepage admin levers)
	isFeatured?: boolean;
	isHero?: boolean;
	// Optional: include correlated photo count subquery
	includePhotoCount?: boolean;
};
 
/** Builds Drizzle WHERE conditions from filter params. Shared by findAll() and count(). */
export function buildProjectConditions(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));
	}
 
	// 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`);
	}
 
	// Curation filters (marketplace homepage admin levers).
	// isHero hits a partial index; isFeatured is already used by the
	// marketplace-listing rank-by-quality ORDER BY at projects.dal.ts:63,83.
	Iif (filters.isFeatured !== undefined) {
		conditions.push(eq(schema.projects.isFeatured, filters.isFeatured));
	}
	Iif (filters.isHero !== undefined) {
		conditions.push(eq(schema.projects.isHero, filters.isHero));
	}
 
	return conditions;
}