This commit is contained in:
2026-05-04 11:34:33 +02:00
parent 9070390770
commit 2087cfb945
12 changed files with 895 additions and 194 deletions
+64 -1
View File
@@ -1 +1,64 @@
pachafamily # 🦙 PachaFamily - Dashboard Familial Sur-Mesure
PachaFamily est une application web privée de gestion familiale. Développée sans framework lourd (Vanilla JS / PHP Natif), elle garantit des performances optimales, une maintenance simplifiée et une personnalisation totale.
## 🌟 Modules & Fonctionnalités
### 💰 1. Module Budget (`/modules/budget/`)
Gestion asynchrone (SPA-like) des finances de la famille.
- **Suivi Mensuel** : Saisie rapide des dépenses avec répartition automatique (Alex/Laia/Commun).
- **Budget Prévisionnel** : Configuration des salaires, charges fixes, et calcul des restes à vivre. Mode "Calculatrice" flottant intégré.
- **Épargne** : Suivi des cagnottes par personne et par catégorie (Vacances, Nens, Perso).
- **Récapitulatif** : Bilan annuel (À venir).
### 📅 2. Module Calendrier (`/modules/family-calendar/`)
Agenda partagé pour toute la famille.
- Affichage des événements et vacances scolaires.
- Gestion des jours de congés avec compteurs annuels par personne.
### 🌴 3. Module Voyages (`/modules/holidays/`)
Planificateur de roadtrips et vacances.
- **Cartographie** : Intégration de Leaflet.js.
- **Itinéraires** : Calcul des trajets via OSRM et géocodage via Nominatim.
- Checkpoints, notes et liaisons directes avec le budget d'épargne.
### 🎁 4. Module Cadeaux (`/modules/gift-list/`)
Listes de souhaits pour les événements (Noël, Anniversaires, Rois Mages...).
---
## 🚀 Plan d'Optimisation & Debugging (Roadmap)
Cette section trace les étapes pour épurer la dette technique et optimiser l'application.
### 🟢 Phase 1 : Quick Wins (Gains rapides)
- [x] **Refonte Asynchrone Budget** : Remplacement des formulaires classiques par des appels `fetch()` silencieux sur `suivi.php`, `budget_prev.php` et `epargne.php`.
- [ ] **Nettoyage des Vues** : Extraire le JavaScript et le CSS encore présents dans les fichiers `.php` vers leurs fichiers `.js` et `.css` dédiés.
- [ ] **Corrections des liens GET** : Remplacer les `<a href="?action=delete">` par des `<button onclick="deleteItem()">` asynchrones partout.
### 🟡 Phase 2 : Robustesse & UX (Effort moyen)
- [ ] **Déploiement des Tests E2E** : Étendre `test-engine.js` pour couvrir le Calendrier et les Voyages.
- [ ] **Uniformisation Mobile** : Vérifier tous les `hover` et `z-index` pour garantir que les actions (édition/suppression) soient cliquables sur écrans tactiles.
- [ ] **Gestion des Erreurs JSON** : Appliquer systématiquement le `.text()` avant `JSON.parse()` dans les fetchs pour capturer les erreurs PHP (Warnings).
### 🔴 Phase 3 : Architecture & Performances (Heavy lifting)
- [ ] **Optimisation SQL (N+1)** : Réviser les requêtes du module Calendrier pour réduire le nombre d'appels à la base de données.
- [ ] **Mise en cache API Map** : Implémenter un système de cache local pour les requêtes OSRM/Nominatim afin d'éviter les limites de requêtes (Rate Limits) sur le module Voyages.
- [ ] **Routeur PHP Global** : Remplacer la navigation par `?tab=` par un routeur natif centralisé (Front Controller).
---
## 🏷️ Patch / Versions
- **v1.1.0 - Le Grand Bond Asynchrone** (Mai 2026) : Transformation des vues Budget (Prévisionnel & Épargne) en interfaces asynchrones (Fetch API). Création d'un moteur de tests E2E maison (`test-engine.js`). Résolution des conflits de `z-index` sur mobile. Sécurisation des JSON face aux Warnings PHP.
- **v1.0.0 - MVP Initial** : Mise en place de la structure de base, base de données MariaDB, modules Budget (Suivi), Calendrier, Cadeaux et Voyages (Leaflet).
+5
View File
@@ -290,6 +290,11 @@ p {
border: 1px solid #fecaca; border: 1px solid #fecaca;
} }
body.no-scroll {
overflow: hidden !important;
height: 100vh !important;
}
/* === FOOTER === */ /* === FOOTER === */
.pf-footer { .pf-footer {
border-top: 1px solid var(--border-light); border-top: 1px solid var(--border-light);
+13
View File
@@ -1,6 +1,19 @@
<?php <?php
// Dictionnaire Catalan // Dictionnaire Catalan
return [ return [
// ==========================================
// TEST AUTO
// ==========================================
'test_running' => 'Proves en curs...',
'test_passed' => 'Prova superada',
'test_failed' => 'Prova fallida',
'tests_title' => 'Laboratori de Proves',
'tests_run_budget' => 'Provar el Pressupost',
'tests_run_all' => 'Iniciar totes les proves',
'tests_copy_report' => 'Copiar l\'informe',
'tests_waiting' => 'Esperant l\'inici...',
'tests_report_copied' => 'Informe copiat al porta-retalls!',
// ========================================== // ==========================================
// GLOBAL & NAVIGATION // GLOBAL & NAVIGATION
// ========================================== // ==========================================
+14
View File
@@ -1,6 +1,20 @@
<?php <?php
// Dictionnaire Français // Dictionnaire Français
return [ return [
// ==========================================
// TEST AUTO
// ==========================================
'test_running' => 'Tests en cours...',
'test_passed' => 'Test réussi',
'test_failed' => 'Test échoué',
'tests_title' => 'Laboratoire de Tests',
'tests_run_budget' => 'Tester le Budget',
'tests_run_all' => 'Lancer tous les tests',
'tests_copy_report' => 'Copier le rapport',
'tests_waiting' => 'En attente du lancement...',
'tests_report_copied' => 'Rapport copié dans le presse-papier !',
// ========================================== // ==========================================
// GLOBAL & NAVIGATION // GLOBAL & NAVIGATION
// ========================================== // ==========================================
+56 -113
View File
@@ -164,7 +164,7 @@
justify-content: center; justify-content: center;
gap: 8px; gap: 8px;
height: 40px; /* Hauteur Fixe */ height: 40px;
padding: 0 24px; padding: 0 24px;
background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
@@ -208,11 +208,8 @@
padding: 6px; padding: 6px;
border-radius: var(--radius-s); border-radius: var(--radius-s);
transition: background 0.2s; transition: background 0.2s;
}
.btn-icon {
font-size: 1.1rem; font-size: 1.1rem;
} }
.btn-icon:hover { .btn-icon:hover {
background: #e2e8f0; background: #e2e8f0;
transform: scale(1.1); transform: scale(1.1);
@@ -223,12 +220,23 @@
gap: 8px; gap: 8px;
} }
/* Sécurité de clic asynchrone */
.btn-safe-click {
position: relative;
z-index: 50 !important;
pointer-events: auto !important;
}
.month-actions { .month-actions {
display: flex; display: flex;
gap: 4px; gap: 4px;
opacity: 0.5; opacity: 0.5;
transition: opacity 0.2s ease; transition: opacity 0.2s ease;
} }
/* Survol des boutons du mois (Epargne) */
.month-header-container:hover .month-actions {
opacity: 1;
}
.month-actions .btn-icon-small { .month-actions .btn-icon-small {
font-size: 0.75rem; font-size: 0.75rem;
@@ -330,7 +338,6 @@
border-top: 2px solid #e2e8f0; border-top: 2px solid #e2e8f0;
} }
/* Bouton supprimer au survol (Style Epargne) */
.btn-cell-delete { .btn-cell-delete {
display: none; display: none;
background: rgba(239, 68, 68, 0.1); background: rgba(239, 68, 68, 0.1);
@@ -429,7 +436,6 @@ input[type="checkbox"]:checked::after {
font-weight: bold; font-weight: bold;
} }
/* Suppression flèches input number (Cross-browser) */
input[type="number"]::-webkit-outer-spin-button, input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button { input[type="number"]::-webkit-inner-spin-button {
-webkit-appearance: none; -webkit-appearance: none;
@@ -530,7 +536,7 @@ input[type="number"] {
color: var(--text-muted); color: var(--text-muted);
} }
/* --- 9. MOBILE RESPONSIVE --- */ /* --- 9. MOBILE RESPONSIVE (Global) --- */
@media (max-width: 768px) { @media (max-width: 768px) {
.budget-tabs-container { .budget-tabs-container {
display: flex; display: flex;
@@ -563,6 +569,19 @@ input[type="number"] {
.form-row { .form-row {
grid-template-columns: 1fr; grid-template-columns: 1fr;
} }
/* FORCAGE VISIBILITE BOUTONS SUR MOBILE (Pas de hover possible) */
.month-actions {
opacity: 1 !important;
}
.btn-cell-delete {
display: flex !important;
opacity: 0.7;
}
.row-actions {
opacity: 1 !important;
pointer-events: auto !important;
}
} }
/* --- 10. BUDGET PREVISIONNEL (TIMELINE) --- */ /* --- 10. BUDGET PREVISIONNEL (TIMELINE) --- */
@@ -588,7 +607,6 @@ input[type="number"] {
letter-spacing: -0.025em; letter-spacing: -0.025em;
} }
/* Inputs "Invisible" */
.prev-input { .prev-input {
width: 100%; width: 100%;
border: 1px solid transparent; border: 1px solid transparent;
@@ -613,7 +631,6 @@ input[type="number"] {
font-weight: 700; font-weight: 700;
} }
/* Tableaux Config & Alloc */
.prev-salary-table { .prev-salary-table {
width: 100%; width: 100%;
max-width: 900px; max-width: 900px;
@@ -665,7 +682,6 @@ input[type="number"] {
text-align: center; text-align: center;
font-size: 0.9rem; font-size: 0.9rem;
} }
.prev-alloc-table td { .prev-alloc-table td {
padding: 3px 14px; padding: 3px 14px;
border-bottom: 1px solid #f1f5f9; border-bottom: 1px solid #f1f5f9;
@@ -675,7 +691,6 @@ input[type="number"] {
font-size: 0.9rem; font-size: 0.9rem;
} }
/* Colonne Sticky */
.col-sticky { .col-sticky {
position: sticky !important; position: sticky !important;
left: 0 !important; left: 0 !important;
@@ -701,7 +716,6 @@ input[type="number"] {
font-size: 0.75rem; font-size: 0.75rem;
} }
/* En-têtes Mois */
.th-month { .th-month {
background: #1e293b !important; background: #1e293b !important;
color: white !important; color: white !important;
@@ -719,7 +733,6 @@ input[type="number"] {
color: var(--text-muted); color: var(--text-muted);
} }
/* Lignes */
.row-total td { .row-total td {
background: #f8fafc; background: #f8fafc;
font-weight: 700; font-weight: 700;
@@ -732,7 +745,6 @@ input[type="number"] {
border-bottom: 2px solid #bfdbfe; border-bottom: 2px solid #bfdbfe;
} }
/* Couleurs */
.txt-alex { .txt-alex {
color: #0891b2; color: #0891b2;
} }
@@ -751,7 +763,6 @@ input[type="number"] {
color: var(--danger); color: var(--danger);
} }
/* Navigation */
.nav-group { .nav-group {
display: flex; display: flex;
gap: 5px; gap: 5px;
@@ -775,20 +786,21 @@ input[type="number"] {
/* --- ACTIONS SUR LIGNES (Edit / Delete) --- */ /* --- ACTIONS SUR LIGNES (Edit / Delete) --- */
.row-actions { .row-actions {
display: none; /* Masqué par défaut */
position: absolute; position: absolute;
right: 5px; right: 10px;
top: 50%; top: 50%;
transform: translateY(-50%); transform: translateY(-50%);
gap: 4px; z-index: 50 !important;
background: rgba(255, 255, 255, 0.9); /* Petit fond pour lisibilité */ opacity: 0;
padding: 2px; pointer-events: none;
border-radius: 4px; display: flex;
gap: 8px;
transition: opacity 0.2s ease-in-out;
} }
/* On affiche au survol de la cellule */ tr:hover .row-actions {
td:hover .row-actions { opacity: 1;
display: flex; pointer-events: auto !important;
} }
.btn-icon-action { .btn-icon-action {
@@ -810,28 +822,25 @@ td:hover .row-actions {
.btn-icon-action.edit { .btn-icon-action.edit {
color: #3b82f6; color: #3b82f6;
} /* Bleu */ }
.btn-icon-action.edit:hover { .btn-icon-action.edit:hover {
background: #eff6ff; background: #eff6ff;
} }
.btn-icon-action.delete { .btn-icon-action.delete {
color: #ef4444; color: #ef4444;
} /* Rouge */ }
.btn-icon-action.delete:hover { .btn-icon-action.delete:hover {
background: #fef2f2; background: #fef2f2;
} }
/* --- 11. RÉCAPITULATIF VIREMENTS (Tableau Unique) --- */ /* --- 11. RÉCAPITULATIF VIREMENTS --- */
.recap-wrapper { .recap-wrapper {
margin-top: 30px; margin-top: 30px;
padding-top: 20px; padding-top: 20px;
border-top: 1px solid #e2e8f0; border-top: 1px solid #e2e8f0;
display: flex; display: flex;
justify-content: center; /* Centré */ justify-content: center;
} }
.recap-card { .recap-card {
background: white; background: white;
border: 1px solid #e2e8f0; border: 1px solid #e2e8f0;
@@ -839,9 +848,8 @@ td:hover .row-actions {
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
overflow: hidden; overflow: hidden;
width: 100%; width: 100%;
max-width: 600px; /* Pas trop large pour rester lisible */ max-width: 600px;
} }
.recap-header { .recap-header {
background: #1e293b; background: #1e293b;
color: white; color: white;
@@ -852,12 +860,10 @@ td:hover .row-actions {
letter-spacing: 0.05em; letter-spacing: 0.05em;
text-align: center; text-align: center;
} }
.recap-table { .recap-table {
width: 100%; width: 100%;
border-collapse: collapse; border-collapse: collapse;
} }
.recap-table th, .recap-table th,
.recap-table td { .recap-table td {
padding: 10px 15px; padding: 10px 15px;
@@ -865,7 +871,6 @@ td:hover .row-actions {
text-align: center; text-align: center;
font-size: 0.95rem; font-size: 0.95rem;
} }
.recap-table th { .recap-table th {
font-weight: 700; font-weight: 700;
text-transform: uppercase; text-transform: uppercase;
@@ -874,15 +879,12 @@ td:hover .row-actions {
background: #f8fafc; background: #f8fafc;
border-bottom: 2px solid #e2e8f0; border-bottom: 2px solid #e2e8f0;
} }
/* Colonne Labels (Gauche) */
.recap-table td:first-child { .recap-table td:first-child {
text-align: left; text-align: left;
font-weight: 600; font-weight: 600;
color: #1e293b; color: #1e293b;
} }
/* Colonne Alex (Cyan) */
.col-alex { .col-alex {
background-color: #ecfeff; background-color: #ecfeff;
color: #0891b2; color: #0891b2;
@@ -892,8 +894,6 @@ th.col-alex {
background-color: #cffafe; background-color: #cffafe;
border-bottom-color: #a5f3fc; border-bottom-color: #a5f3fc;
} }
/* Colonne Laia (Ambre) */
.col-laia { .col-laia {
background-color: #fffbeb; background-color: #fffbeb;
color: #d97706; color: #d97706;
@@ -903,8 +903,6 @@ th.col-laia {
background-color: #fef3c7; background-color: #fef3c7;
border-bottom-color: #fde68a; border-bottom-color: #fde68a;
} }
/* Colonne Global */
.col-global { .col-global {
background-color: #f8fafc; background-color: #f8fafc;
color: #475569; color: #475569;
@@ -912,7 +910,6 @@ th.col-laia {
border-left: 2px solid #e2e8f0; border-left: 2px solid #e2e8f0;
} }
/* Ligne Grand Total */
.row-grand-total td { .row-grand-total td {
background-color: #1e293b; background-color: #1e293b;
color: white; color: white;
@@ -920,7 +917,6 @@ th.col-laia {
border: none; border: none;
padding: 12px 15px; padding: 12px 15px;
} }
/* On garde les couleurs de texte même sur fond sombre pour la lisibilité */
.row-grand-total .col-alex { .row-grand-total .col-alex {
background: #164e63; background: #164e63;
color: #67e8f9; color: #67e8f9;
@@ -937,19 +933,14 @@ th.col-laia {
border: none; border: none;
} }
/* --- 12. OPTIMISATIONS MOBILES (Mode Largeur Fixe 680px) --- */ /* --- 12. OPTIMISATIONS MOBILES PREVISIONNEL --- */
@media (max-width: 768px) { @media (max-width: 768px) {
/* 1. ON FORCE TOUT LE SITE A FAIRE MINIMUM 680px */
/* Cela inclut le Header et le Footer global */
html, html,
body { body {
min-width: 680px !important; min-width: 680px !important;
overflow-x: auto !important; /* Active le scroll horizontal global si besoin */ overflow-x: auto !important;
position: relative; position: relative;
} }
/* Si ton header/footer a des classes spécifiques, ajoute-les ici */
header, header,
footer, footer,
.navbar, .navbar,
@@ -959,32 +950,25 @@ th.col-laia {
width: 100% !important; width: 100% !important;
box-sizing: border-box; box-sizing: border-box;
} }
/* Le conteneur principal du budget */
.budget-view { .budget-view {
min-width: 680px !important; min-width: 680px !important;
width: 100%; width: 100%;
padding-right: 10px; /* Petite marge de sécurité */ padding-right: 10px;
} }
/* 2. TABLEAU REVENUS (Doit s'afficher en entier sans scroll interne) */
.prev-salary-table { .prev-salary-table {
min-width: 100%; /* Prend toute la largeur dispo (680px) */ min-width: 100%;
width: 100%; width: 100%;
} }
/* 3. TABLEAU REPARTITION (Timeline) */
/* Lui est très large (> 1000px). On le laisse scroller DANS la page de 680px */
.prev-timeline-wrapper { .prev-timeline-wrapper {
width: 100%; width: 100%;
overflow-x: auto !important; /* Scrollbar interne */ overflow-x: auto !important;
display: block; display: block;
} }
/* 4. ACTIONS (Crayon/Poubelle) */ /* Sur mobile, on garde les actions visibles sans hover */
/* On garde la logique "au clic" car c'est plus sûr sur mobile */
.row-actions { .row-actions {
display: none !important; display: flex !important;
opacity: 1 !important;
position: absolute; position: absolute;
right: 0; right: 0;
top: 0; top: 0;
@@ -997,37 +981,24 @@ th.col-laia {
z-index: 50; z-index: 50;
border-left: 1px solid #e2e8f0; border-left: 1px solid #e2e8f0;
} }
.row-actions.show-actions {
display: flex !important;
}
/* On ajuste la taille des icônes à cette vue dézoomée */
.btn-icon-action { .btn-icon-action {
font-size: 1.2rem; font-size: 1.2rem;
padding: 5px; padding: 5px;
width: 34px; width: 34px;
height: 34px; height: 34px;
} }
/* 5. COLONNE STICKY */
/* Puisque la page est large, on peut laisser une largeur confortable */
.col-sticky { .col-sticky {
min-width: 180px !important; min-width: 180px !important;
position: sticky !important; position: sticky !important;
left: 0; left: 0;
} }
/* 6. HEADER DE SECTION (Alignement) */
.prev-section-header { .prev-section-header {
flex-direction: row; /* On peut garder aligné car on a de la place (680px) */ flex-direction: row;
align-items: center; align-items: center;
} }
} }
/* ============================================================================ /* --- 13. STYLES SPÉCIFIQUES AU SUIVI MENSUEL (suivi.php) --- */
13. STYLES SPÉCIFIQUES AU SUIVI MENSUEL (suivi.php)
============================================================================ */
.cat-card { .cat-card {
background: var(--bg-card); background: var(--bg-card);
border-radius: var(--radius-l); border-radius: var(--radius-l);
@@ -1037,7 +1008,6 @@ th.col-laia {
overflow: hidden; overflow: hidden;
position: relative; position: relative;
} }
.btn-add-item { .btn-add-item {
background: rgba(255, 255, 255, 0.6); background: rgba(255, 255, 255, 0.6);
color: inherit; color: inherit;
@@ -1053,14 +1023,12 @@ th.col-laia {
justify-content: center; justify-content: center;
transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
} }
.btn-add-item:hover { .btn-add-item:hover {
background: var(--bg-card); background: var(--bg-card);
transform: rotate(90deg) scale(1.1); transform: rotate(90deg) scale(1.1);
box-shadow: var(--shadow-sm); box-shadow: var(--shadow-sm);
border-color: currentColor; border-color: currentColor;
} }
.progress-grid { .progress-grid {
display: grid; display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
@@ -1068,7 +1036,6 @@ th.col-laia {
margin-top: 20px; margin-top: 20px;
} }
/* Animation "Charges à venir" */
.fade-pulse { .fade-pulse {
animation: pulseText 2s infinite; animation: pulseText 2s infinite;
} }
@@ -1084,7 +1051,6 @@ th.col-laia {
} }
} }
/* Navigation par mois (Si elle n'est pas déjà gérée par .nav-group au-dessus) */
.suivi-nav-group { .suivi-nav-group {
display: flex; display: flex;
background: #e2e8f0; background: #e2e8f0;
@@ -1110,7 +1076,6 @@ th.col-laia {
color: var(--primary); color: var(--primary);
} }
/* Sélecteur dynamique de mois (dans l'import CSV) */
input[type="month"].pf-input { input[type="month"].pf-input {
font-family: inherit; font-family: inherit;
color: var(--text-main); color: var(--text-main);
@@ -1119,11 +1084,7 @@ input[type="month"].pf-input {
border-radius: var(--radius-s); border-radius: var(--radius-s);
} }
/* ============================================================================ /* --- 14. EPARGNE (epargne.php) --- */
14. EPARGNE (epargne.php)
============================================================================ */
/* Style compact pour les inputs intégrés au tableau d'épargne */
.epargne-inline-input { .epargne-inline-input {
width: 100%; width: 100%;
min-width: 60px; min-width: 60px;
@@ -1137,12 +1098,10 @@ input[type="month"].pf-input {
font-size: 0.85rem; font-size: 0.85rem;
margin: 0 auto; margin: 0 auto;
} }
.epargne-inline-input:hover { .epargne-inline-input:hover {
border-color: #cbd5e1; border-color: #cbd5e1;
background: #f8fafc; background: #f8fafc;
} }
.epargne-inline-input:focus { .epargne-inline-input:focus {
border-color: var(--primary); border-color: var(--primary);
background: #fff; background: #fff;
@@ -1150,11 +1109,7 @@ input[type="month"].pf-input {
box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.1); box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.1);
} }
/* ========================================================================== /* --- 15. COMPOSANT : CALCULATRICE FLOTTANTE (SOMME RAPIDE) --- */
COMPOSANT : CALCULATRICE FLOTTANTE (SOMME RAPIDE)
========================================================================== */
/* Bouton flottant à DROITE */
.pf-fab-sum { .pf-fab-sum {
position: fixed; position: fixed;
right: 30px; right: 30px;
@@ -1162,7 +1117,7 @@ input[type="month"].pf-input {
width: 56px; width: 56px;
height: 56px; height: 56px;
border-radius: 50%; border-radius: 50%;
background-color: #2563eb; /* Bleu primaire unifié */ background-color: #2563eb;
color: white; color: white;
font-size: 1.5rem; font-size: 1.5rem;
display: flex; display: flex;
@@ -1174,19 +1129,16 @@ input[type="month"].pf-input {
z-index: 9999; z-index: 9999;
transition: all 0.2s cubic-bezier(0.175, 0.885, 0.32, 1.275); transition: all 0.2s cubic-bezier(0.175, 0.885, 0.32, 1.275);
} }
.pf-fab-sum:hover { .pf-fab-sum:hover {
transform: scale(1.1); transform: scale(1.1);
background-color: #1d4ed8; background-color: #1d4ed8;
} }
.pf-fab-sum.active { .pf-fab-sum.active {
background-color: #10b981; /* Devient vert quand activé */ background-color: #10b981;
transform: scale(1.1); transform: scale(1.1);
box-shadow: 0 4px 20px rgba(16, 185, 129, 0.5); box-shadow: 0 4px 20px rgba(16, 185, 129, 0.5);
} }
/* Barre de résultat en bas au centre */
.pf-sum-bar { .pf-sum-bar {
position: fixed; position: fixed;
bottom: 30px; bottom: 30px;
@@ -1205,24 +1157,20 @@ input[type="month"].pf-input {
transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275); transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
font-family: inherit; font-family: inherit;
} }
.pf-sum-bar.visible { .pf-sum-bar.visible {
transform: translateX(-50%) translateY(0); transform: translateX(-50%) translateY(0);
opacity: 1; opacity: 1;
} }
.pf-sum-label { .pf-sum-label {
font-size: 0.9rem; font-size: 0.9rem;
color: #64748b; color: #64748b;
font-weight: 600; font-weight: 600;
} }
.pf-sum-value { .pf-sum-value {
font-size: 1.2rem; font-size: 1.2rem;
color: #0f172a; color: #0f172a;
font-weight: bold; font-weight: bold;
} }
.pf-sum-close { .pf-sum-close {
background: none; background: none;
border: none; border: none;
@@ -1234,22 +1182,17 @@ input[type="month"].pf-input {
line-height: 1; line-height: 1;
transition: color 0.2s; transition: color 0.2s;
} }
.pf-sum-close:hover { .pf-sum-close:hover {
color: #ef4444; /* Croix rouge au survol */ color: #ef4444;
} }
/* Effets sur le curseur quand le mode est actif */
body.sum-mode-active { body.sum-mode-active {
cursor: cell !important; cursor: cell !important;
} }
body.sum-mode-active input, body.sum-mode-active input,
body.sum-mode-active .sum-target { body.sum-mode-active .sum-target {
cursor: cell !important; cursor: cell !important;
} }
/* Style des champs/cellules sélectionnés */
.sum-selected { .sum-selected {
outline: 2px dashed #10b981 !important; outline: 2px dashed #10b981 !important;
outline-offset: -2px; outline-offset: -2px;
@@ -72,4 +72,57 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
} }
exit; exit;
} }
// --- ACTION : SAUVEGARDER UNE DÉPENSE MANUELLE (FETCH) ---
if ($action === 'save_expense_manual') {
header('Content-Type: application/json'); // On force le retour JSON pour notre script JS
try {
$id = !empty($_POST['expense_id']) ? (int)$_POST['expense_id'] : null;
$cat = $_POST['category'] ?? '';
$amount = floatval($_POST['amount'] ?? 0);
$date = $_POST['date'] ?? date('Y-m-d');
// Format attendu pour gestion_month (qui vient de input type="month") : YYYY-MM. On ajoute le jour.
$gestionMonth = $_POST['gestion_month'] ?? '';
if (strlen($gestionMonth) === 7) $gestionMonth .= '-01';
$label = trim($_POST['label'] ?? '');
$budgetItemId = null;
$holidayId = !empty($_POST['holiday_id']) ? (int)$_POST['holiday_id'] : null;
if ($cat === 'School' && !empty($_POST['label_select'])) {
$label = trim($_POST['label_select']);
} elseif (($cat === 'Frais' || $cat === 'Income') && !empty($_POST['budget_item_id'])) {
$budgetItemId = (int)$_POST['budget_item_id'];
}
// Vérification de sécurité
if (empty($label) || $amount <= 0) {
echo json_encode(['success' => false, 'error' => 'Le label et un montant supérieur à 0 sont obligatoires.']);
exit;
}
$is_credit = isset($_POST['is_credit']) ? (int)$_POST['is_credit'] : 0;
$finalAmount = $is_credit ? abs($amount) : -abs($amount);
if ($id) {
// UPDATE
$pdo->prepare("UPDATE pf_expenses SET date_exp=?, gestion_month=?, category=?, label=?, amount=?, budget_item_id=?, holiday_id=? WHERE id=?")
->execute([$date, $gestionMonth, $cat, $label, $finalAmount, $budgetItemId, $holidayId, $id]);
} else {
// INSERT
$uniqueRef = "MANUAL_" . uniqid();
$pdo->prepare("INSERT INTO pf_expenses (date_exp, gestion_month, category, label, amount, import_ref, budget_item_id, holiday_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
->execute([$date, $gestionMonth, $cat, $label, $finalAmount, $uniqueRef, $budgetItemId, $holidayId]);
}
echo json_encode(['success' => true]);
exit;
} catch (PDOException $e) {
echo json_encode(['success' => false, 'error' => 'Erreur base de données.']);
exit;
}
}
} }
+22 -3
View File
@@ -82,6 +82,13 @@ if ($action === 'add_category') {
$stmt = $pdo->prepare("INSERT INTO pf_alloc_categories (name, target, holiday_id) VALUES (?, ?, ?)"); $stmt = $pdo->prepare("INSERT INTO pf_alloc_categories (name, target, holiday_id) VALUES (?, ?, ?)");
$stmt->execute([$name, $target, $holiday_id]); $stmt->execute([$name, $target, $holiday_id]);
} }
// --- NOUVEAU : Réponse AJAX ---
if (isset($_POST['ajax'])) {
header('Content-Type: application/json');
echo json_encode(['success' => true]);
exit;
}
header("Location: " . $_SERVER['HTTP_REFERER']); header("Location: " . $_SERVER['HTTP_REFERER']);
exit; exit;
} }
@@ -97,20 +104,32 @@ if ($action === 'update_category') {
$stmt = $pdo->prepare("UPDATE pf_alloc_categories SET name = ?, target = ?, holiday_id = ? WHERE id = ?"); $stmt = $pdo->prepare("UPDATE pf_alloc_categories SET name = ?, target = ?, holiday_id = ? WHERE id = ?");
$stmt->execute([$name, $target, $holiday_id, $id]); $stmt->execute([$name, $target, $holiday_id, $id]);
} }
// --- NOUVEAU : Réponse AJAX ---
if (isset($_POST['ajax'])) {
header('Content-Type: application/json');
echo json_encode(['success' => true]);
exit;
}
header("Location: " . $_SERVER['HTTP_REFERER']); header("Location: " . $_SERVER['HTTP_REFERER']);
exit; exit;
} }
// 5. SUPPRESSION CATEGORIE // 5. SUPPRESSION CATEGORIE
if ($action === 'delete_category') { if ($action === 'delete_category') {
$id = (int)$_GET['id'] ?? (int)$_POST['id']; $id = (int)($_POST['id'] ?? $_GET['id'] ?? 0);
if ($id > 0) { if ($id > 0) {
$pdo->prepare("DELETE FROM pf_alloc_categories WHERE id = ?")->execute([$id]); $pdo->prepare("DELETE FROM pf_alloc_categories WHERE id = ?")->execute([$id]);
$pdo->prepare("DELETE FROM pf_alloc_values WHERE cat_id = ?")->execute([$id]); $pdo->prepare("DELETE FROM pf_alloc_values WHERE cat_id = ?")->execute([$id]);
} }
// Redirection vers la page précédente
header("Location: " . $_SERVER['HTTP_REFERER']); if (isset($_POST['ajax']) || isset($_GET['ajax'])) {
header('Content-Type: application/json');
echo json_encode(['success' => true]);
exit;
}
header("Location: " . ($_SERVER['HTTP_REFERER'] ?? '/budget.php'));
exit; exit;
} }
+95 -17
View File
@@ -231,11 +231,11 @@ function getTranslatedMonthName($dateString) {
</button> </button>
<a href="?tab=budget_prev&id=<?= $cat['id'] ?>&action=delete_category" <button type="button"
onclick="return confirm('<?= tr('bud_prev_confirm_del_line') ?>')" onclick="deleteCategory(<?= $cat['id'] ?>)"
class="btn-icon-action delete" title="<?= tr('delete') ?>"> class="btn-icon-action delete" title="<?= tr('delete') ?>">
&times; &times;
</a> </button>
</div> </div>
</td> </td>
<?php foreach ($months as $m): <?php foreach ($months as $m):
@@ -577,13 +577,14 @@ body.sum-mode-active .sum-target {
window.appLang = document.documentElement.lang === "ca" ? "ca-ES" : "fr-FR"; window.appLang = document.documentElement.lang === "ca" ? "ca-ES" : "fr-FR";
window.I18N = { window.I18N = {
...(window.I18N || {}), ...(window.I18N || {}),
'bud_prev_label_name': "<?= tr('bud_prev_label_name') ?>", 'bud_prev_label_name': <?= json_encode(tr('bud_prev_label_name')) ?>,
'bud_prev_err_no_history': "<?= tr('bud_prev_err_no_history') ?>", 'bud_prev_err_no_history': <?= json_encode(tr('bud_prev_err_no_history')) ?>,
'bud_prev_confirm_copy': "<?= tr('bud_prev_confirm_copy') ?>", 'bud_prev_confirm_copy': <?= json_encode(tr('bud_prev_confirm_copy')) ?>,
'bud_prev_confirm_transfers': "<?= tr('bud_prev_confirm_transfers') ?>", 'bud_prev_confirm_transfers': <?= json_encode(tr('bud_prev_confirm_transfers')) ?>,
'bud_err_tech': "<?= tr('bud_err_tech') ?>" 'bud_err_tech': <?= json_encode(tr('bud_err_tech')) ?>
}; };
const currentYear = <?= $currentYear ?? 'new Date().getFullYear()' ?>; const currentYear = <?= $currentYear ?? 'new Date().getFullYear()' ?>;
const months = <?= json_encode($months ?? []) ?>; const months = <?= json_encode($months ?? []) ?>;
@@ -627,7 +628,7 @@ function duplicateMonth() {
const sourceDateStr = months[1]; const sourceDateStr = months[1];
if (!sourceDateStr) { if (!sourceDateStr) {
alert(tr("bud_prev_err_no_history")); alert(window.I18N['bud_prev_err_no_history']);
return; return;
} }
@@ -639,7 +640,7 @@ function duplicateMonth() {
const sourceName = formatMonth(sourceDateStr); const sourceName = formatMonth(sourceDateStr);
const targetName = formatMonth(targetDateStr); const targetName = formatMonth(targetDateStr);
const message = tr("bud_prev_confirm_copy").replace('%s', sourceName).replace('%t', targetName); const message = window.I18N['bud_prev_confirm_copy'].replace('%s', sourceName).replace('%t', targetName);
if(!confirm(message)) return; if(!confirm(message)) return;
@@ -762,11 +763,11 @@ function saveData(action, data) {
const formData = new FormData(); const formData = new FormData();
formData.append('action', action); formData.append('action', action);
for (const key in data) formData.append(key, data[key]); for (const key in data) formData.append(key, data[key]);
fetch('/modules/budget/includes/api/save-budget.php', { method: 'POST', body: formData }); fetch('modules/budget/includes/api/save-budget.php', { method: 'POST', body: formData });
} }
function validateTransfers(person, month) { function validateTransfers(person, month) {
const msg = tr("bud_prev_confirm_transfers").replace('%p', person).replace('%m', month); const msg = window.I18N['bud_prev_confirm_transfers'].replace('%p', person).replace('%m', month);
if (!confirm(msg)) return; if (!confirm(msg)) return;
const formData = new FormData(); const formData = new FormData();
@@ -774,7 +775,7 @@ function validateTransfers(person, month) {
formData.append('person', person); formData.append('person', person);
formData.append('month_date', month); formData.append('month_date', month);
fetch('/modules/budget/includes/api/save-budget.php', { fetch('modules/budget/includes/api/save-budget.php', {
method: 'POST', method: 'POST',
body: formData body: formData
}) })
@@ -783,7 +784,7 @@ function validateTransfers(person, month) {
if(data.success) window.location.reload(); if(data.success) window.location.reload();
else alert("Erreur: " + data.error); else alert("Erreur: " + data.error);
}) })
.catch(e => alert(tr("bud_err_tech"))); .catch(e => alert(window.I18N['bud_err_tech']));
} }
function saveGenericNote(noteType, refId, content) { function saveGenericNote(noteType, refId, content) {
@@ -793,7 +794,7 @@ function saveGenericNote(noteType, refId, content) {
formData.append('reference_id', refId); formData.append('reference_id', refId);
formData.append('content', content); formData.append('content', content);
fetch('/modules/budget/includes/api/save-budget.php', { fetch('modules/budget/includes/api/save-budget.php', {
method: 'POST', method: 'POST',
body: formData body: formData
}) })
@@ -869,6 +870,36 @@ function updateSumResult() {
document.getElementById('sumResultValue').innerText = new Intl.NumberFormat(window.appLang, { style: 'currency', currency: 'EUR', maximumFractionDigits: 0 }).format(total); document.getElementById('sumResultValue').innerText = new Intl.NumberFormat(window.appLang, { style: 'currency', currency: 'EUR', maximumFractionDigits: 0 }).format(total);
} }
async function deleteCategory(id) {
if (!confirm(window.I18N['bud_prev_confirm_del_line'] || "Confirmer la suppression ?")) return;
const formData = new FormData();
formData.append('action', 'delete_category');
formData.append('id', id);
formData.append('ajax', '1');
try {
// 💡 CORRECTION : Chemin relatif (sans le "/" au début) pour s'adapter à ton localhost
const response = await fetch('modules/budget/includes/api/save-budget.php', {
method: 'POST',
body: formData
});
if (!response.ok) throw new Error(`Erreur réseau HTTP ${response.status}`);
const result = await response.json();
if (result.success) {
window.location.reload();
} else {
alert((window.I18N['bud_err_tech'] || 'Erreur technique') + " : Suppression impossible.");
}
} catch(e) {
console.error("Erreur Fetch Suppression:", e);
alert("Erreur de communication avec le serveur. Regarde la console (F12) pour plus de détails.");
}
}
document.addEventListener('click', function(e) { document.addEventListener('click', function(e) {
if (!isSumModeActive) return; if (!isSumModeActive) return;
@@ -890,4 +921,51 @@ document.addEventListener('click', function(e) {
}, true); }, true);
document.addEventListener('DOMContentLoaded', recalcAllAllocations); document.addEventListener('DOMContentLoaded', recalcAllAllocations);
// --- INTERCEPTION ASYNCHRONE DES FORMULAIRES DE MODALES ---
document.querySelectorAll('#addCatModal form, #editCatModal form').forEach(form => {
form.addEventListener('submit', async (e) => {
e.preventDefault(); // 🛑 Bloque le rechargement HTML par défaut
const submitBtn = form.querySelector('button[type="submit"]');
const originalText = submitBtn.innerText;
try {
submitBtn.disabled = true;
submitBtn.innerText = '⏳ ...';
const formData = new FormData(form);
formData.append('ajax', '1');
// 💡 CORRECTION DU PIÈGE : On utilise getAttribute() pour forcer la lecture de l'URL !
const actionUrl = form.getAttribute('action');
// On s'assure du bon chemin (chemin relatif depuis budget.php)
const finalUrl = actionUrl.startsWith('/') ? actionUrl.substring(1) : actionUrl;
const response = await fetch(finalUrl, {
method: 'POST',
body: formData
});
if (!response.ok) throw new Error(`Erreur HTTP: ${response.status}`);
const result = await response.json();
if (result.success) {
form.closest('.pf-modal').style.display = 'none';
document.body.classList.remove('no-scroll');
window.location.reload();
} else {
alert((window.I18N['bud_err_tech'] || 'Erreur technique') + " : " + (result.error || "Inconnue"));
}
} catch (error) {
console.error("Erreur Fetch Modale:", error);
alert("Une erreur technique est survenue lors de l'enregistrement.");
} finally {
submitBtn.disabled = false;
submitBtn.innerText = originalText;
}
});
});
</script> </script>
+34 -31
View File
@@ -104,12 +104,12 @@ function getMonthName($dateString) {
?> ?>
</div> </div>
<div class="month-actions" style="justify-content: center; width: 100%;"> <div class="month-actions" style="justify-content: center; width: 100%;">
<button class="btn-icon-small" title="<?= tr('bud_sav_edit_modal') ?>" <button class="btn-icon-small btn-safe-click" title="<?= tr('bud_sav_edit_modal') ?>"
data-json="<?= htmlspecialchars(json_encode($data[$month] ?? []), ENT_QUOTES, 'UTF-8') ?>" data-json="<?= htmlspecialchars(json_encode($data[$month] ?? []), ENT_QUOTES, 'UTF-8') ?>"
onclick='editCustomSavingsMonth("<?= $month ?>", "<?= $currentOwner ?>", JSON.parse(this.getAttribute("data-json")))'> onclick='editCustomSavingsMonth("<?= $month ?>", "<?= $currentOwner ?>", JSON.parse(this.getAttribute("data-json")))'>
✏️ ✏️
</button> </button>
<button class="btn-icon-small" title="<?= tr('bud_sav_delete_month') ?>" <button class="btn-icon-small btn-safe-click" title="<?= tr('bud_sav_delete_month') ?>"
onclick="deleteEntireMonth('<?= $month ?>', '<?= $currentOwner ?>')" onclick="deleteEntireMonth('<?= $month ?>', '<?= $currentOwner ?>')"
style="color: #ef4444; border-color: #fca5a5; background: #fef2f2;"> style="color: #ef4444; border-color: #fca5a5; background: #fef2f2;">
🗑️ 🗑️
@@ -187,7 +187,7 @@ function getMonthName($dateString) {
<button type="button" onclick="document.getElementById('savingsModal').style.display='none'; document.body.classList.remove('no-scroll');" style="border:none; background:none; font-size:1.8rem; cursor:pointer; color:#64748b; line-height:1;">&times;</button> <button type="button" onclick="document.getElementById('savingsModal').style.display='none'; document.body.classList.remove('no-scroll');" style="border:none; background:none; font-size:1.8rem; cursor:pointer; color:#64748b; line-height:1;">&times;</button>
</div> </div>
<form action="/modules/budget/includes/api/save-savings.php" method="POST" id="savingsForm"> <form action="modules/budget/includes/api/save-savings.php" method="POST" id="savingsForm">
<input type="hidden" name="owner" id="sav_owner"> <input type="hidden" name="owner" id="sav_owner">
<input type="hidden" name="redirect_tab" id="redirect_tab" value="<?= htmlspecialchars($requestedOwner) ?>"> <input type="hidden" name="redirect_tab" id="redirect_tab" value="<?= htmlspecialchars($requestedOwner) ?>">
<input type="hidden" name="month_date" id="sav_date_hidden"> <input type="hidden" name="month_date" id="sav_date_hidden">
@@ -248,16 +248,16 @@ function getMonthName($dateString) {
window.appLang = document.documentElement.lang === "ca" ? "ca-ES" : "fr-FR"; window.appLang = document.documentElement.lang === "ca" ? "ca-ES" : "fr-FR";
window.I18N = { window.I18N = {
...(window.I18N || {}), ...(window.I18N || {}),
'bud_sav_modal_title_add': "<?= tr('bud_sav_modal_title_add') ?>", 'bud_sav_modal_title_add': <?= json_encode(tr('bud_sav_modal_title_add')) ?>,
'bud_sav_modal_title_edit': "<?= tr('bud_sav_modal_title_edit') ?>", 'bud_sav_modal_title_edit': <?= json_encode(tr('bud_sav_modal_title_edit')) ?>,
'bud_sav_ph_name': "<?= tr('bud_sav_ph_name') ?>", 'bud_sav_ph_name': <?= json_encode(tr('bud_sav_ph_name')) ?>,
'bud_sav_confirm_delete_month': "<?= tr('bud_sav_confirm_delete_month') ?>", 'bud_sav_confirm_delete_month': <?= json_encode(tr('bud_sav_confirm_delete_month')) ?>,
'bud_sav_prompt_duplicate': "<?= tr('bud_sav_prompt_duplicate') ?>", 'bud_sav_prompt_duplicate': <?= json_encode(tr('bud_sav_prompt_duplicate')) ?>,
'bud_err_tech': "<?= tr('bud_err_tech') ?>", 'bud_err_tech': <?= json_encode(tr('bud_err_tech')) ?>,
'bud_err_server': "<?= tr('bud_err_server') ?>", 'bud_err_server': <?= json_encode(tr('bud_err_server')) ?>,
'bud_err_network_dup': "<?= tr('bud_err_network_dup') ?>", 'bud_err_network_dup': <?= json_encode(tr('bud_err_network_dup')) ?>,
'bud_sav_saving': "<?= tr('bud_sav_saving') ?>", 'bud_sav_saving': <?= json_encode(tr('bud_sav_saving')) ?>,
'bud_err_delete': "<?= tr('bud_err_delete') ?>" 'bud_err_delete': <?= json_encode(tr('bud_err_delete')) ?>
}; };
// --- 2. GESTION DE L'ÉDITION INVISIBLE EN DIRECT --- // --- 2. GESTION DE L'ÉDITION INVISIBLE EN DIRECT ---
@@ -272,10 +272,10 @@ function updateEpargneCell(month, category, owner, inputEl) {
formData.append('owner', owner); formData.append('owner', owner);
formData.append('amount', val); formData.append('amount', val);
fetch('/modules/budget/includes/api/save-savings.php', { fetch('modules/budget/includes/api/save-savings.php', {
method: 'POST', method: 'POST',
body: formData body: formData
}).catch(err => alert(tr("bud_err_tech"))); }).catch(err => alert(window.I18N['bud_err_tech'] || 'Erreur technique'));
const totalInput = document.querySelector(`.total-input-${owner}-${month}`); const totalInput = document.querySelector(`.total-input-${owner}-${month}`);
const totalVal = parseFloat(totalInput ? totalInput.value : 0) || 0; const totalVal = parseFloat(totalInput ? totalInput.value : 0) || 0;
@@ -304,7 +304,7 @@ function addCustomEpargneLine(catName = '', amount = '') {
const html = ` const html = `
<div class="ventilation-line" style="display:flex; gap:10px; align-items:center; background:#f8fafc; padding:8px; border-radius:8px; border:1px solid #e2e8f0;"> <div class="ventilation-line" style="display:flex; gap:10px; align-items:center; background:#f8fafc; padding:8px; border-radius:8px; border:1px solid #e2e8f0;">
<div style="flex:2;"> <div style="flex:2;">
<input type="text" class="pf-input cat-name-input" value="${catName}" placeholder="${tr("bud_sav_ph_name")}" oninput="updateCustomFieldName(this)" style="padding:6px; font-size:0.9rem;" required> <input type="text" class="pf-input cat-name-input" value="${catName}" placeholder="${window.I18N['bud_sav_ph_name'] || 'Catégorie'}" oninput="updateCustomFieldName(this)" style="padding:6px; font-size:0.9rem;" required>
</div> </div>
<div style="width:100px;"> <div style="width:100px;">
<input type="number" step="0.01" class="pf-input base-amount no-spinners" value="${baseAmount}" oninput="recalculateCustomLine(this)" style="padding:6px; font-size:0.9rem; background:#fff;"> <input type="number" step="0.01" class="pf-input base-amount no-spinners" value="${baseAmount}" oninput="recalculateCustomLine(this)" style="padding:6px; font-size:0.9rem; background:#fff;">
@@ -348,7 +348,7 @@ function editCustomSavingsMonth(monthDate, owner, rowData) {
const dateObj = new Date(monthDate); const dateObj = new Date(monthDate);
const monthName = dateObj.toLocaleDateString(window.appLang, { month: 'long', year: 'numeric' }); const monthName = dateObj.toLocaleDateString(window.appLang, { month: 'long', year: 'numeric' });
document.getElementById('savingsModalTitle').innerText = tr("bud_sav_modal_title_edit") + " " + monthName + " (" + owner + ")"; document.getElementById('savingsModalTitle').innerText = (window.I18N['bud_sav_modal_title_edit'] || 'Editer') + " " + monthName + " (" + owner + ")";
document.getElementById('sav_total').value = rowData['TOTAL_BANQUE'] || ''; document.getElementById('sav_total').value = rowData['TOTAL_BANQUE'] || '';
@@ -370,7 +370,7 @@ function openCustomSavingsModal(owner) {
document.getElementById('sav_month').value = ''; document.getElementById('sav_month').value = '';
document.getElementById('sav_total').value = ''; document.getElementById('sav_total').value = '';
document.getElementById('savingsModalTitle').innerText = tr("bud_sav_modal_title_add") + " (" + owner + ")"; document.getElementById('savingsModalTitle').innerText = (window.I18N['bud_sav_modal_title_add'] || 'Ajouter') + " (" + owner + ")";
const container = document.getElementById('linesContainer'); const container = document.getElementById('linesContainer');
container.innerHTML = ''; container.innerHTML = '';
@@ -400,17 +400,20 @@ if (savingsForm) {
const submitBtn = this.querySelector('button[type="submit"]'); const submitBtn = this.querySelector('button[type="submit"]');
const originalText = submitBtn.innerText; const originalText = submitBtn.innerText;
submitBtn.innerText = tr('bud_sav_saving'); submitBtn.innerText = window.I18N['bud_sav_saving'] || 'Sauvegarde...';
submitBtn.disabled = true; submitBtn.disabled = true;
const formData = new FormData(this); const formData = new FormData(this);
fetch(this.action, { method: 'POST', body: formData }) const actionUrl = this.getAttribute('action');
const finalUrl = actionUrl.startsWith('/') ? actionUrl.substring(1) : actionUrl;
fetch(finalUrl, { method: 'POST', body: formData })
.then(response => response.text()) .then(response => response.text())
.then(text => { window.location.reload(); }) .then(text => { window.location.reload(); })
.catch(error => { .catch(error => {
console.error("Erreur:", error); console.error("Erreur:", error);
alert(tr("bud_err_tech")); alert(window.I18N['bud_err_tech'] || 'Erreur Technique');
submitBtn.innerText = originalText; submitBtn.innerText = originalText;
submitBtn.disabled = false; submitBtn.disabled = false;
}); });
@@ -418,16 +421,18 @@ if (savingsForm) {
} }
function deleteEntireMonth(monthDate, owner) { function deleteEntireMonth(monthDate, owner) {
const msg = tr('bud_sav_confirm_delete_month').replace('%m', monthDate).replace('%o', owner); const rawMsg = window.I18N['bud_sav_confirm_delete_month'] || "Supprimer %m pour %o ?";
const msg = rawMsg.replace('%m', monthDate).replace('%o', owner);
if (!confirm(msg)) return; if (!confirm(msg)) return;
const formData = new FormData(); const formData = new FormData();
formData.append("action", "delete_month_global"); formData.append("action", "delete_month_global");
formData.append("month_date", monthDate); formData.append("month_date", monthDate);
formData.append("owner", owner); formData.append("owner", owner);
fetch("/modules/budget/includes/api/save-savings.php", { method: "POST", body: formData })
fetch("modules/budget/includes/api/save-savings.php", { method: "POST", body: formData })
.then(() => window.location.reload()) .then(() => window.location.reload())
.catch(err => alert(tr('bud_err_delete'))); .catch(err => alert(window.I18N['bud_err_delete'] || 'Erreur lors de la suppression'));
} }
function duplicateLastMonth(lastMonthDate, owner) { function duplicateLastMonth(lastMonthDate, owner) {
@@ -450,10 +455,8 @@ function duplicateLastMonth(lastMonthDate, owner) {
defaultTotal = cycleConfigs[nextMonthStr].start_balance; defaultTotal = cycleConfigs[nextMonthStr].start_balance;
} }
const message = tr('bud_sav_prompt_duplicate') const rawMsg = window.I18N['bud_sav_prompt_duplicate'] || "Dupliquer %s vers %t1 ?";
.replace('%s', sourceName) const message = rawMsg.replace('%s', sourceName).replace('%t1', targetName).replace('%t2', targetName);
.replace('%t1', targetName)
.replace('%t2', targetName);
let newTotal = prompt(message, defaultTotal); let newTotal = prompt(message, defaultTotal);
@@ -465,20 +468,20 @@ function duplicateLastMonth(lastMonthDate, owner) {
formData.append("new_total", newTotal); formData.append("new_total", newTotal);
formData.append("owner", owner); formData.append("owner", owner);
fetch("/modules/budget/includes/api/save-savings.php", { method: "POST", body: formData }) fetch("modules/budget/includes/api/save-savings.php", { method: "POST", body: formData })
.then(async r => { .then(async r => {
const text = await r.text(); const text = await r.text();
try { try {
const d = JSON.parse(text); const d = JSON.parse(text);
if (d.success) window.location.reload(); if (d.success) window.location.reload();
else alert(tr('bud_err_server') + (d.error || "Inconnue")); else alert((window.I18N['bud_err_server'] || 'Erreur serveur : ') + (d.error || "Inconnue"));
} catch(e) { } catch(e) {
window.location.reload(); window.location.reload();
} }
}) })
.catch(err => { .catch(err => {
console.error(err); console.error(err);
alert(tr("bud_err_network_dup")); alert(window.I18N['bud_err_network_dup'] || 'Erreur réseau.');
}); });
} }
} }
+61 -29
View File
@@ -57,36 +57,7 @@ if (isset($_POST['action']) && $_POST['action'] === 'reopen_month') {
exit; exit;
} }
if (isset($_POST['action']) && $_POST['action'] === 'save_expense_manual') {
$id = !empty($_POST['expense_id']) ? (int)$_POST['expense_id'] : null;
$cat = $_POST['category'];
$amount = floatval($_POST['amount']);
$date = $_POST['date'];
$gestionMonth = $_POST['gestion_month'];
$label = trim($_POST['label']);
$budgetItemId = null;
$holidayId = !empty($_POST['holiday_id']) ? (int)$_POST['holiday_id'] : null;
if ($cat === 'School' && !empty($_POST['label_select'])) $label = trim($_POST['label_select']);
elseif (($cat === 'Frais' || $cat === 'Income') && !empty($_POST['budget_item_id'])) $budgetItemId = (int)$_POST['budget_item_id'];
if ($label && $amount > 0) {
$is_credit = isset($_POST['is_credit']) ? (int)$_POST['is_credit'] : 0;
$finalAmount = $is_credit ? abs($amount) : -abs($amount);
if ($id) {
$pdo->prepare("UPDATE pf_expenses SET date_exp=?, gestion_month=?, category=?, label=?, amount=?, budget_item_id=?, holiday_id=? WHERE id=?")
->execute([$date, $gestionMonth, $cat, $label, $finalAmount, $budgetItemId, $holidayId, $id]);
} else {
$uniqueRef = "MANUAL_" . uniqid();
$pdo->prepare("INSERT INTO pf_expenses (date_exp, gestion_month, category, label, amount, import_ref, budget_item_id, holiday_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
->execute([$date, $gestionMonth, $cat, $label, $finalAmount, $uniqueRef, $budgetItemId, $holidayId]);
}
echo "<script>window.location.href='?tab=suivi&m=$viewM&y=$viewY';</script>";
exit;
}
}
if (isset($_POST['action']) && $_POST['action'] === 'save_import') { if (isset($_POST['action']) && $_POST['action'] === 'save_import') {
$count = 0; $count = 0;
@@ -766,4 +737,65 @@ function checkValidation() {
} }
if(document.getElementById('formMapping')) { document.querySelectorAll('.line-select').forEach(s => handleLineCatChange(s)); checkValidation(); } if(document.getElementById('formMapping')) { document.querySelectorAll('.line-select').forEach(s => handleLineCatChange(s)); checkValidation(); }
// Ferme la modale si on clique sur le background assombri (.pf-modal)
window.addEventListener('click', (e) => {
if (e.target.classList.contains('pf-modal')) {
e.target.style.display = 'none';
document.body.classList.remove('no-scroll');
}
});
document.addEventListener('DOMContentLoaded', () => {
const formExpense = document.querySelector('#manualExpenseModal form');
if (formExpense) {
formExpense.addEventListener('submit', async (e) => {
e.preventDefault(); // 🛑 On bloque le rechargement brutal de la page
const submitBtn = formExpense.querySelector('button[type="submit"]');
const originalBtnText = submitBtn.innerText;
try {
// 🛡️ Sécurité UI : on désactive le bouton pour éviter les doubles clics (et les doublons en BDD)
submitBtn.disabled = true;
submitBtn.innerText = '⏳ ...';
const formData = new FormData(formExpense);
// On s'assure que l'action est bien définie pour notre API
formData.set('action', 'save_expense_manual');
const response = await fetch('modules/budget/includes/api/manage-item.php', {
method: 'POST',
body: formData
});
if (!response.ok) throw new Error(`Erreur HTTP: ${response.status}`);
const result = await response.json();
if (result.success) {
// ✅ Succès : Fermeture propre de la modale
closeSuiviModal('manualExpenseModal');
formExpense.reset();
// Pour l'instant, on fait un rechargement propre pour voir les calculs à jour.
// Dans une V2 ultra-opti, on mettra à jour le DOM ligne par ligne ici !
window.location.reload();
} else {
// ❌ Erreur renvoyée par le PHP
const errorMsg = result.error || 'Erreur inconnue';
alert(window.I18N ? window.I18N.tr('error_occured') + ' : ' + errorMsg : errorMsg);
}
} catch (error) {
console.error("Erreur lors de l'enregistrement :", error);
alert("Une erreur critique est survenue côté réseau ou serveur.");
} finally {
// 🔄 On restaure le bouton dans tous les cas (succès ou échec)
submitBtn.disabled = false;
submitBtn.innerText = originalBtnText;
}
});
}
});
</script> </script>
+339
View File
@@ -0,0 +1,339 @@
/**
* PachaFamily - Test Engine 🦙
* Moteur de tests automatisés (E2E) - Version Anti-Flakiness
*/
const PachaTestEngine = {
arena: document.getElementById("test-arena"),
reportBox: document.getElementById("test-report"),
doc: null,
// ==========================================
// 🛠️ HELPERS
// ==========================================
wait: (ms) => new Promise((r) => setTimeout(r, ms)),
log: function (msg, icon = "️") {
this.reportBox.value += `[${new Date().toLocaleTimeString()}] ${icon} ${msg}\n`;
this.reportBox.scrollTop = this.reportBox.scrollHeight;
},
assert: function (cond, msgPass, msgFail) {
this.log(cond ? msgPass : msgFail || msgPass, cond ? "✅" : "❌");
},
// 🛡️ NOUVEAU : Attend le rechargement de la page après une action
actionAndWaitForReload: async function (actionFn, timeout = 5000) {
return new Promise(async (resolve) => {
let reloaded = false;
// On écoute le prochain rechargement de l'iframe
this.arena.onload = () => {
reloaded = true;
this.doc = this.arena.contentWindow.document;
this.arena.contentWindow.confirm = () => true;
this.arena.contentWindow.alert = () => true;
resolve();
};
await actionFn(); // On lance le clic ou la soumission
// Sécurité anti-blocage (si le fetch échoue et ne recharge pas la page)
setTimeout(() => {
if (!reloaded) {
this.log(
"⚠️ Le rechargement de la page n'a pas eu lieu dans le temps imparti.",
"⏱️",
);
resolve();
}
}, timeout);
});
},
load: async function (url) {
this.log(`Chargement de la page : ${url}`, "🔄");
return new Promise((resolve) => {
this.arena.onload = () => {
this.doc = this.arena.contentWindow.document;
this.arena.contentWindow.confirm = () => true;
this.arena.contentWindow.alert = () => true;
resolve();
};
this.arena.src = url;
});
},
get: function (sel) {
return this.doc.querySelector(sel);
},
// 🖱️ Clic unique et infaillible
click: async function (sel, delay = 500) {
const el = typeof sel === "string" ? this.get(sel) : sel;
if (el) {
// 1. Coupe les popups bloquantes
this.arena.contentWindow.confirm = () => true;
this.arena.contentWindow.alert = () => true;
// 2. Un seul et unique clic !
el.click();
await this.wait(delay);
return true;
}
return false;
},
fill: function (sel, val) {
const el = this.get(sel);
if (el) el.value = val;
},
select: async function (sel, val, delay = 300) {
const el = this.get(sel);
if (el) {
el.value = val;
el.dispatchEvent(new Event("change"));
await this.wait(delay);
}
},
findInTable: function (text) {
return Array.from(this.doc.querySelectorAll("td, div")).find((el) =>
el.textContent.includes(text),
);
},
// ==========================================
// 🧪 SCÉNARIO 1 : SUIVI MENSUEL
// ==========================================
runBudgetTests: async function () {
this.reportBox.value = "";
this.log("=== 🚀 DÉBUT DU SCÉNARIO : SUIVI BUDGET ===", "INFO");
await this.load("budget.php?tab=suivi");
await this.wait(1000);
if (!this.get(".btn-add-item")) {
this.log("Mois clôturé, test annulé. Déverrouille-le !", "⚠️");
return;
}
await this.click("button[onclick=\"toggleDiv('pendingDetailsList')\"]");
this.assert(
this.get("#pendingDetailsList").style.display !== "none",
"Déploiement : Charges à venir",
);
await this.click(".btn-add-item");
await this.select("#modalCatSelect", "Autres");
this.fill("#modalAmount", "42.42");
this.fill("#modalLabelInput", "TEST_AUTO_PACHA");
this.log("Enregistrement de la dépense...", "WARN");
await this.actionAndWaitForReload(async () => {
await this.click('#manualExpenseModal button[type="submit"]');
});
let targetTd = Array.from(this.doc.querySelectorAll("td")).find((el) =>
el.textContent.includes("TEST_AUTO_PACHA"),
);
this.assert(
targetTd !== undefined,
"Dépense créée avec succès (42.42€).",
"Échec : Dépense introuvable.",
);
if (targetTd) {
this.log("Nettoyage de la base de données...", "WARN");
await this.actionAndWaitForReload(async () => {
await this.click(
targetTd.closest("tr").querySelector('a[href*="delete_expense"]'),
);
});
const checkGone = Array.from(this.doc.querySelectorAll("td")).find((el) =>
el.textContent.includes("TEST_AUTO_PACHA"),
);
this.assert(
checkGone === undefined,
"Base de données nettoyée avec succès.",
);
}
this.log("=== 🏁 FIN DU SCÉNARIO ===", "INFO");
},
// ==========================================
// 🧪 SCÉNARIO 2 : BUDGET PRÉVISIONNEL
// ==========================================
testBudgetPrev: async function () {
this.reportBox.value = "";
this.log("=== 🚀 DÉBUT DU SCÉNARIO : BUDGET PRÉVISIONNEL ===", "INFO");
await this.load("budget.php?tab=budget_prev");
await this.wait(1000);
this.log("🔍 Étape 1 : Test du mode Somme flottant...", "INFO");
await this.click("#fabSumMode");
this.assert(
this.doc.body.classList.contains("sum-mode-active"),
"Le mode somme s'active.",
"Le bouton somme ne répond pas.",
);
const firstSalaryInput = this.get('input[data-field="salary"]');
if (firstSalaryInput) {
await this.click(firstSalaryInput, 500);
this.assert(
firstSalaryInput.classList.contains("sum-selected"),
"La cellule est bien sélectionnée.",
);
const sumValue = this.get("#sumResultValue").innerText;
this.assert(
sumValue !== "0,00 €" && sumValue !== "0 €",
`Le total interactif affiche : ${sumValue}`,
"Le calcul de la somme a échoué.",
);
}
await this.click(".pf-sum-close");
this.assert(
!this.doc.body.classList.contains("sum-mode-active"),
"Le mode somme se désactive.",
);
this.log("🔍 Étape 2 : Test de sauvegarde de la note...", "INFO");
const noteArea = this.get("#monthNoteArea");
if (noteArea) {
const oldNote = noteArea.value;
this.fill("#monthNoteArea", "🤖 Test Auto");
await this.click('button[onclick^="saveGenericNote"]', 1500);
const indicator = this.get("#note-save-indicator");
this.assert(
indicator !== null,
"Sauvegarde asynchrone exécutée.",
"L'indicateur de sauvegarde ne s'est pas affiché.",
);
this.fill("#monthNoteArea", oldNote);
await this.click('button[onclick^="saveGenericNote"]', 500);
}
const uniqueCatName = "TEST_CAT_" + Math.floor(Math.random() * 10000);
this.log(
`🔍 Étape 3 : Création de la catégorie '${uniqueCatName}'...`,
"INFO",
);
await this.click('button[onclick*="addCatModal"]');
this.assert(
this.get("#addCatModal").style.display === "flex",
"Ouverture de la modale d'ajout.",
);
this.fill('#addCatModal input[name="name"]', uniqueCatName);
await this.select('#addCatModal select[name="target"]', "vers commune");
this.log("Attente du rechargement après création...", "WARN");
// 🔄 UTILISATION DU NOUVEAU HELPER SYNCHRONE
await this.actionAndWaitForReload(async () => {
await this.click('#addCatModal button[type="submit"]');
});
const newCatCell = Array.from(
this.doc.querySelectorAll(".prev-alloc-table td, .prev-alloc-table div"),
).find((el) => el.textContent.includes(uniqueCatName));
this.assert(
newCatCell !== undefined,
`SUCCÈS : '${uniqueCatName}' insérée au tableau !`,
"ÉCHEC : Ligne introuvable après rechargement.",
);
if (newCatCell) {
this.log("🧹 Étape 4 : Nettoyage de la BDD...", "WARN");
const row = newCatCell.closest("tr");
const delBtn = row.querySelector(".delete");
if (delBtn) {
// 🔄 UTILISATION DU NOUVEAU HELPER SYNCHRONE
await this.actionAndWaitForReload(async () => {
await this.click(delBtn);
});
const checkGone = Array.from(
this.doc.querySelectorAll(".prev-alloc-table td"),
).find((td) => td.textContent.includes(uniqueCatName));
this.assert(
checkGone === undefined,
"NETTOYAGE PARFAIT : Ligne effacée.",
"La ligne est restée dans le tableau.",
);
} else {
this.log("Bouton de suppression (.delete) introuvable.", "FAIL");
}
}
this.log("=== 🏁 FIN DU SCÉNARIO ===", "INFO");
},
};
// ============================================================================
// ROUTEUR DU LABORATOIRE ET BOUTON COPIER
// ============================================================================
document.getElementById("btn-run-test")?.addEventListener("click", async () => {
const selectedTest = document.getElementById("test-selector").value;
const btnRun = document.getElementById("btn-run-test");
btnRun.disabled = true;
btnRun.style.opacity = "0.5";
try {
switch (selectedTest) {
case "budget_suivi":
await PachaTestEngine.runBudgetTests();
break;
case "budget_prev":
await PachaTestEngine.testBudgetPrev();
break;
default:
PachaTestEngine.log(`Scénario non implémenté : ${selectedTest}`, "⚠️");
}
} catch (error) {
PachaTestEngine.log(`Erreur JS critique : ${error.message}`, "❌");
console.error(error);
}
btnRun.disabled = false;
btnRun.style.opacity = "1";
});
// 📋 Bouton "Copier"
document
.getElementById("btn-copy-report")
?.addEventListener("click", async () => {
const textArea = document.getElementById("test-report");
const reportText = textArea.value;
const successMsg = window.I18N
? window.I18N.tests_report_copied || "Rapport copié !"
: "Rapport copié !";
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(reportText);
alert(successMsg);
} else {
textArea.select();
document.execCommand("copy");
window.getSelection().removeAllRanges();
alert(successMsg);
}
} catch (err) {
alert("Erreur lors de la copie du rapport.");
console.error(err);
}
});
+139
View File
@@ -0,0 +1,139 @@
<?php
require_once 'includes/auth.php';
require_once 'includes/db.php';
require_once 'includes/i18n.php';
require_once 'header.php';
?>
<style>
/* Styles spécifiques au Laboratoire (Look IDE) */
.lab-select {
padding: 6px 32px 6px 12px; /* Espace à droite pour la flèche */
font-size: 0.85rem;
font-weight: 600;
color: #334155;
background-color: #ffffff;
border: 1px solid #cbd5e1;
border-radius: 6px;
cursor: pointer;
appearance: none; /* Supprime la flèche par défaut du navigateur */
-webkit-appearance: none;
-moz-appearance: none;
/* Ajout d'une flèche SVG sur-mesure */
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%2364748b'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 8px center;
background-size: 14px;
transition: all 0.2s ease;
box-shadow: 0 1px 2px rgba(0,0,0,0.02);
}
.lab-select:hover {
border-color: #94a3b8;
}
.lab-select:focus {
outline: none;
border-color: #3b82f6;
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
.lab-container {
max-width: 1400px;
margin: 0 auto;
display: flex;
gap: 20px;
height: 75vh; /* Prend une bonne partie de l'écran */
}
.lab-panel {
flex: 1;
display: flex;
flex-direction: column;
background: #ffffff;
border: 1px solid #e2e8f0;
border-radius: 8px;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
overflow: hidden;
}
.lab-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 15px;
background: #f8fafc;
border-bottom: 1px solid #e2e8f0;
}
.lab-title { margin: 0; font-size: 1.1rem; color: #334155; display: flex; align-items: center; gap: 8px; }
/* Boutons de contrôle minimalistes */
.lab-controls { display: flex; gap: 8px; }
.btn-lab {
padding: 6px 12px;
font-size: 0.85rem;
border-radius: 6px;
cursor: pointer;
border: none;
font-weight: 600;
transition: 0.2s;
display: flex; align-items: center; gap: 5px;
}
.btn-play { background: #eff6ff; color: #2563eb; border: 1px solid #bfdbfe; }
.btn-play:hover { background: #dbeafe; }
.btn-copy { background: #f0fdf4; color: #16a34a; border: 1px solid #bbf7d0; }
.btn-copy:hover { background: #dcfce7; }
/* Terminal Console */
.lab-console {
flex: 1;
width: 100%;
padding: 15px;
background: #1e1e1e;
color: #10b981;
font-family: 'Courier New', Courier, monospace;
font-size: 0.9rem;
border: none;
resize: none;
outline: none;
}
</style>
<section class="pf-section lab-container">
<div class="lab-panel">
<div class="lab-header">
<h2 class="lab-title">🧪 <?= tr('tests_title') ?></h2>
<div class="lab-controls" style="display: flex; align-items: center; gap: 10px;">
<select id="test-selector" class="lab-select">
<optgroup label="💰 Module Budget">
<option value="budget_suivi">Suivi Mensuel (Dépenses)</option>
<option value="budget_prev">Budget Prévisionnel</option>
<option value="budget_epargne" disabled>Épargne (Bientôt...)</option>
<option value="budget_recap" disabled>Récapitulatif (Bientôt...)</option>
</optgroup>
<optgroup label="📅 Autres Modules">
<option value="calendar" disabled>Calendrier Familial (Bientôt...)</option>
<option value="holidays" disabled>Voyages & Roadtrips (Bientôt...)</option>
<option value="gifts" disabled>Liste de Cadeaux (Bientôt...)</option>
</optgroup>
</select>
<button id="btn-run-test" class="btn-lab btn-play">▶ Lancer le test</button>
<button id="btn-test-all" class="btn-lab btn-play" style="opacity: 0.5; cursor: not-allowed;" title="Bientôt disponible">▶ Tout lancer</button>
<button id="btn-copy-report" class="btn-lab btn-copy">📋 <?= tr('tests_copy_report') ?></button>
</div>
</div>
<textarea id="test-report" class="lab-console" readonly><?= tr('tests_waiting') ?></textarea>
</div>
<div class="lab-panel">
<div class="lab-header" style="background: #f1f5f9; justify-content: center;">
<span style="font-size: 0.8rem; color: #64748b; font-weight: bold; text-transform: uppercase; letter-spacing: 1px;">Live Preview</span>
</div>
<iframe id="test-arena" style="width: 100%; height: 100%; border: none;"></iframe>
</div>
</section>
<script src="test-engine.js"></script>
<?php require_once 'footer.php'; ?>