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