Spaces:
Sleeping
Sleeping
File size: 30,004 Bytes
e9d7265 9daebd1 e9d7265 1216eb5 0505dd9 1216eb5 0505dd9 2850f34 e9d7265 2850f34 e9d7265 9daebd1 e9d7265 9daebd1 1216eb5 9daebd1 e9d7265 c7b7e1d e9d7265 c7b7e1d e9d7265 c7b7e1d e9d7265 c7b7e1d e9d7265 c930f50 e9d7265 c930f50 e9d7265 0505dd9 9daebd1 0505dd9 9daebd1 0505dd9 e9d7265 0505dd9 e9d7265 4a32d7b e9d7265 13b7fd7 e9d7265 13b7fd7 e9d7265 13b7fd7 e9d7265 13b7fd7 e9d7265 0505dd9 9daebd1 e9d7265 4a32d7b e9d7265 1bdbe1a e9d7265 c7b7e1d e9d7265 4a32d7b e9d7265 1084c24 1bdbe1a 4a32d7b c7b7e1d 4a32d7b e9d7265 13b7fd7 e9d7265 13b7fd7 e9d7265 13b7fd7 9b995d0 13b7fd7 2b8c508 13b7fd7 2b8c508 13b7fd7 2b8c508 13b7fd7 9b995d0 e9d7265 13b7fd7 9daebd1 13b7fd7 9b995d0 9daebd1 13b7fd7 9daebd1 9b995d0 9daebd1 9b995d0 13b7fd7 9daebd1 13b7fd7 9daebd1 13b7fd7 9daebd1 13b7fd7 9daebd1 13b7fd7 9daebd1 9b995d0 13b7fd7 9b995d0 13b7fd7 9b995d0 9daebd1 13b7fd7 9daebd1 13b7fd7 c7b7e1d e9d7265 1084c24 4a32d7b e9d7265 9daebd1 4a32d7b e9d7265 9daebd1 e9d7265 9daebd1 e9d7265 9daebd1 e9d7265 9daebd1 4a32d7b c7b7e1d e9d7265 9daebd1 e9d7265 1bdbe1a e9d7265 c7b7e1d e9d7265 4a32d7b e9d7265 9daebd1 e9d7265 1bdbe1a e9d7265 c7b7e1d e9d7265 4a32d7b e9d7265 9daebd1 e9d7265 9daebd1 4a32d7b c7b7e1d e9d7265 1bdbe1a e9d7265 c7b7e1d e9d7265 4a32d7b e9d7265 9daebd1 e9d7265 9daebd1 e9d7265 9daebd1 e9d7265 9daebd1 e9d7265 9daebd1 e9d7265 9daebd1 e9d7265 1216eb5 9daebd1 1216eb5 e9d7265 9daebd1 1216eb5 e9d7265 9daebd1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 | const express = require("express");
const Database = require("better-sqlite3");
const { installAuth } = require("./auth");
const path = require("path");
const fs = require("fs");
const multer = require("multer");
const app = express();
const PORT = process.env.PORT || 7860;
const APP_ROOT = path.resolve(__dirname, "..");
const SQLITE_PATH =
process.env.SQLITE_PATH || path.join(APP_ROOT, "data", "immobilier.sqlite");
const UPLOAD_DIR =
process.env.UPLOAD_DIR || path.join(APP_ROOT, "resources", "uploads");
const PUBLIC_UPLOAD_DIR = "resources/uploads";
const MAX_FILE_COUNT = process.env.MAX_FILE_COUNT || 20;
if (!fs.existsSync(UPLOAD_DIR)) {
fs.mkdirSync(UPLOAD_DIR, { recursive: true });
}
const storage = multer.diskStorage({
destination: (_req, _file, cb) => cb(null, UPLOAD_DIR),
filename: (_req, file, cb) => {
const safeBase =
path
.basename(file.originalname, path.extname(file.originalname))
.replace(/[^a-z0-9_-]+/gi, "_")
.replace(/^_+|_+$/g, "")
.slice(0, 40) || "image";
const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;
cb(
null,
`${safeBase}-${uniqueSuffix}${path.extname(file.originalname).toLowerCase()}`,
);
},
});
const upload = multer({
storage,
limits: {
fileSize: 10 * 1024 * 1024,
files: MAX_FILE_COUNT,
},
fileFilter: (_req, file, cb) => {
cb(null, file.mimetype.startsWith("image/"));
},
});
// ─── Middleware ───────────────────────────────────────────────────────────────
app.use(express.json());
// Only application assets are public; never expose the database or server sources.
for (const asset of ["index.html", "index.js", "style.css"]) {
app.get(asset === "index.html" ? ["/", "/index.html"] : `/${asset}`, (_req, res) => {
res.sendFile(path.join(APP_ROOT, asset));
});
}
// ─── Base de données SQLite ───────────────────────────────────────────────────
fs.mkdirSync(path.dirname(SQLITE_PATH), { recursive: true });
const db = new Database(SQLITE_PATH);
db.pragma("foreign_keys = ON");
// ===== CONFIGURATEUR DE COÛT DE CHAUFFAGE =====
/**
* Estime le coût mensuel moyen de chauffage en fonction :
* - Type d'énergie (gaz, électricité, bois, fioul)
* - Superficie (m²)
* - Classe DPE (A à G)
*
* @param {string} typeEnergie - 'gaz', 'electricite_direct', 'electricite_pac', 'bois', 'fioul'
* @param {number} superficie - Surface en m²
* @param {string} classeDpe - 'A', 'B', 'C', 'D', 'E', 'F', 'G'
* @returns {object} { coutMensuel: number, coutAnnuel: number, details: object }
*/
function estimerCoutChauffage(typeEnergie, superficie, classeDpe) {
// Données de consommation par classe DPE (kWhEP/m²/an)
const dpeConsumption = {
A: 70,
B: 110,
C: 180,
D: 250,
E: 330,
F: 420,
G: 450 // Seuil minimal pour la classe G
};
// Profils énergétiques (rendement et prix en €/kWhEF)
// Les prix sont estimés pour 2026 et peuvent être ajustés
const energyProfiles = {
gaz: { rendement: 0.92, prixKwh: 0.14 }, // Chaudière gaz condensation
electricite_direct: { rendement: 1.0, prixKwh: 0.22 }, // Radiateurs électriques
electricite_pac: { rendement: 3.0, prixKwh: 0.22 }, // Pompe à chaleur (COP = 3)
bois: { rendement: 0.8, prixKwh: 0.08 }, // Poêle ou chaudière à granulés
fioul: { rendement: 0.85, prixKwh: 0.12 } // Chaudière fioul
};
// Vérification des entrées
if (!dpeConsumption.hasOwnProperty(classeDpe)) {
throw new Error("Classe DPE invalide. Utilisez 'A', 'B', 'C', 'D', 'E', 'F' ou 'G'.");
}
if (!energyProfiles.hasOwnProperty(typeEnergie)) {
throw new Error("Type d'énergie invalide. Utilisez 'gaz', 'electricite_direct', 'electricite_pac', 'bois' ou 'fioul'.");
}
if (superficie <= 0) {
throw new Error("La superficie doit être positive.");
}
// Calcul de la consommation annuelle
const kwhEpParM2 = dpeConsumption[classeDpe];
const kwhEpTotal = kwhEpParM2 * superficie;
// Conversion en énergie finale (kWhEF) et coût
const profile = energyProfiles[typeEnergie];
const kwhEfTotal = kwhEpTotal / profile.rendement;
const coutAnnuel = kwhEfTotal * profile.prixKwh;
const coutMensuel = coutAnnuel / 12;
// Détails pour l'utilisateur
const details = {
consommationEpAnnuelle: kwhEpTotal,
consommationEfAnnuelle: parseFloat(kwhEfTotal.toFixed(2)),
rendement: profile.rendement,
prixKwhEf: profile.prixKwh,
typeEnergie: typeEnergie,
classeDpe: classeDpe,
superficie: superficie
};
return {
coutMensuel: parseFloat(coutMensuel.toFixed(2)),
coutAnnuel: parseFloat(coutAnnuel.toFixed(2)),
details: details
};
}
// ===== FIN DU CONFIGURATEUR =====
function parseJsonArray(value) {
if (Array.isArray(value)) return value;
if (!value) return [];
if (typeof value !== "string") return [];
try {
const parsed = JSON.parse(value);
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
function parseEnergyItems(value) {
if (Array.isArray(value)) {
return value
.map((entry) => ({
type: String(entry?.type || "").trim(),
amount: Number(entry?.amount) || 0,
}))
.filter((entry) => entry.amount > 0);
}
if (!value) return [];
if (typeof value !== "string") return [];
try {
const parsed = JSON.parse(value);
return parseEnergyItems(parsed);
} catch {
return [];
}
}
function legacyEnergyItemsFromFiche(fiche) {
const amount =
fiche.facture_energie_mensuelle != null
? Number(fiche.facture_energie_mensuelle)
: Number(String(fiche.facture_energie_exemple).match(/\d+/)?.[0] || 0);
if (!(amount > 0)) return [];
const type = String(fiche.facture_energie_type || "").trim();
return [{ type, amount }];
}
function hydrateFiche(fiche, imageRows = []) {
if (!fiche) return fiche;
const energyItems = parseEnergyItems(fiche.facture_energie_items);
const normalizedEnergyItems = energyItems.length
? energyItems
: legacyEnergyItemsFromFiche(fiche);
return {
...fiche,
facture_energie_items: normalizedEnergyItems,
images: imageRows.map((row) => row.path),
image_ids: imageRows.map((row) => row.id),
};
}
function parseRequestPayload(req) {
if (typeof req.body?.payload === "string") {
const payload = JSON.parse(req.body.payload || "{}");
return {
payload,
existingImages: parseJsonArray(req.body.existing_images),
removedImages: parseJsonArray(req.body.removed_images),
};
}
return {
payload: req.body || {},
existingImages: parseJsonArray(req.body?.existing_images),
removedImages: parseJsonArray(req.body?.removed_images),
};
}
function toPublicUploadPath(filename) {
return `${PUBLIC_UPLOAD_DIR}/${filename}`;
}
function resolveStoredImagePath(relativePath) {
const normalizedPath = String(relativePath || "").replace(/^\/+/, "");
const uploadPrefix = `${PUBLIC_UPLOAD_DIR}/`;
if (normalizedPath.startsWith(uploadPrefix)) {
const filename = normalizedPath.slice(uploadPrefix.length);
if (filename && filename === path.basename(filename)) return path.join(UPLOAD_DIR, filename);
}
return null;
}
function mergeImages(existingImages, files = []) {
return [
...parseJsonArray(existingImages),
...files.map((file) => toPublicUploadPath(file.filename)),
];
}
function normalizeFicheStatus(status) {
const allowed = new Set([
"a_traiter",
"en_cours",
"dossier_envoye",
"visite_prevue",
"valide",
"archive",
"abandonne",
]);
return allowed.has(status) ? status : "a_traiter";
}
function getImagesByFicheId(ficheId) {
return db
.prepare(
`
SELECT id, path, sort_order
FROM fiche_images
WHERE fiche_id = ?
ORDER BY sort_order ASC, created_at ASC, id ASC
`,
)
.all(ficheId);
}
function replaceFicheImages(ficheId, imagePaths) {
const normalized = Array.from(
new Set(parseJsonArray(imagePaths).filter(Boolean)),
);
const deleteStmt = db.prepare("DELETE FROM fiche_images WHERE fiche_id = ?");
const insertStmt = db.prepare(
"INSERT INTO fiche_images (fiche_id, path, sort_order) VALUES (?, ?, ?)",
);
const tx = db.transaction(() => {
deleteStmt.run(ficheId);
normalized.forEach((pathValue, index) => {
insertStmt.run(ficheId, pathValue, index);
});
});
tx();
}
function removeStoredImages(imageList) {
parseJsonArray(imageList).forEach((relativePath) => {
const absolutePath = resolveStoredImagePath(relativePath);
const stillUsed = db.prepare("SELECT 1 FROM fiche_images WHERE path = ? LIMIT 1").get(relativePath);
if (absolutePath && !stillUsed && fs.existsSync(absolutePath)) {
fs.unlinkSync(absolutePath);
}
});
}
db.exec(`
CREATE TABLE IF NOT EXISTS fiches (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TEXT DEFAULT (datetime('now', 'localtime')),
-- Identité du bien
adresse TEXT,
date_visite TEXT,
heure_visite TEXT,
contact_nom TEXT,
contact_tel TEXT,
-- Recherche, type & surface
type_search TEXT DEFAULT '', -- location / achat
type_logement TEXT, -- studio / t1t2 / t3plus
surface REAL,
etage TEXT,
-- Bail
type_bail TEXT, -- meuble / vide
-- Achat
taxe_fonciere REAL,
-- Financier
loyer_hc REAL,
charges REAL,
charges_eau_froide INTEGER DEFAULT 0,
charges_eau_chaude INTEGER DEFAULT 0,
charges_chauffage INTEGER DEFAULT 0,
charges_elec INTEGER DEFAULT 0,
loyer_cc REAL,
depot_garantie REAL,
frais_agence REAL,
disponibilite TEXT,
-- Chauffage
chauffage_type TEXT, -- electrique / gaz / fioul
-- Énergie & équipements
facture_energie_type TEXT,
facture_energie_mensuelle REAL,
facture_energie_items TEXT DEFAULT '[]',
facture_energie_exemple TEXT,
fibre_optique INTEGER DEFAULT 0, -- 0/1
-- Stationnement
parking_garage INTEGER DEFAULT 0,
parking_reserve INTEGER DEFAULT 0,
parking_rue INTEGER DEFAULT 0,
-- Stockage
cave INTEGER DEFAULT 0,
grenier INTEGER DEFAULT 0,
-- Notes (1-5)
note_etat_general INTEGER,
note_luminosite INTEGER,
note_isolation INTEGER,
note_cuisine INTEGER,
note_rangements INTEGER,
note_emplacement INTEGER,
note_flexibilite INTEGER,
-- Commentaires par critère
comment_etat_general TEXT,
comment_luminosite TEXT,
comment_isolation TEXT,
comment_cuisine TEXT,
comment_rangements TEXT,
comment_emplacement TEXT,
comment_flexibilite TEXT,
-- Synthèse
points_positifs TEXT,
points_negatifs TEXT,
statut TEXT DEFAULT 'a_traiter', -- a_traiter / en_cours / dossier_envoye / visite_prevue / valide / archive / abandonne
priorite TEXT, -- priorite_absolue / plan_b / non_classe
images TEXT DEFAULT '[]'
)
`);
function ensureColumn(table, column, definition) {
const columns = db.prepare(`PRAGMA table_info(${table})`).all();
if (!columns.some((entry) => entry.name === column)) {
db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
}
}
// Legacy JSON column kept for backward compatibility / migration.
ensureColumn("fiches", "images", "TEXT DEFAULT '[]'");
ensureColumn("fiches", "type_search", "TEXT DEFAULT ''");
ensureColumn("fiches", "taxe_fonciere", "REAL");
ensureColumn("fiches", "statut", "TEXT DEFAULT 'a_traiter'");
ensureColumn("fiches", "facture_energie_type", "TEXT");
ensureColumn("fiches", "facture_energie_mensuelle", "REAL");
ensureColumn("fiches", "facture_energie_items", "TEXT DEFAULT '[]'");
db.prepare(
"UPDATE fiches SET statut = 'a_traiter' WHERE statut IS NULL OR statut = ''",
).run();
db.exec(`
CREATE TABLE IF NOT EXISTS fiche_images (
id INTEGER PRIMARY KEY AUTOINCREMENT,
fiche_id INTEGER NOT NULL,
path TEXT NOT NULL,
sort_order INTEGER DEFAULT 0,
created_at TEXT DEFAULT (datetime('now', 'localtime')),
FOREIGN KEY (fiche_id) REFERENCES fiches(id) ON DELETE CASCADE
)
`);
ensureColumn("fiche_images", "sort_order", "INTEGER DEFAULT 0");
db.exec(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_fiche_images_fiche_path
ON fiche_images (fiche_id, path)
`);
db.exec(`
CREATE TABLE IF NOT EXISTS immo_sites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
nom TEXT NOT NULL,
url TEXT NOT NULL UNIQUE,
favicon_url TEXT GENERATED ALWAYS AS (
'https://www.google.com/s2/favicons?domain=' || url || '&sz=32'
) VIRTUAL,
categorie TEXT CHECK(categorie IN (
'généraliste','agence','particulier',
'meublé','social','neuf','location courte durée'
)),
sort_order INTEGER DEFAULT 0,
actif INTEGER DEFAULT 1,
notes TEXT,
created_at TEXT DEFAULT (datetime('now','localtime'))
)
`);
function normalizeListingSites(rawSites) {
if (!Array.isArray(rawSites)) return [];
const ALLOWED_CATEGORIES = new Set([
"généraliste",
"agence",
"particulier",
"meublé",
"social",
"neuf",
"location courte durée",
]);
const seen = new Set();
return rawSites
.map((site, index) => {
const label = String(site?.label || "").trim();
const url = String(site?.url || "").trim();
const rawCat = String(site?.categorie || "").trim();
const categorie = ALLOWED_CATEGORIES.has(rawCat) ? rawCat : "généraliste";
const sort_order = Number.isFinite(Number(site?.sort_order))
? Number(site.sort_order)
: index;
const enabled = site?.enabled === false || site?.enabled === 0 ? 0 : 1;
const normUrlKey = url
.replace(/^https?:\/\//i, "")
.replace(/^www\./i, "")
.toLowerCase();
return {
id: site?.id ? Number(site.id) : null,
label,
url,
categorie,
sort_order,
enabled,
_normUrlKey: normUrlKey,
};
})
.filter((site) => site.label && site.url)
.filter((site) => {
if (seen.has(site._normUrlKey)) return false;
seen.add(site._normUrlKey);
delete site._normUrlKey;
return true;
});
}
function buildFaviconUrl(url) {
const value = String(url || "").trim();
if (!value) return "";
return `https://www.google.com/s2/favicons?domain=${value}&sz=32`;
}
function migrateLegacyImagesToTable() {
const legacyRows = db
.prepare(
`
SELECT id, images
FROM fiches
WHERE images IS NOT NULL
AND images != ''
AND images != '[]'
`,
)
.all();
const countStmt = db.prepare(
"SELECT COUNT(*) AS count FROM fiche_images WHERE fiche_id = ?",
);
const insertStmt = db.prepare(
"INSERT OR IGNORE INTO fiche_images (fiche_id, path) VALUES (?, ?)",
);
const tx = db.transaction(() => {
legacyRows.forEach((row) => {
const existingCount = countStmt.get(row.id)?.count || 0;
if (existingCount > 0) return;
parseJsonArray(row.images).forEach((pathValue) => {
if (pathValue) insertStmt.run(row.id, pathValue);
});
});
});
tx();
}
migrateLegacyImagesToTable();
function migrateImageSortOrder() {
const rows = db
.prepare(
`
SELECT id, fiche_id, sort_order, created_at
FROM fiche_images
ORDER BY fiche_id ASC, created_at ASC, id ASC
`,
)
.all();
if (!rows.length) return;
if (rows.some((row) => Number(row.sort_order) > 0)) return;
const updateStmt = db.prepare(
"UPDATE fiche_images SET sort_order = ? WHERE id = ?",
);
const tx = db.transaction(() => {
let currentFicheId = null;
let position = 0;
rows.forEach((row) => {
if (row.fiche_id !== currentFicheId) {
currentFicheId = row.fiche_id;
position = 0;
}
updateStmt.run(position, row.id);
position += 1;
});
});
tx();
}
migrateImageSortOrder();
const { requireAuth } = installAuth(app, db);
app.get(`/${PUBLIC_UPLOAD_DIR}/:filename`, requireAuth, (req, res) => {
res.set("Cache-Control", "private, no-store");
res.set("Content-Security-Policy", "default-src 'none'; sandbox");
res.set("X-Content-Type-Options", "nosniff");
const imagePath = toPublicUploadPath(req.params.filename);
const owned = db.prepare(`SELECT 1 FROM fiche_images JOIN fiches ON fiches.id = fiche_images.fiche_id
WHERE fiches.user_id = ? AND fiche_images.path = ?`).get(req.user.id, imagePath);
const storedPath = resolveStoredImagePath(imagePath);
if (!owned || !storedPath) return res.status(404).json({ error: "Image introuvable" });
res.sendFile(storedPath);
});
function getListingSites(userId) {
return db
.prepare(
`
SELECT id, nom, url, categorie, sort_order, actif, notes, created_at
FROM immo_sites
WHERE user_id = ?
ORDER BY sort_order ASC, id ASC
`,
)
.all(userId)
.map((site) => ({
...site,
enabled: site.actif,
favicon_url: buildFaviconUrl(site.url),
}));
}
app.get("/api/listing-sites", (req, res) => {
res.json(getListingSites(req.user.id));
});
app.put("/api/listing-sites", (req, res) => {
const sites = normalizeListingSites(req.body?.sites);
if (!Array.isArray(req.body?.sites)) return res.status(400).json({ error: "Liste de sites invalide" });
const deleteStmt = db.prepare("DELETE FROM immo_sites WHERE user_id = ?");
const insertStmt = db.prepare(
`
INSERT INTO immo_sites (user_id, nom, url, categorie, sort_order, actif, notes)
VALUES (@user_id, @nom, @url, @categorie, @sort_order, @actif, @notes)
`,
);
const tx = db.transaction(() => {
deleteStmt.run(req.user.id);
sites.forEach((site, index) => {
insertStmt.run({
user_id: req.user.id,
nom: site.label,
url: site.url,
categorie: site.categorie,
sort_order: site.sort_order ?? index,
actif: site.enabled,
notes: site.notes || null,
});
});
});
tx();
res.json({
message: "Sites d'annonces mis à jour",
sites: getListingSites(req.user.id),
});
});
// ===== NOUVELLE ROUTE : ESTIMER COÛT DE CHAUFFAGE =====
/**
* Route POST /api/estimer-cout-chauffage
* Calcule le coût mensuel et annuel de chauffage
*/
app.post("/api/estimer-cout-chauffage", (req, res) => {
try {
const { typeEnergie, superficie, classeDpe } = req.body;
// Validation des paramètres
if (!typeEnergie || !superficie || !classeDpe) {
return res.status(400).json({
error: "Paramètres manquants. Veuillez fournir typeEnergie, superficie et classeDpe."
});
}
// Appel du configurateur
const result = estimerCoutChauffage(typeEnergie, superficie, classeDpe);
res.json({
success: true,
coutMensuel: result.coutMensuel,
coutAnnuel: result.coutAnnuel,
details: result.details
});
} catch (error) {
console.error("Erreur dans le calcul du coût de chauffage:", error);
res.status(400).json({
success: false,
error: error.message
});
}
});
// ===== FIN DE LA NOUVELLE ROUTE =====
// ─── Routes existantes (inchangées) ──────────────────────────────────────────
// GET — Liste toutes les fiches (résumé)
app.get("/api/fiches", (req, res) => {
const rawFiches = db
.prepare(
`
SELECT id, adresse, date_visite, type_logement, surface,
loyer_cc, priorite, statut, type_search, type_bail, taxe_fonciere, created_at
FROM fiches
WHERE user_id = ?
ORDER BY created_at DESC
`,
)
.all(req.user.id);
const fiches = rawFiches.map((fiche) =>
hydrateFiche(fiche, getImagesByFicheId(fiche.id)),
);
res.json(fiches);
});
// GET — Détail d'une fiche
app.get("/api/fiches/:id", (req, res) => {
const fiche = db
.prepare("SELECT * FROM fiches WHERE id = ? AND user_id = ?")
.get(req.params.id, req.user.id);
if (!fiche) return res.status(404).json({ error: "Fiche introuvable" });
res.json(hydrateFiche(fiche, getImagesByFicheId(req.params.id)));
});
// POST — Créer une fiche
function ficheData(payload, userId) {
if (!payload || typeof payload !== "object" || Array.isArray(payload) ||
typeof payload.adresse !== "string" || !payload.adresse.trim()) {
const error = new Error("Veuillez renseigner l'adresse du bien.");
error.status = 400;
throw error;
}
const data = {};
for (const column of db.prepare("PRAGMA table_info(fiches)").all()) {
if (!["id", "created_at"].includes(column.name)) data[column.name] = payload[column.name] ?? null;
}
data.user_id = userId;
return data;
}
// Authenticate and check ownership before accepting any files.
app.use("/api/fiches", (req, res, next) => {
res.on("finish", () => {
if (res.statusCode >= 400) removeStoredImages((req.files || []).map((file) => toPublicUploadPath(file.filename)));
});
next();
});
app.param("id", (req, res, next, id) => {
const fiche = db.prepare("SELECT * FROM fiches WHERE id = ? AND user_id = ?").get(id, req.user.id);
if (!fiche) return res.status(404).json({ error: "Fiche introuvable" });
req.fiche = fiche;
next();
});
app.post("/api/fiches", upload.array("images", 10), (req, res) => {
const { payload, existingImages } = parseRequestPayload(req);
const data = ficheData(payload, req.user.id);
if (existingImages.length) return res.status(400).json({ error: "Images existantes non autorisées pour une nouvelle fiche" });
data.statut = normalizeFicheStatus(data.statut);
const legacyEnergyItems = legacyEnergyItemsFromFiche(data);
data.facture_energie_items = JSON.stringify(
parseEnergyItems(data.facture_energie_items).length
? parseEnergyItems(data.facture_energie_items)
: legacyEnergyItems,
);
// Calcul automatique loyer CC si non fourni
if (!data.loyer_cc && data.loyer_hc && data.charges) {
data.loyer_cc = parseFloat(data.loyer_hc) + parseFloat(data.charges);
}
const mergedImages = mergeImages(existingImages, req.files);
data.images = JSON.stringify(mergedImages);
const stmt = db.prepare(`
INSERT INTO fiches (
user_id,
adresse, date_visite, heure_visite, contact_nom, contact_tel,
type_logement, surface, etage, type_search, type_bail, taxe_fonciere,
loyer_hc, charges,
charges_eau_froide, charges_eau_chaude, charges_chauffage, charges_elec,
loyer_cc, depot_garantie, frais_agence, disponibilite,
chauffage_type, facture_energie_type, facture_energie_mensuelle, facture_energie_items, fibre_optique,
parking_garage, parking_reserve, parking_rue,
cave, grenier,
note_etat_general, note_luminosite, note_isolation,
note_cuisine, note_rangements, note_emplacement, note_flexibilite,
comment_etat_general, comment_luminosite, comment_isolation,
comment_cuisine, comment_rangements, comment_emplacement, comment_flexibilite,
points_positifs, points_negatifs, statut, priorite, images
) VALUES (
@user_id,
@adresse, @date_visite, @heure_visite, @contact_nom, @contact_tel,
@type_logement, @surface, @etage, @type_search, @type_bail, @taxe_fonciere,
@loyer_hc, @charges,
@charges_eau_froide, @charges_eau_chaude, @charges_chauffage, @charges_elec,
@loyer_cc, @depot_garantie, @frais_agence, @disponibilite,
@chauffage_type, @facture_energie_type, @facture_energie_mensuelle, @facture_energie_items, @fibre_optique,
@parking_garage, @parking_reserve, @parking_rue,
@cave, @grenier,
@note_etat_general, @note_luminosite, @note_isolation,
@note_cuisine, @note_rangements, @note_emplacement, @note_flexibilite,
@comment_etat_general, @comment_luminosite, @comment_isolation,
@comment_cuisine, @comment_rangements, @comment_emplacement, @comment_flexibilite,
@points_positifs, @points_negatifs, @statut, @priorite, @images
)
`);
const result = db.transaction(() => {
const inserted = stmt.run(data);
replaceFicheImages(inserted.lastInsertRowid, mergedImages);
return inserted;
})();
res.status(201).json({ id: result.lastInsertRowid, message: "Fiche créée" });
});
// PUT — Modifier une fiche
app.put("/api/fiches/:id", upload.array("images", 10), (req, res) => {
const { payload, existingImages } = parseRequestPayload(req);
const data = { ...ficheData(payload, req.user.id), id: req.params.id };
const previousImages = getImagesByFicheId(req.params.id).map((row) => row.path);
if (existingImages.some((image) => !previousImages.includes(image))) {
return res.status(400).json({ error: "Une image n'appartient pas à cette fiche" });
}
data.statut = normalizeFicheStatus(data.statut);
const legacyEnergyItems = legacyEnergyItemsFromFiche(data);
data.facture_energie_items = JSON.stringify(
parseEnergyItems(data.facture_energie_items).length
? parseEnergyItems(data.facture_energie_items)
: legacyEnergyItems,
);
if (!data.loyer_cc && data.loyer_hc && data.charges) {
data.loyer_cc = parseFloat(data.loyer_hc) + parseFloat(data.charges);
}
const mergedImages = mergeImages(existingImages, req.files);
data.images = JSON.stringify(mergedImages);
const stmt = db.prepare(`
UPDATE fiches SET
adresse=@adresse, date_visite=@date_visite, heure_visite=@heure_visite,
contact_nom=@contact_nom, contact_tel=@contact_tel,
type_logement=@type_logement, surface=@surface, etage=@etage,
type_search=@type_search, type_bail=@type_bail, taxe_fonciere=@taxe_fonciere,
loyer_hc=@loyer_hc, charges=@charges,
charges_eau_froide=@charges_eau_froide, charges_eau_chaude=@charges_eau_chaude,
charges_chauffage=@charges_chauffage, charges_elec=@charges_elec,
loyer_cc=@loyer_cc, depot_garantie=@depot_garantie,
frais_agence=@frais_agence, disponibilite=@disponibilite,
chauffage_type=@chauffage_type, facture_energie_type=@facture_energie_type,
facture_energie_mensuelle=@facture_energie_mensuelle,
facture_energie_items=@facture_energie_items,
fibre_optique=@fibre_optique,
parking_garage=@parking_garage, parking_reserve=@parking_reserve,
parking_rue=@parking_rue, cave=@cave, grenier=@grenier,
note_etat_general=@note_etat_general, note_luminosite=@note_luminosite,
note_isolation=@note_isolation, note_cuisine=@note_cuisine,
note_rangements=@note_rangements, note_emplacement=@note_emplacement,
note_flexibilite=@note_flexibilite,
comment_etat_general=@comment_etat_general, comment_luminosite=@comment_luminosite,
comment_isolation=@comment_isolation, comment_cuisine=@comment_cuisine,
comment_rangements=@comment_rangements, comment_emplacement=@comment_emplacement,
comment_flexibilite=@comment_flexibilite,
points_positifs=@points_positifs, points_negatifs=@points_negatifs,
statut=@statut,
priorite=@priorite, images=@images
WHERE id=@id AND user_id=@user_id
`);
db.transaction(() => {
stmt.run(data);
replaceFicheImages(req.params.id, mergedImages);
})();
removeStoredImages(previousImages.filter((image) => !mergedImages.includes(image)));
res.json({ message: "Fiche mise à jour" });
});
// DELETE — Supprimer une fiche
app.delete("/api/fiches/:id", (req, res) => {
const fiche = db
.prepare("SELECT id FROM fiches WHERE id = ? AND user_id = ?")
.get(req.params.id, req.user.id);
if (!fiche) return res.status(404).json({ error: "Fiche introuvable" });
const imageRows = getImagesByFicheId(req.params.id);
const imagePaths = imageRows.map((row) => row.path);
db.prepare("DELETE FROM fiches WHERE id = ? AND user_id = ?").run(req.params.id, req.user.id);
removeStoredImages(imagePaths);
res.json({ message: "Fiche supprimée" });
});
// GET — Export CSV
app.get("/api/export/csv", (req, res) => {
const fiches = db
.prepare("SELECT * FROM fiches WHERE user_id = ? ORDER BY created_at DESC")
.all(req.user.id);
const headers = Object.keys(fiches[0] || {}).join(";");
const rows = fiches.map((f) =>
Object.values(f)
.map((v) => (typeof v === "string" && v.includes(";") ? `"${v}"` : v))
.join(";"),
);
res.setHeader("Content-Type", "text/csv; charset=utf-8");
res.setHeader(
"Content-Disposition",
'attachment; filename="fiches_immo.csv"',
);
res.send("\uFEFF" + [headers, ...rows].join("\n")); // BOM pour Excel
});
// Error handling middleware
app.use((err, _req, res, _next) => {
if (err.code === "LIMIT_FILE_SIZE") {
return res
.status(413)
.json({ error: "Fichier trop volumineux (max 10 Mo)" });
}
console.error(err);
const status = err.status || (err instanceof SyntaxError ? 400 : 500);
res.status(status).json({ error: status < 500 ? err.message : "Erreur serveur" });
});
// ─── Start ────────────────────────────────────────────────────────────────────
if (require.main === module) app.listen(PORT, "0.0.0.0", () => {
console.log(`✅ Serveur lancé → http://0.0.0.0:${PORT}`);
console.log(`📁 Base SQLite : ${SQLITE_PATH}`);
console.log(`📂 Dossier uploads : ${UPLOAD_DIR}`);
});
module.exports = { app, db };
|