All files / dal ho-mood-boards.dal.ts

93.89% Statements 123/131
89.39% Branches 59/66
96.77% Functions 30/31
94.49% Lines 103/109

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                          76x     3x               3x 3x   2x                   2x 2x       5x 5x   5x 1x     5x               5x 5x     6x 5x 5x 2x                 2x     6x   5x       5x       3x               2x 2x   1x             1x       2x                       2x       10x                     11x 10x 10x   10x   9x                 10x                                     9x   9x                                               9x 9x 17x 17x 15x       15x       9x 9x 9x 8x 15x 12x   3x 3x             9x 9x 5x         5x 11x                   9x 9x 3x                               3x 4x 3x         9x 8x 8x 15x 12x 12x   3x 3x 3x 3x     8x       11x           11x 11x 10x       2x         2x       1x                         2x         2x             1x                                     1x 1x 3x 3x 3x   1x         3x             3x   3x                                   1x                 1x                                                                                                                   2x         2x                   3x           3x                                     1x                         1x                         2x   3x                            
import { and, asc, desc, eq, inArray, or, sql } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import type * as schema from "../db/schema";
import {
	hoMoodBoards,
	hoMoodBoardItems,
	hoMoodBoardMembers,
	projects,
	media,
} from "../db/schema";
import { nanoid } from "nanoid";
 
export class HoMoodBoardsDal {
	constructor(private db: DrizzleD1Database<typeof schema>) {}
 
	async findByUser(userId: string) {
		const boards = await this.db
			.select()
			.from(hoMoodBoards)
			.where(eq(hoMoodBoards.userId, userId))
			.orderBy(hoMoodBoards.createdAt)
			.all();
 
		// Get item counts for each board in a single query
		const boardIds = boards.map((b) => b.id);
		if (boardIds.length === 0) return [];
 
		const counts = await this.db
			.select({
				boardId: hoMoodBoardItems.boardId,
				count: sql<number>`count(*)`,
			})
			.from(hoMoodBoardItems)
			.where(inArray(hoMoodBoardItems.boardId, boardIds))
			.groupBy(hoMoodBoardItems.boardId)
			.all();
 
		const countMap = new Map(counts.map((c) => [c.boardId, Number(c.count)]));
		return boards.map((b) => ({ ...b, itemCount: countMap.get(b.id) ?? 0 }));
	}
 
	async findByUserPaginated(userId: string, opts: { limit?: number; cursor?: string }) {
		const limit = Math.min(Math.max(opts.limit ?? 20, 1), 100);
		const conditions = [eq(hoMoodBoards.userId, userId)];
 
		if (opts.cursor) {
			conditions.push(sql`${hoMoodBoards.createdAt} < ${parseInt(opts.cursor, 10)}`);
		}
 
		const rows = await this.db
			.select()
			.from(hoMoodBoards)
			.where(and(...conditions))
			.orderBy(sql`${hoMoodBoards.createdAt} DESC`)
			.limit(limit + 1)
			.all();
 
		const hasMore = rows.length > limit;
		const boards = hasMore ? rows.slice(0, limit) : rows;
 
		// Get item counts for the returned boards
		const boardIds = boards.map((b) => b.id);
		let countMap = new Map<string, number>();
		if (boardIds.length > 0) {
			const counts = await this.db
				.select({
					boardId: hoMoodBoardItems.boardId,
					count: sql<number>`count(*)`,
				})
				.from(hoMoodBoardItems)
				.where(inArray(hoMoodBoardItems.boardId, boardIds))
				.groupBy(hoMoodBoardItems.boardId)
				.all();
			countMap = new Map(counts.map((c) => [c.boardId, Number(c.count)]));
		}
 
		const data = boards.map((b) => ({ ...b, itemCount: countMap.get(b.id) ?? 0 }));
		const nextCursor =
			hasMore && boards.length > 0
				? String(Math.floor(boards[boards.length - 1].createdAt.getTime() / 1000))
				: null;
 
		return { data, nextCursor };
	}
 
	async findById(boardId: string, userId: string) {
		return this.db
			.select()
			.from(hoMoodBoards)
			.where(and(eq(hoMoodBoards.id, boardId), eq(hoMoodBoards.userId, userId)))
			.get();
	}
 
	async findByIdWithItems(boardId: string, userId: string) {
		const board = await this.findById(boardId, userId);
		if (!board) return null;
 
		const items = await this.db
			.select()
			.from(hoMoodBoardItems)
			.where(eq(hoMoodBoardItems.boardId, boardId))
			.orderBy(hoMoodBoardItems.sortOrder)
			.all();
 
		return { ...board, items };
	}
 
