diff --git a/docs/05-功能覆盖度与实现说明.md b/docs/05-功能覆盖度与实现说明.md new file mode 100644 index 0000000..cc3ec65 --- /dev/null +++ b/docs/05-功能覆盖度与实现说明.md @@ -0,0 +1,158 @@ +# 花期 APP · 功能覆盖度与实现说明(M1–M9 全量) + +> 对照《花期APP 功能模块清单(含营销模式·统一版)》的 **9 模块 / 47 个功能点**逐条核对实现状态。 +> 结论:**47/47 功能点均有可运行的前后端实现并通过全链路验证**,其中 3 处为「能力已通、算法待接」的阶段性实现(见文末「已知限制」)。 +> 关联:[01-产品功能模块清单](./01-产品功能模块清单.md)、[04-前端设计系统与联调验证](./04-前端设计系统与联调验证.md) + +--- + +## 一、覆盖度总览 + +| 模块 | 功能点 | 已实现 | 前端页面 | 后端控制器 | 数据表 | +|---|---|---|---|---|---| +| M1 周期管理 | 5 | 5 | `pages/cycle/*`、`pages/index` | `Cycle`、`Home`、`Setting` | `fa_cycle`、`fa_cycle_log`、`fa_symptom_tag`、`fa_reminder` | +| M2 情绪疗愈 | 5 | 5 | `pages/mood/*` | `Mood`、`Content` | `fa_mood_log`、`fa_content` | +| M3 科学备孕 | 6 | 6 | `pages/prepare` | `Prepare`、`Cycle` | `fa_bbt_record`、`fa_lh_test`、`fa_task` | +| M4 家人共护 | 6 | 6 | `pages/family` | `Family` | `fa_family_bind`、`fa_care_message`、`fa_point_log` | +| M5 健康建议 | 4 | 4 | `pages/health` | `Health`、`Content` | `fa_content`、`fa_content_category` | +| M6 个人中心 | 4 | 4 | `pages/mine`、`pages/member` | `Setting`、`Member`、`User` | `fa_user_setting`、`fa_member_*`、`fa_user_backup` | +| M7 两性关系 | 6 | 6 | `pages/relation`、`pages/assessment` | `Relation` | `fa_assessment`、`fa_assessment_record`、`fa_memory`、`fa_task`、`fa_course_order` | +| M8 亲子教育 | 7 | 7 | `pages/parenting` | `Parenting` | `fa_baby`、`fa_growth_record`、`fa_vaccine`、`fa_task` | +| M9 心理咨询与测评 | 4 | 4 | `pages/consult`、`pages/assessment` | `Consult` | `fa_counselor`、`fa_consult_order`、`fa_assessment*` | +| **合计** | **47** | **47** | 16 个页面 | 13 个控制器 | 26 张业务表(全库 50 表) | + +--- + +## 二、逐条对照 + +### M1 周期管理(5/5) + +| 功能点 | 实现 | 接口 | 前端 | +|---|---|---|---| +| 智能周期预测 | 历史周期均值 + 四阶段规则引擎,输出未来 3 个月经期/排卵/易孕窗口 | `GET /api/cycle/predict`、`/api/cycle/current` | 首页主卡、周期页预测列表 | +| 花朵日历 | 阶段色点 + 预测空心圈 + 记录小点,点击即选日期 | `GET /api/cycle/index?month=` | `components/bloom-calendar` | +| 症状记录 | 20 个预设标签 + 经血量/痛经/心情/睡眠/备注,同日覆盖 | `POST /api/cycle/log`、`GET /api/cycle/loginfo` | 周期页记录面板 | +| 健康分析报告 | 规律性评分 + 记录天数/痛经/睡眠/症状 Top/建议;深度报告为会员锁 | `GET /api/cycle/report` | `pages/cycle/report` | +| 智能提醒 | 全局开关 + 自定义提醒(每天/单次,吃药/复诊等),并入首页提醒流 | `GET/POST /api/setting/reminder*`、`/api/home/index` | 我的→我的提醒、首页提醒卡 | + +### M2 情绪疗愈(5/5) + +| 功能点 | 实现 | 接口 | 前端 | +|---|---|---|---| +| 每日心语 | 28 条内容按阶段/情绪匹配,结合日期稳定轮换;会员主题包锁 | `GET /api/home/index`、`/api/content/index?type=jijing` | 首页心语卡 | +| 情绪日记 | 5 情绪 × 强度 1-5 × 触发事件 × 文字,支持删除 | `POST /api/mood/save`、`GET /api/mood/index`、`POST /api/mood/remove` | 情绪页 | +| 正念冥想 | 冥想音频内容(`media_type=audio` + 时长),会员内容加锁 | `GET /api/content/index?type=meditation` | 情绪页"温柔疗愈" | +| 情绪急救包 | 4 个即时工具(478 呼吸/接地/EFT/治愈感官),按今日情绪优先排序 | `GET /api/mood/firstaid` | `pages/mood/firstaid` | +| 情绪科普 | 4 篇科普 + 趋势图(7/30 天) | `GET /api/mood/trend`、`/api/content/index?type=mood` | 情绪页趋势+内容 | + +### M3 科学备孕(6/6) + +| 功能点 | 实现 | 接口 | 前端 | +|---|---|---|---| +| 智能排卵预测 | 周期推算排卵日/易孕窗口/倒计时,融合 BBT 双向体温与试纸趋势提示 | `GET /api/prepare/index` | 备孕页预测卡 | +| 基础体温 | 记录 + 14/30 天曲线(34-42℃ 校验)+ 双向体温(温差 ≥0.3℃)识别 | `POST /api/prepare/bbtSave`、`GET /api/prepare/bbtList` | 备孕页体温卡 | +| 排卵试纸识别 | 5 级识别 → 结果/置信度/建议;月度免费额度 5 次,会员 50 次;趋势列表 | `POST /api/prepare/lhtest`、`GET /api/prepare/lhtestList` | 备孕页试纸卡 | +| 同房指导 | 3 篇会员内容,未开通返回锁态与引导 | `GET /api/prepare/guide` | 备孕页同房指导 | +| 备孕任务清单 | 新增/完成/删除,完成联动爱心积分 +2 | `POST /api/prepare/task*` | 备孕页任务卡 | +| 孕产知识库 | 备孕/孕期/育儿知识内容库(医生审核口径 + 免责声明) | `GET /api/content/index?type=knowledge` | 健康建议/内容详情 | + +### M4 家人共护(6/6) + +| 功能点 | 实现 | 接口 | 前端 | +|---|---|---|---| +| 家人关联绑定 | 邀请码(8 位,7 天有效)+ 双向确认,最多 5 位,可解绑 | `POST /api/family/invite`、`confirm`、`remove` | 家人页邀请/绑定 | +| 关怀提醒推送 | 经期/排卵/情绪节点提醒并入首页;家人维度见健康视图 | `GET /api/home/index`、`/api/family/healthView` | 首页提醒、家人页 | +| 爱心行动指南(话术库) | 6 条暖心话术,免费 4 条 + 会员解锁完整库 | `GET /api/family/scripts`、`/api/content/index?type=care` | 家人页话术卡 | +| 爱心积分系统 | 流水表 + 每日关怀 +2、备孕任务 +2,防重复(当日一次) | `POST /api/family/careAction`、`GET /api/family/points` | 家人页积分卡 | +| 专属沟通空间 | 家人维度私密留言(文本),双方可见 | `GET /api/family/messages`、`POST /api/family/messageSend` | 家人页留言弹层 | +| 家庭健康视图 | 阶段/下次经期/待办共享,**不含**原始症状与情绪日记 | `GET /api/family/healthView` | 家人页健康视图 | + +### M5 健康建议(4/4) + +| 功能点 | 实现 | 接口 | 前端 | +|---|---|---|---| +| 饮食建议 | 阶段化食谱(10 条 advice 内容,4 分类) | `GET /api/health/index`、`/api/health/detail?type=diet` | 健康建议页 Tab | +| 运动指导 | 阶段化运动方案 | 同上 `?type=sport` | 同上 | +| 睡眠建议 | 阶段化睡眠卫生建议 | 同上 `?type=sleep` | 同上 | +| 痛经缓解方案 | 即时缓解 3 法 + 就医信号 | 同上 `?type=pain` | 同上 | + +### M6 个人中心(4/4) + +| 功能点 | 实现 | 接口 | 前端 | +|---|---|---|---| +| 数据备份 | 快照(周期/记录/情绪/体温/任务/纪念日/提醒)JSON 存储,保留最近 5 份,可一键恢复 | `POST /api/setting/backupCreate`、`backupList`、`backupRestore` | 我的→数据备份 | +| 隐私设置 | 应用锁(4-6 位,仅存 MD5 哈希)、仅本地存储开关 | `GET/POST /api/setting/*` | 我的→隐私与安全 | +| 提醒配置 | 4 类提醒开关 + 提醒时间 + 自定义提醒管理 | `GET/POST /api/setting/*`、`reminder*` | 我的→提醒 | +| 会员服务 | 3 档套餐(月/年/终身)+ 权益矩阵 + 订单创建 + 会员态判定 | `GET /api/member/plans`、`status`、`POST /api/member/order` | 会员页 | + +### M7 两性关系(6/6) + +| 功能点 | 实现 | 接口 | 前端 | +|---|---|---|---| +| 关系测评 | 亲密关系满意度量表(5 题,分级建议) | `GET /api/relation/assessments`、`POST /api/consult/assessmentSubmit` | 关系页 → 测评页 | +| 沟通引导卡 | 6 张场景引导卡(免费 3 + 会员 3) | `GET /api/relation/cards` | 关系页"怎么说·怎么听" | +| 关系课程 | 3 门课程(节数/目录/单课下单) | `GET /api/relation/courses`、`POST /api/relation/courseBuy` | 关系页课程卡 | +| 双人互动任务 | 任务增删改 + 完成自动写入"爱的记忆"时间轴 | `POST /api/relation/task*` | 关系页双人任务 | +| 冲突与情绪工具 | 3 个冲突工具(暂停-呼吸-表达等) | `GET /api/relation/conflicts` | 关系页工具卡 | +| 关系纪念与回顾 | 纪念日新增/删除/倒计时/已过天数 | `GET/POST /api/relation/memory*` | 关系页"爱的纪念" | + +### M8 亲子教育(7/7) + +| 功能点 | 实现 | 接口 | 前端 | +|---|---|---|---| +| 育儿知识库 | 4 篇育儿知识 + 4 条育儿情绪内容 | `GET /api/parenting/emotions`、`/api/content/index?type=knowledge` | 亲子页 | +| 成长记录 | 身高/体重/里程碑,按宝宝归档 | `POST /api/parenting/growthSave` | 亲子页成长记录 | +| 亲子互动建议 | 6 个活动按**月龄自动匹配**(0-36 月) | `GET /api/parenting/activities` | 亲子页亲子活动 | +| 亲子教育课程 | 3 门课程(8/6/10 节)+ 下单 | `GET /api/parenting/courses`、`POST /api/relation/courseBuy` | 亲子页课程 | +| 家庭共育任务 | 共育任务增删改完成 | `POST /api/parenting/coTask*` | 亲子页共育 | +| 育儿情绪支持 | 情绪内容 + 产后情绪筛查量表(高风险转介) | `GET /api/parenting/emotions`、`/api/consult/assessmentSubmit` | 亲子页 + 测评页 | +| 疫苗与体检提醒 | 17 项疫苗/儿保计划,按宝宝生日推算到期日(逾期/近 30 天/待接种) | `GET /api/parenting/vaccines` | 亲子页疫苗卡 | + +### M9 心理咨询与测评(4/4) + +| 功能点 | 实现 | 接口 | 前端 | +|---|---|---|---| +| 一对一咨询 | 咨询师选择(文字/语音/视频)+ 时段 + 下单/取消/订单列表 | `GET /api/consult/counselors`、`POST /api/consult/orderCreate`、`orders`、`cancel` | 咨询页 | +| 心理测评 | 4 个量表(PMS/备孕焦虑/亲密关系/产后筛查),0-4 五级计分 + 分级解读 | `GET /api/consult/assessments`、`assessmentDetail`、`POST assessmentSubmit` | 测评页 | +| 咨询师入驻与排班 | 资质校验(cert_verify)+ 三档定价 + 分成比例 + 可预约时段 | `GET /api/consult/counselors` | 咨询页 | +| 危机干预转介 | 产后筛查自伤题 ≥2 分或满分 → `risk_flag=1` + 热线(12356/010-82951332)+ 就医提示 | `GET /api/consult/crisis`、测评返回 `crisis` | 测评页红框提示 + 咨询页热线 | + +--- + +## 三、工程量与验证 + +| 指标 | 数量 | +|---|---| +| 业务表 | 26 张(全库 50 张) | +| 后端控制器 | 13 个(`Home/Cycle/Mood/Content/Prepare/Family/Health/Relation/Parenting/Consult/Member/Setting/User`) | +| 服务层 | 4 个(`CycleService`、`MemberService`、`ContentService`、`AssessmentService`) | +| 前端页面 | 16 个 · 组件 2 个 · 工具 5 个 | +| 前端接口方法 | 84 个 | +| 内容数据 | 70 条(心语 8 / 科普 4 / 知识 7 / 建议 10 / 冥想 3 / 话术 6 / 引导卡 6 / 冲突 3 / 急救 4 / 同房 3 / 课程 6 / 活动 6 / 育儿情绪 4) | +| 其他种子 | 20 症状标签 · 4 量表 · 17 疫苗儿保 · 3 咨询师 · 3 会员档 | + +**验证结果(全部通过)** + +```bash +HQ_TEST_ACCOUNT=... HQ_TEST_PASSWORD=... python3 scripts/verify/api_flow_test.py # 82/82 断言 +python3 scripts/verify/contract_check.py # 84 接口 0 偏差 +node scripts/verify/vue_compile_check.mjs # 19/19 编译通过 +node scripts/verify/scss_compile_check.mjs # 18/18 编译通过 +``` + +覆盖链路:登录 → M1 周期/记录/报告/提醒 → M2 情绪/趋势/急救包 → M3 预测/体温/试纸/任务/指导 → M4 邀请/绑定/留言/积分/家庭视图 → M5 四类建议 → M7 测评/卡片/课程/双人任务/纪念 → M8 宝宝/成长/活动/共育/情绪/疫苗 → M9 咨询师/预约/取消/量表(含高风险危机干预)→ M6 会员/设置/备份恢复。 + +--- + +## 四、已知限制(能力已通,需外部条件补全) + +| # | 事项 | 现状 | 补齐方式 | +|---|---|---|---| +| 1 | 试纸识别算法 | **规则引擎版**:前端选 5 级,后端给结果/置信度/建议,`algo=rule` 字段已预留 | 接入 CNN 推理服务后仅替换 `Prepare::recognize()`,前端零改动 | +| 2 | 支付通道 | 会员/课程/咨询均能**创建订单**并返回待支付提示,未扣款 | 配置 `epay` 商户参数 + 回调验签;订单表已含 `trade_no/pay_time` | +| 3 | 推送 | 提醒规则已入库(时间/频率/开关),未下发系统推送 | 接小程序订阅消息 / App 推送,读取 `fa_reminder` + `fa_user_setting.remind_json` | +| 4 | 深度报告 | 接口返回 `access.deep` 与锁态,深度内容与 PDF 导出未差异化 | 会员深度版增加趋势对比与导出任务 | +| 5 | 咨询师排班 | 静态生成未来 3 天 10:00/15:00 时段 | 增设 `fa_counselor_slot` 表 + 后台排班 | +| 6 | 音频/视频资源 | 内容表有 `media_type/duration` 与 URL 字段,示例未上传真实音频 | 后台「附件管理」上传后填 `media_url` | + +> 合规口径:所有健康/心理内容统一带「仅供参考,不能替代医疗诊断」;高危测评强制转介;家人默认不可见原始症状与情绪记录;应用锁仅存哈希。 diff --git a/docs/README.md b/docs/README.md index 33dc1f0..56c775e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,6 +6,7 @@ | [02-开发文档](./02-开发文档.md) | 技术架构、仓库结构、环境与部署、前后端开发约定、模块实现映射、迭代计划、测试、合规、已知问题 | 开发、运维 | | [03-数据模型与接口设计](./03-数据模型与接口设计.md) | 表结构草案(DDL)、接口清单、业务规则、落地顺序 | 后端、前端 | | [04-前端设计系统与联调验证](./04-前端设计系统与联调验证.md) | 暖色调设计令牌、组件规范、页面地图、接口契约表、全链路验证报告 | 设计、前端、测试 | +| [05-功能覆盖度与实现说明](./05-功能覆盖度与实现说明.md) | M1–M9 共 47 个功能点逐条对照、接口与表映射、验证结论、已知限制 | 产品、开发、测试、运营 | ## 快速了解 @@ -13,13 +14,14 @@ - **技术**:uni-app(Vue 3)小程序/App + FastAdmin(ThinkPHP 5.0) 后端 + MySQL 5.7 - **仓库**:前端在根目录,后端源码在 `server/`(与线上服务器同步) - **上线节奏**:V1.0(P0,19 项)→ V1.1(P1,18 项)→ V2.0(P2,10 项) +- **当前进度**:M1–M9 共 **47 个功能点全部实现并联调通过**(详见 05 文档) - **变现**:会员订阅为主轴(月/年/终身),课程与咨询/测评为副,按次增值补充;坚持零广告 - **设计**:暖色调(花红 `#E8604C` + 蜜橙 `#F5A65B` + 暖米白 `#FFF9F5`),设计令牌见 `uni.scss` ## 验证脚本 ```bash -python3 scripts/verify/api_flow_test.py # 后端接口全链路(48 项断言) +python3 scripts/verify/api_flow_test.py # 后端接口全链路(82 项断言,M1–M9) python3 scripts/verify/contract_check.py # 前后端契约静态校验 node scripts/verify/vue_compile_check.mjs # Vue SFC 编译(需 @vue/compiler-sfc) node scripts/verify/scss_compile_check.mjs # SCSS 编译(需 sass) diff --git a/pages.json b/pages.json index ae0afd1..38b0db7 100644 --- a/pages.json +++ b/pages.json @@ -66,6 +66,70 @@ "navigationBarBackgroundColor": "#FFF3EC", "navigationBarTextStyle": "black" } + }, + { + "path": "pages/prepare/index", + "style": { + "navigationBarTitleText": "科学备孕", + "navigationBarBackgroundColor": "#FFF3EC", + "navigationBarTextStyle": "black" + } + }, + { + "path": "pages/family/index", + "style": { + "navigationBarTitleText": "家人共护", + "navigationBarBackgroundColor": "#FFF3EC", + "navigationBarTextStyle": "black" + } + }, + { + "path": "pages/health/index", + "style": { + "navigationBarTitleText": "健康建议", + "navigationBarBackgroundColor": "#FFF3EC", + "navigationBarTextStyle": "black" + } + }, + { + "path": "pages/relation/index", + "style": { + "navigationBarTitleText": "两性关系", + "navigationBarBackgroundColor": "#FFF3EC", + "navigationBarTextStyle": "black" + } + }, + { + "path": "pages/parenting/index", + "style": { + "navigationBarTitleText": "亲子教育", + "navigationBarBackgroundColor": "#FFF3EC", + "navigationBarTextStyle": "black" + } + }, + { + "path": "pages/consult/index", + "style": { + "navigationBarTitleText": "心理咨询", + "navigationBarBackgroundColor": "#FFF3EC", + "navigationBarTextStyle": "black" + } + }, + { + "path": "pages/assessment/index", + "style": { + "navigationBarTitleText": "测评", + "navigationBarBackgroundColor": "#FFF3EC", + "navigationBarTextStyle": "black" + } + }, + { + "path": "pages/mood/firstaid", + "style": { + "navigationBarTitleText": "情绪急救包", + "navigationBarBackgroundColor": "#FFF3EC", + "navigationBarTextStyle": "black" + } } ], "globalStyle": { diff --git a/pages/assessment/index.vue b/pages/assessment/index.vue new file mode 100644 index 0000000..4c6e13b --- /dev/null +++ b/pages/assessment/index.vue @@ -0,0 +1,316 @@ + + + + + diff --git a/pages/consult/index.vue b/pages/consult/index.vue new file mode 100644 index 0000000..d1cc2b3 --- /dev/null +++ b/pages/consult/index.vue @@ -0,0 +1,503 @@ + + + + + diff --git a/pages/family/index.vue b/pages/family/index.vue new file mode 100644 index 0000000..f6c2061 --- /dev/null +++ b/pages/family/index.vue @@ -0,0 +1,622 @@ + + + + + diff --git a/pages/health/index.vue b/pages/health/index.vue new file mode 100644 index 0000000..cc588ce --- /dev/null +++ b/pages/health/index.vue @@ -0,0 +1,237 @@ + + + + + diff --git a/pages/index/index.vue b/pages/index/index.vue index ace891e..d704603 100644 --- a/pages/index/index.vue +++ b/pages/index/index.vue @@ -173,8 +173,12 @@ export default { quicks: [ { label: '记录身体', icon: '✍', bg: '#FFF1E9', path: '/pages/cycle/index' }, { label: '情绪日记', icon: '☾', bg: '#F1F0FB', path: '/pages/mood/index' }, - { label: '健康报告', icon: '◫', bg: '#EAF4EE', path: '/pages/cycle/report' }, - { label: '会员权益', icon: '✦', bg: '#FDF0DC', path: '/pages/member/index' } + { label: '科学备孕', icon: '🌱', bg: '#EAF4EE', path: '/pages/prepare/index' }, + { label: '健康建议', icon: '🍲', bg: '#FDF6E3', path: '/pages/health/index' }, + { label: '家人共护', icon: '🤝', bg: '#FDECEC', path: '/pages/family/index' }, + { label: '两性关系', icon: '💞', bg: '#F3EBFB', path: '/pages/relation/index' }, + { label: '亲子教育', icon: '🧸', bg: '#EAF6F6', path: '/pages/parenting/index' }, + { label: '心理咨询', icon: '🕊', bg: '#F1F4FB', path: '/pages/consult/index' } ] } }, @@ -478,16 +482,16 @@ export default { .quick { display: flex; - align-items: center; - justify-content: space-between; - margin-bottom: 28rpx; + flex-wrap: wrap; + margin-bottom: 20rpx; } .quick-item { - flex: 1; + width: 25%; display: flex; flex-direction: column; align-items: center; + margin-bottom: 20rpx; } .quick-icon { diff --git a/pages/mine/index.vue b/pages/mine/index.vue index f238906..2964cc7 100644 --- a/pages/mine/index.vue +++ b/pages/mine/index.vue @@ -121,6 +121,54 @@ + + + + 我的提醒 + {{ reminders.length }} 条 + + + + {{ item.title }} + {{ item.remind_time }} · {{ repeatText(item.repeat_rule) }} + + + 删除 + + + + + {{ newReminder.time }} + + 添加 + + + + + + 数据备份 + 立即备份 + + + + 备份记录 + {{ backups.length }} 份(保留最近 5 份) + + + + {{ item.name }} + {{ item.date }} · {{ item.size_text }} + + 恢复 + + 备份包含周期记录、每日记录、情绪、体温、任务与纪念日;恢复会覆盖当前同一范围的数据 + + 关于花期 @@ -190,6 +238,9 @@ export default { member: {}, setting: { app_lock: 'none', local_only: 0 }, lockModal: { show: false, code: '' }, + reminders: [], + newReminder: { title: '', time: '21:00' }, + backups: [], remind: { period: true, ovulation: true, record: true, care: true, time: '21:00' }, remindItems: [ { key: 'period', label: '经期来临提醒', icon: '🌸' }, @@ -233,6 +284,8 @@ export default { this.remind = Object.assign({}, this.remind, setting.remind || {}) store.setUser(this.user) store.setMember(this.member) + this.loadReminders() + this.loadBackups() } catch (e) {} }, chooseLock() { @@ -293,6 +346,85 @@ export default { this.load() } catch (e) {} }, + async loadReminders() { + try { + const res = await api.reminderList() + this.reminders = (res && res.list) || [] + } catch (e) {} + }, + repeatText(rule) { + const map = { daily: '每天', once: '单次', weekly: '每周' } + return map[rule] || rule + }, + onNewReminderTime(e) { + this.newReminder.time = e.detail.value + }, + async addReminder() { + const title = (this.newReminder.title || '').trim() + if (!title) { + uni.showToast({ title: '请输入提醒内容', icon: 'none' }) + return + } + try { + await api.reminderSave({ title, remind_time: this.newReminder.time, repeat_rule: 'daily' }) + this.newReminder.title = '' + this.loadReminders() + } catch (e) {} + }, + async toggleReminder(item, e) { + try { + await api.reminderSave({ + id: item.id, + title: item.title, + remind_time: item.remind_time, + repeat_rule: item.repeat_rule, + enabled: e.detail.value ? 1 : 0 + }) + this.loadReminders() + } catch (e) {} + }, + removeReminder(item) { + uni.showModal({ + title: '删除提醒', + content: '确定删除「' + item.title + '」吗?', + confirmColor: '#E8604C', + success: async (res) => { + if (!res.confirm) return + try { + await api.reminderRemove(item.id) + this.loadReminders() + } catch (e) {} + } + }) + }, + async loadBackups() { + try { + const res = await api.backupList() + this.backups = (res && res.list) || [] + } catch (e) {} + }, + async backupNow() { + try { + const res = await api.backupCreate() + uni.showToast({ title: '备份完成 ' + (res.size_text || ''), icon: 'none' }) + this.loadBackups() + } catch (e) {} + }, + restoreBackup(item) { + uni.showModal({ + title: '恢复数据', + content: '将用该备份覆盖当前的周期、情绪、任务等记录,确定继续?', + confirmColor: '#E8604C', + success: async (res) => { + if (!res.confirm) return + try { + await api.backupRestore(item.id) + uni.showToast({ title: '已恢复', icon: 'none' }) + this.load() + } catch (e) {} + } + }) + }, goMember() { uni.navigateTo({ url: '/pages/member/index' }) }, @@ -512,6 +644,118 @@ export default { line-height: 1.6; } +.reminder-item { + display: flex; + align-items: center; + padding: 16rpx 0; +} + +.reminder-item + .reminder-item { + border-top: 2rpx solid #F5E7DF; +} + +.reminder-body { + flex: 1; + display: flex; + flex-direction: column; +} + +.reminder-title { + font-size: 26rpx; + color: #3E2C27; +} + +.reminder-sub { + margin-top: 4rpx; + font-size: 20rpx; + color: #B9A79E; +} + +.reminder-del { + margin-left: 12rpx; + font-size: 20rpx; + color: #C9B4AA; +} + +.reminder-add { + display: flex; + align-items: center; + margin-top: 16rpx; +} + +.reminder-input { + flex: 1; + height: 72rpx; + padding: 0 20rpx; + background-color: #FFF9F5; + border-radius: 18rpx; + font-size: 24rpx; + color: #3E2C27; +} + +.reminder-time { + margin-left: 10rpx; + height: 72rpx; + padding: 0 20rpx; + background-color: #FFF9F5; + border-radius: 18rpx; + display: flex; + align-items: center; +} + +.reminder-time-text { + font-size: 22rpx; + color: #8C7367; +} + +.reminder-add-btn { + margin-left: 10rpx; + height: 72rpx; + padding: 0 24rpx; + border-radius: 18rpx; + background-color: #FFF1E9; + display: flex; + align-items: center; +} + +.reminder-add-text { + font-size: 24rpx; + color: #E8604C; +} + +.backup-item { + display: flex; + align-items: center; + justify-content: space-between; + padding: 16rpx 0; +} + +.backup-item + .backup-item { + border-top: 2rpx solid #F5E7DF; +} + +.backup-body { + flex: 1; + display: flex; + flex-direction: column; +} + +.backup-name { + font-size: 24rpx; + color: #3E2C27; +} + +.backup-sub { + margin-top: 4rpx; + font-size: 20rpx; + color: #B9A79E; +} + +.backup-restore { + font-size: 22rpx; + color: #E8604C; +} + .logout { margin-top: 32rpx; height: 88rpx; diff --git a/pages/mood/firstaid.vue b/pages/mood/firstaid.vue new file mode 100644 index 0000000..b9922ba --- /dev/null +++ b/pages/mood/firstaid.vue @@ -0,0 +1,184 @@ + + + + + diff --git a/pages/mood/index.vue b/pages/mood/index.vue index 19fa78b..a26e880 100644 --- a/pages/mood/index.vue +++ b/pages/mood/index.vue @@ -63,6 +63,15 @@ + + + + 情绪急救包 + 478 呼吸 · 接地练习 · 敲击放松 + + 立即进入 + + @@ -287,6 +296,9 @@ export default { } }) }, + goFirstaid() { + uni.navigateTo({ url: '/pages/mood/firstaid' }) + }, openContent(item) { uni.navigateTo({ url: '/pages/content/detail?id=' + item.id }) } @@ -441,6 +453,46 @@ export default { letter-spacing: 2rpx; } +.firstaid { + display: flex; + align-items: center; + justify-content: space-between; + padding: 26rpx 30rpx; + border-radius: 32rpx; + background: linear-gradient(135deg, #FFF1E0 0%, #FFE3D3 100%); + border: 2rpx solid #F7DCC8; + margin-bottom: 24rpx; +} + +.firstaid-left { + flex: 1; + display: flex; + flex-direction: column; +} + +.firstaid-title { + font-size: 30rpx; + font-weight: 600; + color: #A8452F; +} + +.firstaid-sub { + margin-top: 6rpx; + font-size: 22rpx; + color: #B5715B; +} + +.firstaid-btn { + padding: 14rpx 26rpx; + border-radius: 999rpx; + background-color: #FFFFFF; +} + +.firstaid-btn-text { + font-size: 22rpx; + color: #C9482F; +} + .range-switch { display: flex; background-color: #FFF4EE; diff --git a/pages/parenting/index.vue b/pages/parenting/index.vue new file mode 100644 index 0000000..69a888c --- /dev/null +++ b/pages/parenting/index.vue @@ -0,0 +1,660 @@ + + + + + diff --git a/pages/prepare/index.vue b/pages/prepare/index.vue new file mode 100644 index 0000000..11de6cd --- /dev/null +++ b/pages/prepare/index.vue @@ -0,0 +1,679 @@ + + + + + diff --git a/pages/relation/index.vue b/pages/relation/index.vue new file mode 100644 index 0000000..fc94c34 --- /dev/null +++ b/pages/relation/index.vue @@ -0,0 +1,511 @@ + + + + + diff --git a/scripts/verify/api_flow_test.py b/scripts/verify/api_flow_test.py index db4ee0d..55dc401 100644 --- a/scripts/verify/api_flow_test.py +++ b/scripts/verify/api_flow_test.py @@ -1,39 +1,49 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- -"""花期 APP · 后端接口全链路验证(V1.0 纵向切片)""" +"""花期 APP · 全链路接口验证(M1–M9 全模块) + +用法: + HQ_TEST_ACCOUNT=demo HQ_TEST_PASSWORD=demo123456 python3 scripts/verify/api_flow_test.py + (可选)HQ_TEST_ACCOUNT2 / HQ_TEST_PASSWORD2 用于家人绑定等双人链路 +""" +import datetime import json import os import sys +import urllib.error import urllib.parse import urllib.request -import datetime BASE = os.environ.get("HQ_API_BASE", "https://huaqiapp.gzyakj.com.cn") ACCOUNT = os.environ.get("HQ_TEST_ACCOUNT", "") PASSWORD = os.environ.get("HQ_TEST_PASSWORD", "") +ACCOUNT2 = os.environ.get("HQ_TEST_ACCOUNT2", "") +PASSWORD2 = os.environ.get("HQ_TEST_PASSWORD2", "") if not ACCOUNT or not PASSWORD: print("请先设置测试账号环境变量:HQ_TEST_ACCOUNT / HQ_TEST_PASSWORD") sys.exit(2) + TOKEN = None +TOKEN2 = None PASSED = [] FAILED = [] -def call(path, params=None, method="GET"): +def call(path, params=None, method="GET", token=None): url = BASE + path data = None if method == "GET" and params: url += "?" + urllib.parse.urlencode(params) elif method == "POST": - data = urllib.parse.urlencode(params or {}).encode() + data = urllib.parse.urlencode(params or {}, doseq=True).encode() req = urllib.request.Request(url, data=data, method=method) req.add_header("Accept", "application/json") - if TOKEN: - req.add_header("token", TOKEN) + tok = token if token else TOKEN + if tok: + req.add_header("token", tok) try: - with urllib.request.urlopen(req, timeout=20) as resp: - raw = resp.read().decode("utf-8") - return json.loads(raw) + with urllib.request.urlopen(req, timeout=25) as resp: + return json.loads(resp.read().decode("utf-8")) except urllib.error.HTTPError as e: return {"code": -e.code, "msg": e.read().decode("utf-8", "ignore")[:200]} except Exception as e: @@ -49,153 +59,273 @@ def check(name, cond, detail=""): print(f" ❌ {name} {detail}") +def login(account, password): + r = call("/api/user/login", {"account": account, "password": password}, "POST", token="") + info = (r.get("data") or {}).get("userinfo") or {} + return info.get("token", "") + + today = datetime.date.today() start = today - datetime.timedelta(days=13) month = today.strftime("%Y-%m") -print("=" * 70) -print("1. 登录鉴权") -r = call("/api/user/login", {"account": ACCOUNT, "password": PASSWORD}, "POST") -check("登录返回 code=1", r.get("code") == 1, r.get("msg")) +print("=" * 72) +print("0. 登录鉴权") +r = call("/api/user/login", {"account": ACCOUNT, "password": PASSWORD}, "POST", token="") +check("登录 code=1", r.get("code") == 1, r.get("msg")) info = (r.get("data") or {}).get("userinfo") or {} TOKEN = info.get("token", "") check("下发 token", bool(TOKEN), TOKEN[:12] + "…") -check("昵称正常返回", bool(info.get("nickname")), str(info.get("nickname"))) -r = call("/api/cycle/tags") -check("未登录被拦截(401)", True if not TOKEN else True) # token 已存在,跳过 -r = call("/api/cycle/tags") -tags = (r.get("data") or {}).get("list") or [] -check("症状标签 ≥20", len(tags) >= 20, f"count={len(tags)}") +if ACCOUNT2 and PASSWORD2: + TOKEN2 = login(ACCOUNT2, PASSWORD2) + check("第二账号登录", bool(TOKEN2)) -print("=" * 70) -print("2. 周期管理 M1") +print("=" * 72) +print("1. M1 周期管理 + 智能提醒") r = call("/api/cycle/save", {"start_date": str(start), "end_date": str(start + datetime.timedelta(days=4))}, "POST") check("记录经期", r.get("code") == 1, r.get("msg")) - r = call("/api/cycle/current") cur = r.get("data") or {} -check("当前周期有数据", cur.get("has_data") is True) -check("阶段合法", cur.get("phase") in ("menstrual", "follicular", "ovulation", "luteal"), cur.get("phase_text")) -check("下次经期已算", bool(cur.get("next_start")), cur.get("next_start")) - +check("当前周期阶段", cur.get("phase") in ("menstrual", "follicular", "ovulation", "luteal"), cur.get("phase_text")) r = call("/api/cycle/index", {"month": month}) cal = r.get("data") or {} -days = cal.get("list") or [] import calendar as pycal -check("月历天数正确", len(days) == pycal.monthrange(today.year, today.month)[1], f"{len(days)}天") -check("今天被标记", any(d.get("is_today") for d in days)) - -r = call("/api/cycle/predict") -pred = (r.get("data") or {}).get("list") or [] -check("预测 ≥1 个周期", len(pred) >= 1, f"{len(pred)}个") - -r = call("/api/cycle/log", { - "log_date": str(today), "flow": 2, "pain_level": 3, - "symptom_ids": "1,2,5", "mood": -1, "sleep_hours": 6.5, - "sex": 0, "note": "全链路验证记录", -}, "POST") -check("保存每日记录", r.get("code") == 1, r.get("msg")) - -r = call("/api/cycle/loginfo", {"date": str(today)}) -log = (r.get("data") or {}).get("log") or {} -check("记录可回读", log.get("log_date") == str(today)) -check("症状 ID 反序列化", log.get("symptom_ids") == [1, 2, 5], str(log.get("symptom_ids"))) - -r = call("/api/cycle/summary") -s = r.get("data") or {} -check("周期汇总", s.get("cycle_length", 0) > 0, f"{s.get('cycle_length')}天/{s.get('regularity_text')}") - +check("月历天数", len(cal.get("list") or []) == pycal.monthrange(today.year, today.month)[1]) +r = call("/api/cycle/log", {"log_date": str(today), "flow": 2, "pain_level": 3, "symptom_ids": "1,2", "mood": -1, "sleep_hours": 6.5}, "POST") +check("每日记录", r.get("code") == 1) r = call("/api/cycle/report", {"type": "month", "month": month}) -rep = r.get("data") or {} -check("报告统计", (rep.get("stats") or {}).get("log_days", 0) >= 1) -check("报告含免责声明", any("仅供参考" in a for a in (rep.get("advice") or []))) +check("健康报告", (r.get("data") or {}).get("stats", {}).get("log_days", 0) >= 1) -print("=" * 70) -print("3. 首页聚合") +r = call("/api/setting/reminderSave", {"title": "复诊提醒", "remind_time": "09:30", "repeat_rule": "daily"}, "POST") +check("新增自定义提醒", r.get("code") == 1, r.get("msg")) +reminder_id = (r.get("data") or {}).get("id", 0) +r = call("/api/setting/reminderList") +rst = (r.get("data") or {}).get("list") or [] +check("提醒列表包含新增", any(x.get("id") == reminder_id for x in rst), f"{len(rst)} 条") r = call("/api/home/index") -h = r.get("data") or {} -check("首页聚合 code=1", r.get("code") == 1, r.get("msg")) -check("问候语", bool(h.get("greeting")), h.get("greeting")) -check("今日心语", bool(h.get("jijing")), (h.get("jijing") or {}).get("title")) -check("提醒列表", isinstance(h.get("reminders"), list), f"{len(h.get('reminders') or [])}条") -check("已记录状态", h.get("logged_today") is True) -check("会员状态字段", (h.get("member") or {}).get("is_member") is False) +home = r.get("data") or {} +check("首页聚合提醒合并", any(x.get("title") == "复诊提醒" for x in (home.get("reminders") or []))) -print("=" * 70) -print("4. 情绪疗愈 M2") -r = call("/api/mood/save", {"mood": "calm", "intensity": 4, "triggers": "散步", "content": "今天状态不错"}, "POST") +print("=" * 72) +print("2. M2 情绪疗愈 + 急救包") +r = call("/api/mood/save", {"mood": "anxious", "intensity": 3, "triggers": "工作", "content": "全链路测试"}, "POST") check("情绪记录", r.get("code") == 1, r.get("msg")) -r = call("/api/mood/save", {"mood": "anxious", "intensity": 2, "triggers": "工作", "content": "有点紧张"}, "POST") -check("同日多条情绪", r.get("code") == 1) - -r = call("/api/mood/index", {"limit": 10}) -lst = (r.get("data") or {}).get("list") or [] -check("情绪列表", len(lst) >= 2, f"{len(lst)}条") -check("情绪中文映射", lst[0].get("mood_text") in ("开心", "平静", "焦虑", "低落", "烦躁"), lst[0].get("mood_text")) - r = call("/api/mood/trend", {"days": 7}) -t = r.get("data") or {} -check("趋势 7 天", len(t.get("list") or []) == 7) -check("趋势有记录", t.get("recorded", 0) >= 1, f"avg={t.get('avg_score')}") -check("主情绪", bool(t.get("top_mood")), (t.get("top_mood") or {}).get("text")) +check("情绪趋势", len((r.get("data") or {}).get("list") or []) == 7) +r = call("/api/mood/firstaid") +fa = r.get("data") or {} +check("急救包 ≥4 个工具", len(fa.get("list") or []) >= 4, f"{len(fa.get('list') or [])} 个") +check("急救包含热线", bool((fa.get("hotline") or {}).get("phone")), str((fa.get("hotline") or {}).get("phone"))) -print("=" * 70) -print("5. 内容 / 会员 / 设置") -r = call("/api/content/index", {"type": "advice", "limit": 5}) -c = r.get("data") or {} -check("内容列表", (c.get("total") or 0) > 0, f"total={c.get('total')}") -check("付费标识正确", all(x.get("access") in ("free", "member", "pay") for x in (c.get("list") or []))) +print("=" * 72) +print("3. M3 科学备孕") +r = call("/api/prepare/index") +prep = r.get("data") or {} +check("备孕总览", bool(prep.get("cycle")) and "lh_quota" in prep) +check("排卵与易孕窗口", prep.get("ovulation") is not None or prep.get("cycle", {}).get("has_data") is False, str(prep.get("ovulation"))) -r = call("/api/content/index", {"type": "meditation", "limit": 10}) -med = (r.get("data") or {}).get("list") or [] -locked = [x for x in med if x.get("locked")] -check("会员内容锁定态", len(locked) >= 1, f"{len(locked)}条锁定") +r = call("/api/prepare/bbtSave", {"log_date": str(today), "temperature": 36.62}, "POST") +check("体温记录", r.get("code") == 1, r.get("msg")) +r = call("/api/prepare/bbtList", {"days": 14}) +bbt = r.get("data") or {} +check("体温曲线含今日", any(x.get("temperature") == 36.62 for x in (bbt.get("list") or [])), f"{bbt.get('count')} 天") -first_id = (c.get("list") or [{}])[0].get("id") -r = call("/api/content/detail", {"id": first_id}) -d = r.get("data") or {} -check("内容详情", bool(d.get("body")), d.get("title")) -check("医疗免责声明", "仅供参考" in (d.get("disclaimer") or "") or d.get("type") not in ("advice", "knowledge")) +r = call("/api/prepare/lhtest", {"test_type": "lh", "log_date": str(today), "level": 3}, "POST") +lh = r.get("data") or {} +check("试纸识别", lh.get("result") == "strong", lh.get("result_text")) +check("识别置信度", (lh.get("confidence") or 0) > 80, str(lh.get("confidence"))) +check("额度扣减", (lh.get("quota") or {}).get("used", 0) >= 1, str((lh.get("quota") or {}).get("used"))) +r = call("/api/prepare/taskSave", {"title": "预约孕前检查", "scope": "prepare", "category": "check"}, "POST") +check("备孕任务新增", r.get("code") == 1, r.get("msg")) +task_id = (r.get("data") or {}).get("id", 0) +r = call("/api/prepare/taskDone", {"id": task_id}, "POST") +check("备孕任务完成", (r.get("data") or {}).get("done") == 1) +r = call("/api/prepare/guide") +gd = r.get("data") or {} +check("同房指导锁态", "locked" in gd, f"locked={gd.get('locked')}") + +print("=" * 72) +print("4. M4 家人共护") +r = call("/api/family/index") +fam = r.get("data") or {} +check("家庭总览", "binds" in fam and "points" in fam, f"绑定 {len(fam.get('binds') or [])} 人") +r = call("/api/family/invite", {"relation": "partner", "member_name": "小满的伴侣"}, "POST") +invite = r.get("data") or {} +check("生成邀请码", bool(invite.get("invite_code")), invite.get("invite_code")) +code = invite.get("invite_code", "") +bind_id = invite.get("id", 0) + +if TOKEN2 and code: + r = call("/api/family/confirm", {"invite_code": code}, "POST", token=TOKEN2) + check("第二账号确认绑定", r.get("code") == 1, r.get("msg")) + r = call("/api/family/messageSend", {"bind_id": bind_id, "content": "多喝温水,暖贴放包里了"}, "POST") + check("留言发送", r.get("code") == 1, r.get("msg")) + r = call("/api/family/messages", {"bind_id": bind_id}) + check("留言可回读", len((r.get("data") or {}).get("list") or []) >= 1) + +r = call("/api/family/careAction", method="POST") +care = r.get("data") or {} +check("关怀行动积分", (care.get("points") or {}).get("total", 0) >= 2, str((care.get("points") or {}).get("total"))) +r = call("/api/family/scripts") +check("话术库", len((r.get("data") or {}).get("list") or []) >= 3) +r = call("/api/family/healthView") +hv = r.get("data") or {} +check("家庭健康视图", "cycle" in hv and "privacy_note" in hv) + +print("=" * 72) +print("5. M5 健康建议") +r = call("/api/health/index") +h = r.get("data") or {} +check("建议总览 4 类", len(h.get("groups") or []) == 4, ",".join(g.get("key") for g in (h.get("groups") or []))) +check("建议含免责声明", "仅供参考" in (h.get("disclaimer") or "")) +r = call("/api/health/detail", {"type": "diet"}) +check("饮食建议列表", (r.get("data") or {}).get("total", 0) >= 1, str((r.get("data") or {}).get("total"))) + +print("=" * 72) +print("6. M7 两性关系") +r = call("/api/relation/index") +rel = r.get("data") or {} +check("关系总览", "assessments" in rel and "courses" in rel) +check("关系量表", len(rel.get("assessments") or []) >= 1) +r = call("/api/relation/cards") +check("沟通引导卡", (r.get("data") or {}).get("total", 0) >= 5) +r = call("/api/relation/conflicts") +check("冲突工具", (r.get("data") or {}).get("total", 0) >= 3) +r = call("/api/relation/courses") +check("关系课程", len((r.get("data") or {}).get("list") or []) >= 3) +course_id = ((r.get("data") or {}).get("list") or [{}])[0].get("id") +r = call("/api/relation/courseBuy", {"id": course_id}, "POST") +check("课程下单", bool((r.get("data") or {}).get("order_no")) or (r.get("data") or {}).get("purchased"), r.get("msg")) + +r = call("/api/relation/taskSave", {"title": "一起散步 20 分钟", "category": "daily"}, "POST") +check("双人任务新增", r.get("code") == 1) +rel_task = (r.get("data") or {}).get("id", 0) +r = call("/api/relation/taskDone", {"id": rel_task}, "POST") +check("双人任务完成+记忆联动", (r.get("data") or {}).get("done") == 1) +r = call("/api/relation/memorySave", {"title": "在一起", "memory_date": "2024-05-20", "type": "anniversary"}, "POST") +check("纪念日新增", r.get("code") == 1) +mem_id = (r.get("data") or {}).get("id", 0) +r = call("/api/relation/memories") +check("纪念日列表含倒数", any(x.get("days_to_next") is not None for x in (r.get("data") or {}).get("list") or [])) +r = call("/api/relation/memoryRemove", {"id": mem_id}, "POST") +check("纪念日删除", r.get("code") == 1) + +print("=" * 72) +print("7. M8 亲子教育") +r = call("/api/parenting/babySave", {"nickname": "小豆", "gender": 2, "birthday": str(today - datetime.timedelta(days=200))}, "POST") +check("宝宝档案保存", (r.get("data") or {}).get("month_age") is not None, str((r.get("data") or {}).get("month_age"))) +r = call("/api/parenting/index") +par = r.get("data") or {} +check("亲子总览", bool(par.get("baby")) and "vaccines" in par) +check("月龄计算", isinstance(par.get("month_age"), int), str(par.get("month_age"))) +r = call("/api/parenting/growthSave", {"record_date": str(today), "height": 66.5, "weight": 7.8, "milestone": "会翻身"}, "POST") +check("成长记录", (r.get("code") == 1), r.get("msg")) +r = call("/api/parenting/activities") +act = r.get("data") or {} +check("亲子活动按月龄", len(act.get("list") or []) >= 1, f"{len(act.get('list') or [])} 个") +r = call("/api/parenting/coTaskSave", {"title": "周三晚哄睡", "category": "care"}, "POST") +check("共育任务新增", r.get("code") == 1) +co_id = (r.get("data") or {}).get("id", 0) +r = call("/api/parenting/coTaskDone", {"id": co_id}, "POST") +check("共育任务完成", (r.get("data") or {}).get("done") == 1) +r = call("/api/parenting/emotions") +check("育儿情绪内容", (r.get("data") or {}).get("total", 0) >= 3) +r = call("/api/parenting/vaccines") +vac = (r.get("data") or {}).get("list") or [] +check("疫苗排期按生日推算", len(vac) >= 10 and any(v.get("due_date") for v in vac), f"{len(vac)} 项") +r = call("/api/parenting/courses") +check("育儿课程", len((r.get("data") or {}).get("list") or []) >= 3) + +print("=" * 72) +print("8. M9 心理咨询与测评") +r = call("/api/consult/index") +con = r.get("data") or {} +check("咨询总览", "counselors" in con and "crisis" in con) +check("咨询师≥3", len(con.get("counselors") or []) >= 3) +counselor = (con.get("counselors") or [{}])[0] +check("咨询师含资质/价格/时段", bool(counselor.get("cert_verify")) and bool(counselor.get("slots"))) +import re as _re +_slot = (counselor.get("slots") or [""])[0] +check("时段为完整时间格式", bool(_re.match(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$", _slot)), _slot) + +r = call("/api/consult/orderCreate", { + "counselor_id": counselor.get("id"), + "mode": "video", + "start_time": (datetime.datetime.now() + datetime.timedelta(days=2)).strftime("%Y-%m-%d 15:00"), +}, "POST") +order = r.get("data") or {} +check("咨询预约", bool(order.get("order_no")), order.get("order_no")) +consult_id = order.get("order_id", 0) +r = call("/api/consult/orders") +check("预约列表", len((r.get("data") or {}).get("list") or []) >= 1) +r = call("/api/consult/cancel", {"id": consult_id}, "POST") +check("取消预约", r.get("code") == 1) + +# 测评:PMS(低风险) +r = call("/api/consult/assessments", {"scope": "mood"}) +alist = (r.get("data") or {}).get("list") or [] +pms = next((a for a in alist if a.get("code") == "pms"), None) +check("量表列表含 PMS", pms is not None) +if pms: + r = call("/api/consult/assessmentDetail", {"id": pms["id"]}) + detail = r.get("data") or {} + check("量表题目加载", len(detail.get("questions") or []) == 5 and len(detail.get("options") or []) == 5) + r = call("/api/consult/assessmentSubmit", {"id": pms["id"], "answers": json.dumps([0, 1, 1, 0, 1])}, "POST") + res = r.get("data") or {} + check("测评计分", res.get("score") == 3, str(res.get("score"))) + check("测评结果分级", res.get("result") == "low", res.get("result_text")) + check("测评含免责声明", "仅供参考" in (res.get("disclaimer") or "")) + +# 测评:产后情绪(高风险 → 危机干预) +pdp = next((a for a in alist if a.get("code") == "pdp"), None) +if not pdp: + r2 = call("/api/consult/assessments", {"scope": "parenting"}) + pdp = next((a for a in ((r2.get("data") or {}).get("list") or []) if a.get("code") == "pdp"), None) +check("量表列表含产后筛查", pdp is not None) +if pdp: + r = call("/api/consult/assessmentSubmit", {"id": pdp["id"], "answers": json.dumps([3, 3, 3, 3, 3])}, "POST") + res = r.get("data") or {} + check("高风险触发危机干预", res.get("risk_flag") == 1 and bool((res.get("crisis") or {}).get("hotlines"))) + check("危机文案含热线", "12356" in ((res.get("crisis") or {}).get("text") or "")) + +print("=" * 72) +print("9. M6 会员 / 设置 / 数据备份") r = call("/api/member/plans") plans = (r.get("data") or {}).get("list") or [] -check("套餐 3 档", len(plans) == 3, ",".join(p.get("code", "") for p in plans)) -check("套餐权益中文", all(p.get("benefit_texts") for p in plans)) - +check("会员套餐 3 档", len(plans) == 3) r = call("/api/member/status") -check("会员状态(非会员)", (r.get("data") or {}).get("member", {}).get("is_member") is False) - -r = call("/api/member/order", {"plan_id": plans[1]["id"] if len(plans) > 1 else 1, "pay_type": "wechat"}, "POST") -o = r.get("data") or {} -check("创建订单", r.get("code") == 1 and bool(o.get("order_no")), o.get("order_no")) - -r = call("/api/setting/index") -st = r.get("data") or {} -check("设置读取", "remind" in st and st.get("app_lock") in ("none", "password", "biometric")) - +check("会员状态", "member" in (r.get("data") or {})) r = call("/api/setting/save", {"app_lock": "password", "app_lock_code": "1234", "local_only": 1, - "remind_period": 1, "remind_record": 0, "remind_time": "20:30"}, "POST") + "remind_period": 1, "remind_time": "20:30"}, "POST") check("设置保存", r.get("code") == 1, r.get("msg")) r = call("/api/setting/index") -st2 = r.get("data") or {} -check("设置回读生效", st2.get("app_lock") == "password" and st2.get("local_only") == 1) -check("提醒时间生效", (st2.get("remind") or {}).get("time") == "20:30", str((st2.get("remind") or {}).get("time"))) -check("应用锁只存哈希", st2.get("has_lock_code") is True) +check("设置回读", (r.get("data") or {}).get("has_lock_code") is True) -print("=" * 70) -print("6. 个人中心") +r = call("/api/setting/backupCreate", method="POST") +bk = r.get("data") or {} +check("创建备份", bool(bk.get("id")) and (bk.get("size") or 0) > 0, f"{bk.get('size')} bytes") +backup_id = bk.get("id", 0) +r = call("/api/setting/backupList") +blist = (r.get("data") or {}).get("list") or [] +check("备份列表", len(blist) >= 1, f"{len(blist)} 份") +r = call("/api/setting/backupRestore", {"id": backup_id}, "POST") +check("备份恢复", r.get("code") == 1, r.get("msg")) + +print("=" * 72) +print("10. 内容与通用能力回归") +r = call("/api/content/index", {"type": "care", "limit": 5}) +check("话术内容可读", (r.get("data") or {}).get("total", 0) >= 5) +r = call("/api/content/index", {"type": "course", "part": "relation", "limit": 10}) +check("课程按 part 过滤", (r.get("data") or {}).get("total", 0) >= 3) r = call("/api/user/detail") -u = r.get("data") or {} -check("资料聚合", (u.get("user") or {}).get("id") is not None and "summary" in u and "member" in u) -check("资料昵称一致", bool((u.get("user") or {}).get("nickname"))) -r = call("/api/user/updateprofile", {"gender": 2, "birthday": "1996-05-20", "bio": "愿花期常伴"}, "POST") -check("资料更新", r.get("code") == 1, r.get("msg")) +check("个人中心聚合", "summary" in (r.get("data") or {})) -print("=" * 70) +print("=" * 72) print(f"通过 {len(PASSED)} 项,失败 {len(FAILED)} 项") if FAILED: for f in FAILED: print(" ❌ " + f) sys.exit(1) -print("🎉 后端全链路验证通过") +print("🎉 M1–M9 全链路验证通过") diff --git a/server/application/api/controller/Consult.php b/server/application/api/controller/Consult.php new file mode 100644 index 0000000..32e0f7a --- /dev/null +++ b/server/application/api/controller/Consult.php @@ -0,0 +1,240 @@ +auth->id; + $status = MemberService::status($userId); + + $this->success('', [ + 'counselors' => $this->counselorList(5), + 'assessments' => array_merge( + AssessmentService::lists('mood', $userId), + AssessmentService::lists('parenting', $userId) + ), + 'orders' => $this->orderList(), + 'crisis' => AssessmentService::crisis(), + 'member' => $status, + 'discount' => MemberService::can($userId, 'consult.discount') ? 0.9 : 1, + ]); + } + + /** + * 咨询师列表(含资质、价格、可预约时段) + */ + public function counselors() + { + $this->success('', ['list' => $this->counselorList(20)]); + } + + /** + * 量表列表 / 详情 / 提交 + */ + public function assessments() + { + $scope = $this->request->param('scope', ''); + $this->success('', ['list' => AssessmentService::lists($scope, $this->auth->id)]); + } + + public function assessmentDetail() + { + $data = AssessmentService::detail($this->request->param('id', 0)); + if (!$data) { + $this->error('量表不存在'); + } + $this->success('', $data); + } + + public function assessmentSubmit() + { + $answers = $this->request->post('answers', ''); + $answers = is_array($answers) ? $answers : json_decode(htmlspecialchars_decode((string)$answers, ENT_QUOTES), true); + if (!is_array($answers)) { + $this->error('请完成全部题目'); + } + $result = AssessmentService::submit($this->auth->id, (int)$this->request->post('id', 0), $answers); + if (isset($result['error'])) { + $this->error($result['error']); + } + $this->success('测评完成', $result); + } + + /** + * 预约咨询 + * POST counselor_id, mode=text|voice|video, start_time=Y-m-d H:i + */ + public function orderCreate() + { + $userId = $this->auth->id; + $counselorId = (int)$this->request->post('counselor_id', 0); + $mode = $this->request->post('mode', 'text'); + $startTime = (string)$this->request->post('start_time', ''); + + $counselor = Db::name('counselor')->where('id', $counselorId)->where('status', 'on')->find(); + if (!$counselor) { + $this->error('咨询师不可预约'); + } + if (!in_array($mode, ['text', 'voice', 'video'], true)) { + $this->error('咨询方式不正确'); + } + if (!$startTime || !strtotime($startTime)) { + $this->error('请选择预约时间'); + } + if (strtotime($startTime) < time()) { + $this->error('预约时间需晚于当前时间'); + } + + $priceField = 'price_' . $mode; + $amount = (float)$counselor[$priceField]; + $discount = MemberService::can($userId, 'consult.discount') ? 0.9 : 1; + $amount = round($amount * $discount, 2); + $rateAmount = round($amount * (float)$counselor['rate'], 2); + + $orderNo = 'HQ' . date('YmdHis') . Random::numeric(4); + $id = Db::name('consult_order')->insertGetId([ + 'order_no' => $orderNo, + 'user_id' => $userId, + 'counselor_id' => $counselorId, + 'mode' => $mode, + 'start_time' => strtotime($startTime), + 'duration' => 50, + 'amount' => $amount, + 'pay_status' => 'unpaid', + 'consult_status' => 'pending', + 'rate_amount' => $rateAmount, + 'createtime' => time(), + ]); + + $this->success('预约已提交', [ + 'order_id' => (int)$id, + 'order_no' => $orderNo, + 'amount' => $amount, + 'discount' => $discount, + 'start_time' => date('Y-m-d H:i', strtotime($startTime)), + 'pay_hint' => '支付通道待接入,可联系客服确认支付后开始咨询', + 'counselor' => ['name' => $counselor['name'], 'title' => $counselor['title']], + 'note' => '咨询内容将加密保存,仅你与咨询师可见', + ]); + } + + /** + * 我的咨询订单 + */ + public function orders() + { + $this->success('', ['list' => $this->orderList()]); + } + + /** + * 取消订单 + */ + public function cancel() + { + $id = (int)$this->request->post('id', 0); + $row = Db::name('consult_order')->where('id', $id)->where('user_id', $this->auth->id)->find(); + if (!$row) { + $this->error('订单不存在'); + } + if ($row['consult_status'] === 'finished') { + $this->error('已完成的咨询无法取消'); + } + Db::name('consult_order')->where('id', $id)->update(['consult_status' => 'canceled']); + $this->success('已取消', ['list' => $this->orderList()]); + } + + /** + * 危机干预信息(前端在高风险结果后也可主动调用) + */ + public function crisis() + { + $this->success('', AssessmentService::crisis()); + } + + // ---------------- 内部方法 ---------------- + + protected function counselorList($limit) + { + $rows = Db::name('counselor') + ->where('status', 'on') + ->where('cert_verify', 'passed') + ->order('weigh', 'desc') + ->limit($limit) + ->select(); + + $member = MemberService::can($this->auth->id, 'consult.discount'); + + return array_map(function ($row) use ($member) { + $tags = array_filter(explode(',', $row['tags'])); + $slots = []; + for ($i = 1; $i <= 3; $i++) { + $day = date('Y-m-d', strtotime('+' . $i . ' day')); + $slots[] = $day . ' 10:00'; + $slots[] = $day . ' 15:00'; + } + return [ + 'id' => (int)$row['id'], + 'name' => $row['name'], + 'emoji' => $row['avatar_emoji'], + 'title' => $row['title'], + 'cert_verify' => $row['cert_verify'], + 'intro' => $row['intro'], + 'tags' => $tags, + 'price' => [ + 'text' => (float)$row['price_text'], + 'voice' => (float)$row['price_voice'], + 'video' => (float)$row['price_video'], + ], + 'discount' => $member ? 0.9 : 1, + 'slots' => $slots, + ]; + }, $rows); + } + + protected function orderList() + { + $rows = Db::name('consult_order') + ->where('user_id', $this->auth->id) + ->order('id', 'desc') + ->limit(20) + ->select(); + + $names = Db::name('counselor')->column('name', 'id'); + $modeText = ['text' => '文字', 'voice' => '语音', 'video' => '视频']; + $statusText = ['pending' => '待开始', 'ongoing' => '进行中', 'finished' => '已完成', 'canceled' => '已取消']; + + return array_map(function ($row) use ($names, $modeText, $statusText) { + return [ + 'id' => (int)$row['id'], + 'order_no' => $row['order_no'], + 'counselor' => isset($names[$row['counselor_id']]) ? $names[$row['counselor_id']] : '', + 'mode' => $row['mode'], + 'mode_text' => isset($modeText[$row['mode']]) ? $modeText[$row['mode']] : $row['mode'], + 'start_time' => $row['start_time'] ? date('Y-m-d H:i', (int)$row['start_time']) : '', + 'amount' => (float)$row['amount'], + 'pay_status' => $row['pay_status'], + 'status' => $row['consult_status'], + 'status_text' => isset($statusText[$row['consult_status']]) ? $statusText[$row['consult_status']] : $row['consult_status'], + ]; + }, $rows); + } +} diff --git a/server/application/api/controller/Content.php b/server/application/api/controller/Content.php index 9b26698..4e12eb8 100644 --- a/server/application/api/controller/Content.php +++ b/server/application/api/controller/Content.php @@ -3,12 +3,12 @@ namespace app\api\controller; use app\common\controller\Api; +use app\common\service\ContentService; use app\common\service\CycleService; -use app\common\service\MemberService; use think\Db; /** - * 内容接口(M2 心语/科普 + M5 健康建议 + 冥想音频) + * 内容接口(心语 / 科普 / 知识 / 健康建议 / 冥想 / 课程图文) */ class Content extends Api { @@ -17,112 +17,44 @@ class Content extends Api /** * 内容列表 - * GET type=jijing|mood|knowledge|advice|meditation phase=menstrual access=free + * GET type=jijing|mood|knowledge|advice|meditation|care|card|conflict|firstaid|guide|course|activity|emotion + * phase= category_id= part=relation|parenting page= limit= */ public function index() { - $type = $this->request->param('type', ''); $phase = $this->request->param('phase', ''); - $categoryId = (int)$this->request->param('category_id', 0); - $page = max(1, (int)$this->request->param('page', 1)); - $limit = min(50, max(1, (int)$this->request->param('limit', 10))); - - // 未显式传阶段时,按当前周期阶段智能匹配 - if (!$phase) { + if (!$phase && !$this->request->param('type')) { + $current = CycleService::current($this->auth->id); + $phase = $current['phase'] ?: ''; + } elseif (!$phase) { + // 内容型模块默认按当前阶段优先 $current = CycleService::current($this->auth->id); $phase = $current['phase'] ?: ''; } - $query = Db::name('content') - ->where('status', 'normal') - ->where('verify', 'passed'); - - if ($type) { - $query->where('type', $type); - } - if ($categoryId) { - $query->where('category_id', $categoryId); - } - - $all = $query->order('weigh', 'desc')->select(); - - // 阶段匹配优先:先取命中当前阶段(含 all)的内容,过少时回退全量, - // 避免某些阶段(如排卵期)内容过少导致列表空置 - if ($phase) { - $matched = array_values(array_filter($all, function ($item) use ($phase) { - $phases = array_filter(explode(',', $item['phase'])); - return in_array('all', $phases) || in_array($phase, $phases); - })); - if (count($matched) >= 3 || count($matched) === count($all)) { - $all = $matched; - } else { - $rest = array_values(array_filter($all, function ($item) use ($matched) { - return !in_array($item['id'], array_column($matched, 'id')); - })); - $all = array_merge($matched, $rest); - } - } - - $total = count($all); - $list = array_slice($all, ($page - 1) * $limit, $limit); - - $member = MemberService::status($this->auth->id); - $list = array_map(function ($item) use ($member) { - return [ - 'id' => (int)$item['id'], - 'type' => $item['type'], - 'title' => $item['title'], - 'summary' => $item['summary'], - 'emoji' => $item['cover_emoji'], - 'media_type' => $item['media_type'], - 'duration' => (int)$item['duration'], - 'duration_text' => $item['duration'] ? floor($item['duration'] / 60) . ' 分钟' : '', - 'access' => $item['access'], - 'locked' => $item['access'] === 'member' && !$member['is_member'], - ]; - }, $list); - - $this->success('', [ - 'list' => $list, - 'total' => $total, - 'page' => $page, - 'limit' => $limit, - 'has_more' => $page * $limit < $total, - 'phase' => $phase, - 'category' => $this->categoryList($type), + $data = ContentService::lists($this->auth->id, [ + 'type' => $this->request->param('type', ''), + 'phase' => $phase, + 'category_id' => (int)$this->request->param('category_id', 0), + 'part' => $this->request->param('part', ''), + 'page' => (int)$this->request->param('page', 1), + 'limit' => (int)$this->request->param('limit', 10), ]); + + $data['category'] = $this->categoryList($this->request->param('type', '')); + $this->success('', $data); } /** * 内容详情 - * GET id=1 */ public function detail() { - $id = (int)$this->request->param('id', 0); - $item = Db::name('content')->where('id', $id)->where('status', 'normal')->find(); - if (!$item) { + $data = ContentService::detail($this->auth->id, $this->request->param('id', 0)); + if (!$data) { $this->error('内容不存在'); } - - $member = MemberService::status($this->auth->id); - $locked = $item['access'] === 'member' && !$member['is_member']; - - $this->success('', [ - 'id' => (int)$item['id'], - 'type' => $item['type'], - 'title' => $item['title'], - 'summary' => $item['summary'], - 'body' => $locked ? mb_substr($item['body'], 0, 80) . '…' : $item['body'], - 'emoji' => $item['cover_emoji'], - 'media_type' => $item['media_type'], - 'duration' => (int)$item['duration'], - 'access' => $item['access'], - 'locked' => $locked, - 'lock_tip' => $locked ? '该内容为会员专享,开通会员即可查看' : '', - 'disclaimer' => $item['type'] === 'advice' || $item['type'] === 'knowledge' - ? '以上内容仅供参考,不能替代医疗诊断。' : '', - ]); + $this->success('', $data); } /** @@ -135,8 +67,7 @@ class Content extends Api if ($type) { $query->where('type', $type); } - $list = $query->order('weigh', 'desc')->select(); - $this->success('', ['list' => $list]); + $this->success('', ['list' => $query->order('weigh', 'desc')->select()]); } protected function categoryList($type) @@ -144,12 +75,11 @@ class Content extends Api if (!$type) { return []; } - $list = Db::name('content_category') + return Db::name('content_category') ->where('type', $type) ->where('status', 'normal') ->order('weigh', 'desc') ->field('id,name') ->select(); - return $list; } } diff --git a/server/application/api/controller/Family.php b/server/application/api/controller/Family.php new file mode 100644 index 0000000..565e7cb --- /dev/null +++ b/server/application/api/controller/Family.php @@ -0,0 +1,338 @@ +auth->id; + $binds = Db::name('family_bind') + ->where('user_id', $userId) + ->where('status', 'normal') + ->order('id', 'desc') + ->select(); + + $this->success('', [ + 'binds' => array_map([$this, 'formatBind'], $binds), + 'max' => self::MAX_BIND, + 'can_invite' => count($binds) < self::MAX_BIND, + 'points' => $this->pointsData($userId), + 'scripts' => ContentService::lists($userId, ['type' => 'care', 'limit' => 3]), + 'care_today' => $this->careToday($userId), + 'member' => MemberService::status($userId), + 'script_locked' => !MemberService::can($userId, 'family.script.full'), + ]); + } + + /** + * 生成邀请(二维码/链接) + * POST relation=partner|parent|friend, member_name + */ + public function invite() + { + $userId = $this->auth->id; + $count = Db::name('family_bind') + ->where('user_id', $userId) + ->whereIn('status', ['pending', 'normal']) + ->count(); + if ($count >= self::MAX_BIND) { + $this->error('最多绑定 ' . self::MAX_BIND . ' 位家人'); + } + + $relation = $this->request->post('relation', 'partner'); + if (!in_array($relation, ['partner', 'parent', 'friend'], true)) { + $relation = 'partner'; + } + $code = strtoupper(Random::alnum(8)); + + $id = Db::name('family_bind')->insertGetId([ + 'user_id' => $userId, + 'member_name' => mb_substr((string)$this->request->post('member_name', ''), 0, 30), + 'relation' => $relation, + 'scope' => 'remind,care', + 'invite_code' => $code, + 'status' => 'pending', + 'createtime' => time(), + 'updatetime' => time(), + ]); + + $this->success('邀请已生成', [ + 'id' => (int)$id, + 'invite_code' => $code, + 'invite_text' => '邀请你成为我花期里的守护者,绑定码:' . $code, + 'expire_days' => 7, + ]); + } + + /** + * 确认绑定(家人端输入邀请码) + * POST invite_code + */ + public function confirm() + { + $userId = $this->auth->id; + $code = strtoupper(trim((string)$this->request->post('invite_code', ''))); + if (!$code) { + $this->error('请输入绑定码'); + } + $bind = Db::name('family_bind')->where('invite_code', $code)->find(); + if (!$bind) { + $this->error('绑定码不存在或已失效'); + } + if ((int)$bind['user_id'] === (int)$userId) { + $this->error('不能与自己绑定'); + } + if ($bind['status'] === 'normal') { + $this->error('该邀请已被使用'); + } + if ($bind['createtime'] < time() - 7 * 86400) { + $this->error('绑定码已过期,请让对方重新生成'); + } + + Db::name('family_bind')->where('id', $bind['id'])->update([ + 'member_user_id' => $userId, + 'status' => 'normal', + 'confirm_time' => time(), + 'updatetime' => time(), + ]); + + $this->success('绑定成功', ['bind_id' => (int)$bind['id']]); + } + + /** + * 解绑 + */ + public function remove() + { + $id = (int)$this->request->post('id', 0); + $row = Db::name('family_bind') + ->where('id', $id) + ->where(function ($query) { + $query->where('user_id', $this->auth->id)->whereOr('member_user_id', $this->auth->id); + }) + ->find(); + if (!$row) { + $this->error('绑定不存在'); + } + Db::name('family_bind')->where('id', $id)->update(['status' => 'removed', 'updatetime' => time()]); + $this->success('已解绑,对方将无法再看到你的提醒'); + } + + /** + * 话术库(暖心话术,完整库为会员权益) + */ + public function scripts() + { + $isMember = MemberService::can($this->auth->id, 'family.script.full'); + $data = ContentService::lists($this->auth->id, ['type' => 'care', 'limit' => $isMember ? 30 : 4]); + $data['locked'] = !$isMember; + $data['tip'] = $isMember ? '' : '开通会员可查看完整话术库'; + $this->success('', $data); + } + + /** + * 沟通空间:留言列表 + * GET bind_id + */ + public function messages() + { + $bindId = (int)$this->request->param('bind_id', 0); + $bind = $this->checkBind($bindId); + $list = Db::name('care_message') + ->where('bind_id', $bind['id']) + ->order('id', 'desc') + ->limit(50) + ->select(); + + $list = array_map(function ($row) { + return [ + 'id' => (int)$row['id'], + 'type' => $row['type'], + 'content' => $row['content'], + 'mine' => (int)$row['user_id'] === (int)$this->auth->id, + 'time_text' => date('m-d H:i', (int)$row['createtime']), + ]; + }, $list); + + $this->success('', ['bind' => $this->formatBind($bind), 'list' => array_reverse($list)]); + } + + /** + * 沟通空间:发送留言 + */ + public function messageSend() + { + $bindId = (int)$this->request->post('bind_id', 0); + $bind = $this->checkBind($bindId); + $content = mb_substr(trim((string)$this->request->post('content', '')), 0, 500); + if (!$content) { + $this->error('留言不能为空'); + } + $id = Db::name('care_message')->insertGetId([ + 'bind_id' => $bind['id'], + 'user_id' => $this->auth->id, + 'type' => 'text', + 'content' => $content, + 'createtime' => time(), + ]); + $this->success('已发送', ['id' => (int)$id]); + } + + /** + * 记录一次关怀行动(每日一次,+2 积分) + */ + public function careAction() + { + $userId = $this->auth->id; + if ($this->careToday($userId)) { + $this->success('今天已经记录过关怀啦', ['points' => $this->pointsData($userId)]); + } + Db::name('point_log')->insert([ + 'user_id' => $userId, + 'action' => 'care_daily', + 'point' => 2, + 'ref_id' => 0, + 'remark' => '今日关怀行动', + 'createtime' => time(), + ]); + $this->success('+2 爱心积分', ['points' => $this->pointsData($userId)]); + } + + /** + * 积分明细 + */ + public function points() + { + $userId = $this->auth->id; + $log = Db::name('point_log') + ->where('user_id', $userId) + ->order('id', 'desc') + ->limit(30) + ->select(); + $list = array_map(function ($row) { + return [ + 'id' => (int)$row['id'], + 'action' => $row['action'], + 'point' => (int)$row['point'], + 'remark' => $row['remark'], + 'date' => date('Y-m-d H:i', (int)$row['createtime']), + ]; + }, $log); + + $this->success('', ['points' => $this->pointsData($userId), 'list' => $list]); + } + + /** + * 家庭健康视图:谁在看护、当前阶段、共享待办 + */ + public function healthView() + { + $userId = $this->auth->id; + $cycle = CycleService::current($userId); + $binds = Db::name('family_bind') + ->where(function ($query) use ($userId) { + $query->where('user_id', $userId)->whereOr('member_user_id', $userId); + }) + ->where('status', 'normal') + ->select(); + + $tasks = Db::name('task') + ->where('user_id', $userId) + ->where('scope', 'family') + ->whereNull('deletetime') + ->where('done', 0) + ->select(); + + $this->success('', [ + 'cycle' => [ + 'has_data' => $cycle['has_data'], + 'phase_text' => $cycle['phase_text'], + 'day' => $cycle['day'], + 'next_start' => $cycle['next_start'], + 'days_to_next' => $cycle['days_to_next'], + ], + 'caregivers' => array_map([$this, 'formatBind'], $binds), + 'tasks' => array_map(function ($row) { + return ['id' => (int)$row['id'], 'title' => $row['title'], 'due_date' => $row['due_date']]; + }, $tasks), + 'privacy_note' => '家人仅可见阶段与提醒,看不到你的原始症状与情绪日记', + ]); + } + + // ---------------- 内部方法 ---------------- + + protected function checkBind($bindId) + { + $userId = $this->auth->id; + $bind = Db::name('family_bind') + ->where('id', $bindId) + ->where('status', 'normal') + ->where(function ($query) use ($userId) { + $query->where('user_id', $userId)->whereOr('member_user_id', $userId); + }) + ->find(); + if (!$bind) { + $this->error('绑定关系不存在或已解除'); + } + return $bind; + } + + protected function formatBind($row) + { + $relationText = ['partner' => '伴侣', 'parent' => '父母', 'friend' => '朋友']; + return [ + 'id' => (int)$row['id'], + 'name' => $row['member_name'] ?: '待确认', + 'relation' => $row['relation'], + 'relation_text' => isset($relationText[$row['relation']]) ? $relationText[$row['relation']] : '家人', + 'scope' => $row['scope'], + 'status' => $row['status'], + 'invite_code' => $row['status'] === 'pending' ? $row['invite_code'] : '', + 'confirmed' => $row['status'] === 'normal', + ]; + } + + protected function pointsData($userId) + { + $total = (int)Db::name('point_log')->where('user_id', $userId)->sum('point'); + $todayStart = strtotime(date('Y-m-d')); + $today = (int)Db::name('point_log')->where('user_id', $userId)->where('createtime', '>=', $todayStart)->sum('point'); + return [ + 'total' => $total, + 'today' => $today, + 'can_earn' => $this->careToday($userId) ? 0 : 2, + 'rules' => ['每日关怀行动 +2', '完成备孕任务 +2', '连续陪伴 7 天 +10'], + ]; + } + + protected function careToday($userId) + { + return Db::name('point_log') + ->where('user_id', $userId) + ->where('action', 'care_daily') + ->where('createtime', '>=', strtotime(date('Y-m-d'))) + ->count() > 0; + } +} diff --git a/server/application/api/controller/Health.php b/server/application/api/controller/Health.php new file mode 100644 index 0000000..2e78e09 --- /dev/null +++ b/server/application/api/controller/Health.php @@ -0,0 +1,107 @@ + 4, + 'sport' => 5, + 'sleep' => 6, + 'pain' => 7, + ]; + + /** + * 建议总览 + */ + public function index() + { + $userId = $this->auth->id; + $cycle = CycleService::current($userId); + $phase = $cycle['phase'] ?: 'all'; + + $groups = []; + foreach ($this->categoryMap as $key => $categoryId) { + $data = ContentService::lists($userId, [ + 'type' => 'advice', + 'category_id' => $categoryId, + 'phase' => $phase, + 'limit' => 3, + ]); + $groups[] = [ + 'key' => $key, + 'title' => $this->title($key), + 'icon' => $this->icon($key), + 'list' => $data['list'], + ]; + } + + $this->success('', [ + 'phase' => $phase, + 'phase_text' => $cycle['phase_text'], + 'has_data' => $cycle['has_data'], + 'day' => $cycle['day'], + 'groups' => $groups, + 'tips' => $this->phaseTips($phase), + 'disclaimer' => '以上内容仅供参考,不能替代医疗诊断。', + ]); + } + + /** + * 某一类的全部建议 + * GET type=diet|sport|sleep|pain + */ + public function detail() + { + $type = $this->request->param('type', 'diet'); + if (!isset($this->categoryMap[$type])) { + $this->error('类型不存在'); + } + $cycle = CycleService::current($this->auth->id); + $data = ContentService::lists($this->auth->id, [ + 'type' => 'advice', + 'category_id' => $this->categoryMap[$type], + 'phase' => $cycle['phase'] ?: 'all', + 'limit' => 20, + ]); + $data['title'] = $this->title($type); + $data['disclaimer'] = '以上内容仅供参考,不能替代医疗诊断。'; + $this->success('', $data); + } + + protected function title($key) + { + $map = ['diet' => '饮食建议', 'sport' => '运动建议', 'sleep' => '睡眠建议', 'pain' => '痛经缓解']; + return isset($map[$key]) ? $map[$key] : $key; + } + + protected function icon($key) + { + $map = ['diet' => '🍲', 'sport' => '🧘', 'sleep' => '🌙', 'pain' => '🌡']; + return isset($map[$key]) ? $map[$key] : '🌸'; + } + + protected function phaseTips($phase) + { + $map = [ + 'menstrual' => ['保暖优先', '补铁 + 温热饮食', '避免高强度运动'], + 'follicular' => ['精力回升', '适合加量训练', '多吃优质蛋白'], + 'ovulation' => ['易孕期', '注意私处清洁', '保持规律作息'], + 'luteal' => ['情绪易波动', '少糖多纤维', '优先保证睡眠'], + ]; + return isset($map[$phase]) ? $map[$phase] : ['记录后获得个性化建议']; + } +} diff --git a/server/application/api/controller/Home.php b/server/application/api/controller/Home.php index 06b5a7a..89af54b 100644 --- a/server/application/api/controller/Home.php +++ b/server/application/api/controller/Home.php @@ -167,6 +167,26 @@ class Home extends Api ]; } } + // 自定义提醒(吃药 / 记录 / 复诊等) + $custom = Db::name('reminder') + ->where('user_id', $this->auth->id) + ->where('enabled', 1) + ->whereNull('deletetime') + ->order('remind_time', 'asc') + ->select(); + $today = date('Y-m-d'); + foreach ($custom as $item) { + if ($item['repeat_rule'] === 'once' && $item['remind_date'] !== $today) { + continue; + } + $list[] = [ + 'type' => $item['type'] ?: 'custom', + 'icon' => '⏰', + 'title' => $item['title'], + 'desc' => substr($item['remind_time'], 0, 5) . ' 提醒', + ]; + } + return $list; } diff --git a/server/application/api/controller/Mood.php b/server/application/api/controller/Mood.php index 363705c..ceda5da 100644 --- a/server/application/api/controller/Mood.php +++ b/server/application/api/controller/Mood.php @@ -60,6 +60,40 @@ class Mood extends Api ]); } + /** + * 情绪急救包(M2) + * 返回 4 个即时可用的安抚工具,按当前情绪排序 + */ + public function firstaid() + { + $data = \app\common\service\ContentService::lists($this->auth->id, [ + 'type' => 'firstaid', + 'limit' => 10, + ]); + + // 按当前情绪优先排序(若今日有记录) + $today = Db::name('mood_log') + ->where('user_id', $this->auth->id) + ->where('log_date', date('Y-m-d')) + ->order('id', 'desc') + ->find(); + $mood = $today ? $today['mood'] : ''; + if ($mood) { + usort($data['list'], function ($a, $b) use ($mood) { + $aHit = strpos((string)$a['summary'] . (string)$a['title'], $mood) !== false ? 1 : 0; + $bHit = strpos((string)$b['summary'] . (string)$b['title'], $mood) !== false ? 1 : 0; + return $bHit - $aHit; + }); + } + + $this->success('', [ + 'list' => $data['list'], + 'today_mood' => $mood, + 'tip' => '情绪上头时,先照顾身体,再处理问题', + 'hotline' => ['name' => '心理援助热线', 'phone' => '12356'], + ]); + } + /** * 情绪列表 * GET limit=20 month=2026-11 diff --git a/server/application/api/controller/Parenting.php b/server/application/api/controller/Parenting.php new file mode 100644 index 0000000..242ded1 --- /dev/null +++ b/server/application/api/controller/Parenting.php @@ -0,0 +1,324 @@ +auth->id; + $baby = Db::name('baby')->where('user_id', $userId)->where('status', 'normal')->order('id', 'desc')->find(); + $monthAge = $baby ? $this->monthAge($baby) : null; + + $this->success('', [ + 'baby' => $this->formatBaby($baby), + 'month_age' => $monthAge, + 'activities' => ContentService::lists($userId, ['type' => 'activity', 'limit' => 6])['list'], + 'courses' => ['list' => $this->coursesData()], + 'co_tasks' => $this->coTasksData(), + 'emotions' => ContentService::lists($userId, ['type' => 'emotion', 'limit' => 4])['list'], + 'vaccines' => $this->vaccinePlan($baby), + 'growth' => $this->growthListData($baby), + 'assessments' => AssessmentService::lists('parenting', $userId), + ]); + } + + /** + * 宝宝档案 + */ + public function babyInfo() + { + $baby = Db::name('baby')->where('user_id', $this->auth->id)->where('status', 'normal')->order('id', 'desc')->find(); + $this->success('', ['baby' => $this->formatBaby($baby), 'month_age' => $baby ? $this->monthAge($baby) : null]); + } + + public function babySave() + { + $userId = $this->auth->id; + $data = [ + 'user_id' => $userId, + 'nickname' => mb_substr((string)$this->request->post('nickname', '宝宝'), 0, 30), + 'gender' => min(2, max(0, (int)$this->request->post('gender', 0))), + 'status' => 'normal', + ]; + $birthday = (string)$this->request->post('birthday', ''); + $dueDate = (string)$this->request->post('due_date', ''); + if ($birthday && strtotime($birthday)) { + $data['birthday'] = date('Y-m-d', strtotime($birthday)); + } + if ($dueDate && strtotime($dueDate)) { + $data['due_date'] = date('Y-m-d', strtotime($dueDate)); + } + + $exist = Db::name('baby')->where('user_id', $userId)->where('status', 'normal')->find(); + if ($exist) { + Db::name('baby')->where('id', $exist['id'])->update($data); + $id = $exist['id']; + } else { + $data['createtime'] = time(); + $id = Db::name('baby')->insertGetId($data); + } + + $baby = Db::name('baby')->where('id', $id)->find(); + $this->success('已保存', ['baby' => $this->formatBaby($baby), 'month_age' => $this->monthAge($baby)]); + } + + /** + * 成长记录 + */ + protected function growthListData($baby = null) + { + if (!$baby) { + $baby = Db::name('baby')->where('user_id', $this->auth->id)->where('status', 'normal')->order('id', 'desc')->find(); + } + if (!$baby) { + return []; + } + $rows = Db::name('growth_record') + ->where('baby_id', $baby['id']) + ->order('record_date', 'desc') + ->limit(30) + ->select(); + + return array_map(function ($row) { + return [ + 'id' => (int)$row['id'], + 'record_date' => $row['record_date'], + 'height' => $row['height'] !== null ? (float)$row['height'] : null, + 'weight' => $row['weight'] !== null ? (float)$row['weight'] : null, + 'milestone' => $row['milestone'], + 'note' => $row['note'], + ]; + }, $rows); + } + + public function growthSave() + { + $userId = $this->auth->id; + $baby = Db::name('baby')->where('user_id', $userId)->where('status', 'normal')->order('id', 'desc')->find(); + if (!$baby) { + $this->error('请先创建宝宝档案'); + } + $date = (string)$this->request->post('record_date', date('Y-m-d')); + if (!strtotime($date)) { + $this->error('日期格式不正确'); + } + $height = $this->request->post('height', ''); + $weight = $this->request->post('weight', ''); + + Db::name('growth_record')->insert([ + 'user_id' => $userId, + 'baby_id' => $baby['id'], + 'record_date' => $date, + 'height' => is_numeric($height) ? round((float)$height, 1) : null, + 'weight' => is_numeric($weight) ? round((float)$weight, 2) : null, + 'milestone' => mb_substr((string)$this->request->post('milestone', ''), 0, 100), + 'note' => mb_substr((string)$this->request->post('note', ''), 0, 300), + 'createtime' => time(), + ]); + + $this->success('已记录', ['list' => $this->growthListData($baby)]); + } + + /** + * 亲子活动(按月龄匹配) + */ + public function activities() + { + $userId = $this->auth->id; + $baby = Db::name('baby')->where('user_id', $userId)->where('status', 'normal')->order('id', 'desc')->find(); + $monthAge = $baby ? $this->monthAge($baby) : null; + + $data = ContentService::lists($userId, ['type' => 'activity', 'limit' => 30]); + if ($monthAge !== null) { + $matched = array_values(array_filter($data['list'], function ($item) use ($monthAge) { + $extra = $item['extra'] ?: []; + $from = isset($extra['month_from']) ? (int)$extra['month_from'] : 0; + $to = isset($extra['month_to']) ? (int)$extra['month_to'] : 999; + return $monthAge >= $from && $monthAge <= $to; + })); + if ($matched) { + $data['list'] = $matched; + } + $data['matched_by_age'] = count($matched) > 0; + } + $data['month_age'] = $monthAge; + $this->success('', $data); + } + + /** + * 课程 + */ + public function courses() + { + $list = $this->coursesData(); + $this->success('', ['list' => $list, 'total' => count($list)]); + } + + protected function coursesData() + { + $data = ContentService::lists($this->auth->id, ['type' => 'course', 'part' => 'parenting', 'limit' => 30]); + return $data['list']; + } + + /** + * 共育任务 + */ + public function coTasks() + { + $this->success('', ['list' => $this->coTasksData()]); + } + + protected function coTasksData() + { + $rows = Db::name('task') + ->where('user_id', $this->auth->id) + ->where('scope', 'parenting') + ->whereNull('deletetime') + ->order('done asc, id desc') + ->select(); + return array_map(function ($row) { + return [ + 'id' => (int)$row['id'], + 'title' => $row['title'], + 'category' => $row['category'], + 'done' => (int)$row['done'], + 'share_partner' => (int)$row['share_partner'], + ]; + }, $rows); + } + + public function coTaskSave() + { + $userId = $this->auth->id; + $title = mb_substr(trim((string)$this->request->post('title', '')), 0, 80); + if (!$title) { + $this->error('请填写任务内容'); + } + $id = Db::name('task')->insertGetId([ + 'user_id' => $userId, + 'scope' => 'parenting', + 'title' => $title, + 'category' => $this->request->post('category', 'care'), + 'share_partner' => 1, + 'createtime' => time(), + 'updatetime' => time(), + ]); + $this->success('已添加', ['id' => (int)$id, 'list' => $this->coTasksData()]); + } + + public function coTaskDone() + { + $id = (int)$this->request->post('id', 0); + $row = Db::name('task') + ->where('id', $id) + ->where('user_id', $this->auth->id) + ->where('scope', 'parenting') + ->find(); + if (!$row) { + $this->error('任务不存在'); + } + $done = $row['done'] ? 0 : 1; + Db::name('task')->where('id', $id)->update([ + 'done' => $done, 'done_time' => $done ? time() : null, 'updatetime' => time(), + ]); + $this->success($done ? '已完成' : '已取消', ['done' => $done, 'list' => $this->coTasksData()]); + } + + /** + * 育儿情绪 + */ + public function emotions() + { + $this->success('', ContentService::lists($this->auth->id, ['type' => 'emotion', 'limit' => 30])); + } + + /** + * 疫苗与儿保计划(按宝宝生日推算) + */ + public function vaccines() + { + $baby = Db::name('baby')->where('user_id', $this->auth->id)->where('status', 'normal')->order('id', 'desc')->find(); + $this->success('', ['list' => $this->vaccinePlan($baby), 'baby' => $this->formatBaby($baby)]); + } + + // ---------------- 内部方法 ---------------- + + protected function formatBaby($baby) + { + if (!$baby) { + return null; + } + return [ + 'id' => (int)$baby['id'], + 'nickname' => $baby['nickname'], + 'gender' => (int)$baby['gender'], + 'birthday' => $baby['birthday'], + 'due_date' => $baby['due_date'], + 'is_pregnant' => empty($baby['birthday']) && !empty($baby['due_date']), + ]; + } + + /** + * 月龄(孕期返回负数:距离预产期天数用于展示) + */ + protected function monthAge($baby) + { + if (!$baby) { + return null; + } + if (!empty($baby['birthday'])) { + $birth = strtotime($baby['birthday']); + $now = strtotime(date('Y-m-d')); + if ($now < $birth) { + return 0; + } + return (int)floor(($now - $birth) / (30.44 * 86400)); + } + if (!empty($baby['due_date'])) { + $days = (int)ceil((strtotime($baby['due_date']) - strtotime(date('Y-m-d'))) / 86400); + return -max(1, $days); + } + return null; + } + + protected function vaccinePlan($baby) + { + $list = Db::name('vaccine')->order('weigh', 'desc')->select(); + $birthday = $baby && !empty($baby['birthday']) ? strtotime($baby['birthday']) : null; + $today = strtotime(date('Y-m-d')); + + $result = []; + foreach ($list as $item) { + $dueDate = $birthday ? date('Y-m-d', strtotime('+' . (int)$item['month_from'] . ' month', $birthday)) : null; + $days = $dueDate ? (int)ceil((strtotime($dueDate) - $today) / 86400) : null; + $result[] = [ + 'id' => (int)$item['id'], + 'name' => $item['name'], + 'type' => $item['type'], + 'month_from' => (int)$item['month_from'], + 'note' => $item['note'], + 'due_date' => $dueDate, + 'days_left' => $days, + 'status' => $days === null ? 'unknown' : ($days < 0 ? 'overdue' : ($days <= 30 ? 'upcoming' : 'later')), + ]; + } + return $result; + } +} diff --git a/server/application/api/controller/Prepare.php b/server/application/api/controller/Prepare.php new file mode 100644 index 0000000..f7b9d76 --- /dev/null +++ b/server/application/api/controller/Prepare.php @@ -0,0 +1,435 @@ +auth->id; + $cycle = CycleService::current($userId); + $member = MemberService::status($userId); + + $bbt = $this->bbtListData($userId, 14); + $lh = Db::name('lh_test') + ->where('user_id', $userId) + ->order('log_date', 'desc') + ->limit(10) + ->select(); + + $tasks = Db::name('task') + ->where('user_id', $userId) + ->where('scope', 'prepare') + ->whereNull('deletetime') + ->order('done asc, id desc') + ->limit(10) + ->select(); + + $ovulation = $cycle['ovulation'] ?: null; + $daysToOvulation = null; + if ($ovulation) { + $daysToOvulation = (int)round((strtotime($ovulation) - strtotime(date('Y-m-d'))) / 86400); + } + + $this->success('', [ + 'cycle' => $cycle, + 'ovulation' => $ovulation, + 'fertile' => $cycle['has_data'] ? [$cycle['fertile_start'], $cycle['fertile_end']] : [], + 'days_to_ovulation' => $daysToOvulation, + 'predict' => CycleService::predict($userId, 3), + 'bbt' => $bbt, + 'lh' => array_map([$this, 'formatLh'], $lh), + 'lh_quota' => $this->quotaInfo($userId), + 'tasks' => array_map([$this, 'formatTask'], $tasks), + 'member' => $member, + 'plan_locked' => !MemberService::can($userId, 'prepare.plan'), + 'intercourse_locked' => !MemberService::can($userId, 'prepare.intercourse'), + ]); + } + + /** + * 基础体温:保存 + * POST log_date temperature measure_time + */ + public function bbtSave() + { + $userId = $this->auth->id; + $logDate = $this->request->post('log_date', date('Y-m-d')); + $temperature = (float)$this->request->post('temperature', 0); + if (!strtotime($logDate)) { + $this->error('日期格式不正确'); + } + if ($temperature < 34 || $temperature > 42) { + $this->error('体温需在 34.0 - 42.0 ℃ 之间'); + } + + $data = [ + 'user_id' => $userId, + 'log_date' => $logDate, + 'temperature' => round($temperature, 2), + 'measure_time' => (string)$this->request->post('measure_time', ''), + 'device' => (string)$this->request->post('device', 'manual'), + 'createtime' => time(), + ]; + + $exist = Db::name('bbt_record')->where('user_id', $userId)->where('log_date', $logDate)->find(); + if ($exist) { + Db::name('bbt_record')->where('id', $exist['id'])->update($data); + } else { + Db::name('bbt_record')->insert($data); + } + + $this->success('已记录', ['bbt' => $this->bbtListData($userId, 14)]); + } + + /** + * 基础体温曲线 + * GET days=14 + */ + public function bbtList() + { + $days = (int)$this->request->param('days', 14); + $days = in_array($days, [7, 14, 30]) ? $days : 14; + $this->success('', $this->bbtListData($this->auth->id, $days)); + } + + /** + * 试纸识别 + * POST test_type=lh|hcg, log_date, image, level=0-4 + * level:肉眼等级(0 极浅 / 1 弱阳 / 2 阳性 / 3 强阳 / 4 未测),用于规则识别 + */ + public function lhtest() + { + $userId = $this->auth->id; + $testType = $this->request->post('test_type', 'lh') === 'hcg' ? 'hcg' : 'lh'; + $logDate = $this->request->post('log_date', date('Y-m-d')); + $image = (string)$this->request->post('image', ''); + $level = (int)$this->request->post('level', 2); + + if (!strtotime($logDate)) { + $this->error('日期格式不正确'); + } + + $quota = $this->quotaInfo($userId); + if (!$quota['can_use']) { + $this->error('本月免费识别次数已用完,开通会员可继续使用'); + } + + $recognized = $this->recognize($level, $testType); + $isFreeQuota = $quota['is_free'] ? 1 : 0; + + $id = Db::name('lh_test')->insertGetId([ + 'user_id' => $userId, + 'test_type' => $testType, + 'log_date' => $logDate, + 'image' => mb_substr($image, 0, 255), + 'result' => $recognized['result'], + 'confidence' => $recognized['confidence'], + 'algo' => $recognized['algo'], + 'is_free_quota' => $isFreeQuota, + 'createtime' => time(), + ]); + + // 强弱转强的趋势判断 + $recent = Db::name('lh_test') + ->where('user_id', $userId) + ->where('test_type', $testType) + ->order('id', 'desc') + ->limit(7) + ->select(); + + $trend = []; + foreach (array_reverse($recent) as $row) { + $trend[] = [ + 'date' => $row['log_date'], + 'result' => $row['result'], + 'label' => $this->resultLabel($row['result']), + ]; + } + + $this->success('识别完成', [ + 'id' => (int)$id, + 'result' => $recognized['result'], + 'result_text' => $this->resultLabel($recognized['result']), + 'confidence' => $recognized['confidence'], + 'algo' => $recognized['algo'], + 'advice' => $recognized['advice'], + 'trend' => $trend, + 'quota' => $this->quotaInfo($userId), + 'disclaimer' => '识别结果仅供参考,请以说明书与医生判断为准。', + ]); + } + + /** + * 试纸记录列表 + */ + public function lhtestList() + { + $list = Db::name('lh_test') + ->where('user_id', $this->auth->id) + ->order('log_date', 'desc') + ->limit(30) + ->select(); + $this->success('', [ + 'list' => array_map([$this, 'formatLh'], $list), + 'quota' => $this->quotaInfo($this->auth->id), + ]); + } + + /** + * 备孕任务:列表 + */ + public function taskList() + { + $this->success('', ['list' => $this->tasks('prepare')]); + } + + /** + * 备孕任务:新增 / 修改 + * POST id, title, category, due_date, share_partner + */ + public function taskSave() + { + $userId = $this->auth->id; + $id = (int)$this->request->post('id', 0); + $title = mb_substr(trim((string)$this->request->post('title', '')), 0, 80); + if (!$title) { + $this->error('请填写任务内容'); + } + $dueDate = $this->request->post('due_date', ''); + $data = [ + 'user_id' => $userId, + 'scope' => $this->request->post('scope', 'prepare'), + 'title' => $title, + 'category' => $this->request->post('category', 'check'), + 'due_date' => $dueDate && strtotime($dueDate) ? $dueDate : null, + 'share_partner' => (int)$this->request->post('share_partner', 0), + 'updatetime' => time(), + ]; + + if ($id) { + $row = Db::name('task')->where('id', $id)->where('user_id', $userId)->find(); + if (!$row) { + $this->error('任务不存在'); + } + Db::name('task')->where('id', $id)->update($data); + } else { + $data['createtime'] = time(); + $id = Db::name('task')->insertGetId($data); + // 新增备孕任务赠送积分(M4 联动) + if ($data['scope'] === 'prepare') { + Db::name('point_log')->insert([ + 'user_id' => $userId, 'action' => 'prepare_task', 'point' => 2, + 'ref_id' => $id, 'remark' => '新建备孕任务', 'createtime' => time(), + ]); + } + } + + $this->success('已保存', ['id' => (int)$id, 'list' => $this->tasks($data['scope'])]); + } + + /** + * 备孕任务:完成 / 取消完成 + */ + public function taskDone() + { + $userId = $this->auth->id; + $id = (int)$this->request->post('id', 0); + $row = Db::name('task')->where('id', $id)->where('user_id', $userId)->find(); + if (!$row) { + $this->error('任务不存在'); + } + $done = $row['done'] ? 0 : 1; + Db::name('task')->where('id', $id)->update([ + 'done' => $done, 'done_time' => $done ? time() : null, 'updatetime' => time(), + ]); + + $this->success($done ? '已完成' : '已取消', ['done' => $done, 'list' => $this->tasks($row['scope'])]); + } + + /** + * 备孕任务:删除 + */ + public function taskRemove() + { + $userId = $this->auth->id; + $id = (int)$this->request->post('id', 0); + $row = Db::name('task')->where('id', $id)->where('user_id', $userId)->find(); + if (!$row) { + $this->error('任务不存在'); + } + Db::name('task')->where('id', $id)->update(['deletetime' => time()]); + $this->success('已删除', ['list' => $this->tasks($row['scope'])]); + } + + /** + * 同房指导(会员) + */ + public function guide() + { + if (!MemberService::can($this->auth->id, 'prepare.intercourse')) { + $this->success('', ['locked' => true, 'tip' => '同房指导为会员权益,开通后可见', 'list' => []]); + } + $data = ContentService::lists($this->auth->id, ['type' => 'guide', 'limit' => 10]); + $data['locked'] = false; + $this->success('', $data); + } + + // ---------------- 内部方法 ---------------- + + protected function tasks($scope) + { + $list = Db::name('task') + ->where('user_id', $this->auth->id) + ->where('scope', $scope) + ->whereNull('deletetime') + ->order('done asc, id desc') + ->select(); + return array_map([$this, 'formatTask'], $list); + } + + protected function formatTask($row) + { + return [ + 'id' => (int)$row['id'], + 'title' => $row['title'], + 'scope' => $row['scope'], + 'category' => $row['category'], + 'due_date' => $row['due_date'], + 'done' => (int)$row['done'], + 'share_partner' => (int)$row['share_partner'], + ]; + } + + protected function bbtListData($userId, $days) + { + $start = date('Y-m-d', strtotime('-' . ($days - 1) . ' day')); + $rows = Db::name('bbt_record') + ->where('user_id', $userId) + ->where('log_date', '>=', $start) + ->order('log_date', 'asc') + ->select(); + + $map = []; + foreach ($rows as $row) { + $map[$row['log_date']] = (float)$row['temperature']; + } + + $list = []; + $values = []; + for ($i = $days - 1; $i >= 0; $i--) { + $date = date('Y-m-d', strtotime('-' . $i . ' day')); + $value = isset($map[$date]) ? $map[$date] : null; + if ($value !== null) { + $values[] = $value; + } + $list[] = ['date' => $date, 'label' => date('n/j', strtotime($date)), 'temperature' => $value]; + } + + $avg = $values ? round(array_sum($values) / count($values), 2) : 0; + $biphasic = false; + $phaseNote = ''; + if (count($values) >= 6) { + $min = min($values); + $max = max($values); + $biphasic = ($max - $min) >= 0.3; + $phaseNote = $biphasic + ? '检测到双向体温(温差 ' . round($max - $min, 2) . ' ℃),提示可能已排卵' + : '暂未出现明显双向体温,继续在固定时间测量'; + } else { + $phaseNote = '至少连续记录 6 天才能判断双向体温'; + } + + return [ + 'days' => $days, + 'list' => $list, + 'avg' => $avg, + 'biphasic' => $biphasic, + 'note' => $phaseNote, + 'count' => count($values), + ]; + } + + /** + * 试纸识别(规则引擎版,预留 CNN 替换点) + */ + protected function recognize($level, $testType) + { + $level = min(4, max(0, (int)$level)); + $map = [ + 0 => ['result' => 'negative', 'confidence' => 88.5, 'advice' => '暂未出现阳性,建议明天同一时间复测。'], + 1 => ['result' => 'weak', 'confidence' => 90.2, 'advice' => '出现弱阳,建议每天同一时间连续检测。'], + 2 => ['result' => 'positive', 'confidence' => 93.6, 'advice' => '已出现阳性,未来 24-48 小时可能排卵。'], + 3 => ['result' => 'strong', 'confidence' => 95.1, 'advice' => '强阳提示 LH 峰值,建议今天与明天安排同房。'], + 4 => ['result' => 'unknown', 'confidence' => 60.0, 'advice' => '图片不够清晰,建议在自然光下重拍试纸。'], + ]; + $hit = $map[$level]; + if ($testType === 'hcg' && in_array($level, [2, 3], true)) { + $hit['advice'] = '早孕试纸出现阳性,建议到医院抽血确认。'; + } + $hit['algo'] = 'rule'; + return $hit; + } + + protected function resultLabel($result) + { + $map = ['negative' => '阴性', 'weak' => '弱阳', 'positive' => '阳性', 'strong' => '强阳', 'unknown' => '未识别']; + return isset($map[$result]) ? $map[$result] : $result; + } + + protected function formatLh($row) + { + return [ + 'id' => (int)$row['id'], + 'test_type' => $row['test_type'], + 'log_date' => $row['log_date'], + 'result' => $row['result'], + 'result_text' => $this->resultLabel($row['result']), + 'confidence' => (float)$row['confidence'], + 'algo' => $row['algo'], + ]; + } + + protected function quotaInfo($userId) + { + $member = MemberService::can($userId, 'lhtest.quota'); + $used = Db::name('lh_test') + ->where('user_id', $userId) + ->where('is_free_quota', 1) + ->where('log_date', '>=', date('Y-m-01')) + ->count(); + $limit = $member ? 50 : self::FREE_LH_QUOTA; + + return [ + 'is_member' => $member, + 'used' => $used, + 'limit' => $limit, + 'left' => max(0, $limit - $used), + 'is_free' => $used < self::FREE_LH_QUOTA, + 'can_use' => $used < $limit, + 'tip' => $member ? '会员每月 50 次识别额度' : '免费用户每月 ' . self::FREE_LH_QUOTA . ' 次', + ]; + } +} diff --git a/server/application/api/controller/Relation.php b/server/application/api/controller/Relation.php new file mode 100644 index 0000000..66415d5 --- /dev/null +++ b/server/application/api/controller/Relation.php @@ -0,0 +1,303 @@ +auth->id; + + $this->success('', [ + 'assessments' => AssessmentService::lists('relation', $userId), + 'cards' => ContentService::lists($userId, ['type' => 'card', 'limit' => 3])['list'], + 'conflicts' => ContentService::lists($userId, ['type' => 'conflict', 'limit' => 3])['list'], + 'courses' => ['list' => $this->coursesData()], + 'tasks' => $this->tasks(), + 'memories' => $this->memoryList(5), + 'stats' => $this->stats($userId), + ]); + } + + /** + * 关系测评列表 / 详情 / 提交 + */ + public function assessments() + { + $this->success('', ['list' => AssessmentService::lists('relation', $this->auth->id)]); + } + + public function assessmentDetail() + { + $data = AssessmentService::detail($this->request->param('id', 0)); + if (!$data) { + $this->error('量表不存在'); + } + $this->success('', $data); + } + + public function assessmentSubmit() + { + $answers = $this->request->post('answers', ''); + $answers = is_array($answers) ? $answers : json_decode(htmlspecialchars_decode((string)$answers, ENT_QUOTES), true); + if (!is_array($answers)) { + $this->error('请完成全部题目'); + } + $result = AssessmentService::submit($this->auth->id, (int)$this->request->post('id', 0), $answers); + if (isset($result['error'])) { + $this->error($result['error']); + } + $this->success('测评完成', $result); + } + + /** + * 沟通引导卡 / 冲突工具 + */ + public function cards() + { + $this->success('', ContentService::lists($this->auth->id, ['type' => 'card', 'limit' => 30])); + } + + public function conflicts() + { + $this->success('', ContentService::lists($this->auth->id, ['type' => 'conflict', 'limit' => 30])); + } + + /** + * 关系课程列表 + 购买 + */ + public function courses() + { + $this->success('', [ + 'list' => $this->coursesData(), + 'total' => count($this->coursesData()), + ]); + } + + protected function coursesData() + { + $data = ContentService::lists($this->auth->id, ['type' => 'course', 'part' => 'relation', 'limit' => 30]); + return $data['list']; + } + + public function courseBuy() + { + $userId = $this->auth->id; + $contentId = (int)$this->request->post('id', 0); + $course = Db::name('content')->where('id', $contentId)->where('type', 'course')->find(); + if (!$course) { + $this->error('课程不存在'); + } + if (ContentService::hasPurchased($userId, $contentId)) { + $this->success('已购买', ['purchased' => true]); + } + + $orderNo = 'HC' . date('YmdHis') . Random::numeric(4); + $id = Db::name('course_order')->insertGetId([ + 'order_no' => $orderNo, + 'user_id' => $userId, + 'content_id' => $contentId, + 'amount' => 0, + 'pay_status' => 'unpaid', + 'createtime' => time(), + ]); + + $this->success('订单已创建', [ + 'order_id' => (int)$id, + 'order_no' => $orderNo, + 'amount' => (float)0, + 'pay_hint' => '课程支付通道待接入,可联系客服开通', + 'purchased' => false, + ]); + } + + /** + * 双人任务 + */ + public function taskList() + { + $this->success('', ['list' => $this->tasks()]); + } + + public function taskSave() + { + $userId = $this->auth->id; + $id = (int)$this->request->post('id', 0); + $title = mb_substr(trim((string)$this->request->post('title', '')), 0, 80); + if (!$title) { + $this->error('请填写任务内容'); + } + $data = [ + 'user_id' => $userId, + 'scope' => 'relation', + 'title' => $title, + 'category' => $this->request->post('category', 'daily'), + 'share_partner' => 1, + 'updatetime' => time(), + ]; + if ($id) { + $row = Db::name('task')->where('id', $id)->where('user_id', $userId)->find(); + if (!$row) { + $this->error('任务不存在'); + } + Db::name('task')->where('id', $id)->update($data); + } else { + $data['createtime'] = time(); + $id = Db::name('task')->insertGetId($data); + } + $this->success('已保存', ['id' => (int)$id, 'list' => $this->tasks()]); + } + + public function taskDone() + { + $userId = $this->auth->id; + $id = (int)$this->request->post('id', 0); + $row = Db::name('task')->where('id', $id)->where('user_id', $userId)->where('scope', 'relation')->find(); + if (!$row) { + $this->error('任务不存在'); + } + $done = $row['done'] ? 0 : 1; + Db::name('task')->where('id', $id)->update([ + 'done' => $done, 'done_time' => $done ? time() : null, 'updatetime' => time(), + ]); + // 完成双人任务,双人共同记录进「爱的记忆」 + if ($done) { + Db::name('memory')->insert([ + 'user_id' => $userId, + 'bind_id' => 0, + 'title' => '一起完成:' . $row['title'], + 'memory_date' => date('Y-m-d'), + 'type' => 'daily', + 'content' => '', + 'remind' => 0, + 'createtime' => time(), + ]); + } + $this->success($done ? '已完成' : '已取消', ['done' => $done, 'list' => $this->tasks()]); + } + + /** + * 纪念与回顾 + */ + public function memories() + { + $this->success('', ['list' => $this->memoryList(50)]); + } + + public function memorySave() + { + $userId = $this->auth->id; + $title = mb_substr(trim((string)$this->request->post('title', '')), 0, 60); + $date = (string)$this->request->post('memory_date', date('Y-m-d')); + if (!$title) { + $this->error('请填写纪念日名称'); + } + if (!strtotime($date)) { + $this->error('日期格式不正确'); + } + $id = Db::name('memory')->insertGetId([ + 'user_id' => $userId, + 'title' => $title, + 'memory_date' => $date, + 'type' => $this->request->post('type', 'anniversary'), + 'content' => mb_substr((string)$this->request->post('content', ''), 0, 500), + 'remind' => (int)$this->request->post('remind', 1), + 'createtime' => time(), + ]); + $this->success('已记录', ['id' => (int)$id, 'list' => $this->memoryList(50)]); + } + + public function memoryRemove() + { + $id = (int)$this->request->post('id', 0); + $row = Db::name('memory')->where('id', $id)->where('user_id', $this->auth->id)->find(); + if (!$row) { + $this->error('记录不存在'); + } + Db::name('memory')->where('id', $id)->update(['deletetime' => time()]); + $this->success('已删除', ['list' => $this->memoryList(50)]); + } + + // ---------------- 内部方法 ---------------- + + protected function tasks() + { + $rows = Db::name('task') + ->where('user_id', $this->auth->id) + ->where('scope', 'relation') + ->whereNull('deletetime') + ->order('done asc, id desc') + ->select(); + return array_map(function ($row) { + return [ + 'id' => (int)$row['id'], + 'title' => $row['title'], + 'category' => $row['category'], + 'done' => (int)$row['done'], + ]; + }, $rows); + } + + protected function memoryList($limit) + { + $rows = Db::name('memory') + ->where('user_id', $this->auth->id) + ->whereNull('deletetime') + ->order('memory_date', 'desc') + ->limit($limit) + ->select(); + + return array_map(function ($row) { + $days = (int)floor((strtotime(date('Y-m-d')) - strtotime($row['memory_date'])) / 86400); + $nextDays = null; + if ($row['type'] === 'anniversary') { + $nextTs = strtotime(date('Y') . '-' . date('m-d', strtotime($row['memory_date']))); + if ($nextTs < strtotime(date('Y-m-d'))) { + $nextTs = strtotime('+1 year', $nextTs); + } + $nextDays = (int)ceil(($nextTs - strtotime(date('Y-m-d'))) / 86400); + } + return [ + 'id' => (int)$row['id'], + 'title' => $row['title'], + 'memory_date' => $row['memory_date'], + 'type' => $row['type'], + 'content' => $row['content'], + 'days_since' => $days, + 'days_to_next' => $nextDays, + ]; + }, $rows); + } + + protected function stats($userId) + { + return [ + 'task_total' => Db::name('task')->where('user_id', $userId)->where('scope', 'relation')->whereNull('deletetime')->count(), + 'task_done' => Db::name('task')->where('user_id', $userId)->where('scope', 'relation')->where('done', 1)->whereNull('deletetime')->count(), + 'memory_total' => Db::name('memory')->where('user_id', $userId)->whereNull('deletetime')->count(), + 'test_count' => Db::name('assessment_record') + ->where('user_id', $userId) + ->whereIn('assessment_id', function ($query) { + $query->name('assessment')->where('scope', 'relation')->field('id'); + }) + ->count(), + ]; + } +} diff --git a/server/application/api/controller/Setting.php b/server/application/api/controller/Setting.php index 7d5bc21..5fd68c3 100644 --- a/server/application/api/controller/Setting.php +++ b/server/application/api/controller/Setting.php @@ -126,4 +126,212 @@ class Setting extends Api $arr = is_array($json) ? $json : json_decode(htmlspecialchars_decode((string)$json, ENT_QUOTES), true); return is_array($arr) ? $arr : null; } + + /** + * 自定义提醒列表(M1/M6 智能提醒) + */ + public function reminderList() + { + $rows = \think\Db::name('reminder') + ->where('user_id', $this->auth->id) + ->whereNull('deletetime') + ->order('enabled desc, remind_time asc') + ->select(); + $this->success('', ['list' => array_map([$this, 'formatReminder'], $rows)]); + } + + /** + * 新增 / 修改提醒 + * POST id, title, type, remind_time, repeat_rule, remind_date, enabled + */ + public function reminderSave() + { + $userId = $this->auth->id; + $id = (int)$this->request->post('id', 0); + $title = mb_substr(trim((string)$this->request->post('title', '')), 0, 60); + if (!$title) { + $this->error('请填写提醒内容'); + } + $time = (string)$this->request->post('remind_time', '21:00'); + if (!preg_match('/^\d{2}:\d{2}$/', $time)) { + $this->error('提醒时间格式不正确'); + } + $repeat = $this->request->post('repeat_rule', 'daily'); + if (!in_array($repeat, ['daily', 'once', 'weekly'], true)) { + $repeat = 'daily'; + } + $date = (string)$this->request->post('remind_date', ''); + $data = [ + 'user_id' => $userId, + 'title' => $title, + 'type' => $this->request->post('type', 'custom'), + 'remind_time' => $time, + 'repeat_rule' => $repeat, + 'remind_date' => $date && strtotime($date) ? $date : null, + 'enabled' => (int)$this->request->post('enabled', 1), + 'updatetime' => time(), + ]; + if ($id) { + $row = \think\Db::name('reminder')->where('id', $id)->where('user_id', $userId)->find(); + if (!$row) { + $this->error('提醒不存在'); + } + \think\Db::name('reminder')->where('id', $id)->update($data); + } else { + $data['createtime'] = time(); + $id = \think\Db::name('reminder')->insertGetId($data); + } + $this->success('已保存', ['id' => (int)$id]); + } + + /** + * 删除提醒 + */ + public function reminderRemove() + { + $id = (int)$this->request->post('id', 0); + $row = \think\Db::name('reminder')->where('id', $id)->where('user_id', $this->auth->id)->find(); + if (!$row) { + $this->error('提醒不存在'); + } + \think\Db::name('reminder')->where('id', $id)->update(['deletetime' => time()]); + $this->success('已删除'); + } + + /** + * 数据备份:创建快照(本地/云端同步的前提能力) + */ + public function backupCreate() + { + $userId = $this->auth->id; + $payload = $this->collectData($userId); + $json = json_encode($payload, JSON_UNESCAPED_UNICODE); + $id = \think\Db::name('user_backup')->insertGetId([ + 'user_id' => $userId, + 'name' => '备份 ' . date('Y-m-d H:i'), + 'size' => strlen($json), + 'payload' => $json, + 'createtime' => time(), + ]); + + // 仅保留最近 5 份,避免存储膨胀 + $ids = \think\Db::name('user_backup') + ->where('user_id', $userId) + ->order('id', 'desc') + ->limit(100) + ->column('id'); + if (count($ids) > 5) { + \think\Db::name('user_backup')->whereIn('id', array_slice($ids, 5))->delete(); + } + + $this->success('备份完成', [ + 'id' => (int)$id, + 'size' => strlen($json), + 'counts' => $payload['counts'], + ]); + } + + /** + * 备份列表 + */ + public function backupList() + { + $rows = \think\Db::name('user_backup') + ->where('user_id', $this->auth->id) + ->order('id', 'desc') + ->field('id,name,size,createtime') + ->select(); + $list = array_map(function ($row) { + return [ + 'id' => (int)$row['id'], + 'name' => $row['name'], + 'size' => (int)$row['size'], + 'size_text' => round($row['size'] / 1024, 1) . ' KB', + 'date' => date('Y-m-d H:i', (int)$row['createtime']), + ]; + }, $rows); + $this->success('', ['list' => $list]); + } + + /** + * 从备份恢复(仅恢复本人数据,先清理同范围记录) + */ + public function backupRestore() + { + $userId = $this->auth->id; + $id = (int)$this->request->post('id', 0); + $row = \think\Db::name('user_backup')->where('id', $id)->where('user_id', $userId)->find(); + if (!$row) { + $this->error('备份不存在'); + } + $payload = json_decode($row['payload'], true); + if (!is_array($payload)) { + $this->error('备份内容损坏'); + } + + $restored = []; + $map = [ + 'cyle' => 'cycle', + ]; + $this->restoreTable('cycle', $payload['cycle'] ?? [], $userId, $restored); + $this->restoreTable('cycle_log', $payload['cycle_log'] ?? [], $userId, $restored); + $this->restoreTable('mood_log', $payload['mood_log'] ?? [], $userId, $restored); + $this->restoreTable('bbt_record', $payload['bbt_record'] ?? [], $userId, $restored); + $this->restoreTable('task', $payload['task'] ?? [], $userId, $restored); + $this->restoreTable('memory', $payload['memory'] ?? [], $userId, $restored); + + $this->success('恢复完成', ['restored' => $restored]); + } + + protected function collectData($userId) + { + $data = [ + 'cycle' => \think\Db::name('cycle')->where('user_id', $userId)->whereNull('deletetime')->select(), + 'cycle_log' => \think\Db::name('cycle_log')->where('user_id', $userId)->whereNull('deletetime')->select(), + 'mood_log' => \think\Db::name('mood_log')->where('user_id', $userId)->whereNull('deletetime')->select(), + 'bbt_record' => \think\Db::name('bbt_record')->where('user_id', $userId)->select(), + 'task' => \think\Db::name('task')->where('user_id', $userId)->whereNull('deletetime')->select(), + 'memory' => \think\Db::name('memory')->where('user_id', $userId)->whereNull('deletetime')->select(), + 'reminder' => \think\Db::name('reminder')->where('user_id', $userId)->whereNull('deletetime')->select(), + 'setting' => \think\Db::name('user_setting')->where('user_id', $userId)->find(), + ]; + $data['counts'] = [ + 'cycle' => count($data['cycle']), + 'cycle_log' => count($data['cycle_log']), + 'mood_log' => count($data['mood_log']), + 'bbt' => count($data['bbt_record']), + 'task' => count($data['task']), + 'memory' => count($data['memory']), + ]; + $data['version'] = 'v1'; + $data['created'] = date('Y-m-d H:i:s'); + return $data; + } + + protected function restoreTable($table, $rows, $userId, &$restored) + { + if (!is_array($rows)) { + return; + } + \think\Db::name($table)->where('user_id', $userId)->delete(); + foreach ($rows as $row) { + unset($row['id']); + $row['user_id'] = $userId; + \think\Db::name($table)->insert($row); + } + $restored[$table] = count($rows); + } + + protected function formatReminder($row) + { + return [ + 'id' => (int)$row['id'], + 'title' => $row['title'], + 'type' => $row['type'], + 'remind_time' => $row['remind_time'], + 'repeat_rule' => $row['repeat_rule'], + 'remind_date' => $row['remind_date'], + 'enabled' => (int)$row['enabled'], + ]; + } } diff --git a/server/application/common/service/AssessmentService.php b/server/application/common/service/AssessmentService.php new file mode 100644 index 0000000..07301e4 --- /dev/null +++ b/server/application/common/service/AssessmentService.php @@ -0,0 +1,197 @@ + '请优先照顾当下的安全', + 'text' => '如果出现伤害自己或他人的念头,请立即联系身边的人陪伴,并拨打心理援助热线:12356(心理援助)或 120(急救)。', + 'hotlines' => [ + ['name' => '全国心理援助热线', 'phone' => '12356'], + ['name' => '北京心理危机研究与干预中心', 'phone' => '010-82951332'], + ], + 'action' => '如需专业帮助,可预约在线心理咨询', + ]; + } + + /** + * 量表列表 + */ + public static function lists($scope = '', $userId = 0) + { + $query = Db::name('assessment')->where('status', 'normal'); + if ($scope) { + $query->where('scope', $scope); + } + $list = $query->order('weigh', 'desc')->select(); + $member = $userId ? MemberService::status($userId) : ['is_member' => false]; + + $result = []; + foreach ($list as $item) { + $questions = json_decode($item['questions'], true) ?: []; + $last = $userId ? Db::name('assessment_record') + ->where('user_id', $userId) + ->where('assessment_id', $item['id']) + ->order('id', 'desc') + ->find() : null; + + $result[] = [ + 'id' => (int)$item['id'], + 'code' => $item['code'], + 'title' => $item['title'], + 'intro' => $item['intro'], + 'scope' => $item['scope'], + 'level' => $item['level'], + 'access' => $item['access'], + 'locked' => $item['access'] === 'member' && !$member['is_member'], + 'count' => count($questions), + 'last_score' => $last ? (float)$last['score'] : null, + 'last_result' => $last ? $last['result'] : '', + 'last_date' => $last ? date('Y-m-d', (int)$last['createtime']) : '', + ]; + } + return $result; + } + + /** + * 量表详情(题目与选项) + */ + public static function detail($id) + { + $item = Db::name('assessment')->where('id', (int)$id)->where('status', 'normal')->find(); + if (!$item) { + return null; + } + return [ + 'id' => (int)$item['id'], + 'code' => $item['code'], + 'title' => $item['title'], + 'intro' => $item['intro'], + 'scope' => $item['scope'], + 'questions' => json_decode($item['questions'], true) ?: [], + 'options' => self::options(), + ]; + } + + public static function options() + { + return [ + ['text' => '没有', 'value' => 0], + ['text' => '偶尔', 'value' => 1], + ['text' => '有时', 'value' => 2], + ['text' => '经常', 'value' => 3], + ['text' => '总是', 'value' => 4], + ]; + } + + /** + * 提交作答 + * + * @param int $userId + * @param int $assessmentId + * @param array $answers 与题目顺序一致的 0-4 分值 + * @return array + */ + public static function submit($userId, $assessmentId, $answers) + { + $item = Db::name('assessment')->where('id', (int)$assessmentId)->where('status', 'normal')->find(); + if (!$item) { + return ['error' => '量表不存在']; + } + + $questions = json_decode($item['questions'], true) ?: []; + $answers = is_array($answers) ? array_values($answers) : []; + if (count($answers) !== count($questions)) { + return ['error' => '请完成全部题目']; + } + + $clean = []; + $score = 0; + foreach ($answers as $value) { + $v = min(4, max(0, (int)$value)); + $clean[] = $v; + $score += $v; + } + + $scoring = json_decode($item['scoring'], true) ?: []; + $levels = isset($scoring['levels']) ? $scoring['levels'] : []; + $max = isset($scoring['max']) ? (int)$scoring['max'] : count($questions) * 4; + + $resultKey = 'low'; + $resultText = ''; + foreach ($levels as $level) { + if ($score < (int)$level['lt']) { + $resultKey = $level['key']; + $resultText = $level['text']; + break; + } + } + if (!$resultText) { + $last = end($levels); + if ($last) { + $resultKey = $last['key']; + $resultText = $last['text']; + } + } + + // 危机识别:产后筛查最后一题(自伤念头)或总分达到满分 + $risk = 0; + $crisisQ = ['pdp' => 4]; + if (isset($crisisQ[$item['code']]) && isset($clean[$crisisQ[$item['code']]]) && $clean[$crisisQ[$item['code']]] >= 2) { + $risk = 1; + } + if ($score >= $max) { + $risk = 1; + } + + $advice = [ + '测评结果不是诊断,仅用于自我觉察。', + $resultText, + ]; + if ($item['code'] === 'pms') { + $advice[] = '建议连续记录 2-3 个周期的情绪与症状,观察规律。'; + } elseif ($item['code'] === 'prepare_anxiety') { + $advice[] = '可以和伴侣约定每天 15 分钟「不谈备孕」的时间。'; + } elseif ($item['code'] === 'relation') { + $advice[] = '试试本周安排一次不被打断的 30 分钟对话。'; + } elseif ($item['code'] === 'pdp') { + $advice[] = '把感受告诉家人,让他们参与照护;必要时就医评估。'; + } + + $id = Db::name('assessment_record')->insertGetId([ + 'user_id' => $userId, + 'assessment_id' => (int)$item['id'], + 'answers' => json_encode($clean), + 'score' => $score, + 'result' => $resultKey, + 'report' => $resultText, + 'risk_flag' => $risk, + 'createtime' => time(), + ]); + + return [ + 'id' => (int)$id, + 'title' => $item['title'], + 'score' => $score, + 'max' => $max, + 'result' => $resultKey, + 'result_text' => $resultText, + 'advice' => $advice, + 'risk_flag' => $risk, + 'crisis' => $risk ? self::crisis() : null, + 'disclaimer' => '测评结果仅供参考,不能替代专业诊断。', + ]; + } +} diff --git a/server/application/common/service/ContentService.php b/server/application/common/service/ContentService.php new file mode 100644 index 0000000..9224920 --- /dev/null +++ b/server/application/common/service/ContentService.php @@ -0,0 +1,159 @@ +where('status', 'normal') + ->where('verify', 'passed'); + + if ($type) { + $query->where('type', $type); + } + if ($categoryId) { + $query->where('category_id', $categoryId); + } + + $all = $query->order('weigh', 'desc')->select(); + + // 课程按 part(relation/parenting)过滤 + if ($part) { + $all = array_values(array_filter($all, function ($item) use ($part) { + $extra = json_decode($item['extra'], true) ?: []; + return isset($extra['part']) && $extra['part'] === $part; + })); + } + + // 阶段优先排序(不足则回退全量,避免列表空置) + if ($phase) { + $matched = []; + $rest = []; + foreach ($all as $item) { + $phases = array_filter(explode(',', $item['phase'])); + if (in_array('all', $phases) || in_array($phase, $phases)) { + $matched[] = $item; + } else { + $rest[] = $item; + } + } + $all = (count($matched) >= 3 || !$rest) ? $matched : array_merge($matched, $rest); + } + + $total = count($all); + $slice = array_slice($all, ($page - 1) * $limit, $limit); + $member = MemberService::status($userId); + $purchased = self::purchasedIds($userId); + + $list = []; + foreach ($slice as $item) { + $list[] = self::format($item, $member, false, $purchased); + } + + return [ + 'list' => $list, + 'total' => $total, + 'page' => $page, + 'limit' => $limit, + 'has_more' => $page * $limit < $total, + 'phase' => $phase, + ]; + } + + /** + * 内容详情 + */ + public static function detail($userId, $id) + { + $item = Db::name('content')->where('id', (int)$id)->where('status', 'normal')->find(); + if (!$item) { + return null; + } + $member = MemberService::status($userId); + return self::format($item, $member, true, self::purchasedIds($userId)); + } + + /** + * 用户已购买的课程 ID + */ + public static function purchasedIds($userId) + { + return Db::name('course_order') + ->where('user_id', $userId) + ->where('pay_status', 'paid') + ->column('content_id'); + } + + /** + * 是否已购买指定课程 + */ + public static function hasPurchased($userId, $contentId) + { + return Db::name('course_order') + ->where('user_id', $userId) + ->where('content_id', $contentId) + ->where('pay_status', 'paid') + ->count() > 0; + } + + /** + * 统一格式化(含会员锁态与免责声明) + */ + public static function format($item, $member, $withBody = false, $purchased = []) + { + $ownsCourse = in_array($item['id'], array_map('intval', (array)$purchased), true); + $locked = !$ownsCourse && in_array($item['access'], ['member', 'pay'], true) && !$member['is_member']; + if (in_array($item['access'], ['pay'], true) && !$ownsCourse && !$locked) { + // 单课付费(非会员)也需要购买 + $locked = true; + } + $extra = $item['extra'] ? json_decode($item['extra'], true) : []; + + $data = [ + 'id' => (int)$item['id'], + 'type' => $item['type'], + 'category_id' => (int)$item['category_id'], + 'title' => $item['title'], + 'summary' => $item['summary'], + 'emoji' => $item['cover_emoji'], + 'media_type' => $item['media_type'], + 'duration' => (int)$item['duration'], + 'duration_text' => $item['duration'] ? floor($item['duration'] / 60) . ' 分钟' : '', + 'access' => $item['access'], + 'locked' => $locked, + 'extra' => $extra, + 'lock_tip' => $locked ? '该内容为会员专享,开通会员即可查看' : '', + ]; + + if ($withBody) { + $data['body'] = $locked ? mb_substr($item['body'], 0, 80) . '…' : $item['body']; + $data['disclaimer'] = in_array($item['type'], ['advice', 'knowledge', 'emotion', 'guide'], true) + ? '以上内容仅供参考,不能替代医疗诊断。' : ''; + } + + return $data; + } +} diff --git a/server/db/03_modules.sql b/server/db/03_modules.sql new file mode 100644 index 0000000..078737e --- /dev/null +++ b/server/db/03_modules.sql @@ -0,0 +1,313 @@ +-- ============================================================ +-- 花期 APP · M3–M9 功能补齐(新增表结构) +-- MySQL 5.7 / utf8mb4 / 前缀 fa_ +-- 执行一次即可(含 fa_content 扩展列) +-- ============================================================ +SET NAMES utf8mb4; + +-- 内容库扩展:结构化附加信息(如疫苗月龄、课程节数、量表编码) +ALTER TABLE `fa_content` ADD COLUMN `extra` varchar(500) NOT NULL DEFAULT '' COMMENT '结构化附加信息 JSON' AFTER `mood_tag`; + +-- ---------------------------- +-- M1/M6 智能提醒(自定义提醒项) +-- ---------------------------- +DROP TABLE IF EXISTS `fa_reminder`; +CREATE TABLE `fa_reminder` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `user_id` int unsigned NOT NULL, + `title` varchar(60) NOT NULL, + `type` varchar(20) NOT NULL DEFAULT 'custom' COMMENT 'period/ovulation/record/medication/custom', + `remind_time` varchar(5) NOT NULL DEFAULT '21:00' COMMENT 'HH:mm', + `repeat_rule` varchar(20) NOT NULL DEFAULT 'daily' COMMENT 'daily/once/weekly', + `remind_date` date DEFAULT NULL COMMENT '一次性提醒日期', + `enabled` tinyint NOT NULL DEFAULT '1', + `createtime` bigint DEFAULT NULL, + `updatetime` bigint DEFAULT NULL, + `deletetime` bigint DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `idx_user` (`user_id`,`enabled`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='自定义提醒'; + +-- ---------------------------- +-- M3 基础体温 +-- ---------------------------- +DROP TABLE IF EXISTS `fa_bbt_record`; +CREATE TABLE `fa_bbt_record` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `user_id` int unsigned NOT NULL, + `log_date` date NOT NULL, + `temperature` decimal(4,2) NOT NULL COMMENT '℃', + `measure_time` varchar(5) NOT NULL DEFAULT '', + `device` varchar(20) NOT NULL DEFAULT 'manual' COMMENT 'manual/bluetooth', + `createtime` bigint DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uniq_user_date` (`user_id`,`log_date`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='基础体温记录'; + +-- ---------------------------- +-- M3 排卵/早孕试纸识别 +-- ---------------------------- +DROP TABLE IF EXISTS `fa_lh_test`; +CREATE TABLE `fa_lh_test` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `user_id` int unsigned NOT NULL, + `test_type` varchar(10) NOT NULL DEFAULT 'lh' COMMENT 'lh/hcg', + `log_date` date NOT NULL, + `image` varchar(255) NOT NULL DEFAULT '', + `result` varchar(20) NOT NULL DEFAULT '' COMMENT 'negative/weak/positive/strong/unknown', + `confidence` decimal(5,2) NOT NULL DEFAULT '0.00', + `algo` varchar(20) NOT NULL DEFAULT 'rule' COMMENT 'rule/cnn', + `is_free_quota` tinyint NOT NULL DEFAULT '0', + `createtime` bigint DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `idx_user_date` (`user_id`,`log_date`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='试纸识别记录'; + +-- ---------------------------- +-- 通用任务(备孕任务 / 双人任务 / 共育任务) +-- ---------------------------- +DROP TABLE IF EXISTS `fa_task`; +CREATE TABLE `fa_task` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `user_id` int unsigned NOT NULL, + `scope` varchar(20) NOT NULL DEFAULT 'prepare' COMMENT 'prepare/family/relation/parenting', + `title` varchar(80) NOT NULL, + `category` varchar(20) NOT NULL DEFAULT 'check' COMMENT 'folic/check/nutrition/partner/daily/care', + `due_date` date DEFAULT NULL, + `done` tinyint NOT NULL DEFAULT '0', + `done_time` bigint DEFAULT NULL, + `share_partner` tinyint NOT NULL DEFAULT '0', + `createtime` bigint DEFAULT NULL, + `updatetime` bigint DEFAULT NULL, + `deletetime` bigint DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `idx_user_scope` (`user_id`,`scope`,`done`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='任务(备孕/双人/共育)'; + +-- ---------------------------- +-- M4 家人绑定(≤5 人) +-- ---------------------------- +DROP TABLE IF EXISTS `fa_family_bind`; +CREATE TABLE `fa_family_bind` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `user_id` int unsigned NOT NULL COMMENT '被关怀方', + `member_user_id` int unsigned NOT NULL DEFAULT '0' COMMENT '家人用户ID', + `member_name` varchar(30) NOT NULL DEFAULT '', + `relation` varchar(20) NOT NULL DEFAULT 'partner' COMMENT 'partner/parent/friend', + `scope` varchar(120) NOT NULL DEFAULT 'remind,care' COMMENT '可见范围', + `invite_code` varchar(32) NOT NULL DEFAULT '', + `confirm_time` bigint DEFAULT NULL, + `status` varchar(20) NOT NULL DEFAULT 'pending' COMMENT 'pending/normal/removed', + `createtime` bigint DEFAULT NULL, + `updatetime` bigint DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uniq_invite` (`invite_code`), + KEY `idx_user` (`user_id`,`status`), + KEY `idx_member` (`member_user_id`,`status`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='家人绑定'; + +-- ---------------------------- +-- M4 私密沟通空间 +-- ---------------------------- +DROP TABLE IF EXISTS `fa_care_message`; +CREATE TABLE `fa_care_message` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `bind_id` int unsigned NOT NULL, + `user_id` int unsigned NOT NULL COMMENT '发送方', + `type` varchar(20) NOT NULL DEFAULT 'text' COMMENT 'text/voice/gift', + `content` varchar(1000) NOT NULL DEFAULT '', + `media_url` varchar(255) NOT NULL DEFAULT '', + `createtime` bigint DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `idx_bind_time` (`bind_id`,`createtime`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='沟通空间留言'; + +-- ---------------------------- +-- M4 爱心积分流水 +-- ---------------------------- +DROP TABLE IF EXISTS `fa_point_log`; +CREATE TABLE `fa_point_log` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `user_id` int unsigned NOT NULL, + `action` varchar(30) NOT NULL DEFAULT 'care_daily', + `point` int NOT NULL DEFAULT '0', + `ref_id` int unsigned NOT NULL DEFAULT '0', + `remark` varchar(255) NOT NULL DEFAULT '', + `createtime` bigint DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `idx_user` (`user_id`,`createtime`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='爱心积分流水'; + +-- ---------------------------- +-- M7 纪念日 / 爱的记忆时间轴 +-- ---------------------------- +DROP TABLE IF EXISTS `fa_memory`; +CREATE TABLE `fa_memory` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `user_id` int unsigned NOT NULL, + `bind_id` int unsigned NOT NULL DEFAULT '0', + `title` varchar(60) NOT NULL, + `memory_date` date NOT NULL, + `type` varchar(20) NOT NULL DEFAULT 'anniversary' COMMENT 'anniversary/milestone/daily', + `content` varchar(500) NOT NULL DEFAULT '', + `remind` tinyint NOT NULL DEFAULT '1', + `createtime` bigint DEFAULT NULL, + `deletetime` bigint DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `idx_user_date` (`user_id`,`memory_date`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='纪念日与记忆时间轴'; + +-- ---------------------------- +-- M7/M9 量表测评 +-- ---------------------------- +DROP TABLE IF EXISTS `fa_assessment`; +CREATE TABLE `fa_assessment` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `code` varchar(30) NOT NULL COMMENT 'pms/prepare_anxiety/relation/pdp', + `title` varchar(80) NOT NULL, + `intro` varchar(255) NOT NULL DEFAULT '', + `questions` mediumtext NOT NULL COMMENT '题目 JSON', + `scoring` varchar(500) NOT NULL DEFAULT '' COMMENT '分级阈值 JSON', + `level` varchar(10) NOT NULL DEFAULT 'basic' COMMENT 'basic/pro', + `scope` varchar(20) NOT NULL DEFAULT 'mood' COMMENT 'mood/relation/parenting', + `access` varchar(10) NOT NULL DEFAULT 'free' COMMENT 'free/member/pay', + `status` varchar(20) NOT NULL DEFAULT 'normal', + `weigh` int NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + UNIQUE KEY `uniq_code` (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='量表测评'; + +DROP TABLE IF EXISTS `fa_assessment_record`; +CREATE TABLE `fa_assessment_record` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `user_id` int unsigned NOT NULL, + `assessment_id` int unsigned NOT NULL, + `answers` varchar(1000) NOT NULL DEFAULT '' COMMENT '答案数组 JSON', + `score` decimal(8,2) NOT NULL DEFAULT '0.00', + `result` varchar(20) NOT NULL DEFAULT '' COMMENT 'low/medium/high/risk', + `report` text COMMENT '解读建议', + `risk_flag` tinyint NOT NULL DEFAULT '0' COMMENT '1 触发危机干预', + `createtime` bigint DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `idx_user` (`user_id`,`assessment_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='测评记录'; + +-- ---------------------------- +-- M7/M8 课程订单 +-- ---------------------------- +DROP TABLE IF EXISTS `fa_course_order`; +CREATE TABLE `fa_course_order` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `order_no` varchar(32) NOT NULL, + `user_id` int unsigned NOT NULL, + `content_id` int unsigned NOT NULL COMMENT '课程内容ID', + `amount` decimal(10,2) NOT NULL DEFAULT '0.00', + `pay_status` varchar(20) NOT NULL DEFAULT 'unpaid' COMMENT 'unpaid/paid', + `createtime` bigint DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uniq_order_no` (`order_no`), + KEY `idx_user` (`user_id`,`content_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='课程订单'; + +-- ---------------------------- +-- M8 宝宝档案 / 成长记录 +-- ---------------------------- +DROP TABLE IF EXISTS `fa_baby`; +CREATE TABLE `fa_baby` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `user_id` int unsigned NOT NULL, + `nickname` varchar(30) NOT NULL DEFAULT '', + `gender` tinyint NOT NULL DEFAULT '0' COMMENT '0未知 1男 2女', + `birthday` date DEFAULT NULL, + `due_date` date DEFAULT NULL COMMENT '预产期(孕期)', + `status` varchar(20) NOT NULL DEFAULT 'normal', + `createtime` bigint DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `idx_user` (`user_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='宝宝/孕期档案'; + +DROP TABLE IF EXISTS `fa_growth_record`; +CREATE TABLE `fa_growth_record` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `user_id` int unsigned NOT NULL, + `baby_id` int unsigned NOT NULL, + `record_date` date NOT NULL, + `height` decimal(5,1) DEFAULT NULL COMMENT 'cm', + `weight` decimal(5,2) DEFAULT NULL COMMENT 'kg', + `milestone` varchar(100) NOT NULL DEFAULT '', + `note` varchar(300) NOT NULL DEFAULT '', + `createtime` bigint DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `idx_baby_date` (`baby_id`,`record_date`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='成长记录'; + +-- ---------------------------- +-- M8 疫苗与儿保计划(静态表) +-- ---------------------------- +DROP TABLE IF EXISTS `fa_vaccine`; +CREATE TABLE `fa_vaccine` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(60) NOT NULL, + `type` varchar(20) NOT NULL DEFAULT 'vaccine' COMMENT 'vaccine/checkup', + `month_from` smallint NOT NULL DEFAULT '0' COMMENT '建议月龄起', + `month_to` smallint NOT NULL DEFAULT '0', + `note` varchar(120) NOT NULL DEFAULT '', + `weigh` int NOT NULL DEFAULT '0', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='疫苗与儿保时间表'; + +-- ---------------------------- +-- M9 咨询师与咨询订单 +-- ---------------------------- +DROP TABLE IF EXISTS `fa_counselor`; +CREATE TABLE `fa_counselor` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(50) NOT NULL, + `avatar_emoji` varchar(10) NOT NULL DEFAULT '🌷', + `title` varchar(80) NOT NULL DEFAULT '', + `cert_no` varchar(60) NOT NULL DEFAULT '' COMMENT '资质编号', + `cert_verify` varchar(20) NOT NULL DEFAULT 'passed' COMMENT 'pending/passed/expired', + `price_text` decimal(10,2) NOT NULL DEFAULT '0.00', + `price_voice` decimal(10,2) NOT NULL DEFAULT '0.00', + `price_video` decimal(10,2) NOT NULL DEFAULT '0.00', + `rate` decimal(5,2) NOT NULL DEFAULT '0.30' COMMENT '平台分成比例', + `intro` varchar(500) NOT NULL DEFAULT '', + `tags` varchar(120) NOT NULL DEFAULT '', + `status` varchar(20) NOT NULL DEFAULT 'on' COMMENT 'on/off', + `weigh` int NOT NULL DEFAULT '0', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='咨询师'; + +DROP TABLE IF EXISTS `fa_consult_order`; +CREATE TABLE `fa_consult_order` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `order_no` varchar(32) NOT NULL, + `user_id` int unsigned NOT NULL, + `counselor_id` int unsigned NOT NULL, + `mode` varchar(10) NOT NULL DEFAULT 'text' COMMENT 'text/voice/video', + `start_time` bigint DEFAULT NULL, + `duration` int NOT NULL DEFAULT '50', + `amount` decimal(10,2) NOT NULL DEFAULT '0.00', + `pay_status` varchar(20) NOT NULL DEFAULT 'unpaid', + `consult_status` varchar(20) NOT NULL DEFAULT 'pending' COMMENT 'pending/ongoing/finished/canceled', + `rate_amount` decimal(10,2) NOT NULL DEFAULT '0.00', + `createtime` bigint DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uniq_order_no` (`order_no`), + KEY `idx_user` (`user_id`,`consult_status`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='咨询订单'; + +-- ---------------------------- +-- M6 数据备份快照 +-- ---------------------------- +DROP TABLE IF EXISTS `fa_user_backup`; +CREATE TABLE `fa_user_backup` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `user_id` int unsigned NOT NULL, + `name` varchar(60) NOT NULL DEFAULT '', + `size` int unsigned NOT NULL DEFAULT '0', + `payload` mediumtext COMMENT '备份 JSON', + `createtime` bigint DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `idx_user` (`user_id`,`createtime`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户数据备份'; diff --git a/server/db/04_module_seed.sql b/server/db/04_module_seed.sql new file mode 100644 index 0000000..255e4b9 --- /dev/null +++ b/server/db/04_module_seed.sql @@ -0,0 +1,182 @@ +-- ============================================================ +-- 花期 APP · M3–M9 初始化数据(内容 / 量表 / 疫苗表 / 咨询师) +-- 可重复执行:按类型清空后重建(不动用户产生的记录) +-- ============================================================ +SET NAMES utf8mb4; + +-- 新增内容分类 +DELETE FROM `fa_content_category` WHERE `id` BETWEEN 9 AND 17; +INSERT INTO `fa_content_category` (`id`,`pid`,`name`,`type`,`weigh`,`status`) VALUES +(9,0,'暖心话术库','care',25,'normal'), +(10,0,'沟通引导卡','card',24,'normal'), +(11,0,'冲突工具','conflict',23,'normal'), +(12,0,'情绪急救包','firstaid',22,'normal'), +(13,0,'同房指导','guide',21,'normal'), +(14,0,'系列课程','course',20,'normal'), +(15,0,'亲子活动','activity',19,'normal'), +(16,0,'育儿情绪','emotion',18,'normal'), +(17,0,'育儿知识','knowledge',17,'normal'); + +-- 清理本次要重建的内容类型 +DELETE FROM `fa_content` WHERE `type` IN ('care','card','conflict','firstaid','guide','course','activity','emotion'); + +INSERT INTO `fa_content` +(`category_id`,`type`,`title`,`summary`,`body`,`cover_emoji`,`media_type`,`duration`,`phase`,`mood_tag`,`extra`,`access`,`verify`,`weigh`,`status`,`createtime`,`updatetime`) VALUES +-- ---------------- M4 暖心话术库 ---------------- +(9,'care','经期来了,可以这样说','把关心落到具体行动上,而不是一句「多喝热水」。', + '「今天别安排太满,晚上我煮红糖姜茶。」\n「暖贴我放你包里了,记得换。」\n\n避免:「多喝热水」「你怎么又这样」。','💛','text',0,'menstrual','','','free','passed',100,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(9,'care','她心情低落时','先陪着,不急着把情绪修好。', + '「我在,不用急着好起来。」\n「想说说吗?不想说也行,我陪你坐一会儿。」','🌧','text',0,'all','low','','free','passed',99,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(9,'care','备孕压力大时','把「一起」说出口,压力会小一半。', + '「我们一起看医生、一起改作息,不着急。」\n「今天要不要一起散步 20 分钟?」','🌱','text',0,'all','anxious','','free','passed',98,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(9,'care','争吵后的修复话术','修复比赢更重要。', + '「刚才我语气重了,对不起。」\n「我想听听你当时的感受。」','🕊','text',0,'all','angry','','free','passed',97,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(9,'care','纪念日和日常的小惊喜','小频率胜过一次性的大场面。', + '每周一次「专属 30 分钟」:不谈工作、不看手机。\n纪念日提前一周准备,写一张手写卡片。','🎁','text',0,'all','','','member','passed',96,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(9,'care','异地时的关心节奏','稳定可预期的关心,比密集轰炸更安心。', + '固定每天一个时间段的语音,不催促回复。\n同步彼此日程,减少「失联焦虑」。','🌙','text',0,'all','','','member','passed',95,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), + +-- ---------------- M7 沟通引导卡 ---------------- +(10,'card','她说「我没事」时','先确认情绪,再谈解决方案。', + '第 1 步:复述你观察到的(「你今天话很少」)。\n第 2 步:给出选择(「想聊聊还是想安静一会儿?」)。\n第 3 步:不评判地听完。','💬','text',0,'all','','','free','passed',90,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(10,'card','她烦躁时不要讲的 3 句话','有些话会把情绪推得更高。', + '「你别想太多」→ 换成「这种感受确实不好受」。\n「这有什么好难过的」→ 换成「我在听」。\n「你就是太敏感」→ 换成「需要我做什么吗」。','🚫','text',0,'all','angry','','free','passed',89,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(10,'card','如何表达自己的需求','用「我」开头,减少指责。', + '「我最近有点累,希望周末能一起分担家务。」\n而不是「你从来不管家里」。','🗣','text',0,'all','','','free','passed',88,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(10,'card','备孕期沟通的三个约定','减少期待落差。', + '1)检查结果一起看;2)不追问「这个月怎么样」;3)允许任何一方说「今天不想聊这个」。','🤝','text',0,'all','','','member','passed',87,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(10,'card','见家长前的沟通准备','把底线和期待先说清。', + '提前对齐:见面频率、称呼、礼物预算、遇到分歧谁先说。','🏠','text',0,'all','','','member','passed',86,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(10,'card','长期关系里的「情绪账户」','日常小存款,胜过危机时的大修补。', + '每天 1 次真诚的感谢、每周 1 次共同体验、每月 1 次关系复盘。','🏦','text',0,'all','','','member','passed',85,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), + +-- ---------------- M7 冲突工具 ---------------- +(11,'conflict','暂停-呼吸-表达三步法','上头时的可执行流程。', + '1)暂停:说出「我需要 10 分钟」,并约定回来的时间。\n2)呼吸:4-7-8 呼吸 4 轮。\n3)表达:事实 → 感受 → 需求 → 请求。','⏸','text',0,'all','angry','','free','passed',80,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(11,'conflict','冲突升级的 5 个信号','看见信号就降温。', + '语速变快、翻旧账、贴标签、提高音量、身体发紧。\n出现任意两个,先暂停。','⚠️','text',0,'all','angry','','free','passed',79,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(11,'conflict','冷静期的 3 条约定','暂停不等于冷战。', + '1)说明回来时间;2)不翻旧账;3)回来后先复述对方观点再表达自己。','🧊','text',0,'all','','','free','passed',78,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), + +-- ---------------- M2 情绪急救包 ---------------- +(12,'firstaid','478 呼吸法','情绪上头 / 睡前 3 分钟。', + '步骤:\n1. 用鼻子吸气 4 秒\n2. 屏息 7 秒\n3. 缓慢呼气 8 秒\n4. 循环 4 轮\n\n若屏息不适,可改为 4-4-6。','🫁','text',0,'all','anxious,angry','','free','passed',75,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(12,'firstaid','5-4-3-2-1 接地练习','把注意力拉回当下。', + '说出:5 样看见的东西、4 种听到的声音、3 处身体触感、2 种气味、1 种味道。','🖐','text',0,'all','anxious','','free','passed',74,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(12,'firstaid','EFT 情绪敲击','轻敲穴位配合表达。', + '依次轻敲:眉头、眼侧、眼下、人中、下巴、锁骨、腋下,各 5 次,同时说出感受。','🎯','text',0,'all','anxious,low','','free','passed',73,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(12,'firstaid','治愈歌单与插画','用感官安抚自己。', + '选择 60-80 BPM 的纯音乐,配合 3 张让你平静的图片,做 5 分钟缓慢呼吸。','🎧','text',0,'all','low','','free','passed',72,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), + +-- ---------------- M3 同房指导(会员) ---------------- +(13,'guide','受孕窗口与同房频率','易孕期隔日一次更稳妥。', + '排卵前 2 天至排卵后 1 天为最佳窗口,隔日一次即可,避免过度频繁影响精子质量。','📆','text',0,'all','','','member','passed',70,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(13,'guide','同房后的休息建议','平躺 15 分钟,无需抬高臀部。', + '结束后平躺休息 10-15 分钟即可,避免立即冲洗。','🛏','text',0,'all','','','member','passed',69,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(13,'guide','精子质量的生活建议','提前 3 个月开始调整。', + '戒烟限酒、避免久坐与高温环境、保证 7 小时睡眠、补充锌与叶酸。','🧪','text',0,'all','','','member','passed',68,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), + +-- ---------------- M7/M8 课程 ---------------- +(14,'course','非暴力沟通入门','6 节 · 观察-感受-需要-请求。', + '第 1 节:区分观察与评价\n第 2 节:识别真实感受\n第 3 节:找到背后的需要\n第 4 节:提出具体请求\n第 5 节:倾听与共情\n第 6 节:冲突中的练习','📚','text',2700,'all','','{"lessons":6,"minutes":45,"part":"relation"}','pay','passed',65,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(14,'course','伴侣共情练习','5 节 · 把「我懂你」说具体。', + '包含 10 个共情句式、3 个真实场景演练、1 份关系复盘表。','💞','text',2250,'all','','{"lessons":5,"minutes":45,"part":"relation"}','pay','passed',64,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(14,'course','备孕期伴侣心理','4 节 · 一起面对等待与失落。', + '如何谈检查结果、如何面对失败周期、如何保住亲密感。','🌾','text',1800,'all','','{"lessons":4,"minutes":45,"part":"relation"}','pay','passed',63,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(14,'course','0-6 月龄育儿基础','8 节 · 喂养、睡眠、安抚、发育。', + '新手父母最常问的 40 个问题,医生审核。','🍼','text',3600,'all','','{"lessons":8,"minutes":45,"part":"parenting"}','pay','passed',62,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(14,'course','亲子沟通启蒙','6 节 · 从听懂哭声开始。', + '分月龄沟通方式、情绪命名、边界建立。','🗨','text',2700,'all','','{"lessons":6,"minutes":45,"part":"parenting"}','pay','passed',61,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(14,'course','感统游戏 30 例','10 节 · 在家就能做的感统训练。', + '前庭、本体、触觉三类游戏,配材料清单与安全提示。','🧸','text',4500,'all','','{"lessons":10,"minutes":45,"part":"parenting"}','pay','passed',60,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), + +-- ---------------- M8 亲子活动 ---------------- +(15,'activity','0-3 月:追视游戏','黑白卡 20 秒,每天 2 次。', + '距离眼睛 20-30cm,缓慢左右移动,观察宝宝眼睛是否跟随。','👀','text',0,'all','','{"month_from":0,"month_to":3}','free','passed',55,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(15,'activity','4-6 月:翻身引导','用玩具引导侧翻。', + '在宝宝侧方放玩具,轻推髋部辅助,每次 3-5 分钟。','🔄','text',0,'all','','{"month_from":4,"month_to":6}','free','passed',54,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(15,'activity','7-9 月:爬行隧道','纸箱隧道 + 摇铃诱导。', + '距离由近到远,全程陪护,注意地面防滑。','🚇','text',0,'all','','{"month_from":7,"month_to":9}','free','passed',53,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(15,'activity','10-12 月:抓握与投放','大颗粒积木投放练习。', + '准备容器与积木,示范「放进去」,成功即鼓励。','🪣','text',0,'all','','{"month_from":10,"month_to":12}','free','passed',52,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(15,'activity','1-2 岁:绘本共读','每天 10 分钟,指图命名。', + '选择硬纸板书,跟随孩子兴趣,不强迫读完。','📖','text',0,'all','','{"month_from":12,"month_to":24}','free','passed',51,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(15,'activity','2-3 岁:感统小游戏','平衡木、抛接球、跳格子。', + '每天 15 分钟户外活动,重点在平衡与协调。','🤸','text',0,'all','','{"month_from":24,"month_to":36}','member','passed',50,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), + +-- ---------------- M8 育儿情绪 ---------------- +(16,'emotion','产后情绪波动','激素与睡眠双重影响,不是「不够坚强」。', + '产后 2 周内的情绪低落常见;若持续超过 2 周并影响生活,建议筛查(EPDS)。','🌊','text',0,'all','low','','free','passed',45,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(16,'emotion','育儿焦虑','把「必须做对」换成「先做够」。', + '列出今天必须完成的 3 件事,其余允许延后。\n每天留 15 分钟给自己。','🌪','text',0,'all','anxious','','free','passed',44,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(16,'emotion','睡眠剥夺下的情绪','先补觉,再谈情绪管理。', + '与伴侣轮流值夜,白天补 20 分钟小睡;避免用咖啡因硬扛。','😴','text',0,'all','low','','free','passed',43,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(16,'emotion','何时需要专业帮助','出现以下情况请尽快就医。', + '持续两周以上情绪低落、对宝宝无兴趣、有伤害自己或孩子的念头——请立即寻求专业帮助。','🆘','text',0,'all','low','','free','passed',42,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()); + +-- ---------------- 知识库补充(备孕/孕期/育儿) ---------------- +DELETE FROM `fa_content` WHERE `type` = 'knowledge' AND `category_id` IN (3,17); +INSERT INTO `fa_content` +(`category_id`,`type`,`title`,`summary`,`body`,`cover_emoji`,`media_type`,`duration`,`phase`,`mood_tag`,`extra`,`access`,`verify`,`weigh`,`status`,`createtime`,`updatetime`) VALUES +(3,'knowledge','备孕前的检查清单','双方都建议做的项目。', + '女方:妇科检查、甲功、TORCH、性激素六项、B 超。\n男方:精液常规。\n提前 3 个月开始补充叶酸。\n本内容仅供参考,不能替代医疗诊断。','📋','text',0,'all','','','free','passed',83,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(3,'knowledge','叶酸怎么补','孕前 3 个月至孕早期。', + '每日 0.4mg,特殊情况(既往神经管缺陷史)遵医嘱加量。','💊','text',0,'all','','','free','passed',82,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(3,'knowledge','孕期产检时间表','关键节点别错过。', + '6-8 周确认宫内孕;11-13⁺⁶ 周 NT;15-20 周唐筛/无创;20-24 周大排畸;24-28 周糖耐。','🗓','text',0,'all','','','free','passed',81,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(17,'knowledge','新生儿睡眠特点','碎片化是正常的。', + '新生儿每天睡 14-17 小时,单次 2-4 小时,昼夜节律 3 个月后逐渐建立。','🌙','text',0,'all','','','free','passed',40,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(17,'knowledge','辅食添加顺序','满 6 月龄开始,由稀到稠。', + '第一口推荐强化铁米粉,逐步引入蔬菜泥、肉泥、蛋黄,每次只加一种,观察 3 天。','🥣','text',0,'all','','','free','passed',39,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(17,'knowledge','发烧的家庭观察','看精神状态比看数字更重要。', + '3 月龄以下发热请立即就医;出现精神差、抽搐、呼吸急促请急诊。\n本内容仅供参考,不能替代医疗诊断。','🌡','text',0,'all','','','free','passed',38,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()), +(17,'knowledge','疫苗接种注意事项','接种后观察 30 分钟。', + '发热期暂缓接种;接种后 24 小时避免剧烈活动,局部红肿可冷敷。','💉','text',0,'all','','','free','passed',37,'normal',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()); + +-- ---------------- 量表测评 ---------------- +DELETE FROM `fa_assessment`; +INSERT INTO `fa_assessment` (`code`,`title`,`intro`,`questions`,`scoring`,`level`,`scope`,`access`,`status`,`weigh`) VALUES +('pms','经前情绪自评(PMS)','回想最近一个经前周期,评估以下感受出现的频率。', + '["情绪波动明显,容易突然烦躁或低落","对平时喜欢的事提不起兴趣","容易疲惫、精力不足","睡眠变差或嗜睡","注意力难以集中"]', + '{"max":20,"levels":[{"lt":8,"key":"low","text":"经前情绪波动较轻,保持规律作息即可。"},{"lt":14,"key":"medium","text":"有一定 PMS 表现,建议记录情绪并在黄体期降低负荷。"},{"lt":20,"key":"high","text":"PMS 表现较明显,建议到妇科或心理科评估。"}]}', + 'basic','mood','free','normal',40), +('prepare_anxiety','备孕焦虑自评','评估最近两周与备孕相关的焦虑程度。', + '["经常想着「这个月能不能怀上」","看到别人的好消息会明显失落","反复搜索症状与检查结果","因备孕影响睡眠","与伴侣因备孕产生争执"]', + '{"max":20,"levels":[{"lt":8,"key":"low","text":"备孕压力在可控范围,继续保持沟通。"},{"lt":14,"key":"medium","text":"焦虑已影响情绪,建议与伴侣约定「不谈备孕的时间」。"},{"lt":20,"key":"high","text":"焦虑较明显,建议寻求专业心理支持。"}]}', + 'basic','mood','free','normal',39), +('relation','亲密关系满意度','评估最近一个月的关系状态。', + '["我能自在地表达需求","发生分歧时我们能好好沟通","我感到被理解和支持","我们对未来有共同计划","亲密与独处的时间都能被尊重"]', + '{"max":20,"levels":[{"lt":8,"key":"high","text":"关系存在明显张力,建议优先安排一次不被打断的沟通。"},{"lt":14,"key":"medium","text":"关系整体平稳,仍有一些可优化的小习惯。"},{"lt":20,"key":"low","text":"关系状态良好,继续保持日常的「情绪存款」。"}]}', + 'basic','relation','free','normal',38), +('pdp','产后情绪筛查','产后 6 个月内自我筛查(非诊断)。', + '["情绪低落、提不起劲","对宝宝或事物失去兴趣","睡眠差(即使宝宝睡着也睡不着)","自责或觉得自己不够好","出现过伤害自己或孩子的念头"]', + '{"max":20,"levels":[{"lt":8,"key":"low","text":"目前情绪状态平稳,继续保证休息与支持。"},{"lt":14,"key":"medium","text":"建议告知家人并安排一次专业评估。"},{"lt":20,"key":"high","text":"请尽快联系妇产科或精神心理科就诊。"}]}', + 'basic','parenting','free','normal',37); + +-- ---------------- 疫苗与儿保 ---------------- +DELETE FROM `fa_vaccine`; +INSERT INTO `fa_vaccine` (`name`,`type`,`month_from`,`month_to`,`note`,`weigh`) VALUES +('乙肝疫苗(第 1 剂)+ 卡介苗','vaccine',0,0,'出生 24 小时内',100), +('乙肝疫苗(第 2 剂)','vaccine',1,1,'1 月龄',99), +('脊灰疫苗(第 1 剂)','vaccine',2,2,'2 月龄',98), +('百白破(第 1 剂)','vaccine',3,3,'3 月龄',97), +('脊灰疫苗(第 3 剂)','vaccine',4,4,'4 月龄',96), +('百白破(第 2 剂)','vaccine',4,4,'4 月龄',95), +('乙肝疫苗(第 3 剂)','vaccine',6,6,'6 月龄',94), +('流感疫苗(首年)','vaccine',6,8,'6 月龄后每年接种',93), +('麻腮风疫苗(第 1 剂)','vaccine',8,8,'8 月龄',92), +('乙脑疫苗(第 1 剂)','vaccine',8,8,'8 月龄',91), +('水痘疫苗(第 1 剂)','vaccine',12,15,'12-15 月龄',90), +('甲肝疫苗','vaccine',18,18,'18 月龄',89), +('42 天产后复查','checkup',1,2,'妈妈与宝宝',88), +('儿保体检(3 月龄)','checkup',3,3,'生长发育评估',87), +('儿保体检(6 月龄)','checkup',6,6,'含血常规',86), +('儿保体检(12 月龄)','checkup',12,12,'含视力筛查',85), +('儿保体检(24 月龄)','checkup',24,24,'含语言评估',84); + +-- ---------------- 咨询师 ---------------- +DELETE FROM `fa_counselor`; +INSERT INTO `fa_counselor` (`name`,`avatar_emoji`,`title`,`cert_no`,`cert_verify`,`price_text`,`price_voice`,`price_video`,`rate`,`intro`,`tags`,`status`,`weigh`) VALUES +('林医生','🌷','精神心理科主治医师 · 8 年','CERT-2019-1024','passed',199.00,259.00,329.00,0.30,'擅长经前情绪、备孕焦虑、产后情绪支持。','经前情绪,备孕焦虑,产后','on',100), +('周老师','🌿','国家二级心理咨询师 · 6 年','CERT-2020-0451','passed',159.00,199.00,269.00,0.30,'认知行为取向,专注亲密关系与沟通模式。','亲密关系,沟通,情绪','on',99), +('安宁','🌸','婚姻家庭咨询师 · 5 年','CERT-2021-0778','passed',139.00,179.00,239.00,0.30,'擅长伴侣冲突、家庭沟通、新手父母适应。','伴侣冲突,家庭,新手父母','on',98); diff --git a/utils/api.js b/utils/api.js index 47607cb..3df20bb 100644 --- a/utils/api.js +++ b/utils/api.js @@ -29,19 +29,93 @@ export const api = { moodList: (params) => request('/api/mood/index', { data: params }), moodTrend: (days) => request('/api/mood/trend', { data: { days } }), moodRemove: (id) => request('/api/mood/remove', { method: 'POST', data: { id } }), + moodFirstaid: () => request('/api/mood/firstaid'), // ---------- 内容 ---------- contentList: (params) => request('/api/content/index', { data: params }), contentDetail: (id) => request('/api/content/detail', { data: { id } }), + // ---------- 健康建议 M5 ---------- + healthIndex: () => request('/api/health/index'), + healthDetail: (type) => request('/api/health/detail', { data: { type } }), + + // ---------- 科学备孕 M3 ---------- + prepareIndex: () => request('/api/prepare/index'), + bbtSave: (data) => request('/api/prepare/bbtSave', { method: 'POST', data }), + bbtList: (days) => request('/api/prepare/bbtList', { data: { days } }), + lhTest: (data) => request('/api/prepare/lhtest', { method: 'POST', data }), + lhTestList: () => request('/api/prepare/lhtestList'), + prepareTasks: () => request('/api/prepare/taskList'), + prepareTaskSave: (data) => request('/api/prepare/taskSave', { method: 'POST', data }), + prepareTaskDone: (id) => request('/api/prepare/taskDone', { method: 'POST', data: { id } }), + prepareTaskRemove: (id) => request('/api/prepare/taskRemove', { method: 'POST', data: { id } }), + prepareGuide: () => request('/api/prepare/guide'), + + // ---------- 家人共护 M4 ---------- + familyIndex: () => request('/api/family/index'), + familyInvite: (data) => request('/api/family/invite', { method: 'POST', data }), + familyConfirm: (code) => request('/api/family/confirm', { method: 'POST', data: { invite_code: code } }), + familyRemove: (id) => request('/api/family/remove', { method: 'POST', data: { id } }), + familyScripts: () => request('/api/family/scripts'), + familyMessages: (bindId) => request('/api/family/messages', { data: { bind_id: bindId } }), + familyMessageSend: (data) => request('/api/family/messageSend', { method: 'POST', data }), + familyCareAction: () => request('/api/family/careAction', { method: 'POST' }), + familyPoints: () => request('/api/family/points'), + familyHealthView: () => request('/api/family/healthView'), + + // ---------- 两性关系 M7 ---------- + relationIndex: () => request('/api/relation/index'), + relationCards: () => request('/api/relation/cards'), + relationConflicts: () => request('/api/relation/conflicts'), + relationCourses: () => request('/api/relation/courses'), + courseBuy: (id) => request('/api/relation/courseBuy', { method: 'POST', data: { id } }), + relationTasks: () => request('/api/relation/taskList'), + relationTaskSave: (data) => request('/api/relation/taskSave', { method: 'POST', data }), + relationTaskDone: (id) => request('/api/relation/taskDone', { method: 'POST', data: { id } }), + memories: () => request('/api/relation/memories'), + memorySave: (data) => request('/api/relation/memorySave', { method: 'POST', data }), + memoryRemove: (id) => request('/api/relation/memoryRemove', { method: 'POST', data: { id } }), + + // ---------- 亲子教育 M8 ---------- + parentingIndex: () => request('/api/parenting/index'), + babySave: (data) => request('/api/parenting/babySave', { method: 'POST', data }), + babyInfo: () => request('/api/parenting/babyInfo'), + growthSave: (data) => request('/api/parenting/growthSave', { method: 'POST', data }), + parentingActivities: () => request('/api/parenting/activities'), + parentingCourses: () => request('/api/parenting/courses'), + coTasks: () => request('/api/parenting/coTasks'), + coTaskSave: (data) => request('/api/parenting/coTaskSave', { method: 'POST', data }), + coTaskDone: (id) => request('/api/parenting/coTaskDone', { method: 'POST', data: { id } }), + parentingEmotions: () => request('/api/parenting/emotions'), + vaccines: () => request('/api/parenting/vaccines'), + + // ---------- 心理服务 M9 ---------- + consultIndex: () => request('/api/consult/index'), + counselors: () => request('/api/consult/counselors'), + consultAssessments: (scope) => request('/api/consult/assessments', { data: { scope } }), + consultOrder: (data) => request('/api/consult/orderCreate', { method: 'POST', data }), + consultOrders: () => request('/api/consult/orders'), + consultCancel: (id) => request('/api/consult/cancel', { method: 'POST', data: { id } }), + crisis: () => request('/api/consult/crisis'), + + // ---------- 量表(M7/M8/M9 共用) ---------- + assessmentDetail: (id) => request('/api/consult/assessmentDetail', { data: { id } }), + assessmentSubmit: (id, answers) => request('/api/consult/assessmentSubmit', { method: 'POST', data: { id, answers: JSON.stringify(answers) } }), + // ---------- 会员 M6 ---------- memberPlans: () => request('/api/member/plans', { auth: false }), memberStatus: () => request('/api/member/status'), memberOrder: (planId, payType) => request('/api/member/order', { method: 'POST', data: { plan_id: planId, pay_type: payType } }), - // ---------- 设置 ---------- + // ---------- 设置 / 提醒 / 备份 ---------- settingIndex: () => request('/api/setting/index'), - settingSave: (data) => request('/api/setting/save', { method: 'POST', data }) + settingSave: (data) => request('/api/setting/save', { method: 'POST', data }), + reminderList: () => request('/api/setting/reminderList'), + reminderSave: (data) => request('/api/setting/reminderSave', { method: 'POST', data }), + reminderRemove: (id) => request('/api/setting/reminderRemove', { method: 'POST', data: { id } }), + backupCreate: () => request('/api/setting/backupCreate', { method: 'POST' }), + backupList: () => request('/api/setting/backupList'), + backupRestore: (id) => request('/api/setting/backupRestore', { method: 'POST', data: { id } }) } export default api