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 | 1x 134x 1x 2x 5x 2x 1x 14x 1x 1x 5x 1x 10x 5x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 2x 2x 2x 2x 2x 1x 3x 3x 3x 3x 3x 3x 3x 2x 2x 3x 90x 150x 3x 3x 3x 3x 1x 3x 3x 3x 1x 2x 2x 1x 1x 3x 3x 3x 3x 3x 3x 2x | // Admin Routes — Web leads (#1085)
//
// The ops surface for the lead store (db/schema/landing-leads.ts): every
// www form, calculator, go. quote check, inquiry, booking, referral and
// WhatsApp lead, one row per person. Mounted behind requirePlatformAdmin in
// ./index.ts, so a non-admin gets 403 before reaching any handler.
import { Hono } from "hono";
import { z } from "zod";
import type { Dal } from "../../dal";
import type { LeadListFilters } from "../../dal/landing-leads.dal";
import {
LEAD_ENTRY_TYPES,
LEAD_QUALIFIED,
LEAD_STATUSES,
} from "../../db/schema/enums";
import type { LandingLead } from "../../db/schema/landing-leads";
import { csvDocument } from "../../lib/csv";
import { buildPaginationMeta, getPagination } from "../../lib/pagination";
import {
error,
handleError,
success,
successWithPagination,
} from "../../lib/response";
import { zv } from "../../lib/zv";
type Env = {
Bindings: CloudflareBindings;
Variables: {
user: { id: string; name: string; email: string } | null;
session: unknown;
dal: Dal;
};
};
/** Rows per D1 round trip while building an export. */
const EXPORT_CHUNK = 1000;
/** A query param left blank (`?status=`) means "no filter", not "status ''". */
const blank = (value: unknown) => (value === "" ? undefined : value);
/**
* `YYYY-MM-DD` as an IST calendar day — the team works in Hyderabad, so
* "leads from the 3rd" means the 3rd in India, not in UTC. A day that does
* not exist (2026-02-31, 2026-13-45) is a 400, not a silent roll-over.
*/
const istDay = (edge: "start" | "end") =>
z.preprocess(
blank,
z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/, "dates must be YYYY-MM-DD")
.refine(
(day) =>
!Number.isNaN(Date.parse(`${day}T00:00:00Z`)) &&
new Date(`${day}T00:00:00Z`).toISOString().startsWith(day),
"not a real date",
)
.transform(
(day) =>
new Date(
`${day}T${edge === "start" ? "00:00:00.000" : "23:59:59.999"}+05:30`,
),
)
.optional(),
);
const filtersSchema = z.object({
status: z.preprocess(blank, z.enum(LEAD_STATUSES).optional()),
entryType: z.preprocess(blank, z.enum(LEAD_ENTRY_TYPES).optional()),
utmSource: z.preprocess(blank, z.string().trim().max(100).optional()),
qualified: z.preprocess(blank, z.enum(LEAD_QUALIFIED).optional()),
open: z.preprocess(
blank,
z
.enum(["true", "false"])
.optional()
.transform((v) => v === "true"),
),
q: z.preprocess(blank, z.string().trim().max(100).optional()),
from: istDay("start"),
to: istDay("end"),
});
const listQuerySchema = filtersSchema.extend({
page: z.preprocess(blank, z.coerce.number().int().min(1).default(1)),
limit: z.preprocess(
blank,
z.coerce.number().int().min(1).max(100).default(20),
),
});
const patchSchema = z
.object({
status: z.enum(LEAD_STATUSES).optional(),
adminNotes: z.string().trim().max(1000).nullable().optional(),
})
.refine(
(body) => body.status !== undefined || body.adminNotes !== undefined,
{ message: "send status and/or adminNotes" },
);
const IST_TIMESTAMP = new Intl.DateTimeFormat("sv-SE", {
timeZone: "Asia/Kolkata",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
hour12: false,
});
/** `2026-10-17 09:15` in IST — sorts as text and reads as a time in a sheet. */
function ist(date: Date | null): string {
return date ? IST_TIMESTAMP.format(date) : "";
}
/**
* An Indian mobile as its 10 digits. `+91…` would be read as a formula by a
* spreadsheet (so lib/csv.ts prefixes it with `'`, which then comes along
* when the number is copied); 10 digits open as a plain, dialable number.
* Anything else keeps its E.164 form.
*/
function csvPhone(phone: string | null): string | null {
return phone && /^\+91\d{10}$/.test(phone) ? phone.slice(3) : phone;
}
const EXPORT_COLUMNS: [header: string, cell: (lead: LandingLead) => unknown][] =
[
["Lead ID", (l) => l.id],
["Created (IST)", (l) => ist(l.dateCreated)],
["Name", (l) => l.name],
["Phone", (l) => csvPhone(l.phone)],
["Email", (l) => l.email],
["City", (l) => l.city],
["Locality", (l) => l.locality],
["Entry type", (l) => l.entryType],
["Offer", (l) => l.offer],
["Source", (l) => l.source],
["UTM source", (l) => l.utmSource],
["UTM medium", (l) => l.utmMedium],
["UTM campaign", (l) => l.utmCampaign],
["UTM content", (l) => l.utmContent],
["UTM term", (l) => l.utmTerm],
["gclid", (l) => l.gclid],
["fbclid", (l) => l.fbclid],
["Internal link", (l) => l.intLink],
["Ad id", (l) => l.sourceId],
["Price test arm", (l) => l.priceTestArm],
["Consent", (l) => l.consentState],
["Consent version", (l) => l.consentVersion],
["Consent at (IST)", (l) => ist(l.consentAt)],
["Status", (l) => l.status],
["Stage", (l) => l.stage],
["Qualified", (l) => l.qualified],
["BHK", (l) => l.bhk],
["Possession", (l) => l.possessionMonth],
["Outcome", (l) => l.outcome],
["Admin notes", (l) => l.adminNotes],
];
const landingLeads = new Hono<Env>();
// List leads, newest first.
landingLeads.get("/", zv("query", listQuerySchema), async (c) => {
try {
const { page, limit, ...filters } = c.req.valid("query");
const p = getPagination(page, limit);
const { items, total } = await c
.get("dal")
.landingLeads.list({ ...filters, limit: p.limit, offset: p.offset });
return successWithPagination(
c,
items,
buildPaginationMeta(total, p.page, p.limit),
);
} catch (err) {
return handleError(c, err);
}
});
// The current filter as CSV, UTM columns included — every matching row, read
// in chunks, never a silently truncated sheet. Before /:id so the literal
// path wins.
landingLeads.get("/export.csv", zv("query", filtersSchema), async (c) => {
try {
const filters: LeadListFilters = c.req.valid("query");
const dal = c.get("dal");
const first = await dal.landingLeads.list({
...filters,
limit: EXPORT_CHUNK,
offset: 0,
});
const items = [...first.items];
for (
let offset = EXPORT_CHUNK;
offset < first.total;
offset += EXPORT_CHUNK
) {
const next = await dal.landingLeads.list({
...filters,
limit: EXPORT_CHUNK,
offset,
});
items.push(...next.items);
}
const body = csvDocument(
EXPORT_COLUMNS.map(([header]) => header),
items.map((lead) => EXPORT_COLUMNS.map(([, cell]) => cell(lead))),
);
c.header("Content-Type", "text/csv; charset=utf-8");
c.header(
"Content-Disposition",
'attachment; filename="interioring-web-leads.csv"',
);
// Names and phone numbers: never let a shared cache keep a copy.
c.header("Cache-Control", "no-store");
// A UTF-8 byte-order mark: without it Excel on Windows opens the file as
// ANSI, and a name in Telugu or Hindi (names accept any letter) or a ₹
// in the notes turns to mojibake. Google Sheets ignores it.
return c.body(`\uFEFF${body}`);
} catch (err) {
return handleError(c, err);
}
});
// One lead with its touch history, newest touch first.
landingLeads.get("/:id", async (c) => {
try {
const id = Number(c.req.param("id"));
if (!Number.isInteger(id)) {
return error(c, "VALIDATION_ERROR", "id must be a number", 400);
}
const lead = await c.get("dal").landingLeads.getWithTouches(id);
if (!lead) return error(c, "NOT_FOUND", "Lead not found", 404);
return success(c, lead);
} catch (err) {
return handleError(c, err);
}
});
// Work a lead: change its status and/or notes. Only the fields sent change,
// so two admins editing different fields don't overwrite each other.
landingLeads.patch("/:id", zv("json", patchSchema), async (c) => {
try {
const id = Number(c.req.param("id"));
Iif (!Number.isInteger(id)) {
return error(c, "VALIDATION_ERROR", "id must be a number", 400);
}
const { status, adminNotes } = c.req.valid("json");
const updated = await c.get("dal").landingLeads.update(id, {
...(status !== undefined ? { status } : {}),
...(adminNotes !== undefined ? { adminNotes: adminNotes || null } : {}),
});
if (!updated) return error(c, "NOT_FOUND", "Lead not found", 404);
return success(c, updated);
} catch (err) {
return handleError(c, err);
}
});
export default landingLeads;
|