	async findByIdForMember(boardId: string, userId: string) {
		const row = await this.db
			.select({ board: hoMoodBoards })
			.from(hoMoodBoards)
			.innerJoin(
				hoMoodBoardMembers,
				and(
					eq(hoMoodBoardMembers.boardId, hoMoodBoards.id),
					eq(hoMoodBoardMembers.userId, userId),
				),
			)
			.where(eq(hoMoodBoards.id, boardId))
			.get();
		return row?.board ?? null;
	}
 
	async listBoardsForMember(userId: string) {
		const rows = await this.db
			.select({ board: hoMoodBoards, role: hoMoodBoardMembers.role })
			.from(hoMoodBoards)
			.innerJoin(
				hoMoodBoardMembers,
				eq(hoMoodBoardMembers.boardId, hoMoodBoards.id),
			)
			.where(eq(hoMoodBoardMembers.userId, userId))
			.orderBy(hoMoodBoards.createdAt)
			.all();
 
		const boardIds = rows.map((r) => r.board.id);
		const countMap = new Map<string, number>();
		const thumbsMap = new Map<string, string[]>();
 
		if (boardIds.length > 0) {
			// Counts (existing).
			const counts = await this.db
				.select({
					boardId: hoMoodBoardItems.boardId,
					count: sql<number>`count(*)`,
				})
				.from(hoMoodBoardItems)
				.where(inArray(hoMoodBoardItems.boardId, boardIds))
				.groupBy(hoMoodBoardItems.boardId)
				.all();
			for (const c of counts) countMap.set(c.boardId, Number(c.count));
 
			// Preview thumbnails. Powers the collage tile on the marketplace
			// /account/mood-boards page so users can see what's inside each
			// board at a glance, without N detail fetches + M enrichment
			// fetches from the client. Strategy:
			//   1. Pull all enrichable items (project/room) across all boards
			//      in one query, ordered by (boardId, sortOrder).
			//   2. Take the first 4 per board.
			//   3. Resolve project covers in one IN-query, room covers in one
			//      IN-query (joining media for the cover row).
			//   4. Slot each thumbnail back into per-board arrays in original
			//      sort order.
			//
			// Photos and pros are intentionally excluded: pros aren't valid
			// moodboard entities anymore, and `photo` items don't have a
			// stable cover lookup (they ARE the photo, not a parent with a
			// cover). When that gets unblocked the photo case can be added
			// without changing the call shape.
			const PER_BOARD_THUMB_CAP = 4;
 
			const previewItems = await this.db
				.select({
					boardId: hoMoodBoardItems.boardId,
					entityType: hoMoodBoardItems.entityType,
					entityId: hoMoodBoardItems.entityId,
				})
				.from(hoMoodBoardItems)
				.where(
					and(
						inArray(hoMoodBoardItems.boardId, boardIds),
						or(
							eq(hoMoodBoardItems.entityType, "project"),
							eq(hoMoodBoardItems.entityType, "room"),
						),
					),
				)
				.orderBy(hoMoodBoardItems.boardId, hoMoodBoardItems.sortOrder)
				.all();
 
			// Slot the first 4 per board. We'll resolve covers AFTER this so
			// the IN-list for projects/rooms only contains items we'll
			// actually render — saves a few dozen rows on power users with
			// 50+ items per board.
			type SlotItem = { entityType: "project" | "room"; entityId: string };
			const itemsByBoard = new Map<string, SlotItem[]>();
			for (const item of previewItems) {
				const existing = itemsByBoard.get(item.boardId) ?? [];
				if (existing.length >= PER_BOARD_THUMB_CAP) continue;
				existing.push({
					entityType: item.entityType as "project" | "room",
					entityId: item.entityId,
				});
				itemsByBoard.set(item.boardId, existing);
			}
 
			// Collect unique entity ids for the bulk cover lookup.
			const projectIdSet = new Set<string>();
			const roomIdSet = new Set<number>();
			for (const items of itemsByBoard.values()) {
				for (const it of items) {
					if (it.entityType === "project") {
						projectIdSet.add(it.entityId);
					} else {
						const n = Number.parseInt(it.entityId, 10);
						Eif (Number.isFinite(n)) roomIdSet.add(n);
					}
				}
			}
 
			// Project covers: one query, denormalized column. Skip when
			// nothing to look up so we don't issue an empty IN clause.
			const projectCoverMap = new Map<string, string | null>();
			if (projectIdSet.size > 0) {
				const pRows = await this.db
					.select({ id: projects.id, coverImage: projects.coverImage })
					.from(projects)
					.where(inArray(projects.id, [...projectIdSet]))
					.all();
				for (const p of pRows) {
					projectCoverMap.set(p.id, p.coverImage);
				}
			}
 
			// Room covers: one query against media, picking the cover row per
			// room. SQLite doesn't have window functions universally
			// available across D1 versions, so we just fetch all candidate
			// rows ordered (isCover DESC, sortOrder ASC) and take the first
			// per room in JS. The candidate set is bounded by 4 * boardCount
			// rooms, each with O(10) media rows on average — negligible.
			const roomCoverMap = new Map<number, string>();
			if (roomIdSet.size > 0) {
				const mRows = await this.db
					.select({
						roomId: media.roomId,
						storageKey: media.storageKey,
						isCover: media.isCover,
						sortOrder: media.sortOrder,
					})
					.from(media)
					.where(
						and(
							inArray(media.roomId, [...roomIdSet]),
							eq(media.mediaType, "image"),
						),
					)
					.orderBy(media.roomId, desc(media.isCover), asc(media.sortOrder))
					.all();
				for (const m of mRows) {
					if (!roomCoverMap.has(m.roomId)) {
						roomCoverMap.set(m.roomId, m.storageKey);
					}
				}
			}
 
			for (const [boardId, items] of itemsByBoard.entries()) {
				const thumbs: string[] = [];
				for (const it of items) {
					if (it.entityType === "project") {
						const cover = projectCoverMap.get(it.entityId) ?? null;
						if (cover) thumbs.push(cover);
					} else {
						const n = Number.parseInt(it.entityId, 10);
						Iif (!Number.isFinite(n)) continue;
						const cover = roomCoverMap.get(n);
						Eif (cover) thumbs.push(cover);
					}
				}
				thumbsMap.set(boardId, thumbs);
			}
		}
 
		const decorate = (r: { board: typeof rows[number]["board"] }) => ({
			...r.board,
			itemCount: countMap.get(r.board.id) ?? 0,
			previewThumbs: thumbsMap.get(r.board.id) ?? [],
		});
 
		const owned = rows.filter((r) => r.role === "owner").map(decorate);
		const shared = rows.filter((r) => r.role === "co_editor").map(decorate);
		return { owned, shared };
	}
 
