feat: 补齐 M1–M9 全部 47 个功能点并打通前后端

后端(新增 7 控制器 + 2 服务 + 17 张表)
- Prepare:排卵预测、BBT(双向体温识别)、试纸识别(规则引擎+额度)、备孕任务、同房指导
- Family:邀请码绑定(≤5)、话术库、爱心积分、私密留言、家庭健康视图
- Health:按周期阶段输出饮食/运动/睡眠/痛经四类建议
- Relation:关系测评、引导卡、冲突工具、课程下单、双人任务(联动记忆)、纪念日
- Parenting:宝宝档案、成长记录、月龄活动匹配、共育任务、育儿情绪、疫苗儿保排期
- Consult:咨询师(资质/定价/时段)、预约下单/取消、量表测评(4 套)、危机干预转介
- Setting:自定义提醒 CRUD、数据备份快照与恢复(保留 5 份)
- Mood 增补急救包;Home 提醒合并自定义提醒
- 服务层:ContentService(统一内容/锁态/购买态)、AssessmentService(计分分级+危机识别)

前端(新增 8 页面)
- 备孕、家人共护、健康建议、两性关系、亲子教育、心理咨询、测评执行页、情绪急救包
- 首页快捷入口扩至 8 个模块;我的页新增提醒中心与数据备份
- utils/api.js 扩至 84 个接口

数据(可重复执行脚本)
- 03_modules.sql:fa_reminder/bbt/lh_test/task/family_bind/care_message/point_log/memory/
  assessment(+record)/course_order/baby/growth_record/vaccine/counselor/consult_order/user_backup
- 04_module_seed.sql:话术6/引导卡6/冲突3/急救4/同房3/课程6/活动6/育儿情绪4/知识7、
  4 套量表、17 项疫苗儿保、3 位咨询师

验证(全部通过)
- 接口全链路 82 项断言(M1–M9,含高风险测评危机干预、备份恢复)
- 契约校验 84 接口 0 偏差;Vue SFC 19/19、SCSS 18/18 编译通过
- 修复 3 个真实缺陷:action 内调用 action 导致响应被劫持、coTasks 返回数组、
  咨询时段跨年错误
这个提交包含在:
linda
2026-11-05 23:27:21 +08:00
父节点 5ea1b461f3
当前提交 d243ece39c
共有 30 个文件被更改,包括 7452 次插入 和 222 次删除

查看文件

@@ -0,0 +1,240 @@
<?php
namespace app\api\controller;
use app\common\controller\Api;
use app\common\service\AssessmentService;
use app\common\service\MemberService;
use fast\Random;
use think\Db;
/**
* 心理咨询与测评接口(M9)
*
* 咨询师入驻与排班 / 一对一咨询预约 / 量表测评 / 危机干预转介
*/
class Consult extends Api
{
protected $noNeedLogin = [];
protected $noNeedRight = '*';
/**
* 总览
*/
public function index()
{
$userId = $this->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);
}
}

查看文件

@@ -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;
}
}

查看文件

@@ -0,0 +1,338 @@
<?php
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 fast\Random;
use think\Db;
/**
* 家人共护接口(M4)
*
* 绑定(≤5 人)/ 关怀提醒 / 话术库 / 爱心积分 / 私密沟通空间 / 家庭健康视图
*/
class Family extends Api
{
protected $noNeedLogin = [];
protected $noNeedRight = '*';
/** 最多绑定人数 */
const MAX_BIND = 5;
/**
* 家庭总览
*/
public function index()
{
$userId = $this->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;
}
}

查看文件

@@ -0,0 +1,107 @@
<?php
namespace app\api\controller;
use app\common\controller\Api;
use app\common\service\ContentService;
use app\common\service\CycleService;
/**
* 健康建议接口(M5)
*
* 内容 + 规则匹配:按当前周期阶段给出 饮食 / 运动 / 睡眠 / 痛经 四类建议。
*/
class Health extends Api
{
protected $noNeedLogin = [];
protected $noNeedRight = '*';
/** 分类 → 建议类型 */
protected $categoryMap = [
'diet' => 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] : ['记录后获得个性化建议'];
}
}

