All files / routes/admin/taxonomy room-types.routes.ts

66.66% Statements 48/72
80% Branches 40/50
84.61% Functions 11/13
65.71% Lines 46/70

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                                                      1x                   1x       1x                                                                                                                                                                                                                                           5x     5x               2x                       3x       3x                           4x           3x 3x 4x             3x 4x 4x                   3x 3x 1x                                       1x       1x 1x                           3x 4x 4x   4x         4x                                       1x 3x 3x 3x             1x 2x 2x 2x 2x 1x         1x                   1x 4x 4x 4x       4x 4x       4x                                                           4x                           4x              
// Room-type taxonomy endpoints — cover-image override (E9A), stats list/single
// (Lane D portal), and the photo-picker media endpoint. Extracted from
// admin/taxonomy.routes.ts to keep that file under the 500-LOC ceiling and to
// keep these single-statement / cache-aware endpoints together.
 
import { and, asc, eq, sql } from "drizzle-orm";
import { Hono, type Context } from "hono";
import { z } from "zod";
import type { Dal } from "../../../dal";
import { getDb } from "../../../db";
import * as schema from "../../../db/schema";
import { CACHE_KEYS, createDualCache } from "../../../lib/cache";
import { logger } from "../../../lib/logger";
import { handleError, success } from "../../../lib/response";
import { requireUser } from "../../../lib/utils";
import type { Services } from "../../../services";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
	};
};
 
const roomTypes = new Hono<Env>();
 
// ============================================================================
// Room Category Cover Override (E9A single-statement validation)
// ============================================================================
 
// Set or clear the editorial cover image for a room category.
// E9A: single conditional UPDATE — race-free, no SELECT-then-UPDATE pattern.
// If coverMediaId is not null, validates that the media belongs to a room of
// this category in a single statement. Returns 409 if validation fails.
const roomCoverSchema = z.object({
	coverMediaId: z.number().int().positive().nullable(),
});
 
