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 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 | 1x 4x 4x 2x 2x 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 4x 4x 4x 4x 4x 4x 2x 2x 2x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 2x 2x 2x 1x 2x 2x 1x 6x 6x 6x 6x 6x 6x 2x 4x 4x 4x 4x 4x 2x 2x 2x 1x 2x 2x 2x 6x 2x 1x 7x 7x 7x 1x 6x 6x 7x 7x 7x 6x 2x 4x 4x 2x 2x 2x 1x 5x 5x 5x 1x 4x 4x 4x 4x 1x 3x 1x 2x 2x 1x 1x 1x 1x 1x 3x 1x 1x 3x 3x 3x 3x 3x 3x 1x 2x 1x 1x 1x | import { Hono } from "hono";
import { zValidator } from "@hono/zod-validator";
import { z } from "zod";
import { createDal } from "../../dal";
import { getDb } from "../../db";
import { success } from "../../lib/response";
import { NotFoundError } from "../../lib/errors";
import { handleError } from "../../lib/response";
import { SHARE_TOKEN_REGEX } from "../../lib/share-token";
import { parseIndianPhone } from "@interioring/utils/validation/phone";
import { sendWhatsAppBoardInvite } from "../../lib/communication/whatsapp-board-invite";
type HoUser = { id: string; name: string; email: string };
type Variables = { hoUser: HoUser; };
const app = new Hono<{ Bindings: CloudflareBindings; Variables: Variables }>();
function buildShareUrl(marketplaceUrl: string | undefined, token: string) {
const base = marketplaceUrl ?? "http://localhost:7003";
return `${base}/boards/share/${token}`;
}
function buildInviteUrl(marketplaceUrl: string | undefined, token: string) {
const base = marketplaceUrl ?? "http://localhost:7003";
return `${base}/boards/invite/${token}`;
}
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 });
});
// POST /api/homeowner/mood-boards/:id/share — owner-only; idempotent
app.post("/:id/share", 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 || role.role !== "owner") {
return c.json({ error: "Only the owner can share" }, 403);
}
const existing = await dal.hoMoodBoardShares.findActiveByBoardId(boardId);
if (existing) {
return c.json({
token: existing.id,
url: buildShareUrl(c.env.MARKETPLACE_URL, existing.id),
});
}
const created = await dal.hoMoodBoardShares.create({
boardId,
createdByUser: user.id,
userName: user.name ?? user.email ?? "user",
});
return c.json({
token: created.id,
url: buildShareUrl(c.env.MARKETPLACE_URL, created.id),
});
});
// DELETE /api/homeowner/mood-boards/:id/share — owner-only; idempotent
app.delete("/:id/share", 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 || role.role !== "owner") {
return c.json({ error: "Only the owner can stop sharing" }, 403);
}
const existing = await dal.hoMoodBoardShares.findActiveByBoardId(boardId);
if (existing) {
await dal.hoMoodBoardShares.revoke(existing.id);
}
await dal.hoMoodBoardMembers.deleteNonOwners(boardId);
return c.json({ ok: true });
});
// POST /api/homeowner/mood-boards/:id/share/send-whatsapp — owner types a
// phone number, server fires a WhatsApp template message with the invite URL.
// Reuses an active share if one exists; auto-creates otherwise so the caller
// never has to pre-call POST /share.
app.post("/:id/share/send-whatsapp", async (c) => {
const user = c.get("hoUser");
const boardId = c.req.param("id");
const body = await c.req.json().catch(() => ({}));
const rawPhone = typeof body?.phone === "string" ? body.phone : "";
const parsedPhone = parseIndianPhone(rawPhone);
if (!parsedPhone || parsedPhone.type !== "mobile") {
return c.json({ error: "Enter a 10-digit Indian mobile number" }, 400);
}
const e164Phone = parsedPhone.e164;
const db = getDb(c.env.DB);
const dal = createDal(db);
const role = await dal.hoMoodBoardMembers.findRole(boardId, user.id);
if (!role || role.role !== "owner") {
return c.json({ error: "Only the owner can send invites" }, 403);
}
// Reuse or auto-create an active share.
let share = await dal.hoMoodBoardShares.findActiveByBoardId(boardId);
if (!share) {
share = await dal.hoMoodBoardShares.create({
boardId,
createdByUser: user.id,
userName: user.name ?? user.email ?? "user",
});
}
const board = await dal.hoMoodBoards.findByIdPublic(boardId);
const inviteUrl = buildInviteUrl(c.env.MARKETPLACE_URL, share.id);
const firstName =
(user.name ?? "").trim().split(/\s+/)[0] || "Someone";
await sendWhatsAppBoardInvite(c.env, {
toPhone: e164Phone,
inviterFirstName: firstName,
boardName: board?.name ?? "a board",
url: inviteUrl,
});
return c.json({ ok: true });
});
// POST /api/homeowner/mood-boards/accept/:token — enroll current user as co-editor
app.post("/accept/:token", async (c) => {
const user = c.get("hoUser");
const token = c.req.param("token");
if (!SHARE_TOKEN_REGEX.test(token)) {
return c.json({ error: "Malformed token" }, 400);
}
const body = await c.req.json().catch(() => ({}));
const via: "share_link" | "direct_invite" =
body?.via === "direct_invite" ? "direct_invite" : "share_link";
const db = getDb(c.env.DB);
const dal = createDal(db);
const share = await dal.hoMoodBoardShares.findByToken(token);
if (!share || share.revokedAt) {
return c.json({ error: "This board is no longer shared" }, 410);
}
const existing = await dal.hoMoodBoardMembers.findRole(share.boardId, user.id);
if (existing) {
return c.json({ boardId: share.boardId, role: existing.role });
}
await dal.hoMoodBoardMembers.createCoEditor({
boardId: share.boardId,
userId: user.id,
invitedVia: via,
});
return c.json({ boardId: share.boardId, role: "co_editor" });
});
// POST /api/homeowner/mood-boards/copy-share/:token — create a fresh owned copy
app.post("/copy-share/:token", async (c) => {
const user = c.get("hoUser");
const token = c.req.param("token");
if (!SHARE_TOKEN_REGEX.test(token)) {
return c.json({ error: "Malformed token" }, 400);
}
const db = getDb(c.env.DB);
const dal = createDal(db);
const share = await dal.hoMoodBoardShares.findByToken(token);
if (!share || share.revokedAt) {
return c.json({ error: "This board is no longer shared" }, 410);
}
// Owner-no-op: checked BEFORE loading source/items so the owner
// doesn't accidentally create a duplicate copy of their own board.
if (share.createdByUser === user.id) {
return c.json({ boardId: share.boardId, copied: false });
}
const source = await dal.hoMoodBoards.findByIdPublic(share.boardId);
if (!source) {
return c.json({ error: "This board is no longer shared" }, 410);
}
const sourceItems = await dal.hoMoodBoards.listItems(share.boardId);
const copy = await dal.hoMoodBoards.create(
user.id,
`${source.name} (copy)`,
source.description ?? undefined,
);
// New boards created via dal.hoMoodBoards.create don't auto-create a
// member row — explicit owner row keeps member-aware queries consistent.
await dal.hoMoodBoardMembers.createOwner({ boardId: copy.id, userId: user.id });
// Serial loop (not Promise.all): addItem does a max-sort-order lookup
// internally; parallel calls would race and produce non-deterministic order.
for (const it of sourceItems) {
await dal.hoMoodBoards.addItem(
copy.id,
it.entityType,
it.entityId,
it.notes ?? undefined,
);
}
return c.json({ boardId: copy.id, copied: true });
});
// POST /api/homeowner/mood-boards/:id/leave — co-editor exits a shared board
app.post("/:id/leave", 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 a member" }, 404);
}
if (role.role === "owner") {
return c.json(
{ error: "Owners can't leave — delete the board instead" },
400,
);
}
await dal.hoMoodBoardMembers.deleteMember(boardId, user.id);
return c.json({ ok: true });
});
export default app;
|