Commit initial : version fonctionnelle du projet

This commit is contained in:
Mouktar Kimba
2025-06-10 05:20:19 +02:00
commit a8acba240b
39 changed files with 7798 additions and 0 deletions

1
.dockerignore Normal file
View File

@ -0,0 +1 @@
node_modules

40
Dockerfile Normal file
View File

@ -0,0 +1,40 @@
FROM node:20 AS base
WORKDIR /usr/local/app
# CLIENT STAGES
FROM base AS client-base
COPY client/package.json client/yarn.lock ./
RUN --mount=type=cache,id=yarn,target=/usr/local/share/.cache/yarn \
yarn install
COPY client/.eslintrc.cjs client/index.html client/vite.config.js ./
COPY client/public ./public
COPY client/src ./src
FROM client-base AS client-dev
CMD ["yarn", "dev"]
FROM client-base AS client-build
RUN yarn build
# BACKEND STAGES
FROM base AS backend-dev
COPY backend/package.json backend/yarn.lock ./
RUN --mount=type=cache,id=yarn,target=/usr/local/share/.cache/yarn \
yarn install --frozen-lockfile
COPY backend/spec ./spec
COPY backend/src ./src
CMD ["yarn", "dev"]
FROM backend-dev AS test
RUN yarn test
# FINAL STAGE
FROM base AS final
ENV NODE_ENV=production
COPY --from=test /usr/local/app/package.json /usr/local/app/yarn.lock ./
RUN --mount=type=cache,id=yarn,target=/usr/local/share/.cache/yarn \
yarn install --production --frozen-lockfile
COPY backend/src ./src
COPY --from=client-build /usr/local/app/dist ./src/static
EXPOSE 3000
CMD ["node", "src/index.js"]

201
LICENSE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2024 Docker, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

92
README.md Normal file
View File

