feat(consult): 咨询改为在线预约表单 + 新增 SDS/SAS/16PF 付费心理测评

一、心理咨询(M9)
- 前端不再选咨询师时段,改为「分类 + 表单」:11 类(婚恋/青少年/职场人际/情绪疏导/
  人生卡点/成长迷茫/脱单指导/分手挽回/社恐咨询/抑郁焦虑/情绪压力)
- 表单字段:称呼、手机号(11 位校验)、方便联系时间、困扰描述(≥5 字),提交后由咨询助理联系
- 支持查看/取消我的预约;同一用户 10 分钟内防重复提交
- 新增表 fa_consult_booking(含跟进状态与备注),后台可跟进

二、心理测评(付费)
- 新增三个付费量表:抑郁自评 SDS(20 题,1-4 级 + 10 道反向题,标准分=粗分×1.25 取整)、
  焦虑自评 SAS(20 题,5 道反向题)、卡特尔 16PF 简版(48 题 / 16 维度,三选项)
- 华东:测评需付费,未付费拦截并返回 need_pay;新增 fa_assessment_order 订单表与下单接口
- 计分:标准分分级(正常/轻度/中度/重度)+ 16PF 维度剖面(1-10 分、高/中/低解读)
- 风险识别:SDS 自伤条目高分或重度 → risk_flag + 危机热线
- 结果页新增 16PF 16 维条形剖面与「预约咨询师解读」入口

三、管理端
- 新增后台模块:心理预约(分类/状态/备注跟进)、测评订单(支付状态可改)
- ManageConfig 增加对应字段配置;菜单脚本 db/06_consult_assessment.sql(可重复执行)
- fa_assessment 增加 price 字段;测评列表/详情接口返回价格与购买状态

四、验证(全绿)
- 咨询+测评专项:54 项断言(分类、表单校验、防重复、脱敏、取消、题库、付费拦截、
  下单、付费后 SDS=62/轻度、SAS=56/轻度、16PF 16 维满分、危机干预)
- 前台接口 78 项、后台自检 33 项(28 模块)、契约 0 偏差、Vue 20/20、SCSS 19/19、无 emoji
这个提交包含在:
linda
2026-11-06 16:00:52 +08:00
父节点 56f5f60aa5
当前提交 3baa52e95a
共有 15 个文件被更改,包括 1623 次插入 和 644 次删除

查看文件

@@ -112,9 +112,9 @@
| 功能点 | 实现 | 接口 | 前端 |
|---|---|---|---|
| 一对一咨询 | 咨询师选择(文字/语音/视频)+ 时段 + 下单/取消/订单列表 | `GET /api/consult/counselors`、`POST /api/consult/orderCreate`、`orders`、`cancel` | 咨询页 |
| 心理测评 | 4 个量表(PMS/备孕焦虑/亲密关系/产后筛查),0-4 五级计分 + 分级解读 | `GET /api/consult/assessments`、`assessmentDetail`、`POST assessmentSubmit` | 测评页 |
| 咨询师入驻与排班 | 资质校验(cert_verify)+ 三档定价 + 分成比例 + 可预约时段 | `GET /api/consult/counselors` | 咨询页 |
| 在线预约(表单) | **分类选择(11 类)+ 称呼/手机号/方便时间/困扰描述**,提交后由咨询助理联系;可查看与取消预约 | `GET /api/consult/categories`、`POST /api/consult/booking`、`bookings`、`bookingCancel` | 咨询页 |
| 心理测评(付费) | **抑郁自评 SDS(20 题)/ 焦虑自评 SAS(20 题)/ 卡特尔 16PF 简版(48 题)**,标准分与 16 维剖面解读;未付费拦截,下单后解锁 | `GET /api/consult/assessments`、`assessmentDetail`、`POST assessmentOrder`、`assessmentSubmit` | 咨询页 + 测评页 |
| 咨询师团队 | 后台维护资质(cert_verify)、三档定价、分成比例,供运营派单与展示 | 后台「咨询师」模块 | 运营后台 |
| 危机干预转介 | 产后筛查自伤题 ≥2 分或满分 → `risk_flag=1` + 热线(12356/010-82951332)+ 就医提示 | `GET /api/consult/crisis`、测评返回 `crisis` | 测评页红框提示 + 咨询页热线 |
---

查看文件

