feat: migrate showcase to Next.js and overhaul CRM UI

- rebuild the public site on the Next.js App Router with static export,
  per-section SEO pages, metadata, sitemap, robots and a generated OG image
- add full-screen scroll-snap regions, staged scroll reveals, a hash-free
  tab navigation with a sliding indicator and region-by-region menu scrolling
- replace the theme text toggle with animated sun/moon icons
- restructure the CRM API into config, middleware, models, routes, services
  and utils layers
- redesign the CRM shell with a single surface, tab rail, full-width blurred
  DataTable, record dialogs and mask-based icons
- update Docker/Nginx publishing, Makefile targets, shared UI polish and docs
This commit is contained in:
2026-11-16 00:52:29 +01:00
parent ab4cde1ce2
commit 09cf07d79b
113 changed files with 6427 additions and 2364 deletions
+20
View File
@@ -0,0 +1,20 @@
/**
* Réglages applicatifs du CRM. Les secrets et paramètres d'environnement
* restent dans `@cohaise/server` (voir `config.ts`) : ce fichier ne contient
* que des constantes métier, sans dépendance à l'environnement.
*/
/** Taille de page par défaut des listes paginées. */
export const DEFAULT_PAGE_SIZE = 25;
/** Plafond de page pour éviter les requêtes trop larges. */
export const MAX_PAGE_SIZE = 100;
/** Source externe des prospects créés par le formulaire de la vitrine. */
export const PUBLIC_LEAD_SOURCE = "cohaise-web";
/** Anti-abus du formulaire public : 5 envois par IP et par quart d'heure. */
export const PUBLIC_LEAD_RATE_LIMIT = {
windowMs: 15 * 60 * 1000,
max: 5,
} as const;
+7 -7
View File
@@ -1,11 +1,11 @@
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { purgeExpiredSessions, startService } from "@cohaise/server";
import { registerAuthRoutes } from "./routes/auth.js";
import { registerCountryRoutes } from "./routes/countries.js";
import { registerOrganizationRoutes } from "./routes/organizations.js";
import { registerContactRoutes } from "./routes/contacts.js";
import { registerLeadRoutes } from "./routes/leads.js";
import { registerAuthRoutes } from "./routes/authRoutes.js";
import { registerCountryRoutes } from "./routes/countryRoutes.js";
import { registerOrganizationRoutes } from "./routes/organizationRoutes.js";
import { registerContactRoutes } from "./routes/contactRoutes.js";
import { registerLeadRoutes } from "./routes/leadRoutes.js";
const migrationsDir = join(dirname(fileURLToPath(import.meta.url)), "../migrations");
@@ -18,8 +18,8 @@ void startService({
registerOrganizationRoutes(app, db);
registerContactRoutes(app, db);
registerLeadRoutes(app, db);
// Les jetons expires n'ont rien a faire en base : purge au demarrage
// plutot qu'un EVENT, qui dependrait du planificateur MariaDB.
// Les jetons expirés n'ont rien à faire en base : purge au démarrage
// plutôt qu'un EVENT, qui dépendrait du planificateur MariaDB.
void purgeExpiredSessions(db);
},
});
+13
View File
@@ -0,0 +1,13 @@
/**
* Porte d'authentification appliquée à une ressource protégée.
*
* `attachUser` est monté sur le chemin exact et sur ses sous-chemins : Hono
* n'hérite pas automatiquement du middleware d'un préfixe. Le contrôle fin
* (`requireAuth`) reste déclaré au niveau de chaque route, comme avant.
*/
import { attachUser, type App, type Db } from "@cohaise/server";
export const mountSession = (app: App, db: Db, basePath: string): void => {
app.use(`${basePath}/*`, attachUser(db));
app.use(basePath, attachUser(db));
};
+88
View File
@@ -0,0 +1,88 @@
/**
* Lignes de base de données et formes exposées par l'API.
*
* Les colonnes gardent leur nom SQL (`first_name`, `phone_code`, …) : les
* services les convertissent au plus près du SELECT, jamais dans les routes.
*/
export interface UserRow {
id: string;
email: string;
password_hash: string;
first_name: string;
last_name: string;
is_active: number;
must_change_password: number;
}
/** Utilisateur renvoyé au client : jamais de hash ni de drapeau interne. */
export interface AuthUser {
id: string;
email: string;
first_name: string;
last_name: string;
must_change_password: boolean;
}
export interface CountryRow {
id: number;
code: string;
name: string;
phone_code: string | null;
}
export interface OrganizationRow {
id: string;
name: string;
slug: string;
website: string | null;
industry: string | null;
phone: string | null;
email: string | null;
address_line1: string | null;
address_line2: string | null;
postal_code: string | null;
city: string | null;
country_id: number | null;
country_name: string | null;
country_code: string | null;
description: string | null;
owner_id: string | null;
owner_name: string | null;
created_at: string;
updated_at: string;
}
export interface ContactRow {
id: string;
first_name: string;
last_name: string;
organization_id: string | null;
organization_name: string | null;
email: string | null;
phone: string | null;
mobile: string | null;
job_title: string | null;
country_id: number | null;
country_name: string | null;
country_code: string | null;
external_source: string | null;
external_id: string | null;
description: string | null;
owner_id: string | null;
owner_name: string | null;
created_at: string;
updated_at: string;
}
/** Corps du formulaire public de la vitrine. */
export interface LeadInput {
firstName: string;
lastName: string;
email: string;
organization?: string | null | undefined;
phone?: string | null | undefined;
message?: string | null | undefined;
/** Honeypot : rempli uniquement par les robots. */
website?: string | null | undefined;
}
-151
View File
@@ -1,151 +0,0 @@
import { z } from "zod";
import {
AppError,
attachUser,
clearSessionCookie,
createSession,
currentUser,
hashPassword,
isHttpsRequest,
requireAuth,
revokeSession,
setSessionCookie,
sha256,
verifyPassword,
type App,
type Config,
type Db,
} from "@cohaise/server";
const credentials = z.object({
email: z.string().trim().toLowerCase().email().max(255),
password: z.string().min(1).max(1024),
});
const changePassword = z.object({
current: z.string().min(1).max(1024),
next: z.string().min(8).max(1024),
});
interface UserRow {
id: string;
email: string;
password_hash: string;
first_name: string;
last_name: string;
is_active: number;
must_change_password: number;
}
const SELECT_USER = `
SELECT u.id, u.email, u.password_hash, u.first_name, u.last_name,
u.is_active, u.must_change_password
FROM users u`;
/**
* Empreinte de repli, calculee pour n'importe quelle chaine : une adresse
* inconnue doit prendre exactement le meme temps qu'une adresse connue avec
* un mauvais mot de passe, sinon l'API devient un annuaire.
*/
const DUMMY_HASH_PROMISE = hashPassword("placeholder-for-anti-enumeration").catch(() => null);
void DUMMY_HASH_PROMISE;
const publicUser = (row: UserRow) => ({
id: row.id,
email: row.email,
first_name: row.first_name,
last_name: row.last_name,
must_change_password: row.must_change_password === 1,
});
export const registerAuthRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/crm/auth/*", attachUser(db));
app.post("/api/crm/auth/login", async (context) => {
const parsed = credentials.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
throw AppError.badRequest("Identifiants invalides.");
}
const row = await db.one<UserRow>(
`${SELECT_USER} WHERE u.email = ? AND u.deleted_at IS NULL`,
[parsed.data.email],
);
const stored = row?.password_hash ?? (await DUMMY_HASH_PROMISE) ?? "";
const valid = stored ? await verifyPassword(parsed.data.password, stored) : false;
if (!row || !valid) throw AppError.unauthorized("Identifiants invalides.");
if (row.is_active !== 1) throw AppError.unauthorized("Compte desactive.");
const { token, expiresAt } = await createSession(
db,
row.id,
{
ipAddress: context.req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? null,
userAgent: context.req.header("user-agent") ?? null,
},
config.SESSION_TTL_HOURS,
);
await db.exec("UPDATE users SET last_login_at = UTC_TIMESTAMP(3) WHERE id = ?", [row.id]);
// Le schema reel de la requete, pas PUBLIC_ORIGIN : voir isHttpsRequest.
const secure = isHttpsRequest(context, config.TRUST_PROXY);
setSessionCookie(context, token, expiresAt, secure);
return context.json({ user: publicUser(row) });
});
app.post("/api/crm/auth/logout", requireAuth, async (context) => {
const token = context.get("token") as string | undefined;
if (token) await revokeSession(db, token);
clearSessionCookie(context);
return context.json({ ok: true });
});
app.get("/api/crm/auth/me", requireAuth, async (context) => {
const session = currentUser(context);
const row = await db.one<UserRow>(`${SELECT_USER} WHERE u.id = ? AND u.deleted_at IS NULL`, [
session.id,
]);
if (!row) throw AppError.unauthorized();
return context.json({ user: publicUser(row) });
});
app.post("/api/crm/auth/change-password", requireAuth, async (context) => {
const session = currentUser(context);
const parsed = changePassword.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
throw AppError.badRequest("Le nouveau mot de passe doit contenir au moins 8 caracteres.");
}
const row = await db.one<{ password_hash: string }>(
"SELECT password_hash FROM users WHERE id = ? AND deleted_at IS NULL",
[session.id],
);
if (!row) throw AppError.unauthorized();
if (!(await verifyPassword(parsed.data.current, row.password_hash))) {
throw AppError.unauthorized("Mot de passe actuel incorrect.");
}
if (parsed.data.current === parsed.data.next) {
throw AppError.badRequest("Le nouveau mot de passe doit differer de l'actuel.");
}
const hash = await hashPassword(parsed.data.next);
// Pas de password_changed_at ici : cette colonne appartient au modele du
// Cloud. Le CRM n'a pas de notion de confirmation d'identite a celebrer.
await db.exec("UPDATE users SET password_hash = ?, must_change_password = 0 WHERE id = ?", [
hash,
session.id,
]);
// La session courante est conservee, toutes les autres sont revoquees.
await db.exec(
`UPDATE user_sessions
SET revoked_at = UTC_TIMESTAMP()
WHERE user_id = ? AND revoked_at IS NULL AND token_hash <> ?`,
[session.id, sha256(context.get("token") ?? "")],
);
return context.json({ ok: true });
});
};
+83
View File
@@ -0,0 +1,83 @@
import { z } from "zod";
import {
AppError,
clearSessionCookie,
currentUser,
isHttpsRequest,
requireAuth,
setSessionCookie,
type App,
type Config,
type Db,
} from "@cohaise/server";
import { mountSession } from "../middleware/auth.js";
import {
changePassword,
getSessionUser,
login,
logout,
} from "../services/authService.js";
const credentials = z.object({
email: z.string().trim().toLowerCase().email().max(255),
password: z.string().min(1).max(1024),
});
const newPassword = z.object({
current: z.string().min(1).max(1024),
next: z.string().min(8).max(1024),
});
export const registerAuthRoutes = (app: App, db: Db, config: Config): void => {
mountSession(app, db, "/api/crm/auth");
app.post("/api/crm/auth/login", async (context) => {
const parsed = credentials.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) throw AppError.badRequest("Identifiants invalides.");
const result = await login(db, config, {
email: parsed.data.email,
password: parsed.data.password,
ipAddress: context.req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? null,
userAgent: context.req.header("user-agent") ?? null,
});
// Le schéma réel de la requête, pas PUBLIC_ORIGIN : voir isHttpsRequest.
const secure = isHttpsRequest(context, config.TRUST_PROXY);
setSessionCookie(context, result.token, result.expiresAt, secure);
return context.json({ user: result.user });
});
app.post("/api/crm/auth/logout", requireAuth, async (context) => {
await logout(db, context.get("token"));
clearSessionCookie(context);
return context.json({ ok: true });
});
app.get("/api/crm/auth/me", requireAuth, async (context) => {
const session = currentUser(context);
const user = await getSessionUser(db, session.id);
return context.json({ user });
});
app.post("/api/crm/auth/change-password", requireAuth, async (context) => {
const session = currentUser(context);
const parsed = newPassword.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
throw AppError.badRequest(
"Le nouveau mot de passe doit contenir au moins 8 caracteres.",
);
}
await changePassword(
db,
session.id,
context.get("token"),
parsed.data.current,
parsed.data.next,
);
return context.json({ ok: true });
});
};
+106
View File
@@ -0,0 +1,106 @@
import { z } from "zod";
import {
AppError,
currentUser,
requireAuth,
type App,
type Db,
} from "@cohaise/server";
import { mountSession } from "../middleware/auth.js";
import {
createContact,
deleteContact,
getContact,
listContacts,
toPublicContact,
updateContact,
} from "../services/contactService.js";
import { parsePagination } from "../utils/pagination.js";
import { invalidBody, uuidSchema } from "../utils/validation.js";
const createContactBody = z.object({
firstName: z.string().trim().min(1).max(100),
lastName: z.string().trim().min(1).max(100),
organizationId: uuidSchema.nullish(),
email: z.string().trim().max(255).nullish(),
phone: z.string().trim().max(50).nullish(),
mobile: z.string().trim().max(50).nullish(),
jobTitle: z.string().trim().max(150).nullish(),
countryId: z.coerce.number().int().positive().nullish(),
externalSource: z.string().trim().max(50).nullish(),
externalId: z.string().trim().max(100).nullish(),
description: z.string().trim().max(4000).nullish(),
});
const updateContactBody = createContactBody.partial();
export const registerContactRoutes = (app: App, db: Db): void => {
mountSession(app, db, "/api/crm/contacts");
app.get("/api/crm/contacts", requireAuth, async (context) => {
const pagination = parsePagination(
context.req.query("page"),
context.req.query("limit"),
);
const { total, contacts } = await listContacts(
db,
{
search: context.req.query("q")?.trim() ?? "",
organizationId: context.req.query("organizationId")?.trim() ?? "",
},
pagination,
);
return context.json({
total,
page: pagination.page,
limit: pagination.limit,
contacts: contacts.map(toPublicContact),
});
});
app.get("/api/crm/contacts/:id", requireAuth, async (context) => {
const id = context.req.param("id");
if (!id || !uuidSchema.safeParse(id).success) {
throw AppError.notFound("Prospect introuvable.");
}
const contact = await getContact(db, id);
return context.json({ contact: toPublicContact(contact) });
});
app.post("/api/crm/contacts", requireAuth, async (context) => {
const user = currentUser(context);
const parsed = createContactBody.safeParse(
await context.req.json().catch(() => null),
);
if (!parsed.success) throw invalidBody(parsed.error);
const contact = await createContact(db, user.id, parsed.data);
return context.json({ contact: toPublicContact(contact) }, 201);
});
app.patch("/api/crm/contacts/:id", requireAuth, async (context) => {
const id = context.req.param("id");
if (!id || !uuidSchema.safeParse(id).success) {
throw AppError.notFound("Prospect introuvable.");
}
const parsed = updateContactBody.safeParse(
await context.req.json().catch(() => null),
);
if (!parsed.success) throw invalidBody(parsed.error);
const contact = await updateContact(db, id, parsed.data);
return context.json({ contact: toPublicContact(contact) });
});
app.delete("/api/crm/contacts/:id", requireAuth, async (context) => {
const id = context.req.param("id");
if (!id || !uuidSchema.safeParse(id).success) {
throw AppError.notFound("Prospect introuvable.");
}
await deleteContact(db, id);
return context.json({ ok: true });
});
};
-274
View File
@@ -1,274 +0,0 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import {
AppError,
attachUser,
currentUser,
requireAuth,
type App,
type Db,
} from "@cohaise/server";
const uuid = z
.string()
.regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, "Identifiant invalide.");
const createContact = z.object({
firstName: z.string().trim().min(1).max(100),
lastName: z.string().trim().min(1).max(100),
organizationId: z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i).nullish(),
email: z.string().trim().max(255).nullish(),
phone: z.string().trim().max(50).nullish(),
mobile: z.string().trim().max(50).nullish(),
jobTitle: z.string().trim().max(150).nullish(),
countryId: z.coerce.number().int().positive().nullish(),
externalSource: z.string().trim().max(50).nullish(),
externalId: z.string().trim().max(100).nullish(),
description: z.string().trim().max(4000).nullish(),
});
const updateContact = createContact.partial();
interface ContactRow {
id: string;
first_name: string;
last_name: string;
organization_id: string | null;
organization_name: string | null;
email: string | null;
phone: string | null;
mobile: string | null;
job_title: string | null;
country_id: number | null;
country_name: string | null;
country_code: string | null;
external_source: string | null;
external_id: string | null;
description: string | null;
owner_id: string | null;
owner_name: string | null;
created_at: string;
updated_at: string;
}
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`;
const publicContact = (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,
});
/** Un e-mail absent ne doit pas heurter l'index actif : NULL passe partout. */
const emailOrNull = (value: string | null | undefined): string | null =>
value ? value.toLowerCase() : null;
export const registerContactRoutes = (app: App, db: Db): void => {
app.use("/api/crm/contacts/*", attachUser(db));
app.use("/api/crm/contacts", attachUser(db));
app.get("/api/crm/contacts", requireAuth, async (context) => {
const search = context.req.query("q")?.trim() ?? "";
const organizationId = context.req.query("organizationId")?.trim() ?? "";
const page = Math.max(1, Number(context.req.query("page") ?? 1) || 1);
const limit = Math.min(100, Math.max(1, Number(context.req.query("limit") ?? 25) || 25));
const offset = (page - 1) * limit;
const clauses = ["ct.deleted_at IS NULL"];
const params: unknown[] = [];
if (search) {
clauses.push(
"(ct.first_name LIKE ? OR ct.last_name LIKE ? OR ct.email LIKE ? OR o.name LIKE ?)",
);
const term = `%${search}%`;
params.push(term, term, term, term);
}
if (uuid.safeParse(organizationId).success) {
clauses.push("ct.organization_id = ?");
params.push(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 total = Number(totalRows[0]?.total ?? 0);
const rows = await db.query<ContactRow>(
`${SELECT_CONTACT} ${where} ORDER BY ct.last_name, ct.first_name LIMIT ${limit} OFFSET ${offset}`,
params,
);
return context.json({
total,
page,
limit,
contacts: rows.map(publicContact),
});
});
app.get("/api/crm/contacts/:id", requireAuth, async (context) => {
const id = context.req.param("id");
if (!uuid.safeParse(id).success) throw AppError.notFound("Prospect introuvable.");
const row = await db.one<ContactRow>(
`${SELECT_CONTACT} WHERE ct.id = ? AND ct.deleted_at IS NULL`,
[id],
);
if (!row) throw AppError.notFound("Prospect introuvable.");
return context.json({ contact: publicContact(row) });
});
app.post(
"/api/crm/contacts",
requireAuth,
async (context) => {
const user = currentUser(context);
const parsed = createContact.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
const issue = parsed.error.issues[0];
throw AppError.badRequest(issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.");
}
const data = parsed.data;
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,
emailOrNull(data.email),
data.phone ?? null,
data.mobile ?? null,
data.jobTitle ?? null,
data.countryId ?? null,
data.externalSource ?? null,
data.externalId ?? null,
data.description ?? null,
user.id,
user.id,
],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Un prospect actif porte deja cette adresse.");
}
if ((error as { errno?: number }).errno === 1452) {
throw AppError.badRequest("L'entreprise ou le pays reference n'existe pas.");
}
throw error;
}
const created = await db.required<ContactRow>(`${SELECT_CONTACT} WHERE ct.id = ?`, [id]);
return context.json({ contact: publicContact(created) }, 201);
},
);
app.patch(
"/api/crm/contacts/:id",
requireAuth,
async (context) => {
const id = context.req.param("id");
if (!uuid.safeParse(id).success) throw AppError.notFound("Prospect introuvable.");
const parsed = updateContact.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) throw AppError.badRequest("Corps invalide.");
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 columns: Record<string, unknown> = {
first_name: parsed.data.firstName,
last_name: parsed.data.lastName,
organization_id: parsed.data.organizationId,
email: parsed.data.email === undefined ? undefined : emailOrNull(parsed.data.email),
phone: parsed.data.phone,
mobile: parsed.data.mobile,
job_title: parsed.data.jobTitle,
country_id: parsed.data.countryId,
external_source: parsed.data.externalSource,
external_id: parsed.data.externalId,
description: parsed.data.description,
};
const assignments = Object.keys(columns)
.filter((key) => columns[key] !== undefined)
.map((key) => `${key} = ?`);
if (assignments.length === 0) throw AppError.badRequest("Aucune modification fournie.");
const values = Object.keys(columns)
.filter((key) => columns[key] !== undefined)
.map((key) => columns[key]);
try {
await db.exec(
`UPDATE contacts SET ${assignments.join(", ")} WHERE id = ? AND deleted_at IS NULL`,
[...values, id],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Un prospect actif porte deja cette adresse.");
}
if ((error as { errno?: number }).errno === 1452) {
throw AppError.badRequest("L'entreprise ou le pays reference n'existe pas.");
}
throw error;
}
const updated = await db.required<ContactRow>(`${SELECT_CONTACT} WHERE ct.id = ?`, [id]);
return context.json({ contact: publicContact(updated) });
},
);
app.delete(
"/api/crm/contacts/:id",
requireAuth,
async (context) => {
const id = context.req.param("id");
if (!uuid.safeParse(id).success) throw AppError.notFound("Prospect introuvable.");
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.");
return context.json({ ok: true });
},
);
};
-150
View File
@@ -1,150 +0,0 @@
import { z } from "zod";
import {
AppError,
attachUser,
requireAuth,
type App,
type Db,
} from "@cohaise/server";
const createCountry = z.object({
code: z
.string()
.trim()
.toUpperCase()
.regex(/^[A-Z]{2}$/, "Code ISO 3166-1 alpha-2 attendu, deux lettres."),
name: z.string().trim().min(1).max(100),
phoneCode: z
.string()
.trim()
.regex(/^\+?[0-9]{1,7}$/, "Indicatif telephonique attendu.")
.nullish(),
});
const updateCountry = createCountry.partial();
interface CountryRow {
id: number;
code: string;
name: string;
phone_code: string | null;
}
const publicCountry = (row: CountryRow) => ({
id: row.id,
code: row.code,
name: row.name,
phone_code: row.phone_code,
});
export const registerCountryRoutes = (app: App, db: Db): void => {
app.use("/api/crm/countries/*", attachUser(db));
app.use("/api/crm/countries", attachUser(db));
// Referentiel : lecture ouverte a tout le monde authentifie, ecriture
// reservee. Le tri est collationnel, donc sans accent ni casse douteuse.
app.get("/api/crm/countries", requireAuth, async (context) => {
const search = context.req.query("q")?.trim() ?? "";
const where = search ? "WHERE name LIKE ? OR code = ?" : "";
const params = search ? [`%${search}%`, search.toUpperCase()] : [];
const rows = await db.query<CountryRow>(
`SELECT id, code, name, phone_code FROM countries ${where} ORDER BY name`,
params,
);
return context.json({ countries: rows.map(publicCountry) });
});
app.post(
"/api/crm/countries",
requireAuth,
async (context) => {
const parsed = createCountry.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
const issue = parsed.error.issues[0];
throw AppError.badRequest(issue?.message ?? "Corps invalide.");
}
try {
await db.exec("INSERT INTO countries (code, name, phone_code) VALUES (?, ?, ?)", [
parsed.data.code,
parsed.data.name,
parsed.data.phoneCode ?? null,
]);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce pays existe deja.");
}
throw error;
}
const created = await db.required<CountryRow>(
"SELECT id, code, name, phone_code FROM countries WHERE code = ?",
[parsed.data.code],
);
return context.json({ country: publicCountry(created) }, 201);
},
);
app.patch(
"/api/crm/countries/:id",
requireAuth,
async (context) => {
const id = Number(context.req.param("id"));
if (!Number.isInteger(id) || id <= 0) throw AppError.notFound("Pays introuvable.");
const parsed = updateCountry.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) throw AppError.badRequest("Corps invalide.");
const columns: Record<string, unknown> = {
code: parsed.data.code,
name: parsed.data.name,
phone_code: parsed.data.phoneCode,
};
const assignments = Object.keys(columns)
.filter((key) => columns[key] !== undefined)
.map((key) => `${key} = ?`);
if (assignments.length === 0) throw AppError.badRequest("Aucune modification fournie.");
const values = Object.keys(columns)
.filter((key) => columns[key] !== undefined)
.map((key) => columns[key]);
try {
const result = await db.exec(
`UPDATE countries SET ${assignments.join(", ")} WHERE id = ?`,
[...values, id],
);
if (result.affectedRows === 0) throw AppError.notFound("Pays introuvable.");
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce code de pays existe deja.");
}
throw error;
}
const updated = await db.required<CountryRow>(
"SELECT id, code, name, phone_code FROM countries WHERE id = ?",
[id],
);
return context.json({ country: publicCountry(updated) });
},
);
app.delete(
"/api/crm/countries/:id",
requireAuth,
async (context) => {
const id = Number(context.req.param("id"));
if (!Number.isInteger(id) || id <= 0) throw AppError.notFound("Pays introuvable.");
try {
const result = await db.exec("DELETE FROM countries WHERE id = ?", [id]);
if (result.affectedRows === 0) throw AppError.notFound("Pays introuvable.");
} catch (error) {
if ((error as { errno?: number }).errno === 1451) {
throw AppError.conflict("Des entreprises ou contacts referencent ce pays.");
}
throw error;
}
return context.json({ ok: true });
},
);
};
+69
View File
@@ -0,0 +1,69 @@
import { z } from "zod";
import { AppError, requireAuth, type App, type Db } from "@cohaise/server";
import { mountSession } from "../middleware/auth.js";
import {
createCountry,
deleteCountry,
listCountries,
toPublicCountry,
updateCountry,
} from "../services/countryService.js";
import { invalidBody } from "../utils/validation.js";
const createCountryBody = z.object({
code: z
.string()
.trim()
.toUpperCase()
.regex(/^[A-Z]{2}$/, "Code ISO 3166-1 alpha-2 attendu, deux lettres."),
name: z.string().trim().min(1).max(100),
phoneCode: z
.string()
.trim()
.regex(/^\+?[0-9]{1,7}$/, "Indicatif telephonique attendu.")
.nullish(),
});
const updateCountryBody = createCountryBody.partial();
export const registerCountryRoutes = (app: App, db: Db): void => {
mountSession(app, db, "/api/crm/countries");
// Référentiel : lecture ouverte à tout le monde authentifié, écriture
// réservée.
app.get("/api/crm/countries", requireAuth, async (context) => {
const rows = await listCountries(db, context.req.query("q") ?? "");
return context.json({ countries: rows.map(toPublicCountry) });
});
app.post("/api/crm/countries", requireAuth, async (context) => {
const parsed = createCountryBody.safeParse(
await context.req.json().catch(() => null),
);
if (!parsed.success) throw invalidBody(parsed.error);
const country = await createCountry(db, parsed.data);
return context.json({ country: toPublicCountry(country) }, 201);
});
app.patch("/api/crm/countries/:id", requireAuth, async (context) => {
const id = Number(context.req.param("id"));
if (!Number.isInteger(id) || id <= 0) throw AppError.notFound("Pays introuvable.");
const parsed = updateCountryBody.safeParse(
await context.req.json().catch(() => null),
);
if (!parsed.success) throw invalidBody(parsed.error);
const country = await updateCountry(db, id, parsed.data);
return context.json({ country: toPublicCountry(country) });
});
app.delete("/api/crm/countries/:id", requireAuth, async (context) => {
const id = Number(context.req.param("id"));
if (!Number.isInteger(id) || id <= 0) throw AppError.notFound("Pays introuvable.");
await deleteCountry(db, id);
return context.json({ ok: true });
});
};
+51
View File
@@ -0,0 +1,51 @@
import { z } from "zod";
import { AppError, type App, type Db } from "@cohaise/server";
import { PUBLIC_LEAD_RATE_LIMIT } from "../config/app.js";
import { createLead } from "../services/leadService.js";
import { createRateLimiter } from "../utils/rateLimit.js";
/**
* Point d'entrée public du formulaire de contact de la vitrine.
*
* Route volontairement sans `requireAuth` : n'importe quel visiteur de
* cohaise.dev peut créer un prospect. Le honeypot et le rate-limit sont
* décrits dans `services/leadService.ts`.
*/
const leadBody = z.object({
firstName: z.string().trim().min(1).max(100),
lastName: z.string().trim().min(1).max(100),
email: z.string().trim().min(1).max(255),
organization: z.string().trim().min(1).max(255).nullish(),
phone: z.string().trim().max(50).nullish(),
message: z.string().trim().max(4000).nullish(),
// Honeypot : vide chez un humain, rempli par un robot.
website: z.string().max(255).nullish(),
});
// Une instance unique par processus : suffisant pour un CRM à un seul nœud.
const limiter = createRateLimiter(PUBLIC_LEAD_RATE_LIMIT);
export const registerLeadRoutes = (app: App, db: Db): void => {
app.post("/api/crm/leads", async (context) => {
const forwarded = context.req.header("x-forwarded-for");
const ip =
forwarded?.split(",")[0]?.trim() ??
context.req.header("x-real-ip") ??
"unknown";
if (!limiter.isAllowed(ip)) throw AppError.tooManyRequests();
const parsed = leadBody.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
const issue = parsed.error.issues[0];
throw AppError.badRequest(
issue
? `${issue.path.join(".") || "corps"} : ${issue.message}`
: "Corps invalide.",
);
}
const result = await createLead(db, parsed.data);
return context.json(result, 201);
});
};
-146
View File
@@ -1,146 +0,0 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import { AppError, type App, type Db } from "@cohaise/server";
/**
* Point d'entrée public du formulaire de contact de la vitrine.
*
* Route volontairement sans `requireAuth` : n'importe quel visiteur de
* cohaise.dev peut creer un prospect. Protection anti-abus a deux etages :
* - un honeypot (champ invisible que seuls les robots remplissent) ;
* - un rate-limit simple en memoire, par IP (Cloudflare reste la 1re ligne).
* Le lead est pose dans `contacts` avec `external_source = 'cohaise-web'`,
* non assigne, pour apparaitre dans la liste des prospects du CRM.
*/
const leadSchema = z.object({
firstName: z.string().trim().min(1).max(100),
lastName: z.string().trim().min(1).max(100),
email: z.string().trim().min(1).max(255),
organization: z.string().trim().min(1).max(255).nullish(),
phone: z.string().trim().max(50).nullish(),
message: z.string().trim().max(4000).nullish(),
// Honeypot : vide chez un humain, rempli par un robot.
website: z.string().max(255).nullish(),
});
const slugify = (value: string): string =>
value
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 255);
/** Un e-mail absent ne doit pas heurter l'index unique : NULL passe partout. */
const emailOrNull = (value: string): string | null => value.toLowerCase();
/** Retrouve l'entreprise par son nom, ou la cree (nom unique en base). */
const findOrCreateOrganization = async (db: Db, name: string): Promise<string> => {
const existing = await db.one<{ id: string }>(
"SELECT id FROM organizations WHERE name = ? AND deleted_at IS NULL",
[name],
);
if (existing) return existing.id;
const id = randomUUID();
try {
await db.exec("INSERT INTO organizations (id, name, slug) VALUES (?, ?, ?)", [
id,
name,
slugify(name),
]);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
// Course : une autre requete vient de creer le meme nom. On la rejoint.
const raced = await db.one<{ id: string }>(
"SELECT id FROM organizations WHERE name = ? AND deleted_at IS NULL",
[name],
);
if (raced) return raced.id;
}
throw error;
}
return id;
};
// Rate-limit en memoire : suffisant pour une instance CRM unique. Derriere
// nginx/Cloudflare, l'IP vient de x-forwarded-for.
const RATE_WINDOW_MS = 15 * 60 * 1000;
const RATE_MAX = 5;
const attempts = new Map<string, number[]>();
const isAllowed = (ip: string): boolean => {
const now = Date.now();
const recent = (attempts.get(ip) ?? []).filter((t) => now - t < RATE_WINDOW_MS);
if (recent.length >= RATE_MAX) {
attempts.set(ip, recent);
return false;
}
recent.push(now);
attempts.set(ip, recent);
return true;
};
export const registerLeadRoutes = (app: App, db: Db): void => {
app.post("/api/crm/leads", async (context) => {
const forwarded = context.req.header("x-forwarded-for");
const ip =
forwarded?.split(",")[0]?.trim() ?? context.req.header("x-real-ip") ?? "unknown";
if (!isAllowed(ip)) throw AppError.tooManyRequests();
const parsed = leadSchema.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
const issue = parsed.error.issues[0];
throw AppError.badRequest(
issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.",
);
}
const data = parsed.data;
// Honeypot rempli : robot. On feint la reussite pour ne pas se trahir.
if (data.website) {
return context.json({ ok: true, id: randomUUID() }, 201);
}
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,
emailOrNull(data.email),
data.phone ?? null,
null,
null,
"cohaise-web",
null,
data.message ?? null,
null,
null,
],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Cette adresse a deja ete enregistree.");
}
if ((error as { errno?: number }).errno === 1452) {
throw AppError.badRequest("L'entreprise referencee n'existe pas.");
}
throw error;
}
return context.json({ ok: true, id }, 201);
});
};
@@ -0,0 +1,110 @@
import { z } from "zod";
import {
AppError,
currentUser,
requireAuth,
type App,
type Db,
} from "@cohaise/server";
import { mountSession } from "../middleware/auth.js";
import {
createOrganization,
deleteOrganization,
getOrganization,
listOrganizations,
toPublicOrganization,
updateOrganization,
} from "../services/organizationService.js";
import { parsePagination } from "../utils/pagination.js";
import { invalidBody, uuidSchema } from "../utils/validation.js";
const writable = z.string().trim().min(1).max(255);
const optionalText = z.string().trim().max(255).nullish();
const optionalLong = z.string().trim().max(4000).nullish();
const createOrganizationBody = z.object({
name: writable,
website: optionalText,
industry: z.string().trim().max(100).nullish(),
phone: z.string().trim().max(50).nullish(),
email: z.string().trim().max(255).nullish(),
addressLine1: optionalText,
addressLine2: optionalText,
postalCode: z.string().trim().max(20).nullish(),
city: z.string().trim().max(100).nullish(),
countryId: z.coerce.number().int().positive().nullish(),
description: optionalLong,
});
const updateOrganizationBody = createOrganizationBody.partial();
export const registerOrganizationRoutes = (app: App, db: Db): void => {
mountSession(app, db, "/api/crm/organizations");
app.get("/api/crm/organizations", requireAuth, async (context) => {
const pagination = parsePagination(
context.req.query("page"),
context.req.query("limit"),
);
const { total, organizations } = await listOrganizations(
db,
context.req.query("q")?.trim() ?? "",
pagination,
);
return context.json({
total,
page: pagination.page,
limit: pagination.limit,
organizations: organizations.map(toPublicOrganization),
});
});
app.get("/api/crm/organizations/:id", requireAuth, async (context) => {
const id = context.req.param("id");
if (!id || !uuidSchema.safeParse(id).success) {
throw AppError.notFound("Entreprise introuvable.");
}
const organization = await getOrganization(db, id);
return context.json({ organization: toPublicOrganization(organization) });
});
app.post("/api/crm/organizations", requireAuth, async (context) => {
const user = currentUser(context);
const parsed = createOrganizationBody.safeParse(
await context.req.json().catch(() => null),
);
if (!parsed.success) throw invalidBody(parsed.error);
const organization = await createOrganization(db, user.id, parsed.data);
return context.json(
{ organization: toPublicOrganization(organization) },
201,
);
});
app.patch("/api/crm/organizations/:id", requireAuth, async (context) => {
const id = context.req.param("id");
if (!id || !uuidSchema.safeParse(id).success) {
throw AppError.notFound("Entreprise introuvable.");
}
const parsed = updateOrganizationBody.safeParse(
await context.req.json().catch(() => null),
);
if (!parsed.success) throw invalidBody(parsed.error);
const organization = await updateOrganization(db, id, parsed.data);
return context.json({ organization: toPublicOrganization(organization) });
});
app.delete("/api/crm/organizations/:id", requireAuth, async (context) => {
const id = context.req.param("id");
if (!id || !uuidSchema.safeParse(id).success) {
throw AppError.notFound("Entreprise introuvable.");
}
await deleteOrganization(db, id);
return context.json({ ok: true });
});
};
-277
View File
@@ -1,277 +0,0 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import {
AppError,
attachUser,
currentUser,
requireAuth,
type App,
type Db,
} from "@cohaise/server";
const uuid = z
.string()
.regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, "Identifiant invalide.");
const writable = z.string().trim().min(1).max(255);
const optionalText = z.string().trim().max(255).nullish();
const optionalLong = z.string().trim().max(4000).nullish();
const createOrganization = z.object({
name: writable,
website: optionalText,
industry: z.string().trim().max(100).nullish(),
phone: z.string().trim().max(50).nullish(),
email: z.string().trim().max(255).nullish(),
addressLine1: optionalText,
addressLine2: optionalText,
postalCode: z.string().trim().max(20).nullish(),
city: z.string().trim().max(100).nullish(),
countryId: z.coerce.number().int().positive().nullish(),
description: optionalLong,
});
const updateOrganization = createOrganization.partial();
interface OrganizationRow {
id: string;
name: string;
slug: string;
website: string | null;
industry: string | null;
phone: string | null;
email: string | null;
address_line1: string | null;
address_line2: string | null;
postal_code: string | null;
city: string | null;
country_id: number | null;
country_name: string | null;
country_code: string | null;
description: string | null;
owner_id: string | null;
owner_name: string | null;
created_at: string;
updated_at: string;
}
const SELECT_ORGANIZATION = `
SELECT o.id, o.name, o.slug, o.website, o.industry, o.phone, o.email,
o.address_line1, o.address_line2, o.postal_code, o.city, o.country_id,
c.name AS country_name, c.code AS country_code,
o.description, o.owner_id,
CONCAT(u.first_name, ' ', u.last_name) AS owner_name,
o.created_at, o.updated_at
FROM organizations o
LEFT JOIN countries c ON c.id = o.country_id
LEFT JOIN users u ON u.id = o.owner_id`;
const publicOrganization = (row: OrganizationRow) => ({
id: row.id,
name: row.name,
slug: row.slug,
website: row.website,
industry: row.industry,
phone: row.phone,
email: row.email,
address_line1: row.address_line1,
address_line2: row.address_line2,
postal_code: row.postal_code,
city: row.city,
country_id: row.country_id,
country_name: row.country_name,
country_code: row.country_code,
description: row.description,
owner_id: row.owner_id,
owner_name: row.owner_name,
created_at: row.created_at,
updated_at: row.updated_at,
});
/** Normalise un nom en slug lisible, sans accent ni punctuation. */
const slugify = (value: string): string =>
value
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 255);
export const registerOrganizationRoutes = (app: App, db: Db): void => {
app.use("/api/crm/organizations/*", attachUser(db));
app.use("/api/crm/organizations", attachUser(db));
app.get("/api/crm/organizations", requireAuth, async (context) => {
const search = context.req.query("q")?.trim() ?? "";
const page = Math.max(1, Number(context.req.query("page") ?? 1) || 1);
const limit = Math.min(100, Math.max(1, Number(context.req.query("limit") ?? 25) || 25));
const offset = (page - 1) * limit;
const where = search
? "WHERE o.deleted_at IS NULL AND (o.name LIKE ? OR o.city LIKE ? OR o.industry LIKE ?)"
: "WHERE o.deleted_at IS NULL";
const term = `%${search}%`;
const params = search ? [term, term, term] : [];
const [{ total }, rows] = await Promise.all([
db
.query<{ total: number }>(`SELECT COUNT(*) AS total FROM organizations o ${where}`, params)
.then((result) => ({ total: Number(result[0]?.total ?? 0) })),
db.query<OrganizationRow>(
`${SELECT_ORGANIZATION} ${where} ORDER BY o.name LIMIT ${limit} OFFSET ${offset}`,
params,
),
]);
return context.json({
total,
page,
limit,
organizations: rows.map(publicOrganization),
});
});
app.get("/api/crm/organizations/:id", requireAuth, async (context) => {
const id = context.req.param("id");
if (!uuid.safeParse(id).success) throw AppError.notFound("Entreprise introuvable.");
const row = await db.one<OrganizationRow>(
`${SELECT_ORGANIZATION} WHERE o.id = ? AND o.deleted_at IS NULL`,
[id],
);
if (!row) throw AppError.notFound("Entreprise introuvable.");
return context.json({ organization: publicOrganization(row) });
});
app.post(
"/api/crm/organizations",
requireAuth,
async (context) => {
const user = currentUser(context);
const parsed = createOrganization.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
const issue = parsed.error.issues[0];
throw AppError.badRequest(
issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.",
);
}
const data = parsed.data;
const id = randomUUID();
try {
await db.exec(
`INSERT INTO organizations
(id, name, slug, website, industry, phone, email, address_line1, address_line2,
postal_code, city, country_id, description, owner_id, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
id,
data.name,
slugify(data.name),
data.website ?? null,
data.industry ?? null,
data.phone ?? null,
data.email ?? null,
data.addressLine1 ?? null,
data.addressLine2 ?? null,
data.postalCode ?? null,
data.city ?? null,
data.countryId ?? null,
data.description ?? null,
user.id,
user.id,
],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Une entreprise porte deja ce nom.");
}
throw error;
}
const created = await db.required<OrganizationRow>(
`${SELECT_ORGANIZATION} WHERE o.id = ?`,
[id],
);
return context.json({ organization: publicOrganization(created) }, 201);
},
);
app.patch(
"/api/crm/organizations/:id",
requireAuth,
async (context) => {
const id = context.req.param("id");
if (!uuid.safeParse(id).success) throw AppError.notFound("Entreprise introuvable.");
const parsed = updateOrganization.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) throw AppError.badRequest("Corps invalide.");
const existing = await db.one<{ id: string }>(
"SELECT id FROM organizations WHERE id = ? AND deleted_at IS NULL",
[id],
);
if (!existing) throw AppError.notFound("Entreprise introuvable.");
const columns: Record<string, unknown> = {
website: parsed.data.website,
industry: parsed.data.industry,
phone: parsed.data.phone,
email: parsed.data.email,
address_line1: parsed.data.addressLine1,
address_line2: parsed.data.addressLine2,
postal_code: parsed.data.postalCode,
city: parsed.data.city,
country_id: parsed.data.countryId,
description: parsed.data.description,
};
if (parsed.data.name !== undefined) {
columns.name = parsed.data.name;
columns.slug = slugify(parsed.data.name);
}
const assignments = Object.keys(columns)
.filter((key) => columns[key] !== undefined)
.map((key) => `${key} = ?`);
if (assignments.length === 0) throw AppError.badRequest("Aucune modification fournie.");
const values = Object.keys(columns)
.filter((key) => columns[key] !== undefined)
.map((key) => columns[key]);
try {
await db.exec(
`UPDATE organizations SET ${assignments.join(", ")} WHERE id = ? AND deleted_at IS NULL`,
[...values, id],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Une entreprise porte deja ce nom.");
}
throw error;
}
const updated = await db.required<OrganizationRow>(
`${SELECT_ORGANIZATION} WHERE o.id = ?`,
[id],
);
return context.json({ organization: publicOrganization(updated) });
},
);
app.delete(
"/api/crm/organizations/:id",
requireAuth,
async (context) => {
const id = context.req.param("id");
if (!uuid.safeParse(id).success) throw AppError.notFound("Entreprise introuvable.");
const result = await db.exec(
"UPDATE organizations SET deleted_at = UTC_TIMESTAMP() WHERE id = ? AND deleted_at IS NULL",
[id],
);
if (result.affectedRows === 0) throw AppError.notFound("Entreprise introuvable.");
return context.json({ ok: true });
},
);
};
+124
View File
@@ -0,0 +1,124 @@
import {
AppError,
createSession,
hashPassword,
revokeSession,
sha256,
verifyPassword,
type Config,
type Db,
} from "@cohaise/server";
import type { AuthUser, UserRow } from "../models/types.js";
const SELECT_USER = `
SELECT u.id, u.email, u.password_hash, u.first_name, u.last_name,
u.is_active, u.must_change_password
FROM users u`;
/**
* Empreinte de repli, calculée pour n'importe quelle chaîne : une adresse
* inconnue doit prendre exactement le même temps qu'une adresse connue avec
* un mauvais mot de passe, sinon l'API devient un annuaire.
*/
const DUMMY_HASH_PROMISE = hashPassword("placeholder-for-anti-enumeration").catch(
() => null,
);
void DUMMY_HASH_PROMISE;
export const toPublicUser = (row: UserRow): AuthUser => ({
id: row.id,
email: row.email,
first_name: row.first_name,
last_name: row.last_name,
must_change_password: row.must_change_password === 1,
});
export interface LoginInput {
email: string;
password: string;
ipAddress: string | null;
userAgent: string | null;
}
export interface LoginResult {
user: AuthUser;
token: string;
expiresAt: Date;
}
export const login = async (
db: Db,
config: Config,
input: LoginInput,
): Promise<LoginResult> => {
const row = await db.one<UserRow>(
`${SELECT_USER} WHERE u.email = ? AND u.deleted_at IS NULL`,
[input.email],
);
const stored = row?.password_hash ?? (await DUMMY_HASH_PROMISE) ?? "";
const valid = stored ? await verifyPassword(input.password, stored) : false;
if (!row || !valid) throw AppError.unauthorized("Identifiants invalides.");
if (row.is_active !== 1) throw AppError.unauthorized("Compte desactive.");
const { token, expiresAt } = await createSession(
db,
row.id,
{ ipAddress: input.ipAddress, userAgent: input.userAgent },
config.SESSION_TTL_HOURS,
);
await db.exec("UPDATE users SET last_login_at = UTC_TIMESTAMP(3) WHERE id = ?", [
row.id,
]);
return { user: toPublicUser(row), token, expiresAt };
};
export const logout = async (db: Db, token: string | undefined): Promise<void> => {
if (token) await revokeSession(db, token);
};
export const getSessionUser = async (db: Db, userId: string): Promise<AuthUser> => {
const row = await db.one<UserRow>(
`${SELECT_USER} WHERE u.id = ? AND u.deleted_at IS NULL`,
[userId],
);
if (!row) throw AppError.unauthorized();
return toPublicUser(row);
};
export const changePassword = async (
db: Db,
userId: string,
token: string | undefined,
current: string,
next: string,
): Promise<void> => {
const row = await db.one<{ password_hash: string }>(
"SELECT password_hash FROM users WHERE id = ? AND deleted_at IS NULL",
[userId],
);
if (!row) throw AppError.unauthorized();
if (!(await verifyPassword(current, row.password_hash))) {
throw AppError.unauthorized("Mot de passe actuel incorrect.");
}
if (current === next) {
throw AppError.badRequest("Le nouveau mot de passe doit differer de l'actuel.");
}
const hash = await hashPassword(next);
// Pas de password_changed_at ici : cette colonne appartient au modèle du
// Cloud. Le CRM n'a pas de notion de confirmation d'identité à célébrer.
await db.exec(
"UPDATE users SET password_hash = ?, must_change_password = 0 WHERE id = ?",
[hash, userId],
);
// La session courante est conservée, toutes les autres sont révoquées.
await db.exec(
`UPDATE user_sessions
SET revoked_at = UTC_TIMESTAMP()
WHERE user_id = ? AND revoked_at IS NULL AND token_hash <> ?`,
[userId, sha256(token ?? "")],
);
};
+209
View File
@@ -0,0 +1,209 @@
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<ContactList> => {
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<ContactRow>(
`${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<ContactRow> => {
const row = await db.one<ContactRow>(
`${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<ContactRow> => {
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<ContactRow>(`${SELECT_CONTACT} WHERE ct.id = ?`, [id]);
};
export const updateContact = async (
db: Db,
id: string,
data: ContactUpdate,
): Promise<ContactRow> => {
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<ContactRow>(`${SELECT_CONTACT} WHERE ct.id = ?`, [id]);
};
export const deleteContact = async (db: Db, id: string): Promise<void> => {
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.");
};
@@ -0,0 +1,91 @@
import { AppError, type Db } from "@cohaise/server";
import type { CountryRow } from "../models/types.js";
import { isDuplicateEntry, isReferencedRow } from "../utils/dbErrors.js";
import { buildAssignments } from "../utils/sql.js";
const SELECT_COUNTRY = "SELECT id, code, name, phone_code FROM countries";
export interface CountryCreate {
code: string;
name: string;
phoneCode?: string | null | undefined;
}
export interface CountryUpdate {
code?: string | undefined;
name?: string | undefined;
phoneCode?: string | null | undefined;
}
export const toPublicCountry = (row: CountryRow) => ({
id: row.id,
code: row.code,
name: row.name,
phone_code: row.phone_code,
});
/** Référentiel : le tri est collationnel, donc sans accent ni casse douteuse. */
export const listCountries = async (db: Db, search: string): Promise<CountryRow[]> => {
const term = search.trim();
const where = term ? "WHERE name LIKE ? OR code = ?" : "";
const params = term ? [`%${term}%`, term.toUpperCase()] : [];
return db.query<CountryRow>(`${SELECT_COUNTRY} ${where} ORDER BY name`, params);
};
export const createCountry = async (
db: Db,
data: CountryCreate,
): Promise<CountryRow> => {
try {
await db.exec("INSERT INTO countries (code, name, phone_code) VALUES (?, ?, ?)", [
data.code,
data.name,
data.phoneCode ?? null,
]);
} catch (error) {
if (isDuplicateEntry(error)) throw AppError.conflict("Ce pays existe deja.");
throw error;
}
return db.required<CountryRow>(`${SELECT_COUNTRY} WHERE code = ?`, [data.code]);
};
export const updateCountry = async (
db: Db,
id: number,
data: CountryUpdate,
): Promise<CountryRow> => {
const assignments = buildAssignments({
code: data.code,
name: data.name,
phone_code: data.phoneCode,
});
if (!assignments) throw AppError.badRequest("Aucune modification fournie.");
try {
const result = await db.exec(
`UPDATE countries SET ${assignments.clause} WHERE id = ?`,
[...assignments.values, id],
);
if (result.affectedRows === 0) throw AppError.notFound("Pays introuvable.");
} catch (error) {
if (isDuplicateEntry(error)) {
throw AppError.conflict("Ce code de pays existe deja.");
}
throw error;
}
return db.required<CountryRow>(`${SELECT_COUNTRY} WHERE id = ?`, [id]);
};
export const deleteCountry = async (db: Db, id: number): Promise<void> => {
try {
const result = await db.exec("DELETE FROM countries WHERE id = ?", [id]);
if (result.affectedRows === 0) throw AppError.notFound("Pays introuvable.");
} catch (error) {
if (isReferencedRow(error)) {
throw AppError.conflict("Des entreprises ou contacts referencent ce pays.");
}
throw error;
}
};
+65
View File
@@ -0,0 +1,65 @@
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<LeadResult> => {
// 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 };
};
@@ -0,0 +1,220 @@
import { randomUUID } from "node:crypto";
import { AppError, type Db } from "@cohaise/server";
import type { OrganizationRow } from "../models/types.js";
import { isDuplicateEntry } from "../utils/dbErrors.js";
import { slugify } from "../utils/normalize.js";
import { buildAssignments } from "../utils/sql.js";
import type { Pagination } from "../utils/pagination.js";
const SELECT_ORGANIZATION = `
SELECT o.id, o.name, o.slug, o.website, o.industry, o.phone, o.email,
o.address_line1, o.address_line2, o.postal_code, o.city, o.country_id,
c.name AS country_name, c.code AS country_code,
o.description, o.owner_id,
CONCAT(u.first_name, ' ', u.last_name) AS owner_name,
o.created_at, o.updated_at
FROM organizations o
LEFT JOIN countries c ON c.id = o.country_id
LEFT JOIN users u ON u.id = o.owner_id`;
export interface OrganizationCreate {
name: string;
website?: string | null | undefined;
industry?: string | null | undefined;
phone?: string | null | undefined;
email?: string | null | undefined;
addressLine1?: string | null | undefined;
addressLine2?: string | null | undefined;
postalCode?: string | null | undefined;
city?: string | null | undefined;
countryId?: number | null | undefined;
description?: string | null | undefined;
}
export type OrganizationUpdate = {
[Key in keyof OrganizationCreate]?: OrganizationCreate[Key] | undefined;
};
export interface OrganizationList {
total: number;
organizations: OrganizationRow[];
}
export const toPublicOrganization = (row: OrganizationRow) => ({
id: row.id,
name: row.name,
slug: row.slug,
website: row.website,
industry: row.industry,
phone: row.phone,
email: row.email,
address_line1: row.address_line1,
address_line2: row.address_line2,
postal_code: row.postal_code,
city: row.city,
country_id: row.country_id,
country_name: row.country_name,
country_code: row.country_code,
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 listOrganizations = async (
db: Db,
search: string,
pagination: Pagination,
): Promise<OrganizationList> => {
const where = search
? "WHERE o.deleted_at IS NULL AND (o.name LIKE ? OR o.city LIKE ? OR o.industry LIKE ?)"
: "WHERE o.deleted_at IS NULL";
const term = `%${search}%`;
const params = search ? [term, term, term] : [];
const [counted, rows] = await Promise.all([
db.query<{ total: number }>(
`SELECT COUNT(*) AS total FROM organizations o ${where}`,
params,
),
db.query<OrganizationRow>(
`${SELECT_ORGANIZATION} ${where} ORDER BY o.name LIMIT ${pagination.limit} OFFSET ${pagination.offset}`,
params,
),
]);
return { total: Number(counted[0]?.total ?? 0), organizations: rows };
};
export const getOrganization = async (db: Db, id: string): Promise<OrganizationRow> => {
const row = await db.one<OrganizationRow>(
`${SELECT_ORGANIZATION} WHERE o.id = ? AND o.deleted_at IS NULL`,
[id],
);
if (!row) throw AppError.notFound("Entreprise introuvable.");
return row;
};
export const createOrganization = async (
db: Db,
ownerId: string,
data: OrganizationCreate,
): Promise<OrganizationRow> => {
const id = randomUUID();
try {
await db.exec(
`INSERT INTO organizations
(id, name, slug, website, industry, phone, email, address_line1, address_line2,
postal_code, city, country_id, description, owner_id, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
id,
data.name,
slugify(data.name),
data.website ?? null,
data.industry ?? null,
data.phone ?? null,
data.email ?? null,
data.addressLine1 ?? null,
data.addressLine2 ?? null,
data.postalCode ?? null,
data.city ?? null,
data.countryId ?? null,
data.description ?? null,
ownerId,
ownerId,
],
);
} catch (error) {
if (isDuplicateEntry(error)) {
throw AppError.conflict("Une entreprise porte deja ce nom.");
}
throw error;
}
return db.required<OrganizationRow>(`${SELECT_ORGANIZATION} WHERE o.id = ?`, [id]);
};
export const updateOrganization = async (
db: Db,
id: string,
data: OrganizationUpdate,
): Promise<OrganizationRow> => {
const existing = await db.one<{ id: string }>(
"SELECT id FROM organizations WHERE id = ? AND deleted_at IS NULL",
[id],
);
if (!existing) throw AppError.notFound("Entreprise introuvable.");
const assignments = buildAssignments({
website: data.website,
industry: data.industry,
phone: data.phone,
email: data.email,
address_line1: data.addressLine1,
address_line2: data.addressLine2,
postal_code: data.postalCode,
city: data.city,
country_id: data.countryId,
description: data.description,
...(data.name === undefined
? {}
: { name: data.name, slug: slugify(data.name) }),
});
if (!assignments) throw AppError.badRequest("Aucune modification fournie.");
try {
await db.exec(
`UPDATE organizations SET ${assignments.clause} WHERE id = ? AND deleted_at IS NULL`,
[...assignments.values, id],
);
} catch (error) {
if (isDuplicateEntry(error)) {
throw AppError.conflict("Une entreprise porte deja ce nom.");
}
throw error;
}
return db.required<OrganizationRow>(`${SELECT_ORGANIZATION} WHERE o.id = ?`, [id]);
};
export const deleteOrganization = async (db: Db, id: string): Promise<void> => {
const result = await db.exec(
"UPDATE organizations SET deleted_at = UTC_TIMESTAMP() WHERE id = ? AND deleted_at IS NULL",
[id],
);
if (result.affectedRows === 0) throw AppError.notFound("Entreprise introuvable.");
};
/** Retrouve l'entreprise par son nom, ou la crée (nom unique en base). */
export const findOrCreateOrganization = async (
db: Db,
name: string,
): Promise<string> => {
const existing = await db.one<{ id: string }>(
"SELECT id FROM organizations WHERE name = ? AND deleted_at IS NULL",
[name],
);
if (existing) return existing.id;
const id = randomUUID();
try {
await db.exec("INSERT INTO organizations (id, name, slug) VALUES (?, ?, ?)", [
id,
name,
slugify(name),
]);
} catch (error) {
if (isDuplicateEntry(error)) {
// Course : une autre requête vient de créer le même nom. On la rejoint.
const raced = await db.one<{ id: string }>(
"SELECT id FROM organizations WHERE name = ? AND deleted_at IS NULL",
[name],
);
if (raced) return raced.id;
}
throw error;
}
return id;
};
+15
View File
@@ -0,0 +1,15 @@
/** Erreurs de contrainte MariaDB, reconnues par leur code numérique. */
const errnoOf = (error: unknown): number | undefined =>
typeof error === "object" && error !== null && "errno" in error
? ((error as { errno?: number }).errno ?? undefined)
: undefined;
/** 1062 : violation d'index unique. */
export const isDuplicateEntry = (error: unknown): boolean => errnoOf(error) === 1062;
/** 1452 : la ligne référencée par une clé étrangère n'existe pas. */
export const isForeignKeyViolation = (error: unknown): boolean => errnoOf(error) === 1452;
/** 1451 : la ligne est encore référencée, suppression impossible. */
export const isReferencedRow = (error: unknown): boolean => errnoOf(error) === 1451;
+15
View File
@@ -0,0 +1,15 @@
/** Normalisations de texte partagées par les services. */
/** Slug lisible : sans accent, sans ponctuation, séparé par des tirets. */
export const slugify = (value: string): string =>
value
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 255);
/** Un e-mail absent ne doit pas heurter l'index unique : NULL passe partout. */
export const normalizeEmail = (value: string | null | undefined): string | null =>
value ? value.toLowerCase() : null;
+22
View File
@@ -0,0 +1,22 @@
import { DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE } from "../config/app.js";
export interface Pagination {
page: number;
limit: number;
offset: number;
}
const positiveInt = (raw: string | undefined, fallback: number): number => {
const value = Number(raw ?? fallback);
return Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallback;
};
/** Lit `page`/`limit` depuis la query string et borne les valeurs. */
export const parsePagination = (
pageRaw: string | undefined,
limitRaw: string | undefined,
): Pagination => {
const page = Math.max(1, positiveInt(pageRaw, 1));
const limit = Math.min(MAX_PAGE_SIZE, Math.max(1, positiveInt(limitRaw, DEFAULT_PAGE_SIZE)));
return { page, limit, offset: (page - 1) * limit };
};
+33
View File
@@ -0,0 +1,33 @@
export interface RateLimitOptions {
/** Fenêtre glissante, en millisecondes. */
windowMs: number;
/** Nombre d'essais autorisés dans la fenêtre. */
max: number;
}
export interface RateLimiter {
/** Enregistre une tentative et indique si elle est autorisée. */
isAllowed: (key: string) => boolean;
}
/**
* Rate-limit en mémoire, suffisant pour une instance CRM unique. Derrière
* nginx/Cloudflare, la clé vient de l'IP transmise par `x-forwarded-for`.
*/
export const createRateLimiter = ({ windowMs, max }: RateLimitOptions): RateLimiter => {
const attempts = new Map<string, number[]>();
return {
isAllowed: (key) => {
const now = Date.now();
const recent = (attempts.get(key) ?? []).filter((time) => now - time < windowMs);
if (recent.length >= max) {
attempts.set(key, recent);
return false;
}
recent.push(now);
attempts.set(key, recent);
return true;
},
};
};
+22
View File
@@ -0,0 +1,22 @@
/** Construction des `UPDATE` partiels, sans jamais concaténer de valeurs. */
export interface Assignments {
clause: string;
values: unknown[];
}
/**
* Transforme `{ city: "Lyon", phone: undefined }` en `city = ?`.
* `null` reste une valeur explicite : elle efface la colonne.
* Retourne `null` quand aucune colonne n'est fournie.
*/
export const buildAssignments = (
columns: Record<string, unknown>,
): Assignments | null => {
const keys = Object.keys(columns).filter((key) => columns[key] !== undefined);
if (keys.length === 0) return null;
return {
clause: keys.map((key) => `${key} = ?`).join(", "),
values: keys.map((key) => columns[key]),
};
};
+20
View File
@@ -0,0 +1,20 @@
import { z } from "zod";
import { AppError } from "@cohaise/server";
/** Identifiant UUID v4 tel que stocké par les tables du CRM. */
export const uuidSchema = z
.string()
.regex(
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
"Identifiant invalide.",
);
/** Erreur 400 homogène pour un corps JSON invalide. */
export const invalidBody = (error: z.ZodError): AppError => {
const issue = error.issues[0];
return AppError.badRequest(
issue
? `${issue.path.join(".") || "corps"} : ${issue.message}`
: "Corps invalide.",
);
};