Files
wxapp_companion/pages/order/orderEdit.js
T
lik 0e648c19ba feat(admin): 订单详情展示支付渠道并支持查询退款
- 订单详情展示支付渠道与退款中状态,提供查询退款结果兜底入口
- 操作按钮按取消状态收敛,已申请取消时仅保留同意取消
- 存在未支付流水时锁定金额输入,避免改价与在途支付冲突
- utils/api.js 新增退款查询接口
2026-11-05 18:55:32 +08:00

539 lines
17 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// pages/order/orderEdit.js
const API = require('../../utils/api.js')
const { calcAge } = require('../../utils/format.js')
// 支付方式选项:与 schema 的 payment.method 枚举一一对应,空串表示未记录
const METHOD_OPTIONS = [
{ value: '', label: '未记录' },
{ value: 'online_wechat', label: '线上微信' },
{ value: 'offline_cash', label: '线下现金' },
{ value: 'offline_transfer', label: '线下转账' }
]
Page({
/**
* 页面的初始数据
*/
data: {
isEdit: false,
form: {
hospital: { province: '', name: '', department: '', doctor: '' },
schedule: { date: '', startTime: '08:30' },
escort: { serviceId: -1, serviceName: '' },
payment: { totalFee: '', method: '' },
notes: { patientNote: '' }
},
// 省份选项来自服务目录的 areas,后端下单按同一份配置校验
provinces: [],
provinceIndex: 0,
profileSummary: null,
// 新增模式下尚未选择档案时为 true,展示选择占位
needPickProfile: false,
// 档案选择弹层
showProfilePicker: false,
profileList: [],
filteredProfiles: [],
profileKeyword: '',
serviceOptions: [],
// 支付方式选项与回显标签
methodOptions: METHOD_OPTIONS,
methodLabel: '',
// 存在未支付流水时金额锁定:需先关单/取消后再改价
amountLocked: false,
today: '',
submitting: false
},
/**
* 生命周期函数--监听页面加载
* 新增:?id=健康档案ID(患者信息取自档案),不带 id 则进入档案选择
* 编辑:?orderId=订单ID(回填订单数据)
*/
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 })
this.loadServices()
if (options && options.orderId) {
// 编辑模式
this.orderId = options.orderId
this.setData({ isEdit: true })
wx.setNavigationBarTitle({ title: '编辑订单' })
this.loadOrder(options.orderId)
return
}
wx.setNavigationBarTitle({ title: '新增预约' })
if (!options || !options.id) {
// 未携带档案ID:弹出档案选择
this.setData({ needPickProfile: true })
this.openProfilePicker()
return
}
this.profileId = options.id
// 组件根据档案ID自行加载(缓存优先)
this.setData({ profileId: options.id })
},
/**
* 空方法:阻止弹层内容区域点击冒泡关闭
*/
noop() {},
/**
* 档案选择弹层:打开并加载档案列表
*/
openProfilePicker() {
this.setData({ showProfilePicker: true, profileKeyword: '' })
if (this.data.profileList.length === 0) {
this.loadProfiles()
} else {
this.filterProfiles()
}
},
closeProfilePicker() {
this.setData({ showProfilePicker: false })
},
loadProfiles() {
API.healthProfile.getProfiles({ page: 1, pageSize: 100, sortBy: 'updatetime' })
.then(res => {
if (res.code !== 0) {
return wx.showToast({ title: res.msg || '获取档案失败', icon: 'none' })
}
const list = ((res.data && res.data.list) || []).map(item => {
const p = item.profile || {}
const age = calcAge(p.birth)
return {
id: item._id,
name: p.name || '',
mobile: p.mobile || '',
sexLabel: p.sex === 'male' ? '男' : (p.sex === 'female' ? '女' : ''),
ageText: age ? `${age}岁` : ''
}
})
this.setData({ profileList: list })
this.filterProfiles()
})
.catch(err => {
console.error('获取健康档案失败', err)
wx.showToast({ title: '网络错误,请重试', icon: 'none' })
})
},
onProfileSearch(e) {
this.setData({ profileKeyword: e.detail.value })
this.filterProfiles()
},
filterProfiles() {
const kw = (this.data.profileKeyword || '').trim()
const list = this.data.profileList
const filtered = kw
? list.filter(item => item.name.includes(kw) || (item.mobile || '').includes(kw))
: list
this.setData({ filteredProfiles: filtered })
},
/**
* 选中档案:加载档案信息并进入表单
*/
onProfileSelect(e) {
const id = e.currentTarget.dataset.id
if (!id) return
this.profileId = id
// 组件根据档案ID自行加载(缓存优先)
this.setData({ profileId: id, needPickProfile: false, showProfilePicker: false })
},
/**
* 编辑模式:加载订单并回填表单
*/
loadOrder(id) {
wx.showLoading({ title: '加载中...' })
API.escort.getRecordById(id)
.then(res => {
wx.hideLoading()
if (res.code !== 0 || !res.data || !res.data.record) {
wx.showToast({ title: res.msg || '订单加载失败', icon: 'none' })
setTimeout(() => wx.navigateBack(), 800)
return
}
const order = res.data.record
this.profileId = order.healthProfileId || null
// 患者信息取自订单快照(作为无关联档案时的回退),字段与 schema 一一对应
const p = order.patient || {}
this.patientInfo = {
name: p.name || '',
mobile: p.mobile || '',
birth: p.birth || '',
weight: p.weight || 0,
height: p.height || 0,
idnumber: p.idnumber || ''
}
if (p.sex) {
this.patientInfo.sex = p.sex
}
const sexLabel = p.sex === 'male' ? '男' : (p.sex === 'female' ? '女' : '')
const age = calcAge(p.birth)
this.originalTotalFee = Number(order.payment && order.payment.totalFee) || 0
const amountLocked = (order.payment?.status || 'unpaid') === 'unpaid'
&& !!order.payment?.paymentRecordId
this.setData({
amountLocked,
// 有关联档案时交由 patient-info 按 ID 加载(不读缓存,以档案最新数据为准)
profileId: order.healthProfileId || '',
// 无关联档案时用订单 patient 快照兜底展示姓名/性别/年龄/电话;
// 血型、身高、体重、备注不属于 escort_record(schema 无 health 块),
// 有关联档案时由 patient-info 按 profileId 加载后经 onProfileLoaded 回填,
// 故这里不再读 order.health(该块恒为空,属死代码)
profileSummary: {
name: p.name || '',
mobile: p.mobile || '',
sexLabel,
ageText: age ? `${age}岁` : ''
},
form: {
hospital: {
province: (order.hospital && order.hospital.province) || '',
name: (order.hospital && order.hospital.name) || '',
department: (order.hospital && order.hospital.department) || '',
doctor: (order.hospital && order.hospital.doctor) || ''
},
schedule: {
date: this.formatDate(order.schedule && order.schedule.date),
startTime: (order.schedule && order.schedule.startTime) || '08:30'
},
escort: {
serviceId: (order.escort && order.escort.serviceId) || -1,
serviceName: (order.escort && order.escort.serviceName) || ''
},
payment: {
totalFee: order.payment && order.payment.totalFee ? String(order.payment.totalFee) : '',
method: (order.payment && order.payment.method) || '',
paid: !!(order.payment && order.payment.status === 'paid')
},
notes: { patientNote: (order.notes && order.notes.patientNote) || '' }
}
}, () => { this.syncProvinces(); this.syncMethodLabel() })
})
.catch(err => {
console.error('获取订单失败', err)
wx.hideLoading()
wx.showToast({ title: '网络错误,请重试', icon: 'none' })
})
},
/**
* 格式化日期为 YYYY-MM-DD(兼容时间戳/字符串)
*/
formatDate(date) {
if (!date) return ''
const d = new Date(date)
if (isNaN(d.getTime())) return String(date)
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
},
/**
* patient-info 组件按档案ID加载完成:保存患者原始信息(供提交)及档案附加信息(供标签展示)
*/
onProfileLoaded(e) {
const profile = e.detail.profile || {}
const p = profile.profile || {}
const h = profile.health || {}
// 订单 patient 快照:与 escort_record schema 的 patient 字段一一对应。
// sex 是 male/female 枚举,空串会校验失败,为空时不写该字段
this.patientInfo = {
name: p.name || '',
mobile: p.mobile || '',
birth: p.birth || '',
weight: h.weight || 0,
height: h.height || 0,
idnumber: p.idnumber || ''
}
if (p.sex) {
this.patientInfo.sex = p.sex
}
this.setData({
profileSummary: {
bloodType: h.bloodType || '',
height: h.height || '',
weight: h.weight || '',
remark: h.remark || ''
}
})
},
/**
* 表单输入处理
*/
onInput(e) {
const key = e.currentTarget.dataset.key
const value = e.detail.value
this.setData({ [`form.${key}`]: value })
},
/**
* 就诊日期选择
*/
onDateChange(e) {
this.setData({ 'form.schedule.date': e.detail.value })
},
/**
* 开始时间选择
*/
onTimeChange(e) {
this.setData({ 'form.schedule.startTime': e.detail.value })
},
/**
* 加载陪诊服务列表(供服务名称下拉选择)
*/
loadServices() {
API.resource.getServices()
.then(res => {
if (res.code !== 0) return
this.setData({ serviceOptions: (res.data && res.data.services) || [] }, () => this.syncProvinces())
})
.catch(err => {
console.error('获取服务列表失败', err)
})
},
/**
* 同步省份选项:优先取当前服务的 areas,未选服务时取所有服务的并集。
* 后端下单校验使用同一份服务目录,避免前后端省份口径不一致。
*/
syncProvinces() {
const { serviceOptions, form } = this.data
let areas = []
if (form.escort.serviceId !== -1) {
const svc = serviceOptions.find(item => Number(item.id) === Number(form.escort.serviceId))
if (svc && Array.isArray(svc.areas)) areas = svc.areas
}
if (areas.length === 0) {
const set = new Set()
serviceOptions.forEach(item => (item.areas || []).forEach(area => set.add(area)))
areas = Array.from(set)
}
if (areas.length === 0) return
const current = form.hospital.province
const province = areas.includes(current) ? current : areas[0]
this.setData({
provinces: areas,
provinceIndex: Math.max(0, areas.indexOf(province)),
'form.hospital.province': province
})
},
/**
* 省份选择
*/
onProvinceChange(e) {
const index = Number(e.detail.value)
this.setData({
provinceIndex: index,
'form.hospital.province': this.data.provinces[index] || ''
})
},
/**
* 服务名称选择:同时记录服务ID与服务名称,并同步该服务的省份范围
*/
onServiceChange(e) {
const svc = this.data.serviceOptions[Number(e.detail.value)]
if (!svc) return
this.setData({
'form.escort.serviceId': svc.id,
'form.escort.serviceName': svc.title
}, () => this.syncProvinces())
},
/**
* 是否已支付切换
*/
onPaidChange(e) {
this.setData({ 'form.payment.paid': e.detail.value })
},
/**
* 支付方式选择
*/
onMethodChange(e) {
const option = METHOD_OPTIONS[Number(e.detail.value)]
if (!option) return
this.setData({ 'form.payment.method': option.value }, () => this.syncMethodLabel())
},
/**
* 同步支付方式回显标签
*/
syncMethodLabel() {
const option = METHOD_OPTIONS.find(item => item.value === this.data.form.payment.method)
this.setData({ methodLabel: option ? option.label : '未记录' })
},
/**
* 提交订单(新增或保存修改)
*/
onSubmit() {
if (this.data.submitting) return
const { form } = this.data
if (!this.profileId) return wx.showToast({ title: '请先选择健康档案', icon: 'none' })
// 患者信息取自档案/订单
const patient = this.patientInfo
if (!patient || !patient.name) return wx.showToast({ title: '健康档案信息未加载', icon: 'none' })
if (!form.hospital.province) return wx.showToast({ title: '请选择省份', icon: 'none' })
if (!form.hospital.name) return wx.showToast({ title: '请输入医院名称', icon: 'none' })
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)
}
},
/**
* 新增订单
*/
createOrder(form, userId) {
const payload = {
userId,
healthProfileId: this.profileId || null,
patient: this.patientInfo,
hospital: {
province: form.hospital.province,
name: form.hospital.name,
department: form.hospital.department,
doctor: form.hospital.doctor
},
schedule: {
date: form.schedule.date,
startTime: form.schedule.startTime || '',
duration: 60
},
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
}
}
this.setData({ submitting: true })
wx.showLoading({ title: '提交中...' })
API.escort.createRecord(payload)
.then(res => {
wx.hideLoading()
if (res.code !== 0) {
this.setData({ submitting: false })
return wx.showToast({ title: res.msg || '创建失败', icon: 'none' })
}
wx.showToast({ title: '创建成功', icon: 'success' })
setTimeout(() => {
wx.navigateBack()
}, 600)
})
.catch(err => {
console.error('创建订单失败', err)
this.setData({ submitting: false })
wx.hideLoading()
wx.showToast({ title: '网络错误,请重试', icon: 'none' })
})
},
/**
* 编辑模式:保存修改
*/
updateOrder(form) {
if (this.data.amountLocked) {
const nextTotalFee = form.payment.totalFee ? Number(form.payment.totalFee) : 0
if (nextTotalFee !== (this.originalTotalFee || 0)) {
return wx.showToast({ title: '存在未支付流水,请先关闭后再修改金额', icon: 'none' })
}
}
const payload = {
'hospital.province': form.hospital.province,
'hospital.name': form.hospital.name,
'hospital.department': form.hospital.department,
'hospital.doctor': form.hospital.doctor,
'schedule.date': form.schedule.date,
'schedule.startTime': form.schedule.startTime || '',
'escort.serviceId': form.escort.serviceId || -1,
'escort.serviceName': form.escort.serviceName,
'payment.totalFee': form.payment.totalFee ? Number(form.payment.totalFee) : 0,
'payment.method': form.payment.method || '',
'payment.paidFee': form.payment.paid ? (form.payment.totalFee ? Number(form.payment.totalFee) : 0) : 0,
'payment.status': form.payment.paid ? 'paid' : 'unpaid',
'notes.patientNote': form.notes.patientNote
}
this.setData({ submitting: true })
wx.showLoading({ title: '保存中...' })
API.escort.updateRecord(this.orderId, payload)
.then(res => {
wx.hideLoading()
if (res.code !== 0) {
this.setData({ submitting: false })
return wx.showToast({ title: res.msg || '保存失败', icon: 'none' })
}
wx.showToast({ title: '保存成功', icon: 'success' })
setTimeout(() => {
wx.navigateBack()
}, 600)
})
.catch(err => {
console.error('更新订单失败', err)
this.setData({ submitting: false })
wx.hideLoading()
wx.showToast({ title: '网络错误,请重试', icon: 'none' })
})
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {
}
})