	async findByIdPublic(boardId: string) {
		const row = await this.db
			.select()
			.from(hoMoodBoards)
			.where(eq(hoMoodBoards.id, boardId))
			.get();
		return row ?? null;
	}
 
	async listItems(boardId: string) {
		return this.db
			.select()
			.from(hoMoodBoardItems)
			.where(eq(hoMoodBoardItems.boardId, boardId))
			.orderBy(hoMoodBoardItems.sortOrder)
			.limit(200)
			.all();
	}
 
	async findMembershipsForItems(
		userId: string,
		items: Array<{ entityType: string; entityId: string }>,
	): Promise<Record<string, Array<{ boardId: string; boardName: string }>>> {
		if (items.length === 0) return {};
 
		// OR the (entityType, entityId) tuples — Drizzle lacks composite-in.
		// AND-guard via the hoMoodBoardMembers join so users only see
		// memberships on boards they belong to.
		const tupleFilters = items.map((it) =>
			and(
				eq(hoMoodBoardItems.entityType, it.entityType as "project" | "room" | "photo"),
				eq(hoMoodBoardItems.entityId, it.entityId),
			),
		);
 
		const rows = await this.db
			.select({
				entityType: hoMoodBoardItems.entityType,
				entityId: hoMoodBoardItems.entityId,
				boardId: hoMoodBoards.id,
				boardName: hoMoodBoards.name,
			})
			.from(hoMoodBoardItems)
			.innerJoin(hoMoodBoards, eq(hoMoodBoards.id, hoMoodBoardItems.boardId))
			.innerJoin(
				hoMoodBoardMembers,
				and(
					eq(hoMoodBoardMembers.boardId, hoMoodBoards.id),
					eq(hoMoodBoardMembers.userId, userId),
				),
			)
			.where(or(...tupleFilters))
			.all();
 
		const map: Record<string, Array<{ boardId: string; boardName: string }>> = {};
		for (const row of rows) {
			const key = `${row.entityType}:${row.entityId}`;
			if (!map[key]) map[key] = [];
			map[key].push({ boardId: row.boardId, boardName: row.boardName });
		}
		return map;
	}
 
	async create(userId: string, name: string, description?: string) {
		// Check if this is the user's first board
		const existing = await this.db
			.select({ id: hoMoodBoards.id })
			.from(hoMoodBoards)
			.where(eq(hoMoodBoards.userId, userId))
			.limit(1)
			.get();
 
		const isDefault = !existing;
 
		return this.db
			.insert(hoMoodBoards)
			.values({
				id: nanoid(),
				userId,
				name,
				description,
				isDefault,
			})
			.returning()
			.get();
	}
 
