Files
wxapp_companion/pages/order/index.js
T
lik d70d9703ad feat(order): 订单池接单与共享入口,实习陪诊师只读
列表展示未分配/共享给我标记并新增接单按钮;详情页支持接单与共享给在职陪诊师,实习仅可查看脱敏信息。
2026-11-10 12:28:06 +08:00

417 lines
12 KiB
JavaScript

// pages/order/index.js
const API = require('../../utils/api.js')
const { calcAge } = require('../../utils/format.js')
const role = require('../../utils/role.js')
// 状态映射配置
const STATUS_MAP = {
pending: { label: '待确认', text: '待确认', color: '#D98E04' },
confirmed: { label: '已确认', text: '已确认', color: '#3E6E9E' },
cancel_requested: { label: '待取消', text: '待取消', color: '#C0564A' },
in_progress: { label: '进行中', text: '进行中', color: '#C26A2E' },
completed: { label: '已完成', text: '已完成', color: '#8A7BB5' },
cancelled: { label: '已取消', text: '已取消', color: '#C0564A' }
};
// 状态筛选选项
const STATUS_FILTERS = [
{ label: '全部', value: '', count: 0 },
{ label: '待确认', value: 'pending', count: 0 },
{ label: '待取消', value: 'cancel_requested', count: 0 },
{ label: '已确认', value: 'confirmed', count: 0 },
{ label: '进行中', value: 'in_progress', count: 0 },
{ label: '已完成', value: 'completed', count: 0 },
{ label: '已取消', value: 'cancelled', count: 0 }
];
// 取消与 status 解耦:展示状态优先取 cancelStatus
function resolveDisplayStatus(order) {
const cancelStatus = order?.cancelStatus || 'none'
if (cancelStatus === 'cancelled') return 'cancelled'
if (cancelStatus === 'requested') return 'cancel_requested'
return order?.status || 'pending'
}
// 页签 → 服务端筛选参数:筛选、分页、计数全部交给后端,避免按当前页过滤
function buildTabFilter(status) {
switch (status) {
case '':
return { includeCancelled: 1 }
case 'pending':
return { status: 'pending', cancelStatus: 'none' }
case 'cancel_requested':
return { cancelStatus: 'requested' }
case 'confirmed':
return { status: 'confirmed', cancelStatus: 'none' }
case 'in_progress':
return { status: 'in_progress', cancelStatus: 'none' }
case 'completed':
return { status: 'completed', cancelStatus: 'none' }
case 'cancelled':
return { cancelStatus: 'cancelled' }
default:
return {}
}
}
Page({
/**
* 页面的初始数据
*/
data: {
// 角色:管理员可新增预约,陪诊员只看订单池/本人订单
role: '',
isAdmin: false,
// 实习陪诊师:能看到未分配订单,但不能接单
isIntern: false,
// 统计
stats: {
total: 0,
pending: 0,
cancelRequested: 0,
confirmed: 0,
inProgress: 0,
completed: 0,
cancelled: 0
},
// 状态筛选
statusFilters: STATUS_FILTERS,
currentStatus: 'pending',
// 订单列表
orderList: [],
// 分页
page: 1,
pageSize: 10,
hasMore: true,
// 加载状态
isLoading: false,
isLoadingMore: false,
isRefreshing: false
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
// 先解析角色:陪诊员走订单池接口,管理员走全量接口
role.ensureRoleSafe().then(({ role: r, attendant }) => {
this.setData({
role: r,
isAdmin: r === 'admin',
isIntern: Boolean(attendant && attendant.stage === 'intern')
})
this.loadOrderList();
})
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
if (this.data.orderList.length > 0) {
this.refreshData();
}
},
/**
* 更新筛选标签计数(口径由后端聚合,避免按当前页统计)
*/
updateFilterCounts(counts) {
const c = counts || {};
const countMap = {
'': c.all,
pending: c.pending,
cancel_requested: c.cancelRequested,
confirmed: c.confirmed,
in_progress: c.inProgress,
completed: c.completed,
cancelled: c.cancelled
};
const statusFilters = this.data.statusFilters.map(filter => ({
...filter,
count: Number(countMap[filter.value]) || 0
}));
this.setData({ statusFilters });
},
/**
* 格式化日期
*/
formatDate(dateStr) {
if (!dateStr) return '';
const date = new Date(dateStr);
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
return `${month}月${day}日`;
},
/**
* 处理订单数据
*/
processOrders(orders) {
return orders.map(order => {
const age = calcAge(order.patient?.birth)
const displayStatus = resolveDisplayStatus(order)
// 接单/共享标记由服务端按身份计算;未分配 = attendant.id 为空
const isPoolOrder = Boolean(order.isPoolOrder)
const assignedToMe = Boolean(order.attendantAssignedToMe)
return {
...order,
displayStatus,
statusText: STATUS_MAP[displayStatus]?.text || displayStatus,
patientFirstChar: (order.patient?.name || '?')[0],
patientAgeText: age ? `${age}岁` : '',
isPoolOrder,
assignedToMe,
sharedToMe: Boolean(order.attendantSharedToMe),
canAccept: !this.data.isAdmin && !this.data.isIntern && isPoolOrder,
// 状态流转只对自己已接的订单开放,管理员保持全量可操作
canOperate: this.data.isAdmin || assignedToMe,
schedule: {
...order.schedule,
dateText: this.formatDate(order.schedule?.date)
}
};
});
},
/**
* 加载订单列表:筛选、分页与计数全部使用服务端口径
*/
loadOrderList(isRefresh = false) {
if (this.data.isLoading || this.data.isLoadingMore) return;
const { currentStatus, page, pageSize } = this.data;
this.setData({ isLoading: !isRefresh, isLoadingMore: isRefresh && page > 1 });
const params = {
page,
pageSize,
...buildTabFilter(currentStatus)
};
role.queryOrders(params)
.then(res => {
if (res.code !== 0) {
wx.showToast({ title: res.msg || '获取订单失败', icon: 'none' });
this.setData({ isLoading: false, isLoadingMore: false, isRefreshing: false });
return;
}
const data = res.data || {};
const list = data.records || [];
const total = Number(data.total) || 0;
const processedOrders = this.processOrders(list);
const orderList = isRefresh && page > 1
? [...this.data.orderList, ...processedOrders]
: processedOrders;
this.updateFilterCounts(data.counts);
this.setData({
orderList,
// 头部总数用后端「全部」口径,页签内条数仍由 currentStatus 决定
stats: { ...this.data.stats, total: Number((data.counts || {}).all) || total },
isLoading: false,
isLoadingMore: false,
isRefreshing: false,
// total 由服务端返回,不能用当前页长度推断
hasMore: page * pageSize < total
});
})
.catch(err => {
console.error('获取订单列表失败', err);
wx.showToast({ title: '网络错误,请重试', icon: 'none' });
this.setData({ isLoading: false, isLoadingMore: false, isRefreshing: false });
});
},
/**
* 刷新数据
*/
refreshData() {
this.setData({ page: 1, hasMore: true }, () => {
this.loadOrderList();
});
},
/**
* 跳转新增预约(页面内选择健康档案)
*/
onAddOrder() {
wx.navigateTo({
url: '/pages/order/orderEdit'
});
},
/**
* 空状态刷新
*/
onReload() {
this.setData({ page: 1, hasMore: true }, () => {
this.loadOrderList();
});
},
/**
* 状态筛选切换
*/
onStatusChange(e) {
const status = e.currentTarget.dataset.status;
if (status === this.data.currentStatus) return;
this.setData({
currentStatus: status,
page: 1,
hasMore: true,
orderList: []
}, () => {
this.loadOrderList();
});
},
/**
* 订单详情
*/
onOrderDetail(e) {
const id = e.currentTarget.dataset.id;
wx.navigateTo({
url: `/pages/order/orderDetail?id=${id}`
});
},
/**
* 订单操作
*/
onOrderAction(e) {
const { id, action } = e.currentTarget.dataset;
const order = this.data.orderList.find(item => item._id === id);
if (!order) return;
if (action === 'accept') {
wx.showModal({
title: '确认接单',
content: '接单后该订单将从其他陪诊师的未分配列表中移除,确认接单?',
confirmColor: '#C26A2E',
success: (res) => {
if (res.confirm) this.acceptOrder(id);
}
});
return;
}
const isCancelRequest = action === 'cancel' && order.displayStatus === 'cancel_requested';
const actionMap = {
confirm: { title: '确认订单', content: '确认接受此订单?', nextStatus: 'confirmed' },
cancel: isCancelRequest
? { title: '同意取消', content: '同意取消该订单?已收款订单将进入退款流程。', nextStatus: 'cancelled' }
: { title: '取消订单', content: '确定要取消此订单?未确认且未收款的订单会被直接删除,已收款订单将进入退款。', nextStatus: 'cancelled' },
start: { title: '开始服务', content: '确认开始陪诊服务?', nextStatus: 'in_progress' },
complete: { title: '完成服务', content: '确认陪诊服务已完成?', nextStatus: 'completed' },
detail: { title: '', content: '', nextStatus: '' }
};
const actionConfig = actionMap[action];
if (!actionConfig) return;
if (action === 'detail') {
wx.navigateTo({
url: `/pages/order/orderDetail?id=${id}`
});
return;
}
wx.showModal({
title: actionConfig.title,
content: actionConfig.content,
confirmColor: '#C26A2E',
success: (res) => {
if (res.confirm) {
this.updateOrderStatus(id, actionConfig.nextStatus);
}
}
});
},
/**
* 接单:服务端会再次校验身份与订单是否已被接走
*/
acceptOrder(id) {
wx.showLoading({ title: '接单中...' });
API.escort.acceptRecord(id)
.then(res => {
wx.hideLoading();
if (res.code !== 0) {
wx.showToast({ title: res.msg || '接单失败', icon: 'none' });
this.refreshData();
return;
}
wx.showToast({ title: '接单成功', icon: 'success' });
this.refreshData();
})
.catch(err => {
console.error('接单失败', err);
wx.hideLoading();
wx.showToast({ title: '网络错误,请重试', icon: 'none' });
});
},
/**
* 更新订单状态
*/
updateOrderStatus(id, newStatus) {
wx.showLoading({ title: '处理中...' });
API.escort.updateStatus(id, { status: newStatus })
.then(res => {
wx.hideLoading();
if (res.code !== 0) {
wx.showToast({ title: res.msg || '操作失败', icon: 'none' });
return;
}
wx.showToast({ title: '操作成功', icon: 'success' });
// 取消可能物理删除订单,状态与计数以服务端为准,不做本地推断
this.refreshData();
})
.catch(err => {
console.error('更新订单状态失败', err);
wx.showToast({ title: '网络错误,请重试', icon: 'none' });
wx.hideLoading();
});
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
this.setData({ isRefreshing: true, page: 1, hasMore: true }, () => {
this.loadOrderList();
});
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
if (!this.data.hasMore || this.data.isLoadingMore) return;
this.setData({ page: this.data.page + 1 }, () => {
this.loadOrderList(true);
});
},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {
return {
title: '订单管理',
path: '/pages/order/index'
};
}
});