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 | 1x 1x 1x 13x 7x 1x 2x 2x 2x 3x 1x 1x 1x 2x 2x 2x 2x 1x 1x 1x 2x 2x 2x 2x 1x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 14x 2x 1x 1x 18x 15x 2x 1x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 1x 1x 2x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 3x 3x 2x 2x 2x 3x 3x 4x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 6x 6x 6x 6x 3x 3x 3x 6x 6x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 2x 2x 2x 1x 1x 1x 2x 2x 1x 1x 3x 3x 3x 3x 3x 3x 1x 2x 2x 2x 2x 5x 5x 2x 2x 2x 1x 1x 1x 2x 1x | // Admin Taxonomy Management Routes
import { and, asc, eq } from "drizzle-orm";
import { Hono } from "hono";
import type { Dal } from "../../dal";
import * as schema from "../../db/schema";
import { getDb } from "../../db";
import { NotFoundError, ValidationError } from "../../lib/errors";
import { handleError, success } from "../../lib/response";
import { requireUser } from "../../lib/utils";
import { createDualCache } from "../../lib/cache";
import { invalidateEntity } from "../../lib/cache-invalidation";
import type { Services } from "../../services";
import roomTypesRoutes from "./taxonomy/room-types.routes";
import {
validateEnumFields,
validateRequiredFields,
validateTaxonomyType,
} from "./taxonomy.validators";
import { getStrategyForType } from "./taxonomy/taxonomy-strategy-factory";
type Env = {
Bindings: CloudflareBindings;
Variables: {
user: { id: string; name: string; email: string } | null;
session: unknown;
dal: Dal;
services: Services;
};
};
const taxonomy = new Hono<Env>();
// Taxonomy types whose rows back the marketplace SEO pages (city / zone /
// locality / service / BHK). Mutating one must drop the cached SEO payloads or
// the change stays invisible to visitors for up to 24h (the KV L2 TTL). The SEO
// keyspace is small (~100 keys) and admin edits are infrequent, so a prefix
// purge is simpler and safer than reconstructing each exact key from entity
// relationships — and it also clears the parent city/zone list pages that embed
// the edited child.
const SEO_TAXONOMY_TYPES = new Set([
"cities",
"zones",
"localities",
"cityServices",
"cityBhkTypes",
]);
// Taxonomy types whose mutations affect the localities lookup cache
// (MARKETPLACE.localitiesAll). Cities and zones are included because the
// lookup endpoint enriches each locality match with zone+city display names;
// a city rename that isn't reflected in the cache would show stale names.
const LOCALITY_CACHE_TYPES = new Set(["cities", "zones", "localities"]);
async function invalidateSeoCacheForType(
env: CloudflareBindings,
type: string,
): Promise<void> {
if (!SEO_TAXONOMY_TYPES.has(type)) return;
await createDualCache(env.KV_CACHE).deletePattern("seo:");
}
// ============================================================================
// Special Routes for Hierarchical Taxonomies
// NOTE: These must be defined BEFORE generic routes like /:type/:id
// ============================================================================
// Get all root-level service categories (no parent)
taxonomy.get("/serviceCategories/roots", async (c) => {
try {
const db = getDb(c.env.DB);
// SQLite treats NULL as a unique value, so we need to check for NULL explicitly
const allCategories = await db
.select()
.from(schema.serviceCategories)
.where(eq(schema.serviceCategories.isActive, true))
.orderBy(
asc(schema.serviceCategories.sortOrder),
asc(schema.serviceCategories.name),
);
// Filter for root categories (those without a parent)
const roots = allCategories.filter((cat) => !cat.parentId);
return success(c, roots);
} catch (err) {
return handleError(c, err);
}
});
// Get zones for a specific city
taxonomy.get("/zones/by-city/:cityId", async (c) => {
try {
const cityId = c.req.param("cityId");
const db = getDb(c.env.DB);
const zones = await db
.select()
.from(schema.zones)
.where(
and(eq(schema.zones.cityId, cityId), eq(schema.zones.isActive, true)),
)
.orderBy(asc(schema.zones.sortOrder), asc(schema.zones.name));
return success(c, zones);
} catch (err) {
return handleError(c, err);
}
});
// Get localities for a specific zone
taxonomy.get("/localities/by-zone/:zoneId", async (c) => {
try {
const zoneId = c.req.param("zoneId");
const db = getDb(c.env.DB);
const localities = await db
.select()
.from(schema.localities)
.where(
and(
eq(schema.localities.zoneId, zoneId),
eq(schema.localities.isActive, true),
),
)
.orderBy(asc(schema.localities.sortOrder), asc(schema.localities.name));
return success(c, localities);
} catch (err) {
return handleError(c, err);
}
});
// Get child service categories for a parent
taxonomy.get("/serviceCategories/by-parent/:parentId", async (c) => {
try {
const parentId = c.req.param("parentId");
const db = getDb(c.env.DB);
const children = await db
.select()
.from(schema.serviceCategories)
.where(
and(
eq(schema.serviceCategories.parentId, parentId),
eq(schema.serviceCategories.isActive, true),
),
)
.orderBy(
asc(schema.serviceCategories.sortOrder),
asc(schema.serviceCategories.name),
);
return success(c, children);
} catch (err) {
return handleError(c, err);
}
});
// Room-type endpoints (cover override + stats list/single + photo picker)
// live in taxonomy/room-types.routes.ts. Must be mounted BEFORE the generic
// /:type routes below so Hono matches the more specific paths first.
taxonomy.route("/", roomTypesRoutes);
// ============================================================================
// Generic CRUD Handlers
// ============================================================================
// List all items for a taxonomy type
taxonomy.get("/:type", async (c) => {
try {
const type = c.req.param("type");
validateTaxonomyType(type);
const db = getDb(c.env.DB);
const strategy = getStrategyForType(type);
const table = strategy.getTable();
const nameField = strategy.getNameField();
// Get query parameters for filtering
const isActiveParam = c.req.query("isActive");
const includeInactive = c.req.query("includeInactive") === "true";
// Build the query based on isActive filter
let items: (typeof table.$inferSelect)[];
if (!includeInactive && isActiveParam !== "false") {
items = await db
.select()
.from(table)
.where(eq(table.isActive, true))
.orderBy(asc(table.sortOrder), asc(nameField));
} else if (isActiveParam === "false") {
items = await db
.select()
.from(table)
.where(eq(table.isActive, false))
.orderBy(asc(table.sortOrder), asc(nameField));
} else {
items = await db
.select()
.from(table)
.orderBy(asc(table.sortOrder), asc(nameField));
}
// Transform items using strategy (adds id/name for roomTypes, no-op for standard types)
const transformed = items.map((item) => strategy.transformItem(item));
return success(c, transformed);
} catch (err) {
return handleError(c, err);
}
});
// Get single item by ID
taxonomy.get("/:type/:id", async (c) => {
try {
const type = c.req.param("type");
const id = c.req.param("id");
validateTaxonomyType(type);
const db = getDb(c.env.DB);
const strategy = getStrategyForType(type);
const table = strategy.getTable();
const items = await db
.select()
.from(table)
.where(strategy.buildFindByIdQuery(id))
.limit(1);
const item = items[0];
if (!item) {
throw new NotFoundError(type, id);
}
return success(c, strategy.transformItem(item));
} catch (err) {
return handleError(c, err);
}
});
// Create new item
taxonomy.post("/:type", async (c) => {
try {
const type = c.req.param("type");
validateTaxonomyType(type);
requireUser(c.get("user"));
const body = await c.req.json<Record<string, unknown>>();
// Validate required fields
validateRequiredFields(type, body);
validateEnumFields(type, body);
const db = getDb(c.env.DB);
const strategy = getStrategyForType(type);
const table = strategy.getTable();
// Prepare data using strategy (handles ID generation for standard types, code for roomTypes)
const data = strategy.prepareInsertData(body);
// Insert the new item
const result = await db
.insert(table)
.values(data as never)
.returning();
// A new SEO entity (e.g. locality) must appear on its parent's cached
// list page without waiting out the TTL.
await invalidateSeoCacheForType(c.env, type);
// Bust the localities lookup cache when a city, zone, or locality is
// created so the /lookup endpoint doesn't serve stale results.
if (LOCALITY_CACHE_TYPES.has(type)) {
try {
const cache = createDualCache(c.env.KV_CACHE);
c.executionCtx.waitUntil(invalidateEntity(cache, "locality"));
} catch {
/* executionCtx unavailable in tests */
}
}
// Transform for response (adds id/name for roomTypes, no-op for standard types)
const item = result[0];
return success(c, strategy.transformItem(item), 201);
} catch (err) {
return handleError(c, err);
}
});
// Update item
taxonomy.put("/:type/:id", async (c) => {
try {
const type = c.req.param("type");
const id = c.req.param("id");
validateTaxonomyType(type);
requireUser(c.get("user"));
const body = await c.req.json<Record<string, unknown>>();
// Validate enum fields if they're being updated
validateEnumFields(type, body);
const db = getDb(c.env.DB);
const strategy = getStrategyForType(type);
const table = strategy.getTable();
// Check if item exists
const existing = await db
.select()
.from(table)
.where(strategy.buildFindByIdQuery(id))
.limit(1);
if (!existing[0]) {
throw new NotFoundError(type, id);
}
// Prepare update data using strategy (removes primary key fields)
const updateData = strategy.prepareUpdateData(body);
// Update the item
const result = await db
.update(table)
.set(updateData as never)
.where(strategy.buildFindByIdQuery(id))
.returning();
// SEO pages cache the marketplace city/zone/locality/service/bhk payloads;
// drop them so an admin edit shows immediately instead of after the TTL.
await invalidateSeoCacheForType(c.env, type);
// Bust the localities lookup cache when a city, zone, or locality is
// updated so the /lookup endpoint doesn't serve stale results.
if (LOCALITY_CACHE_TYPES.has(type)) {
try {
const cache = createDualCache(c.env.KV_CACHE);
c.executionCtx.waitUntil(invalidateEntity(cache, "locality"));
} catch {
/* executionCtx unavailable in tests */
}
}
// Transform for response (adds id/name for roomTypes, no-op for standard types)
const item = result[0];
return success(c, strategy.transformItem(item));
} catch (err) {
return handleError(c, err);
}
});
// Soft delete (set isActive = false)
taxonomy.delete("/:type/:id", async (c) => {
try {
const type = c.req.param("type");
const id = c.req.param("id");
validateTaxonomyType(type);
requireUser(c.get("user"));
const db = getDb(c.env.DB);
const strategy = getStrategyForType(type);
const table = strategy.getTable();
// Check if item exists
const existing = await db
.select()
.from(table)
.where(strategy.buildFindByIdQuery(id))
.limit(1);
if (!existing[0]) {
throw new NotFoundError(type, id);
}
// Soft delete by setting isActive to false
const result = await db
.update(table)
.set({ isActive: false } as never)
.where(strategy.buildFindByIdQuery(id))
.returning();
// Drop the cached SEO payloads so the removed entity stops appearing.
await invalidateSeoCacheForType(c.env, type);
// Bust the localities lookup cache when a city, zone, or locality is
// deleted so the /lookup endpoint doesn't serve stale results.
if (LOCALITY_CACHE_TYPES.has(type)) {
try {
const cache = createDualCache(c.env.KV_CACHE);
c.executionCtx.waitUntil(invalidateEntity(cache, "locality"));
} catch {
/* executionCtx unavailable in tests */
}
}
const item = result[0];
return success(c, {
message: `${type} item deleted successfully`,
item: strategy.transformItem(item),
});
} catch (err) {
return handleError(c, err);
}
});
// Reorder items (update sort_order for multiple items)
taxonomy.patch("/:type/reorder", async (c) => {
try {
const type = c.req.param("type");
validateTaxonomyType(type);
requireUser(c.get("user"));
const body = await c.req.json<{
items: Array<{ id: string; sortOrder: number }>;
}>();
if (!body.items || !Array.isArray(body.items)) {
throw new ValidationError("Request body must contain an 'items' array");
}
const db = getDb(c.env.DB);
const strategy = getStrategyForType(type);
const table = strategy.getTable();
// Update each item's sortOrder using strategy to handle primary key differences
const updatePromises = body.items.map((item) => {
const { condition, data } = strategy.buildReorderUpdate(
item.id,
item.sortOrder,
);
return db
.update(table)
.set(data as never)
.where(condition);
});
await Promise.all(updatePromises);
// Reordering changes the order children render on cached SEO list pages.
await invalidateSeoCacheForType(c.env, type);
// Bust the localities lookup cache when cities, zones, or localities
// are reordered (order is part of the cached payload).
if (LOCALITY_CACHE_TYPES.has(type)) {
try {
const cache = createDualCache(c.env.KV_CACHE);
c.executionCtx.waitUntil(invalidateEntity(cache, "locality"));
} catch {
/* executionCtx unavailable in tests */
}
}
return success(c, {
message: `Reordered ${body.items.length} items successfully`,
count: body.items.length,
});
} catch (err) {
return handleError(c, err);
}
});
export default taxonomy;
|