import { randomUUID } from "node:crypto"; import { AppError, type Db } from "@cohaise/server"; import type { ContactRow } from "../models/types.js"; import { isDuplicateEntry, isForeignKeyViolation } from "../utils/dbErrors.js"; import { normalizeEmail } from "../utils/normalize.js"; import { uuidSchema } from "../utils/validation.js"; import { buildAssignments } from "../utils/sql.js"; import type { Pagination } from "../utils/pagination.js"; const SELECT_CONTACT = ` SELECT ct.id, ct.first_name, ct.last_name, ct.organization_id, o.name AS organization_name, ct.email, ct.phone, ct.mobile, ct.job_title, ct.country_id, c.name AS country_name, c.code AS country_code, ct.external_source, ct.external_id, ct.description, ct.owner_id, CONCAT(u.first_name, ' ', u.last_name) AS owner_name, ct.created_at, ct.updated_at FROM contacts ct LEFT JOIN organizations o ON o.id = ct.organization_id AND o.deleted_at IS NULL LEFT JOIN countries c ON c.id = ct.country_id LEFT JOIN users u ON u.id = ct.owner_id`; export interface ContactCreate { firstName: string; lastName: string; organizationId?: string | null | undefined; email?: string | null | undefined; phone?: string | null | undefined; mobile?: string | null | undefined; jobTitle?: string | null | undefined; countryId?: number | null | undefined; externalSource?: string | null | undefined; externalId?: string | null | undefined; description?: string | null | undefined; } export type ContactUpdate = { [Key in keyof ContactCreate]?: ContactCreate[Key] | undefined; }; export interface ContactList { total: number; contacts: ContactRow[]; } export interface ContactFilters { search: string; organizationId: string; } export const toPublicContact = (row: ContactRow) => ({ id: row.id, first_name: row.first_name, last_name: row.last_name, organization_id: row.organization_id, organization_name: row.organization_name, email: row.email, phone: row.phone, mobile: row.mobile, job_title: row.job_title, country_id: row.country_id, country_name: row.country_name, country_code: row.country_code, external_source: row.external_source, external_id: row.external_id, description: row.description, owner_id: row.owner_id, owner_name: row.owner_name, created_at: row.created_at, updated_at: row.updated_at, }); export const listContacts = async ( db: Db, filters: ContactFilters, pagination: Pagination, ): Promise => { const clauses = ["ct.deleted_at IS NULL"]; const params: unknown[] = []; if (filters.search) { clauses.push( "(ct.first_name LIKE ? OR ct.last_name LIKE ? OR ct.email LIKE ? OR o.name LIKE ?)", ); const term = `%${filters.search}%`; params.push(term, term, term, term); } if (uuidSchema.safeParse(filters.organizationId).success) { clauses.push("ct.organization_id = ?"); params.push(filters.organizationId); } const where = `WHERE ${clauses.join(" AND ")}`; const totalRows = await db.query<{ total: number }>( `SELECT COUNT(*) AS total FROM contacts ct LEFT JOIN organizations o ON o.id = ct.organization_id AND o.deleted_at IS NULL ${where}`, params, ); const rows = await db.query( `${SELECT_CONTACT} ${where} ORDER BY ct.last_name, ct.first_name LIMIT ${pagination.limit} OFFSET ${pagination.offset}`, params, ); return { total: Number(totalRows[0]?.total ?? 0), contacts: rows }; }; export const getContact = async (db: Db, id: string): Promise => { const row = await db.one( `${SELECT_CONTACT} WHERE ct.id = ? AND ct.deleted_at IS NULL`, [id], ); if (!row) throw AppError.notFound("Prospect introuvable."); return row; }; export const createContact = async ( db: Db, ownerId: string, data: ContactCreate, ): Promise => { const id = randomUUID(); try { await db.exec( `INSERT INTO contacts (id, first_name, last_name, organization_id, email, phone, mobile, job_title, country_id, external_source, external_id, description, owner_id, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ id, data.firstName, data.lastName, data.organizationId ?? null, normalizeEmail(data.email), data.phone ?? null, data.mobile ?? null, data.jobTitle ?? null, data.countryId ?? null, data.externalSource ?? null, data.externalId ?? null, data.description ?? null, ownerId, ownerId, ], ); } catch (error) { if (isDuplicateEntry(error)) { throw AppError.conflict("Un prospect actif porte deja cette adresse."); } if (isForeignKeyViolation(error)) { throw AppError.badRequest("L'entreprise ou le pays reference n'existe pas."); } throw error; } return db.required(`${SELECT_CONTACT} WHERE ct.id = ?`, [id]); }; export const updateContact = async ( db: Db, id: string, data: ContactUpdate, ): Promise => { const existing = await db.one<{ id: string }>( "SELECT id FROM contacts WHERE id = ? AND deleted_at IS NULL", [id], ); if (!existing) throw AppError.notFound("Prospect introuvable."); const assignments = buildAssignments({ first_name: data.firstName, last_name: data.lastName, organization_id: data.organizationId, email: data.email === undefined ? undefined : normalizeEmail(data.email), phone: data.phone, mobile: data.mobile, job_title: data.jobTitle, country_id: data.countryId, external_source: data.externalSource, external_id: data.externalId, description: data.description, }); if (!assignments) throw AppError.badRequest("Aucune modification fournie."); try { await db.exec( `UPDATE contacts SET ${assignments.clause} WHERE id = ? AND deleted_at IS NULL`, [...assignments.values, id], ); } catch (error) { if (isDuplicateEntry(error)) { throw AppError.conflict("Un prospect actif porte deja cette adresse."); } if (isForeignKeyViolation(error)) { throw AppError.badRequest("L'entreprise ou le pays reference n'existe pas."); } throw error; } return db.required(`${SELECT_CONTACT} WHERE ct.id = ?`, [id]); }; export const deleteContact = async (db: Db, id: string): Promise => { const result = await db.exec( "UPDATE contacts SET deleted_at = UTC_TIMESTAMP() WHERE id = ? AND deleted_at IS NULL", [id], ); if (result.affectedRows === 0) throw AppError.notFound("Prospect introuvable."); };