roomTypes.put("/roomTypes/:code/cover", async (c) => {
	try {
		requireUser(c.get("user"));
 
		const code = c.req.param("code");
		const body = roomCoverSchema.safeParse(await c.req.json());
		if (!body.success) {
			return c.json(
				{ success: false, error: { message: "coverMediaId must be a positive integer or null" } },
				400,
			);
		}
 
		const { coverMediaId } = body.data;
		const db = getDb(c.env.DB);
 
		// E9A: single conditional UPDATE. If coverMediaId IS NOT NULL, validate
		// inline that the media row exists and belongs to a room of this category.
		// D1 has no transactions — SELECT-then-UPDATE has a race window if the pro
		// deletes the photo between the two statements. This single-statement form
		// is race-free and declarative.
		let result: { meta: { changes: number } };
		if (coverMediaId === null) {
			// Clearing the cover: always valid as long as the room_type exists.
			result = await db.run(sql`
				UPDATE room_types
				SET cover_media_id = NULL
				WHERE code = ${code}
			`);
		} else {
			// Setting the cover: validate media belongs to a room of this category.
			result = await db.run(sql`
				UPDATE room_types
				SET cover_media_id = ${coverMediaId}
				WHERE code = ${code}
				  AND ${coverMediaId} IN (
				    SELECT m.id FROM media m
				    JOIN rooms r ON m.room_id = r.id
				    WHERE r.room_type = ${code}
				      AND m.id = ${coverMediaId}
				  )
			`);
		}
 
		if (result.meta.changes === 0) {
			// Either: (a) room_type code doesn't exist, or (b) coverMediaId doesn't
			// belong to a room of this category (or the media was already deleted).
			return c.json(
				{
					success: false,
					error: { message: "media does not belong to a room of this category, or category does not exist" },
				},
				409,
			);
		}
 
		// Invalidate homepage + room-category cache (6B3).
		// Non-blocking: failures log + continue.
		try {
			const cache = createDualCache(c.env.KV_CACHE);
			const hour = new Date().getUTCHours();
			c.executionCtx.waitUntil(
				Promise.all([
					cache.delete(`${CACHE_KEYS.MARKETPLACE_HOMEPAGE}:h${hour}`),
					cache.delete(`${CACHE_KEYS.MARKETPLACE_ROOM_CATEGORIES}:h${hour}`),
					cache.delete(CACHE_KEYS.MARKETPLACE_HOMEPAGE),
					cache.delete(CACHE_KEYS.MARKETPLACE_ROOM_CATEGORIES),
				]).catch((err) => {
					logger.error("[admin/taxonomy.roomTypes.cover] cache invalidation failed", err);
				}),
			);
		} catch { /* executionCtx unavailable in tests */ }
 
		// Fetch and return the updated room_type row.
		const updated = await db
			.select()
			.from(schema.roomTypes)
			.where(eq(schema.roomTypes.code, code))
			.limit(1);
 
		return success(c, updated[0]);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// ============================================================================
// Room Category — list/single/media (D1B sort, photo picker)
// Defined BEFORE the generic /:type routes (in the parent file) so Hono
// matches them first.
// Lane D's portal client (apps/portal/src/lib/api/admin/room-categories.ts)
// expects RoomCategoryWithStats shape on these endpoints.
// ============================================================================
 
type RoomCategoryWithStats = {
	code: string;
	label: string;
	sortOrder: number;
	coverMediaId: number | null;
	coverMediaUrl: string | null;
	coverMediaAlt: string | null;
	coverProjectTitle: string | null;
	coverProName: string | null;
	coverUploadedAt: string | null;
	coverSource: "curated" | "algorithmic" | "empty";
	projectCount: number;
	photoCount: number;
};
 
// Build enriched room-category stats. Single trip per category-set:
// - one query for the category rows (with cover_media_id)
// - one aggregate query for projectCount + photoCount per room_type
// - one batch fetch of cover media + parent project + parent pro
// Used by both the list and single endpoints below.
async function buildRoomCategoryStats(
	c: Context<Env>,
	codes: string[] | null,
): Promise<RoomCategoryWithStats[]> {
	const db = getDb(c.env.DB);
 
	// 1. Category rows.
	const categoryRows = codes
		? await db
				.select()
				.from(schema.roomTypes)
				.where(
					and(
						eq(schema.roomTypes.isActive, true),
						sql`${schema.roomTypes.code} IN (${sql.join(
							codes.map((c) => sql`${c}`),
							sql`, `,
						)})`,
					),
				)
				.orderBy(asc(schema.roomTypes.sortOrder), asc(schema.roomTypes.displayName))
		: await db
				.select()
				.from(schema.roomTypes)
				.where(eq(schema.roomTypes.isActive, true))
				.orderBy(asc(schema.roomTypes.sortOrder), asc(schema.roomTypes.displayName));
 
	if (categoryRows.length === 0) return [];
 
	// 2. Aggregate stats: distinct project count + media count per room_type.
	// Scoped to published projects so admin sees what visitors see.
	const statsRows = await db.all<{
		room_type: string;
		project_count: number;
		photo_count: number;
	}>(sql`
		SELECT
			r.room_type AS room_type,
			COUNT(DISTINCT p.id) AS project_count,
			COUNT(m.id) AS photo_count
		FROM rooms r
		JOIN projects p ON r.project_id = p.id
		LEFT JOIN media m ON m.room_id = r.id
		WHERE p.status = 'published'
		  AND r.room_type IN (${sql.join(
				categoryRows.map((row) => sql`${row.code}`),
				sql`, `,
			)})
		GROUP BY r.room_type
	`);
 
	const statsMap = new Map<string, { projectCount: number; photoCount: number }>();
	for (const row of statsRows) {
		statsMap.set(row.room_type, {
			projectCount: Number(row.project_count) || 0,
			photoCount: Number(row.photo_count) || 0,
		});
	}
 
	// 3. Cover-media enrichment for categories that have a curated cover.
	const coverMediaIds = categoryRows
		.map((r) => r.coverMediaId)
		.filter((id): id is number => id !== null);
 
	type CoverInfo = {
		id: number;
		storageKey: string;
		altText: string | null;
		dateCreated: Date | null;
		projectTitle: string | null;
		proName: string | null;
	};
	const coverMap = new Map<number, CoverInfo>();
	if (coverMediaIds.length > 0) {
		const coverRows = await db.all<{
			id: number;
			storage_key: string;
			alt_text: string | null;
			date_created: number | null;
			project_title: string | null;
			pro_name: string | null;
		}>(sql`
			SELECT
				m.id AS id,
				m.storage_key AS storage_key,
				m.alt_text AS alt_text,
				m.date_created AS date_created,
				p.title AS project_title,
				pr.business_name AS pro_name
			FROM media m
			JOIN rooms r ON m.room_id = r.id
			JOIN projects p ON r.project_id = p.id
			JOIN pros pr ON p.pro_id = pr.id
			WHERE m.id IN (${sql.join(
				coverMediaIds.map((id) => sql`${id}`),
				sql`, `,
			)})
		`);
		for (const row of coverRows) {
			coverMap.set(Number(row.id), {
				id: Number(row.id),
				storageKey: row.storage_key,
				altText: row.alt_text,
				dateCreated: row.date_created
					? new Date(Number(row.date_created) * 1000)
					: null,
				projectTitle: row.project_title,
				proName: row.pro_name,
			});
		}
	}
 
	// 4. Assemble.
	return categoryRows.map((row) => {
		const stats = statsMap.get(row.code) ?? { projectCount: 0, photoCount: 0 };
		const cover = row.coverMediaId !== null ? coverMap.get(row.coverMediaId) ?? null : null;
		const coverSource: RoomCategoryWithStats["coverSource"] =
			cover !== null
				? "curated"
				: stats.photoCount > 0
					? "algorithmic"
					: "empty";
		return {
			code: row.code,
			label: row.displayName,
			sortOrder: row.sortOrder,
			coverMediaId: row.coverMediaId ?? null,
			coverMediaUrl: cover ? `/api/images/${cover.storageKey}` : null,
			coverMediaAlt: cover?.altText ?? null,
			coverProjectTitle: cover?.projectTitle ?? null,
			coverProName: cover?.proName ?? null,
			coverUploadedAt: cover?.dateCreated?.toISOString() ?? null,
			coverSource,
			projectCount: stats.projectCount,
			photoCount: stats.photoCount,
		};
	});
}
 
// List all room categories with stats. Lane D's room-categories list page calls
// this with ?withStats=true. Sort order is D1B (needs-attention-first) applied
// client-side in Lane D — server returns taxonomy sortOrder.
roomTypes.get("/roomTypes/list-with-stats", async (c) => {
	try {
		const stats = await buildRoomCategoryStats(c, null);
		return success(c, stats);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Single room category with stats. Lane D's detail page calls this.
roomTypes.get("/roomTypes/:code/with-stats", async (c) => {
	try {
		const code = c.req.param("code");
		const rows = await buildRoomCategoryStats(c, [code]);
		if (rows.length === 0) {
			return c.json(
				{ success: false, error: { message: "room type not found" } },
				404,
			);
		}
		return success(c, rows[0]);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Photo picker: list media available for a room category. Used by the
// /admin/room-categories/:code detail page (Lane D).
// Sorted by upload date (recent) or media id (popular placeholder until a
// real popularity signal exists).
roomTypes.get("/roomTypes/:code/media", async (c) => {
	try {
		const code = c.req.param("code");
		const limit = Math.min(
			Math.max(1, Number(c.req.query("limit")) || 100),
			500,
		);
		const sortBy = c.req.query("sortBy") === "popular" ? "popular" : "recent";
		const db = getDb(c.env.DB);
 
		// All media from rooms of this type in published projects.
		// Returns RoomCategoryMedia[] (Lane D client type).
		const rows = await db.all<{
			id: number;
			storage_key: string;
			alt_text: string | null;
			pro_name: string;
			pro_business_name: string;
			project_title: string;
			project_id: string;
			date_created: number;
		}>(sql`
			SELECT
				m.id AS id,
				m.storage_key AS storage_key,
				m.alt_text AS alt_text,
				pr.business_name AS pro_name,
				pr.business_name AS pro_business_name,
				p.title AS project_title,
				p.id AS project_id,
				m.date_created AS date_created
			FROM media m
			JOIN rooms r ON m.room_id = r.id
			JOIN projects p ON r.project_id = p.id
			JOIN pros pr ON p.pro_id = pr.id
			WHERE r.room_type = ${code}
			  AND p.status = 'published'
			  AND m.media_type = 'image'
			ORDER BY ${sortBy === "popular" ? sql`m.id DESC` : sql`m.date_created DESC`}
			LIMIT ${limit}
		`);
 
		const media = rows.map((row) => ({
			id: Number(row.id),
			url: `/api/images/${row.storage_key}`,
			altText: row.alt_text,
			proName: row.pro_name,
			proBusinessName: row.pro_business_name,
			projectTitle: row.project_title,
			projectId: row.project_id,
			uploadedAt: row.date_created
				? new Date(Number(row.date_created) * 1000).toISOString()
				: new Date(0).toISOString(),
			viewCount: 0, // Placeholder — wire up real viewCount when media-level analytics exist.
		}));
 
		return success(c, media);
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default roomTypes;