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 | 4x 4x 4x 4x 4x 1x 1x 4x 4x 49x 49x 49x 49x 49x 49x 49x 49x 49x 488x 488x 488x 488x 488x 49x 57486x 57486x 488x 488x 57486x 40x 6x 2x 2x 4x 34x 34x 40x 57446x 5x 1x 5x 57441x 6001x 6001x 6001x 51440x 4x 4x 4x 4x 51436x 482x 482x 482x 50954x 49x 49x 4x 371x 384x 2x 4x 371x 371x 38x 37x 37x 37x 36x 36x 486x 486x 216x 36x 3021x 34x 428x 34x 34x 38x 38x 34x 38x 38x 38x 38x 38x 425x 1x 1x 424x 424x 423x 28x 28x 395x 3x 3x 392x 21x 21x 371x 371x 371x 371x 371x 371x 371x 371x 371x 425x 33x 33x 33x 33x 33x 33x 33x 33x 369x 40x 40x | /**
* CSV import of the scraped Hyderabad channel-partner list into `rrm_prospects`.
*
* Two rules shape everything here:
*
* 1. NO ROW IS EVER SILENTLY DROPPED. Every row that does not become a
* prospect leaves a numbered reject with a machine-readable reason, and
* the whole set is persisted to `rrm_import_batches.rejects`. "Where did
* my 40 rows go" has to be answerable from the database months later, by
* someone who no longer has the file.
* 2. PROVENANCE IS WRITTEN AT IMPORT AND NEVER CLEARED (spec §14). "Where did
* you get my number?" is the likeliest question in this campaign, and the
* answer has to be one lookup: which file, which line, which source.
*
* Dedupe is NOT implemented here. `resolveOrRejectProspectByPhone` owns the
* whole §5.3 check set — normalisation, suppression, existing prospect,
* registered pro, pro WhatsApp recipient, homeowner inquiry — and is the same
* function the organic landing-page path calls, which is the only reason the
* two doors stay in agreement. This module only decides what an import DOES
* with each outcome.
*/
import { eq } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import type { AppendEventInput } from "../../dal/rrm/events.dal";
import { RrmEventsDal } from "../../dal/rrm/events.dal";
import * as schema from "../../db/schema";
import { RRM_TIERS } from "../../db/schema/enums";
import type { NewRrmProspect, RrmProspect } from "../../db/schema/rrm";
import { generateId } from "../../lib/ids";
import { mintVisitToken } from "../../lib/rrm/token";
import {
type ProspectRejectReason,
type ResolveProspectContext,
type ResolveProspectResult,
resolveOrRejectProspectByPhone,
} from "./prospect-resolver.service";
const PROSPECTS = schema.rrmProspects;
const BATCHES = schema.rrmImportBatches;
// Derived from the table rather than re-imported from enums.ts: the schema is
// the single source of truth, so a column whose enum changes breaks this file
// at compile time instead of at insert time.
type RrmSource = RrmProspect["source"];
type RrmTier = NonNullable<RrmProspect["tier"]>;
// ─────────────────────────────────────────────────────────────────────────────
// The resolver seam
// ─────────────────────────────────────────────────────────────────────────────
/**
* `resolveOrRejectProspectByPhone`, as a type.
*
* Identical to the real function's signature so the default IS the real
* function and any double is checked against the same contract. The seam is
* for injecting failure — the tests use it to make a resolve throw mid-file and
* assert what the batch row is left saying. It is not an invitation to pass a
* different dedupe rule in production; §5.3 has one implementation on purpose.
*/
export type ResolveProspectByPhone = (
rawPhone: string | null | undefined,
ctx: ResolveProspectContext,
) => Promise<ResolveProspectResult>;
// ─────────────────────────────────────────────────────────────────────────────
// Public surface
// ─────────────────────────────────────────────────────────────────────────────
/**
* The resolver's five reasons plus three the import adds.
*
* `already_prospect` is this module's reading of the resolver's third outcome,
* `existing`. The resolver deliberately does not call that a rejection: the
* organic form path resolves to the same prospect and ATTACHES the submission
* to it. For an import there is nothing to attach — the row is a duplicate of
* something already in the CRM — so only here does it become a reject.
*/
export type ImportRejectReason =
| ProspectRejectReason
/** The number is already in `rrm_prospects` (resolver outcome `existing`). */
| "already_prospect"
/** The same number appeared on an earlier line of THIS file. */
| "duplicate_in_file"
/** Cell count did not match the header — the row is misaligned, not data. */
| "malformed_row";
export type ImportReject = {
/**
* 1-based LINE NUMBER IN THE FILE, not an index among data rows. The header
* is line 1, so the first prospect is row 2. An operator can open the CSV,
* jump to that line and see the row, with no arithmetic — which is the whole
* point of recording it.
*/
row: number;
/** The `phone` cell verbatim, so a typo is visible without the file. */
phone?: string;
reason: ImportRejectReason;
detail?: string;
};
export type ImportProspectsResult = {
batchId: string;
rowsTotal: number;
rowsOk: number;
rowsRejected: number;
rejects: ImportReject[];
};
export type ImportProspectsContext = {
db: DrizzleD1Database<typeof schema>;
/**
* Defaults to `resolveOrRejectProspectByPhone`. Overridden only by tests
* that do not want the four extra tables the real resolver reads.
*/
resolveProspect?: ResolveProspectByPhone;
/** `RRM_TOKEN_SECRET`. Required — a prospect without a link is unusable. */
tokenSecret: string;
/** Operator user id. Null only for a script; recorded as `system` then. */
uploadedBy?: string | null;
/** Stored on the batch so a reject can be traced back to a real file. */
filename?: string | null;
/** Injectable clock. The whole import shares one instant on purpose. */
now?: Date;
/** Rows per `db.batch`. Defaults to `IMPORT_CHUNK_ROWS`. */
chunkRows?: number;
};
export class ImportHeaderError extends Error {
code = "INVALID_HEADER";
constructor(public missing: string[]) {
super(`CSV is missing required column(s): ${missing.join(", ")}`);
}
}
export class ImportSecretMissingError extends Error {
code = "TOKEN_SECRET_REQUIRED";
constructor() {
super("importProspects requires ctx.tokenSecret to mint visit tokens");
}
}
/**
* Columns the importer refuses to guess at. `phone` is the identity and the
* rest carry the only per-row information we get; a renamed or reordered export
* that quietly imports 455 nameless rows is worse than a failed upload, so a
* missing one aborts before anything is written.
*/
export const REQUIRED_COLUMNS = [
"tier",
"name",
"phone",
"wa_link",
"micro_market",
"source",
] as const;
/**
* Rows per `db.batch`.
*
* One INSERT per prospect (~24 bound values) plus one per `imported` event (8),
* never a multi-row VALUES list — 24 columns puts a five-row insert past D1's
* 100-bound-parameter-per-statement ceiling. The chunk therefore bounds
* STATEMENTS PER ROUND TRIP, not parameters: 25 rows is 50 statements and
* ~1,300 bound values, comfortably inside D1's request limits, and it turns the
* real 455-row file into 19 round trips instead of 455.
*
* A chunk is atomic; the IMPORT is not. D1 has no cross-request transaction, so
* a crash at chunk 12 leaves chunks 1-11 committed. Recovery is re-running the
* same file: every already-written row comes back `already_prospect`, and the
* unfinished batch row (counts still null) is what flags it for someone.
*/
export const IMPORT_CHUNK_ROWS = 25;
// ─────────────────────────────────────────────────────────────────────────────
// CSV parsing
// ─────────────────────────────────────────────────────────────────────────────
export type CsvRecord = {
/** 1-based line in the file where this record starts. */
line: number;
values: string[];
};
/**
* RFC 4180-ish parser: quoted fields, embedded commas and newlines, `""` for a
* literal quote, LF / CRLF / bare CR line endings, and a UTF-8 BOM.
*
* A character walk rather than `split("\n").map(split(","))` because the split
* version is wrong the first time a firm name contains a comma — which this
* list, full of "Firm Name, LLP", guarantees. No CSV dependency: the correct
* version is forty lines and the tests below pin the edges.
*/
export function parseCsv(text: string): CsvRecord[] {
// Excel's "Save as CSV" emits a BOM. Left in place it becomes part of the
// first header name and every column lookup misses.
const src = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
const records: CsvRecord[] = [];
let values: string[] = [];
let field = "";
let quoted = false;
let line = 1;
let recordLine = 1;
let started = false;
const endRecord = (): void => {
values.push(field);
records.push({ line: recordLine, values });
values = [];
field = "";
started = false;
};
for (let i = 0; i < src.length; i++) {
const ch = src[i];
if (!started) {
recordLine = line;
started = true;
}
if (quoted) {
if (ch === '"') {
if (src[i + 1] === '"') {
field += '"';
i++;
} else {
quoted = false;
}
} else {
if (ch === "\n") line++;
field += ch;
}
continue;
}
if (ch === '"') {
// Quoting only opens at the start of a field. Elsewhere a quote is a
// literal, which is how `Sri Sai 6" Pipes` survives.
if (field === "") quoted = true;
else field += ch;
continue;
}
if (ch === ",") {
values.push(field);
field = "";
continue;
}
if (ch === "\r") {
// A CRLF is one terminator; consume the LF with the CR so it does not
// open an empty record.
if (src[i + 1] === "\n") i++;
endRecord();
line++;
continue;
}
if (ch === "\n") {
endRecord();
line++;
continue;
}
field += ch;
}
// A file with no trailing newline still has a final record.
if (started) endRecord();
return records;
}
// ─────────────────────────────────────────────────────────────────────────────
// Column mapping
// ─────────────────────────────────────────────────────────────────────────────
/**
* Provenance written to `rrm_prospects.source_detail`.
*
* Aliased off the column rather than declared here: `sourceLabel` / `waLink` /
* `category` / `batchId` / `row` are the answer to §14's "where did you get my
* number?", and the schema is where that shape has to be visible to anyone
* reading the table. `listingUrl` and `page` belong to a paginated scrape and
* stay unset for a GMB export.
*/
type ImportProvenance = NonNullable<RrmProspect["sourceDetail"]>;
const SOURCE_PATTERNS: ReadonlyArray<readonly [RegExp, RrmSource]> = [
[/google\s*maps|\bgmb\b|google\s*business/i, "maps"],
[/just\s*dial/i, "justdial"],
[/referr?al/i, "referral"],
[/\bfield\b|walk[\s-]?in/i, "field"],
];
/**
* An unrecognised label imports as `manual` rather than rejecting the row: the
* enum is a routing hint for sequence selection, and `sourceLabel` keeps the
* verbatim string, so nothing is lost. Failing 455 rows over a changed vendor
* string would be the wrong failure.
*/
function mapSource(label: string): RrmSource {
for (const [pattern, source] of SOURCE_PATTERNS) {
if (pattern.test(label)) return source;
}
return "manual";
}
const TIERS: readonly string[] = RRM_TIERS;
/** Unknown or blank tier lands as null and still imports — tier is triage, not identity. */
function mapTier(raw: string): RrmTier | null {
const value = raw.trim().toUpperCase();
return TIERS.includes(value) ? (value as RrmTier) : null;
}
// ─────────────────────────────────────────────────────────────────────────────
// Import
// ─────────────────────────────────────────────────────────────────────────────
type PendingRow = {
values: NewRrmProspect;
event: AppendEventInput;
};
export async function importProspects(
csvText: string,
ctx: ImportProspectsContext,
): Promise<ImportProspectsResult> {
// Checked before anything is parsed or written: a run that imports 455 rows
// and then cannot mint a single link is worse than one that never started.
if (!ctx.tokenSecret) throw new ImportSecretMissingError();
const records = parseCsv(csvText);
const [header, ...body] = records;
// Destructured and narrowed here rather than indexed later: past this line
// `header` is a value, so nothing downstream needs a `?.` that could only
// ever be a dead branch.
if (!header) throw new ImportHeaderError([...REQUIRED_COLUMNS]);
const columns = new Map<string, number>();
header.values.forEach((cell, index) => {
const key = cell.trim().toLowerCase();
// First occurrence wins, so a duplicated column cannot shadow the real one.
if (key && !columns.has(key)) columns.set(key, index);
});
const missing = REQUIRED_COLUMNS.filter((name) => !columns.has(name));
if (missing.length > 0) throw new ImportHeaderError([...missing]);
// `-1` for a column the file does not have: `notes` and `category` are read
// opportunistically, and an export that drops them still imports.
const cellAt = (record: CsvRecord, name: string): string =>
(record.values[columns.get(name) ?? -1] ?? "").trim();
// A bare blank line is whitespace, not a row: it is not counted and not
// rejected. A record with the right shape but empty cells IS a row and falls
// through to the resolver, which rejects it as an invalid phone.
const dataRecords = body.filter(
(r) => !(r.values.length === 1 && r.values[0] === ""),
);
const batchId = generateId();
const now = ctx.now ?? new Date();
const rowsTotal = dataRecords.length;
// Written BEFORE the first prospect, with the counts left null. A crash
// mid-import then leaves a row that says "this file started, it had N rows,
// it never finished" — and the `batchId` stamped into every prospect written
// before the crash still resolves to something. Filled in at the end.
await ctx.db.insert(BATCHES).values({
id: batchId,
filename: ctx.filename ?? null,
uploadedBy: ctx.uploadedBy ?? null,
rowsTotal,
dateCreated: now,
});
// An unattributed import is recorded as `system` rather than as an operator
// with no id — the audit trail may say "a script did this", never nothing.
const actorType = ctx.uploadedBy ? "operator" : "system";
const rejects: ImportReject[] = [];
const pending: PendingRow[] = [];
const seenInFile = new Set<string>();
const resolve = ctx.resolveProspect ?? resolveOrRejectProspectByPhone;
// EVERY row is resolved before ANY row is written. The resolver reads
// `rrm_prospects`, so interleaving resolve and write would make the second
// occurrence of a number inside this same file come back `already_prospect`
// — pointing the operator at the CRM when the fix is in their spreadsheet.
//
// COST, for whoever wires the route: a brand-new number costs the resolver
// five D1 queries (suppression, prospect, then three concurrent ownership
// lookups). The real 455-row list is therefore ~2,300 subrequests, well past
// a Worker's per-request ceiling, and concurrency does not lower the count.
// A file that size has to arrive in slices of roughly 150 rows, or run off
// the request. This function is safe to call repeatedly on slices: rows
// already written come back `already_prospect`, and each slice gets its own
// batch row.
for (const record of dataRecords) {
if (record.values.length !== header.values.length) {
// Misaligned row: every cell after the missing comma is under the wrong
// header, so importing it would write a rating into a phone column.
rejects.push({
row: record.line,
reason: "malformed_row",
detail: `expected ${header.values.length} columns, got ${record.values.length}`,
});
continue;
}
const rawPhone = cellAt(record, "phone");
const resolved = await resolve(rawPhone, { db: ctx.db });
if (resolved.outcome === "reject") {
rejects.push({
row: record.line,
phone: rawPhone,
reason: resolved.reason,
...(resolved.detail === undefined ? {} : { detail: resolved.detail }),
});
continue;
}
if (resolved.outcome === "existing") {
// The prospect id, not the phone: it is what the reject report links to
// so an operator can see the row that already won the number.
rejects.push({
row: record.line,
phone: rawPhone,
reason: "already_prospect",
detail: resolved.prospect.id,
});
continue;
}
// Distinct from `already_prospect` on purpose. "The list you gave me has
// the same agent twice" is a fix to the file; "this number is already in
// the CRM" is not. Collapsing them hides which one happened.
if (seenInFile.has(resolved.phoneNorm)) {
rejects.push({
row: record.line,
phone: rawPhone,
reason: "duplicate_in_file",
detail: resolved.phoneNorm,
});
continue;
}
seenInFile.add(resolved.phoneNorm);
const id = generateId();
const sourceLabel = cellAt(record, "source");
const source = mapSource(sourceLabel);
const microMarket = cellAt(record, "micro_market");
const category = cellAt(record, "category");
const waLink = cellAt(record, "wa_link");
const notes = cellAt(record, "notes");
const provenance: ImportProvenance = {
batchId,
row: record.line,
scrapedAt: now.toISOString(),
...(sourceLabel ? { sourceLabel } : {}),
...(waLink ? { waLink } : {}),
...(category ? { category } : {}),
};
pending.push({
values: {
id,
phoneNorm: resolved.phoneNorm,
// The `name` cell is a GMB listing title — a firm, not a person.
// "Shajwal - Find Your Dream Property" is not someone called Shajwal
// with high enough confidence to greet by, and a WhatsApp message
// that opens with the wrong first name is the most damaging thing a
// recruitment sequence can do. `name` stays null until they reply.
name: null,
firmName: cellAt(record, "name") || null,
// `firmType` is deliberately NOT inferred from `category`: a GMB
// category is self-declared, and "Real Estate Builders" is equally a
// builder and a builder's sales arm — different sequence variants.
// The verbatim category is kept in provenance, so a back-fill later
// is a query, not a re-scrape.
firmType: null,
tier: mapTier(cellAt(record, "tier")),
microMarkets: microMarket ? [microMarket] : null,
source,
sourceDetail: provenance,
stage: "sourced",
stageChangedAt: now,
locale: "en",
// Nothing has been detected or stated yet; `detectLocale()` overwrites
// this with `detected` on the first inbound message.
localeSource: "default",
// A scraped list is not consent. `none` is the value that BLOCKS
// business-initiated sending, and it is why the CSV's `opted_in`
// column is ignored below rather than mapped: a spreadsheet tick is
// not an affirmative act, and DPDP s.6(10) puts the burden of proving
// one on us.
consentBasis: "none",
notes: notes || null,
visitToken: await mintVisitToken(id, ctx.tokenSecret),
dateCreated: now,
dateUpdated: now,
},
event: {
prospectId: id,
type: "imported",
actorType,
actorId: ctx.uploadedBy ?? null,
payload: { batchId, row: record.line, source },
occurredAt: now,
},
});
}
// Columns read above and deliberately not mapped anywhere:
// call_status / wa_sent / opted_in — the spreadsheet's own working columns,
// empty in all 455 rows. They shadow real state: `wa_sent` would be a
// second source of truth against `wa_messages`, `call_status` against
// `rrm_tasks`, and `opted_in` against `consent_basis`. A tick in a cell
// must never be able to unblock a send.
// rating / reviews / core_hyderabad — targeting inputs already folded into
// `tier` by whoever built the list; storing them again invites two
// answers to "is this a good prospect".
await writeChunks(ctx, pending);
const rowsRejected = rejects.length;
const rowsOk = pending.length;
await ctx.db
.update(BATCHES)
.set({ rowsOk, rowsRejected, rejects })
.where(eq(BATCHES.id, batchId));
return { batchId, rowsTotal, rowsOk, rowsRejected, rejects };
}
/** Prospect row and its `imported` event go into the same batch — spec §0 rule 7. */
async function writeChunks(
ctx: ImportProspectsContext,
pending: PendingRow[],
): Promise<void> {
const events = new RrmEventsDal(ctx.db);
const size = Math.max(1, Math.trunc(ctx.chunkRows ?? IMPORT_CHUNK_ROWS));
for (let i = 0; i < pending.length; i += size) {
const statements = pending.slice(i, i + size).flatMap((row) => [
ctx.db.insert(PROSPECTS).values(row.values),
// Reuses the events DAL's unexecuted statement so the row and its event
// commit together or not at all. A prospect with no `imported` event
// would be invisible to the funnel, which is built from events.
events.buildEventStatement(row.event),
]);
const [first, ...rest] = statements;
// `slice` on a non-empty range cannot be empty; the check is what proves
// that to the compiler, since `db.batch` demands a non-empty tuple.
Eif (first) await ctx.db.batch([first, ...rest]);
}
}
|