fbab5486创建于 3 天前历史提交
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() });
});

// ============ 路由模块加载 ============
// routes/index.js 统一注册所有路由
require('./routes')(app);


// 404
app.use(notFound);

// 错误处理
app.use(errorHandler);


// 初始化数据库 + 创建默认管理员
async function initDatabase() {
  try {
    // 测试数据库连接
    await sequelize.authenticate();
    console.log('✅ 数据库连接成功');

    // 同步模型到数据库(只创建新表,不修改已有表结构,避免索引累积)
    await sequelize.sync();
    console.log('✅ 数据表同步完成');

    // 设置 app_user 表自增起始值为 100000(仅 MySQL)
    if (sequelize.getDialect() === 'mysql') {
      await sequelize.query('ALTER TABLE app_user AUTO_INCREMENT = 100000');
      console.log('✅ app_user AUTO_INCREMENT = 100000');
    } else {
      // SQLite: 通过 sqlite_sequence 表设置起始值
      try {
        await sequelize.query("UPDATE sqlite_sequence SET seq = 99999 WHERE name = 'app_user'");
        console.log('✅ app_user AUTOINCREMENT = 100000');
      } catch (e) {
        // sqlite_sequence 可能不存在(表为空时),忽略
        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('   ⚠️ 请及时修改默认密码!');
    }

    // 初始化默认 system_config 配置项
    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;