功能:重建指尖管理师规划系统

This commit is contained in:
xiaowang
2026-06-04 16:39:06 +08:00
parent 73483e7b0c
commit 677890f518
413 changed files with 9602 additions and 795 deletions
+239 -42
View File
@@ -9,7 +9,11 @@
</header>
<main class="content cart-content">
<a-empty v-if="!cartItems.length" class="empty-cart" description="购物车还是空的">
<div v-if="cartLoading && !cartLoaded" class="cart-loading-state" role="status" aria-label="加载购物车">
<a-spin />
</div>
<a-empty v-else-if="cartLoaded && !cartItems.length" class="empty-cart" description="购物车还是空的">
<a-button type="primary" class="empty-action" @click="router.push('/products')">去逛作品</a-button>
</a-empty>
@@ -46,11 +50,11 @@
<p class="product-meta">
<span>{{ item.tagNames || item.tags || checkoutShopName }}</span>
<span v-if="item.approximateDuration">预计 {{ item.approximateDuration }}</span>
<span>预计 {{ displayCartDuration(item) }}</span>
</p>
<div class="product-bottom">
<strong class="product-price">¥{{ Number(item.price || 0).toFixed(2) }}</strong>
<strong class="product-price">参考价 ¥{{ Number(item.price || 0).toFixed(2) }}</strong>
<div class="product-qty" aria-label="调整数量">
<button type="button" :disabled="item.quantity <= 1" @click="changeQuantity(item, -1)">−</button>
<span>{{ item.quantity }}</span>
@@ -71,7 +75,7 @@
<div v-if="selectedCount && firstCheckoutIssue" class="issue-callout stitch-issue">
<div>
<strong>{{ firstCheckoutIssue.message }}</strong>
<span>完善服务信息后即可提交订单</span>
<span>完善服务信息后即可发起询价预约</span>
</div>
<a-button size="small" @click="focusFirstIssue">去完善</a-button>
</div>
@@ -128,7 +132,7 @@
</div>
<div class="service-time-grid">
<button
v-for="slot in quickAppointmentSlots"
v-for="slot in getQuickAppointmentSlots(item)"
:key="`${item.id}-${slot.value}`"
type="button"
class="service-time-option"
@@ -168,11 +172,15 @@
</div>
</section>
<section class="cart-section summary-panel stitch-summary" aria-label="订单摘要">
<h3>订单摘要</h3>
<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 class="cart-section summary-panel stitch-summary" aria-label="询价预约摘要">
<h3>询价预约摘要</h3>
<label class="quote-remark-field">
<span>备注</span>
<a-textarea v-model:value="quoteRemark" :rows="3" :maxlength="300" placeholder="可填写款式偏好、到店需求或其他说明" />
</label>
<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>
</template>
</main>
@@ -183,11 +191,11 @@
size="large"
class="checkout-button"
:loading="submittingOrder"
:disabled="submittingOrder || !selectedCount"
:disabled="submittingOrder || !selectedCount || Boolean(firstCheckoutIssue)"
@click="checkout"
>
<CheckCircleOutlined />
确认订单
发起询价预约
</a-button>
</footer>
@@ -219,7 +227,7 @@
</div>
</div>
<div class="coupon-tip">
{{ checkoutPreview?.vipTip || '系统会按本次订单金额自动预选减免最高的一张券,也可以手动选择不使用优惠。' }}
{{ checkoutPreview?.vipTip || '系统会按本次询价预约的参考金额预估减免最高的一张券,也可以手动选择不使用优惠。' }}
</div>
</a-modal>
@@ -298,7 +306,7 @@ import { cartApi } from '../api/cart'
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
*/
import { orderApi } from '../api/order'
import type { CheckoutCouponPreview, CheckoutPreview } from '../api/order'
import type { CheckoutCouponPreview, CheckoutIssue as ApiCheckoutIssue, CheckoutPreview } from '../api/order'
import { shopApi } from '../api/shop'
import type { IdType } from '@/utils/id'
import { sameId, toOptionalIdString } from '@/utils/id'
@@ -364,6 +372,9 @@ interface CartItem {
tags: string
tagNames?: string
approximateDuration?: string
serviceDurationMinutes?: number
estimatedTime?: number
businessHours?: string
bookableArtists?: string
availableBookableArtistCount?: number
bookableArtistRestricted?: boolean
@@ -382,6 +393,8 @@ interface CheckoutIssue {
key: string
message: string
itemId?: IdType
productId?: IdType
productTitle?: string
}
/**
@@ -389,6 +402,8 @@ interface CheckoutIssue {
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const cartItems = ref<CartItem[]>([])
const cartLoading = ref(false)
const cartLoaded = ref(false)
/**
* Purpose: itemRefs supports CartView.vue by holding or executing the item refs 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.
@@ -406,6 +421,7 @@ const checkoutPreview = ref<CheckoutPreview | null>(null)
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const selectedCoupon = ref<CheckoutCouponPreview | null>(null)
const quoteRemark = ref('')
/** 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. */
@@ -433,6 +449,7 @@ const draftArtistId = ref<IdType>()
const draftAppointmentTime = ref('')
/** currentShopHours is a reactive state variable used by the template and event handlers. */
const currentShopHours = ref('')
const shopHoursById = ref<Record<string, string>>({})
/** 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 "立即预约". */
@@ -478,11 +495,19 @@ const bookingTitle = computed(() => currentItem.value ? `为 ${currentItem.value
const bookingHelperText = computed(() => {
const texts: string[] = []
if (currentShopHours.value) texts.push(`门店营业时间:${currentShopHours.value}`)
if (currentItem.value?.approximateDuration) texts.push(`预计时长:${currentItem.value.approximateDuration}`)
if (currentItem.value) texts.push(`预计时长:${displayCartDuration(currentItem.value)}`)
return texts.join(' · ') || '请选择至少晚于当前 5 分钟的预约时间'
})
/** quickAppointmentSlots is a reactive state variable used by the template and event handlers. */
const quickAppointmentSlots = computed(() => {
if (currentItem.value) {
return getQuickAppointmentSlots(currentItem.value)
}
return buildQuickAppointmentSlots()
})
const buildQuickAppointmentSlots = (item?: CartItem) => {
const now = getMinAppointmentDate()
const today = new Date(now)
const nextHour = new Date(now)
@@ -497,14 +522,20 @@ const quickAppointmentSlots = computed(() => {
const weekendMorning = nextWeekendMorning(today)
return [nextHour, tomorrowMorning, tomorrowAfternoon, afterTomorrowAfternoon, weekendMorning]
.filter((date, index, list) => date.getTime() >= now.getTime() && list.findIndex(item => item.getTime() === date.getTime()) === index)
.filter((date, index, list) =>
date.getTime() >= now.getTime()
&& list.findIndex(current => current.getTime() === date.getTime()) === index
&& isAppointmentWithinBusinessHours(date, item)
)
.slice(0, 5)
.map(date => ({
value: formatAppointmentValue(date),
label: quickDateLabel(date),
time: `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}))
})
}
const getQuickAppointmentSlots = (item: CartItem) => buildQuickAppointmentSlots(item)
/** getMinAppointmentDate is a local helper used by this page script. */
const getMinAppointmentDate = () => {
@@ -546,6 +577,61 @@ const formatAppointmentValue = (date: Date) => {
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:00`
}
const parseDurationMinutes = (value?: string | number | null): number | null => {
if (value == null || value === '') return null
if (typeof value === 'number') return Number.isFinite(value) && value > 0 ? value : null
const text = String(value).trim()
const hourMatch = text.match(/(\d+(?:\.\d+)?)\s*(?:小时|h|hour)/i)
const minuteMatch = text.match(/(\d+(?:\.\d+)?)\s*(?:分钟|min|minute)/i)
if (hourMatch || minuteMatch) {
const hours = hourMatch ? Number(hourMatch[1]) : 0
const minutes = minuteMatch ? Number(minuteMatch[1]) : 0
const total = Math.round(hours * 60 + minutes)
return total > 0 ? total : null
}
const numberMatch = text.match(/\d+(?:\.\d+)?/)
if (!numberMatch) return null
const total = Math.round(Number(numberMatch[0]))
return total > 0 ? total : null
}
const getCartDurationMinutes = (item: CartItem): number | null => {
return parseDurationMinutes(item.approximateDuration)
?? parseDurationMinutes(item.serviceDurationMinutes)
?? parseDurationMinutes(item.estimatedTime)
}
const displayCartDuration = (item: CartItem) => {
const duration = item.approximateDuration?.trim()
if (duration) return duration
const minutes = getCartDurationMinutes(item)
return minutes ? `${minutes}分钟` : '时长待定'
}
const parseBusinessHoursRange = (value?: string | null): { open: number; close: number } | null => {
const text = String(value || '').replace(/[:]/g, ':').replace(/[-—–]/g, '-')
const match = text.match(/(\d{1,2}):(\d{2})\s*-\s*(\d{1,2}):(\d{2})/)
if (!match) return null
const open = Number(match[1]) * 60 + Number(match[2])
const close = Number(match[3]) * 60 + Number(match[4])
if (!Number.isFinite(open) || !Number.isFinite(close) || close <= open) return null
return { open, close }
}
const getItemBusinessHours = (item?: CartItem) => {
if (!item) return ''
const shopKey = toOptionalIdString(item.shopId)
return item.businessHours || (shopKey ? shopHoursById.value[shopKey] : '') || ''
}
const isAppointmentWithinBusinessHours = (date: Date, item?: CartItem) => {
const range = parseBusinessHoursRange(getItemBusinessHours(item))
if (!range) return true
const start = date.getHours() * 60 + date.getMinutes()
const duration = item ? getCartDurationMinutes(item) || 0 : 0
return start >= range.open && start + duration <= range.close
}
/** quickDateLabel is a local helper used by this page script. */
const quickDateLabel = (date: Date) => {
const today = new Date()
@@ -637,6 +723,20 @@ const appointmentStatusText = (item: CartItem) => {
return '已完成'
}
const mapApiCheckoutIssue = (issue: ApiCheckoutIssue): CheckoutIssue | null => {
if (!issue?.message) return null
const matchedItem = selectedItems.value.find(item => issue.itemId != null && sameId(item.id, issue.itemId))
|| selectedItems.value.find(item => issue.productId != null && sameId(item.productId, issue.productId))
return {
key: `server-${issue.code || issue.message}`,
message: issue.message,
itemId: matchedItem?.id || issue.itemId,
productId: issue.productId,
productTitle: issue.productTitle || matchedItem?.productTitle
}
}
// 购物车结算口径要求单店铺、单美甲师、完整预约信息,避免后端拆单和排班出现歧义。
const checkoutIssues = computed<CheckoutIssue[]>(() => {
const items = selectedItems.value
@@ -674,6 +774,12 @@ const checkoutIssues = computed<CheckoutIssue[]>(() => {
issues.push({ key: 'artist-mix', message: '不同美甲师的项目请分开结算', itemId: items[0]?.id })
}
const apiIssues = checkoutPreview.value?.bookingIssues || []
apiIssues
.map(mapApiCheckoutIssue)
.filter((issue): issue is CheckoutIssue => Boolean(issue))
.forEach(issue => issues.push(issue))
return issues
})
@@ -699,34 +805,101 @@ const focusFirstIssue = () => {
scrollToIssue(checkoutIssues.value[0])
}
const isDisplayableImageSource = (value?: string | null) => {
const source = String(value || '').trim()
return source.startsWith('http://')
|| source.startsWith('https://')
|| source.startsWith('/')
|| source.startsWith('data:image/')
|| source.startsWith('blob:')
}
const getInitialCartImage = (rawImage?: string, previousImage?: string) => {
const imageId = extractLegacyFileId(rawImage)
const cachedUrl = imageId ? getCachedSignedImageUrlSync(imageId) : ''
if (cachedUrl) return cachedUrl
if (previousImage) return previousImage
return isDisplayableImageSource(rawImage) ? String(rawImage) : ''
}
/** loadCartItems is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadCartItems = async () => {
const response = await cartApi.getCartList() as unknown as any[]
cartItems.value = (response || []).map(item => ({
...item,
selected: isBuyNowMode.value ? isBuyNowCartItem(item.productId, buyNowProductId.value) : true,
originalProductImage: item.productImage,
productImage: '',
appointmentTime: item.appointmentTime
}))
couponSelectionTouched.value = false
couponSelectionKey.value = NO_COUPON_KEY
selectedCoupon.value = null
await Promise.all([loadProductImages(), loadAvailableCoupons()])
cartLoading.value = true
try {
const response = await cartApi.getCartList() as unknown as any[]
const previousItems = cartItems.value
cartItems.value = (response || []).map(item => {
const previous = previousItems.find(current => sameId(current.id, item.id))
|| previousItems.find(current => sameId(current.productId, item.productId))
const originalProductImage = item.productImage || previous?.originalProductImage || ''
const shopKey = toOptionalIdString(item.shopId)
return {
...item,
selected: isBuyNowMode.value ? isBuyNowCartItem(item.productId, buyNowProductId.value) : previous?.selected ?? true,
originalProductImage,
productImage: getInitialCartImage(originalProductImage, previous?.productImage),
appointmentTime: item.appointmentTime,
businessHours: item.businessHours || previous?.businessHours || (shopKey ? shopHoursById.value[shopKey] : '')
}
})
couponSelectionTouched.value = false
couponSelectionKey.value = NO_COUPON_KEY
selectedCoupon.value = null
await Promise.all([loadProductImages(), loadCartItemShopHours()])
await loadAvailableCoupons()
} finally {
cartLoading.value = false
cartLoaded.value = true
}
}
/** loadProductImages is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadProductImages = async () => {
for (const item of cartItems.value) {
if (!item.originalProductImage) continue
if (!item.originalProductImage) {
continue
}
const imageId = extractLegacyFileId(item.originalProductImage)
if (!imageId) continue
if (!imageId) {
if (!item.productImage && isDisplayableImageSource(item.originalProductImage)) {
item.productImage = item.originalProductImage
}
continue
}
const cachedUrl = getCachedSignedImageUrlSync(imageId)
if (cachedUrl) item.productImage = cachedUrl
item.productImage = await getCachedSignedImageUrl(imageId)
const signedUrl = await getCachedSignedImageUrl(imageId, item.productImage || item.originalProductImage)
if (signedUrl) item.productImage = signedUrl
}
}
const loadCartItemShopHours = async () => {
const shopIds = Array.from(new Set(
cartItems.value
.map(item => toOptionalIdString(item.shopId))
.filter((shopId): shopId is string => Boolean(shopId))
.filter(shopId => !shopHoursById.value[shopId])
))
await Promise.all(shopIds.map(async shopId => {
try {
const shop = await shopApi.getShopById(shopId) as any
const businessHours = String(shop?.businessHours || '')
if (businessHours) {
shopHoursById.value = { ...shopHoursById.value, [shopId]: businessHours }
}
} catch {
shopHoursById.value = { ...shopHoursById.value, [shopId]: '' }
}
}))
cartItems.value.forEach(item => {
const shopKey = toOptionalIdString(item.shopId)
if (shopKey && !item.businessHours && shopHoursById.value[shopKey]) {
item.businessHours = shopHoursById.value[shopKey]
}
})
}
/** 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
@@ -744,6 +917,7 @@ const loadAvailableCoupons = async () => {
const preview = await orderApi.checkoutPreview({
couponId: selectedCoupon.value?.id,
couponSourceType: selectedCoupon.value?.sourceType || (couponSelectionTouched.value && currentSelectedKey === NO_COUPON_KEY ? NO_COUPON_KEY : undefined),
remark: quoteRemark.value.trim() || undefined,
items: selectedItems.value.map(item => ({
productId: item.productId,
quantity: item.quantity,
@@ -876,9 +1050,17 @@ const loadArtists = async (item: CartItem) => {
const loadShopHours = async (shopId?: IdType) => {
currentShopHours.value = ''
if (!shopId) return
const shopKey = toOptionalIdString(shopId)
if (shopKey && shopHoursById.value[shopKey]) {
currentShopHours.value = shopHoursById.value[shopKey]
return
}
try {
const shop = await shopApi.getShopById(shopId) as any
currentShopHours.value = shop?.businessHours || ''
if (shopKey) {
shopHoursById.value = { ...shopHoursById.value, [shopKey]: currentShopHours.value }
}
} catch {
currentShopHours.value = ''
}
@@ -958,15 +1140,15 @@ const applyCouponSelection = async () => {
const openCheckoutRecovery = (error: unknown) => {
const actions = buildRecoveryActions([
{ key: 'retry', text: '重试下单' },
{ key: 'retry', text: '重试发起询价' },
{ key: 'orders', text: '查看订单' }
])
const retryAction = actions[0]
const ordersAction = actions[1]
Modal.confirm({
title: '下单失败',
content: `${getRecoveryMessage(error, '订单创建失败')}。如果担心重复下单,请先查看订单;仍失败时请联系客服。`,
okText: retryAction?.text || '重试下单',
title: '发起询价预约失败',
content: `${getRecoveryMessage(error, '询价预约发起失败')}。如果担心重复提交,请先查看订单;仍失败时请联系客服。`,
okText: retryAction?.text || '重试发起询价',
cancelText: ordersAction?.text || '查看订单',
onOk: () => checkout(),
onCancel: () => router.push(ordersAction?.route || '/orders')
@@ -992,9 +1174,10 @@ const checkout = async () => {
submittingOrder.value = true
try {
await runWithGlobalLoading(() => orderApi.createOrder({
await runWithGlobalLoading(() => orderApi.createInquiryAppointment({
couponId: selectedCoupon.value?.id,
couponSourceType: selectedCoupon.value?.sourceType || (couponSelectionTouched.value && !selectedCoupon.value ? NO_COUPON_KEY : undefined),
remark: quoteRemark.value.trim() || undefined,
items: items.map(item => ({
productId: item.productId,
quantity: item.quantity,
@@ -1002,7 +1185,7 @@ const checkout = async () => {
appointmentTime: item.appointmentTime
}))
}))
message.success('订单创建成功')
message.success('询价预约已发起,等待门店确认价格')
let followupWarningShown = false
try {
@@ -1010,16 +1193,16 @@ const checkout = async () => {
await updateCartCount()
} catch (followupError) {
followupWarningShown = true
console.error('订单创建后刷新购物车失败:', followupError)
message.warning('订单已创建,但购物车刷新失败,请前往订单页查看')
console.error('询价预约发起后刷新购物车失败:', followupError)
message.warning('询价预约已发起,但购物车刷新失败,请前往订单页查看')
}
try {
await router.push('/orders')
} catch (navigationError) {
console.error('订单创建后跳转订单页失败:', navigationError)
console.error('询价预约发起后跳转订单页失败:', navigationError)
if (!followupWarningShown) {
message.warning('订单已创建,但跳转订单页失败,请手动前往订单页查看')
message.warning('询价预约已发起,但跳转订单页失败,请手动前往订单页查看')
}
}
} catch (error: any) {
@@ -1108,6 +1291,12 @@ onMounted(async () => {
box-shadow: 0 18px 44px color-mix(in srgb, var(--theme-neutral) 8%, transparent);
}
.cart-loading-state {
display: grid;
min-height: 56vh;
place-items: center;
}
.empty-cart :deep(.ant-empty-description) {
color: var(--text-secondary);
}
@@ -1715,6 +1904,14 @@ onMounted(async () => {
white-space: nowrap;
}
.quote-remark-field {
display: grid;
gap: 8px;
margin-bottom: 14px;
color: var(--text-secondary);
font-size: 13px;
}
.summary-row.discount strong,
.summary-row.total strong {
color: var(--theme-accent);