feat: initial commit for newborn tracker with family & role management, full responsive ui, offline assets
This commit is contained in:
commit
01f9f2c514
72 files changed
+11186
No files matched your search
@@ -0,0 +1,107 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { pool } = require('../db');
|
||||
const { getBabyAgeContext } = require('../pediatricEngine');
|
||||
|
||||
// GET /api/babies - List all babies (supports optional ?family_id= filter)
|
||||
router.get('/', async (req, res) => {
|
||||
try {
|
||||
const { family_id } = req.query;
|
||||
let query = 'SELECT * FROM `baby_profile`';
|
||||
const params = [];
|
||||
if (family_id) {
|
||||
query += ' WHERE `family_id` = ?';
|
||||
params.push(family_id);
|
||||
}
|
||||
query += ' ORDER BY `is_default` DESC, `id` ASC';
|
||||
|
||||
const [rows] = await pool.query(query, params);
|
||||
const babiesWithContext = rows.map(b => {
|
||||
const ageContext = getBabyAgeContext(b.birth_date);
|
||||
return {
|
||||
...b,
|
||||
ageDays: ageContext.diffDays,
|
||||
ageMonths: ageContext.months,
|
||||
ageText: ageContext.ageText,
|
||||
baseline: ageContext.baseline
|
||||
};
|
||||
});
|
||||
res.json({ success: true, data: babiesWithContext });
|
||||
} catch (err) {
|
||||
console.error('Error fetching babies:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/babies - Create or update baby profile
|
||||
router.post('/', async (req, res) => {
|
||||
const { babyId, familyId, name, gender, birthDate, themeColor } = req.body;
|
||||
if (!name || !birthDate) {
|
||||
return res.status(400).json({ success: false, error: '姓名与出生日期必填' });
|
||||
}
|
||||
|
||||
const id = babyId || 'baby-' + Date.now();
|
||||
const color = themeColor || '#3B82F6';
|
||||
const targetFamilyId = familyId || 'family-001';
|
||||
|
||||
try {
|
||||
if (babyId) {
|
||||
// Update
|
||||
await pool.query(`
|
||||
UPDATE \`baby_profile\`
|
||||
SET \`name\` = ?, \`gender\` = ?, \`birth_date\` = ?, \`theme_color\` = ?
|
||||
WHERE \`baby_id\` = ?
|
||||
`, [name, gender || 'boy', birthDate, color, babyId]);
|
||||
} else {
|
||||
// Insert with family_id
|
||||
await pool.query(`
|
||||
INSERT INTO \`baby_profile\` (\`baby_id\`, \`family_id\`, \`name\`, \`gender\`, \`birth_date\`, \`theme_color\`, \`is_default\`)
|
||||
VALUES (?, ?, ?, ?, ?, ?, 0)
|
||||
`, [id, targetFamilyId, name, gender || 'boy', birthDate, color]);
|
||||
}
|
||||
|
||||
const [updated] = await pool.query('SELECT * FROM `baby_profile` WHERE `baby_id` = ?', [id]);
|
||||
res.json({ success: true, data: updated[0] });
|
||||
} catch (err) {
|
||||
console.error('Error saving baby:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// PUT /api/babies/:babyId - Update baby profile
|
||||
router.put('/:babyId', async (req, res) => {
|
||||
const { babyId } = req.params;
|
||||
const { name, gender, birthDate, themeColor } = 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 [updated] = await pool.query('SELECT * FROM `baby_profile` WHERE `baby_id` = ?', [babyId]);
|
||||
res.json({ success: true, data: updated[0] });
|
||||
} catch (err) {
|
||||
console.error('Error updating baby:', 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;
|
||||
try {
|
||||
await pool.query('UPDATE `baby_profile` SET `is_default` = 0');
|
||||
await pool.query('UPDATE `baby_profile` SET `is_default` = 1 WHERE `baby_id` = ?', [babyId]);
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,26 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { CARE_GUIDES } = require('../careGuidesData');
|
||||
|
||||
// GET /api/care-guides - List all care guides
|
||||
router.get('/', (req, res) => {
|
||||
const { category } = req.query;
|
||||
if (category) {
|
||||
return res.json({
|
||||
success: true,
|
||||
data: CARE_GUIDES.filter(g => g.category === category)
|
||||
});
|
||||
}
|
||||
res.json({ success: true, data: CARE_GUIDES });
|
||||
});
|
||||
|
||||
// GET /api/care-guides/:id - Get specific guide
|
||||
router.get('/:id', (req, res) => {
|
||||
const guide = CARE_GUIDES.find(g => g.id === req.params.id);
|
||||
if (!guide) {
|
||||
return res.status(404).json({ success: false, error: '未找到该指导项目' });
|
||||
}
|
||||
res.json({ success: true, data: guide });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,94 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { pool } = require('../db');
|
||||
|
||||
// GET /api/custom-metrics
|
||||
router.get('/', async (req, res) => {
|
||||
const { babyId } = req.query;
|
||||
try {
|
||||
const [rows] = await pool.query(`
|
||||
SELECT * FROM \`custom_metric\`
|
||||
WHERE \`is_active\` = 1 AND (\`baby_id\` = 'global' OR \`baby_id\` = ?)
|
||||
ORDER BY \`id\` ASC
|
||||
`, [babyId || '']);
|
||||
res.json({ success: true, data: rows });
|
||||
} catch (err) {
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/custom-metrics - Create new metric
|
||||
router.post('/', async (req, res) => {
|
||||
const { babyId, name, icon, unit, targetDaily, defaultValue, type } = req.body;
|
||||
if (!name) {
|
||||
return res.status(400).json({ success: false, error: '名称必填' });
|
||||
}
|
||||
|
||||
const metricId = 'metric-' + Date.now();
|
||||
const target = parseInt(targetDaily) || 1;
|
||||
const unitStr = unit || '次';
|
||||
const iconStr = icon || '✨';
|
||||
const defValStr = String(defaultValue !== undefined && defaultValue !== null && defaultValue !== '' ? defaultValue : '1');
|
||||
const typeStr = type || 'count';
|
||||
const bId = babyId || 'global';
|
||||
|
||||
try {
|
||||
await pool.query(`
|
||||
INSERT INTO \`custom_metric\` (\`metric_id\`, \`baby_id\`, \`name\`, \`icon\`, \`type\`, \`unit\`, \`default_value\`, \`target_daily\`)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`, [metricId, bId, name, iconStr, typeStr, unitStr, defValStr, target]);
|
||||
|
||||
const [created] = await pool.query('SELECT * FROM `custom_metric` WHERE `metric_id` = ?', [metricId]);
|
||||
res.json({ success: true, data: created[0] });
|
||||
} catch (err) {
|
||||
console.error('Error creating custom metric:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// PUT /api/custom-metrics/:metricId - Update metric configuration including default value
|
||||
router.put('/:metricId', async (req, res) => {
|
||||
const { metricId } = req.params;
|
||||
const { name, icon, unit, targetDaily, defaultValue, type, isActive } = req.body;
|
||||
|
||||
try {
|
||||
const [existing] = await pool.query('SELECT * FROM `custom_metric` WHERE `metric_id` = ?', [metricId]);
|
||||
if (existing.length === 0) {
|
||||
return res.status(404).json({ success: false, error: '未找到该自定义指标' });
|
||||
}
|
||||
|
||||
const cur = existing[0];
|
||||
const newName = name !== undefined ? name : cur.name;
|
||||
const newIcon = icon !== undefined ? icon : cur.icon;
|
||||
const newUnit = unit !== undefined ? unit : cur.unit;
|
||||
const newDefVal = defaultValue !== undefined ? String(defaultValue) : cur.default_value;
|
||||
const newTarget = targetDaily !== undefined ? parseInt(targetDaily) : cur.target_daily;
|
||||
const newType = type !== undefined ? type : cur.type;
|
||||
const newActive = isActive !== undefined ? (isActive ? 1 : 0) : cur.is_active;
|
||||
|
||||
await pool.query(`
|
||||
UPDATE \`custom_metric\`
|
||||
SET \`name\` = ?, \`icon\` = ?, \`unit\` = ?, \`default_value\` = ?, \`target_daily\` = ?, \`type\` = ?, \`is_active\` = ?
|
||||
WHERE \`metric_id\` = ?
|
||||
`, [newName, newIcon, newUnit, newDefVal, newTarget, newType, newActive, metricId]);
|
||||
|
||||
const [updated] = await pool.query('SELECT * FROM `custom_metric` WHERE `metric_id` = ?', [metricId]);
|
||||
res.json({ success: true, data: updated[0] });
|
||||
} catch (err) {
|
||||
console.error('Error updating custom metric:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE /api/custom-metrics/:metricId
|
||||
router.delete('/:metricId', async (req, res) => {
|
||||
const { metricId } = req.params;
|
||||
try {
|
||||
await pool.query('UPDATE `custom_metric` SET `is_active` = 0 WHERE `metric_id` = ?', [metricId]);
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,98 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const XLSX = require('xlsx');
|
||||
const { pool } = require('../db');
|
||||
|
||||
router.get('/excel', async (req, res) => {
|
||||
const { babyId } = req.query;
|
||||
if (!babyId) {
|
||||
return res.status(400).json({ success: false, error: '缺少 babyId 参数' });
|
||||
}
|
||||
|
||||
try {
|
||||
const [babies] = await pool.query('SELECT * FROM `baby_profile` WHERE `baby_id` = ?', [babyId]);
|
||||
const babyName = babies.length > 0 ? babies[0].name : '宝宝';
|
||||
|
||||
const [rows] = await pool.query(`
|
||||
SELECT * FROM \`activity_record\`
|
||||
WHERE \`baby_id\` = ?
|
||||
ORDER BY \`start_time\` DESC
|
||||
`, [babyId]);
|
||||
|
||||
// Format Sheet 1: Detail logs
|
||||
const detailData = rows.map(r => {
|
||||
const payload = typeof r.payload === 'string' ? JSON.parse(r.payload || '{}') : (r.payload || {});
|
||||
let detailDesc = '';
|
||||
if (r.activity_type === 'bottle') {
|
||||
detailDesc = `瓶喂 ${payload.amountMl || 0}ml (${payload.milkType === 'formula' ? '配方奶' : '母乳'})`;
|
||||
} else if (r.activity_type === 'breastfeed') {
|
||||
detailDesc = `母乳亲喂 (左侧${payload.leftMinutes || 0}分 / 右侧${payload.rightMinutes || 0}分)`;
|
||||
} else if (r.activity_type === 'sleep') {
|
||||
detailDesc = `睡眠时长: ${r.duration_minutes || 0}分钟`;
|
||||
} else if (r.activity_type === 'diaper') {
|
||||
const t = payload.diaperType === 'poop' ? '便便' : (payload.diaperType === 'both' ? '尿+便' : '嘘嘘');
|
||||
detailDesc = `换尿布: ${t} (${payload.poopColor || ''} ${payload.poopTexture || ''})`;
|
||||
} else {
|
||||
detailDesc = payload.note || '日常记录';
|
||||
}
|
||||
|
||||
const typeMap = {
|
||||
bottle: '瓶喂',
|
||||
breastfeed: '亲喂',
|
||||
sleep: '睡眠',
|
||||
diaper: '换尿布',
|
||||
custom: '其他'
|
||||
};
|
||||
|
||||
return {
|
||||
'发生时间': r.start_time,
|
||||
'行为分类': typeMap[r.activity_type] || r.activity_type,
|
||||
'操作详情': detailDesc,
|
||||
'持续时长(分钟)': r.duration_minutes || 0,
|
||||
'记录人/看护人': r.operator_name || '宝妈',
|
||||
'备注说明': payload.note || ''
|
||||
};
|
||||
});
|
||||
|
||||
// Format Sheet 2: Daily Aggregation
|
||||
const [dailyRows] = await pool.query(`
|
||||
SELECT
|
||||
DATE(\`start_time\`) as logDate,
|
||||
COUNT(*) as totalEvents,
|
||||
SUM(CASE WHEN \`activity_type\` = 'bottle' THEN CAST(JSON_EXTRACT(\`payload\`, '$.amountMl') AS UNSIGNED) ELSE 0 END) as totalMilk,
|
||||
SUM(CASE WHEN \`activity_type\` = 'sleep' THEN \`duration_minutes\` ELSE 0 END) as totalSleepMin,
|
||||
SUM(CASE WHEN \`activity_type\` = 'diaper' THEN 1 ELSE 0 END) as diaperCount
|
||||
FROM \`activity_record\`
|
||||
WHERE \`baby_id\` = ?
|
||||
GROUP BY DATE(\`start_time\`)
|
||||
ORDER BY logDate DESC
|
||||
`, [babyId]);
|
||||
|
||||
const summaryData = dailyRows.map(d => ({
|
||||
'日期': d.logDate,
|
||||
'今日总奶量(ml)': d.totalMilk || 0,
|
||||
'总睡眠时长': `${Math.floor((d.totalSleepMin || 0) / 60)}小时${(d.totalSleepMin || 0) % 60}分`,
|
||||
'换尿布次数': d.diaperCount || 0,
|
||||
'总打卡记录数': d.totalEvents
|
||||
}));
|
||||
|
||||
const wb = XLSX.utils.book_new();
|
||||
const ws1 = XLSX.utils.json_to_sheet(detailData);
|
||||
const ws2 = XLSX.utils.json_to_sheet(summaryData);
|
||||
|
||||
XLSX.utils.book_append_sheet(wb, ws1, '行为流水明细');
|
||||
XLSX.utils.book_append_sheet(wb, ws2, '每日数据汇总');
|
||||
|
||||
const buffer = XLSX.write(wb, { type: 'buffer', bookType: 'xlsx' });
|
||||
|
||||
const fileName = encodeURIComponent(`${babyName}_新生儿日常记录表.xlsx`);
|
||||
res.setHeader('Content-Disposition', `attachment; filename="${fileName}"; filename*=UTF-8''${fileName}`);
|
||||
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
||||
res.send(buffer);
|
||||
} catch (err) {
|
||||
console.error('Error generating Excel export:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,243 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { pool } = require('../db');
|
||||
|
||||
function generateInviteCode() {
|
||||
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||
let code = 'YY';
|
||||
for (let i = 0; i < 4; i++) {
|
||||
code += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
// 1. 获取所有家庭列表(聚合各自的宝宝与看护人成员)
|
||||
router.get('/', async (req, res) => {
|
||||
try {
|
||||
const [families] = await pool.query(
|
||||
'SELECT family_id, name, invite_code, creator_name, is_default, created_at, updated_at FROM `family` ORDER BY is_default DESC, id ASC'
|
||||
);
|
||||
|
||||
if (families.length === 0) {
|
||||
return res.json({ success: true, data: [] });
|
||||
}
|
||||
|
||||
const familyIds = families.map(f => f.family_id);
|
||||
const placeholders = familyIds.map(() => '?').join(',');
|
||||
|
||||
// 批量查询宝宝
|
||||
const [babies] = await pool.query(
|
||||
`SELECT baby_id, family_id, name, gender, birth_date, theme_color, is_default
|
||||
FROM \`baby_profile\`
|
||||
WHERE family_id IN (${placeholders})
|
||||
ORDER BY is_default DESC, id ASC`,
|
||||
familyIds
|
||||
);
|
||||
|
||||
// 批量查询家庭成员
|
||||
const [members] = await pool.query(
|
||||
`SELECT id, family_id, role_name, is_owner, joined_at
|
||||
FROM \`family_member\`
|
||||
WHERE family_id IN (${placeholders})
|
||||
ORDER BY is_owner DESC, id ASC`,
|
||||
familyIds
|
||||
);
|
||||
|
||||
const result = families.map(f => {
|
||||
return {
|
||||
...f,
|
||||
babies: babies.filter(b => b.family_id === f.family_id),
|
||||
members: members.filter(m => m.family_id === f.family_id)
|
||||
};
|
||||
});
|
||||
|
||||
res.json({ success: true, data: result });
|
||||
} catch (err) {
|
||||
console.error('Failed to get families:', err);
|
||||
res.status(500).json({ success: false, message: '获取家庭列表失败', error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// 2. 创建新家庭
|
||||
router.post('/', async (req, res) => {
|
||||
try {
|
||||
const { name, creatorName = '宝妈' } = req.body;
|
||||
if (!name || !name.trim()) {
|
||||
return res.status(400).json({ success: false, message: '家庭名称不能为空' });
|
||||
}
|
||||
|
||||
const familyId = `family-${Date.now().toString(36)}-${Math.random().toString(36).substring(2, 6)}`;
|
||||
let inviteCode = generateInviteCode();
|
||||
|
||||
// 确保邀请码唯一
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const [existing] = await pool.query('SELECT id FROM `family` WHERE invite_code = ?', [inviteCode]);
|
||||
if (existing.length === 0) break;
|
||||
inviteCode = generateInviteCode();
|
||||
}
|
||||
|
||||
await pool.query(
|
||||
'INSERT INTO `family` (family_id, name, invite_code, creator_name, is_default) VALUES (?, ?, ?, ?, 0)',
|
||||
[familyId, name.trim(), inviteCode, creatorName]
|
||||
);
|
||||
|
||||
// 默认加入创建者成员
|
||||
await pool.query(
|
||||
'INSERT INTO `family_member` (family_id, role_name, is_owner) VALUES (?, ?, 1)',
|
||||
[familyId, creatorName]
|
||||
);
|
||||
|
||||
// 默认补充常用协同看护人 (如宝爸)
|
||||
if (creatorName === '宝妈') {
|
||||
await pool.query(
|
||||
'INSERT INTO `family_member` (family_id, role_name, is_owner) VALUES (?, ?, 0)',
|
||||
[familyId, '宝爸']
|
||||
);
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: '家庭创建成功',
|
||||
data: {
|
||||
family_id: familyId,
|
||||
name: name.trim(),
|
||||
invite_code: inviteCode,
|
||||
creator_name: creatorName,
|
||||
is_default: 0
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Failed to create family:', err);
|
||||
res.status(500).json({ success: false, message: '创建家庭失败', error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// 3. 修改家庭基础信息 (如家庭名称)
|
||||
router.put('/:familyId', async (req, res) => {
|
||||
try {
|
||||
const { familyId } = req.params;
|
||||
const { name } = req.body;
|
||||
|
||||
if (!name || !name.trim()) {
|
||||
return res.status(400).json({ success: false, message: '家庭名称不能为空' });
|
||||
}
|
||||
|
||||
const [result] = await pool.query(
|
||||
'UPDATE `family` SET name = ? WHERE family_id = ?',
|
||||
[name.trim(), familyId]
|
||||
);
|
||||
|
||||
if (result.affectedRows === 0) {
|
||||
return res.status(404).json({ success: false, message: '未找到指定家庭' });
|
||||
}
|
||||
|
||||
res.json({ success: true, message: '家庭名称修改成功' });
|
||||
} catch (err) {
|
||||
console.error('Failed to update family:', err);
|
||||
res.status(500).json({ success: false, message: '修改家庭失败', error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// 4. 输入邀请码加入家庭 (为微信邀请/口令加入打通)
|
||||
router.post('/join', async (req, res) => {
|
||||
try {
|
||||
const { inviteCode, roleName = '看护人' } = req.body;
|
||||
if (!inviteCode || !inviteCode.trim()) {
|
||||
return res.status(400).json({ success: false, message: '请输入家庭邀请码' });
|
||||
}
|
||||
|
||||
const cleanCode = inviteCode.trim().toUpperCase();
|
||||
const [families] = await pool.query(
|
||||
'SELECT family_id, name, invite_code, creator_name FROM `family` WHERE UPPER(invite_code) = ?',
|
||||
[cleanCode]
|
||||
);
|
||||
|
||||
if (families.length === 0) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: '邀请码不存在或已失效,请向家庭管理员索取正确的 6 位邀请码'
|
||||
});
|
||||
}
|
||||
|
||||
const family = families[0];
|
||||
|
||||
// 检查该角色成员是否已在该家庭中
|
||||
const [existingMember] = await pool.query(
|
||||
'SELECT id FROM `family_member` WHERE family_id = ? AND role_name = ?',
|
||||
[family.family_id, roleName]
|
||||
);
|
||||
|
||||
if (existingMember.length === 0) {
|
||||
await pool.query(
|
||||
'INSERT INTO `family_member` (family_id, role_name, is_owner) VALUES (?, ?, 0)',
|
||||
[family.family_id, roleName]
|
||||
);
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: `恭喜!已成功加入【${family.name}】`,
|
||||
data: family
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Failed to join family:', err);
|
||||
res.status(500).json({ success: false, message: '加入家庭失败', error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// 5. 获取家庭看护人成员列表
|
||||
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',
|
||||
[familyId]
|
||||
);
|
||||
res.json({ success: true, data: members });
|
||||
} catch (err) {
|
||||
console.error('Failed to get family members:', err);
|
||||
res.status(500).json({ success: false, message: '获取家庭成员失败', error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// 6. 为家庭新增看护人员成员
|
||||
router.post('/:familyId/members', async (req, res) => {
|
||||
try {
|
||||
const { familyId } = req.params;
|
||||
const { roleName } = req.body;
|
||||
|
||||
if (!roleName || !roleName.trim()) {
|
||||
return res.status(400).json({ success: false, message: '看护人身份称谓不能为空' });
|
||||
}
|
||||
|
||||
const [existing] = await pool.query(
|
||||
'SELECT id FROM `family_member` WHERE family_id = ? AND role_name = ?',
|
||||
[familyId, roleName.trim()]
|
||||
);
|
||||
|
||||
if (existing.length > 0) {
|
||||
return res.status(400).json({ success: false, message: '该看护人身份已在家庭中' });
|
||||
}
|
||||
|
||||
const [result] = await pool.query(
|
||||
'INSERT INTO `family_member` (family_id, role_name, is_owner) VALUES (?, ?, 0)',
|
||||
[familyId, roleName.trim()]
|
||||
);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: '添加看护人员成功',
|
||||
data: {
|
||||
id: result.insertId,
|
||||
family_id: familyId,
|
||||
role_name: roleName.trim(),
|
||||
is_owner: 0
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Failed to add family member:', err);
|
||||
res.status(500).json({ success: false, message: '添加家庭成员失败', error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,196 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { pool } = require('../db');
|
||||
const { broadcastEvent } = require('./sse');
|
||||
|
||||
function formatDateTime(d = new Date()) {
|
||||
const pad = n => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
||||
}
|
||||
|
||||
// GET /api/records - Get records for a baby
|
||||
router.get('/', async (req, res) => {
|
||||
const { babyId, date, limit } = req.query;
|
||||
if (!babyId) {
|
||||
return res.status(400).json({ success: false, error: '缺少 babyId 参数' });
|
||||
}
|
||||
|
||||
try {
|
||||
let query = 'SELECT * FROM `activity_record` WHERE `baby_id` = ?';
|
||||
const params = [babyId];
|
||||
|
||||
if (date) {
|
||||
query += ' AND DATE(`start_time`) = ?';
|
||||
params.push(date);
|
||||
}
|
||||
|
||||
query += ' ORDER BY `start_time` DESC';
|
||||
|
||||
if (limit) {
|
||||
query += ' LIMIT ?';
|
||||
params.push(parseInt(limit));
|
||||
}
|
||||
|
||||
const [rows] = await pool.query(query, params);
|
||||
const parsed = rows.map(r => ({
|
||||
...r,
|
||||
payload: typeof r.payload === 'string' ? JSON.parse(r.payload || '{}') : (r.payload || {})
|
||||
}));
|
||||
|
||||
res.json({ success: true, data: parsed });
|
||||
} catch (err) {
|
||||
console.error('Error fetching records:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/records - Create a record (One-tap log)
|
||||
router.post('/', async (req, res) => {
|
||||
const {
|
||||
babyId,
|
||||
activityType,
|
||||
startTime,
|
||||
endTime,
|
||||
durationMinutes,
|
||||
payload,
|
||||
operatorName,
|
||||
operatorUserId
|
||||
} = req.body;
|
||||
|
||||
if (!babyId || !activityType) {
|
||||
return res.status(400).json({ success: false, error: 'babyId 与 activityType 必填' });
|
||||
}
|
||||
|
||||
const recordId = 'rec-' + Date.now() + '-' + Math.random().toString(36).substring(2, 6);
|
||||
const nowStr = formatDateTime();
|
||||
const start = startTime || nowStr;
|
||||
const end = endTime || null;
|
||||
const duration = durationMinutes || 0;
|
||||
const operator = operatorName || '宝妈';
|
||||
const payloadJson = JSON.stringify(payload || {});
|
||||
|
||||
try {
|
||||
// Check recent duplicate tap (within 3 minutes)
|
||||
const [recent] = await pool.query(`
|
||||
SELECT * FROM \`activity_record\`
|
||||
WHERE \`baby_id\` = ?
|
||||
AND \`activity_type\` = ?
|
||||
AND \`start_time\` >= DATE_SUB(NOW(), INTERVAL 3 MINUTE)
|
||||
ORDER BY \`start_time\` DESC LIMIT 1
|
||||
`, [babyId, activityType]);
|
||||
|
||||
let duplicateWarning = null;
|
||||
if (recent.length > 0 && !req.body.forceConfirm) {
|
||||
duplicateWarning = `${recent[0].operator_name} 在刚刚(${recent[0].start_time.substring(11, 16)})已记录过该行为`;
|
||||
}
|
||||
|
||||
await pool.query(`
|
||||
INSERT INTO \`activity_record\`
|
||||
(\`record_id\`, \`baby_id\`, \`activity_type\`, \`start_time\`, \`end_time\`, \`duration_minutes\`, \`payload\`, \`operator_name\`, \`operator_user_id\`)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`, [recordId, babyId, activityType, start, end, duration, payloadJson, operator, operatorUserId || null]);
|
||||
|
||||
const [created] = await pool.query('SELECT * FROM `activity_record` WHERE `record_id` = ?', [recordId]);
|
||||
const recordObj = {
|
||||
...created[0],
|
||||
payload: typeof created[0].payload === 'string' ? JSON.parse(created[0].payload || '{}') : (created[0].payload || {})
|
||||
};
|
||||
|
||||
// Broadcast SSE to all other mobile devices!
|
||||
broadcastEvent({
|
||||
type: 'record_created',
|
||||
babyId,
|
||||
activityType,
|
||||
operatorName: operator,
|
||||
record: recordObj
|
||||
});
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: recordObj,
|
||||
duplicateWarning
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error creating record:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// PUT /api/records/:recordId - Update record
|
||||
router.put('/:recordId', async (req, res) => {
|
||||
const { recordId } = req.params;
|
||||
const { startTime, endTime, durationMinutes, payload, operatorName } = req.body;
|
||||
|
||||
try {
|
||||
const fields = [];
|
||||
const params = [];
|
||||
|
||||
if (startTime !== undefined) {
|
||||
fields.push('`start_time` = ?');
|
||||
params.push(startTime);
|
||||
}
|
||||
if (endTime !== undefined) {
|
||||
fields.push('`end_time` = ?');
|
||||
params.push(endTime);
|
||||
}
|
||||
if (durationMinutes !== undefined) {
|
||||
fields.push('`duration_minutes` = ?');
|
||||
params.push(durationMinutes);
|
||||
}
|
||||
if (payload !== undefined) {
|
||||
fields.push('`payload` = ?');
|
||||
params.push(JSON.stringify(payload));
|
||||
}
|
||||
if (operatorName !== undefined) {
|
||||
fields.push('`operator_name` = ?');
|
||||
params.push(operatorName);
|
||||
}
|
||||
|
||||
if (fields.length === 0) {
|
||||
return res.json({ success: true });
|
||||
}
|
||||
|
||||
params.push(recordId);
|
||||
await pool.query(`UPDATE \`activity_record\` SET ${fields.join(', ')} WHERE \`record_id\` = ?`, params);
|
||||
|
||||
const [updated] = await pool.query('SELECT * FROM `activity_record` WHERE `record_id` = ?', [recordId]);
|
||||
if (updated.length > 0) {
|
||||
broadcastEvent({
|
||||
type: 'record_updated',
|
||||
babyId: updated[0].baby_id,
|
||||
record: updated[0]
|
||||
});
|
||||
}
|
||||
|
||||
res.json({ success: true, data: updated[0] });
|
||||
} catch (err) {
|
||||
console.error('Error updating record:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE /api/records/:recordId - Delete record
|
||||
router.delete('/:recordId', async (req, res) => {
|
||||
const { recordId } = req.params;
|
||||
try {
|
||||
const [existing] = await pool.query('SELECT * FROM `activity_record` WHERE `record_id` = ?', [recordId]);
|
||||
if (existing.length === 0) {
|
||||
return res.status(404).json({ success: false, error: '记录不存在' });
|
||||
}
|
||||
|
||||
await pool.query('DELETE FROM `activity_record` WHERE `record_id` = ?', [recordId]);
|
||||
|
||||
broadcastEvent({
|
||||
type: 'record_deleted',
|
||||
babyId: existing[0].baby_id,
|
||||
recordId
|
||||
});
|
||||
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
console.error('Error deleting record:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,43 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
// List of connected SSE clients
|
||||
let clients = [];
|
||||
|
||||
router.get('/stream', (req, res) => {
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Connection': 'keep-alive'
|
||||
});
|
||||
|
||||
const clientId = Date.now() + '-' + Math.random().toString(36).substring(2, 7);
|
||||
const newClient = {
|
||||
id: clientId,
|
||||
res
|
||||
};
|
||||
clients.push(newClient);
|
||||
|
||||
// Send initial connection event
|
||||
res.write(`data: ${JSON.stringify({ type: 'connected', clientId })}\n\n`);
|
||||
|
||||
req.on('close', () => {
|
||||
clients = clients.filter(c => c.id !== clientId);
|
||||
});
|
||||
});
|
||||
|
||||
function broadcastEvent(eventData) {
|
||||
const dataString = `data: ${JSON.stringify(eventData)}\n\n`;
|
||||
clients.forEach(client => {
|
||||
try {
|
||||
client.res.write(dataString);
|
||||
} catch (e) {
|
||||
// client might have disconnected
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
router,
|
||||
broadcastEvent
|
||||
};
|
||||
@@ -0,0 +1,479 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { pool } = require('../db');
|
||||
const { getBabyAgeContext, calculateWakeWindow } = require('../pediatricEngine');
|
||||
|
||||
function getLocalDateString(d = new Date()) {
|
||||
const pad = n => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
||||
}
|
||||
|
||||
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} 分前`;
|
||||
}
|
||||
|
||||
router.get('/', async (req, res) => {
|
||||
const { babyId } = req.query;
|
||||
const targetDate = req.query.date || getLocalDateString();
|
||||
|
||||
if (!babyId) {
|
||||
return res.status(400).json({ success: false, error: '缺少 babyId 参数' });
|
||||
}
|
||||
|
||||
try {
|
||||
// 1. Fetch baby profile
|
||||
const [babies] = await pool.query('SELECT * FROM `baby_profile` WHERE `baby_id` = ?', [babyId]);
|
||||
if (babies.length === 0) {
|
||||
return res.status(404).json({ success: false, error: '宝宝不存在' });
|
||||
}
|
||||
const baby = babies[0];
|
||||
const ageContext = getBabyAgeContext(baby.birth_date);
|
||||
|
||||
// 2. Fetch all records for target date
|
||||
const [dayRecordsRaw] = await pool.query(`
|
||||
SELECT * FROM \`activity_record\`
|
||||
WHERE \`baby_id\` = ? AND DATE(\`start_time\`) = ?
|
||||
ORDER BY \`start_time\` ASC
|
||||
`, [babyId, targetDate]);
|
||||
|
||||
const dayRecords = dayRecordsRaw.map(r => ({
|
||||
...r,
|
||||
payload: typeof r.payload === 'string' ? JSON.parse(r.payload || '{}') : (r.payload || {})
|
||||
}));
|
||||
|
||||
// 3. Fetch custom metrics definitions
|
||||
const [customDefs] = await pool.query(`
|
||||
SELECT * FROM \`custom_metric\`
|
||||
WHERE \`is_active\` = 1 AND (\`baby_id\` = 'global' OR \`baby_id\` = ?)
|
||||
ORDER BY \`id\` ASC
|
||||
`, [babyId]);
|
||||
|
||||
const customMap = {};
|
||||
customDefs.forEach(def => {
|
||||
customMap[def.metric_id] = {
|
||||
metricId: def.metric_id,
|
||||
name: def.name,
|
||||
icon: def.icon,
|
||||
unit: def.unit,
|
||||
targetDaily: def.target_daily,
|
||||
count: 0,
|
||||
totalValue: 0
|
||||
};
|
||||
});
|
||||
|
||||
// 4. Fetch latest events to compute "time elapsed since last action"
|
||||
const [latestEvents] = await pool.query(`
|
||||
SELECT * FROM \`activity_record\`
|
||||
WHERE \`baby_id\` = ?
|
||||
ORDER BY \`start_time\` DESC LIMIT 50
|
||||
`, [babyId]);
|
||||
|
||||
const parsedLatest = latestEvents.map(r => ({
|
||||
...r,
|
||||
payload: typeof r.payload === 'string' ? JSON.parse(r.payload || '{}') : (r.payload || {})
|
||||
}));
|
||||
|
||||
const now = Date.now();
|
||||
|
||||
// Last Feeding
|
||||
const lastFeed = parsedLatest.find(e => e.activity_type === 'bottle' || e.activity_type === 'breastfeed');
|
||||
let feedingStatus = { hasData: false };
|
||||
if (lastFeed) {
|
||||
const feedTime = new Date(lastFeed.end_time || lastFeed.start_time).getTime();
|
||||
const elapsedMin = Math.max(0, Math.floor((now - feedTime) / 60000));
|
||||
const targetIntervalMin = ageContext.baseline.feedingIntervalHours * 60;
|
||||
const isOverdue = elapsedMin > targetIntervalMin;
|
||||
feedingStatus = {
|
||||
hasData: true,
|
||||
type: lastFeed.activity_type,
|
||||
time: (lastFeed.end_time || lastFeed.start_time).substring(11, 16),
|
||||
elapsedMinutes: elapsedMin,
|
||||
elapsedText: formatElapsed(elapsedMin),
|
||||
amountMl: lastFeed.payload.amountMl || null,
|
||||
durationMinutes: lastFeed.duration_minutes || null,
|
||||
operator: lastFeed.operator_name,
|
||||
targetIntervalHours: ageContext.baseline.feedingIntervalHours,
|
||||
isOverdue,
|
||||
overdueMinutes: isOverdue ? elapsedMin - targetIntervalMin : 0
|
||||
};
|
||||
}
|
||||
|
||||
// Last Diaper
|
||||
const lastDiaper = parsedLatest.find(e => e.activity_type === 'diaper');
|
||||
let diaperStatus = { hasData: false };
|
||||
if (lastDiaper) {
|
||||
const diaperTime = new Date(lastDiaper.start_time).getTime();
|
||||
const elapsedMin = Math.max(0, Math.floor((now - diaperTime) / 60000));
|
||||
diaperStatus = {
|
||||
hasData: true,
|
||||
time: lastDiaper.start_time.substring(11, 16),
|
||||
elapsedMinutes: elapsedMin,
|
||||
elapsedText: formatElapsed(elapsedMin),
|
||||
diaperType: lastDiaper.payload.diaperType || 'pee',
|
||||
operator: lastDiaper.operator_name
|
||||
};
|
||||
}
|
||||
|
||||
// Last Sleep / Current Sleep state
|
||||
const latestSleep = parsedLatest.find(e => e.activity_type === 'sleep');
|
||||
let isCurrentlySleeping = false;
|
||||
let sleepStatus = { hasData: false };
|
||||
let lastSleepEndTime = null;
|
||||
|
||||
if (latestSleep) {
|
||||
const sleepStart = new Date(latestSleep.start_time).getTime();
|
||||
if (!latestSleep.end_time) {
|
||||
isCurrentlySleeping = true;
|
||||
const currentSleepingMin = Math.max(0, Math.floor((now - sleepStart) / 60000));
|
||||
sleepStatus = {
|
||||
hasData: true,
|
||||
isSleeping: true,
|
||||
startTime: latestSleep.start_time.substring(11, 16),
|
||||
currentDurationMinutes: currentSleepingMin,
|
||||
currentDurationText: `${Math.floor(currentSleepingMin / 60)}小时${currentSleepingMin % 60}分`,
|
||||
operator: latestSleep.operator_name
|
||||
};
|
||||
} else {
|
||||
lastSleepEndTime = latestSleep.end_time;
|
||||
const sleepEnd = new Date(latestSleep.end_time).getTime();
|
||||
const awakeMin = Math.max(0, Math.floor((now - sleepEnd) / 60000));
|
||||
sleepStatus = {
|
||||
hasData: true,
|
||||
isSleeping: false,
|
||||
endTime: latestSleep.end_time.substring(11, 16),
|
||||
awakeMinutes: awakeMin,
|
||||
awakeText: formatElapsed(awakeMin),
|
||||
lastDurationMinutes: latestSleep.duration_minutes,
|
||||
operator: latestSleep.operator_name
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Wake Window Predictor
|
||||
const wakeWindow = calculateWakeWindow(lastSleepEndTime, isCurrentlySleeping, ageContext.baseline);
|
||||
|
||||
// 6. Daily Aggregation for Target Date
|
||||
let totalBottleMl = 0;
|
||||
let totalBreastfeedMin = 0;
|
||||
let feedCount = 0;
|
||||
let totalSleepMin = 0;
|
||||
let nightSleepMin = 0;
|
||||
let daySleepMin = 0;
|
||||
let sleepCount = 0;
|
||||
let longestSleepMin = 0;
|
||||
let diaperCount = 0;
|
||||
let peeCount = 0;
|
||||
let poopCount = 0;
|
||||
let abnormalStoolDetected = false;
|
||||
|
||||
// Detailed lists for specific breakdowns
|
||||
const feedingList = [];
|
||||
const sleepList = [];
|
||||
const diaperList = [];
|
||||
const customList = [];
|
||||
|
||||
// Four Day Periods (大块触控时段作息卡片,彻底解决手机上难以点准小点的问题)
|
||||
const periodSlots = {
|
||||
dawn: { label: '凌晨/后半夜 (00:00~06:00)', icon: '🌙', items: [] },
|
||||
morning: { label: '早晨/上午 (06:00~12:00)', icon: '🌅', items: [] },
|
||||
afternoon: { label: '下午 (12:00~18:00)', icon: '☀️', items: [] },
|
||||
evening: { label: '傍晚/夜间 (18:00~24:00)', icon: '🌃', items: [] }
|
||||
};
|
||||
|
||||
// Gantt items for reference
|
||||
const ganttItems = [];
|
||||
|
||||
dayRecords.forEach(r => {
|
||||
const startTimeStr = r.start_time.substring(11, 16);
|
||||
const [sh, sm] = startTimeStr.split(':').map(Number);
|
||||
const startMinuteOfDay = sh * 60 + sm;
|
||||
|
||||
// Assign to period
|
||||
let slotKey = 'dawn';
|
||||
if (sh >= 6 && sh < 12) slotKey = 'morning';
|
||||
else if (sh >= 12 && sh < 18) slotKey = 'afternoon';
|
||||
else if (sh >= 18) slotKey = 'evening';
|
||||
|
||||
let periodItem = {
|
||||
id: r.record_id,
|
||||
type: r.activity_type,
|
||||
time: startTimeStr,
|
||||
operator: r.operator_name,
|
||||
payload: r.payload,
|
||||
duration: r.duration_minutes
|
||||
};
|
||||
|
||||
if (r.activity_type === 'bottle') {
|
||||
const ml = r.payload.amountMl || 0;
|
||||
totalBottleMl += ml;
|
||||
feedCount++;
|
||||
feedingList.push({
|
||||
time: startTimeStr,
|
||||
amountMl: ml,
|
||||
milkType: r.payload.milkType,
|
||||
operator: r.operator_name,
|
||||
note: r.payload.note
|
||||
});
|
||||
periodItem.desc = `瓶喂 ${ml}ml (${r.payload.milkType === 'formula' ? '配方奶' : '母乳'})`;
|
||||
periodItem.badgeColor = 'bg-amber-100 text-amber-800 border-amber-200';
|
||||
periodItem.icon = '🍼';
|
||||
|
||||
ganttItems.push({
|
||||
id: r.record_id,
|
||||
type: 'feeding',
|
||||
subType: 'bottle',
|
||||
startMinute: startMinuteOfDay,
|
||||
durationMinute: Math.max(15, r.duration_minutes || 15),
|
||||
label: `${ml}ml`,
|
||||
operator: r.operator_name,
|
||||
time: startTimeStr,
|
||||
payload: r.payload
|
||||
});
|
||||
} else if (r.activity_type === 'breastfeed') {
|
||||
const left = r.payload.leftMinutes || 0;
|
||||
const right = r.payload.rightMinutes || 0;
|
||||
const dur = left + right || r.duration_minutes || 20;
|
||||
totalBreastfeedMin += dur;
|
||||
feedCount++;
|
||||
feedingList.push({
|
||||
time: startTimeStr,
|
||||
leftMinutes: left,
|
||||
rightMinutes: right,
|
||||
durationMinutes: dur,
|
||||
operator: r.operator_name,
|
||||
note: r.payload.note
|
||||
});
|
||||
periodItem.desc = `母乳亲喂 ${dur}分钟 (左${left}m/右${right}m)`;
|
||||
periodItem.badgeColor = 'bg-rose-100 text-rose-800 border-rose-200';
|
||||
periodItem.icon = '🤱';
|
||||
|
||||
ganttItems.push({
|
||||
id: r.record_id,
|
||||
type: 'feeding',
|
||||
subType: 'breastfeed',
|
||||
startMinute: startMinuteOfDay,
|
||||
durationMinute: dur,
|
||||
label: `亲喂${dur}m`,
|
||||
operator: r.operator_name,
|
||||
time: startTimeStr,
|
||||
payload: r.payload
|
||||
});
|
||||
} else if (r.activity_type === 'sleep') {
|
||||
sleepCount++;
|
||||
const dur = r.duration_minutes || (r.end_time ? Math.round((new Date(r.end_time).getTime() - new Date(r.start_time).getTime()) / 60000) : 60);
|
||||
totalSleepMin += dur;
|
||||
if (dur > longestSleepMin) longestSleepMin = dur;
|
||||
|
||||
if (sh >= 20 || sh < 6) {
|
||||
nightSleepMin += dur;
|
||||
} else {
|
||||
daySleepMin += dur;
|
||||
}
|
||||
|
||||
sleepList.push({
|
||||
startTime: startTimeStr,
|
||||
endTime: r.end_time ? r.end_time.substring(11, 16) : '进行中',
|
||||
durationMinutes: dur,
|
||||
operator: r.operator_name,
|
||||
note: r.payload.note
|
||||
});
|
||||
periodItem.desc = `睡眠 ${Math.floor(dur / 60)}h${dur % 60}m (${r.end_time ? startTimeStr + '~' + r.end_time.substring(11, 16) : '睡着中'})`;
|
||||
periodItem.badgeColor = 'bg-purple-100 text-purple-800 border-purple-200';
|
||||
periodItem.icon = '😴';
|
||||
|
||||
ganttItems.push({
|
||||
id: r.record_id,
|
||||
type: 'sleep',
|
||||
subType: 'sleep',
|
||||
startMinute: startMinuteOfDay,
|
||||
durationMinute: dur,
|
||||
label: `${Math.floor(dur / 60)}h${dur % 60}m`,
|
||||
operator: r.operator_name,
|
||||
time: startTimeStr,
|
||||
payload: r.payload
|
||||
});
|
||||
} else if (r.activity_type === 'diaper') {
|
||||
diaperCount++;
|
||||
const dtype = r.payload.diaperType || 'pee';
|
||||
if (dtype === 'pee') peeCount++;
|
||||
else if (dtype === 'poop') poopCount++;
|
||||
else { peeCount++; poopCount++; }
|
||||
|
||||
if (r.payload.poopColor === 'black' || r.payload.poopColor === 'red' || r.payload.poopColor === 'white') {
|
||||
abnormalStoolDetected = true;
|
||||
}
|
||||
|
||||
diaperList.push({
|
||||
time: startTimeStr,
|
||||
diaperType: dtype,
|
||||
poopColor: r.payload.poopColor,
|
||||
poopTexture: r.payload.poopTexture,
|
||||
operator: r.operator_name,
|
||||
note: r.payload.note
|
||||
});
|
||||
const dText = dtype === 'poop' ? '便便' : (dtype === 'both' ? '小便+大便' : '小便');
|
||||
periodItem.desc = `换尿布: ${dText} ${r.payload.poopColor ? '(' + r.payload.poopColor + ')' : ''}`;
|
||||
periodItem.badgeColor = 'bg-sky-100 text-sky-800 border-sky-200';
|
||||
periodItem.icon = '💧';
|
||||
|
||||
ganttItems.push({
|
||||
id: r.record_id,
|
||||
type: 'diaper',
|
||||
subType: dtype,
|
||||
startMinute: startMinuteOfDay,
|
||||
durationMinute: 10,
|
||||
label: dtype === 'poop' ? '便便' : (dtype === 'both' ? '尿+便' : '嘘嘘'),
|
||||
operator: r.operator_name,
|
||||
time: startTimeStr,
|
||||
payload: r.payload
|
||||
});
|
||||
} else if (r.activity_type === 'custom') {
|
||||
const mid = r.payload.metricId;
|
||||
const mname = r.payload.name || (customMap[mid] ? customMap[mid].name : '自定义项目');
|
||||
const micon = r.payload.icon || (customMap[mid] ? customMap[mid].icon : '✨');
|
||||
const munit = r.payload.unit || (customMap[mid] ? customMap[mid].unit : '次');
|
||||
const val = parseFloat(r.payload.value) || 1;
|
||||
|
||||
if (mid && customMap[mid]) {
|
||||
customMap[mid].count += 1;
|
||||
customMap[mid].totalValue += val;
|
||||
} else {
|
||||
if (!customMap[mname]) {
|
||||
customMap[mname] = { metricId: mname, name: mname, icon: micon, unit: munit, targetDaily: 1, count: 0, totalValue: 0 };
|
||||
}
|
||||
customMap[mname].count += 1;
|
||||
customMap[mname].totalValue += val;
|
||||
}
|
||||
|
||||
customList.push({
|
||||
time: startTimeStr,
|
||||
name: mname,
|
||||
icon: micon,
|
||||
value: val,
|
||||
unit: munit,
|
||||
operator: r.operator_name,
|
||||
note: r.payload.note
|
||||
});
|
||||
|
||||
periodItem.desc = `${mname}: ${val} ${munit}`;
|
||||
periodItem.badgeColor = 'bg-emerald-100 text-emerald-800 border-emerald-200';
|
||||
periodItem.icon = micon;
|
||||
}
|
||||
|
||||
periodSlots[slotKey].items.push(periodItem);
|
||||
});
|
||||
|
||||
// 7. Recent 7 Days Trend Query
|
||||
const [sevenDayHistory] = await pool.query(`
|
||||
SELECT
|
||||
DATE(\`start_time\`) as logDate,
|
||||
\`activity_type\`,
|
||||
SUM(\`duration_minutes\`) as totalDuration,
|
||||
COUNT(*) as eventCount,
|
||||
\`payload\`
|
||||
FROM \`activity_record\`
|
||||
WHERE \`baby_id\` = ?
|
||||
AND \`start_time\` >= DATE_SUB(?, INTERVAL 6 DAY)
|
||||
AND \`start_time\` <= CONCAT(?, ' 23:59:59')
|
||||
GROUP BY DATE(\`start_time\`), \`activity_type\`, \`id\`
|
||||
`, [babyId, targetDate, targetDate]);
|
||||
|
||||
const trendMap = {};
|
||||
for (let i = 6; i >= 0; i--) {
|
||||
const dt = new Date(new Date(targetDate).getTime() - i * 24 * 3600 * 1000);
|
||||
const ds = getLocalDateString(dt);
|
||||
trendMap[ds] = {
|
||||
date: ds,
|
||||
dayLabel: ds.substring(5),
|
||||
totalMilkMl: 0,
|
||||
totalSleepHours: 0,
|
||||
diaperCount: 0
|
||||
};
|
||||
}
|
||||
|
||||
sevenDayHistory.forEach(row => {
|
||||
const ds = row.logDate;
|
||||
if (trendMap[ds]) {
|
||||
const payload = typeof row.payload === 'string' ? JSON.parse(row.payload || '{}') : (row.payload || {});
|
||||
if (row.activity_type === 'bottle') {
|
||||
trendMap[ds].totalMilkMl += (payload.amountMl || 0);
|
||||
} else if (row.activity_type === 'sleep') {
|
||||
trendMap[ds].totalSleepHours += Math.round(((row.totalDuration || 0) / 60) * 10) / 10;
|
||||
} else if (row.activity_type === 'diaper') {
|
||||
trendMap[ds].diaperCount += 1;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const trends = Object.values(trendMap);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
baby: {
|
||||
...baby,
|
||||
ageDays: ageContext.diffDays,
|
||||
ageMonths: ageContext.months,
|
||||
ageText: ageContext.ageText,
|
||||
baseline: ageContext.baseline
|
||||
},
|
||||
targetDate,
|
||||
liveStatus: {
|
||||
feeding: feedingStatus,
|
||||
diaper: diaperStatus,
|
||||
sleep: sleepStatus,
|
||||
wakeWindow
|
||||
},
|
||||
kpi: {
|
||||
feeding: {
|
||||
totalBottleMl,
|
||||
totalBreastfeedMin,
|
||||
feedCount,
|
||||
avgIntervalHours: feedCount > 1 ? Math.round((24 / feedCount) * 10) / 10 : null,
|
||||
targetMlRange: `${ageContext.baseline.dailyMilkMlMin}~${ageContext.baseline.dailyMilkMlMax}ml`,
|
||||
list: feedingList
|
||||
},
|
||||
sleep: {
|
||||
totalSleepMin,
|
||||
totalSleepText: `${Math.floor(totalSleepMin / 60)}小时${totalSleepMin % 60}分`,
|
||||
nightSleepMin,
|
||||
daySleepMin,
|
||||
sleepCount,
|
||||
longestSleepText: `${Math.floor(longestSleepMin / 60)}小时${longestSleepMin % 60}分`,
|
||||
targetSleepRange: `${ageContext.baseline.targetSleepHoursMin}~${ageContext.baseline.targetSleepHoursMax}小时`,
|
||||
list: sleepList
|
||||
},
|
||||
diaper: {
|
||||
diaperCount,
|
||||
peeCount,
|
||||
poopCount,
|
||||
abnormalStoolDetected,
|
||||
targetCountRange: `${ageContext.baseline.diaperCountMin}~${ageContext.baseline.diaperCountMax}次`,
|
||||
list: diaperList
|
||||
},
|
||||
custom: {
|
||||
metrics: Object.values(customMap),
|
||||
list: customList
|
||||
}
|
||||
},
|
||||
periods: periodSlots,
|
||||
periodSlots: periodSlots,
|
||||
gantt: {
|
||||
date: targetDate,
|
||||
items: ganttItems
|
||||
},
|
||||
trends,
|
||||
timeline: dayRecords.reverse()
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error generating summary:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
Reference in new issue
Block a user