commit 858d862fedf97df86efb30e15c54babc7d502dcc Author: xEsiah Date: Tue Nov 10 19:56:03 2026 +0100 feat: init repo diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..0eff9ca --- /dev/null +++ b/.dockerignore @@ -0,0 +1,20 @@ +node_modules +**/node_modules +**/dist +**/build +**/*.tsbuildinfo +**/.env +**/.env.* +!**/.env.example +.git +.gitignore +.vscode +.idea +*.log +npm-debug.log* +.DS_Store +Thumbs.db +docs +README.md +**/*.md +Makefile diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..8c52ff9 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,12 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_style = space +indent_size = 2 +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..e6314ff --- /dev/null +++ b/.env.example @@ -0,0 +1,48 @@ +# CoHaiSe — modele de configuration (vitrine + CRM). +# +# Copiez ce fichier vers .env puis completez-le : +# cp .env.example .env +# +# .env n'est jamais versionne (voir .gitignore). Ne placez aucun mot de passe +# de production dans ce fichier exemple : il est publique. +# +# Deux stacks se partagent ce depot mais se deploient independamment : +# - docker-compose.yml (vitrine cohaise.dev, statique) -> make +# - docker-compose.crm.yml (crm.cohaise.dev, front + API + DB) -> make crm-up + +# --- Vitrine (docker-compose.yml) ---------------------------------------- +# Port ouvert par nginx sur la machine hote. +COHAISE_HTTP_PORT=8080 + +# --- CRM (docker-compose.crm.yml) ---------------------------------------- +# Ports et identifiants de la base CRM. Le demarrage echoue avec la liste +# exacte des variables manquantes ou mal formees, avant l'ouverture d'aucun +# port. C'est voulu. +CRM_HTTP_PORT=8082 +CRM_DB_PORT=3307 +CRM_API_PORT=3202 +CRM_DATABASE=cohaise_crm +CRM_DB_USER=cohaise_crm +CRM_DB_PASSWORD= +# Mot de passe root du conteneur, utilise uniquement par la sauvegarde. +CRM_DB_ROOT_PASSWORD= +# Origines autorisees pour CORS, separees par des virgules. Vide = desactive. +# La vitrine poste le formulaire de contact vers /api/crm/leads : ajoutez son +# origine ici pour que le navigateur accepte la reponse. +CRM_CORS_ORIGIN=https://cohaise.dev +# Connexions simultanees a la base par instance d'API. +CRM_DB_CONNECTION_LIMIT=8 + +# --- Session (obligatoire pour l'API CRM) --------------------------------- +# Secret de chiffrement des sessions. Obligatoire, 32 caracteres minimum. +# Generation : +# node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))" +SESSION_SECRET= +# Duree de vie d'une session, en heures (336 = 14 jours). +SESSION_TTL_HOURS=336 + +# --- Exploitation commune -------------------------------------------------- +# silent | error | warn | info | debug +LOG_LEVEL=info +# true si une reverse proxy (nginx) termine TLS devant l'API. +TRUST_PROXY=true diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..4c10c13 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,18 @@ +name: deploy + +on: + push: + branches: [main] + +jobs: + deploy: + # Label du runner act_runner sur le serveur. À ajuster si le tien diffère. + runs-on: self-hosted + steps: + - name: Déploiement vitrine + CRM + run: | + set -e + cd /srv/apps/cohaise + git pull --ff-only origin main + make deploy-all + docker image prune -f diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2e31670 --- /dev/null +++ b/.gitignore @@ -0,0 +1,24 @@ +node_modules/ +dist/ +build/ +coverage/ +.vite/ +*.tsbuildinfo + +# Sauvegardes de base : contiennent les donnees, jamais versionnees. +backups/ + +.env +.env.* +!.env.example + +*.log +npm-debug.log* + +.DS_Store +Thumbs.db + +.idea/ +.vscode/* +!.vscode/extensions.json +!.vscode/settings.json diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..52a7cff --- /dev/null +++ b/Makefile @@ -0,0 +1,131 @@ +# CoHaiSe — gestion unifiée vitrine + CRM. +# Deux stacks indépendantes (deux fichiers Compose), un seul Makefile. + +COMPOSE = docker compose +CRM = docker compose -f docker-compose.crm.yml + +.PHONY: help \ + up down build logs reload nginx web web-build deploy dev \ + crm-up crm-down crm-build crm-logs crm-front crm-front-build crm-db crm-migrate crm-backup crm-admin crm-dev \ + up-all down-all deploy-all ps typecheck check + +help: + @echo "CoHaiSe — vitrine + CRM" + @echo "" + @echo "Vitrine (cohaise.dev, port 8080)" + @echo " make up Demarrer la vitrine" + @echo " make down Arreter la vitrine" + @echo " make web Reconstruire et publier la vitrine" + @echo " make deploy Build + demarrage" + @echo " make dev Vite vitrine (5173)" + @echo "" + @echo "CRM (crm.cohaise.dev, port 8082)" + @echo " make crm-up Demarrer le CRM" + @echo " make crm-down Arreter le CRM" + @echo " make crm-front Reconstruire et publier le front CRM" + @echo " make crm-migrate Appliquer les migrations" + @echo " make crm-backup Sauvegarder la base" + @echo " make crm-admin ARGS=... Creer ou reinitialiser un compte" + @echo " make crm-dev Vite CRM (5175)" + @echo "" + @echo "Les deux" + @echo " make up-all Demarrer vitrine + CRM" + @echo " make down-all Arreter vitrine + CRM" + @echo " make ps Etat des deux stacks" + @echo "" + @echo "Verification" + @echo " make typecheck / make check" + +# --- Vitrine ------------------------------------------------------------- +up: + $(COMPOSE) up -d + +down: + $(COMPOSE) down + +build: + $(COMPOSE) build + +logs: + $(COMPOSE) logs -f + +reload: + $(COMPOSE) exec nginx nginx -s reload + +nginx: reload + +web: + $(COMPOSE) up -d --build --force-recreate app-build + +web-build: + $(COMPOSE) build app-build + +deploy: + $(COMPOSE) build + $(COMPOSE) up -d --remove-orphans + +dev: + npm run dev --workspace=frontend/web + +# --- CRM ----------------------------------------------------------------- +crm-up: + $(CRM) up -d + +crm-down: + $(CRM) down + +crm-build: + $(CRM) build + +crm-logs: + $(CRM) logs -f + +crm-front: + $(CRM) up -d --build --force-recreate app-build + +crm-front-build: + $(CRM) build app-build + +crm-db: + $(CRM) restart db + +crm-migrate: + $(CRM) build migrate + $(CRM) run --rm migrate + +crm-backup: + @mkdir -p backups + @stamp=$$(date +%Y%m%dT%H%M%SZ); \ + $(CRM) exec -T db sh -c 'mariadb-dump --single-transaction --routines --events --password="$$MARIADB_ROOT_PASSWORD" "$$MARIADB_DATABASE"' | gzip > backups/crm-$$stamp.sql.gz; \ + echo " backups/crm-$$stamp.sql.gz $$(du -h backups/crm-$$stamp.sql.gz | cut -f1)" + +crm-admin: + $(CRM) run --rm --no-deps api node dist/admin.js $(ARGS) + +crm-dev: + npm run dev --workspace=frontend/crm + +# --- Les deux ------------------------------------------------------------ +up-all: + $(COMPOSE) up -d + $(CRM) up -d + +# Deploiement complet : build + demarrage des deux stacks, orphelins retires. +deploy-all: + $(COMPOSE) up -d --build --remove-orphans + $(CRM) up -d --build --remove-orphans + +down-all: + $(CRM) down + $(COMPOSE) down + +ps: + $(COMPOSE) ps + @echo "" + $(CRM) ps + +typecheck: + npm run typecheck + +check: typecheck + npm run build diff --git a/README.md b/README.md new file mode 100644 index 0000000..926102d --- /dev/null +++ b/README.md @@ -0,0 +1,72 @@ +# CoHaiSe + +Monorepo CoHaiSe : la **vitrine** `cohaise.dev` et le **CRM** `crm.cohaise.dev`, +deux applications qui partagent le même design system et le même socle serveur, +mais se déploient dans **deux stacks Docker indépendantes**. + +| Application | Sous-domaine | Stack | Port par défaut | Compose | +| --- | --- | --- | --- | --- | +| Vitrine | `cohaise.dev` | statique (nginx) | 8080 | `docker-compose.yml` | +| CRM | `crm.cohaise.dev` | nginx + API + MariaDB | 8082 | `docker-compose.crm.yml` | + +Le dépôt `CoHaiSe-CLOUD` (`cloud.cohaise.dev`) reste séparé. + +## Structure + +``` +frontend/ + shared/ @cohaise/ui — design system, jetons et composants partagés + web/ @cohaise/web — la vitrine (statique, bilingue FR/EN) + crm/ @cohaise/crm-web — le front du CRM (React + Vite) +backend/ + shared/ @cohaise/server — couche serveur : config, base, auth, http, migrations + crm/ @cohaise/crm — l'API du CRM (auth, organisations, contacts, leads) +docker/ + Dockerfile image nginx (paramétrée par NGINX_CONF) + Dockerfile.app build Vite puis export atomique dans le volume + Dockerfile.api image de l'API + nginx/web.conf serveur de la vitrine + nginx/crm.conf serveur du CRM (proxy /api/ vers l'API) + publish.sh publication atomique (symlink current) +``` + +## Vitrine + +La vitrine est une application statique React + Vite, sans base ni session. +Sections : Hero, Services (accordéon coulissant), Démos (mockups neutres), Stack, +À propos, Contact. Elle est bilingue (FR par défaut, EN) et porte le thème +« liquid glass » carmin du design system. + +Le formulaire de contact POSTe vers `POST /api/crm/leads` du CRM (cross-origin) ; +le lead est posé dans `contacts` avec `external_source = 'cohaise-web'`. + +```sh +cp .env.example .env # COHAISE_HTTP_PORT=8080 +make up # build + démarrage sur 8080 +make web # reconstruire et publier la vitrine +make dev # serveur Vite local, port 5173 +``` + +## CRM + +Application autonome (front + API + base), gérée par les cibles `make crm-*` du +même Makefile. + +```sh +make crm-up # front + API + base, migrations comprises +make crm-admin ARGS="--email moi@exemple.fr --first Jean --last Dupont" +``` + +Variables obligatoires (voir `.env.example`) : `SESSION_SECRET`, +`CRM_DB_PASSWORD`, `CRM_DB_ROOT_PASSWORD`, `CRM_DATABASE`, `CRM_DB_USER`. +Ajoutez `CRM_CORS_ORIGIN=https://cohaise.dev` pour que le formulaire de la +vitrine puisse poster ses leads. + +## Vérification + +```sh +npm run typecheck +npm run build +curl -I http://localhost:8080/healthz # vitrine +curl -I http://localhost:8082/healthz # CRM +``` diff --git a/backend/crm/README.md b/backend/crm/README.md new file mode 100644 index 0000000..f7df511 --- /dev/null +++ b/backend/crm/README.md @@ -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. diff --git a/backend/crm/migrations/000_schema_migrations.sql b/backend/crm/migrations/000_schema_migrations.sql new file mode 100644 index 0000000..103c6ba --- /dev/null +++ b/backend/crm/migrations/000_schema_migrations.sql @@ -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; diff --git a/backend/crm/migrations/001_initial_schema.sql b/backend/crm/migrations/001_initial_schema.sql new file mode 100644 index 0000000..ac675ba --- /dev/null +++ b/backend/crm/migrations/001_initial_schema.sql @@ -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; diff --git a/backend/crm/migrations/002_reference_data.sql b/backend/crm/migrations/002_reference_data.sql new file mode 100644 index 0000000..2cc313f --- /dev/null +++ b/backend/crm/migrations/002_reference_data.sql @@ -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'); diff --git a/backend/crm/migrations/003_integrity_backstop.sql b/backend/crm/migrations/003_integrity_backstop.sql new file mode 100644 index 0000000..7e831c2 --- /dev/null +++ b/backend/crm/migrations/003_integrity_backstop.sql @@ -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); diff --git a/backend/crm/migrations/004_audit_precision.sql b/backend/crm/migrations/004_audit_precision.sql new file mode 100644 index 0000000..bf648f9 --- /dev/null +++ b/backend/crm/migrations/004_audit_precision.sql @@ -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; diff --git a/backend/crm/migrations/005_user_sessions.sql b/backend/crm/migrations/005_user_sessions.sql new file mode 100644 index 0000000..8432b34 --- /dev/null +++ b/backend/crm/migrations/005_user_sessions.sql @@ -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. diff --git a/backend/crm/migrations/006_active_identity.sql b/backend/crm/migrations/006_active_identity.sql new file mode 100644 index 0000000..4950663 --- /dev/null +++ b/backend/crm/migrations/006_active_identity.sql @@ -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') +); diff --git a/backend/crm/migrations/007_no_roles.sql b/backend/crm/migrations/007_no_roles.sql new file mode 100644 index 0000000..3e36033 --- /dev/null +++ b/backend/crm/migrations/007_no_roles.sql @@ -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; diff --git a/backend/crm/package.json b/backend/crm/package.json new file mode 100644 index 0000000..3e92bc1 --- /dev/null +++ b/backend/crm/package.json @@ -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" + } +} diff --git a/backend/crm/src/admin.ts b/backend/crm/src/admin.ts new file mode 100644 index 0000000..8388084 --- /dev/null +++ b/backend/crm/src/admin.ts @@ -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 a@b.c --first Jean --last Dupont + * node dist/admin.js --email a@b.c --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 --first --last [options] + + --email Adresse du compte (obligatoire) + --first Prenom (obligatoire a la creation) + --last Nom (obligatoire a la creation) + --password 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 => { + 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); + }, +); diff --git a/backend/crm/src/index.ts b/backend/crm/src/index.ts new file mode 100644 index 0000000..f296277 --- /dev/null +++ b/backend/crm/src/index.ts @@ -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); + }, +}); diff --git a/backend/crm/src/routes/auth.ts b/backend/crm/src/routes/auth.ts new file mode 100644 index 0000000..2005927 --- /dev/null +++ b/backend/crm/src/routes/auth.ts @@ -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( + `${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(`${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 }); + }); +}; diff --git a/backend/crm/src/routes/contacts.ts b/backend/crm/src/routes/contacts.ts new file mode 100644 index 0000000..02aab58 --- /dev/null +++ b/backend/crm/src/routes/contacts.ts @@ -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( + `${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( + `${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(`${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 = { + 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(`${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 }); + }, + ); +}; diff --git a/backend/crm/src/routes/countries.ts b/backend/crm/src/routes/countries.ts new file mode 100644 index 0000000..09ff1a6 --- /dev/null +++ b/backend/crm/src/routes/countries.ts @@ -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( + `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( + "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 = { + 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( + "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 }); + }, + ); +}; diff --git a/backend/crm/src/routes/leads.ts b/backend/crm/src/routes/leads.ts new file mode 100644 index 0000000..6ffc9ea --- /dev/null +++ b/backend/crm/src/routes/leads.ts @@ -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 => { + 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(); + +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); + }); +}; diff --git a/backend/crm/src/routes/organizations.ts b/backend/crm/src/routes/organizations.ts new file mode 100644 index 0000000..711ee9a --- /dev/null +++ b/backend/crm/src/routes/organizations.ts @@ -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( + `${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( + `${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( + `${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 = { + 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( + `${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 }); + }, + ); +}; diff --git a/backend/crm/tsconfig.json b/backend/crm/tsconfig.json new file mode 100644 index 0000000..ab1723a --- /dev/null +++ b/backend/crm/tsconfig.json @@ -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" }] +} diff --git a/backend/shared/package.json b/backend/shared/package.json new file mode 100644 index 0000000..204681c --- /dev/null +++ b/backend/shared/package.json @@ -0,0 +1,33 @@ +{ + "name": "@cohaise/server", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "files": [ + "dist" + ], + "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" + }, + "devDependencies": { + "@types/node": "^24.0.0", + "typescript": "^7.0.2" + }, + "dependencies": { + "@hono/node-server": "^2.1.3", + "hono": "^4.13.13", + "mysql2": "^3.24.5", + "zod": "^4.6.5" + }, + "bin": { + "cohaise-migrate": "./dist/cli.js" + } +} diff --git a/backend/shared/src/auth.ts b/backend/shared/src/auth.ts new file mode 100644 index 0000000..aa1e58d --- /dev/null +++ b/backend/shared/src/auth.ts @@ -0,0 +1,224 @@ +import { createHash, randomBytes, randomUUID, scrypt as scryptCallback, timingSafeEqual } from "node:crypto"; +import { promisify } from "node:util"; +import type { Context, Next } from "hono"; +import { getCookie, setCookie, deleteCookie } from "hono/cookie"; +import type { Db } from "./db.js"; +import { AppError } from "./errors.js"; + +const scrypt = promisify(scryptCallback) as ( + password: string | Buffer, + salt: Buffer, + keylen: number, + options: { N: number; r: number; p: number; maxmem?: number }, +) => Promise; + +/** + * scrypt du module natif, pas une dependance externe. Une lib native a compiler + * est la facon la plus rapide de casser un build sur une machine cible : argon2 + * ou bcrypt produisent un binaire qui n'est pas portable sans outilchain. + * node:crypto est deja la, et scrypt est un KDF defini par RFC 7914. + */ +const SCRYPT = { N: 16384, r: 8, p: 1, keylen: 64, maxmem: 32 * 1024 * 1024 }; + +export const hashPassword = async (password: string): Promise => { + if (Buffer.byteLength(password) < 8) { + throw AppError.badRequest("Le mot de passe doit contenir au moins 8 caracteres."); + } + const salt = randomBytes(16); + const derived = await scrypt(password, salt, SCRYPT.keylen, SCRYPT); + return `scrypt$${SCRYPT.N}$${SCRYPT.r}$${SCRYPT.p}$${salt.toString("base64")}$${derived.toString("base64")}`; +}; + +export const verifyPassword = async (password: string, stored: string): Promise => { + const parts = stored.split("$"); + if (parts.length !== 6 || parts[0] !== "scrypt") return false; + const [, n, r, p, saltB64, hashB64] = parts; + const salt = Buffer.from(saltB64 ?? "", "base64"); + const expected = Buffer.from(hashB64 ?? "", "base64"); + if (expected.length === 0) return false; + + const derived = await scrypt(password, salt, expected.length, { + N: Number(n), + r: Number(r), + p: Number(p), + maxmem: SCRYPT.maxmem, + }); + return derived.length === expected.length && timingSafeEqual(derived, expected); +}; + +export const sha256 = (value: string): string => createHash("sha256").update(value).digest("hex"); + +/** + * Portrait de l'utilisateur porte par la session. + * + * Les budgets de stockage n'y figurent pas : une valeur figee dans un cookie + * serait fausse des la premiere ecriture, et le CRM n'a pas de notion de + * quota. Chaque route qui en a besoin relit les colonnes en base au moment + * de l'usage. + */ +export interface SessionUser { + id: string; + email: string; + first_name: string; + last_name: string; + role_slug: string; + role_name: string; + is_active: number; + must_change_password: number; +} + +export interface SessionMeta { + ipAddress?: string | null | undefined; + userAgent?: string | null | undefined; +} + +export const SESSION_COOKIE = "cohaise_session"; + +/** + * Le jeton brut part dans le cookie, son empreinte SHA-256 dans la base. + * Une copie de la base ne donne donc aucune session ouvrable : il faudrait + * en plus la table des cookies, qui n'existe pas. + */ +export const createSession = async ( + db: Db, + userId: string, + meta: SessionMeta, + ttlHours: number, +): Promise<{ token: string; expiresAt: Date }> => { + const token = randomBytes(32).toString("base64url"); + const expiresAt = new Date(Date.now() + ttlHours * 3600_000); + + await db.exec( + `INSERT INTO user_sessions (id, user_id, token_hash, ip_address, user_agent, expires_at) + VALUES (?, ?, ?, ?, ?, ?)`, + [ + randomUUID(), + userId, + sha256(token), + meta.ipAddress ?? null, + meta.userAgent?.slice(0, 255) ?? null, + expiresAt, + ], + ); + return { token, expiresAt }; +}; + +export const resolveSession = async (db: Db, token: string): Promise => { + const row = await db.one( + `SELECT u.id, u.email, u.first_name, u.last_name, + r.slug AS role_slug, r.name AS role_name, + u.is_active, u.must_change_password, + s.last_seen_at + FROM user_sessions s + JOIN users u ON u.id = s.user_id + JOIN roles r ON r.id = u.role_id + WHERE s.token_hash = ? + AND s.revoked_at IS NULL + AND s.expires_at > UTC_TIMESTAMP() + AND u.deleted_at IS NULL + AND u.is_active = 1`, + [sha256(token)], + ); + if (!row) return null; + // Etat vu, avec un decalage de 60 s pour ne pas ecrire a chaque requete. + await db.exec( + "UPDATE user_sessions SET last_seen_at = UTC_TIMESTAMP() WHERE token_hash = ? AND last_seen_at < UTC_TIMESTAMP(3) - INTERVAL 60 SECOND", + [sha256(token)], + ); + return row; +}; + +export const revokeSession = async (db: Db, token: string): Promise => { + await db.exec("UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE token_hash = ?", [ + sha256(token), + ]); +}; + +export const purgeExpiredSessions = async (db: Db): Promise => { + const result = await db.exec("DELETE FROM user_sessions WHERE expires_at < UTC_TIMESTAMP()"); + return result.affectedRows; +}; + +/** + * Secure depend du schema reel de la requete, pas d'une origine configuree. + * + * Deriver Secure de PUBLIC_ORIGIN rendait tout test local impossible : le + * navigateur rejette en HTTP un cookie marque Secure, donc la connexion + * echouait sans message exploitable. A l'inverse, un cookie non Secure servi en + * HTTPS laisserait le jeton circuler en clair. + * + * X-Forwarded-Proto n'est pris en compte que si le service fait confiance a son + * proxy ; sinon la connexion parle d'elle-meme. + */ +export const isHttpsRequest = (context: Context, trustProxy: boolean): boolean => { + if (trustProxy) { + const forwarded = context.req.header("x-forwarded-proto"); + if (forwarded) return forwarded.split(",")[0]?.trim() === "https"; + } + return context.req.raw.url.startsWith("https:"); +}; + +export const setSessionCookie = ( + context: Context, + token: string, + expiresAt: Date, + secure: boolean, +): void => { + setCookie(context, SESSION_COOKIE, token, { + httpOnly: true, + sameSite: "Lax", + secure, + path: "/", + expires: expiresAt, + }); +}; + +export const clearSessionCookie = (context: Context): void => { + deleteCookie(context, SESSION_COOKIE, { path: "/" }); +}; + +export interface AuthState { + user: SessionUser; + token: string; +} + +/** Lit le cookie et attache l'utilisateur, sans exiger qu'il existe. */ +export const attachUser = + (db: Db) => + async (context: Context, next: Next): Promise => { + const token = getCookie(context, SESSION_COOKIE); + if (token) { + const user = await resolveSession(db, token); + if (user) { + context.set("user", user); + context.set("token", token); + } else { + clearSessionCookie(context); + } + } + await next(); + }; + +export const requireAuth = async (context: Context, next: Next): Promise => { + const user = context.get("user") as SessionUser | undefined; + if (!user) throw AppError.unauthorized(); + await next(); +}; + +/** Le role est impose en base, jamais en entete, donc ni cacheable ni falsifiable. */ +export const requireRole = + (...slugs: string[]) => + async (context: Context, next: Next): Promise => { + const user = context.get("user") as SessionUser | undefined; + if (!user) throw AppError.unauthorized(); + if (!slugs.includes(user.role_slug)) { + throw AppError.forbidden(`Action reservee au role : ${slugs.join(", ")}.`); + } + await next(); + }; + +export const currentUser = (context: Context): SessionUser => { + const user = context.get("user") as SessionUser | undefined; + if (!user) throw AppError.unauthorized(); + return user; +}; diff --git a/backend/shared/src/cli.ts b/backend/shared/src/cli.ts new file mode 100644 index 0000000..7f338b3 --- /dev/null +++ b/backend/shared/src/cli.ts @@ -0,0 +1,137 @@ +#!/usr/bin/env node + +import { pathToFileURL } from "node:url"; +import { resolve } from "node:path"; +import { ConfigError, loadDbConfig } from "./config.js"; +import { Db } from "./db.js"; +import { AppError, toSafeError } from "./errors.js"; +import { listMigrations, runMigrations } from "./migrate.js"; + +/** + * Point d'entree des migrations : `node dist/cli.js --dir `. + * + * Le conteneur de migration n'a besoin d'aucun secret lisible a la main : + * les variables sont resolues par Docker depuis .env au lancement. + * + * Codes de sortie : + * 0 tout est applique, ou rien a faire + * 1 erreur (connexion, SQL, migration) OU derive detectee + * 2 configuration incomplete + */ + +interface Options { + dir: string; + dryRun: boolean; + check: boolean; + help: boolean; +} + +const USAGE = `Utilisation : cohaise-migrate --dir [--dry-run] [--check] + + --dir Dossier contenant les fichiers NNN_nom.sql (obligatoire) + --dry-run Analyse sans ecrire en base + --check Echoue s'il reste une migration a appliquer + --help Cette aide`; + +const parseArgs = (argv: string[]): Options => { + const options: Options = { dir: "", dryRun: false, check: false, help: false }; + for (let index = 0; index < argv.length; index += 1) { + const arg = argv[index]; + if (arg === undefined) continue; + if (arg === "--dry-run") options.dryRun = true; + else if (arg === "--check") options.check = true; + else if (arg === "--help" || arg === "-h") options.help = true; + else if (arg === "--dir") { + options.dir = argv[index + 1] ?? ""; + index += 1; + } else if (arg.startsWith("--dir=")) { + options.dir = arg.slice("--dir=".length); + } else { + throw AppError.badRequest(`Argument inconnu : ${arg}`, { argument: arg }); + } + } + return options; +}; + +const main = async (argv: string[]): Promise => { + let options: Options; + try { + options = parseArgs(argv); + } catch (error) { + const safe = toSafeError(error); + console.error(` ${safe.message}\n\n${USAGE}`); + return 2; + } + + if (options.help) { + console.log(USAGE); + return 0; + } + if (!options.dir) { + console.error(` --dir est obligatoire\n\n${USAGE}`); + 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 dir = resolve(options.dir); + const db = new Db(config); + + try { + const migrations = await listMigrations(dir); + if (migrations.length === 0) { + console.log(` Aucune migration trouvee dans ${dir}`); + return 0; + } + + const result = await runMigrations(db, dir, { dryRun: options.dryRun }); + const prefix = options.dryRun ? "[dry-run] " : ""; + + console.log( + `${prefix}${migrations.length} migration(s) · ${result.applied.length} appliquee(s) · ` + + `${result.skipped.length} deja en place · ${result.drifted.length} derivee(s)`, + ); + for (const version of result.applied) console.log(` + ${version}`); + for (const drift of result.drifted) { + console.error(` ! ${drift.version} modifiee depuis son execution (checksum attendu ${drift.recorded.slice(0, 12)}…, trouve ${drift.current.slice(0, 12)}…)`); + } + + if (result.drifted.length > 0) return 1; + if (options.check && result.applied.length > 0) return 1; + return 0; + } catch (error) { + const safe = toSafeError(error); + console.error(` Echec : ${safe.code} — ${safe.message}`); + if (error instanceof AppError && error.status >= 500 && error.message.includes("migree")) { + console.error(" Appliquez d'abord les migrations : cohaise-migrate --dir "); + } + return 1; + } finally { + await db.close().catch(() => undefined); + } +}; + +const isDirectRun = + process.argv[1] !== undefined && + import.meta.url === pathToFileURL(process.argv[1]).href; + +if (isDirectRun) { + 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); + }, + ); +} + +export { main, parseArgs }; diff --git a/backend/shared/src/config.ts b/backend/shared/src/config.ts new file mode 100644 index 0000000..4ce402c --- /dev/null +++ b/backend/shared/src/config.ts @@ -0,0 +1,95 @@ +import { z } from "zod"; + +/** + * Configuration lue une seule fois au demarrage. L'objet est fige : + * si une variable manque ou est mal formee, le processus s'arrete avant + * d'ouvrir le moindre port, avec la liste exacte de ce qui pose probleme. + * Une API qui demarre puis echoue sur la premiere requete est un defaut de + * deploiement, pas un defaut d'ecriture de code. + */ + +const bool = (fallback: boolean) => + z + .string() + .optional() + .transform((value) => { + if (value === undefined || value === "") return fallback; + return !["0", "false", "no", "off"].includes(value.toLowerCase()); + }); + +const port = (fallback: number) => + z.coerce.number().int().min(1).max(65535).default(fallback); + +const positiveInt = (fallback: number) => + z.coerce.number().int().positive().default(fallback); + +const schema = z.object({ + NODE_ENV: z.enum(["development", "production", "test"]).default("development"), + LOG_LEVEL: z.enum(["silent", "error", "warn", "info", "debug"]).default("info"), + + PORT: port(3000), + PUBLIC_ORIGIN: z.url().optional().transform((v) => v ?? null), + + DB_HOST: z.string().min(1), + DB_PORT: port(3306), + DB_USER: z.string().min(1), + DB_PASSWORD: z.string().min(1), + DB_NAME: z.string().min(1), + + DB_CONNECTION_LIMIT: positiveInt(8), + DB_CONNECT_TIMEOUT_MS: positiveInt(10_000), + + MEDIA_DIR: z.string().min(1).default("/data/media/originals"), + VARIANT_DIR: z.string().min(1).default("/data/media/variants"), + + SESSION_SECRET: z.string().min(32), + SESSION_TTL_HOURS: positiveInt(24 * 14), + + TRUST_PROXY: bool(false), + CORS_ORIGIN: z.string().optional().transform((v) => v ?? null), +}); + +export type Config = Readonly>; + +export class ConfigError extends Error { + readonly issues: string[]; + constructor(issues: string[]) { + super(`Configuration invalide (${issues.length}) :\n - ${issues.join("\n - ")}`); + this.name = "ConfigError"; + this.issues = issues; + } +} + +export const loadConfig = (env: NodeJS.ProcessEnv = process.env): Config => { + const parsed = schema.safeParse(env); + if (!parsed.success) throw new ConfigError(issuesOf(parsed.error)); + return Object.freeze(parsed.data); +}; + +/** Sous-ensemble DB, pour les outils qui n'ouvrent aucun port (migrations, CLI). */ +const dbSchema = z.object({ + NODE_ENV: z.enum(["development", "production", "test"]).default("development"), + LOG_LEVEL: z.enum(["silent", "error", "warn", "info", "debug"]).default("info"), + DB_HOST: z.string().min(1), + DB_PORT: port(3306), + DB_USER: z.string().min(1), + DB_PASSWORD: z.string().min(1), + DB_NAME: z.string().min(1), + DB_CONNECTION_LIMIT: positiveInt(8), + DB_CONNECT_TIMEOUT_MS: positiveInt(10_000), +}); + +export type DbConfig = Readonly>; + +export const loadDbConfig = (env: NodeJS.ProcessEnv = process.env): DbConfig => { + const parsed = dbSchema.safeParse(env); + if (!parsed.success) throw new ConfigError(issuesOf(parsed.error)); + return Object.freeze(parsed.data); +}; + +const issuesOf = (error: z.ZodError): string[] => + error.issues.map((issue) => { + const path = issue.path.join(".") || "(racine)"; + const missing = issue.code === "invalid_type" && issue.input === undefined; + return missing ? `${path} : variable absente` : `${path} : ${issue.message}`; + }); diff --git a/backend/shared/src/db.ts b/backend/shared/src/db.ts new file mode 100644 index 0000000..1697a1b --- /dev/null +++ b/backend/shared/src/db.ts @@ -0,0 +1,107 @@ +import mysql, { type Pool, type PoolConnection, type ResultSetHeader, type RowDataPacket } from "mysql2/promise"; +import type { DbConfig } from "./config.js"; + +export interface QueryError { + code: string; + errno: number; + sqlMessage?: string; +} + +export class Db { + readonly pool: Pool; + + constructor(config: DbConfig) { + this.pool = mysql.createPool({ + host: config.DB_HOST, + port: config.DB_PORT, + user: config.DB_USER, + password: config.DB_PASSWORD, + database: config.DB_NAME, + waitForConnections: true, + connectionLimit: config.DB_CONNECTION_LIMIT, + connectTimeout: config.DB_CONNECT_TIMEOUT_MS, + timezone: "Z", + charset: "utf8mb4_unicode_ci", + decimalNumbers: true, + // Porte refermee sur les requetes empilees : sans cet option, une + // contamination d'une lecture echappait en INSERT ou en DROP. Les valeurs + // sont toujours transmises en parametres, jamais concatenees dans le SQL. + multipleStatements: false, + namedPlaceholders: false, + }); + } + + /** Lecture en protocole prepare : les valeurs sont binaires, jamais des chains de texte. */ + async query(sql: string, params: unknown[] = []): Promise { + const [rows] = await this.pool.execute(sql, params as never); + return rows as T[]; + } + + /** Requete brute, sans parametres, reservee au DDL des migrations. + Certains etats DDL ne passent pas le protocole prepare de MariaDB. */ + async raw(sql: string): Promise { + await this.pool.query(sql); + } + + async one(sql: string, params: unknown[] = []): Promise { + const rows = await this.query(sql, params); + return (rows[0] as T | undefined) ?? null; + } + + /** Le premier resultat, ou une erreur explicite plutot qu'un undefined silencieux. */ + async required(sql: string, params: unknown[] = []): Promise { + const row = await this.one(sql, params); + if (row === null) { + throw Object.assign(new Error("Ligne introuvable"), { status: 404, code: "NOT_FOUND" }); + } + return row; + } + + async exec(sql: string, params: unknown[] = []): Promise { + const [result] = await this.pool.execute(sql, params as never); + return result as ResultSetHeader; + } + + async transaction(fn: (connection: PoolConnection) => Promise): Promise { + const connection = await this.pool.getConnection(); + try { + await connection.beginTransaction(); + const result = await fn(connection); + await connection.commit(); + return result; + } catch (error) { + await connection.rollback(); + throw error; + } finally { + connection.release(); + } + } + + /** Forme courte des erreurs de contrainte, pour les repondre en 409 et non en 500. */ + static classify(error: unknown): { status: number; message: string } { + const errno = (error as { errno?: number })?.errno; + const sqlMessage = (error as { sqlMessage?: string })?.sqlMessage ?? ""; + switch (errno) { + case 1062: + return { status: 409, message: "Cette valeur existe deja." }; + case 1451: + case 1452: + return { status: 409, message: "Operation impossible : des enregistrements en referent encore." }; + case 1406: + return { status: 422, message: "Valeur trop longue pour la colonne." }; + case 1146: + return { status: 503, message: "Table absente : la base n'est peut-etre pas migree." }; + case 1045: + return { status: 503, message: "Acces refuse par la base de donnees." }; + case 1040: + case 1203: + return { status: 503, message: "Trop de connexions a la base de donnees." }; + default: + return errno === undefined ? { status: 500, message: "Erreur interne." } : { status: 500, message: sqlMessage || "Erreur de base de donnees." }; + } + } + + async close(): Promise { + await this.pool.end(); + } +} diff --git a/backend/shared/src/errors.ts b/backend/shared/src/errors.ts new file mode 100644 index 0000000..4ce8018 --- /dev/null +++ b/backend/shared/src/errors.ts @@ -0,0 +1,100 @@ +/** + * Erreurs portees par un code HTTP. Une erreur qui n'en porte pas est + * consideree interne : on journalise le detail, on ne le rend jamais au + * client, parce que le message d'une exception ne doit pas decrire le schema. + */ + +export class AppError extends Error { + readonly status: number; + readonly code: string; + readonly details?: Record; + + constructor(status: number, code: string, message: string, details?: Record) { + super(message); + this.name = "AppError"; + this.status = status; + this.code = code; + if (details !== undefined) this.details = details; + } + + static badRequest(message: string, details?: Record) { + return new AppError(400, "BAD_REQUEST", message, details); + } + static unauthorized(message = "Authentification requise.") { + return new AppError(401, "UNAUTHORIZED", message); + } + static forbidden(message = "Vous ne pouvez pas effectuer cette action.") { + return new AppError(403, "FORBIDDEN", message); + } + static notFound(message = "Ressource introuvable.") { + return new AppError(404, "NOT_FOUND", message); + } + static conflict(message: string) { + return new AppError(409, "CONFLICT", message); + } + static payloadTooLarge(message = "Fichier trop volumineux.") { + return new AppError(413, "PAYLOAD_TOO_LARGE", message); + } + static unprocessable(message: string, details?: Record) { + return new AppError(422, "UNPROCESSABLE", message, details); + } + static tooManyRequests(message = "Trop de requetes. Reessayez plus tard.") { + return new AppError(429, "TOO_MANY_REQUESTS", message); + } + static serviceUnavailable(message = "Service momentanement indisponible.") { + return new AppError(503, "UNAVAILABLE", message); + } +} + +export interface SafeError { + status: number; + code: string; + message: string; + details?: Record; +} + +export const toSafeError = (error: unknown): SafeError => { + if (error instanceof AppError) { + return error.details !== undefined + ? { status: error.status, code: error.code, message: error.message, details: error.details } + : { status: error.status, code: error.code, message: error.message }; + } + + const status = (error as { status?: number })?.status; + const code = (error as { code?: string })?.code; + if (typeof status === "number" && status >= 400 && status < 500) { + return { status, code: code ?? "BAD_REQUEST", message: (error as Error).message }; + } + + // Une erreur MariaDB connue est un probleme d'exploitation, pas un crash. + const errno = (error as { errno?: number })?.errno; + if (errno !== undefined) { + const { status: dbStatus, message } = classifyDbError(errno); + return { status: dbStatus, code: errno === 1146 ? "NOT_MIGRATED" : "DATABASE", message }; + } + + return { status: 500, code: "INTERNAL", message: "Erreur interne." }; +}; + +const classifyDbError = (errno: number): { status: number; message: string } => { + switch (errno) { + case 1062: + return { status: 409, message: "Cette valeur existe deja." }; + case 1451: + case 1452: + return { status: 409, message: "Operation impossible : des enregistrements en referent encore." }; + case 1406: + return { status: 422, message: "Valeur trop longue pour la colonne." }; + case 1146: + return { status: 503, message: "Base non migree. Lancez les migrations avant de servir." }; + case 1045: + return { status: 503, message: "Acces refuse par la base de donnees." }; + case 1040: + case 1203: + return { status: 503, message: "Trop de connexions a la base de donnees." }; + case 1053: + return { status: 503, message: "Base de donnees en cours d'initialisation." }; + default: + return { status: 503, message: "Base de donnees indisponible." }; + } +}; diff --git a/backend/shared/src/http.ts b/backend/shared/src/http.ts new file mode 100644 index 0000000..09c93f2 --- /dev/null +++ b/backend/shared/src/http.ts @@ -0,0 +1,154 @@ +import { randomUUID } from "node:crypto"; +import { Hono, type Context, type Next } from "hono"; +import { cors } from "hono/cors"; +import type { SessionUser } from "./auth.js"; +import type { Config } from "./config.js"; +import type { Db } from "./db.js"; +import { AppError, toSafeError } from "./errors.js"; + +export interface Logger { + level: Config["LOG_LEVEL"]; + info: (message: string, fields?: Record) => void; + warn: (message: string, fields?: Record) => void; + error: (message: string, fields?: Record) => void; + debug: (message: string, fields?: Record) => void; +} + +const ORDER: Record = { + silent: 0, + error: 1, + warn: 2, + info: 3, + debug: 4, +}; + +export const createLogger = (level: Config["LOG_LEVEL"], service: string): Logger => { + const emit = (name: keyof typeof ORDER, message: string, fields?: Record) => { + if (ORDER[name] > ORDER[level]) return; + const line = JSON.stringify({ + ts: new Date().toISOString(), + level: name, + service, + msg: message, + ...fields, + }); + if (name === "error") console.error(line); + else console.log(line); + }; + + return { + level, + info: (message, fields) => emit("info", message, fields), + warn: (message, fields) => emit("warn", message, fields), + error: (message, fields) => emit("error", message, fields), + debug: (message, fields) => emit("debug", message, fields), + }; +}; + +/** Variables transportees par chaque requete : tracee d'identification. */ +export interface AppEnv { + Variables: { + requestId: string; + /** Posee par attachUser quand le cookie de session est valide. */ + user?: SessionUser; + token?: string; + }; +} + +/** Type public d'une application CoHaiSe, impose aux routes metier. */ +export type App = Hono; + +/** Dependances remises aux routes metier au montage. */ +export interface RouteDeps { + db: Db; + config: Config; + logger: Logger; +} + +export interface AppOptions { + service: string; + config: Config; + db: Db; + logger: Logger; + /** Routes metier, montees sous /api/ dans le routing. */ + routes: (app: App, deps: RouteDeps) => void; + /** Vrai quand l'API doit repondre a /healthz avec l'etat de la base. */ + probeDb?: boolean; +} + +export const createApp = ({ service, config, db, logger, routes, probeDb = true }: AppOptions): App => { + const app = new Hono(); + + app.use("*", async (context: Context, next: Next) => { + const requestId = context.req.header("x-request-id") ?? randomUUID(); + context.set("requestId", requestId); + context.res.headers.set("x-request-id", requestId); + context.res.headers.set("x-content-type-options", "nosniff"); + context.res.headers.set("referrer-policy", "same-origin"); + context.res.headers.set("x-frame-options", "DENY"); + const started = performance.now(); + await next(); + const duration = Math.round(performance.now() - started); + if (context.req.method !== "OPTIONS") { + logger.debug("requete", { + requestId, + method: context.req.method, + path: new URL(context.req.url).pathname, + status: context.res.status, + durationMs: duration, + }); + } + }); + + if (config.CORS_ORIGIN) { + app.use( + "*", + cors({ + origin: config.CORS_ORIGIN.split(",").map((value) => value.trim()), + credentials: true, + maxAge: 600, + }), + ); + } + + app.get("/healthz", async (context) => { + if (!probeDb) return context.json({ status: "ok", service }, 200); + const started = performance.now(); + try { + await db.query("SELECT 1"); + return context.json( + { status: "ok", service, db: "up", latencyMs: Math.round(performance.now() - started) }, + 200, + ); + } catch (error) { + logger.error("sante base en echec", { error: String(error) }); + return context.json({ status: "degraded", service, db: "down" }, 503); + } + }); + + routes(app, { db, config, logger }); + + app.notFound((context) => + context.json({ error: { status: 404, code: "NOT_FOUND", message: "Route introuvable." } }, 404), + ); + + app.onError((error, context) => { + const safe = toSafeError(error); + const requestId = context.get("requestId"); + if (safe.status >= 500) { + logger.error("erreur non geree", { + requestId, + code: safe.code, + message: error instanceof Error ? error.message : String(error), + stack: error instanceof Error ? error.stack : undefined, + }); + } else { + logger.debug("refus", { requestId, code: safe.code, status: safe.status }); + } + return context.json({ error: { ...safe, requestId } }, safe.status as 500); + }); + + return app; +}; + +export { AppError }; diff --git a/backend/shared/src/index.ts b/backend/shared/src/index.ts new file mode 100644 index 0000000..1161d37 --- /dev/null +++ b/backend/shared/src/index.ts @@ -0,0 +1,47 @@ +export { + loadConfig, + loadDbConfig, + ConfigError, + type Config, + type DbConfig, +} from "./config.js"; +export { Db } from "./db.js"; +export { AppError, toSafeError, type SafeError } from "./errors.js"; +export { + createApp, + createLogger, + type App, + type AppEnv, + type AppOptions, + type Logger, + type RouteDeps, +} from "./http.js"; +export { + attachUser, + clearSessionCookie, + createSession, + currentUser, + isHttpsRequest, + hashPassword, + requireAuth, + requireRole, + purgeExpiredSessions, + revokeSession, + SESSION_COOKIE, + setSessionCookie, + sha256, + verifyPassword, + type SessionUser, +} from "./auth.js"; +export { + listMigrations, + runMigrations, + assertNoDrift, + type MigrationResult, +} from "./migrate.js"; +export { + prepareService, + startService, + type Service, + type ServiceOptions, +} from "./service.js"; diff --git a/backend/shared/src/migrate.ts b/backend/shared/src/migrate.ts new file mode 100644 index 0000000..ff35052 --- /dev/null +++ b/backend/shared/src/migrate.ts @@ -0,0 +1,144 @@ +import { createHash } from "node:crypto"; +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import type { Db } from "./db.js"; + +/** + * Applique les fichiers NNN_nom.sql dans l'ordre lexical, et uniquement ceux + * qui ne sont pas encore marques comme appliques. Idempotent : un second appel + * ne reexecute rien. + * + * Limite connue et assumee : le DDL MariaDB n'est pas transactionnel. Un fichier + * echoue au milieu, le reste des statements n'est pas applique et le fichier + * n'est pas enregistre. Le repasser reprend depuis son debut. C'est pourquoi + * chaque migration part de la ou la precedente a fini, et pourquoi une migration + * en desordre doit etre reparue et pas seulement sauvegardee depuis sa moitie. + */ + +export interface MigrationFile { + version: string; + file: string; + sql: string; + checksum: string; +} + +export interface MigrationResult { + applied: string[]; + skipped: string[]; + /** Migrations deja appliquees dont le contenu du fichier a change depuis. */ + drifted: { version: string; recorded: string; current: string }[]; +} + +// Les deux bases utilisent un prefixe a trois chiffres (000, 001, …) ; +// quatre est accepte pour ne pas interdire le passage a un dossier plus large. +const FILE_PATTERN = /^(\d{3,4}_[a-z0-9_]+)\.sql$/; + +export const listMigrations = async (dir: string): Promise => { + const entries = await readdir(dir); + const files = entries.filter((entry) => FILE_PATTERN.test(entry)).sort(); + + return Promise.all( + files.map(async (file) => { + const sql = await readFile(path.join(dir, file), "utf8"); + return { + version: FILE_PATTERN.exec(file)?.[1] ?? file, + file, + sql, + checksum: createHash("sha256").update(sql).digest("hex"), + }; + }), + ); +}; + +const ensureLedger = async (db: Db): Promise => { + await db.raw(` + 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 + `); + // Creer la colonne ici plutot que dans une migration : ajouter une ligne a un + // registre qui enregistre lui-meme les lignes ajoutees boucle sur lui-meme. + await db.raw( + "ALTER TABLE schema_migrations ADD COLUMN IF NOT EXISTS checksum CHAR(64) NULL AFTER applied_at", + ); +}; + +export const runMigrations = async ( + db: Db, + dir: string, + options: { dryRun?: boolean } = {}, +): Promise => { + const files = await listMigrations(dir); + await ensureLedger(db); + + const applied = new Map(); + const rows = await db.query<{ version: string; checksum: string | null }>( + "SELECT version, checksum FROM schema_migrations", + ); + for (const row of rows) applied.set(row.version, { checksum: row.checksum }); + + const result: MigrationResult = { applied: [], skipped: [], drifted: [] }; + + for (const migration of files) { + const record = applied.get(migration.version); + + if (record) { + result.skipped.push(migration.version); + if (record.checksum && record.checksum !== migration.checksum) { + result.drifted.push({ + version: migration.version, + recorded: record.checksum, + current: migration.checksum, + }); + } + continue; + } + + if (options.dryRun) { + result.applied.push(migration.version); + continue; + } + + // Un statement par un statement : un filet de faille reste visible et le + // point d'arret reste reproductible plutot qu'un bloc de 400 lignes perdu. + // + // Les lignes de commentaire sont retirees, pas le statement entier : un + // en-tete de fichier ou une legende au-dessus d'un INSERT ne doit pas + // faire sauter la requete, et encore moins la faire sauter en silence + // pendant que la version est enregistree comme appliquee. + const statements = migration.sql + .split(/;\s*(?:\r?\n|$)/) + .map((statement) => + statement + .split(/\r?\n/) + .filter((line) => !line.trim().startsWith("--")) + .join("\n") + .trim(), + ) + .filter((statement) => statement.length > 0); + + for (const statement of statements) await db.raw(statement); + + await db.exec("INSERT INTO schema_migrations (version, checksum) VALUES (?, ?)", [ + migration.version, + migration.checksum, + ]); + result.applied.push(migration.version); + } + + return result; +}; + +export const assertNoDrift = (result: MigrationResult): void => { + if (result.drifted.length === 0) return; + const lines = result.drifted.map( + (d) => ` ${d.version} : appliquee ${d.recorded.slice(0, 12)}, fichier ${d.current.slice(0, 12)}`, + ); + throw new Error( + `Migrations deja appliquees modifiees depuis leur execution (${result.drifted.length}) :\n` + + `${lines.join("\n")}\n` + + "Une migration appliquee ne se modifie pas : creez un nouveau fichier.", + ); +}; diff --git a/backend/shared/src/service.ts b/backend/shared/src/service.ts new file mode 100644 index 0000000..890a70b --- /dev/null +++ b/backend/shared/src/service.ts @@ -0,0 +1,135 @@ +import { createServer, type Server } from "node:http"; +import { type AddressInfo } from "node:net"; +import { getRequestListener } from "@hono/node-server"; +import { ConfigError, loadConfig, type Config } from "./config.js"; +import { AppError } from "./errors.js"; +import { Db } from "./db.js"; +import { + createLogger, + createApp, + type App, + type AppOptions, + type Logger, + type RouteDeps, +} from "./http.js"; +import { assertNoDrift, runMigrations } from "./migrate.js"; + +export interface ServiceOptions { + service: string; + /** Dossier contenant les fichiers NNN_nom.sql de cette application. */ + migrationsDir?: string; + routes: (app: App, deps: RouteDeps) => void; + probeDb?: boolean; +} + +export interface Service { + config: Config; + db: Db; + logger: Logger; + app: App; +} + +const fail = (error: unknown): never => { + if (error instanceof ConfigError) { + console.error(`\n [${new Date().toISOString()}] Demarrage refuse\n`); + console.error(error.message); + console.error( + "\n Verifiez .env (ou les variables du conteneur). .env.example recense l'ensemble du format attendu.\n", + ); + } else { + console.error( + `\n [${new Date().toISOString()}] Demarrage refuse : ${ + error instanceof Error ? error.message : String(error) + }\n`, + ); + if (error instanceof Error && error.stack) console.error(error.stack); + } + process.exit(1); +}; + +/** + * Prepare le service sans lancer d'ecoute. Utile pour la CLI de migration et + * pour les tests, qui n'ont pas besoin d'un port. + */ +export const prepareService = async (options: ServiceOptions): Promise => { + const config = loadConfig(); + const logger = createLogger(config.LOG_LEVEL, options.service); + const db = new Db(config); + + if (options.migrationsDir) { + const result = await runMigrations(db, options.migrationsDir); + assertNoDrift(result); + if (result.applied.length > 0) { + logger.info("migrations appliquees", { versions: result.applied }); + } + if (result.drifted.length > 0) { + logger.warn("migrations modifiees depuis leur execution", { + versions: result.drifted.map((d) => d.version), + }); + } + } + + const app = createApp({ + service: options.service, + config, + db, + logger, + routes: options.routes, + probeDb: options.probeDb ?? true, + }); + + return { config, db, logger, app }; +}; + +/** Demarre, ecoute, et s'arrete proprement. */ +export const startService = async (options: ServiceOptions): Promise => { + let prepared: Service; + try { + prepared = await prepareService(options); + } catch (error) { + return fail(error); + } + + const { config, db, logger, app } = prepared; + const server: Server = createServer(getRequestListener(app.fetch)); + + server.keepAliveTimeout = 65_000; + server.headersTimeout = 70_000; + + const shutdown = async (signal: string) => { + logger.info("arret demande", { signal }); + // Le SIGTERM de docker stop a un delai limite : fermer d'abord l'ecoute + // evite de nouvelles requetes, puis attendre les requetes en cours. + server.close(async () => { + await db.close().catch((error: unknown) => logger.error("fermeture base", { error: String(error) })); + logger.info("arret termine"); + process.exit(0); + }); + setTimeout(() => { + logger.warn("arret force apres delai"); + process.exit(1); + }, 10_000).unref(); + }; + + process.on("SIGTERM", () => void shutdown("SIGTERM")); + process.on("SIGINT", () => void shutdown("SIGINT")); + process.on("unhandledRejection", (reason) => { + logger.error("rejet de promesse non gere", { reason: String(reason) }); + }); + + await new Promise((resolve) => { + server.listen(config.PORT, "0.0.0.0", () => resolve()); + }); + + const address = server.address() as AddressInfo; + logger.info("api prete", { + port: address.port, + env: config.NODE_ENV, + db: `${config.DB_HOST}:${config.DB_PORT}/${config.DB_NAME}`, + }); + + return server; +}; + +export { AppError, ConfigError, Db, createApp, createLogger, loadConfig, runMigrations }; +export type { AppOptions, Config, Logger, RouteDeps }; diff --git a/backend/shared/tsconfig.json b/backend/shared/tsconfig.json new file mode 100644 index 0000000..c62df5b --- /dev/null +++ b/backend/shared/tsconfig.json @@ -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, + "declarationMap": true, + "sourceMap": true + }, + "include": ["src/**/*.ts"] +} diff --git a/docker-compose.crm.yml b/docker-compose.crm.yml new file mode 100644 index 0000000..95d3a1f --- /dev/null +++ b/docker-compose.crm.yml @@ -0,0 +1,163 @@ +name: cohaise-crm + +x-timezone: &timezone + TZ: Europe/Paris + +x-restart: &restart + restart: unless-stopped + +# Publication du front : build Vite puis export atomique dans le volume nginx. +x-app: &app + container_name: cohaise-crm-builder + restart: "no" + build: + context: . + dockerfile: docker/Dockerfile.app + target: export + command: sh /publish.sh + volumes: + - ./docker/publish.sh:/publish.sh:ro + +# Les services de migration tournent l'executable cohaise-migrate depuis +# backend/shared. Ils ne lisent aucun fichier .env : Docker resout les +# variables ci-dessous au lancement, elles ne passent donc jamais par un +# terminal ni par le depot. +x-migrate-build: &migrate-build + context: . + dockerfile: docker/Dockerfile.api + args: + APP_DIR: backend/shared + +services: + app-build: + <<: *app + build: + context: . + dockerfile: docker/Dockerfile.app + target: export + args: + APP_DIR: frontend/crm + volumes: + - app_data:/output + - ./docker/publish.sh:/publish.sh:ro + + nginx: + container_name: cohaise-crm-nginx + build: + context: . + dockerfile: docker/Dockerfile + args: + NGINX_CONF: crm.conf + ports: + # Tunnel Cloudflare en amont : n'ecouter que sur la boucle locale. + - "127.0.0.1:${CRM_HTTP_PORT:-8082}:80" + # Le tunnel Cloudflare joint nginx par son nom sur le reseau partage. + networks: + - default + - shared-network + environment: + <<: *timezone + volumes: + - app_data:/usr/share/nginx/html + healthcheck: + test: ["CMD-SHELL", "wget -qO- http://127.0.0.1/healthz || exit 1"] + interval: 10s + timeout: 3s + retries: 3 + <<: *restart + + db: + container_name: cohaise-crm-db + image: mariadb:11.4 + environment: + <<: *timezone + MARIADB_ROOT_PASSWORD: ${CRM_DB_ROOT_PASSWORD} + MARIADB_DATABASE: ${CRM_DATABASE} + MARIADB_USER: ${CRM_DB_USER} + MARIADB_PASSWORD: ${CRM_DB_PASSWORD} + ports: + - "127.0.0.1:${CRM_DB_PORT:-3307}:3306" + healthcheck: + test: + [ + "CMD-SHELL", + "healthcheck.sh --connect --innodb_initialized", + ] + interval: 10s + timeout: 5s + retries: 5 + volumes: + - db_data:/var/lib/mysql + <<: *restart + + migrate: + build: *migrate-build + image: cohaise-crm-migrate + restart: "no" + depends_on: + db: + condition: service_healthy + environment: + <<: *timezone + NODE_ENV: production + LOG_LEVEL: ${LOG_LEVEL:-info} + DB_HOST: db + DB_PORT: "3306" + DB_USER: ${CRM_DB_USER} + DB_PASSWORD: ${CRM_DB_PASSWORD} + DB_NAME: ${CRM_DATABASE} + command: ["node", "dist/cli.js", "--dir", "/migrations"] + volumes: + - ./backend/crm/migrations:/migrations:ro + + # Pas de MEDIA_DIR : le CRM ne stocke aucun fichier, seule la base suffit. + # migrate est un prerequis car runMigrations rejoue le meme dossier au + # demarrage du service : les deux chemins doivent voir les memes versions. + api: + container_name: cohaise-crm-api + build: + context: . + dockerfile: docker/Dockerfile.api + args: + APP_DIR: backend/crm + image: cohaise-crm-api + restart: unless-stopped + depends_on: + db: + condition: service_healthy + migrate: + condition: service_completed_successfully + environment: + <<: *timezone + NODE_ENV: production + LOG_LEVEL: ${LOG_LEVEL:-info} + PORT: "8080" + DB_HOST: db + DB_PORT: "3306" + DB_USER: ${CRM_DB_USER} + DB_PASSWORD: ${CRM_DB_PASSWORD} + DB_NAME: ${CRM_DATABASE} + DB_CONNECTION_LIMIT: ${CRM_DB_CONNECTION_LIMIT:-8} + SESSION_SECRET: ${SESSION_SECRET} + SESSION_TTL_HOURS: ${SESSION_TTL_HOURS:-336} + TRUST_PROXY: ${TRUST_PROXY:-true} + CORS_ORIGIN: ${CRM_CORS_ORIGIN:-} + ports: + - "127.0.0.1:${CRM_API_PORT:-3202}:8080" + healthcheck: + test: ["CMD", "wget", "-qO-", "http://127.0.0.1:8080/healthz"] + interval: 15s + timeout: 5s + retries: 5 + start_period: 20s + <<: *restart + +volumes: + app_data: + db_data: + +networks: + # Reseau partage avec le tunnel Cloudflare et les autres applications de + # l'hote. Externe : cree par le compose du tunnel, pas par ce projet. + shared-network: + external: true diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..e20053e --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,56 @@ +name: cohaise-web + +x-timezone: &timezone + TZ: Europe/Paris + +x-restart: &restart + restart: unless-stopped + +services: + app-build: + container_name: cohaise-web-app-build + restart: "no" + build: + context: . + dockerfile: docker/Dockerfile.app + target: export + args: + APP_DIR: frontend/web + command: sh /publish.sh + volumes: + - app_data:/output + - ./docker/publish.sh:/publish.sh:ro + + nginx: + container_name: cohaise-web-nginx + build: + context: . + dockerfile: docker/Dockerfile + args: + NGINX_CONF: web.conf + ports: + # Tunnel Cloudflare en amont : n'ecouter que sur la boucle locale. + - "127.0.0.1:${COHAISE_HTTP_PORT:-8080}:80" + # Le tunnel Cloudflare joint nginx par son nom sur le reseau partage. + networks: + - default + - shared-network + environment: + <<: *timezone + volumes: + - app_data:/usr/share/nginx/html + healthcheck: + test: ["CMD-SHELL", "wget -qO- http://127.0.0.1/healthz || exit 1"] + interval: 10s + timeout: 3s + retries: 3 + <<: *restart + +networks: + # Reseau partage avec le tunnel Cloudflare et les autres applications de + # l'hote. Externe : cree par le compose du tunnel, pas par ce projet. + shared-network: + external: true + +volumes: + app_data: diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000..872f697 --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,11 @@ +FROM nginx:1.27-alpine + +ARG NGINX_CONF=web.conf + +RUN rm -f /etc/nginx/conf.d/default.conf \ + && mkdir -p /usr/share/nginx/html + +COPY docker/nginx/${NGINX_CONF} /etc/nginx/conf.d/app.conf +COPY docker/nginx/snippets /etc/nginx/snippets + +EXPOSE 80 diff --git a/docker/Dockerfile.api b/docker/Dockerfile.api new file mode 100644 index 0000000..3b2d2d9 --- /dev/null +++ b/docker/Dockerfile.api @@ -0,0 +1,41 @@ +# Image des services API Node. Un seul Dockerfile pour Cloud et CRM : +# APP_DIR choisit quelle application on construit, donc les deux deploiements +# ne peuvent pas diverger dans leur methode de construction. +FROM node:22-slim AS builder + +ARG APP_DIR + +WORKDIR /repo + +COPY package.json package-lock.json tsconfig.json tsconfig.base.json ./ +COPY frontend ./frontend +COPY backend ./backend + +RUN npm ci --no-audit --no-fund --fetch-retries=5 +RUN npm run build --workspace=backend/shared +RUN npm run build --workspace=${APP_DIR} + +# On ne embarque pas les devDependencies dans l'image de production. +RUN npm prune --omit=dev && npm cache clean --force + +FROM node:22-alpine AS export + +ARG APP_DIR + +ENV NODE_ENV=production + +WORKDIR /repo + +COPY --from=builder /repo/package.json ./package.json +COPY --from=builder /repo/package-lock.json ./package-lock.json +COPY --from=builder /repo/node_modules ./node_modules +# backend/shared est le paquet @cohaise/server : les liens de workspace +# de node_modules pointent dessus, il doit donc voyager avec l'application. +COPY --from=builder /repo/backend/shared ./backend/shared +COPY --from=builder /repo/${APP_DIR} ./${APP_DIR} + +WORKDIR /repo/${APP_DIR} + +EXPOSE 8080 + +CMD ["node", "dist/index.js"] diff --git a/docker/Dockerfile.app b/docker/Dockerfile.app new file mode 100644 index 0000000..9d36e98 --- /dev/null +++ b/docker/Dockerfile.app @@ -0,0 +1,19 @@ +FROM node:22-slim AS builder + +WORKDIR /repo + +ARG APP_DIR + +COPY package.json package-lock.json tsconfig.json tsconfig.base.json ./ +COPY frontend ./frontend +COPY backend ./backend + +RUN npm ci --no-audit --no-fund --fetch-retries=5 +RUN npm run build --workspace=frontend/shared +RUN npm run build --workspace=${APP_DIR} + +FROM alpine:3.21 AS export + +ARG APP_DIR + +COPY --from=builder /repo/${APP_DIR}/dist /app/dist diff --git a/docker/README.md b/docker/README.md new file mode 100644 index 0000000..4035245 --- /dev/null +++ b/docker/README.md @@ -0,0 +1,78 @@ +# docker/ — images de la vitrine + +Contient **tout ce qui touche à l'image** : build du front, image nginx, +configuration et script de publication. Ce dépôt ne construit qu'une seule app +(la vitrine) mais trois images, d'où ce dossier dédié plutôt que des `Dockerfile` +à la racine. + +Le fonctionnement du service (compose, ports, healthchecks) est décrit dans +[`../docs/deployment.md`](../docs/deployment.md) ; la sécurité des en-têtes, dans +[`../docs/security.md`](../docs/security.md). + +## Fichiers + +| Fichier | Image / rôle | Utilisé par compose ? | +| --- | --- | --- | +| `Dockerfile` | `nginx:1.27-alpine` + `nginx/web.conf` — le serveur | oui → service `nginx` | +| `Dockerfile.app` | build Vite dans `node:22-alpine`, export `dist/` | oui → service `app-build` | +| `Dockerfile.api` | build de `backend/shared` + API | **non** (reliquat du monorepo) | +| `nginx/web.conf` | serveur : racine `current`, `/healthz`, gzip, caches | copié dans l'image | +| `nginx/snippets/security-headers.conf` | `nosniff`, `X-Frame-Options`, `Referrer-Policy` | inclus partout | +| `nginx/snippets/cache-immutable.conf` | `public, immutable` (assets) | `location /assets/` | +| `nginx/snippets/cache-no-cache.conf` | `no-cache` (`index.html`) | `location /` | +| `publish.sh` | publication atomique dans le volume | monté dans `app-build` | + +`Dockerfile.api` n'est référencé nulle part : `npm run build` le rend obsolète +pour la vitrine. Il n'est conservé que parce que `backend/shared` appartient +toujours au workspace. + +## Images + +```sh +docker compose build # les deux images +docker compose build app-build # seulement le build du front +``` + +### `Dockerfile` (nginx) + +Supprime le `default.conf` par défaut, copie `web.conf` et les snippets, +`EXPOSE 80`. Rien d'autre : pas de module ajouté, pas d'utilisateur dédié. + +### `Dockerfile.app` (front) + +- `ARG APP_DIR` (`frontend/web`, passé par compose). +- Stage `builder` : `npm ci` avec cache npm, puis + `npm run build --workspace=frontend/shared` **puis** + `--workspace=${APP_DIR}` (l'ordre compte : la vitrine importe le design system). +- Stage `export` : recopie uniquement `dist/` dans `/app/dist`, sans les + sources ni `node_modules`. + +### Publication + +Le service `app-build` exécute `sh /publish.sh` avec `app_data` monté : + +1. copie de `dist/` vers `releases/-` ; +2. bascule atomique du lien `current` (`ln -sfn` puis `mv -T`) ; +3. purge des releases autres que la courante, **après 5 minutes**. + +Pendant la copie, nginx sert encore l'ancienne version. Aucun reload nécessaire. + +## Aperçu de la conf nginx + +```nginx +root /usr/share/nginx/html/current; +location = /healthz { return 200 "ok\n"; access_log off; } +location /assets/ { include snippets/cache-immutable.conf; expires 1y; try_files $uri =404; } +location / { include snippets/cache-no-cache.conf; try_files $uri $uri/ @spa; } +location @spa { try_files /index.html =404; } +``` + +Les en-têtes de sécurité sont inclus **au niveau serveur et dans chaque +location** : les réponses d'erreur et de santé sont couvertes aussi. + +## Modifier la configuration + +1. Éditer `nginx/web.conf` ou un snippet. +2. `docker compose build nginx && docker compose up -d nginx` + (ou `make reload` si le fichier est monté — il ne l'est pas : il est copié + dans l'image, donc une reconstruction est obligatoire). diff --git a/docker/nginx/crm.conf b/docker/nginx/crm.conf new file mode 100644 index 0000000..15e7b06 --- /dev/null +++ b/docker/nginx/crm.conf @@ -0,0 +1,55 @@ +server { + listen 80 default_server; + listen [::]:80 default_server; + server_name _; + + root /usr/share/nginx/html/current; + index index.html; + + include /etc/nginx/snippets/security-headers.conf; + + gzip on; + gzip_vary on; + gzip_min_length 1024; + gzip_types text/plain text/css application/javascript application/json image/svg+xml application/manifest+json; + + location = /healthz { + access_log off; + default_type text/plain; + return 200 "ok\n"; + } + + # L'API. Le resolver Docker est declare pour que le conteneur soit resolu + # a la demande : nginx peut demarrer avant l'API, et le front reste servi + # pendant un redemarrage de celle-ci. + location /api/ { + include /etc/nginx/snippets/security-headers.conf; + resolver 127.0.0.11 valid=30s ipv6=off; + set $cohaise_api http://api:8080; + proxy_pass $cohaise_api$request_uri; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_read_timeout 60s; + client_max_body_size 1m; + } + + location /assets/ { + include /etc/nginx/snippets/security-headers.conf; + include /etc/nginx/snippets/cache-immutable.conf; + expires 1y; + try_files $uri =404; + } + + location / { + include /etc/nginx/snippets/security-headers.conf; + include /etc/nginx/snippets/cache-no-cache.conf; + try_files $uri $uri/ @spa; + } + + location @spa { + try_files /index.html =404; + } +} diff --git a/docker/nginx/snippets/cache-immutable.conf b/docker/nginx/snippets/cache-immutable.conf new file mode 100644 index 0000000..4d329e2 --- /dev/null +++ b/docker/nginx/snippets/cache-immutable.conf @@ -0,0 +1 @@ +add_header Cache-Control "public, immutable" always; diff --git a/docker/nginx/snippets/cache-no-cache.conf b/docker/nginx/snippets/cache-no-cache.conf new file mode 100644 index 0000000..0d152e5 --- /dev/null +++ b/docker/nginx/snippets/cache-no-cache.conf @@ -0,0 +1 @@ +add_header Cache-Control "no-cache" always; diff --git a/docker/nginx/snippets/security-headers.conf b/docker/nginx/snippets/security-headers.conf new file mode 100644 index 0000000..447b06a --- /dev/null +++ b/docker/nginx/snippets/security-headers.conf @@ -0,0 +1,3 @@ +add_header X-Content-Type-Options "nosniff" always; +add_header X-Frame-Options "DENY" always; +add_header Referrer-Policy "strict-origin-when-cross-origin" always; diff --git a/docker/nginx/web.conf b/docker/nginx/web.conf new file mode 100644 index 0000000..0e685d7 --- /dev/null +++ b/docker/nginx/web.conf @@ -0,0 +1,38 @@ +server { + listen 80 default_server; + listen [::]:80 default_server; + server_name _; + + root /usr/share/nginx/html/current; + index index.html; + + include /etc/nginx/snippets/security-headers.conf; + + gzip on; + gzip_vary on; + gzip_min_length 1024; + gzip_types text/plain text/css application/javascript application/json image/svg+xml application/manifest+json; + + location = /healthz { + access_log off; + default_type text/plain; + return 200 "ok\n"; + } + + location /assets/ { + include /etc/nginx/snippets/security-headers.conf; + include /etc/nginx/snippets/cache-immutable.conf; + expires 1y; + try_files $uri =404; + } + + location / { + include /etc/nginx/snippets/security-headers.conf; + include /etc/nginx/snippets/cache-no-cache.conf; + try_files $uri $uri/ @spa; + } + + location @spa { + try_files /index.html =404; + } +} diff --git a/docker/publish.sh b/docker/publish.sh new file mode 100644 index 0000000..d6b7af1 --- /dev/null +++ b/docker/publish.sh @@ -0,0 +1,17 @@ +#!/bin/sh +set -eu + +SRC="${1:-/app/dist}" +DEST="${2:-/output}" + +REL="releases/$(date -u +%Y%m%dT%H%M%SZ)-$$" +KEEP=$(basename "$REL") + +mkdir -p "$DEST/$REL" +cp -a "$SRC/." "$DEST/$REL/" +touch "$DEST/$REL" + +ln -sfn "$REL" "$DEST/.current.tmp" +mv -T "$DEST/.current.tmp" "$DEST/current" + +find "$DEST/releases" -mindepth 1 -maxdepth 1 -type d ! -name "$KEEP" -mmin +5 -exec rm -rf {} + 2>/dev/null || true diff --git a/docs/agents.md b/docs/agents.md new file mode 100644 index 0000000..04dc1e5 --- /dev/null +++ b/docs/agents.md @@ -0,0 +1,67 @@ +# Agents — CoHaiSe Web + +Conventions de travail pour un agent (ou un nouveau contributeur) reprenant ce +dépôt seul. Paired avec `README.md` (démarrage rapide) et les autres fichiers +de `docs/`. + +## Commandes + +| Action | Commande | +| --- | --- | +| Dev hot-reload | `make dev` (Vite 5173) | +| Vérifier les types | `npm run typecheck` | +| Builder | `npm run build` | +| Reconstruire + publier | `make web` | +| Santé | `curl -I http://localhost:8080/healthz` | +| Conteneurs | `make ps`, `make logs` | + +Aucun linter, aucun test, aucune CI : `typecheck` + `build` sont les seules +vérifications automatiques. Exécuter les deux avant de déclarer un travail fini. + +## Règles du dépôt + +1. **Ne pas toucher aux volumes** : pas de `docker volume rm`, pas de `docker + compose down -v`. Les volumes ne sont jamais supprimés par les cibles. +2. **Ne pas committer ni pousser** sans demande explicite. +3. **Ne pas lire `.env`** : il contient des secrets d'autres apps. Écrire + `SESSION_SECRET` est autorisé, le recopier depuis un autre dépôt aussi, le + diffuser non. +4. **Ne pas créer de backend** : ce dépôt est une vitrine statique. Toute + fonctionnalité nécessitant une API appartient à `CoHaiSe-CLOUD` ou + `CoHaiSe-CRM`. +5. **`.env.example` n'est pas la vérité** : il contient des clés héritées que le + compose n'utilise pas. Seul `COHAISE_HTTP_PORT` est lu. + +## Conventions de code + +- TypeScript strict, project references (`tsconfig.json` racine). +- React 19, pas de routeur : la navigation est un état dans `App.tsx`. +- Tailwind 4 via `@import "tailwindcss"` ; **pas de classes arbitraires en + dur** : passer par les jetons `--cohaise-*` (`@theme inline`). +- Style visuel : `Button`, `Card`, `cn` depuis `@cohaise/ui`. Pas de + `
` quand un composant existe. +- `.editorconfig` : 2 espaces, LF, UTF-8. + +## Duplication du design system + +`frontend/shared` existe à l'identique dans les trois dépôts CoHaiSe. Avant de +modifier un fichier partagé : + +1. chercher d'abord si le besoin n'est pas déjà couvert par un jeton ; +2. si modification : appliquer dans les **trois** dépôts ; +3. vérifier `md5sum */frontend/shared/src/styles/tokens.css` → trois digests + identiques. + +Ne jamais « améliorer » un composant d'un seul dépôt sans répercuter : les +palettes doivent rester synchronisées. + +## Pièges + +- `cohaise.dev` est HSTS-preloadé : `/etc/hosts` ne sert à rien, tester via + `localhost:8080`. +- `backend/shared` est construit mais inutilisé : une erreur de types ici ne + casse pas le site. +- `docker/README.md` décrit la build d'image uniquement ; pour le service, + `docs/deployment.md`. +- Après `make web`, vérifier que le symlink a bien basculé : + `docker compose exec nginx ls -l /usr/share/nginx/html/current`. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..e0d7dd9 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,90 @@ +# Architecture — CoHaiSe Web + +Vitrine statique. Il n'y a **ni API, ni base de données, ni session** : un bundle +Vite servi par nginx. Tout le reste (build, publication, en-têtes) tient dans +`docker/`. + +## Pile + +| Élément | Version | Où | +| --- | --- | --- | +| React | 19 | `frontend/web` | +| Vite | 8 | `frontend/web/vite.config.ts` | +| Tailwind CSS | 4 (`@tailwindcss/vite`) | `frontend/web/src/styles/index.css` | +| TypeScript | 7 (`typescript` en devDependency racine) | `tsconfig.json` (project references) | + +`package.json` racine : `workspaces: ["frontend/*", "backend/*"]`, scripts +`build` (`tsc --build` puis build de chaque paquet), `typecheck`, `clean`. + +## Découpage + +``` +frontend/ + shared/ @cohaise/ui — design system, DUPLOQUÉ dans les 3 dépôts CoHaiSe + web/ @cohaise/web — la vitrine +backend/ + shared/ @cohaise/server — couche serveur, PRÉSENTE mais INUTILISÉE ici +docker/ Dockerfile, Dockerfile.app, nginx/, publish.sh +``` + +`backend/shared` est référencé par `tsconfig.json` racine et donc **construit** +par `npm run build`, mais aucun paquet ne l'importe et `docker-compose.yml` ne +construit pas `Dockerfile.api`. C'est un reliquat du monorepo à trois apps : +inoffensif, mais inutile dans ce dépôt. + +## Chaîne de build + +Deux images, deux rôles : + +1. **`docker/Dockerfile.app`** (`target: export`) — stage `builder` `node:22-alpine` : + `npm ci`, puis `npm run build --workspace=frontend/shared` et + `--workspace=${APP_DIR}` (`APP_DIR: frontend/web` passé par compose). Stage + `export` `alpine:3.21` : recopie `dist/` dans `/app/dist`. +2. **`docker/publish.sh`** — tourne dans le conteneur `app-build` avec le volume + `app_data` monté : copie dans `releases/-`, puis bascule atomique du + lien `current` (`ln -sfn` + `mv -T`). La version précédente reste servie + pendant la copie ; une release plus vieille que 5 minutes est purgée. + +Publication **atomique** : nginx ne voit jamais un répertoire à moitié écrit. + +## Service de rendu + +`docker/Dockerfile` : `nginx:1.27-alpine` + `docker/nginx/web.conf`. + +| Point | Comportement | Référence | +| --- | --- | --- | +| Racine | `/usr/share/nginx/html/current` (symlink) | `nginx/web.conf:6` | +| `/healthz` | `200 ok`, log coupé | `web.conf:16-20` | +| `/assets/` | `expires 1y`, `Cache-Control: public, immutable` | `cache-immutable.conf` | +| Racine applicative | `no-cache`, fallback SPA `try_files → @spa → /index.html` | `web.conf:29-37` | +| gzip | actif, `min_length 1024` | `web.conf:11-14` | +| En-têtes | `snippets/security-headers.conf` au niveau serveur **et** dans chaque `location` | `web.conf:9,23,30` | + +## Front + +- **Pas de routeur** : deux onglets commutés par `useState` (`src/App.tsx:25-29`). +- **Pas de code splitting** : `main.tsx` importe `App` en statique, aucun + `React.lazy`. +- **Thème clair/sombre** : script inline dans `index.html` (anti-FOUC) lit + `localStorage["cohaise-theme"]`, sinon `prefers-color-scheme`, puis pose la + classe `.dark` sur ``. Le basculeur écrit via `useTheme`. +- **Design system** : `Button`, `Card`, `cn` sont les seuls composants utilisés. + `Input` est un `` brut, `DemoCard` (seul utilisateur de `Skeleton`) n'est + jamais monté. +- **Aucun appel réseau** : pas de `fetch`, `axios`, `WebSocket`, ni + `import.meta.env`. Fonts (woff2) et favicon en local, aucune ressource tierce. + +## Jetons + +`frontend/shared/src/styles/tokens.css` est la source des couleurs ; Tailwind 4 +les reçoit par `@theme inline` (`theme.css`). L'application lit le fichier via : + +```css +@import "tailwindcss"; +@import "@cohaise/ui/styles"; +@source "../../../../frontend/shared/src"; +``` + +`--cohaise-destructive` est un rouge (`#d32f2f` clair / `#ef4444` sombre), +l'accent de marque est le carmin `--cohaise-accent` (`#b71c1c`), l'avertissement +reste jaune (`--cohaise-warning`). Voir `standards.md`. diff --git a/docs/crm-api.md b/docs/crm-api.md new file mode 100644 index 0000000..3bac224 --- /dev/null +++ b/docs/crm-api.md @@ -0,0 +1,86 @@ +# API et modèle de données — CoHaiSe CRM + +Base : **`/api/crm`**, plus `GET /healthz` (sonde base, `503` si indisponible). +`attachUser` sur les quatre préfixes ; `requireAuth` sur chaque route sauf la +connexion. **Aucune route n'est protégée par un rôle** depuis `007_no_roles.sql`. + +## Routes + +| Méthode | Chemin | Fichier | +| --- | --- | --- | +| POST | `/api/crm/auth/login` | `routes/auth.ts:64` | +| POST | `/api/crm/auth/logout` | `routes/auth.ts:98` | +| GET | `/api/crm/auth/me` | `routes/auth.ts:105` | +| POST | `/api/crm/auth/change-password` | `routes/auth.ts:114` | +| GET | `/api/crm/countries?q=` | `routes/countries.ts:46` | +| POST | `/api/crm/countries` | `routes/countries.ts:57` | +| PATCH | `/api/crm/countries/:id` | `routes/countries.ts:88` | +| DELETE | `/api/crm/countries/:id` | `routes/countries.ts:132` | +| GET | `/api/crm/organizations?q&page&limit` | `routes/organizations.ts:105` | +| GET | `/api/crm/organizations/:id` | `routes/organizations.ts:135` | +| POST | `/api/crm/organizations` | `routes/organizations.ts:146` | +| PATCH | `/api/crm/organizations/:id` | `routes/organizations.ts:200` | +| DELETE | `/api/crm/organizations/:id` | `routes/organizations.ts:262` | +| GET | `/api/crm/contacts?q&organizationId&page&limit` | `routes/contacts.ts:96` | +| GET | `/api/crm/contacts/:id` | `routes/contacts.ts:140` | +| POST | `/api/crm/contacts` | `routes/contacts.ts:151` | +| PATCH | `/api/crm/contacts/:id` | `routes/contacts.ts:202` | +| DELETE | `/api/crm/contacts/:id` | `routes/contacts.ts:260` | + +### Conventions communes + +- Corps validés par Zod (`createX`/`updateX`, `credentials`, `changePassword`). +- `:id` UUID validé par regex ⇒ **404** sinon (pays : entier `> 0` sinon 404). +- Pagination : `limit` borné `1..100`, défaut 25 ; `q` fait une recherche + texte. +- Unicité violée (`1062`), FK référencée (`1451`/`1452`) ⇒ **409**. +- Suppression : `DELETE FROM countries` en dur ; + `organizations` et `contacts` passent à `deleted_at = NOW()` et disparaissent + des listes (`WHERE deleted_at IS NULL`). +- Réponse d'erreur : + +```json +{ "error": { "status": 404, "code": "NOT_FOUND", "message": "…", "requestId": "…" } } +``` + +## Modèle de données + +`backend/crm/migrations/` — 8 fichiers, application stricte dans l'ordre, +checksum SHA-256 par fichier. + +| Fichier | Contenu | +| --- | --- | +| `000_schema_migrations.sql` | table de suivi (`version`, `applied_at`, `checksum`) | +| `001_initial_schema.sql` | 15 tables : `roles, users, password_reset_tokens, countries, tags, organizations, contacts, contact_tags, pipeline_stages, deals, deal_stage_history, activities, tasks, settings, audit_logs` — 30 FK, 7 `CHECK` | +| `002_reference_data.sql` | seeds : 3 rôles, 7 étapes de pipeline, **19 pays**, 4 réglages, 5 tags | +| `003_integrity_backstop.sql` | FK `users.role_id` (`RESTRICT`) + 6 `CHECK` de longueur | +| `004_audit_precision.sql` | `DATETIME(3)` sur les journaux d'audit, l'historique de pipeline, deals, activités, tâches, `last_login_at` | +| `005_user_sessions.sql` | table `user_sessions` (`token_hash CHAR(64)`, FK `CASCADE`) ; purge confiée au service | +| `006_active_identity.sql` | colonnes générées `contacts.active_email`, `organizations.active_name` (`IF(deleted_at IS NULL, …, NULL) STORED`) + index uniques dédiés | +| `007_no_roles.sql` | **suppression des rôles** : `DROP FOREIGN KEY fk_users_role`, `DROP COLUMN role_id`, `DROP TABLE roles` | + +> `007` laisse `002` (seeds de rôles) et `003` (FK réintroduite) intacts : ces +> fichiers ne se re-modifient jamais, une migration appliquée est figée. + +### Entités exposées + +| Table | Identifiant | Remarques | +| --- | --- | --- | +| `users` | `CHAR(36)` UUID | `first_name`, `last_name`, `must_change_password`, `is_active`, soft delete | +| `organizations` | UUID | FK `countries` (`SET NULL`), `owner_id`, `created_by` | +| `contacts` | UUID | FK `organizations` (`SET NULL`), pays, `owner_id` | +| `countries` | `INT UNSIGNED` | suppression physique | +| `user_sessions` | — | `token_hash`, `expires_at`, `revoked_at` | + +Hors API : `deals`, `activities`, `tasks`, `tags`, `contact_tags`, +`pipeline_stages`, `settings`, `password_reset_tokens`, `audit_logs`. + +## Dérive de migrations + +`runMigrations()` ne joue que les versions absentes et enregistre le SHA-256 du +SQL ; `assertNoDrift()` refuse le démarrage si un fichier déjà appliqué a changé. +CLI : `cohaise-migrate --dir [--dry-run] [--check]`, codes `0` / `1` +(erreur ou dérive) / `2` (configuration). + +Le DDL MariaDB n'est pas transactionnel : une migration interrompue se corrige +par un **nouveau** fichier, jamais en éditant l'ancien. diff --git a/docs/deployment.md b/docs/deployment.md new file mode 100644 index 0000000..b9fafd7 --- /dev/null +++ b/docs/deployment.md @@ -0,0 +1,90 @@ +# Déploiement — CoHaiSe Web + +## Prérequis + +Docker avec le plugin Compose, `make`. Rien d'autre : la vitrine n'a besoin +d'aucun secret, d'aucune base, d'aucun compte. + +```sh +cp .env.example .env # optionnel +make up # build + démarrage sur 8080 +``` + +## Compose + +`docker-compose.yml` — projet **`cohaise-web`**, deux services, un volume : + +| Service | Image | Port | Rôle | +| --- | --- | --- | --- | +| `app-build` | `docker/Dockerfile.app` | — | build Vite, `restart: "no"` | +| `nginx` | `docker/Dockerfile` | `${COHAISE_HTTP_PORT:-8080}:80` | rendu, `restart: unless-stopped` | + +Volume unique : `app_data` (`/usr/share/nginx/html`), monté par les deux. Aucun +`depends_on` : le lien est le partage du volume. `app-build` publie puis +s'arrête ; nginx n'a jamais à redémarrer. + +Healthcheck nginx : `wget -qO- http://127.0.0.1/healthz`, 10 s d'intervalle, +3 s de timeout, 3 essais. + +## Variables + +Seule variable consommée : `COHAISE_HTTP_PORT` (défaut `8080`), lue par la +substitution Compose — il n'y a pas de `env_file`. + +Le `.env.example` contient encore les clés des anciennes apps (CRM, Cloud, +`SESSION_SECRET`…) : **inutiles ici**, la stack n'en lit aucune. Ne pas les +supprimer sans vérifier qu'aucune autre cible ne les référence. + +## Commandes + +```sh +make help # liste complète +make up # build + démarrage +make web # reconstruire et republier la vitrine (sans interruption) +make reload # nginx -s reload, sans coupure +make build # construire les images sans redémarrer +make ps # état +make logs # journaux suivis +make dev # Vite local sur 5173 (hors Docker) +make down # arrêt, volumes conservés +``` + +`make help` affiche aussi `npm run typecheck` / `npm run build` sous +« Vérification » : aucune cible Makefile ne les exécute, ce sont des commandes +npm à taper directement. + +## Vérification + +```sh +curl -I http://localhost:8080/healthz # HTTP/1.1 200 ok +curl -s http://localhost:8080/ | head # index.html servi par le symlink current +``` + +## Publication d'une version + +```sh +make web +``` + +1. `app-build` reconstruit l'image et exécute `publish.sh` ; +2. la nouvelle copie est écrite dans `releases/` ; +3. le lien `current` bascule par `mv -T` (atomique) ; +4. nginx sert immédiatement la nouvelle version, sans reload. + +En cas de régression, l'ancienne release existe encore quelques minutes : on peut +re-basculer le lien manuellement dans le conteneur avant la purge automatique. + +## Exposition publique + +Le port est publié **sans bind IP** (`0.0.0.0:8080`). L'exposition sur Internet +passe par le tunnel cloudflared, qui vit dans un conteneur **hors de ce dépôt** : +ne rien y changer depuis ici. Le `.dev` est HSTS-preload, donc `/etc/hosts` ne +sert jamais à tester `cohaise.dev` en local — utiliser `localhost:8080`. + +## Arrêt + +```sh +make down # conteneurs + réseau, volume app_data conservé +``` + +Les volumes ne sont jamais supprimés par les cibles du Makefile. diff --git a/docs/security.md b/docs/security.md new file mode 100644 index 0000000..2e2ceb8 --- /dev/null +++ b/docs/security.md @@ -0,0 +1,66 @@ +# Sécurité — CoHaiSe Web + +Surface minimale : une application statique, sans comptes, sans cookies, sans +données. Ce document recense ce qui **est** protégé et ce qui **ne l'est pas**, +pour éviter de partir d'hypothèses fausses. + +## Ce qui est en place + +### En-têtes nginx + +`docker/nginx/snippets/security-headers.conf` : + +```nginx +X-Content-Type-Options: nosniff +X-Frame-Options: DENY +Referrer-Policy: strict-origin-when-cross-origin +``` + +Le snippet est inclus au niveau `server` **et** dans chaque `location` (fichiers +`assets`, `/`, `/healthz`) : les réponses d'erreur et de santé portent les mêmes +en-têtes que la page. + +### Aucune donnée sensible + +- Aucun appel réseau côté client (vérifié : pas de `fetch`, `XMLHttpRequest`, + `axios`, `WebSocket`). +- Aucune clé, aucun `import.meta.env` dans `frontend/`. +- `.env` exclu de git (`.gitignore`) et des images (`.dockerignore`). +- Seul stockage navigateur : `localStorage["cohaise-theme"]`. +- Aucun cookie : le design system ne pose pas de cookie, `backend/shared` n'est + pas déployé. + +### Ressources + +Fonts woff2 et favicon hébergées localement — aucune requête vers un tiers, +donc aucun en-tête `Referrer-Policy` à négocier avec un CDN et aucun +`connect-src` à ouvrir. + +## Ce qui n'est pas en place + +| Élément | État | Conséquence | +| --- | --- | --- | +| CSP | **absente** | une injection dans un fichier HTML servi briserait la règle du moins cher possible ; le site n'a aucun script tiers, ajouter une CSP stricte est peu coûteux | +| HSTS | absent | le `.dev` est HSTS-preloadé par le navigateur, donc le trafic est déjà forcé en HTTPS : l'absence d'en-tête ici ne change rien côté navigateur, mais un autre domaine servirait en clair | +| `Permissions-Policy` | absent | caméra/micro/geolocalisation jamais sollicités | +| Bind `127.0.0.1` | non | le port `8080` est publié sur toutes les interfaces ; seul le tunnel définit l'accès réel. Pour un hébergement partagé, restreindre à `127.0.0.1:${COHAISE_HTTP_PORT}:80` dans `docker-compose.yml` | +| Rate limiting | non pertinent | aucun endpoint dynamique | +| TLS | hors du dépôt | nginx n'écoute que le `80`, le terminus HTTPS est le tunnel | + +## Chaîne de confiance + +``` +tunnel cloudflared → nginx:8080 → /usr/share/nginx/html/current → releases/ +``` + +- `current` est un lien créé par `publish.sh` : un contenu publié ne peut pas + être modifié à l'écriture, seulement remplacé de façon atomique. +- nginx tourne en `nginx:1.27-alpine` sans module tiers ajouté. +- Le conteneur n'a pas de droits particuliers déclarés, pas de `cap_add`. + +## À ne pas faire + +- Ne pas brancher de clé ou de token dans le front : ce dépôt n'a pas de back. +- Ne pas ajouter de ressource externe (font CDN, script analytics) sans réviser + les en-têtes et `index.html`. +- Ne pas publier `.env` : il contient des clés héritées d'autres apps. diff --git a/docs/standards.md b/docs/standards.md new file mode 100644 index 0000000..d208149 --- /dev/null +++ b/docs/standards.md @@ -0,0 +1,87 @@ +# Standards — CoHaiSe Web + +Conventions à respecter pour que ce dépôt reste cohérent avec les deux autres +(`CoHaiSe-CLOUD`, `CoHaiSe-CRM`), qui partagent le même design system. + +## Formatage + +`.editorconfig` fait foi : + +| Réglage | Valeur | +| --- | --- | +| Charset | UTF-8, fin de ligne LF | +| Indentation | 2 espaces (pas de tabs) | +| `trim_trailing_whitespace` | `false` pour `*.md`, vrai ailleurs | + +Aucun Prettier/ESLint n'est installé : l'éditeur et l'`.editorconfig` sont la +seule norme mécanique. + +## Palette + +Source unique : `frontend/shared/src/styles/tokens.css`. + +| Jeton | Rôle | Valeur | +| --- | --- | --- | +| `--cohaise-accent` | accent de marque (liens, focus, éléments primaires) | carmin `#b71c1c` (`crimson-700`) | +| `--cohaise-destructive` | suppression, erreurs, champs invalides | `#d32f2f` clair / `#ef4444` sombre | +| `--cohaise-destructive-foreground` | texte posé dessus | `#ffffff` clair / `#1a0505` sombre | +| `--cohaise-warning` | avertissement, badges d'état | jaune `yellow-500` | +| `--cohaise-surface`, `--cohaise-background` | fonds | gris chaud `#f7f5f4` / `#050000` | + +Règles : + +- **L'orange n'existe plus** : `--cohaise-amber-*` a été retiré. Ne pas le + réintroduire — le rouge a remplacé l'ambre sur le bouton destructif pour des + raisons de contraste (≥4.5:1 en clair comme en sombre). +- Ne pas dériver la palette dans un seul dépôt : `tokens.css` doit rester + identique partout. +- Toute nouvelle couleur doit être lisible **comme texte** sur le fond + d'application ET comme fond avec un texte posé dessus. Vérifier les deux cas. + +## Typographies + +Chargées en local (`frontend/shared/fonts/*.woff2`), jamais par CDN : + +| Usage | Police | +| --- | --- | +| Texte courant | Poppins 400/600 | +| Titres display | Orbitron, Cinzel | +| Code / monospace | JetBrains Mono | + +## Composants + +`@cohaise/ui` expose `Button`, `Card` (+ sous-composants), `Input`, `Skeleton`, +`Spinner` et l'utilitaire `cn`. + +- Un composant partagé ne doit pas connaître le métier d'une app. +- Une variante visuelle propre à une app se développe **dans cette app**, pas + dans `frontend/shared`. +- `Skeleton` et `Spinner` sont prévus pour les états de chargement ; ne pas + réinventer un spinner. + +## Thème + +- Bascule clair/sombre par la classe `.dark` sur ``. +- Script inline dans `index.html` (avant le bundle) : lit + `localStorage["cohaise-theme"]`, sinon `prefers-color-scheme`. C'est lui qui + évite le flash de thème. +- `color-scheme: light dark` déclaré pour les contrôles natifs. +- Toute règle sombre va dans le bloc `.dark` de `tokens.css`, pas en + `@media (prefers-color-scheme: dark)` : la préférence utilisateur prime. + +## Git + +- Branche `main` unique, remote `origin` sur `git.cohaise.dev`. +- Pas de convention de message imposée par l'historique (dépôt neuf). +- N'exclure de git que : `.env*` (sauf `.env.example`), `node_modules/`, + `dist/`, `*.log`, `backups/`. +- `docs/` est **versionné** (la ligne `docs/` de `.gitignore` a été retirée). + +## Interdépôts + +| Élément | Attendu | +| --- | --- | +| `frontend/shared/src/styles/tokens.css` | identique (même `md5sum`) | +| Composants `@cohaise/ui` | dupliqués, **peuvent diverger** | +| Ports | web `8080`, CRM `8082`, Cloud `8083` | +| Remotes | un dépôt Git autonome par app, aucun lien de code entre eux | diff --git a/docs/workflow.md b/docs/workflow.md new file mode 100644 index 0000000..526ec6a --- /dev/null +++ b/docs/workflow.md @@ -0,0 +1,78 @@ +# Workflow — CoHaiSe Web + +## Boucle de développement + +```sh +make dev # Vite sur http://localhost:5173, hot reload +``` + +Le serveur de dev sert `frontend/web` avec `server.host: true`, port `5173` +(`vite.config.ts`). Il n'a pas besoin de Docker ni de `.env`. + +## Vérification avant de valider + +```sh +npm run typecheck # tsc --build sur toutes les références +npm run build # typecheck + build de chaque workspace +curl -I http://localhost:8080/healthz +``` + +Il n'y a **ni linter, ni testeur, ni CI** dans ce dépôt : `typecheck` et `build` +sont les seules garanties automatiques. `.editorconfig` porte les conventions +(2 espaces, LF, UTF-8 ; pas de `trim_trailing_whitespace` pour les `.md`). + +## Reconstruire le site publié + +```sh +make web # build + publication atomique +make reload # uniquement si nginx/web.conf a changé +``` + +`make web` ne coupe jamais le service : la copie se fait à côté, le lien +bascule ensuite. + +## Modifier le design system + +Point le plus important : **`frontend/shared` est dupliqué dans les trois +dépôts CoHaiSe.** Il n'y a pas de version centrale. + +- Un correctif de `Button`, `Card`, `Input`, `Skeleton`, `Spinner` ou `cn` + doit être répliqué à la main dans : + - `CoHaiSe/frontend/shared` + - `CoHaiSe-CLOUD/frontend/shared` + - `CoHaiSe-CRM/frontend/shared` +- `tokens.css` doit rester **strictement identique** dans les trois + (comparer par `md5sum`). Les composants, eux, peuvent diverger : chaque app + les redéfinit à sa main. +- Après modification : `npm run build --workspace=frontend/shared`, puis + `make web` pour republier. + +## Où changer quoi + +| Besoin | Fichier | +| --- | --- | +| Couleur, rayon, police, ombre | `frontend/shared/src/styles/tokens.css` | +| Composant partagé | `frontend/shared/src/components/*.tsx` | +| Page, layout, contenu | `frontend/web/src/**` | +| Routage (onglets) | `frontend/web/src/App.tsx` | +| Cache, en-têtes, fallback SPA | `docker/nginx/web.conf` + `docker/nginx/snippets/` | +| Port public | `COHAISE_HTTP_PORT` dans `.env` | +| Thème par défaut | script inline de `frontend/web/index.html` | + +## Git + +- Branche `main`, remote `origin https://git.cohaise.dev/Esiah/CoHaiSe.git`. +- Historique vierge (un commit initial) : aucune convention de message héritée. +- Pas de hooks, pas de CI (`.github/`, `.gitlab-ci.yml` absents). +- Ne jamais committer `.env`, `node_modules/`, `dist/` (exclus par `.gitignore`). + +## Pièges connus + +1. **`.dev` en HSTS-preload** : `/etc/hosts` ne fera jamais fonctionner + `cohaise.dev` en local. Tester sur `localhost`. +2. **`backend/shared` est construit mais jamais utilisé** : une erreur de types + venant de là n'affecte pas le site, mais bloque `npm run typecheck`. +3. **`docker/README.md` historique** : ne sert que les images ; le + fonctionnement réel est dans `docs/deployment.md`. +4. **Aucun code splitting** : tout le site tient dans un seul bundle, ce qui est + volontaire pour une vitrine. diff --git a/frontend/crm/index.html b/frontend/crm/index.html new file mode 100644 index 0000000..5136fa6 --- /dev/null +++ b/frontend/crm/index.html @@ -0,0 +1,24 @@ + + + + + + + CoHaiSe CRM + + + + +
+ + + diff --git a/frontend/crm/package.json b/frontend/crm/package.json new file mode 100644 index 0000000..947650a --- /dev/null +++ b/frontend/crm/package.json @@ -0,0 +1,28 @@ +{ + "name": "@cohaise/crm-web", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc --noEmit && vite build", + "typecheck": "tsc --noEmit", + "preview": "vite preview" + }, + "dependencies": { + "@cohaise/ui": "*", + "react": "^19.3.0", + "react-dom": "^19.3.0", + "three": "^0.187.0" + }, + "devDependencies": { + "@tailwindcss/vite": "^4.3.3", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "@types/three": "^0.187.0", + "@vitejs/plugin-react": "^6.1.1", + "tailwindcss": "^4.3.3", + "typescript": "^7.0.2", + "vite": "^8.3.1" + } +} diff --git a/frontend/crm/public/favicon.webp b/frontend/crm/public/favicon.webp new file mode 100644 index 0000000..d99b850 Binary files /dev/null and b/frontend/crm/public/favicon.webp differ diff --git a/frontend/crm/public/icons/accounts.webp b/frontend/crm/public/icons/accounts.webp new file mode 100644 index 0000000..7270252 Binary files /dev/null and b/frontend/crm/public/icons/accounts.webp differ diff --git a/frontend/crm/public/icons/activity.webp b/frontend/crm/public/icons/activity.webp new file mode 100644 index 0000000..fcb6960 Binary files /dev/null and b/frontend/crm/public/icons/activity.webp differ diff --git a/frontend/crm/public/icons/back.webp b/frontend/crm/public/icons/back.webp new file mode 100644 index 0000000..f199a3b Binary files /dev/null and b/frontend/crm/public/icons/back.webp differ diff --git a/frontend/crm/public/icons/clear.webp b/frontend/crm/public/icons/clear.webp new file mode 100644 index 0000000..a77c969 Binary files /dev/null and b/frontend/crm/public/icons/clear.webp differ diff --git a/frontend/crm/public/icons/close.webp b/frontend/crm/public/icons/close.webp new file mode 100644 index 0000000..06b4839 Binary files /dev/null and b/frontend/crm/public/icons/close.webp differ diff --git a/frontend/crm/public/icons/deactivate.webp b/frontend/crm/public/icons/deactivate.webp new file mode 100644 index 0000000..2c09bbe Binary files /dev/null and b/frontend/crm/public/icons/deactivate.webp differ diff --git a/frontend/crm/public/icons/document.webp b/frontend/crm/public/icons/document.webp new file mode 100644 index 0000000..04f1c2b Binary files /dev/null and b/frontend/crm/public/icons/document.webp differ diff --git a/frontend/crm/public/icons/download.webp b/frontend/crm/public/icons/download.webp new file mode 100644 index 0000000..102dda2 Binary files /dev/null and b/frontend/crm/public/icons/download.webp differ diff --git a/frontend/crm/public/icons/edit-pencil.webp b/frontend/crm/public/icons/edit-pencil.webp new file mode 100644 index 0000000..7c1c32c Binary files /dev/null and b/frontend/crm/public/icons/edit-pencil.webp differ diff --git a/frontend/crm/public/icons/favorite.webp b/frontend/crm/public/icons/favorite.webp new file mode 100644 index 0000000..6541d36 Binary files /dev/null and b/frontend/crm/public/icons/favorite.webp differ diff --git a/frontend/crm/public/icons/file.webp b/frontend/crm/public/icons/file.webp new file mode 100644 index 0000000..af4aabc Binary files /dev/null and b/frontend/crm/public/icons/file.webp differ diff --git a/frontend/crm/public/icons/filter.webp b/frontend/crm/public/icons/filter.webp new file mode 100644 index 0000000..16df815 Binary files /dev/null and b/frontend/crm/public/icons/filter.webp differ diff --git a/frontend/crm/public/icons/folder.webp b/frontend/crm/public/icons/folder.webp new file mode 100644 index 0000000..6fd8a92 Binary files /dev/null and b/frontend/crm/public/icons/folder.webp differ diff --git a/frontend/crm/public/icons/image-file.webp b/frontend/crm/public/icons/image-file.webp new file mode 100644 index 0000000..c160507 Binary files /dev/null and b/frontend/crm/public/icons/image-file.webp differ diff --git a/frontend/crm/public/icons/menu.webp b/frontend/crm/public/icons/menu.webp new file mode 100644 index 0000000..b4fdcca Binary files /dev/null and b/frontend/crm/public/icons/menu.webp differ diff --git a/frontend/crm/public/icons/move.webp b/frontend/crm/public/icons/move.webp new file mode 100644 index 0000000..6880a7f Binary files /dev/null and b/frontend/crm/public/icons/move.webp differ diff --git a/frontend/crm/public/icons/opened-folder.webp b/frontend/crm/public/icons/opened-folder.webp new file mode 100644 index 0000000..b1d0c58 Binary files /dev/null and b/frontend/crm/public/icons/opened-folder.webp differ diff --git a/frontend/crm/public/icons/password-reset.webp b/frontend/crm/public/icons/password-reset.webp new file mode 100644 index 0000000..4c92e13 Binary files /dev/null and b/frontend/crm/public/icons/password-reset.webp differ diff --git a/frontend/crm/public/icons/personal-settings.webp b/frontend/crm/public/icons/personal-settings.webp new file mode 100644 index 0000000..968b3d9 Binary files /dev/null and b/frontend/crm/public/icons/personal-settings.webp differ diff --git a/frontend/crm/public/icons/picture.webp b/frontend/crm/public/icons/picture.webp new file mode 100644 index 0000000..f17a383 Binary files /dev/null and b/frontend/crm/public/icons/picture.webp differ diff --git a/frontend/crm/public/icons/pin.webp b/frontend/crm/public/icons/pin.webp new file mode 100644 index 0000000..ec4404a Binary files /dev/null and b/frontend/crm/public/icons/pin.webp differ diff --git a/frontend/crm/public/icons/plus.webp b/frontend/crm/public/icons/plus.webp new file mode 100644 index 0000000..0e1a538 Binary files /dev/null and b/frontend/crm/public/icons/plus.webp differ diff --git a/frontend/crm/public/icons/restore-data.webp b/frontend/crm/public/icons/restore-data.webp new file mode 100644 index 0000000..395af04 Binary files /dev/null and b/frontend/crm/public/icons/restore-data.webp differ diff --git a/frontend/crm/public/icons/save.webp b/frontend/crm/public/icons/save.webp new file mode 100644 index 0000000..456d201 Binary files /dev/null and b/frontend/crm/public/icons/save.webp differ diff --git a/frontend/crm/public/icons/search.webp b/frontend/crm/public/icons/search.webp new file mode 100644 index 0000000..41f4d53 Binary files /dev/null and b/frontend/crm/public/icons/search.webp differ diff --git a/frontend/crm/public/icons/send.webp b/frontend/crm/public/icons/send.webp new file mode 100644 index 0000000..daded17 Binary files /dev/null and b/frontend/crm/public/icons/send.webp differ diff --git a/frontend/crm/public/icons/share.webp b/frontend/crm/public/icons/share.webp new file mode 100644 index 0000000..4af3faf Binary files /dev/null and b/frontend/crm/public/icons/share.webp differ diff --git a/frontend/crm/public/icons/sign-out.webp b/frontend/crm/public/icons/sign-out.webp new file mode 100644 index 0000000..593026a Binary files /dev/null and b/frontend/crm/public/icons/sign-out.webp differ diff --git a/frontend/crm/public/icons/speech-bubble.webp b/frontend/crm/public/icons/speech-bubble.webp new file mode 100644 index 0000000..0ff122f Binary files /dev/null and b/frontend/crm/public/icons/speech-bubble.webp differ diff --git a/frontend/crm/public/icons/storage.webp b/frontend/crm/public/icons/storage.webp new file mode 100644 index 0000000..2366fd5 Binary files /dev/null and b/frontend/crm/public/icons/storage.webp differ diff --git a/frontend/crm/public/icons/synchronize.webp b/frontend/crm/public/icons/synchronize.webp new file mode 100644 index 0000000..c21724e Binary files /dev/null and b/frontend/crm/public/icons/synchronize.webp differ diff --git a/frontend/crm/public/icons/trash-can.webp b/frontend/crm/public/icons/trash-can.webp new file mode 100644 index 0000000..8f2853c Binary files /dev/null and b/frontend/crm/public/icons/trash-can.webp differ diff --git a/frontend/crm/public/icons/trash-empty.webp b/frontend/crm/public/icons/trash-empty.webp new file mode 100644 index 0000000..79c5ca8 Binary files /dev/null and b/frontend/crm/public/icons/trash-empty.webp differ diff --git a/frontend/crm/public/icons/upload.webp b/frontend/crm/public/icons/upload.webp new file mode 100644 index 0000000..9e8a04a Binary files /dev/null and b/frontend/crm/public/icons/upload.webp differ diff --git a/frontend/crm/public/images/cohaise.webp b/frontend/crm/public/images/cohaise.webp new file mode 100644 index 0000000..d99b850 Binary files /dev/null and b/frontend/crm/public/images/cohaise.webp differ diff --git a/frontend/crm/src/App.tsx b/frontend/crm/src/App.tsx new file mode 100644 index 0000000..10e7876 --- /dev/null +++ b/frontend/crm/src/App.tsx @@ -0,0 +1,59 @@ +import { useCallback, useEffect, useState } from "react"; +import { Spinner } from "@cohaise/ui"; +import { ApiError, api, type User } from "./lib/api.js"; +import { Login } from "./pages/Login.js"; +import { ChangePassword } from "./pages/ChangePassword.js"; +import { Crm } from "./pages/Crm.js"; + +type Session = + | { state: "loading" } + | { state: "guest" } + | { state: "ready"; user: User }; + +export const App = () => { + const [session, setSession] = useState({ state: "loading" }); + + const refresh = useCallback(async () => { + try { + const { user } = await api.me(); + setSession({ state: "ready", user }); + } catch (error) { + // 401 = simplement deconnecte, ce n'est pas une panne. + if (error instanceof ApiError && error.status === 401) setSession({ state: "guest" }); + else setSession({ state: "guest" }); + } + }, []); + + useEffect(() => { + void refresh(); + }, [refresh]); + + const logout = useCallback(async () => { + await api.logout().catch(() => undefined); + setSession({ state: "guest" }); + }, []); + + if (session.state === "loading") { + return ( +
+ +
+ ); + } + + if (session.state === "guest") { + return setSession({ state: "ready", user })} />; + } + + if (session.user.must_change_password) { + return ( + void logout()} + /> + ); + } + + return void logout()} />; +}; diff --git a/frontend/crm/src/components/FaultyTerminal.tsx b/frontend/crm/src/components/FaultyTerminal.tsx new file mode 100644 index 0000000..143bc1b --- /dev/null +++ b/frontend/crm/src/components/FaultyTerminal.tsx @@ -0,0 +1,870 @@ +// @ts-nocheck +// Rendu WebGL2 « terminal » (grille de glyphes, scanlines, glitch). Porté tel +// quel, volontairement non typé (code shader dense). +import { useEffect, useRef } from 'react'; + +const INTRO_SECONDS = 2; +const MAX_CLICKS = 4; +const CLICK_SECONDS = { glitch: 0.7, degauss: 1.6 }; +const GLYPHS = { blocks: 0, dots: 1, characters: 2 }; +const CLICKS = { none: 0, glitch: 1, degauss: 2 }; + +const FONT = [ + ['.###.', '#..##', '#.#.#', '##..#', '.###.'], + ['..#..', '.##..', '..#..', '..#..', '.###.'], + ['####.', '....#', '.###.', '#....', '#####'], + ['####.', '....#', '.###.', '....#', '####.'], + ['#..#.', '#..#.', '#####', '...#.', '...#.'], + ['#####', '#....', '####.', '....#', '####.'], + ['.###.', '#....', '####.', '#...#', '.###.'], + ['#####', '....#', '...#.', '..#..', '..#..'], + ['.###.', '#...#', '.###.', '#...#', '.###.'], + ['.###.', '#...#', '.####', '....#', '.###.'], + ['.###.', '#...#', '#####', '#...#', '#...#'], + ['####.', '#...#', '####.', '#...#', '####.'], + ['.####', '#....', '#....', '#....', '.####'], + ['####.', '#...#', '#...#', '#...#', '####.'], + ['#####', '#....', '####.', '#....', '#####'], + ['#####', '#....', '####.', '#....', '#....'], + ['.....', '..#..', '.###.', '..#..', '.....'], + ['.....', '.....', '.###.', '.....', '.....'], + ['.#...', '..#..', '...#.', '..#..', '.#...'], + ['....#', '...#.', '..#..', '.#...', '#....'], + ['.....', '#.#.#', '.###.', '#.#.#', '.....'], + ['.....', '#####', '.....', '#####', '.....'], + ['.....', '.....', '.....', '.....', '#####'] +]; + +const FONT_BITS = FONT.map(rows => + rows.reduce((bits, row, r) => { + let value = bits; + for (let c = 0; c < 5; c++) if (row[c] === '#') value += 2 ** (r * 5 + c); + return value; + }, 0) +); + +const VERTEX = `#version 300 es +void main() { + vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2)); + gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0); +}`; + +const PATTERN = ` +float time; + +float noise(vec2 p) { + return sin(p.x * 10.0) * sin(p.y * (3.0 + sin(time * 0.090909))) + 0.2; +} + +mat2 rotate(float angle) { + float c = cos(angle); + float s = sin(angle); + return mat2(c, -s, s, c); +} + +float fbm(vec2 p) { + p *= 1.1; + float f = 0.0; + float amp = 0.5 * uNoiseAmp; + mat2 modify0 = rotate(time * 0.02); + f += amp * noise(p); + p = modify0 * p * 2.0; + amp *= 0.454545; + mat2 modify1 = rotate(time * 0.02); + f += amp * noise(p); + p = modify1 * p * 2.0; + amp *= 0.454545; + f += amp * noise(p); + return f; +} + +float pattern(vec2 p) { + vec2 offset1 = vec2(1.0); + vec2 offset0 = vec2(0.0); + mat2 rot01 = rotate(0.1 * time); + mat2 rot1 = rotate(0.1); + vec2 q = vec2(fbm(p + offset1), fbm(rot01 * p + offset1)); + vec2 r = vec2(fbm(rot1 * q + offset0), fbm(q + offset0)); + return fbm(p + r); +} +`; + +const CELL_FRAGMENT = `#version 300 es +precision highp float; +precision highp int; + +uniform float iTime; +uniform vec2 uGridMul; +uniform float uNoiseAmp; +uniform float uScale; +uniform vec2 uMouse; +uniform float uMouseStrength; +uniform float uUseMouse; +uniform float uPageLoadProgress; +uniform float uUsePageLoadAnimation; +uniform ivec2 uOrigin; +uniform sampler2D uPrev0; +uniform sampler2D uPrev1; +uniform float uDecay; +uniform float uFresh; +uniform float uHover; + +layout(location = 0) out vec4 outRings; +layout(location = 1) out vec4 outExtra; +${PATTERN} +void main() { + time = iTime * 0.333333; + ivec2 texel = ivec2(gl_FragCoord.xy); + vec2 grid = uGridMul * 15.0; + vec2 s = vec2(texel + uOrigin) / grid; + float intensity = pattern(s * 0.1) * 1.3 - 0.03; + float lift = 0.0; + float strike = 0.0; + + if (uUseMouse > 0.5) { + vec2 mouseWorld = uMouse * uScale; + float distToMouse = distance(s, mouseWorld); + float mouseInfluence = exp(-distToMouse * 8.0) * uMouseStrength * 10.0; + intensity += mouseInfluence; + float ripple = sin(distToMouse * 20.0 - iTime * 5.0) * 0.1 * mouseInfluence; + intensity += ripple; + lift = mouseInfluence; + } + + if (uUsePageLoadAnimation > 0.5) { + float cellRandom = fract(sin(dot(s, vec2(12.9898, 78.233))) * 43758.5453); + float cellDelay = cellRandom * 0.8; + float cellProgress = clamp((uPageLoadProgress - cellDelay) / 0.2, 0.0, 1.0); + float fadeAlpha = smoothstep(0.0, 1.0, cellProgress); + intensity *= fadeAlpha; + strike = sin(3.14159265 * cellProgress) * step(0.1, intensity); + } + + vec4 on0 = step(vec4(0.1), intensity - vec4(0.0, 1.0, 2.0, 4.0) * 0.0625); + vec2 on1 = step(vec2(0.1), intensity - vec2(5.0, 8.0) * 0.0625); + float level = clamp((intensity - 0.1) / 0.6, 0.0, 1.0); + float heat = max(clamp(lift / 3.0, 0.0, 1.0) * uHover, strike); + + vec4 prev0 = texelFetch(uPrev0, texel, 0) * (1.0 - uFresh); + vec4 prev1 = texelFetch(uPrev1, texel, 0) * (1.0 - uFresh); + vec4 fade0 = max(prev0 * uDecay - 1.0 / 255.0, 0.0); + vec4 fade1 = max(prev1 * uDecay - 1.0 / 255.0, 0.0); + + outRings = max(on0, fade0); + outExtra = vec4(max(on1, fade1.xy), max(level, fade1.z), max(heat, fade1.w)); +}`; + +const fontArray = `const uint FONT[${FONT_BITS.length}] = uint[${FONT_BITS.length}](${FONT_BITS.map( + bits => `${bits}u` +).join(', ')});`; + +const MAIN_FRAGMENT = `#version 300 es +precision highp float; +precision highp int; + +uniform float iTime; +uniform vec3 iResolution; +uniform float uScale; +uniform vec2 uGridMul; +uniform float uDigitSize; +uniform float uScanlineIntensity; +uniform float uGlitchAmount; +uniform float uFlickerAmount; +uniform float uChromaticAberration; +uniform float uDither; +uniform float uCurvature; +uniform vec3 uTint; +uniform float uBrightness; +uniform float uLightMode; +uniform sampler2D uRings0; +uniform sampler2D uRings1; +uniform ivec2 uOrigin; +uniform ivec2 uCellCount; +uniform int uGlyphs; +uniform float uGlow; +uniform float uScramble; +uniform float uMouseGlow; +uniform float uVignette; +uniform vec4 uClicks[${MAX_CLICKS}]; +uniform int uClickMode; +uniform float uClickSeconds; +uniform float uClock; + +out vec4 outColor; + +${fontArray} + +float time; +float clickTear; +float clickSplit; +float pixelHeat; + +float hash21(vec2 p) { + p = fract(p * 234.56); + p += dot(p, p + 34.56); + return fract(p.x * p.y); +} + +float hashCell(vec2 p) { + vec3 q = fract(vec3(p.xyx) * 0.1031); + q += dot(q, q.yzx + 33.33); + return fract((q.x + q.y) * q.z); +} + +ivec2 cellTexel(vec2 cell) { + return clamp(ivec2(cell) - uOrigin, ivec2(0), uCellCount - 1); +} + +float ringValue(float n, vec4 r0, vec4 r1) { + if (n < 0.5) return r0.x; + if (n < 1.5) return r0.y; + if (n < 2.5) return r0.z; + if (n < 4.5) return r0.w; + if (n < 5.5) return r1.x; + return r1.y; +} + +float digit(vec2 p) { + vec2 grid = uGridMul * 15.0; + vec2 cell = floor(p * grid); + ivec2 texel = cellTexel(cell); + vec4 r0 = texelFetch(uRings0, texel, 0); + vec4 r1 = texelFetch(uRings1, texel, 0); + float boost = 1.0 + r1.w * uMouseGlow * 1.3; + pixelHeat = max(pixelHeat, r1.w); + p = fract(p * grid); + p *= uDigitSize; + + float px5 = p.x * 5.0; + float py5 = (1.0 - p.y) * 5.0; + float x = fract(px5); + float y = fract(py5); + float i = floor(py5) - 2.0; + float j = floor(px5) - 2.0; + float inside = step(0.0, p.x) * step(p.x, 1.0) * step(0.0, p.y) * step(p.y, 1.0); + + if (uGlyphs == 2) { + float rate = 1.2 + r1.w * uScramble * 18.0; + float phase = hashCell(cell * 1.37 + 4.1); + float epoch = floor(iTime * rate + phase * 7.0); + float pick = hashCell(cell + vec2(epoch * 0.731, epoch * 1.913)); + uint glyph = FONT[int(min(pick * float(FONT.length()), float(FONT.length()) - 1.0))]; + int bit = int(i + 2.0) * 5 + int(j + 2.0); + float lit = float((glyph >> uint(clamp(bit, 0, 24))) & 1u); + float glow = max(r0.x, r1.z); + float shade = 0.35 + 0.65 * r1.z; + return inside * lit * glow * shade * boost * (0.2 + y * 0.8) * (0.75 + x * 0.25); + } + + float n = i * i + j * j; + float on = ringValue(n, r0, r1); + if (uGlyphs == 1) { + vec2 d = vec2(x, y) - 0.5; + float radius = 0.36 + 0.06 * on; + float edge = fwidth(px5) * 0.75; + float dot = 1.0 - smoothstep(radius - edge, radius + edge, length(d)); + return inside * on * dot * boost * (0.55 + 0.45 * (1.0 - length(d) / 0.5)); + } + float brightness = on * (0.2 + y * 0.8) * (0.75 + x * 0.25); + return inside * brightness * boost; +} + +float onOff(float a, float b, float c) { + return step(c, sin(iTime + a * cos(iTime * b))) * uFlickerAmount; +} + +float displace(vec2 look) { + float y = look.y - mod(iTime * 0.25, 1.0); + float window = 1.0 / (1.0 + 50.0 * y * y); + return sin(look.y * 20.0 + iTime) * 0.0125 * onOff(4.0, 2.0, 0.8) * (1.0 + cos(iTime * 60.0)) * window; +} + +vec2 getLight(vec2 p) { + float bar = step(mod(p.y + time * 20.0, 1.0), 0.2) * 0.4 + 1.0; + bar *= uScanlineIntensity; + + float displacement = displace(p); + p.x += displacement; + + if (uGlitchAmount != 1.0) { + float extra = displacement * (uGlitchAmount - 1.0); + p.x += extra; + } + + p.x += clickTear; + + float middle = digit(p); + + const float off = 0.002; + float sum = digit(p + vec2(-off, -off)) + digit(p + vec2(0.0, -off)) + digit(p + vec2(off, -off)) + + digit(p + vec2(-off, 0.0)) + digit(p + vec2(0.0, 0.0)) + digit(p + vec2(off, 0.0)) + + digit(p + vec2(-off, off)) + digit(p + vec2(0.0, off)) + digit(p + vec2(off, off)); + + return vec2(0.9 * middle, sum * 0.1 * bar); +} + +float glowAt(vec2 p) { + vec2 grid = uGridMul * 15.0; + vec2 cell = floor(p * grid); + vec2 cellPx = iResolution.xy / (uScale * grid); + float sigma = 0.5 * min(cellPx.x, cellPx.y); + float center = 0.5 * min(1.0, 1.0 / max(uDigitSize, 0.001)); + float total = 0.0; + for (int oy = -1; oy <= 1; oy++) { + for (int ox = -1; ox <= 1; ox++) { + vec2 c = cell + vec2(float(ox), float(oy)); + ivec2 texel = cellTexel(c); + vec4 r0 = texelFetch(uRings0, texel, 0); + vec4 r1 = texelFetch(uRings1, texel, 0); + float emission = uGlyphs == 2 + ? max(r0.x, r1.z) * (0.35 + 0.65 * r1.z) * 0.45 + : (r0.x + 4.0 * (r0.y + r0.z + r0.w + r1.y) + 8.0 * r1.x) / 25.0; + emission *= 1.0 + r1.w * uMouseGlow * 1.6; + vec2 d = (p - (c + center) / grid) * iResolution.xy / uScale; + total += emission * exp(-dot(d, d) / (2.0 * sigma * sigma)); + } + } + return total; +} + +vec2 barrel(vec2 uv) { + vec2 c = uv * 2.0 - 1.0; + float r2 = dot(c, c); + c *= 1.0 + uCurvature * r2; + return c * 0.5 + 0.5; +} + +void main() { + time = iTime * 0.333333; + vec2 uv = gl_FragCoord.xy / iResolution.xy; + + if (uCurvature != 0.0) { + uv = barrel(uv); + } + + clickTear = 0.0; + clickSplit = 0.0; + if (uClickMode > 0) { + for (int k = 0; k < ${MAX_CLICKS}; k++) { + vec4 click = uClicks[k]; + if (click.w <= 0.0) continue; + float age = uClock - click.z; + if (age < 0.0 || age > uClickSeconds) continue; + float life = age / uClickSeconds; + float envelope = (1.0 - life) * (1.0 - life); + if (uClickMode == 1) { + float tick = floor(age * 30.0); + float bands = 14.0 + 26.0 * hashCell(vec2(click.z, tick * 0.37)); + float row = floor(uv.y * bands); + float pickRow = hashCell(vec2(row + tick * 7.0, click.z * 17.0)); + float torn = step(0.42, pickRow); + float reach = exp(-abs(uv.y - click.y) * 2.5); + float shift = (hashCell(vec2(row * 1.7 + tick, click.z)) - 0.5) * 0.22; + clickTear += shift * torn * envelope * reach; + clickSplit = max(clickSplit, envelope * reach * (0.4 + 0.6 * torn)); + } else { + vec2 aspect = vec2(iResolution.x / iResolution.y, 1.0); + vec2 delta = (uv - click.xy) * aspect; + float dist = length(delta); + float front = age * 1.6; + float band = exp(-pow((dist - front) / 0.18, 2.0)); + float wave = sin((dist - front) * 40.0) * band; + uv += delta / aspect * wave * 0.05 * envelope; + clickSplit = max(clickSplit, envelope * band); + } + } + } + + vec2 p = uv * uScale; + pixelHeat = 0.0; + vec2 lightG = getLight(p); + float heat = pixelHeat; + vec2 lightR = lightG; + vec2 lightB = lightG; + + float split = uChromaticAberration + clickSplit * 6.0; + if (split != 0.0) { + vec2 ca = vec2(split) / iResolution.xy; + lightR = getLight(p + ca); + lightB = getLight(p - ca); + } + + if (uGlow > 0.0) { + float bloom = uGlow * 0.2 * glowAt(p); + lightR.y += bloom; + lightG.y += bloom; + lightB.y += bloom; + } + + vec3 core = vec3(lightR.x, lightG.x, lightB.x); + vec3 halo = vec3(lightR.y, lightG.y, lightB.y); + vec3 raw = core + halo; + + vec3 luma = vec3(0.2126, 0.7152, 0.0722); + float peak = max(uTint.r, max(uTint.g, uTint.b)); + float phosphor = clamp(uGlow, 0.0, 1.0); + vec3 vividTint = clamp(mix(vec3(dot(uTint, luma)), uTint, 1.0 + 0.8 * phosphor), 0.0, 1.0); + vec3 coreTint = mix(uTint, vec3(peak), phosphor * 0.45 * smoothstep(0.45, 0.9, core)); + vec3 col = core * coreTint + halo * vividTint; + col += (vec3(1.0) - uTint) * min(raw, vec3(1.0)) * heat * uMouseGlow * 0.6; + col *= uBrightness; + + if (uVignette > 0.0) { + float edge = 0.04 + 0.22 * uVignette; + vec2 fade = smoothstep(vec2(0.0), vec2(edge), uv) * smoothstep(vec2(0.0), vec2(edge), 1.0 - uv); + float mask = fade.x * fade.y; + mask = mask * mask * (3.0 - 2.0 * mask); + float keep = mix(1.0, mask, clamp(uVignette * 1.5, 0.0, 1.0)); + col *= keep; + core *= keep; + halo *= keep; + } + + if (uLightMode > 0.5) { + vec3 luma = vec3(0.2126, 0.7152, 0.0722); + float lum = dot(uTint, luma); + float peak = max(uTint.r, max(uTint.g, uTint.b)); + vec3 hue = uTint / max(peak, 0.0001); + vec3 vivid = clamp(mix(vec3(dot(hue, luma)), hue, 1.6), 0.0, 1.0); + vivid = clamp(vivid * (0.3 / max(dot(vivid, luma), 0.0001)), 0.0, 1.0); + vec3 ink = mix(uTint, vivid, smoothstep(0.3, 0.6, lum)); + vec3 cover = (core * 1.15 + halo * 0.4) * uBrightness * (1.0 + heat * uMouseGlow * 0.4); + if (uDither > 0.0) cover += (hash21(gl_FragCoord.xy) - 0.5) * (uDither * 0.003922); + cover = clamp(cover, 0.0, 0.94); + float alpha = max(cover.r, max(cover.g, cover.b)); + outColor = vec4(alpha - cover * (1.0 - ink), alpha); + return; + } + + if (uDither > 0.0) { + float rnd = hash21(gl_FragCoord.xy); + col += (rnd - 0.5) * (uDither * 0.003922); + } + + col = clamp(col, 0.0, 1.0); + outColor = vec4(col, max(col.r, max(col.g, col.b))); +}`; + +const clamp = (value, min, max) => Math.min(max, Math.max(min, value)); + +const compile = (gl, type, source) => { + const shader = gl.createShader(type); + if (!shader) return null; + gl.shaderSource(shader, source); + gl.compileShader(shader); + if (gl.getShaderParameter(shader, gl.COMPILE_STATUS)) return shader; + gl.deleteShader(shader); + return null; +}; + +const link = (gl, fragmentSource) => { + const vertex = compile(gl, gl.VERTEX_SHADER, VERTEX); + const fragment = compile(gl, gl.FRAGMENT_SHADER, fragmentSource); + const program = gl.createProgram(); + if (!vertex || !fragment || !program) return null; + gl.attachShader(program, vertex); + gl.attachShader(program, fragment); + gl.linkProgram(program); + gl.deleteShader(vertex); + gl.deleteShader(fragment); + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + gl.deleteProgram(program); + return null; + } + const uniforms = {}; + const count = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + for (let i = 0; i < count; i++) { + const info = gl.getActiveUniform(program, i); + if (!info) continue; + const name = info.name.replace(/\[0\]$/, ''); + uniforms[name] = gl.getUniformLocation(program, name); + } + return { program, uniforms }; +}; + +const hexToRgb = hex => { + let h = String(hex || '#ffffff') + .replace('#', '') + .trim(); + if (h.length === 3 || h.length === 4) + h = h + .slice(0, 3) + .split('') + .map(c => c + c) + .join(''); + const num = parseInt(h.slice(0, 6), 16); + if (Number.isNaN(num)) return [1, 1, 1]; + return [((num >> 16) & 255) / 255, ((num >> 8) & 255) / 255, (num & 255) / 255]; +}; + +export default function FaultyTerminal({ + scale = 1, + gridMul = [2, 1], + digitSize = 1.5, + timeScale = 0.3, + pause = false, + scanlineIntensity = 0.3, + glitchAmount = 1, + flickerAmount = 1, + noiseAmp = 1, + chromaticAberration = 0, + dither = 0, + curvature = 0.2, + tint = '#ff5252', + mouseReact = true, + mouseStrength = 0.2, + pageLoadAnimation = true, + brightness = 1, + glyphs = 'blocks', + glow = 0.5, + persistence = 0.5, + scramble = 0.5, + mouseGlow = 0.6, + vignette = 0.25, + clickEffect = 'glitch', + variation = undefined, + lightMode = false, + dpr = undefined, + className = '', + style = undefined, + ...rest +}) { + const containerRef = useRef(null); + const canvasRef = useRef(null); + const wakeRef = useRef(null); + const settings = { + scale: Math.max(0.05, scale), + gridX: Math.max(0.1, (gridMul?.[0] ?? 2) * 15), + gridY: Math.max(0.1, (gridMul?.[1] ?? 1) * 15), + digitSize, + timeScale, + pause, + scanlineIntensity, + glitchAmount, + flickerAmount, + noiseAmp, + chromaticAberration, + dither: typeof dither === 'boolean' ? (dither ? 1 : 0) : dither, + curvature, + tint, + mouseReact, + mouseStrength, + pageLoadAnimation, + brightness, + glyphs: GLYPHS[glyphs] ?? 0, + glow: clamp(glow, 0, 3), + persistence: clamp(persistence, 0, 1), + scramble: clamp(scramble, 0, 1), + mouseGlow: clamp(mouseGlow, 0, 1), + vignette: clamp(vignette, 0, 1), + clickEffect: CLICKS[clickEffect] ?? 0, + clickSeconds: CLICK_SECONDS[clickEffect] ?? 1, + variation, + lightMode, + dpr + }; + const settingsRef = useRef(settings); + settingsRef.current = settings; + + useEffect(() => { + const container = containerRef.current; + const canvas = canvasRef.current; + const gl = canvas?.getContext('webgl2', { + alpha: true, + premultipliedAlpha: true, + antialias: false, + depth: false, + stencil: false + }); + if (!container || !canvas || !gl) return undefined; + const cellShader = link(gl, CELL_FRAGMENT); + const mainShader = link(gl, MAIN_FRAGMENT); + if (!cellShader || !mainShader) return undefined; + const cu = cellShader.uniforms; + const mu = mainShader.uniforms; + const vao = gl.createVertexArray(); + + const makeTexture = () => { + const texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + return texture; + }; + const targets = [0, 1].map(() => { + const rings = makeTexture(); + const extra = makeTexture(); + const framebuffer = gl.createFramebuffer(); + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, rings, 0); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT1, gl.TEXTURE_2D, extra, 0); + return { rings, extra, framebuffer }; + }); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false; + const view = { width: 1, height: 1, ratio: 1, columns: 1 }; + const cells = { x: 0, y: 0, w: 1, h: 1, key: '' }; + const pointer = { x: 0.5, y: 0.5, inside: false }; + const mouse = { x: 0.5, y: 0.5 }; + const clicks = new Float32Array(MAX_CLICKS * 4); + let clickIndex = 0; + let clock = 0; + let hover = 0; + let current = 0; + let fresh = true; + const seedOffset = settingsRef.current.variation; + const initialOffset = typeof seedOffset === 'number' ? seedOffset * 10 : Math.random() * 100; + let iTime = initialOffset * settingsRef.current.timeScale; + let introClock = settingsRef.current.pageLoadAnimation && !reduce ? 0 : 1; + let raf = 0; + let last = 0; + let visible = true; + let quiet = 0; + + const layoutCells = s => { + const reach = 1 + Math.max(0, s.curvature) * 2; + const uvMin = 0.5 - 0.5 * reach; + const uvMax = 0.5 + 0.5 * reach; + const margin = 0.06 * Math.max(1, Math.abs(s.glitchAmount)) * Math.max(1, Math.abs(s.flickerAmount)) + 0.2; + const gridX = s.gridX * view.columns; + const x0 = Math.floor((uvMin * s.scale - margin) * gridX) - 2; + const x1 = Math.floor((uvMax * s.scale + margin) * gridX) + 2; + const y0 = Math.floor((uvMin * s.scale - margin) * s.gridY) - 2; + const y1 = Math.floor((uvMax * s.scale + margin) * s.gridY) + 2; + const key = `${x0}:${x1}:${y0}:${y1}`; + if (key === cells.key) return; + cells.key = key; + cells.x = x0; + cells.y = y0; + cells.w = Math.max(1, Math.min(4096, x1 - x0 + 1)); + cells.h = Math.max(1, Math.min(4096, y1 - y0 + 1)); + for (const target of targets) { + for (const texture of [target.rings, target.extra]) { + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, cells.w, cells.h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + } + } + fresh = true; + }; + + const stepCells = (s, decay) => { + const source = targets[current]; + const target = targets[1 - current]; + gl.bindFramebuffer(gl.FRAMEBUFFER, target.framebuffer); + gl.drawBuffers([gl.COLOR_ATTACHMENT0, gl.COLOR_ATTACHMENT1]); + gl.viewport(0, 0, cells.w, cells.h); + gl.disable(gl.BLEND); + gl.useProgram(cellShader.program); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, source.rings); + gl.activeTexture(gl.TEXTURE1); + gl.bindTexture(gl.TEXTURE_2D, source.extra); + gl.uniform1i(cu.uPrev0, 0); + gl.uniform1i(cu.uPrev1, 1); + gl.uniform1f(cu.iTime, iTime); + gl.uniform2f(cu.uGridMul, (s.gridX * view.columns) / 15, s.gridY / 15); + gl.uniform1f(cu.uNoiseAmp, s.noiseAmp); + gl.uniform1f(cu.uScale, s.scale); + gl.uniform2f(cu.uMouse, mouse.x, mouse.y); + gl.uniform1f(cu.uMouseStrength, s.mouseStrength); + gl.uniform1f(cu.uUseMouse, s.mouseReact ? 1 : 0); + gl.uniform1f(cu.uPageLoadProgress, introClock); + gl.uniform1f(cu.uUsePageLoadAnimation, s.pageLoadAnimation ? 1 : 0); + gl.uniform2i(cu.uOrigin, cells.x, cells.y); + gl.uniform1f(cu.uDecay, decay); + gl.uniform1f(cu.uFresh, fresh ? 1 : 0); + gl.uniform1f(cu.uHover, hover); + gl.bindVertexArray(vao); + gl.drawArrays(gl.TRIANGLES, 0, 3); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + current = 1 - current; + fresh = false; + }; + + const draw = () => { + const s = settingsRef.current; + const source = targets[current]; + gl.viewport(0, 0, canvas.width, canvas.height); + gl.clearColor(0, 0, 0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); + gl.useProgram(mainShader.program); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, source.rings); + gl.activeTexture(gl.TEXTURE1); + gl.bindTexture(gl.TEXTURE_2D, source.extra); + gl.uniform1i(mu.uRings0, 0); + gl.uniform1i(mu.uRings1, 1); + gl.uniform1f(mu.iTime, iTime); + gl.uniform3f(mu.iResolution, canvas.width, canvas.height, canvas.width / canvas.height); + gl.uniform1f(mu.uScale, s.scale); + gl.uniform2f(mu.uGridMul, (s.gridX * view.columns) / 15, s.gridY / 15); + gl.uniform1f(mu.uDigitSize, s.digitSize); + gl.uniform1f(mu.uScanlineIntensity, s.scanlineIntensity); + gl.uniform1f(mu.uGlitchAmount, reduce ? 0 : s.glitchAmount); + gl.uniform1f(mu.uFlickerAmount, reduce ? 0 : s.flickerAmount); + gl.uniform1f(mu.uChromaticAberration, s.chromaticAberration); + gl.uniform1f(mu.uDither, s.dither); + gl.uniform1f(mu.uCurvature, s.curvature); + gl.uniform3fv(mu.uTint, hexToRgb(s.tint)); + gl.uniform1f(mu.uBrightness, s.brightness); + gl.uniform1f(mu.uLightMode, s.lightMode ? 1 : 0); + gl.uniform2i(mu.uOrigin, cells.x, cells.y); + gl.uniform2i(mu.uCellCount, cells.w, cells.h); + gl.uniform1i(mu.uGlyphs, s.glyphs); + gl.uniform1f(mu.uGlow, s.glow); + gl.uniform1f(mu.uScramble, s.scramble); + gl.uniform1f(mu.uMouseGlow, s.mouseGlow); + gl.uniform1f(mu.uVignette, s.vignette); + gl.uniform4fv(mu.uClicks, clicks); + gl.uniform1i(mu.uClickMode, s.clickEffect); + gl.uniform1f(mu.uClickSeconds, s.clickSeconds); + gl.uniform1f(mu.uClock, clock); + gl.bindVertexArray(vao); + gl.drawArrays(gl.TRIANGLES, 0, 3); + gl.bindVertexArray(null); + }; + + const resize = () => { + const s = settingsRef.current; + view.width = Math.max(1, container.clientWidth); + view.height = Math.max(1, container.clientHeight); + view.ratio = Math.min(s.dpr || window.devicePixelRatio || 1, 2); + view.columns = Math.min(1, view.width / view.height / 1.5); + canvas.width = Math.max(1, Math.round(view.width * view.ratio)); + canvas.height = Math.max(1, Math.round(view.height * view.ratio)); + layoutCells(s); + stepCells(s, 0); + draw(); + wake(); + }; + + const frame = now => { + raf = 0; + if (!visible || document.hidden) return; + const s = settingsRef.current; + const dt = last ? clamp((now - last) / 1000, 0.001, 1 / 20) : 1 / 60; + last = now; + clock += dt; + if (!s.pause && !reduce) iTime += dt * s.timeScale; + const targetX = pointer.inside ? pointer.x : 0.5; + const targetY = pointer.inside ? pointer.y : 0.5; + const follow = 1 - Math.exp(-dt / (pointer.inside ? 0.19988 : 0.6)); + mouse.x += (targetX - mouse.x) * follow; + mouse.y += (targetY - mouse.y) * follow; + hover += ((pointer.inside ? 1 : 0) - hover) * (1 - Math.exp(-dt / 0.35)); + for (let k = 0; k < MAX_CLICKS; k++) { + if (clicks[k * 4 + 3] > 0 && clock - clicks[k * 4 + 2] > s.clickSeconds) clicks[k * 4 + 3] = 0; + } + layoutCells(s); + const decay = s.persistence > 0 ? Math.exp(-dt / (0.08 + s.persistence * 1.4)) : 0; + stepCells(s, decay); + draw(); + if (introClock < 1) introClock = Math.min(1, introClock + dt / INTRO_SECONDS); + let busy = !(s.pause || reduce) || introClock < 1; + busy = busy || Math.abs(targetX - mouse.x) + Math.abs(targetY - mouse.y) > 0.0001; + busy = busy || Math.abs((pointer.inside ? 1 : 0) - hover) > 0.001; + for (let k = 0; k < MAX_CLICKS; k++) busy = busy || clicks[k * 4 + 3] > 0; + quiet = busy ? 0 : quiet + dt; + if (quiet < 2.5) raf = requestAnimationFrame(frame); + }; + + function wake() { + quiet = 0; + if (!raf && visible && !document.hidden) { + last = 0; + raf = requestAnimationFrame(frame); + } + } + + const locate = event => { + const rect = container.getBoundingClientRect(); + const x = (event.clientX - rect.left) / Math.max(rect.width, 1); + const y = 1 - (event.clientY - rect.top) / Math.max(rect.height, 1); + return { x, y, inside: x >= 0 && x <= 1 && y >= 0 && y <= 1 }; + }; + + const onPointerMove = event => { + const { x, y, inside } = locate(event); + const was = pointer.inside; + pointer.inside = inside; + if (inside) { + pointer.x = x; + pointer.y = y; + } + if (inside || was) wake(); + }; + + const onPointerDown = event => { + const s = settingsRef.current; + const { x, y, inside } = locate(event); + if (!inside || reduce || !s.clickEffect) return; + const o = clickIndex * 4; + clicks[o] = x; + clicks[o + 1] = y; + clicks[o + 2] = clock; + clicks[o + 3] = 1; + clickIndex = (clickIndex + 1) % MAX_CLICKS; + wake(); + }; + + const onPointerLeave = () => { + pointer.inside = false; + wake(); + }; + + const onVisibility = () => wake(); + + const resizeObserver = new ResizeObserver(resize); + resizeObserver.observe(container); + const intersection = new IntersectionObserver(entries => { + visible = entries.some(entry => entry.isIntersecting); + if (visible) wake(); + }); + intersection.observe(container); + window.addEventListener('pointermove', onPointerMove, { passive: true }); + window.addEventListener('pointerdown', onPointerDown, { passive: true }); + document.documentElement.addEventListener('pointerleave', onPointerLeave); + document.addEventListener('visibilitychange', onVisibility); + resize(); + wakeRef.current = wake; + + return () => { + cancelAnimationFrame(raf); + wakeRef.current = null; + resizeObserver.disconnect(); + intersection.disconnect(); + window.removeEventListener('pointermove', onPointerMove); + window.removeEventListener('pointerdown', onPointerDown); + document.documentElement.removeEventListener('pointerleave', onPointerLeave); + document.removeEventListener('visibilitychange', onVisibility); + for (const target of targets) { + gl.deleteTexture(target.rings); + gl.deleteTexture(target.extra); + gl.deleteFramebuffer(target.framebuffer); + } + gl.deleteVertexArray(vao); + gl.deleteProgram(cellShader.program); + gl.deleteProgram(mainShader.program); + gl.getExtension('WEBGL_lose_context')?.loseContext(); + }; + }, []); + + useEffect(() => { + wakeRef.current?.(); + }); + + return ( +
+
+ ); +} diff --git a/frontend/crm/src/components/FaultyTerminalBackdrop.tsx b/frontend/crm/src/components/FaultyTerminalBackdrop.tsx new file mode 100644 index 0000000..5cbc178 --- /dev/null +++ b/frontend/crm/src/components/FaultyTerminalBackdrop.tsx @@ -0,0 +1,20 @@ +import { lazy, Suspense } from "react"; + +const FaultyTerminal = lazy(() => import("./FaultyTerminal.js")); + +export const FaultyTerminalBackdrop = () => ( + +); diff --git a/frontend/crm/src/components/icons.tsx b/frontend/crm/src/components/icons.tsx new file mode 100644 index 0000000..d1f4d26 --- /dev/null +++ b/frontend/crm/src/components/icons.tsx @@ -0,0 +1,175 @@ +import type { ImgHTMLAttributes } from "react"; + +type IconProps = Omit, "src" | "alt"> & { + filled?: boolean; +}; + +const ImgIcon = ({ + src, + className = "", + ...props +}: { src: string } & IconProps) => ( + +); + +export const FolderIcon = (props: IconProps) => ( + +); + +export const FileIcon = (props: IconProps) => ( + +); + +export const ImageIcon = (props: IconProps) => ( + +); + +export const PlayIcon = (props: IconProps) => ( + +); + +export const AudioIcon = (props: IconProps) => ( + +); + +export const ArchiveIcon = (props: IconProps) => ( + +); + +export const UploadIcon = (props: IconProps) => ( + +); + +export const DownloadIcon = (props: IconProps) => ( + +); + +export const PlusIcon = (props: IconProps) => ( + +); + +export const TrashIcon = (props: IconProps) => ( + +); + +export const TrashEmptyIcon = (props: IconProps) => ( + +); + +export const RestoreIcon = (props: IconProps) => ( + +); + +export const RefreshIcon = (props: IconProps) => ( + +); + +export const StarIcon = (props: IconProps) => ( + +); + +export const SearchIcon = (props: IconProps) => ( + +); + +export const UsersIcon = (props: IconProps) => ( + +); + +export const SettingsIcon = (props: IconProps) => ( + +); + +export const LogoutIcon = (props: IconProps) => ( + +); + +export const ShieldIcon = (props: IconProps) => ( + +); + +export const HardDriveIcon = (props: IconProps) => ( + +); + +export const ActivityIcon = (props: IconProps) => ( + +); + +export const SearchNavIcon = (props: IconProps) => ( + +); + +export const FilterIcon = (props: IconProps) => ( + +); + +export const ShareIcon = (props: IconProps) => ( + +); + +export const MenuIcon = (props: IconProps) => ( + +); + +export const CloseIcon = (props: IconProps) => ( + +); + +export const ArrowLeftIcon = (props: IconProps) => ( + +); + +export const ArrowRightIcon = (props: IconProps) => ( + +); + +export const PenIcon = (props: IconProps) => ( + +); + +export const PinIcon = (props: IconProps) => ( + +); + +export const MoveIcon = (props: IconProps) => ( + +); + +export const ChatIcon = (props: IconProps) => ( + +); + +export const SendIcon = (props: IconProps) => ( + +); + +export const ClearIcon = (props: IconProps) => ( + +); + +export const SaveIcon = (props: IconProps) => ( + +); + +export const OpenedFolderIcon = (props: IconProps) => ( + +); + +export const DeactivateIcon = (props: IconProps) => ( + +); + +export const PasswordResetIcon = (props: IconProps) => ( + +); diff --git a/frontend/crm/src/lib/api.ts b/frontend/crm/src/lib/api.ts new file mode 100644 index 0000000..a5ac622 --- /dev/null +++ b/frontend/crm/src/lib/api.ts @@ -0,0 +1,244 @@ +export interface User { + id: string; + email: string; + first_name: string; + last_name: string; + must_change_password: boolean; +} + +export interface Country { + id: number; + code: string; + name: string; + phone_code: string | null; +} + +export interface Organization { + 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 Contact { + 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 accepte par les routes creation / mise a jour d'entreprise. */ +export type OrganizationInput = { + name?: string; + website?: string | null; + industry?: string | null; + phone?: string | null; + email?: string | null; + addressLine1?: string | null; + addressLine2?: string | null; + postalCode?: string | null; + city?: string | null; + countryId?: number | null; + description?: string | null; +}; + +/** Corps accepte par les routes creation / mise a jour de prospect. */ +export type ContactInput = { + firstName?: string; + lastName?: string; + organizationId?: string | null; + email?: string | null; + phone?: string | null; + mobile?: string | null; + jobTitle?: string | null; + countryId?: number | null; + externalSource?: string | null; + externalId?: string | null; + description?: string | null; +}; + +/** Pagination renvoyee par les listes, sans type : la donnee est homogene. */ +export interface Pagination { + total: number; + page: number; + limit: number; +} + +export class ApiError extends Error { + readonly status: number; + + constructor(status: number, message: string) { + super(message); + this.name = "ApiError"; + this.status = status; + } +} + +const BASE = "/api/crm"; + +/** + * Un seul point d'entree HTTP. Le cookie de session est envoye + * automatiquement (same-origin), et toute erreur non-2xx devient une + * ApiError portant le message serveur, jamais un corps brut. + */ +const request = async (path: string, init?: RequestInit): Promise => { + let response: Response; + try { + response = await fetch(`${BASE}${path}`, { + credentials: "same-origin", + ...init, + headers: { + ...(init?.body ? { "content-type": "application/json" } : {}), + ...init?.headers, + }, + }); + } catch { + throw new ApiError(0, "Serveur injoignable. Verifiez votre connexion."); + } + + const body: unknown = await response.json().catch(() => null); + if (!response.ok) { + const message = + (body as { error?: { message?: string } } | null)?.error?.message ?? + "Une erreur est survenue."; + throw new ApiError(response.status, message); + } + return body as T; +}; + +export const api = { + me: () => request<{ user: User }>("/auth/me"), + + login: (email: string, password: string) => + request<{ user: User }>("/auth/login", { + method: "POST", + body: JSON.stringify({ email, password }), + }), + + logout: () => request<{ ok: boolean }>("/auth/logout", { method: "POST" }), + + changePassword: (current: string, next: string) => + request<{ ok: boolean }>("/auth/change-password", { + method: "POST", + body: JSON.stringify({ current, next }), + }), + + countries: (search?: string) => + request<{ countries: Country[] }>( + `/countries${search ? `?q=${encodeURIComponent(search)}` : ""}`, + ), + + createCountry: (input: { code: string; name: string; phoneCode?: string | null }) => + request<{ country: Country }>("/countries", { + method: "POST", + body: JSON.stringify(input), + }), + + updateCountry: (id: number, input: { code?: string; name?: string; phoneCode?: string | null }) => + request<{ country: Country }>(`/countries/${id}`, { + method: "PATCH", + body: JSON.stringify(input), + }), + + deleteCountry: (id: number) => + request<{ ok: boolean }>(`/countries/${id}`, { method: "DELETE" }), + + organizations: (search?: string, page = 1, limit = 25) => { + const params = new URLSearchParams({ page: String(page), limit: String(limit) }); + if (search) params.set("q", search); + return request<{ organizations: Organization[] } & Pagination>( + `/organizations?${params.toString()}`, + ); + }, + + organization: (id: string) => + request<{ organization: Organization }>(`/organizations/${encodeURIComponent(id)}`), + + createOrganization: (input: OrganizationInput) => + request<{ organization: Organization }>("/organizations", { + method: "POST", + body: JSON.stringify(input), + }), + + updateOrganization: (id: string, input: OrganizationInput) => + request<{ organization: Organization }>(`/organizations/${encodeURIComponent(id)}`, { + method: "PATCH", + body: JSON.stringify(input), + }), + + deleteOrganization: (id: string) => + request<{ ok: boolean }>(`/organizations/${encodeURIComponent(id)}`, { method: "DELETE" }), + + contacts: (options: { + search?: string | undefined; + organizationId?: string | undefined; + page?: number | undefined; + limit?: number | undefined; + } = {}) => { + const params = new URLSearchParams({ + page: String(options.page ?? 1), + limit: String(options.limit ?? 25), + }); + if (options.search) params.set("q", options.search); + if (options.organizationId) params.set("organizationId", options.organizationId); + return request<{ contacts: Contact[] } & Pagination>( + `/contacts?${params.toString()}`, + ); + }, + + contact: (id: string) => + request<{ contact: Contact }>(`/contacts/${encodeURIComponent(id)}`), + + createContact: (input: ContactInput) => + request<{ contact: Contact }>("/contacts", { + method: "POST", + body: JSON.stringify(input), + }), + + updateContact: (id: string, input: ContactInput) => + request<{ contact: Contact }>(`/contacts/${encodeURIComponent(id)}`, { + method: "PATCH", + body: JSON.stringify(input), + }), + + deleteContact: (id: string) => + request<{ ok: boolean }>(`/contacts/${encodeURIComponent(id)}`, { method: "DELETE" }), +}; + +/** Date ISO en date lisible, sans changer de jour a cause du fuseau. */ +export const formatDate = (iso: string): string => + new Date(iso).toLocaleDateString("fr-FR", { + day: "2-digit", + month: "2-digit", + year: "numeric", + }); diff --git a/frontend/crm/src/main.tsx b/frontend/crm/src/main.tsx new file mode 100644 index 0000000..7c3597b --- /dev/null +++ b/frontend/crm/src/main.tsx @@ -0,0 +1,16 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { App } from "./App.js"; +import "./styles/index.css"; + +const container = document.getElementById("root"); + +if (!container) { + throw new Error("Element racine introuvable"); +} + +createRoot(container).render( + + + , +); diff --git a/frontend/crm/src/pages/ChangePassword.tsx b/frontend/crm/src/pages/ChangePassword.tsx new file mode 100644 index 0000000..888f25c --- /dev/null +++ b/frontend/crm/src/pages/ChangePassword.tsx @@ -0,0 +1,109 @@ +import { useState, type FormEvent } from "react"; +import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "@cohaise/ui"; +import { ApiError, api, type User } from "../lib/api.js"; + +interface Props { + user: User; + onCompleted: () => void; + onLogout: () => void; +} + +export const ChangePassword = ({ user, onCompleted, onLogout }: Props) => { + const [current, setCurrent] = useState(""); + const [next, setNext] = useState(""); + const [confirm, setConfirm] = useState(""); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + const submit = async (event: FormEvent) => { + event.preventDefault(); + + if (next !== confirm) { + setError("Les deux mots de passe ne correspondent pas."); + return; + } + if (next.length < 8) { + setError("Le nouveau mot de passe doit contenir au moins 8 caractères."); + return; + } + + setBusy(true); + setError(null); + try { + await api.changePassword(current, next); + onCompleted(); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Modification impossible."); + } finally { + setBusy(false); + } + }; + + return ( +
+
+
+

+ CoHaiSe +

+

+ Nouveau mot de passe +

+

+ Bienvenue {user.first_name}. Ce mot de passe a été défini par un + administrateur : choisissez le vôtre. +

+
+ + + + Changement requis + + Les autres sessions ouvertes sur ce compte seront fermées. + + + +
void submit(event)}> + setCurrent(event.target.value)} + /> + setNext(event.target.value)} + /> + setConfirm(event.target.value)} + {...(error ? { error } : {})} + /> + + + +
+
+
+
+
+ ); +}; diff --git a/frontend/crm/src/pages/Contacts.tsx b/frontend/crm/src/pages/Contacts.tsx new file mode 100644 index 0000000..865455d --- /dev/null +++ b/frontend/crm/src/pages/Contacts.tsx @@ -0,0 +1,339 @@ +import { useCallback, useEffect, useState, type FormEvent } from "react"; +import { Button, Card, CardContent, CardHeader, CardTitle, Input, Skeleton } from "@cohaise/ui"; +import { + ApiError, + api, + formatDate, + type Contact, + type ContactInput, + type Country, + type Organization, +} from "../lib/api.js"; + +const EMPTY: ContactInput = { + firstName: "", + lastName: "", + organizationId: null, + email: null, + phone: null, + mobile: null, + jobTitle: null, + countryId: null, + description: null, +}; + +const text = (value: string): string | null => (value.trim() ? value.trim() : null); + +export const Contacts = () => { + const [rows, setRows] = useState([]); + const [organizations, setOrganizations] = useState([]); + const [countries, setCountries] = useState([]); + const [total, setTotal] = useState(0); + const [search, setSearch] = useState(""); + const [loading, setLoading] = useState(true); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [editing, setEditing] = useState(null); + const [form, setForm] = useState(EMPTY); + const [open, setOpen] = useState(false); + + const load = useCallback(async () => { + setLoading(true); + setError(null); + try { + const result = await api.contacts({ search: search || undefined }); + setRows(result.contacts); + setTotal(result.total); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Chargement impossible."); + } finally { + setLoading(false); + } + }, [search]); + + useEffect(() => { + void load(); + }, [load]); + + // Les listes deroulantes sont des donnees de reference : leur echec ne doit + // pas empecher l'ecran de s'afficher, on les laisse vides. + useEffect(() => { + void api + .countries() + .then((result) => setCountries(result.countries)) + .catch(() => undefined); + void api + .organizations(undefined, 1, 100) + .then((result) => setOrganizations(result.organizations)) + .catch(() => undefined); + }, []); + + const openCreate = () => { + setEditing(null); + setForm(EMPTY); + setError(null); + setOpen(true); + }; + + const openEdit = (contact: Contact) => { + setOpen(true); + setEditing(contact); + setForm({ + firstName: contact.first_name, + lastName: contact.last_name, + organizationId: contact.organization_id, + email: contact.email, + phone: contact.phone, + mobile: contact.mobile, + jobTitle: contact.job_title, + countryId: contact.country_id, + description: contact.description, + }); + setError(null); + }; + + const close = () => { + setEditing(null); + setForm(EMPTY); + setError(null); + setOpen(false); + }; + + const submit = async (event: FormEvent) => { + event.preventDefault(); + const firstName = text(form.firstName ?? ""); + const lastName = text(form.lastName ?? ""); + if (!firstName || !lastName) { + setError("Le prénom et le nom sont obligatoires."); + return; + } + + const payload: ContactInput = { + firstName, + lastName, + organizationId: form.organizationId ?? null, + email: text(form.email ?? ""), + phone: text(form.phone ?? ""), + mobile: text(form.mobile ?? ""), + jobTitle: text(form.jobTitle ?? ""), + countryId: form.countryId ?? null, + description: text(form.description ?? ""), + }; + + setBusy(true); + setError(null); + try { + if (editing) await api.updateContact(editing.id, payload); + else await api.createContact(payload); + close(); + await load(); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Enregistrement impossible."); + } finally { + setBusy(false); + } + }; + + const remove = async (contact: Contact) => { + const label = `${contact.first_name} ${contact.last_name}`; + if (!window.confirm(`Supprimer « ${label} » ?`)) return; + setBusy(true); + setError(null); + try { + await api.deleteContact(contact.id); + await load(); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Suppression impossible."); + } finally { + setBusy(false); + } + }; + + const set = (key: keyof ContactInput) => (value: string | number | null) => { + setForm((current) => ({ + ...current, + [key]: key === "countryId" ? (value === null ? null : Number(value)) : text(String(value ?? "")), + })); + }; + + return ( +
+
+
+ setSearch(event.target.value)} + /> +
+ +
+ + {open ? ( + + + {editing ? "Modifier le prospect" : "Nouveau prospect"} + + +
void submit(event)}> + set("firstName")(event.target.value)} + /> + set("lastName")(event.target.value)} + /> + set("jobTitle")(event.target.value)} + /> + set("email")(event.target.value)} + /> + set("phone")(event.target.value)} + /> + set("mobile")(event.target.value)} + /> + + +
+ set("description")(event.target.value)} + /> +
+ + {error ? ( +

+ {error} +

+ ) : null} + +
+ + +
+
+
+
+ ) : null} + + {loading ? ( +
+ + + +
+ ) : error && rows.length === 0 ? ( +

{error}

+ ) : rows.length === 0 ? ( + + +

+ Aucun prospect. Ajoutez le premier pour commencer. +

+
+
+ ) : ( +
+ + + + + + + + + + + + + + {rows.map((contact) => ( + + + + + + + + + + ))} + +
NomFonctionEntrepriseContactPaysAjouté leActions
+ {contact.last_name} {contact.first_name} + {contact.job_title ?? "—"}{contact.organization_name ?? "—"}{contact.email ?? contact.phone ?? "—"}{contact.country_code ?? "—"} + {formatDate(contact.created_at)} + +
+ + { + + } +
+
+

+ {total} prospect{total > 1 ? "s" : ""} +

+
+ )} +
+ ); +}; diff --git a/frontend/crm/src/pages/Countries.tsx b/frontend/crm/src/pages/Countries.tsx new file mode 100644 index 0000000..57157b6 --- /dev/null +++ b/frontend/crm/src/pages/Countries.tsx @@ -0,0 +1,226 @@ +import { useCallback, useEffect, useState, type FormEvent } from "react"; +import { Button, Card, CardContent, CardHeader, CardTitle, Input, Skeleton } from "@cohaise/ui"; +import { ApiError, api, type Country } from "../lib/api.js"; + +interface Form { + code: string; + name: string; + phoneCode: string; +} + +const EMPTY: Form = { code: "", name: "", phoneCode: "" }; + +export const Countries = () => { + const [rows, setRows] = useState([]); + const [loading, setLoading] = useState(true); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [open, setOpen] = useState(false); + const [editing, setEditing] = useState(null); + const [form, setForm] = useState
(EMPTY); + + const load = useCallback(async () => { + setLoading(true); + setError(null); + try { + const result = await api.countries(); + setRows(result.countries); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Chargement impossible."); + } finally { + setLoading(false); + } + }, []); + + useEffect(() => { + void load(); + }, [load]); + + const submit = async (event: FormEvent) => { + event.preventDefault(); + const code = form.code.trim().toUpperCase(); + const name = form.name.trim(); + if (!/^[A-Z]{2}$/.test(code)) { + setError("Le code doit contenir exactement deux lettres."); + return; + } + if (!name) { + setError("Le nom est obligatoire."); + return; + } + + setBusy(true); + setError(null); + try { + const payload = { code, name, phoneCode: form.phoneCode.trim() || null }; + if (editing) await api.updateCountry(editing.id, payload); + else await api.createCountry(payload); + setEditing(null); + setForm(EMPTY); + setOpen(false); + await load(); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Enregistrement impossible."); + } finally { + setBusy(false); + } + }; + + const remove = async (country: Country) => { + if (!window.confirm(`Supprimer « ${country.name} » ?`)) return; + setBusy(true); + setError(null); + try { + await api.deleteCountry(country.id); + await load(); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Suppression impossible."); + } finally { + setBusy(false); + } + }; + + return ( +
+
+

+ Référentiel ISO 3166 utilisé par les entreprises et les prospects. Il ne contient + que les pays déjà saisis dans la base. +

+ { + + } +
+ + {open && ( + + + {editing ? "Modifier le pays" : "Nouveau pays"} + + + void submit(event)} + > + + setForm((current) => ({ ...current, code: event.target.value.toUpperCase() })) + } + /> + setForm((current) => ({ ...current, name: event.target.value }))} + /> + + setForm((current) => ({ ...current, phoneCode: event.target.value })) + } + /> + + {error ? ( +

+ {error} +

+ ) : null} + +
+ + +
+ +
+
+ )} + + {error && rows.length === 0 ? ( +

{error}

+ ) : loading ? ( +
+ + + +
+ ) : ( +
+ + + + + + + + + + + {rows.map((country) => ( + + + + + { + + } + + ))} + +
CodeNomIndicatifActions
{country.code}{country.name}{country.phone_code ?? "—"} +
+ + +
+
+

{rows.length} pays

+
+ )} +
+ ); +}; diff --git a/frontend/crm/src/pages/Crm.tsx b/frontend/crm/src/pages/Crm.tsx new file mode 100644 index 0000000..1b3eeaa --- /dev/null +++ b/frontend/crm/src/pages/Crm.tsx @@ -0,0 +1,85 @@ +import { useState } from "react"; +import { Button, cn } from "@cohaise/ui"; +import type { User } from "../lib/api.js"; +import { Organizations } from "./Organizations.js"; +import { Contacts } from "./Contacts.js"; +import { Countries } from "./Countries.js"; +import { FaultyTerminalBackdrop } from "../components/FaultyTerminalBackdrop.js"; +import { ActivityIcon, FolderIcon, LogoutIcon, UsersIcon } from "../components/icons.js"; + +type Tab = "organizations" | "contacts" | "countries"; + +const TABS: { id: Tab; label: string; icon: typeof FolderIcon }[] = [ + { id: "organizations", label: "Entreprises", icon: FolderIcon }, + { id: "contacts", label: "Prospects", icon: UsersIcon }, + { id: "countries", label: "Pays", icon: ActivityIcon }, +]; + +export const Crm = ({ user, onLogout }: { user: User; onLogout: () => void }) => { + const [tab, setTab] = useState("organizations"); + + return ( +
+ + +
+
+
+ COHAISE + + CRM +
+ +
+
+

+ {user.first_name} {user.last_name} +

+
+ +
+
+ + + +
+
+ {tab === "organizations" ? : null} + {tab === "contacts" ? : null} + {tab === "countries" ? : null} +
+
+
+
+ ); +}; diff --git a/frontend/crm/src/pages/Login.tsx b/frontend/crm/src/pages/Login.tsx new file mode 100644 index 0000000..7330238 --- /dev/null +++ b/frontend/crm/src/pages/Login.tsx @@ -0,0 +1,83 @@ +import { useState, type FormEvent } from "react"; +import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "@cohaise/ui"; +import { ApiError, api, type User } from "../lib/api.js"; + +export const Login = ({ onAuthenticated }: { onAuthenticated: (user: User) => void }) => { + const [email, setEmail] = useState(""); + const [password, setPassword] = useState(""); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + const submit = async (event: FormEvent) => { + event.preventDefault(); + setBusy(true); + setError(null); + try { + const { user } = await api.login(email.trim(), password); + onAuthenticated(user); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Connexion impossible."); + } finally { + setBusy(false); + } + }; + + return ( +
+
+
+

+ CoHaiSe +

+

+ CRM +

+

+ Connectez-vous pour accéder à vos entreprises et prospects. +

+
+ + + + Connexion + Votre session reste ouverte 14 jours. + + +
void submit(event)}> + setEmail(event.target.value)} + /> + setPassword(event.target.value)} + {...(error ? { error } : {})} + /> + + +
+
+
+ +

