Files
estimation-flow/src/lib/db.ts
T

81 lines
1.9 KiB
TypeScript
Raw Normal View History

2025-07-17 11:12:35 +00:00
import Database from 'better-sqlite3';
// Use a file-based database in development
const db = new Database('local.db');
2025-07-18 04:52:21 +00:00
// --- SCHEMA CREATION ---
2025-07-17 11:12:35 +00:00
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
name TEXT NOT NULL
)
`);
2025-07-17 11:21:35 +00:00
db.exec(`
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT
)
`);
db.exec(`
CREATE TABLE IF NOT EXISTS email_templates (
id INTEGER PRIMARY KEY,
subject TEXT,
body TEXT
)
`);
db.exec(`
CREATE TABLE IF NOT EXISTS leads (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL,
phone TEXT,
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
db.exec(`
CREATE TABLE IF NOT EXISTS flows (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT,
2025-07-18 04:52:21 +00:00
path TEXT NOT NULL UNIQUE,
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
2025-07-18 04:52:21 +00:00
// --- SEEDING LOGIC ---
console.log('Running database checks and seeding if necessary...');
// Seed default user
const userStmt = db.prepare('SELECT id FROM users WHERE id = ?');
const defaultUser = userStmt.get(1);
if (!defaultUser) {
const insertUser = db.prepare(
"INSERT INTO users (id, email, password, name) VALUES (?, ?, ?, ?)"
);
insertUser.run(1, 'admin@example.com', 'password', 'Admin User');
console.log('Default user created.');
}
// Seed default flow
const flowStmt = db.prepare("SELECT id FROM flows WHERE path = ?");
const defaultFlow = flowStmt.get('/');
if (!defaultFlow) {
const insertFlow = db.prepare(
"INSERT INTO flows (name, description, path) VALUES (?, ?, ?)"
);
insertFlow.run('Cost Estimator', 'The main cost estimation tool for clients.', '/');
console.log('Default flow created.');
}
console.log('Database setup complete.');
2025-07-17 11:21:35 +00:00
2025-07-17 11:12:35 +00:00
export default db;