功能(网页):新增客户体验流程

This commit is contained in:
xiaowang
2026-05-23 21:56:18 +08:00
parent c2c985b2f8
commit 861eea933b
28 changed files with 2236 additions and 108 deletions
+168 -37
View File
@@ -8,8 +8,8 @@
<template v-else>
<section class="checkout-hero" :class="{ 'has-issues': selectedCount && checkoutIssueCount }">
<div class="hero-main">
<p class="hero-eyebrow">购物车</p>
<h1>{{ selectedCount ? '准备结算' : '选择要结算的作品' }}</h1>
<p class="hero-eyebrow">{{ isBuyNowMode ? '确认订单' : '购物车' }}</p>
<h1>{{ cartHeroTitle }}</h1>
<p>{{ checkoutStatusText }}</p>
</div>
<div class="hero-total">
@@ -128,11 +128,16 @@
<RightOutlined />
</button>
<section v-if="checkoutPreview" class="preview-panel">
<div class="preview-line">{{ checkoutPreview.summaryText }}</div>
<div v-if="checkoutPreview.vipTip" class="preview-line vip">{{ checkoutPreview.vipTip }}</div>
</section>
<section class="summary-panel">
<div class="summary-row"><span>选中项目</span><strong>{{ selectedCount }} 项</strong></div>
<div class="summary-row"><span>作品数量</span><strong>{{ totalQuantity }} 件</strong></div>
<div class="summary-row"><span>小计</span><strong>¥{{ subtotal.toFixed(2) }}</strong></div>
<div v-if="selectedCoupon" class="summary-row discount"><span>优惠</span><strong>-¥{{ discountAmount.toFixed(2) }}</strong></div>
<div class="summary-row"><span>商品小计</span><strong>¥{{ subtotal.toFixed(2) }}</strong></div>
<div v-if="discountAmount > 0" class="summary-row discount"><span>已省</span><strong>-¥{{ discountAmount.toFixed(2) }}</strong></div>
<div class="summary-row total"><span>合计</span><strong>¥{{ totalAmount.toFixed(2) }}</strong></div>
</section>
</aside>
@@ -172,11 +177,20 @@
<a-radio-group v-model:value="couponSelectionKey" class="coupon-options">
<a-radio :value="NO_COUPON_KEY">不使用优惠</a-radio>
<a-radio v-for="coupon in availableCoupons" :key="getCouponKey(coupon)" :value="getCouponKey(coupon)">
{{ formatCouponDisplay(coupon) }}
<span class="coupon-option-copy">
<strong>{{ formatCouponDisplay(coupon) }}</strong>
<em>{{ coupon.savingText || `本单可省 ¥${Number(coupon.discountAmount || 0).toFixed(2)}` }}</em>
</span>
</a-radio>
</a-radio-group>
<div v-if="unavailableCoupons.length" class="coupon-unavailable">
<div v-for="coupon in unavailableCoupons" :key="getCouponKey(coupon)" class="coupon-unavailable-item">
<span>{{ formatCouponDisplay(coupon) }}</span>
<em>{{ coupon.unavailableReason || '本单暂不可用' }}</em>
</div>
</div>
<div class="coupon-tip">
系统会按本次订单金额自动预选减免最高的一张券,也可以手动选择不使用优惠。
{{ checkoutPreview?.vipTip || '系统会按本次订单金额自动预选减免最高的一张券,也可以手动选择不使用优惠。' }}
</div>
</a-modal>
@@ -240,28 +254,32 @@
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, inject, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useRoute, useRouter } from 'vue-router'
import { DeleteOutlined, RightOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { message, Modal } from 'ant-design-vue'
import type { ButtonProps } from 'ant-design-vue/es/button/buttonTypes'
import { cartApi } from '../api/cart'
/**
* Purpose: UserCoupon supports CartView.vue by holding or executing the user coupon page or API role.
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
*/
import { couponApi, type UserCoupon } from '../api/coupon'
import { fileApi } from '../api/index'
import { orderApi } from '../api/order'
import type { CheckoutCouponPreview, CheckoutPreview } from '../api/order'
import { shopApi } from '../api/shop'
import type { IdType } from '@/utils/id'
import { sameId, toOptionalIdString } from '@/utils/id'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { getBuyNowProductIdFromQuery, isBuyNowCartItem } from '@/utils/buy-now'
import { buildRecoveryActions, getRecoveryMessage } from '@/utils/recovery'
/**
* Purpose: router supports CartView.vue by holding or executing the router 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 router = useRouter()
/** route exposes cart query parameters, including the one-shot buyNow checkout target. */
const route = useRoute()
/**
* Purpose: updateCartCount supports CartView.vue by holding or executing the update cart count 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.
@@ -350,12 +368,14 @@ const itemRefs = ref<Record<string, HTMLElement>>({})
* Purpose: availableCoupons supports CartView.vue by holding or executing the available coupons 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 availableCoupons = ref<UserCoupon[]>([])
const availableCoupons = ref<CheckoutCouponPreview[]>([])
const unavailableCoupons = ref<CheckoutCouponPreview[]>([])
const checkoutPreview = ref<CheckoutPreview | null>(null)
/**
* Purpose: selectedCoupon supports CartView.vue by holding or executing the selected coupon 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 selectedCoupon = ref<UserCoupon | null>(null)
const selectedCoupon = ref<CheckoutCouponPreview | null>(null)
/** couponSelectionKey is a reactive state variable used by the template and event handlers. */
const couponSelectionKey = ref(NO_COUPON_KEY)
/** couponSelectionTouched is a reactive state variable used by the template and event handlers. */
@@ -385,6 +405,10 @@ const draftAppointmentTime = ref('')
const currentShopHours = ref('')
/** submittingOrder is a reactive state variable used by the template and event handlers. */
const submittingOrder = ref(false)
/** buyNowProductId limits checkout selection to the product that opened cart from "立即预约". */
const buyNowProductId = computed(() => getBuyNowProductIdFromQuery(route.query))
/** isBuyNowMode switches cart copy into a focused order-confirmation experience. */
const isBuyNowMode = computed(() => Boolean(buyNowProductId.value))
/** selectedItems is a reactive state variable used by the template and event handlers. */
const selectedItems = computed(() => cartItems.value.filter(item => item.selected))
@@ -393,11 +417,19 @@ const selectedCount = computed(() => selectedItems.value.length)
/** totalQuantity is a reactive state variable used by the template and event handlers. */
const totalQuantity = computed(() => selectedItems.value.reduce((sum, item) => sum + item.quantity, 0))
/** subtotal is a reactive state variable used by the template and event handlers. */
const subtotal = computed(() => selectedItems.value.reduce((sum, item) => sum + Number(item.price || 0) * item.quantity, 0))
const localSubtotal = computed(() => selectedItems.value.reduce((sum, item) => sum + Number(item.price || 0) * item.quantity, 0))
const subtotal = computed(() => Number(checkoutPreview.value?.subtotalAmount ?? localSubtotal.value))
/** discountAmount is a reactive state variable used by the template and event handlers. */
const discountAmount = computed(() => calculateCouponDiscount(selectedCoupon.value, subtotal.value))
const discountAmount = computed(() => Number(checkoutPreview.value?.savedAmount ?? calculateCouponDiscount(selectedCoupon.value, subtotal.value)))
/** totalAmount is a reactive state variable used by the template and event handlers. */
const totalAmount = computed(() => Math.max(0, subtotal.value - discountAmount.value))
const totalAmount = computed(() => Number(checkoutPreview.value?.payableAmount ?? Math.max(0, subtotal.value - discountAmount.value)))
/** cartHeroTitle names the current checkout mode for the first screen. */
const cartHeroTitle = computed(() => {
if (isBuyNowMode.value) {
return selectedCount.value ? '确认本次预约订单' : '请选择本次预约项目'
}
return selectedCount.value ? '确认订单' : '选择要结算的作品'
})
/** bookingTitle is a reactive state variable used by the template and event handlers. */
const bookingTitle = computed(() => currentItem.value ? `为 ${currentItem.value.productTitle} 选择预约信息` : '选择预约信息')
/** bookingHelperText is a reactive state variable used by the template and event handlers. */
@@ -483,7 +515,7 @@ const quickDateLabel = (date: Date) => {
}
/** getCouponKey is a local helper used by this page script. */
const getCouponKey = (coupon: UserCoupon) => `${coupon.sourceType || 'USER_COUPON'}:${coupon.id}`
const getCouponKey = (coupon: CheckoutCouponPreview) => `${coupon.sourceType || 'USER_COUPON'}:${coupon.id}`
/** setItemRef is a local helper used by this page script. */
const setItemRef = (itemId: IdType, element: unknown) => {
@@ -503,7 +535,10 @@ const setItemRef = (itemId: IdType, element: unknown) => {
}
/** formatCouponDisplay is a local helper used by this page script. */
const formatCouponDisplay = (coupon: UserCoupon) => {
const formatCouponDisplay = (coupon: CheckoutCouponPreview) => {
if (coupon.displayText) {
return coupon.displayText
}
const badge = coupon.sourceType === 'SYSTEM_VIP' ? '[VIP 自动券]' : '[用户券]'
const benefit = coupon.couponType === 1
? `${coupon.discountValue} 折`
@@ -512,10 +547,13 @@ const formatCouponDisplay = (coupon: UserCoupon) => {
}
/** calculateCouponDiscount is a local helper used by this page script. */
const calculateCouponDiscount = (coupon: UserCoupon | null, amount: number) => {
const calculateCouponDiscount = (coupon: CheckoutCouponPreview | null, amount: number) => {
if (!coupon || amount <= 0) {
return 0
}
if (coupon.discountAmount !== undefined && coupon.discountAmount !== null) {
return Number(coupon.discountAmount || 0)
}
if (coupon.couponType === 1) {
const discountValue = Number(coupon.discountValue || 0)
return discountValue ? amount - amount * discountValue / 10 : 0
@@ -527,7 +565,7 @@ const calculateCouponDiscount = (coupon: UserCoupon | null, amount: number) => {
}
/** findBestCoupon is a local helper used by this page script. */
const findBestCoupon = (coupons: UserCoupon[]) => {
const findBestCoupon = (coupons: CheckoutCouponPreview[]) => {
return coupons
.sort((left, right) => calculateCouponDiscount(right, subtotal.value) - calculateCouponDiscount(left, subtotal.value))[0] || null
}
@@ -604,12 +642,12 @@ const firstCheckoutIssue = computed(() => checkoutIssues.value[0])
/** checkoutStatusText is a reactive state variable used by the template and event handlers. */
const checkoutStatusText = computed(() => {
if (!selectedCount.value) {
return '勾选需要结算的作品,完善预约信息后即可提交订单'
return isBuyNowMode.value ? '本次预约只会提交刚刚选择的作品,不会混入购物车其他项目' : '勾选需要结算的作品,完善预约信息后即可提交订单'
}
if (checkoutIssueCount.value) {
return `还有 ${checkoutIssueCount.value} 项预约信息待完善`
}
return selectedCoupon.value ? '预约信息已完成,优惠已计算' : '预约信息已完成,可以提交订单'
return selectedCoupon.value ? '订单信息已确认,优惠已计算' : '订单信息已确认,可以提交订单'
})
/** checkoutActionText is a reactive state variable used by the template and event handlers. */
const checkoutActionText = computed(() => {
@@ -641,7 +679,7 @@ const loadCartItems = async () => {
const response = await cartApi.getCartList() as unknown as any[]
cartItems.value = (response || []).map(item => ({
...item,
selected: true,
selected: isBuyNowMode.value ? isBuyNowCartItem(item.productId, buyNowProductId.value) : true,
originalProductImage: item.productImage,
productImage: '',
appointmentTime: item.appointmentTime
@@ -673,28 +711,30 @@ const loadProductImages = async () => {
/** loadAvailableCoupons is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadAvailableCoupons = async () => {
const currentSelectedKey = selectedCoupon.value ? getCouponKey(selectedCoupon.value) : couponSelectionKey.value
const selectedShopId = selectedItems.value[0]?.shopId
if (!selectedItems.value.length || subtotal.value <= 0) {
if (!selectedItems.value.length || localSubtotal.value <= 0) {
checkoutPreview.value = null
availableCoupons.value = []
unavailableCoupons.value = []
selectedCoupon.value = null
couponSelectionKey.value = NO_COUPON_KEY
return
}
try {
// 这里只做“最佳 VIP 自动券”兜底预选,普通用户券必须显式点选后才会消耗。
const tags = new Set<string>()
selectedItems.value.forEach(item => {
item.tagNames?.split(',').map(tag => tag.trim()).forEach(tag => {
if (tag) {
tags.add(tag)
}
})
const preview = await orderApi.checkoutPreview({
couponId: selectedCoupon.value?.id,
couponSourceType: selectedCoupon.value?.sourceType || (couponSelectionTouched.value && currentSelectedKey === NO_COUPON_KEY ? NO_COUPON_KEY : undefined),
items: selectedItems.value.map(item => ({
productId: item.productId,
quantity: item.quantity,
artistId: item.artistId,
appointmentTime: item.appointmentTime
}))
})
const data = await couponApi.getAvailableCoupons(Array.from(tags).join(','), subtotal.value, selectedShopId) as unknown as UserCoupon[]
availableCoupons.value = Array.isArray(data) ? data : []
checkoutPreview.value = preview
availableCoupons.value = Array.isArray(preview.availableCoupons) ? preview.availableCoupons : []
unavailableCoupons.value = Array.isArray(preview.unavailableCoupons) ? preview.unavailableCoupons : []
const matchedCoupon = availableCoupons.value.find(coupon => getCouponKey(coupon) === currentSelectedKey) || null
if (matchedCoupon) {
@@ -720,7 +760,9 @@ const loadAvailableCoupons = async () => {
}
} catch (error) {
console.error('获取可用优惠失败:', error)
checkoutPreview.value = null
availableCoupons.value = []
unavailableCoupons.value = []
selectedCoupon.value = null
couponSelectionKey.value = NO_COUPON_KEY
}
@@ -852,7 +894,7 @@ const closeBookingModal = () => {
}
/** confirmBooking is a local helper used by this page script. */
const confirmBooking = () => {
const confirmBooking = async () => {
if (!currentItem.value) return closeBookingModal()
if (!draftArtistId.value) return message.warning('请先选择美甲师')
if (!draftAppointmentTime.value) return message.warning('请选择预约时间')
@@ -861,6 +903,7 @@ const confirmBooking = () => {
currentItem.value.artist = availableArtists.value.find(artist => sameId(artist.id, draftArtistId.value))
currentItem.value.appointmentTime = draftAppointmentTime.value
closeBookingModal()
await loadAvailableCoupons()
}
/** openCouponModal is a local helper used by this page script. */
@@ -870,7 +913,7 @@ const openCouponModal = () => {
}
/** applyCouponSelection is a local helper used by this page script. */
const applyCouponSelection = () => {
const applyCouponSelection = async () => {
couponSelectionTouched.value = true
if (couponSelectionKey.value === NO_COUPON_KEY) {
selectedCoupon.value = null
@@ -878,6 +921,24 @@ const applyCouponSelection = () => {
selectedCoupon.value = availableCoupons.value.find(coupon => getCouponKey(coupon) === couponSelectionKey.value) || null
}
showCouponModal.value = false
await runWithGlobalLoading(() => loadAvailableCoupons())
}
const openCheckoutRecovery = (error: unknown) => {
const actions = buildRecoveryActions([
{ key: 'retry', text: '重试下单' },
{ key: 'orders', text: '查看订单' }
])
const retryAction = actions[0]
const ordersAction = actions[1]
Modal.confirm({
title: '下单失败',
content: `${getRecoveryMessage(error, '订单创建失败')}。如果担心重复下单,请先查看订单;仍失败时请联系客服。`,
okText: retryAction?.text || '重试下单',
cancelText: ordersAction?.text || '查看订单',
onOk: () => checkout(),
onCancel: () => router.push(ordersAction?.route || '/orders')
})
}
/** checkout is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
@@ -931,7 +992,7 @@ const checkout = async () => {
}
} catch (error: any) {
console.error('创建订单失败:', error)
message.error(error?.message || '创建订单失败')
openCheckoutRecovery(error)
} finally {
submittingOrder.value = false
}
@@ -1320,6 +1381,7 @@ onMounted(async () => {
}
.coupon-panel,
.preview-panel,
.summary-panel {
border: 1px solid var(--theme-border);
border-radius: 8px;
@@ -1363,6 +1425,23 @@ onMounted(async () => {
white-space: nowrap;
}
.preview-panel {
display: grid;
gap: 6px;
padding: 13px;
}
.preview-line {
color: var(--text-secondary);
font-size: 12px;
line-height: 1.5;
}
.preview-line.vip {
color: var(--theme-primary);
font-weight: 700;
}
.summary-panel {
padding: 13px;
}
@@ -1441,6 +1520,58 @@ onMounted(async () => {
gap: 8px;
}
.coupon-option-copy {
display: grid;
gap: 2px;
min-width: 0;
}
.coupon-option-copy strong,
.coupon-option-copy em {
overflow-wrap: anywhere;
}
.coupon-option-copy strong {
color: var(--text-primary);
}
.coupon-option-copy em {
color: var(--theme-accent);
font-size: 12px;
font-style: normal;
}
.coupon-unavailable {
display: grid;
gap: 8px;
margin-top: 14px;
padding-top: 14px;
border-top: 1px solid var(--theme-border);
}
.coupon-unavailable-item {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
color: var(--text-secondary);
font-size: 12px;
line-height: 1.5;
}
.coupon-unavailable-item span {
min-width: 0;
color: var(--text-primary);
overflow-wrap: anywhere;
}
.coupon-unavailable-item em {
max-width: 180px;
color: var(--text-secondary);
font-style: normal;
text-align: right;
}
:global(.cart-coupon-modal-wrap .ant-modal) {
max-width: calc(100vw - 24px);
}