FixBug: Décalrage de date des prêts différés

This commit is contained in:
2026-07-12 17:58:28 +02:00
parent ec3c7f7cab
commit 794f8684a2
3 changed files with 211 additions and 17 deletions
+50 -14
View File
@@ -227,27 +227,45 @@ if (rembCols.includes('autres_taxes')) {
}
// ── Migration : renommage date_debut → date_premiere_echeance, date_echeance → date_cible ──
//
// ATTENTION (bug corrigé le 12/07/2026) : le bloc de "correction de formule" ci-dessous
// (SET date_cible = date_premiere_echeance + (duree_mois-1) mois, SANS clause IS NULL)
// s'exécutait auparavant à CHAQUE démarrage du serveur, pour TOUS les investissements,
// quel que soit type_remb. Combiné à la migration suivante (qui recopie date_cible dans
// date_premiere_echeance pour les prêts différés), cela créait une boucle : à chaque
// redémarrage, date_cible dérivait de +(duree_mois-1) mois supplémentaires, sans jamais
// être tracé dans investissement_historique. C'est la cause des dates aberrantes (parfois
// des siècles dans le futur) observées sur les prêts différés. La correction ne doit
// s'exécuter qu'UNE SEULE FOIS, au moment réel du renommage de colonne — jamais après.
{
const cols = db.prepare('PRAGMA table_info(investissements)').all().map(c => c.name);
const migrationEnCours = cols.includes('date_debut') || cols.includes('date_echeance');
if (cols.includes('date_debut')) {
db.exec('ALTER TABLE investissements RENAME COLUMN date_debut TO date_premiere_echeance');
}
if (cols.includes('date_echeance')) {
db.exec('ALTER TABLE investissements RENAME COLUMN date_echeance TO date_cible');
}
// Backfill date_premiere_echeance = souscription + 1 mois si vide
// Backfill date_premiere_echeance = souscription + 1 mois si vide (idempotent : ne touche
// jamais une valeur déjà renseignée)
db.exec(`UPDATE investissements
SET date_premiere_echeance = date(date_souscription, '+1 month')
WHERE date_premiere_echeance IS NULL AND date_souscription IS NOT NULL`);
// Backfill date_cible = date_premiere_echeance + (duree_mois - 1) mois si vide
// Backfill date_cible = date_premiere_echeance + (duree_mois - 1) mois si vide (idempotent)
// Formule cohérente avec la simulation : échéance 1 = date_premiere_echeance, dernière = +duree-1 mois
db.exec(`UPDATE investissements
SET date_cible = date(date_premiere_echeance, '+' || (duree_mois - 1) || ' months')
WHERE date_cible IS NULL AND date_premiere_echeance IS NOT NULL AND duree_mois IS NOT NULL`);
// Correction des date_cible déjà calculées avec l'ancienne formule (+duree_mois au lieu de +duree_mois-1)
db.exec(`UPDATE investissements
SET date_cible = date(date_premiere_echeance, '+' || (duree_mois - 1) || ' months')
WHERE date_premiere_echeance IS NOT NULL AND duree_mois IS NOT NULL`);
// Correction ponctuelle des date_cible déjà calculées avec l'ancienne formule
// (+duree_mois au lieu de +duree_mois-1) — ne s'exécute que le jour du renommage effectif
// des colonnes (migrationEnCours), jamais à chaque démarrage.
if (migrationEnCours) {
db.exec(`UPDATE investissements
SET date_cible = date(date_premiere_echeance, '+' || (duree_mois - 1) || ' months')
WHERE date_premiere_echeance IS NOT NULL AND duree_mois IS NOT NULL`);
}
}
// ── Migration : type_remb 'mensuel' → 'amortissable' + ajout freq_interets ──
@@ -275,19 +293,37 @@ if (!rembCols2.includes('interets_nets')) {
// ── Migration : prêts différés — date_premiere_echeance doit égaler date_cible ──
// (versement unique à l'échéance : les deux dates sont identiques)
{
const needsFix = db.prepare(`
SELECT COUNT(*) AS n FROM investissements
const aCorriger = db.prepare(`
SELECT id, nom_projet, date_premiere_echeance, date_cible
FROM investissements
WHERE type_remb = 'differe'
AND date_cible IS NOT NULL
AND (date_premiere_echeance IS NULL OR date_premiere_echeance != date_cible)
`).get().n;
`).all();
if (needsFix > 0) {
db.exec(`
UPDATE investissements
SET date_premiere_echeance = date_cible
WHERE type_remb = 'differe' AND date_cible IS NOT NULL
if (aCorriger.length > 0) {
const updateStmt = db.prepare(`
UPDATE investissements SET date_premiere_echeance = date_cible WHERE id = ?
`);
const histStmt = db.prepare(`
INSERT INTO investissement_historique (investissement_id, type_evenement, changements, notes)
VALUES (?, 'correction_auto_echeancier', ?, ?)
`);
for (const inv of aCorriger) {
updateStmt.run(inv.id);
histStmt.run(
inv.id,
JSON.stringify([{
champ: 'date_premiere_echeance',
label: 'Date 1ère échéance',
ancienne_valeur: inv.date_premiere_echeance,
nouvelle_valeur: inv.date_cible,
}]),
"Migration au démarrage : synchronisation avec date_cible (prêt différé — les deux dates doivent être identiques)",
);
}
// Régénère les simulations avec la nouvelle logique (date = startDate directement)
const differeInvs = db.prepare(`
SELECT id, montant_investi, taux_interet, duree_mois, type_remb, freq_interets,
+82 -1
View File
@@ -3,7 +3,8 @@ import { z } from 'zod';
import db from '../db/index.js';
import { HttpError } from '../middleware/errorHandler.js';
import { requireInvestisseur } from '../middleware/investisseurScope.js';
import { generateSimul } from '../utils/schedule.js';
import { generateSimul, generateSimulWithReinvestissements } from '../utils/schedule.js';
import { checkStatutsRetard } from '../jobs/autoStatut.js';
const router = Router();
@@ -275,6 +276,86 @@ router.post('/fix-differe-dates', (req, res, next) => {
}
}
// Une date corrigée peut désormais être passée (prêt qui bascule en retard) ou au
// contraire future (prêt qui en sort) — on relance immédiatement la vérification de
// statut plutôt que d'attendre le prochain passage du job (minuit / redémarrage serveur),
// sinon le prêt affiche un statut incohérent avec sa date jusqu'au lendemain.
const statutsMisAJour = corriges.length > 0 ? checkStatutsRetard() : 0;
res.json({ updated: corriges.length, detail: corriges, statutsMisAJour });
} catch (err) {
next(err);
}
});
// POST /api/investissements/check-echeancier-differe
// Vérifie, pour chaque prêt différé, que l'échéancier de projection (simul_remboursements)
// contient bien une unique échéance dont la date correspond à date_premiere_echeance
// (== date_cible pour un prêt différé). Régénère l'échéancier sinon — utile après un
// import, une restauration, ou tout chemin ayant modifié les dates sans régénérer la
// simulation associée (cf. bouton "Corriger les dates des prêts différés" ci-dessus,
// qui ne couvre que l'écart date_souscription + durée > 2 ans).
router.post('/check-echeancier-differe', (req, res, next) => {
try {
const rows = db.prepare(`
SELECT i.id, i.nom_projet, i.date_premiere_echeance, i.date_cible,
i.montant_investi, i.taux_interet, i.duree_mois, i.type_remb, i.freq_interets,
i.date_debut_simul, i.date_souscription, i.echeance_fin_de_mois
FROM investissements i
JOIN investisseurs inv ON inv.id = i.investisseur_id AND inv.user_id = ?
WHERE i.type_remb = 'differe'
AND i.date_premiere_echeance IS NOT NULL
AND i.taux_interet IS NOT NULL
AND i.duree_mois IS NOT NULL
`).all(req.user.id);
const getSimul = db.prepare(`
SELECT id, numero_echeance, date_prevue
FROM simul_remboursements
WHERE investissement_id = ?
ORDER BY numero_echeance
`);
const hasReinvest = db.prepare('SELECT 1 FROM reinvestissements WHERE investissement_id = ? LIMIT 1');
const corriges = [];
for (const inv of rows) {
const simulRows = getSimul.all(inv.id);
const incoherent =
simulRows.length !== 1 ||
simulRows[0].date_prevue !== inv.date_premiere_echeance;
if (!incoherent) continue;
const ancienEcheancier = simulRows.length === 0
? 'aucune échéance'
: simulRows.map(s => `${s.date_prevue} (n°${s.numero_echeance})`).join(', ');
if (hasReinvest.get(inv.id)) {
generateSimulWithReinvestissements(db, inv.id);
} else {
generateSimul(db, inv);
}
recordHistory(inv.id, {
type_evenement: 'correction_auto_echeancier',
changements: [{
champ: 'echeancier',
label: 'Échéancier de projection',
ancienne_valeur: ancienEcheancier,
nouvelle_valeur: inv.date_premiere_echeance,
}],
notes: "Correction automatique (Nettoyage > Vérifier la cohérence de l'échéancier des prêts différés)",
});
corriges.push({
id: inv.id,
nom_projet: inv.nom_projet,
ancien_echeancier: ancienEcheancier,
nouvelle_date: inv.date_premiere_echeance,
});
}
res.json({ updated: corriges.length, detail: corriges });
} catch (err) {
next(err);