const path = require('path');
const envFile = process.env.NODE_ENV === 'production'
? '.env.production'
: '.env';
require('dotenv').config({ path: path.join(__dirname, '../', envFile) });
const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const { sequelize, SysUser, SystemConfig } = require('./models');
const { errorHandler, notFound } = require('./middlewares/errorHandler');
const app = express();
app.use(cors({ origin: process.env.CORS_ORIGIN || '*' }));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(morgan('dev'));
app.get('/health', (req, res) => {
res.json({ status: 'ok', time: new Date().toISOString() });
});
require('./routes')(app);
app.use(notFound);
app.use(errorHandler);
async function initDatabase() {
try {
await sequelize.authenticate();
console.log('✅ 数据库连接成功');
await sequelize.sync();
console.log('✅ 数据表同步完成');
if (sequelize.getDialect() === 'mysql') {
await sequelize.query('ALTER TABLE app_user AUTO_INCREMENT = 100000');
console.log('✅ app_user AUTO_INCREMENT = 100000');
} else {
try {
await sequelize.query("UPDATE sqlite_sequence SET seq = 99999 WHERE name = 'app_user'");
console.log('✅ app_user AUTOINCREMENT = 100000');
} catch (e) {
console.log('ℹ️ app_user AUTOINCREMENT 跳过(表可能为空)');
}
}
const adminExists = await SysUser.findOne({ where: { username: 'admin' } });
if (!adminExists) {
await SysUser.create({
username: 'admin',
password: 'admin123',
nickname: '超级管理员',
role: 'super',
});
console.log('✅ 默认管理员创建成功');
console.log(' 用户名: admin');
console.log(' 密码: admin123');
console.log(' ⚠️ 请及时修改默认密码!');
}
const defaultConfigs = [
{
config_key: 'callback_base_url',
config_value: process.env.CALLBACK_BASE_URL || `http://localhost:${process.env.PORT || 3001}`,
description: '回调基础地址,用于生成各平台的回调URL',
},
];
for (const cfg of defaultConfigs) {
const exists = await SystemConfig.findOne({ where: { config_key: cfg.config_key } });
if (!exists) {
await SystemConfig.create(cfg);
console.log(`✅ 系统配置 [${cfg.config_key}] 初始化完成: ${cfg.config_value}`);
}
}
} catch (err) {
console.error('❌ 数据库初始化失败:', err.message);
process.exit(1);
}
}
const PORT = process.env.PORT || 3001;
initDatabase().then(() => {
app.listen(PORT, () => {
console.log('');
console.log('🚀 聚合赚钱App管理后台 启动成功');
console.log(` 管理后台API: http://localhost:${PORT}`);
console.log(` 回调接收地址: http://localhost:${PORT}/api/callback/:platform_code`);
console.log(` 健康检查: http://localhost:${PORT}/health`);
console.log('');
});
}).catch(err => {
console.error('启动失败:', err);
});
module.exports = app;