All files / dal media.dal.ts

93.84% Statements 61/65
90.9% Branches 20/22
90.47% Functions 19/21
94.73% Lines 54/57

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                  52x 52x       1x               4x                 3x 3x 2x           1x 1x 3x 3x         3x   1x       1x         1x                                                                         1x             1x       1x 1x       2x 1x 1x             6x         6x       1x       1x                               5x 5x 4x 4x               5x 3x 3x         3x 5x 2x     1x         1x       1x       2x       2x             2x                 2x       4x       4x         2x 3x 1x                     1x               1x           1x               2x   2x                     2x      
// Data Access Layer for Media (images and videos)
import { eq, sql, and, asc, inArray, or, isNull } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../db/schema";
import type { Media, NewMedia } from "../db/schema";
import type { ProjectsDal } from "./projects.dal";
 
export class MediaDal {
	constructor(
		private db: DrizzleD1Database<typeof schema>,
		private projectsDal?: ProjectsDal,
	) {}
 
	async findByRoomId(roomId: number): Promise<Media[]> {
		return this.db
			.select()
			.from(schema.media)
			.where(eq(schema.media.roomId, roomId))
			.orderBy(asc(schema.media.sortOrder));
	}
 
	async findByRoomIds(roomIds: number[]): Promise<Media[]> {
		if (roomIds.length === 0) return [];
		// Chunk the roomId list so the `inArray(...)` bind count never exceeds
		// D1's 100-parameter statement limit (#592). Without chunking, the
		// admin search-index rebuild for rooms — which calls this with the
		// full set of published room IDs — fails with a D1_ERROR once the
		// catalog has more than ~100 rooms, which also broke "Rebuild All
		// Indexes". Match the chunk size used by the same handler for
		// proIds (see apps/api/src/routes/admin/search.routes.ts) so we
		// have headroom for any other binds added to the WHERE later.
		const CHUNK_SIZE = 90;
		if (roomIds.length <= CHUNK_SIZE) {
			return this.db
				.select()
				.from(schema.media)
				.where(inArray(schema.media.roomId, roomIds))
				.orderBy(asc(schema.media.sortOrder));
		}
		const results: Media[] = [];
		for (let i = 0; i < roomIds.length; i += CHUNK_SIZE) {
			const chunk = roomIds.slice(i, i + CHUNK_SIZE);
			const rows = await this.db
				.select()
				.from(schema.media)
				.where(inArray(schema.media.roomId, chunk))
				.orderBy(asc(schema.media.sortOrder));
			results.push(...rows);
		}
		return results;
	}
 
	async findById(id: number): Promise<Media | undefined> {
		const result = await this.db
			.select()
			.from(schema.media)
			.where(eq(schema.media.id, id))
			.limit(1);
		return result[0];
	}
 
	async findByIds(ids: number[]): Promise<Media[]> {
		if (ids.length === 0) return [];
		return this.db
			.select()
			.from(schema.media)
			.where(inArray(schema.media.id, ids));
	}
 
	// Returns up to one row if the project has any media eligible for Social
	// Studio reel generation. Eligibility mirrors the auto-mode resolver in
	// internal/social-studio.routes.ts: image type, AND (isCover OR
	// photoType='after' OR photoType IS NULL). Used by the POST /social-drafts
	// preflight check (W6) to fail fast instead of letting the container 30s
	// later throw "No photos returned from API for video assembly".
	async findEligibleForReel(projectId: string): Promise<{ id: number }[]> {
		return this.db
			.select({ id: schema.media.id })
			.from(schema.media)
			.innerJoin(schema.rooms, eq(schema.media.roomId, schema.rooms.id))
			.where(
				and(
					eq(schema.rooms.projectId, projectId),
					eq(schema.media.mediaType, "image"),
					or(
						eq(schema.media.isCover, true),
						eq(schema.media.photoType, "after"),
						isNull(schema.media.photoType),
					),
				),
			)
			.limit(1);
	}
 
	async findCoverImage(roomId: number): Promise<Media | undefined> {
		const result = await this.db
			.select()
			.from(schema.media)
			.where(
				and(eq(schema.media.roomId, roomId), eq(schema.media.isCover, true)),
			)
			.limit(1);
		return result[0];
	}
 
	async create(data: NewMedia): Promise<Media> {
		const result = await this.db.insert(schema.media).values(data).returning();
		return result[0];
	}
 
	async createMany(data: NewMedia[]): Promise<Media[]> {
		if (data.length === 0) return [];
		const result = await this.db.insert(schema.media).values(data).returning();
		return result;
	}
 
