接通前端订单与支付链路

Co-Authored-By: Claude Sonnet 4.6 noreply@anthropic.com
This commit is contained in:
lik
2026-10-24 18:18:15 +08:00
committed by trae-solo-agent
co-authored by Claude Sonnet 4.6 noreply@anthropic.com
parent 031227710d
commit d3f399d1ad
19 changed files with 817 additions and 705 deletions
+43 -20
View File
@@ -15,34 +15,54 @@ App({
}
this.globalData.appId = appId
this.globalData.servicesReady = new Promise((resolve) => {
API.resource.getServices().then((data) => {
this.globalData.services = data.data.services
resolve(data.data.services)
}).catch((err) => {
console.error('获取服务列表失败', err)
resolve([])
})
})
this.globalData.agreementReady = new Promise((resolve) => {
API.resource.getAgreement().then((data) => {
this.globalData.agreement = data.data.agreement
resolve(data.data.agreement)
}).catch((err) => {
console.error('获取服务协议失败', err)
resolve(null)
})
})
this.loadServices()
this.loadAgreement()
this.checkUpdate();
},
onShow() {
this.silentSignin()
this.globalData.authReady = this.silentSignin()
this.initChatSocket()
},
// 启动期资源统一走 Promise;失败后清空 Promise,页面重试可重新发起请求。
loadServices() {
if (this.globalData.servicesReady) return this.globalData.servicesReady
this.globalData.servicesReady = API.resource.getServices()
.then((res) => {
if (res.code !== 0 || !Array.isArray(res.data?.services)) throw new Error(res.msg || '服务列表加载失败')
this.globalData.services = res.data.services
return this.globalData.services
})
.catch((err) => {
console.error('获取服务列表失败', err)
this.globalData.servicesReady = null
return null
})
return this.globalData.servicesReady
},
loadAgreement() {
if (this.globalData.agreementReady) return this.globalData.agreementReady
this.globalData.agreementReady = API.resource.getAgreement()
.then((res) => {
if (res.code !== 0 || !res.data?.agreement) throw new Error(res.msg || '服务协议加载失败')
this.globalData.agreement = res.data.agreement
return this.globalData.agreement
})
.catch((err) => {
console.error('获取服务协议失败', err)
this.globalData.agreementReady = null
return null
})
return this.globalData.agreementReady
},
waitForAuth() {
return this.globalData.authReady || this.silentSignin()
},
// 静默重登:app.onShow 与 request 层的 401 兜底共用这一个入口
// (wxsignin 只凭 code 换到 openid 就能签发 token,见 api/user/handler/users.js)。
//
@@ -174,6 +194,9 @@ App({
user: null,
chatSocket: null,
services: [],
servicesReady: null,
agreement: null,
agreementReady: null,
authReady: null,
}
})
+15 -51
View File
@@ -1,5 +1,3 @@
const app = getApp()
Page({
/**
@@ -7,64 +5,30 @@ Page({
*/
data: {
agreement: null,
loading: true
loading: true,
error: false
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
const agreement = app.globalData.agreement
if (agreement) {
onLoad() {
this.loadAgreement()
},
loadAgreement() {
this.setData({ loading: true, error: false })
getApp().loadAgreement().then((agreement) => {
this.setData({
agreement: agreement,
loading: false
agreement: agreement || null,
loading: false,
error: !agreement
})
})
} else {
this.setData({ loading: false })
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
retry() {
this.loadAgreement()
},
/**
+8 -2
View File
@@ -1,7 +1,13 @@
<!--pages/escort/agreement.wxml-->
<view class="container">
<view wx:if="{{loading}}" class="loading">加载中...</view>
<block wx:if="{{!loading && agreement}}">
<view wx:if="{{loading}}" class="page-state">
<text class="page-state-text">加载中...</text>
</view>
<view wx:elif="{{error}}" class="page-state">
<text class="page-state-text">协议加载失败,请重试</text>
<button class="page-retry" bindtap="retry">重新加载</button>
</view>
<block wx:elif="{{agreement}}">
<view class="header-section">
<view class="header-icon-wrap">
<t-icon name="file-1" size="48rpx" class="header-icon" />
+31
View File
@@ -14,6 +14,37 @@ page {
padding-bottom: 48rpx;
}
.page-state {
min-height: 70vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 48rpx 32rpx;
box-sizing: border-box;
}
.page-state-text {
font-size: 28rpx;
color: var(--muted);
line-height: 1.6;
}
.page-retry {
margin: 28rpx 0 0;
padding: 12rpx 36rpx;
border: 2rpx solid var(--brand-strong);
border-radius: 999rpx;
background: transparent;
color: var(--brand-strong);
font-size: 28rpx;
line-height: 1.5;
}
.page-retry::after {
border: none;
}
/* 顶部标题区:不铺卡面、直接落纸面(同首页 hero),去掉原白→暖白渐变 */
.header-section {
display: flex;
+3 -3
View File
@@ -16,7 +16,7 @@ Page({
},
{
title: '支付费用',
desc: '通过微信支付服务费用'
desc: '联系客服协助支付服务费用'
},
{
// 与 services.js id 1/2 的第 4 步同名;具体材料清单交给下方「就诊前准备」卡,不在这里重复
@@ -80,14 +80,14 @@ Page({
onShareAppMessage() {
return {
title: '暖橙陪诊 · 陪诊指南', // 转发标题
title: '暖橙陪诊 · 服务指南', // 转发标题
path: '/pages/escort/guide'
}
},
onShareTimeline() {
return {
title: '暖橙陪诊 · 陪诊指南'
title: '暖橙陪诊 · 服务指南'
}
}
})
+191 -295
View File
@@ -2,120 +2,149 @@ const API = require('../../utils/api.js')
Page({
data: {
service: {
id: null,
title: '',
subtitle: '',
price: '0.00',
image: '',
tag: '',
description: '',
flow: [],
notices: []
},
service: {},
pageLoading: true,
pageError: '',
totalPrice: '0.00',
serviceIcon: 'user-business',
showOrderPopup: false,
profiles: [], // 已保存的就诊人
selectedProfileId: '', // 必填:订单必须关联就诊人档案
patientName: '', // 只读展示,来自所选档案
patientPhone: '', // 只读展示,来自所选档案
// 选中档案的全部信息,下单时整体写入订单 patient 快照
submitting: false,
profiles: [],
selectedProfileId: '',
patientName: '',
patientPhone: '',
selectedPatient: null,
// 默认北京:取值必须与 provinces[0] 完全一致('北京市' 而非 '北京'),
// 否则 picker 的 value=0 与显示文案会对不上
province: '北京市',
province: '',
provinceIndex: 0,
provinces: ['北京市', '天津市', '河北省', '山西省', '内蒙古自治区', '辽宁省', '吉林省', '黑龙江省', '上海市', '江苏省', '浙江省', '安徽省', '福建省', '江西省', '山东省', '河南省', '湖北省', '湖南省', '广东省', '广西壮族自治区', '海南省', '重庆市', '四川省', '贵州省', '云南省', '西藏自治区', '陕西省', '甘肃省', '青海省', '宁夏回族自治区', '新疆维吾尔自治区', '台湾省', '香港特别行政区', '澳门特别行政区'],
provinces: [],
hospital: '',
appointmentDate: '',
appointmentTime: '',
minAppointmentDate: '',
fixedTime: false,
timeOptions: [],
sessionIndex: 0,
timeStart: '',
timeEnd: '',
remark: '',
today: '',
shippingAddress: '',
requiresAddress: false,
gender: '不限',
genderIndex: 0,
genderOptions: ['不限', '男', '女'],
department: '',
departments: ['内科', '外科', '妇产科', '儿科', '骨科', '神经科', '心血管内科', '消化内科', '呼吸内科', '内分泌科', '皮肤科', '眼科', '耳鼻喉科', '口腔科', '急诊科', '肿瘤科', '康复医学科', '老年病科', '中医科', '针灸推拿科'],
hospitals: []
departments: ['内科', '外科', '妇产科', '儿科', '骨科', '神经科', '心血管内科', '消化内科', '呼吸内科', '内分泌科', '皮肤科', '眼科', '耳鼻喉科', '口腔科', '急诊科', '肿瘤科', '康复医学科', '老年病科', '中医科', '针灸推拿科']
},
onLoad(options) {
const today = new Date()
const year = today.getFullYear()
const month = String(today.getMonth() + 1).padStart(2, '0')
const day = String(today.getDate()).padStart(2, '0')
const todayStr = `${year}-${month}-${day}`
this.serviceId = Number(options.id)
this.openBookAfterLoad = options.book === '1'
if (!Number.isInteger(this.serviceId) || this.serviceId <= 0) {
this.setData({ pageLoading: false, pageError: '服务不存在或已下架' })
return
}
this.initializePage()
},
onShow() {
if (this.data.showOrderPopup) this.loadProfiles()
},
async initializePage() {
this.setData({ pageLoading: true, pageError: '' })
const services = await getApp().loadServices()
if (!services) {
this.setData({ pageLoading: false, pageError: '服务加载失败,请重试' })
return
}
const service = services.find((item) => item.id === this.serviceId)
if (!service) {
this.setData({ pageLoading: false, pageError: '服务不存在或已下架' })
return
}
this.applyBookingConfig(service)
this.setData({
today: todayStr
service,
serviceIcon: this.getServiceIcon(service.title),
totalPrice: service.price,
pageLoading: false
})
const serviceId = parseInt(options.id) || 1
this.loadServiceDetail(serviceId)
// 从列表页的「预约」进来(?book=1)时,直接把预约单弹出来;
// 未登录会由 openOrderPopup 拦下并提示登录
if (options.book === '1') {
wx.setNavigationBarTitle({ title: service.title || '服务详情' })
if (this.openBookAfterLoad) {
this.openBookAfterLoad = false
this.openOrderPopup()
}
},
onShow() {
// 从"新增就诊人"页面返回时,弹窗还开着就刷新一次可选的就诊人
if (this.data.showOrderPopup) {
this.loadProfiles()
}
retryLoad() {
this.initializePage()
},
loadServiceDetail(id) {
const app = getApp()
let service = null
for (const item of app.globalData.services) {
if (item.id === id) {
service = item
break
applyBookingConfig(service) {
const booking = service.booking || {}
const sessions = booking.sessions || []
const fixedTime = sessions.length > 0 && sessions.every((item) => !item.flexible)
const firstSession = sessions[0] || {}
const minDate = new Date()
minDate.setDate(minDate.getDate() + Number(booking.advanceDays || 0))
const minAppointmentDate = `${minDate.getFullYear()}-${String(minDate.getMonth() + 1).padStart(2, '0')}-${String(minDate.getDate()).padStart(2, '0')}`
let timeEnd = firstSession.end || ''
if (!fixedTime && firstSession.end && booking.durationMinutes) {
const [hour, minute] = firstSession.end.split(':').map(Number)
const latest = hour * 60 + minute - booking.durationMinutes
timeEnd = `${String(Math.floor(latest / 60)).padStart(2, '0')}:${String(latest % 60).padStart(2, '0')}`
}
}
if (!service) {
return
}
const totalPrice = this.calculateTotal(service.price, 1)
const provinces = service.areas || []
this.setData({
service: service,
serviceIcon: this.getServiceIcon(service.title),
totalPrice: totalPrice
minAppointmentDate,
fixedTime,
timeOptions: sessions.map((item) => `${item.start} - ${item.end}`),
sessionIndex: 0,
timeStart: firstSession.start || '',
timeEnd,
provinces,
province: provinces[0] || '',
provinceIndex: 0,
requiresAddress: !!booking.requiresAddress
})
},
// 弹窗服务标记:原占位图是全服务共用的一张白色线稿,落在浅橙面板上看不见,
// 改用暖橙 t-icon(名称均已核对 tdesign 图标表,写错不报错只会渲染为空)。
// 图标按服务名选:夜间→月亮,陪诊→时钟,其余(取报告/代取药品等代办)→人像
getServiceIcon(title) {
if (title.indexOf('夜间') > -1) {
return 'moon'
}
if (title.indexOf('陪诊') > -1) {
return 'time'
}
if (title.includes('夜间')) return 'moon'
if (title.includes('陪诊')) return 'time'
return 'user-business'
},
calculateTotal(price) {
return price
async ensureLogin() {
const app = getApp()
await app.waitForAuth()
if (app.globalData.user?._id) return true
const modal = await new Promise((resolve) => {
wx.showModal({
title: '登录后预约',
content: '登录成功后将返回当前服务并继续预约',
confirmText: '登录并继续',
confirmColor: '#B8520A',
success: resolve,
fail: () => resolve({ confirm: false })
})
})
if (!modal.confirm) return null
// 用户明确点击登录时,解除主动退出对静默登录的限制。
wx.removeStorageSync('has_logout')
return app.silentSignin()
},
openOrderPopup() {
const app = getApp()
if (!app.globalData.user) {
wx.showToast({
title: '请先登录',
icon: 'none'
})
async openOrderPopup() {
if (!this.data.service.id || this.data.submitting) return
const loggedIn = await this.ensureLogin()
if (loggedIn === null) return
if (!loggedIn || !getApp().globalData.user?._id) {
wx.showToast({ title: '登录失败,请重试', icon: 'none' })
return
}
// 订单必须关联健康档案,就诊人不再手输:打开弹窗时清空,等用户选择就诊人后带入
this.idempotencyKey = `order_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`
this.setData({
patientName: '',
patientPhone: '',
@@ -123,315 +152,182 @@ Page({
selectedPatient: null,
showOrderPopup: true
})
this.loadProfiles()
},
// 读取已保存的就诊人,供弹窗内一键选择
loadProfiles() {
API.healthProfile.getMyProfiles({
page: 1,
pageSize: 20
})
return API.healthProfile.getMyProfiles({ page: 1, pageSize: 50 })
.then((res) => {
if (res.code !== 0) {
return
}
// 档案是 profile + health 两层嵌套,这里拍平成选人后可直接带入的字段
const list = ((res.data && res.data.list) || []).map((item) => {
const profile = item.profile || {}
const health = item.health || {}
return {
if (res.code !== 0) throw new Error(res.msg || '就诊人加载失败')
const profiles = (res.data?.list || []).map((item) => ({
_id: item._id,
name: profile.name || '',
mobile: profile.mobile || '',
sex: profile.sex || '',
birth: profile.birth || '',
weight: health.weight || 0,
height: health.height || 0,
idnumber: profile.idnumber || ''
}
})
this.setData({
profiles: list
})
name: item.profile?.name || '',
mobile: item.profile?.mobile || '',
sex: item.profile?.sex || '',
birth: item.profile?.birth || ''
}))
this.setData({ profiles })
})
.catch((err) => {
console.log('获取就诊人列表失败', err)
wx.showToast({ title: '就诊人加载失败,请重试', icon: 'none' })
})
},
// 选择就诊人:姓名/电话回填展示,其余字段存入 selectedPatient 供下单使用
onSelectProfile(e) {
const id = e.currentTarget.dataset.id
const profile = this.data.profiles.find((item) => item._id === id)
if (!profile) {
return
}
if (!profile) return
this.setData({
selectedProfileId: id,
// patientName / patientPhone 只用于弹窗内只读展示
patientName: profile.name,
patientPhone: profile.mobile,
// 订单 patient 快照的唯一来源:所选档案的名单字段(体征与证件号不进快照)
selectedPatient: {
name: profile.name,
mobile: profile.mobile,
sex: profile.sex,
birth: profile.birth
}
selectedPatient: profile
})
},
// 跳转到就诊人页新增
goToAddProfile() {
wx.navigateTo({
url: '/pages/health/profileedit'
})
wx.navigateTo({ url: '/pages/health/profileedit' })
},
closeOrderPopup() {
this.setData({
showOrderPopup: false
})
if (!this.data.submitting) this.setData({ showOrderPopup: false })
},
onProvinceChange(e) {
const index = e.detail.value
const province = this.data.provinces[index]
this.setData({
provinceIndex: index,
province: province
})
const index = Number(e.detail.value)
this.setData({ provinceIndex: index, province: this.data.provinces[index] })
},
onHospitalChange(e) {
this.setData({
hospital: e.detail.value
})
this.setData({ hospital: e.detail.value })
},
onDepartmentChange(e) {
this.setData({
department: e.detail.value
})
this.setData({ department: e.detail.value })
},
onDateChange(e) {
this.setData({
appointmentDate: e.detail.value
})
this.setData({ appointmentDate: e.detail.value })
},
onTimeChange(e) {
this.setData({
appointmentTime: e.detail.value
})
if (this.data.fixedTime) {
const index = Number(e.detail.value)
const session = this.data.service.booking.sessions[index]
this.setData({ sessionIndex: index, appointmentTime: session.start })
return
}
this.setData({ appointmentTime: e.detail.value })
},
onGenderChange(e) {
const index = e.detail.value
const gender = this.data.genderOptions[index]
this.setData({
genderIndex: index,
gender: gender
})
const index = Number(e.detail.value)
this.setData({ genderIndex: index, gender: this.data.genderOptions[index] })
},
onRemarkChange(e) {
this.setData({
remark: e.detail.value
})
this.setData({ remark: e.detail.value })
},
onShippingAddressChange(e) {
this.setData({ shippingAddress: e.detail.value })
},
validateOrder() {
const data = this.data
if (!data.selectedProfileId || !data.selectedPatient) return '请选择就诊人'
if (!data.hospital.trim()) return '请输入就诊医院'
if (!data.department.trim()) return '请输入就诊科室'
if (!data.appointmentDate) return '请选择预约日期'
if (!data.appointmentTime) return '请选择预约时间'
if (data.requiresAddress && !data.shippingAddress.trim()) return '请填写完整收货地址'
if (!/^1[3-9]\d{9}$/.test(data.selectedPatient.mobile.trim())) {
return '就诊人手机号有误,请到就诊人档案修改'
}
return ''
},
submitOrder() {
const {
service,
selectedProfileId,
selectedPatient,
province,
hospital,
department,
appointmentDate,
appointmentTime,
gender,
remark
} = this.data
// 订单必须关联就诊人:没有档案就没有 patient 快照,不允许下单
if (!selectedProfileId || !selectedPatient) {
wx.showToast({
title: '请选择就诊人',
icon: 'none'
})
return
}
if (!hospital.trim()) {
wx.showToast({
title: '请输入就诊医院',
icon: 'none'
})
return
}
if (!department.trim()) {
wx.showToast({
title: '请输入就诊科室',
icon: 'none'
})
return
}
if (!appointmentDate) {
wx.showToast({
title: '请选择预约日期',
icon: 'none'
})
return
}
if (!appointmentTime) {
wx.showToast({
title: '请选择预约时间',
icon: 'none'
})
if (this.data.submitting) return
const error = this.validateOrder()
if (error) {
wx.showToast({ title: error, icon: 'none' })
return
}
const phoneRegex = /^1[3-9]\d{9}$/
if (!phoneRegex.test(selectedPatient.mobile.trim())) {
wx.showToast({
title: '就诊人手机号有误,请到就诊人档案修改',
icon: 'none'
})
return
}
const app = getApp()
const user = app.globalData.user
let sex = "none"
if (gender == '男') sex = 'male'
else if (gender == '女') sex = 'female'
// 就诊人快照只取名单字段(schema 口径:name/mobile/sex/birth);
// sex 是 male/female 枚举,空值不写该字段
const patient = {
name: selectedPatient.name.trim(),
mobile: selectedPatient.mobile.trim(),
birth: selectedPatient.birth || ''
}
if (selectedPatient.sex) {
patient.sex = selectedPatient.sex
}
const data = this.data
const sexMap = { 男: 'male', 女: 'female' }
const orderData = {
userId: user._id,
// 订单与就诊人档案的关联,必填(patient 只是下单当刻的快照)
healthProfileId: selectedProfileId,
patient: patient,
idempotencyKey: this.idempotencyKey,
healthProfileId: data.selectedProfileId,
escort: {
serviceId: service.id,
serviceName: service.title,
sexRequirement: sex
serviceId: data.service.id,
sexRequirement: sexMap[data.gender] || 'none'
},
hospital: {
province: province,
name: hospital.trim(),
department: department.trim(),
province: data.province,
name: data.hospital.trim(),
department: data.department.trim()
},
schedule: {
date: appointmentDate,
startTime: appointmentTime
date: data.appointmentDate,
startTime: data.appointmentTime
},
payment: {
totalFee: service.price
},
notes: {
patientNote: remark.trim()
}
shippingAddress: { address: data.shippingAddress.trim() },
notes: { patientNote: data.remark.trim() }
}
wx.showLoading({
title: '提交中...'
})
// 同步锁定按钮;网络重试沿用同一幂等键,服务端只创建一笔订单。
this.setData({ submitting: true })
API.escort.createRecord(orderData)
.then((data) => {
wx.hideLoading()
if (data.code === 0) {
wx.showToast({
title: '下单成功',
icon: 'success'
})
this.setData({
showOrderPopup: false
})
.then((res) => {
if (res.code !== 0) throw new Error(res.msg || '下单失败')
wx.showToast({ title: '下单成功', icon: 'success' })
this.setData({ showOrderPopup: false })
this.resetForm()
// 下单成功回到记录页,直接落到「进行中的」:新单是待确认,属未完成档
wx.navigateTo({url: '/pages/escort/recordlist?tab=ongoing'})
} else {
wx.showToast({
title: data.msg || '下单失败',
icon: 'none'
})
}
wx.navigateTo({ url: '/pages/escort/recordlist?tab=ongoing' })
})
.catch((err) => {
wx.hideLoading()
wx.showToast({
title: '网络请求失败',
icon: 'none'
})
console.log('下单失败', err)
wx.showToast({ title: err.message || '网络请求失败,请重试', icon: 'none' })
})
.finally(() => this.setData({ submitting: false }))
},
resetForm() {
const provinces = this.data.provinces
this.setData({
selectedProfileId: '',
patientName: '',
patientPhone: '',
selectedPatient: null,
// 重置后仍回到默认北京,与 data 初值保持一致
province: '北京市',
province: provinces[0] || '',
provinceIndex: 0,
hospital: '',
department: '',
appointmentDate: '',
appointmentTime: '',
// 重置后回到默认「不限」,与 data 初值(gender: '不限' / genderIndex: 0)保持一致
sessionIndex: 0,
gender: '不限',
genderIndex: 0,
remark: ''
})
const totalPrice = this.calculateTotal(this.data.service.price)
this.setData({
totalPrice: totalPrice
remark: '',
shippingAddress: ''
})
this.idempotencyKey = ''
},
onShareAppMessage() {
const {
service
} = this.data
const service = this.data.service
return {
title: `${service.title} - 专业陪诊服务`,
path: `/pages/escort/itemdetail?id=${service.id}`
title: service.id ? `${service.title} - 专业陪诊服务` : '暖橙陪诊 · 专业陪诊服务',
path: service.id ? `/pages/escort/itemdetail?id=${service.id}` : '/pages/home/index'
}
},
// 朋友圈只能分享当前页,服务 id 只能靠 query 带上;
// 服务未加载完(service.id 为 null)时不带 query,落到默认项,避免拼出 id=null
onShareTimeline() {
const {
service
} = this.data
if (!service.id) {
return {
title: '暖橙陪诊 · 专业陪诊服务'
}
}
return {
title: `${service.title} - 专业陪诊服务`,
query: `id=${service.id}`
}
const service = this.data.service
if (!service.id) return { title: '暖橙陪诊 · 专业陪诊服务' }
return { title: `${service.title} - 专业陪诊服务`, query: `id=${service.id}` }
}
})
+21 -4
View File
@@ -1,5 +1,5 @@
<view class="page-bg">
<view class="container">
<view class="container" wx:if="{{service.id}}">
<!-- 头部:短横色标 + 深墨标题。原顶部 420rpx 大图已去掉:
服务图在多条服务间复用同一张占位图,既分不出是哪项服务,又白占掉大半首屏 -->
@@ -161,7 +161,7 @@
<!-- 预约日期 -->
<view class="order-row">
<text class="order-label">预约日期</text>
<picker class="order-picker" mode="date" value="{{appointmentDate}}" start="{{today}}" bindchange="onDateChange">
<picker class="order-picker" mode="date" value="{{appointmentDate}}" start="{{minAppointmentDate}}" bindchange="onDateChange">
<view class="picker-value {{appointmentDate ? '' : 'placeholder'}}">
{{appointmentDate || '请选择预约日期'}}
</view>
@@ -171,13 +171,25 @@
<!-- 预约时间 -->
<view class="order-row">
<text class="order-label">预约时间</text>
<picker class="order-picker" mode="time" value="{{appointmentTime}}" start="08:00" end="18:00" bindchange="onTimeChange">
<picker wx:if="{{fixedTime}}" class="order-picker" mode="selector" range="{{timeOptions}}" value="{{sessionIndex}}" bindchange="onTimeChange">
<view class="picker-value {{appointmentTime ? '' : 'placeholder'}}">
{{appointmentTime ? timeOptions[sessionIndex] : '请选择服务班次'}}
</view>
</picker>
<picker wx:else class="order-picker" mode="time" value="{{appointmentTime}}" start="{{timeStart}}" end="{{timeEnd}}" bindchange="onTimeChange">
<view class="picker-value {{appointmentTime ? '' : 'placeholder'}}">
{{appointmentTime || '请选择预约时间'}}
</view>
</picker>
</view>
<!-- 收货地址仅对快递/跑腿服务展示,随订单保存快照 -->
<view class="order-row column" wx:if="{{requiresAddress}}">
<text class="order-label">收货地址</text>
<textarea class="order-textarea" value="{{shippingAddress}}" placeholder="请输入省市区、街道门牌等完整收货地址" maxlength="200" placeholder-class="input-placeholder" bindinput="onShippingAddressChange" />
<text class="address-tip">收货人与联系电话使用所选就诊人信息</text>
</view>
<!-- 备注 -->
<view class="order-row column">
<text class="order-label">备注说明</text>
@@ -192,9 +204,14 @@
<text class="price-sym">¥</text>
<text class="popup-price-value">{{ totalPrice }}</text>
</view>
<button class="popup-submit-btn" bindtap="submitOrder">提交预约</button>
<button class="popup-submit-btn" bindtap="submitOrder" disabled="{{submitting}}" loading="{{submitting}}">{{submitting ? '提交中' : '提交预约'}}</button>
</view>
</view>
</view>
<view class="page-state" wx:if="{{pageLoading}}"><t-loading theme="circular" size="40rpx" text="加载中..." /></view>
<view class="page-state" wx:if="{{!pageLoading && pageError}}">
<text class="page-state-text">{{pageError}}</text>
<button class="page-retry" bindtap="retryLoad">重新加载</button>
</view>
</view>
+41
View File
@@ -34,6 +34,39 @@ page {
padding: 0 32rpx calc(40rpx + env(safe-area-inset-bottom));
}
/* 整页加载与失败状态:避免服务未就绪时闪现空内容 */
.page-state {
min-height: 70vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 48rpx 32rpx;
box-sizing: border-box;
}
.page-state-text {
font-size: 28rpx;
color: var(--muted);
line-height: 1.6;
}
.page-retry {
margin: 28rpx 0 0;
padding: 12rpx 36rpx;
border: 2rpx solid var(--brand-strong);
border-radius: 999rpx;
background: transparent;
color: var(--brand-strong);
font-size: 28rpx;
font-weight: 500;
line-height: 1.5;
}
.page-retry::after {
border: none;
}
/* ===== 头部:短横色标 + 深墨标题 ===== */
.page-header {
padding: 32rpx 0 0;
@@ -524,6 +557,14 @@ page {
color: var(--muted);
}
.address-tip {
align-self: flex-start;
margin-top: 10rpx;
font-size: 24rpx;
color: var(--muted);
line-height: 1.6;
}
/* ===== 就诊人选择 ===== */
.patient-scroll {
width: 100%;
+107 -77
View File
@@ -20,6 +20,7 @@ const PAYMENT_STATUS_MAP = {
unpaid: { text: '未支付', color: '#B8520A', bg: '#FFF4E8', border: '#FFE0C2', hint: '请联系客服完成支付' },
partial: { text: '部分支付', color: '#B8520A', bg: '#FFF4E8', border: '#FFE0C2', hint: '请联系客服补齐剩余费用' },
paid: { text: '已支付', color: '#1F7A4D', bg: '#EAF6EE', border: '#CDE9D7' },
refunding: { text: '退款中', color: '#B8520A', bg: '#FFF4E8', border: '#FFE0C2', hint: '退款处理中,如需了解进度请联系客服' },
refunded: { text: '已退款', color: '#6F655C', bg: 'transparent', border: '#E5DACC' }
}
@@ -40,12 +41,20 @@ Page({
data: {
recordId: '',
record: {},
service: null,
loading: false,
loadError: '',
// 编辑全部收进底部弹窗:页面只读,表单只活在弹窗里,两个弹窗各自一个开关
showNotePopup: false,
editPatientNote: '',
// 医院预约信息编辑弹窗:省份列表与下单页(itemdetail.js)保持同一份口径
// 医院预约规则与下单页一致,均由订单关联的服务目录下发
showHospitalPopup: false,
provinces: ['北京市', '天津市', '河北省', '山西省', '内蒙古自治区', '辽宁省', '吉林省', '黑龙江省', '上海市', '江苏省', '浙江省', '安徽省', '福建省', '江西省', '山东省', '河南省', '湖北省', '湖南省', '广东省', '广西壮族自治区', '海南省', '重庆市', '四川省', '贵州省', '云南省', '西藏自治区', '陕西省', '甘肃省', '青海省', '宁夏回族自治区', '新疆维吾尔自治区', '台湾省', '香港特别行政区', '澳门特别行政区'],
provinces: [],
minAppointmentDate: '',
fixedTime: false,
timeOptions: [],
timeStart: '',
timeEnd: '',
editHospital: {},
showCancelPopup: false,
cancelReason: '',
@@ -83,23 +92,60 @@ Page({
}
},
// 渲染到位判据是 record._id(WXML 用它守内容),本方法只负责取数
loadRecord(id) {
return API.escort.getRecordById(id)
.then((res) => {
if (res.code === 0 && res.data) {
const record = this.formatRecord(res.data.record)
this.setData({ record })
// 订单关联了健康档案时,就诊人信息以档案最新数据为准
if (record.healthProfileId) {
this.loadProfileSnapshot(record.healthProfileId)
async loadRecord(id) {
this.setData({ loading: true, loadError: '' })
try {
const app = getApp()
await app.waitForAuth()
if (!app.globalData.user?._id) throw new Error('请先登录后查看订单')
const [res, services] = await Promise.all([
API.escort.getRecordById(id),
app.loadServices()
])
if (res.code !== 0 || !res.data?.record) throw new Error(res.msg || '订单加载失败')
if (!services) throw new Error('服务规则加载失败,请重试')
const item = res.data.record
const service = services.find(entry => entry.id === item.escort?.serviceId) || null
const record = this.formatRecord(item)
// 服务已下架时仍可查看历史订单,但不能再按失效规则修改订单。
if (!service) record.canEditOrder = false
this.setData({ record, service })
if (service) this.applyBookingConfig(service)
if (record.healthProfileId) this.loadProfileSnapshot(record.healthProfileId)
} catch (err) {
this.setData({ record: {}, loadError: err.message || '网络请求失败,请重试' })
} finally {
this.setData({ loading: false })
}
} else {
wx.showToast({ title: res.msg || '加载失败', icon: 'none' })
},
retryLoad() {
if (this.data.recordId) this.loadRecord(this.data.recordId)
},
applyBookingConfig(service) {
const booking = service.booking || {}
const sessions = booking.sessions || []
const fixedTime = sessions.length > 0 && sessions.every(item => !item.flexible)
const firstSession = sessions[0] || {}
const minDate = new Date()
minDate.setDate(minDate.getDate() + Number(booking.advanceDays || 0))
const minAppointmentDate = `${minDate.getFullYear()}-${String(minDate.getMonth() + 1).padStart(2, '0')}-${String(minDate.getDate()).padStart(2, '0')}`
let timeEnd = firstSession.end || ''
if (!fixedTime && firstSession.end && booking.durationMinutes) {
const [hour, minute] = firstSession.end.split(':').map(Number)
const latest = hour * 60 + minute - booking.durationMinutes
timeEnd = `${String(Math.floor(latest / 60)).padStart(2, '0')}:${String(latest % 60).padStart(2, '0')}`
}
})
.catch(() => {
wx.showToast({ title: '网络请求失败', icon: 'none' })
this.setData({
provinces: service.areas || [],
minAppointmentDate,
fixedTime,
timeOptions: sessions.map(item => `${item.start} - ${item.end}`),
timeStart: firstSession.start || '',
timeEnd
})
},
@@ -131,7 +177,7 @@ Page({
'record.patientWeight': patient.weight,
'record.patientHeight': patient.height,
'record.patientMobile': patient.mobile,
'record.patientIdnumber': patient.idnumber,
'record.patientIdnumber': this.maskIdNumber(patient.idnumber),
'record.patientInitial': patient.name.charAt(0),
'record.patientMeta': this.buildPatientMeta(patient)
})
@@ -152,8 +198,7 @@ Page({
const canCancel = status === 'pending' || status === 'confirmed'
const canDelete = paymentStatus === 'unpaid'
&& (status === 'pending' || status === 'confirmed' || status === 'cancelled')
const canComplete = status === 'completed'
const canRebook = status === 'completed' || status === 'cancelled'
const canRebook = (status === 'completed' || status === 'cancelled') && item.escort?.serviceId > 0
// 终态单据只读:医院预约与陪诊需求不允许回改(就诊人「修改」改的是档案,不在此列)
const canEditOrder = status !== 'completed' && status !== 'cancelled'
@@ -174,11 +219,13 @@ Page({
return {
_id: item._id,
displayId: item._id ? `****${String(item._id).slice(-8).toUpperCase()}` : '--',
healthProfileId: item.healthProfileId || '',
serviceId: item.escort?.serviceId || 0,
patientName: patient.name,
patientAge: patient.age,
patientMobile: patient.mobile,
patientIdnumber: patient.idnumber,
patientIdnumber: this.maskIdNumber(patient.idnumber),
patientInitial: patient.name.charAt(0),
patientMeta: this.buildPatientMeta(patient),
hospitalProvince: item.hospital?.province || '',
@@ -197,8 +244,11 @@ Page({
scheduleTimeText: scheduleMeta.timeText,
escortServiceName: item.escort?.serviceName || '',
sexRequirementText: SEX_REQUIREMENT_MAP[item.escort?.sexRequirement] || '',
shippingAddress: item.shippingAddress || null,
cancelReason: item.cancelReason || '',
totalFee: (item.payment?.totalFee || 0).toFixed(2),
paidFee: (item.payment?.paidFee || 0).toFixed(2),
showPaidFee: Number(item.payment?.paidFee) > 0,
paymentStatus,
paymentStatusText: paymentInfo.text,
paymentStatusColor: paymentInfo.color,
@@ -216,11 +266,10 @@ Page({
statusDesc: statusInfo.desc,
canCancel,
canDelete,
canComplete,
canRebook,
canEditOrder,
// 底栏只在确实有按钮时出现,避免无动作状态空留一条白栏
showBottomBar: canCancel || canDelete || canComplete || canRebook,
showBottomBar: canCancel || canDelete || canRebook,
createTime: item.meta?.createtime ? this.formatDateTime(item.meta.createtime) : '',
updateTime: item.meta?.updatetime ? this.formatDateTime(item.meta.updatetime) : ''
}
@@ -303,6 +352,21 @@ Page({
return `${year}-${month}-${day} ${hour}:${minute}`
},
maskIdNumber(idNumber) {
const value = String(idNumber || '').trim()
if (!value) return ''
if (value.length <= 8) return '********'
return `${value.slice(0, 4)}********${value.slice(-4)}`
},
onContactSupport() {
const record = this.data.record
if (!record._id) return
wx.navigateTo({
url: `/pages/mine/contact?orderId=${encodeURIComponent(record._id)}`
})
},
onCallPatient() {
const mobile = this.data.record.patientMobile
if (!mobile || mobile === '--') return
@@ -356,10 +420,12 @@ Page({
onEditHospital() {
const r = this.data.record
const provinceIndex = Math.max(0, this.data.provinces.indexOf(r.hospitalProvince))
const sessions = this.data.service?.booking?.sessions || []
const sessionIndex = Math.max(0, sessions.findIndex(item => item.start === r.scheduleStartTime))
this.setData({
showHospitalPopup: true,
editHospital: {
province: r.hospitalProvince || '',
province: r.hospitalProvince || this.data.provinces[0] || '',
provinceIndex,
name: r.hospitalName || '',
address: r.hospitalAddress || '',
@@ -368,7 +434,7 @@ Page({
medicalRecordNo: r.medicalRecordNo || '',
scheduleDate: r.scheduleDate || '',
startTime: r.scheduleStartTime || '',
endTime: r.scheduleEndTime || ''
sessionIndex
}
})
},
@@ -392,22 +458,18 @@ Page({
},
onStartTimeChange(e) {
if (this.data.fixedTime) {
const sessionIndex = Number(e.detail.value)
const session = this.data.service.booking.sessions[sessionIndex]
this.setData({
'editHospital.sessionIndex': sessionIndex,
'editHospital.startTime': session.start
})
return
}
this.setData({ 'editHospital.startTime': e.detail.value })
},
onEndTimeChange(e) {
this.setData({ 'editHospital.endTime': e.detail.value })
},
// 起止时间都在时重算陪诊时长(分钟);结束不晚于开始视为无效,拦在保存前
calcDuration(startTime, endTime) {
if (!startTime || !endTime) return null
const [sh, sm] = startTime.split(':').map(Number)
const [eh, em] = endTime.split(':').map(Number)
const diff = eh * 60 + em - (sh * 60 + sm)
return diff > 0 ? diff : -1
},
onCancelHospitalEdit() {
this.setData({ showHospitalPopup: false })
},
@@ -422,9 +484,8 @@ Page({
wx.showToast({ title: '请选择预约日期', icon: 'none' })
return
}
const duration = this.calcDuration(form.startTime, form.endTime)
if (duration === -1) {
wx.showToast({ title: '结束时间需晚于开始时间', icon: 'none' })
if (!form.startTime) {
wx.showToast({ title: '请选择预约时间', icon: 'none' })
return
}
@@ -435,13 +496,9 @@ Page({
'hospital.department': (form.department || '').trim(),
'hospital.doctor': (form.doctor || '').trim(),
'hospital.medicalRecordNo': (form.medicalRecordNo || '').trim(),
// schedule.date 后端是 Date 类型,mongoose 会把 YYYY-MM-DD 字符串自动转换
// 时长与结束时间由后端按服务目录重新派生,前端只提交业务输入。
'schedule.date': form.scheduleDate,
'schedule.startTime': form.startTime || '',
'schedule.endTime': form.endTime || ''
}
if (duration !== null) {
update['schedule.duration'] = duration
'schedule.startTime': form.startTime
}
wx.showLoading({ title: '保存中...' })
@@ -516,35 +573,6 @@ Page({
})
},
onConfirmComplete() {
wx.showModal({
title: '确认完成',
content: '确认陪诊服务已完成?',
confirmColor: '#B8520A',
success: (res) => {
if (res.confirm) {
wx.showLoading({ title: '处理中...' })
API.escort.updateStatus(this.data.recordId, {
status: 'completed'
})
.then((res) => {
wx.hideLoading()
if (res.code === 0) {
wx.showToast({ title: '已确认完成', icon: 'success' })
this.loadRecord(this.data.recordId)
} else {
wx.showToast({ title: res.msg || '操作失败', icon: 'none' })
}
})
.catch(() => {
wx.hideLoading()
wx.showToast({ title: '网络请求失败', icon: 'none' })
})
}
}
})
},
onDeleteOrder() {
wx.showModal({
title: '删除订单',
@@ -575,8 +603,10 @@ Page({
},
onRebook() {
const serviceId = this.data.record.serviceId
if (!serviceId) return
wx.navigateTo({
url: `/pages/escort/itemlist`
url: `/pages/escort/itemdetail?id=${serviceId}&book=1`
})
},
+48 -26
View File
@@ -158,28 +158,46 @@
<text class="fee-label">服务费用</text>
<text class="fee-amount">¥{{record.totalFee}}</text>
</view>
<text class="fee-paid">已支付 ¥{{record.paidFee}}</text>
<text class="fee-paid" wx:if="{{record.showPaidFee}}">已支付 ¥{{record.paidFee}}</text>
</view>
<!-- 未付清时的出口指引:全站没有线上支付入口,只能引到客服;
收在费用行之下——「已支付 ¥0.00」之后正是用户想问「怎么付」的位置 -->
<text class="pay-hint" wx:if="{{record.paymentHint}}">{{record.paymentHint}}</text>
<!-- 支付与退款问题都进入带订单上下文的客服页 -->
<view class="pay-hint" wx:if="{{record.paymentHint}}" bindtap="onContactSupport">
<text class="pay-hint-text">{{record.paymentHint}}</text>
<t-icon name="chevron-right" size="26rpx" color="#6F655C" />
</view>
</view>
</view>
<!-- 订单信息:只留编号与时间,订单状态在抬头已出现一次,不重复 -->
<!-- 收货信息为下单时的订单快照,不随后续就诊人资料变化 -->
<view class="section" wx:if="{{record.shippingAddress && record.shippingAddress.address}}">
<view class="section-head">
<view class="section-bar"></view>
<text class="section-title">收货信息</text>
</view>
<view class="card">
<text class="shipping-recipient">{{record.shippingAddress.recipientName}} {{record.shippingAddress.mobile}}</text>
<text class="shipping-address">{{record.shippingAddress.address}}</text>
</view>
</view>
<!-- 订单信息:编号脱敏展示,完整编号由客服入口安全携带 -->
<view class="section">
<view class="section-head">
<view class="section-bar"></view>
<text class="section-title">订单信息</text>
</view>
<view class="card order-card">
<text class="order-no">订单编号 {{record._id || '--'}}</text>
<text class="order-no">订单编号 {{record.displayId}}</text>
<view class="meta-list order-meta">
<text class="meta-item">创建于 {{record.createTime || '--'}}</text>
<view class="meta-sep"></view>
<text class="meta-item">更新于 {{record.updateTime || '--'}}</text>
</view>
<view class="order-extra" wx:if="{{record.cancelReason}}">
<text class="order-extra-label">取消原因</text>
<text class="order-extra-value">{{record.cancelReason}}</text>
</view>
</view>
</view>
@@ -187,9 +205,15 @@
<view class="bottom-placeholder" wx:if="{{record.showBottomBar}}"></view>
</view>
<!-- 底部操作栏:同类实心块只保留一处——
再次预约为「已完成」时让位给「确认完成」,为「已取消」时自己成为主操作(§2.1)。
四种动作都为假时整条栏不出现:进行中且已支付这类状态没有动作可给,不留空白栏 -->
<view class="page-state" wx:if="{{loading && !record._id}}">
<t-loading theme="circular" size="40rpx" text="加载中..." />
</view>
<view class="page-state" wx:if="{{!loading && loadError && !record._id}}">
<text class="page-state-text">{{loadError}}</text>
<button class="page-retry" bindtap="retryLoad">重新加载</button>
</view>
<!-- 底部操作栏:完成状态仅由平台流转,用户不确认完成 -->
<view class="bottom-bar" wx:if="{{record.showBottomBar}}">
<view
class="action-btn action-ghost"
@@ -201,11 +225,6 @@
wx:if="{{record.canDelete}}"
bindtap="onDeleteOrder"
>删除订单</view>
<view
class="action-btn action-primary"
wx:if="{{record.canComplete}}"
bindtap="onConfirmComplete"
>确认完成</view>
<view
class="action-btn {{record.status === 'cancelled' ? 'action-primary' : 'action-ghost'}}"
wx:if="{{record.canRebook}}"
@@ -297,33 +316,36 @@
class="form-picker"
mode="date"
value="{{editHospital.scheduleDate}}"
start="{{minAppointmentDate}}"
bindchange="onScheduleDateChange"
>
<view class="form-picker-value">{{editHospital.scheduleDate || '请选择日期'}}</view>
</picker>
</view>
<view class="form-row">
<text class="form-label">开始时间</text>
<text class="form-label">预约时间</text>
<picker
wx:if="{{fixedTime}}"
class="form-picker"
mode="selector"
range="{{timeOptions}}"
value="{{editHospital.sessionIndex}}"
bindchange="onStartTimeChange"
>
<view class="form-picker-value">{{timeOptions[editHospital.sessionIndex] || '请选择服务班次'}}</view>
</picker>
<picker
wx:else
class="form-picker"
mode="time"
value="{{editHospital.startTime}}"
start="{{timeStart}}"
end="{{timeEnd}}"
bindchange="onStartTimeChange"
>
<view class="form-picker-value">{{editHospital.startTime || '请选择时间'}}</view>
</picker>
</view>
<view class="form-row">
<text class="form-label">结束时间</text>
<picker
class="form-picker"
mode="time"
value="{{editHospital.endTime}}"
bindchange="onEndTimeChange"
>
<view class="form-picker-value">{{editHospital.endTime || '请选择时间'}}</view>
</picker>
</view>
</view>
<view class="popup-footer">
<view class="popup-btn popup-btn-ghost" bindtap="onCancelHospitalEdit">取消</view>
+84 -5
View File
@@ -28,6 +28,38 @@ page {
padding: 0 32rpx 40rpx;
}
.page-state {
min-height: 70vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 48rpx 32rpx;
box-sizing: border-box;
}
.page-state-text {
font-size: 28rpx;
color: var(--muted);
line-height: 1.6;
}
.page-retry {
margin: 28rpx 0 0;
padding: 12rpx 36rpx;
border: 2rpx solid var(--brand-strong);
border-radius: 999rpx;
background: transparent;
color: var(--brand-strong);
font-size: 28rpx;
font-weight: 500;
line-height: 1.5;
}
.page-retry::after {
border: none;
}
/* ===== 抬头状态 ===== */
.page-header {
/* 抬头自成一区,靠空间 + 一条线立住,不引入第二套容器语言:
@@ -382,14 +414,38 @@ page {
letter-spacing: 1rpx;
}
/* 未付清时的出口指引:与元信息同一档(24rpx / --muted),只做说明不做按钮——
付款动作发生在客服侧,本页给不出可点的东西,硬做描边按钮会是空动作 */
/* 支付/退款指引是可点击的客服入口,用 chevron 给出显性动作暗示 */
.pay-hint {
display: flex;
align-items: center;
margin-top: 12rpx;
color: var(--muted);
}
.pay-hint:active {
opacity: 0.65;
}
.pay-hint-text {
flex: 1;
min-width: 0;
font-size: 24rpx;
letter-spacing: 1rpx;
line-height: 1.6;
}
.shipping-recipient {
display: block;
font-size: 28rpx;
font-weight: 700;
color: var(--ink);
}
.shipping-address {
display: block;
margin-top: 12rpx;
font-size: 24rpx;
color: var(--muted);
letter-spacing: 1rpx;
font-size: 26rpx;
color: var(--ink-2);
line-height: 1.6;
}
@@ -406,6 +462,29 @@ page {
margin-top: 10rpx;
}
.order-extra {
display: flex;
align-items: flex-start;
margin-top: 16rpx;
padding-top: 16rpx;
border-top: 2rpx solid var(--line);
}
.order-extra-label {
flex-shrink: 0;
font-size: 24rpx;
color: var(--muted);
}
.order-extra-value {
flex: 1;
min-width: 0;
margin-left: 20rpx;
font-size: 26rpx;
color: var(--ink-2);
line-height: 1.5;
}
/* ===== 备注(只读文本块) ===== */
.note-block {
margin-top: 18rpx;
+64 -112
View File
@@ -1,7 +1,6 @@
const API = require('../../utils/api.js')
// 状态配色遵循 doc/DESIGN.md §三:「待服务 / 服务中 / 已完成 / 已取消」四档,
// 颜色只做强化,文字才是信息。待确认与已确认同属「等待」阶段,共用待服务档
// 状态配色遵循 doc/DESIGN.md §三,颜色只作强化,文字才是信息。
const STATUS_MAP = {
pending: { text: '待确认', color: '#0F766E', bg: '#ECF7F4', border: '#C7E5DF' },
confirmed: { text: '已确认', color: '#0F766E', bg: '#ECF7F4', border: '#C7E5DF' },
@@ -10,48 +9,32 @@ const STATUS_MAP = {
cancelled: { text: '已取消', color: '#B4231A', bg: '#FCF0EE', border: '#F2D6D1' }
}
// 「进行中的」= 未完成全部:待确认 / 已确认 / 进行中 都还没结束,
// 只是处在预约的不同阶段;只有已完成、已取消才算结束。
// 全局筛选只分「全部预约 / 进行中的」两档,卡片上的状态胶囊仍按 STATUS_MAP 逐档显示
const ONGOING_STATUSES = ['pending', 'confirmed', 'in_progress']
const TYPE_MAP = {
outpatient: '门诊陪诊',
inpatient: '住院陪诊',
examination: '检查陪诊',
surgery: '手术陪诊',
medication: '取药陪诊',
other: '其他'
}
// 左右滑动切换状态页的手势参数(单位 px)
const SWIPE_THRESHOLD = 50 // 抬手后触发切换的最小横向位移
const DRAG_MAX = 120 // 跟手位移上限,避免内容被拖出屏幕
const DRAG_FACTOR = 0.5 // 跟手阻尼系数,拖 2px 内容走 1px
const AXIS_LOCK = 8 // 方向锁定阈值,超过后才判定手势方向
// 支付状态:已支付走「已完成」档;未支付 / 退款中复用主色浅档提示待处理;
// 已退款走中性档(--muted 字 + --sep 描边 + 透明底,见 §三 禁用/中性写法)
const PAYMENT_STATUS_MAP = {
unpaid: { text: '未支付', color: '#B8520A', bg: '#FFF4E8', border: '#FFE0C2' },
partial: { text: '部分支付', color: '#B8520A', bg: '#FFF4E8', border: '#FFE0C2' },
paid: { text: '已支付', color: '#1F7A4D', bg: '#EAF6EE', border: '#CDE9D7' },
refunding: { text: '退款中', color: '#B8520A', bg: '#FFF4E8', border: '#FFE0C2' },
refunded: { text: '已退款', color: '#6F655C', bg: 'transparent', border: '#E5DACC' }
}
// 左右滑动切换状态页的手势参数(单位 px)
const SWIPE_THRESHOLD = 50
const DRAG_MAX = 120
const DRAG_FACTOR = 0.5
const AXIS_LOCK = 8
const ONGOING_STATUS_QUERY = 'pending,confirmed,in_progress'
Page({
data: {
records: [],
loading: false,
loadError: '',
hasMore: true,
page: 1,
pageSize: 10,
// 默认落在左格「进行中的」:用户进记录页首先要看的是手上还没结束的单子
statusFilter: 'ongoing',
// 跟手位移(px)与拖动标记:拖动中内容随手左右移动,松手后弹回
dragX: 0,
dragging: false,
// 两段等宽:左 = 进行中的,右 = 全部预约;顺序即 index 顺序,滑动切换按 index 递增递减
statusTabs: [
{ value: 'ongoing', label: '进行中的', count: 0 },
{ value: '', label: '全部预约', count: 0 }
@@ -59,11 +42,9 @@ Page({
},
onLoad(options) {
// tab 来自 URL,只接受当前两档内的值,避免旧参数(如 tab=pending)把列表筛空
const tab = options.tab || this.data.statusFilter
const valid = this.data.statusTabs.some(item => item.value === tab)
this.setData({ statusFilter: valid ? tab : this.data.statusFilter })
this.loadRecords(true)
},
onShow() {
@@ -71,99 +52,89 @@ Page({
},
onPullDownRefresh() {
this.loadRecords(true).finally(() => {
wx.stopPullDownRefresh()
})
this.loadRecords(true).finally(() => wx.stopPullDownRefresh())
},
onReachBottom() {
if (this.data.hasMore && !this.data.loading) {
if (this.data.hasMore && !this.data.loading && !this.data.loadError) {
this.loadRecords(false)
}
},
loadRecords(reset = false) {
const app = getApp()
const user = app.globalData.user
if (!user || !user._id) {
wx.showToast({ title: '请先登录', icon: 'none' })
return Promise.resolve()
}
async loadRecords(reset = false) {
const requestId = (this.requestSequence || 0) + 1
this.requestSequence = requestId
const page = reset ? 1 : this.data.page + 1
this.setData({ loading: true })
this.setData({ loading: true, loadError: '' })
const params = {
userId: user._id,
page,
pageSize: this.data.pageSize
}
try {
const app = getApp()
await app.waitForAuth()
if (!app.globalData.user?._id) throw new Error('请先登录后查看预约记录')
const params = { page, pageSize: this.data.pageSize }
if (this.data.statusFilter === 'ongoing') params.status = ONGOING_STATUS_QUERY
const res = await API.escort.getMyRecords(params)
if (res.code !== 0) throw new Error(res.msg || '预约记录加载失败')
if (requestId !== this.requestSequence) return
const list = res.data?.records || []
const formatted = list.map(item => this.formatRecord(item))
const records = reset ? formatted : this.data.records.concat(formatted)
const total = Number(res.data?.total) || 0
const counts = res.data?.counts || {}
const statusTabs = this.data.statusTabs.map(tab => Object.assign({}, tab, {
count: Number(tab.value === 'ongoing' ? counts.ongoing : counts.all) || 0
}))
return API.escort.getMyRecords(params)
.then((res) => {
if (res.code === 0) {
let list = res.data.records || []
let formatted = list.map(item => this.formatRecord(item))
// 计数按当前页全量算,再按筛选档裁剪展示,保证两档的角标口径一致
const statusTabs = this.computeStatusCounts(formatted, this.data.statusTabs)
formatted = formatted.filter(item => this.matchStatusFilter(item, this.data.statusFilter))
this.setData({
records: reset ? formatted : this.data.records.concat(formatted),
records,
page,
hasMore: list.length >= this.data.pageSize,
total,
hasMore: records.length < total,
statusTabs
})
} catch (err) {
if (requestId !== this.requestSequence) return
if (reset) {
this.setData({
records: [],
hasMore: false,
loadError: err.message || '网络请求失败,请重试'
})
} else {
wx.showToast({ title: res.msg || '加载失败', icon: 'none' })
wx.showToast({ title: '加载失败,请重试', icon: 'none' })
}
} finally {
if (requestId === this.requestSequence) this.setData({ loading: false })
}
})
.catch((err) => {
wx.showToast({ title: '网络请求失败', icon: 'none' })
})
.finally(() => {
this.setData({ loading: false })
})
},
// 两档筛选的唯一判定处:'' = 全部预约,'ongoing' = 未完成的三种状态
matchStatusFilter(record, filter) {
if (!filter) return true
if (filter === 'ongoing') return ONGOING_STATUSES.indexOf(record.status) > -1
return record.status === filter
},
computeStatusCounts(records, tabs) {
return tabs.map(tab => Object.assign({}, tab, {
count: records.filter(item => this.matchStatusFilter(item, tab.value)).length
}))
retryLoad() {
this.loadRecords(true)
},
formatRecord(item) {
const statusInfo = STATUS_MAP[item.status] || STATUS_MAP.pending
const typeText = TYPE_MAP[item.escort?.type] || '陪诊服务'
const fee = item.payment?.totalFee || 0
const appointmentTime = item.schedule?.date
? this.formatDateTime(item.schedule.date) + item.schedule.startTime
: '--'
const paymentStatusInfo = PAYMENT_STATUS_MAP[item.payment?.status] || PAYMENT_STATUS_MAP.unpaid
const fee = Number(item.payment?.totalFee) || 0
const appointmentTime = item.schedule?.date
? `${this.formatDate(item.schedule.date)} ${item.schedule.startTime || ''}`.trim()
: '--'
return {
_id: item._id,
patientName: item.patient?.name || '--',
patientMobile: item.patient?.mobile || '--',
hospital: item.hospital?.name || '--',
department: item.hospital?.department || '--',
typeText,
status: item.status,
typeText: item.escort?.serviceName || '陪诊服务',
statusText: statusInfo.text,
statusColor: statusInfo.color,
statusBg: statusInfo.bg,
statusBorder: statusInfo.border,
appointmentTime,
fee: fee.toFixed(2),
patientNote: item.notes?.patientNote || '',
escortNote: item.notes?.escortNote || '',
paymentStatusText: paymentStatusInfo.text,
paymentStatusColor: paymentStatusInfo.color,
paymentStatusBg: paymentStatusInfo.bg,
@@ -171,27 +142,26 @@ Page({
}
},
formatDateTime(dateStr) {
formatDate(dateStr) {
const d = new Date(dateStr)
if (isNaN(d.getTime())) return '--'
const year = d.getFullYear()
const month = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${year}-${month}-${day} `
return `${year}-${month}-${day}`
},
onTabChange(e) {
this.switchStatusTab(Number(e.currentTarget.dataset.index))
},
// 统一的状态页切换入口:点分段与左右滑动都走这里
switchStatusTab(index) {
const tab = this.data.statusTabs[index]
if (!tab || tab.value === this.data.statusFilter) return
this.setData({ statusFilter: tab.value })
this.setData({ statusFilter: tab.value, records: [], hasMore: true })
this.loadRecords(true)
},
// 左右滑动切换状态页:拖动阶段实时跟手,抬手阶段判断是否成手势
onTouchStart(e) {
const touch = e.touches[0]
this.touchStart = { x: touch.clientX, y: touch.clientY }
@@ -202,19 +172,16 @@ Page({
onTouchMove(e) {
const start = this.touchStart
if (!start) return
const touch = e.touches[0]
const deltaX = touch.clientX - start.x
const deltaY = touch.clientY - start.y
// 首次移动时锁定方向:纵向手势交给页面滚动,不做横向跟手
if (!this.touchAxis) {
if (Math.abs(deltaX) <= AXIS_LOCK && Math.abs(deltaY) <= AXIS_LOCK) return
this.touchAxis = Math.abs(deltaX) > Math.abs(deltaY) ? 'x' : 'y'
}
if (this.touchAxis !== 'x') return
// 阻尼跟手 + 位移上限:内容在有限范围内随手平移,形成可拖拽的实感
const dragX = Math.round(Math.max(-DRAG_MAX, Math.min(DRAG_MAX, deltaX * DRAG_FACTOR)))
if (dragX === this.dragValue) return
this.dragValue = dragX
@@ -231,34 +198,19 @@ Page({
const touch = e.changedTouches[0]
const deltaX = touch.clientX - start.x
const deltaY = touch.clientY - start.y
// 松手先把内容弹回原位,回弹由 .container 的 transition 承担
if (this.data.dragging || this.data.dragX !== 0) {
this.dragValue = 0
this.setData({ dragging: false, dragX: 0 })
}
if (axis !== 'x') return
// 横向位移要足够大、且明显大于纵向,才算切换手势,
// 避免与列表纵向滚动、卡片点按互相干扰
if (Math.abs(deltaX) < SWIPE_THRESHOLD || Math.abs(deltaX) < Math.abs(deltaY) * 1.5) return
const tabs = this.data.statusTabs
const currentIndex = tabs.findIndex(tab => tab.value === this.data.statusFilter)
// 左滑看下一个状态,右滑回上一个状态
const currentIndex = this.data.statusTabs.findIndex(tab => tab.value === this.data.statusFilter)
this.switchStatusTab(deltaX < 0 ? currentIndex + 1 : currentIndex - 1)
},
onTapRecord(e) {
const id = e.currentTarget.dataset.id
wx.navigateTo({
url: `/pages/escort/recorddetail?id=${id}`
})
},
makePhoneCall() {
wx.makePhoneCall({
phoneNumber: '18618162956'
})
wx.navigateTo({ url: `/pages/escort/recorddetail?id=${id}` })
}
})
+11 -4
View File
@@ -72,7 +72,7 @@
</view>
</view>
<!-- 底部:费用 + 支付状态。原右侧的 chevron 已去,支付胶囊贴右边缘对齐 -->
<!-- 底部:费用 + 支付状态 + 详情入口暗示 -->
<view class="card-foot">
<view class="fee">
<text class="fee-sym">¥</text>
@@ -83,14 +83,21 @@
class="pay-chip"
style="background: {{item.paymentStatusBg}}; color: {{item.paymentStatusColor}}; border-color: {{item.paymentStatusBorder}};"
>{{item.paymentStatusText}}</view>
<t-icon class="record-chevron" name="chevron-right" size="28rpx" color="#6F655C" />
</view>
</view>
</view>
</view>
<!-- 空状态:两档口径不同,文案跟着当前档走,
避免「进行中的」为空时误报成「您还没有预约陪诊服务」 -->
<view class="empty-state" wx:if="{{!loading && records.length === 0}}">
<!-- 首屏加载失败时给出明确原因和重试入口,不误报为空记录 -->
<view class="error-state" wx:if="{{!loading && loadError && records.length === 0}}">
<t-icon name="error-circle" size="88rpx" color="#6F655C" />
<text class="error-text">{{loadError}}</text>
<button class="retry-btn" bindtap="retryLoad">重新加载</button>
</view>
<!-- 空状态:两档口径不同,文案跟着当前档走 -->
<view class="empty-state" wx:if="{{!loading && !loadError && records.length === 0}}">
<t-icon name="file-unknown" size="120rpx" color="#A79C92" />
<text class="empty-text">{{statusFilter ? '暂无进行中的预约' : '暂无陪诊记录'}}</text>
<text class="empty-subtext">{{statusFilter ? '已结束的预约可在「全部预约」里查看' : '您还没有预约陪诊服务'}}</text>
+36 -1
View File
@@ -217,6 +217,10 @@ page {
align-items: center;
}
.record-chevron {
margin-left: 12rpx;
}
/* 支付状态胶囊:比订单状态轻一档(无底色的中性档只留字与描边) */
.pay-chip {
padding: 4rpx 14rpx;
@@ -228,7 +232,38 @@ page {
white-space: nowrap;
}
/* ===== 空 / 加载 / 到底 ===== */
/* ===== 空 / 错误 / 加载 / 到底 ===== */
.error-state {
display: flex;
flex-direction: column;
align-items: center;
padding: 140rpx 32rpx 0;
}
.error-text {
margin-top: 24rpx;
font-size: 28rpx;
color: var(--muted);
line-height: 1.6;
text-align: center;
}
.retry-btn {
margin: 28rpx 0 0;
padding: 12rpx 36rpx;
border: 2rpx solid var(--brand-strong);
border-radius: 999rpx;
background: transparent;
color: var(--brand-strong);
font-size: 28rpx;
font-weight: 500;
line-height: 1.5;
}
.retry-btn::after {
border: none;
}
.empty-state {
display: flex;
flex-direction: column;
+37 -26
View File
@@ -19,9 +19,6 @@ const SERVICE_UI = {
// 全天 / 半天是核心营收项,靠排在前两位形成隐性推荐位
const SERVICE_ORDER = [1, 2, 7, 3, 4, 5, 8, 6]
// 计入"待服务订单"的订单状态:待确认 / 已确认 / 进行中
const PENDING_ORDER_STATUS = ['pending', 'confirmed', 'in_progress']
Page({
data: {
escortServices: [], // 陪诊服务(来自后端,按 SERVICE_ORDER 展示)
@@ -72,12 +69,16 @@ Page({
// 读取后端服务列表,拼装成首页宫格所需的展示数据
loadServices() {
const app = getApp()
// servicesReady 由 app.onLaunch 创建,兜底避免极端情况下取不到
const ready = app.globalData.servicesReady || Promise.resolve(app.globalData.services || [])
app.loadServices()
.then((services) => {
if (!services) {
this.setData({ escortServices: [] })
console.error('首页服务列表加载失败')
return
}
ready.then((services) => {
const serviceMap = {}
;(services || []).forEach((service) => {
services.forEach((service) => {
serviceMap[service.id] = service
})
@@ -100,39 +101,49 @@ Page({
escortServices
})
})
.catch((err) => {
this.setData({ escortServices: [] })
console.error('首页服务列表加载失败', err)
})
},
// 统计待服务订单:仅在登录信息就绪后请求,未就绪时稍后重试一次
refreshPendingCount(retry) {
// 统计待服务订单:等待鉴权完成,登录后由后端按状态汇总
refreshPendingCount() {
if (this.pendingRequest) return this.pendingRequest
const app = getApp()
this.pendingRequest = app.waitForAuth()
.then(() => {
const user = app.globalData.user
if (!user || !user._id) {
// 首次进入时 App 的登录请求可能还没返回,延迟重试一次即可
if (!retry) {
setTimeout(() => this.refreshPendingCount(1), 1500)
}
return
this.setData({ pendingCount: 0 })
return null
}
API.escort.getMyRecords({
userId: user._id,
return API.escort.getMyRecords({
page: 1,
pageSize: 50
pageSize: 1,
status: 'pending,confirmed,in_progress'
})
})
.then((res) => {
if (res.code !== 0) {
return
}
const records = (res.data && res.data.records) || []
const pendingCount = records.filter((record) => PENDING_ORDER_STATUS.indexOf(record.status) > -1).length
this.setData({
pendingCount
})
if (!res || res.code !== 0) return
const data = res.data || {}
const counts = data.counts || {}
const pendingCount = counts.ongoing === undefined || counts.ongoing === null
? (data.total || 0)
: counts.ongoing
this.setData({ pendingCount })
})
.catch((err) => {
console.log('获取待服务订单失败', err)
})
.finally(() => {
this.pendingRequest = null
})
return this.pendingRequest
},
// 页脚三个 B 端入口:都进「合作与入驻」页,用 section 定位到各自的卡片
+12
View File
@@ -1,6 +1,7 @@
// pages/mine/contact.js
Page({
data: {
orderContext: '',
// 联系方式配置:action 决定点击行为,call=拨号 / copy=复制 / 空=不可点
contactItems: [{
label: '客服热线',
@@ -29,6 +30,17 @@ Page({
]
},
onLoad(options = {}) {
const orderNo = String(options.orderNo || '').trim()
const orderId = String(options.orderId || '').trim()
const displayNo = (orderNo || orderId.slice(-8)).toUpperCase()
if (!displayNo) return
this.setData({
orderContext: `咨询订单尾号 ${displayNo},联系客服时请提供该编号`
})
},
onItemTap(e) {
const {
action,
+4
View File
@@ -9,6 +9,10 @@
<text class="header-subtitle">人工客服在线,有问题随时找我们</text>
</view>
<view wx:if="{{orderContext}}" class="order-context">
<text class="order-context-text">{{orderContext}}</text>
</view>
<!-- 联系方式:action 决定点击行为(call 拨号 / copy 复制) -->
<view class="card">
<view class="contact-item" wx:for="{{ contactItems }}" wx:key="label"
+14
View File
@@ -57,6 +57,20 @@ page {
letter-spacing: 1rpx;
}
.order-context {
margin-top: 24rpx;
padding: 20rpx 24rpx;
border: 2rpx solid var(--brand-line);
border-radius: 16rpx;
background: var(--brand-soft);
}
.order-context-text {
font-size: 26rpx;
color: var(--brand-ink);
line-height: 1.6;
}
/* ===== 联系方式卡片 ===== */
.card {
margin-top: 32rpx;
+4 -36
View File
@@ -11,11 +11,6 @@ Page({
// 身份行副行,loadUserInfo 时由手机号脱敏填入
account: '',
phone: '',
sex: '',
birth: '',
email: '',
idnumber: '',
ssn: '',
isLoggedIn: false
},
// 菜单分组:按"用途"而非"是不是陪诊"分,三组才立得住。
@@ -34,10 +29,6 @@ Page({
name: '就诊人',
icon: 'user-checked',
bindtap: 'onTapHealth'
}, {
name: '邮寄地址',
icon: 'location',
bindtap: 'onTapAddress'
}]
}, {
groupName: '帮助与支持',
@@ -68,12 +59,9 @@ Page({
}]
},
onLoad() {
this.loadUserInfo()
},
onShow() {
this.loadUserInfo()
const app = getApp()
app.waitForAuth().finally(() => this.loadUserInfo())
// 同步自定义 tabBar 选中态(我的为第 2 项)
if (typeof this.getTabBar === 'function' && this.getTabBar()) {
this.getTabBar().setData({
@@ -96,12 +84,7 @@ Page({
'userInfo.phone': profile.mobile || '',
// 身份行副行(微信那行是微信号):本应用没有账号体系,
// 等价标识是手机号,脱敏成 138****1234 后再上屏
'userInfo.account': this.maskMobile(profile.mobile || ''),
'userInfo.sex': profile.sex || '',
'userInfo.birth': profile.birth ? this.formatDate(profile.birth) : '',
'userInfo.email': profile.email || '',
'userInfo.idnumber': profile.idnumber || '',
'userInfo.ssn': profile.ssn || ''
'userInfo.account': this.maskMobile(profile.mobile || '')
})
} else {
// 未登录(含刚退出登录):身份行收敛回默认态。
@@ -124,17 +107,8 @@ Page({
return `${digits.slice(0, 3)}****${digits.slice(7)}`
},
formatDate(date) {
if (!date) return ''
const d = new Date(date)
const year = d.getFullYear()
const month = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
},
// 顶部身份行整行可点,但未登录时不该跳进"填完才被拦"的资料页
// (个人信息与邮寄地址改真页面后系统返回键归页面栈管,
// (个人信息改真页面后系统返回键归页面栈管,
// 不再像原来的浮层那样被系统返回键直接退出小程序)
onTapProfile() {
if (!this.data.userInfo.isLoggedIn) return
@@ -143,12 +117,6 @@ Page({
})
},
onTapAddress() {
wx.navigateTo({
url: '/pages/mine/addressedit'
})
},
onTapHealth() {
wx.navigateTo({
url: '/pages/health/profilelist'