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 | 5x 5x 5x 18x 29x 3x 3x 3x 3x 5x 4x 4x 4x 12x 4x 61x 39x 39x 4x 39x 4x 39x 3x 3x 39x 1x 39x 5x 5x 2x 3x 2x 5x 34x 2x 39x 5x 5x 2x 3x 2x 4x 34x 2x 39x 5x 5x 2x 3x 4x 34x 3x 39x 3x 3x 39x 39x 39x 29x 28x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 25x 25x 25x 27x 27x 25x 25x 25x 27x 27x 25x 25x 25x 28x 3x 3x 3x 3x 3x 21x 21x 21x 5x 18x 18x 18x 18x 2x 2x 1x 1x 3x 2x 2x 2x 2x 3x 2x 2x 2x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 1x 2x 2x 2x 2x 2x 4x 4x 1x 4x 4x 1x 2x 2x | // Data Access Layer for Pros
import { eq, like, or, sql, desc, and, inArray, ne } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../db/schema";
import type { Pro, NewPro } from "../db/schema";
import { sanitizeSearchInput } from "../lib/utils";
export type ProFilters = {
status?: string;
search?: string;
isFeatured?: boolean;
// When `false`, excludes pros with an empty `businessName` (i.e.
// partially-created onboarding shells that clutter the admin list).
// Defaults to `true` (no filtering) for backward compatibility — only the
// admin pros page opts in. See issue #593.
includeIncomplete?: boolean;
// Taxonomy filters - support both single and multi-select (comma-separated)
businessTypeId?: string;
businessTypeIds?: string; // comma-separated for multi-select
customerSegmentId?: string;
customerSegmentIds?: string; // comma-separated for multi-select
cityId?: string;
cityIds?: string; // comma-separated for multi-select
localityId?: string;
serviceCategoryIds?: string;
materialTagIds?: string;
};
// Cap each comma-separated multi-select filter. Without this, a caller could
// send `?businessTypeIds=a,b,c,...` with thousands of values, producing a
// WHERE clause that burns Worker CPU and risks D1 binding limits.
const MAX_MULTI_SELECT = 20;
// D1 caps each statement at 100 bound parameters. We chunk `inArray` lookups
// at 90 (matching `admin/search.routes.ts`) to leave headroom for any other
// parameters on the same WHERE.
const PRO_ID_CHUNK = 90;
const parseIdList = (raw: string): string[] =>
raw
.split(",")
.map((id) => id.trim())
.filter(Boolean)
.slice(0, MAX_MULTI_SELECT);
// Build an `EXISTS (SELECT 1 FROM <junction> WHERE pro_id = pros.id AND <col>
// IN (...))` predicate for filtering pros by a junction table. Returns null
// when the input has no usable IDs.
function buildJunctionExists(
junctionTable: "pro_service_categories" | "pro_material_tags" | "pro_service_areas",
idColumn: string,
ids: string[],
) {
Iif (ids.length === 0) return null;
const placeholders = sql.join(
ids.map((id) => sql`${id}`),
sql`, `,
);
return sql`EXISTS (SELECT 1 FROM ${sql.raw(junctionTable)} j WHERE j.pro_id = ${schema.pros.id} AND j.${sql.raw(idColumn)} IN (${placeholders}))`;
}
type ProRow = typeof schema.pros.$inferSelect;
// Junction-derived array fields stripped from inserts/updates and applied
// separately. Keeps one list of "these are not real columns" so the strip
// helpers and the write-fanout helpers can't drift apart.
const JUNCTION_ARRAY_FIELDS = [
"serviceCategoryIds",
"materialTagIds",
"serviceAreaIds",
] as const satisfies readonly (keyof Pro)[];
type JunctionArrayField = (typeof JUNCTION_ARRAY_FIELDS)[number];
type JunctionArrays = {
serviceCategoryIds?: string[];
materialTagIds?: string[];
serviceAreaIds?: string[];
};
function splitJunctionArrays<T extends JunctionArrays>(
input: T,
): { row: Omit<T, JunctionArrayField>; junctions: JunctionArrays } {
const junctions: JunctionArrays = {};
const row = { ...input } as Record<string, unknown>;
for (const field of JUNCTION_ARRAY_FIELDS) {
Iif (field in row) {
const val = row[field];
if (Array.isArray(val)) junctions[field] = val as string[];
delete row[field];
}
}
return {
row: row as Omit<T, JunctionArrayField>,
junctions,
};
}
export class ProsDal {
constructor(private db: DrizzleD1Database<typeof schema>) {}
/** Builds Drizzle WHERE conditions from filter params. Shared by findAll() and count(). */
private buildConditions(filters: ProFilters) {
const conditions = [];
if (filters.status) {
conditions.push(
eq(schema.pros.status, filters.status as Pro["status"]),
);
}
if (filters.isFeatured !== undefined) {
conditions.push(eq(schema.pros.isFeatured, filters.isFeatured));
}
if (filters.search) {
const sanitized = sanitizeSearchInput(filters.search);
conditions.push(like(schema.pros.businessName, `%${sanitized}%`));
}
// Issue #593: hide incomplete onboarding shells (empty businessName)
// from the admin list when explicitly opted-in. businessName is NOT
// NULL, but onboarding stores literal "" for auto-created records.
if (filters.includeIncomplete === false) {
conditions.push(ne(schema.pros.businessName, ""));
}
// Taxonomy filters - support both single ID and multi-select (comma-separated)
if (filters.businessTypeIds) {
const ids = parseIdList(filters.businessTypeIds);
if (ids.length === 1) {
conditions.push(eq(schema.pros.businessTypeId, ids[0]));
} else if (ids.length > 1) {
conditions.push(
or(...ids.map((id) => eq(schema.pros.businessTypeId, id))),
);
}
} else if (filters.businessTypeId) {
conditions.push(
eq(schema.pros.businessTypeId, filters.businessTypeId),
);
}
if (filters.customerSegmentIds) {
const ids = parseIdList(filters.customerSegmentIds);
if (ids.length === 1) {
conditions.push(eq(schema.pros.customerSegmentId, ids[0]));
} else if (ids.length > 1) {
conditions.push(
or(...ids.map((id) => eq(schema.pros.customerSegmentId, id))),
);
}
} else if (filters.customerSegmentId) {
conditions.push(
eq(schema.pros.customerSegmentId, filters.customerSegmentId),
);
}
if (filters.cityIds) {
const ids = parseIdList(filters.cityIds);
if (ids.length === 1) {
conditions.push(eq(schema.pros.cityId, ids[0]));
} else if (ids.length > 1) {
conditions.push(or(...ids.map((id) => eq(schema.pros.cityId, id))));
}
} else if (filters.cityId) {
conditions.push(eq(schema.pros.cityId, filters.cityId));
}
// Junction-table filters
if (filters.localityId) {
const exists = buildJunctionExists(
"pro_service_areas",
"locality_id",
parseIdList(filters.localityId),
);
Eif (exists) conditions.push(exists);
}
Iif (filters.serviceCategoryIds) {
const exists = buildJunctionExists(
"pro_service_categories",
"category_id",
parseIdList(filters.serviceCategoryIds),
);
if (exists) conditions.push(exists);
}
Iif (filters.materialTagIds) {
const exists = buildJunctionExists(
"pro_material_tags",
"tag_id",
parseIdList(filters.materialTagIds),
);
if (exists) conditions.push(exists);
}
return conditions;
}
/**
* Hydrate `serviceCategoryIds`, `materialTagIds`, and `serviceAreaIds`
* arrays back onto the given pro rows by batch-fetching from the three
* junction tables. Preserves the API response shape that downstream
* code (portal, pro-sites, services, search) was already consuming.
*
* `inArray(proIds)` is chunked at 90 so a large caller (e.g., the
* search-index cron asking for `findAll({}, 0, 100000)`) doesn't blow
* past D1's 100-bound-parameter limit.
*/
private async hydrateJunctions(rows: ProRow[]): Promise<Pro[]> {
if (rows.length === 0) return [];
const proIds = rows.map((p) => p.id);
// Chunk-and-merge: each junction table gets 1+ queries, paged at 90 IDs.
const chunks: string[][] = [];
for (let i = 0; i < proIds.length; i += PRO_ID_CHUNK) {
chunks.push(proIds.slice(i, i + PRO_ID_CHUNK));
}
const [categoryChunks, materialChunks, areaChunks] = await Promise.all([
Promise.all(
chunks.map((ids) =>
this.db
.select()
.from(schema.proServiceCategories)
.where(inArray(schema.proServiceCategories.proId, ids)),
),
),
Promise.all(
chunks.map((ids) =>
this.db
.select()
.from(schema.proMaterialTags)
.where(inArray(schema.proMaterialTags.proId, ids)),
),
),
Promise.all(
chunks.map((ids) =>
this.db
.select()
.from(schema.proServiceAreas)
.where(inArray(schema.proServiceAreas.proId, ids)),
),
),
]);
const categories = categoryChunks.flat();
const materials = materialChunks.flat();
const areas = areaChunks.flat();
const categoryMap = new Map<string, string[]>();
for (const c of categories) {
const list = categoryMap.get(c.proId) ?? [];
list.push(c.categoryId);
categoryMap.set(c.proId, list);
}
const materialMap = new Map<string, string[]>();
for (const m of materials) {
const list = materialMap.get(m.proId) ?? [];
list.push(m.tagId);
materialMap.set(m.proId, list);
}
const areaMap = new Map<string, string[]>();
for (const a of areas) {
const list = areaMap.get(a.proId) ?? [];
list.push(a.localityId);
areaMap.set(a.proId, list);
}
return rows.map((row) => ({
...row,
serviceCategoryIds: categoryMap.get(row.id) ?? [],
materialTagIds: materialMap.get(row.id) ?? [],
serviceAreaIds: areaMap.get(row.id) ?? [],
}));
}
/**
* Replace junction rows for a pro with the given ID list. For each
* provided field, the delete MUST complete before the insert runs —
* otherwise D1 can pick up the inserts before the deletes and collide
* on the composite PK with the existing rows. The three different
* junction tables are independent and run in parallel.
*
* Delete-all + insert-all is fine for the realistic sizes here
* (handfuls of IDs per pro per field).
*/
private async writeJunctions(
proId: string,
junctions: JunctionArrays,
): Promise<void> {
const fieldOps: Promise<unknown>[] = [];
Iif (junctions.serviceCategoryIds !== undefined) {
const dedup = [...new Set(junctions.serviceCategoryIds)];
fieldOps.push(
(async () => {
await this.db
.delete(schema.proServiceCategories)
.where(eq(schema.proServiceCategories.proId, proId));
if (dedup.length > 0) {
await this.db
.insert(schema.proServiceCategories)
.values(
dedup.map((categoryId) => ({ proId, categoryId })),
);
}
})(),
);
}
Iif (junctions.materialTagIds !== undefined) {
const dedup = [...new Set(junctions.materialTagIds)];
fieldOps.push(
(async () => {
await this.db
.delete(schema.proMaterialTags)
.where(eq(schema.proMaterialTags.proId, proId));
if (dedup.length > 0) {
await this.db
.insert(schema.proMaterialTags)
.values(dedup.map((tagId) => ({ proId, tagId })));
}
})(),
);
}
Iif (junctions.serviceAreaIds !== undefined) {
const dedup = [...new Set(junctions.serviceAreaIds)];
fieldOps.push(
(async () => {
await this.db
.delete(schema.proServiceAreas)
.where(eq(schema.proServiceAreas.proId, proId));
if (dedup.length > 0) {
await this.db
.insert(schema.proServiceAreas)
.values(
dedup.map((localityId) => ({ proId, localityId })),
);
}
})(),
);
}
Eif (fieldOps.length === 0) return;
await Promise.all(fieldOps);
}
async findAll(
filters: ProFilters = {},
offset = 0,
limit = 20,
): Promise<Pro[]> {
const conditions = this.buildConditions(filters);
const query = this.db
.select()
.from(schema.pros)
.orderBy(desc(schema.pros.dateCreated))
.limit(limit)
.offset(offset);
const rows = conditions.length > 0
? await query.where(and(...conditions))
: await query;
return this.hydrateJunctions(rows);
}
async count(filters: ProFilters = {}): Promise<number> {
const conditions = this.buildConditions(filters);
const query = conditions.length > 0
? this.db.select({ count: sql<number>`count(*)` }).from(schema.pros).where(and(...conditions))
: this.db.select({ count: sql<number>`count(*)` }).from(schema.pros);
const result = await query;
return result[0]?.count ?? 0;
}
async findById(id: string): Promise<Pro | undefined> {
const result = await this.db
.select()
.from(schema.pros)
.where(eq(schema.pros.id, id))
.limit(1);
if (result.length === 0) return undefined;
const [hydrated] = await this.hydrateJunctions(result);
return hydrated;
}
/**
* Bulk fetch pros by IDs (N+1 optimization)
* @param ids Array of pro IDs
* @returns Map of proId -> Pro
*/
async findByIds(ids: string[]): Promise<Map<string, Pro>> {
if (ids.length === 0) return new Map();
const result = await this.db
.select()
.from(schema.pros)
.where(inArray(schema.pros.id, ids));
const hydrated = await this.hydrateJunctions(result);
const map = new Map<string, Pro>();
for (const pro of hydrated) {
map.set(pro.id, pro);
}
return map;
}
async findByWhatsappNumber(phone: string): Promise<Pro | undefined> {
const result = await this.db
.select()
.from(schema.pros)
.where(eq(schema.pros.whatsapp, phone))
.limit(1);
if (result.length === 0) return undefined;
const [hydrated] = await this.hydrateJunctions(result);
return hydrated;
}
async findBySlug(slug: string): Promise<Pro | undefined> {
const result = await this.db
.select()
.from(schema.pros)
.where(eq(schema.pros.slug, slug))
.limit(1);
if (result.length === 0) return undefined;
const [hydrated] = await this.hydrateJunctions(result);
return hydrated;
}
async create(data: NewPro): Promise<Pro> {
const { row, junctions } = splitJunctionArrays(data);
const result = await this.db
.insert(schema.pros)
.values(row)
.returning();
const created = result[0];
await this.writeJunctions(created.id, junctions);
const [hydrated] = await this.hydrateJunctions([created]);
return hydrated;
}
async update(
id: string,
data: Partial<Omit<Pro, "id" | "dateCreated">>,
): Promise<Pro | undefined> {
const { row, junctions } = splitJunctionArrays(data);
const hasRowFields = Object.keys(row).length > 0;
const hasJunctionFields = Object.keys(junctions).length > 0;
// Touch dateUpdated whenever ANY field changes — including
// junction-only updates. The UPDATE statement runs with no row
// fields when only junctions are changing, just to refresh the
// timestamp; SELECT-only path is for true no-op calls.
const result =
hasRowFields || hasJunctionFields
? await this.db
.update(schema.pros)
.set({ ...row, dateUpdated: new Date() })
.where(eq(schema.pros.id, id))
.returning()
: await this.db
.select()
.from(schema.pros)
.where(eq(schema.pros.id, id))
.limit(1);
if (result.length === 0) return undefined;
await this.writeJunctions(id, junctions);
const [hydrated] = await this.hydrateJunctions(result);
return hydrated;
}
async delete(id: string): Promise<boolean> {
const result = await this.db
.delete(schema.pros)
.where(eq(schema.pros.id, id))
.returning();
return result.length > 0;
}
async slugExists(slug: string, excludeId?: string): Promise<boolean> {
const conditions = [eq(schema.pros.slug, slug)];
if (excludeId) {
conditions.push(sql`${schema.pros.id} != ${excludeId}`);
}
const result = await this.db
.select({ count: sql<number>`count(*)` })
.from(schema.pros)
.where(and(...conditions));
return (result[0]?.count ?? 0) > 0;
}
async incrementViewCount(id: string): Promise<void> {
await this.db
.update(schema.pros)
.set({
viewCount: sql`${schema.pros.viewCount} + 1`,
lastViewedAt: new Date(),
})
.where(eq(schema.pros.id, id));
}
/**
* Get all pro IDs with a specific status (e.g., 'published')
* Used by marketplace to filter projects to only show those from published pros
*/
async findIdsByStatus(status: Pro["status"]): Promise<string[]> {
const result = await this.db
.select({ id: schema.pros.id })
.from(schema.pros)
.where(eq(schema.pros.status, status));
return result.map((r) => r.id);
}
}
|