feat: init repo
deploy / deploy (push) Canceled after 0s

This commit is contained in:
2026-11-10 19:56:03 +01:00
commit 858d862fed
166 changed files with 13336 additions and 0 deletions
+174
View File
@@ -0,0 +1,174 @@
# CRM — modèle de données
Entreprises, prospects, référentiel des pays. Le runtime **existe** : API Hono
dans `src/`, 18 routes sous `/api/crm`, front React séparé. Le détail des
endpoints, du déploiement et de la sécurité est dans
[`../../docs/api.md`](../../docs/api.md),
[`../../docs/deployment.md`](../../docs/deployment.md) et
[`../../docs/security.md`](../../docs/security.md).
## Modèle de données
```mermaid
erDiagram
users ||--o{ password_reset_tokens : "possede"
users ||--o{ organizations : "pilote"
users ||--o{ contacts : "pilote"
users ||--o{ deals : "pilote"
users ||--o{ tasks : "assignee"
users ||--o{ audit_logs : "trace"
countries ||--o{ organizations : "situee"
countries ||--o{ contacts : "situe"
organizations ||--o{ contacts : "emploie"
organizations ||--o{ deals : "concerne"
contacts ||--o{ deals : "interlocuteur"
pipeline_stages ||--o{ deals : "etape"
pipeline_stages ||--o{ deal_stage_history : "transitions"
deals ||--o{ deal_stage_history : "parcourt"
deals ||--o{ activities : "genere"
deals ||--o{ tasks : "genere"
contacts ||--o{ activities : "genere"
contacts ||--o{ tasks : "genere"
contacts ||--o{ contact_tags : "etiquette"
tags ||--o{ contact_tags : "attribue"
```
La table `roles` n'apparaît plus : supprimée par `007_no_roles.sql`.
## Tables
| Table | Rôle | Exposée par l'API |
|---|---|---|
| `users` | Comptes utilisateurs (plus de `role_id`) | `/auth/*` |
| `user_sessions` | Sessions persistées (`005`) | interne |
| `password_reset_tokens` | Jetons de réinitialisation hachés | non (aucune route) |
| `countries` | Référentiel ISO 3166 | `/countries` |
| `organizations` | Entreprises | `/organizations` |
| `contacts` | Interlocuteurs | `/contacts` |
| `tags` / `contact_tags` | Étiquetage | non |
| `pipeline_stages` | Étapes du pipeline | non |
| `deals` | Affaires | non |
| `deal_stage_history` | Historique des transitions | non |
| `activities` | Appels, e-mails, réunions, notes | non |
| `tasks` | Actions à mener | non |
| `settings` | Configuration clé-valeur | non |
| `audit_logs` | Piste d'audit | non |
| `schema_migrations` | Versions appliquées | non |
16 tables après `007` (17 avant : la table `roles` ayant disparu). Seules celles
marquées « `/…` » sont atteignables depuis le front.
## Conventions
| Sujet | Choix | Raison |
|---|---|---|
| Noms de tables | pluriel `snake_case`, sans préfixe | les tables vivent dans une base dédiée, le préfixe serait redondant |
| Noms de colonnes | `snake_case` | cohérent du DDL jusqu'au JSON |
| Types d'horodatage | `DATETIME`, `DATETIME(3)` pour l'audit | évite la conversion de fuseau de `TIMESTAMP` et la limite de 2038 |
| Durées de vie | `created_at`, `updated_at` sur toute table mutable | `ON UPDATE CURRENT_TIMESTAMP` garantit la fraîcheur sans code applicatif |
| Suppression | `deleted_at`, jamais de `DELETE` métier | conserver l'historique et éviter les suppressions en cascade destructrices |
| Identifiants | `CHAR(36)` pour les entités, `INT UNSIGNED` pour les référentiels | UUID stables hors base, entiers compacts pour les tables de référence |
| Encodage | `utf8mb4` / `utf8mb4_unicode_ci` | accents et emoji, collation correcte |
| Listes fermées | `CHECK` plutôt que table, sauf le pipeline | le jeu de valeurs est stable et court ; `pipeline_stages` reste une table car le nombre d'étapes varie selon les usages |
Trois tables ne portent volontairement pas `updated_at` : `audit_logs`,
`deal_stage_history` et `password_reset_tokens`. Elles sont en ajout seul. Une
piste d'audit modifiable n'est plus une piste d'audit.
Exception à la règle « jamais de `DELETE` » : **`countries` est supprimée en dur**.
Référentiel fini, aucune entreprise ne peut pointer dessus (FK `SET NULL`), et
un pays de trop poserait plus de problèmes qu'il n'en résout.
## Ce qui a été repris du CRM de référence
| Décision | Origine |
|---|---|
| Le pipeline en table, pas en `ENUM` | la référence compte plus de vingt étapes réelles ; un `ENUM` aurait été ingérable |
| Clé externe `UNIQUE` pour les imports | évite les doublons à l'ingestion et permet un `upsert` au `COALESCE` qui n'écrase jamais une saisie humaine |
| `settings` en clé naturelle, sans surrogate | la clé est la donnée |
| `snake_case` homogène DDL, TypeScript, JSON | seule chose réellement bien tenue de la référence |
| Organisation en référentiel plutôt qu'en valeur figée | un rôle unique dans une colonne texte avait produit trois vocabulaires contradictoires |
## Ce qui a été corrigé
| Défaut de la référence | Correction ici |
|---|---|
| Aucun `updated_at` | ajouté partout, maintenu par la base |
| Suppressions dures, `ON DELETE CASCADE` sur l'audit | soft delete, et l'audit survit à la suppression d'un utilisateur (`ON DELETE SET NULL` + instantané `user_email`) |
| `users.role` en texte libre | table `roles` + FK `RESTRICT` (`003`), **puis suppression totale des rôles par `007`** — choix assumé, voir ci-dessous |
| Historique de statut limité à un niveau | `deal_stage_history` conserve toutes les transitions avec auteur et horodatage |
| Aucun index de performance, filtrage et tri faits dans le navigateur | index composites `(deleted_at, …)` dimensionnés pour la pagination serveur |
| `tokens.token` ni indexé ni haché | `token_hash CHAR(64)` indexé, le jeton en clair n'est jamais stocké |
| Clé de déduplication d'envoi sans contrainte en base | contrainte composite en base plutôt qu'en application |
| Aucune société, affaire, activité ni tâche | le modèle en tient compte dès le départ |
| `int(11)` | `INT` ou `INT UNSIGNED` selon le cas |
## Migrations
Les fichiers sont numérotés et appliqués dans l'ordre. Une migration déjà
appliquée ne se modifie jamais : une correction passe par un nouveau fichier.
| Fichier | Contenu |
|---|---|
| `000_schema_migrations.sql` | table de suivi des versions |
| `001_initial_schema.sql` | 15 tables, 30 clés étrangères, 7 `CHECK` |
| `002_reference_data.sql` | rôles, étapes, pays, réglages, étiquettes |
| `003_integrity_backstop.sql` | clé étrangère `users.role_id` manquante, `CHECK` sur les champs obligatoires |
| `004_audit_precision.sql` | millisecondes sur les colonnes d'audit |
| `005_user_sessions.sql` | table `user_sessions` : sans elle, aucune session n'est possible |
| `006_active_identity.sql` | colonnes générées `active_email` / `active_name` |
| `007_no_roles.sql` | **suppression des rôles** : `DROP FOREIGN KEY fk_users_role`, `DROP COLUMN role_id`, `DROP TABLE roles` |
Notes :
- `003` existe parce que `001` avait été livrée avec la clé étrangère
`users.role_id` absente alors que l'index était présent. Le cas a été trouvé en
interrogeant la base, pas en relisant le SQL : c'est pourquoi chaque migration
est validée par des inserts qui doivent échouer, pas seulement par une
exécution sans erreur.
- `005` a été nécessaire pour réutiliser `@cohaise/server` tel quel : le code
partagé attend `user_sessions`, absente du modèle initial.
- `006` corrige un oubli — `uq_contacts_email` et `uq_organizations_name`
portaient sur la colonne brute, ce qui interdisait de réutiliser une adresse
ou un nom après une suppression logique. Corrections en colonnes générées, à
l'image du Cloud ; `001` n'a pas été retouché.
- `007` annule `003` et vide `002` de son sens, sans les réécrire : c'est le
principe même du fichier scellé. Le code, lui, a été vidé de `requireRole` et
de `role_slug` en même temps. **Tout compte authentifié a tous les droits.**
## Sécurité (couche modèle)
- Suppression d'un pays, d'un tag, d'une société référencée : `ON DELETE SET
NULL` ou `RESTRICT`, la donnée métier survit.
- Les identifiants d'organisation et de contact sont des UUID, non devinables
dans les URL.
- `audit_logs` est en ajout seul par convention applicative ; les colonnes
portent la contrainte `JSON_VALID`.
- Sessions : `user_sessions.token_hash` indexé, le jeton en clair n'est jamais
stocké.
Sessions, mots de passe, en-têtes et **absence de cloisonnement** :
[`../../docs/security.md`](../../docs/security.md).
## Limites actuelles
Seules les entités demandées sont exposées : `/auth/{login,logout,me,change-password}`,
`/countries`, `/organizations`, `/contacts`. **Aucune route n'est protégée par un
rôle** — le middleware `requireRole` n'existe plus dans le code.
- **`owner_id` ne cloisonne rien** : la colonne est écrite et retournée dans les
réponses, mais jamais filtrée. Toute ligne est visible et modifiable par tout
compte authentifié.
- Le premier compte se crée par `cohaise-crm-admin`
(`make admin ARGS="--email … --first … --last …"`), jamais par une route
publique. **Il n'existe pas d'option `--role`** : un compte créé a tous les
droits.
- `countries` ne compte que 19 entrées sur les ~250 de la norme ISO ; à
compléter si l'usage le justifie.
- Le pipeline (`deals`, `activities`, `tasks`, `tags`, `pipeline_stages`) existe
en base mais **n'a ni route ni interface**.
- Pas de journalisation des transitions en base : l'écriture dans
`deal_stage_history` relève de l'application, à faire dans la même transaction
que le changement d'étape.
- `password_reset_tokens` est créée mais aucune route ne l'utilise.
- Pas de rate limiting sur la connexion.
@@ -0,0 +1,5 @@
CREATE TABLE IF NOT EXISTS schema_migrations (
version VARCHAR(64) NOT NULL,
applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (version)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
@@ -0,0 +1,295 @@
CREATE TABLE roles (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
slug VARCHAR(50) NOT NULL,
name VARCHAR(100) NOT NULL,
description VARCHAR(255) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_roles_slug (slug)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE users (
id CHAR(36) NOT NULL,
email VARCHAR(255) NOT NULL,
password_hash VARCHAR(255) NOT NULL,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL,
role_id INT UNSIGNED NOT NULL,
is_active TINYINT(1) NOT NULL DEFAULT 1,
must_change_password TINYINT(1) NOT NULL DEFAULT 0,
last_login_at DATETIME NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_users_email (email),
KEY idx_users_role (role_id),
KEY idx_users_deleted (deleted_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE password_reset_tokens (
id CHAR(36) NOT NULL,
user_id CHAR(36) NOT NULL,
token_hash CHAR(64) NOT NULL,
expires_at DATETIME NOT NULL,
used_at DATETIME NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_prt_hash (token_hash),
KEY idx_prt_user (user_id),
KEY idx_prt_expiry (expires_at),
CONSTRAINT fk_prt_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE countries (
id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
code CHAR(2) NOT NULL,
name VARCHAR(100) NOT NULL,
phone_code VARCHAR(8) NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_countries_code (code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE tags (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(60) NOT NULL,
slug VARCHAR(60) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_tags_name (name),
UNIQUE KEY uq_tags_slug (slug)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE organizations (
id CHAR(36) NOT NULL,
name VARCHAR(255) NOT NULL,
slug VARCHAR(255) NOT NULL,
website VARCHAR(255) NULL,
industry VARCHAR(100) NULL,
phone VARCHAR(50) NULL,
email VARCHAR(255) NULL,
address_line1 VARCHAR(255) NULL,
address_line2 VARCHAR(255) NULL,
postal_code VARCHAR(20) NULL,
city VARCHAR(100) NULL,
country_id SMALLINT UNSIGNED NULL,
description TEXT NULL,
owner_id CHAR(36) NULL,
created_by CHAR(36) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_organizations_name (name),
KEY idx_organizations_slug (slug),
KEY idx_organizations_owner (owner_id),
KEY idx_organizations_country (country_id),
KEY idx_organizations_deleted (deleted_at),
KEY idx_organizations_list (deleted_at, created_at, id),
CONSTRAINT fk_organizations_country FOREIGN KEY (country_id) REFERENCES countries (id) ON DELETE SET NULL,
CONSTRAINT fk_organizations_owner FOREIGN KEY (owner_id) REFERENCES users (id) ON DELETE SET NULL,
CONSTRAINT fk_organizations_creator FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE contacts (
id CHAR(36) NOT NULL,
organization_id CHAR(36) NULL,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL,
email VARCHAR(255) NULL,
phone VARCHAR(50) NULL,
mobile VARCHAR(50) NULL,
job_title VARCHAR(150) NULL,
country_id SMALLINT UNSIGNED NULL,
external_source VARCHAR(50) NULL,
external_id VARCHAR(100) NULL,
description TEXT NULL,
owner_id CHAR(36) NULL,
created_by CHAR(36) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_contacts_email (email),
UNIQUE KEY uq_contacts_external (external_source, external_id),
KEY idx_contacts_organization (organization_id),
KEY idx_contacts_owner (owner_id),
KEY idx_contacts_country (country_id),
KEY idx_contacts_deleted (deleted_at),
KEY idx_contacts_list (deleted_at, created_at, id),
KEY idx_contacts_name (last_name, first_name),
CONSTRAINT fk_contacts_organization FOREIGN KEY (organization_id) REFERENCES organizations (id) ON DELETE SET NULL,
CONSTRAINT fk_contacts_country FOREIGN KEY (country_id) REFERENCES countries (id) ON DELETE SET NULL,
CONSTRAINT fk_contacts_owner FOREIGN KEY (owner_id) REFERENCES users (id) ON DELETE SET NULL,
CONSTRAINT fk_contacts_creator FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE contact_tags (
contact_id CHAR(36) NOT NULL,
tag_id INT UNSIGNED NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (contact_id, tag_id),
KEY idx_contact_tags_tag (tag_id),
CONSTRAINT fk_contact_tags_contact FOREIGN KEY (contact_id) REFERENCES contacts (id) ON DELETE CASCADE,
CONSTRAINT fk_contact_tags_tag FOREIGN KEY (tag_id) REFERENCES tags (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE pipeline_stages (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
slug VARCHAR(100) NOT NULL,
position INT UNSIGNED NOT NULL,
probability TINYINT UNSIGNED NOT NULL DEFAULT 0,
is_system TINYINT(1) NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_stages_slug (slug),
KEY idx_stages_position (position),
CONSTRAINT chk_stages_probability CHECK (probability <= 100)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE deals (
id CHAR(36) NOT NULL,
title VARCHAR(255) NOT NULL,
organization_id CHAR(36) NULL,
primary_contact_id CHAR(36) NULL,
stage_id INT UNSIGNED NOT NULL,
value_amount DECIMAL(15,2) NULL,
currency CHAR(3) NOT NULL DEFAULT 'EUR',
probability TINYINT UNSIGNED NOT NULL DEFAULT 0,
expected_close_date DATE NULL,
description TEXT NULL,
lost_reason VARCHAR(255) NULL,
owner_id CHAR(36) NULL,
created_by CHAR(36) NULL,
stage_changed_at DATETIME NULL,
won_at DATETIME NULL,
lost_at DATETIME NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
PRIMARY KEY (id),
KEY idx_deals_stage (stage_id),
KEY idx_deals_organization (organization_id),
KEY idx_deals_contact (primary_contact_id),
KEY idx_deals_owner (owner_id),
KEY idx_deals_deleted (deleted_at),
KEY idx_deals_pipeline (deleted_at, stage_id, updated_at),
KEY idx_deals_close_date (expected_close_date),
KEY idx_deals_list (deleted_at, created_at, id),
CONSTRAINT chk_deals_probability CHECK (probability <= 100),
CONSTRAINT chk_deals_amount CHECK (value_amount IS NULL OR value_amount >= 0),
CONSTRAINT fk_deals_stage FOREIGN KEY (stage_id) REFERENCES pipeline_stages (id) ON DELETE RESTRICT,
CONSTRAINT fk_deals_organization FOREIGN KEY (organization_id) REFERENCES organizations (id) ON DELETE SET NULL,
CONSTRAINT fk_deals_contact FOREIGN KEY (primary_contact_id) REFERENCES contacts (id) ON DELETE SET NULL,
CONSTRAINT fk_deals_owner FOREIGN KEY (owner_id) REFERENCES users (id) ON DELETE SET NULL,
CONSTRAINT fk_deals_creator FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE deal_stage_history (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
deal_id CHAR(36) NOT NULL,
from_stage_id INT UNSIGNED NULL,
to_stage_id INT UNSIGNED NOT NULL,
changed_by CHAR(36) NULL,
changed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY idx_dsh_deal (deal_id, changed_at),
KEY idx_dsh_to (to_stage_id),
CONSTRAINT fk_dsh_deal FOREIGN KEY (deal_id) REFERENCES deals (id) ON DELETE CASCADE,
CONSTRAINT fk_dsh_from FOREIGN KEY (from_stage_id) REFERENCES pipeline_stages (id) ON DELETE SET NULL,
CONSTRAINT fk_dsh_to FOREIGN KEY (to_stage_id) REFERENCES pipeline_stages (id) ON DELETE RESTRICT,
CONSTRAINT fk_dsh_user FOREIGN KEY (changed_by) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE activities (
id CHAR(36) NOT NULL,
type VARCHAR(20) NOT NULL,
subject VARCHAR(255) NOT NULL,
body TEXT NULL,
occurred_at DATETIME NOT NULL,
organization_id CHAR(36) NULL,
contact_id CHAR(36) NULL,
deal_id CHAR(36) NULL,
owner_id CHAR(36) NULL,
created_by CHAR(36) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
PRIMARY KEY (id),
KEY idx_activities_contact (contact_id, occurred_at),
KEY idx_activities_deal (deal_id, occurred_at),
KEY idx_activities_org (organization_id, occurred_at),
KEY idx_activities_owner (owner_id, occurred_at),
KEY idx_activities_deleted (deleted_at),
KEY idx_activities_list (deleted_at, created_at, id),
CONSTRAINT chk_activities_type CHECK (type IN ('call', 'email', 'meeting', 'note', 'demo', 'other')),
CONSTRAINT fk_activities_org FOREIGN KEY (organization_id) REFERENCES organizations (id) ON DELETE CASCADE,
CONSTRAINT fk_activities_contact FOREIGN KEY (contact_id) REFERENCES contacts (id) ON DELETE CASCADE,
CONSTRAINT fk_activities_deal FOREIGN KEY (deal_id) REFERENCES deals (id) ON DELETE CASCADE,
CONSTRAINT fk_activities_owner FOREIGN KEY (owner_id) REFERENCES users (id) ON DELETE SET NULL,
CONSTRAINT fk_activities_creator FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE tasks (
id CHAR(36) NOT NULL,
title VARCHAR(255) NOT NULL,
description TEXT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'open',
priority VARCHAR(20) NOT NULL DEFAULT 'normal',
due_at DATETIME NULL,
completed_at DATETIME NULL,
assigned_to CHAR(36) NULL,
organization_id CHAR(36) NULL,
contact_id CHAR(36) NULL,
deal_id CHAR(36) NULL,
created_by CHAR(36) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
PRIMARY KEY (id),
KEY idx_tasks_assignee (assigned_to, status, due_at),
KEY idx_tasks_deal (deal_id),
KEY idx_tasks_contact (contact_id),
KEY idx_tasks_org (organization_id),
KEY idx_tasks_deleted (deleted_at),
KEY idx_tasks_due (deleted_at, due_at),
CONSTRAINT chk_tasks_status CHECK (status IN ('open', 'in_progress', 'done', 'cancelled')),
CONSTRAINT chk_tasks_priority CHECK (priority IN ('low', 'normal', 'high', 'urgent')),
CONSTRAINT fk_tasks_assignee FOREIGN KEY (assigned_to) REFERENCES users (id) ON DELETE SET NULL,
CONSTRAINT fk_tasks_org FOREIGN KEY (organization_id) REFERENCES organizations (id) ON DELETE CASCADE,
CONSTRAINT fk_tasks_contact FOREIGN KEY (contact_id) REFERENCES contacts (id) ON DELETE CASCADE,
CONSTRAINT fk_tasks_deal FOREIGN KEY (deal_id) REFERENCES deals (id) ON DELETE CASCADE,
CONSTRAINT fk_tasks_creator FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE settings (
setting_key VARCHAR(64) NOT NULL,
setting_value VARCHAR(255) NOT NULL,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (setting_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE audit_logs (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id CHAR(36) NULL,
user_email VARCHAR(255) NULL,
action VARCHAR(50) NOT NULL,
resource VARCHAR(50) NOT NULL,
resource_id VARCHAR(64) NULL,
details LONGTEXT NULL,
ip_address VARCHAR(45) NULL,
user_agent VARCHAR(255) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY idx_audit_created (created_at),
KEY idx_audit_user (user_id),
KEY idx_audit_resource (resource, resource_id),
CONSTRAINT chk_audit_details CHECK (details IS NULL OR JSON_VALID(details)),
CONSTRAINT fk_audit_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
@@ -0,0 +1,47 @@
INSERT INTO roles (id, slug, name, description) VALUES
(1, 'admin', 'Administrateur', 'Accès complet, y compris la gestion des utilisateurs et des parametres.'),
(2, 'manager', 'Responsable', 'Acces a toutes les donnees commerciales et a leur modification.'),
(3, 'agent', 'Commercial', 'Acces limite aux donnees qui lui sont attribuees.');
INSERT INTO pipeline_stages (id, name, slug, position, probability, is_system) VALUES
(1, 'Nouveau', 'nouveau', 1, 10, 1),
(2, 'Qualifie', 'qualifie', 2, 25, 1),
(3, 'Découvert', 'decouvert', 3, 40, 1),
(4, 'Proposition envoyée', 'proposition-envoyee', 4, 60, 1),
(5, 'Négociation', 'negociation', 5, 75, 1),
(6, 'Gagné', 'gagne', 6, 100, 1),
(7, 'Perdu', 'perdu', 7, 0, 1);
INSERT INTO countries (id, code, name, phone_code) VALUES
(1, 'FR', 'France', '+33'),
(2, 'BE', 'Belgique', '+32'),
(3, 'CH', 'Suisse', '+41'),
(4, 'LU', 'Luxembourg', '+352'),
(5, 'DE', 'Allemagne', '+49'),
(6, 'ES', 'Espagne', '+34'),
(7, 'IT', 'Italie', '+39'),
(8, 'GB', 'Royaume-Uni', '+44'),
(9, 'IE', 'Irlande', '+353'),
(10, 'NL', 'Pays-Bas', '+31'),
(11, 'PT', 'Portugal', '+351'),
(12, 'CA', 'Canada', '+1'),
(13, 'US', 'Etats-Unis', '+1'),
(14, 'MA', 'Maroc', '+212'),
(15, 'DZ', 'Algerie', '+213'),
(16, 'TN', 'Tunisie', '+216'),
(17, 'SN', 'Senegal', '+221'),
(18, 'CI', "Cote d'Ivoire", '+225'),
(19, 'CM', 'Cameroun', '+237');
INSERT INTO settings (setting_key, setting_value) VALUES
('password_reset_enabled', 'true'),
('default_currency', 'EUR'),
('default_deal_stage', '1'),
('pagination_limit', '25');
INSERT INTO tags (id, name, slug) VALUES
(1, 'Prioritaire', 'prioritaire'),
(2, 'Partenaire', 'partenaire'),
(3, 'Presse', 'presse'),
(4, 'Salon', 'salon'),
(5, 'Relance', 'relance');
@@ -0,0 +1,18 @@
ALTER TABLE users
ADD CONSTRAINT fk_users_role FOREIGN KEY (role_id) REFERENCES roles (id) ON DELETE RESTRICT,
ADD CONSTRAINT chk_users_names CHECK (CHAR_LENGTH(first_name) > 0 AND CHAR_LENGTH(last_name) > 0);
ALTER TABLE contacts
ADD CONSTRAINT chk_contacts_names CHECK (CHAR_LENGTH(first_name) > 0 AND CHAR_LENGTH(last_name) > 0);
ALTER TABLE organizations
ADD CONSTRAINT chk_organizations_name CHECK (CHAR_LENGTH(name) > 0);
ALTER TABLE deals
ADD CONSTRAINT chk_deals_title CHECK (CHAR_LENGTH(title) > 0);
ALTER TABLE tags
ADD CONSTRAINT chk_tags_name CHECK (CHAR_LENGTH(name) > 0);
ALTER TABLE pipeline_stages
ADD CONSTRAINT chk_stages_name CHECK (CHAR_LENGTH(name) > 0);
@@ -0,0 +1,23 @@
ALTER TABLE audit_logs
MODIFY created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3);
ALTER TABLE deal_stage_history
MODIFY changed_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3);
ALTER TABLE deals
MODIFY stage_changed_at DATETIME(3) NULL,
MODIFY won_at DATETIME(3) NULL,
MODIFY lost_at DATETIME(3) NULL;
ALTER TABLE activities
MODIFY occurred_at DATETIME(3) NOT NULL;
ALTER TABLE tasks
MODIFY due_at DATETIME(3) NULL,
MODIFY completed_at DATETIME(3) NULL;
ALTER TABLE users
MODIFY last_login_at DATETIME(3) NULL;
ALTER TABLE password_reset_tokens
MODIFY expires_at DATETIME(3) NOT NULL;
@@ -0,0 +1,32 @@
-- 005_user_sessions.sql
--
-- Le CRM n'avait aucun support de session : l'authentification etait
-- impossible sans introduire une table. Miroir exact de celle du Cloud
-- (cohaise_cloud.user_sessions), pour que le code partage de
-- @cohaise/server travaille sur les deux bases sans adaptation.
--
-- Le jeton brut ne quitte jamais le serveur : seul son empreinte SHA-256 est
-- stockee, donc une copie de la base ne fournit aucune session ouvrable.
CREATE TABLE user_sessions (
id CHAR(36) NOT NULL,
user_id CHAR(36) NOT NULL,
token_hash CHAR(64) NOT NULL,
ip_address VARCHAR(45) DEFAULT NULL,
user_agent VARCHAR(255) DEFAULT NULL,
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
last_seen_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
expires_at DATETIME(3) NOT NULL,
revoked_at DATETIME(3) DEFAULT NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_user_sessions_hash (token_hash),
KEY idx_user_sessions_user (user_id, revoked_at),
KEY idx_user_sessions_expiry (expires_at),
CONSTRAINT fk_user_sessions_user
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- La purge des jetons expires n'est pas confiee a un EVENT MariaDB : elle
-- depend du planificateur, desactive par defaut, et une migration qui echoue
-- au milieu n'est pas enregistree. Le service appelle purgeExpiredSessions()
-- au demarrage, comme le Cloud.
@@ -0,0 +1,35 @@
-- 006_active_identity.sql
--
-- uq_contacts_email et uq_organizations_name portent sur la colonne brute :
-- une suppression logique laisse la ligne en place, donc l'index voit encore
-- la valeur et interdit toute reutilisation. Un prospect rendu inactif
-- bloquait ainsi sa propre reimportation.
--
-- Meme mecanisme que cohaise_cloud : une colonne generatee ne vaut rien quand
-- deleted_at n'est pas NULL, et en SQL plusieurs NULL ne sont pas egaux, donc
-- l'index ne voit plus la ligne supprimee. La contrainte d'origine est
-- conservee sous un autre nom pour que le controle reste explicable en base.
--
-- 001 n'est pas modifie : la correction passe par un fichier nouveau.
ALTER TABLE contacts
DROP INDEX uq_contacts_email,
ADD COLUMN active_email VARCHAR(255)
GENERATED ALWAYS AS (IF(deleted_at IS NULL, email, NULL)) STORED,
ADD UNIQUE KEY uq_contacts_active_email (active_email);
ALTER TABLE organizations
DROP INDEX uq_organizations_name,
ADD COLUMN active_name VARCHAR(255)
GENERATED ALWAYS AS (IF(deleted_at IS NULL, name, NULL)) STORED,
ADD UNIQUE KEY uq_organizations_active_name (active_name);
-- Deux contacts actifs ne peuvent pas porter la meme adresse, meme si elle
-- est saisie avec des casse differentes : la collation s'en charge deja, mais
-- la cle garantit que le controle ne depend pas du moteur.
INSERT INTO audit_logs (action, resource, details)
VALUES (
'schema.migration',
'migration',
JSON_OBJECT('version', '006_active_identity', 'portee', 'contacts.email, organizations.name')
);
+13
View File
@@ -0,0 +1,13 @@
-- Les roles disparaissent : le CRM n'a qu'un compte principal et un compte de
-- secours, tous deux avec les memes droits. requireRole et role_slug partent
-- en meme temps du code, la base reste le dernier recours.
--
-- 001, 002 et 003 ne sont pas retouches : la correction passe par ce fichier,
-- comme pour toute migration deja appliquee.
ALTER TABLE users DROP FOREIGN KEY fk_users_role;
ALTER TABLE users DROP COLUMN role_id;
-- L'index idx_users_role part avec la colonne.
DROP TABLE roles;
+24
View File
@@ -0,0 +1,24 @@
{
"name": "@cohaise/crm",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"build": "tsc --build",
"clean": "node --eval \"import('node:fs').then(fs => { fs.rmSync('dist', { recursive: true, force: true }); fs.rmSync('tsconfig.tsbuildinfo', { force: true }); })\"",
"typecheck": "tsc --noEmit",
"start": "node dist/index.js",
"admin": "node dist/admin.js"
},
"dependencies": {
"@cohaise/server": "*",
"zod": "^4.6.5"
},
"devDependencies": {
"@types/node": "^24.0.0",
"typescript": "^7.0.2"
},
"bin": {
"cohaise-crm-admin": "./dist/admin.js"
}
}
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env node
import { randomUUID } from "node:crypto";
import { ConfigError, loadDbConfig, hashPassword, AppError, toSafeError } from "@cohaise/server";
/**
* Creation et reinitialisation des comptes CRM, hors requete HTTP.
*
* Meme principe que cohaise-admin : cette commande ne lit que les variables
* DB, pour pouvoir creer le premier administrateur alors que l'API n'a pas
* encore le droit de demarrer.
*
* node dist/admin.js --email [email protected] --first Jean --last Dupont
* node dist/admin.js --email [email protected] --reset
*
* Mot de passe : ADMIN_PASSWORD dans l'environnement, sinon --password,
* sinon un mot de passe aleatoire est genere et affiche une seule fois.
*/
const USAGE = `Utilisation : cohaise-crm-admin --email <adr> --first <prenom> --last <nom> [options]
--email <adr> Adresse du compte (obligatoire)
--first <nom> Prenom (obligatoire a la creation)
--last <nom> Nom (obligatoire a la creation)
--password <mdp> Mot de passe, sinon variable ADMIN_PASSWORD
--reset Reinitialise le mot de passe d'un compte existant
--help Cette aide`;
interface Args {
email: string;
first: string;
last: string;
password?: string;
reset: boolean;
help: boolean;
}
const parseArgs = (argv: string[]): Args => {
const args: Args = {
email: "",
first: "",
last: "",
reset: false,
help: false,
};
const value = (index: number): string => {
const next = argv[index + 1];
if (next === undefined || next.startsWith("--")) {
throw AppError.badRequest(`Valeur manquante pour ${argv[index]}`);
}
return next;
};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === undefined) continue;
if (arg === "--email") args.email = value(index++);
else if (arg === "--first") args.first = value(index++);
else if (arg === "--last") args.last = value(index++);
else if (arg === "--password") args.password = value(index++);
else if (arg === "--reset") args.reset = true;
else if (arg === "--help" || arg === "-h") args.help = true;
else throw AppError.badRequest(`Argument inconnu : ${arg}`);
}
return args;
};
/** Mot de passe aleatoire, lisible a la frappe, sans caractere ambigu. */
const generatePassword = (): string => {
const alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
const bytes = new Uint8Array(18);
globalThis.crypto.getRandomValues(bytes);
let out = "";
for (const byte of bytes) out += alphabet[byte % alphabet.length];
return out;
};
const main = async (argv: string[]): Promise<number> => {
let args: Args;
try {
args = parseArgs(argv);
} catch (error) {
console.error(` ${toSafeError(error).message}\n\n${USAGE}`);
return 2;
}
if (args.help) {
console.log(USAGE);
return 0;
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(args.email)) {
console.error(" Adresse e-mail invalide.");
return 2;
}
let config;
try {
config = loadDbConfig();
} catch (error) {
if (error instanceof ConfigError) {
console.error(` Configuration invalide :\n - ${error.issues.join("\n - ")}`);
return 2;
}
throw error;
}
const { Db } = await import("@cohaise/server");
const db = new Db(config);
try {
// Pas de colonne active_email ici : le CRM n'a pas de migration qui
// neutralise les lignes supprimees sur la table users. On regarde donc
// deleted_at explicitement.
const existing = await db.one<{ id: string; deleted_at: string | null }>(
"SELECT id, deleted_at FROM users WHERE email = ?",
[args.email],
);
if (existing && !args.reset && existing.deleted_at === null) {
console.error(` Ce compte existe deja : ${args.email}`);
console.error(" Utilisez --reset pour reinitialiser son mot de passe.");
return 1;
}
const password = args.password ?? process.env.ADMIN_PASSWORD ?? generatePassword();
if (Buffer.byteLength(password) < 8) {
console.error(" Le mot de passe doit contenir au moins 8 caracteres.");
return 2;
}
const hash = await hashPassword(password);
if (existing) {
const assignments = ["password_hash = ?", "must_change_password = 1", "is_active = 1", "deleted_at = NULL"];
const values: unknown[] = [hash, existing.id];
await db.exec(`UPDATE users SET ${assignments.join(", ")} WHERE id = ?`, values);
console.log(` Mot de passe reinitialise pour ${args.email}`);
console.log(` Mot de passe : ${password}`);
console.log(" Un changement de mot de passe sera demande a la premiere connexion.");
return 0;
}
if (!args.first || !args.last) {
console.error(" --first et --last sont obligatoires a la creation.");
console.error(`\n${USAGE}`);
return 2;
}
const id = randomUUID();
await db.exec(
`INSERT INTO users (id, email, first_name, last_name, password_hash, must_change_password)
VALUES (?, ?, ?, ?, ?, 1)`,
[id, args.email, args.first, args.last, hash],
);
console.log(` Compte cree : ${args.email}`);
console.log(` Mot de passe : ${password}`);
console.log(" Un changement de mot de passe sera demande a la premiere connexion.");
return 0;
} catch (error) {
const safe = toSafeError(error);
console.error(` Echec : ${safe.code} — ${safe.message}`);
return 1;
} finally {
await db.close().catch(() => undefined);
}
};
main(process.argv.slice(2)).then(
(code) => process.exit(code),
(error) => {
console.error(` Erreur inattendue : ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
},
);
+25
View File
@@ -0,0 +1,25 @@
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";
const migrationsDir = join(dirname(fileURLToPath(import.meta.url)), "../migrations");
void startService({
service: "crm",
migrationsDir,
routes: (app, { db, config }) => {
registerAuthRoutes(app, db, config);
registerCountryRoutes(app, db);
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.
void purgeExpiredSessions(db);
},
});
+151
View File
@@ -0,0 +1,151 @@
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 });
});
};
+274
View File
@@ -0,0 +1,274 @@
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
@@ -0,0 +1,150 @@
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 });
},
);
};
+146
View File
@@ -0,0 +1,146 @@
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);
});
};
+277
View File
@@ -0,0 +1,277 @@
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 });
},
);
};
+17
View File
@@ -0,0 +1,17 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2023"],
"types": ["node"],
"rootDir": "src",
"outDir": "dist",
"composite": true,
"declaration": true,
"sourceMap": true
},
"include": ["src/**/*.ts"],
"references": [{ "path": "../shared" }]
}