/** * 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') /** * 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), 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 }) } } })