48 lines
1.7 KiB
JavaScript
Executable File
48 lines
1.7 KiB
JavaScript
Executable File
const Database = require('better-sqlite3');
|
|
const path = require('path');
|
|
const fs = require('fs');
|
|
|
|
const dbPath = process.env.DB_PATH || path.join(__dirname, '..', 'data', 'cpas.db');
|
|
const dir = path.dirname(dbPath);
|
|
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
|
|
|
const db = new Database(dbPath);
|
|
db.pragma('journal_mode = WAL');
|
|
db.pragma('foreign_keys = ON');
|
|
|
|
const schema = fs.readFileSync(path.join(__dirname, 'schema.sql'), 'utf8');
|
|
db.exec(schema);
|
|
|
|
// Migrate: add negated columns if upgrading from Phase 1-3
|
|
const cols = db.prepare("PRAGMA table_info(violations)").all().map(c => c.name);
|
|
if (!cols.includes('negated')) db.exec("ALTER TABLE violations ADD COLUMN negated INTEGER NOT NULL DEFAULT 0");
|
|
if (!cols.includes('negated_at')) db.exec("ALTER TABLE violations ADD COLUMN negated_at DATETIME");
|
|
|
|
// After adding columns + resolutions table, ensure view is correct
|
|
db.exec(`
|
|
DROP VIEW IF EXISTS active_cpas_scores;
|
|
CREATE VIEW active_cpas_scores AS
|
|
SELECT
|
|
employee_id,
|
|
SUM(points) AS active_points,
|
|
COUNT(*) AS violation_count
|
|
FROM violations
|
|
WHERE negated = 0
|
|
AND incident_date >= DATE('now', '-90 days')
|
|
GROUP BY employee_id;
|
|
`);
|
|
|
|
|
|
// Ensure resolutions table exists on upgrade
|
|
db.exec(`CREATE TABLE IF NOT EXISTS violation_resolutions (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
violation_id INTEGER NOT NULL REFERENCES violations(id) ON DELETE CASCADE,
|
|
resolution_type TEXT NOT NULL,
|
|
details TEXT,
|
|
resolved_by TEXT,
|
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
)`);
|
|
|
|
console.log('[DB] Connected:', dbPath);
|
|
module.exports = db;
|