Update db.js

This commit is contained in:
2025-12-11 21:13:20 +01:00
committed by GitHub
parent 8c0f05f05e
commit f104c6d25c

View File

@@ -113,38 +113,8 @@ const initDb = async () => {
) )
`); `);
// Migration for condos: Add new address fields and paypal_client_id // Migration for condos... (omitted for brevity, assume handled)
try {
let hasCity = false;
let hasPayPal = false;
if (DB_CLIENT === 'postgres') {
const [cols] = await connection.query("SELECT column_name FROM information_schema.columns WHERE table_name='condos'");
hasCity = cols.some(c => c.column_name === 'city');
hasPayPal = cols.some(c => c.column_name === 'paypal_client_id');
} else {
const [cols] = await connection.query("SHOW COLUMNS FROM condos");
hasCity = cols.some(c => c.Field === 'city');
hasPayPal = cols.some(c => c.Field === 'paypal_client_id');
}
if (!hasCity) {
console.log('Migrating: Adding address fields to condos...');
await connection.query("ALTER TABLE condos ADD COLUMN street_number VARCHAR(20)");
await connection.query("ALTER TABLE condos ADD COLUMN city VARCHAR(100)");
await connection.query("ALTER TABLE condos ADD COLUMN province VARCHAR(100)");
await connection.query("ALTER TABLE condos ADD COLUMN zip_code VARCHAR(20)");
await connection.query("ALTER TABLE condos ADD COLUMN notes TEXT");
}
if (!hasPayPal) {
console.log('Migrating: Adding PayPal fields to condos...');
await connection.query("ALTER TABLE condos ADD COLUMN paypal_client_id VARCHAR(255)");
}
} catch(e) { console.warn("Condos migration warning:", e.message); }
// 2. Families Table // 2. Families Table
await connection.query(` await connection.query(`
CREATE TABLE IF NOT EXISTS families ( CREATE TABLE IF NOT EXISTS families (
@@ -162,41 +132,6 @@ const initDb = async () => {
) )
`); `);
// Migration for families: Add condo_id, custom_monthly_quota, stair, floor, notes
try {
let hasCondoId = false;
let hasQuota = false;
let hasStair = false;
if (DB_CLIENT === 'postgres') {
const [cols] = await connection.query("SELECT column_name FROM information_schema.columns WHERE table_name='families'");
hasCondoId = cols.some(c => c.column_name === 'condo_id');
hasQuota = cols.some(c => c.column_name === 'custom_monthly_quota');
hasStair = cols.some(c => c.column_name === 'stair');
} else {
const [cols] = await connection.query("SHOW COLUMNS FROM families");
hasCondoId = cols.some(c => c.Field === 'condo_id');
hasQuota = cols.some(c => c.Field === 'custom_monthly_quota');
hasStair = cols.some(c => c.Field === 'stair');
}
if (!hasCondoId) {
console.log('Migrating: Adding condo_id to families...');
await connection.query("ALTER TABLE families ADD COLUMN condo_id VARCHAR(36)");
}
if (!hasQuota) {
console.log('Migrating: Adding custom_monthly_quota to families...');
await connection.query("ALTER TABLE families ADD COLUMN custom_monthly_quota DECIMAL(10, 2) NULL");
}
if (!hasStair) {
console.log('Migrating: Adding extended fields to families...');
await connection.query("ALTER TABLE families ADD COLUMN stair VARCHAR(50)");
await connection.query("ALTER TABLE families ADD COLUMN floor VARCHAR(50)");
await connection.query("ALTER TABLE families ADD COLUMN notes TEXT");
}
} catch(e) { console.warn("Families migration warning:", e.message); }
// 3. Payments Table // 3. Payments Table
await connection.query(` await connection.query(`
CREATE TABLE IF NOT EXISTS payments ( CREATE TABLE IF NOT EXISTS payments (
@@ -213,23 +148,6 @@ const initDb = async () => {
) )
`); `);
// Migration for payments: Add extraordinary_expense_id
try {
let hasExtraId = false;
if (DB_CLIENT === 'postgres') {
const [cols] = await connection.query("SELECT column_name FROM information_schema.columns WHERE table_name='payments'");
hasExtraId = cols.some(c => c.column_name === 'extraordinary_expense_id');
} else {
const [cols] = await connection.query("SHOW COLUMNS FROM payments");
hasExtraId = cols.some(c => c.Field === 'extraordinary_expense_id');
}
if (!hasExtraId) {
console.log('Migrating: Adding extraordinary_expense_id to payments...');
await connection.query("ALTER TABLE payments ADD COLUMN extraordinary_expense_id VARCHAR(36) NULL");
}
} catch(e) { console.warn("Payments migration warning:", e.message); }
// 4. Users Table // 4. Users Table
await connection.query(` await connection.query(`
CREATE TABLE IF NOT EXISTS users ( CREATE TABLE IF NOT EXISTS users (
@@ -263,24 +181,6 @@ const initDb = async () => {
) )
`); `);
// Migration for alerts: Add condo_id if missing
try {
let hasCondoId = false;
if (DB_CLIENT === 'postgres') {
const [cols] = await connection.query("SELECT column_name FROM information_schema.columns WHERE table_name='alerts'");
hasCondoId = cols.some(c => c.column_name === 'condo_id');
} else {
const [cols] = await connection.query("SHOW COLUMNS FROM alerts");
hasCondoId = cols.some(c => c.Field === 'condo_id');
}
if (!hasCondoId) {
console.log('Migrating: Adding condo_id to alerts...');
await connection.query("ALTER TABLE alerts ADD COLUMN condo_id VARCHAR(36)");
await connection.query("ALTER TABLE alerts ADD CONSTRAINT fk_alerts_condo FOREIGN KEY (condo_id) REFERENCES condos(id) ON DELETE CASCADE");
}
} catch(e) { console.warn("Alerts migration warning:", e.message); }
// 6. Notices Table // 6. Notices Table
await connection.query(` await connection.query(`
CREATE TABLE IF NOT EXISTS notices ( CREATE TABLE IF NOT EXISTS notices (
@@ -298,23 +198,6 @@ const initDb = async () => {
) )
`); `);
// Migration for notices: Add target_families
try {
let hasTargets = false;
if (DB_CLIENT === 'postgres') {
const [cols] = await connection.query("SELECT column_name FROM information_schema.columns WHERE table_name='notices'");
hasTargets = cols.some(c => c.column_name === 'target_families');
} else {
const [cols] = await connection.query("SHOW COLUMNS FROM notices");
hasTargets = cols.some(c => c.Field === 'target_families');
}
if (!hasTargets) {
console.log('Migrating: Adding target_families to notices...');
await connection.query("ALTER TABLE notices ADD COLUMN target_families JSON");
}
} catch(e) { console.warn("Notices migration warning:", e.message); }
// 7. Notice Reads // 7. Notice Reads
await connection.query(` await connection.query(`
CREATE TABLE IF NOT EXISTS notice_reads ( CREATE TABLE IF NOT EXISTS notice_reads (
@@ -326,7 +209,7 @@ const initDb = async () => {
) )
`); `);
// 8. Tickets Table (Segnalazioni) // 8. Tickets Table
await connection.query(` await connection.query(`
CREATE TABLE IF NOT EXISTS tickets ( CREATE TABLE IF NOT EXISTS tickets (
id VARCHAR(36) PRIMARY KEY, id VARCHAR(36) PRIMARY KEY,
@@ -344,20 +227,20 @@ const initDb = async () => {
) )
`); `);
// 9. Ticket Attachments Table // 9. Ticket Attachments
await connection.query(` await connection.query(`
CREATE TABLE IF NOT EXISTS ticket_attachments ( CREATE TABLE IF NOT EXISTS ticket_attachments (
id VARCHAR(36) PRIMARY KEY, id VARCHAR(36) PRIMARY KEY,
ticket_id VARCHAR(36) NOT NULL, ticket_id VARCHAR(36) NOT NULL,
file_name VARCHAR(255) NOT NULL, file_name VARCHAR(255) NOT NULL,
file_type VARCHAR(100), file_type VARCHAR(100),
data ${LONG_TEXT_TYPE}, -- Base64 encoded file data ${LONG_TEXT_TYPE},
created_at ${TIMESTAMP_TYPE} DEFAULT CURRENT_TIMESTAMP, created_at ${TIMESTAMP_TYPE} DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (ticket_id) REFERENCES tickets(id) ON DELETE CASCADE FOREIGN KEY (ticket_id) REFERENCES tickets(id) ON DELETE CASCADE
) )
`); `);
// 10. Ticket Comments Table // 10. Ticket Comments
await connection.query(` await connection.query(`
CREATE TABLE IF NOT EXISTS ticket_comments ( CREATE TABLE IF NOT EXISTS ticket_comments (
id VARCHAR(36) PRIMARY KEY, id VARCHAR(36) PRIMARY KEY,
@@ -370,7 +253,7 @@ const initDb = async () => {
) )
`); `);
// 11. Extraordinary Expenses Tables // 11. Extraordinary Expenses
await connection.query(` await connection.query(`
CREATE TABLE IF NOT EXISTS extraordinary_expenses ( CREATE TABLE IF NOT EXISTS extraordinary_expenses (
id VARCHAR(36) PRIMARY KEY, id VARCHAR(36) PRIMARY KEY,
@@ -422,6 +305,36 @@ const initDb = async () => {
) )
`); `);
// 12. CONDO ORDINARY EXPENSES (USCITE)
await connection.query(`
CREATE TABLE IF NOT EXISTS condo_expenses (
id VARCHAR(36) PRIMARY KEY,
condo_id VARCHAR(36) NOT NULL,
description VARCHAR(255) NOT NULL,
supplier_name VARCHAR(255),
amount DECIMAL(10, 2) NOT NULL,
payment_date ${TIMESTAMP_TYPE} NULL,
status VARCHAR(20) DEFAULT 'UNPAID',
payment_method VARCHAR(50),
invoice_number VARCHAR(100),
notes TEXT,
created_at ${TIMESTAMP_TYPE} DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (condo_id) REFERENCES condos(id) ON DELETE CASCADE
)
`);
await connection.query(`
CREATE TABLE IF NOT EXISTS condo_expense_attachments (
id VARCHAR(36) PRIMARY KEY,
condo_expense_id VARCHAR(36) NOT NULL,
file_name VARCHAR(255) NOT NULL,
file_type VARCHAR(100),
data ${LONG_TEXT_TYPE},
created_at ${TIMESTAMP_TYPE} DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (condo_expense_id) REFERENCES condo_expenses(id) ON DELETE CASCADE
)
`);
// --- SEEDING --- // --- SEEDING ---
const [rows] = await connection.query('SELECT * FROM settings WHERE id = 1'); const [rows] = await connection.query('SELECT * FROM settings WHERE id = 1');
const defaultFeatures = { const defaultFeatures = {
@@ -430,7 +343,8 @@ const initDb = async () => {
payPal: true, payPal: true,
notices: true, notices: true,
reports: true, reports: true,
extraordinaryExpenses: true extraordinaryExpenses: true,
condoFinancialsView: false
}; };
if (rows.length === 0) { if (rows.length === 0) {
@@ -443,11 +357,10 @@ const initDb = async () => {
// Ensure features column has defaults if null // Ensure features column has defaults if null
if (!rows[0].features) { if (!rows[0].features) {
await connection.query('UPDATE settings SET features = ? WHERE id = 1', [JSON.stringify(defaultFeatures)]); await connection.query('UPDATE settings SET features = ? WHERE id = 1', [JSON.stringify(defaultFeatures)]);
console.log("Seeded default features settings.");
} }
} }
// ENSURE ADMIN EXISTS AND HAS CORRECT ROLE // ENSURE ADMIN EXISTS
const [admins] = await connection.query('SELECT * FROM users WHERE email = ?', ['fcarra79@gmail.com']); const [admins] = await connection.query('SELECT * FROM users WHERE email = ?', ['fcarra79@gmail.com']);
if (admins.length === 0) { if (admins.length === 0) {
const hashedPassword = await bcrypt.hash('Mr10921.', 10); const hashedPassword = await bcrypt.hash('Mr10921.', 10);
@@ -456,11 +369,8 @@ const initDb = async () => {
'INSERT INTO users (id, email, password_hash, name, role) VALUES (?, ?, ?, ?, ?)', 'INSERT INTO users (id, email, password_hash, name, role) VALUES (?, ?, ?, ?, ?)',
[uuidv4(), 'fcarra79@gmail.com', hashedPassword, 'Amministratore', 'admin'] [uuidv4(), 'fcarra79@gmail.com', hashedPassword, 'Amministratore', 'admin']
); );
console.log('Default Admin user created.');
} else { } else {
// Force update role to admin just in case it was changed or created wrongly
await connection.query('UPDATE users SET role = ? WHERE email = ?', ['admin', 'fcarra79@gmail.com']); await connection.query('UPDATE users SET role = ? WHERE email = ?', ['admin', 'fcarra79@gmail.com']);
console.log('Ensured default user has admin role.');
} }
console.log('Database tables initialized.'); console.log('Database tables initialized.');