文件
huaqiapp/server/application/common/service/CycleService.php
linda 5ea1b461f3 feat: 花期 V1.0 纵向切片(暖色调设计系统 + 周期/情绪/会员全链路)
前端(uni-app · Vue3)
- 设计系统:uni.scss 品牌令牌(花红 #E8604C / 蜜橙 #F5A65B / 暖米白 #FFF9F5),
  App.vue 全局原子类(卡片/按钮/胶囊/单元格/空态/进度)
- 页面:登录、首页(聚合)、周期(花瓣日历+当日记录+预测+概览)、情绪(记录+趋势+日记+疗愈)、
  我的(资料/会员/隐私/提醒)、健康报告、会员套餐、内容详情
- 组件:hq-tabbar(自定义底栏)、bloom-calendar(阶段日历)
- 基础层:utils/{config,request,store,api,date}.js(统一 token、401 处理、接口集中定义)

后端(FastAdmin / ThinkPHP 5.0)
- 新增 api 控制器:Home / Cycle / Mood / Content / Member / Setting,User 增补 detail、updateprofile
- 新增服务层:CycleService(四阶段计算、预测、月历、汇总)、MemberService(权益判定)
- 新增表:fa_cycle / fa_cycle_log / fa_symptom_tag / fa_mood_log / fa_content /
  fa_content_category / fa_member_plan / fa_member_order / fa_user_setting
- 初始化数据:20 个症状标签、28 条内容(心语/科普/知识/食谱/运动/睡眠/痛经/冥想)、3 档会员

验证(全部通过)
- 接口全链路 48 项断言(登录→周期→首页→情绪→内容→会员→设置→资料)
- 前后端契约静态校验 24 个接口 0 偏差
- Vue SFC 编译 11/11、SCSS 编译 10/10
- 验证脚本见 scripts/verify/,报告见 docs/04-前端设计系统与联调验证.md
2026-11-05 22:54:02 +08:00

329 行
12 KiB
PHP

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

<?php
namespace app\common\service;
use think\Db;
/**
* 周期计算服务
*
* 统一为「周期管理 / 情绪疗愈 / 健康建议 / 首页聚合」提供四阶段计算与预测能力,
* 避免各控制器重复实现。所有日期均为 Y-m-d 字符串。
*/
class CycleService
{
const PHASE_MENSTRUAL = 'menstrual';
const PHASE_FOLLICULAR = 'follicular';
const PHASE_OVULATION = 'ovulation';
const PHASE_LUTEAL = 'luteal';
public static $phaseText = [
'menstrual' => '经期',
'follicular' => '卵泡期',
'ovulation' => '排卵期',
'luteal' => '黄体期',
];
/** 各阶段的品牌色(与前端设计令牌保持一致) */
public static $phaseColor = [
'menstrual' => '#E8604C',
'follicular' => '#F5A65B',
'ovulation' => '#F0796A',
'luteal' => '#C79A7B',
];
/**
* 取用户周期列表(按开始日倒序)
*/
public static function cycles($userId, $limit = 12)
{
return Db::name('cycle')
->where('user_id', $userId)
->whereNull('deletetime')
->order('start_date', 'desc')
->limit($limit)
->select();
}
/**
* 周期参数(周期长度 / 经期长度),支持用户自定义后取历史均值
*/
public static function params($userId)
{
$cycles = self::cycles($userId, 6);
$cycleLength = 28;
$periodLength = 5;
if ($cycles) {
// 用最近 6 个周期的平均长度
$lengths = [];
foreach ($cycles as $c) {
if ($c['cycle_length'] > 0) {
$lengths[] = (int)$c['cycle_length'];
}
}
$diff = [];
for ($i = 0; $i < count($cycles) - 1; $i++) {
$days = (strtotime($cycles[$i]['start_date']) - strtotime($cycles[$i + 1]['start_date'])) / 86400;
if ($days >= 18 && $days <= 60) {
$diff[] = (int)$days;
}
}
if ($diff) {
$cycleLength = (int)round(array_sum($diff) / count($diff));
} elseif ($lengths) {
$cycleLength = (int)round(array_sum($lengths) / count($lengths));
}
$periodLength = (int)$cycles[0]['period_length'] ?: 5;
}
return ['cycle_length' => $cycleLength, 'period_length' => $periodLength];
}
/**
* 当前周期状态(首页 / 记录页核心数据)
*/
public static function current($userId, $today = null)
{
$today = $today ?: date('Y-m-d');
$now = strtotime($today);
$cycles = self::cycles($userId);
$params = self::params($userId);
$base = [
'has_data' => false,
'today' => $today,
'phase' => null,
'phase_text' => '',
'phase_color' => '',
'day' => 0,
'cycle_length' => $params['cycle_length'],
'period_length' => $params['period_length'],
'start_date' => null,
'next_start' => null,
'days_to_next' => null,
'ovulation' => null,
'fertile_start' => null,
'fertile_end' => null,
'is_fertile' => false,
'is_period' => false,
'progress' => 0,
];
if (!$cycles) {
return $base;
}
// 找到覆盖今天的周期(start <= today 且 today < start + cycleLength)
$active = null;
foreach ($cycles as $c) {
$start = strtotime($c['start_date']);
if ($start <= $now && $now < $start + $params['cycle_length'] * 86400) {
$active = $c;
break;
}
}
// 今天早于最新周期开始日(补录历史)时,退化使用最新周期推算
if (!$active) {
$active = $cycles[0];
}
$start = strtotime($active['start_date']);
$day = (int)floor(($now - $start) / 86400) + 1;
$phase = self::phaseByDay($day, $params['cycle_length'], $params['period_length']);
$ovulationTs = $start + ($params['cycle_length'] - 14) * 86400;
$nextStartTs = $start + $params['cycle_length'] * 86400;
$daysToNext = (int)ceil(($nextStartTs - $now) / 86400);
$result = array_merge($base, [
'has_data' => true,
'phase' => $phase,
'phase_text' => self::$phaseText[$phase],
'phase_color' => self::$phaseColor[$phase],
'day' => max($day, 1),
'start_date' => $active['start_date'],
'next_start' => date('Y-m-d', $nextStartTs),
'days_to_next' => $daysToNext,
'ovulation' => date('Y-m-d', $ovulationTs),
'fertile_start' => date('Y-m-d', $ovulationTs - 5 * 86400),
'fertile_end' => date('Y-m-d', $ovulationTs + 1 * 86400),
'is_period' => $phase === self::PHASE_MENSTRUAL,
'is_fertile' => $now >= $ovulationTs - 5 * 86400 && $now <= $ovulationTs + 1 * 86400,
'progress' => min(100, (int)round(max($day, 1) / $params['cycle_length'] * 100)),
]);
return $result;
}
/**
* 根据周期内第几天计算阶段
*/
public static function phaseByDay($day, $cycleLength = 28, $periodLength = 5)
{
$ovulationDay = max(1, $cycleLength - 14);
if ($day <= $periodLength) {
return self::PHASE_MENSTRUAL;
}
if ($day < $ovulationDay - 1) {
return self::PHASE_FOLLICULAR;
}
if ($day <= $ovulationDay + 1) {
return self::PHASE_OVULATION;
}
return self::PHASE_LUTEAL;
}
/**
* 未来 N 个月的经期/排卵预测
*/
public static function predict($userId, $months = 3)
{
$cycles = self::cycles($userId, 1);
$params = self::params($userId);
$list = [];
if (!$cycles) {
return ['list' => $list, 'cycle_length' => $params['cycle_length'], 'need_record' => true];
}
$start = strtotime($cycles[0]['start_date']);
$today = strtotime(date('Y-m-d'));
$limit = strtotime('+' . $months . ' month');
$i = 1;
while (true) {
$nextStart = $start + $i * $params['cycle_length'] * 86400;
if ($nextStart > $limit) {
break;
}
$ovulation = $nextStart + ($params['cycle_length'] - 14) * 86400;
$list[] = [
'start' => date('Y-m-d', $nextStart),
'end' => date('Y-m-d', $nextStart + ($params['period_length'] - 1) * 86400),
'ovulation' => date('Y-m-d', $ovulation),
'fertile_start' => date('Y-m-d', $ovulation - 5 * 86400),
'fertile_end' => date('Y-m-d', $ovulation + 86400),
'days_from_now' => (int)ceil(($nextStart - $today) / 86400),
];
$i++;
}
return ['list' => $list, 'cycle_length' => $params['cycle_length'], 'need_record' => false];
}
/**
* 月历:某月每一天的阶段信息
*/
public static function calendar($userId, $month)
{
$first = strtotime($month . '-01');
$daysInMonth = (int)date('t', $first);
$today = date('Y-m-d');
$cycles = self::cycles($userId, 24);
$params = self::params($userId);
$predict = self::predict($userId, 4);
$logs = Db::name('cycle_log')
->where('user_id', $userId)
->whereNull('deletetime')
->whereBetween('log_date', [$month . '-01', $month . '-' . $daysInMonth])
->column('log_date');
$list = [];
for ($d = 1; $d <= $daysInMonth; $d++) {
$date = date('Y-m-d', $first + ($d - 1) * 86400);
$ts = strtotime($date);
$phase = null;
$inPeriod = false;
$isPredicted = false;
// 1) 真实周期覆盖
foreach ($cycles as $c) {
$cStart = strtotime($c['start_date']);
if ($ts >= $cStart && $ts < $cStart + $params['cycle_length'] * 86400) {
$day = (int)floor(($ts - $cStart) / 86400) + 1;
$phase = self::phaseByDay($day, $params['cycle_length'], $params['period_length']);
$inPeriod = $day <= $params['period_length'];
break;
}
}
// 2) 预测经期
if (!$phase) {
foreach ($predict['list'] as $p) {
if ($date >= $p['start'] && $date <= $p['end']) {
$phase = self::PHASE_MENSTRUAL;
$inPeriod = true;
$isPredicted = true;
break;
}
if ($date >= $p['fertile_start'] && $date <= $p['fertile_end']) {
$phase = self::PHASE_OVULATION;
$isPredicted = true;
break;
}
}
}
$list[] = [
'date' => $date,
'day' => $d,
'week' => (int)date('w', $ts),
'phase' => $phase ?: 'unknown',
'phase_text' => $phase ? self::$phaseText[$phase] : '',
'color' => $phase ? self::$phaseColor[$phase] : '',
'in_period' => $inPeriod,
'is_predicted' => $isPredicted,
'has_log' => in_array($date, $logs),
'is_today' => $date === $today,
];
}
return [
'month' => $month,
'list' => $list,
'today' => $today,
'cycle' => self::current($userId),
];
}
/**
* 周期汇总(平均长度、规律性评分、记录量)
*/
public static function summary($userId)
{
$cycles = self::cycles($userId, 12);
$params = self::params($userId);
$diffs = [];
for ($i = 0; $i < count($cycles) - 1; $i++) {
$days = (int)((strtotime($cycles[$i]['start_date']) - strtotime($cycles[$i + 1]['start_date'])) / 86400);
if ($days >= 18 && $days <= 60) {
$diffs[] = $days;
}
}
$variance = 0;
if ($diffs) {
$avg = array_sum($diffs) / count($diffs);
foreach ($diffs as $d) {
$variance += pow($d - $avg, 2);
}
$variance = sqrt($variance / count($diffs));
}
// 规律性:标准差越小分越高(0 天 → 100 分,≥5 天 → 60 分以下)
$regularity = $diffs ? max(50, (int)round(100 - $variance * 8)) : 0;
$regularityText = $regularity >= 85 ? '非常规律' : ($regularity >= 70 ? '较为规律' : ($regularity > 0 ? '略有波动' : '数据不足'));
return [
'cycle_length' => $params['cycle_length'],
'period_length' => $params['period_length'],
'regularity' => $regularity,
'regularity_text' => $regularityText,
'cycle_count' => count($cycles),
'log_count' => Db::name('cycle_log')->where('user_id', $userId)->whereNull('deletetime')->count(),
'mood_count' => Db::name('mood_log')->where('user_id', $userId)->whereNull('deletetime')->count(),
'last_start' => $cycles ? $cycles[0]['start_date'] : null,
];
}
}