Ship configurator updates with catalog DB included for server deploy.

Co-authored-by: Cursor <[email protected]>
This commit is contained in:
lejay
2026-10-07 17:13:03 +02:00
co-authored by Cursor
parent 6c0d7e47b8
commit 30921aade6
75 changed files with 15618 additions and 1300 deletions
+110
View File
@@ -0,0 +1,110 @@
/**
* Dispositions types intégrées, insérées dans `layout_presets` (une fois par seed_key).
* Le client normalise ensuite blocks / rayons (positions System 32, rayon structurel, etc.).
*/
const TYPE_DEFAULTS = {
penderie: { shelves: 1, drawers: 0, hasRod: true },
tiroirs: { shelves: 1, drawers: 3, hasRod: false },
rayonnage: { shelves: 4, drawers: 0, hasRod: false },
bloc_carre: { shelves: 0, drawers: 0, hasRod: false },
mixte: { shelves: 2, drawers: 2, hasRod: true }
};
function column(key, index, type, widthMm, overrides = {}) {
const hasBack = overrides.hasBack ?? false;
return {
id: `preset-${key}-c${index + 1}`,
type,
moduleCode: type,
widthMm,
minWidth: 300,
maxWidth: type === 'tiroirs' || type === 'mixte' ? 1000 : 1200,
position: index,
locked: false,
...TYPE_DEFAULTS[type],
drawerType: 'visible',
hasBack,
hasBackTop: hasBack,
...overrides
};
}
function layout(key, { name, description, widthMm, heightMm = 2400, depthMm = 600, plinthHeightMm = 100, hasBack = false, columns }) {
return {
seedKey: key,
name,
description,
config: {
widthMm,
heightMm,
depthMm,
plinthHeightMm,
hasBack,
stackEnabled: columns.some((c) => Array.isArray(c[2]?.blockHeightsMm) && c[2].blockHeightsMm.length >= 2),
horizontalSpans: [],
modules: columns.map(([type, w, overrides], i) => column(key, i, type, w, { hasBack, ...overrides }))
}
};
}
/*
* Penderie au-delà de 2000 mm: une colonne en un seul block exige un rayon structurel à mi-hauteur,
* ce qui coupe la penderie (< 1100 mm sous tringle). Les penderies sont donc empilées: block bas de
* 1800 mm (≈ 1710 mm sous tringle, manteaux longs ≥ 1600 mm) + surmeuble; la jonction sert de chapelier.
*/
const HANGING = { blockHeightsMm: [1800, 500], shelves: 0 };
const SURMEUBLE = { blockHeightsMm: [2000, 500] };
const OPEN = { blockDoors: [false] };
export const DEFAULT_LAYOUT_PRESETS = [
layout('penderie-double', {
name: 'Penderie double',
description: 'Deux penderies manteaux longs avec surmeubles',
widthMm: 1200,
columns: [['penderie', 600, HANGING], ['penderie', 600, HANGING]]
}),
layout('classique-3', {
name: 'Classique 3 colonnes',
description: 'Penderie, rayonnage et tiroirs',
widthMm: 1800,
columns: [['penderie', 600, HANGING], ['rayonnage', 600], ['tiroirs', 600]]
}),
layout('dressing-4', {
name: 'Dressing 4 colonnes',
description: 'Deux penderies encadrant tiroirs et rayonnage',
widthMm: 2400,
columns: [['penderie', 600, HANGING], ['tiroirs', 600], ['rayonnage', 600], ['penderie', 600, HANGING]]
}),
layout('grande-penderie', {
name: 'Grande penderie',
description: 'Penderie large, rayonnage et penderie avec tiroirs',
widthMm: 2000,
columns: [['penderie', 1000, HANGING], ['rayonnage', 500], ['mixte', 500, HANGING]]
}),
layout('surmeubles', {
name: 'Avec surmeubles',
description: 'Dressing 4 colonnes surmonté de rangements hauts',
widthMm: 2400,
heightMm: 2600,
columns: [
['penderie', 600, { ...SURMEUBLE, shelves: 0 }],
['rayonnage', 600, SURMEUBLE],
['tiroirs', 600, SURMEUBLE],
['penderie', 600, { ...SURMEUBLE, shelves: 0 }]
]
}),
layout('bibliotheque', {
name: 'Bibliothèque ouverte',
description: 'Trois colonnes de rayonnage sans portes, avec dos',
widthMm: 1500,
heightMm: 2200,
depthMm: 350,
hasBack: true,
columns: [
['rayonnage', 500, { ...OPEN, shelves: 5 }],
['rayonnage', 500, { ...OPEN, shelves: 5 }],
['rayonnage', 500, { ...OPEN, shelves: 5 }]
]
})
];
+138 -8
View File
@@ -10,6 +10,7 @@ const dbPath = process.env.DATABASE_PATH || path.join(dataDir, 'configurateur.db
const schemaPath = path.join(__dirname, 'schema.sql');
let db = null;
let sqlJs = null;
/** Création idempotente — bases anciennes sans ces tables (avant migration 014). */
const HARDWARE_CATALOG_DDL = `
@@ -52,23 +53,144 @@ function toSqlitePlaceholders(sql) {
return sql.replace(/\$(\d+)/g, '?');
}
function save() {
if (db && dbPath) {
const data = db.export();
fs.writeFileSync(dbPath, Buffer.from(data));
const BACKUP_DIR = path.join(dataDir, 'backups');
const MAX_BACKUP_DAYS = 14;
/**
* Count formex_materials in an open sql.js Database instance.
*/
function countMaterialsIn(database) {
if (!database) return 0;
try {
const result = database.exec('SELECT COUNT(*) AS c FROM formex_materials');
return Number(result[0]?.values?.[0]?.[0] ?? 0);
} catch {
return 0;
}
}
/**
* Peek material count on a DB file without touching the live in-memory DB.
*/
function countMaterialsOnDisk(filePath = dbPath) {
if (!filePath || !fs.existsSync(filePath) || !sqlJs) return 0;
let probe = null;
try {
const buffer = fs.readFileSync(filePath);
if (!buffer.length) return 0;
probe = new sqlJs.Database(buffer);
return countMaterialsIn(probe);
} catch {
return 0;
} finally {
try { probe?.close(); } catch { /* ignore */ }
}
}
/**
* Snapshot the on-disk DB before this process touches it, so scraped data
* (Häfele, Leuba Hiag, Formex) survives accidental wipes. One backup per
* day (first start of the day), kept for MAX_BACKUP_DAYS days.
* Never replaces a richer day's backup with an emptier DB.
*/
function backupExistingDb() {
try {
if (!fs.existsSync(dbPath)) return;
if (!fs.existsSync(BACKUP_DIR)) fs.mkdirSync(BACKUP_DIR, { recursive: true });
const diskCount = countMaterialsOnDisk(dbPath);
const today = new Date().toISOString().slice(0, 10);
const backupPath = path.join(BACKUP_DIR, `configurateur-${today}.db`);
if (!fs.existsSync(backupPath)) {
if (diskCount === 0) {
console.warn('[db] skip daily backup — on-disk DB has 0 materials (protects older non-empty backups)');
} else {
fs.copyFileSync(dbPath, backupPath);
console.log(`[db] daily backup created: ${backupPath} (${diskCount} materials)`);
}
} else {
const backupCount = countMaterialsOnDisk(backupPath);
if (diskCount > backupCount) {
fs.copyFileSync(dbPath, backupPath);
console.log(`[db] daily backup upgraded: ${backupPath} (${backupCount} → ${diskCount} materials)`);
}
}
const backups = fs.readdirSync(BACKUP_DIR)
.filter((f) => /^configurateur-\d{4}-\d{2}-\d{2}\.db$/.test(f))
.sort();
while (backups.length > MAX_BACKUP_DAYS) {
// Prefer deleting empty backups so a sole non-empty snapshot is kept.
let removeIdx = backups.findIndex((f) => countMaterialsOnDisk(path.join(BACKUP_DIR, f)) === 0);
if (removeIdx < 0) removeIdx = 0;
const removed = backups.splice(removeIdx, 1)[0];
fs.unlinkSync(path.join(BACKUP_DIR, removed));
console.warn(`[db] rotated backup removed: ${removed}`);
}
} catch (e) {
console.error('[db] backup failed:', e.message);
}
}
/**
* Atomically persist the in-memory DB.
*
* Blocks only *catastrophic* overwrites — the failure mode that kept wiping
* scrapes: a stale/empty in-memory process saving over a full on-disk catalog.
* Normal scrapes (count grows) and single-row admin deletes still save.
*/
function save({ allowShrink = false } = {}) {
if (!db || !dbPath) return false;
const memCount = countMaterialsIn(db);
if (!allowShrink && fs.existsSync(dbPath)) {
const diskCount = countMaterialsOnDisk(dbPath);
const emptyClobber = memCount === 0 && diskCount > 0;
const massShrink = diskCount >= 20 && memCount < Math.floor(diskCount * 0.1);
if (emptyClobber || massShrink) {
console.error(
`[db] REFUSING save: in-memory has ${memCount} materials but disk has ${diskCount}. ` +
'Scraped data protected. Restart the server to reload from disk.'
);
try {
if (!fs.existsSync(BACKUP_DIR)) fs.mkdirSync(BACKUP_DIR, { recursive: true });
const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
fs.writeFileSync(
path.join(BACKUP_DIR, `configurateur-refused-${stamp}.db`),
Buffer.from(db.export())
);
} catch { /* best-effort forensic copy */ }
return false;
}
}
const tmpPath = `${dbPath}.tmp`;
const data = Buffer.from(db.export());
fs.writeFileSync(tmpPath, data);
try {
fs.renameSync(tmpPath, dbPath);
} catch {
// Windows may not allow rename over an existing file while another handle is open.
fs.copyFileSync(tmpPath, dbPath);
try { fs.unlinkSync(tmpPath); } catch { /* ignore */ }
}
return true;
}
async function getDb() {
if (db) return db;
const SQL = await initSqlJs({
sqlJs = await initSqlJs({
locateFile: (file) => path.join(__dirname, '..', 'node_modules', 'sql.js', 'dist', file)
});
let buffer;
if (fs.existsSync(dbPath)) {
// sqlJs must be ready before peek-based backup logic.
backupExistingDb();
buffer = fs.readFileSync(dbPath);
}
db = new SQL.Database(buffer || null);
db = new sqlJs.Database(buffer || null);
try {
// Ensure full schema exists for legacy/partial DB files.
if (fs.existsSync(schemaPath)) {
@@ -76,11 +198,13 @@ async function getDb() {
db.exec(schemaSql);
}
db.exec(HARDWARE_CATALOG_DDL);
const data = db.export();
fs.writeFileSync(dbPath, Buffer.from(data));
// Persist schema ensures through the guarded saver (never clobber richer disk).
save();
} catch (e) {
console.error('[db] ensureHardwareCatalogTables:', e.message);
}
const loaded = countMaterialsIn(db);
console.log(`[db] loaded ${loaded} materials from ${dbPath}`);
return db;
}
@@ -105,6 +229,12 @@ export const run = async (sql, params = []) => {
return {};
};
/** Force-persist even if material count shrinks (admin bulk delete, etc.). */
export const saveAllowShrink = async () => {
await getDb();
return save({ allowShrink: true });
};
const pool = {
query: (sql, params) => query(sql, params)
};
+72 -3
View File
@@ -8,12 +8,81 @@ const dataDir = path.join(__dirname, '..', 'data');
if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
const dbPath = process.env.DATABASE_PATH || path.join(dataDir, 'configurateur.db');
const force = process.argv.includes('--force');
const SQL = await initSqlJs({
locateFile: (file) => path.join(__dirname, '..', 'node_modules', 'sql.js', 'dist', file)
});
const db = new SQL.Database();
function countMaterials(database) {
try {
const result = database.exec('SELECT COUNT(*) AS c FROM formex_materials');
return Number(result[0]?.values?.[0]?.[0] ?? 0);
} catch {
return 0;
}
}
function atomicWrite(filePath, database) {
const tmpPath = `${filePath}.tmp`;
fs.writeFileSync(tmpPath, Buffer.from(database.export()));
try {
fs.renameSync(tmpPath, filePath);
} catch {
fs.copyFileSync(tmpPath, filePath);
try { fs.unlinkSync(tmpPath); } catch { /* ignore */ }
}
}
const dbExists = fs.existsSync(dbPath);
if (dbExists && force) {
// Backup before destroying anything.
const backupDir = path.join(dataDir, 'backups');
if (!fs.existsSync(backupDir)) fs.mkdirSync(backupDir, { recursive: true });
const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
const backupPath = path.join(backupDir, `configurateur-pre-init-${stamp}.db`);
fs.copyFileSync(dbPath, backupPath);
console.log(`Existing database backed up to ${backupPath}`);
}
let db;
if (dbExists && !force) {
// Non-destructive: apply schema (CREATE TABLE IF NOT EXISTS) to the existing DB,
// preserving all data (scraped materials, orders, etc.).
db = new SQL.Database(fs.readFileSync(dbPath));
const before = countMaterials(db);
console.log(
`Existing database found (${before} materials) — applying schema without deleting data (use --force to recreate from scratch).`
);
} else {
db = new SQL.Database();
}
const schema = fs.readFileSync(path.join(__dirname, 'schema.sql'), 'utf8');
db.exec(schema);
fs.writeFileSync(dbPath, Buffer.from(db.export()));
if (dbExists && !force) {
const after = countMaterials(db);
const diskBefore = (() => {
try {
const probe = new SQL.Database(fs.readFileSync(dbPath));
const n = countMaterials(probe);
probe.close();
return n;
} catch {
return 0;
}
})();
if (diskBefore > 0 && after < diskBefore) {
console.error(
`REFUSING to write: schema apply would shrink materials ${diskBefore} → ${after}. Aborting.`
);
db.close();
process.exit(1);
}
}
atomicWrite(dbPath, db);
console.log(`Schema applied. Materials on disk: ${countMaterials(db)}`);
db.close();
console.log('Schema applied.');
+22
View File
@@ -66,6 +66,28 @@ CREATE TABLE IF NOT EXISTS orders (
created_at TEXT DEFAULT (datetime('now'))
);
-- Configurations d'armoires sauvegardées pour reprise ultérieure
CREATE TABLE IF NOT EXISTS saved_designs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
config TEXT NOT NULL,
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now'))
);
-- Dispositions types proposées à l'étape Espace (exemples intégrés + dispositions enregistrées)
CREATE TABLE IF NOT EXISTS layout_presets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
seed_key TEXT UNIQUE,
name TEXT NOT NULL,
description TEXT,
config TEXT NOT NULL,
sort_order INTEGER DEFAULT 100,
active INTEGER DEFAULT 1,
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now'))
);
-- Matériaux Formex (données scrapées)
CREATE TABLE IF NOT EXISTS formex_materials (
id INTEGER PRIMARY KEY AUTOINCREMENT,
+35 -2
View File
@@ -14,10 +14,43 @@ if (!fs.existsSync(dbPath)) {
const SQL = await initSqlJs({
locateFile: (file) => path.join(__dirname, '..', 'node_modules', 'sql.js', 'dist', file)
});
function countMaterials(database) {
try {
const result = database.exec('SELECT COUNT(*) AS c FROM formex_materials');
return Number(result[0]?.values?.[0]?.[0] ?? 0);
} catch {
return 0;
}
}
function atomicWrite(filePath, database) {
const tmpPath = `${filePath}.tmp`;
fs.writeFileSync(tmpPath, Buffer.from(database.export()));
try {
fs.renameSync(tmpPath, filePath);
} catch {
fs.copyFileSync(tmpPath, filePath);
try { fs.unlinkSync(tmpPath); } catch { /* ignore */ }
}
}
const buffer = fs.readFileSync(dbPath);
const db = new SQL.Database(buffer);
const before = countMaterials(db);
const seedSql = fs.readFileSync(path.join(__dirname, 'seeds.sql'), 'utf8');
db.exec(seedSql);
fs.writeFileSync(dbPath, Buffer.from(db.export()));
const after = countMaterials(db);
if (before > 0 && after < before) {
console.error(
`REFUSING to write seeds: materials would shrink ${before} → ${after}. Aborting.`
);
db.close();
process.exit(1);
}
atomicWrite(dbPath, db);
db.close();
console.log('Seeds applied.');
console.log(`Seeds applied. Materials preserved: ${after} (was ${before}).`);
+1 -1
View File
@@ -4,7 +4,7 @@ INSERT OR REPLACE INTO settings (key, value) VALUES
('kit_preparation_fee_chf', '350'),
('panel_thickness_mm', '19'),
('plinth_height_min_mm', '60'),
('plinth_height_max_mm', '160'),
('plinth_height_max_mm', '200'),
('niche_clearance_multiplier', '2'),
('min_clearance_mm', '20'),
('sliding_doors_min_width_mm', '1200');