重构项目文件夹目录

This commit is contained in:
2026-06-15 15:53:55 +08:00
parent 8093e07190
commit 7cbe5b3de5
1098 changed files with 34 additions and 4441 deletions
+830
View File
@@ -0,0 +1,830 @@
/**
* Purpose: cartApi supports index.js by holding or executing the cart 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 cartApi = require('../../api/cart')
/**
* 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')
/**
* 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: 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 { 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,
formatPrice,
getMinDateText,
isPastAppointment,
parseAppointmentParts
} = require('../../utils/format')
function buildClientRequestId(prefix) {
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
}
/**
* Purpose: getCouponKey supports index.js by holding or executing the get coupon key 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 getCouponKey(coupon) {
return `${coupon.sourceType || 'USER_COUPON'}:${coupon.id}`
}
/**
* Purpose: getCouponDisplay supports index.js by holding or executing the get coupon display 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 getCouponDisplay(coupon) {
if (coupon && coupon.displayText) {
return coupon.displayText
}
if (Number(coupon.couponType) === 1) {
return `${coupon.couponName} ${coupon.discountValue} 折`
}
return `${coupon.couponName} 满 ${coupon.minAmount} 减 ${coupon.reduceAmount}`
}
/**
* Purpose: calculateCouponDiscount supports index.js by holding or executing the calculate coupon discount 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 calculateCouponDiscount(coupon, amount) {
/**
* `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.
*/
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)
return discountValue ? amount - amount * discountValue / 10 : 0
}
if (Number(coupon.couponType) === 2) {
return Number(coupon.reduceAmount || 0)
}
return 0
}
/**
* Purpose: buildCheckoutIssues supports index.js by holding or executing the build checkout issues 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 buildCheckoutIssues(items) {
const issues = []
const selectedItems = items.filter(item => item.selected)
/**
* `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.
*/
if (!selectedItems.length) {
issues.push('请先勾选要结算的作品')
return issues
}
const missingArtist = selectedItems.find(item => !item.artistId)
/**
* `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.
*/
if (missingArtist) {
issues.push(`请先为“${missingArtist.productTitle}”选择美甲师`)
}
const missingTime = selectedItems.find(item => !item.appointmentValue)
/**
* `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.
*/
if (missingTime) {
issues.push(`请先为“${missingTime.productTitle}”选择预约时间`)
}
const expiredTime = selectedItems.find(item => item.appointmentValue && isPastAppointment(item.appointmentValue))
/**
* `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.
*/
if (expiredTime) {
issues.push(`“${expiredTime.productTitle}”的预约时间已过,请重新选择`)
}
const shopIds = Array.from(new Set(selectedItems.map(item => item.shopId).filter(Boolean)))
/**
* `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.
*/
if (shopIds.length > 1) {
issues.push('跨门店作品请分开结算')
}
const artistIds = Array.from(new Set(selectedItems.map(item => item.artistId).filter(Boolean)))
/**
* `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.
*/
if (artistIds.length > 1) {
issues.push('不同美甲师的项目请分开结算')
}
return issues
}
/**
* cart page logic.
* Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks.
*/
Page({
data: Object.assign(theme.pageThemeData(getApp().globalData.shopTheme), {
isLoggedIn: false,
loading: false,
minDate: getMinDateText(),
cartItems: [],
availableCoupons: [],
unavailableCoupons: [],
checkoutPreview: null,
vipTip: '',
selectedCouponKey: NO_COUPON_KEY,
/**
* Purpose: couponSelectionTouched records whether the user explicitly chose a coupon option.
* Usage: keep normal user coupons manual-only while still allowing VIP auto coupons as default.
*/
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,
recoveryState: clearRecoveryState()
}),
/**
* `onShow` 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.
*/
onShow() {
this.loadCartItems()
},
async onPullDownRefresh() {
await this.loadCartItems()
wx.stopPullDownRefresh()
},
/**
* `getSelectedItems` 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.
*/
getSelectedItems() {
return this.data.cartItems.filter(item => item.selected)
},
/**
* `getSelectedCoupon` 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.
*/
getSelectedCoupon() {
return this.data.availableCoupons.find(item => item.key === this.data.selectedCouponKey) || null
},
/**
* `refreshSummary` 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.
*/
refreshSummary() {
const selectedItems = this.getSelectedItems()
const selectedCoupon = this.getSelectedCoupon()
const selectedCount = selectedItems.length
const totalQuantity = selectedItems.reduce((sum, item) => sum + Number(item.quantity || 0), 0)
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)}`,
discountAmountText: `¥${formatPrice(discountAmount)}`,
totalAmountText: `¥${formatPrice(totalAmount)}`,
checkoutIssues
})
},
async loadCartItems() {
const isLoggedIn = auth.isLoggedIn()
const buyNowContext = isLoggedIn ? readBuyNowContext() : null
const buyNowProductId = buyNowContext && buyNowContext.productId ? String(buyNowContext.productId) : ''
this.setData({
isLoggedIn,
isBuyNowMode: Boolean(buyNowProductId),
loading: isLoggedIn,
recoveryState: clearRecoveryState()
})
/**
* `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.
*/
if (!isLoggedIn) {
this.setData({
cartItems: [],
availableCoupons: [],
unavailableCoupons: [],
checkoutPreview: null,
vipTip: '',
selectedCouponKey: NO_COUPON_KEY,
couponSelectionTouched: false,
loading: false,
recoveryState: clearRecoveryState()
})
this.refreshSummary()
return
}
try {
const cartItems = await cartApi.getCartList()
const list = Array.isArray(cartItems) ? cartItems : []
const formattedItems = await Promise.all(list.map(async item => {
const appointmentParts = parseAppointmentParts(item.appointmentTime)
const productImageUrl = await resolveLegacyImage(item.productImage)
const availableArtists = Array.isArray(item.availableArtists) ? item.availableArtists.map(artist => ({
id: artist.id,
name: artist.name,
avatar: artist.avatar,
userType: artist.userType,
roleLabel: artist.roleLabel,
participateProduction: artist.participateProduction
})) : []
const artist = availableArtists.find(current => String(current.id) === String(item.artistId || ''))
return {
...item,
productImageUrl,
priceText: `¥${formatPrice(item.price)}`,
selected: buyNowProductId ? isBuyNowCartItem(item, buyNowProductId) : true,
artistId: item.artistId || '',
artistName: artist ? artist.name : '',
availableArtists,
appointmentDate: appointmentParts.date,
appointmentClock: appointmentParts.clock,
appointmentValue: buildAppointmentValue(appointmentParts.date, appointmentParts.clock)
}
}))
this.setData({
cartItems: formattedItems,
selectedCouponKey: NO_COUPON_KEY,
couponSelectionTouched: false,
recoveryState: clearRecoveryState()
})
if (buyNowProductId) {
clearBuyNowContext()
}
await this.loadAvailableCoupons()
} catch (error) {
this.setData({
cartItems: [],
recoveryState: buildRecoveryState({
title: '购物车加载失败',
message: error,
fallbackMessage: '购物车暂时没有加载出来,请重试或先去逛作品。',
actions: [
{ key: 'retryCartLoad', text: '重试' },
{ key: 'products', text: '去逛作品' },
{ key: 'contact', text: '联系客服' }
]
})
})
} finally {
this.setData({
loading: false
})
this.refreshSummary()
}
},
async loadAvailableCoupons() {
const selectedItems = this.getSelectedItems()
/**
* `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.
*/
if (!selectedItems.length) {
this.setData({
availableCoupons: [],
unavailableCoupons: [],
checkoutPreview: null,
vipTip: '',
selectedCouponKey: NO_COUPON_KEY,
couponSelectionTouched: false
})
this.refreshSummary()
return
}
try {
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(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)
})) : []
let selectedCouponKey = this.data.selectedCouponKey
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.
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
*/
if (selectedCouponKey === NO_COUPON_KEY && !this.data.couponSelectionTouched) {
const bestCoupons = list
.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.
*/
if (bestCoupons.length) {
selectedCouponKey = bestCoupons[0].key
}
}
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
})
} finally {
this.refreshSummary()
}
},
/**
* `handleOpenAuth` 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.
*/
handleOpenAuth() {
navigation.openAuth('/pages/cart/index')
},
/**
* `handleBrowseProducts` 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.
*/
handleBrowseProducts() {
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()
const item = cartItems[index]
/**
* `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.
*/
if (!item) {
return
}
item.selected = !item.selected
this.setData({
cartItems
})
if (cartItems.some(current => current.selected)) {
await runWithLoading(() => this.loadAvailableCoupons())
return
}
await this.loadAvailableCoupons()
},
async handleChangeQuantity(event) {
const index = Number(event.currentTarget.dataset.index)
const delta = Number(event.currentTarget.dataset.delta)
const cartItems = this.data.cartItems.slice()
const item = cartItems[index]
/**
* `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.
*/
if (!item) {
return
}
const nextQuantity = Number(item.quantity || 0) + delta
/**
* `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.
*/
if (nextQuantity < 1 || nextQuantity > 99) {
return
}
item.quantity = nextQuantity
this.setData({
cartItems
})
this.refreshSummary()
try {
await runWithLoading(async () => {
await cartApi.updateCartQuantity({
productId: item.productId,
quantity: nextQuantity
})
await this.loadAvailableCoupons()
})
await getApp().updateCartBadge()
} catch (error) {
item.quantity -= delta
this.setData({
cartItems
})
this.refreshSummary()
wx.showToast({
title: error.message || '数量更新失败',
icon: 'none'
})
}
},
async handleRemoveItem(event) {
const index = Number(event.currentTarget.dataset.index)
const cartItems = this.data.cartItems.slice()
const item = cartItems[index]
/**
* `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.
*/
if (!item) {
return
}
const confirmed = await new Promise(resolve => {
wx.showModal({
title: '移除作品',
content: '确认从购物车移除这件作品吗?',
success: res => resolve(Boolean(res.confirm))
})
})
/**
* `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.
*/
if (!confirmed) {
return
}
try {
await runWithLoading(() => cartApi.removeFromCart(item.productId))
wx.showToast({
title: '已移出购物车',
icon: 'none'
})
await getApp().updateCartBadge()
this.loadCartItems()
} catch (error) {
wx.showToast({
title: error.message || '移除失败',
icon: 'none'
})
}
},
/**
* `handleOpenProduct` 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.
*/
handleOpenProduct(event) {
const productId = event.currentTarget.dataset.productId
/**
* `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.
*/
if (!productId) {
return
}
navigation.navigate('/pages/product-detail/index', {
id: productId
})
},
async handleChooseArtist(event) {
const index = Number(event.currentTarget.dataset.index)
const cartItems = this.data.cartItems.slice()
const item = cartItems[index]
/**
* `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.
*/
if (!item) {
return
}
/**
* `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.
*/
if (!item.availableArtists.length) {
wx.showToast({
title: '当前作品暂时没有可预约美甲师',
icon: 'none'
})
return
}
const tapIndex = await new Promise(resolve => {
wx.showActionSheet({
itemList: item.availableArtists.map(artist => artist.roleLabel ? `${artist.name}(${artist.roleLabel})` : artist.name),
success: res => resolve(res.tapIndex),
fail: () => resolve(-1)
})
})
/**
* `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.
*/
if (tapIndex < 0 || tapIndex >= item.availableArtists.length) {
return
}
const artist = item.availableArtists[tapIndex]
item.artistId = artist.id
item.artistName = artist.roleLabel ? `${artist.name}(${artist.roleLabel})` : artist.name
this.setData({
cartItems
})
this.refreshSummary()
},
/**
* `handleDateChange` 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.
*/
handleDateChange(event) {
const index = Number(event.currentTarget.dataset.index)
const cartItems = this.data.cartItems.slice()
const item = cartItems[index]
/**
* `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.
*/
if (!item) {
return
}
item.appointmentDate = event.detail.value
item.appointmentValue = buildAppointmentValue(item.appointmentDate, item.appointmentClock)
this.setData({
cartItems
})
this.refreshSummary()
},
/**
* `handleTimeChange` 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.
*/
handleTimeChange(event) {
const index = Number(event.currentTarget.dataset.index)
const cartItems = this.data.cartItems.slice()
const item = cartItems[index]
/**
* `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.
*/
if (!item) {
return
}
item.appointmentClock = event.detail.value
item.appointmentValue = buildAppointmentValue(item.appointmentDate, item.appointmentClock)
this.setData({
cartItems
})
this.refreshSummary()
},
/**
* `handleCouponChange` 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.
*/
handleCouponChange(event) {
this.setData({
selectedCouponKey: event.detail.value,
couponSelectionTouched: true
})
this.loadAvailableCoupons()
},
async handleCheckout() {
/**
* `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.
*/
if (this.data.submittingOrder) {
return
}
const selectedItems = this.getSelectedItems()
const checkoutIssues = buildCheckoutIssues(this.data.cartItems)
/**
* `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.
*/
if (checkoutIssues.length) {
wx.showToast({
title: checkoutIssues[0],
icon: 'none'
})
return
}
this.setData({
submittingOrder: true
})
try {
const selectedCoupon = this.getSelectedCoupon()
await runWithLoading(() => orderApi.createOrder({
couponId: selectedCoupon ? selectedCoupon.id : undefined,
couponSourceType: selectedCoupon ? selectedCoupon.sourceType : (this.data.selectedCouponKey === NO_COUPON_KEY ? NO_COUPON_KEY : undefined),
clientRequestId: buildClientRequestId('mini-order'),
items: selectedItems.map(item => ({
productId: item.productId,
quantity: item.quantity,
artistId: item.artistId,
appointmentTime: item.appointmentValue
}))
}))
let successToast = '订单创建成功'
try {
await getApp().updateCartBadge()
await this.loadCartItems()
} catch (followupError) {
console.error('订单创建后刷新页面失败:', followupError)
successToast = '订单已创建,但页面刷新失败,请前往订单页查看'
}
try {
await navigation.navigate('/pages/orders/index')
} catch (navigationError) {
console.error('订单创建后跳转订单页失败:', navigationError)
successToast = '订单已创建,但跳转订单页失败,请手动前往订单页查看'
}
wx.showToast({
title: successToast,
icon: 'none'
})
} catch (error) {
this.setData({
recoveryState: buildRecoveryState({
title: '下单失败',
message: error,
fallbackMessage: '订单创建失败,请重试;如果担心重复下单,请先查看订单。',
actions: [
{ key: 'retryCheckout', text: '重试下单' },
{ key: 'orders', text: '查看订单' },
{ key: 'contact', text: '联系客服' },
{ key: 'cart', text: '返回购物车' }
]
})
})
} finally {
this.setData({
submittingOrder: false
})
}
}
})
+6
View File
@@ -0,0 +1,6 @@
{
"usingComponents": {
"navigation-bar": "/components/navigation-bar/navigation-bar"
},
"enablePullDownRefresh": true
}
+197
View File
@@ -0,0 +1,197 @@
<navigation-bar title="购物车" showBack="{{false}}" isTabPage="{{true}}" color="{{navThemeColor || '#4A443F'}}" background="{{navThemeBackground || '#FDFBF9'}}"></navigation-bar>
<view class="page-shell cart-page" style="{{themeVars}}">
<view class="page-content cart-content">
<view wx:if="{{!isLoggedIn}}" class="page-card empty-card">
<text class="empty-title">登录后查看购物车</text>
<text class="empty-desc">登录后管理预约内容。</text>
<view class="ghost-btn" bindtap="handleOpenAuth">去登录</view>
</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">{{heroKicker}}</text>
<text class="hero-title">{{heroTitle}}</text>
<text class="hero-desc">{{heroDesc}}</text>
<view class="summary-strip">
<view class="summary-metric">
<text class="summary-label">选中项目</text>
<text class="summary-value">{{selectedCount}} 项</text>
<text class="summary-note">可分批结算</text>
</view>
<view class="summary-metric">
<text class="summary-label">数量合计</text>
<text class="summary-value">{{totalQuantity}} 件</text>
<text class="summary-note">可改数量</text>
</view>
<view class="summary-metric">
<text class="summary-label">待支付</text>
<text class="summary-value">{{totalAmountText}}</text>
<text class="summary-note">已算优惠</text>
</view>
</view>
</view>
<view wx:if="{{checkoutIssues.length}}" class="issue-card">
<view class="issue-title">下单前还需要完善</view>
<view wx:for="{{checkoutIssues}}" wx:key="*this" class="issue-item">{{index + 1}}. {{item}}</view>
</view>
<view wx:for="{{cartItems}}" wx:key="id" class="page-card cart-item-card">
<view class="cart-item-top">
<view class="select-dot {{item.selected ? 'active' : ''}}" data-index="{{index}}" bindtap="handleToggleSelect"></view>
<image class="cart-thumb" src="{{item.productImageUrl}}" mode="aspectFill" data-product-id="{{item.productId}}" bindtap="handleOpenProduct" lazy-load="{{true}}"></image>
<view class="cart-main">
<view class="cart-title-row">
<view class="cart-title" data-product-id="{{item.productId}}" bindtap="handleOpenProduct">{{item.productTitle}}</view>
<view class="cart-price">{{item.priceText}}</view>
</view>
<view class="cart-meta-row">
<text class="meta-chip">{{item.selected ? '已选中' : '未选中'}}</text>
<text wx:if="{{item.approximateDuration}}" class="cart-meta">预计时长 {{item.approximateDuration}}</text>
</view>
</view>
</view>
<view class="selector-group">
<view class="selector-row {{item.selected && !item.artistId ? 'issue' : ''}}" data-index="{{index}}" bindtap="handleChooseArtist">
<text class="selector-label">美甲师</text>
<text class="selector-value">{{item.artistName || '请选择美甲师'}}</text>
</view>
<view class="time-grid">
<picker mode="date" value="{{item.appointmentDate}}" start="{{minDate}}" data-index="{{index}}" bindchange="handleDateChange">
<view class="selector-row compact {{item.selected && !item.appointmentDate ? 'issue' : ''}}">
<text class="selector-label">日期</text>
<text class="selector-value">{{item.appointmentDate || '选择日期'}}</text>
</view>
</picker>
<picker mode="time" value="{{item.appointmentClock}}" data-index="{{index}}" bindchange="handleTimeChange">
<view class="selector-row compact {{item.selected && !item.appointmentClock ? 'issue' : ''}}">
<text class="selector-label">时间</text>
<text class="selector-value">{{item.appointmentClock || '选择时间'}}</text>
</view>
</picker>
</view>
<view wx:if="{{item.appointmentValue}}" class="appointment-preview">
当前预约:{{item.appointmentValue}}
</view>
</view>
<view class="cart-item-foot">
<view class="qty-box">
<view class="qty-btn" data-index="{{index}}" data-delta="-1" bindtap="handleChangeQuantity">-</view>
<text class="qty-value">{{item.quantity}}</text>
<view class="qty-btn" data-index="{{index}}" data-delta="1" bindtap="handleChangeQuantity">+</view>
</view>
<view class="remove-btn" data-index="{{index}}" bindtap="handleRemoveItem">移除</view>
</view>
</view>
<view wx:if="{{selectedCount}}" class="page-card coupon-card">
<view class="section-title">优惠方式</view>
<view class="section-subtitle">{{vipTip || '系统会优先匹配 VIP 优惠。'}}</view>
<radio-group bindchange="handleCouponChange">
<label class="coupon-option">
<radio value="NONE" checked="{{selectedCouponKey === 'NONE'}}" color="{{navThemeColor || '#E8B4B8'}}"></radio>
<view class="coupon-texts">
<view class="coupon-name">不使用优惠</view>
</view>
</label>
<label wx:for="{{availableCoupons}}" wx:key="key" wx:for-item="coupon" class="coupon-option {{selectedCouponKey === coupon.key ? 'active' : ''}}">
<radio value="{{coupon.key}}" checked="{{selectedCouponKey === coupon.key}}" color="{{navThemeColor || '#E8B4B8'}}"></radio>
<view class="coupon-texts">
<view class="coupon-name">{{coupon.displayText}}</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>
</view>
<view class="summary-row">
<text>作品数量</text>
<text>{{totalQuantity}} 件</text>
</view>
<view class="summary-row">
<text>商品小计</text>
<text>{{subtotalText}}</text>
</view>
<view class="summary-row">
<text>已省</text>
<text>-{{discountAmountText}}</text>
</view>
<view class="summary-row total">
<text>合计</text>
<text>{{totalAmountText}}</text>
</view>
</view>
</block>
<view wx:elif="{{loading}}" class="page-card empty-card">
<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>
<view class="ghost-btn" bindtap="handleBrowseProducts">去逛作品</view>
</view>
</view>
<view wx:if="{{isLoggedIn && cartItems.length}}" class="checkout-bar">
<view class="checkout-copy">
<view class="checkout-total">{{totalAmountText}}</view>
<view class="checkout-meta">已选 {{selectedCount}} 项</view>
</view>
<view class="checkout-btn" bindtap="handleCheckout">提交订单</view>
</view>
</view>
+422
View File
@@ -0,0 +1,422 @@
.cart-page {
padding-bottom: calc(env(safe-area-inset-bottom) + 150rpx);
background: var(--theme-page-bg);
}
.cart-content {
padding-bottom: 20rpx;
}
.cart-hero {
background: var(--theme-gradient-soft);
}
.issue-card {
margin-top: 20rpx;
margin-bottom: 20rpx;
padding: 22rpx 24rpx;
border-radius: 24rpx;
background: var(--theme-primary-soft);
color: var(--theme-neutral);
}
.issue-title {
font-size: 28rpx;
font-weight: 700;
}
.issue-item {
margin-top: 10rpx;
font-size: 24rpx;
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: var(--text-primary);
}
.recovery-desc {
font-size: 24rpx;
line-height: 1.6;
color: var(--text-secondary);
}
.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: var(--theme-card-bg);
border: 2rpx solid var(--theme-border);
color: var(--theme-neutral);
font-size: 24rpx;
font-weight: 700;
}
.recovery-btn.primary {
background: var(--theme-primary);
border-color: var(--theme-primary);
color: var(--theme-tertiary);
}
.cart-item-card + .cart-item-card,
.coupon-card,
.summary-card {
margin-top: 20rpx;
}
.cart-item-card {
padding: 24rpx;
}
.cart-item-top {
display: flex;
align-items: flex-start;
gap: 16rpx;
}
.select-dot {
width: 34rpx;
height: 34rpx;
margin-top: 8rpx;
border-radius: 50%;
border: 4rpx solid var(--theme-border);
}
.select-dot.active {
border-color: var(--theme-primary);
background: var(--theme-primary);
}
.cart-thumb {
width: 140rpx;
height: 140rpx;
border-radius: 22rpx;
background: var(--theme-primary-soft);
}
.cart-main {
flex: 1;
}
.cart-title-row {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16rpx;
}
.cart-title {
flex: 1;
min-width: 0;
font-size: 30rpx;
font-weight: 700;
line-height: 1.5;
color: var(--text-primary);
}
.cart-price {
font-size: 30rpx;
font-weight: 700;
color: var(--theme-primary-action);
}
.cart-meta-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12rpx;
margin-top: 12rpx;
}
.meta-chip {
display: inline-flex;
align-items: center;
justify-content: center;
height: 42rpx;
padding: 0 16rpx;
border-radius: 999rpx;
background: var(--theme-primary-soft);
color: var(--theme-primary);
font-size: 20rpx;
font-weight: 700;
}
.cart-meta {
font-size: 24rpx;
color: var(--text-secondary);
}
.selector-group {
margin-top: 24rpx;
}
.selector-row {
display: flex;
align-items: center;
justify-content: space-between;
min-height: 76rpx;
padding: 0 22rpx;
border-radius: 20rpx;
background: var(--theme-primary-soft);
}
.selector-row.compact {
min-height: 72rpx;
}
.selector-row.issue {
background: var(--theme-secondary-soft);
}
.selector-label {
font-size: 24rpx;
color: var(--text-secondary);
}
.selector-value {
font-size: 24rpx;
color: var(--text-primary);
font-weight: 600;
}
.time-grid {
display: flex;
gap: 14rpx;
margin-top: 14rpx;
}
.time-grid picker {
flex: 1;
}
.appointment-preview {
margin-top: 14rpx;
font-size: 24rpx;
color: var(--text-secondary);
}
.cart-item-foot {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 24rpx;
}
.qty-box {
display: flex;
align-items: center;
gap: 16rpx;
}
.qty-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 56rpx;
height: 56rpx;
border-radius: 50%;
background: var(--theme-primary-soft);
color: var(--theme-primary-action);
font-size: 34rpx;
}
.qty-value {
min-width: 48rpx;
text-align: center;
font-size: 28rpx;
font-weight: 700;
color: var(--text-primary);
}
.remove-btn {
font-size: 24rpx;
color: var(--theme-primary-action);
font-weight: 700;
}
.coupon-card,
.summary-card {
padding: 26rpx;
}
.coupon-option {
display: flex;
align-items: center;
gap: 18rpx;
margin-top: 20rpx;
padding: 20rpx 0;
border-top: 2rpx solid var(--theme-border);
}
.coupon-option:first-child {
border-top: 0;
padding-top: 10rpx;
}
.coupon-option.active {
color: var(--theme-primary);
}
.coupon-texts {
flex: 1;
}
.coupon-name {
font-size: 26rpx;
font-weight: 700;
color: var(--text-primary);
}
.coupon-desc {
margin-top: 8rpx;
font-size: 22rpx;
color: var(--text-secondary);
}
.coupon-tag {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 92rpx;
height: 44rpx;
padding: 0 14rpx;
border-radius: 999rpx;
background: var(--theme-primary-soft);
color: var(--theme-primary);
font-size: 20rpx;
font-weight: 700;
}
.unavailable-coupon-list {
margin-top: 22rpx;
padding-top: 18rpx;
border-top: 2rpx solid var(--theme-border);
}
.unavailable-title {
font-size: 24rpx;
font-weight: 700;
color: var(--text-secondary);
}
.unavailable-coupon {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 18rpx;
margin-top: 14rpx;
font-size: 22rpx;
color: var(--text-secondary);
}
.unavailable-coupon text:first-child {
flex: 1;
min-width: 0;
color: var(--theme-neutral);
}
.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: var(--theme-neutral);
font-size: 24rpx;
line-height: 1.6;
}
.summary-vip {
color: var(--theme-primary);
font-weight: 700;
}
.summary-row {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10rpx 0;
font-size: 26rpx;
color: var(--theme-neutral);
}
.summary-row.total {
margin-top: 10rpx;
padding-top: 18rpx;
border-top: 2rpx solid var(--theme-border);
font-size: 30rpx;
font-weight: 700;
color: var(--text-primary);
}
.checkout-bar {
position: fixed;
left: 24rpx;
right: 24rpx;
bottom: calc(env(safe-area-inset-bottom) + 20rpx);
z-index: 20;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20rpx;
padding: 18rpx 20rpx;
border-radius: 30rpx;
background: rgba(255, 255, 255, 0.98);
box-shadow: 0 18rpx 50rpx rgba(122, 67, 88, 0.12);
}
.checkout-copy {
flex: 1;
}
.checkout-total {
font-size: 36rpx;
font-weight: 800;
color: var(--theme-primary-action);
}
.checkout-meta {
margin-top: 8rpx;
font-size: 22rpx;
color: var(--text-secondary);
}
.checkout-btn {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 220rpx;
height: 84rpx;
padding: 0 26rpx;
border-radius: 999rpx;
background: var(--theme-gradient);
color: var(--theme-tertiary);
font-size: 28rpx;
font-weight: 700;
}