完成JC-ArtList与JC-Salon端侧清理和统一命名

This commit is contained in:
2026-08-25 16:21:05 +08:00
parent aa93695704
commit abce4a2787
1839 changed files with 653 additions and 50415 deletions
+437
View File
@@ -0,0 +1,437 @@
<template>
<el-config-provider>
<ConfigProvider :locale="antdLocale" :theme="antdTheme">
<div class="app-container app-container--phone-shell">
<div class="fingertip-designer-phone-frame" :class="{ 'fingertip-designer-phone-frame--hidden-nav': isHiddenNav }">
<BottomNav v-if="!isHiddenNav" />
<div class="page-content" :class="{ 'no-nav-padding': isHiddenNav }">
<router-view v-slot="{ Component }">
<component :is="Component" :key="route.path" />
</router-view>
</div>
</div>
</div>
</ConfigProvider>
</el-config-provider>
</template>
<script setup lang="ts">
/**
* App page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, h, onMounted, onUnmounted, provide, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ConfigProvider, Modal } from 'ant-design-vue'
import type { ButtonProps } from 'ant-design-vue/es/button/buttonTypes'
import type { ThemeConfig } from 'ant-design-vue/es/config-provider/context'
import { CheckOutlined } from '@ant-design/icons-vue'
import BottomNav from './components/BottomNav.vue'
import SystemMessageCard from './components/SystemMessageCard.vue'
import { cartApi } from './api/cart'
/**
* Purpose: SystemMessageVO supports App.vue by holding or executing the system message vo 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 { userApi, type SystemMessageVO } from './api/user'
import antdLocale from './config/antdv-locale'
import { useGlobalConfirmEnter } from './composables/useConfirmEnter'
import { useShopTheme } from './composables/useShopTheme'
import { buildSystemMessageActionPath } from './utils/system-message-action'
/**
* Purpose: route supports App.vue by holding or executing the route 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 route = useRoute()
/**
* Purpose: router supports App.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()
const { currentTheme, refreshShopTheme, setupShopThemeSync } = useShopTheme()
useGlobalConfirmEnter()
/**
* Purpose: ButtonPropsWithClass supports App.vue by holding or executing the button props with class 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.
*/
type ButtonPropsWithClass = ButtonProps & { class?: string }
const popupMessageOkButtonProps: ButtonPropsWithClass = { class: 'popup-message-ok-button' }
/** routerReady is a reactive state variable used by the template and event handlers. */
const routerReady = ref(false)
let stopThemeSync: (() => void) | undefined
const customerThemeRefreshOptions = { mode: 'customer' as const }
const bottomNavRouteNames = new Set(['home', 'products', 'cart', 'profile'])
/** isHiddenNav is a reactive state variable used by the template and event handlers. */
const isHiddenNav = computed(() => {
if (!routerReady.value) {
return true
}
return !bottomNavRouteNames.has(String(route.name || ''))
})
/**
* Purpose: antdTheme supports App.vue by holding or executing the antd 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 antdTheme = computed<ThemeConfig>(() => ({
token: {
colorPrimary: currentTheme.value.primaryColor,
colorLink: currentTheme.value.primaryColor,
borderRadius: 8
},
components: {
Button: {
colorPrimary: currentTheme.value.primaryColor,
colorPrimaryHover: currentTheme.value.accentColor,
colorPrimaryActive: currentTheme.value.accentColor
},
Radio: {
colorPrimary: currentTheme.value.primaryColor
},
Input: {
activeBorderColor: currentTheme.value.primaryColor,
hoverBorderColor: currentTheme.value.primaryColor
}
}
}))
// 全局购物车数量状态
/** cartCount is a reactive state variable used by the template and event handlers. */
const cartCount = ref(0)
/** checkingPopupMessages is a reactive state variable used by the template and event handlers. */
const checkingPopupMessages = ref(false)
// 加载购物车数量
/** loadCartCount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadCartCount = async () => {
try {
// 检查用户是否已登录
const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
if (!token) {
cartCount.value = 0
return
}
const response = await cartApi.getCartList() as any
const data = response || []
const cartList = Array.isArray(data) ? data : []
const totalQuantity = cartList.reduce((sum: number, item: any) => sum + (item.quantity || 0), 0)
cartCount.value = totalQuantity
} catch (error) {
cartCount.value = 0
}
}
// 提供更新购物车数量的方法
/** updateCartCount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const updateCartCount = async () => {
await loadCartCount()
}
/**
* Purpose: resolveSystemMessageActionPath supports App.vue by holding or executing the resolve system message action path 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 resolveSystemMessageActionPath = (item: SystemMessageVO) => {
return buildSystemMessageActionPath(item)
}
/**
* Purpose: openSystemMessageAction supports App.vue by holding or executing the open system message action 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 openSystemMessageAction = async (item: SystemMessageVO) => {
const actionPath = resolveSystemMessageActionPath(item)
if (!actionPath) {
return
}
await router.push(actionPath)
}
/** showPopupMessage is a local helper used by this page script. */
const showPopupMessage = (item: SystemMessageVO) => {
return new Promise<void>((resolve) => {
let settled = false
/** markShownAndResolve is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const markShownAndResolve = async () => {
if (settled) {
return
}
settled = true
await userApi.markMessagePopupShown(item.id)
resolve()
}
const metaText = `${item.publisherName || '系统消息'} · ${item.publishTime || item.createTime || '刚刚'}`
Modal.info({
icon: null,
centered: true,
width: 560,
class: 'fingertip-designer-system-message-dialog',
wrapClassName: 'fingertip-designer-system-message-wrap',
content: h(SystemMessageCard, {
title: item.title || '系统消息',
content: item.content || '',
imageUrl: item.imageUrl || '',
meta: metaText,
surface: 'modal'
}),
okText: h('span', { class: 'popup-message-ok-text' }, [
h(CheckOutlined),
h('span', '我知道了')
]),
okButtonProps: popupMessageOkButtonProps,
async onOk() {
await markShownAndResolve()
await openSystemMessageAction(item)
},
async afterClose() {
await markShownAndResolve()
}
})
})
}
/** checkPopupMessages is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const checkPopupMessages = async () => {
const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
if (!token || checkingPopupMessages.value) {
return
}
checkingPopupMessages.value = true
try {
const messages = await userApi.listMyPopupMessages()
for (const item of messages || []) {
await showPopupMessage(item)
}
} catch (error) {
console.error('加载待弹窗消息失败:', error)
} finally {
checkingPopupMessages.value = false
}
}
provide('updateCartCount', updateCartCount)
provide('cartCount', cartCount)
// 监听路由变化,更新购物车数量
watch(() => route.path, async () => {
await refreshShopTheme(customerThemeRefreshOptions)
await loadCartCount()
await checkPopupMessages()
})
// 页面加载时获取购物车数量
loadCartCount()
onMounted(async () => {
stopThemeSync = setupShopThemeSync()
await router.isReady()
routerReady.value = true
await refreshShopTheme(customerThemeRefreshOptions)
await checkPopupMessages()
})
onUnmounted(() => {
stopThemeSync?.()
})
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: var(--text-primary);
}
.app-container {
min-height: 100vh;
display: flex;
flex-direction: column;
position: relative;
}
.page-content {
flex: 1;
padding-bottom: 60px;
position: relative;
z-index: 1;
}
/* 当导航栏隐藏时,移除底部 padding */
.page-content.no-nav-padding {
padding-bottom: 0;
}
.fingertip-designer-date-picker-panel {
padding: 6px;
}
.fingertip-designer-date-picker-panel .ant-picker-panel-container {
overflow: hidden;
border-radius: 12px;
box-shadow: 0 18px 44px rgba(34, 40, 49, 0.18);
}
.fingertip-designer-date-picker-panel .ant-picker-panel {
border: 0;
}
.fingertip-designer-date-picker-panel .ant-picker-header {
padding: 8px 12px;
border-bottom-color: var(--theme-border);
}
.fingertip-designer-date-picker-panel .ant-picker-header button {
min-width: 34px;
height: 34px;
border-radius: 8px;
}
.fingertip-designer-date-picker-panel .ant-picker-header-view {
line-height: 34px;
font-weight: 700;
}
.fingertip-designer-date-picker-panel .ant-picker-content th {
height: 34px;
color: var(--text-secondary);
font-weight: 600;
}
.fingertip-designer-date-picker-panel .ant-picker-cell {
padding: 4px 0;
}
.fingertip-designer-date-picker-panel .ant-picker-cell-inner {
min-width: 34px;
height: 34px !important;
line-height: 34px !important;
border-radius: 8px !important;
transition: background .18s ease, color .18s ease, transform .18s ease;
}
.fingertip-designer-date-picker-panel .ant-picker-cell:hover .ant-picker-cell-inner {
background: var(--theme-primary-soft);
transform: translateY(-1px);
}
.fingertip-designer-date-picker-panel .ant-picker-cell-selected .ant-picker-cell-inner,
.fingertip-designer-date-picker-panel .ant-picker-cell-range-start .ant-picker-cell-inner,
.fingertip-designer-date-picker-panel .ant-picker-cell-range-end .ant-picker-cell-inner {
background: var(--theme-primary);
color: #fff;
font-weight: 700;
}
.fingertip-designer-date-picker-panel .ant-picker-footer {
border-top-color: var(--theme-border);
}
.fingertip-designer-date-time-panel .ant-picker-time-panel,
.fingertip-designer-time-panel .ant-picker-time-panel {
min-width: 150px;
}
.fingertip-designer-date-time-panel .ant-picker-time-panel-column,
.fingertip-designer-time-panel .ant-picker-time-panel-column {
width: 76px;
padding: 8px 6px;
}
.fingertip-designer-date-time-panel .ant-picker-time-panel-cell-inner,
.fingertip-designer-time-panel .ant-picker-time-panel-cell-inner {
height: 34px !important;
line-height: 34px !important;
border-radius: 8px !important;
text-align: center;
}
.fingertip-designer-date-time-panel .ant-picker-time-panel-cell-selected .ant-picker-time-panel-cell-inner,
.fingertip-designer-time-panel .ant-picker-time-panel-cell-selected .ant-picker-time-panel-cell-inner {
background: var(--theme-primary-soft);
color: var(--theme-primary);
font-weight: 700;
}
.ant-picker {
border-radius: 8px;
}
.ant-picker-focused,
.ant-picker:hover {
border-color: var(--theme-primary);
box-shadow: var(--theme-focus-shadow);
}
.fingertip-designer-system-message-wrap .ant-modal {
max-width: calc(100vw - 32px);
}
.fingertip-designer-system-message-dialog .ant-modal-content {
overflow: hidden;
padding: 0;
border-radius: 8px;
background: var(--theme-card-bg);
box-shadow: 0 24px 70px rgba(38, 31, 36, 0.32);
}
.fingertip-designer-system-message-dialog .ant-modal-confirm-body-wrapper {
margin: 0;
}
.fingertip-designer-system-message-dialog .ant-modal-confirm-body {
display: block;
}
.fingertip-designer-system-message-dialog .ant-modal-confirm-content {
max-width: none;
margin: 0 !important;
color: inherit;
}
.fingertip-designer-system-message-dialog .ant-modal-confirm-btns {
display: flex;
justify-content: stretch;
margin: 0;
padding: 0 30px 30px;
background: var(--theme-card-bg);
}
.fingertip-designer-system-message-dialog .popup-message-ok-button {
width: 100%;
height: 44px;
border: 0;
border-radius: 8px;
color: #ffffff;
font-weight: 700;
background: var(--theme-gradient);
box-shadow: var(--theme-button-shadow);
}
.fingertip-designer-system-message-dialog .popup-message-ok-button:hover,
.fingertip-designer-system-message-dialog .popup-message-ok-button:focus {
color: #ffffff;
background: linear-gradient(135deg, var(--theme-accent) 0%, var(--theme-secondary) 100%);
}
.popup-message-ok-text {
display: inline-flex;
gap: 8px;
align-items: center;
}
@media (max-width: 640px) {
.fingertip-designer-system-message-dialog .ant-modal-content {
border-radius: 8px;
}
.fingertip-designer-system-message-dialog .popup-message-ok-button {
width: 100%;
}
}
</style>
@@ -0,0 +1,63 @@
/**
* Purpose: WEB_API_AUTH_FREE_PATHS supports auth-free-paths.ts by holding or executing the web api auth free paths 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.
*/
export const WEB_API_AUTH_FREE_PATHS = [
'/user/login',
'/user/register',
'/user/check/',
'/user/refresh-token',
'/user/send-verification-code',
'/user/phone-login',
'/user/wechat-mini/',
'/user/reset-password-by-phone',
'/legal-agreement/current',
'/api/legal-agreement/current',
'/product/get/',
'/product/list/',
'/comment/list/product/',
'/nail-artist/',
'/shop/get/',
'/shop/trust-profile/',
'/shop/list',
'/shop/list/public',
'/shop/list/simple',
'/tag/list/all',
'/tag/list/filter-options',
'/file/get-signed-url/',
] as const
/**
* Purpose: normalizePathname supports auth-free-paths.ts by holding or executing the normalize pathname 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 normalizePathname = (url?: string) => {
const raw = String(url || '')
const withoutHash = raw.split('#')[0] || ''
const withoutQuery = withoutHash.split('?')[0] || ''
try {
return new URL(withoutQuery, 'http://fingertipdesigner.local').pathname
} catch {
return withoutQuery.startsWith('/') ? withoutQuery : `/${withoutQuery}`
}
}
/**
* Purpose: matchesAuthFreePath supports auth-free-paths.ts by holding or executing the matches auth free path 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 matchesAuthFreePath = (url: string | undefined, path: string) => {
const pathname = normalizePathname(url)
if (path.endsWith('/')) {
return pathname === path.slice(0, -1) || pathname.startsWith(path)
}
return pathname === path
}
/**
* Purpose: isApiAuthFreePath supports auth-free-paths.ts by holding or executing the is api auth free path 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.
*/
export const isApiAuthFreePath = (url?: string) => {
return WEB_API_AUTH_FREE_PATHS.some(path => matchesAuthFreePath(url, path))
}
+242
View File
@@ -0,0 +1,242 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { IdType } from '@/utils/id'
/**
* Purpose: SendVerificationCodeRequest supports auth.ts by holding or executing the send verification code request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface SendVerificationCodeRequest {
phone: string
sceneCode?: string
}
/**
* Purpose: LoginRequest supports auth.ts by holding or executing the login request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface LoginRequest {
account: string
password: string
rememberMe?: boolean
shopId?: string | number
agreementAccepted?: boolean
agreementVersions?: Record<string, string>
clientType?: string
}
/**
* Purpose: PhoneLoginRequest supports auth.ts by holding or executing the phone login request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface PhoneLoginRequest {
phone: string
verificationCode: string
shopId?: string | number
agreementAccepted?: boolean
agreementVersions?: Record<string, string>
clientType?: string
}
/**
* Purpose: RegisterRequest supports auth.ts by holding or executing the register request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface RegisterRequest {
account: string
password: string
nickname: string
shopId?: string | number
inviteCode?: string
phone?: string
verificationCode?: string
agreementAccepted?: boolean
agreementVersions?: Record<string, string>
clientType?: string
}
/**
* Purpose: LegalAgreement supports auth.ts by holding or executing the legal agreement page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface LegalAgreement {
id: IdType
agreementType: 'USER_TERMS' | 'PRIVACY_POLICY'
agreementTypeName: string
title: string
version: string
content: string
status: number
statusText?: string
effectiveTime?: string
}
/**
* Purpose: LoginResponse supports auth.ts by holding or executing the login response page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface LoginResponse {
accessToken: string
refreshToken: string
userInfo: UserInfo
}
/**
* Purpose: UserInfo supports auth.ts by holding or executing the user info page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface UserInfo {
id: IdType
account: string
nickname: string
avatar?: string
signature?: string
type?: number
shopId?: IdType
shopName?: string
shopAuthorizationExpireTime?: string
shopAuthorizationExpired?: boolean
shopIds?: IdType[]
shopNames?: string[]
createTime: string
updateTime?: string
}
/**
* Purpose: RefreshTokenRequest supports auth.ts by holding or executing the refresh token request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface RefreshTokenRequest {
refreshToken: string
}
/**
* Purpose: RefreshTokenResponse supports auth.ts by holding or executing the refresh token response page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface RefreshTokenResponse {
accessToken: string
refreshToken: string
}
/**
* Purpose: ResetPasswordRequest supports auth.ts by holding or executing the reset password request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ResetPasswordRequest {
phone: string
verificationCode: string
newPassword: string
}
/**
* Purpose: SwitchShopRequest supports auth.ts by holding or executing the switch shop request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface SwitchShopRequest {
shopId?: string | number
}
/**
* authApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const authApi = {
/**
* `sendVerificationCode` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param data: SendVerificationCodeRequest caller-supplied value for `data: SendVerificationCodeRequest`
*/
sendVerificationCode: (data: SendVerificationCodeRequest) => {
return api.post('/user/send-verification-code', data)
},
/**
* `login` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param data: LoginRequest caller-supplied value for `data: LoginRequest`
*/
login: (data: LoginRequest) => {
return api.post<LoginResponse>('/user/login', data)
},
/**
* `phoneLogin` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param data: PhoneLoginRequest caller-supplied value for `data: PhoneLoginRequest`
*/
phoneLogin: (data: PhoneLoginRequest) => {
return api.post<LoginResponse>('/user/phone-login', data)
},
/**
* `register` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param data: RegisterRequest caller-supplied value for `data: RegisterRequest`
*/
register: (data: RegisterRequest) => {
return api.post('/user/register', data)
},
/**
* `refreshToken` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param data: RefreshTokenRequest caller-supplied value for `data: RefreshTokenRequest`
*/
refreshToken: (data: RefreshTokenRequest) => {
return api.post<RefreshTokenResponse>('/user/refresh-token', data)
},
/**
* `logout` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
*/
logout: () => {
return api.post('/user/logout')
},
/**
* `switchShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param data: SwitchShopRequest caller-supplied value for `data: SwitchShopRequest`
*/
switchShop: (data: SwitchShopRequest) => {
return api.post<LoginResponse>('/user/switch-shop', data)
},
/**
* `getUserInfo` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
*/
getUserInfo: () => {
return api.get<UserInfo>('/user/info')
},
/**
* `resetPasswordByPhone` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param data: ResetPasswordRequest caller-supplied value for `data: ResetPasswordRequest`
*/
resetPasswordByPhone: (data: ResetPasswordRequest) => {
return api.post('/user/reset-password-by-phone', data)
}
}
/**
* Purpose: legalAgreementApi supports auth.ts by holding or executing the legal agreement 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.
*/
export const legalAgreementApi = {
listCurrent: () => {
return api.get<LegalAgreement[]>('/legal-agreement/current')
},
getCurrent: (type: 'USER_TERMS' | 'PRIVACY_POLICY') => {
return api.get<LegalAgreement>(`/legal-agreement/current/${type}`)
},
getMyConsent: () => {
return api.get<{ consentVersions: Record<string, string> }>('/user/agreement-consent/me')
}
}
+79
View File
@@ -0,0 +1,79 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { IdType } from '@/utils/id'
/**
* Purpose: CartItem supports cart.ts by holding or executing the cart item page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
interface CartItem {
productId: IdType
quantity: number
}
/**
* cartApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const cartApi = {
// 添加作品到购物车
/**
* `addToCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param item: CartItem caller-supplied value for `item: CartItem`
*/
addToCart: (item: CartItem) => {
return api.post('/cart/add', item)
},
// 从购物车移除作品
/**
* `removeFromCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param productId: IdType caller-supplied value for `productId: IdType`
*/
removeFromCart: (productId: IdType) => {
return api.delete(`/cart/remove/${productId}`)
},
// 批量从购物车移除作品
/**
* `batchRemoveFromCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param cartItemIds: IdType[] caller-supplied value for `cartItemIds: IdType[]`
*/
batchRemoveFromCart: (cartItemIds: IdType[]) => {
return api.post('/cart/batch-remove', cartItemIds)
},
// 更新购物车作品数量
/**
* `updateCartQuantity` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param item: CartItem caller-supplied value for `item: CartItem`
*/
updateCartQuantity: (item: CartItem) => {
return api.put('/cart/update', item)
},
// 获取购物车列表
/**
* `getCartList` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
*/
getCartList: () => {
return api.get('/cart/list')
},
// 清空购物车
/**
* `clearCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
*/
clearCart: () => {
return api.delete('/cart/clear')
}
}
+114
View File
@@ -0,0 +1,114 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { AxiosProgressEvent } from 'axios'
import type { ChunkUploadInitRequest, ChunkUploadSessionVO } from '@/api/file'
import type { IdType } from '@/utils/id'
/**
* Purpose: CommentVO supports comment.ts by holding or executing the comment vo page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface CommentVO {
id: IdType
userId: IdType
userNickname?: string
shopId?: IdType
shopName?: string
productId?: IdType
productTitle?: string
commentContent: string
parentCommentId?: IdType
parentCommentContent?: string
likeCount?: number
ratingScore?: number
imageFileIds?: IdType[]
imageUrls?: string[]
createTime?: string
updateTime?: string
replies?: CommentVO[]
}
export interface CommentCreateRequest {
productId: IdType
shopId?: IdType | null
parentCommentId?: IdType | null
commentContent: string
ratingScore?: number
imageFileIds?: IdType[]
}
export interface CommentImageFileVO {
id: IdType
fileName?: string
fileUrl?: string
createTime?: string
}
/**
* commentApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const commentApi = {
/**
* `listByProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param productId: IdType caller-supplied value for `productId: IdType`
*/
listByProduct: (productId: IdType) => {
return api.get<CommentVO[]>(`/comment/list/product/${productId}`) as unknown as Promise<CommentVO[]>
},
/**
* `create` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param data: { productId: IdType; shopId?: IdType | null; parentCommentId?: IdType | null; commentContent: string } caller-supplied value for `data: { productId: IdType; shopId?: IdType | null; parentCommentId?: IdType | null; commentContent: string }`
*/
create: (data: CommentCreateRequest) => {
return api.post<IdType>('/comment/create', data) as unknown as Promise<IdType>
},
uploadImage: (file: File) => {
const formData = new FormData()
formData.append('file', file)
return api.post<CommentImageFileVO>('/comment/upload-image', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}) as unknown as Promise<CommentImageFileVO>
},
initImageChunkUpload: (data: ChunkUploadInitRequest) => {
return api.post<ChunkUploadSessionVO>('/comment/upload-image/init', data) as unknown as Promise<ChunkUploadSessionVO>
},
uploadImageChunk: (
data: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob },
config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void }
) => {
const formData = new FormData()
formData.append('uploadId', data.uploadId)
formData.append('chunkIndex', String(data.chunkIndex))
formData.append('totalChunks', String(data.totalChunks))
formData.append('chunk', data.chunk)
return api.post<boolean>('/comment/upload-image/chunk', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
signal: config?.signal,
onUploadProgress: config?.onUploadProgress
})
},
completeImageChunkUpload: (uploadId: string) => {
return api.post<CommentImageFileVO>('/comment/upload-image/complete', { uploadId }) as unknown as Promise<CommentImageFileVO>
},
cancelImageChunkUpload: (uploadId: string) => {
return api.delete<boolean>(`/comment/upload-image/${uploadId}`)
},
/**
* `delete` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param id: IdType caller-supplied value for `id: IdType`
*/
delete: (id: IdType) => {
return api.delete<boolean>(`/comment/delete/${id}`) as unknown as Promise<boolean>
}
}
+221
View File
@@ -0,0 +1,221 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import request from './index'
import type { IdType } from '@/utils/id'
/**
* Purpose: Coupon supports coupon.ts by holding or executing the coupon page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface Coupon {
id: IdType
couponCode: string
couponName: string
couponType: number
couponTypeName: string
discountValue?: number
minAmount?: number
reduceAmount?: number
totalCount: number
usedCount: number
remainingCount: number
startTime: string
endTime: string
status: number
statusName: string
shopId?: IdType
couponScene?: string
requiredVipLevel?: string
autoMatch?: number
availableTags: Tag[]
unavailableTags: Tag[]
}
/**
* Purpose: Tag supports coupon.ts by holding or executing the tag page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface Tag {
id: IdType
tagName?: string
}
/**
* Purpose: UserCoupon supports coupon.ts by holding or executing the user coupon page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface UserCoupon {
id: IdType
couponId: IdType
couponName: string
couponType: number
couponTypeName: string
discountValue: string
minAmount: string
reduceAmount: string
startTime: string
endTime: string
status: number
statusName: string
obtainTime: string
useTime: string
sourceType?: string
requiredVipLevel?: string
autoMatched?: boolean
}
/**
* Purpose: CreateCouponRequest supports coupon.ts by holding or executing the create coupon request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface CreateCouponRequest {
couponCode: string
couponName: string
couponType: number
discountValue?: number
minAmount?: number
reduceAmount?: number
totalCount: number
startTime: string
endTime: string
couponScene?: string
requiredVipLevel?: string
autoMatch?: number
availableTagIds: IdType[]
unavailableTagIds: IdType[]
}
/**
* Purpose: CouponListResponse supports coupon.ts by holding or executing the coupon list response page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface CouponListResponse {
list: Coupon[]
total: number
page: number
size: number
}
/**
* couponApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const couponApi = {
// 创建优惠券
/**
* `createCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param data: CreateCouponRequest caller-supplied value for `data: CreateCouponRequest`
*/
createCoupon: (data: CreateCouponRequest) => {
return request({
url: '/coupon/create',
method: 'post',
data
})
},
// 更新优惠券
/**
* `updateCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param id: IdType caller-supplied value for `id: IdType`
* @param data: CreateCouponRequest caller-supplied value for `data: CreateCouponRequest`
*/
updateCoupon: (id: IdType, data: CreateCouponRequest) => {
return request({
url: `/coupon/update/${id}`,
method: 'put',
data
})
},
// 删除优惠券
/**
* `deleteCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param id: IdType caller-supplied value for `id: IdType`
*/
deleteCoupon: (id: IdType) => {
return request({
url: `/coupon/delete/${id}`,
method: 'delete'
})
},
// 获取优惠券详情
/**
* `getCouponById` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param id: IdType caller-supplied value for `id: IdType`
*/
getCouponById: (id: IdType) => {
return request({
url: `/coupon/detail/${id}`,
method: 'get'
})
},
// 获取优惠券列表
/**
* `listCoupons` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param params: { page: number; size: number; shopId?: IdType } caller-supplied value for `params: { page: number; size: number; shopId?: IdType }`
*/
listCoupons: (params: { page: number; size: number; shopId?: IdType }) => {
return request({
url: '/coupon/list',
method: 'get',
params
})
},
// 为用户分配优惠券
/**
* `assignCouponToUser` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param userId: IdType caller-supplied value for `userId: IdType`
* @param couponId: IdType caller-supplied value for `couponId: IdType`
*/
assignCouponToUser: (userId: IdType, couponId: IdType) => {
return request({
url: '/coupon/assign',
method: 'post',
params: { userId, couponId }
})
},
// 获取用户优惠券列表
listUserCoupons: async (status?: number): Promise<UserCoupon[]> => {
return await request({
url: '/coupon/user/list',
method: 'get',
params: { status }
}) as UserCoupon[]
},
// 使用优惠券
/**
* `useCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param userCouponId: IdType caller-supplied value for `userCouponId: IdType`
*/
useCoupon: (userCouponId: IdType) => {
return request({
url: '/coupon/use',
method: 'post',
params: { userCouponId }
})
},
// 获取作品可用的优惠券
getAvailableCoupons: async (productTags: string, productPrice: number, shopId?: IdType): Promise<UserCoupon[]> => {
return await request({
url: '/coupon/available',
method: 'get',
params: { productTags, productPrice, shopId }
}) as UserCoupon[]
}
}
+49
View File
@@ -0,0 +1,49 @@
import { describe, expect, it } from 'vitest'
import type { AxiosError } from 'axios'
import {
getApiResponseMessage,
isPermissionErrorMessage,
isSystemFailureResponse,
isTokenExpiredMessage,
normalizeApiErrorMessage,
shouldShowDedupedError,
updateSystemFailureWindow
} from './error'
describe('api error helpers', () => {
it('extracts messages and classifies error types', () => {
const error = { message: 'fallback', response: { data: { message: '服务异常' } } } as AxiosError
expect(getApiResponseMessage(error, '请求失败')).toBe('服务异常')
expect(isPermissionErrorMessage('权限不足')).toBe(true)
expect(isPermissionErrorMessage('permission denied')).toBe(true)
expect(isTokenExpiredMessage('登录已过期,请重新登录')).toBe(true)
})
it('dedupes prompts by message and time', () => {
expect(shouldShowDedupedError({ lastErrorTime: 10, lastErrorMessage: 'a' }, 'a', 40, 50)).toBe(false)
expect(shouldShowDedupedError({ lastErrorTime: 10, lastErrorMessage: 'a' }, 'b', 100, 50)).toBe(true)
})
it('normalizes garbled booking unavailable messages', () => {
expect(normalizeApiErrorMessage('涓嶅彲棰勭害')).toBe('不可预约,请调整美甲师或预约时间后重试')
expect(normalizeApiErrorMessage('创建订单失败:涓嶅彲棰勭害')).toBe('不可预约,请调整美甲师或预约时间后重试')
})
it('classifies system failure responses', () => {
expect(isSystemFailureResponse({ response: { status: 500 } } as AxiosError)).toBe(true)
expect(isSystemFailureResponse({ response: { status: 503 } } as AxiosError)).toBe(true)
expect(isSystemFailureResponse({ response: { status: 400 } } as AxiosError)).toBe(false)
expect(isSystemFailureResponse({ response: undefined } as AxiosError)).toBe(true)
})
it('tracks failure windows with pruning and threshold', () => {
expect(updateSystemFailureWindow([1_000, 12_000], 40_000, 30_000, 3)).toEqual({
failureTimes: [12_000, 40_000],
triggered: false
})
expect(updateSystemFailureWindow([1_000, 12_000, 20_000], 30_000, 30_000, 3)).toEqual({
failureTimes: [1_000, 12_000, 20_000, 30_000],
triggered: true
})
})
})
+90
View File
@@ -0,0 +1,90 @@
import type { AxiosError } from 'axios'
export interface ApiResponseBody {
message?: string
}
export interface ErrorPromptState {
lastErrorTime: number
lastErrorMessage: string
}
export interface SystemFailureWindowState {
failureTimes: number[]
triggered: boolean
}
const BOOKING_UNAVAILABLE_MESSAGE = '不可预约,请调整美甲师或预约时间后重试'
const GARbled_BOOKING_UNAVAILABLE_MESSAGES = [
'涓嶅彲棰勭害'
]
export const normalizeApiErrorMessage = (messageText: string): string => {
const trimmedMessage = String(messageText || '').trim()
if (!trimmedMessage) return trimmedMessage
if (GARbled_BOOKING_UNAVAILABLE_MESSAGES.some(message => trimmedMessage.includes(message))) {
return BOOKING_UNAVAILABLE_MESSAGE
}
return trimmedMessage
}
export const getApiResponseMessage = (error: AxiosError, fallbackMessage: string): string => {
const responseData = error.response?.data as ApiResponseBody | undefined
return normalizeApiErrorMessage(responseData?.message || error.message || fallbackMessage)
}
export const isPermissionErrorMessage = (messageText: string): boolean =>
messageText.includes('权限') || messageText.includes('permission')
export const isTokenExpiredMessage = (messageText: string): boolean => (
messageText.includes('Token')
|| messageText.includes('token')
|| messageText.includes('登录态')
|| messageText.includes('登录已过期')
|| messageText.includes('未登录')
|| messageText.includes('认证')
|| messageText.includes('重新登录')
)
export const isTokenExpiredResponse = (error: AxiosError, requestToken: string | null): boolean =>
Boolean(requestToken && isTokenExpiredMessage(getApiResponseMessage(error, '请求失败')))
export const isSystemFailureResponse = (error: AxiosError): boolean => {
const status = error.response?.status
if (typeof status === 'number') {
return status >= 500
}
return !error.response
}
export const shouldShowDedupedError = (
state: ErrorPromptState,
messageText: string,
now: number,
debounceTime: number
): boolean => now - state.lastErrorTime > debounceTime || messageText !== state.lastErrorMessage
export const updateErrorPromptState = (
messageText: string,
now: number
): ErrorPromptState => ({
lastErrorTime: now,
lastErrorMessage: messageText
})
export const updateSystemFailureWindow = (
failureTimes: number[],
now: number,
windowMs: number,
threshold: number
): SystemFailureWindowState => {
const nextFailureTimes = failureTimes
.filter(failureTime => now - failureTime <= windowMs)
.concat(now)
return {
failureTimes: nextFailureTimes,
triggered: nextFailureTimes.length >= threshold
}
}
+159
View File
@@ -0,0 +1,159 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import type { AxiosProgressEvent } from 'axios'
import api from './index'
import type { IdType } from '@/utils/id'
/**
* Purpose: ChunkUploadInitRequest supports file.ts by holding or executing the chunk upload init request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ChunkUploadInitRequest {
fileName: string
fileSize: number
contentType: string
fileFingerprint: string
scene: string
}
/**
* Purpose: ChunkUploadSessionVO supports file.ts by holding or executing the chunk upload session vo page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ChunkUploadSessionVO {
uploadId: string
chunkSize: number
totalChunks: number
uploadedChunks: number[]
}
/**
* fileApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const fileApi = {
/**
* `uploadAvatar` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param file: File caller-supplied value for `file: File`
*/
uploadAvatar: (file: File) => {
const formData = new FormData()
formData.append('file', file)
return api.post<string>('/user/upload-avatar', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
},
uploadProfileImage: (file: File) => {
const formData = new FormData()
formData.append('file', file)
return api.post<string>('/user/upload-profile-image', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}) as unknown as Promise<string>
},
/**
* `initAvatarChunkUpload` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param data: ChunkUploadInitRequest caller-supplied value for `data: ChunkUploadInitRequest`
*/
initAvatarChunkUpload: (data: ChunkUploadInitRequest) => {
return api.post<ChunkUploadSessionVO>('/user/upload-avatar/init', data) as unknown as Promise<ChunkUploadSessionVO>
},
uploadAvatarChunk: (
/**
* Purpose: data supports file.ts by holding or executing the data page or API role.
* Usage: import, call, read, or update this page-data from the owning page/module while preserving the surrounding loading and permission flow.
*/
data: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob },
config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void }
) => {
const formData = new FormData()
formData.append('uploadId', data.uploadId)
formData.append('chunkIndex', String(data.chunkIndex))
formData.append('totalChunks', String(data.totalChunks))
formData.append('chunk', data.chunk)
return api.post<boolean>('/user/upload-avatar/chunk', formData, {
/**
* Purpose: headers supports file.ts by holding or executing the headers page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
headers: {
'Content-Type': 'multipart/form-data'
},
/**
* Purpose: signal supports file.ts by holding or executing the signal page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
signal: config?.signal,
/**
* Purpose: onUploadProgress supports file.ts by holding or executing the on upload progress page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
onUploadProgress: config?.onUploadProgress
})
},
/**
* `completeAvatarChunkUpload` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param uploadId: string caller-supplied value for `uploadId: string`
*/
completeAvatarChunkUpload: (uploadId: string) => {
return api.post<string>('/user/upload-avatar/complete', { uploadId }) as unknown as Promise<string>
},
/**
* `cancelAvatarChunkUpload` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param uploadId: string caller-supplied value for `uploadId: string`
*/
cancelAvatarChunkUpload: (uploadId: string) => {
return api.delete<boolean>(`/user/upload-avatar/${uploadId}`)
},
initProfileImageChunkUpload: (data: ChunkUploadInitRequest) => {
return api.post<ChunkUploadSessionVO>('/user/upload-profile-image/init', data) as unknown as Promise<ChunkUploadSessionVO>
},
uploadProfileImageChunk: (
data: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob },
config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void }
) => {
const formData = new FormData()
formData.append('uploadId', data.uploadId)
formData.append('chunkIndex', String(data.chunkIndex))
formData.append('totalChunks', String(data.totalChunks))
formData.append('chunk', data.chunk)
return api.post<boolean>('/user/upload-profile-image/chunk', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
signal: config?.signal,
onUploadProgress: config?.onUploadProgress
})
},
completeProfileImageChunkUpload: (uploadId: string) => {
return api.post<string>('/user/upload-profile-image/complete', { uploadId }) as unknown as Promise<string>
},
cancelProfileImageChunkUpload: (uploadId: string) => {
return api.delete<boolean>(`/user/upload-profile-image/${uploadId}`)
},
/**
* `getSignedUrl` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param fileId: IdType caller-supplied value for `fileId: IdType`
* @param expiryTimeInMinutes?: number caller-supplied value for `expiryTimeInMinutes?: number`
*/
getSignedUrl: (fileId: IdType, expiryTimeInMinutes?: number) => {
return api.get<string>(`/file/get-signed-url/${fileId}`, {
/**
* Purpose: params supports file.ts by holding or executing the params page or API role.
* Usage: import, call, read, or update this page-data-field from the owning page/module while preserving the surrounding loading and permission flow.
*/
params: { expiryTimeInMinutes }
})
}
}
+353
View File
@@ -0,0 +1,353 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import axios, { AxiosError } from 'axios'
import { authApi } from './auth'
import { wishlistApi } from './wishlist'
import { message, Modal } from 'ant-design-vue'
import { API_BASE_URL } from '../config/api'
import type { IdType } from '@/utils/id'
import { attachRequestSignature } from '@/utils/request-signature'
import { isApiAuthFreePath } from './auth-free-paths'
import {
getApiResponseMessage,
isPermissionErrorMessage,
isSystemFailureResponse,
isTokenExpiredResponse,
normalizeApiErrorMessage,
shouldShowDedupedError,
updateSystemFailureWindow,
updateErrorPromptState,
type ErrorPromptState
} from './error'
// 防重复提示标志
let lastErrorTime = 0
/**
* Purpose: lastErrorMessage supports index.ts by holding or executing the last error message page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let lastErrorMessage = ''
/**
* Purpose: ERROR_DEBOUNCE_TIME supports index.ts by holding or executing the error debounce time 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 ERROR_DEBOUNCE_TIME = 1000 // 1秒内不重复显示相同错误
const SYSTEM_FAILURE_WINDOW_MS = 30 * 1000
const SYSTEM_FAILURE_THRESHOLD = 3
const SYSTEM_FAILURE_MODAL_COOLDOWN_MS = 60 * 1000
const SYSTEM_FAILURE_MODAL_TITLE = '系统暂不可用'
const SYSTEM_FAILURE_MODAL_CONTENT = '当前服务暂时无法响应,请稍后重试。如问题持续存在,请联系管理员。'
const SYSTEM_FAILURE_MODAL_OK_TEXT = '我知道了'
let systemFailureTimes: number[] = []
let systemFailureModalVisible = false
let lastSystemFailureModalTime: number | null = null
/**
* Purpose: api supports index.ts by holding or executing the 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 api = axios.create({
baseURL: API_BASE_URL,
timeout: 60000,
headers: {
'Content-Type': 'application/json'
}
})
/**
* Purpose: isRefreshing supports index.ts by holding or executing the is refreshing page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let isRefreshing = false
let failedQueue: Array<{
resolve: (value?: any) => void
reject: (reason?: any) => void
}> = []
/**
* Purpose: getStoredAccessToken supports index.ts by holding or executing the get stored access token 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 getStoredAccessToken = () => {
return localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
}
/**
* Purpose: getStoredRefreshToken supports index.ts by holding or executing the get stored refresh token 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 getStoredRefreshToken = () => {
return localStorage.getItem('refreshToken') || sessionStorage.getItem('refreshToken')
}
/**
* Purpose: getRequestToken supports index.ts by holding or executing the get request token 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 getRequestToken = (request: any) => {
if (request?._authToken) {
return request._authToken as string
}
const authHeader = request?.headers?.Authorization || request?.headers?.authorization
if (typeof authHeader !== 'string') {
return null
}
return authHeader.startsWith('Bearer ') ? authHeader.slice('Bearer '.length) : null
}
/**
* Purpose: isCurrentStoredToken supports index.ts by holding or executing the is current stored token 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 isCurrentStoredToken = (token: string | null) => {
return Boolean(token && token === getStoredAccessToken())
}
/**
* Purpose: processQueue supports index.ts by holding or executing the process queue 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 processQueue = (error: unknown, token: string | null = null) => {
failedQueue.forEach(prom => {
if (error) {
prom.reject(error)
} else {
prom.resolve(token)
}
})
failedQueue = []
}
// 防抖处理错误提示
const showError = (msg: string) => {
const now = Date.now()
const state: ErrorPromptState = { lastErrorTime, lastErrorMessage }
if (!shouldShowDedupedError(state, msg, now, ERROR_DEBOUNCE_TIME)) {
return
}
const nextState = updateErrorPromptState(msg, now)
lastErrorTime = nextState.lastErrorTime
lastErrorMessage = nextState.lastErrorMessage
message.error(msg)
}
const resetSystemFailureWindow = () => {
systemFailureTimes = []
}
const showSystemFailureModal = (now: number) => {
if (
systemFailureModalVisible
|| (
lastSystemFailureModalTime !== null
&& now - lastSystemFailureModalTime < SYSTEM_FAILURE_MODAL_COOLDOWN_MS
)
) {
return
}
systemFailureModalVisible = true
lastSystemFailureModalTime = now
Modal.error({
title: SYSTEM_FAILURE_MODAL_TITLE,
content: SYSTEM_FAILURE_MODAL_CONTENT,
okText: SYSTEM_FAILURE_MODAL_OK_TEXT,
onOk: () => {
systemFailureModalVisible = false
},
afterClose: () => {
systemFailureModalVisible = false
}
})
}
const recordSystemFailure = (error: AxiosError): boolean => {
if (!isSystemFailureResponse(error)) {
return false
}
const now = Date.now()
const nextState = updateSystemFailureWindow(
systemFailureTimes,
now,
SYSTEM_FAILURE_WINDOW_MS,
SYSTEM_FAILURE_THRESHOLD
)
systemFailureTimes = nextState.failureTimes
if (nextState.triggered) {
showSystemFailureModal(now)
return true
}
return false
}
/**
* Purpose: isAuthFreePath supports index.ts by holding or executing the is auth free path 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 isAuthFreePath = (url?: string) => {
return isApiAuthFreePath(url)
}
/**
* Purpose: handleTokenExpired supports index.ts by holding or executing the handle token expired 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 handleTokenExpired = (failedToken: string | null) => {
if (!isCurrentStoredToken(failedToken)) {
return
}
// 清理token和用户信息
localStorage.removeItem('accessToken')
localStorage.removeItem('refreshToken')
localStorage.removeItem('userInfo')
sessionStorage.removeItem('accessToken')
sessionStorage.removeItem('refreshToken')
// 显示错误提示
if (Date.now() - lastErrorTime > ERROR_DEBOUNCE_TIME || lastErrorMessage !== '登录已过期,请重新登录') {
showError('登录已过期,请重新登录')
}
// 执行跳转,确保无论如何都会跳转
setTimeout(() => {
window.location.href = '/'
}, 500) // 延迟执行,确保错误提示先显示
}
api.interceptors.request.use(
async config => {
const token = getStoredAccessToken()
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
;(config as any)._authToken = token || null
return attachRequestSignature(config, token, {
authFree: isAuthFreePath(config.url)
})
},
error => {
return Promise.reject(error)
}
)
api.interceptors.response.use(
response => {
resetSystemFailureWindow()
const res = response.data
if (res.code !== 200) {
const errorMsg = normalizeApiErrorMessage(res.message || '请求失败')
if (!isPermissionErrorMessage(errorMsg)) {
showError(errorMsg)
}
return Promise.reject(new Error(errorMsg))
}
return res.data as any
},
async (error: AxiosError) => {
const originalRequest = error.config as any
const isWhitelistedPath = (url: string) => {
return isApiAuthFreePath(url)
}
if (error.response?.status === 401) {
const requestToken = getRequestToken(originalRequest)
const isRealTokenExpired = isTokenExpiredResponse(error, requestToken)
if (!isRealTokenExpired) {
showError(getApiResponseMessage(error, '请求失败'))
return Promise.reject(error)
}
if (!isCurrentStoredToken(requestToken)) {
return Promise.reject(error)
}
if (!originalRequest._retry && !isWhitelistedPath(originalRequest.url)) {
if (isRefreshing) {
return new Promise((resolve, reject) => {
failedQueue.push({ resolve, reject })
}).then(token => {
if (token) {
originalRequest.headers.Authorization = `Bearer ${token}`
originalRequest._authToken = token
}
return api(originalRequest)
}).catch(err => {
return Promise.reject(err)
})
}
originalRequest._retry = true
isRefreshing = true
try {
const refreshToken = getStoredRefreshToken()
if (!refreshToken) {
throw new Error('No refresh token available')
}
const response = await authApi.refreshToken({ refreshToken })
const newToken = (response as any).accessToken
const newRefreshToken = (response as any).refreshToken
localStorage.setItem('accessToken', newToken)
localStorage.setItem('refreshToken', newRefreshToken)
sessionStorage.setItem('accessToken', newToken)
sessionStorage.setItem('refreshToken', newRefreshToken)
processQueue(null, newToken)
originalRequest.headers.Authorization = `Bearer ${newToken}`
originalRequest._authToken = newToken
return api(originalRequest)
} catch (refreshError) {
processQueue(refreshError, null)
handleTokenExpired(requestToken)
return Promise.reject(refreshError)
} finally {
isRefreshing = false
}
} else {
handleTokenExpired(requestToken)
return Promise.reject(error)
}
} else if (error.response?.status !== 403) { // 403权限不足不提示
const errorMsg = getApiResponseMessage(error, '请求失败')
if (!recordSystemFailure(error)) {
showError(errorMsg)
}
}
return Promise.reject(error)
}
)
/**
* fileApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const fileApi = {
/**
* `getSignedUrl` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param fileId: IdType caller-supplied value for `fileId: IdType`
* @param expiryTimeInMinutes?: number caller-supplied value for `expiryTimeInMinutes?: number`
*/
getSignedUrl: (fileId: IdType, expiryTimeInMinutes?: number) => {
return api.get<string>(`/file/get-signed-url/${fileId}`, {
params: { expiryTimeInMinutes }
})
}
}
export { wishlistApi }
export default api
@@ -0,0 +1,92 @@
import api from './index'
import type { IdType } from '@/utils/id'
export interface NailArtistAvailabilityVO {
startTime: string
endTime: string
dateText: string
timeText: string
available: boolean
}
export interface NailArtistWorkVO {
id: IdType
title?: string
description?: string
price?: number | string
coverImageUrl?: string
imageUrls?: string[]
tags?: string[]
likeCount?: number
collectCount?: number
}
export interface NailArtistReviewVO {
id: IdType
artistId: IdType
customerId?: IdType
customerName?: string
customerAvatar?: string
productId?: IdType
productTitle?: string
rating?: number | string
content?: string
imageFileIds?: IdType[]
imageUrls?: string[]
submittedAt?: string
}
export interface NailArtistListItemVO {
id?: IdType
userId?: IdType
identity?: string
experience?: number
skills?: string
rating?: number | string
status?: number
participateProduction?: number
workStartTime?: string
workEndTime?: string
userType?: number
userTypeName?: string
portfolio?: string
nickname?: string
shopId?: IdType
shopName?: string
signature?: string
}
export interface NailArtistProfileVO {
artistId: IdType
artistName?: string
avatar?: string
identity?: string
signature?: string
experience?: number
status?: number
shopId?: IdType
shopName?: string
rating?: number | string
serviceCount?: number | string
workStartTime?: string
workEndTime?: string
styleTags?: string[]
works?: NailArtistWorkVO[]
reviews?: NailArtistReviewVO[]
availability?: NailArtistAvailabilityVO[]
}
export const nailArtistApi = {
getPublicProfile: async (artistId: IdType): Promise<NailArtistProfileVO> => {
return await api.get<NailArtistProfileVO>(`/nail-artist/profile/${artistId}`) as unknown as NailArtistProfileVO
},
getAvailability: async (artistId: IdType): Promise<NailArtistAvailabilityVO[]> => {
return await api.get<NailArtistAvailabilityVO[]>(`/nail-artist/${artistId}/availability`) as unknown as NailArtistAvailabilityVO[]
},
listReviews: async (artistId: IdType): Promise<NailArtistReviewVO[]> => {
return await api.get<NailArtistReviewVO[]>(`/nail-artist/${artistId}/reviews`) as unknown as NailArtistReviewVO[]
},
listByShopId: async (shopId: IdType): Promise<NailArtistListItemVO[]> => {
return await api.get<NailArtistListItemVO[]>(`/nail-artist/list/shop/${shopId}`) as unknown as NailArtistListItemVO[]
}
}
+398
View File
@@ -0,0 +1,398 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { IdType } from '@/utils/id'
/**
* Purpose: OrderItem supports order.ts by holding or executing the order item page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface OrderItem {
productId: IdType
quantity: number
artistId?: IdType
appointmentTime?: string
}
/**
* Purpose: CreateOrderRequest supports order.ts by holding or executing the create order request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface CreateOrderRequest {
couponId?: IdType
couponSourceType?: string
remark?: string
clientRequestId?: string
items: OrderItem[]
}
export type CheckoutPreviewRequest = CreateOrderRequest
export interface CheckoutCouponPreview {
id: IdType
couponId?: IdType
userCouponId?: IdType
sourceType?: string
couponName: string
couponType: number
couponTypeName?: string
discountValue?: number
minAmount?: number
reduceAmount?: number
discountAmount?: number
available?: boolean
best?: boolean
vipAuto?: boolean
displayText?: string
savingText?: string
unavailableReason?: string
startTime?: string
endTime?: string
}
export interface CheckoutIssue {
code: string
message: string
itemId?: IdType
productId?: IdType
productTitle?: string
}
export interface CheckoutPreview {
subtotalAmount: number
savedAmount: number
payableAmount: number
bestCoupon?: CheckoutCouponPreview
availableCoupons: CheckoutCouponPreview[]
unavailableCoupons: CheckoutCouponPreview[]
bookingAvailable?: boolean
bookingIssues?: CheckoutIssue[]
vipTip?: string
summaryText?: string
}
export interface PaymentOrderVO {
id: IdType
payNo?: string
orderId: IdType
orderNo?: string
userId?: IdType
shopId?: IdType
channel?: string
status?: string
payAmount?: number
paidAmount?: number
payTime?: string
expireTime?: string
remark?: string
}
export interface OrderQuoteItem {
orderItemId: IdType
quotedPrice?: number
}
export interface OrderQuoteSubmitRequest {
remark?: string
items: OrderQuoteItem[]
}
export interface OrderQuoteReplyRequest {
remark?: string
}
export interface OrderQuoteMessage {
id: IdType
orderId: IdType
actorId?: IdType
actorType?: string
actorTypeText?: string
action?: string
actionText?: string
remark?: string
items?: any[]
createTime?: string
}
export interface AfterSaleApplyRequest {
orderId: IdType
orderItemId?: IdType
type: string
reason: string
refundAmount?: number
}
export interface AfterSaleVO {
id: IdType
afterSaleNo?: string
orderId: IdType
orderItemId?: IdType
userId?: IdType
shopId?: IdType
type?: string
reason?: string
refundAmount?: number
status?: string
auditReason?: string
auditTime?: string
createTime?: string
}
export interface PageResult<T> {
list: T[]
total: number
page: number
size: number
}
export interface GrowthSummaryVO {
userId?: IdType
growthValue?: number
levelName?: string
appointmentCount?: number
reviewCount?: number
}
export const paymentApi = {
prepareOrderPayment: async (orderId: IdType): Promise<PaymentOrderVO> => {
return await api.post<PaymentOrderVO>(`/payment/order/${orderId}/prepare`) as unknown as PaymentOrderVO
},
mockSuccess: async (orderId: IdType): Promise<PaymentOrderVO> => {
return await api.post<PaymentOrderVO>(`/payment/order/${orderId}/mock-success`) as unknown as PaymentOrderVO
}
}
export const afterSaleApi = {
apply: async (data: AfterSaleApplyRequest): Promise<AfterSaleVO> => {
return await api.post<AfterSaleVO>('/after-sale/apply', data) as unknown as AfterSaleVO
},
listMy: async (params: { page: number; size: number }): Promise<PageResult<AfterSaleVO>> => {
return await api.get<PageResult<AfterSaleVO>>('/after-sale/my', { params }) as unknown as PageResult<AfterSaleVO>
}
}
export const growthApi = {
getSummary: async (): Promise<GrowthSummaryVO> => {
return await api.get<GrowthSummaryVO>('/growth/summary') as unknown as GrowthSummaryVO
}
}
/**
* Purpose: OrderArtistReviewVO supports order.ts by holding or executing the order artist review vo page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface OrderArtistReviewVO {
id: IdType
orderId: IdType
orderItemId: IdType
productId?: IdType
productTitle?: string
artistId?: IdType
artistName?: string
artistAvatar?: string
userId?: IdType
rating?: number
content?: string
imageFileIds?: IdType[]
status?: number
statusText?: string
submitTime?: string
reviewTime?: string
createTime?: string
}
/**
* Purpose: OrderArtistReviewSubmitRequest supports order.ts by holding or executing the order artist review submit request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface OrderArtistReviewSubmitRequest {
rating: number
content?: string
imageFileIds: IdType[]
}
/**
* Purpose: OrderArtistChangeOptionsVO supports order.ts by holding or executing the order artist change options vo page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface OrderArtistChangeOptionsVO {
orderId: IdType
orderItemId: IdType
currentArtistId?: IdType
currentArtistName?: string
artists: Array<{
artistId: IdType
artistName: string
artistAvatar?: string
userType?: number
participateProduction?: boolean
}>
}
/**
* Purpose: OrderArtistChangeRequestVO supports order.ts by holding or executing the order artist change request vo page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface OrderArtistChangeRequestVO {
id: IdType
orderId: IdType
orderItemId: IdType
productId?: IdType
productTitle?: string
shopId?: IdType
userId?: IdType
customerId?: IdType
originalArtistId?: IdType
originalArtistName?: string
requestedArtistId?: IdType
requestedArtistName?: string
fromArtistId?: IdType
fromArtistName?: string
toArtistId?: IdType
toArtistName?: string
requesterId?: IdType
requesterName?: string
status?: string
statusText?: string
reason?: string
rejectReason?: string
appointmentTime?: string
timeAffected?: boolean
timeImpactText?: string
originalPrice?: number | string
newPrice?: number | string
priceAffected?: boolean
priceImpactText?: string
reviewerId?: IdType
messageId?: IdType
reviewTime?: string
approvedTime?: string
rejectedTime?: string
expireTime?: string
createTime?: string
}
/**
* Purpose: OrderArtistChangeRequestSubmitRequest supports order.ts by holding or executing the order artist change request submit request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface OrderArtistChangeRequestSubmitRequest {
orderId: IdType
orderItemId: IdType
requestedArtistId: IdType
reason: string
}
/**
* Purpose: OrderArtistChangeRejectRequest supports order.ts by holding or executing the order artist change reject request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface OrderArtistChangeRejectRequest {
rejectReason?: string
}
/**
* orderApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const orderApi = {
// 创建订单
/**
* `createOrder` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param data: CreateOrderRequest caller-supplied value for `data: CreateOrderRequest`
*/
createOrder: (data: CreateOrderRequest) => {
return api.post('/order/create', data)
},
createInquiryAppointment: (data: CreateOrderRequest) => {
return api.post('/order/create', data)
},
checkoutPreview: async (data: CheckoutPreviewRequest): Promise<CheckoutPreview> => {
return await api.post<CheckoutPreview>('/order/checkout-preview', data) as unknown as CheckoutPreview
},
replyQuote: async (orderId: IdType, data?: OrderQuoteReplyRequest): Promise<any> => {
return await api.post(`/order/${orderId}/quote/reply`, data || {}) as unknown as any
},
confirmUserQuote: async (orderId: IdType): Promise<any> => {
return await api.put(`/order/${orderId}/quote/confirm`) as unknown as any
},
submitShopQuote: async (orderId: IdType, data: OrderQuoteSubmitRequest): Promise<any> => {
return await api.post(`/order/${orderId}/quote/shop`, data) as unknown as any
},
confirmShopQuote: async (orderId: IdType): Promise<any> => {
return await api.put(`/order/${orderId}/quote/shop/confirm`) as unknown as any
},
// 获取订单列表
getOrderList: async (): Promise<any[]> => {
return await api.get<any[]>('/order/list') as unknown as any[]
},
getMyPendingReviews: async (): Promise<OrderArtistReviewVO[]> => {
return await api.get<OrderArtistReviewVO[]>('/order/review/my-pending') as unknown as OrderArtistReviewVO[]
},
getOrderReviews: async (orderId: IdType): Promise<OrderArtistReviewVO[]> => {
return await api.get<OrderArtistReviewVO[]>(`/order/${orderId}/reviews`) as unknown as OrderArtistReviewVO[]
},
submitArtistReview: async (reviewId: IdType, data: OrderArtistReviewSubmitRequest): Promise<OrderArtistReviewVO> => {
return await api.post<OrderArtistReviewVO>(`/order/review/${reviewId}/submit`, data) as unknown as OrderArtistReviewVO
},
getArtistChangeOptions: async (orderId: IdType, orderItemId: IdType): Promise<OrderArtistChangeOptionsVO> => {
return await api.get<OrderArtistChangeOptionsVO>(`/order/${orderId}/artist-change/options`, {
params: { orderItemId }
}) as unknown as OrderArtistChangeOptionsVO
},
requestArtistChange: async (data: OrderArtistChangeRequestSubmitRequest): Promise<OrderArtistChangeRequestVO> => {
return await api.post<OrderArtistChangeRequestVO>('/order/artist-change/request', data) as unknown as OrderArtistChangeRequestVO
},
getMyPendingArtistChangeRequests: async (): Promise<OrderArtistChangeRequestVO[]> => {
return await api.get<OrderArtistChangeRequestVO[]>('/order/artist-change/my-pending') as unknown as OrderArtistChangeRequestVO[]
},
getOrderArtistChangeRequests: async (orderId: IdType): Promise<OrderArtistChangeRequestVO[]> => {
return await api.get<OrderArtistChangeRequestVO[]>(`/order/${orderId}/artist-change/requests`) as unknown as OrderArtistChangeRequestVO[]
},
approveArtistChange: async (requestId: IdType): Promise<OrderArtistChangeRequestVO> => {
return await api.put<OrderArtistChangeRequestVO>(`/order/artist-change/${requestId}/approve`) as unknown as OrderArtistChangeRequestVO
},
rejectArtistChange: async (requestId: IdType, data?: OrderArtistChangeRejectRequest): Promise<OrderArtistChangeRequestVO> => {
return await api.put<OrderArtistChangeRequestVO>(`/order/artist-change/${requestId}/reject`, data || {}) as unknown as OrderArtistChangeRequestVO
},
// 获取订单详情
/**
* `getOrderDetail` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param orderId: IdType caller-supplied value for `orderId: IdType`
*/
getOrderDetail: (orderId: IdType) => {
return api.get(`/order/detail/${orderId}`)
},
// 取消订单
/**
* `cancelOrder` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param orderId: IdType caller-supplied value for `orderId: IdType`
*/
cancelOrder: (orderId: IdType) => {
return api.put(`/order/cancel/${orderId}`)
},
}
+133
View File
@@ -0,0 +1,133 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { IdType } from '@/utils/id'
/**
* Purpose: ProductVO supports product.ts by holding or executing the product vo page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ProductVO {
id: IdType
shopId: IdType | null
shopName?: string
name: string
title?: string
description: string
targetAudience?: string
precautions?: string
image: string
imageFileIds?: string
imageUrls?: string[]
price: number
estimatedTime: number
approximateDuration?: string
serviceDurationMinutes?: number
bookableArtists?: string
availableBookableArtistCount?: number
bookableArtistRestricted?: boolean
availableCoupons?: string
category: string
tags?: string
tagList?: string[]
tagInfos?: TagInfo[]
status: number
likeCount?: number
collectCount?: number
createTime: string
updateTime: string
}
/**
* Purpose: TagInfo supports product.ts by holding or executing the tag info page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface TagInfo {
id: IdType
tagName: string
textColor?: string
bgColor?: string
borderColor?: string
}
/**
* Purpose: ListProductsParams supports product.ts by holding or executing the list products params page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ListProductsParams {
page: number
size: number
keyword?: string
tag?: string
tagIds?: string
}
/**
* Purpose: CreateProductRequest supports product.ts by holding or executing the create product request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface CreateProductRequest {
name: string
description: string
image: string
price: number
estimatedTime: number
category: string
status: number
shopId: IdType | null
}
/**
* Purpose: UpdateProductRequest supports product.ts by holding or executing the update product request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface UpdateProductRequest {
name?: string
description?: string
image?: string
price?: number
estimatedTime?: number
category?: string
status?: number
shopId?: IdType | null
}
/**
* productApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const productApi = {
getAllProducts: async (): Promise<ProductVO[]> => {
return await api.get<ProductVO[]>('/product/list/all') as unknown as ProductVO[]
},
getProductById: async (id: IdType): Promise<ProductVO> => {
return await api.get<ProductVO>(`/product/get/${id}`) as unknown as ProductVO
},
getProductsByTag: async (tag: string): Promise<ProductVO[]> => {
return await api.get<ProductVO[]>(`/product/list/tag/${tag}`) as unknown as ProductVO[]
},
likeProduct: async (productId: IdType): Promise<boolean> => {
return await api.post<boolean>(`/product-like/like/${productId}`) as unknown as boolean
},
unlikeProduct: async (productId: IdType): Promise<boolean> => {
return await api.post<boolean>(`/product-like/unlike/${productId}`) as unknown as boolean
},
searchProducts: async (keyword: string): Promise<ProductVO[]> => {
return await api.get<ProductVO[]>('/product/list/search', {
params: {
keyword: keyword
}
}) as unknown as ProductVO[]
},
getProductPage: async (params: ListProductsParams): Promise<{ list: ProductVO[]; total: number; page: number; size: number }> => {
return await api.get('/product/list/page', { params }) as unknown as { list: ProductVO[]; total: number; page: number; size: number }
}
}
@@ -0,0 +1,51 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { IdType } from '@/utils/id'
/**
* productLikeApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const productLikeApi = {
/**
* 点赞作品
* @param productId 作品ID
*/
/**
* `likeProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param productId: IdType caller-supplied value for `productId: IdType`
*/
likeProduct: (productId: IdType) => {
return api.post<boolean>(`/product-like/like/${productId}`)
},
/**
* 取消点赞作品
* @param productId 作品ID
*/
/**
* `unlikeProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param productId: IdType caller-supplied value for `productId: IdType`
*/
unlikeProduct: (productId: IdType) => {
return api.post<boolean>(`/product-like/unlike/${productId}`)
},
/**
* 检查用户是否已点赞作品
* @param productId 作品ID
*/
/**
* `checkLikeStatus` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param productId: IdType caller-supplied value for `productId: IdType`
*/
checkLikeStatus: (productId: IdType) => {
return api.get<boolean>(`/product-like/check/${productId}`)
}
}
+184
View File
@@ -0,0 +1,184 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { IdType } from '@/utils/id'
/**
* Purpose: ShopVO supports shop.ts by holding or executing the shop vo page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ShopVO {
id: IdType
shopName: string
description: string
address: string
mapProvider?: string
longitude?: number | string
latitude?: number | string
navigationUrls?: Record<string, string>
businessHours: string
status?: number
authorizationStartDate?: string
authorizationDays?: number
authorizationExpireTime?: string
authorizationExpired?: boolean
authorizationStatusText?: string
coverImageFileId?: string
coverImageUrls?: string[]
imageFileIds: string
imageUrls?: string[]
themePrimaryColor?: string
themeSecondaryColor?: string
themeAccentColor?: string
themePageBgColor?: string
themeCardBgColor?: string
themeBackgroundImageFileId?: string
createTime: string
updateTime: string
}
/**
* Purpose: ShopSimpleVO supports shop.ts by holding or executing the shop simple vo page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ShopSimpleVO {
id: string | number
shopName?: string
name?: string
}
/**
* Purpose: ShopTrustProfileVO carries public trust signals for a shop detail page.
* Usage: fetch it with getTrustProfile and render ratings, recent reviews, environment images, and booking hints.
*/
export interface ShopTrustProfileVO {
shopId: IdType
shopName?: string
businessHoursText?: string
businessStatusText?: string
locationAvailable?: boolean
distanceCapabilityText?: string
navigationAvailable?: boolean
stats?: {
averageRating?: number
reviewCount?: number
productCount?: number
artistCount?: number
recentReviewCount?: number
}
environmentImages?: string[]
featuredProducts?: Array<{
id: IdType
title?: string
imageUrl?: string
imageFileIds?: string
price?: number
likeCount?: number
collectCount?: number
availableBookableArtistCount?: number
bookingHint?: string
}>
recentReviews?: Array<{
id: IdType
productId?: IdType
productTitle?: string
ratingScore?: number
content?: string
imageUrls?: string[]
submittedAt?: string
}>
availabilitySummary?: {
available?: boolean
summaryText?: string
nextSlots?: string[]
}
contactSummary?: {
actionText?: string
phoneExposed?: boolean
phone?: string
}
}
/**
* Purpose: ListShopsParams supports shop.ts by holding or executing the list shops params page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ListShopsParams {
page: number
size: number
keyword?: string
}
/**
* Purpose: CreateShopRequest supports shop.ts by holding or executing the create shop request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface CreateShopRequest {
name: string
description: string
image: string
phone: string
address: string
businessHours: string
status: number
authorizationStartDate?: string
authorizationDays?: number
authorizationExpireTime?: string
themePrimaryColor?: string
themeSecondaryColor?: string
themeAccentColor?: string
themePageBgColor?: string
themeCardBgColor?: string
themeBackgroundImageFileId?: string
}
/**
* Purpose: UpdateShopRequest supports shop.ts by holding or executing the update shop request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface UpdateShopRequest {
name?: string
description?: string
image?: string
phone?: string
address?: string
businessHours?: string
status?: number
authorizationStartDate?: string
authorizationDays?: number
authorizationExpireTime?: string
themePrimaryColor?: string
themeSecondaryColor?: string
themeAccentColor?: string
themePageBgColor?: string
themeCardBgColor?: string
themeBackgroundImageFileId?: string
}
/**
* shopApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const shopApi = {
getAllShops: async (): Promise<ShopVO[]> => {
return await api.get<ShopVO[]>('/shop/list/all') as unknown as ShopVO[]
},
getPublicShops: async (): Promise<ShopVO[]> => {
return await api.get<ShopVO[]>('/shop/list/public') as unknown as ShopVO[]
},
getShopsSimple: async (): Promise<ShopSimpleVO[]> => {
return await api.get<ShopSimpleVO[]>('/shop/list/simple') as unknown as ShopSimpleVO[]
},
getShopById: async (id: IdType): Promise<ShopVO> => {
return await api.get<ShopVO>(`/shop/get/${id}`) as unknown as ShopVO
},
getTrustProfile: async (id: IdType): Promise<ShopTrustProfileVO> => {
return await api.get<ShopTrustProfileVO>(`/shop/trust-profile/${id}`) as unknown as ShopTrustProfileVO
}
}
+109
View File
@@ -0,0 +1,109 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { IdType } from '@/utils/id'
/**
* Purpose: TagVO supports tag.ts by holding or executing the tag vo page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface TagVO {
id: IdType
tagName: string
textColor: string
bgColor: string
borderColor: string
sceneGroup?: string
displayName?: string
sortOrder?: number
frontVisible?: number
createTime: string
updateTime: string
}
/**
* Purpose: TagFilterGroupVO groups public tags for scene filters.
* Usage: render each group as one filter row and pass selected tag ids to product list APIs.
*/
export interface TagFilterGroupVO {
groupName: string
tags: TagVO[]
}
/**
* Purpose: TagDTO supports tag.ts by holding or executing the tag dto page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface TagDTO {
tagName: string
textColor: string
bgColor: string
borderColor: string
sceneGroup?: string
displayName?: string
sortOrder?: number
frontVisible?: number
}
/**
* tagApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const tagApi = {
/**
* `getAllTags` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
*/
getAllTags: () => {
return api.get<TagVO[]>('/tag/list/all')
},
/**
* `getFilterOptions` API call. Use this method to load customer-facing scene filters.
* Call guide: optionally pass shopId, await the grouped tags, then query products with tagIds.
*/
getFilterOptions: (shopId?: IdType | null) => {
return api.get<TagFilterGroupVO[]>('/tag/list/filter-options', {
params: shopId ? { shopId } : undefined
})
},
/**
* `getTagById` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param id: IdType caller-supplied value for `id: IdType`
*/
getTagById: (id: IdType) => {
return api.get<TagVO>(`/tag/get/${id}`)
},
/**
* `createTag` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param data: TagDTO caller-supplied value for `data: TagDTO`
*/
createTag: (data: TagDTO) => {
return api.post<TagVO>('/tag/add', data)
},
/**
* `updateTag` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param id: IdType caller-supplied value for `id: IdType`
* @param data: TagDTO caller-supplied value for `data: TagDTO`
*/
updateTag: (id: IdType, data: TagDTO) => {
return api.put<TagVO>(`/tag/update/${id}`, data)
},
/**
* `deleteTag` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param id: IdType caller-supplied value for `id: IdType`
*/
deleteTag: (id: IdType) => {
return api.delete(`/tag/delete/${id}`)
}
}
+469
View File
@@ -0,0 +1,469 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { UserInfo } from './auth'
import type { IdType } from '@/utils/id'
/**
* Purpose: UserVO supports user.ts by holding or executing the user vo page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface UserVO extends UserInfo {
id: IdType
shopId?: IdType
shopName?: string
shopIds?: IdType[]
shopNames?: string[]
nickname: string
account: string
avatar: string
signature?: string
level?: string
type: number
vipId?: IdType
createTime: string
updateTime: string
status: number
phone?: string
contactPhone?: string
birthday?: string
wechatId?: string
wechatQrCode?: string
email?: string
maskedPhone?: string
maskedEmail?: string
shopRoleId?: IdType
shopRoleName?: string
parentUserId?: IdType
parentUserName?: string
parentUserTypeName?: string
relationSourceType?: string
}
/**
* Purpose: UpdateUserInfoRequest supports user.ts by holding or executing the update user info request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface UpdateUserInfoRequest {
nickname?: string
avatar?: string
signature?: string
contactPhone?: string
birthday?: string
wechatId?: string
wechatQrCode?: string
}
/**
* Purpose: ListUsersParams supports user.ts by holding or executing the list users params page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ListUsersParams {
page: number
size: number
keyword?: string
shopId?: IdType
status?: number
}
/**
* Purpose: CreateUserRequest supports user.ts by holding or executing the create user request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface CreateUserRequest {
account: string
nickname: string
phone: string
contactPhone?: string
birthday?: string
wechatId?: string
wechatQrCode?: string
password: string
type: number
shopId?: IdType
shopIds?: IdType[]
}
/**
* Purpose: UpdateUserRequest supports user.ts by holding or executing the update user request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface UpdateUserRequest {
account?: string
nickname?: string
phone?: string
contactPhone?: string
birthday?: string
wechatId?: string
wechatQrCode?: string
type?: number
shopId?: IdType
shopIds?: IdType[]
}
/**
* Purpose: UpdatePasswordRequest supports user.ts by holding or executing the update password request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface UpdatePasswordRequest {
password: string
verificationCode: string
}
/**
* Purpose: BindPhoneRequest supports user.ts by holding or executing the bind phone request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface BindPhoneRequest {
phone: string
verificationCode: string
}
/**
* Purpose: AvailabilityCheckResponse supports user.ts by holding or executing the availability check response page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface AvailabilityCheckResponse {
available: boolean
message: string
}
/**
* Purpose: LoginAccountCheckResponse supports user.ts by holding or executing the login account check response page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface LoginAccountCheckResponse {
exists: boolean
nickname?: string
message: string
}
/**
* Purpose: LoginShopSelectionResponse supports user.ts by holding or executing the login shop selection response page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface LoginShopSelectionResponse {
allowShoplessLogin: boolean
message: string
shops: Array<{
id: IdType
shopName: string
}>
}
/**
* Purpose: UserRelationVO supports user.ts by holding or executing the user relation vo page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface UserRelationVO {
userId: IdType
shopId?: IdType
shopName?: string
parentUserId?: IdType
parentUserName?: string
parentRoleType?: number
parentRoleTypeName?: string
sourceType?: string
sourceTypeName?: string
}
/**
* Purpose: NailArtistInfoVO supports user.ts by holding or executing the nail artist info vo page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface NailArtistInfoVO {
userId?: IdType
userType?: number
participateProduction?: number | boolean
status?: number
}
// 用户端常用接口约定:
// - relation 表示当前用户的门店和直属上级归属;
// - announcement 只用于首页滚动公告,不进入消息通知历史;
// - system-message 才是站内消息,popup/read 分开记录。
export interface InviteCodeVO {
id: IdType
inviteCode: string
ownerUserId?: IdType
ownerUserName?: string
shopId?: IdType
shopName?: string
status?: number
useCount?: number
expireTime?: string
createTime?: string
}
/**
* Purpose: UpdatePhoneRequest supports user.ts by holding or executing the update phone request page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface UpdatePhoneRequest {
oldPhone: string
newPhone: string
verificationCode: string
}
/**
* Purpose: UserAssetVO supports user.ts by holding or executing the user asset vo page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface UserAssetVO {
userId: IdType
nickname: string
balance: number
totalRechargeAmount: number
lastRechargeTime?: string
vipInfoId?: IdType
vipLevel: string
benefitId?: IdType
benefitInfo?: string
manualOverride?: boolean
vipStartTime?: string
vipExpireTime?: string
}
/**
* Purpose: BalanceHistoryItem supports user.ts by holding or executing the balance history item page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface BalanceHistoryItem {
id: IdType
userId: IdType
userNickname?: string
amount: number
type?: string
currentBalance?: number
beforeBalance?: number
afterBalance?: number
changeScene?: string
relatedOrderId?: IdType
relatedOrderNo?: string
externalOrderNo?: string
remark?: string
changeTime?: string
}
/**
* Purpose: SystemMessageVO supports user.ts by holding or executing the system message vo page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface SystemMessageVO {
id: IdType
title: string
content: string
imageFileId?: IdType
imageUrl?: string
publisherName?: string
targetType?: string
targetTypeName?: string
businessType?: string
businessId?: IdType
actionPath?: string
popupEnabled?: number
popupShown?: number
readStatus?: number
publishTime?: string
createTime?: string
}
/**
* Purpose: AnnouncementVO supports user.ts by holding or executing the announcement vo page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface AnnouncementVO {
id: IdType
title: string
content: string
publisherName?: string
targetType?: string
status?: number
sortOrder?: number
publishTime?: string
}
/**
* Purpose: VipRechargePlanVO supports user.ts by holding or executing the vip recharge plan vo page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface VipRechargePlanVO {
id: IdType
shopId: IdType
shopName?: string
title: string
rechargeAmount: number
giftAmount: number
vipLevel: string
description?: string
sortOrder?: number
status: number
}
/**
* Purpose: ContactInfoVO supports user.ts by holding or executing the contact info vo page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ContactInfoVO {
contactUserId?: IdType
contactName?: string
roleLabel?: string
phone?: string
phoneAvailable?: boolean
wechatId?: string
wechatAvailable?: boolean
wechatQrCode?: string
platformContactAvailable?: boolean
platformContactText?: string
}
/**
* userApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const userApi = {
getUserInfo: async (): Promise<UserVO> => {
return await api.get<UserVO>('/user/info') as unknown as UserVO
},
/**
* `updateUserInfo` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param data: UpdateUserInfoRequest caller-supplied value for `data: UpdateUserInfoRequest`
*/
updateUserInfo: (data: UpdateUserInfoRequest) => {
return api.put('/user/update', data)
},
/**
* `updatePassword` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param data: UpdatePasswordRequest caller-supplied value for `data: UpdatePasswordRequest`
*/
updatePassword: (data: UpdatePasswordRequest) => {
return api.put('/user/password', data)
},
/**
* `bindPhone` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param data: BindPhoneRequest caller-supplied value for `data: BindPhoneRequest`
*/
bindPhone: (data: BindPhoneRequest) => {
return api.post('/user/bind-phone', data)
},
/**
* `updatePhone` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param data: UpdatePhoneRequest caller-supplied value for `data: UpdatePhoneRequest`
*/
updatePhone: (data: UpdatePhoneRequest) => {
return api.put('/user/phone', data)
},
getUserByAccount: async (account: string): Promise<UserVO> => {
return await api.get<UserVO>(`/user/get/account/${account}`) as unknown as UserVO
},
checkAccountAvailability: async (account: string): Promise<AvailabilityCheckResponse> => {
return await api.get<AvailabilityCheckResponse>(`/user/check/account/${encodeURIComponent(account)}`) as unknown as AvailabilityCheckResponse
},
checkLoginAccountAvailability: async (account: string): Promise<LoginAccountCheckResponse> => {
return await api.get<LoginAccountCheckResponse>(`/user/check/login-account/${encodeURIComponent(account)}`) as unknown as LoginAccountCheckResponse
},
getLoginShopsByAccount: async (account: string): Promise<LoginShopSelectionResponse> => {
return await api.get<LoginShopSelectionResponse>(`/user/check/login-shops/account/${encodeURIComponent(account)}`) as unknown as LoginShopSelectionResponse
},
getLoginShopsByPhone: async (phone: string): Promise<LoginShopSelectionResponse> => {
return await api.get<LoginShopSelectionResponse>(`/user/check/login-shops/phone/${encodeURIComponent(phone)}`) as unknown as LoginShopSelectionResponse
},
checkPhoneAvailability: async (phone: string): Promise<AvailabilityCheckResponse> => {
return await api.get<AvailabilityCheckResponse>(`/user/check/phone/${encodeURIComponent(phone)}`) as unknown as AvailabilityCheckResponse
},
listUsersByType: async (type: number): Promise<UserVO[]> => {
return await api.get<UserVO[]>(`/user/list/type/${type}`) as unknown as UserVO[]
},
/**
* `sendVerificationCode` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param data: { phone: string; sceneCode?: string } caller-supplied value for `data: { phone: string; sceneCode?: string }`
*/
sendVerificationCode: (data: { phone: string; sceneCode?: string }) => {
return api.post('/user/send-verification-code', data)
},
/**
* `switchShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param shopId?: string | number caller-supplied value for `shopId?: string | number`
*/
switchShop: (shopId?: string | number) => {
return api.post('/user/switch-shop', { shopId })
},
getMyAsset: async (): Promise<UserAssetVO> => {
return await api.get<UserAssetVO>('/user/asset/me') as unknown as UserAssetVO
},
getMyBalanceHistory: async (): Promise<BalanceHistoryItem[]> => {
return await api.get<BalanceHistoryItem[]>('/user/balance/history/me') as unknown as BalanceHistoryItem[]
},
listMyMessages: async (): Promise<SystemMessageVO[]> => {
return await api.get<SystemMessageVO[]>('/system-message/my/list') as unknown as SystemMessageVO[]
},
listMyPopupMessages: async (): Promise<SystemMessageVO[]> => {
return await api.get<SystemMessageVO[]>('/system-message/my/popup') as unknown as SystemMessageVO[]
},
getMyUnreadMessageCount: async (): Promise<{ unreadCount: number }> => {
return await api.get<{ unreadCount: number }>('/system-message/my/unread-count') as unknown as { unreadCount: number }
},
getMyMessage: async (id: IdType): Promise<SystemMessageVO> => {
return await api.get<SystemMessageVO>(`/system-message/my/${id}`) as unknown as SystemMessageVO
},
/**
* `markMessagePopupShown` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param id: IdType caller-supplied value for `id: IdType`
*/
markMessagePopupShown: (id: IdType) => {
return api.put(`/system-message/my/${id}/popup-shown`, {})
},
/**
* `markMessageRead` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param id: IdType caller-supplied value for `id: IdType`
*/
markMessageRead: (id: IdType) => {
return api.put(`/system-message/my/${id}/read`, {})
},
listMyAnnouncements: async (): Promise<AnnouncementVO[]> => {
return await api.get<AnnouncementVO[]>('/announcement/my/list') as unknown as AnnouncementVO[]
},
listMyVipRechargePlans: async (): Promise<VipRechargePlanVO[]> => {
return await api.get<VipRechargePlanVO[]>('/vip-recharge-plan/my/list') as unknown as VipRechargePlanVO[]
},
getMyRelation: async (): Promise<UserRelationVO> => {
return await api.get<UserRelationVO>('/user/relation/me') as unknown as UserRelationVO
},
getNailArtistInfo: async (userId: IdType): Promise<NailArtistInfoVO | null> => {
return await api.get<NailArtistInfoVO | null>(`/nail-artist/get/${userId}`) as unknown as NailArtistInfoVO | null
},
// 注册页输入邀请码时先解析,给用户展示“将归属到谁/哪个店铺”。
resolveInviteCode: async (code: string): Promise<InviteCodeVO> => {
return await api.get<InviteCodeVO>('/user/invite-code/resolve', { params: { code } }) as unknown as InviteCodeVO
},
getShopManagerContact: async (shopId: IdType): Promise<ContactInfoVO> => {
return await api.get<ContactInfoVO>(`/contact-info/shop/${shopId}/manager`) as unknown as ContactInfoVO
},
getProductArtistContact: async (productId: IdType, artistId: IdType): Promise<ContactInfoVO> => {
return await api.get<ContactInfoVO>(`/contact-info/product/${productId}/artist/${artistId}`) as unknown as ContactInfoVO
},
getOrderArtistContact: async (orderId: IdType, artistId?: IdType): Promise<ContactInfoVO> => {
const params = artistId ? { artistId } : {}
return await api.get<ContactInfoVO>(`/contact-info/order/${orderId}/artist`, { params }) as unknown as ContactInfoVO
},
getPlatformContact: async (): Promise<ContactInfoVO> => {
return await api.get<ContactInfoVO>('/contact-info/platform') as unknown as ContactInfoVO
},
/**
* `deactivateAccount` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
*/
deactivateAccount: () => {
return api.delete('/user/deactivate')
}
}
+123
View File
@@ -0,0 +1,123 @@
/**
* Front-end API wrapper for this module.
* Call guide: import the named API object, then call the matching method from a Vue page or composable.
*/
import api from './index'
import type { IdType } from '@/utils/id'
/**
* Purpose: WishlistItem supports wishlist.ts by holding or executing the wishlist item page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface WishlistItem {
id: IdType
userId: IdType
productId: IdType
groupId?: IdType | null
groupName?: string | null
note?: string | null
sortOrder?: number | null
product: {
id: IdType
shopId: IdType | null
shopName?: string
title: string
description: string
imageFileIds?: string
imageUrls?: string[]
price: number
tags?: string
tagList?: string[]
tagInfos?: any[]
likeCount?: number
collectCount?: number
approximateDuration?: string
bookableArtists?: string
availableCoupons?: string
createTime: string
updateTime: string
}
}
export interface WishlistGroup {
id: IdType
name: string
sortOrder: number
itemCount: number
items?: WishlistItem[]
}
export interface WishlistInspiration {
total: number
groups: WishlistGroup[]
}
export interface WishlistGroupPayload {
name: string
sortOrder?: number
}
export interface WishlistAddWithGroupPayload {
productId: IdType
groupId?: IdType | null
note?: string
sortOrder?: number
}
export interface WishlistMovePayload {
wishlistId?: IdType
productId?: IdType
groupId?: IdType | null
note?: string
sortOrder?: number
}
/**
* wishlistApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const wishlistApi = {
addToWishlist: async (productId: IdType): Promise<boolean> => {
return await api.post<boolean>('/wishlist/add', { productId }) as unknown as boolean
},
removeFromWishlist: async (productId: IdType): Promise<boolean> => {
return await api.post<boolean>('/wishlist/remove', { productId }) as unknown as boolean
},
checkWishlist: async (productId: IdType): Promise<boolean> => {
return await api.get<boolean>(`/wishlist/check?productId=${productId}`) as unknown as boolean
},
getWishlist: async (): Promise<WishlistItem[]> => {
return await api.get<WishlistItem[]>('/wishlist/list') as unknown as WishlistItem[]
},
getGroups: async (): Promise<WishlistGroup[]> => {
return await api.get<WishlistGroup[]>('/wishlist/groups') as unknown as WishlistGroup[]
},
createGroup: async (payload: WishlistGroupPayload): Promise<IdType> => {
return await api.post<IdType>('/wishlist/groups', payload) as unknown as IdType
},
updateGroup: async (id: IdType, payload: WishlistGroupPayload): Promise<boolean> => {
return await api.put<boolean>(`/wishlist/groups/${id}`, payload) as unknown as boolean
},
deleteGroup: async (id: IdType): Promise<boolean> => {
return await api.delete<boolean>(`/wishlist/groups/${id}`) as unknown as boolean
},
addWithGroup: async (payload: WishlistAddWithGroupPayload): Promise<boolean> => {
return await api.post<boolean>('/wishlist/add-with-group', payload) as unknown as boolean
},
moveWishlist: async (payload: WishlistMovePayload): Promise<boolean> => {
return await api.post<boolean>('/wishlist/move', payload) as unknown as boolean
},
getInspiration: async (): Promise<WishlistInspiration> => {
return await api.get<WishlistInspiration>('/wishlist/inspiration') as unknown as WishlistInspiration
}
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>

After

Width:  |  Height:  |  Size: 496 B

+90
View File
@@ -0,0 +1,90 @@
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// Generated by unplugin-auto-import
// biome-ignore lint: disable
export {}
declare global {
const EffectScope: typeof import('vue').EffectScope
const acceptHMRUpdate: typeof import('pinia').acceptHMRUpdate
const computed: typeof import('vue').computed
const createApp: typeof import('vue').createApp
const createPinia: typeof import('pinia').createPinia
const customRef: typeof import('vue').customRef
const defineAsyncComponent: typeof import('vue').defineAsyncComponent
const defineComponent: typeof import('vue').defineComponent
const defineStore: typeof import('pinia').defineStore
const effectScope: typeof import('vue').effectScope
const getActivePinia: typeof import('pinia').getActivePinia
const getCurrentInstance: typeof import('vue').getCurrentInstance
const getCurrentScope: typeof import('vue').getCurrentScope
const getCurrentWatcher: typeof import('vue').getCurrentWatcher
const h: typeof import('vue').h
const inject: typeof import('vue').inject
const isProxy: typeof import('vue').isProxy
const isReactive: typeof import('vue').isReactive
const isReadonly: typeof import('vue').isReadonly
const isRef: typeof import('vue').isRef
const isShallow: typeof import('vue').isShallow
const mapActions: typeof import('pinia').mapActions
const mapGetters: typeof import('pinia').mapGetters
const mapState: typeof import('pinia').mapState
const mapStores: typeof import('pinia').mapStores
const mapWritableState: typeof import('pinia').mapWritableState
const markRaw: typeof import('vue').markRaw
const nextTick: typeof import('vue').nextTick
const onActivated: typeof import('vue').onActivated
const onBeforeMount: typeof import('vue').onBeforeMount
const onBeforeRouteLeave: typeof import('vue-router').onBeforeRouteLeave
const onBeforeRouteUpdate: typeof import('vue-router').onBeforeRouteUpdate
const onBeforeUnmount: typeof import('vue').onBeforeUnmount
const onBeforeUpdate: typeof import('vue').onBeforeUpdate
const onDeactivated: typeof import('vue').onDeactivated
const onErrorCaptured: typeof import('vue').onErrorCaptured
const onMounted: typeof import('vue').onMounted
const onRenderTracked: typeof import('vue').onRenderTracked
const onRenderTriggered: typeof import('vue').onRenderTriggered
const onScopeDispose: typeof import('vue').onScopeDispose
const onServerPrefetch: typeof import('vue').onServerPrefetch
const onUnmounted: typeof import('vue').onUnmounted
const onUpdated: typeof import('vue').onUpdated
const onWatcherCleanup: typeof import('vue').onWatcherCleanup
const provide: typeof import('vue').provide
const reactive: typeof import('vue').reactive
const readonly: typeof import('vue').readonly
const ref: typeof import('vue').ref
const resolveComponent: typeof import('vue').resolveComponent
const setActivePinia: typeof import('pinia').setActivePinia
const setMapStoreSuffix: typeof import('pinia').setMapStoreSuffix
const shallowReactive: typeof import('vue').shallowReactive
const shallowReadonly: typeof import('vue').shallowReadonly
const shallowRef: typeof import('vue').shallowRef
const storeToRefs: typeof import('pinia').storeToRefs
const toRaw: typeof import('vue').toRaw
const toRef: typeof import('vue').toRef
const toRefs: typeof import('vue').toRefs
const toValue: typeof import('vue').toValue
const triggerRef: typeof import('vue').triggerRef
const unref: typeof import('vue').unref
const useAttrs: typeof import('vue').useAttrs
const useCssModule: typeof import('vue').useCssModule
const useCssVars: typeof import('vue').useCssVars
const useId: typeof import('vue').useId
const useLink: typeof import('vue-router').useLink
const useModel: typeof import('vue').useModel
const useRoute: typeof import('vue-router').useRoute
const useRouter: typeof import('vue-router').useRouter
const useSlots: typeof import('vue').useSlots
const useTemplateRef: typeof import('vue').useTemplateRef
const watch: typeof import('vue').watch
const watchEffect: typeof import('vue').watchEffect
const watchPostEffect: typeof import('vue').watchPostEffect
const watchSyncEffect: typeof import('vue').watchSyncEffect
}
// for type re-export
declare global {
// @ts-ignore
export type { Component, Slot, Slots, ComponentPublicInstance, ComputedRef, DirectiveBinding, ExtractDefaultPropTypes, ExtractPropTypes, ExtractPublicPropTypes, InjectionKey, PropType, Ref, ShallowRef, MaybeRef, MaybeRefOrGetter, VNode, WritableComputedRef } from 'vue'
import('vue')
}
+88
View File
@@ -0,0 +1,88 @@
/* eslint-disable */
// @ts-nocheck
// biome-ignore lint: disable
// oxlint-disable
// ------
// Generated by unplugin-vue-components
// Read more: https://github.com/vuejs/core/pull/3399
export {}
/* prettier-ignore */
declare module 'vue' {
export interface GlobalComponents {
AAlert: typeof import('ant-design-vue/es')['Alert']
AAvatar: typeof import('ant-design-vue/es')['Avatar']
ABadge: typeof import('ant-design-vue/es')['Badge']
AButton: typeof import('ant-design-vue/es')['Button']
ACard: typeof import('ant-design-vue/es')['Card']
ACarousel: typeof import('ant-design-vue/es')['Carousel']
ACheckbox: typeof import('ant-design-vue/es')['Checkbox']
ACheckboxGroup: typeof import('ant-design-vue/es')['CheckboxGroup']
ACol: typeof import('ant-design-vue/es')['Col']
ACollapse: typeof import('ant-design-vue/es')['Collapse']
ACollapsePanel: typeof import('ant-design-vue/es')['CollapsePanel']
ADatePicker: typeof import('ant-design-vue/es')['DatePicker']
ADescriptions: typeof import('ant-design-vue/es')['Descriptions']
ADescriptionsItem: typeof import('ant-design-vue/es')['DescriptionsItem']
ADivider: typeof import('ant-design-vue/es')['Divider']
ADrawer: typeof import('ant-design-vue/es')['Drawer']
ADropdown: typeof import('ant-design-vue/es')['Dropdown']
AEmpty: typeof import('ant-design-vue/es')['Empty']
AForm: typeof import('ant-design-vue/es')['Form']
AFormItem: typeof import('ant-design-vue/es')['FormItem']
AImage: typeof import('ant-design-vue/es')['Image']
AInput: typeof import('ant-design-vue/es')['Input']
AInputNumber: typeof import('ant-design-vue/es')['InputNumber']
AInputPassword: typeof import('ant-design-vue/es')['InputPassword']
AInputSearch: typeof import('ant-design-vue/es')['InputSearch']
ALayout: typeof import('ant-design-vue/es')['Layout']
ALayoutContent: typeof import('ant-design-vue/es')['LayoutContent']
ALayoutHeader: typeof import('ant-design-vue/es')['LayoutHeader']
ALayoutSider: typeof import('ant-design-vue/es')['LayoutSider']
AList: typeof import('ant-design-vue/es')['List']
AListItem: typeof import('ant-design-vue/es')['ListItem']
AListItemMeta: typeof import('ant-design-vue/es')['ListItemMeta']
AMenu: typeof import('ant-design-vue/es')['Menu']
AMenuDivider: typeof import('ant-design-vue/es')['MenuDivider']
AMenuItem: typeof import('ant-design-vue/es')['MenuItem']
AModal: typeof import('ant-design-vue/es')['Modal']
APageHeader: typeof import('ant-design-vue/es')['PageHeader']
APopconfirm: typeof import('ant-design-vue/es')['Popconfirm']
AProgress: typeof import('ant-design-vue/es')['Progress']
ARadio: typeof import('ant-design-vue/es')['Radio']
ARadioButton: typeof import('ant-design-vue/es')['RadioButton']
ARadioGroup: typeof import('ant-design-vue/es')['RadioGroup']
ARangePicker: typeof import('ant-design-vue/es')['RangePicker']
AResult: typeof import('ant-design-vue/es')['Result']
ARow: typeof import('ant-design-vue/es')['Row']
ASegmented: typeof import('ant-design-vue/es')['Segmented']
ASelect: typeof import('ant-design-vue/es')['Select']
ASelectOption: typeof import('ant-design-vue/es')['SelectOption']
ASkeleton: typeof import('ant-design-vue/es')['Skeleton']
ASpace: typeof import('ant-design-vue/es')['Space']
ASpin: typeof import('ant-design-vue/es')['Spin']
AStatistic: typeof import('ant-design-vue/es')['Statistic']
ASwitch: typeof import('ant-design-vue/es')['Switch']
ATable: typeof import('ant-design-vue/es')['Table']
ATabPane: typeof import('ant-design-vue/es')['TabPane']
ATabs: typeof import('ant-design-vue/es')['Tabs']
ATag: typeof import('ant-design-vue/es')['Tag']
ATextarea: typeof import('ant-design-vue/es')['Textarea']
ATimeline: typeof import('ant-design-vue/es')['Timeline']
ATimelineItem: typeof import('ant-design-vue/es')['TimelineItem']
ATooltip: typeof import('ant-design-vue/es')['Tooltip']
ATypographyText: typeof import('ant-design-vue/es')['TypographyText']
AUpload: typeof import('ant-design-vue/es')['Upload']
BottomNav: typeof import('./components/BottomNav.vue')['default']
DraftActions: typeof import('./components/DraftActions.vue')['default']
ElButton: typeof import('element-plus/es')['ElButton']
ElColorPicker: typeof import('element-plus/es')['ElColorPicker']
ElConfigProvider: typeof import('element-plus/es')['ElConfigProvider']
ElIcon: typeof import('element-plus/es')['ElIcon']
RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView']
SystemMessageCard: typeof import('./components/SystemMessageCard.vue')['default']
TableEllipsisText: typeof import('./components/TableEllipsisText.vue')['default']
}
}
@@ -0,0 +1,273 @@
<template>
<a-layout class="bottom-nav">
<a-layout-content class="nav-content">
<button class="nav-item" :class="{ active: currentRoute === 'home' }" type="button" @click="handleNavClick('home')">
<a-badge :count="0" :offset="[0, 0]">
<div class="nav-icon">
<HomeOutlined :style="{ fontSize: '25px' }" />
</div>
</a-badge>
<span class="nav-label">首页</span>
</button>
<button class="nav-item" :class="{ active: currentRoute === 'products' }" type="button" @click="handleNavClick('products')">
<a-badge :count="0" :offset="[0, 0]">
<div class="nav-icon">
<ShoppingOutlined :style="{ fontSize: '25px' }" />
</div>
</a-badge>
<span class="nav-label">作品集</span>
</button>
<button class="nav-item" :class="{ active: currentRoute === 'cart' }" type="button" @click="handleNavClick('cart')">
<a-badge :count="cartCount" :offset="[0, 0]">
<div class="nav-icon">
<ShoppingCartOutlined :style="{ fontSize: '25px' }" />
</div>
</a-badge>
<span class="nav-label">购物车</span>
</button>
<button class="nav-item" :class="{ active: currentRoute === 'profile' }" type="button" @click="handleNavClick('profile')">
<a-badge :dot="hasNotification" :offset="[0, 0]">
<div class="nav-icon">
<UserOutlined :style="{ fontSize: '25px' }" />
</div>
</a-badge>
<span class="nav-label">我的</span>
</button>
</a-layout-content>
</a-layout>
</template>
<script setup lang="ts">
/**
* BottomNav page script.
* 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, useRoute } from 'vue-router'
import { HomeOutlined, ShoppingOutlined, ShoppingCartOutlined, UserOutlined } from '@ant-design/icons-vue'
/**
* Purpose: router supports BottomNav.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()
/**
* Purpose: route supports BottomNav.vue by holding or executing the route 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 route = useRoute()
// 注入全局购物车数量状态
const cartCount = inject('cartCount', ref(0))
// 注入更新购物车数量的方法
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
// 是否有未读通知
/** hasNotification is a reactive state variable used by the template and event handlers. */
const hasNotification = computed(() => true)
// 加载购物车数量
/** loadCartCount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadCartCount = async () => {
// 这里我们不需要做任何事情,因为全局状态会自动更新
// 但我们仍然需要这个方法,因为 App.vue 会调用它
}
// 页面加载时获取购物车数量
onMounted(() => {
updateCartCount()
})
// 提供一个方法让其他组件调用更新购物车数量
defineExpose({
loadCartCount
})
// 根据当前路由判断激活的导航项
/** currentRoute is a reactive state variable used by the template and event handlers. */
const currentRoute = computed(() => {
if (!route || !route.path) return 'home'
const path = route.path
if (path === '/') return 'home'
if (path === '/products') return 'products'
if (path === '/product') return 'products'
if (path === '/cart') return 'cart'
if (path === '/profile') return 'profile'
if (path === '/wishlist') return 'profile'
return 'home'
})
// 处理导航点击事件
/** handleNavClick is a local helper used by this page script. */
const handleNavClick = (tab: string) => {
if (tab === 'home') {
router.push('/home')
} else if (tab === 'products') {
router.push('/products')
} else if (tab === 'cart') {
router.push('/cart')
} else if (tab === 'profile') {
router.push('/profile')
}
}
</script>
<style scoped>
.bottom-nav {
position: fixed;
bottom: 0;
left: 0;
right: 0;
width: 100%;
height: 64px;
background: color-mix(in srgb, var(--theme-card-bg) 96%, transparent);
border-top: 1px solid var(--theme-border);
box-shadow: 0 -14px 34px color-mix(in srgb, var(--theme-neutral) 10%, transparent);
z-index: 1000;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
backdrop-filter: blur(18px);
backface-visibility: hidden;
will-change: transform;
transform: translateZ(0);
transition: none !important;
}
.nav-content {
display: flex;
justify-content: space-around;
align-items: center;
height: 100%;
width: 100%;
max-width: none;
margin: 0 auto;
padding: 0 12px calc(env(safe-area-inset-bottom, 0px) / 2);
transition: none !important;
}
.nav-item {
appearance: none;
border: 0;
background: transparent;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 3px;
min-width: 58px;
min-height: 54px;
padding: 6px 8px;
cursor: pointer;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
color: var(--text-secondary);
}
.nav-item:hover {
transform: translateY(-2px);
}
.nav-item.active {
color: var(--theme-primary-action);
}
.nav-item.active .nav-icon {
transform: translateY(-2px);
}
.nav-icon {
display: flex;
align-items: center;
justify-content: center;
width: 40px;
height: 34px;
margin-bottom: 0;
border-radius: 18px 18px 16px 16px;
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
color: var(--text-secondary);
opacity: 1;
}
.nav-item.active .nav-icon {
color: var(--theme-primary-action);
background: color-mix(in srgb, var(--theme-primary) 34%, var(--theme-card-bg));
}
.nav-label {
font-size: 11px;
font-weight: 700;
color: var(--text-secondary);
transition: all 0.3s ease;
}
.nav-item.active .nav-label {
color: var(--theme-primary-action);
}
.nav-item :deep(.ant-badge-count) {
min-width: 16px;
height: 16px;
line-height: 16px;
background: var(--theme-primary-action);
box-shadow: 0 0 0 1px var(--theme-card-bg);
}
.nav-item :deep(.ant-badge-dot) {
background: var(--theme-secondary);
box-shadow: 0 0 0 1px var(--theme-card-bg);
}
@media (max-width: 359px) {
.bottom-nav {
height: 56px;
}
.nav-content {
padding: 0 4px;
}
.nav-item {
min-width: 0;
padding: 8px 4px;
border-radius: 10px;
}
.nav-icon {
margin-bottom: 0;
}
.nav-icon :deep(.anticon) {
font-size: 22px !important;
}
.nav-label {
display: none;
}
}
@media (min-width: 768px) {
.nav-content {
max-width: var(--frontend-page-max-width);
}
}
</style>
<style>
@media (min-width: 768px) {
.fingertip-designer-phone-frame > .bottom-nav {
right: auto;
bottom: 0;
left: 50%;
width: var(--frontend-page-max-width);
max-width: calc(100vw - 48px);
border-bottom-right-radius: 32px;
border-bottom-left-radius: 32px;
transform: translateX(-50%) translateZ(0);
}
}
</style>
@@ -0,0 +1,71 @@
<template>
<div class="draft-actions">
<a-space wrap>
<a-button size="small" @click="$emit('save')" :disabled="disabled">
暂存
</a-button>
<a-button v-if="showClear" size="small" type="link" @click="$emit('clear')" :disabled="disabled">
清除暂存
</a-button>
<span v-if="savedAt" class="draft-saved-at">
上次暂存:{{ formattedSavedAt }}
</span>
<span v-else class="draft-saved-at">
暂存仅保存在当前浏览器中
</span>
</a-space>
</div>
</template>
<script setup lang="ts">
/**
* DraftActions page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed } from 'vue'
/**
* Purpose: props supports DraftActions.vue by holding or executing the props 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 props = withDefaults(defineProps<{
savedAt?: number | null
disabled?: boolean
showClear?: boolean
}>(), {
savedAt: null,
disabled: false,
showClear: true
})
defineEmits<{
(event: 'save'): void
(event: 'clear'): void
}>()
/** formattedSavedAt is a reactive state variable used by the template and event handlers. */
const formattedSavedAt = computed(() => {
if (!props.savedAt) {
return ''
}
const date = new Date(props.savedAt)
const year = date.getFullYear()
const month = `${date.getMonth() + 1}`.padStart(2, '0')
const day = `${date.getDate()}`.padStart(2, '0')
const hour = `${date.getHours()}`.padStart(2, '0')
const minute = `${date.getMinutes()}`.padStart(2, '0')
return `${year}-${month}-${day} ${hour}:${minute}`
})
</script>
<style scoped>
.draft-actions {
margin-bottom: 12px;
}
.draft-saved-at {
color: var(--text-secondary);
font-size: 12px;
line-height: 24px;
}
</style>
@@ -0,0 +1,280 @@
<script setup lang="ts">
import { computed } from 'vue'
import { BellOutlined, ClockCircleOutlined } from '@ant-design/icons-vue'
import { renderRichContent } from '@/utils/rich-content'
/**
* Purpose: props supports SystemMessageCard.vue by holding or executing the props 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 props = withDefaults(defineProps<{
title?: string
content?: string
imageUrl?: string
imageAlt?: string
meta?: string
badge?: string
auxiliaryBadge?: string
surface?: 'modal' | 'preview'
footerAlign?: 'between' | 'end'
}>(), {
title: '系统消息',
content: '',
imageUrl: '',
imageAlt: '消息图片',
meta: '',
badge: '',
auxiliaryBadge: '',
surface: 'preview',
footerAlign: 'between'
})
/**
* Purpose: hasImage supports SystemMessageCard.vue by holding or executing the has image 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 hasImage = computed(() => Boolean(props.imageUrl))
/**
* Purpose: displayTitle supports SystemMessageCard.vue by holding or executing the display title 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 displayTitle = computed(() => props.title?.trim() || '系统消息')
/**
* Purpose: displayContent supports SystemMessageCard.vue by holding or executing the display content 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 displayContent = computed(() => props.content?.trim() || (hasImage.value ? '' : '你收到了一条新的系统消息。'))
const displayContentHtml = computed(() => renderRichContent(displayContent.value))
</script>
<template>
<article
class="system-message-card"
:class="[
`system-message-card--${surface}`,
`system-message-card--footer-${footerAlign}`,
{ 'system-message-card--with-image': hasImage }
]"
>
<div v-if="hasImage" class="system-message-card__media">
<img :src="imageUrl" :alt="imageAlt" />
</div>
<div v-else class="system-message-card__icon">
<BellOutlined />
</div>
<section class="system-message-card__main">
<div v-if="badge || auxiliaryBadge" class="system-message-card__badges">
<span v-if="auxiliaryBadge" class="system-message-card__badge system-message-card__badge--soft">{{ auxiliaryBadge }}</span>
<span v-if="badge" class="system-message-card__badge">{{ badge }}</span>
</div>
<h2 class="system-message-card__title">{{ displayTitle }}</h2>
<div v-if="meta" class="system-message-card__meta">
<ClockCircleOutlined />
<span>{{ meta }}</span>
</div>
<div v-if="displayContentHtml" class="system-message-card__content" v-html="displayContentHtml"></div>
</section>
<footer v-if="$slots.footer" class="system-message-card__footer">
<slot name="footer" />
</footer>
</article>
</template>
<style scoped>
.system-message-card {
width: 100%;
overflow: hidden;
border: 1px solid var(--theme-border);
border-radius: 8px;
background: var(--theme-card-bg);
}
.system-message-card--preview {
box-shadow: 0 20px 54px rgba(77, 50, 62, 0.16);
}
.system-message-card--modal {
border: 0;
box-shadow: none;
}
.system-message-card__media {
width: 100%;
aspect-ratio: 16 / 9;
padding: 12px 12px 0;
background: var(--theme-gradient-soft);
}
.system-message-card__media img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 8px;
}
.system-message-card__icon {
display: grid;
width: 48px;
height: 48px;
margin: 28px auto 0;
place-items: center;
border-radius: 8px;
color: #ffffff;
font-size: 20px;
background: var(--theme-gradient);
box-shadow: var(--theme-button-shadow);
}
.system-message-card__main {
padding: 20px 30px 28px;
text-align: center;
}
.system-message-card--with-image .system-message-card__main {
padding-top: 20px;
}
.system-message-card__badges {
display: flex;
flex-wrap: wrap;
gap: 8px;
justify-content: center;
margin-bottom: 12px;
}
.system-message-card__badge {
display: inline-flex;
min-height: 24px;
align-items: center;
padding: 0 10px;
border-radius: 8px;
color: #ffffff;
font-size: 12px;
font-weight: 700;
background: var(--theme-gradient);
}
.system-message-card__badge--soft {
color: var(--theme-primary);
background: var(--theme-primary-soft);
}
.system-message-card__title {
margin: 0;
color: var(--text-primary);
font-size: 19px;
font-weight: 800;
line-height: 1.35;
overflow-wrap: break-word;
}
.system-message-card__meta {
display: inline-flex;
max-width: 100%;
gap: 6px;
align-items: center;
justify-content: center;
margin-top: 10px;
color: var(--text-secondary);
font-size: 13px;
line-height: 1.5;
overflow-wrap: break-word;
}
.system-message-card__content {
margin: 20px 0 0;
color: var(--text-primary);
font-size: 15px;
line-height: 1.75;
text-align: left;
overflow-wrap: break-word;
}
.system-message-card__content :deep(*) {
max-width: 100%;
}
.system-message-card__content :deep(p),
.system-message-card__content :deep(ul),
.system-message-card__content :deep(ol),
.system-message-card__content :deep(blockquote),
.system-message-card__content :deep(pre),
.system-message-card__content :deep(table) {
margin: 0 0 12px;
}
.system-message-card__content :deep(p:last-child),
.system-message-card__content :deep(ul:last-child),
.system-message-card__content :deep(ol:last-child),
.system-message-card__content :deep(blockquote:last-child),
.system-message-card__content :deep(pre:last-child),
.system-message-card__content :deep(table:last-child) {
margin-bottom: 0;
}
.system-message-card__content :deep(ul),
.system-message-card__content :deep(ol) {
padding-left: 1.25em;
}
.system-message-card__content :deep(a) {
color: var(--theme-primary);
}
.system-message-card__content :deep(img) {
display: block;
max-width: 100%;
border-radius: 8px;
}
.system-message-card__content :deep(pre) {
overflow-x: auto;
padding: 10px 12px;
border-radius: 8px;
background: var(--theme-primary-soft);
}
.system-message-card__footer {
display: flex;
gap: 12px;
align-items: center;
justify-content: space-between;
padding: 18px 30px;
border-top: 1px solid var(--theme-border);
color: var(--text-secondary);
font-size: 13px;
background: var(--theme-card-bg);
}
.system-message-card--footer-end .system-message-card__footer {
justify-content: flex-end;
}
@media (max-width: 640px) {
.system-message-card {
border-radius: 8px;
}
.system-message-card__main,
.system-message-card__footer {
padding-left: 22px;
padding-right: 22px;
}
.system-message-card__title {
font-size: 18px;
}
.system-message-card__footer {
align-items: stretch;
flex-direction: column;
}
}
</style>
@@ -0,0 +1,76 @@
<template>
<span v-if="!displayText" class="empty-text">{{ emptyText }}</span>
<a-tooltip v-else :title="displayText" placement="topLeft">
<div class="ellipsis-text" :class="lineClass">
{{ displayText }}
</div>
</a-tooltip>
</template>
<script setup lang="ts">
/**
* TableEllipsisText page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed } from 'vue'
/**
* Purpose: props supports TableEllipsisText.vue by holding or executing the props 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 props = withDefaults(defineProps<{
text?: string | number | null
lines?: 1 | 2 | 3
emptyText?: string
}>(), {
lines: 1,
emptyText: '--'
})
/** displayText is a reactive state variable used by the template and event handlers. */
const displayText = computed(() => {
if (props.text === undefined || props.text === null) {
return ''
}
const value = String(props.text).trim()
return value
})
/** lineClass is a reactive state variable used by the template and event handlers. */
const lineClass = computed(() => {
return props.lines > 1 ? `lines-${props.lines}` : ''
})
</script>
<style scoped>
.ellipsis-text {
display: inline-block;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
line-height: 1.5;
vertical-align: bottom;
}
.lines-2,
.lines-3 {
display: -webkit-box;
-webkit-box-orient: vertical;
white-space: normal;
word-break: normal;
overflow-wrap: normal;
}
.lines-2 {
-webkit-line-clamp: 2;
}
.lines-3 {
-webkit-line-clamp: 3;
}
.empty-text {
color: var(--text-secondary);
}
</style>
@@ -0,0 +1,274 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createApp } from 'vue'
import { useGlobalConfirmEnter } from './useConfirmEnter'
/**
* Purpose: visibleRects supports useConfirmEnter.test.ts by holding or executing the visible rects 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 visibleRects = [{
bottom: 100,
height: 100,
left: 0,
right: 100,
top: 0,
width: 100,
x: 0,
y: 0,
toJSON: () => ({})
}] as DOMRect[]
/**
* Purpose: makeVisible supports useConfirmEnter.test.ts by holding or executing the make visible 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 makeVisible = (element: HTMLElement) => {
vi.spyOn(element, 'getClientRects').mockReturnValue(visibleRects as unknown as DOMRectList)
}
/**
* Purpose: setDesktopViewport supports useConfirmEnter.test.ts by holding or executing the set desktop viewport 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 setDesktopViewport = () => {
Object.defineProperty(window, 'innerWidth', {
configurable: true,
value: 1280
})
window.matchMedia = vi.fn().mockImplementation((query: string) => ({
matches: query === '(pointer: coarse)' ? false : false,
media: query,
onchange: null,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
addListener: vi.fn(),
removeListener: vi.fn(),
dispatchEvent: vi.fn()
}))
}
/**
* Purpose: setMobileViewport supports useConfirmEnter.test.ts by holding or executing the set mobile viewport 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 setMobileViewport = () => {
Object.defineProperty(window, 'innerWidth', {
configurable: true,
value: 640
})
}
/**
* Purpose: setCoarsePointer supports useConfirmEnter.test.ts by holding or executing the set coarse pointer 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 setCoarsePointer = () => {
Object.defineProperty(window, 'innerWidth', {
configurable: true,
value: 1280
})
window.matchMedia = vi.fn().mockImplementation((query: string) => ({
matches: query === '(pointer: coarse)',
media: query,
onchange: null,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
addListener: vi.fn(),
removeListener: vi.fn(),
dispatchEvent: vi.fn()
}))
}
/**
* Purpose: mountGlobalConfirmEnter supports useConfirmEnter.test.ts by holding or executing the mount global confirm enter 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 mountGlobalConfirmEnter = () => {
const host = document.createElement('div')
document.body.appendChild(host)
const app = createApp({
setup() {
useGlobalConfirmEnter()
return () => null
}
})
app.mount(host)
return () => {
app.unmount()
host.remove()
}
}
/**
* Purpose: createModal supports useConfirmEnter.test.ts by holding or executing the create modal 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 createModal = ({
zIndex = 1000,
buttonClass = '',
disabled = false,
ariaDisabled = false,
footerClass = 'ant-modal-footer'
}: {
zIndex?: number
buttonClass?: string
disabled?: boolean
ariaDisabled?: boolean
footerClass?: 'ant-modal-footer' | 'ant-modal-confirm-btns'
} = {}) => {
const wrap = document.createElement('div')
wrap.className = 'ant-modal-wrap'
wrap.style.zIndex = String(zIndex)
const footer = document.createElement('div')
footer.className = footerClass
const button = document.createElement('button')
button.type = 'button'
button.className = `ant-btn ant-btn-primary ${buttonClass}`.trim()
button.disabled = disabled
if (ariaDisabled) {
button.setAttribute('aria-disabled', 'true')
}
const onClick = vi.fn()
const click = vi.spyOn(button, 'click')
button.addEventListener('click', onClick)
footer.appendChild(button)
wrap.appendChild(footer)
document.body.appendChild(wrap)
makeVisible(wrap)
makeVisible(button)
return { wrap, button, click, onClick }
}
/**
* Purpose: createKeyboardEvent supports useConfirmEnter.test.ts by holding or executing the create keyboard event 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 createKeyboardEvent = () => new KeyboardEvent('keydown', {
key: 'Enter',
bubbles: true,
cancelable: true
})
/**
* Purpose: pressEnter supports useConfirmEnter.test.ts by holding or executing the press enter 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 pressEnter = (target: EventTarget = document) => {
const event = createKeyboardEvent()
target.dispatchEvent(event)
return event
}
describe('useGlobalConfirmEnter', () => {
let unmount: (() => void) | undefined
beforeEach(() => {
document.body.innerHTML = ''
setDesktopViewport()
unmount = mountGlobalConfirmEnter()
})
afterEach(() => {
unmount?.()
document.body.innerHTML = ''
vi.restoreAllMocks()
})
it('clicks the visible top modal primary ok button when PC users press Enter', () => {
const { onClick } = createModal()
const event = pressEnter()
expect(onClick).toHaveBeenCalledTimes(1)
expect(event.defaultPrevented).toBe(true)
})
it('does not click the ok button when Enter starts inside textarea or contenteditable elements', () => {
const { onClick } = createModal()
const textarea = document.createElement('textarea')
document.body.appendChild(textarea)
pressEnter(textarea)
const editable = document.createElement('div')
editable.setAttribute('contenteditable', 'true')
document.body.appendChild(editable)
pressEnter(editable)
expect(onClick).not.toHaveBeenCalled()
})
it.each([
'ant-select-dropdown',
'ant-picker-dropdown',
'ant-dropdown',
'ant-popover'
])('does not click the ok button while %s is open', (dropdownClass) => {
const { onClick } = createModal()
const popup = document.createElement('div')
popup.className = dropdownClass
document.body.appendChild(popup)
pressEnter()
expect(onClick).not.toHaveBeenCalled()
})
it('does not click disabled or loading ok buttons', () => {
const disabledModal = createModal({ disabled: true })
pressEnter()
expect(disabledModal.click).not.toHaveBeenCalled()
expect(disabledModal.onClick).not.toHaveBeenCalled()
disabledModal.wrap.remove()
const ariaDisabledModal = createModal({ ariaDisabled: true })
pressEnter()
expect(ariaDisabledModal.click).not.toHaveBeenCalled()
expect(ariaDisabledModal.onClick).not.toHaveBeenCalled()
ariaDisabledModal.wrap.remove()
const loadingModal = createModal({ buttonClass: 'ant-btn-loading' })
pressEnter()
expect(loadingModal.click).not.toHaveBeenCalled()
expect(loadingModal.onClick).not.toHaveBeenCalled()
})
it('does not click the ok button on mobile width or coarse pointer devices', () => {
const mobileModal = createModal()
setMobileViewport()
pressEnter()
expect(mobileModal.onClick).not.toHaveBeenCalled()
mobileModal.wrap.remove()
const coarsePointerModal = createModal()
setCoarsePointer()
pressEnter()
expect(coarsePointerModal.onClick).not.toHaveBeenCalled()
})
it('clicks only the z-index and DOM-top modal when multiple modals are visible', () => {
const firstModal = createModal({ zIndex: 1000 })
const secondModal = createModal({ zIndex: 1000 })
const topZIndexModal = createModal({ zIndex: 1200 })
pressEnter()
expect(firstModal.onClick).not.toHaveBeenCalled()
expect(secondModal.onClick).not.toHaveBeenCalled()
expect(topZIndexModal.onClick).toHaveBeenCalledTimes(1)
topZIndexModal.wrap.remove()
pressEnter()
expect(firstModal.onClick).not.toHaveBeenCalled()
expect(secondModal.onClick).toHaveBeenCalledTimes(1)
})
})
@@ -0,0 +1,231 @@
/**
* Purpose: ComputedRef supports useConfirmEnter.ts by holding or executing the computed ref 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 { computed, onBeforeUnmount, onMounted, type ComputedRef } from 'vue'
/**
* Purpose: UseConfirmEnterOptions supports useConfirmEnter.ts by holding or executing the use confirm enter options page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
interface UseConfirmEnterOptions {
enabled: ComputedRef<boolean>
onConfirm: (event: KeyboardEvent) => void
isConfirmDisabled?: () => boolean
isTopLayer?: () => boolean
}
/**
* Purpose: CONFIRM_ENTER_DISABLED_CLASS supports useConfirmEnter.ts by holding or executing the confirm enter disabled class 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.
*/
export const CONFIRM_ENTER_DISABLED_CLASS = 'confirm-enter-disabled'
/**
* Purpose: DESKTOP_MIN_WIDTH supports useConfirmEnter.ts by holding or executing the desktop min width 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 DESKTOP_MIN_WIDTH = 960
/**
* Purpose: isEditableTarget supports useConfirmEnter.ts by holding or executing the is editable target 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 isEditableTarget = (target: EventTarget | null) => {
if (!(target instanceof HTMLElement)) {
return false
}
if (target.isContentEditable) {
return true
}
return target.tagName.toLowerCase() === 'textarea' || Boolean(target.closest('[contenteditable="true"]'))
}
/**
* Purpose: hasOpenPickerOrDropdown supports useConfirmEnter.ts by holding or executing the has open picker or dropdown 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 hasOpenPickerOrDropdown = () => {
return Boolean(document.querySelector([
'.ant-select-dropdown:not(.ant-select-dropdown-hidden)',
'.ant-picker-dropdown:not(.ant-picker-dropdown-hidden)',
'.ant-cascader-dropdown:not(.ant-cascader-dropdown-hidden)',
'.ant-dropdown:not(.ant-dropdown-hidden)',
'.ant-popover:not(.ant-popover-hidden)'
].join(',')))
}
/**
* Purpose: isDesktopViewport supports useConfirmEnter.ts by holding or executing the is desktop viewport 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 isDesktopViewport = () => {
if (typeof window === 'undefined') {
return false
}
const coarsePointer = window.matchMedia?.('(pointer: coarse)').matches ?? false
return window.innerWidth > DESKTOP_MIN_WIDTH && !coarsePointer
}
/**
* Purpose: isVisibleElement supports useConfirmEnter.ts by holding or executing the is visible element 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 isVisibleElement = (element: Element) => {
if (!(element instanceof HTMLElement)) {
return false
}
const style = window.getComputedStyle(element)
return style.display !== 'none'
&& style.visibility !== 'hidden'
&& style.opacity !== '0'
&& element.getClientRects().length > 0
}
/**
* Purpose: isDisabledButton supports useConfirmEnter.ts by holding or executing the is disabled button 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 isDisabledButton = (button: HTMLButtonElement) => {
return button.disabled
|| button.getAttribute('aria-disabled') === 'true'
|| button.classList.contains('ant-btn-loading')
|| button.classList.contains('ant-btn-disabled')
}
/**
* Purpose: getTopModalWrap supports useConfirmEnter.ts by holding or executing the get top modal wrap 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 getTopModalWrap = () => {
const modals = Array.from(document.querySelectorAll<HTMLElement>('.ant-modal-wrap'))
.filter(isVisibleElement)
if (!modals.length) {
return null
}
const sortedModals = modals
.map((modal, index) => {
const zIndex = Number.parseInt(window.getComputedStyle(modal).zIndex || '0', 10)
return {
modal,
index,
zIndex: Number.isNaN(zIndex) ? 0 : zIndex
}
})
.sort((left, right) => left.zIndex - right.zIndex || left.index - right.index)
return sortedModals[sortedModals.length - 1]?.modal ?? null
}
/**
* Purpose: getTopModalConfirmButton supports useConfirmEnter.ts by holding or executing the get top modal confirm button 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 getTopModalConfirmButton = () => {
const topModal = getTopModalWrap()
if (!topModal || topModal.classList.contains(CONFIRM_ENTER_DISABLED_CLASS)) {
return null
}
const button = topModal.querySelector<HTMLButtonElement>([
'.ant-modal-confirm-btns .ant-btn-primary',
'.ant-modal-footer .ant-btn-primary'
].join(','))
if (!button || !isVisibleElement(button) || isDisabledButton(button)) {
return null
}
return button
}
/**
* Purpose: useConfirmEnter supports useConfirmEnter.ts by holding or executing the use confirm enter 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.
*/
export const useConfirmEnter = ({
enabled,
onConfirm,
isConfirmDisabled,
isTopLayer
}: UseConfirmEnterOptions) => {
const canConfirm = computed(() => (
enabled.value
&& !(isConfirmDisabled?.() ?? false)
&& (isTopLayer?.() ?? true)
))
const handleKeydown = (event: KeyboardEvent) => {
if (
event.key !== 'Enter'
|| event.defaultPrevented
|| event.shiftKey
|| event.ctrlKey
|| event.altKey
|| event.metaKey
|| event.isComposing
|| !canConfirm.value
|| isEditableTarget(event.target)
|| hasOpenPickerOrDropdown()
) {
return
}
event.preventDefault()
onConfirm(event)
}
onMounted(() => {
document.addEventListener('keydown', handleKeydown)
})
onBeforeUnmount(() => {
document.removeEventListener('keydown', handleKeydown)
})
}
/**
* Purpose: useGlobalConfirmEnter supports useConfirmEnter.ts by holding or executing the use global confirm enter 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.
*/
export const useGlobalConfirmEnter = () => {
const handleKeydown = (event: KeyboardEvent) => {
if (
event.key !== 'Enter'
|| event.defaultPrevented
|| event.shiftKey
|| event.ctrlKey
|| event.altKey
|| event.metaKey
|| event.isComposing
|| (event as KeyboardEvent & { keyCode?: number }).keyCode === 229
|| !isDesktopViewport()
|| isEditableTarget(event.target)
|| hasOpenPickerOrDropdown()
) {
return
}
const confirmButton = getTopModalConfirmButton()
if (!confirmButton) {
return
}
event.preventDefault()
event.stopImmediatePropagation()
confirmButton.click()
}
onMounted(() => {
document.addEventListener('keydown', handleKeydown)
})
onBeforeUnmount(() => {
document.removeEventListener('keydown', handleKeydown)
})
}
@@ -0,0 +1,71 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('@/api/file', () => ({
fileApi: {
getSignedUrl: vi.fn()
}
}))
vi.mock('@/api/shop', () => ({
shopApi: {
getShopById: vi.fn()
}
}))
import { shopApi } from '@/api/shop'
import { DEFAULT_SHOP_THEME } from '@/utils/shop-theme'
import { useShopTheme } from './useShopTheme'
describe('useShopTheme', () => {
beforeEach(() => {
localStorage.clear()
sessionStorage.clear()
vi.clearAllMocks()
document.documentElement.removeAttribute('style')
})
it('uses the first preset as the default visible theme', async () => {
const { resetShopTheme } = useShopTheme()
resetShopTheme()
expect(DEFAULT_SHOP_THEME.primaryColor).toBe('#E8B4B8')
expect(DEFAULT_SHOP_THEME.secondaryColor).toBe('#C5A059')
expect(DEFAULT_SHOP_THEME.accentColor).toBe('#4A443F')
expect(DEFAULT_SHOP_THEME.pageBgColor).toBe('#FDFBF9')
expect(DEFAULT_SHOP_THEME.cardBgColor).toBe('#FFFFFF')
expect(document.documentElement.style.getPropertyValue('--theme-primary')).toBe('#E8B4B8')
expect(document.documentElement.style.getPropertyValue('--theme-secondary')).toBe('#C5A059')
expect(document.documentElement.style.getPropertyValue('--theme-neutral')).toBe('#4A443F')
expect(document.documentElement.style.getPropertyValue('--theme-tertiary')).toBe('#FDFBF9')
})
it('refreshes the customer theme from the cached shop context', async () => {
localStorage.setItem('accessToken', 'customer-token')
localStorage.setItem('userInfo', JSON.stringify({ shopId: 42 }))
vi.mocked(shopApi.getShopById).mockResolvedValue({
themePrimaryColor: '#123456',
themeSecondaryColor: '#ABCDEF',
themeAccentColor: '#345678',
themePageBgColor: '#F7FAFC',
themeCardBgColor: '#FFFFFF'
} as never)
const { refreshShopTheme } = useShopTheme()
await refreshShopTheme({ mode: 'customer' })
expect(shopApi.getShopById).toHaveBeenCalledWith('42')
expect(document.documentElement.style.getPropertyValue('--theme-primary')).toBe('#123456')
expect(document.documentElement.style.getPropertyValue('--theme-secondary')).toBe('#ABCDEF')
})
it('keeps the default theme for login pages without a shop context', async () => {
const { refreshShopTheme } = useShopTheme()
await refreshShopTheme({ mode: 'customer' })
expect(shopApi.getShopById).not.toHaveBeenCalled()
expect(document.documentElement.style.getPropertyValue('--theme-primary')).toBe('#E8B4B8')
})
})
@@ -0,0 +1,185 @@
import { readonly, shallowRef } from 'vue'
import { fileApi } from '@/api/file'
/**
* Purpose: ShopVO supports useShopTheme.ts by holding or executing the shop vo 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 { shopApi, type ShopVO } from '@/api/shop'
import {
applyShopTheme,
DEFAULT_SHOP_THEME,
resolveShopTheme,
SHOP_THEME_CHANGED_EVENT,
type ResolvedShopTheme
} from '@/utils/shop-theme'
type ShopThemeMode = 'auto' | 'customer'
export interface RefreshShopThemeOptions {
mode?: ShopThemeMode
shopId?: string | number | null
}
/**
* Purpose: currentTheme supports useShopTheme.ts by holding or executing the current 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 currentTheme = shallowRef<ResolvedShopTheme>(DEFAULT_SHOP_THEME)
let cleanupThemeSync: (() => void) | undefined
/**
* Purpose: refreshSequence supports useShopTheme.ts by holding or executing the refresh sequence page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let refreshSequence = 0
applyShopTheme(DEFAULT_SHOP_THEME)
/**
* Purpose: useShopTheme supports useShopTheme.ts by holding or executing the use shop theme 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.
*/
export function useShopTheme() {
return {
currentTheme: readonly(currentTheme),
refreshShopTheme,
resetShopTheme,
setupShopThemeSync
}
}
/**
* Purpose: refreshShopTheme supports useShopTheme.ts by holding or executing the refresh shop theme 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.
*/
async function refreshShopTheme(options: RefreshShopThemeOptions = {}) {
const mode = resolveThemeMode(options.mode)
const token = readToken(mode)
const userInfo = readStoredUserInfo(mode)
const shopId = options.shopId === undefined ? userInfo?.shopId : options.shopId
if (!token || !shopId) {
resetShopTheme()
return
}
const sequence = ++refreshSequence
try {
const shop = await shopApi.getShopById(String(shopId))
if (sequence !== refreshSequence) {
return
}
await applyThemeFromShop(shop)
} catch {
if (sequence === refreshSequence) {
resetShopTheme()
}
}
}
/**
* Purpose: resetShopTheme supports useShopTheme.ts by holding or executing the reset shop theme 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 resetShopTheme() {
refreshSequence += 1
currentTheme.value = DEFAULT_SHOP_THEME
applyShopTheme(DEFAULT_SHOP_THEME)
}
/**
* Purpose: setupShopThemeSync supports useShopTheme.ts by holding or executing the setup shop theme sync 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 setupShopThemeSync() {
if (cleanupThemeSync || typeof window === 'undefined') {
return cleanupThemeSync || (() => {})
}
const handleThemeEvent = () => {
void refreshShopTheme()
}
const handleStorage = (event: StorageEvent) => {
if ([
'accessToken',
'userInfo',
'refreshToken',
].includes(event.key || '')) {
void refreshShopTheme()
}
}
window.addEventListener(SHOP_THEME_CHANGED_EVENT, handleThemeEvent)
window.addEventListener('storage', handleStorage)
window.addEventListener('focus', handleThemeEvent)
cleanupThemeSync = () => {
window.removeEventListener(SHOP_THEME_CHANGED_EVENT, handleThemeEvent)
window.removeEventListener('storage', handleStorage)
window.removeEventListener('focus', handleThemeEvent)
cleanupThemeSync = undefined
}
return cleanupThemeSync
}
/**
* Purpose: applyThemeFromShop supports useShopTheme.ts by holding or executing the apply theme from shop 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.
*/
async function applyThemeFromShop(shop: ShopVO) {
const theme = resolveShopTheme(shop)
currentTheme.value = theme
const backgroundImageUrl = await resolveBackgroundImageUrl(theme.backgroundImageFileId)
applyShopTheme(theme, backgroundImageUrl)
}
/**
* Purpose: resolveBackgroundImageUrl supports useShopTheme.ts by holding or executing the resolve background image url 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.
*/
async function resolveBackgroundImageUrl(fileId?: string) {
if (!fileId) {
return null
}
try {
return await fileApi.getSignedUrl(fileId, 120) as unknown as string
} catch {
return null
}
}
/**
* Purpose: readToken supports useShopTheme.ts by holding or executing the read token 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 resolveThemeMode(mode: ShopThemeMode = 'auto'): Exclude<ShopThemeMode, 'auto'> {
if (mode !== 'auto') {
return mode
}
return 'customer'
}
function readToken(_mode: Exclude<ShopThemeMode, 'auto'>) {
if (typeof window === 'undefined') {
return ''
}
return localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken') || ''
}
/**
* Purpose: readStoredUserInfo supports useShopTheme.ts by holding or executing the read stored user info 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 readStoredUserInfo(_mode: Exclude<ShopThemeMode, 'auto'>): { shopId?: string | number } | null {
if (typeof window === 'undefined') {
return null
}
const raw = localStorage.getItem('userInfo')
if (!raw) {
return null
}
try {
return JSON.parse(raw) as { shopId?: string | number }
} catch {
return null
}
}
@@ -0,0 +1,58 @@
import zhCN from 'ant-design-vue/es/locale/zh_CN'
/**
* Purpose: baseCalendar supports antdv-locale.ts by holding or executing the base calendar 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 baseCalendar = (zhCN.Calendar || { lang: {} }) as any
/**
* Purpose: baseDatePicker supports antdv-locale.ts by holding or executing the base date picker 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 baseDatePicker = (zhCN.DatePicker || { lang: {}, timePickerLocale: {} }) as any
/**
* Purpose: baseTimePicker supports antdv-locale.ts by holding or executing the base time picker 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 baseTimePicker = (zhCN.TimePicker || {}) as any
const antdLocale: any = {
...zhCN,
Modal: {
...zhCN.Modal,
okText: '确认',
cancelText: zhCN.Modal?.cancelText || '取消',
justOkText: zhCN.Modal?.justOkText || '知道了'
},
Popconfirm: {
...zhCN.Popconfirm,
okText: '确认',
cancelText: zhCN.Popconfirm?.cancelText || '取消'
},
Calendar: {
...baseCalendar,
lang: {
...baseCalendar.lang,
ok: '确认',
now: '现在时间'
}
},
DatePicker: {
...baseDatePicker,
lang: {
...baseDatePicker.lang,
ok: '确认',
now: '现在时间'
},
timePickerLocale: {
...baseDatePicker.timePickerLocale,
now: '现在时间'
}
},
TimePicker: {
...baseTimePicker,
now: '现在时间'
}
}
export default antdLocale
+29
View File
@@ -0,0 +1,29 @@
/**
* Purpose: normalizeBaseUrl supports api.ts by holding or executing the normalize base url 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 normalizeBaseUrl(value: string | undefined, fallbackValue: string) {
const target = String(value || fallbackValue).trim()
return target.replace(/\/+$/, '')
}
/**
* Purpose: DEFAULT_API_BASE_URL supports api.ts by holding or executing the default api base url 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 DEFAULT_API_BASE_URL = import.meta.env.DEV ? '/api' : 'https://yunail.art/api'
/**
* Purpose: API_CONFIG supports api.ts by holding or executing the api config 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.
*/
export const API_CONFIG = {
mode: import.meta.env.MODE,
apiBaseUrl: normalizeBaseUrl(import.meta.env.VITE_API_BASE_URL, DEFAULT_API_BASE_URL),
}
/**
* Purpose: API_BASE_URL supports api.ts by holding or executing the api base url 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.
*/
export const API_BASE_URL = API_CONFIG.apiBaseUrl
+11
View File
@@ -0,0 +1,11 @@
function normalizeBrandValue(value: string | undefined, fallbackValue: string): string {
const target = String(value || fallbackValue).trim()
return target || fallbackValue
}
export const BRAND_CONFIG = {
appName: normalizeBrandValue(import.meta.env.VITE_APP_NAME, '甲屿设计师'),
appNameEn: normalizeBrandValue(import.meta.env.VITE_APP_NAME_EN, 'Jiayu Designer'),
appTitle: normalizeBrandValue(import.meta.env.VITE_APP_TITLE, '甲屿设计师'),
appShortName: normalizeBrandValue(import.meta.env.VITE_APP_SHORT_NAME, 'YN')
}
@@ -0,0 +1,15 @@
/**
* Purpose: DEFAULT_AVATAR supports index.ts by holding or executing the default avatar 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.
*/
export const DEFAULT_AVATAR = 'https://api.dicebear.com/7.x/avataaars/svg?seed=default'
/**
* Purpose: DEFAULT_PRODUCT_IMAGE supports index.ts by holding or executing the default product image 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.
*/
export const DEFAULT_PRODUCT_IMAGE = '/assets/images/default-product.png'
/**
* Purpose: DEFAULT_SHOP_IMAGE supports index.ts by holding or executing the default shop image 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.
*/
export const DEFAULT_SHOP_IMAGE = '/assets/images/default-shop.png'
+25
View File
@@ -0,0 +1,25 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import 'ant-design-vue/dist/reset.css'
import './style.css'
import App from './App.vue'
import router from './router'
import { BRAND_CONFIG } from './config/brand'
document.title = BRAND_CONFIG.appTitle
/**
* Purpose: app supports main.ts by holding or executing the app 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 app = createApp(App)
/**
* Purpose: pinia supports main.ts by holding or executing the pinia 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 pinia = createPinia()
app.use(pinia)
app.use(router)
app.mount('#app')
+176
View File
@@ -0,0 +1,176 @@
import { createRouter, createWebHistory } from 'vue-router'
/**
* Purpose: router supports index.ts 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 = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'auth',
component: () => import('../views/AuthView.vue'),
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
},
{
path: '/home',
name: 'home',
component: () => import('../views/HomeView.vue'),
meta: { requiresAuth: false, isAdmin: false }
},
{
path: '/products',
name: 'products',
component: () => import('../views/ProductListView.vue'),
meta: { requiresAuth: false, isAdmin: false }
},
{
path: '/product/:id',
name: 'product-detail',
component: () => import('../views/ProductDetailView.vue'),
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
},
{
path: '/cart',
name: 'cart',
component: () => import('../views/CartView.vue'),
meta: { requiresAuth: true, isAdmin: false }
},
{
path: '/profile',
name: 'profile',
component: () => import('../views/ProfileView.vue'),
meta: { requiresAuth: true, isAdmin: false }
},
{
path: '/shop/:id',
name: 'shop-detail',
component: () => import('../views/ShopDetailView.vue'),
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
},
{
path: '/shop/:shopId/artists',
name: 'shop-artists',
component: () => import('../views/ArtistListView.vue'),
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
},
{
path: '/artist/:id',
name: 'artist-profile',
component: () => import('../views/ArtistProfileView.vue'),
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
},
{
path: '/wishlist',
name: 'wishlist',
component: () => import('../views/WishlistView.vue'),
meta: { requiresAuth: true, isAdmin: false }
},
{
path: '/orders',
name: 'orders',
component: () => import('../views/OrderView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/orders/:id',
name: 'order-detail',
component: () => import('../views/OrderDetailView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/after-sales',
name: 'after-sales',
component: () => import('../views/AfterSalesView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/after-sale/apply',
name: 'after-sale-apply',
component: () => import('../views/AfterSaleApplyView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/service-progress',
name: 'service-progress',
component: () => import('../views/ServiceProgressView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/help',
name: 'help',
component: () => import('../views/HelpView.vue'),
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
},
{
path: '/settings',
name: 'settings',
component: () => import('../views/SettingsView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/settings/account',
name: 'account-settings',
component: () => import('../views/AccountSettingsView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/settings/password',
name: 'password-settings',
component: () => import('../views/PasswordSettingsView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/coupons',
name: 'coupons',
component: () => import('../views/CouponView.vue'),
meta: { requiresAuth: true, isAdmin: false, hideNav: true }
},
{
path: '/vip-center',
name: 'vip-center',
component: () => import('../views/VipCenterView.vue'),
meta: { requiresAuth: true, isAdmin: false, hideNav: true }
},
{
path: '/notifications',
name: 'notifications',
component: () => import('../views/NotificationsView.vue'),
meta: { requiresAuth: true, isAdmin: false, hideNav: true }
},
{
path: '/:pathMatch(.*)*',
name: 'not-found',
component: () => import('../views/NotFoundView.vue'),
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
}
]
})
router.beforeEach(async (to) => {
const requiresAuth = Boolean(to.meta.requiresAuth)
const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
if (requiresAuth && !token) {
return '/'
}
if (to.path === '/' && token) {
return '/home'
}
if (requiresAuth && token) {
const userInfo = localStorage.getItem('userInfo')
if (!userInfo) {
localStorage.removeItem('accessToken')
localStorage.removeItem('refreshToken')
sessionStorage.removeItem('accessToken')
return '/'
}
}
return true
})
export default router
+334
View File
@@ -0,0 +1,334 @@
:root {
--primary-color: #E8B4B8;
--theme-primary: #E8B4B8;
--theme-secondary: #C5A059;
--theme-accent: #4A443F;
--theme-neutral: #4A443F;
--theme-tertiary: #FDFBF9;
--theme-primary-action: #766361;
--theme-primary-soft: #FAEFF0;
--theme-secondary-soft: #EADCC2;
--theme-page-bg: #FDFBF9;
--theme-card-bg: #FFFFFF;
--theme-border: #F9EAEC;
--theme-gradient: linear-gradient(135deg, #766361 0%, #C5A059 100%);
--theme-gradient-soft: linear-gradient(145deg, #FFFFFF 0%, #EADCC2 58%, #F5E0E0 100%);
--theme-button-shadow: 0 12px 28px rgba(232, 180, 184, 0.26);
--theme-focus-shadow: 0 0 0 3px rgba(232, 180, 184, 0.2);
--theme-background-image: none;
--bg-color: #FDFBF9;
--secondary-bg-color: #EADCC2;
--surface-color: #FFFFFF;
--text-primary: #4A443F;
--text-secondary: #6B6662;
--border-radius-base: 10px;
--border-radius-large: 30px;
--frontend-min-safe-width: 320px;
--frontend-page-max-width: 430px;
--frontend-content-max-width: 1120px;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
img,
video,
canvas,
svg {
max-width: 100%;
}
html,
body {
min-width: var(--frontend-min-safe-width);
overflow-x: hidden;
}
body {
background:
radial-gradient(circle at 50% 0%, color-mix(in srgb, var(--theme-primary) 24%, transparent), transparent 34%),
linear-gradient(180deg, var(--theme-tertiary), color-mix(in srgb, var(--theme-secondary) 12%, var(--theme-tertiary)));
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
color: var(--text-primary);
}
.mobile-container {
width: 100%;
min-width: var(--frontend-min-safe-width);
max-width: none;
margin: 0 auto;
min-height: 100vh;
background:
radial-gradient(circle at 82% 2%, color-mix(in srgb, var(--theme-primary) 30%, transparent), transparent 28%),
linear-gradient(180deg, color-mix(in srgb, var(--theme-card-bg) 74%, transparent), color-mix(in srgb, var(--theme-page-bg) 98%, var(--theme-card-bg))),
var(--theme-background-image),
var(--bg-color);
background-size: auto, cover, cover, auto;
background-position: center top;
position: relative;
overflow-x: hidden;
}
.fingertip-designer-page {
min-height: 100vh;
padding: 18px 18px calc(88px + env(safe-area-inset-bottom, 0px));
color: var(--text-primary);
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.7), rgba(253, 251, 249, 0.96)),
var(--theme-background-image),
var(--theme-page-bg);
background-size: cover, cover, auto;
background-position: center top;
}
.fingertip-designer-page--no-nav {
padding-bottom: calc(28px + env(safe-area-inset-bottom, 0px));
}
.fingertip-designer-section {
margin-top: 22px;
}
.fingertip-designer-section-head {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 16px;
margin-bottom: 14px;
}
.fingertip-designer-kicker {
display: block;
color: var(--theme-primary-action);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.fingertip-designer-title {
display: block;
color: var(--text-primary);
font-size: 21px;
font-weight: 760;
line-height: 1.18;
}
.fingertip-designer-subtitle {
display: block;
margin-top: 6px;
color: var(--text-secondary);
font-size: 13px;
line-height: 1.65;
}
.fingertip-designer-glass-card {
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.9);
border-radius: 24px;
background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent);
box-shadow: 0 20px 44px rgba(74, 68, 63, 0.1);
backdrop-filter: blur(16px);
}
.fingertip-designer-icon-button {
display: inline-flex;
align-items: center;
justify-content: center;
width: 34px;
height: 34px;
border: 0;
border-radius: 999px;
color: var(--theme-neutral);
background: color-mix(in srgb, var(--theme-card-bg) 78%, transparent);
box-shadow: 0 10px 24px color-mix(in srgb, var(--theme-neutral) 8%, transparent);
cursor: pointer;
backdrop-filter: blur(14px);
}
.fingertip-designer-icon-button:active {
transform: scale(0.96);
}
.app-container--phone-shell :where(.nav-button, .icon-btn, .back-btn, .fingertip-designer-icon-button) :where(.anticon),
.app-container--phone-shell :where(.header, .shop-topbar, .detail-header, .artist-topbar, .artist-list-topbar, .auth-topbar, .not-found-topbar, .cart-topbar, .vip-header) :where(.ant-btn .anticon, button .anticon) {
font-size: 21px !important;
line-height: 1;
}
.app-container--phone-shell :where(.bottom-nav .nav-icon) {
width: 40px;
height: 34px;
}
.app-container--phone-shell :where(.bottom-nav .nav-icon .anticon) {
font-size: 25px !important;
line-height: 1;
}
.app-container--phone-shell :where(.nav-button, .icon-btn, .back-btn, .fingertip-designer-icon-button, .bottom-nav .nav-icon) :where(.anticon svg) {
display: block;
width: 1em;
height: 1em;
}
.fingertip-designer-page-titlebar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 12px 18px 8px;
}
.fingertip-designer-page-titlebar__title {
min-width: 0;
flex: 1;
text-align: center;
color: var(--text-primary);
font-size: 16px;
font-weight: 780;
}
.fingertip-designer-status-chip {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 26px;
padding: 0 12px;
border: 1px solid var(--theme-border);
border-radius: 999px;
color: var(--theme-primary-action);
background: var(--theme-primary-soft);
font-size: 12px;
font-weight: 700;
white-space: nowrap;
}
.fingertip-designer-bottom-action {
position: sticky;
bottom: 0;
z-index: 20;
display: flex;
gap: 12px;
margin: 24px -18px -18px;
padding: 14px 18px calc(14px + env(safe-area-inset-bottom, 0px));
border-top: 1px solid var(--theme-border);
background: color-mix(in srgb, var(--theme-card-bg) 90%, transparent);
backdrop-filter: blur(18px);
}
.app-container--phone-shell :where(.ant-card) {
border-color: var(--theme-border);
border-radius: 24px;
background: rgba(255, 255, 255, 0.86);
box-shadow: 0 18px 42px rgba(74, 68, 63, 0.09);
backdrop-filter: blur(14px);
}
.app-container--phone-shell :where(.ant-btn-primary) {
border-color: transparent;
background: var(--theme-gradient);
box-shadow: var(--theme-button-shadow);
}
.app-container--phone-shell :where(.ant-btn-primary:hover, .ant-btn-primary:focus) {
border-color: transparent;
background: linear-gradient(135deg, var(--theme-primary-action), var(--theme-secondary));
}
.app-container--phone-shell :where(.ant-input, .ant-input-affix-wrapper, .ant-select-selector, .ant-picker) {
border-color: var(--theme-border);
border-radius: 14px;
background: color-mix(in srgb, var(--theme-card-bg) 86%, transparent);
}
.app-container--phone-shell :where(.ant-input:hover, .ant-input:focus, .ant-input-affix-wrapper:hover, .ant-input-affix-wrapper-focused, .ant-picker:hover, .ant-picker-focused) {
border-color: var(--theme-primary);
box-shadow: var(--theme-focus-shadow);
}
.app-container--phone-shell :where(.ant-tag) {
border-radius: 999px;
}
.app-container--phone-shell .header {
background: color-mix(in srgb, var(--theme-card-bg) 90%, transparent);
border-bottom-color: var(--theme-border);
backdrop-filter: blur(18px);
}
.fingertip-designer-phone-frame {
width: 100%;
min-width: var(--frontend-min-safe-width);
min-height: 100vh;
margin: 0 auto;
background: var(--theme-page-bg);
position: relative;
}
.fingertip-designer-phone-frame--hidden-nav {
min-height: 100vh;
}
@media (min-width: 768px) {
body {
background:
radial-gradient(circle at 18% 8%, rgba(254, 212, 136, 0.28), transparent 30%),
radial-gradient(circle at 82% 12%, rgba(232, 180, 184, 0.24), transparent 34%),
var(--secondary-bg-color);
}
.app-container--phone-shell {
align-items: center;
padding: 0;
}
.mobile-container {
max-width: var(--frontend-page-max-width);
}
.fingertip-designer-phone-frame {
width: min(100%, var(--frontend-page-max-width));
min-height: 100vh;
margin: 0 auto;
overflow: clip;
border: 1px solid rgba(212, 194, 195, 0.72);
border-radius: 32px;
box-shadow: 0 28px 80px rgba(74, 68, 63, 0.14);
}
.fingertip-designer-phone-frame > .bottom-nav,
.fingertip-designer-phone-frame > .page-content .header,
.fingertip-designer-phone-frame > .page-content .header-bg,
.fingertip-designer-phone-frame > .page-content .gallery-header,
.fingertip-designer-phone-frame > .page-content .order-header {
left: 50%;
right: auto;
width: var(--frontend-page-max-width);
max-width: calc(100vw - 48px);
transform: translateX(-50%) translateZ(0);
}
.fingertip-designer-phone-frame > .page-content .header,
.fingertip-designer-phone-frame > .page-content .header-bg,
.fingertip-designer-phone-frame > .page-content .gallery-header,
.fingertip-designer-phone-frame > .page-content .order-header {
top: 0;
}
.fingertip-designer-phone-frame > .page-content .header,
.fingertip-designer-phone-frame > .page-content .gallery-header,
.fingertip-designer-phone-frame > .page-content .order-header {
border-top-left-radius: 32px;
border-top-right-radius: 32px;
}
.fingertip-designer-phone-frame > .bottom-nav {
bottom: 0;
border-bottom-right-radius: 32px;
border-bottom-left-radius: 32px;
}
}
@@ -0,0 +1,12 @@
.bottom-nav {
position: fixed;
bottom: 0;
width: 100%;
height: 60px;
background: white;
display: flex;
justify-content: space-around;
align-items: center;
box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
z-index: 1000;
}
+22
View File
@@ -0,0 +1,22 @@
/**
* Purpose: ACCOUNT_REGEX supports account.ts by holding or executing the account regex 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.
*/
export const ACCOUNT_REGEX = /^[A-Za-z0-9]+$/
/**
* Purpose: ACCOUNT_SANITIZE_REGEX supports account.ts by holding or executing the account sanitize regex 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 ACCOUNT_SANITIZE_REGEX = /[^A-Za-z0-9]/g
/**
* Purpose: ACCOUNT_RULE_MESSAGE supports account.ts by holding or executing the account rule message 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.
*/
export const ACCOUNT_RULE_MESSAGE = '账号只能包含字母和数字'
/**
* Purpose: sanitizeAccountInput supports account.ts by holding or executing the sanitize account input 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.
*/
export const sanitizeAccountInput = (value: string) => (value || '').replace(ACCOUNT_SANITIZE_REGEX, '')
@@ -0,0 +1,76 @@
/**
* Purpose: LoadingInstance supports action-loading.ts by holding or executing the loading instance 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 { ElLoading, type LoadingInstance } from 'element-plus'
import 'element-plus/es/components/loading/style/css'
/**
* Purpose: GlobalLoadingOptions supports action-loading.ts by holding or executing the global loading options page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface GlobalLoadingOptions {
text?: string
lock?: boolean
}
/**
* Purpose: activeLoadingCount supports action-loading.ts by holding or executing the active loading count page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let activeLoadingCount = 0
let loadingInstance: LoadingInstance | null = null
/**
* Purpose: openGlobalLoading supports action-loading.ts by holding or executing the open global loading 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 openGlobalLoading = (options?: GlobalLoadingOptions) => {
activeLoadingCount += 1
if (typeof window === 'undefined' || loadingInstance) {
return
}
loadingInstance = ElLoading.service({
lock: options?.lock ?? true,
text: options?.text ?? '\u52a0\u8f7d\u4e2d',
background: 'rgba(255, 255, 255, 0.72)'
})
}
/**
* Purpose: closeGlobalLoading supports action-loading.ts by holding or executing the close global loading 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 closeGlobalLoading = () => {
activeLoadingCount = Math.max(0, activeLoadingCount - 1)
if (activeLoadingCount > 0) {
return
}
loadingInstance?.close()
loadingInstance = null
}
/**
* Purpose: runWithGlobalLoading supports action-loading.ts by holding or executing the run with global loading 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.
*/
export const runWithGlobalLoading = async <T>(
task: (() => Promise<T>) | Promise<T>,
options?: GlobalLoadingOptions
) => {
openGlobalLoading(options)
try {
if (typeof task === 'function') {
return await task()
}
return await task
} finally {
closeGlobalLoading()
}
}
@@ -0,0 +1,19 @@
import { describe, expect, it } from 'vitest'
import { BUY_NOW_MODE, getBuyNowProductIdFromQuery, isBuyNowCartItem } from './buy-now'
describe('buy-now checkout mode', () => {
it('reads the target product id only when cart query is in buyNow mode', () => {
expect(getBuyNowProductIdFromQuery({ mode: BUY_NOW_MODE, productId: '1001' })).toBe('1001')
expect(getBuyNowProductIdFromQuery({ mode: 'cart', productId: '1001' })).toBe('')
})
it('uses the first query value when vue-router provides array values', () => {
expect(getBuyNowProductIdFromQuery({ mode: [BUY_NOW_MODE], productId: ['2002', '3003'] })).toBe('2002')
})
it('matches numeric and string product ids for cart selection', () => {
expect(isBuyNowCartItem(1001, '1001')).toBe(true)
expect(isBuyNowCartItem('1002', '1001')).toBe(false)
})
})
+15
View File
@@ -0,0 +1,15 @@
export const BUY_NOW_MODE = 'buyNow'
type QueryValue = string | string[] | null | undefined
const firstQueryValue = (value: QueryValue) => Array.isArray(value) ? value[0] : value
export const getBuyNowProductIdFromQuery = (query: Record<string, unknown>) => {
const mode = firstQueryValue(query.mode as QueryValue)
const productId = firstQueryValue(query.productId as QueryValue)
return mode === BUY_NOW_MODE && productId ? String(productId) : ''
}
export const isBuyNowCartItem = (itemProductId: unknown, buyNowProductId: string) => {
return Boolean(buyNowProductId) && String(itemProductId || '') === String(buyNowProductId)
}
@@ -0,0 +1,41 @@
import { cartApi } from '@/api/cart'
import { toOptionalIdString } from '@/utils/id'
/**
* Purpose: fetchCartProductIdSet supports cart-state.ts by holding or executing the fetch cart product id set 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.
*/
export const fetchCartProductIdSet = async () => {
try {
const response = await cartApi.getCartList() as unknown as Array<{ productId?: string | number }>
return new Set(
(Array.isArray(response) ? response : [])
.map(item => toOptionalIdString(item && item.productId))
.filter((id): id is string => Boolean(id))
)
} catch (error) {
return new Set<string>()
}
}
/**
* Purpose: hasCartProduct supports cart-state.ts by holding or executing the has cart product 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.
*/
export const hasCartProduct = (cartProductIdSet: Set<string>, productId: unknown) => {
const normalizedId = toOptionalIdString(productId)
return Boolean(normalizedId && cartProductIdSet.has(normalizedId))
}
/**
* Purpose: withAddedCartProduct supports cart-state.ts by holding or executing the with added cart product 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.
*/
export const withAddedCartProduct = (cartProductIdSet: Set<string>, productId: unknown) => {
const next = new Set(cartProductIdSet || [])
const normalizedId = toOptionalIdString(productId)
if (normalizedId) {
next.add(normalizedId)
}
return next
}
@@ -0,0 +1,84 @@
import { describe, expect, it, vi } from 'vitest'
import { createChunkUploadTask, type ChunkUploadApi } from './chunk-upload'
const createFile = (size: number) => new File([new Uint8Array(size)], 'large.png', {
type: 'image/png',
lastModified: 1
})
describe('chunk-upload', () => {
it('uploads chunks with the requested concurrency', async () => {
const releaseCallbacks: Array<() => void> = []
let activeUploads = 0
let maxActiveUploads = 0
const api: ChunkUploadApi<string> = {
initUpload: vi.fn().mockResolvedValue({
uploadId: 'upload-1',
chunkSize: 2,
totalChunks: 4,
uploadedChunks: []
}),
uploadChunk: vi.fn((_payload, config) => {
activeUploads += 1
maxActiveUploads = Math.max(maxActiveUploads, activeUploads)
config?.onUploadProgress?.({ loaded: 2, total: 2 } as never)
return new Promise(resolve => {
releaseCallbacks.push(() => {
activeUploads -= 1
resolve(true)
})
})
}),
completeUpload: vi.fn().mockResolvedValue('done'),
cancelUpload: vi.fn()
}
const task = createChunkUploadTask({
file: createFile(8),
scene: 'test-image',
concurrency: 3,
api
})
await vi.waitFor(() => expect(maxActiveUploads).toBe(3))
while (releaseCallbacks.length) {
releaseCallbacks.shift()?.()
await Promise.resolve()
}
await expect(task.promise).resolves.toMatchObject({
response: 'done',
uploadId: 'upload-1'
})
expect(api.uploadChunk).toHaveBeenCalledTimes(4)
expect(api.completeUpload).toHaveBeenCalledWith('upload-1')
})
it('skips already uploaded chunks', async () => {
const api: ChunkUploadApi<string> = {
initUpload: vi.fn().mockResolvedValue({
uploadId: 'upload-2',
chunkSize: 2,
totalChunks: 3,
uploadedChunks: [0, 2]
}),
uploadChunk: vi.fn().mockResolvedValue(true),
completeUpload: vi.fn().mockResolvedValue('done')
}
const task = createChunkUploadTask({
file: createFile(6),
scene: 'test-image',
concurrency: 3,
api
})
await expect(task.promise).resolves.toMatchObject({ response: 'done' })
expect(api.uploadChunk).toHaveBeenCalledTimes(1)
expect(api.uploadChunk).toHaveBeenCalledWith(
expect.objectContaining({ chunkIndex: 1 }),
expect.any(Object)
)
})
})
@@ -0,0 +1,197 @@
import type { AxiosProgressEvent } from 'axios'
export interface ChunkUploadSession {
uploadId: string
chunkSize: number
totalChunks: number
uploadedChunks: number[]
}
export interface ChunkUploadInitRequest {
fileName: string
fileSize: number
contentType: string
fileFingerprint: string
scene: string
}
export interface ChunkUploadApi<TResponse> {
initUpload: (payload: ChunkUploadInitRequest) => Promise<ChunkUploadSession>
uploadChunk: (
payload: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob },
config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void }
) => Promise<unknown>
completeUpload: (uploadId: string) => Promise<TResponse>
cancelUpload?: (uploadId: string) => Promise<unknown>
}
export interface ChunkUploadOptions<TResponse> {
file: File
scene: string
api: ChunkUploadApi<TResponse>
concurrency: number
preprocessFile?: (file: File) => Promise<File>
onProgress?: (percent: number) => void
}
export interface ChunkUploadResult<TResponse> {
response: TResponse
uploadId: string
processedFile: File
}
export interface ChunkUploadTask<TResponse> {
promise: Promise<ChunkUploadResult<TResponse>>
cancel: () => void
getUploadId: () => string
}
const computeFileFingerprint = async (file: File) => {
const fingerprintSeed = `${file.name}|${file.size}|${file.lastModified}|${file.type}`
if (!window.crypto?.subtle) {
return btoa(unescape(encodeURIComponent(fingerprintSeed)))
}
const buffer = new TextEncoder().encode(fingerprintSeed)
const hashBuffer = await window.crypto.subtle.digest('SHA-256', buffer)
const hashArray = Array.from(new Uint8Array(hashBuffer))
return hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('')
}
const getChunkSizeByIndex = (fileSize: number, chunkSize: number, chunkIndex: number) => {
const start = chunkIndex * chunkSize
const end = Math.min(start + chunkSize, fileSize)
return Math.max(end - start, 0)
}
const calculateUploadedBytes = (fileSize: number, chunkSize: number, uploadedChunks: number[]) =>
uploadedChunks.reduce((total, chunkIndex) => total + getChunkSizeByIndex(fileSize, chunkSize, chunkIndex), 0)
const normalizeConcurrency = (concurrency: number) => {
if (!Number.isFinite(concurrency) || concurrency < 1) {
return 1
}
return Math.floor(concurrency)
}
const createPendingChunkIndexes = (totalChunks: number, uploadedChunkSet: Set<number>) => {
const chunkIndexes: number[] = []
for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
if (!uploadedChunkSet.has(chunkIndex)) {
chunkIndexes.push(chunkIndex)
}
}
return chunkIndexes
}
export const createChunkUploadTask = <TResponse>(options: ChunkUploadOptions<TResponse>): ChunkUploadTask<TResponse> => {
const abortController = new AbortController()
let uploadId = ''
let cancelled = false
const cleanupCancelledSession = async () => {
if (uploadId && options.api.cancelUpload) {
await options.api.cancelUpload(uploadId).catch(() => undefined)
}
}
const promise = (async () => {
const processedFile = options.preprocessFile ? await options.preprocessFile(options.file) : options.file
const fileFingerprint = await computeFileFingerprint(processedFile)
const session = await options.api.initUpload({
fileName: processedFile.name,
fileSize: processedFile.size,
contentType: processedFile.type || 'application/octet-stream',
fileFingerprint,
scene: options.scene
})
uploadId = session.uploadId
if (cancelled) {
await cleanupCancelledSession()
throw new Error('上传已取消')
}
const uploadedChunkSet = new Set(session.uploadedChunks || [])
let uploadedBytes = calculateUploadedBytes(processedFile.size, session.chunkSize, Array.from(uploadedChunkSet))
const uploadingChunkBytes = new Map<number, number>()
const pendingChunkIndexes = createPendingChunkIndexes(session.totalChunks, uploadedChunkSet)
const concurrency = Math.min(normalizeConcurrency(options.concurrency), Math.max(pendingChunkIndexes.length, 1))
const emitProgress = (limit: number) => {
const inFlightBytes = Array.from(uploadingChunkBytes.values()).reduce((total, loaded) => total + loaded, 0)
const percent = ((uploadedBytes + inFlightBytes) / Math.max(processedFile.size, 1)) * 100
options.onProgress?.(Math.min(percent, limit))
}
options.onProgress?.(Math.min((uploadedBytes / Math.max(processedFile.size, 1)) * 100, 100))
let nextChunkIndexCursor = 0
const uploadNextChunk = async (): Promise<void> => {
const chunkIndex = pendingChunkIndexes[nextChunkIndexCursor]
nextChunkIndexCursor += 1
if (chunkIndex === undefined) {
return
}
if (cancelled) {
await cleanupCancelledSession()
throw new Error('上传已取消')
}
const start = chunkIndex * session.chunkSize
const end = Math.min(start + session.chunkSize, processedFile.size)
const chunk = processedFile.slice(start, end)
const chunkBytes = end - start
await options.api.uploadChunk(
{
uploadId: session.uploadId,
chunkIndex,
totalChunks: session.totalChunks,
chunk
},
{
signal: abortController.signal,
onUploadProgress: (event) => {
const loaded = Math.min(event.loaded || 0, chunkBytes)
uploadingChunkBytes.set(chunkIndex, loaded)
emitProgress(99.9)
}
}
)
uploadedChunkSet.add(chunkIndex)
uploadedBytes += chunkBytes
uploadingChunkBytes.delete(chunkIndex)
options.onProgress?.(Math.min((uploadedBytes / Math.max(processedFile.size, 1)) * 100, 99.9))
await uploadNextChunk()
}
await Promise.all(Array.from({ length: concurrency }, () => uploadNextChunk()))
if (cancelled) {
await cleanupCancelledSession()
throw new Error('上传已取消')
}
const response = await options.api.completeUpload(session.uploadId)
options.onProgress?.(100)
return {
response,
uploadId: session.uploadId,
processedFile
}
})()
return {
promise,
cancel: () => {
cancelled = true
abortController.abort()
if (uploadId && options.api.cancelUpload) {
void options.api.cancelUpload(uploadId).catch(() => undefined)
}
},
getUploadId: () => uploadId
}
}
@@ -0,0 +1,16 @@
import { describe, expect, it } from 'vitest'
import { buildRatingStars, normalizeCommentRating } from './comment-review'
describe('comment review helpers', () => {
it('normalizes comment ratings for display and submit', () => {
expect(normalizeCommentRating(undefined)).toBe(5)
expect(normalizeCommentRating(0)).toBe(1)
expect(normalizeCommentRating(6)).toBe(5)
expect(normalizeCommentRating('3')).toBe(3)
})
it('builds filled and empty star states from a rating', () => {
expect(buildRatingStars(3)).toEqual([true, true, true, false, false])
expect(buildRatingStars(5)).toEqual([true, true, true, true, true])
})
})
@@ -0,0 +1,12 @@
export const normalizeCommentRating = (value: unknown, fallback = 5) => {
const numeric = Number(value ?? fallback)
if (!Number.isFinite(numeric)) {
return fallback
}
return Math.min(5, Math.max(1, Math.round(numeric)))
}
export const buildRatingStars = (rating: unknown) => {
const normalized = normalizeCommentRating(rating)
return Array.from({ length: 5 }, (_, index) => index < normalized)
}
@@ -0,0 +1,70 @@
/**
* Purpose: DraftStorageMode supports form-draft.ts by holding or executing the draft storage mode 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.
*/
export type DraftStorageMode = 'local' | 'session'
/**
* Purpose: DraftRecord supports form-draft.ts by holding or executing the draft record page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface DraftRecord<T> {
savedAt: number
payload: T
}
/**
* Purpose: getStorage supports form-draft.ts by holding or executing the get storage 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 getStorage = (mode: DraftStorageMode) => (mode === 'session' ? window.sessionStorage : window.localStorage)
/**
* Purpose: buildDraftStorageKey supports form-draft.ts by holding or executing the build draft storage key 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.
*/
export const buildDraftStorageKey = (...parts: Array<string | number | undefined | null>) => {
const normalizedParts = parts
.filter((part): part is string | number => part !== undefined && part !== null && String(part).trim().length > 0)
.map(part => String(part).trim())
return `fingertipdesigner:draft:${normalizedParts.join(':')}`
}
/**
* Purpose: saveDraftRecord supports form-draft.ts by holding or executing the save draft record 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.
*/
export const saveDraftRecord = <T>(key: string, payload: T, mode: DraftStorageMode = 'local') => {
const record: DraftRecord<T> = {
savedAt: Date.now(),
payload
}
getStorage(mode).setItem(key, JSON.stringify(record))
return record
}
/**
* Purpose: loadDraftRecord supports form-draft.ts by holding or executing the load draft record 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.
*/
export const loadDraftRecord = <T>(key: string, mode: DraftStorageMode = 'local') => {
const rawValue = getStorage(mode).getItem(key)
if (!rawValue) {
return null
}
try {
return JSON.parse(rawValue) as DraftRecord<T>
} catch {
getStorage(mode).removeItem(key)
return null
}
}
/**
* Purpose: clearDraftRecord supports form-draft.ts by holding or executing the clear draft record 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.
*/
export const clearDraftRecord = (key: string, mode: DraftStorageMode = 'local') => {
getStorage(mode).removeItem(key)
}
+34
View File
@@ -0,0 +1,34 @@
/**
* Purpose: IdType supports id.ts by holding or executing the id type 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.
*/
export type IdType = string | number
/**
* Purpose: isEmptyId supports id.ts by holding or executing the is empty id 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.
*/
export const isEmptyId = (value: unknown): value is undefined | null | '' => {
return value === undefined || value === null || `${value}`.trim() === ''
}
/**
* Purpose: toIdString supports id.ts by holding or executing the to id string 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.
*/
export const toIdString = (value: IdType) => String(value)
// 前端统一把雪花 ID 视为字符串语义处理,避免任何 Number 转换带来的精度污染。
export const toOptionalIdString = (value: unknown) => {
if (isEmptyId(value)) {
return undefined
}
return String(value).trim()
}
// 比较 ID 时统一做字符串归一化,兼容接口返回 string / number 两种情况。
export const sameId = (left: unknown, right: unknown) => {
const leftId = toOptionalIdString(left)
const rightId = toOptionalIdString(right)
return leftId !== undefined && leftId === rightId
}
@@ -0,0 +1,271 @@
/**
* Purpose: DEFAULT_MAX_IMAGE_SIZE supports image-upload.ts by holding or executing the default max image size 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 DEFAULT_MAX_IMAGE_SIZE = 5 * 1024 * 1024
/**
* Purpose: AUTO_COMPRESS_TYPES supports image-upload.ts by holding or executing the auto compress types 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 AUTO_COMPRESS_TYPES = new Set(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])
/**
* Purpose: inferImageMimeType supports image-upload.ts by holding or executing the infer image mime type 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 inferImageMimeType = (file: File) => {
if (file.type) return file.type.toLowerCase()
const name = file.name.toLowerCase().split(/[?#]/)[0] || ''
if (name.endsWith('.jpg') || name.endsWith('.jpeg')) return 'image/jpeg'
if (name.endsWith('.png')) return 'image/png'
if (name.endsWith('.webp')) return 'image/webp'
if (name.endsWith('.gif')) return 'image/gif'
return ''
}
/**
* Purpose: ImageCompressionResult supports image-upload.ts by holding or executing the image compression result page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ImageCompressionResult {
file: File
originalSize: number
finalSize: number
compressed: boolean
converted: boolean
skippedReason?: string
}
/**
* Purpose: QUALITY_STEPS supports image-upload.ts by holding or executing the quality steps 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 QUALITY_STEPS = [0.92, 0.84, 0.76, 0.68, 0.6, 0.52]
/**
* Purpose: SCALE_STEPS supports image-upload.ts by holding or executing the scale steps 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 SCALE_STEPS = [1, 0.9, 0.8, 0.7, 0.6, 0.5]
/**
* Purpose: loadImageElement supports image-upload.ts by holding or executing the load image element 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 loadImageElement = (file: File) => {
return new Promise<HTMLImageElement>((resolve, reject) => {
const image = new Image()
const objectUrl = URL.createObjectURL(file)
image.onload = () => {
URL.revokeObjectURL(objectUrl)
resolve(image)
}
image.onerror = () => {
URL.revokeObjectURL(objectUrl)
reject(new Error('图片读取失败'))
}
image.src = objectUrl
})
}
/**
* Purpose: canvasToBlob supports image-upload.ts by holding or executing the canvas to blob 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 canvasToBlob = (canvas: HTMLCanvasElement, type: string, quality?: number) => {
return new Promise<Blob>((resolve, reject) => {
canvas.toBlob(
(blob) => {
if (!blob) {
reject(new Error('图片压缩失败'))
return
}
resolve(blob)
},
type,
quality
)
})
}
/**
* Purpose: getOutputExtension supports image-upload.ts by holding or executing the get output extension 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 getOutputExtension = (type: string) => {
if (type === 'image/png') {
return '.png'
}
if (type === 'image/webp') {
return '.webp'
}
return '.jpg'
}
/**
* Purpose: buildOutputName supports image-upload.ts by holding or executing the build output name 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 buildOutputName = (fileName: string, type: string) => {
const extension = getOutputExtension(type)
const dotIndex = fileName.lastIndexOf('.')
const baseName = dotIndex > -1 ? fileName.slice(0, dotIndex) : fileName
return `${baseName}${extension}`
}
/**
* Purpose: drawImageToCanvas supports image-upload.ts by holding or executing the draw image to canvas 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 drawImageToCanvas = (image: HTMLImageElement, width: number, height: number, mimeType: string) => {
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
const context = canvas.getContext('2d')
if (!context) {
throw new Error('无法初始化图片压缩画布')
}
if (mimeType !== 'image/png') {
context.fillStyle = '#ffffff'
context.fillRect(0, 0, width, height)
}
context.drawImage(image, 0, 0, width, height)
return canvas
}
/**
* Purpose: toCompressedFile supports image-upload.ts by holding or executing the to compressed file 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 toCompressedFile = (blob: Blob, sourceFile: File, mimeType: string) => {
return new File([blob], buildOutputName(sourceFile.name, mimeType), {
type: mimeType,
lastModified: sourceFile.lastModified
})
}
/**
* Purpose: getPreferredMimeTypes supports image-upload.ts by holding or executing the get preferred mime types 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 getPreferredMimeTypes = (file: File) => {
if (file.type === 'image/png') {
return ['image/png', 'image/jpeg']
}
if (file.type === 'image/webp') {
return ['image/webp', 'image/jpeg']
}
return ['image/jpeg']
}
/**
* Purpose: formatFileSize supports image-upload.ts by holding or executing the format file size 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.
*/
export const formatFileSize = (bytes: number) => {
if (bytes >= 1024 * 1024) {
return `${(bytes / 1024 / 1024).toFixed(2)}MB`
}
return `${(bytes / 1024).toFixed(0)}KB`
}
/**
* Purpose: compressImageIfNeeded supports image-upload.ts by holding or executing the compress image if needed 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.
*/
export const compressImageIfNeeded = async (
file: File,
maxSize = DEFAULT_MAX_IMAGE_SIZE
): Promise<ImageCompressionResult> => {
const sourceType = inferImageMimeType(file)
if (!sourceType.startsWith('image/')) {
return {
file,
originalSize: file.size,
finalSize: file.size,
compressed: false,
converted: false,
skippedReason: '仅支持图片文件上传'
}
}
if (file.size <= maxSize) {
return {
file,
originalSize: file.size,
finalSize: file.size,
compressed: false,
converted: false
}
}
if (!AUTO_COMPRESS_TYPES.has(sourceType)) {
return {
file,
originalSize: file.size,
finalSize: file.size,
compressed: false,
converted: false,
skippedReason: '当前图片格式暂不支持自动压缩,请手动处理后重试'
}
}
const image = await loadImageElement(file)
const preferredMimeTypes = getPreferredMimeTypes(new File([file], file.name, { type: sourceType || file.type }))
let bestBlob: Blob | null = null
let bestMimeType = sourceType || file.type
for (const scale of SCALE_STEPS) {
const width = Math.max(1, Math.round(image.naturalWidth * scale))
const height = Math.max(1, Math.round(image.naturalHeight * scale))
for (const mimeType of preferredMimeTypes) {
const canvas = drawImageToCanvas(image, width, height, mimeType)
const qualitySteps = mimeType === 'image/png' ? [undefined] : QUALITY_STEPS
for (const quality of qualitySteps) {
const blob = await canvasToBlob(canvas, mimeType, quality)
if (!bestBlob || blob.size < bestBlob.size) {
bestBlob = blob
bestMimeType = mimeType
}
if (blob.size <= maxSize) {
const compressedFile = toCompressedFile(blob, file, mimeType)
return {
file: compressedFile,
originalSize: file.size,
finalSize: blob.size,
compressed: true,
converted: mimeType !== file.type
}
}
}
}
}
if (!bestBlob) {
throw new Error('图片压缩失败')
}
const compressedFile = toCompressedFile(bestBlob, file, bestMimeType)
return {
file: compressedFile,
originalSize: file.size,
finalSize: bestBlob.size,
compressed: true,
converted: bestMimeType !== file.type
}
}
/**
* Purpose: MAX_IMAGE_UPLOAD_SIZE supports image-upload.ts by holding or executing the max image upload size 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.
*/
export const MAX_IMAGE_UPLOAD_SIZE = DEFAULT_MAX_IMAGE_SIZE
@@ -0,0 +1,89 @@
import { describe, expect, it } from 'vitest'
import { resolveOrderReviewFocus } from './order-review-focus'
const orders = [
{
id: 10,
items: [
{ id: 1001, productTitle: '猫眼款' }
]
},
{
id: 11,
items: [
{ id: 1101, productTitle: '法式款' }
]
}
]
describe('resolveOrderReviewFocus', () => {
it('focuses the exact pending review from message query parameters', () => {
const result = resolveOrderReviewFocus({
orders,
pendingReviews: [{ id: 99, orderId: 10, orderItemId: 1001 }],
orderReviews: {},
query: { reviewId: 99 }
})
expect(result.status).toBe('pending')
expect(result.focusOrderId).toBe('10')
expect(result.focusOrderItemId).toBe('1001')
expect(result.focusReviewId).toBe('99')
})
it('reports a friendly submitted state when the reminder was already handled', () => {
const result = resolveOrderReviewFocus({
orders,
pendingReviews: [],
orderReviews: {
10: [{ id: 99, orderId: 10, orderItemId: 1001, status: 1 }]
},
query: { reviewId: 99 }
})
expect(result.status).toBe('submitted')
expect(result.focusOrderId).toBe('10')
expect(result.focusOrderItemId).toBe('1001')
expect(result.message).toContain('已处理')
})
it('chooses the first pending review for profile pending-review entry', () => {
const result = resolveOrderReviewFocus({
orders,
pendingReviews: [{ id: 88, orderId: 11, orderItemId: 1101 }],
orderReviews: {},
query: { review: 'pending' }
})
expect(result.status).toBe('pending')
expect(result.focusOrderId).toBe('11')
expect(result.focusOrderItemId).toBe('1101')
expect(result.focusReviewId).toBe('88')
})
it('keeps an order-level focus when only orderId is provided', () => {
const result = resolveOrderReviewFocus({
orders,
pendingReviews: [],
orderReviews: {},
query: { orderId: 10 }
})
expect(result.status).toBe('order')
expect(result.focusOrderId).toBe('10')
expect(result.focusOrderItemId).toBe('')
})
it('keeps the order visible when a review id is stale but orderId still exists', () => {
const result = resolveOrderReviewFocus({
orders,
pendingReviews: [],
orderReviews: {},
query: { orderId: 10, reviewId: 404 }
})
expect(result.status).toBe('missing')
expect(result.focusOrderId).toBe('10')
expect(result.message).toContain('失效')
})
})
@@ -0,0 +1,120 @@
import type { OrderArtistReviewVO } from '@/api/order'
type QueryValue = string | number | null | undefined | Array<string | number | null | undefined>
interface OrderLike {
id?: unknown
items?: Array<{ id?: unknown }>
}
interface ResolveOrderReviewFocusOptions {
orders: OrderLike[]
pendingReviews: OrderArtistReviewVO[]
orderReviews: Record<string, OrderArtistReviewVO[]>
query: Record<string, QueryValue>
}
export interface OrderReviewFocusResult {
status: 'none' | 'pending' | 'submitted' | 'missing' | 'order'
focusOrderId: string
focusOrderItemId: string
focusReviewId: string
message: string
}
const toText = (value: QueryValue | unknown) => {
if (Array.isArray(value)) {
return value[0] === undefined || value[0] === null ? '' : String(value[0])
}
return value === undefined || value === null ? '' : String(value)
}
const sameId = (left: unknown, right: unknown) => {
const leftText = toText(left)
const rightText = toText(right)
return leftText !== '' && leftText === rightText
}
const flattenSubmittedReviews = (orderReviews: Record<string, OrderArtistReviewVO[]>) => {
return Object.values(orderReviews).flat().filter(review => Number(review.status) === 1 || Boolean(review.rating))
}
const findOrder = (orders: OrderLike[], orderId: string) => {
return orders.find(order => sameId(order.id, orderId))
}
const buildResult = (
status: OrderReviewFocusResult['status'],
review?: OrderArtistReviewVO,
fallbackOrderId = '',
message = ''
): OrderReviewFocusResult => ({
status,
focusOrderId: toText(review?.orderId) || fallbackOrderId,
focusOrderItemId: toText(review?.orderItemId),
focusReviewId: toText(review?.id),
message
})
export const resolveOrderReviewFocus = ({
orders,
pendingReviews,
orderReviews,
query
}: ResolveOrderReviewFocusOptions): OrderReviewFocusResult => {
const reviewId = toText(query.reviewId)
const orderId = toText(query.orderId)
const orderItemId = toText(query.orderItemId)
const reviewMode = toText(query.review)
const submittedReviews = flattenSubmittedReviews(orderReviews)
if (reviewId) {
const pending = pendingReviews.find(review => sameId(review.id, reviewId))
if (pending) {
return buildResult('pending', pending, '', '已为你定位到待评价订单。')
}
const submitted = submittedReviews.find(review => sameId(review.id, reviewId))
if (submitted) {
return buildResult('submitted', submitted, '', '这条评价提醒已处理,可查看已评价内容。')
}
return {
status: 'missing',
focusOrderId: findOrder(orders, orderId) ? orderId : '',
focusOrderItemId: orderItemId,
focusReviewId: reviewId,
message: '这条评价提醒已失效,可在订单页查看最新状态。'
}
}
if (reviewMode === 'pending') {
const firstPending = pendingReviews[0]
if (firstPending) {
return buildResult('pending', firstPending, '', '已为你定位到待评价订单。')
}
return {
status: 'missing',
focusOrderId: '',
focusOrderItemId: '',
focusReviewId: '',
message: '暂无待评价订单。'
}
}
if (orderId && findOrder(orders, orderId)) {
return {
status: 'order',
focusOrderId: orderId,
focusOrderItemId: orderItemId,
focusReviewId: '',
message: ''
}
}
return {
status: 'none',
focusOrderId: '',
focusOrderItemId: '',
focusReviewId: '',
message: ''
}
}
@@ -0,0 +1,64 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const publicGetSignedUrl = vi.fn()
vi.mock('@/api/file', () => ({
fileApi: {
getSignedUrl: publicGetSignedUrl
}
}))
describe('public-image-assets', () => {
beforeEach(() => {
vi.resetModules()
vi.clearAllMocks()
publicGetSignedUrl.mockResolvedValue({ data: 'img.yunail.art/signed.jpg?token=1' })
})
it('prefers direct image urls over signing file ids', async () => {
const { resolvePublicImageUrls } = await import('./public-image-assets')
await expect(resolvePublicImageUrls({
imageUrls: ['http://img.yunail.art/direct.jpg'],
imageFileIds: '42'
}, 'fallback.png')).resolves.toEqual(['http://img.yunail.art/direct.jpg'])
expect(publicGetSignedUrl).not.toHaveBeenCalled()
})
it('normalizes direct image urls without scheme', async () => {
const { resolvePublicImageUrls } = await import('./public-image-assets')
await expect(resolvePublicImageUrls({
imageUrls: ['img.yunail.art/direct.jpg?token=1']
}, 'fallback.png')).resolves.toEqual(['http://img.yunail.art/direct.jpg?token=1'])
})
it('signs public file ids when direct urls are missing', async () => {
const { resolvePublicImageUrls, resolvePublicImageUrlsSync } = await import('./public-image-assets')
expect(resolvePublicImageUrlsSync({ imageFileIds: '42' }, 'fallback.png')).toEqual(['fallback.png'])
await expect(resolvePublicImageUrls({ imageFileIds: '42' }, 'fallback.png')).resolves.toEqual([
'http://img.yunail.art/signed.jpg?token=1'
])
expect(publicGetSignedUrl).toHaveBeenCalledWith('42')
})
it('extracts legacy file ids from old file urls', async () => {
const { getDirectPublicImageUrls, getPublicImageFileIds } = await import('./public-image-assets')
const record = {
imageUrl: '/api/file/get/325517232303947776',
imageFileIds: '325517232303947776,325517220106911744'
}
expect(getDirectPublicImageUrls(record)).toEqual([])
expect(getPublicImageFileIds(record)).toEqual(['325517232303947776', '325517220106911744'])
})
it('uses fallback when no image source is available', async () => {
const { resolvePublicImageUrls } = await import('./public-image-assets')
await expect(resolvePublicImageUrls({}, 'fallback.png')).resolves.toEqual(['fallback.png'])
})
})
@@ -0,0 +1,97 @@
import { DEFAULT_PRODUCT_IMAGE } from '@/constants'
import type { IdType } from '@/utils/id'
import {
extractLegacyFileId,
getCachedSignedImageUrl,
getCachedSignedImageUrlSync,
parseImageFileIds,
refreshCachedSignedImageUrl
} from '@/utils/signed-image-cache'
export interface PublicImageRecord {
imageUrls?: string[] | string | null
imageFileIds?: string[] | string | null
coverImageUrl?: string | null
coverImageUrls?: string[] | string | null
coverImageFileId?: string[] | string | null
imageUrl?: string | null
}
const normalizePublicUrl = (value: unknown): string => {
const source = String(value || '').replace(/[`]/g, '').trim()
if (!source) return ''
if (/^\/?api\/file\/get\/\d+/i.test(source)) return ''
if (/^(https?:)?\/\//i.test(source) || /^(data|blob):/i.test(source) || source.startsWith('/')) {
return source.startsWith('//') ? `http:${source}` : source
}
if (source.includes('/') || /\.(jpg|jpeg|png|gif|webp|bmp|svg)(\?|#|$)/i.test(source)) {
return `http://${source}`
}
return ''
}
const normalizeUrlList = (value: unknown): string[] => {
const rawValues = Array.isArray(value) ? value : String(value || '').split(',')
return Array.from(new Set(rawValues.map(normalizePublicUrl).filter(Boolean)))
}
export const getPublicImageFileIds = (record: PublicImageRecord): string[] => {
const rawFileIds = [
...(Array.isArray(record.coverImageFileId) ? record.coverImageFileId : parseImageFileIds(String(record.coverImageFileId || ''))),
...(Array.isArray(record.imageFileIds) ? record.imageFileIds : parseImageFileIds(String(record.imageFileIds || ''))),
extractLegacyFileId(record.coverImageUrl),
extractLegacyFileId(record.imageUrl)
]
return Array.from(new Set(rawFileIds.map(id => String(id || '').trim()).filter(Boolean)))
}
export const getDirectPublicImageUrls = (record: PublicImageRecord): string[] => {
return Array.from(new Set([
...normalizeUrlList(record.coverImageUrls),
...normalizeUrlList(record.coverImageUrl),
...normalizeUrlList(record.imageUrls),
...normalizeUrlList(record.imageUrl)
]))
}
export const resolvePublicImageUrlsSync = (
record: PublicImageRecord,
fallback = DEFAULT_PRODUCT_IMAGE
): string[] => {
const directUrls = getDirectPublicImageUrls(record)
if (directUrls.length) return directUrls
const cachedUrls = getPublicImageFileIds(record)
.map(fileId => getCachedSignedImageUrlSync(fileId, 'public'))
.filter(Boolean)
if (cachedUrls.length) return cachedUrls
return fallback ? [fallback] : []
}
export const resolvePublicImageUrls = async (
record: PublicImageRecord,
fallback = DEFAULT_PRODUCT_IMAGE
): Promise<string[]> => {
const directUrls = getDirectPublicImageUrls(record)
if (directUrls.length) return directUrls
const signedUrls = await Promise.all(getPublicImageFileIds(record).map(fileId => getCachedSignedImageUrl(fileId, '', 'public')))
const usableUrls = signedUrls.filter(Boolean)
if (usableUrls.length) return usableUrls
return fallback ? [fallback] : []
}
export const resolvePublicImageUrl = async (
record: PublicImageRecord,
fallback = DEFAULT_PRODUCT_IMAGE
): Promise<string> => {
const urls = await resolvePublicImageUrls(record, fallback)
return urls[0] || fallback
}
export const refreshPublicImageUrl = async (
fileId: IdType | null | undefined,
fallback = DEFAULT_PRODUCT_IMAGE
): Promise<string> => refreshCachedSignedImageUrl(fileId, fallback, 'public')
@@ -0,0 +1,25 @@
import { describe, expect, it } from 'vitest'
import { buildRecoveryActions, getRecoveryMessage, recoveryRouteFor } from './recovery'
describe('recovery utils', () => {
it('normalizes error messages with fallback text', () => {
expect(getRecoveryMessage(new Error('网络开小差了'), '请求失败')).toBe('网络开小差了')
expect(getRecoveryMessage('', '请求失败')).toBe('请求失败')
})
it('adds default routes and primary action state', () => {
const actions = buildRecoveryActions([
{ key: 'retry', text: '重试' },
{ key: 'orders', text: '查看订单' },
{ key: 'cart', text: '返回购物车' }
])
const retryAction = actions[0]
const ordersAction = actions[1]
const cartAction = actions[2]
expect(retryAction?.primary).toBe(true)
expect(ordersAction?.route).toBe('/orders')
expect(cartAction?.route).toBe('/cart')
expect(recoveryRouteFor('products')).toBe('/products')
})
})
+43
View File
@@ -0,0 +1,43 @@
export type RecoveryActionKey = 'retry' | 'orders' | 'cart' | 'products' | 'profile' | 'contact'
export interface RecoveryAction {
key: RecoveryActionKey
text: string
route?: string
primary?: boolean
}
const DEFAULT_ROUTES: Record<string, string> = {
orders: '/orders',
cart: '/cart',
products: '/products',
profile: '/profile'
}
export const getRecoveryMessage = (error: unknown, fallbackMessage: string): string => {
if (error instanceof Error && error.message.trim()) {
return error.message.trim()
}
if (typeof error === 'string' && error.trim()) {
return error.trim()
}
if (error && typeof error === 'object' && 'message' in error) {
const message = String((error as { message?: unknown }).message || '').trim()
if (message) {
return message
}
}
return fallbackMessage
}
export const recoveryRouteFor = (key: RecoveryActionKey): string => DEFAULT_ROUTES[key] || ''
export const buildRecoveryActions = (actions: RecoveryAction[]): RecoveryAction[] => (
actions
.filter(action => action.key && action.text)
.map((action, index) => ({
...action,
route: action.route || recoveryRouteFor(action.key),
primary: action.primary ?? index === 0
}))
)
@@ -0,0 +1,51 @@
// @vitest-environment jsdom
import type { InternalAxiosRequestConfig } from 'axios'
import { createHash, createHmac } from 'node:crypto'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { attachRequestSignature } from './request-signature'
describe('request signature', () => {
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
localStorage.clear()
})
it('falls back when Web Crypto subtle digest is unavailable', async () => {
vi.spyOn(Date, 'now').mockReturnValue(1700000000000)
vi.stubGlobal('crypto', {
randomUUID: () => 'fallback-id'
})
const config = {
method: 'post',
baseURL: '/api',
url: '/order/checkout-preview',
headers: {
'Content-Type': 'application/json'
},
data: {
items: []
}
} as unknown as InternalAxiosRequestConfig
await attachRequestSignature(config, 'access-token')
const headers = config.headers as Record<string, string>
const payloadHash = createHash('sha256').update(JSON.stringify({ items: [] })).digest('hex')
const canonical = [
'POST',
'/order/checkout-preview',
'1700000000000',
'1700000000000-fallback-id',
payloadHash
].join('\n')
const expectedSignature = createHmac('sha256', 'access-token').update(canonical).digest('hex')
expect(headers['X-Timestamp']).toBe('1700000000000')
expect(headers['X-Nonce']).toBe('1700000000000-fallback-id')
expect(headers['X-Sign-Version']).toBe('v1')
expect(headers['X-Signature']).toBe(expectedSignature)
})
})
@@ -0,0 +1,462 @@
import type { InternalAxiosRequestConfig } from 'axios'
/**
* Purpose: HEADER_TIMESTAMP supports request-signature.ts by holding or executing the header timestamp 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 HEADER_TIMESTAMP = 'X-Timestamp'
/**
* Purpose: HEADER_NONCE supports request-signature.ts by holding or executing the header nonce 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 HEADER_NONCE = 'X-Nonce'
/**
* Purpose: HEADER_SIGNATURE supports request-signature.ts by holding or executing the header signature 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 HEADER_SIGNATURE = 'X-Signature'
/**
* Purpose: HEADER_SIGNATURE_VERSION supports request-signature.ts by holding or executing the header signature version 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 HEADER_SIGNATURE_VERSION = 'X-Sign-Version'
/**
* Purpose: DEVICE_ID_HEADER supports request-signature.ts by holding or executing the device id header 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 DEVICE_ID_HEADER = 'X-Device-Id'
/**
* Purpose: DEVICE_ID_STORAGE_KEY supports request-signature.ts by holding or executing the device id storage key 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 DEVICE_ID_STORAGE_KEY = 'fingertipdesigner-device-id'
/**
* Purpose: SIGNATURE_VERSION supports request-signature.ts by holding or executing the signature version 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 SIGNATURE_VERSION = 'v1'
/**
* Purpose: HeaderContainer supports request-signature.ts by holding or executing the header container 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.
*/
type HeaderContainer = Record<string, unknown> & {
set?: (name: string, value: string) => void
get?: (name: string) => unknown
}
const SHA256_K = new Uint32Array([
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
])
/**
* Purpose: RequestSignatureOptions supports request-signature.ts by holding or executing the request signature options page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
interface RequestSignatureOptions {
authFree?: boolean
}
/**
* Purpose: isSafeMethod supports request-signature.ts by holding or executing the is safe method 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 isSafeMethod(method?: string) {
return ['GET', 'HEAD', 'OPTIONS'].includes(String(method || 'GET').toUpperCase())
}
/**
* Purpose: toHex supports request-signature.ts by holding or executing the to hex 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 toHex(bytes: ArrayBuffer | Uint8Array) {
const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
return Array.from(view)
.map(byte => byte.toString(16).padStart(2, '0'))
.join('')
}
function encodeUtf8(text: string) {
return new TextEncoder().encode(text)
}
function rightRotate(value: number, bits: number) {
return (value >>> bits) | (value << (32 - bits))
}
function concatBytes(left: Uint8Array, right: Uint8Array) {
const result = new Uint8Array(left.length + right.length)
result.set(left, 0)
result.set(right, left.length)
return result
}
function sha256Bytes(input: Uint8Array) {
const paddedLength = Math.ceil((input.length + 9) / 64) * 64
const padded = new Uint8Array(paddedLength)
padded.set(input)
padded[input.length] = 0x80
const bitLength = input.length * 8
const view = new DataView(padded.buffer)
view.setUint32(paddedLength - 8, Math.floor(bitLength / 0x100000000), false)
view.setUint32(paddedLength - 4, bitLength >>> 0, false)
let h0 = 0x6a09e667
let h1 = 0xbb67ae85
let h2 = 0x3c6ef372
let h3 = 0xa54ff53a
let h4 = 0x510e527f
let h5 = 0x9b05688c
let h6 = 0x1f83d9ab
let h7 = 0x5be0cd19
const words = new Uint32Array(64)
for (let offset = 0; offset < paddedLength; offset += 64) {
for (let index = 0; index < 16; index++) {
words[index] = view.getUint32(offset + index * 4, false)
}
for (let index = 16; index < 64; index++) {
const word15 = words[index - 15]!
const word2 = words[index - 2]!
const s0 = rightRotate(word15, 7) ^ rightRotate(word15, 18) ^ (word15 >>> 3)
const s1 = rightRotate(word2, 17) ^ rightRotate(word2, 19) ^ (word2 >>> 10)
words[index] = (words[index - 16]! + s0 + words[index - 7]! + s1) >>> 0
}
let a = h0
let b = h1
let c = h2
let d = h3
let e = h4
let f = h5
let g = h6
let h = h7
for (let index = 0; index < 64; index++) {
const s1 = rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)
const ch = (e & f) ^ (~e & g)
const temp1 = (h + s1 + ch + SHA256_K[index]! + words[index]!) >>> 0
const s0 = rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)
const maj = (a & b) ^ (a & c) ^ (b & c)
const temp2 = (s0 + maj) >>> 0
h = g
g = f
f = e
e = (d + temp1) >>> 0
d = c
c = b
b = a
a = (temp1 + temp2) >>> 0
}
h0 = (h0 + a) >>> 0
h1 = (h1 + b) >>> 0
h2 = (h2 + c) >>> 0
h3 = (h3 + d) >>> 0
h4 = (h4 + e) >>> 0
h5 = (h5 + f) >>> 0
h6 = (h6 + g) >>> 0
h7 = (h7 + h) >>> 0
}
const output = new Uint8Array(32)
const outputView = new DataView(output.buffer)
;[h0, h1, h2, h3, h4, h5, h6, h7].forEach((value, index) => {
outputView.setUint32(index * 4, value, false)
})
return output
}
function hmacSha256Bytes(secret: string, message: string) {
const blockSize = 64
let key = encodeUtf8(secret)
if (key.length > blockSize) {
key = sha256Bytes(key)
}
const paddedKey = new Uint8Array(blockSize)
paddedKey.set(key)
const outer = new Uint8Array(blockSize)
const inner = new Uint8Array(blockSize)
for (let index = 0; index < blockSize; index++) {
outer[index] = paddedKey[index]! ^ 0x5c
inner[index] = paddedKey[index]! ^ 0x36
}
return sha256Bytes(concatBytes(outer, sha256Bytes(concatBytes(inner, encodeUtf8(message)))))
}
function getSubtleCrypto() {
return globalThis.crypto?.subtle
}
/**
* Purpose: sha256Hex supports request-signature.ts by holding or executing the sha256 hex 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.
*/
async function sha256Hex(text: string) {
const subtle = getSubtleCrypto()
if (!subtle) {
return toHex(sha256Bytes(encodeUtf8(text)))
}
const digest = await subtle.digest('SHA-256', encodeUtf8(text))
return toHex(digest)
}
/**
* Purpose: hmacSha256Hex supports request-signature.ts by holding or executing the hmac sha256 hex 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.
*/
async function hmacSha256Hex(secret: string, message: string) {
const subtle = getSubtleCrypto()
if (!subtle) {
return toHex(hmacSha256Bytes(secret, message))
}
const key = await subtle.importKey(
'raw',
encodeUtf8(secret),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign']
)
const signature = await subtle.sign('HMAC', key, encodeUtf8(message))
return toHex(signature)
}
/**
* Purpose: randomNonce supports request-signature.ts by holding or executing the random nonce 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 randomNonce() {
if (typeof globalThis.crypto?.randomUUID === 'function') {
return `${Date.now()}-${globalThis.crypto.randomUUID()}`
}
return `${Date.now()}-${Math.random().toString(36).slice(2, 12)}`
}
/**
* Purpose: getDeviceId supports request-signature.ts by holding or executing the get device id 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.
*/
export function getDeviceId() {
try {
const stored = localStorage.getItem(DEVICE_ID_STORAGE_KEY)
if (stored) {
return stored
}
const next = `web-${randomNonce()}`
localStorage.setItem(DEVICE_ID_STORAGE_KEY, next)
return next
} catch {
return `web-${randomNonce()}`
}
}
/**
* Purpose: setHeader supports request-signature.ts by holding or executing the set header 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 setHeader(config: InternalAxiosRequestConfig, name: string, value: string) {
const headers = config.headers as HeaderContainer | undefined
if (headers && typeof headers.set === 'function') {
headers.set(name, value)
return
}
config.headers = {
...(headers || {}),
[name]: value
} as InternalAxiosRequestConfig['headers']
}
/**
* Purpose: getHeader supports request-signature.ts by holding or executing the get header 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 getHeader(config: InternalAxiosRequestConfig, name: string) {
const headers = config.headers as HeaderContainer | undefined
if (!headers) {
return ''
}
if (typeof headers.get === 'function') {
const value = headers.get(name)
if (value !== undefined && value !== null) {
return String(value)
}
}
return String(headers[name] || headers[name.toLowerCase()] || '')
}
/**
* Purpose: extractPath supports request-signature.ts by holding or executing the extract path 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 extractPath(value?: string) {
if (!value) {
return ''
}
try {
return new URL(value, window.location.origin).pathname
} catch {
return value.split('?')[0] || ''
}
}
/**
* Purpose: joinAxiosPath supports request-signature.ts by holding or executing the join axios path 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 joinAxiosPath(baseUrl?: string, requestUrl?: string) {
if (requestUrl && /^[a-z][a-z\d+\-.]*:\/\//i.test(requestUrl)) {
return extractPath(requestUrl)
}
const basePath = extractPath(baseUrl).replace(/^\/+|\/+$/g, '')
const requestPath = extractPath(requestUrl).replace(/^\/+|\/+$/g, '')
const joined = [basePath, requestPath].filter(Boolean).join('/')
return joined ? `/${joined}` : '/'
}
/**
* Purpose: toBackendRequestPath supports request-signature.ts by holding or executing the to backend request path 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 toBackendRequestPath(baseUrl?: string, requestUrl?: string) {
const path = joinAxiosPath(baseUrl, requestUrl)
if (path === '/api') {
return '/'
}
if (path.startsWith('/api/')) {
return `/${path.slice('/api/'.length)}`
}
return path
}
/**
* Purpose: appendParam supports request-signature.ts by holding or executing the append param 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 appendParam(target: Record<string, unknown[]>, key: string, value: unknown) {
if (value === undefined || value === null || value === '') {
return
}
if (!target[key]) {
target[key] = []
}
if (Array.isArray(value)) {
value.forEach(item => appendParam(target, key, item))
return
}
target[key].push(value)
}
/**
* Purpose: collectParams supports request-signature.ts by holding or executing the collect params 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 collectParams(source: unknown, target: Record<string, unknown[]>) {
if (!source) {
return
}
if (source instanceof URLSearchParams) {
source.forEach((value, key) => appendParam(target, key, value))
return
}
if (source instanceof FormData) {
source.forEach((value, key) => {
if (!(value instanceof Blob)) {
appendParam(target, key, value)
}
})
return
}
if (typeof source === 'object') {
Object.entries(source as Record<string, unknown>).forEach(([key, value]) => appendParam(target, key, value))
}
}
/**
* Purpose: buildCanonicalParams supports request-signature.ts by holding or executing the build canonical params 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 buildCanonicalParams(...sources: unknown[]) {
const params: Record<string, unknown[]> = {}
sources.forEach(source => collectParams(source, params))
return Object.keys(params)
.sort()
.map(key => {
const normalized = params[key]
?.map(value => String(value))
.sort()
.join(',') || ''
return `${key}=${normalized}`
})
.join('&')
}
/**
* Purpose: buildJsonPayload supports request-signature.ts by holding or executing the build json payload 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 buildJsonPayload(data: unknown) {
if (data === undefined || data === null || data === '') {
return ''
}
if (typeof data === 'string') {
return data
}
return JSON.stringify(data)
}
/**
* Purpose: resolvePayload supports request-signature.ts by holding or executing the resolve payload 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 resolvePayload(config: InternalAxiosRequestConfig) {
const contentType = getHeader(config, 'Content-Type').toLowerCase()
const jsonPayload = contentType.includes('application/json') ? buildJsonPayload(config.data) : ''
if (jsonPayload) {
return jsonPayload
}
return buildCanonicalParams(config.params, config.data)
}
/**
* Purpose: attachRequestSignature supports request-signature.ts by holding or executing the attach request signature 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.
*/
export async function attachRequestSignature(
config: InternalAxiosRequestConfig,
accessToken?: string | null,
options: RequestSignatureOptions = {}
) {
setHeader(config, DEVICE_ID_HEADER, getDeviceId())
const method = String(config.method || 'GET').toUpperCase()
if (!accessToken || options.authFree || isSafeMethod(method)) {
return config
}
const timestamp = String(Date.now())
const nonce = randomNonce()
const payloadHash = await sha256Hex(resolvePayload(config))
const canonical = [
method,
toBackendRequestPath(config.baseURL, config.url),
timestamp,
nonce,
payloadHash
].join('\n')
setHeader(config, HEADER_TIMESTAMP, timestamp)
setHeader(config, HEADER_NONCE, nonce)
setHeader(config, HEADER_SIGNATURE, await hmacSha256Hex(accessToken, canonical))
setHeader(config, HEADER_SIGNATURE_VERSION, SIGNATURE_VERSION)
return config
}
@@ -0,0 +1,24 @@
import { describe, expect, it } from 'vitest'
import { extractRichText, renderRichContent } from './rich-content'
describe('rich content helpers', () => {
it('renders markdown into html', () => {
const html = renderRichContent('# 标题\n\n- 甲\n- 乙\n\n**加粗** [链接](https://example.com)')
expect(html).toContain('<h1>标题</h1>')
expect(html).toContain('<ul>')
expect(html).toContain('<strong>加粗</strong>')
expect(html).toContain('<a href="https://example.com"')
})
it('keeps safe html and strips scripts', () => {
const html = renderRichContent('<p>hello <strong>world</strong></p><script>alert(1)</script>')
expect(html).toBe('<p>hello <strong>world</strong></p>')
})
it('extracts plain text from rich content', () => {
expect(extractRichText('<p>Hello <strong>world</strong></p>')).toBe('Hello world')
expect(extractRichText('## 标题\n\n内容')).toBe('标题 内容')
})
})
@@ -0,0 +1,272 @@
const HTML_TAG_PATTERN = /<\/?[a-z][\s\S]*>/i
const DANGEROUS_TAGS = new Set(['script', 'style', 'iframe', 'object', 'embed', 'form', 'input', 'button', 'textarea', 'select', 'svg', 'math'])
const ALLOWED_TAGS = new Set([
'a',
'blockquote',
'br',
'code',
'del',
'div',
'em',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'hr',
'img',
'li',
'ol',
'p',
'pre',
'span',
'strong',
'table',
'tbody',
'td',
'th',
'thead',
'tr',
'ul'
])
const GLOBAL_ATTRS = new Set(['class', 'title'])
const TAG_ATTRS: Record<string, Set<string>> = {
a: new Set(['href', 'target', 'rel', 'title']),
img: new Set(['src', 'alt', 'title']),
td: new Set(['colspan', 'rowspan']),
th: new Set(['colspan', 'rowspan'])
}
const escapeHtml = (value: string) => value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;')
const escapeAttr = (value: string) => escapeHtml(value).replace(/`/g, '&#96;')
const isSafeUrl = (value: string) => {
const normalized = value.trim().replace(/[\u0000-\u001F\u007F\s]+/g, '')
if (!normalized) return false
if (normalized.startsWith('#')) return true
if (normalized.startsWith('/') && !normalized.startsWith('//')) return true
if (/^(https?:|mailto:|tel:)/i.test(normalized)) return true
return /^data:image\/(?:png|jpe?g|gif|webp);base64,/i.test(normalized)
}
const isAllowedAttr = (tagName: string, attrName: string) => {
if (attrName.startsWith('on')) return false
return GLOBAL_ATTRS.has(attrName) || TAG_ATTRS[tagName]?.has(attrName)
}
const sanitizeFallback = (html: string) => html
.replace(/<\s*(script|style|iframe|object|embed|svg|math)[^>]*>[\s\S]*?<\s*\/\s*\1\s*>/gi, '')
.replace(/\s+on[a-z]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, '')
.replace(/\s+(href|src)\s*=\s*(["'])\s*javascript:[\s\S]*?\2/gi, '')
export const sanitizeRichHtml = (html: string) => {
const source = html.trim()
if (!source) return ''
if (typeof DOMParser === 'undefined') {
return sanitizeFallback(source)
}
const parser = new DOMParser()
const doc = parser.parseFromString(source, 'text/html')
const walk = (node: Node) => {
if (node.nodeType === Node.COMMENT_NODE) {
node.parentNode?.removeChild(node)
return
}
if (node.nodeType !== Node.ELEMENT_NODE) {
return
}
const element = node as HTMLElement
const tagName = element.tagName.toLowerCase()
if (DANGEROUS_TAGS.has(tagName)) {
element.remove()
return
}
if (!ALLOWED_TAGS.has(tagName)) {
const children = Array.from(element.childNodes)
element.replaceWith(...children)
children.forEach(walk)
return
}
Array.from(element.attributes).forEach(attribute => {
const attrName = attribute.name.toLowerCase()
const attrValue = attribute.value
if (!isAllowedAttr(tagName, attrName)) {
element.removeAttribute(attribute.name)
return
}
if ((attrName === 'href' || attrName === 'src') && !isSafeUrl(attrValue)) {
element.removeAttribute(attribute.name)
}
})
if (tagName === 'a' && element.getAttribute('href')) {
element.setAttribute('target', '_blank')
element.setAttribute('rel', 'noopener noreferrer')
}
Array.from(element.childNodes).forEach(walk)
}
Array.from(doc.body.childNodes).forEach(walk)
return doc.body.innerHTML.trim()
}
const renderInlineMarkdown = (value: string) => {
let html = escapeHtml(value)
html = html.replace(/`([^`]+)`/g, '<code>$1</code>')
html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
html = html.replace(/__([^_]+)__/g, '<strong>$1</strong>')
html = html.replace(/\*([^*]+)\*/g, '<em>$1</em>')
html = html.replace(/_([^_]+)_/g, '<em>$1</em>')
html = html.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_match, label: string, url: string) => {
const href = url.replace(/&amp;/g, '&')
if (!isSafeUrl(href)) {
return label
}
return `<a href="${escapeAttr(href)}" target="_blank" rel="noopener noreferrer">${label}</a>`
})
return html.replace(/\n/g, '<br>')
}
const markdownToHtml = (markdown: string) => {
const lines = markdown.replace(/\r\n?/g, '\n').split('\n')
const html: string[] = []
const paragraphs: string[] = []
const listItems: string[] = []
let listTag: 'ul' | 'ol' | '' = ''
let inCodeFence = false
let codeLines: string[] = []
const flushParagraph = () => {
if (!paragraphs.length) return
html.push(`<p>${renderInlineMarkdown(paragraphs.join('\n'))}</p>`)
paragraphs.length = 0
}
const flushList = () => {
if (!listTag || !listItems.length) return
html.push(`<${listTag}>${listItems.map(item => `<li>${renderInlineMarkdown(item)}</li>`).join('')}</${listTag}>`)
listItems.length = 0
listTag = ''
}
const flushCodeFence = () => {
html.push(`<pre><code>${escapeHtml(codeLines.join('\n'))}</code></pre>`)
codeLines = []
}
lines.forEach(line => {
if (/^```/.test(line.trim())) {
if (inCodeFence) {
inCodeFence = false
flushCodeFence()
} else {
flushParagraph()
flushList()
inCodeFence = true
codeLines = []
}
return
}
if (inCodeFence) {
codeLines.push(line)
return
}
if (!line.trim()) {
flushParagraph()
flushList()
return
}
const heading = /^(#{1,6})\s+(.+)$/.exec(line)
if (heading) {
flushParagraph()
flushList()
const level = heading[1]!.length
html.push(`<h${level}>${renderInlineMarkdown(heading[2]!.trim())}</h${level}>`)
return
}
const blockquote = /^>\s?(.*)$/.exec(line)
if (blockquote) {
flushParagraph()
flushList()
html.push(`<blockquote>${renderInlineMarkdown(blockquote[1] || '')}</blockquote>`)
return
}
const unordered = /^\s*[-*+]\s+(.+)$/.exec(line)
if (unordered) {
flushParagraph()
if (listTag && listTag !== 'ul') flushList()
listTag = 'ul'
listItems.push(unordered[1] || '')
return
}
const ordered = /^\s*\d+\.\s+(.+)$/.exec(line)
if (ordered) {
flushParagraph()
if (listTag && listTag !== 'ol') flushList()
listTag = 'ol'
listItems.push(ordered[1] || '')
return
}
flushList()
paragraphs.push(line)
})
if (inCodeFence) {
flushCodeFence()
}
flushParagraph()
flushList()
return html.join('')
}
export const renderRichContent = (content?: string | null) => {
const source = String(content || '').trim()
if (!source) return ''
const html = HTML_TAG_PATTERN.test(source) ? source : markdownToHtml(source)
return sanitizeRichHtml(html)
}
export const extractRichText = (content?: string | null) => {
const html = renderRichContent(content)
if (!html) return ''
const spacedHtml = html
.replace(/<br\s*\/?>/gi, ' ')
.replace(/<\/(p|div|h[1-6]|li|blockquote|tr)>/gi, ' </$1>')
if (typeof DOMParser === 'undefined') {
return spacedHtml.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim()
}
const parser = new DOMParser()
const doc = parser.parseFromString(spacedHtml, 'text/html')
return (doc.body.textContent || '').replace(/\s+/g, ' ').trim()
}
+252
View File
@@ -0,0 +1,252 @@
/**
* Purpose: SHOP_THEME_CHANGED_EVENT supports shop-theme.ts by holding or executing the shop theme changed event 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.
*/
export const SHOP_THEME_CHANGED_EVENT = 'fingertip-designer-shop-theme-updated'
/**
* Purpose: ShopThemeSource supports shop-theme.ts by holding or executing the shop theme source page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ShopThemeSource {
themePrimaryColor?: string | null
themeSecondaryColor?: string | null
themeAccentColor?: string | null
themePageBgColor?: string | null
themeCardBgColor?: string | null
themeBackgroundImageFileId?: string | number | null
}
/**
* Purpose: ResolvedShopTheme supports shop-theme.ts by holding or executing the resolved shop theme page or API role.
* Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow.
*/
export interface ResolvedShopTheme {
primaryColor: string
secondaryColor: string
accentColor: string
tertiaryColor: string
neutralColor: string
pageBgColor: string
cardBgColor: string
textPrimary: string
textSecondary: string
borderColor: string
primarySoftColor: string
secondarySoftColor: string
primaryActionColor: string
gradient: string
softGradient: string
backgroundImageFileId?: string
cssVars: Record<string, string>
}
/**
* Purpose: HEX_COLOR_PATTERN supports shop-theme.ts by holding or executing the hex color pattern 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 HEX_COLOR_PATTERN = /^#[0-9a-fA-F]{6}$/
export const DEFAULT_SHOP_THEME: ResolvedShopTheme = resolveShopThemeSource()
/**
* Purpose: resolveShopTheme supports shop-theme.ts by holding or executing the resolve shop theme 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.
*/
export function resolveShopTheme(source?: ShopThemeSource | null): ResolvedShopTheme {
return resolveShopThemeSource(source)
}
/**
* Purpose: applyShopTheme supports shop-theme.ts by holding or executing the apply shop theme 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.
*/
export function applyShopTheme(theme: ResolvedShopTheme, backgroundImageUrl?: string | null) {
if (typeof document === 'undefined') {
return
}
const root = document.documentElement
Object.entries(theme.cssVars).forEach(([key, value]) => {
root.style.setProperty(key, value)
})
root.style.setProperty('--theme-background-image', backgroundImageUrl ? `url("${backgroundImageUrl}")` : 'none')
}
/**
* Purpose: notifyShopThemeChanged supports shop-theme.ts by holding or executing the notify shop theme changed 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.
*/
export function notifyShopThemeChanged() {
if (typeof window === 'undefined') {
return
}
window.dispatchEvent(new Event(SHOP_THEME_CHANGED_EVENT))
}
/**
* Purpose: resolveShopThemeSource supports shop-theme.ts by holding or executing the resolve shop theme source 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 resolveShopThemeSource(source?: ShopThemeSource | null): ResolvedShopTheme {
const normalizedPrimaryColor = normalizeHexColor(source?.themePrimaryColor)
const primaryColor = normalizedPrimaryColor || '#E8B4B8'
const secondaryColor = normalizeHexColor(source?.themeSecondaryColor)
|| (normalizedPrimaryColor ? mixColor(primaryColor, '#C5A059', 0.35) : '#C5A059')
const neutralColor = normalizeHexColor(source?.themeAccentColor)
|| (normalizedPrimaryColor ? mixColor('#4A443F', primaryColor, 0.14) : '#4A443F')
const accentColor = neutralColor
const tertiaryColor = normalizeHexColor(source?.themePageBgColor) || '#FDFBF9'
const pageBgColor = tertiaryColor
const cardBgColor = normalizeHexColor(source?.themeCardBgColor) || '#FFFFFF'
const textPrimary = readableTextColor(pageBgColor, neutralColor)
const textSecondary = textPrimary === neutralColor
? mixColor(neutralColor, cardBgColor, 0.18)
: mixColor('#FFFFFF', primaryColor, 0.3)
const borderColor = mixColor(primaryColor, cardBgColor, 0.72)
const primarySoftColor = mixColor(primaryColor, cardBgColor, 0.78)
const secondarySoftColor = mixColor(secondaryColor, pageBgColor, 0.66)
const primaryActionColor = mixColor(neutralColor, primaryColor, 0.28)
const gradient = `linear-gradient(135deg, ${primaryActionColor} 0%, ${secondaryColor} 100%)`
const softGradient = `linear-gradient(145deg, ${cardBgColor} 0%, ${secondarySoftColor} 58%, ${mixColor(primaryColor, pageBgColor, 0.62)} 100%)`
const backgroundImageFileId = source?.themeBackgroundImageFileId === undefined || source?.themeBackgroundImageFileId === null
? undefined
: String(source.themeBackgroundImageFileId).trim() || undefined
return {
primaryColor,
secondaryColor,
accentColor,
tertiaryColor,
neutralColor,
pageBgColor,
cardBgColor,
textPrimary,
textSecondary,
borderColor,
primarySoftColor,
secondarySoftColor,
primaryActionColor,
gradient,
softGradient,
backgroundImageFileId,
cssVars: {
'--primary-color': primaryColor,
'--theme-primary': primaryColor,
'--theme-secondary': secondaryColor,
'--theme-accent': accentColor,
'--theme-neutral': neutralColor,
'--theme-tertiary': tertiaryColor,
'--theme-primary-action': primaryActionColor,
'--theme-primary-soft': primarySoftColor,
'--theme-secondary-soft': secondarySoftColor,
'--theme-page-bg': pageBgColor,
'--theme-card-bg': cardBgColor,
'--theme-border': borderColor,
'--theme-gradient': gradient,
'--theme-gradient-soft': softGradient,
'--theme-button-shadow': `0 12px 28px ${rgba(primaryColor, 0.22)}`,
'--theme-focus-shadow': `0 0 0 3px ${rgba(primaryColor, 0.16)}`,
'--bg-color': pageBgColor,
'--secondary-bg-color': mixColor(secondaryColor, pageBgColor, 0.58),
'--surface-color': cardBgColor,
'--text-primary': textPrimary,
'--text-secondary': textSecondary
}
}
}
/**
* Purpose: normalizeHexColor supports shop-theme.ts by holding or executing the normalize hex color 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 normalizeHexColor(value?: string | null): string | undefined {
if (!value) {
return undefined
}
const normalized = value.trim()
return HEX_COLOR_PATTERN.test(normalized) ? normalized.toUpperCase() : undefined
}
/**
* Purpose: mixColor supports shop-theme.ts by holding or executing the mix color 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 mixColor(foreground: string, background: string, backgroundWeight: number): string {
const fg = hexToRgb(foreground)
const bg = hexToRgb(background)
const weight = clamp(backgroundWeight, 0, 1)
return rgbToHex({
r: Math.round(fg.r * (1 - weight) + bg.r * weight),
g: Math.round(fg.g * (1 - weight) + bg.g * weight),
b: Math.round(fg.b * (1 - weight) + bg.b * weight)
})
}
/**
* Purpose: readableTextColor supports shop-theme.ts by holding or executing the readable text color 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 readableTextColor(background: string, preferred: string): string {
return relativeLuminance(hexToRgb(background)) > 0.48 ? preferred : '#FFFFFF'
}
/**
* Purpose: rgba supports shop-theme.ts by holding or executing the rgba 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 rgba(color: string, alpha: number): string {
const rgb = hexToRgb(color)
return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${clamp(alpha, 0, 1)})`
}
/**
* Purpose: relativeLuminance supports shop-theme.ts by holding or executing the relative luminance 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 relativeLuminance(rgb: { r: number; g: number; b: number }): number {
const toLinearChannel = (value: number) => {
const channel = value / 255
return channel <= 0.03928 ? channel / 12.92 : Math.pow((channel + 0.055) / 1.055, 2.4)
}
const r = toLinearChannel(rgb.r)
const g = toLinearChannel(rgb.g)
const b = toLinearChannel(rgb.b)
return 0.2126 * r + 0.7152 * g + 0.0722 * b
}
/**
* Purpose: hexToRgb supports shop-theme.ts by holding or executing the hex to rgb 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 hexToRgb(color: string): { r: number; g: number; b: number } {
const value = color.replace('#', '')
return {
r: Number.parseInt(value.slice(0, 2), 16),
g: Number.parseInt(value.slice(2, 4), 16),
b: Number.parseInt(value.slice(4, 6), 16)
}
}
/**
* Purpose: rgbToHex supports shop-theme.ts by holding or executing the rgb to hex 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 rgbToHex(rgb: { r: number; g: number; b: number }): string {
return `#${toHex(rgb.r)}${toHex(rgb.g)}${toHex(rgb.b)}`
}
/**
* Purpose: toHex supports shop-theme.ts by holding or executing the to hex 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 toHex(value: number): string {
return clamp(value, 0, 255).toString(16).padStart(2, '0').toUpperCase()
}
/**
* Purpose: clamp supports shop-theme.ts by holding or executing the clamp 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 clamp(value: number, min: number, max: number): number {
return Math.min(max, Math.max(min, value))
}
@@ -0,0 +1,131 @@
import { fileApi } from '@/api/file'
import type { IdType } from '@/utils/id'
const SIGNED_IMAGE_CACHE_TTL_MS = 10 * 60 * 1000
export type SignedImageSource = 'public'
type SignedImageCacheEntry = {
url: string
expiresAt: number
}
const signedImageUrlCache = new Map<string, SignedImageCacheEntry>()
const pendingSignedImageUrlRequests = new Map<string, Promise<string>>()
const normalizeFileId = (fileId: IdType | null | undefined) => String(fileId ?? '').trim()
const buildCacheKey = (source: SignedImageSource, fileId: string) => `${source}:${fileId}`
const normalizeImageUrl = (url: string): string => {
const trimmedUrl = url.trim()
if (!trimmedUrl) return ''
if (/^(https?:)?\/\//i.test(trimmedUrl) || /^(data|blob):/i.test(trimmedUrl) || trimmedUrl.startsWith('/')) {
return trimmedUrl
}
return `http://${trimmedUrl}`
}
const requestSignedImageUrl = (_source: SignedImageSource, fileId: string): Promise<string> => {
return fileApi.getSignedUrl(fileId).then(response => String(response.data || ''))
}
const getUsableCacheEntry = (key: string) => {
const cached = signedImageUrlCache.get(key)
if (!cached) return undefined
if (cached.expiresAt <= Date.now()) {
signedImageUrlCache.delete(key)
return undefined
}
return cached.url
}
export const parseImageFileIds = (value?: string | null): string[] =>
String(value || '')
.split(',')
.map(id => id.trim())
.filter(Boolean)
export const getCachedSignedImageUrlSync = (
fileId: IdType | null | undefined,
source: SignedImageSource = 'public'
): string => {
const fileIdKey = normalizeFileId(fileId)
if (!fileIdKey) return ''
return getUsableCacheEntry(buildCacheKey(source, fileIdKey)) || ''
}
export const getCachedSignedImageUrl = async (
fileId: IdType | null | undefined,
fallback = '',
source: SignedImageSource = 'public'
): Promise<string> => {
const fileIdKey = normalizeFileId(fileId)
if (!fileIdKey) return fallback
const key = buildCacheKey(source, fileIdKey)
const cachedUrl = getUsableCacheEntry(key)
if (cachedUrl) return cachedUrl
const pendingRequest = pendingSignedImageUrlRequests.get(key)
if (pendingRequest) {
return pendingRequest.then(url => url || fallback).catch(() => fallback)
}
const request = requestSignedImageUrl(source, fileIdKey)
.then(response => {
const url = normalizeImageUrl(String(response || ''))
if (url) {
signedImageUrlCache.set(key, {
url,
expiresAt: Date.now() + SIGNED_IMAGE_CACHE_TTL_MS
})
}
return url
})
.finally(() => {
pendingSignedImageUrlRequests.delete(key)
})
pendingSignedImageUrlRequests.set(key, request)
return request.then(url => url || fallback).catch(() => fallback)
}
export const clearCachedSignedImageUrl = (
fileId: IdType | null | undefined,
source: SignedImageSource = 'public'
): void => {
const fileIdKey = normalizeFileId(fileId)
if (!fileIdKey) return
const cacheKey = buildCacheKey(source, fileIdKey)
signedImageUrlCache.delete(cacheKey)
pendingSignedImageUrlRequests.delete(cacheKey)
}
export const refreshCachedSignedImageUrl = async (
fileId: IdType | null | undefined,
fallback = '',
source: SignedImageSource = 'public'
): Promise<string> => {
clearCachedSignedImageUrl(fileId, source)
return getCachedSignedImageUrl(fileId, fallback, source)
}
export const getCachedSignedImageUrls = async (
fileIds: Array<IdType | null | undefined>,
fallback = '',
source: SignedImageSource = 'public'
): Promise<string[]> => {
const urls = await Promise.all(fileIds.map(fileId => getCachedSignedImageUrl(fileId, '', source)))
const validUrls = urls.filter(Boolean)
return validUrls.length ? validUrls : (fallback ? [fallback] : [])
}
export const getCachedSignedImageUrlsSync = (
fileIds: Array<IdType | null | undefined>,
source: SignedImageSource = 'public'
): string[] =>
fileIds.map(fileId => getCachedSignedImageUrlSync(fileId, source)).filter(Boolean)
export const extractLegacyFileId = (value?: string | null): string => {
const source = String(value || '').replace(/<[^>]*>/g, '')
return source.match(/\/api\/file\/get\/([^/?#"'<>]+)/)?.[1] || ''
}
@@ -0,0 +1,53 @@
import { describe, expect, it } from 'vitest'
import { buildSystemMessageActionPath } from './system-message-action'
describe('buildSystemMessageActionPath', () => {
it('keeps safe review action paths with order and review query parameters', () => {
expect(buildSystemMessageActionPath({
actionPath: '/orders?orderId=10&reviewId=99&orderItemId=1001',
businessType: 'ORDER_ARTIST_REVIEW',
businessId: 99
})).toBe('/orders?orderId=10&reviewId=99&orderItemId=1001')
})
it('uses reviewId fallback for review reminder messages when actionPath is absent', () => {
expect(buildSystemMessageActionPath({
businessType: 'ORDER_ARTIST_REVIEW',
businessId: 99
})).toBe('/orders?reviewId=99&source=message')
})
it('opens pending reviews when a review reminder has no business id', () => {
expect(buildSystemMessageActionPath({
businessType: 'ORDER_ARTIST_REVIEW'
})).toBe('/orders?review=pending&source=message')
})
it('uses orderId fallback for generic order messages', () => {
expect(buildSystemMessageActionPath({
businessType: 'ORDER',
businessId: 10
})).toBe('/orders/10')
})
it('uses after-sale fallback for after-sale messages', () => {
expect(buildSystemMessageActionPath({
businessType: 'AFTER_SALE',
businessId: 10
})).toBe('/after-sales?orderId=10&source=message')
})
it('keeps safe order detail and after-sale action paths', () => {
expect(buildSystemMessageActionPath({ actionPath: '/orders/10' })).toBe('/orders/10')
expect(buildSystemMessageActionPath({ actionPath: '/after-sales?orderId=10' })).toBe('/after-sales?orderId=10')
expect(buildSystemMessageActionPath({ actionPath: '/after-sale/apply?orderId=10&orderItemId=99' })).toBe('/after-sale/apply?orderId=10&orderItemId=99')
expect(buildSystemMessageActionPath({ actionPath: '/service-progress?orderId=10' })).toBe('/service-progress?orderId=10')
})
it('rejects unsafe or backend-only action paths', () => {
expect(buildSystemMessageActionPath({ actionPath: '//evil.example/orders' })).toBe('')
expect(buildSystemMessageActionPath({ actionPath: 'https://evil.example/orders' })).toBe('')
expect(buildSystemMessageActionPath({ actionPath: '/admin/users' })).toBe('')
expect(buildSystemMessageActionPath({ actionPath: '/orders-admin' })).toBe('')
})
})
@@ -0,0 +1,95 @@
import type { SystemMessageVO } from '@/api/user'
type MessageLike = Pick<SystemMessageVO, 'actionPath' | 'businessType' | 'businessId'>
const USER_ACTION_PREFIXES = [
'/orders',
'/after-sales',
'/after-sale/apply',
'/service-progress',
'/help',
'/product/',
'/shop/',
'/coupons',
'/vip-center',
'/cart',
'/notifications',
'/wishlist',
'/profile',
'/settings',
'/artist-orders',
'/artist-calendar'
]
const appendQuery = (path: string, query: Record<string, string | number | undefined>) => {
const params = new URLSearchParams()
Object.entries(query).forEach(([key, value]) => {
if (value !== undefined && value !== '') {
params.set(key, String(value))
}
})
const queryString = params.toString()
return queryString ? `${path}?${queryString}` : path
}
const isAllowedUserActionPath = (actionPath: string) => {
const pathOnly = actionPath.split('?')[0] || ''
return USER_ACTION_PREFIXES.some(prefix => {
if (prefix.endsWith('/')) {
return pathOnly.startsWith(prefix)
}
return pathOnly === prefix || pathOnly.startsWith(`${prefix}/`)
})
}
export const normalizeSystemMessageActionPath = (value?: string) => {
const actionPath = String(value || '').trim()
if (!actionPath || !actionPath.startsWith('/') || actionPath.startsWith('//') || actionPath.includes('\\')) {
return ''
}
return isAllowedUserActionPath(actionPath) ? actionPath : ''
}
export const buildSystemMessageActionPath = (message: MessageLike) => {
const actionPath = normalizeSystemMessageActionPath(message.actionPath)
if (actionPath) {
return actionPath
}
const businessType = String(message.businessType || '').toUpperCase()
const businessId = message.businessId === undefined || message.businessId === null ? '' : String(message.businessId)
if (businessType === 'ORDER_ARTIST_REVIEW') {
return businessId
? appendQuery('/orders', { reviewId: businessId, source: 'message' })
: appendQuery('/orders', { review: 'pending', source: 'message' })
}
if (businessType === 'ORDER' && businessId) {
return `/orders/${encodeURIComponent(businessId)}`
}
if (businessType === 'ORDER_ARTIST_CHANGE' && businessId) {
return appendQuery('/service-progress', { orderId: businessId, source: 'message' })
}
if (businessType === 'ORDER_ARTIST_CHANGE' || businessType === 'ORDER') {
return appendQuery('/orders', { orderId: businessId || undefined, source: 'message' })
}
if (businessType === 'AFTER_SALE') {
return appendQuery('/after-sales', { orderId: businessId || undefined, source: 'message' })
}
if (businessType === 'PRODUCT' && businessId) {
return `/product/${encodeURIComponent(businessId)}`
}
if (businessType === 'SHOP' && businessId) {
return `/shop/${encodeURIComponent(businessId)}`
}
if (businessType === 'VIP') {
return '/vip-center'
}
if (businessType === 'COUPON') {
return '/coupons'
}
if (businessType === 'CART') {
return '/cart'
}
return ''
}
@@ -0,0 +1,831 @@
<template>
<div class="mobile-container">
<!-- 头部区域 -->
<header class="header">
<a-button class="back-btn" type="text" @click="handleBackClick">
<LeftOutlined :style="{ fontSize: '20px' }" />
</a-button>
<h1>账号设置</h1>
<div class="empty"></div>
</header>
<!-- 账号设置内容 -->
<div class="account-settings">
<!-- 账号设置选项 -->
<a-card :bordered="false" class="settings-card">
<a-list :data-source="accountSettings" :split="false">
<template #renderItem="{ item }">
<a-list-item class="setting-item" @click="handleSettingClick(item.key)">
<template #actions>
<RightOutlined />
</template>
<a-list-item-meta>
<template #avatar>
<div class="setting-icon" :style="{ backgroundColor: item.bgColor }">
<component :is="item.icon" />
</div>
</template>
<template #title>
<span>{{ item.title }}</span>
</template>
<template #description v-if="item.desc">
<span>{{ item.desc }}</span>
</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
</a-card>
</div>
<!-- 绑定手机号弹窗 -->
<a-modal
v-model:visible="bindPhoneModalVisible"
title="绑定手机号"
@ok="handleBindPhoneSubmit"
@cancel="handleBindPhoneCancel"
:confirmLoading="bindPhoneLoading"
>
<DraftActions
:saved-at="bindPhoneDraftSavedAt"
@save="handleSaveBindPhoneDraft"
@clear="handleClearBindPhoneDraft"
/>
<a-form layout="vertical">
<a-form-item label="手机号" name="phone">
<a-input
v-model:value="bindPhoneForm.phone"
placeholder="请输入手机号"
:disabled="!!userInfo.phone"
/>
</a-form-item>
<a-form-item label="验证码" name="verificationCode">
<a-input
v-model:value="bindPhoneForm.verificationCode"
placeholder="请输入验证码"
>
<template #suffix>
<a-button
type="link"
:disabled="countdown > 0 || !bindPhoneForm.phone"
@click="handleSendVerificationCode"
>
{{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
</a-button>
</template>
</a-input>
</a-form-item>
</a-form>
</a-modal>
<!-- 修改手机号弹窗 -->
<a-modal
v-model:visible="changePhoneModalVisible"
title="修改手机号"
@ok="handleChangePhoneSubmit"
@cancel="handleChangePhoneCancel"
:confirmLoading="changePhoneLoading"
>
<DraftActions
:saved-at="changePhoneDraftSavedAt"
@save="handleSaveChangePhoneDraft"
@clear="handleClearChangePhoneDraft"
/>
<a-form layout="vertical">
<a-form-item label="旧手机号">
<a-input :value="userInfo.phone" disabled />
</a-form-item>
<a-form-item label="新手机号" name="newPhone">
<a-input
v-model:value="changePhoneForm.newPhone"
placeholder="请输入新手机号"
/>
</a-form-item>
<a-form-item label="验证码" name="verificationCode">
<a-input
v-model:value="changePhoneForm.verificationCode"
placeholder="请输入验证码"
>
<template #suffix>
<a-button
type="link"
:disabled="countdown > 0 || !changePhoneForm.newPhone"
@click="handleSendChangePhoneVerificationCode"
>
{{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
</a-button>
</template>
</a-input>
</a-form-item>
</a-form>
</a-modal>
<!-- 修改密码弹窗 -->
<a-modal
v-model:visible="changePasswordModalVisible"
title="修改密码"
@ok="handleChangePasswordSubmit"
@cancel="handleChangePasswordCancel"
:confirmLoading="changePasswordLoading"
>
<DraftActions
:saved-at="changePasswordDraftSavedAt"
@save="handleSaveChangePasswordDraft"
@clear="handleClearChangePasswordDraft"
/>
<a-form layout="vertical">
<a-form-item label="手机号">
<a-input :value="userInfo.phone" disabled />
</a-form-item>
<a-form-item label="验证码" name="verificationCode">
<a-input
v-model:value="changePasswordForm.verificationCode"
placeholder="请输入验证码"
>
<template #suffix>
<a-button
type="link"
:disabled="countdown > 0"
@click="handleSendChangePasswordVerificationCode"
>
{{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
</a-button>
</template>
</a-input>
</a-form-item>
<a-form-item label="新密码" name="password">
<a-input-password
v-model:value="changePasswordForm.password"
placeholder="请输入新密码"
/>
<div class="password-tip">
密码长度至少8位,包含字母和数字
</div>
</a-form-item>
<a-form-item label="确认密码" name="confirmPassword">
<a-input-password
v-model:value="changePasswordForm.confirmPassword"
placeholder="请再次输入新密码"
/>
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script setup lang="ts">
/**
* AccountSettingsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined, RightOutlined, LockOutlined, PhoneOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import DraftActions from '@/components/DraftActions.vue'
import { userApi } from '@/api/user'
import type { UserVO } from '@/api/user'
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
import { runWithGlobalLoading } from '@/utils/action-loading'
/**
* Purpose: router supports AccountSettingsView.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()
// 用户信息
const userInfo = ref<UserVO>({
id: 0,
nickname: '',
account: '',
avatar: '',
type: 0,
status: 0,
createTime: '',
updateTime: ''
})
// 状态标识
/** hasPassword is a reactive state variable used by the template and event handlers. */
const hasPassword = ref(false)
/** hasPhone is a reactive state variable used by the template and event handlers. */
const hasPhone = ref(false)
// 绑定手机号表单
/** bindPhoneModalVisible is a reactive state variable used by the template and event handlers. */
const bindPhoneModalVisible = ref(false)
/** bindPhoneLoading is a reactive state variable used by the template and event handlers. */
const bindPhoneLoading = ref(false)
/**
* Purpose: bindPhoneDraftSavedAt supports AccountSettingsView.vue by holding or executing the bind phone draft saved at 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 bindPhoneDraftSavedAt = ref<number | null>(null)
/**
* Purpose: bindPhoneForm supports AccountSettingsView.vue by holding or executing the bind phone form 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 bindPhoneForm = reactive({
phone: '',
verificationCode: ''
})
// 修改手机号表单
/** changePhoneModalVisible is a reactive state variable used by the template and event handlers. */
const changePhoneModalVisible = ref(false)
/** changePhoneLoading is a reactive state variable used by the template and event handlers. */
const changePhoneLoading = ref(false)
/**
* Purpose: changePhoneDraftSavedAt supports AccountSettingsView.vue by holding or executing the change phone draft saved at 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 changePhoneDraftSavedAt = ref<number | null>(null)
/**
* Purpose: changePhoneForm supports AccountSettingsView.vue by holding or executing the change phone form 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 changePhoneForm = reactive({
newPhone: '',
verificationCode: ''
})
// 修改密码表单
/** changePasswordModalVisible is a reactive state variable used by the template and event handlers. */
const changePasswordModalVisible = ref(false)
/** changePasswordLoading is a reactive state variable used by the template and event handlers. */
const changePasswordLoading = ref(false)
/**
* Purpose: changePasswordDraftSavedAt supports AccountSettingsView.vue by holding or executing the change password draft saved at 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 changePasswordDraftSavedAt = ref<number | null>(null)
/**
* Purpose: changePasswordForm supports AccountSettingsView.vue by holding or executing the change password form 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 changePasswordForm = reactive({
verificationCode: '',
password: '',
confirmPassword: ''
})
/**
* Purpose: restoreSessionDraft supports AccountSettingsView.vue by holding or executing the restore session draft 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 restoreSessionDraft = <T extends Record<string, any>>(key: string, target: T, savedAtRef: typeof bindPhoneDraftSavedAt) => {
const draft = loadDraftRecord<T>(key, 'session')
if (!draft) {
savedAtRef.value = null
return
}
Object.assign(target, draft.payload)
savedAtRef.value = draft.savedAt
message.success('已恢复暂存内容')
}
/**
* Purpose: saveSessionDraft supports AccountSettingsView.vue by holding or executing the save session draft 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 saveSessionDraft = <T>(key: string, payload: T, savedAtRef: typeof bindPhoneDraftSavedAt, successMessage = '已暂存到当前会话') => {
const draft = saveDraftRecord(key, payload, 'session')
savedAtRef.value = draft.savedAt
message.success(successMessage)
}
/** clearSessionDraft is a local helper used by this page script. */
const clearSessionDraft = (key: string, savedAtRef: typeof bindPhoneDraftSavedAt, showMessage = true) => {
clearDraftRecord(key, 'session')
savedAtRef.value = null
if (showMessage) {
message.success('已清除暂存')
}
}
/**
* Purpose: bindPhoneDraftKey supports AccountSettingsView.vue by holding or executing the bind phone draft key 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 bindPhoneDraftKey = buildDraftStorageKey('account-settings', 'bind-phone')
/**
* Purpose: changePhoneDraftKey supports AccountSettingsView.vue by holding or executing the change phone draft key 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 changePhoneDraftKey = buildDraftStorageKey('account-settings', 'change-phone')
/**
* Purpose: changePasswordDraftKey supports AccountSettingsView.vue by holding or executing the change password draft key 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 changePasswordDraftKey = buildDraftStorageKey('account-settings', 'change-password')
/** handleSaveBindPhoneDraft is a local helper used by this page script. */
const handleSaveBindPhoneDraft = () => {
saveSessionDraft(bindPhoneDraftKey, { ...bindPhoneForm }, bindPhoneDraftSavedAt)
}
/** handleClearBindPhoneDraft is a local helper used by this page script. */
const handleClearBindPhoneDraft = (showMessage = true) => {
clearSessionDraft(bindPhoneDraftKey, bindPhoneDraftSavedAt, showMessage)
}
/** handleSaveChangePhoneDraft is a local helper used by this page script. */
const handleSaveChangePhoneDraft = () => {
saveSessionDraft(changePhoneDraftKey, { ...changePhoneForm }, changePhoneDraftSavedAt)
}
/** handleClearChangePhoneDraft is a local helper used by this page script. */
const handleClearChangePhoneDraft = (showMessage = true) => {
clearSessionDraft(changePhoneDraftKey, changePhoneDraftSavedAt, showMessage)
}
/** handleSaveChangePasswordDraft is a local helper used by this page script. */
const handleSaveChangePasswordDraft = () => {
saveSessionDraft(changePasswordDraftKey, { ...changePasswordForm }, changePasswordDraftSavedAt)
}
/** handleClearChangePasswordDraft is a local helper used by this page script. */
const handleClearChangePasswordDraft = (showMessage = true) => {
clearSessionDraft(changePasswordDraftKey, changePasswordDraftSavedAt, showMessage)
}
// 倒计时
/** countdown is a reactive state variable used by the template and event handlers. */
const countdown = ref(0)
// 账号设置选项
/** accountSettings is a reactive state variable used by the template and event handlers. */
const accountSettings = ref([
{
key: 'changePhone',
title: '修改手机号',
icon: PhoneOutlined,
bgColor: '#e6f7ff'
},
{
key: 'changePassword',
title: '修改密码',
icon: LockOutlined,
bgColor: '#f6ffed'
},
{
key: 'deactivateAccount',
title: '注销账号',
icon: LockOutlined,
bgColor: '#fff1f0'
}
])
// 根据用户状态动态更新账号设置选项
/** updateAccountSettings is a local helper used by this page script. */
const updateAccountSettings = () => {
const settings = []
// 手机号相关
if (!hasPhone.value) {
settings.push({
key: 'bindPhone',
title: '绑定手机号',
icon: PhoneOutlined,
bgColor: '#e6f7ff'
})
} else {
settings.push({
key: 'changePhone',
title: '修改手机号',
icon: PhoneOutlined,
bgColor: '#e6f7ff'
})
}
// 密码相关
if (!hasPassword.value) {
settings.push({
key: 'setPassword',
title: '设置密码',
icon: LockOutlined,
bgColor: '#fff7e6'
})
} else {
settings.push({
key: 'changePassword',
title: '修改密码',
icon: LockOutlined,
bgColor: '#f6ffed'
})
}
// 注销账号
settings.push({
key: 'deactivateAccount',
title: '注销账号',
icon: LockOutlined,
bgColor: '#fff1f0'
})
accountSettings.value = settings
}
// 获取用户信息
/** fetchUserInfo is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUserInfo = async () => {
try {
const response = await userApi.getUserInfo() as any
userInfo.value = response
// 检查是否绑定手机号
hasPhone.value = !!userInfo.value.phone
// 检查是否设置密码(通过localStorage中的标识)
hasPassword.value = localStorage.getItem('needSetPassword') !== 'true'
// 更新账号设置选项
updateAccountSettings()
} catch (error) {
console.error('获取用户信息失败:', error)
message.error('获取用户信息失败')
}
}
// 处理返回
/** handleBackClick is a local helper used by this page script. */
const handleBackClick = () => {
router.back()
}
// 处理设置项点击
/** handleSettingClick is a local helper used by this page script. */
const handleSettingClick = (key: string) => {
switch (key) {
case 'bindPhone':
restoreSessionDraft(bindPhoneDraftKey, bindPhoneForm, bindPhoneDraftSavedAt)
bindPhoneModalVisible.value = true
break
case 'changePhone':
restoreSessionDraft(changePhoneDraftKey, changePhoneForm, changePhoneDraftSavedAt)
changePhoneModalVisible.value = true
break
case 'setPassword':
handleSetPassword()
break
case 'changePassword':
restoreSessionDraft(changePasswordDraftKey, changePasswordForm, changePasswordDraftSavedAt)
changePasswordModalVisible.value = true
break
case 'deactivateAccount':
handleDeactivateAccount()
break
default:
break
}
}
// 处理设置密码
/** handleSetPassword is a local helper used by this page script. */
const handleSetPassword = () => {
router.push('/settings/password')
}
// 发送绑定手机号验证码
/** handleSendVerificationCode is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSendVerificationCode = async () => {
if (!bindPhoneForm.phone) {
message.error('请输入手机号')
return
}
const phoneRegex = /^1[3-9]\d{9}$/
if (!phoneRegex.test(bindPhoneForm.phone)) {
message.error('手机号格式不正确')
return
}
try {
await runWithGlobalLoading(() => userApi.sendVerificationCode({
phone: bindPhoneForm.phone,
sceneCode: 'USER_BIND_PHONE_SMS_CODE'
}))
message.success('验证码发送成功')
startCountdown()
} catch (error) {
console.error('发送验证码失败:', error)
message.error('发送验证码失败')
}
}
// 发送修改手机号验证码
/** handleSendChangePhoneVerificationCode is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSendChangePhoneVerificationCode = async () => {
if (!changePhoneForm.newPhone) {
message.error('请输入新手机号')
return
}
const phoneRegex = /^1[3-9]\d{9}$/
if (!phoneRegex.test(changePhoneForm.newPhone)) {
message.error('手机号格式不正确')
return
}
try {
await runWithGlobalLoading(() => userApi.sendVerificationCode({
phone: changePhoneForm.newPhone,
sceneCode: 'USER_CHANGE_PHONE_SMS_CODE'
}))
message.success('验证码发送成功')
startCountdown()
} catch (error) {
console.error('发送验证码失败:', error)
message.error('发送验证码失败')
}
}
// 发送修改密码验证码
/** handleSendChangePasswordVerificationCode is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSendChangePasswordVerificationCode = async () => {
if (!userInfo.value.phone) {
message.error('请先绑定手机号')
return
}
const phone = userInfo.value.phone
const phoneRegex = /^1[3-9]\d{9}$/
if (!phoneRegex.test(phone)) {
message.error('手机号格式不正确')
return
}
try {
await runWithGlobalLoading(() => userApi.sendVerificationCode({
phone,
sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE'
}))
message.success('验证码发送成功')
startCountdown()
} catch (error) {
console.error('发送验证码失败:', error)
message.error('发送验证码失败')
}
}
// 开始倒计时
/** startCountdown is a local helper used by this page script. */
const startCountdown = () => {
countdown.value = 60
const timer = setInterval(() => {
countdown.value--
if (countdown.value <= 0) {
clearInterval(timer)
}
}, 1000)
}
// 处理绑定手机号提交
/** handleBindPhoneSubmit is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleBindPhoneSubmit = async () => {
if (!bindPhoneForm.phone || !bindPhoneForm.verificationCode) {
message.error('请填写完整信息')
return
}
bindPhoneLoading.value = true
try {
await runWithGlobalLoading(async () => {
await userApi.bindPhone({
phone: bindPhoneForm.phone,
verificationCode: bindPhoneForm.verificationCode
})
await fetchUserInfo()
})
message.success('手机号绑定成功')
handleClearBindPhoneDraft(false)
bindPhoneModalVisible.value = false
} catch (error: any) {
console.error('绑定手机号失败:', error)
message.error(error.message || '绑定手机号失败')
} finally {
bindPhoneLoading.value = false
}
}
// 处理绑定手机号取消
/** handleBindPhoneCancel is a local helper used by this page script. */
const handleBindPhoneCancel = () => {
bindPhoneModalVisible.value = false
bindPhoneForm.phone = ''
bindPhoneForm.verificationCode = ''
}
// 处理修改手机号提交
/** handleChangePhoneSubmit is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleChangePhoneSubmit = async () => {
if (!changePhoneForm.newPhone || !changePhoneForm.verificationCode) {
message.error('请填写完整信息')
return
}
changePhoneLoading.value = true
try {
await runWithGlobalLoading(async () => {
await userApi.updatePhone({
oldPhone: userInfo.value.phone!,
newPhone: changePhoneForm.newPhone,
verificationCode: changePhoneForm.verificationCode
})
await fetchUserInfo()
})
message.success('手机号修改成功')
handleClearChangePhoneDraft(false)
changePhoneModalVisible.value = false
} catch (error: any) {
console.error('修改手机号失败:', error)
message.error(error.message || '修改手机号失败')
} finally {
changePhoneLoading.value = false
}
}
// 处理修改手机号取消
/** handleChangePhoneCancel is a local helper used by this page script. */
const handleChangePhoneCancel = () => {
changePhoneModalVisible.value = false
changePhoneForm.newPhone = ''
changePhoneForm.verificationCode = ''
}
// 处理修改密码提交
/** handleChangePasswordSubmit is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleChangePasswordSubmit = async () => {
if (!changePasswordForm.verificationCode || !changePasswordForm.password || !changePasswordForm.confirmPassword) {
message.error('请填写完整信息')
return
}
if (changePasswordForm.password !== changePasswordForm.confirmPassword) {
message.error('两次输入的密码不一致')
return
}
changePasswordLoading.value = true
try {
await runWithGlobalLoading(() => userApi.updatePassword({
password: changePasswordForm.password,
verificationCode: changePasswordForm.verificationCode
}))
message.success('密码修改成功')
handleClearChangePasswordDraft(false)
changePasswordModalVisible.value = false
// 清除需要设置密码的标识
localStorage.removeItem('needSetPassword')
hasPassword.value = true
updateAccountSettings()
} catch (error: any) {
console.error('修改密码失败:', error)
message.error(error.message || '修改密码失败')
} finally {
changePasswordLoading.value = false
}
}
// 处理修改密码取消
/** handleChangePasswordCancel is a local helper used by this page script. */
const handleChangePasswordCancel = () => {
changePasswordModalVisible.value = false
changePasswordForm.verificationCode = ''
changePasswordForm.password = ''
changePasswordForm.confirmPassword = ''
}
// 处理注销账号
/** handleDeactivateAccount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleDeactivateAccount = async () => {
Modal.confirm({
title: '确认注销账号',
content: '注销账号后,您的所有数据将被删除且无法恢复。确定要注销账号吗?',
okText: '确认注销',
okType: 'danger',
cancelText: '取消',
onOk: async () => {
await runWithGlobalLoading(async () => {
try {
await userApi.deactivateAccount()
message.success('账号注销成功')
} catch (error) {
console.error('注销账号失败:', error)
message.error('注销账号失败')
} finally {
// 无论成功或失败,都清除本地存储的用户信息
localStorage.removeItem('accessToken')
localStorage.removeItem('refreshToken')
localStorage.removeItem('userInfo')
localStorage.removeItem('needSetPassword')
localStorage.removeItem('userPermissions')
sessionStorage.removeItem('accessToken')
// 跳转到登录页
router.push('/')
}
})
}
})
}
// 生命周期
onMounted(() => {
fetchUserInfo()
})
</script>
<style scoped>
.mobile-container {
min-height: 100vh;
background: var(--theme-page-bg);
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 15px;
background: var(--theme-card-bg);
border-bottom: 1px solid var(--theme-border);
}
.header h1 {
font-size: 18px;
font-weight: bold;
margin: 0;
}
.back-btn,
.empty {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
}
.account-settings {
padding: 15px;
}
.status-tips {
margin-bottom: 15px;
}
.settings-card {
border-radius: 16px;
overflow: hidden;
background: var(--theme-card-bg);
}
.settings-card :deep(.ant-card-body) {
padding: 0;
}
.setting-item {
padding: 16px;
cursor: pointer;
transition: background 0.3s;
border-bottom: 1px solid var(--theme-border);
}
.setting-item:hover {
background: var(--theme-primary-soft);
}
.setting-item:last-child {
border-bottom: none;
}
.setting-item :deep(.ant-list-item-action) {
margin-left: 8px;
color: var(--text-secondary);
}
.setting-icon {
width: 40px;
height: 40px;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
color: white;
}
.setting-item :deep(.ant-list-item-meta-title) {
font-size: 15px;
font-weight: 500;
color: var(--text-primary);
}
.setting-item :deep(.ant-list-item-meta-description) {
font-size: 12px;
color: var(--text-secondary);
}
.password-tip {
font-size: 12px;
color: var(--text-secondary);
margin-top: 8px;
}
</style>
@@ -0,0 +1,141 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { afterSaleApi, orderApi } from '../api/order'
import type { IdType } from '@/utils/id'
import { runWithGlobalLoading } from '@/utils/action-loading'
const route = useRoute()
const router = useRouter()
const loading = ref(false)
const submitting = ref(false)
const order = ref<any | null>(null)
const orderId = computed(() => String(route.query.orderId || ''))
const items = computed(() => Array.isArray(order.value?.items) ? order.value.items : [])
const form = reactive({
orderItemId: undefined as IdType | undefined,
type: 'REFUND',
reason: '',
refundAmount: undefined as number | undefined
})
const formatMoney = (value?: number | string) => {
const amount = Number(value)
return Number.isFinite(amount) ? `¥${amount.toFixed(2)}` : '¥0.00'
}
const loadOrder = async () => {
if (!orderId.value) return
loading.value = true
try {
order.value = await orderApi.getOrderDetail(orderId.value)
const preferredItemId = String(route.query.orderItemId || '')
const firstItem = items.value.find((item: any) => String(item.id) === preferredItemId) || items.value[0]
form.orderItemId = firstItem?.id
form.refundAmount = Number(order.value?.actualAmount || order.value?.totalAmount || 0)
} catch (error: any) {
message.error(error?.message || '订单信息加载失败')
} finally {
loading.value = false
}
}
const submit = async () => {
if (!orderId.value) {
message.warning('缺少订单信息')
return
}
if (!form.reason.trim()) {
message.warning('请填写售后原因')
return
}
submitting.value = true
try {
await runWithGlobalLoading(() => afterSaleApi.apply({
orderId: orderId.value,
orderItemId: form.orderItemId,
type: form.type,
reason: form.reason.trim(),
refundAmount: form.refundAmount
}))
message.success('售后申请已提交')
router.replace({ path: '/after-sales', query: { orderId: orderId.value } })
} catch (error: any) {
message.error(error?.message || '售后申请提交失败')
} finally {
submitting.value = false
}
}
onMounted(loadOrder)
</script>
<template>
<div class="apply-page">
<header class="header">
<a-button type="text" @click="router.back()">
<LeftOutlined />
</a-button>
<h1>申请售后</h1>
<a-button type="link" @click="router.push('/after-sales')">记录</a-button>
</header>
<main class="content">
<section class="hero-card">
<span>售后申请</span>
<h2>{{ order?.orderNo || (orderId ? `订单 ${orderId}` : '选择订单') }}</h2>
<p>{{ order ? `可申请金额 ${formatMoney(order.actualAmount || order.totalAmount)}` : '从订单详情或订单中心进入可自动带入订单信息' }}</p>
</section>
<a-spin :spinning="loading">
<a-empty v-if="!orderId" description="缺少订单参数">
<a-button type="primary" @click="router.push('/orders')">选择订单</a-button>
</a-empty>
<section v-else class="form-card">
<a-form layout="vertical">
<a-form-item label="订单项目">
<a-select v-model:value="form.orderItemId" allow-clear placeholder="默认整单">
<a-select-option v-for="item in items" :key="item.id" :value="item.id">
{{ item.productTitle || `项目 ${item.id}` }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="售后类型" required>
<a-select v-model:value="form.type">
<a-select-option value="REFUND">退款</a-select-option>
<a-select-option value="AFTER_SALE">售后服务</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="退款金额">
<a-input-number v-model:value="form.refundAmount" :min="0" :step="0.01" style="width: 100%" />
</a-form-item>
<a-form-item label="原因说明" required>
<a-textarea v-model:value="form.reason" :rows="5" :maxlength="300" placeholder="请说明退款或售后原因" />
</a-form-item>
<a-button type="primary" block :loading="submitting" @click="submit">提交申请</a-button>
</a-form>
</section>
</a-spin>
</main>
</div>
</template>
<style scoped>
.apply-page { min-height: 100vh; padding-top: 60px; background: var(--theme-page-bg); color: var(--text-primary); }
.header { position: fixed; top: 0; left: 0; right: 0; z-index: 10; display: flex; align-items: center; justify-content: space-between; height: 60px; padding: 9px 14px; background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent); border-bottom: 1px solid var(--theme-border); backdrop-filter: blur(14px); }
.header h1 { margin: 0; font-size: 18px; }
.content { padding: 16px 14px 32px; }
.hero-card, .form-card { border: 1px solid var(--theme-border); border-radius: 20px; background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent); box-shadow: 0 18px 44px rgba(74, 68, 63, 0.08); }
.hero-card { padding: 22px; margin-bottom: 14px; background: var(--theme-gradient-soft); }
.hero-card span { color: var(--theme-primary); font-size: 12px; font-weight: 700; letter-spacing: .05em; }
.hero-card h2 { margin: 10px 0 6px; font-size: 21px; }
.hero-card p { margin: 0; color: var(--text-secondary); line-height: 1.6; }
.form-card { padding: 16px; }
:deep(.ant-btn-primary) { background: var(--theme-primary); border-color: var(--theme-primary); }
:deep(.ant-btn-link) { color: var(--theme-primary); }
:deep(.ant-input:focus), :deep(.ant-input-focused), :deep(.ant-select-focused .ant-select-selector) { border-color: var(--theme-primary) !important; box-shadow: var(--theme-focus-shadow) !important; }
</style>
@@ -0,0 +1,122 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { afterSaleApi, type AfterSaleVO } from '../api/order'
const route = useRoute()
const router = useRouter()
const loading = ref(false)
const records = ref<AfterSaleVO[]>([])
const focusOrderId = computed(() => String(route.query.orderId || ''))
const focusedRecords = computed(() => {
if (!focusOrderId.value) return records.value
return records.value.filter(item => String(item.orderId) === focusOrderId.value)
})
const statusText = (status?: string) => {
if (status === 'PENDING') return '审核中'
if (status === 'APPROVED') return '已通过'
if (status === 'REJECTED') return '已拒绝'
return status || '处理中'
}
const typeText = (type?: string) => type === 'REFUND' ? '退款' : (type || '售后')
const formatMoney = (value?: number) => value === undefined || value === null ? '--' : `¥${Number(value).toFixed(2)}`
const formatTime = (value?: string) => value ? String(value).replace('T', ' ').slice(0, 16) : '--'
const loadRecords = async () => {
loading.value = true
try {
const page = await afterSaleApi.listMy({ page: 1, size: 50 })
records.value = page?.list || []
} catch (error: any) {
records.value = []
message.error(error?.message || '售后记录加载失败')
} finally {
loading.value = false
}
}
onMounted(loadRecords)
</script>
<template>
<div class="after-sales-page">
<header class="header">
<a-button type="text" @click="router.back()">
<LeftOutlined />
</a-button>
<h1>售后记录</h1>
<a-button type="link" @click="loadRecords">刷新</a-button>
</header>
<main class="content">
<section class="hero-card">
<span>售后服务</span>
<h2>{{ focusedRecords.length }} 条记录</h2>
<p>{{ focusOrderId ? `订单 ${focusOrderId} 的售后进度` : '查看退款、售后审核与处理说明' }}</p>
</section>
<a-spin :spinning="loading">
<a-empty v-if="!focusedRecords.length" description="暂无售后记录">
<a-button type="primary" @click="router.push('/orders')">查看订单</a-button>
</a-empty>
<article v-for="item in focusedRecords" :key="item.id" class="record-card">
<div class="record-head">
<div>
<span class="record-label">{{ typeText(item.type) }}</span>
<h3>{{ item.afterSaleNo || `售后 ${item.id}` }}</h3>
</div>
<strong>{{ statusText(item.status) }}</strong>
</div>
<dl>
<div>
<dt>订单</dt>
<dd>{{ item.orderId }}</dd>
</div>
<div>
<dt>金额</dt>
<dd>{{ formatMoney(item.refundAmount) }}</dd>
</div>
<div>
<dt>提交时间</dt>
<dd>{{ formatTime(item.createTime) }}</dd>
</div>
</dl>
<p v-if="item.reason">原因:{{ item.reason }}</p>
<p v-if="item.auditReason">处理说明:{{ item.auditReason }}</p>
<div class="actions">
<a-button size="small" @click="router.push(`/orders/${item.orderId}`)">订单详情</a-button>
<a-button size="small" @click="router.push({ path: '/service-progress', query: { orderId: String(item.orderId) } })">服务进度</a-button>
</div>
</article>
</a-spin>
</main>
</div>
</template>
<style scoped>
.after-sales-page { min-height: 100vh; padding-top: 60px; background: var(--theme-page-bg); color: var(--text-primary); }
.header { position: fixed; top: 0; left: 0; right: 0; z-index: 10; display: flex; align-items: center; justify-content: space-between; height: 60px; padding: 9px 14px; background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent); border-bottom: 1px solid var(--theme-border); backdrop-filter: blur(14px); }
.header h1 { margin: 0; font-size: 18px; }
.content { padding: 16px 14px 32px; }
.hero-card, .record-card { border: 1px solid var(--theme-border); border-radius: 20px; background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent); box-shadow: 0 18px 44px rgba(74, 68, 63, 0.08); }
.hero-card { padding: 22px; margin-bottom: 14px; background: var(--theme-gradient-soft); }
.hero-card span, .record-label { color: var(--theme-primary); font-size: 12px; font-weight: 700; letter-spacing: .05em; }
.hero-card h2 { margin: 10px 0 6px; font-size: 21px; }
.hero-card p, .record-card p { margin: 0; color: var(--text-secondary); line-height: 1.6; }
.record-card { padding: 16px; margin-top: 14px; }
.record-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
.record-head h3 { margin: 6px 0 0; font-size: 17px; }
.record-head strong { flex: 0 0 auto; padding: 6px 12px; border-radius: 999px; background: var(--theme-primary-soft); color: var(--theme-primary); font-size: 12px; }
dl { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; margin: 14px 0; }
dt { color: var(--text-secondary); font-size: 12px; }
dd { margin: 4px 0 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 700; }
.actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 14px; }
:deep(.ant-btn-primary) { background: var(--theme-primary); border-color: var(--theme-primary); }
:deep(.ant-btn-link) { color: var(--theme-primary); }
</style>
@@ -0,0 +1,340 @@
<script setup lang="ts">
import { computed, ref, shallowRef, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
CalendarOutlined,
LeftOutlined,
RightOutlined,
StarFilled,
UserOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { nailArtistApi, type NailArtistListItemVO } from '@/api/nail-artist'
const route = useRoute()
const router = useRouter()
const artists = ref<NailArtistListItemVO[]>([])
const loading = shallowRef(false)
const loadError = shallowRef('')
const shopId = computed(() => String(route.params.shopId || ''))
const pageTitle = computed(() => String(route.query.shopName || '美甲师'))
const formatRating = (value?: number | string) => {
const rating = Number(value || 0)
return rating > 0 ? rating.toFixed(1) : '暂无'
}
const parseSkillTags = (skills?: string) => {
return String(skills || '')
.split(/[,;,;、\s]+/)
.map(tag => tag.trim())
.filter(Boolean)
.slice(0, 4)
}
const formatWorkTime = (artist: NailArtistListItemVO) => {
const start = String(artist.workStartTime || '').slice(0, 5)
const end = String(artist.workEndTime || '').slice(0, 5)
return start && end ? `${start}-${end}` : '到店确认'
}
const displayName = (artist: NailArtistListItemVO) => artist.nickname || artist.identity || '美甲师'
const openArtist = (artist: NailArtistListItemVO) => {
const artistId = artist.userId
if (!artistId) {
message.info('美甲师信息暂未完善')
return
}
router.push(`/artist/${artistId}`)
}
const loadArtists = async () => {
if (!shopId.value) {
loadError.value = '缺少店铺信息'
return
}
loading.value = true
loadError.value = ''
try {
artists.value = await nailArtistApi.listByShopId(shopId.value)
} catch (error) {
loadError.value = error instanceof Error ? error.message : '美甲师列表加载失败'
message.error(loadError.value)
} finally {
loading.value = false
}
}
watch(shopId, loadArtists, { immediate: true })
</script>
<template>
<div class="artist-list-page">
<header class="artist-list-topbar">
<a-button class="nav-button" type="text" aria-label="返回" @click="router.back()">
<LeftOutlined />
</a-button>
<h1>{{ pageTitle }}</h1>
<span class="topbar-count">{{ artists.length }} 位</span>
</header>
<main class="artist-list-body">
<a-spin :spinning="loading">
<a-result v-if="loadError" status="warning" title="暂时无法查看美甲师" :sub-title="loadError">
<template #extra>
<a-button type="primary" @click="loadArtists">重试</a-button>
</template>
</a-result>
<template v-else>
<section class="list-summary">
<span>Artists</span>
<h2>本店美甲师</h2>
<p>选择熟悉的美甲师进入主页,查看作品、评价和近期可预约时间。</p>
</section>
<div v-if="artists.length" class="artist-cards">
<button
v-for="artist in artists"
:key="artist.userId || artist.id"
class="artist-card"
type="button"
@click="openArtist(artist)"
>
<a-avatar :size="56" class="artist-avatar">
<UserOutlined />
</a-avatar>
<div class="artist-copy">
<div class="artist-heading">
<strong>{{ displayName(artist) }}</strong>
<span :class="['status-chip', artist.status === 1 ? 'status-chip--active' : '']">
{{ artist.status === 1 ? '可预约' : '休息中' }}
</span>
</div>
<p>{{ artist.signature || artist.identity || '专注细节与稳定出品' }}</p>
<div class="artist-meta">
<span><StarFilled /> {{ formatRating(artist.rating) }}</span>
<span><CalendarOutlined /> {{ formatWorkTime(artist) }}</span>
</div>
<div v-if="parseSkillTags(artist.skills).length" class="tag-row">
<span v-for="tag in parseSkillTags(artist.skills)" :key="tag">{{ tag }}</span>
</div>
</div>
<RightOutlined class="card-arrow" />
</button>
</div>
<a-empty v-else class="empty-state" description="本店暂未配置可展示的美甲师" />
</template>
</a-spin>
</main>
</div>
</template>
<style scoped>
.artist-list-page {
min-height: 100vh;
background:
radial-gradient(circle at 18% 0%, rgba(232, 180, 184, 0.28), transparent 34%),
var(--theme-page-bg);
color: var(--text-primary);
}
.artist-list-topbar {
position: sticky;
top: 0;
z-index: 20;
display: grid;
grid-template-columns: 44px minmax(0, 1fr) 52px;
align-items: center;
height: 58px;
max-width: 960px;
margin: 0 auto;
padding: 0 14px;
background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent);
border-bottom: 1px solid var(--theme-border);
backdrop-filter: blur(14px);
}
.nav-button {
width: 40px;
height: 40px;
}
.artist-list-topbar h1 {
margin: 0;
overflow: hidden;
font-size: 17px;
font-weight: 700;
text-align: center;
text-overflow: ellipsis;
white-space: nowrap;
}
.topbar-count {
color: var(--text-secondary);
font-size: 13px;
text-align: right;
}
.artist-list-body {
max-width: 960px;
margin: 0 auto;
padding: 18px 14px 36px;
}
.list-summary {
padding: 20px;
background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent);
border: 1px solid color-mix(in srgb, var(--theme-border) 78%, transparent);
border-radius: 16px;
box-shadow: 0 16px 40px rgba(124, 83, 87, 0.08);
backdrop-filter: blur(18px);
}
.list-summary span {
color: var(--theme-primary);
font-size: 12px;
font-weight: 700;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.list-summary h2 {
margin: 8px 0;
font-size: 22px;
line-height: 1.2;
}
.list-summary p {
margin: 0;
color: var(--text-secondary);
line-height: 1.7;
}
.artist-cards {
display: grid;
gap: 12px;
margin-top: 16px;
}
.artist-card {
display: grid;
grid-template-columns: 56px minmax(0, 1fr) 18px;
gap: 14px;
align-items: center;
width: 100%;
padding: 16px;
color: inherit;
text-align: left;
cursor: pointer;
background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent);
border: 1px solid color-mix(in srgb, var(--theme-border) 82%, transparent);
border-radius: 16px;
box-shadow: 0 12px 28px rgba(124, 83, 87, 0.06);
}
.artist-avatar {
color: var(--theme-primary);
background: var(--theme-primary-soft);
border: 2px solid #fff;
}
.artist-copy {
min-width: 0;
}
.artist-heading {
display: flex;
gap: 8px;
align-items: center;
justify-content: space-between;
}
.artist-heading strong {
overflow: hidden;
font-size: 17px;
text-overflow: ellipsis;
white-space: nowrap;
}
.status-chip {
flex: 0 0 auto;
padding: 4px 8px;
color: var(--text-secondary);
font-size: 12px;
background: color-mix(in srgb, var(--theme-card-bg) 70%, var(--theme-primary-soft));
border-radius: 999px;
}
.status-chip--active {
color: var(--theme-primary);
background: var(--theme-primary-soft);
}
.artist-copy p {
display: -webkit-box;
margin: 6px 0 10px;
overflow: hidden;
color: var(--text-secondary);
font-size: 13px;
line-height: 1.5;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
}
.artist-meta,
.tag-row {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.artist-meta span {
display: inline-flex;
gap: 4px;
align-items: center;
color: var(--text-secondary);
font-size: 12px;
}
.artist-meta svg {
color: var(--theme-primary);
}
.tag-row {
margin-top: 10px;
}
.tag-row span {
padding: 4px 8px;
color: var(--theme-primary);
font-size: 12px;
background: var(--theme-primary-soft);
border-radius: 999px;
}
.card-arrow {
color: var(--text-secondary);
font-size: 12px;
}
.empty-state {
margin-top: 48px;
}
@media (max-width: 640px) {
.artist-list-body {
padding: 14px 12px 30px;
}
.artist-card {
grid-template-columns: 52px minmax(0, 1fr) 16px;
gap: 12px;
padding: 14px;
}
}
</style>
@@ -0,0 +1,951 @@
<script setup lang="ts">
import { computed, onMounted, ref, shallowRef } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
CalendarOutlined,
HeartOutlined,
LeftOutlined,
MessageOutlined,
SafetyCertificateOutlined,
ShareAltOutlined,
ShopOutlined,
StarFilled,
UserOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { DEFAULT_PRODUCT_IMAGE } from '@/constants'
import {
getPublicImageFileIds,
refreshPublicImageUrl,
resolvePublicImageUrl,
resolvePublicImageUrlsSync
} from '@/utils/public-image-assets'
import {
nailArtistApi,
type NailArtistAvailabilityVO,
type NailArtistProfileVO,
type NailArtistReviewVO,
type NailArtistWorkVO
} from '@/api/nail-artist'
import { productApi, type ProductVO } from '@/api/product'
const route = useRoute()
const router = useRouter()
const profile = shallowRef<NailArtistProfileVO | null>(null)
const workImageUrls = ref<Record<string, string>>({})
const reviews = ref<NailArtistReviewVO[]>([])
const availability = ref<NailArtistAvailabilityVO[]>([])
const loading = shallowRef(false)
const loadError = shallowRef('')
const selectedDate = shallowRef('')
const workFilter = shallowRef('全部')
const artistId = computed(() => String(route.params.id || ''))
const artistName = computed(() => profile.value?.artistName || '美甲师')
const ratingValue = computed(() => Number(profile.value?.rating || 0))
const ratingText = computed(() => ratingValue.value > 0 ? ratingValue.value.toFixed(1) : '暂无')
const serviceCountText = computed(() => formatCompactNumber(Number(profile.value?.serviceCount || 0)))
const goodRateText = computed(() => ratingValue.value > 0 ? `${Math.min(99, Math.round((ratingValue.value / 5) * 100))}%` : '暂无')
const works = computed<NailArtistWorkVO[]>(() => profile.value?.works || [])
const styleTags = computed(() => profile.value?.styleTags?.filter(Boolean) || [])
const firstWorkImage = computed(() => {
const firstWork = works.value.find(work => getWorkImage(work) !== DEFAULT_PRODUCT_IMAGE)
return firstWork ? getWorkImage(firstWork) : DEFAULT_PRODUCT_IMAGE
})
const workTimeText = computed(() => {
const start = profile.value?.workStartTime?.slice(0, 5)
const end = profile.value?.workEndTime?.slice(0, 5)
return start && end ? `${start}-${end}` : '到店确认'
})
const availabilityGroups = computed(() => {
const groupMap = new Map<string, NailArtistAvailabilityVO[]>()
availability.value
.filter(slot => slot.available !== false)
.forEach(slot => {
const date = slot.dateText || String(slot.startTime || '').slice(0, 10)
if (!date) return
const slots = groupMap.get(date) || []
slots.push(slot)
groupMap.set(date, slots)
})
return Array.from(groupMap.entries()).map(([date, slots]) => ({
date,
label: formatDateLabel(date),
week: formatWeekLabel(date),
slots
}))
})
const selectedDateSlots = computed(() => {
return availabilityGroups.value.find(group => group.date === selectedDate.value)?.slots || []
})
const workFilterOptions = computed(() => {
const tags = new Set<string>()
works.value.forEach(work => work.tags?.filter(Boolean).forEach(tag => tags.add(tag)))
return ['全部', ...Array.from(tags).slice(0, 5)]
})
const filteredWorks = computed(() => {
if (workFilter.value === '全部') {
return works.value
}
return works.value.filter(work => work.tags?.includes(workFilter.value))
})
const PROFILE_WORK_LIMIT = 20
const certificationText = computed(() => {
const identity = profile.value?.identity || '认证美甲师'
const experience = Number(profile.value?.experience || 0)
return experience > 0 ? `${identity} · ${experience} 年经验` : identity
})
function formatCompactNumber(value: number) {
if (value >= 1000) {
return `${(value / 1000).toFixed(1)}k+`
}
return String(value || 0)
}
function formatDateLabel(dateText: string) {
const date = new Date(`${dateText}T00:00:00`)
if (Number.isNaN(date.getTime())) {
return dateText
}
return `${date.getMonth() + 1}.${date.getDate()}`
}
function formatWeekLabel(dateText: string) {
const date = new Date(`${dateText}T00:00:00`)
if (Number.isNaN(date.getTime())) {
return '可约'
}
const today = new Date()
today.setHours(0, 0, 0, 0)
const diffDays = Math.round((date.getTime() - today.getTime()) / 86400000)
if (diffDays === 0) return '今天'
if (diffDays === 1) return '明天'
return ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()]
}
const formatDateTime = (value?: string) => {
if (!value) {
return ''
}
return value.replace('T', ' ').slice(0, 16)
}
const roundedRating = (value?: number | string) => Math.round(Number(value || 0))
const openProduct = (work: NailArtistWorkVO) => {
if (!work.id) {
return
}
router.push(`/product/${work.id}`)
}
const getWorkImage = (work: NailArtistWorkVO) => workImageUrls.value[String(work.id)] || work.coverImageUrl || DEFAULT_PRODUCT_IMAGE
const isArtistBookableForProduct = (product: ProductVO) => {
const ids = String(product.bookableArtists || '')
.split(',')
.map(id => id.trim())
.filter(Boolean)
return ids.includes(artistId.value)
}
const mapProductToWork = (product: ProductVO): NailArtistWorkVO & { imageFileIds?: string } => ({
id: product.id,
title: product.title || product.name,
description: product.description,
price: product.price,
imageUrls: product.imageUrls,
imageFileIds: product.imageFileIds,
tags: product.tagList || product.tags?.split(/[;,,、]/).map(tag => tag.trim()).filter(Boolean),
likeCount: product.likeCount,
collectCount: product.collectCount
})
const loadSupplementWorks = async (existingWorks: NailArtistWorkVO[]): Promise<NailArtistWorkVO[]> => {
if (existingWorks.length >= PROFILE_WORK_LIMIT) {
return existingWorks.slice(0, PROFILE_WORK_LIMIT)
}
const existingIds = new Set(existingWorks.map(work => String(work.id)))
const products = await productApi.getAllProducts().catch(() => [])
const supplementWorks = products
.filter(product => !existingIds.has(String(product.id)))
.filter(product => !profile.value?.shopId || String(product.shopId || '') === String(profile.value.shopId))
.filter(isArtistBookableForProduct)
.slice(0, PROFILE_WORK_LIMIT - existingWorks.length)
.map(mapProductToWork)
return [...existingWorks, ...supplementWorks]
}
const loadWorkImages = async (nextWorks: NailArtistWorkVO[]) => {
const entries = await Promise.all(nextWorks.map(async work => {
const cachedUrls = resolvePublicImageUrlsSync(work as NailArtistWorkVO & Record<string, unknown>, '')
const imageUrl = cachedUrls[0] || await resolvePublicImageUrl(work as NailArtistWorkVO & Record<string, unknown>, DEFAULT_PRODUCT_IMAGE)
return [String(work.id), imageUrl] as const
}))
workImageUrls.value = Object.fromEntries(entries)
}
const handleWorkImageError = async (work: NailArtistWorkVO) => {
const fileId = getPublicImageFileIds(work as NailArtistWorkVO & Record<string, unknown>)[0]
const imageUrl = fileId ? await refreshPublicImageUrl(fileId, DEFAULT_PRODUCT_IMAGE) : DEFAULT_PRODUCT_IMAGE
workImageUrls.value = { ...workImageUrls.value, [String(work.id)]: imageUrl }
}
const openShop = () => {
if (!profile.value?.shopId) {
message.info('门店信息暂未完善')
return
}
router.push(`/shop/${profile.value.shopId}`)
}
const handleBookNow = () => {
const firstWork = works.value[0]
if (firstWork?.id) {
openProduct(firstWork)
return
}
openShop()
}
const handleConsult = () => {
if (profile.value?.shopId) {
router.push(`/shop/${profile.value.shopId}`)
return
}
message.info('请先选择作品后联系门店')
}
const handleShare = async () => {
const shareTitle = `${artistName.value}的美甲师主页`
const shareUrl = window.location.href
try {
if (navigator.share) {
await navigator.share({ title: shareTitle, url: shareUrl })
return
}
await navigator.clipboard.writeText(shareUrl)
message.success('主页链接已复制')
} catch {
message.info('分享已取消')
}
}
const loadProfile = async () => {
if (!artistId.value) {
loadError.value = '缺少美甲师信息'
return
}
loading.value = true
loadError.value = ''
try {
const [profileData, availabilityData, reviewData] = await Promise.all([
nailArtistApi.getPublicProfile(artistId.value),
nailArtistApi.getAvailability(artistId.value),
nailArtistApi.listReviews(artistId.value)
])
profile.value = profileData
availability.value = availabilityData || profileData.availability || []
reviews.value = reviewData || profileData.reviews || []
const nextWorks = await loadSupplementWorks(profileData.works || [])
profile.value = { ...profileData, works: nextWorks }
await loadWorkImages(nextWorks)
selectedDate.value = availability.value[0]?.dateText || String(availability.value[0]?.startTime || '').slice(0, 10)
} catch (error) {
loadError.value = error instanceof Error ? error.message : '美甲师个人页加载失败'
message.error(loadError.value)
} finally {
loading.value = false
}
}
onMounted(loadProfile)
</script>
<template>
<div class="artist-profile">
<header class="artist-topbar">
<a-button type="text" class="icon-btn" aria-label="返回" @click="router.back()">
<LeftOutlined />
</a-button>
<h1>美甲师</h1>
<a-button type="text" class="icon-btn" aria-label="分享" @click="handleShare">
<ShareAltOutlined />
</a-button>
</header>
<main class="artist-body">
<a-spin :spinning="loading">
<a-result v-if="loadError" status="warning" title="暂时无法查看个人页" :sub-title="loadError">
<template #extra>
<a-button type="primary" @click="loadProfile">重试</a-button>
</template>
</a-result>
<template v-else-if="profile">
<section class="profile-card">
<img class="profile-glow-image" :src="firstWorkImage" alt="" aria-hidden="true" />
<div class="avatar-wrap">
<a-avatar :size="112" :src="profile.avatar">
<UserOutlined />
</a-avatar>
<span class="top-badge">TOP 1%</span>
</div>
<h2>{{ artistName }}</h2>
<div class="rating-line">
<span class="star-row">
<StarFilled v-for="star in 5" :key="star" :class="{ active: star <= roundedRating(profile.rating) }" />
</span>
<strong>{{ ratingText }}</strong>
<span>{{ reviews.length }} 条评价</span>
</div>
<p>{{ profile.signature || profile.identity || '专注细节与稳定出品,让每一次指尖细节都更贴合你的风格。' }}</p>
<button type="button" class="shop-link" @click="openShop">
<ShopOutlined />
<span>{{ profile.shopName || '门店待确认' }}</span>
</button>
<div class="style-tags">
<span v-for="tag in styleTags" :key="tag">{{ tag }}</span>
<span v-if="!styleTags.length">风格待补充</span>
</div>
</section>
<section class="stats-section">
<div class="stat-card">
<strong>{{ serviceCountText }}</strong>
<span>累计服务</span>
</div>
<div class="stat-card">
<strong>{{ goodRateText }}</strong>
<span>好评率</span>
</div>
<div class="cert-card">
<SafetyCertificateOutlined />
<div>
<span>认证资质</span>
<strong>{{ certificationText }}</strong>
</div>
</div>
</section>
<section class="content-section">
<div class="section-head">
<div>
<span>Schedule</span>
<h3>可预约时间</h3>
</div>
<small>{{ workTimeText }}</small>
</div>
<div v-if="availabilityGroups.length" class="date-strip">
<button
v-for="group in availabilityGroups"
:key="group.date"
type="button"
:class="['date-card', { active: selectedDate === group.date }]"
@click="selectedDate = group.date"
>
<span>{{ group.week }}</span>
<strong>{{ group.label }}</strong>
</button>
</div>
<div v-if="selectedDateSlots.length" class="time-grid">
<button v-for="slot in selectedDateSlots" :key="slot.startTime" type="button" class="time-chip">
{{ slot.timeText }}
</button>
</div>
<a-empty v-else description="近期暂未放出可预约时间" />
</section>
<section class="content-section">
<div class="section-head">
<div>
<span>Portfolio</span>
<h3>作品集</h3>
</div>
</div>
<div v-if="workFilterOptions.length > 1" class="filter-row">
<button
v-for="option in workFilterOptions"
:key="option"
type="button"
:class="['filter-chip', { active: workFilter === option }]"
@click="workFilter = option"
>
{{ option }}
</button>
</div>
<div v-if="filteredWorks.length" class="work-grid">
<button v-for="work in filteredWorks" :key="work.id" type="button" class="work-card" @click="openProduct(work)">
<img :src="getWorkImage(work)" :alt="work.title || '作品'" loading="lazy" decoding="async" @error="handleWorkImageError(work)" />
<span>{{ work.title || '美甲作品' }}</span>
</button>
</div>
<a-empty v-else description="作品正在整理中" />
</section>
<section class="content-section review-section">
<div class="section-head">
<div>
<span>Reviews</span>
<h3>用户评价</h3>
</div>
<small>{{ reviews.length }} 条</small>
</div>
<div v-if="reviews.length" class="review-list">
<article v-for="review in reviews" :key="review.id" class="review-item">
<div class="review-top">
<a-avatar :size="44" :src="review.customerAvatar">
<UserOutlined />
</a-avatar>
<div class="review-author">
<strong>{{ review.customerName || '匿名用户' }}</strong>
<span class="star-row">
<StarFilled v-for="star in 5" :key="star" :class="{ active: star <= roundedRating(review.rating) }" />
</span>
</div>
<time>{{ formatDateTime(review.submittedAt) }}</time>
</div>
<p>{{ review.content || '这位用户没有填写文字评价' }}</p>
<div v-if="review.imageUrls?.length" class="review-images">
<img v-for="url in review.imageUrls" :key="url" :src="url" alt="评价图片" loading="lazy" decoding="async" />
</div>
</article>
</div>
<a-empty v-else description="还没有公开评价" />
</section>
</template>
</a-spin>
</main>
<footer v-if="profile" class="booking-bar">
<button type="button" class="bar-icon-btn" @click="handleConsult">
<MessageOutlined />
<span>咨询</span>
</button>
<button type="button" class="bar-icon-btn" @click="message.info('收藏功能即将开放')">
<HeartOutlined />
<span>收藏</span>
</button>
<button type="button" class="book-btn" @click="handleBookNow">
<CalendarOutlined />
<span>立即预约</span>
</button>
</footer>
</div>
</template>
<style scoped>
.artist-profile {
min-height: 100vh;
background:
linear-gradient(180deg, rgba(232, 180, 184, 0.24), rgba(255, 248, 244, 0) 260px),
var(--theme-page-bg);
color: var(--text-primary);
}
.artist-topbar {
position: sticky;
top: 0;
z-index: 30;
display: grid;
grid-template-columns: 44px minmax(0, 1fr) 44px;
align-items: center;
height: 62px;
max-width: 960px;
margin: 0 auto;
padding: 0 14px;
background: color-mix(in srgb, var(--theme-card-bg) 86%, transparent);
border-bottom: 1px solid color-mix(in srgb, var(--theme-border) 72%, transparent);
backdrop-filter: blur(18px);
}
.artist-topbar h1 {
margin: 0;
font-size: 17px;
font-weight: 700;
text-align: center;
}
.icon-btn {
width: 40px;
height: 40px;
}
.artist-body {
max-width: 960px;
margin: 0 auto;
padding: 22px 14px 116px;
}
.profile-card,
.content-section,
.stat-card,
.cert-card,
.review-item {
background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent);
border: 1px solid color-mix(in srgb, var(--theme-border) 72%, transparent);
box-shadow: 0 18px 48px rgba(124, 83, 87, 0.08);
backdrop-filter: blur(18px);
}
.profile-card {
position: relative;
display: grid;
justify-items: center;
padding: 34px 20px 24px;
overflow: hidden;
text-align: center;
border-radius: 24px;
}
.profile-glow-image {
position: absolute;
inset: 0;
width: 100%;
height: 170px;
object-fit: cover;
opacity: 0.18;
filter: blur(14px);
transform: scale(1.08);
}
.avatar-wrap {
position: relative;
z-index: 1;
}
.avatar-wrap :deep(.ant-avatar) {
color: var(--theme-primary);
background: var(--theme-primary-soft);
border: 4px solid #fff;
box-shadow: 0 16px 36px rgba(124, 83, 87, 0.18);
}
.top-badge {
position: absolute;
right: -8px;
bottom: 8px;
padding: 5px 8px;
color: #fff;
font-size: 11px;
font-weight: 800;
background: var(--theme-primary);
border: 2px solid #fff;
border-radius: 999px;
}
.profile-card h2 {
position: relative;
margin: 18px 0 8px;
font-size: 26px;
line-height: 1.2;
}
.rating-line {
position: relative;
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
justify-content: center;
color: var(--text-secondary);
font-size: 13px;
}
.rating-line strong {
color: var(--text-primary);
}
.star-row {
display: inline-flex;
gap: 2px;
color: color-mix(in srgb, var(--theme-border) 70%, #fff);
}
.star-row .active {
color: #b88935;
}
.profile-card p {
position: relative;
max-width: 640px;
margin: 14px 0;
color: var(--text-secondary);
line-height: 1.75;
}
.shop-link {
position: relative;
display: inline-flex;
gap: 8px;
align-items: center;
max-width: 100%;
padding: 8px 12px;
color: var(--theme-primary);
cursor: pointer;
background: var(--theme-primary-soft);
border: 0;
border-radius: 999px;
}
.shop-link span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.style-tags {
position: relative;
display: flex;
flex-wrap: wrap;
gap: 8px;
justify-content: center;
margin-top: 18px;
}
.style-tags span,
.filter-chip {
padding: 7px 11px;
color: var(--theme-primary);
font-size: 12px;
background: color-mix(in srgb, var(--theme-primary-soft) 86%, #fff);
border: 1px solid color-mix(in srgb, var(--theme-primary) 18%, transparent);
border-radius: 999px;
}
.stats-section {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
margin-top: 18px;
}
.stat-card {
display: grid;
gap: 6px;
min-height: 96px;
padding: 18px;
border-radius: 18px;
}
.stat-card strong {
color: var(--theme-primary);
font-size: 24px;
line-height: 1.1;
}
.stat-card span,
.cert-card span {
color: var(--text-secondary);
font-size: 13px;
}
.cert-card {
grid-column: 1 / -1;
display: flex;
gap: 12px;
align-items: center;
padding: 16px;
border-radius: 18px;
}
.cert-card svg {
color: #b88935;
font-size: 24px;
}
.cert-card div {
display: grid;
gap: 4px;
min-width: 0;
}
.cert-card strong {
overflow: hidden;
font-size: 15px;
text-overflow: ellipsis;
white-space: nowrap;
}
.content-section {
margin-top: 22px;
padding: 18px;
border-radius: 22px;
}
.section-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 16px;
}
.section-head span {
color: var(--theme-primary);
font-size: 12px;
font-weight: 800;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.section-head h3 {
margin: 4px 0 0;
font-size: 19px;
line-height: 1.25;
}
.section-head small {
color: var(--text-secondary);
font-size: 12px;
}
.date-strip {
display: flex;
gap: 10px;
overflow-x: auto;
padding-bottom: 4px;
}
.date-card {
display: grid;
flex: 0 0 80px;
gap: 8px;
place-items: center;
min-height: 92px;
color: var(--text-secondary);
cursor: pointer;
background: color-mix(in srgb, var(--theme-card-bg) 72%, var(--theme-primary-soft));
border: 1px solid color-mix(in srgb, var(--theme-border) 72%, transparent);
border-radius: 18px;
}
.date-card strong {
color: var(--text-primary);
font-size: 18px;
}
.date-card.active {
color: #fff;
background: var(--theme-primary);
border-color: var(--theme-primary);
}
.date-card.active strong {
color: #fff;
}
.time-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 10px;
margin-top: 14px;
}
.time-chip {
min-height: 44px;
color: var(--theme-primary);
font-weight: 700;
cursor: default;
background: var(--theme-primary-soft);
border: 1px solid color-mix(in srgb, var(--theme-primary) 18%, transparent);
border-radius: 14px;
}
.filter-row {
display: flex;
gap: 8px;
overflow-x: auto;
margin-bottom: 14px;
}
.filter-chip {
flex: 0 0 auto;
cursor: pointer;
}
.filter-chip.active {
color: #fff;
background: var(--theme-primary);
}
.work-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.work-card {
position: relative;
min-height: 0;
padding: 0;
overflow: hidden;
cursor: pointer;
background: var(--theme-primary-soft);
border: 0;
border-radius: 22px;
aspect-ratio: 3 / 4;
}
.work-card img {
width: 100%;
height: 100%;
object-fit: cover;
}
.work-card::after {
position: absolute;
inset: auto 0 0;
height: 46%;
content: "";
background: linear-gradient(180deg, transparent, rgba(31, 27, 23, 0.62));
}
.work-card span {
position: absolute;
right: 12px;
bottom: 12px;
left: 12px;
z-index: 1;
overflow: hidden;
color: #fff;
font-weight: 700;
text-align: left;
text-overflow: ellipsis;
white-space: nowrap;
}
.review-list {
display: grid;
gap: 12px;
}
.review-item {
padding: 14px;
border-radius: 18px;
}
.review-top {
display: grid;
grid-template-columns: 44px minmax(0, 1fr) auto;
gap: 10px;
align-items: center;
}
.review-author {
display: grid;
gap: 4px;
min-width: 0;
}
.review-author strong {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.review-top time {
color: var(--text-secondary);
font-size: 12px;
}
.review-item p {
margin: 12px 0 0;
color: var(--text-secondary);
line-height: 1.7;
white-space: pre-wrap;
}
.review-images {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 12px;
}
.review-images img {
width: 80px;
height: 80px;
object-fit: cover;
border-radius: 14px;
}
.booking-bar {
position: fixed;
right: 0;
bottom: 0;
left: 0;
z-index: 40;
display: grid;
grid-template-columns: 64px 64px minmax(0, 1fr);
gap: 10px;
align-items: center;
max-width: 960px;
margin: 0 auto;
padding: 12px 14px max(12px, env(safe-area-inset-bottom));
background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent);
border-top: 1px solid var(--theme-border);
box-shadow: 0 -16px 40px rgba(124, 83, 87, 0.1);
backdrop-filter: blur(18px);
}
.bar-icon-btn,
.book-btn {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 48px;
cursor: pointer;
border: 0;
border-radius: 999px;
}
.bar-icon-btn {
flex-direction: column;
gap: 2px;
color: var(--theme-primary);
font-size: 11px;
background: var(--theme-primary-soft);
}
.book-btn {
gap: 8px;
color: #fff;
font-size: 15px;
font-weight: 800;
background: var(--theme-primary);
}
@media (max-width: 640px) {
.artist-body {
padding: 18px 12px 112px;
}
.profile-card {
padding: 30px 16px 22px;
}
.profile-card h2 {
font-size: 24px;
}
.content-section {
padding: 16px;
}
.time-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
</style>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,446 @@
<template>
<div class="mobile-container">
<header class="header">
<a-button type="text" class="back-btn" @click="router.back()">
<LeftOutlined />
</a-button>
<h1>我的优惠券</h1>
<div class="placeholder"></div>
</header>
<div class="coupon-section">
<a-card :bordered="false" class="filter-card">
<a-segmented
v-model:value="activeFilter"
:options="filterOptions"
class="filter-segmented"
/>
</a-card>
<a-card v-if="loading" :bordered="false" class="content-card">
<a-skeleton :paragraph="{ rows: 3 }" />
</a-card>
<a-card v-else-if="coupons.length === 0" :bordered="false" class="content-card">
<a-empty description="暂无优惠券">
<a-button type="primary">去领取</a-button>
</a-empty>
</a-card>
<div v-else class="coupon-list">
<a-card
v-for="coupon in filteredCoupons"
:key="coupon.id"
class="coupon-card"
:class="{ 'expired': coupon.status === 3 }"
>
<div class="coupon-content">
<div class="coupon-value">
{{ coupon.couponType === 1 ? `${coupon.discountValue}折` : `¥${coupon.reduceAmount}` }}
</div>
<div class="coupon-info">
<div class="coupon-name">{{ coupon.couponName }}</div>
<div class="coupon-condition" v-if="coupon.couponType === 2">
满{{ coupon.minAmount }}元可用
</div>
<div class="coupon-time">
{{ formatDate(coupon.startTime) }} 至 {{ formatDate(coupon.endTime) }}
</div>
<div :class="['coupon-status', getStatusClass(coupon.status)]">
{{ coupon.statusName }}
</div>
</div>
</div>
</a-card>
</div>
</div>
</div>
</template>
<script setup lang="ts">
/**
* CouponView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { couponApi } from '@/api/coupon'
/**
* Purpose: router supports CouponView.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()
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/**
* Purpose: coupons supports CouponView.vue by holding or executing the 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 coupons = ref<any[]>([])
/** activeFilter is a reactive state variable used by the template and event handlers. */
const activeFilter = ref('all')
/**
* Purpose: filterOptions supports CouponView.vue by holding or executing the filter options 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 filterOptions = [
{ label: '全部', value: 'all' },
{ label: '未使用', value: 'available' },
{ label: '已使用', value: 'used' },
{ label: '已过期', value: 'expired' }
]
/** filteredCoupons is a reactive state variable used by the template and event handlers. */
const filteredCoupons = computed(() => {
if (activeFilter.value === 'all') {
return coupons.value
} else if (activeFilter.value === 'available') {
return coupons.value.filter(coupon => coupon.status === 1)
} else if (activeFilter.value === 'used') {
return coupons.value.filter(coupon => coupon.status === 2)
} else if (activeFilter.value === 'expired') {
return coupons.value.filter(coupon => coupon.status === 3)
}
return coupons.value
})
/** loadCoupons is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadCoupons = async () => {
loading.value = true
try {
const response = await couponApi.listUserCoupons() as any
coupons.value = response || []
} catch (error) {
console.error('获取优惠券列表失败:', error)
message.error('获取优惠券列表失败')
} finally {
loading.value = false
}
}
/** getStatusClass is a local helper used by this page script. */
const getStatusClass = (status: number) => {
switch (status) {
case 1:
return 'available'
case 2:
return 'used'
case 3:
return 'expired'
default:
return ''
}
}
/** formatDate is a local helper used by this page script. */
const formatDate = (dateString: string) => {
if (!dateString) return ''
const date = new Date(dateString)
return date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
})
}
onMounted(() => {
loadCoupons()
})
</script>
<style scoped>
.mobile-container {
padding-top: 60px;
min-height: 100vh;
background:
linear-gradient(rgba(255, 255, 255, 0.68), rgba(255, 255, 255, 0.92)),
var(--theme-background-image),
var(--theme-page-bg);
background-size: cover, cover, auto;
background-position: center top;
}
.header {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 100;
display: flex;
justify-content: space-between;
align-items: center;
height: 60px;
padding: 10px 15px;
background: rgba(255, 255, 255, 0.92);
border-bottom: 1px solid var(--theme-border);
backdrop-filter: blur(14px);
}
.header h1 {
font-size: 18px;
font-weight: bold;
margin: 0;
color: var(--text-primary);
}
.back-btn {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
color: var(--text-primary);
}
.placeholder {
width: 40px;
}
.coupon-section {
padding: 15px;
}
.filter-card {
border-radius: 14px;
margin-bottom: 15px;
background: var(--theme-card-bg);
border: 1px solid var(--theme-border);
box-shadow: 0 14px 34px rgba(122, 67, 88, 0.08);
}
.filter-segmented {
width: 100%;
}
.content-card {
border-radius: 14px;
background: var(--theme-card-bg);
border: 1px solid var(--theme-border);
box-shadow: 0 14px 34px rgba(122, 67, 88, 0.08);
padding: 40px 20px;
}
.coupon-list {
display: flex;
flex-direction: column;
gap: 15px;
}
.coupon-card {
border-radius: 14px;
overflow: hidden;
background: var(--theme-gradient-soft);
border: 1px solid var(--theme-border);
transition: all 0.3s ease;
box-shadow: 0 14px 34px rgba(122, 67, 88, 0.08);
}
.coupon-card:hover {
transform: translateY(-2px);
box-shadow: 0 18px 44px rgba(122, 67, 88, 0.12);
}
.coupon-card.expired {
opacity: 0.66;
background: var(--theme-card-bg);
}
.coupon-content {
display: flex;
align-items: center;
gap: 20px;
padding: 20px;
}
.coupon-value {
font-size: 24px;
font-weight: 700;
color: var(--theme-primary);
padding: 20px;
background: var(--theme-primary-soft);
border-radius: 8px;
min-width: 100px;
text-align: center;
}
.coupon-card.expired .coupon-value {
color: var(--text-secondary);
background: var(--theme-primary-soft);
}
.coupon-info {
flex: 1;
display: flex;
flex-direction: column;
gap: 8px;
}
.coupon-name {
font-size: 16px;
font-weight: 600;
color: var(--text-primary);
}
.coupon-condition {
font-size: 12px;
color: var(--theme-primary);
}
.coupon-time {
font-size: 12px;
color: var(--text-secondary);
}
.coupon-status {
font-size: 12px;
font-weight: 600;
padding: 2px 8px;
border-radius: 8px;
align-self: flex-start;
}
.coupon-status.available {
background: var(--theme-primary-soft);
color: var(--theme-primary);
}
.coupon-status.used {
background: var(--theme-primary-soft);
color: var(--text-secondary);
}
.coupon-status.expired {
background: var(--theme-primary-soft);
color: var(--theme-accent);
}
:deep(.ant-segmented) {
background: var(--theme-primary-soft);
}
:deep(.ant-segmented-item-selected) {
background: var(--theme-primary);
color: #fff;
}
:deep(.ant-btn-primary) {
background: var(--theme-primary);
border-color: var(--theme-primary);
}
.mobile-container {
padding-top: 68px;
background:
radial-gradient(circle at 84% 0%, color-mix(in srgb, var(--theme-primary) 26%, transparent), transparent 32%),
linear-gradient(180deg, color-mix(in srgb, var(--theme-card-bg) 78%, transparent), var(--theme-page-bg));
}
.header {
height: 64px;
padding: 12px 18px 10px;
background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent);
}
.header h1 {
font-size: 17px;
font-weight: 820;
}
.back-btn {
border-radius: 999px;
background: color-mix(in srgb, var(--theme-card-bg) 74%, transparent);
}
.coupon-section {
padding: 18px;
}
.filter-card,
.content-card {
border-radius: 22px;
background: color-mix(in srgb, var(--theme-card-bg) 90%, transparent);
box-shadow: 0 18px 40px color-mix(in srgb, var(--theme-neutral) 8%, transparent);
}
.coupon-list {
gap: 14px;
}
.coupon-card {
position: relative;
overflow: hidden;
border-radius: 24px;
background:
linear-gradient(135deg, color-mix(in srgb, var(--theme-card-bg) 88%, transparent), color-mix(in srgb, var(--theme-primary) 20%, var(--theme-card-bg)));
box-shadow: 0 20px 42px color-mix(in srgb, var(--theme-neutral) 9%, transparent);
}
.coupon-card::before {
content: '';
position: absolute;
top: 0;
bottom: 0;
left: 112px;
width: 1px;
background: linear-gradient(var(--theme-border) 52%, transparent 0);
background-size: 1px 12px;
}
.coupon-content {
gap: 18px;
padding: 18px;
}
.coupon-value {
min-width: 78px;
padding: 16px 8px;
border-radius: 18px;
color: var(--theme-primary-action);
background: color-mix(in srgb, var(--theme-primary) 24%, var(--theme-card-bg));
font-family: Georgia, 'Times New Roman', serif;
}
.coupon-name {
font-weight: 820;
}
.coupon-condition,
.coupon-status.available {
color: var(--theme-primary-action);
}
:deep(.ant-segmented) {
width: 100%;
padding: 4px;
border-radius: 16px;
background: color-mix(in srgb, var(--theme-primary) 16%, var(--theme-card-bg));
}
:deep(.ant-segmented-item) {
border-radius: 13px;
}
:deep(.ant-segmented-item-selected) {
background: var(--theme-card-bg);
color: var(--theme-primary-action);
box-shadow: 0 10px 20px color-mix(in srgb, var(--theme-neutral) 8%, transparent);
}
:deep(.ant-btn-primary) {
border-color: transparent;
background: linear-gradient(135deg, var(--theme-primary-action), var(--theme-secondary));
}
@media (min-width: 992px) {
.coupon-section {
max-width: 960px;
margin: 0 auto;
padding: 24px;
}
}
</style>
@@ -0,0 +1,96 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { userApi, type ContactInfoVO } from '@/api/user'
import { BRAND_CONFIG } from '@/config/brand'
const router = useRouter()
const loading = ref(false)
const contact = ref<ContactInfoVO | null>(null)
const loadContact = async () => {
loading.value = true
try {
contact.value = await userApi.getPlatformContact()
} catch (error: any) {
contact.value = null
message.warning(error?.message || '暂时无法加载客服信息')
} finally {
loading.value = false
}
}
onMounted(loadContact)
</script>
<template>
<div class="help-page">
<header class="header">
<a-button type="text" @click="router.back()">
<LeftOutlined />
</a-button>
<h1>帮助与客服</h1>
<a-button type="link" @click="loadContact">刷新</a-button>
</header>
<main class="content">
<section class="hero-card">
<span>{{ BRAND_CONFIG.appName }}客服</span>
<h2>帮助与客服</h2>
<p>订单、预约、售后和账号问题都可以从这里继续处理。</p>
</section>
<a-spin :spinning="loading">
<section class="section-card">
<h3>平台联系信息</h3>
<p v-if="contact?.contactName">{{ contact.contactName }} {{ contact.roleLabel || '' }}</p>
<p v-if="contact?.phoneAvailable && contact.phone">电话:{{ contact.phone }}</p>
<p v-if="contact?.wechatAvailable && contact.wechatId">微信:{{ contact.wechatId }}</p>
<p v-if="contact?.platformContactText">{{ contact.platformContactText }}</p>
<p v-if="!contact">暂无可展示的客服信息,请稍后重试或通过订单详情联系服务人员。</p>
</section>
<section class="quick-grid">
<button type="button" @click="router.push('/orders')">
<strong>订单中心</strong>
<span>查看预约、支付、评价</span>
</button>
<button type="button" @click="router.push('/after-sales')">
<strong>售后记录</strong>
<span>查看退款和处理进度</span>
</button>
<button type="button" @click="router.push('/notifications')">
<strong>消息中心</strong>
<span>查看系统通知</span>
</button>
<button type="button" @click="router.push('/settings')">
<strong>账号设置</strong>
<span>修改资料、手机号和密码</span>
</button>
</section>
</a-spin>
</main>
</div>
</template>
<style scoped>
.help-page { min-height: 100vh; padding-top: 66px; background: linear-gradient(180deg, color-mix(in srgb, var(--theme-card-bg) 76%, transparent), var(--theme-page-bg)); color: var(--text-primary); }
.header { position: fixed; top: 0; left: 0; right: 0; z-index: 10; display: flex; align-items: center; justify-content: space-between; height: 64px; padding: 11px 18px; background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent); border-bottom: 1px solid var(--theme-border); backdrop-filter: blur(14px); }
.header h1 { margin: 0; font-size: 17px; font-weight: 820; }
.content { padding: 18px 18px 34px; }
.hero-card, .section-card, .quick-grid button { border: 1px solid var(--theme-border); border-radius: 24px; background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent); box-shadow: 0 18px 44px color-mix(in srgb, var(--theme-neutral) 8%, transparent); }
.hero-card { padding: 24px; margin-bottom: 14px; background: linear-gradient(135deg, color-mix(in srgb, var(--theme-primary) 24%, var(--theme-card-bg)), color-mix(in srgb, var(--theme-secondary) 18%, var(--theme-card-bg))); }
.hero-card span { color: var(--theme-primary-action); font-family: Georgia, 'Times New Roman', serif; font-size: 12px; font-weight: 800; }
.hero-card h2 { margin: 10px 0 6px; font-size: 21px; font-weight: 850; }
.hero-card p, .section-card p, .quick-grid span { margin: 0; color: var(--text-secondary); line-height: 1.6; }
.section-card { padding: 16px; }
.section-card h3 { margin: 0 0 12px; font-size: 17px; }
.section-card p + p { margin-top: 8px; }
.quick-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; margin-top: 14px; }
.quick-grid button { display: grid; gap: 6px; min-height: 112px; padding: 16px; border-color: var(--theme-border); text-align: left; color: var(--text-primary); cursor: pointer; }
.quick-grid strong { font-size: 16px; }
.quick-grid span { font-size: 13px; }
:deep(.ant-btn-link) { color: var(--theme-primary-action); }
</style>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,224 @@
<template>
<div class="not-found-container">
<header class="not-found-topbar">
<button class="not-found-back" type="button" aria-label="返回" @click="handleBackClick">
<LeftOutlined />
</button>
<strong>{{ BRAND_CONFIG.appName }}</strong>
<span class="not-found-topbar-spacer" aria-hidden="true"></span>
</header>
<div class="not-found-content">
<span class="not-found-kicker">{{ BRAND_CONFIG.appName }}</span>
<div class="error-code">404</div>
<h1>这页去做护理了</h1>
<p>您访问的页面不存在或已被删除,我们带您回到首页继续浏览作品。</p>
<p class="redirect-message">
将在 <span class="countdown">{{ countdown }}</span> 秒后自动跳转到首页...
</p>
<a-button type="primary" @click="redirectToHome">立即前往首页</a-button>
</div>
</div>
</template>
<script setup lang="ts">
/**
* NotFoundView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
import { BRAND_CONFIG } from '@/config/brand'
/**
* Purpose: router supports NotFoundView.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()
/** countdown is a reactive state variable used by the template and event handlers. */
const countdown = ref(5)
let timer: number | null = null
const clearRedirectTimer = () => {
if (timer) {
clearInterval(timer)
timer = null
}
}
const handleBackClick = () => {
clearRedirectTimer()
if (window.history.length > 1) {
router.back()
return
}
router.push('/home')
}
/** redirectToHome is a local helper used by this page script. */
const redirectToHome = () => {
clearRedirectTimer()
router.push('/home')
}
onMounted(() => {
timer = window.setInterval(() => {
if (countdown.value > 0) {
countdown.value--
} else {
if (timer) {
clearInterval(timer)
}
redirectToHome()
}
}, 1000)
})
onUnmounted(() => {
clearRedirectTimer()
})
</script>
<style scoped>
.not-found-container {
position: relative;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background:
radial-gradient(circle at 82% 12%, color-mix(in srgb, var(--theme-primary) 30%, transparent), transparent 34%),
linear-gradient(180deg, var(--theme-tertiary), color-mix(in srgb, var(--theme-secondary) 14%, var(--theme-tertiary)));
padding: 20px;
}
.not-found-topbar {
position: fixed;
top: 12px;
left: 50%;
z-index: 20;
display: grid;
grid-template-columns: 40px minmax(0, 1fr) 40px;
align-items: center;
width: min(calc(100% - 32px), var(--app-mobile-max-width, 480px));
height: 44px;
transform: translateX(-50%);
}
.not-found-back {
display: inline-grid;
width: 36px;
height: 36px;
place-items: center;
border: 1px solid color-mix(in srgb, var(--theme-border) 78%, transparent);
border-radius: 999px;
color: var(--theme-primary-action);
background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent);
box-shadow: 0 10px 24px color-mix(in srgb, var(--theme-neutral) 8%, transparent);
cursor: pointer;
}
.not-found-topbar strong {
overflow: hidden;
color: var(--text-primary);
font-size: 16px;
font-weight: 800;
text-align: center;
text-overflow: ellipsis;
white-space: nowrap;
}
.not-found-topbar-spacer {
width: 36px;
height: 36px;
}
.not-found-content {
background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent);
border: 1px solid var(--theme-border);
border-radius: 28px;
padding: 48px 28px;
text-align: center;
box-shadow: 0 24px 54px color-mix(in srgb, var(--theme-neutral) 12%, transparent);
max-width: 500px;
width: 100%;
backdrop-filter: blur(16px);
}
.not-found-kicker {
color: var(--theme-secondary);
font-family: Georgia, 'Times New Roman', serif;
font-size: 13px;
font-weight: 800;
}
.error-code {
font-size: 104px;
font-weight: 900;
color: var(--theme-primary-action);
margin: 10px 0 14px;
line-height: 1;
}
.not-found-content h1 {
font-size: 28px;
font-weight: 700;
color: var(--text-primary);
margin: 0 0 16px 0;
}
.not-found-content p {
font-size: 16px;
color: var(--text-secondary);
margin: 0 0 24px 0;
line-height: 1.6;
}
.redirect-message {
margin: 20px 0 30px 0;
color: var(--text-secondary);
font-size: 14px;
}
.countdown {
color: var(--theme-primary-action);
font-weight: bold;
font-size: 18px;
margin: 0 4px;
}
:deep(.ant-btn-primary) {
background: linear-gradient(135deg, var(--theme-primary-action), var(--theme-secondary));
border: none;
padding: 12px 32px;
font-size: 16px;
font-weight: 600;
border-radius: 25px;
box-shadow: var(--theme-button-shadow);
transition: all 0.3s ease;
}
:deep(.ant-btn-primary:hover) {
transform: translateY(-2px);
box-shadow: var(--theme-button-shadow);
}
@media (max-width: 768px) {
.not-found-content {
padding: 40px 20px;
}
.error-code {
font-size: 80px;
}
.not-found-content h1 {
font-size: 24px;
}
.not-found-content p {
font-size: 14px;
}
}
</style>
@@ -0,0 +1,331 @@
<template>
<div class="notifications-page">
<header class="page-header">
<button class="back-btn" type="button" @click="router.back()">‹</button>
<div>
<h1>消息通知</h1>
<p>{{ unreadCount }} 条未读消息</p>
</div>
</header>
<main class="message-list">
<button
v-for="item in messages"
:key="item.id"
class="message-item"
:class="{ unread: item.readStatus !== 1 }"
type="button"
@click="openMessage(item)"
>
<span class="dot"></span>
<span class="message-main">
<strong>{{ item.title }}</strong>
<small>{{ item.publisherName || '系统消息' }} · {{ item.publishTime || item.createTime }}</small>
<em v-if="item.imageUrl">含图片</em>
</span>
</button>
<a-empty v-if="!loading && messages.length === 0" description="暂无消息" />
</main>
<a-modal v-model:open="detailVisible" title="消息详情" @ok="detailVisible = false">
<h3>{{ currentMessage?.title }}</h3>
<p class="message-meta">{{ currentMessage?.publisherName || '系统消息' }} · {{ currentMessage?.publishTime }}</p>
<div v-if="currentMessageContentHtml" class="message-content" v-html="currentMessageContentHtml"></div>
<img v-if="currentMessage?.imageUrl" class="message-image" :src="currentMessage.imageUrl" alt="消息图片" />
</a-modal>
</div>
</template>
<script setup lang="ts">
/**
* NotificationsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
/**
* Purpose: SystemMessageVO supports NotificationsView.vue by holding or executing the system message vo 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 { userApi, type SystemMessageVO } from '@/api/user'
import { buildSystemMessageActionPath } from '@/utils/system-message-action'
import { renderRichContent } from '@/utils/rich-content'
/**
* Purpose: router supports NotificationsView.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()
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/**
* Purpose: messages supports NotificationsView.vue by holding or executing the messages 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 messages = ref<SystemMessageVO[]>([])
/** detailVisible is a reactive state variable used by the template and event handlers. */
const detailVisible = ref(false)
/**
* Purpose: currentMessage supports NotificationsView.vue by holding or executing the current message 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 currentMessage = ref<SystemMessageVO | null>(null)
/** unreadCount is a reactive state variable used by the template and event handlers. */
const unreadCount = computed(() => messages.value.filter(item => item.readStatus !== 1).length)
const currentMessageContentHtml = computed(() => renderRichContent(currentMessage.value?.content || ''))
/**
* Purpose: resolveSystemMessageActionPath supports NotificationsView.vue by holding or executing the resolve system message action path 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 resolveSystemMessageActionPath = (item: SystemMessageVO) => buildSystemMessageActionPath(item)
/**
* Purpose: markMessageReadIfNeeded supports NotificationsView.vue by holding or executing the mark message read if needed 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 markMessageReadIfNeeded = async (item: SystemMessageVO) => {
if (item.readStatus === 1) {
return
}
await userApi.markMessageRead(item.id)
item.readStatus = 1
}
/** loadMessages is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadMessages = async () => {
loading.value = true
try {
messages.value = await userApi.listMyMessages()
} catch (error: any) {
message.error(error?.message || '消息加载失败')
} finally {
loading.value = false
}
}
/** openMessage is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const openMessage = async (item: SystemMessageVO) => {
try {
await markMessageReadIfNeeded(item)
} catch (error: any) {
message.error(error?.message || '标记已读失败')
return
}
const actionPath = resolveSystemMessageActionPath(item)
if (actionPath) {
await router.push(actionPath)
return
}
currentMessage.value = item
detailVisible.value = true
}
onMounted(loadMessages)
</script>
<style scoped>
.notifications-page {
min-height: 100vh;
background: var(--theme-page-bg);
padding: 18px;
}
.page-header {
display: flex;
gap: 14px;
align-items: center;
margin-bottom: 18px;
}
.page-header h1 {
margin: 0;
font-size: 20px;
}
.page-header p {
margin: 4px 0 0;
color: var(--text-secondary);
}
.back-btn {
width: 40px;
height: 40px;
border: 0;
border-radius: 20px;
background: var(--theme-card-bg);
font-size: 28px;
}
.message-list {
display: grid;
gap: 10px;
}
.message-item {
display: flex;
align-items: center;
gap: 12px;
width: 100%;
padding: 16px;
border: 0;
border-radius: 8px;
background: var(--theme-card-bg);
border: 1px solid var(--theme-border);
text-align: left;
}
.message-item .dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--theme-border);
}
.message-item.unread .dot {
background: var(--theme-primary);
}
.message-main {
display: grid;
gap: 4px;
}
.message-main em {
width: fit-content;
padding: 2px 8px;
border-radius: 999px;
background: var(--theme-primary-soft);
color: var(--theme-primary);
font-size: 12px;
font-style: normal;
}
.message-main small,
.message-meta {
color: var(--text-secondary);
}
.message-content {
line-height: 1.8;
overflow-wrap: break-word;
}
.message-content :deep(*) {
max-width: 100%;
}
.message-content :deep(p),
.message-content :deep(ul),
.message-content :deep(ol),
.message-content :deep(blockquote),
.message-content :deep(pre),
.message-content :deep(table) {
margin: 0 0 12px;
}
.message-content :deep(p:last-child),
.message-content :deep(ul:last-child),
.message-content :deep(ol:last-child),
.message-content :deep(blockquote:last-child),
.message-content :deep(pre:last-child),
.message-content :deep(table:last-child) {
margin-bottom: 0;
}
.message-content :deep(ul),
.message-content :deep(ol) {
padding-left: 1.25em;
}
.message-content :deep(a) {
color: var(--theme-primary);
}
.message-content :deep(img) {
display: block;
max-width: 100%;
border-radius: 8px;
}
.message-content :deep(pre) {
overflow-x: auto;
padding: 10px 12px;
border-radius: 8px;
background: var(--theme-primary-soft);
}
.message-image {
display: block;
width: 100%;
max-height: 420px;
margin-top: 14px;
object-fit: contain;
border-radius: 8px;
background: var(--theme-primary-soft);
}
.notifications-page {
padding: 18px 18px 34px;
background:
radial-gradient(circle at 84% 0%, color-mix(in srgb, var(--theme-primary) 28%, transparent), transparent 30%),
linear-gradient(180deg, color-mix(in srgb, var(--theme-card-bg) 74%, transparent), var(--theme-page-bg));
}
.page-header {
margin-bottom: 22px;
}
.page-header h1 {
font-size: 21px;
font-weight: 860;
}
.page-header p {
color: var(--theme-secondary);
font-weight: 700;
}
.back-btn {
color: var(--theme-primary-action);
background: color-mix(in srgb, var(--theme-card-bg) 82%, transparent);
box-shadow: 0 12px 24px color-mix(in srgb, var(--theme-neutral) 8%, transparent);
}
.message-list {
gap: 12px;
}
.message-item {
align-items: flex-start;
padding: 17px;
border-radius: 22px;
background: color-mix(in srgb, var(--theme-card-bg) 90%, transparent);
box-shadow: 0 18px 38px color-mix(in srgb, var(--theme-neutral) 7%, transparent);
}
.message-item.unread {
border-color: color-mix(in srgb, var(--theme-primary) 36%, var(--theme-border));
}
.message-item.unread .dot {
background: var(--theme-primary-action);
}
.message-main strong {
color: var(--text-primary);
font-size: 15px;
}
.message-main em {
color: var(--theme-primary-action);
background: color-mix(in srgb, var(--theme-primary) 18%, var(--theme-card-bg));
}
.message-content :deep(a) {
color: var(--theme-primary-action);
}
</style>
@@ -0,0 +1,429 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { afterSaleApi, orderApi, paymentApi } from '../api/order'
import type { AfterSaleVO, OrderArtistChangeRequestVO, OrderArtistReviewVO } from '../api/order'
import { userApi, type ContactInfoVO } from '@/api/user'
import type { IdType } from '@/utils/id'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { extractLegacyFileId, getCachedSignedImageUrl, getCachedSignedImageUrlSync } from '@/utils/signed-image-cache'
const route = useRoute()
const router = useRouter()
const loading = ref(false)
const order = ref<any | null>(null)
const reviews = ref<OrderArtistReviewVO[]>([])
const changeRequests = ref<OrderArtistChangeRequestVO[]>([])
const afterSales = ref<AfterSaleVO[]>([])
const contact = ref<ContactInfoVO | null>(null)
const quoteReply = ref('')
const quoteSubmitting = ref(false)
const quoteConfirming = ref(false)
const orderId = computed(() => String(route.params.id || route.query.orderId || ''))
const items = computed(() => Array.isArray(order.value?.items) ? order.value.items : [])
const formatMoney = (value?: number | string) => {
const amount = Number(value)
return Number.isFinite(amount) ? `¥${amount.toFixed(2)}` : '¥0.00'
}
const formatDateTime = (value?: string) => value ? String(value).replace('T', ' ').slice(0, 16) : '--'
const isQuoteStatus = (status?: unknown) => Number(status) === 0
const isQuoteConfirming = computed(() => isQuoteStatus(order.value?.status))
const statusClass = (status?: number) => isQuoteStatus(status) ? 'quote' : status === 2 ? 'done' : status === 3 ? 'cancelled' : 'pending'
const isOrderPaid = (target: any) => String(target?.paymentStatus || '').toUpperCase() === 'PAID'
const canPreparePayment = computed(() => !isQuoteConfirming.value && Number(order.value?.status) === 1 && !isOrderPaid(order.value))
const canMockPay = computed(() => !isQuoteConfirming.value && Number(order.value?.status) === 1 && String(order.value?.paymentStatus || '').toUpperCase() === 'PAYING')
const canApplyAfterSale = computed(() => !isQuoteConfirming.value && (Number(order.value?.status) === 2 || isOrderPaid(order.value)))
const timeline = computed(() => {
const current = order.value || {}
const firstAppointment = items.value.map((item: any) => item.appointmentTime).find(Boolean)
const status = Number(current.status)
if (status === 0) {
return [
{ key: 'created', title: '已创建', text: formatDateTime(current.createTime), done: true, active: false },
{ key: 'quote', title: '确认价格', text: current.quoteStatusText || '等待双方确认', done: Boolean(current.quoteUserConfirmed && current.quoteShopConfirmed), active: true },
{ key: 'appointment', title: '预约时间', text: firstAppointment ? formatDateTime(firstAppointment) : '价格确认后安排', done: Boolean(firstAppointment), active: false },
{ key: 'service', title: '服务完成', text: '待服务', done: false, active: false },
{ key: 'review', title: '评价', text: '完成后可评价', done: false, active: false }
]
}
return [
{ key: 'created', title: '已创建', text: formatDateTime(current.createTime), done: true, active: false },
{ key: 'appointment', title: '预约时间', text: formatDateTime(firstAppointment), done: Boolean(firstAppointment), active: status === 1 },
{ key: 'service', title: status === 3 ? '已取消' : '服务完成', text: formatDateTime(current.completeTime || current.cancelTime || current.updateTime), done: status === 2 || status === 3, active: status === 2 || status === 3 },
{ key: 'review', title: '评价', text: reviews.value.length ? `${reviews.value.length} 条记录` : '完成后可评价', done: reviews.value.some(item => Number(item.status) === 1 || item.rating), active: reviews.value.some(item => Number(item.status) !== 1 && !item.rating) },
{ key: 'after-sale', title: '售后', text: afterSales.value.length ? `${afterSales.value.length} 条记录` : '暂无售后', done: afterSales.value.length > 0, active: afterSales.value.some(item => item.status === 'PENDING') }
]
})
const hasAmount = (value: unknown) => value !== undefined && value !== null && value !== '' && Number.isFinite(Number(value))
const formatQuoteAmount = (value: unknown, fallback = '--') => hasAmount(value) ? formatMoney(value as number | string) : fallback
const quoteReferencePrice = (item: any) => item?.referencePrice ?? item?.price
const quoteMessages = computed(() => Array.isArray(order.value?.quoteMessages) ? order.value.quoteMessages : [])
const quoteStatusText = computed(() => order.value?.quoteStatusText || order.value?.statusText || '确认价格中')
const quoteExpireText = computed(() => {
const expireTime = formatDateTime(order.value?.quoteExpireTime)
return expireTime !== '--' ? `有效期至 ${expireTime}` : '等待门店报价'
})
const quoteMessageItems = (quoteMessage: any) => Array.isArray(quoteMessage?.items) ? quoteMessage.items : []
const quoteActorText = (quoteMessage: any) => {
if (quoteMessage?.actorTypeText) return quoteMessage.actorTypeText
if (String(quoteMessage?.actorType || '').toUpperCase() === 'USER') return '用户'
if (String(quoteMessage?.actorType || '').toUpperCase() === 'SHOP') return '门店'
return '系统'
}
const quoteActionText = (quoteMessage: any) => quoteMessage?.actionText || quoteMessage?.action || '报价更新'
const quoteMessageKey = (quoteMessage: any, index: string | number) => {
return String(quoteMessage?.id ?? `${quoteMessage?.createTime || 'quote'}-${quoteMessage?.action || index}`)
}
const quoteMessageItemKey = (quoteItem: any) => {
return String(quoteItem?.orderItemId ?? quoteItem?.productId ?? quoteItem?.id ?? JSON.stringify(quoteItem))
}
const quoteMessageItemText = (quoteItem: any) => {
const sourceItem = items.value.find((item: any) => String(item.id) === String(quoteItem?.orderItemId) || String(item.productId) === String(quoteItem?.productId))
const title = quoteItem?.productTitle || sourceItem?.productTitle || '预约项目'
const amount = quoteItem?.confirmedPrice ?? quoteItem?.quotedPrice ?? quoteItem?.price
return hasAmount(amount) ? `${title}:${formatMoney(amount)}` : title
}
const orderHasCurrentQuote = computed(() => {
return items.value.some((item: any) => hasAmount(item?.quotedPrice ?? item?.confirmedPrice))
})
const resolveOrderImages = async () => {
for (const item of items.value) {
const imageId = extractLegacyFileId(item.productImage)
if (!imageId) continue
const cachedUrl = getCachedSignedImageUrlSync(imageId)
if (cachedUrl) item.productImage = cachedUrl
item.productImage = await getCachedSignedImageUrl(imageId)
}
}
const loadRelated = async () => {
if (!orderId.value) return
const [reviewList, changeList, afterSalePage, contactInfo] = await Promise.all([
orderApi.getOrderReviews(orderId.value).catch(() => []),
orderApi.getOrderArtistChangeRequests(orderId.value).catch(() => []),
afterSaleApi.listMy({ page: 1, size: 50 }).catch(() => ({ list: [] })),
userApi.getOrderArtistContact(orderId.value).catch(() => null)
])
reviews.value = reviewList || []
changeRequests.value = changeList || []
afterSales.value = ((afterSalePage as any)?.list || []).filter((item: AfterSaleVO) => String(item.orderId) === orderId.value)
contact.value = contactInfo
}
const loadOrder = async () => {
if (!orderId.value) {
order.value = null
return
}
loading.value = true
try {
order.value = await orderApi.getOrderDetail(orderId.value)
await resolveOrderImages()
await loadRelated()
} catch (error: any) {
order.value = null
message.error(error?.message || '订单详情加载失败')
} finally {
loading.value = false
}
}
const submitQuoteReply = async () => {
if (!order.value?.id) return
const remark = quoteReply.value.trim()
if (!remark) {
message.warning('请先填写回复内容')
return
}
quoteSubmitting.value = true
try {
await runWithGlobalLoading(async () => {
await orderApi.replyQuote(order.value.id, { remark })
await loadOrder()
})
quoteReply.value = ''
message.success('报价回复已发送')
} catch (error: any) {
message.error(error?.message || '发送报价回复失败')
} finally {
quoteSubmitting.value = false
}
}
const confirmQuote = () => {
if (!order.value?.id) return
if (!orderHasCurrentQuote.value) {
message.warning('当前暂无可确认报价')
return
}
Modal.confirm({
title: '确认当前报价',
content: '确认后门店会继续处理预约,请确认当前报价无误。',
onOk: async () => {
quoteConfirming.value = true
try {
await runWithGlobalLoading(async () => {
await orderApi.confirmUserQuote(order.value.id)
await loadOrder()
})
message.success('已确认当前报价')
} catch (error: any) {
message.error(error?.message || '确认报价失败')
} finally {
quoteConfirming.value = false
}
}
})
}
const preparePayment = async () => {
if (!order.value?.id) return
await runWithGlobalLoading(async () => {
await paymentApi.prepareOrderPayment(order.value.id)
await loadOrder()
})
message.success('支付单已准备')
}
const mockPay = async () => {
if (!order.value?.id) return
await runWithGlobalLoading(async () => {
await paymentApi.mockSuccess(order.value.id)
await loadOrder()
})
message.success('模拟支付成功')
}
const cancelOrder = () => {
if (!order.value?.id) return
Modal.confirm({
title: '取消订单',
content: '确认取消这笔订单吗?',
onOk: async () => {
await runWithGlobalLoading(() => orderApi.cancelOrder(order.value.id as IdType))
message.success('订单已取消')
await loadOrder()
}
})
}
onMounted(loadOrder)
</script>
<template>
<div class="detail-page">
<header class="header">
<a-button type="text" @click="router.back()">
<LeftOutlined />
</a-button>
<h1>订单详情</h1>
<a-button type="link" @click="router.push('/orders')">列表</a-button>
</header>
<main class="content">
<a-spin :spinning="loading">
<a-empty v-if="!order" description="未找到订单">
<a-button type="primary" @click="router.push('/orders')">查看订单中心</a-button>
</a-empty>
<template v-else>
<section class="hero-card">
<span class="eyebrow">{{ isQuoteConfirming ? '询价预约' : '预约订单' }}</span>
<h2>{{ order.orderNo || `订单 ${order.id}` }}</h2>
<p>{{ order.shopName || '当前门店' }}</p>
<div class="hero-meta">
<strong>{{ formatMoney(order.actualAmount || order.totalAmount) }}</strong>
<span :class="['status-pill', statusClass(order.status)]">{{ isQuoteConfirming ? quoteStatusText : (order.statusText || '处理中') }}</span>
</div>
</section>
<section class="timeline-card">
<article v-for="node in timeline" :key="node.key" :class="{ done: node.done, active: node.active }">
<strong>{{ node.title }}</strong>
<span>{{ node.text }}</span>
</article>
</section>
<section v-if="isQuoteConfirming" class="section-card quote-detail-panel">
<div class="section-head">
<div>
<h3>报价确认</h3>
<p>{{ quoteStatusText }} · {{ quoteExpireText }}</p>
</div>
</div>
<p>客户备注:{{ order.customerRemark || '暂无备注' }}</p>
<div class="quote-flags">
<span :class="{ active: order.quoteUserConfirmed }">用户{{ order.quoteUserConfirmed ? '已确认' : '待确认' }}</span>
<span :class="{ active: order.quoteShopConfirmed }">门店{{ order.quoteShopConfirmed ? '已确认' : '待确认' }}</span>
</div>
<div class="quote-items">
<article v-for="item in items" :key="item.id || item.productId" class="quote-item">
<strong>{{ item.productTitle || '预约项目' }}</strong>
<span>参考价 {{ formatQuoteAmount(quoteReferencePrice(item), '待确认') }}</span>
<span>当前报价 {{ formatQuoteAmount(item.quotedPrice, '待报价') }}</span>
<span>最终价 {{ formatQuoteAmount(item.confirmedPrice, '待确认') }}</span>
</article>
</div>
<div class="quote-history">
<strong>报价历史</strong>
<div v-if="quoteMessages.length" class="quote-history__list">
<article v-for="(quoteMessage, index) in quoteMessages" :key="quoteMessageKey(quoteMessage, index)" class="quote-history__item">
<div>
<span>{{ quoteActorText(quoteMessage) }}</span>
<em>{{ quoteActionText(quoteMessage) }}</em>
<small>{{ formatDateTime(quoteMessage.createTime) }}</small>
</div>
<p v-if="quoteMessage.remark">{{ quoteMessage.remark }}</p>
<div v-if="quoteMessageItems(quoteMessage).length" class="quote-history__prices">
<span v-for="quoteItem in quoteMessageItems(quoteMessage)" :key="quoteMessageItemKey(quoteItem)">
{{ quoteMessageItemText(quoteItem) }}
</span>
</div>
</article>
</div>
<p v-else>暂无报价历史</p>
</div>
<div class="quote-reply">
<a-textarea v-model:value="quoteReply" :rows="3" :maxlength="300" placeholder="给门店补充说明或回复当前报价" />
<div class="quote-reply__actions">
<a-button :loading="quoteSubmitting" @click="submitQuoteReply">发送回复</a-button>
<a-button
v-if="!order.quoteUserConfirmed"
type="primary"
:loading="quoteConfirming"
:disabled="!orderHasCurrentQuote"
@click="confirmQuote"
>
确认当前报价
</a-button>
<span v-else class="quote-confirmed">你已确认当前报价</span>
</div>
</div>
</section>
<section class="section-card">
<div class="section-head">
<h3>预约项目</h3>
<a-button type="link" @click="router.push({ path: '/service-progress', query: { orderId } })">服务进度</a-button>
</div>
<article v-for="item in items" :key="item.id" class="item-row">
<div class="thumb">
<img v-if="item.productImage" :src="item.productImage" :alt="item.productTitle" loading="lazy" decoding="async" />
<span v-else>{{ String(item.productTitle || '项').slice(0, 1) }}</span>
</div>
<div class="item-main">
<strong>{{ item.productTitle || '预约项目' }}</strong>
<span>{{ isQuoteConfirming ? '参考价 ' : '' }}{{ formatMoney(item.price) }} x {{ item.quantity || 1 }}</span>
<span v-if="item.artistName">美甲师:{{ item.artistName }}</span>
<span v-if="item.appointmentTime">预约:{{ formatDateTime(item.appointmentTime) }}</span>
</div>
</article>
</section>
<section v-if="contact" class="section-card">
<h3>联系信息</h3>
<p>{{ contact.contactName || contact.roleLabel || '服务联系人' }}</p>
<p v-if="contact.phoneAvailable && contact.phone">电话:{{ contact.phone }}</p>
<p v-if="contact.wechatAvailable && contact.wechatId">微信:{{ contact.wechatId }}</p>
<p v-if="contact.platformContactText">{{ contact.platformContactText }}</p>
</section>
<section v-if="afterSales.length || changeRequests.length || reviews.length" class="section-card">
<h3>关联记录</h3>
<p v-for="item in afterSales" :key="`as-${item.id}`">售后 {{ item.afterSaleNo || item.id }}:{{ item.status || '-' }}</p>
<p v-for="item in changeRequests" :key="`change-${item.id}`">改派:{{ item.statusText || item.status || '-' }}</p>
<p v-for="item in reviews" :key="`review-${item.id}`">评价:{{ item.statusText || item.rating || '待评价' }}</p>
</section>
<section class="action-bar">
<a-button v-if="canPreparePayment" @click="preparePayment">准备支付</a-button>
<a-button v-if="canMockPay" type="primary" @click="mockPay">模拟支付</a-button>
<a-button v-if="canApplyAfterSale" @click="router.push({ path: '/after-sale/apply', query: { orderId } })">申请售后</a-button>
<a-button v-if="order.status === 1" danger @click="cancelOrder">取消订单</a-button>
</section>
</template>
</a-spin>
</main>
</div>
</template>
<style scoped>
.detail-page { min-height: 100vh; padding-top: 60px; background: var(--theme-page-bg); color: var(--text-primary); }
.header { position: fixed; top: 0; left: 0; right: 0; z-index: 10; display: flex; align-items: center; justify-content: space-between; height: 60px; padding: 9px 14px; background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent); border-bottom: 1px solid var(--theme-border); backdrop-filter: blur(14px); }
.header h1 { margin: 0; font-size: 18px; }
.content { padding: 16px 14px 28px; }
.hero-card, .section-card, .timeline-card { border: 1px solid var(--theme-border); border-radius: 20px; background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent); box-shadow: 0 18px 44px rgba(74, 68, 63, 0.08); }
.hero-card { padding: 22px; background: var(--theme-gradient-soft); }
.eyebrow { display: block; color: var(--theme-primary); font-size: 12px; font-weight: 700; letter-spacing: .05em; }
.hero-card h2 { margin: 10px 0 6px; font-size: 21px; }
.hero-card p { margin: 0; color: var(--text-secondary); }
.hero-meta { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-top: 18px; }
.hero-meta strong { font-size: 20px; }
.status-pill { padding: 6px 12px; border-radius: 999px; font-size: 12px; font-weight: 700; background: var(--theme-primary-soft); color: var(--theme-primary); }
.status-pill.quote { color: #6b4600; background: #fff2cc; }
.status-pill.cancelled { color: var(--theme-accent); }
.timeline-card { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 1px; overflow: hidden; margin-top: 14px; background: var(--theme-border); }
.timeline-card article { min-width: 0; padding: 12px 8px; background: var(--theme-card-bg); color: var(--text-secondary); }
.timeline-card article.active { color: var(--theme-primary); }
.timeline-card article.done strong { color: var(--theme-primary); }
.timeline-card strong, .timeline-card span { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.timeline-card strong { font-size: 12px; }
.timeline-card span { margin-top: 4px; font-size: 11px; }
.section-card { margin-top: 14px; padding: 16px; }
.section-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.section-card h3 { margin: 0 0 12px; font-size: 17px; }
.section-card p { margin: 8px 0 0; color: var(--text-secondary); line-height: 1.6; }
.section-head p { margin: 4px 0 0; font-size: 13px; }
.quote-detail-panel { display: grid; gap: 12px; }
.quote-flags { display: flex; flex-wrap: wrap; gap: 8px; }
.quote-flags span { padding: 4px 9px; border-radius: 999px; color: var(--text-secondary); background: var(--theme-primary-soft); font-size: 12px; }
.quote-flags span.active { color: var(--theme-primary); font-weight: 700; }
.quote-items, .quote-history, .quote-history__list, .quote-reply { display: grid; gap: 8px; }
.quote-item { display: grid; grid-template-columns: minmax(0, 1.35fr) repeat(3, minmax(82px, auto)); gap: 8px; align-items: center; min-width: 0; padding: 10px; border-radius: 12px; background: color-mix(in srgb, var(--theme-primary-soft) 48%, var(--theme-card-bg)); }
.quote-item strong { min-width: 0; overflow-wrap: anywhere; color: var(--text-primary); font-size: 13px; }
.quote-item span, .quote-history__item small, .quote-confirmed { color: var(--text-secondary); font-size: 12px; }
.quote-history > strong { color: var(--text-primary); font-size: 13px; }
.quote-history__item { display: grid; gap: 6px; padding: 10px; border-radius: 12px; background: color-mix(in srgb, var(--theme-primary-soft) 42%, var(--theme-card-bg)); }
.quote-history__item div { display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center; }
.quote-history__item span, .quote-history__item em { color: var(--theme-primary); font-size: 12px; font-style: normal; font-weight: 700; }
.quote-history__item p { margin: 0; overflow-wrap: anywhere; font-size: 13px; }
.quote-history__prices { display: flex; flex-wrap: wrap; gap: 6px; }
.quote-history__prices span { padding: 3px 7px; border-radius: 8px; color: var(--text-secondary); background: var(--theme-card-bg); font-size: 12px; }
.quote-reply__actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; }
.quote-confirmed { display: inline-flex; align-items: center; min-height: 32px; color: var(--theme-primary); font-weight: 700; }
.item-row { display: flex; gap: 12px; padding: 12px 0; border-top: 1px solid var(--theme-border); }
.item-row:first-of-type { border-top: 0; padding-top: 0; }
.thumb { width: 64px; height: 64px; flex: 0 0 auto; border-radius: 14px; overflow: hidden; display: grid; place-items: center; background: var(--theme-primary-soft); color: var(--theme-primary); font-weight: 700; }
.thumb img { width: 100%; height: 100%; object-fit: cover; }
.item-main { display: grid; gap: 5px; min-width: 0; color: var(--text-secondary); font-size: 13px; }
.item-main strong { color: var(--text-primary); font-size: 15px; }
.action-bar { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 10px; margin-top: 16px; }
:deep(.ant-btn-primary) { background: var(--theme-primary); border-color: var(--theme-primary); }
:deep(.ant-btn-link) { color: var(--theme-primary); }
@media (max-width: 640px) {
.quote-item { grid-template-columns: 1fr; }
.quote-reply__actions { justify-content: stretch; }
.quote-reply__actions :deep(.ant-btn) { flex: 1 1 140px; }
}
</style>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,343 @@
<template>
<div class="mobile-container">
<header class="header">
<a-button class="back-btn" type="text" @click="handleBackClick">
<LeftOutlined :style="{ fontSize: '20px' }" />
</a-button>
<h1>设置密码</h1>
<div class="empty"></div>
</header>
<div class="password-form">
<a-card :bordered="false" class="form-card">
<DraftActions
:saved-at="draftSavedAt"
@save="handleSaveDraft"
@clear="handleClearDraft"
/>
<a-form
ref="formRef"
:model="formState"
:rules="formRules"
layout="vertical"
@finish="handleSubmit"
>
<a-form-item label="手机号">
<a-input :value="userPhone || '未绑定手机号'" disabled size="large" />
</a-form-item>
<a-form-item label="验证码" name="verificationCode">
<a-input
v-model:value="formState.verificationCode"
placeholder="请输入验证码"
size="large"
>
<template #suffix>
<a-button
type="link"
:disabled="countdown > 0 || !userPhone"
@click="handleSendVerificationCode"
>
{{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
</a-button>
</template>
</a-input>
</a-form-item>
<a-form-item label="新密码" name="password">
<a-input-password
v-model:value="formState.password"
placeholder="请输入新密码"
size="large"
@pressEnter="handleSubmit"
>
<template #prefix>
<LockOutlined style="color: var(--text-secondary)" />
</template>
</a-input-password>
<div class="password-tip">
密码长度至少 8 位,且需包含字母和数字
</div>
</a-form-item>
<a-form-item label="确认密码" name="confirmPassword">
<a-input-password
v-model:value="formState.confirmPassword"
placeholder="请再次输入新密码"
size="large"
@pressEnter="handleSubmit"
>
<template #prefix>
<LockOutlined style="color: var(--text-secondary)" />
</template>
</a-input-password>
</a-form-item>
<a-form-item>
<a-button
type="primary"
html-type="submit"
size="large"
block
:loading="loading"
>
确认设置
</a-button>
</a-form-item>
</a-form>
</a-card>
</div>
</div>
</template>
<script setup lang="ts">
/**
* PasswordSettingsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined, LockOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import DraftActions from '@/components/DraftActions.vue'
import { userApi } from '@/api/user'
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
import { runWithGlobalLoading } from '@/utils/action-loading'
/**
* Purpose: router supports PasswordSettingsView.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()
/**
* Purpose: formRef supports PasswordSettingsView.vue by holding or executing the form ref 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 formRef = ref<FormInstance>()
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** countdown is a reactive state variable used by the template and event handlers. */
const countdown = ref(0)
/**
* Purpose: userInfo supports PasswordSettingsView.vue by holding or executing the user info 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 userInfo = ref<{ phone?: string } | null>(null)
/**
* Purpose: draftSavedAt supports PasswordSettingsView.vue by holding or executing the draft saved at 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 draftSavedAt = ref<number | null>(null)
let countdownTimer: ReturnType<typeof setInterval> | null = null
/**
* Purpose: formState supports PasswordSettingsView.vue by holding or executing the form state 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 formState = reactive({
verificationCode: '',
password: '',
confirmPassword: ''
})
/**
* Purpose: draftKey supports PasswordSettingsView.vue by holding or executing the draft key 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 draftKey = buildDraftStorageKey('password-settings', 'set-password')
/** restoreDraft is a local helper used by this page script. */
const restoreDraft = () => {
const draft = loadDraftRecord<typeof formState>(draftKey, 'session')
if (!draft) {
draftSavedAt.value = null
return
}
Object.assign(formState, draft.payload)
draftSavedAt.value = draft.savedAt
message.success('已恢复暂存内容')
}
/** handleSaveDraft is a local helper used by this page script. */
const handleSaveDraft = () => {
const draft = saveDraftRecord(draftKey, { ...formState }, 'session')
draftSavedAt.value = draft.savedAt
message.success('已暂存到当前会话')
}
/** handleClearDraft is a local helper used by this page script. */
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(draftKey, 'session')
draftSavedAt.value = null
if (showMessage) {
message.success('已清除暂存')
}
}
/** userPhone is a reactive state variable used by the template and event handlers. */
const userPhone = computed(() => userInfo.value?.phone || '')
/** validateConfirmPassword is a local helper used by this page script. */
const validateConfirmPassword = (_rule: any, value: string) => {
if (value !== formState.password) {
return Promise.reject(new Error('两次输入的密码不一致'))
}
return Promise.resolve()
}
const formRules: Record<string, Rule[]> = {
verificationCode: [
{ required: true, message: '请输入验证码', trigger: 'blur' },
{ pattern: /^\d{6}$/, message: '验证码必须是6位数字', trigger: 'blur' }
],
password: [
{ required: true, message: '请输入新密码', trigger: 'blur' },
{ min: 8, message: '密码长度至少8位', trigger: 'blur' },
{ pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,}$/, message: '密码必须包含字母和数字', trigger: 'blur' }
],
confirmPassword: [
{ required: true, message: '请确认新密码', trigger: 'blur' },
{ validator: validateConfirmPassword, trigger: 'blur' }
]
}
/** startCountdown is a local helper used by this page script. */
const startCountdown = () => {
countdown.value = 60
if (countdownTimer) {
clearInterval(countdownTimer)
}
countdownTimer = setInterval(() => {
countdown.value -= 1
if (countdown.value <= 0 && countdownTimer) {
clearInterval(countdownTimer)
countdownTimer = null
}
}, 1000)
}
/** fetchUserInfo is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUserInfo = async () => {
try {
const res = await userApi.getUserInfo()
userInfo.value = res as unknown as { phone?: string }
} catch (error: any) {
console.error('获取用户信息失败:', error)
message.error(error.message || '获取用户信息失败')
}
}
/** handleSendVerificationCode is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSendVerificationCode = async () => {
if (!userPhone.value) {
message.error('请先绑定手机号')
return
}
try {
await runWithGlobalLoading(() => userApi.sendVerificationCode({
phone: userPhone.value,
sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE'
}))
message.success('验证码发送成功')
startCountdown()
} catch (error: any) {
console.error('发送验证码失败:', error)
message.error(error.message || '发送验证码失败')
}
}
/** handleSubmit is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSubmit = async () => {
if (!formRef.value) return
try {
await formRef.value.validate()
if (!userPhone.value) {
message.error('请先绑定手机号')
return
}
loading.value = true
await runWithGlobalLoading(() => userApi.updatePassword({
password: formState.password,
verificationCode: formState.verificationCode
}))
message.success('密码设置成功')
handleClearDraft(false)
localStorage.removeItem('needSetPassword')
router.push('/profile')
} catch (error: any) {
console.error('设置密码失败:', error)
message.error(error.message || '设置密码失败')
} finally {
loading.value = false
}
}
/** handleBackClick is a local helper used by this page script. */
const handleBackClick = () => {
router.back()
}
onMounted(() => {
fetchUserInfo()
restoreDraft()
})
onUnmounted(() => {
if (countdownTimer) {
clearInterval(countdownTimer)
}
})
</script>
<style scoped>
.mobile-container {
min-height: 100vh;
background: var(--theme-page-bg);
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 15px;
background: var(--theme-card-bg);
border-bottom: 1px solid var(--theme-border);
}
.header h1 {
font-size: 18px;
font-weight: bold;
margin: 0;
}
.back-btn,
.empty {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
}
.password-form {
padding: 15px;
}
.form-card {
border-radius: 16px;
overflow: hidden;
background: var(--theme-card-bg);
}
.password-tip {
margin-top: 8px;
color: var(--text-secondary);
font-size: 12px;
}
</style>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,147 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { afterSaleApi, orderApi } from '../api/order'
import type { AfterSaleVO, OrderArtistChangeRequestVO, OrderArtistReviewVO } from '../api/order'
const route = useRoute()
const router = useRouter()
const loading = ref(false)
const order = ref<any | null>(null)
const reviews = ref<OrderArtistReviewVO[]>([])
const changes = ref<OrderArtistChangeRequestVO[]>([])
const afterSales = ref<AfterSaleVO[]>([])
const orderId = computed(() => String(route.query.orderId || route.params.id || ''))
const items = computed(() => Array.isArray(order.value?.items) ? order.value.items : [])
const firstAppointment = computed(() => items.value.map((item: any) => item.appointmentTime).find(Boolean))
const formatTime = (value?: string) => value ? String(value).replace('T', ' ').slice(0, 16) : '--'
const latestChangeText = computed(() => {
const latest = changes.value.slice().sort((left: any, right: any) => String(right.updateTime || right.createTime || '').localeCompare(String(left.updateTime || left.createTime || '')))[0] as any
return latest ? (latest.statusText || latest.status || '改派记录') : '暂无改派'
})
const nodes = computed(() => {
const current = order.value || {}
const status = Number(current.status)
return [
{ key: 'created', title: '订单创建', desc: formatTime(current.createTime), done: true, active: false },
{ key: 'appointment', title: '预约确认', desc: formatTime(firstAppointment.value), done: Boolean(firstAppointment.value), active: status === 1 },
{ key: 'artist', title: '服务安排', desc: latestChangeText.value, done: changes.value.length > 0 || items.value.some((item: any) => item.artistName), active: changes.value.some(item => item.status === 'PENDING') },
{ key: 'service', title: status === 3 ? '订单取消' : '服务完成', desc: formatTime(current.completeTime || current.cancelTime || current.updateTime), done: status === 2 || status === 3, active: status === 2 || status === 3 },
{ key: 'after-sale', title: '售后/评价', desc: afterSales.value.length ? `${afterSales.value.length} 条售后` : (reviews.value.length ? `${reviews.value.length} 条评价` : '暂无记录'), done: afterSales.value.length > 0 || reviews.value.length > 0, active: afterSales.value.some(item => item.status === 'PENDING') || reviews.value.some(item => !item.rating) }
]
})
const loadProgress = async () => {
if (!orderId.value) return
loading.value = true
try {
const [detail, reviewList, changeList, afterSalePage] = await Promise.all([
orderApi.getOrderDetail(orderId.value),
orderApi.getOrderReviews(orderId.value).catch(() => []),
orderApi.getOrderArtistChangeRequests(orderId.value).catch(() => []),
afterSaleApi.listMy({ page: 1, size: 50 }).catch(() => ({ list: [] }))
])
order.value = detail
reviews.value = reviewList || []
changes.value = changeList || []
afterSales.value = ((afterSalePage as any)?.list || []).filter((item: AfterSaleVO) => String(item.orderId) === orderId.value)
} catch (error: any) {
order.value = null
message.error(error?.message || '服务进度加载失败')
} finally {
loading.value = false
}
}
onMounted(loadProgress)
</script>
<template>
<div class="progress-page">
<header class="header">
<a-button type="text" @click="router.back()">
<LeftOutlined />
</a-button>
<h1>服务进度</h1>
<a-button type="link" @click="loadProgress">刷新</a-button>
</header>
<main class="content">
<section class="hero-card">
<span>进度追踪</span>
<h2>{{ order?.orderNo || (orderId ? `订单 ${orderId}` : '选择订单') }}</h2>
<p>{{ order?.shopName || '查看预约、服务、评价与售后节点' }}</p>
</section>
<a-spin :spinning="loading">
<a-empty v-if="!orderId" description="缺少订单参数">
<a-button type="primary" @click="router.push('/orders')">选择订单</a-button>
</a-empty>
<template v-else>
<section class="progress-list">
<article v-for="node in nodes" :key="node.key" :class="{ done: node.done, active: node.active }">
<i />
<div>
<strong>{{ node.title }}</strong>
<span>{{ node.desc }}</span>
</div>
</article>
</section>
<section v-if="items.length" class="section-card">
<h3>项目进度</h3>
<p v-for="item in items" :key="item.id">
{{ item.productTitle || '预约项目' }}:{{ item.artistName || '待安排美甲师' }},{{ formatTime(item.appointmentTime) }}
</p>
</section>
<section v-if="changes.length" class="section-card">
<h3>改派记录</h3>
<p v-for="item in changes" :key="item.id">{{ item.statusText || item.status }}:{{ item.reason || item.timeImpactText || '已记录' }}</p>
</section>
<section v-if="afterSales.length" class="section-card">
<h3>售后记录</h3>
<p v-for="item in afterSales" :key="item.id">{{ item.afterSaleNo || item.id }}:{{ item.status || '-' }}</p>
</section>
<div class="actions">
<a-button @click="router.push(`/orders/${orderId}`)">订单详情</a-button>
<a-button type="primary" @click="router.push({ path: '/after-sale/apply', query: { orderId } })">申请售后</a-button>
</div>
</template>
</a-spin>
</main>
</div>
</template>
<style scoped>
.progress-page { min-height: 100vh; padding-top: 60px; background: var(--theme-page-bg); color: var(--text-primary); }
.header { position: fixed; top: 0; left: 0; right: 0; z-index: 10; display: flex; align-items: center; justify-content: space-between; height: 60px; padding: 9px 14px; background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent); border-bottom: 1px solid var(--theme-border); backdrop-filter: blur(14px); }
.header h1 { margin: 0; font-size: 18px; }
.content { padding: 16px 14px 32px; }
.hero-card, .section-card, .progress-list { border: 1px solid var(--theme-border); border-radius: 20px; background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent); box-shadow: 0 18px 44px rgba(74, 68, 63, 0.08); }
.hero-card { padding: 22px; margin-bottom: 14px; background: var(--theme-gradient-soft); }
.hero-card span { color: var(--theme-primary); font-size: 12px; font-weight: 700; letter-spacing: .05em; }
.hero-card h2 { margin: 10px 0 6px; font-size: 21px; }
.hero-card p { margin: 0; color: var(--text-secondary); line-height: 1.6; }
.progress-list { display: grid; gap: 0; overflow: hidden; }
.progress-list article { display: flex; gap: 12px; padding: 16px; border-top: 1px solid var(--theme-border); }
.progress-list article:first-child { border-top: 0; }
.progress-list i { width: 14px; height: 14px; margin-top: 3px; border-radius: 999px; background: var(--theme-border); box-shadow: 0 0 0 5px var(--theme-primary-soft); }
.progress-list article.done i, .progress-list article.active i { background: var(--theme-primary); }
.progress-list strong, .progress-list span { display: block; }
.progress-list span, .section-card p { margin-top: 6px; color: var(--text-secondary); line-height: 1.6; }
.section-card { margin-top: 14px; padding: 16px; }
.section-card h3 { margin: 0 0 10px; font-size: 17px; }
.section-card p { margin: 8px 0 0; }
.actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 16px; }
:deep(.ant-btn-primary) { background: var(--theme-primary); border-color: var(--theme-primary); }
:deep(.ant-btn-link) { color: var(--theme-primary); }
</style>
@@ -0,0 +1,258 @@
<template>
<div class="mobile-container">
<header class="header">
<a-button class="back-btn" type="text" @click="handleBackClick">
<LeftOutlined :style="{ fontSize: '20px' }" />
</a-button>
<h1>设置中心</h1>
<div class="empty"></div>
</header>
<div class="settings-menu">
<a-card :bordered="false" class="settings-card">
<a-list :data-source="settingsSections" :split="false">
<template #renderItem="{ item }">
<a-list-item v-if="item.type === 'title'" class="section-title">
<span>{{ item.title }}</span>
</a-list-item>
<a-list-item v-else class="setting-item" @click="handleSettingClick(item.key)">
<template #actions>
<RightOutlined />
</template>
<a-list-item-meta>
<template #avatar>
<div class="setting-icon" :style="{ backgroundColor: item.bgColor }">
<component :is="item.icon" />
</div>
</template>
<template #title>
<span>{{ item.title }}</span>
</template>
<template #description>
<span>{{ item.desc }}</span>
</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
</a-card>
</div>
<div class="version-info">
<a-typography-text type="secondary">版本 0.0.1</a-typography-text>
</div>
</div>
</template>
<script setup lang="ts">
/**
* SettingsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import {
LeftOutlined,
LockOutlined,
RightOutlined,
} from '@ant-design/icons-vue'
/**
* Purpose: router supports SettingsView.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()
/** settingsSections is a reactive state variable used by the template and event handlers. */
const settingsSections = ref([
{
type: 'title',
title: '账号与安全'
},
{
key: 'account',
title: '账号设置',
desc: '管理手机号、登录密码和账号安全',
icon: LockOutlined,
bgColor: 'var(--theme-primary-soft)'
}
])
/** handleBackClick is a local helper used by this page script. */
const handleBackClick = () => {
router.back()
}
/** handleSettingClick is a local helper used by this page script. */
const handleSettingClick = (key: string) => {
if (key === 'account') {
router.push('/settings/account')
return
}
}
</script>
<style scoped>
.mobile-container {
min-height: 100vh;
padding-top: 60px;
background:
linear-gradient(rgba(255, 255, 255, 0.68), rgba(255, 255, 255, 0.92)),
var(--theme-background-image),
var(--theme-page-bg);
background-size: cover, cover, auto;
background-position: center top;
}
.header {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 100;
display: flex;
justify-content: space-between;
align-items: center;
height: 60px;
padding: 10px 15px;
background: rgba(255, 255, 255, 0.92);
border-bottom: 1px solid var(--theme-border);
backdrop-filter: blur(14px);
}
.header h1 {
font-size: 18px;
font-weight: bold;
margin: 0;
color: var(--text-primary);
}
.back-btn,
.empty {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
}
.settings-menu {
padding: 15px;
}
.settings-card {
border-radius: 16px;
overflow: hidden;
background: var(--theme-card-bg);
border: 1px solid var(--theme-border);
box-shadow: 0 14px 34px rgba(122, 67, 88, 0.08);
}
.settings-card :deep(.ant-card-body) {
padding: 0;
}
.section-title {
padding: 12px 16px;
font-size: 13px;
color: var(--theme-accent);
background: var(--theme-primary-soft);
}
.setting-item {
padding: 16px;
cursor: pointer;
transition: background 0.3s;
border-bottom: 1px solid var(--theme-border);
}
.setting-item:hover {
background: var(--theme-primary-soft);
}
.setting-item:last-child {
border-bottom: none;
}
.setting-item :deep(.ant-list-item-action) {
margin-left: 8px;
color: var(--text-secondary);
}
.setting-icon {
width: 40px;
height: 40px;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
color: var(--theme-primary);
}
.setting-item :deep(.ant-list-item-meta-title) {
font-size: 15px;
font-weight: 500;
color: var(--text-primary);
}
.setting-item :deep(.ant-list-item-meta-description) {
font-size: 12px;
color: var(--text-secondary);
}
.version-info {
padding: 20px;
text-align: center;
}
.mobile-container {
padding-top: 68px;
background:
radial-gradient(circle at 85% 0%, color-mix(in srgb, var(--theme-primary) 28%, transparent), transparent 32%),
linear-gradient(180deg, color-mix(in srgb, var(--theme-card-bg) 78%, transparent), var(--theme-page-bg));
}
.header {
height: 64px;
padding: 12px 18px 10px;
background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent);
}
.header h1 {
font-size: 17px;
font-weight: 820;
}
.back-btn {
border-radius: 999px;
background: color-mix(in srgb, var(--theme-card-bg) 74%, transparent);
}
.settings-menu {
padding: 18px;
}
.settings-card {
border-radius: 24px;
background: color-mix(in srgb, var(--theme-card-bg) 90%, transparent);
box-shadow: 0 20px 42px color-mix(in srgb, var(--theme-neutral) 9%, transparent);
}
.section-title {
color: var(--theme-primary-action);
background: color-mix(in srgb, var(--theme-primary) 18%, var(--theme-card-bg));
font-weight: 800;
}
.setting-item {
padding: 18px 16px;
}
.setting-icon {
border-radius: 14px;
color: var(--theme-primary-action);
background: color-mix(in srgb, var(--theme-primary) 22%, var(--theme-card-bg)) !important;
}
</style>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,957 @@
<script setup lang="ts">
import { computed, onMounted, ref, shallowRef } from 'vue'
import { useRouter } from 'vue-router'
import {
CreditCardOutlined,
CrownOutlined,
GiftOutlined,
HistoryOutlined,
LeftOutlined,
PayCircleOutlined,
PercentageOutlined,
SafetyCertificateOutlined,
ScissorOutlined,
ShoppingOutlined,
StarFilled,
TrophyOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { userApi, type BalanceHistoryItem, type UserAssetVO, type VipRechargePlanVO } from '@/api/user'
const router = useRouter()
const loading = shallowRef(false)
const rechargeOpen = shallowRef(false)
const visibleHistoryCount = shallowRef(3)
const asset = ref<UserAssetVO | null>(null)
const history = ref<BalanceHistoryItem[]>([])
const plans = ref<VipRechargePlanVO[]>([])
const selectedPlan = ref<VipRechargePlanVO | null>(null)
const rechargeSectionRef = ref<HTMLElement | null>(null)
interface LevelStep {
name: string
amount: number
}
const levelSteps: [LevelStep, ...LevelStep[]] = [
{ name: '普通会员', amount: 0 },
{ name: '玫瑰金会员', amount: 1000 },
{ name: '钻石会员', amount: 5000 }
]
const money = (value?: number | string) => {
const amount = Number(value || 0)
return Number.isFinite(amount)
? amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
: '0.00'
}
const formatTime = (value?: string) => value ? value.replace('T', ' ').slice(0, 16) : '--'
const sceneText = (scene?: string) => {
const map: Record<string, string> = {
MANUAL_RECHARGE: '手工充值',
MANUAL_DEDUCT: '手工扣减',
ORDER_PAY: '订单消费',
ORDER_REFUND: '订单退款',
RECHARGE: '会员充值',
CONSUME: '余额消费'
}
return map[scene || ''] || scene || '余额变动'
}
const sceneIcon = (item: BalanceHistoryItem) => {
const scene = item.changeScene || item.type || ''
if (Number(item.amount) > 0 || scene.includes('RECHARGE') || scene.includes('REFUND')) {
return PayCircleOutlined
}
if (scene.includes('ORDER') || scene.includes('CONSUME')) {
return ScissorOutlined
}
return HistoryOutlined
}
const memberLevel = computed(() => asset.value?.vipLevel || '普通会员')
const totalRecharge = computed(() => Number(asset.value?.totalRechargeAmount || 0))
const balanceAmount = computed(() => Number(asset.value?.balance || 0))
const sortedPlans = computed(() => [...plans.value].sort((left, right) => {
const sortDelta = Number(left.sortOrder || 0) - Number(right.sortOrder || 0)
return sortDelta || Number(left.rechargeAmount || 0) - Number(right.rechargeAmount || 0)
}))
const visibleHistory = computed(() => history.value.slice(0, visibleHistoryCount.value))
const canLoadMoreHistory = computed(() => visibleHistoryCount.value < history.value.length)
const currentStep = computed(() => {
return [...levelSteps].reverse().find(step => totalRecharge.value >= step.amount) || levelSteps[0]
})
const nextStep = computed(() => levelSteps.find(step => step.amount > totalRecharge.value))
const levelProgress = computed(() => {
const next = nextStep.value
if (!next) return 100
const current = currentStep.value
const range = Math.max(next.amount - current.amount, 1)
return Math.min(100, Math.max(8, ((totalRecharge.value - current.amount) / range) * 100))
})
const nextLevelText = computed(() => nextStep.value ? `下一等级:${nextStep.value.name}` : '已达最高等级')
const remainingAmountText = computed(() => {
const next = nextStep.value
if (!next) return '继续保持你的专属礼遇'
return `再充值 ¥${money(Math.max(next.amount - totalRecharge.value, 0))} 可升级`
})
const validityText = computed(() => {
const start = formatTime(asset.value?.vipStartTime)
const expire = formatTime(asset.value?.vipExpireTime)
if (start === '--' && expire === '--') return '长期有效'
if (expire === '--') return `${start} 起生效`
return `${start} - ${expire}`
})
const benefitCards = computed(() => [
{
icon: GiftOutlined,
title: '生日礼遇',
desc: '生日月专属美甲套装',
tone: 'rose'
},
{
icon: SafetyCertificateOutlined,
title: '优先预约',
desc: '热门时段优先锁定档期',
tone: 'gold'
},
{
icon: PercentageOutlined,
title: '专属优惠',
desc: asset.value?.benefitInfo || '会员专属折扣权益',
tone: 'slate'
},
{
icon: CrownOutlined,
title: '护理礼遇',
desc: '精选护理权益持续更新',
tone: 'cream'
}
])
const planTag = (index: number) => {
if (index === 0) return '超值'
if (index === 1) return '最佳选择'
return '尊享'
}
const openPlan = (plan: VipRechargePlanVO) => {
selectedPlan.value = plan
rechargeOpen.value = true
}
const scrollToRecharge = () => {
rechargeSectionRef.value?.scrollIntoView({ behavior: 'smooth', block: 'start' })
}
const loadMoreHistory = () => {
visibleHistoryCount.value += 3
}
const loadData = async () => {
loading.value = true
try {
const [assetRes, historyRes] = await Promise.all([
userApi.getMyAsset(),
userApi.getMyBalanceHistory()
])
asset.value = assetRes
history.value = historyRes || []
plans.value = await userApi.listMyVipRechargePlans().catch(() => [])
} catch (error: any) {
message.error(error?.message || '获取 VIP 信息失败')
} finally {
loading.value = false
}
}
onMounted(loadData)
</script>
<template>
<div class="vip-center">
<header class="vip-topbar">
<button class="topbar-button" type="button" aria-label="返回" @click="router.back()">
<LeftOutlined />
</button>
<h1>VIP中心</h1>
<button class="topbar-button" type="button" aria-label="购物车" @click="router.push('/cart')">
<ShoppingOutlined />
</button>
</header>
<a-spin :spinning="loading">
<main class="vip-main">
<section class="vip-hero-card">
<div class="hero-glow hero-glow--top"></div>
<div class="hero-glow hero-glow--bottom"></div>
<div class="hero-content">
<div class="hero-head">
<div>
<span class="vip-kicker">当前会员等级</span>
<h2>{{ memberLevel }} <StarFilled /></h2>
</div>
<div class="fingerprint-badge">
<CrownOutlined />
</div>
</div>
<div class="hero-stats">
<div>
<span>可用余额</span>
<strong><small>¥</small>{{ money(balanceAmount) }}</strong>
</div>
<div>
<span>累计充值</span>
<strong><small>¥</small>{{ money(totalRecharge) }}</strong>
</div>
</div>
<div class="level-progress">
<div>
<span>等级进度</span>
<span>{{ nextLevelText }}</span>
</div>
<div class="progress-track">
<i :style="{ width: `${levelProgress}%` }"></i>
</div>
<p>{{ remainingAmountText }}</p>
</div>
</div>
<TrophyOutlined class="hero-watermark" />
</section>
<section class="vip-section">
<div class="section-head">
<h3>会员特权</h3>
<button type="button" @click="scrollToRecharge">查看全部</button>
</div>
<div class="benefit-grid">
<article
v-for="item in benefitCards"
:key="item.title"
class="benefit-card"
:class="`benefit-card--${item.tone}`"
>
<span class="benefit-icon">
<component :is="item.icon" />
</span>
<strong>{{ item.title }}</strong>
<p>{{ item.desc }}</p>
</article>
</div>
</section>
<section class="vip-section member-info-section">
<div class="section-head">
<h3>会员信息</h3>
</div>
<div class="info-grid">
<article>
<span>生效周期</span>
<strong>{{ validityText }}</strong>
</article>
<article>
<span>最近充值</span>
<strong>{{ formatTime(asset?.lastRechargeTime) }}</strong>
</article>
<article>
<span>等级来源</span>
<strong>{{ asset?.manualOverride ? '后台指定' : '自动计算' }}</strong>
</article>
<article>
<span>当前权益</span>
<strong>{{ asset?.benefitInfo || '暂无额外权益说明' }}</strong>
</article>
</div>
</section>
<section ref="rechargeSectionRef" class="vip-section recharge-section">
<div class="section-head">
<h3>快速充值</h3>
</div>
<div v-if="sortedPlans.length" class="plan-grid">
<article
v-for="(plan, index) in sortedPlans"
:key="String(plan.id)"
class="plan-card"
:class="{ 'plan-card--featured': index === 1 }"
>
<div class="plan-tag" :class="{ 'plan-tag--featured': index === 1 }">
{{ planTag(index) }}
</div>
<span class="plan-title">{{ plan.title || plan.vipLevel }}</span>
<div class="plan-price">
<small>¥</small>
<strong>{{ money(plan.rechargeAmount).replace('.00', '') }}</strong>
</div>
<p>赠送 <b>¥{{ money(plan.giftAmount) }}</b> 奖励金</p>
<button type="button" @click="openPlan(plan)">立即充值</button>
</article>
</div>
<a-empty v-else description="暂无可展示充值档位" />
</section>
<section class="vip-section history-section">
<div class="section-head">
<h3>最近动态</h3>
</div>
<div v-if="visibleHistory.length" class="history-card">
<article
v-for="item in visibleHistory"
:key="String(item.id)"
class="history-row"
>
<span class="history-icon" :class="{ 'history-icon--income': Number(item.amount) > 0 }">
<component :is="sceneIcon(item)" />
</span>
<div class="history-copy">
<strong>{{ sceneText(item.changeScene || item.type) }}</strong>
<span>{{ formatTime(item.changeTime) }}</span>
<em v-if="item.remark">{{ item.remark }}</em>
</div>
<div class="history-amount">
<strong :class="{ income: Number(item.amount) > 0 }">
{{ Number(item.amount) > 0 ? '+' : '' }}¥{{ money(item.amount) }}
</strong>
<span v-if="item.afterBalance !== undefined">余额: ¥{{ money(item.afterBalance) }}</span>
</div>
</article>
</div>
<a-empty v-else description="暂无余额变动" />
<button v-if="canLoadMoreHistory" class="load-more-button" type="button" @click="loadMoreHistory">
加载更多交易记录
</button>
</section>
</main>
</a-spin>
<a-modal v-model:open="rechargeOpen" title="充值档位说明" :footer="null">
<div class="plan-modal" v-if="selectedPlan">
<span class="modal-icon"><CreditCardOutlined /></span>
<h3>{{ selectedPlan.title || selectedPlan.vipLevel }}</h3>
<p>充值 ¥{{ money(selectedPlan.rechargeAmount) }},赠送 ¥{{ money(selectedPlan.giftAmount) }} 奖励金。</p>
<p>{{ selectedPlan.description || '该档位仅展示,暂不发起支付。' }}</p>
</div>
</a-modal>
</div>
</template>
<style scoped>
.vip-center {
--vip-bg: #fff8f4;
--vip-surface: rgba(255, 255, 255, 0.82);
--vip-surface-strong: rgba(255, 255, 255, 0.94);
--vip-surface-low: #fcf2ea;
--vip-surface-mid: #f6ece5;
--vip-surface-high: #f1e6df;
--vip-text: #1f1b17;
--vip-muted: #504444;
--vip-outline: #d4c2c3;
--vip-outline-soft: rgba(212, 194, 195, 0.54);
--vip-primary: #7c5357;
--vip-blush: #e8b4b8;
--vip-blush-soft: #ffdadc;
--vip-blush-dim: #eeb9bd;
--vip-gold: #775a19;
--vip-gold-soft: #fed488;
--vip-neutral: #5e5e5d;
--vip-neutral-soft: #c2c1bf;
--vip-hero-text: #fff8f4;
--vip-shadow: rgba(74, 68, 63, 0.1);
min-height: 100vh;
color: var(--vip-text);
background:
radial-gradient(circle at 84% 0%, rgba(232, 180, 184, 0.38), transparent 34%),
radial-gradient(circle at 4% 18%, rgba(254, 212, 136, 0.34), transparent 30%),
linear-gradient(180deg, var(--vip-bg) 0%, var(--vip-surface-low) 46%, var(--vip-bg) 100%);
}
.vip-topbar {
position: sticky;
top: 0;
z-index: 30;
display: grid;
grid-template-columns: 42px minmax(0, 1fr) 42px;
align-items: center;
width: min(100%, var(--app-mobile-max-width, 480px));
min-height: 64px;
margin: 0 auto;
padding: 8px 20px;
background: rgba(255, 248, 244, 0.86);
box-shadow: 0 8px 28px rgba(74, 68, 63, 0.06);
backdrop-filter: blur(18px);
}
.vip-topbar h1 {
margin: 0;
color: var(--vip-primary);
font-family: Georgia, 'Times New Roman', serif;
font-size: 24px;
font-weight: 700;
line-height: 1.15;
text-align: center;
}
.topbar-button {
display: inline-flex;
align-items: center;
justify-content: center;
width: 40px;
height: 40px;
padding: 0;
border: 0;
border-radius: 999px;
color: var(--vip-primary);
background: var(--vip-surface-strong);
box-shadow: 0 12px 24px rgba(74, 68, 63, 0.08);
cursor: pointer;
}
.topbar-button :deep(.anticon) {
font-size: 21px;
}
.vip-main {
display: grid;
gap: 32px;
width: min(100%, var(--app-mobile-max-width, 480px));
margin: 0 auto;
padding: 22px 20px 42px;
}
.vip-hero-card {
position: relative;
overflow: hidden;
padding: 28px;
border-radius: 32px;
color: var(--vip-hero-text);
background:
linear-gradient(135deg, var(--vip-primary) 0%, var(--vip-blush) 55%, var(--vip-gold-soft) 100%);
box-shadow: 0 26px 54px rgba(124, 83, 87, 0.22);
}
.hero-glow {
position: absolute;
width: 210px;
height: 210px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.13);
filter: blur(18px);
}
.hero-glow--top {
top: -74px;
right: -78px;
}
.hero-glow--bottom {
bottom: -118px;
left: -86px;
background: rgba(254, 212, 136, 0.24);
}
.hero-content {
position: relative;
z-index: 1;
display: grid;
gap: 22px;
}
.hero-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
}
.vip-kicker,
.section-head button,
.plan-title {
font-size: 12px;
font-weight: 800;
line-height: 1.2;
letter-spacing: 0;
text-transform: uppercase;
}
.vip-kicker {
display: block;
margin-bottom: 6px;
opacity: 0.78;
}
.hero-head h2 {
display: flex;
align-items: center;
gap: 8px;
margin: 0;
font-family: Georgia, 'Times New Roman', serif;
font-size: 28px;
font-weight: 700;
line-height: 1.15;
}
.hero-head h2 :deep(.anticon) {
color: var(--vip-gold-soft);
font-size: 18px;
}
.fingerprint-badge {
display: grid;
flex: 0 0 auto;
width: 52px;
height: 52px;
place-items: center;
border: 1px solid rgba(255, 255, 255, 0.28);
border-radius: 18px;
background: rgba(255, 255, 255, 0.18);
backdrop-filter: blur(12px);
}
.fingerprint-badge :deep(.anticon) {
font-size: 28px;
}
.hero-stats {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.hero-stats > div {
min-width: 0;
padding: 14px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 16px;
background: rgba(255, 255, 255, 0.12);
backdrop-filter: blur(10px);
}
.hero-stats span,
.level-progress span,
.level-progress p {
color: rgba(255, 255, 255, 0.74);
font-size: 12px;
line-height: 1.35;
}
.hero-stats strong {
display: flex;
align-items: baseline;
gap: 3px;
min-width: 0;
margin-top: 6px;
overflow-wrap: anywhere;
color: var(--vip-hero-text);
font-family: Georgia, 'Times New Roman', serif;
font-size: 22px;
line-height: 1.1;
}
.hero-stats small,
.plan-price small {
font-family: inherit;
font-size: 13px;
}
.level-progress {
display: grid;
gap: 8px;
}
.level-progress > div:first-child {
display: flex;
justify-content: space-between;
gap: 10px;
}
.progress-track {
height: 6px;
overflow: hidden;
border-radius: 999px;
background: rgba(255, 255, 255, 0.2);
}
.progress-track i {
display: block;
height: 100%;
border-radius: inherit;
background: var(--vip-hero-text);
box-shadow: 0 0 14px rgba(255, 255, 255, 0.5);
}
.level-progress p {
margin: 0;
}
.hero-watermark {
position: absolute;
right: 20px;
bottom: -26px;
color: rgba(255, 255, 255, 0.1);
font-size: 118px;
}
.vip-section {
display: grid;
gap: 18px;
}
.section-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.section-head h3 {
margin: 0;
color: var(--vip-text);
font-family: Georgia, 'Times New Roman', serif;
font-size: 24px;
font-weight: 700;
line-height: 1.2;
}
.section-head button {
border: 0;
color: var(--vip-primary);
background: transparent;
cursor: pointer;
}
.benefit-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px;
}
.benefit-card,
.member-info-section,
.plan-card,
.history-card {
border: 1px solid rgba(212, 194, 195, 0.5);
background: var(--vip-surface);
box-shadow: 0 20px 40px var(--vip-shadow);
backdrop-filter: blur(16px);
}
.benefit-card {
display: grid;
justify-items: center;
gap: 10px;
min-height: 164px;
padding: 20px 14px;
border-radius: 18px;
text-align: center;
}
.benefit-icon {
display: grid;
width: 50px;
height: 50px;
place-items: center;
border-radius: 999px;
font-size: 24px;
}
.benefit-card--rose .benefit-icon {
color: var(--vip-primary);
background: var(--vip-blush-soft);
}
.benefit-card--gold .benefit-icon {
color: var(--vip-gold);
background: rgba(254, 212, 136, 0.72);
}
.benefit-card--slate .benefit-icon {
color: var(--vip-neutral);
background: rgba(194, 193, 191, 0.48);
}
.benefit-card--cream .benefit-icon {
color: var(--vip-primary);
background: var(--vip-surface-high);
}
.benefit-card strong {
color: var(--vip-text);
font-size: 14px;
font-weight: 850;
}
.benefit-card p {
display: -webkit-box;
margin: 0;
overflow: hidden;
color: var(--vip-muted);
font-size: 12px;
line-height: 1.45;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
}
.member-info-section {
padding: 18px;
border-radius: 24px;
}
.info-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.info-grid article {
min-width: 0;
padding: 13px;
border: 1px solid var(--vip-outline-soft);
border-radius: 16px;
background: rgba(252, 242, 234, 0.78);
}
.info-grid span,
.history-copy span,
.history-copy em,
.history-amount span {
display: block;
color: var(--vip-muted);
font-size: 12px;
line-height: 1.35;
}
.info-grid strong {
display: block;
margin-top: 6px;
overflow-wrap: anywhere;
color: var(--vip-text);
font-size: 13px;
font-weight: 800;
line-height: 1.35;
}
.plan-grid {
display: grid;
gap: 16px;
}
.plan-card {
position: relative;
display: grid;
gap: 13px;
padding: 24px;
border-radius: 24px;
}
.plan-card--featured {
border-color: rgba(119, 90, 25, 0.24);
background: linear-gradient(135deg, rgba(255, 250, 240, 0.92), rgba(254, 212, 136, 0.28));
}
.plan-tag {
justify-self: start;
padding: 5px 11px;
border-radius: 999px;
color: var(--vip-primary);
background: var(--vip-blush-soft);
font-size: 10px;
font-weight: 900;
}
.plan-tag--featured {
position: absolute;
top: -11px;
right: 22px;
color: var(--vip-hero-text);
background: var(--vip-gold);
}
.plan-title {
color: var(--vip-muted);
}
.plan-price {
display: flex;
align-items: baseline;
gap: 5px;
color: var(--vip-primary);
}
.plan-price strong {
font-family: Georgia, 'Times New Roman', serif;
font-size: 40px;
line-height: 1;
}
.plan-card p {
margin: 0;
color: var(--vip-muted);
font-size: 14px;
}
.plan-card p b {
color: var(--vip-primary);
}
.plan-card button {
width: 100%;
min-height: 46px;
border: 0;
border-radius: 999px;
color: var(--vip-hero-text);
background: var(--vip-primary);
font-size: 14px;
font-weight: 850;
cursor: pointer;
box-shadow: 0 14px 28px rgba(124, 83, 87, 0.2);
}
.plan-card--featured button {
background: var(--vip-gold);
}
.history-card {
overflow: hidden;
border-radius: 24px;
}
.history-row {
display: grid;
grid-template-columns: 42px minmax(0, 1fr) auto;
gap: 12px;
align-items: center;
padding: 16px;
border-bottom: 1px solid var(--vip-outline-soft);
}
.history-row:last-child {
border-bottom: 0;
}
.history-icon {
display: grid;
width: 40px;
height: 40px;
place-items: center;
border-radius: 999px;
color: var(--vip-muted);
background: var(--vip-surface-high);
}
.history-icon--income {
color: var(--vip-primary);
background: var(--vip-blush-soft);
}
.history-copy {
min-width: 0;
}
.history-copy strong {
display: block;
overflow: hidden;
color: var(--vip-text);
font-size: 14px;
font-weight: 850;
text-overflow: ellipsis;
white-space: nowrap;
}
.history-copy em {
margin-top: 3px;
overflow: hidden;
font-style: normal;
text-overflow: ellipsis;
white-space: nowrap;
}
.history-amount {
min-width: 88px;
text-align: right;
}
.history-amount strong {
display: block;
color: var(--vip-text);
font-size: 13px;
font-weight: 900;
white-space: nowrap;
}
.history-amount strong.income {
color: var(--vip-gold);
}
.load-more-button {
width: 100%;
min-height: 44px;
border: 0;
border-radius: 16px;
color: var(--vip-primary);
background: rgba(232, 180, 184, 0.22);
font-weight: 850;
cursor: pointer;
}
.plan-modal {
display: grid;
gap: 10px;
text-align: center;
}
.modal-icon {
display: grid;
width: 54px;
height: 54px;
margin: 0 auto;
place-items: center;
border-radius: 999px;
color: var(--vip-primary);
background: var(--vip-blush-soft);
font-size: 25px;
}
.plan-modal h3 {
margin: 4px 0 0;
font-size: 18px;
font-weight: 850;
}
.plan-modal p {
margin: 0;
color: var(--vip-muted);
line-height: 1.65;
}
@media (max-width: 370px) {
.vip-main {
padding-right: 14px;
padding-left: 14px;
}
.vip-hero-card {
padding: 22px;
}
.hero-stats,
.benefit-grid,
.info-grid {
grid-template-columns: 1fr;
}
}
@media (min-width: 768px) {
.vip-topbar {
border-top-left-radius: 32px;
border-top-right-radius: 32px;
}
.plan-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
</style>
@@ -0,0 +1,520 @@
<template>
<div class="mobile-container">
<header class="header">
<div class="back-btn" @click="handleBackClick">
<el-icon><ArrowLeft /></el-icon>
</div>
<h1>我的收藏</h1>
<div class="empty"></div>
</header>
<div v-if="groups.length" class="group-tabs">
<button
class="group-tab"
:class="{ 'group-tab--active': activeGroupId === null }"
type="button"
@click="activeGroupId = null"
>
All
</button>
<button
v-for="group in groups"
:key="String(group.id)"
class="group-tab"
:class="{ 'group-tab--active': sameId(activeGroupId, group.id) }"
type="button"
@click="activeGroupId = group.id"
>
{{ group.name }}
</button>
</div>
<div class="wishlist-items">
<div v-for="item in visibleWishlistItems" :key="item.id" class="wishlist-item">
<div class="item-image" @click="handleProductClick(item.product.id)">
<img
v-if="getProductImages(item.product).length > 0"
:src="getProductImages(item.product)[0]"
:alt="item.product.title"
loading="lazy"
decoding="async"
/>
<div v-else class="image-placeholder" :style="{ backgroundColor: getRandomColor() }">
<span>{{ item.product.title ? item.product.title[0] : '作' }}</span>
</div>
</div>
<div class="item-details">
<h3 class="item-name" @click="handleProductClick(item.product.id)">{{ item.product.title }}</h3>
<div class="item-group">{{ item.groupName || '最近想做' }}</div>
<p v-if="item.note" class="item-note">{{ item.note }}</p>
<p class="item-price">¥{{ Number(item.product.price || 0).toFixed(2) }}</p>
<div class="item-actions">
<el-button
size="small"
:type="isProductInCart(item.product.id) ? 'info' : 'primary'"
@click="handleAddToCart(item.product.id)"
>
{{ isProductInCart(item.product.id) ? '购物车已有' : '加入购物车' }}
</el-button>
<el-icon class="delete-icon" @click="handleRemoveItem(item.product.id)"><Delete /></el-icon>
</div>
</div>
</div>
</div>
<div v-if="wishlistItems.length === 0" class="empty-wishlist">
<el-icon :size="60" :style="{ color: 'var(--theme-primary)' }"><StarFilled /></el-icon>
<p>收藏列表为空</p>
<el-button type="primary" @click="handleBrowseProducts">
浏览作品
</el-button>
</div>
</div>
</template>
<script setup lang="ts">
/**
* WishlistView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, ref, onMounted, inject } from 'vue'
import { ArrowLeft, Delete, StarFilled } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import 'element-plus/es/components/message/style/css'
/**
* Purpose: WishlistItem supports WishlistView.vue by holding or executing the wishlist item 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 { wishlistApi, type WishlistGroup, type WishlistItem } from '@/api/wishlist'
import { cartApi } from '@/api/cart'
import type { IdType } from '@/utils/id'
import { sameId } from '@/utils/id'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { fetchCartProductIdSet, hasCartProduct, withAddedCartProduct } from '@/utils/cart-state'
import { resolvePublicImageUrls, resolvePublicImageUrlsSync } from '@/utils/public-image-assets'
import type { PublicImageRecord } from '@/utils/public-image-assets'
/**
* Purpose: router supports WishlistView.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()
/**
* Purpose: updateCartCount supports WishlistView.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.
*/
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
/**
* Purpose: wishlistItems supports WishlistView.vue by holding or executing the wishlist items 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 wishlistItems = ref<WishlistItem[]>([])
const groups = ref<WishlistGroup[]>([])
const activeGroupId = ref<IdType | null>(null)
/**
* Purpose: imageUrls supports WishlistView.vue by holding or executing the image urls 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 imageUrls = ref<Record<string, string[]>>({})
/** cartProductIdSet is a reactive state variable used by the template and event handlers. */
const cartProductIdSet = ref(new Set<string>())
/**
* Purpose: DEFAULT_PRODUCT_IMAGE supports WishlistView.vue by holding or executing the default product image 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 DEFAULT_PRODUCT_IMAGE = 'data:image/svg+xml;base64,PHN2ZyB3aW0dPSJodHRwOi8vd3d3Lm9yZy8yMDAwL3N2ZyI+Pjwvc3ZnPg=='
const visibleWishlistItems = computed(() => {
if (activeGroupId.value === null) {
return wishlistItems.value
}
return wishlistItems.value.filter(item => sameId(item.groupId, activeGroupId.value))
})
/** handleBackClick is a local helper used by this page script. */
const handleBackClick = () => {
router.back()
}
/** fetchWishlist is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchWishlist = async () => {
try {
const [response, nextGroups, nextCartProductIdSet] = await Promise.all([
wishlistApi.getWishlist(),
wishlistApi.getGroups(),
fetchCartProductIdSet()
])
cartProductIdSet.value = nextCartProductIdSet
groups.value = nextGroups
wishlistItems.value = response as unknown as WishlistItem[]
await loadImageUrls(response as unknown as WishlistItem[])
} catch (error: any) {
console.error('获取收藏列表失败:', error)
ElMessage.error(error?.message || '获取收藏列表失败')
}
}
/** loadImageUrls is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadImageUrls = async (items: WishlistItem[]) => {
for (const item of items) {
const productKey = String(item.product.id)
const cachedUrls = resolvePublicImageUrlsSync(item.product as PublicImageRecord, '')
if (cachedUrls.length) {
imageUrls.value[productKey] = cachedUrls
}
const urls = await resolvePublicImageUrls(item.product as PublicImageRecord, DEFAULT_PRODUCT_IMAGE)
imageUrls.value[productKey] = urls.length ? urls : [DEFAULT_PRODUCT_IMAGE]
}
}
/** getProductImages is a local helper used by this page script. */
const getProductImages = (product: { id: IdType }): string[] => {
return imageUrls.value[String(product.id)] || [DEFAULT_PRODUCT_IMAGE]
}
/** isProductInCart is a local helper used by this page script. */
const isProductInCart = (productId: IdType) => hasCartProduct(cartProductIdSet.value, productId)
/** handleAddToCart is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleAddToCart = async (productId: IdType) => {
if (isProductInCart(productId)) {
ElMessage.info('购物车已有')
return
}
try {
await runWithGlobalLoading(() => cartApi.addToCart({ productId, quantity: 1 }))
cartProductIdSet.value = withAddedCartProduct(cartProductIdSet.value, productId)
await updateCartCount()
ElMessage.success('已添加到购物车')
} catch (error: any) {
console.error('添加到购物车失败:', error)
ElMessage.error(error?.message || '添加到购物车失败')
}
}
/** handleRemoveItem is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleRemoveItem = async (productId: IdType) => {
try {
await runWithGlobalLoading(() => wishlistApi.removeFromWishlist(productId))
wishlistItems.value = wishlistItems.value.filter(item => !sameId(item.productId, productId))
ElMessage.success('已从收藏中移除')
} catch (error: any) {
console.error('移除收藏失败:', error)
ElMessage.error(error?.message || '移除收藏失败')
}
}
/** handleBrowseProducts is a local helper used by this page script. */
const handleBrowseProducts = () => {
router.push('/products')
}
/** handleProductClick is a local helper used by this page script. */
const handleProductClick = (productId: IdType) => {
router.push(`/product/${productId}`)
}
/** getRandomColor is a local helper used by this page script. */
const getRandomColor = () => {
return 'var(--theme-primary-soft)'
}
onMounted(() => {
fetchWishlist()
})
</script>
<style scoped>
.mobile-container {
min-height: 100vh;
padding-top: 60px;
background:
linear-gradient(rgba(255, 255, 255, 0.68), rgba(255, 255, 255, 0.92)),
var(--theme-background-image),
var(--theme-page-bg);
background-size: cover, cover, auto;
background-position: center top;
}
.header {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 100;
display: flex;
justify-content: space-between;
align-items: center;
height: 60px;
padding: 10px 15px;
background: rgba(255, 255, 255, 0.92);
border-bottom: 1px solid var(--theme-border);
backdrop-filter: blur(14px);
}
.back-btn {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
color: var(--text-primary);
}
.header h1 {
margin: 0;
font-size: 18px;
font-weight: bold;
color: var(--text-primary);
}
.empty {
width: 40px;
}
.group-tabs {
display: flex;
gap: 8px;
overflow-x: auto;
padding: 14px 16px 0;
}
.group-tab {
flex: 0 0 auto;
height: 32px;
padding: 0 12px;
border: 1px solid var(--theme-border);
border-radius: 8px;
background: var(--theme-card-bg);
color: var(--text-secondary);
font-size: 13px;
line-height: 30px;
white-space: nowrap;
}
.group-tab--active {
border-color: var(--theme-primary);
background: var(--theme-primary-soft);
color: var(--theme-primary);
font-weight: 600;
}
.wishlist-items {
padding: 16px;
padding-bottom: 28px;
}
.wishlist-item {
display: flex;
gap: 15px;
padding: 15px;
background: var(--theme-card-bg);
border: 1px solid var(--theme-border);
border-radius: 16px;
margin-bottom: 15px;
box-shadow: 0 14px 34px rgba(122, 67, 88, 0.08);
}
.item-image {
width: 80px;
height: 80px;
border-radius: 10px;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
cursor: pointer;
}
.item-image img {
width: 100%;
height: 100%;
object-fit: cover;
}
.image-placeholder {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
font-size: 30px;
font-weight: bold;
color: rgba(0, 0, 0, 0.1);
border: 1px solid var(--theme-border);
}
.item-details {
flex: 1;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.item-name {
font-size: 16px;
font-weight: bold;
margin: 0 0 5px 0;
color: var(--text-primary);
}
.item-group {
width: fit-content;
max-width: 100%;
margin-bottom: 6px;
padding: 2px 8px;
border-radius: 8px;
background: var(--theme-primary-soft);
color: var(--theme-accent);
font-size: 12px;
line-height: 18px;
}
.item-note {
margin: 0 0 8px;
color: var(--text-secondary);
font-size: 13px;
line-height: 18px;
word-break: break-word;
}
.item-price {
color: var(--theme-primary);
font-weight: bold;
margin: 0 0 10px 0;
}
.item-actions {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
}
.delete-icon {
color: var(--theme-accent);
cursor: pointer;
font-size: 20px;
}
.empty-wishlist {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin: 16px;
padding: 64px 20px;
color: var(--text-secondary);
background: var(--theme-card-bg);
border: 1px solid var(--theme-border);
border-radius: 18px;
box-shadow: 0 14px 34px rgba(122, 67, 88, 0.08);
}
.empty-wishlist p {
margin: 20px 0;
font-size: 16px;
}
:deep(.el-button--primary) {
--el-button-bg-color: var(--theme-primary);
--el-button-border-color: var(--theme-primary);
--el-button-hover-bg-color: var(--theme-accent);
--el-button-hover-border-color: var(--theme-accent);
}
:deep(.el-button--info) {
--el-button-bg-color: var(--theme-primary-soft);
--el-button-border-color: var(--theme-border);
--el-button-text-color: var(--theme-accent);
--el-button-hover-bg-color: var(--theme-primary-soft);
--el-button-hover-border-color: var(--theme-border);
--el-button-hover-text-color: var(--theme-accent);
}
.mobile-container {
padding-top: 68px;
background:
radial-gradient(circle at 84% 0%, color-mix(in srgb, var(--theme-primary) 26%, transparent), transparent 32%),
linear-gradient(180deg, color-mix(in srgb, var(--theme-card-bg) 76%, transparent), var(--theme-page-bg));
}
.header {
height: 64px;
padding: 12px 18px 10px;
background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent);
}
.header h1 {
font-size: 17px;
font-weight: 820;
}
.back-btn {
border-radius: 999px;
background: color-mix(in srgb, var(--theme-card-bg) 74%, transparent);
}
.group-tabs {
padding: 16px 18px 0;
}
.group-tab {
height: 34px;
border-radius: 999px;
background: color-mix(in srgb, var(--theme-card-bg) 84%, transparent);
}
.group-tab--active {
border-color: color-mix(in srgb, var(--theme-primary) 40%, var(--theme-border));
background: color-mix(in srgb, var(--theme-primary) 20%, var(--theme-card-bg));
color: var(--theme-primary-action);
}
.wishlist-items {
padding: 18px;
}
.wishlist-item {
border-radius: 24px;
background: color-mix(in srgb, var(--theme-card-bg) 90%, transparent);
box-shadow: 0 18px 42px color-mix(in srgb, var(--theme-neutral) 8%, transparent);
}
.item-image {
width: 92px;
height: 92px;
border-radius: 18px;
}
.item-name {
font-weight: 820;
}
.item-group {
border-radius: 999px;
color: var(--theme-primary-action);
background: color-mix(in srgb, var(--theme-primary) 18%, var(--theme-card-bg));
}
.item-price {
color: var(--theme-primary-action);
}
.empty-wishlist {
border-radius: 24px;
background: color-mix(in srgb, var(--theme-card-bg) 90%, transparent);
box-shadow: 0 18px 42px color-mix(in srgb, var(--theme-neutral) 8%, transparent);
}
:deep(.el-button--primary) {
--el-button-bg-color: var(--theme-primary-action);
--el-button-border-color: var(--theme-primary-action);
--el-button-hover-bg-color: var(--theme-secondary);
--el-button-hover-border-color: var(--theme-secondary);
}
</style>