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 | 1x 1x 1x 34x 34x 34x 34x 1x 33x 1x 32x 32x 32x 32x 1x 31x 31x 2x 29x 29x 1x 28x 1x 27x 34x 1x 26x 34x 1x 25x 25x 3x 3x 3x 1x 24x 3x 3x 1x 2x 2x 1x 22x 22x 2x 20x 1x 19x 5x 1x 5x 3x 16x 16x 16x 16x 16x 1x 16x 16x 16x 1x 16x 16x 16x 16x 16x 16x 1x 16x 16x 16x 16x 16x 1x 1x 1x 15x 18x | // Public Marketplace Inquiry Routes (API Key Protected)
import { Hono } from "hono";
import type { Dal } from "../../dal";
import type { Services } from "../../services";
import { success, handleError } from "../../lib/response";
import { ValidationError } from "../../lib/errors";
import { rateLimit } from "../../middleware/rate-limit.middleware";
import {
buildWhatsAppRedirectUrl,
VALID_REQUIREMENT_TYPES,
VALID_SOURCE_TYPES,
} from "../../lib/whatsapp";
import { CommunicationGateway } from "../../lib/communication/gateway";
import { NewInquiryHandler } from "../../lib/communication/handlers/new-inquiry.handler";
import { resolveEnvironment } from "../../lib/domain-utils";
import { getWhatsAppSafetyConfig } from "../../lib/env-config";
import { parseIndianPhone } from "@interioring/utils/validation/phone";
import {
validateCustomerName,
customerNameErrorMessage,
normalizeCustomerName,
} from "@interioring/utils/validation/customer-name";
import { isValidEmail } from "@interioring/utils/validation/email";
import { logger } from "../../lib/logger";
import {
cityNameErrorMessage,
validateCityName,
} from "@interioring/utils/validation/address";
type Env = {
Bindings: CloudflareBindings;
Variables: {
dal: Dal;
services: Services;
};
};
const inquiries = new Hono<Env>();
// Rate limit: 5 requests per 10 minutes per IP
const inquiryRateLimit = rateLimit({
windowMs: 10 * 60 * 1000,
max: 5,
message: "Too many inquiries. Please try again in 10 minutes.",
});
// Submit a new inquiry
inquiries.post("/", inquiryRateLimit, async (c) => {
try {
const services = c.get("services");
const body = await c.req.json();
// Validate required fields
if (!body.proId) {
throw new ValidationError("proId is required");
}
if (!body.customerName) {
throw new ValidationError("customerName is required");
}
const nameError = validateCustomerName(String(body.customerName));
Iif (nameError) {
throw new ValidationError(customerNameErrorMessage(nameError));
}
const normalizedCustomerName = normalizeCustomerName(
String(body.customerName),
);
if (!body.customerPhone) {
throw new ValidationError("customerPhone is required");
}
const parsedPhone = parseIndianPhone(String(body.customerPhone));
if (!parsedPhone || parsedPhone.type !== "mobile") {
throw new ValidationError(
"customerPhone must be a valid 10-digit Indian mobile number",
);
}
const normalizedPhone = parsedPhone.e164;
// Validate optional fields
if (
body.requirementType &&
!VALID_REQUIREMENT_TYPES.includes(body.requirementType)
) {
throw new ValidationError(
`Invalid requirementType. Must be one of: ${VALID_REQUIREMENT_TYPES.join(", ")}`,
);
}
if (body.sourceType && !VALID_SOURCE_TYPES.includes(body.sourceType)) {
throw new ValidationError(
`Invalid sourceType. Must be one of: ${VALID_SOURCE_TYPES.join(", ")}`,
);
}
const rawDescription =
body.requirementType === "other" && body.requirementDescription
? String(body.requirementDescription).trim()
: undefined;
if (rawDescription && rawDescription.length > 500) {
throw new ValidationError(
"requirementDescription must be 500 characters or fewer",
);
}
const requirementDescription = rawDescription?.slice(0, 500);
// Length-cap free-text fields before they're persisted or forwarded
// to the notification pipeline. Previously `requirement`, `sourcePage`,
// and `customerEmail` were written to D1 with no bound — a caller
// could persist 100KB+ payloads that slow down every subsequent read.
if (body.requirement && String(body.requirement).length > 5000) {
throw new ValidationError("requirement must be 5000 characters or fewer");
}
Iif (body.sourcePage && String(body.sourcePage).length > 500) {
throw new ValidationError("sourcePage must be 500 characters or fewer");
}
if (body.customerEmail) {
const email = String(body.customerEmail).trim();
Iif (email.length > 254) {
throw new ValidationError("customerEmail must be 254 characters or fewer");
}
if (!isValidEmail(email)) {
throw new ValidationError("customerEmail must be a valid email address");
}
}
// `customerLocation` is forwarded to WhatsApp/email notification
// payloads. It must be a recognisable city name when present —
// otherwise junk like "12345" reaches the pro's inbox (audit during
// issue #563 fix surfaced this gap).
if (body.customerLocation) {
const loc = String(body.customerLocation).trim();
if (loc.length > 200) {
throw new ValidationError(
"customerLocation must be 200 characters or fewer",
);
}
const locError = validateCityName(loc);
if (locError) {
throw new ValidationError(
`customerLocation: ${cityNameErrorMessage(locError)}`,
);
}
}
// Verify pro exists and is published. Wrap getById so the "does not
// exist" and "not published" cases both resolve to the same 400
// response — otherwise the error-status differential (404 vs 400)
// lets an attacker enumerate which pro IDs exist in the system.
const pro = await services.pro.getById(body.proId).catch(() => null);
if (!pro || pro.status !== "published") {
throw new ValidationError("Pro not found");
}
// WhatsApp path: validate pro has WhatsApp before creating inquiry
if (body.type === "whatsapp" && !pro.whatsapp) {
throw new ValidationError(
"This pro does not have WhatsApp configured",
);
}
// If projectId provided, verify it belongs to the pro AND is published.
// Previously only the proId link was checked; referencing a draft or
// archived project with the correct proId succeeded, leaking the
// existence of unpublished projects. Same catch-and-uniform-error
// pattern as the pro check above.
if (body.projectId) {
const project = await services.project
.getById(body.projectId)
.catch(() => null);
if (
!project ||
project.proId !== body.proId ||
project.status !== "published"
) {
throw new ValidationError("Project does not belong to this pro");
}
}
const inquiry = await services.inquiry.create({
proId: body.proId,
projectId: body.projectId,
customerName: normalizedCustomerName,
customerPhone: normalizedPhone,
customerEmail: body.customerEmail,
requirement: body.requirement,
type: body.type || "form_submit",
sourcePage: body.sourcePage,
requirementType: body.requirementType,
sourceType: body.sourceType || "marketplace",
});
// Send notifications via communication gateway
const dal = c.get("dal");
c.executionCtx.waitUntil(
(async () => {
try {
const project = body.projectId
? await services.project.getById(body.projectId).catch(() => null)
: null;
const gateway = new CommunicationGateway(dal, c.env);
const handler = new NewInquiryHandler(gateway, dal);
await handler.handle({
inquiryId: inquiry.id,
proId: body.proId,
customerName: normalizedCustomerName,
customerPhone: normalizedPhone,
customerEmail: body.customerEmail,
customerLocation: body.customerLocation,
requirement: body.requirement,
requirementType: body.requirementType,
projectTitle: project?.title,
});
} catch (err) {
logger.error("[INQUIRY] Failed to send notifications:", err);
}
})(),
);
// Auto-create CRM lead from inquiry, then send in-app + push notification
// Notification fires AFTER lead creation so we have the correct lead ID for deep linking
c.executionCtx.waitUntil(
(async () => {
let lead: Awaited<ReturnType<typeof services.leads.createFromInquiry>> | null = null;
try {
await services.pipelineStages.ensureInitialized(body.proId);
} catch (err) {
logger.error("[INQUIRY] Pipeline init failed:", err);
}
try {
lead = await services.leads.createFromInquiry(body.proId, {
customerName: normalizedCustomerName,
customerPhone: normalizedPhone,
customerEmail: body.customerEmail,
customerLocation: body.customerLocation,
requirement: body.requirement,
requirementType: body.requirementType,
inquiryId: inquiry.id,
});
} catch (err) {
logger.error("[INQUIRY] CRM lead creation failed:", err);
}
try {
const deepLink = lead ? `/crm/leads/${lead.id}` : "/crm";
await services.notification.notify({
proId: body.proId,
eventType: "new_inquiry",
title: `New enquiry from ${normalizedCustomerName}`,
body:
body.requirement?.substring(0, 200) ??
"New customer enquiry received",
data: {
url: deepLink,
...(lead && { leadId: lead.id }),
inquiryId: inquiry.id,
},
});
} catch (err) {
logger.error("[INQUIRY] Notification delivery failed:", err);
}
})(),
);
// WhatsApp path: generate redirect URL
if (body.type === "whatsapp") {
const safetyConfig = getWhatsAppSafetyConfig(resolveEnvironment(c.env.ENVIRONMENT));
const whatsappRedirectUrl = buildWhatsAppRedirectUrl({
proWhatsapp: pro.whatsapp as string,
proName: pro.businessName,
customerName: normalizedCustomerName,
customerPhone: normalizedPhone,
requirementType: body.requirementType,
requirementDescription,
environment: c.env.ENVIRONMENT,
overrideNumber: safetyConfig.overrideNumber,
});
return success(
c,
{ id: inquiry.id, whatsapp_redirect_url: whatsappRedirectUrl },
201,
);
}
return success(c, inquiry, 201);
} catch (err) {
return handleError(c, err);
}
});
export default inquiries;
|