import { randomUUID } from "node:crypto"; import { AppError, type Db } from "@cohaise/server"; import { PUBLIC_LEAD_SOURCE } from "../config/app.js"; import type { LeadInput } from "../models/types.js"; import { isDuplicateEntry, isForeignKeyViolation } from "../utils/dbErrors.js"; import { normalizeEmail } from "../utils/normalize.js"; import { findOrCreateOrganization } from "./organizationService.js"; export interface LeadResult { ok: true; id: string; } /** * Crée un prospect depuis le formulaire public de la vitrine. * * Protection anti-abus à deux étages, appliquée par la route : * - un honeypot (champ invisible que seuls les robots remplissent) ; * - un rate-limit simple en mémoire, par IP (Cloudflare reste la 1re ligne). * Le lead est posé dans `contacts` avec `external_source = 'cohaise-web'`, * non assigné, pour apparaître dans la liste des prospects du CRM. */ export const createLead = async (db: Db, data: LeadInput): Promise => { // Honeypot rempli : robot. On feint la réussite pour ne pas se trahir. if (data.website) return { ok: true, id: randomUUID() }; const organizationId = data.organization ? await findOrCreateOrganization(db, data.organization) : null; const id = randomUUID(); try { await db.exec( `INSERT INTO contacts (id, first_name, last_name, organization_id, email, phone, job_title, country_id, external_source, external_id, description, owner_id, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ id, data.firstName, data.lastName, organizationId, normalizeEmail(data.email), data.phone ?? null, null, null, PUBLIC_LEAD_SOURCE, null, data.message ?? null, null, null, ], ); } catch (error) { if (isDuplicateEntry(error)) { throw AppError.conflict("Cette adresse a deja ete enregistree."); } if (isForeignKeyViolation(error)) { throw AppError.badRequest("L'entreprise referencee n'existe pas."); } throw error; } return { ok: true, id }; };