feat(admin): 新增陪诊员入驻申请与全局角色守卫

- 新增 pages/apply 入驻申请页:填写资料、上传证件、查看审核状态
- 新增 utils/role.js 统一角色解析与管理端页面守卫
- app.js 包装 Page 构造器集中做 onShow 守卫,无身份用户重定向至申请页
- 订单、客户、档案、统计等按角色区分能力:陪诊员不请求档案接口,改用订单快照
- 订单列表支持待取消订单一键同意取消;新增订单价格由服务目录决定只读展示
This commit is contained in:
lik
2026-11-08 12:01:48 +08:00
parent bfe820aa31
commit c8bcc79865
27 changed files with 1332 additions and 206 deletions
+38
View File
@@ -2,6 +2,44 @@
import config from './config';
import createBus from './utils/eventBus';
const API = require('./utils/api.js');
const role = require('./utils/role.js');
// ==================== 全局页面守卫 ====================
// 无身份用户(role=none)只能停留在入驻申请页,其余页面在 onShow 时统一重定向。
// 包装全局 Page 构造器集中处理,避免在 10 个页面各写一遍、漏掉某个入口就绕过去了。
const ROLE_WHITELIST = ['pages/apply/index'];
let redirecting = false;
function guardPage(route) {
if (!route || ROLE_WHITELIST.indexOf(route) > -1) return;
role
.ensureRoleSafe()
.then((detail) => {
// 解析失败(用户服务抖动 / 断网)不跳转:
// 把解析失败当成"无身份"会将在职陪诊师误踢到申请页
if (!detail.ok || detail.role !== 'none') return;
if (redirecting) return;
redirecting = true;
wx.reLaunch({
url: '/pages/apply/index',
complete: () => setTimeout(() => { redirecting = false; }, 800),
});
})
.catch(() => {});
}
const rawPage = Page;
Page = function (options = {}) {
const rawOnShow = options.onShow;
options.onShow = function (...args) {
const result = rawOnShow && rawOnShow.apply(this, args);
guardPage(this.route);
return result;
};
return rawPage(options);
};
App({
onLaunch() {
+8 -7
View File
@@ -9,7 +9,8 @@
"pages/order/orderEdit",
"pages/healthprofile/index",
"pages/healthprofile/profileInfo",
"pages/me/index"
"pages/me/index",
"pages/apply/index"
],
"usingComponents": {
"t-toast": "tdesign-miniprogram/toast/toast"
@@ -21,11 +22,11 @@
"navigationBarBackgroundColor": "#ffffff",
"navigationBarTitleText": "Weixin",
"navigationBarTextStyle": "black",
"backgroundColor": "#0f1535"
"backgroundColor": "#FAF6F1"
},
"tabBar": {
"color": "#8a8a8a",
"selectedColor": "#1a8a63",
"color": "#8A8078",
"selectedColor": "#C26A2E",
"backgroundColor": "#ffffff",
"borderStyle": "black",
"list": [
@@ -33,19 +34,19 @@
"pagePath": "pages/home/index",
"text": "首页",
"iconPath": "images/home.png",
"selectedIconPath": "images/home-green.png"
"selectedIconPath": "images/home-warm.png"
},
{
"pagePath": "pages/ai/index",
"text": "AI",
"iconPath": "images/chat.png",
"selectedIconPath": "images/chat-green.png"
"selectedIconPath": "images/chat-warm.png"
},
{
"pagePath": "pages/set/index",
"text": "设置",
"iconPath": "images/set.png",
"selectedIconPath": "images/set-green.png"
"selectedIconPath": "images/set-warm.png"
}
]
},
+2 -2
View File
@@ -1,6 +1,6 @@
// components/order-stats/index.js
// 首页订单统计卡片:全部完成 / 本月完成 / 未完成
const API = require('../../utils/api.js')
const role = require('../../utils/role.js')
Component({
data: {
@@ -27,7 +27,7 @@ Component({
* 费用取 payment.totalFee 合计
*/
load() {
API.escort.getAllRecords({ page: 1, pageSize: 200 })
role.queryOrders({ page: 1, pageSize: 200 })
.then(res => {
if (res.code !== 0) return
const records = res.data.records || []
+55 -4
View File
@@ -3,10 +3,12 @@
// 第一行:姓名 + 性别(左) · 年龄(右)
// 第二行:电话(左,可选拨打) · 所在地(右)
//
// 两种用法:
// 三种用法:
// 1. 直接传展示字段(name/sexLabel/ageText/mobile/locationText),适用于列表批量渲染
// 2. 只传 profile-id,组件内部加载档案:优先读全局缓存(utils/store.js),未命中再请求
// 加载完成后触发 loaded 事件(携带档案原始文档),展示字段以加载结果为准
// 3. 传 snapshot(订单 patient 快照):档案不可读(陪诊员无权限 / 档案已删除)时兜底展示,
// 避免患者姓名电话为空
const store = require('../../utils/store.js')
const { calcAge } = require('../../utils/format.js')
@@ -19,18 +21,42 @@ Component({
locationText: { type: String, value: '' },
// 是否显示"拨打"并触发 call 事件
dial: { type: Boolean, value: false },
// 订单患者快照(escort_record.patient):档案加载失败时的兜底
snapshot: {
type: Object,
value: null,
observer(newVal) {
if (newVal) this.applySnapshot(newVal)
}
},
// 是否允许读取完整档案:陪诊员传 false,避免必然的 403 与信息越权
canLoadProfile: {
type: Boolean,
value: true
},
// 健康档案ID:传入后组件内部加载,展示字段以加载结果为准
profileId: {
type: String,
value: '',
observer(newVal) {
if (newVal) this.loadProfile(newVal)
if (!newVal) return
if (this.data.canLoadProfile) this.loadProfile(newVal)
else if (this.data.snapshot) this.applySnapshot(this.data.snapshot)
}
},
// 是否读取缓存:true 缓存优先(默认),false 直接请求最新数据(请求成功后仍回填缓存)
useCache: { type: Boolean, value: true }
},
lifetimes: {
attached() {
if (this.data.snapshot) this.applySnapshot(this.data.snapshot)
if (this.data.profileId && this.data.canLoadProfile) {
this.loadProfile(this.data.profileId)
}
}
},
methods: {
onCallTap() {
if (!this.data.mobile) return
@@ -38,9 +64,14 @@ Component({
},
/**
* 按档案ID加载:缓存优先,未命中再请求
* 按档案ID加载:缓存优先,未命中再请求;失败时回落到订单快照
*/
loadProfile(id) {
// 陪诊员没有档案读取权限:即使 observer 早于属性赋值触发也直接走快照
if (!this.data.canLoadProfile) {
this.applySnapshot(this.data.snapshot)
return
}
const cached = store.getProfile(id)
if (cached) {
this.applyProfile(cached)
@@ -49,13 +80,17 @@ Component({
const API = require('../../utils/api.js')
API.healthProfile.getProfileById(id)
.then(res => {
if (res.code !== 0 || !res.data || !res.data.profile) return
if (res.code !== 0 || !res.data || !res.data.profile) {
this.applySnapshot(this.data.snapshot)
return
}
const profile = res.data.profile
store.cacheProfile(profile)
this.applyProfile(profile)
})
.catch(err => {
console.error('获取健康档案失败', err)
this.applySnapshot(this.data.snapshot)
})
},
@@ -75,6 +110,22 @@ Component({
locationText: [loc.province, loc.city].filter(Boolean).join(' ')
})
this.triggerEvent('loaded', { profile })
},
/**
* 订单快照兜底:只在档案不可读时使用,因此不触发 loaded 事件
*/
applySnapshot(snapshot) {
const p = snapshot || {}
if (!p.name && !p.mobile) return
const age = calcAge(p.birth)
const sexLabel = p.sex === 'male' ? '男' : (p.sex === 'female' ? '女' : '')
this.setData({
name: p.name || '',
sexLabel,
ageText: age ? `${age}岁` : '',
mobile: p.mobile || ''
})
}
}
})
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.1 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

+303
View File
@@ -0,0 +1,303 @@
// pages/apply/index.js
// 陪诊师入驻申请页
//
// 无身份用户(role=none)被全局守卫拦住后落到这里;提交后进入待审核视图。
// 审核通过后本页 onShow 会强刷角色,直接切回首页,不需要用户手动重新登录。
const API = require('../../utils/api.js')
const role = require('../../utils/role.js')
const SEX_OPTIONS = [
{ value: 'female', label: '女' },
{ value: 'male', label: '男' }
]
const SEX_LABELS = SEX_OPTIONS.map((item) => item.label)
const MOBILE_REGEX = /^1[3-9]\d{9}$/
const ID_NUMBER_REGEX = /^\d{17}[\dXx]$/
// 服务端单张限 5MB,但 wx.request 请求体上限 10MB:
// base64 膨胀 4/3,两张 5MB 图 ≈ 13MB 会在发送前就失败,端上按 3MB/张收紧
const MAX_IMAGE_BYTES = 3 * 1024 * 1024
Page({
data: {
loading: true,
view: 'form', // form 填写 / pending 待审核 / approved 已通过但角色未刷新
submitting: false,
rejectReason: '',
application: null,
serviceAreaText: '',
submitTimeText: '',
accountName: '微信用户',
today: '',
sexLabels: SEX_LABELS,
sexIndex: 0,
form: {
name: '',
mobile: '',
idNumber: '',
sex: '',
serviceAreas: '',
introduction: ''
},
healthExpireDate: '',
photos: {
qualification: '',
healthCertificate: ''
}
},
onLoad() {
const now = new Date()
const pad = (n) => String(n).padStart(2, '0')
this.setData({ today: `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}` })
},
onShow() {
this.refresh()
},
/**
* 先确认身份,再决定展示哪个视图
* force=true:审批可能刚刚通过,必须绕过角色缓存
*/
refresh() {
this.setData({ loading: true })
role
.ensureRoleSafe(true)
.then((detail) => {
if (detail.ok && detail.role !== 'none') {
wx.switchTab({ url: '/pages/home/index' })
return
}
this.loadApplication()
})
.catch(() => this.loadApplication())
},
loadApplication() {
const app = getApp()
const user = app && app.globalData ? app.globalData.user : null
const accountName = user && user.profile && user.profile.name ? user.profile.name : '微信用户'
API.attendantApplication
.getMine()
.then((res) => {
if (res.code !== 0) {
wx.showToast({ title: res.msg || '加载失败', icon: 'none' })
this.setData({ loading: false, accountName })
return
}
const application = res.data ? res.data.application : null
if (!application) {
this.setData({ loading: false, view: 'form', accountName })
return
}
if (application.status === 'pending') {
this.setData({
loading: false,
view: 'pending',
application,
accountName,
serviceAreaText: (application.applicant.serviceAreas || []).join('、'),
submitTimeText: this.formatTime(application.createtime)
})
return
}
if (application.status === 'approved') {
// 走到这里说明员工档案还没查到(接口抖动或数据延迟),给一个手动重试入口
this.setData({ loading: false, view: 'approved', application, accountName })
return
}
// 已驳回:回填上次填写的内容,证件照不必重复上传
const applicant = application.applicant || {}
const sexIndex = SEX_OPTIONS.findIndex((item) => item.value === applicant.sex)
this.setData({
loading: false,
view: 'form',
application,
accountName,
rejectReason: application.rejectReason || '',
sexIndex: sexIndex > -1 ? sexIndex : 0,
healthExpireDate: application.healthExpireDate || '',
form: {
name: applicant.name || '',
mobile: applicant.mobile || '',
idNumber: applicant.idNumber || '',
sex: applicant.sex || '',
serviceAreas: (applicant.serviceAreas || []).join(','),
introduction: applicant.introduction || ''
}
})
})
.catch(() => {
this.setData({ loading: false, accountName })
wx.showToast({ title: '网络错误,请重试', icon: 'none' })
})
},
formatTime(value) {
if (!value) return ''
const date = new Date(value)
if (isNaN(date.getTime())) return ''
const pad = (n) => String(n).padStart(2, '0')
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
},
onInput(e) {
const key = e.currentTarget.dataset.key
if (!key) return
this.setData({ [`form.${key}`]: e.detail.value })
},
onSexChange(e) {
const index = Number(e.detail.value)
const option = SEX_OPTIONS[index]
this.setData({ sexIndex: index, 'form.sex': option ? option.value : '' })
},
onExpireChange(e) {
this.setData({ healthExpireDate: e.detail.value })
},
pickImage(e) {
const field = e.currentTarget.dataset.field
if (!field) return
wx.chooseMedia({
count: 1,
mediaType: ['image'],
sourceType: ['album', 'camera'],
sizeType: ['compressed'],
success: (res) => {
const file = res.tempFiles && res.tempFiles[0]
if (!file) return
if (file.size && file.size > 10 * 1024 * 1024) {
wx.showToast({ title: '请选择 10MB 以内的图片', icon: 'none' })
return
}
// 先压再读:原图直传很容易把请求体顶到小程序 10MB 上限
wx.compressImage({
src: file.tempFilePath,
quality: 60,
success: (compressed) => this.readAsDataUrl(compressed.tempFilePath, field),
fail: () => this.readAsDataUrl(file.tempFilePath, field)
})
},
fail: () => {}
})
},
readAsDataUrl(path, field) {
wx.getFileSystemManager().readFile({
filePath: path,
encoding: 'base64',
success: (res) => {
const bytes = Math.floor((res.data.length * 3) / 4)
if (bytes > MAX_IMAGE_BYTES) {
wx.showToast({ title: '图片过大,请重新拍摄或裁剪到 3MB 以内', icon: 'none' })
return
}
const mime = /\.png$/i.test(path) ? 'png' : 'jpeg'
this.setData({ [`photos.${field}`]: `data:image/${mime};base64,${res.data}` })
},
fail: () => {
wx.showToast({ title: '读取图片失败', icon: 'none' })
}
})
},
submit() {
if (this.data.submitting) return
const { form, photos, healthExpireDate, application } = this.data
const name = form.name.trim()
const mobile = form.mobile.trim()
const idNumber = form.idNumber.trim().toUpperCase()
const areas = form.serviceAreas
.split(/[,,、\s]+/)
.map((item) => item.trim())
.filter(Boolean)
if (!name) return this.toast('请填写姓名')
if (!MOBILE_REGEX.test(mobile)) return this.toast('请填写正确的手机号')
if (!ID_NUMBER_REGEX.test(idNumber)) return this.toast('请填写 18 位身份证号')
if (!areas.length) return this.toast('请填写服务城市')
if (!healthExpireDate) return this.toast('请选择健康证明有效期')
// 驳回后重新提交时允许沿用上次上传的证件照
const isResubmit = !!application && application.status === 'rejected'
if (!photos.qualification && !isResubmit) return this.toast('请上传资质证书照片')
if (!photos.healthCertificate && !isResubmit) return this.toast('请上传健康证明照片')
const payload = {
applicant: {
name,
mobile,
idNumber,
sex: form.sex,
serviceAreas: areas,
introduction: form.introduction.trim()
},
healthExpireDate
}
const materials = {}
if (photos.qualification) materials.qualification = photos.qualification
if (photos.healthCertificate) materials.healthCertificate = photos.healthCertificate
if (Object.keys(materials).length) payload.materials = materials
this.setData({ submitting: true })
API.attendantApplication
.create(payload)
.then((res) => {
if (res.code === 0) {
const next = res.data ? res.data.application : null
wx.showToast({ title: '申请已提交', icon: 'success' })
this.setData({
submitting: false,
view: 'pending',
application: next,
rejectReason: '',
serviceAreaText: next ? (next.applicant.serviceAreas || []).join('、') : areas.join('、'),
submitTimeText: next ? this.formatTime(next.createtime) : ''
})
return
}
// 409 分两种:已是陪诊师 → 刷新角色直接进首页;身份证号被绑/账号冲突 → 弹窗说明,留在表单
if (res.code === 409) {
const isAttendant = res.data && res.data.isAttendant
if (isAttendant) {
wx.showToast({ title: res.msg || '你已是陪诊师', icon: 'none' })
setTimeout(() => this.refresh(), 800)
return
}
wx.showModal({
title: '无法提交',
content: res.msg || '提交失败,请联系客服',
showCancel: false
})
this.setData({ submitting: false })
return
}
wx.showToast({ title: res.msg || '提交失败', icon: 'none' })
this.setData({ submitting: false })
})
.catch(() => {
wx.showToast({ title: '网络错误,请重试', icon: 'none' })
this.setData({ submitting: false })
})
},
toast(title) {
wx.showToast({ title, icon: 'none' })
},
onRetry() {
this.refresh()
}
})
+4
View File
@@ -0,0 +1,4 @@
{
"navigationBarTitleText": "成为陪诊师",
"usingComponents": {}
}
+205
View File
@@ -0,0 +1,205 @@
<!--pages/apply/index.wxml-->
<view class="apply-page">
<view class="loading-box" wx:if="{{loading}}">
<text class="loading-text">加载中…</text>
</view>
<!-- 待审核 -->
<block wx:elif="{{view === 'pending'}}">
<view class="hero">
<view class="hero-badge">待审核</view>
<text class="hero-title">申请已提交</text>
<text class="hero-desc">审核通过后重新进入小程序即可接单。期间无需重复提交。</text>
</view>
<view class="card">
<view class="row">
<text class="row-label">申请人</text>
<text class="row-value">{{application.applicant.name}}</text>
</view>
<view class="row">
<text class="row-label">手机号</text>
<text class="row-value">{{application.applicant.mobile}}</text>
</view>
<view class="row">
<text class="row-label">服务城市</text>
<text class="row-value">{{serviceAreaText}}</text>
</view>
<view class="row">
<text class="row-label">提交时间</text>
<text class="row-value">{{submitTimeText}}</text>
</view>
</view>
<view class="foot-note">当前微信账号:{{accountName}}</view>
</block>
<!-- 审核已通过但角色还没刷新(多为瞬时接口异常) -->
<block wx:elif="{{view === 'approved'}}">
<view class="hero">
<view class="hero-badge hero-badge-ok">已通过</view>
<text class="hero-title">审核已通过</text>
<text class="hero-desc">权限正在同步,点击下方按钮重新进入。</text>
</view>
<button class="submit-btn" bindtap="onRetry">重新进入</button>
<view class="foot-note">当前微信账号:{{accountName}}</view>
</block>
<!-- 填写申请表 -->
<block wx:else>
<view class="hero">
<text class="hero-title">成为陪诊师</text>
<text class="hero-desc">提交资料并通过审核后,即可查看订单、接单并使用 AI 办公。</text>
</view>
<view class="reject-box" wx:if="{{rejectReason}}">
<text class="reject-title">上次申请未通过</text>
<text class="reject-text">原因:{{rejectReason}}</text>
<text class="reject-hint">修改后可重新提交,已上传的证件照无需重复上传。</text>
</view>
<view class="card">
<text class="card-title">基本信息</text>
<view class="field">
<text class="field-label">姓名</text>
<input
class="field-input"
value="{{form.name}}"
data-key="name"
maxlength="20"
placeholder="请输入真实姓名"
bindinput="onInput"
/>
</view>
<view class="field">
<text class="field-label">手机号</text>
<input
class="field-input"
type="number"
value="{{form.mobile}}"
data-key="mobile"
maxlength="11"
placeholder="用于审核联系"
bindinput="onInput"
/>
</view>
<view class="field">
<text class="field-label">身份证号</text>
<input
class="field-input"
value="{{form.idNumber}}"
data-key="idNumber"
maxlength="18"
placeholder="18 位身份证号"
bindinput="onInput"
/>
</view>
<view class="field">
<text class="field-label">性别</text>
<picker
class="field-picker"
mode="selector"
range="{{sexLabels}}"
value="{{sexIndex}}"
bindchange="onSexChange"
>
<view class="field-value {{form.sex ? '' : 'placeholder'}}">
{{form.sex ? sexLabels[sexIndex] : '请选择性别'}}
<text class="arrow">›</text>
</view>
</picker>
</view>
<view class="field">
<text class="field-label">服务城市</text>
<input
class="field-input"
value="{{form.serviceAreas}}"
data-key="serviceAreas"
placeholder="多个城市用逗号分隔"
bindinput="onInput"
/>
</view>
<view class="field field-block">
<text class="field-label">个人简介</text>
<textarea
class="field-textarea"
value="{{form.introduction}}"
data-key="introduction"
maxlength="200"
placeholder="介绍一下你的陪诊经验、擅长科室等"
bindinput="onInput"
/>
</view>
</view>
<view class="card">
<text class="card-title">证件材料</text>
<view class="upload-row">
<view class="upload-tile" data-field="qualification" bindtap="pickImage">
<image
wx:if="{{photos.qualification}}"
class="upload-img"
src="{{photos.qualification}}"
mode="aspectFill"
/>
<view wx:else class="upload-empty">
<text class="upload-plus">+</text>
</view>
</view>
<view class="upload-meta">
<text class="upload-name">资质证书照片</text>
<text class="upload-tip">{{photos.qualification ? '已选择,点击可重新上传' : 'JPG / PNG,单张不超过 3MB'}}</text>
</view>
</view>
<view class="upload-row">
<view class="upload-tile" data-field="healthCertificate" bindtap="pickImage">
<image
wx:if="{{photos.healthCertificate}}"
class="upload-img"
src="{{photos.healthCertificate}}"
mode="aspectFill"
/>
<view wx:else class="upload-empty">
<text class="upload-plus">+</text>
</view>
</view>
<view class="upload-meta">
<text class="upload-name">健康证明照片</text>
<text class="upload-tip">{{photos.healthCertificate ? '已选择,点击可重新上传' : 'JPG / PNG,单张不超过 3MB'}}</text>
</view>
</view>
<view class="field">
<text class="field-label">健康证有效期</text>
<picker
class="field-picker"
mode="date"
value="{{healthExpireDate}}"
start="{{today}}"
bindchange="onExpireChange"
>
<view class="field-value {{healthExpireDate ? '' : 'placeholder'}}">
{{healthExpireDate || '请选择到期日期'}}
<text class="arrow">›</text>
</view>
</picker>
</view>
</view>
<button class="submit-btn" loading="{{submitting}}" disabled="{{submitting}}" bindtap="submit">
提交申请
</button>
<view class="foot-note">
当前微信账号:{{accountName}}。如需更换账号,请在微信中切换后重新打开小程序。
</view>
</block>
</view>
+253
View File
@@ -0,0 +1,253 @@
/* pages/apply/index.wxss */
.apply-page {
min-height: 100vh;
box-sizing: border-box;
padding: 16rpx 24rpx 60rpx;
background-color: #FAF6F1;
}
.loading-box {
padding: 160rpx 0;
text-align: center;
}
.loading-text {
font-size: 26rpx;
color: #A3988B;
}
/* 顶部说明 */
.hero {
padding: 24rpx 8rpx 32rpx;
}
.hero-badge {
display: inline-block;
padding: 6rpx 20rpx;
margin-bottom: 16rpx;
border-radius: 999rpx;
background-color: #F7E4CE;
color: #A8551F;
font-size: 24rpx;
}
.hero-badge-ok {
background-color: #EAF1F8;
color: #3E6E9E;
}
.hero-title {
display: block;
font-size: 44rpx;
font-weight: 600;
color: #2A211B;
line-height: 1.35;
}
.hero-desc {
display: block;
margin-top: 12rpx;
font-size: 26rpx;
line-height: 1.6;
color: #8A8078;
}
/* 卡片 */
.card {
margin-bottom: 24rpx;
padding: 8rpx 28rpx;
border-radius: 24rpx;
background-color: #fff;
box-shadow: 0 4rpx 20rpx rgba(74, 64, 56, 0.05);
}
.card-title {
display: block;
padding: 24rpx 0 8rpx;
font-size: 28rpx;
font-weight: 600;
color: #2A211B;
}
/* 表单行 */
.field {
display: flex;
align-items: center;
min-height: 96rpx;
border-bottom: 1rpx solid #F4EFE9;
}
.field:last-child {
border-bottom: none;
}
.field-label {
width: 180rpx;
font-size: 28rpx;
color: #6F655C;
}
.field-input {
flex: 1;
font-size: 28rpx;
color: #2A211B;
}
.field-picker {
flex: 1;
}
.field-value {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 28rpx;
color: #2A211B;
}
.field-value.placeholder {
color: #C7BDB2;
}
.arrow {
margin-left: 8rpx;
color: #C7BDB2;
}
.field-block {
flex-direction: column;
align-items: flex-start;
padding: 24rpx 0;
}
.field-textarea {
width: 100%;
height: 160rpx;
margin-top: 12rpx;
font-size: 28rpx;
line-height: 1.6;
color: #2A211B;
}
/* 证件上传 */
.upload-row {
display: flex;
align-items: center;
padding: 20rpx 0;
border-bottom: 1rpx solid #F4EFE9;
}
.upload-tile {
display: flex;
align-items: center;
justify-content: center;
width: 148rpx;
height: 148rpx;
overflow: hidden;
border: 1rpx dashed #DED3C6;
border-radius: 16rpx;
background-color: #FAF6F1;
}
.upload-img {
width: 100%;
height: 100%;
}
.upload-plus {
font-size: 56rpx;
line-height: 1;
color: #C7BDB2;
}
.upload-meta {
display: flex;
flex-direction: column;
margin-left: 24rpx;
}
.upload-name {
font-size: 28rpx;
color: #2A211B;
}
.upload-tip {
margin-top: 8rpx;
font-size: 24rpx;
color: #A3988B;
}
/* 驳回提示 */
.reject-box {
margin-bottom: 24rpx;
padding: 24rpx;
border-radius: 20rpx;
background-color: #FCEEEB;
}
.reject-title {
font-size: 28rpx;
font-weight: 600;
color: #9E443A;
}
.reject-text {
display: block;
margin-top: 8rpx;
font-size: 26rpx;
line-height: 1.6;
color: #9E443A;
}
.reject-hint {
display: block;
margin-top: 8rpx;
font-size: 24rpx;
color: #C0564A;
}
/* 提交 */
.submit-btn {
height: 92rpx;
margin: 8rpx 0 24rpx;
border-radius: 48rpx;
background-color: #C26A2E;
color: #fff;
font-size: 30rpx;
line-height: 92rpx;
}
.submit-btn::after {
border: none;
}
.foot-note {
padding: 0 16rpx;
text-align: center;
font-size: 24rpx;
line-height: 1.6;
color: #A3988B;
}
/* 待审核信息行 */
.row {
display: flex;
justify-content: space-between;
padding: 26rpx 0;
border-bottom: 1rpx solid #F4EFE9;
font-size: 28rpx;
}
.row:last-child {
border-bottom: none;
}
.row-label {
color: #8A8078;
}
.row-value {
max-width: 440rpx;
text-align: right;
color: #2A211B;
}
+6 -1
View File
@@ -1,5 +1,6 @@
// pages/customer/index.js
const API = require('../../utils/api.js')
const role = require('../../utils/role.js')
// 性别映射
const SEX_MAP = {
@@ -32,11 +33,15 @@ Page({
},
onLoad(options) {
this.loadCustomerList();
// 客户管理仅管理员可用
role.guardAdminPage().then(ok => {
if (ok) this.loadCustomerList()
})
},
onShow() {
// 页面显示时如果已有数据则刷新
if (role.getRoleSync() !== 'admin') return
if (this.data.customerList.length > 0) {
this.refreshData();
}
+7 -1
View File
@@ -1,6 +1,7 @@
// pages/healthprofile/index.js
const API = require('../../utils/api.js')
const { calcAge } = require('../../utils/format.js')
const role = require('../../utils/role.js')
Page({
data: {
@@ -15,10 +16,15 @@ Page({
},
onLoad() {
this.loadData()
// 档案管理仅管理员可用,陪诊员从订单快照查看联系人
role.guardAdminPage().then(ok => {
if (ok) this.loadData()
})
},
onShow() {
// 返回栈重新进入时角色已缓存,非管理员直接跳过请求
if (role.getRoleSync() !== 'admin') return
this.loadData()
},
+17 -11
View File
@@ -1,6 +1,7 @@
// pages/healthprofile/profileInfo.js
const API = require('../../utils/api.js')
const store = require('../../utils/store.js')
const role = require('../../utils/role.js')
const SEX_MAP = [
{ label: '男', value: 'male' },
@@ -41,20 +42,25 @@ Page({
},
onLoad(options) {
const now = new Date()
const today = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
this.setData({ today })
if (options && options.id) {
this.setData({ isEdit: true, profileId: options.id })
wx.setNavigationBarTitle({ title: '档案详情' })
this.loadProfile(options.id)
} else {
wx.setNavigationBarTitle({ title: '新建档案' })
}
// 档案读写仅管理员可用
role.guardAdminPage().then(ok => {
if (!ok) return
const now = new Date()
const today = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
this.setData({ today })
if (options && options.id) {
this.setData({ isEdit: true, profileId: options.id })
wx.setNavigationBarTitle({ title: '档案详情' })
this.loadProfile(options.id)
} else {
wx.setNavigationBarTitle({ title: '新建档案' })
}
})
},
onShow() {
// 从订单页返回后刷新关联订单列表
if (role.getRoleSync() !== 'admin') return
if (this.data.isEdit && this.data.profileId) {
this.loadProfileOrders(this.data.profileId)
}
@@ -248,7 +254,7 @@ Page({
wx.showModal({
title: '删除确认',
content: '确定要删除该健康档案吗?删除后不可恢复。',
confirmColor: '#ff4d4f',
confirmColor: '#C0564A',
success: res => {
if (!res.confirm) return
API.healthProfile.deleteProfile(profileId)
+44 -20
View File
@@ -1,5 +1,5 @@
// pages/home/index.js
const API = require('../../utils/api.js')
const role = require('../../utils/role.js')
// 取消与 status 解耦:展示状态优先取 cancelStatus
function resolveDisplayStatus(order) {
@@ -9,22 +9,33 @@ function resolveDisplayStatus(order) {
return order?.status || 'pending'
}
// 快捷入口:type=quick 为快捷操作(琥珀浅色系),type=function 为功能入口(暖铜主色系),分行显示。
// 管理员与陪诊员共用同一套入口配置,但陪诊员不展示档案/客户等管理员能力
const ADMIN_ENTRIES = [
{ type: 'quick', icon: 'add-circle', name: '增加预约', url: '/pages/order/orderEdit', color: '#E8A96B' },
{ type: 'quick', icon: 'file-add', name: '增加档案', url: '/pages/healthprofile/profileInfo', color: '#E8A96B' },
{ type: 'quick', icon: 'lightbulb-circle-filled', name: 'AI办公', url: '/pages/ai/index', isTab: true, color: '#E8A96B' },
{ type: 'function', icon: 'bill', name: '预约订单', url: '/pages/order/index', color: '#C26A2E' },
{ type: 'function', icon: 'heart', name: '健康档案', url: '/pages/healthprofile/index', color: '#C26A2E' },
{ type: 'function', icon: 'user', name: '注册用户', url: '/pages/customer/index', color: '#C26A2E' },
{ type: 'function', icon: 'user-circle', name: '个人信息', url: '/pages/me/index', color: '#C26A2E' }
]
const ATTENDANT_ENTRIES = [
{ type: 'quick', icon: 'lightbulb-circle-filled', name: 'AI办公', url: '/pages/ai/index', isTab: true, color: '#E8A96B' },
{ type: 'function', icon: 'bill', name: '预约订单', url: '/pages/order/index', color: '#C26A2E' },
{ type: 'function', icon: 'user-circle', name: '个人信息', url: '/pages/me/index', color: '#C26A2E' }
]
Page({
data: {
today: '',
greeting: '',
todayText: '',
recentOrders: [],
// 快捷入口:type=quick 为快捷操作(橙色系),type=function 为功能入口(绿色系),分行显示
quickEntries: [
{ type: 'quick', icon: 'add-circle', name: '增加预约', url: '/pages/order/orderEdit', color: '#ff8f4d' },
{ type: 'quick', icon: 'file-add', name: '增加档案', url: '/pages/healthprofile/profileInfo', color: '#ff8f4d' },
{ type: 'quick', icon: 'lightbulb-circle-filled', name: 'AI办公', url: '/pages/ai/index', isTab: true, color: '#ff8f4d' },
{ type: 'function', icon: 'bill', name: '预约订单', url: '/pages/order/index', color: '#1abc9c' },
{ type: 'function', icon: 'heart', name: '健康档案', url: '/pages/healthprofile/index', color: '#1abc9c' },
{ type: 'function', icon: 'user', name: '注册用户', url: '/pages/customer/index', color: '#1abc9c' },
{ type: 'function', icon: 'user-circle', name: '个人信息', url: '/pages/me/index', color: '#1abc9c' }
],
role: '',
isAdmin: false,
quickEntries: [],
online: true,
profile: {
name: '',
@@ -57,21 +68,34 @@ Page({
},
onLoad(options) {
this.loadUser()
const now = new Date();
const today = now.toISOString().substring(0, 10);
const hour = now.getHours();
const greeting = hour < 6 ? '夜深了' : hour < 9 ? '早上好' : hour < 12 ? '上午好' : hour < 14 ? '中午好' : hour < 18 ? '下午好' : '晚上好';
const week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][now.getDay()];
this.setData({ today, greeting, todayText: `${now.getMonth() + 1}月${now.getDate()}日 ${week}` });
this.getRecentOrders();
this.getStats();
},
onShow() {
this.loadUser()
this.getRecentOrders();
this.getStats();
this.init()
},
/**
* 先解析角色再取数:管理员看全量,陪诊员只看本人订单
*/
init() {
return role.ensureRole()
.then(r => {
this.setData({
role: r,
isAdmin: r === 'admin',
quickEntries: r === 'admin' ? ADMIN_ENTRIES : (r === 'attendant' ? ATTENDANT_ENTRIES : [])
})
this.loadUser()
this.getRecentOrders()
this.getStats()
})
.catch(() => {})
},
loadUser() {
@@ -104,8 +128,8 @@ Page({
const feeOf = (item) => Number(item.payment && item.payment.totalFee) || 0;
const [todayRes, completedRes] = await Promise.all([
API.escort.getAllRecords({ appointmentDate: todayStr }),
API.escort.getAllRecords({ status: 'completed' })
role.queryOrders({ appointmentDate: todayStr }),
role.queryOrders({ status: 'completed' })
]);
// 今日收益:当日已完成订单的费用合计
@@ -129,7 +153,7 @@ Page({
* 加载近7日订单(含6天前至今及未来订单,按预约时间倒序,最多10条)
*/
async getRecentOrders() {
const res = await API.escort.getAllRecords({ page: 1, pageSize: 50 });
const res = await role.queryOrders({ page: 1, pageSize: 50 });
if (res.code !== 0) return;
const start = new Date();
+70 -119
View File
@@ -1,15 +1,16 @@
// pages/order/index.js
const API = require('../../utils/api.js')
const { calcAge } = require('../../utils/format.js')
const role = require('../../utils/role.js')
// 状态映射配置
const STATUS_MAP = {
pending: { label: '待确认', text: '待确认', color: '#f59f00' },
confirmed: { label: '已确认', text: '已确认', color: '#1abc9c' },
cancel_requested: { label: '待取消', text: '待取消', color: '#f59f00' },
in_progress: { label: '进行中', text: '进行中', color: '#20c997' },
completed: { label: '已完成', text: '已完成', color: '#51cf66' },
cancelled: { label: '已取消', text: '已取消', color: '#ff6b6b' }
pending: { label: '待确认', text: '待确认', color: '#D98E04' },
confirmed: { label: '已确认', text: '已确认', color: '#3E6E9E' },
cancel_requested: { label: '待取消', text: '待取消', color: '#C0564A' },
in_progress: { label: '进行中', text: '进行中', color: '#C26A2E' },
completed: { label: '已完成', text: '已完成', color: '#8A7BB5' },
cancelled: { label: '已取消', text: '已取消', color: '#C0564A' }
};
// 状态筛选选项
@@ -31,12 +32,37 @@ function resolveDisplayStatus(order) {
return order?.status || 'pending'
}
// 页签 → 服务端筛选参数:筛选、分页、计数全部交给后端,避免按当前页过滤
function buildTabFilter(status) {
switch (status) {
case '':
return { includeCancelled: 1 }
case 'pending':
return { status: 'pending', cancelStatus: 'none' }
case 'cancel_requested':
return { cancelStatus: 'requested' }
case 'confirmed':
return { status: 'confirmed', cancelStatus: 'none' }
case 'in_progress':
return { status: 'in_progress', cancelStatus: 'none' }
case 'completed':
return { status: 'completed', cancelStatus: 'none' }
case 'cancelled':
return { cancelStatus: 'cancelled' }
default:
return {}
}
}
Page({
/**
* 页面的初始数据
*/
data: {
// 角色:管理员可新增预约,陪诊员只看本人订单
role: '',
isAdmin: false,
// 统计
stats: {
total: 0,
@@ -66,7 +92,11 @@ Page({
* 生命周期函数--监听页面加载
*/
onLoad(options) {
this.loadOrderList();
// 先解析角色:陪诊员走本人订单接口,管理员走全量接口
role.ensureRole().then(r => {
this.setData({ role: r, isAdmin: r === 'admin' })
this.loadOrderList();
})
},
/**
@@ -79,77 +109,23 @@ Page({
},
/**
* 计算统计数据
* 更新筛选标签计数(口径由后端聚合,避免按当前页统计)
*/
calculateStats(orders) {
const stats = {
total: orders.length,
pending: 0,
cancelRequested: 0,
confirmed: 0,
inProgress: 0,
completed: 0,
cancelled: 0
updateFilterCounts(counts) {
const c = counts || {};
const countMap = {
'': c.all,
pending: c.pending,
cancel_requested: c.cancelRequested,
confirmed: c.confirmed,
in_progress: c.inProgress,
completed: c.completed,
cancelled: c.cancelled
};
orders.forEach(order => {
switch (resolveDisplayStatus(order)) {
case 'pending':
stats.pending++;
break;
case 'cancel_requested':
stats.cancelRequested++;
break;
case 'confirmed':
stats.confirmed++;
break;
case 'in_progress':
stats.inProgress++;
break;
case 'completed':
stats.completed++;
break;
case 'cancelled':
stats.cancelled++;
break;
}
});
return stats;
},
/**
* 更新筛选标签计数
*/
updateFilterCounts(stats) {
const statusFilters = this.data.statusFilters.map(filter => {
let count = 0;
switch (filter.value) {
case '':
count = stats.total;
break;
case 'pending':
count = stats.pending;
break;
case 'cancel_requested':
count = stats.cancelRequested;
break;
case 'confirmed':
count = stats.confirmed;
break;
case 'in_progress':
count = stats.inProgress;
break;
case 'completed':
count = stats.completed;
break;
case 'cancelled':
count = stats.cancelled;
break;
}
return { ...filter, count };
});
const statusFilters = this.data.statusFilters.map(filter => ({
...filter,
count: Number(countMap[filter.value]) || 0
}));
this.setData({ statusFilters });
},
@@ -186,7 +162,7 @@ Page({
},
/**
* 加载订单列表
* 加载订单列表:筛选、分页与计数全部使用服务端口径
*/
loadOrderList(isRefresh = false) {
if (this.data.isLoading || this.data.isLoadingMore) return;
@@ -198,12 +174,10 @@ Page({
const params = {
page,
pageSize,
// 筛选在本页按展示状态完成,因此一次取回含已取消在内的全部订单
status: 'pending,confirmed,in_progress,completed',
includeCancelled: 1
...buildTabFilter(currentStatus)
};
API.escort.getAllRecords(params)
role.queryOrders(params)
.then(res => {
if (res.code !== 0) {
wx.showToast({ title: res.msg || '获取订单失败', icon: 'none' });
@@ -213,30 +187,24 @@ Page({
const data = res.data || {};
const list = data.records || [];
let total = list.length || 0;
const total = Number(data.total) || 0;
const processedOrders = this.processOrders(list);
const allOrders = isRefresh && page > 1
const orderList = isRefresh && page > 1
? [...this.data.orderList, ...processedOrders]
: processedOrders;
const stats = this.calculateStats(allOrders);
this.updateFilterCounts(stats);
const { currentStatus } = this.data;
const orderList = currentStatus
? allOrders.filter(order => order.displayStatus === currentStatus)
: allOrders;
total = orderList.length;
this.updateFilterCounts(data.counts);
this.setData({
orderList,
stats,
// 头部总数用后端「全部」口径,页签内条数仍由 currentStatus 决定
stats: { ...this.data.stats, total: Number((data.counts || {}).all) || total },
isLoading: false,
isLoadingMore: false,
isRefreshing: false,
hasMore: orderList.length < total
// total 由服务端返回,不能用当前页长度推断
hasMore: page * pageSize < total
});
})
.catch(err => {
@@ -308,9 +276,12 @@ Page({
const order = this.data.orderList.find(item => item._id === id);
if (!order) return;
const isCancelRequest = action === 'cancel' && order.displayStatus === 'cancel_requested';
const actionMap = {
confirm: { title: '确认订单', content: '确认接受此订单?', nextStatus: 'confirmed' },
cancel: { title: '取消订单', content: '确定要取消此订单?', nextStatus: 'cancelled' },
cancel: isCancelRequest
? { title: '同意取消', content: '同意取消该订单?已收款订单将进入退款流程。', nextStatus: 'cancelled' }
: { title: '取消订单', content: '确定要取消此订单?未确认且未收款的订单会被直接删除,已收款订单将进入退款。', nextStatus: 'cancelled' },
start: { title: '开始服务', content: '确认开始陪诊服务?', nextStatus: 'in_progress' },
complete: { title: '完成服务', content: '确认陪诊服务已完成?', nextStatus: 'completed' },
detail: { title: '', content: '', nextStatus: '' }
@@ -329,7 +300,7 @@ Page({
wx.showModal({
title: actionConfig.title,
content: actionConfig.content,
confirmColor: '#1abc9c',
confirmColor: '#C26A2E',
success: (res) => {
if (res.confirm) {
this.updateOrderStatus(id, actionConfig.nextStatus);
@@ -346,35 +317,15 @@ Page({
API.escort.updateStatus(id, { status: newStatus })
.then(res => {
wx.hideLoading();
if (res.code !== 0) {
wx.showToast({ title: res.msg || '操作失败', icon: 'none' });
wx.hideLoading();
return;
}
const orderList = this.data.orderList.map(order => {
if (order._id === id) {
// 取消只写 cancelStatus,status 保留取消前的服务状态
const next = newStatus === 'cancelled'
? { ...order, cancelStatus: 'cancelled', cancelledAt: new Date().toISOString() }
: { ...order, status: newStatus }
const displayStatus = resolveDisplayStatus(next)
return {
...next,
displayStatus,
statusText: STATUS_MAP[displayStatus]?.text || displayStatus,
'meta.updatetime': new Date().toISOString()
};
}
return order;
});
const stats = this.calculateStats(orderList);
this.updateFilterCounts(stats);
this.setData({ orderList, stats });
wx.hideLoading();
wx.showToast({ title: '操作成功', icon: 'success' });
// 取消可能物理删除订单,状态与计数以服务端为准,不做本地推断
this.refreshData();
})
.catch(err => {
console.error('更新订单状态失败', err);
+9 -1
View File
@@ -6,7 +6,7 @@
<text class="header-title">订单管理</text>
<text class="header-sub">共 {{stats.total}} 个订单</text>
</view>
<view class="header-add" bindtap="onAddOrder">新增预约</view>
<view class="header-add" wx:if="{{isAdmin}}" bindtap="onAddOrder">新增预约</view>
</view>
<!-- 状态筛选 -->
@@ -139,6 +139,14 @@
data-action="complete"
catchtap="onOrderAction"
>完成</view>
<!-- 待取消订单:列表内可直接同意取消 -->
<view
class="action-btn btn-solid"
wx:if="{{item.displayStatus === 'cancel_requested'}}"
data-id="{{item._id}}"
data-action="cancel"
catchtap="onOrderAction"
>同意取消</view>
</view>
</view>
</view>
+22 -11
View File
@@ -1,5 +1,6 @@
// pages/order/orderDetail.js
const API = require('../../utils/api.js')
const role = require('../../utils/role.js')
const STATUS_MAP = {
pending: '待确认',
@@ -74,6 +75,8 @@ Page({
data: {
orderId: '',
loaded: false,
// 角色:管理员可查看档案与退款操作,陪诊员只看服务必需信息
isAdmin: false,
// 订单数据
order: null,
// 格式化后的显示字段
@@ -105,9 +108,11 @@ Page({
onLoad(options) {
const id = options.id || ''
this.setData({ orderId: id })
if (id) {
this.loadOrderDetail(id)
}
// 先解析角色:详情页按角色决定是否读取档案、是否展示退款操作
role.ensureRole().then(r => {
this.setData({ isAdmin: r === 'admin' })
if (id) this.loadOrderDetail(id)
})
},
onPullDownRefresh() {
@@ -168,9 +173,11 @@ Page({
payChannelText: PAY_CHANNEL_MAP[payment.payChannel || 'offline'] || '',
// 线上退款:回调丢失时由管理端主动查退款补写终态;
// 人工核销:线下退款、或历史手工标记「线上微信」但无退款单的订单;
// 后端在存在处理中的线上退款时会拒绝,避免误把微信退款标成已完成
showQueryRefundBtn: payment.status === 'refunding' && payment.method === 'online_wechat',
showManualRefundBtn: payment.status === 'refunding',
// 后端在存在处理中的线上退款时会拒绝,避免误把微信退款标成已完成。
// 退款属管理员能力,陪诊员不展示
showQueryRefundBtn: this.data.isAdmin
&& payment.status === 'refunding' && payment.method === 'online_wechat',
showManualRefundBtn: this.data.isAdmin && payment.status === 'refunding',
queryingRefund: false,
completingRefund: false,
attendantSexText: attendant.sex === 'male' ? '男' : attendant.sex === 'female' ? '女' : '',
@@ -197,8 +204,12 @@ Page({
wx.makePhoneCall({ phoneNumber: phone })
},
// 点击患者信息,进入健康档案详情
// 点击患者信息,进入健康档案详情(仅管理员有档案权限)
onProfileTap() {
if (!this.data.isAdmin) {
wx.showToast({ title: '仅管理员可查看档案', icon: 'none' })
return
}
if (!this.data.healthProfileId) {
wx.showToast({ title: '该订单未关联健康档案', icon: 'none' })
return
@@ -220,7 +231,7 @@ Page({
wx.showModal({
title: '确认订单',
content: '确认接受此订单?',
confirmColor: '#1abc9c',
confirmColor: '#C26A2E',
success: (res) => {
if (res.confirm) {
this.updateStatus('confirmed')
@@ -234,7 +245,7 @@ Page({
wx.showModal({
title: '取消订单',
content: '确定要取消此订单?',
confirmColor: '#ff6b6b',
confirmColor: '#C0564A',
success: (res) => {
if (res.confirm) {
this.updateStatus('cancelled')
@@ -248,7 +259,7 @@ Page({
wx.showModal({
title: '开始服务',
content: '确认开始陪诊服务?',
confirmColor: '#1abc9c',
confirmColor: '#C26A2E',
success: (res) => {
if (res.confirm) {
this.updateStatus('in_progress')
@@ -262,7 +273,7 @@ Page({
wx.showModal({
title: '完成服务',
content: '确认陪诊服务已完成?',
confirmColor: '#1abc9c',
confirmColor: '#C26A2E',
success: (res) => {
if (res.confirm) {
this.updateStatus('completed')
+4 -1
View File
@@ -18,9 +18,12 @@
<view class="info-section">
<text class="section-title">患者信息</text>
<view class="info-card">
<!-- 订单必须关联健康档案:按档案ID加载(不读缓存,直接请求最新) -->
<!-- 订单必须关联健康档案:管理员按档案ID加载最新数据,
陪诊员不请求档案接口(必然 403),直接用订单 patient 快照兜底 -->
<patient-info
profile-id="{{healthProfileId}}"
snapshot="{{order.patient}}"
can-load-profile="{{isAdmin}}"
use-cache="{{false}}"
dial="{{true}}"
bind:call="callPhone"
+46 -20
View File
@@ -1,6 +1,7 @@
// pages/order/orderEdit.js
const API = require('../../utils/api.js')
const { calcAge } = require('../../utils/format.js')
const role = require('../../utils/role.js')
// 支付方式选项:与 schema 的 payment.method 枚举一一对应,空串表示未记录
const METHOD_OPTIONS = [
@@ -17,6 +18,8 @@ Page({
*/
data: {
isEdit: false,
// 角色:代客下单仅管理员可用
isAdmin: false,
form: {
hospital: { province: '', name: '', department: '', doctor: '' },
schedule: { date: '', startTime: '08:30' },
@@ -44,6 +47,10 @@ Page({
amountLocked: false,
// 已收款/退款中的订单锁定支付信息,避免把退款状态改回未支付后被重复收款
paymentLocked: false,
// 新增模式下服务价格只读展示(后端按服务目录取价)
servicePrice: '',
// 所选档案未关联客户:订单归属留空,可后期补录
profileOwnerMissing: false,
today: '',
submitting: false
},
@@ -59,7 +66,17 @@ Page({
this.setData({ today })
this.loadServices()
if (options && options.orderId) {
role.ensureRole().then(r => {
this.setData({ isAdmin: r === 'admin' })
this.enterPage(options || {})
})
},
/**
* 角色就绪后进入页面:新增仅管理员可用
*/
enterPage(options) {
if (options.orderId) {
// 编辑模式
this.orderId = options.orderId
this.setData({ isEdit: true })
@@ -68,8 +85,17 @@ Page({
return
}
if (!this.data.isAdmin) {
wx.showToast({ title: '仅管理员可新增预约', icon: 'none' })
setTimeout(() => wx.navigateBack(), 600)
return
}
// 幂等键:进入新增页生成一次,连点或弱网重试不会重复建单
this.idempotencyKey = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
wx.setNavigationBarTitle({ title: '新增预约' })
if (!options || !options.id) {
if (!options.id) {
// 未携带档案ID:弹出档案选择
this.setData({ needPickProfile: true })
this.openProfilePicker()
@@ -273,7 +299,9 @@ Page({
height: h.height || '',
weight: h.weight || '',
remark: h.remark || ''
}
},
// 档案未关联客户:订单归属留空,提示管理员后期补录
profileOwnerMissing: !this.data.isEdit && !profile.userId
})
},
@@ -363,7 +391,9 @@ Page({
if (!svc) return
this.setData({
'form.escort.serviceId': svc.id,
'form.escort.serviceName': svc.title
'form.escort.serviceName': svc.title,
// 新增订单价格以后端服务目录为准,这里只做只读展示
servicePrice: Number(svc.price) || 0
}, () => this.syncProvinces())
},
@@ -407,23 +437,21 @@ Page({
if (form.escort.serviceId === -1) return wx.showToast({ title: '请选择服务', icon: 'none' })
if (!form.schedule.date) return wx.showToast({ title: '请选择就诊日期', icon: 'none' })
const app = getApp()
const userId = app.globalData.user?._id
if (!userId) return wx.showToast({ title: '未获取到用户信息,请重新登录', icon: 'none' })
if (this.data.isEdit) {
this.updateOrder(form)
} else {
this.createOrder(form, userId)
this.createOrder(form)
}
},
/**
* 新增订单
* 归属、价格与支付状态均由后端派生:订单归属取档案 userId(无归属留空),
* 价格取服务目录,初始为未支付,因此这里不再提交 userId / payment
*/
createOrder(form, userId) {
createOrder(form) {
const payload = {
userId,
idempotencyKey: this.idempotencyKey,
healthProfileId: this.profileId || null,
patient: this.patientInfo,
hospital: {
@@ -434,19 +462,12 @@ Page({
},
schedule: {
date: form.schedule.date,
startTime: form.schedule.startTime || '',
duration: 60
startTime: form.schedule.startTime || ''
},
escort: {
serviceId: form.escort.serviceId || -1,
serviceName: form.escort.serviceName
},
payment: {
totalFee: form.payment.totalFee ? Number(form.payment.totalFee) : 0,
method: form.payment.method || '',
paidFee: 0,
status: 'unpaid'
},
notes: {
patientNote: form.notes.patientNote
},
@@ -467,8 +488,13 @@ Page({
return wx.showToast({ title: res.msg || '创建失败', icon: 'none' })
}
wx.showToast({ title: '创建成功', icon: 'success' })
const recordId = res.data && res.data.record ? res.data.record._id : ''
setTimeout(() => {
wx.navigateBack()
if (recordId) {
wx.redirectTo({ url: `/pages/order/orderDetail?id=${recordId}` })
} else {
wx.navigateBack()
}
}, 600)
})
.catch(err => {
+13 -6
View File
@@ -33,6 +33,8 @@
<text wx:if="{{profileSummary.weight}}" class="brief-tag">体重 {{profileSummary.weight}}kg</text>
</view>
<text wx:if="{{profileSummary.remark}}" class="brief-remark">备注:{{profileSummary.remark}}</text>
<!-- 档案未关联客户:订单归属留空,管理员可后期在订单编辑中补录 -->
<text wx:if="{{profileOwnerMissing}}" class="field-tip">该档案未关联客户,订单归属将留空,可后期在订单编辑中补录</text>
</view>
<view class="form">
@@ -103,20 +105,25 @@
<view class="field">
<text class="field-label">费用(元)</text>
<input class="field-input" type="digit" placeholder="请输入服务费用" value="{{form.payment.totalFee}}" data-key="payment.totalFee" bindinput="onInput" disabled="{{amountLocked}}" />
<text class="field-tip" wx:if="{{paymentLocked}}">已收款订单支付信息已锁定,退款请走取消流程</text>
<text class="field-tip" wx:elif="{{amountLocked}}">存在未支付流水,金额已锁定</text>
<!-- 新增:价格由服务目录决定,只读展示;编辑:管理员可改价 -->
<text wx:if="{{!isEdit}}" class="field-value">{{servicePrice ? servicePrice : '选择服务后自动带出'}}</text>
<block wx:else>
<input class="field-input" type="digit" placeholder="请输入服务费用" value="{{form.payment.totalFee}}" data-key="payment.totalFee" bindinput="onInput" disabled="{{amountLocked}}" />
<text class="field-tip" wx:if="{{paymentLocked}}">已收款订单支付信息已锁定,退款请走取消流程</text>
<text class="field-tip" wx:elif="{{amountLocked}}">存在未支付流水,金额已锁定</text>
</block>
</view>
<view class="field">
<!-- 支付状态与方式仅编辑时维护:新增订单固定为未支付,收款由编辑页补记 -->
<view class="field" wx:if="{{isEdit}}">
<text class="field-label">是否已支付</text>
<view class="field-switch">
<text class="switch-label {{form.payment.paid ? 'paid' : 'unpaid'}}">{{form.payment.paid ? '已支付' : '未支付'}}</text>
<switch checked="{{form.payment.paid}}" color="#17c3a5" disabled="{{paymentLocked}}" bindchange="onPaidChange" />
<switch checked="{{form.payment.paid}}" color="#C26A2E" disabled="{{paymentLocked}}" bindchange="onPaidChange" />
</view>
</view>
<view class="field">
<view class="field" wx:if="{{isEdit}}">
<text class="field-label">支付方式</text>
<picker class="field-picker" mode="selector" range="{{methodOptions}}" range-key="label" disabled="{{paymentLocked}}" bindchange="onMethodChange">
<view class="field-value">
+6 -2
View File
@@ -1,4 +1,5 @@
const API = require('../../utils/api.js')
const role = require('../../utils/role.js')
Page({
data: {
@@ -162,7 +163,7 @@ Page({
wx.showModal({
title: '退出登录',
content: '确定要退出登录吗?',
confirmColor: '#1a8a63',
confirmColor: '#C26A2E',
success: (res) => {
if (res.confirm) {
wx.showLoading({ title: '退出中...' })
@@ -182,6 +183,8 @@ Page({
doLogout() {
const app = getApp()
app.globalData.user = null
// 角色随账号失效,避免下一个登录账号沿用旧角色
role.resetRole()
wx.removeStorageSync('admin_user_info')
wx.removeStorageSync('admin_ai_session_id')
wx.removeStorageSync('admin_ai_chat_history')
@@ -199,13 +202,14 @@ Page({
wx.showModal({
title: '清除缓存',
content: '确定要清除所有缓存数据吗?',
confirmColor: '#1a8a63',
confirmColor: '#C26A2E',
success: (res) => {
if (res.confirm) {
wx.clearStorage({
success: () => {
const app = getApp()
app.globalData.user = null
role.resetRole()
this.applyUser(null)
wx.showToast({ title: '缓存已清除', icon: 'success' })
}
+14
View File
@@ -35,6 +35,20 @@ const API = {
deleteProfile: (id) => request.delete(`/health/health-profile/${id}`),
},
// 当前账号的员工档案:登录即可访问,用于判定在职陪诊员身份
employee: {
getMe: () => request.get('/health/employee/me'),
},
// 陪诊师入驻申请:提交/查询本人只要求登录,审核接口仅管理员
attendantApplication: {
create: (data) => request.post('/health/attendant-application', data),
getMine: () => request.get('/health/attendant-application/mine'),
list: (params) => request.get('/health/attendant-application', params),
getMaterials: (id) => request.get(`/health/attendant-application/${id}/materials`),
review: (id, data) => request.post(`/health/attendant-application/${id}/review`, data),
},
resource: {
getServices: (params) => request.get('/health/service', params),
getAgreement: (params) => request.get('/health/agreement', params),
+206
View File
@@ -0,0 +1,206 @@
// utils/role.js
// 管理端角色:admin(管理员)/ attendant(在职陪诊员)/ none(无可用身份)
//
// - 管理员身份按登录响应的 apps 判定,与 api/health/utils/permissions.js 同口径
// (wxapp-escort-admin / web-escort-admin 任一含 admin 即管理员)
// - 陪诊员身份以员工档案为准(GET /health/employee/me),不能用 app role 判断,
// 普通账号首次登录管理端时 user 服务会写入 role: ["user"]
const API = require('./api.js')
const ADMIN_APP_IDS = ['wxapp-escort-admin', 'web-escort-admin']
let cachedRole = null
// 缓存是否来自一次成功的解析:ensureRole 在接口异常时会把 none 写进缓存,
// 守卫不能把这种"失败"当成"确实无身份"
let cachedRoleOk = false
let pending = null
let pendingSafe = null
function rolesOf(entry) {
if (!entry) return []
if (Array.isArray(entry.roles)) return entry.roles
if (Array.isArray(entry.role)) return entry.role
return entry.role ? [entry.role] : []
}
/**
* 管理员判定:与后端 isAdmin 保持同一口径
* @param {Object} user 登录响应里的用户
* @returns {boolean}
*/
function isAdminUser(user) {
if (!user) return false
if (Array.isArray(user.apps)) {
return user.apps.some((m) =>
ADMIN_APP_IDS.indexOf(m && m.appId) > -1 &&
m.status !== 'disabled' &&
Array.isArray(m.roles) &&
m.roles.indexOf('admin') > -1
)
}
return ADMIN_APP_IDS.some((appId) => {
const entry = user.app && user.app[appId]
if (!entry) return false
if (rolesOf(entry).indexOf('admin') > -1) return true
// 历史兼容:role 缺失按管理员处理(后端同样兼容并告警)
return entry.role === undefined
})
}
function applyAppRole(role) {
try {
const app = getApp()
if (app && app.globalData) app.globalData.role = role
} catch (e) {
// 页面未初始化时忽略
}
}
/**
* 带失败标记的角色解析
*
* 与 ensureRole 的区别只在「解析不出来」时:ensureRole 把异常吞成 none,
* 页面守卫不能据此跳转,否则用户服务抖动一下就会把在职陪诊师弹到申请页。
*
* @returns {Promise<{ok: boolean, role: "admin"|"attendant"|"none"}>}
*/
async function resolveRoleDetail() {
let user = null
try {
const app = getApp()
if (app && app.ensureLogin) user = await app.ensureLogin()
else user = app && app.globalData ? app.globalData.user : null
} catch (e) {
return { ok: false, role: 'none' }
}
if (!user) return { ok: false, role: 'none' }
if (isAdminUser(user)) return { ok: true, role: 'admin' }
try {
const res = await API.employee.getMe()
if (!res || res.code !== 0) return { ok: false, role: 'none' }
const employee = res.data ? res.data.employee : null
if (employee && employee.status === 'active' && employee.role === 'attendant') {
return { ok: true, role: 'attendant' }
}
return { ok: true, role: 'none' }
} catch (e) {
// 员工接口异常:解析失败,不据此判定为无身份
return { ok: false, role: 'none' }
}
}
/**
* 解析并缓存当前角色;并发调用复用同一次请求
* @param {boolean} force 强制重新解析
* @returns {Promise<"admin"|"attendant"|"none">}
*/
function ensureRole(force) {
// cachedRoleOk=false 表示缓存来自一次失败的解析,不作为命中,下次重新解析
if (!force && cachedRole && cachedRoleOk) return Promise.resolve(cachedRole)
if (!force && pending) return pending
pending = resolveRoleDetail()
.then((detail) => {
cachedRole = detail.role
cachedRoleOk = detail.ok
applyAppRole(detail.role)
return detail.role
})
.finally(() => {
pending = null
})
return pending
}
/**
* 带失败标记的角色解析(守卫专用)
*
* 与 ensureRole 的区别:ok=false 表示「没解析出来」,调用方不能据此做跳转。
* 解析成功时同样写入缓存,后续 ensureRole 可直接复用。
*
* @param {boolean} [force] 强制重新解析
* @returns {Promise<{ok: boolean, role: "admin"|"attendant"|"none"}>}
*/
function ensureRoleSafe(force) {
if (!force && cachedRole && cachedRoleOk) return Promise.resolve({ ok: true, role: cachedRole })
if (!force && pendingSafe) return pendingSafe
pendingSafe = resolveRoleDetail()
.then((detail) => {
// 解析失败不覆盖已有缓存,守卫下一次仍有机会拿到真实身份
if (detail.ok) {
cachedRole = detail.role
cachedRoleOk = true
applyAppRole(detail.role)
}
return detail
})
.finally(() => {
pendingSafe = null
})
return pendingSafe
}
function getRoleSync() {
return cachedRole
}
/**
* 退出登录 / 清除缓存后重置,避免沿用上一个账号的角色
*/
function resetRole() {
cachedRole = null
cachedRoleOk = false
pending = null
pendingSafe = null
applyAppRole(null)
}
function emptyPage() {
return { code: 0, data: { records: [], total: 0, counts: {} }, msg: '查询成功' }
}
/**
* 按角色查询订单列表:陪诊员走 /attendant,管理员走全量列表
* @param {Object} params 查询参数
* @returns {Promise<Object>}
*/
async function queryOrders(params) {
const role = await ensureRole()
if (role === 'attendant') return API.escort.getAttendantRecords(params)
if (role === 'admin') return API.escort.getAllRecords(params)
// 无身份时不打管理接口,避免必然的 403
return emptyPage()
}
/**
* 页面级守卫:非管理员提示后返回
* @param {string} [message]
* @returns {Promise<boolean>} 是否有权限继续
*/
async function guardAdminPage(message) {
const role = await ensureRole()
if (role === 'admin') return true
wx.showToast({ title: message || '仅管理员可访问', icon: 'none' })
setTimeout(() => {
wx.navigateBack({
fail: () => wx.switchTab({ url: '/pages/home/index' })
})
}, 600)
return false
}
module.exports = {
isAdminUser,
ensureRole,
ensureRoleSafe,
getRoleSync,
resetRole,
queryOrders,
guardAdminPage
}