85 lines
2.6 KiB
TypeScript
85 lines
2.6 KiB
TypeScript
import Database from 'better-sqlite3';
|
|
import bcrypt from 'bcryptjs';
|
|
import path from 'path';
|
|
|
|
const dbPath = path.join(process.cwd(), 'data/database.sqlite');
|
|
const db = new Database(dbPath, { verbose: console.log });
|
|
|
|
const createTables = (): void => {
|
|
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 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 (): Promise<void> => {
|
|
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 (): Promise<void> => {
|
|
createTables();
|
|
await createDefaultUser();
|
|
db.close();
|
|
console.log('数据库连接已关闭');
|
|
};
|
|
|
|
initDatabase();
|