@@ -1,6 +1,7 @@
# 花期 APP · 运营后台(与前端模块对齐)与数据同步
> 本轮内容:**运营后台登录页品牌化重构** + **后台 26 个业务模块与前端 M1–M9 对齐** + **前后端数据同步全链路验证**。
> 本轮内容:**运营后台登录页品牌化重构** + **后台 28 个业务模块与前端 M1–M9 对齐** + **前后端数据同步全链路验证**。
> 后续增补:心理咨询改为**在线预约表单(11 类)**,心理测评新增 **SDS / SAS / 16PF** 三个付费量表。
> 关联:[02-开发文档](./02-开发文档.md)、[05-功能覆盖度与实现说明](./05-功能覆盖度与实现说明.md)
---
@@ -21,7 +22,7 @@
---
## 2. 后台业务模块矩阵(26 个,与前端一一对应)
## 2. 后台业务模块矩阵(28 个,与前端一一对应)
| 前端模块 | 后台菜单 | 数据表 | 权限节点 |
|---|---|---|---|
@@ -32,11 +33,11 @@
| M4 家人共护 | 家人绑定 / 沟通留言 / 爱心积分 | `fa_family_bind`、`fa_care_message`、`fa_point_log` | `familybind/index`、`caremessage/index`、`pointlog/index` |
| M7 两性关系 | 纪念日 / 课程订单 | `fa_memory`、`fa_course_order` | `memory/index`、`courseorder/index` |
| M8 亲子教育 | 宝宝档案 / 成长记录 / 疫苗与儿保 | `fa_baby`、`fa_growth_record`、`fa_vaccine` | `baby/index`、`growthrecord/index`、`vaccine/index` |
| M9 心理服务 | 咨询师 / 咨询订单 / 量表管理 / 测评记录 | `fa_counselor`、`fa_consult_order`、`fa_assessment`、`fa_assessment_record` | `counselor/index`、`consultorder/index`、`assessment/index`、`assessmentrecord/index` |
| M9 心理服务 | **心理预约** / **测评订单** / 咨询师 / 咨询订单 / 量表管理 / 测评记录 | `fa_consult_booking`、`fa_assessment_order`、`fa_counselor`、`fa_consult_order`、`fa_assessment`、`fa_assessment_record` | `consultbooking/index`、`assessmentorder/index`、`counselor/index`、`consultorder/index`、`assessment/index`、`assessmentrecord/index` |
| M6 会员中心 | 会员套餐 / 会员订单 / 隐私与提醒 / 数据备份 | `fa_member_plan`、`fa_member_order`、`fa_user_setting`、`fa_user_backup` | `memberplan/index`、`memberorder/index`、`usersetting/index`、`userbackup/index` |
| 用户(FastAdmin 原生) | 会员管理 | `fa_user` | `user/user` |
菜单脚本:`server/db/05_admin_menu.sql`(可重复执行),父菜单「花期运营」+ 26 个业务菜单 + 6 个通用操作权限(`manage/index|add|edit|del|multi|columns`)。
菜单脚本:`server/db/05_admin_menu.sql` + `server/db/06_consult_assessment.sql`(均可重复执行),父菜单「花期运营」+ 28 个业务菜单 + 6 个通用操作权限(`manage/index|add|edit|del|multi|columns`)。
---
@@ -79,7 +80,7 @@ public/assets/js/backend/manage.js # 通用列表脚本:按后端列元数据
---
## 5. 前后端数据同步验证(31 项,全部通过)
## 5. 前后端数据同步验证(33 项,全部通过)
脚本:`scripts/verify/admin_backend_check.php`(在服务器上执行)
@@ -90,7 +91,7 @@ php scripts/verify/admin_backend_check.php /www/wwwroot/huaqiapp.gzyakj.com.cn h
覆盖:
1. **登录页品牌**:HTTP 200 且包含「登录运营后台」「花期」
2. **后台框架 + 菜单**:HTTP 200 且包含「花期运营」「周期档案」
3. **26 个业务模块**:页面 200(含 `hq-admin` 标记)+ 列表接口返回 `total`(实测数据量:症状标签 20、内容 70、分类 17、任务 12、疫苗 17、测评记录 8…)
3. **28 个业务模块**:页面 200(含 `hq-admin` 标记)+ 列表接口返回 `total`(实测数据量:症状标签 20、内容 70、分类 17、任务 12、疫苗 17、测评记录 26、测评订单 3…)
4. **写入链路**:后台 AJAX 编辑 → 断言返回 `code=1` → 断言数据库字段已更新
5. **同步链路**:会员 token 调 `/api/content/detail` → 断言前台接口读到后台新标题
6. **还原**:改回原值并断言一致(不污染线上数据)
@@ -106,7 +107,7 @@ php scripts/verify/admin_backend_check.php /www/wwwroot/huaqiapp.gzyakj.com.cn h
✅ 后台改动 → 前台 API 同步(读取到:同步自检110816)
✅ 数据还原(经期温热暖身餐)
========================================
通过 31 项,失败 0 项
通过 33 项,失败 0 项
```
**其它回归**:前台接口 82 项断言全绿;前后端契约 84 接口 0 偏差;Vue 20/20、SCSS 19/19、无 emoji 校验通过。

查看文件

@@ -16,7 +16,8 @@
- **仓库**:前端在根目录,后端源码在 `server/`(与线上服务器同步)
- **上线节奏**:V1.0(P0,19 项)→ V1.1(P1,18 项)→ V2.0(P2,10 项)
- **当前进度**:M1–M9 共 **47 个功能点全部实现并联调通过**(详见 05 文档)
- **运营后台**:登录页品牌化 + 26 个业务模块(与前端模块一一对应)+ 通用 CRUD(详见 06 文档)
- **运营后台**:登录页品牌化 + 28 个业务模块(与前端模块一一对应)+ 通用 CRUD(详见 06 文档)
- **心理服务**:咨询改为在线预约表单(11 类);测评含 SDS / SAS / 16PF,付费后作答
- **变现**:会员订阅为主轴(月/年/终身),课程与咨询/测评为副,按次增值补充;坚持零广告
- **设计**:暖色调(花红 `#E8604C` + 蜜橙 `#F5A65B` + 暖米白 `#FFF9F5`),设计令牌见 `uni.scss`
- **图标**:全站 61 个内联 SVG 矢量图标(`utils/icons.js` + `<hq-icon>`),**禁止使用 emoji 图片**
@@ -30,6 +31,8 @@ node scripts/verify/vue_compile_check.mjs # Vue SFC 编译(需 @vue/compiler
node scripts/verify/scss_compile_check.mjs # SCSS 编译(需 sass)
python3 scripts/verify/no_emoji_check.py # 图标规范(禁止 emoji / 图标名与组件注册)
python3 scripts/verify/consult_assessment_test.py # 咨询预约 + 付费测评(54 项,需 HQ_TEST_*)
# 运营后台(在服务器执行)
php scripts/verify/admin_backend_check.php <站点目录> <站点域名> # 26 模块 + 数据同步 31 项
```

查看文件

@@ -1,45 +1,93 @@
<template>
<view class="hq-page">
<view class="head">
<text class="head-title">{{ detail.title || '测评' }}</text>
<text class="head-intro">{{ detail.intro }}</text>
<view class="progress-row">
<view class="hq-progress progress-track">
<view class="hq-progress-inner" :style="{ width: progress + '%' }"></view>
<!-- 付费墙 -->
<view class="paywall" v-if="detail.need_pay && !detail.paid">
<view class="paywall-card">
<hq-icon name="clipboard" :size="72" :stroke="1.6" color="#E8604C" style="margin-bottom: 18rpx" />
<text class="paywall-title">{{ detail.title }}</text>
<text class="paywall-desc">{{ detail.intro }}</text>
<view class="paywall-meta">
<view class="paywall-meta-item">
<text class="paywall-meta-value">{{ detail.questions }}</text>
<text class="paywall-meta-label">题目数</text>
</view>
<view class="paywall-meta-item">
<text class="paywall-meta-value">{{ detail.scale || '专业' }}</text>
<text class="paywall-meta-label">量表类型</text>
</view>
<view class="paywall-meta-item">
<text class="paywall-meta-value">¥{{ detail.price }}</text>
<text class="paywall-meta-label">测评费用</text>
</view>
</view>
<text class="progress-text">{{ answered }}/{{ total }}</text>
<view class="hq-btn paywall-btn" @tap="buy">
<text class="paywall-btn-text">{{ buying ? '创建订单中…' : '支付 ¥' + detail.price + ' 并开始' }}</text>
</view>
<text class="paywall-tip">支付通道接入中:下单后可联系客服完成支付,支付完成后返回即可作答</text>
</view>
</view>
<view class="hq-card q-card" v-for="(q, index) in detail.questions" :key="index">
<text class="q-title">{{ index + 1 }}. {{ q }}</text>
<view class="q-options">
<view
v-for="opt in detail.options"
:key="opt.value"
class="q-option"
:class="{ 'q-option-active': answers[index] === opt.value }"
@tap="choose(index, opt.value)"
>
<text class="q-option-text" :class="{ 'q-option-text-active': answers[index] === opt.value }">{{ opt.text }}</text>
<!-- 题目 -->
<view v-else>
<view class="head">
<text class="head-title">{{ detail.title || '测评' }}</text>
<text class="head-intro">{{ detail.intro }}</text>
<text class="head-note" v-if="detail.note">{{ detail.note }}</text>
<view class="progress-row">
<view class="hq-progress progress-track">
<view class="hq-progress-inner" :style="{ width: progress + '%' }"></view>
</view>
<text class="progress-text">{{ answered }}/{{ total }}</text>
</view>
</view>
<view class="hq-card q-card" v-for="(item, index) in detail.items || []" :key="index">
<text class="q-title">{{ index + 1 }}. {{ item.q }}</text>
<view class="q-options" :class="{ 'q-options-grid': (detail.options || []).length <= 3 }">
<view
v-for="(opt, oi) in detail.options || []"
:key="oi"
class="q-option"
:class="{ 'q-option-active': answers[index] === oi }"
@tap="choose(index, oi)"
>
<text class="q-option-text" :class="{ 'q-option-text-active': answers[index] === oi }">{{ opt.text }}</text>
</view>
</view>
</view>
<view class="hq-btn submit" @tap="submit">
<text class="submit-text">{{ submitting ? '计算中…' : '提交并查看结果' }}</text>
</view>
</view>
<view class="hq-btn submit" @tap="submit">
<text class="submit-text">{{ submitting ? '提交中…' : '查看结果' }}</text>
</view>
<!-- 结果 -->
<view class="hq-card result" v-if="result">
<view class="result-head">
<text class="result-score">{{ result.score }}</text>
<text class="result-max">/ {{ result.max }} 分</text>
<text class="result-max">/ {{ result.max }}{{ result.scale === '16PF' ? ' 分(最高维度)' : ' 分' }}</text>
</view>
<text class="result-text">{{ result.result_text }}</text>
<view class="advice" v-for="(a, i) in result.advice" :key="i">
<!-- 16PF 剖面 -->
<view class="dims" v-if="(result.dims || []).length">
<view class="dim" v-for="d in result.dims" :key="d.key">
<text class="dim-name">{{ d.name }}</text>
<view class="dim-bar-wrap">
<view class="dim-bar" :class="'dim-' + d.level" :style="{ width: d.score * 10 + '%' }"></view>
</view>
<text class="dim-score">{{ d.score }}</text>
</view>
<text class="dim-tip">分数越高代表该特质越突出;1-4 偏低、5-6 居中、7-10 偏高</text>
</view>
<view class="advice" v-for="(a, i) in result.advice || []" :key="i">
<view class="advice-dot"></view>
<text class="advice-text">{{ a }}</text>
</view>
<view class="crisis" v-if="result.risk_flag && result.crisis">
<text class="crisis-title">{{ result.crisis.title }}</text>
<text class="crisis-text">{{ result.crisis.text }}</text>
@@ -48,7 +96,14 @@
<text class="crisis-hotline-phone">{{ h.phone }}</text>
</view>
</view>
<text class="result-disclaimer">{{ result.disclaimer }}</text>
<view class="result-actions">
<view class="hq-btn-ghost result-btn" @tap="goConsult">
<text class="result-btn-text">预约咨询师解读</text>
</view>
</view>
</view>
<view class="footer">
@@ -60,20 +115,23 @@
<script>
import api from '@/utils/api.js'
import store from '@/utils/store.js'
import hqIcon from '@/components/hq-icon/hq-icon.vue'
export default {
components: { hqIcon },
data() {
return {
id: 0,
detail: { questions: [], options: [] },
detail: { items: [], options: [] },
answers: [],
submitting: false,
buying: false,
result: null
}
},
computed: {
total() {
return (this.detail.questions || []).length
return (this.detail.items || []).length
},
answered() {
return this.answers.filter((v) => v !== null && v !== undefined).length
@@ -95,12 +153,37 @@ export default {
try {
const data = await api.assessmentDetail(this.id)
this.detail = data
this.answers = new Array((data.questions || []).length).fill(null)
this.answers = new Array((data.items || []).length).fill(null)
uni.setNavigationBarTitle({ title: data.title || '测评' })
} catch (e) {}
},
choose(index, value) {
this.answers[index] = value
choose(index, optionIndex) {
this.answers[index] = optionIndex
},
async buy() {
if (this.buying) return
this.buying = true
try {
const order = await api.assessmentOrder(this.id)
if (order && order.paid) {
this.detail.paid = true
return
}
uni.showModal({
title: '订单已创建',
content:
'订单号:' + (order.order_no || '') +
'\n金额:¥' + (order.amount || this.detail.price) +
'\n\n' + (order.pay_hint || ''),
showCancel: false,
confirmColor: '#E8604C'
})
// 支付完成后回到本页会自动刷新
setTimeout(() => this.load(), 1200)
} catch (e) {
} finally {
this.buying = false
}
},
async submit() {
if (this.submitting) return
@@ -113,15 +196,102 @@ export default {
this.result = await api.assessmentSubmit(this.id, this.answers)
uni.pageScrollTo({ scrollTop: 99999, duration: 300 })
} catch (e) {
const data = (e && e.data) || {}
if (data && data.need_pay) {
this.detail.paid = false
this.detail.need_pay = true
uni.showToast({ title: '请先完成支付', icon: 'none' })
}
} finally {
this.submitting = false
}
},
goConsult() {
uni.navigateTo({ url: '/pages/consult/index' })
}
}
}
</script>
<style lang="scss" scoped>
/* ---------- 付费墙 ---------- */
.paywall {
padding: 40rpx 0;
}
.paywall-card {
background-color: #FFFFFF;
border-radius: 36rpx;
padding: 48rpx 36rpx 36rpx;
box-shadow: 0 20rpx 50rpx rgba(232, 96, 76, 0.12);
display: flex;
flex-direction: column;
align-items: center;
}
.paywall-title {
font-size: 36rpx;
font-weight: 600;
color: #3E2C27;
text-align: center;
}
.paywall-desc {
margin-top: 12rpx;
font-size: 24rpx;
color: #8C7367;
line-height: 1.7;
text-align: center;
}
.paywall-meta {
display: flex;
width: 100%;
margin: 32rpx 0 8rpx;
padding: 24rpx 0;
border-radius: 24rpx;
background-color: #FFF9F5;
}
.paywall-meta-item {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
}
.paywall-meta-value {
font-size: 32rpx;
font-weight: 600;
color: #E8604C;
}
.paywall-meta-label {
margin-top: 6rpx;
font-size: 20rpx;
color: #B9A79E;
}
.paywall-btn {
width: 100%;
margin-top: 24rpx;
}
.paywall-btn-text {
font-size: 30rpx;
color: #FFFFFF;
letter-spacing: 1rpx;
}
.paywall-tip {
margin-top: 18rpx;
font-size: 20rpx;
color: #B9A79E;
text-align: center;
line-height: 1.7;
}
/* ---------- 题目 ---------- */
.head {
padding: 28rpx 0 20rpx;
}
@@ -140,6 +310,14 @@ export default {
line-height: 1.7;
}
.head-note {
display: block;
margin-top: 8rpx;
font-size: 20rpx;
color: #B9A79E;
line-height: 1.6;
}
.progress-row {
display: flex;
align-items: center;
@@ -172,8 +350,15 @@ export default {
margin-top: 16rpx;
}
.q-options-grid .q-option {
flex: 1;
min-width: 30%;
display: flex;
justify-content: center;
}
.q-option {
padding: 12rpx 24rpx;
padding: 14rpx 24rpx;
border-radius: 999rpx;
background-color: #FFF4EE;
margin: 0 12rpx 12rpx 0;
@@ -203,6 +388,7 @@ export default {
letter-spacing: 2rpx;
}
/* ---------- 结果 ---------- */
.result {
margin-top: 24rpx;
}
@@ -221,7 +407,7 @@ export default {
.result-max {
margin-left: 8rpx;
font-size: 24rpx;
font-size: 22rpx;
color: #B9A79E;
}
@@ -233,6 +419,63 @@ export default {
line-height: 1.8;
}
.dims {
margin-top: 24rpx;
padding-top: 20rpx;
border-top: 2rpx solid #F5E7DF;
}
.dim {
display: flex;
align-items: center;
margin-bottom: 14rpx;
}
.dim-name {
width: 120rpx;
font-size: 22rpx;
color: #8C7367;
}
.dim-bar-wrap {
flex: 1;
height: 14rpx;
border-radius: 999rpx;
background-color: #FFF1E9;
overflow: hidden;
margin: 0 14rpx;
}
.dim-bar {
height: 100%;
border-radius: 999rpx;
background: linear-gradient(90deg, #F5A65B 0%, #E8604C 100%);
}
.dim-low {
background: linear-gradient(90deg, #C7D8E8 0%, #8FA6C4 100%);
}
.dim-mid {
background: linear-gradient(90deg, #F5D6A5 0%, #E9A23B 100%);
}
.dim-score {
width: 40rpx;
text-align: right;
font-size: 22rpx;
color: #3E2C27;
font-weight: 600;
}
.dim-tip {
display: block;
margin-top: 8rpx;
font-size: 18rpx;
color: #B9A79E;
line-height: 1.6;
}
.advice {
display: flex;
align-items: flex-start;
@@ -304,6 +547,19 @@ export default {
color: #B9A79E;
}
.result-actions {
margin-top: 24rpx;
}
.result-btn {
height: 80rpx;
}
.result-btn-text {
font-size: 26rpx;
color: #E8604C;
}
.footer {
padding: 24rpx 0;
text-align: center;

查看文件

@@ -2,10 +2,10 @@
<view class="hq-page">
<view class="head">
<text class="head-title">心理咨询</text>
<text class="head-sub">一对一在线咨询 · 咨询师资质已审核</text>
<text class="head-sub">一对一在线咨询 · 提交预约后由咨询助理联系</text>
</view>
<!-- 危机干预 -->
<!-- 热线 -->
<view class="crisis" @tap="callHotline">
<hq-icon name="phone" :size="42" :stroke="1.7" color="#C9482F" style="margin-right: 20rpx" />
<view class="crisis-body">
@@ -14,92 +14,118 @@
</view>
</view>
<!-- 咨询师 -->
<view class="hq-card counselor" v-for="item in counselors" :key="item.id">
<view class="counselor-head">
<view class="counselor-avatar">
<hq-icon :name="counselorIcon(item)" :size="50" :stroke="1.7" color="#C9482F" />
</view>
<view class="counselor-info">
<view class="counselor-name-row">
<text class="counselor-name">{{ item.name }}</text>
<text class="counselor-cert" v-if="item.cert_verify === 'passed'">已认证</text>
</view>
<text class="counselor-title">{{ item.title }}</text>
<view class="counselor-tags">
<text class="counselor-tag" v-for="t in item.tags" :key="t">{{ t }}</text>
</view>
</view>
<!-- 预约表单 -->
<view class="hq-card form-card">
<view class="hq-section-head">
<text class="hq-section-title">预约咨询</text>
<text class="hq-muted">1 个工作日内联系你</text>
</view>
<text class="counselor-intro">{{ item.intro }}</text>
<view class="modes">
<text class="field-label">咨询分类</text>
<view class="cat-grid">
<view
v-for="mode in modes"
:key="mode.key"
class="mode"
:class="{ 'mode-active': activeMode[item.id] === mode.key }"
@tap="setMode(item.id, mode.key)"
v-for="cat in categories"
:key="cat.key"
class="cat"
:class="{ 'cat-active': form.category === cat.key }"
@tap="form.category = cat.key"
>
<text class="mode-text" :class="{ 'mode-text-active': activeMode[item.id] === mode.key }">
{{ mode.label }} ¥{{ priceOf(item, mode.key) }}
</text>
<text class="cat-text" :class="{ 'cat-text-active': form.category === cat.key }">{{ cat.name }}</text>
</view>
</view>
<view class="slots">
<text
v-for="slot in item.slots"
:key="slot"
class="slot"
:class="{ 'slot-active': activeSlot[item.id] === slot }"
@tap="setSlot(item.id, slot)"
>{{ slot }}</text>
<view class="field">
<text class="field-label">你的称呼</text>
<input class="hq-input" v-model="form.name" placeholder="怎么称呼你?" placeholder-class="ph" maxlength="30" />
</view>
<view class="hq-btn book" @tap="book(item)">
<text class="book-text">{{ booking === item.id ? '提交中…' : '预约咨询' }}</text>
<view class="field">
<text class="field-label">联系电话</text>
<input class="hq-input" type="number" v-model="form.mobile" placeholder="11 位手机号,方便助理联系" placeholder-class="ph" maxlength="11" />
</view>
<view class="field">
<text class="field-label">方便联系的时间</text>
<input class="hq-input" v-model="form.prefer_time" placeholder="例如:工作日 19:00-21:00" placeholder-class="ph" maxlength="40" />
</view>
<view class="field">
<text class="field-label">想聊的困扰</text>
<textarea
class="hq-textarea"
v-model="form.description"
placeholder="简单描述一下最近的状态或困扰,助理会提前了解(至少 5 个字)"
placeholder-class="ph"
maxlength="500"
auto-height
/>
</view>
<view class="hq-btn submit-btn" @tap="submitBooking">
<text class="submit-text">{{ submitting ? '提交中…' : '提交预约' }}</text>
</view>
<text class="form-notice">{{ notice }}</text>
</view>
<!-- 我的预约 -->
<view class="hq-section-head">
<text class="hq-section-title">我的预约</text>
<text class="hq-section-more">{{ orders.length }} 条</text>
<text class="hq-section-more">{{ bookings.length }} 条</text>
</view>
<view class="hq-card" v-if="orders.length">
<view class="order" v-for="item in orders" :key="item.id">
<view class="order-body">
<text class="order-title">{{ item.counselor }} · {{ item.mode_text }}</text>
<text class="order-time">{{ item.start_time }}</text>
<text class="order-no">订单 {{ item.order_no }}</text>
</view>
<view class="order-right">
<text class="order-status">{{ item.status_text }}</text>
<text class="order-cancel" v-if="item.status !== 'finished' && item.status !== 'canceled'" @tap="cancel(item)">取消</text>
<view class="hq-card" v-if="bookings.length">
<view class="booking" v-for="item in bookings" :key="item.id">
<view class="booking-body">
<view class="booking-head">
<text class="booking-cat">{{ item.category_text }}</text>
<text class="booking-status" :class="'st-' + item.status">{{ item.status_text }}</text>
</view>
<text class="booking-desc">{{ item.description }}</text>
<text class="booking-meta">{{ item.create_time }} · {{ item.mobile }} · {{ item.prefer_time }}</text>
</view>
<text
class="booking-cancel"
v-if="item.status === 'pending' || item.status === 'contacted'"
@tap="cancelBooking(item)"
>取消</text>
</view>
</view>
<view class="hq-card" v-else>
<view class="hq-empty">
<hq-icon name="chat-heart" :size="96" :stroke="1.6" color="#E6D3C9" />
<text class="hq-empty-text">还没有咨询预约</text>
<hq-icon name="calendar" :size="96" :stroke="1.6" color="#E6D3C9" />
<text class="hq-empty-text">还没有提交过预约\n选好分类,写下困扰即可</text>
</view>
</view>
<!-- 量表测评 -->
<!-- 心理测评 -->
<view class="hq-section-head">
<text class="hq-section-title">心理测评</text>
<text class="hq-section-more">基础测评免费</text>
<text class="hq-section-more">付费后作答 · 专业量表</text>
</view>
<view class="hq-card test" v-for="item in assessments" :key="'a' + item.id" @tap="startTest(item)">
<view class="test-body">
<text class="test-title">{{ item.title }}</text>
<text class="test-sub">{{ item.intro }}</text>
<text class="test-meta" v-if="item.last_date">上次 {{ item.last_date }} · {{ item.last_score }} 分</text>
<view class="hq-card assess" v-for="item in assessments" :key="item.id">
<view class="assess-head">
<view class="assess-title-wrap">
<text class="assess-title">{{ item.title }}</text>
<text class="assess-sub">{{ item.intro }}</text>
</view>
<view class="assess-price" v-if="item.need_pay && !item.paid">
<text class="assess-price-text">¥{{ item.price }}</text>
</view>
<view class="assess-price assess-price-free" v-else-if="!item.need_pay">
<text class="assess-price-text assess-price-free-text">免费</text>
</view>
</view>
<view class="assess-meta">
<text class="assess-meta-item">{{ item.questions }} 题</text>
<text class="assess-meta-item" v-if="item.note">{{ item.note }}</text>
<text class="assess-meta-item" v-if="item.last_date">上次 {{ item.last_date }} · {{ item.last_score }} 分</text>
</view>
<view class="assess-actions">
<view class="assess-btn" :class="{ 'assess-btn-pay': item.need_pay && !item.paid }" @tap="startAssessment(item)">
<text class="assess-btn-text">{{ item.paid ? '开始测评' : '¥' + item.price + ' 购买并测评' }}</text>
</view>
</view>
<text class="test-action">开始 ›</text>
</view>
<view class="footer">
@@ -111,24 +137,24 @@
<script>
import api from '@/utils/api.js'
import store from '@/utils/store.js'
import { resolveIcon } from '@/utils/icons.js'
import hqIcon from '@/components/hq-icon/hq-icon.vue'
export default {
components: { hqIcon },
data() {
return {
counselors: [],
categories: [],
bookings: [],
assessments: [],
orders: [],
modes: [
{ key: 'text', label: '文字' },
{ key: 'voice', label: '语音' },
{ key: 'video', label: '视频' }
],
activeMode: {},
activeSlot: {},
booking: 0
notice: '提交后 1 个工作日内,咨询助理会通过电话或微信与你联系',
submitting: false,
form: {
category: '',
name: '',
mobile: '',
prefer_time: '',
description: ''
}
}
},
onShow() {
@@ -142,57 +168,51 @@ export default {
async load() {
try {
const data = await api.consultIndex()
this.counselors = (data && data.counselors) || []
this.categories = (data && data.categories) || []
this.bookings = (data && data.bookings) || []
this.assessments = (data && data.assessments) || []
this.orders = (data && data.orders) || []
this.counselors.forEach((c) => {
if (!this.activeMode[c.id]) this.activeMode[c.id] = 'text'
if (!this.activeSlot[c.id] && c.slots && c.slots.length) this.activeSlot[c.id] = c.slots[0]
})
if (data && data.notice) this.notice = data.notice
if (!this.form.category && this.categories.length) {
this.form.category = this.categories[0].key
}
if (store.user) {
this.form.name = this.form.name || store.user.nickname || ''
this.form.mobile = this.form.mobile || store.user.mobile || ''
}
} catch (e) {}
},
counselorIcon(item) {
return resolveIcon(item && (item.icon || item.emoji), 'flower')
},
priceOf(item, key) {
const price = (item.price && item.price[key]) || 0
return Math.round(price * (item.discount || 1))
},
setMode(id, key) {
this.activeMode[id] = key
},
setSlot(id, slot) {
this.activeSlot[id] = slot
},
async book(item) {
if (this.booking) return
const slot = this.activeSlot[item.id]
if (!slot) {
uni.showToast({ title: '请选择时间', icon: 'none' })
return
}
// slot 形如 "2026-11-08 10:00"
const startTime = slot
this.booking = item.id
async submitBooking() {
if (this.submitting) return
const f = this.form
if (!f.category) return uni.showToast({ title: '请选择咨询分类', icon: 'none' })
if (!f.name.trim()) return uni.showToast({ title: '请填写称呼', icon: 'none' })
if (!/^1\d{10}$/.test(f.mobile)) return uni.showToast({ title: '请填写正确的手机号', icon: 'none' })
if (!f.prefer_time.trim()) return uni.showToast({ title: '请填写方便联系的时间', icon: 'none' })
if (f.description.trim().length < 5) return uni.showToast({ title: '请简单描述你的困扰', icon: 'none' })
this.submitting = true
try {
const res = await api.consultOrder({
counselor_id: item.id,
mode: this.activeMode[item.id],
start_time: startTime
const res = await api.consultBooking({
category: f.category,
name: f.name.trim(),
mobile: f.mobile,
prefer_time: f.prefer_time.trim(),
description: f.description.trim()
})
uni.showModal({
title: '预约已提交',
content: res.order_no + '\n' + res.start_time + '\n金额 ¥' + res.amount + '\n' + (res.pay_hint || ''),
content: (res && res.notice) || '咨询助理会在 1 个工作日内联系你',
showCancel: false,
confirmColor: '#E8604C'
})
this.form.description = ''
this.load()
} catch (e) {
} finally {
this.booking = 0
this.submitting = false
}
},
cancel(item) {
cancelBooking(item) {
uni.showModal({
title: '取消预约',
content: '确定取消这次咨询预约吗?',
@@ -200,13 +220,38 @@ export default {
success: async (res) => {
if (!res.confirm) return
try {
await api.consultCancel(item.id)
this.load()
const r = await api.consultBookingCancel(item.id)
this.bookings = (r && r.list) || []
} catch (e) {}
}
})
},
startTest(item) {
async startAssessment(item) {
if (item.need_pay && !item.paid) {
uni.showModal({
title: '购买心理测评',
content: item.title + '\n价格 ¥' + item.price + '\n支付后即可开始作答与查看报告',
confirmText: '去支付',
confirmColor: '#E8604C',
success: async (res) => {
if (!res.confirm) return
try {
const order = await api.assessmentOrder(item.id)
if (order && order.paid) {
uni.navigateTo({ url: '/pages/assessment/index?id=' + item.id })
return
}
uni.showModal({
title: '订单已创建',
content: '订单号:' + (order.order_no || '') + '\n' + (order.pay_hint || ''),
showCancel: false,
confirmColor: '#E8604C'
})
} catch (e) {}
}
})
return
}
uni.navigateTo({ url: '/pages/assessment/index?id=' + item.id })
},
callHotline() {
@@ -244,11 +289,7 @@ export default {
border-radius: 28rpx;
background: linear-gradient(135deg, #FFF1E0 0%, #FFE3D3 100%);
border: 2rpx solid #F7DCC8;
margin-bottom: 20rpx;
}
.crisis-icon {
margin-right: 16rpx;
margin-bottom: 24rpx;
}
.crisis-body {
@@ -258,7 +299,7 @@ export default {
}
.crisis-title {
font-size: 26rpx;
font-size: 28rpx;
color: #A8452F;
font-weight: 500;
}
@@ -269,229 +310,253 @@ export default {
color: #B5715B;
}
.counselor {
padding: 28rpx;
.form-card {
padding-bottom: 28rpx;
}
.counselor-head {
.field-label {
display: block;
font-size: 24rpx;
color: #8C7367;
margin: 22rpx 0 12rpx;
}
.cat-grid {
display: flex;
flex-wrap: wrap;
}
.cat {
padding: 12rpx 22rpx;
border-radius: 999rpx;
background-color: #FFF4EE;
margin: 0 12rpx 12rpx 0;
}
.cat-active {
background: linear-gradient(135deg, #F58C7C 0%, #E8604C 100%);
box-shadow: 0 8rpx 18rpx rgba(232, 96, 76, 0.2);
}
.cat-text {
font-size: 24rpx;
color: #8C7367;
}
.cat-text-active {
color: #FFFFFF;
font-weight: 500;
}
.hq-input {
height: 84rpx;
padding: 0 24rpx;
background-color: #FFF9F5;
border-radius: 20rpx;
font-size: 26rpx;
color: #3E2C27;
}
.hq-textarea {
width: 100%;
min-height: 150rpx;
padding: 22rpx 24rpx;
box-sizing: border-box;
background-color: #FFF9F5;
border-radius: 20rpx;
font-size: 26rpx;
color: #3E2C27;
line-height: 1.7;
}
.ph {
color: #C9B4AA;
font-size: 24rpx;
}
.submit-btn {
margin-top: 28rpx;
}
.submit-text {
font-size: 30rpx;
color: #FFFFFF;
letter-spacing: 2rpx;
}
.form-notice {
display: block;
margin-top: 16rpx;
font-size: 20rpx;
color: #B9A79E;
line-height: 1.7;
text-align: center;
}
.booking {
display: flex;
align-items: flex-start;
padding: 18rpx 0;
}
.booking + .booking {
border-top: 2rpx solid #F5E7DF;
}
.booking-body {
flex: 1;
display: flex;
flex-direction: column;
}
.booking-head {
display: flex;
align-items: center;
}
.counselor-avatar {
width: 100rpx;
height: 100rpx;
border-radius: 30rpx;
.booking-cat {
font-size: 26rpx;
font-weight: 600;
color: #3E2C27;
}
.booking-status {
margin-left: 12rpx;
font-size: 18rpx;
padding: 4rpx 14rpx;
border-radius: 999rpx;
background-color: #FFF1E9;
color: #B5715B;
}
.st-pending {
background-color: #FFF6E6;
color: #B5802A;
}
.st-contacted {
background-color: #EAF4EE;
color: #2F7A4F;
}
.st-finished {
background-color: #F1F0FB;
color: #5B5B8A;
}
.st-canceled {
background-color: #F5E7DF;
color: #A08D84;
}
.booking-desc {
margin-top: 6rpx;
font-size: 24rpx;
color: #5C4A43;
line-height: 1.6;
}
.booking-meta {
margin-top: 6rpx;
font-size: 20rpx;
color: #B9A79E;
}
.booking-cancel {
margin-left: 16rpx;
font-size: 22rpx;
color: #C9B4AA;
}
.assess {
padding: 26rpx 28rpx;
}
.assess-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
}
.assess-title-wrap {
flex: 1;
display: flex;
flex-direction: column;
padding-right: 16rpx;
}
.assess-title {
font-size: 28rpx;
font-weight: 600;
color: #3E2C27;
}
.assess-sub {
margin-top: 6rpx;
font-size: 22rpx;
color: #8C7367;
line-height: 1.6;
}
.assess-price {
padding: 8rpx 18rpx;
border-radius: 999rpx;
background: linear-gradient(135deg, #F5A65B 0%, #E8604C 100%);
}
.assess-price-free {
background-color: #EAF4EE;
}
.assess-price-text {
font-size: 22rpx;
color: #FFFFFF;
font-weight: 600;
}
.assess-price-free-text {
color: #2F7A4F;
}
.assess-meta {
display: flex;
flex-wrap: wrap;
margin-top: 12rpx;
}
.assess-meta-item {
font-size: 20rpx;
color: #B9A79E;
margin-right: 18rpx;
}
.assess-actions {
margin-top: 18rpx;
padding-top: 18rpx;
border-top: 2rpx solid #F5E7DF;
}
.assess-btn {
height: 76rpx;
border-radius: 38rpx;
background-color: #FFF1E9;
display: flex;
align-items: center;
justify-content: center;
}
.counselor-info {
flex: 1;
margin-left: 18rpx;
display: flex;
flex-direction: column;
}
.counselor-name-row {
display: flex;
align-items: center;
}
.counselor-name {
font-size: 30rpx;
font-weight: 600;
color: #3E2C27;
}
.counselor-cert {
margin-left: 10rpx;
font-size: 18rpx;
color: #2F7A4F;
background-color: #E9F5EC;
padding: 4rpx 12rpx;
border-radius: 999rpx;
}
.counselor-title {
margin-top: 4rpx;
font-size: 22rpx;
color: #8C7367;
}
.counselor-tags {
display: flex;
flex-wrap: wrap;
margin-top: 8rpx;
}
.counselor-tag {
font-size: 18rpx;
color: #B5715B;
background-color: #FFF4EE;
padding: 4rpx 12rpx;
border-radius: 999rpx;
margin-right: 8rpx;
}
.counselor-intro {
display: block;
margin-top: 14rpx;
font-size: 22rpx;
color: #8C7367;
line-height: 1.7;
}
.modes {
display: flex;
margin-top: 16rpx;
}
.mode {
flex: 1;
height: 68rpx;
border-radius: 20rpx;
background-color: #FFF9F5;
margin-right: 10rpx;
display: flex;
align-items: center;
justify-content: center;
}
.mode:last-child {
margin-right: 0;
}
.mode-active {
.assess-btn-pay {
background: linear-gradient(135deg, #F58C7C 0%, #E8604C 100%);
box-shadow: 0 10rpx 22rpx rgba(232, 96, 76, 0.22);
}
.mode-text {
font-size: 22rpx;
color: #8C7367;
}
.mode-text-active {
color: #FFFFFF;
font-weight: 500;
}
.slots {
display: flex;
flex-wrap: wrap;
margin-top: 14rpx;
}
.slot {
font-size: 20rpx;
color: #8C7367;
background-color: #FFF4EE;
padding: 8rpx 16rpx;
border-radius: 999rpx;
margin: 0 10rpx 10rpx 0;
}
.slot-active {
background-color: #FFE6DC;
color: #C9482F;
font-weight: 600;
}
.book {
height: 80rpx;
margin-top: 8rpx;
}
.book-text {
font-size: 28rpx;
color: #FFFFFF;
}
.order {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16rpx 0;
}
.order + .order {
border-top: 2rpx solid #F5E7DF;
}
.order-body {
flex: 1;
display: flex;
flex-direction: column;
}
.order-title {
.assess-btn-text {
font-size: 26rpx;
color: #3E2C27;
}
.order-time {
margin-top: 4rpx;
font-size: 22rpx;
color: #8C7367;
}
.order-no {
margin-top: 2rpx;
font-size: 18rpx;
color: #C9B4AA;
}
.order-right {
display: flex;
flex-direction: column;
align-items: flex-end;
}
.order-status {
font-size: 22rpx;
color: #E8604C;
}
.order-cancel {
margin-top: 8rpx;
font-size: 20rpx;
color: #C9B4AA;
}
.test {
display: flex;
align-items: center;
padding: 24rpx 26rpx;
}
.test-body {
flex: 1;
display: flex;
flex-direction: column;
}
.test-title {
font-size: 26rpx;
color: #3E2C27;
}
.test-sub {
margin-top: 4rpx;
font-size: 22rpx;
color: #8C7367;
}
.test-meta {
margin-top: 4rpx;
font-size: 18rpx;
color: #C9B4AA;
}
.test-action {
font-size: 22rpx;
color: #E8604C;
.assess-btn-pay .assess-btn-text {
color: #FFFFFF;
}
.footer {

查看文件

@@ -85,7 +85,8 @@ $modules = [
'family_bind' => '家人绑定', 'care_message' => '沟通留言', 'point_log' => '爱心积分',
'memory' => '纪念日', 'course_order' => '课程订单',
'baby' => '宝宝档案', 'growth_record' => '成长记录', 'vaccine' => '疫苗与儿保',
'counselor' => '咨询师', 'consult_order' => '咨询订单', 'assessment' => '量表管理', 'assessment_record' => '测评记录',
'counselor' => '咨询师', 'consult_order' => '咨询订单', 'consult_booking' => '心理预约',
'assessment' => '量表管理', 'assessment_record' => '测评记录', 'assessment_order' => '测评订单',
'member_plan' => '会员套餐', 'member_order' => '会员订单', 'user_setting' => '隐私与提醒', 'user_backup' => '数据备份',
];

查看文件

@@ -132,10 +132,14 @@ bbt = r.get("data") or {}
check("体温曲线含今日", any(x.get("temperature") == 36.62 for x in (bbt.get("list") or [])), f"{bbt.get('count')} 天")
r = call("/api/prepare/lhtest", {"test_type": "lh", "log_date": str(today), "level": 3}, "POST")
lh = r.get("data") or {}
check("试纸识别", lh.get("result") == "strong", lh.get("result_text"))
check("识别置信度", (lh.get("confidence") or 0) > 80, str(lh.get("confidence")))
check("额度扣减", (lh.get("quota") or {}).get("used", 0) >= 1, str((lh.get("quota") or {}).get("used")))
if r.get("code") == 1:
lh = r.get("data") or {}
check("试纸识别", lh.get("result") == "strong", lh.get("result_text"))
check("识别置信度", (lh.get("confidence") or 0) > 80, str(lh.get("confidence")))
check("额度扣减", (lh.get("quota") or {}).get("used", 0) >= 1, str((lh.get("quota") or {}).get("used")))
else:
# 免费额度用尽(每月 5 次)时应给出明确提示,属预期行为
check("试纸识别额度控制", ("用完" in (r.get("msg") or "")) or ("会员" in (r.get("msg") or "")), r.get("msg"))
r = call("/api/prepare/taskSave", {"title": "预约孕前检查", "scope": "prepare", "category": "check"}, "POST")
check("备孕任务新增", r.get("code") == 1, r.get("msg"))
@@ -239,51 +243,61 @@ r = call("/api/parenting/courses")
check("育儿课程", len((r.get("data") or {}).get("list") or []) >= 3)
print("=" * 72)
print("8. M9 心理咨询与测评")
print("8. M9 心理咨询(预约表单)+ 心理测评")
r = call("/api/consult/index")
con = r.get("data") or {}
check("咨询总览", "counselors" in con and "crisis" in con)
check("咨询师≥3", len(con.get("counselors") or []) >= 3)
counselor = (con.get("counselors") or [{}])[0]
check("咨询师含资质/价格/时段", bool(counselor.get("cert_verify")) and bool(counselor.get("slots")))
import re as _re
_slot = (counselor.get("slots") or [""])[0]
check("时段为完整时间格式", bool(_re.match(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$", _slot)), _slot)
check("咨询总览", "categories" in con and "bookings" in con and "assessments" in con)
check("咨询分类 11 个", len(con.get("categories") or []) == 11, f"{len(con.get('categories') or [])} 个")
check("危机信息含热线", "12356" in ((con.get("crisis") or {}).get("text") or ""))
r = call("/api/consult/orderCreate", {
"counselor_id": counselor.get("id"),
"mode": "video",
"start_time": (datetime.datetime.now() + datetime.timedelta(days=2)).strftime("%Y-%m-%d 15:00"),
# 清理历史待处理预约,保证可重复执行
for b in (con.get("bookings") or []):
if b.get("status") in ("pending", "contacted"):
call("/api/consult/bookingCancel", {"id": b["id"]}, "POST")
r = call("/api/consult/booking", {
"name": "小满", "mobile": "13900002222", "category": "emotion",
"prefer_time": "工作日 19:00-21:00", "description": "最近工作压力大,睡眠不好,想找人聊聊",
}, "POST")
order = r.get("data") or {}
check("咨询预约", bool(order.get("order_no")), order.get("order_no"))
consult_id = order.get("order_id", 0)
r = call("/api/consult/orders")
check("预约列表", len((r.get("data") or {}).get("list") or []) >= 1)
r = call("/api/consult/cancel", {"id": consult_id}, "POST")
check("取消预约", r.get("code") == 1)
booking = r.get("data") or {}
check("提交咨询预约", r.get("code") == 1 and bool(booking.get("id")), r.get("msg"))
check("预约分类中文", booking.get("category") == "情绪疏导", str(booking.get("category")))
booking_id = booking.get("id", 0)
r = call("/api/consult/bookings")
blist = (r.get("data") or {}).get("list") or []
check("我的预约列表", any(x.get("id") == booking_id for x in blist), f"{len(blist)} 条")
if blist:
check("手机号脱敏", "****" in (blist[0].get("mobile") or ""))
r = call("/api/consult/bookingCancel", {"id": booking_id}, "POST")
check("取消预约", r.get("code") == 1, r.get("msg"))
# 测评:PMS(低风险)
r = call("/api/consult/assessments", {"scope": "mood"})
alist = (r.get("data") or {}).get("list") or []
codes = {a.get("code"): a for a in alist}
check("量表列表含 SDS", "dep_sds" in codes)
check("量表列表含 SAS", "anx_sas" in codes)
check("量表列表含 16PF", "pf16" in codes)
sds = codes.get("dep_sds") or {}
check("SDS 需付费 29.9", sds.get("need_pay") is True and abs((sds.get("price") or 0) - 29.9) < 0.01, f"¥{sds.get('price')}")
check("SDS 题数 20", sds.get("questions") == 20, str(sds.get("questions")))
r = call("/api/consult/assessmentDetail", {"id": sds.get("id")})
detail = r.get("data") or {}
check("SDS 题库加载", len(detail.get("items") or []) == 20 and len(detail.get("options") or []) == 4)
# 免费量表(PMS)计分仍正常
pms = next((a for a in alist if a.get("code") == "pms"), None)
check("量表列表含 PMS", pms is not None)
check("免费量表 PMS 存在", pms is not None)
if pms:
r = call("/api/consult/assessmentDetail", {"id": pms["id"]})
detail = r.get("data") or {}
check("量表题目加载", len(detail.get("questions") or []) == 5 and len(detail.get("options") or []) == 5)
r = call("/api/consult/assessmentSubmit", {"id": pms["id"], "answers": json.dumps([0, 1, 1, 0, 1])}, "POST")
res = r.get("data") or {}
check("测评计分", res.get("score") == 3, str(res.get("score")))
check("测评结果分级", res.get("result") == "low", res.get("result_text"))
check("测评含免责声明", "仅供参考" in (res.get("disclaimer") or ""))
check("PMS 计分 3", res.get("score") == 3, str(res.get("score")))
check("PMS 分级 low", res.get("result") == "low", str(res.get("result")))
# 测评:产后情绪(高风险 → 危机干预)
# 产后情绪高风险 → 危机干预
pdp = next((a for a in alist if a.get("code") == "pdp"), None)
if not pdp:
r2 = call("/api/consult/assessments", {"scope": "parenting"})
pdp = next((a for a in ((r2.get("data") or {}).get("list") or []) if a.get("code") == "pdp"), None)
check("量表列表含产后筛查", pdp is not None)
if pdp:
r = call("/api/consult/assessmentSubmit", {"id": pdp["id"], "answers": json.dumps([3, 3, 3, 3, 3])}, "POST")
res = r.get("data") or {}

查看文件

@@ -0,0 +1,223 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""花期 APP · 心理咨询预约 + 付费心理测评 全链路验证
前置:
export HQ_TEST_ACCOUNT=demo HQ_TEST_PASSWORD=demo123456
可选:
export HQ_ASSESSMENT_PAID=1 # 已在后台把测评订单置为 paid 后,验证计分链路
用法:
python3 scripts/verify/consult_assessment_test.py
"""
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
BASE = os.environ.get("HQ_API_BASE", "https://huaqiapp.gzyakj.com.cn")
ACCOUNT = os.environ.get("HQ_TEST_ACCOUNT", "")
PASSWORD = os.environ.get("HQ_TEST_PASSWORD", "")
PAID_READY = os.environ.get("HQ_ASSESSMENT_PAID", "") == "1"
TOKEN = ""
PASSED = []
FAILED = []
if not ACCOUNT or not PASSWORD:
print("请先设置 HQ_TEST_ACCOUNT / HQ_TEST_PASSWORD")
sys.exit(2)
def call(path, params=None, method="GET", auth=True):
url = BASE + path
data = None
if method == "GET" and params:
url += "?" + urllib.parse.urlencode(params)
elif method == "POST":
data = urllib.parse.urlencode(params or {}).encode()
req = urllib.request.Request(url, data=data, method=method)
req.add_header("Accept", "application/json")
if auth and TOKEN:
req.add_header("token", TOKEN)
try:
with urllib.request.urlopen(req, timeout=25) as resp:
return json.loads(resp.read().decode("utf-8"))
except urllib.error.HTTPError as e:
return {"code": -e.code, "msg": e.read().decode("utf-8", "ignore")[:200]}
except Exception as e:
return {"code": -1, "msg": str(e)}
def check(name, cond, detail=""):
if cond:
PASSED.append(name)
print(f" ✅ {name}" + (f" {detail}" if detail else ""))
else:
FAILED.append(f"{name} {detail}")
print(f" ❌ {name} {detail}")
print("=" * 72)
print("0. 登录")
r = call("/api/user/login", {"account": ACCOUNT, "password": PASSWORD}, "POST", auth=False)
info = (r.get("data") or {}).get("userinfo") or {}
TOKEN = info.get("token", "")
check("登录成功", bool(TOKEN))
print("=" * 72)
print("1. 咨询分类(免登录)")
r = call("/api/consult/categories", auth=False)
cats = (r.get("data") or {}).get("list") or []
names = [c.get("name") for c in cats]
check("分类 11 个", len(cats) == 11, f"{len(cats)} 个")
for expect in ["婚恋咨询", "青少年心理", "职场人际", "情绪疏导", "人生卡点", "成长迷茫",
"脱单指导", "分手挽回", "社恐咨询", "抑郁焦虑", "情绪压力"]:
check(f"分类含「{expect}」", expect in names)
print("=" * 72)
print("2. 预约表单校验")
r = call("/api/consult/booking", {"name": "", "mobile": "13800000000", "category": "love",
"prefer_time": "工作日 19:00", "description": "最近压力很大"}, "POST")
check("缺少称呼被拦截", r.get("code") == 0, r.get("msg"))
r = call("/api/consult/booking", {"name": "小满", "mobile": "1390000", "category": "love",
"prefer_time": "工作日 19:00", "description": "最近压力很大"}, "POST")
check("手机号格式校验", r.get("code") == 0, r.get("msg"))
r = call("/api/consult/booking", {"name": "小满", "mobile": "13900001111", "category": "unknown",
"prefer_time": "工作日 19:00", "description": "最近压力很大"}, "POST")
check("非法分类被拦截", r.get("code") == 0, r.get("msg"))
r = call("/api/consult/booking", {"name": "小满", "mobile": "13900001111", "category": "love",
"prefer_time": "工作日 19:00", "description": "最近压力很大"}, "POST")
data = r.get("data") or {}
check("提交预约成功", r.get("code") == 1 and bool(data.get("id")), r.get("msg"))
booking_id = data.get("id", 0)
check("返回分类中文", data.get("category") == "婚恋咨询", str(data.get("category")))
check("返回联系提示", bool(data.get("notice")))
r = call("/api/consult/booking", {"name": "小满", "mobile": "13900001111", "category": "emotion",
"prefer_time": "明天上午", "description": "重复提交测试"}, "POST")
check("10 分钟内重复提交被拦截", r.get("code") == 0, r.get("msg"))
print("=" * 72)
print("3. 我的预约")
r = call("/api/consult/bookings")
list_ = (r.get("data") or {}).get("list") or []
check("预约列表含新记录", any(x.get("id") == booking_id for x in list_), f"{len(list_)} 条")
if list_:
first = list_[0]
check("手机号脱敏", "****" in (first.get("mobile") or ""), first.get("mobile"))
check("状态文案", first.get("status_text") in ("待联系", "已联系", "已完成", "已取消"), first.get("status_text"))
r = call("/api/consult/bookingCancel", {"id": booking_id}, "POST")
list_ = (r.get("data") or {}).get("list") or []
check("取消预约", any(x.get("id") == booking_id and x.get("status") == "canceled" for x in list_), r.get("msg"))
print("=" * 72)
print("4. 心理测评列表(付费)")
r = call("/api/consult/assessments", {"scope": "mood"})
scales = (r.get("data") or {}).get("list") or []
by_code = {s.get("code"): s for s in scales}
for code, title, price, count in [("dep_sds", "抑郁自评量表(SDS)", 29.9, 20),
("anx_sas", "焦虑自评量表(SAS)", 29.9, 20),
("pf16", "卡特尔十六种人格因素测验(16PF 简版)", 59.9, 48)]:
s = by_code.get(code)
check(f"量表存在:{code}", s is not None)
if s:
check(f" {code} 需付费", s.get("need_pay") is True and abs((s.get("price") or 0) - price) < 0.01,
f"¥{s.get('price')}")
check(f" {code} 题数 {count}", s.get("questions") == count, str(s.get("questions")))
if not PAID_READY:
check(f" {code} 未购买锁定", s.get("paid") is False and s.get("locked") is True)
else:
check(f" {code} 已购买解锁", s.get("paid") is True)
print("=" * 72)
print("5. 题库与选项")
sid = by_code.get("dep_sds", {}).get("id")
r = call("/api/consult/assessmentDetail", {"id": sid})
d = r.get("data") or {}
check("SDS 题库加载", len(d.get("items") or []) == 20 and len(d.get("options") or []) == 4)
check("SDS 选项为 1-4 级", [o.get("value") for o in d.get("options") or []] == [1, 2, 3, 4])
check("SDS 含计分类型", d.get("scale") == "SDS")
pf = by_code.get("pf16", {})
r = call("/api/consult/assessmentDetail", {"id": pf.get("id")})
pd = r.get("data") or {}
check("16PF 题库 48 题", len(pd.get("items") or []) == 48)
check("16PF 三选项", len(pd.get("options") or []) == 3)
check("16PF 16 个维度", len(pd.get("dims") or {}) == 16)
print("=" * 72)
if not PAID_READY:
print("6. 未付费拦截")
answers20 = [1] * 20
r = call("/api/consult/assessmentSubmit", {"id": sid, "answers": json.dumps(answers20)}, "POST")
check("未付费提交被拒绝", r.get("code") == 0, r.get("msg"))
need_pay = (r.get("data") or {}).get("need_pay") if isinstance(r.get("data"), dict) else None
check("返回 need_pay 标记", need_pay == 1 or "付费" in (r.get("msg") or ""), str(need_pay))
print("=" * 72)
print("7. 下单")
r = call("/api/consult/assessmentOrder", {"id": sid}, "POST")
order = r.get("data") or {}
check("测评订单创建", bool(order.get("order_no")) and order.get("need_pay") is True, order.get("order_no"))
check("订单金额正确", abs((order.get("amount") or 0) - 29.9) < 0.01, str(order.get("amount")))
else:
print("6. 已付费(跳过未付费拦截断言)")
print("7. 已付费(跳过下单断言)")
order = {}
if not PAID_READY:
print("=" * 72)
print("⏸ 未设置 HQ_ASSESSMENT_PAID=1,跳过计分链路(请先在后台把该订单置为已支付)")
print(f" 订单号:{order.get('order_no')}")
else:
print("=" * 72)
print("8. 付费后计分(SDS / SAS / 16PF)")
r = call("/api/consult/assessments", {"scope": "mood"})
paid_list = {s.get("code"): s for s in ((r.get("data") or {}).get("list") or [])}
check("SDS 已解锁", paid_list.get("dep_sds", {}).get("paid") is True)
# SDS:全部选第 1 个选项(值 1)→ 粗分 47 → 标准分 59(轻度)
r = call("/api/consult/assessmentSubmit", {"id": sid, "answers": json.dumps([0] * 20)}, "POST")
res = r.get("data") or {}
check("SDS 提交成功", r.get("code") == 1, r.get("msg"))
check("SDS 标准分 62", res.get("score") == 62, str(res.get("score")))
check("SDS 分级 mild", res.get("result") == "mild", str(res.get("result")))
check("SDS 含建议与免责", bool(res.get("advice")) and "仅供参考" in (res.get("disclaimer") or ""))
# SDS 风险:第 19 题选最高(自伤念头)→ risk_flag
risky = [0] * 20
risky[18] = 3
r = call("/api/consult/assessmentSubmit", {"id": sid, "answers": json.dumps(risky)}, "POST")
res = r.get("data") or {}
check("SDS 高风险触发危机干预", res.get("risk_flag") == 1 and bool((res.get("crisis") or {}).get("hotlines")))
# SAS:全部选第 2 个选项(值 2)→ 粗分 40 → 标准分 50(轻度)
sas_id = paid_list.get("anx_sas", {}).get("id")
r = call("/api/consult/assessmentSubmit", {"id": sas_id, "answers": json.dumps([1] * 20)}, "POST")
res = r.get("data") or {}
check("SAS 标准分 56", res.get("score") == 56, str(res.get("score")))
check("SAS 分级 mild", res.get("result") == "mild", str(res.get("result")))
# 16PF:全选 A(值 2)→ 每维度 6 分 → 标准分 10
pf_id = paid_list.get("pf16", {}).get("id")
r = call("/api/consult/assessmentSubmit", {"id": pf_id, "answers": json.dumps([0] * 48)}, "POST")
res = r.get("data") or {}
check("16PF 提交成功", r.get("code") == 1, r.get("msg"))
check("16PF 16 维剖面", len(res.get("dims") or []) == 16)
check("16PF 维度满分 10", all(d.get("score") == 10 for d in (res.get("dims") or [])), str((res.get("dims") or [{}])[0]))
check("16PF 含主导特质文案", "最突出的特质" in (res.get("result_text") or ""), res.get("result_text"))
print("=" * 72)
print(f"通过 {len(PASSED)} 项,失败 {len(FAILED)} 项")
if FAILED:
for f in FAILED:
print(" ❌ " + f)
sys.exit(1)
print("🎉 咨询预约 + 付费心理测评 全链路验证通过")

查看文件

@@ -0,0 +1,13 @@
<?php
namespace app\admin\controller;
/**
* 测评订单(心理服务)
*
* 表:fa_assessment_order
*/
class AssessmentOrder extends Manage
{
protected $fixedTable = 'fa_assessment_order';
}

查看文件

@@ -0,0 +1,13 @@
<?php
namespace app\admin\controller;
/**
* 心理预约(心理服务)
*
* 表:fa_consult_booking
*/
class ConsultBooking extends Manage
{
protected $fixedTable = 'fa_consult_booking';
}

查看文件

@@ -46,7 +46,12 @@ class ManageConfig
'memory_type' => ['anniversary' => '纪念日', 'milestone' => '里程碑', 'daily' => '日常记录'],
'vaccine_type' => ['vaccine' => '疫苗', 'checkup' => '儿保体检'],
'gender' => ['0' => '未知', '1' => '男', '2' => '女'],
'advice_key' => [],
'consult_category' => [
'love' => '婚恋咨询', 'teen' => '青少年心理', 'career' => '职场人际', 'emotion' => '情绪疏导',
'life' => '人生卡点', 'growth' => '成长迷茫', 'single' => '脱单指导', 'breakup' => '分手挽回',
'social' => '社恐咨询', 'depress' => '抑郁焦虑', 'pressure' => '情绪压力',
],
'booking_status' => ['pending' => '待联系', 'contacted' => '已联系', 'finished' => '已完成', 'canceled' => '已取消'],
];
/**
@@ -367,11 +372,40 @@ class ManageConfig
'scoring' => ['label' => '分级规则(JSON)', 'type' => 'textarea'],
'level' => ['label' => '版本', 'type' => 'select', 'options' => 'level'],
'scope' => ['label' => '归属', 'type' => 'select', 'options' => ['mood' => '情绪', 'relation' => '关系', 'parenting' => '育儿']],
'access' => ['label' => '访问权限', 'type' => 'select', 'options' => 'access'],
'access' => ['label' => '访问权限', 'type' => 'select', 'options' => 'access', 'search' => true],
'price' => ['label' => '测评价格', 'type' => 'decimal'],
'status' => ['label' => '状态', 'type' => 'select', 'options' => 'status'],
'weigh' => ['label' => '权重', 'type' => 'number'],
],
],
'fa_consult_booking' => [
'title' => '心理预约',
'group' => '心理服务',
'sort' => 'id desc',
'fields' => [
'user_id' => ['label' => '用户', 'type' => 'user', 'search' => true],
'name' => ['label' => '称呼', 'type' => 'text', 'search' => true],
'mobile' => ['label' => '联系电话', 'type' => 'text', 'search' => true],
'category' => ['label' => '咨询分类', 'type' => 'select', 'options' => 'consult_category', 'search' => true],
'prefer_time' => ['label' => '方便时间', 'type' => 'text'],
'description' => ['label' => '困扰描述', 'type' => 'textarea'],
'status' => ['label' => '跟进状态', 'type' => 'select', 'options' => 'booking_status', 'search' => true],
'admin_remark' => ['label' => '跟进备注', 'type' => 'textarea'],
],
],
'fa_assessment_order' => [
'title' => '测评订单',
'group' => '心理服务',
'sort' => 'id desc',
'fields' => [
'order_no' => ['label' => '订单号', 'type' => 'text', 'search' => true],
'user_id' => ['label' => '用户', 'type' => 'user', 'search' => true],
'assessment_id' => ['label' => '量表ID', 'type' => 'number', 'search' => true],
'amount' => ['label' => '金额', 'type' => 'decimal'],
'pay_status' => ['label' => '支付状态', 'type' => 'select', 'options' => 'pay_status', 'search' => true],
'pay_time' => ['label' => '支付时间', 'type' => 'datetime'],
],
],
'fa_assessment_record' => [
'title' => '测评记录',
'group' => '心理服务',

查看文件

@@ -9,46 +9,149 @@ use fast\Random;
use think\Db;
/**
* 心理咨询与测评接口(M9)
* 心理咨询与心理测评接口(M9)
*
* 咨询师入驻与排班 / 一对一咨询预约 / 量表测评 / 危机干预转介
* 咨询:线上预约表单(不选咨询师时段),按分类提交,后台跟进。
* 测评:抑郁自评 SDS / 焦虑自评 SAS / 卡特尔 16PF(简版)等,付费后作答。
*/
class Consult extends Api
{
protected $noNeedLogin = [];
protected $noNeedLogin = ['categories'];
protected $noNeedRight = '*';
/** 咨询分类 */
public static $categories = [
'love' => '婚恋咨询',
'teen' => '青少年心理',
'career' => '职场人际',
'emotion' => '情绪疏导',
'life' => '人生卡点',
'growth' => '成长迷茫',
'single' => '脱单指导',
'breakup' => '分手挽回',
'social' => '社恐咨询',
'depress' => '抑郁焦虑',
'pressure' => '情绪压力',
];
/**
* 总览
* 咨询分类(无需登录,供表单下拉)
*/
public function categories()
{
$list = [];
foreach (self::$categories as $key => $text) {
$list[] = ['key' => $key, 'name' => $text];
}
$this->success('', ['list' => $list]);
}
/**
* 心理服务总览:分类 + 我的预约 + 可做测评 + 危机信息
*/
public function index()
{
$userId = $this->auth->id;
$status = MemberService::status($userId);
$this->success('', [
'counselors' => $this->counselorList(5),
'assessments' => array_merge(
AssessmentService::lists('mood', $userId),
AssessmentService::lists('parenting', $userId)
),
'orders' => $this->orderList(),
'crisis' => AssessmentService::crisis(),
'member' => $status,
'discount' => MemberService::can($userId, 'consult.discount') ? 0.9 : 1,
'categories' => $this->categoriesData(),
'bookings' => $this->bookingList($userId, 5),
'assessments' => AssessmentService::lists('mood', $userId),
'crisis' => AssessmentService::crisis(),
'member' => MemberService::status($userId),
'notice' => '提交后 1 个工作日内,咨询助理会通过电话或微信与你联系',
]);
}
/**
* 咨询师列表(含资质、价格、可预约时段)
* 提交咨询预约表单
* POST name, mobile, category, prefer_time, description
*/
public function counselors()
public function booking()
{
$this->success('', ['list' => $this->counselorList(20)]);
$userId = $this->auth->id;
$name = mb_substr(trim((string)$this->request->post('name', '')), 0, 30);
$mobile = trim((string)$this->request->post('mobile', ''));
$category = trim((string)$this->request->post('category', ''));
$preferTime = mb_substr(trim((string)$this->request->post('prefer_time', '')), 0, 40);
$description = mb_substr(trim((string)$this->request->post('description', '')), 0, 500);
if (!$name) {
$this->error('请填写你的称呼');
}
if (!preg_match('/^1\d{10}$/', $mobile)) {
$this->error('请填写正确的 11 位手机号');
}
if (!isset(self::$categories[$category])) {
$this->error('请选择咨询分类');
}
if (!$preferTime) {
$this->error('请填写方便联系的时间');
}
if (mb_strlen($description) < 5) {
$this->error('请简单描述一下你的困扰(至少 5 个字)');
}
// 同一用户 10 分钟内不允许重复提交
$recent = Db::name('consult_booking')
->where('user_id', $userId)
->where('createtime', '>', time() - 600)
->where('status', 'pending')
->count();
if ($recent > 0) {
$this->error('你已提交过预约,请等待咨询助理联系');
}
$id = Db::name('consult_booking')->insertGetId([
'user_id' => $userId,
'name' => $name,
'mobile' => $mobile,
'category' => $category,
'prefer_time' => $preferTime,
'description' => $description,
'status' => 'pending',
'createtime' => time(),
'updatetime' => time(),
]);
$this->success('预约已提交', [
'id' => (int)$id,
'category' => self::$categories[$category],
'status_text' => '待联系',
'notice' => '咨询助理会在 1 个工作日内联系你,请保持电话畅通',
'hotline' => '12356',
]);
}
/**
* 量表列表 / 详情 / 提交
* 我的预约列表
*/
public function bookings()
{
$this->success('', ['list' => $this->bookingList($this->auth->id, 20)]);
}
/**
* 取消预约
*/
public function bookingCancel()
{
$id = (int)$this->request->post('id', 0);
$row = Db::name('consult_booking')->where('id', $id)->where('user_id', $this->auth->id)->find();
if (!$row) {
$this->error('预约不存在');
}
if ($row['status'] === 'finished') {
$this->error('已完成的预约无法取消');
}
Db::name('consult_booking')->where('id', $id)->update([
'status' => 'canceled', 'updatetime' => time(),
]);
$this->success('已取消', ['list' => $this->bookingList($this->auth->id, 20)]);
}
/**
* 测评列表(含价格、是否已购买)
*/
public function assessments()
{
@@ -56,23 +159,104 @@ class Consult extends Api
$this->success('', ['list' => AssessmentService::lists($scope, $this->auth->id)]);
}
/**
* 测评详情(题库)
*/
public function assessmentDetail()
{
$data = AssessmentService::detail($this->request->param('id', 0));
$data = AssessmentService::detail($this->request->param('id', 0), $this->auth->id);
if (!$data) {
$this->error('量表不存在');
}
$this->success('', $data);
}
/**
* 创建测评订单(付费后解锁)
* POST id
*/
public function assessmentOrder()
{
$userId = $this->auth->id;
$id = (int)$this->request->post('id', 0);
$item = Db::name('assessment')->where('id', $id)->where('status', 'normal')->find();
if (!$item) {
$this->error('量表不存在');
}
$price = (float)($item['price'] ?? 0);
if ($item['access'] !== 'pay' || $price <= 0) {
$this->success('该测评无需付费', ['paid' => true, 'need_pay' => false]);
}
if (AssessmentService::isPaid($userId, $id)) {
$this->success('已购买,可直接开始测评', ['paid' => true, 'need_pay' => false]);
}
// 复用未支付订单,避免重复下单
$exist = Db::name('assessment_order')
->where('user_id', $userId)
->where('assessment_id', $id)
->where('pay_status', 'unpaid')
->order('id', 'desc')
->find();
if ($exist) {
$orderNo = $exist['order_no'];
$orderId = (int)$exist['id'];
} else {
$orderNo = 'HA' . date('YmdHis') . Random::numeric(4);
$orderId = Db::name('assessment_order')->insertGetId([
'order_no' => $orderNo,
'user_id' => $userId,
'assessment_id' => $id,
'amount' => $price,
'pay_status' => 'unpaid',
'createtime' => time(),
]);
}
$this->success('订单已创建', [
'order_id' => $orderId,
'order_no' => $orderNo,
'amount' => $price,
'title' => $item['title'],
'pay_hint' => '支付通道接入中:可联系客服完成支付,支付后即可开始测评',
'paid' => false,
'need_pay' => true,
]);
}
/**
* 提交测评(需先付费)
* POST id, answers=[0,1,2...]
*/
public function assessmentSubmit()
{
$userId = $this->auth->id;
$id = (int)$this->request->post('id', 0);
$item = Db::name('assessment')->where('id', $id)->where('status', 'normal')->find();
if (!$item) {
$this->error('量表不存在');
}
$price = (float)($item['price'] ?? 0);
$needPay = $item['access'] === 'pay' && $price > 0;
if ($needPay && !AssessmentService::isPaid($userId, $id)) {
$this->error('该测评需付费后开始', [
'need_pay' => 1,
'price' => $price,
'title' => $item['title'],
'pay_hint' => '支付后即可开始测评',
]);
}
$answers = $this->request->post('answers', '');
$answers = is_array($answers) ? $answers : json_decode(htmlspecialchars_decode((string)$answers, ENT_QUOTES), true);
if (!is_array($answers)) {
$this->error('请完成全部题目');
}
$result = AssessmentService::submit($this->auth->id, (int)$this->request->post('id', 0), $answers);
$result = AssessmentService::submit($userId, $id, $answers);
if (isset($result['error'])) {
$this->error($result['error']);
}
@@ -80,161 +264,80 @@ class Consult extends Api
}
/**
* 预约咨询
* POST counselor_id, mode=text|voice|video, start_time=Y-m-d H:i
*/
public function orderCreate()
{
$userId = $this->auth->id;
$counselorId = (int)$this->request->post('counselor_id', 0);
$mode = $this->request->post('mode', 'text');
$startTime = (string)$this->request->post('start_time', '');
$counselor = Db::name('counselor')->where('id', $counselorId)->where('status', 'on')->find();
if (!$counselor) {
$this->error('咨询师不可预约');
}
if (!in_array($mode, ['text', 'voice', 'video'], true)) {
$this->error('咨询方式不正确');
}
if (!$startTime || !strtotime($startTime)) {
$this->error('请选择预约时间');
}
if (strtotime($startTime) < time()) {
$this->error('预约时间需晚于当前时间');
}
$priceField = 'price_' . $mode;
$amount = (float)$counselor[$priceField];
$discount = MemberService::can($userId, 'consult.discount') ? 0.9 : 1;
$amount = round($amount * $discount, 2);
$rateAmount = round($amount * (float)$counselor['rate'], 2);
$orderNo = 'HQ' . date('YmdHis') . Random::numeric(4);
$id = Db::name('consult_order')->insertGetId([
'order_no' => $orderNo,
'user_id' => $userId,
'counselor_id' => $counselorId,
'mode' => $mode,
'start_time' => strtotime($startTime),
'duration' => 50,
'amount' => $amount,
'pay_status' => 'unpaid',
'consult_status' => 'pending',
'rate_amount' => $rateAmount,
'createtime' => time(),
]);
$this->success('预约已提交', [
'order_id' => (int)$id,
'order_no' => $orderNo,
'amount' => $amount,
'discount' => $discount,
'start_time' => date('Y-m-d H:i', strtotime($startTime)),
'pay_hint' => '支付通道待接入,可联系客服确认支付后开始咨询',
'counselor' => ['name' => $counselor['name'], 'title' => $counselor['title']],
'note' => '咨询内容将加密保存,仅你与咨询师可见',
]);
}
/**
* 我的咨询订单
*/
public function orders()
{
$this->success('', ['list' => $this->orderList()]);
}
/**
* 取消订单
*/
public function cancel()
{
$id = (int)$this->request->post('id', 0);
$row = Db::name('consult_order')->where('id', $id)->where('user_id', $this->auth->id)->find();
if (!$row) {
$this->error('订单不存在');
}
if ($row['consult_status'] === 'finished') {
$this->error('已完成的咨询无法取消');
}
Db::name('consult_order')->where('id', $id)->update(['consult_status' => 'canceled']);
$this->success('已取消', ['list' => $this->orderList()]);
}
/**
* 危机干预信息(前端在高风险结果后也可主动调用)
* 危机干预信息
*/
public function crisis()
{
$this->success('', AssessmentService::crisis());
}
// ---------------- 内部方法 ----------------
protected function counselorList($limit)
/* ============================================================
* 兼容旧接口:咨询师列表与咨询订单(前台已改为预约表单)
* ============================================================ */
public function counselors()
{
$rows = Db::name('counselor')
->where('status', 'on')
->where('cert_verify', 'passed')
->order('weigh', 'desc')
->limit($limit)
->limit(20)
->select();
$member = MemberService::can($this->auth->id, 'consult.discount');
return array_map(function ($row) use ($member) {
$tags = array_filter(explode(',', $row['tags']));
$slots = [];
for ($i = 1; $i <= 3; $i++) {
$day = date('Y-m-d', strtotime('+' . $i . ' day'));
$slots[] = $day . ' 10:00';
$slots[] = $day . ' 15:00';
}
$list = array_map(function ($row) use ($member) {
return [
'id' => (int)$row['id'],
'name' => $row['name'],
'emoji' => $row['avatar_emoji'],
'title' => $row['title'],
'cert_verify' => $row['cert_verify'],
'intro' => $row['intro'],
'tags' => $tags,
'price' => [
'id' => (int)$row['id'],
'name' => $row['name'],
'emoji' => $row['avatar_emoji'],
'title' => $row['title'],
'intro' => $row['intro'],
'tags' => array_filter(explode(',', $row['tags'])),
'price' => [
'text' => (float)$row['price_text'],
'voice' => (float)$row['price_voice'],
'video' => (float)$row['price_video'],
],
'discount' => $member ? 0.9 : 1,
'slots' => $slots,
'discount' => $member ? 0.9 : 1,
];
}, $rows);
$this->success('', ['list' => $list]);
}
protected function orderList()
/* ============================================================
* 内部方法
* ============================================================ */
protected function categoriesData()
{
$rows = Db::name('consult_order')
->where('user_id', $this->auth->id)
$list = [];
foreach (self::$categories as $key => $text) {
$list[] = ['key' => $key, 'name' => $text];
}
return $list;
}
protected function bookingList($userId, $limit = 20)
{
$rows = Db::name('consult_booking')
->where('user_id', $userId)
->order('id', 'desc')
->limit(20)
->limit($limit)
->select();
$names = Db::name('counselor')->column('name', 'id');
$modeText = ['text' => '文字', 'voice' => '语音', 'video' => '视频'];
$statusText = ['pending' => '待开始', 'ongoing' => '进行中', 'finished' => '已完成', 'canceled' => '已取消'];
return array_map(function ($row) use ($names, $modeText, $statusText) {
return [
'id' => (int)$row['id'],
'order_no' => $row['order_no'],
'counselor' => isset($names[$row['counselor_id']]) ? $names[$row['counselor_id']] : '',
'mode' => $row['mode'],
'mode_text' => isset($modeText[$row['mode']]) ? $modeText[$row['mode']] : $row['mode'],
'start_time' => $row['start_time'] ? date('Y-m-d H:i', (int)$row['start_time']) : '',
'amount' => (float)$row['amount'],
'pay_status' => $row['pay_status'],
'status' => $row['consult_status'],
'status_text' => isset($statusText[$row['consult_status']]) ? $statusText[$row['consult_status']] : $row['consult_status'],
$statusText = ['pending' => '待联系', 'contacted' => '已联系', 'finished' => '已完成', 'canceled' => '已取消'];
$list = [];
foreach ($rows as $row) {
$list[] = [
'id' => (int)$row['id'],
'name' => $row['name'],
'mobile' => substr($row['mobile'], 0, 3) . '****' . substr($row['mobile'], -2),
'category' => $row['category'],
'category_text' => self::$categories[$row['category']] ?? $row['category'],
'prefer_time' => $row['prefer_time'],
'description' => $row['description'],
'status' => $row['status'],
'status_text' => $statusText[$row['status']] ?? $row['status'],
'create_time' => date('Y-m-d H:i', (int)$row['createtime']),
];
}, $rows);
}
return $list;
}
}

查看文件

@@ -7,12 +7,15 @@ use think\Db;
/**
* 量表测评服务(M7 关系测评 / M9 心理测评 共用)
*
* 题目为文本数组,答案统一 0-4 五级计分;分级阈值由 scoring 字段配置。
* 危机干预:命中高风险或用「自我伤害」类题目高分时返回转介信息。
* 支持两类题库:
* 1) 新格式(对象):{scale, options[], items[], dims{}, note}
* - SDS / SAS:标准分 = 粗分 × 1.25,支持反向计分
* - 16PF:按维度计分,输出 16 项人格剖面
* 2) 旧格式(题目字符串数组):0-4 五级计分(历史量表,保持兼容)
*/
class AssessmentService
{
/** 危机干预提示(合规文案,必须与人工审核口径一致) */
/** 危机干预提示(合规文案) */
public static function crisis()
{
return [
@@ -22,12 +25,12 @@ class AssessmentService
['name' => '全国心理援助热线', 'phone' => '12356'],
['name' => '北京心理危机研究与干预中心', 'phone' => '010-82951332'],
],
'action' => '如需专业帮助,可预约在线心理咨询',
'action' => '如需专业帮助,可提交在线预约',
];
}
/**
* 量表列表
* 量表列表(含价格与是否已购买)
*/
public static function lists($scope = '', $userId = 0)
{
@@ -40,7 +43,11 @@ class AssessmentService
$result = [];
foreach ($list as $item) {
$questions = json_decode($item['questions'], true) ?: [];
$parsed = self::parseQuestions($item['questions']);
$price = (float)($item['price'] ?? 0);
$needPay = $item['access'] === 'pay' && $price > 0;
$paid = !$needPay || ($userId && self::isPaid($userId, (int)$item['id']));
$last = $userId ? Db::name('assessment_record')
->where('user_id', $userId)
->where('assessment_id', $item['id'])
@@ -48,18 +55,23 @@ class AssessmentService
->find() : null;
$result[] = [
'id' => (int)$item['id'],
'code' => $item['code'],
'title' => $item['title'],
'intro' => $item['intro'],
'scope' => $item['scope'],
'level' => $item['level'],
'access' => $item['access'],
'locked' => $item['access'] === 'member' && !$member['is_member'],
'count' => count($questions),
'id' => (int)$item['id'],
'code' => $item['code'],
'title' => $item['title'],
'intro' => $item['intro'],
'scope' => $item['scope'],
'level' => $item['level'],
'access' => $item['access'],
'price' => $price,
'need_pay' => $needPay,
'paid' => $paid,
'locked' => !$paid,
'questions' => count($parsed['items']),
'scale' => $parsed['scale'],
'note' => $parsed['note'],
'last_score' => $last ? (float)$last['score'] : null,
'last_result' => $last ? $last['result'] : '',
'last_date' => $last ? date('Y-m-d', (int)$last['createtime']) : '',
'last_date' => $last ? date('Y-m-d', (int)$last['createtime']) : '',
];
}
return $result;
@@ -68,20 +80,145 @@ class AssessmentService
/**
* 量表详情(题目与选项)
*/
public static function detail($id)
public static function detail($id, $userId = 0)
{
$item = Db::name('assessment')->where('id', (int)$id)->where('status', 'normal')->find();
if (!$item) {
return null;
}
$parsed = self::parseQuestions($item['questions']);
$price = (float)($item['price'] ?? 0);
$needPay = $item['access'] === 'pay' && $price > 0;
return [
'id' => (int)$item['id'],
'code' => $item['code'],
'title' => $item['title'],
'intro' => $item['intro'],
'scope' => $item['scope'],
'questions' => json_decode($item['questions'], true) ?: [],
'options' => self::options(),
'scale' => $parsed['scale'],
'note' => $parsed['note'],
'questions' => count($parsed['items']),
'items' => $parsed['items'],
'options' => $parsed['options'],
'dims' => $parsed['dims'],
'price' => $price,
'need_pay' => $needPay,
'paid' => !$needPay || ($userId && self::isPaid($userId, (int)$item['id'])),
];
}
/**
* 提交作答(answers 为选项下标)
*/
public static function submit($userId, $assessmentId, $answers)
{
$item = Db::name('assessment')->where('id', (int)$assessmentId)->where('status', 'normal')->find();
if (!$item) {
return ['error' => '量表不存在'];
}
$parsed = self::parseQuestions($item['questions']);
$answers = is_array($answers) ? array_values($answers) : [];
if (count($answers) !== count($parsed['items'])) {
return ['error' => '请完成全部题目'];
}
$options = $parsed['options'];
$optionCount = count($options);
// 下标 → 选项值
$values = [];
foreach ($answers as $index) {
$idx = (int)$index;
$idx = max(0, min($optionCount - 1, $idx));
$values[] = (int)$options[$idx]['value'];
}
$scoring = json_decode($item['scoring'], true) ?: [];
$type = $scoring['type'] ?? 'legacy';
if ($type === 'standard_score') {
$result = self::scoreStandard($parsed, $scoring, $values);
} elseif ($type === 'profile') {
$result = self::scoreProfile($parsed, $scoring, $values);
} else {
$result = self::scoreLegacy($parsed, $scoring, $values);
}
$risk = $result['risk_flag'];
$advice = $result['advice'];
if ($risk) {
array_unshift($advice, '检测到需要关注的风险信号,建议尽快寻求专业支持。');
}
$id = Db::name('assessment_record')->insertGetId([
'user_id' => $userId,
'assessment_id' => (int)$item['id'],
'answers' => json_encode($values),
'score' => $result['score'],
'result' => $result['result'],
'report' => $result['result_text'],
'risk_flag' => $risk,
'createtime' => time(),
]);
return [
'id' => (int)$id,
'title' => $item['title'],
'scale' => $parsed['scale'],
'score' => $result['score'],
'max' => $result['max'],
'result' => $result['result'],
'result_text' => $result['result_text'],
'advice' => $advice,
'dims' => $result['dims'],
'risk_flag' => $risk,
'crisis' => $risk ? self::crisis() : null,
'disclaimer' => '测评结果仅供参考,不能替代专业诊断。',
];
}
/* ============================================================
* 题库解析
* ============================================================ */
public static function parseQuestions($questionsJson)
{
$data = json_decode($questionsJson, true);
if (!is_array($data)) {
return ['scale' => '', 'note' => '', 'items' => [], 'options' => self::options(), 'dims' => [], 'legacy' => false];
}
// 旧格式:["题目1","题目2",...]
if (array_keys($data) === range(0, count($data) - 1)) {
$items = [];
foreach ($data as $text) {
$items[] = ['q' => $text, 'dim' => '', 'rev' => 0];
}
return ['scale' => 'BASIC', 'note' => '', 'items' => $items, 'options' => self::options(), 'dims' => [], 'legacy' => true];
}
// 新格式
$items = [];
foreach (($data['items'] ?? []) as $row) {
$items[] = [
'q' => $row['q'] ?? '',
'dim' => $row['dim'] ?? '',
'rev' => (int)($row['rev'] ?? 0),
];
}
$options = $data['options'] ?? self::options();
$options = array_map(function ($opt) {
return ['text' => $opt['text'], 'value' => (int)$opt['value']];
}, $options);
return [
'scale' => $data['scale'] ?? 'BASIC',
'note' => $data['note'] ?? '',
'items' => $items,
'options' => $options,
'dims' => $data['dims'] ?? [],
'legacy' => false,
];
}
@@ -96,38 +233,136 @@ class AssessmentService
];
}
/**
* 提交作答
*
* @param int $userId
* @param int $assessmentId
* @param array $answers 与题目顺序一致的 0-4 分值
* @return array
*/
public static function submit($userId, $assessmentId, $answers)
/** 是否已购买该测评 */
public static function isPaid($userId, $assessmentId)
{
$item = Db::name('assessment')->where('id', (int)$assessmentId)->where('status', 'normal')->find();
if (!$item) {
return ['error' => '量表不存在'];
return Db::name('assessment_order')
->where('user_id', $userId)
->where('assessment_id', $assessmentId)
->where('pay_status', 'paid')
->count() > 0;
}
/* ============================================================
* 计分实现
* ============================================================ */
/** 标准分类型(SDS / SAS) */
protected static function scoreStandard($parsed, $scoring, $values)
{
$min = (int)($scoring['raw_range'][0] ?? 1);
$max = (int)($scoring['raw_range'][1] ?? 4);
$raw = 0;
// 反向题位置(SDS 第 19 题为自伤念头,单独取原始值做风险判断)
$selfHarmIndex = 18;
foreach ($parsed['items'] as $i => $item) {
$v = $values[$i];
$raw += $item['rev'] ? ($min + $max - $v) : $v;
}
// 常规口径:标准分 = 粗分 × 1.25,取整数部分
$standard = (int)floor($raw * (float)($scoring['factor'] ?? 1.25));
$resultKey = 'normal';
$resultText = '';
$levels = $scoring['levels'] ?? [];
foreach ($levels as $level) {
if ($standard < (int)$level['lt']) {
$resultKey = $level['key'];
$resultText = $level['text'];
break;
}
}
if (!$resultText && $levels) {
$last = end($levels);
$resultKey = $last['key'];
$resultText = $last['text'];
}
$questions = json_decode($item['questions'], true) ?: [];
$answers = is_array($answers) ? array_values($answers) : [];
if (count($answers) !== count($questions)) {
return ['error' => '请完成全部题目'];
$risk = 0;
if (isset($values[$selfHarmIndex]) && $values[$selfHarmIndex] >= 3 && $parsed['scale'] === 'SDS') {
$risk = 1;
}
if (in_array($resultKey, ['severe'], true)) {
$risk = 1;
}
$clean = [];
$score = 0;
foreach ($answers as $value) {
$v = min(4, max(0, (int)$value));
$clean[] = $v;
$score += $v;
$advice = [$resultText, '本标准分为粗分 × 1.25,分数越高代表困扰越明显。'];
if ($parsed['scale'] === 'SDS') {
$advice[] = '建议连续记录两周情绪,并保持规律作息与日照。';
} else {
$advice[] = '可以尝试 4-7-8 呼吸与规律运动,减少咖啡因摄入。';
}
$scoring = json_decode($item['scoring'], true) ?: [];
$levels = isset($scoring['levels']) ? $scoring['levels'] : [];
$max = isset($scoring['max']) ? (int)$scoring['max'] : count($questions) * 4;
return [
'score' => $standard,
'max' => (int)floor(count($parsed['items']) * $max * (float)($scoring['factor'] ?? 1.25)),
'result' => $resultKey,
'result_text' => $resultText,
'advice' => $advice,
'dims' => [],
'risk_flag' => $risk,
];
}
/** 人格剖面类型(16PF) */
protected static function scoreProfile($parsed, $scoring, $values)
{
$maxRaw = (int)($scoring['max_raw'] ?? 6);
$raw = [];
foreach ($parsed['items'] as $i => $item) {
$dim = $item['dim'] ?: 'X';
if (!isset($raw[$dim])) {
$raw[$dim] = 0;
}
$raw[$dim] += $values[$i];
}
$dims = [];
$highest = null;
foreach (($parsed['dims'] ?: []) as $key => $meta) {
$r = $raw[$key] ?? 0;
$std = (int)round($r / max(1, $maxRaw) * 9) + 1;
$std = max(1, min(10, $std));
$level = $std >= 7 ? 'high' : ($std <= 4 ? 'low' : 'mid');
$dims[] = [
'key' => $key,
'name' => $meta['name'],
'raw' => $r,
'score' => $std,
'level' => $level,
'text' => $level === 'high' ? $meta['high'] : ($level === 'low' ? $meta['low'] : '表现居中,视情境灵活调整'),
];
if ($highest === null || $std > $highest['score']) {
$highest = ['key' => $key, 'name' => $meta['name'], 'score' => $std];
}
}
$top = array_slice(array_values(array_filter($dims, function ($d) {
return $d['level'] === 'high';
})), 0, 3);
$topNames = $top ? implode('、', array_column($top, 'name')) : ($highest ? $highest['name'] : '');
return [
'score' => $highest ? $highest['score'] : 0,
'max' => 10,
'result' => $highest ? $highest['key'] : '',
'result_text' => '最突出的特质:' . ($topNames ?: '暂无') . '。16PF 描述的是倾向而非优劣,请结合具体情境理解。',
'advice' => [
'高分维度代表你更常表现的行为倾向,低分维度代表相反倾向。',
'同一维度在不同情境下可能不同,建议结合近半年的真实经历回看。',
'如需深入解读,可提交心理咨询预约,由咨询师一对一分析。',
],
'dims' => $dims,
'risk_flag' => 0,
];
}
/** 旧格式(0-4 五级) */
protected static function scoreLegacy($parsed, $scoring, $values)
{
$score = array_sum($values);
$levels = $scoring['levels'] ?? [];
$max = (int)($scoring['max'] ?? count($parsed['items']) * 4);
$resultKey = 'low';
$resultText = '';
@@ -138,60 +373,20 @@ class AssessmentService
break;
}
}
if (!$resultText) {
if (!$resultText && $levels) {
$last = end($levels);
if ($last) {
$resultKey = $last['key'];
$resultText = $last['text'];
}
$resultKey = $last['key'];
$resultText = $last['text'];
}
// 危机识别:产后筛查最后一题(自伤念头)或总分达到满分
$risk = 0;
$crisisQ = ['pdp' => 4];
if (isset($crisisQ[$item['code']]) && isset($clean[$crisisQ[$item['code']]]) && $clean[$crisisQ[$item['code']]] >= 2) {
$risk = 1;
}
if ($score >= $max) {
$risk = 1;
}
$advice = [
'测评结果不是诊断,仅用于自我觉察。',
$resultText,
];
if ($item['code'] === 'pms') {
$advice[] = '建议连续记录 2-3 个周期的情绪与症状,观察规律。';
} elseif ($item['code'] === 'prepare_anxiety') {
$advice[] = '可以和伴侣约定每天 15 分钟「不谈备孕」的时间。';
} elseif ($item['code'] === 'relation') {
$advice[] = '试试本周安排一次不被打断的 30 分钟对话。';
} elseif ($item['code'] === 'pdp') {
$advice[] = '把感受告诉家人,让他们参与照护;必要时就医评估。';
}
$id = Db::name('assessment_record')->insertGetId([
'user_id' => $userId,
'assessment_id' => (int)$item['id'],
'answers' => json_encode($clean),
'score' => $score,
'result' => $resultKey,
'report' => $resultText,
'risk_flag' => $risk,
'createtime' => time(),
]);
return [
'id' => (int)$id,
'title' => $item['title'],
'score' => $score,
'max' => $max,
'result' => $resultKey,
'result_text' => $resultText,
'advice' => $advice,
'risk_flag' => $risk,
'crisis' => $risk ? self::crisis() : null,
'disclaimer' => '测评结果仅供参考,不能替代专业诊断。',
'advice' => ['测评结果不是诊断,仅用于自我觉察。', $resultText],
'dims' => [],
'risk_flag' => $score >= $max ? 1 : 0,
];
}
}

文件差异因一行或多行过长而隐藏

查看文件

@@ -91,11 +91,12 @@ export const api = {
// ---------- 心理服务 M9 ----------
consultIndex: () => request('/api/consult/index'),
counselors: () => request('/api/consult/counselors'),
consultCategories: () => request('/api/consult/categories', { auth: false }),
consultBooking: (data) => request('/api/consult/booking', { method: 'POST', data }),
consultBookings: () => request('/api/consult/bookings'),
consultBookingCancel: (id) => request('/api/consult/bookingCancel', { method: 'POST', data: { id } }),
consultAssessments: (scope) => request('/api/consult/assessments', { data: { scope } }),
consultOrder: (data) => request('/api/consult/orderCreate', { method: 'POST', data }),
consultOrders: () => request('/api/consult/orders'),
consultCancel: (id) => request('/api/consult/cancel', { method: 'POST', data: { id } }),
assessmentOrder: (id) => request('/api/consult/assessmentOrder', { method: 'POST', data: { id } }),
crisis: () => request('/api/consult/crisis'),
// ---------- 量表(M7/M8/M9 共用) ----------