+ Mot de passe oublié ? Contactez un administrateur. +

+
+
+ ); +}; diff --git a/frontend/crm/src/pages/Organizations.tsx b/frontend/crm/src/pages/Organizations.tsx new file mode 100644 index 0000000..2cc41fc --- /dev/null +++ b/frontend/crm/src/pages/Organizations.tsx @@ -0,0 +1,344 @@ +import { useCallback, useEffect, useState, type FormEvent } from "react"; +import { Button, Card, CardContent, CardHeader, CardTitle, Input, Skeleton, Spinner } from "@cohaise/ui"; +import { + ApiError, + api, + formatDate, + type Country, + type Organization, + type OrganizationInput, +} from "../lib/api.js"; + +const EMPTY: OrganizationInput = { + name: "", + website: null, + industry: null, + phone: null, + email: null, + addressLine1: null, + addressLine2: null, + postalCode: null, + city: null, + countryId: null, + description: null, +}; + +const text = (value: string): string | null => (value.trim() ? value.trim() : null); + +export const Organizations = () => { + const [rows, setRows] = useState([]); + const [countries, setCountries] = useState([]); + const [total, setTotal] = useState(0); + const [search, setSearch] = useState(""); + const [loading, setLoading] = useState(true); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [editing, setEditing] = useState(null); + const [form, setForm] = useState(EMPTY); + // Un etat explicite : comparer form a EMPTY ne fonctionnerait pas, car + // saisir puis effacer recrée un objet different de la constante. + const [open, setOpen] = useState(false); + + const load = useCallback(async () => { + setLoading(true); + setError(null); + try { + const result = await api.organizations(search || undefined); + setRows(result.organizations); + setTotal(result.total); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Chargement impossible."); + } finally { + setLoading(false); + } + }, [search]); + + useEffect(() => { + void load(); + }, [load]); + + useEffect(() => { + void api + .countries() + .then((result) => setCountries(result.countries)) + .catch(() => undefined); + }, []); + + const openCreate = () => { + setEditing(null); + setForm(EMPTY); + setError(null); + setOpen(true); + }; + + const openEdit = (organization: Organization) => { + setOpen(true); + setEditing(organization); + setForm({ + name: organization.name, + website: organization.website, + industry: organization.industry, + phone: organization.phone, + email: organization.email, + addressLine1: organization.address_line1, + addressLine2: organization.address_line2, + postalCode: organization.postal_code, + city: organization.city, + countryId: organization.country_id, + description: organization.description, + }); + setError(null); + }; + + const submit = async (event: FormEvent) => { + event.preventDefault(); + const name = text(form.name ?? ""); + if (!name) { + setError("Le nom de l'entreprise est obligatoire."); + return; + } + + const payload: OrganizationInput = { + name, + website: text(form.website ?? ""), + industry: text(form.industry ?? ""), + phone: text(form.phone ?? ""), + email: text(form.email ?? ""), + addressLine1: text(form.addressLine1 ?? ""), + addressLine2: text(form.addressLine2 ?? ""), + postalCode: text(form.postalCode ?? ""), + city: text(form.city ?? ""), + countryId: form.countryId ?? null, + description: text(form.description ?? ""), + }; + + setBusy(true); + setError(null); + try { + if (editing) await api.updateOrganization(editing.id, payload); + else await api.createOrganization(payload); + setEditing(null); + setForm(EMPTY); + setOpen(false); + await load(); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Enregistrement impossible."); + } finally { + setBusy(false); + } + }; + + const remove = async (organization: Organization) => { + if (!window.confirm(`Supprimer « ${organization.name} » ? Cette action est réversible par un administrateur.`)) { + return; + } + setBusy(true); + setError(null); + try { + await api.deleteOrganization(organization.id); + await load(); + } catch (caught) { + setError(caught instanceof ApiError ? caught.message : "Suppression impossible."); + } finally { + setBusy(false); + } + }; + + const set = (key: keyof OrganizationInput) => (value: string | number | null) => { + setForm((current) => ({ + ...current, + [key]: key === "countryId" ? (value === null ? null : Number(value)) : text(String(value ?? "")), + })); + }; + + return ( +
+
+
+ setSearch(event.target.value)} + /> +
+ +
+ + {open ? ( + + + {editing ? "Modifier l'entreprise" : "Nouvelle entreprise"} + + +
void submit(event)}> + set("name")(event.target.value)} + /> + set("industry")(event.target.value)} + /> + set("website")(event.target.value)} + /> + set("email")(event.target.value)} + /> + set("phone")(event.target.value)} + /> + + set("addressLine1")(event.target.value)} + /> + set("addressLine2")(event.target.value)} + /> + set("postalCode")(event.target.value)} + /> + set("city")(event.target.value)} + /> +
+ set("description")(event.target.value)} + /> +
+ + {error ? ( +

+ {error} +

+ ) : null} + +
+ + +
+
+
+
+ ) : null} + + {loading ? ( +
+ + + +
+ ) : error && rows.length === 0 ? ( +

{error}

+ ) : rows.length === 0 ? ( + + +

+ Aucune entreprise. Créez la première pour commencer. +

+
+
+ ) : ( +
+ + + + + + + + + + + + + + {rows.map((organization) => ( + + + + + + + + + + ))} + +
NomVillePaysSecteurContactCréée leActions
{organization.name}{organization.city ?? "—"}{organization.country_code ?? "—"}{organization.industry ?? "—"} + {organization.email ?? organization.phone ?? "—"} + + {formatDate(organization.created_at)} + +
+ + { + + } +
+
+

+ {total} entreprise{total > 1 ? "s" : ""} + {loading ? : null} +

+
+ )} +
+ ); +}; diff --git a/frontend/crm/src/styles/index.css b/frontend/crm/src/styles/index.css new file mode 100644 index 0000000..07ea97d --- /dev/null +++ b/frontend/crm/src/styles/index.css @@ -0,0 +1,4 @@ +@import "tailwindcss"; +@import "@cohaise/ui/styles"; + +@source "../../../../frontend/shared/src"; diff --git a/frontend/crm/tsconfig.json b/frontend/crm/tsconfig.json new file mode 100644 index 0000000..ee988a6 --- /dev/null +++ b/frontend/crm/tsconfig.json @@ -0,0 +1,11 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "jsx": "react-jsx", + "types": ["vite/client"], + "noEmit": true + }, + "include": ["src/**/*.ts", "src/**/*.tsx"] +} diff --git a/frontend/crm/vite.config.ts b/frontend/crm/vite.config.ts new file mode 100644 index 0000000..675b291 --- /dev/null +++ b/frontend/crm/vite.config.ts @@ -0,0 +1,19 @@ +import { defineConfig } from "vite"; +import react from "@vitejs/plugin-react"; +import tailwindcss from "@tailwindcss/vite"; + +export default defineConfig({ + plugins: [react(), tailwindcss()], + server: { + host: true, + port: 5175, + // En developpement, l'API CRM tourne sur 3002 ; en production nginx + // intercepte /api/ lui-meme. Meme chemin des deux cotes. + proxy: { + "/api": { + target: "http://127.0.0.1:3202", + changeOrigin: false, + }, + }, + }, +}); diff --git a/frontend/shared/README.md b/frontend/shared/README.md new file mode 100644 index 0000000..4d8571a --- /dev/null +++ b/frontend/shared/README.md @@ -0,0 +1,186 @@ +# @cohaise/ui + +Design system partagé de l'écosystème CoHaiSe. Point d'entrée unique des jetons de style +utilisés par `frontend/web`, `frontend/crm` et `frontend/cloud`, garantissant une identité visuelle +homogène et la thématisation dynamique clair/sombre. + +## Couche de jetons + +Ce paquet expose une chaîne CSS en trois fichiers, du plus primitif au plus dérivé. + +| Fichier | Rôle | +|---|---| +| `src/styles/tokens.css` | Variables CSS brutes (`--cohaise-*`). Échelle de gris en `oklch`, jetons sémantiques, ombres, typographie, rayons, courbes et durées de mouvement. | +| `src/styles/theme.css` | Directive `@theme inline` mappant les variables brutes vers les utilitaires Tailwind (`bg-surface`, `text-muted-foreground`, `border-border`...). | +| `src/styles/index.css` | Point d'entrée, importe les deux fichiers ci-dessus. | + +### Mouvement + +Tailwind v4 ne réserve pas de namespace de thème aux durées : `duration-*` est un +utilitaire à valeur nue. Les trois durées sont donc exposées via `@utility` dans +`theme.css`, adossées aux jetons `--cohaise-duration-*`. + +`--default-transition-duration` et `--default-transition-timing-function` sont +également déclarés, si bien que toute classe `transition-*` hérite du mouvement du +design system sans avoir à le répéter : + +```css +.transition-colors { + transition-timing-function: var(--tw-ease, var(--cohaise-ease-out-soft)); + transition-duration: var(--tw-duration, var(--cohaise-duration-base)); +} +``` + +Les utilitaires `duration-fast`, `duration-base`, `duration-slow` et `ease-out-soft` +surchargent ces valeurs au cas par cas. + +### Chaîne de résolution + +```mermaid +flowchart TD + A["tokens.css
--cohaise-gray-*, --cohaise-crimson-*"] --> B["tokens.css
--cohaise-background, --cohaise-border, ..."] + B --> C["theme.css
@theme inline"] + C --> D["Tailwind CSS
compile les utilitaires"] + D --> E["frontend/web · frontend/crm · frontend/cloud"] + + F["Classe .dark sur <html>"] -.->|surcharge les jetons sémantiques| B +``` + +L'échelle de gris et l'échelle carmin sont les seules sources de vérité des couleurs +brutes. Les jetons sémantiques n'y font référence que par `var()`, jamais par une valeur +littérale, sauf pour les statuts (`success`, `warning`, `info`) et l'ombre carmin, qui +n'existent que dans le mode sombre. + +La source de vérité du rouge est `--clr-accent` du site, soit `#b71c1c`, et non le +carmin `#c3073f` qui apparaît davantage dans la feuille de style compilée. Les deux +valeurs ont été retenues à un moment de la construction du thème : le carmin est plus +vif, la valeur déclarée plus profonde et moins magenta. Sur un outil de gestion de +fichiers, c'est la seconde qui tient le mieux sur de grandes surfaces. + +## Couleurs + +Les valeurs viennent de `esiah.dev`. Le fond sombre est un noir à dominante rouge +(`#050000`), pas un gris neutre, et l'accent est le carmin `#b71c1c`. + +| Rôle | Clair | Sombre | +|---|---|---| +| Fond | `#f7f5f4` | `#050000` | +| Surface | `#ffffff` | `#1a0505` | +| Surface surélevée | `#ffffff` | `#1e1e22` | +| Texte | `#1a1a1a` | `#f4f4f2` | +| Texte atténué | `#5c5656` | `#a8a0a0` | +| Primaire | `#b71c1c` | `#b71c1c` | +| Accent graphique | `#b71c1c` | `#c92a2a` | +| Filet de séparation | `#e8dcdc` | `#2e1c1c` | + +Un seul rouge de marque dans les deux modes, ce qui rend les captures et les +comparaisons d'écran reproductibles. Il n'est appliqué qu'en aplat plein, avec du texte +blanc dessus, où il atteint 6,57:1. + +`accent-graphic` est un ton séparé, réservé aux **petits éléments posés sur** une +surface : filet de carte, carré de liste, anneau de focus. Ces éléments sont lus comme +interface et relèvent du seuil de 3:1, or le rouge de marque ne donne que 2,65:1 sur la +surface sombre. Le même raisonnement impose une bordure de champ distincte, à 3,57:1 en +sombre et 3,73:1 en clair. + +**Le destructif est ambre, pas rouge.** C'est une décision de lisibilité, pas un goût : +l'accent du site est un rouge, donc un bouton « supprimer » rouge serait confondu avec un +bouton d'accent. `destructive` occupe donc le ton `oklch(0.768 0.188 70)`, déjà présent +dans la palette, et `warning` garde le jaune plus clair. Le prix à payer est que +« supprimer » et « attention » sont proches en teinte ; ils ne se croisent jamais dans le +même écran, et c'est un choix à revoir si l'interface grossit. + +**Les bordures de champs de formulaire ont leur propre jeton.** Les bordures +décoratives restent très discrètes, `1.2:1` sur le fond en mode sombre, pour respecter le +grain du site. Un champ de formulaire doit en revanche pouvoir être identifié sans le +remplir ni le survoler, ce que la WCAG 1.4.11 chiffre à `3:1`. `border-control` est +donc nettement plus clair, `3.5:1` en sombre et `3.7:1` en clair, et c'est lui que +`Input` utilise. Les deux valeurs ont été retenues en mesurant le contraste réel plutôt +qu'à l'œil. + +## Polices + +| Usage | Police | Variable | +|---|---|---| +| Titres, libellés, boutons | Orbitron | `--cohaise-font-display` | +| Texte courant et paragraphes | Poppins | `--cohaise-font-sans` | +| Marque | Orbitron | `--cohaise-font-logo` | +| Accroche courte, registre éditorial | Cinzel | `--cohaise-font-serif` | +| Code | JetBrains Mono et replis | `--cohaise-font-mono` | + +Le partage vient du site, où `body` est en Orbitron. Orbitron a une chasse très large : à +32 px, un titre paraît écrit à la main, et un mot-symbole doit être resserré pour ne pas +s'éparpiller. D'où quatre jetons d'interlettrage dédiés, dont un négatif pour les titres. + +Orbitron est donc cantonnée aux **chaînes courtes** — titres jusqu'à `h3`, libellés en +capitales, boutons — avec `tracking-label` en positif. Au-delà de `h3`, la chasse est trop +large pour la taille du texte. Le flux est en Poppins. C'est pourquoi `font-display` est +appliqué dans la couche `base` plutôt que laissé au soin de chaque composant : c'est la +seule façon d'éviter qu'un titre revienne en Poppins parce qu'un écran l'a oublié. + +Cinzel est conservée en réserve. C'est un bon caractère, mais une serif d'inscription +romaine sur des libellés d'interface ou un paragraphe devient vite illisible, et c'est +précisément ce qui donnait au premier jet de ce thème son aspect de thème généré. + +Les trois faces sont **auto-hébergées** dans `frontend/shared/fonts`, 53,6 Ko au total, +soit 30 Ko de moins que Roboto seul. Un appel à Google Fonts aurait fait fuiter l'adresse +IP de chaque visiteur de ton NAS vers un tiers, ce qui n'a pas sa place dans un écosystème +privé. + +## Modes clair et sombre + +Le mode est piloté par la classe `.dark` appliquée sur ``. `:root` porte le mode +clair, `.dark` surcharge l'ensemble des jetons sémantiques. `color-scheme` est défini +sur les deux blocs pour aligner les contrôles natifs et les barres de défilement. + +```mermaid +flowchart LR + subgraph Light["`:root` — mode clair"] + LA["--cohaise-background
#f7f5f4"] + LB["--cohaise-foreground
#1a1a1a"] + LC["--cohaise-primary
#b71c1c"] + end + subgraph Dark["`.dark` — mode sombre"] + DA["--cohaise-background
#050000"] + DB["--cohaise-foreground
#f4f4f2"] + DC["--cohaise-primary
#b71c1c"] + end + Light -->|bascule de classe| Dark +``` + +Aucune règle `@media (prefers-color-scheme)` n'est déclarée : la bascule est +explicite, ce qui garantit un comportement unique quelle que soit la préférence +système. + +## Forme + +Les rayons sont quasi nuls, de 2 à 6 px, contre 4 à 12 px pour les valeurs par défaut de +Tailwind. Les tuiles à coins arrondis sont la signature la plus immédiate d'une interface +sans intention, et un registre d'instrument se lit dans l'angle autant que dans la +couleur. + +Trois marques complètent le registre : un filet carmin d'un pixel en tête de `Card`, un +carré plein de 6 px devant chaque élément de liste au lieu d'une puce ronde, et des +libellés en capitales espacées. Aucune n'est décorative au sens strict : elles servent à +séparer des blocs sans ajouter de bordure lourde, et à rendre les métriques denses +scannables. + +## Consommation + +```css +@import "tailwindcss"; +@import "@cohaise/ui/styles"; +``` + +L'application conserve la main sur la directive `tailwindcss` et sur sa configuration ; +ce paquet ne fournit que les jetons. Le build Vite résout l'entrée via le champ +`exports` du `package.json`. + +## Contraintes + +- Aucune valeur de couleur littérale n'est autorisée dans les composants : uniquement + des utilitaires derivés des jetons sémantiques, sinon la thématisation casse. +- `@theme inline` est obligatoire plutôt que `@theme`, car les utilitaires doivent + référencer la variable pour résoudre la valeur au changement de mode. +- Aucune durée ne doit être écrite en dur dans un composant (`duration-150` est + interdit) : passer par `duration-fast`, `duration-base` ou `duration-slow`. diff --git a/frontend/shared/fonts/cinzel-latin.woff2 b/frontend/shared/fonts/cinzel-latin.woff2 new file mode 100644 index 0000000..a54fd00 Binary files /dev/null and b/frontend/shared/fonts/cinzel-latin.woff2 differ diff --git a/frontend/shared/fonts/jetbrains-mono-latin.woff2 b/frontend/shared/fonts/jetbrains-mono-latin.woff2 new file mode 100644 index 0000000..4d09cda Binary files /dev/null and b/frontend/shared/fonts/jetbrains-mono-latin.woff2 differ diff --git a/frontend/shared/fonts/orbitron-latin.woff2 b/frontend/shared/fonts/orbitron-latin.woff2 new file mode 100644 index 0000000..39d9db5 Binary files /dev/null and b/frontend/shared/fonts/orbitron-latin.woff2 differ diff --git a/frontend/shared/fonts/poppins-400.woff2 b/frontend/shared/fonts/poppins-400.woff2 new file mode 100644 index 0000000..b69e009 Binary files /dev/null and b/frontend/shared/fonts/poppins-400.woff2 differ diff --git a/frontend/shared/fonts/poppins-600.woff2 b/frontend/shared/fonts/poppins-600.woff2 new file mode 100644 index 0000000..921e962 Binary files /dev/null and b/frontend/shared/fonts/poppins-600.woff2 differ diff --git a/frontend/shared/package.json b/frontend/shared/package.json new file mode 100644 index 0000000..de83787 --- /dev/null +++ b/frontend/shared/package.json @@ -0,0 +1,38 @@ +{ + "name": "@cohaise/ui", + "version": "0.0.0", + "private": true, + "type": "module", + "sideEffects": ["**/*.css"], + "style": "./src/styles/index.css", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./styles": "./src/styles/index.css", + "./styles/tokens": "./src/styles/tokens.css", + "./styles/theme": "./src/styles/theme.css" + }, + "files": ["dist", "src/styles"], + "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" + }, + "peerDependencies": { + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "react": "^19.3.0", + "react-dom": "^19.3.0", + "typescript": "^7.0.2" + }, + "dependencies": { + "clsx": "^2.1.1", + "tailwind-merge": "^3.7.0" + } +} diff --git a/frontend/shared/src/components/Button.tsx b/frontend/shared/src/components/Button.tsx new file mode 100644 index 0000000..1a656c0 --- /dev/null +++ b/frontend/shared/src/components/Button.tsx @@ -0,0 +1,72 @@ +import type { ButtonHTMLAttributes, ReactNode } from "react"; +import { cn } from "../lib/cn.js"; +import { Spinner } from "./Spinner.js"; +import type { SpinnerSize } from "./Spinner.js"; + +const variantClasses = { + primary: "bg-primary text-primary-foreground hover:bg-primary-hover", + secondary: "border border-border-strong bg-surface text-foreground hover:bg-surface-hover", + ghost: "text-foreground hover:bg-surface-hover", + destructive: "bg-destructive text-destructive-foreground hover:bg-destructive-hover", +} as const; + +const sizeClasses = { + sm: "h-8 gap-1.5 rounded-sm px-3 text-[0.6875rem]", + md: "h-10 gap-2 rounded-md px-4 text-xs", + lg: "h-12 gap-2.5 rounded-lg px-6 text-sm", +} as const; + +const spinnerBySize: Record = { + sm: "xs", + md: "sm", + lg: "md", +}; + +export type ButtonVariant = keyof typeof variantClasses; +export type ButtonSize = keyof typeof sizeClasses; + +export interface ButtonProps extends ButtonHTMLAttributes { + variant?: ButtonVariant; + size?: ButtonSize; + isLoading?: boolean; + showTextWhileLoading?: boolean; + iconLeading?: ReactNode; + iconTrailing?: ReactNode; + fullWidth?: boolean; +} + +export const Button = ({ + variant = "primary", + size = "md", + isLoading = false, + showTextWhileLoading = true, + iconLeading, + iconTrailing, + fullWidth = false, + disabled, + type = "button", + className, + children, + ...props +}: ButtonProps) => ( + +); diff --git a/frontend/shared/src/components/Card.tsx b/frontend/shared/src/components/Card.tsx new file mode 100644 index 0000000..739f83f --- /dev/null +++ b/frontend/shared/src/components/Card.tsx @@ -0,0 +1,49 @@ +import type { HTMLAttributes } from "react"; +import { cn } from "../lib/cn.js"; + +export const Card = ({ className, ...props }: HTMLAttributes) => ( +
+); + +/* Signature du produit : un filet carmin d'un pixel en tete de carte. Invisible sur + une grille dense, mais c'est lui qui donne aux cartes leur epaisseur et evite + l'aspect de tuiles interchangeables. */ +export const CardHeader = ({ className, ...props }: HTMLAttributes) => ( +
+); + +export const CardTitle = ({ className, ...props }: HTMLAttributes) => ( +

+); + +export const CardDescription = ({ className, ...props }: HTMLAttributes) => ( +

+); + +export const CardContent = ({ className, ...props }: HTMLAttributes) => ( +

+); + +export const CardFooter = ({ className, ...props }: HTMLAttributes) => ( +
+); diff --git a/frontend/shared/src/components/Input.tsx b/frontend/shared/src/components/Input.tsx new file mode 100644 index 0000000..141afe8 --- /dev/null +++ b/frontend/shared/src/components/Input.tsx @@ -0,0 +1,72 @@ +import { useId } from "react"; +import type { InputHTMLAttributes, ReactNode } from "react"; +import { cn } from "../lib/cn.js"; + +export interface InputProps extends Omit, "size"> { + label?: ReactNode; + hint?: ReactNode; + error?: ReactNode; + sizeVariant?: "sm" | "md" | "lg"; +} + +const inputSize = { + sm: "h-8 px-2.5 text-xs", + md: "h-10 px-3 text-sm", + lg: "h-12 px-4 text-base", +} as const; + +export const Input = ({ + label, + hint, + error, + sizeVariant = "md", + id, + className, + disabled, + ...props +}: InputProps) => { + const generatedId = useId(); + const inputId = id ?? generatedId; + const messageId = `${inputId}-message`; + const isInvalid = error !== undefined && error !== null && error !== ""; + + return ( +
+ {label ? ( + + ) : null} + + + + {isInvalid || hint ? ( +

+ {isInvalid ? error : hint} +

+ ) : null} +
+ ); +}; diff --git a/frontend/shared/src/components/Skeleton.tsx b/frontend/shared/src/components/Skeleton.tsx new file mode 100644 index 0000000..71a7c09 --- /dev/null +++ b/frontend/shared/src/components/Skeleton.tsx @@ -0,0 +1,32 @@ +import type { HTMLAttributes } from "react"; +import { cn } from "../lib/cn.js"; + +export type SkeletonProps = HTMLAttributes & { + width?: string; + height?: string; + radius?: "sm" | "md" | "lg" | "xl" | "full"; +}; + +const skeletonRadius = { + sm: "rounded-sm", + md: "rounded-md", + lg: "rounded-lg", + xl: "rounded-xl", + full: "rounded-full", +} as const; + +export const Skeleton = ({ + width, + height, + radius = "md", + className, + style, + ...props +}: SkeletonProps) => ( +