-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
336 lines (297 loc) · 12.4 KB
/
Copy pathserver.js
File metadata and controls
336 lines (297 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import express from "express";
import mysql from "mysql2/promise";
const app = express();
app.use(express.json());
app.use(express.static("public"));
// --- Palette de couleurs autorisées pour les projets ---------------------
// Source de vérité côté serveur : toute couleur hors de cette liste est
// refusée (on retombe alors sur la couleur par défaut).
const PROJECT_COLORS = [
"#4f46e5", // bleu (défaut)
"#16a34a", // vert
"#ea580c", // orange
"#dc2626", // rouge
"#7c3aed", // violet
"#db2777", // rose
"#0891b2", // turquoise
"#6b7280", // gris
];
const DEFAULT_COLOR = PROJECT_COLORS[0];
// Renvoie la couleur si elle fait partie de la palette, sinon la couleur par défaut.
function sanitizeColor(value) {
return PROJECT_COLORS.includes(value) ? value : DEFAULT_COLOR;
}
// Une échéance valide est une date RÉELLE au format AAAA-MM-JJ.
// (La seule regex laisserait passer "2026-99-99", que MySQL rejetterait en
// faisant échouer la requête ; on vérifie donc que la date existe vraiment.)
function isValidDueDate(value) {
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
const [y, m, d] = value.split("-").map(Number);
if (y < 1000) return false; // plage minimale du type DATE de MySQL
const date = new Date(Date.UTC(y, m - 1, d));
return date.getUTCFullYear() === y && date.getUTCMonth() === m - 1 && date.getUTCDate() === d;
}
// --- Connexion à la base MySQL -------------------------------------------
// Railway fournit l'URL de connexion via une variable d'environnement.
// On accepte plusieurs noms possibles pour plus de souplesse.
const dbUrl =
process.env.DATABASE_URL ||
process.env.MYSQL_URL ||
process.env.MYSQL_PUBLIC_URL;
if (!dbUrl) {
console.error("Aucune URL de base de données trouvée (DATABASE_URL / MYSQL_URL).");
process.exit(1);
}
const pool = mysql.createPool(dbUrl);
// Indique si une colonne existe déjà dans une table (utilisé par les migrations).
async function columnExists(table, column) {
const [rows] = await pool.query(
`SELECT COLUMN_NAME FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?`,
[table, column]
);
return rows.length > 0;
}
// Crée/complète les tables si besoin. On réessaie quelques fois car la base
// peut mettre quelques secondes à être prête au démarrage.
async function initDb(retries = 10) {
for (let attempt = 1; attempt <= retries; attempt++) {
try {
// 1) Table des projets
await pool.query(`
CREATE TABLE IF NOT EXISTS projects (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
// 2) Table des tâches (créée si absente)
await pool.query(`
CREATE TABLE IF NOT EXISTS tasks (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
done BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
// 3) S'assurer qu'il existe au moins un projet "Général"
// (pour y ranger les tâches existantes).
const [projRows] = await pool.query("SELECT id FROM projects ORDER BY id ASC LIMIT 1");
let defaultProjectId;
if (projRows.length === 0) {
const [r] = await pool.query("INSERT INTO projects (name) VALUES (?)", ["Général"]);
defaultProjectId = r.insertId;
} else {
defaultProjectId = projRows[0].id;
}
// 4) Ajouter la colonne project_id aux tâches si elle n'existe pas encore.
if (!(await columnExists("tasks", "project_id"))) {
await pool.query("ALTER TABLE tasks ADD COLUMN project_id INT NULL");
// Ranger toutes les tâches existantes dans le projet "Général".
await pool.query("UPDATE tasks SET project_id = ? WHERE project_id IS NULL", [defaultProjectId]);
}
// 4 bis) Ajouter la colonne "due_date" (échéance) aux tâches si absente.
// Les tâches existantes restent simplement sans échéance.
if (!(await columnExists("tasks", "due_date"))) {
await pool.query("ALTER TABLE tasks ADD COLUMN due_date DATE NULL");
}
// 4 ter) Ajouter la colonne "color" aux projets si elle n'existe pas encore.
// Les projets existants prennent la couleur par défaut (bleu).
if (!(await columnExists("projects", "color"))) {
await pool.query(
"ALTER TABLE projects ADD COLUMN color VARCHAR(7) NOT NULL DEFAULT ?",
[DEFAULT_COLOR]
);
}
// 5) Table des notes (documents écrits) rattachées à un projet.
await pool.query(`
CREATE TABLE IF NOT EXISTS notes (
id INT AUTO_INCREMENT PRIMARY KEY,
project_id INT NOT NULL,
title VARCHAR(255) NOT NULL,
body MEDIUMTEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
`);
console.log("Base prête : tables 'projects', 'tasks', 'notes' OK.");
return;
} catch (err) {
console.log(`Base pas encore prête (essai ${attempt}/${retries}) : ${err.message}`);
await new Promise((r) => setTimeout(r, 2000));
}
}
throw new Error("Impossible de se connecter à la base après plusieurs essais.");
}
// --- Routes : PROJETS -----------------------------------------------------
// Lister les projets
app.get("/api/projects", async (req, res) => {
const [rows] = await pool.query("SELECT * FROM projects ORDER BY created_at ASC");
res.json(rows);
});
// Créer un projet
app.post("/api/projects", async (req, res) => {
const name = (req.body.name || "").trim();
if (!name) return res.status(400).json({ error: "Le nom du projet est vide." });
const color = sanitizeColor(req.body.color);
const [result] = await pool.query(
"INSERT INTO projects (name, color) VALUES (?, ?)",
[name, color]
);
res.status(201).json({ id: result.insertId, name, color });
});
// Renommer un projet et/ou changer sa couleur
app.patch("/api/projects/:id", async (req, res) => {
const fields = [];
const values = [];
if (req.body.name !== undefined) {
const name = (req.body.name || "").trim();
if (!name) return res.status(400).json({ error: "Le nom du projet est vide." });
fields.push("name = ?");
values.push(name);
}
if (req.body.color !== undefined) {
fields.push("color = ?");
values.push(sanitizeColor(req.body.color));
}
if (fields.length === 0) {
return res.status(400).json({ error: "Rien à mettre à jour." });
}
values.push(req.params.id);
await pool.query(`UPDATE projects SET ${fields.join(", ")} WHERE id = ?`, values);
res.json({ ok: true });
});
// Supprimer un projet (et ses tâches + notes)
app.delete("/api/projects/:id", async (req, res) => {
const { id } = req.params;
await pool.query("DELETE FROM tasks WHERE project_id = ?", [id]);
await pool.query("DELETE FROM notes WHERE project_id = ?", [id]);
await pool.query("DELETE FROM projects WHERE id = ?", [id]);
res.json({ ok: true });
});
// --- Routes : TÂCHES ------------------------------------------------------
// Lister les tâches d'un projet
app.get("/api/tasks", async (req, res) => {
const projectId = req.query.project_id;
if (!projectId) return res.json([]);
// DATE_FORMAT garantit un due_date en texte AAAA-MM-JJ, sans décalage de fuseau.
// Tri : les tâches avec échéance d'abord (la plus proche en premier), puis les autres.
const [rows] = await pool.query(
`SELECT id, title, done, project_id, created_at,
DATE_FORMAT(due_date, '%Y-%m-%d') AS due_date
FROM tasks WHERE project_id = ?
ORDER BY (due_date IS NULL), due_date ASC, created_at DESC`,
[projectId]
);
res.json(rows);
});
// Ajouter une tâche dans un projet (échéance optionnelle)
app.post("/api/tasks", async (req, res) => {
const title = (req.body.title || "").trim();
const projectId = req.body.project_id;
if (!title) return res.status(400).json({ error: "Le titre est vide." });
if (!projectId) return res.status(400).json({ error: "Aucun projet sélectionné." });
let dueDate = null;
if (req.body.due_date) {
if (!isValidDueDate(req.body.due_date)) {
return res.status(400).json({ error: "La date limite est invalide." });
}
dueDate = req.body.due_date;
}
const [result] = await pool.query(
"INSERT INTO tasks (title, project_id, due_date) VALUES (?, ?, ?)",
[title, projectId, dueDate]
);
res.status(201).json({
id: result.insertId, title, done: false, project_id: projectId, due_date: dueDate,
});
});
// Modifier une tâche :
// - corps avec "due_date" → change l'échéance ("" ou null pour l'effacer)
// - sinon → coche/décoche la tâche (comportement historique)
app.patch("/api/tasks/:id", async (req, res) => {
if (req.body && req.body.due_date !== undefined) {
const raw = req.body.due_date;
let dueDate = null;
if (raw !== null && raw !== "") {
if (!isValidDueDate(raw)) {
return res.status(400).json({ error: "La date limite est invalide." });
}
dueDate = raw;
}
await pool.query("UPDATE tasks SET due_date = ? WHERE id = ?", [dueDate, req.params.id]);
return res.json({ ok: true });
}
await pool.query("UPDATE tasks SET done = NOT done WHERE id = ?", [req.params.id]);
res.json({ ok: true });
});
// Supprimer une tâche
app.delete("/api/tasks/:id", async (req, res) => {
await pool.query("DELETE FROM tasks WHERE id = ?", [req.params.id]);
res.json({ ok: true });
});
// --- Routes : NOTES -------------------------------------------------------
// Lister les notes d'un projet
app.get("/api/notes", async (req, res) => {
const projectId = req.query.project_id;
if (!projectId) return res.json([]);
const [rows] = await pool.query(
"SELECT * FROM notes WHERE project_id = ? ORDER BY updated_at DESC",
[projectId]
);
res.json(rows);
});
// Créer une note dans un projet
app.post("/api/notes", async (req, res) => {
const title = (req.body.title || "").trim();
const body = (req.body.body || "").toString();
const projectId = req.body.project_id;
if (!title) return res.status(400).json({ error: "Le titre de la note est vide." });
if (!projectId) return res.status(400).json({ error: "Aucun projet sélectionné." });
const [result] = await pool.query(
"INSERT INTO notes (project_id, title, body) VALUES (?, ?, ?)",
[projectId, title, body]
);
res.status(201).json({ id: result.insertId, project_id: projectId, title, body });
});
// Modifier une note
app.patch("/api/notes/:id", async (req, res) => {
const title = (req.body.title || "").trim();
const body = (req.body.body || "").toString();
if (!title) return res.status(400).json({ error: "Le titre de la note est vide." });
await pool.query("UPDATE notes SET title = ?, body = ? WHERE id = ?", [title, body, req.params.id]);
res.json({ ok: true });
});
// Supprimer une note
app.delete("/api/notes/:id", async (req, res) => {
await pool.query("DELETE FROM notes WHERE id = ?", [req.params.id]);
res.json({ ok: true });
});
// --- Diagnostic (temporaire) ---------------------------------------------
app.get("/__dbcheck", async (req, res) => {
try {
const [r] = await pool.query("SELECT 1 AS ok");
res.json({ db: "ok", result: r });
} catch (e) {
// Le détail complet reste dans les logs serveur ; on ne renvoie au
// navigateur qu'un code d'erreur, pas le message technique brut.
console.error("/__dbcheck :", e);
res.status(500).json({ db: "error", code: e.code });
}
});
// --- Démarrage ------------------------------------------------------------
const port = process.env.PORT || 3000;
// Indique en clair vers quel hôte de base on se connecte (sans le mot de passe).
try {
const u = new URL(dbUrl);
console.log(`Connexion base visée : ${u.hostname}:${u.port || 3306} (db ${u.pathname.slice(1)})`);
} catch {}
// On démarre le serveur web IMMÉDIATEMENT : le conteneur reste en ligne même si la
// base met du temps à être prête (important sur les PaaS type Dokploy/Coolify).
app.listen(port, () => console.log(`Appli en ligne sur le port ${port}`));
// Connexion à la base en arrière-plan, avec de larges réessais (~2 min). On ne quitte
// JAMAIS le process : si la base tarde, les routes répondront en erreur le temps qu'elle
// soit prête, mais le conteneur ne plante pas.
initDb(60).catch((err) =>
console.error("initDb a échoué après plusieurs essais :", err.message)
);