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 | 1x 2x 2x 6x 6x 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 10x 10x 10x 10x 10x 10x 2x 8x 8x 8x 8x 8x 2x 6x 6x 1x 6x 6x 6x 10x 6x 4x 4x 4x 1x 4x 2x 4x 1x 1x 1x 1x 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 | // Mood-board sharing endpoints — share-link create/revoke, WhatsApp invite
// send, share-link accept/copy, member leave. Split out of mood-boards.routes.ts
// to keep that file focused on board + item CRUD.
import { parseIndianPhone } from "@interioring/utils/validation/phone";
import { Hono } from "hono";
import { createDal } from "../../../dal";
import { getDb } from "../../../db";
import { sendWhatsAppBoardInvite } from "../../../lib/communication/whatsapp-board-invite";
import type { AdapterErrorCode } from "../../../lib/communication/types";
import { SHARE_TOKEN_REGEX } from "../../../lib/share-token";
type HoUser = { id: string; name: string; email: string };
type Variables = { hoUser: HoUser };
const sharing = 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}`;
}
// POST /api/homeowner/mood-boards/:id/share — owner-only; idempotent
sharing.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
sharing.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.
sharing.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";
const sendResult = await sendWhatsAppBoardInvite(c.env, {
toPhone: e164Phone,
inviterFirstName: firstName,
boardName: board?.name ?? "a board",
url: inviteUrl,
});
if (sendResult.status === "failed") {
const mapped = mapDeliveryFailure(sendResult.errorCode);
const headers: Record<string, string> = {};
if (mapped.retryAfterSeconds !== undefined) {
headers["Retry-After"] = String(mapped.retryAfterSeconds);
}
return c.json(
{ error: mapped.message, code: mapped.code },
mapped.status,
headers,
);
}
return c.json({ ok: true });
});
// Translate adapter errorCode into HTTP status + user-facing copy. Keeps the
// route handler thin and gives the marketplace UI a stable machine-readable
// `code` field alongside the human message.
//
// SAFETY: `message` values MUST be static English strings — never interpolate
// recipient input, board names, or upstream error text. ShareMenu.tsx renders
// this directly as toast text; mixing user input here is a content-injection
// risk and shows raw Meta error messages to homeowners.
function mapDeliveryFailure(errorCode: AdapterErrorCode): {
status: 429 | 502 | 503;
code: "config" | "rate_limit" | "delivery_blocked" | "transport" | "unknown";
message: string;
retryAfterSeconds?: number;
} {
switch (errorCode) {
case "config":
return {
status: 503,
code: "config",
message:
"WhatsApp delivery is not configured. Please try copying the link instead.",
};
case "rate_limit":
case "quota":
return {
status: 429,
code: "rate_limit",
message:
"Too many invites sent. Please wait a minute and try again.",
retryAfterSeconds: 60,
};
case "template_rejected":
case "policy":
case "content_filtered":
case "suppressed":
return {
status: 502,
code: "delivery_blocked",
message:
"WhatsApp couldn't deliver this invite. Try sharing the link manually.",
};
case "transport":
return {
status: 502,
code: "transport",
message:
"WhatsApp is temporarily unavailable. Try again in a moment.",
};
case "unknown":
return {
status: 502,
code: "unknown",
message: "Couldn't send — try again.",
};
default: {
// Exhaustiveness guard — if a new AdapterErrorCode is added to
// ADAPTER_ERROR_CODES, this becomes a compile error here.
const _exhaustive: never = errorCode;
void _exhaustive;
return {
status: 502,
code: "unknown",
message: "Couldn't send — try again.",
};
}
}
}
// POST /api/homeowner/mood-boards/accept/:token — enroll current user as co-editor
sharing.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
sharing.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
sharing.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 sharing;
|