diff --git a/Frontend/src/api/admin.ts b/Frontend/src/api/admin.ts index fda2263c..71c7bf73 100644 --- a/Frontend/src/api/admin.ts +++ b/Frontend/src/api/admin.ts @@ -3,10 +3,9 @@ import router from '../router' import { message } from 'ant-design-vue' import { ADMIN_API_BASE_URL } from '../config/api' -// 防重复提示标志 let lastErrorTime = 0 let lastErrorMessage = '' -const ERROR_DEBOUNCE_TIME = 1000 // 1秒内不重复显示相同错误 +const ERROR_DEBOUNCE_TIME = 1000 const adminApi = axios.create({ baseURL: ADMIN_API_BASE_URL, @@ -16,10 +15,62 @@ const adminApi = axios.create({ } }) +let isRefreshing = false +let failedQueue: Array<{ + resolve: (value?: any) => void + reject: (reason?: any) => void +}> = [] + +const processQueue = (error: any, 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() + if (now - lastErrorTime > ERROR_DEBOUNCE_TIME || msg !== lastErrorMessage) { + lastErrorTime = now + lastErrorMessage = msg + message.error(msg) + } +} + +const isAuthFreePath = (url?: string) => { + return Boolean(url?.includes('/auth/login') || url?.includes('/auth/refresh')) +} + +const handleAdminTokenExpired = () => { + localStorage.removeItem('adminAccessToken') + localStorage.removeItem('adminRefreshToken') + localStorage.removeItem('adminUserInfo') + localStorage.removeItem('userPermissions') + sessionStorage.removeItem('adminAccessToken') + sessionStorage.removeItem('adminRefreshToken') + + if (Date.now() - lastErrorTime > ERROR_DEBOUNCE_TIME || lastErrorMessage !== '登录已过期,请重新登录') { + showError('登录已过期,请重新登录') + } + + setTimeout(() => { + try { + router.push('/admin/login').catch(() => { + window.location.href = '/admin/login' + }) + } catch { + window.location.href = '/admin/login' + } + }, 300) +} + adminApi.interceptors.request.use( config => { - // 登录请求不需要携带Token - if (!config.url?.includes('/auth/login')) { + if (!isAuthFreePath(config.url)) { let token = localStorage.getItem('adminAccessToken') if (!token) { token = sessionStorage.getItem('adminAccessToken') @@ -30,9 +81,7 @@ adminApi.interceptors.request.use( } return config }, - error => { - return Promise.reject(error) - } + error => Promise.reject(error) ) adminApi.interceptors.response.use( @@ -41,7 +90,7 @@ adminApi.interceptors.response.use( if (res.code !== 200) { const errorMsg = res.message || '请求失败' if (!errorMsg.includes('权限') && !errorMsg.includes('permission')) { - message.error(errorMsg) + showError(errorMsg) } else { console.error('权限不足:', errorMsg) } @@ -50,35 +99,56 @@ adminApi.interceptors.response.use( return res.data as any }, async (error: AxiosError) => { - // 防抖处理错误提示 - const showError = (msg: string) => { - const now = Date.now() - if (now - lastErrorTime > ERROR_DEBOUNCE_TIME || msg !== lastErrorMessage) { - lastErrorTime = now - lastErrorMessage = msg - message.error(msg) - } - } + const originalRequest = error.config as any if (error.response?.status === 401) { - // 登录过期,只提示一次 - if (Date.now() - lastErrorTime > ERROR_DEBOUNCE_TIME || lastErrorMessage !== '登录已过期,请重新登录') { - localStorage.removeItem('adminAccessToken') - localStorage.removeItem('adminRefreshToken') - localStorage.removeItem('adminUserInfo') - sessionStorage.removeItem('adminAccessToken') - showError('登录已过期,请重新登录') - try { - router.push('/admin/login').catch(err => { - console.error('跳转到登录页失败:', err) - window.location.href = '/admin/login' + if (!originalRequest?._retry && !isAuthFreePath(originalRequest?.url)) { + if (isRefreshing) { + return new Promise((resolve, reject) => { + failedQueue.push({ resolve, reject }) + }).then(token => { + if (token) { + originalRequest.headers.Authorization = `Bearer ${token}` + } + return adminApi(originalRequest) }) - } catch (err) { - console.error('跳转到登录页异常:', err) - window.location.href = '/admin/login' + } + + originalRequest._retry = true + isRefreshing = true + + try { + let refreshToken = localStorage.getItem('adminRefreshToken') + if (!refreshToken) { + refreshToken = sessionStorage.getItem('adminRefreshToken') + } + if (!refreshToken) { + throw new Error('No refresh token available') + } + + const response = await adminAuthApi.refreshToken(refreshToken) + const newToken = (response as any).accessToken + const newRefreshToken = (response as any).refreshToken + + localStorage.setItem('adminAccessToken', newToken) + localStorage.setItem('adminRefreshToken', newRefreshToken) + sessionStorage.setItem('adminAccessToken', newToken) + sessionStorage.setItem('adminRefreshToken', newRefreshToken) + + processQueue(null, newToken) + originalRequest.headers.Authorization = `Bearer ${newToken}` + return adminApi(originalRequest) + } catch (refreshError) { + processQueue(refreshError, null) + handleAdminTokenExpired() + return Promise.reject(refreshError) + } finally { + isRefreshing = false } } - } else if (error.response?.status !== 403) { // 403权限不足不提示 + + handleAdminTokenExpired() + } else if (error.response?.status !== 403) { const errorMsg = (error.response?.data as any)?.message || error.message || '请求失败' showError(errorMsg) } else { @@ -102,10 +172,28 @@ export interface AdminLoginResponse { userInfo: any } +export interface LoginShopSelectionResponse { + allowShoplessLogin: boolean + message: string + shops: Array<{ + id: number | string + shopName: string + }> +} + export const adminAuthApi = { login: (data: AdminLoginRequest) => { return adminApi.post('/auth/login', data) }, + getLoginShops: (account: string) => { + return adminApi.get(`/auth/login-shops/${encodeURIComponent(account)}`) + }, + logout: () => { + return adminApi.post('/auth/logout') + }, + switchShop: (shopId?: string | number) => { + return adminApi.post('/auth/switch-shop', { shopId }) + }, refreshToken: (refreshToken: string) => { return adminApi.post<{ accessToken: string; refreshToken: string }>('/auth/refresh', { refreshToken }) } @@ -275,6 +363,7 @@ export interface Shop { description: string address: string businessHours: string + status?: number coverImageFileId?: string coverImageUrls?: string[] imageFileIds?: string @@ -297,6 +386,7 @@ export interface CreateShopRequest { businessHours: string coverImageFileId?: string imageFileIds?: string + status?: number } export const adminShopApi = { @@ -312,6 +402,9 @@ export const adminShopApi = { updateShop: (id: number, data: CreateShopRequest) => { return adminApi.put(`/shops/update/${id}`, data) }, + updateShopStatus: (id: number, status: number) => { + return adminApi.put(`/shops/status/${id}`, { status }) + }, deleteShop: (id: number) => { return adminApi.delete(`/shops/delete/${id}`) } @@ -321,6 +414,8 @@ export interface UserVO { id: number shopId?: number shopName?: string + shopIds?: Array + shopNames?: string[] nickname: string account: string avatar: string @@ -429,7 +524,6 @@ export interface AdminUserVipOverrideRequest { remark?: string } -// 别名导出,兼容旧代码 export const userApi = adminUserApi export interface OrderVO { @@ -460,16 +554,18 @@ export const adminOrderApi = { } } -// 仪表盘相关接口 export interface HotProductVO { - productId: number - productName: string - orderCount: number + id: number + title: string + price: number + likeCount: number + collectCount: number } export interface RecentActivityVO { id: number type: string + title?: string description: string time: string color?: string diff --git a/Frontend/src/api/auth.ts b/Frontend/src/api/auth.ts index 38077756..cd65113b 100644 --- a/Frontend/src/api/auth.ts +++ b/Frontend/src/api/auth.ts @@ -8,20 +8,20 @@ export interface LoginRequest { account: string password: string rememberMe?: boolean - shopId?: number + shopId?: string | number } export interface PhoneLoginRequest { phone: string verificationCode: string - shopId?: number + shopId?: string | number } export interface RegisterRequest { account: string password: string nickname: string - shopId?: number + shopId?: string | number phone?: string verificationCode?: string } @@ -38,7 +38,11 @@ export interface UserInfo { nickname: string avatar?: string signature?: string + type?: number + shopId?: number | string shopName?: string + shopIds?: Array + shopNames?: string[] createTime: string updateTime?: string } @@ -58,6 +62,10 @@ export interface ResetPasswordRequest { newPassword: string } +export interface SwitchShopRequest { + shopId?: string | number +} + export const authApi = { sendVerificationCode: (data: SendVerificationCodeRequest) => { return api.post('/user/send-verification-code', data) @@ -87,6 +95,10 @@ export const authApi = { return api.post('/user/logout') }, + switchShop: (data: SwitchShopRequest) => { + return api.post('/user/switch-shop', data) + }, + getUserInfo: () => { return api.get('/user/info') }, @@ -94,4 +106,4 @@ export const authApi = { resetPasswordByPhone: (data: ResetPasswordRequest) => { return api.post('/user/reset-password-by-phone', data) } -} \ No newline at end of file +} diff --git a/Frontend/src/api/coupon.ts b/Frontend/src/api/coupon.ts index 1255fb5d..1b6bf03d 100644 --- a/Frontend/src/api/coupon.ts +++ b/Frontend/src/api/coupon.ts @@ -127,12 +127,12 @@ export const couponApi = { }, // 获取用户优惠券列表 - listUserCoupons: (status?: number) => { - return request({ + listUserCoupons: async (status?: number): Promise => { + return await request({ url: '/coupon/user/list', method: 'get', params: { status } - }) + }) as UserCoupon[] }, // 使用优惠券 @@ -145,11 +145,11 @@ export const couponApi = { }, // 获取作品可用的优惠券 - getAvailableCoupons: (productTags: string, productPrice: number, shopId?: number) => { - return request({ + getAvailableCoupons: async (productTags: string, productPrice: number, shopId?: number): Promise => { + return await request({ url: '/coupon/available', method: 'get', params: { productTags, productPrice, shopId } - }) + }) as UserCoupon[] } } diff --git a/Frontend/src/api/index.ts b/Frontend/src/api/index.ts index 7700c959..84716332 100644 --- a/Frontend/src/api/index.ts +++ b/Frontend/src/api/index.ts @@ -137,7 +137,13 @@ api.interceptors.response.use( url?.includes('/user/refresh-token') || url?.includes('/user/send-verification-code') || url?.includes('/user/phone-login') || + url?.includes('/product/get/') || + url?.includes('/product/list/') || + url?.includes('/shop/get/') || + url?.includes('/shop/list/public') || url?.includes('/shop/list/simple') || + url?.includes('/tag/list/all') || + url?.includes('/file/get-signed-url/') || url?.includes('/admin/auth/login') || url?.includes('/admin/auth/refresh') } diff --git a/Frontend/src/api/order.ts b/Frontend/src/api/order.ts index ecab5532..a7a8d445 100644 --- a/Frontend/src/api/order.ts +++ b/Frontend/src/api/order.ts @@ -20,8 +20,8 @@ export const orderApi = { }, // 获取订单列表 - getOrderList: () => { - return api.get('/order/list') + getOrderList: async (): Promise => { + return await api.get('/order/list') as unknown as any[] }, // 获取订单详情 diff --git a/Frontend/src/api/product.ts b/Frontend/src/api/product.ts index 684e1607..5a7ff376 100644 --- a/Frontend/src/api/product.ts +++ b/Frontend/src/api/product.ts @@ -13,6 +13,8 @@ export interface ProductVO { price: number estimatedTime: number approximateDuration?: string + bookableArtists?: string + availableCoupons?: string category: string tags?: string tagList?: string[] diff --git a/Frontend/src/api/shop.ts b/Frontend/src/api/shop.ts index 1e60cf34..f596eb9d 100644 --- a/Frontend/src/api/shop.ts +++ b/Frontend/src/api/shop.ts @@ -6,6 +6,7 @@ export interface ShopVO { description: string address: string businessHours: string + status?: number imageFileIds: string imageUrls?: string[] createTime: string @@ -45,15 +46,19 @@ export interface UpdateShopRequest { } export const shopApi = { - getAllShops: () => { - return api.get('/shop/list/all') + getAllShops: async (): Promise => { + return await api.get('/shop/list/all') as unknown as ShopVO[] }, - getShopsSimple: () => { - return api.get('/shop/list/simple') + getPublicShops: async (): Promise => { + return await api.get('/shop/list/public') as unknown as ShopVO[] }, - getShopById: (id: number) => { - return api.get(`/shop/get/${id}`) + getShopsSimple: async (): Promise => { + return await api.get('/shop/list/simple') as unknown as ShopSimpleVO[] + }, + + getShopById: async (id: number): Promise => { + return await api.get(`/shop/get/${id}`) as unknown as ShopVO } } diff --git a/Frontend/src/api/user.ts b/Frontend/src/api/user.ts index bec07198..6bd1e5e0 100644 --- a/Frontend/src/api/user.ts +++ b/Frontend/src/api/user.ts @@ -5,6 +5,8 @@ export interface UserVO extends UserInfo { id: number shopId?: number shopName?: string + shopIds?: Array + shopNames?: string[] nickname: string account: string avatar: string @@ -39,6 +41,7 @@ export interface CreateUserRequest { password: string type: number shopId?: number + shopIds?: Array } export interface UpdateUserRequest { @@ -47,6 +50,7 @@ export interface UpdateUserRequest { phone?: string type?: number shopId?: number + shopIds?: Array } export interface UpdatePasswordRequest { @@ -70,6 +74,15 @@ export interface LoginAccountCheckResponse { message: string } +export interface LoginShopSelectionResponse { + allowShoplessLogin: boolean + message: string + shops: Array<{ + id: number | string + shopName: string + }> +} + export interface UpdatePhoneRequest { oldPhone: string newPhone: string @@ -77,8 +90,8 @@ export interface UpdatePhoneRequest { } export const userApi = { - getUserInfo: () => { - return api.get('/user/info') + getUserInfo: async (): Promise => { + return await api.get('/user/info') as unknown as UserVO }, updateUserInfo: (data: UpdateUserInfoRequest) => { return api.put('/user/update', data) @@ -92,24 +105,33 @@ export const userApi = { updatePhone: (data: UpdatePhoneRequest) => { return api.put('/user/phone', data) }, - getUserByAccount: (account: string) => { - return api.get(`/user/get/account/${account}`) + getUserByAccount: async (account: string): Promise => { + return await api.get(`/user/get/account/${account}`) as unknown as UserVO }, - checkAccountAvailability: (account: string) => { - return api.get(`/user/check/account/${encodeURIComponent(account)}`) + checkAccountAvailability: async (account: string): Promise => { + return await api.get(`/user/check/account/${encodeURIComponent(account)}`) as unknown as AvailabilityCheckResponse }, - checkLoginAccountAvailability: (account: string) => { - return api.get(`/user/check/login-account/${encodeURIComponent(account)}`) + checkLoginAccountAvailability: async (account: string): Promise => { + return await api.get(`/user/check/login-account/${encodeURIComponent(account)}`) as unknown as LoginAccountCheckResponse }, - checkPhoneAvailability: (phone: string) => { - return api.get(`/user/check/phone/${encodeURIComponent(phone)}`) + getLoginShopsByAccount: async (account: string): Promise => { + return await api.get(`/user/check/login-shops/account/${encodeURIComponent(account)}`) as unknown as LoginShopSelectionResponse }, - listUsersByType: (type: number) => { - return api.get(`/user/list/type/${type}`) + getLoginShopsByPhone: async (phone: string): Promise => { + return await api.get(`/user/check/login-shops/phone/${encodeURIComponent(phone)}`) as unknown as LoginShopSelectionResponse + }, + checkPhoneAvailability: async (phone: string): Promise => { + return await api.get(`/user/check/phone/${encodeURIComponent(phone)}`) as unknown as AvailabilityCheckResponse + }, + listUsersByType: async (type: number): Promise => { + return await api.get(`/user/list/type/${type}`) as unknown as UserVO[] }, sendVerificationCode: (data: { phone: string }) => { return api.post('/user/send-verification-code', data) }, + switchShop: (shopId?: string | number) => { + return api.post('/user/switch-shop', { shopId }) + }, deactivateAccount: () => { return api.delete('/user/deactivate') } diff --git a/Frontend/src/api/wishlist.ts b/Frontend/src/api/wishlist.ts index d25605ef..d6a66c65 100644 --- a/Frontend/src/api/wishlist.ts +++ b/Frontend/src/api/wishlist.ts @@ -27,19 +27,19 @@ export interface WishlistItem { } export const wishlistApi = { - addToWishlist: (productId: number) => { - return api.post('/wishlist/add', { productId }) + addToWishlist: async (productId: number): Promise => { + return await api.post('/wishlist/add', { productId }) as unknown as boolean }, - removeFromWishlist: (productId: number) => { - return api.post('/wishlist/remove', { productId }) + removeFromWishlist: async (productId: number): Promise => { + return await api.post('/wishlist/remove', { productId }) as unknown as boolean }, - checkWishlist: (productId: number) => { - return api.get(`/wishlist/check?productId=${productId}`) + checkWishlist: async (productId: number): Promise => { + return await api.get(`/wishlist/check?productId=${productId}`) as unknown as boolean }, - getWishlist: () => { - return api.get('/wishlist/list') + getWishlist: async (): Promise => { + return await api.get('/wishlist/list') as unknown as WishlistItem[] } } diff --git a/Frontend/src/components.d.ts b/Frontend/src/components.d.ts index 85c1395f..3f126148 100644 --- a/Frontend/src/components.d.ts +++ b/Frontend/src/components.d.ts @@ -52,6 +52,7 @@ declare module 'vue' { ARadio: typeof import('ant-design-vue/es')['Radio'] ARadioButton: typeof import('ant-design-vue/es')['RadioButton'] ARadioGroup: typeof import('ant-design-vue/es')['RadioGroup'] + 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'] @@ -75,7 +76,6 @@ declare module 'vue' { ElColorPicker: typeof import('element-plus/es')['ElColorPicker'] ElConfigProvider: typeof import('element-plus/es')['ElConfigProvider'] ElIcon: typeof import('element-plus/es')['ElIcon'] - ElTag: typeof import('element-plus/es')['ElTag'] HelloWorld: typeof import('./components/HelloWorld.vue')['default'] RouterLink: typeof import('vue-router')['RouterLink'] RouterView: typeof import('vue-router')['RouterView'] diff --git a/Frontend/src/components/BottomNav.vue b/Frontend/src/components/BottomNav.vue index 609284f1..cb6ab664 100644 --- a/Frontend/src/components/BottomNav.vue +++ b/Frontend/src/components/BottomNav.vue @@ -98,7 +98,7 @@ const currentRoute = computed(() => { // 处理导航点击事件 const handleNavClick = (tab: string) => { if (tab === 'home') { - router.push('/') + router.push('/home') } else if (tab === 'products') { router.push('/products') } else if (tab === 'cart') { diff --git a/Frontend/src/config/api.ts b/Frontend/src/config/api.ts index 97877d1c..10a72931 100644 --- a/Frontend/src/config/api.ts +++ b/Frontend/src/config/api.ts @@ -1,7 +1,7 @@ // API配置文件 // 提取域名和端口,方便后续修改 export const API_CONFIG = { - domain: 'http://yunail.art', + domain: 'http://127.0.0.1', port: '80', basePath: '/api', adminBasePath: '/admin/api' diff --git a/Frontend/src/router/index.ts b/Frontend/src/router/index.ts index c6057723..7b45fc1a 100644 --- a/Frontend/src/router/index.ts +++ b/Frontend/src/router/index.ts @@ -13,19 +13,19 @@ const router = createRouter({ path: '/home', name: 'home', component: () => import('../views/HomeView.vue'), - meta: { requiresAuth: true, isAdmin: false } + meta: { requiresAuth: false, isAdmin: false } }, { path: '/products', name: 'products', component: () => import('../views/ProductListView.vue'), - meta: { requiresAuth: true, isAdmin: false } + meta: { requiresAuth: false, isAdmin: false } }, { path: '/product/:id', name: 'product-detail', component: () => import('../views/ProductDetailView.vue'), - meta: { requiresAuth: true, hideNav: true, isAdmin: false } + meta: { requiresAuth: false, hideNav: true, isAdmin: false } }, { path: '/cart', @@ -43,7 +43,7 @@ const router = createRouter({ path: '/shop/:id', name: 'shop-detail', component: () => import('../views/ShopDetailView.vue'), - meta: { requiresAuth: true, hideNav: true, isAdmin: false } + meta: { requiresAuth: false, hideNav: true, isAdmin: false } }, { path: '/wishlist', @@ -273,8 +273,6 @@ router.beforeEach((to, _from, next) => { next('/') } else if (to.path === '/' && token) { next('/home') - } else if (to.path === '/home' && !token) { - next('/') } else { // 对于需要认证的页面,验证token的有效性 if (requiresAuth && token) { diff --git a/Frontend/src/views/AuthView.vue b/Frontend/src/views/AuthView.vue index d2adf329..2ae4effa 100644 --- a/Frontend/src/views/AuthView.vue +++ b/Frontend/src/views/AuthView.vue @@ -180,30 +180,39 @@ - 暂无店铺数据 + {{ allowLoginShopless ? '当前无需选择店铺' : '暂无可用店铺' }} {{ shop.shopName }} +
+ {{ loginShopMessage }} +
{{ shop.shopName }} @@ -385,7 +394,12 @@ import { message } from 'ant-design-vue' import type { Rule } from 'ant-design-vue/es/form' import { authApi } from '@/api/auth' import { shopApi } from '@/api/shop' -import { userApi, type AvailabilityCheckResponse, type LoginAccountCheckResponse } from '@/api/user' +import { + userApi, + type AvailabilityCheckResponse, + type LoginAccountCheckResponse, + type LoginShopSelectionResponse +} from '@/api/user' const router = useRouter() @@ -394,10 +408,13 @@ const loginType = ref<'password' | 'phone'>('password') const loading = ref(false) const loadingShops = ref(false) const shops = ref([]) +const loginShops = ref>([]) const countdown = ref(0) const loginAccountStatus = ref(null) const registerAccountStatus = ref(null) const registerPhoneStatus = ref(null) +const loginShopMessage = ref('') +const allowLoginShopless = ref(false) const forgotPasswordVisible = ref(false) const forgotCountdown = ref(0) @@ -414,16 +431,33 @@ const formData = reactive({ password: '', confirmPassword: '', nickname: '', - shopId: undefined as number | undefined, + shopId: undefined as string | undefined, phone: '', verificationCode: '', rememberMe: false }) let loginAccountCheckTimer: number | undefined +let loginPhoneShopCheckTimer: number | undefined const phoneRegex = /^1[3-9]\d{9}$/ const verificationCodeRegex = /^\d{6}$/ +const loginShopPlaceholder = computed(() => { + if (allowLoginShopless.value) { + return '当前暂无启用店铺,可直接登录' + } + if (loadingShops.value) { + return '正在加载可登录店铺' + } + return loginShops.value.length ? '请选择登录店铺' : '请先输入账号或手机号' +}) + +const validateLoginShopRequired = async () => { + if (allowLoginShopless.value || !loginShops.value.length || formData.shopId) { + return Promise.resolve() + } + return Promise.reject('请选择登录店铺') +} const validatePassword = async (_rule: Rule, value: string) => { if (!value || value.length < 6) { @@ -489,6 +523,9 @@ const loginPasswordRules: Record = { ], password: [ { required: true, message: '请输入密码', trigger: 'blur' } + ], + shopId: [ + { validator: validateLoginShopRequired, trigger: 'change' } ] } @@ -500,6 +537,9 @@ const loginPhoneRules: Record = { verificationCode: [ { required: true, message: '请输入验证码', trigger: 'blur' }, { pattern: verificationCodeRegex, message: '验证码必须为 6 位数字', trigger: 'blur' } + ], + shopId: [ + { validator: validateLoginShopRequired, trigger: 'change' } ] } @@ -545,6 +585,140 @@ const resetLoginAccountStatus = () => { loginAccountStatus.value = null } +const resetPhoneLoginShopCheck = () => { + if (loginPhoneShopCheckTimer !== undefined) { + window.clearTimeout(loginPhoneShopCheckTimer) + loginPhoneShopCheckTimer = undefined + } +} + +const resetLoginShopState = (clearSelectedShop = activeTab.value === 'login') => { + resetPhoneLoginShopCheck() + loginShops.value = [] + loginShopMessage.value = '' + allowLoginShopless.value = false + if (clearSelectedShop) { + formData.shopId = undefined + } +} + +const normalizeShopOptionValue = (shopId?: string | number | null) => { + if (shopId === undefined || shopId === null || shopId === '') { + return undefined + } + return String(shopId) +} + +const isLoginShopPrefetchUnsupported = (error: unknown) => { + const status = (error as any)?.response?.status + return status === 404 +} + +const applyLoginShopSelection = (selection?: LoginShopSelectionResponse | null) => { + loginShops.value = selection?.shops || [] + allowLoginShopless.value = Boolean(selection?.allowShoplessLogin) + loginShopMessage.value = selection?.message || '' + + if (allowLoginShopless.value) { + formData.shopId = undefined + return + } + + if (!loginShops.value.length) { + formData.shopId = undefined + return + } + + const currentShopId = normalizeShopOptionValue(formData.shopId) + const matchedShop = loginShops.value.find(shop => normalizeShopOptionValue(shop.id) === currentShopId) + if (matchedShop) { + formData.shopId = normalizeShopOptionValue(matchedShop.id) + return + } + + if (loginShops.value.length === 1) { + const [onlyShop] = loginShops.value + if (onlyShop) { + formData.shopId = normalizeShopOptionValue(onlyShop.id) + return + } + } + + formData.shopId = undefined +} + +const loadLoginShopsByAccount = async (account = formData.account) => { + const trimmedAccount = account.trim() + if (activeTab.value !== 'login' || loginType.value !== 'password' || !trimmedAccount) { + resetLoginShopState() + return null + } + + try { + const selection = await userApi.getLoginShopsByAccount(trimmedAccount) as unknown as LoginShopSelectionResponse + if ( + activeTab.value === 'login' + && loginType.value === 'password' + && formData.account.trim() === trimmedAccount + ) { + applyLoginShopSelection(selection) + } + return selection + } catch (error) { + if (formData.account.trim() === trimmedAccount) { + if (isLoginShopPrefetchUnsupported(error)) { + applyLoginShopSelection({ + allowShoplessLogin: true, + message: '当前环境暂未开放登录前店铺预加载,可直接登录。', + shops: [] + }) + } else { + resetLoginShopState() + } + } + if (!isLoginShopPrefetchUnsupported(error)) { + console.error('登录店铺查询失败:', error) + } + return null + } +} + +const loadLoginShopsByPhone = async (phone = formData.phone) => { + const trimmedPhone = phone.trim() + if (activeTab.value !== 'login' || loginType.value !== 'phone' || !phoneRegex.test(trimmedPhone)) { + resetLoginShopState() + return null + } + + try { + const selection = await userApi.getLoginShopsByPhone(trimmedPhone) as unknown as LoginShopSelectionResponse + if ( + activeTab.value === 'login' + && loginType.value === 'phone' + && formData.phone.trim() === trimmedPhone + ) { + applyLoginShopSelection(selection) + } + return selection + } catch (error) { + if (formData.phone.trim() === trimmedPhone) { + if (isLoginShopPrefetchUnsupported(error)) { + applyLoginShopSelection({ + allowShoplessLogin: true, + message: '当前环境暂未开放登录前店铺预加载,可直接登录。', + shops: [] + }) + } else { + resetLoginShopState() + } + } + if (!isLoginShopPrefetchUnsupported(error)) { + console.error('手机号登录店铺查询失败:', error) + } + return null + } +} + const checkLoginAccountAvailability = async (account = formData.account) => { const trimmedAccount = account.trim() if (activeTab.value !== 'login' || loginType.value !== 'password' || !trimmedAccount) { @@ -818,6 +992,20 @@ const handleAdminLogin = () => { watch([activeTab, loginType], () => { resetLoginAccountStatus() + resetLoginShopState(activeTab.value === 'login') + if (activeTab.value !== 'login') { + return + } + if (loginType.value === 'password' && formData.account.trim()) { + void Promise.all([ + checkLoginAccountAvailability(formData.account.trim()), + loadLoginShopsByAccount(formData.account.trim()) + ]) + return + } + if (loginType.value === 'phone' && phoneRegex.test(formData.phone.trim())) { + void loadLoginShopsByPhone(formData.phone.trim()) + } }) watch( @@ -835,7 +1023,31 @@ watch( loginAccountCheckTimer = window.setTimeout(() => { loginAccountCheckTimer = undefined - void checkLoginAccountAvailability(trimmedAccount) + void Promise.all([ + checkLoginAccountAvailability(trimmedAccount), + loadLoginShopsByAccount(trimmedAccount) + ]) + }, 400) + } +) + +watch( + () => formData.phone, + value => { + if (activeTab.value !== 'login' || loginType.value !== 'phone') { + return + } + + resetPhoneLoginShopCheck() + const trimmedPhone = value.trim() + if (!phoneRegex.test(trimmedPhone)) { + resetLoginShopState() + return + } + + loginPhoneShopCheckTimer = window.setTimeout(() => { + loginPhoneShopCheckTimer = undefined + void loadLoginShopsByPhone(trimmedPhone) }, 400) } ) @@ -846,6 +1058,7 @@ onMounted(() => { onBeforeUnmount(() => { resetLoginAccountStatus() + resetPhoneLoginShopCheck() }) diff --git a/Frontend/src/views/CartView.vue b/Frontend/src/views/CartView.vue index 2c49b412..111521e2 100644 --- a/Frontend/src/views/CartView.vue +++ b/Frontend/src/views/CartView.vue @@ -5,15 +5,36 @@

购物车

- 编辑 + + {{ editing ? '完成' : '批量删除' }} +
- - 去逛逛 + + 去逛作品 - + + + + +
@@ -22,15 +43,19 @@
{{ item.productTitle }}
-
¥{{ item.price.toFixed(2) }}
+
¥{{ Number(item.price || 0).toFixed(2) }}
-
+
美甲师 {{ item.artist?.name || '请选择美甲师' }}
-
+
预约时间 {{ item.appointmentTime ? formatAppointmentDisplay(item.appointmentTime) : (item.artistId ? '请选择预约时间' : '先选择美甲师') }} @@ -46,7 +71,7 @@ {{ item.quantity }} +
- + @@ -56,37 +81,56 @@
- +
- 优惠券 - {{ selectedCoupon ? formatCouponDisplay(selectedCoupon) : '使用优惠券' }} + 优惠方式 + {{ selectedCoupon ? formatCouponDisplay(selectedCoupon) : '不使用优惠' }} +
+
+ {{ selectedCoupon.sourceType === 'SYSTEM_VIP' ? '当前为 VIP 自动折扣,不会消耗用户券。' : '当前为用户券,只有下单成功才会消耗。' }} + -¥{{ discountAmount.toFixed(2) }}
-
优惠金额 -¥{{ discountAmount.toFixed(2) }}
- + +
选中项目{{ selectedCount }} 项
作品数量{{ totalQuantity }} 件
小计¥{{ subtotal.toFixed(2) }}
优惠-¥{{ discountAmount.toFixed(2) }}
-
总计¥{{ totalAmount.toFixed(2) }}
+
合计¥{{ totalAmount.toFixed(2) }}
- - 结算 {{ selectedCount }} 个项目,预计金额 ¥{{ totalAmount.toFixed(2) }} + + 删除已选中的 {{ selectedCount }} 项 + + + 结算 {{ selectedCount }} 项,预计金额 ¥{{ totalAmount.toFixed(2) }}
- + - 不使用优惠券 + 不使用优惠 {{ formatCouponDisplay(coupon) }}
- 系统只会默认预选 VIP 自动券,普通用户券需要你手动选择后才会在下单时使用。 + 系统只会默认预选最佳 VIP 自动券,普通用户券需要你手动选择后才会在下单时使用。
@@ -106,7 +150,7 @@ {{ artist.name }} - +