	async update(
		id: number,
		data: Partial<Omit<Media, "id" | "dateCreated">>,
	): Promise<Media | undefined> {
		const result = await this.db
			.update(schema.media)
			.set({ ...data, dateUpdated: new Date() })
			.where(eq(schema.media.id, id))
			.returning();
		return result[0];
	}
 
	async delete(id: number): Promise<boolean> {
		const result = await this.db
			.delete(schema.media)
			.where(eq(schema.media.id, id))
			.returning();
		return result.length > 0;
	}
 
	/**
	 * Save funnel for media (1B): write a media update AND trigger quality score
	 * recompute on the parent project. The project's score changes whenever
	 * photo count or isCover changes — this ensures it stays fresh.
	 *
	 * Usage: call this instead of update() when the change affects photo count
	 * or cover status. Use update() directly for caption/altText edits that
	 * don't affect score inputs.
	 */
	async save(
		id: number,
		data: Partial<Omit<Media, "id" | "dateCreated">>,
	): Promise<Media | undefined> {
		const updated = await this.update(id, data);
		if (!updated) return undefined;
		await this.recomputeParentProjectScore(updated.roomId);
		return updated;
	}
 
	/**
	 * Resolve the project ID from a room and trigger quality score recompute.
	 * Non-blocking: logs failures and returns without rethrowing.
	 */
	private async recomputeParentProjectScore(roomId: number): Promise<void> {
		if (!this.projectsDal) return;
		try {
			const roomRows = await this.db
				.select({ projectId: schema.rooms.projectId })
				.from(schema.rooms)
				.where(eq(schema.rooms.id, roomId))
				.limit(1);
			const projectId = roomRows[0]?.projectId;
			if (projectId) {
				await this.projectsDal.computeAndSaveQualityScore(projectId);
			}
		} catch (err) {
			console.error("[media.dal] recomputeParentProjectScore failed", { roomId, err });
		}
	}
 
	async deleteByRoomId(roomId: number): Promise<number> {
		const result = await this.db
			.delete(schema.media)
			.where(eq(schema.media.roomId, roomId))
			.returning();
		return result.length;
	}
 
	async countByRoomId(roomId: number): Promise<number> {
		const result = await this.db
			.select({ count: sql<number>`count(*)` })
			.from(schema.media)
			.where(eq(schema.media.roomId, roomId));
		return result[0]?.count ?? 0;
	}
 
	async countByMediaType(
		roomId: number,
		mediaType: "image" | "video",
	): Promise<number> {
		const result = await this.db
			.select({ count: sql<number>`count(*)` })
			.from(schema.media)
			.where(
				and(
					eq(schema.media.roomId, roomId),
					eq(schema.media.mediaType, mediaType),
				),
			);
		return result[0]?.count ?? 0;
	}
 
	async getMaxSortOrder(roomId: number): Promise<number> {
		const result = await this.db
			.select({ maxSort: sql<number>`max(sort_order)` })
			.from(schema.media)
			.where(eq(schema.media.roomId, roomId));
		return result[0]?.maxSort ?? 0;
	}
 
	async updateSortOrder(mediaIds: number[]): Promise<void> {
		// Batch update sort order using a single CASE WHEN statement
		if (mediaIds.length === 0) return;
		const cases = mediaIds.map((id, i) => sql`WHEN ${id} THEN ${i}`);
		await this.db
			.update(schema.media)
			.set({
				sortOrder: sql`CASE ${schema.media.id} ${sql.join(cases, sql` `)} END`,
				dateUpdated: new Date(),
			})
			.where(inArray(schema.media.id, mediaIds));
	}
 
	async setCoverImage(roomId: number, mediaId: number): Promise<void> {
		// First, unset any existing cover
		await this.db
			.update(schema.media)
			.set({ isCover: false, dateUpdated: new Date() })
			.where(
				and(eq(schema.media.roomId, roomId), eq(schema.media.isCover, true)),
			);
 
		// Then set the new cover
		await this.db
			.update(schema.media)
			.set({ isCover: true, dateUpdated: new Date() })
			.where(eq(schema.media.id, mediaId));
 
		// 1B: isCover is a quality score input — trigger recompute.
		await this.recomputeParentProjectScore(roomId);
	}
 
	async moveToRoom(
		mediaId: number,
		newRoomId: number,
	): Promise<Media | undefined> {
		// Get the max sort order in the new room
		const maxSort = await this.getMaxSortOrder(newRoomId);
 
		const result = await this.db
			.update(schema.media)
			.set({
				roomId: newRoomId,
				sortOrder: maxSort + 1,
				isCover: false, // Reset cover status when moving
				dateUpdated: new Date(),
			})
			.where(eq(schema.media.id, mediaId))
			.returning();
 
		return result[0];
	}
}