更新
This commit is contained in:
1 parent
01f9f2c514
commit
dc23ea53ed
25 files changed
+3116
-176
No files matched your search
@@ -11,6 +11,7 @@ const careGuidesRouter = require('./routes/careGuides');
|
||||
const exportRouter = require('./routes/export');
|
||||
const customMetricsRouter = require('./routes/customMetrics');
|
||||
const familiesRouter = require('./routes/families');
|
||||
const memosRouter = require('./routes/memos');
|
||||
const { router: sseRouter } = require('./routes/sse');
|
||||
|
||||
const app = express();
|
||||
@@ -31,6 +32,7 @@ app.use('/api/summary', summaryRouter);
|
||||
app.use('/api/care-guides', careGuidesRouter);
|
||||
app.use('/api/export', exportRouter);
|
||||
app.use('/api/custom-metrics', customMetricsRouter);
|
||||
app.use('/api/memos', memosRouter);
|
||||
app.use('/api/events', sseRouter);
|
||||
|
||||
// Fallback to index.html for SPA
|
||||
@@ -41,6 +43,22 @@ app.use((req, res, next) => {
|
||||
next();
|
||||
});
|
||||
|
||||
// 全局 API 错误处理中间件
|
||||
app.use((err, req, res, next) => {
|
||||
console.error(`[API Error] ${req.method} ${req.url}:`, err);
|
||||
if (!res.headersSent) {
|
||||
res.status(500).json({ success: false, error: err.message || 'Internal Server Error' });
|
||||
}
|
||||
});
|
||||
|
||||
process.on('uncaughtException', (err) => {
|
||||
console.error('[Process Uncaught Exception]:', err);
|
||||
});
|
||||
process.on('unhandledRejection', (reason) => {
|
||||
console.error('[Process Unhandled Rejection]:', reason);
|
||||
});
|
||||
|
||||
|
||||
async function start() {
|
||||
try {
|
||||
await initDatabase();
|
||||
|
||||
@@ -9,11 +9,79 @@ const pool = mysql.createPool({
|
||||
database: process.env.DB_NAME || 'yyyy',
|
||||
waitForConnections: true,
|
||||
connectionLimit: 10,
|
||||
maxIdle: 2,
|
||||
idleTimeout: 30000,
|
||||
enableKeepAlive: true,
|
||||
keepAliveInitialDelay: 5000,
|
||||
queueLimit: 0,
|
||||
connectTimeout: 10000,
|
||||
dateStrings: true
|
||||
});
|
||||
|
||||
// 监听底层连接错误,防止空闲断开的 Socket 触发未捕获异常
|
||||
if (pool.pool) {
|
||||
pool.pool.on('connection', (connection) => {
|
||||
connection.on('error', (err) => {
|
||||
if (err.code === 'PROTOCOL_CONNECTION_LOST' || err.code === 'ECONNRESET') {
|
||||
console.warn('[DB] Stale connection dropped by remote server, pool will reconnect.');
|
||||
} else {
|
||||
console.error('[DB] Connection error:', err.message);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 封装带自动重试的 query 与 execute,抵御云端 MySQL/NAT 偶发断连
|
||||
const originalQuery = pool.query.bind(pool);
|
||||
const originalExecute = pool.execute.bind(pool);
|
||||
|
||||
async function executeWithRetry(fn, args, maxRetries = 3) {
|
||||
let attempt = 0;
|
||||
while (true) {
|
||||
try {
|
||||
return await fn(...args);
|
||||
} catch (err) {
|
||||
attempt++;
|
||||
const isConnectionLost = err && (
|
||||
err.code === 'PROTOCOL_CONNECTION_LOST' ||
|
||||
err.code === 'ECONNRESET' ||
|
||||
err.code === 'ETIMEDOUT' ||
|
||||
err.code === 'EPIPE' ||
|
||||
err.code === 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR' ||
|
||||
err.fatal
|
||||
);
|
||||
if (isConnectionLost && attempt <= maxRetries) {
|
||||
console.warn(`[DB] MySQL connection lost (${err.code || err.message}). Auto-retrying attempt ${attempt}/${maxRetries}...`);
|
||||
await new Promise(res => setTimeout(res, 250 * attempt));
|
||||
continue;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pool.query = function(...args) {
|
||||
return executeWithRetry(originalQuery, args);
|
||||
};
|
||||
|
||||
pool.execute = function(...args) {
|
||||
return executeWithRetry(originalExecute, args);
|
||||
};
|
||||
|
||||
// 心跳探针:每 25 秒自动执行一次 SELECT 1,防止云端防火墙丢弃空闲长连接
|
||||
const heartbeatTimer = setInterval(async () => {
|
||||
try {
|
||||
await pool.query('SELECT 1');
|
||||
} catch (err) {
|
||||
console.warn('[DB] Heartbeat ping error:', err.message);
|
||||
}
|
||||
}, 25000);
|
||||
|
||||
if (heartbeatTimer.unref) {
|
||||
heartbeatTimer.unref();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 数据库初始化
|
||||
*
|
||||
@@ -135,6 +203,33 @@ async function initDatabase() {
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='看护人用户表(预留)';
|
||||
`);
|
||||
|
||||
// 7. 家庭日常备忘待办清单表 (family_memo - 家庭看护团队协同清单)
|
||||
await conn.query(`
|
||||
CREATE TABLE IF NOT EXISTS \`family_memo\` (
|
||||
\`id\` BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '自增主键',
|
||||
\`memo_id\` VARCHAR(64) NOT NULL UNIQUE COMMENT '备忘唯一业务ID',
|
||||
\`family_id\` VARCHAR(64) NOT NULL DEFAULT 'family-001' COMMENT '所属家庭ID',
|
||||
\`content\` VARCHAR(255) NOT NULL COMMENT '待办备忘内容',
|
||||
\`due_period\` VARCHAR(30) DEFAULT 'today' COMMENT '推荐时段',
|
||||
\`is_completed\` TINYINT(1) DEFAULT 0 COMMENT '是否已完成',
|
||||
\`completed_at\` DATETIME NULL COMMENT '完成时刻',
|
||||
\`created_by\` VARCHAR(50) DEFAULT '宝妈' COMMENT '创建人称谓',
|
||||
\`created_at\` DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
\`updated_at\` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
INDEX \`idx_memo_family\` (\`family_id\`, \`is_completed\`),
|
||||
INDEX \`idx_memo_created\` (\`created_at\`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='家庭日常备忘待办清单表';
|
||||
`);
|
||||
|
||||
// 增量字段安全检测 (preferences & default_config)
|
||||
try {
|
||||
await conn.query("ALTER TABLE `family_member` ADD COLUMN `preferences` JSON NULL COMMENT '角色专属行为偏好'");
|
||||
} catch (e) {}
|
||||
|
||||
try {
|
||||
await conn.query("ALTER TABLE `baby_profile` ADD COLUMN `default_config` JSON NULL COMMENT '宝宝默认行为配置'");
|
||||
} catch (e) {}
|
||||
|
||||
// 预置默认家庭 (如果无家庭)
|
||||
const [existingFamilies] = await conn.query('SELECT COUNT(*) as count FROM `family`');
|
||||
if (existingFamilies[0].count === 0) {
|
||||
|
||||
+30
-6
@@ -71,18 +71,27 @@ router.post('/', async (req, res) => {
|
||||
// PUT /api/babies/:babyId - Update baby profile
|
||||
router.put('/:babyId', async (req, res) => {
|
||||
const { babyId } = req.params;
|
||||
const { name, gender, birthDate, themeColor } = req.body;
|
||||
const { name, gender, birthDate, themeColor, defaultConfig } = req.body;
|
||||
if (!name || !birthDate) {
|
||||
return res.status(400).json({ success: false, error: '姓名与出生日期必填' });
|
||||
}
|
||||
const color = themeColor || '#3B82F6';
|
||||
|
||||
try {
|
||||
await pool.query(`
|
||||
UPDATE \`baby_profile\`
|
||||
SET \`name\` = ?, \`gender\` = ?, \`birth_date\` = ?, \`theme_color\` = ?
|
||||
WHERE \`baby_id\` = ?
|
||||
`, [name, gender || 'boy', birthDate, color, babyId]);
|
||||
const configJson = defaultConfig ? (typeof defaultConfig === 'string' ? defaultConfig : JSON.stringify(defaultConfig)) : null;
|
||||
if (configJson !== null) {
|
||||
await pool.query(`
|
||||
UPDATE \`baby_profile\`
|
||||
SET \`name\` = ?, \`gender\` = ?, \`birth_date\` = ?, \`theme_color\` = ?, \`default_config\` = ?
|
||||
WHERE \`baby_id\` = ?
|
||||
`, [name, gender || 'boy', birthDate, color, configJson, babyId]);
|
||||
} else {
|
||||
await pool.query(`
|
||||
UPDATE \`baby_profile\`
|
||||
SET \`name\` = ?, \`gender\` = ?, \`birth_date\` = ?, \`theme_color\` = ?
|
||||
WHERE \`baby_id\` = ?
|
||||
`, [name, gender || 'boy', birthDate, color, babyId]);
|
||||
}
|
||||
|
||||
const [updated] = await pool.query('SELECT * FROM `baby_profile` WHERE `baby_id` = ?', [babyId]);
|
||||
res.json({ success: true, data: updated[0] });
|
||||
@@ -92,6 +101,21 @@ router.put('/:babyId', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// PUT /api/babies/:babyId/defaults - Update default config for baby
|
||||
router.put('/:babyId/defaults', async (req, res) => {
|
||||
const { babyId } = req.params;
|
||||
const { defaultConfig } = req.body;
|
||||
try {
|
||||
const configJson = typeof defaultConfig === 'string' ? defaultConfig : JSON.stringify(defaultConfig || {});
|
||||
await pool.query('UPDATE `baby_profile` SET `default_config` = ? WHERE `baby_id` = ?', [configJson, babyId]);
|
||||
const [updated] = await pool.query('SELECT * FROM `baby_profile` WHERE `baby_id` = ?', [babyId]);
|
||||
res.json({ success: true, message: '宝宝默认行为配置已更新', data: updated[0] });
|
||||
} catch (err) {
|
||||
console.error('Error updating baby defaults:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/babies/:babyId/default - Set as default baby
|
||||
router.post('/:babyId/default', async (req, res) => {
|
||||
const { babyId } = req.params;
|
||||
|
||||
@@ -36,7 +36,7 @@ router.get('/', async (req, res) => {
|
||||
|
||||
// 批量查询家庭成员
|
||||
const [members] = await pool.query(
|
||||
`SELECT id, family_id, role_name, is_owner, joined_at
|
||||
`SELECT id, family_id, role_name, is_owner, preferences, joined_at
|
||||
FROM \`family_member\`
|
||||
WHERE family_id IN (${placeholders})
|
||||
ORDER BY is_owner DESC, id ASC`,
|
||||
@@ -190,7 +190,7 @@ router.get('/:familyId/members', async (req, res) => {
|
||||
try {
|
||||
const { familyId } = req.params;
|
||||
const [members] = await pool.query(
|
||||
'SELECT id, family_id, role_name, is_owner, joined_at FROM `family_member` WHERE family_id = ? ORDER BY is_owner DESC, id ASC',
|
||||
'SELECT id, family_id, role_name, is_owner, preferences, joined_at FROM `family_member` WHERE family_id = ? ORDER BY is_owner DESC, id ASC',
|
||||
[familyId]
|
||||
);
|
||||
res.json({ success: true, data: members });
|
||||
@@ -240,4 +240,40 @@ router.post('/:familyId/members', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// 7. 更新指定看护人专属行为记忆偏好
|
||||
router.put('/:familyId/members/:roleName/preferences', async (req, res) => {
|
||||
try {
|
||||
const { familyId, roleName } = req.params;
|
||||
const { preferences } = req.body;
|
||||
|
||||
const [member] = await pool.query(
|
||||
'SELECT id, preferences FROM `family_member` WHERE family_id = ? AND role_name = ?',
|
||||
[familyId, roleName]
|
||||
);
|
||||
|
||||
if (member.length === 0) {
|
||||
return res.status(404).json({ success: false, message: '该看护人成员不存在' });
|
||||
}
|
||||
|
||||
const prefJson = typeof preferences === 'string' ? preferences : JSON.stringify(preferences || {});
|
||||
await pool.query(
|
||||
'UPDATE `family_member` SET `preferences` = ? WHERE family_id = ? AND role_name = ?',
|
||||
[prefJson, familyId, roleName]
|
||||
);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: '角色偏好已保存',
|
||||
data: {
|
||||
familyId,
|
||||
roleName,
|
||||
preferences: typeof preferences === 'string' ? JSON.parse(preferences) : preferences
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Failed to update member preferences:', err);
|
||||
res.status(500).json({ success: false, message: '更新角色偏好失败', error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,206 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { pool } = require('../db');
|
||||
const { broadcastEvent } = require('./sse');
|
||||
|
||||
/**
|
||||
* GET /api/memos
|
||||
* 获取指定家庭的备忘待办清单
|
||||
*/
|
||||
router.get('/', async (req, res) => {
|
||||
try {
|
||||
const familyId = req.query.familyId || 'family-001';
|
||||
const { status, search, period } = req.query;
|
||||
|
||||
let query = 'SELECT * FROM family_memo WHERE family_id = ?';
|
||||
const params = [familyId];
|
||||
|
||||
if (status === 'pending') {
|
||||
query += ' AND is_completed = 0';
|
||||
} else if (status === 'completed') {
|
||||
query += ' AND is_completed = 1';
|
||||
}
|
||||
|
||||
if (period && period !== 'all') {
|
||||
query += ' AND due_period = ?';
|
||||
params.push(period);
|
||||
}
|
||||
|
||||
if (search && search.trim()) {
|
||||
query += ' AND (content LIKE ? OR created_by LIKE ?)';
|
||||
params.push(`%${search.trim()}%`, `%${search.trim()}%`);
|
||||
}
|
||||
|
||||
query += ' ORDER BY is_completed ASC, created_at DESC';
|
||||
|
||||
const [rows] = await pool.query(query, params);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: rows
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Failed to get memos:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/memos/clear-completed
|
||||
* 清理指定家庭已完成的历史备忘
|
||||
*/
|
||||
router.post('/clear-completed', async (req, res) => {
|
||||
try {
|
||||
const { familyId = 'family-001' } = req.body;
|
||||
const [result] = await pool.query(
|
||||
'DELETE FROM family_memo WHERE family_id = ? AND is_completed = 1',
|
||||
[familyId]
|
||||
);
|
||||
|
||||
broadcastEvent({
|
||||
type: 'memos_cleared',
|
||||
familyId,
|
||||
clearedCount: result.affectedRows
|
||||
});
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: `已成功清理 ${result.affectedRows} 项已完成备忘`,
|
||||
affectedRows: result.affectedRows
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Failed to clear completed memos:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/memos
|
||||
* 新增备忘待办事项
|
||||
*/
|
||||
router.post('/', async (req, res) => {
|
||||
try {
|
||||
const { familyId = 'family-001', content, duePeriod = 'today', operatorName = '家人' } = req.body;
|
||||
if (!content || !content.trim()) {
|
||||
return res.status(400).json({ success: false, error: '备忘待办内容不能为空' });
|
||||
}
|
||||
|
||||
const memoId = `memo-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
|
||||
await pool.query(
|
||||
`INSERT INTO family_memo (memo_id, family_id, content, due_period, is_completed, created_by)
|
||||
VALUES (?, ?, ?, ?, 0, ?)`,
|
||||
[memoId, familyId, content.trim(), duePeriod, operatorName]
|
||||
);
|
||||
|
||||
const [created] = await pool.query('SELECT * FROM family_memo WHERE memo_id = ?', [memoId]);
|
||||
|
||||
broadcastEvent({
|
||||
type: 'memo_created',
|
||||
familyId,
|
||||
memo: created[0]
|
||||
});
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: created[0]
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Failed to create memo:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* PUT /api/memos/:memoId
|
||||
* 更新备忘事项(勾选完成/修改内容)
|
||||
*/
|
||||
router.put('/:memoId', async (req, res) => {
|
||||
try {
|
||||
const { memoId } = req.params;
|
||||
const { isCompleted, content, duePeriod } = req.body;
|
||||
|
||||
const [rows] = await pool.query('SELECT * FROM family_memo WHERE memo_id = ?', [memoId]);
|
||||
if (rows.length === 0) {
|
||||
return res.status(404).json({ success: false, error: '备忘事项不存在' });
|
||||
}
|
||||
|
||||
const updates = [];
|
||||
const params = [];
|
||||
|
||||
if (isCompleted !== undefined) {
|
||||
updates.push('is_completed = ?');
|
||||
params.push(isCompleted ? 1 : 0);
|
||||
if (isCompleted) {
|
||||
updates.push('completed_at = CURRENT_TIMESTAMP');
|
||||
} else {
|
||||
updates.push('completed_at = NULL');
|
||||
}
|
||||
}
|
||||
|
||||
if (content !== undefined && content.trim()) {
|
||||
updates.push('content = ?');
|
||||
params.push(content.trim());
|
||||
}
|
||||
|
||||
if (duePeriod !== undefined) {
|
||||
updates.push('due_period = ?');
|
||||
params.push(duePeriod);
|
||||
}
|
||||
|
||||
if (updates.length > 0) {
|
||||
params.push(memoId);
|
||||
await pool.query(
|
||||
`UPDATE family_memo SET ${updates.join(', ')} WHERE memo_id = ?`,
|
||||
params
|
||||
);
|
||||
}
|
||||
|
||||
const [updated] = await pool.query('SELECT * FROM family_memo WHERE memo_id = ?', [memoId]);
|
||||
|
||||
broadcastEvent({
|
||||
type: 'memo_updated',
|
||||
familyId: rows[0].family_id,
|
||||
memo: updated[0]
|
||||
});
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: updated[0]
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Failed to update memo:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* DELETE /api/memos/:memoId
|
||||
* 删除备忘事项
|
||||
*/
|
||||
router.delete('/:memoId', async (req, res) => {
|
||||
try {
|
||||
const { memoId } = req.params;
|
||||
const [rows] = await pool.query('SELECT * FROM family_memo WHERE memo_id = ?', [memoId]);
|
||||
if (rows.length === 0) {
|
||||
return res.status(404).json({ success: false, error: '备忘事项不存在' });
|
||||
}
|
||||
|
||||
await pool.query('DELETE FROM family_memo WHERE memo_id = ?', [memoId]);
|
||||
|
||||
broadcastEvent({
|
||||
type: 'memo_deleted',
|
||||
familyId: rows[0].family_id,
|
||||
memoId
|
||||
});
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: '备忘事项已删除'
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Failed to delete memo:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -26,6 +26,19 @@ router.get('/stream', (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
// 定时发送心跳保持 SSE 长连接活跃,防止代理与浏览器切断
|
||||
const sseHeartbeat = setInterval(() => {
|
||||
clients.forEach(client => {
|
||||
try {
|
||||
client.res.write(': ping\n\n');
|
||||
} catch (e) {}
|
||||
});
|
||||
}, 20000);
|
||||
if (sseHeartbeat.unref) {
|
||||
sseHeartbeat.unref();
|
||||
}
|
||||
|
||||
|
||||
function broadcastEvent(eventData) {
|
||||
const dataString = `data: ${JSON.stringify(eventData)}\n\n`;
|
||||
clients.forEach(client => {
|
||||
|
||||
@@ -12,8 +12,9 @@ function formatElapsed(minutes) {
|
||||
if (minutes < 1) return '刚刚';
|
||||
const h = Math.floor(minutes / 60);
|
||||
const m = minutes % 60;
|
||||
if (h === 0) return `${m} 分钟前`;
|
||||
return `${h} 小时 ${m} 分前`;
|
||||
if (h === 0) return `${m}分钟前`;
|
||||
if (m === 0) return `${h}小时前`;
|
||||
return `${h}小时${m}分前`;
|
||||
}
|
||||
|
||||
router.get('/', async (req, res) => {
|
||||
|
||||
Reference in new issue
Block a user