优化页面展示

This commit is contained in:
gs committed 2026-09-26 03:58:48 +08:00
1 parent cbcd6b4c7f
commit 1ed38c6648
67 files changed
+4425 -311

No files matched your search

+137
View File
@@ -0,0 +1,137 @@
# Baby Tracker AI 代理与开发者指南 (AGENTS.md)
本文件提炼并规范了 Baby Tracker 项目的核心架构决策、业务原则、代码规范与工程约束,供所有协作 AI Agent 及人类开发者遵循执行。
---
## 1. 核心定位与业务原则
1. **核心场景聚焦**:
- 当前阶段始终聚焦**“顺产 3 天新生儿家庭的每日照护记录工具”**;
- 最关键的三大高频记录:
- **喂养**:亲喂(左右侧独立计时/切换、左右侧时长结构化持久化)、瓶喂(奶量极简化输入与偏好联动);
- **睡眠**:开始/结束时间、持续时长推导;
- **排泄**:嘘嘘/便便及性状观察;
- 弱化非核心干扰:暂不引入复杂家庭多级权限、自定义非标指标、长周期图表预测、复杂管理后台等,优先保证高频操作的极简、顺畅。
2. **用户心智与温馨文案规范**:
- 底部 4 个导航 Tab 统一采用亲切自然的双字词:**【今日】·【记录】·【统计】·【家庭】**;
- **严禁在用户界面使用生硬冷冰的工科或金融技术词汇**(如“流水”必须统一为“记录”,“设置”必须统一为“家庭”或具体业务名称)。
3. **决策文档先行原则**:
- 重大架构、模型或页面调整**必须先在 `/doc` 目录下新建或更新 Markdown 文档**,再进入代码实现;
- 代码与文档不一致时,以最新文档作为下一步调整依据,并在实现后同步更新 `/doc/README.md`。
---
## 2. 数据库规范 (Database Conventions)
1. **主键与 ID 策略**:
- 所有数据表主键统一为 **`id CHAR(32) NOT NULL`**;
- **严禁使用自增主键**,严禁并存业务 ID 与数据库自增 ID;
- 主键必须由后端程序通过雪花算法 (`SnowflakeIdGenerator`) 生成;
- 外键字段保留语义名称(如 `family_id`、`baby_id`、`user_id`),引用的均为目标表的 32 位雪花 ID。
2. **六大标准通用审计字段**(所有业务表必须全部具备):
- `remark`: `VARCHAR(500) NULL COMMENT '备注'`
- `deleted`: `TINYINT(1) NOT NULL DEFAULT 0 COMMENT '删除状态: 0未删除, 1已删除'`
- `created_by`: `VARCHAR(50) NOT NULL DEFAULT 'admin' COMMENT '创建人'`
- `created_time`: `DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间'`
- `updated_by`: `VARCHAR(50) NOT NULL DEFAULT 'admin' COMMENT '修改人'`
- `updated_time`: `DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间'`
3. **关键业务字段约定**:
- 照护记录表 `care_record` 具备专门的亲喂分侧时长字段:`left_duration_minutes INT NULL COMMENT '亲喂左侧时长(分钟)'` 与 `right_duration_minutes INT NULL COMMENT '亲喂右侧时长(分钟)'`,禁止仅将结构化数据以文本拼接混在备注中。
4. **索引约束**:
- **严禁给 `deleted` 字段建立单独索引**,以降低写操作与维护开销。
5. **脚本集中维护规范**:
- **所有 SQL 脚本必须统一在根目录 `/sql` 下维护**,严禁在 `server-java` 内部维护分散副本;
- 增量迁移脚本存放于 `sql/migration/Vx__*.sql`,Maven 构建阶段会自动将其打包映射进 `target/classes/db/migration` 供 Flyway 运行时执行;
- 全新环境与快速建表脚本统一维护在 `sql/schema-full.sql`,每次 DDL 变更需同步保持最新。
---
## 3. 后端开发规范 (Backend Conventions)
- **环境基准**:Java 21 + Spring Boot 3.3.5 + MyBatis-Plus 3.5.9 + MySQL 8.0 + Flyway + Lombok。
### 3.1 实体与审计
1. **基类继承**:所有数据库 Entity 实体类必须继承 `com.babytracker.common.model.BaseEntity`,严禁在子类中重复声明 6 大标准通用字段;
2. **逻辑删除**:`BaseEntity` 中的 `deleted` 字段标注 `@TableLogic`,配合 `application.yml` 配置 `logic-delete-field: deleted`;
3. **自动填充**:
- 必须通过 `AuditFieldFillInterceptor` (`InnerInterceptor`) 与 `AuditMetaObjectHandler` 进行自动填充拦截;
- 插入时自动注入 `created_time`、`updated_time`、`created_by`、`updated_by`、`deleted=0`;更新时自动注入 `updated_time`、`updated_by`;
- 操作人统一通过 `UserContext` (`ThreadLocal`) 获取,**无登录用户时一律默认降级为 `"admin"`**。
### 3.2 接口协议规范
1. **严禁使用 `@PathVariable`**:
- 所有 Controller 接口(查询、更新、新增、删除、状态修改等)**一律不使用 `@PathVariable`**;
- 需要参数的接口统一使用 **`@RequestBody`** 接收请求体对象;
2. **响应统一**:所有端点统一返回 `ApiResponse<T>`,错误状态码与业务提示由 `BusinessException` + `GlobalExceptionHandler` 统一收敛拦截。
### 3.3 模块分层与对象命名 (RO / VO / DTO)
各业务模块(`baby`、`family`、`record`、`summary` 等)统一划分子目录存放模型,严格遵守以下命名规范:
- **`ro/`(请求体 Request Object)**:
- 文件命名:**`xxRO.java`**(如 `CreateBabyRO.java`、`UpdateCareRecordRO.java`、`DeleteMemberRO.java`);
- 职责:专门接收前端 `@RequestBody` 请求体,使用 `jakarta.validation`(如 `@NotBlank`、`@NotNull`)进行参数校验。
- **`vo/`(响应体 View Object)**:
- 文件命名:**`xxVO.java`**(如 `BabyVO.java`、`CareRecordVO.java`、`FamilyContextVO.java`);
- 职责:作为 Controller 向外输出的视图响应模型,隔离内部实体字段。
- **`dto/`(转化体与转换器 Data Transfer Object)**:
- 数据模型命名:**`xxDTO.java`**(如 `BabyDTO.java`、`CareRecordDTO.java`);
- 转化工具类命名:**`xxConvert.java`**(如 `BabyConvert.java`、`CareRecordConvert.java`),提供 Entity / DTO / VO 之间的纯静态映射方法。
- **`mapper/`**:MyBatis-Plus BaseMapper 接口。
- **模块根目录**:仅保留 Entity、Service 与 Controller。
### 3.4 字段注释规范 (Field Documentation)
- **强制要求**:所有实体(Entity)、请求体(`xxRO`)、响应体(`xxVO`)、传输对象(`xxDTO`)的**全部字段必须配备标准 JavaDoc 注释**(`/** 注释内容 */`);
- 注释需注明含义、取值范围(如枚举项说明)及选填/必填约束,保证代码阅读与接口对接的自解释性。
### 3.5 编码规范
- 实体类与模型必须使用 Lombok(`@Data`, `@EqualsAndHashCode(callSuper = true)`);
- 服务层与控制层依赖注入必须使用 `@RequiredArgsConstructor` + `private final`,**严禁使用 `@Autowired` 进行字段注入**;
- 复杂或单表多条件查询优先使用 MyBatis-Plus `LambdaQueryWrapper` / `LambdaUpdateWrapper`,禁止硬编码易错列名。
---
## 4. 前端开发规范 (Frontend Conventions)
- **技术栈**:Vue 3 (Composition API / `<script setup>`) + TypeScript + Vite + Pinia + Vant。
### 4.1 页面与子组件拆分规范
1. **页面精简化(页面仅作为容器)**:
- 路由页面(`src/pages/*.vue`)代码量尽量控制在 100 行左右,专注于路由布局、全局上下文与组件装配;
2. **Tab 模块拆分**:
- 复杂多 Tab 页面(如 `SettingsPage.vue`)必须拆分成独立子组件(如 `components/settings/BabySettingsTab.vue`、`FamilySettingsTab.vue`、`MemberSettingsTab.vue`、`ActionSettingsTab.vue`);
3. **操作弹窗与抽屉拆分**:
- 补录、编辑、切换等重型交互必须抽离为独立子组件(如 `components/timeline/TimelineManualModal.vue`、`TimelineEditModal.vue`);
- 弹窗统一使用 `<van-popup position="bottom" round safe-area-inset-bottom teleport="body">` 保证在视口底部完整呈现,免去页面滚轮上下滑动的不良体验。
### 4.2 接口调用与状态管理
- API 客户端统一在 `src/api/client.ts` 封装;
- 遵循后端协议变更:向后端发送参数时统一以 JSON body(POST/PUT)传递,不再使用 URL 路径拼接参数;
- 业务全局状态集中在 Pinia `stores/careStore.ts`,数据变动后主动触发相关视图局部或看板刷新;
- 类型定义统一收敛在 `src/types/domain.ts` 中,必须通过 `vue-tsc -b` 严格检查;
- **分侧数据兼容性**:展示与编辑时优先使用结构化字段 `leftDurationMinutes` / `rightDurationMinutes`,同时提供平滑降级(兼顾历史记录中存留在备注文本中的分侧信息)。
---
## 5. 编译、打包与部署规范 (Build & Deploy Workflow)
1. **环境注意**:
- 后端需要 Java 21 与 Maven 3.9+。在 Windows PowerShell 下编译时若默认环境非 Java 21,必须前置设置:
```powershell
$env:JAVA_HOME="D:\Java\ms-21.0.7"; $env:Path="D:\Java\apache-maven-3.9.12\bin;D:\Java\ms-21.0.7\bin;" + $env:Path;
```
2. **部署产物规范**:
- **唯一输出归档路径**:`deploy/artifacts/server` 与 `deploy/artifacts/web`;
- 产物目录 `deploy/artifacts` 已被 `.gitignore` 排除,**严禁将构建后的 jar 包或 web 产物提交到 Git 仓库**;
- 构建脚本内置自动复制:
- 后端:`server-java/pom.xml` 中配置了 `maven-antrun-plugin`,打包完成自动将 `baby-tracker-server-0.1.0.jar` 复制到 `deploy/artifacts/server`;
- 前端:`apps/web/package.json` 中的 build 命令配置了 `node scripts/copy-artifacts.mjs`,构建完成自动将 `dist` 内容复制到 `deploy/artifacts/web`。
3. **一键构建脚本**:
- Windows 环境执行:`./build-artifacts.ps1`
- Linux/macOS 环境执行:`./build-artifacts.sh`
4. **服务器部署流程**:
- 在本地或 CI 完成编译后,直接将 `deploy/artifacts` 目录复制到服务器的 `/opt/docker/baby-tracker/deploy/artifacts`;
- 在服务器上执行:
```bash
cd /opt/docker/baby-tracker/deploy && ./deploy.sh
```
- 部署脚本会自动基于已上传产物构建 Docker 镜像并平滑重启容器,整个部署流程轻量闭环。
+211
View File
@@ -0,0 +1,211 @@
# Baby Tracker (新生儿日常照护记录工具)
[![Java 21](https://img.shields.io/badge/Java-21-orange.svg)](https://openjdk.org/projects/jdk/21/)
[![Spring Boot](https://img.shields.io/badge/Spring%20Boot-3.3.5-brightgreen.svg)](https://spring.io/projects/spring-boot)
[![Vue 3](https://img.shields.io/badge/Vue-3.x-green.svg)](https://vuejs.org/)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.x-blue.svg)](https://www.typescriptlang.org/)
[![MyBatis-Plus](https://img.shields.io/badge/MyBatis--Plus-3.5.9-blueviolet.svg)](https://baomidou.com/)
[![License](https://img.shields.io/badge/License-MIT-lightgrey.svg)](LICENSE)
Baby Tracker 是一款专为**新生儿家庭(尤其顺产出院头几周)**量身打造的极简日常照护与健康记录工具。帮助新手爸妈及家庭照顾者在睡眠匮乏、节奏紧凑的环境下,以最低操作负担记录宝宝的高频照护数据,并提供直观的今日概览与统计视图。
---
## 🌟 核心功能与业务聚焦
1. **核心场景深度聚焦**:
- **喂养记录**:
- **母乳亲喂**:支持左/右侧开始、实时秒级分侧独立计时与无缝切换;提供快捷预设时长(10/15/20/30分钟)一键记录并自动按侧别推导起止时间;数据库具备结构化独立字段 `left_duration_minutes` 与 `right_duration_minutes`;
- **瓶喂记录**:奶量步进调节极简化展示,默认数值与用户偏好配置实时联动。
- **睡眠记录**:入睡计时、醒来打卡、睡眠时长自动推导计算。
- **排泄观察**:小便(嘘嘘)、大便(便便)次数记录与性状特征观察。
2. **贴心的人性化导航(双字对仗)**:
- **今日**(`/today`):宝宝状态卡片、实时分侧亲喂计时与一键打卡主阵地;
- **记录**(`/timeline`):取代生硬金融词“流水”,清晰查阅历史照护时间线明细,支持就近弹窗编辑与补录;
- **统计**(`/stats`):全天喂养频次、睡眠总时长、尿布排泄次数事实汇总,喂养方式中文直观呈现;
- **家庭**(`/settings`):取代生硬工科词“设置”,承载宝宝成长档案、全家成员角色(爸/妈/月嫂/长辈)协同与照护习惯。
3. **多宝宝与多成员协同**:
- 今日顶部一体化信息卡片,直观呈现宝宝月龄天数与当前记录人;
- 底部半屏抽屉式切换,一键平滑切换当前照护宝宝与署名看护人。
4. **极简操作交互**:
- 专为移动端(H5 / 微信内浏览 / 手机浏览器)优化的一触即达操作流程;
- 弱化非核心干扰:暂不引入复杂长周期图表与冗余权限配置,操作即所得。
---
## 🛠️ 技术栈与架构概览
### 前端 (Web / H5)
- **核心框架**:Vue 3 (Composition API / `<script setup>`) + TypeScript 5
- **构建工具**:Vite 5
- **状态管理**:Pinia 2
- **UI 组件库**:Vant 4(移动端轻量级组件库)
- **类型安全**:`src/types/domain.ts` 集中收敛,`vue-tsc -b` 严格检查
### 后端 (Server)
- **语言基准**:Java 21
- **核心框架**:Spring Boot 3.3.5
- **ORM / 持久层**:MyBatis-Plus 3.5.9
- **数据库**:MySQL 8.0+
- **数据库迁移**:Flyway 10.x(增量脚本统一维护于 `sql/migration/`)
- **主键算法**:自定义 32 位雪花算法(`SnowflakeIdGenerator`)
- **代码规范**:Lombok、全字段 JavaDoc 详尽注释、Controller 统一 `@RequestBody`、统一响应体 `ApiResponse<T>`
### 部署与运维
- **容器化**:Docker + Docker Compose
- **Web 代理**:Nginx
- **产物归档**:一键脚本自动化构建打包至 `deploy/artifacts`(Server jar + Web 静态资源)
---
## 📁 目录结构
```text
baby-tracker/
├── AGENTS.md # AI Agent 与开发者协作规范及核心开发准则
├── README.md # 项目综合说明文档(本文件)
├── build-artifacts.ps1 # Windows 一键编译与产物归档脚本
├── build-artifacts.sh # Linux/macOS 一键编译与产物归档脚本
├── apps/
│ └── web/ # 前端 Vue 3 + TypeScript 移动端 H5 工程
│ ├── src/
│ │ ├── api/ # 后端 API 请求客户端封装
│ │ ├── components/ # 业务与公共组件(Tab/抽屉/弹窗独立维护)
│ │ ├── pages/ # 路由页面(容器化,聚焦布局与状态分发)
│ │ ├── stores/ # Pinia 状态管理
│ │ ├── types/ # 全局领域类型声明
│ │ └── utils/ # 格式化与业务转换工具库
│ └── package.json
├── server-java/ # 后端 Spring Boot 3 + Java 21 工程
│ ├── src/main/java/com/babytracker/
│ │ ├── common/ # 公共配置、模型(BaseEntity)、异常、拦截器
│ │ └── module/ # 业务模块(baby、family、record、summary)
│ │ ├── ro/ # Request Object 请求参数对象(全字段 Javadoc)
│ │ ├── vo/ # View Object 响应视图对象(全字段 Javadoc)
│ │ ├── dto/ # Data Transfer Object 传输对象及转换器
│ │ ├── mapper/ # MyBatis-Plus BaseMapper 映射器
│ │ └── ...Service & Controller
│ └── pom.xml
├── sql/ # 数据库脚本全生命周期统一维护目录
│ ├── migration/ # Flyway 增量演变脚本 (V1__*, V2__*, V3__* 等)
│ ├── schema-full.sql # 全新环境快速一键建表脚本(含亲喂分侧等最新字段)
│ └── README.md # 数据库规范与说明
├── deploy/ # 生产部署与容器化目录
│ ├── artifacts/ # 构建产物目录(.gitignore 忽略,部署包归档)
│ ├── docker-compose.yml # 容器编排服务定义(Server + Web + MySQL)
│ ├── Dockerfile.server # 后端运行镜像定义
│ ├── Dockerfile.web # 前端 Nginx 运行镜像定义
│ └── deploy.sh # 服务器平滑构建部署脚本
└── doc/ # 历史架构决策、调整记录与演进文档
```
---
## 🚀 快速上手 (本地开发)
### 1. 环境准备
- **Java**:JDK 21
- **Node.js**:v18+ 及 npm
- **Maven**:3.9+
- **MySQL**:8.0+
### 2. 数据库配置
1. 创建本地数据库:
```sql
CREATE DATABASE baby_tracker CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
```
2. 后端集成了 Flyway,启动时会自动按顺序执行 `sql/migration/` 下的迁移脚本,无需手动导入全量 SQL。
### 3. 后端服务启动
在 Windows PowerShell 环境下:
```powershell
# 若本地默认 Java 非 JDK 21,先声明环境变量
$env:JAVA_HOME="D:\Java\ms-21.0.7"
$env:Path="D:\Java\apache-maven-3.9.12\bin;D:\Java\ms-21.0.7\bin;" + $env:Path
cd server-java
mvn spring-boot:run
```
后端服务默认监听在 `http://localhost:8080`,健康检查接口:`http://localhost:8080/api/health`。
### 4. 前端应用启动
```bash
cd apps/web
npm install
npm run dev
```
前端开发服务启动后访问:`http://localhost:5173`。Vite 会将 `/api` 请求自动反向代理到本地后端的 `8080` 端口。
---
## 📦 一键构建与打包
项目提供了跨平台的一键构建脚本,会自动完成前后端编译并将可部署产物归档至 `deploy/artifacts/` 目录:
- **Windows 用户**:
```powershell
./build-artifacts.ps1
```
- **Linux / macOS 用户**:
```bash
chmod +x build-artifacts.sh
./build-artifacts.sh
```
构建完成后,将自动生成并归档:
- `deploy/artifacts/server/baby-tracker-server-0.1.0.jar`
- `deploy/artifacts/web/`(前端静态 html/js/css 资源)
---
## 🚢 服务器容器化部署
1. **上传产物与配置文件**:
将项目中的 `deploy/` 目录整体同步至服务器(例如 `/opt/docker/baby-tracker/deploy`)。
2. **在服务器上执行部署**:
```bash
cd /opt/docker/baby-tracker/deploy
chmod +x deploy.sh
./deploy.sh
```
3. `deploy.sh` 脚本会自动:
- 检查 `artifacts/` 下的前后端构建包;
- 执行 `docker compose build` 构建轻量级生产镜像;
- 启动并平滑拉起 MySQL 容器、Spring Boot 容器以及 Nginx 前端容器。
---
## 📐 核心设计与协作规范
在对本项目进行功能新增或重构开发时,**必须严格遵循以下原则**(详细规范参见 [AGENTS.md](./AGENTS.md)):
1. **主键与 ID 规范**:所有表统一使用 `CHAR(32)` 字符串主键,由后端雪花算法生成,**严禁使用自增主键**。
2. **通用审计字段**:所有业务表必须具备 6 大标准通用审计字段(`remark`, `deleted`, `created_by`, `created_time`, `updated_by`, `updated_time`),通过 MyBatis-Plus 拦截器统一填充,逻辑删除使用 `@TableLogic`。
3. **接口传参规范**:所有 Controller 接口**一律严禁使用 `@PathVariable`**,一律使用 `@RequestBody` 接收统一命名的请求对象。
4. **模型分层与注释规范**:
- `ro/`:接收前端入参(`xxRO.java`);
- `vo/`:输出前端视图响应(`xxVO.java`);
- `dto/`:层间数据传输与静态转换工具(`xxDTO.java`、`xxConvert.java`);
- 所有 Entity、RO、VO、DTO 字段**必须配备清晰规范的 JavaDoc 注释**。
5. **前端组件拆分与文案贴心化**:
- 页面文件(`pages/*.vue`)仅作为容器保持简洁;
- 底部 4 个导航 Tab 统一为:**今日 · 记录 · 统计 · 家庭**;
- 复杂多 Tab 与弹窗/抽屉表单必须下沉至 `components/` 独立子组件维护。
6. **SQL 维护唯一源**:所有 SQL 脚本统一在根目录 `sql/` 下维护,禁止在 `server-java` 内部保留分散副本。
---
## 📖 相关文档索引
详细的设计决策与各版本重构历程请参阅 [doc/ 目录](./doc/):
- [总架构与演进规划方案](./doc/architecture-adjustment-plan.md)
- [32 位雪花 ID 生成与数据库主键策略](./doc/2026-09-26-id-strategy.md)
- [MyBatis-Plus 集成与 SQL 操作优化](./doc/2026-09-26-mybatis-plus-integration.md)
- [审计字段统一、RO/VO/DTO 分层与接口规范](./doc/2026-09-26-audit-fields-ro-vo-dto-restructure.md)
- [前端设置与流水页面组件化重构](./doc/2026-09-26-frontend-settings-timeline-component-split.md)
- [部署脚本自动化与产物自闭环优化](./doc/2026-09-26-deploy-script-optimization.md)
- [亲喂左右侧分别计时切换与瓶喂奶量设置优化](./doc/2026-09-26-breastfeeding-split-timer-and-bottle-settings.md)
- [今日 Tab 顶部宝宝信息展示与切换交互优化](./doc/2026-09-26-today-header-and-switchers-optimization.md)
- [流水编辑弹窗位置修复与亲喂总时长起止时间优化](./doc/2026-09-26-timeline-edit-modal-and-feeding-duration-optimization.md)
- [底部导航与页面文案贴心化(今日·记录·统计·家庭)优化](./doc/2026-09-26-navigation-tabs-wording-optimization.md)
- [亲喂左右侧时长独立字段架构设计与落地](./doc/2026-09-26-breastfeeding-split-duration-fields.md)
+2 -2
View File
@@ -1,9 +1,9 @@
<script setup lang="ts"> <script setup lang="ts">
const tabs = [ const tabs = [
{ to: '/today', label: '今日' }, { to: '/today', label: '今日' },
{ to: '/timeline', label: '流水' }, { to: '/timeline', label: '记录' },
{ to: '/stats', label: '统计' }, { to: '/stats', label: '统计' },
{ to: '/settings', label: '设置' } { to: '/settings', label: '家庭' }
] ]
</script> </script>
+20 -4
View File
@@ -10,6 +10,7 @@ import type {
FamilyInfo, FamilyInfo,
FamilyMember, FamilyMember,
FeedingMethod, FeedingMethod,
ServerTimeInfo,
UpdateCareRecordPayload, UpdateCareRecordPayload,
UpdateFamilyPayload, UpdateFamilyPayload,
UpdateMemberPayload UpdateMemberPayload
@@ -98,15 +99,23 @@ export function getDailySummary(babyId: string) {
return request<DailySummary>(`/api/v1/summary/daily?babyId=${encodeURIComponent(babyId)}`) return request<DailySummary>(`/api/v1/summary/daily?babyId=${encodeURIComponent(babyId)}`)
} }
export function getRecords(babyId: string) { export function getRecords(babyId: string, date?: string) {
return request<CareRecord[]>(`/api/v1/records?babyId=${encodeURIComponent(babyId)}`) const query = date
? `/api/v1/records?babyId=${encodeURIComponent(babyId)}&date=${encodeURIComponent(date)}`
: `/api/v1/records?babyId=${encodeURIComponent(babyId)}`
return request<CareRecord[]>(query)
} }
export function createFeeding(payload: { export function createFeeding(payload: {
babyId: string babyId: string
feedingMethod: FeedingMethod feedingMethod: FeedingMethod
amountMl?: number amountMl?: number
breastSide?: 'left' | 'right' breastSide?: string
durationMinutes?: number
feedingTime?: string
endTime?: string
leftDurationMinutes?: number
rightDurationMinutes?: number
operatorName: string operatorName: string
remark?: string remark?: string
note?: string note?: string
@@ -135,7 +144,9 @@ export function startFeeding(payload: {
export function endFeeding(payload: { export function endFeeding(payload: {
babyId: string babyId: string
breastSide: 'left' | 'right' breastSide?: 'left' | 'right'
leftDurationMinutes?: number
rightDurationMinutes?: number
operatorName: string operatorName: string
remark?: string remark?: string
note?: string note?: string
@@ -197,3 +208,8 @@ export function updateRecord(recordId: string, payload: UpdateCareRecordPayload)
body: JSON.stringify({ ...payload, recordId }) body: JSON.stringify({ ...payload, recordId })
}) })
} }
export function getServerTime() {
return request<ServerTimeInfo>('/api/v1/system/time')
}
@@ -2,6 +2,7 @@
import { onMounted, reactive, ref, watch } from 'vue' import { onMounted, reactive, ref, watch } from 'vue'
import { showToast } from 'vant' import { showToast } from 'vant'
import { useCareStore } from '../../stores/careStore' import { useCareStore } from '../../stores/careStore'
import { getLocalDateStr } from '../../utils/format'
const store = useCareStore() const store = useCareStore()
@@ -18,7 +19,7 @@ const showAddBabyModal = ref(false)
const newBabyForm = reactive({ const newBabyForm = reactive({
name: '', name: '',
gender: 'boy', gender: 'boy',
birthDate: new Date().toISOString().slice(0, 10), birthDate: getLocalDateStr(store.getServerNow()),
deliveryType: 'natural', deliveryType: 'natural',
isDefault: false isDefault: false
}) })
@@ -58,7 +59,7 @@ async function saveBaby() {
function openAddBabyModal() { function openAddBabyModal() {
newBabyForm.name = '' newBabyForm.name = ''
newBabyForm.gender = 'boy' newBabyForm.gender = 'boy'
newBabyForm.birthDate = new Date().toISOString().slice(0, 10) newBabyForm.birthDate = getLocalDateStr(store.getServerNow())
newBabyForm.deliveryType = 'natural' newBabyForm.deliveryType = 'natural'
newBabyForm.isDefault = false newBabyForm.isDefault = false
showAddBabyModal.value = true showAddBabyModal.value = true
@@ -158,11 +159,18 @@ async function handleSetDefaultBaby(babyId: string) {
</div> </div>
<!-- 弹窗:添加新宝宝 --> <!-- 弹窗:添加新宝宝 -->
<div v-if="showAddBabyModal" class="modal-backdrop" @click.self="showAddBabyModal = false"> <van-popup
<div class="modal-sheet"> v-model:show="showAddBabyModal"
position="bottom"
round
safe-area-inset-bottom
teleport="body"
class="timeline-modal-popup"
>
<div class="modal-sheet-inner">
<div class="modal-header"> <div class="modal-header">
<h3>添加宝宝档案</h3> <h3>添加宝宝档案</h3>
<button class="close-btn" @click="showAddBabyModal = false">×</button> <button class="close-btn" type="button" @click="showAddBabyModal = false">×</button>
</div> </div>
<div class="modal-form"> <div class="modal-form">
<label> <label>
@@ -192,11 +200,11 @@ async function handleSetDefaultBaby(babyId: string) {
<label for="setDefCheck" style="font-size: 14px; cursor: pointer; color: #1f2933;">设为当前默认关注的宝宝</label> <label for="setDefCheck" style="font-size: 14px; cursor: pointer; color: #1f2933;">设为当前默认关注的宝宝</label>
</div> </div>
<div class="modal-actions"> <div class="modal-actions">
<button class="secondary-button" @click="showAddBabyModal = false">取消</button> <button class="secondary-button" type="button" @click="showAddBabyModal = false">取消</button>
<button class="save-button" @click="submitAddBaby">确认添加</button> <button class="save-button" type="button" @click="submitAddBaby">确认添加</button>
</div>
</div> </div>
</div> </div>
</div> </div>
</van-popup>
</section> </section>
</template> </template>
@@ -135,11 +135,18 @@ function selectOperator(name: string) {
</div> </div>
<!-- 弹窗:添加/编辑家庭成员 --> <!-- 弹窗:添加/编辑家庭成员 -->
<div v-if="showMemberModal" class="modal-backdrop" @click.self="showMemberModal = false"> <van-popup
<div class="modal-sheet"> v-model:show="showMemberModal"
position="bottom"
round
safe-area-inset-bottom
teleport="body"
class="timeline-modal-popup"
>
<div class="modal-sheet-inner">
<div class="modal-header"> <div class="modal-header">
<h3>{{ isEditingMember ? '修改照护成员' : '添加照护成员' }}</h3> <h3>{{ isEditingMember ? '修改照护成员' : '添加照护成员' }}</h3>
<button class="close-btn" @click="showMemberModal = false">×</button> <button class="close-btn" type="button" @click="showMemberModal = false">×</button>
</div> </div>
<div class="modal-form"> <div class="modal-form">
<label> <label>
@@ -174,13 +181,13 @@ function selectOperator(name: string) {
<label for="defOpCheck" style="font-size: 14px; cursor: pointer; color: #1f2933;">设为默认记录人</label> <label for="defOpCheck" style="font-size: 14px; cursor: pointer; color: #1f2933;">设为默认记录人</label>
</div> </div>
<div class="modal-actions"> <div class="modal-actions">
<button class="secondary-button" @click="showMemberModal = false">取消</button> <button class="secondary-button" type="button" @click="showMemberModal = false">取消</button>
<button class="save-button" @click="submitMember"> <button class="save-button" type="button" @click="submitMember">
{{ isEditingMember ? '保存修改' : '确认添加' }} {{ isEditingMember ? '保存修改' : '确认添加' }}
</button> </button>
</div> </div>
</div> </div>
</div> </div>
</div> </van-popup>
</section> </section>
</template> </template>
@@ -2,6 +2,7 @@
import { reactive, watch } from 'vue' import { reactive, watch } from 'vue'
import { showToast } from 'vant' import { showToast } from 'vant'
import { useCareStore } from '../../stores/careStore' import { useCareStore } from '../../stores/careStore'
import { parseFeedingSplitInfo } from '../../utils/format'
import type { CareRecord, ExcretionType, FeedingMethod, RecordType } from '../../types/domain' import type { CareRecord, ExcretionType, FeedingMethod, RecordType } from '../../types/domain'
const props = defineProps<{ const props = defineProps<{
@@ -28,7 +29,9 @@ const editForm = reactive({
durationMinutes: null as number | null, durationMinutes: null as number | null,
feedingMethod: 'breastfeed' as FeedingMethod, feedingMethod: 'breastfeed' as FeedingMethod,
amountMl: null as number | null, amountMl: null as number | null,
breastSide: 'left' as 'left' | 'right', breastMode: 'both' as 'left' | 'right' | 'both',
leftMinutes: null as number | null,
rightMinutes: null as number | null,
excretionType: 'pee' as ExcretionType, excretionType: 'pee' as ExcretionType,
operatorName: '', operatorName: '',
note: '' note: ''
@@ -60,11 +63,104 @@ function initFromRecord(record: CareRecord) {
editForm.durationMinutes = record.durationMinutes || null editForm.durationMinutes = record.durationMinutes || null
editForm.feedingMethod = (record.feedingMethod as FeedingMethod) || 'breastfeed' editForm.feedingMethod = (record.feedingMethod as FeedingMethod) || 'breastfeed'
editForm.amountMl = record.amountMl || null editForm.amountMl = record.amountMl || null
const noteStr = record.note || record.remark || '' const noteStr = record.note || record.remark || ''
editForm.breastSide = noteStr.includes('右侧') ? 'right' : 'left' const splitInfo = (record.leftDurationMinutes != null || record.rightDurationMinutes != null)
? { leftMinutes: record.leftDurationMinutes ?? undefined, rightMinutes: record.rightDurationMinutes ?? undefined }
: parseFeedingSplitInfo(noteStr, record.durationMinutes)
if (splitInfo?.leftMinutes && splitInfo?.rightMinutes) {
editForm.breastMode = 'both'
editForm.leftMinutes = splitInfo.leftMinutes
editForm.rightMinutes = splitInfo.rightMinutes
} else if (splitInfo?.leftMinutes) {
editForm.breastMode = 'left'
editForm.leftMinutes = splitInfo.leftMinutes
editForm.rightMinutes = null
} else if (splitInfo?.rightMinutes) {
editForm.breastMode = 'right'
editForm.rightMinutes = splitInfo.rightMinutes
editForm.leftMinutes = null
} else {
editForm.breastMode = noteStr.includes('右侧') ? 'right' : 'left'
if (record.durationMinutes) {
if (editForm.breastMode === 'left') editForm.leftMinutes = record.durationMinutes
else editForm.rightMinutes = record.durationMinutes
}
}
editForm.excretionType = (record.excretionType as ExcretionType) || 'pee' editForm.excretionType = (record.excretionType as ExcretionType) || 'pee'
editForm.operatorName = record.operatorName || store.operatorName editForm.operatorName = record.operatorName || store.operatorName
editForm.note = noteStr // 清理前置亲喂标签,保留真实备注
editForm.note = noteStr.replace(/亲喂侧:[^;;]+[;;]?\s*/g, '').trim()
if (editForm.recordType === 'feeding' && editForm.feedingMethod === 'breastfeed' && !editForm.hasEndTime && editForm.durationMinutes) {
autoUpdateEndTime()
}
}
function handleBreastModeChange(mode: 'left' | 'right' | 'both') {
editForm.breastMode = mode
const currentTotal = editForm.durationMinutes || 20
if (mode === 'both') {
editForm.leftMinutes = Math.floor(currentTotal / 2) || 10
editForm.rightMinutes = Math.ceil(currentTotal / 2) || 10
editForm.durationMinutes = (editForm.leftMinutes || 0) + (editForm.rightMinutes || 0)
} else if (mode === 'left') {
editForm.leftMinutes = currentTotal || 20
editForm.rightMinutes = null
editForm.durationMinutes = editForm.leftMinutes
} else {
editForm.rightMinutes = currentTotal || 20
editForm.leftMinutes = null
editForm.durationMinutes = editForm.rightMinutes
}
autoUpdateEndTime()
}
function onSplitMinutesChange() {
if (editForm.breastMode === 'both') {
editForm.durationMinutes = (editForm.leftMinutes || 0) + (editForm.rightMinutes || 0)
} else if (editForm.breastMode === 'left') {
editForm.durationMinutes = editForm.leftMinutes || 0
} else {
editForm.durationMinutes = editForm.rightMinutes || 0
}
autoUpdateEndTime()
}
function onTotalDurationChange() {
const total = editForm.durationMinutes || 0
if (editForm.breastMode === 'both') {
editForm.leftMinutes = Math.floor(total / 2)
editForm.rightMinutes = Math.ceil(total / 2)
} else if (editForm.breastMode === 'left') {
editForm.leftMinutes = total
editForm.rightMinutes = null
} else {
editForm.rightMinutes = total
editForm.leftMinutes = null
}
autoUpdateEndTime()
}
function autoUpdateEndTime() {
if (!editForm.startDate || !editForm.startTimeStr || !editForm.durationMinutes) return
try {
const startMs = new Date(`${editForm.startDate}T${editForm.startTimeStr}:00`).getTime()
if (isNaN(startMs)) return
const endMs = startMs + editForm.durationMinutes * 60000
const endDateObj = new Date(endMs)
const y = endDateObj.getFullYear()
const m = String(endDateObj.getMonth() + 1).padStart(2, '0')
const d = String(endDateObj.getDate()).padStart(2, '0')
const hh = String(endDateObj.getHours()).padStart(2, '0')
const mm = String(endDateObj.getMinutes()).padStart(2, '0')
editForm.endDate = `${y}-${m}-${d}`
editForm.endTimeStr = `${hh}:${mm}`
editForm.hasEndTime = true
} catch {
// ignore
}
} }
function appendNote(tag: string) { function appendNote(tag: string) {
@@ -83,13 +179,7 @@ async function submitEdit() {
endTime = `${editForm.endDate}T${editForm.endTimeStr}:00` endTime = `${editForm.endDate}T${editForm.endTimeStr}:00`
} }
let finalNote = editForm.note const finalNote = editForm.note.trim()
if (editForm.recordType === 'feeding' && editForm.feedingMethod === 'breastfeed' && editForm.breastSide) {
const sideText = editForm.breastSide === 'left' ? '左侧' : '右侧'
if (!finalNote.includes('亲喂侧')) {
finalNote = `亲喂侧: ${sideText}${finalNote ? ';' + finalNote : ''}`
}
}
try { try {
await store.editRecord(props.record.recordId, { await store.editRecord(props.record.recordId, {
@@ -97,6 +187,8 @@ async function submitEdit() {
startTime, startTime,
endTime, endTime,
durationMinutes: editForm.durationMinutes, durationMinutes: editForm.durationMinutes,
leftDurationMinutes: editForm.recordType === 'feeding' && editForm.feedingMethod === 'breastfeed' ? (editForm.breastMode === 'right' ? null : editForm.leftMinutes) : null,
rightDurationMinutes: editForm.recordType === 'feeding' && editForm.feedingMethod === 'breastfeed' ? (editForm.breastMode === 'left' ? null : editForm.rightMinutes) : null,
feedingMethod: editForm.recordType === 'feeding' ? editForm.feedingMethod : null, feedingMethod: editForm.recordType === 'feeding' ? editForm.feedingMethod : null,
amountMl: editForm.recordType === 'feeding' && editForm.feedingMethod !== 'breastfeed' ? editForm.amountMl : null, amountMl: editForm.recordType === 'feeding' && editForm.feedingMethod !== 'breastfeed' ? editForm.amountMl : null,
excretionType: editForm.recordType === 'excretion' ? editForm.excretionType : null, excretionType: editForm.recordType === 'excretion' ? editForm.excretionType : null,
@@ -113,11 +205,19 @@ async function submitEdit() {
</script> </script>
<template> <template>
<div v-if="props.show" class="modal-backdrop" @click.self="emit('update:show', false)"> <van-popup
<div class="modal-sheet"> :show="props.show"
position="bottom"
round
safe-area-inset-bottom
teleport="body"
class="timeline-modal-popup"
@update:show="(val: boolean) => emit('update:show', val)"
>
<div class="modal-sheet-inner">
<div class="modal-header"> <div class="modal-header">
<h3>编辑照护记录</h3> <h3>编辑照护记录</h3>
<button class="close-btn" @click="emit('update:show', false)">×</button> <button class="close-btn" type="button" @click="emit('update:show', false)">×</button>
</div> </div>
<div class="modal-form"> <div class="modal-form">
@@ -152,19 +252,19 @@ async function submitEdit() {
</div> </div>
</label> </label>
<!-- 发生时间 --> <!-- 开始起止时间设置 -->
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;"> <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
<label> <label>
开始日期 开始日期
<input v-model="editForm.startDate" type="date" /> <input v-model="editForm.startDate" type="date" @change="autoUpdateEndTime" />
</label> </label>
<label> <label>
开始时间 开始时间
<input v-model="editForm.startTimeStr" type="time" /> <input v-model="editForm.startTimeStr" type="time" @change="autoUpdateEndTime" />
</label> </label>
</div> </div>
<!-- 喂奶特定字段 --> <!-- 喂奶专属表单 -->
<template v-if="editForm.recordType === 'feeding'"> <template v-if="editForm.recordType === 'feeding'">
<label> <label>
喂养方式 喂养方式
@@ -176,77 +276,72 @@ async function submitEdit() {
</select> </select>
</label> </label>
<div v-if="editForm.feedingMethod === 'breastfeed'"> <!-- 亲喂:侧别与分侧耗时 -->
<label> <div v-if="editForm.feedingMethod === 'breastfeed'" style="background: #faf7f2; border: 1px solid #eee5d8; border-radius: 12px; padding: 12px;">
亲喂侧 <label style="margin-bottom: 8px;">
亲喂模式
<div class="chip-group"> <div class="chip-group">
<button <button
type="button" type="button"
class="chip sm" class="chip sm"
:class="{ active: editForm.breastSide === 'left' }" :class="{ active: editForm.breastMode === 'both' }"
@click="editForm.breastSide = 'left'" @click="handleBreastModeChange('both')"
> >
左侧 双侧 (左右各喂)
</button> </button>
<button <button
type="button" type="button"
class="chip sm" class="chip sm"
:class="{ active: editForm.breastSide === 'right' }" :class="{ active: editForm.breastMode === 'left' }"
@click="editForm.breastSide = 'right'" @click="handleBreastModeChange('left')"
> >
右侧 仅左侧
</button>
<button
type="button"
class="chip sm"
:class="{ active: editForm.breastMode === 'right' }"
@click="handleBreastModeChange('right')"
>
仅右侧
</button> </button>
</div> </div>
</label> </label>
<!-- 分侧耗时 -->
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 8px;">
<label v-if="editForm.breastMode === 'left' || editForm.breastMode === 'both'">
左侧耗时 (分钟)
<input v-model.number="editForm.leftMinutes" type="number" min="0" max="120" placeholder="分钟" @input="onSplitMinutesChange" />
</label>
<label v-if="editForm.breastMode === 'right' || editForm.breastMode === 'both'">
右侧耗时 (分钟)
<input v-model.number="editForm.rightMinutes" type="number" min="0" max="120" placeholder="分钟" @input="onSplitMinutesChange" />
</label>
</div> </div>
<div v-else> <!-- 总时长 -->
<label> <label style="margin-top: 8px;">
奶量 (ml) 亲喂总时长 (分钟)
<div style="display: flex; gap: 8px; align-items: center;"> <input v-model.number="editForm.durationMinutes" type="number" min="1" max="180" @input="onTotalDurationChange" />
<input v-model.number="editForm.amountMl" type="number" placeholder="输入奶量 ml" />
<div class="chip-group" style="margin: 0;">
<button
v-for="amt in [30, 60, 90, 120]"
:key="amt"
type="button"
class="chip sm"
:class="{ active: editForm.amountMl === amt }"
@click="editForm.amountMl = amt"
>
{{ amt }}
</button>
</div>
</div>
</label> </label>
</div> </div>
<label v-else>
单次奶量 (ml)
<input v-model.number="editForm.amountMl" type="number" min="5" max="400" step="5" />
</label>
</template> </template>
<!-- 睡眠特定字段 --> <!-- 睡眠专属表单 -->
<template v-if="editForm.recordType === 'sleep'"> <template v-if="editForm.recordType === 'sleep'">
<div style="display: flex; align-items: center; gap: 8px; margin: 4px 0;">
<input id="editHasEnd" v-model="editForm.hasEndTime" type="checkbox" style="width: 18px; height: 18px;" />
<label for="editHasEnd" style="font-size: 14px; cursor: pointer; color: #1f2933;">包含醒来结束时间</label>
</div>
<div v-if="editForm.hasEndTime" style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
<label> <label>
醒来日期 睡眠时长 (分钟)
<input v-model="editForm.endDate" type="date" /> <input v-model.number="editForm.durationMinutes" type="number" min="1" placeholder="留空则按起止时间自动计算" @input="autoUpdateEndTime" />
</label>
<label>
醒来时间
<input v-model="editForm.endTimeStr" type="time" />
</label>
</div>
<label v-if="!editForm.hasEndTime">
睡眠持续时间 (分钟,可选)
<input v-model.number="editForm.durationMinutes" type="number" placeholder="例如:45" />
</label> </label>
</template> </template>
<!-- 排泄特定字段 --> <!-- 排泄专属表单 -->
<template v-if="editForm.recordType === 'excretion'"> <template v-if="editForm.recordType === 'excretion'">
<label> <label>
排泄类型 排泄类型
@@ -257,7 +352,7 @@ async function submitEdit() {
:class="{ active: editForm.excretionType === 'pee' }" :class="{ active: editForm.excretionType === 'pee' }"
@click="editForm.excretionType = 'pee'" @click="editForm.excretionType = 'pee'"
> >
💧 嘘嘘 (尿尿) 💧 小便 (尿尿)
</button> </button>
<button <button
type="button" type="button"
@@ -265,13 +360,31 @@ async function submitEdit() {
:class="{ active: editForm.excretionType === 'poop' }" :class="{ active: editForm.excretionType === 'poop' }"
@click="editForm.excretionType = 'poop'" @click="editForm.excretionType = 'poop'"
> >
💩 便便 (大便) 💩 大便 (便便)
</button> </button>
</div> </div>
</label> </label>
</template> </template>
<!-- 记录人选择 --> <!-- 结束时间(选填/联动) -->
<div style="border-top: 1px dashed #e8e3d8; padding-top: 10px;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
<span style="font-size: 13px; font-weight: 700; color: #4b5563;">记录结束时间</span>
<input v-model="editForm.hasEndTime" type="checkbox" style="width: 18px; height: 18px;" />
</div>
<div v-if="editForm.hasEndTime" style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
<label>
结束日期
<input v-model="editForm.endDate" type="date" />
</label>
<label>
结束时间
<input v-model="editForm.endTimeStr" type="time" />
</label>
</div>
</div>
<!-- 记录人 -->
<label> <label>
记录人称谓 记录人称谓
<input v-model="editForm.operatorName" placeholder="例如:宝妈、宝爸" /> <input v-model="editForm.operatorName" placeholder="例如:宝妈、宝爸" />
@@ -307,10 +420,10 @@ async function submitEdit() {
</label> </label>
<div class="modal-actions"> <div class="modal-actions">
<button class="secondary-button" @click="emit('update:show', false)">取消</button> <button class="secondary-button" type="button" @click="emit('update:show', false)">取消</button>
<button class="save-button" @click="submitEdit">保存修改</button> <button class="save-button" type="button" @click="submitEdit">保存修改</button>
</div>
</div> </div>
</div> </div>
</div> </div>
</van-popup>
</template> </template>
@@ -3,6 +3,7 @@ import { reactive, watch } from 'vue'
import { showToast } from 'vant' import { showToast } from 'vant'
import { useCareStore } from '../../stores/careStore' import { useCareStore } from '../../stores/careStore'
import type { ExcretionType, FeedingMethod, RecordType } from '../../types/domain' import type { ExcretionType, FeedingMethod, RecordType } from '../../types/domain'
import { getLocalDateStr, getLocalTimeStr } from '../../utils/format'
const props = defineProps<{ const props = defineProps<{
show: boolean show: boolean
@@ -17,17 +18,20 @@ const store = useCareStore()
const quickNotes = ['拍嗝顺利', '溢奶微量', '金黄色便便', '安睡无闹', '微胀气', '吃得香'] const quickNotes = ['拍嗝顺利', '溢奶微量', '金黄色便便', '安睡无闹', '微胀气', '吃得香']
const initialNow = store.getServerNow()
const manualForm = reactive({ const manualForm = reactive({
recordType: 'feeding' as RecordType, recordType: 'feeding' as RecordType,
startDate: new Date().toISOString().slice(0, 10), startDate: getLocalDateStr(initialNow),
startTimeStr: new Date().toTimeString().slice(0, 5), startTimeStr: getLocalTimeStr(initialNow),
hasEndTime: false, hasEndTime: false,
endDate: new Date().toISOString().slice(0, 10), endDate: getLocalDateStr(initialNow),
endTimeStr: '', endTimeStr: '',
durationMinutes: null as number | null, durationMinutes: null as number | null,
feedingMethod: 'breastfeed' as FeedingMethod, feedingMethod: 'breastfeed' as FeedingMethod,
amountMl: null as number | null, amountMl: null as number | null,
breastSide: 'left' as 'left' | 'right', breastMode: 'both' as 'left' | 'right' | 'both',
leftMinutes: 10 as number | null,
rightMinutes: 10 as number | null,
excretionType: 'pee' as ExcretionType, excretionType: 'pee' as ExcretionType,
operatorName: store.operatorName, operatorName: store.operatorName,
note: '' note: ''
@@ -40,20 +44,87 @@ watch(() => props.show, (newVal) => {
}) })
function initForm() { function initForm() {
const now = new Date() const now = store.getServerNow()
manualForm.recordType = 'feeding' manualForm.recordType = 'feeding'
manualForm.startDate = now.toISOString().slice(0, 10) manualForm.startDate = getLocalDateStr(now)
manualForm.startTimeStr = now.toTimeString().slice(0, 5) manualForm.startTimeStr = getLocalTimeStr(now)
manualForm.hasEndTime = false manualForm.hasEndTime = true
manualForm.endDate = now.toISOString().slice(0, 10) manualForm.endDate = getLocalDateStr(now)
manualForm.endTimeStr = '' manualForm.durationMinutes = 20
manualForm.durationMinutes = null
manualForm.feedingMethod = store.preferences.defaultFeedingMethod || 'breastfeed' manualForm.feedingMethod = store.preferences.defaultFeedingMethod || 'breastfeed'
manualForm.amountMl = manualForm.feedingMethod === 'bottle' ? store.preferences.defaultBottleAmount : null manualForm.amountMl = manualForm.feedingMethod === 'bottle' ? (store.preferences.defaultBottleAmount || 30) : null
manualForm.breastSide = store.preferences.defaultBreastSide || 'left' manualForm.breastMode = 'both'
manualForm.leftMinutes = 10
manualForm.rightMinutes = 10
manualForm.excretionType = 'pee' manualForm.excretionType = 'pee'
manualForm.operatorName = store.operatorName manualForm.operatorName = store.operatorName
manualForm.note = '' manualForm.note = ''
autoUpdateEndTime()
}
function handleBreastModeChange(mode: 'left' | 'right' | 'both') {
manualForm.breastMode = mode
const currentTotal = manualForm.durationMinutes || 20
if (mode === 'both') {
manualForm.leftMinutes = Math.floor(currentTotal / 2) || 10
manualForm.rightMinutes = Math.ceil(currentTotal / 2) || 10
manualForm.durationMinutes = (manualForm.leftMinutes || 0) + (manualForm.rightMinutes || 0)
} else if (mode === 'left') {
manualForm.leftMinutes = currentTotal || 20
manualForm.rightMinutes = null
manualForm.durationMinutes = manualForm.leftMinutes
} else {
manualForm.rightMinutes = currentTotal || 20
manualForm.leftMinutes = null
manualForm.durationMinutes = manualForm.rightMinutes
}
autoUpdateEndTime()
}
function onSplitMinutesChange() {
if (manualForm.breastMode === 'both') {
manualForm.durationMinutes = (manualForm.leftMinutes || 0) + (manualForm.rightMinutes || 0)
} else if (manualForm.breastMode === 'left') {
manualForm.durationMinutes = manualForm.leftMinutes || 0
} else {
manualForm.durationMinutes = manualForm.rightMinutes || 0
}
autoUpdateEndTime()
}
function onTotalDurationChange() {
const total = manualForm.durationMinutes || 0
if (manualForm.breastMode === 'both') {
manualForm.leftMinutes = Math.floor(total / 2)
manualForm.rightMinutes = Math.ceil(total / 2)
} else if (manualForm.breastMode === 'left') {
manualForm.leftMinutes = total
manualForm.rightMinutes = null
} else {
manualForm.rightMinutes = total
manualForm.leftMinutes = null
}
autoUpdateEndTime()
}
function autoUpdateEndTime() {
if (!manualForm.startDate || !manualForm.startTimeStr || !manualForm.durationMinutes) return
try {
const startMs = new Date(`${manualForm.startDate}T${manualForm.startTimeStr}:00`).getTime()
if (isNaN(startMs)) return
const endMs = startMs + manualForm.durationMinutes * 60000
const endDateObj = new Date(endMs)
const y = endDateObj.getFullYear()
const m = String(endDateObj.getMonth() + 1).padStart(2, '0')
const d = String(endDateObj.getDate()).padStart(2, '0')
const hh = String(endDateObj.getHours()).padStart(2, '0')
const mm = String(endDateObj.getMinutes()).padStart(2, '0')
manualForm.endDate = `${y}-${m}-${d}`
manualForm.endTimeStr = `${hh}:${mm}`
manualForm.hasEndTime = true
} catch {
// ignore
}
} }
function appendNote(tag: string) { function appendNote(tag: string) {
@@ -71,13 +142,7 @@ async function submitManual() {
endTime = `${manualForm.endDate}T${manualForm.endTimeStr}:00` endTime = `${manualForm.endDate}T${manualForm.endTimeStr}:00`
} }
let finalNote = manualForm.note const finalNote = manualForm.note.trim()
if (manualForm.recordType === 'feeding' && manualForm.feedingMethod === 'breastfeed' && manualForm.breastSide) {
const sideText = manualForm.breastSide === 'left' ? '左侧' : '右侧'
if (!finalNote.includes('亲喂侧')) {
finalNote = `亲喂侧: ${sideText}${finalNote ? ';' + finalNote : ''}`
}
}
try { try {
await store.manualLog({ await store.manualLog({
@@ -85,6 +150,8 @@ async function submitManual() {
startTime, startTime,
endTime, endTime,
durationMinutes: manualForm.durationMinutes, durationMinutes: manualForm.durationMinutes,
leftDurationMinutes: manualForm.recordType === 'feeding' && manualForm.feedingMethod === 'breastfeed' ? (manualForm.breastMode === 'right' ? null : manualForm.leftMinutes) : null,
rightDurationMinutes: manualForm.recordType === 'feeding' && manualForm.feedingMethod === 'breastfeed' ? (manualForm.breastMode === 'left' ? null : manualForm.rightMinutes) : null,
feedingMethod: manualForm.recordType === 'feeding' ? manualForm.feedingMethod : null, feedingMethod: manualForm.recordType === 'feeding' ? manualForm.feedingMethod : null,
amountMl: manualForm.recordType === 'feeding' && manualForm.feedingMethod !== 'breastfeed' ? manualForm.amountMl : null, amountMl: manualForm.recordType === 'feeding' && manualForm.feedingMethod !== 'breastfeed' ? manualForm.amountMl : null,
excretionType: manualForm.recordType === 'excretion' ? manualForm.excretionType : null, excretionType: manualForm.recordType === 'excretion' ? manualForm.excretionType : null,
@@ -101,11 +168,19 @@ async function submitManual() {
</script> </script>
<template> <template>
<div v-if="props.show" class="modal-backdrop" @click.self="emit('update:show', false)"> <van-popup
<div class="modal-sheet"> :show="props.show"
position="bottom"
round
safe-area-inset-bottom
teleport="body"
class="timeline-modal-popup"
@update:show="(val: boolean) => emit('update:show', val)"
>
<div class="modal-sheet-inner">
<div class="modal-header"> <div class="modal-header">
<h3>补录照护记录</h3> <h3>补录照护记录</h3>
<button class="close-btn" @click="emit('update:show', false)">×</button> <button class="close-btn" type="button" @click="emit('update:show', false)">×</button>
</div> </div>
<div class="modal-form"> <div class="modal-form">
@@ -140,19 +215,19 @@ async function submitManual() {
</div> </div>
</label> </label>
<!-- 发生时间 --> <!-- 开始起止时间设置 -->
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;"> <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
<label> <label>
开始日期 开始日期
<input v-model="manualForm.startDate" type="date" /> <input v-model="manualForm.startDate" type="date" @change="autoUpdateEndTime" />
</label> </label>
<label> <label>
开始时间 开始时间
<input v-model="manualForm.startTimeStr" type="time" /> <input v-model="manualForm.startTimeStr" type="time" @change="autoUpdateEndTime" />
</label> </label>
</div> </div>
<!-- 喂奶特定字段 --> <!-- 喂奶专属表单 -->
<template v-if="manualForm.recordType === 'feeding'"> <template v-if="manualForm.recordType === 'feeding'">
<label> <label>
喂养方式 喂养方式
@@ -164,77 +239,72 @@ async function submitManual() {
</select> </select>
</label> </label>
<div v-if="manualForm.feedingMethod === 'breastfeed'"> <!-- 亲喂:侧别与分侧耗时 -->
<label> <div v-if="manualForm.feedingMethod === 'breastfeed'" style="background: #faf7f2; border: 1px solid #eee5d8; border-radius: 12px; padding: 12px;">
亲喂侧 <label style="margin-bottom: 8px;">
亲喂模式
<div class="chip-group"> <div class="chip-group">
<button <button
type="button" type="button"
class="chip sm" class="chip sm"
:class="{ active: manualForm.breastSide === 'left' }" :class="{ active: manualForm.breastMode === 'both' }"
@click="manualForm.breastSide = 'left'" @click="handleBreastModeChange('both')"
> >
左侧 双侧 (左右各喂)
</button> </button>
<button <button
type="button" type="button"
class="chip sm" class="chip sm"
:class="{ active: manualForm.breastSide === 'right' }" :class="{ active: manualForm.breastMode === 'left' }"
@click="manualForm.breastSide = 'right'" @click="handleBreastModeChange('left')"
> >
右侧 仅左侧
</button>
<button
type="button"
class="chip sm"
:class="{ active: manualForm.breastMode === 'right' }"
@click="handleBreastModeChange('right')"
>
仅右侧
</button> </button>
</div> </div>
</label> </label>
<!-- 分侧耗时 -->
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 8px;">
<label v-if="manualForm.breastMode === 'left' || manualForm.breastMode === 'both'">
左侧耗时 (分钟)
<input v-model.number="manualForm.leftMinutes" type="number" min="0" max="120" placeholder="分钟" @input="onSplitMinutesChange" />
</label>
<label v-if="manualForm.breastMode === 'right' || manualForm.breastMode === 'both'">
右侧耗时 (分钟)
<input v-model.number="manualForm.rightMinutes" type="number" min="0" max="120" placeholder="分钟" @input="onSplitMinutesChange" />
</label>
</div> </div>
<div v-else> <!-- 总时长 -->
<label> <label style="margin-top: 8px;">
奶量 (ml) 亲喂总时长 (分钟)
<div style="display: flex; gap: 8px; align-items: center;"> <input v-model.number="manualForm.durationMinutes" type="number" min="1" max="180" @input="onTotalDurationChange" />
<input v-model.number="manualForm.amountMl" type="number" placeholder="输入奶量 ml" />
<div class="chip-group" style="margin: 0;">
<button
v-for="amt in [30, 60, 90, 120]"
:key="amt"
type="button"
class="chip sm"
:class="{ active: manualForm.amountMl === amt }"
@click="manualForm.amountMl = amt"
>
{{ amt }}
</button>
</div>
</div>
</label> </label>
</div> </div>
<label v-else>
单次奶量 (ml)
<input v-model.number="manualForm.amountMl" type="number" min="5" max="400" step="5" />
</label>
</template> </template>
<!-- 睡眠特定字段 --> <!-- 睡眠专属表单 -->
<template v-if="manualForm.recordType === 'sleep'"> <template v-if="manualForm.recordType === 'sleep'">
<div style="display: flex; align-items: center; gap: 8px; margin: 4px 0;">
<input id="manualHasEnd" v-model="manualForm.hasEndTime" type="checkbox" style="width: 18px; height: 18px;" />
<label for="manualHasEnd" style="font-size: 14px; cursor: pointer; color: #1f2933;">包含醒来结束时间</label>
</div>
<div v-if="manualForm.hasEndTime" style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
<label> <label>
醒来日期 睡眠时长 (分钟)
<input v-model="manualForm.endDate" type="date" /> <input v-model.number="manualForm.durationMinutes" type="number" min="1" placeholder="留空则按起止时间自动计算" @input="autoUpdateEndTime" />
</label>
<label>
醒来时间
<input v-model="manualForm.endTimeStr" type="time" />
</label>
</div>
<label v-if="!manualForm.hasEndTime">
睡眠持续时间 (分钟,可选)
<input v-model.number="manualForm.durationMinutes" type="number" placeholder="例如:45" />
</label> </label>
</template> </template>
<!-- 排泄特定字段 --> <!-- 排泄专属表单 -->
<template v-if="manualForm.recordType === 'excretion'"> <template v-if="manualForm.recordType === 'excretion'">
<label> <label>
排泄类型 排泄类型
@@ -245,7 +315,7 @@ async function submitManual() {
:class="{ active: manualForm.excretionType === 'pee' }" :class="{ active: manualForm.excretionType === 'pee' }"
@click="manualForm.excretionType = 'pee'" @click="manualForm.excretionType = 'pee'"
> >
💧 嘘嘘 (尿尿) 💧 小便 (尿尿)
</button> </button>
<button <button
type="button" type="button"
@@ -253,18 +323,34 @@ async function submitManual() {
:class="{ active: manualForm.excretionType === 'poop' }" :class="{ active: manualForm.excretionType === 'poop' }"
@click="manualForm.excretionType = 'poop'" @click="manualForm.excretionType = 'poop'"
> >
💩 便便 (大便) 💩 大便 (便便)
</button> </button>
</div> </div>
</label> </label>
</template> </template>
<!-- 记录人选择 --> <!-- 结束时间(选填/联动) -->
<div style="border-top: 1px dashed #e8e3d8; padding-top: 10px;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
<span style="font-size: 13px; font-weight: 700; color: #4b5563;">记录结束时间</span>
<input v-model="manualForm.hasEndTime" type="checkbox" style="width: 18px; height: 18px;" />
</div>
<div v-if="manualForm.hasEndTime" style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
<label>
结束日期
<input v-model="manualForm.endDate" type="date" />
</label>
<label>
结束时间
<input v-model="manualForm.endTimeStr" type="time" />
</label>
</div>
</div>
<!-- 记录人 -->
<label> <label>
记录人称谓 记录人称谓
<div style="display: flex; gap: 8px;">
<input v-model="manualForm.operatorName" placeholder="例如:宝妈、宝爸" /> <input v-model="manualForm.operatorName" placeholder="例如:宝妈、宝爸" />
</div>
<div class="chip-group"> <div class="chip-group">
<button <button
v-for="m in store.members" v-for="m in store.members"
@@ -297,10 +383,10 @@ async function submitManual() {
</label> </label>
<div class="modal-actions"> <div class="modal-actions">
<button class="secondary-button" @click="emit('update:show', false)">取消</button> <button class="secondary-button" type="button" @click="emit('update:show', false)">取消</button>
<button class="save-button" @click="submitManual">确认补录</button> <button class="save-button" type="button" @click="submitManual">确定补录</button>
</div>
</div> </div>
</div> </div>
</div> </div>
</van-popup>
</template> </template>
+2 -2
View File
@@ -21,8 +21,8 @@ onMounted(async () => {
<template> <template>
<section class="page"> <section class="page">
<header class="page-header"> <header class="page-header">
<p class="eyebrow">设置与配置</p> <p class="eyebrow">宝宝与家庭</p>
<h1>家庭照护维护</h1> <h1>家庭照护管理</h1>
<p>{{ currentBabyLabel }}</p> <p>{{ currentBabyLabel }}</p>
</header> </header>
+2 -2
View File
@@ -1,7 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted } from 'vue' import { onMounted } from 'vue'
import { useCareStore } from '../stores/careStore' import { useCareStore } from '../stores/careStore'
import { formatMinutes } from '../utils/format' import { formatMinutes, formatFeedingMethod } from '../utils/format'
const store = useCareStore() const store = useCareStore()
@@ -42,7 +42,7 @@ onMounted(() => {
<h2>喂奶方式</h2> <h2>喂奶方式</h2>
</div> </div>
<div class="stat-row" v-for="(count, method) in store.summary?.feedingMethodCounts || {}" :key="method"> <div class="stat-row" v-for="(count, method) in store.summary?.feedingMethodCounts || {}" :key="method">
<span>{{ method }}</span> <span>{{ formatFeedingMethod(method as string) }}</span>
<strong>{{ count }} 次</strong> <strong>{{ count }} 次</strong>
</div> </div>
<p v-if="!Object.keys(store.summary?.feedingMethodCounts || {}).length" class="empty">暂无喂奶记录。</p> <p v-if="!Object.keys(store.summary?.feedingMethodCounts || {}).length" class="empty">暂无喂奶记录。</p>
+205 -26
View File
@@ -1,15 +1,28 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, ref } from 'vue' import { computed, onMounted, ref, watch } from 'vue'
import { showToast, showConfirmDialog } from 'vant' import { showToast, showConfirmDialog } from 'vant'
import { deleteRecord } from '../api/client' import { deleteRecord, getRecords } from '../api/client'
import { useCareStore } from '../stores/careStore' import { useCareStore } from '../stores/careStore'
import { formatMinutes, formatTime, recordLabel } from '../utils/format' import {
formatMinutes,
recordLabel,
getFeedingSplitInfo,
formatRecordTimeRange,
formatCleanNote,
formatDate,
getFriendlyDayLabel
} from '../utils/format'
import type { CareRecord } from '../types/domain' import type { CareRecord } from '../types/domain'
import TimelineManualModal from '../components/timeline/TimelineManualModal.vue' import TimelineManualModal from '../components/timeline/TimelineManualModal.vue'
import TimelineEditModal from '../components/timeline/TimelineEditModal.vue' import TimelineEditModal from '../components/timeline/TimelineEditModal.vue'
const store = useCareStore() const store = useCareStore()
const loading = ref(false)
const records = ref<CareRecord[]>([])
const filterDate = ref<string>('')
const sortOrder = ref<'desc' | 'asc'>('desc')
// 补录弹窗控制 // 补录弹窗控制
const showManualModal = ref(false) const showManualModal = ref(false)
@@ -17,10 +30,50 @@ const showManualModal = ref(false)
const showEditModal = ref(false) const showEditModal = ref(false)
const selectedRecord = ref<CareRecord | null>(null) const selectedRecord = ref<CareRecord | null>(null)
onMounted(async () => { interface RecordDayGroup {
date: string
dateLabel: string
count: number
records: CareRecord[]
}
async function loadData() {
loading.value = true
try {
await store.load() await store.load()
const babyId = store.baby?.babyId || store.selectedBabyId
if (babyId) {
records.value = await getRecords(babyId, filterDate.value || undefined)
}
} catch (err: any) {
showToast(err.message || '加载记录失败')
} finally {
loading.value = false
}
}
onMounted(async () => {
await loadData()
}) })
watch(filterDate, () => {
loadData()
})
watch(() => store.baby?.babyId || store.selectedBabyId, (newId) => {
if (newId) {
loadData()
}
})
function clearFilter() {
filterDate.value = ''
}
function toggleSortOrder() {
sortOrder.value = sortOrder.value === 'desc' ? 'asc' : 'desc'
}
function openManualModal() { function openManualModal() {
showManualModal.value = true showManualModal.value = true
} }
@@ -30,6 +83,11 @@ function openEditModal(record: CareRecord) {
showEditModal.value = true showEditModal.value = true
} }
async function handleRecordChanged() {
await loadData()
await store.refreshSummary()
}
async function remove(recordId: string) { async function remove(recordId: string) {
try { try {
await showConfirmDialog({ await showConfirmDialog({
@@ -37,37 +95,129 @@ async function remove(recordId: string) {
message: '确定要删除这条照护记录吗?' message: '确定要删除这条照护记录吗?'
}) })
await deleteRecord(recordId) await deleteRecord(recordId)
await loadData()
await store.refreshSummary() await store.refreshSummary()
showToast({ message: '记录已删除', type: 'success' }) showToast({ message: '记录已删除', type: 'success' })
} catch { } catch {
// cancel // cancel
} }
} }
// 记录按照开始时间按日分组,天内根据 sortOrder 升降序
const groupedRecords = computed<RecordDayGroup[]>(() => {
if (!records.value || !records.value.length) return []
const groupMap = new Map<string, CareRecord[]>()
for (const record of records.value) {
const d = formatDate(record.startTime) || '未知日期'
if (!groupMap.has(d)) {
groupMap.set(d, [])
}
groupMap.get(d)!.push(record)
}
// 日期从近到远倒序(最新日期在最前面)
const sortedDates = Array.from(groupMap.keys()).sort((a, b) => b.localeCompare(a))
return sortedDates.map(date => {
const list = groupMap.get(date) || []
const sortedList = [...list].sort((a, b) => {
const timeA = new Date(a.startTime).getTime()
const timeB = new Date(b.startTime).getTime()
return sortOrder.value === 'desc' ? timeB - timeA : timeA - timeB
})
return {
date,
dateLabel: getFriendlyDayLabel(date),
count: list.length,
records: sortedList
}
})
})
const totalCount = computed(() => records.value.length)
</script> </script>
<template> <template>
<section class="page"> <section class="page">
<header class="page-header"> <header class="page-header">
<p class="eyebrow">实时照护记录</p> <p class="eyebrow">全周期照护记录</p>
<h1>照护流水</h1> <h1>照护记录</h1>
</header> </header>
<!-- 顶部操作栏 --> <!-- 顶部过滤与排序工具栏 -->
<div class="timeline-header-actions"> <div class="timeline-toolbar">
<div> <div class="timeline-filter-row">
<span style="font-size: 13px; color: #65707d;"> <!-- 日期过滤输入框 -->
今日已记录 <strong>{{ store.summary?.timeline?.length || 0 }}</strong> 项 <div class="date-filter-box">
</span> <span class="filter-icon">📅</span>
</div> <input
<button class="primary-pill-button" @click="openManualModal"> v-model="filterDate"
+ 补录记录 type="date"
class="filter-date-input"
aria-label="筛选特定日期"
/>
<button
v-if="filterDate"
type="button"
class="clear-filter-btn"
title="查看全部日期"
@click="clearFilter"
>
✕ 全部
</button> </button>
</div> </div>
<!-- 流水列表 --> <!-- 右侧操作项:天内排序切换与补录 -->
<div class="timeline"> <div class="toolbar-actions">
<button
type="button"
class="sort-toggle-btn"
:class="{ active: sortOrder === 'asc' }"
:title="sortOrder === 'desc' ? '当前:当天内由晚到早(倒序),点击切换为正序' : '当前:当天内由早到晚(正序),点击切换为倒序'"
@click="toggleSortOrder"
>
<span class="sort-icon">{{ sortOrder === 'desc' ? '↓' : '↑' }}</span>
{{ sortOrder === 'desc' ? '时间倒序' : '时间正序' }}
</button>
<button class="primary-pill-button" @click="openManualModal">
+ 补录
</button>
</div>
</div>
<!-- 状态概览提示 -->
<div class="timeline-meta-bar">
<span v-if="filterDate" class="meta-filter-active">
已筛选 <strong>{{ filterDate }}</strong>,共 <strong>{{ totalCount }}</strong> 项记录
</span>
<span v-else class="meta-all-dates">
全部历史记录,共 <strong>{{ totalCount }}</strong> 项(已按日分组)
</span>
</div>
</div>
<!-- 记录按日分组展示列表 -->
<div v-if="groupedRecords.length" class="timeline-groups">
<section
v-for="group in groupedRecords"
:key="group.date"
class="timeline-day-group"
>
<!-- 日期分组标头 -->
<div class="timeline-day-header">
<div class="day-header-left">
<span class="day-badge-dot"></span>
<span class="day-title">{{ group.dateLabel }}</span>
</div>
<span class="day-records-count">共 {{ group.count }} 项</span>
</div>
<!-- 当天记录列表 -->
<div class="timeline-day-list">
<article <article
v-for="record in store.summary?.timeline || []" v-for="record in group.records"
:key="record.recordId" :key="record.recordId"
class="timeline-item" class="timeline-item"
> >
@@ -83,12 +233,26 @@ async function remove(recordId: string) {
{{ formatMinutes(record.durationMinutes) }} {{ formatMinutes(record.durationMinutes) }}
</span> </span>
</div> </div>
<p> <p style="margin: 4px 0 2px; font-weight: 600; color: #374151;">
{{ formatTime(record.startTime) }} {{ formatRecordTimeRange(record.startTime, record.endTime) }}
<span v-if="record.endTime"> ~ {{ formatTime(record.endTime) }}</span>
</p> </p>
<p v-if="record.note || record.remark" style="color: #4b5563; font-size: 13px; margin-top: 2px;"> <!-- 亲喂分侧分别耗时展示 -->
📝 {{ record.note || record.remark }} <div v-if="getFeedingSplitInfo(record)" style="display: flex; gap: 6px; margin: 3px 0;">
<span
v-if="getFeedingSplitInfo(record)?.leftMinutes"
style="background: #e0f2fe; color: #0369a1; font-size: 11px; font-weight: 700; padding: 2px 6px; border-radius: 4px;"
>
左侧: {{ getFeedingSplitInfo(record)?.leftMinutes }}分钟
</span>
<span
v-if="getFeedingSplitInfo(record)?.rightMinutes"
style="background: #fdf2f8; color: #be185d; font-size: 11px; font-weight: 700; padding: 2px 6px; border-radius: 4px;"
>
右侧: {{ getFeedingSplitInfo(record)?.rightMinutes }}分钟
</span>
</div>
<p v-if="formatCleanNote(record.note || record.remark)" style="color: #6b7280; font-size: 13px; margin-top: 2px;">
📝 {{ formatCleanNote(record.note || record.remark) }}
</p> </p>
<small>记录人: {{ record.operatorName }}</small> <small>记录人: {{ record.operatorName }}</small>
</div> </div>
@@ -98,14 +262,29 @@ async function remove(recordId: string) {
<button class="delete-button" @click="remove(record.recordId)">删除</button> <button class="delete-button" @click="remove(record.recordId)">删除</button>
</div> </div>
</article> </article>
</div>
</section>
</div>
<p v-if="!store.summary?.timeline?.length" class="empty">今天还没有记录,点击上方“+ 补录记录”开始吧。</p> <!-- 空状态 -->
<div v-else-if="!loading" class="timeline-empty-card">
<div style="font-size: 36px; margin-bottom: 8px;">📋</div>
<p v-if="filterDate" style="color: #4b5563; font-weight: 600; margin: 0 0 12px;">
{{ filterDate }} 暂无任何照护记录
</p>
<p v-else style="color: #4b5563; font-weight: 600; margin: 0 0 12px;">
宝宝目前还没有照护记录,点击下方按钮开始补录吧
</p>
<div style="display: flex; gap: 10px; justify-content: center;">
<button v-if="filterDate" class="secondary-btn" @click="clearFilter">查看全部日期</button>
<button class="primary-pill-button" @click="openManualModal">+ 补录记录</button>
</div>
</div> </div>
<!-- 弹窗:补录记录维护组件 --> <!-- 弹窗:补录记录维护组件 -->
<TimelineManualModal v-model:show="showManualModal" /> <TimelineManualModal v-model:show="showManualModal" @success="handleRecordChanged" />
<!-- 弹窗:编辑记录维护组件 --> <!-- 弹窗:编辑记录维护组件 -->
<TimelineEditModal v-model:show="showEditModal" :record="selectedRecord" /> <TimelineEditModal v-model:show="showEditModal" :record="selectedRecord" @success="handleRecordChanged" />
</section> </section>
</template> </template>
+629 -64
View File
@@ -1,68 +1,243 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, ref } from 'vue' import { onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant' import { showToast } from 'vant'
import { useCareStore } from '../stores/careStore' import { useCareStore } from '../stores/careStore'
import { formatMinutes, formatTime } from '../utils/format' import { formatMinutes, formatTime, getLocalDateStr, getLocalTimeStr } from '../utils/format'
const router = useRouter()
const store = useCareStore() const store = useCareStore()
const bottleAmount = ref(30) // 喂养聚合 Tab 控制
const breastSide = ref<'left' | 'right'>('left') type FeedingTabType = 'breastfeed' | 'bottle' | 'formula' | 'mixed'
const currentFeedingTab = ref<FeedingTabType>(
(store.preferences.defaultFeedingMethod as FeedingTabType) || 'breastfeed'
)
const babyOptions = computed(() => store.babies.map(baby => ({ const feedingTabOptions = [
text: `${baby.name} · ${baby.ageText}`, { value: 'breastfeed' as FeedingTabType, label: '亲喂' },
value: baby.babyId { value: 'bottle' as FeedingTabType, label: '瓶喂' },
}))) { value: 'formula' as FeedingTabType, label: '配方奶' },
{ value: 'mixed' as FeedingTabType, label: '混合喂养' }
]
const memberOptions = computed(() => store.members.map(member => ({ const bottleAmount = ref(store.preferences.defaultBottleAmount || 30)
text: member.roleName, const formulaAmount = ref(store.preferences.defaultBottleAmount || 60)
value: member.roleName const mixedAmount = ref(store.preferences.defaultBottleAmount || 40)
}))) const mixedNote = ref('')
const breastSide = ref<'left' | 'right'>(store.preferences.defaultBreastSide || 'left')
const activeFeedingText = computed(() => { // 切换抽屉状态
const active = store.summary?.activeFeeding const showBabyPicker = ref(false)
return active ? `亲喂中 · ${formatTime(active.startTime)}` : '未计时' const showMemberPicker = ref(false)
})
// 一次性亲喂配置
const breastSideMode = ref<'left' | 'right' | 'both'>('both')
const oneClickDuration = ref(20)
watch(
() => store.preferences.defaultBottleAmount,
(val) => {
if (val && typeof val === 'number') {
bottleAmount.value = val
formulaAmount.value = val
mixedAmount.value = val
}
},
{ immediate: true }
)
watch(
() => store.preferences.defaultFeedingMethod,
(val) => {
if (val && !store.bfTimerActive) {
currentFeedingTab.value = val as FeedingTabType
}
},
{ immediate: true }
)
watch(
() => store.bfTimerActive,
(active) => {
if (active) {
currentFeedingTab.value = 'breastfeed'
}
}
)
watch(
() => store.preferences.defaultBreastSide,
(val) => {
if (val && !store.bfTimerActive) {
breastSide.value = val
}
}
)
async function logMixedFeeding() {
await runWithTip(
() => store.logFeeding({
method: 'mixed',
amountMl: mixedAmount.value,
note: mixedNote.value.trim() || undefined
}),
`已记录混合喂养 ${mixedAmount.value}ml`
)
mixedNote.value = ''
}
function getRoleIcon(roleName: string) {
if (!roleName) return '👤'
if (roleName.includes('妈')) return '👩'
if (roleName.includes('爸')) return '👨'
if (roleName.includes('月嫂') || roleName.includes('育儿')) return '🤱'
if (roleName.includes('奶') || roleName.includes('婆')) return '👵'
if (roleName.includes('爷') || roleName.includes('公')) return '👴'
return '👤'
}
function formatSec(seconds: number) {
const m = Math.floor(seconds / 60)
const s = seconds % 60
return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`
}
function formatTotalBfTime() {
const total = store.bfLeftSeconds + store.bfRightSeconds
const m = Math.floor(total / 60)
const s = total % 60
return `${m}分${String(s).padStart(2, '0')}秒`
}
function handleCardClick(side: 'left' | 'right') {
if (store.bfTimerActive) {
store.switchBreastfeedSide(side)
} else {
breastSide.value = side
}
}
async function selectBaby(babyId: string, name: string) {
showBabyPicker.value = false
if (babyId === store.baby?.babyId) return
await store.selectBaby(babyId)
showToast({ message: `已切换为宝宝:${name}`, type: 'success' })
}
function selectOperator(name: string) {
showMemberPicker.value = false
if (name === store.operatorName) return
store.setOperatorName(name)
showToast({ message: `已切换记录人为:${name}`, type: 'success' })
}
function goToSettings() {
showBabyPicker.value = false
showMemberPicker.value = false
router.push('/settings')
}
onMounted(() => { onMounted(() => {
store.load() store.load()
}) })
async function runWithTip(action: () => Promise<void>, message: string) { const operating = ref(false)
async function runWithTip(action: () => Promise<void>, message?: string) {
if (operating.value) return
operating.value = true
try {
await action() await action()
if (message) {
showToast({ message, type: 'success', duration: 1400 }) showToast({ message, type: 'success', duration: 1400 })
}
} catch (err: any) {
showToast(err.message || '操作失败')
} finally {
operating.value = false
}
}
async function handleOneClickBreastfeeding() {
if (operating.value) return
const dur = oneClickDuration.value || 20
const now = store.getServerNow()
const startMs = now.getTime() - dur * 60000
const startDate = new Date(startMs)
const startTime = `${getLocalDateStr(startDate)}T${getLocalTimeStr(startDate)}:00`
const endTime = `${getLocalDateStr(now)}T${getLocalTimeStr(now)}:00`
let leftDur: number | undefined
let rightDur: number | undefined
if (breastSideMode.value === 'both') {
leftDur = Math.floor(dur / 2)
rightDur = Math.ceil(dur / 2)
} else if (breastSideMode.value === 'left') {
leftDur = dur
rightDur = 0
} else {
leftDur = 0
rightDur = dur
}
const startStr = `${String(startDate.getHours()).padStart(2, '0')}:${String(startDate.getMinutes()).padStart(2, '0')}`
const endStr = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`
await runWithTip(
() => store.logFeeding({
method: 'breastfeed',
durationMinutes: dur,
feedingTime: startTime,
endTime,
leftDurationMinutes: leftDur,
rightDurationMinutes: rightDur,
breastSide: breastSideMode.value
}),
`已记录亲喂 ${dur}分钟(${startStr} ~ ${endStr})`
)
} }
</script> </script>
<template> <template>
<section class="page"> <section class="page">
<header class="hero clean-hero"> <!-- 顶部一体化温润状态卡片 -->
<div> <header class="today-top-card">
<p class="eyebrow">{{ store.context?.family.name || '新生儿照护家庭' }}</p> <!-- 顶栏:家庭名称与记录人切换胶囊 -->
<h1>{{ store.baby?.name || '宝宝' }}</h1> <div class="top-row">
<p>{{ store.baby?.ageText || '出生第 3 天' }} · {{ store.operatorName }}记录中</p> <div class="family-badge">
<span class="family-icon">🏡</span>
<span class="family-name">{{ store.context?.family.name || '新生儿照护家庭' }}</span>
</div>
<button class="operator-pill" type="button" @click="showMemberPicker = true">
<span class="operator-avatar">{{ getRoleIcon(store.operatorName) }}</span>
<span class="operator-text">{{ store.operatorName }}</span>
<span class="pill-arrow">▾</span>
</button>
</div>
<!-- 主体:宝宝信息与切换入口 -->
<div class="baby-main-row" @click="showBabyPicker = true">
<div class="baby-avatar-wrap">
<span class="baby-avatar-emoji">👶</span>
<span class="gender-dot" :class="store.baby?.gender || 'boy'"></span>
</div>
<div class="baby-meta">
<div class="baby-name-row">
<h1 class="baby-name">{{ store.baby?.name || '宝宝' }}</h1>
<span class="baby-switch-tag">切换宝宝 ▾</span>
</div>
<div class="baby-tags">
<span class="baby-age-chip">{{ store.baby?.ageText || '出生第 3 天' }}</span>
<span v-if="store.baby?.deliveryType === 'natural'" class="baby-sub-chip">顺产</span>
<span v-else-if="store.baby?.deliveryType === 'c_section'" class="baby-sub-chip">剖腹产</span>
</div>
</div>
</div> </div>
</header> </header>
<p v-if="store.error" class="notice error">{{ store.error }}</p> <p v-if="store.error" class="notice error">{{ store.error }}</p>
<p v-if="store.loading" class="notice">正在加载今日记录...</p> <p v-if="store.loading" class="notice">正在加载今日记录...</p>
<section class="context-panel">
<van-dropdown-menu>
<van-dropdown-item
:model-value="store.baby?.babyId"
:options="babyOptions"
title="宝宝"
@update:model-value="value => store.selectBaby(String(value))"
/>
<van-dropdown-item
:model-value="store.operatorName"
:options="memberOptions"
title="记录人"
@update:model-value="value => store.setOperatorName(String(value))"
/>
</van-dropdown-menu>
</section>
<section class="summary-grid"> <section class="summary-grid">
<article class="metric-card"> <article class="metric-card">
<span>喂奶</span> <span>喂奶</span>
@@ -86,58 +261,326 @@ async function runWithTip(action: () => Promise<void>, message: string) {
</article> </article>
</section> </section>
<section class="panel"> <!-- 统一喂养聚合面板 -->
<section class="panel feeding-panel">
<div class="panel-title"> <div class="panel-title">
<h2>亲喂</h2> <div style="display: flex; justify-content: space-between; align-items: center;">
<p>可以计时,也可以一键记录,之后再补调时间。</p> <h2>喂养</h2>
<span v-if="store.bfTimerActive" class="bf-live-badge">亲喂进行中</span>
</div> </div>
<van-segmented v-model="breastSide" :options="[ <p>支持亲喂、瓶喂、配方奶与混合喂养多模式快捷记录。</p>
{ label: '左侧', value: 'left' },
{ label: '右侧', value: 'right' }
]" />
<div class="feeding-status">
<span>{{ activeFeedingText }}</span>
<strong v-if="store.summary?.activeFeeding">{{ breastSide === 'left' ? '左侧' : '右侧' }}</strong>
</div> </div>
<div class="two-actions">
<!-- 四大喂养方式切换 Tab -->
<div class="feeding-segmented-nav">
<button
v-for="tab in feedingTabOptions"
:key="tab.value"
type="button"
class="feeding-tab-btn"
:class="{ active: currentFeedingTab === tab.value }"
@click="currentFeedingTab = tab.value"
>
{{ tab.label }}
<span v-if="tab.value === 'breastfeed' && store.bfTimerActive" class="tab-live-dot" />
</button>
</div>
<!-- Tab 1: 亲喂 -->
<div v-show="currentFeedingTab === 'breastfeed'" class="feeding-tab-content">
<!-- 左右双侧计时卡片 -->
<div class="bf-dual-grid">
<!-- 左侧 -->
<div
class="bf-side-card"
:class="{
active: store.bfTimerActive && store.bfActiveSide === 'left',
selected: !store.bfTimerActive && breastSide === 'left'
}"
@click="handleCardClick('left')"
>
<div class="bf-card-header">
<span class="bf-card-title">左侧</span>
<span v-if="store.bfTimerActive" class="bf-status-tag" :class="store.bfActiveSide === 'left' ? 'timing' : 'paused'">
{{ store.bfActiveSide === 'left' ? '计时中' : '已暂计' }}
</span>
<span v-else class="bf-status-tag idle">
{{ breastSide === 'left' ? '优先起始' : '点击选择' }}
</span>
</div>
<div class="bf-card-time">
{{ formatSec(store.bfLeftSeconds) }}
</div>
<div v-if="store.bfTimerActive" class="bf-card-footer">
<button
v-if="store.bfActiveSide !== 'left'"
class="bf-switch-chip"
type="button"
:disabled="operating"
@click.stop="!operating && store.switchBreastfeedSide('left')"
>
切至左侧
</button>
<span v-else class="bf-active-hint">正在喂奶</span>
</div>
</div>
<!-- 右侧 -->
<div
class="bf-side-card"
:class="{
active: store.bfTimerActive && store.bfActiveSide === 'right',
selected: !store.bfTimerActive && breastSide === 'right'
}"
@click="handleCardClick('right')"
>
<div class="bf-card-header">
<span class="bf-card-title">右侧</span>
<span v-if="store.bfTimerActive" class="bf-status-tag" :class="store.bfActiveSide === 'right' ? 'timing' : 'paused'">
{{ store.bfActiveSide === 'right' ? '计时中' : '已暂计' }}
</span>
<span v-else class="bf-status-tag idle">
{{ breastSide === 'right' ? '优先起始' : '点击选择' }}
</span>
</div>
<div class="bf-card-time">
{{ formatSec(store.bfRightSeconds) }}
</div>
<div v-if="store.bfTimerActive" class="bf-card-footer">
<button
v-if="store.bfActiveSide !== 'right'"
class="bf-switch-chip"
type="button"
:disabled="operating"
@click.stop="!operating && store.switchBreastfeedSide('right')"
>
切至右侧
</button>
<span v-else class="bf-active-hint">正在喂奶</span>
</div>
</div>
</div>
<!-- 计时汇总横条 -->
<div v-if="store.bfTimerActive" class="bf-summary-bar">
<span>本次亲喂总计:<strong>{{ formatTotalBfTime() }}</strong></span>
<small>(左侧 {{ formatSec(store.bfLeftSeconds) }} · 右侧 {{ formatSec(store.bfRightSeconds) }})</small>
</div>
<!-- 未在计时状态下的亲喂模式与时长配置 -->
<div v-if="!store.bfTimerActive" class="bf-config-box">
<div style="display: flex; justify-content: space-between; align-items: center;">
<span style="font-size: 13px; font-weight: 700; color: #475569;">亲喂模式</span>
<div class="chip-group" style="margin: 0;">
<button
type="button"
class="chip sm"
:class="{ active: breastSideMode === 'both' }"
@click="breastSideMode = 'both'"
>
双侧均喂
</button>
<button
type="button"
class="chip sm"
:class="{ active: breastSideMode === 'left' }"
@click="breastSideMode = 'left'"
>
仅左侧
</button>
<button
type="button"
class="chip sm"
:class="{ active: breastSideMode === 'right' }"
@click="breastSideMode = 'right'"
>
仅右侧
</button>
</div>
</div>
<div style="display: flex; justify-content: space-between; align-items: center; margin-top: 10px;">
<span style="font-size: 13px; font-weight: 700; color: #475569;">一次性记录时长</span>
<div class="chip-group" style="margin: 0;">
<button
v-for="d in [10, 15, 20, 30]"
:key="d"
type="button"
class="chip sm"
:class="{ active: oneClickDuration === d }"
@click="oneClickDuration = d"
>
{{ d }}分钟
</button>
</div>
</div>
<div style="font-size: 12px; color: #64748b; margin-top: 8px; background: #ffffff; padding: 6px 10px; border-radius: 6px; border: 1px dashed #e2e8f0;">
💡 一键记录将按
<strong>
{{ breastSideMode === 'both' ? `左侧 ${Math.floor(oneClickDuration / 2)}分 + 右侧 ${Math.ceil(oneClickDuration / 2)}分(总计 ${oneClickDuration}分)` : breastSideMode === 'left' ? `左侧 ${oneClickDuration}分钟` : `右侧 ${oneClickDuration}分钟` }}
</strong>
自动推导起止时间并入库
</div>
</div>
<!-- 操作按钮区 -->
<div v-if="!store.bfTimerActive" class="two-actions">
<van-button <van-button
block block
round round
type="primary" type="primary"
@click="runWithTip(() => store.toggleBreastfeedTimer(breastSide), store.summary?.activeFeeding ? '已结束本次亲喂,辛苦啦' : '已开始亲喂计时')" :loading="operating"
:disabled="operating"
@click="runWithTip(() => store.startBreastfeedTimer(breastSideMode === 'right' ? 'right' : 'left'), `已开始亲喂计时(${breastSideMode === 'right' ? '右侧开始' : '左侧开始'})`)"
> >
{{ store.summary?.activeFeeding ? '结束亲喂' : '开始亲喂' }} 开始亲喂 ({{ breastSideMode === 'right' ? '右侧开始' : '左侧开始' }})
</van-button> </van-button>
<van-button <van-button
block block
round round
plain plain
type="primary" type="primary"
@click="runWithTip(() => store.logFeeding('breastfeed', undefined, breastSide), '已记录一次亲喂')" :loading="operating"
:disabled="operating"
@click="handleOneClickBreastfeeding"
> >
一键记录 一键记录 {{ oneClickDuration }}分钟
</van-button> </van-button>
</div> </div>
</section>
<section class="panel"> <div v-else class="two-actions">
<div class="panel-title"> <van-button
<h2>瓶喂</h2> block
<p>奶量可调整,默认按当前数值记录。</p> round
type="warning"
:disabled="operating"
@click="store.switchBreastfeedSide(store.bfActiveSide === 'left' ? 'right' : 'left')"
>
⇄ 切换到{{ store.bfActiveSide === 'left' ? '右侧' : '左侧' }}
</van-button>
<van-button
block
round
type="danger"
:loading="operating"
:disabled="operating"
@click="runWithTip(() => store.endBreastfeedTimer(), '已结束本次亲喂,辛苦啦')"
>
结束亲喂
</van-button>
</div> </div>
</div>
<!-- Tab 2: 瓶喂 -->
<div v-show="currentFeedingTab === 'bottle'" class="feeding-tab-content">
<div class="amount-row"> <div class="amount-row">
<span>奶量</span> <span>母乳奶量 (ml)</span>
<van-stepper v-model="bottleAmount" :min="5" :max="300" :step="5" integer /> <van-stepper v-model="bottleAmount" :min="5" :max="300" :step="5" integer />
<strong>{{ bottleAmount }} ml</strong> </div>
<div class="quick-amount-chips">
<button
v-for="amt in [30, 60, 90, 120]"
:key="amt"
type="button"
class="chip sm"
:class="{ active: bottleAmount === amt }"
@click="bottleAmount = amt"
>
{{ amt }}ml
</button>
</div> </div>
<van-button <van-button
block block
round round
type="success" type="success"
:loading="operating"
:disabled="operating"
@click="runWithTip(() => store.logFeeding('bottle', bottleAmount), `已记录瓶喂 ${bottleAmount}ml`)" @click="runWithTip(() => store.logFeeding('bottle', bottleAmount), `已记录瓶喂 ${bottleAmount}ml`)"
> >
记录瓶喂 记录瓶喂
</van-button> </van-button>
</div>
<!-- Tab 3: 配方奶 -->
<div v-show="currentFeedingTab === 'formula'" class="feeding-tab-content">
<div class="amount-row">
<span>冲调奶量 (ml)</span>
<van-stepper v-model="formulaAmount" :min="5" :max="300" :step="5" integer />
</div>
<div class="quick-amount-chips">
<button
v-for="amt in [30, 60, 90, 120]"
:key="amt"
type="button"
class="chip sm"
:class="{ active: formulaAmount === amt }"
@click="formulaAmount = amt"
>
{{ amt }}ml
</button>
</div>
<van-button
block
round
type="primary"
style="background: #2b70f0; border-color: #2b70f0;"
:loading="operating"
:disabled="operating"
@click="runWithTip(() => store.logFeeding('formula', formulaAmount), `已记录配方奶 ${formulaAmount}ml`)"
>
记录配方奶
</van-button>
</div>
<!-- Tab 4: 混合喂养 -->
<div v-show="currentFeedingTab === 'mixed'" class="feeding-tab-content">
<div class="amount-row">
<span>补喂奶量 (ml)</span>
<van-stepper v-model="mixedAmount" :min="5" :max="300" :step="5" integer />
</div>
<div class="quick-amount-chips">
<button
v-for="amt in [30, 60, 90, 120]"
:key="amt"
type="button"
class="chip sm"
:class="{ active: mixedAmount === amt }"
@click="mixedAmount = amt"
>
{{ amt }}ml
</button>
</div>
<div style="margin: 8px 0 14px;">
<input
v-model="mixedNote"
placeholder="备注说明(选填,如:先亲喂后补配方)"
style="width: 100%; padding: 8px 12px; border: 1.5px solid #e2e8f0; border-radius: 8px; font-size: 13px; box-sizing: border-box; background: #fafafa;"
/>
<div class="chip-group" style="margin-top: 6px;">
<button
v-for="tag in ['先亲喂后补配方', '纯补配方', '吃得香', '稍微溢奶']"
:key="tag"
type="button"
class="chip sm"
@click="mixedNote = tag"
>
+ {{ tag }}
</button>
</div>
</div>
<van-button
block
round
type="warning"
style="background: #e67e22; border-color: #e67e22;"
:loading="operating"
:disabled="operating"
@click="logMixedFeeding"
>
记录混合喂养
</van-button>
</div>
</section> </section>
<section class="panel"> <section class="panel">
@@ -146,15 +589,27 @@ async function runWithTip(action: () => Promise<void>, message: string) {
<p>尿尿、便便和睡眠优先保证动作清晰。</p> <p>尿尿、便便和睡眠优先保证动作清晰。</p>
</div> </div>
<div class="action-grid compact-actions"> <div class="action-grid compact-actions">
<button class="primary-action sleep" @click="runWithTip(() => store.toggleSleep(), store.summary?.activeSleep ? '已结束睡眠记录' : '已开始睡眠记录')"> <button
class="primary-action sleep"
:disabled="operating"
@click="runWithTip(() => store.toggleSleep(), store.summary?.activeSleep ? '已结束睡眠记录' : '已开始睡眠记录')"
>
<strong>{{ store.summary?.activeSleep ? '结束睡眠' : '开始睡眠' }}</strong> <strong>{{ store.summary?.activeSleep ? '结束睡眠' : '开始睡眠' }}</strong>
<span>{{ store.summary?.activeSleep ? '自动计算时长' : '宝宝睡下了' }}</span> <span>{{ store.summary?.activeSleep ? '自动计算时长' : '宝宝睡下了' }}</span>
</button> </button>
<button class="primary-action pee" @click="runWithTip(() => store.logPee(), '已记录一次小便')"> <button
class="primary-action pee"
:disabled="operating"
@click="runWithTip(() => store.logPee(), '已记录一次小便')"
>
<strong>小便</strong> <strong>小便</strong>
<span>记录一次</span> <span>记录一次</span>
</button> </button>
<button class="primary-action poop" @click="runWithTip(() => store.logPoop(), '已记录一次大便')"> <button
class="primary-action poop"
:disabled="operating"
@click="runWithTip(() => store.logPoop(), '已记录一次大便')"
>
<strong>大便</strong> <strong>大便</strong>
<span>记录一次</span> <span>记录一次</span>
</button> </button>
@@ -176,5 +631,115 @@ async function runWithTip(action: () => Promise<void>, message: string) {
</div> </div>
</div> </div>
</section> </section>
<!-- 宝宝切换抽屉 -->
<van-popup
v-model:show="showBabyPicker"
position="bottom"
round
safe-area-inset-bottom
teleport="body"
class="switcher-popup"
>
<div class="popup-sheet">
<div class="popup-sheet-header">
<div class="popup-title-group">
<h3>切换宝宝档案</h3>
<span class="popup-subtitle">当前家庭共 {{ store.babies.length }} 位宝宝</span>
</div>
<button class="popup-close-btn" type="button" @click="showBabyPicker = false">✕</button>
</div>
<div class="popup-list">
<div
v-for="baby in store.babies"
:key="baby.babyId"
class="switcher-card"
:class="{ active: baby.babyId === store.baby?.babyId }"
@click="selectBaby(baby.babyId, baby.name)"
>
<div class="switcher-card-left">
<span class="switcher-avatar-circle">👶</span>
<div class="switcher-info">
<div class="switcher-name-row">
<strong class="switcher-name">{{ baby.name }}</strong>
<span v-if="baby.isDefault" class="switcher-badge default">默认</span>
<span v-if="baby.babyId === store.baby?.babyId" class="switcher-badge current">当前照护</span>
</div>
<div class="switcher-sub-row">
<span>{{ baby.ageText }}</span>
<span class="dot-sep">·</span>
<span>{{ baby.gender === 'girl' ? '女宝 👧' : baby.gender === 'boy' ? '男宝 👦' : '宝宝' }}</span>
<span class="dot-sep">·</span>
<span>{{ baby.deliveryType === 'natural' ? '顺产' : '剖腹产' }}</span>
</div>
</div>
</div>
<div class="switcher-check">
<span v-if="baby.babyId === store.baby?.babyId" class="check-icon">✓</span>
</div>
</div>
</div>
<div class="popup-footer">
<button class="popup-footer-btn" type="button" @click="goToSettings">
👶 前往家庭管理宝宝档案
</button>
</div>
</div>
</van-popup>
<!-- 记录人切换抽屉 -->
<van-popup
v-model:show="showMemberPicker"
position="bottom"
round
safe-area-inset-bottom
teleport="body"
class="switcher-popup"
>
<div class="popup-sheet">
<div class="popup-sheet-header">
<div class="popup-title-group">
<h3>选择当前记录人</h3>
<span class="popup-subtitle">本次及后续记录将署名所选看护人</span>
</div>
<button class="popup-close-btn" type="button" @click="showMemberPicker = false">✕</button>
</div>
<div class="popup-list">
<div
v-for="member in store.members"
:key="member.memberId"
class="switcher-card"
:class="{ active: member.roleName === store.operatorName }"
@click="selectOperator(member.roleName)"
>
<div class="switcher-card-left">
<span class="switcher-avatar-circle">{{ getRoleIcon(member.roleName) }}</span>
<div class="switcher-info">
<div class="switcher-name-row">
<strong class="switcher-name">{{ member.roleName }}</strong>
<span v-if="member.defaultOperator" class="switcher-badge default">默认看护</span>
<span v-if="member.roleName === store.operatorName" class="switcher-badge current">记录中</span>
</div>
<div class="switcher-sub-row">
<span>{{ member.roleType === 'owner' ? '家庭创建者' : '照护成员' }}</span>
</div>
</div>
</div>
<div class="switcher-check">
<span v-if="member.roleName === store.operatorName" class="check-icon">✓</span>
</div>
</div>
</div>
<div class="popup-footer">
<button class="popup-footer-btn" type="button" @click="goToSettings">
👨‍👩‍👧 前往家庭管理成员角色
</button>
</div>
</div>
</van-popup>
</section> </section>
</template> </template>
+222 -6
View File
@@ -18,7 +18,8 @@ import {
updateCurrentBaby, updateCurrentBaby,
updateFamily, updateFamily,
updateMember, updateMember,
updateRecord updateRecord,
getServerTime
} from '../api/client' } from '../api/client'
import type { import type {
ActionPreferences, ActionPreferences,
@@ -37,7 +38,7 @@ import type {
const defaultPreferences: ActionPreferences = { const defaultPreferences: ActionPreferences = {
defaultFeedingMethod: 'breastfeed', defaultFeedingMethod: 'breastfeed',
defaultBottleAmount: 60, defaultBottleAmount: 30,
defaultBreastSide: 'left', defaultBreastSide: 'left',
defaultSleepMode: 'timer', defaultSleepMode: 'timer',
quickFeedbackToast: true, quickFeedbackToast: true,
@@ -56,6 +57,36 @@ function loadInitialPreferences(): ActionPreferences {
return defaultPreferences return defaultPreferences
} }
let bfTicker: ReturnType<typeof setInterval> | null = null
function startBfTicker(store: any) {
if (bfTicker) return
bfTicker = setInterval(() => {
if (!store.bfTimerActive) {
stopBfTicker()
return
}
const now = Date.now()
const delta = Math.max(0, Math.floor((now - store.bfLastTickTime) / 1000))
if (delta > 0) {
if (store.bfActiveSide === 'left') {
store.bfLeftSeconds += delta
} else {
store.bfRightSeconds += delta
}
store.bfLastTickTime = now
store.persistBfTimer()
}
}, 1000)
}
function stopBfTicker() {
if (bfTicker) {
clearInterval(bfTicker)
bfTicker = null
}
}
export const useCareStore = defineStore('care', { export const useCareStore = defineStore('care', {
state: () => ({ state: () => ({
context: null as FamilyContext | null, context: null as FamilyContext | null,
@@ -66,14 +97,34 @@ export const useCareStore = defineStore('care', {
summary: null as DailySummary | null, summary: null as DailySummary | null,
operatorName: localStorage.getItem('operatorName') || '宝妈', operatorName: localStorage.getItem('operatorName') || '宝妈',
preferences: loadInitialPreferences() as ActionPreferences, preferences: loadInitialPreferences() as ActionPreferences,
bfTimerActive: false,
bfActiveSide: 'left' as 'left' | 'right',
bfLeftSeconds: 0,
bfRightSeconds: 0,
bfLastTickTime: 0,
serverOffsetMs: 0,
loading: false, loading: false,
error: '' error: ''
}), }),
actions: { actions: {
async syncServerTime() {
try {
const info = await getServerTime()
if (info && typeof info.timestamp === 'number') {
this.serverOffsetMs = info.timestamp - Date.now()
}
} catch {
// fallback
}
},
getServerNow(): Date {
return new Date(Date.now() + this.serverOffsetMs)
},
async load() { async load() {
this.loading = true this.loading = true
this.error = '' this.error = ''
try { try {
await this.syncServerTime()
this.context = await getFamilyContext() this.context = await getFamilyContext()
this.babies = this.context.babies this.babies = this.context.babies
this.members = this.context.members this.members = this.context.members
@@ -85,6 +136,7 @@ export const useCareStore = defineStore('care', {
if (this.baby) { if (this.baby) {
localStorage.setItem('selectedBabyId', this.baby.babyId) localStorage.setItem('selectedBabyId', this.baby.babyId)
this.summary = await getDailySummary(this.baby.babyId) this.summary = await getDailySummary(this.baby.babyId)
this.syncBreastfeedTimer()
} }
} catch (error) { } catch (error) {
this.error = error instanceof Error ? error.message : '加载失败' this.error = error instanceof Error ? error.message : '加载失败'
@@ -94,7 +146,9 @@ export const useCareStore = defineStore('care', {
}, },
async refreshSummary() { async refreshSummary() {
if (!this.baby) return if (!this.baby) return
await this.syncServerTime()
this.summary = await getDailySummary(this.baby.babyId) this.summary = await getDailySummary(this.baby.babyId)
this.syncBreastfeedTimer()
}, },
async selectBaby(babyId: string) { async selectBaby(babyId: string) {
this.selectedBabyId = babyId this.selectedBabyId = babyId
@@ -162,23 +216,185 @@ export const useCareStore = defineStore('care', {
await deleteMember(this.context.family.familyId, memberId) await deleteMember(this.context.family.familyId, memberId)
this.members = this.members.filter(m => m.memberId !== memberId) this.members = this.members.filter(m => m.memberId !== memberId)
}, },
async logFeeding(method: FeedingMethod, amountMl?: number, breastSide?: 'left' | 'right') { async logFeeding(
payloadOrMethod: {
method: FeedingMethod
amountMl?: number
breastSide?: string
durationMinutes?: number
feedingTime?: string
endTime?: string
leftDurationMinutes?: number
rightDurationMinutes?: number
note?: string
} | FeedingMethod,
amountMl?: number,
breastSide?: string
) {
if (!this.baby) return if (!this.baby) return
if (typeof payloadOrMethod === 'string') {
await createFeeding({ await createFeeding({
babyId: this.baby.babyId, babyId: this.baby.babyId,
feedingMethod: method, feedingMethod: payloadOrMethod,
amountMl, amountMl,
breastSide, breastSide,
operatorName: this.operatorName operatorName: this.operatorName
}) })
} else {
await createFeeding({
babyId: this.baby.babyId,
feedingMethod: payloadOrMethod.method,
amountMl: payloadOrMethod.amountMl,
breastSide: payloadOrMethod.breastSide,
durationMinutes: payloadOrMethod.durationMinutes,
feedingTime: payloadOrMethod.feedingTime,
endTime: payloadOrMethod.endTime,
leftDurationMinutes: payloadOrMethod.leftDurationMinutes,
rightDurationMinutes: payloadOrMethod.rightDurationMinutes,
note: payloadOrMethod.note,
operatorName: this.operatorName
})
}
await this.refreshSummary()
},
persistBfTimer() {
if (!this.baby) return
try {
localStorage.setItem(`bfTimer_${this.baby.babyId}`, JSON.stringify({
activeSide: this.bfActiveSide,
leftSeconds: this.bfLeftSeconds,
rightSeconds: this.bfRightSeconds,
lastTickTime: this.bfLastTickTime
}))
} catch {
// ignore
}
},
clearBfTimerStorage() {
if (!this.baby) return
try {
localStorage.removeItem(`bfTimer_${this.baby.babyId}`)
} catch {
// ignore
}
},
syncBreastfeedTimer() {
if (!this.baby) return
const active = this.summary?.activeFeeding
if (active) {
let restored = false
try {
const raw = localStorage.getItem(`bfTimer_${this.baby.babyId}`)
if (raw) {
const data = JSON.parse(raw)
this.bfActiveSide = data.activeSide === 'right' ? 'right' : 'left'
this.bfLeftSeconds = Number(data.leftSeconds) || 0
this.bfRightSeconds = Number(data.rightSeconds) || 0
const lastTick = Number(data.lastTickTime) || Date.now()
const delta = Math.max(0, Math.floor((Date.now() - lastTick) / 1000))
if (delta > 0) {
if (this.bfActiveSide === 'left') {
this.bfLeftSeconds += delta
} else {
this.bfRightSeconds += delta
}
}
this.bfLastTickTime = Date.now()
this.bfTimerActive = true
restored = true
}
} catch {
// ignore
}
if (!restored) {
const startMs = active.startTime ? new Date(active.startTime).getTime() : Date.now()
const totalElapsed = Math.max(0, Math.floor((Date.now() - startMs) / 1000))
this.bfActiveSide = this.preferences.defaultBreastSide || 'left'
this.bfLeftSeconds = this.bfActiveSide === 'left' ? totalElapsed : 0
this.bfRightSeconds = this.bfActiveSide === 'right' ? totalElapsed : 0
this.bfLastTickTime = Date.now()
this.bfTimerActive = true
}
this.persistBfTimer()
startBfTicker(this)
} else {
if (this.bfTimerActive) {
this.bfTimerActive = false
this.bfLeftSeconds = 0
this.bfRightSeconds = 0
this.clearBfTimerStorage()
stopBfTicker()
}
}
},
async startBreastfeedTimer(breastSide: 'left' | 'right') {
if (!this.baby) return
await startFeeding({
babyId: this.baby.babyId,
breastSide,
operatorName: this.operatorName
})
this.bfTimerActive = true
this.bfActiveSide = breastSide
this.bfLeftSeconds = 0
this.bfRightSeconds = 0
this.bfLastTickTime = Date.now()
this.persistBfTimer()
startBfTicker(this)
await this.refreshSummary()
},
switchBreastfeedSide(targetSide: 'left' | 'right') {
if (!this.bfTimerActive || this.bfActiveSide === targetSide) return
const now = Date.now()
const delta = Math.max(0, Math.floor((now - this.bfLastTickTime) / 1000))
if (delta > 0) {
if (this.bfActiveSide === 'left') {
this.bfLeftSeconds += delta
} else {
this.bfRightSeconds += delta
}
}
this.bfActiveSide = targetSide
this.bfLastTickTime = now
this.persistBfTimer()
},
async endBreastfeedTimer() {
if (!this.baby) return
if (this.bfTimerActive) {
const now = Date.now()
const delta = Math.max(0, Math.floor((now - this.bfLastTickTime) / 1000))
if (delta > 0) {
if (this.bfActiveSide === 'left') {
this.bfLeftSeconds += delta
} else {
this.bfRightSeconds += delta
}
}
}
const leftMinutes = this.bfLeftSeconds > 0 ? Math.max(1, Math.round(this.bfLeftSeconds / 60)) : 0
const rightMinutes = this.bfRightSeconds > 0 ? Math.max(1, Math.round(this.bfRightSeconds / 60)) : 0
await endFeeding({
babyId: this.baby.babyId,
breastSide: this.bfActiveSide,
leftDurationMinutes: leftMinutes,
rightDurationMinutes: rightMinutes,
operatorName: this.operatorName
})
this.bfTimerActive = false
this.bfLeftSeconds = 0
this.bfRightSeconds = 0
this.clearBfTimerStorage()
stopBfTicker()
await this.refreshSummary() await this.refreshSummary()
}, },
async toggleBreastfeedTimer(breastSide: 'left' | 'right') { async toggleBreastfeedTimer(breastSide: 'left' | 'right') {
if (!this.baby) return if (!this.baby) return
if (this.summary?.activeFeeding) { if (this.summary?.activeFeeding) {
await endFeeding({ babyId: this.baby.babyId, breastSide, operatorName: this.operatorName }) await this.endBreastfeedTimer()
} else { } else {
await startFeeding({ babyId: this.baby.babyId, breastSide, operatorName: this.operatorName }) await this.startBreastfeedTimer(breastSide)
} }
await this.refreshSummary() await this.refreshSummary()
}, },
+787 -4
View File
@@ -79,6 +79,353 @@ button {
font-weight: 800; font-weight: 800;
} }
/* 顶部一体化温润状态卡片 */
.today-top-card {
background: linear-gradient(135deg, #fffbf0 0%, #fff6df 100%);
border: 1px solid #f6e6c4;
border-radius: 16px;
padding: 14px 16px;
box-shadow: 0 4px 14px rgba(184, 134, 11, 0.06);
margin-bottom: 12px;
}
.top-row {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.family-badge {
display: flex;
align-items: center;
gap: 5px;
font-size: 12px;
font-weight: 600;
color: #8c6d3b;
}
.family-icon {
font-size: 14px;
}
.operator-pill {
display: inline-flex;
align-items: center;
gap: 5px;
background: #ffffff;
border: 1px solid #ebd8b2;
border-radius: 999px;
padding: 4px 10px 4px 7px;
cursor: pointer;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
transition: all 0.15s ease;
}
.operator-pill:active {
background: #faf4e8;
transform: scale(0.97);
}
.operator-avatar {
font-size: 14px;
line-height: 1;
}
.operator-text {
font-size: 12px;
font-weight: 700;
color: #5c4314;
}
.pill-arrow {
font-size: 10px;
color: #9c8253;
margin-left: -1px;
}
.baby-main-row {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 12px;
border-radius: 12px;
background: rgba(255, 255, 255, 0.7);
border: 1px solid rgba(246, 230, 196, 0.6);
cursor: pointer;
transition: all 0.15s ease;
}
.baby-main-row:active {
background: rgba(255, 255, 255, 0.95);
transform: scale(0.99);
}
.baby-avatar-wrap {
position: relative;
width: 44px;
height: 44px;
background: #fffaee;
border: 2px solid #ecd8af;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.baby-avatar-emoji {
font-size: 24px;
line-height: 1;
}
.gender-dot {
position: absolute;
right: -2px;
bottom: -2px;
width: 12px;
height: 12px;
border-radius: 50%;
border: 2px solid #ffffff;
}
.gender-dot.boy {
background: #3b82f6;
}
.gender-dot.girl {
background: #ec4899;
}
.baby-meta {
flex: 1;
min-width: 0;
}
.baby-name-row {
display: flex;
align-items: center;
gap: 8px;
}
.baby-name {
margin: 0;
font-size: 20px;
font-weight: 800;
color: #2c2518;
line-height: 1.2;
}
.baby-switch-tag {
font-size: 11px;
font-weight: 600;
color: #8c6d3b;
background: #fbf2dc;
padding: 1px 6px;
border-radius: 4px;
border: 1px solid #ebd9b5;
}
.baby-tags {
display: flex;
align-items: center;
gap: 6px;
margin-top: 4px;
}
.baby-age-chip {
font-size: 12px;
font-weight: 700;
color: #b45309;
background: #fef3c7;
padding: 2px 7px;
border-radius: 4px;
}
.baby-sub-chip {
font-size: 11px;
font-weight: 600;
color: #65707d;
background: #f1f5f9;
padding: 2px 6px;
border-radius: 4px;
}
/* 切换底部抽屉样式 */
.switcher-popup {
left: 0 !important;
right: 0 !important;
margin: 0 auto !important;
width: min(600px, 100%) !important;
max-width: 600px !important;
max-height: 75vh;
}
.popup-sheet {
padding: 16px 16px 20px;
background: #ffffff;
}
.popup-sheet-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
padding-bottom: 12px;
border-bottom: 1px solid #f1f5f9;
}
.popup-title-group h3 {
margin: 0;
font-size: 17px;
font-weight: 800;
color: #1e293b;
}
.popup-subtitle {
font-size: 12px;
color: #64748b;
margin-top: 2px;
display: block;
}
.popup-close-btn {
background: #f1f5f9;
border: none;
border-radius: 50%;
width: 28px;
height: 28px;
display: flex;
align-items: center;
justify-content: center;
color: #64748b;
font-size: 14px;
cursor: pointer;
}
.popup-list {
display: flex;
flex-direction: column;
gap: 10px;
margin-top: 14px;
max-height: 50vh;
overflow-y: auto;
}
.switcher-card {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 14px;
border: 1.5px solid #e2e8f0;
border-radius: 12px;
background: #f8fafc;
cursor: pointer;
transition: all 0.15s ease;
}
.switcher-card:active {
transform: scale(0.98);
}
.switcher-card.active {
border-color: #10b981;
background: #ecfdf5;
}
.switcher-card-left {
display: flex;
align-items: center;
gap: 12px;
}
.switcher-avatar-circle {
width: 38px;
height: 38px;
border-radius: 50%;
background: #ffffff;
border: 1px solid #e2e8f0;
display: flex;
align-items: center;
justify-content: center;
font-size: 20px;
}
.switcher-info {
display: flex;
flex-direction: column;
gap: 2px;
}
.switcher-name-row {
display: flex;
align-items: center;
gap: 6px;
}
.switcher-name {
font-size: 15px;
font-weight: 700;
color: #1e293b;
}
.switcher-badge {
font-size: 10px;
font-weight: 700;
padding: 1px 5px;
border-radius: 4px;
}
.switcher-badge.default {
background: #e2e8f0;
color: #475569;
}
.switcher-badge.current {
background: #d1fae5;
color: #065f46;
}
.switcher-sub-row {
display: flex;
align-items: center;
gap: 4px;
font-size: 12px;
color: #64748b;
}
.dot-sep {
color: #cbd5e1;
}
.switcher-check {
font-size: 18px;
font-weight: 800;
color: #10b981;
}
.popup-footer {
margin-top: 16px;
padding-top: 12px;
border-top: 1px solid #f1f5f9;
}
.popup-footer-btn {
width: 100%;
padding: 10px;
background: #f8fafc;
border: 1px dashed #cbd5e1;
border-radius: 8px;
font-size: 13px;
font-weight: 600;
color: #475569;
cursor: pointer;
text-align: center;
}
.popup-footer-btn:active {
background: #f1f5f9;
}
.context-panel { .context-panel {
margin: 12px 0 16px; margin: 12px 0 16px;
overflow: hidden; overflow: hidden;
@@ -156,6 +503,13 @@ button {
color: #17202a; color: #17202a;
} }
.primary-action:disabled {
opacity: 0.55;
cursor: not-allowed;
filter: grayscale(0.25);
pointer-events: none;
}
.primary-action strong { .primary-action strong {
display: block; display: block;
font-size: 20px; font-size: 20px;
@@ -229,8 +583,7 @@ button {
margin-top: 12px; margin-top: 12px;
} }
.feeding-status, .feeding-status {
.amount-row {
grid-template-columns: 1fr auto auto; grid-template-columns: 1fr auto auto;
align-items: center; align-items: center;
padding: 12px; padding: 12px;
@@ -238,13 +591,240 @@ button {
background: #faf7f1; background: #faf7f1;
} }
.amount-row {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 14px;
border-radius: 8px;
background: #faf7f1;
}
.feeding-status span, .feeding-status span,
.amount-row span { .amount-row span {
color: #65707d; color: #65707d;
font-weight: 600;
} }
.two-actions { .two-actions {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
margin-top: 12px;
}
/* 今日主页四大喂养方式聚合 Tab 样式 */
.feeding-segmented-nav {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 6px;
background: #f1f5f9;
padding: 4px;
border-radius: 12px;
margin: 10px 0 14px;
}
.feeding-tab-btn {
position: relative;
border: none;
background: transparent;
padding: 8px 4px;
border-radius: 9px;
font-size: 13px;
font-weight: 700;
color: #64748b;
cursor: pointer;
transition: all 0.2s ease;
display: flex;
align-items: center;
justify-content: center;
gap: 4px;
user-select: none;
}
.feeding-tab-btn.active {
background: #ffffff;
color: #1e293b;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
}
.tab-live-dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: #10b981;
display: inline-block;
animation: pulse-dot 1.5s infinite;
}
@keyframes pulse-dot {
0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.4; transform: scale(1.3); }
}
.quick-amount-chips {
display: flex;
gap: 8px;
margin: 8px 0 14px;
}
.quick-amount-chips .chip {
flex: 1;
text-align: center;
}
/* 亲喂分别计时双侧卡片 */
.bf-dual-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 12px;
margin-top: 10px;
}
.bf-side-card {
background: #fdfbf7;
border: 2px solid #ede8de;
border-radius: 12px;
padding: 12px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
min-height: 106px;
cursor: pointer;
transition: all 0.2s ease;
user-select: none;
}
.bf-side-card.selected {
border-color: #2b70f0;
background: #f0f5ff;
}
.bf-side-card.active {
border-color: #10b981;
background: #f0fdf4;
box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.15);
}
.bf-card-header {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
}
.bf-card-title {
font-size: 14px;
font-weight: 700;
color: #24292f;
}
.bf-status-tag {
font-size: 11px;
font-weight: 600;
padding: 2px 6px;
border-radius: 4px;
}
.bf-status-tag.timing {
background: #d1fae5;
color: #065f46;
animation: pulse-timing 2s infinite;
}
.bf-status-tag.paused {
background: #fef3c7;
color: #92400e;
}
.bf-status-tag.idle {
background: #f3f4f6;
color: #6b7280;
}
@keyframes pulse-timing {
0%, 100% { opacity: 1; }
50% { opacity: 0.6; }
}
.bf-card-time {
font-size: 26px;
font-weight: 800;
color: #1f2937;
letter-spacing: 0.5px;
margin: 6px 0;
font-variant-numeric: tabular-nums;
}
.bf-side-card.active .bf-card-time {
color: #059669;
}
.bf-card-footer {
width: 100%;
display: flex;
justify-content: center;
margin-top: 4px;
}
.bf-switch-chip {
background: #e0e7ff;
color: #4338ca;
border: none;
border-radius: 999px;
padding: 4px 10px;
font-size: 12px;
font-weight: 600;
cursor: pointer;
width: 100%;
}
.bf-switch-chip:active {
background: #c7d2fe;
}
.bf-switch-chip:disabled {
opacity: 0.5;
cursor: not-allowed;
pointer-events: none;
}
.bf-active-hint {
font-size: 11px;
font-weight: 600;
color: #10b981;
}
.bf-summary-bar {
display: flex;
flex-direction: column;
align-items: center;
gap: 2px;
background: #f8fafc;
border: 1px dashed #cbd5e1;
border-radius: 8px;
padding: 8px 12px;
margin-top: 10px;
font-size: 13px;
color: #334155;
}
.bf-config-box {
background: #f8fafc;
border: 1px solid #e2e8f0;
border-radius: 10px;
padding: 10px 12px;
margin-top: 10px;
}
.bf-live-badge {
font-size: 11px;
font-weight: 700;
color: #059669;
background: #d1fae5;
padding: 2px 8px;
border-radius: 999px;
} }
.timeline-item:last-child, .timeline-item:last-child,
@@ -453,6 +1033,31 @@ button {
to { opacity: 1; } to { opacity: 1; }
} }
/* 全局规范所有底部弹出层在宽屏/PC下的水平居中与宽度自适应 */
.van-popup--bottom {
left: 0 !important;
right: 0 !important;
margin: 0 auto !important;
width: min(600px, 100%) !important;
max-width: 600px !important;
}
.timeline-modal-popup {
left: 0 !important;
right: 0 !important;
margin: 0 auto !important;
width: min(600px, 100%) !important;
max-width: 600px !important;
max-height: 85vh;
}
.modal-sheet-inner {
padding: 20px 20px 32px;
overflow-y: auto;
max-height: 85vh;
background: #ffffff;
}
.modal-sheet { .modal-sheet {
width: 100%; width: 100%;
max-width: 600px; max-width: 600px;
@@ -535,6 +1140,185 @@ button {
margin-bottom: 16px; margin-bottom: 16px;
} }
/* 照护记录工具栏与按日分组样式 */
.timeline-toolbar {
margin-bottom: 16px;
background: #ffffff;
border-radius: 14px;
padding: 12px 14px;
border: 1px solid #ede8de;
}
.timeline-filter-row {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 10px;
}
.date-filter-box {
display: flex;
align-items: center;
background: #fdfbf7;
border: 1px solid #e2dbcd;
border-radius: 8px;
padding: 3px 8px;
gap: 6px;
}
.filter-icon {
font-size: 14px;
line-height: 1;
}
.filter-date-input {
border: none;
background: transparent;
font-size: 13px;
font-weight: 600;
color: #2c2518;
font-family: inherit;
outline: none;
padding: 4px 0;
}
.clear-filter-btn {
background: #ecdac5;
color: #794b1a;
border: none;
border-radius: 4px;
font-size: 11px;
font-weight: 700;
padding: 2px 7px;
cursor: pointer;
transition: background 0.15s ease;
}
.clear-filter-btn:hover {
background: #dfc8af;
}
.toolbar-actions {
display: flex;
align-items: center;
gap: 8px;
}
.sort-toggle-btn {
background: #f8fafc;
color: #475569;
border: 1px solid #cbd5e1;
border-radius: 999px;
font-size: 12px;
font-weight: 600;
padding: 6px 12px;
cursor: pointer;
display: flex;
align-items: center;
gap: 4px;
transition: all 0.2s;
}
.sort-toggle-btn:active {
background: #e2e8f0;
}
.sort-toggle-btn.active {
background: #eff6ff;
color: #1d4ed8;
border-color: #93c5fd;
}
.sort-icon {
font-weight: 800;
}
.timeline-meta-bar {
margin-top: 8px;
font-size: 12px;
color: #65707d;
display: flex;
align-items: center;
justify-content: space-between;
}
.meta-filter-active strong {
color: #b45309;
}
.meta-all-dates strong {
color: #1f2937;
}
.timeline-groups {
display: flex;
flex-direction: column;
gap: 16px;
}
.timeline-day-group {
background: #ffffff;
border-radius: 14px;
border: 1px solid #ede8de;
overflow: hidden;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.02);
}
.timeline-day-header {
background: #fdfbf7;
padding: 10px 14px;
border-bottom: 1px solid #f0eae0;
display: flex;
justify-content: space-between;
align-items: center;
}
.day-header-left {
display: flex;
align-items: center;
gap: 8px;
}
.day-badge-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #f59e0b;
}
.day-title {
font-size: 14px;
font-weight: 700;
color: #1f2937;
}
.day-records-count {
font-size: 12px;
font-weight: 600;
color: #8c7853;
background: #fef3c7;
padding: 2px 8px;
border-radius: 999px;
}
.timeline-day-list {
padding: 0 14px;
}
.timeline-day-list .timeline-item:last-child {
border-bottom: none;
}
.timeline-empty-card {
background: #ffffff;
border-radius: 14px;
border: 1px dashed #d1d5db;
padding: 36px 16px;
text-align: center;
margin-top: 16px;
}
.tag-badge { .tag-badge {
display: inline-block; display: inline-block;
padding: 2px 8px; padding: 2px 8px;
@@ -592,8 +1376,7 @@ button {
grid-template-columns: 1fr; grid-template-columns: 1fr;
} }
.feeding-status, .feeding-status {
.amount-row {
grid-template-columns: 1fr; grid-template-columns: 1fr;
} }
} }
+15
View File
@@ -43,6 +43,8 @@ export interface CareRecord {
startTime: string startTime: string
endTime?: string | null endTime?: string | null
durationMinutes?: number | null durationMinutes?: number | null
leftDurationMinutes?: number | null
rightDurationMinutes?: number | null
feedingMethod?: FeedingMethod | null feedingMethod?: FeedingMethod | null
amountMl?: number | null amountMl?: number | null
excretionType?: ExcretionType | null excretionType?: ExcretionType | null
@@ -84,6 +86,8 @@ export interface CreateManualRecordPayload {
startTime: string startTime: string
endTime?: string | null endTime?: string | null
durationMinutes?: number | null durationMinutes?: number | null
leftDurationMinutes?: number | null
rightDurationMinutes?: number | null
feedingMethod?: FeedingMethod | null feedingMethod?: FeedingMethod | null
amountMl?: number | null amountMl?: number | null
excretionType?: ExcretionType | null excretionType?: ExcretionType | null
@@ -96,6 +100,8 @@ export interface UpdateCareRecordPayload {
startTime?: string startTime?: string
endTime?: string | null endTime?: string | null
durationMinutes?: number | null durationMinutes?: number | null
leftDurationMinutes?: number | null
rightDurationMinutes?: number | null
feedingMethod?: FeedingMethod | null feedingMethod?: FeedingMethod | null
amountMl?: number | null amountMl?: number | null
excretionType?: ExcretionType | null excretionType?: ExcretionType | null
@@ -137,3 +143,12 @@ export interface ApiResponse<T> {
message: string message: string
} }
} }
export interface ServerTimeInfo {
serverTime: string
currentDate: string
currentTime: string
timeZone: string
timestamp: number
}
+115 -6
View File
@@ -1,9 +1,68 @@
export function formatDate(value?: string | null) {
if (!value) return ''
const date = new Date(value)
return getLocalDateStr(date)
}
export function getLocalDateStr(date: Date = new Date()): string {
const y = date.getFullYear()
const m = String(date.getMonth() + 1).padStart(2, '0')
const d = String(date.getDate()).padStart(2, '0')
return `${y}-${m}-${d}`
}
export function getLocalTimeStr(date: Date = new Date()): string {
const h = String(date.getHours()).padStart(2, '0')
const min = String(date.getMinutes()).padStart(2, '0')
return `${h}:${min}`
}
export function formatTime(value?: string | null) { export function formatTime(value?: string | null) {
if (!value) return '--' if (!value) return '--'
const date = new Date(value) const date = new Date(value)
return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}` return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
} }
export function getFriendlyDayLabel(dateStr: string): string {
if (!dateStr) return ''
const today = getLocalDateStr(new Date())
const yesterday = getLocalDateStr(new Date(Date.now() - 86400000))
if (dateStr === today) return `${dateStr} · 今天`
if (dateStr === yesterday) return `${dateStr} · 昨天`
const parts = dateStr.split('-')
if (parts.length === 3) {
const d = new Date(Number(parts[0]), Number(parts[1]) - 1, Number(parts[2]))
const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
const weekday = days[d.getDay()] || ''
return `${dateStr} · ${weekday}`
}
return dateStr
}
export function formatRecordTimeRange(startTime?: string | null, endTime?: string | null) {
if (!startTime) return '--'
const startDate = formatDate(startTime)
const startT = formatTime(startTime)
if (!endTime) {
return `${startDate} ${startT}`
}
const endDate = formatDate(endTime)
const endT = formatTime(endTime)
if (startDate === endDate) {
return `${startDate} ${startT} ~ ${endT}`
}
return `${startDate} ${startT} ~ ${endDate} ${endT}`
}
export function formatCleanNote(noteOrRemark?: string | null): string {
if (!noteOrRemark) return ''
const cleaned = noteOrRemark
.replace(/亲喂侧\s*:\s*[^;;\n]+([;;]\s*)?/g, '')
.trim()
return cleaned
}
export function formatMinutes(minutes: number) { export function formatMinutes(minutes: number) {
const h = Math.floor(minutes / 60) const h = Math.floor(minutes / 60)
const m = minutes % 60 const m = minutes % 60
@@ -12,16 +71,22 @@ export function formatMinutes(minutes: number) {
return `${h} 小时 ${m} 分钟` return `${h} 小时 ${m} 分钟`
} }
export function recordLabel(type: string, sub?: string | null) { export const FEEDING_METHOD_MAP: Record<string, string> = {
if (type === 'feeding') {
const map: Record<string, string> = {
breastfeed: '亲喂', breastfeed: '亲喂',
bottle: '瓶喂', bottle: '瓶喂',
formula: '配方奶', formula: '配方奶',
mixed: '混合', mixed: '混合喂养',
other: '其他' other: '其他'
} }
return `喂奶 · ${map[sub || 'other'] || '其他'}`
export function formatFeedingMethod(method?: string | null): string {
if (!method) return '其他'
return FEEDING_METHOD_MAP[method] || method
}
export function recordLabel(type: string, sub?: string | null) {
if (type === 'feeding') {
return `喂奶 · ${formatFeedingMethod(sub)}`
} }
if (type === 'sleep') return '睡眠' if (type === 'sleep') return '睡眠'
if (type === 'excretion' && sub === 'pee') return '小便' if (type === 'excretion' && sub === 'pee') return '小便'
@@ -29,3 +94,47 @@ export function recordLabel(type: string, sub?: string | null) {
return '记录' return '记录'
} }
export interface FeedingSplitInfo {
leftMinutes?: number
rightMinutes?: number
}
export function parseFeedingSplitInfo(noteOrRemark?: string | null, durationMinutes?: number | null): FeedingSplitInfo | null {
if (!noteOrRemark) return null
const leftMatch = noteOrRemark.match(/左侧\s*(\d+)\s*分钟/)
const rightMatch = noteOrRemark.match(/右侧\s*(\d+)\s*分钟/)
if (leftMatch || rightMatch) {
return {
leftMinutes: leftMatch ? Number(leftMatch[1]) : undefined,
rightMinutes: rightMatch ? Number(rightMatch[1]) : undefined
}
}
if (noteOrRemark.includes('亲喂侧: 左侧') && durationMinutes) {
return { leftMinutes: durationMinutes }
}
if (noteOrRemark.includes('亲喂侧: 右侧') && durationMinutes) {
return { rightMinutes: durationMinutes }
}
return null
}
export function getFeedingSplitInfo(record?: {
leftDurationMinutes?: number | null
rightDurationMinutes?: number | null
remark?: string | null
note?: string | null
durationMinutes?: number | null
} | null): FeedingSplitInfo | null {
if (!record) return null
if ((record.leftDurationMinutes != null && record.leftDurationMinutes > 0) ||
(record.rightDurationMinutes != null && record.rightDurationMinutes > 0)) {
return {
leftMinutes: record.leftDurationMinutes ?? undefined,
rightMinutes: record.rightDurationMinutes ?? undefined
}
}
return parseFeedingSplitInfo(record.remark || record.note, record.durationMinutes)
}
@@ -0,0 +1,55 @@
# 亲喂左右侧时长独立字段架构设计与落地记录 (2026-09-26)
## 1. 背景与目标
在前期亲喂(母乳喂养)功能演进中:
1. 实现了前端分侧计时、秒级累加以及一键记录功能;
2. 为兼容已有数据结构,分侧时长此前暂存在 `remark` 文本中(例如:`亲喂侧: 左侧 10分钟 / 右侧 15分钟`),前端在展示时通过正则提取。
### 为什么必须添加专门字段?
1. **结构化查询与统计需求**:
- 宝妈和月嫂需要掌握双侧吸吮平衡性(预防单侧乳腺堵奶、乳腺炎或大小胸);
- 后续统计报表需要对左右侧总吸吮时长进行聚合统计(如 `SUM(left_duration_minutes)` / `SUM(right_duration_minutes)`),文本字段无法高效做 SQL 聚合计算。
2. **多端消费与数据治理**:
- 未来扩展微信小程序、医生端报告、导出 PDF 时,结构化数值字段 `left_duration_minutes` 和 `right_duration_minutes` 保证了数据的一致性与严谨性,无需依赖各端各写一套正则解析。
3. **补录与编辑的双向绑定**:
- 用户在“补录”或“编辑”亲喂记录时,可以直接通过表单控件查看和修改左右侧分钟数,而不是编辑一段拼接好的备注字符串。
---
## 2. 数据库变更方案
### 2.1 变更表:`care_record`
在 `duration_minutes` 字段后增加两个整数型字段:
- `left_duration_minutes`: `INT NULL COMMENT '亲喂左侧时长(分钟)'`
- `right_duration_minutes`: `INT NULL COMMENT '亲喂右侧时长(分钟)'`
### 2.2 脚本维护
1. **增量脚本**:统一放置在根目录 `/sql/migration/V3__add_breastfeeding_split_durations.sql`;
2. **全量脚本**:同步更新根目录 `/sql/schema-full.sql` 中的 `care_record` 建表语句。
---
## 3. 后端模型与服务改造
1. **实体与传输模型**:
- `CareRecord.java`(实体):补充 `leftDurationMinutes`、`rightDurationMinutes`;
- `CreateFeedingRO.java`:已包含分侧字段,确保其沉淀入库;
- `CreateManualRecordRO.java`:补充 `leftDurationMinutes`、`rightDurationMinutes`;
- `UpdateCareRecordRO.java`:补充 `leftDurationMinutes`、`rightDurationMinutes`;
- `CareRecordDTO.java` 与 `CareRecordVO.java`:补充字段输出;
- `CareRecordConvert.java`:静态双向映射补充。
2. **业务逻辑 (`CareRecordService.java`)**:
- `recordFeeding` / `startFeeding` / `endFeeding`:将分侧时长存入实体的专门字段,同时保留可读的 `remark` 描述;
- `createManual` / `update`:支持直接保存或修改分侧时长。
---
## 4. 前端类型与组件改造
1. **类型定义 (`domain.ts`)**:
- `CareRecord`、`CreateManualRecordPayload`、`UpdateCareRecordPayload` 增加 `leftDurationMinutes`、`rightDurationMinutes`;
2. **展示逻辑 (`format.ts` & `TimelinePage.vue`)**:
- 优先使用 `record.leftDurationMinutes` 和 `record.rightDurationMinutes`;若历史记录中为空,则平滑降级使用 `parseFeedingSplitInfo(remark, durationMinutes)` 正则解析历史文本,保证新老数据完美兼容;
3. **补录与编辑弹窗 (`TimelineManualModal.vue` & `TimelineEditModal.vue`)**:
- 当类型为喂奶且方式为亲喂时,提供左右侧时长设置。
@@ -0,0 +1,64 @@
# 亲喂左右侧分别计时切换与瓶喂奶量设置优化
## 1. 背景与目标
### 1.1 背景
- **亲喂母乳场景**:新生儿(尤其顺产出院头几周)哺乳时,母亲通常需要在左乳和右乳之间交替哺乳(如左侧 10 分钟,拍嗝或休息后换右侧 10 分钟)。原系统只有一个总计时器与单选侧别,无法在哺乳过程中自由切换侧别,更无法分别精确记录左乳与右乳的耗时。
- **瓶喂奶量交互**:在今日主界面中,瓶喂卡片在步进器右侧重复显示了 `{{ bottleAmount }} ml` 文本,视觉冗余;同时当前瓶喂默认奶量(30ml)为硬编码,用户在“设置-照护行为偏好”中配置的默认奶量未与首页有效联动。
### 1.2 优化目标
1. **亲喂左右侧独立分别计时与自由切换**:
- 首页展示左侧与右侧双侧计时看板;
- 未计时时支持选定起始侧(左/右侧);
- 计时中支持随时一键无缝切换侧别(切换到另一侧时,原侧保持已累计时间并暂停,目标侧开始/继续计时);
- 界面实时显示两侧各自累计时间(分:秒)与本次亲喂总耗时;
- 结束亲喂时,后端流水与备注清晰记录左右侧各自时长(如 `亲喂侧: 左侧 10分钟 / 右侧 8分钟`)与总持续分钟数;
- 具备本地存储容灾(息屏、刷新、切页均不丢失计时进度)。
2. **瓶喂奶量精简与设置联动**:
- 瓶喂行删除右侧重复显示的数字文本,仅保留中间步进器输入框;
- 首页瓶喂默认数值联动读取“设置”中的 `defaultBottleAmount`(设置更改后首页同步更新)。
---
## 2. 详细方案设计
### 2.1 亲喂计时器状态与逻辑 (`careStore.ts`)
1. **状态定义**:
- `bfTimerActive`: 是否处于亲喂计时中;
- `bfActiveSide`: 当前计时的侧别(`'left' | 'right'`);
- `bfLeftSeconds`: 左侧累计秒数;
- `bfRightSeconds`: 右侧累计秒数;
- `bfStartTime`: 亲喂开始时间戳;
- `bfLastTickTime`: 上次 tick 时间戳(用于息屏/切后台的时间差补偿)。
2. **操作行为**:
- `startBreastfeedTimer(side)`:启动亲喂,通知后端 `startFeeding`,重置并启动定时器;
- `switchBreastfeedSide(targetSide)`:结算当前侧增量秒数,切换 `bfActiveSide` 为目标侧,刷新持久化缓存;
- `endBreastfeedTimer()`:结算最后秒数,换算左右侧分钟数,调用后端 `endFeeding`(传入左右侧分钟数),清理定时器与缓存;
- `syncTimerState()`:挂载时根据后端 `summary.activeFeeding` 与本地缓存恢复实时秒数。
### 2.2 后端接口与模型扩展
1. **`CreateFeedingRO`**:
- 增加 `leftDurationMinutes`(Integer)与 `rightDurationMinutes`(Integer);
2. **`CareRecordService`**:
- `endFeeding` 时接收左右侧时长,在 `buildFeedingRemark` 中智能生成左右侧具体耗时描述(例如:`亲喂侧: 左侧 10分钟 / 右侧 8分钟`);
- 总时长自动取前后时间差与左右侧时长和的合理最大值。
### 2.3 瓶喂奶量显示与设置配置
1. **`TodayPage.vue`**:
- 去除 `<strong v-if="...` 冗余奶量文本;
- `bottleAmount` 初始值与监听器绑定 `store.preferences.defaultBottleAmount`;
2. **`ActionSettingsTab.vue`**:
- 默认瓶喂奶量配置(`defaultBottleAmount`)保存后通过 Pinia 响应式广播更新。
---
## 3. 影响范围与验证
- 变更范围:
- 后端:`CreateFeedingRO.java`、`CareRecordService.java`
- 前端:`apps/web/src/stores/careStore.ts`、`apps/web/src/pages/TodayPage.vue`、`apps/web/src/api/client.ts`、`apps/web/src/style.css`
- 文档:`doc/` 与 `doc/README.md`
- 验证项:
- 后端单元测试与编译无报错;
- 前端 `vue-tsc -b && vite build` 编译通过;
- 亲喂左右侧分别计时、切换、结束保存全流程验证;
- 瓶喂无重复数字,并在设置调整默认值后首页生效。
@@ -0,0 +1,52 @@
# 底部导航与页面文案贴心化优化记录 (2026-09-26)
## 1. 背景与目标
在原有的产品设计中,底部导航的 4 个 Tab 分别命名为:
- `今日` (`/today`)
- `流水` (`/timeline`)
- `统计` (`/stats`)
- `设置` (`/settings`)
### 存在的问题与用户体验痛点
1. **“流水”过于生硬与工程化**:
- “流水”是典型的金融记账或技术开发词汇(如数据流水、交易流水),与新生儿家庭的温情照护场景严重脱节;
- 父母或月嫂在实际沟通中只会说“看看上一顿喂奶的记录”、“帮我补记一条”,用户心智模型是“照护记录”,而非“查流水”。
2. **“设置”过于机械化与技术化**:
- “设置”通常对应于底层系统参数配置,而该页面核心承载的是宝宝成长档案(出生日期、顺产/剖腹产、月龄)、家庭与协作邀请、家人角色(爸爸、妈妈、月嫂、长辈)以及个人喂养偏好;
- 命名为“家庭”,赋予了共同带娃的家庭归属感与温度。
3. **整体协调与产品定位**:
- 顺产 3 天新生儿家庭,核心场景是每日照护。底部导航栏是使用最高频的锚点,文案应当温暖、亲切且意图明确。
---
## 2. 优化方案
### 2.1 底部导航 Tab 优化对照
| 路由路径 | 原 Tab 名称 | 优化后 Tab 名称 | 设计意图与用户心智 |
| :--- | :--- | :--- | :--- |
| `/today` | 今日 | **今日** | 聚焦当前时刻,即时亲喂计时、瓶喂睡眠排泄快捷打卡 |
| `/timeline` | 流水 | **记录** | 彻底摒弃冰冷“流水”,清晰表达全天照护事件的时间轴与历史记录 |
| `/stats` | 统计 | **统计** | 直观汇总全天喂养频次、睡眠时长与尿布排泄事实 |
| `/settings` | 设置 | **家庭** | 彻底摒弃系统级“设置”,凸显宝宝档案、全家协同与成员角色管理 |
### 2.2 关联页面细节文案同步优化
1. **记录页 (`TimelinePage.vue`)**:
- 标题由 `照护流水` 调整为 `照护记录`;
- 注释及相关提示文案同步更新为“记录”。
2. **家庭页 (`SettingsPage.vue`)**:
- 副标题(eyebrow)由 `设置与配置` 调整为 `宝宝与家庭`;
- 标题由 `家庭照护维护` 优化为更亲切的 `家庭照护管理`。
3. **今日页 (`TodayPage.vue`) 快捷跳转**:
- 抽屉底部空状态引导文案由 `⚙️ 前往设置管理宝宝档案` 优化为 `👶 前往家庭管理宝宝档案`;
- `⚙️ 前往设置管理家庭成员` 优化为 `👨‍👩‍👧 前往家庭管理家庭成员`。
---
## 3. 实现与验证
- 更新 `apps/web/src/App.vue` 中的 Tab 数组定义;
- 更新 `apps/web/src/pages/TimelinePage.vue`;
- 更新 `apps/web/src/pages/SettingsPage.vue`;
- 更新 `apps/web/src/pages/TodayPage.vue`;
- 执行 `npm run build`,确保 TypeScript 编译通过并归档至 `deploy/artifacts/web`。
@@ -0,0 +1,53 @@
# 照护记录页面按日分组优化与服务端上海时区校准设计文档
## 1. 需求背景与目标
1. **服务端时区校准(方案B)**:
- 生产/部署容器默认系统时区为 UTC(`Etc/UTC`),导致 `SystemController` 返回的 `currentDate` 为昨日(相差 8 小时),`serverTime` 亦呈现 UTC 时间;
- 需要在服务端显式指定上海时区(`Asia/Shanghai`),并设置 JVM 默认时区,确保时间接口输出与业务数据库统一在东八区。
2. **记录页面(【记录】Tab)深度优化**:
- **全量展示与倒序排列**:进入【记录】页面默认展示该宝宝所有历史日期的记录,而非仅限于今天;整体按日期倒序排列(最新日期置顶);
- **按日分组(Day Grouping)**:记录依据开始时间所属日期进行自然分组展示(例如:“2026-09-26 · 今天 · 共 5 条”),分组视觉层次清晰温馨;
- **天内升降序切换**:同一天内部支持用户自由切换时间的升序(由早到晚,正向观察作息)与降序(由晚到早,快速查看最新进展);
- **日期过滤查询**:顶部提供日期筛选输入框,可快速指定查看某一天的详细记录,并支持一键清除筛选以恢复全部展示。
---
## 2. 方案设计与技术实现
### 2.1 后端调整
1. **`SystemController.java` 显式时区转换**:
- 使用 `ZoneId.of("Asia/Shanghai")`,通过 `ZonedDateTime.now(SHANGHAI_ZONE)` 构建响应;
- 返回标准上海时区字符串 `serverTime`、`currentDate`、`currentTime`,以及 `timeZone: "Asia/Shanghai"` 和 `timestamp`;
2. **`BabyTrackerApplication.java` JVM 时区兜底**:
- 增加 `@PostConstruct public void init() { TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai")); }`,保障各类 `LocalDateTime.now()` 与 MyBatis-Plus 审计字段在任何宿主容器下均运行于东八区;
3. **`CareRecordService.java` 支持全量记录查询**:
- 原 `list(String babyId, LocalDate date)` 方法中,若 `date == null` 原先强制赋值为 `LocalDate.now()`,现改为:`date == null` 时不添加日期范围限制,直接查询该宝宝所有未删除记录,按 `start_time DESC` 倒序返回;
- 在 `SummaryService.daily` 中,若未指定日期,显式传入上海时区的当前日期 `LocalDate.now(ZoneId.of("Asia/Shanghai"))`,保持日摘要统计口径稳定。
### 2.2 前端调整
1. **接口层 (`apps/web/src/api/client.ts`)**:
- 暴露 `getCareRecords(babyId: string, date?: string)` 接口,支持带日期筛选或全量获取;
2. **视图与状态管理 (`apps/web/src/pages/TimelinePage.vue`)**:
- 维护独立的 `records = ref<CareRecord[]>([])` 与 `filterDate = ref<string>('')`;
- 维护天内排序状态 `sortOrder = ref<'desc' | 'asc'>('desc')`;
- 提供计算属性 `groupedRecords`:
- 将记录按本地日期归类(如 `2026-09-26`、`2026-09-25`);
- 对日期组按日期倒序排列;
- 对每组内的记录根据 `sortOrder` 进行升序或降序排列;
- 赋予自然语言日期标签(如“今天”、“昨天”、“周X”);
- 顶部提供日期过滤控件与“升序/降序”切换按钮;
- 在补录、编辑或删除操作成功后,同时刷新 `fetchRecords()` 与 `store.refreshSummary()`,保证全局状态一致。
---
## 3. 验收标准
1. `GET /api/v1/system/time` 返回的 `timeZone` 为 `Asia/Shanghai`,`currentDate` 与 `currentTime` 均为准确的北京时间;
2. 进入【记录】页面,默认加载并展示历史所有记录,按天分块分组清晰;
3. 点击“时间倒序 / 时间正序”按钮,当天内的记录顺序即时切换;
4. 选择特定日期时,页面仅展示该日期的记录分组;清空筛选时恢复全量展示;
5. 新增/编辑/删除记录后,分组列表即时更新;
6. `npm run build` 与 `mvn test` 均通过无错误。
@@ -0,0 +1,61 @@
# 服务器时间同步与全端时区日期一致性设计方案
## 1. 背景与问题定义
用户在使用系统时反馈:在今天(2026-09-26)凌晨 03:25 操作照护补录,页面展示的时刻为 03:25,但落库存储的日期却变成了昨天(2026-09-25 03:25)。
### 根因复盘
1. **时区混用缺陷**:
- 凌晨 00:00 ~ 08:00(UTC+8 / 上海时区)时,由于北京时间比格林威治标准时间快 8 小时,UTC 时间此时仍在前一天(昨天 16:00 ~ 昨天 23:59);
- 前端表单初始化默认日期时,使用了 `now.toISOString().slice(0, 10)`,`toISOString()` 强制将时间转为 UTC,导致截出的日期为**昨天(2026-09-25)**;
- 与此同时,时间部分却使用了 `now.toTimeString().slice(0, 5)`,提取的是本地时刻 **`03:25`**;
- 两者拼接为 `2026-09-25T03:25:00`,提交后端原样存入 MySQL `DATETIME` 字段,造成“日期提前一天、时间不变”的数据偏差。
2. **前后端时钟一致性需求**:
- 为避免客户端本地设备时钟错误(如手机时间不准、跨时区出差或恶意篡改本地时间),需要后端提供统一的服务器时间接口,由前端对齐服务器时钟。
---
## 2. 方案设计
### 2.1 后端接口与时区模型
新增系统与通用模块 `com.babytracker.module.system`:
1. **控制器**:`SystemController`
- 端点:`/api/v1/system/time`(同时支持 `GET` 和 `POST`,便于无参请求与标准协议兼容);
- 响应:`ApiResponse<ServerTimeVO>`。
2. **响应对象**:`ServerTimeVO`
```java
public class ServerTimeVO {
/** 服务器当前完整日期时间 */
private LocalDateTime serverTime;
/** 服务器当前日期 (yyyy-MM-dd) */
private String currentDate;
/** 服务器当前时间 (HH:mm:ss) */
private String currentTime;
/** 服务器时区 (如 Asia/Shanghai) */
private String timeZone;
/** 服务器当前时间戳毫秒数 */
private Long timestamp;
}
```
- 严格遵循 `AGENTS.md`:字段配备完整 JavaDoc 注释与 Lombok。
### 2.2 前端对齐与格式化工具改造
1. **接口封装**:在 `apps/web/src/api/client.ts` 中封装 `getServerTime(): Promise<ServerTimeVO>`;
2. **时钟对齐**:在 Pinia `careStore.ts` 中记录客户端与服务器的时间偏移差值:
$$\text{serverOffsetMs} = \text{serverTime.timestamp} - \text{Date.now()}$$
提供 `store.getServerNow(): Date` 方法,无论客户端本地时钟如何偏移,均能基于服务器时钟推算当前服务器的实时 `Date`;
3. **彻底杜绝 `toISOString()` 截取日期**:
在 `apps/web/src/utils/format.ts` 中提供本地时区标准格式化工具:
- `getLocalDateStr(date: Date)`:精准输出本地时区的 `yyyy-MM-dd`;
- `getLocalTimeStr(date: Date)`:精准输出本地时区的 `HH:mm`;
4. **全面替换业务组件**:
- `TimelineManualModal.vue`(补录弹窗默认日期/时间);
- `TodayPage.vue`(一键亲喂与快速记录的开始/结束时间);
- `BabySettingsTab.vue`(添加宝宝的默认出生日期)。
---
## 3. 验收标准
1. 在凌晨 00:00 ~ 08:00 之间打开任何补录弹窗或添加宝宝,日期必须严格等于服务器当天日期,绝不提前一天;
2. 提交到后端的照护事件时间字面量与服务器当前时刻严格同步;
3. `mvn test` 与前端 `npm run build` 全部成功通过。
@@ -0,0 +1,47 @@
# 流水编辑弹窗位置修复与亲喂总时长起止时间优化
## 1. 背景与目标
### 1.1 背景
- **弹窗位置缺陷**:在“流水”页面点击编辑照护记录时,弹窗(`TimelineEditModal`)受局部容器上下文和 `align-items: flex-end` 样式影响,在页面较长或滚动场景下出现在页面底部,导致用户必须向下滚动滚轮才能看到弹窗内容,体验不便。
- **亲喂时间记录与展示不全**:此前亲喂一键记录未指定总耗时,结束时间为空;且流水中仅显示单点时间或侧别文字,未能完整展示总的开始与结束时间(如 `18:00 ~ 18:20 · 20分钟`),也未能清晰以徽章/结构化形式分别展示左侧与右侧的独立耗时。
### 1.2 优化目标
1. **流水编辑与补录弹窗位置修复**:
- 将 `TimelineEditModal.vue` 与 `TimelineManualModal.vue` 重构成基于 `van-popup`(`teleport="body"`)的移动端底部标准抽屉;
- 无论页面滚动在何处,点击“编辑”或“补录”瞬间,弹窗始终精准呈现在当前屏幕视口内,免去滚轮滚动。
2. **亲喂一次性记录总时间与起止时间联动**:
- 亲喂记录支持设定总耗时(如默认 20 分钟),系统自动联动总开始时间和总结束时间(`startTime ~ endTime`);
- 支持左侧、右侧、双侧分别配置耗时(如左侧 10 分钟 / 右侧 10 分钟,自动汇总总时间 20 分钟);
3. **流水时间线分别展示左右耗时**:
- 流水卡片中统一展示总的开始时间与结束时间(如 `18:00 ~ 18:20`)及总时长;
- 存在左右分侧记录时,分别以专属徽章直观呈现两侧耗时(如 `左: 10分钟`、`右: 10分钟`);
4. **今日 Tab 操作同步升级**:
- “今日” Tab 中的亲喂卡片支持选择单侧(左/右)或双侧(左右皆喂),并提供快捷总时长设置;
- 点击“一键记录”自动按所选时长及分侧耗时生成完整的起止时间并入库。
---
## 2. 方案实现细节
### 2.1 后端扩展与入参适配
1. `CreateFeedingRO` 增加 `durationMinutes` 字段;
2. `CareRecordService.createFeeding`:
- 亲喂记录传入总时长或左右侧时长时,自动推算 `startTime` 与 `endTime`,保证流水记录起止时间完整;
- `buildFeedingRemark` 持续维护结构化分侧备注。
### 2.2 前端 API 与状态对齐
1. `client.ts` 与 `careStore.ts`:
- `createFeeding` / `logFeeding` 支持传递 `durationMinutes`, `startTime`, `endTime`, `leftDurationMinutes`, `rightDurationMinutes`;
- 增加分侧耗时解析工具函数 `parseFeedingSplitInfo`。
### 2.3 弹窗重构与视口定位
- 使用 `<van-popup v-model:show="show" position="bottom" round safe-area-inset-bottom teleport="body">`;
- 限制 `max-height: 85vh`,内部表单自适应滚动,底部操作栏清晰常驻。
---
## 3. 验证项
1. 点击任何滚动位置的流水记录“编辑”,弹窗立即在当前视口底部滑出,无需滑动页面;
2. 亲喂一键记录及手动编辑时输入左右分侧时长,总时间与起止时间准确联动;
3. 流水列表清晰展示总起止时间、总耗时及左/右侧分别耗时。
@@ -0,0 +1,64 @@
# 今日照护操作防重与接口响应置灰机制方案
## 1. 背景与目标
- **问题背景**:
在【今日】(`TodayPage.vue`)照护首页进行亲喂计时、一键亲喂、瓶喂、配方奶、混合喂养、睡眠、小便、大便等高频操作时,若用户在网络偶发延迟或弱网环境下连续快速点击,容易造成重复请求与多次入库,甚至导致状态混乱。
- **优化目标**:
在任何照护操作触发后,全局锁定操作状态(`operating = true`),将操作按钮立即置灰并禁用(`disabled`)以及展示 loading 加载态,直至接口响应完成才恢复可操作,彻底杜绝重复提交。
---
## 2. 方案设计
### 2.1 状态管理与防重拦截
在 `TodayPage.vue` 中收敛并强化 `runWithTip` 执行器:
```ts
const operating = ref(false)
async function runWithTip(action: () => Promise<void>, message?: string) {
if (operating.value) return // 1. 拦截并发与防抖防重
operating.value = true // 2. 锁定操作状态
try {
await action()
if (message) {
showToast({ message, type: 'success', duration: 1400 })
}
} catch (err: any) {
showToast(err.message || '操作失败')
} finally {
operating.value = false // 3. 接口返回后解锁
}
}
```
### 2.2 视图层(UI)禁用置灰与 Loading 态绑定
1. **喂养面板各操作**:
- 开始亲喂:`<van-button :disabled="operating" :loading="operating">`;
- 一键记录亲喂:`<van-button :disabled="operating" :loading="operating">`;
- 切换侧别:`<van-button :disabled="operating">`;
- 结束亲喂:`<van-button :disabled="operating" :loading="operating">`;
- 记录瓶喂:`<van-button :disabled="operating" :loading="operating">`;
- 记录配方奶:`<van-button :disabled="operating" :loading="operating">`;
- 记录混合喂养:`<van-button :disabled="operating" :loading="operating">`。
2. **快速记录面板(睡眠、小便、大便)**:
- `<button class="primary-action sleep" :disabled="operating">`
- `<button class="primary-action pee" :disabled="operating">`
- `<button class="primary-action poop" :disabled="operating">`
3. **视觉反馈样式**:
在 `style.css` 中增加 `.primary-action:disabled` 视觉表现:
```css
.primary-action:disabled {
opacity: 0.55;
cursor: not-allowed;
filter: grayscale(0.2);
pointer-events: none;
}
```
---
## 3. 验收标准
1. 点击任何喂养或快速记录按钮后,按钮立即进入 loading 或置灰状态,连续多次点击不会发出多次网络请求;
2. 接口返回后(无论成功还是异常),按钮解除置灰并恢复正常交互;
3. `npm run build` 前端校验与编译成功。
@@ -0,0 +1,56 @@
# 今日主页四大喂养方式聚合 Tab 设计方案
## 1. 背景与业务目标
- **当前现状**:
在【今日】(`TodayPage.vue`)照护首页中,“亲喂”与“瓶喂”各自占用独立的卡片面板,垂直占用了较多屏幕空间;同时,系统定义的基础喂养方式中的另外两种——**“配方奶 (formula)”**与**“混合喂养 (mixed)”**无法直接在今日首页快速录入,导致操作能力不全。
- **优化目标**:
将“亲喂”、“瓶喂”、“配方奶”、“混合喂养”四大高频喂养方式合并收敛为统一的**【喂养】**面板,通过亲切友好的二级 Tab / 分段选择器(Segmented Tabs)切换,实现四合一极简高效操作。
---
## 2. 交互与功能设计
### 2.1 面板布局结构
在【今日】页面中,原“亲喂”与“瓶喂”两个 Panel 合并为一个标准的【喂养】Panel:
```
┌────────────────────────────────────────────────────────┐
│ 喂养 [亲喂进行中] │
│ [ 亲喂 ] [ 瓶喂 ] [ 配方奶 ] [ 混合喂养 ] │
├────────────────────────────────────────────────────────┤
│ Tab 1: 亲喂 │
│ - 左右侧分别耗时卡片与计时状态 (00:00) │
│ - 亲喂模式 (双侧/仅左/仅右) & 快捷耗时胶囊 │
│ - 开始亲喂 / 一键记录 / 切换侧别 / 结束亲喂 │
├────────────────────────────────────────────────────────┤
│ Tab 2: 瓶喂 │
│ - 奶量步进器 (ml) & 30/60/90/120ml 快捷选项 │
│ - 记录瓶喂按钮 │
├────────────────────────────────────────────────────────┤
│ Tab 3: 配方奶 │
│ - 奶量步进器 (ml) & 快捷奶量选项 │
│ - 记录配方奶按钮 │
├────────────────────────────────────────────────────────┤
│ Tab 4: 混合喂养 │
│ - 奶量步进器 (ml) & 快捷奶量选项 │
│ - 快捷场景便签 (+ 先亲喂后补配方、+ 补配方等) │
│ - 记录混合喂养按钮 │
└────────────────────────────────────────────────────────┘
```
### 2.2 状态与偏好联动
1. **默认 Tab 激活策略**:
- 页面加载时,优先根据用户在【家庭 -> 照护偏好】中设置的 `defaultFeedingMethod` 自动高亮对应 Tab;
- 若当前有正在进行中的亲喂计时(`store.bfTimerActive == true`),则强制优先展示【亲喂】Tab,并在 Tab 标签右上角显示动态呼吸绿点;
2. **快捷记录与轻提示**:
- 点击记录配方奶后提示:`已记录配方奶 {amount}ml`;
- 点击记录混合喂养后提示:`已记录混合喂养 {amount}ml`;
- 记录完成后自动刷新今日总次数与最近一次喂奶状态。
---
## 3. 验收标准
1. 页面无两个分散的喂养面板,整合成一个带有 4 种喂养子 Tab 的统一卡片;
2. 亲喂计时进行中不影响切换 Tab 查阅,切回亲喂 Tab 计时状态完全保持;
3. 瓶喂、配方奶、混合喂养均可调节奶量并一键记录,数据正确计入今日统计与流水;
4. `npm run build` 前端编译与类型校验 100% 通过。
@@ -0,0 +1,53 @@
# 今日 Tab 顶部宝宝信息展示与切换交互优化
## 1. 背景与目标
### 1.1 背景
- **顶部信息视觉割裂**:原“今日”页面顶部采用上方黄色 Hero 大卡片(展示家庭、宝宝名字、天数与记录人),下方紧接一个独立的白色 `van-dropdown-menu` 下拉条(分别包含“宝宝”与“记录人”下拉项)。两者存在大量信息重复,且垂直方向占据了过多屏幕空间,挤压了高频记录核心操作区。
- **下拉菜单体验生硬**:原生 `van-dropdown-menu` 属于典型电商筛选器交互,展开时直接从导航条向下弹开大面积遮罩,层级突兀,在母婴日常单手操作场景下不够自然顺畅。
### 1.2 优化目标
1. **一体化温润状态卡片**:
- 融合家庭名称、宝宝信息与记录人身份,合并为一个精致紧凑的顶部 Header;
- 左侧主体呈现宝宝头像、昵称、出生天数/分娩标签及切换微标;
- 右上角以胶囊徽标(Pill Tag)呈现当前记录人(带身份图标与下拉指示);
- 大幅释放黄金首屏垂直空间,操作“所见即所点”。
2. **轻量优雅的切换弹窗 (Action Bottom Sheet)**:
- 移除生硬的 `van-dropdown-menu`;
- 点击宝宝信息区,唤起专为母婴定制的“切换宝宝档案”底部抽屉,清晰展示各宝宝年龄、性别及当前选中态,并提供前往设置的管理入口;
- 点击记录人胶囊,唤起“选择当前记录人”底部抽屉,直观展示家庭成员及选中状态,单手一键切换。
---
## 2. 详细交互设计与实现
### 2.1 顶部一体化卡片 (`today-top-card`)
- **顶栏 (`top-row`)**:
- 家庭标签:`🏡 [家庭名称]`
- 记录人胶囊:`👩 [记录人] ▾`(根据称谓匹配萌趣身份图标)
- **宝宝主体栏 (`baby-main-row`)**:
- 头像区:圆角萌趣宝宝头像与性别识别微标
- 文本区:大字宝宝昵称 + `切换 ▾` 按钮 + `出生第 X 天` 芯片 + 分娩方式标签
### 2.2 底部切换弹层 (`van-action-sheet` / `van-popup`)
1. **宝宝切换器**:
- 支持多宝宝多档案切换;
- 动态计算并展示每个宝宝的当前年龄与性别;
- 选中后自动刷新今日概览流水并给出轻提示。
2. **记录人切换器**:
- 罗列家庭全部看护成员;
- 标明当前活跃记录人与默认看护人;
- 一键点选切换,全局状态即时同步。
---
## 3. 影响范围与验证
- 变更文件:
- 前端视图:`apps/web/src/pages/TodayPage.vue`
- 前端样式:`apps/web/src/style.css`
- 文档:`doc/2026-09-26-today-header-and-switchers-optimization.md`、`doc/README.md`
- 验证项:
- 前端构建与 TypeScript 检查通过(`npm run build`);
- 顶部信息融合后布局美观,无信息冗余;
- 宝宝与记录人切换抽屉唤起、点选切换与关闭正常;
- 生产产物自动归档验证。
+9
View File
@@ -17,6 +17,15 @@
- [2026-09-26-settings-maintenance-and-timeline-edit.md](./2026-09-26-settings-maintenance-and-timeline-edit.md): 前端设置模块(宝宝/家庭/成员/行为)全面维护与流水编辑/补录功能实现记录。 - [2026-09-26-settings-maintenance-and-timeline-edit.md](./2026-09-26-settings-maintenance-and-timeline-edit.md): 前端设置模块(宝宝/家庭/成员/行为)全面维护与流水编辑/补录功能实现记录。
- [2026-09-26-audit-fields-ro-vo-dto-restructure.md](./2026-09-26-audit-fields-ro-vo-dto-restructure.md): 统一通用审计字段、请求/响应/转化体分层(RO/VO/DTO)与接口规范化调整记录。 - [2026-09-26-audit-fields-ro-vo-dto-restructure.md](./2026-09-26-audit-fields-ro-vo-dto-restructure.md): 统一通用审计字段、请求/响应/转化体分层(RO/VO/DTO)与接口规范化调整记录。
- [2026-09-26-frontend-settings-timeline-component-split.md](./2026-09-26-frontend-settings-timeline-component-split.md): 前端设置页(4 个 Tab)与流水维护操作(补录/编辑)子组件化重构记录。 - [2026-09-26-frontend-settings-timeline-component-split.md](./2026-09-26-frontend-settings-timeline-component-split.md): 前端设置页(4 个 Tab)与流水维护操作(补录/编辑)子组件化重构记录。
- [2026-09-26-breastfeeding-split-timer-and-bottle-settings.md](./2026-09-26-breastfeeding-split-timer-and-bottle-settings.md): 亲喂左右侧分别计时切换与瓶喂奶量设置优化记录。
- [2026-09-26-today-header-and-switchers-optimization.md](./2026-09-26-today-header-and-switchers-optimization.md): 今日 Tab 顶部宝宝信息展示与切换交互优化记录。
- [2026-09-26-timeline-edit-modal-and-feeding-duration-optimization.md](./2026-09-26-timeline-edit-modal-and-feeding-duration-optimization.md): 流水编辑弹窗位置修复与亲喂总时长起止时间优化记录。
- [2026-09-26-navigation-tabs-wording-optimization.md](./2026-09-26-navigation-tabs-wording-optimization.md): 底部导航与页面文案贴心化(今日·记录·统计·家庭)优化记录。
- [2026-09-26-breastfeeding-split-duration-fields.md](./2026-09-26-breastfeeding-split-duration-fields.md): 亲喂左右侧时长独立字段架构设计与落地记录。
- [2026-09-26-server-time-sync-and-date-consistency.md](./2026-09-26-server-time-sync-and-date-consistency.md): 服务器时间同步与全端时区日期一致性设计方案。
- [2026-09-26-today-feeding-tabs-unification.md](./2026-09-26-today-feeding-tabs-unification.md): 今日主页四大喂养方式聚合 Tab 设计方案。
- [2026-09-26-today-action-debounce-and-disable.md](./2026-09-26-today-action-debounce-and-disable.md): 今日照护操作防重与接口响应置灰机制方案。
- [2026-09-26-server-shanghai-timezone-and-timeline-grouping.md](./2026-09-26-server-shanghai-timezone-and-timeline-grouping.md): 照护记录页面按日分组优化与服务端上海时区校准设计方案。
## 记录原则 ## 记录原则
@@ -1,12 +1,21 @@
package com.babytracker; package com.babytracker;
import jakarta.annotation.PostConstruct;
import org.mybatis.spring.annotation.MapperScan; import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.TimeZone;
@SpringBootApplication @SpringBootApplication
@MapperScan("com.babytracker.module.**.mapper") @MapperScan("com.babytracker.module.**.mapper")
public class BabyTrackerApplication { public class BabyTrackerApplication {
@PostConstruct
public void init() {
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
}
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(BabyTrackerApplication.class, args); SpringApplication.run(BabyTrackerApplication.class, args);
} }
@@ -11,22 +11,40 @@ import java.time.LocalDateTime;
@Data @Data
public abstract class BaseEntity implements Serializable { public abstract class BaseEntity implements Serializable {
/**
* 备注
*/
@TableField("remark") @TableField("remark")
private String remark; private String remark;
/**
* 删除状态: 0未删除, 1已删除
*/
@TableLogic @TableLogic
@TableField(value = "deleted", fill = FieldFill.INSERT) @TableField(value = "deleted", fill = FieldFill.INSERT)
private Integer deleted; private Integer deleted;
/**
* 创建人
*/
@TableField(value = "created_by", fill = FieldFill.INSERT) @TableField(value = "created_by", fill = FieldFill.INSERT)
private String createdBy; private String createdBy;
/**
* 创建时间
*/
@TableField(value = "created_time", fill = FieldFill.INSERT) @TableField(value = "created_time", fill = FieldFill.INSERT)
private LocalDateTime createdTime; private LocalDateTime createdTime;
/**
* 修改人
*/
@TableField(value = "updated_by", fill = FieldFill.INSERT_UPDATE) @TableField(value = "updated_by", fill = FieldFill.INSERT_UPDATE)
private String updatedBy; private String updatedBy;
/**
* 修改时间
*/
@TableField(value = "updated_time", fill = FieldFill.INSERT_UPDATE) @TableField(value = "updated_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updatedTime; private LocalDateTime updatedTime;
} }
@@ -16,27 +16,51 @@ import java.time.temporal.ChronoUnit;
@TableName("baby_profile") @TableName("baby_profile")
public class BabyProfile extends BaseEntity { public class BabyProfile extends BaseEntity {
/**
* 宝宝ID,雪花ID字符串
*/
@TableId(value = "id", type = IdType.INPUT) @TableId(value = "id", type = IdType.INPUT)
private String babyId; private String babyId;
/**
* 所属家庭ID
*/
@TableField("family_id") @TableField("family_id")
private String familyId; private String familyId;
/**
* 宝宝姓名或昵称
*/
@TableField("name") @TableField("name")
private String name; private String name;
/**
* 性别: boy(男宝), girl(女宝), unknown(未知)
*/
@TableField("gender") @TableField("gender")
private String gender; private String gender;
/**
* 出生日期
*/
@TableField("birth_date") @TableField("birth_date")
private LocalDate birthDate; private LocalDate birthDate;
/**
* 分娩方式: natural(顺产), c_section(剖腹产), unknown(未知)
*/
@TableField("delivery_type") @TableField("delivery_type")
private String deliveryType; private String deliveryType;
/**
* 是否默认宝宝: 0否, 1是
*/
@TableField("is_default") @TableField("is_default")
private Integer isDefault; private Integer isDefault;
/**
* 状态: active(正常), archived(归档)
*/
@TableField("status") @TableField("status")
private String status; private String status;
@@ -7,19 +7,78 @@ import java.time.LocalDateTime;
@Data @Data
public class BabyDTO { public class BabyDTO {
/**
* 宝宝ID,雪花ID字符串
*/
private String babyId; private String babyId;
/**
* 所属家庭ID
*/
private String familyId; private String familyId;
/**
* 宝宝姓名或昵称
*/
private String name; private String name;
/**
* 性别: boy(男宝), girl(女宝), unknown(未知)
*/
private String gender; private String gender;
/**
* 出生日期
*/
private LocalDate birthDate; private LocalDate birthDate;
/**
* 分娩方式: natural(顺产), c_section(剖腹产), unknown(未知)
*/
private String deliveryType; private String deliveryType;
/**
* 是否默认宝宝: 0否, 1是
*/
private Integer isDefault; private Integer isDefault;
/**
* 状态: active(正常), archived(归档)
*/
private String status; private String status;
/**
* 出生天数
*/
private long ageDays; private long ageDays;
/**
* 月龄/天数文案描述(如: 出生第 3 天)
*/
private String ageText; private String ageText;
/**
* 备注
*/
private String remark; private String remark;
/**
* 创建人
*/
private String createdBy; private String createdBy;
/**
* 创建时间
*/
private LocalDateTime createdTime; private LocalDateTime createdTime;
/**
* 修改人
*/
private String updatedBy; private String updatedBy;
/**
* 修改时间
*/
private LocalDateTime updatedTime; private LocalDateTime updatedTime;
} }
@@ -5,18 +5,39 @@ import lombok.Data;
@Data @Data
public class CreateBabyRO { public class CreateBabyRO {
/**
* 所属家庭ID,选填(不填则默认为当前活跃家庭)
*/
private String familyId; private String familyId;
/**
* 宝宝姓名或昵称
*/
@NotBlank(message = "宝宝姓名不能为空") @NotBlank(message = "宝宝姓名不能为空")
private String name; private String name;
/**
* 性别: boy(男宝), girl(女宝), unknown(未知)
*/
private String gender; private String gender;
/**
* 出生日期 (格式: yyyy-MM-dd)
*/
private String birthDate; private String birthDate;
/**
* 分娩方式: natural(顺产), c_section(剖腹产), unknown(未知)
*/
private String deliveryType; private String deliveryType;
/**
* 是否设置为当前默认宝宝
*/
private Boolean isDefault; private Boolean isDefault;
/**
* 备注
*/
private String remark; private String remark;
} }
@@ -5,6 +5,9 @@ import lombok.Data;
@Data @Data
public class SetDefaultBabyRO { public class SetDefaultBabyRO {
/**
* 目标宝宝ID
*/
@NotBlank(message = "宝宝ID不能为空") @NotBlank(message = "宝宝ID不能为空")
private String babyId; private String babyId;
} }
@@ -5,16 +5,34 @@ import lombok.Data;
@Data @Data
public class UpdateBabyRO { public class UpdateBabyRO {
/**
* 宝宝ID(选填,不填则默认修改当前宝宝)
*/
private String babyId; private String babyId;
/**
* 宝宝姓名或昵称
*/
@NotBlank(message = "宝宝姓名不能为空") @NotBlank(message = "宝宝姓名不能为空")
private String name; private String name;
/**
* 性别: boy(男宝), girl(女宝), unknown(未知)
*/
private String gender; private String gender;
/**
* 出生日期 (格式: yyyy-MM-dd)
*/
private String birthDate; private String birthDate;
/**
* 分娩方式: natural(顺产), c_section(剖腹产), unknown(未知)
*/
private String deliveryType; private String deliveryType;
/**
* 备注
*/
private String remark; private String remark;
} }
@@ -7,20 +7,79 @@ import java.time.LocalDateTime;
@Data @Data
public class BabyVO { public class BabyVO {
/**
* 宝宝ID,雪花ID字符串
*/
private String babyId; private String babyId;
/**
* 所属家庭ID
*/
private String familyId; private String familyId;
/**
* 宝宝姓名或昵称
*/
private String name; private String name;
/**
* 性别: boy(男宝), girl(女宝), unknown(未知)
*/
private String gender; private String gender;
/**
* 出生日期
*/
private LocalDate birthDate; private LocalDate birthDate;
/**
* 分娩方式: natural(顺产), c_section(剖腹产), unknown(未知)
*/
private String deliveryType; private String deliveryType;
/**
* 是否默认宝宝: 0否, 1是
*/
private Integer isDefault; private Integer isDefault;
/**
* 状态: active(正常), archived(归档)
*/
private String status; private String status;
/**
* 出生天数
*/
private long ageDays; private long ageDays;
/**
* 月龄/天数文案描述(如: 出生第 3 天)
*/
private String ageText; private String ageText;
/**
* 备注
*/
private String remark; private String remark;
/**
* 创建人
*/
private String createdBy; private String createdBy;
/**
* 创建时间
*/
private LocalDateTime createdTime; private LocalDateTime createdTime;
/**
* 修改人
*/
private String updatedBy; private String updatedBy;
/**
* 修改时间
*/
private LocalDateTime updatedTime; private LocalDateTime updatedTime;
public LocalDateTime getCreatedAt() { public LocalDateTime getCreatedAt() {
@@ -13,15 +13,27 @@ import lombok.EqualsAndHashCode;
@TableName("family") @TableName("family")
public class FamilyInfo extends BaseEntity { public class FamilyInfo extends BaseEntity {
/**
* 家庭ID,雪花ID字符串
*/
@TableId(value = "id", type = IdType.INPUT) @TableId(value = "id", type = IdType.INPUT)
private String familyId; private String familyId;
/**
* 家庭名称
*/
@TableField("name") @TableField("name")
private String name; private String name;
/**
* 家庭共享邀请码
*/
@TableField("invite_code") @TableField("invite_code")
private String inviteCode; private String inviteCode;
/**
* 状态: active(正常), archived(归档)
*/
@TableField("status") @TableField("status")
private String status; private String status;
} }
@@ -13,24 +13,45 @@ import lombok.EqualsAndHashCode;
@TableName("family_member") @TableName("family_member")
public class FamilyMember extends BaseEntity { public class FamilyMember extends BaseEntity {
/**
* 成员记录ID,雪花ID字符串
*/
@TableId(value = "id", type = IdType.INPUT) @TableId(value = "id", type = IdType.INPUT)
private String memberId; private String memberId;
/**
* 所属家庭ID
*/
@TableField("family_id") @TableField("family_id")
private String familyId; private String familyId;
/**
* 关联用户ID(未绑定系统用户时可为空)
*/
@TableField("user_id") @TableField("user_id")
private String userId; private String userId;
/**
* 角色称谓(如: 宝妈、宝爸、月嫂、奶奶、外婆)
*/
@TableField("role_name") @TableField("role_name")
private String roleName; private String roleName;
/**
* 角色权限类型: owner(家庭主理人), caregiver(看护成员)
*/
@TableField("role_type") @TableField("role_type")
private String roleType; private String roleType;
/**
* 是否当前默认记录人
*/
@TableField("is_default_operator") @TableField("is_default_operator")
private boolean defaultOperator; private boolean defaultOperator;
/**
* 状态: active(正常), archived(归档)
*/
@TableField("status") @TableField("status")
private String status; private String status;
} }
@@ -6,13 +6,48 @@ import java.time.LocalDateTime;
@Data @Data
public class FamilyDTO { public class FamilyDTO {
/**
* 家庭ID,雪花ID字符串
*/
private String familyId; private String familyId;
/**
* 家庭名称
*/
private String name; private String name;
/**
* 家庭共享邀请码
*/
private String inviteCode; private String inviteCode;
/**
* 状态: active(正常), archived(归档)
*/
private String status; private String status;
/**
* 备注
*/
private String remark; private String remark;
/**
* 创建人
*/
private String createdBy; private String createdBy;
/**
* 创建时间
*/
private LocalDateTime createdTime; private LocalDateTime createdTime;
/**
* 修改人
*/
private String updatedBy; private String updatedBy;
/**
* 修改时间
*/
private LocalDateTime updatedTime; private LocalDateTime updatedTime;
} }
@@ -6,16 +6,63 @@ import java.time.LocalDateTime;
@Data @Data
public class FamilyMemberDTO { public class FamilyMemberDTO {
/**
* 成员ID,雪花ID字符串
*/
private String memberId; private String memberId;
/**
* 所属家庭ID
*/
private String familyId; private String familyId;
/**
* 关联用户ID
*/
private String userId; private String userId;
/**
* 角色称谓(如: 宝妈、宝爸、月嫂、奶奶)
*/
private String roleName; private String roleName;
/**
* 角色权限类型: owner(主理人), caregiver(看护人), viewer(观察者)
*/
private String roleType; private String roleType;
/**
* 是否当前默认记录人
*/
private boolean defaultOperator; private boolean defaultOperator;
/**
* 状态: active(正常), archived(归档)
*/
private String status; private String status;
/**
* 备注
*/
private String remark; private String remark;
/**
* 创建人
*/
private String createdBy; private String createdBy;
/**
* 创建时间
*/
private LocalDateTime createdTime; private LocalDateTime createdTime;
/**
* 修改人
*/
private String updatedBy; private String updatedBy;
/**
* 修改时间
*/
private LocalDateTime updatedTime; private LocalDateTime updatedTime;
} }
@@ -5,14 +5,29 @@ import lombok.Data;
@Data @Data
public class CreateMemberRO { public class CreateMemberRO {
/**
* 所属家庭ID,选填(不填则默认为当前活跃家庭)
*/
private String familyId; private String familyId;
/**
* 角色称谓(如: 宝妈、宝爸、月嫂、奶奶)
*/
@NotBlank(message = "角色称谓不能为空") @NotBlank(message = "角色称谓不能为空")
private String roleName; private String roleName;
private String roleType; // owner, caregiver, viewer /**
* 权限角色类型: owner(主理人), caregiver(看护人), viewer(观察者)
*/
private String roleType;
/**
* 是否设为默认记录人
*/
private Boolean defaultOperator; private Boolean defaultOperator;
/**
* 备注
*/
private String remark; private String remark;
} }
@@ -5,8 +5,14 @@ import lombok.Data;
@Data @Data
public class DeleteMemberRO { public class DeleteMemberRO {
/**
* 家庭ID,选填
*/
private String familyId; private String familyId;
/**
* 待删除的成员ID
*/
@NotBlank(message = "成员ID不能为空") @NotBlank(message = "成员ID不能为空")
private String memberId; private String memberId;
} }
@@ -5,12 +5,24 @@ import lombok.Data;
@Data @Data
public class UpdateFamilyRO { public class UpdateFamilyRO {
/**
* 家庭ID(选填,不填则默认修改当前家庭)
*/
private String familyId; private String familyId;
/**
* 家庭名称
*/
@NotBlank(message = "家庭名称不能为空") @NotBlank(message = "家庭名称不能为空")
private String name; private String name;
/**
* 家庭共享邀请码
*/
private String inviteCode; private String inviteCode;
/**
* 备注
*/
private String remark; private String remark;
} }
@@ -5,17 +5,35 @@ import lombok.Data;
@Data @Data
public class UpdateMemberRO { public class UpdateMemberRO {
/**
* 家庭ID,选填
*/
private String familyId; private String familyId;
/**
* 成员ID
*/
@NotBlank(message = "成员ID不能为空") @NotBlank(message = "成员ID不能为空")
private String memberId; private String memberId;
/**
* 角色称谓(如: 宝妈、宝爸、月嫂、奶奶)
*/
@NotBlank(message = "角色称谓不能为空") @NotBlank(message = "角色称谓不能为空")
private String roleName; private String roleName;
private String roleType; // owner, caregiver, viewer /**
* 权限角色类型: owner(主理人), caregiver(看护人), viewer(观察者)
*/
private String roleType;
/**
* 是否设为默认记录人
*/
private Boolean defaultOperator; private Boolean defaultOperator;
/**
* 备注
*/
private String remark; private String remark;
} }
@@ -7,7 +7,18 @@ import java.util.List;
@Data @Data
public class FamilyContextVO { public class FamilyContextVO {
/**
* 当前家庭信息
*/
private FamilyVO family; private FamilyVO family;
/**
* 家庭下的宝宝档案列表
*/
private List<BabyVO> babies; private List<BabyVO> babies;
/**
* 家庭成员列表
*/
private List<FamilyMemberVO> members; private List<FamilyMemberVO> members;
} }
@@ -6,17 +6,64 @@ import java.time.LocalDateTime;
@Data @Data
public class FamilyMemberVO { public class FamilyMemberVO {
/**
* 成员ID,雪花ID字符串
*/
private String memberId; private String memberId;
/**
* 所属家庭ID
*/
private String familyId; private String familyId;
/**
* 关联用户ID
*/
private String userId; private String userId;
/**
* 角色称谓(如: 宝妈、宝爸、月嫂、奶奶)
*/
private String roleName; private String roleName;
/**
* 角色权限类型: owner(主理人), caregiver(看护人), viewer(观察者)
*/
private String roleType; private String roleType;
/**
* 是否当前默认记录人
*/
private boolean defaultOperator; private boolean defaultOperator;
/**
* 状态: active(正常), archived(归档)
*/
private String status; private String status;
/**
* 备注
*/
private String remark; private String remark;
/**
* 创建人
*/
private String createdBy; private String createdBy;
/**
* 创建时间
*/
private LocalDateTime createdTime; private LocalDateTime createdTime;
/**
* 修改人
*/
private String updatedBy; private String updatedBy;
/**
* 修改时间
*/
private LocalDateTime updatedTime; private LocalDateTime updatedTime;
public LocalDateTime getCreatedAt() { public LocalDateTime getCreatedAt() {
@@ -6,14 +6,49 @@ import java.time.LocalDateTime;
@Data @Data
public class FamilyVO { public class FamilyVO {
/**
* 家庭ID,雪花ID字符串
*/
private String familyId; private String familyId;
/**
* 家庭名称
*/
private String name; private String name;
/**
* 家庭共享邀请码
*/
private String inviteCode; private String inviteCode;
/**
* 状态: active(正常), archived(归档)
*/
private String status; private String status;
/**
* 备注
*/
private String remark; private String remark;
/**
* 创建人
*/
private String createdBy; private String createdBy;
/**
* 创建时间
*/
private LocalDateTime createdTime; private LocalDateTime createdTime;
/**
* 修改人
*/
private String updatedBy; private String updatedBy;
/**
* 修改时间
*/
private LocalDateTime updatedTime; private LocalDateTime updatedTime;
public LocalDateTime getCreatedAt() { public LocalDateTime getCreatedAt() {
@@ -16,42 +16,93 @@ import java.time.LocalDateTime;
@TableName("care_record") @TableName("care_record")
public class CareRecord extends BaseEntity { public class CareRecord extends BaseEntity {
/**
* 记录ID,雪花ID字符串
*/
@TableId(value = "id", type = IdType.INPUT) @TableId(value = "id", type = IdType.INPUT)
private String recordId; private String recordId;
/**
* 家庭ID
*/
@TableField("family_id") @TableField("family_id")
private String familyId; private String familyId;
/**
* 宝宝ID
*/
@TableField("baby_id") @TableField("baby_id")
private String babyId; private String babyId;
/**
* 记录类型: feeding(喂奶), sleep(睡眠), excretion(排泄)
*/
@TableField("record_type") @TableField("record_type")
private String recordType; private String recordType;
/**
* 开始时间 / 发生时间
*/
@TableField("start_time") @TableField("start_time")
private LocalDateTime startTime; private LocalDateTime startTime;
/**
* 结束时间(可选,计时类项目结束时填充)
*/
@TableField("end_time") @TableField("end_time")
private LocalDateTime endTime; private LocalDateTime endTime;
/**
* 持续时长(分钟)
*/
@TableField("duration_minutes") @TableField("duration_minutes")
private Integer durationMinutes; private Integer durationMinutes;
/**
* 亲喂左侧时长(分钟)
*/
@TableField("left_duration_minutes")
private Integer leftDurationMinutes;
/**
* 亲喂右侧时长(分钟)
*/
@TableField("right_duration_minutes")
private Integer rightDurationMinutes;
/**
* 喂奶方式: breastfeed(亲喂), bottle(瓶喂), formula(配方奶), mixed(混合喂养), other(其他)
*/
@TableField("feeding_method") @TableField("feeding_method")
private String feedingMethod; private String feedingMethod;
/**
* 奶量(毫升 ml,瓶喂/配方奶时填写)
*/
@TableField("amount_ml") @TableField("amount_ml")
private Integer amountMl; private Integer amountMl;
/**
* 排泄类型: pee(小便), poop(大便)
*/
@TableField("excretion_type") @TableField("excretion_type")
private String excretionType; private String excretionType;
/**
* 记录人称谓(如: 宝妈、宝爸、月嫂)
*/
@TableField("operator_name") @TableField("operator_name")
private String operatorName; private String operatorName;
/**
* 记录人用户ID(可选)
*/
@TableField("operator_user_id") @TableField("operator_user_id")
private String operatorUserId; private String operatorUserId;
/**
* 记录来源: h5, miniapp, admin, system
*/
@TableField("source") @TableField("source")
private String source = "h5"; private String source = "h5";
@@ -28,27 +28,50 @@ public class CareRecordService {
private final SnowflakeIdGenerator idGenerator; private final SnowflakeIdGenerator idGenerator;
public List<CareRecordVO> list(String babyId, LocalDate date) { public List<CareRecordVO> list(String babyId, LocalDate date) {
LocalDate targetDate = date == null ? LocalDate.now() : date; LambdaQueryWrapper<CareRecord> wrapper = new LambdaQueryWrapper<CareRecord>()
LocalDateTime dayStart = targetDate.atStartOfDay(); .eq(CareRecord::getBabyId, babyId);
LocalDateTime dayEnd = targetDate.plusDays(1).atStartOfDay(); if (date != null) {
LocalDateTime dayStart = date.atStartOfDay();
LocalDateTime dayEnd = date.plusDays(1).atStartOfDay();
wrapper.ge(CareRecord::getStartTime, dayStart)
.lt(CareRecord::getStartTime, dayEnd);
}
wrapper.orderByDesc(CareRecord::getStartTime)
.orderByDesc(CareRecord::getRecordId);
List<CareRecord> records = careRecordMapper.selectList( List<CareRecord> records = careRecordMapper.selectList(wrapper);
new LambdaQueryWrapper<CareRecord>()
.eq(CareRecord::getBabyId, babyId)
.ge(CareRecord::getStartTime, dayStart)
.lt(CareRecord::getStartTime, dayEnd)
.orderByDesc(CareRecord::getStartTime)
.orderByDesc(CareRecord::getRecordId)
);
return CareRecordConvert.toVOList(records); return CareRecordConvert.toVOList(records);
} }
public CareRecordVO createFeeding(CreateFeedingRO request) { public CareRecordVO createFeeding(CreateFeedingRO request) {
CareRecord record = baseRecord(request.getBabyId(), "feeding", request.getFeedingTime(), request.getOperatorName(), request.getRemark()); String remark = "breastfeed".equals(request.getFeedingMethod()) ? buildFeedingRemark(request) : request.getRemark();
LocalDateTime startTime = request.getFeedingTime() == null ? LocalDateTime.now() : request.getFeedingTime();
LocalDateTime endTime = request.getEndTime();
Integer duration = request.getDurationMinutes();
if (duration == null && (request.getLeftDurationMinutes() != null || request.getRightDurationMinutes() != null)) {
int sum = (request.getLeftDurationMinutes() == null ? 0 : request.getLeftDurationMinutes())
+ (request.getRightDurationMinutes() == null ? 0 : request.getRightDurationMinutes());
if (sum > 0) {
duration = sum;
}
}
if (endTime == null && duration != null && duration > 0) {
// 如果未传结束时间但传入了总时长,则以当前时间为结束时间,开始时间向前推导
endTime = startTime;
startTime = startTime.minusMinutes(duration);
}
CareRecord record = baseRecord(request.getBabyId(), "feeding", startTime, request.getOperatorName(), remark);
record.setFeedingMethod(request.getFeedingMethod()); record.setFeedingMethod(request.getFeedingMethod());
record.setAmountMl(request.getAmountMl()); record.setAmountMl(request.getAmountMl());
record.setEndTime(request.getEndTime()); record.setEndTime(endTime);
if (record.getStartTime() != null && record.getEndTime() != null) { record.setLeftDurationMinutes(request.getLeftDurationMinutes());
record.setRightDurationMinutes(request.getRightDurationMinutes());
if (duration != null) {
record.setDurationMinutes(duration);
} else if (record.getStartTime() != null && record.getEndTime() != null) {
record.recalculateDuration(); record.recalculateDuration();
} }
careRecordMapper.insert(record); careRecordMapper.insert(record);
@@ -62,6 +85,8 @@ public class CareRecordService {
} }
CareRecord record = baseRecord(request.getBabyId(), "feeding", request.getFeedingTime(), request.getOperatorName(), buildFeedingRemark(request)); CareRecord record = baseRecord(request.getBabyId(), "feeding", request.getFeedingTime(), request.getOperatorName(), buildFeedingRemark(request));
record.setFeedingMethod("breastfeed"); record.setFeedingMethod("breastfeed");
record.setLeftDurationMinutes(request.getLeftDurationMinutes());
record.setRightDurationMinutes(request.getRightDurationMinutes());
careRecordMapper.insert(record); careRecordMapper.insert(record);
return CareRecordConvert.toVO(record); return CareRecordConvert.toVO(record);
} }
@@ -76,10 +101,23 @@ public class CareRecordService {
throw new BusinessException("INVALID_FEEDING_TIME", "喂奶结束时间不能早于开始时间"); throw new BusinessException("INVALID_FEEDING_TIME", "喂奶结束时间不能早于开始时间");
} }
activeFeeding.setEndTime(end); activeFeeding.setEndTime(end);
if (request.getLeftDurationMinutes() != null) {
activeFeeding.setLeftDurationMinutes(request.getLeftDurationMinutes());
}
if (request.getRightDurationMinutes() != null) {
activeFeeding.setRightDurationMinutes(request.getRightDurationMinutes());
}
if (request.getRemark() != null) { if (request.getRemark() != null) {
activeFeeding.setRemark(buildFeedingRemark(request)); activeFeeding.setRemark(request.getRemark().trim().isEmpty() ? null : request.getRemark().trim());
} }
activeFeeding.recalculateDuration(); activeFeeding.recalculateDuration();
if (request.getLeftDurationMinutes() != null || request.getRightDurationMinutes() != null) {
int sumSplit = (activeFeeding.getLeftDurationMinutes() == null ? 0 : activeFeeding.getLeftDurationMinutes())
+ (activeFeeding.getRightDurationMinutes() == null ? 0 : activeFeeding.getRightDurationMinutes());
if (sumSplit > 0 && (activeFeeding.getDurationMinutes() == null || activeFeeding.getDurationMinutes() < sumSplit)) {
activeFeeding.setDurationMinutes(sumSplit);
}
}
careRecordMapper.updateById(activeFeeding); careRecordMapper.updateById(activeFeeding);
return CareRecordConvert.toVO(activeFeeding); return CareRecordConvert.toVO(activeFeeding);
} }
@@ -137,6 +175,8 @@ public class CareRecordService {
record.recalculateDuration(); record.recalculateDuration();
} }
record.setFeedingMethod(request.getFeedingMethod()); record.setFeedingMethod(request.getFeedingMethod());
record.setLeftDurationMinutes(request.getLeftDurationMinutes());
record.setRightDurationMinutes(request.getRightDurationMinutes());
record.setAmountMl(request.getAmountMl()); record.setAmountMl(request.getAmountMl());
record.setExcretionType(request.getExcretionType()); record.setExcretionType(request.getExcretionType());
record.setOperatorName(request.getOperatorName() == null || request.getOperatorName().trim().isEmpty() ? "宝妈" : request.getOperatorName().trim()); record.setOperatorName(request.getOperatorName() == null || request.getOperatorName().trim().isEmpty() ? "宝妈" : request.getOperatorName().trim());
@@ -173,6 +213,12 @@ public class CareRecordService {
if (request.getFeedingMethod() != null) { if (request.getFeedingMethod() != null) {
record.setFeedingMethod(request.getFeedingMethod()); record.setFeedingMethod(request.getFeedingMethod());
} }
if (request.getLeftDurationMinutes() != null) {
record.setLeftDurationMinutes(request.getLeftDurationMinutes());
}
if (request.getRightDurationMinutes() != null) {
record.setRightDurationMinutes(request.getRightDurationMinutes());
}
if (request.getAmountMl() != null) { if (request.getAmountMl() != null) {
record.setAmountMl(request.getAmountMl()); record.setAmountMl(request.getAmountMl());
} }
@@ -231,16 +277,11 @@ public class CareRecordService {
} }
private String buildFeedingRemark(CreateFeedingRO request) { private String buildFeedingRemark(CreateFeedingRO request) {
String side = request.getBreastSide();
String remark = request.getRemark(); String remark = request.getRemark();
if (side == null || side.trim().isEmpty()) { if (remark != null && !remark.trim().isEmpty()) {
return remark; return remark.trim();
} }
String sideText = "left".equals(side) ? "左侧" : "right".equals(side) ? "右侧" : side.trim(); return null;
if (remark == null || remark.trim().isEmpty()) {
return "亲喂侧: " + sideText;
}
return "亲喂侧: " + sideText + ";" + remark.trim();
} }
private CareRecordVO createExcretion(ExcretionRO request, String excretionType) { private CareRecordVO createExcretion(ExcretionRO request, String excretionType) {
@@ -23,6 +23,8 @@ public final class CareRecordConvert {
vo.setStartTime(entity.getStartTime()); vo.setStartTime(entity.getStartTime());
vo.setEndTime(entity.getEndTime()); vo.setEndTime(entity.getEndTime());
vo.setDurationMinutes(entity.getDurationMinutes()); vo.setDurationMinutes(entity.getDurationMinutes());
vo.setLeftDurationMinutes(entity.getLeftDurationMinutes());
vo.setRightDurationMinutes(entity.getRightDurationMinutes());
vo.setFeedingMethod(entity.getFeedingMethod()); vo.setFeedingMethod(entity.getFeedingMethod());
vo.setAmountMl(entity.getAmountMl()); vo.setAmountMl(entity.getAmountMl());
vo.setExcretionType(entity.getExcretionType()); vo.setExcretionType(entity.getExcretionType());
@@ -62,6 +64,8 @@ public final class CareRecordConvert {
dto.setStartTime(entity.getStartTime()); dto.setStartTime(entity.getStartTime());
dto.setEndTime(entity.getEndTime()); dto.setEndTime(entity.getEndTime());
dto.setDurationMinutes(entity.getDurationMinutes()); dto.setDurationMinutes(entity.getDurationMinutes());
dto.setLeftDurationMinutes(entity.getLeftDurationMinutes());
dto.setRightDurationMinutes(entity.getRightDurationMinutes());
dto.setFeedingMethod(entity.getFeedingMethod()); dto.setFeedingMethod(entity.getFeedingMethod());
dto.setAmountMl(entity.getAmountMl()); dto.setAmountMl(entity.getAmountMl());
dto.setExcretionType(entity.getExcretionType()); dto.setExcretionType(entity.getExcretionType());
@@ -6,23 +6,108 @@ import java.time.LocalDateTime;
@Data @Data
public class CareRecordDTO { public class CareRecordDTO {
/**
* 记录ID,雪花ID字符串
*/
private String recordId; private String recordId;
/**
* 家庭ID
*/
private String familyId; private String familyId;
/**
* 宝宝ID
*/
private String babyId; private String babyId;
/**
* 记录类型: feeding(喂奶), sleep(睡眠), excretion(排泄)
*/
private String recordType; private String recordType;
/**
* 开始时间 / 发生时间
*/
private LocalDateTime startTime; private LocalDateTime startTime;
/**
* 结束时间
*/
private LocalDateTime endTime; private LocalDateTime endTime;
/**
* 持续时长(分钟)
*/
private Integer durationMinutes; private Integer durationMinutes;
/**
* 亲喂左侧时长(分钟)
*/
private Integer leftDurationMinutes;
/**
* 亲喂右侧时长(分钟)
*/
private Integer rightDurationMinutes;
/**
* 喂奶方式: breastfeed(亲喂), bottle(瓶喂), formula(配方奶), mixed(混合喂养), other(其他)
*/
private String feedingMethod; private String feedingMethod;
/**
* 奶量(毫升 ml)
*/
private Integer amountMl; private Integer amountMl;
/**
* 排泄类型: pee(小便), poop(大便)
*/
private String excretionType; private String excretionType;
/**
* 记录人称谓(如: 宝妈、宝爸、月嫂)
*/
private String operatorName; private String operatorName;
/**
* 记录人用户ID
*/
private String operatorUserId; private String operatorUserId;
/**
* 备注
*/
private String remark; private String remark;
/**
* 来源: h5, miniapp, admin, system
*/
private String source; private String source;
/**
* 删除状态: 0未删除, 1已删除
*/
private Integer deleted; private Integer deleted;
/**
* 创建人
*/
private String createdBy; private String createdBy;
/**
* 创建时间
*/
private LocalDateTime createdTime; private LocalDateTime createdTime;
/**
* 修改人
*/
private String updatedBy; private String updatedBy;
/**
* 修改时间
*/
private LocalDateTime updatedTime; private LocalDateTime updatedTime;
} }
@@ -7,17 +7,61 @@ import java.time.LocalDateTime;
@Data @Data
public class CreateFeedingRO { public class CreateFeedingRO {
/**
* 宝宝ID
*/
@NotBlank(message = "宝宝ID不能为空") @NotBlank(message = "宝宝ID不能为空")
private String babyId; private String babyId;
/**
* 喂奶方式: breastfeed(亲喂), bottle(瓶喂), formula(配方奶), mixed(混合喂养), other(其他)
*/
@NotBlank(message = "喂养方式不能为空") @NotBlank(message = "喂养方式不能为空")
private String feedingMethod; private String feedingMethod;
/**
* 喂奶开始时间(不传默认当前时间)
*/
private LocalDateTime feedingTime; private LocalDateTime feedingTime;
/**
* 喂奶结束时间(可选)
*/
private LocalDateTime endTime; private LocalDateTime endTime;
/**
* 喂奶总时长(分钟)
*/
private Integer durationMinutes;
/**
* 喂奶量(毫升 ml,瓶喂/配方奶时使用)
*/
private Integer amountMl; private Integer amountMl;
/**
* 亲喂侧别: left(左侧), right(右侧), both(双侧)
*/
private String breastSide; private String breastSide;
/**
* 亲喂左侧时长(分钟)
*/
private Integer leftDurationMinutes;
/**
* 亲喂右侧时长(分钟)
*/
private Integer rightDurationMinutes;
/**
* 记录人称谓(如: 宝妈、宝爸、月嫂)
*/
private String operatorName; private String operatorName;
/**
* 备注
*/
private String remark; private String remark;
public String getNote() { public String getNote() {
@@ -8,21 +8,67 @@ import java.time.LocalDateTime;
@Data @Data
public class CreateManualRecordRO { public class CreateManualRecordRO {
/**
* 宝宝ID
*/
@NotBlank(message = "宝宝ID不能为空") @NotBlank(message = "宝宝ID不能为空")
private String babyId; private String babyId;
/**
* 记录类型: feeding(喂奶), sleep(睡眠), excretion(排泄)
*/
@NotBlank(message = "记录类型不能为空") @NotBlank(message = "记录类型不能为空")
private String recordType; private String recordType;
/**
* 开始时间 / 发生时间
*/
@NotNull(message = "开始时间不能为空") @NotNull(message = "开始时间不能为空")
private LocalDateTime startTime; private LocalDateTime startTime;
/**
* 结束时间(可选)
*/
private LocalDateTime endTime; private LocalDateTime endTime;
/**
* 持续时长(分钟)
*/
private Integer durationMinutes; private Integer durationMinutes;
/**
* 亲喂左侧时长(分钟)
*/
private Integer leftDurationMinutes;
/**
* 亲喂右侧时长(分钟)
*/
private Integer rightDurationMinutes;
/**
* 喂奶方式: breastfeed(亲喂), bottle(瓶喂), formula(配方奶), mixed(混合喂养), other(其他)
*/
private String feedingMethod; private String feedingMethod;
/**
* 奶量(毫升 ml,瓶喂/配方奶时使用)
*/
private Integer amountMl; private Integer amountMl;
/**
* 排泄类型: pee(小便), poop(大便)
*/
private String excretionType; private String excretionType;
/**
* 记录人称谓(如: 宝妈、宝爸、月嫂)
*/
private String operatorName; private String operatorName;
/**
* 备注
*/
private String remark; private String remark;
public String getNote() { public String getNote() {
@@ -5,6 +5,9 @@ import lombok.Data;
@Data @Data
public class DeleteCareRecordRO { public class DeleteCareRecordRO {
/**
* 待删除的照护记录ID
*/
@NotBlank(message = "记录ID不能为空") @NotBlank(message = "记录ID不能为空")
private String recordId; private String recordId;
} }
@@ -7,11 +7,25 @@ import java.time.LocalDateTime;
@Data @Data
public class ExcretionRO { public class ExcretionRO {
/**
* 宝宝ID
*/
@NotBlank(message = "宝宝ID不能为空") @NotBlank(message = "宝宝ID不能为空")
private String babyId; private String babyId;
/**
* 发生时间(不传默认当前时间)
*/
private LocalDateTime time; private LocalDateTime time;
/**
* 记录人称谓(如: 宝妈、宝爸、月嫂)
*/
private String operatorName; private String operatorName;
/**
* 备注
*/
private String remark; private String remark;
public String getNote() { public String getNote() {
@@ -7,11 +7,25 @@ import java.time.LocalDateTime;
@Data @Data
public class SleepRO { public class SleepRO {
/**
* 宝宝ID
*/
@NotBlank(message = "宝宝ID不能为空") @NotBlank(message = "宝宝ID不能为空")
private String babyId; private String babyId;
/**
* 睡眠开始或结束时间(不传默认当前时间)
*/
private LocalDateTime time; private LocalDateTime time;
/**
* 记录人称谓(如: 宝妈、宝爸、月嫂)
*/
private String operatorName; private String operatorName;
/**
* 备注
*/
private String remark; private String remark;
public String getNote() { public String getNote() {
@@ -7,17 +7,65 @@ import java.time.LocalDateTime;
@Data @Data
public class UpdateCareRecordRO { public class UpdateCareRecordRO {
/**
* 记录ID
*/
@NotBlank(message = "记录ID不能为空") @NotBlank(message = "记录ID不能为空")
private String recordId; private String recordId;
/**
* 记录类型: feeding(喂奶), sleep(睡眠), excretion(排泄)
*/
private String recordType; private String recordType;
/**
* 开始时间 / 发生时间
*/
private LocalDateTime startTime; private LocalDateTime startTime;
/**
* 结束时间
*/
private LocalDateTime endTime; private LocalDateTime endTime;
/**
* 持续时长(分钟)
*/
private Integer durationMinutes; private Integer durationMinutes;
/**
* 亲喂左侧时长(分钟)
*/
private Integer leftDurationMinutes;
/**
* 亲喂右侧时长(分钟)
*/
private Integer rightDurationMinutes;
/**
* 喂奶方式: breastfeed(亲喂), bottle(瓶喂), formula(配方奶), mixed(混合喂养), other(其他)
*/
private String feedingMethod; private String feedingMethod;
/**
* 奶量(毫升 ml)
*/
private Integer amountMl; private Integer amountMl;
/**
* 排泄类型: pee(小便), poop(大便)
*/
private String excretionType; private String excretionType;
/**
* 记录人称谓(如: 宝妈、宝爸、月嫂)
*/
private String operatorName; private String operatorName;
/**
* 备注
*/
private String remark; private String remark;
public String getNote() { public String getNote() {
@@ -6,25 +6,114 @@ import java.time.LocalDateTime;
@Data @Data
public class CareRecordVO { public class CareRecordVO {
/**
* 记录ID,雪花ID字符串
*/
private String recordId; private String recordId;
/**
* 家庭ID
*/
private String familyId; private String familyId;
/**
* 宝宝ID
*/
private String babyId; private String babyId;
/**
* 记录类型: feeding(喂奶), sleep(睡眠), excretion(排泄)
*/
private String recordType; private String recordType;
/**
* 开始时间 / 发生时间
*/
private LocalDateTime startTime; private LocalDateTime startTime;
/**
* 结束时间
*/
private LocalDateTime endTime; private LocalDateTime endTime;
/**
* 持续时长(分钟)
*/
private Integer durationMinutes; private Integer durationMinutes;
/**
* 亲喂左侧时长(分钟)
*/
private Integer leftDurationMinutes;
/**
* 亲喂右侧时长(分钟)
*/
private Integer rightDurationMinutes;
/**
* 喂奶方式: breastfeed(亲喂), bottle(瓶喂), formula(配方奶), mixed(混合喂养), other(其他)
*/
private String feedingMethod; private String feedingMethod;
/**
* 奶量(毫升 ml)
*/
private Integer amountMl; private Integer amountMl;
/**
* 排泄类型: pee(小便), poop(大便)
*/
private String excretionType; private String excretionType;
/**
* 记录人称谓(如: 宝妈、宝爸、月嫂)
*/
private String operatorName; private String operatorName;
/**
* 记录人用户ID
*/
private String operatorUserId; private String operatorUserId;
/**
* 备注
*/
private String remark; private String remark;
/**
* 兼容旧版备注字段
*/
private String note; private String note;
/**
* 来源: h5, miniapp, admin, system
*/
private String source; private String source;
/**
* 删除状态: 0未删除, 1已删除
*/
private Integer deleted; private Integer deleted;
/**
* 创建人
*/
private String createdBy; private String createdBy;
/**
* 创建时间
*/
private LocalDateTime createdTime; private LocalDateTime createdTime;
/**
* 修改人
*/
private String updatedBy; private String updatedBy;
/**
* 修改时间
*/
private LocalDateTime updatedTime; private LocalDateTime updatedTime;
public String getNote() { public String getNote() {
@@ -7,6 +7,7 @@ import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.ZoneId;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -14,10 +15,11 @@ import java.util.Map;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class SummaryService { public class SummaryService {
private static final ZoneId SHANGHAI_ZONE = ZoneId.of("Asia/Shanghai");
private final CareRecordService careRecordService; private final CareRecordService careRecordService;
public DailySummaryVO daily(String babyId, LocalDate date) { public DailySummaryVO daily(String babyId, LocalDate date) {
LocalDate targetDate = date == null ? LocalDate.now() : date; LocalDate targetDate = date == null ? LocalDate.now(SHANGHAI_ZONE) : date;
List<CareRecordVO> timeline = careRecordService.list(babyId, targetDate); List<CareRecordVO> timeline = careRecordService.list(babyId, targetDate);
DailySummaryVO summary = new DailySummaryVO(); DailySummaryVO summary = new DailySummaryVO();
summary.setBabyId(babyId); summary.setBabyId(babyId);
@@ -8,15 +8,58 @@ import java.util.Map;
@Data @Data
public class DailySummaryDTO { public class DailySummaryDTO {
/**
* 宝宝ID
*/
private String babyId; private String babyId;
/**
* 汇总日期 (yyyy-MM-dd)
*/
private String date; private String date;
/**
* 今日喂奶总次数
*/
private int feedingCount; private int feedingCount;
/**
* 今日各喂奶方式次数统计(key: feedingMethod, value: 次数)
*/
private Map<String, Integer> feedingMethodCounts; private Map<String, Integer> feedingMethodCounts;
/**
* 今日睡眠总时长(分钟)
*/
private int sleepTotalMinutes; private int sleepTotalMinutes;
/**
* 今日小便次数
*/
private int peeCount; private int peeCount;
/**
* 今日大便次数
*/
private int poopCount; private int poopCount;
/**
* 最近一次喂奶记录
*/
private CareRecordDTO lastFeeding; private CareRecordDTO lastFeeding;
/**
* 当前进行中的亲喂记录(若无则为 null)
*/
private CareRecordDTO activeFeeding; private CareRecordDTO activeFeeding;
/**
* 当前进行中的睡眠记录(若无则为 null)
*/
private CareRecordDTO activeSleep; private CareRecordDTO activeSleep;
/**
* 今日照护事件时间轴列表
*/
private List<CareRecordDTO> timeline; private List<CareRecordDTO> timeline;
} }
@@ -7,8 +7,14 @@ import java.time.LocalDate;
@Data @Data
public class SummaryQueryRO { public class SummaryQueryRO {
/**
* 宝宝ID(选填,不填则默认查询当前宝宝)
*/
private String babyId; private String babyId;
/**
* 汇总日期(选填,格式 yyyy-MM-dd,不传默认当日)
*/
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private LocalDate date; private LocalDate date;
} }
@@ -8,15 +8,58 @@ import java.util.Map;
@Data @Data
public class DailySummaryVO { public class DailySummaryVO {
/**
* 宝宝ID
*/
private String babyId; private String babyId;
/**
* 汇总日期 (yyyy-MM-dd)
*/
private String date; private String date;
/**
* 今日喂奶总次数
*/
private int feedingCount; private int feedingCount;
/**
* 今日各喂奶方式次数统计(key: feedingMethod, value: 次数)
*/
private Map<String, Integer> feedingMethodCounts; private Map<String, Integer> feedingMethodCounts;
/**
* 今日睡眠总时长(分钟)
*/
private int sleepTotalMinutes; private int sleepTotalMinutes;
/**
* 今日小便次数
*/
private int peeCount; private int peeCount;
/**
* 今日大便次数
*/
private int poopCount; private int poopCount;
/**
* 最近一次喂奶记录
*/
private CareRecordVO lastFeeding; private CareRecordVO lastFeeding;
/**
* 当前进行中的亲喂记录(若无则为 null)
*/
private CareRecordVO activeFeeding; private CareRecordVO activeFeeding;
/**
* 当前进行中的睡眠记录(若无则为 null)
*/
private CareRecordVO activeSleep; private CareRecordVO activeSleep;
/**
* 今日照护事件时间轴列表
*/
private List<CareRecordVO> timeline; private List<CareRecordVO> timeline;
} }
@@ -0,0 +1,55 @@
package com.babytracker.module.system;
import com.babytracker.common.response.ApiResponse;
import com.babytracker.module.system.vo.ServerTimeVO;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
/**
* 系统通用接口控制器
*/
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/system")
public class SystemController {
private static final ZoneId SHANGHAI_ZONE = ZoneId.of("Asia/Shanghai");
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");
/**
* 获取服务器当前时间信息(支持 GET 请求)
*/
@GetMapping("/time")
public ApiResponse<ServerTimeVO> getServerTime() {
return ApiResponse.ok(buildServerTimeVO());
}
/**
* 获取服务器当前时间信息(支持 POST 请求)
*/
@PostMapping("/time")
public ApiResponse<ServerTimeVO> getServerTimeByPost() {
return ApiResponse.ok(buildServerTimeVO());
}
private ServerTimeVO buildServerTimeVO() {
ZonedDateTime now = ZonedDateTime.now(SHANGHAI_ZONE);
return ServerTimeVO.builder()
.serverTime(now.toLocalDateTime())
.currentDate(now.format(DATE_FORMATTER))
.currentTime(now.format(TIME_FORMATTER))
.timeZone(SHANGHAI_ZONE.getId())
.timestamp(now.toInstant().toEpochMilli())
.build();
}
}
@@ -0,0 +1,45 @@
package com.babytracker.module.system.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
/**
* 服务器当前时间信息响应体
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ServerTimeVO {
/**
* 服务器当前日期时间 (格式: yyyy-MM-dd HH:mm:ss)
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime serverTime;
/**
* 服务器当前日期 (格式: yyyy-MM-dd)
*/
private String currentDate;
/**
* 服务器当前时间 (格式: HH:mm:ss)
*/
private String currentTime;
/**
* 服务器时区 (如: Asia/Shanghai)
*/
private String timeZone;
/**
* 服务器当前时间戳毫秒数
*/
private Long timestamp;
}
@@ -16,7 +16,7 @@ spring:
flyway: flyway:
enabled: true enabled: true
baseline-on-migrate: true baseline-on-migrate: true
baseline-version: 0 baseline-version: 3
locations: classpath:db/migration locations: classpath:db/migration
jackson: jackson:
time-zone: Asia/Shanghai time-zone: Asia/Shanghai
@@ -64,4 +64,26 @@ class BabyTrackerApplicationTests {
// 测试逻辑删除 // 测试逻辑删除
careRecordService.delete(created.getRecordId()); careRecordService.delete(created.getRecordId());
} }
@Autowired
private com.babytracker.module.system.SystemController systemController;
@Test
void testSystemTimeEndpoint() {
var getResp = systemController.getServerTime();
assertNotNull(getResp);
assertTrue(getResp.isSuccess());
assertNotNull(getResp.getData());
assertNotNull(getResp.getData().getServerTime());
assertNotNull(getResp.getData().getCurrentDate());
assertNotNull(getResp.getData().getCurrentTime());
assertNotNull(getResp.getData().getTimeZone());
assertNotNull(getResp.getData().getTimestamp());
var postResp = systemController.getServerTimeByPost();
assertNotNull(postResp);
assertTrue(postResp.isSuccess());
assertNotNull(postResp.getData());
assertEquals(getResp.getData().getCurrentDate(), postResp.getData().getCurrentDate());
}
} }
+4 -2
View File
@@ -8,7 +8,8 @@
sql/ sql/
├── migration/ # Flyway 增量版本迁移脚本目录(由 Maven 打包自动装配至后端运行时) ├── migration/ # Flyway 增量版本迁移脚本目录(由 Maven 打包自动装配至后端运行时)
│ ├── V1__init_mvp_schema.sql # V1: MVP 基础表结构与最小种子数据 │ ├── V1__init_mvp_schema.sql # V1: MVP 基础表结构与最小种子数据
│ └── V2__audit_fields_and_logic_delete.sql # V2: 通用审计字段(remark,deleted,created_by,created_time,updated_by,updated_time)与字段清理 │ ├── V2__audit_fields_and_logic_delete.sql # V2: 通用审计字段与字段清理
│ └── V3__add_breastfeeding_split_durations.sql # V3: 亲喂左侧/右侧独立耗时结构化字段
├── schema-full.sql # 当前最新完整建表与初始化数据脚本(全新环境初始化直接执行) ├── schema-full.sql # 当前最新完整建表与初始化数据脚本(全新环境初始化直接执行)
├── schema-evolution.sql # 数据库结构版本演进与变更记录 ├── schema-evolution.sql # 数据库结构版本演进与变更记录
├── database.sql # 历史初始原型脚本(仅供归档参考) ├── database.sql # 历史初始原型脚本(仅供归档参考)
@@ -22,7 +23,8 @@ sql/
- 后端 Maven 打包已通过 `<resources>` 自动将本目录映射并打包进 `target/classes/db/migration`,Spring Boot 启动时由 Flyway 自动执行增量迁移。 - 后端 Maven 打包已通过 `<resources>` 自动将本目录映射并打包进 `target/classes/db/migration`,Spring Boot 启动时由 Flyway 自动执行增量迁移。
2. **最新全量建表脚本 (`sql/schema-full.sql`)**: 2. **最新全量建表脚本 (`sql/schema-full.sql`)**:
- 每次数据库表结构或核心字段变更后,需同步更新 `schema-full.sql`; - 每次数据库表结构或核心字段变更后,需同步更新 `schema-full.sql`;
- 新部署环境、本地或容器一键初始化数据库时,直接执行 `schema-full.sql` 即可获得最新的标准数据库。 - 新部署环境、本地或容器一键初始化数据库时,直接执行 `schema-full.sql` 即可获得最新的标准数据库;
- `schema-full.sql` 末尾已内置初始化 `flyway_schema_history` 基准记录,同时 `application.yml` 配置了 `baseline-version: 3`,确保在直接执行全量脚本后,Flyway 不会误判为历史空库而重复回放早期的增量迁移。
3. **字段规范**: 3. **字段规范**:
- 所有表必须包含 6 大标准通用字段: - 所有表必须包含 6 大标准通用字段:
- `remark`: 备注 - `remark`: 备注
@@ -0,0 +1,5 @@
-- V3: 照护记录表增加亲喂左右侧独立时长字段
ALTER TABLE `care_record`
ADD COLUMN `left_duration_minutes` INT NULL COMMENT '亲喂左侧时长(分钟)' AFTER `duration_minutes`,
ADD COLUMN `right_duration_minutes` INT NULL COMMENT '亲喂右侧时长(分钟)' AFTER `left_duration_minutes`;
+23
View File
@@ -101,6 +101,8 @@ CREATE TABLE `care_record` (
`start_time` DATETIME NOT NULL COMMENT '开始/发生时间', `start_time` DATETIME NOT NULL COMMENT '开始/发生时间',
`end_time` DATETIME NULL COMMENT '结束时间', `end_time` DATETIME NULL COMMENT '结束时间',
`duration_minutes` INT NULL COMMENT '持续分钟数', `duration_minutes` INT NULL COMMENT '持续分钟数',
`left_duration_minutes` INT NULL COMMENT '亲喂左侧时长(分钟)',
`right_duration_minutes` INT NULL COMMENT '亲喂右侧时长(分钟)',
`feeding_method` VARCHAR(30) NULL COMMENT '喂奶方式', `feeding_method` VARCHAR(30) NULL COMMENT '喂奶方式',
`amount_ml` INT NULL COMMENT '奶量 ml,可选', `amount_ml` INT NULL COMMENT '奶量 ml,可选',
`excretion_type` VARCHAR(20) NULL COMMENT '排泄类型: pee, poop', `excretion_type` VARCHAR(20) NULL COMMENT '排泄类型: pee, poop',
@@ -133,4 +135,25 @@ VALUES
INSERT IGNORE INTO `baby_profile` (`id`, `family_id`, `name`, `gender`, `birth_date`, `delivery_type`, `is_default`, `status`, `created_by`, `updated_by`) INSERT IGNORE INTO `baby_profile` (`id`, `family_id`, `name`, `gender`, `birth_date`, `delivery_type`, `is_default`, `status`, `created_by`, `updated_by`)
VALUES ('00000000000000361915955447599104', '00000000000000361915955439210496', '宝宝', 'boy', DATE_SUB(CURDATE(), INTERVAL 3 DAY), 'natural', 1, 'active', 'admin', 'admin'); VALUES ('00000000000000361915955447599104', '00000000000000361915955439210496', '宝宝', 'boy', DATE_SUB(CURDATE(), INTERVAL 3 DAY), 'natural', 1, 'active', 'admin', 'admin');
-- 初始化 Flyway 版本基准(确保执行本全量脚本后,Flyway 能识别当前库已达最新版本,避免重复执行早期增量迁移)
CREATE TABLE IF NOT EXISTS `flyway_schema_history` (
`installed_rank` INT NOT NULL,
`version` VARCHAR(50) NULL,
`description` VARCHAR(200) NOT NULL,
`type` VARCHAR(20) NOT NULL,
`script` VARCHAR(1000) NOT NULL,
`checksum` INT NULL,
`installed_by` VARCHAR(100) NOT NULL,
`installed_on` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`execution_time` INT NOT NULL,
`success` TINYINT(1) NOT NULL,
PRIMARY KEY (`installed_rank`),
KEY `flyway_schema_history_s_idx` (`success`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Flyway版本控制表';
INSERT IGNORE INTO `flyway_schema_history`
(`installed_rank`, `version`, `description`, `type`, `script`, `checksum`, `installed_by`, `installed_on`, `execution_time`, `success`)
VALUES
(1, '3', '<< Flyway Baseline >>', 'BASELINE', '<< Flyway Baseline >>', NULL, 'admin', CURRENT_TIMESTAMP, 0, 1);
SET FOREIGN_KEY_CHECKS = 1; SET FOREIGN_KEY_CHECKS = 1;