first commit

This commit is contained in:
Your Name
2026-09-08 11:40:15 +08:00
commit a5353f7eb5
9568 changed files with 1646214 additions and 0 deletions
+111
View File
@@ -0,0 +1,111 @@
<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\api\logic;
use app\common\enum\YesNoEnum;
use app\common\logic\BaseLogic;
use app\common\model\article\Article;
use app\common\model\article\ArticleCate;
use app\common\model\article\ArticleCollect;
/**
* 文章逻辑
* Class ArticleLogic
* @package app\api\logic
*/
class ArticleLogic extends BaseLogic
{
/**
* @notes 文章详情
* @param $articleId
* @param $userId
* @return array
* @author 段誉
* @date 2022/9/20 17:09
*/
public static function detail($articleId, $userId)
{
// 文章详情
$article = Article::getArticleDetailArr($articleId);
// 关注状态
$article['collect'] = ArticleCollect::isCollectArticle($userId, $articleId);
return $article;
}
/**
* @notes 加入收藏
* @param $userId
* @param $articleId
* @author 段誉
* @date 2022/9/20 16:52
*/
public static function addCollect($articleId, $userId)
{
$where = ['user_id' => $userId, 'article_id' => $articleId];
$collect = ArticleCollect::where($where)->findOrEmpty();
if ($collect->isEmpty()) {
ArticleCollect::create([
'user_id' => $userId,
'article_id' => $articleId,
'status' => YesNoEnum::YES
]);
} else {
ArticleCollect::update([
'id' => $collect['id'],
'status' => YesNoEnum::YES
]);
}
}
/**
* @notes 取消收藏
* @param $articleId
* @param $userId
* @author 段誉
* @date 2022/9/20 16:59
*/
public static function cancelCollect($articleId, $userId)
{
ArticleCollect::update(['status' => YesNoEnum::NO], [
'user_id' => $userId,
'article_id' => $articleId,
'status' => YesNoEnum::YES
]);
}
/**
* @notes 文章分类
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 段誉
* @date 2022/9/23 14:11
*/
public static function cate()
{
return ArticleCate::field('id,name')
->where('is_show', '=', 1)
->order(['sort' => 'desc', 'id' => 'desc'])
->select()->toArray();
}
}
+118
View File
@@ -0,0 +1,118 @@
<?php
namespace app\api\logic;
use app\common\logic\BaseLogic;
use think\facade\Cache;
/**
* 聊天打开通知逻辑(患者打开会话时通知医生)
* 使用缓存存储,支持多消息队列
*/
class ChatNotifyLogic extends BaseLogic
{
const CACHE_PREFIX = 'chat_open_notify:';
const CACHE_TTL = 86400; // 24小时
const MAX_PER_DOCTOR = 50; // 每个医生最多保留条数
/**
* 添加患者打开会话通知
* @param int $doctorId 医生ID (admin_id)
* @param string $patientId 患者/诊单ID
* @param string $patientName 患者姓名
* @return bool
*/
public static function addNotify(int $doctorId, string $patientId, string $patientName): bool
{
$key = self::CACHE_PREFIX . $doctorId;
$item = [
'id' => uniqid('', true),
'type' => 'patient_opened_chat',
'doctor_id' => $doctorId,
'patient_id' => $patientId,
'patient_name' => $patientName,
'created_at' => time(),
];
$list = Cache::get($key) ?: [];
if (!is_array($list)) {
$list = [];
}
array_unshift($list, $item);
$list = array_slice($list, 0, self::MAX_PER_DOCTOR);
Cache::set($key, $list, self::CACHE_TTL);
return true;
}
/**
* 患者离开会话页/诊室时通知医生端(管理后台轮询)
*/
public static function addPatientLeftNotify(int $doctorId, string $patientId, string $patientName): bool
{
$key = self::CACHE_PREFIX . $doctorId;
$item = [
'id' => uniqid('', true),
'type' => 'patient_left_chat',
'doctor_id' => $doctorId,
'patient_id' => $patientId,
'patient_name' => $patientName,
'created_at' => time(),
];
$list = Cache::get($key) ?: [];
if (!is_array($list)) {
$list = [];
}
array_unshift($list, $item);
$list = array_slice($list, 0, self::MAX_PER_DOCTOR);
Cache::set($key, $list, self::CACHE_TTL);
return true;
}
/**
* 添加面诊结束通知(医生完成接诊后通知对应医助)
* @param int $assistantId 医助ID (admin_id)
* @param string $patientName 患者姓名
* @param string $doctorName 医生姓名
* @param int $diagnosisId 诊单ID
* @return bool
*/
public static function addConsultationCompleteNotify(int $assistantId, string $patientName, string $doctorName, int $diagnosisId = 0): bool
{
$key = self::CACHE_PREFIX . $assistantId;
$item = [
'id' => uniqid('', true),
'type' => 'consultation_complete',
'assistant_id' => $assistantId,
'patient_name' => $patientName,
'doctor_name' => $doctorName,
'diagnosis_id' => $diagnosisId,
'created_at' => time(),
];
$list = Cache::get($key) ?: [];
if (!is_array($list)) {
$list = [];
}
array_unshift($list, $item);
$list = array_slice($list, 0, self::MAX_PER_DOCTOR);
Cache::set($key, $list, self::CACHE_TTL);
return true;
}
/**
* 获取未读通知(医生/医助通用,按 admin_id 获取)
* @param int $adminId 管理员ID (医生或医助)
* @param bool $consume 是否消费(移除)已获取的
* @return array
*/
public static function getNotifies(int $adminId, bool $consume = true): array
{
$key = self::CACHE_PREFIX . $adminId;
$list = Cache::get($key) ?: [];
if (!is_array($list)) {
$list = [];
}
if ($consume && !empty($list)) {
Cache::delete($key);
}
return $list;
}
}
+222
View File
@@ -0,0 +1,222 @@
<?php
namespace app\api\logic;
use app\common\logic\BaseLogic;
use app\common\model\auth\Admin;
use app\common\model\auth\AdminRole;
use app\common\model\doctor\Roster;
use app\common\model\doctor\Appointment;
/**
* 医生逻辑层
* Class DoctorLogic
* @package app\api\logic
*/
class DoctorLogic extends BaseLogic
{
/**
* @notes 获取医生列表
* @param array $params
* @return array
*/
public static function getDoctorList($params = [])
{
$page_no = $params['page_no'] ?? 1;
$page_size = $params['page_size'] ?? 10;
$keyword = $params['keyword'] ?? '';
$offset = ($page_no - 1) * $page_size;
// 通过中间表 zyt_admin_role 查询 role_id = 1 的医生
$adminIds = AdminRole::where('role_id', 1)->column('admin_id');
if (empty($adminIds)) {
return [
'lists' => [],
'count' => 0,
'page_no' => $page_no,
'page_size' => $page_size
];
}
$query = Admin::whereIn('id', $adminIds)
->where('disable', 0);
// 搜索关键词
if (!empty($keyword)) {
$query->where('name|account', 'like', '%' . $keyword . '%');
}
$lists = $query->field(['id', 'name', 'account', 'avatar', 'title','specialty'])
->limit($offset, $page_size)
->order('id asc')
->select()
->toArray();
// 处理医生数据
$doctors = [];
foreach ($lists as $doctor) {
$doctors[] = [
'id' => $doctor['id'],
'name' => $doctor['name'],
'account' => $doctor['account'],
'avatar' => $doctor['avatar'] ?? '',
'specialty' => $doctor['specialty'], // 可根据需要扩展
'title' => $doctor['title'], // 可根据需要扩展
'rating' => '9.8', // 可根据需要从其他表获取
];
}
// 获取总数
$countQuery = Admin::whereIn('id', $adminIds)
->where('disable', 0);
if (!empty($keyword)) {
$countQuery->where('name|account', 'like', '%' . $keyword . '%');
}
$count = $countQuery->count();
return [
'lists' => $doctors,
'count' => $count,
'page_no' => $page_no,
'page_size' => $page_size
];
}
/**
* @notes 获取医生详情(含完整档案信息)
* @param int $doctorId
* @return array|null
*/
public static function getDoctorDetail($doctorId)
{
// 检查该医生是否有医生角色(role_id = 1)
$hasRole = AdminRole::where('admin_id', $doctorId)
->where('role_id', 1)
->count() > 0;
if (!$hasRole) {
return null;
}
$doctor = Admin::where('id', $doctorId)
->where('disable', 0)
->field(['id', 'name', 'account','experience', 'title','qualification_images','avatar','specialty','license_no','qualification_images','enable_image_consult','enable_video_consult','enable_charge'])
->find();
if (!$doctor) {
return null;
}
$doctorData = $doctor->toArray();
// 统计患者数(已完成预约,去重)
$patientIds = Appointment::where('doctor_id', $doctorId)
->where('status', 3)
->column('patient_id');
$patientCount = count(array_unique(array_filter($patientIds)));
return [
'id' => $doctorData['id'],
'name' => $doctorData['name'],
'account' => $doctorData['account'],
'avatar' => $doctorData['avatar'] ?? '',
'mobile' => $doctorData['mobile'] ?? '',
'email' => $doctorData['email'] ?? '',
'license_no' => $doctorData['license_no'] ?? '',
'qualification_images' => $doctorData['qualification_images'] ?? '',
'enable_image_consult' => $doctorData['enable_image_consult'] ?? 1,
'enable_video_consult' => $doctorData['enable_video_consult'] ?? 1,
'enable_charge' => $doctorData['enable_charge'] ?? 0,
'specialty' => $doctorData['specialty']??'中医',
'title' => $doctorData['title'],
'hospital' => '甄养堂互联网医院',
'experience' => $doctorData['experience']??'10+年临床经验',
'rating' => '4.9',
'patient_count' => $patientCount,
'papers' => 15,
'about' => $doctorData['specialty'] ?? '擅长运用传统中医理论与现代诊断相结合,专注于慢性炎症及呼吸系统健康的调理。精通草本方剂,致力于为患者提供个性化的整体康复方案。',
'expertise' => [
['icon' => 'psychiatry', 'title' => '草本药方', 'desc' => '为整体康复提供量身定制的草本处方。'],
['icon' => 'eco', 'title' => '草本药方', 'desc' => '为整体康复提供量身定制的草本处方。'],
['icon' => 'vital_signs', 'title' => '切脉诊断', 'desc' => '运用传统方法对全身平衡和器官健康进行深度触诊评估。', 'wide' => true],
],
];
}
/**
* @notes 获取医生评价列表
* @param int $doctorId
* @param int $pageNo
* @param int $pageSize
* @return array
*/
public static function getDoctorReviews($doctorId, $pageNo = 1, $pageSize = 10)
{
$hasRole = AdminRole::where('admin_id', $doctorId)
->where('role_id', 1)
->count() > 0;
if (!$hasRole) {
return ['lists' => [], 'count' => 0];
}
// 默认评价数据(后续可扩展为独立评价表)
$defaultReviews = [
[
'id' => 1,
'patient_initials' => 'JS',
'patient_name' => 'James S.',
'rating' => 5,
'content' => '对我慢性疲劳的治疗改变了我的生活。他在建议方剂之前足足听我倾诉了45分钟。真是一位大师级的人物。',
'create_time' => '2天前',
],
[
'id' => 2,
'patient_initials' => 'ML',
'patient_name' => 'Mei Ling',
'rating' => 5,
'content' => '非常专业,知识渊博。针灸疗程显著缓解了我的偏头痛。非常推荐这家医院。',
'create_time' => '1周前',
],
];
$offset = ($pageNo - 1) * $pageSize;
$lists = array_slice($defaultReviews, $offset, $pageSize);
return [
'lists' => $lists,
'count' => count($defaultReviews),
'page_no' => $pageNo,
'page_size' => $pageSize,
];
}
/**
* @notes 获取医生排班
* @param int $doctorId
* @param string $date
* @return array
*/
public static function getDoctorRoster($doctorId, $date)
{
// 检查该医生是否有医生角色
$hasRole = AdminRole::where('admin_id', $doctorId)
->where('role_id', 1)
->count() > 0;
if (!$hasRole) {
return [];
}
$rosters = Roster::where('doctor_id', $doctorId)
->where('date', $date)
->select()
->toArray();
return $rosters;
}
}
+160
View File
@@ -0,0 +1,160 @@
<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\api\logic;
use app\common\logic\BaseLogic;
use app\common\model\article\Article;
use app\common\model\decorate\DecoratePage;
use app\common\model\decorate\DecorateTabbar;
use app\common\service\ConfigService;
use app\common\service\FileService;
/**
* index
* Class IndexLogic
* @package app\api\logic
*/
class IndexLogic extends BaseLogic
{
/**
* @notes 首页数据
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 段誉
* @date 2022/9/21 19:15
*/
public static function getIndexData()
{
// 装修配置
$decoratePage = DecoratePage::findOrEmpty(1);
// 首页文章
$field = [
'id', 'title', 'desc', 'abstract', 'image',
'author', 'click_actual', 'click_virtual', 'create_time'
];
$article = Article::field($field)
->where(['is_show' => 1])
->order(['id' => 'desc'])
->limit(20)->append(['click'])
->hidden(['click_actual', 'click_virtual'])
->select()->toArray();
return [
'page' => $decoratePage,
'article' => $article
];
}
/**
* @notes 获取政策协议
* @param string $type
* @return array
* @author 段誉
* @date 2022/9/20 20:00
*/
public static function getPolicyByType(string $type)
{
return [
'title' => ConfigService::get('agreement', $type . '_title', ''),
'content' => get_file_domain(ConfigService::get('agreement', $type . '_content', '')),
];
}
/**
* @notes 装修信息
* @param $id
* @return array
* @author 段誉
* @date 2022/9/21 18:37
*/
public static function getDecorate($id)
{
return DecoratePage::field(['type', 'name', 'data', 'meta'])
->findOrEmpty($id)->toArray();
}
/**
* @notes 获取配置
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 段誉
* @date 2022/9/21 19:38
*/
public static function getConfigData()
{
// 底部导航
$tabbar = DecorateTabbar::getTabbarLists();
// 导航颜色
$style = ConfigService::get('tabbar', 'style', config('project.decorate.tabbar_style'));
// 登录配置
$loginConfig = [
// 登录方式
'login_way' => ConfigService::get('login', 'login_way', config('project.login.login_way')),
// 注册强制绑定手机
'coerce_mobile' => ConfigService::get('login', 'coerce_mobile', config('project.login.coerce_mobile')),
// 政策协议
'login_agreement' => ConfigService::get('login', 'login_agreement', config('project.login.login_agreement')),
// 第三方登录 开关
'third_auth' => ConfigService::get('login', 'third_auth', config('project.login.third_auth')),
// 微信授权登录
'wechat_auth' => ConfigService::get('login', 'wechat_auth', config('project.login.wechat_auth')),
// qq授权登录
'qq_auth' => ConfigService::get('login', 'qq_auth', config('project.login.qq_auth')),
];
// 网址信息
$website = [
'h5_favicon' => FileService::getFileUrl(ConfigService::get('website', 'h5_favicon')),
'shop_name' => ConfigService::get('website', 'shop_name'),
'shop_logo' => FileService::getFileUrl(ConfigService::get('website', 'shop_logo')),
];
// H5配置
$webPage = [
// 渠道状态 0-关闭 1-开启
'status' => ConfigService::get('web_page', 'status', 1),
// 关闭后渠道后访问页面 0-空页面 1-自定义链接
'page_status' => ConfigService::get('web_page', 'page_status', 0),
// 自定义链接
'page_url' => ConfigService::get('web_page', 'page_url', ''),
'url' => request()->domain() . '/mobile'
];
// 备案信息
$copyright = ConfigService::get('copyright', 'config', []);
return [
'domain' => FileService::getFileUrl(),
'style' => $style,
'tabbar' => $tabbar,
'login' => $loginConfig,
'website' => $website,
'webPage' => $webPage,
'version'=> config('project.version'),
'copyright' => $copyright,
];
}
}
+433
View File
@@ -0,0 +1,433 @@
<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\api\logic;
use app\common\cache\WebScanLoginCache;
use app\common\logic\BaseLogic;
use app\api\service\{UserTokenService, WechatUserService};
use app\common\enum\{LoginEnum, user\UserTerminalEnum, YesNoEnum};
use app\common\service\{
ConfigService,
FileService,
wechat\WeChatConfigService,
wechat\WeChatMnpService,
wechat\WeChatOaService,
wechat\WeChatRequestService
};
use app\common\model\user\{User, UserAuth};
use think\facade\{Db, Config};
/**
* 登录逻辑
* Class LoginLogic
* @package app\api\logic
*/
class LoginLogic extends BaseLogic
{
/**
* @notes 账号密码注册
* @param array $params
* @return bool
* @author 段誉
* @date 2022/9/7 15:37
*/
public static function register(array $params)
{
try {
$userSn = User::createUserSn();
$passwordSalt = Config::get('project.unique_identification');
$password = create_password($params['password'], $passwordSalt);
$avatar = ConfigService::get('default_image', 'user_avatar');
User::create([
'sn' => $userSn,
'avatar' => $avatar,
'nickname' => '用户' . $userSn,
'account' => $params['account'],
'password' => $password,
'channel' => $params['channel'],
]);
return true;
} catch (\Exception $e) {
self::setError($e->getMessage());
return false;
}
}
/**
* @notes 账号/手机号登录,手机号验证码
* @param $params
* @return array|false
* @author 段誉
* @date 2022/9/6 19:26
*/
public static function login($params)
{
try {
// 账号/手机号 密码登录
$where = ['account|mobile' => $params['account']];
if ($params['scene'] == LoginEnum::MOBILE_CAPTCHA) {
//手机验证码登录
$where = ['mobile' => $params['account']];
}
$user = User::where($where)->findOrEmpty();
if ($user->isEmpty()) {
throw new \Exception('用户不存在');
}
//更新登录信息
$user->login_time = time();
$user->login_ip = request()->ip();
$user->save();
//设置token
$userInfo = UserTokenService::setToken($user->id, $params['terminal']);
//返回登录信息
$avatar = $user->avatar ?: Config::get('project.default_image.user_avatar');
$avatar = FileService::getFileUrl($avatar);
return [
'nickname' => $userInfo['nickname'],
'sn' => $userInfo['sn'],
'mobile' => $userInfo['mobile'],
'avatar' => $avatar,
'token' => $userInfo['token'],
];
} catch (\Exception $e) {
self::setError($e->getMessage());
return false;
}
}
/**
* @notes 退出登录
* @param $userInfo
* @return bool
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 段誉
* @date 2022/9/16 17:56
*/
public static function logout($userInfo)
{
//token不存在,不注销
if (!isset($userInfo['token'])) {
return false;
}
//设置token过期
return UserTokenService::expireToken($userInfo['token']);
}
/**
* @notes 获取微信请求code的链接
* @param string $url
* @return string
* @author 段誉
* @date 2022/9/20 19:47
*/
public static function codeUrl(string $url)
{
return (new WeChatOaService())->getCodeUrl($url);
}
/**
* @notes 公众号登录
* @param array $params
* @return array|false
* @throws \GuzzleHttp\Exception\GuzzleException
* @author 段誉
* @date 2022/9/20 19:47
*/
public static function oaLogin(array $params)
{
Db::startTrans();
try {
//通过code获取微信 openid
$response = (new WeChatOaService())->getOaResByCode($params['code']);
$userServer = new WechatUserService($response, UserTerminalEnum::WECHAT_OA);
$userInfo = $userServer->getResopnseByUserInfo()->authUserLogin()->getUserInfo();
// 更新登录信息
self::updateLoginInfo($userInfo['id']);
Db::commit();
return $userInfo;
} catch (\Exception $e) {
Db::rollback();
self::$error = $e->getMessage();
return false;
}
}
/**
* @notes 小程序-静默登录
* @param array $params
* @return array|false
* @author 段誉
* @date 2022/9/20 19:47
*/
public static function silentLogin(array $params)
{
try {
//通过code获取微信 openid
$response = (new WeChatMnpService())->getMnpResByCode($params['code']);
$userServer = new WechatUserService($response, UserTerminalEnum::WECHAT_MMP);
$userInfo = $userServer->getResopnseByUserInfo('silent')->getUserInfo();
if (!empty($userInfo)) {
// 更新登录信息
self::updateLoginInfo($userInfo['id']);
}
return $userInfo;
} catch (\Exception $e) {
self::$error = $e->getMessage();
return false;
}
}
/**
* @notes 小程序-授权登录
* @param array $params
* @return array|false
* @author 段誉
* @date 2022/9/20 19:47
*/
public static function mnpLogin(array $params)
{
Db::startTrans();
try {
//通过code获取微信 openid
$response = (new WeChatMnpService())->getMnpResByCode($params['code']);
$userServer = new WechatUserService($response, UserTerminalEnum::WECHAT_MMP);
$userInfo = $userServer->getResopnseByUserInfo()->authUserLogin()->getUserInfo();
// 更新登录信息
self::updateLoginInfo($userInfo['id']);
Db::commit();
return $userInfo;
} catch (\Exception $e) {
Db::rollback();
self::$error = $e->getMessage();
return false;
}
}
/**
* @notes 更新登录信息
* @param $userId
* @throws \Exception
* @author 段誉
* @date 2022/9/20 19:46
*/
public static function updateLoginInfo($userId)
{
$user = User::findOrEmpty($userId);
if ($user->isEmpty()) {
throw new \Exception('用户不存在');
}
$time = time();
$user->login_time = $time;
$user->login_ip = request()->ip();
$user->update_time = $time;
$user->save();
}
/**
* @notes 小程序端绑定微信
* @param array $params
* @return bool
* @author 段誉
* @date 2022/9/20 19:46
*/
public static function mnpAuthLogin(array $params)
{
try {
//通过code获取微信openid
$response = (new WeChatMnpService())->getMnpResByCode($params['code']);
$response['user_id'] = $params['user_id'];
$response['terminal'] = UserTerminalEnum::WECHAT_MMP;
return self::createAuth($response);
} catch (\Exception $e) {
self::$error = $e->getMessage();
return false;
}
}
/**
* @notes 公众号端绑定微信
* @param array $params
* @return bool
* @throws \GuzzleHttp\Exception\GuzzleException
* @author 段誉
* @date 2022/9/16 10:43
*/
public static function oaAuthLogin(array $params)
{
try {
//通过code获取微信openid
$response = (new WeChatOaService())->getOaResByCode($params['code']);
$response['user_id'] = $params['user_id'];
$response['terminal'] = UserTerminalEnum::WECHAT_OA;
return self::createAuth($response);
} catch (\Exception $e) {
self::$error = $e->getMessage();
return false;
}
}
/**
* @notes 生成授权记录
* @param $response
* @return bool
* @throws \Exception
* @author 段誉
* @date 2022/9/16 10:43
*/
public static function createAuth($response)
{
//先检查openid是否有记录
$isAuth = UserAuth::where('openid', '=', $response['openid'])->findOrEmpty();
if (!$isAuth->isEmpty()) {
throw new \Exception('该微信已被绑定');
}
if (isset($response['unionid']) && !empty($response['unionid'])) {
//在用unionid找记录,防止生成两个账号,同个unionid的问题
$userAuth = UserAuth::where(['unionid' => $response['unionid']])
->findOrEmpty();
if (!$userAuth->isEmpty() && $userAuth->user_id != $response['user_id']) {
throw new \Exception('该微信已被绑定');
}
}
//如果没有授权,直接生成一条微信授权记录
UserAuth::create([
'user_id' => $response['user_id'],
'openid' => $response['openid'],
'unionid' => $response['unionid'] ?? '',
'terminal' => $response['terminal'],
]);
return true;
}
/**
* @notes 获取扫码登录地址
* @return array|false
* @author 段誉
* @date 2022/10/20 18:23
*/
public static function getScanCode($redirectUri)
{
try {
$config = WeChatConfigService::getOpConfig();
$appId = $config['app_id'];
$redirectUri = UrlEncode($redirectUri);
// 设置有效时间标记状态, 超时扫码不可登录
$state = MD5(time().rand(10000, 99999));
(new WebScanLoginCache())->setScanLoginState($state);
// 扫码地址
$url = WeChatRequestService::getScanCodeUrl($appId, $redirectUri, $state);
return ['url' => $url];
} catch (\Exception $e) {
self::$error = $e->getMessage();
return false;
}
}
/**
* @notes 网站扫码登录
* @param $params
* @return array|false
* @author 段誉
* @date 2022/10/21 10:28
*/
public static function scanLogin($params)
{
Db::startTrans();
try {
// 通过code 获取 access_token,openid,unionid等信息
$userAuth = WeChatRequestService::getUserAuthByCode($params['code']);
if (empty($userAuth['openid']) || empty($userAuth['access_token'])) {
throw new \Exception('获取用户授权信息失败');
}
// 获取微信用户信息
$response = WeChatRequestService::getUserInfoByAuth($userAuth['access_token'], $userAuth['openid']);
// 生成用户或更新用户信息
$userServer = new WechatUserService($response, UserTerminalEnum::PC);
$userInfo = $userServer->getResopnseByUserInfo()->authUserLogin()->getUserInfo();
// 更新登录信息
self::updateLoginInfo($userInfo['id']);
Db::commit();
return $userInfo;
} catch (\Exception $e) {
Db::rollback();
self::$error = $e->getMessage();
return false;
}
}
/**
* @notes 更新用户信息
* @param $params
* @param $userId
* @return User
* @author 段誉
* @date 2023/2/22 11:19
*/
public static function updateUser($params, $userId)
{
return User::where(['id' => $userId])->update([
'nickname' => $params['nickname'],
'avatar' => FileService::setFileUrl($params['avatar']),
'is_new_user' => YesNoEnum::NO
]);
}
}
+246
View File
@@ -0,0 +1,246 @@
<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\api\logic;
use app\common\enum\YesNoEnum;
use app\common\logic\BaseLogic;
use app\common\model\article\Article;
use app\common\model\article\ArticleCate;
use app\common\model\article\ArticleCollect;
use app\common\model\decorate\DecoratePage;
use app\common\service\ConfigService;
use app\common\service\FileService;
/**
* index
* Class IndexLogic
* @package app\api\logic
*/
class PcLogic extends BaseLogic
{
/**
* @notes 首页数据
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 段誉
* @date 2022/9/21 19:15
*/
public static function getIndexData()
{
// 装修配置
$decoratePage = DecoratePage::findOrEmpty(4);
// 最新资讯
$newArticle = self::getLimitArticle('new', 7);
// 全部资讯
$allArticle = self::getLimitArticle('all', 5);
// 热门资讯
$hotArticle = self::getLimitArticle('hot', 8);
return [
'page' => $decoratePage,
'all' => $allArticle,
'new' => $newArticle,
'hot' => $hotArticle
];
}
/**
* @notes 获取文章
* @param string $sortType
* @param int $limit
* @return mixed
* @author 段誉
* @date 2022/10/19 9:53
*/
public static function getLimitArticle(string $sortType, int $limit = 0, int $cate = 0, int $excludeId = 0)
{
// 查询字段
$field = [
'id', 'cid', 'title', 'desc', 'abstract', 'image',
'author', 'click_actual', 'click_virtual', 'create_time'
];
// 排序条件
$orderRaw = 'sort desc, id desc';
if ($sortType == 'new') {
$orderRaw = 'id desc';
}
if ($sortType == 'hot') {
$orderRaw = 'click_actual + click_virtual desc, id desc';
}
// 查询条件
$where[] = ['is_show', '=', YesNoEnum::YES];
if (!empty($cate)) {
$where[] = ['cid', '=', $cate];
}
if (!empty($excludeId)) {
$where[] = ['id', '<>', $excludeId];
}
$article = Article::field($field)
->where($where)
->append(['click'])
->orderRaw($orderRaw)
->hidden(['click_actual', 'click_virtual']);
if ($limit) {
$article->limit($limit);
}
return $article->select()->toArray();
}
/**
* @notes 获取配置
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 段誉
* @date 2022/9/21 19:38
*/
public static function getConfigData()
{
// 登录配置
$loginConfig = [
// 登录方式
'login_way' => ConfigService::get('login', 'login_way', config('project.login.login_way')),
// 注册强制绑定手机
'coerce_mobile' => ConfigService::get('login', 'coerce_mobile', config('project.login.coerce_mobile')),
// 政策协议
'login_agreement' => ConfigService::get('login', 'login_agreement', config('project.login.login_agreement')),
// 第三方登录 开关
'third_auth' => ConfigService::get('login', 'third_auth', config('project.login.third_auth')),
// 微信授权登录
'wechat_auth' => ConfigService::get('login', 'wechat_auth', config('project.login.wechat_auth')),
// qq授权登录
'qq_auth' => ConfigService::get('login', 'qq_auth', config('project.login.qq_auth')),
];
// 网站信息
$website = [
'shop_name' => ConfigService::get('website', 'shop_name'),
'shop_logo' => FileService::getFileUrl(ConfigService::get('website', 'shop_logo')),
'pc_logo' => FileService::getFileUrl(ConfigService::get('website', 'pc_logo')),
'pc_title' => ConfigService::get('website', 'pc_title'),
'pc_ico' => FileService::getFileUrl(ConfigService::get('website', 'pc_ico')),
'pc_desc' => ConfigService::get('website', 'pc_desc'),
'pc_keywords' => ConfigService::get('website', 'pc_keywords'),
];
// 站点统计
$siteStatistics = [
'clarity_code' => ConfigService::get('siteStatistics', 'clarity_code'),
];
// 备案信息
$copyright = ConfigService::get('copyright', 'config', []);
// 公众号二维码
$oaQrCode = ConfigService::get('oa_setting', 'qr_code', '');
$oaQrCode = empty($oaQrCode) ? $oaQrCode : FileService::getFileUrl($oaQrCode);
// 小程序二维码
$mnpQrCode = ConfigService::get('mnp_setting', 'qr_code', '');
$mnpQrCode = empty($mnpQrCode) ? $mnpQrCode : FileService::getFileUrl($mnpQrCode);
return [
'domain' => FileService::getFileUrl(),
'login' => $loginConfig,
'website' => $website,
'siteStatistics' => $siteStatistics,
'version' => config('project.version'),
'copyright' => $copyright,
'admin_url' => request()->domain() . '/admin',
'qrcode' => [
'oa' => $oaQrCode,
'mnp' => $mnpQrCode,
]
];
}
/**
* @notes 资讯中心
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 段誉
* @date 2022/10/19 16:55
*/
public static function getInfoCenter()
{
$data = ArticleCate::field(['id', 'name'])
->with(['article' => function ($query) {
$query->hidden(['content', 'click_virtual', 'click_actual'])
->order(['sort' => 'desc', 'id' => 'desc'])
->append(['click'])
->limit(10);
}])
->where(['is_show' => YesNoEnum::YES])
->order(['sort' => 'desc', 'id' => 'desc'])
->select()
->toArray();
return $data;
}
/**
* @notes 获取文章详情
* @param $userId
* @param $articleId
* @param string $source
* @return array
* @author 段誉
* @date 2022/10/20 15:18
*/
public static function getArticleDetail($userId, $articleId, $source = 'default')
{
// 文章详情
$detail = Article::getArticleDetailArr($articleId);
// 根据来源列表查找对应列表
$nowIndex = 0;
$lists = self::getLimitArticle($source, 0, $detail['cid']);
foreach ($lists as $key => $item) {
if ($item['id'] == $articleId) {
$nowIndex = $key;
}
}
// 上一篇
$detail['last'] = $lists[$nowIndex - 1] ?? [];
// 下一篇
$detail['next'] = $lists[$nowIndex + 1] ?? [];
// 最新资讯
$detail['new'] = self::getLimitArticle('new', 8, $detail['cid'], $detail['id']);
// 关注状态
$detail['collect'] = ArticleCollect::isCollectArticle($userId, $articleId);
// 分类名
$detail['cate_name'] = ArticleCate::where('id', $detail['cid'])->value('name');
return $detail;
}
}
+85
View File
@@ -0,0 +1,85 @@
<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\api\logic;
use app\common\enum\PayEnum;
use app\common\logic\BaseLogic;
use app\common\model\recharge\RechargeOrder;
use app\common\model\user\User;
use app\common\service\ConfigService;
/**
* 充值逻辑层
* Class RechargeLogic
* @package app\shopapi\logic
*/
class RechargeLogic extends BaseLogic
{
/**
* @notes 充值
* @param array $params
* @return array|false
* @author 段誉
* @date 2023/2/24 10:43
*/
public static function recharge(array $params)
{
try {
$data = [
'sn' => generate_sn(RechargeOrder::class, 'sn'),
'order_terminal' => $params['terminal'],
'user_id' => $params['user_id'],
'pay_status' => PayEnum::UNPAID,
'order_amount' => $params['money'],
];
$order = RechargeOrder::create($data);
return [
'order_id' => (int)$order['id'],
'from' => 'recharge'
];
} catch (\Exception $e) {
self::setError($e->getMessage());
return false;
}
}
/**
* @notes 充值配置
* @param $userId
* @return array
* @author 段誉
* @date 2023/2/24 16:56
*/
public static function config($userId)
{
$userMoney = User::where(['id' => $userId])->value('user_money');
$minAmount = ConfigService::get('recharge', 'min_amount', 0);
$status = ConfigService::get('recharge', 'status', 0);
return [
'status' => $status,
'min_amount' => $minAmount,
'user_money' => $userMoney,
];
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\api\logic;
use app\common\logic\BaseLogic;
use app\common\model\HotSearch;
use app\common\service\ConfigService;
/**
* 搜索逻辑
* Class SearchLogic
* @package app\api\logic
*/
class SearchLogic extends BaseLogic
{
/**
* @notes 热搜列表
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 段誉
* @date 2022/9/23 14:34
*/
public static function hotLists()
{
$data = HotSearch::field(['name', 'sort'])
->order(['sort' => 'desc', 'id' => 'desc'])
->select()->toArray();
return [
// 功能状态 0-关闭 1-开启
'status' => ConfigService::get('hot_search', 'status', 0),
// 热门搜索数据
'data' => $data,
];
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\api\logic;
use app\common\enum\notice\NoticeEnum;
use app\common\logic\BaseLogic;
/**
* 短信逻辑
* Class SmsLogic
* @package app\api\logic
*/
class SmsLogic extends BaseLogic
{
/**
* @notes 发送验证码
* @param $params
* @return false|mixed
* @author 段誉
* @date 2022/9/15 16:17
*/
public static function sendCode($params)
{
try {
$scene = NoticeEnum::getSceneByTag($params['scene']);
if (empty($scene)) {
throw new \Exception('场景值异常');
}
$result = event('Notice', [
'scene_id' => $scene,
'params' => [
'mobile' => $params['mobile'],
'code' => mt_rand(1000, 9999),
]
]);
return $result[0];
} catch (\Exception $e) {
self::$error = $e->getMessage();
return false;
}
}
}
+323
View File
@@ -0,0 +1,323 @@
<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\api\logic;
use app\common\{enum\notice\NoticeEnum,
enum\user\UserTerminalEnum,
enum\YesNoEnum,
logic\BaseLogic,
model\user\User,
model\user\UserAuth,
service\FileService,
service\sms\SmsDriver,
service\wechat\WeChatMnpService};
use think\facade\Config;
/**
* 会员逻辑层
* Class UserLogic
* @package app\shopapi\logic
*/
class UserLogic extends BaseLogic
{
/**
* @notes 个人中心
* @param array $userInfo
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 段誉
* @date 2022/9/16 18:04
*/
public static function center(array $userInfo): array
{
$user = User::where(['id' => $userInfo['user_id']])
->field('id,sn,sex,account,nickname,real_name,avatar,mobile,create_time,is_new_user,user_money,password')
->findOrEmpty();
if (in_array($userInfo['terminal'], [UserTerminalEnum::WECHAT_MMP, UserTerminalEnum::WECHAT_OA])) {
$auth = UserAuth::where(['user_id' => $userInfo['user_id'], 'terminal' => $userInfo['terminal']])->find();
$user['is_auth'] = $auth ? YesNoEnum::YES : YesNoEnum::NO;
}
$user['has_password'] = !empty($user['password']);
$user->hidden(['password']);
return $user->toArray();
}
/**
* @notes 个人信息
* @param $userId
* @return array
* @author 段誉
* @date 2022/9/20 19:45
*/
public static function info(int $userId)
{
$user = User::where(['id' => $userId])
->with('diagnosis')
->field('id,sn,sex,account,password,nickname,real_name,avatar,mobile,age,create_time,user_money')
->findOrEmpty();
$user['has_password'] = !empty($user['password']);
$user['has_auth'] = self::hasWechatAuth($userId);
$user['version'] = config('project.version');
$user->hidden(['password']);
// 字段映射,便于前端使用
$result = $user->toArray();
$result['phone'] = $result['mobile'] ?? '';
$result['gender'] = $result['sex'] ?? 1;
$result['patient_name'] = $result['real_name'] ?? '';
return $result;
}
/**
* @notes 设置用户信息
* @param int $userId
* @param array $params
* @return bool
* @author 段誉
* @date 2022/9/21 16:53
*/
public static function setInfo(int $userId, array $params)
{
try {
// 支持批量更新多个字段
$updateData = ['id' => $userId];
// 字段映射
$fieldMap = [
'avatar' => 'avatar',
'phone' => 'mobile',
'nickname' => 'nickname',
'sex' => 'sex',
'age' => 'age',
'patient_name' => 'real_name'
];
// 处理头像
if (isset($params['avatar']) && !empty($params['avatar'])) {
$updateData['avatar'] = FileService::setFileUrl($params['avatar']);
}
// 处理其他字段
foreach ($fieldMap as $key => $field) {
if ($key !== 'avatar' && isset($params[$key])) {
$updateData[$field] = $params[$key];
}
}
User::update($updateData);
return true;
} catch (\Exception $e) {
self::$error = $e->getMessage();
return false;
}
}
/**
* @notes 是否有微信授权信息
* @param $userId
* @return bool
* @author 段誉
* @date 2022/9/20 19:36
*/
public static function hasWechatAuth(int $userId)
{
//是否有微信授权登录
$terminal = [UserTerminalEnum::WECHAT_MMP, UserTerminalEnum::WECHAT_OA,UserTerminalEnum::PC];
$auth = UserAuth::where(['user_id' => $userId])
->whereIn('terminal', $terminal)
->findOrEmpty();
return !$auth->isEmpty();
}
/**
* @notes 重置登录密码
* @param $params
* @return bool
* @author 段誉
* @date 2022/9/16 18:06
*/
public static function resetPassword(array $params)
{
try {
// 校验验证码
$smsDriver = new SmsDriver();
if (!$smsDriver->verify($params['mobile'], $params['code'], NoticeEnum::FIND_LOGIN_PASSWORD_CAPTCHA)) {
throw new \Exception('验证码错误');
}
// 重置密码
$passwordSalt = Config::get('project.unique_identification');
$password = create_password($params['password'], $passwordSalt);
// 更新
User::where('mobile', $params['mobile'])->update([
'password' => $password
]);
return true;
} catch (\Exception $e) {
self::setError($e->getMessage());
return false;
}
}
/**
* @notes 修稿密码
* @param $params
* @param $userId
* @return bool
* @author 段誉
* @date 2022/9/20 19:13
*/
public static function changePassword(array $params, int $userId)
{
try {
$user = User::findOrEmpty($userId);
if ($user->isEmpty()) {
throw new \Exception('用户不存在');
}
// 密码盐
$passwordSalt = Config::get('project.unique_identification');
if (!empty($user['password'])) {
if (empty($params['old_password'])) {
throw new \Exception('请填写旧密码');
}
$oldPassword = create_password($params['old_password'], $passwordSalt);
if ($oldPassword != $user['password']) {
throw new \Exception('原密码不正确');
}
}
// 保存密码
$password = create_password($params['password'], $passwordSalt);
$user->password = $password;
$user->save();
return true;
} catch (\Exception $e) {
self::setError($e->getMessage());
return false;
}
}
/**
* @notes 获取小程序手机号
* @param array $params
* @return bool
* @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
* @author 段誉
* @date 2023/2/27 11:49
*/
public static function getMobileByMnp(array $params)
{
try {
$response = (new WeChatMnpService())->getUserPhoneNumber($params['code']);
$phoneNumber = $response['phone_info']['purePhoneNumber'] ?? '';
if (empty($phoneNumber)) {
throw new \Exception('获取手机号码失败');
}
$user = User::where([
['mobile', '=', $phoneNumber],
['id', '<>', $params['user_id']]
])->findOrEmpty();
if (!$user->isEmpty()) {
throw new \Exception('手机号已被其他账号绑定');
}
// 绑定手机号
$update = [
'id' => $params['user_id'],
'mobile' => $phoneNumber,
];
if (isset($params['sex']) && in_array((int) $params['sex'], [1, 2], true)) {
$update['sex'] = (int) $params['sex'];
}
User::update($update);
return true;
} catch (\Exception $e) {
self::setError($e->getMessage());
return false;
}
}
/**
* @notes 绑定手机号
* @param $params
* @return bool
* @author 段誉
* @date 2022/9/21 17:28
*/
public static function bindMobile(array $params)
{
try {
// 变更手机号场景
$sceneId = NoticeEnum::CHANGE_MOBILE_CAPTCHA;
$where = [
['id', '=', $params['user_id']],
['mobile', '=', $params['mobile']]
];
// 绑定手机号场景
if ($params['type'] == 'bind') {
$sceneId = NoticeEnum::BIND_MOBILE_CAPTCHA;
$where = [
['mobile', '=', $params['mobile']]
];
}
// 校验短信
$checkSmsCode = (new SmsDriver())->verify($params['mobile'], $params['code'], $sceneId);
if (!$checkSmsCode) {
throw new \Exception('验证码错误');
}
$user = User::where($where)->findOrEmpty();
if (!$user->isEmpty()) {
throw new \Exception('该手机号已被使用');
}
User::update([
'id' => $params['user_id'],
'mobile' => $params['mobile'],
]);
return true;
} catch (\Exception $e) {
self::setError($e->getMessage());
return false;
}
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\api\logic;
use app\common\logic\BaseLogic;
use app\common\service\wechat\WeChatOaService;
use EasyWeChat\Kernel\Exceptions\Exception;
/**
* 微信
* Class WechatLogic
* @package app\api\logic
*/
class WechatLogic extends BaseLogic
{
/**
* @notes 微信JSSDK授权接口
* @param $params
* @return false|mixed[]
* @throws \Psr\SimpleCache\InvalidArgumentException
* @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
* @author 段誉
* @date 2023/3/1 11:49
*/
public static function jsConfig($params)
{
try {
$url = urldecode($params['url']);
return (new WeChatOaService())->getJsConfig($url, [
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'onMenuShareWeibo',
'onMenuShareQZone',
'openLocation',
'getLocation',
'chooseWXPay',
'updateAppMessageShareData',
'updateTimelineShareData',
'openAddress',
'scanQRCode'
]);
} catch (Exception $e) {
self::setError('获取jssdk失败:' . $e->getMessage());
return false;
}
}
}
@@ -0,0 +1,442 @@
<?php
namespace app\api\logic\tcm;
use app\common\model\tcm\Diagnosis;
use app\common\service\AiChatService;
use think\facade\Cache;
/**
* 日常护理 - 血糖照护 AI(累计 7 天有记录后:血糖建议 + 中医调理方向)
*/
class DailyBloodCareAiLogic
{
private const CACHE_TTL = 86400;
private const MIN_RECORD_DAYS = 7;
private const AI_TIMEOUT_SEC = 14;
private const AI_STREAM_TIMEOUT_SEC = 22;
/**
* @return array{ok:bool,error?:string,data?:array}
*/
public static function getDailyCarePlan(int $diagnosisId, bool $refresh = false): array
{
if ($diagnosisId <= 0) {
return ['ok' => false, 'error' => '缺少就诊卡'];
}
$context = self::buildCareContext($diagnosisId);
if (!$context['ok']) {
return ['ok' => false, 'error' => $context['error'] ?? '获取档案失败'];
}
$gate = self::ensureEnoughBloodDays($context['data']);
if (!$gate['ok']) {
return ['ok' => false, 'error' => $gate['error']];
}
$analysis = self::buildAnalysisPayload($context['data']);
$cacheKey = self::careCacheKey($diagnosisId);
if (!$refresh) {
$cached = Cache::get($cacheKey);
if (is_array($cached) && !empty($cached['summary'])) {
$cached['cached'] = true;
$cached['analysis'] = $analysis;
return ['ok' => true, 'data' => $cached];
}
}
$data = null;
if (AiChatService::isEnabled()) {
$raw = self::aiDailyCarePlan($context['data'], $refresh);
if (is_array($raw) && !empty($raw['summary'])) {
$data = self::finalizeCarePlan($raw);
}
}
if (!$data) {
$data = GiKnowledge::fallbackBloodCarePlan(
$context['data']['stats_7d'] ?? [],
$context['data']['stats_30d'] ?? [],
$context['data']
);
}
$data['date'] = date('Y-m-d');
$data['cached'] = false;
$data['analysis'] = $analysis;
Cache::set($cacheKey, $data, self::CACHE_TTL);
return ['ok' => true, 'data' => $data];
}
/**
* @param callable(string, array<string, mixed>):void $emit
*/
public static function streamDailyCarePlan(int $diagnosisId, bool $refresh, callable $emit): void
{
if ($diagnosisId <= 0) {
$emit('error', ['message' => '缺少就诊卡']);
return;
}
$context = self::buildCareContext($diagnosisId);
if (!$context['ok']) {
$emit('error', ['message' => $context['error'] ?? '获取档案失败']);
return;
}
$gate = self::ensureEnoughBloodDays($context['data']);
if (!$gate['ok']) {
$emit('error', ['message' => $gate['error']]);
return;
}
$analysis = self::buildAnalysisPayload($context['data']);
$emit('analysis', ['analysis' => $analysis]);
$cacheKey = self::careCacheKey($diagnosisId);
if (!$refresh) {
$cached = Cache::get($cacheKey);
if (is_array($cached) && !empty($cached['summary'])) {
$cached['cached'] = true;
$cached['analysis'] = $analysis;
$emit('done', $cached);
return;
}
}
$data = null;
$fullText = '';
if (AiChatService::isEnabled()) {
[$system, $user] = self::buildCareStreamPrompts($context['data'], $refresh);
$streamRes = AiChatService::streamChat([
['role' => 'system', 'content' => $system],
['role' => 'user', 'content' => $user],
], static function (string $delta) use (&$fullText, $emit): void {
$fullText .= $delta;
$emit('delta', ['text' => $delta, 'buffer' => $fullText]);
}, [
'temperature' => $refresh ? 0.75 : 0.4,
'max_tokens' => 720,
'timeout' => self::AI_STREAM_TIMEOUT_SEC,
]);
if ($streamRes['ok'] && trim($fullText) !== '') {
$parsed = self::parseCarePlainText(trim($fullText));
if ($parsed && !empty($parsed['summary'])) {
$data = self::finalizeCarePlan($parsed);
}
}
}
if (!$data) {
$data = GiKnowledge::fallbackBloodCarePlan(
$context['data']['stats_7d'] ?? [],
$context['data']['stats_30d'] ?? [],
$context['data']
);
}
$data['date'] = date('Y-m-d');
$data['cached'] = false;
$data['analysis'] = $analysis;
Cache::set($cacheKey, $data, self::CACHE_TTL);
$emit('done', $data);
}
private static function careCacheKey(int $diagnosisId): string
{
return 'daily_blood_care_ai_v1:' . $diagnosisId . ':' . date('Y-m-d');
}
/**
* @return array{ok:bool,error?:string,data?:array}
*/
private static function buildCareContext(int $diagnosisId): array
{
$base = DailyDietAiLogic::getPatientContext($diagnosisId);
if (!$base['ok']) {
return $base;
}
$diagnosis = Diagnosis::where('id', $diagnosisId)->where('delete_time', null)->find();
if ($diagnosis) {
$row = $diagnosis->toArray();
$base['data']['syndrome_type'] = trim((string) ($row['syndrome_type'] ?? ''));
$base['data']['symptoms'] = trim((string) ($row['symptoms'] ?? ''));
$base['data']['remark'] = trim((string) ($row['remark'] ?? ''));
}
return $base;
}
/**
* @param array<string,mixed> $context
* @return array{ok:bool,error?:string}
*/
private static function ensureEnoughBloodDays(array $context): array
{
$days30 = (int) (($context['stats_30d']['record_days'] ?? 0));
$days7 = (int) (($context['stats_7d']['record_days'] ?? 0));
$total = max($days30, $days7);
if ($total < self::MIN_RECORD_DAYS) {
return ['ok' => false, 'error' => '累计记录满7天后可生成照护建议'];
}
return ['ok' => true];
}
/**
* @param array<string,mixed> $context
* @return array<int,array<string,mixed>>
*/
private static function buildAnalysisPayload(array $context): array
{
$out = [];
foreach (['stats_7d', 'stats_30d'] as $key) {
$s = $context[$key] ?? null;
if (is_array($s)) {
$out[] = $s;
}
}
return $out;
}
/**
* @param array<string,mixed> $context
* @return array<string,mixed>|null
*/
private static function aiDailyCarePlan(array $context, bool $refresh): ?array
{
[$system, $user] = self::buildCareJsonPrompts($context, $refresh);
$res = AiChatService::chat([
['role' => 'system', 'content' => $system],
['role' => 'user', 'content' => $user],
], [
'temperature' => $refresh ? 0.7 : 0.35,
'max_tokens' => 650,
'timeout' => self::AI_TIMEOUT_SEC,
'response_format' => ['type' => 'json_object'],
]);
if (empty($res['ok']) || empty($res['content'])) {
return null;
}
$json = self::parseJsonObject((string) $res['content']);
return is_array($json) ? $json : null;
}
/**
* @param array<string,mixed> $context
* @return array{0:string,1:string}
*/
private static function buildCareJsonPrompts(array $context, bool $refresh): array
{
$bloodLine = self::bloodLine($context);
$stat7Line = self::statsLine($context['stats_7d'] ?? []);
$stat30Line = self::statsLine($context['stats_30d'] ?? []);
$syndrome = trim((string) ($context['syndrome_type'] ?? ''));
$symptoms = trim((string) ($context['symptoms'] ?? ''));
$system = <<<SYS
你是基层中医糖尿病照护助手,面向农村中老年患者,用通俗中文给「血糖管理 + 中医调理方向」建议。
硬性要求:
1. 不得开具具体中药处方名、剂量、加减;不得指导自行增减西药/胰岛素。
2. 中医部分写调理思路、食疗方向、穴位艾灸注意事项,强调需面诊脉诊后由医师定方。
3. 结合提供的血糖统计与逐日记录,给出可执行的监测与生活方式建议。
4. 只输出 JSON
{"summary":"一句话总评","blood_advice":"血糖监测与饮食运动","tcm_plan":"中医辨证与调理方案","watch_points":["留意1","留意2"],"next_steps":"下一步复诊或就医提醒"}
SYS;
$user = sprintf(
"患者:%s,%s,%s岁。证型登记:%s。症状摘要:%s。\n日期:%s。\n近7日血糖:%s。\n统计:%s%s。\n请根据控制好坏给出个性化 JSON。",
$context['patient_name'] ?: '患者',
$context['gender_text'] ?? '',
$context['age'] ?? 0,
$syndrome !== '' ? $syndrome : '未登记',
$symptoms !== '' ? mb_substr($symptoms, 0, 120) : '无',
$context['today'] ?? date('Y-m-d'),
$bloodLine,
$stat7Line,
$stat30Line
);
if ($refresh) {
$user .= "\n\n用户点了「换一换」,请换一套不同表述但同样严谨的建议,编号" . substr(md5((string) microtime(true)), 0, 8) . '。';
}
return [$system, $user];
}
/**
* @param array<string,mixed> $context
* @return array{0:string,1:string}
*/
private static function buildCareStreamPrompts(array $context, bool $refresh): array
{
$bloodLine = self::bloodLine($context);
$stat7Line = self::statsLine($context['stats_7d'] ?? []);
$stat30Line = self::statsLine($context['stats_30d'] ?? []);
$system = <<<SYS
你是基层中医糖尿病照护助手,给农村中老年患者写血糖与中医调理建议。
硬性要求:
1. 不得写具体中药方名剂量、不得指导自行调药。
2. 中医写辨证思路与调理方向,强调面诊后由医师定方。
3. 严格按下面 5 行输出,不要 JSON、不要 markdown
总评:(一句话)
血糖:(监测、饮食、运动,2-4句)
中医:(辨证思路、食疗艾灸方向,2-4句)
留意:(用顿号隔开 2-4 条)
复诊:(下一步)
SYS;
$user = sprintf(
"患者:%s,%s,%s岁。证型:%s。症状:%s。\n近7日血糖:%s。\n%s%s。",
$context['patient_name'] ?: '患者',
$context['gender_text'] ?? '',
$context['age'] ?? 0,
($context['syndrome_type'] ?? '') ?: '未登记',
mb_substr((string) ($context['symptoms'] ?? ''), 0, 80) ?: '无',
$bloodLine,
$stat7Line,
$stat30Line
);
if ($refresh) {
$user .= "\n\n换一换,重新写一套,编号" . substr(md5((string) microtime(true)), 0, 8) . '。';
}
return [$system, $user];
}
/**
* @param array<string,mixed> $context
*/
private static function bloodLine(array $context): string
{
$recent = $context['blood_recent'] ?? [];
if (!is_array($recent) || empty($recent)) {
return '近7日无逐日明细';
}
return implode('', $recent);
}
/**
* @param array<string,mixed> $stats
*/
private static function statsLine(array $stats): string
{
$label = (string) ($stats['label'] ?? '统计');
if (($stats['record_days'] ?? 0) <= 0) {
return $label . '无记录';
}
$parts = [
$label . "有记录{$stats['record_days']}",
"偏高{$stats['high_days']}",
"达标率{$stats['compliance']}%",
];
if ($stats['fasting_avg'] !== null) {
$parts[] = "空腹均值{$stats['fasting_avg']}";
}
if ($stats['postprandial_avg'] !== null) {
$parts[] = "餐后均值{$stats['postprandial_avg']}";
}
return implode('', $parts);
}
/**
* @return array<string,mixed>|null
*/
private static function parseCarePlainText(string $text): ?array
{
$text = trim($text);
if ($text === '') {
return null;
}
if ($text[0] === '{') {
$json = self::parseJsonObject($text);
return is_array($json) ? $json : null;
}
$map = [];
if (preg_match('/总评[:]\s*(.+)$/mu', $text, $m)) {
$map['summary'] = trim(preg_split('/\R/u', $m[1])[0] ?? $m[1]);
}
if (preg_match('/血糖[:]\s*(.+)$/mu', $text, $m)) {
$map['blood_advice'] = trim(preg_split('/\R/u', $m[1])[0] ?? $m[1]);
}
if (preg_match('/中医[:]\s*(.+)$/mu', $text, $m)) {
$map['tcm_plan'] = trim(preg_split('/\R/u', $m[1])[0] ?? $m[1]);
}
if (preg_match('/留意[:]\s*(.+)$/mu', $text, $m)) {
$line = trim(preg_split('/\R/u', $m[1])[0] ?? $m[1]);
$parts = preg_split('/[、,;\s]+/u', $line) ?: [];
$map['watch_points'] = array_values(array_filter(array_map('trim', $parts)));
}
if (preg_match('/复诊[:]\s*(.+)$/mu', $text, $m)) {
$map['next_steps'] = trim(preg_split('/\R/u', $m[1])[0] ?? $m[1]);
}
if (empty($map['summary'])) {
return null;
}
return $map;
}
/**
* @param array<string,mixed> $raw
* @return array<string,mixed>
*/
private static function finalizeCarePlan(array $raw): array
{
$watch = $raw['watch_points'] ?? [];
if (!is_array($watch)) {
$watch = preg_split('/[、,;\n]+/u', (string) $watch) ?: [];
}
$watch = array_values(array_filter(array_map('trim', $watch)));
return [
'summary' => trim((string) ($raw['summary'] ?? '')),
'blood_advice' => trim((string) ($raw['blood_advice'] ?? '')),
'tcm_plan' => trim((string) ($raw['tcm_plan'] ?? '')),
'watch_points' => $watch,
'next_steps' => trim((string) ($raw['next_steps'] ?? '')),
'control_level' => (string) ($raw['control_level'] ?? ''),
'control_label' => (string) ($raw['control_label'] ?? ''),
'disclaimer' => trim((string) ($raw['disclaimer'] ?? 'AI 建议供参考,不能替代医师面诊、开方与调药。')),
'source' => (string) ($raw['source'] ?? 'ai'),
];
}
/**
* @return array<string,mixed>|null
*/
private static function parseJsonObject(string $text): ?array
{
$text = trim($text);
if ($text === '') {
return null;
}
if (preg_match('/\{[\s\S]*\}/u', $text, $m)) {
$text = $m[0];
}
$data = json_decode($text, true);
return is_array($data) ? $data : null;
}
}
@@ -0,0 +1,858 @@
<?php
namespace app\api\logic\tcm;
use app\common\model\tcm\BloodRecord;
use app\common\model\tcm\Diagnosis;
use app\common\service\AiChatService;
use think\facade\Cache;
/**
* 日常护理 - AI 饮食建议(基于霍大夫升糖指数)
*/
class DailyDietAiLogic
{
private const CACHE_TTL = 86400;
/** 单次 AI 请求超时(秒),避免接口长时间挂起 */
private const AI_TIMEOUT_SEC = 12;
/** 流式 AI 请求超时(秒) */
private const AI_STREAM_TIMEOUT_SEC = 18;
/**
* 今日推荐饮食(按诊单+日期缓存)
*
* @return array{ok:bool,error?:string,data?:array}
*/
public static function getDailyRecommend(int $diagnosisId, bool $refresh = false): array
{
if ($diagnosisId <= 0) {
return ['ok' => false, 'error' => '缺少就诊卡'];
}
$context = self::buildPatientContext($diagnosisId);
if (!$context['ok']) {
return ['ok' => false, 'error' => $context['error'] ?? '获取档案失败'];
}
$analysis = self::buildAnalysisPayload($context['data']);
$exercise = self::buildExercisePayload($context['data']);
$cacheKey = self::recommendCacheKey($diagnosisId);
if (!$refresh) {
$cached = Cache::get($cacheKey);
if (is_array($cached) && !empty($cached['breakfast'])) {
$cached['cached'] = true;
$cached['analysis'] = $analysis;
$cached['exercise'] = $exercise;
return ['ok' => true, 'data' => $cached];
}
}
$data = null;
if (AiChatService::isEnabled()) {
$raw = self::aiDailyRecommend($context['data'], $refresh);
if (is_array($raw) && !empty($raw['breakfast'])) {
$data = self::finalizeAiRecommendPlan($raw);
}
}
if (!$data) {
$tplIdx = self::resolveFallbackTemplateIndex($diagnosisId, $refresh);
$data = GiKnowledge::fallbackDailyMeals($diagnosisId, $tplIdx);
$data['disclaimer'] = '按升糖指数与农家饭硬性规则推荐(午餐≥2样蛋白、淀粉不重复)。';
}
$data['date'] = date('Y-m-d');
$data['cached'] = false;
Cache::set($cacheKey, $data, self::CACHE_TTL);
$data['analysis'] = $analysis;
$data['exercise'] = $exercise;
return ['ok' => true, 'data' => $data];
}
/**
* 询问某食物能不能吃
*
* @return array{ok:bool,error?:string,data?:array}
*/
public static function askFood(int $diagnosisId, string $question): array
{
$question = trim($question);
if ($question === '') {
return ['ok' => false, 'error' => '请输入想咨询的食物'];
}
if (mb_strlen($question) > 80) {
return ['ok' => false, 'error' => '问题过长,请简短描述'];
}
$cacheKey = 'daily_diet_ai_ask:' . md5($diagnosisId . ':' . mb_strtolower($question));
$cached = Cache::get($cacheKey);
if (is_array($cached) && !empty($cached['advice'])) {
$cached['cached'] = true;
return ['ok' => true, 'data' => $cached];
}
$context = self::buildPatientContext($diagnosisId);
$data = null;
if (AiChatService::isEnabled()) {
$data = self::aiAskFood($context['data'] ?? [], $question);
}
if (!$data) {
$data = GiKnowledge::fallbackAsk($question);
}
$data['question'] = $question;
$data['disclaimer'] = '仅供参考,不能替代医嘱。';
$data['cached'] = false;
Cache::set($cacheKey, $data, 3600);
return ['ok' => true, 'data' => $data];
}
/**
* 流式:今日饮食推荐(SSE delta + done
*
* @param callable(string, array<string, mixed>):void $emit event: delta|done|error
*/
public static function streamDailyRecommend(int $diagnosisId, bool $refresh, callable $emit): void
{
if ($diagnosisId <= 0) {
$emit('error', ['message' => '缺少就诊卡']);
return;
}
$context = self::buildPatientContext($diagnosisId);
if (!$context['ok']) {
$emit('error', ['message' => $context['error'] ?? '获取档案失败']);
return;
}
$analysis = self::buildAnalysisPayload($context['data']);
$exercise = self::buildExercisePayload($context['data']);
// 先把「分析依据」「运动建议」推给前端,提升首屏感知
$emit('analysis', ['analysis' => $analysis]);
$emit('exercise', ['exercise' => $exercise]);
$cacheKey = self::recommendCacheKey($diagnosisId);
if (!$refresh) {
$cached = Cache::get($cacheKey);
if (is_array($cached) && !empty($cached['breakfast'])) {
$cached['cached'] = true;
$cached['analysis'] = $analysis;
$cached['exercise'] = $exercise;
$emit('done', $cached);
return;
}
}
$data = null;
$fullText = '';
if (AiChatService::isEnabled()) {
[$system, $user] = self::buildRecommendStreamPrompts($context['data'], $refresh);
$streamRes = AiChatService::streamChat([
['role' => 'system', 'content' => $system],
['role' => 'user', 'content' => $user],
], static function (string $delta) use (&$fullText, $emit): void {
$fullText .= $delta;
$emit('delta', ['text' => $delta, 'buffer' => $fullText]);
}, [
'temperature' => $refresh ? 0.78 : 0.35,
'max_tokens' => 400,
'timeout' => self::AI_STREAM_TIMEOUT_SEC,
]);
if ($streamRes['ok'] && $fullText !== '') {
$parsed = self::parseRecommendPlainText($fullText);
if ($parsed && !empty($parsed['breakfast'])) {
$data = self::finalizeAiRecommendPlan($parsed);
}
}
}
if (!$data) {
$tplIdx = self::resolveFallbackTemplateIndex($diagnosisId, $refresh);
$data = GiKnowledge::fallbackDailyMeals($diagnosisId, $tplIdx);
$data['source'] = 'rule';
$data['disclaimer'] = '按升糖指数与农家饭硬性规则推荐(午餐≥2样蛋白、淀粉不重复)。';
}
$data['date'] = date('Y-m-d');
$data['cached'] = false;
Cache::set($cacheKey, $data, self::CACHE_TTL);
$data['analysis'] = $analysis;
$data['exercise'] = $exercise;
$emit('done', $data);
}
/**
* 流式:能不能吃(SSE delta + done
*
* @param callable(string, array<string, mixed>):void $emit event: delta|done|error
*/
public static function streamAskFood(int $diagnosisId, string $question, callable $emit): void
{
$question = trim($question);
if ($question === '') {
$emit('error', ['message' => '请输入想咨询的食物']);
return;
}
if (mb_strlen($question) > 80) {
$emit('error', ['message' => '问题过长,请简短描述']);
return;
}
$cacheKey = 'daily_diet_ai_ask:' . md5($diagnosisId . ':' . mb_strtolower($question));
$cached = Cache::get($cacheKey);
if (is_array($cached) && !empty($cached['advice'])) {
$cached['cached'] = true;
$emit('done', $cached);
return;
}
$context = self::buildPatientContext($diagnosisId);
$data = null;
$fullText = '';
if (AiChatService::isEnabled()) {
[$system, $user] = self::buildAskStreamPrompts($context['data'] ?? [], $question);
$streamRes = AiChatService::streamChat([
['role' => 'system', 'content' => $system],
['role' => 'user', 'content' => $user],
], static function (string $delta) use (&$fullText, $emit): void {
$fullText .= $delta;
$emit('delta', ['text' => $delta, 'advice' => $fullText]);
}, [
'temperature' => 0.3,
'max_tokens' => 200,
'timeout' => self::AI_STREAM_TIMEOUT_SEC,
]);
if ($streamRes['ok'] && trim($fullText) !== '') {
$data = self::finalizeAskFromText($context['data'] ?? [], $question, trim($fullText));
}
}
if (!$data) {
$data = GiKnowledge::fallbackAsk($question);
}
$data['question'] = $question;
$data['disclaimer'] = '仅供参考,不能替代医嘱。';
$data['cached'] = false;
Cache::set($cacheKey, $data, 3600);
$emit('done', $data);
}
private static function recommendCacheKey(int $diagnosisId): string
{
return 'daily_diet_ai_rec_v2:' . $diagnosisId . ':' . date('Y-m-d');
}
/** 换一换时轮换规则模板下标(与 GiKnowledge::$mealTemplates 数量一致) */
private static function resolveFallbackTemplateIndex(int $diagnosisId, bool $refresh): int
{
$count = 6;
$cacheKey = 'daily_diet_ai_tpl_idx:' . $diagnosisId . ':' . date('Y-m-d');
$defaultIdx = abs(crc32(date('Y-m-d') . ':' . $diagnosisId)) % $count;
if (!$refresh) {
Cache::set($cacheKey, $defaultIdx, self::CACHE_TTL);
return $defaultIdx;
}
$last = Cache::get($cacheKey);
if ($last === null || $last === false) {
$last = $defaultIdx;
}
$idx = (((int) $last) + 1) % $count;
Cache::set($cacheKey, $idx, self::CACHE_TTL);
return $idx;
}
/**
* @return array{ok:bool,error?:string,data?:array}
*/
private static function buildPatientContext(int $diagnosisId): array
{
$diagnosis = Diagnosis::where('id', $diagnosisId)->where('delete_time', null)->find();
if (!$diagnosis) {
return ['ok' => false, 'error' => '就诊卡不存在'];
}
$row = $diagnosis->toArray();
$gender = (int) ($row['gender'] ?? 0);
$genderText = $gender === 1 ? '男' : ($gender === 0 ? '女' : '未知');
$age = (int) ($row['age'] ?? 0);
// 拉取近 30 天血糖(涵盖近 7 天),统一计算 7/30 天统计
$since30 = strtotime('-30 days 00:00:00');
$bloodList = BloodRecord::where('diagnosis_id', $diagnosisId)
->where('record_date', '>=', $since30)
->where('delete_time', null)
->order('record_date', 'desc')
->field('record_date,fasting_blood_sugar,postprandial_blood_sugar,other_blood_sugar')
->select()
->toArray();
$since7 = strtotime('-7 days 00:00:00');
$list7 = array_values(array_filter($bloodList, static function ($b) use ($since7) {
return (int) ($b['record_date'] ?? 0) >= $since7;
}));
// 近 7 天逐日明细(喂给 AI 的细节)
$bloodSummary = [];
foreach (array_slice($list7, 0, 7) as $b) {
$date = !empty($b['record_date']) ? date('Y-m-d', (int) $b['record_date']) : '';
$parts = [];
if ($b['fasting_blood_sugar'] !== null && $b['fasting_blood_sugar'] !== '') {
$parts[] = '空腹' . $b['fasting_blood_sugar'];
}
if ($b['postprandial_blood_sugar'] !== null && $b['postprandial_blood_sugar'] !== '') {
$parts[] = '餐后' . $b['postprandial_blood_sugar'];
}
if ($b['other_blood_sugar'] !== null && $b['other_blood_sugar'] !== '') {
$parts[] = '其他' . $b['other_blood_sugar'];
}
if ($date && $parts) {
$bloodSummary[] = $date . '' . implode('', $parts) . ' mmol/L';
}
}
$stats7 = self::aggregateBloodStats($list7, $age, '近7天');
$stats30 = self::aggregateBloodStats($bloodList, $age, '近30天');
return [
'ok' => true,
'data' => [
'patient_name' => (string) ($row['patient_name'] ?? ''),
'age' => $age,
'gender_text' => $genderText,
'blood_recent' => $bloodSummary,
'stats_7d' => $stats7,
'stats_30d' => $stats30,
'today' => date('Y-m-d'),
],
];
}
/**
* 根据年龄返回血糖偏高阈值(与前端 getBloodSugarThresholds 保持一致)
*
* @return array{fasting:float,postprandial:float}|null
*/
private static function bloodThresholds(int $age): array
{
// 年龄未知时用通用糖尿病控制目标兜底,避免「无阈值=全部达标」
if ($age <= 0) {
return ['fasting' => 7.0, 'postprandial' => 10.0];
}
return $age < 50
? ['fasting' => 7.0, 'postprandial' => 9.0]
: ['fasting' => 8.0, 'postprandial' => 10.0];
}
/**
* 汇总一段时间内的血糖统计:有记录天数、偏高天数、达标率、均值
*
* @param array<int,array<string,mixed>> $rows
* @return array<string,mixed>
*/
private static function aggregateBloodStats(array $rows, int $age, string $label): array
{
$thresholds = self::bloodThresholds($age);
$byDate = [];
$fastingSum = 0.0;
$fastingCnt = 0;
$postSum = 0.0;
$postCnt = 0;
foreach ($rows as $b) {
$ts = (int) ($b['record_date'] ?? 0);
if ($ts <= 0) {
continue;
}
$date = date('Y-m-d', $ts);
$fasting = ($b['fasting_blood_sugar'] !== null && $b['fasting_blood_sugar'] !== '') ? (float) $b['fasting_blood_sugar'] : null;
$post = ($b['postprandial_blood_sugar'] !== null && $b['postprandial_blood_sugar'] !== '') ? (float) $b['postprandial_blood_sugar'] : null;
if ($fasting === null && $post === null) {
continue;
}
if (!isset($byDate[$date])) {
$byDate[$date] = ['high' => false];
}
if ($fasting !== null) {
$fastingSum += $fasting;
$fastingCnt++;
if ($thresholds && $fasting >= $thresholds['fasting']) {
$byDate[$date]['high'] = true;
}
}
if ($post !== null) {
$postSum += $post;
$postCnt++;
if ($thresholds && $post >= $thresholds['postprandial']) {
$byDate[$date]['high'] = true;
}
}
}
$recordDays = count($byDate);
$highDays = 0;
foreach ($byDate as $d) {
if ($d['high']) {
$highDays++;
}
}
$normalDays = max(0, $recordDays - $highDays);
$compliance = $recordDays > 0 ? (int) round($normalDays / $recordDays * 100) : 0;
return [
'label' => $label,
'record_days' => $recordDays,
'high_days' => $highDays,
'normal_days' => $normalDays,
'compliance' => $compliance,
'fasting_avg' => $fastingCnt > 0 ? round($fastingSum / $fastingCnt, 1) : null,
'postprandial_avg' => $postCnt > 0 ? round($postSum / $postCnt, 1) : null,
];
}
/**
* 把统计数据拼成喂给 AI 的一行人类可读文本
*
* @param array<string,mixed> $stats
*/
private static function statsToLine(array $stats): string
{
if (($stats['record_days'] ?? 0) <= 0) {
return $stats['label'] . '无血糖记录';
}
$segs = [
$stats['label'] . "有记录{$stats['record_days']}",
"偏高{$stats['high_days']}",
"达标率{$stats['compliance']}%",
];
if ($stats['fasting_avg'] !== null) {
$segs[] = "空腹均值{$stats['fasting_avg']}";
}
if ($stats['postprandial_avg'] !== null) {
$segs[] = "餐后均值{$stats['postprandial_avg']}";
}
return implode('', $segs);
}
/**
* 给前端展示的「分析依据」结构(近7天 + 近30天)
*
* @param array<string,mixed> $context
* @return array<int,array<string,mixed>>
*/
private static function buildAnalysisPayload(array $context): array
{
$out = [];
foreach (['stats_7d', 'stats_30d'] as $key) {
$s = $context[$key] ?? null;
if (is_array($s)) {
$out[] = $s;
}
}
return $out;
}
/**
* 给前端展示的「运动降糖」建议(按血糖统计调整强度)
*
* @param array<string,mixed> $context
* @return array<string,mixed>
*/
private static function buildExercisePayload(array $context): array
{
return GiKnowledge::exercisePlan(
is_array($context['stats_7d'] ?? null) ? $context['stats_7d'] : [],
is_array($context['stats_30d'] ?? null) ? $context['stats_30d'] : []
);
}
/**
* @return array{0:string,1:string}
*/
private static function buildRecommendPrompts(array $context, bool $refresh = false): array
{
$bloodLine = empty($context['blood_recent'])
? '近7日无血糖记录'
: implode('', $context['blood_recent']);
$stat7Line = self::statsToLine($context['stats_7d'] ?? ['label' => '近7天', 'record_days' => 0]);
$stat30Line = self::statsToLine($context['stats_30d'] ?? ['label' => '近30天', 'record_days' => 0]);
$system = <<<SYS
你是村里懂糖尿病饮食的大夫助手,依据「霍大夫升糖指数(GI)」给农村老人推荐一日三餐。输出必须严格可执行。
硬性规则(违反即不合格):
1. 午餐至少 2 样蛋白质(鱼/鸡鸭/瘦肉/蛋/豆腐/豆干),且午餐蛋白种类数 > 早餐 > 晚餐。
2. 淀粉定义:粥/饭/面/饼/窝头/薯/南瓜。每餐最多 1 种淀粉;早中晚 3 种淀粉必须互不相同。
3. 严禁:白馒头、油条、粘豆包、糯米饭、西瓜、含糖饮料、白稀饭(杂面窝头、玉米碴粥除外)。
4. 低 GI 优先;农村家常;禁止轻食/沙拉/藜麦等词。
5. lunch 字段写法:蛋白菜放前面,淀粉(如有)放最后且注明「小半碗/一个」。
6. 早餐必须包含「驼奶粉」(温水冲服,适量),可与粥、蛋、菜并列写。
7. drinks 单独写全天喝什么:温开水为主;可写驼奶粉冲饮时间;严禁含糖饮料、果汁、酒。
8. 只输出 JSON
{"breakfast":"...","drinks":"...","lunch":"...","dinner":"...","tips":"...","avoid":["...","..."]}
SYS;
$user = sprintf(
"患者:%s%s%s岁。日期:%s。\n近7日逐日血糖:%s。\n血糖统计:%s%s。\n(若近期偏高天数多或达标率低,请收紧主食与高GI食物,多安排蛋白与绿叶菜;若控制平稳可正常推荐。)\n\nGI知识:\n%s\n\n农家饭参考:\n%s\n\n请输出严格符合硬性规则的三餐 JSON。",
$context['patient_name'] ?: '大爷大妈',
$context['gender_text'] ?? '',
$context['age'] ?? 0,
$context['today'] ?? date('Y-m-d'),
$bloodLine,
$stat7Line,
$stat30Line,
GiKnowledge::summaryText(),
GiKnowledge::ruralMealHints()
);
if ($refresh) {
$user .= "\n\n用户点了「换一换」,请给一套完全不同的农家三餐,编号" . substr(md5((string) microtime(true)), 0, 8) . '。';
}
return [$system, $user];
}
/**
* 流式三餐推荐:纯文本格式,便于逐字输出
*
* @return array{0:string,1:string}
*/
private static function buildRecommendStreamPrompts(array $context, bool $refresh = false): array
{
$bloodLine = empty($context['blood_recent'])
? '近7日无血糖记录'
: implode('', $context['blood_recent']);
$stat7Line = self::statsToLine($context['stats_7d'] ?? ['label' => '近7天', 'record_days' => 0]);
$stat30Line = self::statsToLine($context['stats_30d'] ?? ['label' => '近30天', 'record_days' => 0]);
$system = <<<SYS
你是村里懂糖尿病饮食的大夫助手,依据「霍大夫升糖指数(GI)」给农村老人推荐一日三餐。
硬性规则:
1. 午餐至少 2 样蛋白质(鱼/鸡鸭/瘦肉/蛋/豆腐/豆干),且午餐蛋白 > 早餐 > 晚餐。
2. 淀粉(粥/饭/面/饼/窝头/薯/南瓜)每餐最多 1 种,早中晚互不相同。
3. 严禁白馒头、油条、粘豆包、糯米饭、西瓜、含糖饮料。
4. 农村家常饭,禁止轻食/沙拉/藜麦。
5. 早餐必须含驼奶粉(温水冲服);喝的单独一行。
严格按下面 6 行格式输出,不要 JSON、不要 markdown、不要多余解释:
早餐:(具体食物,须含驼奶粉)
喝的:(温开水、驼奶粉冲饮安排等,忌甜饮)
午餐:(具体食物,蛋白放前)
晚餐:(具体食物)
提示:(一句土话提醒)
少碰:(用顿号隔开,如:白馒头、油条)
SYS;
$user = sprintf(
"患者:%s%s%s岁。日期:%s。\n近7日逐日血糖:%s。\n血糖统计:%s%s。\n(偏高多或达标率低则收紧主食、多蛋白绿叶菜;平稳则正常推荐。)\n\nGI摘要:\n%s",
$context['patient_name'] ?: '大爷大妈',
$context['gender_text'] ?? '',
$context['age'] ?? 0,
$context['today'] ?? date('Y-m-d'),
$bloodLine,
$stat7Line,
$stat30Line,
mb_substr(GiKnowledge::summaryText(), 0, 320)
);
if ($refresh) {
$user .= "\n\n用户点了「换一换」,请重新给一套完全不同的农家三餐,编号" . substr(md5((string) microtime(true)), 0, 8) . ',别跟常见模板重复。';
}
return [$system, $user];
}
/**
* 解析流式三餐纯文本(兼容 JSON 回退)
*
* @return array<string, mixed>|null
*/
private static function parseRecommendPlainText(string $text): ?array
{
$text = trim($text);
if ($text === '') {
return null;
}
if ($text[0] === '{') {
$json = self::parseJsonObject($text);
if (is_array($json)) {
return $json;
}
}
$map = [
'breakfast' => null,
'drinks' => null,
'lunch' => null,
'dinner' => null,
'tips' => null,
'avoid' => null,
];
if (preg_match('/早餐[:]\s*(.+)$/mu', $text, $m)) {
$map['breakfast'] = trim(preg_split('/\R/u', $m[1])[0] ?? $m[1]);
}
if (preg_match('/喝的[:]\s*(.+)$/mu', $text, $m)) {
$map['drinks'] = trim(preg_split('/\R/u', $m[1])[0] ?? $m[1]);
}
if (preg_match('/午餐[:]\s*(.+)$/mu', $text, $m)) {
$map['lunch'] = trim(preg_split('/\R/u', $m[1])[0] ?? $m[1]);
}
if (preg_match('/晚餐[:]\s*(.+)$/mu', $text, $m)) {
$map['dinner'] = trim(preg_split('/\R/u', $m[1])[0] ?? $m[1]);
}
if (preg_match('/提示[:]\s*(.+)$/mu', $text, $m)) {
$map['tips'] = trim(preg_split('/\R/u', $m[1])[0] ?? $m[1]);
}
if (preg_match('/少碰[:]\s*(.+)$/mu', $text, $m)) {
$avoidLine = trim(preg_split('/\R/u', $m[1])[0] ?? $m[1]);
$parts = preg_split('/[、,;\s]+/u', $avoidLine) ?: [];
$map['avoid'] = array_values(array_filter(array_map('trim', $parts)));
}
if (empty($map['breakfast'])) {
return null;
}
$out = [
'breakfast' => (string) $map['breakfast'],
'drinks' => (string) ($map['drinks'] ?? ''),
'lunch' => (string) ($map['lunch'] ?? ''),
'dinner' => (string) ($map['dinner'] ?? ''),
'tips' => (string) ($map['tips'] ?? ''),
'avoid' => is_array($map['avoid']) ? $map['avoid'] : [],
];
return $out;
}
/**
* 产品要求:早餐含驼奶粉,并单独给出「喝的」
*
* @param array<string, mixed> $plan
* @return array<string, mixed>
*/
private static function applyDietProductDefaults(array $plan): array
{
$breakfast = trim((string) ($plan['breakfast'] ?? ''));
if ($breakfast !== '' && mb_strpos($breakfast, '驼奶粉') === false && mb_strpos($breakfast, '驼奶') === false) {
$plan['breakfast'] = '驼奶粉(温水冲服)、' . $breakfast;
}
$drinks = trim((string) ($plan['drinks'] ?? ''));
if ($drinks === '') {
$plan['drinks'] = '白天多喝温开水;早餐按量冲驼奶粉,别喝甜饮料、果汁。';
} elseif (mb_strpos($drinks, '驼奶') === false) {
$plan['drinks'] = $drinks . ';早餐已安排驼奶粉';
}
return $plan;
}
/**
* 规范化 AI 三餐方案;校验未过也保留 AI 文案(避免流式展示后被规则模板覆盖)
*
* @param array<string, mixed> $parsed
* @return array<string, mixed>
*/
private static function finalizeAiRecommendPlan(array $parsed): array
{
$parsed = self::applyDietProductDefaults($parsed);
$checked = DietMealValidator::validateAndNormalize($parsed);
$data = $checked['plan'];
$data['source'] = 'ai';
$data['rules_summary'] = DietMealValidator::metaSummary($checked['meta']);
if ($checked['ok']) {
$data['disclaimer'] = 'AI 建议已通过规则校验,仍请结合医嘱与血糖监测。';
} else {
$data['validation_warnings'] = $checked['errors'];
$data['disclaimer'] = 'AI 建议供参考,仍请结合医嘱与血糖监测。';
}
return $data;
}
/**
* @return array{0:string,1:string}
*/
private static function buildAskStreamPrompts(array $context, string $question): array
{
$food = GiKnowledge::extractFoodName($question);
$hit = GiKnowledge::lookupFood($food);
$kbHint = $hit
? "知识库命中:{$hit['food']}{$hit['level_label']}{$hit['category']}"
: '知识库未命中,按 GI 原则用农村常识回答';
$system = <<<SYS
你是村里糖尿病饮食顾问,用升糖指数(GI)回答农村老人「能不能吃某东西」。
用一两句土话直接回答,40字以内,先说能不能吃、再说咋吃/吃多少。不要 JSON、不要 markdown、不要列表。
SYS;
$user = sprintf(
"老人%s%s。问:%s\n%s\n\nGI摘要:\n%s",
$context['patient_name'] ?? '',
$context['gender_text'] ?? '',
$question,
$kbHint,
GiKnowledge::summaryText()
);
return [$system, $user];
}
/**
* @return array<string, mixed>
*/
private static function finalizeAskFromText(array $context, string $question, string $text): array
{
$food = GiKnowledge::extractFoodName($question);
$hit = GiKnowledge::lookupFood($food);
$data = [
'food' => $food,
'advice' => $text,
'source' => 'ai',
];
if ($hit) {
$data['food'] = $hit['food'];
$data['level'] = $hit['level'];
$data['level_label'] = $hit['level_label'];
$data['portion'] = $hit['level'] === GiKnowledge::LEVEL_HIGH
? '尽量别吃'
: ($hit['level'] === GiKnowledge::LEVEL_MEDIUM ? '少量' : '适量');
} else {
$data['level'] = GiKnowledge::LEVEL_MEDIUM;
$data['level_label'] = '中升糖';
$data['portion'] = '少量';
}
return $data;
}
private static function aiDailyRecommend(array $context, bool $refresh = false): ?array
{
[$system, $user] = self::buildRecommendPrompts($context, $refresh);
$res = AiChatService::chat([
['role' => 'system', 'content' => $system],
['role' => 'user', 'content' => $user],
], [
'temperature' => $refresh ? 0.78 : 0.35,
'max_tokens' => 900,
'timeout' => self::AI_TIMEOUT_SEC,
'response_format' => ['type' => 'json_object'],
]);
if (!$res['ok']) {
return null;
}
$parsed = self::parseJsonObject((string) $res['content']);
if (!$parsed || empty($parsed['breakfast'])) {
return null;
}
$parsed['avoid'] = is_array($parsed['avoid'] ?? null) ? $parsed['avoid'] : [];
return $parsed;
}
/**
* @param array $context
* @return array|null
*/
private static function aiAskFood(array $context, string $question): ?array
{
$food = GiKnowledge::extractFoodName($question);
$hit = GiKnowledge::lookupFood($food);
$system = <<<SYS
你是村里糖尿病饮食顾问,用升糖指数(GI)回答农村老人「能不能吃某东西」。
只输出 JSON{"food":"食物名","level":"low|medium|high","level_label":"低升糖|中升糖|高升糖","advice":"40字内土话建议","portion":"咋吃、吃多少"}
levellow≤55medium 56-69high≥70。advice 要口语化,别文绉绉。
SYS;
$kbHint = $hit
? "知识库命中:{$hit['food']}{$hit['level_label']}{$hit['category']}"
: '知识库未命中,按 GI 原则用农村常识回答';
$user = sprintf(
"老人%s%s。问:%s\n%s\n\nGI摘要:\n%s\n\n农家饭原则:\n%s",
$context['patient_name'] ?? '',
$context['gender_text'] ?? '',
$question,
$kbHint,
GiKnowledge::summaryText(),
GiKnowledge::ruralMealHints()
);
$res = AiChatService::chat([
['role' => 'system', 'content' => $system],
['role' => 'user', 'content' => $user],
], [
'temperature' => 0.3,
'max_tokens' => 400,
'timeout' => self::AI_TIMEOUT_SEC,
'response_format' => ['type' => 'json_object'],
]);
if (!$res['ok']) {
return null;
}
$parsed = self::parseJsonObject((string) $res['content']);
if (!$parsed || empty($parsed['advice'])) {
return null;
}
if ($hit) {
$parsed['food'] = $hit['food'];
$parsed['level'] = $hit['level'];
$parsed['level_label'] = $hit['level_label'];
if (empty($parsed['portion'])) {
$parsed['portion'] = $hit['level'] === GiKnowledge::LEVEL_HIGH ? '尽量别吃' : ($hit['level'] === GiKnowledge::LEVEL_MEDIUM ? '少量' : '适量');
}
}
$parsed['source'] = 'ai';
if (empty($parsed['food'])) {
$parsed['food'] = $food;
}
return $parsed;
}
/**
* @return array<string, mixed>|null
*/
private static function parseJsonObject(string $content): ?array
{
$content = trim($content);
if ($content === '') {
return null;
}
if ($content[0] !== '{') {
if (preg_match('/\{[\s\S]*\}/', $content, $m)) {
$content = $m[0];
}
}
$decoded = json_decode($content, true);
return is_array($decoded) ? $decoded : null;
}
}
@@ -0,0 +1,256 @@
<?php
namespace app\api\logic\tcm;
use app\common\model\tcm\DailyFamilyLike;
use app\common\model\tcm\DailyShareInvite;
use app\common\model\tcm\Diagnosis;
/**
* 家人点赞(邀请观看页 → 患者日常页展示)
*/
class DailyFamilyLikeLogic
{
protected static string $error = '';
/** @var string[] */
protected static array $praisePool = [
'坚持得很好,为您点赞!',
'每天记录真棒,继续保持!',
'您的自律让人佩服!',
'加油,家人一直支持您!',
'稳糖路上,您并不孤单!',
'好习惯正在养成,真为您高兴!',
];
public static function getError(): string
{
return self::$error;
}
protected static function setError(string $msg): bool
{
self::$error = $msg;
return false;
}
/**
* 校验当日邀请码
*
* @return array{diagnosis_id:int,invite_code:string}|false
*/
protected static function resolveInvite(string $inviteCode): array|false
{
$inviteCode = strtoupper(trim($inviteCode));
if ($inviteCode === '') {
return self::setError('邀请码不能为空') ? false : false;
}
$row = DailyShareInvite::where('invite_code', $inviteCode)->find();
if (!$row) {
return self::setError('邀请码无效或已失效') ? false : false;
}
$today = date('Y-m-d');
if ((string) $row['invite_date'] !== $today) {
return self::setError('邀请码已过期,仅可在分享当天点赞') ? false : false;
}
return [
'diagnosis_id' => (int) $row['diagnosis_id'],
'invite_code' => $inviteCode,
];
}
protected static function normalizeViewerKey(string $viewerKey): string
{
$viewerKey = preg_replace('/[^\w\-]/', '', trim($viewerKey)) ?? '';
if (strlen($viewerKey) < 8) {
return '';
}
return substr($viewerKey, 0, 64);
}
protected static function normalizeNickname(string $nickname): string
{
$nickname = trim($nickname);
if ($nickname === '') {
return '家人';
}
$nickname = mb_substr($nickname, 0, 8, 'UTF-8');
return $nickname !== '' ? $nickname : '家人';
}
public static function countToday(int $diagnosisId, ?string $likeDate = null): int
{
$likeDate = $likeDate ?: date('Y-m-d');
return (int) DailyFamilyLike::where('diagnosis_id', $diagnosisId)
->where('like_date', $likeDate)
->count();
}
public static function likedByViewer(int $diagnosisId, string $viewerKey, ?string $likeDate = null): bool
{
$viewerKey = self::normalizeViewerKey($viewerKey);
if ($viewerKey === '') {
return false;
}
$likeDate = $likeDate ?: date('Y-m-d');
return DailyFamilyLike::where('diagnosis_id', $diagnosisId)
->where('like_date', $likeDate)
->where('viewer_key', $viewerKey)
->find() !== null;
}
/**
* 邀请预览附加点赞信息
*/
public static function metaForInvite(string $inviteCode, string $viewerKey = ''): array
{
$resolved = self::resolveInvite($inviteCode);
if ($resolved === false) {
return [
'like_count' => 0,
'liked_by_me' => false,
];
}
$diagnosisId = $resolved['diagnosis_id'];
$viewerKey = self::normalizeViewerKey($viewerKey);
return [
'like_count' => self::countToday($diagnosisId),
'liked_by_me' => $viewerKey !== '' && self::likedByViewer($diagnosisId, $viewerKey),
];
}
/**
* 家人点赞(无需登录)
*/
public static function addLike(string $inviteCode, string $viewerKey, string $nickname = ''): array|false
{
self::$error = '';
$resolved = self::resolveInvite($inviteCode);
if ($resolved === false) {
return false;
}
$viewerKey = self::normalizeViewerKey($viewerKey);
if ($viewerKey === '') {
return self::setError('设备标识无效,请重试') ? false : false;
}
$diagnosisId = $resolved['diagnosis_id'];
$likeDate = date('Y-m-d');
$nickname = self::normalizeNickname($nickname);
$exists = DailyFamilyLike::where('diagnosis_id', $diagnosisId)
->where('like_date', $likeDate)
->where('viewer_key', $viewerKey)
->find();
if ($exists) {
return [
'already_liked' => true,
'like_count' => self::countToday($diagnosisId, $likeDate),
'praise_message' => '您今天已经点过赞啦,谢谢您的鼓励',
'nickname' => (string) ($exists['nickname'] ?? '家人'),
];
}
$todayCount = self::countToday($diagnosisId, $likeDate);
if ($todayCount >= 50) {
return self::setError('今日点赞已满,明天再来吧') ? false : false;
}
DailyFamilyLike::create([
'diagnosis_id' => $diagnosisId,
'like_date' => $likeDate,
'invite_code' => $resolved['invite_code'],
'viewer_key' => $viewerKey,
'nickname' => $nickname,
'create_time' => time(),
]);
$likeCount = self::countToday($diagnosisId, $likeDate);
$idx = $likeCount > 0 ? ($likeCount - 1) % count(self::$praisePool) : 0;
return [
'already_liked' => false,
'like_count' => $likeCount,
'praise_message' => self::$praisePool[$idx],
'nickname' => $nickname,
];
}
/**
* 患者查看今日家人点赞(需登录且拥有诊单)
*/
public static function summaryForPatient(int $userId, int $diagnosisId): array|false
{
self::$error = '';
if ($userId <= 0) {
return self::setError('请先登录') ? false : false;
}
if ($diagnosisId <= 0) {
return self::setError('诊单ID不能为空') ? false : false;
}
$owned = \think\facade\Db::name('diagnosis_view_records')
->where('user_id', $userId)
->where('diagnosis_id', $diagnosisId)
->where('delete_time', null)
->find();
if (!$owned) {
return self::setError('无权查看该诊单') ? false : false;
}
$diagnosis = Diagnosis::where('id', $diagnosisId)->where('delete_time', null)->field('show_card')->find();
if (!$diagnosis || (int) ($diagnosis['show_card'] ?? 1) !== 1) {
return self::setError('该就诊卡已在统计端隐藏') ? false : false;
}
$likeDate = date('Y-m-d');
$count = self::countToday($diagnosisId, $likeDate);
$rows = DailyFamilyLike::where('diagnosis_id', $diagnosisId)
->where('like_date', $likeDate)
->order('id', 'desc')
->limit(8)
->select()
->toArray();
$recent = [];
foreach ($rows as $r) {
$recent[] = [
'nickname' => (string) ($r['nickname'] ?? '家人'),
'time_label' => self::timeLabel((int) ($r['create_time'] ?? 0)),
];
}
$summaryLine = $count > 0
? "今日有 {$count} 位家人为您点赞,继续加油!"
: '分享战报给家人,邀请他们为您点赞鼓劲';
return [
'like_count' => $count,
'summary_line' => $summaryLine,
'recent' => $recent,
];
}
protected static function timeLabel(int $ts): string
{
if ($ts <= 0) {
return '刚刚';
}
$diff = time() - $ts;
if ($diff < 60) {
return '刚刚';
}
if ($diff < 3600) {
return (int) floor($diff / 60) . '分钟前';
}
return date('H:i', $ts);
}
}
@@ -0,0 +1,425 @@
<?php
namespace app\api\logic\tcm;
use app\common\model\tcm\BloodRecord;
use app\common\model\tcm\DailyGamify;
use app\common\model\tcm\DietRecord;
use app\common\model\tcm\ExerciseRecord;
/**
* 稳糖分 / 勋章 / 浇水领奖
*/
class DailyGamifyLogic
{
protected static string $error = '';
/** @var array<string,array{name:string,points:int}> */
protected static array $taskDefs = [
'glucose' => ['name' => '测血糖', 'points' => 10],
'bp' => ['name' => '测血压', 'points' => 10],
'diet' => ['name' => '饮食', 'points' => 10],
'exercise' => ['name' => '运动', 'points' => 10],
];
public static function getError(): string
{
return self::$error;
}
protected static function setError(string $msg): bool
{
self::$error = $msg;
return false;
}
protected static function assertOwned(int $userId, int $diagnosisId): bool
{
if ($userId <= 0) {
return self::setError('请先登录') ? false : false;
}
if ($diagnosisId <= 0) {
return self::setError('诊单ID不能为空') ? false : false;
}
$owned = \think\facade\Db::name('diagnosis_view_records')
->where('user_id', $userId)
->where('diagnosis_id', $diagnosisId)
->where('delete_time', null)
->find();
if (!$owned) {
return self::setError('无权操作该诊单') ? false : false;
}
$diagnosis = \app\common\model\tcm\Diagnosis::where('id', $diagnosisId)
->where('delete_time', null)
->field('show_card')
->find();
if (!$diagnosis || (int) ($diagnosis['show_card'] ?? 1) !== 1) {
return self::setError('该就诊卡已在统计端隐藏') ? false : false;
}
return true;
}
protected static function todayRange(): array
{
return [
strtotime(date('Y-m-d 00:00:00')),
strtotime(date('Y-m-d 23:59:59')),
];
}
protected static function hasValue($v): bool
{
if ($v === null || $v === '' || $v === '0' || $v === 0) {
return false;
}
if (is_string($v)) {
return trim($v) !== '';
}
return is_numeric($v) && (float) $v > 0;
}
/**
* 今日任务是否已完成(依据真实业务记录)
*/
public static function evaluateTaskCompletion(int $diagnosisId): array
{
[$start, $end] = self::todayRange();
$blood = BloodRecord::where('diagnosis_id', $diagnosisId)
->where('source', 1)
->where('record_date', '>=', $start)
->where('record_date', '<=', $end)
->find();
$glucoseDone = false;
$bpDone = false;
if ($blood) {
$glucoseDone = self::hasValue($blood['fasting_blood_sugar'] ?? null)
|| self::hasValue($blood['postprandial_blood_sugar'] ?? null)
|| self::hasValue($blood['other_blood_sugar'] ?? null);
$bpDone = self::hasValue($blood['systolic_pressure'] ?? null)
|| self::hasValue($blood['diastolic_pressure'] ?? null);
}
$diet = DietRecord::where('diagnosis_id', $diagnosisId)
->where('record_date', '>=', $start)
->where('record_date', '<=', $end)
->order('id', 'desc')
->find();
$dietDone = false;
if ($diet) {
$dietDone = self::hasValue($diet['breakfast_foods'] ?? null)
|| self::hasValue($diet['lunch_foods'] ?? null)
|| self::hasValue($diet['dinner_foods'] ?? null);
}
$exercise = ExerciseRecord::where('diagnosis_id', $diagnosisId)
->where('record_date', '>=', $start)
->where('record_date', '<=', $end)
->order('id', 'desc')
->find();
$exerciseDone = false;
if ($exercise) {
$exerciseDone = self::hasValue($exercise['exercise_type'] ?? null)
|| self::hasValue($exercise['duration'] ?? null);
}
return [
'glucose' => $glucoseDone,
'bp' => $bpDone,
'diet' => $dietDone,
'exercise' => $exerciseDone,
];
}
/**
* @param array<string,array<string,bool>> $taskAwards
* @return array<int,array{id:string,name:string,points:int,completed:bool,claimed:bool}>
*/
public static function buildTodayTasks(int $diagnosisId, array $taskAwards): array
{
$today = date('Y-m-d');
$awards = isset($taskAwards[$today]) && is_array($taskAwards[$today]) ? $taskAwards[$today] : [];
$completion = self::evaluateTaskCompletion($diagnosisId);
$list = [];
foreach (self::$taskDefs as $id => $def) {
$list[] = [
'id' => $id,
'name' => $def['name'],
'points' => $def['points'],
'completed' => !empty($completion[$id]),
'claimed' => self::isTaskClaimed($id, $awards, $completion),
];
}
return $list;
}
/**
* 任务是否已领取(兼容旧版 blood 合并任务)
*
* @param array<string,bool> $awards
* @param array<string,bool> $completion
*/
protected static function isTaskClaimed(string $id, array $awards, array $completion = []): bool
{
if (!empty($awards[$id])) {
return true;
}
// 旧版 blood 一次性领取:对应分项当日已有记录则视为已领,避免拆分后重复领奖/轮换引导
if (!empty($awards['blood'])) {
if ($id === 'glucose' && !empty($completion['glucose'])) {
return true;
}
if ($id === 'bp' && !empty($completion['bp'])) {
return true;
}
}
return false;
}
/** 与前端 tongji/utils/treeLevels.js 保持一致 */
protected const TREE_MAX_LEVEL = 9;
protected const TREE_XP_PER_LEVEL = 50;
protected static function treeMeta(int $points): array
{
$points = max(0, (int) $points);
$level = min(self::TREE_MAX_LEVEL, (int) floor($points / self::TREE_XP_PER_LEVEL));
$names = ['种子眠', '破土芽', '展两叶', '小树苗', '青枝繁', '拔节高', '稳糖冠', '初绽香', '漫开花', '圆满树'];
$xpIn = $level >= self::TREE_MAX_LEVEL ? self::TREE_XP_PER_LEVEL : ($points % self::TREE_XP_PER_LEVEL);
$progress = $level >= self::TREE_MAX_LEVEL
? 100
: (int) round(($xpIn / self::TREE_XP_PER_LEVEL) * 100);
$nextName = $level < self::TREE_MAX_LEVEL ? ($names[$level + 1] ?? '') : '';
$pointsToNext = $level >= self::TREE_MAX_LEVEL
? 0
: (self::TREE_XP_PER_LEVEL - $xpIn);
return [
'tree_level' => $level,
'tree_progress' => $progress,
'tree_level_name' => $names[$level] ?? '种子眠',
'tree_xp_in_level' => $xpIn,
'tree_xp_need' => self::TREE_XP_PER_LEVEL,
'tree_points_next' => $pointsToNext,
'tree_next_name' => $nextName,
'tree_is_max' => $level >= self::TREE_MAX_LEVEL,
];
}
/**
* 获取稳糖乐园状态(含今日任务)
*/
public static function getState(int $userId, int $diagnosisId): array|false
{
self::$error = '';
if (!self::assertOwned($userId, $diagnosisId)) {
return false;
}
$row = DailyGamify::where('diagnosis_id', $diagnosisId)
->where('user_id', $userId)
->find();
$points = $row ? (int) $row['points'] : 0;
$badges = $row ? self::decodeJsonArray((string) ($row['badges'] ?? '')) : [];
$taskAwards = $row ? self::decodeJsonObject((string) ($row['task_awards'] ?? '')) : [];
$todayTasks = self::buildTodayTasks($diagnosisId, $taskAwards);
$claimable = 0;
foreach ($todayTasks as $t) {
if ($t['completed'] && !$t['claimed']) {
$claimable += (int) $t['points'];
}
}
return array_merge([
'points' => $points,
'badges' => $badges,
'task_awards' => $taskAwards,
'today_tasks' => $todayTasks,
'claimable_points' => $claimable,
], self::treeMeta($points));
}
/**
* 浇水:领取今日已完成且未领取的任务积分
*/
public static function waterTree(int $userId, int $diagnosisId): array|false
{
self::$error = '';
if (!self::assertOwned($userId, $diagnosisId)) {
return false;
}
$row = DailyGamify::where('diagnosis_id', $diagnosisId)
->where('user_id', $userId)
->find();
$points = $row ? (int) $row['points'] : 0;
$badges = $row ? self::decodeJsonArray((string) ($row['badges'] ?? '')) : [];
$taskAwards = $row ? self::decodeJsonObject((string) ($row['task_awards'] ?? '')) : [];
$today = date('Y-m-d');
$todayTasks = self::buildTodayTasks($diagnosisId, $taskAwards);
$addedPoints = 0;
$claimedIds = [];
$pending = [];
if (!isset($taskAwards[$today]) || !is_array($taskAwards[$today])) {
$taskAwards[$today] = [];
}
foreach ($todayTasks as $task) {
if ($task['completed'] && !$task['claimed']) {
$id = (string) $task['id'];
$taskAwards[$today][$id] = true;
$addedPoints += (int) $task['points'];
$claimedIds[] = $id;
} elseif (!$task['completed']) {
$pending[] = [
'id' => $task['id'],
'name' => $task['name'],
];
}
}
if ($addedPoints <= 0) {
$claimable = 0;
foreach ($todayTasks as $t) {
if ($t['completed'] && !$t['claimed']) {
$claimable += (int) $t['points'];
}
}
$refreshedTasks = self::buildTodayTasks($diagnosisId, $taskAwards);
return [
'added_points' => 0,
'claimed_tasks' => [],
'claimable_points' => $claimable,
'pending_tasks' => $pending,
'points' => $points,
'badges' => $badges,
'task_awards' => $taskAwards,
'today_tasks' => $refreshedTasks,
'message' => $claimable > 0 ? '请先点击浇水领取积分' : (count($pending) ? '请先完成今日任务再浇水' : '今日奖励已全部领取'),
] + self::treeMeta($points);
}
$newPoints = $points + $addedPoints;
$saved = self::saveState($userId, $diagnosisId, $newPoints, $badges, $taskAwards);
if ($saved === false) {
return false;
}
$refreshed = self::buildTodayTasks($diagnosisId, $taskAwards);
return [
'added_points' => $addedPoints,
'claimed_tasks' => $claimedIds,
'claimable_points' => 0,
'pending_tasks' => $pending,
'points' => $newPoints,
'badges' => $badges,
'task_awards' => $taskAwards,
'today_tasks' => $refreshed,
'message' => "浇水成功,获得 {$addedPoints} 稳糖积分",
] + self::treeMeta($newPoints);
}
/**
* @param array<int,string> $badges
* @param array<string,array<string,bool>> $taskAwards
*/
public static function saveState(int $userId, int $diagnosisId, int $points, array $badges, array $taskAwards): array|false
{
self::$error = '';
if (!self::assertOwned($userId, $diagnosisId)) {
return false;
}
$points = max(0, (int) $points);
$badges = array_values(array_unique(array_filter(array_map('strval', $badges))));
if (!is_array($taskAwards)) {
$taskAwards = [];
}
$now = time();
$row = DailyGamify::where('diagnosis_id', $diagnosisId)
->where('user_id', $userId)
->find();
$data = [
'points' => $points,
'badges' => json_encode($badges, JSON_UNESCAPED_UNICODE),
'task_awards' => json_encode($taskAwards, JSON_UNESCAPED_UNICODE),
'update_time' => $now,
];
if ($row) {
DailyGamify::where('id', (int) $row['id'])->update($data);
} else {
$data['diagnosis_id'] = $diagnosisId;
$data['user_id'] = $userId;
$data['create_time'] = $now;
DailyGamify::create($data);
}
return [
'points' => $points,
'badges' => $badges,
'task_awards' => $taskAwards,
];
}
/**
* 本地缓存迁到服务端:取 points/badges/task_awards 的较大合并
*/
public static function mergeFromClient(int $userId, int $diagnosisId, int $points, array $badges, array $taskAwards): array|false
{
$server = self::getState($userId, $diagnosisId);
if ($server === false) {
return false;
}
$mergedPoints = max((int) $server['points'], max(0, $points));
$mergedBadges = array_values(array_unique(array_merge($server['badges'], $badges)));
$mergedAwards = $server['task_awards'];
foreach ($taskAwards as $date => $tasks) {
if (!is_array($tasks)) {
continue;
}
if (!isset($mergedAwards[$date]) || !is_array($mergedAwards[$date])) {
$mergedAwards[$date] = [];
}
foreach ($tasks as $taskId => $flag) {
if ($flag) {
$mergedAwards[$date][(string) $taskId] = true;
}
}
}
return self::saveState($userId, $diagnosisId, $mergedPoints, $mergedBadges, $mergedAwards);
}
protected static function decodeJsonArray(string $json): array
{
if ($json === '') {
return [];
}
$data = json_decode($json, true);
return is_array($data) ? array_values(array_map('strval', $data)) : [];
}
protected static function decodeJsonObject(string $json): array
{
if ($json === '') {
return [];
}
$data = json_decode($json, true);
return is_array($data) ? $data : [];
}
}
@@ -0,0 +1,200 @@
<?php
namespace app\api\logic\tcm;
use app\adminapi\logic\tcm\DiagnosisLogic;
use app\common\model\DiagnosisViewRecord;
use app\common\model\tcm\Diagnosis;
use app\common\model\user\User;
/**
* 日常血糖:手机号快捷建档(无完整就诊卡时)
*/
class DailyPhoneLogic
{
/** 小程序完整建档(edit_card */
public const CREATE_SOURCE_MNP = 'mnp';
/** 小程序手机号快捷建档(日常血糖) */
public const CREATE_SOURCE_MNP_DAILY = 'mnp_daily';
/**
* 用户 sex(1男2女) → 诊单 gender(1男0女)
*/
public static function mapUserSexToDiagnosisGender($sex): int
{
$sex = (int) $sex;
if ($sex === 2) {
return 0;
}
if ($sex === 1) {
return 1;
}
return 1;
}
/**
* 已绑定手机号则返回可用诊单;无卡时自动创建轻量档案
*
* @param array{sex?:int|null} $options sex: 用户表 1男2女,授权手机号时可传入
* @return array{ok:bool,need_mobile?:bool,error?:string,created?:bool,diagnosis_id?:int,patient_id?:int,patient_name?:string,gender?:int,age?:int,mobile?:string,create_source?:string}
*/
public static function ensureDailyContext(int $userId, array $options = []): array
{
if ($userId <= 0) {
return ['ok' => false, 'need_mobile' => false, 'error' => '请先登录'];
}
$user = User::where('id', $userId)
->field('id,nickname,real_name,mobile,sex,age')
->find();
if (!$user) {
return ['ok' => false, 'need_mobile' => false, 'error' => '用户不存在'];
}
$mobile = trim((string) ($user['mobile'] ?? ''));
if ($mobile === '') {
return ['ok' => false, 'need_mobile' => true, 'error' => '请先授权手机号'];
}
if (array_key_exists('sex', $options) && $options['sex'] !== null && $options['sex'] !== '') {
$sex = (int) $options['sex'];
if (in_array($sex, [1, 2], true) && (int) ($user['sex'] ?? 0) !== $sex) {
User::update(['id' => $userId, 'sex' => $sex]);
$user['sex'] = $sex;
}
}
$cardList = DiagnosisLogic::getCardList($userId);
if ($cardList === false) {
return [
'ok' => false,
'need_mobile' => false,
'error' => DiagnosisLogic::getError() ?: '获取就诊卡失败',
];
}
if (!empty($cardList)) {
$card = $cardList[0];
return self::buildContextOk($card, $mobile, false, false);
}
// 该手机号已在诊单库建档:关联查看记录,禁止重复创建轻量档案
$existing = Diagnosis::where('phone', $mobile)
->where('delete_time', null)
->order('id', 'desc')
->find();
if ($existing && (int) ($existing['show_card'] ?? 1) !== 1) {
return [
'ok' => false,
'need_mobile' => false,
'error' => '该手机号对应就诊卡因隐私设置已隐藏,请联系医生',
];
}
if ($existing) {
if (!self::ensureUserViewRecord($userId, (int) $existing['id'], (int) $existing['patient_id'])) {
return [
'ok' => false,
'need_mobile' => false,
'error' => '该手机号已建档,暂无法关联到当前账号',
];
}
return self::buildContextOk([
'id' => (int) $existing['id'],
'patient_id' => (int) $existing['patient_id'],
'patient_name' => (string) ($existing['patient_name'] ?? ''),
'gender' => (int) ($existing['gender'] ?? 0),
'age' => (int) ($existing['age'] ?? 0),
'create_source' => (string) ($existing['create_source'] ?? ''),
], $mobile, false, true);
}
$displayName = trim((string) (($user['real_name'] ?? '') ?: ($user['nickname'] ?? '')));
if ($displayName === '') {
$displayName = '用户' . substr($mobile, -4);
}
$gender = self::mapUserSexToDiagnosisGender($user['sex'] ?? 1);
$result = DiagnosisLogic::addCard([
'user_id' => $userId,
'patient_name' => $displayName,
'phone' => $mobile,
'gender' => $gender,
'age' => max(0, (int) ($user['age'] ?? 0)),
'diagnosis_date' => time(),
'create_source' => self::CREATE_SOURCE_MNP_DAILY,
'remark' => '小程序手机号快捷建档(日常血糖)',
]);
if ($result === false) {
return [
'ok' => false,
'need_mobile' => false,
'error' => DiagnosisLogic::getError() ?: '创建档案失败',
];
}
return self::buildContextOk([
'id' => (int) $result['id'],
'patient_id' => (int) $result['patient_id'],
'patient_name' => $displayName,
'gender' => $gender,
'age' => max(0, (int) ($user['age'] ?? 0)),
'create_source' => self::CREATE_SOURCE_MNP_DAILY,
], $mobile, true, false);
}
/**
* @param array{id:int,patient_id:int,patient_name?:string,gender?:int,age?:int,create_source?:string} $card
*/
private static function buildContextOk(array $card, string $mobile, bool $created, bool $linkedExisting): array
{
return [
'ok' => true,
'need_mobile' => false,
'created' => $created,
'linked_existing' => $linkedExisting,
'diagnosis_id' => (int) $card['id'],
'patient_id' => (int) $card['patient_id'],
'patient_name' => (string) ($card['patient_name'] ?? ''),
'gender' => (int) ($card['gender'] ?? 0),
'age' => (int) ($card['age'] ?? 0),
'mobile' => $mobile,
'create_source' => (string) ($card['create_source'] ?? ''),
];
}
/** 将已有诊单挂到当前小程序用户(diagnosis_view_records */
private static function ensureUserViewRecord(int $userId, int $diagnosisId, int $patientId): bool
{
if ($userId <= 0 || $diagnosisId <= 0) {
return false;
}
try {
$exists = DiagnosisViewRecord::where('user_id', $userId)
->where('diagnosis_id', $diagnosisId)
->where('delete_time', null)
->find();
if ($exists) {
return true;
}
$now = time();
DiagnosisViewRecord::create([
'user_id' => $userId,
'diagnosis_id' => $diagnosisId,
'patient_id' => $patientId,
'share_user_id' => 0,
'view_count' => 1,
'first_view_time' => $now,
'last_view_time' => $now,
'is_confirmed' => 0,
'create_time' => $now,
'update_time' => $now,
]);
return true;
} catch (\Throwable $e) {
return false;
}
}
}
@@ -0,0 +1,376 @@
<?php
namespace app\api\logic\tcm;
use app\common\model\tcm\BloodRecord;
use app\common\model\tcm\DailyShareInvite;
use app\common\model\tcm\Diagnosis;
/**
* 日常记录分享邀请码(当日有效、脱敏预览)
*/
class DailyShareLogic
{
protected static string $error = '';
public static function getError(): string
{
return self::$error;
}
protected static function setError(string $msg): bool
{
self::$error = $msg;
return false;
}
/**
* 生成当日邀请码(分享人须已拥有诊单)
*/
public static function createInvite(int $userId, int $diagnosisId): array|false
{
self::$error = '';
if ($userId <= 0) {
return self::setError('请先登录') ? false : false;
}
if ($diagnosisId <= 0) {
return self::setError('诊单ID不能为空') ? false : false;
}
$owned = \think\facade\Db::name('diagnosis_view_records')
->where('user_id', $userId)
->where('diagnosis_id', $diagnosisId)
->where('delete_time', null)
->find();
if (!$owned) {
return self::setError('无权分享该诊单') ? false : false;
}
$diagnosis = Diagnosis::where('id', $diagnosisId)->where('delete_time', null)->find();
if (!$diagnosis) {
return self::setError('诊单不存在') ? false : false;
}
if ((int) ($diagnosis['show_card'] ?? 1) !== 1) {
return self::setError('该就诊卡已在统计端隐藏') ? false : false;
}
$inviteDate = date('Y-m-d');
$code = self::generateUniqueCode();
DailyShareInvite::create([
'invite_code' => $code,
'diagnosis_id' => $diagnosisId,
'user_id' => $userId,
'invite_date' => $inviteDate,
'create_time' => time(),
]);
return [
'invite_code' => $code,
'invite_date' => $inviteDate,
'expires_hint' => '邀请码仅今日有效,明日将无法查看',
'share_path' => '/tongji/pages/index?from=share&invite_code=' . $code,
];
}
/**
* 凭邀请码查看分享战报(含近 7 日血糖/血压记录,仅当日邀请码有效)
*/
public static function previewByInviteCode(string $inviteCode, string $viewerKey = ''): array|false
{
self::$error = '';
$inviteCode = strtoupper(trim($inviteCode));
if ($inviteCode === '') {
return self::setError('邀请码不能为空') ? false : false;
}
$row = DailyShareInvite::where('invite_code', $inviteCode)->find();
if (!$row) {
return self::setError('邀请码无效或已失效') ? false : false;
}
$today = date('Y-m-d');
if ((string) $row['invite_date'] !== $today) {
return self::setError('邀请码已过期,仅可在分享当天查看') ? false : false;
}
$diagnosisId = (int) $row['diagnosis_id'];
$diagnosis = Diagnosis::where('id', $diagnosisId)->where('delete_time', null)->find();
if (!$diagnosis) {
return self::setError('诊单不存在') ? false : false;
}
$age = (int) ($diagnosis['age'] ?? 0);
$stats = self::buildDesensitizedWeekStats($diagnosisId, $age);
$name = trim((string) ($diagnosis['patient_name'] ?? ''));
$label = self::maskPatientName($name);
$likeMeta = DailyFamilyLikeLogic::metaForInvite($inviteCode, $viewerKey);
return array_merge($stats, $likeMeta, [
'invite_code' => $inviteCode,
'invite_date' => $today,
'expires_hint' => '本邀请码仅今日有效,明日将无法查看',
'viewer_notice' => '您正在查看家人分享的近7日血糖记录',
'patient_label' => $label,
]);
}
protected static function generateUniqueCode(): string
{
for ($i = 0; $i < 8; $i++) {
$code = strtoupper(substr(bin2hex(random_bytes(4)), 0, 8));
if (!DailyShareInvite::where('invite_code', $code)->find()) {
return $code;
}
}
return strtoupper(substr(uniqid('', true), -8));
}
protected static function maskPatientName(string $name): string
{
$name = trim($name);
if ($name === '') {
return '家人';
}
$len = mb_strlen($name, 'UTF-8');
if ($len <= 1) {
return $name . '*';
}
if ($len === 2) {
return mb_substr($name, 0, 1, 'UTF-8') . '*';
}
return mb_substr($name, 0, 1, 'UTF-8') . '*' . mb_substr($name, -1, 1, 'UTF-8');
}
/**
* 近 7 天习惯统计 + 每日血糖/血压记录(供家人分享页展示)
*/
public static function buildDesensitizedWeekStats(int $diagnosisId, int $age = 0): array
{
$today = new \DateTime('today');
$dayKeys = [];
for ($i = 6; $i >= 0; $i--) {
$d = clone $today;
$d->modify("-{$i} days");
$dayKeys[] = $d->format('Y-m-d');
}
$startTs = strtotime($dayKeys[0] . ' 00:00:00');
$endTs = strtotime($dayKeys[6] . ' 23:59:59');
$rows = BloodRecord::where('diagnosis_id', $diagnosisId)
->where('record_date', '>=', $startTs)
->where('record_date', '<=', $endTs)
->field('record_date,fasting_blood_sugar,postprandial_blood_sugar,other_blood_sugar,systolic_pressure,diastolic_pressure')
->select()
->toArray();
$byDate = [];
foreach ($rows as $r) {
$key = date('Y-m-d', (int) $r['record_date']);
if (!isset($byDate[$key])) {
$byDate[$key] = $r;
} else {
foreach (['fasting_blood_sugar', 'postprandial_blood_sugar', 'other_blood_sugar', 'systolic_pressure', 'diastolic_pressure'] as $f) {
if (self::hasValue($r[$f]) && !self::hasValue($byDate[$key][$f])) {
$byDate[$key][$f] = $r[$f];
}
}
}
}
$recordDays = 0;
$completeDays = 0;
foreach ($dayKeys as $key) {
$b = $byDate[$key] ?? null;
if (!$b || !self::dayHasBlood($b)) {
continue;
}
$recordDays++;
if (self::hasValue($b['fasting_blood_sugar']) && self::hasValue($b['postprandial_blood_sugar'])) {
$completeDays++;
}
}
$streakDays = self::calcStreakDays($diagnosisId);
$tree = self::treeMeta($recordDays);
$quote = self::buildQuote($recordDays, $completeDays);
$weekdayLabels = ['日', '一', '二', '三', '四', '五', '六'];
$dailyRecords = [];
foreach ($dayKeys as $key) {
$b = $byDate[$key] ?? null;
$dt = new \DateTime($key);
$w = (int) $dt->format('w');
$has = $b && self::dayHasBlood($b);
$fasting = $has ? self::formatSugarValue($b['fasting_blood_sugar'] ?? null) : null;
$post = $has ? self::formatSugarValue($b['postprandial_blood_sugar'] ?? null) : null;
$other = $has ? self::formatSugarValue($b['other_blood_sugar'] ?? null) : null;
$sys = $has ? self::formatSugarValue($b['systolic_pressure'] ?? null) : null;
$dia = $has ? self::formatSugarValue($b['diastolic_pressure'] ?? null) : null;
$dailyRecords[] = [
'date' => $key,
'date_label' => $dt->format('n') . '/' . $dt->format('j'),
'weekday' => '周' . $weekdayLabels[$w],
'has_record' => $has,
'fasting' => $fasting,
'fasting_high' => self::isHighFasting($fasting, $age),
'postprandial' => $post,
'postprandial_high' => self::isHighPostprandial($post, $age),
'other' => $other,
'other_high' => self::isHighPostprandial($other, $age),
'systolic' => $sys,
'diastolic' => $dia,
'bp_high' => self::isHighBp($sys, $dia),
'bp_text' => self::formatBpText($sys, $dia),
];
}
return [
'week_label' => $today->format('Y') . '年 第' . self::weekOfYear($today) . '周',
'record_days' => $recordDays,
'complete_days' => $completeDays,
'streak_days' => $streakDays,
'quote' => $quote,
'tree_emoji' => $tree['emoji'],
'tree_title' => $tree['title'],
'tree_desc' => $tree['desc'],
'tree_level' => $tree['level'],
'daily_records' => $dailyRecords,
];
}
protected static function formatSugarValue($v): ?float
{
if (!self::hasValue($v)) {
return null;
}
return round((float) $v, 1);
}
protected static function getBloodSugarThresholds(int $age): ?array
{
if ($age <= 0) {
return null;
}
if ($age < 50) {
return ['fasting' => 7.0, 'postprandial' => 9.0];
}
return ['fasting' => 8.0, 'postprandial' => 10.0];
}
protected static function isHighFasting(?float $v, int $age): bool
{
$t = self::getBloodSugarThresholds($age);
return $v !== null && $t !== null && $v >= $t['fasting'];
}
protected static function isHighPostprandial(?float $v, int $age): bool
{
$t = self::getBloodSugarThresholds($age);
return $v !== null && $t !== null && $v >= $t['postprandial'];
}
protected static function isHighBp(?float $systolic, ?float $diastolic): bool
{
return ($systolic !== null && $systolic > 140)
|| ($diastolic !== null && $diastolic > 90);
}
protected static function formatBpText(?float $systolic, ?float $diastolic): string
{
if ($systolic === null && $diastolic === null) {
return '';
}
$s = $systolic !== null ? (string) (int) round($systolic) : '—';
$d = $diastolic !== null ? (string) (int) round($diastolic) : '—';
return $s . '/' . $d;
}
protected static function hasValue($v): bool
{
if ($v === null || $v === '' || $v === '0' || $v === 0) {
return false;
}
return is_numeric($v) && (float) $v > 0;
}
protected static function dayHasBlood(array $b): bool
{
return self::hasValue($b['fasting_blood_sugar'] ?? null)
|| self::hasValue($b['postprandial_blood_sugar'] ?? null)
|| self::hasValue($b['other_blood_sugar'] ?? null)
|| self::hasValue($b['systolic_pressure'] ?? null)
|| self::hasValue($b['diastolic_pressure'] ?? null);
}
protected static function calcStreakDays(int $diagnosisId): int
{
$today = new \DateTime('today');
$count = 0;
for ($i = 0; $i < 90; $i++) {
$d = clone $today;
$d->modify("-{$i} days");
$key = $d->format('Y-m-d');
$start = strtotime($key . ' 00:00:00');
$end = strtotime($key . ' 23:59:59');
$exists = BloodRecord::where('diagnosis_id', $diagnosisId)
->where('record_date', '>=', $start)
->where('record_date', '<=', $end)
->whereRaw('(fasting_blood_sugar > 0 OR postprandial_blood_sugar > 0 OR other_blood_sugar > 0 OR systolic_pressure > 0 OR diastolic_pressure > 0)')
->find();
if ($exists) {
$count++;
continue;
}
if ($i === 0) {
continue;
}
break;
}
return $count;
}
protected static function treeMeta(int $recordDays): array
{
if ($recordDays >= 7) {
return ['level' => 4, 'emoji' => '🌸', 'title' => '控糖树 · 开花啦', 'desc' => '本周每天都记录了'];
}
if ($recordDays >= 5) {
return ['level' => 3, 'emoji' => '🌳', 'title' => '控糖树 · 枝繁叶茂', 'desc' => "本周 {$recordDays}/7 天有记录"];
}
if ($recordDays >= 3) {
return ['level' => 2, 'emoji' => '🌿', 'title' => '控糖树 · 茁壮成长', 'desc' => "本周 {$recordDays}/7 天有记录"];
}
if ($recordDays >= 1) {
return ['level' => 1, 'emoji' => '🌱', 'title' => '控糖树 · 破土发芽', 'desc' => '本周已开始记录'];
}
return ['level' => 0, 'emoji' => '🪴', 'title' => '控糖树 · 等待浇水', 'desc' => '本周暂无记录'];
}
protected static function buildQuote(int $recordDays, int $completeDays): string
{
if ($recordDays >= 7) {
return '本周每天都留下了记录,这份自律值得骄傲!';
}
if ($completeDays >= 5) {
return "本周有 {$completeDays} 天完成了空腹+餐后记录,习惯越来越稳。";
}
if ($recordDays >= 4) {
return "本周已记录 {$recordDays} 天,坚持就是胜利。";
}
if ($recordDays > 0) {
return '好的开始!继续记录会更稳。';
}
return '分享者本周尚未记录,鼓励 Ta 每天记一笔。';
}
protected static function weekOfYear(\DateTime $date): int
{
return (int) $date->format('W');
}
}
@@ -0,0 +1,209 @@
<?php
namespace app\api\logic\tcm;
/**
* 三餐推荐硬性规则校验(午餐高蛋白、淀粉不重复、禁高 GI)
*/
class DietMealValidator
{
/** 淀粉类关键词 → 分组(同组即视为同一种淀粉) */
private const STARCH_GROUPS = [
'porridge' => ['粥', '稀饭', '玉米碴', '棒子面', '高粱', '糊糊'],
'rice' => ['米饭', '糙米饭', '二米饭', '杂豆饭', '红米饭', '饭'],
'noodle' => ['挂面', '面条', '手擀面', '拉面', '刀削面'],
'bun' => ['馒头', '窝头', '贴饼', '玉米面饼', '杂面馒头', '杂面窝头', '杂面', '饼'],
'potato' => ['红薯', '地瓜', '番薯', '土豆', '洋芋', '芋头'],
'pumpkin' => ['南瓜'],
];
/** 蛋白质关键词(出现即计 1,同词不重复计) */
private const PROTEIN_KEYWORDS = [
'鲫鱼', '鲤鱼', '小鱼', '清蒸鱼', '炖鱼', '鱼',
'虾', '蟹',
'鸡肉', '鸡胸', '鸡', '鸭肉', '鸭',
'牛肉', '羊肉', '猪肉', '瘦肉', '肉',
'鸡蛋', '茶叶蛋', '蛋羹', '炒蛋', '蛋',
'豆腐脑', '豆干', '豆腐', '豆角', '芸豆', '扁豆',
];
/** 高 GI 禁用(出现在任一餐即违规) */
private const FORBIDDEN_HIGH_GI = [
'白馒头', '馒头', '油条', '粘豆包', '糯米饭', '西瓜', '荔枝', '龙眼',
'含糖饮料', '可乐', '汽水', '糖糕', '糕点', '白稀饭', '稀饭',
];
/**
* 校验并规范化三餐方案;不通过则 ok=false
*
* @param array{breakfast?:string,lunch?:string,dinner?:string,tips?:string,avoid?:array} $plan
* @return array{ok:bool,errors:list<string>,plan:array,meta:array}
*/
public static function validateAndNormalize(array $plan): array
{
$breakfast = trim((string) ($plan['breakfast'] ?? ''));
$lunch = trim((string) ($plan['lunch'] ?? ''));
$dinner = trim((string) ($plan['dinner'] ?? ''));
$errors = [];
if ($breakfast === '' || $lunch === '' || $dinner === '') {
$errors[] = '三餐内容不完整';
}
foreach (self::FORBIDDEN_HIGH_GI as $bad) {
foreach (['breakfast' => $breakfast, 'lunch' => $lunch, 'dinner' => $dinner] as $mealName => $text) {
if ($text !== '' && mb_strpos($text, $bad) !== false) {
// 「杂面馒头」含馒头但可接受;纯「馒头」才禁
if ($bad === '馒头' && (mb_strpos($text, '杂面') !== false || mb_strpos($text, '玉米面') !== false)) {
continue;
}
if ($bad === '稀饭' && mb_strpos($text, '玉米') !== false) {
continue;
}
$errors[] = "{$mealName}含高 GI 食物「{$bad}";
}
}
}
$bfStarch = self::detectStarchGroups($breakfast);
$luStarch = self::detectStarchGroups($lunch);
$diStarch = self::detectStarchGroups($dinner);
if (count($bfStarch) > 1) {
$errors[] = '早餐淀粉种类超过 1 种';
}
if (count($luStarch) > 1) {
$errors[] = '午餐淀粉种类超过 1 种';
}
if (count($diStarch) > 1) {
$errors[] = '晚餐淀粉种类超过 1 种';
}
$dayGroups = array_values(array_filter([
$bfStarch[0] ?? null,
$luStarch[0] ?? null,
$diStarch[0] ?? null,
]));
if (count($dayGroups) !== count(array_unique($dayGroups))) {
$errors[] = '早中晚淀粉种类重复';
}
$bfProtein = self::countProteinHits($breakfast);
$luProtein = self::countProteinHits($lunch);
$diProtein = self::countProteinHits($dinner);
if ($luProtein < 2) {
$errors[] = '午餐高蛋白不足(至少 2 样:鱼/肉/蛋/豆腐)';
}
if ($luProtein < $bfProtein || $luProtein < $diProtein) {
$errors[] = '午餐蛋白质应多于早、晚餐';
}
$avoid = is_array($plan['avoid'] ?? null) ? $plan['avoid'] : [];
if (count($avoid) < 3) {
$avoid = array_values(array_unique(array_merge($avoid, [
'白面馒头', '油条', '粘豆包', '西瓜', '含糖饮料',
])));
$avoid = array_slice($avoid, 0, 5);
}
$tips = trim((string) ($plan['tips'] ?? ''));
if ($tips === '') {
$tips = '中午鱼蛋豆肉吃足;早中晚各一种主食,别重复。';
}
$normalized = [
'breakfast' => $breakfast,
'drinks' => trim((string) ($plan['drinks'] ?? '')),
'lunch' => $lunch,
'dinner' => $dinner,
'tips' => $tips,
'avoid' => $avoid,
];
$meta = [
'protein' => ['breakfast' => $bfProtein, 'lunch' => $luProtein, 'dinner' => $diProtein],
'starch' => ['breakfast' => $bfStarch[0] ?? '', 'lunch' => $luStarch[0] ?? '', 'dinner' => $diStarch[0] ?? ''],
'rules_ok' => empty($errors),
];
return [
'ok' => empty($errors),
'errors' => $errors,
'plan' => $normalized,
'meta' => $meta,
];
}
/**
* @return list<string> 淀粉分组 id,按命中顺序
*/
public static function detectStarchGroups(string $text): array
{
if ($text === '') {
return [];
}
$found = [];
foreach (self::STARCH_GROUPS as $groupId => $keywords) {
foreach ($keywords as $kw) {
if (mb_strpos($text, $kw) !== false) {
$found[$groupId] = true;
break;
}
}
}
return array_keys($found);
}
public static function countProteinHits(string $text): int
{
if ($text === '') {
return 0;
}
$count = 0;
$used = [];
foreach (self::PROTEIN_KEYWORDS as $kw) {
if (isset($used[$kw])) {
continue;
}
if (mb_strpos($text, $kw) !== false) {
// 「鱼」已命中则不再计「小鱼」「鲫鱼」
$skip = false;
foreach ($used as $u) {
if (mb_strpos($u, $kw) !== false || mb_strpos($kw, $u) !== false) {
$skip = true;
break;
}
}
if ($skip) {
continue;
}
$used[$kw] = true;
$count++;
}
}
return $count;
}
public static function metaSummary(array $meta): string
{
$p = $meta['protein'] ?? [];
$s = $meta['starch'] ?? [];
$starchLabels = [
'porridge' => '粥', 'rice' => '饭', 'noodle' => '面', 'bun' => '饼/窝头',
'potato' => '薯', 'pumpkin' => '南瓜',
];
$sBf = $starchLabels[$s['breakfast'] ?? ''] ?? ($s['breakfast'] ?: '—');
$sLu = $starchLabels[$s['lunch'] ?? ''] ?? ($s['lunch'] ?: '—');
$sDi = $starchLabels[$s['dinner'] ?? ''] ?? ($s['dinner'] ?: '—');
return sprintf(
'午餐 %d 样蛋白(早%d/晚%d);淀粉:早%s·午%s·晚%s',
(int) ($p['lunch'] ?? 0),
(int) ($p['breakfast'] ?? 0),
(int) ($p['dinner'] ?? 0),
$sBf,
$sLu,
$sDi
);
}
}
@@ -0,0 +1,530 @@
<?php
namespace app\api\logic\tcm;
use app\common\service\FileService;
use think\facade\Db;
use think\facade\Log;
/**
* 控糖消消乐平台能力:真实用户、每周7人同行榜、幂等成绩上报和微信分享。
*/
class GamePlatformLogic
{
private const GROUP_SIZE = 7;
private const MAX_SESSION_LEARNED = 20000;
private const MAX_SCORE = 100000000;
protected static string $error = '';
public static function getError(): string
{
return self::$error;
}
protected static function fail(string $message): bool
{
self::$error = $message;
return false;
}
/**
* 获取当前用户所在的真实周榜;首次进入会分配到当周同性别7人组。
*/
public static function leaderboard(int $userId): array|false
{
self::$error = '';
if ($userId <= 0) {
return self::fail('请先登录');
}
try {
Db::startTrans();
$score = self::ensureWeeklyScore($userId, self::weekStart());
$inviteCode = self::ensureShareInvite($userId, self::weekStart());
Db::commit();
return self::buildLeaderboard((int) $score['group_id'], $userId, $inviteCode);
} catch (\Throwable $e) {
Db::rollback();
self::logException('leaderboard', $e);
return self::fail('同行榜暂时不可用,请稍后再试');
}
}
/**
* 上报每局绝对进度。session_key + learned_count 共同保证网络重试不会重复计分。
*
* @param array{session_key:string,learned_count:int,score:int,ended:int|bool} $params
*/
public static function submitProgress(int $userId, array $params): array|false
{
self::$error = '';
if ($userId <= 0) {
return self::fail('请先登录');
}
$sessionKey = trim((string) ($params['session_key'] ?? ''));
if (!preg_match('/^[A-Za-z0-9_-]{16,64}$/', $sessionKey)) {
return self::fail('游戏局标识无效');
}
$learned = max(0, min(self::MAX_SESSION_LEARNED, (int) ($params['learned_count'] ?? 0)));
$scoreValue = max(0, min(self::MAX_SCORE, (int) ($params['score'] ?? 0)));
$ended = !empty($params['ended']) ? 1 : 0;
$weekStart = self::weekStart();
try {
Db::startTrans();
$weeklyScore = self::ensureWeeklyScore($userId, $weekStart);
$session = Db::name('tcm_game_session')
->where('session_key', $sessionKey)
->lock(true)
->find();
$now = time();
if ($session && (int) $session['user_id'] !== $userId) {
Db::rollback();
return self::fail('游戏局标识已被使用');
}
if (!$session) {
$sessionId = Db::name('tcm_game_session')->insertGetId([
'session_key' => $sessionKey,
'user_id' => $userId,
'week_start' => $weekStart,
'learned_count' => 0,
'last_score' => 0,
'ended' => 0,
'create_time' => $now,
'update_time' => $now,
]);
$session = [
'id' => $sessionId,
'week_start' => $weekStart,
'learned_count' => 0,
'last_score' => 0,
'ended' => 0,
];
}
$sessionWeek = (string) $session['week_start'];
if ($sessionWeek !== $weekStart) {
$weeklyScore = self::ensureWeeklyScore($userId, $sessionWeek);
}
$confirmedLearned = (int) $session['learned_count'];
$nextLearned = max($confirmedLearned, $learned);
$delta = $nextLearned - $confirmedLearned;
$wasEnded = (int) $session['ended'] === 1;
$markEnded = $wasEnded || $ended === 1;
Db::name('tcm_game_session')->where('id', (int) $session['id'])->update([
'learned_count' => $nextLearned,
'last_score' => max((int) $session['last_score'], $scoreValue),
'ended' => $markEnded ? 1 : 0,
'update_time' => $now,
]);
$weeklyLearned = (int) $weeklyScore['learned_count'] + $delta;
$weeklyBest = max((int) $weeklyScore['best_score'], $scoreValue);
$gamesPlayed = (int) $weeklyScore['games_played'] + (!$wasEnded && $ended === 1 ? 1 : 0);
Db::name('tcm_game_weekly_score')->where('id', (int) $weeklyScore['id'])->update([
'learned_count' => $weeklyLearned,
'best_score' => $weeklyBest,
'games_played' => $gamesPlayed,
'update_time' => $now,
]);
$inviteCode = self::ensureShareInvite($userId, $sessionWeek);
Db::commit();
$result = self::buildLeaderboard((int) $weeklyScore['group_id'], $userId, $inviteCode, $sessionWeek);
$result['confirmed_session_learned'] = $nextLearned;
return $result;
} catch (\Throwable $e) {
Db::rollback();
self::logException('submitProgress', $e);
return self::fail('成绩保存失败,请稍后再试');
}
}
/** 记录用户发起一次微信分享,并返回当前分享码。 */
public static function recordShare(int $userId): array|false
{
self::$error = '';
if ($userId <= 0) {
return self::fail('请先登录');
}
try {
Db::startTrans();
$score = self::ensureWeeklyScore($userId, self::weekStart());
Db::name('tcm_game_weekly_score')->where('id', (int) $score['id'])->inc('share_count')->update([
'update_time' => time(),
]);
$inviteCode = self::ensureShareInvite($userId, self::weekStart());
Db::commit();
return ['invite_code' => $inviteCode];
} catch (\Throwable $e) {
Db::rollback();
self::logException('recordShare', $e);
return self::fail('分享记录失败');
}
}
/**
* 记录从分享卡片进入。仅记录一次轻量同行关系,不做家庭/好友强绑定。
*/
public static function acceptShare(int $userId, string $inviteCode): array|false
{
self::$error = '';
$inviteCode = strtoupper(trim($inviteCode));
if ($userId <= 0) {
return self::fail('请先登录');
}
if (!preg_match('/^[A-F0-9]{12}$/', $inviteCode)) {
return self::fail('分享码无效');
}
try {
$invite = Db::name('tcm_game_share_invite')->where('invite_code', $inviteCode)->find();
if (!$invite) {
return self::fail('分享已失效');
}
$inviterUserId = (int) $invite['user_id'];
if ($inviterUserId === $userId) {
return ['accepted' => false, 'message' => '这是您自己的分享'];
}
Db::startTrans();
$inserted = Db::name('tcm_game_share_visit')->duplicate([
'invite_code',
])->insert([
'invite_code' => $inviteCode,
'inviter_user_id' => $inviterUserId,
'visitor_user_id' => $userId,
'create_time' => time(),
]);
$accepted = $inserted === 1;
if ($accepted) {
Db::name('tcm_game_share_invite')->where('id', (int) $invite['id'])->inc('open_count')->update([
'update_time' => time(),
]);
}
Db::commit();
$inviter = Db::name('user')->where('id', $inviterUserId)->field('nickname')->find();
return [
'accepted' => $accepted,
'message' => '已加入控糖消消乐',
'inviter' => self::displayName((string) ($inviter['nickname'] ?? ''), $inviterUserId),
];
} catch (\Throwable $e) {
Db::rollback();
self::logException('acceptShare', $e);
return self::fail('分享关系记录失败');
}
}
private static function ensureWeeklyScore(int $userId, string $weekStart): array
{
$profile = self::userProfile($userId);
$now = time();
$existing = Db::name('tcm_game_weekly_score')
->where('week_start', $weekStart)
->where('user_id', $userId)
->find();
if ($existing) {
$existing = Db::name('tcm_game_weekly_score')
->where('id', (int) $existing['id'])
->lock(true)
->find();
$profileChanged = (string) $existing['nickname'] !== $profile['nickname']
|| (string) $existing['avatar'] !== $profile['avatar'];
if ($profileChanged) {
Db::name('tcm_game_weekly_score')->where('id', (int) $existing['id'])->update([
'nickname' => $profile['nickname'],
'avatar' => $profile['avatar'],
'update_time'=> $now,
]);
$existing['nickname'] = $profile['nickname'];
$existing['avatar'] = $profile['avatar'];
}
return $existing;
}
// 每周、每个性别使用一行分配锁串行化首次入组。直接 upsert 锁行,
// 避免空分组上的间隙锁导致首批并发请求互相等待或偶发死锁。
Db::name('tcm_game_weekly_allocator')->duplicate([
'update_time',
])->insert([
'week_start' => $weekStart,
'sex' => $profile['sex'],
'create_time'=> $now,
'update_time'=> $now,
]);
$allocator = Db::name('tcm_game_weekly_allocator')
->where('week_start', $weekStart)
->where('sex', $profile['sex'])
->lock(true)
->find();
if (!$allocator) {
throw new \RuntimeException('同行分配锁创建失败');
}
// 等待分配锁期间,同一用户的另一个请求可能已经完成分配。
$existing = Db::name('tcm_game_weekly_score')
->where('week_start', $weekStart)
->where('user_id', $userId)
->lock(true)
->find();
if ($existing) {
return $existing;
}
$group = Db::name('tcm_game_weekly_group')
->where('week_start', $weekStart)
->where('sex', $profile['sex'])
->where('member_count', '<', self::GROUP_SIZE)
->order('group_no', 'asc')
->lock(true)
->find();
if (!$group) {
$maxGroupNo = (int) Db::name('tcm_game_weekly_group')
->where('week_start', $weekStart)
->where('sex', $profile['sex'])
->max('group_no');
$groupNo = $maxGroupNo + 1;
// 首批用户并发进入时可能同时算出相同 group_no。利用唯一键 upsert
// 让请求汇合到同一组,再锁定该组继续分配,避免偶发 1062/死锁。
Db::name('tcm_game_weekly_group')->duplicate([
'update_time',
])->insert([
'week_start' => $weekStart,
'sex' => $profile['sex'],
'group_no' => $groupNo,
'member_count'=> 0,
'create_time' => $now,
'update_time' => $now,
]);
$group = Db::name('tcm_game_weekly_group')
->where('week_start', $weekStart)
->where('sex', $profile['sex'])
->where('group_no', $groupNo)
->lock(true)
->find();
if (!$group) {
throw new \RuntimeException('同行分组创建失败');
}
}
$scoreRow = [
'group_id' => (int) $group['id'],
'week_start' => $weekStart,
'user_id' => $userId,
'learned_count' => 0,
'best_score' => 0,
'games_played' => 0,
'share_count' => 0,
'nickname' => $profile['nickname'],
'avatar' => $profile['avatar'],
'sex' => $profile['sex'],
'create_time' => $now,
'update_time' => $now,
];
$inserted = Db::name('tcm_game_weekly_score')->duplicate([
'nickname',
'avatar',
'sex',
'update_time',
])->insert($scoreRow);
$score = Db::name('tcm_game_weekly_score')
->where('week_start', $weekStart)
->where('user_id', $userId)
->lock(true)
->find();
if (!$score) {
throw new \RuntimeException('同行成绩创建失败');
}
// 仅新插入时刷新人数;使用实际成绩行数纠正历史并发造成的计数漂移。
if ($inserted === 1) {
$memberCount = (int) Db::name('tcm_game_weekly_score')
->where('group_id', (int) $group['id'])
->count();
Db::name('tcm_game_weekly_group')->where('id', (int) $group['id'])->update([
'member_count' => min(self::GROUP_SIZE, $memberCount),
'update_time' => $now,
]);
}
return $score;
}
private static function buildLeaderboard(
int $groupId,
int $userId,
string $inviteCode,
?string $weekStart = null
): array {
$weekStart = $weekStart ?: self::weekStart();
$rows = Db::name('tcm_game_weekly_score')
->where('group_id', $groupId)
->where('week_start', $weekStart)
->order('learned_count', 'desc')
->order('best_score', 'desc')
->order('create_time', 'asc')
->limit(self::GROUP_SIZE)
->select()
->toArray();
$players = [];
$myIndex = 0;
foreach ($rows as $index => $row) {
$isMe = (int) $row['user_id'] === $userId;
if ($isMe) {
$myIndex = $index;
}
$players[] = [
// 前端只需要稳定列表键,不暴露平台内部 user_id。
'id' => (int) $row['id'],
'name' => self::displayName((string) $row['nickname'], (int) $row['user_id']),
'avatar' => self::avatarUrl((string) $row['avatar']),
'count' => (int) $row['learned_count'],
'best_score' => (int) $row['best_score'],
'rank' => $index + 1,
'is_me' => $isMe,
];
}
$me = $players[$myIndex] ?? [
'count' => 0,
'rank' => 1,
'best_score' => 0,
];
$distance = $myIndex > 0
? max(1, (int) $players[$myIndex - 1]['count'] - (int) $me['count'] + 1)
: 0;
$group = Db::name('tcm_game_weekly_group')->where('id', $groupId)->find();
$sex = (int) ($group['sex'] ?? 0);
return [
'week_start' => $weekStart,
'week_end' => date('Y-m-d', strtotime($weekStart . ' +6 days')),
'sex' => $sex,
'sex_label' => $sex === 1 ? '男士同行' : ($sex === 2 ? '女士同行' : '同行'),
'group_size' => self::GROUP_SIZE,
'member_count'=> count($players),
'players' => $players,
'me' => [
'count' => (int) ($me['count'] ?? 0),
'rank' => (int) ($me['rank'] ?? 1),
'best_score' => (int) ($me['best_score'] ?? 0),
'distance' => $distance,
'is_first' => $myIndex === 0,
],
'invite_code' => $inviteCode,
];
}
/** @return array{nickname:string,avatar:string,sex:int} */
private static function userProfile(int $userId): array
{
$user = Db::name('user')
->where('id', $userId)
->whereNull('delete_time')
->field('id,sn,nickname,avatar,sex')
->find();
if (!$user) {
throw new \RuntimeException('用户不存在');
}
$sex = (int) ($user['sex'] ?? 0);
if ($sex !== 1 && $sex !== 2) {
$gender = Db::name('diagnosis_view_records')->alias('v')
->join('tcm_diagnosis d', 'd.id = v.diagnosis_id')
->where('v.user_id', $userId)
->whereNull('v.delete_time')
->whereNull('d.delete_time')
->order('v.id', 'desc')
->value('d.gender');
if ($gender !== null && $gender !== '') {
$sex = (int) $gender === 1 ? 1 : 2;
}
}
return [
'nickname' => self::displayName((string) ($user['nickname'] ?? ''), $userId),
'avatar' => (string) ($user['avatar'] ?? ''),
'sex' => in_array($sex, [1, 2], true) ? $sex : 0,
];
}
private static function displayName(string $nickname, int $userId): string
{
$nickname = trim(strip_tags($nickname));
if ($nickname === '') {
return '控糖好友' . substr((string) $userId, -2);
}
return mb_substr($nickname, 0, 12);
}
private static function avatarUrl(string $avatar): string
{
return $avatar === '' ? '' : FileService::getFileUrl($avatar);
}
private static function ensureShareInvite(int $userId, string $weekStart): string
{
$existing = Db::name('tcm_game_share_invite')
->where('week_start', $weekStart)
->where('user_id', $userId)
->find();
if ($existing) {
return (string) $existing['invite_code'];
}
for ($attempt = 0; $attempt < 5; $attempt++) {
$code = strtoupper(bin2hex(random_bytes(6)));
$now = time();
// 同一用户并发打开榜单时,以 week_start + user_id 唯一键汇合;
// 极小概率随机码撞车时,查询不到本人的记录就继续生成新码。
Db::name('tcm_game_share_invite')->duplicate([
'update_time',
])->insert([
'invite_code' => $code,
'user_id' => $userId,
'week_start' => $weekStart,
'open_count' => 0,
'create_time' => $now,
'update_time' => $now,
]);
$invite = Db::name('tcm_game_share_invite')
->where('week_start', $weekStart)
->where('user_id', $userId)
->find();
if ($invite) {
return (string) $invite['invite_code'];
}
}
throw new \RuntimeException('分享码生成失败');
}
private static function weekStart(?int $timestamp = null): string
{
$timestamp = $timestamp ?: time();
$day = (int) date('N', $timestamp);
return date('Y-m-d', strtotime('-' . ($day - 1) . ' days', $timestamp));
}
private static function logException(string $action, \Throwable $e): void
{
Log::error(sprintf(
'tcm endless game %s failed: %s at %s:%d',
$action,
$e->getMessage(),
$e->getFile(),
$e->getLine()
));
}
}
+323
View File
@@ -0,0 +1,323 @@
<?php
namespace app\api\logic\tcm;
/**
* 霍大夫升糖指数(GI)知识库
*/
class GiKnowledge
{
public const LEVEL_LOW = 'low';
public const LEVEL_MEDIUM = 'medium';
public const LEVEL_HIGH = 'high';
/** @var array<string, array<string, list<string>>> */
private static array $foods = [
self::LEVEL_LOW => [
'五谷类' => ['全蛋面', '荞麦面', '粉丝', '黑米', '黑米粥', '通心粉', '藕粉'],
'蔬菜类' => ['魔芋', '粟米', '大白菜', '黄瓜', '芹菜', '茄子', '青椒', '海带', '金针菇', '香菇', '菠菜', '番茄', '豆芽', '芦笋', '花椰菜', '洋葱', '生菜'],
'豆类' => ['黄豆', '眉豆', '鸡心豆', '豆腐', '豆角', '绿豆', '扁豆', '四季豆'],
'水果类' => ['苹果', '水梨', '橙子', '桃', '提子', '沙田柚', '雪梨', '车厘子', '柚子', '草莓', '樱桃', '金桔', '葡萄'],
'奶类' => ['牛奶', '低脂奶', '脱脂奶', '驼奶粉', '驼奶', '低脂乳酪', '红茶', '优格', '无糖豆浆'],
],
self::LEVEL_MEDIUM => [
'主食类' => ['红米饭', '糙米饭', '西米', '乌冬面', '面包', '麦片', '番薯', '芋头'],
'蔬菜类' => ['薯片', '番茄', '莲藕', '牛蒡'],
'肉类' => ['鱼肉', '鸡肉', '鸭肉', '猪肉', '羊肉', '牛肉', '虾子', '蟹'],
'水果类' => ['木瓜', '提子干', '菠萝', '香蕉', '芒果', '哈密瓜', '奇异果', '柳丁'],
'其他' => ['蔗糖', '蜂蜜', '红酒', '啤酒', '可乐', '咖啡'],
],
self::LEVEL_HIGH => [
'主食类' => ['白饭', '馒头', '油条', '糯米饭', '白面包', '燕麦片', '拉面', '炒饭', '爆米花'],
'肉类加工品' => ['贡丸', '肥肠', '蛋饺'],
'蔬菜类' => ['薯蓉', '南瓜', '焗薯'],
'水果类' => ['西瓜', '荔枝', '龙眼', '凤梨', '枣'],
'其他' => ['葡萄糖', '砂糖', '麦芽糖', '汽水', '柳橙汁', '蜂蜜'],
],
];
/** @var list<array{breakfast:string,drinks:string,lunch:string,dinner:string,tips:string}> */
private static array $mealTemplates = [
[
'breakfast' => '驼奶粉(温水冲服)、玉米碴子粥、煮鸡蛋、拌黄瓜',
'drinks' => '白天多喝温开水;早餐冲驼奶粉,别喝甜饮料、果汁。',
'lunch' => '清炖鲤鱼、豆腐炖白菜、清炒豆角、米饭小半碗',
'dinner' => '玉米面饼一个、瘦肉丝、凉拌茄子',
'tips' => '中午鱼豆肉吃足;早中晚淀粉别重复,一顿一种主食就够。',
],
[
'breakfast' => '驼奶粉(温水冲服)、小米粥、煮鸡蛋、小碟咸菜(少盐)',
'drinks' => '温开水为主;驼奶粉跟早餐一起吃,下午也记得喝水。',
'lunch' => '去皮炖鸡肉、芹菜炒豆干、木耳炒鸡蛋',
'dinner' => '蒸红薯(小半块)、清炒菠菜、豆腐汤',
'tips' => '午餐最讲究蛋白;晚上才吃薯,别跟中午再配大米饭。',
],
[
'breakfast' => '驼奶粉(温水冲服)、豆腐脑(少卤)、煮鸡蛋',
'drinks' => '早餐饮驼奶粉;白天喝白开水,别碰含糖饮料。',
'lunch' => '清炖鸡肉、炖芸豆、番茄炒蛋、贴饼子一个',
'dinner' => '挂面一小碗、清蒸小鱼、拌海带丝',
'tips' => '中午饼配肉豆,蛋白管够;面条放晚上,别三顿都是粥饭。',
],
[
'breakfast' => '驼奶粉(温水冲服)、高粱米粥、茶叶蛋、拌萝卜丝',
'drinks' => '温开水;早餐驼奶粉按说明冲,别加糖。',
'lunch' => '炖牛肉(瘦)、豆腐炒韭菜、清炒油菜、杂豆饭小半碗',
'dinner' => '蒸南瓜(小半碗)、鸡蛋羹、拍黄瓜',
'tips' => '中午肉蛋豆要多吃;南瓜算晚饭主食,别再加馒头稀饭。',
],
[
'breakfast' => '驼奶粉(温水冲服)、棒子面粥、水煮蛋、大拌菜(少油)',
'drinks' => '多喝温开水;驼奶粉放早餐,忌可乐汽水果汁。',
'lunch' => '清炖鲫鱼、番茄炒蛋、炖扁豆、糙米饭小半碗',
'dinner' => '玉米面饼一个、清炒豆芽、豆腐脑',
'tips' => '午饭鱼蛋豆齐上;玉米面放晚上,跟中午米饭分开。',
],
[
'breakfast' => '驼奶粉(温水冲服)、小米粥、煮鸡蛋、拌生菜',
'drinks' => '白天小口多次喝温水;早餐冲好驼奶粉再吃饭。',
'lunch' => '白切鸡(去皮)、炖豆腐、清炒豆角、二米饭小半碗',
'dinner' => '杂面馒头一个、瘦肉炒芹菜、凉拌黄瓜',
'tips' => '中午蛋白打主力;三顿别都喝粥吃面,一顿一种淀粉。',
],
];
public static function summaryText(): string
{
$path = root_path() . 'app/api/logic/tcm/data/gi_huo_summary.txt';
if (is_file($path)) {
$text = trim((string) file_get_contents($path));
if ($text !== '') {
return $text;
}
}
return '低 GI(≤55)优先;中 GI56-69)适量;高 GI(≥70)尽量避免。多选全谷物、蔬菜、豆类,少加工、少精制糖。';
}
/** 农村/口语别名 → 标准名(便于「能不能吃」匹配) */
private static array $aliases = [
'棒子面' => '荞麦面', '玉米碴' => '粟米', '地瓜' => '番薯', '红薯' => '番薯',
'洋芋' => '芋头', '土豆' => '芋头', '窝头' => '通心粉', '贴饼子' => '通心粉',
'二米饭' => '红米饭', '稀饭' => '白饭', '白稀饭' => '白饭', '糖糕' => '麦芽糖',
'驼奶' => '驼奶粉',
];
/**
* @return array{level:string,level_label:string,category:string,advice:string}|null
*/
public static function lookupFood(string $name): ?array
{
$name = trim($name);
if ($name === '') {
return null;
}
$canonical = self::$aliases[$name] ?? $name;
foreach ([self::LEVEL_LOW, self::LEVEL_MEDIUM, self::LEVEL_HIGH] as $level) {
foreach (self::$foods[$level] as $category => $items) {
foreach ($items as $item) {
if ($canonical === $item || $name === $item
|| mb_strpos($item, $canonical) !== false || mb_strpos($canonical, $item) !== false
|| mb_strpos($item, $name) !== false || mb_strpos($name, $item) !== false) {
return [
'level' => $level,
'level_label' => self::levelLabel($level),
'category' => $category,
'food' => $item,
'advice' => self::adviceForLevel($level, $name),
];
}
}
}
}
return null;
}
/** 供 AI 参考:老农民家常、集市易得食材示例 */
public static function ruralMealHints(): string
{
return implode("\n", [
'【早餐】须安排驼奶粉温水冲服(低 GI 奶类,稳血糖),可与粥、蛋、菜同餐。',
'【喝的】单独说明:温开水为主;早餐驼奶粉;严禁含糖饮料、果汁、酒。',
'【午餐】蛋白质要最高:至少 2 样高蛋白(鱼/鸡鸭/瘦肉/蛋/豆腐/豆干),肉蛋豆是午饭主角。',
'【淀粉不重复】粥/饭/面/饼/窝头/红薯/土豆/玉米/南瓜等算淀粉;早中晚各最多 1 种,且三顿不能同一种、不要顿顿大主食。',
'推荐蛋白:鸡蛋、豆腐、豆干、自家鸡鸭蛋、瘦肉、鲫鱼鲤鱼;',
'推荐蔬菜:白菜、萝卜、黄瓜、豆角、茄子、菠菜、芹菜;',
'淀粉示例(全天选 3 种不同的):玉米碴粥、二米饭小半碗、贴饼子、杂面窝头、挂面小碗、蒸红薯;',
'少吃:白馒头、油条、粘豆包、糯米饭、西瓜、含糖饮料、糕点。',
'说话要土话、短句,像村里大夫叮嘱。',
]);
}
public static function levelLabel(string $level): string
{
return match ($level) {
self::LEVEL_LOW => '低升糖',
self::LEVEL_MEDIUM => '中升糖',
default => '高升糖',
};
}
public static function adviceForLevel(string $level, string $food): string
{
return match ($level) {
self::LEVEL_LOW => "{$food}」升糖慢,老农民家常能吃,当菜当饭都行,有助于稳血糖。",
self::LEVEL_MEDIUM => "{$food}」升糖中等,可以吃但要少搁点,别当主食猛吃,配着蔬菜鸡蛋更好。",
default => "{$food}」升糖快,血糖高时尽量别吃或少吃,尤其别空腹猛吃。",
};
}
/**
* @param int|null $templateIndex 指定模板下标(换一换时轮换)
* @return array{breakfast:string,lunch:string,dinner:string,tips:string,avoid:list<string>,source:string}
*/
public static function fallbackDailyMeals(int $diagnosisId, ?int $templateIndex = null): array
{
$templates = self::$mealTemplates;
$count = count($templates);
if ($templateIndex !== null) {
$idx = (($templateIndex % $count) + $count) % $count;
} else {
$idx = abs(crc32(date('Y-m-d') . ':' . $diagnosisId)) % $count;
}
$meal = $templates[$idx];
$plan = [
'breakfast' => $meal['breakfast'],
'drinks' => $meal['drinks'] ?? '白天多喝温开水;早餐冲驼奶粉,别喝甜饮。',
'lunch' => $meal['lunch'],
'dinner' => $meal['dinner'],
'tips' => $meal['tips'],
'avoid' => ['白面馒头', '油条', '粘豆包', '西瓜', '含糖饮料', '稀饭配糖'],
'source' => 'rule',
];
$checked = DietMealValidator::validateAndNormalize($plan);
$out = $checked['plan'];
$out['source'] = 'rule';
$out['rules_summary'] = DietMealValidator::metaSummary($checked['meta']);
return $out;
}
/**
* 根据血糖统计给出「运动降糖」建议(规则化,按控制好坏调整强度)
*
* @param array<string,mixed> $stats7 近7天统计
* @param array<string,mixed> $stats30 近30天统计
* @return array{level:string,level_label:string,headline:string,items:list<string>,intensity:string,note:string}
*/
public static function exercisePlan(array $stats7 = [], array $stats30 = []): array
{
// 优先用记录更全的口径判断;都没记录则用近7天
$primary = ((int) ($stats30['record_days'] ?? 0) > 0) ? $stats30 : $stats7;
$recordDays = (int) ($primary['record_days'] ?? 0);
$compliance = (int) ($primary['compliance'] ?? 0);
$highDays = (int) ($primary['high_days'] ?? 0);
if ($recordDays <= 0) {
$level = 'unknown';
} elseif ($compliance < 50 || $highDays * 2 >= $recordDays) {
$level = 'high'; // 偏高多、达标率低 = 控制不佳
} elseif ($compliance < 80) {
$level = 'medium';
} else {
$level = 'good';
}
$note = '餐后 1 小时内开始动,别空腹剧烈运动;身上带几块糖,头晕、心慌、出虚汗就马上停下歇着。';
switch ($level) {
case 'high':
return [
'level' => 'high',
'level_label' => '血糖偏高 · 多动',
'headline' => '近期血糖偏高,三顿饭后都动一动,最能帮着把糖降下来。',
'items' => [
'早饭后快走 15 分钟,走到微微出汗',
'午饭后快走或原地踏步 20–30 分钟,降餐后血糖最管用',
'晚饭后慢走 30 分钟,吃完别马上坐下、躺下',
],
'intensity' => '中等强度 · 每天累计约 60 分钟',
'note' => $note,
];
case 'medium':
return [
'level' => 'medium',
'level_label' => '基本平稳 · 再稳稳',
'headline' => '血糖大体平稳,坚持餐后活动,把它稳住。',
'items' => [
'三餐后各散步 20 分钟,午饭后可以走快些',
'每天加一段八段锦或太极拳,10–15 分钟',
'能走楼梯少坐电梯,多干点家务、地里活',
],
'intensity' => '中低强度 · 每天累计 4050 分钟',
'note' => $note,
];
case 'good':
return [
'level' => 'good',
'level_label' => '控制不错 · 保持',
'headline' => '血糖控制得不错,保持规律活动就行。',
'items' => [
'餐后散步 1520 分钟,雷打不动',
'每天一段八段锦、太极或柔和拉伸',
'天好多到院里、地里走动,别久坐',
],
'intensity' => '中低强度 · 每天累计 3040 分钟',
'note' => $note,
];
default:
return [
'level' => 'unknown',
'level_label' => '先记血糖 · 再调运动',
'headline' => '血糖记录还少,先按基础来:饭后多走动。',
'items' => [
'三餐后都散步 1520 分钟',
'每天一段八段锦或太极拳',
'少久坐,坐 1 小时就起来活动几分钟',
],
'intensity' => '中低强度 · 每天累计约 30 分钟',
'note' => $note,
];
}
}
/**
* @return array{food:string,level:string,level_label:string,advice:string,source:string}
*/
public static function fallbackAsk(string $question): array
{
$food = self::extractFoodName($question);
$hit = self::lookupFood($food);
if ($hit) {
return [
'food' => $hit['food'],
'level' => $hit['level'],
'level_label' => $hit['level_label'],
'advice' => $hit['advice'],
'source' => 'rule',
];
}
return [
'food' => $food,
'level' => '',
'level_label' => '未知',
'advice' => '库里没查到「' . $food . '」。一般多吃小米玉米、白菜豆角豆腐鸡蛋,少吃白馒头油条甜口;拿不准问村医。',
'source' => 'rule',
];
}
public static function extractFoodName(string $question): string
{
$q = trim($question);
$q = preg_replace('/^(能不能吃|可以吃|能吃|可不可以吃|请问|我想问)/u', '', $q) ?? $q;
$q = preg_replace('/(吗|呢||\?)+$/u', '', $q) ?? $q;
$q = trim($q);
return $q !== '' ? $q : $question;
}
}
@@ -0,0 +1,7 @@
食物升糖指数(GI)知识摘要(霍大夫),面向农村老人日常吃饭:
- 低 GI(≤55):小米、玉米碴、杂面、大部分蔬菜、豆腐、鸡蛋、苹果/梨/柚子等,有助于稳血糖。
- 中 GI(56-69):二米饭、红薯、土豆、香蕉等,可以吃但要少、别当顿顿主食。
- 高 GI(≥70):白馒头、白稀饭、油条、粘豆包、糯米饭、西瓜、含糖饮料、糕点,尽量别碰。
- 午餐蛋白质要最高:鱼、鸡鸭、瘦肉、蛋、豆腐至少两样,午饭是全天蛋白主力。
- 淀粉不重复:粥/饭/面/饼/薯/玉米/南瓜等,早中晚各最多一种,三顿不要同一种、别顿顿大主食。
- 吃饭窍门:先吃菜和蛋白,再动主食,每餐七分饱。