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 | 70x 70x 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 | // Data Access Layer for Projects
import { eq, 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 {
computeQualityScore,
weightsFromEnv,
QualityScoreComputeError,
type QualityScoreWeights,
} from "../services/quality-score";
import { type ProjectFilters, buildProjectConditions } from "./projects-helpers";
export type { ProjectFilters };
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 = buildProjectConditions(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 = buildProjectConditions(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));
}
}
|