chore: prettier everywhere
This commit is contained in:
32
BACKUP.md
32
BACKUP.md
@@ -70,12 +70,14 @@ BACKUP_STORAGE_PATH="/var/backups/towercontrol" npm run backup:create
|
||||
### Interface graphique
|
||||
|
||||
#### Paramètres Avancés
|
||||
|
||||
- **Visualisation** du statut en temps réel
|
||||
- **Création manuelle** de sauvegardes
|
||||
- **Vérification** de l'intégrité
|
||||
- **Lien** vers la gestion complète
|
||||
|
||||
#### Page de gestion complète
|
||||
|
||||
- **Configuration** détaillée du système
|
||||
- **Liste** de toutes les sauvegardes
|
||||
- **Actions** (supprimer, restaurer)
|
||||
@@ -153,6 +155,7 @@ Par défaut : `./backups/` (relatif au dossier du projet)
|
||||
### Métadonnées
|
||||
|
||||
Chaque sauvegarde contient :
|
||||
|
||||
- **Horodatage** précis de création
|
||||
- **Taille** du fichier
|
||||
- **Type** (manuelle ou automatique)
|
||||
@@ -172,11 +175,13 @@ Chaque sauvegarde contient :
|
||||
### Procédure
|
||||
|
||||
#### Via interface (développement uniquement)
|
||||
|
||||
1. Aller dans la gestion des sauvegardes
|
||||
2. Cliquer sur **"Restaurer"** à côté du fichier souhaité
|
||||
3. Confirmer l'action
|
||||
|
||||
#### Via CLI
|
||||
|
||||
```bash
|
||||
# Restaurer avec confirmation
|
||||
tsx scripts/backup-manager.ts restore towercontrol_2025-01-15T10-30-00-000Z.db.gz
|
||||
@@ -236,6 +241,7 @@ Les opérations de sauvegarde sont loggées dans la console de l'application.
|
||||
### Problèmes courants
|
||||
|
||||
#### Erreur "sqlite3 command not found"
|
||||
|
||||
```bash
|
||||
# Sur macOS
|
||||
brew install sqlite
|
||||
@@ -245,6 +251,7 @@ sudo apt-get install sqlite3
|
||||
```
|
||||
|
||||
#### Permissions insuffisantes
|
||||
|
||||
```bash
|
||||
# Vérifier les permissions du dossier de sauvegarde
|
||||
ls -la backups/
|
||||
@@ -254,6 +261,7 @@ chmod 755 backups/
|
||||
```
|
||||
|
||||
#### Espace disque insuffisant
|
||||
|
||||
```bash
|
||||
# Vérifier l'espace disponible
|
||||
df -h
|
||||
@@ -268,9 +276,11 @@ tsx scripts/backup-manager.ts delete <filename>
|
||||
Pour activer le debug détaillé, modifier `services/database.ts` :
|
||||
|
||||
```typescript
|
||||
export const prisma = globalThis.__prisma || new PrismaClient({
|
||||
log: ['query', 'info', 'warn', 'error'], // Debug activé
|
||||
});
|
||||
export const prisma =
|
||||
globalThis.__prisma ||
|
||||
new PrismaClient({
|
||||
log: ['query', 'info', 'warn', 'error'], // Debug activé
|
||||
});
|
||||
```
|
||||
|
||||
## Sécurité
|
||||
@@ -298,18 +308,19 @@ En environnement Docker, tout est centralisé dans le dossier `data/` :
|
||||
```yaml
|
||||
# docker-compose.yml
|
||||
environment:
|
||||
DATABASE_URL: "file:./data/prod.db" # Base de données Prisma
|
||||
BACKUP_DATABASE_PATH: "./data/prod.db" # Base à sauvegarder
|
||||
BACKUP_STORAGE_PATH: "./data/backups" # Dossier des sauvegardes
|
||||
DATABASE_URL: 'file:./data/prod.db' # Base de données Prisma
|
||||
BACKUP_DATABASE_PATH: './data/prod.db' # Base à sauvegarder
|
||||
BACKUP_STORAGE_PATH: './data/backups' # Dossier des sauvegardes
|
||||
volumes:
|
||||
- ./data:/app/data # Bind mount vers dossier local
|
||||
- ./data:/app/data # Bind mount vers dossier local
|
||||
```
|
||||
|
||||
**Structure des dossiers :**
|
||||
|
||||
```
|
||||
./data/ # Dossier local mappé
|
||||
├── prod.db # Base de données production
|
||||
├── dev.db # Base de données développement
|
||||
├── dev.db # Base de données développement
|
||||
└── backups/ # Sauvegardes (créé automatiquement)
|
||||
├── towercontrol_*.db.gz
|
||||
└── ...
|
||||
@@ -333,7 +344,7 @@ POST /api/backups/[filename] # Restaurer (dev seulement)
|
||||
const response = await fetch('/api/backups', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ action: 'create' })
|
||||
body: JSON.stringify({ action: 'create' }),
|
||||
});
|
||||
|
||||
// Lister les sauvegardes
|
||||
@@ -366,15 +377,16 @@ scripts/
|
||||
## Roadmap
|
||||
|
||||
### Version actuelle ✅
|
||||
|
||||
- Sauvegardes automatiques et manuelles
|
||||
- Interface graphique complète
|
||||
- CLI d'administration
|
||||
- Compression et rétention
|
||||
|
||||
### Améliorations futures 🚧
|
||||
|
||||
- Sauvegarde vers cloud (S3, Google Drive)
|
||||
- Chiffrement des sauvegardes
|
||||
- Notifications par email
|
||||
- Métriques de performance
|
||||
- Sauvegarde incrémentale
|
||||
|
||||
|
||||
32
DOCKER.md
32
DOCKER.md
@@ -5,6 +5,7 @@ Guide d'utilisation de TowerControl avec Docker.
|
||||
## 🚀 Démarrage rapide
|
||||
|
||||
### Production
|
||||
|
||||
```bash
|
||||
# Démarrer le service de production
|
||||
docker-compose up -d towercontrol
|
||||
@@ -14,6 +15,7 @@ open http://localhost:3006
|
||||
```
|
||||
|
||||
### Développement
|
||||
|
||||
```bash
|
||||
# Démarrer le service de développement avec live reload
|
||||
docker-compose --profile dev up towercontrol-dev
|
||||
@@ -25,6 +27,7 @@ open http://localhost:3005
|
||||
## 📋 Services disponibles
|
||||
|
||||
### 🚀 `towercontrol` (Production)
|
||||
|
||||
- **Port** : 3006
|
||||
- **Base de données** : `./data/prod.db`
|
||||
- **Sauvegardes** : `./data/backups/`
|
||||
@@ -32,6 +35,7 @@ open http://localhost:3005
|
||||
- **Restart** : Automatique
|
||||
|
||||
### 🛠️ `towercontrol-dev` (Développement)
|
||||
|
||||
- **Port** : 3005
|
||||
- **Base de données** : `./data/dev.db`
|
||||
- **Sauvegardes** : `./data/backups/` (partagées)
|
||||
@@ -54,13 +58,13 @@ open http://localhost:3005
|
||||
|
||||
### Variables d'environnement
|
||||
|
||||
| Variable | Production | Développement | Description |
|
||||
|----------|------------|---------------|-------------|
|
||||
| `NODE_ENV` | `production` | `development` | Mode d'exécution |
|
||||
| `DATABASE_URL` | `file:./data/prod.db` | `file:./data/dev.db` | Base Prisma |
|
||||
| `BACKUP_DATABASE_PATH` | `./data/prod.db` | `./data/dev.db` | Source backup |
|
||||
| `BACKUP_STORAGE_PATH` | `./data/backups` | `./data/backups` | Dossier backup |
|
||||
| `TZ` | `Europe/Paris` | `Europe/Paris` | Fuseau horaire |
|
||||
| Variable | Production | Développement | Description |
|
||||
| ---------------------- | --------------------- | -------------------- | ---------------- |
|
||||
| `NODE_ENV` | `production` | `development` | Mode d'exécution |
|
||||
| `DATABASE_URL` | `file:./data/prod.db` | `file:./data/dev.db` | Base Prisma |
|
||||
| `BACKUP_DATABASE_PATH` | `./data/prod.db` | `./data/dev.db` | Source backup |
|
||||
| `BACKUP_STORAGE_PATH` | `./data/backups` | `./data/backups` | Dossier backup |
|
||||
| `TZ` | `Europe/Paris` | `Europe/Paris` | Fuseau horaire |
|
||||
|
||||
### Ports
|
||||
|
||||
@@ -70,6 +74,7 @@ open http://localhost:3005
|
||||
## 📚 Commandes utiles
|
||||
|
||||
### Gestion des conteneurs
|
||||
|
||||
```bash
|
||||
# Voir les logs
|
||||
docker-compose logs -f towercontrol
|
||||
@@ -86,6 +91,7 @@ docker-compose down -v --rmi all
|
||||
```
|
||||
|
||||
### Gestion des données
|
||||
|
||||
```bash
|
||||
# Sauvegarder les données
|
||||
docker-compose exec towercontrol npm run backup:create
|
||||
@@ -98,6 +104,7 @@ docker-compose exec towercontrol sh
|
||||
```
|
||||
|
||||
### Base de données
|
||||
|
||||
```bash
|
||||
# Migrations Prisma
|
||||
docker-compose exec towercontrol npx prisma migrate deploy
|
||||
@@ -112,6 +119,7 @@ docker-compose exec towercontrol-dev npx prisma studio
|
||||
## 🔍 Debugging
|
||||
|
||||
### Vérifier la santé
|
||||
|
||||
```bash
|
||||
# Health check
|
||||
curl http://localhost:3006/api/health
|
||||
@@ -122,6 +130,7 @@ docker-compose exec towercontrol env | grep -E "(DATABASE|BACKUP|NODE_ENV)"
|
||||
```
|
||||
|
||||
### Logs détaillés
|
||||
|
||||
```bash
|
||||
# Logs avec timestamps
|
||||
docker-compose logs -f -t towercontrol
|
||||
@@ -135,6 +144,7 @@ docker-compose logs --tail=100 towercontrol
|
||||
### Problèmes courants
|
||||
|
||||
**Port déjà utilisé**
|
||||
|
||||
```bash
|
||||
# Trouver le processus qui utilise le port
|
||||
lsof -i :3006
|
||||
@@ -142,12 +152,14 @@ kill -9 <PID>
|
||||
```
|
||||
|
||||
**Base de données corrompue**
|
||||
|
||||
```bash
|
||||
# Restaurer depuis une sauvegarde
|
||||
docker-compose exec towercontrol npm run backup:restore filename.db.gz
|
||||
```
|
||||
|
||||
**Permissions**
|
||||
|
||||
```bash
|
||||
# Corriger les permissions du dossier data
|
||||
sudo chown -R $USER:$USER ./data
|
||||
@@ -156,6 +168,7 @@ sudo chown -R $USER:$USER ./data
|
||||
## 📊 Monitoring
|
||||
|
||||
### Espace disque
|
||||
|
||||
```bash
|
||||
# Taille du dossier data
|
||||
du -sh ./data
|
||||
@@ -165,6 +178,7 @@ df -h .
|
||||
```
|
||||
|
||||
### Performance
|
||||
|
||||
```bash
|
||||
# Stats des conteneurs
|
||||
docker stats
|
||||
@@ -176,6 +190,7 @@ docker-compose exec towercontrol free -h
|
||||
## 🔒 Production
|
||||
|
||||
### Recommandations
|
||||
|
||||
- Utiliser un reverse proxy (nginx, traefik)
|
||||
- Configurer HTTPS
|
||||
- Sauvegarder régulièrement `./data/`
|
||||
@@ -183,11 +198,12 @@ docker-compose exec towercontrol free -h
|
||||
- Logs centralisés
|
||||
|
||||
### Exemple nginx
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 80;
|
||||
server_name towercontrol.example.com;
|
||||
|
||||
|
||||
location / {
|
||||
proxy_pass http://localhost:3006;
|
||||
proxy_set_header Host $host;
|
||||
|
||||
35
README.md
35
README.md
@@ -12,7 +12,7 @@ TowerControl est un gestionnaire de tâches **standalone** conçu pour les déve
|
||||
|
||||
- **Local first** : Base SQLite, pas de cloud requis
|
||||
- **Architecture moderne** : Next.js 15 + React 19 + TypeScript + Prisma
|
||||
- **Design minimaliste** : Interface dark/light avec focus sur la productivité
|
||||
- **Design minimaliste** : Interface dark/light avec focus sur la productivité
|
||||
- **Intégrations intelligentes** : Sync unidirectionnelle Jira sans pollution
|
||||
|
||||
---
|
||||
@@ -20,6 +20,7 @@ TowerControl est un gestionnaire de tâches **standalone** conçu pour les déve
|
||||
## ✨ Fonctionnalités principales
|
||||
|
||||
### 🏗️ Kanban moderne
|
||||
|
||||
- **Drag & drop fluide** avec @dnd-kit (optimistic updates)
|
||||
- **Colonnes configurables** : backlog, todo, in_progress, done, cancelled, freeze, archived
|
||||
- **Vues multiples** : Kanban classique + swimlanes par priorité
|
||||
@@ -27,18 +28,21 @@ TowerControl est un gestionnaire de tâches **standalone** conçu pour les déve
|
||||
- **Création rapide** : Ajout inline dans chaque colonne
|
||||
|
||||
### 🏷️ Système de tags avancé
|
||||
|
||||
- **Tags colorés** avec sélecteur de couleur
|
||||
- **Autocomplete intelligent** lors de la saisie
|
||||
- **Filtrage en temps réel** par tags
|
||||
- **Gestion complète** avec page dédiée `/tags`
|
||||
|
||||
### 📊 Filtrage et recherche
|
||||
|
||||
- **Recherche temps réel** dans les titres et descriptions
|
||||
- **Filtres combinables** : statut, priorité, tags, source
|
||||
- **Tri flexible** : date, priorité, alphabétique
|
||||
- **Interface intuitive** avec dropdowns et toggles
|
||||
|
||||
### 📝 Daily Notes
|
||||
|
||||
- **Checkboxes quotidiennes** avec sections "Hier" / "Aujourd'hui"
|
||||
- **Navigation par date** (précédent/suivant)
|
||||
- **Liaison optionnelle** avec les tâches existantes
|
||||
@@ -46,6 +50,7 @@ TowerControl est un gestionnaire de tâches **standalone** conçu pour les déve
|
||||
- **Historique calendaire** des dailies
|
||||
|
||||
### 🔗 Intégration Jira Cloud
|
||||
|
||||
- **Synchronisation unidirectionnelle** (Jira → local)
|
||||
- **Authentification sécurisée** (email + API token)
|
||||
- **Mapping intelligent** des statuts Jira
|
||||
@@ -54,6 +59,7 @@ TowerControl est un gestionnaire de tâches **standalone** conçu pour les déve
|
||||
- **Interface de configuration** complète
|
||||
|
||||
### 🎨 Interface & UX
|
||||
|
||||
- **Thème adaptatif** : dark/light + détection système
|
||||
- **Design cohérent** : palette cyberpunk/tech avec Tailwind CSS
|
||||
- **Composants modulaires** : Button, Input, Card, Modal, Badge
|
||||
@@ -61,6 +67,7 @@ TowerControl est un gestionnaire de tâches **standalone** conçu pour les déve
|
||||
- **Responsive design** pour tous les écrans
|
||||
|
||||
### ⚡ Performance & Architecture
|
||||
|
||||
- **Server Actions** pour les mutations rapides (vs API routes)
|
||||
- **Architecture SSR** avec hydratation optimisée
|
||||
- **Base de données SQLite** ultra-rapide
|
||||
@@ -72,7 +79,8 @@ TowerControl est un gestionnaire de tâches **standalone** conçu pour les déve
|
||||
## 🛠️ Installation
|
||||
|
||||
### Prérequis
|
||||
- **Node.js** 18+
|
||||
|
||||
- **Node.js** 18+
|
||||
- **npm** ou **yarn**
|
||||
|
||||
### Installation locale
|
||||
@@ -115,10 +123,12 @@ docker compose --profile dev up -d
|
||||
```
|
||||
|
||||
**Accès :**
|
||||
|
||||
- **Production** : http://localhost:3006
|
||||
- **Développement** : http://localhost:3005
|
||||
|
||||
**Gestion des données :**
|
||||
|
||||
```bash
|
||||
# Utiliser votre base locale existante (décommentez dans docker-compose.yml)
|
||||
# - ./prisma/dev.db:/app/data/prod.db
|
||||
@@ -134,9 +144,10 @@ docker compose down -v
|
||||
```
|
||||
|
||||
**Avantages Docker :**
|
||||
|
||||
- ✅ **Isolation complète** - Pas de pollution de l'environnement local
|
||||
- ✅ **Base persistante** - Volumes Docker pour SQLite
|
||||
- ✅ **Prêt pour prod** - Configuration optimisée
|
||||
- ✅ **Prêt pour prod** - Configuration optimisée
|
||||
- ✅ **Healthcheck intégré** - Monitoring automatique
|
||||
- ✅ **Hot-reload** - Mode dev avec synchronisation du code
|
||||
|
||||
@@ -234,7 +245,7 @@ towercontrol/
|
||||
|
||||
### Démarrage rapide
|
||||
|
||||
1. **Créer une tâche** :
|
||||
1. **Créer une tâche** :
|
||||
- Clic sur `+ Ajouter` dans une colonne
|
||||
- Ou bouton `+ Nouvelle tâche` global
|
||||
|
||||
@@ -289,10 +300,10 @@ npm run seed # Ajouter des données de test
|
||||
```typescript
|
||||
// lib/config.ts
|
||||
export const UI_CONFIG = {
|
||||
theme: 'system', // 'light' | 'dark' | 'system'
|
||||
itemsPerPage: 50, // Pagination
|
||||
enableDragAndDrop: true, // Drag & drop
|
||||
autoSave: true // Sauvegarde auto
|
||||
theme: 'system', // 'light' | 'dark' | 'system'
|
||||
itemsPerPage: 50, // Pagination
|
||||
enableDragAndDrop: true, // Drag & drop
|
||||
autoSave: true, // Sauvegarde auto
|
||||
};
|
||||
```
|
||||
|
||||
@@ -322,6 +333,7 @@ DATABASE_URL="postgresql://user:pass@localhost:5432/towercontrol"
|
||||
## 🚧 Roadmap
|
||||
|
||||
### ✅ Version 2.0 (Actuelle)
|
||||
|
||||
- Interface Kanban moderne avec drag & drop
|
||||
- Système de tags avancé
|
||||
- Daily notes avec navigation
|
||||
@@ -330,12 +342,14 @@ DATABASE_URL="postgresql://user:pass@localhost:5432/towercontrol"
|
||||
- Server Actions pour les performances
|
||||
|
||||
### 🔄 Version 2.1 (En cours)
|
||||
|
||||
- [ ] Page dashboard avec analytics
|
||||
- [ ] Système de sauvegarde automatique (configurable)
|
||||
- [ ] Métriques de productivité et graphiques
|
||||
- [ ] Actions en lot (sélection multiple)
|
||||
|
||||
### 🎯 Version 2.2 (Futur)
|
||||
|
||||
- [ ] Sous-tâches et hiérarchie
|
||||
- [ ] Dates d'échéance et rappels
|
||||
- [ ] Collaboration et assignation
|
||||
@@ -343,6 +357,7 @@ DATABASE_URL="postgresql://user:pass@localhost:5432/towercontrol"
|
||||
- [ ] Mode PWA et offline
|
||||
|
||||
### 🚀 Version 3.0 (Vision)
|
||||
|
||||
- [ ] Analytics d'équipe avancées
|
||||
- [ ] Intégrations multiples (GitHub, Linear, etc.)
|
||||
- [ ] API publique et webhooks
|
||||
@@ -379,11 +394,11 @@ MIT License - Voir le fichier [LICENSE](LICENSE) pour plus de détails.
|
||||
## 🙏 Remerciements
|
||||
|
||||
- **Next.js** pour le framework moderne
|
||||
- **Prisma** pour l'ORM élégant
|
||||
- **Prisma** pour l'ORM élégant
|
||||
- **@dnd-kit** pour le drag & drop fluide
|
||||
- **Tailwind CSS** pour le styling rapide
|
||||
- **Jira API** pour l'intégration robuste
|
||||
|
||||
---
|
||||
|
||||
**Développé avec ❤️ pour optimiser la productivité des équipes tech**
|
||||
**Développé avec ❤️ pour optimiser la productivité des équipes tech**
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# Mise à niveau TFS : Récupération des PRs assignées à l'utilisateur
|
||||
|
||||
## 🎯 Objectif
|
||||
|
||||
Permettre au service TFS de récupérer **toutes** les Pull Requests assignées à l'utilisateur sur l'ensemble de son organisation Azure DevOps, plutôt que de se limiter à un projet spécifique.
|
||||
|
||||
## ⚡ Changements apportés
|
||||
@@ -8,17 +9,20 @@ Permettre au service TFS de récupérer **toutes** les Pull Requests assignées
|
||||
### 1. Service TFS (`src/services/tfs.ts`)
|
||||
|
||||
#### Nouvelles méthodes ajoutées :
|
||||
|
||||
- **`getMyPullRequests()`** : Récupère toutes les PRs concernant l'utilisateur
|
||||
- **`getPullRequestsByCreator()`** : PRs créées par l'utilisateur
|
||||
- **`getPullRequestsByReviewer()`** : PRs où l'utilisateur est reviewer
|
||||
- **`filterPullRequests()`** : Applique les filtres de configuration
|
||||
|
||||
#### Méthode syncTasks refactorisée :
|
||||
|
||||
- Utilise maintenant `getMyPullRequests()` au lieu de parcourir tous les repositories
|
||||
- Plus efficace et centrée sur l'utilisateur
|
||||
- Récupération directe via l'API Azure DevOps avec critères `@me`
|
||||
|
||||
#### Configuration mise à jour :
|
||||
|
||||
- **`projectName`** devient **optionnel**
|
||||
- Validation assouplie dans les factories
|
||||
- Comportement adaptatif : projet spécifique OU toute l'organisation
|
||||
@@ -26,12 +30,14 @@ Permettre au service TFS de récupérer **toutes** les Pull Requests assignées
|
||||
### 2. Interface utilisateur (`src/components/settings/TfsConfigForm.tsx`)
|
||||
|
||||
#### Modifications du formulaire :
|
||||
|
||||
- Champ "Nom du projet" marqué comme **optionnel**
|
||||
- Validation `required` supprimée
|
||||
- Placeholder mis à jour : *"laisser vide pour toute l'organisation"*
|
||||
- Affichage du statut : *"Toute l'organisation"* si pas de projet
|
||||
- Placeholder mis à jour : _"laisser vide pour toute l'organisation"_
|
||||
- Affichage du statut : _"Toute l'organisation"_ si pas de projet
|
||||
|
||||
#### Instructions mises à jour :
|
||||
|
||||
- Explique le nouveau comportement **synchronisation intelligente**
|
||||
- Précise que les PRs sont récupérées automatiquement selon l'assignation
|
||||
- Note sur la portée projet vs organisation
|
||||
@@ -39,17 +45,20 @@ Permettre au service TFS de récupérer **toutes** les Pull Requests assignées
|
||||
### 3. Endpoints API
|
||||
|
||||
#### `/api/tfs/test/route.ts`
|
||||
|
||||
- Validation mise à jour (projectName optionnel)
|
||||
- Message de réponse enrichi avec portée (projet/organisation)
|
||||
- Retour détaillé du scope de synchronisation
|
||||
|
||||
#### `/api/tfs/sync/route.ts`
|
||||
|
||||
- Validation assouplie pour les deux méthodes GET/POST
|
||||
- Configuration adaptative selon la présence du projectName
|
||||
|
||||
## 🔧 API Azure DevOps utilisées
|
||||
|
||||
### Nouvelles requêtes :
|
||||
|
||||
```typescript
|
||||
// PRs créées par l'utilisateur
|
||||
/_apis/git/pullrequests?searchCriteria.creatorId=@me&searchCriteria.status=active
|
||||
@@ -59,6 +68,7 @@ Permettre au service TFS de récupérer **toutes** les Pull Requests assignées
|
||||
```
|
||||
|
||||
### Comportement intelligent :
|
||||
|
||||
- **Fusion automatique** des deux types de PRs
|
||||
- **Déduplication** basée sur `pullRequestId`
|
||||
- **Filtrage** selon la configuration (repositories, branches, projet)
|
||||
@@ -74,11 +84,13 @@ Permettre au service TFS de récupérer **toutes** les Pull Requests assignées
|
||||
## 🎨 Interface utilisateur
|
||||
|
||||
### Avant :
|
||||
|
||||
- Champ projet **obligatoire**
|
||||
- Synchronisation limitée à UN projet
|
||||
- Configuration rigide
|
||||
|
||||
### Après :
|
||||
|
||||
- Champ projet **optionnel**
|
||||
- Synchronisation intelligente de TOUTES les PRs assignées
|
||||
- Configuration flexible et adaptative
|
||||
@@ -94,10 +106,11 @@ Permettre au service TFS de récupérer **toutes** les Pull Requests assignées
|
||||
## 🚀 Déploiement
|
||||
|
||||
La migration est **transparente** :
|
||||
|
||||
- Les configurations existantes continuent à fonctionner
|
||||
- Possibilité de supprimer le `projectName` pour étendre la portée
|
||||
- Pas de rupture de compatibilité
|
||||
|
||||
---
|
||||
|
||||
*Cette mise à niveau transforme le service TFS d'un outil de surveillance de projet en un assistant personnel intelligent pour Azure DevOps.* 🎯
|
||||
_Cette mise à niveau transforme le service TFS d'un outil de surveillance de projet en un assistant personnel intelligent pour Azure DevOps._ 🎯
|
||||
|
||||
24
TODO.md
24
TODO.md
@@ -1,11 +1,13 @@
|
||||
# TowerControl v2.0 - Gestionnaire de tâches moderne
|
||||
|
||||
## Fix
|
||||
|
||||
- [ ] Calendrier n'a plus le bouton calendrier d'ouverture du calendrier visuel dans les inputs datetime
|
||||
- [ ] Un raccourci pour chercher dans la page de Kanban
|
||||
- [ ] Bouton cloner une tache dans la modale d'edition
|
||||
|
||||
## Idées à developper
|
||||
|
||||
- [ ] Optimisations Perf : requetes DB
|
||||
- [ ] PWA et mode offline
|
||||
|
||||
@@ -14,8 +16,9 @@
|
||||
## 🐛 Problèmes relevés en réunion - Corrections UI/UX
|
||||
|
||||
### 🎨 Design et Interface
|
||||
- [X] **Homepage cards** : toute en variant glass
|
||||
- [X] **Icône Kanban homepage** - Changer icône sur la page d'accueil, pas lisible (utiliser une lib)
|
||||
|
||||
- [x] **Homepage cards** : toute en variant glass
|
||||
- [x] **Icône Kanban homepage** - Changer icône sur la page d'accueil, pas lisible (utiliser une lib)
|
||||
- [x] **Lisibilité label graph par tag** - Améliorer la lisibilité des labels dans les graphiques par tag <!-- Amélioré marges, légendes, tailles de police, retiré emojis -->
|
||||
- [x] **Tag homepage** - Problème d'affichage des graphs de tags sur la homepage côté lisibilité, certaines icones ne sont pas entièrement visible, et la légende est trop proche du graphe. <!-- Amélioré hauteur, marges, responsive -->
|
||||
- [x] **Tâches récentes** - Revoir l'affichage et la logique des tâches récentes <!-- Logique améliorée (tâches terminées récentes), responsive, icône claire -->
|
||||
@@ -33,18 +36,19 @@
|
||||
- [ ] **Deux modales** - Problème de duplication de modales
|
||||
- [ ] **Control panel et select** - Problème avec les contrôles et sélecteurs
|
||||
- [ ] **TaskCard et Kanban transparence** - Appliquer la transparence sur le background et non sur la card
|
||||
- [X] **Recherche Kanban desktop controls** - Ajouter icône et label : "rechercher" pour rapetir
|
||||
- [x] **Recherche Kanban desktop controls** - Ajouter icône et label : "rechercher" pour rapetir
|
||||
- [ ] **Largeur page Kanban** - Réduire légèrement la largeur et revoir toutes les autres pages
|
||||
- [x] **Icône thème à gauche du profil** - Repositionner l'icône de thème dans le header
|
||||
- [ ] **Déconnexion trop petit et couleur** - Améliorer le bouton de déconnexion
|
||||
- [ ] **Fond modal trop opaque** - Réduire l'opacité du fond des modales
|
||||
- [ ] **Couleurs thème clair et TFS Jira Kanban** - Harmoniser les couleurs du thème clair
|
||||
- [X] **États sélectionnés desktop control** - Revoir les couleurs des états sélectionnés pour avoir le joli bleu du dropdown partout
|
||||
- [x] **États sélectionnés desktop control** - Revoir les couleurs des états sélectionnés pour avoir le joli bleu du dropdown partout
|
||||
- [ ] **Dépasse 1000 caractères en edit modal task** - Corriger la limite (pas de limite) et revoir la quickcard description
|
||||
- [ ] **UI si échéance et trop de labels dans le footer de card** - Améliorer l'affichage en mode détaillé TaskCard; certains boutons sont sur deux lignes ce qui casse l'affichage
|
||||
- [ ] **Gravatar** - Implémenter l'affichage des avatars Gravatar
|
||||
|
||||
### 🔧 Fonctionnalités et Intégrations
|
||||
|
||||
- [ ] **Synchro Jira et TFS shortcuts** - Ajouter des raccourcis et bouton dans Kanban
|
||||
- [x] **Intégration suppressions Jira/TFS** - Aligner la gestion des suppressions sur TFS, je veux que ce qu'on a récupéré dans la synchro, quand ca devient terminé dans Jira ou TFS, soit marqué comme terminé dans le Kanban et non supprimé du kanban. <!-- COMPLET: 1) JQL inclut resolved >= -30d pour récupérer tâches terminées, 2) syncSingleTask met à jour status + completedAt, 3) cleanupUnassignedTasks/cleanupInactivePullRequests préservent tâches done/archived -->
|
||||
- [ ] **Log d'activité** - Implémenter un système de log d'activité (feature potentielle)
|
||||
@@ -54,6 +58,7 @@
|
||||
## 🚀 Nouvelles idées & fonctionnalités futures
|
||||
|
||||
### 🎯 Jira - Suivi des demandes en attente
|
||||
|
||||
- [ ] **Page "Jiras en attente"**
|
||||
- [ ] Liste des Jiras créés par moi mais non assignés à mon équipe
|
||||
- [ ] Suivi des demandes formulées à d'autres équipes
|
||||
@@ -66,10 +71,12 @@
|
||||
### 👥 Gestion multi-utilisateurs (PROJET MAJEUR)
|
||||
|
||||
#### **Architecture actuelle → Multi-tenant**
|
||||
|
||||
- **Problème** : App mono-utilisateur avec données globales
|
||||
- **Solution** : Transformation en app multi-utilisateurs avec isolation des données + système de rôles
|
||||
|
||||
#### **Plan de migration**
|
||||
|
||||
- [ ] **Phase 1: Authentification**
|
||||
- [ ] Système de login/mot de passe (NextAuth.js)
|
||||
- [ ] Gestion des sessions sécurisées
|
||||
@@ -152,6 +159,7 @@
|
||||
- [ ] Historique des modifications par utilisateur
|
||||
|
||||
#### **Considérations techniques**
|
||||
|
||||
- **Base de données** : Ajouter `userId` partout + contraintes
|
||||
- **Sécurité** : Validation côté serveur de l'isolation des données
|
||||
- **Performance** : Index sur `userId`, pagination pour gros volumes
|
||||
@@ -210,6 +218,7 @@
|
||||
### **Fonctionnalités IA concrètes**
|
||||
|
||||
#### 🎯 **Smart Task Creation**
|
||||
|
||||
- [ ] **Bouton "Créer avec IA" dans le Kanban**
|
||||
- [ ] Input libre : "Préparer présentation client pour vendredi"
|
||||
- [ ] IA génère : titre, description, estimation durée, sous-tâches
|
||||
@@ -217,6 +226,7 @@
|
||||
- [ ] Validation/modification avant création
|
||||
|
||||
#### 🧠 **Daily Assistant**
|
||||
|
||||
- [ ] **Bouton "Smart Daily" dans la page Daily**
|
||||
- [ ] Input libre : "Réunion client 14h, finir le rapport, appeler le fournisseur"
|
||||
- [ ] IA génère une liste de checkboxes structurées
|
||||
@@ -226,6 +236,7 @@
|
||||
- [ ] Pendant la saisie, IA propose des checkboxes similaires
|
||||
|
||||
#### 🎨 **Smart Tagging**
|
||||
|
||||
- [ ] **Auto-tagging des nouvelles tâches**
|
||||
- [ ] IA analyse le titre/description
|
||||
- [ ] Propose automatiquement 2-3 tags **existants** pertinents
|
||||
@@ -235,6 +246,7 @@
|
||||
- [ ] Tri par fréquence d'usage et pertinence
|
||||
|
||||
#### 💬 **Chat Assistant**
|
||||
|
||||
- [ ] **Widget chat en bas à droite**
|
||||
- [ ] "Quelles sont mes tâches urgentes cette semaine ?"
|
||||
- [ ] "Comment optimiser mon planning demain ?"
|
||||
@@ -245,6 +257,7 @@
|
||||
- [ ] Recherche par contexte, pas juste mots-clés
|
||||
|
||||
#### 📈 **Smart Reports**
|
||||
|
||||
- [ ] **Génération automatique de rapports**
|
||||
- [ ] Bouton "Générer rapport IA" dans analytics
|
||||
- [ ] IA analyse les données et génère un résumé textuel
|
||||
@@ -255,6 +268,7 @@
|
||||
- [ ] Notifications contextuelles et actionables
|
||||
|
||||
#### ⚡ **Quick Actions**
|
||||
|
||||
- [ ] **Bouton "Optimiser" sur une tâche**
|
||||
- [ ] IA suggère des améliorations (titre, description)
|
||||
- [ ] Propose des **tags existants** pertinents
|
||||
@@ -268,4 +282,4 @@
|
||||
|
||||
---
|
||||
|
||||
*Focus sur l'expérience utilisateur et le design moderne. App standalone prête pour évoluer vers une plateforme d'intégration complète.*
|
||||
_Focus sur l'expérience utilisateur et le design moderne. App standalone prête pour évoluer vers une plateforme d'intégration complète._
|
||||
|
||||
@@ -3,19 +3,22 @@
|
||||
## ✅ Phase 1: Nettoyage et architecture (TERMINÉ)
|
||||
|
||||
### 1.1 Configuration projet Next.js
|
||||
|
||||
- [x] Initialiser Next.js avec TypeScript
|
||||
- [x] Configurer ESLint, Prettier
|
||||
- [x] Configurer ESLint, Prettier
|
||||
- [x] Setup structure de dossiers selon les règles du workspace
|
||||
- [x] Configurer base de données (SQLite local)
|
||||
- [x] Setup Prisma ORM
|
||||
|
||||
### 1.2 Architecture backend standalone
|
||||
|
||||
- [x] Créer `services/database.ts` - Pool de connexion DB
|
||||
- [x] Créer `services/tasks.ts` - Service CRUD pour les tâches
|
||||
- [x] Créer `lib/types.ts` - Types partagés (Task, Tag, etc.)
|
||||
- [x] Nettoyer l'ancien code de synchronisation
|
||||
|
||||
### 1.3 API moderne et propre
|
||||
|
||||
- [x] `app/api/tasks/route.ts` - API CRUD complète (GET, POST, PATCH, DELETE)
|
||||
- [x] Supprimer les routes de synchronisation obsolètes
|
||||
- [x] Configuration moderne dans `lib/config.ts`
|
||||
@@ -25,19 +28,22 @@
|
||||
## 🎯 Phase 2: Interface utilisateur moderne (EN COURS)
|
||||
|
||||
### 2.1 Système de design et composants UI
|
||||
|
||||
- [x] Créer les composants UI de base (Button, Input, Card, Modal, Badge)
|
||||
- [x] Implémenter le système de design tech dark (couleurs, typographie, spacing)
|
||||
- [x] Setup Tailwind CSS avec classes utilitaires personnalisées
|
||||
- [x] Créer une palette de couleurs tech/cyberpunk
|
||||
|
||||
### 2.2 Composants Kanban existants (à améliorer)
|
||||
|
||||
- [x] `components/kanban/Board.tsx` - Tableau Kanban principal
|
||||
- [x] `components/kanban/Column.tsx` - Colonnes du Kanban
|
||||
- [x] `components/kanban/Column.tsx` - Colonnes du Kanban
|
||||
- [x] `components/kanban/TaskCard.tsx` - Cartes de tâches
|
||||
- [x] `components/ui/Header.tsx` - Header avec statistiques
|
||||
- [x] Refactoriser les composants pour utiliser le nouveau système UI
|
||||
|
||||
### 2.3 Gestion des tâches (CRUD)
|
||||
|
||||
- [x] Formulaire de création de tâche (Modal + Form)
|
||||
- [x] Création rapide inline dans les colonnes (QuickAddTask)
|
||||
- [x] Formulaire d'édition de tâche (Modal + Form avec pré-remplissage)
|
||||
@@ -47,6 +53,7 @@
|
||||
- [x] Validation des formulaires et gestion d'erreurs
|
||||
|
||||
### 2.4 Gestion des tags
|
||||
|
||||
- [x] Créer/éditer des tags avec sélecteur de couleur
|
||||
- [x] Autocomplete pour les tags existants
|
||||
- [x] Suppression de tags (avec vérification des dépendances)
|
||||
@@ -66,6 +73,7 @@
|
||||
- [x] Intégration des filtres dans KanbanBoard
|
||||
|
||||
### 2.5 Clients HTTP et hooks
|
||||
|
||||
- [x] `clients/tasks-client.ts` - Client pour les tâches (CRUD complet)
|
||||
- [x] `clients/tags-client.ts` - Client pour les tags
|
||||
- [x] `clients/base/http-client.ts` - Client HTTP de base
|
||||
@@ -76,6 +84,7 @@
|
||||
- [x] Architecture SSR + hydratation client optimisée
|
||||
|
||||
### 2.6 Fonctionnalités Kanban avancées
|
||||
|
||||
- [x] Drag & drop entre colonnes (@dnd-kit avec React 19)
|
||||
- [x] Drag & drop optimiste (mise à jour immédiate + rollback si erreur)
|
||||
- [x] Filtrage par statut/priorité/assigné
|
||||
@@ -85,6 +94,7 @@
|
||||
- [x] Tri des tâches (date, priorité, alphabétique)
|
||||
|
||||
### 2.7 Système de thèmes (clair/sombre)
|
||||
|
||||
- [x] Créer le contexte de thème (ThemeContext + ThemeProvider)
|
||||
- [x] Ajouter toggle de thème dans le Header (bouton avec icône soleil/lune)
|
||||
- [x] Définir les variables CSS pour le thème clair
|
||||
@@ -99,6 +109,7 @@
|
||||
## 📊 Phase 3: Intégrations et analytics (Priorité 3)
|
||||
|
||||
### 3.1 Gestion du Daily
|
||||
|
||||
- [x] Créer `services/daily.ts` - Service de gestion des daily notes
|
||||
- [x] Modèle de données Daily (date, checkboxes hier/aujourd'hui)
|
||||
- [x] Interface Daily avec sections "Hier" et "Aujourd'hui"
|
||||
@@ -111,6 +122,7 @@
|
||||
- [x] Vue calendar/historique des dailies
|
||||
|
||||
### 3.2 Intégration Jira Cloud
|
||||
|
||||
- [x] Créer `services/jira.ts` - Service de connexion à l'API Jira Cloud
|
||||
- [x] Configuration Jira (URL, email, API token) dans `lib/config.ts`
|
||||
- [x] Authentification Basic Auth (email + API token)
|
||||
@@ -127,6 +139,7 @@
|
||||
- [x] Gestion des erreurs et timeouts API
|
||||
|
||||
### 3.3 Page d'accueil/dashboard
|
||||
|
||||
- [x] Créer une page d'accueil moderne avec vue d'ensemble
|
||||
- [x] Widgets de statistiques (tâches par statut, priorité, etc.)
|
||||
- [x] Déplacer kanban vers /kanban et créer nouveau dashboard à la racine
|
||||
@@ -137,6 +150,7 @@
|
||||
- [x] Intégration des analytics dans le dashboard
|
||||
|
||||
### 3.4 Analytics et métriques
|
||||
|
||||
- [x] `services/analytics.ts` - Calculs statistiques
|
||||
- [x] Métriques de productivité (vélocité, temps moyen, etc.)
|
||||
- [x] Graphiques avec Recharts (tendances, vélocité, distribution)
|
||||
@@ -144,6 +158,7 @@
|
||||
- [x] Insights automatiques et métriques visuelles
|
||||
|
||||
## Autre Todo
|
||||
|
||||
- [x] Avoir un bouton pour réduire/agrandir la font des taches dans les kanban (swimlane et classique)
|
||||
- [x] Refactorer les couleurs des priorités dans un seul endroit
|
||||
- [x] Settings synchro Jira : ajouter une liste de projet à ignorer, doit etre pris en compte par le service bien sur
|
||||
@@ -161,16 +176,17 @@
|
||||
- [x] Vérification d'intégrité et restauration sécurisée
|
||||
- [x] Option de restauration depuis une sauvegarde sélectionnée
|
||||
|
||||
|
||||
## 🔧 Phase 4: Server Actions - Migration API Routes (Nouveau)
|
||||
|
||||
### 4.1 Migration vers Server Actions - Actions rapides
|
||||
|
||||
**Objectif** : Remplacer les API routes par des server actions pour les actions simples et fréquentes
|
||||
|
||||
#### Actions TaskCard (Priorité 1)
|
||||
|
||||
- [x] Créer `actions/tasks.ts` avec server actions de base
|
||||
- [x] `updateTaskStatus(taskId, status)` - Changement de statut
|
||||
- [x] `updateTaskTitle(taskId, title)` - Édition inline du titre
|
||||
- [x] `updateTaskTitle(taskId, title)` - Édition inline du titre
|
||||
- [x] `deleteTask(taskId)` - Suppression de tâche
|
||||
- [x] Modifier `TaskCard.tsx` pour utiliser server actions directement
|
||||
- [x] Remplacer les props callbacks par calls directs aux actions
|
||||
@@ -180,7 +196,8 @@
|
||||
- [x] **Nettoyage** : Simplifier `tasks-client.ts` (garder GET et POST uniquement)
|
||||
- [x] **Nettoyage** : Modifier `useTasks.ts` pour remplacer mutations par server actions
|
||||
|
||||
#### Actions Daily (Priorité 2)
|
||||
#### Actions Daily (Priorité 2)
|
||||
|
||||
- [x] Créer `actions/daily.ts` pour les checkboxes
|
||||
- [x] `toggleCheckbox(checkboxId)` - Toggle état checkbox
|
||||
- [x] `addCheckboxToDaily(dailyId, content)` - Ajouter checkbox
|
||||
@@ -193,9 +210,10 @@
|
||||
- [x] **Nettoyage** : Modifier hook `useDaily.ts` pour `useTransition`
|
||||
|
||||
#### Actions User Preferences (Priorité 3)
|
||||
|
||||
- [x] Créer `actions/preferences.ts` pour les toggles
|
||||
- [x] `updateViewPreferences(preferences)` - Préférences d'affichage
|
||||
- [x] `updateKanbanFilters(filters)` - Filtres Kanban
|
||||
- [x] `updateKanbanFilters(filters)` - Filtres Kanban
|
||||
- [x] `updateColumnVisibility(columns)` - Visibilité colonnes
|
||||
- [x] `updateTheme(theme)` - Changement de thème
|
||||
- [x] Remplacer les hooks par server actions directes
|
||||
@@ -204,6 +222,7 @@
|
||||
- [x] **Nettoyage** : Modifier `UserPreferencesContext.tsx` pour server actions
|
||||
|
||||
#### Actions Tags (Priorité 4)
|
||||
|
||||
- [x] Créer `actions/tags.ts` pour la gestion tags
|
||||
- [x] `createTag(name, color)` - Création tag
|
||||
- [x] `updateTag(tagId, data)` - Modification tag
|
||||
@@ -214,37 +233,43 @@
|
||||
- [x] **Nettoyage** : Modifier `useTags.ts` pour server actions directes
|
||||
|
||||
#### Migration progressive avec nettoyage immédiat
|
||||
|
||||
**Principe** : Pour chaque action migrée → nettoyage immédiat des routes et code obsolètes
|
||||
|
||||
### 4.2 Conservation API Routes - Endpoints complexes
|
||||
|
||||
**À GARDER en API routes** (pas de migration)
|
||||
|
||||
#### Endpoints de fetching initial
|
||||
|
||||
- ✅ `GET /api/tasks` - Récupération avec filtres complexes
|
||||
- ✅ `GET /api/daily` - Vue daily avec logique métier
|
||||
- ✅ `GET /api/tags` - Liste tags avec recherche
|
||||
- ✅ `GET /api/user-preferences` - Préférences initiales
|
||||
|
||||
#### Endpoints d'intégration externe
|
||||
#### Endpoints d'intégration externe
|
||||
|
||||
- ✅ `POST /api/jira/sync` - Synchronisation Jira complexe
|
||||
- ✅ `GET /api/jira/logs` - Logs de synchronisation
|
||||
- ✅ Configuration Jira (formulaires complexes)
|
||||
|
||||
#### Raisons de conservation
|
||||
|
||||
- **API publique** : Réutilisable depuis mobile/externe
|
||||
- **Logique complexe** : Synchronisation, analytics, rapports
|
||||
- **Monitoring** : Besoin de logs HTTP séparés
|
||||
- **Real-time futur** : WebSockets/SSE non compatibles server actions
|
||||
|
||||
### 4.3 Architecture hybride cible
|
||||
|
||||
```
|
||||
Actions rapides → Server Actions directes
|
||||
├── TaskCard actions (status, title, delete)
|
||||
├── Daily checkboxes (toggle, add, edit)
|
||||
├── Daily checkboxes (toggle, add, edit)
|
||||
├── Preferences toggles (theme, filters)
|
||||
└── Tags CRUD (create, update, delete)
|
||||
|
||||
Endpoints complexes → API Routes conservées
|
||||
Endpoints complexes → API Routes conservées
|
||||
├── Fetching initial avec filtres
|
||||
├── Intégrations externes (Jira, webhooks)
|
||||
├── Analytics et rapports
|
||||
@@ -252,6 +277,7 @@ Endpoints complexes → API Routes conservées
|
||||
```
|
||||
|
||||
### 4.4 Avantages attendus
|
||||
|
||||
- **🚀 Performance** : Pas de sérialisation HTTP pour actions rapides
|
||||
- **🔄 Cache intelligent** : `revalidatePath()` automatique
|
||||
- **📦 Bundle reduction** : Moins de code client HTTP
|
||||
@@ -261,6 +287,7 @@ Endpoints complexes → API Routes conservées
|
||||
## 📊 Phase 5: Surveillance Jira - Analytics d'équipe (Priorité 5)
|
||||
|
||||
### 5.1 Configuration projet Jira
|
||||
|
||||
- [x] Ajouter champ `projectKey` dans la config Jira (settings)
|
||||
- [x] Interface pour sélectionner le projet à surveiller
|
||||
- [x] Validation de l'existence du projet via API Jira
|
||||
@@ -268,6 +295,7 @@ Endpoints complexes → API Routes conservées
|
||||
- [x] Test de connexion spécifique au projet configuré
|
||||
|
||||
### 5.2 Service d'analytics Jira
|
||||
|
||||
- [x] Créer `services/jira-analytics.ts` - Métriques avancées
|
||||
- [x] Récupération des tickets du projet (toute l'équipe, pas seulement assignés)
|
||||
- [x] Calculs de vélocité d'équipe (story points par sprint)
|
||||
@@ -278,6 +306,7 @@ Endpoints complexes → API Routes conservées
|
||||
- [x] Cache intelligent des métriques (éviter API rate limits)
|
||||
|
||||
### 5.3 Page de surveillance `/jira-dashboard`
|
||||
|
||||
- [x] Créer page dédiée avec navigation depuis settings Jira
|
||||
- [x] Vue d'ensemble du projet (nom, lead, statut global)
|
||||
- [x] Sélecteur de période (7j, 30j, 3 mois, sprint actuel)
|
||||
@@ -287,6 +316,7 @@ Endpoints complexes → API Routes conservées
|
||||
- [x] Alertes visuelles (tickets en retard, sprints déviants)
|
||||
|
||||
### 5.4 Métriques et graphiques avancés
|
||||
|
||||
- [x] **Vélocité** : Story points complétés par sprint
|
||||
- [x] **Burndown chart** : Progression vs planifié
|
||||
- [x] **Cycle time** : Temps moyen par type de ticket
|
||||
@@ -297,6 +327,7 @@ Endpoints complexes → API Routes conservées
|
||||
- [x] **Collaboration** : Matrice d'interactions entre assignees
|
||||
|
||||
### 5.5 Fonctionnalités de surveillance
|
||||
|
||||
- [x] **Cache serveur intelligent** : Cache en mémoire avec invalidation manuelle
|
||||
- [x] **Export des métriques** : Export CSV/JSON avec téléchargement automatique
|
||||
- [x] **Comparaison inter-sprints** : Tendances, prédictions et recommandations
|
||||
@@ -308,11 +339,13 @@ Endpoints complexes → API Routes conservées
|
||||
### 📁 Refactoring structure des dossiers (PRIORITÉ HAUTE)
|
||||
|
||||
#### **Problème actuel**
|
||||
|
||||
- Structure mixte : `src/app/`, `src/actions/`, `src/contexts/` mais `components/`, `lib/`, `services/`, etc. à la racine
|
||||
- Alias TypeScript incohérents dans `tsconfig.json`
|
||||
- Non-conformité avec les bonnes pratiques Next.js 13+ App Router
|
||||
|
||||
#### **Plan de migration**
|
||||
|
||||
- [x] **Phase 1: Migration des dossiers**
|
||||
- [x] `mv components/ src/components/`
|
||||
- [x] `mv lib/ src/lib/`
|
||||
@@ -321,6 +354,7 @@ Endpoints complexes → API Routes conservées
|
||||
- [x] `mv services/ src/services/`
|
||||
|
||||
- [x] **Phase 2: Mise à jour tsconfig.json**
|
||||
|
||||
```json
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
@@ -350,6 +384,7 @@ Endpoints complexes → API Routes conservées
|
||||
- [x] Tester les fonctionnalités principales
|
||||
|
||||
#### **Structure finale attendue**
|
||||
|
||||
```
|
||||
src/
|
||||
├── app/ # Pages Next.js (déjà OK)
|
||||
@@ -378,12 +413,14 @@ src/
|
||||
|
||||
### Organisation cible des services:
|
||||
```
|
||||
|
||||
src/services/
|
||||
├── core/ # Services fondamentaux
|
||||
├── analytics/ # Analytics et métriques
|
||||
├── core/ # Services fondamentaux
|
||||
├── analytics/ # Analytics et métriques
|
||||
├── data-management/# Backup, système, base
|
||||
├── integrations/ # Services externes
|
||||
├── integrations/ # Services externes
|
||||
├── task-management/# Gestion des tâches
|
||||
|
||||
```
|
||||
|
||||
### Phase 1: Services Core (infrastructure) ✅
|
||||
@@ -455,8 +492,8 @@ src/services/
|
||||
|
||||
```
|
||||
|
||||
|
||||
### 🔄 Intégration TFS/Azure DevOps
|
||||
|
||||
- [x] **Lecture des Pull Requests TFS** : Synchronisation des PR comme tâches <!-- Implémenté le 22/09/2025 -->
|
||||
- [x] PR arrivent en backlog avec filtrage par team project
|
||||
- [x] Synchronisation aussi riche que Jira (statuts, assignés, commentaires)
|
||||
@@ -468,6 +505,7 @@ src/services/
|
||||
- [x] Système de plugins pour ajouter facilement de nouveaux services
|
||||
|
||||
### 📋 Daily - Gestion des tâches non cochées
|
||||
|
||||
- [x] **Section des tâches en attente** <!-- Implémenté le 21/09/2025 -->
|
||||
- [x] Liste de toutes les todos non cochées (historique complet)
|
||||
- [x] Filtrage par date (7/14/30 jours), catégorie (tâches/réunions), ancienneté
|
||||
@@ -482,12 +520,12 @@ src/services/
|
||||
- [ ] Possibilité de désarchiver une tâche
|
||||
- [ ] Champ dédié en base de données (actuellement via texte)
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 🖼️ **IMAGE DE FOND PERSONNALISÉE** ✅ TERMINÉ
|
||||
|
||||
### **Fonctionnalités implémentées :**
|
||||
|
||||
- [x] **Sélecteur d'images de fond** dans les paramètres généraux
|
||||
- [x] **Images prédéfinies** : dégradés bleu, violet, coucher de soleil, océan, forêt
|
||||
- [x] **URL personnalisée** : possibilité d'ajouter une image via URL
|
||||
@@ -498,6 +536,7 @@ src/services/
|
||||
- [x] **Interface intuitive** : sélection facile avec aperçus visuels
|
||||
|
||||
### **Architecture technique :**
|
||||
|
||||
- **Types** : `backgroundImage` ajouté à `ViewPreferences`
|
||||
- **Service** : `userPreferencesService` mis à jour
|
||||
- **Actions** : `setBackgroundImage` server action créée
|
||||
@@ -508,6 +547,7 @@ src/services/
|
||||
## 🔄 **SCHEDULER TFS** ✅ TERMINÉ
|
||||
|
||||
### **Fonctionnalités implémentées :**
|
||||
|
||||
- [x] **Scheduler TFS automatique** basé sur le modèle Jira
|
||||
- [x] **Configuration dans UserPreferences** : `tfsAutoSync` et `tfsSyncInterval`
|
||||
- [x] **Intervalles configurables** : hourly, daily, weekly
|
||||
@@ -517,6 +557,7 @@ src/services/
|
||||
- [x] **Status et monitoring** du scheduler
|
||||
|
||||
### **Architecture technique :**
|
||||
|
||||
- **Service** : `TfsScheduler` dans `src/services/integrations/tfs/scheduler.ts`
|
||||
- **Configuration** : Champs `tfsAutoSync` et `tfsSyncInterval` dans `UserPreferences`
|
||||
- **Migration** : Méthode `ensureTfsSchedulerFields()` pour compatibilité
|
||||
@@ -525,11 +566,13 @@ src/services/
|
||||
- **Logs** : Console logs détaillés pour monitoring
|
||||
|
||||
### **Différences avec Jira :**
|
||||
|
||||
- **Pas de board d'équipe** : TFS se concentre sur les Pull Requests individuelles
|
||||
- **Configuration simplifiée** : Pas de `ignoredProjects`, mais `ignoredRepositories`
|
||||
- **Focus utilisateur** : Synchronisation basée sur les PRs assignées à l'utilisateur
|
||||
|
||||
### **Interface utilisateur :**
|
||||
|
||||
- **TfsSchedulerConfig** : Configuration du scheduler automatique avec statut et contrôles
|
||||
- **TfsSync** : Interface de synchronisation manuelle avec détails et statistiques
|
||||
- **API Routes** : `/api/tfs/scheduler-config` et `/api/tfs/scheduler-status` pour la gestion
|
||||
@@ -540,6 +583,7 @@ src/services/
|
||||
## 🎨 **REFACTORING THÈME & PERSONNALISATION COULEURS**
|
||||
|
||||
### **Phase 1: Nettoyage Architecture Thème**
|
||||
|
||||
- [x] **Décider de la stratégie** : CSS Variables vs Tailwind Dark Mode vs Hybride <!-- CSS Variables choisi -->
|
||||
- [x] **Configurer tailwind.config.js** avec `darkMode: 'class'` si nécessaire <!-- Annulé : CSS Variables pur -->
|
||||
- [x] **Supprimer la double application** du thème (layout.tsx + ThemeContext + UserPreferencesContext) <!-- ThemeContext est maintenant la source unique -->
|
||||
@@ -548,4 +592,4 @@ src/services/
|
||||
- [ ] **Corriger les problèmes d'hydration** mismatch et flashs de thème
|
||||
- [ ] **Créer un système de design cohérent** avec tokens de couleur
|
||||
|
||||
---
|
||||
---
|
||||
|
||||
@@ -29,9 +29,7 @@ function TaskCard({ task }) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Button variant="primary">
|
||||
{task.title}
|
||||
</Button>
|
||||
<Button variant="primary">{task.title}</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
@@ -41,6 +39,7 @@ function TaskCard({ task }) {
|
||||
## 📦 Composants UI Disponibles
|
||||
|
||||
### Button
|
||||
|
||||
```tsx
|
||||
<Button variant="primary" size="md">Action</Button>
|
||||
<Button variant="secondary">Secondaire</Button>
|
||||
@@ -49,6 +48,7 @@ function TaskCard({ task }) {
|
||||
```
|
||||
|
||||
### Badge
|
||||
|
||||
```tsx
|
||||
<Badge variant="primary">Tag</Badge>
|
||||
<Badge variant="success">Succès</Badge>
|
||||
@@ -56,6 +56,7 @@ function TaskCard({ task }) {
|
||||
```
|
||||
|
||||
### Alert
|
||||
|
||||
```tsx
|
||||
<Alert variant="success">
|
||||
<AlertTitle>Succès</AlertTitle>
|
||||
@@ -64,12 +65,14 @@ function TaskCard({ task }) {
|
||||
```
|
||||
|
||||
### Input
|
||||
|
||||
```tsx
|
||||
<Input placeholder="Saisir..." />
|
||||
<Input variant="error" placeholder="Erreur" />
|
||||
```
|
||||
|
||||
### StyledCard
|
||||
|
||||
```tsx
|
||||
<StyledCard variant="outline" color="primary">
|
||||
Contenu avec style coloré
|
||||
@@ -77,6 +80,7 @@ function TaskCard({ task }) {
|
||||
```
|
||||
|
||||
### Avatar
|
||||
|
||||
```tsx
|
||||
// Avatar avec URL personnalisée
|
||||
<Avatar url="https://example.com/photo.jpg" email="user@example.com" name="John Doe" size={64} />
|
||||
@@ -91,14 +95,17 @@ function TaskCard({ task }) {
|
||||
## 🔄 Migration
|
||||
|
||||
### Étape 1: Identifier les patterns
|
||||
|
||||
- Rechercher `var(--` dans les composants métier
|
||||
- Identifier les patterns répétés (boutons, cartes, badges)
|
||||
|
||||
### Étape 2: Créer des composants UI
|
||||
|
||||
- Encapsuler les styles dans des composants UI
|
||||
- Utiliser des variants pour les variations
|
||||
|
||||
### Étape 3: Remplacer dans les composants métier
|
||||
|
||||
- Importer les composants UI
|
||||
- Remplacer les éléments HTML par les composants UI
|
||||
|
||||
|
||||
@@ -18,11 +18,13 @@ data/
|
||||
## 🎯 Utilisation
|
||||
|
||||
### En développement local
|
||||
|
||||
- La base de données principale est dans `prisma/dev.db`
|
||||
- Ce dossier `data/` est utilisé uniquement par Docker
|
||||
- Les sauvegardes locales sont dans `backups/` (racine du projet)
|
||||
|
||||
### En production Docker
|
||||
|
||||
- Base de données : `data/prod.db` ou `data/dev.db`
|
||||
- Sauvegardes : `data/backups/`
|
||||
- Tout ce dossier est mappé vers `/app/data` dans le conteneur
|
||||
@@ -45,12 +47,14 @@ BACKUP_STORAGE_PATH="./data/backups"
|
||||
## 🗂️ Fichiers
|
||||
|
||||
### Bases de données SQLite
|
||||
|
||||
- **prod.db** : Base de données de production
|
||||
- **dev.db** : Base de données de développement Docker
|
||||
- Format : SQLite 3
|
||||
- Contient : Tasks, Tags, User Preferences, Sync Logs, etc.
|
||||
|
||||
### Sauvegardes
|
||||
|
||||
- **Format** : `towercontrol_YYYY-MM-DDTHH-mm-ss-sssZ.db.gz`
|
||||
- **Compression** : gzip
|
||||
- **Rétention** : Configurable (défaut: 5 sauvegardes)
|
||||
|
||||
@@ -5,21 +5,21 @@ services:
|
||||
dockerfile: Dockerfile
|
||||
target: runner
|
||||
ports:
|
||||
- "3006:3000"
|
||||
- '3006:3000'
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
DATABASE_URL: "file:../data/dev.db" # Prisma
|
||||
BACKUP_DATABASE_PATH: "./data/dev.db" # Base de données à sauvegarder
|
||||
BACKUP_STORAGE_PATH: "./data/backups" # Dossier des sauvegardes
|
||||
DATABASE_URL: 'file:../data/dev.db' # Prisma
|
||||
BACKUP_DATABASE_PATH: './data/dev.db' # Base de données à sauvegarder
|
||||
BACKUP_STORAGE_PATH: './data/backups' # Dossier des sauvegardes
|
||||
TZ: Europe/Paris
|
||||
# NextAuth.js
|
||||
NEXTAUTH_SECRET: "TbwIWAmQgBcOlg7jRZrhkeEUDTpSr8Cj/Cc7W58fAyw="
|
||||
NEXTAUTH_URL: "http://localhost:3006"
|
||||
NEXTAUTH_SECRET: 'TbwIWAmQgBcOlg7jRZrhkeEUDTpSr8Cj/Cc7W58fAyw='
|
||||
NEXTAUTH_URL: 'http://localhost:3006'
|
||||
volumes:
|
||||
- ./data:/app/data # Dossier local data/ vers /app/data
|
||||
- ./data:/app/data # Dossier local data/ vers /app/data
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://localhost:3000/api/health"]
|
||||
test: ['CMD', 'wget', '-qO-', 'http://localhost:3000/api/health']
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
@@ -31,21 +31,21 @@ services:
|
||||
dockerfile: Dockerfile
|
||||
target: base
|
||||
ports:
|
||||
- "3005:3000"
|
||||
- '3005:3000'
|
||||
environment:
|
||||
NODE_ENV: development
|
||||
DATABASE_URL: "file:../data/dev.db" # Prisma
|
||||
BACKUP_DATABASE_PATH: "./data/dev.db" # Base de données à sauvegarder
|
||||
BACKUP_STORAGE_PATH: "./data/backups" # Dossier des sauvegardes
|
||||
DATABASE_URL: 'file:../data/dev.db' # Prisma
|
||||
BACKUP_DATABASE_PATH: './data/dev.db' # Base de données à sauvegarder
|
||||
BACKUP_STORAGE_PATH: './data/backups' # Dossier des sauvegardes
|
||||
TZ: Europe/Paris
|
||||
# NextAuth.js
|
||||
NEXTAUTH_SECRET: "TbwIWAmQgBcOlg7jRZrhkeEUDTpSr8Cj/Cc7W58fAyw="
|
||||
NEXTAUTH_URL: "http://localhost:3005"
|
||||
NEXTAUTH_SECRET: 'TbwIWAmQgBcOlg7jRZrhkeEUDTpSr8Cj/Cc7W58fAyw='
|
||||
NEXTAUTH_URL: 'http://localhost:3005'
|
||||
volumes:
|
||||
- .:/app # code en live
|
||||
- /app/node_modules # vol anonyme pour ne pas écraser ceux du conteneur
|
||||
- .:/app # code en live
|
||||
- /app/node_modules # vol anonyme pour ne pas écraser ceux du conteneur
|
||||
- /app/.next
|
||||
- ./data:/app/data # Dossier local data/ vers /app/data
|
||||
- ./data:/app/data # Dossier local data/ vers /app/data
|
||||
command: >
|
||||
sh -c "npm install &&
|
||||
npx prisma generate &&
|
||||
@@ -53,7 +53,6 @@ services:
|
||||
npm run dev"
|
||||
profiles:
|
||||
- dev
|
||||
|
||||
# 📁 Structure des données :
|
||||
# ./data/ -> /app/data (bind mount)
|
||||
# ├── prod.db -> Base de données production
|
||||
@@ -61,4 +60,4 @@ services:
|
||||
# └── backups/ -> Sauvegardes automatiques
|
||||
#
|
||||
# 🔧 Configuration via .env.docker
|
||||
# 📚 Documentation : ./data/README.md
|
||||
# 📚 Documentation : ./data/README.md
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { dirname } from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import { FlatCompat } from "@eslint/eslintrc";
|
||||
import { dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { FlatCompat } from '@eslint/eslintrc';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
@@ -10,14 +10,14 @@ const compat = new FlatCompat({
|
||||
});
|
||||
|
||||
const eslintConfig = [
|
||||
...compat.extends("next/core-web-vitals", "next/typescript"),
|
||||
...compat.extends('next/core-web-vitals', 'next/typescript'),
|
||||
{
|
||||
ignores: [
|
||||
"node_modules/**",
|
||||
".next/**",
|
||||
"out/**",
|
||||
"build/**",
|
||||
"next-env.d.ts",
|
||||
'node_modules/**',
|
||||
'.next/**',
|
||||
'out/**',
|
||||
'build/**',
|
||||
'next-env.d.ts',
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { NextConfig } from "next";
|
||||
import type { NextConfig } from 'next';
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
output: 'standalone',
|
||||
@@ -45,7 +45,7 @@ const nextConfig: NextConfig = {
|
||||
turbopack: {
|
||||
rules: {
|
||||
'*.sql': ['raw'],
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
const config = {
|
||||
plugins: ["@tailwindcss/postcss"],
|
||||
plugins: ['@tailwindcss/postcss'],
|
||||
};
|
||||
|
||||
export default config;
|
||||
|
||||
@@ -4,7 +4,10 @@
|
||||
* Usage: tsx scripts/backup-manager.ts [command] [options]
|
||||
*/
|
||||
|
||||
import { backupService, BackupConfig } from '../src/services/data-management/backup';
|
||||
import {
|
||||
backupService,
|
||||
BackupConfig,
|
||||
} from '../src/services/data-management/backup';
|
||||
import { backupScheduler } from '../src/services/data-management/backup-scheduler';
|
||||
import { formatDateForDisplay } from '../src/lib/date-utils';
|
||||
|
||||
@@ -57,7 +60,7 @@ OPTIONS:
|
||||
|
||||
for (let i = 1; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
|
||||
|
||||
if (arg === '--force') {
|
||||
options.force = true;
|
||||
} else if (arg === '--help') {
|
||||
@@ -70,9 +73,12 @@ OPTIONS:
|
||||
return options;
|
||||
}
|
||||
|
||||
private async confirmAction(message: string, force?: boolean): Promise<boolean> {
|
||||
private async confirmAction(
|
||||
message: string,
|
||||
force?: boolean
|
||||
): Promise<boolean> {
|
||||
if (force) return true;
|
||||
|
||||
|
||||
// Simulation d'une confirmation (en CLI réel, utiliser readline)
|
||||
console.log(`⚠️ ${message}`);
|
||||
console.log('✅ Action confirmée (--force activé ou mode auto)');
|
||||
@@ -83,12 +89,12 @@ OPTIONS:
|
||||
const units = ['B', 'KB', 'MB', 'GB'];
|
||||
let size = bytes;
|
||||
let unitIndex = 0;
|
||||
|
||||
|
||||
while (size >= 1024 && unitIndex < units.length - 1) {
|
||||
size /= 1024;
|
||||
unitIndex++;
|
||||
}
|
||||
|
||||
|
||||
return `${size.toFixed(1)} ${units[unitIndex]}`;
|
||||
}
|
||||
|
||||
@@ -170,15 +176,19 @@ OPTIONS:
|
||||
}
|
||||
|
||||
private async createBackup(force: boolean = false): Promise<void> {
|
||||
console.log('🔄 Création d\'une sauvegarde...');
|
||||
console.log("🔄 Création d'une sauvegarde...");
|
||||
const result = await backupService.createBackup('manual', force);
|
||||
|
||||
|
||||
if (result === null) {
|
||||
console.log('⏭️ Sauvegarde sautée: Aucun changement détecté depuis la dernière sauvegarde');
|
||||
console.log(' 💡 Utilisez --force pour créer une sauvegarde malgré tout');
|
||||
console.log(
|
||||
'⏭️ Sauvegarde sautée: Aucun changement détecté depuis la dernière sauvegarde'
|
||||
);
|
||||
console.log(
|
||||
' 💡 Utilisez --force pour créer une sauvegarde malgré tout'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (result.status === 'success') {
|
||||
console.log(`✅ Sauvegarde créée: ${result.filename}`);
|
||||
console.log(` Taille: ${this.formatFileSize(result.size)}`);
|
||||
@@ -194,24 +204,28 @@ OPTIONS:
|
||||
private async listBackups(): Promise<void> {
|
||||
console.log('📋 Liste des sauvegardes:\n');
|
||||
const backups = await backupService.listBackups();
|
||||
|
||||
|
||||
if (backups.length === 0) {
|
||||
console.log(' Aucune sauvegarde disponible');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`${'Nom'.padEnd(40)} ${'Taille'.padEnd(10)} ${'Type'.padEnd(12)} ${'Date'}`);
|
||||
console.log(
|
||||
`${'Nom'.padEnd(40)} ${'Taille'.padEnd(10)} ${'Type'.padEnd(12)} ${'Date'}`
|
||||
);
|
||||
console.log('─'.repeat(80));
|
||||
|
||||
|
||||
for (const backup of backups) {
|
||||
const name = backup.filename.padEnd(40);
|
||||
const size = this.formatFileSize(backup.size).padEnd(10);
|
||||
const type = (backup.type === 'manual' ? 'Manuelle' : 'Automatique').padEnd(12);
|
||||
const type = (
|
||||
backup.type === 'manual' ? 'Manuelle' : 'Automatique'
|
||||
).padEnd(12);
|
||||
const date = this.formatDate(backup.createdAt);
|
||||
|
||||
|
||||
console.log(`${name} ${size} ${type} ${date}`);
|
||||
}
|
||||
|
||||
|
||||
console.log(`\n📊 Total: ${backups.length} sauvegarde(s)`);
|
||||
}
|
||||
|
||||
@@ -220,7 +234,7 @@ OPTIONS:
|
||||
`Supprimer la sauvegarde "${filename}" ?`,
|
||||
force
|
||||
);
|
||||
|
||||
|
||||
if (!confirmed) {
|
||||
console.log('❌ Suppression annulée');
|
||||
return;
|
||||
@@ -230,12 +244,15 @@ OPTIONS:
|
||||
console.log(`✅ Sauvegarde supprimée: ${filename}`);
|
||||
}
|
||||
|
||||
private async restoreBackup(filename: string, force?: boolean): Promise<void> {
|
||||
private async restoreBackup(
|
||||
filename: string,
|
||||
force?: boolean
|
||||
): Promise<void> {
|
||||
const confirmed = await this.confirmAction(
|
||||
`Restaurer la base de données depuis "${filename}" ? ATTENTION: Cela remplacera toutes les données actuelles !`,
|
||||
force
|
||||
);
|
||||
|
||||
|
||||
if (!confirmed) {
|
||||
console.log('❌ Restauration annulée');
|
||||
return;
|
||||
@@ -247,7 +264,7 @@ OPTIONS:
|
||||
}
|
||||
|
||||
private async verifyDatabase(): Promise<void> {
|
||||
console.log('🔍 Vérification de l\'intégrité de la base...');
|
||||
console.log("🔍 Vérification de l'intégrité de la base...");
|
||||
await backupService.verifyDatabaseHealth();
|
||||
console.log('✅ Base de données vérifiée avec succès');
|
||||
}
|
||||
@@ -255,21 +272,29 @@ OPTIONS:
|
||||
private async showConfig(): Promise<void> {
|
||||
const config = backupService.getConfig();
|
||||
const status = backupScheduler.getStatus();
|
||||
|
||||
|
||||
console.log('⚙️ Configuration des sauvegardes:\n');
|
||||
console.log(` Activé: ${config.enabled ? '✅ Oui' : '❌ Non'}`);
|
||||
console.log(
|
||||
` Activé: ${config.enabled ? '✅ Oui' : '❌ Non'}`
|
||||
);
|
||||
console.log(` Fréquence: ${config.interval}`);
|
||||
console.log(` Max sauvegardes: ${config.maxBackups}`);
|
||||
console.log(` Compression: ${config.compression ? '✅ Oui' : '❌ Non'}`);
|
||||
console.log(
|
||||
` Compression: ${config.compression ? '✅ Oui' : '❌ Non'}`
|
||||
);
|
||||
console.log(` Chemin: ${config.backupPath}`);
|
||||
console.log(`\n📊 Statut du planificateur:`);
|
||||
console.log(` En cours: ${status.isRunning ? '✅ Oui' : '❌ Non'}`);
|
||||
console.log(` Prochaine: ${status.nextBackup ? this.formatDate(status.nextBackup) : 'Non planifiée'}`);
|
||||
console.log(
|
||||
` En cours: ${status.isRunning ? '✅ Oui' : '❌ Non'}`
|
||||
);
|
||||
console.log(
|
||||
` Prochaine: ${status.nextBackup ? this.formatDate(status.nextBackup) : 'Non planifiée'}`
|
||||
);
|
||||
}
|
||||
|
||||
private async setConfig(configString: string): Promise<void> {
|
||||
const [key, value] = configString.split('=');
|
||||
|
||||
|
||||
if (!key || !value) {
|
||||
console.error('❌ Format invalide. Utilisez: key=value');
|
||||
process.exit(1);
|
||||
@@ -283,7 +308,9 @@ OPTIONS:
|
||||
break;
|
||||
case 'interval':
|
||||
if (!['hourly', 'daily', 'weekly'].includes(value)) {
|
||||
console.error('❌ Interval invalide. Utilisez: hourly, daily, ou weekly');
|
||||
console.error(
|
||||
'❌ Interval invalide. Utilisez: hourly, daily, ou weekly'
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
newConfig.interval = value as BackupConfig['interval'];
|
||||
@@ -306,7 +333,7 @@ OPTIONS:
|
||||
|
||||
backupService.updateConfig(newConfig);
|
||||
console.log(`✅ Configuration mise à jour: ${key} = ${value}`);
|
||||
|
||||
|
||||
// Redémarrer le scheduler si nécessaire
|
||||
if (key === 'enabled' || key === 'interval') {
|
||||
backupScheduler.restart();
|
||||
@@ -326,12 +353,18 @@ OPTIONS:
|
||||
|
||||
private async schedulerStatus(): Promise<void> {
|
||||
const status = backupScheduler.getStatus();
|
||||
|
||||
|
||||
console.log('📊 Statut du planificateur:\n');
|
||||
console.log(` État: ${status.isRunning ? '✅ Actif' : '❌ Arrêté'}`);
|
||||
console.log(` Activé: ${status.isEnabled ? '✅ Oui' : '❌ Non'}`);
|
||||
console.log(
|
||||
` État: ${status.isRunning ? '✅ Actif' : '❌ Arrêté'}`
|
||||
);
|
||||
console.log(
|
||||
` Activé: ${status.isEnabled ? '✅ Oui' : '❌ Non'}`
|
||||
);
|
||||
console.log(` Fréquence: ${status.interval}`);
|
||||
console.log(` Prochaine: ${status.nextBackup ? this.formatDate(status.nextBackup) : 'Non planifiée'}`);
|
||||
console.log(
|
||||
` Prochaine: ${status.nextBackup ? this.formatDate(status.nextBackup) : 'Non planifiée'}`
|
||||
);
|
||||
console.log(` Max sauvegardes: ${status.maxBackups}`);
|
||||
}
|
||||
}
|
||||
@@ -340,7 +373,7 @@ OPTIONS:
|
||||
if (require.main === module) {
|
||||
const cli = new BackupManagerCLI();
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
|
||||
cli.run(args).catch((error) => {
|
||||
console.error('❌ Erreur fatale:', error);
|
||||
process.exit(1);
|
||||
|
||||
@@ -10,18 +10,18 @@ import * as readline from 'readline';
|
||||
|
||||
function displayCacheStats() {
|
||||
console.log('\n📊 === STATISTIQUES DU CACHE JIRA ANALYTICS ===');
|
||||
|
||||
|
||||
const stats = jiraAnalyticsCache.getStats();
|
||||
|
||||
|
||||
console.log(`\n📈 Total des entrées: ${stats.totalEntries}`);
|
||||
|
||||
|
||||
if (stats.projects.length === 0) {
|
||||
console.log('📭 Aucune donnée en cache');
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
console.log('\n📋 Projets en cache:');
|
||||
stats.projects.forEach(project => {
|
||||
stats.projects.forEach((project) => {
|
||||
const status = project.isExpired ? '❌ EXPIRÉ' : '✅ VALIDE';
|
||||
console.log(` • ${project.projectKey}:`);
|
||||
console.log(` - Âge: ${project.age}`);
|
||||
@@ -44,13 +44,13 @@ function displayCacheActions() {
|
||||
|
||||
async function monitorRealtime() {
|
||||
console.log('\n👀 Surveillance en temps réel (Ctrl+C pour arrêter)...');
|
||||
|
||||
|
||||
const interval = setInterval(() => {
|
||||
console.clear();
|
||||
displayCacheStats();
|
||||
console.log('\n⏰ Mise à jour toutes les 5 secondes...');
|
||||
}, 5000);
|
||||
|
||||
|
||||
// Gérer l'arrêt propre
|
||||
process.on('SIGINT', () => {
|
||||
clearInterval(interval);
|
||||
@@ -61,74 +61,77 @@ async function monitorRealtime() {
|
||||
|
||||
async function main() {
|
||||
console.log('🚀 Cache Monitor Jira Analytics');
|
||||
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const command = args[0];
|
||||
|
||||
|
||||
switch (command) {
|
||||
case 'stats':
|
||||
displayCacheStats();
|
||||
break;
|
||||
|
||||
|
||||
case 'cleanup':
|
||||
console.log('\n🧹 Nettoyage forcé du cache...');
|
||||
const cleaned = jiraAnalyticsCache.forceCleanup();
|
||||
console.log(`✅ ${cleaned} entrées supprimées`);
|
||||
break;
|
||||
|
||||
|
||||
case 'clear':
|
||||
console.log('\n🗑️ Invalidation de tout le cache...');
|
||||
jiraAnalyticsCache.invalidateAll();
|
||||
console.log('✅ Cache vidé');
|
||||
break;
|
||||
|
||||
|
||||
case 'monitor':
|
||||
await monitorRealtime();
|
||||
break;
|
||||
|
||||
|
||||
default:
|
||||
displayCacheStats();
|
||||
displayCacheActions();
|
||||
|
||||
|
||||
// Interface interactive simple
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout
|
||||
output: process.stdout,
|
||||
});
|
||||
|
||||
|
||||
const askAction = () => {
|
||||
rl.question('\nChoisissez une action (1-5): ', async (answer: string) => {
|
||||
switch (answer.trim()) {
|
||||
case '1':
|
||||
displayCacheStats();
|
||||
askAction();
|
||||
break;
|
||||
case '2':
|
||||
const cleaned = jiraAnalyticsCache.forceCleanup();
|
||||
console.log(`✅ ${cleaned} entrées supprimées`);
|
||||
askAction();
|
||||
break;
|
||||
case '3':
|
||||
jiraAnalyticsCache.invalidateAll();
|
||||
console.log('✅ Cache vidé');
|
||||
askAction();
|
||||
break;
|
||||
case '4':
|
||||
rl.close();
|
||||
await monitorRealtime();
|
||||
break;
|
||||
case '5':
|
||||
console.log('👋 Au revoir !');
|
||||
rl.close();
|
||||
process.exit(0);
|
||||
break;
|
||||
default:
|
||||
console.log('❌ Action invalide');
|
||||
askAction();
|
||||
rl.question(
|
||||
'\nChoisissez une action (1-5): ',
|
||||
async (answer: string) => {
|
||||
switch (answer.trim()) {
|
||||
case '1':
|
||||
displayCacheStats();
|
||||
askAction();
|
||||
break;
|
||||
case '2':
|
||||
const cleaned = jiraAnalyticsCache.forceCleanup();
|
||||
console.log(`✅ ${cleaned} entrées supprimées`);
|
||||
askAction();
|
||||
break;
|
||||
case '3':
|
||||
jiraAnalyticsCache.invalidateAll();
|
||||
console.log('✅ Cache vidé');
|
||||
askAction();
|
||||
break;
|
||||
case '4':
|
||||
rl.close();
|
||||
await monitorRealtime();
|
||||
break;
|
||||
case '5':
|
||||
console.log('👋 Au revoir !');
|
||||
rl.close();
|
||||
process.exit(0);
|
||||
break;
|
||||
default:
|
||||
console.log('❌ Action invalide');
|
||||
askAction();
|
||||
}
|
||||
}
|
||||
});
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
askAction();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,9 +10,13 @@ async function resetDatabase() {
|
||||
try {
|
||||
// Compter les tâches avant suppression
|
||||
const beforeCount = await prisma.task.count();
|
||||
const manualCount = await prisma.task.count({ where: { source: 'manual' } });
|
||||
const remindersCount = await prisma.task.count({ where: { source: 'reminders' } });
|
||||
|
||||
const manualCount = await prisma.task.count({
|
||||
where: { source: 'manual' },
|
||||
});
|
||||
const remindersCount = await prisma.task.count({
|
||||
where: { source: 'reminders' },
|
||||
});
|
||||
|
||||
console.log(`📊 État actuel:`);
|
||||
console.log(` Total: ${beforeCount} tâches`);
|
||||
console.log(` Manuelles: ${manualCount} tâches`);
|
||||
@@ -22,8 +26,8 @@ async function resetDatabase() {
|
||||
// Supprimer toutes les tâches de synchronisation
|
||||
const deletedTasks = await prisma.task.deleteMany({
|
||||
where: {
|
||||
source: 'reminders'
|
||||
}
|
||||
source: 'reminders',
|
||||
},
|
||||
});
|
||||
|
||||
console.log(`✅ Supprimé ${deletedTasks.count} tâches de synchronisation`);
|
||||
@@ -38,11 +42,11 @@ async function resetDatabase() {
|
||||
|
||||
// Compter après nettoyage
|
||||
const afterCount = await prisma.task.count();
|
||||
|
||||
|
||||
console.log('');
|
||||
console.log('🎉 Base de données nettoyée !');
|
||||
console.log(`📊 Résultat: ${afterCount} tâches restantes`);
|
||||
|
||||
|
||||
// Afficher les tâches restantes
|
||||
if (afterCount > 0) {
|
||||
console.log('');
|
||||
@@ -51,30 +55,32 @@ async function resetDatabase() {
|
||||
include: {
|
||||
taskTags: {
|
||||
include: {
|
||||
tag: true
|
||||
}
|
||||
}
|
||||
tag: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: 'desc' }
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
|
||||
|
||||
remainingTasks.forEach((task, index) => {
|
||||
const statusEmoji = {
|
||||
'todo': '⏳',
|
||||
'in_progress': '🔄',
|
||||
'done': '✅',
|
||||
'cancelled': '❌'
|
||||
}[task.status] || '❓';
|
||||
|
||||
const statusEmoji =
|
||||
{
|
||||
todo: '⏳',
|
||||
in_progress: '🔄',
|
||||
done: '✅',
|
||||
cancelled: '❌',
|
||||
}[task.status] || '❓';
|
||||
|
||||
// Utiliser les relations TaskTag
|
||||
const tags = task.taskTags ? task.taskTags.map(tt => tt.tag.name) : [];
|
||||
|
||||
const tags = task.taskTags
|
||||
? task.taskTags.map((tt) => tt.tag.name)
|
||||
: [];
|
||||
|
||||
const tagsStr = tags.length > 0 ? ` [${tags.join(', ')}]` : '';
|
||||
|
||||
|
||||
console.log(` ${index + 1}. ${statusEmoji} ${task.title}${tagsStr}`);
|
||||
});
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Erreur lors du reset:', error);
|
||||
throw error;
|
||||
@@ -83,14 +89,16 @@ async function resetDatabase() {
|
||||
|
||||
// Exécuter le script
|
||||
if (require.main === module) {
|
||||
resetDatabase().then(() => {
|
||||
console.log('');
|
||||
console.log('✨ Reset terminé avec succès !');
|
||||
process.exit(0);
|
||||
}).catch((error) => {
|
||||
console.error('💥 Erreur fatale:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
resetDatabase()
|
||||
.then(() => {
|
||||
console.log('');
|
||||
console.log('✨ Reset terminé avec succès !');
|
||||
process.exit(0);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('💥 Erreur fatale:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
export { resetDatabase };
|
||||
|
||||
@@ -11,19 +11,21 @@ async function seedTestData() {
|
||||
const testTasks = [
|
||||
{
|
||||
title: '🎨 Design System Implementation',
|
||||
description: 'Create and implement a comprehensive design system with reusable components',
|
||||
description:
|
||||
'Create and implement a comprehensive design system with reusable components',
|
||||
status: 'in_progress' as TaskStatus,
|
||||
priority: 'high' as TaskPriority,
|
||||
tags: ['design', 'ui', 'frontend'],
|
||||
dueDate: new Date('2025-12-31')
|
||||
dueDate: new Date('2025-12-31'),
|
||||
},
|
||||
{
|
||||
title: '🔧 API Performance Optimization',
|
||||
description: 'Optimize API endpoints response time and implement pagination',
|
||||
description:
|
||||
'Optimize API endpoints response time and implement pagination',
|
||||
status: 'todo' as TaskStatus,
|
||||
priority: 'medium' as TaskPriority,
|
||||
tags: ['backend', 'performance', 'api'],
|
||||
dueDate: new Date('2025-12-15')
|
||||
dueDate: new Date('2025-12-15'),
|
||||
},
|
||||
{
|
||||
title: '✅ Test Coverage Improvement',
|
||||
@@ -31,7 +33,7 @@ async function seedTestData() {
|
||||
status: 'todo' as TaskStatus,
|
||||
priority: 'medium' as TaskPriority,
|
||||
tags: ['testing', 'quality'],
|
||||
dueDate: new Date('2025-12-20')
|
||||
dueDate: new Date('2025-12-20'),
|
||||
},
|
||||
{
|
||||
title: '📱 Mobile Responsive Design',
|
||||
@@ -39,7 +41,7 @@ async function seedTestData() {
|
||||
status: 'todo' as TaskStatus,
|
||||
priority: 'high' as TaskPriority,
|
||||
tags: ['frontend', 'mobile', 'ui'],
|
||||
dueDate: new Date('2025-12-10')
|
||||
dueDate: new Date('2025-12-10'),
|
||||
},
|
||||
{
|
||||
title: '🔒 Security Audit',
|
||||
@@ -47,8 +49,8 @@ async function seedTestData() {
|
||||
status: 'backlog' as TaskStatus,
|
||||
priority: 'urgent' as TaskPriority,
|
||||
tags: ['security', 'audit'],
|
||||
dueDate: new Date('2026-01-15')
|
||||
}
|
||||
dueDate: new Date('2026-01-15'),
|
||||
},
|
||||
];
|
||||
|
||||
let createdCount = 0;
|
||||
@@ -57,34 +59,39 @@ async function seedTestData() {
|
||||
for (const taskData of testTasks) {
|
||||
try {
|
||||
const task = await tasksService.createTask(taskData);
|
||||
|
||||
|
||||
const statusEmoji = {
|
||||
'backlog': '📋',
|
||||
'todo': '⏳',
|
||||
'in_progress': '🔄',
|
||||
'freeze': '🧊',
|
||||
'done': '✅',
|
||||
'cancelled': '❌',
|
||||
'archived': '📦'
|
||||
backlog: '📋',
|
||||
todo: '⏳',
|
||||
in_progress: '🔄',
|
||||
freeze: '🧊',
|
||||
done: '✅',
|
||||
cancelled: '❌',
|
||||
archived: '📦',
|
||||
}[task.status];
|
||||
|
||||
|
||||
const priorityEmoji = {
|
||||
'low': '🔵',
|
||||
'medium': '🟡',
|
||||
'high': '🔴',
|
||||
'urgent': '🚨'
|
||||
low: '🔵',
|
||||
medium: '🟡',
|
||||
high: '🔴',
|
||||
urgent: '🚨',
|
||||
}[task.priority];
|
||||
|
||||
|
||||
console.log(` ${statusEmoji} ${priorityEmoji} ${task.title}`);
|
||||
console.log(` Tags: ${task.tags?.join(', ') || 'aucun'}`);
|
||||
if (task.dueDate) {
|
||||
console.log(` Échéance: ${task.dueDate.toLocaleDateString('fr-FR')}`);
|
||||
console.log(
|
||||
` Échéance: ${task.dueDate.toLocaleDateString('fr-FR')}`
|
||||
);
|
||||
}
|
||||
console.log('');
|
||||
|
||||
|
||||
createdCount++;
|
||||
} catch (error) {
|
||||
console.error(` ❌ Erreur pour "${taskData.title}":`, error instanceof Error ? error.message : error);
|
||||
console.error(
|
||||
` ❌ Erreur pour "${taskData.title}":`,
|
||||
error instanceof Error ? error.message : error
|
||||
);
|
||||
errorCount++;
|
||||
}
|
||||
}
|
||||
@@ -92,7 +99,7 @@ async function seedTestData() {
|
||||
console.log('📊 Résumé:');
|
||||
console.log(` ✅ Tâches créées: ${createdCount}`);
|
||||
console.log(` ❌ Erreurs: ${errorCount}`);
|
||||
|
||||
|
||||
// Afficher les stats finales
|
||||
const stats = await tasksService.getTaskStats();
|
||||
console.log('');
|
||||
@@ -107,14 +114,16 @@ async function seedTestData() {
|
||||
|
||||
// Exécuter le script
|
||||
if (require.main === module) {
|
||||
seedTestData().then(() => {
|
||||
console.log('');
|
||||
console.log('✨ Données de test ajoutées avec succès !');
|
||||
process.exit(0);
|
||||
}).catch((error) => {
|
||||
console.error('💥 Erreur fatale:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
seedTestData()
|
||||
.then(() => {
|
||||
console.log('');
|
||||
console.log('✨ Données de test ajoutées avec succès !');
|
||||
process.exit(0);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('💥 Erreur fatale:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
export { seedTestData };
|
||||
|
||||
@@ -10,13 +10,18 @@ import { userPreferencesService } from '../src/services/core/user-preferences';
|
||||
|
||||
async function testJiraFields() {
|
||||
console.log('🔍 Identification des champs personnalisés Jira\n');
|
||||
|
||||
|
||||
try {
|
||||
// Récupérer la config Jira pour l'utilisateur spécifié ou 'default'
|
||||
const userId = process.argv[2] || 'default';
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(userId);
|
||||
|
||||
if (!jiraConfig.enabled || !jiraConfig.baseUrl || !jiraConfig.email || !jiraConfig.apiToken) {
|
||||
|
||||
if (
|
||||
!jiraConfig.enabled ||
|
||||
!jiraConfig.baseUrl ||
|
||||
!jiraConfig.email ||
|
||||
!jiraConfig.apiToken
|
||||
) {
|
||||
console.log('❌ Configuration Jira manquante');
|
||||
return;
|
||||
}
|
||||
@@ -27,14 +32,14 @@ async function testJiraFields() {
|
||||
}
|
||||
|
||||
console.log(`📋 Analyse du projet: ${jiraConfig.projectKey}`);
|
||||
|
||||
|
||||
// Créer le service Jira
|
||||
const jiraService = new JiraService(jiraConfig);
|
||||
|
||||
|
||||
// Récupérer un seul ticket pour analyser tous ses champs
|
||||
const jql = `project = "${jiraConfig.projectKey}" ORDER BY updated DESC`;
|
||||
const issues = await jiraService.searchIssues(jql);
|
||||
|
||||
|
||||
if (issues.length === 0) {
|
||||
console.log('❌ Aucun ticket trouvé');
|
||||
return;
|
||||
@@ -44,17 +49,23 @@ async function testJiraFields() {
|
||||
console.log(`\n📄 Analyse du ticket: ${firstIssue.key}`);
|
||||
console.log(`Titre: ${firstIssue.summary}`);
|
||||
console.log(`Type: ${firstIssue.issuetype.name}`);
|
||||
|
||||
|
||||
// Afficher les story points actuels
|
||||
console.log(`\n🎯 Story Points actuels: ${firstIssue.storyPoints || 'Non défini'}`);
|
||||
|
||||
console.log(
|
||||
`\n🎯 Story Points actuels: ${firstIssue.storyPoints || 'Non défini'}`
|
||||
);
|
||||
|
||||
console.log('\n💡 Pour identifier le bon champ story points:');
|
||||
console.log('1. Connectez-vous à votre instance Jira');
|
||||
console.log('2. Allez dans Administration > Projets > [Votre projet]');
|
||||
console.log('3. Regardez dans "Champs" ou "Story Points"');
|
||||
console.log('4. Notez le nom du champ personnalisé (ex: customfield_10003)');
|
||||
console.log('5. Modifiez le code dans src/services/integrations/jira/jira.ts ligne 167');
|
||||
|
||||
console.log(
|
||||
'4. Notez le nom du champ personnalisé (ex: customfield_10003)'
|
||||
);
|
||||
console.log(
|
||||
'5. Modifiez le code dans src/services/integrations/jira/jira.ts ligne 167'
|
||||
);
|
||||
|
||||
console.log('\n🔧 Champs couramment utilisés pour les story points:');
|
||||
console.log('• customfield_10002 (par défaut)');
|
||||
console.log('• customfield_10003');
|
||||
@@ -65,7 +76,7 @@ async function testJiraFields() {
|
||||
console.log('• customfield_10008');
|
||||
console.log('• customfield_10009');
|
||||
console.log('• customfield_10010');
|
||||
|
||||
|
||||
console.log('\n📝 Alternative: Utiliser les estimations par type');
|
||||
console.log('Le système utilise déjà des estimations intelligentes:');
|
||||
console.log('• Epic: 13 points');
|
||||
@@ -73,7 +84,6 @@ async function testJiraFields() {
|
||||
console.log('• Task: 3 points');
|
||||
console.log('• Bug: 2 points');
|
||||
console.log('• Subtask: 1 point');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Erreur lors du test:', error);
|
||||
}
|
||||
@@ -81,4 +91,3 @@ async function testJiraFields() {
|
||||
|
||||
// Exécution du script
|
||||
testJiraFields().catch(console.error);
|
||||
|
||||
|
||||
@@ -10,13 +10,18 @@ import { userPreferencesService } from '../src/services/core/user-preferences';
|
||||
|
||||
async function testStoryPoints() {
|
||||
console.log('🧪 Test de récupération des story points Jira\n');
|
||||
|
||||
|
||||
try {
|
||||
// Récupérer la config Jira pour l'utilisateur spécifié ou 'default'
|
||||
const userId = process.argv[2] || 'default';
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(userId);
|
||||
|
||||
if (!jiraConfig.enabled || !jiraConfig.baseUrl || !jiraConfig.email || !jiraConfig.apiToken) {
|
||||
|
||||
if (
|
||||
!jiraConfig.enabled ||
|
||||
!jiraConfig.baseUrl ||
|
||||
!jiraConfig.email ||
|
||||
!jiraConfig.apiToken
|
||||
) {
|
||||
console.log('❌ Configuration Jira manquante');
|
||||
return;
|
||||
}
|
||||
@@ -27,41 +32,47 @@ async function testStoryPoints() {
|
||||
}
|
||||
|
||||
console.log(`📋 Test sur le projet: ${jiraConfig.projectKey}`);
|
||||
|
||||
|
||||
// Créer le service Jira
|
||||
const jiraService = new JiraService(jiraConfig);
|
||||
|
||||
|
||||
// Récupérer quelques tickets pour tester
|
||||
const jql = `project = "${jiraConfig.projectKey}" ORDER BY updated DESC`;
|
||||
const issues = await jiraService.searchIssues(jql);
|
||||
|
||||
|
||||
console.log(`\n📊 Analyse de ${issues.length} tickets:\n`);
|
||||
|
||||
|
||||
let totalStoryPoints = 0;
|
||||
let ticketsWithStoryPoints = 0;
|
||||
let ticketsWithoutStoryPoints = 0;
|
||||
|
||||
|
||||
const storyPointsDistribution: Record<number, number> = {};
|
||||
const typeDistribution: Record<string, { count: number; totalPoints: number }> = {};
|
||||
|
||||
const typeDistribution: Record<
|
||||
string,
|
||||
{ count: number; totalPoints: number }
|
||||
> = {};
|
||||
|
||||
issues.slice(0, 20).forEach((issue, index) => {
|
||||
const storyPoints = issue.storyPoints || 0;
|
||||
const issueType = issue.issuetype.name;
|
||||
|
||||
|
||||
console.log(`${index + 1}. ${issue.key} (${issueType})`);
|
||||
console.log(` Titre: ${issue.summary.substring(0, 50)}...`);
|
||||
console.log(` Story Points: ${storyPoints > 0 ? storyPoints : 'Non défini'}`);
|
||||
console.log(
|
||||
` Story Points: ${storyPoints > 0 ? storyPoints : 'Non défini'}`
|
||||
);
|
||||
console.log(` Statut: ${issue.status.name}`);
|
||||
console.log('');
|
||||
|
||||
|
||||
if (storyPoints > 0) {
|
||||
ticketsWithStoryPoints++;
|
||||
totalStoryPoints += storyPoints;
|
||||
storyPointsDistribution[storyPoints] = (storyPointsDistribution[storyPoints] || 0) + 1;
|
||||
storyPointsDistribution[storyPoints] =
|
||||
(storyPointsDistribution[storyPoints] || 0) + 1;
|
||||
} else {
|
||||
ticketsWithoutStoryPoints++;
|
||||
}
|
||||
|
||||
|
||||
// Distribution par type
|
||||
if (!typeDistribution[issueType]) {
|
||||
typeDistribution[issueType] = { count: 0, totalPoints: 0 };
|
||||
@@ -69,37 +80,47 @@ async function testStoryPoints() {
|
||||
typeDistribution[issueType].count++;
|
||||
typeDistribution[issueType].totalPoints += storyPoints;
|
||||
});
|
||||
|
||||
|
||||
console.log('📈 === RÉSUMÉ ===\n');
|
||||
console.log(`Total tickets analysés: ${issues.length}`);
|
||||
console.log(`Tickets avec story points: ${ticketsWithStoryPoints}`);
|
||||
console.log(`Tickets sans story points: ${ticketsWithoutStoryPoints}`);
|
||||
console.log(`Total story points: ${totalStoryPoints}`);
|
||||
console.log(`Moyenne par ticket: ${issues.length > 0 ? (totalStoryPoints / issues.length).toFixed(2) : 0}`);
|
||||
|
||||
console.log(
|
||||
`Moyenne par ticket: ${issues.length > 0 ? (totalStoryPoints / issues.length).toFixed(2) : 0}`
|
||||
);
|
||||
|
||||
console.log('\n📊 Distribution des story points:');
|
||||
Object.entries(storyPointsDistribution)
|
||||
.sort(([a], [b]) => parseInt(a) - parseInt(b))
|
||||
.forEach(([points, count]) => {
|
||||
console.log(` ${points} points: ${count} tickets`);
|
||||
});
|
||||
|
||||
|
||||
console.log('\n🏷️ Distribution par type:');
|
||||
Object.entries(typeDistribution)
|
||||
.sort(([,a], [,b]) => b.count - a.count)
|
||||
.sort(([, a], [, b]) => b.count - a.count)
|
||||
.forEach(([type, stats]) => {
|
||||
const avgPoints = stats.count > 0 ? (stats.totalPoints / stats.count).toFixed(2) : '0';
|
||||
console.log(` ${type}: ${stats.count} tickets, ${stats.totalPoints} points total, ${avgPoints} points moyen`);
|
||||
const avgPoints =
|
||||
stats.count > 0 ? (stats.totalPoints / stats.count).toFixed(2) : '0';
|
||||
console.log(
|
||||
` ${type}: ${stats.count} tickets, ${stats.totalPoints} points total, ${avgPoints} points moyen`
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
if (ticketsWithoutStoryPoints > 0) {
|
||||
console.log('\n⚠️ Recommandations:');
|
||||
console.log('• Vérifiez que le champ "Story Points" est configuré dans votre projet Jira');
|
||||
console.log(
|
||||
'• Vérifiez que le champ "Story Points" est configuré dans votre projet Jira'
|
||||
);
|
||||
console.log('• Le champ par défaut est "customfield_10002"');
|
||||
console.log('• Si votre projet utilise un autre champ, modifiez le code dans jira.ts');
|
||||
console.log('• En attendant, le système utilise des estimations basées sur le type de ticket');
|
||||
console.log(
|
||||
'• Si votre projet utilise un autre champ, modifiez le code dans jira.ts'
|
||||
);
|
||||
console.log(
|
||||
'• En attendant, le système utilise des estimations basées sur le type de ticket'
|
||||
);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Erreur lors du test:', error);
|
||||
}
|
||||
@@ -107,4 +128,3 @@ async function testStoryPoints() {
|
||||
|
||||
// Exécution du script
|
||||
testStoryPoints().catch(console.error);
|
||||
|
||||
|
||||
@@ -6,28 +6,32 @@ import { revalidatePath } from 'next/cache';
|
||||
export async function createBackupAction(force: boolean = false) {
|
||||
try {
|
||||
const result = await backupService.createBackup('manual', force);
|
||||
|
||||
|
||||
// Invalider le cache de la page pour forcer le rechargement des données SSR
|
||||
revalidatePath('/settings/backup');
|
||||
|
||||
|
||||
if (result === null) {
|
||||
return {
|
||||
success: true,
|
||||
skipped: true,
|
||||
message: 'Sauvegarde sautée : aucun changement détecté. Utilisez "Forcer" pour créer malgré tout.'
|
||||
message:
|
||||
'Sauvegarde sautée : aucun changement détecté. Utilisez "Forcer" pour créer malgré tout.',
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: result,
|
||||
message: `Sauvegarde créée : ${result.filename}`
|
||||
message: `Sauvegarde créée : ${result.filename}`,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Failed to create backup:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur lors de la création de la sauvegarde'
|
||||
error:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Erreur lors de la création de la sauvegarde',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -37,13 +41,13 @@ export async function verifyDatabaseAction() {
|
||||
await backupService.verifyDatabaseHealth();
|
||||
return {
|
||||
success: true,
|
||||
message: 'Intégrité vérifiée'
|
||||
message: 'Intégrité vérifiée',
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Database verification failed:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Vérification échouée'
|
||||
error: error instanceof Error ? error.message : 'Vérification échouée',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
'use server';
|
||||
|
||||
import { dailyService } from '@/services/task-management/daily';
|
||||
import { UpdateDailyCheckboxData, DailyCheckbox, CreateDailyCheckboxData } from '@/lib/types';
|
||||
import {
|
||||
UpdateDailyCheckboxData,
|
||||
DailyCheckbox,
|
||||
CreateDailyCheckboxData,
|
||||
} from '@/lib/types';
|
||||
import { revalidatePath } from 'next/cache';
|
||||
import { getToday, getPreviousWorkday, parseDate, normalizeDate } from '@/lib/date-utils';
|
||||
import {
|
||||
getToday,
|
||||
getPreviousWorkday,
|
||||
parseDate,
|
||||
normalizeDate,
|
||||
} from '@/lib/date-utils';
|
||||
|
||||
/**
|
||||
* Toggle l'état d'une checkbox
|
||||
@@ -18,41 +27,44 @@ export async function toggleCheckbox(checkboxId: string): Promise<{
|
||||
// En absence de getCheckboxById, nous allons essayer de la trouver via une vue daily
|
||||
// Pour l'instant, nous allons simplement toggle via updateCheckbox
|
||||
// (le front-end gère déjà l'état optimiste)
|
||||
|
||||
|
||||
// Récupérer toutes les checkboxes d'aujourd'hui et hier pour trouver celle à toggle
|
||||
const today = getToday();
|
||||
const dailyView = await dailyService.getDailyView(today);
|
||||
|
||||
let checkbox = dailyView.today.find(cb => cb.id === checkboxId);
|
||||
|
||||
let checkbox = dailyView.today.find((cb) => cb.id === checkboxId);
|
||||
if (!checkbox) {
|
||||
checkbox = dailyView.yesterday.find(cb => cb.id === checkboxId);
|
||||
checkbox = dailyView.yesterday.find((cb) => cb.id === checkboxId);
|
||||
}
|
||||
|
||||
|
||||
if (!checkbox) {
|
||||
return { success: false, error: 'Checkbox non trouvée' };
|
||||
}
|
||||
|
||||
|
||||
// Toggle l'état
|
||||
const updatedCheckbox = await dailyService.updateCheckbox(checkboxId, {
|
||||
isChecked: !checkbox.isChecked
|
||||
isChecked: !checkbox.isChecked,
|
||||
});
|
||||
|
||||
|
||||
revalidatePath('/daily');
|
||||
return { success: true, data: updatedCheckbox };
|
||||
} catch (error) {
|
||||
console.error('Erreur toggleCheckbox:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Ajoute une checkbox pour aujourd'hui
|
||||
*/
|
||||
export async function addTodayCheckbox(content: string, type?: 'task' | 'meeting', taskId?: string): Promise<{
|
||||
export async function addTodayCheckbox(
|
||||
content: string,
|
||||
type?: 'task' | 'meeting',
|
||||
taskId?: string
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
data?: DailyCheckbox;
|
||||
error?: string;
|
||||
@@ -62,16 +74,16 @@ export async function addTodayCheckbox(content: string, type?: 'task' | 'meeting
|
||||
date: getToday(),
|
||||
text: content,
|
||||
type: type || 'task',
|
||||
taskId
|
||||
taskId,
|
||||
});
|
||||
|
||||
|
||||
revalidatePath('/daily');
|
||||
return { success: true, data: newCheckbox };
|
||||
} catch (error) {
|
||||
console.error('Erreur addTodayCheckbox:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -79,51 +91,57 @@ export async function addTodayCheckbox(content: string, type?: 'task' | 'meeting
|
||||
/**
|
||||
* Ajoute une checkbox pour hier
|
||||
*/
|
||||
export async function addYesterdayCheckbox(content: string, type?: 'task' | 'meeting', taskId?: string): Promise<{
|
||||
export async function addYesterdayCheckbox(
|
||||
content: string,
|
||||
type?: 'task' | 'meeting',
|
||||
taskId?: string
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
data?: DailyCheckbox;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const yesterday = getPreviousWorkday(getToday());
|
||||
|
||||
|
||||
const newCheckbox = await dailyService.addCheckbox({
|
||||
date: yesterday,
|
||||
text: content,
|
||||
type: type || 'task',
|
||||
taskId
|
||||
taskId,
|
||||
});
|
||||
|
||||
|
||||
revalidatePath('/daily');
|
||||
return { success: true, data: newCheckbox };
|
||||
} catch (error) {
|
||||
console.error('Erreur addYesterdayCheckbox:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Met à jour une checkbox complète
|
||||
*/
|
||||
export async function updateCheckbox(checkboxId: string, data: UpdateDailyCheckboxData): Promise<{
|
||||
export async function updateCheckbox(
|
||||
checkboxId: string,
|
||||
data: UpdateDailyCheckboxData
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
data?: DailyCheckbox;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const updatedCheckbox = await dailyService.updateCheckbox(checkboxId, data);
|
||||
|
||||
|
||||
revalidatePath('/daily');
|
||||
return { success: true, data: updatedCheckbox };
|
||||
} catch (error) {
|
||||
console.error('Erreur updateCheckbox:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -137,14 +155,14 @@ export async function deleteCheckbox(checkboxId: string): Promise<{
|
||||
}> {
|
||||
try {
|
||||
await dailyService.deleteCheckbox(checkboxId);
|
||||
|
||||
|
||||
revalidatePath('/daily');
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('Erreur deleteCheckbox:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -152,7 +170,11 @@ export async function deleteCheckbox(checkboxId: string): Promise<{
|
||||
/**
|
||||
* Ajoute un todo lié à une tâche
|
||||
*/
|
||||
export async function addTodoToTask(taskId: string, text: string, date?: Date): Promise<{
|
||||
export async function addTodoToTask(
|
||||
taskId: string,
|
||||
text: string,
|
||||
date?: Date
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
data?: DailyCheckbox;
|
||||
error?: string;
|
||||
@@ -165,11 +187,11 @@ export async function addTodoToTask(taskId: string, text: string, date?: Date):
|
||||
text: text.trim(),
|
||||
type: 'task',
|
||||
taskId: taskId,
|
||||
isChecked: false
|
||||
isChecked: false,
|
||||
};
|
||||
|
||||
const checkbox = await dailyService.addCheckbox(checkboxData);
|
||||
|
||||
|
||||
revalidatePath('/daily');
|
||||
revalidatePath('/kanban');
|
||||
return { success: true, data: checkbox };
|
||||
@@ -177,7 +199,7 @@ export async function addTodoToTask(taskId: string, text: string, date?: Date):
|
||||
console.error('Erreur addTodoToTask:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -185,23 +207,26 @@ export async function addTodoToTask(taskId: string, text: string, date?: Date):
|
||||
/**
|
||||
* Réorganise les checkboxes d'une date
|
||||
*/
|
||||
export async function reorderCheckboxes(dailyId: string, checkboxIds: string[]): Promise<{
|
||||
export async function reorderCheckboxes(
|
||||
dailyId: string,
|
||||
checkboxIds: string[]
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
// Le dailyId correspond à la date au format YYYY-MM-DD
|
||||
const date = parseDate(dailyId);
|
||||
|
||||
|
||||
await dailyService.reorderCheckboxes(date, checkboxIds);
|
||||
|
||||
|
||||
revalidatePath('/daily');
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('Erreur reorderCheckboxes:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -216,14 +241,14 @@ export async function moveCheckboxToToday(checkboxId: string): Promise<{
|
||||
}> {
|
||||
try {
|
||||
const updatedCheckbox = await dailyService.moveCheckboxToToday(checkboxId);
|
||||
|
||||
|
||||
revalidatePath('/daily');
|
||||
return { success: true, data: updatedCheckbox };
|
||||
} catch (error) {
|
||||
console.error('Erreur moveCheckboxToToday:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,9 @@ export type JiraAnalyticsResult = {
|
||||
/**
|
||||
* Server Action pour récupérer les analytics Jira du projet configuré
|
||||
*/
|
||||
export async function getJiraAnalytics(forceRefresh = false): Promise<JiraAnalyticsResult> {
|
||||
export async function getJiraAnalytics(
|
||||
forceRefresh = false
|
||||
): Promise<JiraAnalyticsResult> {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user?.id) {
|
||||
@@ -23,45 +25,56 @@ export async function getJiraAnalytics(forceRefresh = false): Promise<JiraAnalyt
|
||||
}
|
||||
|
||||
// Récupérer la config Jira depuis la base de données
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(session.user.id);
|
||||
|
||||
if (!jiraConfig.enabled || !jiraConfig.baseUrl || !jiraConfig.email || !jiraConfig.apiToken) {
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(
|
||||
session.user.id
|
||||
);
|
||||
|
||||
if (
|
||||
!jiraConfig.enabled ||
|
||||
!jiraConfig.baseUrl ||
|
||||
!jiraConfig.email ||
|
||||
!jiraConfig.apiToken
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Configuration Jira manquante. Configurez Jira dans les paramètres.'
|
||||
error:
|
||||
'Configuration Jira manquante. Configurez Jira dans les paramètres.',
|
||||
};
|
||||
}
|
||||
|
||||
if (!jiraConfig.projectKey) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Aucun projet configuré pour les analytics. Configurez un projet dans les paramètres Jira.'
|
||||
error:
|
||||
'Aucun projet configuré pour les analytics. Configurez un projet dans les paramètres Jira.',
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
// Créer le service d'analytics
|
||||
const analyticsService = new JiraAnalyticsService({
|
||||
enabled: jiraConfig.enabled,
|
||||
baseUrl: jiraConfig.baseUrl,
|
||||
email: jiraConfig.email,
|
||||
apiToken: jiraConfig.apiToken,
|
||||
projectKey: jiraConfig.projectKey
|
||||
projectKey: jiraConfig.projectKey,
|
||||
});
|
||||
|
||||
// Récupérer les analytics (avec cache ou actualisation forcée)
|
||||
const analytics = await analyticsService.getProjectAnalytics(forceRefresh);
|
||||
// Récupérer les analytics (avec cache ou actualisation forcée)
|
||||
const analytics = await analyticsService.getProjectAnalytics(forceRefresh);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: analytics
|
||||
data: analytics,
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Erreur lors du calcul des analytics Jira:', error);
|
||||
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur lors du calcul des analytics'
|
||||
error:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Erreur lors du calcul des analytics',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
'use server';
|
||||
|
||||
import { jiraAnomalyDetection, JiraAnomaly, AnomalyDetectionConfig } from '@/services/integrations/jira/anomaly-detection';
|
||||
import { JiraAnalyticsService, JiraAnalyticsConfig } from '@/services/integrations/jira/analytics';
|
||||
import {
|
||||
jiraAnomalyDetection,
|
||||
JiraAnomaly,
|
||||
AnomalyDetectionConfig,
|
||||
} from '@/services/integrations/jira/anomaly-detection';
|
||||
import {
|
||||
JiraAnalyticsService,
|
||||
JiraAnalyticsConfig,
|
||||
} from '@/services/integrations/jira/analytics';
|
||||
import { userPreferencesService } from '@/services/core/user-preferences';
|
||||
import { getServerSession } from 'next-auth';
|
||||
import { authOptions } from '@/lib/auth';
|
||||
@@ -15,7 +22,9 @@ export interface AnomalyDetectionResult {
|
||||
/**
|
||||
* Détecte les anomalies dans les métriques Jira actuelles
|
||||
*/
|
||||
export async function detectJiraAnomalies(forceRefresh = false): Promise<AnomalyDetectionResult> {
|
||||
export async function detectJiraAnomalies(
|
||||
forceRefresh = false
|
||||
): Promise<AnomalyDetectionResult> {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user?.id) {
|
||||
@@ -23,12 +32,19 @@ export async function detectJiraAnomalies(forceRefresh = false): Promise<Anomaly
|
||||
}
|
||||
|
||||
// Récupérer la config Jira
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(session.user.id);
|
||||
|
||||
if (!jiraConfig?.baseUrl || !jiraConfig?.email || !jiraConfig?.apiToken || !jiraConfig?.projectKey) {
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(
|
||||
session.user.id
|
||||
);
|
||||
|
||||
if (
|
||||
!jiraConfig?.baseUrl ||
|
||||
!jiraConfig?.email ||
|
||||
!jiraConfig?.apiToken ||
|
||||
!jiraConfig?.projectKey
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Configuration Jira incomplète'
|
||||
error: 'Configuration Jira incomplète',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -36,8 +52,10 @@ export async function detectJiraAnomalies(forceRefresh = false): Promise<Anomaly
|
||||
if (!jiraConfig.baseUrl || !jiraConfig.projectKey) {
|
||||
return { success: false, error: 'Configuration Jira incomplète' };
|
||||
}
|
||||
|
||||
const analyticsService = new JiraAnalyticsService(jiraConfig as JiraAnalyticsConfig);
|
||||
|
||||
const analyticsService = new JiraAnalyticsService(
|
||||
jiraConfig as JiraAnalyticsConfig
|
||||
);
|
||||
const analytics = await analyticsService.getProjectAnalytics(forceRefresh);
|
||||
|
||||
// Détecter les anomalies
|
||||
@@ -45,13 +63,13 @@ export async function detectJiraAnomalies(forceRefresh = false): Promise<Anomaly
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: anomalies
|
||||
data: anomalies,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('❌ Erreur lors de la détection d\'anomalies:', error);
|
||||
console.error("❌ Erreur lors de la détection d'anomalies:", error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -59,19 +77,21 @@ export async function detectJiraAnomalies(forceRefresh = false): Promise<Anomaly
|
||||
/**
|
||||
* Met à jour la configuration de détection d'anomalies
|
||||
*/
|
||||
export async function updateAnomalyDetectionConfig(config: Partial<AnomalyDetectionConfig>) {
|
||||
export async function updateAnomalyDetectionConfig(
|
||||
config: Partial<AnomalyDetectionConfig>
|
||||
) {
|
||||
try {
|
||||
jiraAnomalyDetection.updateConfig(config);
|
||||
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: jiraAnomalyDetection.getConfig()
|
||||
data: jiraAnomalyDetection.getConfig(),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('❌ Erreur lors de la mise à jour de la config:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -83,13 +103,13 @@ export async function getAnomalyDetectionConfig() {
|
||||
try {
|
||||
return {
|
||||
success: true,
|
||||
data: jiraAnomalyDetection.getConfig()
|
||||
data: jiraAnomalyDetection.getConfig(),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('❌ Erreur lors de la récupération de la config:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,15 +91,17 @@ export interface JiraAnalytics {
|
||||
/**
|
||||
* Server Action pour exporter les analytics Jira au format CSV ou JSON
|
||||
*/
|
||||
export async function exportJiraAnalytics(format: ExportFormat = 'csv'): Promise<ExportResult> {
|
||||
export async function exportJiraAnalytics(
|
||||
format: ExportFormat = 'csv'
|
||||
): Promise<ExportResult> {
|
||||
try {
|
||||
// Récupérer les analytics (force refresh pour avoir les données les plus récentes)
|
||||
const analyticsResult = await getJiraAnalytics(true);
|
||||
|
||||
|
||||
if (!analyticsResult.success || !analyticsResult.data) {
|
||||
return {
|
||||
success: false,
|
||||
error: analyticsResult.error || 'Impossible de récupérer les analytics'
|
||||
error: analyticsResult.error || 'Impossible de récupérer les analytics',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -111,25 +113,24 @@ export async function exportJiraAnalytics(format: ExportFormat = 'csv'): Promise
|
||||
return {
|
||||
success: true,
|
||||
data: JSON.stringify(analytics, null, 2),
|
||||
filename: `jira-analytics-${projectKey}-${timestamp}.json`
|
||||
filename: `jira-analytics-${projectKey}-${timestamp}.json`,
|
||||
};
|
||||
}
|
||||
|
||||
// Format CSV
|
||||
const csvData = generateCSV(analytics);
|
||||
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: csvData,
|
||||
filename: `jira-analytics-${projectKey}-${timestamp}.csv`
|
||||
filename: `jira-analytics-${projectKey}-${timestamp}.csv`,
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Erreur lors de l\'export des analytics:', error);
|
||||
|
||||
console.error("❌ Erreur lors de l'export des analytics:", error);
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -143,103 +144,126 @@ function generateCSV(analytics: JiraAnalytics): string {
|
||||
// Header du rapport
|
||||
lines.push('# Rapport Analytics Jira');
|
||||
lines.push(`# Projet: ${analytics.project.name} (${analytics.project.key})`);
|
||||
lines.push(`# Généré le: ${formatDateForDisplay(getToday(), 'DISPLAY_LONG')}`);
|
||||
lines.push(
|
||||
`# Généré le: ${formatDateForDisplay(getToday(), 'DISPLAY_LONG')}`
|
||||
);
|
||||
lines.push(`# Total tickets: ${analytics.project.totalIssues}`);
|
||||
lines.push('');
|
||||
|
||||
// Section 1: Métriques d'équipe
|
||||
lines.push('## Répartition de l\'équipe');
|
||||
lines.push('Assignee,Nom,Total Tickets,Tickets Complétés,Tickets En Cours,Pourcentage');
|
||||
analytics.teamMetrics.issuesDistribution.forEach((assignee: AssigneeMetrics) => {
|
||||
lines.push([
|
||||
escapeCsv(assignee.assignee),
|
||||
escapeCsv(assignee.displayName),
|
||||
assignee.totalIssues,
|
||||
assignee.completedIssues,
|
||||
assignee.inProgressIssues,
|
||||
assignee.percentage.toFixed(1) + '%'
|
||||
].join(','));
|
||||
});
|
||||
lines.push("## Répartition de l'équipe");
|
||||
lines.push(
|
||||
'Assignee,Nom,Total Tickets,Tickets Complétés,Tickets En Cours,Pourcentage'
|
||||
);
|
||||
analytics.teamMetrics.issuesDistribution.forEach(
|
||||
(assignee: AssigneeMetrics) => {
|
||||
lines.push(
|
||||
[
|
||||
escapeCsv(assignee.assignee),
|
||||
escapeCsv(assignee.displayName),
|
||||
assignee.totalIssues,
|
||||
assignee.completedIssues,
|
||||
assignee.inProgressIssues,
|
||||
assignee.percentage.toFixed(1) + '%',
|
||||
].join(',')
|
||||
);
|
||||
}
|
||||
);
|
||||
lines.push('');
|
||||
|
||||
// Section 2: Historique des sprints
|
||||
lines.push('## Historique des sprints');
|
||||
lines.push('Sprint,Date Début,Date Fin,Points Planifiés,Points Complétés,Taux de Complétion');
|
||||
lines.push(
|
||||
'Sprint,Date Début,Date Fin,Points Planifiés,Points Complétés,Taux de Complétion'
|
||||
);
|
||||
analytics.velocityMetrics.sprintHistory.forEach((sprint: SprintHistory) => {
|
||||
lines.push([
|
||||
escapeCsv(sprint.sprintName),
|
||||
sprint.startDate.slice(0, 10),
|
||||
sprint.endDate.slice(0, 10),
|
||||
sprint.plannedPoints,
|
||||
sprint.completedPoints,
|
||||
sprint.completionRate + '%'
|
||||
].join(','));
|
||||
lines.push(
|
||||
[
|
||||
escapeCsv(sprint.sprintName),
|
||||
sprint.startDate.slice(0, 10),
|
||||
sprint.endDate.slice(0, 10),
|
||||
sprint.plannedPoints,
|
||||
sprint.completedPoints,
|
||||
sprint.completionRate + '%',
|
||||
].join(',')
|
||||
);
|
||||
});
|
||||
lines.push('');
|
||||
|
||||
// Section 3: Cycle time par type
|
||||
lines.push('## Cycle Time par type de ticket');
|
||||
lines.push('Type de Ticket,Temps Moyen (jours),Temps Médian (jours),Échantillons');
|
||||
analytics.cycleTimeMetrics.cycleTimeByType.forEach((type: CycleTimeByType) => {
|
||||
lines.push([
|
||||
escapeCsv(type.issueType),
|
||||
type.averageDays,
|
||||
type.medianDays,
|
||||
type.samples
|
||||
].join(','));
|
||||
});
|
||||
lines.push(
|
||||
'Type de Ticket,Temps Moyen (jours),Temps Médian (jours),Échantillons'
|
||||
);
|
||||
analytics.cycleTimeMetrics.cycleTimeByType.forEach(
|
||||
(type: CycleTimeByType) => {
|
||||
lines.push(
|
||||
[
|
||||
escapeCsv(type.issueType),
|
||||
type.averageDays,
|
||||
type.medianDays,
|
||||
type.samples,
|
||||
].join(',')
|
||||
);
|
||||
}
|
||||
);
|
||||
lines.push('');
|
||||
|
||||
// Section 4: Work in Progress
|
||||
lines.push('## Work in Progress par statut');
|
||||
lines.push('Statut,Nombre,Pourcentage');
|
||||
analytics.workInProgress.byStatus.forEach((status: WorkInProgressStatus) => {
|
||||
lines.push([
|
||||
escapeCsv(status.status),
|
||||
status.count,
|
||||
status.percentage + '%'
|
||||
].join(','));
|
||||
lines.push(
|
||||
[escapeCsv(status.status), status.count, status.percentage + '%'].join(
|
||||
','
|
||||
)
|
||||
);
|
||||
});
|
||||
lines.push('');
|
||||
|
||||
// Section 5: Charge de travail par assignee
|
||||
lines.push('## Charge de travail par assignee');
|
||||
lines.push('Assignee,Nom,À Faire,En Cours,En Revue,Total Actif');
|
||||
analytics.workInProgress.byAssignee.forEach((assignee: WorkInProgressAssignee) => {
|
||||
lines.push([
|
||||
escapeCsv(assignee.assignee),
|
||||
escapeCsv(assignee.displayName),
|
||||
assignee.todoCount,
|
||||
assignee.inProgressCount,
|
||||
assignee.reviewCount,
|
||||
assignee.totalActive
|
||||
].join(','));
|
||||
});
|
||||
analytics.workInProgress.byAssignee.forEach(
|
||||
(assignee: WorkInProgressAssignee) => {
|
||||
lines.push(
|
||||
[
|
||||
escapeCsv(assignee.assignee),
|
||||
escapeCsv(assignee.displayName),
|
||||
assignee.todoCount,
|
||||
assignee.inProgressCount,
|
||||
assignee.reviewCount,
|
||||
assignee.totalActive,
|
||||
].join(',')
|
||||
);
|
||||
}
|
||||
);
|
||||
lines.push('');
|
||||
|
||||
// Section 6: Métriques résumé
|
||||
lines.push('## Métriques de résumé');
|
||||
lines.push('Métrique,Valeur');
|
||||
lines.push([
|
||||
'Total membres équipe',
|
||||
analytics.teamMetrics.totalAssignees
|
||||
].join(','));
|
||||
lines.push([
|
||||
'Membres actifs',
|
||||
analytics.teamMetrics.activeAssignees
|
||||
].join(','));
|
||||
lines.push([
|
||||
'Points complétés sprint actuel',
|
||||
analytics.velocityMetrics.currentSprintPoints
|
||||
].join(','));
|
||||
lines.push([
|
||||
'Vélocité moyenne',
|
||||
analytics.velocityMetrics.averageVelocity
|
||||
].join(','));
|
||||
lines.push([
|
||||
'Cycle time moyen (jours)',
|
||||
analytics.cycleTimeMetrics.averageCycleTime
|
||||
].join(','));
|
||||
lines.push(
|
||||
['Total membres équipe', analytics.teamMetrics.totalAssignees].join(',')
|
||||
);
|
||||
lines.push(
|
||||
['Membres actifs', analytics.teamMetrics.activeAssignees].join(',')
|
||||
);
|
||||
lines.push(
|
||||
[
|
||||
'Points complétés sprint actuel',
|
||||
analytics.velocityMetrics.currentSprintPoints,
|
||||
].join(',')
|
||||
);
|
||||
lines.push(
|
||||
['Vélocité moyenne', analytics.velocityMetrics.averageVelocity].join(',')
|
||||
);
|
||||
lines.push(
|
||||
[
|
||||
'Cycle time moyen (jours)',
|
||||
analytics.cycleTimeMetrics.averageCycleTime,
|
||||
].join(',')
|
||||
);
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
@@ -249,12 +273,12 @@ function generateCSV(analytics: JiraAnalytics): string {
|
||||
*/
|
||||
function escapeCsv(value: string): string {
|
||||
if (typeof value !== 'string') return String(value);
|
||||
|
||||
|
||||
// Si la valeur contient des guillemets, virgules ou retours à la ligne
|
||||
if (value.includes('"') || value.includes(',') || value.includes('\n')) {
|
||||
// Doubler les guillemets et entourer de guillemets
|
||||
return '"' + value.replace(/"/g, '""') + '"';
|
||||
}
|
||||
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
'use server';
|
||||
|
||||
import { JiraAnalyticsService, JiraAnalyticsConfig } from '@/services/integrations/jira/analytics';
|
||||
import {
|
||||
JiraAnalyticsService,
|
||||
JiraAnalyticsConfig,
|
||||
} from '@/services/integrations/jira/analytics';
|
||||
import { JiraAdvancedFiltersService } from '@/services/integrations/jira/advanced-filters';
|
||||
import { userPreferencesService } from '@/services/core/user-preferences';
|
||||
import { AvailableFilters, JiraAnalyticsFilters, JiraAnalytics } from '@/lib/types';
|
||||
import {
|
||||
AvailableFilters,
|
||||
JiraAnalyticsFilters,
|
||||
JiraAnalytics,
|
||||
} from '@/lib/types';
|
||||
import { getServerSession } from 'next-auth';
|
||||
import { authOptions } from '@/lib/auth';
|
||||
|
||||
@@ -30,12 +37,19 @@ export async function getAvailableJiraFilters(): Promise<FiltersResult> {
|
||||
}
|
||||
|
||||
// Récupérer la config Jira
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(session.user.id);
|
||||
|
||||
if (!jiraConfig?.baseUrl || !jiraConfig?.email || !jiraConfig?.apiToken || !jiraConfig?.projectKey) {
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(
|
||||
session.user.id
|
||||
);
|
||||
|
||||
if (
|
||||
!jiraConfig?.baseUrl ||
|
||||
!jiraConfig?.email ||
|
||||
!jiraConfig?.apiToken ||
|
||||
!jiraConfig?.projectKey
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Configuration Jira incomplète'
|
||||
error: 'Configuration Jira incomplète',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -43,24 +57,27 @@ export async function getAvailableJiraFilters(): Promise<FiltersResult> {
|
||||
if (!jiraConfig.baseUrl || !jiraConfig.projectKey) {
|
||||
return { success: false, error: 'Configuration Jira incomplète' };
|
||||
}
|
||||
|
||||
const analyticsService = new JiraAnalyticsService(jiraConfig as JiraAnalyticsConfig);
|
||||
|
||||
|
||||
const analyticsService = new JiraAnalyticsService(
|
||||
jiraConfig as JiraAnalyticsConfig
|
||||
);
|
||||
|
||||
// Récupérer la liste des issues pour extraire les filtres
|
||||
const allIssues = await analyticsService.getAllProjectIssues();
|
||||
|
||||
|
||||
// Extraire les filtres disponibles
|
||||
const availableFilters = JiraAdvancedFiltersService.extractAvailableFilters(allIssues);
|
||||
const availableFilters =
|
||||
JiraAdvancedFiltersService.extractAvailableFilters(allIssues);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: availableFilters
|
||||
data: availableFilters,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('❌ Erreur lors de la récupération des filtres:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -68,7 +85,9 @@ export async function getAvailableJiraFilters(): Promise<FiltersResult> {
|
||||
/**
|
||||
* Applique des filtres aux analytics et retourne les données filtrées
|
||||
*/
|
||||
export async function getFilteredJiraAnalytics(filters: Partial<JiraAnalyticsFilters>): Promise<FilteredAnalyticsResult> {
|
||||
export async function getFilteredJiraAnalytics(
|
||||
filters: Partial<JiraAnalyticsFilters>
|
||||
): Promise<FilteredAnalyticsResult> {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user?.id) {
|
||||
@@ -76,12 +95,19 @@ export async function getFilteredJiraAnalytics(filters: Partial<JiraAnalyticsFil
|
||||
}
|
||||
|
||||
// Récupérer la config Jira
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(session.user.id);
|
||||
|
||||
if (!jiraConfig?.baseUrl || !jiraConfig?.email || !jiraConfig?.apiToken || !jiraConfig?.projectKey) {
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(
|
||||
session.user.id
|
||||
);
|
||||
|
||||
if (
|
||||
!jiraConfig?.baseUrl ||
|
||||
!jiraConfig?.email ||
|
||||
!jiraConfig?.apiToken ||
|
||||
!jiraConfig?.projectKey
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Configuration Jira incomplète'
|
||||
error: 'Configuration Jira incomplète',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -89,37 +115,40 @@ export async function getFilteredJiraAnalytics(filters: Partial<JiraAnalyticsFil
|
||||
if (!jiraConfig.baseUrl || !jiraConfig.projectKey) {
|
||||
return { success: false, error: 'Configuration Jira incomplète' };
|
||||
}
|
||||
|
||||
const analyticsService = new JiraAnalyticsService(jiraConfig as JiraAnalyticsConfig);
|
||||
|
||||
const analyticsService = new JiraAnalyticsService(
|
||||
jiraConfig as JiraAnalyticsConfig
|
||||
);
|
||||
const originalAnalytics = await analyticsService.getProjectAnalytics();
|
||||
|
||||
|
||||
// Si aucun filtre actif, retourner les données originales
|
||||
if (!JiraAdvancedFiltersService.hasActiveFilters(filters)) {
|
||||
return {
|
||||
success: true,
|
||||
data: originalAnalytics
|
||||
data: originalAnalytics,
|
||||
};
|
||||
}
|
||||
|
||||
// Récupérer toutes les issues pour appliquer les filtres
|
||||
const allIssues = await analyticsService.getAllProjectIssues();
|
||||
|
||||
|
||||
// Appliquer les filtres
|
||||
const filteredAnalytics = JiraAdvancedFiltersService.applyFiltersToAnalytics(
|
||||
originalAnalytics,
|
||||
filters,
|
||||
allIssues
|
||||
);
|
||||
const filteredAnalytics =
|
||||
JiraAdvancedFiltersService.applyFiltersToAnalytics(
|
||||
originalAnalytics,
|
||||
filters,
|
||||
allIssues
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: filteredAnalytics
|
||||
data: filteredAnalytics,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('❌ Erreur lors du filtrage des analytics:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
'use server';
|
||||
|
||||
import { JiraAnalyticsService, JiraAnalyticsConfig } from '@/services/integrations/jira/analytics';
|
||||
import {
|
||||
JiraAnalyticsService,
|
||||
JiraAnalyticsConfig,
|
||||
} from '@/services/integrations/jira/analytics';
|
||||
import { userPreferencesService } from '@/services/core/user-preferences';
|
||||
import { SprintDetails } from '@/components/jira/SprintDetailModal';
|
||||
import { JiraTask, AssigneeDistribution, StatusDistribution, SprintVelocity } from '@/lib/types';
|
||||
import {
|
||||
JiraTask,
|
||||
AssigneeDistribution,
|
||||
StatusDistribution,
|
||||
SprintVelocity,
|
||||
} from '@/lib/types';
|
||||
import { parseDate } from '@/lib/date-utils';
|
||||
import { getServerSession } from 'next-auth';
|
||||
import { authOptions } from '@/lib/auth';
|
||||
@@ -17,7 +25,9 @@ export interface SprintDetailsResult {
|
||||
/**
|
||||
* Récupère les détails d'un sprint spécifique
|
||||
*/
|
||||
export async function getSprintDetails(sprintName: string): Promise<SprintDetailsResult> {
|
||||
export async function getSprintDetails(
|
||||
sprintName: string
|
||||
): Promise<SprintDetailsResult> {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user?.id) {
|
||||
@@ -25,12 +35,19 @@ export async function getSprintDetails(sprintName: string): Promise<SprintDetail
|
||||
}
|
||||
|
||||
// Récupérer la config Jira
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(session.user.id);
|
||||
|
||||
if (!jiraConfig?.baseUrl || !jiraConfig?.email || !jiraConfig?.apiToken || !jiraConfig?.projectKey) {
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(
|
||||
session.user.id
|
||||
);
|
||||
|
||||
if (
|
||||
!jiraConfig?.baseUrl ||
|
||||
!jiraConfig?.email ||
|
||||
!jiraConfig?.apiToken ||
|
||||
!jiraConfig?.projectKey
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Configuration Jira incomplète'
|
||||
error: 'Configuration Jira incomplète',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -38,38 +55,42 @@ export async function getSprintDetails(sprintName: string): Promise<SprintDetail
|
||||
if (!jiraConfig.baseUrl || !jiraConfig.projectKey) {
|
||||
return { success: false, error: 'Configuration Jira incomplète' };
|
||||
}
|
||||
|
||||
const analyticsService = new JiraAnalyticsService(jiraConfig as JiraAnalyticsConfig);
|
||||
|
||||
const analyticsService = new JiraAnalyticsService(
|
||||
jiraConfig as JiraAnalyticsConfig
|
||||
);
|
||||
const analytics = await analyticsService.getProjectAnalytics();
|
||||
|
||||
const sprint = analytics.velocityMetrics.sprintHistory.find(s => s.sprintName === sprintName);
|
||||
|
||||
const sprint = analytics.velocityMetrics.sprintHistory.find(
|
||||
(s) => s.sprintName === sprintName
|
||||
);
|
||||
if (!sprint) {
|
||||
return {
|
||||
success: false,
|
||||
error: `Sprint "${sprintName}" introuvable`
|
||||
error: `Sprint "${sprintName}" introuvable`,
|
||||
};
|
||||
}
|
||||
|
||||
// Récupérer toutes les issues du projet pour filtrer par sprint
|
||||
const allIssues = await analyticsService.getAllProjectIssues();
|
||||
|
||||
|
||||
// Filtrer les issues pour ce sprint spécifique
|
||||
// Note: En réalité, il faudrait une requête JQL plus précise pour récupérer les issues d'un sprint
|
||||
// Pour simplifier, on prend les issues dans la période du sprint
|
||||
const sprintStart = parseDate(sprint.startDate);
|
||||
const sprintEnd = parseDate(sprint.endDate);
|
||||
|
||||
const sprintIssues = allIssues.filter(issue => {
|
||||
|
||||
const sprintIssues = allIssues.filter((issue) => {
|
||||
const issueDate = parseDate(issue.created);
|
||||
return issueDate >= sprintStart && issueDate <= sprintEnd;
|
||||
});
|
||||
|
||||
// Calculer les métriques du sprint
|
||||
const sprintMetrics = calculateSprintMetrics(sprintIssues, sprint);
|
||||
|
||||
|
||||
// Calculer la distribution par assigné pour ce sprint
|
||||
const assigneeDistribution = calculateAssigneeDistribution(sprintIssues);
|
||||
|
||||
|
||||
// Calculer la distribution par statut pour ce sprint
|
||||
const statusDistribution = calculateStatusDistribution(sprintIssues);
|
||||
|
||||
@@ -78,18 +99,21 @@ export async function getSprintDetails(sprintName: string): Promise<SprintDetail
|
||||
issues: sprintIssues,
|
||||
assigneeDistribution,
|
||||
statusDistribution,
|
||||
metrics: sprintMetrics
|
||||
metrics: sprintMetrics,
|
||||
};
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: sprintDetails
|
||||
data: sprintDetails,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('❌ Erreur lors de la récupération des détails du sprint:', error);
|
||||
console.error(
|
||||
'❌ Erreur lors de la récupération des détails du sprint:',
|
||||
error
|
||||
);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -99,34 +123,39 @@ export async function getSprintDetails(sprintName: string): Promise<SprintDetail
|
||||
*/
|
||||
function calculateSprintMetrics(issues: JiraTask[], sprint: SprintVelocity) {
|
||||
const totalIssues = issues.length;
|
||||
const completedIssues = issues.filter(issue =>
|
||||
issue.status.category === 'Done' ||
|
||||
issue.status.name.toLowerCase().includes('done') ||
|
||||
issue.status.name.toLowerCase().includes('closed')
|
||||
const completedIssues = issues.filter(
|
||||
(issue) =>
|
||||
issue.status.category === 'Done' ||
|
||||
issue.status.name.toLowerCase().includes('done') ||
|
||||
issue.status.name.toLowerCase().includes('closed')
|
||||
).length;
|
||||
|
||||
const inProgressIssues = issues.filter(issue =>
|
||||
issue.status.category === 'In Progress' ||
|
||||
issue.status.name.toLowerCase().includes('progress') ||
|
||||
issue.status.name.toLowerCase().includes('review')
|
||||
|
||||
const inProgressIssues = issues.filter(
|
||||
(issue) =>
|
||||
issue.status.category === 'In Progress' ||
|
||||
issue.status.name.toLowerCase().includes('progress') ||
|
||||
issue.status.name.toLowerCase().includes('review')
|
||||
).length;
|
||||
|
||||
const blockedIssues = issues.filter(issue =>
|
||||
issue.status.name.toLowerCase().includes('blocked') ||
|
||||
issue.status.name.toLowerCase().includes('waiting')
|
||||
|
||||
const blockedIssues = issues.filter(
|
||||
(issue) =>
|
||||
issue.status.name.toLowerCase().includes('blocked') ||
|
||||
issue.status.name.toLowerCase().includes('waiting')
|
||||
).length;
|
||||
|
||||
// Calcul du cycle time moyen pour ce sprint
|
||||
const completedIssuesWithDates = issues.filter(issue =>
|
||||
issue.status.category === 'Done' && issue.created && issue.updated
|
||||
const completedIssuesWithDates = issues.filter(
|
||||
(issue) =>
|
||||
issue.status.category === 'Done' && issue.created && issue.updated
|
||||
);
|
||||
|
||||
|
||||
let averageCycleTime = 0;
|
||||
if (completedIssuesWithDates.length > 0) {
|
||||
const totalCycleTime = completedIssuesWithDates.reduce((total, issue) => {
|
||||
const created = parseDate(issue.created);
|
||||
const updated = parseDate(issue.updated);
|
||||
const cycleTime = (updated.getTime() - created.getTime()) / (1000 * 60 * 60 * 24); // en jours
|
||||
const cycleTime =
|
||||
(updated.getTime() - created.getTime()) / (1000 * 60 * 60 * 24); // en jours
|
||||
return total + cycleTime;
|
||||
}, 0);
|
||||
averageCycleTime = totalCycleTime / completedIssuesWithDates.length;
|
||||
@@ -146,40 +175,51 @@ function calculateSprintMetrics(issues: JiraTask[], sprint: SprintVelocity) {
|
||||
inProgressIssues,
|
||||
blockedIssues,
|
||||
averageCycleTime,
|
||||
velocityTrend
|
||||
velocityTrend,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Calcule la distribution par assigné pour le sprint
|
||||
*/
|
||||
function calculateAssigneeDistribution(issues: JiraTask[]): AssigneeDistribution[] {
|
||||
const assigneeMap = new Map<string, { total: number; completed: number; inProgress: number }>();
|
||||
|
||||
issues.forEach(issue => {
|
||||
function calculateAssigneeDistribution(
|
||||
issues: JiraTask[]
|
||||
): AssigneeDistribution[] {
|
||||
const assigneeMap = new Map<
|
||||
string,
|
||||
{ total: number; completed: number; inProgress: number }
|
||||
>();
|
||||
|
||||
issues.forEach((issue) => {
|
||||
const assigneeName = issue.assignee?.displayName || 'Non assigné';
|
||||
const current = assigneeMap.get(assigneeName) || { total: 0, completed: 0, inProgress: 0 };
|
||||
|
||||
const current = assigneeMap.get(assigneeName) || {
|
||||
total: 0,
|
||||
completed: 0,
|
||||
inProgress: 0,
|
||||
};
|
||||
|
||||
current.total++;
|
||||
|
||||
|
||||
if (issue.status.category === 'Done') {
|
||||
current.completed++;
|
||||
} else if (issue.status.category === 'In Progress') {
|
||||
current.inProgress++;
|
||||
}
|
||||
|
||||
|
||||
assigneeMap.set(assigneeName, current);
|
||||
});
|
||||
|
||||
return Array.from(assigneeMap.entries()).map(([displayName, stats]) => ({
|
||||
assignee: displayName === 'Non assigné' ? '' : displayName,
|
||||
displayName,
|
||||
totalIssues: stats.total,
|
||||
completedIssues: stats.completed,
|
||||
inProgressIssues: stats.inProgress,
|
||||
percentage: issues.length > 0 ? (stats.total / issues.length) * 100 : 0,
|
||||
count: stats.total // Ajout pour compatibilité
|
||||
})).sort((a, b) => b.totalIssues - a.totalIssues);
|
||||
return Array.from(assigneeMap.entries())
|
||||
.map(([displayName, stats]) => ({
|
||||
assignee: displayName === 'Non assigné' ? '' : displayName,
|
||||
displayName,
|
||||
totalIssues: stats.total,
|
||||
completedIssues: stats.completed,
|
||||
inProgressIssues: stats.inProgress,
|
||||
percentage: issues.length > 0 ? (stats.total / issues.length) * 100 : 0,
|
||||
count: stats.total, // Ajout pour compatibilité
|
||||
}))
|
||||
.sort((a, b) => b.totalIssues - a.totalIssues);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -187,14 +227,19 @@ function calculateAssigneeDistribution(issues: JiraTask[]): AssigneeDistribution
|
||||
*/
|
||||
function calculateStatusDistribution(issues: JiraTask[]): StatusDistribution[] {
|
||||
const statusMap = new Map<string, number>();
|
||||
|
||||
issues.forEach(issue => {
|
||||
statusMap.set(issue.status.name, (statusMap.get(issue.status.name) || 0) + 1);
|
||||
|
||||
issues.forEach((issue) => {
|
||||
statusMap.set(
|
||||
issue.status.name,
|
||||
(statusMap.get(issue.status.name) || 0) + 1
|
||||
);
|
||||
});
|
||||
|
||||
return Array.from(statusMap.entries()).map(([status, count]) => ({
|
||||
status,
|
||||
count,
|
||||
percentage: issues.length > 0 ? (count / issues.length) * 100 : 0
|
||||
})).sort((a, b) => b.count - a.count);
|
||||
return Array.from(statusMap.entries())
|
||||
.map(([status, count]) => ({
|
||||
status,
|
||||
count,
|
||||
percentage: issues.length > 0 ? (count / issues.length) * 100 : 0,
|
||||
}))
|
||||
.sort((a, b) => b.count - a.count);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
'use server';
|
||||
|
||||
import { MetricsService, WeeklyMetricsOverview, VelocityTrend } from '@/services/analytics/metrics';
|
||||
import {
|
||||
MetricsService,
|
||||
WeeklyMetricsOverview,
|
||||
VelocityTrend,
|
||||
} from '@/services/analytics/metrics';
|
||||
import { getToday } from '@/lib/date-utils';
|
||||
|
||||
/**
|
||||
@@ -14,16 +18,19 @@ export async function getWeeklyMetrics(date?: Date): Promise<{
|
||||
try {
|
||||
const targetDate = date || getToday();
|
||||
const metrics = await MetricsService.getWeeklyMetrics(targetDate);
|
||||
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: metrics
|
||||
data: metrics,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error fetching weekly metrics:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to fetch weekly metrics'
|
||||
error:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Failed to fetch weekly metrics',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -40,22 +47,24 @@ export async function getVelocityTrends(weeksBack: number = 4): Promise<{
|
||||
if (weeksBack < 1 || weeksBack > 12) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Invalid weeksBack parameter (must be 1-12)'
|
||||
error: 'Invalid weeksBack parameter (must be 1-12)',
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
const trends = await MetricsService.getVelocityTrends(weeksBack);
|
||||
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: trends
|
||||
data: trends,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error fetching velocity trends:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to fetch velocity trends'
|
||||
error:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Failed to fetch velocity trends',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
'use server';
|
||||
|
||||
import { userPreferencesService } from '@/services/core/user-preferences';
|
||||
import { KanbanFilters, ViewPreferences, ColumnVisibility, TaskStatus } from '@/lib/types';
|
||||
import {
|
||||
KanbanFilters,
|
||||
ViewPreferences,
|
||||
ColumnVisibility,
|
||||
TaskStatus,
|
||||
} from '@/lib/types';
|
||||
import { Theme } from '@/lib/ui-config';
|
||||
import { revalidatePath } from 'next/cache';
|
||||
import { getServerSession } from 'next-auth';
|
||||
@@ -10,7 +15,9 @@ import { authOptions } from '@/lib/auth';
|
||||
/**
|
||||
* Met à jour les préférences de vue
|
||||
*/
|
||||
export async function updateViewPreferences(updates: Partial<ViewPreferences>): Promise<{
|
||||
export async function updateViewPreferences(
|
||||
updates: Partial<ViewPreferences>
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}> {
|
||||
@@ -19,15 +26,18 @@ export async function updateViewPreferences(updates: Partial<ViewPreferences>):
|
||||
if (!session?.user?.id) {
|
||||
return { success: false, error: 'Non authentifié' };
|
||||
}
|
||||
|
||||
await userPreferencesService.updateViewPreferences(session.user.id, updates);
|
||||
|
||||
await userPreferencesService.updateViewPreferences(
|
||||
session.user.id,
|
||||
updates
|
||||
);
|
||||
revalidatePath('/');
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('Erreur updateViewPreferences:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -35,7 +45,9 @@ export async function updateViewPreferences(updates: Partial<ViewPreferences>):
|
||||
/**
|
||||
* Met à jour l'image de fond
|
||||
*/
|
||||
export async function setBackgroundImage(backgroundImage: string | undefined): Promise<{
|
||||
export async function setBackgroundImage(
|
||||
backgroundImage: string | undefined
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}> {
|
||||
@@ -44,15 +56,17 @@ export async function setBackgroundImage(backgroundImage: string | undefined): P
|
||||
if (!session?.user?.id) {
|
||||
return { success: false, error: 'Non authentifié' };
|
||||
}
|
||||
|
||||
await userPreferencesService.updateViewPreferences(session.user.id, { backgroundImage });
|
||||
|
||||
await userPreferencesService.updateViewPreferences(session.user.id, {
|
||||
backgroundImage,
|
||||
});
|
||||
revalidatePath('/');
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('Erreur setBackgroundImage:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -60,7 +74,9 @@ export async function setBackgroundImage(backgroundImage: string | undefined): P
|
||||
/**
|
||||
* Met à jour les filtres Kanban
|
||||
*/
|
||||
export async function updateKanbanFilters(updates: Partial<KanbanFilters>): Promise<{
|
||||
export async function updateKanbanFilters(
|
||||
updates: Partial<KanbanFilters>
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}> {
|
||||
@@ -69,7 +85,7 @@ export async function updateKanbanFilters(updates: Partial<KanbanFilters>): Prom
|
||||
if (!session?.user?.id) {
|
||||
return { success: false, error: 'Non authentifié' };
|
||||
}
|
||||
|
||||
|
||||
await userPreferencesService.updateKanbanFilters(session.user.id, updates);
|
||||
revalidatePath('/kanban');
|
||||
return { success: true };
|
||||
@@ -77,7 +93,7 @@ export async function updateKanbanFilters(updates: Partial<KanbanFilters>): Prom
|
||||
console.error('Erreur updateKanbanFilters:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -85,7 +101,9 @@ export async function updateKanbanFilters(updates: Partial<KanbanFilters>): Prom
|
||||
/**
|
||||
* Met à jour la visibilité des colonnes
|
||||
*/
|
||||
export async function updateColumnVisibility(updates: Partial<ColumnVisibility>): Promise<{
|
||||
export async function updateColumnVisibility(
|
||||
updates: Partial<ColumnVisibility>
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}> {
|
||||
@@ -94,21 +112,26 @@ export async function updateColumnVisibility(updates: Partial<ColumnVisibility>)
|
||||
if (!session?.user?.id) {
|
||||
return { success: false, error: 'Non authentifié' };
|
||||
}
|
||||
|
||||
const preferences = await userPreferencesService.getAllPreferences(session.user.id);
|
||||
|
||||
const preferences = await userPreferencesService.getAllPreferences(
|
||||
session.user.id
|
||||
);
|
||||
const newColumnVisibility: ColumnVisibility = {
|
||||
...preferences.columnVisibility,
|
||||
...updates
|
||||
...updates,
|
||||
};
|
||||
|
||||
await userPreferencesService.saveColumnVisibility(session.user.id, newColumnVisibility);
|
||||
|
||||
await userPreferencesService.saveColumnVisibility(
|
||||
session.user.id,
|
||||
newColumnVisibility
|
||||
);
|
||||
revalidatePath('/kanban');
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('Erreur updateColumnVisibility:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -125,18 +148,22 @@ export async function toggleObjectivesVisibility(): Promise<{
|
||||
if (!session?.user?.id) {
|
||||
return { success: false, error: 'Non authentifié' };
|
||||
}
|
||||
|
||||
const preferences = await userPreferencesService.getAllPreferences(session.user.id);
|
||||
|
||||
const preferences = await userPreferencesService.getAllPreferences(
|
||||
session.user.id
|
||||
);
|
||||
const showObjectives = !preferences.viewPreferences.showObjectives;
|
||||
|
||||
await userPreferencesService.updateViewPreferences(session.user.id, { showObjectives });
|
||||
|
||||
await userPreferencesService.updateViewPreferences(session.user.id, {
|
||||
showObjectives,
|
||||
});
|
||||
revalidatePath('/');
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('Erreur toggleObjectivesVisibility:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -153,18 +180,22 @@ export async function toggleObjectivesCollapse(): Promise<{
|
||||
if (!session?.user?.id) {
|
||||
return { success: false, error: 'Non authentifié' };
|
||||
}
|
||||
|
||||
const preferences = await userPreferencesService.getAllPreferences(session.user.id);
|
||||
|
||||
const preferences = await userPreferencesService.getAllPreferences(
|
||||
session.user.id
|
||||
);
|
||||
const collapseObjectives = !preferences.viewPreferences.collapseObjectives;
|
||||
|
||||
await userPreferencesService.updateViewPreferences(session.user.id, { collapseObjectives });
|
||||
|
||||
await userPreferencesService.updateViewPreferences(session.user.id, {
|
||||
collapseObjectives,
|
||||
});
|
||||
revalidatePath('/');
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('Erreur toggleObjectivesCollapse:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -181,15 +212,17 @@ export async function setTheme(theme: Theme): Promise<{
|
||||
if (!session?.user?.id) {
|
||||
return { success: false, error: 'Non authentifié' };
|
||||
}
|
||||
|
||||
await userPreferencesService.updateViewPreferences(session.user.id, { theme });
|
||||
|
||||
await userPreferencesService.updateViewPreferences(session.user.id, {
|
||||
theme,
|
||||
});
|
||||
revalidatePath('/');
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('Erreur setTheme:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -206,18 +239,23 @@ export async function toggleTheme(): Promise<{
|
||||
if (!session?.user?.id) {
|
||||
return { success: false, error: 'Non authentifié' };
|
||||
}
|
||||
|
||||
const preferences = await userPreferencesService.getAllPreferences(session.user.id);
|
||||
const newTheme = preferences.viewPreferences.theme === 'dark' ? 'light' : 'dark';
|
||||
|
||||
await userPreferencesService.updateViewPreferences(session.user.id, { theme: newTheme });
|
||||
|
||||
const preferences = await userPreferencesService.getAllPreferences(
|
||||
session.user.id
|
||||
);
|
||||
const newTheme =
|
||||
preferences.viewPreferences.theme === 'dark' ? 'light' : 'dark';
|
||||
|
||||
await userPreferencesService.updateViewPreferences(session.user.id, {
|
||||
theme: newTheme,
|
||||
});
|
||||
revalidatePath('/');
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('Erreur toggleTheme:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -234,21 +272,31 @@ export async function toggleFontSize(): Promise<{
|
||||
if (!session?.user?.id) {
|
||||
return { success: false, error: 'Non authentifié' };
|
||||
}
|
||||
|
||||
const preferences = await userPreferencesService.getAllPreferences(session.user.id);
|
||||
const fontSizes: ('small' | 'medium' | 'large')[] = ['small', 'medium', 'large'];
|
||||
const currentIndex = fontSizes.indexOf(preferences.viewPreferences.fontSize);
|
||||
|
||||
const preferences = await userPreferencesService.getAllPreferences(
|
||||
session.user.id
|
||||
);
|
||||
const fontSizes: ('small' | 'medium' | 'large')[] = [
|
||||
'small',
|
||||
'medium',
|
||||
'large',
|
||||
];
|
||||
const currentIndex = fontSizes.indexOf(
|
||||
preferences.viewPreferences.fontSize
|
||||
);
|
||||
const nextIndex = (currentIndex + 1) % fontSizes.length;
|
||||
const newFontSize = fontSizes[nextIndex];
|
||||
|
||||
await userPreferencesService.updateViewPreferences(session.user.id, { fontSize: newFontSize });
|
||||
|
||||
await userPreferencesService.updateViewPreferences(session.user.id, {
|
||||
fontSize: newFontSize,
|
||||
});
|
||||
revalidatePath('/');
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('Erreur toggleFontSize:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -266,26 +314,28 @@ export async function toggleColumnVisibility(status: TaskStatus): Promise<{
|
||||
return { success: false, error: 'Non authentifié' };
|
||||
}
|
||||
|
||||
const preferences = await userPreferencesService.getAllPreferences(session.user.id);
|
||||
const preferences = await userPreferencesService.getAllPreferences(
|
||||
session.user.id
|
||||
);
|
||||
const hiddenStatuses = new Set(preferences.columnVisibility.hiddenStatuses);
|
||||
|
||||
|
||||
if (hiddenStatuses.has(status)) {
|
||||
hiddenStatuses.delete(status);
|
||||
} else {
|
||||
hiddenStatuses.add(status);
|
||||
}
|
||||
|
||||
|
||||
await userPreferencesService.saveColumnVisibility(session.user.id, {
|
||||
hiddenStatuses: Array.from(hiddenStatuses)
|
||||
hiddenStatuses: Array.from(hiddenStatuses),
|
||||
});
|
||||
|
||||
|
||||
revalidatePath('/kanban');
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('Erreur toggleColumnVisibility:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,55 +1,67 @@
|
||||
'use server'
|
||||
'use server';
|
||||
|
||||
import { getServerSession } from 'next-auth/next'
|
||||
import { authOptions } from '@/lib/auth'
|
||||
import { usersService } from '@/services/users'
|
||||
import { revalidatePath } from 'next/cache'
|
||||
import { getGravatarUrl } from '@/lib/gravatar'
|
||||
import { getServerSession } from 'next-auth/next';
|
||||
import { authOptions } from '@/lib/auth';
|
||||
import { usersService } from '@/services/users';
|
||||
import { revalidatePath } from 'next/cache';
|
||||
import { getGravatarUrl } from '@/lib/gravatar';
|
||||
|
||||
export async function updateProfile(formData: {
|
||||
name?: string
|
||||
firstName?: string
|
||||
lastName?: string
|
||||
avatar?: string
|
||||
useGravatar?: boolean
|
||||
name?: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
avatar?: string;
|
||||
useGravatar?: boolean;
|
||||
}) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions)
|
||||
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return { success: false, error: 'Non authentifié' }
|
||||
return { success: false, error: 'Non authentifié' };
|
||||
}
|
||||
|
||||
// Validation
|
||||
if (formData.firstName && formData.firstName.length > 50) {
|
||||
return { success: false, error: 'Le prénom ne peut pas dépasser 50 caractères' }
|
||||
return {
|
||||
success: false,
|
||||
error: 'Le prénom ne peut pas dépasser 50 caractères',
|
||||
};
|
||||
}
|
||||
|
||||
if (formData.lastName && formData.lastName.length > 50) {
|
||||
return { success: false, error: 'Le nom ne peut pas dépasser 50 caractères' }
|
||||
return {
|
||||
success: false,
|
||||
error: 'Le nom ne peut pas dépasser 50 caractères',
|
||||
};
|
||||
}
|
||||
|
||||
if (formData.name && formData.name.length > 100) {
|
||||
return { success: false, error: 'Le nom d\'affichage ne peut pas dépasser 100 caractères' }
|
||||
return {
|
||||
success: false,
|
||||
error: "Le nom d'affichage ne peut pas dépasser 100 caractères",
|
||||
};
|
||||
}
|
||||
|
||||
if (formData.avatar && formData.avatar.length > 500) {
|
||||
return { success: false, error: 'L\'URL de l\'avatar ne peut pas dépasser 500 caractères' }
|
||||
return {
|
||||
success: false,
|
||||
error: "L'URL de l'avatar ne peut pas dépasser 500 caractères",
|
||||
};
|
||||
}
|
||||
|
||||
// Déterminer l'URL de l'avatar
|
||||
let finalAvatarUrl: string | null = null
|
||||
|
||||
let finalAvatarUrl: string | null = null;
|
||||
|
||||
if (formData.useGravatar) {
|
||||
// Utiliser Gravatar si demandé
|
||||
finalAvatarUrl = getGravatarUrl(session.user.email || '', { size: 200 })
|
||||
finalAvatarUrl = getGravatarUrl(session.user.email || '', { size: 200 });
|
||||
} else if (formData.avatar) {
|
||||
// Utiliser l'URL custom si fournie
|
||||
finalAvatarUrl = formData.avatar
|
||||
finalAvatarUrl = formData.avatar;
|
||||
} else {
|
||||
// Garder l'avatar actuel ou null
|
||||
const currentUser = await usersService.getUserById(session.user.id)
|
||||
finalAvatarUrl = currentUser?.avatar || null
|
||||
const currentUser = await usersService.getUserById(session.user.id);
|
||||
finalAvatarUrl = currentUser?.avatar || null;
|
||||
}
|
||||
|
||||
// Mettre à jour l'utilisateur
|
||||
@@ -58,10 +70,10 @@ export async function updateProfile(formData: {
|
||||
firstName: formData.firstName || null,
|
||||
lastName: formData.lastName || null,
|
||||
avatar: finalAvatarUrl,
|
||||
})
|
||||
});
|
||||
|
||||
// Revalider la page de profil
|
||||
revalidatePath('/profile')
|
||||
revalidatePath('/profile');
|
||||
|
||||
return {
|
||||
success: true,
|
||||
@@ -75,27 +87,26 @@ export async function updateProfile(formData: {
|
||||
role: updatedUser.role,
|
||||
createdAt: updatedUser.createdAt.toISOString(),
|
||||
lastLoginAt: updatedUser.lastLoginAt?.toISOString() || null,
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Profile update error:', error)
|
||||
return { success: false, error: 'Erreur lors de la mise à jour du profil' }
|
||||
console.error('Profile update error:', error);
|
||||
return { success: false, error: 'Erreur lors de la mise à jour du profil' };
|
||||
}
|
||||
}
|
||||
|
||||
export async function getProfile() {
|
||||
try {
|
||||
const session = await getServerSession(authOptions)
|
||||
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return { success: false, error: 'Non authentifié' }
|
||||
return { success: false, error: 'Non authentifié' };
|
||||
}
|
||||
|
||||
const user = await usersService.getUserById(session.user.id)
|
||||
|
||||
const user = await usersService.getUserById(session.user.id);
|
||||
|
||||
if (!user) {
|
||||
return { success: false, error: 'Utilisateur non trouvé' }
|
||||
return { success: false, error: 'Utilisateur non trouvé' };
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -110,37 +121,39 @@ export async function getProfile() {
|
||||
role: user.role,
|
||||
createdAt: user.createdAt.toISOString(),
|
||||
lastLoginAt: user.lastLoginAt?.toISOString() || null,
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Profile get error:', error)
|
||||
return { success: false, error: 'Erreur lors de la récupération du profil' }
|
||||
console.error('Profile get error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: 'Erreur lors de la récupération du profil',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function applyGravatar() {
|
||||
try {
|
||||
const session = await getServerSession(authOptions)
|
||||
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return { success: false, error: 'Non authentifié' }
|
||||
return { success: false, error: 'Non authentifié' };
|
||||
}
|
||||
|
||||
if (!session.user?.email) {
|
||||
return { success: false, error: 'Email requis pour Gravatar' }
|
||||
return { success: false, error: 'Email requis pour Gravatar' };
|
||||
}
|
||||
|
||||
// Générer l'URL Gravatar
|
||||
const gravatarUrl = getGravatarUrl(session.user.email, { size: 200 })
|
||||
const gravatarUrl = getGravatarUrl(session.user.email, { size: 200 });
|
||||
|
||||
// Mettre à jour l'utilisateur
|
||||
const updatedUser = await usersService.updateUser(session.user.id, {
|
||||
avatar: gravatarUrl,
|
||||
})
|
||||
});
|
||||
|
||||
// Revalider la page de profil
|
||||
revalidatePath('/profile')
|
||||
revalidatePath('/profile');
|
||||
|
||||
return {
|
||||
success: true,
|
||||
@@ -154,11 +167,10 @@ export async function applyGravatar() {
|
||||
role: updatedUser.role,
|
||||
createdAt: updatedUser.createdAt.toISOString(),
|
||||
lastLoginAt: updatedUser.lastLoginAt?.toISOString() || null,
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Gravatar update error:', error)
|
||||
return { success: false, error: 'Erreur lors de la mise à jour Gravatar' }
|
||||
console.error('Gravatar update error:', error);
|
||||
return { success: false, error: 'Erreur lors de la mise à jour Gravatar' };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,10 @@ export async function getSystemInfo() {
|
||||
return { success: true, data: systemInfo };
|
||||
} catch (error) {
|
||||
console.error('Error getting system info:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to get system info'
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
error instanceof Error ? error.message : 'Failed to get system info',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,18 +19,18 @@ export async function createTag(
|
||||
): Promise<ActionResult<Tag>> {
|
||||
try {
|
||||
const tag = await tagsService.createTag({ name, color });
|
||||
|
||||
|
||||
// Revalider les pages qui utilisent les tags
|
||||
revalidatePath('/');
|
||||
revalidatePath('/kanban');
|
||||
revalidatePath('/tags');
|
||||
|
||||
|
||||
return { success: true, data: tag };
|
||||
} catch (error) {
|
||||
console.error('Error creating tag:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to create tag'
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to create tag',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -44,22 +44,22 @@ export async function updateTag(
|
||||
): Promise<ActionResult<Tag>> {
|
||||
try {
|
||||
const tag = await tagsService.updateTag(tagId, data);
|
||||
|
||||
|
||||
if (!tag) {
|
||||
return { success: false, error: 'Tag non trouvé' };
|
||||
}
|
||||
|
||||
|
||||
// Revalider les pages qui utilisent les tags
|
||||
revalidatePath('/');
|
||||
revalidatePath('/kanban');
|
||||
revalidatePath('/tags');
|
||||
|
||||
|
||||
return { success: true, data: tag };
|
||||
} catch (error) {
|
||||
console.error('Error updating tag:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to update tag'
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to update tag',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -70,19 +70,18 @@ export async function updateTag(
|
||||
export async function deleteTag(tagId: string): Promise<ActionResult> {
|
||||
try {
|
||||
await tagsService.deleteTag(tagId);
|
||||
|
||||
|
||||
// Revalider les pages qui utilisent les tags
|
||||
revalidatePath('/');
|
||||
revalidatePath('/kanban');
|
||||
revalidatePath('/tags');
|
||||
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('Error deleting tag:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to delete tag'
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to delete tag',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
'use server'
|
||||
'use server';
|
||||
|
||||
import { tasksService } from '@/services/task-management/tasks';
|
||||
import { revalidatePath } from 'next/cache';
|
||||
@@ -14,22 +14,23 @@ export type ActionResult<T = unknown> = {
|
||||
* Server Action pour mettre à jour le statut d'une tâche
|
||||
*/
|
||||
export async function updateTaskStatus(
|
||||
taskId: string,
|
||||
taskId: string,
|
||||
status: TaskStatus
|
||||
): Promise<ActionResult> {
|
||||
try {
|
||||
const task = await tasksService.updateTask(taskId, { status });
|
||||
|
||||
|
||||
// Revalidation automatique du cache
|
||||
revalidatePath('/');
|
||||
revalidatePath('/tasks');
|
||||
|
||||
|
||||
return { success: true, data: task };
|
||||
} catch (error) {
|
||||
console.error('Error updating task status:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to update task status'
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
error instanceof Error ? error.message : 'Failed to update task status',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -38,7 +39,7 @@ export async function updateTaskStatus(
|
||||
* Server Action pour mettre à jour le titre d'une tâche
|
||||
*/
|
||||
export async function updateTaskTitle(
|
||||
taskId: string,
|
||||
taskId: string,
|
||||
title: string
|
||||
): Promise<ActionResult> {
|
||||
try {
|
||||
@@ -47,17 +48,18 @@ export async function updateTaskTitle(
|
||||
}
|
||||
|
||||
const task = await tasksService.updateTask(taskId, { title: title.trim() });
|
||||
|
||||
|
||||
// Revalidation automatique du cache
|
||||
revalidatePath('/');
|
||||
revalidatePath('/tasks');
|
||||
|
||||
|
||||
return { success: true, data: task };
|
||||
} catch (error) {
|
||||
console.error('Error updating task title:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to update task title'
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
error instanceof Error ? error.message : 'Failed to update task title',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -68,17 +70,17 @@ export async function updateTaskTitle(
|
||||
export async function deleteTask(taskId: string): Promise<ActionResult> {
|
||||
try {
|
||||
await tasksService.deleteTask(taskId);
|
||||
|
||||
|
||||
// Revalidation automatique du cache
|
||||
revalidatePath('/');
|
||||
revalidatePath('/tasks');
|
||||
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('Error deleting task:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to delete task'
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to delete task',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -98,33 +100,35 @@ export async function updateTask(data: {
|
||||
}): Promise<ActionResult> {
|
||||
try {
|
||||
const updateData: Record<string, unknown> = {};
|
||||
|
||||
|
||||
if (data.title !== undefined) {
|
||||
if (!data.title.trim()) {
|
||||
return { success: false, error: 'Title cannot be empty' };
|
||||
}
|
||||
updateData.title = data.title.trim();
|
||||
}
|
||||
|
||||
if (data.description !== undefined) updateData.description = data.description.trim();
|
||||
|
||||
if (data.description !== undefined)
|
||||
updateData.description = data.description.trim();
|
||||
if (data.status !== undefined) updateData.status = data.status;
|
||||
if (data.priority !== undefined) updateData.priority = data.priority;
|
||||
if (data.tags !== undefined) updateData.tags = data.tags;
|
||||
if (data.primaryTagId !== undefined) updateData.primaryTagId = data.primaryTagId;
|
||||
if (data.primaryTagId !== undefined)
|
||||
updateData.primaryTagId = data.primaryTagId;
|
||||
if (data.dueDate !== undefined) updateData.dueDate = data.dueDate;
|
||||
|
||||
const task = await tasksService.updateTask(data.taskId, updateData);
|
||||
|
||||
|
||||
// Revalidation automatique du cache
|
||||
revalidatePath('/');
|
||||
revalidatePath('/tasks');
|
||||
|
||||
|
||||
return { success: true, data: task };
|
||||
} catch (error) {
|
||||
console.error('Error updating task:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to update task'
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to update task',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -151,19 +155,19 @@ export async function createTask(data: {
|
||||
status: data.status || 'todo',
|
||||
priority: data.priority || 'medium',
|
||||
tags: data.tags || [],
|
||||
primaryTagId: data.primaryTagId
|
||||
primaryTagId: data.primaryTagId,
|
||||
});
|
||||
|
||||
|
||||
// Revalidation automatique du cache
|
||||
revalidatePath('/');
|
||||
revalidatePath('/tasks');
|
||||
|
||||
|
||||
return { success: true, data: task };
|
||||
} catch (error) {
|
||||
console.error('Error creating task:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to create task'
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to create task',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,10 +17,10 @@ export async function saveTfsConfig(config: TfsConfig) {
|
||||
}
|
||||
|
||||
await userPreferencesService.saveTfsConfig(session.user.id, config);
|
||||
|
||||
|
||||
// Réinitialiser le service pour prendre en compte la nouvelle config
|
||||
tfsService.reset();
|
||||
|
||||
|
||||
revalidatePath('/settings/integrations');
|
||||
return {
|
||||
success: true,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import NextAuth from "next-auth"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
import NextAuth from 'next-auth';
|
||||
import { authOptions } from '@/lib/auth';
|
||||
|
||||
const handler = NextAuth(authOptions)
|
||||
const handler = NextAuth(authOptions);
|
||||
|
||||
export { handler as GET, handler as POST }
|
||||
export { handler as GET, handler as POST };
|
||||
|
||||
@@ -1,32 +1,32 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { usersService } from '@/services/users'
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { usersService } from '@/services/users';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const { email, name, firstName, lastName, password } = await request.json()
|
||||
const { email, name, firstName, lastName, password } = await request.json();
|
||||
|
||||
// Validation
|
||||
if (!email || !password) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Email et mot de passe requis' },
|
||||
{ status: 400 }
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (password.length < 6) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Le mot de passe doit contenir au moins 6 caractères' },
|
||||
{ status: 400 }
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Vérifier si l'email existe déjà
|
||||
const emailExists = await usersService.emailExists(email)
|
||||
const emailExists = await usersService.emailExists(email);
|
||||
if (emailExists) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Un compte avec cet email existe déjà' },
|
||||
{ status: 400 }
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Créer l'utilisateur
|
||||
@@ -36,7 +36,7 @@ export async function POST(request: NextRequest) {
|
||||
firstName,
|
||||
lastName,
|
||||
password,
|
||||
})
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
message: 'Compte créé avec succès',
|
||||
@@ -46,14 +46,13 @@ export async function POST(request: NextRequest) {
|
||||
name: user.name,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
}
|
||||
})
|
||||
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Registration error:', error)
|
||||
console.error('Registration error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Erreur lors de la création du compte' },
|
||||
{ status: 500 }
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,16 +7,15 @@ interface RouteParams {
|
||||
}>;
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: RouteParams
|
||||
) {
|
||||
export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const { filename } = await params;
|
||||
|
||||
|
||||
// Vérification de sécurité - s'assurer que c'est bien un fichier de backup
|
||||
if (!filename.startsWith('towercontrol_') ||
|
||||
(!filename.endsWith('.db') && !filename.endsWith('.db.gz'))) {
|
||||
if (
|
||||
!filename.startsWith('towercontrol_') ||
|
||||
(!filename.endsWith('.db') && !filename.endsWith('.db.gz'))
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Invalid backup filename' },
|
||||
{ status: 400 }
|
||||
@@ -24,27 +23,25 @@ export async function DELETE(
|
||||
}
|
||||
|
||||
await backupService.deleteBackup(filename);
|
||||
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: `Backup ${filename} deleted successfully`
|
||||
message: `Backup ${filename} deleted successfully`,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error deleting backup:', error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to delete backup'
|
||||
{
|
||||
success: false,
|
||||
error:
|
||||
error instanceof Error ? error.message : 'Failed to delete backup',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: RouteParams
|
||||
) {
|
||||
export async function POST(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const { filename } = await params;
|
||||
const body = await request.json();
|
||||
@@ -52,8 +49,10 @@ export async function POST(
|
||||
|
||||
if (action === 'restore') {
|
||||
// Vérification de sécurité
|
||||
if (!filename.startsWith('towercontrol_') ||
|
||||
(!filename.endsWith('.db') && !filename.endsWith('.db.gz'))) {
|
||||
if (
|
||||
!filename.startsWith('towercontrol_') ||
|
||||
(!filename.endsWith('.db') && !filename.endsWith('.db.gz'))
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Invalid backup filename' },
|
||||
{ status: 400 }
|
||||
@@ -63,16 +62,19 @@ export async function POST(
|
||||
// Protection environnement de production
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Restore not allowed in production via API' },
|
||||
{
|
||||
success: false,
|
||||
error: 'Restore not allowed in production via API',
|
||||
},
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
await backupService.restoreBackup(filename);
|
||||
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: `Database restored from ${filename}`
|
||||
message: `Database restored from ${filename}`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -83,12 +85,11 @@ export async function POST(
|
||||
} catch (error) {
|
||||
console.error('Error in backup operation:', error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Operation failed'
|
||||
{
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Operation failed',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,57 +10,61 @@ export async function GET(request: NextRequest) {
|
||||
if (action === 'logs') {
|
||||
const maxLines = parseInt(searchParams.get('maxLines') || '100');
|
||||
const logs = await backupService.getBackupLogs(maxLines);
|
||||
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: { logs }
|
||||
data: { logs },
|
||||
});
|
||||
}
|
||||
|
||||
if (action === 'stats') {
|
||||
const days = parseInt(searchParams.get('days') || '30');
|
||||
const stats = await backupService.getBackupStats(days);
|
||||
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: stats
|
||||
data: stats,
|
||||
});
|
||||
}
|
||||
|
||||
console.log('🔄 API GET /api/backups called');
|
||||
|
||||
|
||||
// Test de la configuration d'abord
|
||||
const config = backupService.getConfig();
|
||||
console.log('✅ Config loaded:', config);
|
||||
|
||||
|
||||
// Test du scheduler
|
||||
const schedulerStatus = backupScheduler.getStatus();
|
||||
console.log('✅ Scheduler status:', schedulerStatus);
|
||||
|
||||
|
||||
// Test de la liste des backups
|
||||
const backups = await backupService.listBackups();
|
||||
console.log('✅ Backups loaded:', backups.length);
|
||||
|
||||
|
||||
const response = {
|
||||
success: true,
|
||||
data: {
|
||||
backups,
|
||||
scheduler: schedulerStatus,
|
||||
config,
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
console.log('✅ API response ready');
|
||||
return NextResponse.json(response);
|
||||
} catch (error) {
|
||||
console.error('❌ Error fetching backups:', error);
|
||||
console.error('Error stack:', error instanceof Error ? error.stack : 'Unknown');
|
||||
|
||||
console.error(
|
||||
'Error stack:',
|
||||
error instanceof Error ? error.stack : 'Unknown'
|
||||
);
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to fetch backups',
|
||||
details: error instanceof Error ? error.stack : undefined
|
||||
{
|
||||
success: false,
|
||||
error:
|
||||
error instanceof Error ? error.message : 'Failed to fetch backups',
|
||||
details: error instanceof Error ? error.stack : undefined,
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
@@ -76,34 +80,38 @@ export async function POST(request: NextRequest) {
|
||||
case 'create':
|
||||
const forceCreate = params.force === true;
|
||||
const backup = await backupService.createBackup('manual', forceCreate);
|
||||
|
||||
|
||||
if (backup === null) {
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
skipped: true,
|
||||
message: 'No changes detected since last backup. Use force=true to create anyway.'
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
skipped: true,
|
||||
message:
|
||||
'No changes detected since last backup. Use force=true to create anyway.',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
return NextResponse.json({ success: true, data: backup });
|
||||
|
||||
case 'verify':
|
||||
await backupService.verifyDatabaseHealth();
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Database health check passed'
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Database health check passed',
|
||||
});
|
||||
|
||||
case 'config':
|
||||
await backupService.updateConfig(params.config);
|
||||
// Redémarrer le scheduler si la config a changé
|
||||
if (params.config.enabled !== undefined || params.config.interval !== undefined) {
|
||||
if (
|
||||
params.config.enabled !== undefined ||
|
||||
params.config.interval !== undefined
|
||||
) {
|
||||
backupScheduler.restart();
|
||||
}
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Configuration updated',
|
||||
data: backupService.getConfig()
|
||||
data: backupService.getConfig(),
|
||||
});
|
||||
|
||||
case 'scheduler':
|
||||
@@ -112,9 +120,9 @@ export async function POST(request: NextRequest) {
|
||||
} else {
|
||||
backupScheduler.stop();
|
||||
}
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: backupScheduler.getStatus()
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: backupScheduler.getStatus(),
|
||||
});
|
||||
|
||||
default:
|
||||
@@ -126,9 +134,9 @@ export async function POST(request: NextRequest) {
|
||||
} catch (error) {
|
||||
console.error('Error in backup operation:', error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
{
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
|
||||
@@ -7,7 +7,7 @@ export async function PATCH(
|
||||
) {
|
||||
try {
|
||||
const { id: checkboxId } = await params;
|
||||
|
||||
|
||||
if (!checkboxId) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Checkbox ID is required' },
|
||||
|
||||
@@ -9,7 +9,6 @@ export async function GET() {
|
||||
try {
|
||||
const dates = await dailyService.getDailyDates();
|
||||
return NextResponse.json({ dates });
|
||||
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de la récupération des dates:', error);
|
||||
return NextResponse.json(
|
||||
|
||||
@@ -5,17 +5,21 @@ import { DailyCheckboxType } from '@/lib/types';
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
|
||||
const maxDays = searchParams.get('maxDays') ? parseInt(searchParams.get('maxDays')!) : undefined;
|
||||
|
||||
const maxDays = searchParams.get('maxDays')
|
||||
? parseInt(searchParams.get('maxDays')!)
|
||||
: undefined;
|
||||
const excludeToday = searchParams.get('excludeToday') === 'true';
|
||||
const type = searchParams.get('type') as DailyCheckboxType | undefined;
|
||||
const limit = searchParams.get('limit') ? parseInt(searchParams.get('limit')!) : undefined;
|
||||
const limit = searchParams.get('limit')
|
||||
? parseInt(searchParams.get('limit')!)
|
||||
: undefined;
|
||||
|
||||
const pendingCheckboxes = await dailyService.getPendingCheckboxes({
|
||||
maxDays,
|
||||
excludeToday,
|
||||
type,
|
||||
limit
|
||||
limit,
|
||||
});
|
||||
|
||||
return NextResponse.json(pendingCheckboxes);
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { dailyService } from '@/services/task-management/daily';
|
||||
import { getToday, parseDate, isValidAPIDate, createDateFromParts } from '@/lib/date-utils';
|
||||
import {
|
||||
getToday,
|
||||
parseDate,
|
||||
isValidAPIDate,
|
||||
createDateFromParts,
|
||||
} from '@/lib/date-utils';
|
||||
|
||||
/**
|
||||
* API route pour récupérer la vue daily (hier + aujourd'hui)
|
||||
@@ -8,33 +13,36 @@ import { getToday, parseDate, isValidAPIDate, createDateFromParts } from '@/lib/
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
|
||||
|
||||
const action = searchParams.get('action');
|
||||
const date = searchParams.get('date');
|
||||
|
||||
|
||||
if (action === 'history') {
|
||||
// Récupérer l'historique
|
||||
const limit = parseInt(searchParams.get('limit') || '30');
|
||||
const history = await dailyService.getCheckboxHistory(limit);
|
||||
return NextResponse.json(history);
|
||||
}
|
||||
|
||||
|
||||
if (action === 'search') {
|
||||
// Recherche dans les checkboxes
|
||||
const query = searchParams.get('q') || '';
|
||||
const limit = parseInt(searchParams.get('limit') || '20');
|
||||
|
||||
|
||||
if (!query.trim()) {
|
||||
return NextResponse.json({ error: 'Query parameter required' }, { status: 400 });
|
||||
return NextResponse.json(
|
||||
{ error: 'Query parameter required' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
const checkboxes = await dailyService.searchCheckboxes(query, limit);
|
||||
return NextResponse.json(checkboxes);
|
||||
}
|
||||
|
||||
|
||||
// Vue daily pour une date donnée (ou aujourd'hui par défaut)
|
||||
let targetDate: Date;
|
||||
|
||||
|
||||
if (date) {
|
||||
if (!isValidAPIDate(date)) {
|
||||
return NextResponse.json(
|
||||
@@ -46,10 +54,9 @@ export async function GET(request: Request) {
|
||||
} else {
|
||||
targetDate = getToday();
|
||||
}
|
||||
|
||||
|
||||
const dailyView = await dailyService.getDailyView(targetDate);
|
||||
return NextResponse.json(dailyView);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de la récupération du daily:', error);
|
||||
return NextResponse.json(
|
||||
@@ -65,7 +72,7 @@ export async function GET(request: Request) {
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
|
||||
|
||||
// Validation des données
|
||||
if (!body.date || !body.text) {
|
||||
return NextResponse.json(
|
||||
@@ -73,7 +80,7 @@ export async function POST(request: Request) {
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// Parser la date de façon plus robuste
|
||||
let date: Date;
|
||||
if (typeof body.date === 'string') {
|
||||
@@ -83,27 +90,26 @@ export async function POST(request: Request) {
|
||||
} else {
|
||||
date = parseDate(body.date);
|
||||
}
|
||||
|
||||
|
||||
if (isNaN(date.getTime())) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Format de date invalide. Utilisez YYYY-MM-DD' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
const checkbox = await dailyService.addCheckbox({
|
||||
date,
|
||||
text: body.text,
|
||||
type: body.type,
|
||||
taskId: body.taskId,
|
||||
order: body.order,
|
||||
isChecked: body.isChecked
|
||||
isChecked: body.isChecked,
|
||||
});
|
||||
|
||||
|
||||
return NextResponse.json(checkbox, { status: 201 });
|
||||
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de l\'ajout de la checkbox:', error);
|
||||
console.error("Erreur lors de l'ajout de la checkbox:", error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Erreur interne du serveur' },
|
||||
{ status: 500 }
|
||||
|
||||
@@ -9,28 +9,27 @@ export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const limit = parseInt(searchParams.get('limit') || '10');
|
||||
|
||||
|
||||
const logs = await prisma.syncLog.findMany({
|
||||
where: {
|
||||
source: 'jira'
|
||||
source: 'jira',
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: 'desc'
|
||||
createdAt: 'desc',
|
||||
},
|
||||
take: limit
|
||||
take: limit,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
data: logs
|
||||
data: logs,
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Erreur récupération logs Jira:', error);
|
||||
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
{
|
||||
error: 'Erreur lors de la récupération des logs',
|
||||
details: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
details: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { createJiraService, JiraService } from '@/services/integrations/jira/jira';
|
||||
import {
|
||||
createJiraService,
|
||||
JiraService,
|
||||
} from '@/services/integrations/jira/jira';
|
||||
import { userPreferencesService } from '@/services/core/user-preferences';
|
||||
import { jiraScheduler } from '@/services/integrations/jira/scheduler';
|
||||
import { getServerSession } from 'next-auth';
|
||||
@@ -33,23 +36,23 @@ export async function POST(request: Request) {
|
||||
} else {
|
||||
jiraScheduler.stop();
|
||||
}
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: await jiraScheduler.getStatus(session.user.id)
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: await jiraScheduler.getStatus(session.user.id),
|
||||
});
|
||||
|
||||
case 'config':
|
||||
await userPreferencesService.saveJiraSchedulerConfig(
|
||||
session.user.id,
|
||||
params.jiraAutoSync,
|
||||
params.jiraAutoSync,
|
||||
params.jiraSyncInterval
|
||||
);
|
||||
// Redémarrer le scheduler si la config a changé
|
||||
await jiraScheduler.restart(session.user.id);
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Configuration scheduler mise à jour',
|
||||
data: await jiraScheduler.getStatus(session.user.id)
|
||||
data: await jiraScheduler.getStatus(session.user.id),
|
||||
});
|
||||
|
||||
default:
|
||||
@@ -61,11 +64,18 @@ export async function POST(request: Request) {
|
||||
}
|
||||
|
||||
// Synchronisation normale (manuelle)
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(session.user.id);
|
||||
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(
|
||||
session.user.id
|
||||
);
|
||||
|
||||
let jiraService: JiraService | null = null;
|
||||
|
||||
if (jiraConfig.enabled && jiraConfig.baseUrl && jiraConfig.email && jiraConfig.apiToken) {
|
||||
|
||||
if (
|
||||
jiraConfig.enabled &&
|
||||
jiraConfig.baseUrl &&
|
||||
jiraConfig.email &&
|
||||
jiraConfig.apiToken
|
||||
) {
|
||||
// Utiliser la config depuis la base de données
|
||||
jiraService = new JiraService({
|
||||
enabled: jiraConfig.enabled,
|
||||
@@ -73,27 +83,33 @@ export async function POST(request: Request) {
|
||||
email: jiraConfig.email,
|
||||
apiToken: jiraConfig.apiToken,
|
||||
projectKey: jiraConfig.projectKey,
|
||||
ignoredProjects: jiraConfig.ignoredProjects || []
|
||||
ignoredProjects: jiraConfig.ignoredProjects || [],
|
||||
});
|
||||
} else {
|
||||
// Fallback sur les variables d'environnement
|
||||
jiraService = createJiraService();
|
||||
}
|
||||
|
||||
|
||||
if (!jiraService) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Configuration Jira manquante. Configurez Jira dans les paramètres ou vérifiez les variables d\'environnement.' },
|
||||
{
|
||||
error:
|
||||
"Configuration Jira manquante. Configurez Jira dans les paramètres ou vérifiez les variables d'environnement.",
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
console.log('🔄 Début de la synchronisation Jira manuelle...');
|
||||
|
||||
|
||||
// Tester la connexion d'abord
|
||||
const connectionOk = await jiraService.testConnection();
|
||||
if (!connectionOk) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Impossible de se connecter à Jira. Vérifiez la configuration.' },
|
||||
{
|
||||
error:
|
||||
'Impossible de se connecter à Jira. Vérifiez la configuration.',
|
||||
},
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
@@ -111,37 +127,36 @@ export async function POST(request: Request) {
|
||||
tasksDeleted: syncResult.stats.deleted,
|
||||
errors: syncResult.errors,
|
||||
unknownStatuses: syncResult.unknownStatuses || [], // Nouveaux statuts inconnus
|
||||
actions: syncResult.actions.map(action => ({
|
||||
actions: syncResult.actions.map((action) => ({
|
||||
type: action.type as 'created' | 'updated' | 'skipped' | 'deleted',
|
||||
taskKey: action.itemId.toString(),
|
||||
taskTitle: action.title,
|
||||
reason: action.message,
|
||||
changes: action.message ? [action.message] : undefined
|
||||
}))
|
||||
changes: action.message ? [action.message] : undefined,
|
||||
})),
|
||||
};
|
||||
|
||||
if (syncResult.success) {
|
||||
return NextResponse.json({
|
||||
message: 'Synchronisation Jira terminée avec succès',
|
||||
data: jiraSyncResult
|
||||
data: jiraSyncResult,
|
||||
});
|
||||
} else {
|
||||
return NextResponse.json(
|
||||
{
|
||||
{
|
||||
error: 'Synchronisation Jira terminée avec des erreurs',
|
||||
data: jiraSyncResult
|
||||
data: jiraSyncResult,
|
||||
},
|
||||
{ status: 207 } // Multi-Status
|
||||
);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Erreur API sync Jira:', error);
|
||||
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
{
|
||||
error: 'Erreur interne lors de la synchronisation',
|
||||
details: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
details: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
@@ -163,11 +178,18 @@ export async function GET() {
|
||||
}
|
||||
|
||||
// Essayer d'abord la config depuis la base de données
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(session.user.id);
|
||||
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(
|
||||
session.user.id
|
||||
);
|
||||
|
||||
let jiraService: JiraService | null = null;
|
||||
|
||||
if (jiraConfig.enabled && jiraConfig.baseUrl && jiraConfig.email && jiraConfig.apiToken) {
|
||||
|
||||
if (
|
||||
jiraConfig.enabled &&
|
||||
jiraConfig.baseUrl &&
|
||||
jiraConfig.email &&
|
||||
jiraConfig.apiToken
|
||||
) {
|
||||
// Utiliser la config depuis la base de données
|
||||
jiraService = new JiraService({
|
||||
enabled: jiraConfig.enabled,
|
||||
@@ -175,54 +197,55 @@ export async function GET() {
|
||||
email: jiraConfig.email,
|
||||
apiToken: jiraConfig.apiToken,
|
||||
projectKey: jiraConfig.projectKey,
|
||||
ignoredProjects: jiraConfig.ignoredProjects || []
|
||||
ignoredProjects: jiraConfig.ignoredProjects || [],
|
||||
});
|
||||
} else {
|
||||
// Fallback sur les variables d'environnement
|
||||
jiraService = createJiraService();
|
||||
}
|
||||
|
||||
|
||||
if (!jiraService) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
connected: false,
|
||||
message: 'Configuration Jira manquante'
|
||||
}
|
||||
);
|
||||
return NextResponse.json({
|
||||
connected: false,
|
||||
message: 'Configuration Jira manquante',
|
||||
});
|
||||
}
|
||||
|
||||
const connected = await jiraService.testConnection();
|
||||
|
||||
|
||||
// Si connexion OK et qu'un projet est configuré, tester aussi le projet
|
||||
let projectValidation = null;
|
||||
if (connected && jiraConfig.projectKey) {
|
||||
projectValidation = await jiraService.validateProject(jiraConfig.projectKey);
|
||||
projectValidation = await jiraService.validateProject(
|
||||
jiraConfig.projectKey
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// Récupérer aussi le statut du scheduler avec l'utilisateur connecté
|
||||
const schedulerStatus = await jiraScheduler.getStatus(session.user.id);
|
||||
|
||||
|
||||
return NextResponse.json({
|
||||
connected,
|
||||
message: connected ? 'Connexion Jira OK' : 'Impossible de se connecter à Jira',
|
||||
project: projectValidation ? {
|
||||
key: jiraConfig.projectKey,
|
||||
exists: projectValidation.exists,
|
||||
name: projectValidation.name,
|
||||
error: projectValidation.error
|
||||
} : null,
|
||||
scheduler: schedulerStatus
|
||||
message: connected
|
||||
? 'Connexion Jira OK'
|
||||
: 'Impossible de se connecter à Jira',
|
||||
project: projectValidation
|
||||
? {
|
||||
key: jiraConfig.projectKey,
|
||||
exists: projectValidation.exists,
|
||||
name: projectValidation.name,
|
||||
error: projectValidation.error,
|
||||
}
|
||||
: null,
|
||||
scheduler: schedulerStatus,
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Erreur test connexion Jira:', error);
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
connected: false,
|
||||
message: 'Erreur lors du test de connexion',
|
||||
details: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
}
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
connected: false,
|
||||
message: 'Erreur lors du test de connexion',
|
||||
details: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,10 +12,7 @@ export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Non authentifié' },
|
||||
{ status: 401 }
|
||||
);
|
||||
return NextResponse.json({ error: 'Non authentifié' }, { status: 401 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
@@ -29,11 +26,21 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
|
||||
// Récupérer la config Jira depuis la base de données
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(session.user.id);
|
||||
|
||||
if (!jiraConfig.enabled || !jiraConfig.baseUrl || !jiraConfig.email || !jiraConfig.apiToken) {
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(
|
||||
session.user.id
|
||||
);
|
||||
|
||||
if (
|
||||
!jiraConfig.enabled ||
|
||||
!jiraConfig.baseUrl ||
|
||||
!jiraConfig.email ||
|
||||
!jiraConfig.apiToken
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Configuration Jira manquante. Configurez Jira dans les paramètres.' },
|
||||
{
|
||||
error:
|
||||
'Configuration Jira manquante. Configurez Jira dans les paramètres.',
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
@@ -42,37 +49,44 @@ export async function POST(request: NextRequest) {
|
||||
const jiraService = createJiraService();
|
||||
if (!jiraService) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Impossible de créer le service Jira. Vérifiez la configuration.' },
|
||||
{
|
||||
error:
|
||||
'Impossible de créer le service Jira. Vérifiez la configuration.',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
// Valider le projet
|
||||
const validation = await jiraService.validateProject(projectKey.trim().toUpperCase());
|
||||
|
||||
const validation = await jiraService.validateProject(
|
||||
projectKey.trim().toUpperCase()
|
||||
);
|
||||
|
||||
if (validation.exists) {
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
exists: true,
|
||||
projectName: validation.name,
|
||||
message: `Projet "${projectKey}" trouvé : ${validation.name}`
|
||||
message: `Projet "${projectKey}" trouvé : ${validation.name}`,
|
||||
});
|
||||
} else {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
exists: false,
|
||||
error: validation.error,
|
||||
message: validation.error || `Projet "${projectKey}" introuvable`
|
||||
}, { status: 404 });
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
exists: false,
|
||||
error: validation.error,
|
||||
message: validation.error || `Projet "${projectKey}" introuvable`,
|
||||
},
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de la validation du projet Jira:', error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
{
|
||||
success: false,
|
||||
error: 'Erreur lors de la validation du projet',
|
||||
message: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
message: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
|
||||
@@ -13,23 +13,19 @@ export async function GET(
|
||||
const tag = await tagsService.getTagById(id);
|
||||
|
||||
if (!tag) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Tag non trouvé' },
|
||||
{ status: 404 }
|
||||
);
|
||||
return NextResponse.json({ error: 'Tag non trouvé' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
data: tag,
|
||||
message: 'Tag récupéré avec succès'
|
||||
message: 'Tag récupéré avec succès',
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de la récupération du tag:', error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
{
|
||||
error: 'Erreur lors de la récupération du tag',
|
||||
message: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
message: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
|
||||
@@ -26,15 +26,14 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
return NextResponse.json({
|
||||
data: tags,
|
||||
message: 'Tags récupérés avec succès'
|
||||
message: 'Tags récupérés avec succès',
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de la récupération des tags:', error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
{
|
||||
error: 'Erreur lors de la récupération des tags',
|
||||
message: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
message: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
|
||||
@@ -2,12 +2,12 @@ import { NextRequest, NextResponse } from 'next/server';
|
||||
import { tasksService } from '@/services/task-management/tasks';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
|
||||
|
||||
if (!id) {
|
||||
return NextResponse.json(
|
||||
{ error: 'ID de tâche requis' },
|
||||
|
||||
@@ -8,7 +8,7 @@ import { TaskStatus } from '@/lib/types';
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
|
||||
|
||||
// Extraire les paramètres de filtre
|
||||
const filters: {
|
||||
status?: TaskStatus[];
|
||||
@@ -17,27 +17,27 @@ export async function GET(request: Request) {
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
} = {};
|
||||
|
||||
|
||||
const status = searchParams.get('status');
|
||||
if (status) {
|
||||
filters.status = status.split(',') as TaskStatus[];
|
||||
}
|
||||
|
||||
|
||||
const source = searchParams.get('source');
|
||||
if (source) {
|
||||
filters.source = source.split(',');
|
||||
}
|
||||
|
||||
|
||||
const search = searchParams.get('search');
|
||||
if (search) {
|
||||
filters.search = search;
|
||||
}
|
||||
|
||||
|
||||
const limit = searchParams.get('limit');
|
||||
if (limit) {
|
||||
filters.limit = parseInt(limit);
|
||||
}
|
||||
|
||||
|
||||
const offset = searchParams.get('offset');
|
||||
if (offset) {
|
||||
filters.offset = parseInt(offset);
|
||||
@@ -52,21 +52,23 @@ export async function GET(request: Request) {
|
||||
data: tasks,
|
||||
stats,
|
||||
filters: filters,
|
||||
count: tasks.length
|
||||
count: tasks.length,
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Erreur lors de la récupération des tâches:', error);
|
||||
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
}, { status: 500 });
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// POST, PATCH, DELETE methods have been migrated to Server Actions
|
||||
// See /src/actions/tasks.ts for:
|
||||
// - createTask (replaces POST)
|
||||
// - updateTask, updateTaskStatus, updateTaskTitle (replaces PATCH)
|
||||
// - updateTask, updateTaskStatus, updateTaskTitle (replaces PATCH)
|
||||
// - deleteTask (replaces DELETE)
|
||||
|
||||
@@ -7,34 +7,40 @@ import { tfsService } from '@/services/integrations/tfs/tfs';
|
||||
export async function DELETE() {
|
||||
try {
|
||||
console.log('🔄 Début de la suppression des tâches TFS...');
|
||||
|
||||
|
||||
// Supprimer via le service singleton
|
||||
const result = await tfsService.deleteAllTasks();
|
||||
|
||||
|
||||
if (result.success) {
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: result.deletedCount > 0
|
||||
? `${result.deletedCount} tâche(s) TFS supprimée(s) avec succès`
|
||||
: 'Aucune tâche TFS trouvée à supprimer',
|
||||
message:
|
||||
result.deletedCount > 0
|
||||
? `${result.deletedCount} tâche(s) TFS supprimée(s) avec succès`
|
||||
: 'Aucune tâche TFS trouvée à supprimer',
|
||||
data: {
|
||||
deletedCount: result.deletedCount
|
||||
}
|
||||
deletedCount: result.deletedCount,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: result.error || 'Erreur lors de la suppression',
|
||||
}, { status: 500 });
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: result.error || 'Erreur lors de la suppression',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Erreur lors de la suppression des tâches TFS:', error);
|
||||
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: 'Erreur lors de la suppression des tâches TFS',
|
||||
details: error instanceof Error ? error.message : 'Erreur inconnue'
|
||||
}, { status: 500 });
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: 'Erreur lors de la suppression des tâches TFS',
|
||||
details: error instanceof Error ? error.message : 'Erreur inconnue',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,21 +12,32 @@ export async function GET() {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ success: false, error: 'Non authentifié' }, { status: 401 });
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Non authentifié' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const schedulerConfig = await userPreferencesService.getTfsSchedulerConfig(session.user.id);
|
||||
|
||||
const schedulerConfig = await userPreferencesService.getTfsSchedulerConfig(
|
||||
session.user.id
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: schedulerConfig
|
||||
data: schedulerConfig,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Erreur récupération config scheduler TFS:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur lors de la récupération'
|
||||
}, { status: 500 });
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Erreur lors de la récupération',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,24 +49,33 @@ export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ success: false, error: 'Non authentifié' }, { status: 401 });
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Non authentifié' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { tfsAutoSync, tfsSyncInterval } = body;
|
||||
|
||||
if (typeof tfsAutoSync !== 'boolean') {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: 'tfsAutoSync doit être un booléen'
|
||||
}, { status: 400 });
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: 'tfsAutoSync doit être un booléen',
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!['hourly', 'daily', 'weekly'].includes(tfsSyncInterval)) {
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: 'tfsSyncInterval doit être hourly, daily ou weekly'
|
||||
}, { status: 400 });
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: 'tfsSyncInterval doit être hourly, daily ou weekly',
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
await userPreferencesService.saveTfsSchedulerConfig(
|
||||
@@ -73,13 +93,19 @@ export async function POST(request: NextRequest) {
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Configuration scheduler TFS mise à jour',
|
||||
data: status
|
||||
data: status,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Erreur sauvegarde config scheduler TFS:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur lors de la sauvegarde'
|
||||
}, { status: 500 });
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Erreur lors de la sauvegarde',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,20 +11,29 @@ export async function GET() {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ success: false, error: 'Non authentifié' }, { status: 401 });
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Non authentifié' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const status = await tfsScheduler.getStatus(session.user.id);
|
||||
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: status
|
||||
data: status,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Erreur récupération statut scheduler TFS:', error);
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur lors de la récupération'
|
||||
}, { status: 500 });
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Erreur lors de la récupération',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,4 +94,3 @@ export async function GET() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,13 +12,12 @@ export async function GET() {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Non authentifié' },
|
||||
{ status: 401 }
|
||||
);
|
||||
return NextResponse.json({ error: 'Non authentifié' }, { status: 401 });
|
||||
}
|
||||
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(session.user.id);
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(
|
||||
session.user.id
|
||||
);
|
||||
return NextResponse.json({ jiraConfig });
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de la récupération de la config Jira:', error);
|
||||
@@ -37,10 +36,7 @@ export async function PUT(request: NextRequest) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Non authentifié' },
|
||||
{ status: 401 }
|
||||
);
|
||||
return NextResponse.json({ error: 'Non authentifié' }, { status: 401 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
@@ -79,20 +75,22 @@ export async function PUT(request: NextRequest) {
|
||||
apiToken: apiToken.trim(),
|
||||
enabled: true,
|
||||
projectKey: projectKey ? projectKey.trim().toUpperCase() : undefined,
|
||||
ignoredProjects: Array.isArray(ignoredProjects)
|
||||
? ignoredProjects.map((p: string) => p.trim().toUpperCase()).filter((p: string) => p.length > 0)
|
||||
: []
|
||||
ignoredProjects: Array.isArray(ignoredProjects)
|
||||
? ignoredProjects
|
||||
.map((p: string) => p.trim().toUpperCase())
|
||||
.filter((p: string) => p.length > 0)
|
||||
: [],
|
||||
};
|
||||
|
||||
await userPreferencesService.saveJiraConfig(session.user.id, jiraConfig);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Configuration Jira sauvegardée avec succès',
|
||||
jiraConfig: {
|
||||
...jiraConfig,
|
||||
apiToken: '••••••••' // Masquer le token dans la réponse
|
||||
}
|
||||
apiToken: '••••••••', // Masquer le token dans la réponse
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de la sauvegarde de la config Jira:', error);
|
||||
@@ -111,10 +109,7 @@ export async function DELETE() {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Non authentifié' },
|
||||
{ status: 401 }
|
||||
);
|
||||
return NextResponse.json({ error: 'Non authentifié' }, { status: 401 });
|
||||
}
|
||||
|
||||
const defaultConfig: JiraConfig = {
|
||||
@@ -122,14 +117,14 @@ export async function DELETE() {
|
||||
email: '',
|
||||
apiToken: '',
|
||||
enabled: false,
|
||||
ignoredProjects: []
|
||||
ignoredProjects: [],
|
||||
};
|
||||
|
||||
await userPreferencesService.saveJiraConfig(session.user.id, defaultConfig);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Configuration Jira réinitialisée avec succès'
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Configuration Jira réinitialisée avec succès',
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de la suppression de la config Jira:', error);
|
||||
|
||||
@@ -16,18 +16,20 @@ export async function GET() {
|
||||
);
|
||||
}
|
||||
|
||||
const preferences = await userPreferencesService.getAllPreferences(session.user.id);
|
||||
|
||||
const preferences = await userPreferencesService.getAllPreferences(
|
||||
session.user.id
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: preferences
|
||||
data: preferences,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de la récupération des préférences:', error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: 'Erreur lors de la récupération des préférences'
|
||||
{
|
||||
success: false,
|
||||
error: 'Erreur lors de la récupération des préférences',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
@@ -48,19 +50,22 @@ export async function PUT(request: NextRequest) {
|
||||
}
|
||||
|
||||
const preferences = await request.json();
|
||||
|
||||
await userPreferencesService.saveAllPreferences(session.user.id, preferences);
|
||||
|
||||
|
||||
await userPreferencesService.saveAllPreferences(
|
||||
session.user.id,
|
||||
preferences
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Préférences sauvegardées avec succès'
|
||||
message: 'Préférences sauvegardées avec succès',
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de la sauvegarde des préférences:', error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: 'Erreur lors de la sauvegarde des préférences'
|
||||
{
|
||||
success: false,
|
||||
error: 'Erreur lors de la sauvegarde des préférences',
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
|
||||
@@ -13,7 +13,12 @@ import { DailySection } from '@/components/daily/DailySection';
|
||||
import { PendingTasksSection } from '@/components/daily/PendingTasksSection';
|
||||
import { dailyClient } from '@/clients/daily-client';
|
||||
import { Header } from '@/components/ui/Header';
|
||||
import { getPreviousWorkday, formatDateLong, isToday, generateDateTitle } from '@/lib/date-utils';
|
||||
import {
|
||||
getPreviousWorkday,
|
||||
formatDateLong,
|
||||
isToday,
|
||||
generateDateTitle,
|
||||
} from '@/lib/date-utils';
|
||||
import { useGlobalKeyboardShortcuts } from '@/hooks/useGlobalKeyboardShortcuts';
|
||||
import { Emoji } from '@/components/ui/Emoji';
|
||||
|
||||
@@ -25,12 +30,12 @@ interface DailyPageClientProps {
|
||||
initialPendingTasks?: DailyCheckbox[];
|
||||
}
|
||||
|
||||
export function DailyPageClient({
|
||||
initialDailyView,
|
||||
initialDailyDates = [],
|
||||
export function DailyPageClient({
|
||||
initialDailyView,
|
||||
initialDailyDates = [],
|
||||
initialDate,
|
||||
initialDeadlineMetrics,
|
||||
initialPendingTasks = []
|
||||
initialPendingTasks = [],
|
||||
}: DailyPageClientProps = {}) {
|
||||
const {
|
||||
dailyView,
|
||||
@@ -51,7 +56,7 @@ export function DailyPageClient({
|
||||
goToNextDay,
|
||||
goToToday,
|
||||
setDate,
|
||||
refreshDailySilent
|
||||
refreshDailySilent,
|
||||
} = useDaily(initialDate, initialDailyView);
|
||||
|
||||
const [dailyDates, setDailyDates] = useState<string[]>(initialDailyDates);
|
||||
@@ -69,19 +74,28 @@ export function DailyPageClient({
|
||||
// Charger les dates avec des dailies pour le calendrier (seulement si pas de données SSR)
|
||||
useEffect(() => {
|
||||
if (initialDailyDates.length === 0) {
|
||||
import('@/clients/daily-client').then(({ dailyClient }) => {
|
||||
return dailyClient.getDailyDates();
|
||||
}).then(setDailyDates).catch(console.error);
|
||||
import('@/clients/daily-client')
|
||||
.then(({ dailyClient }) => {
|
||||
return dailyClient.getDailyDates();
|
||||
})
|
||||
.then(setDailyDates)
|
||||
.catch(console.error);
|
||||
}
|
||||
}, [initialDailyDates.length]);
|
||||
|
||||
const handleAddTodayCheckbox = async (text: string, type: DailyCheckboxType) => {
|
||||
const handleAddTodayCheckbox = async (
|
||||
text: string,
|
||||
type: DailyCheckboxType
|
||||
) => {
|
||||
await addTodayCheckbox(text, type);
|
||||
// Recharger aussi les dates pour le calendrier
|
||||
await refreshDailyDates();
|
||||
};
|
||||
|
||||
const handleAddYesterdayCheckbox = async (text: string, type: DailyCheckboxType) => {
|
||||
const handleAddYesterdayCheckbox = async (
|
||||
text: string,
|
||||
type: DailyCheckboxType
|
||||
) => {
|
||||
await addYesterdayCheckbox(text, type);
|
||||
// Recharger aussi les dates pour le calendrier
|
||||
await refreshDailyDates();
|
||||
@@ -91,7 +105,7 @@ export function DailyPageClient({
|
||||
useGlobalKeyboardShortcuts({
|
||||
onNavigatePrevious: goToPreviousDay,
|
||||
onNavigateNext: goToNextDay,
|
||||
onGoToToday: goToToday
|
||||
onGoToToday: goToToday,
|
||||
});
|
||||
|
||||
const handleToggleCheckbox = async (checkboxId: string) => {
|
||||
@@ -104,12 +118,18 @@ export function DailyPageClient({
|
||||
await refreshDailyDates();
|
||||
};
|
||||
|
||||
const handleUpdateCheckbox = async (checkboxId: string, text: string, type: DailyCheckboxType, taskId?: string, date?: Date) => {
|
||||
await updateCheckbox(checkboxId, {
|
||||
text,
|
||||
type,
|
||||
const handleUpdateCheckbox = async (
|
||||
checkboxId: string,
|
||||
text: string,
|
||||
type: DailyCheckboxType,
|
||||
taskId?: string,
|
||||
date?: Date
|
||||
) => {
|
||||
await updateCheckbox(checkboxId, {
|
||||
text,
|
||||
type,
|
||||
taskId, // Permet la liaison tâche pour tous les types
|
||||
date // Permet la modification de la date/heure
|
||||
date, // Permet la modification de la date/heure
|
||||
});
|
||||
// Refresh dates après modification pour mettre à jour le calendrier si la date a changé
|
||||
if (date) {
|
||||
@@ -121,7 +141,6 @@ export function DailyPageClient({
|
||||
await reorderCheckboxes({ date, checkboxIds });
|
||||
};
|
||||
|
||||
|
||||
const getYesterdayDate = () => {
|
||||
return getPreviousWorkday(currentDate);
|
||||
};
|
||||
@@ -144,49 +163,71 @@ export function DailyPageClient({
|
||||
|
||||
const getTodayTitle = () => {
|
||||
const { emoji, text } = generateDateTitle(currentDate, '🎯');
|
||||
return <><Emoji emoji={emoji} /> {text}</>;
|
||||
return (
|
||||
<>
|
||||
<Emoji emoji={emoji} /> {text}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const getYesterdayTitle = () => {
|
||||
const yesterdayDate = getYesterdayDate();
|
||||
const { emoji, text } = generateDateTitle(yesterdayDate, '📋');
|
||||
return <><Emoji emoji={emoji} /> {text}</>;
|
||||
return (
|
||||
<>
|
||||
<Emoji emoji={emoji} /> {text}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
// Convertir les métriques de deadline en AlertItem
|
||||
const convertDeadlineMetricsToAlertItems = (metrics: DeadlineMetrics | null): AlertItem[] => {
|
||||
const convertDeadlineMetricsToAlertItems = (
|
||||
metrics: DeadlineMetrics | null
|
||||
): AlertItem[] => {
|
||||
if (!metrics) return [];
|
||||
|
||||
|
||||
const urgentTasks = [
|
||||
...metrics.overdue,
|
||||
...metrics.critical,
|
||||
...metrics.warning
|
||||
...metrics.warning,
|
||||
].sort((a, b) => {
|
||||
const urgencyOrder: Record<string, number> = { 'overdue': 0, 'critical': 1, 'warning': 2 };
|
||||
const urgencyOrder: Record<string, number> = {
|
||||
overdue: 0,
|
||||
critical: 1,
|
||||
warning: 2,
|
||||
};
|
||||
if (urgencyOrder[a.urgencyLevel] !== urgencyOrder[b.urgencyLevel]) {
|
||||
return urgencyOrder[a.urgencyLevel] - urgencyOrder[b.urgencyLevel];
|
||||
}
|
||||
return a.daysRemaining - b.daysRemaining;
|
||||
});
|
||||
|
||||
return urgentTasks.map(task => ({
|
||||
return urgentTasks.map((task) => ({
|
||||
id: task.id,
|
||||
title: task.title,
|
||||
icon: task.urgencyLevel === 'overdue' ? '🔴' :
|
||||
task.urgencyLevel === 'critical' ? '🟠' : '🟡',
|
||||
icon:
|
||||
task.urgencyLevel === 'overdue'
|
||||
? '🔴'
|
||||
: task.urgencyLevel === 'critical'
|
||||
? '🟠'
|
||||
: '🟡',
|
||||
urgency: task.urgencyLevel as 'low' | 'medium' | 'high' | 'critical',
|
||||
source: task.source,
|
||||
metadata: task.urgencyLevel === 'overdue' ?
|
||||
(task.daysRemaining === -1 ? 'En retard de 1 jour' : `En retard de ${Math.abs(task.daysRemaining)} jours`) :
|
||||
task.urgencyLevel === 'critical' ?
|
||||
(task.daysRemaining === 0 ? 'Échéance aujourd\'hui' :
|
||||
task.daysRemaining === 1 ? 'Échéance demain' :
|
||||
`Dans ${task.daysRemaining} jours`) :
|
||||
`Dans ${task.daysRemaining} jours`
|
||||
metadata:
|
||||
task.urgencyLevel === 'overdue'
|
||||
? task.daysRemaining === -1
|
||||
? 'En retard de 1 jour'
|
||||
: `En retard de ${Math.abs(task.daysRemaining)} jours`
|
||||
: task.urgencyLevel === 'critical'
|
||||
? task.daysRemaining === 0
|
||||
? "Échéance aujourd'hui"
|
||||
: task.daysRemaining === 1
|
||||
? 'Échéance demain'
|
||||
: `Dans ${task.daysRemaining} jours`
|
||||
: `Dans ${task.daysRemaining} jours`,
|
||||
}));
|
||||
};
|
||||
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
@@ -217,8 +258,8 @@ export function DailyPageClient({
|
||||
return (
|
||||
<div className="min-h-screen bg-[var(--background)]">
|
||||
{/* Header uniforme */}
|
||||
<Header
|
||||
title="TowerControl"
|
||||
<Header
|
||||
title="TowerControl"
|
||||
subtitle="Daily - Gestion quotidienne"
|
||||
syncing={saving}
|
||||
/>
|
||||
@@ -235,7 +276,7 @@ export function DailyPageClient({
|
||||
>
|
||||
←
|
||||
</Button>
|
||||
|
||||
|
||||
<div className="text-center min-w-[200px]">
|
||||
<div className="text-sm font-bold text-[var(--foreground)] font-mono">
|
||||
{formatCurrentDate()}
|
||||
@@ -266,7 +307,9 @@ export function DailyPageClient({
|
||||
<div className="hidden sm:block container mx-auto px-4 pt-4 pb-2">
|
||||
<AlertBanner
|
||||
title="Rappel - Tâches urgentes"
|
||||
items={convertDeadlineMetricsToAlertItems(initialDeadlineMetrics || null)}
|
||||
items={convertDeadlineMetricsToAlertItems(
|
||||
initialDeadlineMetrics || null
|
||||
)}
|
||||
icon="⚠️"
|
||||
variant="warning"
|
||||
onItemClick={(item) => {
|
||||
@@ -296,7 +339,7 @@ export function DailyPageClient({
|
||||
saving={saving}
|
||||
refreshing={refreshing}
|
||||
/>
|
||||
|
||||
|
||||
{/* Calendrier en bas sur mobile */}
|
||||
<Calendar
|
||||
currentDate={currentDate}
|
||||
@@ -375,13 +418,24 @@ export function DailyPageClient({
|
||||
<div className="text-center text-sm text-[var(--muted-foreground)] font-mono">
|
||||
Daily pour {formatCurrentDate()}
|
||||
{' • '}
|
||||
{dailyView.yesterday.length + dailyView.today.length} tâche{dailyView.yesterday.length + dailyView.today.length > 1 ? 's' : ''} au total
|
||||
{dailyView.yesterday.length + dailyView.today.length} tâche
|
||||
{dailyView.yesterday.length + dailyView.today.length > 1
|
||||
? 's'
|
||||
: ''}{' '}
|
||||
au total
|
||||
{' • '}
|
||||
{dailyView.yesterday.filter(cb => cb.isChecked).length + dailyView.today.filter(cb => cb.isChecked).length} complétée{(dailyView.yesterday.filter(cb => cb.isChecked).length + dailyView.today.filter(cb => cb.isChecked).length) > 1 ? 's' : ''}
|
||||
{dailyView.yesterday.filter((cb) => cb.isChecked).length +
|
||||
dailyView.today.filter((cb) => cb.isChecked).length}{' '}
|
||||
complétée
|
||||
{dailyView.yesterday.filter((cb) => cb.isChecked).length +
|
||||
dailyView.today.filter((cb) => cb.isChecked).length >
|
||||
1
|
||||
? 's'
|
||||
: ''}
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,21 +15,24 @@ export const metadata: Metadata = {
|
||||
export default async function DailyPage() {
|
||||
// Récupérer les données côté serveur
|
||||
const today = getToday();
|
||||
|
||||
|
||||
try {
|
||||
const [dailyView, dailyDates, deadlineMetrics, pendingTasks] = await Promise.all([
|
||||
dailyService.getDailyView(today),
|
||||
dailyService.getDailyDates(),
|
||||
DeadlineAnalyticsService.getDeadlineMetrics().catch(() => null), // Graceful fallback
|
||||
dailyService.getPendingCheckboxes({
|
||||
maxDays: 7,
|
||||
excludeToday: true,
|
||||
limit: 50
|
||||
}).catch(() => []) // Graceful fallback
|
||||
]);
|
||||
const [dailyView, dailyDates, deadlineMetrics, pendingTasks] =
|
||||
await Promise.all([
|
||||
dailyService.getDailyView(today),
|
||||
dailyService.getDailyDates(),
|
||||
DeadlineAnalyticsService.getDeadlineMetrics().catch(() => null), // Graceful fallback
|
||||
dailyService
|
||||
.getPendingCheckboxes({
|
||||
maxDays: 7,
|
||||
excludeToday: true,
|
||||
limit: 50,
|
||||
})
|
||||
.catch(() => []), // Graceful fallback
|
||||
]);
|
||||
|
||||
return (
|
||||
<DailyPageClient
|
||||
<DailyPageClient
|
||||
initialDailyView={dailyView}
|
||||
initialDailyDates={dailyDates}
|
||||
initialDate={today}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
@import "tailwindcss";
|
||||
@import 'tailwindcss';
|
||||
|
||||
:root {
|
||||
/* Valeurs par défaut (Light theme) */
|
||||
@@ -22,7 +22,7 @@
|
||||
--blue: #2563eb; /* blue-600 */
|
||||
--gray: #6b7280; /* gray-500 */
|
||||
--gray-light: #e5e7eb; /* gray-200 */
|
||||
|
||||
|
||||
/* Cartes spéciales */
|
||||
--jira-card: #dbeafe; /* blue-100 - clair */
|
||||
--tfs-card: #fed7aa; /* orange-200 - clair */
|
||||
@@ -30,7 +30,7 @@
|
||||
--tfs-border: #f59e0b; /* amber-500 */
|
||||
--jira-text: #1e40af; /* blue-800 - foncé pour contraste */
|
||||
--tfs-text: #92400e; /* amber-800 - foncé pour contraste */
|
||||
|
||||
|
||||
/* Effets de profondeur pour les cards */
|
||||
--card-shadow-light: rgba(0, 0, 0, 0.08);
|
||||
--card-shadow-medium: rgba(0, 0, 0, 0.15);
|
||||
@@ -61,7 +61,7 @@
|
||||
--blue: #2563eb; /* blue-600 */
|
||||
--gray: #6b7280; /* gray-500 */
|
||||
--gray-light: #e5e7eb; /* gray-200 */
|
||||
|
||||
|
||||
/* Cartes spéciales */
|
||||
--jira-card: #dbeafe; /* blue-100 - clair */
|
||||
--tfs-card: #fed7aa; /* orange-200 - clair */
|
||||
@@ -69,7 +69,7 @@
|
||||
--tfs-border: #f59e0b; /* amber-500 */
|
||||
--jira-text: #1e40af; /* blue-800 - foncé pour contraste */
|
||||
--tfs-text: #92400e; /* amber-800 - foncé pour contraste */
|
||||
|
||||
|
||||
/* Effets de profondeur pour les cards */
|
||||
--card-shadow-light: rgba(0, 0, 0, 0.08);
|
||||
--card-shadow-medium: rgba(0, 0, 0, 0.15);
|
||||
@@ -100,7 +100,7 @@
|
||||
--blue: #3b82f6; /* blue-500 */
|
||||
--gray: #9ca3af; /* gray-400 */
|
||||
--gray-light: #374151; /* gray-700 */
|
||||
|
||||
|
||||
/* Cartes spéciales */
|
||||
--jira-card: #475569; /* slate-700 - plus subtil */
|
||||
--tfs-card: #475569; /* slate-600 - plus subtil */
|
||||
@@ -108,7 +108,7 @@
|
||||
--tfs-border: #fb923c; /* orange-400 - plus clair pour contraste */
|
||||
--jira-text: #93c5fd; /* blue-300 - clair pour contraste */
|
||||
--tfs-text: #fdba74; /* orange-300 - clair pour contraste */
|
||||
|
||||
|
||||
/* Effets de profondeur pour les cards */
|
||||
--card-shadow-light: rgba(255, 255, 255, 0.05);
|
||||
--card-shadow-medium: rgba(255, 255, 255, 0.1);
|
||||
@@ -139,7 +139,7 @@
|
||||
--blue: #8be9fd; /* dracula cyan */
|
||||
--gray: #6272a4; /* dracula comment */
|
||||
--gray-light: #44475a; /* dracula current line */
|
||||
|
||||
|
||||
/* Cartes spéciales */
|
||||
--jira-card: #44475a; /* dracula current line - fond neutre */
|
||||
--tfs-card: #44475a; /* dracula current line - fond neutre */
|
||||
@@ -147,7 +147,7 @@
|
||||
--tfs-border: #ffb86c; /* dracula orange */
|
||||
--jira-text: #f8f8f2; /* dracula foreground - texte principal */
|
||||
--tfs-text: #f8f8f2; /* dracula foreground - texte principal */
|
||||
|
||||
|
||||
/* Effets de profondeur pour les cards */
|
||||
--card-shadow-light: rgba(255, 255, 255, 0.05);
|
||||
--card-shadow-medium: rgba(255, 255, 255, 0.1);
|
||||
@@ -178,7 +178,7 @@
|
||||
--blue: #66d9ef; /* monokai cyan */
|
||||
--gray: #75715e; /* monokai comment */
|
||||
--gray-light: #3e3d32; /* monokai selection */
|
||||
|
||||
|
||||
/* Cartes spéciales */
|
||||
--jira-card: #3e3d32; /* monokai selection - fond neutre */
|
||||
--tfs-card: #3e3d32; /* monokai selection - fond neutre */
|
||||
@@ -186,7 +186,7 @@
|
||||
--tfs-border: #fd971f; /* monokai orange */
|
||||
--jira-text: #f8f8f2; /* monokai foreground */
|
||||
--tfs-text: #f8f8f2; /* monokai foreground */
|
||||
|
||||
|
||||
/* Effets de profondeur pour les cards */
|
||||
--card-shadow-light: rgba(255, 255, 255, 0.05);
|
||||
--card-shadow-medium: rgba(255, 255, 255, 0.1);
|
||||
@@ -217,7 +217,7 @@
|
||||
--blue: #5e81ac; /* nord10 */
|
||||
--gray: #4c566a; /* nord3 */
|
||||
--gray-light: #3b4252; /* nord1 */
|
||||
|
||||
|
||||
/* Cartes spéciales */
|
||||
--jira-card: #3b4252; /* nord1 - fond neutre */
|
||||
--tfs-card: #3b4252; /* nord1 - fond neutre */
|
||||
@@ -225,7 +225,7 @@
|
||||
--tfs-border: #d08770; /* nord12 - orange */
|
||||
--jira-text: #d8dee9; /* nord4 - texte principal */
|
||||
--tfs-text: #d8dee9; /* nord4 - texte principal */
|
||||
|
||||
|
||||
/* Effets de profondeur pour les cards */
|
||||
--card-shadow-light: rgba(255, 255, 255, 0.05);
|
||||
--card-shadow-medium: rgba(255, 255, 255, 0.1);
|
||||
@@ -256,7 +256,7 @@
|
||||
--blue: #83a598; /* gruvbox blue */
|
||||
--gray: #a89984; /* gruvbox gray */
|
||||
--gray-light: #3c3836; /* gruvbox bg1 */
|
||||
|
||||
|
||||
/* Cartes spéciales */
|
||||
--jira-card: #3c3836; /* gruvbox bg1 - fond neutre */
|
||||
--tfs-card: #3c3836; /* gruvbox bg1 - fond neutre */
|
||||
@@ -264,7 +264,7 @@
|
||||
--tfs-border: #fe8019; /* gruvbox orange */
|
||||
--jira-text: #ebdbb2; /* gruvbox fg */
|
||||
--tfs-text: #ebdbb2; /* gruvbox fg */
|
||||
|
||||
|
||||
/* Effets de profondeur pour les cards */
|
||||
--card-shadow-light: rgba(255, 255, 255, 0.05);
|
||||
--card-shadow-medium: rgba(255, 255, 255, 0.1);
|
||||
@@ -295,7 +295,7 @@
|
||||
--blue: #7aa2f7; /* tokyo-night blue */
|
||||
--gray: #565f89; /* tokyo-night comment */
|
||||
--gray-light: #24283b; /* tokyo-night bg_highlight */
|
||||
|
||||
|
||||
/* Cartes spéciales */
|
||||
--jira-card: #24283b; /* tokyo-night bg_highlight - fond neutre */
|
||||
--tfs-card: #24283b; /* tokyo-night bg_highlight - fond neutre */
|
||||
@@ -303,7 +303,7 @@
|
||||
--tfs-border: #ff9e64; /* tokyo-night orange */
|
||||
--jira-text: #a9b1d6; /* tokyo-night fg */
|
||||
--tfs-text: #a9b1d6; /* tokyo-night fg */
|
||||
|
||||
|
||||
/* Effets de profondeur pour les cards */
|
||||
--card-shadow-light: rgba(255, 255, 255, 0.05);
|
||||
--card-shadow-medium: rgba(255, 255, 255, 0.1);
|
||||
@@ -334,7 +334,7 @@
|
||||
--blue: #89b4fa; /* catppuccin blue */
|
||||
--gray: #6c7086; /* catppuccin overlay0 */
|
||||
--gray-light: #313244; /* catppuccin surface0 */
|
||||
|
||||
|
||||
/* Cartes spéciales */
|
||||
--jira-card: #313244; /* catppuccin surface0 - fond neutre */
|
||||
--tfs-card: #313244; /* catppuccin surface0 - fond neutre */
|
||||
@@ -342,7 +342,7 @@
|
||||
--tfs-border: #fab387; /* catppuccin peach */
|
||||
--jira-text: #cdd6f4; /* catppuccin text */
|
||||
--tfs-text: #cdd6f4; /* catppuccin text */
|
||||
|
||||
|
||||
/* Effets de profondeur pour les cards */
|
||||
--card-shadow-light: rgba(255, 255, 255, 0.05);
|
||||
--card-shadow-medium: rgba(255, 255, 255, 0.1);
|
||||
@@ -373,7 +373,7 @@
|
||||
--blue: #3e8fb0; /* rose-pine pine */
|
||||
--gray: #6e6a86; /* rose-pine muted */
|
||||
--gray-light: #26233a; /* rose-pine surface */
|
||||
|
||||
|
||||
/* Cartes spéciales */
|
||||
--jira-card: #26233a; /* rose-pine surface - fond neutre */
|
||||
--tfs-card: #26233a; /* rose-pine surface - fond neutre */
|
||||
@@ -381,7 +381,7 @@
|
||||
--tfs-border: #f6c177; /* rose-pine gold - orange/jaune */
|
||||
--jira-text: #e0def4; /* rose-pine text */
|
||||
--tfs-text: #e0def4; /* rose-pine text */
|
||||
|
||||
|
||||
/* Effets de profondeur pour les cards */
|
||||
--card-shadow-light: rgba(255, 255, 255, 0.05);
|
||||
--card-shadow-medium: rgba(255, 255, 255, 0.1);
|
||||
@@ -412,7 +412,7 @@
|
||||
--blue: #61afef; /* one-dark blue */
|
||||
--gray: #5c6370; /* one-dark bg3 */
|
||||
--gray-light: #3e4451; /* one-dark bg1 */
|
||||
|
||||
|
||||
/* Cartes spéciales */
|
||||
--jira-card: #3e4451; /* one-dark bg1 - fond neutre */
|
||||
--tfs-card: #3e4451; /* one-dark bg1 - fond neutre */
|
||||
@@ -420,7 +420,7 @@
|
||||
--tfs-border: #e5c07b; /* one-dark yellow */
|
||||
--jira-text: #abb2bf; /* one-dark fg */
|
||||
--tfs-text: #abb2bf; /* one-dark fg */
|
||||
|
||||
|
||||
/* Effets de profondeur pour les cards */
|
||||
--card-shadow-light: rgba(255, 255, 255, 0.05);
|
||||
--card-shadow-medium: rgba(255, 255, 255, 0.1);
|
||||
@@ -451,7 +451,7 @@
|
||||
--blue: #2196f3; /* material info */
|
||||
--gray: #3c3c3c; /* material outline */
|
||||
--gray-light: #1e1e1e; /* material surface */
|
||||
|
||||
|
||||
/* Cartes spéciales */
|
||||
--jira-card: #1e1e1e; /* material surface - fond neutre */
|
||||
--tfs-card: #1e1e1e; /* material surface - fond neutre */
|
||||
@@ -459,7 +459,7 @@
|
||||
--tfs-border: #ffab40; /* material secondary - orange */
|
||||
--jira-text: #ffffff; /* material on-bg */
|
||||
--tfs-text: #ffffff; /* material on-bg */
|
||||
|
||||
|
||||
/* Effets de profondeur pour les cards */
|
||||
--card-shadow-light: rgba(255, 255, 255, 0.05);
|
||||
--card-shadow-medium: rgba(255, 255, 255, 0.1);
|
||||
@@ -490,7 +490,7 @@
|
||||
--blue: #268bd2; /* solarized blue */
|
||||
--gray: #586e75; /* solarized base01 */
|
||||
--gray-light: #073642; /* solarized base02 */
|
||||
|
||||
|
||||
/* Cartes spéciales */
|
||||
--jira-card: #073642; /* solarized base02 - fond neutre */
|
||||
--tfs-card: #073642; /* solarized base02 - fond neutre */
|
||||
@@ -498,7 +498,7 @@
|
||||
--tfs-border: #b58900; /* solarized yellow */
|
||||
--jira-text: #93a1a1; /* solarized base1 */
|
||||
--tfs-text: #93a1a1; /* solarized base1 */
|
||||
|
||||
|
||||
/* Effets de profondeur pour les cards */
|
||||
--card-shadow-light: rgba(255, 255, 255, 0.05);
|
||||
--card-shadow-medium: rgba(255, 255, 255, 0.1);
|
||||
@@ -606,17 +606,41 @@ body.has-background-image .min-h-screen.bg-\[var\(--background\)\] {
|
||||
|
||||
/* Effets de texture sophistiqués pour les cards */
|
||||
.card-texture-subtle {
|
||||
background-image:
|
||||
radial-gradient(circle at 20% 80%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
|
||||
radial-gradient(circle at 80% 20%, rgba(255, 255, 255, 0.05) 0%, transparent 50%),
|
||||
radial-gradient(circle at 40% 40%, rgba(255, 255, 255, 0.03) 0%, transparent 50%);
|
||||
background-image:
|
||||
radial-gradient(
|
||||
circle at 20% 80%,
|
||||
rgba(255, 255, 255, 0.1) 0%,
|
||||
transparent 50%
|
||||
),
|
||||
radial-gradient(
|
||||
circle at 80% 20%,
|
||||
rgba(255, 255, 255, 0.05) 0%,
|
||||
transparent 50%
|
||||
),
|
||||
radial-gradient(
|
||||
circle at 40% 40%,
|
||||
rgba(255, 255, 255, 0.03) 0%,
|
||||
transparent 50%
|
||||
);
|
||||
}
|
||||
|
||||
.card-texture-dark {
|
||||
background-image:
|
||||
radial-gradient(circle at 20% 80%, rgba(255, 255, 255, 0.05) 0%, transparent 50%),
|
||||
radial-gradient(circle at 80% 20%, rgba(255, 255, 255, 0.02) 0%, transparent 50%),
|
||||
radial-gradient(circle at 40% 40%, rgba(255, 255, 255, 0.01) 0%, transparent 50%);
|
||||
background-image:
|
||||
radial-gradient(
|
||||
circle at 20% 80%,
|
||||
rgba(255, 255, 255, 0.05) 0%,
|
||||
transparent 50%
|
||||
),
|
||||
radial-gradient(
|
||||
circle at 80% 20%,
|
||||
rgba(255, 255, 255, 0.02) 0%,
|
||||
transparent 50%
|
||||
),
|
||||
radial-gradient(
|
||||
circle at 40% 40%,
|
||||
rgba(255, 255, 255, 0.01) 0%,
|
||||
transparent 50%
|
||||
);
|
||||
}
|
||||
|
||||
/* Effets de brillance pour les cards */
|
||||
@@ -647,32 +671,32 @@ body.has-background-image .min-h-screen.bg-\[var\(--background\)\] {
|
||||
|
||||
/* Effets de profondeur améliorés */
|
||||
.card-depth-1 {
|
||||
box-shadow:
|
||||
box-shadow:
|
||||
0 1px 3px var(--card-shadow-light),
|
||||
0 1px 2px var(--card-shadow-light);
|
||||
}
|
||||
|
||||
.card-depth-2 {
|
||||
box-shadow:
|
||||
box-shadow:
|
||||
0 4px 6px -1px var(--card-shadow-light),
|
||||
0 2px 4px -1px var(--card-shadow-light);
|
||||
}
|
||||
|
||||
.card-depth-3 {
|
||||
box-shadow:
|
||||
box-shadow:
|
||||
0 10px 15px -3px var(--card-shadow-medium),
|
||||
0 4px 6px -2px var(--card-shadow-light);
|
||||
}
|
||||
|
||||
.card-glow-primary {
|
||||
box-shadow:
|
||||
box-shadow:
|
||||
0 0 0 1px var(--card-glow-primary),
|
||||
0 4px 6px -1px var(--card-shadow-light),
|
||||
0 2px 4px -1px var(--card-shadow-light);
|
||||
}
|
||||
|
||||
.card-glow-accent {
|
||||
box-shadow:
|
||||
box-shadow:
|
||||
0 0 0 1px var(--card-glow-accent),
|
||||
0 4px 6px -1px var(--card-shadow-light),
|
||||
0 2px 4px -1px var(--card-shadow-light);
|
||||
@@ -737,8 +761,13 @@ body.has-background-image .min-h-screen.bg-\[var\(--background\)\] {
|
||||
|
||||
/* Animations tech */
|
||||
@keyframes glow {
|
||||
0%, 100% { box-shadow: 0 0 5px var(--primary); }
|
||||
50% { box-shadow: 0 0 20px var(--primary); }
|
||||
0%,
|
||||
100% {
|
||||
box-shadow: 0 0 5px var(--primary);
|
||||
}
|
||||
50% {
|
||||
box-shadow: 0 0 20px var(--primary);
|
||||
}
|
||||
}
|
||||
|
||||
.animate-glow {
|
||||
|
||||
@@ -4,7 +4,11 @@ import { useState, useEffect, useMemo } from 'react';
|
||||
import { JiraConfig, JiraAnalytics } from '@/lib/types';
|
||||
import { useJiraAnalytics } from '@/hooks/useJiraAnalytics';
|
||||
import { useJiraExport } from '@/hooks/useJiraExport';
|
||||
import { filterAnalyticsByPeriod, getPeriodInfo, type PeriodFilter } from '@/lib/jira-period-filter';
|
||||
import {
|
||||
filterAnalyticsByPeriod,
|
||||
getPeriodInfo,
|
||||
type PeriodFilter,
|
||||
} from '@/lib/jira-period-filter';
|
||||
import { Header } from '@/components/ui/Header';
|
||||
import { Card, CardHeader, CardContent } from '@/components/ui/Card';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
@@ -24,7 +28,9 @@ import { CollaborationMatrix } from '@/components/jira/CollaborationMatrix';
|
||||
import { SprintComparison } from '@/components/jira/SprintComparison';
|
||||
import AnomalyDetectionPanel from '@/components/jira/AnomalyDetectionPanel';
|
||||
import FilterBar from '@/components/jira/FilterBar';
|
||||
import SprintDetailModal, { SprintDetails } from '@/components/jira/SprintDetailModal';
|
||||
import SprintDetailModal, {
|
||||
SprintDetails,
|
||||
} from '@/components/jira/SprintDetailModal';
|
||||
import { getSprintDetails } from '../../actions/jira-sprint-details';
|
||||
import { useJiraFilters } from '@/hooks/useJiraFilters';
|
||||
import { SprintVelocity } from '@/lib/types';
|
||||
@@ -36,27 +42,46 @@ interface JiraDashboardPageClientProps {
|
||||
initialAnalytics?: JiraAnalytics | null;
|
||||
}
|
||||
|
||||
export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }: JiraDashboardPageClientProps) {
|
||||
const { analytics: rawAnalytics, isLoading, error, loadAnalytics, refreshAnalytics } = useJiraAnalytics(initialAnalytics);
|
||||
const { isExporting, error: exportError, exportCSV, exportJSON } = useJiraExport();
|
||||
const {
|
||||
availableFilters,
|
||||
activeFilters,
|
||||
export function JiraDashboardPageClient({
|
||||
initialJiraConfig,
|
||||
initialAnalytics,
|
||||
}: JiraDashboardPageClientProps) {
|
||||
const {
|
||||
analytics: rawAnalytics,
|
||||
isLoading,
|
||||
error,
|
||||
loadAnalytics,
|
||||
refreshAnalytics,
|
||||
} = useJiraAnalytics(initialAnalytics);
|
||||
const {
|
||||
isExporting,
|
||||
error: exportError,
|
||||
exportCSV,
|
||||
exportJSON,
|
||||
} = useJiraExport();
|
||||
const {
|
||||
availableFilters,
|
||||
activeFilters,
|
||||
filteredAnalytics,
|
||||
applyFilters,
|
||||
hasActiveFilters
|
||||
hasActiveFilters,
|
||||
} = useJiraFilters(rawAnalytics);
|
||||
const [selectedPeriod, setSelectedPeriod] = useState<PeriodFilter>('current');
|
||||
const [selectedSprint, setSelectedSprint] = useState<SprintVelocity | null>(null);
|
||||
const [selectedSprint, setSelectedSprint] = useState<SprintVelocity | null>(
|
||||
null
|
||||
);
|
||||
const [showSprintModal, setShowSprintModal] = useState(false);
|
||||
const [activeTab, setActiveTab] = useState<'overview' | 'velocity' | 'analytics' | 'quality'>('overview');
|
||||
const [activeTab, setActiveTab] = useState<
|
||||
'overview' | 'velocity' | 'analytics' | 'quality'
|
||||
>('overview');
|
||||
|
||||
// Filtrer les analytics selon la période sélectionnée et les filtres avancés
|
||||
const analytics = useMemo(() => {
|
||||
// Si on a des filtres actifs ET des analytics filtrées, utiliser celles-ci
|
||||
// Sinon utiliser les analytics brutes
|
||||
// Si on est en train de charger les filtres, garder les données originales
|
||||
const baseAnalytics = hasActiveFilters && filteredAnalytics ? filteredAnalytics : rawAnalytics;
|
||||
const baseAnalytics =
|
||||
hasActiveFilters && filteredAnalytics ? filteredAnalytics : rawAnalytics;
|
||||
if (!baseAnalytics) return null;
|
||||
return filterAnalyticsByPeriod(baseAnalytics, selectedPeriod);
|
||||
}, [rawAnalytics, filteredAnalytics, selectedPeriod, hasActiveFilters]);
|
||||
@@ -66,10 +91,19 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
|
||||
useEffect(() => {
|
||||
// Charger les analytics au montage seulement si Jira est configuré ET qu'on n'a pas déjà des données
|
||||
if (initialJiraConfig.enabled && initialJiraConfig.projectKey && !initialAnalytics) {
|
||||
if (
|
||||
initialJiraConfig.enabled &&
|
||||
initialJiraConfig.projectKey &&
|
||||
!initialAnalytics
|
||||
) {
|
||||
loadAnalytics();
|
||||
}
|
||||
}, [initialJiraConfig.enabled, initialJiraConfig.projectKey, loadAnalytics, initialAnalytics]);
|
||||
}, [
|
||||
initialJiraConfig.enabled,
|
||||
initialJiraConfig.projectKey,
|
||||
loadAnalytics,
|
||||
initialAnalytics,
|
||||
]);
|
||||
|
||||
// Gestion du clic sur un sprint
|
||||
const handleSprintClick = (sprint: SprintVelocity) => {
|
||||
@@ -82,19 +116,24 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
setSelectedSprint(null);
|
||||
};
|
||||
|
||||
const loadSprintDetails = async (sprintName: string): Promise<SprintDetails> => {
|
||||
const loadSprintDetails = async (
|
||||
sprintName: string
|
||||
): Promise<SprintDetails> => {
|
||||
const result = await getSprintDetails(sprintName);
|
||||
if (result.success && result.data) {
|
||||
return result.data;
|
||||
} else {
|
||||
throw new Error(result.error || 'Erreur lors du chargement des détails du sprint');
|
||||
throw new Error(
|
||||
result.error || 'Erreur lors du chargement des détails du sprint'
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// Vérifier si Jira est configuré
|
||||
const isJiraConfigured = initialJiraConfig.enabled &&
|
||||
initialJiraConfig.baseUrl &&
|
||||
initialJiraConfig.email &&
|
||||
const isJiraConfigured =
|
||||
initialJiraConfig.enabled &&
|
||||
initialJiraConfig.baseUrl &&
|
||||
initialJiraConfig.email &&
|
||||
initialJiraConfig.apiToken;
|
||||
|
||||
const hasProjectConfigured = isJiraConfigured && initialJiraConfig.projectKey;
|
||||
@@ -102,25 +141,26 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
if (!isJiraConfigured) {
|
||||
return (
|
||||
<div className="min-h-screen bg-[var(--background)]">
|
||||
<Header
|
||||
<Header
|
||||
title="TowerControl"
|
||||
subtitle="Dashboard Jira - Analytics d'équipe"
|
||||
/>
|
||||
|
||||
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<Card className="max-w-2xl mx-auto">
|
||||
<CardHeader>
|
||||
<h2 className="text-xl font-semibold"><Emoji emoji="⚙️" /> Configuration requise</h2>
|
||||
<h2 className="text-xl font-semibold">
|
||||
<Emoji emoji="⚙️" /> Configuration requise
|
||||
</h2>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<p className="text-[var(--muted-foreground)]">
|
||||
Jira n'est pas configuré. Vous devez d'abord configurer votre connexion Jira
|
||||
pour accéder aux analytics d'équipe.
|
||||
Jira n'est pas configuré. Vous devez d'abord
|
||||
configurer votre connexion Jira pour accéder aux analytics
|
||||
d'équipe.
|
||||
</p>
|
||||
<Link href="/settings/integrations">
|
||||
<Button variant="primary">
|
||||
Configurer Jira
|
||||
</Button>
|
||||
<Button variant="primary">Configurer Jira</Button>
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -132,25 +172,26 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
if (!hasProjectConfigured) {
|
||||
return (
|
||||
<div className="min-h-screen bg-[var(--background)]">
|
||||
<Header
|
||||
<Header
|
||||
title="TowerControl"
|
||||
subtitle="Dashboard Jira - Analytics d'équipe"
|
||||
/>
|
||||
|
||||
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<Card className="max-w-2xl mx-auto">
|
||||
<CardHeader>
|
||||
<h2 className="text-xl font-semibold"><Emoji emoji="🎯" /> Projet requis</h2>
|
||||
<h2 className="text-xl font-semibold">
|
||||
<Emoji emoji="🎯" /> Projet requis
|
||||
</h2>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<p className="text-[var(--muted-foreground)]">
|
||||
Aucun projet n'est configuré pour les analytics d'équipe.
|
||||
Configurez un projet spécifique à surveiller dans les paramètres Jira.
|
||||
Aucun projet n'est configuré pour les analytics
|
||||
d'équipe. Configurez un projet spécifique à surveiller dans
|
||||
les paramètres Jira.
|
||||
</p>
|
||||
<Link href="/settings/integrations">
|
||||
<Button variant="primary">
|
||||
Configurer un projet
|
||||
</Button>
|
||||
<Button variant="primary">Configurer un projet</Button>
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -161,20 +202,26 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[var(--background)]">
|
||||
<Header
|
||||
<Header
|
||||
title="TowerControl"
|
||||
subtitle={`Analytics Jira - Projet ${initialJiraConfig.projectKey}`}
|
||||
/>
|
||||
|
||||
|
||||
<div className="container mx-auto px-4 py-4">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
{/* Breadcrumb */}
|
||||
<div className="mb-4 text-sm">
|
||||
<Link href="/settings" className="text-[var(--muted-foreground)] hover:text-[var(--primary)]">
|
||||
<Link
|
||||
href="/settings"
|
||||
className="text-[var(--muted-foreground)] hover:text-[var(--primary)]"
|
||||
>
|
||||
Paramètres
|
||||
</Link>
|
||||
<span className="mx-2 text-[var(--muted-foreground)]">/</span>
|
||||
<Link href="/settings/integrations" className="text-[var(--muted-foreground)] hover:text-[var(--primary)]">
|
||||
<Link
|
||||
href="/settings/integrations"
|
||||
className="text-[var(--muted-foreground)] hover:text-[var(--primary)]"
|
||||
>
|
||||
Intégrations
|
||||
</Link>
|
||||
<span className="mx-2 text-[var(--muted-foreground)]">/</span>
|
||||
@@ -189,16 +236,19 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
</h1>
|
||||
<div className="space-y-1">
|
||||
<p className="text-[var(--muted-foreground)]">
|
||||
Surveillance en temps réel du projet {initialJiraConfig.projectKey}
|
||||
Surveillance en temps réel du projet{' '}
|
||||
{initialJiraConfig.projectKey}
|
||||
</p>
|
||||
<p className="text-sm text-[var(--primary)] flex items-center gap-1">
|
||||
<span>{periodInfo.icon}</span>
|
||||
<span>{periodInfo.label}</span>
|
||||
<span className="text-[var(--muted-foreground)]">• {periodInfo.description}</span>
|
||||
<span className="text-[var(--muted-foreground)]">
|
||||
• {periodInfo.description}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Sélecteur de période */}
|
||||
<PeriodSelector
|
||||
@@ -206,19 +256,21 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
{ value: '7d', label: '7j' },
|
||||
{ value: '30d', label: '30j' },
|
||||
{ value: '3m', label: '3m' },
|
||||
{ value: 'current', label: 'Sprint' }
|
||||
{ value: 'current', label: 'Sprint' },
|
||||
]}
|
||||
selectedValue={selectedPeriod}
|
||||
onValueChange={(value) => setSelectedPeriod(value as PeriodFilter)}
|
||||
onValueChange={(value) =>
|
||||
setSelectedPeriod(value as PeriodFilter)
|
||||
}
|
||||
/>
|
||||
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{analytics && (
|
||||
<>
|
||||
<div className="text-xs text-[var(--muted-foreground)] px-2 py-1 bg-[var(--card)] border border-[var(--border)] rounded">
|
||||
💾 Données en cache
|
||||
</div>
|
||||
|
||||
|
||||
{/* Boutons d'export */}
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
@@ -227,7 +279,12 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
variant="ghost"
|
||||
className="text-xs px-2 py-1 h-auto"
|
||||
>
|
||||
{isExporting ? <Emoji emoji="⏳" /> : <Emoji emoji="📊" />} CSV
|
||||
{isExporting ? (
|
||||
<Emoji emoji="⏳" />
|
||||
) : (
|
||||
<Emoji emoji="📊" />
|
||||
)}{' '}
|
||||
CSV
|
||||
</Button>
|
||||
<Button
|
||||
onClick={exportJSON}
|
||||
@@ -240,19 +297,27 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
|
||||
<Button
|
||||
onClick={refreshAnalytics}
|
||||
disabled={isLoading}
|
||||
variant="secondary"
|
||||
>
|
||||
{isLoading ? <><Emoji emoji="⏳" /> Actualisation...</> : <><Emoji emoji="🔄" /> Actualiser</>}
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Emoji emoji="⏳" /> Actualisation...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Emoji emoji="🔄" />
|
||||
Actualiser
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
{/* Contenu principal */}
|
||||
{error && (
|
||||
<AlertBanner
|
||||
@@ -274,9 +339,7 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
/>
|
||||
)}
|
||||
|
||||
{isLoading && !analytics && (
|
||||
<SkeletonGrid count={6} />
|
||||
)}
|
||||
{isLoading && !analytics && <SkeletonGrid count={6} />}
|
||||
|
||||
{analytics && (
|
||||
<div className="space-y-6">
|
||||
@@ -300,23 +363,23 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
{
|
||||
title: 'Tickets',
|
||||
value: analytics.project.totalIssues,
|
||||
color: 'primary'
|
||||
color: 'primary',
|
||||
},
|
||||
{
|
||||
title: 'Équipe',
|
||||
value: analytics.teamMetrics.totalAssignees,
|
||||
color: 'default'
|
||||
color: 'default',
|
||||
},
|
||||
{
|
||||
title: 'Actifs',
|
||||
value: analytics.teamMetrics.activeAssignees,
|
||||
color: 'success'
|
||||
color: 'success',
|
||||
},
|
||||
{
|
||||
title: 'Points',
|
||||
value: analytics.velocityMetrics.currentSprintPoints,
|
||||
color: 'warning'
|
||||
}
|
||||
color: 'warning',
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
@@ -337,13 +400,17 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
{/* Onglets de navigation */}
|
||||
<Tabs
|
||||
items={[
|
||||
{ id: 'overview', label: '📊 Vue d\'ensemble' },
|
||||
{ id: 'overview', label: "📊 Vue d'ensemble" },
|
||||
{ id: 'velocity', label: '🚀 Vélocité & Sprints' },
|
||||
{ id: 'analytics', label: '📈 Analytics avancées' },
|
||||
{ id: 'quality', label: '🎯 Qualité & Collaboration' }
|
||||
{ id: 'quality', label: '🎯 Qualité & Collaboration' },
|
||||
]}
|
||||
activeTab={activeTab}
|
||||
onTabChange={(tabId) => setActiveTab(tabId as 'overview' | 'velocity' | 'analytics' | 'quality')}
|
||||
onTabChange={(tabId) =>
|
||||
setActiveTab(
|
||||
tabId as 'overview' | 'velocity' | 'analytics' | 'quality'
|
||||
)
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Contenu des onglets */}
|
||||
@@ -351,200 +418,244 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
<div className="space-y-6">
|
||||
{/* Info discrète sur le calcul des points */}
|
||||
<div className="text-xs text-[var(--muted-foreground)] bg-[var(--card-column)] px-3 py-2 rounded border border-[var(--border)]">
|
||||
<Emoji emoji="💡" /> <strong>Points :</strong> Utilise les story points Jira si définis, sinon Epic(13), Story(5), Task(3), Bug(2), Subtask(1)
|
||||
<Emoji emoji="💡" /> <strong>Points :</strong> Utilise les
|
||||
story points Jira si définis, sinon Epic(13), Story(5),
|
||||
Task(3), Bug(2), Subtask(1)
|
||||
</div>
|
||||
|
||||
{/* Graphiques principaux */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold"><Emoji emoji="👥" /> Répartition de l'équipe</h3>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<TeamDistributionChart
|
||||
distribution={analytics.teamMetrics.issuesDistribution}
|
||||
className="h-64"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* Graphiques principaux */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold">
|
||||
<Emoji emoji="👥" /> Répartition de l'équipe
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<TeamDistributionChart
|
||||
distribution={
|
||||
analytics.teamMetrics.issuesDistribution
|
||||
}
|
||||
className="h-64"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold"><Emoji emoji="🚀" /> Vélocité des sprints</h3>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<VelocityChart
|
||||
sprintHistory={analytics.velocityMetrics.sprintHistory}
|
||||
className="h-64"
|
||||
onSprintClick={handleSprintClick}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold">
|
||||
<Emoji emoji="🚀" /> Vélocité des sprints
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<VelocityChart
|
||||
sprintHistory={
|
||||
analytics.velocityMetrics.sprintHistory
|
||||
}
|
||||
className="h-64"
|
||||
onSprintClick={handleSprintClick}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Métriques de temps et cycle time */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold"><Emoji emoji="⏱️" /> Cycle Time par type</h3>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CycleTimeChart
|
||||
cycleTimeByType={analytics.cycleTimeMetrics.cycleTimeByType}
|
||||
className="h-64"
|
||||
/>
|
||||
<div className="mt-4 text-center">
|
||||
<div className="text-2xl font-bold text-[var(--primary)]">
|
||||
{analytics.cycleTimeMetrics.averageCycleTime}
|
||||
</div>
|
||||
<div className="text-sm text-[var(--muted-foreground)]">
|
||||
jours en moyenne globale
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold">🚀 Vélocité</h3>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="mb-4">
|
||||
<div className="text-3xl font-bold text-green-500">
|
||||
{analytics.velocityMetrics.averageVelocity}
|
||||
</div>
|
||||
<div className="text-sm text-[var(--muted-foreground)]">
|
||||
points par sprint
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{analytics.velocityMetrics.sprintHistory.map(sprint => (
|
||||
<div key={sprint.sprintName} className="text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span>{sprint.sprintName}</span>
|
||||
<span className="font-mono">
|
||||
{sprint.completedPoints}/{sprint.plannedPoints}
|
||||
</span>
|
||||
{/* Métriques de temps et cycle time */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold">
|
||||
<Emoji emoji="⏱️" /> Cycle Time par type
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CycleTimeChart
|
||||
cycleTimeByType={
|
||||
analytics.cycleTimeMetrics.cycleTimeByType
|
||||
}
|
||||
className="h-64"
|
||||
/>
|
||||
<div className="mt-4 text-center">
|
||||
<div className="text-2xl font-bold text-[var(--primary)]">
|
||||
{analytics.cycleTimeMetrics.averageCycleTime}
|
||||
</div>
|
||||
<div className="w-full bg-[var(--muted)] rounded-full h-1.5 mt-1">
|
||||
<div
|
||||
className="bg-green-500 h-1.5 rounded-full"
|
||||
style={{ width: `${sprint.completionRate}%` }}
|
||||
></div>
|
||||
<div className="text-sm text-[var(--muted-foreground)]">
|
||||
jours en moyenne globale
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Métriques avancées */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold"><Emoji emoji="📉" /> Burndown Chart</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full h-96 overflow-hidden">
|
||||
<BurndownChart
|
||||
sprintHistory={analytics.velocityMetrics.sprintHistory}
|
||||
className="h-full w-full"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold"><Emoji emoji="📈" /> Throughput</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full h-96 overflow-hidden">
|
||||
<ThroughputChart
|
||||
sprintHistory={analytics.velocityMetrics.sprintHistory}
|
||||
className="h-full w-full"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Métriques de qualité */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold"><Emoji emoji="🎯" /> Métriques de qualité</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full overflow-hidden">
|
||||
<QualityMetrics
|
||||
analytics={analytics}
|
||||
className="min-h-96 w-full"
|
||||
/>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold">🚀 Vélocité</h3>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="mb-4">
|
||||
<div className="text-3xl font-bold text-green-500">
|
||||
{analytics.velocityMetrics.averageVelocity}
|
||||
</div>
|
||||
<div className="text-sm text-[var(--muted-foreground)]">
|
||||
points par sprint
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{analytics.velocityMetrics.sprintHistory.map(
|
||||
(sprint) => (
|
||||
<div key={sprint.sprintName} className="text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span>{sprint.sprintName}</span>
|
||||
<span className="font-mono">
|
||||
{sprint.completedPoints}/
|
||||
{sprint.plannedPoints}
|
||||
</span>
|
||||
</div>
|
||||
<div className="w-full bg-[var(--muted)] rounded-full h-1.5 mt-1">
|
||||
<div
|
||||
className="bg-green-500 h-1.5 rounded-full"
|
||||
style={{
|
||||
width: `${sprint.completionRate}%`,
|
||||
}}
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Métriques de predictabilité */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold"><Emoji emoji="📊" /> Predictabilité</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full overflow-hidden">
|
||||
<PredictabilityMetrics
|
||||
sprintHistory={analytics.velocityMetrics.sprintHistory}
|
||||
className="h-auto w-full"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* Métriques avancées */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold">
|
||||
<Emoji emoji="📉" /> Burndown Chart
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full h-96 overflow-hidden">
|
||||
<BurndownChart
|
||||
sprintHistory={
|
||||
analytics.velocityMetrics.sprintHistory
|
||||
}
|
||||
className="h-full w-full"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Matrice de collaboration - ligne entière */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold"><Emoji emoji="🤝" /> Matrice de collaboration</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full overflow-hidden">
|
||||
<CollaborationMatrix
|
||||
analytics={analytics}
|
||||
className="h-auto w-full"
|
||||
/>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold">
|
||||
<Emoji emoji="📈" /> Throughput
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full h-96 overflow-hidden">
|
||||
<ThroughputChart
|
||||
sprintHistory={
|
||||
analytics.velocityMetrics.sprintHistory
|
||||
}
|
||||
className="h-full w-full"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Comparaison inter-sprints */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold"><Emoji emoji="📊" /> Comparaison inter-sprints</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full overflow-hidden">
|
||||
<SprintComparison
|
||||
sprintHistory={analytics.velocityMetrics.sprintHistory}
|
||||
className="h-auto w-full"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* Métriques de qualité */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold">
|
||||
<Emoji emoji="🎯" /> Métriques de qualité
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full overflow-hidden">
|
||||
<QualityMetrics
|
||||
analytics={analytics}
|
||||
className="min-h-96 w-full"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Heatmap d'activité de l'équipe */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold"><Emoji emoji="🔥" /> Heatmap d'activité de l'équipe</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full overflow-hidden">
|
||||
<TeamActivityHeatmap
|
||||
workloadByAssignee={analytics.workInProgress.byAssignee}
|
||||
statusDistribution={analytics.workInProgress.byStatus}
|
||||
className="min-h-96 w-full"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* Métriques de predictabilité */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold">
|
||||
<Emoji emoji="📊" /> Predictabilité
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full overflow-hidden">
|
||||
<PredictabilityMetrics
|
||||
sprintHistory={
|
||||
analytics.velocityMetrics.sprintHistory
|
||||
}
|
||||
className="h-auto w-full"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Matrice de collaboration - ligne entière */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold">
|
||||
<Emoji emoji="🤝" /> Matrice de collaboration
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full overflow-hidden">
|
||||
<CollaborationMatrix
|
||||
analytics={analytics}
|
||||
className="h-auto w-full"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Comparaison inter-sprints */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold">
|
||||
<Emoji emoji="📊" /> Comparaison inter-sprints
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full overflow-hidden">
|
||||
<SprintComparison
|
||||
sprintHistory={
|
||||
analytics.velocityMetrics.sprintHistory
|
||||
}
|
||||
className="h-auto w-full"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Heatmap d'activité de l'équipe */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold">
|
||||
<Emoji emoji="🔥" /> Heatmap d'activité de
|
||||
l'équipe
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full overflow-hidden">
|
||||
<TeamActivityHeatmap
|
||||
workloadByAssignee={
|
||||
analytics.workInProgress.byAssignee
|
||||
}
|
||||
statusDistribution={analytics.workInProgress.byStatus}
|
||||
className="min-h-96 w-full"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -553,12 +664,16 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
{/* Graphique de vélocité */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold"><Emoji emoji="🚀" /> Vélocité des sprints</h3>
|
||||
<h3 className="font-semibold">
|
||||
<Emoji emoji="🚀" /> Vélocité des sprints
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full h-64 overflow-hidden">
|
||||
<VelocityChart
|
||||
sprintHistory={analytics.velocityMetrics.sprintHistory}
|
||||
<VelocityChart
|
||||
sprintHistory={
|
||||
analytics.velocityMetrics.sprintHistory
|
||||
}
|
||||
className="h-full w-full"
|
||||
onSprintClick={handleSprintClick}
|
||||
/>
|
||||
@@ -570,12 +685,16 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold"><Emoji emoji="📉" /> Burndown Chart</h3>
|
||||
<h3 className="font-semibold">
|
||||
<Emoji emoji="📉" /> Burndown Chart
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full h-96 overflow-hidden">
|
||||
<BurndownChart
|
||||
sprintHistory={analytics.velocityMetrics.sprintHistory}
|
||||
<BurndownChart
|
||||
sprintHistory={
|
||||
analytics.velocityMetrics.sprintHistory
|
||||
}
|
||||
className="h-full w-full"
|
||||
/>
|
||||
</div>
|
||||
@@ -584,12 +703,16 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold"><Emoji emoji="📊" /> Throughput</h3>
|
||||
<h3 className="font-semibold">
|
||||
<Emoji emoji="📊" /> Throughput
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full h-96 overflow-hidden">
|
||||
<ThroughputChart
|
||||
sprintHistory={analytics.velocityMetrics.sprintHistory}
|
||||
<ThroughputChart
|
||||
sprintHistory={
|
||||
analytics.velocityMetrics.sprintHistory
|
||||
}
|
||||
className="h-full w-full"
|
||||
/>
|
||||
</div>
|
||||
@@ -600,12 +723,16 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
{/* Comparaison des sprints */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold"><Emoji emoji="📊" /> Comparaison des sprints</h3>
|
||||
<h3 className="font-semibold">
|
||||
<Emoji emoji="📊" /> Comparaison des sprints
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full overflow-hidden">
|
||||
<SprintComparison
|
||||
sprintHistory={analytics.velocityMetrics.sprintHistory}
|
||||
<SprintComparison
|
||||
sprintHistory={
|
||||
analytics.velocityMetrics.sprintHistory
|
||||
}
|
||||
className="h-auto w-full"
|
||||
/>
|
||||
</div>
|
||||
@@ -620,18 +747,24 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold"><Emoji emoji="⏱️" /> Cycle Time par type</h3>
|
||||
<h3 className="font-semibold">
|
||||
<Emoji emoji="⏱️" /> Cycle Time par type
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full h-64 overflow-hidden">
|
||||
<CycleTimeChart
|
||||
cycleTimeByType={analytics.cycleTimeMetrics.cycleTimeByType}
|
||||
<CycleTimeChart
|
||||
cycleTimeByType={
|
||||
analytics.cycleTimeMetrics.cycleTimeByType
|
||||
}
|
||||
className="h-full w-full"
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-4 text-center">
|
||||
<div className="text-2xl font-bold text-[var(--primary)]">
|
||||
{analytics.cycleTimeMetrics.averageCycleTime.toFixed(1)}
|
||||
{analytics.cycleTimeMetrics.averageCycleTime.toFixed(
|
||||
1
|
||||
)}
|
||||
</div>
|
||||
<div className="text-sm text-[var(--muted-foreground)]">
|
||||
Cycle time moyen (jours)
|
||||
@@ -642,13 +775,19 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold">🔥 Heatmap d'activité</h3>
|
||||
<h3 className="font-semibold">
|
||||
🔥 Heatmap d'activité
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full h-64 overflow-hidden">
|
||||
<TeamActivityHeatmap
|
||||
workloadByAssignee={analytics.workInProgress.byAssignee}
|
||||
statusDistribution={analytics.workInProgress.byStatus}
|
||||
<TeamActivityHeatmap
|
||||
workloadByAssignee={
|
||||
analytics.workInProgress.byAssignee
|
||||
}
|
||||
statusDistribution={
|
||||
analytics.workInProgress.byStatus
|
||||
}
|
||||
className="h-full w-full"
|
||||
/>
|
||||
</div>
|
||||
@@ -660,11 +799,13 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold"><Emoji emoji="🎯" /> Métriques de qualité</h3>
|
||||
<h3 className="font-semibold">
|
||||
<Emoji emoji="🎯" /> Métriques de qualité
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full h-64 overflow-hidden">
|
||||
<QualityMetrics
|
||||
<QualityMetrics
|
||||
analytics={analytics}
|
||||
className="h-full w-full"
|
||||
/>
|
||||
@@ -674,12 +815,16 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold"><Emoji emoji="📈" /> Predictabilité</h3>
|
||||
<h3 className="font-semibold">
|
||||
<Emoji emoji="📈" /> Predictabilité
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full h-64 overflow-hidden">
|
||||
<PredictabilityMetrics
|
||||
sprintHistory={analytics.velocityMetrics.sprintHistory}
|
||||
<PredictabilityMetrics
|
||||
sprintHistory={
|
||||
analytics.velocityMetrics.sprintHistory
|
||||
}
|
||||
className="h-full w-full"
|
||||
/>
|
||||
</div>
|
||||
@@ -695,12 +840,16 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold"><Emoji emoji="👥" /> Répartition de l'équipe</h3>
|
||||
<h3 className="font-semibold">
|
||||
<Emoji emoji="👥" /> Répartition de l'équipe
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full h-64 overflow-hidden">
|
||||
<TeamDistributionChart
|
||||
distribution={analytics.teamMetrics.issuesDistribution}
|
||||
<TeamDistributionChart
|
||||
distribution={
|
||||
analytics.teamMetrics.issuesDistribution
|
||||
}
|
||||
className="h-full w-full"
|
||||
/>
|
||||
</div>
|
||||
@@ -709,11 +858,13 @@ export function JiraDashboardPageClient({ initialJiraConfig, initialAnalytics }:
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<h3 className="font-semibold"><Emoji emoji="🤝" /> Matrice de collaboration</h3>
|
||||
<h3 className="font-semibold">
|
||||
<Emoji emoji="🤝" /> Matrice de collaboration
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardContent className="p-4">
|
||||
<div className="w-full h-64 overflow-hidden">
|
||||
<CollaborationMatrix
|
||||
<CollaborationMatrix
|
||||
analytics={analytics}
|
||||
className="h-full w-full"
|
||||
/>
|
||||
|
||||
@@ -14,8 +14,10 @@ export default async function JiraDashboardPage() {
|
||||
}
|
||||
|
||||
// Récupérer la config Jira côté serveur
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(session.user.id);
|
||||
|
||||
const jiraConfig = await userPreferencesService.getJiraConfig(
|
||||
session.user.id
|
||||
);
|
||||
|
||||
// Récupérer les analytics côté serveur (utilise le cache du service)
|
||||
let initialAnalytics = null;
|
||||
if (jiraConfig.enabled && jiraConfig.projectKey) {
|
||||
@@ -26,8 +28,8 @@ export default async function JiraDashboardPage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<JiraDashboardPageClient
|
||||
initialJiraConfig={jiraConfig}
|
||||
<JiraDashboardPageClient
|
||||
initialJiraConfig={jiraConfig}
|
||||
initialAnalytics={initialAnalytics}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -20,8 +20,15 @@ interface KanbanPageClientProps {
|
||||
}
|
||||
|
||||
function KanbanPageContent() {
|
||||
const { syncing, createTask, activeFiltersCount, kanbanFilters, setKanbanFilters } = useTasksContext();
|
||||
const { preferences, updateViewPreferences, toggleFontSize } = useUserPreferences();
|
||||
const {
|
||||
syncing,
|
||||
createTask,
|
||||
activeFiltersCount,
|
||||
kanbanFilters,
|
||||
setKanbanFilters,
|
||||
} = useTasksContext();
|
||||
const { preferences, updateViewPreferences, toggleFontSize } =
|
||||
useUserPreferences();
|
||||
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
|
||||
const isMobile = useIsMobile(768); // Tailwind md breakpoint
|
||||
const searchParams = useSearchParams();
|
||||
@@ -51,9 +58,9 @@ function KanbanPageContent() {
|
||||
};
|
||||
|
||||
const handleToggleDueDateFilter = () => {
|
||||
setKanbanFilters({
|
||||
...kanbanFilters,
|
||||
showWithDueDate: !kanbanFilters.showWithDueDate
|
||||
setKanbanFilters({
|
||||
...kanbanFilters,
|
||||
showWithDueDate: !kanbanFilters.showWithDueDate,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -74,19 +81,21 @@ function KanbanPageContent() {
|
||||
onToggleFontSize: toggleFontSize,
|
||||
onOpenSearch: () => {
|
||||
// Focus sur le champ de recherche dans les contrôles desktop
|
||||
const searchInput = document.querySelector('input[placeholder*="Rechercher"]') as HTMLInputElement;
|
||||
const searchInput = document.querySelector(
|
||||
'input[placeholder*="Rechercher"]'
|
||||
) as HTMLInputElement;
|
||||
searchInput?.focus();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[var(--background)]">
|
||||
<Header
|
||||
title="Kanban Board"
|
||||
<Header
|
||||
title="Kanban Board"
|
||||
subtitle="Gestionnaire de tâches"
|
||||
syncing={syncing}
|
||||
/>
|
||||
|
||||
|
||||
{/* Barre de contrôles responsive */}
|
||||
{isMobile ? (
|
||||
<MobileControls
|
||||
@@ -117,9 +126,9 @@ function KanbanPageContent() {
|
||||
onCreateTask={() => setIsCreateModalOpen(true)}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
<main className="h-[calc(100vh-160px)]">
|
||||
<KanbanBoardContainer
|
||||
<KanbanBoardContainer
|
||||
showFilters={showFilters}
|
||||
showObjectives={showObjectives}
|
||||
initialTaskIdToEdit={taskIdFromUrl}
|
||||
@@ -137,12 +146,12 @@ function KanbanPageContent() {
|
||||
);
|
||||
}
|
||||
|
||||
export function KanbanPageClient({ initialTasks, initialTags }: KanbanPageClientProps) {
|
||||
export function KanbanPageClient({
|
||||
initialTasks,
|
||||
initialTags,
|
||||
}: KanbanPageClientProps) {
|
||||
return (
|
||||
<TasksProvider
|
||||
initialTasks={initialTasks}
|
||||
initialTags={initialTags}
|
||||
>
|
||||
<TasksProvider initialTasks={initialTasks} initialTags={initialTags}>
|
||||
<KanbanPageContent />
|
||||
</TasksProvider>
|
||||
);
|
||||
|
||||
@@ -9,13 +9,10 @@ export default async function KanbanPage() {
|
||||
// SSR - Récupération des données côté serveur
|
||||
const [initialTasks, initialTags] = await Promise.all([
|
||||
tasksService.getTasks(),
|
||||
tagsService.getTags()
|
||||
tagsService.getTags(),
|
||||
]);
|
||||
|
||||
return (
|
||||
<KanbanPageClient
|
||||
initialTasks={initialTasks}
|
||||
initialTags={initialTags}
|
||||
/>
|
||||
<KanbanPageClient initialTasks={initialTasks} initialTags={initialTags} />
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,32 +1,32 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import "./globals.css";
|
||||
import { ThemeProvider } from "@/contexts/ThemeContext";
|
||||
import { BackgroundProvider } from "@/contexts/BackgroundContext";
|
||||
import { JiraConfigProvider } from "@/contexts/JiraConfigContext";
|
||||
import { UserPreferencesProvider } from "@/contexts/UserPreferencesContext";
|
||||
import { KeyboardShortcutsProvider } from "@/contexts/KeyboardShortcutsContext";
|
||||
import { userPreferencesService } from "@/services/core/user-preferences";
|
||||
import { KeyboardShortcuts } from "@/components/KeyboardShortcuts";
|
||||
import { GlobalKeyboardShortcuts } from "@/components/GlobalKeyboardShortcuts";
|
||||
import { ToastProvider } from "@/components/ui/Toast";
|
||||
import { AuthProvider } from "../components/AuthProvider";
|
||||
import type { Metadata } from 'next';
|
||||
import { Geist, Geist_Mono } from 'next/font/google';
|
||||
import './globals.css';
|
||||
import { ThemeProvider } from '@/contexts/ThemeContext';
|
||||
import { BackgroundProvider } from '@/contexts/BackgroundContext';
|
||||
import { JiraConfigProvider } from '@/contexts/JiraConfigContext';
|
||||
import { UserPreferencesProvider } from '@/contexts/UserPreferencesContext';
|
||||
import { KeyboardShortcutsProvider } from '@/contexts/KeyboardShortcutsContext';
|
||||
import { userPreferencesService } from '@/services/core/user-preferences';
|
||||
import { KeyboardShortcuts } from '@/components/KeyboardShortcuts';
|
||||
import { GlobalKeyboardShortcuts } from '@/components/GlobalKeyboardShortcuts';
|
||||
import { ToastProvider } from '@/components/ui/Toast';
|
||||
import { AuthProvider } from '../components/AuthProvider';
|
||||
import { getServerSession } from 'next-auth';
|
||||
import { authOptions } from '@/lib/auth';
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
subsets: ["latin"],
|
||||
variable: '--font-geist-sans',
|
||||
subsets: ['latin'],
|
||||
});
|
||||
|
||||
const geistMono = Geist_Mono({
|
||||
variable: "--font-geist-mono",
|
||||
subsets: ["latin"],
|
||||
variable: '--font-geist-mono',
|
||||
subsets: ['latin'],
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Tower control",
|
||||
description: "Tour de controle (Kanban, tache, daily, ...)",
|
||||
title: 'Tower control',
|
||||
description: 'Tour de controle (Kanban, tache, daily, ...)',
|
||||
};
|
||||
|
||||
export default async function RootLayout({
|
||||
@@ -36,13 +36,13 @@ export default async function RootLayout({
|
||||
}>) {
|
||||
// Récupérer la session côté serveur pour le SSR
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
|
||||
// Charger les préférences seulement si l'utilisateur est connecté
|
||||
// Sinon, les préférences par défaut seront chargées côté client
|
||||
const initialPreferences = session?.user?.id
|
||||
const initialPreferences = session?.user?.id
|
||||
? await userPreferencesService.getAllPreferences(session.user.id)
|
||||
: undefined;
|
||||
|
||||
|
||||
return (
|
||||
<html lang="fr">
|
||||
<body
|
||||
@@ -50,14 +50,24 @@ export default async function RootLayout({
|
||||
>
|
||||
<AuthProvider>
|
||||
<ToastProvider>
|
||||
<ThemeProvider
|
||||
initialTheme={initialPreferences?.viewPreferences.theme || 'light'}
|
||||
userPreferredTheme={initialPreferences?.viewPreferences.theme === 'light' ? 'dark' : initialPreferences?.viewPreferences.theme || 'light'}
|
||||
<ThemeProvider
|
||||
initialTheme={
|
||||
initialPreferences?.viewPreferences.theme || 'light'
|
||||
}
|
||||
userPreferredTheme={
|
||||
initialPreferences?.viewPreferences.theme === 'light'
|
||||
? 'dark'
|
||||
: initialPreferences?.viewPreferences.theme || 'light'
|
||||
}
|
||||
>
|
||||
<KeyboardShortcutsProvider>
|
||||
<KeyboardShortcuts />
|
||||
<JiraConfigProvider config={initialPreferences?.jiraConfig || { enabled: false }}>
|
||||
<UserPreferencesProvider initialPreferences={initialPreferences}>
|
||||
<JiraConfigProvider
|
||||
config={initialPreferences?.jiraConfig || { enabled: false }}
|
||||
>
|
||||
<UserPreferencesProvider
|
||||
initialPreferences={initialPreferences}
|
||||
>
|
||||
<BackgroundProvider>
|
||||
<GlobalKeyboardShortcuts />
|
||||
{children}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
'use client'
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { signIn, getSession, useSession } from 'next-auth/react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import Link from 'next/link'
|
||||
import { Button } from '@/components/ui/Button'
|
||||
import { Input } from '@/components/ui/Input'
|
||||
import { TowerLogo } from '@/components/TowerLogo'
|
||||
import { TowerBackground } from '@/components/TowerBackground'
|
||||
import { THEME_CONFIG } from '@/lib/ui-config'
|
||||
import { useTheme } from '@/contexts/ThemeContext'
|
||||
import { PRESET_BACKGROUNDS } from '@/lib/ui-config'
|
||||
import { useState, useEffect } from 'react';
|
||||
import { signIn, getSession, useSession } from 'next-auth/react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import { TowerLogo } from '@/components/TowerLogo';
|
||||
import { TowerBackground } from '@/components/TowerBackground';
|
||||
import { THEME_CONFIG } from '@/lib/ui-config';
|
||||
import { useTheme } from '@/contexts/ThemeContext';
|
||||
import { PRESET_BACKGROUNDS } from '@/lib/ui-config';
|
||||
|
||||
function RandomThemeApplier() {
|
||||
const { setTheme } = useTheme();
|
||||
@@ -19,9 +19,12 @@ function RandomThemeApplier() {
|
||||
useEffect(() => {
|
||||
if (!applied) {
|
||||
// Sélectionner un thème aléatoire côté client seulement
|
||||
const randomTheme = THEME_CONFIG.allThemes[Math.floor(Math.random() * THEME_CONFIG.allThemes.length)];
|
||||
const randomTheme =
|
||||
THEME_CONFIG.allThemes[
|
||||
Math.floor(Math.random() * THEME_CONFIG.allThemes.length)
|
||||
];
|
||||
console.log('Applying random theme:', randomTheme);
|
||||
|
||||
|
||||
// Utiliser setTheme du ThemeContext pour forcer le changement
|
||||
setTheme(randomTheme);
|
||||
setApplied(true);
|
||||
@@ -37,20 +40,25 @@ function RandomBackground() {
|
||||
|
||||
useEffect(() => {
|
||||
// Sélectionner un background aléatoire parmi les presets (sauf 'none')
|
||||
const availableBackgrounds = PRESET_BACKGROUNDS.filter(bg => bg.id !== 'none');
|
||||
const randomBackground = availableBackgrounds[Math.floor(Math.random() * availableBackgrounds.length)];
|
||||
const availableBackgrounds = PRESET_BACKGROUNDS.filter(
|
||||
(bg) => bg.id !== 'none'
|
||||
);
|
||||
const randomBackground =
|
||||
availableBackgrounds[
|
||||
Math.floor(Math.random() * availableBackgrounds.length)
|
||||
];
|
||||
setBackground(randomBackground.preview);
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
|
||||
return (
|
||||
<div
|
||||
<div
|
||||
className="absolute inset-0 -z-10"
|
||||
style={{ background: mounted ? background : 'var(--background)' }}
|
||||
>
|
||||
{/* Effet de profondeur */}
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-black/20 via-transparent to-transparent"></div>
|
||||
|
||||
|
||||
{/* Effet de lumière */}
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-transparent via-white/5 to-transparent"></div>
|
||||
</div>
|
||||
@@ -58,47 +66,47 @@ function RandomBackground() {
|
||||
}
|
||||
|
||||
function LoginPageContent() {
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const router = useRouter()
|
||||
const { data: session, status } = useSession()
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const router = useRouter();
|
||||
const { data: session, status } = useSession();
|
||||
|
||||
// Redirection si l'utilisateur est déjà connecté
|
||||
useEffect(() => {
|
||||
if (status === 'authenticated' && session) {
|
||||
router.push('/')
|
||||
router.push('/');
|
||||
}
|
||||
}, [status, session, router])
|
||||
}, [status, session, router]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setIsLoading(true)
|
||||
setError('')
|
||||
e.preventDefault();
|
||||
setIsLoading(true);
|
||||
setError('');
|
||||
|
||||
try {
|
||||
const result = await signIn('credentials', {
|
||||
email,
|
||||
password,
|
||||
redirect: false,
|
||||
})
|
||||
});
|
||||
|
||||
if (result?.error) {
|
||||
setError('Email ou mot de passe incorrect')
|
||||
setError('Email ou mot de passe incorrect');
|
||||
} else {
|
||||
// Vérifier que la session est bien créée
|
||||
const session = await getSession()
|
||||
const session = await getSession();
|
||||
if (session) {
|
||||
router.push('/')
|
||||
router.push('/');
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
setError('Une erreur est survenue')
|
||||
setError('Une erreur est survenue');
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Afficher un loader pendant la vérification de session
|
||||
if (status === 'loading') {
|
||||
@@ -109,12 +117,12 @@ function LoginPageContent() {
|
||||
<div className="text-[var(--foreground)]">Chargement...</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Ne pas afficher le formulaire si l'utilisateur est connecté
|
||||
if (status === 'authenticated') {
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -136,7 +144,10 @@ function LoginPageContent() {
|
||||
<form className="space-y-6" onSubmit={handleSubmit}>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-[var(--foreground)] mb-2">
|
||||
<label
|
||||
htmlFor="email"
|
||||
className="block text-sm font-medium text-[var(--foreground)] mb-2"
|
||||
>
|
||||
Email
|
||||
</label>
|
||||
<Input
|
||||
@@ -150,9 +161,12 @@ function LoginPageContent() {
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm font-medium text-[var(--foreground)] mb-2">
|
||||
<label
|
||||
htmlFor="password"
|
||||
className="block text-sm font-medium text-[var(--foreground)] mb-2"
|
||||
>
|
||||
Mot de passe
|
||||
</label>
|
||||
<Input
|
||||
@@ -187,7 +201,10 @@ function LoginPageContent() {
|
||||
<div className="text-center text-sm text-[var(--muted-foreground)]">
|
||||
<p>
|
||||
Pas encore de compte ?{' '}
|
||||
<Link href="/register" className="text-[var(--primary)] hover:underline font-medium">
|
||||
<Link
|
||||
href="/register"
|
||||
className="text-[var(--primary)] hover:underline font-medium"
|
||||
>
|
||||
Créer un compte
|
||||
</Link>
|
||||
</p>
|
||||
@@ -197,9 +214,9 @@ function LoginPageContent() {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
return <LoginPageContent />
|
||||
return <LoginPageContent />;
|
||||
}
|
||||
|
||||
@@ -10,17 +10,24 @@ export const dynamic = 'force-dynamic';
|
||||
|
||||
export default async function HomePage() {
|
||||
// SSR - Récupération des données côté serveur
|
||||
const [initialTasks, initialTags, initialStats, productivityMetrics, deadlineMetrics, tagMetrics] = await Promise.all([
|
||||
const [
|
||||
initialTasks,
|
||||
initialTags,
|
||||
initialStats,
|
||||
productivityMetrics,
|
||||
deadlineMetrics,
|
||||
tagMetrics,
|
||||
] = await Promise.all([
|
||||
tasksService.getTasks(),
|
||||
tagsService.getTags(),
|
||||
tasksService.getTaskStats(),
|
||||
AnalyticsService.getProductivityMetrics(),
|
||||
DeadlineAnalyticsService.getDeadlineMetrics(),
|
||||
TagAnalyticsService.getTagDistributionMetrics()
|
||||
TagAnalyticsService.getTagDistributionMetrics(),
|
||||
]);
|
||||
|
||||
return (
|
||||
<HomePageClient
|
||||
<HomePageClient
|
||||
initialTasks={initialTasks}
|
||||
initialTags={initialTags}
|
||||
initialStats={initialStats}
|
||||
|
||||
@@ -1,36 +1,47 @@
|
||||
'use client'
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useTransition } from 'react'
|
||||
import { useSession } from 'next-auth/react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { Button } from '@/components/ui/Button'
|
||||
import { Input } from '@/components/ui/Input'
|
||||
import { Header } from '@/components/ui/Header'
|
||||
import { updateProfile, getProfile, applyGravatar } from '@/actions/profile'
|
||||
import { getGravatarUrl, isGravatarUrl } from '@/lib/gravatar'
|
||||
import { Check, User, Mail, Calendar, Shield, Save, X, Loader2, Image, ExternalLink } from 'lucide-react'
|
||||
import { Avatar } from '@/components/ui/Avatar'
|
||||
import { useState, useEffect, useTransition } from 'react';
|
||||
import { useSession } from 'next-auth/react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import { Header } from '@/components/ui/Header';
|
||||
import { updateProfile, getProfile, applyGravatar } from '@/actions/profile';
|
||||
import { getGravatarUrl, isGravatarUrl } from '@/lib/gravatar';
|
||||
import {
|
||||
Check,
|
||||
User,
|
||||
Mail,
|
||||
Calendar,
|
||||
Shield,
|
||||
Save,
|
||||
X,
|
||||
Loader2,
|
||||
Image,
|
||||
ExternalLink,
|
||||
} from 'lucide-react';
|
||||
import { Avatar } from '@/components/ui/Avatar';
|
||||
|
||||
interface UserProfile {
|
||||
id: string
|
||||
email: string
|
||||
name: string | null
|
||||
firstName: string | null
|
||||
lastName: string | null
|
||||
avatar: string | null
|
||||
role: string
|
||||
createdAt: string
|
||||
lastLoginAt: string | null
|
||||
id: string;
|
||||
email: string;
|
||||
name: string | null;
|
||||
firstName: string | null;
|
||||
lastName: string | null;
|
||||
avatar: string | null;
|
||||
role: string;
|
||||
createdAt: string;
|
||||
lastLoginAt: string | null;
|
||||
}
|
||||
|
||||
export default function ProfilePage() {
|
||||
const { data: session, update } = useSession()
|
||||
const router = useRouter()
|
||||
const [isPending, startTransition] = useTransition()
|
||||
const [profile, setProfile] = useState<UserProfile | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
const [success, setSuccess] = useState('')
|
||||
const { data: session, update } = useSession();
|
||||
const router = useRouter();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [profile, setProfile] = useState<UserProfile | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [success, setSuccess] = useState('');
|
||||
|
||||
// Form data
|
||||
const [formData, setFormData] = useState({
|
||||
@@ -38,110 +49,114 @@ export default function ProfilePage() {
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
avatar: '',
|
||||
})
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!session) {
|
||||
router.push('/login')
|
||||
return
|
||||
router.push('/login');
|
||||
return;
|
||||
}
|
||||
|
||||
fetchProfile()
|
||||
}, [session, router])
|
||||
fetchProfile();
|
||||
}, [session, router]);
|
||||
|
||||
const fetchProfile = async () => {
|
||||
try {
|
||||
const result = await getProfile()
|
||||
const result = await getProfile();
|
||||
if (!result.success || !result.user) {
|
||||
throw new Error(result.error || 'Erreur lors du chargement du profil')
|
||||
throw new Error(result.error || 'Erreur lors du chargement du profil');
|
||||
}
|
||||
setProfile(result.user)
|
||||
setProfile(result.user);
|
||||
setFormData({
|
||||
name: result.user.name || '',
|
||||
firstName: result.user.firstName || '',
|
||||
lastName: result.user.lastName || '',
|
||||
avatar: result.user.avatar || '',
|
||||
})
|
||||
});
|
||||
} catch (error) {
|
||||
setError(error instanceof Error ? error.message : 'Erreur inconnue')
|
||||
setError(error instanceof Error ? error.message : 'Erreur inconnue');
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setSuccess('')
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setSuccess('');
|
||||
|
||||
startTransition(async () => {
|
||||
try {
|
||||
const result = await updateProfile(formData)
|
||||
|
||||
const result = await updateProfile(formData);
|
||||
|
||||
if (!result.success || !result.user) {
|
||||
setError(result.error || 'Erreur lors de la mise à jour')
|
||||
return
|
||||
setError(result.error || 'Erreur lors de la mise à jour');
|
||||
return;
|
||||
}
|
||||
|
||||
setProfile(result.user)
|
||||
setSuccess('Profil mis à jour avec succès')
|
||||
|
||||
setProfile(result.user);
|
||||
setSuccess('Profil mis à jour avec succès');
|
||||
|
||||
// Mettre à jour la session NextAuth
|
||||
await update({
|
||||
...session,
|
||||
user: {
|
||||
...session?.user,
|
||||
name: result.user.name || `${result.user.firstName || ''} ${result.user.lastName || ''}`.trim() || result.user.email,
|
||||
name:
|
||||
result.user.name ||
|
||||
`${result.user.firstName || ''} ${result.user.lastName || ''}`.trim() ||
|
||||
result.user.email,
|
||||
firstName: result.user.firstName,
|
||||
lastName: result.user.lastName,
|
||||
avatar: result.user.avatar,
|
||||
}
|
||||
})
|
||||
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
setError(error instanceof Error ? error.message : 'Erreur inconnue')
|
||||
setError(error instanceof Error ? error.message : 'Erreur inconnue');
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const handleUseGravatar = async () => {
|
||||
setError('')
|
||||
setSuccess('')
|
||||
setError('');
|
||||
setSuccess('');
|
||||
|
||||
startTransition(async () => {
|
||||
try {
|
||||
const result = await applyGravatar()
|
||||
|
||||
const result = await applyGravatar();
|
||||
|
||||
if (!result.success || !result.user) {
|
||||
setError(result.error || 'Erreur lors de la mise à jour Gravatar')
|
||||
return
|
||||
setError(result.error || 'Erreur lors de la mise à jour Gravatar');
|
||||
return;
|
||||
}
|
||||
|
||||
setProfile(result.user)
|
||||
setFormData(prev => ({ ...prev, avatar: result.user!.avatar || '' }))
|
||||
setSuccess('Avatar Gravatar appliqué avec succès')
|
||||
|
||||
setProfile(result.user);
|
||||
setFormData((prev) => ({ ...prev, avatar: result.user!.avatar || '' }));
|
||||
setSuccess('Avatar Gravatar appliqué avec succès');
|
||||
|
||||
// Mettre à jour la session NextAuth
|
||||
await update({
|
||||
...session,
|
||||
user: {
|
||||
...session?.user,
|
||||
name: result.user.name || `${result.user.firstName || ''} ${result.user.lastName || ''}`.trim() || result.user.email,
|
||||
name:
|
||||
result.user.name ||
|
||||
`${result.user.firstName || ''} ${result.user.lastName || ''}`.trim() ||
|
||||
result.user.email,
|
||||
firstName: result.user.firstName,
|
||||
lastName: result.user.lastName,
|
||||
avatar: result.user.avatar,
|
||||
}
|
||||
})
|
||||
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
setError(error instanceof Error ? error.message : 'Erreur inconnue')
|
||||
setError(error instanceof Error ? error.message : 'Erreur inconnue');
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const handleChange = (field: string, value: string) => {
|
||||
setFormData(prev => ({ ...prev, [field]: value }))
|
||||
}
|
||||
setFormData((prev) => ({ ...prev, [field]: value }));
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
@@ -155,7 +170,7 @@ export default function ProfilePage() {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!profile) {
|
||||
@@ -170,13 +185,13 @@ export default function ProfilePage() {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[var(--background)]">
|
||||
<Header title="TowerControl" subtitle="Profil utilisateur" />
|
||||
|
||||
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<div className="max-w-4xl mx-auto">
|
||||
{/* Header avec avatar et infos principales */}
|
||||
@@ -184,8 +199,8 @@ export default function ProfilePage() {
|
||||
<div className="flex flex-col md:flex-row items-center md:items-start gap-6">
|
||||
{/* Avatar section */}
|
||||
<div className="flex-shrink-0 relative">
|
||||
<Avatar
|
||||
url={profile.avatar || undefined}
|
||||
<Avatar
|
||||
url={profile.avatar || undefined}
|
||||
email={profile.email}
|
||||
name={profile.name || undefined}
|
||||
size={96}
|
||||
@@ -194,30 +209,43 @@ export default function ProfilePage() {
|
||||
{profile.avatar && (
|
||||
<div className="absolute -bottom-2 -right-2 w-8 h-8 bg-[var(--success)] rounded-full border-4 border-[var(--card)] flex items-center justify-center">
|
||||
{isGravatarUrl(profile.avatar) ? (
|
||||
<ExternalLink className="w-4 h-4 text-white" aria-label="Avatar Gravatar" />
|
||||
<ExternalLink
|
||||
className="w-4 h-4 text-white"
|
||||
aria-label="Avatar Gravatar"
|
||||
/>
|
||||
) : (
|
||||
<Image className="w-4 h-4 text-white" aria-label="Avatar personnalisé" />
|
||||
<Image
|
||||
className="w-4 h-4 text-white"
|
||||
aria-label="Avatar personnalisé"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
{/* User info */}
|
||||
<div className="flex-1 text-center md:text-left">
|
||||
<h1 className="text-3xl font-mono font-bold text-[var(--foreground)] mb-2">
|
||||
{profile.name || `${profile.firstName || ''} ${profile.lastName || ''}`.trim() || profile.email}
|
||||
{profile.name ||
|
||||
`${profile.firstName || ''} ${profile.lastName || ''}`.trim() ||
|
||||
profile.email}
|
||||
</h1>
|
||||
<p className="text-[var(--muted-foreground)] text-lg mb-4">{profile.email}</p>
|
||||
|
||||
<p className="text-[var(--muted-foreground)] text-lg mb-4">
|
||||
{profile.email}
|
||||
</p>
|
||||
|
||||
<div className="flex flex-wrap gap-4 justify-center md:justify-start">
|
||||
<div className="flex items-center gap-2 px-3 py-1 bg-[var(--card)] rounded-full border border-[var(--border)]">
|
||||
<div className="w-2 h-2 bg-[var(--success)] rounded-full"></div>
|
||||
<span className="text-sm font-medium text-[var(--foreground)]">{profile.role}</span>
|
||||
<span className="text-sm font-medium text-[var(--foreground)]">
|
||||
{profile.role}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 px-3 py-1 bg-[var(--card)] rounded-full border border-[var(--border)]">
|
||||
<Calendar className="w-4 h-4 text-[var(--muted-foreground)]" />
|
||||
<span className="text-sm text-[var(--muted-foreground)]">
|
||||
Membre depuis {new Date(profile.createdAt).toLocaleDateString('fr-FR')}
|
||||
Membre depuis{' '}
|
||||
{new Date(profile.createdAt).toLocaleDateString('fr-FR')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -232,21 +260,29 @@ export default function ProfilePage() {
|
||||
<User className="w-5 h-5 text-[var(--primary)]" />
|
||||
Informations générales
|
||||
</h2>
|
||||
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-3 p-3 bg-[var(--input)] rounded-lg border border-[var(--border)]">
|
||||
<Mail className="w-5 h-5 text-[var(--muted-foreground)]" />
|
||||
<div>
|
||||
<div className="text-[var(--foreground)] font-medium">{profile.email}</div>
|
||||
<div className="text-xs text-[var(--muted-foreground)]">Email principal</div>
|
||||
<div className="text-[var(--foreground)] font-medium">
|
||||
{profile.email}
|
||||
</div>
|
||||
<div className="text-xs text-[var(--muted-foreground)]">
|
||||
Email principal
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 p-3 bg-[var(--input)] rounded-lg border border-[var(--border)]">
|
||||
<Shield className="w-5 h-5 text-[var(--muted-foreground)]" />
|
||||
<div>
|
||||
<div className="text-[var(--foreground)] font-medium">{profile.role}</div>
|
||||
<div className="text-xs text-[var(--muted-foreground)]">Rôle utilisateur</div>
|
||||
<div className="text-[var(--foreground)] font-medium">
|
||||
{profile.role}
|
||||
</div>
|
||||
<div className="text-xs text-[var(--muted-foreground)]">
|
||||
Rôle utilisateur
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -257,7 +293,9 @@ export default function ProfilePage() {
|
||||
<div className="text-[var(--foreground)] font-medium">
|
||||
{new Date(profile.lastLoginAt).toLocaleString('fr-FR')}
|
||||
</div>
|
||||
<div className="text-xs text-[var(--muted-foreground)]">Dernière connexion</div>
|
||||
<div className="text-xs text-[var(--muted-foreground)]">
|
||||
Dernière connexion
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -274,19 +312,27 @@ export default function ProfilePage() {
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label htmlFor="firstName" className="block text-sm font-medium text-[var(--foreground)] mb-2">
|
||||
<label
|
||||
htmlFor="firstName"
|
||||
className="block text-sm font-medium text-[var(--foreground)] mb-2"
|
||||
>
|
||||
Prénom
|
||||
</label>
|
||||
<Input
|
||||
id="firstName"
|
||||
value={formData.firstName}
|
||||
onChange={(e) => handleChange('firstName', e.target.value)}
|
||||
onChange={(e) =>
|
||||
handleChange('firstName', e.target.value)
|
||||
}
|
||||
placeholder="Votre prénom"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="lastName" className="block text-sm font-medium text-[var(--foreground)] mb-2">
|
||||
<label
|
||||
htmlFor="lastName"
|
||||
className="block text-sm font-medium text-[var(--foreground)] mb-2"
|
||||
>
|
||||
Nom de famille
|
||||
</label>
|
||||
<Input
|
||||
@@ -299,47 +345,58 @@ export default function ProfilePage() {
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="name" className="block text-sm font-medium text-[var(--foreground)] mb-2">
|
||||
<label
|
||||
htmlFor="name"
|
||||
className="block text-sm font-medium text-[var(--foreground)] mb-2"
|
||||
>
|
||||
Nom d'affichage (optionnel)
|
||||
</label>
|
||||
<Input
|
||||
id="name"
|
||||
value={formData.name}
|
||||
onChange={(e) => handleChange('name', e.target.value)}
|
||||
placeholder="Nom d'affichage personnalisé"
|
||||
placeholder="Nom d'affichage personnalisé"
|
||||
/>
|
||||
<p className="text-xs text-[var(--muted-foreground)] mt-1">
|
||||
Si vide, sera généré automatiquement à partir du prénom et nom
|
||||
Si vide, sera généré automatiquement à partir du prénom et
|
||||
nom
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="avatar" className="block text-sm font-medium text-[var(--foreground)] mb-2">
|
||||
<label
|
||||
htmlFor="avatar"
|
||||
className="block text-sm font-medium text-[var(--foreground)] mb-2"
|
||||
>
|
||||
Avatar
|
||||
</label>
|
||||
|
||||
|
||||
{/* Option Gravatar */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-3 p-3 bg-[var(--input)] rounded-lg border border-[var(--border)]">
|
||||
<div className="flex-shrink-0">
|
||||
{profile.email && (
|
||||
/* eslint-disable-next-line @next/next/no-img-element */
|
||||
<img
|
||||
src={getGravatarUrl(profile.email, { size: 40 })}
|
||||
alt="Aperçu Gravatar"
|
||||
<img
|
||||
src={getGravatarUrl(profile.email, { size: 40 })}
|
||||
alt="Aperçu Gravatar"
|
||||
className="w-10 h-10 rounded-full object-cover"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<div className="text-sm font-medium text-[var(--foreground)]">Gravatar</div>
|
||||
<div className="text-sm font-medium text-[var(--foreground)]">
|
||||
Gravatar
|
||||
</div>
|
||||
<div className="text-xs text-[var(--muted-foreground)]">
|
||||
Utilise l'avatar lié à votre email
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant={isGravatarUrl(formData.avatar) ? "primary" : "ghost"}
|
||||
variant={
|
||||
isGravatarUrl(formData.avatar) ? 'primary' : 'ghost'
|
||||
}
|
||||
size="sm"
|
||||
onClick={handleUseGravatar}
|
||||
disabled={isPending}
|
||||
@@ -352,29 +409,38 @@ export default function ProfilePage() {
|
||||
{/* Option URL custom */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Image className="w-4 h-4 text-[var(--muted-foreground)]" aria-label="URL personnalisée" />
|
||||
<span className="text-sm font-medium text-[var(--foreground)]">URL personnalisée</span>
|
||||
<Image
|
||||
className="w-4 h-4 text-[var(--muted-foreground)]"
|
||||
aria-label="URL personnalisée"
|
||||
/>
|
||||
<span className="text-sm font-medium text-[var(--foreground)]">
|
||||
URL personnalisée
|
||||
</span>
|
||||
</div>
|
||||
<Input
|
||||
id="avatar"
|
||||
value={formData.avatar}
|
||||
onChange={(e) => handleChange('avatar', e.target.value)}
|
||||
placeholder="https://example.com/avatar.jpg"
|
||||
className={isGravatarUrl(formData.avatar) ? 'opacity-50' : ''}
|
||||
className={
|
||||
isGravatarUrl(formData.avatar) ? 'opacity-50' : ''
|
||||
}
|
||||
/>
|
||||
<p className="text-xs text-[var(--muted-foreground)]">
|
||||
Entrez une URL d'image sécurisée (HTTPS uniquement)
|
||||
</p>
|
||||
{formData.avatar && !isGravatarUrl(formData.avatar) && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-[var(--muted-foreground)]">Aperçu:</span>
|
||||
<span className="text-xs text-[var(--muted-foreground)]">
|
||||
Aperçu:
|
||||
</span>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={formData.avatar}
|
||||
alt="Aperçu avatar personnalisé"
|
||||
<img
|
||||
src={formData.avatar}
|
||||
alt="Aperçu avatar personnalisé"
|
||||
className="w-8 h-8 rounded-full object-cover border border-[var(--border)]"
|
||||
onError={(e) => {
|
||||
e.currentTarget.style.display = 'none'
|
||||
e.currentTarget.style.display = 'none';
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
@@ -382,7 +448,7 @@ export default function ProfilePage() {
|
||||
</div>
|
||||
|
||||
{/* Reset button */}
|
||||
{(formData.avatar && !isGravatarUrl(formData.avatar)) && (
|
||||
{formData.avatar && !isGravatarUrl(formData.avatar) && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
@@ -400,14 +466,18 @@ export default function ProfilePage() {
|
||||
{error && (
|
||||
<div className="flex items-center gap-2 p-3 bg-[var(--destructive)]/10 border border-[var(--destructive)]/30 rounded-lg">
|
||||
<X className="w-5 h-5 text-[var(--destructive)]" />
|
||||
<span className="text-[var(--destructive)] text-sm">{error}</span>
|
||||
<span className="text-[var(--destructive)] text-sm">
|
||||
{error}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{success && (
|
||||
<div className="flex items-center gap-2 p-3 bg-[var(--success)]/10 border border-[var(--success)]/30 rounded-lg">
|
||||
<Check className="w-5 h-5 text-[var(--success)]" />
|
||||
<span className="text-[var(--success)] text-sm">{success}</span>
|
||||
<span className="text-[var(--success)] text-sm">
|
||||
{success}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -436,5 +506,5 @@ export default function ProfilePage() {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,49 +1,49 @@
|
||||
'use client'
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useSession } from 'next-auth/react'
|
||||
import { Button } from '@/components/ui/Button'
|
||||
import { Input } from '@/components/ui/Input'
|
||||
import Link from 'next/link'
|
||||
import { TowerLogo } from '@/components/TowerLogo'
|
||||
import { TowerBackground } from '@/components/TowerBackground'
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useSession } from 'next-auth/react';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import Link from 'next/link';
|
||||
import { TowerLogo } from '@/components/TowerLogo';
|
||||
import { TowerBackground } from '@/components/TowerBackground';
|
||||
|
||||
export default function RegisterPage() {
|
||||
const [email, setEmail] = useState('')
|
||||
const [name, setName] = useState('')
|
||||
const [firstName, setFirstName] = useState('')
|
||||
const [lastName, setLastName] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [confirmPassword, setConfirmPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const router = useRouter()
|
||||
const { data: session, status } = useSession()
|
||||
const [email, setEmail] = useState('');
|
||||
const [name, setName] = useState('');
|
||||
const [firstName, setFirstName] = useState('');
|
||||
const [lastName, setLastName] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const router = useRouter();
|
||||
const { data: session, status } = useSession();
|
||||
|
||||
// Redirection si l'utilisateur est déjà connecté
|
||||
useEffect(() => {
|
||||
if (status === 'authenticated' && session) {
|
||||
router.push('/')
|
||||
router.push('/');
|
||||
}
|
||||
}, [status, session, router])
|
||||
}, [status, session, router]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setIsLoading(true)
|
||||
setError('')
|
||||
e.preventDefault();
|
||||
setIsLoading(true);
|
||||
setError('');
|
||||
|
||||
// Validation côté client
|
||||
if (password !== confirmPassword) {
|
||||
setError('Les mots de passe ne correspondent pas')
|
||||
setIsLoading(false)
|
||||
return
|
||||
setError('Les mots de passe ne correspondent pas');
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (password.length < 6) {
|
||||
setError('Le mot de passe doit contenir au moins 6 caractères')
|
||||
setIsLoading(false)
|
||||
return
|
||||
setError('Le mot de passe doit contenir au moins 6 caractères');
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -59,22 +59,24 @@ export default function RegisterPage() {
|
||||
lastName,
|
||||
password,
|
||||
}),
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json()
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || 'Une erreur est survenue')
|
||||
throw new Error(data.error || 'Une erreur est survenue');
|
||||
}
|
||||
|
||||
// Rediriger vers la page de login avec un message de succès
|
||||
router.push('/login?message=Compte créé avec succès')
|
||||
router.push('/login?message=Compte créé avec succès');
|
||||
} catch (error) {
|
||||
setError(error instanceof Error ? error.message : 'Une erreur est survenue')
|
||||
setError(
|
||||
error instanceof Error ? error.message : 'Une erreur est survenue'
|
||||
);
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Afficher un loader pendant la vérification de session
|
||||
if (status === 'loading') {
|
||||
@@ -85,12 +87,12 @@ export default function RegisterPage() {
|
||||
<div className="text-[var(--foreground)]">Chargement...</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Ne pas afficher le formulaire si l'utilisateur est connecté
|
||||
if (status === 'authenticated') {
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -111,7 +113,10 @@ export default function RegisterPage() {
|
||||
<form className="space-y-6" onSubmit={handleSubmit}>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-[var(--foreground)] mb-2">
|
||||
<label
|
||||
htmlFor="email"
|
||||
className="block text-sm font-medium text-[var(--foreground)] mb-2"
|
||||
>
|
||||
Email
|
||||
</label>
|
||||
<Input
|
||||
@@ -125,10 +130,13 @@ export default function RegisterPage() {
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label htmlFor="firstName" className="block text-sm font-medium text-[var(--foreground)] mb-2">
|
||||
<label
|
||||
htmlFor="firstName"
|
||||
className="block text-sm font-medium text-[var(--foreground)] mb-2"
|
||||
>
|
||||
Prénom
|
||||
</label>
|
||||
<Input
|
||||
@@ -143,7 +151,10 @@ export default function RegisterPage() {
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="lastName" className="block text-sm font-medium text-[var(--foreground)] mb-2">
|
||||
<label
|
||||
htmlFor="lastName"
|
||||
className="block text-sm font-medium text-[var(--foreground)] mb-2"
|
||||
>
|
||||
Nom
|
||||
</label>
|
||||
<Input
|
||||
@@ -159,7 +170,10 @@ export default function RegisterPage() {
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="name" className="block text-sm font-medium text-[var(--foreground)] mb-2">
|
||||
<label
|
||||
htmlFor="name"
|
||||
className="block text-sm font-medium text-[var(--foreground)] mb-2"
|
||||
>
|
||||
Nom d'affichage (optionnel)
|
||||
</label>
|
||||
<Input
|
||||
@@ -168,13 +182,16 @@ export default function RegisterPage() {
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="Nom d'affichage personnalisé"
|
||||
placeholder="Nom d'affichage personnalisé"
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm font-medium text-[var(--foreground)] mb-2">
|
||||
<label
|
||||
htmlFor="password"
|
||||
className="block text-sm font-medium text-[var(--foreground)] mb-2"
|
||||
>
|
||||
Mot de passe
|
||||
</label>
|
||||
<Input
|
||||
@@ -190,7 +207,10 @@ export default function RegisterPage() {
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="confirmPassword" className="block text-sm font-medium text-[var(--foreground)] mb-2">
|
||||
<label
|
||||
htmlFor="confirmPassword"
|
||||
className="block text-sm font-medium text-[var(--foreground)] mb-2"
|
||||
>
|
||||
Confirmer le mot de passe
|
||||
</label>
|
||||
<Input
|
||||
@@ -225,7 +245,10 @@ export default function RegisterPage() {
|
||||
<div className="text-center text-sm text-[var(--muted-foreground)]">
|
||||
<p>
|
||||
Déjà un compte ?{' '}
|
||||
<Link href="/login" className="text-[var(--primary)] hover:underline font-medium">
|
||||
<Link
|
||||
href="/login"
|
||||
className="text-[var(--primary)] hover:underline font-medium"
|
||||
>
|
||||
Se connecter
|
||||
</Link>
|
||||
</p>
|
||||
@@ -235,5 +258,5 @@ export default function RegisterPage() {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,31 +11,31 @@ export default async function AdvancedSettingsPage() {
|
||||
// Fetch all data server-side
|
||||
const [taskStats, tags] = await Promise.all([
|
||||
tasksService.getTaskStats(),
|
||||
tagsService.getTags()
|
||||
tagsService.getTags(),
|
||||
]);
|
||||
|
||||
// Compose backup data like the API does
|
||||
const backups = await backupService.listBackups();
|
||||
const schedulerStatus = backupScheduler.getStatus();
|
||||
const config = backupService.getConfig();
|
||||
|
||||
|
||||
const backupData = {
|
||||
backups,
|
||||
scheduler: {
|
||||
...schedulerStatus,
|
||||
nextBackup: schedulerStatus.nextBackup?.toISOString() || null
|
||||
nextBackup: schedulerStatus.nextBackup?.toISOString() || null,
|
||||
},
|
||||
config
|
||||
config,
|
||||
};
|
||||
|
||||
const dbStats = {
|
||||
taskCount: taskStats.total,
|
||||
tagCount: tags.length,
|
||||
completionRate: taskStats.completionRate
|
||||
completionRate: taskStats.completionRate,
|
||||
};
|
||||
|
||||
return (
|
||||
<AdvancedSettingsPageClient
|
||||
<AdvancedSettingsPageClient
|
||||
initialDbStats={dbStats}
|
||||
initialBackupData={backupData}
|
||||
/>
|
||||
|
||||
@@ -16,13 +16,13 @@ export default async function BackupSettingsPage() {
|
||||
backups,
|
||||
scheduler: {
|
||||
...schedulerStatus,
|
||||
nextBackup: schedulerStatus.nextBackup ? schedulerStatus.nextBackup.toISOString() : null,
|
||||
nextBackup: schedulerStatus.nextBackup
|
||||
? schedulerStatus.nextBackup.toISOString()
|
||||
: null,
|
||||
},
|
||||
config,
|
||||
backupStats,
|
||||
};
|
||||
|
||||
return (
|
||||
<BackupSettingsPageClient initialData={initialData} />
|
||||
);
|
||||
return <BackupSettingsPageClient initialData={initialData} />;
|
||||
}
|
||||
|
||||
@@ -16,11 +16,11 @@ export default async function IntegrationsSettingsPage() {
|
||||
// Preferences are now available via context
|
||||
const [jiraConfig, tfsConfig] = await Promise.all([
|
||||
userPreferencesService.getJiraConfig(session.user.id),
|
||||
userPreferencesService.getTfsConfig(session.user.id)
|
||||
userPreferencesService.getTfsConfig(session.user.id),
|
||||
]);
|
||||
|
||||
return (
|
||||
<IntegrationsSettingsPageClient
|
||||
<IntegrationsSettingsPageClient
|
||||
initialJiraConfig={jiraConfig}
|
||||
initialTfsConfig={tfsConfig}
|
||||
/>
|
||||
|
||||
@@ -7,10 +7,6 @@ export const dynamic = 'force-dynamic';
|
||||
export default async function SettingsPage() {
|
||||
// Fetch data in parallel for better performance
|
||||
const systemInfo = await SystemInfoService.getSystemInfo();
|
||||
|
||||
return (
|
||||
<SettingsIndexPageClient
|
||||
initialSystemInfo={systemInfo}
|
||||
/>
|
||||
);
|
||||
|
||||
return <SettingsIndexPageClient initialSystemInfo={systemInfo} />;
|
||||
}
|
||||
|
||||
@@ -11,16 +11,13 @@ interface WeeklyManagerPageClientProps {
|
||||
initialTags: (Tag & { usage: number })[];
|
||||
}
|
||||
|
||||
export function WeeklyManagerPageClient({
|
||||
initialSummary,
|
||||
initialTasks,
|
||||
initialTags
|
||||
export function WeeklyManagerPageClient({
|
||||
initialSummary,
|
||||
initialTasks,
|
||||
initialTags,
|
||||
}: WeeklyManagerPageClientProps) {
|
||||
return (
|
||||
<TasksProvider
|
||||
initialTasks={initialTasks}
|
||||
initialTags={initialTags}
|
||||
>
|
||||
<TasksProvider initialTasks={initialTasks} initialTags={initialTags}>
|
||||
<ManagerWeeklySummary initialSummary={initialSummary} />
|
||||
</TasksProvider>
|
||||
);
|
||||
|
||||
@@ -12,15 +12,15 @@ export default async function WeeklyManagerPage() {
|
||||
const [summary, initialTasks, initialTags] = await Promise.all([
|
||||
ManagerSummaryService.getManagerSummary(),
|
||||
tasksService.getTasks(),
|
||||
tagsService.getTags()
|
||||
tagsService.getTags(),
|
||||
]);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[var(--background)]">
|
||||
<Header />
|
||||
|
||||
|
||||
<main className="container mx-auto px-6 py-8">
|
||||
<WeeklyManagerPageClient
|
||||
<WeeklyManagerPageClient
|
||||
initialSummary={summary}
|
||||
initialTasks={initialTasks}
|
||||
initialTags={initialTags}
|
||||
|
||||
@@ -21,7 +21,9 @@ export class BackupClient {
|
||||
* Liste toutes les sauvegardes disponibles et l'état du scheduler
|
||||
*/
|
||||
async listBackups(): Promise<BackupListResponse> {
|
||||
const response = await httpClient.get<{ data: BackupListResponse }>(this.baseUrl);
|
||||
const response = await httpClient.get<{ data: BackupListResponse }>(
|
||||
this.baseUrl
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
@@ -29,15 +31,19 @@ export class BackupClient {
|
||||
* Crée une nouvelle sauvegarde manuelle
|
||||
*/
|
||||
async createBackup(force: boolean = false): Promise<BackupInfo | null> {
|
||||
const response = await httpClient.post<{ data?: BackupInfo; skipped?: boolean; message?: string }>(this.baseUrl, {
|
||||
const response = await httpClient.post<{
|
||||
data?: BackupInfo;
|
||||
skipped?: boolean;
|
||||
message?: string;
|
||||
}>(this.baseUrl, {
|
||||
action: 'create',
|
||||
force
|
||||
force,
|
||||
});
|
||||
|
||||
|
||||
if (response.skipped) {
|
||||
return null; // Backup was skipped
|
||||
}
|
||||
|
||||
|
||||
return response.data!;
|
||||
}
|
||||
|
||||
@@ -46,7 +52,7 @@ export class BackupClient {
|
||||
*/
|
||||
async verifyDatabase(): Promise<void> {
|
||||
await httpClient.post(this.baseUrl, {
|
||||
action: 'verify'
|
||||
action: 'verify',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -54,10 +60,13 @@ export class BackupClient {
|
||||
* Met à jour la configuration des sauvegardes
|
||||
*/
|
||||
async updateConfig(config: Partial<BackupConfig>): Promise<BackupConfig> {
|
||||
const response = await httpClient.post<{ data: BackupConfig }>(this.baseUrl, {
|
||||
action: 'config',
|
||||
config
|
||||
});
|
||||
const response = await httpClient.post<{ data: BackupConfig }>(
|
||||
this.baseUrl,
|
||||
{
|
||||
action: 'config',
|
||||
config,
|
||||
}
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
@@ -72,16 +81,18 @@ export class BackupClient {
|
||||
maxBackups: number;
|
||||
backupPath: string;
|
||||
}> {
|
||||
const response = await httpClient.post<{ data: {
|
||||
isRunning: boolean;
|
||||
isEnabled: boolean;
|
||||
interval: string;
|
||||
nextBackup: string | null;
|
||||
maxBackups: number;
|
||||
backupPath: string;
|
||||
} }>(this.baseUrl, {
|
||||
const response = await httpClient.post<{
|
||||
data: {
|
||||
isRunning: boolean;
|
||||
isEnabled: boolean;
|
||||
interval: string;
|
||||
nextBackup: string | null;
|
||||
maxBackups: number;
|
||||
backupPath: string;
|
||||
};
|
||||
}>(this.baseUrl, {
|
||||
action: 'scheduler',
|
||||
enabled
|
||||
enabled,
|
||||
});
|
||||
return response.data;
|
||||
}
|
||||
@@ -98,7 +109,7 @@ export class BackupClient {
|
||||
*/
|
||||
async restoreBackup(filename: string): Promise<void> {
|
||||
await httpClient.post(`${this.baseUrl}/${filename}`, {
|
||||
action: 'restore'
|
||||
action: 'restore',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -106,25 +117,31 @@ export class BackupClient {
|
||||
* Récupère les logs de backup
|
||||
*/
|
||||
async getBackupLogs(maxLines: number = 100): Promise<string[]> {
|
||||
const response = await httpClient.get<{ data: { logs: string[] } }>(`${this.baseUrl}?action=logs&maxLines=${maxLines}`);
|
||||
const response = await httpClient.get<{ data: { logs: string[] } }>(
|
||||
`${this.baseUrl}?action=logs&maxLines=${maxLines}`
|
||||
);
|
||||
return response.data.logs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère les statistiques de sauvegarde par jour
|
||||
*/
|
||||
async getBackupStats(days: number = 30): Promise<Array<{
|
||||
date: string;
|
||||
manual: number;
|
||||
automatic: number;
|
||||
total: number;
|
||||
}>> {
|
||||
const response = await httpClient.get<{ data: Array<{
|
||||
async getBackupStats(days: number = 30): Promise<
|
||||
Array<{
|
||||
date: string;
|
||||
manual: number;
|
||||
automatic: number;
|
||||
total: number;
|
||||
}> }>(`${this.baseUrl}?action=stats&days=${days}`);
|
||||
}>
|
||||
> {
|
||||
const response = await httpClient.get<{
|
||||
data: Array<{
|
||||
date: string;
|
||||
manual: number;
|
||||
automatic: number;
|
||||
total: number;
|
||||
}>;
|
||||
}>(`${this.baseUrl}?action=stats&days=${days}`);
|
||||
return response.data;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ export class HttpClient {
|
||||
options: RequestInit = {}
|
||||
): Promise<T> {
|
||||
const url = `${this.baseUrl}${endpoint}`;
|
||||
|
||||
|
||||
const config: RequestInit = {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -24,10 +24,12 @@ export class HttpClient {
|
||||
|
||||
try {
|
||||
const response = await fetch(url, config);
|
||||
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.error || `HTTP ${response.status}: ${response.statusText}`);
|
||||
throw new Error(
|
||||
errorData.error || `HTTP ${response.status}: ${response.statusText}`
|
||||
);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
@@ -38,10 +40,10 @@ export class HttpClient {
|
||||
}
|
||||
|
||||
async get<T>(endpoint: string, params?: Record<string, string>): Promise<T> {
|
||||
const url = params
|
||||
const url = params
|
||||
? `${endpoint}?${new URLSearchParams(params)}`
|
||||
: endpoint;
|
||||
|
||||
|
||||
return this.request<T>(url, { method: 'GET' });
|
||||
}
|
||||
|
||||
@@ -66,11 +68,14 @@ export class HttpClient {
|
||||
});
|
||||
}
|
||||
|
||||
async delete<T>(endpoint: string, params?: Record<string, string>): Promise<T> {
|
||||
const url = params
|
||||
async delete<T>(
|
||||
endpoint: string,
|
||||
params?: Record<string, string>
|
||||
): Promise<T> {
|
||||
const url = params
|
||||
? `${endpoint}?${new URLSearchParams(params)}`
|
||||
: endpoint;
|
||||
|
||||
|
||||
return this.request<T>(url, { method: 'DELETE' });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { httpClient } from './base/http-client';
|
||||
import { DailyCheckbox, DailyView, Task } from '@/lib/types';
|
||||
import { formatDateForAPI, parseDate, getToday, addDays, subtractDays } from '@/lib/date-utils';
|
||||
import {
|
||||
formatDateForAPI,
|
||||
parseDate,
|
||||
getToday,
|
||||
addDays,
|
||||
subtractDays,
|
||||
} from '@/lib/date-utils';
|
||||
|
||||
// Types pour les réponses API (avec dates en string)
|
||||
interface ApiCheckbox {
|
||||
@@ -67,29 +73,35 @@ export class DailyClient {
|
||||
/**
|
||||
* Récupère l'historique des checkboxes
|
||||
*/
|
||||
async getCheckboxHistory(filters?: DailyHistoryFilters): Promise<{ date: Date; checkboxes: DailyCheckbox[] }[]> {
|
||||
async getCheckboxHistory(
|
||||
filters?: DailyHistoryFilters
|
||||
): Promise<{ date: Date; checkboxes: DailyCheckbox[] }[]> {
|
||||
const params = new URLSearchParams({ action: 'history' });
|
||||
|
||||
|
||||
if (filters?.limit) params.append('limit', filters.limit.toString());
|
||||
|
||||
|
||||
const result = await httpClient.get<ApiHistoryItem[]>(`/daily?${params}`);
|
||||
return result.map(item => ({
|
||||
return result.map((item) => ({
|
||||
date: parseDate(item.date),
|
||||
checkboxes: item.checkboxes.map((cb: ApiCheckbox) => this.transformCheckboxDates(cb))
|
||||
checkboxes: item.checkboxes.map((cb: ApiCheckbox) =>
|
||||
this.transformCheckboxDates(cb)
|
||||
),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Recherche dans les checkboxes
|
||||
*/
|
||||
async searchCheckboxes(filters: DailySearchFilters): Promise<DailyCheckbox[]> {
|
||||
async searchCheckboxes(
|
||||
filters: DailySearchFilters
|
||||
): Promise<DailyCheckbox[]> {
|
||||
const params = new URLSearchParams({
|
||||
action: 'search',
|
||||
q: filters.query
|
||||
q: filters.query,
|
||||
});
|
||||
|
||||
|
||||
if (filters.limit) params.append('limit', filters.limit.toString());
|
||||
|
||||
|
||||
const result = await httpClient.get<ApiCheckbox[]>(`/daily?${params}`);
|
||||
return result.map((cb: ApiCheckbox) => this.transformCheckboxDates(cb));
|
||||
}
|
||||
@@ -110,7 +122,7 @@ export class DailyClient {
|
||||
date: parseDate(checkbox.date),
|
||||
createdAt: parseDate(checkbox.createdAt),
|
||||
updatedAt: parseDate(checkbox.updatedAt),
|
||||
isArchived: checkbox.text.includes('[ARCHIVÉ]')
|
||||
isArchived: checkbox.text.includes('[ARCHIVÉ]'),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -120,17 +132,23 @@ export class DailyClient {
|
||||
private transformDailyViewDates(view: ApiDailyView): DailyView {
|
||||
return {
|
||||
date: parseDate(view.date),
|
||||
yesterday: view.yesterday.map((cb: ApiCheckbox) => this.transformCheckboxDates(cb)),
|
||||
today: view.today.map((cb: ApiCheckbox) => this.transformCheckboxDates(cb))
|
||||
yesterday: view.yesterday.map((cb: ApiCheckbox) =>
|
||||
this.transformCheckboxDates(cb)
|
||||
),
|
||||
today: view.today.map((cb: ApiCheckbox) =>
|
||||
this.transformCheckboxDates(cb)
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère la vue daily d'une date relative (hier, aujourd'hui, demain)
|
||||
*/
|
||||
async getDailyViewByRelativeDate(relative: 'yesterday' | 'today' | 'tomorrow'): Promise<DailyView> {
|
||||
async getDailyViewByRelativeDate(
|
||||
relative: 'yesterday' | 'today' | 'tomorrow'
|
||||
): Promise<DailyView> {
|
||||
let date: Date;
|
||||
|
||||
|
||||
switch (relative) {
|
||||
case 'yesterday':
|
||||
date = subtractDays(getToday(), 1);
|
||||
@@ -143,7 +161,7 @@ export class DailyClient {
|
||||
date = getToday();
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
return this.getDailyView(date);
|
||||
}
|
||||
|
||||
@@ -166,12 +184,15 @@ export class DailyClient {
|
||||
}): Promise<DailyCheckbox[]> {
|
||||
const params = new URLSearchParams();
|
||||
if (options?.maxDays) params.append('maxDays', options.maxDays.toString());
|
||||
if (options?.excludeToday !== undefined) params.append('excludeToday', options.excludeToday.toString());
|
||||
if (options?.excludeToday !== undefined)
|
||||
params.append('excludeToday', options.excludeToday.toString());
|
||||
if (options?.type) params.append('type', options.type);
|
||||
if (options?.limit) params.append('limit', options.limit.toString());
|
||||
|
||||
|
||||
const queryString = params.toString();
|
||||
const result = await httpClient.get<ApiCheckbox[]>(`/daily/pending${queryString ? `?${queryString}` : ''}`);
|
||||
const result = await httpClient.get<ApiCheckbox[]>(
|
||||
`/daily/pending${queryString ? `?${queryString}` : ''}`
|
||||
);
|
||||
return result.map((cb: ApiCheckbox) => this.transformCheckboxDates(cb));
|
||||
}
|
||||
|
||||
@@ -179,10 +200,12 @@ export class DailyClient {
|
||||
* Archive une checkbox
|
||||
*/
|
||||
async archiveCheckbox(checkboxId: string): Promise<DailyCheckbox> {
|
||||
const result = await httpClient.patch<ApiCheckbox>(`/daily/checkboxes/${checkboxId}/archive`);
|
||||
const result = await httpClient.patch<ApiCheckbox>(
|
||||
`/daily/checkboxes/${checkboxId}/archive`
|
||||
);
|
||||
return this.transformCheckboxDates(result);
|
||||
}
|
||||
}
|
||||
|
||||
// Instance singleton du client
|
||||
export const dailyClient = new DailyClient();
|
||||
export const dailyClient = new DailyClient();
|
||||
|
||||
@@ -46,7 +46,7 @@ export class JiraClient extends HttpClient {
|
||||
async toggleScheduler(enabled: boolean): Promise<JiraSchedulerStatus> {
|
||||
const response = await this.post<{ data: JiraSchedulerStatus }>('/sync', {
|
||||
action: 'scheduler',
|
||||
enabled
|
||||
enabled,
|
||||
});
|
||||
return response.data;
|
||||
}
|
||||
@@ -54,11 +54,14 @@ export class JiraClient extends HttpClient {
|
||||
/**
|
||||
* Met à jour la configuration du scheduler
|
||||
*/
|
||||
async updateSchedulerConfig(jiraAutoSync: boolean, jiraSyncInterval: 'hourly' | 'daily' | 'weekly'): Promise<JiraSchedulerStatus> {
|
||||
async updateSchedulerConfig(
|
||||
jiraAutoSync: boolean,
|
||||
jiraSyncInterval: 'hourly' | 'daily' | 'weekly'
|
||||
): Promise<JiraSchedulerStatus> {
|
||||
const response = await this.post<{ data: JiraSchedulerStatus }>('/sync', {
|
||||
action: 'config',
|
||||
jiraAutoSync,
|
||||
jiraSyncInterval
|
||||
jiraSyncInterval,
|
||||
});
|
||||
return response.data;
|
||||
}
|
||||
|
||||
@@ -33,7 +33,9 @@ class JiraConfigClient {
|
||||
/**
|
||||
* Sauvegarde la configuration Jira
|
||||
*/
|
||||
async saveJiraConfig(config: SaveJiraConfigRequest): Promise<SaveJiraConfigResponse> {
|
||||
async saveJiraConfig(
|
||||
config: SaveJiraConfigRequest
|
||||
): Promise<SaveJiraConfigResponse> {
|
||||
return httpClient.put<SaveJiraConfigResponse>(this.basePath, config);
|
||||
}
|
||||
|
||||
|
||||
@@ -43,27 +43,33 @@ export class TagsClient extends HttpClient {
|
||||
*/
|
||||
async getTags(filters?: TagFilters): Promise<TagsResponse> {
|
||||
const params: Record<string, string> = {};
|
||||
|
||||
|
||||
if (filters?.q) {
|
||||
params.q = filters.q;
|
||||
}
|
||||
|
||||
|
||||
if (filters?.popular) {
|
||||
params.popular = 'true';
|
||||
}
|
||||
|
||||
|
||||
if (filters?.limit) {
|
||||
params.limit = filters.limit.toString();
|
||||
}
|
||||
|
||||
return this.get<TagsResponse>('', Object.keys(params).length > 0 ? params : undefined);
|
||||
return this.get<TagsResponse>(
|
||||
'',
|
||||
Object.keys(params).length > 0 ? params : undefined
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère les tags populaires (les plus utilisés)
|
||||
*/
|
||||
async getPopularTags(limit: number = 10): Promise<PopularTagsResponse> {
|
||||
return this.get<PopularTagsResponse>('', { popular: 'true', limit: limit.toString() });
|
||||
return this.get<PopularTagsResponse>('', {
|
||||
popular: 'true',
|
||||
limit: limit.toString(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -121,4 +127,4 @@ export class TagsClient extends HttpClient {
|
||||
}
|
||||
|
||||
// Instance singleton
|
||||
export const tagsClient = new TagsClient();
|
||||
export const tagsClient = new TagsClient();
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { httpClient } from './base/http-client';
|
||||
import { Task, TaskStatus, TaskPriority, TaskStats, DailyCheckbox } from '@/lib/types';
|
||||
import {
|
||||
Task,
|
||||
TaskStatus,
|
||||
TaskPriority,
|
||||
TaskStats,
|
||||
DailyCheckbox,
|
||||
} from '@/lib/types';
|
||||
|
||||
export interface TaskFilters {
|
||||
status?: TaskStatus[];
|
||||
@@ -39,13 +45,12 @@ export interface UpdateTaskData {
|
||||
* Client pour la gestion des tâches
|
||||
*/
|
||||
export class TasksClient {
|
||||
|
||||
/**
|
||||
* Récupère toutes les tâches avec filtres
|
||||
*/
|
||||
async getTasks(filters?: TaskFilters): Promise<TasksResponse> {
|
||||
const params: Record<string, string> = {};
|
||||
|
||||
|
||||
if (filters?.status) {
|
||||
params.status = filters.status.join(',');
|
||||
}
|
||||
@@ -69,7 +74,9 @@ export class TasksClient {
|
||||
* Récupère les daily checkboxes liées à une tâche
|
||||
*/
|
||||
async getTaskCheckboxes(taskId: string): Promise<DailyCheckbox[]> {
|
||||
const response = await httpClient.get<{ data: DailyCheckbox[] }>(`/tasks/${taskId}/checkboxes`);
|
||||
const response = await httpClient.get<{ data: DailyCheckbox[] }>(
|
||||
`/tasks/${taskId}/checkboxes`
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,32 +1,29 @@
|
||||
'use client'
|
||||
'use client';
|
||||
|
||||
import { useSession, signOut } from 'next-auth/react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { Button } from '@/components/ui/Button'
|
||||
import { Emoji } from '@/components/ui/Emoji'
|
||||
import { Avatar } from '@/components/ui/Avatar'
|
||||
import { useSession, signOut } from 'next-auth/react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Emoji } from '@/components/ui/Emoji';
|
||||
import { Avatar } from '@/components/ui/Avatar';
|
||||
|
||||
export function AuthButton() {
|
||||
const { data: session, status } = useSession()
|
||||
const router = useRouter()
|
||||
const { data: session, status } = useSession();
|
||||
const router = useRouter();
|
||||
|
||||
if (status === 'loading') {
|
||||
return (
|
||||
<div className="text-[var(--muted-foreground)] text-sm">
|
||||
Chargement...
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!session) {
|
||||
return (
|
||||
<Button
|
||||
onClick={() => router.push('/login')}
|
||||
size="sm"
|
||||
>
|
||||
<Button onClick={() => router.push('/login')} size="sm">
|
||||
Se connecter
|
||||
</Button>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -38,8 +35,8 @@ export function AuthButton() {
|
||||
className="p-1 h-auto"
|
||||
title={`Profil - ${session.user?.email}`}
|
||||
>
|
||||
<Avatar
|
||||
url={session.user?.avatar}
|
||||
<Avatar
|
||||
url={session.user?.avatar}
|
||||
email={session.user?.email}
|
||||
name={session.user?.name}
|
||||
size={40}
|
||||
@@ -56,5 +53,5 @@ export function AuthButton() {
|
||||
<Emoji emoji="🚪" />
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client'
|
||||
'use client';
|
||||
|
||||
import { SessionProvider } from "next-auth/react"
|
||||
import { SessionProvider } from 'next-auth/react';
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
return <SessionProvider>{children}</SessionProvider>
|
||||
return <SessionProvider>{children}</SessionProvider>;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ export function GlobalKeyboardShortcuts() {
|
||||
const { cycleBackground } = useBackground();
|
||||
|
||||
useGlobalKeyboardShortcuts({
|
||||
onCycleBackground: cycleBackground
|
||||
onCycleBackground: cycleBackground,
|
||||
});
|
||||
|
||||
return null;
|
||||
|
||||
@@ -25,8 +25,11 @@ interface HomePageClientProps {
|
||||
tagMetrics: TagDistributionMetrics;
|
||||
}
|
||||
|
||||
|
||||
function HomePageContent({ productivityMetrics, deadlineMetrics, tagMetrics }: {
|
||||
function HomePageContent({
|
||||
productivityMetrics,
|
||||
deadlineMetrics,
|
||||
tagMetrics,
|
||||
}: {
|
||||
productivityMetrics: ProductivityMetrics;
|
||||
deadlineMetrics: DeadlineMetrics;
|
||||
tagMetrics: TagDistributionMetrics;
|
||||
@@ -44,31 +47,33 @@ function HomePageContent({ productivityMetrics, deadlineMetrics, tagMetrics }: {
|
||||
useGlobalKeyboardShortcuts({
|
||||
onOpenSearch: () => {
|
||||
// Focus sur le champ de recherche s'il existe, sinon naviguer vers Kanban
|
||||
const searchInput = document.querySelector('input[placeholder*="Rechercher"]') as HTMLInputElement;
|
||||
const searchInput = document.querySelector(
|
||||
'input[placeholder*="Rechercher"]'
|
||||
) as HTMLInputElement;
|
||||
if (searchInput) {
|
||||
searchInput.focus();
|
||||
} else {
|
||||
// Naviguer vers Kanban où il y a une recherche
|
||||
window.location.href = '/kanban';
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[var(--background)]">
|
||||
<Header
|
||||
<Header
|
||||
title="TowerControl"
|
||||
subtitle="Dashboard - Vue d'ensemble"
|
||||
syncing={syncing}
|
||||
/>
|
||||
|
||||
|
||||
<main className="container mx-auto px-6 py-8">
|
||||
{/* Section de bienvenue */}
|
||||
<WelcomeSection />
|
||||
|
||||
|
||||
{/* Filtre d'intégrations */}
|
||||
<div className="flex justify-end mb-6">
|
||||
<IntegrationFilter
|
||||
<IntegrationFilter
|
||||
selectedSources={selectedSources}
|
||||
onSourcesChange={setSelectedSources}
|
||||
hiddenSources={hiddenSources}
|
||||
@@ -76,44 +81,51 @@ function HomePageContent({ productivityMetrics, deadlineMetrics, tagMetrics }: {
|
||||
alignRight={true}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
{/* Statistiques */}
|
||||
<DashboardStats selectedSources={selectedSources} hiddenSources={hiddenSources} />
|
||||
|
||||
<DashboardStats
|
||||
selectedSources={selectedSources}
|
||||
hiddenSources={hiddenSources}
|
||||
/>
|
||||
|
||||
{/* Actions rapides */}
|
||||
<QuickActions onCreateTask={handleCreateTask} />
|
||||
|
||||
|
||||
{/* Analytics et métriques */}
|
||||
<ProductivityAnalytics
|
||||
<ProductivityAnalytics
|
||||
metrics={productivityMetrics}
|
||||
deadlineMetrics={deadlineMetrics}
|
||||
tagMetrics={tagMetrics}
|
||||
selectedSources={selectedSources}
|
||||
hiddenSources={hiddenSources}
|
||||
/>
|
||||
|
||||
|
||||
{/* Tâches récentes */}
|
||||
<RecentTasks tasks={tasks} selectedSources={selectedSources} hiddenSources={hiddenSources} />
|
||||
<RecentTasks
|
||||
tasks={tasks}
|
||||
selectedSources={selectedSources}
|
||||
hiddenSources={hiddenSources}
|
||||
/>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function HomePageClient({
|
||||
initialTasks,
|
||||
initialTags,
|
||||
initialStats,
|
||||
productivityMetrics,
|
||||
export function HomePageClient({
|
||||
initialTasks,
|
||||
initialTags,
|
||||
initialStats,
|
||||
productivityMetrics,
|
||||
deadlineMetrics,
|
||||
tagMetrics
|
||||
tagMetrics,
|
||||
}: HomePageClientProps) {
|
||||
return (
|
||||
<TasksProvider
|
||||
<TasksProvider
|
||||
initialTasks={initialTasks}
|
||||
initialTags={initialTags}
|
||||
initialStats={initialStats}
|
||||
>
|
||||
<HomePageContent
|
||||
<HomePageContent
|
||||
productivityMetrics={productivityMetrics}
|
||||
deadlineMetrics={deadlineMetrics}
|
||||
tagMetrics={tagMetrics}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { KeyboardShortcutsModal } from '@/components/ui/KeyboardShortcutsModal';
|
||||
export function KeyboardShortcuts() {
|
||||
useGlobalKeyboardShortcuts();
|
||||
const { isOpen, shortcuts, closeModal } = useKeyboardShortcutsModal();
|
||||
|
||||
|
||||
return (
|
||||
<KeyboardShortcutsModal
|
||||
isOpen={isOpen}
|
||||
|
||||
@@ -2,54 +2,63 @@
|
||||
|
||||
import { useTheme } from '@/contexts/ThemeContext';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Theme, THEME_CONFIG, THEME_NAMES, getThemeIcon, getThemeDescription } from '@/lib/ui-config';
|
||||
|
||||
import {
|
||||
Theme,
|
||||
THEME_CONFIG,
|
||||
THEME_NAMES,
|
||||
getThemeIcon,
|
||||
getThemeDescription,
|
||||
} from '@/lib/ui-config';
|
||||
|
||||
// Génération des thèmes à partir de la configuration centralisée
|
||||
const themes: { id: Theme; name: string; description: string; icon: string }[] = THEME_CONFIG.allThemes.map(themeId => {
|
||||
return {
|
||||
id: themeId,
|
||||
name: THEME_NAMES[themeId],
|
||||
description: getThemeDescription(themeId),
|
||||
icon: getThemeIcon(themeId)
|
||||
};
|
||||
});
|
||||
const themes: { id: Theme; name: string; description: string; icon: string }[] =
|
||||
THEME_CONFIG.allThemes.map((themeId) => {
|
||||
return {
|
||||
id: themeId,
|
||||
name: THEME_NAMES[themeId],
|
||||
description: getThemeDescription(themeId),
|
||||
icon: getThemeIcon(themeId),
|
||||
};
|
||||
});
|
||||
|
||||
// Composant pour l'aperçu du thème
|
||||
function ThemePreview({ themeId, isSelected }: { themeId: Theme; isSelected: boolean }) {
|
||||
function ThemePreview({
|
||||
themeId,
|
||||
isSelected,
|
||||
}: {
|
||||
themeId: Theme;
|
||||
isSelected: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
<div
|
||||
className={`w-16 h-12 rounded-lg border-2 overflow-hidden ${themeId}`}
|
||||
style={{
|
||||
style={{
|
||||
borderColor: isSelected ? 'var(--primary)' : 'var(--border)',
|
||||
backgroundColor: 'var(--background)'
|
||||
backgroundColor: 'var(--background)',
|
||||
}}
|
||||
>
|
||||
{/* Barre de titre */}
|
||||
<div
|
||||
className="h-3 w-full"
|
||||
style={{ backgroundColor: 'var(--card)' }}
|
||||
/>
|
||||
|
||||
<div className="h-3 w-full" style={{ backgroundColor: 'var(--card)' }} />
|
||||
|
||||
{/* Contenu avec couleurs du thème */}
|
||||
<div className="p-1 h-9 flex flex-col gap-0.5">
|
||||
{/* Ligne de texte */}
|
||||
<div
|
||||
<div
|
||||
className="h-1 rounded-sm"
|
||||
style={{ backgroundColor: 'var(--foreground)' }}
|
||||
/>
|
||||
|
||||
|
||||
{/* Couleurs d'accent */}
|
||||
<div className="flex gap-0.5">
|
||||
<div
|
||||
<div
|
||||
className="h-1 flex-1 rounded-sm"
|
||||
style={{ backgroundColor: 'var(--primary)' }}
|
||||
/>
|
||||
<div
|
||||
<div
|
||||
className="h-1 flex-1 rounded-sm"
|
||||
style={{ backgroundColor: 'var(--accent)' }}
|
||||
/>
|
||||
<div
|
||||
<div
|
||||
className="h-1 flex-1 rounded-sm"
|
||||
style={{ backgroundColor: 'var(--success)' }}
|
||||
/>
|
||||
@@ -66,16 +75,21 @@ export function ThemeSelector() {
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 className="text-lg font-mono font-semibold text-[var(--foreground)]">Thème de l'interface</h3>
|
||||
<h3 className="text-lg font-mono font-semibold text-[var(--foreground)]">
|
||||
Thème de l'interface
|
||||
</h3>
|
||||
<p className="text-sm text-[var(--muted-foreground)] mt-1">
|
||||
Choisissez l'apparence de TowerControl
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-sm text-[var(--muted-foreground)]">
|
||||
Actuel: <span className="font-medium text-[var(--primary)] capitalize">{theme}</span>
|
||||
Actuel:{' '}
|
||||
<span className="font-medium text-[var(--primary)] capitalize">
|
||||
{theme}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
|
||||
{themes.map((themeOption) => (
|
||||
<Button
|
||||
@@ -87,12 +101,12 @@ export function ThemeSelector() {
|
||||
<div className="flex items-start gap-3">
|
||||
{/* Aperçu du thème */}
|
||||
<div className="flex-shrink-0">
|
||||
<ThemePreview
|
||||
themeId={themeOption.id}
|
||||
isSelected={theme === themeOption.id}
|
||||
<ThemePreview
|
||||
themeId={themeOption.id}
|
||||
isSelected={theme === themeOption.id}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium text-[var(--foreground)] mb-1 flex items-center gap-2">
|
||||
{themeOption.name}
|
||||
|
||||
@@ -3,9 +3,9 @@ export function TowerBackground() {
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-[var(--primary)]/20 via-[var(--background)] to-[var(--accent)]/20">
|
||||
{/* Effet de profondeur */}
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-black/20 via-transparent to-transparent"></div>
|
||||
|
||||
|
||||
{/* Effet de lumière */}
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-transparent via-[var(--primary)]/5 to-transparent"></div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,30 +1,38 @@
|
||||
interface TowerLogoProps {
|
||||
size?: 'sm' | 'md' | 'lg'
|
||||
showText?: boolean
|
||||
className?: string
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
showText?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function TowerLogo({ size = 'md', showText = true, className = '' }: TowerLogoProps) {
|
||||
export function TowerLogo({
|
||||
size = 'md',
|
||||
showText = true,
|
||||
className = '',
|
||||
}: TowerLogoProps) {
|
||||
const sizeClasses = {
|
||||
sm: 'w-12 h-12',
|
||||
md: 'w-20 h-20',
|
||||
lg: 'w-32 h-32'
|
||||
}
|
||||
lg: 'w-32 h-32',
|
||||
};
|
||||
|
||||
const textSizes = {
|
||||
sm: 'text-2xl',
|
||||
md: 'text-4xl',
|
||||
lg: 'text-6xl'
|
||||
}
|
||||
lg: 'text-6xl',
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`text-center ${className}`}>
|
||||
<div className={`inline-flex items-center justify-center ${sizeClasses[size]} rounded-2xl mb-4 text-6xl`}>
|
||||
<div
|
||||
className={`inline-flex items-center justify-center ${sizeClasses[size]} rounded-2xl mb-4 text-6xl`}
|
||||
>
|
||||
🗼
|
||||
</div>
|
||||
{showText && (
|
||||
<>
|
||||
<h1 className={`${textSizes[size]} font-mono font-bold text-[var(--foreground)] mb-2`}>
|
||||
<h1
|
||||
className={`${textSizes[size]} font-mono font-bold text-[var(--foreground)] mb-2`}
|
||||
>
|
||||
TowerControl
|
||||
</h1>
|
||||
<p className="text-[var(--muted-foreground)] text-lg">
|
||||
@@ -33,5 +41,5 @@ export function TowerLogo({ size = 'md', showText = true, className = '' }: Towe
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -12,20 +12,25 @@ interface BackupTimelineChartProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function BackupTimelineChart({ stats = [], className = '' }: BackupTimelineChartProps) {
|
||||
export function BackupTimelineChart({
|
||||
stats = [],
|
||||
className = '',
|
||||
}: BackupTimelineChartProps) {
|
||||
// Protection contre les stats non-array
|
||||
const safeStats = Array.isArray(stats) ? stats : [];
|
||||
const error = safeStats.length === 0 ? 'Aucune donnée disponible' : null;
|
||||
|
||||
// Convertir les stats en map pour accès rapide
|
||||
const statsMap = new Map(safeStats.map(s => [s.date, s]));
|
||||
|
||||
const statsMap = new Map(safeStats.map((s) => [s.date, s]));
|
||||
|
||||
// Générer les 30 derniers jours
|
||||
const days = Array.from({ length: 30 }, (_, i) => {
|
||||
const date = new Date();
|
||||
date.setDate(date.getDate() - (29 - i));
|
||||
// Utiliser la date locale pour éviter les décalages UTC
|
||||
const localDate = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
|
||||
const localDate = new Date(
|
||||
date.getTime() - date.getTimezoneOffset() * 60000
|
||||
);
|
||||
return localDate.toISOString().split('T')[0];
|
||||
});
|
||||
|
||||
@@ -35,23 +40,19 @@ export function BackupTimelineChart({ stats = [], className = '' }: BackupTimeli
|
||||
weeks.push(days.slice(i, i + 7));
|
||||
}
|
||||
|
||||
|
||||
|
||||
const formatDateFull = (dateStr: string) => {
|
||||
const date = new Date(dateStr);
|
||||
return date.toLocaleDateString('fr-FR', {
|
||||
return date.toLocaleDateString('fr-FR', {
|
||||
weekday: 'long',
|
||||
day: 'numeric',
|
||||
month: 'long'
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
});
|
||||
};
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className={`p-4 sm:p-6 ${className}`}>
|
||||
<div className="text-gray-500 text-sm text-center py-8">
|
||||
{error}
|
||||
</div>
|
||||
<div className="text-gray-500 text-sm text-center py-8">{error}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -61,55 +62,71 @@ export function BackupTimelineChart({ stats = [], className = '' }: BackupTimeli
|
||||
<h3 className="text-lg font-semibold mb-4 flex items-center gap-2">
|
||||
💾 Activité de sauvegarde (30 derniers jours)
|
||||
</h3>
|
||||
|
||||
|
||||
{/* Vue en ligne avec indicateurs clairs */}
|
||||
<div className="mb-6">
|
||||
{/* En-têtes des jours */}
|
||||
<div className="grid grid-cols-7 gap-1 mb-2">
|
||||
{['Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim'].map(day => (
|
||||
<div key={day} className="text-xs text-center text-gray-500 font-medium py-1">
|
||||
{['Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim'].map((day) => (
|
||||
<div
|
||||
key={day}
|
||||
className="text-xs text-center text-gray-500 font-medium py-1"
|
||||
>
|
||||
{day}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
|
||||
{/* Grille des jours avec indicateurs visuels */}
|
||||
<div className="space-y-1">
|
||||
{weeks.map((week, weekIndex) => (
|
||||
<div key={weekIndex} className="grid grid-cols-7 gap-1">
|
||||
{week.map((day) => {
|
||||
const stat = statsMap.get(day) || { date: day, manual: 0, automatic: 0, total: 0 };
|
||||
const stat = statsMap.get(day) || {
|
||||
date: day,
|
||||
manual: 0,
|
||||
automatic: 0,
|
||||
total: 0,
|
||||
};
|
||||
const hasManual = stat.manual > 0;
|
||||
const hasAuto = stat.automatic > 0;
|
||||
const dayNumber = new Date(day).getDate();
|
||||
|
||||
|
||||
return (
|
||||
<div key={day} className="group relative">
|
||||
<div className={`
|
||||
<div
|
||||
className={`
|
||||
relative h-8 rounded border-2 transition-all duration-200 cursor-pointer flex items-center justify-center text-xs font-medium
|
||||
${stat.total === 0
|
||||
? 'border-[var(--border)] text-[var(--muted-foreground)]'
|
||||
: 'border-transparent'
|
||||
${
|
||||
stat.total === 0
|
||||
? 'border-[var(--border)] text-[var(--muted-foreground)]'
|
||||
: 'border-transparent'
|
||||
}
|
||||
`}>
|
||||
`}
|
||||
>
|
||||
{/* Jour du mois */}
|
||||
<span className={`relative z-10 ${stat.total > 0 ? 'text-white font-bold' : ''}`}>
|
||||
<span
|
||||
className={`relative z-10 ${stat.total > 0 ? 'text-white font-bold' : ''}`}
|
||||
>
|
||||
{dayNumber}
|
||||
</span>
|
||||
|
||||
|
||||
{/* Fond selon le type */}
|
||||
{stat.total > 0 && (
|
||||
<div className={`
|
||||
<div
|
||||
className={`
|
||||
absolute inset-0 rounded
|
||||
${hasManual && hasAuto
|
||||
? 'bg-gradient-to-br from-blue-500 to-green-500'
|
||||
: hasManual
|
||||
? 'bg-blue-500'
|
||||
: 'bg-green-500'
|
||||
${
|
||||
hasManual && hasAuto
|
||||
? 'bg-gradient-to-br from-blue-500 to-green-500'
|
||||
: hasManual
|
||||
? 'bg-blue-500'
|
||||
: 'bg-green-500'
|
||||
}
|
||||
`}></div>
|
||||
`}
|
||||
></div>
|
||||
)}
|
||||
|
||||
|
||||
{/* Indicateurs visuels pour l'intensité */}
|
||||
{stat.total > 0 && stat.total > 1 && (
|
||||
<div className="absolute -top-1 -right-1 bg-orange-500 text-white rounded-full w-4 h-4 flex items-center justify-center text-xs font-bold">
|
||||
@@ -117,7 +134,7 @@ export function BackupTimelineChart({ stats = [], className = '' }: BackupTimeli
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
{/* Tooltip détaillé */}
|
||||
<div className="absolute bottom-full mb-2 left-1/2 transform -translate-x-1/2 bg-black text-white text-xs rounded py-2 px-3 opacity-0 group-hover:opacity-100 pointer-events-none transition-opacity whitespace-nowrap z-20">
|
||||
<div className="font-semibold">{formatDateFull(day)}</div>
|
||||
@@ -140,7 +157,9 @@ export function BackupTimelineChart({ stats = [], className = '' }: BackupTimeli
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-gray-300 mt-1">Aucune sauvegarde</div>
|
||||
<div className="text-gray-300 mt-1">
|
||||
Aucune sauvegarde
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -152,30 +171,50 @@ export function BackupTimelineChart({ stats = [], className = '' }: BackupTimeli
|
||||
</div>
|
||||
|
||||
{/* Légende claire */}
|
||||
<div className="mb-6 p-3 rounded-lg" style={{ backgroundColor: 'var(--card-hover)' }}>
|
||||
<h4 className="text-sm font-medium mb-3 text-[var(--foreground)]">Légende</h4>
|
||||
<div
|
||||
className="mb-6 p-3 rounded-lg"
|
||||
style={{ backgroundColor: 'var(--card-hover)' }}
|
||||
>
|
||||
<h4 className="text-sm font-medium mb-3 text-[var(--foreground)]">
|
||||
Légende
|
||||
</h4>
|
||||
<div className="grid grid-cols-2 gap-3 text-sm">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-6 h-6 bg-blue-500 rounded flex items-center justify-center text-white text-xs font-bold">15</div>
|
||||
<div className="w-6 h-6 bg-blue-500 rounded flex items-center justify-center text-white text-xs font-bold">
|
||||
15
|
||||
</div>
|
||||
<span className="text-[var(--foreground)]">Manuel seul</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-6 h-6 bg-green-500 rounded flex items-center justify-center text-white text-xs font-bold">15</div>
|
||||
<div className="w-6 h-6 bg-green-500 rounded flex items-center justify-center text-white text-xs font-bold">
|
||||
15
|
||||
</div>
|
||||
<span className="text-[var(--foreground)]">Auto seul</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-6 h-6 bg-gradient-to-br from-blue-500 to-green-500 rounded flex items-center justify-center text-white text-xs font-bold">15</div>
|
||||
<div className="w-6 h-6 bg-gradient-to-br from-blue-500 to-green-500 rounded flex items-center justify-center text-white text-xs font-bold">
|
||||
15
|
||||
</div>
|
||||
<span className="text-[var(--foreground)]">Manuel + Auto</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-6 h-6 border-2 rounded flex items-center justify-center text-xs" style={{ backgroundColor: 'var(--gray-light)', borderColor: 'var(--border)', color: 'var(--muted-foreground)' }}>15</div>
|
||||
<div
|
||||
className="w-6 h-6 border-2 rounded flex items-center justify-center text-xs"
|
||||
style={{
|
||||
backgroundColor: 'var(--gray-light)',
|
||||
borderColor: 'var(--border)',
|
||||
color: 'var(--muted-foreground)',
|
||||
}}
|
||||
>
|
||||
15
|
||||
</div>
|
||||
<span className="text-[var(--foreground)]">Aucune</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -187,23 +226,52 @@ export function BackupTimelineChart({ stats = [], className = '' }: BackupTimeli
|
||||
|
||||
{/* Statistiques résumées */}
|
||||
<div className="grid grid-cols-3 gap-3 text-center">
|
||||
<div className="p-3 rounded-lg" style={{ backgroundColor: 'color-mix(in srgb, var(--blue) 10%, transparent)' }}>
|
||||
<div
|
||||
className="p-3 rounded-lg"
|
||||
style={{
|
||||
backgroundColor: 'color-mix(in srgb, var(--blue) 10%, transparent)',
|
||||
}}
|
||||
>
|
||||
<div className="text-xl font-bold" style={{ color: 'var(--blue)' }}>
|
||||
{safeStats.reduce((sum, s) => sum + s.manual, 0)}
|
||||
</div>
|
||||
<div className="text-xs font-medium" style={{ color: 'var(--blue)' }}>Manuelles</div>
|
||||
<div className="text-xs font-medium" style={{ color: 'var(--blue)' }}>
|
||||
Manuelles
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-3 rounded-lg" style={{ backgroundColor: 'color-mix(in srgb, var(--green) 10%, transparent)' }}>
|
||||
<div
|
||||
className="p-3 rounded-lg"
|
||||
style={{
|
||||
backgroundColor:
|
||||
'color-mix(in srgb, var(--green) 10%, transparent)',
|
||||
}}
|
||||
>
|
||||
<div className="text-xl font-bold" style={{ color: 'var(--green)' }}>
|
||||
{safeStats.reduce((sum, s) => sum + s.automatic, 0)}
|
||||
</div>
|
||||
<div className="text-xs font-medium" style={{ color: 'var(--green)' }}>Automatiques</div>
|
||||
<div
|
||||
className="text-xs font-medium"
|
||||
style={{ color: 'var(--green)' }}
|
||||
>
|
||||
Automatiques
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-3 rounded-lg" style={{ backgroundColor: 'color-mix(in srgb, var(--purple) 10%, transparent)' }}>
|
||||
<div
|
||||
className="p-3 rounded-lg"
|
||||
style={{
|
||||
backgroundColor:
|
||||
'color-mix(in srgb, var(--purple) 10%, transparent)',
|
||||
}}
|
||||
>
|
||||
<div className="text-xl font-bold" style={{ color: 'var(--purple)' }}>
|
||||
{safeStats.reduce((sum, s) => sum + s.total, 0)}
|
||||
</div>
|
||||
<div className="text-xs font-medium" style={{ color: 'var(--purple)' }}>Total</div>
|
||||
<div
|
||||
className="text-xs font-medium"
|
||||
style={{ color: 'var(--purple)' }}
|
||||
>
|
||||
Total
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
'use client';
|
||||
|
||||
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
|
||||
import {
|
||||
LineChart,
|
||||
Line,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
ResponsiveContainer,
|
||||
} from 'recharts';
|
||||
import { Card } from '@/components/ui/Card';
|
||||
import { parseDate, formatDateShort } from '@/lib/date-utils';
|
||||
|
||||
@@ -16,7 +24,10 @@ interface CompletionTrendChartProps {
|
||||
title?: string;
|
||||
}
|
||||
|
||||
export function CompletionTrendChart({ data, title = "Tendance de Completion" }: CompletionTrendChartProps) {
|
||||
export function CompletionTrendChart({
|
||||
data,
|
||||
title = 'Tendance de Completion',
|
||||
}: CompletionTrendChartProps) {
|
||||
// Formatter pour les dates
|
||||
const formatDate = (dateStr: string) => {
|
||||
try {
|
||||
@@ -27,19 +38,29 @@ export function CompletionTrendChart({ data, title = "Tendance de Completion" }:
|
||||
};
|
||||
|
||||
// Tooltip personnalisé
|
||||
const CustomTooltip = ({ active, payload, label }: {
|
||||
active?: boolean;
|
||||
payload?: Array<{ name: string; value: number; color: string }>;
|
||||
label?: string
|
||||
const CustomTooltip = ({
|
||||
active,
|
||||
payload,
|
||||
label,
|
||||
}: {
|
||||
active?: boolean;
|
||||
payload?: Array<{ name: string; value: number; color: string }>;
|
||||
label?: string;
|
||||
}) => {
|
||||
if (active && payload && payload.length) {
|
||||
return (
|
||||
<div className="bg-[var(--card)] border border-[var(--border)] rounded-lg p-3 shadow-lg">
|
||||
<p className="text-sm font-medium mb-2">{label ? formatDate(label) : ''}</p>
|
||||
<p className="text-sm font-medium mb-2">
|
||||
{label ? formatDate(label) : ''}
|
||||
</p>
|
||||
{payload.map((entry, index: number) => (
|
||||
<p key={index} className="text-sm" style={{ color: entry.color }}>
|
||||
{entry.name === 'completed' ? 'Terminées' :
|
||||
entry.name === 'created' ? 'Créées' : 'Total'}: {entry.value}
|
||||
{entry.name === 'completed'
|
||||
? 'Terminées'
|
||||
: entry.name === 'created'
|
||||
? 'Créées'
|
||||
: 'Total'}
|
||||
: {entry.value}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
@@ -53,37 +74,40 @@ export function CompletionTrendChart({ data, title = "Tendance de Completion" }:
|
||||
<h3 className="text-lg font-semibold mb-4">{title}</h3>
|
||||
<div className="h-64">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<LineChart data={data} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
|
||||
<CartesianGrid
|
||||
strokeDasharray="3 3"
|
||||
stroke="var(--border)"
|
||||
<LineChart
|
||||
data={data}
|
||||
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
|
||||
>
|
||||
<CartesianGrid
|
||||
strokeDasharray="3 3"
|
||||
stroke="var(--border)"
|
||||
opacity={0.3}
|
||||
/>
|
||||
<XAxis
|
||||
dataKey="date"
|
||||
<XAxis
|
||||
dataKey="date"
|
||||
tickFormatter={formatDate}
|
||||
stroke="var(--muted-foreground)"
|
||||
fontSize={12}
|
||||
tick={{ fill: 'var(--muted-foreground)' }}
|
||||
/>
|
||||
<YAxis
|
||||
<YAxis
|
||||
stroke="var(--muted-foreground)"
|
||||
fontSize={12}
|
||||
tick={{ fill: 'var(--muted-foreground)' }}
|
||||
/>
|
||||
<Tooltip content={<CustomTooltip />} />
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="completed"
|
||||
stroke="#10b981"
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="completed"
|
||||
stroke="#10b981"
|
||||
strokeWidth={2}
|
||||
dot={{ fill: '#10b981', strokeWidth: 2, r: 4 }}
|
||||
activeDot={{ r: 6, stroke: '#10b981', strokeWidth: 2 }}
|
||||
/>
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="created"
|
||||
stroke="#3b82f6"
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="created"
|
||||
stroke="#3b82f6"
|
||||
strokeWidth={2}
|
||||
strokeDasharray="5 5"
|
||||
dot={{ fill: '#3b82f6', strokeWidth: 2, r: 4 }}
|
||||
@@ -92,12 +116,14 @@ export function CompletionTrendChart({ data, title = "Tendance de Completion" }:
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
|
||||
|
||||
{/* Légende */}
|
||||
<div className="flex items-center justify-center gap-6 mt-4 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-3 h-0.5 bg-green-500"></div>
|
||||
<span className="text-[var(--muted-foreground)]">Tâches terminées</span>
|
||||
<span className="text-[var(--muted-foreground)]">
|
||||
Tâches terminées
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-3 h-0.5 bg-blue-500 border-dashed border-t"></div>
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
'use client';
|
||||
|
||||
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip, Legend, PieLabelRenderProps } from 'recharts';
|
||||
import {
|
||||
PieChart,
|
||||
Pie,
|
||||
Cell,
|
||||
ResponsiveContainer,
|
||||
Tooltip,
|
||||
Legend,
|
||||
PieLabelRenderProps,
|
||||
} from 'recharts';
|
||||
import { Card } from '@/components/ui/Card';
|
||||
import { getPriorityChartColor } from '@/lib/status-config';
|
||||
|
||||
@@ -18,9 +26,18 @@ interface PriorityDistributionChartProps {
|
||||
|
||||
// Couleurs importées depuis la configuration centralisée
|
||||
|
||||
export function PriorityDistributionChart({ data, title = "Distribution des Priorités" }: PriorityDistributionChartProps) {
|
||||
export function PriorityDistributionChart({
|
||||
data,
|
||||
title = 'Distribution des Priorités',
|
||||
}: PriorityDistributionChartProps) {
|
||||
// Tooltip personnalisé
|
||||
const CustomTooltip = ({ active, payload }: { active?: boolean; payload?: Array<{ payload: PriorityData }> }) => {
|
||||
const CustomTooltip = ({
|
||||
active,
|
||||
payload,
|
||||
}: {
|
||||
active?: boolean;
|
||||
payload?: Array<{ payload: PriorityData }>;
|
||||
}) => {
|
||||
if (active && payload && payload.length) {
|
||||
const data = payload[0].payload;
|
||||
return (
|
||||
@@ -36,12 +53,16 @@ export function PriorityDistributionChart({ data, title = "Distribution des Prio
|
||||
};
|
||||
|
||||
// Légende personnalisée
|
||||
const CustomLegend = ({ payload }: { payload?: Array<{ value: string; color: string }> }) => {
|
||||
const CustomLegend = ({
|
||||
payload,
|
||||
}: {
|
||||
payload?: Array<{ value: string; color: string }>;
|
||||
}) => {
|
||||
return (
|
||||
<div className="flex flex-wrap justify-center gap-4 mt-4">
|
||||
{payload?.map((entry, index: number) => (
|
||||
<div key={index} className="flex items-center gap-2">
|
||||
<div
|
||||
<div
|
||||
className="w-3 h-3 rounded-full"
|
||||
style={{ backgroundColor: entry.color }}
|
||||
></div>
|
||||
@@ -56,7 +77,8 @@ export function PriorityDistributionChart({ data, title = "Distribution des Prio
|
||||
|
||||
// Label personnalisé pour afficher les pourcentages
|
||||
const renderLabel = (props: PieLabelRenderProps) => {
|
||||
const percentage = typeof props.percent === 'number' ? props.percent * 100 : 0;
|
||||
const percentage =
|
||||
typeof props.percent === 'number' ? props.percent * 100 : 0;
|
||||
return percentage > 5 ? `${Math.round(percentage)}%` : '';
|
||||
};
|
||||
|
||||
@@ -78,9 +100,9 @@ export function PriorityDistributionChart({ data, title = "Distribution des Prio
|
||||
nameKey="priority"
|
||||
>
|
||||
{data.map((entry, index) => (
|
||||
<Cell
|
||||
key={`cell-${index}`}
|
||||
fill={getPriorityChartColor(entry.priority)}
|
||||
<Cell
|
||||
key={`cell-${index}`}
|
||||
fill={getPriorityChartColor(entry.priority)}
|
||||
/>
|
||||
))}
|
||||
</Pie>
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
'use client';
|
||||
|
||||
import { Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Line, ComposedChart } from 'recharts';
|
||||
import {
|
||||
Bar,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
ResponsiveContainer,
|
||||
Line,
|
||||
ComposedChart,
|
||||
} from 'recharts';
|
||||
import { Card } from '@/components/ui/Card';
|
||||
|
||||
interface VelocityData {
|
||||
@@ -14,12 +23,19 @@ interface VelocityChartProps {
|
||||
title?: string;
|
||||
}
|
||||
|
||||
export function VelocityChart({ data, title = "Vélocité Hebdomadaire" }: VelocityChartProps) {
|
||||
export function VelocityChart({
|
||||
data,
|
||||
title = 'Vélocité Hebdomadaire',
|
||||
}: VelocityChartProps) {
|
||||
// Tooltip personnalisé
|
||||
const CustomTooltip = ({ active, payload, label }: {
|
||||
active?: boolean;
|
||||
payload?: Array<{ dataKey: string; value: number; color: string }>;
|
||||
label?: string
|
||||
const CustomTooltip = ({
|
||||
active,
|
||||
payload,
|
||||
label,
|
||||
}: {
|
||||
active?: boolean;
|
||||
payload?: Array<{ dataKey: string; value: number; color: string }>;
|
||||
label?: string;
|
||||
}) => {
|
||||
if (active && payload && payload.length) {
|
||||
return (
|
||||
@@ -27,7 +43,8 @@ export function VelocityChart({ data, title = "Vélocité Hebdomadaire" }: Veloc
|
||||
<p className="text-sm font-medium mb-2">{label}</p>
|
||||
{payload.map((entry, index: number) => (
|
||||
<p key={index} className="text-sm" style={{ color: entry.color }}>
|
||||
{entry.dataKey === 'completed' ? 'Terminées' : 'Moyenne'}: {entry.value}
|
||||
{entry.dataKey === 'completed' ? 'Terminées' : 'Moyenne'}:{' '}
|
||||
{entry.value}
|
||||
{entry.dataKey === 'completed' ? ' tâches' : ' tâches/sem'}
|
||||
</p>
|
||||
))}
|
||||
@@ -42,34 +59,37 @@ export function VelocityChart({ data, title = "Vélocité Hebdomadaire" }: Veloc
|
||||
<h3 className="text-lg font-semibold mb-4">{title}</h3>
|
||||
<div className="h-64">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<ComposedChart data={data} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
|
||||
<CartesianGrid
|
||||
strokeDasharray="3 3"
|
||||
stroke="var(--border)"
|
||||
<ComposedChart
|
||||
data={data}
|
||||
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
|
||||
>
|
||||
<CartesianGrid
|
||||
strokeDasharray="3 3"
|
||||
stroke="var(--border)"
|
||||
opacity={0.3}
|
||||
/>
|
||||
<XAxis
|
||||
dataKey="week"
|
||||
<XAxis
|
||||
dataKey="week"
|
||||
stroke="var(--muted-foreground)"
|
||||
fontSize={12}
|
||||
tick={{ fill: 'var(--muted-foreground)' }}
|
||||
/>
|
||||
<YAxis
|
||||
<YAxis
|
||||
stroke="var(--muted-foreground)"
|
||||
fontSize={12}
|
||||
tick={{ fill: 'var(--muted-foreground)' }}
|
||||
/>
|
||||
<Tooltip content={<CustomTooltip />} />
|
||||
<Bar
|
||||
dataKey="completed"
|
||||
<Bar
|
||||
dataKey="completed"
|
||||
fill="#3b82f6"
|
||||
radius={[4, 4, 0, 0]}
|
||||
opacity={0.8}
|
||||
/>
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="average"
|
||||
stroke="#f59e0b"
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="average"
|
||||
stroke="#f59e0b"
|
||||
strokeWidth={3}
|
||||
dot={{ fill: '#f59e0b', strokeWidth: 2, r: 5 }}
|
||||
activeDot={{ r: 7, stroke: '#f59e0b', strokeWidth: 2 }}
|
||||
@@ -77,12 +97,14 @@ export function VelocityChart({ data, title = "Vélocité Hebdomadaire" }: Veloc
|
||||
</ComposedChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
|
||||
|
||||
{/* Légende */}
|
||||
<div className="flex items-center justify-center gap-6 mt-4 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-3 h-3 bg-blue-500 rounded-sm opacity-80"></div>
|
||||
<span className="text-[var(--muted-foreground)]">Tâches terminées</span>
|
||||
<span className="text-[var(--muted-foreground)]">
|
||||
Tâches terminées
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-3 h-0.5 bg-amber-500"></div>
|
||||
|
||||
@@ -15,18 +15,23 @@ interface WeeklyStatsCardProps {
|
||||
title?: string;
|
||||
}
|
||||
|
||||
export function WeeklyStatsCard({ stats, title = "Performance Hebdomadaire" }: WeeklyStatsCardProps) {
|
||||
export function WeeklyStatsCard({
|
||||
stats,
|
||||
title = 'Performance Hebdomadaire',
|
||||
}: WeeklyStatsCardProps) {
|
||||
const isPositive = stats.change >= 0;
|
||||
const changeColor = isPositive ? 'text-[var(--success)]' : 'text-[var(--destructive)]';
|
||||
const changeColor = isPositive
|
||||
? 'text-[var(--success)]'
|
||||
: 'text-[var(--destructive)]';
|
||||
const changeIcon = isPositive ? '↗️' : '↘️';
|
||||
const changeBg = isPositive
|
||||
? 'bg-[var(--success)]/10 border border-[var(--success)]/20'
|
||||
const changeBg = isPositive
|
||||
? 'bg-[var(--success)]/10 border border-[var(--success)]/20'
|
||||
: 'bg-[var(--destructive)]/10 border border-[var(--destructive)]/20';
|
||||
|
||||
return (
|
||||
<Card variant="glass" className="p-6">
|
||||
<h3 className="text-lg font-semibold mb-6">{title}</h3>
|
||||
|
||||
|
||||
<div className="grid grid-cols-2 gap-6">
|
||||
{/* Cette semaine */}
|
||||
<div className="text-center">
|
||||
@@ -37,7 +42,7 @@ export function WeeklyStatsCard({ stats, title = "Performance Hebdomadaire" }: W
|
||||
Cette semaine
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
{/* Semaine dernière */}
|
||||
<div className="text-center">
|
||||
<div className="text-3xl font-bold text-[var(--muted-foreground)] mb-2">
|
||||
@@ -48,30 +53,52 @@ export function WeeklyStatsCard({ stats, title = "Performance Hebdomadaire" }: W
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
{/* Changement */}
|
||||
<div className="mt-6 pt-4 border-t border-[var(--border)]">
|
||||
<div className={`flex items-center justify-center gap-2 p-3 rounded-lg ${changeBg}`}>
|
||||
<span className="text-lg"><Emoji emoji={changeIcon} /></span>
|
||||
<div
|
||||
className={`flex items-center justify-center gap-2 p-3 rounded-lg ${changeBg}`}
|
||||
>
|
||||
<span className="text-lg">
|
||||
<Emoji emoji={changeIcon} />
|
||||
</span>
|
||||
<div className="text-center">
|
||||
<div className={`font-bold ${changeColor}`}>
|
||||
{isPositive ? '+' : ''}{stats.change} tâches
|
||||
{isPositive ? '+' : ''}
|
||||
{stats.change} tâches
|
||||
</div>
|
||||
<div className={`text-sm ${changeColor}`}>
|
||||
{isPositive ? '+' : ''}{stats.changePercent}% vs semaine dernière
|
||||
{isPositive ? '+' : ''}
|
||||
{stats.changePercent}% vs semaine dernière
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
{/* Insight */}
|
||||
<div className="mt-4 text-center">
|
||||
<p className="text-xs text-[var(--muted-foreground)]">
|
||||
{stats.changePercent > 20 ? <><Emoji emoji="🚀" /> Excellente progression !</> :
|
||||
stats.changePercent > 0 ? <><Emoji emoji="👍" /> Bonne progression</> :
|
||||
stats.changePercent === 0 ? <><Emoji emoji="📊" /> Performance stable</> :
|
||||
stats.changePercent > -20 ? <><Emoji emoji="💪" /> Légère baisse, restez motivé</> :
|
||||
<><Emoji emoji="🎯" /> Focus sur la productivité cette semaine</>}
|
||||
{stats.changePercent > 20 ? (
|
||||
<>
|
||||
<Emoji emoji="🚀" /> Excellente progression !
|
||||
</>
|
||||
) : stats.changePercent > 0 ? (
|
||||
<>
|
||||
<Emoji emoji="👍" /> Bonne progression
|
||||
</>
|
||||
) : stats.changePercent === 0 ? (
|
||||
<>
|
||||
<Emoji emoji="📊" /> Performance stable
|
||||
</>
|
||||
) : stats.changePercent > -20 ? (
|
||||
<>
|
||||
<Emoji emoji="💪" /> Légère baisse, restez motivé
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Emoji emoji="🎯" /> Focus sur la productivité cette semaine
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
@@ -9,29 +9,43 @@ import { EditCheckboxModal } from './EditCheckboxModal';
|
||||
interface DailyCheckboxItemProps {
|
||||
checkbox: DailyCheckbox;
|
||||
onToggle: (checkboxId: string) => Promise<void>;
|
||||
onUpdate: (checkboxId: string, text: string, type: DailyCheckboxType, taskId?: string, date?: Date) => Promise<void>;
|
||||
onUpdate: (
|
||||
checkboxId: string,
|
||||
text: string,
|
||||
type: DailyCheckboxType,
|
||||
taskId?: string,
|
||||
date?: Date
|
||||
) => Promise<void>;
|
||||
onDelete: (checkboxId: string) => Promise<void>;
|
||||
saving?: boolean;
|
||||
}
|
||||
|
||||
export function DailyCheckboxItem({
|
||||
checkbox,
|
||||
onToggle,
|
||||
onUpdate,
|
||||
onDelete,
|
||||
saving = false
|
||||
export function DailyCheckboxItem({
|
||||
checkbox,
|
||||
onToggle,
|
||||
onUpdate,
|
||||
onDelete,
|
||||
saving = false,
|
||||
}: DailyCheckboxItemProps) {
|
||||
const [inlineEditingId, setInlineEditingId] = useState<string | null>(null);
|
||||
const [inlineEditingText, setInlineEditingText] = useState('');
|
||||
const [editingCheckbox, setEditingCheckbox] = useState<DailyCheckbox | null>(null);
|
||||
const [optimisticChecked, setOptimisticChecked] = useState<boolean | null>(null);
|
||||
const [editingCheckbox, setEditingCheckbox] = useState<DailyCheckbox | null>(
|
||||
null
|
||||
);
|
||||
const [optimisticChecked, setOptimisticChecked] = useState<boolean | null>(
|
||||
null
|
||||
);
|
||||
|
||||
// État optimiste local pour une réponse immédiate
|
||||
const isChecked = optimisticChecked !== null ? optimisticChecked : checkbox.isChecked;
|
||||
const isChecked =
|
||||
optimisticChecked !== null ? optimisticChecked : checkbox.isChecked;
|
||||
|
||||
// Synchroniser l'état optimiste avec les changements externes
|
||||
useEffect(() => {
|
||||
if (optimisticChecked !== null && optimisticChecked === checkbox.isChecked) {
|
||||
if (
|
||||
optimisticChecked !== null &&
|
||||
optimisticChecked === checkbox.isChecked
|
||||
) {
|
||||
// L'état serveur a été mis à jour, on peut reset l'optimiste
|
||||
setOptimisticChecked(null);
|
||||
}
|
||||
@@ -40,10 +54,10 @@ export function DailyCheckboxItem({
|
||||
// Handler optimiste pour le toggle
|
||||
const handleOptimisticToggle = async () => {
|
||||
const newCheckedState = !isChecked;
|
||||
|
||||
|
||||
// Mise à jour optimiste immédiate
|
||||
setOptimisticChecked(newCheckedState);
|
||||
|
||||
|
||||
try {
|
||||
await onToggle(checkbox.id);
|
||||
// Reset l'état optimiste après succès
|
||||
@@ -65,7 +79,12 @@ export function DailyCheckboxItem({
|
||||
if (!inlineEditingText.trim()) return;
|
||||
|
||||
try {
|
||||
await onUpdate(checkbox.id, inlineEditingText.trim(), checkbox.type, checkbox.taskId);
|
||||
await onUpdate(
|
||||
checkbox.id,
|
||||
inlineEditingText.trim(),
|
||||
checkbox.type,
|
||||
checkbox.taskId
|
||||
);
|
||||
setInlineEditingId(null);
|
||||
setInlineEditingText('');
|
||||
} catch (error) {
|
||||
@@ -93,7 +112,12 @@ export function DailyCheckboxItem({
|
||||
setEditingCheckbox(checkbox);
|
||||
};
|
||||
|
||||
const handleSaveAdvancedEdit = async (text: string, type: DailyCheckboxType, taskId?: string, date?: Date) => {
|
||||
const handleSaveAdvancedEdit = async (
|
||||
text: string,
|
||||
type: DailyCheckboxType,
|
||||
taskId?: string,
|
||||
date?: Date
|
||||
) => {
|
||||
await onUpdate(checkbox.id, text, type, taskId, date);
|
||||
setEditingCheckbox(null);
|
||||
};
|
||||
@@ -107,11 +131,13 @@ export function DailyCheckboxItem({
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={`flex items-center gap-3 px-3 py-2 sm:py-1.5 sm:gap-2 rounded border transition-colors group ${
|
||||
checkbox.type === 'meeting'
|
||||
? 'border-l-4 border-l-blue-500 border-t-[var(--border)]/30 border-r-[var(--border)]/30 border-b-[var(--border)]/30 hover:border-t-[var(--border)] hover:border-r-[var(--border)] hover:border-b-[var(--border)]'
|
||||
: 'border-l-4 border-l-green-500 border-t-[var(--border)]/30 border-r-[var(--border)]/30 border-b-[var(--border)]/30 hover:border-t-[var(--border)] hover:border-r-[var(--border)] hover:border-b-[var(--border)]'
|
||||
} ${isArchived ? 'opacity-60 bg-[var(--muted)]/20' : ''}`}>
|
||||
<div
|
||||
className={`flex items-center gap-3 px-3 py-2 sm:py-1.5 sm:gap-2 rounded border transition-colors group ${
|
||||
checkbox.type === 'meeting'
|
||||
? 'border-l-4 border-l-blue-500 border-t-[var(--border)]/30 border-r-[var(--border)]/30 border-b-[var(--border)]/30 hover:border-t-[var(--border)] hover:border-r-[var(--border)] hover:border-b-[var(--border)]'
|
||||
: 'border-l-4 border-l-green-500 border-t-[var(--border)]/30 border-r-[var(--border)]/30 border-b-[var(--border)]/30 hover:border-t-[var(--border)] hover:border-r-[var(--border)] hover:border-b-[var(--border)]'
|
||||
} ${isArchived ? 'opacity-60 bg-[var(--muted)]/20' : ''}`}
|
||||
>
|
||||
{/* Checkbox */}
|
||||
<input
|
||||
type="checkbox"
|
||||
@@ -119,12 +145,12 @@ export function DailyCheckboxItem({
|
||||
onChange={handleOptimisticToggle}
|
||||
disabled={saving || isArchived}
|
||||
className={`w-4 h-4 md:w-3.5 md:h-3.5 rounded border text-[var(--primary)] focus:ring-[var(--primary)]/20 focus:ring-1 ${
|
||||
isArchived
|
||||
? 'border-[var(--muted)] cursor-not-allowed opacity-50'
|
||||
isArchived
|
||||
? 'border-[var(--muted)] cursor-not-allowed opacity-50'
|
||||
: 'border-[var(--border)]'
|
||||
}`}
|
||||
/>
|
||||
|
||||
|
||||
{/* Contenu principal */}
|
||||
{inlineEditingId === checkbox.id ? (
|
||||
<Input
|
||||
@@ -138,10 +164,10 @@ export function DailyCheckboxItem({
|
||||
) : (
|
||||
<div className="flex-1 flex items-center gap-2">
|
||||
{/* Texte cliquable pour édition inline */}
|
||||
<span
|
||||
<span
|
||||
className={`flex-1 text-sm sm:text-xs font-mono transition-all cursor-pointer hover:bg-[var(--muted)]/50 py-0.5 px-1 rounded ${
|
||||
isArchived || checkbox.isChecked
|
||||
? 'line-through text-[var(--muted-foreground)]'
|
||||
isArchived || checkbox.isChecked
|
||||
? 'line-through text-[var(--muted-foreground)]'
|
||||
: 'text-[var(--foreground)]'
|
||||
}`}
|
||||
onClick={handleStartInlineEdit}
|
||||
|
||||
@@ -8,7 +8,12 @@ import { DailyCheckboxItem } from './DailyCheckboxItem';
|
||||
interface DailyCheckboxSortableProps {
|
||||
checkbox: DailyCheckbox;
|
||||
onToggle: (checkboxId: string) => Promise<void>;
|
||||
onUpdate: (checkboxId: string, text: string, type: DailyCheckboxType, taskId?: string) => Promise<void>;
|
||||
onUpdate: (
|
||||
checkboxId: string,
|
||||
text: string,
|
||||
type: DailyCheckboxType,
|
||||
taskId?: string
|
||||
) => Promise<void>;
|
||||
onDelete: (checkboxId: string) => Promise<void>;
|
||||
saving?: boolean;
|
||||
}
|
||||
@@ -18,7 +23,7 @@ export function DailyCheckboxSortable({
|
||||
onToggle,
|
||||
onUpdate,
|
||||
onDelete,
|
||||
saving = false
|
||||
saving = false,
|
||||
}: DailyCheckboxSortableProps) {
|
||||
const {
|
||||
attributes,
|
||||
@@ -49,8 +54,8 @@ export function DailyCheckboxSortable({
|
||||
>
|
||||
<div className="relative group">
|
||||
{/* Handle de drag */}
|
||||
<div
|
||||
{...attributes}
|
||||
<div
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
className="absolute left-0 top-0 bottom-0 w-3 cursor-grab active:cursor-grabbing flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
title="Glisser pour réorganiser"
|
||||
@@ -61,7 +66,7 @@ export function DailyCheckboxSortable({
|
||||
<div className="w-full h-0.5 bg-[var(--muted-foreground)] rounded"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
{/* Checkbox item avec padding left pour le handle */}
|
||||
<div className="pl-4">
|
||||
<DailyCheckboxItem
|
||||
|
||||
@@ -8,8 +8,18 @@ import { DailyCheckboxSortable } from './DailyCheckboxSortable';
|
||||
import { CheckboxItem, CheckboxItemData } from '@/components/ui/CheckboxItem';
|
||||
import { DailyAddForm, AddFormOption } from '@/components/ui/DailyAddForm';
|
||||
import { CheckSquare2, Calendar } from 'lucide-react';
|
||||
import { DndContext, closestCenter, DragEndEvent, DragOverlay, DragStartEvent } from '@dnd-kit/core';
|
||||
import { SortableContext, verticalListSortingStrategy, arrayMove } from '@dnd-kit/sortable';
|
||||
import {
|
||||
DndContext,
|
||||
closestCenter,
|
||||
DragEndEvent,
|
||||
DragOverlay,
|
||||
DragStartEvent,
|
||||
} from '@dnd-kit/core';
|
||||
import {
|
||||
SortableContext,
|
||||
verticalListSortingStrategy,
|
||||
arrayMove,
|
||||
} from '@dnd-kit/sortable';
|
||||
import { useState } from 'react';
|
||||
import React from 'react';
|
||||
|
||||
@@ -19,7 +29,13 @@ interface DailySectionProps {
|
||||
checkboxes: DailyCheckbox[];
|
||||
onAddCheckbox: (text: string, type: DailyCheckboxType) => Promise<void>;
|
||||
onToggleCheckbox: (checkboxId: string) => Promise<void>;
|
||||
onUpdateCheckbox: (checkboxId: string, text: string, type: DailyCheckboxType, taskId?: string, date?: Date) => Promise<void>;
|
||||
onUpdateCheckbox: (
|
||||
checkboxId: string,
|
||||
text: string,
|
||||
type: DailyCheckboxType,
|
||||
taskId?: string,
|
||||
date?: Date
|
||||
) => Promise<void>;
|
||||
onDeleteCheckbox: (checkboxId: string) => Promise<void>;
|
||||
onReorderCheckboxes: (date: Date, checkboxIds: string[]) => Promise<void>;
|
||||
onToggleAll?: () => Promise<void>;
|
||||
@@ -27,18 +43,18 @@ interface DailySectionProps {
|
||||
refreshing?: boolean;
|
||||
}
|
||||
|
||||
export function DailySection({
|
||||
title,
|
||||
export function DailySection({
|
||||
title,
|
||||
date,
|
||||
checkboxes,
|
||||
onAddCheckbox,
|
||||
onToggleCheckbox,
|
||||
checkboxes,
|
||||
onAddCheckbox,
|
||||
onToggleCheckbox,
|
||||
onUpdateCheckbox,
|
||||
onDeleteCheckbox,
|
||||
onReorderCheckboxes,
|
||||
onToggleAll,
|
||||
saving,
|
||||
refreshing = false
|
||||
refreshing = false,
|
||||
}: DailySectionProps) {
|
||||
const [activeId, setActiveId] = useState<string | null>(null);
|
||||
const [items, setItems] = useState(checkboxes);
|
||||
@@ -69,7 +85,7 @@ export function DailySection({
|
||||
setItems(newItems);
|
||||
|
||||
// Envoyer l'ordre au serveur
|
||||
const checkboxIds = newItems.map(item => item.id);
|
||||
const checkboxIds = newItems.map((item) => item.id);
|
||||
try {
|
||||
await onReorderCheckboxes(date, checkboxIds);
|
||||
} catch (error) {
|
||||
@@ -80,23 +96,37 @@ export function DailySection({
|
||||
}
|
||||
};
|
||||
|
||||
const activeCheckbox = activeId ? items.find(item => item.id === activeId) : null;
|
||||
const activeCheckbox = activeId
|
||||
? items.find((item) => item.id === activeId)
|
||||
: null;
|
||||
|
||||
// Options pour le formulaire d'ajout
|
||||
const addFormOptions: AddFormOption[] = [
|
||||
{ value: 'meeting', label: 'Réunion', icon: <Calendar size={14} />, color: 'blue' },
|
||||
{ value: 'task', label: 'Tâche', icon: <CheckSquare2 size={14} />, color: 'green' }
|
||||
{
|
||||
value: 'meeting',
|
||||
label: 'Réunion',
|
||||
icon: <Calendar size={14} />,
|
||||
color: 'blue',
|
||||
},
|
||||
{
|
||||
value: 'task',
|
||||
label: 'Tâche',
|
||||
icon: <CheckSquare2 size={14} />,
|
||||
color: 'green',
|
||||
},
|
||||
];
|
||||
|
||||
// Convertir les checkboxes en format CheckboxItemData
|
||||
const convertToCheckboxItemData = (checkbox: DailyCheckbox): CheckboxItemData => ({
|
||||
const convertToCheckboxItemData = (
|
||||
checkbox: DailyCheckbox
|
||||
): CheckboxItemData => ({
|
||||
id: checkbox.id,
|
||||
text: checkbox.text,
|
||||
isChecked: checkbox.isChecked,
|
||||
type: checkbox.type,
|
||||
taskId: checkbox.taskId,
|
||||
task: checkbox.task,
|
||||
isArchived: checkbox.isArchived
|
||||
isArchived: checkbox.isArchived,
|
||||
});
|
||||
|
||||
return (
|
||||
@@ -111,14 +141,16 @@ export function DailySection({
|
||||
<div className="p-4 pb-0">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-lg font-bold text-[var(--foreground)] font-mono flex items-center gap-2">
|
||||
{title} <span className="text-sm font-normal text-[var(--muted-foreground)]"></span>
|
||||
{title}{' '}
|
||||
<span className="text-sm font-normal text-[var(--muted-foreground)]"></span>
|
||||
{refreshing && (
|
||||
<div className="w-4 h-4 border-2 border-[var(--primary)] border-t-transparent rounded-full animate-spin"></div>
|
||||
)}
|
||||
</h2>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-[var(--muted-foreground)] font-mono">
|
||||
{checkboxes.filter(cb => cb.isChecked).length}/{checkboxes.length}
|
||||
{checkboxes.filter((cb) => cb.isChecked).length}/
|
||||
{checkboxes.length}
|
||||
</span>
|
||||
{onToggleAll && checkboxes.length > 0 && (
|
||||
<Button
|
||||
@@ -139,7 +171,10 @@ export function DailySection({
|
||||
|
||||
{/* Liste des checkboxes - zone scrollable avec drag & drop */}
|
||||
<div className="flex-1 px-4 overflow-y-auto min-h-0">
|
||||
<SortableContext items={items.map(item => item.id)} strategy={verticalListSortingStrategy}>
|
||||
<SortableContext
|
||||
items={items.map((item) => item.id)}
|
||||
strategy={verticalListSortingStrategy}
|
||||
>
|
||||
<div className="space-y-1.5 pb-4">
|
||||
{items.map((checkbox) => (
|
||||
<DailyCheckboxSortable
|
||||
@@ -164,7 +199,9 @@ export function DailySection({
|
||||
{/* Footer - Formulaire d'ajout toujours en bas */}
|
||||
<div className="p-4 pt-2 border-t border-[var(--border)]/30 bg-[var(--card)]/50">
|
||||
<DailyAddForm
|
||||
onAdd={(text, option) => onAddCheckbox(text, option as DailyCheckboxType)}
|
||||
onAdd={(text, option) =>
|
||||
onAddCheckbox(text, option as DailyCheckboxType)
|
||||
}
|
||||
disabled={saving}
|
||||
placeholder="Ajouter une tâche..."
|
||||
options={addFormOptions}
|
||||
@@ -173,9 +210,9 @@ export function DailySection({
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<DragOverlay
|
||||
<DragOverlay
|
||||
dropAnimation={null}
|
||||
style={{
|
||||
style={{
|
||||
transformOrigin: '0 0',
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -18,16 +18,21 @@ interface EditCheckboxModalProps {
|
||||
checkbox: DailyCheckbox;
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSave: (text: string, type: DailyCheckboxType, taskId?: string, date?: Date) => Promise<void>;
|
||||
onSave: (
|
||||
text: string,
|
||||
type: DailyCheckboxType,
|
||||
taskId?: string,
|
||||
date?: Date
|
||||
) => Promise<void>;
|
||||
saving?: boolean;
|
||||
}
|
||||
|
||||
export function EditCheckboxModal({
|
||||
checkbox,
|
||||
isOpen,
|
||||
onClose,
|
||||
onSave,
|
||||
saving = false
|
||||
export function EditCheckboxModal({
|
||||
checkbox,
|
||||
isOpen,
|
||||
onClose,
|
||||
onSave,
|
||||
saving = false,
|
||||
}: EditCheckboxModalProps) {
|
||||
const [text, setText] = useState(checkbox.text);
|
||||
const [type, setType] = useState<DailyCheckboxType>(checkbox.type);
|
||||
@@ -42,8 +47,9 @@ export function EditCheckboxModal({
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setTasksLoading(true);
|
||||
tasksClient.getTasks()
|
||||
.then(response => {
|
||||
tasksClient
|
||||
.getTasks()
|
||||
.then((response) => {
|
||||
setAllTasks(response.data);
|
||||
// Trouver la tâche sélectionnée si elle existe
|
||||
if (taskId) {
|
||||
@@ -67,15 +73,18 @@ export function EditCheckboxModal({
|
||||
}, [taskId, allTasks]);
|
||||
|
||||
// Filtrer les tâches selon la recherche et exclure les tâches avec des tags "objectif principal"
|
||||
const filteredTasks = allTasks.filter(task => {
|
||||
const filteredTasks = allTasks.filter((task) => {
|
||||
// Exclure les tâches avec des tags marqués comme "objectif principal" (isPinned = true)
|
||||
if (task.tagDetails && task.tagDetails.some(tag => tag.isPinned)) {
|
||||
if (task.tagDetails && task.tagDetails.some((tag) => tag.isPinned)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// Filtrer selon la recherche
|
||||
return task.title.toLowerCase().includes(taskSearch.toLowerCase()) ||
|
||||
(task.description && task.description.toLowerCase().includes(taskSearch.toLowerCase()));
|
||||
return (
|
||||
task.title.toLowerCase().includes(taskSearch.toLowerCase()) ||
|
||||
(task.description &&
|
||||
task.description.toLowerCase().includes(taskSearch.toLowerCase()))
|
||||
);
|
||||
});
|
||||
|
||||
const handleTaskSelect = (task: Task) => {
|
||||
@@ -85,7 +94,7 @@ export function EditCheckboxModal({
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!text.trim()) return;
|
||||
|
||||
|
||||
try {
|
||||
await onSave(text.trim(), type, taskId, date);
|
||||
onClose();
|
||||
@@ -172,100 +181,104 @@ export function EditCheckboxModal({
|
||||
|
||||
{/* Liaison tâche (pour tous les types) */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-[var(--foreground)] mb-2">
|
||||
Lier à une tâche (optionnel)
|
||||
</label>
|
||||
|
||||
{selectedTask ? (
|
||||
// Tâche déjà sélectionnée
|
||||
<Card className="p-3" background="muted">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium text-sm truncate">{selectedTask.title}</div>
|
||||
{selectedTask.description && (
|
||||
<div className="text-xs text-[var(--muted-foreground)] truncate">
|
||||
{selectedTask.description}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2 mt-1">
|
||||
<StatusBadge status={selectedTask.status} />
|
||||
{selectedTask.tags && selectedTask.tags.length > 0 && (
|
||||
<TagDisplay
|
||||
tags={selectedTask.tags}
|
||||
size="sm"
|
||||
availableTags={selectedTask.tagDetails}
|
||||
maxTags={3}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<label className="block text-sm font-medium text-[var(--foreground)] mb-2">
|
||||
Lier à une tâche (optionnel)
|
||||
</label>
|
||||
|
||||
{selectedTask ? (
|
||||
// Tâche déjà sélectionnée
|
||||
<Card className="p-3" background="muted">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium text-sm truncate">
|
||||
{selectedTask.title}
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => setTaskId(undefined)}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-[var(--destructive)] hover:bg-[var(--destructive)]/10"
|
||||
disabled={saving}
|
||||
>
|
||||
×
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
) : (
|
||||
// Interface de sélection simplifiée
|
||||
<div className="space-y-2">
|
||||
<SearchInput
|
||||
value={taskSearch}
|
||||
onChange={setTaskSearch}
|
||||
placeholder="Rechercher une tâche..."
|
||||
disabled={saving || tasksLoading}
|
||||
className="w-full"
|
||||
/>
|
||||
|
||||
{taskSearch.trim() && (
|
||||
<Card className="max-h-40 overflow-y-auto" shadow="sm">
|
||||
{tasksLoading ? (
|
||||
<div className="p-3 text-center text-sm text-[var(--muted-foreground)]">
|
||||
Chargement...
|
||||
</div>
|
||||
) : filteredTasks.length === 0 ? (
|
||||
<div className="p-3 text-center text-sm text-[var(--muted-foreground)]">
|
||||
Aucune tâche trouvée
|
||||
</div>
|
||||
) : (
|
||||
filteredTasks.slice(0, 5).map((task) => (
|
||||
<button
|
||||
key={task.id}
|
||||
type="button"
|
||||
onClick={() => handleTaskSelect(task)}
|
||||
className="w-full text-left p-3 hover:bg-[var(--muted)]/50 transition-colors border-b border-[var(--border)]/30 last:border-b-0"
|
||||
disabled={saving}
|
||||
>
|
||||
<div className="font-medium text-sm truncate">{task.title}</div>
|
||||
{task.description && (
|
||||
<div className="text-xs text-[var(--muted-foreground)] truncate mt-1 max-w-full overflow-hidden">
|
||||
{task.description}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2 mt-1">
|
||||
<StatusBadge status={task.status} />
|
||||
{task.tags && task.tags.length > 0 && (
|
||||
<TagDisplay
|
||||
tags={task.tags}
|
||||
size="sm"
|
||||
availableTags={task.tagDetails}
|
||||
maxTags={3}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
))
|
||||
{selectedTask.description && (
|
||||
<div className="text-xs text-[var(--muted-foreground)] truncate">
|
||||
{selectedTask.description}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2 mt-1">
|
||||
<StatusBadge status={selectedTask.status} />
|
||||
{selectedTask.tags && selectedTask.tags.length > 0 && (
|
||||
<TagDisplay
|
||||
tags={selectedTask.tags}
|
||||
size="sm"
|
||||
availableTags={selectedTask.tagDetails}
|
||||
maxTags={3}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => setTaskId(undefined)}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-[var(--destructive)] hover:bg-[var(--destructive)]/10"
|
||||
disabled={saving}
|
||||
>
|
||||
×
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
) : (
|
||||
// Interface de sélection simplifiée
|
||||
<div className="space-y-2">
|
||||
<SearchInput
|
||||
value={taskSearch}
|
||||
onChange={setTaskSearch}
|
||||
placeholder="Rechercher une tâche..."
|
||||
disabled={saving || tasksLoading}
|
||||
className="w-full"
|
||||
/>
|
||||
|
||||
{taskSearch.trim() && (
|
||||
<Card className="max-h-40 overflow-y-auto" shadow="sm">
|
||||
{tasksLoading ? (
|
||||
<div className="p-3 text-center text-sm text-[var(--muted-foreground)]">
|
||||
Chargement...
|
||||
</div>
|
||||
) : filteredTasks.length === 0 ? (
|
||||
<div className="p-3 text-center text-sm text-[var(--muted-foreground)]">
|
||||
Aucune tâche trouvée
|
||||
</div>
|
||||
) : (
|
||||
filteredTasks.slice(0, 5).map((task) => (
|
||||
<button
|
||||
key={task.id}
|
||||
type="button"
|
||||
onClick={() => handleTaskSelect(task)}
|
||||
className="w-full text-left p-3 hover:bg-[var(--muted)]/50 transition-colors border-b border-[var(--border)]/30 last:border-b-0"
|
||||
disabled={saving}
|
||||
>
|
||||
<div className="font-medium text-sm truncate">
|
||||
{task.title}
|
||||
</div>
|
||||
{task.description && (
|
||||
<div className="text-xs text-[var(--muted-foreground)] truncate mt-1 max-w-full overflow-hidden">
|
||||
{task.description}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2 mt-1">
|
||||
<StatusBadge status={task.status} />
|
||||
{task.tags && task.tags.length > 0 && (
|
||||
<TagDisplay
|
||||
tags={task.tags}
|
||||
size="sm"
|
||||
availableTags={task.tagDetails}
|
||||
maxTags={3}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex gap-2 justify-end pt-4">
|
||||
|
||||
@@ -18,21 +18,22 @@ interface PendingTasksSectionProps {
|
||||
initialPendingTasks?: DailyCheckbox[]; // Données SSR
|
||||
}
|
||||
|
||||
export function PendingTasksSection({
|
||||
onToggleCheckbox,
|
||||
export function PendingTasksSection({
|
||||
onToggleCheckbox,
|
||||
onDeleteCheckbox,
|
||||
onRefreshDaily,
|
||||
refreshTrigger,
|
||||
initialPendingTasks = []
|
||||
initialPendingTasks = [],
|
||||
}: PendingTasksSectionProps) {
|
||||
const [isCollapsed, setIsCollapsed] = useState(false); // Open by default
|
||||
const [pendingTasks, setPendingTasks] = useState<DailyCheckbox[]>(initialPendingTasks);
|
||||
const [pendingTasks, setPendingTasks] =
|
||||
useState<DailyCheckbox[]>(initialPendingTasks);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [filters, setFilters] = useState({
|
||||
maxDays: 7,
|
||||
type: 'all' as 'all' | DailyCheckboxType,
|
||||
limit: 50
|
||||
limit: 50,
|
||||
});
|
||||
|
||||
// Charger les tâches en attente
|
||||
@@ -43,7 +44,7 @@ export function PendingTasksSection({
|
||||
maxDays: filters.maxDays,
|
||||
excludeToday: true,
|
||||
type: filters.type === 'all' ? undefined : filters.type,
|
||||
limit: filters.limit
|
||||
limit: filters.limit,
|
||||
});
|
||||
setPendingTasks(tasks);
|
||||
} catch (error) {
|
||||
@@ -59,22 +60,33 @@ export function PendingTasksSection({
|
||||
// Si on a des données initiales et qu'on utilise les filtres par défaut, ne pas recharger
|
||||
// SAUF si refreshTrigger a changé (pour recharger après toggle/delete)
|
||||
const hasInitialData = initialPendingTasks.length > 0;
|
||||
const usingDefaultFilters = filters.maxDays === 7 && filters.type === 'all' && filters.limit === 50;
|
||||
|
||||
if (!hasInitialData || !usingDefaultFilters || (refreshTrigger && refreshTrigger > 0)) {
|
||||
const usingDefaultFilters =
|
||||
filters.maxDays === 7 && filters.type === 'all' && filters.limit === 50;
|
||||
|
||||
if (
|
||||
!hasInitialData ||
|
||||
!usingDefaultFilters ||
|
||||
(refreshTrigger && refreshTrigger > 0)
|
||||
) {
|
||||
loadPendingTasks();
|
||||
}
|
||||
}
|
||||
}, [isCollapsed, filters, refreshTrigger, loadPendingTasks, initialPendingTasks.length]);
|
||||
}, [
|
||||
isCollapsed,
|
||||
filters,
|
||||
refreshTrigger,
|
||||
loadPendingTasks,
|
||||
initialPendingTasks.length,
|
||||
]);
|
||||
|
||||
// Gérer l'archivage d'une tâche
|
||||
const handleArchiveTask = async (checkboxId: string) => {
|
||||
try {
|
||||
await dailyClient.archiveCheckbox(checkboxId);
|
||||
// Mise à jour optimiste de l'état local
|
||||
setPendingTasks(prev => prev.filter(task => task.id !== checkboxId));
|
||||
setPendingTasks((prev) => prev.filter((task) => task.id !== checkboxId));
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de l\'archivage:', error);
|
||||
console.error("Erreur lors de l'archivage:", error);
|
||||
// En cas d'erreur, recharger pour être sûr
|
||||
await loadPendingTasks();
|
||||
}
|
||||
@@ -91,7 +103,7 @@ export function PendingTasksSection({
|
||||
try {
|
||||
await onDeleteCheckbox(checkboxId);
|
||||
// Mise à jour optimiste de l'état local
|
||||
setPendingTasks(prev => prev.filter(task => task.id !== checkboxId));
|
||||
setPendingTasks((prev) => prev.filter((task) => task.id !== checkboxId));
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de la suppression:', error);
|
||||
// En cas d'erreur, recharger pour être sûr
|
||||
@@ -103,15 +115,20 @@ export function PendingTasksSection({
|
||||
const handleMoveToToday = (checkboxId: string) => {
|
||||
startTransition(async () => {
|
||||
const result = await moveCheckboxToToday(checkboxId);
|
||||
|
||||
|
||||
if (result.success) {
|
||||
// Mise à jour optimiste de l'état local
|
||||
setPendingTasks(prev => prev.filter(task => task.id !== checkboxId));
|
||||
setPendingTasks((prev) =>
|
||||
prev.filter((task) => task.id !== checkboxId)
|
||||
);
|
||||
if (onRefreshDaily) {
|
||||
await onRefreshDaily(); // Rafraîchir la vue daily principale
|
||||
}
|
||||
} else {
|
||||
console.error('Erreur lors du déplacement vers aujourd\'hui:', result.error);
|
||||
console.error(
|
||||
"Erreur lors du déplacement vers aujourd'hui:",
|
||||
result.error
|
||||
);
|
||||
// En cas d'erreur, recharger pour être sûr
|
||||
await loadPendingTasks();
|
||||
}
|
||||
@@ -142,7 +159,9 @@ export function PendingTasksSection({
|
||||
onClick={() => setIsCollapsed(!isCollapsed)}
|
||||
className="flex items-center gap-2 text-lg font-semibold hover:text-[var(--primary)] transition-colors"
|
||||
>
|
||||
<span className={`transform transition-transform ${isCollapsed ? 'rotate-0' : 'rotate-90'}`}>
|
||||
<span
|
||||
className={`transform transition-transform ${isCollapsed ? 'rotate-0' : 'rotate-90'}`}
|
||||
>
|
||||
▶️
|
||||
</span>
|
||||
📋 Tâches en attente
|
||||
@@ -152,30 +171,40 @@ export function PendingTasksSection({
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
|
||||
{!isCollapsed && (
|
||||
<div className="flex items-center gap-2">
|
||||
{/* Filtres rapides */}
|
||||
<select
|
||||
value={filters.maxDays}
|
||||
onChange={(e) => setFilters(prev => ({ ...prev, maxDays: parseInt(e.target.value) }))}
|
||||
onChange={(e) =>
|
||||
setFilters((prev) => ({
|
||||
...prev,
|
||||
maxDays: parseInt(e.target.value),
|
||||
}))
|
||||
}
|
||||
className="text-xs px-2 py-1 border border-[var(--border)] rounded bg-[var(--background)]"
|
||||
>
|
||||
<option value={7}>7 derniers jours</option>
|
||||
<option value={14}>14 derniers jours</option>
|
||||
<option value={30}>30 derniers jours</option>
|
||||
</select>
|
||||
|
||||
|
||||
<select
|
||||
value={filters.type}
|
||||
onChange={(e) => setFilters(prev => ({ ...prev, type: e.target.value as 'all' | DailyCheckboxType }))}
|
||||
onChange={(e) =>
|
||||
setFilters((prev) => ({
|
||||
...prev,
|
||||
type: e.target.value as 'all' | DailyCheckboxType,
|
||||
}))
|
||||
}
|
||||
className="text-xs px-2 py-1 border border-[var(--border)] rounded bg-[var(--background)]"
|
||||
>
|
||||
<option value="all">Tous types</option>
|
||||
<option value="task">Tâches</option>
|
||||
<option value="meeting">Réunions</option>
|
||||
</select>
|
||||
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
@@ -204,12 +233,14 @@ export function PendingTasksSection({
|
||||
{pendingTasks.map((task) => {
|
||||
const daysAgo = getDaysAgo(task.date);
|
||||
const isArchived = task.text.includes('[ARCHIVÉ]');
|
||||
|
||||
|
||||
return (
|
||||
<div
|
||||
key={task.id}
|
||||
className={`flex items-center gap-3 p-3 rounded-lg border border-[var(--border)] ${
|
||||
isArchived ? 'opacity-60 bg-[var(--muted)]/20' : 'bg-[var(--card)]'
|
||||
isArchived
|
||||
? 'opacity-60 bg-[var(--muted)]/20'
|
||||
: 'bg-[var(--card)]'
|
||||
}`}
|
||||
>
|
||||
{/* Checkbox */}
|
||||
@@ -217,28 +248,34 @@ export function PendingTasksSection({
|
||||
onClick={() => handleToggleTask(task.id)}
|
||||
disabled={isArchived}
|
||||
className={`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${
|
||||
isArchived
|
||||
isArchived
|
||||
? 'border-[var(--muted)] cursor-not-allowed'
|
||||
: 'border-[var(--border)] hover:border-[var(--primary)]'
|
||||
}`}
|
||||
>
|
||||
{task.isChecked && <span className="text-[var(--primary)]">✓</span>}
|
||||
{task.isChecked && (
|
||||
<span className="text-[var(--primary)]">✓</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Contenu */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span>{getTypeIcon(task.type)}</span>
|
||||
<span className={`text-sm font-medium ${isArchived ? 'line-through' : ''}`}>
|
||||
<span
|
||||
className={`text-sm font-medium ${isArchived ? 'line-through' : ''}`}
|
||||
>
|
||||
{task.text}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 text-xs text-[var(--muted-foreground)]">
|
||||
<span>{formatDateShort(task.date)}</span>
|
||||
<span className={getAgeColor(task.date)}>
|
||||
{daysAgo === 0 ? 'Aujourd\'hui' :
|
||||
daysAgo === 1 ? 'Hier' :
|
||||
`Il y a ${daysAgo} jours`}
|
||||
{daysAgo === 0
|
||||
? "Aujourd'hui"
|
||||
: daysAgo === 1
|
||||
? 'Hier'
|
||||
: `Il y a ${daysAgo} jours`}
|
||||
</span>
|
||||
{task.task && (
|
||||
<Link
|
||||
|
||||
@@ -5,41 +5,53 @@ import { StatCard, ProgressBar } from '@/components/ui';
|
||||
import { getDashboardStatColors } from '@/lib/status-config';
|
||||
import { useTasksContext } from '@/contexts/TasksContext';
|
||||
import { useMemo } from 'react';
|
||||
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip, Legend, PieLabelRenderProps } from 'recharts';
|
||||
import {
|
||||
PieChart,
|
||||
Pie,
|
||||
Cell,
|
||||
ResponsiveContainer,
|
||||
Tooltip,
|
||||
Legend,
|
||||
PieLabelRenderProps,
|
||||
} from 'recharts';
|
||||
|
||||
interface DashboardStatsProps {
|
||||
selectedSources?: string[];
|
||||
hiddenSources?: string[];
|
||||
}
|
||||
|
||||
export function DashboardStats({ selectedSources = [], hiddenSources = [] }: DashboardStatsProps) {
|
||||
export function DashboardStats({
|
||||
selectedSources = [],
|
||||
hiddenSources = [],
|
||||
}: DashboardStatsProps) {
|
||||
const { regularTasks } = useTasksContext();
|
||||
|
||||
|
||||
// Calculer les stats filtrées selon les sources
|
||||
const filteredStats = useMemo(() => {
|
||||
let filteredTasks = regularTasks;
|
||||
|
||||
|
||||
// Si on a des sources sélectionnées, ne garder que celles-ci
|
||||
if (selectedSources.length > 0) {
|
||||
filteredTasks = filteredTasks.filter(task =>
|
||||
filteredTasks = filteredTasks.filter((task) =>
|
||||
selectedSources.includes(task.source)
|
||||
);
|
||||
} else if (hiddenSources.length > 0) {
|
||||
// Sinon, retirer les sources masquées
|
||||
filteredTasks = filteredTasks.filter(task =>
|
||||
!hiddenSources.includes(task.source)
|
||||
filteredTasks = filteredTasks.filter(
|
||||
(task) => !hiddenSources.includes(task.source)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
return {
|
||||
total: filteredTasks.length,
|
||||
todo: filteredTasks.filter(t => t.status === 'todo').length,
|
||||
inProgress: filteredTasks.filter(t => t.status === 'in_progress').length,
|
||||
completed: filteredTasks.filter(t => t.status === 'done').length,
|
||||
cancelled: filteredTasks.filter(t => t.status === 'cancelled').length,
|
||||
backlog: filteredTasks.filter(t => t.status === 'backlog').length,
|
||||
freeze: filteredTasks.filter(t => t.status === 'freeze').length,
|
||||
archived: filteredTasks.filter(t => t.status === 'archived').length
|
||||
todo: filteredTasks.filter((t) => t.status === 'todo').length,
|
||||
inProgress: filteredTasks.filter((t) => t.status === 'in_progress')
|
||||
.length,
|
||||
completed: filteredTasks.filter((t) => t.status === 'done').length,
|
||||
cancelled: filteredTasks.filter((t) => t.status === 'cancelled').length,
|
||||
backlog: filteredTasks.filter((t) => t.status === 'backlog').length,
|
||||
freeze: filteredTasks.filter((t) => t.status === 'freeze').length,
|
||||
archived: filteredTasks.filter((t) => t.status === 'archived').length,
|
||||
};
|
||||
}, [regularTasks, selectedSources, hiddenSources]);
|
||||
|
||||
@@ -49,67 +61,67 @@ export function DashboardStats({ selectedSources = [], hiddenSources = [] }: Das
|
||||
if (totalTasks === 0) return [];
|
||||
|
||||
const data = [];
|
||||
|
||||
|
||||
if (filteredStats.backlog > 0) {
|
||||
data.push({
|
||||
status: 'Backlog',
|
||||
count: filteredStats.backlog,
|
||||
percentage: Math.round((filteredStats.backlog / totalTasks) * 100),
|
||||
color: '#6b7280'
|
||||
color: '#6b7280',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
if (filteredStats.todo > 0) {
|
||||
data.push({
|
||||
status: 'À Faire',
|
||||
count: filteredStats.todo,
|
||||
percentage: Math.round((filteredStats.todo / totalTasks) * 100),
|
||||
color: '#eab308'
|
||||
color: '#eab308',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
if (filteredStats.inProgress > 0) {
|
||||
data.push({
|
||||
status: 'En Cours',
|
||||
count: filteredStats.inProgress,
|
||||
percentage: Math.round((filteredStats.inProgress / totalTasks) * 100),
|
||||
color: '#3b82f6'
|
||||
color: '#3b82f6',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
if (filteredStats.freeze > 0) {
|
||||
data.push({
|
||||
status: 'Gelé',
|
||||
count: filteredStats.freeze,
|
||||
percentage: Math.round((filteredStats.freeze / totalTasks) * 100),
|
||||
color: '#8b5cf6'
|
||||
color: '#8b5cf6',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
if (filteredStats.completed > 0) {
|
||||
data.push({
|
||||
status: 'Terminé',
|
||||
count: filteredStats.completed,
|
||||
percentage: Math.round((filteredStats.completed / totalTasks) * 100),
|
||||
color: '#10b981'
|
||||
color: '#10b981',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
if (filteredStats.cancelled > 0) {
|
||||
data.push({
|
||||
status: 'Annulé',
|
||||
count: filteredStats.cancelled,
|
||||
percentage: Math.round((filteredStats.cancelled / totalTasks) * 100),
|
||||
color: '#ef4444'
|
||||
color: '#ef4444',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
if (filteredStats.archived > 0) {
|
||||
data.push({
|
||||
status: 'Archivé',
|
||||
count: filteredStats.archived,
|
||||
percentage: Math.round((filteredStats.archived / totalTasks) * 100),
|
||||
color: '#9ca3af'
|
||||
color: '#9ca3af',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -121,36 +133,42 @@ export function DashboardStats({ selectedSources = [], hiddenSources = [] }: Das
|
||||
const totalTasks = filteredStats.total;
|
||||
if (totalTasks === 0) return [];
|
||||
|
||||
const jiraCount = regularTasks.filter(task => task.source === 'jira').length;
|
||||
const tfsCount = regularTasks.filter(task => task.source === 'tfs').length;
|
||||
const manualCount = regularTasks.filter(task => task.source === 'manual').length;
|
||||
const jiraCount = regularTasks.filter(
|
||||
(task) => task.source === 'jira'
|
||||
).length;
|
||||
const tfsCount = regularTasks.filter(
|
||||
(task) => task.source === 'tfs'
|
||||
).length;
|
||||
const manualCount = regularTasks.filter(
|
||||
(task) => task.source === 'manual'
|
||||
).length;
|
||||
|
||||
const data = [];
|
||||
|
||||
|
||||
if (jiraCount > 0) {
|
||||
data.push({
|
||||
source: 'Jira',
|
||||
count: jiraCount,
|
||||
percentage: Math.round((jiraCount / totalTasks) * 100),
|
||||
color: '#2563eb'
|
||||
color: '#2563eb',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
if (tfsCount > 0) {
|
||||
data.push({
|
||||
source: 'TFS',
|
||||
count: tfsCount,
|
||||
percentage: Math.round((tfsCount / totalTasks) * 100),
|
||||
color: '#7c3aed'
|
||||
color: '#7c3aed',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
if (manualCount > 0) {
|
||||
data.push({
|
||||
source: 'Manuel',
|
||||
count: manualCount,
|
||||
percentage: Math.round((manualCount / totalTasks) * 100),
|
||||
color: '#059669'
|
||||
color: '#059669',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -158,7 +176,15 @@ export function DashboardStats({ selectedSources = [], hiddenSources = [] }: Das
|
||||
}, [filteredStats, regularTasks]);
|
||||
|
||||
// Tooltip personnalisé pour les statuts
|
||||
const StatusTooltip = ({ active, payload }: { active?: boolean; payload?: Array<{ payload: { status: string; count: number; percentage: number } }> }) => {
|
||||
const StatusTooltip = ({
|
||||
active,
|
||||
payload,
|
||||
}: {
|
||||
active?: boolean;
|
||||
payload?: Array<{
|
||||
payload: { status: string; count: number; percentage: number };
|
||||
}>;
|
||||
}) => {
|
||||
if (active && payload && payload.length) {
|
||||
const data = payload[0].payload;
|
||||
return (
|
||||
@@ -174,7 +200,15 @@ export function DashboardStats({ selectedSources = [], hiddenSources = [] }: Das
|
||||
};
|
||||
|
||||
// Tooltip personnalisé pour les sources
|
||||
const SourceTooltip = ({ active, payload }: { active?: boolean; payload?: Array<{ payload: { source: string; count: number; percentage: number } }> }) => {
|
||||
const SourceTooltip = ({
|
||||
active,
|
||||
payload,
|
||||
}: {
|
||||
active?: boolean;
|
||||
payload?: Array<{
|
||||
payload: { source: string; count: number; percentage: number };
|
||||
}>;
|
||||
}) => {
|
||||
if (active && payload && payload.length) {
|
||||
const data = payload[0].payload;
|
||||
return (
|
||||
@@ -190,12 +224,16 @@ export function DashboardStats({ selectedSources = [], hiddenSources = [] }: Das
|
||||
};
|
||||
|
||||
// Légende personnalisée
|
||||
const CustomLegend = ({ payload }: { payload?: Array<{ value: string; color: string }> }) => {
|
||||
const CustomLegend = ({
|
||||
payload,
|
||||
}: {
|
||||
payload?: Array<{ value: string; color: string }>;
|
||||
}) => {
|
||||
return (
|
||||
<div className="flex flex-wrap justify-center gap-4 mt-4">
|
||||
{payload?.map((entry, index: number) => (
|
||||
<div key={index} className="flex items-center gap-2">
|
||||
<div
|
||||
<div
|
||||
className="w-3 h-3 rounded-full"
|
||||
style={{ backgroundColor: entry.color }}
|
||||
></div>
|
||||
@@ -210,39 +248,49 @@ export function DashboardStats({ selectedSources = [], hiddenSources = [] }: Das
|
||||
|
||||
// Label personnalisé pour afficher les pourcentages
|
||||
const renderLabel = (props: PieLabelRenderProps) => {
|
||||
const percentage = typeof props.percent === 'number' ? props.percent * 100 : 0;
|
||||
const percentage =
|
||||
typeof props.percent === 'number' ? props.percent * 100 : 0;
|
||||
return percentage > 5 ? `${Math.round(percentage)}%` : '';
|
||||
};
|
||||
|
||||
|
||||
const totalTasks = filteredStats.total;
|
||||
const completionRate = totalTasks > 0 ? Math.round((filteredStats.completed / totalTasks) * 100) : 0;
|
||||
const inProgressRate = totalTasks > 0 ? Math.round((filteredStats.inProgress / totalTasks) * 100) : 0;
|
||||
const completionRate =
|
||||
totalTasks > 0
|
||||
? Math.round((filteredStats.completed / totalTasks) * 100)
|
||||
: 0;
|
||||
const inProgressRate =
|
||||
totalTasks > 0
|
||||
? Math.round((filteredStats.inProgress / totalTasks) * 100)
|
||||
: 0;
|
||||
|
||||
const statCards = [
|
||||
{
|
||||
title: 'Total Tâches',
|
||||
value: filteredStats.total,
|
||||
icon: '📋',
|
||||
color: 'default' as const
|
||||
color: 'default' as const,
|
||||
},
|
||||
{
|
||||
title: 'À Faire',
|
||||
value: filteredStats.todo + filteredStats.backlog,
|
||||
icon: '⏳',
|
||||
color: 'warning' as const
|
||||
color: 'warning' as const,
|
||||
},
|
||||
{
|
||||
title: 'En Cours',
|
||||
value: filteredStats.inProgress + filteredStats.freeze,
|
||||
icon: '🔄',
|
||||
color: 'primary' as const
|
||||
color: 'primary' as const,
|
||||
},
|
||||
{
|
||||
title: 'Terminées',
|
||||
value: filteredStats.completed + filteredStats.cancelled + filteredStats.archived,
|
||||
value:
|
||||
filteredStats.completed +
|
||||
filteredStats.cancelled +
|
||||
filteredStats.archived,
|
||||
icon: '✅',
|
||||
color: 'success' as const
|
||||
}
|
||||
color: 'success' as const,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
@@ -256,9 +304,12 @@ export function DashboardStats({ selectedSources = [], hiddenSources = [] }: Das
|
||||
color={stat.color}
|
||||
/>
|
||||
))}
|
||||
|
||||
|
||||
{/* Cartes de pourcentage */}
|
||||
<Card variant="glass" className="p-6 hover:shadow-lg transition-shadow md:col-span-1 lg:col-span-1">
|
||||
<Card
|
||||
variant="glass"
|
||||
className="p-6 hover:shadow-lg transition-shadow md:col-span-1 lg:col-span-1"
|
||||
>
|
||||
<h3 className="text-lg font-semibold mb-4">Taux de Completion</h3>
|
||||
<div className="space-y-4">
|
||||
<ProgressBar
|
||||
@@ -266,7 +317,7 @@ export function DashboardStats({ selectedSources = [], hiddenSources = [] }: Das
|
||||
label="Terminées"
|
||||
color="success"
|
||||
/>
|
||||
|
||||
|
||||
<ProgressBar
|
||||
value={inProgressRate}
|
||||
label="En Cours"
|
||||
@@ -274,11 +325,14 @@ export function DashboardStats({ selectedSources = [], hiddenSources = [] }: Das
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
|
||||
{/* Distribution détaillée par statut */}
|
||||
<Card variant="glass" className="p-6 hover:shadow-lg transition-shadow md:col-span-1 lg:col-span-1">
|
||||
<Card
|
||||
variant="glass"
|
||||
className="p-6 hover:shadow-lg transition-shadow md:col-span-1 lg:col-span-1"
|
||||
>
|
||||
<h3 className="text-lg font-semibold mb-4">Distribution par Statut</h3>
|
||||
|
||||
|
||||
{/* Graphique en camembert avec Recharts */}
|
||||
<div className="h-64">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
@@ -295,10 +349,7 @@ export function DashboardStats({ selectedSources = [], hiddenSources = [] }: Das
|
||||
nameKey="status"
|
||||
>
|
||||
{statusChartData.map((entry, index) => (
|
||||
<Cell
|
||||
key={`cell-${index}`}
|
||||
fill={entry.color}
|
||||
/>
|
||||
<Cell key={`cell-${index}`} fill={entry.color} />
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip content={<StatusTooltip />} />
|
||||
@@ -307,25 +358,34 @@ export function DashboardStats({ selectedSources = [], hiddenSources = [] }: Das
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
|
||||
{/* Insights rapides */}
|
||||
<Card variant="glass" className="p-6 hover:shadow-lg transition-shadow md:col-span-1 lg:col-span-1">
|
||||
<Card
|
||||
variant="glass"
|
||||
className="p-6 hover:shadow-lg transition-shadow md:col-span-1 lg:col-span-1"
|
||||
>
|
||||
<h3 className="text-lg font-semibold mb-4">Aperçu Rapide</h3>
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={`w-2 h-2 rounded-full ${getDashboardStatColors('completed').dotColor}`}></span>
|
||||
<span
|
||||
className={`w-2 h-2 rounded-full ${getDashboardStatColors('completed').dotColor}`}
|
||||
></span>
|
||||
<span className="text-sm">
|
||||
{filteredStats.completed} tâches terminées sur {totalTasks}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={`w-2 h-2 rounded-full ${getDashboardStatColors('inProgress').dotColor}`}></span>
|
||||
<span
|
||||
className={`w-2 h-2 rounded-full ${getDashboardStatColors('inProgress').dotColor}`}
|
||||
></span>
|
||||
<span className="text-sm">
|
||||
{filteredStats.inProgress} tâches en cours de traitement
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={`w-2 h-2 rounded-full ${getDashboardStatColors('todo').dotColor}`}></span>
|
||||
<span
|
||||
className={`w-2 h-2 rounded-full ${getDashboardStatColors('todo').dotColor}`}
|
||||
></span>
|
||||
<span className="text-sm">
|
||||
{filteredStats.todo} tâches en attente
|
||||
</span>
|
||||
@@ -339,11 +399,14 @@ export function DashboardStats({ selectedSources = [], hiddenSources = [] }: Das
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
|
||||
{/* Distribution par sources */}
|
||||
<Card variant="glass" className="p-6 hover:shadow-lg transition-shadow md:col-span-1 lg:col-span-1">
|
||||
<Card
|
||||
variant="glass"
|
||||
className="p-6 hover:shadow-lg transition-shadow md:col-span-1 lg:col-span-1"
|
||||
>
|
||||
<h3 className="text-lg font-semibold mb-4">Distribution par Sources</h3>
|
||||
|
||||
|
||||
{/* Graphique en camembert avec Recharts */}
|
||||
<div className="h-64">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
@@ -360,10 +423,7 @@ export function DashboardStats({ selectedSources = [], hiddenSources = [] }: Das
|
||||
nameKey="source"
|
||||
>
|
||||
{sourceChartData.map((entry, index) => (
|
||||
<Cell
|
||||
key={`cell-${index}`}
|
||||
fill={entry.color}
|
||||
/>
|
||||
<Cell key={`cell-${index}`} fill={entry.color} />
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip content={<SourceTooltip />} />
|
||||
|
||||
@@ -10,13 +10,13 @@ interface IntegrationFilterProps {
|
||||
// Interface pour Kanban (nouvelle)
|
||||
filters?: KanbanFilters;
|
||||
onFiltersChange?: (filters: KanbanFilters) => void;
|
||||
|
||||
|
||||
// Interface pour Dashboard (ancienne)
|
||||
selectedSources?: string[];
|
||||
onSourcesChange?: (sources: string[]) => void;
|
||||
hiddenSources?: string[];
|
||||
onHiddenSourcesChange?: (sources: string[]) => void;
|
||||
|
||||
|
||||
// Alignement du dropdown
|
||||
alignRight?: boolean;
|
||||
}
|
||||
@@ -30,14 +30,14 @@ interface SourceOption {
|
||||
|
||||
type FilterMode = 'all' | 'show' | 'hide';
|
||||
|
||||
export function IntegrationFilter({
|
||||
filters,
|
||||
onFiltersChange,
|
||||
selectedSources,
|
||||
onSourcesChange,
|
||||
hiddenSources,
|
||||
export function IntegrationFilter({
|
||||
filters,
|
||||
onFiltersChange,
|
||||
selectedSources,
|
||||
onSourcesChange,
|
||||
hiddenSources,
|
||||
onHiddenSourcesChange,
|
||||
alignRight = false
|
||||
alignRight = false,
|
||||
}: IntegrationFilterProps) {
|
||||
const { regularTasks, pinnedTasks } = useTasksContext();
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
@@ -45,31 +45,30 @@ export function IntegrationFilter({
|
||||
// Vérifier quelles sources ont des tâches (regularTasks + pinnedTasks)
|
||||
const sources = useMemo((): SourceOption[] => {
|
||||
const allTasks = [...regularTasks, ...pinnedTasks];
|
||||
const hasJiraTasks = allTasks.some(task => task.source === 'jira');
|
||||
const hasTfsTasks = allTasks.some(task => task.source === 'tfs');
|
||||
const hasManualTasks = allTasks.some(task => task.source === 'manual');
|
||||
|
||||
const hasJiraTasks = allTasks.some((task) => task.source === 'jira');
|
||||
const hasTfsTasks = allTasks.some((task) => task.source === 'tfs');
|
||||
const hasManualTasks = allTasks.some((task) => task.source === 'manual');
|
||||
|
||||
return [
|
||||
{
|
||||
id: 'jira' as const,
|
||||
label: 'Jira',
|
||||
icon: <Circle size={14} />,
|
||||
hasTasks: hasJiraTasks
|
||||
hasTasks: hasJiraTasks,
|
||||
},
|
||||
{
|
||||
id: 'tfs' as const,
|
||||
label: 'TFS',
|
||||
icon: <Square size={14} />,
|
||||
hasTasks: hasTfsTasks
|
||||
hasTasks: hasTfsTasks,
|
||||
},
|
||||
{
|
||||
id: 'manual' as const,
|
||||
label: 'Manuel',
|
||||
icon: <Hand size={14} />,
|
||||
hasTasks: hasManualTasks
|
||||
}
|
||||
].filter(source => source.hasTasks);
|
||||
hasTasks: hasManualTasks,
|
||||
},
|
||||
].filter((source) => source.hasTasks);
|
||||
}, [regularTasks, pinnedTasks]);
|
||||
|
||||
// Si aucune source disponible, on n'affiche rien
|
||||
@@ -77,20 +76,36 @@ export function IntegrationFilter({
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
// Déterminer le mode d'utilisation (Kanban ou Dashboard)
|
||||
const isKanbanMode = filters && onFiltersChange;
|
||||
const isDashboardMode = selectedSources && onSourcesChange && hiddenSources && onHiddenSourcesChange;
|
||||
const isDashboardMode =
|
||||
selectedSources &&
|
||||
onSourcesChange &&
|
||||
hiddenSources &&
|
||||
onHiddenSourcesChange;
|
||||
|
||||
// Déterminer l'état actuel de chaque source
|
||||
const getSourceMode = (sourceId: 'jira' | 'tfs' | 'manual'): FilterMode => {
|
||||
if (isKanbanMode && filters) {
|
||||
if (sourceId === 'jira') {
|
||||
return filters.showJiraOnly ? 'show' : filters.hideJiraTasks ? 'hide' : 'all';
|
||||
return filters.showJiraOnly
|
||||
? 'show'
|
||||
: filters.hideJiraTasks
|
||||
? 'hide'
|
||||
: 'all';
|
||||
} else if (sourceId === 'tfs') {
|
||||
return filters.showTfsOnly ? 'show' : filters.hideTfsTasks ? 'hide' : 'all';
|
||||
} else { // manual
|
||||
return filters.showManualOnly ? 'show' : filters.hideManualTasks ? 'hide' : 'all';
|
||||
return filters.showTfsOnly
|
||||
? 'show'
|
||||
: filters.hideTfsTasks
|
||||
? 'hide'
|
||||
: 'all';
|
||||
} else {
|
||||
// manual
|
||||
return filters.showManualOnly
|
||||
? 'show'
|
||||
: filters.hideManualTasks
|
||||
? 'hide'
|
||||
: 'all';
|
||||
}
|
||||
} else if (isDashboardMode && selectedSources && hiddenSources) {
|
||||
if (selectedSources.includes(sourceId)) {
|
||||
@@ -104,10 +119,13 @@ export function IntegrationFilter({
|
||||
return 'all';
|
||||
};
|
||||
|
||||
const handleModeChange = (sourceId: 'jira' | 'tfs' | 'manual', mode: FilterMode) => {
|
||||
const handleModeChange = (
|
||||
sourceId: 'jira' | 'tfs' | 'manual',
|
||||
mode: FilterMode
|
||||
) => {
|
||||
if (isKanbanMode && filters && onFiltersChange) {
|
||||
const updates: Partial<KanbanFilters> = {};
|
||||
|
||||
|
||||
if (sourceId === 'jira') {
|
||||
updates.showJiraOnly = mode === 'show';
|
||||
updates.hideJiraTasks = mode === 'hide';
|
||||
@@ -118,39 +136,45 @@ export function IntegrationFilter({
|
||||
updates.showManualOnly = mode === 'show';
|
||||
updates.hideManualTasks = mode === 'hide';
|
||||
}
|
||||
|
||||
|
||||
onFiltersChange({ ...filters, ...updates });
|
||||
} else if (isDashboardMode && onSourcesChange && onHiddenSourcesChange && selectedSources && hiddenSources) {
|
||||
} else if (
|
||||
isDashboardMode &&
|
||||
onSourcesChange &&
|
||||
onHiddenSourcesChange &&
|
||||
selectedSources &&
|
||||
hiddenSources
|
||||
) {
|
||||
let newSelectedSources = [...selectedSources];
|
||||
let newHiddenSources = [...hiddenSources];
|
||||
|
||||
|
||||
if (mode === 'show') {
|
||||
// Ajouter à selectedSources et retirer de hiddenSources
|
||||
if (!newSelectedSources.includes(sourceId)) {
|
||||
newSelectedSources.push(sourceId);
|
||||
}
|
||||
newHiddenSources = newHiddenSources.filter(id => id !== sourceId);
|
||||
newHiddenSources = newHiddenSources.filter((id) => id !== sourceId);
|
||||
} else if (mode === 'hide') {
|
||||
// Ajouter à hiddenSources et retirer de selectedSources
|
||||
if (!newHiddenSources.includes(sourceId)) {
|
||||
newHiddenSources.push(sourceId);
|
||||
}
|
||||
newSelectedSources = newSelectedSources.filter(id => id !== sourceId);
|
||||
} else { // 'all'
|
||||
newSelectedSources = newSelectedSources.filter((id) => id !== sourceId);
|
||||
} else {
|
||||
// 'all'
|
||||
// Retirer des deux listes
|
||||
newSelectedSources = newSelectedSources.filter(id => id !== sourceId);
|
||||
newHiddenSources = newHiddenSources.filter(id => id !== sourceId);
|
||||
newSelectedSources = newSelectedSources.filter((id) => id !== sourceId);
|
||||
newHiddenSources = newHiddenSources.filter((id) => id !== sourceId);
|
||||
}
|
||||
|
||||
|
||||
onHiddenSourcesChange(newHiddenSources);
|
||||
onSourcesChange(newSelectedSources);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// Déterminer la variante du bouton principal
|
||||
const getMainButtonVariant = () => {
|
||||
const activeFilters = sources.filter(source => {
|
||||
const activeFilters = sources.filter((source) => {
|
||||
const mode = getSourceMode(source.id);
|
||||
return mode !== 'all';
|
||||
});
|
||||
@@ -159,7 +183,7 @@ export function IntegrationFilter({
|
||||
};
|
||||
|
||||
const getMainButtonText = () => {
|
||||
const activeFilters = sources.filter(source => {
|
||||
const activeFilters = sources.filter((source) => {
|
||||
const mode = getSourceMode(source.id);
|
||||
return mode !== 'all';
|
||||
});
|
||||
@@ -179,7 +203,7 @@ export function IntegrationFilter({
|
||||
<div className="space-y-3">
|
||||
{sources.map((source) => {
|
||||
const currentMode = getSourceMode(source.id);
|
||||
|
||||
|
||||
return (
|
||||
<div key={source.id} className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
@@ -187,7 +211,7 @@ export function IntegrationFilter({
|
||||
<span>{source.icon}</span>
|
||||
<span>{source.label}</span>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
{/* Bouton Afficher */}
|
||||
<button
|
||||
@@ -199,14 +223,14 @@ export function IntegrationFilter({
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
className={`px-2 py-1 text-xs rounded transition-colors cursor-pointer ${
|
||||
currentMode === 'show'
|
||||
? 'bg-[var(--primary)] text-[var(--primary-foreground)]'
|
||||
? 'bg-[var(--primary)] text-[var(--primary-foreground)]'
|
||||
: 'bg-[var(--muted)] text-[var(--muted-foreground)] hover:bg-[var(--primary)]/20'
|
||||
}`}
|
||||
title="Afficher seulement cette source"
|
||||
>
|
||||
✓
|
||||
</button>
|
||||
|
||||
|
||||
{/* Bouton Masquer */}
|
||||
<button
|
||||
onClick={(e) => {
|
||||
@@ -217,7 +241,7 @@ export function IntegrationFilter({
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
className={`px-2 py-1 text-xs rounded transition-colors cursor-pointer ${
|
||||
currentMode === 'hide'
|
||||
? 'bg-[var(--destructive)] text-white'
|
||||
? 'bg-[var(--destructive)] text-white'
|
||||
: 'bg-[var(--muted)] text-[var(--muted-foreground)] hover:bg-[var(--destructive)]/20'
|
||||
}`}
|
||||
title="Masquer cette source"
|
||||
@@ -229,7 +253,7 @@ export function IntegrationFilter({
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
|
||||
{/* Option pour réinitialiser tous les filtres */}
|
||||
<div className="border-t border-[var(--border)] pt-2 mt-2">
|
||||
<Button
|
||||
@@ -243,10 +267,14 @@ export function IntegrationFilter({
|
||||
showTfsOnly: false,
|
||||
hideTfsTasks: false,
|
||||
showManualOnly: false,
|
||||
hideManualTasks: false
|
||||
hideManualTasks: false,
|
||||
};
|
||||
onFiltersChange({ ...filters, ...updates });
|
||||
} else if (isDashboardMode && onHiddenSourcesChange && onSourcesChange) {
|
||||
} else if (
|
||||
isDashboardMode &&
|
||||
onHiddenSourcesChange &&
|
||||
onSourcesChange
|
||||
) {
|
||||
onHiddenSourcesChange([]);
|
||||
onSourcesChange([]);
|
||||
}
|
||||
@@ -273,8 +301,8 @@ export function IntegrationFilter({
|
||||
}
|
||||
variant={getMainButtonVariant()}
|
||||
content={dropdownContent}
|
||||
placement={alignRight ? "bottom-end" : "bottom-start"}
|
||||
className={`min-w-[239px] max-h-[190px] overflow-y-auto ${alignRight ? "transform -translate-x-full" : ""}`}
|
||||
placement={alignRight ? 'bottom-end' : 'bottom-start'}
|
||||
className={`min-w-[239px] max-h-[190px] overflow-y-auto ${alignRight ? 'transform -translate-x-full' : ''}`}
|
||||
triggerClassName="h-[33px] py-1 max-w-[140px] truncate"
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -18,13 +18,19 @@ interface ManagerWeeklySummaryProps {
|
||||
initialSummary: ManagerSummary;
|
||||
}
|
||||
|
||||
export default function ManagerWeeklySummary({ initialSummary }: ManagerWeeklySummaryProps) {
|
||||
export default function ManagerWeeklySummary({
|
||||
initialSummary,
|
||||
}: ManagerWeeklySummaryProps) {
|
||||
const [summary] = useState<ManagerSummary>(initialSummary);
|
||||
const [activeView, setActiveView] = useState<'narrative' | 'accomplishments' | 'challenges' | 'metrics'>('narrative');
|
||||
const [activeView, setActiveView] = useState<
|
||||
'narrative' | 'accomplishments' | 'challenges' | 'metrics'
|
||||
>('narrative');
|
||||
const { tags: availableTags } = useTasksContext();
|
||||
|
||||
const handleTabChange = (tabId: string) => {
|
||||
setActiveView(tabId as 'narrative' | 'accomplishments' | 'challenges' | 'metrics');
|
||||
setActiveView(
|
||||
tabId as 'narrative' | 'accomplishments' | 'challenges' | 'metrics'
|
||||
);
|
||||
};
|
||||
|
||||
const handleRefresh = () => {
|
||||
@@ -32,7 +38,6 @@ export default function ManagerWeeklySummary({ initialSummary }: ManagerWeeklySu
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
|
||||
const formatPeriod = () => {
|
||||
return `7 derniers jours (${format(summary.period.start, 'dd MMM', { locale: fr })} - ${format(summary.period.end, 'dd MMM yyyy', { locale: fr })})`;
|
||||
};
|
||||
@@ -40,33 +45,41 @@ export default function ManagerWeeklySummary({ initialSummary }: ManagerWeeklySu
|
||||
// Configuration des onglets
|
||||
const tabItems: TabItem[] = [
|
||||
{ id: 'narrative', label: 'Vue Executive', icon: '📝' },
|
||||
{ id: 'accomplishments', label: 'Accomplissements', icon: '✅', count: summary.keyAccomplishments.length },
|
||||
{ id: 'challenges', label: 'Enjeux à venir', icon: '🎯', count: summary.upcomingChallenges.length },
|
||||
{ id: 'metrics', label: 'Métriques', icon: '📊' }
|
||||
{
|
||||
id: 'accomplishments',
|
||||
label: 'Accomplissements',
|
||||
icon: '✅',
|
||||
count: summary.keyAccomplishments.length,
|
||||
},
|
||||
{
|
||||
id: 'challenges',
|
||||
label: 'Enjeux à venir',
|
||||
icon: '🎯',
|
||||
count: summary.upcomingChallenges.length,
|
||||
},
|
||||
{ id: 'metrics', label: 'Métriques', icon: '📊' },
|
||||
];
|
||||
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header avec navigation */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-[var(--foreground)]"><Emoji emoji="👔" /> Weekly</h1>
|
||||
<h1 className="text-2xl font-bold text-[var(--foreground)]">
|
||||
<Emoji emoji="👔" /> Weekly
|
||||
</h1>
|
||||
<p className="text-[var(--muted-foreground)]">{formatPeriod()}</p>
|
||||
</div>
|
||||
{activeView !== 'metrics' && (
|
||||
<Button
|
||||
onClick={handleRefresh}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
>
|
||||
<Emoji emoji="🔄" /> Actualiser
|
||||
<Button onClick={handleRefresh} variant="secondary" size="sm">
|
||||
<Emoji emoji="🔄" />
|
||||
Actualiser
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Navigation des vues */}
|
||||
<Tabs
|
||||
<Tabs
|
||||
items={tabItems}
|
||||
activeTab={activeView}
|
||||
onTabChange={handleTabChange}
|
||||
@@ -86,18 +99,30 @@ export default function ManagerWeeklySummary({ initialSummary }: ManagerWeeklySu
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="outline-card-blue p-4">
|
||||
<h3 className="font-medium mb-2"><Emoji emoji="🎯" /> Points clés accomplis</h3>
|
||||
<p className="text-sm text-[var(--muted-foreground)]">{summary.narrative.weekHighlight}</p>
|
||||
<h3 className="font-medium mb-2">
|
||||
<Emoji emoji="🎯" /> Points clés accomplis
|
||||
</h3>
|
||||
<p className="text-sm text-[var(--muted-foreground)]">
|
||||
{summary.narrative.weekHighlight}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="outline-card-orange p-4">
|
||||
<h3 className="font-medium mb-2"><Emoji emoji="⚡" /> Défis traités</h3>
|
||||
<p className="text-sm text-[var(--muted-foreground)]">{summary.narrative.mainChallenges}</p>
|
||||
<h3 className="font-medium mb-2">
|
||||
<Emoji emoji="⚡" /> Défis traités
|
||||
</h3>
|
||||
<p className="text-sm text-[var(--muted-foreground)]">
|
||||
{summary.narrative.mainChallenges}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="outline-card-green p-4">
|
||||
<h3 className="font-medium mb-2"><Emoji emoji="🔮" /> Focus 7 prochains jours</h3>
|
||||
<p className="text-sm text-[var(--muted-foreground)]">{summary.narrative.nextWeekFocus}</p>
|
||||
<h3 className="font-medium mb-2">
|
||||
<Emoji emoji="🔮" /> Focus 7 prochains jours
|
||||
</h3>
|
||||
<p className="text-sm text-[var(--muted-foreground)]">
|
||||
{summary.narrative.nextWeekFocus}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -105,32 +130,67 @@ export default function ManagerWeeklySummary({ initialSummary }: ManagerWeeklySu
|
||||
{/* Métriques rapides */}
|
||||
<Card variant="elevated">
|
||||
<CardHeader>
|
||||
<h2 className="text-lg font-semibold"><Emoji emoji="📈" /> Métriques en bref</h2>
|
||||
<h2 className="text-lg font-semibold">
|
||||
<Emoji emoji="📈" /> Métriques en bref
|
||||
</h2>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="outline-metric-blue">
|
||||
<div className="text-2xl font-bold mb-1">{summary.metrics.totalTasksCompleted}</div>
|
||||
<div className="text-xs font-medium mb-1">Tâches complétées</div>
|
||||
<div className="text-xs text-[var(--muted-foreground)]">dont {summary.metrics.highPriorityTasksCompleted} priorité haute</div>
|
||||
<div className="text-2xl font-bold mb-1">
|
||||
{summary.metrics.totalTasksCompleted}
|
||||
</div>
|
||||
<div className="text-xs font-medium mb-1">
|
||||
Tâches complétées
|
||||
</div>
|
||||
<div className="text-xs text-[var(--muted-foreground)]">
|
||||
dont {summary.metrics.highPriorityTasksCompleted} priorité
|
||||
haute
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="outline-metric-green">
|
||||
<div className="text-2xl font-bold mb-1">{summary.metrics.totalCheckboxesCompleted}</div>
|
||||
<div className="text-xs font-medium mb-1">Todos complétés</div>
|
||||
<div className="text-xs text-[var(--muted-foreground)]">dont {summary.metrics.meetingCheckboxesCompleted} meetings</div>
|
||||
<div className="text-2xl font-bold mb-1">
|
||||
{summary.metrics.totalCheckboxesCompleted}
|
||||
</div>
|
||||
<div className="text-xs font-medium mb-1">
|
||||
Todos complétés
|
||||
</div>
|
||||
<div className="text-xs text-[var(--muted-foreground)]">
|
||||
dont {summary.metrics.meetingCheckboxesCompleted} meetings
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="outline-metric-orange">
|
||||
<div className="text-2xl font-bold mb-1">{summary.keyAccomplishments.filter(a => a.impact === 'high').length}</div>
|
||||
<div className="text-xs font-medium mb-1">Items à fort impact</div>
|
||||
<div className="text-xs text-[var(--muted-foreground)]">/ {summary.keyAccomplishments.length} accomplissements</div>
|
||||
<div className="text-2xl font-bold mb-1">
|
||||
{
|
||||
summary.keyAccomplishments.filter(
|
||||
(a) => a.impact === 'high'
|
||||
).length
|
||||
}
|
||||
</div>
|
||||
<div className="text-xs font-medium mb-1">
|
||||
Items à fort impact
|
||||
</div>
|
||||
<div className="text-xs text-[var(--muted-foreground)]">
|
||||
/ {summary.keyAccomplishments.length} accomplissements
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="outline-metric-gray">
|
||||
<div className="text-2xl font-bold mb-1">{summary.upcomingChallenges.filter(c => c.priority === 'high').length}</div>
|
||||
<div className="text-xs font-medium mb-1">Priorités critiques</div>
|
||||
<div className="text-xs text-[var(--muted-foreground)]">/ {summary.upcomingChallenges.length} enjeux</div>
|
||||
<div className="text-2xl font-bold mb-1">
|
||||
{
|
||||
summary.upcomingChallenges.filter(
|
||||
(c) => c.priority === 'high'
|
||||
).length
|
||||
}
|
||||
</div>
|
||||
<div className="text-xs font-medium mb-1">
|
||||
Priorités critiques
|
||||
</div>
|
||||
<div className="text-xs text-[var(--muted-foreground)]">
|
||||
/ {summary.upcomingChallenges.length} enjeux
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
@@ -139,11 +199,18 @@ export default function ManagerWeeklySummary({ initialSummary }: ManagerWeeklySu
|
||||
|
||||
{/* Top accomplissements */}
|
||||
<Card variant="elevated">
|
||||
<CardHeader className="pb-4" style={{
|
||||
borderBottom: '1px solid',
|
||||
borderBottomColor: 'color-mix(in srgb, var(--success) 10%, var(--border))'
|
||||
}}>
|
||||
<h2 className="text-lg font-semibold flex items-center gap-2" style={{ color: 'var(--success)' }}>
|
||||
<CardHeader
|
||||
className="pb-4"
|
||||
style={{
|
||||
borderBottom: '1px solid',
|
||||
borderBottomColor:
|
||||
'color-mix(in srgb, var(--success) 10%, var(--border))',
|
||||
}}
|
||||
>
|
||||
<h2
|
||||
className="text-lg font-semibold flex items-center gap-2"
|
||||
style={{ color: 'var(--success)' }}
|
||||
>
|
||||
<Emoji emoji="🏆" /> Top accomplissements
|
||||
</h2>
|
||||
</CardHeader>
|
||||
@@ -151,20 +218,29 @@ export default function ManagerWeeklySummary({ initialSummary }: ManagerWeeklySu
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{summary.keyAccomplishments.length === 0 ? (
|
||||
<div className="col-span-3 text-center py-8 text-[var(--muted-foreground)]">
|
||||
<p>Aucun accomplissement significatif trouvé cette semaine.</p>
|
||||
<p className="text-sm mt-2">Ajoutez des tâches avec priorité haute/medium ou des meetings.</p>
|
||||
<p>
|
||||
Aucun accomplissement significatif trouvé cette semaine.
|
||||
</p>
|
||||
<p className="text-sm mt-2">
|
||||
Ajoutez des tâches avec priorité haute/medium ou des
|
||||
meetings.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
summary.keyAccomplishments.slice(0, 6).map((accomplishment, index) => (
|
||||
<AchievementCard
|
||||
key={accomplishment.id}
|
||||
achievement={accomplishment}
|
||||
availableTags={availableTags as (Tag & { usage: number })[]}
|
||||
index={index}
|
||||
showDescription={true}
|
||||
maxTags={2}
|
||||
/>
|
||||
))
|
||||
summary.keyAccomplishments
|
||||
.slice(0, 6)
|
||||
.map((accomplishment, index) => (
|
||||
<AchievementCard
|
||||
key={accomplishment.id}
|
||||
achievement={accomplishment}
|
||||
availableTags={
|
||||
availableTags as (Tag & { usage: number })[]
|
||||
}
|
||||
index={index}
|
||||
showDescription={true}
|
||||
maxTags={2}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
@@ -172,11 +248,18 @@ export default function ManagerWeeklySummary({ initialSummary }: ManagerWeeklySu
|
||||
|
||||
{/* Top challenges */}
|
||||
<Card variant="elevated">
|
||||
<CardHeader className="pb-4" style={{
|
||||
borderBottom: '1px solid',
|
||||
borderBottomColor: 'color-mix(in srgb, var(--destructive) 10%, var(--border))'
|
||||
}}>
|
||||
<h2 className="text-lg font-semibold flex items-center gap-2" style={{ color: 'var(--destructive)' }}>
|
||||
<CardHeader
|
||||
className="pb-4"
|
||||
style={{
|
||||
borderBottom: '1px solid',
|
||||
borderBottomColor:
|
||||
'color-mix(in srgb, var(--destructive) 10%, var(--border))',
|
||||
}}
|
||||
>
|
||||
<h2
|
||||
className="text-lg font-semibold flex items-center gap-2"
|
||||
style={{ color: 'var(--destructive)' }}
|
||||
>
|
||||
<Emoji emoji="🎯" /> Top enjeux à venir
|
||||
</h2>
|
||||
</CardHeader>
|
||||
@@ -185,19 +268,26 @@ export default function ManagerWeeklySummary({ initialSummary }: ManagerWeeklySu
|
||||
{summary.upcomingChallenges.length === 0 ? (
|
||||
<div className="col-span-3 text-center py-8 text-[var(--muted-foreground)]">
|
||||
<p>Aucun enjeu prioritaire trouvé.</p>
|
||||
<p className="text-sm mt-2">Ajoutez des tâches non complétées avec priorité haute/medium.</p>
|
||||
<p className="text-sm mt-2">
|
||||
Ajoutez des tâches non complétées avec priorité
|
||||
haute/medium.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
summary.upcomingChallenges.slice(0, 6).map((challenge, index) => (
|
||||
<ChallengeCard
|
||||
key={challenge.id}
|
||||
challenge={challenge}
|
||||
availableTags={availableTags as (Tag & { usage: number })[]}
|
||||
index={index}
|
||||
showDescription={true}
|
||||
maxTags={2}
|
||||
/>
|
||||
))
|
||||
summary.upcomingChallenges
|
||||
.slice(0, 6)
|
||||
.map((challenge, index) => (
|
||||
<ChallengeCard
|
||||
key={challenge.id}
|
||||
challenge={challenge}
|
||||
availableTags={
|
||||
availableTags as (Tag & { usage: number })[]
|
||||
}
|
||||
index={index}
|
||||
showDescription={true}
|
||||
maxTags={2}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
@@ -209,21 +299,36 @@ export default function ManagerWeeklySummary({ initialSummary }: ManagerWeeklySu
|
||||
{activeView === 'accomplishments' && (
|
||||
<Card variant="elevated">
|
||||
<CardHeader>
|
||||
<h2 className="text-lg font-semibold"><Emoji emoji="✅" /> Accomplissements des 7 derniers jours</h2>
|
||||
<h2 className="text-lg font-semibold">
|
||||
<Emoji emoji="✅" /> Accomplissements des 7 derniers jours
|
||||
</h2>
|
||||
<p className="text-sm text-[var(--muted-foreground)]">
|
||||
{summary.keyAccomplishments.length} accomplissements significatifs • {summary.metrics.totalTasksCompleted} tâches • {summary.metrics.totalCheckboxesCompleted} todos complétés
|
||||
{summary.keyAccomplishments.length} accomplissements significatifs
|
||||
• {summary.metrics.totalTasksCompleted} tâches •{' '}
|
||||
{summary.metrics.totalCheckboxesCompleted} todos complétés
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{summary.keyAccomplishments.length === 0 ? (
|
||||
<div className="p-8 text-center rounded-xl border-2" style={{
|
||||
backgroundColor: 'color-mix(in srgb, var(--muted) 15%, transparent)',
|
||||
borderColor: 'color-mix(in srgb, var(--muted) 40%, var(--border))',
|
||||
color: 'var(--muted-foreground)'
|
||||
}}>
|
||||
<div className="text-4xl mb-4"><Emoji emoji="📭" /></div>
|
||||
<p className="text-lg mb-2">Aucun accomplissement significatif trouvé cette semaine.</p>
|
||||
<p className="text-sm">Ajoutez des tâches avec priorité haute/medium ou des meetings.</p>
|
||||
<div
|
||||
className="p-8 text-center rounded-xl border-2"
|
||||
style={{
|
||||
backgroundColor:
|
||||
'color-mix(in srgb, var(--muted) 15%, transparent)',
|
||||
borderColor:
|
||||
'color-mix(in srgb, var(--muted) 40%, var(--border))',
|
||||
color: 'var(--muted-foreground)',
|
||||
}}
|
||||
>
|
||||
<div className="text-4xl mb-4">
|
||||
<Emoji emoji="📭" />
|
||||
</div>
|
||||
<p className="text-lg mb-2">
|
||||
Aucun accomplissement significatif trouvé cette semaine.
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Ajoutez des tâches avec priorité haute/medium ou des meetings.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
@@ -247,21 +352,42 @@ export default function ManagerWeeklySummary({ initialSummary }: ManagerWeeklySu
|
||||
{activeView === 'challenges' && (
|
||||
<Card variant="elevated">
|
||||
<CardHeader>
|
||||
<h2 className="text-lg font-semibold"><Emoji emoji="🎯" /> Enjeux et défis à venir</h2>
|
||||
<h2 className="text-lg font-semibold">
|
||||
<Emoji emoji="🎯" /> Enjeux et défis à venir
|
||||
</h2>
|
||||
<p className="text-sm text-[var(--muted-foreground)]">
|
||||
{summary.upcomingChallenges.length} défis identifiés • {summary.upcomingChallenges.filter(c => c.priority === 'high').length} priorité haute • {summary.upcomingChallenges.filter(c => c.blockers.length > 0).length} avec blockers
|
||||
{summary.upcomingChallenges.length} défis identifiés •{' '}
|
||||
{
|
||||
summary.upcomingChallenges.filter((c) => c.priority === 'high')
|
||||
.length
|
||||
}{' '}
|
||||
priorité haute •{' '}
|
||||
{
|
||||
summary.upcomingChallenges.filter((c) => c.blockers.length > 0)
|
||||
.length
|
||||
}{' '}
|
||||
avec blockers
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{summary.upcomingChallenges.length === 0 ? (
|
||||
<div className="p-8 text-center rounded-xl border-2" style={{
|
||||
backgroundColor: 'color-mix(in srgb, var(--muted) 15%, transparent)',
|
||||
borderColor: 'color-mix(in srgb, var(--muted) 40%, var(--border))',
|
||||
color: 'var(--muted-foreground)'
|
||||
}}>
|
||||
<div className="text-4xl mb-4"><Emoji emoji="🎯" /></div>
|
||||
<div
|
||||
className="p-8 text-center rounded-xl border-2"
|
||||
style={{
|
||||
backgroundColor:
|
||||
'color-mix(in srgb, var(--muted) 15%, transparent)',
|
||||
borderColor:
|
||||
'color-mix(in srgb, var(--muted) 40%, var(--border))',
|
||||
color: 'var(--muted-foreground)',
|
||||
}}
|
||||
>
|
||||
<div className="text-4xl mb-4">
|
||||
<Emoji emoji="🎯" />
|
||||
</div>
|
||||
<p className="text-lg mb-2">Aucun enjeu prioritaire trouvé.</p>
|
||||
<p className="text-sm">Ajoutez des tâches non complétées avec priorité haute/medium.</p>
|
||||
<p className="text-sm">
|
||||
Ajoutez des tâches non complétées avec priorité haute/medium.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
@@ -282,9 +408,7 @@ export default function ManagerWeeklySummary({ initialSummary }: ManagerWeeklySu
|
||||
)}
|
||||
|
||||
{/* Vue Métriques */}
|
||||
{activeView === 'metrics' && (
|
||||
<MetricsTab />
|
||||
)}
|
||||
{activeView === 'metrics' && <MetricsTab />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -21,9 +21,19 @@ interface MetricsTabProps {
|
||||
export function MetricsTab({ className }: MetricsTabProps) {
|
||||
const [selectedDate] = useState<Date>(getToday());
|
||||
const [weeksBack, setWeeksBack] = useState(4);
|
||||
|
||||
const { metrics, loading: metricsLoading, error: metricsError, refetch: refetchMetrics } = useWeeklyMetrics(selectedDate);
|
||||
const { trends, loading: trendsLoading, error: trendsError, refetch: refetchTrends } = useVelocityTrends(weeksBack);
|
||||
|
||||
const {
|
||||
metrics,
|
||||
loading: metricsLoading,
|
||||
error: metricsError,
|
||||
refetch: refetchMetrics,
|
||||
} = useWeeklyMetrics(selectedDate);
|
||||
const {
|
||||
trends,
|
||||
loading: trendsLoading,
|
||||
error: trendsError,
|
||||
refetch: refetchTrends,
|
||||
} = useVelocityTrends(weeksBack);
|
||||
|
||||
const handleRefresh = () => {
|
||||
refetchMetrics();
|
||||
@@ -35,7 +45,6 @@ export function MetricsTab({ className }: MetricsTabProps) {
|
||||
return `7 derniers jours (${format(metrics.period.start, 'dd MMM', { locale: fr })} - ${format(metrics.period.end, 'dd MMM yyyy', { locale: fr })})`;
|
||||
};
|
||||
|
||||
|
||||
if (metricsError || trendsError) {
|
||||
return (
|
||||
<div className={className}>
|
||||
@@ -61,13 +70,15 @@ export function MetricsTab({ className }: MetricsTabProps) {
|
||||
{/* Header avec période et contrôles */}
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h2 className="text-xl font-bold text-[var(--foreground)]"><Emoji emoji="📊" /> Métriques & Analytics</h2>
|
||||
<h2 className="text-xl font-bold text-[var(--foreground)]">
|
||||
<Emoji emoji="📊" /> Métriques & Analytics
|
||||
</h2>
|
||||
<p className="text-[var(--muted-foreground)]">{formatPeriod()}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
onClick={handleRefresh}
|
||||
variant="secondary"
|
||||
<Button
|
||||
onClick={handleRefresh}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
disabled={metricsLoading || trendsLoading}
|
||||
>
|
||||
@@ -83,7 +94,9 @@ export function MetricsTab({ className }: MetricsTabProps) {
|
||||
<div className="h-4 bg-[var(--border)] rounded w-1/4 mx-auto mb-4"></div>
|
||||
<div className="h-32 bg-[var(--border)] rounded"></div>
|
||||
</div>
|
||||
<p className="text-[var(--muted-foreground)] mt-4">Chargement des métriques...</p>
|
||||
<p className="text-[var(--muted-foreground)] mt-4">
|
||||
Chargement des métriques...
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : metrics ? (
|
||||
@@ -98,7 +111,7 @@ export function MetricsTab({ className }: MetricsTabProps) {
|
||||
<MetricsDistributionCharts metrics={metrics} />
|
||||
|
||||
{/* Tendances de vélocité */}
|
||||
<MetricsVelocitySection
|
||||
<MetricsVelocitySection
|
||||
trends={trends}
|
||||
trendsLoading={trendsLoading}
|
||||
weeksBack={weeksBack}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user