1078 lines
38 KiB
JavaScript
1078 lines
38 KiB
JavaScript
/**
|
||
* Purpose: orderApi supports index.js by holding or executing the order api page or API role.
|
||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
const orderApi = require('../../api/order')
|
||
const paymentApi = require('../../api/payment')
|
||
const afterSaleApi = require('../../api/after-sale')
|
||
const cartApi = require('../../api/cart')
|
||
/**
|
||
* Purpose: auth supports index.js by holding or executing the auth page or API role.
|
||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
const auth = require('../../utils/auth')
|
||
/**
|
||
* Purpose: navigation supports index.js by holding or executing the navigation page or API role.
|
||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
const navigation = require('../../utils/navigation')
|
||
/**
|
||
* Purpose: actionGuard supports index.js by holding or executing the action guard page or API role.
|
||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
const actionGuard = require('../../utils/action-guard')
|
||
/**
|
||
* Purpose: theme supports index.js by holding or executing the theme page or API role.
|
||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
const theme = require('../../utils/theme')
|
||
const { resolveLegacyImage } = require('../../utils/file')
|
||
const { formatDateTime, formatPrice, getOrderStatusClass, getOrderStatusText } = require('../../utils/format')
|
||
const { runWithLoading } = require('../../utils/loading')
|
||
const { buildRecoveryState, clearRecoveryState } = require('../../utils/recovery')
|
||
|
||
/**
|
||
* Purpose: REVIEW_SCORE_OPTIONS supports index.js by holding or executing the review score options page or API role.
|
||
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
const REVIEW_SCORE_OPTIONS = [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]
|
||
|
||
const PAYMENT_STATUS_TEXT = {
|
||
UNPAID: '待支付',
|
||
PAYING: '待确认支付',
|
||
PAID: '已支付',
|
||
REFUNDED: '已退款'
|
||
}
|
||
|
||
const AFTER_SALE_STATUS_TEXT = {
|
||
PENDING: '审核中',
|
||
APPROVED: '已通过',
|
||
REJECTED: '已拒绝'
|
||
}
|
||
|
||
/**
|
||
* Purpose: toId supports index.js by holding or executing the to id page or API role.
|
||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
function toId(value) {
|
||
return value === undefined || value === null ? '' : String(value)
|
||
}
|
||
|
||
/**
|
||
* Purpose: sameId supports index.js by holding or executing the same id page or API role.
|
||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
function sameId(left, right) {
|
||
const leftId = toId(left)
|
||
const rightId = toId(right)
|
||
return leftId !== '' && leftId === rightId
|
||
}
|
||
|
||
/**
|
||
* Purpose: safeList supports index.js by holding or executing the safe list page or API role.
|
||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
function safeList(value) {
|
||
return Array.isArray(value) ? value : []
|
||
}
|
||
|
||
/**
|
||
* Purpose: trimText supports index.js by holding or executing the trim text page or API role.
|
||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
function trimText(value) {
|
||
return String(value || '').trim()
|
||
}
|
||
|
||
function normalizeStatus(value) {
|
||
return String(value || '').trim().toUpperCase()
|
||
}
|
||
|
||
function firstFilled(values) {
|
||
return values.find(value => value !== undefined && value !== null && value !== '')
|
||
}
|
||
|
||
function toAmount(value) {
|
||
const amount = Number(value)
|
||
return isFinite(amount) ? amount : 0
|
||
}
|
||
|
||
function getOrderPayAmount(order) {
|
||
return toAmount(firstFilled([
|
||
order && order.payAmount,
|
||
order && order.actualAmount,
|
||
order && order.totalAmount
|
||
]))
|
||
}
|
||
|
||
function resolvePaymentStatus(order) {
|
||
const status = normalizeStatus(order && (order.paymentStatus || order.payStatus || order.paymentState))
|
||
if (status) {
|
||
return status
|
||
}
|
||
if (Number(order && order.status) === 2 || getOrderPayAmount(order) <= 0) {
|
||
return 'PAID'
|
||
}
|
||
return 'UNPAID'
|
||
}
|
||
|
||
function buildPaymentInfo(order) {
|
||
const status = resolvePaymentStatus(order)
|
||
const payAmount = getOrderPayAmount(order)
|
||
const paidAmount = toAmount(firstFilled([
|
||
order && order.paidAmount,
|
||
status === 'PAID' ? payAmount : ''
|
||
]))
|
||
return {
|
||
status,
|
||
statusText: PAYMENT_STATUS_TEXT[status] || status || '待支付',
|
||
statusClass: `payment-${status.toLowerCase() || 'unpaid'}`,
|
||
amountText: `¥${formatPrice(payAmount)}`,
|
||
paidAmountText: `¥${formatPrice(paidAmount)}`,
|
||
payNoText: (order && (order.paymentOrderNo || order.payNo)) || '',
|
||
canPay: status === 'UNPAID' || status === 'PAYING',
|
||
isPaid: status === 'PAID',
|
||
isRefunded: status === 'REFUNDED'
|
||
}
|
||
}
|
||
|
||
function getAfterSaleStatusText(record) {
|
||
const status = normalizeStatus(record && record.status)
|
||
return AFTER_SALE_STATUS_TEXT[status] || status || '已申请'
|
||
}
|
||
|
||
function buildAfterSaleSummary(record) {
|
||
if (!record) {
|
||
return null
|
||
}
|
||
const amount = firstFilled([record.refundAmount, record.amount])
|
||
return {
|
||
...record,
|
||
status: normalizeStatus(record.status),
|
||
statusText: getAfterSaleStatusText(record),
|
||
typeText: record.type === 'REFUND' ? '退款' : (record.type || '售后'),
|
||
amountText: amount === undefined || amount === null || amount === '' ? '' : `¥${formatPrice(amount)}`,
|
||
reasonText: trimText(record.reason),
|
||
auditReasonText: trimText(record.auditReason),
|
||
createdText: formatDateTime(record.createTime)
|
||
}
|
||
}
|
||
|
||
function latestRecordTime(record) {
|
||
return String((record && (record.auditTime || record.updateTime || record.createTime)) || '')
|
||
}
|
||
|
||
function extractListPayload(payload) {
|
||
if (Array.isArray(payload)) {
|
||
return payload
|
||
}
|
||
if (payload && Array.isArray(payload.list)) {
|
||
return payload.list
|
||
}
|
||
if (payload && Array.isArray(payload.records)) {
|
||
return payload.records
|
||
}
|
||
return []
|
||
}
|
||
|
||
function indexLatestAfterSaleByOrderId(list) {
|
||
return safeList(list).reduce((result, item) => {
|
||
const orderId = toId(item && item.orderId)
|
||
if (!orderId) {
|
||
return result
|
||
}
|
||
const current = result[orderId]
|
||
if (!current || latestRecordTime(item).localeCompare(latestRecordTime(current)) > 0) {
|
||
result[orderId] = item
|
||
}
|
||
return result
|
||
}, {})
|
||
}
|
||
|
||
function canApplyAfterSale(order, afterSaleSummary) {
|
||
const paymentInfo = order && order.paymentInfo ? order.paymentInfo : buildPaymentInfo(order)
|
||
const afterSaleStatus = normalizeStatus(afterSaleSummary && afterSaleSummary.status)
|
||
return paymentInfo.isPaid
|
||
&& Number(order && order.status) !== 3
|
||
&& afterSaleStatus !== 'PENDING'
|
||
&& afterSaleStatus !== 'APPROVED'
|
||
}
|
||
|
||
/**
|
||
* Purpose: formatRating supports index.js by holding or executing the format rating page or API role.
|
||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
function formatRating(value) {
|
||
const rating = Number(value)
|
||
if (!isFinite(rating) || rating <= 0) {
|
||
return ''
|
||
}
|
||
return rating % 1 === 0 ? String(rating) : rating.toFixed(1)
|
||
}
|
||
|
||
/**
|
||
* Purpose: isSubmittedReview supports index.js by holding or executing the is submitted review page or API role.
|
||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
function isSubmittedReview(review) {
|
||
if (!review) {
|
||
return false
|
||
}
|
||
if (Number(review.status) === 1) {
|
||
return true
|
||
}
|
||
return Boolean(review.rating)
|
||
}
|
||
|
||
/**
|
||
* Purpose: resolveRelatedRecord supports index.js by holding or executing the resolve related record page or API role.
|
||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
function resolveRelatedRecord(source, orderItemId) {
|
||
if (Array.isArray(source)) {
|
||
return source.find(item => sameId(item && item.orderItemId, orderItemId)) || null
|
||
}
|
||
if (source && typeof source === 'object') {
|
||
if (!source.orderItemId || sameId(source.orderItemId, orderItemId)) {
|
||
return source
|
||
}
|
||
}
|
||
return null
|
||
}
|
||
|
||
/**
|
||
* Purpose: buildReviewSummary supports index.js by holding or executing the build review summary page or API role.
|
||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
function buildReviewSummary(review) {
|
||
if (!review || !isSubmittedReview(review)) {
|
||
return null
|
||
}
|
||
const ratingText = formatRating(review.rating)
|
||
return {
|
||
...review,
|
||
ratingText,
|
||
contentText: trimText(review.content),
|
||
displayText: ratingText ? `已评价:${ratingText} 分` : (review.statusText || '已评价')
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Purpose: buildPendingReview supports index.js by holding or executing the build pending review page or API role.
|
||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
function buildPendingReview(review) {
|
||
if (!review || isSubmittedReview(review)) {
|
||
return null
|
||
}
|
||
return review
|
||
}
|
||
|
||
/**
|
||
* Purpose: formatImpactTime supports index.js by normalizing backend or order item appointment values for change summaries.
|
||
* Usage: call it when building user-visible artist-change cards and confirmation modal copy.
|
||
*/
|
||
function formatImpactTime(value) {
|
||
return formatDateTime(value)
|
||
}
|
||
|
||
/**
|
||
* Purpose: buildArtistChangeSummary supports index.js by holding or executing the build artist change summary page or API role.
|
||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
function buildArtistChangeSummary(request, orderItem) {
|
||
if (!request) {
|
||
return null
|
||
}
|
||
const originalName = request.originalArtistName || request.fromArtistName || (orderItem && orderItem.artistName) || '原美甲师'
|
||
const requestedName = request.requestedArtistName || request.toArtistName || '新美甲师'
|
||
const appointmentTime = formatImpactTime(request.appointmentTime || (orderItem && orderItem.appointmentTime))
|
||
const timeImpactText = request.timeImpactText || (request.timeAffected ? '预约时间可能调整' : '预约时间不变')
|
||
const priceImpactText = request.priceImpactText || (request.priceAffected ? '订单价格可能调整' : '价格不变')
|
||
const priceValue = request.priceAffected ? request.newPrice : (request.newPrice || request.originalPrice || (orderItem && orderItem.price))
|
||
const priceText = priceValue !== undefined && priceValue !== null && priceValue !== '' ? `¥${formatPrice(priceValue)}` : ''
|
||
const impactLines = [
|
||
appointmentTime ? `${timeImpactText}:${appointmentTime}` : timeImpactText,
|
||
priceText ? `${priceImpactText}:${priceText}` : priceImpactText
|
||
].filter(Boolean)
|
||
const originalArtistText = `原美甲师:${originalName}`
|
||
const requestedArtistText = `新美甲师:${requestedName}`
|
||
return {
|
||
...request,
|
||
originalArtistText,
|
||
requestedArtistText,
|
||
artistLines: [originalArtistText, requestedArtistText],
|
||
displayText: `改派申请:${originalName} → ${requestedName}`,
|
||
reasonText: trimText(request.reason),
|
||
impactLines,
|
||
confirmText: [
|
||
`原美甲师:${originalName}`,
|
||
`新美甲师:${requestedName}`,
|
||
request.reason ? `原因:${trimText(request.reason)}` : '',
|
||
...impactLines
|
||
].filter(Boolean).join('\n')
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Purpose: indexByOrderItemId supports index.js by holding or executing the index by order item id page or API role.
|
||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
function indexByOrderItemId(list) {
|
||
return safeList(list).reduce((result, item) => {
|
||
if (item && item.orderItemId) {
|
||
result[toId(item.orderItemId)] = item
|
||
}
|
||
return result
|
||
}, {})
|
||
}
|
||
|
||
/**
|
||
* Purpose: formatTimelineTime keeps timeline timestamps short enough for mini-program cards.
|
||
* Usage: call it while building the order lifecycle timeline from backend date fields.
|
||
*/
|
||
function formatTimelineTime(value) {
|
||
return formatDateTime(value) || ''
|
||
}
|
||
|
||
/**
|
||
* Purpose: latestChangeTime picks the most meaningful time from a change request record.
|
||
* Usage: use it when summarizing historical artist-change requests on the timeline.
|
||
*/
|
||
function latestChangeTime(request) {
|
||
return (request && (request.approvedTime || request.rejectedTime || request.reviewTime || request.createTime)) || ''
|
||
}
|
||
|
||
/**
|
||
* Purpose: buildOrderTimeline creates a compact lifecycle timeline for one order.
|
||
* Usage: call it after pending reviews, submitted reviews, and change requests are loaded.
|
||
*/
|
||
function buildOrderTimeline(order, orderReviews, changeRequests, pendingReviews) {
|
||
const items = safeList(order && order.items)
|
||
const firstAppointment = items.map(item => item && item.appointmentTime).find(Boolean)
|
||
const changes = safeList(changeRequests)
|
||
const latestChange = changes
|
||
.slice()
|
||
.sort((left, right) => String(latestChangeTime(right)).localeCompare(String(latestChangeTime(left))))[0]
|
||
const submittedReviews = safeList(orderReviews).filter(isSubmittedReview)
|
||
const hasPendingReview = safeList(pendingReviews).some(review => sameId(review && review.orderId, order && order.id))
|
||
const status = Number(order && order.status)
|
||
return [
|
||
{
|
||
key: 'created',
|
||
title: '已创建',
|
||
text: formatTimelineTime(order && order.createTime) || '已提交',
|
||
done: true,
|
||
active: false
|
||
},
|
||
{
|
||
key: 'appointment',
|
||
title: '预约时间',
|
||
text: formatTimelineTime(firstAppointment) || '待确认',
|
||
done: Boolean(firstAppointment),
|
||
active: status === 1
|
||
},
|
||
changes.length ? {
|
||
key: 'artist-change',
|
||
title: '改派记录',
|
||
text: `${changes.length} 次申请`,
|
||
subText: formatTimelineTime(latestChangeTime(latestChange)),
|
||
done: changes.every(request => String((request && request.status) || '').toUpperCase() !== 'PENDING'),
|
||
active: changes.some(request => String((request && request.status) || '').toUpperCase() === 'PENDING')
|
||
} : null,
|
||
{
|
||
key: status === 3 ? 'cancelled' : 'completed',
|
||
title: status === 3 ? '已取消' : '已完成',
|
||
text: formatTimelineTime(order && (order.completeTime || order.cancelTime || order.updateTime)) || (status === 2 ? '服务完成' : (status === 3 ? '订单已取消' : '等待服务')),
|
||
done: status === 2 || status === 3,
|
||
active: status === 2 || status === 3
|
||
},
|
||
{
|
||
key: 'review',
|
||
title: '评价',
|
||
text: submittedReviews.length ? '已评价' : (hasPendingReview ? '待评价' : '完成后可评价'),
|
||
subText: formatTimelineTime((submittedReviews[0] && (submittedReviews[0].reviewTime || submittedReviews[0].submitTime)) || ''),
|
||
done: submittedReviews.length > 0,
|
||
active: hasPendingReview
|
||
}
|
||
].filter(Boolean)
|
||
}
|
||
|
||
/**
|
||
* Purpose: safeCall supports index.js by holding or executing the safe call page or API role.
|
||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
async function safeCall(factory, fallbackValue) {
|
||
try {
|
||
const result = await factory()
|
||
return result === undefined || result === null ? fallbackValue : result
|
||
} catch (error) {
|
||
return fallbackValue
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Purpose: loadAssistData supports index.js by holding or executing the load assist data page or API role.
|
||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
async function loadAssistData(orders) {
|
||
const pendingReviewsPromise = safeCall(() => orderApi.listMyPendingReviews(), [])
|
||
const pendingChangesPromise = safeCall(() => orderApi.listMyPendingArtistChangeRequests(), [])
|
||
const afterSalesPromise = safeCall(() => afterSaleApi.getMyAfterSales({
|
||
page: 1,
|
||
size: 50
|
||
}), { list: [] })
|
||
const orderReviewListsPromise = Promise.all(orders.map(order => (
|
||
safeCall(() => orderApi.listOrderReviews(order.id), [])
|
||
)))
|
||
const orderChangeListsPromise = Promise.all(orders.map(order => (
|
||
safeCall(() => orderApi.listOrderArtistChangeRequests(order.id), [])
|
||
)))
|
||
const [pendingReviews, pendingChanges, afterSales, orderReviewLists, orderChangeLists] = await Promise.all([
|
||
pendingReviewsPromise,
|
||
pendingChangesPromise,
|
||
afterSalesPromise,
|
||
orderReviewListsPromise,
|
||
orderChangeListsPromise
|
||
])
|
||
|
||
const submittedReviews = []
|
||
safeList(orderReviewLists).forEach(list => {
|
||
safeList(list).forEach(review => {
|
||
if (isSubmittedReview(review)) {
|
||
submittedReviews.push(review)
|
||
}
|
||
})
|
||
})
|
||
|
||
return {
|
||
pendingReviewByItemId: indexByOrderItemId(pendingReviews),
|
||
submittedReviewByItemId: indexByOrderItemId(submittedReviews),
|
||
pendingChangeByItemId: indexByOrderItemId(pendingChanges),
|
||
afterSaleByOrderId: indexLatestAfterSaleByOrderId(extractListPayload(afterSales)),
|
||
pendingReviews,
|
||
reviewsByOrderId: safeList(orders).reduce((result, order, index) => {
|
||
result[toId(order && order.id)] = safeList(orderReviewLists[index])
|
||
return result
|
||
}, {}),
|
||
changesByOrderId: safeList(orders).reduce((result, order, index) => {
|
||
result[toId(order && order.id)] = safeList(orderChangeLists[index])
|
||
return result
|
||
}, {})
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Purpose: findReviewDraft supports index.js by holding or executing the find review draft page or API role.
|
||
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
function findReviewDraft(orders, reviewId) {
|
||
const reviewIdText = toId(reviewId)
|
||
for (let i = 0; i < orders.length; i += 1) {
|
||
const items = safeList(orders[i].items)
|
||
for (let j = 0; j < items.length; j += 1) {
|
||
const pendingReview = items[j].pendingReview
|
||
if (pendingReview && toId(pendingReview.id) === reviewIdText) {
|
||
return items[j].reviewDraft || {}
|
||
}
|
||
}
|
||
}
|
||
return {}
|
||
}
|
||
|
||
function normalizeRebookQuantity(quantity) {
|
||
const value = Number(quantity)
|
||
return isFinite(value) && value > 0 ? Math.max(1, Math.floor(value)) : 1
|
||
}
|
||
|
||
function getRebookableOrderItems(order) {
|
||
return safeList(order && order.items).filter(item => item && item.productId !== undefined && item.productId !== null)
|
||
}
|
||
|
||
function findOrderById(orders, orderId) {
|
||
const orderIdText = toId(orderId)
|
||
return safeList(orders).find(order => toId(order.id) === orderIdText) || null
|
||
}
|
||
|
||
Page({
|
||
data: Object.assign(theme.pageThemeData(getApp().globalData.shopTheme), {
|
||
loading: false,
|
||
isLoggedIn: false,
|
||
orders: [],
|
||
/**
|
||
* Purpose: focusOrderId stores an optional order id from message navigation so the target order can be surfaced.
|
||
* Usage: set it from onLoad route options and compare it while formatting order cards.
|
||
*/
|
||
focusOrderId: '',
|
||
reviewScoreOptions: REVIEW_SCORE_OPTIONS,
|
||
recoveryState: clearRecoveryState()
|
||
}),
|
||
|
||
/**
|
||
* Purpose: onLoad captures message or deep-link order ids before the order list is loaded.
|
||
* Usage: mini-program runtime passes route options; store orderId for highlighting after loadOrders.
|
||
*/
|
||
onLoad(options) {
|
||
this.setData({
|
||
focusOrderId: (options && options.orderId) || '',
|
||
focusOrderItemId: (options && options.orderItemId) || '',
|
||
focusReviewId: (options && options.reviewId) || '',
|
||
focusReviewMode: (options && options.review) || ''
|
||
})
|
||
},
|
||
|
||
/**
|
||
* Purpose: onShow supports index.js by holding or executing the on show page or API role.
|
||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
onShow() {
|
||
this.loadOrders()
|
||
},
|
||
|
||
async loadOrders() {
|
||
const isLoggedIn = auth.isLoggedIn()
|
||
this.setData({
|
||
isLoggedIn,
|
||
loading: isLoggedIn,
|
||
recoveryState: clearRecoveryState()
|
||
})
|
||
|
||
if (!isLoggedIn) {
|
||
this.setData({
|
||
orders: [],
|
||
loading: false,
|
||
recoveryState: clearRecoveryState()
|
||
})
|
||
return
|
||
}
|
||
|
||
try {
|
||
const orders = await orderApi.getOrderList()
|
||
const list = safeList(orders)
|
||
const assistData = await loadAssistData(list)
|
||
let resolvedFocusOrderId = this.data.focusOrderId
|
||
let resolvedFocusOrderItemId = this.data.focusOrderItemId
|
||
const targetReviewId = toId(this.data.focusReviewId)
|
||
if (!resolvedFocusOrderId && this.data.focusReviewMode === 'pending') {
|
||
const firstPending = safeList(assistData.pendingReviews)[0]
|
||
resolvedFocusOrderId = toId(firstPending && firstPending.orderId)
|
||
resolvedFocusOrderItemId = toId(firstPending && firstPending.orderItemId)
|
||
} else if (targetReviewId) {
|
||
const submittedReviews = Object.values(assistData.reviewsByOrderId || {}).reduce((all, reviews) => all.concat(safeList(reviews)), [])
|
||
const matchedReview = safeList(assistData.pendingReviews).concat(submittedReviews).find(review => sameId(review && review.id, targetReviewId))
|
||
resolvedFocusOrderId = toId(matchedReview && matchedReview.orderId) || resolvedFocusOrderId
|
||
resolvedFocusOrderItemId = toId(matchedReview && matchedReview.orderItemId) || resolvedFocusOrderItemId
|
||
}
|
||
const formattedOrders = await Promise.all(list.map(async order => ({
|
||
...order,
|
||
focusTarget: sameId(order.id, resolvedFocusOrderId),
|
||
statusText: getOrderStatusText(order),
|
||
statusClass: getOrderStatusClass(order),
|
||
shopNameText: order.shopName ? `所属店铺:${order.shopName}` : '',
|
||
actualAmountText: `\u00a5${formatPrice(order.actualAmount)}`,
|
||
paymentInfo: buildPaymentInfo(order),
|
||
afterSaleSummary: buildAfterSaleSummary(order.afterSaleSummary || assistData.afterSaleByOrderId[toId(order.id)]),
|
||
timeline: buildOrderTimeline(order, assistData.reviewsByOrderId[toId(order.id)], assistData.changesByOrderId[toId(order.id)], assistData.pendingReviews),
|
||
items: await Promise.all(safeList(order.items).map(async item => {
|
||
const itemId = toId(item.id)
|
||
const inlinePendingReview = resolveRelatedRecord(item.pendingReview || order.pendingReview, item.id)
|
||
const inlineReviewSummary = resolveRelatedRecord(item.reviewSummary || order.reviewSummary, item.id)
|
||
const inlinePendingChange = resolveRelatedRecord(item.pendingArtistChangeRequest || order.pendingArtistChangeRequest, item.id)
|
||
const pendingReview = buildPendingReview(inlinePendingReview || assistData.pendingReviewByItemId[itemId])
|
||
const reviewSummary = buildReviewSummary(inlineReviewSummary || assistData.submittedReviewByItemId[itemId])
|
||
const pendingArtistChangeRequest = buildArtistChangeSummary(inlinePendingChange || assistData.pendingChangeByItemId[itemId], item)
|
||
|
||
return {
|
||
...item,
|
||
productImageUrl: await resolveLegacyImage(item.productImage),
|
||
priceText: `\u00a5${formatPrice(item.price)}`,
|
||
appointmentText: formatDateTime(item.appointmentTime),
|
||
focusTarget: sameId(order.id, resolvedFocusOrderId) && (!resolvedFocusOrderItemId || sameId(item.id, resolvedFocusOrderItemId)),
|
||
pendingReview,
|
||
reviewSummary,
|
||
reviewDraft: pendingReview ? { rating: 0, content: '' } : null,
|
||
pendingArtistChangeRequest
|
||
}
|
||
}))
|
||
})))
|
||
|
||
formattedOrders.forEach(order => {
|
||
order.canRebook = Number(order.status) === 2 && getRebookableOrderItems(order).length > 0
|
||
order.canApplyAfterSale = canApplyAfterSale(order, order.afterSaleSummary)
|
||
})
|
||
|
||
this.setData({
|
||
orders: formattedOrders,
|
||
recoveryState: clearRecoveryState()
|
||
})
|
||
} catch (error) {
|
||
this.setData({
|
||
orders: [],
|
||
recoveryState: buildRecoveryState({
|
||
title: '订单列表加载失败',
|
||
message: error,
|
||
fallbackMessage: '订单暂时没有加载出来,请重试或稍后再查看。',
|
||
actions: [
|
||
{ key: 'retryOrdersLoad', text: '重试' },
|
||
{ key: 'products', text: '去逛作品' },
|
||
{ key: 'profile', text: '返回我的' }
|
||
]
|
||
})
|
||
})
|
||
} finally {
|
||
this.setData({
|
||
loading: false
|
||
})
|
||
}
|
||
},
|
||
|
||
/**
|
||
* Purpose: handleOpenAuth supports index.js by holding or executing the handle open auth page or API role.
|
||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
handleOpenAuth() {
|
||
navigation.openAuth('/pages/orders/index')
|
||
},
|
||
|
||
/**
|
||
* Purpose: handleBack supports index.js by holding or executing the handle back page or API role.
|
||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
handleBack() {
|
||
navigation.goBack('/pages/profile/index')
|
||
},
|
||
|
||
handleRecoveryAction(event) {
|
||
const key = event.currentTarget.dataset.key
|
||
if (key === 'retryOrdersLoad') {
|
||
this.setData({ recoveryState: clearRecoveryState() })
|
||
this.loadOrders()
|
||
return
|
||
}
|
||
|
||
const actions = this.data.recoveryState.actions || []
|
||
const action = actions.find(item => item.key === key)
|
||
if (action && action.route) {
|
||
this.openRecoveryRoute(action.route)
|
||
}
|
||
},
|
||
|
||
openRecoveryRoute(route) {
|
||
const pureRoute = String(route || '').split('?')[0]
|
||
if (!pureRoute) {
|
||
return
|
||
}
|
||
if (navigation.isTabPage(pureRoute)) {
|
||
navigation.switchTab(pureRoute)
|
||
return
|
||
}
|
||
navigation.navigate(route)
|
||
},
|
||
|
||
/**
|
||
* Purpose: updateReviewDraft supports index.js by holding or executing the update review draft page or API role.
|
||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
updateReviewDraft(reviewId, patch) {
|
||
const reviewIdText = toId(reviewId)
|
||
const orders = this.data.orders.map(order => ({
|
||
...order,
|
||
items: safeList(order.items).map(item => {
|
||
const pendingReview = item.pendingReview
|
||
if (!pendingReview || toId(pendingReview.id) !== reviewIdText) {
|
||
return item
|
||
}
|
||
return {
|
||
...item,
|
||
reviewDraft: {
|
||
...(item.reviewDraft || {}),
|
||
...patch
|
||
}
|
||
}
|
||
})
|
||
}))
|
||
this.setData({
|
||
orders
|
||
})
|
||
},
|
||
|
||
/**
|
||
* Purpose: handleSelectReviewScore supports index.js by holding or executing the handle select review score page or API role.
|
||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
handleSelectReviewScore(event) {
|
||
const reviewId = event.currentTarget.dataset.reviewId
|
||
const score = Number(event.currentTarget.dataset.score)
|
||
this.updateReviewDraft(reviewId, {
|
||
rating: score
|
||
})
|
||
},
|
||
|
||
/**
|
||
* Purpose: handleReviewContentInput supports index.js by holding or executing the handle review content input page or API role.
|
||
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
|
||
*/
|
||
handleReviewContentInput(event) {
|
||
const reviewId = event.currentTarget.dataset.reviewId
|
||
this.updateReviewDraft(reviewId, {
|
||
content: event.detail.value
|
||
})
|
||
},
|
||
|
||
async handleSubmitReview(event) {
|
||
const reviewId = event.currentTarget.dataset.reviewId
|
||
if (!reviewId) {
|
||
return
|
||
}
|
||
|
||
try {
|
||
await actionGuard.run(this, `order:review:${reviewId}`, async () => {
|
||
const draft = findReviewDraft(this.data.orders, reviewId)
|
||
const rating = Number(draft.rating)
|
||
if (!isFinite(rating) || rating < 0.5 || rating > 5 || rating * 2 % 1 !== 0) {
|
||
wx.showToast({
|
||
title: '请选择 0.5-5 分评分',
|
||
icon: 'none'
|
||
})
|
||
return
|
||
}
|
||
|
||
await runWithLoading(() => orderApi.submitArtistReview(reviewId, {
|
||
rating,
|
||
content: trimText(draft.content),
|
||
imageFileIds: []
|
||
}))
|
||
wx.showToast({
|
||
title: '评价已提交',
|
||
icon: 'none'
|
||
})
|
||
await this.loadOrders()
|
||
}, {
|
||
message: '评价正在提交中,请勿重复点击'
|
||
})
|
||
} catch (error) {
|
||
if (actionGuard.isGuardError(error)) {
|
||
return
|
||
}
|
||
wx.showToast({
|
||
title: error.message || '评价提交失败',
|
||
icon: 'none'
|
||
})
|
||
}
|
||
},
|
||
|
||
async handleApproveArtistChange(event) {
|
||
const requestId = event.currentTarget.dataset.requestId
|
||
const confirmText = event.currentTarget.dataset.confirmText
|
||
if (!requestId) {
|
||
return
|
||
}
|
||
|
||
try {
|
||
await actionGuard.run(this, `order:artist-change:approve:${requestId}`, async () => {
|
||
const confirmed = await new Promise(resolve => {
|
||
wx.showModal({
|
||
title: '同意改派',
|
||
content: confirmText || '确认同意这次美甲师改派申请吗?',
|
||
success: modalRes => resolve(Boolean(modalRes.confirm))
|
||
})
|
||
})
|
||
if (!confirmed) {
|
||
return
|
||
}
|
||
|
||
await runWithLoading(() => orderApi.approveArtistChange(requestId))
|
||
wx.showToast({
|
||
title: '已同意改派',
|
||
icon: 'none'
|
||
})
|
||
await this.loadOrders()
|
||
}, {
|
||
message: '改派处理中,请勿重复点击'
|
||
})
|
||
} catch (error) {
|
||
if (actionGuard.isGuardError(error)) {
|
||
return
|
||
}
|
||
wx.showToast({
|
||
title: error.message || '同意改派失败',
|
||
icon: 'none'
|
||
})
|
||
}
|
||
},
|
||
|
||
async handleRejectArtistChange(event) {
|
||
const requestId = event.currentTarget.dataset.requestId
|
||
const confirmText = event.currentTarget.dataset.confirmText
|
||
if (!requestId) {
|
||
return
|
||
}
|
||
|
||
try {
|
||
await actionGuard.run(this, `order:artist-change:reject:${requestId}`, async () => {
|
||
const confirmed = await new Promise(resolve => {
|
||
wx.showModal({
|
||
title: '拒绝改派',
|
||
content: confirmText ? `${confirmText}\n\n确认拒绝这次改派申请吗?拒绝后可在下一步补充原因。` : '确认拒绝这次美甲师改派申请吗?拒绝后可在下一步补充原因。',
|
||
confirmText: '拒绝',
|
||
success: modalRes => resolve(Boolean(modalRes.confirm))
|
||
})
|
||
})
|
||
if (!confirmed) {
|
||
return
|
||
}
|
||
|
||
const rejectReason = await this.promptRejectReason()
|
||
|
||
await runWithLoading(() => orderApi.rejectArtistChange(requestId, {
|
||
rejectReason
|
||
}))
|
||
wx.showToast({
|
||
title: '已拒绝改派',
|
||
icon: 'none'
|
||
})
|
||
await this.loadOrders()
|
||
}, {
|
||
message: '改派处理中,请勿重复点击'
|
||
})
|
||
} catch (error) {
|
||
if (actionGuard.isGuardError(error)) {
|
||
return
|
||
}
|
||
wx.showToast({
|
||
title: error.message || '拒绝改派失败',
|
||
icon: 'none'
|
||
})
|
||
}
|
||
},
|
||
|
||
async handlePayOrder(event) {
|
||
const orderId = event.currentTarget.dataset.orderId
|
||
const order = findOrderById(this.data.orders, orderId)
|
||
if (!order || !order.paymentInfo || !order.paymentInfo.canPay) {
|
||
wx.showToast({
|
||
title: '当前订单无需支付',
|
||
icon: 'none'
|
||
})
|
||
return
|
||
}
|
||
|
||
try {
|
||
await actionGuard.run(this, `order:pay:${orderId}`, async () => {
|
||
await runWithLoading(() => paymentApi.prepareOrderPayment(orderId), {
|
||
title: '准备支付'
|
||
})
|
||
const confirmed = await new Promise(resolve => {
|
||
wx.showModal({
|
||
title: '准备支付',
|
||
content: `本次需支付 ${order.paymentInfo.amountText},支付单准备后请等待正式支付接入。`,
|
||
confirmText: '知道了',
|
||
success: res => resolve(Boolean(res.confirm)),
|
||
fail: () => resolve(false)
|
||
})
|
||
})
|
||
if (!confirmed) {
|
||
return
|
||
}
|
||
wx.showToast({
|
||
title: '支付单已准备',
|
||
icon: 'none'
|
||
})
|
||
await this.loadOrders()
|
||
}, {
|
||
message: '支付处理中,请勿重复点击'
|
||
})
|
||
} catch (error) {
|
||
if (actionGuard.isGuardError(error)) {
|
||
return
|
||
}
|
||
wx.showToast({
|
||
title: error.message || '支付失败',
|
||
icon: 'none'
|
||
})
|
||
}
|
||
},
|
||
|
||
async handleApplyAfterSale(event) {
|
||
const orderId = event.currentTarget.dataset.orderId
|
||
const order = findOrderById(this.data.orders, orderId)
|
||
if (!order || !order.canApplyAfterSale) {
|
||
wx.showToast({
|
||
title: '当前订单暂不可申请售后',
|
||
icon: 'none'
|
||
})
|
||
return
|
||
}
|
||
|
||
try {
|
||
await actionGuard.run(this, `order:after-sale:${orderId}`, async () => {
|
||
const reason = await this.promptAfterSaleReason()
|
||
if (!reason) {
|
||
return
|
||
}
|
||
await runWithLoading(() => afterSaleApi.applyAfterSale({
|
||
orderId,
|
||
type: 'REFUND',
|
||
reason,
|
||
refundAmount: getOrderPayAmount(order)
|
||
}), {
|
||
title: '提交售后'
|
||
})
|
||
wx.showToast({
|
||
title: '售后已提交',
|
||
icon: 'none'
|
||
})
|
||
await this.loadOrders()
|
||
}, {
|
||
message: '售后申请提交中,请勿重复点击'
|
||
})
|
||
} catch (error) {
|
||
if (actionGuard.isGuardError(error)) {
|
||
return
|
||
}
|
||
wx.showToast({
|
||
title: error.message || '售后申请失败',
|
||
icon: 'none'
|
||
})
|
||
}
|
||
},
|
||
|
||
promptAfterSaleReason() {
|
||
return new Promise(resolve => {
|
||
wx.showModal({
|
||
title: '申请售后',
|
||
content: '请填写售后原因,提交后门店会尽快处理。',
|
||
editable: true,
|
||
placeholderText: '例如:需要退款或调整服务',
|
||
confirmText: '提交',
|
||
success: res => {
|
||
if (!res.confirm) {
|
||
resolve('')
|
||
return
|
||
}
|
||
const reason = trimText(res.content)
|
||
if (!reason) {
|
||
wx.showToast({
|
||
title: '请填写售后原因',
|
||
icon: 'none'
|
||
})
|
||
}
|
||
resolve(reason)
|
||
},
|
||
fail: () => resolve('')
|
||
})
|
||
})
|
||
},
|
||
|
||
/**
|
||
* Purpose: promptRejectReason collects an optional customer reason before rejecting an artist-change request.
|
||
* Usage: call it after the confirmation dialog and pass the returned text to rejectArtistChange.
|
||
*/
|
||
promptRejectReason() {
|
||
return new Promise(resolve => {
|
||
wx.showModal({
|
||
title: '拒绝原因',
|
||
editable: true,
|
||
placeholderText: '可选,告诉美甲师原因',
|
||
confirmText: '提交',
|
||
success: res => {
|
||
if (!res.confirm) {
|
||
resolve('')
|
||
return
|
||
}
|
||
resolve(trimText(res.content))
|
||
},
|
||
fail: () => resolve('')
|
||
})
|
||
})
|
||
},
|
||
|
||
async handleRebookOrder(event) {
|
||
const orderId = event.currentTarget.dataset.orderId
|
||
const order = findOrderById(this.data.orders, orderId)
|
||
if (!order || !order.canRebook) {
|
||
wx.showToast({
|
||
title: '这笔订单暂无可复刻作品',
|
||
icon: 'none'
|
||
})
|
||
return
|
||
}
|
||
|
||
const items = getRebookableOrderItems(order)
|
||
try {
|
||
await actionGuard.run(this, `order:rebook:${orderId}`, async () => {
|
||
await runWithLoading(async () => {
|
||
for (let i = 0; i < items.length; i += 1) {
|
||
await cartApi.addToCart({
|
||
productId: items[i].productId,
|
||
quantity: normalizeRebookQuantity(items[i].quantity)
|
||
})
|
||
}
|
||
await getApp().updateCartBadge()
|
||
})
|
||
await new Promise(resolve => {
|
||
wx.showModal({
|
||
title: '已加入购物车',
|
||
content: '请重新选择美甲师和预约时间后再提交订单。',
|
||
showCancel: false,
|
||
confirmText: '去选择',
|
||
success: () => resolve(),
|
||
fail: () => resolve()
|
||
})
|
||
})
|
||
await navigation.switchTab('/pages/cart/index')
|
||
}, {
|
||
message: '正在加入购物车,请勿重复点击'
|
||
})
|
||
} catch (error) {
|
||
if (actionGuard.isGuardError(error)) {
|
||
return
|
||
}
|
||
wx.showToast({
|
||
title: error.message || '复刻同款失败',
|
||
icon: 'none'
|
||
})
|
||
}
|
||
},
|
||
|
||
async handleCancelOrder(event) {
|
||
const orderId = event.currentTarget.dataset.orderId
|
||
if (!orderId) {
|
||
return
|
||
}
|
||
|
||
try {
|
||
await actionGuard.run(this, `order:cancel:${orderId}`, async () => {
|
||
const confirmed = await new Promise(resolve => {
|
||
wx.showModal({
|
||
title: '\u53d6\u6d88\u8ba2\u5355',
|
||
content: '\u786e\u8ba4\u53d6\u6d88\u8fd9\u7b14\u8ba2\u5355\u5417\uff1f',
|
||
success: modalRes => resolve(Boolean(modalRes.confirm))
|
||
})
|
||
})
|
||
|
||
if (!confirmed) {
|
||
return
|
||
}
|
||
|
||
await runWithLoading(() => orderApi.cancelOrder(orderId))
|
||
wx.showToast({
|
||
title: '\u8ba2\u5355\u5df2\u53d6\u6d88',
|
||
icon: 'none'
|
||
})
|
||
await this.loadOrders()
|
||
}, {
|
||
message: '\u64cd\u4f5c\u8fdb\u884c\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb'
|
||
})
|
||
} catch (error) {
|
||
if (actionGuard.isGuardError(error)) {
|
||
return
|
||
}
|
||
wx.showToast({
|
||
title: error.message || '\u53d6\u6d88\u8ba2\u5355\u5931\u8d25',
|
||
icon: 'none'
|
||
})
|
||
}
|
||
}
|
||
})
|