diff --git a/Dockerfile b/Dockerfile index 576f7a4..c0ec44b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -81,6 +81,9 @@ RUN npm ci --only=production && npm cache clean --force COPY --from=build --chown=nextjs:nodejs /app/dist ./dist COPY --from=build --chown=nextjs:nodejs /app/shared ./shared +# Copy migration scripts +COPY --chown=nextjs:nodejs scripts/ ./scripts/ + # Create symlink for public files to be accessible from dist RUN ln -sf /app/dist/public /app/dist/public @@ -103,5 +106,11 @@ USER nextjs HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD wget --no-verbose --tries=1 --spider http://localhost:3000/api/health || exit 1 -# Start the application +# Copy and set entrypoint script +COPY --chown=nextjs:nodejs scripts/docker-entrypoint.sh ./ +RUN chmod +x /app/scripts/auto-migrate-production.sh && \ + chmod +x /app/docker-entrypoint.sh + +# Start the application with migration +ENTRYPOINT ["/app/docker-entrypoint.sh"] CMD ["node", "dist/index.js"] \ No newline at end of file diff --git a/INSTRUCTIONS_DEPLOYMENT.md b/INSTRUCTIONS_DEPLOYMENT.md new file mode 100644 index 0000000..ef1be00 --- /dev/null +++ b/INSTRUCTIONS_DEPLOYMENT.md @@ -0,0 +1,112 @@ +# 🚀 Instructions de Déploiement avec Migration Automatique + +## Vue d'ensemble +Le système est maintenant configuré pour exécuter automatiquement les migrations de base de données lors de chaque mise à jour Docker, garantissant que toutes les tables nécessaires sont créées. + +## 🔧 Configuration Automatique + +### Scripts créés +1. **`scripts/auto-migrate-production.sh`** - Migration automatique au démarrage +2. **`scripts/docker-entrypoint.sh`** - Point d'entrée avec migration +3. **`scripts/manual-migrate.sh`** - Migration manuelle si nécessaire + +### Dockerfile modifié +- Copie automatique des scripts de migration +- Point d'entrée personnalisé avec migration +- Permissions configurées automatiquement + +## 🚀 Déploiement + +### Option 1: Reconstruction complète (Recommandée) +```bash +# Arrêter le conteneur actuel +docker-compose down + +# Reconstruire avec les nouveaux scripts +docker-compose up --build -d + +# Vérifier les logs de migration +docker-compose logs -f +``` + +### Option 2: Mise à jour sans reconstruction +```bash +# Copier les scripts dans le conteneur existant +docker cp scripts/ logiflow-logiflow-1:/app/ + +# Exécuter la migration manuellement +docker exec logiflow-logiflow-1 chmod +x /app/scripts/auto-migrate-production.sh +docker exec logiflow-logiflow-1 /app/scripts/auto-migrate-production.sh + +# Redémarrer l'application +docker-compose restart +``` + +## 🔍 Vérification + +### Logs de migration +```bash +# Voir les logs de migration au démarrage +docker-compose logs | grep "AUTO-MIGRATE" +``` + +### État des tables +```bash +# Vérifier que toutes les tables existent +docker exec logiflow-logiflow-1 psql $DATABASE_URL -c " +SELECT tablename +FROM pg_tables +WHERE schemaname = 'public' +ORDER BY tablename; +" +``` + +### Test du système d'annonces +```bash +# Vérifier la table announcements spécifiquement +docker exec logiflow-logiflow-1 psql $DATABASE_URL -c " +SELECT 'announcements' as table_name, count(*) as columns +FROM information_schema.columns +WHERE table_name = 'announcements'; +" +``` + +## 🛠️ Dépannage + +### Migration manuelle forcée +```bash +# Si la migration automatique échoue +docker exec logiflow-logiflow-1 /app/scripts/manual-migrate.sh +``` + +### Vérification des permissions +```bash +# Vérifier que les scripts sont exécutables +docker exec logiflow-logiflow-1 ls -la /app/scripts/ +``` + +### Logs détaillés +```bash +# Activer le debug des migrations +docker-compose up -d --env DEBUG_MIGRATIONS=true +``` + +## 📋 Tables créées automatiquement + +✅ **announcements** - Système d'informations +✅ **sav_tickets** - Tickets SAV +✅ **sav_ticket_history** - Historique SAV +✅ **weather_settings** - Configuration météo +✅ **weather_data** - Cache météo +✅ **database_backups** - Sauvegardes +✅ **invoice_verification_cache** - Cache vérification factures + +## 🔄 Futures mises à jour + +Désormais, chaque fois que vous mettez à jour votre application Docker : +1. Le conteneur démarre +2. La migration automatique s'exécute +3. Toutes les nouvelles tables sont créées +4. L'application démarre normalement + +**Plus besoin d'intervention manuelle !** \ No newline at end of file diff --git a/docker-compose.override.yml b/docker-compose.override.yml new file mode 100644 index 0000000..24cfc62 --- /dev/null +++ b/docker-compose.override.yml @@ -0,0 +1,15 @@ +# Fichier de configuration Docker Compose pour le développement et la production +# Utilise les variables d'environnement pour la configuration + +version: '3.8' + +services: + app: + volumes: + # Monter les scripts de migration + - ./scripts:/app/scripts:ro + environment: + # Forcer l'exécution des migrations au démarrage + - AUTO_MIGRATE=true + # Variables de debug + - DEBUG_MIGRATIONS=true \ No newline at end of file diff --git a/replit.md b/replit.md index 8f29201..d8112da 100644 --- a/replit.md +++ b/replit.md @@ -35,7 +35,7 @@ The platform is built with a clear separation of concerns, utilizing a modern fu - **Invoice Verification Cache:** Robust caching system for invoice verification results with automatic expiration and conflict resolution. Enhanced with unique constraint handling and graceful error management for production stability (August 2025). Fixed production SSL certificate errors and fetch timeout loops with enhanced error handling, network timeout protection, and error result caching to prevent infinite retry loops (August 2025). - **UI Scrollbar Optimization:** Eliminated redundant vertical scrollbar on the right side of the screen while preserving necessary internal page scrolling. Implemented global CSS rules with `overflow: hidden` on html/body/root and Layout height management to prevent vertical overflow issues in production (August 2025). - **Task Management:** Système complet de gestion des tâches avec fonctionnalités temporelles avancées - tri intelligent (pending > priorité > date), dates d'échéance avec sélecteur calendrier, indicateurs visuels pour tâches en retard/urgentes, filtres par échéance (aujourd'hui, cette semaine, en retard, sans échéance), vue Kanban et liste, badges colorés pour statut temporel. Interface optimisée pour suivi prioritaire des tâches non validées. Correction critique de l'isolation des données : chaque magasin ne voit maintenant que ses propres tâches (Août 2025). **PRODUCTION FIX (Août 2025)** : Résolution du problème de rechargements multiples nécessaires pour l'administrateur - le cache des tâches s'invalide maintenant automatiquement lors du changement de magasin sélectionné. -- **Information System (Announcements):** Système d'informations complet remplaçant la carte commandes clients dans le dashboard - gestion d'annonces avec niveaux de priorité (normal, important, urgent), contrôle d'accès basé sur les rôles (admin : CRUD complet, autres rôles : lecture seule), tri intelligent par priorité et date, filtrage par magasin pour administrateurs, interface moderne avec badges colorés et indicateurs visuels. Intégration complète avec migrations automatiques et fichier init.sql complet pour nouvelles installations (Août 2025). +- **Information System (Announcements):** Système d'informations complet remplaçant la carte commandes clients dans le dashboard - gestion d'annonces avec niveaux de priorité (normal, important, urgent), contrôle d'accès basé sur les rôles (admin : CRUD complet, autres rôles : lecture seule), tri intelligent par priorité et date, filtrage par magasin pour administrateurs, interface moderne avec badges colorés et indicateurs visuels. Intégration complète avec migrations automatiques et fichier init.sql complet pour nouvelles installations. **MIGRATION AUTOMATIQUE (Août 2025)** : Système de migration automatique intégré au Dockerfile avec scripts de déploiement pour créer automatiquement toutes les tables lors des mises à jour Docker. - **DLC Module Permissions:** Correction des permissions de validation DLC pour permettre aux admin, directeur et manager de valider les produits DLC. Ajout de logs de debug pour traçabilité des validations (Août 2025). - **User and Permission Management:** Granular access controls ensuring that users (e.g., employees) have appropriate permissions for tasks like creating customer orders. - **Reporting:** Statistical reporting, including monthly summaries of deliveries based on `deliveredDate`. diff --git a/scripts/auto-migrate-production.sh b/scripts/auto-migrate-production.sh new file mode 100644 index 0000000..125a9b3 --- /dev/null +++ b/scripts/auto-migrate-production.sh @@ -0,0 +1,191 @@ +#!/bin/bash +# Script de migration automatique pour les mises à jour Docker +# Ce script s'exécute automatiquement lors du démarrage du conteneur + +set -e + +echo "🔄 [AUTO-MIGRATE] Début de la migration automatique..." + +# Vérifier si la base de données est accessible +if ! psql "$DATABASE_URL" -c "SELECT 1;" > /dev/null 2>&1; then + echo "❌ [AUTO-MIGRATE] Impossible de se connecter à la base de données" + exit 1 +fi + +echo "✅ [AUTO-MIGRATE] Connexion à la base de données réussie" + +# Fonction pour vérifier si une table existe +table_exists() { + local table_name=$1 + psql "$DATABASE_URL" -tAc "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema='public' AND table_name='$table_name');" +} + +# Fonction pour vérifier si une colonne existe +column_exists() { + local table_name=$1 + local column_name=$2 + psql "$DATABASE_URL" -tAc "SELECT EXISTS (SELECT FROM information_schema.columns WHERE table_schema='public' AND table_name='$table_name' AND column_name='$column_name');" +} + +# Migration 1: Créer la table announcements si elle n'existe pas +if [ "$(table_exists 'announcements')" = "f" ]; then + echo "🔧 [AUTO-MIGRATE] Création de la table announcements..." + psql "$DATABASE_URL" << 'EOF' +CREATE TABLE announcements ( + id SERIAL PRIMARY KEY, + title VARCHAR(255) NOT NULL, + content TEXT NOT NULL, + priority VARCHAR(20) NOT NULL DEFAULT 'normal', + author_id VARCHAR(255) NOT NULL, + group_id INTEGER, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + CONSTRAINT announcements_priority_check CHECK (priority IN ('normal', 'important', 'urgent')), + CONSTRAINT announcements_author_id_fkey FOREIGN KEY (author_id) REFERENCES users(id) ON DELETE CASCADE, + CONSTRAINT announcements_group_id_fkey FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE +); + +CREATE INDEX IF NOT EXISTS idx_announcements_priority ON announcements(priority); +CREATE INDEX IF NOT EXISTS idx_announcements_created_at ON announcements(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_announcements_author_id ON announcements(author_id); +CREATE INDEX IF NOT EXISTS idx_announcements_group_id ON announcements(group_id); + +COMMENT ON TABLE announcements IS 'Admin-managed announcements/information system'; +EOF + echo "✅ [AUTO-MIGRATE] Table announcements créée avec succès" +else + echo "ℹ️ [AUTO-MIGRATE] Table announcements existe déjà" +fi + +# Migration 2: Créer les tables SAV si elles n'existent pas +if [ "$(table_exists 'sav_tickets')" = "f" ]; then + echo "🔧 [AUTO-MIGRATE] Création des tables SAV..." + psql "$DATABASE_URL" << 'EOF' +CREATE TABLE IF NOT EXISTS sav_tickets ( + id SERIAL PRIMARY KEY, + ticket_number VARCHAR(50) NOT NULL UNIQUE, + title VARCHAR(255) NOT NULL, + description TEXT NOT NULL, + status VARCHAR(20) NOT NULL DEFAULT 'nouveau', + priority VARCHAR(20) NOT NULL DEFAULT 'normale', + supplier_id INTEGER NOT NULL, + group_id INTEGER NOT NULL, + created_by VARCHAR(255) NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT sav_tickets_status_check CHECK (status IN ('nouveau', 'en_cours', 'en_attente', 'resolu', 'ferme')), + CONSTRAINT sav_tickets_priority_check CHECK (priority IN ('faible', 'normale', 'elevee', 'critique')), + CONSTRAINT sav_tickets_supplier_id_fkey FOREIGN KEY (supplier_id) REFERENCES suppliers(id), + CONSTRAINT sav_tickets_group_id_fkey FOREIGN KEY (group_id) REFERENCES groups(id), + CONSTRAINT sav_tickets_created_by_fkey FOREIGN KEY (created_by) REFERENCES users(id) +); + +CREATE TABLE IF NOT EXISTS sav_ticket_history ( + id SERIAL PRIMARY KEY, + ticket_id INTEGER NOT NULL, + action VARCHAR(50) NOT NULL, + description TEXT NOT NULL, + created_by VARCHAR(255) NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT sav_ticket_history_ticket_id_fkey FOREIGN KEY (ticket_id) REFERENCES sav_tickets(id) ON DELETE CASCADE, + CONSTRAINT sav_ticket_history_created_by_fkey FOREIGN KEY (created_by) REFERENCES users(id) +); + +CREATE INDEX IF NOT EXISTS idx_sav_tickets_status ON sav_tickets(status); +CREATE INDEX IF NOT EXISTS idx_sav_tickets_priority ON sav_tickets(priority); +CREATE INDEX IF NOT EXISTS idx_sav_tickets_group_id ON sav_tickets(group_id); +CREATE INDEX IF NOT EXISTS idx_sav_ticket_history_ticket_id ON sav_ticket_history(ticket_id); +EOF + echo "✅ [AUTO-MIGRATE] Tables SAV créées avec succès" +else + echo "ℹ️ [AUTO-MIGRATE] Tables SAV existent déjà" +fi + +# Migration 3: Créer les tables météo si elles n'existent pas +if [ "$(table_exists 'weather_settings')" = "f" ]; then + echo "🔧 [AUTO-MIGRATE] Création des tables météo..." + psql "$DATABASE_URL" << 'EOF' +CREATE TABLE IF NOT EXISTS weather_settings ( + id SERIAL PRIMARY KEY, + api_key VARCHAR(255) NOT NULL, + location VARCHAR(255) NOT NULL, + is_active BOOLEAN DEFAULT true, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE IF NOT EXISTS weather_data ( + id SERIAL PRIMARY KEY, + date VARCHAR(10) NOT NULL, + is_current_year BOOLEAN NOT NULL, + temp_max VARCHAR(10), + temp_min VARCHAR(10), + conditions VARCHAR(255), + icon VARCHAR(50), + description TEXT, + location VARCHAR(255), + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + UNIQUE(date, is_current_year) +); + +CREATE INDEX IF NOT EXISTS idx_weather_data_date_year ON weather_data(date, is_current_year); +EOF + echo "✅ [AUTO-MIGRATE] Tables météo créées avec succès" +else + echo "ℹ️ [AUTO-MIGRATE] Tables météo existent déjà" +fi + +# Migration 4: Créer les tables utilitaires si elles n'existent pas +if [ "$(table_exists 'database_backups')" = "f" ]; then + echo "🔧 [AUTO-MIGRATE] Création des tables utilitaires..." + psql "$DATABASE_URL" << 'EOF' +CREATE TABLE IF NOT EXISTS database_backups ( + id SERIAL PRIMARY KEY, + filename VARCHAR(255) NOT NULL, + file_size BIGINT NOT NULL, + backup_type VARCHAR(50) NOT NULL, + created_by VARCHAR(255) NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + status VARCHAR(20) DEFAULT 'completed' +); + +CREATE TABLE IF NOT EXISTS invoice_verification_cache ( + id SERIAL PRIMARY KEY, + invoice_reference VARCHAR(255) NOT NULL, + nocodb_config_id INTEGER NOT NULL, + verification_result TEXT NOT NULL, + is_found BOOLEAN NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + expires_at TIMESTAMP NOT NULL, + UNIQUE(invoice_reference, nocodb_config_id) +); + +CREATE INDEX IF NOT EXISTS idx_invoice_verification_expires ON invoice_verification_cache(expires_at); +EOF + echo "✅ [AUTO-MIGRATE] Tables utilitaires créées avec succès" +else + echo "ℹ️ [AUTO-MIGRATE] Tables utilitaires existent déjà" +fi + +# Nettoyage des anciennes données de cache +echo "🧹 [AUTO-MIGRATE] Nettoyage du cache expiré..." +psql "$DATABASE_URL" -c "DELETE FROM invoice_verification_cache WHERE expires_at < NOW();" 2>/dev/null || true +psql "$DATABASE_URL" -c "DELETE FROM weather_data WHERE created_at < NOW() - INTERVAL '30 days';" 2>/dev/null || true + +# Affichage du statut final +echo "📊 [AUTO-MIGRATE] État des tables après migration:" +psql "$DATABASE_URL" -c " +SELECT + schemaname as schema, + tablename as table_name, + CASE + WHEN tablename IN ('announcements', 'sav_tickets', 'weather_settings', 'database_backups') THEN '🆕 Nouvelles' + ELSE '📦 Existantes' + END as status +FROM pg_tables +WHERE schemaname = 'public' +ORDER BY tablename; +" + +echo "✅ [AUTO-MIGRATE] Migration automatique terminée avec succès!" \ No newline at end of file diff --git a/scripts/docker-entrypoint.sh b/scripts/docker-entrypoint.sh new file mode 100644 index 0000000..dd0f154 --- /dev/null +++ b/scripts/docker-entrypoint.sh @@ -0,0 +1,37 @@ +#!/bin/bash +# Point d'entrée Docker avec migration automatique +# Ce script remplace le point d'entrée par défaut du conteneur + +set -e + +echo "🚀 [ENTRYPOINT] Démarrage du conteneur avec migration automatique..." + +# Attendre que la base de données soit prête +echo "⏳ [ENTRYPOINT] Attente de la base de données..." +timeout=60 +counter=0 + +while ! psql "$DATABASE_URL" -c "SELECT 1;" > /dev/null 2>&1; do + counter=$((counter + 1)) + if [ $counter -gt $timeout ]; then + echo "❌ [ENTRYPOINT] Timeout: impossible de se connecter à la base de données après ${timeout}s" + exit 1 + fi + echo "⏳ [ENTRYPOINT] Tentative $counter/$timeout..." + sleep 1 +done + +echo "✅ [ENTRYPOINT] Base de données accessible" + +# Exécuter les migrations automatiques +if [ -f "/app/scripts/auto-migrate-production.sh" ]; then + echo "🔄 [ENTRYPOINT] Exécution des migrations automatiques..." + chmod +x /app/scripts/auto-migrate-production.sh + /app/scripts/auto-migrate-production.sh +else + echo "⚠️ [ENTRYPOINT] Script de migration non trouvé, poursuite sans migration" +fi + +# Démarrer l'application +echo "🎯 [ENTRYPOINT] Démarrage de l'application..." +exec "$@" \ No newline at end of file diff --git a/scripts/manual-migrate.sh b/scripts/manual-migrate.sh new file mode 100644 index 0000000..c0a9a70 --- /dev/null +++ b/scripts/manual-migrate.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Script de migration manuelle pour forcer une mise à jour +# Usage: docker exec logiflow-logiflow-1 /app/scripts/manual-migrate.sh + +echo "🔧 [MANUAL-MIGRATE] Début de la migration manuelle forcée..." + +# Sourcer le script de migration automatique +if [ -f "/app/scripts/auto-migrate-production.sh" ]; then + source /app/scripts/auto-migrate-production.sh +else + echo "❌ [MANUAL-MIGRATE] Script de migration automatique non trouvé" + exit 1 +fi + +echo "✅ [MANUAL-MIGRATE] Migration manuelle terminée!" \ No newline at end of file