const Database = require('better-sqlite3'); const bcrypt = require('bcryptjs'); const path = require('path'); // 创建数据库连接 const dbPath = path.join(__dirname, '../data/database.sqlite'); const db = new Database(dbPath, { verbose: console.log }); // 创建表 const createTables = () => { // 用户表 db.exec(` CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password TEXT NOT NULL, name TEXT NOT NULL, email TEXT, role TEXT DEFAULT 'user', created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ) `); // 企业表 db.exec(` CREATE TABLE IF NOT EXISTS companies ( id INTEGER PRIMARY KEY AUTOINCREMENT, company_name TEXT UNIQUE NOT NULL, is_active BOOLEAN DEFAULT 1, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ) `); // 序列号表 db.exec(` CREATE TABLE IF NOT EXISTS serials ( id INTEGER PRIMARY KEY AUTOINCREMENT, serial_number TEXT UNIQUE NOT NULL, company_name TEXT NOT NULL, valid_until DATETIME, is_active BOOLEAN DEFAULT 1, created_by INTEGER, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (created_by) REFERENCES users (id), FOREIGN KEY (company_name) REFERENCES companies (company_name) ) `); // 创建索引 db.exec('CREATE INDEX IF NOT EXISTS idx_company_name_companies ON companies (company_name)'); db.exec('CREATE INDEX IF NOT EXISTS idx_serial_number ON serials (serial_number)'); db.exec('CREATE INDEX IF NOT EXISTS idx_company_name_serials ON serials (company_name)'); db.exec('CREATE INDEX IF NOT EXISTS idx_created_by ON serials (created_by)'); console.log('数据库表创建完成'); }; // 创建默认管理员用户 const createDefaultUser = async () => { const username = 'admin'; const password = 'Beifan@2026'; const name = '系统管理员'; // 检查用户是否已存在 const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username); if (!user) { // 哈希密码 const hashedPassword = await bcrypt.hash(password, 10); // 创建用户 db.prepare( 'INSERT INTO users (username, password, name, email, role) VALUES (?, ?, ?, ?, ?)' ).run(username, hashedPassword, name, 'admin@example.com', 'admin'); console.log('默认管理员用户创建完成:'); console.log('用户名:', username); console.log('密码:', password); } else { console.log('默认管理员用户已存在'); } }; // 初始化数据库 const initDatabase = async () => { createTables(); await createDefaultUser(); // 关闭数据库连接 db.close(); console.log('数据库连接已关闭'); }; initDatabase();