功能(小程序):同步用户体验流程到小程序

This commit is contained in:
xiaowang
2026-05-23 21:56:52 +08:00
parent 861eea933b
commit b67dae502f
38 changed files with 2163 additions and 126 deletions
+148 -40
View File
@@ -3,11 +3,6 @@
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const cartApi = require('../../api/cart')
/**
* Purpose: couponApi supports index.js by holding or executing the coupon 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 couponApi = require('../../api/coupon')
/**
* 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.
@@ -31,6 +26,8 @@ const theme = require('../../utils/theme')
const { resolveLegacyImage } = require('../../utils/file')
const { NO_COUPON_KEY } = require('../../utils/config')
const { runWithLoading } = require('../../utils/loading')
const { clearBuyNowContext, isBuyNowCartItem, readBuyNowContext } = require('../../utils/buy-now')
const { buildRecoveryState, clearRecoveryState } = require('../../utils/recovery')
const {
buildAppointmentValue,
formatDateTime,
@@ -53,6 +50,9 @@ function getCouponKey(coupon) {
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getCouponDisplay(coupon) {
if (coupon && coupon.displayText) {
return coupon.displayText
}
if (Number(coupon.couponType) === 1) {
return `${coupon.couponName} ${coupon.discountValue} 折`
}
@@ -71,6 +71,9 @@ function calculateCouponDiscount(coupon, amount) {
if (!coupon || amount <= 0) {
return 0
}
if (coupon.discountAmount !== undefined && coupon.discountAmount !== null) {
return Number(coupon.discountAmount || 0)
}
if (Number(coupon.couponType) === 1) {
const discountValue = Number(coupon.discountValue || 0)
@@ -160,6 +163,9 @@ Page({
minDate: getMinDateText(),
cartItems: [],
availableCoupons: [],
unavailableCoupons: [],
checkoutPreview: null,
vipTip: '',
selectedCouponKey: NO_COUPON_KEY,
/**
* Purpose: couponSelectionTouched records whether the user explicitly chose a coupon option.
@@ -167,13 +173,18 @@ Page({
*/
couponSelectionTouched: false,
selectedCount: 0,
isBuyNowMode: false,
heroKicker: '结算准备',
heroTitle: '已选 0 个预约项目',
heroDesc: '确认美甲师和时间后再下单。',
totalQuantity: 0,
subtotalAmount: 0,
subtotalText: '¥0.00',
discountAmountText: '¥0.00',
totalAmountText: '¥0.00',
checkoutIssues: [],
submittingOrder: false
submittingOrder: false,
recoveryState: clearRecoveryState()
}),
/**
@@ -214,13 +225,19 @@ Page({
const selectedCoupon = this.getSelectedCoupon()
const selectedCount = selectedItems.length
const totalQuantity = selectedItems.reduce((sum, item) => sum + Number(item.quantity || 0), 0)
const subtotalAmount = selectedItems.reduce((sum, item) => sum + Number(item.price || 0) * Number(item.quantity || 0), 0)
const discountAmount = calculateCouponDiscount(selectedCoupon, subtotalAmount)
const totalAmount = Math.max(0, subtotalAmount - discountAmount)
const localSubtotalAmount = selectedItems.reduce((sum, item) => sum + Number(item.price || 0) * Number(item.quantity || 0), 0)
const preview = this.data.checkoutPreview || {}
const subtotalAmount = preview.subtotalAmount !== undefined ? Number(preview.subtotalAmount || 0) : localSubtotalAmount
const discountAmount = preview.savedAmount !== undefined ? Number(preview.savedAmount || 0) : calculateCouponDiscount(selectedCoupon, subtotalAmount)
const totalAmount = preview.payableAmount !== undefined ? Number(preview.payableAmount || 0) : Math.max(0, subtotalAmount - discountAmount)
const checkoutIssues = buildCheckoutIssues(this.data.cartItems)
const isBuyNowMode = Boolean(this.data.isBuyNowMode)
this.setData({
selectedCount,
heroKicker: isBuyNowMode ? '确认订单' : '结算准备',
heroTitle: isBuyNowMode ? '确认本次预约' : `已选 ${selectedCount} 个预约项目`,
heroDesc: isBuyNowMode ? '本次只会提交刚刚选择的作品,不会混入购物车其他项目。' : '确认美甲师和时间后再下单。',
totalQuantity,
subtotalAmount,
subtotalText: `¥${formatPrice(subtotalAmount)}`,
@@ -232,9 +249,13 @@ Page({
async loadCartItems() {
const isLoggedIn = auth.isLoggedIn()
const buyNowContext = isLoggedIn ? readBuyNowContext() : null
const buyNowProductId = buyNowContext && buyNowContext.productId ? String(buyNowContext.productId) : ''
this.setData({
isLoggedIn,
loading: isLoggedIn
isBuyNowMode: Boolean(buyNowProductId),
loading: isLoggedIn,
recoveryState: clearRecoveryState()
})
/**
@@ -245,9 +266,13 @@ Page({
this.setData({
cartItems: [],
availableCoupons: [],
unavailableCoupons: [],
checkoutPreview: null,
vipTip: '',
selectedCouponKey: NO_COUPON_KEY,
couponSelectionTouched: false,
loading: false
loading: false,
recoveryState: clearRecoveryState()
})
this.refreshSummary()
return
@@ -273,7 +298,7 @@ Page({
...item,
productImageUrl,
priceText: `¥${formatPrice(item.price)}`,
selected: true,
selected: buyNowProductId ? isBuyNowCartItem(item, buyNowProductId) : true,
artistId: item.artistId || '',
artistName: artist ? artist.name : '',
availableArtists,
@@ -286,16 +311,26 @@ Page({
this.setData({
cartItems: formattedItems,
selectedCouponKey: NO_COUPON_KEY,
couponSelectionTouched: false
couponSelectionTouched: false,
recoveryState: clearRecoveryState()
})
if (buyNowProductId) {
clearBuyNowContext()
}
await this.loadAvailableCoupons()
} catch (error) {
this.setData({
cartItems: []
})
wx.showToast({
title: error.message || '购物车加载失败',
icon: 'none'
cartItems: [],
recoveryState: buildRecoveryState({
title: '购物车加载失败',
message: error,
fallbackMessage: '购物车暂时没有加载出来,请重试或先去逛作品。',
actions: [
{ key: 'retryCartLoad', text: '重试' },
{ key: 'products', text: '去逛作品' },
{ key: 'contact', text: '联系客服' }
]
})
})
} finally {
this.setData({
@@ -314,6 +349,9 @@ Page({
if (!selectedItems.length) {
this.setData({
availableCoupons: [],
unavailableCoupons: [],
checkoutPreview: null,
vipTip: '',
selectedCouponKey: NO_COUPON_KEY,
couponSelectionTouched: false
})
@@ -321,24 +359,25 @@ Page({
return
}
const tags = new Set()
const subtotalAmount = selectedItems.reduce((sum, item) => sum + Number(item.price || 0) * Number(item.quantity || 0), 0)
selectedItems.forEach(item => {
String(item.tagNames || '')
.split(',')
.map(tag => tag.trim())
.filter(Boolean)
.forEach(tag => tags.add(tag))
})
try {
const coupons = await couponApi.getAvailableCoupons(
Array.from(tags).join(','),
subtotalAmount,
selectedItems[0].shopId
)
const selectedCoupon = this.getSelectedCoupon()
const preview = await orderApi.checkoutPreview({
couponId: selectedCoupon ? selectedCoupon.id : undefined,
couponSourceType: selectedCoupon ? selectedCoupon.sourceType : (this.data.couponSelectionTouched && this.data.selectedCouponKey === NO_COUPON_KEY ? NO_COUPON_KEY : undefined),
items: selectedItems.map(item => ({
productId: item.productId,
quantity: item.quantity,
artistId: item.artistId,
appointmentTime: item.appointmentValue
}))
})
const list = Array.isArray(coupons) ? coupons.map(item => ({
const list = Array.isArray(preview && preview.availableCoupons) ? preview.availableCoupons.map(item => ({
...item,
key: getCouponKey(item),
displayText: getCouponDisplay(item)
})) : []
const unavailableCoupons = Array.isArray(preview && preview.unavailableCoupons) ? preview.unavailableCoupons.map(item => ({
...item,
key: getCouponKey(item),
displayText: getCouponDisplay(item)
@@ -348,6 +387,7 @@ Page({
if (selectedCouponKey !== NO_COUPON_KEY && !list.find(item => item.key === selectedCouponKey)) {
selectedCouponKey = NO_COUPON_KEY
}
const previewSubtotalAmount = Number((preview && preview.subtotalAmount) || this.data.subtotalAmount || 0)
/**
* `if` page method. Use this from WXML event bindings or lifecycle hooks.
@@ -355,8 +395,7 @@ Page({
*/
if (selectedCouponKey === NO_COUPON_KEY && !this.data.couponSelectionTouched) {
const bestCoupons = list
.filter(item => item.sourceType === 'SYSTEM_VIP')
.sort((left, right) => calculateCouponDiscount(right, subtotalAmount) - calculateCouponDiscount(left, subtotalAmount))
.sort((left, right) => calculateCouponDiscount(right, previewSubtotalAmount) - calculateCouponDiscount(left, previewSubtotalAmount))
/**
* `if` page method. Use this from WXML event bindings or lifecycle hooks.
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
@@ -368,11 +407,17 @@ Page({
this.setData({
availableCoupons: list,
unavailableCoupons,
checkoutPreview: preview || null,
vipTip: preview && preview.vipTip ? preview.vipTip : '',
selectedCouponKey
})
} catch (error) {
this.setData({
availableCoupons: [],
unavailableCoupons: [],
checkoutPreview: null,
vipTip: '',
selectedCouponKey: NO_COUPON_KEY,
couponSelectionTouched: false
})
@@ -397,6 +442,60 @@ Page({
navigation.switchTab('/pages/products/index')
},
handleRecoveryAction(event) {
const key = event.currentTarget.dataset.key
if (key === 'retryCartLoad') {
this.setData({ recoveryState: clearRecoveryState() })
this.loadCartItems()
return
}
if (key === 'retryCheckout') {
this.setData({ recoveryState: clearRecoveryState() })
this.handleCheckout()
return
}
if (key === 'contact') {
this.handleContactSupport()
return
}
if (key === 'cart') {
this.setData({ recoveryState: clearRecoveryState() })
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)
},
handleContactSupport() {
wx.showModal({
title: '联系客服',
content: '请截图保留失败提示;如果担心重复下单,请先查看订单。也可以前往“我的”页联系门店或平台客服。',
confirmText: '去我的',
cancelText: '留在本页',
success: res => {
if (res.confirm) {
navigation.switchTab('/pages/profile/index')
}
}
})
},
async handleToggleSelect(event) {
const index = Number(event.currentTarget.dataset.index)
const cartItems = this.data.cartItems.slice()
@@ -640,7 +739,7 @@ Page({
selectedCouponKey: event.detail.value,
couponSelectionTouched: true
})
this.refreshSummary()
this.loadAvailableCoupons()
},
async handleCheckout() {
@@ -704,9 +803,18 @@ Page({
icon: 'none'
})
} catch (error) {
wx.showToast({
title: error.message || '订单创建失败',
icon: 'none'
this.setData({
recoveryState: buildRecoveryState({
title: '下单失败',
message: error,
fallbackMessage: '订单创建失败,请重试;如果担心重复下单,请先查看订单。',
actions: [
{ key: 'retryCheckout', text: '重试下单' },
{ key: 'orders', text: '查看订单' },
{ key: 'contact', text: '联系客服' },
{ key: 'cart', text: '返回购物车' }
]
})
})
} finally {
this.setData({
+45 -7
View File
@@ -9,10 +9,24 @@
</view>
<block wx:elif="{{cartItems.length}}">
<view wx:if="{{recoveryState.visible}}" class="page-card recovery-card">
<text class="recovery-title">{{recoveryState.title}}</text>
<text class="recovery-desc">{{recoveryState.message}}</text>
<view class="recovery-actions">
<view
wx:for="{{recoveryState.actions}}"
wx:key="key"
class="recovery-btn {{item.primary ? 'primary' : ''}}"
data-key="{{item.key}}"
bindtap="handleRecoveryAction"
>{{item.text}}</view>
</view>
</view>
<view class="page-hero cart-hero">
<text class="hero-kicker">结算准备</text>
<text class="hero-title">已选 {{selectedCount}} 个预约项目</text>
<text class="hero-desc">确认美甲师和时间后再下单。</text>
<text class="hero-kicker">{{heroKicker}}</text>
<text class="hero-title">{{heroTitle}}</text>
<text class="hero-desc">{{heroDesc}}</text>
<view class="summary-strip">
<view class="summary-metric">
@@ -93,7 +107,7 @@
<view wx:if="{{selectedCount}}" class="page-card coupon-card">
<view class="section-title">优惠方式</view>
<view class="section-subtitle">系统会优先匹配 VIP 优惠。</view>
<view class="section-subtitle">{{vipTip || '系统会优先匹配 VIP 优惠。'}}</view>
<radio-group bindchange="handleCouponChange">
<label class="coupon-option">
@@ -107,14 +121,24 @@
<radio value="{{coupon.key}}" checked="{{selectedCouponKey === coupon.key}}" color="{{navThemeColor || '#C6597D'}}"></radio>
<view class="coupon-texts">
<view class="coupon-name">{{coupon.displayText}}</view>
<view class="coupon-desc">{{coupon.sourceType === 'SYSTEM_VIP' ? 'VIP 自动折扣' : '用户优惠券'}}</view>
<view class="coupon-desc">{{coupon.savingText || (coupon.sourceType === 'SYSTEM_VIP' ? 'VIP 自动折扣' : '用户优惠券')}}</view>
</view>
<view class="coupon-tag">{{coupon.sourceType === 'SYSTEM_VIP' ? '推荐' : '手动选择'}}</view>
</label>
</radio-group>
<view wx:if="{{unavailableCoupons.length}}" class="unavailable-coupon-list">
<view class="unavailable-title">本单暂不可用</view>
<view wx:for="{{unavailableCoupons}}" wx:key="key" wx:for-item="coupon" class="unavailable-coupon">
<text>{{coupon.displayText}}</text>
<text>{{coupon.unavailableReason || '本单暂不可用'}}</text>
</view>
</view>
</view>
<view class="page-card summary-card">
<view wx:if="{{checkoutPreview && checkoutPreview.summaryText}}" class="summary-preview">{{checkoutPreview.summaryText}}</view>
<view wx:if="{{vipTip}}" class="summary-vip">{{vipTip}}</view>
<view class="summary-row">
<text>选中项目</text>
<text>{{selectedCount}} 项</text>
@@ -124,11 +148,11 @@
<text>{{totalQuantity}} 件</text>
</view>
<view class="summary-row">
<text>小计</text>
<text>商品小计</text>
<text>{{subtotalText}}</text>
</view>
<view class="summary-row">
<text>优惠</text>
<text>已省</text>
<text>-{{discountAmountText}}</text>
</view>
<view class="summary-row total">
@@ -142,6 +166,20 @@
<text class="empty-title">正在加载购物车</text>
</view>
<view wx:elif="{{recoveryState.visible}}" class="page-card recovery-card">
<text class="recovery-title">{{recoveryState.title}}</text>
<text class="recovery-desc">{{recoveryState.message}}</text>
<view class="recovery-actions">
<view
wx:for="{{recoveryState.actions}}"
wx:key="key"
class="recovery-btn {{item.primary ? 'primary' : ''}}"
data-key="{{item.key}}"
bindtap="handleRecoveryAction"
>{{item.text}}</view>
</view>
</view>
<view wx:else class="page-card empty-card">
<text class="empty-title">购物车还是空的</text>
<text class="empty-desc">先加购,再预约。</text>
+97
View File
@@ -31,6 +31,54 @@
line-height: 1.7;
}
.recovery-card {
display: flex;
flex-direction: column;
gap: 14rpx;
margin-bottom: 20rpx;
padding: 26rpx;
border: 2rpx solid var(--theme-border);
}
.recovery-title {
font-size: 30rpx;
font-weight: 800;
color: #2d2430;
}
.recovery-desc {
font-size: 24rpx;
line-height: 1.6;
color: #8d7a84;
}
.recovery-actions {
display: flex;
flex-wrap: wrap;
gap: 14rpx;
}
.recovery-btn {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 136rpx;
height: 60rpx;
padding: 0 20rpx;
border-radius: 999rpx;
background: #ffffff;
border: 2rpx solid var(--theme-border);
color: #5d4b55;
font-size: 24rpx;
font-weight: 700;
}
.recovery-btn.primary {
background: var(--theme-primary);
border-color: var(--theme-primary);
color: #ffffff;
}
.cart-item-card + .cart-item-card,
.coupon-card,
.summary-card {
@@ -260,6 +308,55 @@
font-weight: 700;
}
.unavailable-coupon-list {
margin-top: 22rpx;
padding-top: 18rpx;
border-top: 2rpx solid #f6eaee;
}
.unavailable-title {
font-size: 24rpx;
font-weight: 700;
color: #8d7a84;
}
.unavailable-coupon {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 18rpx;
margin-top: 14rpx;
font-size: 22rpx;
color: #8d7a84;
}
.unavailable-coupon text:first-child {
flex: 1;
min-width: 0;
color: #5d4b55;
}
.unavailable-coupon text:last-child {
max-width: 260rpx;
text-align: right;
}
.summary-preview,
.summary-vip {
margin-bottom: 14rpx;
padding: 16rpx 18rpx;
border-radius: 18rpx;
background: var(--theme-primary-soft);
color: #5d4b55;
font-size: 24rpx;
line-height: 1.6;
}
.summary-vip {
color: var(--theme-primary);
font-weight: 700;
}
.summary-row {
display: flex;
align-items: center;