99 lines
3.9 KiB
JavaScript
99 lines
3.9 KiB
JavaScript
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;
|