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 | 1x 23x 23x 23x 11x 1x 17x 6x 6x 6x 5x 5x 4x 4x 1x 1x 4x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 6x 6x 1x 9x 12x 8x 8x 4x 8x 1x 1x 4x 4x 4x 4x 4x 1x 3x 1x 12x 12x 12x 12x 12x 12x 9x 12x 5x 5x 7x 6x 1x 1x 17x 17x 17x 17x 17x 17x 17x 17x 17x 7x 6x 6x 6x 11x 10x 10x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 1x 1x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x | // Pro Project Routes - Manage own projects
import { Hono } from "hono";
import type { Dal } from "../../dal";
import type { getDb } from "../../db";
import type { Services } from "../../services";
import { type DualCache, CACHE_TTL, MARKETPLACE } from "../../lib/cache";
import {
invalidateProjectCache,
precomputeEnrichedProject,
} from "../../lib/project-cache";
import { invalidateProjectsListCache } from "../../lib/project-mutations";
import {
success,
successWithPagination,
handleError,
} from "../../lib/response";
import {
getPagination,
buildPaginationMeta,
requireUser,
} from "../../lib/utils";
import { z } from "zod";
import {
validateProjectTitle,
projectTitleErrorMessage,
normalizeProjectTitle,
} from "@interioring/utils/validation/project-title";
import {
validatePropertySize,
propertySizeErrorMessage,
normalizePropertySize,
} from "@interioring/utils/validation/property-size";
import { BadRequestError } from "../../lib/errors";
import { requireProAccess, resourceCreationRateLimit } from "../../middleware";
// Accepts only titles that survive validateProjectTitle (no symbol-only,
// digit-only, or length violations). The schema also *normalizes* the title
// (trim + collapse internal whitespace) so non-Portal API consumers can't
// persist `" Modern Kitchen "` literally — the parsed output is what
// reaches the DAL. validateProjectTitle owns every length and content check;
// we deliberately do NOT layer a `.min/.max` on top because zod v4 no longer
// short-circuits on prior failures and the duplicate error messages are
// noisy in 400 responses.
const projectTitleSchema = z
.string()
.transform((v) => normalizeProjectTitle(v))
.superRefine((v, ctx) => {
const err = validateProjectTitle(v);
if (err) {
ctx.addIssue({
code: "custom",
message: projectTitleErrorMessage(err),
});
}
});
// Property size is optional and free-form (so "3 BHK", "Studio", "2400 sq ft"
// and bare numbers all pass) but must contain at least one alphanumeric
// character — otherwise pure-symbol input like "@#$%" / "---" leaks onto the
// public marketplace project listings (issue #638). null / undefined / empty
// pass through unchanged so partial-update routes keep no-op-on-absent
// semantics; non-empty values are normalized (trim + collapse) before persist.
const propertySizeSchema = z
.string()
.nullish()
.transform((val, ctx) => {
if (val === undefined) return undefined;
Iif (val === null) return null;
const normalized = normalizePropertySize(val);
if (normalized.length === 0) return null;
const err = validatePropertySize(normalized);
if (err) {
ctx.addIssue({
code: "custom",
message: propertySizeErrorMessage(err),
});
return z.NEVER;
}
return normalized;
});
type Env = {
Bindings: CloudflareBindings;
Variables: {
user: { id: string; name: string; email: string } | null;
session: unknown;
dal: Dal;
services: Services;
db: ReturnType<typeof getDb>;
cache: DualCache;
proId: string;
proRole: string;
};
};
// Dynamic year validator. Re-evaluates `getFullYear()` on every `.parse()`
// instead of baking it at module load — Cloudflare Workers isolates can live
// for hours/days, so a static max-year would over-reject valid input after a
// year rollover until the next deploy. Used by both create + update schemas.
const yearCompletedSchema = z
.number()
.int()
.min(1900, "yearCompleted must be 1900 or later")
.refine((y) => y <= new Date().getFullYear(), {
message: "yearCompleted cannot be in the future",
})
.nullish();
const createProjectSchema = z.object({
title: projectTitleSchema,
description: z.string().max(5000).nullish(),
clientTestimonial: z.string().max(5000).nullish(),
status: z.enum(["draft", "published"]).optional(),
propertyType: z.string().max(50).nullish(),
budgetRange: z.string().max(50).nullish(),
scope: z.array(z.string().max(50)).max(20).optional(),
area: z.number().positive().nullish(),
areaUnit: z.string().max(20).nullish(),
yearCompleted: yearCompletedSchema,
durationMonths: z.number().int().min(0).max(120).nullish(),
location: z.string().max(200).nullish(),
roomTypeId: z.string().nullish(),
});
// Update schema covers every field the portal's Edit-Project modals can send
// (BasicInfo, ScopeAreas, LocationProperty, BudgetTimeline, AdditionalInfo, Seo,
// RoomCardsGrid). Fields not listed here are silently dropped by Zod's default
// `.strip()` strategy — including server-managed fields the portal echoes back
// from a previous GET response (id, slug, proId, viewCount, qualityScore,
// qualityScoreComputedAt, dateCreated, dateUpdated, userCreated, userUpdated,
// photoCount, sourceImportId, sourceUrl, isFeatured, bhkCount, lastViewedAt).
// Without stripping these the DAL's `.set(...)` either rejects unknown columns
// at runtime or, worse, silently overwrites curation/scoring fields with stale
// portal-cached values.
const updateProjectSchema = z.object({
title: projectTitleSchema.optional(),
description: z.string().max(5000).nullish(),
clientTestimonial: z.string().max(5000).nullish(),
status: z.enum(["draft", "published", "archived"]).optional(),
propertyType: z
.enum(["apartment", "villa", "independent_house", "commercial"])
.nullish(),
propertySize: propertySizeSchema,
projectAreaSqft: z.number().int().positive().nullish(),
budgetRange: z
.enum(["under_1l", "1_3l", "3_5l", "5_10l", "above_10l"])
.nullish(),
duration: z.string().max(50).nullish(),
scope: z.array(z.enum(["design", "material", "execution"])).max(3).nullish(),
workedAreaIds: z.array(z.string().max(100)).max(50).nullish(),
materialTagIds: z.array(z.string().max(100)).max(50).nullish(),
styleTagIds: z.array(z.string().max(100)).max(50).nullish(),
localityId: z.string().max(100).nullish(),
yearCompleted: yearCompletedSchema,
isBeforeAfter: z.boolean().optional(),
useRooms: z.boolean().optional(),
defaultRoomId: z.number().int().positive().nullish(),
coverImage: z.string().max(500).nullish(),
metaTitle: z.string().max(60).nullish(),
metaDescription: z.string().max(160).nullish(),
ogImage: z.string().max(500).nullish(),
sort: z.number().int().nullish(),
});
const projects = new Hono<Env>();
// List own projects (with cover photos)
projects.get("/:proId/projects", requireProAccess, async (c) => {
try {
const services = c.get("services");
const proId = c.get("proId");
const cache = c.get("cache");
const { page, limit } = getPagination(
Number(c.req.query("page") || 1),
Number(c.req.query("limit") || 20),
);
const status = c.req.query("status");
const search = c.req.query("search");
const includePhotoCountParam = c.req.query("includePhotoCount");
const includePhotoCount =
includePhotoCountParam === "1" || includePhotoCountParam === "true";
const filters = {
proId,
status,
search,
...(includePhotoCount ? { includePhotoCount: true as const } : {}),
};
// Use KV cache for default list requests (page 1, no filters, no extras)
const isDefaultList = page === 1 && !status && !search && !includePhotoCount;
const cacheKey = MARKETPLACE.proProjects(proId);
if (isDefaultList) {
const cached = await cache.get<{
data: unknown[];
pagination: unknown;
}>(cacheKey);
if (cached) {
return c.json({ success: true, ...cached });
}
}
const { projects: data, total } = await services.project.list(
filters,
page,
limit,
);
// Use denormalized coverImage column directly from project data
const projectsWithCovers = data.map((project) => ({
...project,
coverImage: project.coverImage || null,
}));
const pagination = buildPaginationMeta(total, page, limit);
// Cache default list in KV
if (isDefaultList) {
c.executionCtx.waitUntil(
cache.put(
cacheKey,
{ data: projectsWithCovers, pagination },
{ l1Ttl: CACHE_TTL.PRO_PROJECTS_L1, l2Ttl: CACHE_TTL.PRO_PROJECTS_L2 },
),
);
}
return successWithPagination(c, projectsWithCovers, pagination);
} catch (err) {
return handleError(c, err);
}
});
// Get single project (must belong to pro)
projects.get(
"/:proId/projects/:projectId",
requireProAccess,
async (c) => {
try {
const services = c.get("services");
const proId = c.get("proId");
const projectId = c.req.param("projectId");
// Verify project belongs to pro
const project = await services.project.verifyProOwnership(
projectId,
proId,
);
return success(c, { ...project, photos: [] });
} catch (err) {
return handleError(c, err);
}
},
);
// Create new project
projects.post("/:proId/projects", requireProAccess, resourceCreationRateLimit, async (c) => {
try {
const services = c.get("services");
const user = requireUser(c.get("user"));
const proId = c.get("proId");
const body = createProjectSchema.parse(await c.req.json());
// Strip null values to undefined (service types use optional, not nullable)
const cleaned = Object.fromEntries(
Object.entries(body).filter(([, v]) => v !== null),
);
// Force proId to current pro
const project = await services.project.create(
{ ...cleaned, proId } as Parameters<typeof services.project.create>[0],
user.id,
);
c.executionCtx.waitUntil(
invalidateProjectsListCache(c.get("cache"), proId),
);
return success(c, project, 201);
} catch (err) {
if (err instanceof z.ZodError) {
return handleError(c, new BadRequestError(`Validation failed: ${err.issues.map((e) => e.message).join(", ")}`));
}
return handleError(c, err);
}
});
// Update own project
projects.put(
"/:proId/projects/:projectId",
requireProAccess,
async (c) => {
try {
const services = c.get("services");
const dal = c.get("dal");
const db = c.get("db");
const user = requireUser(c.get("user"));
const proId = c.get("proId");
const projectId = c.req.param("projectId");
// Validate against the update schema — silently strips server-managed
// fields (id, slug, qualityScore, dateCreated, etc.) that the portal
// may echo back from a prior GET response. Without stripping, those
// flow into the DAL save() funnel and cause cryptic Drizzle errors
// or stale-overwrite bugs on curation/scoring columns.
const body = updateProjectSchema.parse(await c.req.json());
// Verify project belongs to pro
await services.project.verifyProOwnership(projectId, proId);
const project = await services.project.update(projectId, body, user.id);
// Invalidate project list cache and re-compute enriched cache
c.executionCtx.waitUntil(
invalidateProjectsListCache(c.get("cache"), proId),
);
c.executionCtx.waitUntil(
precomputeEnrichedProject(projectId, db, dal, services),
);
return success(c, project);
} catch (err) {
if (err instanceof z.ZodError) {
return handleError(
c,
new BadRequestError(
`Validation failed: ${err.issues.map((e) => e.message).join(", ")}`,
),
);
}
return handleError(c, err);
}
},
);
// Delete own project
projects.delete(
"/:proId/projects/:projectId",
requireProAccess,
async (c) => {
try {
const services = c.get("services");
const proId = c.get("proId");
const projectId = c.req.param("projectId");
// Verify project belongs to pro and get project data for slug
const project = await services.project.verifyProOwnership(
projectId,
proId,
);
await services.project.delete(projectId);
// Invalidate both project list cache and enriched project cache
c.executionCtx.waitUntil(
invalidateProjectsListCache(c.get("cache"), proId),
);
c.executionCtx.waitUntil(invalidateProjectCache(projectId, project.slug));
return success(c, { message: "Project deleted successfully" });
} catch (err) {
return handleError(c, err);
}
},
);
// Publish own project
projects.post(
"/:proId/projects/:projectId/publish",
requireProAccess,
async (c) => {
try {
const services = c.get("services");
const dal = c.get("dal");
const db = c.get("db");
const user = requireUser(c.get("user"));
const proId = c.get("proId");
const projectId = c.req.param("projectId");
// Verify project belongs to pro
await services.project.verifyProOwnership(projectId, proId);
const project = await services.project.publish(projectId, user.id);
// Invalidate project list cache and pre-compute enriched project cache
c.executionCtx.waitUntil(
invalidateProjectsListCache(c.get("cache"), proId),
);
c.executionCtx.waitUntil(
precomputeEnrichedProject(projectId, db, dal, services),
);
// Auto-reel-on-publish removed (2026-04-27): publishing a project
// no longer enqueues a Social Studio reel. Pros now opt in
// explicitly via "New Reel" on the /social-studio page. Eliminates:
// - surprise compute spend on every publish
// - the producer-route bug class entirely (queue.send rollback,
// stuck-pending drafts on side-effect failure, partial-success
// drift between publish and reel state)
// - the publish→draft→queue→DO chain that's hard to reason about
// when the publish succeeds but the side-effect fails silently
// Manual create at POST /api/pro/:proId/social-drafts is the
// single supported path; it has all the C2/C3/D3 protections.
return success(c, project);
} catch (err) {
return handleError(c, err);
}
},
);
// Archive own project
projects.post(
"/:proId/projects/:projectId/archive",
requireProAccess,
async (c) => {
try {
const services = c.get("services");
const user = requireUser(c.get("user"));
const proId = c.get("proId");
const projectId = c.req.param("projectId");
// Verify project belongs to pro
await services.project.verifyProOwnership(projectId, proId);
const project = await services.project.archive(projectId, user.id);
// Invalidate both project list cache and enriched project cache
c.executionCtx.waitUntil(
invalidateProjectsListCache(c.get("cache"), proId),
);
c.executionCtx.waitUntil(invalidateProjectCache(projectId, project.slug));
return success(c, project);
} catch (err) {
return handleError(c, err);
}
},
);
// Unarchive own project (move back to draft)
projects.post(
"/:proId/projects/:projectId/unarchive",
requireProAccess,
async (c) => {
try {
const services = c.get("services");
const user = requireUser(c.get("user"));
const proId = c.get("proId");
const projectId = c.req.param("projectId");
// Verify project belongs to pro
await services.project.verifyProOwnership(projectId, proId);
const project = await services.project.unarchive(projectId, user.id);
// Invalidate both project list cache and enriched project cache
c.executionCtx.waitUntil(
invalidateProjectsListCache(c.get("cache"), proId),
);
c.executionCtx.waitUntil(invalidateProjectCache(projectId, project.slug));
return success(c, project);
} catch (err) {
return handleError(c, err);
}
},
);
export default projects;
|