完善表单校验与公共数据逻辑

Co-Authored-By: Kimi-K3.1-Pro <noreply@moonshot.ai>
This commit is contained in:
lik
2026-10-24 18:49:02 +08:00
committed by trae-solo-agent
co-authored by Kimi-K3.1-Pro
parent d731fc1da3
commit a45a3d7a86
18 changed files with 496 additions and 336 deletions
+2 -1
View File
@@ -1,4 +1,5 @@
const API = require('../../utils/api.js')
const { formatDate } = require('../../utils/date.js')
Page({
data: {
@@ -88,7 +89,7 @@ Page({
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')}`
const minAppointmentDate = formatDate(minDate)
let timeEnd = firstSession.end || ''
if (!fixedTime && firstSession.end && booking.durationMinutes) {
const [hour, minute] = firstSession.end.split(':').map(Number)
+23 -13
View File
@@ -44,7 +44,9 @@ function formatPrice(value) {
Page({
data: {
groups: []
groups: [],
loading: true,
loadError: ''
},
onShareAppMessage() {
@@ -61,23 +63,23 @@ Page({
},
onLoad() {
const app = getApp()
// 与首页同样走 servicesReady,避免直接从详情页返回时 globalData 尚未就绪
const ready = app.globalData.servicesReady || Promise.resolve(app.globalData.services || [])
this.loadServices()
},
async loadServices() {
this.setData({ loading: true, loadError: '' })
try {
const services = await getApp().loadServices()
if (!services) throw new Error('服务加载失败,请重试')
ready.then((services) => {
const list = services || []
const serviceMap = {}
list.forEach((service) => {
services.forEach((service) => {
serviceMap[service.id] = service
})
// 取到服务后再加工成列表页要用的字段:unit 补规格签,price 去掉 .00。
// 说明句不再加工,直接用 subtitle 原文——原先按「第一个逗号」剥时长前缀,
// 副标题一旦写成「八小时服务/次(早8点-中午12点,下午1点-晚上5点),…」,
// 括号里的逗号会先被匹配上,行内只剩「下午1点-晚上5点),专业陪诊师全程陪同」,
// 开头半个括号、括号不配对。行内允许折行,不靠截文案来压行数。
// 最后空组不展示,免得留下一个没有服务、只有标题的分组
// 说明句直接使用 subtitle 原文,允许折行,不靠截断来压缩行数。
const groups = SERVICE_GROUPS
.map((group) => ({
key: group.key,
@@ -95,7 +97,15 @@ Page({
.filter((group) => group.items.length > 0)
this.setData({ groups })
})
} catch (err) {
this.setData({ groups: [], loadError: err.message || '网络请求失败,请重试' })
} finally {
this.setData({ loading: false })
}
},
retryLoad() {
this.loadServices()
},
// 预约:带 book=1 进详情页,详情页读完服务后会自己把预约单弹出来,
+11
View File
@@ -20,6 +20,17 @@
<text class="notice-text">目前已开通北京、天津。费用仅含人工服务费,不含就医费用。</text>
</view>
<view class="page-state" wx:if="{{loading}}">
<t-loading theme="circular" size="40rpx" text="加载中..." />
</view>
<view class="page-state" wx:elif="{{loadError}}">
<text class="page-state-text">{{loadError}}</text>
<view class="page-retry" bindtap="retryLoad">重新加载</view>
</view>
<view class="page-state" wx:elif="{{groups.length === 0}}">
<text class="page-state-text">暂无可用服务</text>
</view>
<!-- 服务按"要办的事"分两组,每组是"组头 + 每项一张白卡":
组头(竖条 + 36rpx 标题 + 暖橙底副题)落在纸面上,下面直接堆叠服务白卡。
分组本轮由"通栏白底章节带"改为"组头在纸面上、卡片逐张堆叠"(原理详见 itemlist.wxss 的 .group)。
+25
View File
@@ -146,6 +146,31 @@ page {
line-height: 1.7;
}
/* ===== 加载、失败与真实空态 ===== */
.page-state {
display: flex;
flex-direction: column;
align-items: center;
padding: 80rpx 32rpx;
}
.page-state-text {
font-size: 28rpx;
line-height: 1.6;
color: var(--muted);
text-align: center;
}
.page-retry {
margin-top: 24rpx;
padding: 12rpx 28rpx;
border: 2rpx solid var(--brand-strong);
border-radius: 28rpx;
font-size: 26rpx;
font-weight: 500;
color: var(--brand-strong);
}
/* ===== 页尾文档行 =====
服务指南 / 用户协议两枚链接,从页首披露卡下移到这里。
不做卡:清单已由末张服务卡收口,页尾只补一行"文档级"元信息,重量压到最低。
+14 -71
View File
@@ -1,28 +1,8 @@
const API = require('../../utils/api.js')
// 状态配色遵循 doc/DESIGN.md §三:四档状态色 + 状态说明文字,
// 颜色只做强化,文字才是信息。待确认与已确认同属「等待」阶段,共用待服务档
const STATUS_MAP = {
// 待确认是唯一「等用户自己决定」的阶段(底栏此时一定有「取消订单」),
// 说明文字因此带上可执行动作,靠文字而不是靠再叠一层色块来提请注意
pending: { text: '待确认', color: '#0F766E', bg: '#ECF7F4', border: '#C7E5DF', desc: '订单已提交,等待陪诊师确认;确认前可取消' },
confirmed: { text: '已确认', color: '#0F766E', bg: '#ECF7F4', border: '#C7E5DF', desc: '订单已确认,陪诊师将准时为您服务' },
in_progress: { text: '进行中', color: '#B8520A', bg: '#FFF4E8', border: '#FFE0C2', desc: '陪诊服务正在进行中' },
completed: { text: '已完成', color: '#1F7A4D', bg: '#EAF6EE', border: '#CDE9D7', desc: '陪诊服务已完成,感谢您的使用' },
cancelled: { text: '已取消', color: '#B4231A', bg: '#FCF0EE', border: '#F2D6D1', desc: '该订单已取消' }
}
// 支付状态胶囊:未支付 / 部分支付复用主色浅档提示待处理;已退款走中性档(--muted 字 + --sep 描边 + 透明底);
// 已支付不显示胶囊(支付完成是常态,不需要状态强调),paid 档仅为映射兜底保留。
// hint 是未付清时的出口指引:全站没有线上支付入口,只能引导走客服;
// 部分支付要说清是「补齐」而不是「完成支付」,否则用户会以为要再付一次全款
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' }
}
const { parseDate, formatDate, formatDateTime, calcAge } = require('../../utils/date.js')
const { STATUS_MAP, PAYMENT_STATUS_MAP } = require('../../utils/order.js')
const { maskIdNumber, maskOrderId } = require('../../utils/privacy.js')
const SEX_MAP = {
male: '男',
@@ -132,7 +112,7 @@ Page({
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')}`
const minAppointmentDate = formatDate(minDate)
let timeEnd = firstSession.end || ''
if (!fixedTime && firstSession.end && booking.durationMinutes) {
const [hour, minute] = firstSession.end.split(':').map(Number)
@@ -165,7 +145,7 @@ Page({
const patient = {
name: profile.name || '',
sexText: SEX_MAP[profile.sex] || '',
age: this.calcAge(profile.birth),
age: calcAge(profile.birth),
weight: health.weight || 0,
height: health.height || 0,
mobile: profile.mobile || '',
@@ -177,7 +157,7 @@ Page({
'record.patientWeight': patient.weight,
'record.patientHeight': patient.height,
'record.patientMobile': patient.mobile,
'record.patientIdnumber': this.maskIdNumber(patient.idnumber),
'record.patientIdnumber': maskIdNumber(patient.idnumber),
'record.patientInitial': patient.name.charAt(0),
'record.patientMeta': this.buildPatientMeta(patient)
})
@@ -207,7 +187,7 @@ Page({
const patient = {
name: item.patient?.name || '',
sexText: SEX_MAP[item.patient?.sex] || '',
age: this.calcAge(item.patient?.birth),
age: calcAge(item.patient?.birth),
weight: item.patient?.weight || 0,
height: item.patient?.height || 0,
mobile: item.patient?.mobile || '',
@@ -219,13 +199,13 @@ Page({
return {
_id: item._id,
displayId: item._id ? `****${String(item._id).slice(-8).toUpperCase()}` : '--',
displayId: maskOrderId(item._id),
healthProfileId: item.healthProfileId || '',
serviceId: item.escort?.serviceId || 0,
patientName: patient.name,
patientAge: patient.age,
patientMobile: patient.mobile,
patientIdnumber: this.maskIdNumber(patient.idnumber),
patientIdnumber: maskIdNumber(patient.idnumber),
patientInitial: patient.name.charAt(0),
patientMeta: this.buildPatientMeta(patient),
hospitalProvince: item.hospital?.province || '',
@@ -237,7 +217,7 @@ Page({
hospitalDoctor: item.hospital?.doctor || '',
medicalRecordNo: item.hospital?.medicalRecordNo || '',
// scheduleDate 保留 YYYY-MM-DD 原格式:编辑弹窗的 date picker 直接喂它
scheduleDate: item.schedule?.date ? this.formatDate(item.schedule.date) : '',
scheduleDate: item.schedule?.date ? formatDate(item.schedule.date) : '',
scheduleStartTime: item.schedule?.startTime || '',
scheduleEndTime: item.schedule?.endTime || '',
scheduleDateText: scheduleMeta.dateText,
@@ -270,8 +250,8 @@ Page({
canEditOrder,
// 底栏只在确实有按钮时出现,避免无动作状态空留一条白栏
showBottomBar: canCancel || canDelete || canRebook,
createTime: item.meta?.createtime ? this.formatDateTime(item.meta.createtime) : '',
updateTime: item.meta?.updatetime ? this.formatDateTime(item.meta.updatetime) : ''
createTime: item.meta?.createtime ? formatDateTime(item.meta.createtime) : '',
updateTime: item.meta?.updatetime ? formatDateTime(item.meta.updatetime) : ''
}
},
@@ -301,8 +281,8 @@ Page({
buildScheduleMeta(schedule) {
const result = { dateText: '', timeText: '' }
if (schedule.date) {
const d = new Date(schedule.date)
if (!isNaN(d.getTime())) {
const d = parseDate(schedule.date)
if (d) {
result.dateText = `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日 ${WEEKDAYS[d.getDay()]}`
}
}
@@ -322,43 +302,6 @@ Page({
return result
},
// 根据出生年月(YYYY-MM-DD)计算年龄
calcAge(birth) {
if (!birth) return 0
const d = new Date(birth)
if (isNaN(d.getTime())) return 0
const now = new Date()
let age = now.getFullYear() - d.getFullYear()
const m = now.getMonth() - d.getMonth()
if (m < 0 || (m === 0 && now.getDate() < d.getDate())) age--
return age > 0 ? age : 0
},
formatDate(dateStr) {
const d = new Date(dateStr)
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}`
},
formatDateTime(dateStr) {
const d = new Date(dateStr)
const year = d.getFullYear()
const month = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
const hour = String(d.getHours()).padStart(2, '0')
const minute = String(d.getMinutes()).padStart(2, '0')
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
+3 -27
View File
@@ -1,21 +1,6 @@
const API = require('../../utils/api.js')
// 状态配色遵循 doc/DESIGN.md §三,颜色只作强化,文字才是信息。
const STATUS_MAP = {
pending: { text: '待确认', color: '#0F766E', bg: '#ECF7F4', border: '#C7E5DF' },
confirmed: { text: '已确认', color: '#0F766E', bg: '#ECF7F4', border: '#C7E5DF' },
in_progress: { text: '进行中', color: '#B8520A', bg: '#FFF4E8', border: '#FFE0C2' },
completed: { text: '已完成', color: '#1F7A4D', bg: '#EAF6EE', border: '#CDE9D7' },
cancelled: { text: '已取消', color: '#B4231A', bg: '#FCF0EE', border: '#F2D6D1' }
}
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' }
}
const { formatDate } = require('../../utils/date.js')
const { STATUS_MAP, PAYMENT_STATUS_MAP } = require('../../utils/order.js')
// 左右滑动切换状态页的手势参数(单位 px)
const SWIPE_THRESHOLD = 50
@@ -120,7 +105,7 @@ Page({
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()
? `${formatDate(item.schedule.date, '--')} ${item.schedule.startTime || ''}`.trim()
: '--'
return {
@@ -142,15 +127,6 @@ Page({
}
},
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}`
},
onTabChange(e) {
this.switchStatusTab(Number(e.currentTarget.dataset.index))
},
+147 -136
View File
@@ -1,24 +1,25 @@
const API = require('../../utils/api.js')
const { parseDate, formatDate } = require('../../utils/date.js')
const { setUnsavedGuard } = require('../../utils/form.js')
// 性别选项,与后端 schema 的 male / female 对应
const SEX_OPTIONS = [{
value: 'male',
label: '男'
},
{
value: 'female',
label: '女'
}
const SEX_OPTIONS = [
{ value: 'male', label: '男' },
{ value: 'female', label: '女' }
]
const MOBILE_REGEX = /^1[3-9]\d{9}$/
const ID_NUMBER_REGEX = /^\d{17}[\dXx]$/
Page({
data: {
id: '',
isEdit: false,
saving: false,
loading: false,
loadError: '',
today: '',
errors: {},
sexOptions: SEX_OPTIONS,
form: {
name: '',
@@ -34,11 +35,13 @@ Page({
onLoad(options) {
const id = options.id || ''
this.unsavedGuardActive = false
this.initialFormSnapshot = ''
this.setData({
id,
isEdit: !!id,
today: this.formatDate(new Date())
today: formatDate(new Date())
})
wx.setNavigationBarTitle({
@@ -47,59 +50,71 @@ Page({
if (id) {
this.loadProfile(id)
} else {
this.captureInitialForm()
}
},
formatDate(date) {
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
onUnload() {
if (this.unsavedGuardActive) setUnsavedGuard(false)
},
// 编辑模式:读取档案详情回填表单
loadProfile(id) {
API.healthProfile.getMyProfileById(id)
.then((res) => {
if (res.code !== 0) {
wx.showToast({
title: res.msg || '加载失败',
icon: 'none'
})
return
}
const detail = (res.data && res.data.profile) || {}
const profile = detail.profile || {}
const health = detail.health || {}
captureInitialForm() {
this.initialFormSnapshot = JSON.stringify(this.data.form)
this.syncUnsavedGuard()
},
this.setData({
form: {
name: profile.name || '',
sex: profile.sex || '',
birth: profile.birth || '',
mobile: profile.mobile || '',
idnumber: profile.idnumber || '',
// 身高的 schema 默认值是 0,0 视为未填写,回填成空串而不是 "0"
height: health.height ? String(health.height) : '',
weight: health.weight ? String(health.weight) : '',
remark: health.remark || ''
}
})
})
.catch((err) => {
console.log('获取就诊人信息失败', err)
wx.showToast({
title: '网络请求失败',
icon: 'none'
})
syncUnsavedGuard() {
const dirty = JSON.stringify(this.data.form) !== this.initialFormSnapshot
if (dirty === this.unsavedGuardActive) return
this.unsavedGuardActive = dirty
setUnsavedGuard(dirty)
},
// 编辑模式:读取档案详情回填表单;失败时不能用空表单冒充已加载。
async loadProfile(id) {
this.setData({ loading: true, loadError: '' })
try {
const res = await API.healthProfile.getMyProfileById(id)
if (res.code !== 0) throw new Error(res.msg || '就诊人信息加载失败')
const detail = (res.data && res.data.profile) || {}
const profile = detail.profile || {}
const health = detail.health || {}
this.setData({
form: {
name: profile.name || '',
sex: profile.sex || '',
birth: formatDate(profile.birth),
mobile: profile.mobile || '',
idnumber: profile.idnumber || '',
// 身高的 schema 默认值是 0,0 视为未填写,回填成空串而不是 "0"
height: health.height ? String(health.height) : '',
weight: health.weight ? String(health.weight) : '',
remark: health.remark || ''
}
})
this.captureInitialForm()
} catch (err) {
console.log('获取就诊人信息失败', err)
this.setData({ loadError: err.message || '网络请求失败,请重试' })
} finally {
this.setData({ loading: false })
}
},
retryLoad() {
if (this.data.id) this.loadProfile(this.data.id)
},
onFieldInput(e) {
const field = e.currentTarget.dataset.field
this.setData({
[`form.${field}`]: e.detail.value
[`form.${field}`]: e.detail.value,
[`errors.${field}`]: ''
})
this.syncUnsavedGuard()
},
onSexSelect(e) {
@@ -108,80 +123,97 @@ Page({
this.setData({
'form.sex': this.data.form.sex === sex ? '' : sex
})
this.syncUnsavedGuard()
},
onBirthChange(e) {
this.setData({
'form.birth': e.detail.value
'form.birth': e.detail.value,
'errors.birth': ''
})
this.syncUnsavedGuard()
},
// 表单校验,返回错误提示文案;通过校验返回空字符串
validateOptionalNumber(value, min, max) {
if (!value.trim()) return true
const number = Number(value)
return Number.isFinite(number) && number >= min && number <= max
},
// 返回字段错误表,WXML 在对应字段下展示,保存时同时提示首个错误。
validate() {
const {
name,
mobile
} = this.data.form
const { name, mobile, birth, idnumber, height, weight } = this.data.form
const errors = {}
if (!name.trim()) {
return '请输入就诊人姓名'
}
if (!name.trim()) errors.name = '请输入就诊人姓名'
if (!mobile.trim()) {
return '请输入联系电话'
errors.mobile = '请输入联系电话'
} else if (!MOBILE_REGEX.test(mobile.trim())) {
errors.mobile = '请输入正确的 11 位手机号'
}
if (!MOBILE_REGEX.test(mobile.trim())) {
return '请输入正确的手机号'
if (birth) {
const birthDate = parseDate(birth)
if (!birthDate) {
errors.birth = '请选择有效的出生日期'
} else if (birthDate < parseDate('1900-01-01') || birthDate > parseDate(this.data.today)) {
errors.birth = '出生日期需在 1900-01-01 至今天之间'
}
}
return ''
if (idnumber.trim()) {
const value = idnumber.trim()
if (!ID_NUMBER_REGEX.test(value)) {
errors.idnumber = '请输入 18 位身份证号,末位可为 X'
} else {
const idBirth = `${value.slice(6, 10)}-${value.slice(10, 12)}-${value.slice(12, 14)}`
if (!parseDate(idBirth)) errors.idnumber = '身份证号中的出生日期无效'
}
}
if (!this.validateOptionalNumber(height, 30, 250)) {
errors.height = '身高需为 30–250 cm 的数字'
}
if (!this.validateOptionalNumber(weight, 2, 300)) {
errors.weight = '体重需为 2–300 kg 的数字'
}
return errors
},
onSave() {
if (this.data.saving) {
async onSave() {
if (this.data.saving) return
const errors = this.validate()
const firstError = Object.values(errors)[0]
this.setData({ errors })
if (firstError) {
wx.showToast({ title: firstError, icon: 'none' })
return
}
const errorMessage = this.validate()
if (errorMessage) {
wx.showToast({
title: errorMessage,
icon: 'none'
})
return
}
const { name, sex, birth, mobile, idnumber, height, weight, remark } = this.data.form
// 可选数值留空才写 0;所有非空值已通过校验,不再用 || 0 吞掉非法输入。
const heightNum = height.trim() ? Number(height) : 0
const weightNum = weight.trim() ? Number(weight) : 0
const {
name,
sex,
birth,
mobile,
idnumber,
height,
weight,
remark
} = this.data.form
// schema 里身高/体重是 Number,未填按 0(Number('') 即 0,非法输入 NaN 也回落 0)
const heightNum = Number(height) || 0
const weightNum = Number(weight) || 0
// 新增用嵌套对象(schema 的 new Model 需要嵌套结构);
// 更新用点号路径(schema 更新姓名时会额外写 profile.pinyin,整体替换 profile 会冲突)
// 新增用嵌套对象;更新用点号路径,避免与后端 profile.pinyin 的额外写入冲突。
const payload = this.data.isEdit ? {
'profile.name': name.trim(),
'profile.sex': sex,
'profile.birth': birth,
'profile.mobile': mobile.trim(),
'profile.idnumber': idnumber.trim(),
'profile.idnumber': idnumber.trim().toUpperCase(),
'health.height': heightNum,
'health.weight': weightNum,
'health.remark': remark.trim()
} : {
profile: {
name: name.trim(),
sex: sex,
birth: birth,
sex,
birth,
mobile: mobile.trim(),
idnumber: idnumber.trim()
idnumber: idnumber.trim().toUpperCase()
},
health: {
height: heightNum,
@@ -190,53 +222,32 @@ Page({
}
}
this.setData({
saving: true
})
wx.showLoading({
title: '保存中...'
})
this.setData({ saving: true })
wx.showLoading({ title: '保存中...' })
const request = this.data.isEdit ?
API.healthProfile.updateMyProfile(this.data.id, payload) :
API.healthProfile.createMyProfile(payload)
try {
const request = this.data.isEdit
? API.healthProfile.updateMyProfile(this.data.id, payload)
: API.healthProfile.createMyProfile(payload)
const res = await request
if (res.code !== 0) {
wx.showToast({ title: res.msg || '保存失败', icon: 'none' })
return
}
request
.then((res) => {
wx.hideLoading()
if (res.code !== 0) {
wx.showToast({
title: res.msg || '保存失败',
icon: 'none'
})
return
}
wx.showToast({
title: '保存成功',
icon: 'success'
})
setTimeout(() => {
wx.navigateBack()
}, 800)
})
.catch((err) => {
wx.hideLoading()
console.log('保存就诊人失败', err)
wx.showToast({
title: '网络请求失败',
icon: 'none'
})
})
.finally(() => {
this.setData({
saving: false
})
})
this.captureInitialForm()
wx.showToast({ title: '保存成功', icon: 'success' })
setTimeout(() => wx.navigateBack(), 800)
} catch (err) {
console.log('保存就诊人失败', err)
wx.showToast({ title: '网络请求失败', icon: 'none' })
} finally {
wx.hideLoading()
this.setData({ saving: false })
}
},
// 本页是就诊人档案表单(姓名 / 手机号 / 身份证号),转发卡片不指向本页,
// 统一落到首页,避免好友打开一个需要登录的空表单;
// 也不提供朋友圈分享——朋友圈只能分享当前页 URL,会把档案页地址带出去
// 转发卡片统一落到首页,避免好友打开需要登录的空表单。
onShareAppMessage() {
return {
title: '暖橙陪诊 · 专业陪诊服务',
+22 -6
View File
@@ -1,12 +1,23 @@
<view class="container">
<!-- 编辑模式先等待档案回填;加载失败时展示真实错误态,不露出可保存的空表单。 -->
<view class="page-state" wx:if="{{loading}}">
<t-loading size="48rpx" />
<text class="page-state-text">正在加载就诊人信息</text>
</view>
<view class="page-state" wx:if="{{isEdit && !loading && loadError}}">
<text class="page-state-text">{{loadError}}</text>
<view class="page-retry" bindtap="retryLoad">重新加载</view>
</view>
<!-- 基本信息:通栏白块(白面 + 上下 2rpx 发丝线 + 中性阴影,圆角 0),
行内标签左走 --muted、值右走 --ink 700,与「个人信息」「邮寄地址」同一表单语言 -->
<view class="form-card">
<view class="form-card" wx:if="{{!loading && !loadError}}">
<view class="form-row">
<text class="form-label">姓名</text>
<input class="form-input" value="{{form.name}}" placeholder="请输入就诊人姓名" placeholder-class="form-placeholder"
maxlength="20" data-field="name" bindinput="onFieldInput" />
<text class="field-error" wx:if="{{errors.name}}">{{errors.name}}</text>
</view>
<view class="form-row">
@@ -28,34 +39,39 @@
{{form.birth || '请选择出生年月'}}
</view>
</picker>
<text class="field-error" wx:if="{{errors.birth}}">{{errors.birth}}</text>
</view>
<view class="form-row">
<text class="form-label">联系电话</text>
<input class="form-input" value="{{form.mobile}}" type="number" placeholder="用于陪诊师联系您" placeholder-class="form-placeholder"
maxlength="11" data-field="mobile" bindinput="onFieldInput" />
<text class="field-error" wx:if="{{errors.mobile}}">{{errors.mobile}}</text>
</view>
<view class="form-row form-row-last">
<text class="form-label">证件号</text>
<input class="form-input" value="{{form.idnumber}}" placeholder="选填,用于医院建档取号" placeholder-class="form-placeholder"
maxlength="30" data-field="idnumber" bindinput="onFieldInput" />
maxlength="18" data-field="idnumber" bindinput="onFieldInput" />
<text class="field-error" wx:if="{{errors.idnumber}}">{{errors.idnumber}}</text>
</view>
</view>
<!-- 健康信息:身高/体重是短输入,沿用行内表单语言(标签左、值右);健康备注是多行输入,
无法与标签同排,故留在本块末尾单独一排——标签在上、文本域在下、字数右下 -->
<view class="form-card">
<view class="form-card" wx:if="{{!loading && !loadError}}">
<view class="form-row">
<text class="form-label">身高(cm)</text>
<input class="form-input" value="{{form.height}}" type="digit" placeholder="选填,单位 cm" placeholder-class="form-placeholder"
maxlength="5" data-field="height" bindinput="onFieldInput" />
<text class="field-error" wx:if="{{errors.height}}">{{errors.height}}</text>
</view>
<view class="form-row">
<text class="form-label">体重(kg)</text>
<input class="form-input" value="{{form.weight}}" type="digit" placeholder="选填,单位 kg" placeholder-class="form-placeholder"
maxlength="5" data-field="weight" bindinput="onFieldInput" />
<text class="field-error" wx:if="{{errors.weight}}">{{errors.weight}}</text>
</view>
<view class="form-remark">
@@ -66,14 +82,14 @@
</view>
</view>
<view class="tips">
<view class="tips" wx:if="{{!loading && !loadError}}">
<t-icon name="lock-on" class="tips-icon" size="26rpx" />
<text class="tips-text">信息仅用于陪诊服务,我们会严格保密</text>
</view>
<!-- 保存是本页唯一的实心暖橙块,独占「全页同类实心块不超过一处」的额度 -->
<view class="footer-bar">
<view class="footer-bar" wx:if="{{!loading && !loadError}}">
<button class="primary-btn {{saving ? 'primary-btn-disabled' : ''}}" bindtap="onSave">保存</button>
</view>
</view>
</view>
+36
View File
@@ -11,6 +11,32 @@ page {
padding: 40rpx 32rpx calc(180rpx + env(safe-area-inset-bottom));
}
/* ===== 加载与失败状态 ===== */
.page-state {
display: flex;
flex-direction: column;
align-items: center;
padding: 120rpx 32rpx;
}
.page-state-text {
margin-top: 20rpx;
font-size: 28rpx;
line-height: 1.6;
color: var(--muted);
text-align: center;
}
.page-retry {
margin-top: 24rpx;
padding: 12rpx 28rpx;
border: 2rpx solid var(--brand-strong);
border-radius: 28rpx;
font-size: 26rpx;
font-weight: 500;
color: var(--brand-strong);
}
/* ===== 通栏白块 =====
白面 + 上下各 2rpx 发丝线 + 中性阴影,圆角 0;
负向 margin 抵消容器 32rpx 内距后左右顶到屏幕两侧,
@@ -31,12 +57,22 @@ page {
/* 行高约 87rpx(28rpx×1.4 + 上下 24rpx),贴近 iOS 44pt 触控目标 */
.form-row {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
padding: 24rpx 32rpx;
border-bottom: 2rpx solid var(--line);
}
.field-error {
width: 100%;
margin-top: 12rpx;
font-size: 24rpx;
line-height: 1.5;
color: #B4231A;
text-align: right;
}
.form-row-last {
border-bottom: none;
}
+32 -45
View File
@@ -1,9 +1,12 @@
const API = require('../../utils/api.js')
const { formatDate } = require('../../utils/date.js')
const { maskIdNumber } = require('../../utils/privacy.js')
Page({
data: {
profiles: [],
loading: false
loading: false,
loadError: ''
},
// 用 onShow 而不是 onLoad:从新增/编辑页返回后需要刷新列表
@@ -17,41 +20,34 @@ Page({
})
},
// 拉取当前登录用户的就诊人列表
loadProfiles() {
this.setData({
loading: true
})
// 拉取当前登录用户的就诊人列表;空数组只在请求成功后展示为空态。
async loadProfiles() {
this.setData({ loading: true, loadError: '' })
return API.healthProfile.getMyProfiles({
page: 1,
pageSize: 50
})
.then((res) => {
if (res.code !== 0) {
wx.showToast({
title: res.msg || '加载失败',
icon: 'none'
})
return
}
const list = (res.data && res.data.list) || []
this.setData({
profiles: list.map((item) => this.formatProfile(item))
})
})
.catch((err) => {
console.log('获取就诊人失败', err)
wx.showToast({
title: '网络请求失败',
icon: 'none'
})
})
.finally(() => {
this.setData({
loading: false
})
try {
await getApp().waitForAuth()
const res = await API.healthProfile.getMyProfiles({ page: 1, pageSize: 50 })
if (res.code !== 0) throw new Error(res.msg || '就诊人加载失败')
const list = (res.data && res.data.list) || []
this.setData({
profiles: list.map((item) => this.formatProfile(item))
})
} catch (err) {
console.log('获取就诊人失败', err)
if (this.data.profiles.length === 0) {
this.setData({ loadError: err.message || '网络请求失败,请重试' })
} else {
// 已有成功数据时保留列表,刷新失败不打断查看和编辑。
wx.showToast({ title: '刷新失败,请重试', icon: 'none' })
}
} finally {
this.setData({ loading: false })
}
},
retryLoad() {
this.loadProfiles()
},
// 后端返回的是嵌套结构,这里拍平成卡片展示需要的字段
@@ -63,13 +59,13 @@ Page({
// 顺序:出生年月 → 联系电话 → 证件号(脱敏)
const metaList = []
if (profile.birth) {
metaList.push(profile.birth)
metaList.push(formatDate(profile.birth, profile.birth))
}
if (profile.mobile) {
metaList.push(profile.mobile)
}
if (profile.idnumber) {
metaList.push(this.maskIdNumber(profile.idnumber))
metaList.push(maskIdNumber(profile.idnumber))
}
return {
@@ -83,15 +79,6 @@ Page({
}
},
// 证件号脱敏:仅保留前 4 位与后 4 位(只在有值时调用)
maskIdNumber(idnumber) {
const value = String(idnumber || '')
if (value.length <= 8) {
return value
}
return `${value.slice(0, 4)}********${value.slice(-4)}`
},
onAdd() {
wx.navigateTo({
url: '/pages/health/profileedit'
+7 -1
View File
@@ -46,8 +46,14 @@
</view>
</view>
<!-- 请求失败与真实空态分开,失败时提供原地重试。 -->
<view class="load-error" wx:if="{{!loading && loadError}}">
<text class="load-error-text">{{loadError}}</text>
<view class="retry-btn" bindtap="retryLoad">重新加载</view>
</view>
<!-- 空状态 -->
<view class="profile-empty" wx:if="{{!loading && profiles.length === 0}}">
<view class="profile-empty" wx:if="{{!loading && !loadError && profiles.length === 0}}">
<t-icon name="user-checked" class="profile-empty-icon" size="80rpx" />
<text class="profile-empty-text">还没有就诊人,添加后下单即可一键带入</text>
</view>
+25
View File
@@ -183,6 +183,31 @@ page {
white-space: nowrap;
}
/* ===== 加载失败 ===== */
.load-error {
display: flex;
flex-direction: column;
align-items: center;
padding: 100rpx 32rpx;
}
.load-error-text {
font-size: 28rpx;
line-height: 1.6;
color: var(--muted);
text-align: center;
}
.retry-btn {
margin-top: 24rpx;
padding: 12rpx 28rpx;
border: 2rpx solid var(--brand-strong);
border-radius: 28rpx;
font-size: 26rpx;
font-weight: 500;
color: var(--brand-strong);
}
/* ===== 空态 ===== */
.profile-empty {
display: flex;
+30 -29
View File
@@ -1,5 +1,7 @@
// pages/mine/profileedit.js
const API = require('../../utils/api.js')
const { formatDate, toISOString } = require('../../utils/date.js')
const { setUnsavedGuard } = require('../../utils/form.js')
Page({
data: {
@@ -18,13 +20,28 @@ Page({
},
onLoad() {
const today = new Date()
this.setData({
today: `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
})
this.unsavedGuardActive = false
this.initialEditSnapshot = ''
this.setData({ today: formatDate(new Date()) })
this.initEditData()
},
onUnload() {
if (this.unsavedGuardActive) setUnsavedGuard(false)
},
captureInitialForm() {
this.initialEditSnapshot = JSON.stringify(this.data.editData)
this.syncUnsavedGuard()
},
syncUnsavedGuard() {
const dirty = JSON.stringify(this.data.editData) !== this.initialEditSnapshot
if (dirty === this.unsavedGuardActive) return
this.unsavedGuardActive = dirty
setUnsavedGuard(dirty)
},
// 表单初值取自全局用户对象。页面栈上「我的」页的 onShow 读的也是它,
// 所以保存成功后必须回写 app.globalData.user,否则返回时看到的还是旧值
initEditData() {
@@ -33,52 +50,33 @@ Page({
const profile = user.profile || {}
const location = user.location || {}
let birth = ''
if (profile.birth) {
const date = new Date(profile.birth)
birth = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}
this.setData({
editData: {
// 空字符串表示"无真头像",模板据此渲染浅橙底 + 暖陶土 user 线标的默认头像
// 头像修改暂未开放,这里只展示当前头像或默认头像。
avatar: profile.avatar || '',
name: profile.name || '',
phone: profile.mobile || '',
sex: profile.sex || '',
birth,
birth: formatDate(profile.birth),
province: location.province || '',
city: location.city || '',
district: location.district || ''
}
})
},
onChooseAvatar() {
wx.chooseMedia({
count: 1,
mediaType: ['image'],
sourceType: ['album', 'camera'],
success: (res) => {
// 微信返回的是本地临时路径,没有文件上传接口可落库,
// 故只在本次编辑中生效
this.setData({
'editData.avatar': res.tempFiles[0].tempFilePath
})
}
})
}, () => this.captureInitialForm())
},
onSelectSex(e) {
this.setData({
'editData.sex': e.currentTarget.dataset.sex
})
this.syncUnsavedGuard()
},
onBirthChange(e) {
this.setData({
'editData.birth': e.detail.value
})
this.syncUnsavedGuard()
},
onRegionChange(e) {
@@ -88,6 +86,7 @@ Page({
'editData.city': region[1] || '',
'editData.district': region[2] || ''
})
this.syncUnsavedGuard()
},
onFieldInput(e) {
@@ -95,6 +94,7 @@ Page({
this.setData({
[`editData.${field}`]: e.detail.value
})
this.syncUnsavedGuard()
},
onSave() {
@@ -117,7 +117,7 @@ Page({
profile: {
name: editData.name,
sex: editData.sex,
birth: editData.birth ? new Date(editData.birth).toISOString() : null,
birth: toISOString(editData.birth),
mobile: editData.phone
},
location: {
@@ -135,6 +135,7 @@ Page({
// 整替会把本机 token 抹掉,之后所有接口都变成未登录。security 保留本地那份
const prev = app.globalData.user || {}
app.globalData.user = { ...prev, ...data.data.user, security: prev.security || {} }
this.captureInitialForm()
wx.showToast({ title: '保存成功', icon: 'success' })
// 返回上一页(「我的」),由它的 onShow 重新读取全局对象
wx.navigateBack()
+3 -7
View File
@@ -7,19 +7,15 @@
行内沿用列表页/弹窗表单的语言:标签左走 --muted,值右走 --ink 加粗,
行间隔用 2rpx --line 发丝线 -->
<view class="form-card">
<!-- 头像:右侧 chevron 是"可换图"的点击暗示。
无真头像时渲染与「我的」页同一个默认底座(浅橙底 + 暖陶土 user 线标),
不再用 home-ink 位图——位图着色读不到令牌,换主色要整图重上色。
注:新选的图是微信本地临时路径,utils/api.js 无文件上传接口,
目前不会落库,只在本次编辑中生效 -->
<view class="form-row" bindtap="onChooseAvatar" hover-class="form-row-hover">
<!-- 头像修改暂未开放,此行只展示当前头像,不保留点击暗示。
无真头像时渲染与「我的」页同一个默认底座(浅橙底 + 暖陶土 user 线标)。 -->
<view class="form-row">
<text class="form-label">头像</text>
<view class="avatar-wrap">
<view class="avatar avatar-default" wx:if="{{!editData.avatar}}">
<t-icon name="user" size="48rpx" color="#9B4508" />
</view>
<image class="avatar" wx:else src="{{editData.avatar}}" mode="aspectFill"></image>
<t-icon name="chevron-right" class="form-arrow" size="32rpx" />
</view>
</view>
+63
View File
@@ -0,0 +1,63 @@
// 小程序各端对 new Date('YYYY-MM-DD') 的解析并不一致,纯日期统一按本地年月日构造。
function parseDate(value) {
if (value instanceof Date) {
return Number.isNaN(value.getTime()) ? null : value
}
if (!value) return null
const text = String(value)
const dateOnly = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text)
if (dateOnly) {
const year = Number(dateOnly[1])
const month = Number(dateOnly[2])
const day = Number(dateOnly[3])
const date = new Date(year, month - 1, day)
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
return null
}
return date
}
const date = new Date(text)
return Number.isNaN(date.getTime()) ? null : date
}
function pad(value) {
return String(value).padStart(2, '0')
}
function formatDate(value, fallback = '') {
const date = parseDate(value)
if (!date) return fallback
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
}
function formatDateTime(value, fallback = '') {
const date = parseDate(value)
if (!date) return fallback
return `${formatDate(date)} ${pad(date.getHours())}:${pad(date.getMinutes())}`
}
function calcAge(value) {
const birth = parseDate(value)
if (!birth) return 0
const today = new Date()
let age = today.getFullYear() - birth.getFullYear()
const monthDelta = today.getMonth() - birth.getMonth()
if (monthDelta < 0 || (monthDelta === 0 && today.getDate() < birth.getDate())) age--
return age > 0 && age <= 120 ? age : 0
}
function toISOString(value) {
const date = parseDate(value)
return date ? date.toISOString() : null
}
module.exports = {
parseDate,
formatDate,
formatDateTime,
calcAge,
toISOString
}
+16
View File
@@ -0,0 +1,16 @@
// 使用微信原生返回拦截,导航栏返回和手势返回都不会静默丢失未保存内容。
function setUnsavedGuard(enabled) {
if (enabled && wx.canIUse('enableAlertBeforeUnload')) {
wx.enableAlertBeforeUnload({
message: '当前修改尚未保存,确定要离开吗?'
})
return
}
if (!enabled && wx.canIUse('disableAlertBeforeUnload')) {
wx.disableAlertBeforeUnload()
}
}
module.exports = {
setUnsavedGuard
}
+21
View File
@@ -0,0 +1,21 @@
// 订单与支付状态的唯一前端映射,列表和详情只按展示需要读取不同扩展字段。
const STATUS_MAP = {
pending: { text: '待确认', color: '#0F766E', bg: '#ECF7F4', border: '#C7E5DF', desc: '订单已提交,等待陪诊师确认;确认前可取消' },
confirmed: { text: '已确认', color: '#0F766E', bg: '#ECF7F4', border: '#C7E5DF', desc: '订单已确认,陪诊师将准时为您服务' },
in_progress: { text: '进行中', color: '#B8520A', bg: '#FFF4E8', border: '#FFE0C2', desc: '陪诊服务正在进行中' },
completed: { text: '已完成', color: '#1F7A4D', bg: '#EAF6EE', border: '#CDE9D7', desc: '陪诊服务已完成,感谢您的使用' },
cancelled: { text: '已取消', color: '#B4231A', bg: '#FCF0EE', border: '#F2D6D1', desc: '该订单已取消' }
}
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' }
}
module.exports = {
STATUS_MAP,
PAYMENT_STATUS_MAP
}
+16
View File
@@ -0,0 +1,16 @@
function maskIdNumber(value) {
const text = String(value || '').trim()
if (!text) return ''
if (text.length <= 8) return '********'
return `${text.slice(0, 4)}********${text.slice(-4)}`
}
function maskOrderId(value) {
const text = String(value || '').trim()
return text ? `****${text.slice(-8).toUpperCase()}` : '--'
}
module.exports = {
maskIdNumber,
maskOrderId
}