ci: run on the cohaise runner label #1
@@ -0,0 +1,52 @@
|
||||
name: PR — Ouverture automatique
|
||||
|
||||
on:
|
||||
push:
|
||||
branches-ignore: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
create-pr:
|
||||
runs-on: cohaise
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Ouvrir (ou vérifier) la pull request
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
API: ${{ github.server_url }}/api/v1
|
||||
REPO: ${{ github.repository }}
|
||||
BRANCH: ${{ github.ref_name }}
|
||||
run: |
|
||||
set -eu
|
||||
if [ "$BRANCH" = "main" ]; then
|
||||
echo "main est la base : aucune PR à ouvrir."
|
||||
exit 0
|
||||
fi
|
||||
title=$(git log -1 --pretty=%s)
|
||||
body=$(git log -1 --pretty=%b)
|
||||
[ -n "$body" ] || body="PR automatique de $BRANCH vers main."
|
||||
|
||||
open=$(curl -fsS -H "Authorization: token $GITEA_TOKEN" \
|
||||
"$API/repos/$REPO/pulls?state=open&limit=50" \
|
||||
| python3 -c 'import json,os,sys; b=os.environ["BRANCH"]; print(sum(1 for p in json.load(sys.stdin) if p.get("head", {}).get("ref") == b))')
|
||||
if [ "$open" -gt 0 ]; then
|
||||
echo "Une PR est déjà ouverte pour $BRANCH."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
python3 - "$BRANCH" "$title" "$body" <<'PY' | curl -fsS -X POST \
|
||||
-H "Authorization: token $GITEA_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
--data-binary @- \
|
||||
"$API/repos/$REPO/pulls"
|
||||
import json, sys
|
||||
branch, title, body = sys.argv[1], sys.argv[2], sys.argv[3]
|
||||
print(json.dumps({"base": "main", "head": branch, "title": title, "body": body}))
|
||||
PY
|
||||
echo "PR créée."
|
||||
@@ -3,6 +3,8 @@ dist/
|
||||
build/
|
||||
coverage/
|
||||
.vite/
|
||||
.next/
|
||||
out/
|
||||
*.tsbuildinfo
|
||||
|
||||
# Sauvegardes de base : contiennent les donnees, jamais versionnees.
|
||||
|
||||
@@ -16,14 +16,15 @@ help:
|
||||
@echo " make up Demarrer la vitrine"
|
||||
@echo " make down Arreter la vitrine"
|
||||
@echo " make web Reconstruire et publier la vitrine"
|
||||
@echo " make build Construire les images (ne publie rien)"
|
||||
@echo " make deploy Build + demarrage"
|
||||
@echo " make dev Vite vitrine (5173)"
|
||||
@echo " make dev Next.js vitrine (3000)"
|
||||
@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-migrate Migrer la base et recharger l'API"
|
||||
@echo " make crm-backup Sauvegarder la base"
|
||||
@echo " make crm-admin ARGS=... Creer ou reinitialiser un compte"
|
||||
@echo " make crm-dev Vite CRM (5175)"
|
||||
@@ -90,8 +91,9 @@ crm-db:
|
||||
$(CRM) restart db
|
||||
|
||||
crm-migrate:
|
||||
$(CRM) build migrate
|
||||
$(CRM) build api migrate
|
||||
$(CRM) run --rm migrate
|
||||
$(CRM) up -d --no-deps api
|
||||
|
||||
crm-backup:
|
||||
@mkdir -p backups
|
||||
|
||||
@@ -6,7 +6,7 @@ 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` |
|
||||
| Vitrine | `cohaise.dev` | Next.js (export 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é.
|
||||
@@ -16,14 +16,14 @@ Le dépôt `CoHaiSe-CLOUD` (`cloud.cohaise.dev`) reste séparé.
|
||||
```
|
||||
frontend/
|
||||
shared/ @cohaise/ui — design system, jetons et composants partagés
|
||||
web/ @cohaise/web — la vitrine (statique, bilingue FR/EN)
|
||||
web/ @cohaise/web — la vitrine (Next.js, 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.app build Next/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)
|
||||
@@ -32,10 +32,13 @@ docker/
|
||||
|
||||
## 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.
|
||||
La vitrine est un site Next.js en export statique, sans base ni session. Routes
|
||||
dédiées : `/`, `/services`, `/demos`, `/stack`, `/about`, `/contact`. Les
|
||||
métadonnées, le sitemap, `robots.txt` et l'image Open Graph sont générés par
|
||||
Next. Elle est bilingue (FR par défaut, EN) via un toggle client, et porte le
|
||||
thème « liquid glass » carmin du design system. Les animations d'entrée
|
||||
(fade-in-up au threshold) et le smooth scroll par section respectent
|
||||
`prefers-reduced-motion`.
|
||||
|
||||
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'`.
|
||||
@@ -44,7 +47,7 @@ le lead est posé dans `contacts` avec `external_source = 'cohaise-web'`.
|
||||
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
|
||||
make dev # serveur Next local, port 3000
|
||||
```
|
||||
|
||||
## CRM
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Réglages applicatifs du CRM. Les secrets et paramètres d'environnement
|
||||
* restent dans `@cohaise/server` (voir `config.ts`) : ce fichier ne contient
|
||||
* que des constantes métier, sans dépendance à l'environnement.
|
||||
*/
|
||||
|
||||
/** Taille de page par défaut des listes paginées. */
|
||||
export const DEFAULT_PAGE_SIZE = 25;
|
||||
|
||||
/** Plafond de page pour éviter les requêtes trop larges. */
|
||||
export const MAX_PAGE_SIZE = 100;
|
||||
|
||||
/** Source externe des prospects créés par le formulaire de la vitrine. */
|
||||
export const PUBLIC_LEAD_SOURCE = "cohaise-web";
|
||||
|
||||
/** Anti-abus du formulaire public : 5 envois par IP et par quart d'heure. */
|
||||
export const PUBLIC_LEAD_RATE_LIMIT = {
|
||||
windowMs: 15 * 60 * 1000,
|
||||
max: 5,
|
||||
} as const;
|
||||
@@ -1,11 +1,11 @@
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { purgeExpiredSessions, startService } from "@cohaise/server";
|
||||
import { registerAuthRoutes } from "./routes/auth.js";
|
||||
import { registerCountryRoutes } from "./routes/countries.js";
|
||||
import { registerOrganizationRoutes } from "./routes/organizations.js";
|
||||
import { registerContactRoutes } from "./routes/contacts.js";
|
||||
import { registerLeadRoutes } from "./routes/leads.js";
|
||||
import { registerAuthRoutes } from "./routes/authRoutes.js";
|
||||
import { registerCountryRoutes } from "./routes/countryRoutes.js";
|
||||
import { registerOrganizationRoutes } from "./routes/organizationRoutes.js";
|
||||
import { registerContactRoutes } from "./routes/contactRoutes.js";
|
||||
import { registerLeadRoutes } from "./routes/leadRoutes.js";
|
||||
|
||||
const migrationsDir = join(dirname(fileURLToPath(import.meta.url)), "../migrations");
|
||||
|
||||
@@ -18,8 +18,8 @@ void startService({
|
||||
registerOrganizationRoutes(app, db);
|
||||
registerContactRoutes(app, db);
|
||||
registerLeadRoutes(app, db);
|
||||
// Les jetons expires n'ont rien a faire en base : purge au demarrage
|
||||
// plutot qu'un EVENT, qui dependrait du planificateur MariaDB.
|
||||
// Les jetons expirés n'ont rien à faire en base : purge au démarrage
|
||||
// plutôt qu'un EVENT, qui dépendrait du planificateur MariaDB.
|
||||
void purgeExpiredSessions(db);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Porte d'authentification appliquée à une ressource protégée.
|
||||
*
|
||||
* `attachUser` est monté sur le chemin exact et sur ses sous-chemins : Hono
|
||||
* n'hérite pas automatiquement du middleware d'un préfixe. Le contrôle fin
|
||||
* (`requireAuth`) reste déclaré au niveau de chaque route, comme avant.
|
||||
*/
|
||||
import { attachUser, type App, type Db } from "@cohaise/server";
|
||||
|
||||
export const mountSession = (app: App, db: Db, basePath: string): void => {
|
||||
app.use(`${basePath}/*`, attachUser(db));
|
||||
app.use(basePath, attachUser(db));
|
||||
};
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Lignes de base de données et formes exposées par l'API.
|
||||
*
|
||||
* Les colonnes gardent leur nom SQL (`first_name`, `phone_code`, …) : les
|
||||
* services les convertissent au plus près du SELECT, jamais dans les routes.
|
||||
*/
|
||||
|
||||
export interface UserRow {
|
||||
id: string;
|
||||
email: string;
|
||||
password_hash: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
is_active: number;
|
||||
must_change_password: number;
|
||||
}
|
||||
|
||||
/** Utilisateur renvoyé au client : jamais de hash ni de drapeau interne. */
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
must_change_password: boolean;
|
||||
}
|
||||
|
||||
export interface CountryRow {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
phone_code: string | null;
|
||||
}
|
||||
|
||||
export interface OrganizationRow {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
website: string | null;
|
||||
industry: string | null;
|
||||
phone: string | null;
|
||||
email: string | null;
|
||||
address_line1: string | null;
|
||||
address_line2: string | null;
|
||||
postal_code: string | null;
|
||||
city: string | null;
|
||||
country_id: number | null;
|
||||
country_name: string | null;
|
||||
country_code: string | null;
|
||||
description: string | null;
|
||||
owner_id: string | null;
|
||||
owner_name: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface ContactRow {
|
||||
id: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
organization_id: string | null;
|
||||
organization_name: string | null;
|
||||
email: string | null;
|
||||
phone: string | null;
|
||||
mobile: string | null;
|
||||
job_title: string | null;
|
||||
country_id: number | null;
|
||||
country_name: string | null;
|
||||
country_code: string | null;
|
||||
external_source: string | null;
|
||||
external_id: string | null;
|
||||
description: string | null;
|
||||
owner_id: string | null;
|
||||
owner_name: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
/** Corps du formulaire public de la vitrine. */
|
||||
export interface LeadInput {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
organization?: string | null | undefined;
|
||||
phone?: string | null | undefined;
|
||||
message?: string | null | undefined;
|
||||
/** Honeypot : rempli uniquement par les robots. */
|
||||
website?: string | null | undefined;
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
AppError,
|
||||
attachUser,
|
||||
clearSessionCookie,
|
||||
createSession,
|
||||
currentUser,
|
||||
hashPassword,
|
||||
isHttpsRequest,
|
||||
requireAuth,
|
||||
revokeSession,
|
||||
setSessionCookie,
|
||||
sha256,
|
||||
verifyPassword,
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
} from "@cohaise/server";
|
||||
|
||||
const credentials = z.object({
|
||||
email: z.string().trim().toLowerCase().email().max(255),
|
||||
password: z.string().min(1).max(1024),
|
||||
});
|
||||
|
||||
const changePassword = z.object({
|
||||
current: z.string().min(1).max(1024),
|
||||
next: z.string().min(8).max(1024),
|
||||
});
|
||||
|
||||
interface UserRow {
|
||||
id: string;
|
||||
email: string;
|
||||
password_hash: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
is_active: number;
|
||||
must_change_password: number;
|
||||
}
|
||||
|
||||
const SELECT_USER = `
|
||||
SELECT u.id, u.email, u.password_hash, u.first_name, u.last_name,
|
||||
u.is_active, u.must_change_password
|
||||
FROM users u`;
|
||||
|
||||
/**
|
||||
* Empreinte de repli, calculee pour n'importe quelle chaine : une adresse
|
||||
* inconnue doit prendre exactement le meme temps qu'une adresse connue avec
|
||||
* un mauvais mot de passe, sinon l'API devient un annuaire.
|
||||
*/
|
||||
const DUMMY_HASH_PROMISE = hashPassword("placeholder-for-anti-enumeration").catch(() => null);
|
||||
void DUMMY_HASH_PROMISE;
|
||||
|
||||
const publicUser = (row: UserRow) => ({
|
||||
id: row.id,
|
||||
email: row.email,
|
||||
first_name: row.first_name,
|
||||
last_name: row.last_name,
|
||||
must_change_password: row.must_change_password === 1,
|
||||
});
|
||||
|
||||
export const registerAuthRoutes = (app: App, db: Db, config: Config): void => {
|
||||
app.use("/api/crm/auth/*", attachUser(db));
|
||||
|
||||
app.post("/api/crm/auth/login", async (context) => {
|
||||
const parsed = credentials.safeParse(await context.req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
throw AppError.badRequest("Identifiants invalides.");
|
||||
}
|
||||
|
||||
const row = await db.one<UserRow>(
|
||||
`${SELECT_USER} WHERE u.email = ? AND u.deleted_at IS NULL`,
|
||||
[parsed.data.email],
|
||||
);
|
||||
|
||||
const stored = row?.password_hash ?? (await DUMMY_HASH_PROMISE) ?? "";
|
||||
const valid = stored ? await verifyPassword(parsed.data.password, stored) : false;
|
||||
if (!row || !valid) throw AppError.unauthorized("Identifiants invalides.");
|
||||
if (row.is_active !== 1) throw AppError.unauthorized("Compte desactive.");
|
||||
|
||||
const { token, expiresAt } = await createSession(
|
||||
db,
|
||||
row.id,
|
||||
{
|
||||
ipAddress: context.req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? null,
|
||||
userAgent: context.req.header("user-agent") ?? null,
|
||||
},
|
||||
config.SESSION_TTL_HOURS,
|
||||
);
|
||||
await db.exec("UPDATE users SET last_login_at = UTC_TIMESTAMP(3) WHERE id = ?", [row.id]);
|
||||
|
||||
// Le schema reel de la requete, pas PUBLIC_ORIGIN : voir isHttpsRequest.
|
||||
const secure = isHttpsRequest(context, config.TRUST_PROXY);
|
||||
setSessionCookie(context, token, expiresAt, secure);
|
||||
|
||||
return context.json({ user: publicUser(row) });
|
||||
});
|
||||
|
||||
app.post("/api/crm/auth/logout", requireAuth, async (context) => {
|
||||
const token = context.get("token") as string | undefined;
|
||||
if (token) await revokeSession(db, token);
|
||||
clearSessionCookie(context);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
|
||||
app.get("/api/crm/auth/me", requireAuth, async (context) => {
|
||||
const session = currentUser(context);
|
||||
const row = await db.one<UserRow>(`${SELECT_USER} WHERE u.id = ? AND u.deleted_at IS NULL`, [
|
||||
session.id,
|
||||
]);
|
||||
if (!row) throw AppError.unauthorized();
|
||||
return context.json({ user: publicUser(row) });
|
||||
});
|
||||
|
||||
app.post("/api/crm/auth/change-password", requireAuth, async (context) => {
|
||||
const session = currentUser(context);
|
||||
const parsed = changePassword.safeParse(await context.req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
throw AppError.badRequest("Le nouveau mot de passe doit contenir au moins 8 caracteres.");
|
||||
}
|
||||
|
||||
const row = await db.one<{ password_hash: string }>(
|
||||
"SELECT password_hash FROM users WHERE id = ? AND deleted_at IS NULL",
|
||||
[session.id],
|
||||
);
|
||||
if (!row) throw AppError.unauthorized();
|
||||
|
||||
if (!(await verifyPassword(parsed.data.current, row.password_hash))) {
|
||||
throw AppError.unauthorized("Mot de passe actuel incorrect.");
|
||||
}
|
||||
if (parsed.data.current === parsed.data.next) {
|
||||
throw AppError.badRequest("Le nouveau mot de passe doit differer de l'actuel.");
|
||||
}
|
||||
|
||||
const hash = await hashPassword(parsed.data.next);
|
||||
// Pas de password_changed_at ici : cette colonne appartient au modele du
|
||||
// Cloud. Le CRM n'a pas de notion de confirmation d'identite a celebrer.
|
||||
await db.exec("UPDATE users SET password_hash = ?, must_change_password = 0 WHERE id = ?", [
|
||||
hash,
|
||||
session.id,
|
||||
]);
|
||||
// La session courante est conservee, toutes les autres sont revoquees.
|
||||
await db.exec(
|
||||
`UPDATE user_sessions
|
||||
SET revoked_at = UTC_TIMESTAMP()
|
||||
WHERE user_id = ? AND revoked_at IS NULL AND token_hash <> ?`,
|
||||
[session.id, sha256(context.get("token") ?? "")],
|
||||
);
|
||||
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,83 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
AppError,
|
||||
clearSessionCookie,
|
||||
currentUser,
|
||||
isHttpsRequest,
|
||||
requireAuth,
|
||||
setSessionCookie,
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
} from "@cohaise/server";
|
||||
import { mountSession } from "../middleware/auth.js";
|
||||
import {
|
||||
changePassword,
|
||||
getSessionUser,
|
||||
login,
|
||||
logout,
|
||||
} from "../services/authService.js";
|
||||
|
||||
const credentials = z.object({
|
||||
email: z.string().trim().toLowerCase().email().max(255),
|
||||
password: z.string().min(1).max(1024),
|
||||
});
|
||||
|
||||
const newPassword = z.object({
|
||||
current: z.string().min(1).max(1024),
|
||||
next: z.string().min(8).max(1024),
|
||||
});
|
||||
|
||||
export const registerAuthRoutes = (app: App, db: Db, config: Config): void => {
|
||||
mountSession(app, db, "/api/crm/auth");
|
||||
|
||||
app.post("/api/crm/auth/login", async (context) => {
|
||||
const parsed = credentials.safeParse(await context.req.json().catch(() => null));
|
||||
if (!parsed.success) throw AppError.badRequest("Identifiants invalides.");
|
||||
|
||||
const result = await login(db, config, {
|
||||
email: parsed.data.email,
|
||||
password: parsed.data.password,
|
||||
ipAddress: context.req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? null,
|
||||
userAgent: context.req.header("user-agent") ?? null,
|
||||
});
|
||||
|
||||
// Le schéma réel de la requête, pas PUBLIC_ORIGIN : voir isHttpsRequest.
|
||||
const secure = isHttpsRequest(context, config.TRUST_PROXY);
|
||||
setSessionCookie(context, result.token, result.expiresAt, secure);
|
||||
|
||||
return context.json({ user: result.user });
|
||||
});
|
||||
|
||||
app.post("/api/crm/auth/logout", requireAuth, async (context) => {
|
||||
await logout(db, context.get("token"));
|
||||
clearSessionCookie(context);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
|
||||
app.get("/api/crm/auth/me", requireAuth, async (context) => {
|
||||
const session = currentUser(context);
|
||||
const user = await getSessionUser(db, session.id);
|
||||
return context.json({ user });
|
||||
});
|
||||
|
||||
app.post("/api/crm/auth/change-password", requireAuth, async (context) => {
|
||||
const session = currentUser(context);
|
||||
const parsed = newPassword.safeParse(await context.req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
throw AppError.badRequest(
|
||||
"Le nouveau mot de passe doit contenir au moins 8 caracteres.",
|
||||
);
|
||||
}
|
||||
|
||||
await changePassword(
|
||||
db,
|
||||
session.id,
|
||||
context.get("token"),
|
||||
parsed.data.current,
|
||||
parsed.data.next,
|
||||
);
|
||||
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,106 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
AppError,
|
||||
currentUser,
|
||||
requireAuth,
|
||||
type App,
|
||||
type Db,
|
||||
} from "@cohaise/server";
|
||||
import { mountSession } from "../middleware/auth.js";
|
||||
import {
|
||||
createContact,
|
||||
deleteContact,
|
||||
getContact,
|
||||
listContacts,
|
||||
toPublicContact,
|
||||
updateContact,
|
||||
} from "../services/contactService.js";
|
||||
import { parsePagination } from "../utils/pagination.js";
|
||||
import { invalidBody, uuidSchema } from "../utils/validation.js";
|
||||
|
||||
const createContactBody = z.object({
|
||||
firstName: z.string().trim().min(1).max(100),
|
||||
lastName: z.string().trim().min(1).max(100),
|
||||
organizationId: uuidSchema.nullish(),
|
||||
email: z.string().trim().max(255).nullish(),
|
||||
phone: z.string().trim().max(50).nullish(),
|
||||
mobile: z.string().trim().max(50).nullish(),
|
||||
jobTitle: z.string().trim().max(150).nullish(),
|
||||
countryId: z.coerce.number().int().positive().nullish(),
|
||||
externalSource: z.string().trim().max(50).nullish(),
|
||||
externalId: z.string().trim().max(100).nullish(),
|
||||
description: z.string().trim().max(4000).nullish(),
|
||||
});
|
||||
|
||||
const updateContactBody = createContactBody.partial();
|
||||
|
||||
export const registerContactRoutes = (app: App, db: Db): void => {
|
||||
mountSession(app, db, "/api/crm/contacts");
|
||||
|
||||
app.get("/api/crm/contacts", requireAuth, async (context) => {
|
||||
const pagination = parsePagination(
|
||||
context.req.query("page"),
|
||||
context.req.query("limit"),
|
||||
);
|
||||
const { total, contacts } = await listContacts(
|
||||
db,
|
||||
{
|
||||
search: context.req.query("q")?.trim() ?? "",
|
||||
organizationId: context.req.query("organizationId")?.trim() ?? "",
|
||||
},
|
||||
pagination,
|
||||
);
|
||||
|
||||
return context.json({
|
||||
total,
|
||||
page: pagination.page,
|
||||
limit: pagination.limit,
|
||||
contacts: contacts.map(toPublicContact),
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/crm/contacts/:id", requireAuth, async (context) => {
|
||||
const id = context.req.param("id");
|
||||
if (!id || !uuidSchema.safeParse(id).success) {
|
||||
throw AppError.notFound("Prospect introuvable.");
|
||||
}
|
||||
const contact = await getContact(db, id);
|
||||
return context.json({ contact: toPublicContact(contact) });
|
||||
});
|
||||
|
||||
app.post("/api/crm/contacts", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const parsed = createContactBody.safeParse(
|
||||
await context.req.json().catch(() => null),
|
||||
);
|
||||
if (!parsed.success) throw invalidBody(parsed.error);
|
||||
|
||||
const contact = await createContact(db, user.id, parsed.data);
|
||||
return context.json({ contact: toPublicContact(contact) }, 201);
|
||||
});
|
||||
|
||||
app.patch("/api/crm/contacts/:id", requireAuth, async (context) => {
|
||||
const id = context.req.param("id");
|
||||
if (!id || !uuidSchema.safeParse(id).success) {
|
||||
throw AppError.notFound("Prospect introuvable.");
|
||||
}
|
||||
|
||||
const parsed = updateContactBody.safeParse(
|
||||
await context.req.json().catch(() => null),
|
||||
);
|
||||
if (!parsed.success) throw invalidBody(parsed.error);
|
||||
|
||||
const contact = await updateContact(db, id, parsed.data);
|
||||
return context.json({ contact: toPublicContact(contact) });
|
||||
});
|
||||
|
||||
app.delete("/api/crm/contacts/:id", requireAuth, async (context) => {
|
||||
const id = context.req.param("id");
|
||||
if (!id || !uuidSchema.safeParse(id).success) {
|
||||
throw AppError.notFound("Prospect introuvable.");
|
||||
}
|
||||
|
||||
await deleteContact(db, id);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
};
|
||||
@@ -1,274 +0,0 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
AppError,
|
||||
attachUser,
|
||||
currentUser,
|
||||
requireAuth,
|
||||
type App,
|
||||
type Db,
|
||||
} from "@cohaise/server";
|
||||
|
||||
const uuid = z
|
||||
.string()
|
||||
.regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, "Identifiant invalide.");
|
||||
|
||||
const createContact = z.object({
|
||||
firstName: z.string().trim().min(1).max(100),
|
||||
lastName: z.string().trim().min(1).max(100),
|
||||
organizationId: z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i).nullish(),
|
||||
email: z.string().trim().max(255).nullish(),
|
||||
phone: z.string().trim().max(50).nullish(),
|
||||
mobile: z.string().trim().max(50).nullish(),
|
||||
jobTitle: z.string().trim().max(150).nullish(),
|
||||
countryId: z.coerce.number().int().positive().nullish(),
|
||||
externalSource: z.string().trim().max(50).nullish(),
|
||||
externalId: z.string().trim().max(100).nullish(),
|
||||
description: z.string().trim().max(4000).nullish(),
|
||||
});
|
||||
|
||||
const updateContact = createContact.partial();
|
||||
|
||||
interface ContactRow {
|
||||
id: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
organization_id: string | null;
|
||||
organization_name: string | null;
|
||||
email: string | null;
|
||||
phone: string | null;
|
||||
mobile: string | null;
|
||||
job_title: string | null;
|
||||
country_id: number | null;
|
||||
country_name: string | null;
|
||||
country_code: string | null;
|
||||
external_source: string | null;
|
||||
external_id: string | null;
|
||||
description: string | null;
|
||||
owner_id: string | null;
|
||||
owner_name: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
const SELECT_CONTACT = `
|
||||
SELECT ct.id, ct.first_name, ct.last_name, ct.organization_id,
|
||||
o.name AS organization_name, ct.email, ct.phone, ct.mobile, ct.job_title,
|
||||
ct.country_id, c.name AS country_name, c.code AS country_code,
|
||||
ct.external_source, ct.external_id, ct.description, ct.owner_id,
|
||||
CONCAT(u.first_name, ' ', u.last_name) AS owner_name,
|
||||
ct.created_at, ct.updated_at
|
||||
FROM contacts ct
|
||||
LEFT JOIN organizations o ON o.id = ct.organization_id AND o.deleted_at IS NULL
|
||||
LEFT JOIN countries c ON c.id = ct.country_id
|
||||
LEFT JOIN users u ON u.id = ct.owner_id`;
|
||||
|
||||
const publicContact = (row: ContactRow) => ({
|
||||
id: row.id,
|
||||
first_name: row.first_name,
|
||||
last_name: row.last_name,
|
||||
organization_id: row.organization_id,
|
||||
organization_name: row.organization_name,
|
||||
email: row.email,
|
||||
phone: row.phone,
|
||||
mobile: row.mobile,
|
||||
job_title: row.job_title,
|
||||
country_id: row.country_id,
|
||||
country_name: row.country_name,
|
||||
country_code: row.country_code,
|
||||
external_source: row.external_source,
|
||||
external_id: row.external_id,
|
||||
description: row.description,
|
||||
owner_id: row.owner_id,
|
||||
owner_name: row.owner_name,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
});
|
||||
|
||||
/** Un e-mail absent ne doit pas heurter l'index actif : NULL passe partout. */
|
||||
const emailOrNull = (value: string | null | undefined): string | null =>
|
||||
value ? value.toLowerCase() : null;
|
||||
|
||||
export const registerContactRoutes = (app: App, db: Db): void => {
|
||||
app.use("/api/crm/contacts/*", attachUser(db));
|
||||
app.use("/api/crm/contacts", attachUser(db));
|
||||
|
||||
app.get("/api/crm/contacts", requireAuth, async (context) => {
|
||||
const search = context.req.query("q")?.trim() ?? "";
|
||||
const organizationId = context.req.query("organizationId")?.trim() ?? "";
|
||||
const page = Math.max(1, Number(context.req.query("page") ?? 1) || 1);
|
||||
const limit = Math.min(100, Math.max(1, Number(context.req.query("limit") ?? 25) || 25));
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
const clauses = ["ct.deleted_at IS NULL"];
|
||||
const params: unknown[] = [];
|
||||
if (search) {
|
||||
clauses.push(
|
||||
"(ct.first_name LIKE ? OR ct.last_name LIKE ? OR ct.email LIKE ? OR o.name LIKE ?)",
|
||||
);
|
||||
const term = `%${search}%`;
|
||||
params.push(term, term, term, term);
|
||||
}
|
||||
if (uuid.safeParse(organizationId).success) {
|
||||
clauses.push("ct.organization_id = ?");
|
||||
params.push(organizationId);
|
||||
}
|
||||
const where = `WHERE ${clauses.join(" AND ")}`;
|
||||
|
||||
const totalRows = await db.query<{ total: number }>(
|
||||
`SELECT COUNT(*) AS total
|
||||
FROM contacts ct
|
||||
LEFT JOIN organizations o ON o.id = ct.organization_id AND o.deleted_at IS NULL
|
||||
${where}`,
|
||||
params,
|
||||
);
|
||||
const total = Number(totalRows[0]?.total ?? 0);
|
||||
|
||||
const rows = await db.query<ContactRow>(
|
||||
`${SELECT_CONTACT} ${where} ORDER BY ct.last_name, ct.first_name LIMIT ${limit} OFFSET ${offset}`,
|
||||
params,
|
||||
);
|
||||
|
||||
return context.json({
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
contacts: rows.map(publicContact),
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/crm/contacts/:id", requireAuth, async (context) => {
|
||||
const id = context.req.param("id");
|
||||
if (!uuid.safeParse(id).success) throw AppError.notFound("Prospect introuvable.");
|
||||
const row = await db.one<ContactRow>(
|
||||
`${SELECT_CONTACT} WHERE ct.id = ? AND ct.deleted_at IS NULL`,
|
||||
[id],
|
||||
);
|
||||
if (!row) throw AppError.notFound("Prospect introuvable.");
|
||||
return context.json({ contact: publicContact(row) });
|
||||
});
|
||||
|
||||
app.post(
|
||||
"/api/crm/contacts",
|
||||
requireAuth,
|
||||
async (context) => {
|
||||
const user = currentUser(context);
|
||||
const parsed = createContact.safeParse(await context.req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
const issue = parsed.error.issues[0];
|
||||
throw AppError.badRequest(issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.");
|
||||
}
|
||||
const data = parsed.data;
|
||||
|
||||
const id = randomUUID();
|
||||
try {
|
||||
await db.exec(
|
||||
`INSERT INTO contacts
|
||||
(id, first_name, last_name, organization_id, email, phone, mobile, job_title,
|
||||
country_id, external_source, external_id, description, owner_id, created_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[
|
||||
id,
|
||||
data.firstName,
|
||||
data.lastName,
|
||||
data.organizationId ?? null,
|
||||
emailOrNull(data.email),
|
||||
data.phone ?? null,
|
||||
data.mobile ?? null,
|
||||
data.jobTitle ?? null,
|
||||
data.countryId ?? null,
|
||||
data.externalSource ?? null,
|
||||
data.externalId ?? null,
|
||||
data.description ?? null,
|
||||
user.id,
|
||||
user.id,
|
||||
],
|
||||
);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Un prospect actif porte deja cette adresse.");
|
||||
}
|
||||
if ((error as { errno?: number }).errno === 1452) {
|
||||
throw AppError.badRequest("L'entreprise ou le pays reference n'existe pas.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const created = await db.required<ContactRow>(`${SELECT_CONTACT} WHERE ct.id = ?`, [id]);
|
||||
return context.json({ contact: publicContact(created) }, 201);
|
||||
},
|
||||
);
|
||||
|
||||
app.patch(
|
||||
"/api/crm/contacts/:id",
|
||||
requireAuth,
|
||||
async (context) => {
|
||||
const id = context.req.param("id");
|
||||
if (!uuid.safeParse(id).success) throw AppError.notFound("Prospect introuvable.");
|
||||
|
||||
const parsed = updateContact.safeParse(await context.req.json().catch(() => null));
|
||||
if (!parsed.success) throw AppError.badRequest("Corps invalide.");
|
||||
|
||||
const existing = await db.one<{ id: string }>(
|
||||
"SELECT id FROM contacts WHERE id = ? AND deleted_at IS NULL",
|
||||
[id],
|
||||
);
|
||||
if (!existing) throw AppError.notFound("Prospect introuvable.");
|
||||
|
||||
const columns: Record<string, unknown> = {
|
||||
first_name: parsed.data.firstName,
|
||||
last_name: parsed.data.lastName,
|
||||
organization_id: parsed.data.organizationId,
|
||||
email: parsed.data.email === undefined ? undefined : emailOrNull(parsed.data.email),
|
||||
phone: parsed.data.phone,
|
||||
mobile: parsed.data.mobile,
|
||||
job_title: parsed.data.jobTitle,
|
||||
country_id: parsed.data.countryId,
|
||||
external_source: parsed.data.externalSource,
|
||||
external_id: parsed.data.externalId,
|
||||
description: parsed.data.description,
|
||||
};
|
||||
|
||||
const assignments = Object.keys(columns)
|
||||
.filter((key) => columns[key] !== undefined)
|
||||
.map((key) => `${key} = ?`);
|
||||
if (assignments.length === 0) throw AppError.badRequest("Aucune modification fournie.");
|
||||
const values = Object.keys(columns)
|
||||
.filter((key) => columns[key] !== undefined)
|
||||
.map((key) => columns[key]);
|
||||
|
||||
try {
|
||||
await db.exec(
|
||||
`UPDATE contacts SET ${assignments.join(", ")} WHERE id = ? AND deleted_at IS NULL`,
|
||||
[...values, id],
|
||||
);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Un prospect actif porte deja cette adresse.");
|
||||
}
|
||||
if ((error as { errno?: number }).errno === 1452) {
|
||||
throw AppError.badRequest("L'entreprise ou le pays reference n'existe pas.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const updated = await db.required<ContactRow>(`${SELECT_CONTACT} WHERE ct.id = ?`, [id]);
|
||||
return context.json({ contact: publicContact(updated) });
|
||||
},
|
||||
);
|
||||
|
||||
app.delete(
|
||||
"/api/crm/contacts/:id",
|
||||
requireAuth,
|
||||
async (context) => {
|
||||
const id = context.req.param("id");
|
||||
if (!uuid.safeParse(id).success) throw AppError.notFound("Prospect introuvable.");
|
||||
const result = await db.exec(
|
||||
"UPDATE contacts SET deleted_at = UTC_TIMESTAMP() WHERE id = ? AND deleted_at IS NULL",
|
||||
[id],
|
||||
);
|
||||
if (result.affectedRows === 0) throw AppError.notFound("Prospect introuvable.");
|
||||
return context.json({ ok: true });
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -1,150 +0,0 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
AppError,
|
||||
attachUser,
|
||||
requireAuth,
|
||||
type App,
|
||||
type Db,
|
||||
} from "@cohaise/server";
|
||||
|
||||
const createCountry = z.object({
|
||||
code: z
|
||||
.string()
|
||||
.trim()
|
||||
.toUpperCase()
|
||||
.regex(/^[A-Z]{2}$/, "Code ISO 3166-1 alpha-2 attendu, deux lettres."),
|
||||
name: z.string().trim().min(1).max(100),
|
||||
phoneCode: z
|
||||
.string()
|
||||
.trim()
|
||||
.regex(/^\+?[0-9]{1,7}$/, "Indicatif telephonique attendu.")
|
||||
.nullish(),
|
||||
});
|
||||
|
||||
const updateCountry = createCountry.partial();
|
||||
|
||||
interface CountryRow {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
phone_code: string | null;
|
||||
}
|
||||
|
||||
const publicCountry = (row: CountryRow) => ({
|
||||
id: row.id,
|
||||
code: row.code,
|
||||
name: row.name,
|
||||
phone_code: row.phone_code,
|
||||
});
|
||||
|
||||
export const registerCountryRoutes = (app: App, db: Db): void => {
|
||||
app.use("/api/crm/countries/*", attachUser(db));
|
||||
app.use("/api/crm/countries", attachUser(db));
|
||||
|
||||
// Referentiel : lecture ouverte a tout le monde authentifie, ecriture
|
||||
// reservee. Le tri est collationnel, donc sans accent ni casse douteuse.
|
||||
app.get("/api/crm/countries", requireAuth, async (context) => {
|
||||
const search = context.req.query("q")?.trim() ?? "";
|
||||
const where = search ? "WHERE name LIKE ? OR code = ?" : "";
|
||||
const params = search ? [`%${search}%`, search.toUpperCase()] : [];
|
||||
const rows = await db.query<CountryRow>(
|
||||
`SELECT id, code, name, phone_code FROM countries ${where} ORDER BY name`,
|
||||
params,
|
||||
);
|
||||
return context.json({ countries: rows.map(publicCountry) });
|
||||
});
|
||||
|
||||
app.post(
|
||||
"/api/crm/countries",
|
||||
requireAuth,
|
||||
async (context) => {
|
||||
const parsed = createCountry.safeParse(await context.req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
const issue = parsed.error.issues[0];
|
||||
throw AppError.badRequest(issue?.message ?? "Corps invalide.");
|
||||
}
|
||||
|
||||
try {
|
||||
await db.exec("INSERT INTO countries (code, name, phone_code) VALUES (?, ?, ?)", [
|
||||
parsed.data.code,
|
||||
parsed.data.name,
|
||||
parsed.data.phoneCode ?? null,
|
||||
]);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Ce pays existe deja.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const created = await db.required<CountryRow>(
|
||||
"SELECT id, code, name, phone_code FROM countries WHERE code = ?",
|
||||
[parsed.data.code],
|
||||
);
|
||||
return context.json({ country: publicCountry(created) }, 201);
|
||||
},
|
||||
);
|
||||
|
||||
app.patch(
|
||||
"/api/crm/countries/:id",
|
||||
requireAuth,
|
||||
async (context) => {
|
||||
const id = Number(context.req.param("id"));
|
||||
if (!Number.isInteger(id) || id <= 0) throw AppError.notFound("Pays introuvable.");
|
||||
|
||||
const parsed = updateCountry.safeParse(await context.req.json().catch(() => null));
|
||||
if (!parsed.success) throw AppError.badRequest("Corps invalide.");
|
||||
|
||||
const columns: Record<string, unknown> = {
|
||||
code: parsed.data.code,
|
||||
name: parsed.data.name,
|
||||
phone_code: parsed.data.phoneCode,
|
||||
};
|
||||
const assignments = Object.keys(columns)
|
||||
.filter((key) => columns[key] !== undefined)
|
||||
.map((key) => `${key} = ?`);
|
||||
if (assignments.length === 0) throw AppError.badRequest("Aucune modification fournie.");
|
||||
const values = Object.keys(columns)
|
||||
.filter((key) => columns[key] !== undefined)
|
||||
.map((key) => columns[key]);
|
||||
|
||||
try {
|
||||
const result = await db.exec(
|
||||
`UPDATE countries SET ${assignments.join(", ")} WHERE id = ?`,
|
||||
[...values, id],
|
||||
);
|
||||
if (result.affectedRows === 0) throw AppError.notFound("Pays introuvable.");
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Ce code de pays existe deja.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const updated = await db.required<CountryRow>(
|
||||
"SELECT id, code, name, phone_code FROM countries WHERE id = ?",
|
||||
[id],
|
||||
);
|
||||
return context.json({ country: publicCountry(updated) });
|
||||
},
|
||||
);
|
||||
|
||||
app.delete(
|
||||
"/api/crm/countries/:id",
|
||||
requireAuth,
|
||||
async (context) => {
|
||||
const id = Number(context.req.param("id"));
|
||||
if (!Number.isInteger(id) || id <= 0) throw AppError.notFound("Pays introuvable.");
|
||||
try {
|
||||
const result = await db.exec("DELETE FROM countries WHERE id = ?", [id]);
|
||||
if (result.affectedRows === 0) throw AppError.notFound("Pays introuvable.");
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1451) {
|
||||
throw AppError.conflict("Des entreprises ou contacts referencent ce pays.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return context.json({ ok: true });
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,69 @@
|
||||
import { z } from "zod";
|
||||
import { AppError, requireAuth, type App, type Db } from "@cohaise/server";
|
||||
import { mountSession } from "../middleware/auth.js";
|
||||
import {
|
||||
createCountry,
|
||||
deleteCountry,
|
||||
listCountries,
|
||||
toPublicCountry,
|
||||
updateCountry,
|
||||
} from "../services/countryService.js";
|
||||
import { invalidBody } from "../utils/validation.js";
|
||||
|
||||
const createCountryBody = z.object({
|
||||
code: z
|
||||
.string()
|
||||
.trim()
|
||||
.toUpperCase()
|
||||
.regex(/^[A-Z]{2}$/, "Code ISO 3166-1 alpha-2 attendu, deux lettres."),
|
||||
name: z.string().trim().min(1).max(100),
|
||||
phoneCode: z
|
||||
.string()
|
||||
.trim()
|
||||
.regex(/^\+?[0-9]{1,7}$/, "Indicatif telephonique attendu.")
|
||||
.nullish(),
|
||||
});
|
||||
|
||||
const updateCountryBody = createCountryBody.partial();
|
||||
|
||||
export const registerCountryRoutes = (app: App, db: Db): void => {
|
||||
mountSession(app, db, "/api/crm/countries");
|
||||
|
||||
// Référentiel : lecture ouverte à tout le monde authentifié, écriture
|
||||
// réservée.
|
||||
app.get("/api/crm/countries", requireAuth, async (context) => {
|
||||
const rows = await listCountries(db, context.req.query("q") ?? "");
|
||||
return context.json({ countries: rows.map(toPublicCountry) });
|
||||
});
|
||||
|
||||
app.post("/api/crm/countries", requireAuth, async (context) => {
|
||||
const parsed = createCountryBody.safeParse(
|
||||
await context.req.json().catch(() => null),
|
||||
);
|
||||
if (!parsed.success) throw invalidBody(parsed.error);
|
||||
|
||||
const country = await createCountry(db, parsed.data);
|
||||
return context.json({ country: toPublicCountry(country) }, 201);
|
||||
});
|
||||
|
||||
app.patch("/api/crm/countries/:id", requireAuth, async (context) => {
|
||||
const id = Number(context.req.param("id"));
|
||||
if (!Number.isInteger(id) || id <= 0) throw AppError.notFound("Pays introuvable.");
|
||||
|
||||
const parsed = updateCountryBody.safeParse(
|
||||
await context.req.json().catch(() => null),
|
||||
);
|
||||
if (!parsed.success) throw invalidBody(parsed.error);
|
||||
|
||||
const country = await updateCountry(db, id, parsed.data);
|
||||
return context.json({ country: toPublicCountry(country) });
|
||||
});
|
||||
|
||||
app.delete("/api/crm/countries/:id", requireAuth, async (context) => {
|
||||
const id = Number(context.req.param("id"));
|
||||
if (!Number.isInteger(id) || id <= 0) throw AppError.notFound("Pays introuvable.");
|
||||
|
||||
await deleteCountry(db, id);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,51 @@
|
||||
import { z } from "zod";
|
||||
import { AppError, type App, type Db } from "@cohaise/server";
|
||||
import { PUBLIC_LEAD_RATE_LIMIT } from "../config/app.js";
|
||||
import { createLead } from "../services/leadService.js";
|
||||
import { createRateLimiter } from "../utils/rateLimit.js";
|
||||
|
||||
/**
|
||||
* Point d'entrée public du formulaire de contact de la vitrine.
|
||||
*
|
||||
* Route volontairement sans `requireAuth` : n'importe quel visiteur de
|
||||
* cohaise.dev peut créer un prospect. Le honeypot et le rate-limit sont
|
||||
* décrits dans `services/leadService.ts`.
|
||||
*/
|
||||
|
||||
const leadBody = z.object({
|
||||
firstName: z.string().trim().min(1).max(100),
|
||||
lastName: z.string().trim().min(1).max(100),
|
||||
email: z.string().trim().min(1).max(255),
|
||||
organization: z.string().trim().min(1).max(255).nullish(),
|
||||
phone: z.string().trim().max(50).nullish(),
|
||||
message: z.string().trim().max(4000).nullish(),
|
||||
// Honeypot : vide chez un humain, rempli par un robot.
|
||||
website: z.string().max(255).nullish(),
|
||||
});
|
||||
|
||||
// Une instance unique par processus : suffisant pour un CRM à un seul nœud.
|
||||
const limiter = createRateLimiter(PUBLIC_LEAD_RATE_LIMIT);
|
||||
|
||||
export const registerLeadRoutes = (app: App, db: Db): void => {
|
||||
app.post("/api/crm/leads", async (context) => {
|
||||
const forwarded = context.req.header("x-forwarded-for");
|
||||
const ip =
|
||||
forwarded?.split(",")[0]?.trim() ??
|
||||
context.req.header("x-real-ip") ??
|
||||
"unknown";
|
||||
if (!limiter.isAllowed(ip)) throw AppError.tooManyRequests();
|
||||
|
||||
const parsed = leadBody.safeParse(await context.req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
const issue = parsed.error.issues[0];
|
||||
throw AppError.badRequest(
|
||||
issue
|
||||
? `${issue.path.join(".") || "corps"} : ${issue.message}`
|
||||
: "Corps invalide.",
|
||||
);
|
||||
}
|
||||
|
||||
const result = await createLead(db, parsed.data);
|
||||
return context.json(result, 201);
|
||||
});
|
||||
};
|
||||
@@ -1,146 +0,0 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
import { AppError, type App, type Db } from "@cohaise/server";
|
||||
|
||||
/**
|
||||
* Point d'entrée public du formulaire de contact de la vitrine.
|
||||
*
|
||||
* Route volontairement sans `requireAuth` : n'importe quel visiteur de
|
||||
* cohaise.dev peut creer un prospect. Protection anti-abus a deux etages :
|
||||
* - un honeypot (champ invisible que seuls les robots remplissent) ;
|
||||
* - un rate-limit simple en memoire, par IP (Cloudflare reste la 1re ligne).
|
||||
* Le lead est pose dans `contacts` avec `external_source = 'cohaise-web'`,
|
||||
* non assigne, pour apparaitre dans la liste des prospects du CRM.
|
||||
*/
|
||||
|
||||
const leadSchema = z.object({
|
||||
firstName: z.string().trim().min(1).max(100),
|
||||
lastName: z.string().trim().min(1).max(100),
|
||||
email: z.string().trim().min(1).max(255),
|
||||
organization: z.string().trim().min(1).max(255).nullish(),
|
||||
phone: z.string().trim().max(50).nullish(),
|
||||
message: z.string().trim().max(4000).nullish(),
|
||||
// Honeypot : vide chez un humain, rempli par un robot.
|
||||
website: z.string().max(255).nullish(),
|
||||
});
|
||||
|
||||
const slugify = (value: string): string =>
|
||||
value
|
||||
.normalize("NFD")
|
||||
.replace(/[\u0300-\u036f]/g, "")
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 255);
|
||||
|
||||
/** Un e-mail absent ne doit pas heurter l'index unique : NULL passe partout. */
|
||||
const emailOrNull = (value: string): string | null => value.toLowerCase();
|
||||
|
||||
/** Retrouve l'entreprise par son nom, ou la cree (nom unique en base). */
|
||||
const findOrCreateOrganization = async (db: Db, name: string): Promise<string> => {
|
||||
const existing = await db.one<{ id: string }>(
|
||||
"SELECT id FROM organizations WHERE name = ? AND deleted_at IS NULL",
|
||||
[name],
|
||||
);
|
||||
if (existing) return existing.id;
|
||||
|
||||
const id = randomUUID();
|
||||
try {
|
||||
await db.exec("INSERT INTO organizations (id, name, slug) VALUES (?, ?, ?)", [
|
||||
id,
|
||||
name,
|
||||
slugify(name),
|
||||
]);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
// Course : une autre requete vient de creer le meme nom. On la rejoint.
|
||||
const raced = await db.one<{ id: string }>(
|
||||
"SELECT id FROM organizations WHERE name = ? AND deleted_at IS NULL",
|
||||
[name],
|
||||
);
|
||||
if (raced) return raced.id;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return id;
|
||||
};
|
||||
|
||||
// Rate-limit en memoire : suffisant pour une instance CRM unique. Derriere
|
||||
// nginx/Cloudflare, l'IP vient de x-forwarded-for.
|
||||
const RATE_WINDOW_MS = 15 * 60 * 1000;
|
||||
const RATE_MAX = 5;
|
||||
const attempts = new Map<string, number[]>();
|
||||
|
||||
const isAllowed = (ip: string): boolean => {
|
||||
const now = Date.now();
|
||||
const recent = (attempts.get(ip) ?? []).filter((t) => now - t < RATE_WINDOW_MS);
|
||||
if (recent.length >= RATE_MAX) {
|
||||
attempts.set(ip, recent);
|
||||
return false;
|
||||
}
|
||||
recent.push(now);
|
||||
attempts.set(ip, recent);
|
||||
return true;
|
||||
};
|
||||
|
||||
export const registerLeadRoutes = (app: App, db: Db): void => {
|
||||
app.post("/api/crm/leads", async (context) => {
|
||||
const forwarded = context.req.header("x-forwarded-for");
|
||||
const ip =
|
||||
forwarded?.split(",")[0]?.trim() ?? context.req.header("x-real-ip") ?? "unknown";
|
||||
if (!isAllowed(ip)) throw AppError.tooManyRequests();
|
||||
|
||||
const parsed = leadSchema.safeParse(await context.req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
const issue = parsed.error.issues[0];
|
||||
throw AppError.badRequest(
|
||||
issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.",
|
||||
);
|
||||
}
|
||||
const data = parsed.data;
|
||||
|
||||
// Honeypot rempli : robot. On feint la reussite pour ne pas se trahir.
|
||||
if (data.website) {
|
||||
return context.json({ ok: true, id: randomUUID() }, 201);
|
||||
}
|
||||
|
||||
const organizationId = data.organization
|
||||
? await findOrCreateOrganization(db, data.organization)
|
||||
: null;
|
||||
|
||||
const id = randomUUID();
|
||||
try {
|
||||
await db.exec(
|
||||
`INSERT INTO contacts
|
||||
(id, first_name, last_name, organization_id, email, phone, job_title,
|
||||
country_id, external_source, external_id, description, owner_id, created_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[
|
||||
id,
|
||||
data.firstName,
|
||||
data.lastName,
|
||||
organizationId,
|
||||
emailOrNull(data.email),
|
||||
data.phone ?? null,
|
||||
null,
|
||||
null,
|
||||
"cohaise-web",
|
||||
null,
|
||||
data.message ?? null,
|
||||
null,
|
||||
null,
|
||||
],
|
||||
);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Cette adresse a deja ete enregistree.");
|
||||
}
|
||||
if ((error as { errno?: number }).errno === 1452) {
|
||||
throw AppError.badRequest("L'entreprise referencee n'existe pas.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return context.json({ ok: true, id }, 201);
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,110 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
AppError,
|
||||
currentUser,
|
||||
requireAuth,
|
||||
type App,
|
||||
type Db,
|
||||
} from "@cohaise/server";
|
||||
import { mountSession } from "../middleware/auth.js";
|
||||
import {
|
||||
createOrganization,
|
||||
deleteOrganization,
|
||||
getOrganization,
|
||||
listOrganizations,
|
||||
toPublicOrganization,
|
||||
updateOrganization,
|
||||
} from "../services/organizationService.js";
|
||||
import { parsePagination } from "../utils/pagination.js";
|
||||
import { invalidBody, uuidSchema } from "../utils/validation.js";
|
||||
|
||||
const writable = z.string().trim().min(1).max(255);
|
||||
const optionalText = z.string().trim().max(255).nullish();
|
||||
const optionalLong = z.string().trim().max(4000).nullish();
|
||||
|
||||
const createOrganizationBody = z.object({
|
||||
name: writable,
|
||||
website: optionalText,
|
||||
industry: z.string().trim().max(100).nullish(),
|
||||
phone: z.string().trim().max(50).nullish(),
|
||||
email: z.string().trim().max(255).nullish(),
|
||||
addressLine1: optionalText,
|
||||
addressLine2: optionalText,
|
||||
postalCode: z.string().trim().max(20).nullish(),
|
||||
city: z.string().trim().max(100).nullish(),
|
||||
countryId: z.coerce.number().int().positive().nullish(),
|
||||
description: optionalLong,
|
||||
});
|
||||
|
||||
const updateOrganizationBody = createOrganizationBody.partial();
|
||||
|
||||
export const registerOrganizationRoutes = (app: App, db: Db): void => {
|
||||
mountSession(app, db, "/api/crm/organizations");
|
||||
|
||||
app.get("/api/crm/organizations", requireAuth, async (context) => {
|
||||
const pagination = parsePagination(
|
||||
context.req.query("page"),
|
||||
context.req.query("limit"),
|
||||
);
|
||||
const { total, organizations } = await listOrganizations(
|
||||
db,
|
||||
context.req.query("q")?.trim() ?? "",
|
||||
pagination,
|
||||
);
|
||||
|
||||
return context.json({
|
||||
total,
|
||||
page: pagination.page,
|
||||
limit: pagination.limit,
|
||||
organizations: organizations.map(toPublicOrganization),
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/crm/organizations/:id", requireAuth, async (context) => {
|
||||
const id = context.req.param("id");
|
||||
if (!id || !uuidSchema.safeParse(id).success) {
|
||||
throw AppError.notFound("Entreprise introuvable.");
|
||||
}
|
||||
const organization = await getOrganization(db, id);
|
||||
return context.json({ organization: toPublicOrganization(organization) });
|
||||
});
|
||||
|
||||
app.post("/api/crm/organizations", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const parsed = createOrganizationBody.safeParse(
|
||||
await context.req.json().catch(() => null),
|
||||
);
|
||||
if (!parsed.success) throw invalidBody(parsed.error);
|
||||
|
||||
const organization = await createOrganization(db, user.id, parsed.data);
|
||||
return context.json(
|
||||
{ organization: toPublicOrganization(organization) },
|
||||
201,
|
||||
);
|
||||
});
|
||||
|
||||
app.patch("/api/crm/organizations/:id", requireAuth, async (context) => {
|
||||
const id = context.req.param("id");
|
||||
if (!id || !uuidSchema.safeParse(id).success) {
|
||||
throw AppError.notFound("Entreprise introuvable.");
|
||||
}
|
||||
|
||||
const parsed = updateOrganizationBody.safeParse(
|
||||
await context.req.json().catch(() => null),
|
||||
);
|
||||
if (!parsed.success) throw invalidBody(parsed.error);
|
||||
|
||||
const organization = await updateOrganization(db, id, parsed.data);
|
||||
return context.json({ organization: toPublicOrganization(organization) });
|
||||
});
|
||||
|
||||
app.delete("/api/crm/organizations/:id", requireAuth, async (context) => {
|
||||
const id = context.req.param("id");
|
||||
if (!id || !uuidSchema.safeParse(id).success) {
|
||||
throw AppError.notFound("Entreprise introuvable.");
|
||||
}
|
||||
|
||||
await deleteOrganization(db, id);
|
||||
return context.json({ ok: true });
|
||||
});
|
||||
};
|
||||
@@ -1,277 +0,0 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
AppError,
|
||||
attachUser,
|
||||
currentUser,
|
||||
requireAuth,
|
||||
type App,
|
||||
type Db,
|
||||
} from "@cohaise/server";
|
||||
|
||||
const uuid = z
|
||||
.string()
|
||||
.regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, "Identifiant invalide.");
|
||||
|
||||
const writable = z.string().trim().min(1).max(255);
|
||||
const optionalText = z.string().trim().max(255).nullish();
|
||||
const optionalLong = z.string().trim().max(4000).nullish();
|
||||
|
||||
const createOrganization = z.object({
|
||||
name: writable,
|
||||
website: optionalText,
|
||||
industry: z.string().trim().max(100).nullish(),
|
||||
phone: z.string().trim().max(50).nullish(),
|
||||
email: z.string().trim().max(255).nullish(),
|
||||
addressLine1: optionalText,
|
||||
addressLine2: optionalText,
|
||||
postalCode: z.string().trim().max(20).nullish(),
|
||||
city: z.string().trim().max(100).nullish(),
|
||||
countryId: z.coerce.number().int().positive().nullish(),
|
||||
description: optionalLong,
|
||||
});
|
||||
|
||||
const updateOrganization = createOrganization.partial();
|
||||
|
||||
interface OrganizationRow {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
website: string | null;
|
||||
industry: string | null;
|
||||
phone: string | null;
|
||||
email: string | null;
|
||||
address_line1: string | null;
|
||||
address_line2: string | null;
|
||||
postal_code: string | null;
|
||||
city: string | null;
|
||||
country_id: number | null;
|
||||
country_name: string | null;
|
||||
country_code: string | null;
|
||||
description: string | null;
|
||||
owner_id: string | null;
|
||||
owner_name: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
const SELECT_ORGANIZATION = `
|
||||
SELECT o.id, o.name, o.slug, o.website, o.industry, o.phone, o.email,
|
||||
o.address_line1, o.address_line2, o.postal_code, o.city, o.country_id,
|
||||
c.name AS country_name, c.code AS country_code,
|
||||
o.description, o.owner_id,
|
||||
CONCAT(u.first_name, ' ', u.last_name) AS owner_name,
|
||||
o.created_at, o.updated_at
|
||||
FROM organizations o
|
||||
LEFT JOIN countries c ON c.id = o.country_id
|
||||
LEFT JOIN users u ON u.id = o.owner_id`;
|
||||
|
||||
const publicOrganization = (row: OrganizationRow) => ({
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
slug: row.slug,
|
||||
website: row.website,
|
||||
industry: row.industry,
|
||||
phone: row.phone,
|
||||
email: row.email,
|
||||
address_line1: row.address_line1,
|
||||
address_line2: row.address_line2,
|
||||
postal_code: row.postal_code,
|
||||
city: row.city,
|
||||
country_id: row.country_id,
|
||||
country_name: row.country_name,
|
||||
country_code: row.country_code,
|
||||
description: row.description,
|
||||
owner_id: row.owner_id,
|
||||
owner_name: row.owner_name,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
});
|
||||
|
||||
/** Normalise un nom en slug lisible, sans accent ni punctuation. */
|
||||
const slugify = (value: string): string =>
|
||||
value
|
||||
.normalize("NFD")
|
||||
.replace(/[\u0300-\u036f]/g, "")
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 255);
|
||||
|
||||
export const registerOrganizationRoutes = (app: App, db: Db): void => {
|
||||
app.use("/api/crm/organizations/*", attachUser(db));
|
||||
app.use("/api/crm/organizations", attachUser(db));
|
||||
|
||||
app.get("/api/crm/organizations", requireAuth, async (context) => {
|
||||
const search = context.req.query("q")?.trim() ?? "";
|
||||
const page = Math.max(1, Number(context.req.query("page") ?? 1) || 1);
|
||||
const limit = Math.min(100, Math.max(1, Number(context.req.query("limit") ?? 25) || 25));
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
const where = search
|
||||
? "WHERE o.deleted_at IS NULL AND (o.name LIKE ? OR o.city LIKE ? OR o.industry LIKE ?)"
|
||||
: "WHERE o.deleted_at IS NULL";
|
||||
const term = `%${search}%`;
|
||||
const params = search ? [term, term, term] : [];
|
||||
|
||||
const [{ total }, rows] = await Promise.all([
|
||||
db
|
||||
.query<{ total: number }>(`SELECT COUNT(*) AS total FROM organizations o ${where}`, params)
|
||||
.then((result) => ({ total: Number(result[0]?.total ?? 0) })),
|
||||
db.query<OrganizationRow>(
|
||||
`${SELECT_ORGANIZATION} ${where} ORDER BY o.name LIMIT ${limit} OFFSET ${offset}`,
|
||||
params,
|
||||
),
|
||||
]);
|
||||
|
||||
return context.json({
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
organizations: rows.map(publicOrganization),
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/crm/organizations/:id", requireAuth, async (context) => {
|
||||
const id = context.req.param("id");
|
||||
if (!uuid.safeParse(id).success) throw AppError.notFound("Entreprise introuvable.");
|
||||
const row = await db.one<OrganizationRow>(
|
||||
`${SELECT_ORGANIZATION} WHERE o.id = ? AND o.deleted_at IS NULL`,
|
||||
[id],
|
||||
);
|
||||
if (!row) throw AppError.notFound("Entreprise introuvable.");
|
||||
return context.json({ organization: publicOrganization(row) });
|
||||
});
|
||||
|
||||
app.post(
|
||||
"/api/crm/organizations",
|
||||
requireAuth,
|
||||
async (context) => {
|
||||
const user = currentUser(context);
|
||||
const parsed = createOrganization.safeParse(await context.req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
const issue = parsed.error.issues[0];
|
||||
throw AppError.badRequest(
|
||||
issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.",
|
||||
);
|
||||
}
|
||||
const data = parsed.data;
|
||||
|
||||
const id = randomUUID();
|
||||
try {
|
||||
await db.exec(
|
||||
`INSERT INTO organizations
|
||||
(id, name, slug, website, industry, phone, email, address_line1, address_line2,
|
||||
postal_code, city, country_id, description, owner_id, created_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[
|
||||
id,
|
||||
data.name,
|
||||
slugify(data.name),
|
||||
data.website ?? null,
|
||||
data.industry ?? null,
|
||||
data.phone ?? null,
|
||||
data.email ?? null,
|
||||
data.addressLine1 ?? null,
|
||||
data.addressLine2 ?? null,
|
||||
data.postalCode ?? null,
|
||||
data.city ?? null,
|
||||
data.countryId ?? null,
|
||||
data.description ?? null,
|
||||
user.id,
|
||||
user.id,
|
||||
],
|
||||
);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Une entreprise porte deja ce nom.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const created = await db.required<OrganizationRow>(
|
||||
`${SELECT_ORGANIZATION} WHERE o.id = ?`,
|
||||
[id],
|
||||
);
|
||||
return context.json({ organization: publicOrganization(created) }, 201);
|
||||
},
|
||||
);
|
||||
|
||||
app.patch(
|
||||
"/api/crm/organizations/:id",
|
||||
requireAuth,
|
||||
async (context) => {
|
||||
const id = context.req.param("id");
|
||||
if (!uuid.safeParse(id).success) throw AppError.notFound("Entreprise introuvable.");
|
||||
|
||||
const parsed = updateOrganization.safeParse(await context.req.json().catch(() => null));
|
||||
if (!parsed.success) throw AppError.badRequest("Corps invalide.");
|
||||
|
||||
const existing = await db.one<{ id: string }>(
|
||||
"SELECT id FROM organizations WHERE id = ? AND deleted_at IS NULL",
|
||||
[id],
|
||||
);
|
||||
if (!existing) throw AppError.notFound("Entreprise introuvable.");
|
||||
|
||||
const columns: Record<string, unknown> = {
|
||||
website: parsed.data.website,
|
||||
industry: parsed.data.industry,
|
||||
phone: parsed.data.phone,
|
||||
email: parsed.data.email,
|
||||
address_line1: parsed.data.addressLine1,
|
||||
address_line2: parsed.data.addressLine2,
|
||||
postal_code: parsed.data.postalCode,
|
||||
city: parsed.data.city,
|
||||
country_id: parsed.data.countryId,
|
||||
description: parsed.data.description,
|
||||
};
|
||||
if (parsed.data.name !== undefined) {
|
||||
columns.name = parsed.data.name;
|
||||
columns.slug = slugify(parsed.data.name);
|
||||
}
|
||||
|
||||
const assignments = Object.keys(columns)
|
||||
.filter((key) => columns[key] !== undefined)
|
||||
.map((key) => `${key} = ?`);
|
||||
if (assignments.length === 0) throw AppError.badRequest("Aucune modification fournie.");
|
||||
|
||||
const values = Object.keys(columns)
|
||||
.filter((key) => columns[key] !== undefined)
|
||||
.map((key) => columns[key]);
|
||||
|
||||
try {
|
||||
await db.exec(
|
||||
`UPDATE organizations SET ${assignments.join(", ")} WHERE id = ? AND deleted_at IS NULL`,
|
||||
[...values, id],
|
||||
);
|
||||
} catch (error) {
|
||||
if ((error as { errno?: number }).errno === 1062) {
|
||||
throw AppError.conflict("Une entreprise porte deja ce nom.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const updated = await db.required<OrganizationRow>(
|
||||
`${SELECT_ORGANIZATION} WHERE o.id = ?`,
|
||||
[id],
|
||||
);
|
||||
return context.json({ organization: publicOrganization(updated) });
|
||||
},
|
||||
);
|
||||
|
||||
app.delete(
|
||||
"/api/crm/organizations/:id",
|
||||
requireAuth,
|
||||
async (context) => {
|
||||
const id = context.req.param("id");
|
||||
if (!uuid.safeParse(id).success) throw AppError.notFound("Entreprise introuvable.");
|
||||
|
||||
const result = await db.exec(
|
||||
"UPDATE organizations SET deleted_at = UTC_TIMESTAMP() WHERE id = ? AND deleted_at IS NULL",
|
||||
[id],
|
||||
);
|
||||
if (result.affectedRows === 0) throw AppError.notFound("Entreprise introuvable.");
|
||||
return context.json({ ok: true });
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,124 @@
|
||||
import {
|
||||
AppError,
|
||||
createSession,
|
||||
hashPassword,
|
||||
revokeSession,
|
||||
sha256,
|
||||
verifyPassword,
|
||||
type Config,
|
||||
type Db,
|
||||
} from "@cohaise/server";
|
||||
import type { AuthUser, UserRow } from "../models/types.js";
|
||||
|
||||
const SELECT_USER = `
|
||||
SELECT u.id, u.email, u.password_hash, u.first_name, u.last_name,
|
||||
u.is_active, u.must_change_password
|
||||
FROM users u`;
|
||||
|
||||
/**
|
||||
* Empreinte de repli, calculée pour n'importe quelle chaîne : une adresse
|
||||
* inconnue doit prendre exactement le même temps qu'une adresse connue avec
|
||||
* un mauvais mot de passe, sinon l'API devient un annuaire.
|
||||
*/
|
||||
const DUMMY_HASH_PROMISE = hashPassword("placeholder-for-anti-enumeration").catch(
|
||||
() => null,
|
||||
);
|
||||
void DUMMY_HASH_PROMISE;
|
||||
|
||||
export const toPublicUser = (row: UserRow): AuthUser => ({
|
||||
id: row.id,
|
||||
email: row.email,
|
||||
first_name: row.first_name,
|
||||
last_name: row.last_name,
|
||||
must_change_password: row.must_change_password === 1,
|
||||
});
|
||||
|
||||
export interface LoginInput {
|
||||
email: string;
|
||||
password: string;
|
||||
ipAddress: string | null;
|
||||
userAgent: string | null;
|
||||
}
|
||||
|
||||
export interface LoginResult {
|
||||
user: AuthUser;
|
||||
token: string;
|
||||
expiresAt: Date;
|
||||
}
|
||||
|
||||
export const login = async (
|
||||
db: Db,
|
||||
config: Config,
|
||||
input: LoginInput,
|
||||
): Promise<LoginResult> => {
|
||||
const row = await db.one<UserRow>(
|
||||
`${SELECT_USER} WHERE u.email = ? AND u.deleted_at IS NULL`,
|
||||
[input.email],
|
||||
);
|
||||
|
||||
const stored = row?.password_hash ?? (await DUMMY_HASH_PROMISE) ?? "";
|
||||
const valid = stored ? await verifyPassword(input.password, stored) : false;
|
||||
if (!row || !valid) throw AppError.unauthorized("Identifiants invalides.");
|
||||
if (row.is_active !== 1) throw AppError.unauthorized("Compte desactive.");
|
||||
|
||||
const { token, expiresAt } = await createSession(
|
||||
db,
|
||||
row.id,
|
||||
{ ipAddress: input.ipAddress, userAgent: input.userAgent },
|
||||
config.SESSION_TTL_HOURS,
|
||||
);
|
||||
await db.exec("UPDATE users SET last_login_at = UTC_TIMESTAMP(3) WHERE id = ?", [
|
||||
row.id,
|
||||
]);
|
||||
|
||||
return { user: toPublicUser(row), token, expiresAt };
|
||||
};
|
||||
|
||||
export const logout = async (db: Db, token: string | undefined): Promise<void> => {
|
||||
if (token) await revokeSession(db, token);
|
||||
};
|
||||
|
||||
export const getSessionUser = async (db: Db, userId: string): Promise<AuthUser> => {
|
||||
const row = await db.one<UserRow>(
|
||||
`${SELECT_USER} WHERE u.id = ? AND u.deleted_at IS NULL`,
|
||||
[userId],
|
||||
);
|
||||
if (!row) throw AppError.unauthorized();
|
||||
return toPublicUser(row);
|
||||
};
|
||||
|
||||
export const changePassword = async (
|
||||
db: Db,
|
||||
userId: string,
|
||||
token: string | undefined,
|
||||
current: string,
|
||||
next: string,
|
||||
): Promise<void> => {
|
||||
const row = await db.one<{ password_hash: string }>(
|
||||
"SELECT password_hash FROM users WHERE id = ? AND deleted_at IS NULL",
|
||||
[userId],
|
||||
);
|
||||
if (!row) throw AppError.unauthorized();
|
||||
|
||||
if (!(await verifyPassword(current, row.password_hash))) {
|
||||
throw AppError.unauthorized("Mot de passe actuel incorrect.");
|
||||
}
|
||||
if (current === next) {
|
||||
throw AppError.badRequest("Le nouveau mot de passe doit differer de l'actuel.");
|
||||
}
|
||||
|
||||
const hash = await hashPassword(next);
|
||||
// Pas de password_changed_at ici : cette colonne appartient au modèle du
|
||||
// Cloud. Le CRM n'a pas de notion de confirmation d'identité à célébrer.
|
||||
await db.exec(
|
||||
"UPDATE users SET password_hash = ?, must_change_password = 0 WHERE id = ?",
|
||||
[hash, userId],
|
||||
);
|
||||
// La session courante est conservée, toutes les autres sont révoquées.
|
||||
await db.exec(
|
||||
`UPDATE user_sessions
|
||||
SET revoked_at = UTC_TIMESTAMP()
|
||||
WHERE user_id = ? AND revoked_at IS NULL AND token_hash <> ?`,
|
||||
[userId, sha256(token ?? "")],
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,209 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { AppError, type Db } from "@cohaise/server";
|
||||
import type { ContactRow } from "../models/types.js";
|
||||
import { isDuplicateEntry, isForeignKeyViolation } from "../utils/dbErrors.js";
|
||||
import { normalizeEmail } from "../utils/normalize.js";
|
||||
import { uuidSchema } from "../utils/validation.js";
|
||||
import { buildAssignments } from "../utils/sql.js";
|
||||
import type { Pagination } from "../utils/pagination.js";
|
||||
|
||||
const SELECT_CONTACT = `
|
||||
SELECT ct.id, ct.first_name, ct.last_name, ct.organization_id,
|
||||
o.name AS organization_name, ct.email, ct.phone, ct.mobile, ct.job_title,
|
||||
ct.country_id, c.name AS country_name, c.code AS country_code,
|
||||
ct.external_source, ct.external_id, ct.description, ct.owner_id,
|
||||
CONCAT(u.first_name, ' ', u.last_name) AS owner_name,
|
||||
ct.created_at, ct.updated_at
|
||||
FROM contacts ct
|
||||
LEFT JOIN organizations o ON o.id = ct.organization_id AND o.deleted_at IS NULL
|
||||
LEFT JOIN countries c ON c.id = ct.country_id
|
||||
LEFT JOIN users u ON u.id = ct.owner_id`;
|
||||
|
||||
export interface ContactCreate {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
organizationId?: string | null | undefined;
|
||||
email?: string | null | undefined;
|
||||
phone?: string | null | undefined;
|
||||
mobile?: string | null | undefined;
|
||||
jobTitle?: string | null | undefined;
|
||||
countryId?: number | null | undefined;
|
||||
externalSource?: string | null | undefined;
|
||||
externalId?: string | null | undefined;
|
||||
description?: string | null | undefined;
|
||||
}
|
||||
|
||||
export type ContactUpdate = {
|
||||
[Key in keyof ContactCreate]?: ContactCreate[Key] | undefined;
|
||||
};
|
||||
|
||||
export interface ContactList {
|
||||
total: number;
|
||||
contacts: ContactRow[];
|
||||
}
|
||||
|
||||
export interface ContactFilters {
|
||||
search: string;
|
||||
organizationId: string;
|
||||
}
|
||||
|
||||
export const toPublicContact = (row: ContactRow) => ({
|
||||
id: row.id,
|
||||
first_name: row.first_name,
|
||||
last_name: row.last_name,
|
||||
organization_id: row.organization_id,
|
||||
organization_name: row.organization_name,
|
||||
email: row.email,
|
||||
phone: row.phone,
|
||||
mobile: row.mobile,
|
||||
job_title: row.job_title,
|
||||
country_id: row.country_id,
|
||||
country_name: row.country_name,
|
||||
country_code: row.country_code,
|
||||
external_source: row.external_source,
|
||||
external_id: row.external_id,
|
||||
description: row.description,
|
||||
owner_id: row.owner_id,
|
||||
owner_name: row.owner_name,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
});
|
||||
|
||||
export const listContacts = async (
|
||||
db: Db,
|
||||
filters: ContactFilters,
|
||||
pagination: Pagination,
|
||||
): Promise<ContactList> => {
|
||||
const clauses = ["ct.deleted_at IS NULL"];
|
||||
const params: unknown[] = [];
|
||||
|
||||
if (filters.search) {
|
||||
clauses.push(
|
||||
"(ct.first_name LIKE ? OR ct.last_name LIKE ? OR ct.email LIKE ? OR o.name LIKE ?)",
|
||||
);
|
||||
const term = `%${filters.search}%`;
|
||||
params.push(term, term, term, term);
|
||||
}
|
||||
if (uuidSchema.safeParse(filters.organizationId).success) {
|
||||
clauses.push("ct.organization_id = ?");
|
||||
params.push(filters.organizationId);
|
||||
}
|
||||
const where = `WHERE ${clauses.join(" AND ")}`;
|
||||
|
||||
const totalRows = await db.query<{ total: number }>(
|
||||
`SELECT COUNT(*) AS total
|
||||
FROM contacts ct
|
||||
LEFT JOIN organizations o ON o.id = ct.organization_id AND o.deleted_at IS NULL
|
||||
${where}`,
|
||||
params,
|
||||
);
|
||||
const rows = await db.query<ContactRow>(
|
||||
`${SELECT_CONTACT} ${where} ORDER BY ct.last_name, ct.first_name LIMIT ${pagination.limit} OFFSET ${pagination.offset}`,
|
||||
params,
|
||||
);
|
||||
|
||||
return { total: Number(totalRows[0]?.total ?? 0), contacts: rows };
|
||||
};
|
||||
|
||||
export const getContact = async (db: Db, id: string): Promise<ContactRow> => {
|
||||
const row = await db.one<ContactRow>(
|
||||
`${SELECT_CONTACT} WHERE ct.id = ? AND ct.deleted_at IS NULL`,
|
||||
[id],
|
||||
);
|
||||
if (!row) throw AppError.notFound("Prospect introuvable.");
|
||||
return row;
|
||||
};
|
||||
|
||||
export const createContact = async (
|
||||
db: Db,
|
||||
ownerId: string,
|
||||
data: ContactCreate,
|
||||
): Promise<ContactRow> => {
|
||||
const id = randomUUID();
|
||||
try {
|
||||
await db.exec(
|
||||
`INSERT INTO contacts
|
||||
(id, first_name, last_name, organization_id, email, phone, mobile, job_title,
|
||||
country_id, external_source, external_id, description, owner_id, created_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[
|
||||
id,
|
||||
data.firstName,
|
||||
data.lastName,
|
||||
data.organizationId ?? null,
|
||||
normalizeEmail(data.email),
|
||||
data.phone ?? null,
|
||||
data.mobile ?? null,
|
||||
data.jobTitle ?? null,
|
||||
data.countryId ?? null,
|
||||
data.externalSource ?? null,
|
||||
data.externalId ?? null,
|
||||
data.description ?? null,
|
||||
ownerId,
|
||||
ownerId,
|
||||
],
|
||||
);
|
||||
} catch (error) {
|
||||
if (isDuplicateEntry(error)) {
|
||||
throw AppError.conflict("Un prospect actif porte deja cette adresse.");
|
||||
}
|
||||
if (isForeignKeyViolation(error)) {
|
||||
throw AppError.badRequest("L'entreprise ou le pays reference n'existe pas.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return db.required<ContactRow>(`${SELECT_CONTACT} WHERE ct.id = ?`, [id]);
|
||||
};
|
||||
|
||||
export const updateContact = async (
|
||||
db: Db,
|
||||
id: string,
|
||||
data: ContactUpdate,
|
||||
): Promise<ContactRow> => {
|
||||
const existing = await db.one<{ id: string }>(
|
||||
"SELECT id FROM contacts WHERE id = ? AND deleted_at IS NULL",
|
||||
[id],
|
||||
);
|
||||
if (!existing) throw AppError.notFound("Prospect introuvable.");
|
||||
|
||||
const assignments = buildAssignments({
|
||||
first_name: data.firstName,
|
||||
last_name: data.lastName,
|
||||
organization_id: data.organizationId,
|
||||
email: data.email === undefined ? undefined : normalizeEmail(data.email),
|
||||
phone: data.phone,
|
||||
mobile: data.mobile,
|
||||
job_title: data.jobTitle,
|
||||
country_id: data.countryId,
|
||||
external_source: data.externalSource,
|
||||
external_id: data.externalId,
|
||||
description: data.description,
|
||||
});
|
||||
if (!assignments) throw AppError.badRequest("Aucune modification fournie.");
|
||||
|
||||
try {
|
||||
await db.exec(
|
||||
`UPDATE contacts SET ${assignments.clause} WHERE id = ? AND deleted_at IS NULL`,
|
||||
[...assignments.values, id],
|
||||
);
|
||||
} catch (error) {
|
||||
if (isDuplicateEntry(error)) {
|
||||
throw AppError.conflict("Un prospect actif porte deja cette adresse.");
|
||||
}
|
||||
if (isForeignKeyViolation(error)) {
|
||||
throw AppError.badRequest("L'entreprise ou le pays reference n'existe pas.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return db.required<ContactRow>(`${SELECT_CONTACT} WHERE ct.id = ?`, [id]);
|
||||
};
|
||||
|
||||
export const deleteContact = async (db: Db, id: string): Promise<void> => {
|
||||
const result = await db.exec(
|
||||
"UPDATE contacts SET deleted_at = UTC_TIMESTAMP() WHERE id = ? AND deleted_at IS NULL",
|
||||
[id],
|
||||
);
|
||||
if (result.affectedRows === 0) throw AppError.notFound("Prospect introuvable.");
|
||||
};
|
||||
@@ -0,0 +1,91 @@
|
||||
import { AppError, type Db } from "@cohaise/server";
|
||||
import type { CountryRow } from "../models/types.js";
|
||||
import { isDuplicateEntry, isReferencedRow } from "../utils/dbErrors.js";
|
||||
import { buildAssignments } from "../utils/sql.js";
|
||||
|
||||
const SELECT_COUNTRY = "SELECT id, code, name, phone_code FROM countries";
|
||||
|
||||
export interface CountryCreate {
|
||||
code: string;
|
||||
name: string;
|
||||
phoneCode?: string | null | undefined;
|
||||
}
|
||||
|
||||
export interface CountryUpdate {
|
||||
code?: string | undefined;
|
||||
name?: string | undefined;
|
||||
phoneCode?: string | null | undefined;
|
||||
}
|
||||
|
||||
export const toPublicCountry = (row: CountryRow) => ({
|
||||
id: row.id,
|
||||
code: row.code,
|
||||
name: row.name,
|
||||
phone_code: row.phone_code,
|
||||
});
|
||||
|
||||
/** Référentiel : le tri est collationnel, donc sans accent ni casse douteuse. */
|
||||
export const listCountries = async (db: Db, search: string): Promise<CountryRow[]> => {
|
||||
const term = search.trim();
|
||||
const where = term ? "WHERE name LIKE ? OR code = ?" : "";
|
||||
const params = term ? [`%${term}%`, term.toUpperCase()] : [];
|
||||
return db.query<CountryRow>(`${SELECT_COUNTRY} ${where} ORDER BY name`, params);
|
||||
};
|
||||
|
||||
export const createCountry = async (
|
||||
db: Db,
|
||||
data: CountryCreate,
|
||||
): Promise<CountryRow> => {
|
||||
try {
|
||||
await db.exec("INSERT INTO countries (code, name, phone_code) VALUES (?, ?, ?)", [
|
||||
data.code,
|
||||
data.name,
|
||||
data.phoneCode ?? null,
|
||||
]);
|
||||
} catch (error) {
|
||||
if (isDuplicateEntry(error)) throw AppError.conflict("Ce pays existe deja.");
|
||||
throw error;
|
||||
}
|
||||
|
||||
return db.required<CountryRow>(`${SELECT_COUNTRY} WHERE code = ?`, [data.code]);
|
||||
};
|
||||
|
||||
export const updateCountry = async (
|
||||
db: Db,
|
||||
id: number,
|
||||
data: CountryUpdate,
|
||||
): Promise<CountryRow> => {
|
||||
const assignments = buildAssignments({
|
||||
code: data.code,
|
||||
name: data.name,
|
||||
phone_code: data.phoneCode,
|
||||
});
|
||||
if (!assignments) throw AppError.badRequest("Aucune modification fournie.");
|
||||
|
||||
try {
|
||||
const result = await db.exec(
|
||||
`UPDATE countries SET ${assignments.clause} WHERE id = ?`,
|
||||
[...assignments.values, id],
|
||||
);
|
||||
if (result.affectedRows === 0) throw AppError.notFound("Pays introuvable.");
|
||||
} catch (error) {
|
||||
if (isDuplicateEntry(error)) {
|
||||
throw AppError.conflict("Ce code de pays existe deja.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return db.required<CountryRow>(`${SELECT_COUNTRY} WHERE id = ?`, [id]);
|
||||
};
|
||||
|
||||
export const deleteCountry = async (db: Db, id: number): Promise<void> => {
|
||||
try {
|
||||
const result = await db.exec("DELETE FROM countries WHERE id = ?", [id]);
|
||||
if (result.affectedRows === 0) throw AppError.notFound("Pays introuvable.");
|
||||
} catch (error) {
|
||||
if (isReferencedRow(error)) {
|
||||
throw AppError.conflict("Des entreprises ou contacts referencent ce pays.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,65 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { AppError, type Db } from "@cohaise/server";
|
||||
import { PUBLIC_LEAD_SOURCE } from "../config/app.js";
|
||||
import type { LeadInput } from "../models/types.js";
|
||||
import { isDuplicateEntry, isForeignKeyViolation } from "../utils/dbErrors.js";
|
||||
import { normalizeEmail } from "../utils/normalize.js";
|
||||
import { findOrCreateOrganization } from "./organizationService.js";
|
||||
|
||||
export interface LeadResult {
|
||||
ok: true;
|
||||
id: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Crée un prospect depuis le formulaire public de la vitrine.
|
||||
*
|
||||
* Protection anti-abus à deux étages, appliquée par la route :
|
||||
* - un honeypot (champ invisible que seuls les robots remplissent) ;
|
||||
* - un rate-limit simple en mémoire, par IP (Cloudflare reste la 1re ligne).
|
||||
* Le lead est posé dans `contacts` avec `external_source = 'cohaise-web'`,
|
||||
* non assigné, pour apparaître dans la liste des prospects du CRM.
|
||||
*/
|
||||
export const createLead = async (db: Db, data: LeadInput): Promise<LeadResult> => {
|
||||
// Honeypot rempli : robot. On feint la réussite pour ne pas se trahir.
|
||||
if (data.website) return { ok: true, id: randomUUID() };
|
||||
|
||||
const organizationId = data.organization
|
||||
? await findOrCreateOrganization(db, data.organization)
|
||||
: null;
|
||||
|
||||
const id = randomUUID();
|
||||
try {
|
||||
await db.exec(
|
||||
`INSERT INTO contacts
|
||||
(id, first_name, last_name, organization_id, email, phone, job_title,
|
||||
country_id, external_source, external_id, description, owner_id, created_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[
|
||||
id,
|
||||
data.firstName,
|
||||
data.lastName,
|
||||
organizationId,
|
||||
normalizeEmail(data.email),
|
||||
data.phone ?? null,
|
||||
null,
|
||||
null,
|
||||
PUBLIC_LEAD_SOURCE,
|
||||
null,
|
||||
data.message ?? null,
|
||||
null,
|
||||
null,
|
||||
],
|
||||
);
|
||||
} catch (error) {
|
||||
if (isDuplicateEntry(error)) {
|
||||
throw AppError.conflict("Cette adresse a deja ete enregistree.");
|
||||
}
|
||||
if (isForeignKeyViolation(error)) {
|
||||
throw AppError.badRequest("L'entreprise referencee n'existe pas.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return { ok: true, id };
|
||||
};
|
||||
@@ -0,0 +1,220 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { AppError, type Db } from "@cohaise/server";
|
||||
import type { OrganizationRow } from "../models/types.js";
|
||||
import { isDuplicateEntry } from "../utils/dbErrors.js";
|
||||
import { slugify } from "../utils/normalize.js";
|
||||
import { buildAssignments } from "../utils/sql.js";
|
||||
import type { Pagination } from "../utils/pagination.js";
|
||||
|
||||
const SELECT_ORGANIZATION = `
|
||||
SELECT o.id, o.name, o.slug, o.website, o.industry, o.phone, o.email,
|
||||
o.address_line1, o.address_line2, o.postal_code, o.city, o.country_id,
|
||||
c.name AS country_name, c.code AS country_code,
|
||||
o.description, o.owner_id,
|
||||
CONCAT(u.first_name, ' ', u.last_name) AS owner_name,
|
||||
o.created_at, o.updated_at
|
||||
FROM organizations o
|
||||
LEFT JOIN countries c ON c.id = o.country_id
|
||||
LEFT JOIN users u ON u.id = o.owner_id`;
|
||||
|
||||
export interface OrganizationCreate {
|
||||
name: string;
|
||||
website?: string | null | undefined;
|
||||
industry?: string | null | undefined;
|
||||
phone?: string | null | undefined;
|
||||
email?: string | null | undefined;
|
||||
addressLine1?: string | null | undefined;
|
||||
addressLine2?: string | null | undefined;
|
||||
postalCode?: string | null | undefined;
|
||||
city?: string | null | undefined;
|
||||
countryId?: number | null | undefined;
|
||||
description?: string | null | undefined;
|
||||
}
|
||||
|
||||
export type OrganizationUpdate = {
|
||||
[Key in keyof OrganizationCreate]?: OrganizationCreate[Key] | undefined;
|
||||
};
|
||||
|
||||
export interface OrganizationList {
|
||||
total: number;
|
||||
organizations: OrganizationRow[];
|
||||
}
|
||||
|
||||
export const toPublicOrganization = (row: OrganizationRow) => ({
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
slug: row.slug,
|
||||
website: row.website,
|
||||
industry: row.industry,
|
||||
phone: row.phone,
|
||||
email: row.email,
|
||||
address_line1: row.address_line1,
|
||||
address_line2: row.address_line2,
|
||||
postal_code: row.postal_code,
|
||||
city: row.city,
|
||||
country_id: row.country_id,
|
||||
country_name: row.country_name,
|
||||
country_code: row.country_code,
|
||||
description: row.description,
|
||||
owner_id: row.owner_id,
|
||||
owner_name: row.owner_name,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
});
|
||||
|
||||
export const listOrganizations = async (
|
||||
db: Db,
|
||||
search: string,
|
||||
pagination: Pagination,
|
||||
): Promise<OrganizationList> => {
|
||||
const where = search
|
||||
? "WHERE o.deleted_at IS NULL AND (o.name LIKE ? OR o.city LIKE ? OR o.industry LIKE ?)"
|
||||
: "WHERE o.deleted_at IS NULL";
|
||||
const term = `%${search}%`;
|
||||
const params = search ? [term, term, term] : [];
|
||||
|
||||
const [counted, rows] = await Promise.all([
|
||||
db.query<{ total: number }>(
|
||||
`SELECT COUNT(*) AS total FROM organizations o ${where}`,
|
||||
params,
|
||||
),
|
||||
db.query<OrganizationRow>(
|
||||
`${SELECT_ORGANIZATION} ${where} ORDER BY o.name LIMIT ${pagination.limit} OFFSET ${pagination.offset}`,
|
||||
params,
|
||||
),
|
||||
]);
|
||||
|
||||
return { total: Number(counted[0]?.total ?? 0), organizations: rows };
|
||||
};
|
||||
|
||||
export const getOrganization = async (db: Db, id: string): Promise<OrganizationRow> => {
|
||||
const row = await db.one<OrganizationRow>(
|
||||
`${SELECT_ORGANIZATION} WHERE o.id = ? AND o.deleted_at IS NULL`,
|
||||
[id],
|
||||
);
|
||||
if (!row) throw AppError.notFound("Entreprise introuvable.");
|
||||
return row;
|
||||
};
|
||||
|
||||
export const createOrganization = async (
|
||||
db: Db,
|
||||
ownerId: string,
|
||||
data: OrganizationCreate,
|
||||
): Promise<OrganizationRow> => {
|
||||
const id = randomUUID();
|
||||
try {
|
||||
await db.exec(
|
||||
`INSERT INTO organizations
|
||||
(id, name, slug, website, industry, phone, email, address_line1, address_line2,
|
||||
postal_code, city, country_id, description, owner_id, created_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[
|
||||
id,
|
||||
data.name,
|
||||
slugify(data.name),
|
||||
data.website ?? null,
|
||||
data.industry ?? null,
|
||||
data.phone ?? null,
|
||||
data.email ?? null,
|
||||
data.addressLine1 ?? null,
|
||||
data.addressLine2 ?? null,
|
||||
data.postalCode ?? null,
|
||||
data.city ?? null,
|
||||
data.countryId ?? null,
|
||||
data.description ?? null,
|
||||
ownerId,
|
||||
ownerId,
|
||||
],
|
||||
);
|
||||
} catch (error) {
|
||||
if (isDuplicateEntry(error)) {
|
||||
throw AppError.conflict("Une entreprise porte deja ce nom.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return db.required<OrganizationRow>(`${SELECT_ORGANIZATION} WHERE o.id = ?`, [id]);
|
||||
};
|
||||
|
||||
export const updateOrganization = async (
|
||||
db: Db,
|
||||
id: string,
|
||||
data: OrganizationUpdate,
|
||||
): Promise<OrganizationRow> => {
|
||||
const existing = await db.one<{ id: string }>(
|
||||
"SELECT id FROM organizations WHERE id = ? AND deleted_at IS NULL",
|
||||
[id],
|
||||
);
|
||||
if (!existing) throw AppError.notFound("Entreprise introuvable.");
|
||||
|
||||
const assignments = buildAssignments({
|
||||
website: data.website,
|
||||
industry: data.industry,
|
||||
phone: data.phone,
|
||||
email: data.email,
|
||||
address_line1: data.addressLine1,
|
||||
address_line2: data.addressLine2,
|
||||
postal_code: data.postalCode,
|
||||
city: data.city,
|
||||
country_id: data.countryId,
|
||||
description: data.description,
|
||||
...(data.name === undefined
|
||||
? {}
|
||||
: { name: data.name, slug: slugify(data.name) }),
|
||||
});
|
||||
if (!assignments) throw AppError.badRequest("Aucune modification fournie.");
|
||||
|
||||
try {
|
||||
await db.exec(
|
||||
`UPDATE organizations SET ${assignments.clause} WHERE id = ? AND deleted_at IS NULL`,
|
||||
[...assignments.values, id],
|
||||
);
|
||||
} catch (error) {
|
||||
if (isDuplicateEntry(error)) {
|
||||
throw AppError.conflict("Une entreprise porte deja ce nom.");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return db.required<OrganizationRow>(`${SELECT_ORGANIZATION} WHERE o.id = ?`, [id]);
|
||||
};
|
||||
|
||||
export const deleteOrganization = async (db: Db, id: string): Promise<void> => {
|
||||
const result = await db.exec(
|
||||
"UPDATE organizations SET deleted_at = UTC_TIMESTAMP() WHERE id = ? AND deleted_at IS NULL",
|
||||
[id],
|
||||
);
|
||||
if (result.affectedRows === 0) throw AppError.notFound("Entreprise introuvable.");
|
||||
};
|
||||
|
||||
/** Retrouve l'entreprise par son nom, ou la crée (nom unique en base). */
|
||||
export const findOrCreateOrganization = async (
|
||||
db: Db,
|
||||
name: string,
|
||||
): Promise<string> => {
|
||||
const existing = await db.one<{ id: string }>(
|
||||
"SELECT id FROM organizations WHERE name = ? AND deleted_at IS NULL",
|
||||
[name],
|
||||
);
|
||||
if (existing) return existing.id;
|
||||
|
||||
const id = randomUUID();
|
||||
try {
|
||||
await db.exec("INSERT INTO organizations (id, name, slug) VALUES (?, ?, ?)", [
|
||||
id,
|
||||
name,
|
||||
slugify(name),
|
||||
]);
|
||||
} catch (error) {
|
||||
if (isDuplicateEntry(error)) {
|
||||
// Course : une autre requête vient de créer le même nom. On la rejoint.
|
||||
const raced = await db.one<{ id: string }>(
|
||||
"SELECT id FROM organizations WHERE name = ? AND deleted_at IS NULL",
|
||||
[name],
|
||||
);
|
||||
if (raced) return raced.id;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return id;
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
/** Erreurs de contrainte MariaDB, reconnues par leur code numérique. */
|
||||
|
||||
const errnoOf = (error: unknown): number | undefined =>
|
||||
typeof error === "object" && error !== null && "errno" in error
|
||||
? ((error as { errno?: number }).errno ?? undefined)
|
||||
: undefined;
|
||||
|
||||
/** 1062 : violation d'index unique. */
|
||||
export const isDuplicateEntry = (error: unknown): boolean => errnoOf(error) === 1062;
|
||||
|
||||
/** 1452 : la ligne référencée par une clé étrangère n'existe pas. */
|
||||
export const isForeignKeyViolation = (error: unknown): boolean => errnoOf(error) === 1452;
|
||||
|
||||
/** 1451 : la ligne est encore référencée, suppression impossible. */
|
||||
export const isReferencedRow = (error: unknown): boolean => errnoOf(error) === 1451;
|
||||
@@ -0,0 +1,15 @@
|
||||
/** Normalisations de texte partagées par les services. */
|
||||
|
||||
/** Slug lisible : sans accent, sans ponctuation, séparé par des tirets. */
|
||||
export const slugify = (value: string): string =>
|
||||
value
|
||||
.normalize("NFD")
|
||||
.replace(/[\u0300-\u036f]/g, "")
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 255);
|
||||
|
||||
/** Un e-mail absent ne doit pas heurter l'index unique : NULL passe partout. */
|
||||
export const normalizeEmail = (value: string | null | undefined): string | null =>
|
||||
value ? value.toLowerCase() : null;
|
||||
@@ -0,0 +1,22 @@
|
||||
import { DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE } from "../config/app.js";
|
||||
|
||||
export interface Pagination {
|
||||
page: number;
|
||||
limit: number;
|
||||
offset: number;
|
||||
}
|
||||
|
||||
const positiveInt = (raw: string | undefined, fallback: number): number => {
|
||||
const value = Number(raw ?? fallback);
|
||||
return Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallback;
|
||||
};
|
||||
|
||||
/** Lit `page`/`limit` depuis la query string et borne les valeurs. */
|
||||
export const parsePagination = (
|
||||
pageRaw: string | undefined,
|
||||
limitRaw: string | undefined,
|
||||
): Pagination => {
|
||||
const page = Math.max(1, positiveInt(pageRaw, 1));
|
||||
const limit = Math.min(MAX_PAGE_SIZE, Math.max(1, positiveInt(limitRaw, DEFAULT_PAGE_SIZE)));
|
||||
return { page, limit, offset: (page - 1) * limit };
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
export interface RateLimitOptions {
|
||||
/** Fenêtre glissante, en millisecondes. */
|
||||
windowMs: number;
|
||||
/** Nombre d'essais autorisés dans la fenêtre. */
|
||||
max: number;
|
||||
}
|
||||
|
||||
export interface RateLimiter {
|
||||
/** Enregistre une tentative et indique si elle est autorisée. */
|
||||
isAllowed: (key: string) => boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rate-limit en mémoire, suffisant pour une instance CRM unique. Derrière
|
||||
* nginx/Cloudflare, la clé vient de l'IP transmise par `x-forwarded-for`.
|
||||
*/
|
||||
export const createRateLimiter = ({ windowMs, max }: RateLimitOptions): RateLimiter => {
|
||||
const attempts = new Map<string, number[]>();
|
||||
|
||||
return {
|
||||
isAllowed: (key) => {
|
||||
const now = Date.now();
|
||||
const recent = (attempts.get(key) ?? []).filter((time) => now - time < windowMs);
|
||||
if (recent.length >= max) {
|
||||
attempts.set(key, recent);
|
||||
return false;
|
||||
}
|
||||
recent.push(now);
|
||||
attempts.set(key, recent);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
/** Construction des `UPDATE` partiels, sans jamais concaténer de valeurs. */
|
||||
|
||||
export interface Assignments {
|
||||
clause: string;
|
||||
values: unknown[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforme `{ city: "Lyon", phone: undefined }` en `city = ?`.
|
||||
* `null` reste une valeur explicite : elle efface la colonne.
|
||||
* Retourne `null` quand aucune colonne n'est fournie.
|
||||
*/
|
||||
export const buildAssignments = (
|
||||
columns: Record<string, unknown>,
|
||||
): Assignments | null => {
|
||||
const keys = Object.keys(columns).filter((key) => columns[key] !== undefined);
|
||||
if (keys.length === 0) return null;
|
||||
return {
|
||||
clause: keys.map((key) => `${key} = ?`).join(", "),
|
||||
values: keys.map((key) => columns[key]),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
import { z } from "zod";
|
||||
import { AppError } from "@cohaise/server";
|
||||
|
||||
/** Identifiant UUID v4 tel que stocké par les tables du CRM. */
|
||||
export const uuidSchema = z
|
||||
.string()
|
||||
.regex(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
|
||||
"Identifiant invalide.",
|
||||
);
|
||||
|
||||
/** Erreur 400 homogène pour un corps JSON invalide. */
|
||||
export const invalidBody = (error: z.ZodError): AppError => {
|
||||
const issue = error.issues[0];
|
||||
return AppError.badRequest(
|
||||
issue
|
||||
? `${issue.path.join(".") || "corps"} : ${issue.message}`
|
||||
: "Corps invalide.",
|
||||
);
|
||||
};
|
||||
@@ -16,6 +16,7 @@ services:
|
||||
target: export
|
||||
args:
|
||||
APP_DIR: frontend/web
|
||||
OUTPUT_DIR: out
|
||||
command: sh /publish.sh
|
||||
volumes:
|
||||
- app_data:/output
|
||||
|
||||
@@ -15,5 +15,7 @@ RUN npm run build --workspace=${APP_DIR}
|
||||
FROM alpine:3.21 AS export
|
||||
|
||||
ARG APP_DIR
|
||||
# Vite écrit dans `dist/`, Next.js (export statique) dans `out/`.
|
||||
ARG OUTPUT_DIR=dist
|
||||
|
||||
COPY --from=builder /repo/${APP_DIR}/dist /app/dist
|
||||
COPY --from=builder /repo/${APP_DIR}/${OUTPUT_DIR} /app/dist
|
||||
|
||||
+33
-5
@@ -3,6 +3,10 @@ server {
|
||||
listen [::]:80 default_server;
|
||||
server_name _;
|
||||
|
||||
# Redirections relatives (`/services/`) : derrière un proxy ou un port
|
||||
# publié, un Location absolu sans port casserait la navigation.
|
||||
absolute_redirect off;
|
||||
|
||||
root /usr/share/nginx/html/current;
|
||||
index index.html;
|
||||
|
||||
@@ -11,7 +15,7 @@ server {
|
||||
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;
|
||||
gzip_types text/plain text/css application/javascript application/json application/xml image/svg+xml image/webp application/manifest+json;
|
||||
|
||||
location = /healthz {
|
||||
access_log off;
|
||||
@@ -19,6 +23,15 @@ server {
|
||||
return 200 "ok\n";
|
||||
}
|
||||
|
||||
# Assets fingerprintés par Next.js : cache long et immuable.
|
||||
location /_next/static/ {
|
||||
include /etc/nginx/snippets/security-headers.conf;
|
||||
include /etc/nginx/snippets/cache-immutable.conf;
|
||||
expires 1y;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# Anciens assets Vite (conservés pour les releases encore servies).
|
||||
location /assets/ {
|
||||
include /etc/nginx/snippets/security-headers.conf;
|
||||
include /etc/nginx/snippets/cache-immutable.conf;
|
||||
@@ -26,13 +39,28 @@ server {
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# Image Open Graph générée par Next.js : fichier sans extension.
|
||||
location = /opengraph-image {
|
||||
include /etc/nginx/snippets/security-headers.conf;
|
||||
include /etc/nginx/snippets/cache-immutable.conf;
|
||||
default_type image/png;
|
||||
expires 1y;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# Page d'erreur générée par l'export statique Next.js.
|
||||
location = /404.html {
|
||||
internal;
|
||||
include /etc/nginx/snippets/security-headers.conf;
|
||||
include /etc/nginx/snippets/cache-no-cache.conf;
|
||||
}
|
||||
|
||||
location / {
|
||||
include /etc/nginx/snippets/security-headers.conf;
|
||||
include /etc/nginx/snippets/cache-no-cache.conf;
|
||||
try_files $uri $uri/ @spa;
|
||||
# Export statique : chaque route est un dossier avec son index.html.
|
||||
try_files $uri $uri/ =404;
|
||||
}
|
||||
|
||||
location @spa {
|
||||
try_files /index.html =404;
|
||||
}
|
||||
error_page 404 /404.html;
|
||||
}
|
||||
|
||||
+9
-7
@@ -8,7 +8,7 @@ de `docs/`.
|
||||
|
||||
| Action | Commande |
|
||||
| --- | --- |
|
||||
| Dev hot-reload | `make dev` (Vite 5173) |
|
||||
| Dev hot-reload | `make dev` (Next.js 3000) |
|
||||
| Vérifier les types | `npm run typecheck` |
|
||||
| Builder | `npm run build` |
|
||||
| Reconstruire + publier | `make web` |
|
||||
@@ -26,18 +26,20 @@ vérifications automatiques. Exécuter les deux avant de déclarer un travail fi
|
||||
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`.
|
||||
4. **La vitrine n'a pas d'API** : l'export Next est statique ; le formulaire de
|
||||
contact appelle le CRM séparé (`backend/crm`). Ne pas ajouter de route
|
||||
dynamique serveur ou de secret dans `frontend/web`.
|
||||
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`.
|
||||
- React 19, Next.js app router : les pages et layouts sont des Server
|
||||
Components ; `"use client"` uniquement quand un hook ou un événement l'exige.
|
||||
- Tailwind 4 via `@import "tailwindcss"` ; **pas de classes arbitraires en
|
||||
dur** : passer par les jetons `--cohaise-*` (`@theme inline`).
|
||||
- Un élément animé porte `data-reveal` et reste visible sans JavaScript.
|
||||
- Style visuel : `Button`, `Card`, `cn` depuis `@cohaise/ui`. Pas de
|
||||
`<div class="bg-…">` quand un composant existe.
|
||||
- `.editorconfig` : 2 espaces, LF, UTF-8.
|
||||
@@ -59,8 +61,8 @@ palettes doivent rester synchronisées.
|
||||
|
||||
- `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.
|
||||
- `backend/shared` est construit avec le reste et consommé par `backend/crm` :
|
||||
une erreur de types ici bloque `npm run typecheck` pour tout le monorepo.
|
||||
- `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é :
|
||||
|
||||
+127
-44
@@ -1,49 +1,70 @@
|
||||
# Architecture — CoHaiSe Web
|
||||
# Architecture — CoHaiSe
|
||||
|
||||
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/`.
|
||||
Monorepo à deux applications déployées séparément :
|
||||
|
||||
| Application | Sous-domaine | Stack | Compose |
|
||||
| --- | --- | --- | --- |
|
||||
| Vitrine | `cohaise.dev` | Next.js 16 (export statique) + nginx | `docker-compose.yml` |
|
||||
| CRM | `crm.cohaise.dev` | Next/Vite + API Node + MariaDB | `docker-compose.crm.yml` |
|
||||
|
||||
## 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) |
|
||||
| React | 19 | `frontend/*` |
|
||||
| Next.js (app router) | 16 | `frontend/web` |
|
||||
| Vite | 8 | `frontend/crm` |
|
||||
| Tailwind CSS | 4 (`@tailwindcss/postcss`) | `frontend/web/app/globals.css` |
|
||||
| TypeScript | 7 | `tsconfig.json` (project references) |
|
||||
| Hono + mysql2 + Zod | — | `backend/shared`, `backend/crm` |
|
||||
|
||||
`package.json` racine : `workspaces: ["frontend/*", "backend/*"]`, scripts
|
||||
`build` (`tsc --build` puis build de chaque paquet), `typecheck`, `clean`.
|
||||
`@cohaise/ui` doit être construit avant la vitrine : `tsc --build` s'en charge.
|
||||
|
||||
## Découpage
|
||||
|
||||
```
|
||||
frontend/
|
||||
shared/ @cohaise/ui — design system, DUPLOQUÉ dans les 3 dépôts CoHaiSe
|
||||
web/ @cohaise/web — la vitrine
|
||||
shared/ @cohaise/ui — design system, dupliqué dans les 3 dépôts CoHaiSe
|
||||
web/ @cohaise/web — la vitrine Next.js
|
||||
crm/ @cohaise/crm-web — le front du CRM (React + Vite)
|
||||
backend/
|
||||
shared/ @cohaise/server — couche serveur, PRÉSENTE mais INUTILISÉE ici
|
||||
docker/ Dockerfile, Dockerfile.app, nginx/, publish.sh
|
||||
shared/ @cohaise/server — config, base, auth, http, migrations
|
||||
crm/ @cohaise/crm — l'API du CRM
|
||||
docker/ Dockerfile, Dockerfile.app, Dockerfile.api, 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.
|
||||
### Backend CRM
|
||||
|
||||
## Chaîne de build
|
||||
```
|
||||
backend/crm/src/
|
||||
index.ts composition du service (routes + purge des sessions)
|
||||
admin.ts création/réinitialisation de comptes hors HTTP
|
||||
config/app.ts constantes métier (pagination, rate-limit, source lead)
|
||||
middleware/auth.ts montage de `attachUser` sur une ressource
|
||||
models/types.ts lignes SQL et formes exposées par l'API
|
||||
routes/*Routes.ts routes minces : validation Zod, HTTP, statuts
|
||||
services/*Service.ts requêtes et règles métier
|
||||
utils/ dbErrors, normalize, pagination, rateLimit, sql, validation
|
||||
```
|
||||
|
||||
Le socle (`Db`, `App`, sessions, erreurs) reste dans `@cohaise/server` : la
|
||||
réorganisation n'a changé ni la stack ni les contrats HTTP.
|
||||
|
||||
## Chaîne de build de la vitrine
|
||||
|
||||
Deux images, deux rôles :
|
||||
|
||||
1. **`docker/Dockerfile.app`** (`target: export`) — stage `builder` `node:22-alpine` :
|
||||
1. **`docker/Dockerfile.app`** (`target: export`) — stage `builder` `node:22-slim` :
|
||||
`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/<UTC>-<pid>`, 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.
|
||||
`--workspace=${APP_DIR}`. `OUTPUT_DIR` choisit le dossier produit (`out` pour
|
||||
Next, `dist` pour Vite). Le stage `export` recopie ce dossier dans
|
||||
`/app/dist`.
|
||||
2. **`docker/publish.sh`** — tourne dans `app-build` avec le volume `app_data`
|
||||
monté : copie dans `releases/<UTC>-<pid>`, 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.
|
||||
|
||||
@@ -51,38 +72,100 @@ Publication **atomique** : nginx ne voit jamais un répertoire à moitié écrit
|
||||
|
||||
`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` |
|
||||
| Point | Comportement |
|
||||
| --- | --- |
|
||||
| Racine | `/usr/share/nginx/html/current` (symlink) |
|
||||
| `/healthz` | `200 ok`, log coupé |
|
||||
| `/_next/static/` | `expires 1y`, `Cache-Control: public, immutable` |
|
||||
| `/opengraph-image` | fichier sans extension servi en `image/png` |
|
||||
| `/404.html` | page d'erreur générée par l'export Next |
|
||||
| Racine applicative | `no-cache`, `try_files $uri $uri/ =404` (pas de fallback SPA) |
|
||||
| gzip | actif, `min_length 1024` |
|
||||
| En-têtes | `snippets/security-headers.conf` au niveau serveur **et** dans chaque `location` |
|
||||
|
||||
Chaque route Next est un dossier avec son `index.html` (`trailingSlash: true`).
|
||||
|
||||
## 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
|
||||
- **App router** : `app/layout.tsx` porte le shell, les providers, le fond et les
|
||||
métadonnées par défaut. Une page SEO autonome par section (`/services`,
|
||||
`/demos`, `/stack`, `/about`, `/contact`), plus `/` qui compose les mêmes
|
||||
sections. Le menu se comporte comme une barre d'onglets : une pastille
|
||||
glisse d'une entrée à l'autre et l'URL ne reçoit **aucun `#`**. Sur
|
||||
l'accueil, le clic fait défiler jusqu'à la région et l'onglet actif suit le
|
||||
défilement ; depuis une page autonome, la cible est mémorisée dans
|
||||
`sessionStorage` puis rejointe après le retour à `/`. Ces pages tiennent en
|
||||
un écran (voir `globals.css`, règle `:only-child`) et ne défilent pas.
|
||||
- **SEO** : `metadata` par page, canonical, OpenGraph/Twitter, JSON-LD
|
||||
`Organization`/`WebSite`/`ProfessionalService` sur l'accueil, `sitemap.ts`,
|
||||
`robots.ts` et `opengraph-image.tsx` généré (1200×630).
|
||||
- **Bilingue** : toggle client FR/EN (`LanguageContext`). Le HTML prérendu est en
|
||||
français — c'est la version indexée. La préférence stockée est appliquée après
|
||||
le montage pour éviter tout mismatch d'hydratation.
|
||||
- **Thème clair/sombre** : script inline dans `app/layout.tsx` (anti-FOUC) lit
|
||||
`localStorage["cohaise-theme"]`, sinon `prefers-color-scheme`, puis pose la
|
||||
classe `.dark` sur `<html>`. Le basculeur écrit via `useTheme`.
|
||||
- **Design system** : `Button`, `Card`, `cn` sont les seuls composants utilisés.
|
||||
`Input` est un `<input>` 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.
|
||||
classe `.dark` sur `<html>`. `ThemeContext` lit cet état après le montage.
|
||||
Le bouton d'en-tête (`ThemeToggle`) est une icône seule : lune en clair,
|
||||
soleil en sombre, avec étoile et transition rotation/fondu (`.theme-icon-*`
|
||||
dans `globals.css`).
|
||||
- **Régions plein écran** : chaque section est un `<section data-region>`
|
||||
(`Section`) en `min-h-dvh` ; Stack et About partagent une seule région sur
|
||||
l'accueil (`StackAbout`). `scroll-snap-type: y mandatory` +
|
||||
`scroll-snap-stop: always` (voir `globals.css`) empêchent de s'arrêter entre
|
||||
deux régions ou d'en sauter une. Le footer, hors région, s'aligne sur la fin
|
||||
du viewport pour rester atteignable. Si une région dépasse la hauteur de
|
||||
l'écran (téléphone étroit, texte long), `useScrollReveal` pose
|
||||
`html[data-snap="off"]` et le snap est coupé pour ne pas bloquer le contenu.
|
||||
Snap aussi désactivé en `prefers-reduced-motion` et sous 620 px de hauteur.
|
||||
- **Animations** : `useScrollReveal` observe chaque `[data-region]` via une
|
||||
bande centrale du viewport. Une fois la région stable à l'écran, ses
|
||||
éléments `[data-reveal]` apparaissent en cascade après 0,25 s (le hero est
|
||||
réglé à 0,05 s). Quitter la région avant la fin annule le minuteur : elle se
|
||||
révélera au prochain passage. `data-reveal-delay` décale les voisins et
|
||||
`prefers-reduced-motion` désactive tout. Pendant une séquence de menu
|
||||
(`data-scroll-anim`), la région traversée est révélée sans délai.
|
||||
- **Défilement** : GSAP `ScrollToPlugin` (`scrollToSection`) anime les sauts du
|
||||
menu **région par région** (une étape par région traversée, courte
|
||||
respiration entre chaque) ; le snap est suspendu le temps de la séquence
|
||||
(`html[data-scroll-anim]`) pour que le navigateur ne saute pas directement à
|
||||
la destination, et un geste de défilement l'interrompt. Pas de
|
||||
`scroll-behavior: smooth` global, qui entrerait en conflit avec GSAP. Le snap
|
||||
s'applique aux sections de `main[data-scroll-snap]`.
|
||||
- **Fond WebGL** : `Topography` est un Client Component chargé via
|
||||
`next/dynamic` avec `ssr: false`, en position fixed derrière le contenu.
|
||||
- **Contact** : le formulaire POSTe vers `POST /api/crm/leads` du CRM
|
||||
(`NEXT_PUBLIC_CRM_API_URL` au build, sinon `https://crm.cohaise.dev`).
|
||||
|
||||
## Front CRM
|
||||
|
||||
- **Shell fixe** : `Crm` occupe `h-dvh` en `overflow-hidden` ; l'en-tête reste
|
||||
figé et le reste du viewport est **une seule surface** : rail d'onglets à
|
||||
gauche (15 % à partir de `md`, icônes seules en dessous), vue des données à
|
||||
droite. La page ne défile jamais ; seules les zones de contenu portent leur
|
||||
propre défilement (`DataTable`, formulaire du dialogue).
|
||||
- **Profondeur** : seul l'en-tête porte `.glass` (flou d'arrière-plan). La
|
||||
surface de travail est un simple voile `bg-surface/40` sans flou ; c'est le
|
||||
`DataTable` qui porte son propre fond translucide et flouté.
|
||||
- **DataTable** : `components/DataTable.tsx` affiche la liste triable, la
|
||||
recherche, les actions de ligne, le squelette, l'état vide et les cartes
|
||||
mobiles. L'en-tête reste collé et le tableau défile dans son cadre
|
||||
(`overflow-auto`). Les pages ne réimplémentent plus de `<table>`.
|
||||
- **Saisie** : `RecordDialog` borne le formulaire à la hauteur de l'écran ;
|
||||
seul le corps du dialogue défile, y compris sur téléphone.
|
||||
- **Fond** : `FaultyTerminalBackdrop` est monté sur l'écran connecté, la
|
||||
connexion, le changement de mot de passe et l'attente de session.
|
||||
|
||||
## 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 :
|
||||
les reçoit par `@theme inline` (`theme.css`). La vitrine importe le design system
|
||||
depuis `app/globals.css` :
|
||||
|
||||
```css
|
||||
@import "tailwindcss";
|
||||
@import "@cohaise/ui/styles";
|
||||
@source "../../../../frontend/shared/src";
|
||||
|
||||
@source "../../shared/src";
|
||||
```
|
||||
|
||||
`--cohaise-destructive` est un rouge (`#d32f2f` clair / `#ef4444` sombre),
|
||||
|
||||
+33
-21
@@ -1,35 +1,42 @@
|
||||
# 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`.
|
||||
`attachUser` sur `auth`, `countries`, `organizations` et `contacts` ;
|
||||
`requireAuth` sur toutes leurs routes sauf la connexion. `POST /leads` est
|
||||
public (formulaire de la vitrine). **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` |
|
||||
| POST | `/api/crm/auth/login` | `routes/authRoutes.ts` |
|
||||
| POST | `/api/crm/auth/logout` | `routes/authRoutes.ts` |
|
||||
| GET | `/api/crm/auth/me` | `routes/authRoutes.ts` |
|
||||
| POST | `/api/crm/auth/change-password` | `routes/authRoutes.ts` |
|
||||
| GET | `/api/crm/countries?q=` | `routes/countryRoutes.ts` |
|
||||
| POST | `/api/crm/countries` | `routes/countryRoutes.ts` |
|
||||
| PATCH | `/api/crm/countries/:id` | `routes/countryRoutes.ts` |
|
||||
| DELETE | `/api/crm/countries/:id` | `routes/countryRoutes.ts` |
|
||||
| GET | `/api/crm/organizations?q&page&limit` | `routes/organizationRoutes.ts` |
|
||||
| GET | `/api/crm/organizations/:id` | `routes/organizationRoutes.ts` |
|
||||
| POST | `/api/crm/organizations` | `routes/organizationRoutes.ts` |
|
||||
| PATCH | `/api/crm/organizations/:id` | `routes/organizationRoutes.ts` |
|
||||
| DELETE | `/api/crm/organizations/:id` | `routes/organizationRoutes.ts` |
|
||||
| GET | `/api/crm/contacts?q&organizationId&page&limit` | `routes/contactRoutes.ts` |
|
||||
| GET | `/api/crm/contacts/:id` | `routes/contactRoutes.ts` |
|
||||
| POST | `/api/crm/contacts` | `routes/contactRoutes.ts` |
|
||||
| PATCH | `/api/crm/contacts/:id` | `routes/contactRoutes.ts` |
|
||||
| DELETE | `/api/crm/contacts/:id` | `routes/contactRoutes.ts` |
|
||||
| POST | `/api/crm/leads` | `routes/leadRoutes.ts` |
|
||||
|
||||
Chaque route valide son corps puis délègue à `services/*Service.ts` ; aucune
|
||||
requête SQL n'est écrite dans `routes/`.
|
||||
|
||||
### Conventions communes
|
||||
|
||||
- Corps validés par Zod (`createX`/`updateX`, `credentials`, `changePassword`).
|
||||
- Corps validés par Zod dans les routes (`createXBody`, `updateXBody`,
|
||||
`credentials`, `newPassword`, `leadBody`).
|
||||
- `: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.
|
||||
@@ -84,3 +91,8 @@ CLI : `cohaise-migrate --dir <dossier> [--dry-run] [--check]`, codes `0` / `1`
|
||||
|
||||
Le DDL MariaDB n'est pas transactionnel : une migration interrompue se corrige
|
||||
par un **nouveau** fichier, jamais en éditant l'ancien.
|
||||
|
||||
`make crm-migrate` applique les migrations **puis reconstruit et redémarre
|
||||
l'API** : un binaire plus ancien que le schéma (par exemple du code qui lit
|
||||
encore `roles` après `007`) répondrait `NOT_MIGRATED` alors que la base est à
|
||||
jour.
|
||||
|
||||
+2
-2
@@ -16,7 +16,7 @@ make up # build + démarrage sur 8080
|
||||
|
||||
| Service | Image | Port | Rôle |
|
||||
| --- | --- | --- | --- |
|
||||
| `app-build` | `docker/Dockerfile.app` | — | build Vite, `restart: "no"` |
|
||||
| `app-build` | `docker/Dockerfile.app` | — | build Next.js (`out/`), `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
|
||||
@@ -45,7 +45,7 @@ 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 dev # Next.js local sur 3000 (hors Docker)
|
||||
make down # arrêt, volumes conservés
|
||||
```
|
||||
|
||||
|
||||
+18
-15
@@ -1,8 +1,9 @@
|
||||
# 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.
|
||||
Surface minimale : un export statique Next.js, sans comptes ni cookies côté
|
||||
vitrine. Seul appel réseau : le formulaire de contact vers l'API du CRM. 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
|
||||
|
||||
@@ -16,19 +17,20 @@ 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.
|
||||
Le snippet est inclus au niveau `server` **et** dans chaque `location` (assets
|
||||
Next, image OG, `/`, `/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/`.
|
||||
- Un seul appel réseau côté client : `POST /api/crm/leads` (formulaire de
|
||||
contact), vers le CRM.
|
||||
- Aucune clé : seule `NEXT_PUBLIC_CRM_API_URL` est lue au build, et elle est
|
||||
publique par construction.
|
||||
- `.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é.
|
||||
- Stockage navigateur limité à `cohaise-theme` et `cohaise-lang`.
|
||||
- Aucun cookie posé par la vitrine ; les sessions appartiennent au CRM, sur son
|
||||
propre domaine.
|
||||
|
||||
### Ressources
|
||||
|
||||
@@ -44,7 +46,7 @@ donc aucun en-tête `Referrer-Policy` à négocier avec un CDN et aucun
|
||||
| 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 |
|
||||
| Rate limiting | côté CRM | l'endpoint public `POST /api/crm/leads` porte honeypot + 5 envois/IP/15 min ; la vitrine n'a aucun endpoint |
|
||||
| TLS | hors du dépôt | nginx n'écoute que le `80`, le terminus HTTPS est le tunnel |
|
||||
|
||||
## Chaîne de confiance
|
||||
@@ -60,7 +62,8 @@ tunnel cloudflared → nginx:8080 → /usr/share/nginx/html/current → rele
|
||||
|
||||
## À 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 brancher de clé ou de token dans le front : la vitrine est publique,
|
||||
tout ce qui est dans le bundle est lisible. Les secrets restent dans le CRM.
|
||||
- Ne pas ajouter de ressource externe (font CDN, script analytics) sans réviser
|
||||
les en-têtes et `index.html`.
|
||||
les en-têtes et `frontend/web/app/layout.tsx`.
|
||||
- Ne pas publier `.env` : il contient des clés héritées d'autres apps.
|
||||
|
||||
+76
-4
@@ -13,8 +13,10 @@ Conventions à respecter pour que ce dépôt reste cohérent avec les deux autre
|
||||
| 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.
|
||||
Aucun Prettier n'est installé : l'éditeur et l'`.editorconfig` sont la seule
|
||||
norme mécanique. ESLint a été retiré de `frontend/web` : `typescript-eslint`
|
||||
ne supporte pas encore TypeScript 7.0. Ne pas le réintroduire tant que ce
|
||||
support n'existe pas.
|
||||
|
||||
## Palette
|
||||
|
||||
@@ -62,19 +64,89 @@ Chargées en local (`frontend/shared/fonts/*.woff2`), jamais par CDN :
|
||||
## Thème
|
||||
|
||||
- Bascule clair/sombre par la classe `.dark` sur `<html>`.
|
||||
- Script inline dans `index.html` (avant le bundle) : lit
|
||||
- Script inline dans `frontend/web/app/layout.tsx` (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.
|
||||
|
||||
## Next.js (vitrine)
|
||||
|
||||
- Tout fichier qui utilise un hook, un événement ou une API navigateur porte
|
||||
`"use client"` ; les pages et le layout restent des Server Components.
|
||||
- Les métadonnées SEO vont dans `export const metadata` (page ou layout), pas
|
||||
dans un composant client. Une page = une entrée dans `app/lib/site.ts` pour
|
||||
rester alignée avec le sitemap.
|
||||
- Les données statiques vivent dans `app/data/`. Un objet contenant des
|
||||
fonctions ou des icônes React ne doit jamais traverser la frontière
|
||||
serveur → client : le composant importe la donnée lui-même.
|
||||
- Une section = une région plein écran : `<Section>` pose `data-region` et
|
||||
`min-h-dvh`. Ne pas créer de section hors de ce composant, sinon elle
|
||||
échappe au scroll-snap.
|
||||
- Les reveals passent par `data-reveal` / `data-reveal-delay` et
|
||||
`useScrollReveal` (délai par région via `data-region-delay`) ; ne pas
|
||||
animer un élément sans prévoir son état sans JS.
|
||||
- `next build` produit `out/` (`output: "export"`). Ne pas ajouter de route
|
||||
dynamique sans vérifier la compatibilité avec l'export statique.
|
||||
- Le menu de l'en-tête est une barre d'onglets, pas une liste d'ancres : aucun
|
||||
`#` n'est écrit dans l'URL. Sur l'accueil, clic → séquence GSAP région par
|
||||
région et pastille qui glisse vers l'onglet ; ailleurs, la cible passe par
|
||||
`setPendingSection`/`sessionStorage` puis est rejointe après le retour à `/`.
|
||||
`scrollToSection` suspend le snap (`data-scroll-anim`) le temps de la
|
||||
séquence, sinon le navigateur saute directement à la destination ; la durée
|
||||
renvoyée prolonge le verrou d'onglet. L'onglet actif suit la région visible
|
||||
(bande centrale) sauf pendant le défilement déclenché par un clic, où il
|
||||
reste sur l'entrée choisie. Une cible imbriquée (About dans la région Stack)
|
||||
est ramenée à sa région par `scrollToSection`, car le snap opère par région.
|
||||
- Les pages SEO autonomes (`/services`, `/about`, …) réutilisent une seule
|
||||
région sans pied de page et tiennent dans le viewport (règle
|
||||
`section[data-region]:only-child` dans `globals.css`). Ne pas les laisser
|
||||
défiler : le menu est justement là pour ramener aux régions de l'accueil.
|
||||
|
||||
## Front CRM
|
||||
|
||||
- La page ne défile **jamais** : le shell est en `h-dvh overflow-hidden`, et les
|
||||
zones de contenu (`DataTable`, dialogue) portent `min-h-0` + `overflow-auto`.
|
||||
Ne pas retirer `min-h-0` d'un parent flex, sinon le tableau repousse la page.
|
||||
- Toute liste passe par `components/DataTable.tsx` : colonnes triables,
|
||||
recherche, actions de ligne, squelette et cartes sous `md`. Ne pas recréer un
|
||||
`<table>` dans une page.
|
||||
- Les formulaires de création/édition passent par `RecordDialog` ; seul son
|
||||
corps défile. Les boutons d'action de ligne utilisent `RowActionButton`.
|
||||
- Les pictogrammes viennent des WebP du dépôt, rendus par `MaskIcon` dans
|
||||
`components/icons.tsx` : `FolderMaskIcon`/`UsersMaskIcon`/`ActivityMaskIcon`
|
||||
pour le rail, `PenMaskIcon`, `TrashMaskIcon`, `SearchMaskIcon`,
|
||||
`CloseMaskIcon`, `LogoutMaskIcon` pour les actions. Le masque CSS +
|
||||
`background-color: currentColor` permet au survol de les teinter en accent ou
|
||||
en destructif sans filtre. Ne pas revenir à un `<img>` : les fichiers sont
|
||||
blancs et disparaîtraient sur fond clair. `components/glyphs.tsx` ne garde que
|
||||
les flèches (`ChevronDownGlyph`, `ArrowUpGlyph`).
|
||||
- L'en-tête du CRM porte `.glass` (défini dans `theme.css`, commun à la vitrine
|
||||
et au CRM) ; la surface de travail reste sans flou et `DataTable` porte son
|
||||
propre fond translucide (`bg-surface/80 backdrop-blur-xl`), avec un en-tête
|
||||
sticky à `/90` pour garder le texte lisible quand les lignes passent dessous.
|
||||
- Les champs (`Input` partagé, selects, recherche) réagissent au survol par un
|
||||
bord accent ; le bouton de déconnexion est une icône seule
|
||||
(`LogoutMaskIcon`) avec `aria-label` et `title`, jamais un libellé visible.
|
||||
|
||||
## Backend CRM
|
||||
|
||||
- Une route valide l'entrée (Zod), appelle un service, renvoie le statut HTTP.
|
||||
Aucune requête SQL directement dans `routes/`.
|
||||
- Un service reçoit `db` et des données déjà typées ; il lève `AppError` pour
|
||||
les cas métier (404, 409, 422) et laisse remonter le reste.
|
||||
- Les noms de colonnes SQL restent dans les services et `models/types.ts` ;
|
||||
l'API expose ses propres champs.
|
||||
- Les erreurs de contrainte MariaDB passent par `utils/dbErrors.ts` (1062,
|
||||
1451, 1452), jamais par une comparaison de message.
|
||||
|
||||
## 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/`.
|
||||
`dist/`, `.next/`, `out/`, `*.log`, `backups/`.
|
||||
- `docs/` est **versionné** (la ligne `docs/` de `.gitignore` a été retirée).
|
||||
|
||||
## Interdépôts
|
||||
|
||||
+19
-12
@@ -3,11 +3,12 @@
|
||||
## Boucle de développement
|
||||
|
||||
```sh
|
||||
make dev # Vite sur http://localhost:5173, hot reload
|
||||
make dev # Next.js sur http://localhost:3000, 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`.
|
||||
Le serveur de dev sert `frontend/web` avec Next.js. Il n'a pas besoin de Docker
|
||||
ni de `.env`. Pour tester le formulaire de contact, l'API CRM doit tourner sur
|
||||
`http://localhost:8082` (ou définir `NEXT_PUBLIC_CRM_API_URL`).
|
||||
|
||||
## Vérification avant de valider
|
||||
|
||||
@@ -53,26 +54,32 @@ dépôts CoHaiSe.** Il n'y a pas de version centrale.
|
||||
| --- | --- |
|
||||
| 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/` |
|
||||
| Page, layout, contenu | `frontend/web/app/**` |
|
||||
| Routes et métadonnées SEO | `frontend/web/app/*/page.tsx`, `frontend/web/app/lib/site.ts` |
|
||||
| Sitemap / robots / image OG | `frontend/web/app/sitemap.ts`, `robots.ts`, `opengraph-image.tsx` |
|
||||
| Animations d'entrée | `frontend/web/app/hooks/useScrollReveal.ts` + `globals.css` |
|
||||
| Cache, en-têtes, 404 | `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` |
|
||||
| Thème par défaut | script inline de `frontend/web/app/layout.tsx` |
|
||||
|
||||
## 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`).
|
||||
- Ne jamais committer `.env`, `node_modules/`, `dist/`, `out/`, `.next/`
|
||||
(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`.
|
||||
2. **`backend/shared` est construit avec le reste** : il est consommé par
|
||||
`backend/crm`, mais une erreur de types ici bloque aussi `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.
|
||||
4. **Export statique** : `next build` écrit dans `out/`, pas `dist/`. Ne pas
|
||||
ajouter de route dynamique sans vérifier la compatibilité avec
|
||||
`output: "export"`.
|
||||
5. **Pas d'ESLint** : `typescript-eslint` ne supporte pas TypeScript 7.0. Seuls
|
||||
`typecheck` et `build` vérifient le code.
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 74 KiB After Width: | Height: | Size: 195 KiB |
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Spinner } from "@cohaise/ui";
|
||||
import { ApiError, api, type User } from "./lib/api.js";
|
||||
import { FaultyTerminalBackdrop } from "./components/FaultyTerminalBackdrop.js";
|
||||
import { Login } from "./pages/Login.js";
|
||||
import { ChangePassword } from "./pages/ChangePassword.js";
|
||||
import { Crm } from "./pages/Crm.js";
|
||||
@@ -35,8 +36,11 @@ export const App = () => {
|
||||
|
||||
if (session.state === "loading") {
|
||||
return (
|
||||
<div className="flex min-h-dvh items-center justify-center bg-background">
|
||||
<Spinner size="md" />
|
||||
<div className="relative flex min-h-dvh items-center justify-center bg-background">
|
||||
<FaultyTerminalBackdrop />
|
||||
<div className="relative z-10">
|
||||
<Spinner size="md" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
import { useMemo, useState, type ReactNode } from "react";
|
||||
import { cn, Skeleton, Spinner } from "@cohaise/ui";
|
||||
import { SearchMaskIcon } from "./icons.js";
|
||||
|
||||
export interface DataTableColumn<T> {
|
||||
/** Identifiant stable de la colonne, utilisé pour le tri. */
|
||||
id: string;
|
||||
header: string;
|
||||
cell: (row: T) => ReactNode;
|
||||
sortable?: boolean;
|
||||
/** Valeur brute comparée lors du tri. Obligatoire si `sortable`. */
|
||||
sortValue?: (row: T) => string | number | null | undefined;
|
||||
className?: string;
|
||||
headerClassName?: string;
|
||||
/** Masque la colonne sur les cartes mobiles (utile pour un champ secondaire). */
|
||||
mobileHidden?: boolean;
|
||||
}
|
||||
|
||||
type SortDirection = "asc" | "desc";
|
||||
|
||||
interface SortState {
|
||||
column: string;
|
||||
direction: SortDirection;
|
||||
}
|
||||
|
||||
export interface DataTableProps<T> {
|
||||
data: T[];
|
||||
columns: DataTableColumn<T>[];
|
||||
keyExtractor: (row: T) => string | number;
|
||||
loading?: boolean;
|
||||
error?: string | null;
|
||||
emptyMessage?: string;
|
||||
emptyHint?: string;
|
||||
search?: {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
placeholder?: string;
|
||||
};
|
||||
/** Contenu libre à gauche de la barre d'outils, quand il n'y a pas de recherche. */
|
||||
toolbarStart?: ReactNode;
|
||||
/** Bouton(s) à droite de la barre d'outils, par exemple « Nouveau ». */
|
||||
actions?: ReactNode;
|
||||
rowActions?: (row: T) => ReactNode;
|
||||
footer?: ReactNode;
|
||||
initialSort?: SortState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tableau de données du CRM.
|
||||
*
|
||||
* La page ne défile jamais : ce composant occupe la hauteur restante
|
||||
* (`min-h-0 flex-1`) et seul le bloc tableau (`overflow-auto`) défile. L'en-tête
|
||||
* reste collé en haut, les actions sont alignées à droite et chaque ligne
|
||||
* devient une carte sous `md`.
|
||||
*/
|
||||
export function DataTable<T>({
|
||||
data,
|
||||
columns,
|
||||
keyExtractor,
|
||||
loading = false,
|
||||
error = null,
|
||||
emptyMessage = "Aucun résultat",
|
||||
emptyHint,
|
||||
search,
|
||||
toolbarStart,
|
||||
actions,
|
||||
rowActions,
|
||||
footer,
|
||||
initialSort,
|
||||
}: DataTableProps<T>) {
|
||||
const [sort, setSort] = useState<SortState | null>(initialSort ?? null);
|
||||
|
||||
const sorted = useMemo(() => {
|
||||
if (!sort) return data;
|
||||
const column = columns.find((item) => item.id === sort.column);
|
||||
const read = column?.sortValue;
|
||||
if (!read) return data;
|
||||
|
||||
const direction = sort.direction === "asc" ? 1 : -1;
|
||||
return [...data].sort((left, right) => {
|
||||
const a = read(left);
|
||||
const b = read(right);
|
||||
const aEmpty = a === null || a === undefined || a === "";
|
||||
const bEmpty = b === null || b === undefined || b === "";
|
||||
// Les valeurs absentes restent en fin de liste, quel que soit le sens.
|
||||
if (aEmpty && bEmpty) return 0;
|
||||
if (aEmpty) return 1;
|
||||
if (bEmpty) return -1;
|
||||
if (typeof a === "number" && typeof b === "number") return (a - b) * direction;
|
||||
return (
|
||||
String(a).localeCompare(String(b), "fr", { sensitivity: "base", numeric: true }) *
|
||||
direction
|
||||
);
|
||||
});
|
||||
}, [columns, data, sort]);
|
||||
|
||||
const toggleSort = (column: DataTableColumn<T>) => {
|
||||
if (!column.sortable || !column.sortValue) return;
|
||||
setSort((current) =>
|
||||
current?.column === column.id
|
||||
? { column: column.id, direction: current.direction === "asc" ? "desc" : "asc" }
|
||||
: { column: column.id, direction: "asc" },
|
||||
);
|
||||
};
|
||||
|
||||
const showSkeleton = loading && data.length === 0;
|
||||
const hasActions = Boolean(rowActions);
|
||||
const columnCount = columns.length + (hasActions ? 1 : 0);
|
||||
const showToolbar = Boolean(search || toolbarStart || actions);
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-4">
|
||||
{showToolbar ? (
|
||||
<div className="flex shrink-0 flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex min-w-0 flex-1 flex-wrap items-center gap-3">
|
||||
{search ? (
|
||||
<div className="relative w-full sm:max-w-xs">
|
||||
<SearchMaskIcon className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-subtle-foreground" />
|
||||
<input
|
||||
type="search"
|
||||
value={search.value}
|
||||
onChange={(event) => search.onChange(event.target.value)}
|
||||
placeholder={search.placeholder ?? "Rechercher…"}
|
||||
className="h-9 w-full rounded-sm border border-border-control bg-surface pl-9 pr-3 text-sm text-foreground placeholder:text-subtle-foreground transition-[background-color,border-color,box-shadow] duration-fast ease-out-soft hover:border-accent/60 hover:bg-surface-raised focus-visible:border-border-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{toolbarStart}
|
||||
</div>
|
||||
{actions ? <div className="flex shrink-0 items-center gap-2">{actions}</div> : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{error ? (
|
||||
<p className="shrink-0 text-sm text-destructive" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="relative flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border border-border bg-surface/80 shadow-sm backdrop-blur-xl before:pointer-events-none before:absolute before:inset-x-0 before:top-0 before:z-20 before:h-px before:bg-accent-graphic">
|
||||
{/* Tableau : au-delà de md. Le conteneur porte seul le défilement. */}
|
||||
<div
|
||||
className="hidden min-h-0 flex-1 overflow-auto md:block"
|
||||
aria-busy={loading}
|
||||
data-table-scroll="desktop"
|
||||
>
|
||||
<table className="w-full min-w-[42rem] border-separate border-spacing-0 text-left text-sm">
|
||||
<thead className="sticky top-0 z-10">
|
||||
<tr>
|
||||
{columns.map((column) => {
|
||||
const active = sort?.column === column.id;
|
||||
return (
|
||||
<th
|
||||
key={column.id}
|
||||
scope="col"
|
||||
aria-sort={
|
||||
active
|
||||
? sort.direction === "asc"
|
||||
? "ascending"
|
||||
: "descending"
|
||||
: column.sortable
|
||||
? "none"
|
||||
: undefined
|
||||
}
|
||||
className={cn(
|
||||
"border-b border-border bg-surface/90 px-4 py-3 font-display text-[0.6875rem] font-semibold uppercase tracking-label text-subtle-foreground backdrop-blur-xl",
|
||||
column.headerClassName,
|
||||
)}
|
||||
>
|
||||
{column.sortable && column.sortValue ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleSort(column)}
|
||||
className={cn(
|
||||
"group inline-flex items-center gap-1.5 transition-colors hover:text-foreground",
|
||||
active && "text-foreground",
|
||||
)}
|
||||
>
|
||||
{column.header}
|
||||
<SortGlyph direction={active ? sort.direction : null} />
|
||||
</button>
|
||||
) : (
|
||||
column.header
|
||||
)}
|
||||
</th>
|
||||
);
|
||||
})}
|
||||
{hasActions ? (
|
||||
<th
|
||||
scope="col"
|
||||
className="border-b border-border bg-surface/90 px-4 py-3 text-right font-display text-[0.6875rem] font-semibold uppercase tracking-label text-subtle-foreground backdrop-blur-xl"
|
||||
>
|
||||
Actions
|
||||
</th>
|
||||
) : null}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{showSkeleton ? (
|
||||
Array.from({ length: 7 }).map((_, rowIndex) => (
|
||||
<tr key={rowIndex}>
|
||||
{Array.from({ length: columnCount }).map((__, cellIndex) => (
|
||||
<td key={cellIndex} className="border-b border-border/60 px-4 py-3.5">
|
||||
<Skeleton
|
||||
className="h-4"
|
||||
width={cellIndex === 0 ? "70%" : cellIndex === columnCount - 1 ? "40%" : "55%"}
|
||||
/>
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))
|
||||
) : sorted.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={columnCount} className="px-6 py-16">
|
||||
<div className="flex flex-col items-center gap-1 text-center">
|
||||
<p className="font-display text-sm font-semibold uppercase tracking-label text-foreground">
|
||||
{emptyMessage}
|
||||
</p>
|
||||
{emptyHint ? (
|
||||
<p className="text-sm text-muted-foreground">{emptyHint}</p>
|
||||
) : null}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
sorted.map((row) => {
|
||||
const key = keyExtractor(row);
|
||||
return (
|
||||
<tr
|
||||
key={key}
|
||||
className="transition-colors hover:bg-surface-hover/60"
|
||||
>
|
||||
{columns.map((column) => (
|
||||
<td
|
||||
key={column.id}
|
||||
className={cn(
|
||||
"border-b border-border/60 px-4 py-3.5 align-middle",
|
||||
column.className,
|
||||
)}
|
||||
>
|
||||
{column.cell(row)}
|
||||
</td>
|
||||
))}
|
||||
{hasActions ? (
|
||||
<td className="border-b border-border/60 px-4 py-3.5 text-right">
|
||||
{rowActions?.(row)}
|
||||
</td>
|
||||
) : null}
|
||||
</tr>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Cartes : en dessous de md. Même zone de défilement, aucun scroll de page. */}
|
||||
<div
|
||||
className="flex min-h-0 flex-1 flex-col gap-3 overflow-auto p-3 md:hidden"
|
||||
aria-busy={loading}
|
||||
data-table-scroll="mobile"
|
||||
>
|
||||
{showSkeleton ? (
|
||||
Array.from({ length: 4 }).map((_, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex flex-col gap-3 rounded-lg border border-border bg-surface-raised/75 p-4 backdrop-blur-sm"
|
||||
>
|
||||
<Skeleton className="h-3" width="35%" />
|
||||
<Skeleton className="h-4" width="75%" />
|
||||
<Skeleton className="h-3" width="45%" />
|
||||
<Skeleton className="h-4" width="60%" />
|
||||
</div>
|
||||
))
|
||||
) : sorted.length === 0 ? (
|
||||
<div className="flex flex-col items-center gap-1 px-6 py-12 text-center">
|
||||
<p className="font-display text-sm font-semibold uppercase tracking-label text-foreground">
|
||||
{emptyMessage}
|
||||
</p>
|
||||
{emptyHint ? (
|
||||
<p className="text-sm text-muted-foreground">{emptyHint}</p>
|
||||
) : null}
|
||||
</div>
|
||||
) : (
|
||||
sorted.map((row) => {
|
||||
const key = keyExtractor(row);
|
||||
return (
|
||||
<article
|
||||
key={key}
|
||||
className="rounded-lg border border-border bg-surface-raised/75 p-4 shadow-sm backdrop-blur-sm"
|
||||
>
|
||||
<dl className="flex flex-col gap-3">
|
||||
{columns
|
||||
.filter((column) => !column.mobileHidden)
|
||||
.map((column) => (
|
||||
<div key={column.id} className="flex flex-col gap-0.5">
|
||||
<dt className="font-display text-[0.625rem] font-semibold uppercase tracking-label text-subtle-foreground">
|
||||
{column.header}
|
||||
</dt>
|
||||
<dd className="break-words text-sm">{column.cell(row)}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
{hasActions ? (
|
||||
<div className="mt-4 flex justify-end border-t border-border pt-3">
|
||||
{rowActions?.(row)}
|
||||
</div>
|
||||
) : null}
|
||||
</article>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
|
||||
{footer ? (
|
||||
<div
|
||||
className="flex shrink-0 items-center justify-between gap-3 border-t border-border bg-surface/70 px-4 py-2 text-xs text-subtle-foreground backdrop-blur-xl"
|
||||
data-table-footer=""
|
||||
>
|
||||
<span>{footer}</span>
|
||||
{loading && !showSkeleton ? <Spinner size="xs" /> : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const SortGlyph = ({ direction }: { direction: SortDirection | null }) => (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={2}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden="true"
|
||||
className="h-3.5 w-3.5 shrink-0"
|
||||
>
|
||||
<path d="m8 9 4-4 4 4" className={direction === "asc" ? "opacity-100" : "opacity-25"} />
|
||||
<path
|
||||
d="m16 15-4 4-4-4"
|
||||
className={direction === "desc" ? "opacity-100" : "opacity-25"}
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useEffect, type ReactNode } from "react";
|
||||
import { CloseMaskIcon } from "./icons.js";
|
||||
|
||||
interface RecordDialogProps {
|
||||
open: boolean;
|
||||
title: string;
|
||||
onClose: () => void;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Panneau de saisie par-dessus la liste.
|
||||
*
|
||||
* Le CRM ne défile jamais au niveau de la page : sur grand écran le panneau est
|
||||
* borné à la hauteur du viewport, et seule sa zone de formulaire défile. Sur
|
||||
* téléphone il occupe l'écran entier, toujours sans faire grandir la page.
|
||||
*/
|
||||
export const RecordDialog = ({ open, title, onClose, children }: RecordDialogProps) => {
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") onClose();
|
||||
};
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [open, onClose]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
role="presentation"
|
||||
onMouseDown={(event) => {
|
||||
if (event.target === event.currentTarget) onClose();
|
||||
}}
|
||||
className="fixed inset-0 z-40 flex items-center justify-center bg-black/60 backdrop-blur-sm sm:p-6"
|
||||
>
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={title}
|
||||
className="flex h-full w-full flex-col overflow-hidden border-border bg-surface shadow-lg sm:h-auto sm:max-h-full sm:max-w-2xl sm:rounded-xl sm:border"
|
||||
>
|
||||
<header className="flex shrink-0 items-center justify-between gap-4 border-b border-border px-5 py-4">
|
||||
<h2 className="font-display text-sm font-semibold uppercase tracking-label text-foreground">
|
||||
{title}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="Fermer"
|
||||
title="Fermer"
|
||||
className="flex size-8 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
|
||||
>
|
||||
<CloseMaskIcon />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-5 py-5">{children}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
interface RowActionButtonProps {
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
tone?: "neutral" | "destructive";
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bouton d'action compact d'une ligne de tableau.
|
||||
*
|
||||
* Les icônes au trait héritent de `currentColor` : le survol teinte donc le
|
||||
* pictogramme en accent (modifier) ou en destructif (supprimer).
|
||||
*/
|
||||
export const RowActionButton = ({
|
||||
label,
|
||||
onClick,
|
||||
tone = "neutral",
|
||||
children,
|
||||
}: RowActionButtonProps) => (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
className={
|
||||
tone === "destructive"
|
||||
? "flex size-8 items-center justify-center rounded-sm border border-border-strong bg-surface text-muted-foreground transition-colors hover:border-destructive hover:bg-destructive/10 hover:text-destructive focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
|
||||
: "flex size-8 items-center justify-center rounded-sm border border-border-strong bg-surface text-muted-foreground transition-colors hover:border-accent hover:bg-accent/10 hover:text-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { SVGProps } from "react";
|
||||
import { cn } from "@cohaise/ui";
|
||||
|
||||
/**
|
||||
* Petites icônes au trait, dessinées avec `currentColor`.
|
||||
*
|
||||
* Les pictogrammes d'action (recherche, modifier, supprimer, fermer,
|
||||
* déconnexion) viennent des WebP du dépôt et passent par `MaskIcon` dans
|
||||
* `icons.tsx`. On ne garde ici que les flèches, qui n'ont pas d'équivalent.
|
||||
*/
|
||||
type GlyphProps = SVGProps<SVGSVGElement>;
|
||||
|
||||
const Glyph = ({ className, children, ...props }: GlyphProps) => (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={2}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden="true"
|
||||
className={cn("h-4 w-4 shrink-0", className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const ChevronDownGlyph = (props: GlyphProps) => (
|
||||
<Glyph {...props}>
|
||||
<path d="m6 9 6 6 6-6" />
|
||||
</Glyph>
|
||||
);
|
||||
|
||||
export const ArrowUpGlyph = (props: GlyphProps) => (
|
||||
<Glyph {...props}>
|
||||
<path d="M12 19V5M5 12l7-7 7 7" />
|
||||
</Glyph>
|
||||
);
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ImgHTMLAttributes } from "react";
|
||||
import type { HTMLAttributes, ImgHTMLAttributes } from "react";
|
||||
|
||||
type IconProps = Omit<ImgHTMLAttributes<HTMLImageElement>, "src" | "alt"> & {
|
||||
filled?: boolean;
|
||||
@@ -18,6 +18,39 @@ const ImgIcon = ({
|
||||
/>
|
||||
);
|
||||
|
||||
type MaskIconProps = Omit<HTMLAttributes<HTMLSpanElement>, "children">;
|
||||
|
||||
/**
|
||||
* Icône WebP du dépôt teintée par `currentColor`.
|
||||
*
|
||||
* Les fichiers sont blancs avec un canal alpha : un `<img>` serait invisible
|
||||
* sur fond clair. Le masque CSS garde la forme et laisse le bouton décider de
|
||||
* la couleur (accent au survol, destructif pour la poubelle).
|
||||
*/
|
||||
const MaskIcon = ({
|
||||
src,
|
||||
className = "",
|
||||
style,
|
||||
...props
|
||||
}: MaskIconProps & { src: string }) => (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={`inline-block h-4 w-4 shrink-0 bg-current ${className}`}
|
||||
style={{
|
||||
maskImage: `url(${src})`,
|
||||
WebkitMaskImage: `url(${src})`,
|
||||
maskRepeat: "no-repeat",
|
||||
WebkitMaskRepeat: "no-repeat",
|
||||
maskPosition: "center",
|
||||
WebkitMaskPosition: "center",
|
||||
maskSize: "contain",
|
||||
WebkitMaskSize: "contain",
|
||||
...style,
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export const FolderIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/folder.webp" {...props} />
|
||||
);
|
||||
@@ -90,6 +123,39 @@ export const LogoutIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/sign-out.webp" {...props} />
|
||||
);
|
||||
|
||||
/* Variantes masquées : mêmes WebP, mais teintées par `currentColor`. */
|
||||
export const LogoutMaskIcon = (props: MaskIconProps) => (
|
||||
<MaskIcon src="/icons/sign-out.webp" {...props} />
|
||||
);
|
||||
|
||||
export const SearchMaskIcon = (props: MaskIconProps) => (
|
||||
<MaskIcon src="/icons/search.webp" {...props} />
|
||||
);
|
||||
|
||||
export const FolderMaskIcon = (props: MaskIconProps) => (
|
||||
<MaskIcon src="/icons/folder.webp" {...props} />
|
||||
);
|
||||
|
||||
export const UsersMaskIcon = (props: MaskIconProps) => (
|
||||
<MaskIcon src="/icons/accounts.webp" {...props} />
|
||||
);
|
||||
|
||||
export const ActivityMaskIcon = (props: MaskIconProps) => (
|
||||
<MaskIcon src="/icons/activity.webp" {...props} />
|
||||
);
|
||||
|
||||
export const CloseMaskIcon = (props: MaskIconProps) => (
|
||||
<MaskIcon src="/icons/close.webp" {...props} />
|
||||
);
|
||||
|
||||
export const PenMaskIcon = (props: MaskIconProps) => (
|
||||
<MaskIcon src="/icons/edit-pencil.webp" {...props} />
|
||||
);
|
||||
|
||||
export const TrashMaskIcon = (props: MaskIconProps) => (
|
||||
<MaskIcon src="/icons/trash-can.webp" {...props} />
|
||||
);
|
||||
|
||||
export const ShieldIcon = (props: IconProps) => (
|
||||
<ImgIcon src="/icons/accounts.webp" {...props} />
|
||||
);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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";
|
||||
import { FaultyTerminalBackdrop } from "../components/FaultyTerminalBackdrop.js";
|
||||
|
||||
interface Props {
|
||||
user: User;
|
||||
@@ -40,8 +41,10 @@ export const ChangePassword = ({ user, onCompleted, onLogout }: Props) => {
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="flex min-h-dvh items-center justify-center bg-background px-4 py-10">
|
||||
<div className="w-full max-w-sm">
|
||||
<main className="relative flex min-h-dvh items-center justify-center bg-background px-4 py-10">
|
||||
<FaultyTerminalBackdrop />
|
||||
|
||||
<div className="relative z-10 w-full max-w-sm">
|
||||
<header className="mb-6 text-center">
|
||||
<p className="font-display text-xs font-semibold uppercase tracking-logo text-accent">
|
||||
CoHaiSe
|
||||
|
||||
+214
-189
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useState, type FormEvent } from "react";
|
||||
import { Button, Card, CardContent, CardHeader, CardTitle, Input, Skeleton } from "@cohaise/ui";
|
||||
import { Button, Input } from "@cohaise/ui";
|
||||
import {
|
||||
ApiError,
|
||||
api,
|
||||
@@ -9,6 +9,10 @@ import {
|
||||
type Country,
|
||||
type Organization,
|
||||
} from "../lib/api.js";
|
||||
import { DataTable, type DataTableColumn } from "../components/DataTable.js";
|
||||
import { RecordDialog } from "../components/RecordDialog.js";
|
||||
import { RowActionButton } from "../components/RowActionButton.js";
|
||||
import { PenMaskIcon, TrashMaskIcon } from "../components/icons.js";
|
||||
|
||||
const EMPTY: ContactInput = {
|
||||
firstName: "",
|
||||
@@ -33,6 +37,7 @@ export const Contacts = () => {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [editing, setEditing] = useState<Contact | null>(null);
|
||||
const [form, setForm] = useState<ContactInput>(EMPTY);
|
||||
const [open, setOpen] = useState(false);
|
||||
@@ -68,15 +73,21 @@ export const Contacts = () => {
|
||||
.catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
const close = () => {
|
||||
setEditing(null);
|
||||
setForm(EMPTY);
|
||||
setFormError(null);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
setForm(EMPTY);
|
||||
setError(null);
|
||||
setFormError(null);
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
const openEdit = (contact: Contact) => {
|
||||
setOpen(true);
|
||||
setEditing(contact);
|
||||
setForm({
|
||||
firstName: contact.first_name,
|
||||
@@ -89,14 +100,8 @@ export const Contacts = () => {
|
||||
countryId: contact.country_id,
|
||||
description: contact.description,
|
||||
});
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const close = () => {
|
||||
setEditing(null);
|
||||
setForm(EMPTY);
|
||||
setError(null);
|
||||
setOpen(false);
|
||||
setFormError(null);
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
const submit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
@@ -104,7 +109,7 @@ export const Contacts = () => {
|
||||
const firstName = text(form.firstName ?? "");
|
||||
const lastName = text(form.lastName ?? "");
|
||||
if (!firstName || !lastName) {
|
||||
setError("Le prénom et le nom sont obligatoires.");
|
||||
setFormError("Le prénom et le nom sont obligatoires.");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -121,14 +126,14 @@ export const Contacts = () => {
|
||||
};
|
||||
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setFormError(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.");
|
||||
setFormError(caught instanceof ApiError ? caught.message : "Enregistrement impossible.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -156,184 +161,204 @@ export const Contacts = () => {
|
||||
}));
|
||||
};
|
||||
|
||||
const columns: DataTableColumn<Contact>[] = [
|
||||
{
|
||||
id: "name",
|
||||
header: "Nom",
|
||||
sortable: true,
|
||||
sortValue: (row) => `${row.last_name} ${row.first_name}`,
|
||||
cell: (row) => (
|
||||
<span className="font-medium text-foreground">
|
||||
{row.last_name} {row.first_name}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "job",
|
||||
header: "Fonction",
|
||||
sortable: true,
|
||||
sortValue: (row) => row.job_title,
|
||||
className: "text-muted-foreground",
|
||||
cell: (row) => row.job_title ?? "—",
|
||||
},
|
||||
{
|
||||
id: "organization",
|
||||
header: "Entreprise",
|
||||
sortable: true,
|
||||
sortValue: (row) => row.organization_name,
|
||||
className: "text-muted-foreground",
|
||||
cell: (row) => row.organization_name ?? "—",
|
||||
},
|
||||
{
|
||||
id: "contact",
|
||||
header: "Contact",
|
||||
className: "text-muted-foreground",
|
||||
cell: (row) => (
|
||||
<div className="flex flex-col">
|
||||
<span>{row.email ?? row.phone ?? row.mobile ?? "—"}</span>
|
||||
{row.email && (row.phone ?? row.mobile) ? (
|
||||
<span className="text-xs text-subtle-foreground">{row.phone ?? row.mobile}</span>
|
||||
) : null}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "country",
|
||||
header: "Pays",
|
||||
sortable: true,
|
||||
sortValue: (row) => row.country_name ?? row.country_code,
|
||||
className: "text-muted-foreground",
|
||||
cell: (row) => row.country_code ?? "—",
|
||||
},
|
||||
{
|
||||
id: "created",
|
||||
header: "Ajouté le",
|
||||
sortable: true,
|
||||
sortValue: (row) => row.created_at,
|
||||
cell: (row) => (
|
||||
<span className="tabular-nums text-subtle-foreground">{formatDate(row.created_at)}</span>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-6">
|
||||
<div className="flex flex-wrap items-end justify-between gap-4">
|
||||
<div className="w-full max-w-xs">
|
||||
<>
|
||||
<DataTable
|
||||
data={rows}
|
||||
columns={columns}
|
||||
keyExtractor={(contact) => contact.id}
|
||||
loading={loading}
|
||||
error={error}
|
||||
emptyMessage="Aucun prospect"
|
||||
emptyHint="Ajoutez le premier pour commencer."
|
||||
search={{
|
||||
value: search,
|
||||
onChange: setSearch,
|
||||
placeholder: "Prénom, nom, e-mail, entreprise…",
|
||||
}}
|
||||
actions={<Button onClick={openCreate}>Nouveau prospect</Button>}
|
||||
rowActions={(contact) => (
|
||||
<div className="flex items-center justify-end gap-1.5">
|
||||
<RowActionButton
|
||||
label={`Modifier ${contact.first_name} ${contact.last_name}`}
|
||||
onClick={() => openEdit(contact)}
|
||||
>
|
||||
<PenMaskIcon />
|
||||
</RowActionButton>
|
||||
<RowActionButton
|
||||
label={`Supprimer ${contact.first_name} ${contact.last_name}`}
|
||||
tone="destructive"
|
||||
onClick={() => void remove(contact)}
|
||||
>
|
||||
<TrashMaskIcon />
|
||||
</RowActionButton>
|
||||
</div>
|
||||
)}
|
||||
footer={
|
||||
<span>
|
||||
{rows.length === total
|
||||
? `${total} prospect${total > 1 ? "s" : ""}`
|
||||
: `${rows.length} sur ${total} prospects`}
|
||||
</span>
|
||||
}
|
||||
initialSort={{ column: "created", direction: "desc" }}
|
||||
/>
|
||||
|
||||
<RecordDialog
|
||||
open={open}
|
||||
title={editing ? "Modifier le prospect" : "Nouveau prospect"}
|
||||
onClose={close}
|
||||
>
|
||||
<form className="grid gap-4 sm:grid-cols-2" onSubmit={(event) => void submit(event)}>
|
||||
<Input
|
||||
label="Rechercher"
|
||||
type="search"
|
||||
placeholder="Prénom, nom, e-mail, entreprise…"
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
label="Prénom *"
|
||||
required
|
||||
value={form.firstName ?? ""}
|
||||
onChange={(event) => set("firstName")(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Button onClick={openCreate}>Nouveau prospect</Button>
|
||||
</div>
|
||||
|
||||
{open ? (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{editing ? "Modifier le prospect" : "Nouveau prospect"}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form className="grid gap-4 sm:grid-cols-2" onSubmit={(event) => void submit(event)}>
|
||||
<Input
|
||||
label="Prénom *"
|
||||
required
|
||||
value={form.firstName ?? ""}
|
||||
onChange={(event) => set("firstName")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Nom *"
|
||||
required
|
||||
value={form.lastName ?? ""}
|
||||
onChange={(event) => set("lastName")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Fonction"
|
||||
value={form.jobTitle ?? ""}
|
||||
onChange={(event) => set("jobTitle")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="E-mail"
|
||||
type="email"
|
||||
value={form.email ?? ""}
|
||||
onChange={(event) => set("email")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Téléphone"
|
||||
value={form.phone ?? ""}
|
||||
onChange={(event) => set("phone")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Mobile"
|
||||
value={form.mobile ?? ""}
|
||||
onChange={(event) => set("mobile")(event.target.value)}
|
||||
/>
|
||||
<label className="flex flex-col gap-2 text-sm font-medium text-foreground">
|
||||
Entreprise
|
||||
<select
|
||||
className="h-10 rounded-md border border-border-control bg-background px-3 text-sm"
|
||||
value={form.organizationId ?? ""}
|
||||
onChange={(event) => set("organizationId")(event.target.value || null)}
|
||||
>
|
||||
<option value="">— Aucune —</option>
|
||||
{organizations.map((organization) => (
|
||||
<option key={organization.id} value={organization.id}>
|
||||
{organization.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="flex flex-col gap-2 text-sm font-medium text-foreground">
|
||||
Pays
|
||||
<select
|
||||
className="h-10 rounded-md border border-border-control bg-background px-3 text-sm"
|
||||
value={form.countryId ?? ""}
|
||||
onChange={(event) =>
|
||||
set("countryId")(event.target.value ? Number(event.target.value) : null)
|
||||
}
|
||||
>
|
||||
<option value="">— Aucun —</option>
|
||||
{countries.map((country) => (
|
||||
<option key={country.id} value={country.id}>
|
||||
{country.name} ({country.code})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<div className="sm:col-span-2">
|
||||
<Input
|
||||
label="Notes"
|
||||
value={form.description ?? ""}
|
||||
onChange={(event) => set("description")(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<p className="text-sm text-destructive sm:col-span-2" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="flex gap-3 sm:col-span-2">
|
||||
<Button type="submit" isLoading={busy}>
|
||||
{editing ? "Enregistrer" : "Créer"}
|
||||
</Button>
|
||||
<Button type="button" variant="secondary" onClick={close}>
|
||||
Annuler
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
{loading ? (
|
||||
<div className="flex flex-col gap-3">
|
||||
<Skeleton className="h-10" />
|
||||
<Skeleton className="h-10" />
|
||||
<Skeleton className="h-10" />
|
||||
</div>
|
||||
) : error && rows.length === 0 ? (
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
) : rows.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Aucun prospect. Ajoutez le premier pour commencer.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="min-h-0 flex-1 overflow-y-auto overflow-x-auto">
|
||||
<table className="w-full border-collapse text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border-control text-left text-xs uppercase tracking-label text-subtle-foreground">
|
||||
<th className="py-2 pr-4">Nom</th>
|
||||
<th className="py-2 pr-4">Fonction</th>
|
||||
<th className="py-2 pr-4">Entreprise</th>
|
||||
<th className="py-2 pr-4">Contact</th>
|
||||
<th className="py-2 pr-4">Pays</th>
|
||||
<th className="py-2 pr-4">Ajouté le</th>
|
||||
<th className="py-2 pr-4 text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((contact) => (
|
||||
<tr key={contact.id} className="border-b border-border-control/60">
|
||||
<td className="py-3 pr-4 font-medium">
|
||||
{contact.last_name} {contact.first_name}
|
||||
</td>
|
||||
<td className="py-3 pr-4">{contact.job_title ?? "—"}</td>
|
||||
<td className="py-3 pr-4">{contact.organization_name ?? "—"}</td>
|
||||
<td className="py-3 pr-4">{contact.email ?? contact.phone ?? "—"}</td>
|
||||
<td className="py-3 pr-4">{contact.country_code ?? "—"}</td>
|
||||
<td className="py-3 pr-4 text-subtle-foreground">
|
||||
{formatDate(contact.created_at)}
|
||||
</td>
|
||||
<td className="py-3 pr-4">
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button size="sm" variant="secondary" onClick={() => openEdit(contact)}>
|
||||
Modifier
|
||||
</Button>
|
||||
{
|
||||
<Button size="sm" variant="destructive" onClick={() => void remove(contact)}>
|
||||
Supprimer
|
||||
</Button>
|
||||
}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<Input
|
||||
label="Nom *"
|
||||
required
|
||||
value={form.lastName ?? ""}
|
||||
onChange={(event) => set("lastName")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Fonction"
|
||||
value={form.jobTitle ?? ""}
|
||||
onChange={(event) => set("jobTitle")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="E-mail"
|
||||
type="email"
|
||||
value={form.email ?? ""}
|
||||
onChange={(event) => set("email")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Téléphone"
|
||||
value={form.phone ?? ""}
|
||||
onChange={(event) => set("phone")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Mobile"
|
||||
value={form.mobile ?? ""}
|
||||
onChange={(event) => set("mobile")(event.target.value)}
|
||||
/>
|
||||
<label className="flex flex-col gap-2 text-sm font-medium text-foreground">
|
||||
Entreprise
|
||||
<select
|
||||
className="h-10 w-full rounded-sm border border-border-control bg-surface px-3 text-sm text-foreground transition-[background-color,border-color,box-shadow] duration-fast ease-out-soft hover:border-accent/60 hover:bg-surface-raised focus-visible:border-border-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
|
||||
value={form.organizationId ?? ""}
|
||||
onChange={(event) => set("organizationId")(event.target.value || null)}
|
||||
>
|
||||
<option value="">— Aucune —</option>
|
||||
{organizations.map((organization) => (
|
||||
<option key={organization.id} value={organization.id}>
|
||||
{organization.name}
|
||||
</option>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<p className="mt-3 text-xs text-subtle-foreground">
|
||||
{total} prospect{total > 1 ? "s" : ""}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</select>
|
||||
</label>
|
||||
<label className="flex flex-col gap-2 text-sm font-medium text-foreground">
|
||||
Pays
|
||||
<select
|
||||
className="h-10 w-full rounded-sm border border-border-control bg-surface px-3 text-sm text-foreground transition-[background-color,border-color,box-shadow] duration-fast ease-out-soft hover:border-accent/60 hover:bg-surface-raised focus-visible:border-border-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
|
||||
value={form.countryId ?? ""}
|
||||
onChange={(event) =>
|
||||
set("countryId")(event.target.value ? Number(event.target.value) : null)
|
||||
}
|
||||
>
|
||||
<option value="">— Aucun —</option>
|
||||
{countries.map((country) => (
|
||||
<option key={country.id} value={country.id}>
|
||||
{country.name} ({country.code})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<div className="sm:col-span-2">
|
||||
<Input
|
||||
label="Notes"
|
||||
value={form.description ?? ""}
|
||||
onChange={(event) => set("description")(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{formError ? (
|
||||
<p className="text-sm text-destructive sm:col-span-2" role="alert">
|
||||
{formError}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="flex items-center justify-end gap-3 sm:col-span-2">
|
||||
<Button type="button" variant="secondary" onClick={close}>
|
||||
Annuler
|
||||
</Button>
|
||||
<Button type="submit" isLoading={busy}>
|
||||
{editing ? "Enregistrer" : "Créer"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</RecordDialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { useCallback, useEffect, useState, type FormEvent } from "react";
|
||||
import { Button, Card, CardContent, CardHeader, CardTitle, Input, Skeleton } from "@cohaise/ui";
|
||||
import { useCallback, useEffect, useMemo, useState, type FormEvent } from "react";
|
||||
import { Button, Input } from "@cohaise/ui";
|
||||
import { ApiError, api, type Country } from "../lib/api.js";
|
||||
import { DataTable, type DataTableColumn } from "../components/DataTable.js";
|
||||
import { RecordDialog } from "../components/RecordDialog.js";
|
||||
import { RowActionButton } from "../components/RowActionButton.js";
|
||||
import { PenMaskIcon, TrashMaskIcon } from "../components/icons.js";
|
||||
|
||||
interface Form {
|
||||
code: string;
|
||||
@@ -12,9 +16,11 @@ const EMPTY: Form = { code: "", name: "", phoneCode: "" };
|
||||
|
||||
export const Countries = () => {
|
||||
const [rows, setRows] = useState<Country[]>([]);
|
||||
const [search, setSearch] = useState("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<Country | null>(null);
|
||||
const [form, setForm] = useState<Form>(EMPTY);
|
||||
@@ -36,31 +42,66 @@ export const Countries = () => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
// Le referentiel est court : le filtrage reste local, sans requete par frappe.
|
||||
const filtered = useMemo(() => {
|
||||
const query = search.trim().toLowerCase();
|
||||
if (!query) return rows;
|
||||
return rows.filter((country) =>
|
||||
[country.code, country.name, country.phone_code ?? ""]
|
||||
.join(" ")
|
||||
.toLowerCase()
|
||||
.includes(query),
|
||||
);
|
||||
}, [rows, search]);
|
||||
|
||||
const close = () => {
|
||||
setEditing(null);
|
||||
setForm(EMPTY);
|
||||
setFormError(null);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
setForm(EMPTY);
|
||||
setFormError(null);
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
const openEdit = (country: Country) => {
|
||||
setEditing(country);
|
||||
setForm({
|
||||
code: country.code,
|
||||
name: country.name,
|
||||
phoneCode: country.phone_code ?? "",
|
||||
});
|
||||
setFormError(null);
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
const submit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
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.");
|
||||
setFormError("Le code doit contenir exactement deux lettres.");
|
||||
return;
|
||||
}
|
||||
if (!name) {
|
||||
setError("Le nom est obligatoire.");
|
||||
setFormError("Le nom est obligatoire.");
|
||||
return;
|
||||
}
|
||||
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setFormError(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);
|
||||
close();
|
||||
await load();
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Enregistrement impossible.");
|
||||
setFormError(caught instanceof ApiError ? caught.message : "Enregistrement impossible.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -80,147 +121,135 @@ export const Countries = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const columns: DataTableColumn<Country>[] = [
|
||||
{
|
||||
id: "code",
|
||||
header: "Code",
|
||||
sortable: true,
|
||||
sortValue: (row) => row.code,
|
||||
cell: (row) => (
|
||||
<span className="inline-flex rounded-sm border border-border bg-surface-muted px-1.5 py-0.5 font-mono text-xs font-semibold tracking-wide text-foreground">
|
||||
{row.code}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "name",
|
||||
header: "Nom",
|
||||
sortable: true,
|
||||
sortValue: (row) => row.name,
|
||||
cell: (row) => <span className="font-medium text-foreground">{row.name}</span>,
|
||||
},
|
||||
{
|
||||
id: "phone",
|
||||
header: "Indicatif",
|
||||
sortable: true,
|
||||
sortValue: (row) => row.phone_code,
|
||||
cell: (row) => (
|
||||
<span className="font-mono text-sm text-muted-foreground">{row.phone_code ?? "—"}</span>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-6">
|
||||
<div className="flex flex-wrap items-end justify-between gap-4">
|
||||
<p className="max-w-lg text-sm text-muted-foreground">
|
||||
Référentiel ISO 3166 utilisé par les entreprises et les prospects. Il ne contient
|
||||
que les pays déjà saisis dans la base.
|
||||
</p>
|
||||
{
|
||||
<Button
|
||||
onClick={() => {
|
||||
setEditing(null);
|
||||
setForm(EMPTY);
|
||||
setError(null);
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
Nouveau pays
|
||||
</Button>
|
||||
<>
|
||||
<DataTable
|
||||
data={filtered}
|
||||
columns={columns}
|
||||
keyExtractor={(country) => country.id}
|
||||
loading={loading}
|
||||
error={error}
|
||||
emptyMessage={search ? "Aucun pays correspondant" : "Aucun pays"}
|
||||
emptyHint={
|
||||
search
|
||||
? "Essayez un autre code, un autre nom ou un indicatif."
|
||||
: "Ajoutez le premier pays du référentiel."
|
||||
}
|
||||
</div>
|
||||
|
||||
{open && (
|
||||
<Card className="shrink-0">
|
||||
<CardHeader>
|
||||
<CardTitle>{editing ? "Modifier le pays" : "Nouveau pays"}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form
|
||||
className="grid gap-4 sm:grid-cols-3"
|
||||
onSubmit={(event) => void submit(event)}
|
||||
search={{
|
||||
value: search,
|
||||
onChange: setSearch,
|
||||
placeholder: "Code, nom, indicatif…",
|
||||
}}
|
||||
toolbarStart={
|
||||
<p className="hidden max-w-lg text-sm text-muted-foreground lg:block">
|
||||
Référentiel ISO 3166 utilisé par les entreprises et les prospects.
|
||||
</p>
|
||||
}
|
||||
actions={<Button onClick={openCreate}>Nouveau pays</Button>}
|
||||
rowActions={(country) => (
|
||||
<div className="flex items-center justify-end gap-1.5">
|
||||
<RowActionButton
|
||||
label={`Modifier ${country.name}`}
|
||||
onClick={() => openEdit(country)}
|
||||
>
|
||||
<Input
|
||||
label="Code *"
|
||||
required
|
||||
maxLength={2}
|
||||
placeholder="FR"
|
||||
value={form.code}
|
||||
onChange={(event) =>
|
||||
setForm((current) => ({ ...current, code: event.target.value.toUpperCase() }))
|
||||
}
|
||||
/>
|
||||
<Input
|
||||
label="Nom *"
|
||||
required
|
||||
value={form.name}
|
||||
onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))}
|
||||
/>
|
||||
<Input
|
||||
label="Indicatif"
|
||||
placeholder="+33"
|
||||
value={form.phoneCode}
|
||||
onChange={(event) =>
|
||||
setForm((current) => ({ ...current, phoneCode: event.target.value }))
|
||||
}
|
||||
/>
|
||||
<PenMaskIcon />
|
||||
</RowActionButton>
|
||||
<RowActionButton
|
||||
label={`Supprimer ${country.name}`}
|
||||
tone="destructive"
|
||||
onClick={() => void remove(country)}
|
||||
>
|
||||
<TrashMaskIcon />
|
||||
</RowActionButton>
|
||||
</div>
|
||||
)}
|
||||
footer={
|
||||
<span>
|
||||
{filtered.length === rows.length
|
||||
? `${rows.length} pays`
|
||||
: `${filtered.length} sur ${rows.length} pays`}
|
||||
</span>
|
||||
}
|
||||
initialSort={{ column: "name", direction: "asc" }}
|
||||
/>
|
||||
|
||||
{error ? (
|
||||
<p className="text-sm text-destructive sm:col-span-3" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
<RecordDialog
|
||||
open={open}
|
||||
title={editing ? "Modifier le pays" : "Nouveau pays"}
|
||||
onClose={close}
|
||||
>
|
||||
<form className="grid gap-4 sm:grid-cols-3" onSubmit={(event) => void submit(event)}>
|
||||
<Input
|
||||
label="Code *"
|
||||
required
|
||||
maxLength={2}
|
||||
placeholder="FR"
|
||||
value={form.code}
|
||||
onChange={(event) =>
|
||||
setForm((current) => ({ ...current, code: event.target.value.toUpperCase() }))
|
||||
}
|
||||
/>
|
||||
<Input
|
||||
label="Nom *"
|
||||
required
|
||||
value={form.name}
|
||||
onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))}
|
||||
/>
|
||||
<Input
|
||||
label="Indicatif"
|
||||
placeholder="+33"
|
||||
value={form.phoneCode}
|
||||
onChange={(event) =>
|
||||
setForm((current) => ({ ...current, phoneCode: event.target.value }))
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="flex gap-3 sm:col-span-3">
|
||||
<Button type="submit" isLoading={busy}>
|
||||
{editing ? "Enregistrer" : "Créer"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
setEditing(null);
|
||||
setForm(EMPTY);
|
||||
setError(null);
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
Annuler
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
{formError ? (
|
||||
<p className="text-sm text-destructive sm:col-span-3" role="alert">
|
||||
{formError}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{error && rows.length === 0 ? (
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
) : loading ? (
|
||||
<div className="flex flex-col gap-3">
|
||||
<Skeleton className="h-10" />
|
||||
<Skeleton className="h-10" />
|
||||
<Skeleton className="h-10" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="min-h-0 flex-1 overflow-y-auto overflow-x-auto">
|
||||
<table className="w-full border-collapse text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border-control text-left text-xs uppercase tracking-label text-subtle-foreground">
|
||||
<th className="py-2 pr-4">Code</th>
|
||||
<th className="py-2 pr-4">Nom</th>
|
||||
<th className="py-2 pr-4">Indicatif</th>
|
||||
<th className="py-2 pr-4 text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((country) => (
|
||||
<tr key={country.id} className="border-b border-border-control/60">
|
||||
<td className="py-3 pr-4 font-medium">{country.code}</td>
|
||||
<td className="py-3 pr-4">{country.name}</td>
|
||||
<td className="py-3 pr-4">{country.phone_code ?? "—"}</td>
|
||||
{
|
||||
<td className="py-3 pr-4">
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
setEditing(country);
|
||||
setForm({
|
||||
code: country.code,
|
||||
name: country.name,
|
||||
phoneCode: country.phone_code ?? "",
|
||||
});
|
||||
setError(null);
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
Modifier
|
||||
</Button>
|
||||
<Button size="sm" variant="destructive" onClick={() => void remove(country)}>
|
||||
Supprimer
|
||||
</Button>
|
||||
</div>
|
||||
</td>
|
||||
}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<p className="mt-3 text-xs text-subtle-foreground">{rows.length} pays</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-3 sm:col-span-3">
|
||||
<Button type="button" variant="secondary" onClick={close}>
|
||||
Annuler
|
||||
</Button>
|
||||
<Button type="submit" isLoading={busy}>
|
||||
{editing ? "Enregistrer" : "Créer"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</RecordDialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,18 +1,23 @@
|
||||
import { useState } from "react";
|
||||
import { Button, cn } from "@cohaise/ui";
|
||||
import { 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";
|
||||
import {
|
||||
ActivityMaskIcon,
|
||||
FolderMaskIcon,
|
||||
LogoutMaskIcon,
|
||||
UsersMaskIcon,
|
||||
} 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 },
|
||||
const TABS: { id: Tab; label: string; icon: typeof FolderMaskIcon }[] = [
|
||||
{ id: "organizations", label: "Entreprises", icon: FolderMaskIcon },
|
||||
{ id: "contacts", label: "Prospects", icon: UsersMaskIcon },
|
||||
{ id: "countries", label: "Pays", icon: ActivityMaskIcon },
|
||||
];
|
||||
|
||||
export const Crm = ({ user, onLogout }: { user: User; onLogout: () => void }) => {
|
||||
@@ -23,7 +28,7 @@ export const Crm = ({ user, onLogout }: { user: User; onLogout: () => void }) =>
|
||||
<FaultyTerminalBackdrop />
|
||||
|
||||
<div className="relative z-10 flex h-full min-h-0 flex-col gap-3 p-3 sm:p-4">
|
||||
<header className="glass flex shrink-0 items-center justify-between gap-4 rounded-xl border border-border/50 px-4 py-3 shadow-sm">
|
||||
<header className="glass flex shrink-0 items-center justify-between gap-4 rounded-xl border border-border/50 px-4 py-2.5 shadow-sm">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="font-logo text-sm font-bold tracking-logo text-accent">COHAISE</span>
|
||||
<span className="text-border" aria-hidden="true">
|
||||
@@ -32,52 +37,72 @@ export const Crm = ({ user, onLogout }: { user: User; onLogout: () => void }) =>
|
||||
<span className="font-display text-sm font-semibold uppercase tracking-label">CRM</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<div className="hidden text-right sm:block">
|
||||
<p className="text-sm font-medium">
|
||||
<p className="font-display text-[0.8125rem] font-semibold uppercase tracking-label text-foreground">
|
||||
{user.first_name} {user.last_name}
|
||||
</p>
|
||||
<p className="text-[0.6875rem] text-muted-foreground">{user.email}</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
<span className="flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-surface/50 p-1">
|
||||
<img
|
||||
src="/images/cohaise.webp"
|
||||
alt=""
|
||||
width={28}
|
||||
height={28}
|
||||
aria-hidden="true"
|
||||
className="h-full w-full object-contain"
|
||||
/>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onLogout}
|
||||
iconLeading={<LogoutIcon />}
|
||||
aria-label="Se déconnecter"
|
||||
title="Se déconnecter"
|
||||
className="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full border border-border/60 bg-surface/40 text-muted-foreground transition-[color,background-color,border-color,box-shadow] duration-fast ease-out-soft hover:border-destructive/50 hover:bg-destructive/10 hover:text-destructive focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background focus-visible:outline-none"
|
||||
>
|
||||
Se déconnecter
|
||||
</Button>
|
||||
<LogoutMaskIcon />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<nav className="glass flex shrink-0 items-center gap-1 rounded-xl border border-border/50 p-1.5">
|
||||
{TABS.map((item) => {
|
||||
const Icon = item.icon;
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
onClick={() => setTab(item.id)}
|
||||
aria-current={tab === item.id ? "page" : undefined}
|
||||
className={cn(
|
||||
"flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium transition-colors",
|
||||
tab === item.id
|
||||
? "bg-accent/10 text-accent"
|
||||
: "text-muted-foreground hover:bg-surface-hover hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<Icon />
|
||||
{item.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
{/* Une seule grande surface : onglets à gauche, vue des données à droite. */}
|
||||
<main className="flex min-h-0 flex-1 overflow-hidden rounded-xl border border-border/50 bg-surface/40">
|
||||
<nav
|
||||
aria-label="Sections du CRM"
|
||||
className="flex w-14 shrink-0 flex-col gap-1 border-r border-border/50 p-1.5 sm:p-2 md:w-[15%]"
|
||||
>
|
||||
{TABS.map((item) => {
|
||||
const Icon = item.icon;
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
onClick={() => setTab(item.id)}
|
||||
aria-current={tab === item.id ? "page" : undefined}
|
||||
aria-label={item.label}
|
||||
title={item.label}
|
||||
className={cn(
|
||||
"flex items-center justify-center gap-2.5 rounded-lg px-2 py-2.5 text-sm font-medium transition-colors md:justify-start lg:px-3",
|
||||
tab === item.id
|
||||
? "bg-accent/10 text-accent"
|
||||
: "text-muted-foreground hover:bg-surface-hover hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<Icon className="h-4 w-4 shrink-0" />
|
||||
<span className="hidden truncate lg:inline">{item.label}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
<main className="glass flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border border-border/50">
|
||||
<div className="mx-auto flex min-h-0 w-full max-w-6xl flex-1 flex-col px-4 py-6">
|
||||
{tab === "organizations" ? <Organizations /> : null}
|
||||
{tab === "contacts" ? <Contacts /> : null}
|
||||
{tab === "countries" ? <Countries /> : null}
|
||||
</div>
|
||||
<section className="flex min-h-0 min-w-0 flex-1 flex-col px-3 py-3 sm:px-4 sm:py-4">
|
||||
<div className="flex min-h-0 w-full flex-1 flex-col">
|
||||
{tab === "organizations" ? <Organizations /> : null}
|
||||
{tab === "contacts" ? <Contacts /> : null}
|
||||
{tab === "countries" ? <Countries /> : null}
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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";
|
||||
import { FaultyTerminalBackdrop } from "../components/FaultyTerminalBackdrop.js";
|
||||
|
||||
export const Login = ({ onAuthenticated }: { onAuthenticated: (user: User) => void }) => {
|
||||
const [email, setEmail] = useState("");
|
||||
@@ -23,8 +24,10 @@ export const Login = ({ onAuthenticated }: { onAuthenticated: (user: User) => vo
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="flex min-h-dvh items-center justify-center bg-background px-4 py-10">
|
||||
<div className="w-full max-w-sm">
|
||||
<main className="relative flex min-h-dvh items-center justify-center bg-background px-4 py-10">
|
||||
<FaultyTerminalBackdrop />
|
||||
|
||||
<div className="relative z-10 w-full max-w-sm">
|
||||
<header className="mb-6 text-center">
|
||||
<p className="font-display text-xs font-semibold uppercase tracking-logo text-accent">
|
||||
CoHaiSe
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useState, type FormEvent } from "react";
|
||||
import { Button, Card, CardContent, CardHeader, CardTitle, Input, Skeleton, Spinner } from "@cohaise/ui";
|
||||
import { Button, Input } from "@cohaise/ui";
|
||||
import {
|
||||
ApiError,
|
||||
api,
|
||||
@@ -8,6 +8,10 @@ import {
|
||||
type Organization,
|
||||
type OrganizationInput,
|
||||
} from "../lib/api.js";
|
||||
import { DataTable, type DataTableColumn } from "../components/DataTable.js";
|
||||
import { RecordDialog } from "../components/RecordDialog.js";
|
||||
import { RowActionButton } from "../components/RowActionButton.js";
|
||||
import { PenMaskIcon, TrashMaskIcon } from "../components/icons.js";
|
||||
|
||||
const EMPTY: OrganizationInput = {
|
||||
name: "",
|
||||
@@ -33,10 +37,11 @@ export const Organizations = () => {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [editing, setEditing] = useState<Organization | null>(null);
|
||||
const [form, setForm] = useState<OrganizationInput>(EMPTY);
|
||||
// Un etat explicite : comparer form a EMPTY ne fonctionnerait pas, car
|
||||
// saisir puis effacer recrée un objet different de la constante.
|
||||
// saisir puis effacer recree un objet different de la constante.
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
@@ -64,15 +69,21 @@ export const Organizations = () => {
|
||||
.catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
const close = () => {
|
||||
setEditing(null);
|
||||
setForm(EMPTY);
|
||||
setFormError(null);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
setForm(EMPTY);
|
||||
setError(null);
|
||||
setFormError(null);
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
const openEdit = (organization: Organization) => {
|
||||
setOpen(true);
|
||||
setEditing(organization);
|
||||
setForm({
|
||||
name: organization.name,
|
||||
@@ -87,14 +98,15 @@ export const Organizations = () => {
|
||||
countryId: organization.country_id,
|
||||
description: organization.description,
|
||||
});
|
||||
setError(null);
|
||||
setFormError(null);
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
const submit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
const name = text(form.name ?? "");
|
||||
if (!name) {
|
||||
setError("Le nom de l'entreprise est obligatoire.");
|
||||
setFormError("Le nom de l'entreprise est obligatoire.");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -113,16 +125,14 @@ export const Organizations = () => {
|
||||
};
|
||||
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setFormError(null);
|
||||
try {
|
||||
if (editing) await api.updateOrganization(editing.id, payload);
|
||||
else await api.createOrganization(payload);
|
||||
setEditing(null);
|
||||
setForm(EMPTY);
|
||||
setOpen(false);
|
||||
close();
|
||||
await load();
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : "Enregistrement impossible.");
|
||||
setFormError(caught instanceof ApiError ? caught.message : "Enregistrement impossible.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -151,194 +161,207 @@ export const Organizations = () => {
|
||||
}));
|
||||
};
|
||||
|
||||
const columns: DataTableColumn<Organization>[] = [
|
||||
{
|
||||
id: "name",
|
||||
header: "Nom",
|
||||
sortable: true,
|
||||
sortValue: (row) => row.name,
|
||||
cell: (row) => (
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<span className="truncate font-medium text-foreground">{row.name}</span>
|
||||
{row.website ? (
|
||||
<a
|
||||
href={/^https?:\/\//i.test(row.website) ? row.website : `https://${row.website}`}
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
className="block max-w-[16rem] truncate text-xs text-subtle-foreground transition-colors hover:text-accent"
|
||||
>
|
||||
{row.website.replace(/^https?:\/\//i, "")}
|
||||
</a>
|
||||
) : null}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "city",
|
||||
header: "Ville",
|
||||
sortable: true,
|
||||
sortValue: (row) => row.city,
|
||||
className: "text-muted-foreground",
|
||||
cell: (row) => row.city ?? "—",
|
||||
},
|
||||
{
|
||||
id: "country",
|
||||
header: "Pays",
|
||||
sortable: true,
|
||||
sortValue: (row) => row.country_name ?? row.country_code,
|
||||
className: "text-muted-foreground",
|
||||
cell: (row) => row.country_code ?? "—",
|
||||
},
|
||||
{
|
||||
id: "industry",
|
||||
header: "Secteur",
|
||||
sortable: true,
|
||||
sortValue: (row) => row.industry,
|
||||
className: "text-muted-foreground",
|
||||
cell: (row) => row.industry ?? "—",
|
||||
},
|
||||
{
|
||||
id: "contact",
|
||||
header: "Contact",
|
||||
className: "text-muted-foreground",
|
||||
cell: (row) => row.email ?? row.phone ?? "—",
|
||||
},
|
||||
{
|
||||
id: "created",
|
||||
header: "Créée le",
|
||||
sortable: true,
|
||||
sortValue: (row) => row.created_at,
|
||||
cell: (row) => (
|
||||
<span className="tabular-nums text-subtle-foreground">{formatDate(row.created_at)}</span>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-6">
|
||||
<div className="flex flex-wrap items-end justify-between gap-4">
|
||||
<div className="w-full max-w-xs">
|
||||
<>
|
||||
<DataTable
|
||||
data={rows}
|
||||
columns={columns}
|
||||
keyExtractor={(organization) => organization.id}
|
||||
loading={loading}
|
||||
error={error}
|
||||
emptyMessage="Aucune entreprise"
|
||||
emptyHint="Créez la première pour commencer."
|
||||
search={{
|
||||
value: search,
|
||||
onChange: setSearch,
|
||||
placeholder: "Nom, ville, secteur…",
|
||||
}}
|
||||
actions={<Button onClick={openCreate}>Nouvelle entreprise</Button>}
|
||||
rowActions={(organization) => (
|
||||
<div className="flex items-center justify-end gap-1.5">
|
||||
<RowActionButton
|
||||
label={`Modifier ${organization.name}`}
|
||||
onClick={() => openEdit(organization)}
|
||||
>
|
||||
<PenMaskIcon />
|
||||
</RowActionButton>
|
||||
<RowActionButton
|
||||
label={`Supprimer ${organization.name}`}
|
||||
tone="destructive"
|
||||
onClick={() => void remove(organization)}
|
||||
>
|
||||
<TrashMaskIcon />
|
||||
</RowActionButton>
|
||||
</div>
|
||||
)}
|
||||
footer={
|
||||
<span>
|
||||
{rows.length === total
|
||||
? `${total} entreprise${total > 1 ? "s" : ""}`
|
||||
: `${rows.length} sur ${total} entreprises`}
|
||||
</span>
|
||||
}
|
||||
initialSort={{ column: "created", direction: "desc" }}
|
||||
/>
|
||||
|
||||
<RecordDialog
|
||||
open={open}
|
||||
title={editing ? "Modifier l'entreprise" : "Nouvelle entreprise"}
|
||||
onClose={close}
|
||||
>
|
||||
<form className="grid gap-4 sm:grid-cols-2" onSubmit={(event) => void submit(event)}>
|
||||
<Input
|
||||
label="Rechercher"
|
||||
type="search"
|
||||
placeholder="Nom, ville, secteur…"
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
label="Nom *"
|
||||
required
|
||||
value={form.name ?? ""}
|
||||
onChange={(event) => set("name")(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Button onClick={openCreate}>Nouvelle entreprise</Button>
|
||||
</div>
|
||||
|
||||
{open ? (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{editing ? "Modifier l'entreprise" : "Nouvelle entreprise"}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form className="grid gap-4 sm:grid-cols-2" onSubmit={(event) => void submit(event)}>
|
||||
<Input
|
||||
label="Nom *"
|
||||
required
|
||||
value={form.name ?? ""}
|
||||
onChange={(event) => set("name")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Secteur"
|
||||
value={form.industry ?? ""}
|
||||
onChange={(event) => set("industry")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Site web"
|
||||
type="url"
|
||||
value={form.website ?? ""}
|
||||
onChange={(event) => set("website")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="E-mail"
|
||||
type="email"
|
||||
value={form.email ?? ""}
|
||||
onChange={(event) => set("email")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Téléphone"
|
||||
value={form.phone ?? ""}
|
||||
onChange={(event) => set("phone")(event.target.value)}
|
||||
/>
|
||||
<label className="flex flex-col gap-2 text-sm font-medium text-foreground">
|
||||
Pays
|
||||
<select
|
||||
className="h-10 rounded-md border border-border-control bg-background px-3 text-sm"
|
||||
value={form.countryId ?? ""}
|
||||
onChange={(event) =>
|
||||
set("countryId")(event.target.value ? Number(event.target.value) : null)
|
||||
}
|
||||
>
|
||||
<option value="">— Aucun —</option>
|
||||
{countries.map((country) => (
|
||||
<option key={country.id} value={country.id}>
|
||||
{country.name} ({country.code})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<Input
|
||||
label="Adresse"
|
||||
value={form.addressLine1 ?? ""}
|
||||
onChange={(event) => set("addressLine1")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Complément"
|
||||
value={form.addressLine2 ?? ""}
|
||||
onChange={(event) => set("addressLine2")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Code postal"
|
||||
value={form.postalCode ?? ""}
|
||||
onChange={(event) => set("postalCode")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Ville"
|
||||
value={form.city ?? ""}
|
||||
onChange={(event) => set("city")(event.target.value)}
|
||||
/>
|
||||
<div className="sm:col-span-2">
|
||||
<Input
|
||||
label="Notes"
|
||||
value={form.description ?? ""}
|
||||
onChange={(event) => set("description")(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<p className="text-sm text-destructive sm:col-span-2" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="flex gap-3 sm:col-span-2">
|
||||
<Button type="submit" isLoading={busy}>
|
||||
{editing ? "Enregistrer" : "Créer"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
setEditing(null);
|
||||
setForm(EMPTY);
|
||||
setError(null);
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
Annuler
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
{loading ? (
|
||||
<div className="flex flex-col gap-3">
|
||||
<Skeleton className="h-10" />
|
||||
<Skeleton className="h-10" />
|
||||
<Skeleton className="h-10" />
|
||||
</div>
|
||||
) : error && rows.length === 0 ? (
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
) : rows.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Aucune entreprise. Créez la première pour commencer.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="min-h-0 flex-1 overflow-y-auto overflow-x-auto">
|
||||
<table className="w-full border-collapse text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border-control text-left text-xs uppercase tracking-label text-subtle-foreground">
|
||||
<th className="py-2 pr-4">Nom</th>
|
||||
<th className="py-2 pr-4">Ville</th>
|
||||
<th className="py-2 pr-4">Pays</th>
|
||||
<th className="py-2 pr-4">Secteur</th>
|
||||
<th className="py-2 pr-4">Contact</th>
|
||||
<th className="py-2 pr-4">Créée le</th>
|
||||
<th className="py-2 pr-4 text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((organization) => (
|
||||
<tr key={organization.id} className="border-b border-border-control/60">
|
||||
<td className="py-3 pr-4 font-medium">{organization.name}</td>
|
||||
<td className="py-3 pr-4">{organization.city ?? "—"}</td>
|
||||
<td className="py-3 pr-4">{organization.country_code ?? "—"}</td>
|
||||
<td className="py-3 pr-4">{organization.industry ?? "—"}</td>
|
||||
<td className="py-3 pr-4">
|
||||
{organization.email ?? organization.phone ?? "—"}
|
||||
</td>
|
||||
<td className="py-3 pr-4 text-subtle-foreground">
|
||||
{formatDate(organization.created_at)}
|
||||
</td>
|
||||
<td className="py-3 pr-4">
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button size="sm" variant="secondary" onClick={() => openEdit(organization)}>
|
||||
Modifier
|
||||
</Button>
|
||||
{
|
||||
<Button size="sm" variant="destructive" onClick={() => void remove(organization)}>
|
||||
Supprimer
|
||||
</Button>
|
||||
}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<Input
|
||||
label="Secteur"
|
||||
value={form.industry ?? ""}
|
||||
onChange={(event) => set("industry")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Site web"
|
||||
type="url"
|
||||
value={form.website ?? ""}
|
||||
onChange={(event) => set("website")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="E-mail"
|
||||
type="email"
|
||||
value={form.email ?? ""}
|
||||
onChange={(event) => set("email")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Téléphone"
|
||||
value={form.phone ?? ""}
|
||||
onChange={(event) => set("phone")(event.target.value)}
|
||||
/>
|
||||
<label className="flex flex-col gap-2 text-sm font-medium text-foreground">
|
||||
Pays
|
||||
<select
|
||||
className="h-10 w-full rounded-sm border border-border-control bg-surface px-3 text-sm text-foreground transition-[background-color,border-color,box-shadow] duration-fast ease-out-soft hover:border-accent/60 hover:bg-surface-raised focus-visible:border-border-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
|
||||
value={form.countryId ?? ""}
|
||||
onChange={(event) =>
|
||||
set("countryId")(event.target.value ? Number(event.target.value) : null)
|
||||
}
|
||||
>
|
||||
<option value="">— Aucun —</option>
|
||||
{countries.map((country) => (
|
||||
<option key={country.id} value={country.id}>
|
||||
{country.name} ({country.code})
|
||||
</option>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<p className="mt-3 text-xs text-subtle-foreground">
|
||||
{total} entreprise{total > 1 ? "s" : ""}
|
||||
{loading ? <Spinner size="xs" /> : null}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</select>
|
||||
</label>
|
||||
<Input
|
||||
label="Adresse"
|
||||
value={form.addressLine1 ?? ""}
|
||||
onChange={(event) => set("addressLine1")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Complément"
|
||||
value={form.addressLine2 ?? ""}
|
||||
onChange={(event) => set("addressLine2")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Code postal"
|
||||
value={form.postalCode ?? ""}
|
||||
onChange={(event) => set("postalCode")(event.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="Ville"
|
||||
value={form.city ?? ""}
|
||||
onChange={(event) => set("city")(event.target.value)}
|
||||
/>
|
||||
<div className="sm:col-span-2">
|
||||
<Input
|
||||
label="Notes"
|
||||
value={form.description ?? ""}
|
||||
onChange={(event) => set("description")(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{formError ? (
|
||||
<p className="text-sm text-destructive sm:col-span-2" role="alert">
|
||||
{formError}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="flex items-center justify-end gap-3 sm:col-span-2">
|
||||
<Button type="button" variant="secondary" onClick={close}>
|
||||
Annuler
|
||||
</Button>
|
||||
<Button type="submit" isLoading={busy}>
|
||||
{editing ? "Enregistrer" : "Créer"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</RecordDialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -2,3 +2,11 @@
|
||||
@import "@cohaise/ui/styles";
|
||||
|
||||
@source "../../../../frontend/shared/src";
|
||||
|
||||
/* Hauteur explicite de la racine : le shell du CRM peut ainsi occuper
|
||||
exactement le viewport et ne jamais faire defiler la page elle-meme. */
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
@@ -49,6 +49,7 @@ export const Input = ({
|
||||
className={cn(
|
||||
"w-full rounded-sm border bg-surface text-foreground placeholder:text-subtle-foreground",
|
||||
"transition-[background-color,border-color,box-shadow] duration-fast ease-out-soft",
|
||||
"enabled:hover:border-accent/60 enabled:hover:bg-surface-raised",
|
||||
"focus-visible:ring-ring focus-visible:border-border-strong focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-offset-background focus-visible:outline-none",
|
||||
"disabled:cursor-not-allowed disabled:bg-surface-muted disabled:opacity-60",
|
||||
isInvalid ? "border-destructive focus-visible:ring-destructive" : "border-border-control",
|
||||
|
||||
@@ -70,6 +70,13 @@
|
||||
--default-transition-timing-function: var(--cohaise-ease-out-soft);
|
||||
}
|
||||
|
||||
/* Verre « liquide » : panneau translucide floute, pose sur le fond sombre.
|
||||
Partage par la vitrine et le CRM pour que les deux enveloppes se repondent. */
|
||||
.glass {
|
||||
background: color-mix(in oklab, var(--cohaise-surface) 58%, transparent);
|
||||
backdrop-filter: blur(16px) saturate(1.5);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
html,
|
||||
body {
|
||||
|
||||
+92
-63
@@ -1,19 +1,20 @@
|
||||
# @cohaise/web
|
||||
|
||||
Vitrine institutionnelle de `cohaise.dev`. Première application du monorepo CoHaiSe et premier consommateur réel du design system partagé.
|
||||
Vitrine institutionnelle de `cohaise.dev`, en Next.js 16 (app router, export
|
||||
statique). Ses routes sont servies par nginx : aucun serveur Node en production.
|
||||
|
||||
## Rôle
|
||||
|
||||
| Responsabilité | Localisation |
|
||||
| -------------------------------------------- | ----------------- |
|
||||
| Design system, jetons, composants | `frontend/shared` |
|
||||
| vitrine institutionnelle | `frontend/web` |
|
||||
| Point d'entrée local, publication des builds | `docker/nginx` |
|
||||
| Responsabilité | Localisation |
|
||||
| --- | --- |
|
||||
| Design system, jetons, composants | `frontend/shared` |
|
||||
| Vitrine institutionnelle | `frontend/web` |
|
||||
| Publication des builds | `docker/` |
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph navigateur
|
||||
app["frontend/web<br/>React + Vite"]
|
||||
app["frontend/web<br/>Next.js (export statique)"]
|
||||
end
|
||||
subgraph monorepo
|
||||
ui["frontend/shared<br/>@cohaise/ui"]
|
||||
@@ -22,7 +23,7 @@ flowchart LR
|
||||
web["nginx<br/>cohaise.dev"]
|
||||
end
|
||||
app -->|import| ui
|
||||
app -->|build statique| web
|
||||
app -->|out/| web
|
||||
```
|
||||
|
||||
## Prérequis
|
||||
@@ -32,76 +33,104 @@ flowchart LR
|
||||
|
||||
## Commandes
|
||||
|
||||
| Commande | Effet |
|
||||
| ----------------------------------- | ----------------------------------------------------------- |
|
||||
| `npm run dev -w @cohaise/web` | serveur Vite sur `http://localhost:5173` |
|
||||
| `npm run build -w @cohaise/web` | vérification de types puis build de production dans `dist/` |
|
||||
| `npm run preview -w @cohaise/web` | sert le build de production localement |
|
||||
| `npm run typecheck -w @cohaise/web` | vérification de types seule |
|
||||
| `make web` | construit l'image et republie le build dans le volume Nginx |
|
||||
| Commande | Effet |
|
||||
| --- | --- |
|
||||
| `npm run dev -w @cohaise/web` | serveur Next sur `http://localhost:3000` |
|
||||
| `npm run build -w @cohaise/web` | build de production dans `out/` |
|
||||
| `npm run typecheck -w @cohaise/web` | vérification de types seule |
|
||||
| `make web` | construit l'image et republie le build dans le volume nginx |
|
||||
|
||||
## Publication dans l'infrastructure
|
||||
Le premier build de la vitrine exige que `frontend/shared` soit construit :
|
||||
`npm run build` à la racine exécute `tsc --build` avant les workspaces.
|
||||
|
||||
Le `Dockerfile` est un build multi-étapes. Le contexte de construction est la racine du
|
||||
monorepo, car le build a besoin des workspaces, du lockfile et des références
|
||||
TypeScript partagées.
|
||||
## Routes
|
||||
|
||||
```text
|
||||
node:22-alpine deps installation déterministe via npm ci
|
||||
node:22-alpine builder tsc --build puis vite build
|
||||
alpine:3.21 export /app/dist, copié dans le volume web_data
|
||||
```
|
||||
| Route | Contenu |
|
||||
| --- | --- |
|
||||
| `/` | accueil : Hero + toutes les sections, JSON-LD |
|
||||
| `/services` | développement web, mobile, UI/UX, logiciels sur mesure |
|
||||
| `/demos` | CRM, inventaire IT, gamification scolaire |
|
||||
| `/stack` | technologies utilisées |
|
||||
| `/about` | présentation |
|
||||
| `/contact` | formulaire de contact → `POST /api/crm/leads` |
|
||||
| `/sitemap.xml` | généré depuis `app/lib/site.ts` |
|
||||
| `/robots.txt` | généré par `app/robots.ts` |
|
||||
| `/opengraph-image` | image 1200×630 générée par `app/opengraph-image.tsx` |
|
||||
|
||||
Le service `cohaise-web-build` copie le résultat dans le volume `web_data`, que Nginx
|
||||
monte déjà sur `/usr/share/nginx/html/web`. Aucune modification de la configuration
|
||||
Nginx n'est nécessaire, et la publication reste découplée des autres applications.
|
||||
## SEO
|
||||
|
||||
## Consommation du design system
|
||||
- `app/layout.tsx` : métadonnées par défaut, canonical, OpenGraph, Twitter,
|
||||
icônes, `metadataBase`.
|
||||
- Chaque page exporte son propre `metadata` (titre, description, canonical).
|
||||
- L'accueil injecte un JSON-LD `Organization`, `WebSite` et
|
||||
`ProfessionalService`.
|
||||
- Le HTML prérendu est en **français** : le toggle FR/EN est purement client et
|
||||
ne change pas l'URL indexée.
|
||||
|
||||
L'application importe la feuille de style publique du package partagé une seule fois, dans `src/styles/index.css` :
|
||||
## Animations et défilement
|
||||
|
||||
```css
|
||||
@import "tailwindcss";
|
||||
@import "@cohaise/ui/styles";
|
||||
- Chaque section est une région d'un écran (`<Section>`, `min-h-dvh`,
|
||||
`data-region`). Sur l'accueil, Stack et About partagent la même région.
|
||||
- `app/globals.css` : `scroll-snap-type: y mandatory` +
|
||||
`scroll-snap-stop: always` sur `main[data-scroll-snap] > section[data-region]`.
|
||||
On ne peut donc pas s'arrêter entre deux régions, ni en sauter une d'un
|
||||
geste. Le footer s'aligne sur la fin du viewport (`scroll-snap-align: end`)
|
||||
pour rester atteignable. Snap désactivé en `prefers-reduced-motion`, sous
|
||||
620 px de haut, et dès qu'une région dépasse l'écran (`html[data-snap="off"]`,
|
||||
posé par `useScrollReveal`) pour ne jamais bloquer son contenu.
|
||||
- `app/hooks/useScrollReveal.ts` observe chaque région via une bande centrale
|
||||
du viewport. Après 0,25 s d'arrêt sur la région, ses `[data-reveal]`
|
||||
apparaissent en cascade (`data-reveal-delay` pour le décalage, le hero est
|
||||
à 0,2 s). Quitter la région avant la fin annule le minuteur.
|
||||
- `app/globals.css` définit `.reveal-init` / `.is-revealed` (fade-in-up).
|
||||
- Le contenu reste visible sans JavaScript ; `prefers-reduced-motion` désactive
|
||||
les animations et le scroll-snap.
|
||||
|
||||
@source "../../../../frontend/shared/src";
|
||||
```
|
||||
## Thème et langue
|
||||
|
||||
La directive `@source` est indispensable. Sans elle, Tailwind ignore `node_modules` et les classes utilisées par les composants de `frontend/shared` ne sont jamais générées : les composants s'afficheraient sans style.
|
||||
|
||||
## Thème
|
||||
|
||||
Le thème est appliqué par la classe `dark` sur `<html>`. Le script inline de `index.html` applique la préférence enregistrée ou celle du système avant le premier rendu, ce qui évite le flash de thème clair. `src/hooks/useTheme.ts` pilote le changement et persiste le choix dans `localStorage` sous la clé `cohaise-theme`.
|
||||
- Thème : script inline dans `app/layout.tsx` (anti-FOUC), état lu après montage
|
||||
par `ThemeContext`, persisté sous `cohaise-theme`.
|
||||
- Langue : `LanguageContext`, français au premier rendu, préférence persistée
|
||||
sous `cohaise-lang` puis appliquée après hydratation.
|
||||
|
||||
## Structure
|
||||
|
||||
```text
|
||||
frontend/web
|
||||
├── index.html amorce de thème et point de montage
|
||||
├── public/favicon.webp
|
||||
├── src
|
||||
│ ├── App.tsx composition de la page
|
||||
│ ├── main.tsx point d'entrée React
|
||||
│ ├── components
|
||||
│ │ ├── DemoCard.tsx états repos, chargement, chargé
|
||||
│ │ └── ThemeToggle.tsx
|
||||
│ ├── hooks
|
||||
│ │ └── useTheme.ts
|
||||
│ └── styles/index.css import du design system
|
||||
├── tsconfig.json
|
||||
├── tsconfig.node.json
|
||||
└── vite.config.ts
|
||||
├── app
|
||||
│ ├── layout.tsx shell, providers, métadonnées, script thème
|
||||
│ ├── page.tsx accueil + JSON-LD
|
||||
│ ├── globals.css Tailwind, régions (snap), reveal
|
||||
│ ├── providers.tsx
|
||||
│ ├── components/ Section (région), Header, Hero, Services,
|
||||
│ │ Demos, StackAbout, Contact, Footer,
|
||||
│ │ Background, ScrollReveal…
|
||||
│ │ └── background/ Topography (WebGL, client uniquement)
|
||||
│ ├── contexts/ LanguageContext, ThemeContext
|
||||
│ ├── data/ services, demos, stack
|
||||
│ ├── hooks/ useScrollReveal
|
||||
│ ├── lib/ site, api, gsap
|
||||
│ ├── services/ … une page par dossier
|
||||
│ ├── sitemap.ts, robots.ts, opengraph-image.tsx
|
||||
│ └── not-found.tsx
|
||||
├── public/ favicon, images
|
||||
├── next.config.ts export statique, trailingSlash
|
||||
├── postcss.config.mjs
|
||||
└── tsconfig.json
|
||||
```
|
||||
|
||||
## Limites actuelles
|
||||
|
||||
- Aucun appel réseau : toutes les données de démonstration sont locales.
|
||||
- Aucun routage : la page est un point d'entrée unique.
|
||||
- Les URL d'API devront passer par un wrapper dédié, jamais codées en dur dans les composants.
|
||||
|
||||
## Variables d'environnement
|
||||
|
||||
L'application ne déclare aucune variable pour l'instant. Le gabarit `frontend/web/.env.example`
|
||||
prendra une entrée `VITE_API_BASE_URL` au moment où le premier appel réseau existera, afin
|
||||
que l'URL reste définie à un seul endroit. Seules les variables préfixées par `VITE_` sont
|
||||
exposées au bundle ; aucun secret ne doit jamais être lu par le navigateur.
|
||||
| Variable | Usage |
|
||||
| --- | --- |
|
||||
| `NEXT_PUBLIC_CRM_API_URL` | URL de l'API CRM au build (défaut : `https://crm.cohaise.dev`, ou `http://localhost:8082` en local) |
|
||||
|
||||
Seules les variables préfixées par `NEXT_PUBLIC_` sont exposées au navigateur.
|
||||
Aucun secret ne doit jamais être lu par le front.
|
||||
|
||||
## Limites
|
||||
|
||||
- Export statique : pas de route dynamique serveur, pas d'optimisation d'image
|
||||
Next (`images.unoptimized: true`).
|
||||
- Le fond WebGL et les animations sont chargés côté client uniquement.
|
||||
- Les tests navigateur réels (hydratation, WebGL, reveals) restent manuels.
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { Metadata } from "next";
|
||||
import { About } from "../components/About";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "À propos",
|
||||
description:
|
||||
"CoHaiSe développe des outils sur mesure, rapides, maintenables et agréables à utiliser, de la première idée à la mise en ligne.",
|
||||
alternates: { canonical: "/about" },
|
||||
};
|
||||
|
||||
export default function AboutPage() {
|
||||
return <About />;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
"use client";
|
||||
|
||||
import { useLanguage } from "../contexts/LanguageContext";
|
||||
import { Section, SectionHeading } from "./Section";
|
||||
|
||||
/** Présentation, réutilisée seule (`/about`) ou avec Stack (accueil). */
|
||||
export const AboutContent = () => {
|
||||
const { t } = useLanguage();
|
||||
|
||||
return (
|
||||
<>
|
||||
<SectionHeading title={t("about.title")} className="mb-6" />
|
||||
<p
|
||||
data-reveal
|
||||
data-reveal-delay="0.15"
|
||||
className="max-w-2xl text-base leading-relaxed text-muted-foreground sm:text-lg"
|
||||
>
|
||||
{t("about.body")}
|
||||
</p>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export const About = () => (
|
||||
<Section id="about">
|
||||
<AboutContent />
|
||||
</Section>
|
||||
);
|
||||
+11
-3
@@ -1,6 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { cn } from "@cohaise/ui";
|
||||
import { scrollToSection } from "../lib/gsap.js";
|
||||
import { scrollToSection } from "../lib/gsap";
|
||||
|
||||
export const BackToTop = () => {
|
||||
const [visible, setVisible] = useState(false);
|
||||
@@ -19,11 +21,17 @@ export const BackToTop = () => {
|
||||
aria-label="Retour en haut"
|
||||
title="Retour en haut"
|
||||
className={cn(
|
||||
"glass fixed bottom-6 right-6 z-50 flex size-11 items-center justify-center rounded-full border border-border/60 text-foreground shadow-md transition-all duration-base hover:border-border-strong",
|
||||
visible ? "translate-y-0 opacity-100" : "pointer-events-none translate-y-3 opacity-0",
|
||||
"glass group fixed bottom-6 right-6 z-50 flex size-11 items-center justify-center rounded-full border border-border/60 text-foreground shadow-md transition-all duration-base",
|
||||
"hover:-translate-y-0.5 hover:border-accent/70 hover:text-accent hover:shadow-lg hover:ring-2 hover:ring-accent/20",
|
||||
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
|
||||
"active:translate-y-0",
|
||||
visible
|
||||
? "translate-y-0 opacity-100"
|
||||
: "pointer-events-none translate-y-3 opacity-0",
|
||||
)}
|
||||
>
|
||||
<svg
|
||||
className="transition-transform duration-base group-hover:-translate-y-0.5"
|
||||
width="18"
|
||||
height="18"
|
||||
viewBox="0 0 24 24"
|
||||
@@ -0,0 +1,16 @@
|
||||
"use client";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
|
||||
// Le fond WebGL (topographie) est lourd : chargé à la demande, jamais côté
|
||||
// serveur. Il vit en position fixed (z-0) : seul le contenu (z-10) défile.
|
||||
const Topography = dynamic(() => import("./background/Topography"), {
|
||||
ssr: false,
|
||||
loading: () => null,
|
||||
});
|
||||
|
||||
export const Background = () => (
|
||||
<div className="pointer-events-none fixed inset-0 z-0" aria-hidden="true">
|
||||
<Topography color="#ff5252" opacity={0.5} speed={0.22} clickEffect="none" />
|
||||
</div>
|
||||
);
|
||||
@@ -1,12 +1,15 @@
|
||||
"use client";
|
||||
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { Input } from "@cohaise/ui";
|
||||
import { useLanguage } from "../lib/i18n.js";
|
||||
import { LEADS_ENDPOINT } from "../lib/api.js";
|
||||
import { Section, SectionHeading } from "./Section.js";
|
||||
import { useLanguage } from "../contexts/LanguageContext";
|
||||
import { LEADS_ENDPOINT } from "../lib/api";
|
||||
import { Section, SectionHeading } from "./Section";
|
||||
|
||||
type Status = "idle" | "sending" | "success" | "error";
|
||||
|
||||
const text = (value: FormDataEntryValue | null): string => String(value ?? "").trim();
|
||||
const text = (value: FormDataEntryValue | null): string =>
|
||||
String(value ?? "").trim();
|
||||
|
||||
export const Contact = () => {
|
||||
const { t } = useLanguage();
|
||||
@@ -49,12 +52,16 @@ export const Contact = () => {
|
||||
|
||||
return (
|
||||
<Section id="contact">
|
||||
<SectionHeading title={t("contact.title")} subtitle={t("contact.subtitle")} />
|
||||
<SectionHeading
|
||||
title={t("contact.title")}
|
||||
subtitle={t("contact.subtitle")}
|
||||
/>
|
||||
|
||||
<form
|
||||
onSubmit={(event) => void handleSubmit(event)}
|
||||
className="glass max-w-2xl rounded-lg border border-border/60 p-6 sm:p-8"
|
||||
className="glass max-w-2xl rounded-lg border border-border/60 p-5 sm:p-6"
|
||||
data-reveal
|
||||
data-reveal-delay="0.1"
|
||||
noValidate
|
||||
>
|
||||
<input
|
||||
@@ -66,21 +73,46 @@ export const Contact = () => {
|
||||
className="absolute -left-[9999px] h-px w-px opacity-0"
|
||||
/>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<Input name="firstName" label={t("contact.firstName")} required autoComplete="given-name" />
|
||||
<Input name="lastName" label={t("contact.lastName")} required autoComplete="family-name" />
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Input
|
||||
name="firstName"
|
||||
label={t("contact.firstName")}
|
||||
required
|
||||
autoComplete="given-name"
|
||||
/>
|
||||
<Input
|
||||
name="lastName"
|
||||
label={t("contact.lastName")}
|
||||
required
|
||||
autoComplete="family-name"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-4 sm:grid-cols-2">
|
||||
<Input name="organization" label={t("contact.company")} autoComplete="organization" />
|
||||
<Input name="phone" label={t("contact.phone")} type="tel" autoComplete="tel" />
|
||||
<div className="mt-3 grid grid-cols-2 gap-3">
|
||||
<Input
|
||||
name="organization"
|
||||
label={t("contact.company")}
|
||||
autoComplete="organization"
|
||||
/>
|
||||
<Input
|
||||
name="phone"
|
||||
label={t("contact.phone")}
|
||||
type="tel"
|
||||
autoComplete="tel"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mt-4">
|
||||
<Input name="email" label={t("contact.email")} type="email" required autoComplete="email" />
|
||||
<div className="mt-3">
|
||||
<Input
|
||||
name="email"
|
||||
label={t("contact.email")}
|
||||
type="email"
|
||||
required
|
||||
autoComplete="email"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 flex flex-col gap-1.5">
|
||||
<div className="mt-3 flex flex-col gap-1.5">
|
||||
<label
|
||||
htmlFor="message"
|
||||
className="font-display text-[0.6875rem] font-semibold uppercase tracking-label text-foreground"
|
||||
@@ -90,19 +122,21 @@ export const Contact = () => {
|
||||
<textarea
|
||||
id="message"
|
||||
name="message"
|
||||
rows={5}
|
||||
rows={4}
|
||||
required
|
||||
className="w-full rounded-sm border border-border-control bg-surface px-3 py-2.5 text-sm text-foreground placeholder:text-subtle-foreground transition-[border-color,box-shadow] duration-fast focus-visible:border-border-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 flex flex-wrap items-center gap-4">
|
||||
<div className="mt-5 flex flex-wrap items-center gap-4">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={status === "sending"}
|
||||
className="inline-flex h-12 items-center gap-2.5 rounded-lg bg-primary px-6 font-display text-sm font-semibold uppercase tracking-label text-primary-foreground transition-colors hover:bg-primary-hover disabled:pointer-events-none disabled:opacity-50"
|
||||
>
|
||||
{status === "sending" ? t("contact.sending") : t("contact.submit")}
|
||||
{status === "sending"
|
||||
? t("contact.sending")
|
||||
: t("contact.submit")}
|
||||
</button>
|
||||
|
||||
{status === "success" ? (
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import { cn } from "@cohaise/ui";
|
||||
import type { DemoVariant } from "../data/demos.js";
|
||||
import type { DemoVariant } from "../data/demos";
|
||||
|
||||
const Bar = ({ className }: { className?: string }) => (
|
||||
<span className={cn("block rounded-full bg-surface-hover", className)} aria-hidden="true" />
|
||||
@@ -1,7 +1,9 @@
|
||||
import { useLanguage } from "../lib/i18n.js";
|
||||
import type { Demo } from "../data/demos.js";
|
||||
import { DemoMockup } from "./DemoMockup.js";
|
||||
import { Section, SectionHeading } from "./Section.js";
|
||||
"use client";
|
||||
|
||||
import { useLanguage } from "../contexts/LanguageContext";
|
||||
import type { Demo } from "../data/demos";
|
||||
import { DemoMockup } from "./DemoMockup";
|
||||
import { Section, SectionHeading } from "./Section";
|
||||
|
||||
export const Demos = ({ demos }: { demos: Demo[] }) => {
|
||||
const { t, pick } = useLanguage();
|
||||
@@ -10,24 +12,29 @@ export const Demos = ({ demos }: { demos: Demo[] }) => {
|
||||
<Section id="demos">
|
||||
<SectionHeading title={t("demos.title")} subtitle={t("demos.subtitle")} />
|
||||
|
||||
<div className="grid gap-6 md:grid-cols-3">
|
||||
{/*
|
||||
Sur mobile, les cartes défilent horizontalement : la région garde la
|
||||
hauteur d'un écran au lieu d'empiler trois blocs. Dès `md`, on retrouve
|
||||
la grille de trois colonnes.
|
||||
*/}
|
||||
<div className="-mx-4 flex snap-x snap-mandatory gap-4 overflow-x-auto px-4 pb-2 [scrollbar-width:none] sm:-mx-6 sm:px-6 md:mx-0 md:grid md:grid-cols-3 md:gap-6 md:overflow-visible md:px-0 md:pb-0">
|
||||
{demos.map((demo, index) => (
|
||||
<article
|
||||
key={demo.slug}
|
||||
data-reveal
|
||||
data-reveal-delay={String(index * 0.08)}
|
||||
className="glass flex flex-col overflow-hidden rounded-lg border border-border/60 shadow-sm"
|
||||
className="glass flex w-[82%] max-w-xs shrink-0 snap-center flex-col overflow-hidden rounded-lg border border-border/60 shadow-sm md:w-auto md:max-w-none md:snap-align-none"
|
||||
>
|
||||
<DemoMockup variant={demo.mockup} />
|
||||
|
||||
<div className="flex flex-1 flex-col gap-3 p-5">
|
||||
<div className="flex flex-1 flex-col gap-3 p-4 sm:p-5">
|
||||
<span className="font-display text-[0.625rem] font-semibold uppercase tracking-label text-accent-graphic">
|
||||
{pick(demo.category)}
|
||||
</span>
|
||||
<h3 className="font-display text-lg font-bold uppercase tracking-display">
|
||||
{demo.title}
|
||||
</h3>
|
||||
<p className="text-sm leading-relaxed text-muted-foreground">
|
||||
<p className="line-clamp-3 text-sm leading-relaxed text-muted-foreground">
|
||||
{pick(demo.description)}
|
||||
</p>
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { useLanguage } from "../lib/i18n.js";
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useLanguage } from "../contexts/LanguageContext";
|
||||
|
||||
const year = new Date().getFullYear();
|
||||
|
||||
@@ -9,15 +12,21 @@ export const Footer = () => {
|
||||
<footer className="border-t border-border/60">
|
||||
<div className="mx-auto flex w-full max-w-6xl flex-col gap-6 px-4 py-10 sm:flex-row sm:items-center sm:justify-between sm:px-6">
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="font-logo text-sm font-bold tracking-logo text-foreground">
|
||||
<Link
|
||||
href="/"
|
||||
className="font-logo text-sm font-bold tracking-logo text-foreground"
|
||||
>
|
||||
{t("brand.name")}
|
||||
</span>
|
||||
</Link>
|
||||
<span className="text-xs text-subtle-foreground">
|
||||
{t("footer.built")}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<nav className="flex flex-wrap gap-x-6 gap-y-2" aria-label="Liens">
|
||||
<nav
|
||||
className="flex flex-wrap gap-x-6 gap-y-2"
|
||||
aria-label="Liens externes"
|
||||
>
|
||||
<a
|
||||
href="https://git.cohaise.dev/Esiah"
|
||||
target="_blank"
|
||||
@@ -0,0 +1,253 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type MouseEvent,
|
||||
} from "react";
|
||||
import { cn } from "@cohaise/ui";
|
||||
import { useLanguage } from "../contexts/LanguageContext";
|
||||
import {
|
||||
scrollToSection,
|
||||
setPendingSection,
|
||||
takePendingSection,
|
||||
} from "../lib/gsap";
|
||||
import { ThemeToggle } from "./ThemeToggle";
|
||||
|
||||
const links = [
|
||||
{ id: "services", path: "/services", key: "nav.services" },
|
||||
{ id: "demos", path: "/demos", key: "nav.demos" },
|
||||
{ id: "stack", path: "/stack", key: "nav.stack" },
|
||||
{ id: "about", path: "/about", key: "nav.about" },
|
||||
{ id: "contact", path: "/contact", key: "nav.contact" },
|
||||
] as const;
|
||||
|
||||
type SectionId = (typeof links)[number]["id"];
|
||||
type NavLink = (typeof links)[number];
|
||||
|
||||
const normalize = (path: string): string =>
|
||||
path !== "/" ? path.replace(/\/+$/, "") : path;
|
||||
|
||||
/*
|
||||
Durée pendant laquelle le suivi du scroll est suspendu après un clic : le
|
||||
temps que GSAP atteigne la région sans que l'indicateur ne revienne en
|
||||
arrière. Une fois le défilement fini, l'onglet cliqué reste donc actif
|
||||
(utile pour « À propos », qui partage la région de « Stack »).
|
||||
*/
|
||||
const NAV_LOCK = 1400;
|
||||
|
||||
interface Indicator {
|
||||
left: number;
|
||||
width: number;
|
||||
}
|
||||
|
||||
export const Header = () => {
|
||||
const { t, lang, setLang } = useLanguage();
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
const current = normalize(pathname);
|
||||
|
||||
const navRef = useRef<HTMLDivElement>(null);
|
||||
const tabRefs = useRef(new Map<SectionId, HTMLAnchorElement>());
|
||||
const lockUntil = useRef(0);
|
||||
const [active, setActive] = useState<SectionId | null>(null);
|
||||
const [indicator, setIndicator] = useState<Indicator | null>(null);
|
||||
|
||||
/** Région qui occupe la bande centrale du viewport. */
|
||||
const regionAt = useCallback((): SectionId | null => {
|
||||
const marker = window.innerHeight * 0.45;
|
||||
let found: SectionId | null = null;
|
||||
|
||||
for (const link of links) {
|
||||
const element = document.getElementById(link.id);
|
||||
if (!element) continue;
|
||||
const rect = element.getBoundingClientRect();
|
||||
if (rect.top <= marker && rect.bottom > marker) found = link.id;
|
||||
}
|
||||
|
||||
return found;
|
||||
}, []);
|
||||
|
||||
/** Aligne la pastille glissante sur l'onglet actif. */
|
||||
const measure = useCallback(() => {
|
||||
const nav = navRef.current;
|
||||
const tab = active ? tabRefs.current.get(active) : undefined;
|
||||
if (!nav || !tab) {
|
||||
setIndicator(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const navRect = nav.getBoundingClientRect();
|
||||
const tabRect = tab.getBoundingClientRect();
|
||||
setIndicator({ left: tabRect.left - navRect.left, width: tabRect.width });
|
||||
}, [active]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
measure();
|
||||
}, [measure, lang]);
|
||||
|
||||
useEffect(() => {
|
||||
const nav = navRef.current;
|
||||
if (!nav) return;
|
||||
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(nav);
|
||||
|
||||
// Les libellés changent de largeur quand la police arrive.
|
||||
document.fonts?.ready.then(measure).catch(() => {});
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, [measure]);
|
||||
|
||||
/*
|
||||
Sur l'accueil, l'onglet actif suit la région visible. Depuis une page SEO
|
||||
autonome, il suit le chemin courant ; au retour, la région mémorisée est
|
||||
rejointe sans passer par un `#`.
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (current !== "/") {
|
||||
const match = links.find((link) => link.path === current);
|
||||
setActive(match?.id ?? null);
|
||||
return;
|
||||
}
|
||||
|
||||
let frame = 0;
|
||||
const pending = takePendingSection();
|
||||
const target = pending
|
||||
? links.find((link) => link.id === pending)
|
||||
: undefined;
|
||||
|
||||
if (target) {
|
||||
setActive(target.id);
|
||||
lockUntil.current = Date.now() + NAV_LOCK;
|
||||
// Deux frames : laisser Next monter la page d'accueil et poser les régions.
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = requestAnimationFrame(() => {
|
||||
const duration = scrollToSection(`#${target.id}`);
|
||||
lockUntil.current = Date.now() + Math.max(NAV_LOCK, duration + 400);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
setActive(regionAt());
|
||||
}
|
||||
|
||||
const onScroll = () => {
|
||||
if (Date.now() < lockUntil.current) return;
|
||||
setActive(regionAt());
|
||||
};
|
||||
|
||||
window.addEventListener("scroll", onScroll, { passive: true });
|
||||
window.addEventListener("resize", onScroll);
|
||||
|
||||
return () => {
|
||||
cancelAnimationFrame(frame);
|
||||
window.removeEventListener("scroll", onScroll);
|
||||
window.removeEventListener("resize", onScroll);
|
||||
};
|
||||
}, [current, regionAt]);
|
||||
|
||||
const goTo = (event: MouseEvent<HTMLAnchorElement>, link: NavLink) => {
|
||||
if (current !== "/") {
|
||||
event.preventDefault();
|
||||
setPendingSection(link.id);
|
||||
router.push("/");
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
lockUntil.current = Date.now() + NAV_LOCK;
|
||||
setActive(link.id);
|
||||
const duration = scrollToSection(`#${link.id}`);
|
||||
lockUntil.current = Date.now() + Math.max(NAV_LOCK, duration + 400);
|
||||
};
|
||||
|
||||
const goHome = (event: MouseEvent<HTMLAnchorElement>) => {
|
||||
if (current !== "/") return;
|
||||
event.preventDefault();
|
||||
lockUntil.current = Date.now() + NAV_LOCK;
|
||||
setActive(null);
|
||||
const duration = scrollToSection("#top");
|
||||
lockUntil.current = Date.now() + Math.max(NAV_LOCK, duration + 400);
|
||||
};
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-40 border-b border-border/60 bg-background/70 backdrop-blur-xl">
|
||||
<div className="mx-auto flex h-16 max-w-6xl items-center gap-4 px-4 sm:px-6">
|
||||
<Link href="/" onClick={goHome} className="flex items-center gap-2.5">
|
||||
<img
|
||||
src="/images/cohaise.webp"
|
||||
alt=""
|
||||
width={28}
|
||||
height={28}
|
||||
className="size-7 object-contain"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="font-logo text-sm font-bold tracking-logo text-foreground">
|
||||
{t("brand.name")}
|
||||
</span>
|
||||
</Link>
|
||||
|
||||
<nav className="ml-auto hidden md:flex" aria-label="Navigation">
|
||||
<div
|
||||
ref={navRef}
|
||||
className="relative flex items-center gap-0.5 rounded-full border border-border/70 bg-surface/50 p-1 backdrop-blur-md"
|
||||
>
|
||||
{/* Pastille unique qui glisse d'un onglet à l'autre. */}
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"pointer-events-none absolute bottom-1 left-0 top-1 z-0 rounded-full bg-accent/15 ring-1 ring-accent/30 transition-[transform,width,opacity] duration-500 ease-out-soft",
|
||||
indicator ? "opacity-100" : "opacity-0",
|
||||
)}
|
||||
style={{
|
||||
width: indicator?.width ?? 0,
|
||||
transform: `translateX(${indicator?.left ?? 0}px)`,
|
||||
}}
|
||||
/>
|
||||
|
||||
{links.map((link) => {
|
||||
const isActive = active === link.id;
|
||||
return (
|
||||
<Link
|
||||
key={link.id}
|
||||
ref={(node) => {
|
||||
if (node) tabRefs.current.set(link.id, node);
|
||||
else tabRefs.current.delete(link.id);
|
||||
}}
|
||||
href={link.path}
|
||||
onClick={(event) => goTo(event, link)}
|
||||
aria-current={isActive ? "page" : undefined}
|
||||
className={cn(
|
||||
"relative z-10 flex h-8 items-center rounded-full px-3.5 font-display text-[0.6875rem] font-semibold uppercase tracking-label transition-colors duration-fast",
|
||||
isActive
|
||||
? "text-accent"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{t(link.key)}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div className="flex items-center gap-2 md:ml-6">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setLang(lang === "fr" ? "en" : "fr")}
|
||||
className="inline-flex h-8 items-center justify-center rounded-full border border-border/70 bg-surface/40 px-2.5 font-display text-[0.625rem] font-semibold uppercase tracking-label text-muted-foreground transition-colors hover:border-accent/50 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background focus-visible:outline-none"
|
||||
aria-label={lang === "fr" ? "Switch to English" : "Passer en français"}
|
||||
>
|
||||
{lang === "fr" ? "EN" : "FR"}
|
||||
</button>
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
};
|
||||
@@ -1,14 +1,17 @@
|
||||
import { useLanguage } from "../lib/i18n.js";
|
||||
import { scrollToSection } from "../lib/gsap.js";
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useLanguage } from "../contexts/LanguageContext";
|
||||
import { Section } from "./Section";
|
||||
|
||||
export const Hero = () => {
|
||||
const { t } = useLanguage();
|
||||
|
||||
return (
|
||||
<section className="mx-auto flex w-full max-w-6xl flex-col items-start gap-6 px-4 pb-28 pt-24 sm:px-6 sm:pt-32">
|
||||
<Section id="hero" delay={0.05} className="items-start gap-6">
|
||||
<h1
|
||||
data-reveal
|
||||
data-reveal-delay="0.08"
|
||||
data-reveal-delay="0.05"
|
||||
className="font-display text-5xl font-black uppercase leading-none tracking-display sm:text-7xl md:text-8xl"
|
||||
>
|
||||
{t("brand.name")}
|
||||
@@ -16,7 +19,7 @@ export const Hero = () => {
|
||||
|
||||
<p
|
||||
data-reveal
|
||||
data-reveal-delay="0.16"
|
||||
data-reveal-delay="0.1"
|
||||
className="max-w-2xl text-xl font-medium leading-relaxed text-foreground sm:text-2xl"
|
||||
>
|
||||
{t("hero.tagline")}
|
||||
@@ -24,7 +27,7 @@ export const Hero = () => {
|
||||
|
||||
<p
|
||||
data-reveal
|
||||
data-reveal-delay="0.24"
|
||||
data-reveal-delay="0.15"
|
||||
className="max-w-xl text-base leading-relaxed text-muted-foreground"
|
||||
>
|
||||
{t("hero.subtitle")}
|
||||
@@ -32,30 +35,22 @@ export const Hero = () => {
|
||||
|
||||
<div
|
||||
data-reveal
|
||||
data-reveal-delay="0.32"
|
||||
data-reveal-delay="0.2"
|
||||
className="mt-6 flex flex-wrap gap-3"
|
||||
>
|
||||
<a
|
||||
href="#services"
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
scrollToSection("#services");
|
||||
}}
|
||||
<Link
|
||||
href="/services"
|
||||
className="inline-flex h-12 items-center gap-2.5 rounded-lg bg-primary px-6 font-display text-sm font-semibold uppercase tracking-label text-primary-foreground transition-colors hover:bg-primary-hover"
|
||||
>
|
||||
{t("hero.primary")}
|
||||
</a>
|
||||
<a
|
||||
href="#contact"
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
scrollToSection("#contact");
|
||||
}}
|
||||
</Link>
|
||||
<Link
|
||||
href="/contact"
|
||||
className="inline-flex h-12 items-center gap-2.5 rounded-lg border border-border-strong bg-surface px-6 font-display text-sm font-semibold uppercase tracking-label text-foreground transition-colors hover:bg-surface-hover"
|
||||
>
|
||||
{t("hero.secondary")}
|
||||
</a>
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
</Section>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { useScrollReveal } from "../hooks/useScrollReveal";
|
||||
|
||||
/** Monte l'observateur d'animations d'entrée, une fois par page. */
|
||||
export const ScrollReveal = () => {
|
||||
useScrollReveal();
|
||||
return null;
|
||||
};
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { cn } from "@cohaise/ui";
|
||||
|
||||
export interface SectionProps {
|
||||
id: string;
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
/**
|
||||
* Secondes d'attente avant de révéler la région, une fois qu'elle occupe
|
||||
* le centre de l'écran. Absent → délai par défaut de `useScrollReveal`.
|
||||
*/
|
||||
delay?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Une région = un écran. `min-h-dvh` et le scroll-snap de `globals.css`
|
||||
* garantissent qu'on ne s'arrête jamais entre deux sections ; le contenu est
|
||||
* centré verticalement et laisse respirer l'en-tête sticky en haut.
|
||||
*/
|
||||
export const Section = ({ id, children, className, delay }: SectionProps) => (
|
||||
<section
|
||||
id={id}
|
||||
data-region
|
||||
data-region-delay={delay === undefined ? undefined : String(delay)}
|
||||
className={cn(
|
||||
"relative mx-auto flex min-h-dvh w-full max-w-6xl flex-col justify-center px-4 pb-8 pt-20 sm:px-6 sm:py-16",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
|
||||
export const SectionHeading = ({
|
||||
eyebrow,
|
||||
title,
|
||||
subtitle,
|
||||
className,
|
||||
}: {
|
||||
eyebrow?: string;
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
className?: string;
|
||||
}) => (
|
||||
<div className={cn("mb-8 flex flex-col gap-3", className)} data-reveal>
|
||||
{eyebrow ? (
|
||||
<span className="font-display text-[0.625rem] font-semibold uppercase tracking-label text-accent-graphic">
|
||||
{eyebrow}
|
||||
</span>
|
||||
) : null}
|
||||
<h2 className="font-display text-3xl font-bold uppercase tracking-display sm:text-4xl">
|
||||
{title}
|
||||
</h2>
|
||||
{subtitle ? (
|
||||
<p className="max-w-2xl text-sm leading-relaxed text-muted-foreground sm:text-base">
|
||||
{subtitle}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
@@ -0,0 +1,101 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { cn } from "@cohaise/ui";
|
||||
import { useLanguage } from "../contexts/LanguageContext";
|
||||
import type { Service } from "../data/services";
|
||||
import { Section, SectionHeading } from "./Section";
|
||||
|
||||
/**
|
||||
* Services en onglets plutôt qu'en accordéon : la hauteur de la région reste
|
||||
* stable, donc le scroll-snap ne saute jamais quand on change de service.
|
||||
*/
|
||||
export const Services = ({ services }: { services: Service[] }) => {
|
||||
const { t, pick } = useLanguage();
|
||||
const [selected, setSelected] = useState(services[0]?.slug ?? null);
|
||||
const current =
|
||||
services.find((service) => service.slug === selected) ?? services[0];
|
||||
|
||||
return (
|
||||
<Section id="services">
|
||||
<SectionHeading
|
||||
title={t("services.title")}
|
||||
subtitle={t("services.subtitle")}
|
||||
/>
|
||||
|
||||
<div className="grid gap-6 md:grid-cols-[minmax(0,0.85fr)_minmax(0,1.15fr)] md:items-center md:gap-10">
|
||||
<div className="flex flex-col" data-reveal>
|
||||
{services.map((service) => {
|
||||
const active = service.slug === current?.slug;
|
||||
return (
|
||||
<button
|
||||
key={service.slug}
|
||||
type="button"
|
||||
onClick={() => setSelected(service.slug)}
|
||||
aria-pressed={active}
|
||||
className={cn(
|
||||
"group flex w-full items-center gap-3 border-b border-border/60 py-3 text-left first:border-t sm:py-4",
|
||||
active
|
||||
? "text-foreground"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"font-display text-xl font-bold uppercase tracking-display transition-colors sm:text-2xl md:text-3xl",
|
||||
active && "text-accent",
|
||||
)}
|
||||
>
|
||||
{pick(service.title)}
|
||||
</span>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"ml-auto font-display text-2xl font-light transition-transform duration-base",
|
||||
active
|
||||
? "rotate-45 text-accent"
|
||||
: "rotate-0 text-subtle-foreground",
|
||||
)}
|
||||
>
|
||||
+
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{current ? (
|
||||
<div
|
||||
data-reveal
|
||||
data-reveal-delay="0.12"
|
||||
aria-live="polite"
|
||||
className="glass flex min-h-40 flex-col gap-4 rounded-lg border border-border/60 p-4 sm:min-h-72 sm:p-5"
|
||||
>
|
||||
<img
|
||||
src={current.image}
|
||||
alt=""
|
||||
width={600}
|
||||
height={400}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
className="hidden aspect-[16/9] max-h-48 w-full rounded-md border border-border/60 object-cover sm:block"
|
||||
/>
|
||||
<p className="text-sm leading-relaxed text-muted-foreground sm:text-base">
|
||||
{pick(current.description)}
|
||||
</p>
|
||||
<ul className="flex flex-wrap gap-2">
|
||||
{current.tags.map((tag) => (
|
||||
<li
|
||||
key={pick(tag)}
|
||||
className="rounded-full border border-border/60 px-3 py-1 text-[0.625rem] uppercase tracking-label text-foreground transition-colors hover:bg-surface-hover sm:px-4 sm:py-1.5 sm:text-[0.6875rem]"
|
||||
>
|
||||
{pick(tag)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</Section>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,110 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { gsap, prefersReducedMotion } from "../lib/gsap";
|
||||
import { useLanguage } from "../contexts/LanguageContext";
|
||||
import { stack } from "../data/stack";
|
||||
import { Section, SectionHeading } from "./Section";
|
||||
|
||||
/** Bandeau technologique, réutilisé seul (`/stack`) ou avec About (accueil). */
|
||||
export const StackContent = () => {
|
||||
const { t } = useLanguage();
|
||||
const trackRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const track = trackRef.current;
|
||||
if (!track || prefersReducedMotion()) return;
|
||||
|
||||
const region = track.closest<HTMLElement>("[data-region]");
|
||||
|
||||
// Le bandeau ne démarre qu'une fois la région révélée : sinon les logos
|
||||
// défilent alors que le reste de Stack/About est encore masqué.
|
||||
let tween: gsap.core.Tween | undefined;
|
||||
const slow = () => {
|
||||
if (tween) gsap.to(tween, { timeScale: 0.25, duration: 0.6, overwrite: true });
|
||||
};
|
||||
const resume = () => {
|
||||
if (tween) gsap.to(tween, { timeScale: 1, duration: 0.6, overwrite: true });
|
||||
};
|
||||
|
||||
const start = () => {
|
||||
if (tween) return;
|
||||
// Deux copies rendues dans le JSX : -50 % = exactement une copie, boucle sans couture.
|
||||
tween = gsap.to(track, {
|
||||
xPercent: -50,
|
||||
duration: 36,
|
||||
ease: "none",
|
||||
repeat: -1,
|
||||
});
|
||||
track.addEventListener("mouseenter", slow);
|
||||
track.addEventListener("mouseleave", resume);
|
||||
};
|
||||
|
||||
let observer: MutationObserver | undefined;
|
||||
if (!region || region.dataset.revealed === "true") {
|
||||
start();
|
||||
} else {
|
||||
observer = new MutationObserver(() => {
|
||||
if (region.dataset.revealed !== "true") return;
|
||||
observer?.disconnect();
|
||||
observer = undefined;
|
||||
start();
|
||||
});
|
||||
observer.observe(region, {
|
||||
attributes: true,
|
||||
attributeFilter: ["data-revealed"],
|
||||
});
|
||||
}
|
||||
|
||||
return () => {
|
||||
observer?.disconnect();
|
||||
track.removeEventListener("mouseenter", slow);
|
||||
track.removeEventListener("mouseleave", resume);
|
||||
tween?.kill();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const doubled = [...stack, ...stack];
|
||||
|
||||
return (
|
||||
<>
|
||||
<SectionHeading
|
||||
title={t("stack.title")}
|
||||
subtitle={t("stack.subtitle")}
|
||||
className="mb-6"
|
||||
/>
|
||||
|
||||
<div
|
||||
data-reveal
|
||||
data-reveal-delay="0.1"
|
||||
className="overflow-hidden [mask-image:linear-gradient(to_right,transparent,black_10%,black_90%,transparent)]"
|
||||
>
|
||||
<div ref={trackRef} className="flex w-max items-center gap-12">
|
||||
{doubled.map((item, index) => {
|
||||
const Icon = item.Icon;
|
||||
return (
|
||||
<span
|
||||
key={`${item.name}-${index}`}
|
||||
className="group/item flex shrink-0 items-center gap-3 whitespace-nowrap"
|
||||
>
|
||||
<Icon
|
||||
className="size-7 text-subtle-foreground transition-transform duration-300 ease-out group-hover/item:scale-125"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="font-display text-lg uppercase tracking-label text-subtle-foreground">
|
||||
{item.name}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export const Stack = () => (
|
||||
<Section id="stack">
|
||||
<StackContent />
|
||||
</Section>
|
||||
);
|
||||
@@ -0,0 +1,20 @@
|
||||
import { AboutContent } from "./About";
|
||||
import { Section } from "./Section";
|
||||
import { StackContent } from "./Stack";
|
||||
|
||||
/**
|
||||
* Une seule région pour Stack et About : le snap ne peut donc jamais
|
||||
* s'arrêter entre les deux. Les deux blocs sont empilés et occupent toute la
|
||||
* largeur de la région.
|
||||
*/
|
||||
export const StackAbout = () => (
|
||||
<Section id="stack">
|
||||
<div className="flex w-full flex-col gap-8 sm:gap-10">
|
||||
<StackContent />
|
||||
{/* Ancre du menu : About partage la région de Stack sur l'accueil. */}
|
||||
<div id="about" className="w-full">
|
||||
<AboutContent />
|
||||
</div>
|
||||
</div>
|
||||
</Section>
|
||||
);
|
||||
@@ -0,0 +1,65 @@
|
||||
"use client";
|
||||
|
||||
import { useLanguage } from "../contexts/LanguageContext";
|
||||
import { useTheme } from "../contexts/ThemeContext";
|
||||
|
||||
/**
|
||||
* Soleil et lune au trait fin, avec une étoile : la bascule de thème prend le
|
||||
* vocabulaire « spatial » du reste du site plutôt qu'un libellé texte.
|
||||
*
|
||||
* Le CSS de `globals.css` décide laquelle est visible selon `.dark` (posé avant
|
||||
* le premier rendu par le script anti-FOUC), donc aucun flash d'icône.
|
||||
*/
|
||||
const SunIcon = () => (
|
||||
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true" className="size-[18px]">
|
||||
<circle cx="12" cy="12" r="3.6" stroke="currentColor" strokeWidth="1.5" />
|
||||
<circle cx="12" cy="12" r="1" fill="currentColor" />
|
||||
<g stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
|
||||
<path d="M12 2.75v1.9M12 19.35v1.9M2.75 12h1.9M19.35 12h1.9M5.45 5.45l1.35 1.35M17.2 17.2l1.35 1.35M18.55 5.45l-1.35 1.35M6.8 17.2l-1.35 1.35" />
|
||||
</g>
|
||||
<path
|
||||
d="M19.4 2.6l.45 1.05 1.05.45-1.05.45-.45 1.05-.45-1.05-1.05-.45 1.05-.45Z"
|
||||
fill="currentColor"
|
||||
opacity=".8"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
|
||||
const MoonIcon = () => (
|
||||
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true" className="size-[18px]">
|
||||
<path
|
||||
d="M20.2 14.6A8.6 8.6 0 0 1 9.4 3.8 8.6 8.6 0 1 0 20.2 14.6Z"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<path
|
||||
d="M17.6 4.1l.4.95.95.4-.95.4-.4.95-.4-.95-.95-.4.95-.4Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
<circle cx="21" cy="8.6" r=".7" fill="currentColor" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const ThemeToggle = () => {
|
||||
const { t } = useLanguage();
|
||||
const { theme, toggleTheme } = useTheme();
|
||||
const label = t(theme === "dark" ? "theme.light" : "theme.dark");
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleTheme}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
className="group relative inline-flex h-8 w-8 items-center justify-center rounded-full border border-border/70 bg-surface/40 text-muted-foreground transition-[color,background-color,border-color,box-shadow] duration-fast ease-out-soft hover:border-accent/50 hover:bg-accent/10 hover:text-accent hover:shadow-[0_0_20px_-6px_var(--color-accent)] focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background focus-visible:outline-none"
|
||||
>
|
||||
<span className="theme-icon theme-icon-sun absolute inset-0 flex items-center justify-center transition-[opacity,transform] duration-500 ease-out-soft">
|
||||
<SunIcon />
|
||||
</span>
|
||||
<span className="theme-icon theme-icon-moon absolute inset-0 flex items-center justify-center transition-[opacity,transform] duration-500 ease-out-soft">
|
||||
<MoonIcon />
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Contact } from "../components/Contact";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Contact",
|
||||
description:
|
||||
"Un projet en tête ? Contactez CoHaiSe pour discuter de votre site vitrine, application mobile ou logiciel sur mesure.",
|
||||
alternates: { canonical: "/contact" },
|
||||
};
|
||||
|
||||
export default function ContactPage() {
|
||||
return <Contact />;
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
@@ -104,10 +106,14 @@ const dictionaries: Record<Lang, Record<MessageKey, string>> = { fr, en };
|
||||
|
||||
const STORAGE_KEY = "cohaise-lang";
|
||||
|
||||
const readInitialLang = (): Lang => {
|
||||
const stored = window.localStorage.getItem(STORAGE_KEY);
|
||||
if (stored === "fr" || stored === "en") return stored;
|
||||
if (navigator.language?.toLowerCase().startsWith("en")) return "en";
|
||||
const readStoredLang = (): Lang => {
|
||||
try {
|
||||
const stored = window.localStorage.getItem(STORAGE_KEY);
|
||||
if (stored === "fr" || stored === "en") return stored;
|
||||
if (window.navigator.language?.toLowerCase().startsWith("en")) return "en";
|
||||
} catch {
|
||||
// localStorage indisponible (navigation privée stricte, etc.)
|
||||
}
|
||||
return "fr";
|
||||
};
|
||||
|
||||
@@ -121,11 +127,23 @@ interface LanguageContextValue {
|
||||
const LanguageContext = createContext<LanguageContextValue | null>(null);
|
||||
|
||||
export const LanguageProvider = ({ children }: { children: ReactNode }) => {
|
||||
const [lang, setLangState] = useState<Lang>(readInitialLang);
|
||||
// Le premier rendu est toujours en français : il doit être identique côté
|
||||
// serveur (export statique) et côté client pour éviter un mismatch
|
||||
// d'hydratation. La préférence stockée est appliquée après le montage.
|
||||
const [lang, setLangState] = useState<Lang>("fr");
|
||||
|
||||
useEffect(() => {
|
||||
const next = readStoredLang();
|
||||
setLangState((current) => (current === next ? current : next));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.lang = lang;
|
||||
window.localStorage.setItem(STORAGE_KEY, lang);
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_KEY, lang);
|
||||
} catch {
|
||||
// Écriture impossible : la langue reste valable pour la session.
|
||||
}
|
||||
}, [lang]);
|
||||
|
||||
const setLang = useCallback((next: Lang) => setLangState(next), []);
|
||||
@@ -0,0 +1,66 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
|
||||
export type Theme = "light" | "dark";
|
||||
|
||||
const STORAGE_KEY = "cohaise-theme";
|
||||
|
||||
interface ThemeContextValue {
|
||||
/** `null` tant que la préférence n'a pas été lue côté client. */
|
||||
theme: Theme | null;
|
||||
toggleTheme: () => void;
|
||||
}
|
||||
|
||||
const ThemeContext = createContext<ThemeContextValue | null>(null);
|
||||
|
||||
export const ThemeProvider = ({ children }: { children: ReactNode }) => {
|
||||
// Rendu serveur et premier rendu client identiques (`null`). Le script
|
||||
// inline de `layout.tsx` a déjà posé `.dark` sur <html> avant l'hydratation :
|
||||
// on se contente de lire cet état après le montage.
|
||||
const [theme, setTheme] = useState<Theme | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setTheme(
|
||||
document.documentElement.classList.contains("dark") ? "dark" : "light",
|
||||
);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (theme === null) return;
|
||||
document.documentElement.classList.toggle("dark", theme === "dark");
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_KEY, theme);
|
||||
} catch {
|
||||
// Écriture impossible : le thème reste valable pour la session.
|
||||
}
|
||||
}, [theme]);
|
||||
|
||||
const toggleTheme = useCallback(() => {
|
||||
setTheme((current) => (current === "dark" ? "light" : "dark"));
|
||||
}, []);
|
||||
|
||||
const value = useMemo<ThemeContextValue>(
|
||||
() => ({ theme, toggleTheme }),
|
||||
[theme, toggleTheme],
|
||||
);
|
||||
|
||||
return (
|
||||
<ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useTheme = (): ThemeContextValue => {
|
||||
const context = useContext(ThemeContext);
|
||||
if (!context)
|
||||
throw new Error("useTheme doit être utilisé sous ThemeProvider.");
|
||||
return context;
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Localized } from "../lib/i18n.js";
|
||||
import type { Localized } from "../contexts/LanguageContext";
|
||||
|
||||
export type DemoVariant = "crm" | "inventory" | "leaderboard";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Localized } from "../lib/i18n.js";
|
||||
import type { Localized } from "../contexts/LanguageContext";
|
||||
|
||||
export interface Service {
|
||||
slug: string;
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Demos } from "../components/Demos";
|
||||
import { demos } from "../data/demos";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Démos",
|
||||
description:
|
||||
"Des réalisations concrètes : CRM, inventaire IT et gamification scolaire. Découvrez des projets réels construits avec React, Next.js et Docker.",
|
||||
alternates: { canonical: "/demos" },
|
||||
};
|
||||
|
||||
export default function DemosPage() {
|
||||
return <Demos demos={demos} />;
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
@import "tailwindcss";
|
||||
@import "@cohaise/ui/styles";
|
||||
|
||||
@source "../../shared/src";
|
||||
|
||||
@layer base {
|
||||
body {
|
||||
min-height: 100dvh;
|
||||
}
|
||||
|
||||
/*
|
||||
Une région = un écran. Le snap est `mandatory` : le navigateur ne peut pas
|
||||
s'arrêter entre deux régions, et `scroll-snap-stop: always` empêche un
|
||||
geste rapide d'en sauter une. Pas de `scroll-padding-top` : l'en-tête est
|
||||
sticky, chaque région réserve elle-même la place sous lui.
|
||||
*/
|
||||
html:has(main[data-scroll-snap]) {
|
||||
scroll-snap-type: y mandatory;
|
||||
}
|
||||
|
||||
/*
|
||||
Pendant un saut de menu, `scrollToSection` anime la page région par région.
|
||||
Le snap obligatoire reprendrait la main à chaque étape et transformerait la
|
||||
séquence en saut direct : on le suspend le temps de l'animation.
|
||||
*/
|
||||
html[data-scroll-anim]:has(main[data-scroll-snap]) {
|
||||
scroll-snap-type: none;
|
||||
}
|
||||
|
||||
main[data-scroll-snap] > section[data-region] {
|
||||
scroll-snap-align: start;
|
||||
scroll-snap-stop: always;
|
||||
}
|
||||
|
||||
/*
|
||||
Le pied de page vit hors région, après la dernière. Sans point d'ancrage,
|
||||
un snap obligatoire rendrait le bas de page inatteignable : on aligne sa
|
||||
fin sur le bas du viewport, ce qui correspond exactement au scroll maximal.
|
||||
*/
|
||||
html:has(main[data-scroll-snap]) footer {
|
||||
scroll-snap-align: end;
|
||||
scroll-snap-stop: always;
|
||||
}
|
||||
|
||||
/*
|
||||
Si une région est plus haute que l'écran (téléphone étroit, texte long),
|
||||
un snap obligatoire bloquerait la fin de son contenu. `useScrollReveal`
|
||||
mesure les régions et coupe le snap dans ce cas.
|
||||
*/
|
||||
html[data-snap="off"]:has(main[data-scroll-snap]) {
|
||||
scroll-snap-type: none;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
html {
|
||||
scroll-behavior: auto;
|
||||
}
|
||||
|
||||
html:has(main[data-scroll-snap]) {
|
||||
scroll-snap-type: none;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Fenêtres très basses (téléphone en paysage, petite fenêtre) : une région
|
||||
plus haute que l'écran deviendrait impossible à parcourir avec un snap
|
||||
obligatoire. On rend la main au défilement libre.
|
||||
*/
|
||||
@media (max-height: 620px) {
|
||||
html:has(main[data-scroll-snap]) {
|
||||
scroll-snap-type: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Pages SEO autonomes (/services, /about, ...) : une seule région, pas de
|
||||
pied de page, hauteur bornée sous l'en-tête (h-16). La page tient donc
|
||||
exactement dans le viewport et ne défile pas. Les liens du menu, eux,
|
||||
ramènent à l'accueil sur la région correspondante.
|
||||
|
||||
Hors `@layer` : ces règles doivent l'emporter sur `min-h-dvh` de `Section`.
|
||||
*/
|
||||
html:has(main[data-scroll-snap] > section[data-region]:only-child) footer {
|
||||
display: none;
|
||||
}
|
||||
|
||||
main[data-scroll-snap]:has(> section[data-region]:only-child),
|
||||
main[data-scroll-snap] > section[data-region]:only-child {
|
||||
/* h-16 + la bordure basse de l'en-tête (1 px). */
|
||||
min-height: calc(100dvh - 4rem - 1px);
|
||||
}
|
||||
|
||||
/* L'en-tête est déjà au-dessus de la région : inutile de réserver `pt-20`. */
|
||||
main[data-scroll-snap] > section[data-region]:only-child {
|
||||
padding-block: 2rem;
|
||||
}
|
||||
|
||||
/*
|
||||
Bascule de thème : en clair on montre la lune (passage au sombre), en sombre
|
||||
le soleil. `.dark` est posé avant le premier rendu, donc pas de flash.
|
||||
*/
|
||||
.theme-icon-sun {
|
||||
opacity: 0;
|
||||
transform: rotate(-90deg) scale(0.5);
|
||||
}
|
||||
|
||||
.theme-icon-moon {
|
||||
opacity: 1;
|
||||
transform: rotate(0deg) scale(1);
|
||||
}
|
||||
|
||||
.dark .theme-icon-sun {
|
||||
opacity: 1;
|
||||
transform: rotate(0deg) scale(1);
|
||||
}
|
||||
|
||||
.dark .theme-icon-moon {
|
||||
opacity: 0;
|
||||
transform: rotate(90deg) scale(0.5);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.theme-icon {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Animations d'entrée : le contenu est visible par défaut (pas de JS, pas de
|
||||
masquage SSR). `useScrollReveal` ajoute `.reveal-init` côté client avant
|
||||
d'observer l'élément, puis `.is-revealed` quand le threshold est franchi.
|
||||
*/
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.reveal-init {
|
||||
opacity: 0;
|
||||
transform: translateY(24px);
|
||||
will-change: opacity, transform;
|
||||
}
|
||||
|
||||
.reveal-init.is-revealed {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
transition:
|
||||
opacity 0.7s ease-out,
|
||||
transform 0.7s cubic-bezier(0.22, 1, 0.36, 1);
|
||||
transition-delay: var(--reveal-delay, 0s);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
import { usePathname } from "next/navigation";
|
||||
|
||||
export interface RevealOptions {
|
||||
/** Attente par défaut, en secondes, avant de révéler une région. */
|
||||
delay?: number;
|
||||
/**
|
||||
* Bande du viewport qui rend une région « active ». Par défaut le tiers
|
||||
* central : une région est active quand elle occupe le milieu de l'écran.
|
||||
*/
|
||||
rootMargin?: string;
|
||||
}
|
||||
|
||||
const DEFAULT_DELAY = 0.25;
|
||||
const DEFAULT_ROOT_MARGIN = "-35% 0px -35% 0px";
|
||||
|
||||
/**
|
||||
* Anime l'entrée d'une région après que le visiteur s'y est arrêté.
|
||||
*
|
||||
* Chaque `[data-region]` est observé dans une bande centrale du viewport. Le
|
||||
* délai court (0,25 s par défaut, `data-region-delay` pour le surcharger) ne
|
||||
* démarre que lorsque la région occupe cette bande ; s'il repart avant la fin,
|
||||
* le minuteur est annulé et la région se révélera à son prochain passage. Les
|
||||
* éléments `[data-reveal]` de la région apparaissent alors en cascade via
|
||||
* `data-reveal-delay`.
|
||||
*
|
||||
* Le contenu reste visible sans JavaScript et avec `prefers-reduced-motion`.
|
||||
*/
|
||||
export const useScrollReveal = ({
|
||||
delay = DEFAULT_DELAY,
|
||||
rootMargin = DEFAULT_ROOT_MARGIN,
|
||||
}: RevealOptions = {}): void => {
|
||||
const pathname = usePathname();
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === "undefined") return;
|
||||
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
|
||||
|
||||
const regions = Array.from(
|
||||
document.querySelectorAll<HTMLElement>("[data-region]"),
|
||||
);
|
||||
if (regions.length === 0) return;
|
||||
|
||||
const timers = new Map<HTMLElement, number>();
|
||||
|
||||
// Un snap obligatoire sur une région plus haute que l'écran rendrait la fin
|
||||
// de son contenu inatteignable : dans ce cas on rend la main au défilement
|
||||
// libre (cf. `html[data-snap="off"]` dans `globals.css`).
|
||||
const root = document.documentElement;
|
||||
const syncSnap = () => {
|
||||
const tooTall = regions.some(
|
||||
(region) => region.getBoundingClientRect().height > window.innerHeight + 1,
|
||||
);
|
||||
if (tooTall) root.dataset.snap = "off";
|
||||
else delete root.dataset.snap;
|
||||
};
|
||||
syncSnap();
|
||||
const resizeObserver = new ResizeObserver(syncSnap);
|
||||
for (const region of regions) resizeObserver.observe(region);
|
||||
window.addEventListener("resize", syncSnap);
|
||||
|
||||
const reveal = (region: HTMLElement) => {
|
||||
region.dataset.revealed = "true";
|
||||
region.querySelectorAll<HTMLElement>("[data-reveal]").forEach((item) => {
|
||||
const itemDelay = Number.parseFloat(item.dataset.revealDelay ?? "");
|
||||
if (Number.isFinite(itemDelay) && itemDelay > 0) {
|
||||
item.style.setProperty("--reveal-delay", `${itemDelay}s`);
|
||||
}
|
||||
item.classList.add("is-revealed");
|
||||
});
|
||||
};
|
||||
|
||||
// Masquage posé au montage : le HTML prérendu reste lisible sans JS.
|
||||
for (const region of regions) {
|
||||
if (region.dataset.revealed === "true") continue;
|
||||
region
|
||||
.querySelectorAll<HTMLElement>("[data-reveal]")
|
||||
.forEach((item) => item.classList.add("reveal-init"));
|
||||
}
|
||||
|
||||
const waitFor = (region: HTMLElement): number => {
|
||||
const raw = region.dataset.regionDelay;
|
||||
if (raw === undefined) return delay;
|
||||
const value = Number.parseFloat(raw);
|
||||
return Number.isFinite(value) && value >= 0 ? value : delay;
|
||||
};
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
for (const entry of entries) {
|
||||
const region = entry.target as HTMLElement;
|
||||
|
||||
if (entry.isIntersecting) {
|
||||
/*
|
||||
Pendant un saut de menu, la région ne fait que traverser l'écran :
|
||||
le délai serait annulé avant la fin. On la révèle tout de suite
|
||||
pour que la séquence ne montre pas de zones vides.
|
||||
*/
|
||||
if (document.documentElement.dataset.scrollAnim !== undefined) {
|
||||
reveal(region);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (region.dataset.revealed === "true" || timers.has(region)) {
|
||||
continue;
|
||||
}
|
||||
timers.set(
|
||||
region,
|
||||
window.setTimeout(() => {
|
||||
timers.delete(region);
|
||||
reveal(region);
|
||||
}, waitFor(region) * 1000),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Sortie de la bande avant la fin du délai : le visiteur a continué
|
||||
// sa route, inutile de révéler une région qu'il ne regarde plus.
|
||||
const timer = timers.get(region);
|
||||
if (timer !== undefined) {
|
||||
window.clearTimeout(timer);
|
||||
timers.delete(region);
|
||||
}
|
||||
}
|
||||
},
|
||||
{ threshold: 0, rootMargin },
|
||||
);
|
||||
|
||||
for (const region of regions) observer.observe(region);
|
||||
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
resizeObserver.disconnect();
|
||||
window.removeEventListener("resize", syncSnap);
|
||||
for (const timer of timers.values()) window.clearTimeout(timer);
|
||||
timers.clear();
|
||||
};
|
||||
}, [pathname, delay, rootMargin]);
|
||||
};
|
||||
@@ -0,0 +1,120 @@
|
||||
import type { Metadata, Viewport } from "next";
|
||||
import "./globals.css";
|
||||
import { Providers } from "./providers";
|
||||
import { Header } from "./components/Header";
|
||||
import { Footer } from "./components/Footer";
|
||||
import { BackToTop } from "./components/BackToTop";
|
||||
import { Background } from "./components/Background";
|
||||
import { ScrollReveal } from "./components/ScrollReveal";
|
||||
import { SITE_DESCRIPTION, SITE_NAME, SITE_URL } from "./lib/site";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
metadataBase: new URL(SITE_URL),
|
||||
title: {
|
||||
default: "CoHaiSe — Développement web, applications et design sur mesure",
|
||||
template: "%s | CoHaiSe",
|
||||
},
|
||||
description: SITE_DESCRIPTION,
|
||||
applicationName: SITE_NAME,
|
||||
authors: [{ name: "Esiah", url: SITE_URL }],
|
||||
creator: "CoHaiSe",
|
||||
publisher: "CoHaiSe",
|
||||
category: "technology",
|
||||
keywords: [
|
||||
"développement web",
|
||||
"site vitrine",
|
||||
"application mobile",
|
||||
"React",
|
||||
"Next.js",
|
||||
"UI UX design",
|
||||
"logiciel sur mesure",
|
||||
"CoHaiSe",
|
||||
],
|
||||
alternates: {
|
||||
canonical: "/",
|
||||
},
|
||||
openGraph: {
|
||||
type: "website",
|
||||
locale: "fr_FR",
|
||||
url: SITE_URL,
|
||||
siteName: SITE_NAME,
|
||||
title: "CoHaiSe — Développement web, applications et design sur mesure",
|
||||
description: SITE_DESCRIPTION,
|
||||
images: [
|
||||
{
|
||||
url: "/images/cohaise.webp",
|
||||
width: 512,
|
||||
height: 512,
|
||||
alt: "CoHaiSe",
|
||||
},
|
||||
],
|
||||
},
|
||||
twitter: {
|
||||
card: "summary_large_image",
|
||||
title: "CoHaiSe — Développement web, applications et design sur mesure",
|
||||
description: SITE_DESCRIPTION,
|
||||
images: ["/images/cohaise.webp"],
|
||||
},
|
||||
icons: {
|
||||
icon: [{ url: "/favicon.webp", type: "image/webp" }],
|
||||
shortcut: ["/favicon.webp"],
|
||||
},
|
||||
robots: {
|
||||
index: true,
|
||||
follow: true,
|
||||
googleBot: { index: true, follow: true },
|
||||
},
|
||||
};
|
||||
|
||||
export const viewport: Viewport = {
|
||||
colorScheme: "light dark",
|
||||
themeColor: [
|
||||
{ media: "(prefers-color-scheme: light)", color: "#f7f5f4" },
|
||||
{ media: "(prefers-color-scheme: dark)", color: "#050000" },
|
||||
],
|
||||
};
|
||||
|
||||
// Script anti-FOUC : applique le thème enregistré avant le premier rendu.
|
||||
const themeScript = `(() => {
|
||||
try {
|
||||
const stored = localStorage.getItem("cohaise-theme");
|
||||
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||||
const theme = stored ?? (prefersDark ? "dark" : "light");
|
||||
if (theme === "dark") document.documentElement.classList.add("dark");
|
||||
} catch {}
|
||||
})();`;
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<html lang="fr" suppressHydrationWarning>
|
||||
<head>
|
||||
<script dangerouslySetInnerHTML={{ __html: themeScript }} />
|
||||
</head>
|
||||
<body className="bg-background text-foreground antialiased">
|
||||
<Providers>
|
||||
<div
|
||||
id="top"
|
||||
className="relative flex min-h-screen flex-col"
|
||||
>
|
||||
<Background />
|
||||
|
||||
<div className="relative z-10 flex flex-1 flex-col">
|
||||
<Header />
|
||||
<main data-scroll-snap className="flex flex-1 flex-col">
|
||||
{children}
|
||||
</main>
|
||||
<Footer />
|
||||
</div>
|
||||
|
||||
<BackToTop />
|
||||
<ScrollReveal />
|
||||
</div>
|
||||
</Providers>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
/** Point d'entrée de l'API CRM. Surchargeable via VITE_CRM_API_URL au build. */
|
||||
/** Point d'entrée de l'API CRM. Surchargeable via NEXT_PUBLIC_CRM_API_URL au build. */
|
||||
const host = typeof window !== "undefined" ? window.location.hostname : "";
|
||||
const isLocal = host === "localhost" || host === "127.0.0.1" || host === "0.0.0.0";
|
||||
const isLocal =
|
||||
host === "localhost" || host === "127.0.0.1" || host === "0.0.0.0";
|
||||
|
||||
const base =
|
||||
(import.meta.env.VITE_CRM_API_URL as string | undefined) ??
|
||||
process.env.NEXT_PUBLIC_CRM_API_URL ??
|
||||
(isLocal ? "http://localhost:8082" : "https://crm.cohaise.dev");
|
||||
|
||||
const trimmed = base.replace(/\/+$/, "");
|
||||
@@ -0,0 +1,197 @@
|
||||
import { gsap } from "gsap";
|
||||
import { ScrollToPlugin } from "gsap/ScrollToPlugin";
|
||||
|
||||
gsap.registerPlugin(ScrollToPlugin);
|
||||
|
||||
export { gsap };
|
||||
|
||||
export const prefersReducedMotion = (): boolean =>
|
||||
typeof window !== "undefined" &&
|
||||
window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
|
||||
/*
|
||||
Le menu ne touche plus à l'URL : pour ramener un visiteur d'une page SEO vers
|
||||
une région de l'accueil, on mémorise la cible le temps de la navigation.
|
||||
`sessionStorage` survit au montage de la nouvelle page et reste limité à
|
||||
l'onglet courant.
|
||||
*/
|
||||
const PENDING_SECTION_KEY = "cohaise:pending-section";
|
||||
|
||||
export const setPendingSection = (id: string): void => {
|
||||
try {
|
||||
window.sessionStorage.setItem(PENDING_SECTION_KEY, id);
|
||||
} catch {
|
||||
// Stockage indisponible : le lien ramènera simplement en haut de l'accueil.
|
||||
}
|
||||
};
|
||||
|
||||
export const takePendingSection = (): string | null => {
|
||||
try {
|
||||
const id = window.sessionStorage.getItem(PENDING_SECTION_KEY);
|
||||
if (id !== null) window.sessionStorage.removeItem(PENDING_SECTION_KEY);
|
||||
return id;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/** Position de scroll maximale de la page. */
|
||||
const maxScroll = (): number =>
|
||||
Math.max(0, document.documentElement.scrollHeight - window.innerHeight);
|
||||
|
||||
/** Début de chaque région, plus le haut de page, sans doublon. */
|
||||
const scrollStops = (): number[] => {
|
||||
const limit = maxScroll();
|
||||
const regions = Array.from(
|
||||
document.querySelectorAll<HTMLElement>(
|
||||
"main[data-scroll-snap] > [data-region]",
|
||||
),
|
||||
);
|
||||
const tops = regions.map((region) => {
|
||||
const top = region.getBoundingClientRect().top + window.scrollY;
|
||||
return Math.round(Math.min(Math.max(top, 0), limit));
|
||||
});
|
||||
|
||||
return [...new Set([0, ...tops])].sort((a, b) => a - b);
|
||||
};
|
||||
|
||||
/** Index du dernier point d'arrêt situé au-dessus de la position courante. */
|
||||
const stopAtOrAbove = (stops: number[], y: number): number => {
|
||||
let index = 0;
|
||||
for (let i = 0; i < stops.length; i += 1) {
|
||||
const stop = stops[i];
|
||||
if (stop === undefined || stop > y + 2) break;
|
||||
index = i;
|
||||
}
|
||||
return index;
|
||||
};
|
||||
|
||||
/*
|
||||
Un saut de menu ne téléporte plus la page : elle est animée région par
|
||||
région, avec une courte respiration entre chaque étape. Le snap obligatoire
|
||||
est suspendu pendant la séquence (`html[data-scroll-anim]`), sinon le
|
||||
navigateur reprend la main et saute directement à la destination.
|
||||
*/
|
||||
const STEP_DURATION = 0.45;
|
||||
const STEP_GAP = 0.06;
|
||||
|
||||
let sequence: gsap.core.Timeline | null = null;
|
||||
|
||||
/**
|
||||
* Anime le défilement vers une section, sans toucher à l'URL.
|
||||
*
|
||||
* @returns la durée de la séquence en millisecondes (0 si aucun mouvement).
|
||||
*/
|
||||
export const scrollToSection = (hash: string): number => {
|
||||
const target = document.querySelector<HTMLElement>(hash);
|
||||
if (!target) return 0;
|
||||
|
||||
/*
|
||||
Une région est l'unité de snap : une ancre imbriquée (About partage la
|
||||
région de Stack) doit viser la région entière, sinon le snap obligatoire
|
||||
choisit un bord et peut sauter par-dessus le contenu visé.
|
||||
*/
|
||||
const anchor = target.closest<HTMLElement>("[data-region]") ?? target;
|
||||
|
||||
if (prefersReducedMotion()) {
|
||||
sequence?.kill();
|
||||
sequence = null;
|
||||
delete document.documentElement.dataset.scrollAnim;
|
||||
anchor.scrollIntoView({ behavior: "auto" });
|
||||
return 0;
|
||||
}
|
||||
|
||||
const limit = maxScroll();
|
||||
const targetTop = Math.round(
|
||||
Math.min(
|
||||
Math.max(anchor.getBoundingClientRect().top + window.scrollY, 0),
|
||||
limit,
|
||||
),
|
||||
);
|
||||
|
||||
if (Math.abs(window.scrollY - targetTop) < 2) return 0;
|
||||
|
||||
const stops = scrollStops();
|
||||
const from = stopAtOrAbove(stops, window.scrollY);
|
||||
const to = stops.reduce((best, stop, index) => {
|
||||
const bestStop = stops[best];
|
||||
if (bestStop === undefined) return index;
|
||||
return Math.abs(stop - targetTop) < Math.abs(bestStop - targetTop)
|
||||
? index
|
||||
: best;
|
||||
}, 0);
|
||||
|
||||
// Chaque région traversée est une étape : le mouvement reste lisible et
|
||||
// n'expédie jamais le visiteur d'un bord à l'autre de la page.
|
||||
const path: number[] = [];
|
||||
if (to > from) {
|
||||
for (let i = from + 1; i <= to; i += 1) {
|
||||
const stop = stops[i];
|
||||
if (stop !== undefined) path.push(stop);
|
||||
}
|
||||
} else {
|
||||
for (let i = from - 1; i >= to; i -= 1) {
|
||||
const stop = stops[i];
|
||||
if (stop !== undefined) path.push(stop);
|
||||
}
|
||||
}
|
||||
if (path.length === 0) path.push(targetTop);
|
||||
|
||||
sequence?.kill();
|
||||
|
||||
const root = document.documentElement;
|
||||
root.dataset.scrollAnim = "";
|
||||
|
||||
/*
|
||||
Un geste de défilement pendant la séquence doit reprendre la main
|
||||
immédiatement : on coupe l'animation plutôt que de lutter contre le
|
||||
visiteur. Les événements souris/tactiles arrivent après le clic qui a lancé
|
||||
la séquence, donc ils ne l'annulent pas elle-même.
|
||||
*/
|
||||
const scrollKeys = new Set([
|
||||
"ArrowUp",
|
||||
"ArrowDown",
|
||||
"PageUp",
|
||||
"PageDown",
|
||||
"Home",
|
||||
"End",
|
||||
" ",
|
||||
]);
|
||||
|
||||
const interrupt = () => {
|
||||
sequence?.kill();
|
||||
};
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (scrollKeys.has(event.key)) interrupt();
|
||||
};
|
||||
|
||||
const finish = () => {
|
||||
delete root.dataset.scrollAnim;
|
||||
window.removeEventListener("wheel", interrupt);
|
||||
window.removeEventListener("touchmove", interrupt);
|
||||
window.removeEventListener("keydown", onKeyDown);
|
||||
if (sequence === timeline) sequence = null;
|
||||
};
|
||||
|
||||
const timeline = gsap.timeline({ onComplete: finish, onInterrupt: finish });
|
||||
|
||||
window.addEventListener("wheel", interrupt, { passive: true });
|
||||
window.addEventListener("touchmove", interrupt, { passive: true });
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
|
||||
path.forEach((top, index) => {
|
||||
timeline.to(
|
||||
window,
|
||||
{
|
||||
scrollTo: { y: top, autoKill: false },
|
||||
duration: STEP_DURATION,
|
||||
ease: "power2.inOut",
|
||||
},
|
||||
index === 0 ? 0 : `+=${STEP_GAP}`,
|
||||
);
|
||||
});
|
||||
|
||||
sequence = timeline;
|
||||
return Math.round(timeline.duration() * 1000);
|
||||
};
|
||||
@@ -0,0 +1,57 @@
|
||||
/** Métadonnées de site partagées par toutes les pages. */
|
||||
export const SITE_URL = "https://cohaise.dev";
|
||||
export const SITE_NAME = "CoHaiSe";
|
||||
export const SITE_DESCRIPTION =
|
||||
"CoHaiSe conçoit des sites vitrines, applications mobiles et logiciels sur mesure : modernes, rapides et agréables à utiliser.";
|
||||
|
||||
export interface RouteMeta {
|
||||
path: string;
|
||||
title: string;
|
||||
description: string;
|
||||
priority: number;
|
||||
}
|
||||
|
||||
/** Routes publiques indexables, source unique du menu et du sitemap. */
|
||||
export const ROUTES: RouteMeta[] = [
|
||||
{
|
||||
path: "/",
|
||||
title: "Développement web, applications et design sur mesure",
|
||||
description: SITE_DESCRIPTION,
|
||||
priority: 1,
|
||||
},
|
||||
{
|
||||
path: "/services",
|
||||
title: "Services",
|
||||
description:
|
||||
"Développement web, applications mobiles, UI/UX design et logiciels sur mesure. Des outils modernes, rapides et pensés pour durer.",
|
||||
priority: 0.9,
|
||||
},
|
||||
{
|
||||
path: "/demos",
|
||||
title: "Démos",
|
||||
description:
|
||||
"Des réalisations concrètes : CRM, inventaire IT et gamification scolaire. Découvrez des projets réels construits avec React, Next.js et Docker.",
|
||||
priority: 0.8,
|
||||
},
|
||||
{
|
||||
path: "/stack",
|
||||
title: "Stack technique",
|
||||
description:
|
||||
"React, Next.js, TypeScript, Node.js, MariaDB, Docker, Tailwind CSS : les technologies qui font tourner les projets CoHaiSe.",
|
||||
priority: 0.7,
|
||||
},
|
||||
{
|
||||
path: "/about",
|
||||
title: "À propos",
|
||||
description:
|
||||
"CoHaiSe développe des outils sur mesure, rapides, maintenables et agréables à utiliser, de la première idée à la mise en ligne.",
|
||||
priority: 0.7,
|
||||
},
|
||||
{
|
||||
path: "/contact",
|
||||
title: "Contact",
|
||||
description:
|
||||
"Un projet en tête ? Contactez CoHaiSe pour discuter de votre site vitrine, application mobile ou logiciel sur mesure.",
|
||||
priority: 0.8,
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,24 @@
|
||||
import Link from "next/link";
|
||||
|
||||
export default function NotFound() {
|
||||
return (
|
||||
<section className="mx-auto flex w-full max-w-6xl flex-col items-start gap-6 px-4 py-32 sm:px-6">
|
||||
<span className="font-display text-[0.625rem] font-semibold uppercase tracking-label text-accent-graphic">
|
||||
404
|
||||
</span>
|
||||
<h1 className="font-display text-4xl font-black uppercase leading-none tracking-display sm:text-6xl">
|
||||
Page introuvable
|
||||
</h1>
|
||||
<p className="max-w-xl text-base leading-relaxed text-muted-foreground">
|
||||
La page demandée n'existe pas ou a été déplacée. Revenez à
|
||||
l'accueil pour découvrir les services CoHaiSe.
|
||||
</p>
|
||||
<Link
|
||||
href="/"
|
||||
className="inline-flex h-12 items-center rounded-lg bg-primary px-6 font-display text-sm font-semibold uppercase tracking-label text-primary-foreground transition-colors hover:bg-primary-hover"
|
||||
>
|
||||
Retour à l'accueil
|
||||
</Link>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { ImageResponse } from "next/og";
|
||||
import { SITE_DESCRIPTION, SITE_NAME } from "./lib/site";
|
||||
|
||||
export const dynamic = "force-static";
|
||||
export const alt = `${SITE_NAME} — Développement web, applications et design sur mesure`;
|
||||
export const size = { width: 1200, height: 630 };
|
||||
export const contentType = "image/png";
|
||||
|
||||
export default function OpenGraphImage() {
|
||||
return new ImageResponse(
|
||||
(
|
||||
<div
|
||||
style={{
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
justifyContent: "space-between",
|
||||
padding: "72px",
|
||||
background: "#050000",
|
||||
color: "#f7f5f4",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "20px",
|
||||
fontSize: 40,
|
||||
fontWeight: 700,
|
||||
letterSpacing: "0.18em",
|
||||
color: "#ff5252",
|
||||
}}
|
||||
>
|
||||
COHAISE
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
gap: "24px",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
fontSize: 76,
|
||||
fontWeight: 800,
|
||||
lineHeight: 1.05,
|
||||
textTransform: "uppercase",
|
||||
}}
|
||||
>
|
||||
<span>Développement web,</span>
|
||||
<span>applications & design</span>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
fontSize: 30,
|
||||
lineHeight: 1.4,
|
||||
color: "#c9c4c2",
|
||||
maxWidth: "900px",
|
||||
}}
|
||||
>
|
||||
{SITE_DESCRIPTION}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
{ ...size },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Hero } from "./components/Hero";
|
||||
import { Services } from "./components/Services";
|
||||
import { Demos } from "./components/Demos";
|
||||
import { StackAbout } from "./components/StackAbout";
|
||||
import { Contact } from "./components/Contact";
|
||||
import { services } from "./data/services";
|
||||
import { demos } from "./data/demos";
|
||||
import { SITE_DESCRIPTION, SITE_NAME, SITE_URL } from "./lib/site";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
description: SITE_DESCRIPTION,
|
||||
alternates: { canonical: "/" },
|
||||
};
|
||||
|
||||
const jsonLd = {
|
||||
"@context": "https://schema.org",
|
||||
"@graph": [
|
||||
{
|
||||
"@type": "Organization",
|
||||
"@id": `${SITE_URL}/#organization`,
|
||||
name: SITE_NAME,
|
||||
url: SITE_URL,
|
||||
logo: `${SITE_URL}/images/cohaise.webp`,
|
||||
sameAs: [
|
||||
"https://git.cohaise.dev/Esiah",
|
||||
"https://github.com/xEsiah",
|
||||
],
|
||||
},
|
||||
{
|
||||
"@type": "WebSite",
|
||||
"@id": `${SITE_URL}/#website`,
|
||||
url: SITE_URL,
|
||||
name: SITE_NAME,
|
||||
inLanguage: "fr",
|
||||
publisher: { "@id": `${SITE_URL}/#organization` },
|
||||
},
|
||||
{
|
||||
"@type": "ProfessionalService",
|
||||
"@id": `${SITE_URL}/#service`,
|
||||
name: SITE_NAME,
|
||||
url: SITE_URL,
|
||||
description: SITE_DESCRIPTION,
|
||||
areaServed: "FR",
|
||||
serviceType: [
|
||||
"Développement web",
|
||||
"Applications mobiles",
|
||||
"UI/UX design",
|
||||
"Logiciels sur mesure",
|
||||
],
|
||||
parentOrganization: { "@id": `${SITE_URL}/#organization` },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export default function HomePage() {
|
||||
return (
|
||||
<>
|
||||
<script
|
||||
type="application/ld+json"
|
||||
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
|
||||
/>
|
||||
<Hero />
|
||||
<Services services={services} />
|
||||
<Demos demos={demos} />
|
||||
<StackAbout />
|
||||
<Contact />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import { LanguageProvider } from "./contexts/LanguageContext";
|
||||
import { ThemeProvider } from "./contexts/ThemeContext";
|
||||
|
||||
export const Providers = ({ children }: { children: React.ReactNode }) => (
|
||||
<ThemeProvider>
|
||||
<LanguageProvider>{children}</LanguageProvider>
|
||||
</ThemeProvider>
|
||||
);
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { MetadataRoute } from "next";
|
||||
import { SITE_URL } from "./lib/site";
|
||||
|
||||
export const dynamic = "force-static";
|
||||
|
||||
export default function robots(): MetadataRoute.Robots {
|
||||
return {
|
||||
rules: [{ userAgent: "*", allow: "/" }],
|
||||
sitemap: `${SITE_URL}/sitemap.xml`,
|
||||
host: SITE_URL,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Services } from "../components/Services";
|
||||
import { services } from "../data/services";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Services",
|
||||
description:
|
||||
"Développement web, applications mobiles, UI/UX design et logiciels sur mesure. Des outils modernes, rapides et pensés pour durer.",
|
||||
alternates: { canonical: "/services" },
|
||||
};
|
||||
|
||||
export default function ServicesPage() {
|
||||
return <Services services={services} />;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { MetadataRoute } from "next";
|
||||
import { ROUTES, SITE_URL } from "./lib/site";
|
||||
|
||||
export const dynamic = "force-static";
|
||||
|
||||
export default function sitemap(): MetadataRoute.Sitemap {
|
||||
const lastModified = new Date();
|
||||
|
||||
return ROUTES.map((route) => {
|
||||
// `trailingSlash: true` : l'URL canonique se termine par `/` sauf la racine.
|
||||
const path = route.path === "/" ? "/" : `${route.path}/`;
|
||||
return {
|
||||
url: new URL(path, SITE_URL).toString(),
|
||||
lastModified,
|
||||
changeFrequency: route.path === "/" ? "monthly" : "yearly",
|
||||
priority: route.priority,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Stack } from "../components/Stack";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Stack technique",
|
||||
description:
|
||||
"React, Next.js, TypeScript, Node.js, MariaDB, Docker, Tailwind CSS : les technologies qui font tourner les projets CoHaiSe.",
|
||||
alternates: { canonical: "/stack" },
|
||||
};
|
||||
|
||||
export default function StackPage() {
|
||||
return <Stack />;
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="color-scheme" content="light dark" />
|
||||
<meta
|
||||
name="description"
|
||||
content="CoHaiSe conçoit des sites vitrines, applications mobiles et logiciels sur mesure : modernes, rapides et agréables à utiliser."
|
||||
/>
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.webp" />
|
||||
<title>
|
||||
CoHaiSe — Développement web, applications et design sur mesure
|
||||
</title>
|
||||
<script>
|
||||
(() => {
|
||||
const stored = localStorage.getItem("cohaise-theme");
|
||||
const prefersDark = window.matchMedia(
|
||||
"(prefers-color-scheme: dark)",
|
||||
).matches;
|
||||
const theme = stored ?? (prefersDark ? "dark" : "light");
|
||||
if (theme === "dark") document.documentElement.classList.add("dark");
|
||||
})();
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
import "./.next/types/routes.d.ts";
|
||||
import "./.next/types/root-params.d.ts";
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
// Vitrine entièrement statique : `next build` produit `out/`, publié tel quel
|
||||
// par nginx (voir docker/Dockerfile.app). Aucun serveur Node en production.
|
||||
output: "export",
|
||||
trailingSlash: true,
|
||||
poweredByHeader: false,
|
||||
images: {
|
||||
// L'export statique n'a pas de serveur d'optimisation d'images.
|
||||
unoptimized: true,
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
@@ -4,27 +4,26 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"preview": "vite preview",
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@cohaise/ui": "*",
|
||||
"gsap": "^3.15.1",
|
||||
"next": "16.4.6",
|
||||
"react": "^19.3.0",
|
||||
"react-dom": "^19.3.0",
|
||||
"react-icons": "^5.7.0",
|
||||
"three": "^0.187.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@tailwindcss/postcss": "^4.3.3",
|
||||
"@types/node": "^24.0.0",
|
||||
"@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"
|
||||
"typescript": "^7.0.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
const config = {
|
||||
plugins: {
|
||||
"@tailwindcss/postcss": {},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -1,50 +0,0 @@
|
||||
import { lazy, Suspense } from "react";
|
||||
import { LanguageProvider } from "./lib/i18n.js";
|
||||
import { useScrollReveal } from "./hooks/useScrollReveal.js";
|
||||
import { Header } from "./components/Header.js";
|
||||
import { Hero } from "./components/Hero.js";
|
||||
import { Services } from "./components/Services.js";
|
||||
import { Demos } from "./components/Demos.js";
|
||||
import { Stack } from "./components/Stack.js";
|
||||
import { About } from "./components/About.js";
|
||||
import { Contact } from "./components/Contact.js";
|
||||
import { Footer } from "./components/Footer.js";
|
||||
import { BackToTop } from "./components/BackToTop.js";
|
||||
import { services } from "./data/services.js";
|
||||
import { demos } from "./data/demos.js";
|
||||
import { stack } from "./data/stack.js";
|
||||
|
||||
// Le fond WebGL (topographie) est lourd : chargé à la demande. Il vit en
|
||||
// `position: fixed` (z-0) : le défilement n'a aucune incidence sur lui, seul
|
||||
// le contenu (z-10) défile au-dessus.
|
||||
const Topography = lazy(() => import("./components/background/Topography.js"));
|
||||
|
||||
export const App = () => {
|
||||
useScrollReveal();
|
||||
|
||||
return (
|
||||
<LanguageProvider>
|
||||
<div id="top" className="relative flex min-h-screen flex-col bg-background text-foreground">
|
||||
<div className="pointer-events-none fixed inset-0 z-0" aria-hidden="true">
|
||||
<Suspense fallback={null}>
|
||||
<Topography color="#ff5252" opacity={0.5} speed={0.22} clickEffect="none" />
|
||||
</Suspense>
|
||||
</div>
|
||||
|
||||
<div className="relative z-10 flex flex-1 flex-col">
|
||||
<Header />
|
||||
<main className="flex flex-1 flex-col">
|
||||
<Hero />
|
||||
<Services services={services} />
|
||||
<Demos demos={demos} />
|
||||
<Stack items={stack} />
|
||||
<About />
|
||||
<Contact />
|
||||
</main>
|
||||
<Footer />
|
||||
<BackToTop />
|
||||
</div>
|
||||
</div>
|
||||
</LanguageProvider>
|
||||
);
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user