查看文件

@@ -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;
}

查看文件

@@ -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

查看文件

@@ -0,0 +1,324 @@
<?php
namespace app\api\controller;
use app\common\controller\Api;
use app\common\service\AssessmentService;
use app\common\service\ContentService;
use think\Db;
/**
* 亲子教育接口(M8)
*
* 育儿知识库 / 成长记录 / 亲子活动 / 课程 / 共育任务 / 育儿情绪 / 疫苗与儿保
*/
class Parenting extends Api
{
protected $noNeedLogin = [];
protected $noNeedRight = '*';
/**
* 亲子模块总览
*/
public function index()
{
$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;
$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;
}
}

查看文件

@@ -0,0 +1,435 @@
<?php
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;
/**
* 科学备孕接口(M3)
*
* 排卵预测 / 基础体温 / 试纸识别 / 备孕任务 / 知识库 / 同房指导
* 说明:试纸识别当前为「规则识别」,接口已按 CNN 服务形态预留 algo 字段,
* 接入推理服务后只需替换 recognize() 内部实现,前端无需改动。
*/
class Prepare extends Api
{
protected $noNeedLogin = [];
protected $noNeedRight = '*';
/** 每月免费识别额度 */
const FREE_LH_QUOTA = 5;
/**
* 备孕总览(一次请求返回预测 + 体温 + 试纸趋势 + 任务进度)
*/
public function index()
{
$userId = $this->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 . ' 次',
];
}
}

查看文件

@@ -0,0 +1,303 @@
<?php
namespace app\api\controller;
use app\common\controller\Api;
use app\common\service\AssessmentService;
use app\common\service\ContentService;
use fast\Random;
use think\Db;
/**
* 两性关系接口(M7)
*
* 关系测评 / 沟通引导卡 / 冲突工具 / 关系课程 / 双人任务 / 纪念回顾
*/
class Relation extends Api
{
protected $noNeedLogin = [];
protected $noNeedRight = '*';
/**
* 关系模块总览
*/
public function index()
{
$userId = $this->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(),
];
}
}

查看文件

@@ -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'],
];
}
}

查看文件

@@ -0,0 +1,197 @@
<?php
namespace app\common\service;
use think\Db;
/**
* 量表测评服务(M7 关系测评 / M9 心理测评 共用)
*
* 题目为文本数组,答案统一 0-4 五级计分;分级阈值由 scoring 字段配置。
* 危机干预:命中高风险或用「自我伤害」类题目高分时返回转介信息。
*/
class AssessmentService
{
/** 危机干预提示(合规文案,必须与人工审核口径一致) */
public static function crisis()
{
return [
'title' => '请优先照顾当下的安全',
'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' => '测评结果仅供参考,不能替代专业诊断。',
];
}
}

查看文件

@@ -0,0 +1,159 @@
<?php
namespace app\common\service;
use think\Db;
/**
* 内容服务(情绪 / 健康建议 / 话术 / 引导卡 / 课程 / 亲子活动 / 知识库 共用)
*
* 统一处理:类型筛选、阶段匹配、会员锁态、分页。
*/
class ContentService
{
/**
* 内容列表
*
* @param int $userId
* @param array $params type/phase/category_id/page/limit/part
* @return array
*/
public static function lists($userId, $params = [])
{
$type = isset($params['type']) ? $params['type'] : '';
$phase = isset($params['phase']) ? $params['phase'] : '';
$categoryId = isset($params['category_id']) ? (int)$params['category_id'] : 0;
$part = isset($params['part']) ? $params['part'] : '';
$page = max(1, isset($params['page']) ? (int)$params['page'] : 1);
$limit = min(50, max(1, isset($params['limit']) ? (int)$params['limit'] : 10));
$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();
// 课程按 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;
}
}

313
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='用户数据备份';

182
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);