	async update(
		boardId: string,
		userId: string,
		data: { name?: string; description?: string },
	) {
		return this.db
			.update(hoMoodBoards)
			.set({ ...data, updatedAt: new Date() })
			.where(and(eq(hoMoodBoards.id, boardId), eq(hoMoodBoards.userId, userId)))
			.returning()
			.get();
	}
 
	async delete(boardId: string, userId: string) {
		return this.db
			.delete(hoMoodBoards)
			.where(and(eq(hoMoodBoards.id, boardId), eq(hoMoodBoards.userId, userId)))
			.run();
	}
 
	/**
	 * Promote a board to be the user's default. Clears the `isDefault` flag on
	 * all other boards owned by the user so there's exactly one default.
	 * Returns the updated target row when the board exists + is owned by this
	 * user, or `null` otherwise (so callers can 404 cleanly).
	 */
	async setDefault(boardId: string, userId: string) {
		// Confirm the board exists and is owned by this user before flipping
		// the flag — avoids clearing defaults when the id is wrong.
		const target = await this.db
			.select({ id: hoMoodBoards.id, isDefault: hoMoodBoards.isDefault })
			.from(hoMoodBoards)
			.where(and(eq(hoMoodBoards.id, boardId), eq(hoMoodBoards.userId, userId)))
			.limit(1)
			.get();
		if (!target) return null;
		if (target.isDefault) {
			// Already default — no-op.
			return this.findById(boardId, userId);
		}
 
		// Two statements: clear all other defaults for this user, then set the
		// target. SQLite doesn't support multi-row UPDATE with CASE easily.
		// There is intentionally no unique partial index enforcing "one default
		// per user" at the DB layer (verified against
		// `apps/api/src/db/schema/homeowner.ts` — the existing index is plain
		// non-unique on `userId`). In the narrow Workers case where two isolates
		// run `setDefault` + a `create` concurrently for the same user, the
		// final state could transiently have two defaults; the next call to
		// `create` or `setDefault` converges state. If that becomes load-bearing,
		// add a partial unique index in a future migration.
		await this.db
			.update(hoMoodBoards)
			.set({ isDefault: false, updatedAt: new Date() })
			.where(
				and(
					eq(hoMoodBoards.userId, userId),
					eq(hoMoodBoards.isDefault, true),
				),
			)
			.run();
		return this.db
			.update(hoMoodBoards)
			.set({ isDefault: true, updatedAt: new Date() })
			.where(and(eq(hoMoodBoards.id, boardId), eq(hoMoodBoards.userId, userId)))
			.returning()
			.get();
	}
 
	// Items
 
	async countItems(boardId: string): Promise<number> {
		const row = await this.db
			.select({ count: sql<number>`count(*)` })
			.from(hoMoodBoardItems)
			.where(eq(hoMoodBoardItems.boardId, boardId))
			.get();
		return row?.count ?? 0;
	}
 
	async addItem(
		boardId: string,
		entityType: string,
		entityId: string,
		notes?: string,
	) {
		// Get max sort order
		const maxSort = await this.db
			.select({ max: sql<number>`coalesce(max(sort_order), -1)` })
			.from(hoMoodBoardItems)
			.where(eq(hoMoodBoardItems.boardId, boardId))
			.get();
 
		return this.db
			.insert(hoMoodBoardItems)
			.values({
				boardId,
				entityType: entityType as "project" | "room" | "photo",
				entityId,
				notes,
				sortOrder: (maxSort?.max ?? -1) + 1,
			})
			.onConflictDoNothing()
			.returning()
			.get();
	}
 
	async removeItemByEntity(
		boardId: string,
		entityType: string,
		entityId: string,
	): Promise<void> {
		await this.db
			.delete(hoMoodBoardItems)
			.where(
				and(
					eq(hoMoodBoardItems.boardId, boardId),
					eq(hoMoodBoardItems.entityType, entityType as "project" | "room" | "photo"),
					eq(hoMoodBoardItems.entityId, entityId),
				),
			)
			.run();
	}
 
	async removeItem(boardId: string, itemId: number) {
		return this.db
			.delete(hoMoodBoardItems)
			.where(
				and(
					eq(hoMoodBoardItems.boardId, boardId),
					eq(hoMoodBoardItems.id, itemId),
				),
			)
			.run();
	}
 
	async reorderItems(boardId: string, itemIds: number[]) {
		// Update sort_order for each item
		await Promise.all(
			itemIds.map((id, index) =>
				this.db
					.update(hoMoodBoardItems)
					.set({ sortOrder: index })
					.where(
						and(
							eq(hoMoodBoardItems.boardId, boardId),
							eq(hoMoodBoardItems.id, id),
						),
					)
					.run(),
			),
		);
	}
}