This commit is contained in:
gs committed 2026-09-25 22:08:37 +08:00
1 parent 01f9f2c514
commit dc23ea53ed
25 files changed
+3096 -156

No files matched your search

@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-09-24
@@ -0,0 +1,67 @@
# Design: 喂奶双模式与角色行为记忆偏好系统 (Feeding Modes & Role Preference Memory)
## Context
在新生儿照护系统中,日常打卡需追求“单手、低认知负荷、极速”。当前系统喂奶卡片仅侧重瓶喂(按容量 ml 加减),对高频的母乳亲喂(以起止时间和持续时长为核心)缺乏独立的卡片形态支持。此外,家庭中不同角色(如宝妈偏好亲喂、宝爸/长辈偏好瓶喂)在切换角色时无法自动加载习惯模式,每次均需重复点选。
本设计旨在打造一个**以角色为记忆单元、以双模式为核心表现、以档案为配置中枢**的通用行为偏好系统。
## Goals / Non-Goals
**Goals:**
1. **喂奶双模式无缝切换**:喂奶卡片支持「🤱 亲喂」与「🍼 瓶喂」双态,亲喂以开始时刻、结束时刻、持续分钟数和左右侧为核心;瓶喂以 ml 容量为核心。
2. **角色行为独立记忆 (Per-Role Memory)**:每个看护人角色独立拥有行为偏好配置,切换操作人时自动无感恢复其专属模式。
3. **档案与全局默认配置**:在宝贝档案中提供全局默认模式与各角色偏好集中管理面板。
4. **通用行为架构拓展**:将“模式切换 + 默认值预设 + 人工精细修改 + 角色记忆”统一应用到喂奶、睡眠、尿布与自定义打卡中。
5. **本地缓存与服务端持久化结合**:前端 LocalStorage 实现 0 延迟秒级响应,后端 MySQL 提供多端同步备份。
**Non-Goals:**
- 不强制要求亲喂必须使用实时秒级秒表(提供即时一键按预设时长倒推完成,亦支持微调起止点)。
- 不破坏已有 `activity_record` 的历史数据结构,全面向后兼容。
## Decisions
### 1. 喂奶卡片双态 UI 交互架构 (Dual-State Card Component)
- **选择方案**:在快速打卡界面的「喂奶卡片」内部顶部引入轻量 Segmented Tabs:`[ 🤱 亲喂 (时长) | 🍼 瓶喂 (容量) ]`。
- **状态驱动渲染**:
- **亲喂状态**:展示当前预设时长(如 `20分钟`)、预估开始/结束时间、左右侧时长快捷选块、`一键完成亲喂 (20m)` 按钮与 `[✏️ 微调时间]` 按钮;
- **瓶喂状态**:展示快捷容量徽章(60/90/120/150ml)、`±10ml` 步进器、奶液类型切换(配方奶/母乳)及 `一键打卡 120ml` 按钮;
- **替代方案考虑**:
- *备选方案 A*:分成两张独立的打卡大卡片(一张亲喂卡片,一张瓶喂卡片)。
*为何否定*:快速打卡区域空间寸土寸金,并列两张卡片会造成界面冗余,且对同一时间只能发生一种喂奶行为的场景而言不够聚焦。
### 2. 看护人角色记忆存储分层设计 (Dual-Layer Preference Storage)
- **选择方案**:
- **L1 本地即时层 (Client LocalStorage)**:键名 `baby_role_preferences`,存储以 `role_name` 为 Key 的偏好映射字典。用户任何模式切换或微调,立即在本地无阻塞写入,并在切换角色时 0ms 瞬间渲染;
- **L2 云端持久层 (Server MySQL)**:在 `family_member` 表追加 `preferences JSON NULL` 字段(并在 `baby_profile` 表追加 `default_config JSON NULL`),通过 RESTful API `PUT /api/families/:familyId/members/:roleName/preferences` 实现多手机端同步。
- **降级与合并机制**:
`当前卡片显示 = 本地该角色专属记忆 ?? 档案该角色推荐值 ?? 宝贝档案全局默认值 ?? 系统兜底值`。
### 3. 亲喂起止时间与数据结构持久化
- **选择方案**:
- `activity_record.activity_type = 'breastfeed'`
- `start_time`:亲喂开始时间(如一键打卡时,`start_time = now - duration`);
- `end_time`:亲喂结束时间(`now` 或人工指定时间);
- `duration_minutes`:总持续时长(分钟);
- `payload`:JSON 扩展存 `{ leftMinutes: 10, rightMinutes: 10, note: "..." }`;
- 看板 KPI 与作息流中:亲喂以“亲喂 20分钟”呈现,瓶喂以“瓶喂 120ml”呈现。
### 4. 通用行为模式向睡眠与尿布拓展
- **睡眠卡片**:支持切换「☀️ 唤醒结算 (进行中计时)」与「🌙 快捷补录 (预设90分钟)」,并记住各角色习惯;
- **尿布卡片**:支持记忆常用性状(如宝爸常换嘘嘘、宝妈常记录便便与性状),点击直接以该角色常用性状入库。
## Risks / Trade-offs
- **[Risk 1: 多设备并发修改角色偏好可能存在覆盖]**
→ **Mitigation**: 偏好属于客户端个性化展示辅助,采用 Last-Write-Wins 策略,且优先尊重当前手机上实际操作者的微调。
- **[Risk 2: 亲喂时间跨天或手工输入不合理]**
→ **Mitigation**: 前端及后端增加时长校验规则(开始时间不得晚于结束时间,单次亲喂时长限制在 1~120 分钟内)。
- **[Risk 3: 数据库旧数据缺少 preferences 字段]**
→ **Mitigation**: 使用 `JSON NULL` 字段,并在服务启动时通过安全 DDL/代码容错处理,未配置时自动回退至默认策略。
## Migration Plan
1. 在 `sql/database.sql` 追加 V1.3.0 变更脚本:为 `family_member` 增加 `preferences JSON`,为 `baby_profile` 增加 `default_config JSON`;
2. 升级后端路由 `records.js`、`families.js`,支持偏好存取及亲喂起止时间计算;
3. 重构前端快速打卡喂奶组件、角色切换事件总线及宝贝档案配置面板;
4. 进行自动化端到端测试与真实浏览器多端验证。
@@ -0,0 +1,65 @@
# Proposal: 喂奶双模式与角色行为记忆偏好系统 (Feeding Modes & Role Preference Memory)
## Why
在新生儿日常照料中,喂奶分为两大截然不同的核心场景:
1. **母乳亲喂 (Breastfeeding)**:以**时间**为核心维度(开始时刻、结束时刻、预设持续时长如 15~20 分钟),支持倒计时/正计时或快速录入与人工修改;
2. **奶瓶喂养 (Bottle Feeding)**:以**容量 (ml)** 为核心维度(如 90ml、120ml 配方奶/储奶瓶喂),辅以快速加减量调整。
同时,家庭多看护人分工差异显著:
- 宝妈通常以**亲喂**为主;
- 宝爸、爷爷奶奶、外公外婆通常以**瓶喂**为主;
- 不同看护人在记录换尿布、安抚睡眠、做抚触/维D等操作时也具有固定的惯用模式。
当前系统缺乏针对亲喂起止时间的精细化配置,且无法记住不同看护人角色的操作偏好。看护人每次切换身份后都需要重新手动选择模式或调整数值,严重增加了夜间或单手抱娃时的记录负担。因此需要建立**喂养双模式**以及**基于看护人角色的行为记忆与配置系统**,并在全行为(喂奶、睡眠、尿布、自定义项)中统一落地。
## What Changes
1. **喂奶双模式与起止时间管理 (Feeding Dual-Mode System)**:
- 快速打卡喂奶卡片支持 **「亲喂」** 与 **「瓶喂」** 一键顶栏 Tab 切换;
- **亲喂模式**:
- 支持记录明确的「开始时间」与「结束时间」;
- 支持在档案/设置中预设默认亲喂时长(例如默认 15 分钟或 20 分钟);
- 点击快速打卡时,可直接按预设时长生成(结束时间 = 开始时间 + 默认时长),亦可在打卡弹窗中人工微调起止时间与时长(左右侧时长);
- 支持计时打卡与即时完成两种方式;
- **瓶喂模式**:
- 以喂奶容量 (ml) 为核心,展示快捷增减量(如 60ml/90ml/120ml/150ml);
- 支持标记奶液类型(配方奶 / 母乳瓶喂)。
2. **角色专属偏好记忆系统 (Per-Role Behavioral Preference Memory)**:
- 每个看护人角色(宝妈、宝爸、爷爷、奶奶、外公、外婆、舅舅、舅妈等)拥有**独立的记忆存储**;
- 当用户在顶部切换当前看护人角色时,系统自动切换并加载该角色专属的偏好:
- **喂奶偏好**:当前角色上次/默认选中的是亲喂还是瓶喂、默认喂养容量或默认亲喂时长;
- **睡眠偏好**:默认睡眠记录方式(计时模式 vs 快速推算预设时长如 90 分钟);
- **尿布偏好**:默认尿布性状(仅嘘嘘、仅便便、嘘嘘+便便);
- **自定义项偏好**:常用私人目标与常用数值;
- 支持本地持久化记忆(LocalStorage)+ 服务端同步兜底。
3. **家庭/宝贝档案全局默认模式与角色配置 (Configuration in Baby Profile)**:
- 在「👶 宝贝档案」设置专区中,提供「喂养模式与行为默认配置」控制台;
- 可配置宝宝全局默认喂奶模式(亲喂 or 瓶喂)及默认参数;
- 可针对各个看护人角色查看并设定专属推荐模式。
4. **全行为统一体验 (Universal Behavior Pattern Alignment)**:
- 将“模式切换 + 默认值预设 + 人工精细修改 + 角色记忆”的设计模式统一推广到睡眠、换尿布、自定义打卡等全行为中。
## Capabilities
### New Capabilities
- `feeding-modes`: 喂养双模式系统(亲喂起止时间/预设时长/人工修改 vs 瓶喂按量)与快速打卡即时切换能力。
- `role-preference-memory`: 看护人角色行为偏好记忆与配置系统(多角色独立记忆、切换角色自动恢复模式、宝贝档案配置全局与角色默认偏好、全行为统一适配)。
### Modified Capabilities
<!-- None -->
## Impact
- **前端影响** (`public/index.html`, `public/app.js`, `public/style.css`):
- 快速打卡喂奶卡片重构为支持亲喂(起止时间/时长)与瓶喂(毫升)双形态切换;
- 角色切换控制器 (`roleModal` 与全局角色状态) 增加角色偏好加载与存储监听;
- 宝贝档案新增喂奶默认模式与看护人偏好配置面板;
- 流水修改弹窗进一步强化亲喂起止时间与左右侧明细编辑。
- **后端影响** (`server/routes/records.js`, `server/routes/families.js`, `server/routes/babies.js`, `server/db.js`):
- `activity_record` 对 `breastfeed` 记录的 `start_time`、`end_time` 与 `duration_minutes` 提供完备支持与校验;
- 支持保存与查询角色偏好设置(可存储在 `family_member` 或独立角色偏好配置中)。
- **兼容性**:100% 向后兼容现有 29 条历史记录与看板聚合逻辑。
@@ -0,0 +1,39 @@
# Spec Delta: 喂养双模式系统 (Feeding Modes)
## Purpose
为新生儿日常记录系统提供亲喂(按起止时间与时长精细记录)与瓶喂(按毫升容量与奶液类型记录)的双形态喂养模式支持,并允许快速打卡即时切换及档案预设默认模式。
## ADDED Requirements
### Requirement: 快速打卡喂养卡片支持亲喂与瓶喂双模式即时切换
系统 SHALL 在快速打卡主页面的喂奶卡片中提供「亲喂」与「瓶喂」双模式 Tab 切换控件。切换时卡片表单与打卡按钮形态即时变换,且不影响其他行为卡片。
#### Scenario: 用户在快速打卡中切换模式
- **WHEN** 用户点击喂奶卡片顶部的「亲喂」或「瓶喂」切换按钮
- **THEN** 喂奶卡片界面在 0.1 秒内切换对应形态:选「瓶喂」时展示毫升加减与容量预设;选「亲喂」时展示起止时刻预估、默认时长及计时/即时完成控件
### Requirement: 亲喂模式支持起止时间与预设时长打卡
系统 SHALL 支持记录亲喂的开始时刻 (`start_time`)、结束时刻 (`end_time`) 以及总持续时长 (`duration_minutes`)。系统允许在快速打卡中一键按默认时长自动补全起止时间,并支持在保存前微调或保存后人工修改。
#### Scenario: 快速打卡亲喂按预设时长即时记录
- **WHEN** 用户在亲喂模式下点击一键打卡按钮(预设时长为 20 分钟)
- **THEN** 系统自动以当前时刻为结束时间,倒推 20 分钟作为开始时间,生成一条 activity_type 为 `breastfeed`、duration_minutes 为 20 的打卡流水,并更新看板喂养时间与已逝时间
#### Scenario: 用户自定义微调亲喂起止时间
- **WHEN** 用户点击亲喂卡片中的「微调时间」或进入流水修改该条记录
- **THEN** 系统弹出时间选择器,允许用户手动调整精确的开始时间、结束时间或左右侧吸吮时长,保存后服务端重新核算该次持续分钟数
### Requirement: 瓶喂模式以容量为核心并支持快速微调
系统 SHALL 支持记录瓶喂的进食容量 (`amountMl`) 与奶液类型 (`formula` 配方奶 或 `breastmilk` 瓶喂母乳),并提供快速步进调整按钮(如 ±10ml、±30ml)及常用量快捷标签。
#### Scenario: 快速打卡瓶喂容量调整
- **WHEN** 用户在瓶喂模式下点击预设容量标签(如 120ml)或步进加减按钮并确认打卡
- **THEN** 系统即刻记录一条 activity_type 为 `bottle` 的流水,记录 payload 包含 `amountMl: 120`,并即时同步累加至今日看板总奶量
### Requirement: 宝贝档案中支持配置喂奶默认模式与默认参数
系统 SHALL 在「宝贝档案」页面中提供喂养模式配置区,允许家长设置宝宝当前阶段的默认喂养方式(亲喂或瓶喂)、默认亲喂单次目标时长(如 15/20/30 分钟)以及默认瓶喂推荐量(如 90/120/150 ml)。
#### Scenario: 家长在档案中更改喂奶默认模式
- **WHEN** 家长在宝贝档案中将默认喂奶模式更改为「亲喂 (默认 20 分钟)」并保存
- **THEN** 快速打卡页面在新会话或未指定角色偏好时,默认将喂奶卡片初始化为「亲喂」,且默认时长显示为 20 分钟
@@ -0,0 +1,38 @@
# Spec Delta: 看护人角色偏好与通用行为记忆系统 (Role Preference Memory)
## Purpose
为系统多看护人角色提供专属的行为操作记忆能力,实现切换角色时自动恢复其惯用模式(如宝妈偏好亲喂、宝爸偏好瓶喂),并将模式切换与默认值配置能力统一推广至睡眠、尿布与自定义指标等全行为模块。
## ADDED Requirements
### Requirement: 每个看护人角色拥有独立的专属行为操作记忆
系统 SHALL 为家庭成员中的每个看护人角色(宝妈、宝爸、爷爷、奶奶、外公、外婆、舅舅、舅妈等)独立存储其行为偏好配置,包括但不限于默认喂奶模式、默认喂奶参数、睡眠记录方式与尿布常用性状。
#### Scenario: 宝妈与宝爸具有不同的喂奶偏好记忆
- **WHEN** 宝妈在快速打卡中切换并使用了「亲喂」,而宝爸切换并使用了「瓶喂 (120ml)」
- **THEN** 系统分别独立持久化保存宝妈偏好为「亲喂」及宝爸偏好为「瓶喂 (120ml)」,两者互不冲突覆盖
### Requirement: 顶部切换角色时即时联动恢复该角色偏好
系统 SHALL 在用户通过顶部 Header 切换当前操作看护人角色时,自动读取并应用该角色最近记忆或预设的偏好,实时更新快速打卡页面的卡片激活形态。
#### Scenario: 切换角色触发卡片状态自动变换
- **WHEN** 当前角色为「宝妈」(偏好亲喂),用户通过顶部角色弹窗切换为「宝爸」(偏好瓶喂)
- **THEN** 快速打卡页面的喂奶卡片自动在无需用户再次点击的情况下,平滑流转为「瓶喂」模式并加载其上次常用的 120ml 配置;换尿布卡片自动加载宝爸常用项
### Requirement: 宝贝档案中支持查看与个性化管理各角色偏好
系统 SHALL 在「宝贝档案」中提供家庭看护人偏好管理界面,允许管理员(如创建者宝妈)集中查看各家庭成员角色的默认习惯,并支持重置或手动指定推荐默认模式。
#### Scenario: 在宝贝档案中为角色指定初始推荐偏好
- **WHEN** 家长在档案偏好列表中将「奶奶」的喂奶模式预设为「瓶喂 100ml」,将「外婆」预设为「瓶喂 120ml」
- **THEN** 系统保存设置,当长辈手机或本机切换至对应角色时,初始直接使用该配置
### Requirement: 通用行为模式全景推广(睡眠、尿布、自定义项)
系统 SHALL 将「模式切换 + 默认值预设 + 人工精细修改 + 角色记忆」的统一设计原则应用到睡眠、换尿布与自定义打卡全场景中:
- 睡眠:支持快速打卡切换「计时安睡」与「补录已睡时长(默认90分钟)」;
- 换尿布:支持快速打卡记忆常用排泄性状(仅嘘嘘、仅便便、嘘嘘+便便);
- 自定义项:记忆常用私人目标与预设打卡数值。
#### Scenario: 睡眠卡片根据角色偏好与状态自动调整
- **WHEN** 用户在睡眠卡片中选择「快捷补录」模式并设定默认补录 90 分钟
- **THEN** 系统记忆该角色的睡眠补录偏好,下次该角色操作时默认呈现 90 分钟快捷记录按钮,并允许一键微调起止时刻
@@ -0,0 +1,30 @@
# Tasks: 喂奶双模式与角色行为记忆偏好系统 (Feeding Modes & Role Preference Memory)
## 1. 数据库与后端服务增强 (Database & Backend Enhancements)
- [x] 1.1 在 `sql/database.sql` 添加 V1.3.0 变更脚本(为 `family_member` 和 `baby_profile` 增补偏好配置支持),并在 `server/db.js` 添加自动容错保障,通过 Node 运行验证数据库字段。
- [x] 1.2 在 `server/routes/records.js` 中完善亲喂起止时间 (`start_time`, `end_time`, `duration_minutes`, `payload`) 校验与入库逻辑,确保看板与流水接口精准解析。
- [x] 1.3 在 `server/routes/families.js` 与 `server/routes/babies.js` 中实现角色偏好与默认配置接口 (`GET/PUT /api/families/:familyId/members/:roleName/preferences` 及宝宝默认配置),通过自动化请求验证读写。
## 2. 前端快速打卡喂奶双模式重构 (Frontend Feeding Dual-Mode)
- [x] 2.1 在 `public/index.html` 中重构喂奶打卡卡片,增加「🤱 亲喂 (时长)」与「🍼 瓶喂 (容量)」分段切换 Tab,构建亲喂起止时间展示、预设时长按钮、微调弹窗及一键打卡按钮。
- [x] 2.2 在 `public/app.js` 实现亲喂打卡交互逻辑(支持按预设时长倒推开始时间一键打卡、微调起止时刻与左右侧时长、即时同步刷新已逝时间与看板)。
- [x] 2.3 在 `public/app.js` 保持并优化瓶喂容量快速加减与奶液类型选择,确保双模式切换平滑无闪烁。
## 3. 看护人角色偏好记忆系统实现 (Role Preference Memory Engine)
- [x] 3.1 在 `public/app.js` 实现客户端角色偏好管理器(基于 `localStorage` 的 `baby_role_preferences` 字典并联动云端同步)。
- [x] 3.2 将角色切换逻辑与偏好引擎绑定:当用户在顶部 Header 切换角色(宝妈、宝爸、爷爷、奶奶等)时,自动瞬间恢复该角色上次使用的喂养模式与参数。
- [x] 3.3 在快速打卡页面中,用户切换模式或调整数值时自动静默写回当前角色的记忆偏好。
## 4. 宝贝档案配置专区与全行为通用推广 (Profile Configuration & Universal Behaviors)
- [x] 4.1 在 `public/index.html` 与 `public/app.js` 的「👶 宝贝档案」中新增「喂养模式与全行为默认配置」管理控制台,支持修改全局默认模式与查看各角色偏好。
- [x] 4.2 将模式切换与记忆设计统一推广至睡眠(唤醒计时 vs 预设补录)与尿布(常用排泄性状)及自定义打卡项。
## 5. 整体联调与规范验证 (Integration & Validation)
- [x] 5.1 扩展 `test_api.js`,增加亲喂起止时间打卡与角色偏好接口的端到端自动化测试并执行通过。
- [x] 5.2 启动本地服务,在浏览器中验证:宝妈切换亲喂记忆、宝爸切换瓶喂记忆、快速打卡即时切换、档案配置生效。
- [x] 5.3 运行 `openspec validate feeding-modes-and-role-preferences` 确保规范验证通过。
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-09-24
@@ -0,0 +1,72 @@
# Design: 家庭备忘待办清单与专注活动倒计时放大模式 (Memo Checklist & Focus Countdown Timers)
## Context
新手父母在照料新生儿时具有多任务并发、注意力高度分散的特点。在实际日常中:
1. 家长常需要记录临时性、非结构化的备忘琐事(如体温复测、煮水消毒、换药洗护等);
2. 在进行母乳亲喂、俯趴锻炼或睡眠陪伴时,家长双手抱娃或守护在侧,手机通常摆放在床头或小茶几上,无法看清普通界面的小字,急需一个可放大、抗干扰的专注倒计时模式。
本设计旨在打造一个**家庭协同轻备忘系统**以及一个**全局沉浸式多活动专注大视窗 (Focus Mode)**。
## Goals / Non-Goals
**Goals:**
1. **轻量清单待办**:提供简便的备忘录入、完成勾选与清理机制,基于家庭 (`family_id`) 跨端共享。
2. **多活动精准倒计时引擎**:支持亲喂(分左右侧倒计时)、俯趴锻炼(预设15m)、抚触等时长活动。
3. **全屏/大视窗沉浸专注模式 (Focus View)**:提供 50px+ 超大字体倒计时、大号触摸操作区(加时、换侧、结算),支持随时最小化至悬浮小窗或恢复全屏。
4. **计时完成后无缝打卡结算**:倒计时完毕或中途结算,直接自动转换填入并提交 `activity_record`,无需家长再次手动输入时长。
**Non-Goals:**
- 不做过于复杂的日程日历与日历 ICS 协议同步(聚焦于家庭日常 1~3 天内的高频轻待办)。
- 不依赖原生 App 后台服务(纯 Web 环境下使用系统可见的 Web Audio 与轻量持久化计时戳,页面切回自动核准时间差)。
## Decisions
### 1. 专注倒计时状态引擎架构 (Global Active Timer Engine)
- **选择方案**:建立全局单例计时器状态 `state.activeTimer`:
```javascript
{
activityType: 'breastfeed', // 'breastfeed' | 'tummy' | 'massage' | 'sleep'
title: '母乳亲喂',
targetMinutes: 20,
startTime: Date.now(),
currentSide: 'left', // 'left' | 'right'
leftSeconds: 600,
rightSeconds: 600,
remainingSeconds: 1200,
isRunning: true,
isExpanded: false
}
```
- **切后台与断电保护机制**:基于绝对时间戳 `startTimestamp` 与 `Date.now()` 进行核算,即使手机息屏或浏览器降频,重新点亮唤醒时时间依然绝对准确。
### 2. 专注全屏大视窗组件 (`#focusModal`)
- **选择方案**:独立遮罩容器,覆盖全屏并采用护眼暗夜/温润深墨绿材质(`bg-stone-900/95`,适合昏暗夜间哺乳):
- 核心展示:巨大环形 SVG 倒计时动效 + 60px 粗体数字 + 醒目操作胶囊(【切换到右侧】、【+5分钟】、【提前完成】、【缩小至卡片】);
- 提示音设计:使用 Web Audio API 原生合成柔和双音节提示音(Bells/Marimba),不依赖外部音频网络文件,100% 离线播放。
### 3. 备忘清单数据表与家庭协同设计
- **选择方案**:新增 `family_memo` 表:
- `id` BIGINT 自增主键;
- `memo_id` VARCHAR(64) 唯一业务ID;
- `family_id` VARCHAR(64) 关联家庭;
- `content` VARCHAR(255) 待办事项内容;
- `due_period` VARCHAR(30) 推荐时段(早晨、下午、睡前、指定时间);
- `is_completed` TINYINT(1) DEFAULT 0;
- `completed_at` DATETIME NULL;
- `created_by` VARCHAR(50) 创建人角色。
- **接口**:标准 RESTful API `GET/POST/PUT/DELETE /api/memos`。
## Risks / Trade-offs
- **[Risk 1: 手机息屏导致 setInterval 停顿]**
→ **Mitigation**: 计时器采用“目标截止绝对时刻 (`targetEndTime = startTime + duration`)”比对,每次 tick 均通过 `Math.max(0, targetEndTime - Date.now())` 实时计算剩余秒数,彻底解决后台暂停漂移问题。
- **[Risk 2: 亲喂单手哺乳时误触关闭全屏]**
→ **Mitigation**: 放大模式中关键操作按键设置防误触尺寸(最小高度 48px),退出全屏按钮置于右上角且二次轻触确认。
## Migration Plan
1. 在 `sql/database.sql` 追加 V1.4.0 变更脚本:创建 `family_memo` 表;
2. 新增服务端路由 `server/routes/memos.js` 并挂载至 `app.js`;
3. 前端实现备忘待办卡片、倒计时引擎与全屏专注放大大视窗;
4. 运行端到端接口验证与多端交互测试。
@@ -0,0 +1,53 @@
# Proposal: 家庭备忘待办清单与专注活动倒计时放大模式 (Memo Checklist & Focus Countdown Timers)
## Why
在新生儿家庭照护中,父母和家人经常面临两大核心痛点:
1. **繁杂琐事与待办备忘极易遗忘**:例如“下午3点测体温”、“给宝宝喂D3滴剂”、“准备45℃温水”、“周五打第二针乙肝疫苗”、“清洗消毒吸奶器”等。目前系统仅有事后打卡记录,缺乏事前与当天的**备忘待办清单 (Todo Checklist)**,长辈与父母之间容易沟通脱节或遗漏;
2. **有时长的照料动作缺乏陪伴式倒计时与沉浸大屏展示**:
- **母乳亲喂**:单侧通常需喂 10~15 分钟,双侧需轮换,母亲单手抱娃哺乳时急需清晰的**倒计时**与**换侧提醒**;
- **俯趴锻炼 (Tummy Time)**、抚触按摩、盆浴等有时长要求的活动同样需要倒计时指引;
- 手机小屏幕在哺乳或照护时难以看清,急需一个**能够一键放大的「专注全屏/沉浸大卡片模式」**,字号硕大、界面纯粹,方便把手机立在床头或桌上,一眼获知当前进行中的活动进度。
## What Changes
1. **家庭智能备忘待办清单 (Family Memo & Checklist)**:
- 在快速打卡主界面与看板中增设「📝 今日备忘待办 (Memo Checklist)」模块;
- 支持家长手动快速输入待办备忘事项(如任务内容、推荐完成时间、指派或关联人);
- 按照清单清单式推进,支持点击一键勾选完成(已完成划线归档)、取消完成及快速删除;
- 支持家庭多成员协同共享,多手机端同步更新。
2. **多活动专注倒计时系统 (Universal Activity Countdown Timers)**:
- **亲喂倒计时 (Breastfeeding Countdown)**:
- 支持设置单次亲喂目标倒计时(如默认 15/20/30 分钟,支持 ±5分钟微调);
- 支持**左右侧乳房切换 (Left/Right Breast Switch)** 分边计时与切换温馨提示;
- 倒计时结束支持柔和提示音与触觉振动,并可直接一键将本次亲喂结算入库;
- **通用计时拓展**:将倒计时推广至俯趴锻炼 (Tummy Time,如 15分钟)、抚触护肤、水浴与自定义计时活动。
3. **专注模式全屏/大卡片放大展示 (Focus Large View Mode)**:
- 当任意活动(亲喂、睡眠、俯趴等)处于进行中倒计时或正计时状态时,界面提供「🔍 放大专注」入口;
- 点击后呼出**大字号极简全屏/沉浸式大视窗**:
- 巨大环形进度与清晰倒计时数字(如 `14:28`);
- 醒目标识当前动作(如 `🤱 正在亲喂 (左侧)` 或 `🐢 正在俯趴锻炼`);
- 提供大触控热区按键:【换侧】、【+5分钟】、【提前完成入库】、【暂停/退出全屏】;
- 适配横屏立放与竖屏床头桌面摆放场景。
## Capabilities
### New Capabilities
- `memo-checklist`: 家庭日常备忘待办清单系统(手动输入清单、状态勾选、待办分类、家庭多端同步)。
- `focus-countdown-timers`: 专注活动倒计时与大屏沉浸放大模式(亲喂分侧倒计时、通用动作计时、全屏/大卡片专注模式、结算自动流水入库)。
### Modified Capabilities
<!-- None -->
## Impact
- **前端架构** (`public/index.html`, `public/app.js`, `public/style.css`):
- 新增全屏专注大视窗组件 (`#focusModal` / `#focusOverlay`);
- 快速打卡喂奶卡片与俯趴卡片集成倒计时控制器与放大按钮;
- 新增备忘清单卡片 (`#memoChecklistCard`) 及输入新增交互。
- **后端架构** (`server/routes/memos.js`, `server/db.js`, `sql/database.sql`):
- 新建 `family_memo` 备忘数据表,支持基于 `family_id` 的待办增删改查;
- 倒计时结算无缝复用已有 `POST /api/records` 入库流程。
- **数据库**:无破坏性变更,向后完全兼容。
@@ -0,0 +1,32 @@
# Spec Delta: 专注活动倒计时与放大模式 (Focus Countdown Timers & Large View)
## Purpose
为有时长属性的照料动作(如亲喂、俯趴锻炼、抚触等)提供高精度倒计时、左右侧切换提示以及一键放大的全屏沉浸专注模式,满足哺乳与陪伴时的大字号远距阅览需求。
## ADDED Requirements
### Requirement: 亲喂活动支持分侧倒计时与左右轮换
系统 SHALL 支持为亲喂活动开启目标倒计时(如默认 20 分钟),并在界面清晰呈现剩余分钟秒数与当前喂哺侧别(左侧 / 右侧)。系统支持用户在哺乳中途一键切换喂哺侧,并分别累计左右侧实际吸吮分钟数。
#### Scenario: 开启亲喂倒计时并换侧
- **WHEN** 宝妈点击「开启亲喂倒计时 (20分钟)」,并在喂了 10 分钟后点击「切换到右侧」
- **THEN** 界面左侧计时停止在 10 分钟,右侧计时自动开始倒计剩余 10 分钟,并清晰标识当前为右侧
### Requirement: 通用时长活动统一支持倒计时
系统 SHALL 为所有具备 duration 属性的日常保健与习惯活动(如俯趴锻炼 Tummy Time、抚触按摩、温水洗浴)提供统一的倒计时触发入口,支持预设推荐时长(如 15 分钟)并在倒计时完毕时提供完成提示。
#### Scenario: 开启俯趴锻炼倒计时
- **WHEN** 用户在俯趴打卡项点击「开始 15 分钟倒计时」
- **THEN** 系统启动 15 分钟动态倒数,进度条同步按比例缩减,到达 00:00 时发出轻柔提醒并提示用户完成打卡
### Requirement: 当前操作倒计时支持放大全屏专注模式
系统 SHALL 在活动计时进行中提供「🔍 放大专注」入口。点击后以全屏/沉浸式大卡片形式呈现当前活动,展示超大号倒计时数字、环形动态进度、大按钮操作区(暂停/继续、加时、提前完成),屏蔽其他无关界面元素的视觉干扰。
#### Scenario: 用户在哺乳或俯趴时放大专注视窗
- **WHEN** 用户在进行中倒计时界面点击「放大专注」按钮
- **THEN** 系统弹出覆盖全屏的大字号专注面板,倒计时字号提升至 48px 以上,支持手机横屏与竖屏立放远距清晰可视
#### Scenario: 从放大模式直接结算完成打卡
- **WHEN** 用户在专注全屏模式下点击「完成本次活动并打卡」
- **THEN** 系统自动采集本次实际发生时长、起止时间与操作人,直接将流水入库并关闭全屏,自动刷新今日看板
@@ -0,0 +1,35 @@
# Spec Delta: 家庭日常备忘待办清单 (Memo Checklist)
## Purpose
为新生儿看护家庭提供事前与日常照料的备忘清单管理能力,支持手动快速添加备忘、勾选完成与删除,并实现全家看护团队多端同步流转。
## ADDED Requirements
### Requirement: 用户可以手动添加备忘待办事项
系统 SHALL 提供快捷输入界面,允许用户输入备忘标题、选择可选提醒时段(如早晨、下午、睡前)及关联看护人,并保存至当前活跃家庭。
#### Scenario: 手动新增备忘事项成功
- **WHEN** 用户在备忘区域输入「带宝宝去社区医院打疫苗」并点击添加
- **THEN** 系统立即在备忘列表中新增一条待办事项,状态为未完成,并在 1 秒内持久化存入服务端与本地缓存
### Requirement: 按照清单实现勾选与状态切换
系统 SHALL 支持用户以 Checkbox 形式逐项勾选待办,勾选后视觉展示为已完成(划线或淡出至已完成分组),并支持反悔再次点击取消完成。
#### Scenario: 勾选完成某项备忘
- **WHEN** 用户点击备忘事项「给宝宝补充维D3」左侧的勾选框
- **THEN** 该项状态变更为已完成,字体呈现完成划线效果,并更新未完成待办计数
### Requirement: 备忘清单支持快速清理与删除
系统 SHALL 允许用户对单条备忘进行左滑/点击垃圾桶删除,或一键清除所有已完成的待办事项。
#### Scenario: 删除单条备忘
- **WHEN** 用户点击某条已失效备忘右侧的删除按钮并确认
- **THEN** 系统从列表中移除该项,并在数据库中执行软删除或物理删除
### Requirement: 家庭看护成员多端共享备忘清单
系统 SHALL 保证备忘清单基于 `family_id` 维护,任意家庭成员(宝妈、宝爸等)新增或勾选备忘后,其他手机切回或刷新时自动同步呈现最新清单状态。
#### Scenario: 跨设备同步待办状态
- **WHEN** 宝爸在手机上勾选了「已冲洗并消毒奶瓶」
- **THEN** 宝妈手机在下一次自动刷新或加载看板时,该项同样显示为已完成状态
@@ -0,0 +1,29 @@
# Tasks: 家庭备忘待办清单与专注活动倒计时放大模式 (Memo Checklist & Focus Countdown Timers)
## 1. 备忘清单数据库与服务端路由 (Database & Backend Memos)
- [x] 1.1 在 `sql/database.sql` 追加 V1.4.0 脚本(创建 `family_memo` 表并在 `server/db.js` 完成初始化),通过测试验证表创建与索引配置。
- [x] 1.2 创建 `server/routes/memos.js` 并挂载至 `server/app.js`,实现 `GET/POST/PUT/DELETE /api/memos` 完整待办 CRUD 接口,通过自动化脚本验证。
## 2. 前端家庭备忘待办清单实现 (Frontend Memo Checklist)
- [x] 2.1 在 `public/index.html` 中增加「📝 今日备忘待办清单」卡片组件(含快速输入框、待办项列表、完成划线与删除操作)。
- [x] 2.2 在 `public/app.js` 实现备忘清单的增删改查交互、完成状态勾选、计数提示与家庭成员共享同步。
## 3. 多活动倒计时核心引擎 (Activity Countdown Engine)
- [x] 3.1 在 `public/app.js` 封装基于绝对时间戳的单例倒计时引擎(支持防息屏漂移、暂停/继续、加时、倒计时完毕柔和音频提示)。
- [x] 3.2 在喂奶卡片中实现亲喂倒计时触发器,支持目标时长倒数、左右侧乳房一键切换与分侧时长累计。
- [x] 3.3 为俯趴锻炼 (Tummy Time) 及其他时长保健活动接入通用倒计时入口。
## 4. 全屏沉浸专注大视窗 (Focus Large View Mode)
- [x] 4.1 在 `public/index.html` 构建全屏沉浸专注大视窗容器(`#focusModal`),包含大号环形进度、50px+ 倒计时字体、左右侧指示及大号操作按钮。
- [x] 4.2 在 `public/app.js` 实现「🔍 放大专注」与「缩小恢复」双向平滑流转逻辑,确保全屏模式下支持换侧、加时与一键打卡结算入库。
- [x] 4.3 在 `public/style.css` 补充专注模式的暗夜微光动效、环形进度动画与夜间护眼配色。
## 5. 联调测试与规范校验 (Integration & Validation)
- [x] 5.1 扩展 `test_api.js`,加入备忘待办全生命周期(创建、勾选、删除)与计时入库的自动化测试并验证通过。
- [x] 5.2 在 Chrome 浏览器中测试亲喂倒计时、放大全屏专注模式、左右换侧、备忘清单勾选并结算打卡。
- [x] 5.3 运行 `openspec validate memo-checklist-and-focus-timers` 确保规范验证通过。
+1303 -28
View File
File diff suppressed because it is too large. Load diff
+597 -95
View File
@@ -25,47 +25,47 @@
</script> </script>
<link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="style.css">
</head> </head>
<body class="bg-slate-100 text-slate-800 antialiased select-none pb-24 md:pb-8 min-h-screen"> <body class="text-stone-800 antialiased select-none pb-28 md:pb-8 min-h-screen">
<!-- Responsive App Container (手机与电脑自适应) --> <!-- Responsive App Container (温暖治愈微拟物卡片外壳) -->
<div id="app" class="w-full max-w-5xl mx-auto min-h-screen bg-slate-50/70 shadow-xl relative flex flex-col transition-all duration-300"> <div id="app" class="w-full max-w-5xl mx-auto min-h-screen md:min-h-[92vh] bg-white/95 backdrop-blur-2xl shadow-soft-lg md:rounded-[36px] md:my-5 md:border md:border-stone-200/60 relative flex flex-col transition-all duration-300 overflow-hidden">
<!-- TOP HEADER: WARM, ELEGANT & USER-FOCUSED (自适应单行紧凑设计,专注宝宝与看护人) --> <!-- TOP HEADER: WARM, ELEGANT & USER-FOCUSED (自适应单行紧凑设计,专注宝宝与看护人) -->
<header class="sticky top-0 z-40 bg-white/95 backdrop-blur-md border-b border-slate-200/80 px-4 md:px-6 py-2.5 shadow-2xs"> <header class="sticky top-0 z-40 bg-white/90 backdrop-blur-md border-b border-stone-200/60 px-4 md:px-6 py-2.5 shadow-2xs">
<div class="flex items-center justify-between"> <div class="flex items-center justify-between">
<!-- 左侧:宝宝身份与成长阶段 (点击可进入档案或切换宝宝) --> <!-- 左侧:宝宝身份与成长阶段 (点击可进入档案或切换宝宝) -->
<button id="babySelectorBtn" class="flex items-center space-x-2.5 active:scale-95 transition text-left group"> <button id="babySelectorBtn" class="flex items-center space-x-2.5 active:scale-95 transition text-left group">
<div id="babyAvatarDot" class="w-9 h-9 rounded-full bg-blue-500 text-white font-extrabold text-sm flex items-center justify-center shadow-xs border-2 border-white ring-1 ring-slate-100"> <div id="babyAvatarDot" class="w-9 h-9 rounded-full bg-gradient-to-tr from-amber-400 to-orange-400 text-white font-black text-sm flex items-center justify-center shadow-xs border-2 border-white ring-1 ring-amber-100">
嘟 嘟
</div> </div>
<div> <div>
<div class="flex items-center space-x-1.5"> <div class="flex items-center space-x-1.5">
<span id="currentBabyName" class="font-extrabold text-sm text-slate-900 group-hover:text-indigo-600 transition">嘟嘟</span> <span id="currentBabyName" class="font-black text-sm text-stone-900 group-hover:text-amber-600 transition">嘟嘟</span>
<span class="text-[10px] text-slate-400 group-hover:text-indigo-500 transition">▼</span> <span class="text-[10px] text-stone-400 group-hover:text-amber-500 transition">▼</span>
</div> </div>
<div class="flex items-center space-x-1 mt-0.5"> <div class="flex items-center space-x-1 mt-0.5">
<span id="headerFamilyNameBadge" class="text-[9px] font-bold text-indigo-700 bg-indigo-50 border border-indigo-200/80 px-1.5 py-0.2 rounded-md truncate max-w-[90px]" title="点击管理或切换家庭">🏡 小花园之家</span> <span id="headerFamilyNameBadge" class="text-[9px] font-bold text-amber-800 bg-amber-50 border border-amber-200/80 px-1.5 py-0.2 rounded-md truncate max-w-[90px]" title="点击管理或切换家庭">🏡 小花园之家</span>
<span id="currentBabyAge" class="text-[10px] text-slate-400 font-medium">42天</span> <span id="currentBabyAge" class="text-[10px] text-stone-400 font-medium">42天</span>
</div> </div>
</div> </div>
</button> </button>
<!-- 中间:桌面端专属主导航条 (md:flex 展现,移动端隐藏) --> <!-- 中间:桌面端专属主导航条 (md:flex 展现,移动端隐藏) -->
<nav id="desktopNavTabs" class="hidden md:flex items-center space-x-1 bg-slate-100/90 p-1 rounded-2xl border border-slate-200/70"> <nav id="desktopNavTabs" class="hidden md:flex items-center space-x-1 bg-stone-100/90 p-1 rounded-2xl border border-stone-200/70">
<button class="tab-btn active px-4 py-1.5 rounded-xl text-xs text-indigo-600 font-bold bg-white shadow-2xs transition flex items-center space-x-1" data-target="quick"> <button class="tab-btn active px-4 py-1.5 rounded-xl text-xs text-amber-900 font-bold bg-white shadow-2xs transition flex items-center space-x-1" data-target="quick">
<span>⚡</span> <span>⚡</span>
<span>快速打卡</span> <span>快速打卡</span>
</button> </button>
<button class="tab-btn px-4 py-1.5 rounded-xl text-xs text-slate-500 hover:text-slate-800 font-semibold transition flex items-center space-x-1" data-target="dashboard"> <button class="tab-btn px-4 py-1.5 rounded-xl text-xs text-stone-500 hover:text-stone-800 font-semibold transition flex items-center space-x-1" data-target="dashboard">
<span>📊</span> <span>📊</span>
<span>统计看板</span> <span>统计看板</span>
</button> </button>
<button class="tab-btn px-4 py-1.5 rounded-xl text-xs text-slate-500 hover:text-slate-800 font-semibold transition flex items-center space-x-1" data-target="guides"> <button class="tab-btn px-4 py-1.5 rounded-xl text-xs text-stone-500 hover:text-stone-800 font-semibold transition flex items-center space-x-1" data-target="guides">
<span>📖</span> <span>📖</span>
<span>护理视频</span> <span>护理视频</span>
</button> </button>
<button class="tab-btn px-4 py-1.5 rounded-xl text-xs text-slate-500 hover:text-slate-800 font-semibold transition flex items-center space-x-1" data-target="profile"> <button class="tab-btn px-4 py-1.5 rounded-xl text-xs text-stone-500 hover:text-stone-800 font-semibold transition flex items-center space-x-1" data-target="profile">
<span>👶</span> <span>👶</span>
<span>宝贝档案</span> <span>宝贝档案</span>
</button> </button>
@@ -74,17 +74,17 @@
<!-- 右侧:看护人称谓与快捷流水入口 --> <!-- 右侧:看护人称谓与快捷流水入口 -->
<div class="flex items-center space-x-2"> <div class="flex items-center space-x-2">
<!-- 身份称呼:表明当前记录人,点击自由切换宝妈/宝爸/月嫂 --> <!-- 身份称呼:表明当前记录人,点击自由切换宝妈/宝爸/月嫂 -->
<button id="roleSelectorBtn" class="flex items-center space-x-1.5 bg-slate-100 hover:bg-slate-200 active:scale-95 transition px-3 py-1.5 rounded-full text-xs font-bold text-slate-700 shadow-2xs" title="点击切换当前记录身份"> <button id="roleSelectorBtn" class="flex items-center space-x-1.5 bg-stone-100 hover:bg-stone-200 active:scale-95 transition px-3 py-1.5 rounded-full text-xs font-bold text-stone-700 shadow-2xs" title="点击切换当前记录身份">
<span id="currentOperatorIcon">👩</span> <span id="currentOperatorIcon">👩</span>
<span id="currentOperatorName">宝妈</span> <span id="currentOperatorName">宝妈</span>
<span class="text-[10px] text-slate-400">▼</span> <span class="text-[10px] text-stone-400">▼</span>
</button> </button>
<!-- 快捷流水气泡入口:随时查看今日明细 --> <!-- 快捷流水气泡入口:随时查看今日明细 -->
<button onclick="openTimelineModal()" class="flex items-center space-x-1 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 active:scale-95 transition px-2.5 py-1.5 rounded-full text-xs font-bold border border-indigo-200/60 shadow-2xs" title="查看今日所有操作流水"> <button onclick="openTimelineModal()" class="flex items-center space-x-1 bg-amber-50 hover:bg-amber-100 text-amber-800 active:scale-95 transition px-2.5 py-1.5 rounded-full text-xs font-bold border border-amber-200/60 shadow-2xs" title="查看今日所有操作流水">
<span>📋</span> <span>📋</span>
<span>流水</span> <span>流水</span>
<span id="headerTimelineCountBadge" class="bg-indigo-600 text-white text-[10px] px-1.5 py-0.2 rounded-full min-w-[16px] text-center">0</span> <span id="headerTimelineCountBadge" class="bg-amber-500 text-white text-[10px] px-1.5 py-0.2 rounded-full min-w-[16px] text-center">0</span>
</button> </button>
</div> </div>
@@ -108,123 +108,207 @@
<!-- 核心高频打卡卡片群 (手机单列垂直流,电脑端三列并排大盘) --> <!-- 核心高频打卡卡片群 (手机单列垂直流,电脑端三列并排大盘) -->
<div class="grid grid-cols-1 md:grid-cols-3 gap-3.5"> <div class="grid grid-cols-1 md:grid-cols-3 gap-3.5">
<!-- 1. 🍼 喂养打卡卡片 (距上次喂奶已逝时间直接融合) --> <!-- 1. 🍼 喂养打卡卡片 (支持 🤱 亲喂按时长与 🍼 瓶喂按容量 双模式切换) -->
<div class="bg-white border border-amber-200 rounded-3xl p-4 shadow-xs space-y-2.5 flex flex-col justify-between"> <div id="cardFeeding" class="bg-white border border-amber-200/90 rounded-3xl p-4 shadow-soft space-y-2 flex flex-col justify-between transition-all">
<div> <div>
<div class="flex items-center justify-between"> <div class="flex items-center justify-between gap-1">
<div class="flex items-center space-x-2.5"> <div class="flex items-center space-x-2 min-w-0">
<span class="text-2xl p-2 bg-amber-500 text-white rounded-2xl shadow-xs">🍼</span> <span id="feedingCardIcon" class="text-xl p-2 bg-amber-500 text-white rounded-2xl shadow-xs shrink-0">🍼</span>
<div> <div class="min-w-0">
<div class="flex items-center space-x-2"> <div class="flex items-center space-x-1.5">
<span class="font-black text-slate-900 text-sm">喂奶打卡</span> <span id="feedingCardTitle" class="font-black text-stone-900 text-sm whitespace-nowrap">喂奶打卡</span>
<button class="text-[10px] font-bold text-amber-700 bg-amber-100 hover:bg-amber-200 px-2 py-0.5 rounded-full" onclick="openCareGuideModal('guide-bottle')">💡手法</button> <button class="w-5 h-5 rounded-full bg-amber-100/90 hover:bg-amber-200 text-amber-800 flex items-center justify-center text-[11px] transition shrink-0 active:scale-90" onclick="openCareGuideModal('guide-bottle')" title="查看喂奶规范手法视频">💡</button>
</div> </div>
<div id="feedLastSummary" class="text-[11px] text-slate-500 mt-0.5">上次: --</div> <div id="feedLastSummary" class="text-[11px] text-stone-500 mt-0.5 truncate">上次: --</div>
</div> </div>
</div> </div>
<!-- 距上次喂奶已逝时间 --> <!-- 距上次喂奶已逝时间 -->
<div class="text-right"> <div class="text-right shrink-0">
<span id="lastFeedingTime" class="text-xs font-black text-amber-700 bg-amber-50 border border-amber-200/80 px-2.5 py-1 rounded-xl">距上次 --</span> <span id="lastFeedingTime" class="text-xs font-black text-amber-800 bg-amber-50 border border-amber-200/80 px-2 py-1 rounded-xl whitespace-nowrap inline-block">距上次 --</span>
</div> </div>
</div> </div>
<!-- 亲喂 vs 瓶喂 分段模式切换 Tab (各角色自动记忆偏好) -->
<div class="flex p-0.5 bg-amber-100/70 rounded-xl text-xs font-bold mt-2 mb-1">
<button id="btnModeBreastfeed" class="flex-1 py-1.5 rounded-lg transition text-stone-600 flex items-center justify-center space-x-1 whitespace-nowrap font-bold" onclick="setFeedingMode('breastfeed')">
<span>🤱 亲喂 (时长)</span>
</button>
<button id="btnModeBottle" class="flex-1 py-1.5 rounded-lg transition bg-white text-amber-900 shadow-2xs flex items-center justify-center space-x-1 whitespace-nowrap font-bold" onclick="setFeedingMode('bottle')">
<span>🍼 瓶喂 (容量)</span>
</button>
</div>
<!-- 觅食/超时间隔温和提示 (仅超时时显示) --> <!-- 觅食/超时间隔温和提示 (仅超时时显示) -->
<div id="feedingAlertBanner" class="hidden text-[11px] text-amber-900 bg-amber-100 border border-amber-300/80 px-3 py-1.5 rounded-xl font-bold flex items-center justify-between mt-2"> <div id="feedingAlertBanner" class="hidden text-[11px] text-amber-900 bg-amber-100 border border-amber-300/80 px-3 py-1.5 rounded-xl font-bold flex items-center justify-between mt-1.5">
<span>⏰ 已达月龄推荐喂养间隔,可留意寻乳/觅食信号</span> <span>⏰ 已达月龄推荐喂养间隔,可留意寻乳/觅食信号</span>
</div> </div>
</div> </div>
<!-- 快捷操作按键群 --> <!-- 模式 A: 🍼 瓶喂操作区 (纯极速秒记按键) -->
<div class="flex items-center space-x-1.5 pt-2"> <div id="feedBottleSection" class="pt-1">
<button class="flex-1 bg-amber-500 hover:bg-amber-600 active:scale-98 text-white font-extrabold text-xs py-3 rounded-2xl shadow-xs transition flex items-center justify-center space-x-1" onclick="quickLogBottleDefault()"> <button class="w-full bg-gradient-to-r from-amber-500 to-amber-600 hover:from-amber-600 hover:to-amber-700 active:scale-98 text-white font-black text-xs sm:text-sm py-3.5 rounded-2xl shadow-xs transition flex items-center justify-center space-x-1.5 whitespace-nowrap cursor-pointer" onclick="quickLogBottleDefault()">
<span>秒记</span> <span>🍼 秒记瓶喂</span>
<span id="btnLastBottleAmount" class="underline decoration-white/60">120ml</span> <span id="btnLastBottleAmount" class="underline decoration-white/60 font-mono text-sm">120ml</span>
</button> </button>
<button class="bg-amber-100 hover:bg-amber-200 active:scale-95 text-amber-800 font-bold text-xs px-2.5 py-3 rounded-2xl transition" onclick="openBottleAdjustModal()" title="自定义本次冲奶量"> </div>
改量
<!-- 模式 B: 🤱 亲喂操作区 (纯极速打卡与倒计时按键) -->
<div id="feedBreastfeedSection" class="hidden pt-1">
<div class="flex items-center space-x-2">
<button id="btnStartBfTimer" class="flex-1 bg-gradient-to-r from-rose-500 to-pink-500 hover:from-rose-600 hover:to-pink-600 active:scale-98 text-white font-black text-xs sm:text-sm py-3.5 rounded-2xl shadow-xs transition flex items-center justify-center space-x-1.5 whitespace-nowrap cursor-pointer" onclick="handleStartBfCountdown()">
<span>⏱️ 亲喂倒计时</span>
<span id="quickBfDurationText" class="opacity-90 underline decoration-white/60 font-mono text-xs">20m</span>
</button> </button>
<button class="bg-rose-50 hover:bg-rose-100 active:scale-95 text-rose-700 font-bold text-xs px-3 py-3 rounded-2xl border border-rose-200 transition" onclick="handleQuickBreastfeed()" title="亲喂双侧时长"> <button id="btnBfFocusExpand" class="hidden bg-rose-100 hover:bg-rose-200 text-rose-800 font-bold text-xs px-3 py-3.5 rounded-2xl transition shrink-0 whitespace-nowrap cursor-pointer" onclick="openFocusModal('breastfeed')" title="放大全屏专注模式">
🤱 亲喂 🔍 专注
</button>
<button class="bg-rose-100 hover:bg-rose-200 active:scale-95 text-rose-800 font-bold text-xs sm:text-sm px-4 py-3.5 rounded-2xl transition shrink-0 whitespace-nowrap cursor-pointer" onclick="quickLogBreastfeedDefault()" title="以当前时刻倒推默认时长直接秒记">
<span>⚡ 秒记</span>
<span id="quickBfSecText" class="opacity-90 font-mono text-xs">20m</span>
</button> </button>
</div> </div>
</div> </div>
<!-- 2. 😴 睡眠打卡卡片 (当前状态与已逝时长直接融合) -->
<div id="btnSleepCard" class="bg-white border border-purple-200 rounded-3xl p-4 shadow-xs space-y-2.5 flex flex-col justify-between">
<div>
<div class="flex items-center justify-between">
<div class="flex items-center space-x-2.5">
<span id="sleepToggleIcon" class="text-2xl p-2 bg-purple-600 text-white rounded-2xl shadow-xs">😴</span>
<div>
<div class="flex items-center space-x-2">
<span id="sleepCardTitle" class="font-black text-slate-900 text-sm">睡眠打卡</span>
<button class="text-[10px] font-bold text-purple-700 bg-purple-100 hover:bg-purple-200 px-2 py-0.5 rounded-full" onclick="openCareGuideModal('guide-sleep')">💡手法</button>
</div> </div>
<div id="currentSleepStateDetail" class="text-[11px] text-slate-500 mt-0.5">宝宝清醒中</div>
<!-- 2. 😴 睡眠打卡卡片 (支持倒计时、已安睡时长感知与放大全屏专注) -->
<div id="btnSleepCard" class="bg-white border border-purple-200/90 rounded-3xl p-4 shadow-soft space-y-2 flex flex-col justify-between transition-all">
<div>
<div class="flex items-center justify-between gap-1">
<div class="flex items-center space-x-2 min-w-0">
<span id="sleepToggleIcon" class="text-xl p-2 bg-purple-600 text-white rounded-2xl shadow-xs shrink-0">😴</span>
<div class="min-w-0">
<div class="flex items-center space-x-1.5">
<span id="sleepCardTitle" class="font-black text-stone-900 text-sm whitespace-nowrap">睡眠打卡</span>
<button class="w-5 h-5 rounded-full bg-purple-100/90 hover:bg-purple-200 text-purple-700 flex items-center justify-center text-[11px] transition shrink-0 active:scale-90" onclick="openCareGuideModal('guide-sleep')" title="查看睡眠安抚规范手法视频">💡</button>
</div>
<div id="currentSleepStateDetail" class="text-[11px] text-stone-500 mt-0.5 truncate">宝宝清醒中</div>
</div> </div>
</div> </div>
<!-- 当前状态与已逝时长 --> <!-- 当前状态与已逝时长 -->
<div class="text-right"> <div class="text-right flex items-center space-x-1.5 shrink-0">
<span id="currentSleepStateTitle" class="text-xs font-black text-purple-700 bg-purple-50 border border-purple-200/80 px-2.5 py-1 rounded-xl">清醒 35分钟</span> <span id="currentSleepStateTitle" class="text-xs font-black text-purple-700 bg-purple-50 border border-purple-200/80 px-2 py-1 rounded-xl whitespace-nowrap inline-block">清醒中</span>
</div> <!-- 正在睡觉时提供放大专注大视窗入口 -->
<button id="btnSleepFocusExpand" class="hidden text-xs text-purple-700 bg-purple-100 hover:bg-purple-200 px-2 py-1 rounded-xl font-bold whitespace-nowrap" onclick="openFocusModal('sleep')" title="放大全屏夜间睡眠专注大屏">
🔍 专注
</button>
</div> </div>
</div> </div>
<!-- 一键状态切换大按键 --> <!-- 睡眠规律建议标签 -->
<div class="pt-2"> <div class="flex items-center justify-between text-xs font-semibold px-2.5 py-1.5 bg-purple-50/70 rounded-xl border border-purple-100/70 text-purple-900 mt-2 mb-1">
<button id="btnSleepToggle" class="w-full bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-700 hover:to-indigo-700 active:scale-98 text-white font-extrabold text-xs py-3.5 rounded-2xl shadow-md transition flex items-center justify-center space-x-2" onclick="handleQuickSleepToggle()"> <span class="flex items-center space-x-1.5"><span class="text-sm">💤</span><span>建议小睡 1.5~2小时</span></span>
<span id="sleepToggleActionText">🌙 宝宝睡下了 (点击开始计时)</span> <span class="text-[10px] text-purple-600 font-bold">规律作息培养</span>
</div>
</div>
<!-- 一键状态切换大按键与快捷补录 -->
<div class="flex items-center space-x-1.5 pt-1">
<button id="btnSleepToggle" class="flex-1 bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-700 hover:to-indigo-700 active:scale-98 text-white font-black text-xs py-3 rounded-2xl shadow-xs transition flex items-center justify-center space-x-2 whitespace-nowrap" onclick="handleQuickSleepToggle()">
<span id="sleepToggleActionText">🌙 宝宝睡下了 (开始计时)</span>
</button>
<button class="bg-purple-100 hover:bg-purple-200 active:scale-95 text-purple-800 font-bold text-xs px-2.5 py-3 rounded-2xl transition shrink-0 whitespace-nowrap" onclick="openRetroRecordModal()" title="补录既往睡眠记录">
+补录
</button> </button>
</div> </div>
</div> </div>
<!-- 3. 💧 换尿布卡片 (距上次更换已逝时间直接融合) --> <!-- 3. 💧 换尿布卡片 (距上次更换已逝时间直接融合) -->
<div class="bg-white border border-sky-200 rounded-3xl p-4 shadow-xs space-y-2.5 flex flex-col justify-between"> <div class="bg-white border border-sky-200/90 rounded-3xl p-4 shadow-soft space-y-2 flex flex-col justify-between transition-all">
<div> <div>
<div class="flex items-center justify-between"> <div class="flex items-center justify-between gap-1">
<div class="flex items-center space-x-2.5"> <div class="flex items-center space-x-2 min-w-0">
<span class="text-2xl p-2 bg-sky-500 text-white rounded-2xl shadow-xs">💧</span> <span class="text-xl p-2 bg-sky-500 text-white rounded-2xl shadow-xs shrink-0">💧</span>
<div> <div class="min-w-0">
<div class="flex items-center space-x-2"> <div class="flex items-center space-x-1.5">
<span class="font-black text-slate-900 text-sm">换尿布打卡</span> <span class="font-black text-stone-900 text-sm whitespace-nowrap">换尿布打卡</span>
<button class="text-[10px] font-bold text-sky-700 bg-sky-100 hover:bg-sky-200 px-2 py-0.5 rounded-full" onclick="openCareGuideModal('guide-diaper')">💡手法</button> <button class="w-5 h-5 rounded-full bg-sky-100/90 hover:bg-sky-200 text-sky-700 flex items-center justify-center text-[11px] transition shrink-0 active:scale-90" onclick="openCareGuideModal('guide-diaper')" title="查看换尿布护臀规范手法视频">💡</button>
</div> </div>
<div id="lastDiaperDetail" class="text-[11px] text-slate-500 mt-0.5">上次: --</div> <div id="lastDiaperDetail" class="text-[11px] text-stone-500 mt-0.5 truncate">上次: --</div>
</div> </div>
</div> </div>
<!-- 距上次更换已逝时间 --> <!-- 距上次更换已逝时间 -->
<div class="text-right"> <div class="text-right shrink-0">
<span id="lastDiaperTime" class="text-xs font-black text-sky-700 bg-sky-50 border border-sky-200/80 px-2.5 py-1 rounded-xl">距上次 --</span> <span id="lastDiaperTime" class="text-xs font-black text-sky-700 bg-sky-50 border border-sky-200/80 px-2 py-1 rounded-xl whitespace-nowrap inline-block">距上次 --</span>
</div>
</div> </div>
</div> </div>
<!-- 双大按键并排一触即发 --> <!-- 护臀干爽建议 -->
<div class="grid grid-cols-2 gap-2 pt-2"> <div class="flex items-center justify-between text-xs font-semibold px-2.5 py-1.5 bg-sky-50/70 rounded-xl border border-sky-100/70 text-sky-900 mt-2 mb-1">
<button class="bg-sky-500 hover:bg-sky-600 active:scale-98 text-white font-extrabold text-xs py-3 rounded-2xl shadow-xs transition flex items-center justify-center space-x-1.5" onclick="handleQuickDiaper('pee')"> <span class="flex items-center space-x-1.5"><span class="text-sm">🛡️</span><span>勤换护臀 · 保持干爽</span></span>
<span>💧</span> <span class="text-[10px] text-sky-600 font-bold">即触即记</span>
<span>嘘嘘 (纯小便)</span> </div>
</div>
<!-- 三大快捷按键一触即发 -->
<div class="grid grid-cols-3 gap-2 pt-1">
<button class="bg-sky-500 hover:bg-sky-600 active:scale-98 text-white font-black text-xs py-3 rounded-2xl shadow-xs transition flex items-center justify-center space-x-1 whitespace-nowrap cursor-pointer" onclick="handleQuickDiaper('pee')">
<span>💧 纯嘘嘘</span>
</button> </button>
<button class="bg-emerald-600 hover:bg-emerald-700 active:scale-98 text-white font-extrabold text-xs py-3 rounded-2xl shadow-xs transition flex items-center justify-center space-x-1.5" onclick="handleQuickDiaper('poop')"> <button class="bg-emerald-600 hover:bg-emerald-700 active:scale-98 text-white font-black text-xs py-3 rounded-2xl shadow-xs transition flex items-center justify-center space-x-1 whitespace-nowrap cursor-pointer" onclick="handleQuickDiaper('poop')">
<span>💩</span> <span>💩 纯便便</span>
<span>便便 (大便)</span> </button>
<button class="bg-gradient-to-r from-teal-500 to-cyan-600 hover:from-teal-600 hover:to-cyan-700 active:scale-98 text-white font-black text-xs py-3 rounded-2xl shadow-xs transition flex items-center justify-center space-x-1 whitespace-nowrap cursor-pointer" onclick="handleQuickDiaper('both')">
<span>✨ 嘘+便</span>
</button> </button>
</div> </div>
</div> </div>
</div> </div>
<!-- 4. ✨ 日常保健与私人目标一键打卡 (自适应网格) --> <!-- 4. 📝 今日家庭备忘待办清单 (MEMO CHECKLIST - 家人协同/勾选即完成) -->
<div class="bg-white border border-slate-200/90 rounded-3xl p-4 shadow-2xs space-y-2.5"> <div id="memoChecklistCard" class="bg-white border border-stone-200/80 rounded-3xl p-4 shadow-soft space-y-3">
<div class="flex items-center justify-between">
<div class="flex items-center space-x-2">
<span class="text-lg p-1.5 bg-indigo-50 text-indigo-600 rounded-xl">📝</span>
<div>
<div class="flex items-center space-x-2">
<h3 class="font-black text-sm text-stone-900">今日家庭备忘待办清单</h3>
<span id="memoCountBadge" class="text-[10px] font-bold text-indigo-700 bg-indigo-50 px-2 py-0.5 rounded-full border border-indigo-100">0 项待办</span>
</div>
<p class="text-[11px] text-stone-400">家人协同清单 · 照料事项防遗漏 · 勾选划线完成</p>
</div>
</div>
<div class="flex items-center space-x-1.5 shrink-0">
<button type="button" class="text-xs bg-indigo-50 hover:bg-indigo-100 text-indigo-700 font-bold px-2.5 py-1 rounded-xl transition flex items-center space-x-1 cursor-pointer active:scale-95" onclick="openMemoHistoryModal()" title="查看并维护全量历史备忘清单">
<span>📋</span>
<span>历史备忘</span>
</button>
<button type="button" class="text-xs text-indigo-600 hover:text-indigo-800 font-bold px-1.5 py-1 cursor-pointer" onclick="focusMemoInput()">+ 添加</button>
</div>
</div>
<!-- 快捷输入行 -->
<form id="memoAddForm" onsubmit="handleCreateMemo(event)" class="flex items-center space-x-2 bg-stone-50/90 p-2 rounded-2xl border border-stone-200/60">
<input type="text" id="memoInputContent" placeholder="输入待办备忘 (如: 下午3点测温、补充维D3滴剂、准备温水洗澡...)" class="flex-1 bg-transparent text-xs px-2 py-1 outline-hidden text-stone-800 placeholder-stone-400 font-medium" required>
<select id="memoDuePeriod" class="text-[11px] bg-white border border-stone-200/80 rounded-xl px-2 py-1 text-stone-600 font-bold">
<option value="today">全天</option>
<option value="morning">上午</option>
<option value="afternoon">下午</option>
<option value="evening">睡前</option>
</select>
<button type="submit" class="bg-indigo-600 hover:bg-indigo-700 active:scale-95 text-white text-xs font-bold px-3 py-1.5 rounded-xl transition shadow-2xs">
添加
</button>
</form>
<!-- 备忘待办列表容器 -->
<div id="memoListContainer" class="space-y-1.5 max-h-56 overflow-y-auto no-scrollbar">
<!-- Dynamic Memos rendered via JS -->
</div>
</div>
<!-- 5. ✨ 日常保健与私人目标一键打卡 (自适应网格,带倒计时与微调) -->
<div class="bg-white border border-stone-200/80 rounded-3xl p-4 shadow-soft space-y-2.5">
<div class="flex items-center justify-between px-1"> <div class="flex items-center justify-between px-1">
<span class="text-xs font-bold text-slate-700 flex items-center space-x-1.5"> <span class="text-xs font-bold text-stone-700 flex items-center space-x-1.5">
<span>✨</span> <span>✨</span>
<span>日常保健与私人目标 (一键打卡)</span> <span>日常保健与私人目标 (一键打卡 / 倒计时)</span>
</span> </span>
<span class="text-[10px] text-slate-400">在宝贝档案中增减与配置默认值</span> <span class="text-[10px] text-stone-400">在宝贝档案中增减与配置默认值</span>
</div> </div>
<!-- 动态渲染自定义目标打卡按钮列表 (手机2列,桌面4列) --> <!-- 动态渲染自定义目标打卡按钮列表 (手机1列,平板2列,桌面4列) -->
<div id="quickCustomMetricsGrid" class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2 text-xs"> <div id="quickCustomMetricsGrid" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-2.5 text-xs">
<!-- Dynamic Custom Quick Buttons (D3, Tummy, Temp etc.) --> <!-- Dynamic Custom Quick Buttons (D3, Tummy, Temp etc.) -->
</div> </div>
</div> </div>
@@ -455,11 +539,17 @@
<div id="currentFamilyMeta" class="text-[11px] text-slate-500 mt-0.5">创建人: 宝妈 · 1 位宝宝 · 3 位看护人</div> <div id="currentFamilyMeta" class="text-[11px] text-slate-500 mt-0.5">创建人: 宝妈 · 1 位宝宝 · 3 位看护人</div>
</div> </div>
</div> </div>
<button class="bg-indigo-600 hover:bg-indigo-700 active:scale-95 text-white font-bold text-xs px-3.5 py-1.5 rounded-2xl shadow-xs transition flex items-center space-x-1" onclick="openFamilySwitchModal()"> <div class="flex items-center space-x-2">
<button type="button" class="bg-white hover:bg-indigo-50 text-indigo-700 border border-indigo-200/90 active:scale-95 font-bold text-xs px-3 py-1.5 rounded-2xl shadow-2xs transition flex items-center space-x-1 cursor-pointer" onclick="openMemoHistoryModal()" title="查看并维护家庭全量历史备忘待办">
<span>📋</span>
<span>历史备忘</span>
</button>
<button type="button" class="bg-indigo-600 hover:bg-indigo-700 active:scale-95 text-white font-bold text-xs px-3.5 py-1.5 rounded-2xl shadow-xs transition flex items-center space-x-1 cursor-pointer" onclick="openFamilySwitchModal()">
<span>⇄</span> <span>⇄</span>
<span>切换家庭</span> <span>切换家庭</span>
</button> </button>
</div> </div>
</div>
<!-- 微信/口令家庭邀请卡片 (为微信邀请加入打通) --> <!-- 微信/口令家庭邀请卡片 (为微信邀请加入打通) -->
<div class="bg-white/90 border border-indigo-100/90 rounded-2xl p-3 flex flex-col sm:flex-row sm:items-center justify-between gap-2.5"> <div class="bg-white/90 border border-indigo-100/90 rounded-2xl p-3 flex flex-col sm:flex-row sm:items-center justify-between gap-2.5">
@@ -519,17 +609,181 @@
</div> </div>
</div> </div>
<!-- 2. 私人专属目标打卡项与指标默认值配置 (移入宝贝档案) --> <!-- ⚙️ 专属配置中心 (CARE & DEFAULT CONFIGURATION MENU) -->
<div class="bg-white border border-slate-200 rounded-2xl p-4 shadow-xs space-y-3"> <div class="bg-white border border-slate-200/90 rounded-3xl p-4 shadow-soft space-y-4">
<div class="flex items-center justify-between border-b border-slate-100 pb-2.5"> <div class="border-b border-slate-100 pb-2.5">
<div class="flex items-center space-x-2">
<span class="text-lg p-1.5 bg-indigo-50 text-indigo-600 rounded-xl">⚙️</span>
<div> <div>
<h3 class="text-xs font-black text-slate-800 flex items-center space-x-1.5"> <h3 class="font-black text-xs sm:text-sm text-slate-900">看护习惯与专属配置菜单</h3>
<span>✨</span> <p class="text-[10px] text-slate-500">维护打卡默认值、看护人角色偏好与私人目标</p>
<span>私人目标打卡项与指标默认值配置</span>
</h3>
<p class="text-[10px] text-slate-500 mt-0.5">配置打卡时使用的默认数值与每日目标频次</p>
</div> </div>
<button class="text-xs bg-emerald-600 hover:bg-emerald-700 text-white px-3 py-1.5 rounded-full font-bold shadow-xs active:scale-95 transition" onclick="openAddCustomMetricModal()">+ 新建目标</button> </div>
</div>
<!-- Configuration Navigation Tabs -->
<div class="flex p-1 bg-slate-100/90 rounded-2xl text-xs font-bold gap-1">
<button id="cfgSubTabBtnFeeding" class="flex-1 py-1.5 rounded-xl bg-white text-indigo-700 shadow-2xs transition whitespace-nowrap cursor-pointer" onclick="switchConfigSubTab('feeding')">
🍼 喂养打卡
</button>
<button id="cfgSubTabBtnRoles" class="flex-1 py-1.5 rounded-xl text-slate-600 hover:text-slate-900 transition whitespace-nowrap cursor-pointer" onclick="switchConfigSubTab('roles')">
👥 角色偏好
</button>
<button id="cfgSubTabBtnMetrics" class="flex-1 py-1.5 rounded-xl text-slate-600 hover:text-slate-900 transition whitespace-nowrap cursor-pointer" onclick="switchConfigSubTab('metrics')">
✨ 私人目标
</button>
</div>
<!-- Subpanel 1: 🍼 喂养默认模式与打卡参数配置 -->
<div id="cfgSubPanelFeeding" class="space-y-3.5">
<div class="bg-amber-50/70 border border-amber-200/60 rounded-2xl p-3 text-xs space-y-1">
<div class="font-bold text-amber-900 flex items-center justify-between">
<span>当前宝宝: <span id="cfgBabyFeedingName" class="font-black underline decoration-amber-400">--</span></span>
<span class="text-[10px] bg-amber-200/80 text-amber-900 px-2 py-0.5 rounded-full font-bold">打卡秒记基准</span>
</div>
<p class="text-[11px] text-amber-800/80">配置宝宝常用的喂养方式、奶量和亲喂时长,在快速打卡中一触即记。</p>
</div>
<!-- 默认喂养模式单选 -->
<div class="space-y-1.5">
<label class="text-xs font-bold text-slate-700">默认喂养模式:</label>
<div class="grid grid-cols-2 gap-2 text-xs font-bold">
<label class="flex items-center space-x-2 p-2.5 rounded-xl border border-slate-200 cursor-pointer hover:bg-slate-50 transition has-checked:border-indigo-600 has-checked:bg-indigo-50/50 has-checked:text-indigo-900">
<input type="radio" name="cfgDefaultMode" value="bottle" class="accent-indigo-600" checked>
<span>🍼 瓶喂 (按容量)</span>
</label>
<label class="flex items-center space-x-2 p-2.5 rounded-xl border border-slate-200 cursor-pointer hover:bg-slate-50 transition has-checked:border-indigo-600 has-checked:bg-indigo-50/50 has-checked:text-indigo-900">
<input type="radio" name="cfgDefaultMode" value="breastfeed" class="accent-indigo-600">
<span>🤱 亲喂 (按时长)</span>
</label>
</div>
</div>
<!-- 默认冲奶量 -->
<div class="space-y-1.5">
<div class="flex items-center justify-between">
<label class="text-xs font-bold text-slate-700">默认单次瓶喂冲奶量 (ml):</label>
<div class="flex items-center space-x-1 font-mono text-xs">
<span id="cfgBottleMlDisplay" class="font-bold text-amber-600">120</span>
<span class="text-slate-400">ml</span>
</div>
</div>
<div class="grid grid-cols-5 gap-1 text-xs text-center font-bold">
<button type="button" class="cfg-bottle-chip py-1.5 rounded-xl bg-slate-100 hover:bg-amber-100 transition cursor-pointer" onclick="setCfgBottlePreset(60)">60</button>
<button type="button" class="cfg-bottle-chip py-1.5 rounded-xl bg-slate-100 hover:bg-amber-100 transition cursor-pointer" onclick="setCfgBottlePreset(90)">90</button>
<button type="button" class="cfg-bottle-chip active py-1.5 rounded-xl bg-amber-500 text-white transition cursor-pointer" onclick="setCfgBottlePreset(120)">120</button>
<button type="button" class="cfg-bottle-chip py-1.5 rounded-xl bg-slate-100 hover:bg-amber-100 transition cursor-pointer" onclick="setCfgBottlePreset(150)">150</button>
<button type="button" class="cfg-bottle-chip py-1.5 rounded-xl bg-slate-100 hover:bg-amber-100 transition cursor-pointer" onclick="setCfgBottlePreset(180)">180</button>
</div>
<input type="number" id="cfgInputBottleMl" value="120" min="10" max="350" step="5" class="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-1.5 text-xs text-slate-800 font-bold outline-hidden focus:border-indigo-500" oninput="onCfgBottleInput(this.value)">
</div>
<!-- 默认亲喂目标时长 -->
<div class="space-y-1.5">
<div class="flex items-center justify-between">
<label class="text-xs font-bold text-slate-700">默认亲喂目标时长 (分钟):</label>
<div class="flex items-center space-x-1 font-mono text-xs">
<span id="cfgBfMinDisplay" class="font-bold text-rose-600">20</span>
<span class="text-slate-400">分钟</span>
</div>
</div>
<div class="grid grid-cols-4 gap-1 text-xs text-center font-bold">
<button type="button" class="cfg-bf-chip py-1.5 rounded-xl bg-slate-100 hover:bg-rose-100 transition cursor-pointer" onclick="setCfgBfPreset(15)">15m</button>
<button type="button" class="cfg-bf-chip active py-1.5 rounded-xl bg-rose-500 text-white transition cursor-pointer" onclick="setCfgBfPreset(20)">20m</button>
<button type="button" class="cfg-bf-chip py-1.5 rounded-xl bg-slate-100 hover:bg-rose-100 transition cursor-pointer" onclick="setCfgBfPreset(25)">25m</button>
<button type="button" class="cfg-bf-chip py-1.5 rounded-xl bg-slate-100 hover:bg-rose-100 transition cursor-pointer" onclick="setCfgBfPreset(30)">30m</button>
</div>
<input type="number" id="cfgInputBfMinutes" value="20" min="5" max="60" step="1" class="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-1.5 text-xs text-slate-800 font-bold outline-hidden focus:border-indigo-500" oninput="onCfgBfInput(this.value)">
</div>
<!-- 默认奶液类型 -->
<div class="space-y-1.5">
<label class="text-xs font-bold text-slate-700">默认奶液类型:</label>
<div class="grid grid-cols-2 gap-2 text-xs font-bold">
<label class="flex items-center space-x-2 p-2 rounded-xl border border-slate-200 cursor-pointer hover:bg-slate-50 transition has-checked:border-indigo-600 has-checked:bg-indigo-50/50 has-checked:text-indigo-900">
<input type="radio" name="cfgDefaultMilkType" value="formula" class="accent-indigo-600" checked>
<span>🍼 配方奶粉</span>
</label>
<label class="flex items-center space-x-2 p-2 rounded-xl border border-slate-200 cursor-pointer hover:bg-slate-50 transition has-checked:border-indigo-600 has-checked:bg-indigo-50/50 has-checked:text-indigo-900">
<input type="radio" name="cfgDefaultMilkType" value="breast_milk" class="accent-indigo-600">
<span>💧 母乳/冷藏储奶</span>
</label>
</div>
</div>
<button type="button" class="w-full bg-indigo-600 hover:bg-indigo-700 active:scale-98 text-white font-bold text-xs py-2.5 rounded-2xl shadow-xs transition flex items-center justify-center space-x-1.5 cursor-pointer" onclick="saveBabyFeedingDefaults()">
<span>💾 保存宝宝喂养打卡默认配置</span>
</button>
</div>
<!-- Subpanel 2: 👥 看护人角色记忆与偏好配置 -->
<div id="cfgSubPanelRoles" class="hidden space-y-3.5">
<div class="bg-indigo-50/70 border border-indigo-200/60 rounded-2xl p-3 text-xs space-y-1">
<div class="font-bold text-indigo-900 flex items-center justify-between">
<span>👥 各角色专属打卡习惯</span>
<span class="text-[10px] bg-indigo-200/80 text-indigo-900 px-2 py-0.5 rounded-full font-bold">云端独立记忆</span>
</div>
<p class="text-[11px] text-indigo-800/80">宝妈常亲喂、宝爸/月嫂常瓶喂?为各家庭成员定制专属模式与容量,打卡自动适配。</p>
</div>
<!-- 成员选择 -->
<div class="space-y-1.5">
<label class="text-xs font-bold text-slate-700">选择要配置的看护人角色:</label>
<select id="cfgRoleSelect" onchange="loadRoleConfigForSelectedRole()" class="w-full bg-white border border-slate-200 rounded-xl px-3 py-2 text-xs font-bold text-slate-800 outline-hidden focus:border-indigo-500">
<!-- Dynamic populated roles -->
</select>
</div>
<!-- 该角色喂养模式 -->
<div class="space-y-1.5">
<label class="text-xs font-bold text-slate-700">该角色打卡模式偏好:</label>
<div class="grid grid-cols-3 gap-1.5 text-xs font-bold">
<label class="flex items-center justify-center p-2 rounded-xl border border-slate-200 cursor-pointer text-center hover:bg-slate-50 transition has-checked:border-indigo-600 has-checked:bg-indigo-50/50 has-checked:text-indigo-900">
<input type="radio" name="cfgRoleMode" value="" class="accent-indigo-600 sr-only" checked>
<span>🔄 跟随宝宝</span>
</label>
<label class="flex items-center justify-center p-2 rounded-xl border border-slate-200 cursor-pointer text-center hover:bg-slate-50 transition has-checked:border-indigo-600 has-checked:bg-indigo-50/50 has-checked:text-indigo-900">
<input type="radio" name="cfgRoleMode" value="bottle" class="accent-indigo-600 sr-only">
<span>🍼 瓶喂</span>
</label>
<label class="flex items-center justify-center p-2 rounded-xl border border-slate-200 cursor-pointer text-center hover:bg-slate-50 transition has-checked:border-indigo-600 has-checked:bg-indigo-50/50 has-checked:text-indigo-900">
<input type="radio" name="cfgRoleMode" value="breastfeed" class="accent-indigo-600 sr-only">
<span>🤱 亲喂</span>
</label>
</div>
</div>
<!-- 该角色瓶喂容量 -->
<div class="space-y-1.5">
<div class="flex items-center justify-between">
<label class="text-xs font-bold text-slate-700">该角色常用瓶喂奶量 (ml):</label>
<span class="text-[10px] text-slate-400">留空则跟随宝宝默认</span>
</div>
<input type="number" id="cfgRoleBottleMl" placeholder="跟随宝宝默认 (如120)" min="10" max="350" step="5" class="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-1.5 text-xs text-slate-800 font-bold outline-hidden focus:border-indigo-500">
</div>
<!-- 该角色亲喂时长 -->
<div class="space-y-1.5">
<div class="flex items-center justify-between">
<label class="text-xs font-bold text-slate-700">该角色常用亲喂目标时长 (分钟):</label>
<span class="text-[10px] text-slate-400">留空则跟随宝宝默认</span>
</div>
<input type="number" id="cfgRoleBfMinutes" placeholder="跟随宝宝默认 (如20)" min="5" max="60" step="1" class="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-1.5 text-xs text-slate-800 font-bold outline-hidden focus:border-indigo-500">
</div>
<button type="button" class="w-full bg-indigo-600 hover:bg-indigo-700 active:scale-98 text-white font-bold text-xs py-2.5 rounded-2xl shadow-xs transition flex items-center justify-center space-x-1.5 cursor-pointer" onclick="saveRolePreferencesFromProfile()">
<span>💾 保存该角色专属偏好</span>
</button>
</div>
<!-- Subpanel 3: ✨ 私人专属目标打卡项维护 -->
<div id="cfgSubPanelMetrics" class="hidden space-y-3.5">
<div class="flex items-center justify-between border-b border-slate-100 pb-2">
<div>
<h4 class="text-xs font-black text-slate-800">自定义目标与预设值维护</h4>
<p class="text-[10px] text-slate-500">配置打卡默认数值、单位与每日达标频次</p>
</div>
<button class="text-xs bg-emerald-600 hover:bg-emerald-700 text-white px-3 py-1.5 rounded-full font-bold shadow-xs active:scale-95 transition cursor-pointer" onclick="openAddCustomMetricModal()">+ 新建目标</button>
</div> </div>
<div id="profileCustomMetricsList" class="space-y-2"> <div id="profileCustomMetricsList" class="space-y-2">
@@ -537,10 +791,149 @@
</div> </div>
</div> </div>
</div> </div>
</div>
</section> </section>
</main> </main>
<!-- ======================================================== -->
<!-- MEMO HISTORY QUERY & MAINTENANCE MODAL (历史备忘查询与维护弹窗) -->
<!-- ======================================================== -->
<div id="memoHistoryModal" class="fixed inset-0 bg-black/60 z-50 hidden flex items-end md:items-center justify-center backdrop-blur-xs p-0 md:p-4">
<div class="bg-white rounded-t-3xl md:rounded-3xl max-w-md md:max-w-2xl w-full max-h-[88vh] flex flex-col shadow-2xl mx-auto pb-2">
<!-- Modal Header -->
<div class="p-4 border-b border-slate-100 flex items-center justify-between">
<div class="flex items-center space-x-2.5">
<span class="text-xl p-2 bg-indigo-50 text-indigo-600 rounded-2xl shadow-2xs">📋</span>
<div>
<div class="flex items-center space-x-2">
<h3 class="font-extrabold text-sm sm:text-base text-slate-900">家庭备忘清单与历史归档</h3>
<span id="memoHistoryTotalCountBadge" class="text-[10px] font-bold text-indigo-700 bg-indigo-50 px-2 py-0.5 rounded-full border border-indigo-100">0 条记录</span>
</div>
<p class="text-[11px] text-slate-500 mt-0.5">全量待办检索 · 历史完成追溯 · 待办内容与时段维护</p>
</div>
</div>
<div class="flex items-center space-x-2">
<button type="button" class="text-xs bg-rose-50 hover:bg-rose-100 text-rose-600 font-bold px-2.5 py-1.5 rounded-xl transition flex items-center space-x-1 cursor-pointer active:scale-95" onclick="clearCompletedMemos()" title="一键清理所有已标记完成的待办">
<span>🧹</span>
<span>清理已完成</span>
</button>
<button type="button" class="text-slate-400 hover:text-slate-600 text-lg font-bold ml-1 cursor-pointer" onclick="closeModal('memoHistoryModal')">✕</button>
</div>
</div>
<!-- Filter & Search Toolbar -->
<div class="p-3 border-b border-slate-100 space-y-2.5 bg-slate-50/60">
<!-- Search Box -->
<div class="relative">
<input type="text" id="memoHistorySearchInput" placeholder="🔍 搜索备忘内容、创建看护人..." class="w-full bg-white border border-slate-200 rounded-xl pl-3 pr-8 py-2 text-xs text-slate-800 placeholder:text-slate-400 outline-hidden focus:border-indigo-500 font-medium" oninput="onMemoHistoryFilterChange()">
<button type="button" id="btnClearMemoSearch" class="hidden absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 text-xs font-bold cursor-pointer" onclick="clearMemoHistorySearch()">✕</button>
</div>
<!-- Dual Filter Bar (Status tabs + Period pills) -->
<div class="flex flex-wrap items-center justify-between gap-2 text-xs">
<!-- Status Filter -->
<div class="flex items-center bg-white p-0.5 rounded-xl border border-slate-200/80 font-bold">
<button type="button" class="memo-status-filter active px-2.5 py-1 rounded-lg bg-indigo-600 text-white transition cursor-pointer text-xs" data-status="all" onclick="setMemoStatusFilter('all')">
全部 (<span id="memoCountAll">0</span>)
</button>
<button type="button" class="memo-status-filter px-2.5 py-1 rounded-lg text-slate-600 hover:text-slate-900 transition cursor-pointer text-xs" data-status="pending" onclick="setMemoStatusFilter('pending')">
待办中 (<span id="memoCountPending">0</span>)
</button>
<button type="button" class="memo-status-filter px-2.5 py-1 rounded-lg text-slate-600 hover:text-slate-900 transition cursor-pointer text-xs" data-status="completed" onclick="setMemoStatusFilter('completed')">
已完成 (<span id="memoCountCompleted">0</span>)
</button>
</div>
<!-- Due Period Filter -->
<div class="flex items-center space-x-1 overflow-x-auto no-scrollbar font-medium">
<button type="button" class="memo-period-filter active px-2 py-0.5 rounded-lg bg-slate-200 text-slate-800 text-[11px] font-bold cursor-pointer" data-period="all" onclick="setMemoPeriodFilter('all')">全部时段</button>
<button type="button" class="memo-period-filter px-2 py-0.5 rounded-lg bg-white border border-slate-200 text-slate-600 text-[11px] hover:bg-slate-100 cursor-pointer" data-period="today" onclick="setMemoPeriodFilter('today')">📅 全天</button>
<button type="button" class="memo-period-filter px-2 py-0.5 rounded-lg bg-white border border-slate-200 text-slate-600 text-[11px] hover:bg-slate-100 cursor-pointer" data-period="morning" onclick="setMemoPeriodFilter('morning')">☀️ 上午</button>
<button type="button" class="memo-period-filter px-2 py-0.5 rounded-lg bg-white border border-slate-200 text-slate-600 text-[11px] hover:bg-slate-100 cursor-pointer" data-period="afternoon" onclick="setMemoPeriodFilter('afternoon')">🌤️ 下午</button>
<button type="button" class="memo-period-filter px-2 py-0.5 rounded-lg bg-white border border-slate-200 text-slate-600 text-[11px] hover:bg-slate-100 cursor-pointer" data-period="evening" onclick="setMemoPeriodFilter('evening')">🌙 睡前</button>
</div>
</div>
</div>
<!-- Scrollable Memo List -->
<div id="memoHistoryList" class="flex-1 overflow-y-auto p-4 space-y-2.5 text-xs">
<!-- Dynamic Memos rendered via JS -->
</div>
<!-- Bottom Quick Add Bar in History Modal -->
<div class="p-3 border-t border-slate-100 bg-white">
<form onsubmit="handleCreateMemoFromHistory(event)" class="flex items-center space-x-2">
<input type="text" id="historyModalInputContent" placeholder="+ 在历史备忘中快速新建待办..." class="flex-1 bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-xs outline-hidden focus:border-indigo-500 font-medium text-slate-800" required>
<select id="historyModalDuePeriod" class="text-[11px] bg-slate-50 border border-slate-200 rounded-xl px-2.5 py-2 text-slate-700 font-bold">
<option value="today">全天</option>
<option value="morning">上午</option>
<option value="afternoon">下午</option>
<option value="evening">睡前</option>
</select>
<button type="submit" class="bg-indigo-600 hover:bg-indigo-700 active:scale-95 text-white text-xs font-bold px-4 py-2 rounded-xl transition shadow-2xs whitespace-nowrap cursor-pointer">
添加待办
</button>
</form>
</div>
</div>
</div>
<!-- ======================================================== -->
<!-- EDIT MEMO MODAL (编辑修改备忘待办弹窗) -->
<!-- ======================================================== -->
<div id="editMemoModal" class="fixed inset-0 bg-black/60 z-50 hidden flex items-center justify-center p-4 backdrop-blur-xs">
<div class="bg-white rounded-3xl max-w-sm w-full p-5 space-y-4 shadow-2xl mx-auto">
<div class="flex items-center justify-between border-b border-slate-100 pb-2.5">
<div class="flex items-center space-x-2">
<span class="text-lg">✏️</span>
<h3 class="font-extrabold text-sm text-slate-800">编辑备忘待办</h3>
</div>
<button type="button" class="text-slate-400 hover:text-slate-600 text-lg font-bold cursor-pointer" onclick="closeModal('editMemoModal')">✕</button>
</div>
<input type="hidden" id="editMemoId">
<div class="space-y-1.5">
<label class="text-xs font-bold text-slate-700">待办事项内容:</label>
<textarea id="editMemoContentInput" rows="3" class="w-full bg-slate-50 border border-slate-200 rounded-xl p-2.5 text-xs text-slate-800 font-medium outline-hidden focus:border-indigo-500" placeholder="输入待办事项内容..." required></textarea>
</div>
<div class="space-y-1.5">
<label class="text-xs font-bold text-slate-700">执行建议时段:</label>
<select id="editMemoPeriodSelect" class="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-xs font-bold text-slate-800 outline-hidden focus:border-indigo-500">
<option value="today">📅 全天</option>
<option value="morning">☀️ 上午</option>
<option value="afternoon">🌤️ 下午</option>
<option value="evening">🌙 睡前</option>
</select>
</div>
<div class="space-y-1.5">
<label class="text-xs font-bold text-slate-700">完成状态:</label>
<div class="grid grid-cols-2 gap-2 text-xs font-bold">
<label class="flex items-center space-x-2 p-2 rounded-xl border border-slate-200 cursor-pointer hover:bg-slate-50 transition has-checked:border-indigo-600 has-checked:bg-indigo-50/50 has-checked:text-indigo-900">
<input type="radio" name="editMemoStatus" value="0" class="accent-indigo-600" id="editMemoStatusPending">
<span>⏳ 待办进行中</span>
</label>
<label class="flex items-center space-x-2 p-2 rounded-xl border border-slate-200 cursor-pointer hover:bg-slate-50 transition has-checked:border-emerald-600 has-checked:bg-emerald-50/50 has-checked:text-emerald-900">
<input type="radio" name="editMemoStatus" value="1" class="accent-emerald-600" id="editMemoStatusDone">
<span>✅ 已标记完成</span>
</label>
</div>
</div>
<div class="pt-2 flex items-center space-x-2">
<button type="button" class="flex-1 bg-slate-100 hover:bg-slate-200 text-slate-700 font-bold text-xs py-2.5 rounded-2xl transition cursor-pointer" onclick="closeModal('editMemoModal')">
取消
</button>
<button type="button" class="flex-1 bg-indigo-600 hover:bg-indigo-700 active:scale-98 text-white font-bold text-xs py-2.5 rounded-2xl shadow-xs transition cursor-pointer" onclick="submitEditMemo()">
💾 保存修改
</button>
</div>
</div>
</div>
<!-- ======================================================== --> <!-- ======================================================== -->
<!-- PUBLIC COMMON TIMELINE DRAWER / MODAL (公共流水明细弹窗) --> <!-- PUBLIC COMMON TIMELINE DRAWER / MODAL (公共流水明细弹窗) -->
<!-- ======================================================== --> <!-- ======================================================== -->
@@ -1109,6 +1502,115 @@
</div> </div>
</div> </div>
<!-- FLOATING DOCKED TIMER WIDGET (当有计时进行中且最小化时浮现) -->
<div id="floatingTimerWidget" class="hidden fixed bottom-24 right-4 z-40 bg-stone-900/95 hover:bg-stone-900 text-white backdrop-blur-md border border-white/20 px-3.5 py-2.5 rounded-2xl shadow-xl flex items-center space-x-3 cursor-pointer transition active:scale-95" onclick="openFocusModal()">
<span class="relative flex h-3 w-3">
<span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-amber-400 opacity-75"></span>
<span class="relative inline-flex rounded-full h-3 w-3 bg-amber-500"></span>
</span>
<div>
<div id="floatingTimerTitle" class="text-[10px] text-amber-300 font-bold">亲喂计时中 (左侧)</div>
<div id="floatingTimerDigits" class="text-sm font-mono font-black">15:00</div>
</div>
<button onclick="event.stopPropagation(); completeFocusTimerAndRecord();" class="text-xs bg-amber-500 hover:bg-amber-600 text-white font-bold px-2 py-1 rounded-xl shadow-xs" title="快速完成">
打卡
</button>
</div>
<!-- FULLSCREEN FOCUS MODAL (超大号沉浸专注模式) -->
<div id="focusModal" class="fixed inset-0 z-50 hidden flex flex-col justify-between bg-stone-950/95 text-white backdrop-blur-2xl p-6 sm:p-10 select-none transition-all duration-300">
<!-- 顶部控制栏 -->
<div class="flex items-center justify-between max-w-xl w-full mx-auto">
<div class="flex items-center space-x-2.5">
<span id="focusActivityIcon" class="text-2xl p-2 bg-white/10 rounded-2xl">🤱</span>
<div>
<div class="flex items-center space-x-2">
<h2 id="focusActivityTitle" class="font-black text-base sm:text-lg text-white">亲喂倒计时专注</h2>
<span id="focusBabyBadge" class="text-[10px] font-bold bg-amber-400/20 text-amber-300 border border-amber-400/40 px-2 py-0.5 rounded-full">嘟嘟</span>
</div>
<p id="focusOperatorTip" class="text-[11px] text-stone-400 mt-0.5">当前记录人: 宝妈 · 保持静心专注</p>
</div>
</div>
<div class="flex items-center space-x-2">
<button onclick="minimizeFocusModal()" class="text-xs bg-white/10 hover:bg-white/20 active:scale-95 text-stone-300 hover:text-white px-3 py-1.5 rounded-xl font-bold transition flex items-center space-x-1" title="最小化浮窗运行">
<span>▾</span>
<span>最小化</span>
</button>
<button onclick="closeFocusModal()" class="text-stone-400 hover:text-white p-1 text-xl font-bold transition" title="关闭专注窗口">
✕
</button>
</div>
</div>
<!-- 中心聚焦核心:大号圆形进度环与倒计时巨幅字体 -->
<div class="flex-1 flex flex-col items-center justify-center py-4 my-auto">
<div class="relative flex items-center justify-center">
<!-- SVG Circular Progress Ring (r=120, circumference=754) -->
<svg class="w-64 h-64 sm:w-80 sm:h-80 -rotate-90 transform" viewBox="0 0 280 280">
<circle cx="140" cy="140" r="120" stroke="#334155" stroke-width="10" fill="transparent" class="opacity-40" />
<circle id="focusRingCircle" cx="140" cy="140" r="120" stroke="#F59E0B" stroke-width="12" fill="transparent" stroke-dasharray="754" stroke-dashoffset="0" stroke-linecap="round" class="focus-glow-ring transition-all duration-700" />
</svg>
<!-- 环内信息聚焦 -->
<div class="absolute inset-0 flex flex-col items-center justify-center text-center p-4">
<div id="focusCurrentPhaseText" class="text-xs sm:text-sm font-bold tracking-widest text-amber-300 uppercase mb-1">
左侧哺乳进行中
</div>
<div id="focusDigitsDisplay" class="font-mono font-black text-6xl sm:text-7xl md:text-8xl tracking-tight text-white drop-shadow-md">
15:00
</div>
<div id="focusSubInfo" class="text-xs text-stone-400 mt-2 font-medium">
目标: 15分钟 · 已进行: 00:00
</div>
</div>
</div>
<!-- 亲喂专属:分侧时长实时统计与一键换侧 -->
<div id="focusBfSideStats" class="flex items-center space-x-3 mt-6">
<button id="btnFocusLeftBreast" onclick="switchBreastSide('left')" class="px-4 py-2 rounded-2xl bg-amber-500/25 border-2 border-amber-400 text-amber-200 font-bold text-xs flex items-center space-x-2 transition shadow-sm">
<span>🤱 左侧</span>
<span id="focusLeftTime" class="font-mono font-black text-sm">00:00</span>
</button>
<button onclick="toggleBreastSide()" class="p-2.5 rounded-2xl bg-white/10 hover:bg-white/20 active:scale-95 text-white font-bold text-sm transition" title="左右换侧">
⇄ 换侧
</button>
<button id="btnFocusRightBreast" onclick="switchBreastSide('right')" class="px-4 py-2 rounded-2xl bg-white/5 border border-white/20 text-stone-400 font-bold text-xs flex items-center space-x-2 transition">
<span>🤱 右侧</span>
<span id="focusRightTime" class="font-mono font-black text-sm">00:00</span>
</button>
</div>
</div>
<!-- 底部控制面板 -->
<div class="max-w-md w-full mx-auto space-y-3 pb-2">
<div class="flex items-center space-x-2">
<button onclick="addFocusMinutes(5)" class="flex-1 bg-white/10 hover:bg-white/20 active:scale-95 text-white font-bold text-xs py-3 rounded-2xl transition flex items-center justify-center space-x-1">
<span>+5m</span>
<span>加时</span>
</button>
<button id="btnFocusPauseResume" onclick="togglePauseFocusTimer()" class="flex-1 bg-white/15 hover:bg-white/25 active:scale-95 text-white font-bold text-xs py-3 rounded-2xl transition flex items-center justify-center space-x-1">
<span id="focusPauseIcon">⏸</span>
<span id="focusPauseText">暂停</span>
</button>
<button onclick="cancelFocusTimer()" class="px-4 bg-white/5 hover:bg-rose-500/20 text-stone-400 hover:text-rose-300 font-bold text-xs py-3 rounded-2xl transition">
取消
</button>
</div>
<button id="btnFocusComplete" onclick="completeFocusTimerAndRecord()" class="w-full bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-600 hover:to-orange-600 active:scale-98 text-white font-black text-sm py-3.5 rounded-2xl shadow-focus transition flex items-center justify-center space-x-2">
<span>✓</span>
<span>完成并自动打卡入库</span>
</button>
</div>
</div>
</div> </div>
<script src="app.js"></script> <script src="app.js"></script>
+64
View File
@@ -86,3 +86,67 @@ img, video {
filter: brightness(0.95); filter: brightness(0.95);
transform: translateY(-1px); transform: translateY(-1px);
} }
/* Warm & Soft Theme Tokens (方案 1 温暖治愈系) */
:root {
--color-warm-bg: #FAF7F2;
--color-card-bg: #FFFFFF;
}
body {
background-color: #F8F5EE;
background-image:
radial-gradient(at 0% 0%, rgba(254, 243, 199, 0.35) 0px, transparent 50%),
radial-gradient(at 100% 100%, rgba(243, 232, 255, 0.35) 0px, transparent 50%),
radial-gradient(at 50% 50%, rgba(240, 249, 255, 0.25) 0px, transparent 50%);
background-attachment: fixed;
}
/* Soft Ambient Diffuse Shadows */
.shadow-soft {
box-shadow: 0 10px 30px -4px rgba(160, 140, 120, 0.08), 0 4px 12px -2px rgba(160, 140, 120, 0.04);
}
.shadow-soft-lg {
box-shadow: 0 20px 40px -6px rgba(160, 140, 120, 0.12), 0 8px 16px -4px rgba(160, 140, 120, 0.06);
}
.shadow-focus {
box-shadow: 0 0 50px rgba(245, 158, 11, 0.25);
}
/* Floating Dock for Mobile */
.floating-dock {
box-shadow: 0 12px 36px rgba(100, 90, 80, 0.14), 0 2px 8px rgba(100, 90, 80, 0.06);
}
/* Checkbox strikethrough animation */
.memo-done-text {
text-decoration: line-through;
color: #94A3B8;
transition: all 0.2s ease;
}
/* Fullscreen Focus Overlay Animations */
.focus-glow-ring {
filter: drop-shadow(0 0 16px rgba(245, 158, 11, 0.4));
transition: stroke-dashoffset 0.8s ease;
}
.focus-sleep-glow {
filter: drop-shadow(0 0 18px rgba(139, 92, 246, 0.5));
}
.focus-tummy-glow {
filter: drop-shadow(0 0 18px rgba(16, 185, 129, 0.45));
}
@keyframes pulseGlow {
0%, 100% {
transform: scale(1);
opacity: 0.95;
}
50% {
transform: scale(1.02);
opacity: 1;
}
}
.animate-focus-pulse {
animation: pulseGlow 3s infinite ease-in-out;
}
+70
View File
@@ -0,0 +1,70 @@
const { pool } = require('../server/db');
async function migrate() {
const conn = await pool.getConnection();
try {
console.log('Running V1.3 & V1.4 DB migration...');
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='家庭日常备忘待办清单表';
`);
console.log('✅ Table family_memo ensured.');
try {
await conn.query("ALTER TABLE `family_member` ADD COLUMN `preferences` JSON NULL COMMENT '角色专属行为偏好'");
console.log('✅ Column preferences added to family_member.');
} catch (e) {
if (e.code === 'ER_DUP_FIELDNAME') {
console.log('ℹ️ Column preferences already exists in family_member.');
} else {
console.warn('family_member column warning:', e.message);
}
}
try {
await conn.query("ALTER TABLE `baby_profile` ADD COLUMN `default_config` JSON NULL COMMENT '宝宝默认行为配置'");
console.log('✅ Column default_config added to baby_profile.');
} catch (e) {
if (e.code === 'ER_DUP_FIELDNAME') {
console.log('ℹ️ Column default_config already exists in baby_profile.');
} else {
console.warn('baby_profile column warning:', e.message);
}
}
// Insert sample initial memo if none exists
const [memos] = await conn.query("SELECT COUNT(*) as count FROM `family_memo` WHERE `family_id` = 'family-001'");
if (memos[0].count === 0) {
await conn.query(`
INSERT INTO \`family_memo\` (\`memo_id\`, \`family_id\`, \`content\`, \`due_period\`, \`is_completed\`, \`created_by\`)
VALUES
('memo-001', 'family-001', '下午3点:准备45℃温水洗澡', 'afternoon', 0, '宝妈'),
('memo-002', 'family-001', '睡前:喂服维生素 D3 滴剂', 'evening', 0, '宝爸'),
('memo-003', 'family-001', '消毒所有奶瓶及吸奶器配件', 'morning', 1, '奶奶')
`);
console.log('✅ Seed memos initialized for family-001.');
}
console.log('Migration finished successfully!');
} finally {
conn.release();
process.exit(0);
}
}
migrate().catch(err => {
console.error('Migration failed:', err);
process.exit(1);
});
+18
View File
@@ -11,6 +11,7 @@ const careGuidesRouter = require('./routes/careGuides');
const exportRouter = require('./routes/export'); const exportRouter = require('./routes/export');
const customMetricsRouter = require('./routes/customMetrics'); const customMetricsRouter = require('./routes/customMetrics');
const familiesRouter = require('./routes/families'); const familiesRouter = require('./routes/families');
const memosRouter = require('./routes/memos');
const { router: sseRouter } = require('./routes/sse'); const { router: sseRouter } = require('./routes/sse');
const app = express(); const app = express();
@@ -31,6 +32,7 @@ app.use('/api/summary', summaryRouter);
app.use('/api/care-guides', careGuidesRouter); app.use('/api/care-guides', careGuidesRouter);
app.use('/api/export', exportRouter); app.use('/api/export', exportRouter);
app.use('/api/custom-metrics', customMetricsRouter); app.use('/api/custom-metrics', customMetricsRouter);
app.use('/api/memos', memosRouter);
app.use('/api/events', sseRouter); app.use('/api/events', sseRouter);
// Fallback to index.html for SPA // Fallback to index.html for SPA
@@ -41,6 +43,22 @@ app.use((req, res, next) => {
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() { async function start() {
try { try {
await initDatabase(); await initDatabase();
+95
View File
@@ -9,11 +9,79 @@ const pool = mysql.createPool({
database: process.env.DB_NAME || 'yyyy', database: process.env.DB_NAME || 'yyyy',
waitForConnections: true, waitForConnections: true,
connectionLimit: 10, connectionLimit: 10,
maxIdle: 2,
idleTimeout: 30000,
enableKeepAlive: true,
keepAliveInitialDelay: 5000,
queueLimit: 0, queueLimit: 0,
connectTimeout: 10000, connectTimeout: 10000,
dateStrings: true 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='看护人用户表(预留)'; ) 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`'); const [existingFamilies] = await conn.query('SELECT COUNT(*) as count FROM `family`');
if (existingFamilies[0].count === 0) { if (existingFamilies[0].count === 0) {
+25 -1
View File
@@ -71,18 +71,27 @@ router.post('/', async (req, res) => {
// PUT /api/babies/:babyId - Update baby profile // PUT /api/babies/:babyId - Update baby profile
router.put('/:babyId', async (req, res) => { router.put('/:babyId', async (req, res) => {
const { babyId } = req.params; const { babyId } = req.params;
const { name, gender, birthDate, themeColor } = req.body; const { name, gender, birthDate, themeColor, defaultConfig } = req.body;
if (!name || !birthDate) { if (!name || !birthDate) {
return res.status(400).json({ success: false, error: '姓名与出生日期必填' }); return res.status(400).json({ success: false, error: '姓名与出生日期必填' });
} }
const color = themeColor || '#3B82F6'; const color = themeColor || '#3B82F6';
try { try {
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(` await pool.query(`
UPDATE \`baby_profile\` UPDATE \`baby_profile\`
SET \`name\` = ?, \`gender\` = ?, \`birth_date\` = ?, \`theme_color\` = ? SET \`name\` = ?, \`gender\` = ?, \`birth_date\` = ?, \`theme_color\` = ?
WHERE \`baby_id\` = ? WHERE \`baby_id\` = ?
`, [name, gender || 'boy', birthDate, color, babyId]); `, [name, gender || 'boy', birthDate, color, babyId]);
}
const [updated] = await pool.query('SELECT * FROM `baby_profile` WHERE `baby_id` = ?', [babyId]); const [updated] = await pool.query('SELECT * FROM `baby_profile` WHERE `baby_id` = ?', [babyId]);
res.json({ success: true, data: updated[0] }); 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 // POST /api/babies/:babyId/default - Set as default baby
router.post('/:babyId/default', async (req, res) => { router.post('/:babyId/default', async (req, res) => {
const { babyId } = req.params; const { babyId } = req.params;
+38 -2
View File
@@ -36,7 +36,7 @@ router.get('/', async (req, res) => {
// 批量查询家庭成员 // 批量查询家庭成员
const [members] = await pool.query( 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\` FROM \`family_member\`
WHERE family_id IN (${placeholders}) WHERE family_id IN (${placeholders})
ORDER BY is_owner DESC, id ASC`, ORDER BY is_owner DESC, id ASC`,
@@ -190,7 +190,7 @@ router.get('/:familyId/members', async (req, res) => {
try { try {
const { familyId } = req.params; const { familyId } = req.params;
const [members] = await pool.query( 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] [familyId]
); );
res.json({ success: true, data: members }); 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; module.exports = router;
+206
View File
@@ -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;
+13
View File
@@ -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) { function broadcastEvent(eventData) {
const dataString = `data: ${JSON.stringify(eventData)}\n\n`; const dataString = `data: ${JSON.stringify(eventData)}\n\n`;
clients.forEach(client => { clients.forEach(client => {
+3 -2
View File
@@ -12,8 +12,9 @@ function formatElapsed(minutes) {
if (minutes < 1) return '刚刚'; if (minutes < 1) return '刚刚';
const h = Math.floor(minutes / 60); const h = Math.floor(minutes / 60);
const m = minutes % 60; const m = minutes % 60;
if (h === 0) return `${m} 分钟前`; if (h === 0) return `${m}分钟前`;
return `${h} 小时 ${m} 分前`; if (m === 0) return `${h}小时前`;
return `${h}小时${m}分前`;
} }
router.get('/', async (req, res) => { router.get('/', async (req, res) => {
+66 -25
View File
@@ -47,6 +47,7 @@ CREATE TABLE IF NOT EXISTS `family_member` (
`role_name` VARCHAR(50) NOT NULL COMMENT '看护人身份称谓 (如: 宝妈, 宝爸, 月嫂, 外婆, 奶奶)', `role_name` VARCHAR(50) NOT NULL COMMENT '看护人身份称谓 (如: 宝妈, 宝爸, 月嫂, 外婆, 奶奶)',
`user_id` VARCHAR(64) NULL COMMENT '关联系统用户ID (二阶段微信openid/手机号用户)', `user_id` VARCHAR(64) NULL COMMENT '关联系统用户ID (二阶段微信openid/手机号用户)',
`is_owner` TINYINT(1) DEFAULT 0 COMMENT '是否为创建者/主看护人 (1:是, 0:否)', `is_owner` TINYINT(1) DEFAULT 0 COMMENT '是否为创建者/主看护人 (1:是, 0:否)',
`preferences` JSON NULL COMMENT '看护人专属行为记忆偏好 (如默认亲喂/瓶喂、默认容量、尿布性状)',
`joined_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '加入家庭时间', `joined_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '加入家庭时间',
INDEX `idx_family_member` (`family_id`), INDEX `idx_family_member` (`family_id`),
INDEX `idx_member_user` (`user_id`) INDEX `idx_member_user` (`user_id`)
@@ -62,6 +63,7 @@ CREATE TABLE IF NOT EXISTS `baby_profile` (
`birth_date` DATE NOT NULL COMMENT '出生日期 (YYYY-MM-DD)', `birth_date` DATE NOT NULL COMMENT '出生日期 (YYYY-MM-DD)',
`theme_color` VARCHAR(20) DEFAULT '#3B82F6' COMMENT '主题识别色 HEX (如 #3B82F6, #EC4899)', `theme_color` VARCHAR(20) DEFAULT '#3B82F6' COMMENT '主题识别色 HEX (如 #3B82F6, #EC4899)',
`is_default` TINYINT(1) DEFAULT 0 COMMENT '是否为系统默认选中的活跃宝宝 (1:是, 0:否)', `is_default` TINYINT(1) DEFAULT 0 COMMENT '是否为系统默认选中的活跃宝宝 (1:是, 0:否)',
`default_config` JSON NULL COMMENT '宝宝全局行为默认配置 (默认喂养模式、默认亲喂时长、默认瓶喂量)',
`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '档案创建时间', `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '档案创建时间',
`updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后更新时间', `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后更新时间',
INDEX `idx_baby_family` (`family_id`), INDEX `idx_baby_family` (`family_id`),
@@ -105,7 +107,23 @@ CREATE TABLE IF NOT EXISTS `custom_metric` (
INDEX `idx_metric_active` (`is_active`) INDEX `idx_metric_active` (`is_active`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户私人自定义打卡项目配置表'; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户私人自定义打卡项目配置表';
-- 6. 用户体系预留表 (user - 二阶段微信/手机号登录预留) -- 6. 家庭日常备忘待办清单表 (family_memo - 家庭看护团队协同清单)
CREATE TABLE IF NOT EXISTS `family_memo` (
`id` BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '自增主键',
`memo_id` VARCHAR(64) NOT NULL UNIQUE COMMENT '备忘唯一业务ID (如 memo-xxx 或 UUID)',
`family_id` VARCHAR(64) NOT NULL DEFAULT 'family-001' COMMENT '所属家庭ID (关联 family.family_id)',
`content` VARCHAR(255) NOT NULL COMMENT '待办备忘内容',
`due_period` VARCHAR(30) DEFAULT 'today' COMMENT '推荐时段 (morning, afternoon, evening, today 等)',
`is_completed` TINYINT(1) DEFAULT 0 COMMENT '是否已完成 (1:是, 0:否)',
`completed_at` DATETIME NULL COMMENT '完成时刻',
`created_by` VARCHAR(50) DEFAULT '宝妈' COMMENT '创建人称谓',
`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
INDEX `idx_memo_family` (`family_id`, `is_completed`),
INDEX `idx_memo_created` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='家庭日常备忘待办清单表';
-- 7. 用户体系预留表 (user - 二阶段微信/手机号登录预留)
CREATE TABLE IF NOT EXISTS `user` ( CREATE TABLE IF NOT EXISTS `user` (
`id` BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '自增主键', `id` BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '自增主键',
`user_id` VARCHAR(64) NOT NULL UNIQUE COMMENT '用户唯一系统ID', `user_id` VARCHAR(64) NOT NULL UNIQUE COMMENT '用户唯一系统ID',
@@ -127,21 +145,28 @@ INSERT IGNORE INTO `family` (`family_id`, `name`, `invite_code`, `creator_name`,
VALUES ('family-001', '小花园之家', 'YY8888', '宝妈', 1); VALUES ('family-001', '小花园之家', 'YY8888', '宝妈', 1);
-- 初始化默认家庭成员 (多个看护人: 宝爸、宝妈、爷爷、奶奶、外公、外婆、舅舅、舅妈) -- 初始化默认家庭成员 (多个看护人: 宝爸、宝妈、爷爷、奶奶、外公、外婆、舅舅、舅妈)
INSERT IGNORE INTO `family_member` (`family_id`, `role_name`, `is_owner`) INSERT IGNORE INTO `family_member` (`family_id`, `role_name`, `is_owner`, `preferences`)
VALUES VALUES
('family-001', '宝妈', 1), ('family-001', '宝妈', 1, '{"feedingMode":"breastfeed","breastfeedDuration":20,"bottleAmount":120}'),
('family-001', '宝爸', 0), ('family-001', '宝爸', 0, '{"feedingMode":"bottle","bottleAmount":120,"breastfeedDuration":15}'),
('family-001', '爷爷', 0), ('family-001', '爷爷', 0, '{"feedingMode":"bottle","bottleAmount":120}'),
('family-001', '奶奶', 0), ('family-001', '奶奶', 0, '{"feedingMode":"bottle","bottleAmount":100}'),
('family-001', '外公', 0), ('family-001', '外公', 0, '{"feedingMode":"bottle","bottleAmount":120}'),
('family-001', '外婆', 0), ('family-001', '外婆', 0, '{"feedingMode":"bottle","bottleAmount":120}'),
('family-001', '舅舅', 0), ('family-001', '舅舅', 0, '{"feedingMode":"bottle","bottleAmount":120}'),
('family-001', '舅妈', 0); ('family-001', '舅妈', 0, '{"feedingMode":"bottle","bottleAmount":120}');
-- 初始化默认宝宝档案 (默认仅单个宝宝: 嘟嘟) -- 初始化默认宝宝档案 (默认仅单个宝宝: 嘟嘟)
INSERT IGNORE INTO `baby_profile` (`baby_id`, `family_id`, `name`, `gender`, `birth_date`, `theme_color`, `is_default`) INSERT IGNORE INTO `baby_profile` (`baby_id`, `family_id`, `name`, `gender`, `birth_date`, `theme_color`, `is_default`, `default_config`)
VALUES VALUES
('baby-001', 'family-001', '嘟嘟', 'boy', DATE_SUB(CURDATE(), INTERVAL 42 DAY), '#3B82F6', 1); ('baby-001', 'family-001', '嘟嘟', 'boy', DATE_SUB(CURDATE(), INTERVAL 42 DAY), '#3B82F6', 1, '{"feedingMode":"breastfeed","breastfeedDuration":20,"bottleAmount":120}');
-- 初始化默认家庭备忘待办
INSERT IGNORE INTO `family_memo` (`memo_id`, `family_id`, `content`, `due_period`, `is_completed`, `created_by`)
VALUES
('memo-001', 'family-001', '下午3点:准备45℃温水洗澡', 'afternoon', 0, '宝妈'),
('memo-002', 'family-001', '睡前:喂服维生素 D3 滴剂', 'evening', 0, '宝爸'),
('memo-003', 'family-001', '消毒所有奶瓶及吸奶器配件', 'morning', 1, '奶奶');
-- 初始化通用私人自定义目标项 -- 初始化通用私人自定义目标项
INSERT IGNORE INTO `custom_metric` (`metric_id`, `baby_id`, `name`, `icon`, `type`, `unit`, `default_value`, `target_daily`, `is_active`) INSERT IGNORE INTO `custom_metric` (`metric_id`, `baby_id`, `name`, `icon`, `type`, `unit`, `default_value`, `target_daily`, `is_active`)
@@ -284,23 +309,39 @@ DELETE FROM `baby_profile` WHERE `baby_id` = 'baby-002';
*/ */
-- ------------------------------------------------------------------------------ -- ------------------------------------------------------------------------------
-- [Version 1.2.1 -> 1.2.2 变更记录] (执行日期: 2026-09-24) -- [Version 1.2.2 -> 1.3.0 变更记录] (执行日期: 2026-09-24)
-- 变更说明: -- 变更说明:
-- 小花园之家看护人团队角色更新为: 宝爸、宝妈、爷爷、奶奶、外公、外婆、舅舅、舅妈 -- 1. family_member 表新增 preferences JSON 字段存储看护人专属行为记忆偏好
-- 2. baby_profile 表新增 default_config JSON 字段存储宝宝全局行为默认配置
-- ------------------------------------------------------------------------------ -- ------------------------------------------------------------------------------
-- 手动执行 SQL: -- 手动执行 SQL:
/* /*
DELETE FROM `family_member` WHERE `family_id` = 'family-001'; ALTER TABLE `family_member` ADD COLUMN `preferences` JSON NULL COMMENT '角色专属行为偏好';
INSERT INTO `family_member` (`family_id`, `role_name`, `is_owner`) ALTER TABLE `baby_profile` ADD COLUMN `default_config` JSON NULL COMMENT '宝宝默认行为配置';
VALUES */
('family-001', '宝妈', 1),
('family-001', '宝爸', 0), -- ------------------------------------------------------------------------------
('family-001', '爷爷', 0), -- [Version 1.3.0 -> 1.4.0 变更记录] (执行日期: 2026-09-24)
('family-001', '奶奶', 0), -- 变更说明:
('family-001', '外公', 0), -- 新增 family_memo 表,支持家庭日常备忘清单与待办流转
('family-001', '外婆', 0), -- ------------------------------------------------------------------------------
('family-001', '舅舅', 0), -- 手动执行 SQL:
('family-001', '舅妈', 0); /*
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='家庭日常备忘待办清单表';
*/ */
SET FOREIGN_KEY_CHECKS = 1; SET FOREIGN_KEY_CHECKS = 1;
+134 -3
View File
@@ -49,7 +49,7 @@ async function runTests() {
}); });
console.log('2. PUT /api/babies/:babyId:', updateRes.status, 'Success:', updateRes.data.success); console.log('2. PUT /api/babies/:babyId:', updateRes.status, 'Success:', updateRes.data.success);
// 3. Test Custom Metric Creation & Query // 3. Test Custom Metric Creation & Query & Cleanup
const customRes = await request({ const customRes = await request({
hostname: 'localhost', hostname: 'localhost',
path: '/api/custom-metrics', path: '/api/custom-metrics',
@@ -57,13 +57,14 @@ async function runTests() {
headers: { 'Content-Type': 'application/json' } headers: { 'Content-Type': 'application/json' }
}, { }, {
babyId: baby.baby_id, babyId: baby.baby_id,
name: '补充维D3滴剂', name: '临时测试指标',
icon: '💊', icon: '💊',
unit: '滴', unit: '滴',
dailyTarget: 1, dailyTarget: 1,
type: 'count' type: 'count'
}); });
console.log('3. POST /api/custom-metrics:', customRes.status, 'Success:', customRes.data.success); console.log('3. POST /api/custom-metrics:', customRes.status, 'Success:', customRes.data.success);
const testMetricId = customRes.data.data?.metric_id;
const listCustomRes = await request({ const listCustomRes = await request({
hostname: 'localhost', hostname: 'localhost',
@@ -72,6 +73,14 @@ async function runTests() {
}); });
console.log(' GET /api/custom-metrics:', listCustomRes.status, 'Metrics count:', listCustomRes.data.data.length); console.log(' GET /api/custom-metrics:', listCustomRes.status, 'Metrics count:', listCustomRes.data.data.length);
if (testMetricId) {
await request({
hostname: 'localhost',
path: `/api/custom-metrics/${testMetricId}`,
method: 'DELETE'
});
}
// 4. Test Quick Logging: Bottle Record // 4. Test Quick Logging: Bottle Record
const bottleRes = await request({ const bottleRes = await request({
hostname: 'localhost', hostname: 'localhost',
@@ -127,7 +136,129 @@ async function runTests() {
}); });
console.log('7. GET /api/care-guides:', guidesRes.status, 'Guides count:', guidesRes.data.data.length); console.log('7. GET /api/care-guides:', guidesRes.status, 'Guides count:', guidesRes.data.data.length);
console.log('--- All API Tests Passed Successfully! ---'); // 8. Test Family Memos CRUD
console.log('\n--- Testing Family Memos CRUD ---');
const familiesRes = await request({ hostname: 'localhost', path: '/api/families', method: 'GET' });
const testFamilyId = familiesRes.data.data[0].family_id;
// 8a. Create Memo
const createMemoRes = await request({
hostname: 'localhost',
path: '/api/memos',
method: 'POST',
headers: { 'Content-Type': 'application/json' }
}, {
familyId: testFamilyId,
babyId: baby.baby_id,
content: '测试备忘待办:下午3点测温并做抚触操',
duePeriod: 'afternoon',
creatorRole: '宝妈'
});
console.log('8a. POST /api/memos:', createMemoRes.status, 'Memo ID:', createMemoRes.data.data?.memo_id);
const memoId = createMemoRes.data.data?.memo_id;
// 8b. Get Memos
const getMemosRes = await request({
hostname: 'localhost',
path: `/api/memos?familyId=${testFamilyId}`,
method: 'GET'
});
console.log('8b. GET /api/memos:', getMemosRes.status, 'Memos count:', getMemosRes.data.data?.length);
// 8c. Update Memo (mark completed & edit content)
const updateMemoRes = await request({
hostname: 'localhost',
path: `/api/memos/${memoId}`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' }
}, {
content: '测试备忘待办:下午3点测温(已复测正常)',
isCompleted: true,
duePeriod: 'afternoon'
});
console.log('8c. PUT /api/memos/:id (update content & complete):', updateMemoRes.status, 'Success:', updateMemoRes.data.success);
// 8d. Query Historical Memos with Filters (status & search)
const filterMemosRes = await request({
hostname: 'localhost',
path: `/api/memos?familyId=${testFamilyId}&status=completed&search=${encodeURIComponent('测温')}`,
method: 'GET'
});
console.log('8d. GET /api/memos (filter status=completed & search=测温):', filterMemosRes.status, 'Filtered count:', filterMemosRes.data.data?.length);
// 8e. Clear Completed Memos
const clearMemosRes = await request({
hostname: 'localhost',
path: '/api/memos/clear-completed',
method: 'POST',
headers: { 'Content-Type': 'application/json' }
}, {
familyId: testFamilyId
});
console.log('8e. POST /api/memos/clear-completed:', clearMemosRes.status, 'Cleared count:', clearMemosRes.data.affectedRows);
// 9. Test Role Preferences Persistence
console.log('\n--- Testing Role Preferences ---');
const rolePrefRes = await request({
hostname: 'localhost',
path: `/api/families/${testFamilyId}/members/${encodeURIComponent('宝爸')}/preferences`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' }
}, {
preferences: {
defaultFeedingMode: 'bottle',
defaultBottleMl: 150,
defaultBfMinutes: 15
}
});
console.log('9. PUT /api/families/:id/members/:role/preferences:', rolePrefRes.status, 'Success:', rolePrefRes.data.success);
// 10. Test Baby Default Config
console.log('\n--- Testing Baby Default Config ---');
const defaultsRes = await request({
hostname: 'localhost',
path: `/api/babies/${baby.baby_id}/defaults`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' }
}, {
defaultConfig: {
feedingMode: 'breastfeed',
bottleAmountMl: 120,
bfDurationMinutes: 20
}
});
console.log('10. PUT /api/babies/:id/defaults:', defaultsRes.status, 'Success:', defaultsRes.data.success);
// 11. Test Breastfeed Record with Start & End Time + Duration
console.log('\n--- Testing Breastfeed Record with Duration ---');
const now = new Date();
const startTime = new Date(now.getTime() - 25 * 60000);
const pad = n => String(n).padStart(2, '0');
const fmt = d => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
const bfRecordRes = await request({
hostname: 'localhost',
path: '/api/records',
method: 'POST',
headers: { 'Content-Type': 'application/json' }
}, {
babyId: baby.baby_id,
operatorName: '宝妈',
activityType: 'breastfeed',
startTime: fmt(startTime),
endTime: fmt(now),
durationMinutes: 25,
payload: {
leftMinutes: 13,
rightMinutes: 12,
note: '亲喂倒计时专注打卡测试'
}
});
console.log('11. POST /api/records (breastfeed 25min):', bfRecordRes.status, 'Success:', bfRecordRes.data.success);
console.log('\n=============================================');
console.log('🎉 All 11 API End-to-End Tests Passed Successfully!');
console.log('=============================================');
} }
runTests().catch(console.error); runTests().catch(console.error);