@ -0,0 +1,92 @@
# Gestionnaire de Tâches - Projet Académique
Bienvenue sur mon projet de Gestionnaire de Tâches, une application web moderne et complète développée dans le cadre de mon cursus académique. L'application permet de gérer des tâches quotidiennes de manière simple et intuitive.
Ce projet démontre la mise en place d'une architecture web complète avec un frontend en React, un backend en Node.js, et une base de données MySQL, le tout orchestré dans un environnement de développement professionnel avec Docker.
![Aperçu de l'application](https://i.imgur.com/uG9nB7Q.png)
*NOTE : Je te conseille de faire une vraie capture d'écran de ton application finale et de remplacer le lien ci-dessus.*
---
## ✨ Fonctionnalités
* **Ajout, Modification et Suppression** de tâches.
* **Dates d'échéance** pour chaque tâche.
* Marquer une tâche comme **terminée** et consulter l'historique.
* **Filtres dynamiques** pour afficher les tâches : "Aujourd'hui", "À venir" et "En retard".
* Interface utilisateur **moderne et responsive** avec un fond vidéo animé pour une expérience utilisateur agréable.
---
## 🛠️ Technologies Utilisées
Ce projet a été construit avec les technologies suivantes :
* **Frontend :**
* [React](https://reactjs.org/)
* [Vite](https://vitejs.dev/)
* [Sass](https://sass-lang.com/)
* [React-Bootstrap](https://react-bootstrap.github.io/)
* [date-fns](https://date-fns.org/) pour la manipulation des dates.
* **Backend :**
* [Node.js](https://nodejs.org/)
* [Express.js](https://expressjs.com/)
* **Base de Données :**
* [MySQL](https://www.mysql.com/)
* **Environnement & Déploiement :**
* [Docker](https://www.docker.com/) & [Docker Compose](https://docs.docker.com/compose/)
* [Traefik](https://traefik.io/traefik/) comme reverse proxy.
---
## 🚀 Installation et Lancement
Pour lancer ce projet en local, vous aurez besoin de **Docker Desktop** installé sur votre machine.
1. **Clonez ce dépôt GitHub :**
```bash
# Remplace avec l'URL de TON propre dépôt GitHub
git clone [https://github.com/TonNom/TonRepo.git](https://github.com/TonNom/TonRepo.git)
```
2. **Naviguez dans le dossier du projet :**
```bash
cd TonRepo
```
3. **Construisez et lancez les conteneurs Docker :**
Cette commande va construire les images du backend et du frontend, télécharger MySQL et le proxy, et démarrer tous les services.
```bash
docker-compose up --build
```
La première fois, cela peut prendre quelques minutes.
---
## 🌐 Comment Utiliser l'Application
Une fois les conteneurs démarrés, vous pouvez accéder aux différents services :
* **Application Principale :**
* Ouvrez votre navigateur et allez à l'adresse : **[http://localhost:8000](http://localhost:8000)**
* **Gestion de la Base de Données (phpMyAdmin) :**
* Pour visualiser directement les données dans la base MySQL, allez à : **[http://db.localhost:8000](http://db.localhost:8000)**
* *(Note: Cette adresse est routée par le proxy, d'où le port 8000)*
* **Tableau de Bord du Proxy (Traefik) :**
* Pour voir l'état du routage et des services, allez à : **[http://localhost:8080](http://localhost:8080)**
---
## 🛑 Arrêter l'Application
Pour arrêter tous les services et supprimer les conteneurs, retournez dans votre terminal et lancez la commande :
```bash
docker-compose down
```

40
backend/package.json Normal file
View File

@ -0,0 +1,40 @@
{
"name": "gestionnaire-taches-api",
"version": "1.0.0",
"description": "API backend pour l'application de gestion de tâches.",
"author": "Ton Nom <ton.email@example.com>",
"license": "MIT",
"main": "index.js",
"repository": {
"type": "git",
"url": "https://github.com/TonNom/TonRepo.git"
},
"scripts": {
"format": "prettier -l --write \"**/*.js\"",
"format-check": "prettier --check \"**/*.js\"",
"test": "jest",
"dev": "nodemon src/index.js"
},
"dependencies": {
"express": "^4.18.2",
"mysql2": "^3.9.1",
"sqlite3": "^5.1.7",
"uuid": "^9.0.1",
"wait-port": "^1.1.0"
},
"resolutions": {
"@babel/core": "7.23.9"
},
"prettier": {
"trailingComma": "all",
"tabWidth": 4,
"useTabs": false,
"semi": true,
"singleQuote": true
},
"devDependencies": {
"jest": "^29.7.0",
"nodemon": "^3.0.3",
"prettier": "^3.2.4"
}
}

View File

@ -0,0 +1,65 @@
const db = require('../../src/persistence/sqlite');
const fs = require('fs');
const location = process.env.SQLITE_DB_LOCATION || '/etc/todos/todo.db';
const ITEM = {
id: '7aef3d7c-d301-4846-8358-2a91ec9d6be3',
name: 'Test',
completed: false,
};
beforeEach(() => {
if (fs.existsSync(location)) {
fs.unlinkSync(location);
}
});
test('it initializes correctly', async () => {
await db.init();
});
test('it can store and retrieve items', async () => {
await db.init();
await db.storeItem(ITEM);
const items = await db.getItems();
expect(items.length).toBe(1);
expect(items[0]).toEqual(ITEM);
});
test('it can update an existing item', async () => {
await db.init();
const initialItems = await db.getItems();
expect(initialItems.length).toBe(0);
await db.storeItem(ITEM);
await db.updateItem(
ITEM.id,
Object.assign({}, ITEM, { completed: !ITEM.completed }),
);
const items = await db.getItems();
expect(items.length).toBe(1);
expect(items[0].completed).toBe(!ITEM.completed);
});
test('it can remove an existing item', async () => {
await db.init();
await db.storeItem(ITEM);
await db.removeItem(ITEM.id);
const items = await db.getItems();
expect(items.length).toBe(0);
});
test('it can get a single item', async () => {
await db.init();
await db.storeItem(ITEM);
const item = await db.getItem(ITEM.id);
expect(item).toEqual(ITEM);
});

View File

@ -0,0 +1,30 @@
const db = require('../../src/persistence');
const addItem = require('../../src/routes/addItem');
const ITEM = { id: 12345 };
const { v4: uuid } = require('uuid');
jest.mock('uuid', () => ({ v4: jest.fn() }));
jest.mock('../../src/persistence', () => ({
removeItem: jest.fn(),
storeItem: jest.fn(),
getItem: jest.fn(),
}));
test('it stores item correctly', async () => {
const id = 'something-not-a-uuid';
const name = 'A sample item';
const req = { body: { name } };
const res = { send: jest.fn() };
uuid.mockReturnValue(id);
await addItem(req, res);
const expectedItem = { id, name, completed: false };
expect(db.storeItem.mock.calls.length).toBe(1);
expect(db.storeItem.mock.calls[0][0]).toEqual(expectedItem);
expect(res.send.mock.calls[0].length).toBe(1);
expect(res.send.mock.calls[0][0]).toEqual(expectedItem);
});

View File

@ -0,0 +1,20 @@
const db = require('../../src/persistence');
const deleteItem = require('../../src/routes/deleteItem');
const ITEM = { id: 12345 };
jest.mock('../../src/persistence', () => ({
removeItem: jest.fn(),
getItem: jest.fn(),
}));
test('it removes item correctly', async () => {
const req = { params: { id: 12345 } };
const res = { sendStatus: jest.fn() };
await deleteItem(req, res);
expect(db.removeItem.mock.calls.length).toBe(1);
expect(db.removeItem.mock.calls[0][0]).toBe(req.params.id);
expect(res.sendStatus.mock.calls[0].length).toBe(1);
expect(res.sendStatus.mock.calls[0][0]).toBe(200);
});

View File

@ -0,0 +1,19 @@
const db = require('../../src/persistence');
const getItems = require('../../src/routes/getItems');
const ITEMS = [{ id: 12345 }];
jest.mock('../../src/persistence', () => ({
getItems: jest.fn(),
}));
test('it gets items correctly', async () => {
const req = {};
const res = { send: jest.fn() };
db.getItems.mockReturnValue(Promise.resolve(ITEMS));
await getItems(req, res);
expect(db.getItems.mock.calls.length).toBe(1);
expect(res.send.mock.calls[0].length).toBe(1);
expect(res.send.mock.calls[0][0]).toEqual(ITEMS);
});

View File

@ -0,0 +1,33 @@
const db = require('../../src/persistence');
const updateItem = require('../../src/routes/updateItem');
const ITEM = { id: 12345 };
jest.mock('../../src/persistence', () => ({
getItem: jest.fn(),
updateItem: jest.fn(),
}));
test('it updates items correctly', async () => {
const req = {
params: { id: 1234 },
body: { name: 'New title', completed: false },
};
const res = { send: jest.fn() };
db.getItem.mockReturnValue(Promise.resolve(ITEM));
await updateItem(req, res);
expect(db.updateItem.mock.calls.length).toBe(1);
expect(db.updateItem.mock.calls[0][0]).toBe(req.params.id);
expect(db.updateItem.mock.calls[0][1]).toEqual({
name: 'New title',
completed: false,
});
expect(db.getItem.mock.calls.length).toBe(1);
expect(db.getItem.mock.calls[0][0]).toBe(req.params.id);
expect(res.send.mock.calls[0].length).toBe(1);
expect(res.send.mock.calls[0][0]).toEqual(ITEM);
});

51
backend/src/index.js Normal file
View File

@ -0,0 +1,51 @@
// Fichier: backend/src/index.js
// Point d'entrée principal pour le serveur backend.
// --- Importation des dépendances ---
const express = require('express');
const app = express();
const db = require('./persistence'); // Gestion de la base de données
const getGreeting = require('./routes/getGreeting');
const getItems = require('./routes/getItems');
const addItem = require('./routes/addItem');
const updateItem = require('./routes/updateItem');
const deleteItem = require('./routes/deleteItem');
// --- Middleware ---
// Permet au serveur de comprendre les requêtes JSON
app.use(express.json());
// Sert les fichiers statiques (si vous en avez, par exemple une version buildée du client)
app.use(express.static(__dirname + '/static'));
// --- Définition des Routes de l'API ---
// Chaque route est associée à une fonction spécifique.
app.get('/api/greeting', getGreeting); // Route pour un message d'accueil
app.get('/api/items', getItems); // Route pour obtenir toutes les tâches
app.post('/api/items', addItem); // Route pour ajouter une nouvelle tâche
app.put('/api/items/:id', updateItem); // Route pour mettre à jour une tâche existante
app.delete('/api/items/:id', deleteItem); // Route pour supprimer une tâche
// --- Démarrage du serveur ---
// Initialise la base de données, puis démarre le serveur Express.
db.init()
.then(() => {
app.listen(3000, () => console.log('Serveur démarré et à l\'écoute sur le port 3000'));
})
.catch((err) => {
console.error("Erreur lors de l'initialisation de la base de données:", err);
process.exit(1); // Quitte l'application en cas d'erreur critique
});
// --- Gestion de la fermeture propre de l'application ---
// Cette fonction s'assure que la connexion à la base de données est bien fermée
// lorsque le processus Node.js est arrêté.
const gracefulShutdown = () => {
db.teardown()
.catch(() => {})
.then(() => process.exit());
};
// Écoute les signaux d'arrêt du système
process.on('SIGINT', gracefulShutdown); // Ctrl+C
process.on('SIGTERM', gracefulShutdown); // Signal d'arrêt standard
process.on('SIGUSR2', gracefulShutdown); // Signal utilisé par nodemon pour le redémarrage

View File

@ -0,0 +1,2 @@
if (process.env.MYSQL_HOST) module.exports = require('./mysql');
else module.exports = require('./sqlite');

View File

@ -0,0 +1,108 @@
const waitPort = require('wait-port');
const fs = require('fs');
const mysql = require('mysql2');
const {
MYSQL_HOST: HOST,
MYSQL_HOST_FILE: HOST_FILE,
MYSQL_USER: USER,
MYSQL_USER_FILE: USER_FILE,
MYSQL_PASSWORD: PASSWORD,
MYSQL_PASSWORD_FILE: PASSWORD_FILE,
MYSQL_DB: DB,
MYSQL_DB_FILE: DB_FILE,
} = process.env;
let pool;
async function init() {
const host = HOST_FILE ? fs.readFileSync(HOST_FILE) : HOST;
const user = USER_FILE ? fs.readFileSync(USER_FILE) : USER;
const password = PASSWORD_FILE ? fs.readFileSync(PASSWORD_FILE) : PASSWORD;
const database = DB_FILE ? fs.readFileSync(DB_FILE) : DB;
await waitPort({
host,
port: 3306,
timeout: 10000,
waitForDns: true,
});
pool = mysql.createPool({
connectionLimit: 5,
host,
user,
password,
database,
charset: 'utf8mb4',
}).promise(); // On utilise les promesses pour un code plus propre
// MODIFIÉ : Ajout de la colonne "dueDate" de type DATE
const createTableSql = `
CREATE TABLE IF NOT EXISTS todo_items (
id varchar(36),
name varchar(255),
completed boolean,
dueDate DATE,
PRIMARY KEY (id)
) DEFAULT CHARSET utf8mb4
`;
try {
await pool.query(createTableSql);
console.log(`Connected to mysql db at host ${HOST}`);
} catch (err) {
throw new Error(err);
}
}
async function teardown() {
await pool.end();
}
async function getItems() {
const [rows] = await pool.query('SELECT * FROM todo_items');
return rows.map((item) =>
Object.assign({}, item, {
completed: item.completed === 1,
}),
);
}
async function getItem(id) {
const [rows] = await pool.query('SELECT * FROM todo_items WHERE id=?', [id]);
if (rows.length === 0) return null;
return Object.assign({}, rows[0], {
completed: rows[0].completed === 1,
});
}
async function storeItem(item) {
// MODIFIÉ : Ajout de la colonne "dueDate" dans l'insertion
await pool.query(
'INSERT INTO todo_items (id, name, completed, dueDate) VALUES (?, ?, ?, ?)',
[item.id, item.name, item.completed ? 1 : 0, item.dueDate],
);
}
async function updateItem(id, item) {
// MODIFIÉ : Ajout de "dueDate" dans la mise à jour
await pool.query(
'UPDATE todo_items SET name=?, completed=?, dueDate=? WHERE id=?',
[item.name, item.completed ? 1 : 0, item.dueDate, id],
);
}
async function removeItem(id) {
await pool.query('DELETE FROM todo_items WHERE id = ?', [id]);
}
module.exports = {
init,
teardown,
getItems,
getItem,
storeItem,
updateItem,
removeItem,
};

View File

@ -0,0 +1,124 @@
const sqlite3 = require('sqlite3').verbose();
const fs = require('fs');
const location = process.env.SQLITE_DB_LOCATION || '/etc/todos/todo.db';
let db;
function init() {
const dirName = require('path').dirname(location);
if (!fs.existsSync(dirName)) {
fs.mkdirSync(dirName, { recursive: true });
}
return new Promise((acc, rej) => {
db = new sqlite3.Database(location, (err) => {
if (err) return rej(err);
if (process.env.NODE_ENV !== 'test')
console.log(`Using sqlite database at ${location}`);
// MODIFIÉ : Ajout de la colonne "dueDate" de type DATE
const createTableSql = `
CREATE TABLE IF NOT EXISTS todo_items (
id varchar(36),
name varchar(255),
completed boolean,
"dueDate" DATE
)
`;
db.run(createTableSql, (err) => {
if (err) return rej(err);
acc();
});
});
});
}
async function teardown() {
return new Promise((acc, rej) => {
db.close((err) => {
if (err) rej(err);
else acc();
});
});
}
async function getItems() {
return new Promise((acc, rej) => {
db.all('SELECT * FROM todo_items', (err, rows) => {
if (err) return rej(err);
acc(
rows.map((item) =>
Object.assign({}, item, {
completed: item.completed === 1,
}),
),
);
});
});
}
async function getItem(id) {
return new Promise((acc, rej) => {
db.all('SELECT * FROM todo_items WHERE id=?', [id], (err, rows) => {
if (err) return rej(err);
acc(
rows.map((item) =>
Object.assign({}, item, {
completed: item.completed === 1,
}),
)[0],
);
});
});
}
async function storeItem(item) {
return new Promise((acc, rej) => {
// MODIFIÉ : Ajout de la colonne "dueDate" dans l'insertion
db.run(
'INSERT INTO todo_items (id, name, completed, "dueDate") VALUES (?, ?, ?, ?)',
// MODIFIÉ : Ajout de item.dueDate aux valeurs
[item.id, item.name, item.completed ? 1 : 0, item.dueDate],
(err) => {
if (err) return rej(err);
acc();
},
);
});
}
async function updateItem(id, item) {
return new Promise((acc, rej) => {
// MODIFIÉ : Ajout de "dueDate" dans la mise à jour
db.run(
'UPDATE todo_items SET name=?, completed=?, "dueDate"=? WHERE id = ?',
// MODIFIÉ : Ajout de item.dueDate aux valeurs
[item.name, item.completed ? 1 : 0, item.dueDate, id],
(err) => {
if (err) return rej(err);
acc();
},
);
});
}
async function removeItem(id) {
return new Promise((acc, rej) => {
db.run('DELETE FROM todo_items WHERE id = ?', [id], (err) => {
if (err) return rej(err);
acc();
});
});
}
module.exports = {
init,
teardown,
getItems,
getItem,
storeItem,
updateItem,
removeItem,
};

View File

@ -0,0 +1,22 @@
const db = require('../persistence');
const { v4: uuid } = require('uuid');
module.exports = async (req, res) => {
// MODIFIÉ : On récupère 'name' et 'dueDate' du corps de la requête
const { name, dueDate } = req.body;
// Ajout d'une petite validation
if (!name || !dueDate) {
return res.status(400).send({ error: 'Le nom et la date d\'échéance sont requis.' });
}
const item = {
id: uuid(),
name: name,
completed: false,
dueDate: dueDate, // MODIFIÉ : On ajoute la date d'échéance à l'objet
};
await db.storeItem(item);
res.status(201).send(item); // On utilise 201 Created pour un ajout réussi
};

View File

@ -0,0 +1,6 @@
const db = require('../persistence');
module.exports = async (req, res) => {
await db.removeItem(req.params.id);
res.sendStatus(200);
};

View File

@ -0,0 +1,7 @@
const GREETING = 'Hello world!';
module.exports = async (req, res) => {
res.send({
greeting: GREETING,
});
};

View File

@ -0,0 +1,6 @@
const db = require('../persistence');
module.exports = async (req, res) => {
const items = await db.getItems();
res.send(items);
};

View File

@ -0,0 +1,26 @@
const db = require('../persistence');
module.exports = async (req, res) => {
// ÉTAPE 1 : Récupérer la tâche actuelle pour avoir ses valeurs par défaut
const currentItem = await db.getItem(req.params.id);
if (!currentItem) {
return res.status(404).send({ error: 'Tâche non trouvée.' });
}
// ÉTAPE 2 : Créer l'objet mis à jour.
// On utilise les nouvelles valeurs si elles existent dans la requête,
// sinon on garde les anciennes valeurs de 'currentItem'.
const updatedItem = {
name: req.body.name !== undefined ? req.body.name : currentItem.name,
completed: req.body.completed !== undefined ? req.body.completed : currentItem.completed,
dueDate: req.body.dueDate !== undefined ? req.body.dueDate : currentItem.dueDate,
};
// ÉTAPE 3 : Sauvegarder l'objet complet en base de données
await db.updateItem(req.params.id, updatedItem);
// ÉTAPE 4 : Renvoyer la tâche mise à jour au client
const item = await db.getItem(req.params.id);
res.send(item);
};

View File

3492
backend/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

20
client/.eslintrc.cjs Normal file
View File

@ -0,0 +1,20 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:react/jsx-runtime',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parserOptions: { ecmaVersion: 'latest', sourceType: 'module' },
settings: { react: { version: '18.2' } },
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
};

24
client/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

18
client/index.html Normal file
View File

@ -0,0 +1,18 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Une application simple de gestion de tâches pour un projet académique." />
<link
href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap"
rel="stylesheet"
/>
<title>Gestionnaire de Tâches</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

53
client/package.json Normal file
View File

@ -0,0 +1,53 @@
{
"name": "gestionnaire-taches-ui",
"private": true,
"version": "1.0.0",
"description": "Interface utilisateur pour l'application de gestion de tâches.",
"author": "Ton Nom <ton.email@example.com>",
"license": "MIT",
"type": "module",
"repository": {
"type": "git",
"url": "https://github.com/TonNom/TonRepo.git"
},
"scripts": {
"dev": "vite --host=0.0.0.0",
"build": "vite build",
"lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview",
"format": "prettier --write \"**/*.jsx\"",
"format-check": "prettier --check \"**/*.js\""
},
"dependencies": {
"@fortawesome/fontawesome-free-regular": "^5.0.13",
"@fortawesome/fontawesome-svg-core": "^6.5.1",
"@fortawesome/free-regular-svg-icons": "^6.7.2",
"@fortawesome/free-solid-svg-icons": "^6.7.2",
"@fortawesome/react-fontawesome": "^0.2.2",
"bootstrap": "^5.3.6",
"date-fns": "^4.1.0",
"react": "^18.2.0",
"react-bootstrap": "^2.10.0",
"react-dom": "^18.2.0",
"sass": "^1.70.0",
"sweetalert2": "^11.6.13"
},
"devDependencies": {
"@types/react": "^18.2.43",
"@types/react-dom": "^18.2.17",
"@vitejs/plugin-react": "^4.2.1",
"eslint": "^8.57.1",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.5",
"prettier": "^3.2.4",
"vite": "^6.3.5"
},
"prettier": {
"trailingComma": "all",
"tabWidth": 4,
"useTabs": false,
"semi": true,
"singleQuote": true
}
}

1
client/public/vite.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

39
client/src/App.jsx Normal file
View File

@ -0,0 +1,39 @@
// Fichier: client/src/App.jsx
import React from 'react';
import { CarteTaches } from './components/CarteTaches';
// On définit les URLs directement comme des constantes.
const imageUrl = 'https://images.unsplash.com/photo-1686934674798-2e390dc94019?fm=jpg&q=60&w=3000&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1yZWxhdGVkfDE0fHx8ZW58MHx8fHx8';
const videoUrl = 'https://videos.pexels.com/video-files/4782135/4782135-hd_1920_1080_25fps.mp4';
// Le composant pour le fond vidéo
function VideoBackground() {
return (
<div className="video-background">
{/* CORRECTION : playsinline est devenu playsInline */}
<video autoPlay muted loop playsInline src={videoUrl}>
Votre navigateur ne supporte pas les vidéos.
</video>
</div>
);
}
function App() {
return (
<div>
<VideoBackground />
{/* On applique l'image de fond via un style inline en utilisant notre constante */}
<header className="app-header" style={{ backgroundImage: `url(${imageUrl})` }}>
<h1>Gestionnaire de Tâches</h1>
</header>
<main className="main-content">
<CarteTaches />
</main>
</div>
);
}
export default App;

View File

@ -0,0 +1,65 @@
// Fichier: client/src/components/AffichageTache.jsx
import PropTypes from 'prop-types';
import { Form } from 'react-bootstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
// On importe l'icône de la poubelle
import { faClock, faPenToSquare, faTrash } from '@fortawesome/free-solid-svg-icons';
import { format, isPast, isToday } from 'date-fns';
import { fr } from 'date-fns/locale';
import './AffichageTache.scss';
export function AffichageTache({ tache, onToggle, onSuppression, onEdit }) {
const estEnRetard = !tache.completed && tache.dueDate && isPast(new Date(tache.dueDate)) && !isToday(new Date(tache.dueDate));
let statusClass = 'pending';
if (estEnRetard) {
statusClass = 'overdue';
}
const handleDeleteClick = (e) => {
e.stopPropagation();
onSuppression(tache.id);
};
return (
<div className={`tache-item-wrapper ${tache.completed ? 'complete' : ''}`}>
<Form.Check
type="checkbox"
checked={tache.completed}
onChange={() => onToggle(tache)}
aria-label={`Marquer ${tache.name} comme ${tache.completed ? 'incomplète' : 'complétée'}`}
/>
<div className="tache-details">
<span className="tache-nom">{tache.name}</span>
{tache.dueDate && (
<span className="tache-date">
<FontAwesomeIcon icon={faClock} />
{format(new Date(tache.dueDate), 'd MMM yy', { locale: fr })}
</span>
)}
</div>
<div className="tache-actions">
<button className="action-btn edit-btn" aria-label="Modifier la tâche" onClick={() => onEdit(tache)}>
<FontAwesomeIcon icon={faPenToSquare} />
</button>
{/* On remplace l'indicateur par un bouton avec une icône */}
<button className="action-btn delete-btn" aria-label="Supprimer la tâche" onClick={handleDeleteClick}>
<FontAwesomeIcon icon={faTrash} />
</button>
</div>
</div>
);
}
AffichageTache.propTypes = {
tache: PropTypes.shape({
id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
completed: PropTypes.bool.isRequired,
dueDate: PropTypes.string,
}).isRequired,
onToggle: PropTypes.func.isRequired,
onSuppression: PropTypes.func.isRequired,
onEdit: PropTypes.func.isRequired,
};

View File

@ -0,0 +1,74 @@
// Fichier: client/src/components/AffichageTache.scss
.tache-item-wrapper {
display: flex;
align-items: center;
gap: 1rem;
padding: 1rem 0;
border-bottom: 1px solid var(--couleur-bordure);
transition: background-color 0.2s ease-in-out;
&:last-child {
border-bottom: none;
}
.form-check-input {
cursor: pointer;
}
.tache-details {
flex-grow: 1;
display: flex;
justify-content: space-between;
align-items: center;
gap: 1rem;
}
.tache-nom {
font-weight: 500;
color: var(--couleur-texte-principal);
}
.tache-date {
font-size: 0.875rem;
color: var(--couleur-texte-secondaire);
display: flex;
align-items: center;
gap: 0.5rem;
flex-shrink: 0;
}
.tache-actions {
display: flex;
align-items: center;
gap: 0.75rem;
}
.action-btn {
background: none;
border: none;
color: var(--couleur-texte-secondaire);
cursor: pointer;
padding: 0.25rem;
font-size: 0.9rem;
transition: color 0.2s ease-in-out;
&:hover {
color: var(--couleur-theme-vert);
}
}
// Style spécifique pour le bouton supprimer
.delete-btn {
&:hover {
color: var(--couleur-danger); // Devient rouge au survol
}
}
&.complete {
.tache-nom, .tache-date {
text-decoration: line-through;
opacity: 0.6;
}
}
}

View File

@ -0,0 +1,184 @@
// Fichier: client/src/components/CarteTaches.jsx
import { useCallback, useEffect, useState, useMemo } from 'react';
import { Button, Modal, Form, Spinner, Alert } from 'react-bootstrap';
import { isToday, isFuture, isPast, startOfDay, format } from 'date-fns';
import { fr } from 'date-fns/locale';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faChevronDown } from '@fortawesome/free-solid-svg-icons';
import { AffichageTache } from './AffichageTache';
import './CarteTaches.scss';
export function CarteTaches() {
const [taches, setTaches] = useState([]);
const [chargement, setChargement] = useState(true);
const [erreur, setErreur] = useState('');
const [showModal, setShowModal] = useState(false);
const [editingTask, setEditingTask] = useState(null);
const [activeFilter, setActiveFilter] = useState("Aujourd'hui");
const [completedVisible, setCompletedVisible] = useState(true);
const filtresTraduits = {
"Aujourd'hui": "Aujourd'hui",
"À venir": "À venir",
"En retard": "En retard"
};
useEffect(() => {
fetch('/api/items')
.then(res => res.ok ? res.json() : Promise.reject(res))
.then(data => setTaches(data.sort((a, b) => new Date(a.dueDate) - new Date(b.dueDate))))
.catch(() => setErreur("Impossible de charger les tâches. Le serveur est peut-être indisponible."))
.finally(() => setChargement(false));
}, []);
const listesDeTaches = useMemo(() => {
const tachesEnCours = taches.filter(t => !t.completed);
const filtres = {
"Aujourd'hui": tachesEnCours.filter(t => t.dueDate && isToday(new Date(t.dueDate))),
"À venir": tachesEnCours.filter(t => t.dueDate && isFuture(new Date(t.dueDate))),
"En retard": tachesEnCours.filter(t => t.dueDate && isPast(new Date(t.dueDate)) && !isToday(new Date(t.dueDate)))
};
return {
tachesAffichees: filtres[activeFilter] || [],
tachesTerminees: taches.filter(t => t.completed)
};
}, [taches, activeFilter]);
const handleOpenAddModal = () => {
setEditingTask(null);
setShowModal(true);
};
const handleOpenEditModal = (tache) => {
setEditingTask(tache);
setShowModal(true);
};
const handleCloseModal = () => {
setShowModal(false);
setEditingTask(null);
};
const handleToggle = useCallback((tacheToToggle) => {
fetch(`/api/items/${tacheToToggle.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ completed: !tacheToToggle.completed })
})
.then(res => res.json())
.then(updatedTask => {
setTaches(current => current.map(t => (t.id === updatedTask.id ? updatedTask : t)));
}).catch(err => console.error("Erreur de mise à jour:", err));
}, []);
const handleDelete = useCallback((idToDelete) => {
if (window.confirm("Êtes-vous sûr de vouloir supprimer cette tâche ?")) {
fetch(`/api/items/${idToDelete}`, { method: 'DELETE' })
.then(res => {
if (res.ok) {
setTaches(current => current.filter(t => t.id !== idToDelete));
} else {
alert("Erreur lors de la suppression.");
}
}).catch(err => console.error("Erreur de suppression:", err));
}
}, []);
const handleFormSubmit = (event) => {
event.preventDefault();
const name = event.target.elements.taskName.value;
const dueDate = event.target.elements.taskDueDate.value;
const taskData = { name, dueDate };
if (editingTask) {
fetch(`/api/items/${editingTask.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(taskData)
})
.then(res => res.json())
.then(updatedTask => {
setTaches(current => current.map(t => (t.id === updatedTask.id ? updatedTask : t)));
handleCloseModal();
}).catch(console.error);
} else {
fetch('/api/items', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(taskData)
})
.then(res => res.json())
.then(newTask => {
setTaches(current => [...current, newTask].sort((a, b) => new Date(a.dueDate) - new Date(b.dueDate)));
handleCloseModal();
}).catch(console.error);
}
};
return (
<>
<div className="tasks-header">
<h2>Tâches</h2>
<Button onClick={handleOpenAddModal} className="add-task-btn">
Ajouter une tâche
</Button>
</div>
<div className="filter-tabs">
{Object.keys(filtresTraduits).map(filter => (
<button
key={filter}
className={`filter-btn ${activeFilter === filter ? 'active' : ''}`}
onClick={() => setActiveFilter(filter)}>
{filtresTraduits[filter]}
</button>
))}
</div>
<div className="tasks-list">
{chargement && <Spinner animation="border" />}
{erreur && <Alert variant="danger">{erreur}</Alert>}
{!chargement && !erreur && listesDeTaches.tachesAffichees.length === 0 && (
<p className="empty-list-message">Aucune tâche pour "{filtresTraduits[activeFilter]}".</p>
)}
{listesDeTaches.tachesAffichees.map(tache => (
<AffichageTache key={tache.id} tache={tache} onToggle={handleToggle} onSuppression={handleDelete} onEdit={handleOpenEditModal} />
))}
</div>
<div className="completed-section-header" onClick={() => setCompletedVisible(!completedVisible)}>
<h3>Terminé</h3>
<FontAwesomeIcon icon={faChevronDown} className={`chevron-icon ${completedVisible ? 'open' : ''}`} />
</div>
{completedVisible && (
<div className="tasks-list completed-list">
{listesDeTaches.tachesTerminees.length === 0 && <p className="empty-list-message">Aucune tâche terminée.</p>}
{listesDeTaches.tachesTerminees.map(tache => (
<AffichageTache key={tache.id} tache={tache} onToggle={handleToggle} onSuppression={handleDelete} onEdit={handleOpenEditModal} />
))}
</div>
)}
<Modal show={showModal} onHide={handleCloseModal} centered>
<Modal.Header closeButton>
<Modal.Title>
{editingTask ? "Modifier la tâche" : "Ajouter une nouvelle tâche"}
</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form onSubmit={handleFormSubmit}>
<Form.Group className="mb-3" controlId="taskName">
<Form.Label>Nom de la tâche</Form.Label>
<Form.Control type="text" placeholder="Ex: Sortir les poubelles" required defaultValue={editingTask ? editingTask.name : ''} />
</Form.Group>
<Form.Group className="mb-3" controlId="taskDueDate">
<Form.Label>Date d'échéance</Form.Label>
<Form.Control type="date" required defaultValue={editingTask ? format(new Date(editingTask.dueDate), 'yyyy-MM-dd') : format(new Date(), 'yyyy-MM-dd')} />
</Form.Group>
<Button variant="success" type="submit" className="w-100">
{editingTask ? "Enregistrer les modifications" : "Enregistrer la tâche"}
</Button>
</Form>
</Modal.Body>
</Modal>
</>
);
}

View File

@ -0,0 +1,89 @@
// Fichier: client/src/components/CarteTaches.scss
.tasks-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1.5rem;
h2 {
margin: 0;
font-weight: 600;
}
.add-task-btn {
background-color: var(--couleur-theme-vert);
border-color: var(--couleur-theme-vert);
font-weight: 500;
}
}
.filter-tabs {
display: flex;
gap: 0.75rem;
margin-bottom: 1.5rem;
border-bottom: 1px solid var(--couleur-bordure);
}
.filter-btn {
background: none;
border: none;
padding: 0.75rem 0.5rem;
font-size: 1rem;
font-weight: 500;
color: var(--couleur-texte-secondaire);
cursor: pointer;
position: relative;
transition: color 0.2s ease-in-out;
&::after {
content: '';
position: absolute;
bottom: -1px;
left: 0;
width: 100%;
height: 3px;
background-color: var(--couleur-theme-vert);
transform: scaleX(0);
transition: transform 0.3s ease;
}
&:hover {
color: var(--couleur-texte-principal);
}
&.active {
color: var(--couleur-theme-vert);
&::after {
transform: scaleX(1);
}
}
}
.completed-section-header {
display: flex;
justify-content: space-between;
align-items: center;
cursor: pointer;
margin-top: 2rem;
padding: 0.5rem 0;
h3 {
font-size: 1.1rem;
font-weight: 600;
margin: 0;
}
.chevron-icon {
transition: transform 0.3s ease;
&.open {
transform: rotate(180deg);
}
}
}
.empty-list-message {
padding: 2rem;
text-align: center;
color: var(--couleur-texte-secondaire);
}

View File

@ -0,0 +1,71 @@
// Fichier: client/src/components/FormulaireAjout.jsx
// Gère le formulaire pour ajouter une nouvelle tâche.
import { useState } from 'react';
import PropTypes from 'prop-types';
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';
import InputGroup from 'react-bootstrap/InputGroup';
export function FormulaireAjout({ onNouvelleTache }) {
const [nouvelleTache, setNouvelleTache] = useState('');
const [envoiEnCours, setEnvoiEnCours] = useState(false);
const [erreur, setErreur] = useState('');
const soumettreNouvelleTache = (e) => {
e.preventDefault();
setEnvoiEnCours(true);
setErreur(''); // Réinitialise l'erreur à chaque soumission
const options = {
method: 'POST',
body: JSON.stringify({ name: nouvelleTache }),
headers: { 'Content-Type': 'application/json' },
};
fetch('/api/items', options)
.then((res) => {
if (!res.ok) {
throw new Error('La requête a échoué');
}
return res.json();
})
.then((tache) => {
onNouvelleTache(tache);
setNouvelleTache(''); // Vide le champ après succès
})
.catch(() => {
setErreur("Impossible d'ajouter la tâche. Veuillez réessayer.");
})
.finally(() => {
setEnvoiEnCours(false);
});
};
return (
<Form onSubmit={soumettreNouvelleTache}>
<InputGroup className="mb-3">
<Form.Control
value={nouvelleTache}
onChange={(e) => setNouvelleTache(e.target.value)}
type="text"
placeholder="Entrez une nouvelle tâche..."
aria-label="Entrez une nouvelle tâche"
required
/>
<Button
type="submit"
variant="primary"
disabled={!nouvelleTache.length || envoiEnCours}
>
{envoiEnCours ? 'Ajout...' : 'Ajouter Tâche'}
</Button>
</InputGroup>
{erreur && <p className="text-danger small mt-1">{erreur}</p>}
</Form>
);
}
FormulaireAjout.propTypes = {
onNouvelleTache: PropTypes.func.isRequired,
};

View File

@ -0,0 +1,19 @@
// Fichier: client/src/components/MessageAccueil.jsx
// Affiche un message de bienvenue dynamique récupéré depuis le backend.
import { useEffect, useState } from 'react';
export function MessageAccueil() {
const [message, setMessage] = useState('');
useEffect(() => {
fetch('/api/greeting')
.then((res) => res.json())
.then((data) => setMessage(data.greeting))
.catch(() => setMessage('Bienvenue !')); // Message par défaut en cas d'erreur
}, []); // Le tableau vide signifie que cet effet ne s'exécute qu'une fois
if (!message) return null;
return <p className="lead text-muted">{message}</p>;
}

View File

@ -0,0 +1,21 @@
import React from 'react';
import Navbar from 'react-bootstrap/Navbar';
import Nav from 'react-bootstrap/Nav';
export default function NavbarComponent() {
return (
<Navbar bg="dark" variant="dark" expand="lg">
<Navbar.Brand href="#home" className="ms-3">
Gestionnaire de Tâches Pro
</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="me-auto ms-3">
<Nav.Link href="#home">Accueil</Nav.Link>
<Nav.Link href="#features">Fonctionnalités</Nav.Link>
<Nav.Link href="#about">À Propos</Nav.Link>
</Nav>
</Navbar.Collapse>
</Navbar>
);
}

70
client/src/index.scss Normal file
View File

@ -0,0 +1,70 @@
// Fichier: client/src/index.scss
@use 'bootstrap/scss/bootstrap-grid';
@use 'bootstrap/scss/bootstrap-reboot';
:root {
--couleur-fond-page: #eef2f7;
--couleur-carte: #f8fafc; // Fond de carte moderne
--couleur-texte-principal: #1e293b;
--couleur-texte-secondaire: #64748b;
--couleur-theme-vert: #166534;
--couleur-theme-vert-clair: #22c55e;
--couleur-danger: #ef4444;
--couleur-warning: #f59e0b;
--couleur-bordure: #e2e8f0;
--bordure-radius: 12px;
--header-height: 180px;
}
.video-background {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: -1;
}
.video-background video {
width: 100%;
height: 100%;
object-fit: cover;
opacity: 0.07;
}
body {
background-color: var(--couleur-fond-page);
font-family: 'Poppins', sans-serif;
color: var(--couleur-texte-principal);
}
.app-header {
height: var(--header-height);
// L'image est maintenant appliquée via un style inline dans App.jsx
background-size: cover;
background-position: center;
display: flex;
align-items: center;
justify-content: center;
color: white;
text-shadow: 2px 2px 8px rgba(0, 0, 0, 0.6);
}
.app-header h1 {
font-size: 3.5rem;
font-weight: 600;
letter-spacing: 1.5px;
}
.main-content {
max-width: 900px;
margin: -60px auto 50px auto;
background-color: var(--couleur-carte);
border-radius: var(--bordure-radius);
box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.1);
position: relative;
z-index: 1;
min-height: 400px;
padding: 2rem;
}

18
client/src/main.jsx Normal file
View File

@ -0,0 +1,18 @@
// Fichier: client/src/main.jsx
// Point d'entrée de l'application React.
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.jsx';
// NOUVEAU : Importation du CSS de Bootstrap pour styliser les composants
import 'bootstrap/dist/css/bootstrap.min.css';
import './index.scss'; // Importation de nos styles globaux personnalisés
// Rendu du composant principal "App" dans l'élément HTML avec l'ID "root".
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);

7
client/vite.config.js Normal file
View File

@ -0,0 +1,7 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
});

2568
client/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

72
compose.yml Normal file
View File

@ -0,0 +1,72 @@
services:
proxy:
image: traefik:v2.11
command:
- --api.insecure=true
- --providers.docker
ports:
- "8000:80"
- "8080:8080"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
labels:
- "traefik.http.routers.dashboard.rule=Host(`localhost`) && PathPrefix(`/dashboard`)"
backend:
build:
context: ./
target: backend-dev
environment:
MYSQL_HOST: mysql
MYSQL_USER: root
MYSQL_PASSWORD: secret
MYSQL_DB: todos
develop:
watch:
- path: ./backend/src
action: sync
target: /usr/local/app/src
- path: ./backend/package.json
action: rebuild
labels:
traefik.http.routers.backend.rule: Host(`localhost`) && PathPrefix(`/api`)
traefik.http.services.backend.loadbalancer.server.port: 3000
client:
build:
context: ./
target: client-dev
volumes:
- ./client:/usr/local/app
- /usr/local/app/node_modules
develop:
watch:
- path: ./client/src
action: sync
target: /usr/local/app/src
- path: ./client/package.json
action: rebuild
labels:
traefik.http.routers.client.rule: Host(`localhost`)
traefik.http.services.client.loadbalancer.server.port: 5173
mysql:
image: mysql:8.0
volumes:
- todo-mysql-data:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: secret
MYSQL_DATABASE: todos
phpmyadmin:
image: phpmyadmin
environment:
PMA_HOST: mysql
PMA_USER: root
PMA_PASSWORD: secret
labels:
traefik.http.routers.phpmyadmin.rule: Host(`db.localhost`)
traefik.http.services.phpmyadmin.loadbalancer.server.port: 80
volumes:
todo-mysql-data: