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;