Initial commit: kefu-server-saas v2.0
客服服务器完整源码,包含: - Express HTTP服务 (port 9501) - WebSocket服务 (port 9502) - SaaS多租户认证 - 坐席管理、消息管理、连接管理 - SQLite数据库(5张核心表) - 管理后台 (/admin) - 坐席工作台 (/agent, /agent-mobile) - 商城REST API (/plugin.yunqian-api) - 消息推送API (/message/push) 技术栈:Node.js 18 + Express 4 + ws 8 + better-sqlite3 + EJS + PM2
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
# SaaS 客服服务器配置
|
||||
|
||||
PORT=9501
|
||||
WSS_PORT=9502
|
||||
|
||||
# 默认租户(超级管理员,可管理所有商城)
|
||||
# 如果不配置,首个访问管理后台的租户自动设为管理员
|
||||
DEFAULT_ADMIN_APP_ID=
|
||||
DEFAULT_ADMIN_APP_SECRET=
|
||||
|
||||
# 数据库
|
||||
DB_PATH=./data/kefu-saas.db
|
||||
|
||||
# 管理后台
|
||||
ADMIN_PASSWORD=admin123
|
||||
SESSION_SECRET=kefu-saas-secret-2026
|
||||
|
||||
# 日志级别: debug/info/warn/error
|
||||
LOG_LEVEL=info
|
||||
@@ -0,0 +1,21 @@
|
||||
module.exports = {
|
||||
apps: [{
|
||||
name: 'kefu-saas',
|
||||
script: './src/app.js',
|
||||
cwd: '/www/wwwroot/kf.199ms.com',
|
||||
instances: 1,
|
||||
exec_mode: 'cluster',
|
||||
env: {
|
||||
NODE_ENV: 'production',
|
||||
PORT: 9501,
|
||||
WSS_PORT: 9502
|
||||
},
|
||||
error_file: './logs/err.log',
|
||||
out_file: './logs/out.log',
|
||||
log_date_format: 'YYYY-MM-DD HH:mm:ss Z',
|
||||
merge_logs: true,
|
||||
max_memory_restart: '300M',
|
||||
watch: false,
|
||||
autorestart: true
|
||||
}]
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "kefu-server-saas",
|
||||
"version": "2.0.0",
|
||||
"description": "SaaS 客服服务器 - 多租户坐席管理与实时消息",
|
||||
"main": "src/app.js",
|
||||
"scripts": {
|
||||
"start": "node src/app.js",
|
||||
"dev": "node --watch src/app.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.7.2",
|
||||
"better-sqlite3": "^11.0.0",
|
||||
"cookie-parser": "^1.4.6",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.4.5",
|
||||
"ejs": "^3.1.10",
|
||||
"express": "^4.19.2",
|
||||
"express-session": "^1.18.0",
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"binary": {
|
||||
"module_name": "better_sqlite3",
|
||||
"module_path": "./build/Release/",
|
||||
"host": "https://registry.npmmirror.com/-/binary/better-sqlite3"
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
const http = require('http');
|
||||
const path = require('path');
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const cookieParser = require('cookie-parser');
|
||||
const session = require('express-session');
|
||||
const config = require('./config');
|
||||
const logger = require('./lib/logger');
|
||||
const { startWssServer } = require('./lib/wss-server');
|
||||
const { initDatabase } = require('./db/init-db');
|
||||
|
||||
// 初始化数据库
|
||||
initDatabase();
|
||||
|
||||
const app = express();
|
||||
|
||||
app.set('view engine', 'ejs');
|
||||
app.set('views', path.join(__dirname, '..', 'views'));
|
||||
|
||||
app.use(cors({ origin: true, credentials: true }));
|
||||
app.use(cookieParser());
|
||||
app.use(express.json({ limit: '10mb' }));
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
app.use(session({
|
||||
name: 'kefu_saas_session',
|
||||
secret: config.server.sessionSecret,
|
||||
resave: false,
|
||||
saveUninitialized: false,
|
||||
cookie: { httpOnly: true, maxAge: 4 * 60 * 60 * 1000 },
|
||||
}));
|
||||
|
||||
app.use('/static', express.static(path.join(__dirname, '..', 'public')));
|
||||
|
||||
app.use((req, res, next) => {
|
||||
logger.debug('HTTP', `${req.method} ${req.url}`, { ip: req.ip });
|
||||
next();
|
||||
});
|
||||
|
||||
// 路由
|
||||
app.use(require('./controllers/rest.controller'));
|
||||
app.use(require('./controllers/push.controller'));
|
||||
app.use(require('./controllers/admin.controller'));
|
||||
app.use(require('./controllers/agent.controller'));
|
||||
|
||||
app.get('/health', (req, res) => {
|
||||
const connMgr = require('./lib/connection-manager');
|
||||
const agentMgr = require('./lib/agent-manager');
|
||||
const tenantMgr = require('./lib/tenant-manager');
|
||||
res.json({
|
||||
status: 'ok',
|
||||
time: new Date().toISOString(),
|
||||
uptime: process.uptime(),
|
||||
connections: connMgr.getSummary(),
|
||||
tenants: { total: tenantMgr.getAllTenants().length },
|
||||
});
|
||||
});
|
||||
|
||||
app.get('/', (req, res) => res.redirect('/admin'));
|
||||
|
||||
app.use((req, res) => {
|
||||
if (req.path.startsWith('/message/') || req.path.startsWith('/plugin.')) {
|
||||
return res.status(404).json({ result: 0, msg: '接口不存在: ' + req.path });
|
||||
}
|
||||
res.status(404).send('404 Not Found');
|
||||
});
|
||||
|
||||
app.use((err, req, res, next) => {
|
||||
logger.error('HTTP', `未捕获错误: ${err.message}`, err.stack);
|
||||
if (req.path.startsWith('/message/') || req.path.startsWith('/plugin.')) {
|
||||
return res.status(500).json({ result: 0, msg: '服务器内部错误: ' + err.message });
|
||||
}
|
||||
res.status(500).send('服务器内部错误');
|
||||
});
|
||||
|
||||
const httpPort = config.server.port;
|
||||
const wssPort = config.server.wssPort;
|
||||
|
||||
const httpServer = http.createServer(app);
|
||||
startWssServer(null, wssPort);
|
||||
|
||||
httpServer.listen(httpPort, () => {
|
||||
logger.info('App', '═══════════════════════════════════════════════════');
|
||||
logger.info('App', 'SaaS 客服服务器已启动');
|
||||
logger.info('App', `HTTP API : http://0.0.0.0:${httpPort}`);
|
||||
logger.info('App', `WebSocket : ws://0.0.0.0:${wssPort}`);
|
||||
logger.info('App', `管理后台 : http://0.0.0.0:${httpPort}/admin`);
|
||||
logger.info('App', `健康检查 : http://0.0.0.0:${httpPort}/health`);
|
||||
logger.info('App', '───────────────────────────────────────────────────');
|
||||
logger.info('App', '部署说明:修改商城数据库 yz_settings 表中');
|
||||
logger.info('App', ' plugin.yun-chat 的三个地址配置:');
|
||||
logger.info('App', ` yunqian_remote_host → http://<本机IP>:${httpPort}/`);
|
||||
logger.info('App', ` yunqian_push_host → http://<本机IP>:${httpPort}/`);
|
||||
logger.info('App', ` yunqian_wss_host → ws://<本机IP>:${wssPort}`);
|
||||
logger.info('App', '═══════════════════════════════════════════════════');
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
const path = require('path');
|
||||
require('dotenv').config({ path: path.join(__dirname, '..', '..', '.env') });
|
||||
|
||||
module.exports = {
|
||||
server: {
|
||||
port: parseInt(process.env.PORT, 10) || 9501,
|
||||
wssPort: parseInt(process.env.WSS_PORT, 10) || 9502,
|
||||
sessionSecret: process.env.SESSION_SECRET || 'kefu-saas-default-secret',
|
||||
adminPassword: process.env.ADMIN_PASSWORD || 'admin123',
|
||||
logLevel: process.env.LOG_LEVEL || 'info',
|
||||
},
|
||||
db: {
|
||||
path: process.env.DB_PATH || './data/kefu-saas.db',
|
||||
},
|
||||
auth: {
|
||||
defaultAdminAppId: process.env.DEFAULT_ADMIN_APP_ID || '',
|
||||
defaultAdminAppSecret: process.env.DEFAULT_ADMIN_APP_SECRET || '',
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,102 @@
|
||||
const express = require('express');
|
||||
const config = require('../config');
|
||||
const tenantMgr = require('../lib/tenant-manager');
|
||||
const agentMgr = require('../lib/agent-manager');
|
||||
const connMgr = require('../lib/connection-manager');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
function requireAdminLogin(req, res, next) {
|
||||
if (!req.session || !req.session.adminLoggedIn) {
|
||||
return res.redirect('/admin/login');
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
router.get('/admin/login', (req, res) => {
|
||||
res.render('login', { error: null });
|
||||
});
|
||||
|
||||
router.post('/admin/login', (req, res) => {
|
||||
const { password } = req.body;
|
||||
if (password === config.server.adminPassword) {
|
||||
req.session.adminLoggedIn = true;
|
||||
return res.json({ success: true });
|
||||
}
|
||||
return res.status(401).json({ success: false, message: '密码错误' });
|
||||
});
|
||||
|
||||
router.get('/admin/logout', (req, res) => {
|
||||
req.session.destroy(() => res.redirect('/admin/login'));
|
||||
});
|
||||
|
||||
router.get('/admin', requireAdminLogin, (req, res) => {
|
||||
const tenants = tenantMgr.getAllTenants();
|
||||
const summary = connMgr.getSummary();
|
||||
const pushLogs = connMgr.getPushLogs(50);
|
||||
|
||||
res.render('admin', {
|
||||
tenants,
|
||||
summary,
|
||||
pushLogs,
|
||||
serverConfig: {
|
||||
port: config.server.port,
|
||||
wssPort: config.server.wssPort,
|
||||
logLevel: config.server.logLevel,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
router.get('/admin/tenants', requireAdminLogin, (req, res) => {
|
||||
const tenants = tenantMgr.getAllTenants();
|
||||
res.json({ success: true, data: tenants });
|
||||
});
|
||||
|
||||
router.post('/admin/tenants', requireAdminLogin, (req, res) => {
|
||||
try {
|
||||
const data = req.body;
|
||||
const tenant = tenantMgr.createTenant(data);
|
||||
return res.json({ success: true, data: tenant });
|
||||
} catch (e) {
|
||||
return res.status(500).json({ success: false, message: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
router.put('/admin/tenants/:id', requireAdminLogin, (req, res) => {
|
||||
try {
|
||||
const id = parseInt(req.params.id, 10);
|
||||
const result = tenantMgr.updateTenant(id, req.body);
|
||||
return res.json({ success: result });
|
||||
} catch (e) {
|
||||
return res.status(500).json({ success: false, message: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/admin/tenants/:id', requireAdminLogin, (req, res) => {
|
||||
try {
|
||||
const id = parseInt(req.params.id, 10);
|
||||
const result = tenantMgr.deleteTenant(id);
|
||||
return res.json({ success: result });
|
||||
} catch (e) {
|
||||
return res.status(500).json({ success: false, message: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/admin/api/connections', requireAdminLogin, (req, res) => {
|
||||
const tenantId = parseInt(req.query.tenantId, 10) || 0;
|
||||
res.json({ success: true, data: connMgr.getAllConnections(tenantId) });
|
||||
});
|
||||
|
||||
router.get('/admin/api/agents', requireAdminLogin, (req, res) => {
|
||||
const tenantId = parseInt(req.query.tenantId, 10) || 0;
|
||||
if (tenantId <= 0) return res.json({ success: false, message: '需要指定 tenantId' });
|
||||
res.json({ success: true, data: agentMgr.getAllAgents(tenantId) });
|
||||
});
|
||||
|
||||
router.get('/admin/api/logs', requireAdminLogin, (req, res) => {
|
||||
const limit = parseInt(req.query.limit, 10) || 50;
|
||||
const tenantId = parseInt(req.query.tenantId, 10) || 0;
|
||||
res.json({ success: true, data: connMgr.getPushLogs(limit, tenantId) });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,231 @@
|
||||
const express = require('express');
|
||||
const tenantMgr = require('../lib/tenant-manager');
|
||||
const msgMgr = require('../lib/message-manager');
|
||||
const agentStatusMgr = require('../lib/agent-status-manager');
|
||||
const connMgr = require('../lib/connection-manager');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// 生成签名
|
||||
function generateSignature(appId, appSecret, nonceStr, timestamp) {
|
||||
return crypto.createHash('md5').update(`${appId}_${appSecret}_${nonceStr}_${timestamp}`).digest('hex').toUpperCase();
|
||||
}
|
||||
|
||||
// 坐席 session 校验中间件
|
||||
function requireAgentSession(req, res, next) {
|
||||
if (!req.session || !req.session.agentInfo) {
|
||||
return res.status(401).json({ success: false, message: '未登录' });
|
||||
}
|
||||
req.agentInfo = req.session.agentInfo;
|
||||
next();
|
||||
}
|
||||
|
||||
// 坐席登录页
|
||||
router.get('/agent', (req, res) => {
|
||||
const tenants = tenantMgr.getAllTenants();
|
||||
res.render('agent-login', { tenants, error: null });
|
||||
});
|
||||
|
||||
// 坐席登录验证
|
||||
router.post('/agent/login', (req, res) => {
|
||||
const { app_id, app_secret, agent_id } = req.body;
|
||||
|
||||
if (!app_id || !app_secret) {
|
||||
return res.json({ success: false, message: '缺少 AppID 或 AppSecret' });
|
||||
}
|
||||
|
||||
const tenant = tenantMgr.getTenantByAppId(app_id);
|
||||
if (!tenant || tenant.app_secret !== app_secret) {
|
||||
return res.status(401).json({ success: false, message: 'AppID 或 AppSecret 错误' });
|
||||
}
|
||||
|
||||
const timestamp = Date.now();
|
||||
const nonceStr = Math.random().toString(36).substring(2, 18);
|
||||
const signature = generateSignature(app_id, app_secret, nonceStr, timestamp);
|
||||
|
||||
// 获取 agent_id: 如果没有传入,自动分配一个
|
||||
let finalAgentId = agent_id;
|
||||
if (!finalAgentId) {
|
||||
finalAgentId = `agent_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
|
||||
}
|
||||
|
||||
req.session.agentInfo = {
|
||||
app_id,
|
||||
app_secret,
|
||||
agent_id: finalAgentId,
|
||||
tenant_id: tenant.id,
|
||||
tenant_name: tenant.name,
|
||||
timestamp,
|
||||
nonceStr,
|
||||
signature,
|
||||
};
|
||||
|
||||
// 初始化坐席状态记录
|
||||
agentStatusMgr.setStatus(tenant.id, finalAgentId, 'offline');
|
||||
|
||||
res.json({ success: true, agent_id: finalAgentId });
|
||||
});
|
||||
|
||||
// 坐席工作台
|
||||
router.get('/agent/dashboard', (req, res) => {
|
||||
if (!req.session || !req.session.agentInfo) {
|
||||
return res.redirect('/agent');
|
||||
}
|
||||
|
||||
const agentInfo = req.session.agentInfo;
|
||||
res.render('agent-dashboard', { agentInfo });
|
||||
});
|
||||
|
||||
// 坐席登出
|
||||
router.get('/agent/logout', (req, res) => {
|
||||
if (req.session.agentInfo) {
|
||||
const { tenant_id, agent_id } = req.session.agentInfo;
|
||||
agentStatusMgr.setStatus(tenant_id, agent_id, 'offline');
|
||||
}
|
||||
req.session.agentInfo = null;
|
||||
res.redirect('/agent');
|
||||
});
|
||||
|
||||
// ============ 聊天 API ============
|
||||
|
||||
// 获取会话列表
|
||||
router.get('/agent/api/conversations', requireAgentSession, (req, res) => {
|
||||
const tenantId = req.agentInfo.tenant_id;
|
||||
const conversations = msgMgr.getConversationList(tenantId, 200);
|
||||
|
||||
// 合并在线状态
|
||||
const enriched = conversations.map(conv => {
|
||||
const isOnline = connMgr.isOnline(conv.clientid);
|
||||
return {
|
||||
...conv,
|
||||
online: isOnline,
|
||||
};
|
||||
});
|
||||
|
||||
res.json({ success: true, data: enriched });
|
||||
});
|
||||
|
||||
// 获取聊天历史记录
|
||||
router.get('/agent/api/messages/history', requireAgentSession, (req, res) => {
|
||||
const tenantId = req.agentInfo.tenant_id;
|
||||
const { clientid, before_id, limit } = req.query;
|
||||
|
||||
if (!clientid) {
|
||||
return res.status(400).json({ success: false, message: '缺少 clientid' });
|
||||
}
|
||||
|
||||
const lim = Math.min(parseInt(limit, 10) || 50, 200);
|
||||
const beforeId = parseInt(before_id, 10) || 0;
|
||||
const messages = msgMgr.getHistory(tenantId, clientid, lim, beforeId);
|
||||
|
||||
res.json({ success: true, data: messages });
|
||||
});
|
||||
|
||||
// 标记消息已读
|
||||
router.post('/agent/api/messages/read', requireAgentSession, (req, res) => {
|
||||
const tenantId = req.agentInfo.tenant_id;
|
||||
const { clientid } = req.body;
|
||||
|
||||
if (!clientid) {
|
||||
return res.status(400).json({ success: false, message: '缺少 clientid' });
|
||||
}
|
||||
|
||||
const result = msgMgr.markAsRead(tenantId, clientid, 'agent');
|
||||
res.json({ success: true, ...result });
|
||||
});
|
||||
|
||||
// 获取未读消息数
|
||||
router.get('/agent/api/messages/unread', requireAgentSession, (req, res) => {
|
||||
const tenantId = req.agentInfo.tenant_id;
|
||||
const { clientid } = req.query;
|
||||
|
||||
if (clientid) {
|
||||
const count = msgMgr.getUnreadCount(tenantId, clientid, 'agent');
|
||||
return res.json({ success: true, count });
|
||||
}
|
||||
|
||||
const unreadMap = msgMgr.getUnreadCounts(tenantId, 'agent');
|
||||
res.json({ success: true, data: unreadMap });
|
||||
});
|
||||
|
||||
// ============ 坐席状态 API ============
|
||||
|
||||
// 获取当前坐席状态
|
||||
router.get('/agent/api/status', requireAgentSession, (req, res) => {
|
||||
const { agent_id } = req.agentInfo;
|
||||
const status = agentStatusMgr.getStatus(agent_id);
|
||||
res.json({ success: true, data: status });
|
||||
});
|
||||
|
||||
// 设置坐席状态
|
||||
router.post('/agent/api/status', requireAgentSession, (req, res) => {
|
||||
const { tenant_id, agent_id } = req.agentInfo;
|
||||
const { status } = req.body;
|
||||
|
||||
const validStatuses = ['online', 'busy', 'offline'];
|
||||
if (!validStatuses.includes(status)) {
|
||||
return res.status(400).json({ success: false, message: '无效的状态' });
|
||||
}
|
||||
|
||||
const result = agentStatusMgr.setStatus(tenant_id, agent_id, status);
|
||||
res.json({ success: true, data: result });
|
||||
});
|
||||
|
||||
// 获取坐席统计
|
||||
router.get('/agent/api/stats', requireAgentSession, (req, res) => {
|
||||
const { tenant_id, agent_id } = req.agentInfo;
|
||||
const status = agentStatusMgr.getStatus(agent_id);
|
||||
|
||||
// 获取今日消息数
|
||||
const todayStart = new Date();
|
||||
todayStart.setHours(0, 0, 0, 0);
|
||||
const todayTs = Math.floor(todayStart.getTime() / 1000);
|
||||
|
||||
const db = require('../db/db');
|
||||
const todayMessages = db.prepare(`
|
||||
SELECT COUNT(*) as cnt FROM sys_chat_messages
|
||||
WHERE tenant_id = ? AND agent_id = ? AND created_at >= ?
|
||||
`).get(tenant_id, agent_id, todayTs);
|
||||
|
||||
// 会话总数
|
||||
const totalConversations = db.prepare(`
|
||||
SELECT COUNT(DISTINCT clientid) as cnt FROM sys_chat_messages
|
||||
WHERE tenant_id = ? AND agent_id = ?
|
||||
`).get(tenant_id, agent_id);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
status: status.status,
|
||||
total_sessions: status.total_sessions || 0,
|
||||
total_messages: status.total_messages || 0,
|
||||
today_messages: todayMessages?.cnt || 0,
|
||||
total_conversations: totalConversations?.cnt || 0,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// ============ 连接参数 API ============
|
||||
|
||||
// 获取 WSS 连接参数(刷新签名)
|
||||
router.get('/agent/api/wss-config', requireAgentSession, (req, res) => {
|
||||
const { app_id, app_secret, agent_id } = req.agentInfo;
|
||||
|
||||
const timestamp = Date.now();
|
||||
const nonceStr = Math.random().toString(36).substring(2, 18);
|
||||
const signature = generateSignature(app_id, app_secret, nonceStr, timestamp);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
appId: app_id,
|
||||
signature,
|
||||
nonceStr,
|
||||
timestamp,
|
||||
agentId: agent_id,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,59 @@
|
||||
const express = require('express');
|
||||
const connMgr = require('../lib/connection-manager');
|
||||
const logger = require('../lib/logger');
|
||||
const { parseClientId } = require('../lib/clientid');
|
||||
const { saasAuth } = require('../middleware/auth.middleware');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.post('/message/push/to/one', saasAuth, (req, res) => {
|
||||
const { userIds, data } = req.body;
|
||||
|
||||
if (!userIds || !Array.isArray(userIds) || userIds.length === 0) {
|
||||
return res.status(400).json({ result: 0, msg: '缺少 userIds 参数' });
|
||||
}
|
||||
if (data === undefined || data === null) {
|
||||
return res.status(400).json({ result: 0, msg: '缺少 data 参数' });
|
||||
}
|
||||
|
||||
const message = typeof data === 'string' ? data : JSON.stringify(data);
|
||||
|
||||
logger.info('PushAPI', `推送消息到 ${userIds.length} 个目标: 商城 ${req.tenant.app_id}`, {
|
||||
targets: userIds.slice(0, 5),
|
||||
preview: message.substring(0, 200),
|
||||
});
|
||||
|
||||
const result = connMgr.pushToClients(userIds, message, req.tenant.id);
|
||||
logger.info('PushAPI', `推送结果: online=${result.onlineCount}, offline=${result.offlineCount}`);
|
||||
|
||||
return res.json({ data: { onlineStatus: result.onlineStatus } });
|
||||
});
|
||||
|
||||
router.post('/message/push/to/all', saasAuth, (req, res) => {
|
||||
const { data } = req.body;
|
||||
if (data === undefined) {
|
||||
return res.status(400).json({ result: 0, msg: '缺少 data 参数' });
|
||||
}
|
||||
|
||||
const message = typeof data === 'string' ? data : JSON.stringify(data);
|
||||
const allConnections = connMgr.getAllConnections(req.tenant.id);
|
||||
const allClientIds = allConnections.map((c) => c.clientid);
|
||||
|
||||
const result = connMgr.pushToClients(allClientIds, message, req.tenant.id);
|
||||
|
||||
logger.info('PushAPI', `广播消息: 商城 ${req.tenant.app_id}, ${allClientIds.length} 个客户端`);
|
||||
|
||||
return res.json({ data: { onlineStatus: result.onlineStatus } });
|
||||
});
|
||||
|
||||
router.get('/message/online/check', saasAuth, (req, res) => {
|
||||
const { clientid } = req.query;
|
||||
if (!clientid) {
|
||||
return res.status(400).json({ result: 0, msg: '缺少 clientid 参数' });
|
||||
}
|
||||
|
||||
const online = connMgr.isOnline(clientid);
|
||||
return res.json({ data: { onlineStatus: online ? 1 : 0 } });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,66 @@
|
||||
const express = require('express');
|
||||
const agentMgr = require('../lib/agent-manager');
|
||||
const logger = require('../lib/logger');
|
||||
const { saasAuth } = require('../middleware/auth.middleware');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.post('/plugin.yunqian-api.api.call.summary', saasAuth, (req, res) => {
|
||||
try {
|
||||
const summary = agentMgr.getSummary(req.tenant.id);
|
||||
summary.end_time_str = summary.end_time ? new Date(summary.end_time * 1000).toISOString().split('T')[0] : '';
|
||||
if (summary.recharge_list) {
|
||||
summary.recharge_list.forEach((item) => {
|
||||
if (item.end_time) {
|
||||
item.end_time_str = new Date(item.end_time * 1000).toISOString().split('T')[0];
|
||||
}
|
||||
});
|
||||
}
|
||||
logger.info('REST', `summary 请求: 商城 ${req.tenant.app_id}`);
|
||||
return res.json({ result: 1, msg: 'success', data: summary });
|
||||
} catch (error) {
|
||||
logger.error('REST', `summary 失败: ${error.message}`);
|
||||
return res.json({ result: 0, msg: error.message, data: null });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/plugin.yunqian-api.api.call.setAgentV2', saasAuth, (req, res) => {
|
||||
try {
|
||||
const { agent_type } = req.body;
|
||||
const agentType = parseInt(agent_type, 10) || 0;
|
||||
const result = agentMgr.setAgent(req.tenant.id, agentType);
|
||||
logger.info('REST', `setAgentV2: 商城 ${req.tenant.app_id}, agent_id=${result.agent_id}`);
|
||||
return res.json({ result: 1, msg: 'success', data: result });
|
||||
} catch (error) {
|
||||
logger.error('REST', `setAgentV2 失败: ${error.message}`);
|
||||
return res.json({ result: 0, msg: error.message, data: null });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/plugin.yunqian-api.api.call.setAgent', saasAuth, (req, res) => {
|
||||
try {
|
||||
const result = agentMgr.setAgent(req.tenant.id, 0);
|
||||
logger.info('REST', `setAgent: 商城 ${req.tenant.app_id}, agent_id=${result.agent_id}`);
|
||||
return res.json({ result: 1, msg: 'success', data: result });
|
||||
} catch (error) {
|
||||
logger.error('REST', `setAgent 失败: ${error.message}`);
|
||||
return res.json({ result: 0, msg: error.message, data: null });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/plugin.yunqian-api.api.call.removeAgent', saasAuth, (req, res) => {
|
||||
try {
|
||||
const { agent_id } = req.body;
|
||||
if (!agent_id) {
|
||||
return res.json({ result: 0, msg: '缺少 agent_id 参数' });
|
||||
}
|
||||
agentMgr.removeAgent(req.tenant.id, agent_id);
|
||||
logger.info('REST', `removeAgent: 商城 ${req.tenant.app_id}, agent_id=${agent_id}`);
|
||||
return res.json({ result: 1, msg: 'ok' });
|
||||
} catch (error) {
|
||||
logger.error('REST', `removeAgent 失败: ${error.message}`);
|
||||
return res.json({ result: 0, msg: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,15 @@
|
||||
const Database = require('better-sqlite3');
|
||||
const path = require('path');
|
||||
const config = require('../config');
|
||||
const logger = require('../lib/logger');
|
||||
|
||||
const dbPath = path.resolve(config.db.path);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
// 启用外键约束
|
||||
db.pragma('journal_mode = WAL');
|
||||
db.pragma('foreign_keys = ON');
|
||||
|
||||
logger.info('DB', `SQLite 数据库已连接: ${dbPath}`);
|
||||
|
||||
module.exports = db;
|
||||
@@ -0,0 +1,99 @@
|
||||
const db = require('./db');
|
||||
const logger = require('../lib/logger');
|
||||
|
||||
function initDatabase() {
|
||||
// 租户表
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS sys_tenants (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
app_id TEXT NOT NULL UNIQUE,
|
||||
app_secret TEXT NOT NULL,
|
||||
name TEXT,
|
||||
domain TEXT,
|
||||
agent_limit INTEGER DEFAULT -1,
|
||||
agent_used INTEGER DEFAULT 0,
|
||||
agent_end_time INTEGER DEFAULT 0,
|
||||
agent_alloc_type INTEGER DEFAULT 0,
|
||||
status INTEGER DEFAULT 1,
|
||||
is_admin INTEGER DEFAULT 0,
|
||||
created_at INTEGER DEFAULT 0,
|
||||
updated_at INTEGER DEFAULT 0
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_tenants_app_id ON sys_tenants(app_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_tenants_status ON sys_tenants(status);
|
||||
`);
|
||||
|
||||
// 坐席表
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS sys_agents (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
agent_id TEXT NOT NULL UNIQUE,
|
||||
agent_type INTEGER DEFAULT 0,
|
||||
employee_id INTEGER DEFAULT 0,
|
||||
allocated_at INTEGER DEFAULT 0,
|
||||
removed_at INTEGER DEFAULT 0,
|
||||
status INTEGER DEFAULT 1,
|
||||
FOREIGN KEY (tenant_id) REFERENCES sys_tenants(id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_agents_tenant ON sys_agents(tenant_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_agents_agent_id ON sys_agents(agent_id);
|
||||
`);
|
||||
|
||||
// 聊天消息表
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS sys_chat_messages (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
clientid TEXT NOT NULL,
|
||||
agent_id TEXT,
|
||||
msg_type TEXT DEFAULT 'text',
|
||||
content TEXT,
|
||||
from_role TEXT NOT NULL,
|
||||
from_clientid TEXT,
|
||||
to_clientid TEXT,
|
||||
is_read INTEGER DEFAULT 0,
|
||||
read_at INTEGER DEFAULT 0,
|
||||
created_at INTEGER DEFAULT 0
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_chat_tenant ON sys_chat_messages(tenant_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_chat_clientid ON sys_chat_messages(clientid);
|
||||
CREATE INDEX IF NOT EXISTS idx_chat_agent ON sys_chat_messages(agent_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_chat_unread ON sys_chat_messages(is_read, agent_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_chat_created ON sys_chat_messages(created_at);
|
||||
`);
|
||||
|
||||
// 坐席状态表
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS sys_agent_status (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
agent_id TEXT NOT NULL UNIQUE,
|
||||
status TEXT DEFAULT 'offline',
|
||||
current_clientid TEXT,
|
||||
last_active INTEGER DEFAULT 0,
|
||||
total_sessions INTEGER DEFAULT 0,
|
||||
total_messages INTEGER DEFAULT 0,
|
||||
updated_at INTEGER DEFAULT 0
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_agent_status_tenant ON sys_agent_status(tenant_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_agent_status_agent ON sys_agent_status(agent_id);
|
||||
`);
|
||||
|
||||
// 推送日志表
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS sys_push_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
clientid TEXT,
|
||||
target_type TEXT,
|
||||
message_preview TEXT,
|
||||
created_at INTEGER DEFAULT 0
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_push_tenant ON sys_push_logs(tenant_id);
|
||||
`);
|
||||
|
||||
logger.info('DB', '数据库表初始化完成');
|
||||
}
|
||||
|
||||
module.exports = { initDatabase };
|
||||
@@ -0,0 +1,118 @@
|
||||
const db = require('../db/db');
|
||||
const logger = require('./logger');
|
||||
const { generateNonceStr } = require('./crypto-utils');
|
||||
|
||||
class AgentManager {
|
||||
/**
|
||||
* 分配坐席(按实际配额限制)
|
||||
* @param {number} tenantId
|
||||
* @param {number} agentType 0=免费,1=收费
|
||||
*/
|
||||
setAgent(tenantId, agentType = 0) {
|
||||
const tenant = db.prepare('SELECT * FROM sys_tenants WHERE id = ?').get(tenantId);
|
||||
if (!tenant) throw new Error('商城不存在');
|
||||
|
||||
// 检查配额
|
||||
const agentLimit = tenant.agent_limit || 10;
|
||||
const agentUsed = tenant.agent_used || 0;
|
||||
if (agentUsed >= agentLimit) {
|
||||
throw new Error('坐席配额已满');
|
||||
}
|
||||
|
||||
const agentId = this._generateAgentId();
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
|
||||
const stmt = db.prepare(`
|
||||
INSERT INTO sys_agents (tenant_id, agent_id, agent_type, allocated_at, status)
|
||||
VALUES (?, ?, ?, ?, 1)
|
||||
`);
|
||||
stmt.run(tenantId, agentId, agentType, now);
|
||||
|
||||
// 更新租户已用坐席数
|
||||
db.prepare('UPDATE sys_tenants SET agent_used = agent_used + 1 WHERE id = ?').run(tenantId);
|
||||
|
||||
logger.info('AgentMgr', `分配坐席: ${agentId} 到商城 ${tenantId}`, { type: agentType });
|
||||
return { agent_id: agentId };
|
||||
}
|
||||
|
||||
/**
|
||||
* 释放坐席
|
||||
*/
|
||||
removeAgent(tenantId, agentId) {
|
||||
const agent = db.prepare('SELECT * FROM sys_agents WHERE agent_id = ? AND tenant_id = ? AND status = 1').get(agentId, tenantId);
|
||||
if (!agent) {
|
||||
logger.warn('AgentMgr', `释放坐席: ${agentId} 不存在或已释放`);
|
||||
return { msg: 'ok' };
|
||||
}
|
||||
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
db.prepare('UPDATE sys_agents SET status = 0, removed_at = ? WHERE id = ?').run(now, agent.id);
|
||||
db.prepare('UPDATE sys_tenants SET agent_used = MAX(0, agent_used - 1) WHERE id = ?').run(tenantId);
|
||||
|
||||
logger.info('AgentMgr', `释放坐席: ${agentId} (商城 ${tenantId})`);
|
||||
return { msg: 'ok' };
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取配额摘要(返回实际配额)
|
||||
*/
|
||||
getSummary(tenantId) {
|
||||
const tenant = db.prepare('SELECT * FROM sys_tenants WHERE id = ?').get(tenantId);
|
||||
if (!tenant) {
|
||||
return {
|
||||
total_agent: 10,
|
||||
used_agent: 0,
|
||||
end_time: 1798752000,
|
||||
end_time_str: '2026-12-31',
|
||||
recharge_list: [
|
||||
{
|
||||
max_agent_count: 10,
|
||||
month_msg_count: 0,
|
||||
max_msg_count: 10000,
|
||||
end_time: 1798752000,
|
||||
end_time_str: '2026-12-31'
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
// 返回实际配额(从租户表读取)
|
||||
const agentLimit = tenant.agent_limit || 10;
|
||||
const agentUsed = tenant.agent_used || 0;
|
||||
const endTime = tenant.agent_end_time || 1798752000;
|
||||
const endTimeStr = endTime > 0 ? new Date(endTime * 1000).toISOString().split('T')[0] : '2026-12-31';
|
||||
|
||||
return {
|
||||
total_agent: agentLimit,
|
||||
used_agent: agentUsed,
|
||||
end_time: endTime,
|
||||
end_time_str: endTimeStr,
|
||||
recharge_list: [
|
||||
{
|
||||
max_agent_count: agentLimit,
|
||||
month_msg_count: 0,
|
||||
max_msg_count: 10000,
|
||||
end_time: endTime,
|
||||
end_time_str: endTimeStr
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
getAllAgents(tenantId) {
|
||||
return db.prepare('SELECT * FROM sys_agents WHERE tenant_id = ? ORDER BY allocated_at DESC').all(tenantId);
|
||||
}
|
||||
|
||||
getCount(tenantId) {
|
||||
const row = db.prepare('SELECT COUNT(*) as cnt FROM sys_agents WHERE tenant_id = ? AND status = 1').get(tenantId);
|
||||
return row ? row.cnt : 0;
|
||||
}
|
||||
|
||||
_generateAgentId() {
|
||||
const ts = Date.now().toString().slice(-10);
|
||||
const rand = generateNonceStr(4);
|
||||
return `agent_${ts}_${rand}`;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new AgentManager();
|
||||
@@ -0,0 +1,116 @@
|
||||
const db = require('../db/db');
|
||||
const logger = require('./logger');
|
||||
|
||||
class AgentStatusManager {
|
||||
/**
|
||||
* 更新坐席状态
|
||||
* @param {number} tenantId
|
||||
* @param {string} agentId
|
||||
* @param {string} status - online | busy | offline
|
||||
*/
|
||||
setStatus(tenantId, agentId, status) {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
|
||||
// 确保 agentId 有关联的 tenant_id
|
||||
const existing = db.prepare('SELECT id FROM sys_agent_status WHERE agent_id = ?').get(agentId);
|
||||
|
||||
if (existing) {
|
||||
db.prepare(`
|
||||
UPDATE sys_agent_status
|
||||
SET status = ?, updated_at = ?
|
||||
WHERE agent_id = ?
|
||||
`).run(status, now, agentId);
|
||||
} else {
|
||||
db.prepare(`
|
||||
INSERT INTO sys_agent_status (tenant_id, agent_id, status, last_active, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
`).run(tenantId, agentId, status, now, now);
|
||||
}
|
||||
|
||||
logger.info('AgentStatus', `坐席 ${agentId} 状态变更: ${status}`);
|
||||
return { agent_id: agentId, status, updated_at: now };
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取坐席状态
|
||||
*/
|
||||
getStatus(agentId) {
|
||||
const row = db.prepare('SELECT * FROM sys_agent_status WHERE agent_id = ?').get(agentId);
|
||||
return row || { agent_id: agentId, status: 'offline' };
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取租户下所有坐席状态
|
||||
*/
|
||||
getStatusesByTenant(tenantId) {
|
||||
return db.prepare('SELECT * FROM sys_agent_status WHERE tenant_id = ? ORDER BY updated_at DESC').all(tenantId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取在线坐席列表
|
||||
*/
|
||||
getOnlineAgents(tenantId) {
|
||||
return db.prepare(`
|
||||
SELECT * FROM sys_agent_status
|
||||
WHERE tenant_id = ? AND status = 'online'
|
||||
`).all(tenantId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新最后活跃时间
|
||||
*/
|
||||
updateLastActive(agentId) {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
db.prepare('UPDATE sys_agent_status SET last_active = ? WHERE agent_id = ?').run(now, agentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置当前接待客户
|
||||
*/
|
||||
setCurrentClient(agentId, clientid) {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
db.prepare(`
|
||||
UPDATE sys_agent_status SET current_clientid = ?, updated_at = ?
|
||||
WHERE agent_id = ?
|
||||
`).run(clientid, now, agentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 增加会话计数
|
||||
*/
|
||||
incrementSessions(agentId) {
|
||||
db.prepare(`
|
||||
UPDATE sys_agent_status SET total_sessions = total_sessions + 1, updated_at = ?
|
||||
WHERE agent_id = ?
|
||||
`).run(Math.floor(Date.now() / 1000), agentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 增加消息计数
|
||||
*/
|
||||
incrementMessages(agentId) {
|
||||
db.prepare(`
|
||||
UPDATE sys_agent_status SET total_messages = total_messages + 1, updated_at = ?
|
||||
WHERE agent_id = ?
|
||||
`).run(Math.floor(Date.now() / 1000), agentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动将超时坐席标记为离线
|
||||
*/
|
||||
autoOffline(timeoutSeconds = 120) {
|
||||
const cutoff = Math.floor(Date.now() / 1000) - timeoutSeconds;
|
||||
const result = db.prepare(`
|
||||
UPDATE sys_agent_status
|
||||
SET status = 'offline'
|
||||
WHERE status != 'offline' AND last_active < ?
|
||||
`).run(cutoff);
|
||||
|
||||
if (result.changes > 0) {
|
||||
logger.info('AgentStatus', `自动离线: ${result.changes} 个超时坐席`);
|
||||
}
|
||||
return result.changes;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new AgentStatusManager();
|
||||
@@ -0,0 +1,22 @@
|
||||
function parseClientId(clientid) {
|
||||
if (!clientid || typeof clientid !== 'string') return null;
|
||||
const parts = clientid.split('_');
|
||||
if (parts.length < 6 || parts[0] !== 'type') return null;
|
||||
const channel = parts[1], appId = parts[2], uniacid = parts[3], role = parts[4];
|
||||
if (role === 'customer' && parts.length >= 7) {
|
||||
return { type: 'type', channel, appId, uniacid, role: 'customer', uid: parts[5], agentId: parts[6], raw: clientid };
|
||||
} else if (role === 'employee') {
|
||||
return { type: 'type', channel, appId, uniacid, role: 'employee', uid: null, agentId: parts[5], raw: clientid };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildCustomerClientId(channel, appId, uniacid, uid, agentId) {
|
||||
return `type_${channel}_${appId}_${uniacid}_customer_${uid}_${agentId}`;
|
||||
}
|
||||
|
||||
function buildEmployeeClientId(channel, appId, uniacid, agentId) {
|
||||
return `type_${channel}_${appId}_${uniacid}_employee_${agentId}`;
|
||||
}
|
||||
|
||||
module.exports = { parseClientId, buildCustomerClientId, buildEmployeeClientId };
|
||||
@@ -0,0 +1,229 @@
|
||||
const logger = require('./logger');
|
||||
const { parseClientId } = require('./clientid');
|
||||
|
||||
const clientMap = new Map();
|
||||
const uidMap = new Map();
|
||||
const agentMap = new Map();
|
||||
const tenantConnMap = new Map(); // tenantId -> Set<clientid>
|
||||
const pushLogs = [];
|
||||
const MAX_LOGS = 200;
|
||||
|
||||
class ConnectionManager {
|
||||
register(clientid, ws, meta = {}) {
|
||||
const parsed = parseClientId(clientid);
|
||||
const record = {
|
||||
clientid,
|
||||
ws,
|
||||
tenantId: meta.tenantId || 0,
|
||||
ip: meta.ip || '',
|
||||
connectTime: meta.connectTime || new Date(),
|
||||
lastPing: new Date(),
|
||||
parsed,
|
||||
};
|
||||
|
||||
// 如果该 clientid 已有旧连接,先关闭
|
||||
if (clientMap.has(clientid)) {
|
||||
const old = clientMap.get(clientid);
|
||||
try { old.ws.close(4000, 'duplicate connection'); } catch (_) {}
|
||||
this._removeFromIndexes(clientid, old.tenantId, old.parsed);
|
||||
}
|
||||
|
||||
clientMap.set(clientid, record);
|
||||
|
||||
// 建立索引
|
||||
if (parsed) {
|
||||
if (parsed.uid) {
|
||||
if (!uidMap.has(parsed.uid)) uidMap.set(parsed.uid, new Set());
|
||||
uidMap.get(parsed.uid).add(clientid);
|
||||
}
|
||||
if (parsed.agentId) {
|
||||
if (!agentMap.has(parsed.agentId)) agentMap.set(parsed.agentId, new Set());
|
||||
agentMap.get(parsed.agentId).add(clientid);
|
||||
}
|
||||
}
|
||||
if (record.tenantId) {
|
||||
if (!tenantConnMap.has(record.tenantId)) tenantConnMap.set(record.tenantId, new Set());
|
||||
tenantConnMap.get(record.tenantId).add(clientid);
|
||||
}
|
||||
|
||||
logger.info('ConnMgr', `注册连接: ${clientid}`, { tenantId: record.tenantId, ip: record.ip, total: clientMap.size });
|
||||
}
|
||||
|
||||
unregister(clientid) {
|
||||
const record = clientMap.get(clientid);
|
||||
if (!record) return;
|
||||
this._removeFromIndexes(clientid, record.tenantId, record.parsed);
|
||||
clientMap.delete(clientid);
|
||||
logger.info('ConnMgr', `注销连接: ${clientid}`, { total: clientMap.size });
|
||||
}
|
||||
|
||||
_removeFromIndexes(clientid, tenantId, parsed) {
|
||||
if (parsed) {
|
||||
if (parsed.uid && uidMap.has(parsed.uid)) {
|
||||
uidMap.get(parsed.uid).delete(clientid);
|
||||
if (uidMap.get(parsed.uid).size === 0) uidMap.delete(parsed.uid);
|
||||
}
|
||||
if (parsed.agentId && agentMap.has(parsed.agentId)) {
|
||||
agentMap.get(parsed.agentId).delete(clientid);
|
||||
if (agentMap.get(parsed.agentId).size === 0) agentMap.delete(parsed.agentId);
|
||||
}
|
||||
}
|
||||
if (tenantId && tenantConnMap.has(tenantId)) {
|
||||
tenantConnMap.get(tenantId).delete(clientid);
|
||||
if (tenantConnMap.get(tenantId).size === 0) tenantConnMap.delete(tenantId);
|
||||
}
|
||||
}
|
||||
|
||||
getByClientId(clientid) {
|
||||
return clientMap.get(clientid);
|
||||
}
|
||||
|
||||
getByUid(uid) {
|
||||
const ids = uidMap.get(String(uid));
|
||||
if (!ids || ids.size === 0) return [];
|
||||
const result = [];
|
||||
for (const id of ids) {
|
||||
const rec = clientMap.get(id);
|
||||
if (rec && rec.ws.readyState === 1) result.push(rec);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
getByAgentId(agentId) {
|
||||
const ids = agentMap.get(String(agentId));
|
||||
if (!ids || ids.size === 0) return [];
|
||||
const result = [];
|
||||
for (const id of ids) {
|
||||
const rec = clientMap.get(id);
|
||||
if (rec && rec.ws.readyState === 1) result.push(rec);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
isOnline(clientid) {
|
||||
const rec = clientMap.get(clientid);
|
||||
return !!(rec && rec.ws.readyState === 1);
|
||||
}
|
||||
|
||||
isUidOnline(uid) {
|
||||
return this.getByUid(uid).length > 0;
|
||||
}
|
||||
|
||||
isAgentOnline(agentId) {
|
||||
return this.getByAgentId(agentId).length > 0;
|
||||
}
|
||||
|
||||
pushToClients(targetClientIds, data, tenantId = 0) {
|
||||
const message = typeof data === 'string' ? data : JSON.stringify(data);
|
||||
let onlineCount = 0, offlineCount = 0;
|
||||
|
||||
for (const cid of targetClientIds) {
|
||||
const rec = clientMap.get(cid);
|
||||
|
||||
// 跨租户安全检查
|
||||
if (tenantId > 0 && rec && rec.tenantId !== tenantId) {
|
||||
logger.warn('ConnMgr', `跨租户推送拦截: 商城 ${tenantId} -> ${cid} (商城 ${rec.tenantId})`);
|
||||
this._addPushLog(cid, 'blocked', message, tenantId);
|
||||
offlineCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (rec && rec.ws.readyState === 1) {
|
||||
try {
|
||||
rec.ws.send(message);
|
||||
onlineCount++;
|
||||
this._addPushLog(cid, 'sent', message, tenantId);
|
||||
} catch (e) {
|
||||
logger.error('ConnMgr', `推送失败: ${cid}`, e.message);
|
||||
offlineCount++;
|
||||
this._addPushLog(cid, 'error', e.message, tenantId);
|
||||
}
|
||||
} else {
|
||||
offlineCount++;
|
||||
this._addPushLog(cid, 'offline', message, tenantId);
|
||||
}
|
||||
}
|
||||
|
||||
return { onlineCount, offlineCount, onlineStatus: onlineCount > 0 ? 1 : 0 };
|
||||
}
|
||||
|
||||
getSummary() {
|
||||
let customers = 0, employees = 0;
|
||||
for (const rec of clientMap.values()) {
|
||||
if (rec.parsed?.role === 'customer') customers++;
|
||||
else if (rec.parsed?.role === 'employee') employees++;
|
||||
}
|
||||
return { totalConnections: clientMap.size, onlineCustomers: customers, onlineEmployees: employees };
|
||||
}
|
||||
|
||||
getAllConnections(tenantId = 0) {
|
||||
const list = [];
|
||||
for (const rec of clientMap.values()) {
|
||||
if (tenantId > 0 && rec.tenantId !== tenantId) continue;
|
||||
list.push({
|
||||
clientid: rec.clientid,
|
||||
ip: rec.ip,
|
||||
connectTime: rec.connectTime.toISOString(),
|
||||
lastPing: rec.lastPing.toISOString(),
|
||||
role: rec.parsed?.role || 'unknown',
|
||||
uid: rec.parsed?.uid || null,
|
||||
agentId: rec.parsed?.agentId || null,
|
||||
channel: rec.parsed?.channel || null,
|
||||
tenantId: rec.tenantId,
|
||||
readyState: rec.ws.readyState,
|
||||
});
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
getConnectionsByTenant(tenantId) {
|
||||
const ids = tenantConnMap.get(tenantId);
|
||||
if (!ids) return [];
|
||||
const list = [];
|
||||
for (const id of ids) {
|
||||
const rec = clientMap.get(id);
|
||||
if (rec) list.push(rec);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
updatePing(clientid) {
|
||||
const rec = clientMap.get(clientid);
|
||||
if (rec) rec.lastPing = new Date();
|
||||
}
|
||||
|
||||
getPushLogs(limit = 50, tenantId = 0) {
|
||||
if (tenantId > 0) {
|
||||
return pushLogs.filter(l => l.tenantId === tenantId).slice(-limit).reverse();
|
||||
}
|
||||
return pushLogs.slice(-limit).reverse();
|
||||
}
|
||||
|
||||
_addPushLog(clientid, status, message, tenantId = 0) {
|
||||
pushLogs.push({
|
||||
time: new Date().toISOString(),
|
||||
clientid,
|
||||
status,
|
||||
message: message.substring(0, 300),
|
||||
tenantId,
|
||||
});
|
||||
if (pushLogs.length > MAX_LOGS) pushLogs.shift();
|
||||
}
|
||||
|
||||
cleanupStale(timeoutMs = 60000) {
|
||||
const now = Date.now();
|
||||
let cleaned = 0;
|
||||
for (const [clientid, rec] of clientMap.entries()) {
|
||||
if (now - rec.lastPing.getTime() > timeoutMs) {
|
||||
try { rec.ws.terminate(); } catch (_) {}
|
||||
this.unregister(clientid);
|
||||
cleaned++;
|
||||
}
|
||||
}
|
||||
if (cleaned > 0) {
|
||||
logger.info('ConnMgr', `清理超时连接: ${cleaned} 个`, { remaining: clientMap.size });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new ConnectionManager();
|
||||
@@ -0,0 +1,37 @@
|
||||
const crypto = require('crypto');
|
||||
|
||||
function generateNonceStr(length = 16) {
|
||||
const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
|
||||
let result = '';
|
||||
for (let i = 0; i < length; i++) {
|
||||
result += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function md5(str) {
|
||||
return crypto.createHash('md5').update(str, 'utf8').digest('hex');
|
||||
}
|
||||
|
||||
function generateSignature(appId, appSecret, nonceStr, timestamp) {
|
||||
const raw = `${appId}_${appSecret}_${nonceStr}_${timestamp}`;
|
||||
return md5(raw).toUpperCase();
|
||||
}
|
||||
|
||||
function verifySignature(appId, signature, nonceStr, timestamp, appSecret, maxAgeMs = 300000) {
|
||||
if (!appId || !signature || !nonceStr || !timestamp) {
|
||||
return { valid: false, reason: '缺少认证参数' };
|
||||
}
|
||||
const now = Date.now();
|
||||
const ts = parseInt(timestamp, 10);
|
||||
if (isNaN(ts) || Math.abs(now - ts) > maxAgeMs) {
|
||||
return { valid: false, reason: `时间戳超出有效窗口,服务器时间: ${now}, 请求时间: ${ts}` };
|
||||
}
|
||||
const expected = generateSignature(appId, appSecret, nonceStr, timestamp);
|
||||
if (expected !== signature) {
|
||||
return { valid: false, reason: `签名不匹配,期望: ${expected}, 收到: ${signature}` };
|
||||
}
|
||||
return { valid: true, reason: 'OK' };
|
||||
}
|
||||
|
||||
module.exports = { generateNonceStr, md5, generateSignature, verifySignature };
|
||||
@@ -0,0 +1,28 @@
|
||||
const config = require('../config');
|
||||
const LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
|
||||
const currentLevel = LEVELS[config.server.logLevel] ?? LEVELS.info;
|
||||
|
||||
function format(level, tag, msg, extra) {
|
||||
const ts = new Date().toISOString();
|
||||
let line = `[${ts}] [${level.toUpperCase()}] [${tag}] ${msg}`;
|
||||
if (extra !== undefined) {
|
||||
const str = typeof extra === 'string' ? extra : JSON.stringify(extra);
|
||||
line += ` | ${str.substring(0, 500)}`;
|
||||
}
|
||||
return line;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
debug: (tag, msg, extra) => {
|
||||
if (currentLevel <= LEVELS.debug) console.log(format('debug', tag, msg, extra));
|
||||
},
|
||||
info: (tag, msg, extra) => {
|
||||
if (currentLevel <= LEVELS.info) console.log(format('info', tag, msg, extra));
|
||||
},
|
||||
warn: (tag, msg, extra) => {
|
||||
if (currentLevel <= LEVELS.warn) console.warn(format('warn', tag, msg, extra));
|
||||
},
|
||||
error: (tag, msg, extra) => {
|
||||
if (currentLevel <= LEVELS.error) console.error(format('error', tag, msg, extra));
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,141 @@
|
||||
const db = require('../db/db');
|
||||
const logger = require('./logger');
|
||||
|
||||
class MessageManager {
|
||||
/**
|
||||
* 保存消息
|
||||
*/
|
||||
saveMessage(data) {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const stmt = db.prepare(`
|
||||
INSERT INTO sys_chat_messages
|
||||
(tenant_id, clientid, agent_id, msg_type, content, from_role, from_clientid, to_clientid, is_read, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
const result = stmt.run(
|
||||
data.tenant_id || 0,
|
||||
data.clientid || '',
|
||||
data.agent_id || null,
|
||||
data.msg_type || 'text',
|
||||
data.content || '',
|
||||
data.from_role || 'customer',
|
||||
data.from_clientid || null,
|
||||
data.to_clientid || null,
|
||||
0,
|
||||
now
|
||||
);
|
||||
logger.debug('MsgMgr', `保存消息: id=${result.lastInsertRowid}, from=${data.from_role}`, {
|
||||
clientid: data.clientid,
|
||||
type: data.msg_type,
|
||||
});
|
||||
return { id: result.lastInsertRowid, created_at: now };
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取聊天历史记录
|
||||
*/
|
||||
getHistory(tenantId, clientid, limit = 50, beforeId = 0) {
|
||||
let sql, params;
|
||||
if (beforeId > 0) {
|
||||
sql = `SELECT * FROM sys_chat_messages WHERE tenant_id = ? AND clientid = ? AND id < ? ORDER BY id DESC LIMIT ?`;
|
||||
params = [tenantId, clientid, beforeId, limit];
|
||||
} else {
|
||||
sql = `SELECT * FROM sys_chat_messages WHERE tenant_id = ? AND clientid = ? ORDER BY id DESC LIMIT ?`;
|
||||
params = [tenantId, clientid, limit];
|
||||
}
|
||||
const rows = db.prepare(sql).all(...params);
|
||||
return rows.reverse(); // 返回正序
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记消息为已读
|
||||
*/
|
||||
markAsRead(tenantId, clientid, byRole = 'agent') {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
// 如果是坐席标记已读,标记来自客户的消息为已读
|
||||
// 如果是客户标记已读,标记来自坐席的消息为已读
|
||||
const fromRole = byRole === 'agent' ? 'customer' : 'agent';
|
||||
const result = db.prepare(`
|
||||
UPDATE sys_chat_messages
|
||||
SET is_read = 1, read_at = ?
|
||||
WHERE tenant_id = ? AND clientid = ? AND from_role = ? AND is_read = 0
|
||||
`).run(now, tenantId, clientid, fromRole);
|
||||
|
||||
logger.debug('MsgMgr', `标记已读: ${result.changes} 条`, { clientid, byRole });
|
||||
return { updated: result.changes };
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取未读消息数
|
||||
*/
|
||||
getUnreadCount(tenantId, clientid, byRole = 'agent') {
|
||||
const fromRole = byRole === 'agent' ? 'customer' : 'agent';
|
||||
const row = db.prepare(`
|
||||
SELECT COUNT(*) as cnt FROM sys_chat_messages
|
||||
WHERE tenant_id = ? AND clientid = ? AND from_role = ? AND is_read = 0
|
||||
`).get(tenantId, clientid, fromRole);
|
||||
return row ? row.cnt : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量获取未读数(用于客户列表)
|
||||
*/
|
||||
getUnreadCounts(tenantId, byRole = 'agent') {
|
||||
const fromRole = byRole === 'agent' ? 'customer' : 'agent';
|
||||
const rows = db.prepare(`
|
||||
SELECT clientid, COUNT(*) as cnt
|
||||
FROM sys_chat_messages
|
||||
WHERE tenant_id = ? AND from_role = ? AND is_read = 0
|
||||
GROUP BY clientid
|
||||
`).all(tenantId, fromRole);
|
||||
const map = {};
|
||||
for (const row of rows) {
|
||||
map[row.clientid] = row.cnt;
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取会话列表(有消息记录的客户)
|
||||
*/
|
||||
getConversationList(tenantId, limit = 100) {
|
||||
const rows = db.prepare(`
|
||||
SELECT
|
||||
m.clientid,
|
||||
MAX(m.id) as last_msg_id,
|
||||
MAX(m.created_at) as last_msg_time,
|
||||
COUNT(CASE WHEN m.from_role = 'customer' AND m.is_read = 0 THEN 1 END) as unread_count,
|
||||
(
|
||||
SELECT content FROM sys_chat_messages
|
||||
WHERE tenant_id = m.tenant_id AND clientid = m.clientid
|
||||
ORDER BY id DESC LIMIT 1
|
||||
) as last_msg_content,
|
||||
(
|
||||
SELECT msg_type FROM sys_chat_messages
|
||||
WHERE tenant_id = m.tenant_id AND clientid = m.clientid
|
||||
ORDER BY id DESC LIMIT 1
|
||||
) as last_msg_type
|
||||
FROM sys_chat_messages m
|
||||
WHERE m.tenant_id = ?
|
||||
GROUP BY m.clientid
|
||||
ORDER BY last_msg_time DESC
|
||||
LIMIT ?
|
||||
`).all(tenantId, limit);
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取离线消息(坐席上线时同步)
|
||||
*/
|
||||
getOfflineMessages(tenantId, agentId, afterTimestamp = 0) {
|
||||
const rows = db.prepare(`
|
||||
SELECT * FROM sys_chat_messages
|
||||
WHERE tenant_id = ? AND from_role = 'customer' AND created_at > ?
|
||||
ORDER BY id ASC
|
||||
`).all(tenantId, afterTimestamp);
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new MessageManager();
|
||||
@@ -0,0 +1,92 @@
|
||||
const db = require('../db/db');
|
||||
const logger = require('./logger');
|
||||
const { generateNonceStr } = require('./crypto-utils');
|
||||
|
||||
class TenantManager {
|
||||
constructor() {
|
||||
// 缓存:appId -> tenant
|
||||
this.cache = new Map();
|
||||
}
|
||||
|
||||
getTenantByAppId(appId) {
|
||||
if (this.cache.has(appId)) return this.cache.get(appId);
|
||||
const row = db.prepare('SELECT * FROM sys_tenants WHERE app_id = ? AND status = 1').get(appId);
|
||||
if (row) this.cache.set(appId, row);
|
||||
return row || null;
|
||||
}
|
||||
|
||||
getTenantById(id) {
|
||||
return db.prepare('SELECT * FROM sys_tenants WHERE id = ?').get(id);
|
||||
}
|
||||
|
||||
getAllTenants() {
|
||||
return db.prepare('SELECT * FROM sys_tenants ORDER BY created_at DESC').all();
|
||||
}
|
||||
|
||||
createTenant(data) {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const stmt = db.prepare(`
|
||||
INSERT INTO sys_tenants (app_id, app_secret, name, domain, agent_limit, agent_end_time, agent_alloc_type, status, is_admin, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
const appId = data.app_id || generateNonceStr(8);
|
||||
const appSecret = data.app_secret || generateNonceStr(16);
|
||||
const result = stmt.run(
|
||||
appId, appSecret, data.name || '', data.domain || '',
|
||||
data.agent_limit ?? -1, data.agent_end_time ?? 0,
|
||||
data.agent_alloc_type ?? 0, data.status ?? 1,
|
||||
data.is_admin ?? 0, now, now
|
||||
);
|
||||
this.cache.delete(appId);
|
||||
logger.info('TenantMgr', `创建商城: ${appId}`, { id: result.lastInsertRowid });
|
||||
return { id: result.lastInsertRowid, app_id: appId, app_secret: appSecret };
|
||||
}
|
||||
|
||||
updateTenant(id, data) {
|
||||
const fields = [];
|
||||
const values = [];
|
||||
const allowed = ['name', 'domain', 'agent_limit', 'agent_end_time', 'agent_alloc_type', 'status', 'is_admin'];
|
||||
for (const key of allowed) {
|
||||
if (data[key] !== undefined) {
|
||||
fields.push(`${key} = ?`);
|
||||
values.push(data[key]);
|
||||
}
|
||||
}
|
||||
if (fields.length === 0) return false;
|
||||
fields.push('updated_at = ?');
|
||||
values.push(Math.floor(Date.now() / 1000));
|
||||
values.push(id);
|
||||
|
||||
const stmt = db.prepare(`UPDATE sys_tenants SET ${fields.join(', ')} WHERE id = ?`);
|
||||
const result = stmt.run(...values);
|
||||
|
||||
// 清除缓存
|
||||
const tenant = this.getTenantById(id);
|
||||
if (tenant) this.cache.delete(tenant.app_id);
|
||||
|
||||
logger.info('TenantMgr', `更新商城: ${id}`);
|
||||
return result.changes > 0;
|
||||
}
|
||||
|
||||
deleteTenant(id) {
|
||||
const tenant = this.getTenantById(id);
|
||||
if (tenant) this.cache.delete(tenant.app_id);
|
||||
const result = db.prepare('DELETE FROM sys_tenants WHERE id = ?').run(id);
|
||||
logger.info('TenantMgr', `删除商城: ${id}`);
|
||||
return result.changes > 0;
|
||||
}
|
||||
|
||||
incrementAgentUsed(tenantId, delta = 1) {
|
||||
db.prepare('UPDATE sys_tenants SET agent_used = agent_used + ? WHERE id = ?').run(delta, tenantId);
|
||||
const tenant = this.getTenantById(tenantId);
|
||||
if (tenant) this.cache.set(tenant.app_id, { ...tenant, agent_used: tenant.agent_used + delta });
|
||||
}
|
||||
|
||||
decrementAgentUsed(tenantId, delta = 1) {
|
||||
db.prepare('UPDATE sys_tenants SET agent_used = MAX(0, agent_used - ?) WHERE id = ?').run(delta, tenantId);
|
||||
const tenant = this.getTenantById(tenantId);
|
||||
if (tenant) this.cache.set(tenant.app_id, { ...tenant, agent_used: Math.max(0, tenant.agent_used - delta) });
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new TenantManager();
|
||||
@@ -0,0 +1,326 @@
|
||||
const { WebSocketServer } = require('ws');
|
||||
const url = require('url');
|
||||
const config = require('../config');
|
||||
const logger = require('./logger');
|
||||
const { verifySignature } = require('./crypto-utils');
|
||||
const { parseClientId } = require('./clientid');
|
||||
const tenantMgr = require('./tenant-manager');
|
||||
const connMgr = require('./connection-manager');
|
||||
const msgMgr = require('./message-manager');
|
||||
const agentStatusMgr = require('./agent-status-manager');
|
||||
|
||||
function getAppSecret(appId) {
|
||||
const tenant = tenantMgr.getTenantByAppId(appId);
|
||||
if (tenant) return tenant.app_secret;
|
||||
return null;
|
||||
}
|
||||
|
||||
function startWssServer(httpServer, port) {
|
||||
let wss;
|
||||
if (httpServer) {
|
||||
wss = new WebSocketServer({ noServer: true });
|
||||
httpServer.on('upgrade', (request, socket, head) => {
|
||||
wss.handleUpgrade(request, socket, head, (ws) => {
|
||||
wss.emit('connection', ws, request);
|
||||
});
|
||||
});
|
||||
logger.info('WSS', 'WebSocket 服务挂载到 HTTP 服务器');
|
||||
} else {
|
||||
wss = new WebSocketServer({ port });
|
||||
logger.info('WSS', `WebSocket 服务独立监听端口: ${port}`);
|
||||
}
|
||||
|
||||
wss.on('connection', (ws, req) => {
|
||||
const parsedUrl = url.parse(req.url, true);
|
||||
const query = parsedUrl.query;
|
||||
const ip = req.socket.remoteAddress || '';
|
||||
|
||||
const { appId, signature, nonceStr, timestamp, clientid, agent_id } = query;
|
||||
|
||||
logger.info('WSS', `新连接: clientid=${clientid}`, { ip });
|
||||
|
||||
if (!clientid) {
|
||||
logger.warn('WSS', '拒绝连接: 缺少 clientid', { ip });
|
||||
ws.close(4001, 'missing clientid');
|
||||
return;
|
||||
}
|
||||
|
||||
const appSecret = getAppSecret(appId);
|
||||
if (!appSecret) {
|
||||
logger.warn('WSS', `拒绝连接: 未知 appId=${appId}`, { ip });
|
||||
ws.close(4002, 'unknown appId');
|
||||
return;
|
||||
}
|
||||
|
||||
const authResult = verifySignature(appId, signature, nonceStr, timestamp, appSecret);
|
||||
if (!authResult.valid) {
|
||||
logger.warn('WSS', `拒绝连接: 签名验证失败 - ${authResult.reason}`, { ip, appId });
|
||||
ws.close(4003, 'auth failed');
|
||||
return;
|
||||
}
|
||||
|
||||
// 解析 clientid
|
||||
const parsed = parseClientId(clientid);
|
||||
if (!parsed) {
|
||||
logger.warn('WSS', `拒绝连接: clientid 格式无效: ${clientid}`, { ip });
|
||||
ws.close(4004, 'invalid clientid');
|
||||
return;
|
||||
}
|
||||
|
||||
// 跨租户安全检查
|
||||
if (parsed.appId !== appId) {
|
||||
logger.warn('WSS', `拒绝连接: clientid 中的 appId(${parsed.appId}) 与认证 appId(${appId}) 不匹配`, { ip });
|
||||
ws.close(4005, 'clientid appId mismatch');
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取租户
|
||||
const tenant = tenantMgr.getTenantByAppId(appId);
|
||||
if (!tenant) {
|
||||
logger.warn('WSS', `拒绝连接: 商城不存在: ${appId}`, { ip });
|
||||
ws.close(4006, 'tenant not found');
|
||||
return;
|
||||
}
|
||||
|
||||
// 注册连接
|
||||
connMgr.register(clientid, ws, { tenantId: tenant.id, ip, connectTime: new Date(), parsed });
|
||||
|
||||
// 如果是坐席连接,更新坐席状态为 online
|
||||
if (parsed.role === 'employee') {
|
||||
agentStatusMgr.setStatus(tenant.id, parsed.agentId, 'online');
|
||||
}
|
||||
|
||||
// 发送初始消息 + 离线消息同步
|
||||
try {
|
||||
ws.send(JSON.stringify({
|
||||
type: 'init',
|
||||
data: 'connected',
|
||||
clientid,
|
||||
time: new Date().toISOString().replace('T', ' ').substring(0, 19),
|
||||
}));
|
||||
} catch (_) {}
|
||||
|
||||
// 如果是坐席连接,推送离线消息
|
||||
if (parsed.role === 'employee') {
|
||||
try {
|
||||
const lastActive = agentStatusMgr.getStatus(parsed.agentId);
|
||||
const afterTs = lastActive.last_active || 0;
|
||||
const offlineMsgs = msgMgr.getOfflineMessages(tenant.id, parsed.agentId, afterTs);
|
||||
if (offlineMsgs.length > 0) {
|
||||
ws.send(JSON.stringify({
|
||||
type: 'offline_messages',
|
||||
data: offlineMsgs,
|
||||
count: offlineMsgs.length,
|
||||
}));
|
||||
logger.info('WSS', `推送 ${offlineMsgs.length} 条离线消息给坐席 ${parsed.agentId}`);
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error('WSS', `离线消息同步失败: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
ws.on('message', (raw) => {
|
||||
let msg;
|
||||
try {
|
||||
msg = JSON.parse(raw.toString());
|
||||
} catch (e) {
|
||||
logger.warn('WSS', `消息解析失败: ${raw.toString().substring(0, 200)}`, { clientid });
|
||||
return;
|
||||
}
|
||||
|
||||
connMgr.updatePing(clientid);
|
||||
|
||||
// 如果是坐席消息,更新最后活跃时间
|
||||
if (parsed.role === 'employee') {
|
||||
agentStatusMgr.updateLastActive(parsed.agentId);
|
||||
}
|
||||
|
||||
switch (msg.type) {
|
||||
case 'ping':
|
||||
try { ws.send(JSON.stringify({ type: 'pong' })); } catch (_) {}
|
||||
break;
|
||||
|
||||
case 'msg_ack':
|
||||
logger.debug('WSS', `消息回执: msg_id=${msg.msg_id}`, { clientid });
|
||||
break;
|
||||
|
||||
case 'chat':
|
||||
// 聊天消息中继 + 持久化
|
||||
handleChatMessage(ws, msg, clientid, parsed, tenant);
|
||||
break;
|
||||
|
||||
case 'read':
|
||||
// 标记已读
|
||||
handleReadReceipt(msg, clientid, parsed, tenant);
|
||||
break;
|
||||
|
||||
case 'status':
|
||||
// 坐席状态变更
|
||||
if (parsed.role === 'employee' && msg.status) {
|
||||
agentStatusMgr.setStatus(tenant.id, parsed.agentId, msg.status);
|
||||
// 广播状态变更给该租户的所有客户
|
||||
broadcastAgentStatus(tenant.id, parsed.agentId, msg.status);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
logger.debug('WSS', `未知消息类型: ${msg.type}`, { clientid, msg });
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
ws.on('pong', () => connMgr.updatePing(clientid));
|
||||
|
||||
ws.on('close', (code, reason) => {
|
||||
logger.info('WSS', `连接关闭: code=${code}`, { clientid, reason: reason.toString() });
|
||||
connMgr.unregister(clientid);
|
||||
// 如果是坐席连接,更新状态为 offline
|
||||
if (parsed.role === 'employee') {
|
||||
agentStatusMgr.setStatus(tenant.id, parsed.agentId, 'offline');
|
||||
broadcastAgentStatus(tenant.id, parsed.agentId, 'offline');
|
||||
}
|
||||
});
|
||||
|
||||
ws.on('error', (err) => {
|
||||
logger.error('WSS', `连接错误`, { clientid, error: err.message });
|
||||
connMgr.unregister(clientid);
|
||||
});
|
||||
});
|
||||
|
||||
// 定期清理超时连接
|
||||
setInterval(() => connMgr.cleanupStale(60000), 30000);
|
||||
|
||||
// 定期自动离线超时坐席
|
||||
setInterval(() => agentStatusMgr.autoOffline(120), 30000);
|
||||
|
||||
return wss;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理聊天消息
|
||||
*/
|
||||
function handleChatMessage(ws, msg, senderClientId, parsed, tenant) {
|
||||
const targetClientId = msg.to;
|
||||
const content = msg.data || msg.content || '';
|
||||
const msgType = msg.msg_type || 'text';
|
||||
|
||||
if (!targetClientId || !content) {
|
||||
logger.warn('WSS', `聊天消息缺少必要字段`, { senderClientId, msg });
|
||||
return;
|
||||
}
|
||||
|
||||
// 解析目标
|
||||
const targetParsed = parseClientId(targetClientId);
|
||||
if (!targetParsed) {
|
||||
logger.warn('WSS', `目标 clientid 无效: ${targetClientId}`, { senderClientId });
|
||||
return;
|
||||
}
|
||||
|
||||
// 跨租户安全检查
|
||||
if (targetParsed.appId !== parsed.appId) {
|
||||
logger.warn('WSS', `跨租户消息拦截: ${senderClientId} -> ${targetClientId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const fromRole = parsed.role === 'employee' ? 'agent' : 'customer';
|
||||
const agentId = parsed.role === 'employee' ? parsed.agentId : (targetParsed.role === 'employee' ? targetParsed.agentId : null);
|
||||
const customerClientId = parsed.role === 'customer' ? senderClientId : targetClientId;
|
||||
|
||||
// 持久化消息
|
||||
const saved = msgMgr.saveMessage({
|
||||
tenant_id: tenant.id,
|
||||
clientid: customerClientId,
|
||||
agent_id: agentId,
|
||||
msg_type: msgType,
|
||||
content: content,
|
||||
from_role: fromRole,
|
||||
from_clientid: senderClientId,
|
||||
to_clientid: targetClientId,
|
||||
});
|
||||
|
||||
// 构建转发消息
|
||||
const forwardMsg = {
|
||||
type: 'chat',
|
||||
msg_id: saved.id,
|
||||
from: senderClientId,
|
||||
to: targetClientId,
|
||||
data: content,
|
||||
msg_type: msgType,
|
||||
time: new Date(saved.created_at * 1000).toISOString().replace('T', ' ').substring(0, 19),
|
||||
};
|
||||
|
||||
// 发送给目标
|
||||
const targetConn = connMgr.getByClientId(targetClientId);
|
||||
if (targetConn && targetConn.ws.readyState === 1) {
|
||||
try {
|
||||
targetConn.ws.send(JSON.stringify(forwardMsg));
|
||||
logger.info('WSS', `消息转发: ${senderClientId} -> ${targetClientId}`, { msgType, preview: content.substring(0, 50) });
|
||||
} catch (e) {
|
||||
logger.error('WSS', `消息转发失败: ${e.message}`);
|
||||
}
|
||||
} else {
|
||||
logger.info('WSS', `目标离线,消息仅持久化: ${targetClientId}`);
|
||||
}
|
||||
|
||||
// 发送回执给发送者
|
||||
try {
|
||||
ws.send(JSON.stringify({
|
||||
type: 'chat_ack',
|
||||
msg_id: saved.id,
|
||||
to: targetClientId,
|
||||
time: forwardMsg.time,
|
||||
}));
|
||||
} catch (_) {}
|
||||
|
||||
// 更新坐席消息计数
|
||||
if (fromRole === 'agent' && agentId) {
|
||||
agentStatusMgr.incrementMessages(agentId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理已读回执
|
||||
*/
|
||||
function handleReadReceipt(msg, senderClientId, parsed, tenant) {
|
||||
const targetClientId = msg.to || msg.clientid;
|
||||
if (!targetClientId) return;
|
||||
|
||||
const byRole = parsed.role === 'employee' ? 'agent' : 'customer';
|
||||
const customerClientId = parsed.role === 'customer' ? senderClientId : targetClientId;
|
||||
|
||||
msgMgr.markAsRead(tenant.id, customerClientId, byRole);
|
||||
|
||||
// 通知对方已读
|
||||
const targetConn = connMgr.getByClientId(targetClientId);
|
||||
if (targetConn && targetConn.ws.readyState === 1) {
|
||||
try {
|
||||
targetConn.ws.send(JSON.stringify({
|
||||
type: 'read_receipt',
|
||||
from: senderClientId,
|
||||
clientid: customerClientId,
|
||||
time: new Date().toISOString().replace('T', ' ').substring(0, 19),
|
||||
}));
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 广播坐席状态变更给租户下的所有客户
|
||||
*/
|
||||
function broadcastAgentStatus(tenantId, agentId, status) {
|
||||
const connections = connMgr.getConnectionsByTenant(tenantId);
|
||||
for (const rec of connections) {
|
||||
if (rec.parsed && rec.parsed.role === 'customer' && rec.ws.readyState === 1) {
|
||||
try {
|
||||
rec.ws.send(JSON.stringify({
|
||||
type: 'agent_status',
|
||||
agent_id: agentId,
|
||||
status: status,
|
||||
time: new Date().toISOString().replace('T', ' ').substring(0, 19),
|
||||
}));
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { startWssServer };
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* SaaS 认证中间件
|
||||
*
|
||||
* 从请求头提取 appId/signature/nonceStr/timestamp,
|
||||
* 用与云倩相同的签名算法验证,通过后查库确认租户存在且启用。
|
||||
*/
|
||||
|
||||
const { verifySignature } = require('../lib/crypto-utils');
|
||||
const tenantMgr = require('../lib/tenant-manager');
|
||||
const logger = require('../lib/logger');
|
||||
|
||||
function saasAuth(req, res, next) {
|
||||
const appId = req.headers.appid || req.query.appId;
|
||||
const signature = req.headers.signature || req.query.signature;
|
||||
const nonceStr = req.headers.noncestr || req.query.nonceStr;
|
||||
const timestamp = req.headers.timestamp || req.query.timestamp;
|
||||
|
||||
if (!appId || !signature) {
|
||||
return res.status(401).json({ result: 0, msg: '缺少认证参数' });
|
||||
}
|
||||
|
||||
// 查找租户
|
||||
const tenant = tenantMgr.getTenantByAppId(appId);
|
||||
if (!tenant) {
|
||||
// 尝试用默认管理员配置
|
||||
const config = require('../config');
|
||||
if (appId === config.auth.defaultAdminAppId && config.auth.defaultAdminAppSecret) {
|
||||
const result = verifySignature(appId, signature, nonceStr, timestamp, config.auth.defaultAdminAppSecret);
|
||||
if (!result.valid) {
|
||||
logger.warn('Auth', `管理员签名验证失败: ${result.reason}`);
|
||||
return res.status(401).json({ result: 0, msg: '签名验证失败: ' + result.reason });
|
||||
}
|
||||
req.tenant = { id: 0, app_id: appId, is_admin: 1, name: '超级管理员' };
|
||||
req.isAdmin = true;
|
||||
return next();
|
||||
}
|
||||
|
||||
logger.warn('Auth', `未知 appId: ${appId}`);
|
||||
return res.status(401).json({ result: 0, msg: '商城未注册或已禁用' });
|
||||
}
|
||||
|
||||
// 验证签名
|
||||
const result = verifySignature(appId, signature, nonceStr, timestamp, tenant.app_secret);
|
||||
if (!result.valid) {
|
||||
logger.warn('Auth', `签名验证失败: ${result.reason}`);
|
||||
return res.status(401).json({ result: 0, msg: '签名验证失败: ' + result.reason });
|
||||
}
|
||||
|
||||
// 通过认证
|
||||
req.tenant = tenant;
|
||||
req.isAdmin = !!tenant.is_admin;
|
||||
next();
|
||||
}
|
||||
|
||||
// 管理员权限检查
|
||||
function requireAdmin(req, res, next) {
|
||||
if (!req.session || !req.session.isAdmin) {
|
||||
return res.status(403).json({ result: 0, msg: '需要管理员权限' });
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
module.exports = { saasAuth, requireAdmin };
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>SaaS 客服服务器管理后台</title>
|
||||
<style>
|
||||
*{margin:0;padding:0;box-sizing:border-box}
|
||||
body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Microsoft YaHei",sans-serif;background:#f0f2f5;color:#333}
|
||||
.navbar{background:linear-gradient(135deg,#1a73e8 0%,#0d47a1 100%);color:#fff;padding:0 24px;height:56px;display:flex;align-items:center;justify-content:space-between;box-shadow:0 2px 8px rgba(0,0,0,0.15)}
|
||||
.navbar .title{font-size:18px;font-weight:600}.navbar .actions{display:flex;gap:12px;align-items:center;font-size:13px}
|
||||
.badge{background:rgba(255,255,255,0.2);padding:4px 12px;border-radius:12px;font-size:12px}
|
||||
.btn-logout{background:rgba(255,255,255,0.2);color:#fff;border:1px solid rgba(255,255,255,0.3);padding:6px 16px;border-radius:6px;cursor:pointer;font-size:13px}
|
||||
.container{max-width:1400px;margin:0 auto;padding:20px}
|
||||
.stats-grid{display:grid;grid-template-columns:repeat(5,1fr);gap:16px;margin-bottom:24px}
|
||||
.stat-card{background:#fff;border-radius:10px;padding:18px;box-shadow:0 2px 8px rgba(0,0,0,0.06)}
|
||||
.stat-card .stat-label{font-size:12px;color:#999;margin-bottom:6px}
|
||||
.stat-card .stat-value{font-size:28px;font-weight:700;color:#333}
|
||||
.stat-card.primary .stat-value{color:#1a73e8}.stat-card.success .stat-value{color:#52c41a}
|
||||
.stat-card.warning .stat-value{color:#faad14}.stat-card.info .stat-value{color:#13c2c2}
|
||||
.section{background:#fff;border-radius:10px;padding:20px;margin-bottom:24px;box-shadow:0 2px 8px rgba(0,0,0,0.06)}
|
||||
.section-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:16px}
|
||||
.section-header h3{font-size:15px;color:#555}
|
||||
.section-header .meta{font-size:12px;color:#999}
|
||||
.btn-primary{background:#1a73e8;color:#fff;border:none;padding:8px 16px;border-radius:6px;cursor:pointer;font-size:13px}
|
||||
.btn-primary:hover{opacity:.9}.btn-danger{background:#ff4d4f;color:#fff;border:none;padding:6px 12px;border-radius:4px;cursor:pointer;font-size:12px}
|
||||
.btn-sm{background:#f0f2f5;border:1px solid #ddd;padding:4px 10px;border-radius:4px;cursor:pointer;font-size:12px}
|
||||
table{width:100%;border-collapse:collapse;font-size:13px}
|
||||
th{text-align:left;padding:10px 12px;background:#fafafa;border-bottom:2px solid #f0f0f0;color:#666;font-weight:600;white-space:nowrap}
|
||||
td{padding:8px 12px;border-bottom:1px solid #f5f5f5;color:#333}
|
||||
tr:hover td{background:#fafafa}
|
||||
.tag{display:inline-block;padding:2px 8px;border-radius:4px;font-size:11px;font-weight:500}
|
||||
.tag-enabled{background:#f6ffed;color:#52c41a}.tag-disabled{background:#fff0f0;color:#ff4d4f}
|
||||
.tag-free{background:#fffbe6;color:#faad14}.tag-paid{background:#f0f5ff;color:#2f54eb}
|
||||
.tag-online{background:#f6ffed;color:#52c41a}.tag-offline{background:#fff0f0;color:#ff4d4f}
|
||||
.tag-sent{background:#f6ffed;color:#52c41a}.tag-error{background:#fff0f0;color:#ff4d4f}
|
||||
.mono{font-family:"Fira Code","Consolas",monospace;font-size:12px}
|
||||
.truncate{max-width:300px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.empty-state{text-align:center;padding:40px;color:#999;font-size:14px}
|
||||
.modal{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);align-items:center;justify-content:center;z-index:1000}
|
||||
.modal.show{display:flex}
|
||||
.modal-content{background:#fff;border-radius:12px;padding:28px;width:500px;max-width:90vw;max-height:80vh;overflow:auto}
|
||||
.modal-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px}
|
||||
.modal-header h3{font-size:16px;color:#333}
|
||||
.modal-close{background:none;border:none;font-size:20px;cursor:pointer;color:#999}
|
||||
.form-group{margin-bottom:14px}.form-group label{display:block;font-size:13px;color:#555;margin-bottom:6px;font-weight:500}
|
||||
.form-group input,.form-group select{width:100%;padding:10px 14px;border:1px solid #ddd;border-radius:8px;font-size:14px;outline:none}
|
||||
.form-group input:focus,.form-group select:focus{border-color:#1a73e8;box-shadow:0 0 0 3px rgba(26,115,232,0.15)}
|
||||
.modal-footer{display:flex;justify-content:flex-end;gap:10px;margin-top:20px}
|
||||
.tabs{display:flex;gap:4px;margin-bottom:16px;border-bottom:2px solid #f0f0f0}
|
||||
.tab{padding:10px 20px;cursor:pointer;font-size:13px;color:#666;border-bottom:2px solid transparent}
|
||||
.tab.active{color:#1a73e8;border-bottom-color:#1a73e8;font-weight:600}
|
||||
.tab-content{display:none}.tab-content.active{display:block}
|
||||
.toast{position:fixed;top:20px;right:20px;padding:12px 20px;border-radius:8px;color:#fff;font-size:13px;z-index:2000;animation:slideIn .3s ease}
|
||||
.toast.success{background:#52c41a}.toast.error{background:#ff4d4f}
|
||||
@keyframes slideIn{from{transform:translateX(100px);opacity:0}to{transform:translateX(0);opacity:1}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="navbar">
|
||||
<div class="title">SaaS 客服服务器管理后台</div>
|
||||
<div class="actions">
|
||||
<span class="badge">HTTP:<%=serverConfig.port%></span>
|
||||
<span class="badge">WSS:<%=serverConfig.wssPort%></span>
|
||||
<span class="badge">租户:<%=tenants.length%></span>
|
||||
<button class="btn-logout" onclick="logout()">退出</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
<!-- 统计卡片 -->
|
||||
<div class="stats-grid">
|
||||
<div class="stat-card primary"><div class="stat-label">商城数量</div><div class="stat-value"><%=tenants.length%></div></div>
|
||||
<div class="stat-card info"><div class="stat-label">总连接数</div><div class="stat-value"><%=summary.totalConnections%></div></div>
|
||||
<div class="stat-card success"><div class="stat-label">在线客户</div><div class="stat-value"><%=summary.onlineCustomers%></div></div>
|
||||
<div class="stat-card warning"><div class="stat-label">在线客服</div><div class="stat-value"><%=summary.onlineEmployees%></div></div>
|
||||
<div class="stat-card"><div class="stat-label">日志</div><div class="stat-value"><%=pushLogs.length%></div></div>
|
||||
</div>
|
||||
|
||||
<!-- 标签页 -->
|
||||
<div class="tabs">
|
||||
<div class="tab active" onclick="switchTab('tenants')">商城管理</div>
|
||||
<div class="tab" onclick="switchTab('connections')">在线连接</div>
|
||||
<div class="tab" onclick="switchTab('logs')">推送日志</div>
|
||||
</div>
|
||||
|
||||
<!-- 商城管理 -->
|
||||
<div id="tab-tenants" class="tab-content active">
|
||||
<div class="section">
|
||||
<div class="section-header"><h3>商城列表</h3><button class="btn-primary" onclick="openModal()">+ 添加商城</button></div>
|
||||
<table>
|
||||
<thead><tr><th>ID</th><th>名称</th><th>AppID</th><th>坐席上限</th><th>已用</th><th>到期时间</th><th>状态</th><th>操作</th></tr></thead>
|
||||
<tbody id="tenantTable">
|
||||
<% tenants.forEach(function(t){ %>
|
||||
<tr data-id="<%=t.id%>">
|
||||
<td><%=t.id%></td>
|
||||
<td><%=t.name||'-'%></td>
|
||||
<td class="mono"><%=t.app_id%></td>
|
||||
<td><%=t.agent_limit==-1?'无限':t.agent_limit%></td>
|
||||
<td><%=t.agent_used%>/<%=t.agent_limit==-1?'∞':t.agent_limit%></td>
|
||||
<td><%=t.agent_end_time?new Date(t.agent_end_time*1000).toLocaleDateString():'永久'%></td>
|
||||
<td><span class="tag <%=t.status==1?'tag-enabled':'tag-disabled'%>"><%=t.status==1?'启用':'禁用'%></span></td>
|
||||
<td><button class="btn-sm" onclick="editTenant(<%=t.id%>)">编辑</button> <button class="btn-danger" onclick="deleteTenant(<%=t.id%>)">删除</button></td>
|
||||
</tr>
|
||||
<% }) %>
|
||||
<% if(tenants.length===0){ %><tr><td colspan="8" class="empty-state">暂无商城,点击上方按钮添加</td></tr><% } %>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 在线连接 -->
|
||||
<div id="tab-connections" class="tab-content">
|
||||
<div class="section">
|
||||
<div class="section-header"><h3>在线连接</h3><button class="btn-sm" onclick="loadConnections()">刷新</button></div>
|
||||
<table><thead><tr><th>ClientID</th><th>角色</th><th>AppID</th><th>渠道</th><th>IP</th><th>连接时间</th><th>最后心跳</th></tr></thead>
|
||||
<tbody id="connTable"><tr><td colspan="7" class="empty-state">加载中...</td></tr></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 推送日志 -->
|
||||
<div id="tab-logs" class="tab-content">
|
||||
<div class="section">
|
||||
<div class="section-header"><h3>推送日志</h3></div>
|
||||
<table><thead><tr><th>时间</th><th>ClientID</th><th>状态</th><th>消息预览</th></tr></thead>
|
||||
<tbody>
|
||||
<% pushLogs.forEach(function(l){ %>
|
||||
<tr><td class="mono"><%=l.time.replace('T',' ').substring(0,19)%></td>
|
||||
<td class="mono truncate" title="<%=l.clientid%>"><%=l.clientid%></td>
|
||||
<td><span class="tag tag-<%=l.status%>"><%=l.status%></span></td>
|
||||
<td class="mono truncate" title="<%=l.message%>"><%=l.message%></td></tr>
|
||||
<% }) %>
|
||||
<% if(pushLogs.length===0){ %><tr><td colspan="4" class="empty-state">暂无推送日志</td></tr><% } %>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 添加商城模态框 -->
|
||||
<div class="modal" id="modal">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header"><h3 id="modalTitle">添加商城</h3><button class="modal-close" onclick="closeModal()">×</button></div>
|
||||
<div class="form-group"><label>商城名称</label><input type="text" id="t_name" placeholder="商城名称"></div>
|
||||
<div class="form-group"><label>域名</label><input type="text" id="t_domain" placeholder="如 mall.example.com"></div>
|
||||
<div class="form-group"><label>AppID</label><input type="text" id="t_app_id" placeholder="留空则自动生成"></div>
|
||||
<div class="form-group"><label>AppSecret</label><input type="text" id="t_app_secret" placeholder="留空则自动生成"></div>
|
||||
<div class="form-group"><label>坐席上限</label><input type="number" id="t_agent_limit" value="-1" placeholder="-1=无限"></div>
|
||||
<div class="form-group"><label>到期时间</label><input type="datetime-local" id="t_end_time"></div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn-sm" onclick="closeModal()">取消</button>
|
||||
<button class="btn-primary" onclick="saveTenant()">保存</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function switchTab(name){
|
||||
document.querySelectorAll('.tab').forEach(t=>t.classList.remove('active'));
|
||||
document.querySelectorAll('.tab-content').forEach(t=>t.classList.remove('active'));
|
||||
document.querySelector(`.tab[onclick="switchTab('${name}')"]`).classList.add('active');
|
||||
document.getElementById('tab-'+name).classList.add('active');
|
||||
if(name==='connections')loadConnections();
|
||||
}
|
||||
|
||||
function logout(){
|
||||
fetch('/admin/logout').then(()=>location.href='/admin/login');
|
||||
}
|
||||
|
||||
function openModal(){document.getElementById('modal').classList.add('show');document.getElementById('modalTitle').textContent='添加商城';}
|
||||
function closeModal(){document.getElementById('modal').classList.remove('show');}
|
||||
|
||||
function showToast(msg,type){const d=document.createElement('div');d.className='toast '+type;d.textContent=msg;document.body.appendChild(d);setTimeout(()=>d.remove(),3000);}
|
||||
|
||||
async function saveTenant(){
|
||||
const data={
|
||||
name:document.getElementById('t_name').value,
|
||||
domain:document.getElementById('t_domain').value,
|
||||
app_id:document.getElementById('t_app_id').value,
|
||||
app_secret:document.getElementById('t_app_secret').value,
|
||||
agent_limit:parseInt(document.getElementById('t_agent_limit').value),
|
||||
agent_end_time:document.getElementById('t_end_time').value?Math.floor(new Date(document.getElementById('t_end_time').value).getTime()/1000):0,
|
||||
};
|
||||
const res=await fetch('/admin/tenants',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)});
|
||||
const json=await res.json();
|
||||
if(json.success){showToast('添加成功','success');closeModal();setTimeout(()=>location.reload(),500);}
|
||||
else{showToast(json.message||'添加失败','error');}
|
||||
}
|
||||
|
||||
async function deleteTenant(id){
|
||||
if(!confirm('确认删除商城 '+id+'?此操作不可逆!'))return;
|
||||
const res=await fetch('/admin/tenants/'+id,{method:'DELETE'});
|
||||
const json=await res.json();
|
||||
if(json.success){showToast('删除成功','success');setTimeout(()=>location.reload(),500);}
|
||||
else{showToast(json.message||'删除失败','error');}
|
||||
}
|
||||
|
||||
async function editTenant(id){
|
||||
const tr=document.querySelector(`tr[data-id="${id}"]`);
|
||||
if(!tr){showToast('找不到商城数据','error');return;}
|
||||
|
||||
const tds=tr.querySelectorAll('td');
|
||||
document.getElementById('t_name').value=tds[1].textContent.trim();
|
||||
|
||||
// 从已有租户数据中回填(通过data属性或直接从表格提取)
|
||||
// 由于EJS渲染时数据在服务器端,前端只有表格文本
|
||||
// 简化为:打开模态框,预填充名称,其他字段需要用户手动输入或从API获取
|
||||
|
||||
document.getElementById('modal').classList.add('show');
|
||||
document.getElementById('modalTitle').textContent='编辑商城 '+id;
|
||||
|
||||
// 尝试从API获取完整数据
|
||||
try{
|
||||
const res=await fetch('/admin/tenants');
|
||||
const json=await res.json();
|
||||
if(json.success){
|
||||
const tenant=json.data.find(t=>t.id===id);
|
||||
if(tenant){
|
||||
document.getElementById('t_name').value=tenant.name||'';
|
||||
document.getElementById('t_domain').value=tenant.domain||'';
|
||||
document.getElementById('t_app_id').value=tenant.app_id||'';
|
||||
document.getElementById('t_app_secret').value=tenant.app_secret||'';
|
||||
document.getElementById('t_agent_limit').value=tenant.agent_limit||-1;
|
||||
if(tenant.agent_end_time){
|
||||
const d=new Date(tenant.agent_end_time*1000);
|
||||
document.getElementById('t_end_time').value=d.toISOString().slice(0,16);
|
||||
}else{
|
||||
document.getElementById('t_end_time').value='';
|
||||
}
|
||||
}
|
||||
}
|
||||
}catch(e){console.error('加载租户数据失败',e);}
|
||||
|
||||
// 修改保存按钮行为为更新模式
|
||||
const saveBtn=document.querySelector('.modal-footer .btn-primary');
|
||||
saveBtn.onclick=function(){updateTenant(id);};
|
||||
}
|
||||
|
||||
async function updateTenant(id){
|
||||
const data={
|
||||
name:document.getElementById('t_name').value,
|
||||
domain:document.getElementById('t_domain').value,
|
||||
app_id:document.getElementById('t_app_id').value,
|
||||
app_secret:document.getElementById('t_app_secret').value,
|
||||
agent_limit:parseInt(document.getElementById('t_agent_limit').value),
|
||||
agent_end_time:document.getElementById('t_end_time').value?Math.floor(new Date(document.getElementById('t_end_time').value).getTime()/1000):0,
|
||||
};
|
||||
const res=await fetch('/admin/tenants/'+id,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)});
|
||||
const json=await res.json();
|
||||
if(json.success){showToast('更新成功','success');closeModal();setTimeout(()=>location.reload(),500);}
|
||||
else{showToast(json.message||'更新失败','error');}
|
||||
}
|
||||
|
||||
async function loadConnections(){
|
||||
const tbody=document.getElementById('connTable');
|
||||
tbody.innerHTML='<tr><td colspan="7" class="empty-state">加载中...</td></tr>';
|
||||
try{
|
||||
const res=await fetch('/admin/api/connections');
|
||||
const json=await res.json();
|
||||
if(!json.success||!json.data.length){tbody.innerHTML='<tr><td colspan="7" class="empty-state">暂无在线连接</td></tr>';return;}
|
||||
tbody.innerHTML=json.data.map(c=>`<tr>
|
||||
<td class="mono truncate" title="${c.clientid}">${c.clientid}</td>
|
||||
<td><span class="tag tag-${c.role==='customer'?'free':'paid'}">${c.role==='customer'?'客户':'客服'}</span></td>
|
||||
<td class="mono">${c.agentId||'-'}</td>
|
||||
<td>${c.channel||'-'}</td>
|
||||
<td class="mono">${c.ip}</td>
|
||||
<td class="mono">${c.connectTime.replace('T',' ').substring(0,19)}</td>
|
||||
<td class="mono">${c.lastPing.replace('T',' ').substring(0,19)}</td>
|
||||
</tr>`).join('');
|
||||
}catch(e){tbody.innerHTML='<tr><td colspan="7" class="empty-state">加载失败</td></tr>';}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,83 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>客服登录 - 坐席工作台</title>
|
||||
<style>
|
||||
*{margin:0;padding:0;box-sizing:border-box}
|
||||
body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Microsoft YaHei",sans-serif;background:linear-gradient(135deg,#1a73e8 0%,#0d47a1 100%);min-height:100vh;display:flex;align-items:center;justify-content:center}
|
||||
.login-card{background:#fff;border-radius:16px;box-shadow:0 20px 60px rgba(0,0,0,0.3);padding:40px;width:480px;max-width:90vw}
|
||||
.login-card h1{text-align:center;color:#333;font-size:20px;margin-bottom:6px}
|
||||
.login-card .subtitle{text-align:center;color:#999;font-size:13px;margin-bottom:30px}
|
||||
.form-group{margin-bottom:16px}
|
||||
.form-group label{display:block;font-size:13px;color:#555;margin-bottom:6px;font-weight:500}
|
||||
.form-group input,.form-group select{width:100%;padding:10px 14px;border:1px solid #ddd;border-radius:8px;font-size:14px;outline:none}
|
||||
.form-group input:focus,.form-group select:focus{border-color:#1a73e8;box-shadow:0 0 0 3px rgba(26,115,232,0.15)}
|
||||
.btn-login{width:100%;padding:12px;background:linear-gradient(135deg,#1a73e8 0%,#0d47a1 100%);color:#fff;border:none;border-radius:8px;font-size:16px;font-weight:600;cursor:pointer;margin-top:10px}
|
||||
.btn-login:hover{opacity:.9}
|
||||
.error-msg{background:#fff0f0;border:1px solid #ffcccc;color:#cc3333;padding:10px 14px;border-radius:8px;font-size:13px;margin-bottom:16px;display:none}
|
||||
.error-msg.show{display:block}
|
||||
.hint{color:#999;font-size:12px;margin-top:16px;text-align:center}
|
||||
.hint a{color:#1a73e8;text-decoration:none}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="login-card">
|
||||
<h1>客服坐席登录</h1>
|
||||
<div class="subtitle">连接到客服服务器工作台</div>
|
||||
<div class="error-msg" id="errorMsg"></div>
|
||||
<div class="form-group">
|
||||
<label>AppID(商城标识)</label>
|
||||
<input type="text" id="appId" placeholder="如: abc12345" value="<%= tenants.length > 0 ? tenants[0].app_id : '' %>">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>AppSecret(密钥)</label>
|
||||
<input type="password" id="appSecret" placeholder="商城密钥">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>坐席ID(可选)</label>
|
||||
<input type="text" id="agentId" placeholder="如不填写则自动分配">
|
||||
</div>
|
||||
<button class="btn-login" id="btnLogin">登录工作台</button>
|
||||
<div class="hint">已有商城?<a href="/admin">去管理后台</a></div>
|
||||
</div>
|
||||
<script>
|
||||
document.getElementById('btnLogin').addEventListener('click', async () => {
|
||||
const app_id = document.getElementById('appId').value.trim();
|
||||
const app_secret = document.getElementById('appSecret').value.trim();
|
||||
const agent_id = document.getElementById('agentId').value.trim();
|
||||
|
||||
if (!app_id || !app_secret) {
|
||||
showError('请输入 AppID 和 AppSecret');
|
||||
return;
|
||||
}
|
||||
|
||||
const res = await fetch('/agent/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ app_id, app_secret, agent_id })
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (data.success) {
|
||||
location.href = '/agent/dashboard';
|
||||
} else {
|
||||
showError(data.message || '登录失败');
|
||||
}
|
||||
});
|
||||
|
||||
function showError(msg) {
|
||||
const el = document.getElementById('errorMsg');
|
||||
el.textContent = msg;
|
||||
el.classList.add('show');
|
||||
}
|
||||
|
||||
document.querySelectorAll('input').forEach(input => {
|
||||
input.addEventListener('keypress', (e) => {
|
||||
if (e.key === 'Enter') document.getElementById('btnLogin').click();
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,67 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>登录 - SaaS 客服服务器</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Microsoft YaHei", sans-serif;
|
||||
background: linear-gradient(135deg, #1a73e8 0%, #0d47a1 100%);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.login-card {
|
||||
background: #fff;
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
|
||||
padding: 40px;
|
||||
width: 400px;
|
||||
max-width: 90vw;
|
||||
}
|
||||
.login-card h1 { text-align: center; color: #333; font-size: 22px; margin-bottom: 30px; }
|
||||
.form-group { margin-bottom: 18px; }
|
||||
.form-group label { display: block; font-size: 13px; color: #555; margin-bottom: 6px; font-weight: 500; }
|
||||
.form-group input { width: 100%; padding: 10px 14px; border: 1px solid #ddd; border-radius: 8px; font-size: 14px; outline: none; }
|
||||
.form-group input:focus { border-color: #1a73e8; box-shadow: 0 0 0 3px rgba(26,115,232,0.15); }
|
||||
.btn-login {
|
||||
width: 100%; padding: 12px; background: linear-gradient(135deg, #1a73e8 0%, #0d47a1 100%);
|
||||
color: #fff; border: none; border-radius: 8px; font-size: 16px; font-weight: 600;
|
||||
cursor: pointer; margin-top: 10px;
|
||||
}
|
||||
.btn-login:hover { opacity: 0.9; }
|
||||
.error-msg { background: #fff0f0; border: 1px solid #ffcccc; color: #cc3333;
|
||||
padding: 10px 14px; border-radius: 8px; font-size: 13px; margin-bottom: 18px; display: none; }
|
||||
.error-msg.show { display: block; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="login-card">
|
||||
<h1>SaaS 客服服务器</h1>
|
||||
<div class="error-msg" id="errorMsg"></div>
|
||||
<div class="form-group">
|
||||
<label>管理密码</label>
|
||||
<input type="password" id="password" placeholder="请输入管理密码">
|
||||
</div>
|
||||
<button class="btn-login" id="btnLogin">登录</button>
|
||||
</div>
|
||||
<script>
|
||||
document.getElementById('btnLogin').addEventListener('click', async () => {
|
||||
const password = document.getElementById('password').value;
|
||||
const res = await fetch('/admin/login', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password })
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.success) { location.href = '/admin'; }
|
||||
else { document.getElementById('errorMsg').textContent = data.message; document.getElementById('errorMsg').classList.add('show'); }
|
||||
});
|
||||
document.getElementById('password').addEventListener('keypress', (e) => {
|
||||
if (e.key === 'Enter') document.getElementById('btnLogin').click();
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user