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 | 2x 2x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 4x 5x 5x 1x 3x 3x 3x 3x 3x 3x 3x 1x 4x 4x 4x 3x 57x 57x 57x 57x 54x 54x 54x 54x 57x 3x 1x 2x 2x 2x 2x 1x 7x 7x 7x 7x 7x 7x 2x 5x 5x 1x 5x 5x 5x 1x 5x 5x 5x 7x 1x 4x 4x 4x 4x 4x 4x 1x 3x 7x 3x 1x 4x 4x 4x 4x 4x 4x 4x 1x 3x 3x 3x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 1x 8x 8x 8x 2x 6x 6x 1x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 1x 2x 2x 1x 3x 3x 3x 3x 3x 3x 3x 1x 2x 2x 1x | import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";
import { z } from "zod";
import { createDal } from "../../dal";
import { getDb } from "../../db";
import { NotFoundError } from "../../lib/errors";
import { handleError, success } from "../../lib/response";
import sharingRoutes from "./mood-boards/sharing.routes";
type HoUser = { id: string; name: string; email: string };
type Variables = { hoUser: HoUser };
function buildShareUrl(marketplaceUrl: string | undefined, token: string) {
const base = marketplaceUrl ?? "http://localhost:7003";
return `${base}/boards/share/${token}`;
}
const app = new Hono<{ Bindings: CloudflareBindings; Variables: Variables }>();
const createBoardSchema = z.object({
name: z.string().min(1).max(100),
description: z.string().max(500).optional(),
});
const updateBoardSchema = z.object({
name: z.string().min(1).max(100).optional(),
description: z.string().max(500).optional(),
});
// Mood boards hold visual inspiration only — pros aren't images and belong in
// favorites/following, not collections. The enum here is the enforcement
// point; the UI narrows the same way for type safety.
const addItemSchema = z.object({
entityType: z.enum(["project", "room", "photo"]),
entityId: z.string().min(1),
notes: z.string().max(500).optional(),
});
const reorderSchema = z.object({
itemIds: z.array(z.number()),
});
const byEntitySchema = z.object({
entityType: z.enum(["project", "room", "photo"]),
entityId: z.string().min(1),
});
// GET /api/homeowner/mood-boards
// V2 shape: { owned: [...], shared: [...] }. Owned boards are enriched with
// `hasActiveShare` via a single batch lookup; co-editors don't need that flag.
app.get("/", async (c) => {
const user = c.get("hoUser");
const db = getDb(c.env.DB);
const dal = createDal(db);
const { owned, shared } = await dal.hoMoodBoards.listBoardsForMember(user.id);
const activeShareIds = await dal.hoMoodBoardShares.findActiveBoardIds(
owned.map((b) => b.id),
);
const ownedWithShare = owned.map((b) => ({
...b,
hasActiveShare: activeShareIds.has(b.id),
}));
return success(c, { owned: ownedWithShare, shared });
});
// POST /api/homeowner/mood-boards
app.post("/", zValidator("json", createBoardSchema), async (c) => {
const user = c.get("hoUser");
const { name, description } = c.req.valid("json");
const db = getDb(c.env.DB);
const dal = createDal(db);
const board = await dal.hoMoodBoards.create(user.id, name, description);
// V2 introduced member-aware access gates. Every board must have at
// least one member row (the owner) or it's unreachable via findByIdForMember.
await dal.hoMoodBoardMembers.createOwner({
boardId: board.id,
userId: user.id,
});
return success(c, board, 201);
});
// GET /api/homeowner/mood-boards/memberships?items=project:p1,room:r5
// Batch endpoint for card grids — one call per page hydration, returns
// a map of entityType:entityId → [{boardId, boardName}, ...]. Capped at
// 50 items per call. Declared BEFORE /:id so Hono's declared-order matcher
// doesn't treat "memberships" as a board id.
app.get("/memberships", async (c) => {
const user = c.get("hoUser");
const raw = c.req.query("items") ?? "";
if (!raw) return c.json({ memberships: {} });
const tuples = raw
.split(",")
.map((s) => s.trim())
.filter((s) => s.length > 0)
.map((s) => {
const idx = s.indexOf(":");
if (idx <= 0 || idx === s.length - 1) return null;
const entityType = s.slice(0, idx);
const entityId = s.slice(idx + 1);
Iif (!["project", "room", "photo"].includes(entityType)) return null;
return { entityType, entityId };
})
.filter((t): t is { entityType: string; entityId: string } => t !== null);
if (tuples.length > 50) {
return c.json({ error: "Too many items (max 50)" }, 400);
}
const db = getDb(c.env.DB);
const dal = createDal(db);
const memberships = await dal.hoMoodBoards.findMembershipsForItems(
user.id,
tuples,
);
return c.json({ memberships });
});
// GET /api/homeowner/mood-boards/:id
// V2 shape adds `role` ("owner" | "co_editor") and `share` ({ active, url })
// so the board detail UI can decide which affordances to render (Share button
// for owners, Leave for co-editors) without a second round-trip.
app.get("/:id", async (c) => {
const user = c.get("hoUser");
const boardId = c.req.param("id");
const db = getDb(c.env.DB);
const dal = createDal(db);
// Member-aware access: owner OR co-editor via hoMoodBoardMembers.
const board = await dal.hoMoodBoards.findByIdForMember(boardId, user.id);
if (!board) {
return handleError(c, new NotFoundError("Mood board not found"));
}
const items = await dal.hoMoodBoards.listItems(boardId);
// Photo items are stored with the media row id as entityId. The SSR
// consumer needs both the parent roomId (to fetch the enriched room
// shape) and the photo's storageKey (to override the room's cover with
// the specific pinned photo). Resolve both here so the consumer sees
// `photoMeta` populated. Without this, /account/mood-boards/[id]
// silently dropped photo items because its enrichment branch only
// handled project/room.
// Dedupe via Set — the same photo could legitimately appear once per
// item, but we don't want to re-query for duplicates if list integrity
// ever drifts. One batched WHERE id IN (...) lookup beats N round trips.
const photoEntityIds = Array.from(
new Set(
items
.filter((it) => it.entityType === "photo")
.map((it) => Number.parseInt(it.entityId, 10))
.filter((n) => Number.isFinite(n) && n > 0),
),
);
const photoMediaMap = new Map<
number,
{ roomId: number; storageKey: string }
>();
Iif (photoEntityIds.length > 0) {
const mediaRows = await dal.media.findByIds(photoEntityIds);
for (const m of mediaRows) {
photoMediaMap.set(m.id, {
roomId: m.roomId,
storageKey: m.storageKey,
});
}
}
const itemsWithPhotoMeta = items.map((it) => {
Eif (it.entityType !== "photo") return it;
const meta = photoMediaMap.get(Number.parseInt(it.entityId, 10));
return { ...it, photoMeta: meta ?? null };
});
const role = await dal.hoMoodBoardMembers.findRole(boardId, user.id);
const activeShare = await dal.hoMoodBoardShares.findActiveByBoardId(boardId);
const share = {
active: !!activeShare,
url: activeShare
? buildShareUrl(c.env.MARKETPLACE_URL, activeShare.id)
: null,
};
return success(c, {
...board,
items: itemsWithPhotoMeta,
role: role?.role ?? null,
share,
});
});
// GET /api/homeowner/mood-boards/:id/members — collaborator list for strip UI.
// Any member (owner OR co-editor) can view. Non-members get 404 to avoid
// leaking board existence. Response is PII-reduced: no user IDs, first-name
// only, plus role + acceptedAt (unix seconds) for the UI.
app.get("/:id/members", async (c) => {
const user = c.get("hoUser");
const boardId = c.req.param("id");
const db = getDb(c.env.DB);
const dal = createDal(db);
const role = await dal.hoMoodBoardMembers.findRole(boardId, user.id);
if (!role) {
return c.json({ error: "Not found" }, 404);
}
const rows = await dal.hoMoodBoardMembers.listMembersWithNames(boardId);
const members = rows.map((r) => ({
role: r.role,
firstName: (r.userName ?? "").trim().split(/\s+/)[0] || "Someone",
acceptedAt: r.acceptedAt
? Math.floor(r.acceptedAt.getTime() / 1000)
: null,
}));
return c.json({ members });
});
// PUT /api/homeowner/mood-boards/:id
app.put("/:id", zValidator("json", updateBoardSchema), async (c) => {
const user = c.get("hoUser");
const boardId = c.req.param("id");
const data = c.req.valid("json");
const db = getDb(c.env.DB);
const dal = createDal(db);
// Member-aware access check — co-editors may update name/description.
const board = await dal.hoMoodBoards.findByIdForMember(boardId, user.id);
if (!board) {
return handleError(c, new NotFoundError("Mood board not found"));
}
// Update against the board's owner so the existing owner-gated DAL call
// still succeeds when a co-editor is performing the edit.
const updated = await dal.hoMoodBoards.update(boardId, board.userId, data);
Iif (!updated) {
return handleError(c, new NotFoundError("Mood board not found"));
}
return success(c, updated);
});
// DELETE /api/homeowner/mood-boards/:id
app.delete("/:id", async (c) => {
const user = c.get("hoUser");
const boardId = c.req.param("id");
const db = getDb(c.env.DB);
const dal = createDal(db);
// Owner-only: co-editors can edit but not delete (per V2 permissions).
const board = await dal.hoMoodBoards.findById(boardId, user.id);
if (!board) {
return handleError(c, new NotFoundError("Mood board not found"));
}
await dal.hoMoodBoards.delete(boardId, user.id);
return success(c, { deleted: true });
});
// POST /api/homeowner/mood-boards/:id/set-default — #376
// Owner-only (mirrors DELETE): the DAL's `setDefault` filters by
// `hoMoodBoards.userId === user.id`, so co-editors calling this get a 404
// rather than a 403 — the board "doesn't exist" from their ownership view.
// Promote the target board to the user's default; clears `isDefault` on all
// other boards owned by the user so exactly one stays default.
app.post("/:id/set-default", async (c) => {
const user = c.get("hoUser");
const boardId = c.req.param("id");
const db = getDb(c.env.DB);
const dal = createDal(db);
const updated = await dal.hoMoodBoards.setDefault(boardId, user.id);
if (!updated) {
return handleError(c, new NotFoundError("Mood board not found"));
}
return success(c, updated);
});
// POST /api/homeowner/mood-boards/:id/items
app.post("/:id/items", zValidator("json", addItemSchema), async (c) => {
const user = c.get("hoUser");
const boardId = c.req.param("id");
const { entityType, entityId, notes } = c.req.valid("json");
const db = getDb(c.env.DB);
const dal = createDal(db);
// Member-aware access check — co-editors may add items.
const board = await dal.hoMoodBoards.findByIdForMember(boardId, user.id);
if (!board) {
return handleError(c, new NotFoundError("Mood board not found"));
}
// Cap at 200 items to prevent unbounded listItems() queries on the public
// share endpoint (N+1 risk: each item fires 1-3 D1 round-trips).
const MAX_BOARD_ITEMS = 200;
const currentCount = await dal.hoMoodBoards.countItems(boardId);
if (currentCount >= MAX_BOARD_ITEMS) {
return c.json(
{
success: false,
error: {
code: "CONFLICT",
message: `Board has reached the maximum of ${MAX_BOARD_ITEMS} items`,
},
},
409,
);
}
const item = await dal.hoMoodBoards.addItem(boardId, entityType, entityId, notes);
return success(c, item, 201);
});
// DELETE /api/homeowner/mood-boards/:id/items/by-entity
// Removes an item identified by (entityType, entityId) rather than numeric
// id. The picker UI toggles chips by tuple, not by item row id. Declared
// BEFORE the /:id/items/:itemId dynamic route so Hono's declaration-order
// matcher doesn't try to parse "by-entity" as an integer itemId.
app.delete(
"/:id/items/by-entity",
zValidator("json", byEntitySchema),
async (c) => {
const user = c.get("hoUser");
const boardId = c.req.param("id");
const { entityType, entityId } = c.req.valid("json");
const db = getDb(c.env.DB);
const dal = createDal(db);
const board = await dal.hoMoodBoards.findByIdForMember(boardId, user.id);
if (!board) {
return handleError(c, new NotFoundError("Mood board not found"));
}
await dal.hoMoodBoards.removeItemByEntity(boardId, entityType, entityId);
return c.json({ ok: true });
},
);
// DELETE /api/homeowner/mood-boards/:id/items/:itemId
app.delete("/:id/items/:itemId", async (c) => {
const user = c.get("hoUser");
const boardId = c.req.param("id");
const itemId = Number.parseInt(c.req.param("itemId"), 10);
const db = getDb(c.env.DB);
const dal = createDal(db);
// Member-aware access check — co-editors may remove items.
const board = await dal.hoMoodBoards.findByIdForMember(boardId, user.id);
if (!board) {
return handleError(c, new NotFoundError("Mood board not found"));
}
await dal.hoMoodBoards.removeItem(boardId, itemId);
return success(c, { removed: true });
});
// PATCH /api/homeowner/mood-boards/:id/items/reorder
app.patch("/:id/items/reorder", zValidator("json", reorderSchema), async (c) => {
const user = c.get("hoUser");
const boardId = c.req.param("id");
const { itemIds } = c.req.valid("json");
const db = getDb(c.env.DB);
const dal = createDal(db);
// Member-aware access check — co-editors may reorder items.
const board = await dal.hoMoodBoards.findByIdForMember(boardId, user.id);
if (!board) {
return handleError(c, new NotFoundError("Mood board not found"));
}
await dal.hoMoodBoards.reorderItems(boardId, itemIds);
return success(c, { reordered: true });
});
// Sharing endpoints (share-link create/revoke, WhatsApp invite, accept/copy
// share-link, leave board) live in mood-boards/sharing.routes.ts.
app.route("/", sharingRoutes);
export default app;
|