功能:完善多店铺登录与首次部署SQL

This commit is contained in:
xiaowang
2026-03-26 10:28:28 +08:00
parent 5601428087
commit 764bfadb51
79 changed files with 6524 additions and 2603 deletions
+133 -37
View File
@@ -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<AdminLoginResponse>('/auth/login', data)
},
getLoginShops: (account: string) => {
return adminApi.get<LoginShopSelectionResponse>(`/auth/login-shops/${encodeURIComponent(account)}`)
},
logout: () => {
return adminApi.post<boolean>('/auth/logout')
},
switchShop: (shopId?: string | number) => {
return adminApi.post<AdminLoginResponse>('/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<boolean>(`/shops/update/${id}`, data)
},
updateShopStatus: (id: number, status: number) => {
return adminApi.put<boolean>(`/shops/status/${id}`, { status })
},
deleteShop: (id: number) => {
return adminApi.delete<boolean>(`/shops/delete/${id}`)
}
@@ -321,6 +414,8 @@ export interface UserVO {
id: number
shopId?: number
shopName?: string
shopIds?: Array<number | string>
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
+16 -4
View File
@@ -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<number | string>
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<LoginResponse>('/user/switch-shop', data)
},
getUserInfo: () => {
return api.get<UserInfo>('/user/info')
},
@@ -94,4 +106,4 @@ export const authApi = {
resetPasswordByPhone: (data: ResetPasswordRequest) => {
return api.post('/user/reset-password-by-phone', data)
}
}
}
+6 -6
View File
@@ -127,12 +127,12 @@ export const couponApi = {
},
// 获取用户优惠券列表
listUserCoupons: (status?: number) => {
return request({
listUserCoupons: async (status?: number): Promise<UserCoupon[]> => {
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<UserCoupon[]> => {
return await request({
url: '/coupon/available',
method: 'get',
params: { productTags, productPrice, shopId }
})
}) as UserCoupon[]
}
}
+6
View File
@@ -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')
}
+2 -2
View File
@@ -20,8 +20,8 @@ export const orderApi = {
},
// 获取订单列表
getOrderList: () => {
return api.get('/order/list')
getOrderList: async (): Promise<any[]> => {
return await api.get<any[]>('/order/list') as unknown as any[]
},
// 获取订单详情
+2
View File
@@ -13,6 +13,8 @@ export interface ProductVO {
price: number
estimatedTime: number
approximateDuration?: string
bookableArtists?: string
availableCoupons?: string
category: string
tags?: string
tagList?: string[]
+11 -6
View File
@@ -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<ShopVO[]>('/shop/list/all')
getAllShops: async (): Promise<ShopVO[]> => {
return await api.get<ShopVO[]>('/shop/list/all') as unknown as ShopVO[]
},
getShopsSimple: () => {
return api.get<ShopSimpleVO[]>('/shop/list/simple')
getPublicShops: async (): Promise<ShopVO[]> => {
return await api.get<ShopVO[]>('/shop/list/public') as unknown as ShopVO[]
},
getShopById: (id: number) => {
return api.get<ShopVO>(`/shop/get/${id}`)
getShopsSimple: async (): Promise<ShopSimpleVO[]> => {
return await api.get<ShopSimpleVO[]>('/shop/list/simple') as unknown as ShopSimpleVO[]
},
getShopById: async (id: number): Promise<ShopVO> => {
return await api.get<ShopVO>(`/shop/get/${id}`) as unknown as ShopVO
}
}
+34 -12
View File
@@ -5,6 +5,8 @@ export interface UserVO extends UserInfo {
id: number
shopId?: number
shopName?: string
shopIds?: Array<number | string>
shopNames?: string[]
nickname: string
account: string
avatar: string
@@ -39,6 +41,7 @@ export interface CreateUserRequest {
password: string
type: number
shopId?: number
shopIds?: Array<number | string>
}
export interface UpdateUserRequest {
@@ -47,6 +50,7 @@ export interface UpdateUserRequest {
phone?: string
type?: number
shopId?: number
shopIds?: Array<number | string>
}
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<UserVO>('/user/info')
getUserInfo: async (): Promise<UserVO> => {
return await api.get<UserVO>('/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<UserVO>(`/user/get/account/${account}`)
getUserByAccount: async (account: string): Promise<UserVO> => {
return await api.get<UserVO>(`/user/get/account/${account}`) as unknown as UserVO
},
checkAccountAvailability: (account: string) => {
return api.get<AvailabilityCheckResponse>(`/user/check/account/${encodeURIComponent(account)}`)
checkAccountAvailability: async (account: string): Promise<AvailabilityCheckResponse> => {
return await api.get<AvailabilityCheckResponse>(`/user/check/account/${encodeURIComponent(account)}`) as unknown as AvailabilityCheckResponse
},
checkLoginAccountAvailability: (account: string) => {
return api.get<LoginAccountCheckResponse>(`/user/check/login-account/${encodeURIComponent(account)}`)
checkLoginAccountAvailability: async (account: string): Promise<LoginAccountCheckResponse> => {
return await api.get<LoginAccountCheckResponse>(`/user/check/login-account/${encodeURIComponent(account)}`) as unknown as LoginAccountCheckResponse
},
checkPhoneAvailability: (phone: string) => {
return api.get<AvailabilityCheckResponse>(`/user/check/phone/${encodeURIComponent(phone)}`)
getLoginShopsByAccount: async (account: string): Promise<LoginShopSelectionResponse> => {
return await api.get<LoginShopSelectionResponse>(`/user/check/login-shops/account/${encodeURIComponent(account)}`) as unknown as LoginShopSelectionResponse
},
listUsersByType: (type: number) => {
return api.get<UserVO[]>(`/user/list/type/${type}`)
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: (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')
}
+8 -8
View File
@@ -27,19 +27,19 @@ export interface WishlistItem {
}
export const wishlistApi = {
addToWishlist: (productId: number) => {
return api.post('/wishlist/add', { productId })
addToWishlist: async (productId: number): Promise<boolean> => {
return await api.post<boolean>('/wishlist/add', { productId }) as unknown as boolean
},
removeFromWishlist: (productId: number) => {
return api.post('/wishlist/remove', { productId })
removeFromWishlist: async (productId: number): Promise<boolean> => {
return await api.post<boolean>('/wishlist/remove', { productId }) as unknown as boolean
},
checkWishlist: (productId: number) => {
return api.get<boolean>(`/wishlist/check?productId=${productId}`)
checkWishlist: async (productId: number): Promise<boolean> => {
return await api.get<boolean>(`/wishlist/check?productId=${productId}`) as unknown as boolean
},
getWishlist: () => {
return api.get<WishlistItem[]>('/wishlist/list')
getWishlist: async (): Promise<WishlistItem[]> => {
return await api.get<WishlistItem[]>('/wishlist/list') as unknown as WishlistItem[]
}
}
+1 -1
View File
@@ -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']
+1 -1
View File
@@ -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') {
+1 -1
View File
@@ -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'
+4 -6
View File
@@ -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) {
+223 -10
View File
@@ -180,30 +180,39 @@
<a-form-item
v-if="activeTab === 'login'"
label="选择店铺(可选)"
name="shopId"
label="选择登录店铺"
>
<a-select
v-model:value="formData.shopId"
placeholder="如需绑定店铺或首次手机号登录,请选择店铺"
:placeholder="loginShopPlaceholder"
size="large"
:loading="loadingShops"
:disabled="!allowLoginShopless && !loginShops.length"
allow-clear
>
<a-select-option
v-if="shops.length === 0"
v-if="loginShops.length === 0"
disabled
value=""
>
暂无店铺数据
{{ allowLoginShopless ? '当前无需选择店铺' : '暂无可用店铺' }}
</a-select-option>
<a-select-option
v-for="shop in shops"
v-for="shop in loginShops"
:key="shop.id"
:value="shop.id"
:value="normalizeShopOptionValue(shop.id)"
>
{{ shop.shopName }}
</a-select-option>
</a-select>
<div
v-if="loginShopMessage"
class="field-status"
:class="loginShops.length || allowLoginShopless ? 'success' : 'error'"
>
{{ loginShopMessage }}
</div>
</a-form-item>
<a-form-item
@@ -251,7 +260,7 @@
<a-select-option
v-for="shop in shops"
:key="shop.id"
:value="shop.id"
:value="normalizeShopOptionValue(shop.id)"
>
{{ shop.shopName }}
</a-select-option>
@@ -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<any[]>([])
const loginShops = ref<Array<{ id: number | string; shopName: string }>>([])
const countdown = ref(0)
const loginAccountStatus = ref<LoginAccountCheckResponse | null>(null)
const registerAccountStatus = ref<AvailabilityCheckResponse | null>(null)
const registerPhoneStatus = ref<AvailabilityCheckResponse | null>(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<string, Rule[]> = {
],
password: [
{ required: true, message: '请输入密码', trigger: 'blur' }
],
shopId: [
{ validator: validateLoginShopRequired, trigger: 'change' }
]
}
@@ -500,6 +537,9 @@ const loginPhoneRules: Record<string, Rule[]> = {
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()
})
</script>
+400 -85
View File
@@ -5,15 +5,36 @@
<LeftOutlined :style="{ fontSize: '20px' }" />
</a-button>
<h1>购物车</h1>
<a-button type="text">编辑</a-button>
<a-button type="text" @click="editing = !editing">
{{ editing ? '完成' : '批量删除' }}
</a-button>
</header>
<main class="content">
<a-empty v-if="!cartItems.length" description="购物车是空的">
<a-button type="primary" @click="router.push('/products')">去逛逛</a-button>
<a-empty v-if="!cartItems.length" description="购物车还是空的">
<a-button type="primary" @click="router.push('/products')">去逛作品</a-button>
</a-empty>
<a-card v-for="item in cartItems" :key="item.id" class="item-card">
<a-alert
v-if="selectedCount && checkoutIssues.length && !editing"
class="issue-alert"
type="warning"
show-icon
:message="`还有 ${checkoutIssues.length} 项待完善`"
:description="checkoutIssues.map(issue => issue.message).join(';')"
>
<template #action>
<a-button size="small" @click="focusFirstIssue">定位问题</a-button>
</template>
</a-alert>
<a-card
v-for="item in cartItems"
:key="item.id"
:ref="element => setItemRef(item.id, element)"
class="item-card"
:class="{ 'issue-card': item.selected && hasItemIssue(item) }"
>
<div class="item-row">
<a-checkbox v-model:checked="item.selected" @change="loadAvailableCoupons" />
<div class="thumb" @click="openProduct(item)">
@@ -22,15 +43,19 @@
</div>
<div class="item-main">
<div class="title" @click="openProduct(item)">{{ item.productTitle }}</div>
<div class="price">¥{{ item.price.toFixed(2) }}</div>
<div class="price">¥{{ Number(item.price || 0).toFixed(2) }}</div>
<div class="selector" @click="openBookingModal(item)">
<div class="selector" :class="{ issue: item.selected && !item.artistId }" @click="openBookingModal(item)">
<span class="label">美甲师</span>
<span class="value">{{ item.artist?.name || '请选择美甲师' }}</span>
<RightOutlined />
</div>
<div class="selector" @click="openBookingModal(item)">
<div
class="selector"
:class="{ issue: item.selected && (!item.appointmentTime || isPastAppointment(item.appointmentTime)) }"
@click="openBookingModal(item)"
>
<span class="label">预约时间</span>
<span class="value">
{{ item.appointmentTime ? formatAppointmentDisplay(item.appointmentTime) : (item.artistId ? '请选择预约时间' : '先选择美甲师') }}
@@ -46,7 +71,7 @@
<span>{{ item.quantity }}</span>
<a-button size="small" :disabled="item.quantity >= 99" @click="changeQuantity(item, 1)">+</a-button>
</div>
<a-popconfirm title="确定删除吗?" ok-text="确认" cancel-text="取消" @confirm="removeItem(item)">
<a-popconfirm title="确认删除这件作品吗?" ok-text="确认" cancel-text="取消" @confirm="removeItem(item)">
<a-button type="text" danger size="small">
<DeleteOutlined />
</a-button>
@@ -56,37 +81,56 @@
</div>
</a-card>
<a-card v-if="selectedCount" class="coupon-card" @click="openCouponModal">
<a-card v-if="selectedCount && !editing" class="coupon-card" @click="openCouponModal">
<div class="coupon-row">
<span>优惠券</span>
<span>{{ selectedCoupon ? formatCouponDisplay(selectedCoupon) : '使用优惠券' }}</span>
<span>优惠方式</span>
<span>{{ selectedCoupon ? formatCouponDisplay(selectedCoupon) : '不使用优惠' }}</span>
</div>
<div v-if="selectedCoupon" class="coupon-extra">
<span>{{ selectedCoupon.sourceType === 'SYSTEM_VIP' ? '当前为 VIP 自动折扣,不会消耗用户券。' : '当前为用户券,只有下单成功才会消耗。' }}</span>
<strong>-¥{{ discountAmount.toFixed(2) }}</strong>
</div>
<div v-if="selectedCoupon" class="coupon-discount">优惠金额 -¥{{ discountAmount.toFixed(2) }}</div>
</a-card>
<a-card v-if="cartItems.length" class="summary-card">
<a-card v-if="cartItems.length && !editing" class="summary-card">
<div class="summary-row"><span>选中项目</span><span>{{ selectedCount }} 项</span></div>
<div class="summary-row"><span>作品数量</span><span>{{ totalQuantity }} 件</span></div>
<div class="summary-row"><span>小计</span><span>¥{{ subtotal.toFixed(2) }}</span></div>
<div v-if="selectedCoupon" class="summary-row"><span>优惠</span><span>-¥{{ discountAmount.toFixed(2) }}</span></div>
<div class="summary-row total"><span>总计</span><span>¥{{ totalAmount.toFixed(2) }}</span></div>
<div class="summary-row total"><span>合计</span><span>¥{{ totalAmount.toFixed(2) }}</span></div>
</a-card>
</main>
<footer v-if="cartItems.length" class="footer">
<a-button type="primary" size="large" block @click="checkout">
结算 {{ selectedCount }} 个项目,预计金额 ¥{{ totalAmount.toFixed(2) }}
<a-button
v-if="editing"
danger
size="large"
block
@click="removeSelectedItems"
>
删除已选中的 {{ selectedCount }} 项
</a-button>
<a-button
v-else
type="primary"
size="large"
block
@click="checkout"
>
结算 {{ selectedCount }} 项,预计金额 ¥{{ totalAmount.toFixed(2) }}
</a-button>
</footer>
<a-modal v-model:open="showCouponModal" title="使用优惠券" @ok="applyCouponSelection" @cancel="showCouponModal = false">
<a-modal v-model:open="showCouponModal" title="选择优惠方式" @ok="applyCouponSelection" @cancel="showCouponModal = false">
<a-radio-group v-model:value="couponSelectionKey" class="coupon-options">
<a-radio :value="NO_COUPON_KEY">不使用优惠券</a-radio>
<a-radio :value="NO_COUPON_KEY">不使用优惠</a-radio>
<a-radio v-for="coupon in availableCoupons" :key="getCouponKey(coupon)" :value="getCouponKey(coupon)">
{{ formatCouponDisplay(coupon) }}
</a-radio>
</a-radio-group>
<div class="coupon-tip">
系统只会默认预选 VIP 自动券,普通用户券需要你手动选择后才会在下单时使用。
系统只会默认预选最佳 VIP 自动券,普通用户券需要你手动选择后才会在下单时使用。
</div>
</a-modal>
@@ -106,7 +150,7 @@
<span>{{ artist.name }}</span>
</button>
</div>
<a-empty v-else description="暂无可用美甲师" />
<a-empty v-else description="暂无可预约美甲师" />
</div>
<div class="modal-section">
@@ -173,8 +217,15 @@ interface CartItem {
artist?: ArtistOption
}
interface CheckoutIssue {
key: string
message: string
itemId?: number
}
const cartItems = ref<CartItem[]>([])
const imageIdCache = ref<Record<string, string>>({})
const itemRefs = ref<Record<number, HTMLElement>>({})
const availableCoupons = ref<UserCoupon[]>([])
const selectedCoupon = ref<UserCoupon | null>(null)
const couponSelectionKey = ref(NO_COUPON_KEY)
@@ -186,18 +237,19 @@ const availableArtists = ref<ArtistOption[]>([])
const draftArtistId = ref<number>()
const draftAppointmentTime = ref('')
const currentShopHours = ref('')
const editing = ref(false)
const selectedItems = computed(() => cartItems.value.filter(item => item.selected))
const selectedCount = computed(() => selectedItems.value.length)
const totalQuantity = computed(() => selectedItems.value.reduce((sum, item) => sum + item.quantity, 0))
const subtotal = computed(() => selectedItems.value.reduce((sum, item) => sum + item.price * item.quantity, 0))
const subtotal = computed(() => selectedItems.value.reduce((sum, item) => sum + Number(item.price || 0) * item.quantity, 0))
const discountAmount = computed(() => calculateCouponDiscount(selectedCoupon.value, subtotal.value))
const totalAmount = computed(() => Math.max(0, subtotal.value - discountAmount.value))
const bookingTitle = computed(() => currentItem.value ? '为 ' + currentItem.value.productTitle + ' 选择预约信息' : '选择预约信息')
const bookingTitle = computed(() => currentItem.value ? `为 ${currentItem.value.productTitle} 选择预约信息` : '选择预约信息')
const bookingHelperText = computed(() => {
const texts: string[] = []
if (currentShopHours.value) texts.push('门店营业时间:' + currentShopHours.value)
if (currentItem.value?.approximateDuration) texts.push('预计时长:' + currentItem.value.approximateDuration)
if (currentShopHours.value) texts.push(`门店营业时间:${currentShopHours.value}`)
if (currentItem.value?.approximateDuration) texts.push(`预计时长:${currentItem.value.approximateDuration}`)
return texts.join(' · ') || '请选择至少晚于当前 5 分钟的预约时间'
})
@@ -216,16 +268,33 @@ const getDayBoundary = (date: Date) => {
const getCouponKey = (coupon: UserCoupon) => `${coupon.sourceType || 'USER_COUPON'}:${coupon.id}`
const setItemRef = (itemId: number, element: unknown) => {
if (element && (element as any).$el) {
itemRefs.value[itemId] = (element as any).$el as HTMLElement
return
}
if (element instanceof HTMLElement) {
itemRefs.value[itemId] = element
return
}
delete itemRefs.value[itemId]
}
const formatCouponDisplay = (coupon: UserCoupon) => {
const badge = coupon.sourceType === 'SYSTEM_VIP' ? '[VIP 自动券]' : '[用户券]'
const benefit = coupon.couponType === 1
? `${coupon.discountValue} 折`
: `满 ${coupon.minAmount} 减 ${coupon.reduceAmount}`
return `${badge} ${coupon.couponName} ${benefit}`
}
const calculateCouponDiscount = (coupon: UserCoupon | null, amount: number) => {
if (!coupon || amount <= 0) {
return 0
}
if (coupon.couponType === 1) {
const discountValue = Number(coupon.discountValue || 0)
if (!discountValue) {
return 0
}
return amount - amount * discountValue / 10
return discountValue ? amount - amount * discountValue / 10 : 0
}
if (coupon.couponType === 2) {
return Number(coupon.reduceAmount || 0)
@@ -233,27 +302,63 @@ const calculateCouponDiscount = (coupon: UserCoupon | null, amount: number) => {
return 0
}
const formatCouponDisplay = (coupon: UserCoupon) => {
const badge = coupon.sourceType === 'SYSTEM_VIP' ? '[VIP 自动券]' : '[用户券]'
const benefit = coupon.couponType === 1
? `${coupon.discountValue}折`
: `满${coupon.minAmount}减${coupon.reduceAmount}`
return `${badge} ${coupon.couponName} ${benefit}`
}
const findBestSystemVipCoupon = (coupons: UserCoupon[]) => {
return coupons
.filter(coupon => coupon.sourceType === 'SYSTEM_VIP')
.sort((left, right) => calculateCouponDiscount(right, subtotal.value) - calculateCouponDiscount(left, subtotal.value))[0] || null
}
const openProduct = (item: CartItem) => {
router.push('/product/' + item.productId)
const formatAppointmentDisplay = (value?: string) => value ? value.replace('T', ' ').slice(0, 16) : '未选择预约时间'
const isPastAppointment = (value?: string) => !!value && new Date(value.replace(' ', 'T')).getTime() < getMinAppointmentDate().getTime()
const hasItemIssue = (item: CartItem) => !item.artistId || !item.appointmentTime || isPastAppointment(item.appointmentTime)
const checkoutIssues = computed<CheckoutIssue[]>(() => {
const items = selectedItems.value
const issues: CheckoutIssue[] = []
const firstMissingArtist = items.find(item => !item.artistId)
if (firstMissingArtist) {
issues.push({ key: 'artist', message: `请先为“${firstMissingArtist.productTitle}”选择美甲师`, itemId: firstMissingArtist.id })
}
const firstMissingTime = items.find(item => !item.appointmentTime)
if (firstMissingTime) {
issues.push({ key: 'time', message: `请先为“${firstMissingTime.productTitle}”选择预约时间`, itemId: firstMissingTime.id })
}
const firstExpiredTime = items.find(item => isPastAppointment(item.appointmentTime))
if (firstExpiredTime) {
issues.push({ key: 'expired', message: `“${firstExpiredTime.productTitle}”的预约时间已过期,请重新选择`, itemId: firstExpiredTime.id })
}
if (new Set(items.map(item => item.shopId).filter(Boolean)).size > 1) {
issues.push({ key: 'shop', message: '跨店铺项目请分开结算', itemId: items[0]?.id })
}
if (new Set(items.map(item => item.artistId).filter(Boolean)).size > 1) {
issues.push({ key: 'artist-mix', message: '不同美甲师的项目请分开结算', itemId: items[0]?.id })
}
return issues
})
const scrollToIssue = (issue?: CheckoutIssue) => {
if (!issue?.itemId) {
return
}
const target = itemRefs.value[issue.itemId]
if (target) {
target.scrollIntoView({ behavior: 'smooth', block: 'center' })
}
}
const focusFirstIssue = () => {
scrollToIssue(checkoutIssues.value[0])
}
const loadCartItems = async () => {
const response = await cartApi.getCartList() as unknown as any[]
cartItems.value = response.map(item => ({
cartItems.value = (response || []).map(item => ({
...item,
selected: true,
originalProductImage: item.productImage,
@@ -263,6 +368,7 @@ const loadCartItems = async () => {
couponSelectionTouched.value = false
couponSelectionKey.value = NO_COUPON_KEY
selectedCoupon.value = null
editing.value = false
await Promise.all([loadProductImages(), loadAvailableCoupons()])
}
@@ -284,6 +390,10 @@ const loadProductImages = async () => {
}
const loadAvailableCoupons = async () => {
if (editing.value) {
return
}
const currentSelectedKey = selectedCoupon.value ? getCouponKey(selectedCoupon.value) : couponSelectionKey.value
const selectedShopId = selectedItems.value[0]?.shopId
@@ -330,7 +440,7 @@ const loadAvailableCoupons = async () => {
couponSelectionKey.value = NO_COUPON_KEY
}
} catch (error) {
console.error('获取可用优惠券失败:', error)
console.error('获取可用优惠失败:', error)
availableCoupons.value = []
selectedCoupon.value = null
couponSelectionKey.value = NO_COUPON_KEY
@@ -361,6 +471,26 @@ const removeItem = async (item: CartItem) => {
}
}
const removeSelectedItems = async () => {
if (!selectedItems.value.length) {
message.warning('请先勾选要删除的作品')
return
}
try {
await Promise.all(selectedItems.value.map(item => cartApi.removeFromCart(item.productId)))
await Promise.all([loadCartItems(), updateCartCount()])
message.success('已删除选中的作品')
} catch (error) {
console.error('批量删除失败:', error)
message.error('批量删除失败,请稍后重试')
}
}
const openProduct = (item: CartItem) => {
router.push('/product/' + item.productId)
}
const openBookingModal = async (item: CartItem) => {
currentItem.value = item
draftArtistId.value = item.artistId
@@ -374,7 +504,13 @@ const loadArtists = async (item: CartItem) => {
const allowedIds = new Set((item.bookableArtists || '').split(',').map(id => Number(id.trim())).filter(id => Number.isFinite(id) && id > 0))
availableArtists.value = await Promise.all(
users
.filter(user => (!item.shopId || user.shopId === item.shopId) && (!allowedIds.size || allowedIds.has(user.id)))
.filter(user => user.status === 1)
.filter(user => {
const matchedShop = !item.shopId
|| user.shopId === item.shopId
|| (Array.isArray((user as any).shopIds) && (user as any).shopIds.some((shopId: string | number) => String(shopId) === String(item.shopId)))
return matchedShop && (!allowedIds.size || allowedIds.has(user.id))
})
.map(async user => {
try {
const detail = await api.get('/nail-artist/get/' + user.id) as any
@@ -397,14 +533,11 @@ const loadShopHours = async (shopId?: number) => {
}
}
const formatAppointmentDisplay = (value?: string) => value ? value.replace('T', ' ').slice(0, 16) : '未选择预约时间'
const isPastAppointment = (value?: string) => !!value && new Date(value.replace(' ', 'T')).getTime() < getMinAppointmentDate().getTime()
const disablePastAppointmentDate = (current: any) => {
if (!current) {
return false
}
if (!current) return false
return current.valueOf() < getDayBoundary(new Date())
}
const disablePastAppointmentTime = (current: any) => {
if (!current || typeof current.format !== 'function') {
return {}
@@ -466,12 +599,16 @@ const applyCouponSelection = () => {
const checkout = async () => {
const items = selectedItems.value
if (!items.length) return message.warning('请先选择要结算的作品')
if (items.some(item => !item.artistId)) return message.warning('请先为所有项目选择美甲师')
if (items.some(item => !item.appointmentTime)) return message.warning('请先为所有项目选择预约时间')
if (items.some(item => isPastAppointment(item.appointmentTime))) return message.warning('存在已过期的预约时间,请重新选择')
if (new Set(items.map(item => item.shopId).filter(Boolean)).size > 1) return message.warning('跨店铺商品请分开结算')
if (new Set(items.map(item => item.artistId).filter(Boolean)).size > 1) return message.warning('不同美甲师的项目请分开结算')
if (!items.length) {
return message.warning('请先选择要结算的作品')
}
const firstIssue = checkoutIssues.value[0]
if (firstIssue) {
message.warning(firstIssue.message)
scrollToIssue(firstIssue)
return
}
try {
await orderApi.createOrder({
@@ -510,41 +647,219 @@ onMounted(async () => {
</script>
<style scoped>
.page { min-height: 100vh; padding-top: 60px; background: #f5f5f5; }
.header, .footer { position: fixed; left: 0; right: 0; background: #fff; z-index: 10; }
.header { top: 0; display: flex; align-items: center; justify-content: space-between; padding: 10px 15px; border-bottom: 1px solid #f0f0f0; }
.header h1 { margin: 0; font-size: 18px; }
.content { padding: 15px; padding-bottom: 140px; }
.item-card, .coupon-card, .summary-card { margin-bottom: 12px; border-radius: 12px; }
.item-row { display: flex; gap: 12px; align-items: flex-start; }
.thumb { width: 80px; height: 80px; border-radius: 8px; overflow: hidden; background: #eef3ff; display: flex; align-items: center; justify-content: center; cursor: pointer; }
.thumb img { width: 100%; height: 100%; object-fit: cover; }
.item-main { flex: 1; }
.title { font-weight: 600; cursor: pointer; }
.price { margin: 4px 0 10px; color: #ff4d4f; font-weight: 700; }
.selector { display: flex; align-items: center; gap: 8px; padding: 10px 12px; margin-bottom: 10px; border-radius: 8px; background: #f8f9ff; cursor: pointer; }
.selector .label { min-width: 56px; color: #666; font-size: 13px; }
.selector .value { flex: 1; color: #1890ff; font-size: 13px; }
.actions, .qty, .coupon-row, .summary-row { display: flex; align-items: center; justify-content: space-between; }
.qty { gap: 8px; }
.duration, .coupon-discount, .helper, .coupon-tip { color: #666; font-size: 12px; }
.coupon-tip { margin-top: 12px; line-height: 1.6; }
.summary-row.total { font-weight: 700; }
.footer { bottom: 60px; padding: 15px; border-top: 1px solid #f0f0f0; box-shadow: 0 -2px 8px rgba(0,0,0,.06); }
.coupon-options { display: flex; flex-direction: column; gap: 8px; }
.modal-section + .modal-section { margin-top: 16px; }
.section-title { margin-bottom: 8px; font-weight: 600; }
.artist-list { display: flex; flex-wrap: wrap; gap: 8px; }
.artist-option { display: inline-flex; align-items: center; gap: 8px; padding: 8px 12px; border: 1px solid #d9d9d9; border-radius: 999px; background: #fff; cursor: pointer; }
.artist-option.active { border-color: #1890ff; color: #1890ff; background: #f0f9ff; }
.artist-option img { width: 24px; height: 24px; border-radius: 50%; object-fit: cover; }
.time-picker { border-radius: 8px; }
.page {
min-height: 100vh;
padding-top: 60px;
background: #f5f5f5;
}
@media (min-width: 992px) {
.header,
.footer {
position: fixed;
left: 0;
right: 0;
background: #fff;
z-index: 10;
}
.header {
top: 0;
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 15px;
border-bottom: 1px solid #f0f0f0;
}
.header h1 {
margin: 0;
font-size: 18px;
font-weight: 700;
}
.content {
max-width: 980px;
margin: 0 auto;
padding: 16px 16px 140px;
}
.issue-alert {
margin-bottom: 16px;
border-radius: 16px;
}
.item-card,
.coupon-card,
.summary-card {
margin-bottom: 12px;
border-radius: 16px;
}
.issue-card {
border-color: #faad14;
box-shadow: 0 8px 24px rgba(250, 173, 20, 0.12);
}
.item-row {
display: flex;
gap: 12px;
align-items: flex-start;
}
.thumb {
width: 84px;
height: 84px;
border-radius: 12px;
overflow: hidden;
background: #eef3ff;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
.thumb img {
width: 100%;
height: 100%;
object-fit: cover;
}
.item-main {
flex: 1;
}
.title {
font-size: 15px;
font-weight: 700;
cursor: pointer;
}
.price {
margin: 6px 0 10px;
color: #ff4d4f;
font-weight: 700;
}
.selector {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 12px;
margin-bottom: 10px;
border: 1px solid transparent;
border-radius: 10px;
background: #f8f9ff;
cursor: pointer;
}
.selector.issue {
border-color: #faad14;
background: #fff7e6;
}
.selector .label {
min-width: 56px;
color: #666;
font-size: 13px;
}
.selector .value {
flex: 1;
color: #1677ff;
font-size: 13px;
}
.duration,
.coupon-tip,
.helper {
color: #666;
font-size: 12px;
}
.actions,
.qty,
.coupon-row,
.summary-row,
.coupon-extra {
display: flex;
align-items: center;
justify-content: space-between;
}
.qty {
gap: 8px;
}
.coupon-extra {
margin-top: 10px;
color: #666;
gap: 12px;
}
.summary-row {
margin-bottom: 10px;
}
.summary-row.total {
margin-bottom: 0;
font-weight: 700;
}
.footer {
bottom: 60px;
padding: 15px;
border-top: 1px solid #f0f0f0;
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
}
.coupon-options {
display: flex;
flex-direction: column;
gap: 8px;
}
.modal-section + .modal-section {
margin-top: 16px;
}
.section-title {
margin-bottom: 8px;
font-weight: 700;
}
.artist-list {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.artist-option {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
border: 1px solid #d9d9d9;
border-radius: 999px;
background: #fff;
cursor: pointer;
}
.artist-option.active {
border-color: #1677ff;
color: #1677ff;
background: #f0f9ff;
}
.artist-option img {
width: 24px;
height: 24px;
border-radius: 50%;
object-fit: cover;
}
@media (max-width: 767px) {
.content {
max-width: 980px;
margin: 0 auto;
padding: 24px 24px 140px;
padding: 15px 15px 140px;
}
}
</style>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+200 -292
View File
@@ -1,7 +1,5 @@
<template>
<div class="mobile-container">
<!-- 头部区域 -->
<header class="header">
<a-button class="back-btn" type="text" @click="handleBackClick">
<LeftOutlined :style="{ fontSize: '20px' }" />
@@ -12,8 +10,8 @@
v-model:value="searchKeyword"
placeholder="搜索作品"
class="search-input"
@search="handleSearch"
enter-button
@search="handleSearch"
/>
</div>
<a-button class="search-btn" type="text" @click="toggleSearch">
@@ -21,12 +19,10 @@
</a-button>
</header>
<!-- 主内容区域 -->
<div class="main-content">
<!-- 左侧分类边栏 -->
<div class="category-sidebar">
<div
v-for="category in categories"
<div
v-for="category in categories"
:key="category"
class="category-item"
:class="{ active: selectedCategory === category }"
@@ -36,9 +32,15 @@
</div>
</div>
<!-- 右侧作品区域 -->
<div class="product-section">
<!-- 作品网格 -->
<a-alert
v-if="activeBannerText"
class="page-banner"
type="info"
show-icon
:message="activeBannerText"
/>
<div class="product-grid">
<a-card
v-for="item in products"
@@ -48,85 +50,53 @@
hoverable
@click="handleProductClick(item)"
>
<!-- 作品图片 -->
<div class="product-img">
<img
v-if="getProductImages(item) && getProductImages(item).length > 0"
:src="getProductImages(item)[0]"
<img
v-if="getProductImages(item).length > 0"
:src="getProductImages(item)[0]"
:alt="item.title || item.name"
class="product-image"
/>
<div v-else class="product-img-placeholder">
<span>{{ (item.title || item.name) ? (item.title || item.name)[0] : '商' }}</span>
<span>{{ (item.title || item.name)?.[0] || '作' }}</span>
</div>
<a-badge
v-if="item.category"
:text="item.category"
color="#ff4d4f"
class="product-tag"
/>
</div>
<!-- 作品信息 -->
<div class="product-info">
<p class="name">{{ item.title || item.name }}</p>
<div class="product-meta">
<span class="duration">{{ item.approximateDuration || '0分钟' }}</span>
<span class="duration">{{ item.approximateDuration || '时长待定' }}</span>
<div class="stats">
<span class="like-count">{{ item.likeCount || 0 }} 赞</span>
<span class="collect-count">{{ item.collectCount || 0 }} 收藏</span>
<span>{{ item.likeCount || 0 }} 点赞</span>
<span>{{ item.collectCount || 0 }} 收藏</span>
</div>
</div>
<!-- 标签展示 -->
<div class="product-tags">
<template v-if="item.tagInfos && item.tagInfos.length > 0">
<a-tag
<template v-if="item.tagInfos?.length">
<a-tag
v-for="tag in item.tagInfos"
:key="tag.id"
size="small"
:style="{
marginRight: '4px',
marginRight: '4px',
marginBottom: '4px',
fontSize: '9px',
padding: '1px 6px',
color: tag.textColor || '#333333',
backgroundColor: tag.bgColor || '#F0F0F0',
borderColor: tag.borderColor || '#F0F0F0',
borderWidth: '1px',
borderStyle: 'solid',
borderRadius: '8px'
color: tag.textColor || '#333',
backgroundColor: tag.bgColor || '#f0f0f0',
borderColor: tag.borderColor || '#f0f0f0'
}"
>
{{ tag.tagName }}
</a-tag>
</template>
<template v-else-if="item.category">
<a-tag
size="small"
:style="{
marginRight: '4px',
marginBottom: '4px',
fontSize: '9px',
padding: '1px 6px',
color: '#333333',
backgroundColor: '#F0F0F0',
borderColor: '#F0F0F0',
borderWidth: '1px',
borderStyle: 'solid',
borderRadius: '8px'
}"
>
{{ item.category }}
</a-tag>
</template>
<a-tag v-else size="small" color="gray" style="font-size: 10px; padding: 2px 6px">
无标签
</a-tag>
<a-tag v-else size="small" color="default">暂无标签</a-tag>
</div>
<div class="price-row">
<p class="price">¥{{ item.price }}</p>
<a-button
type="primary"
size="small"
<p class="price">¥{{ Number(item.price || 0).toFixed(2) }}</p>
<a-button
type="primary"
size="small"
shape="circle"
@click.stop="handleAddToCart(item)"
>
@@ -137,17 +107,14 @@
</a-card>
</div>
<!-- 空状态 -->
<div v-if="products.length === 0 && !loading" class="empty-state">
<a-typography-text type="secondary">商家暂未上架更多作品</a-typography-text>
<a-empty description="暂时没有匹配的作品">
<a-button type="primary" @click="resetFilters">查看全部作品</a-button>
</a-empty>
</div>
<!-- 加载更多 -->
<div v-else-if="products.length > 0" class="load-more">
<a-button v-if="hasMore" type="link" @click="handleLoadMore">
加载更多 <DownOutlined />
</a-button>
<a-typography-text v-else type="secondary">没有更多作品了</a-typography-text>
<div v-if="loading" class="loading-state">
<a-spin />
</div>
</div>
</div>
@@ -155,198 +122,192 @@
</template>
<script setup lang="ts">
import { ref, onMounted, inject } from 'vue'
import { useRouter } from 'vue-router'
import {
LeftOutlined,
SearchOutlined,
ShoppingCartOutlined,
DownOutlined
} from '@ant-design/icons-vue'
import { onMounted, ref, watch, inject, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { LeftOutlined, SearchOutlined, ShoppingCartOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { productApi, type ProductVO } from '@/api/product'
import { tagApi, type TagVO } from '@/api/tag'
import { cartApi } from '@/api/cart'
import { fileApi } from '@/api/file'
const router = useRouter()
const route = useRoute()
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
const router = useRouter()
// 标签列表
const allTags = ref<TagVO[]>([])
// 当前选中的分类
const selectedCategory = ref('全部')
// 分类列表(动态从标签获取)
const categories = ref<string[]>(['全部'])
// 作品数据
const selectedCategory = ref('全部')
const products = ref<ProductVO[]>([])
// 是否还有更多数据
const hasMore = ref(true)
// 加载状态
const loading = ref(false)
// 搜索相关状态
const showSearch = ref(false)
const searchKeyword = ref('')
const isSearching = ref(false)
// 图片ID缓存
const imageIdCache = ref<Record<string, string>>({})
const imageUrls = ref<Record<number, string[]>>({})
const DEFAULT_PRODUCT_IMAGE = 'data:image/svg+xml;base64,PHN2ZyB3aW0dPSJodHRwOi8vd3d3Lm9yZy8yMDAwL3N2ZyI+Pjwvc3ZnPg=='
// 从后端获取标签列表
const isLoggedIn = computed(() => Boolean(localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')))
const activeBannerText = computed(() => {
if (searchKeyword.value.trim()) {
return `当前显示“${searchKeyword.value.trim()}”的搜索结果`
}
if (selectedCategory.value !== '全部') {
return `当前按标签“${selectedCategory.value}”筛选`
}
return ''
})
const DEFAULT_PRODUCT_IMAGE = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCBmaWxsPSIjZjVmNWY1IiB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIvPjx0ZXh0IHg9IjUwJSIgeT0iNTAlIiBmaWxsPSIjYmZiZmJmIiBmb250LXNpemU9IjI0IiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBkeT0iLjNlbSI+YWFhPC90ZXh0Pjwvc3ZnPg=='
const ensureLoginForAction = (actionText: string) => {
if (isLoggedIn.value) {
return true
}
message.info(`${actionText}前请先登录账号`)
router.push('/')
return false
}
const loadImageUrls = async (productList: ProductVO[]) => {
for (const product of productList) {
if (!product.imageFileIds) {
imageUrls.value[product.id] = [DEFAULT_PRODUCT_IMAGE]
continue
}
const ids = product.imageFileIds.split(',').map(id => id.trim()).filter(Boolean)
const urls: string[] = []
for (const id of ids) {
try {
if (!imageIdCache.value[id]) {
imageIdCache.value[id] = await fileApi.getSignedUrl(Number(id)) as unknown as string
}
if (imageIdCache.value[id]) {
urls.push(imageIdCache.value[id])
}
} catch (error) {
console.error('获取作品图片失败:', error)
}
}
imageUrls.value[product.id] = urls.length ? urls : [DEFAULT_PRODUCT_IMAGE]
}
}
const getProductImages = (product: ProductVO): string[] => imageUrls.value[product.id] || [DEFAULT_PRODUCT_IMAGE]
const fetchTags = async () => {
try {
const response = await tagApi.getAllTags() as any
allTags.value = response || []
const response = await tagApi.getAllTags() as unknown as TagVO[]
allTags.value = Array.isArray(response) ? response : []
categories.value = ['全部', ...allTags.value.map(tag => tag.tagName)]
} catch (error) {
console.error('获取标签失败:', error)
categories.value = ['全部']
}
}
// 加载作品列表
const loadImageUrls = async (productList: ProductVO[]) => {
for (const product of productList) {
if (product.imageFileIds) {
const ids = product.imageFileIds.split(',')
const urls: string[] = []
for (const id of ids) {
if (id) {
try {
if (!imageIdCache.value[id]) {
const response = await fileApi.getSignedUrl(Number(id)) as any
imageIdCache.value[id] = response
}
if (imageIdCache.value[id]) {
urls.push(imageIdCache.value[id] as string)
}
} catch (error) {
console.error('获取签名链接失败:', error)
urls.push(DEFAULT_PRODUCT_IMAGE)
}
}
}
imageUrls.value[product.id] = urls
} else {
imageUrls.value[product.id] = [DEFAULT_PRODUCT_IMAGE]
}
}
}
const getProductImages = (product: ProductVO): string[] => {
return imageUrls.value[product.id] || [DEFAULT_PRODUCT_IMAGE]
}
// 从后端获取作品数据
const fetchProducts = async () => {
if (loading.value) return
loading.value = true
try {
let response: any
if (selectedCategory.value === '全部') {
response = await productApi.getAllProducts() as any
let response: ProductVO[] = []
const keyword = searchKeyword.value.trim()
if (keyword) {
response = await productApi.searchProducts(keyword)
} else if (selectedCategory.value === '全部') {
response = await productApi.getAllProducts()
} else {
response = await productApi.getProductsByTag(selectedCategory.value) as any
response = await productApi.getProductsByTag(selectedCategory.value)
}
products.value = response || []
products.value = Array.isArray(response) ? response : []
await loadImageUrls(products.value)
hasMore.value = false
} catch (error) {
message.error('未登录,请先登录')
console.error('获取作品列表失败:', error)
message.error('加载作品列表失败,请稍后重试')
products.value = []
} finally {
loading.value = false
}
}
const syncRouteFilters = async () => {
const keyword = typeof route.query.keyword === 'string' ? route.query.keyword.trim() : ''
const tag = typeof route.query.tag === 'string' ? route.query.tag.trim() : ''
searchKeyword.value = keyword
showSearch.value = Boolean(keyword)
selectedCategory.value = tag && categories.value.includes(tag) ? tag : '全部'
await fetchProducts()
}
// 处理返回按钮点击
const handleBackClick = () => {
router.push('/')
router.push('/home')
}
// 处理分类点击
const handleCategoryClick = (category: string) => {
selectedCategory.value = category
showSearch.value = false
searchKeyword.value = ''
isSearching.value = false
fetchProducts()
showSearch.value = false
router.replace({
path: '/products',
query: category === '全部' ? {} : { tag: category }
})
}
// 处理作品卡片点击
const handleProductClick = (item: any) => {
const handleProductClick = (item: ProductVO) => {
router.push(`/product/${item.id}`)
}
// 处理添加到购物车
const handleAddToCart = async (item: any) => {
const handleAddToCart = async (item: ProductVO) => {
if (!ensureLoginForAction('加入购物车')) {
return
}
try {
await cartApi.addToCart({ productId: item.id, quantity: 1 })
await updateCartCount()
message.success(`已将 ${item.title || item.name || '作品'} 添加到购物车`)
message.success(`已将 ${item.title || item.name || '作品'} 加入购物车`)
} catch (error) {
message.error('添加到购物车失败,请重试')
console.error('加入购物车失败:', error)
message.error('加入购物车失败,请稍后重试')
}
}
// 处理加载更多
const handleLoadMore = () => {
// 这里可以添加加载更多逻辑
hasMore.value = false
const handleSearch = () => {
const keyword = searchKeyword.value.trim()
router.replace({
path: '/products',
query: keyword ? { keyword } : {}
})
}
// 切换搜索框显示/隐藏
const toggleSearch = () => {
showSearch.value = !showSearch.value
if (!showSearch.value) {
searchKeyword.value = ''
isSearching.value = false
fetchProducts() // 重置为默认作品列表
router.replace({ path: '/products', query: selectedCategory.value === '全部' ? {} : { tag: selectedCategory.value } })
}
}
// 处理搜索操作
const handleSearch = async () => {
if (!searchKeyword.value.trim()) {
message.info('请输入搜索关键词')
return
}
loading.value = true
try {
const response = await productApi.searchProducts(searchKeyword.value.trim()) as any
products.value = response || []
await loadImageUrls(products.value)
hasMore.value = false
isSearching.value = true
} catch (error) {
message.error('搜索失败,请重试')
} finally {
loading.value = false
}
const resetFilters = () => {
selectedCategory.value = '全部'
searchKeyword.value = ''
showSearch.value = false
router.replace('/products')
}
// 页面挂载时获取标签和作品数据
watch(
() => route.query,
async () => {
await syncRouteFilters()
},
{ deep: true }
)
onMounted(async () => {
await fetchTags()
fetchProducts()
await syncRouteFilters()
})
</script>
@@ -373,9 +334,9 @@ onMounted(async () => {
}
.header h1 {
font-size: 18px;
font-weight: bold;
margin: 0;
font-size: 18px;
font-weight: 700;
}
.back-btn,
@@ -392,23 +353,16 @@ onMounted(async () => {
margin: 0 10px;
}
.search-input {
width: 100%;
}
/* 主内容区域 */
.main-content {
display: flex;
height: calc(100vh - 60px);
overflow: hidden;
min-height: calc(100vh - 60px);
}
/* 左侧分类边栏 */
.category-sidebar {
width: 90px;
background: #f8f8f8;
width: 92px;
background: #fafafa;
border-right: 1px solid #ececec;
overflow-y: auto;
border-right: 1px solid #e8e8e8;
}
.category-item {
@@ -417,60 +371,44 @@ onMounted(async () => {
color: #666;
text-align: center;
cursor: pointer;
transition: all 0.3s;
transition: all 0.2s ease;
border-left: 3px solid transparent;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.category-item:hover {
background: #e8e8e8;
color: #1890ff;
}
.category-item.active {
color: #1677ff;
background: white;
color: #1890ff;
border-left-color: #1890ff;
font-weight: 600;
border-left-color: #1677ff;
font-weight: 700;
}
/* 右侧作品区域 */
.product-section {
flex: 1;
padding: 16px;
overflow-y: auto;
background: #f5f5f5;
}
.page-banner {
margin-bottom: 16px;
border-radius: 14px;
}
.product-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
padding: 0 20px;
gap: 15px;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
}
.product-card {
cursor: pointer;
transition: transform 0.3s, box-shadow 0.3s;
}
.product-card:hover {
transform: translateY(-4px);
}
.product-card :deep(.ant-card-body) {
padding: 12px;
border-radius: 18px;
}
.product-img {
width: 100%;
aspect-ratio: 1;
border-radius: 12px;
position: relative;
overflow: hidden;
margin-bottom: 10px;
background: #f8f8f8;
border-radius: 14px;
background: #eef3ff;
}
.product-image {
@@ -483,48 +421,37 @@ onMounted(async () => {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
justify-content: center;
font-size: 40px;
font-weight: bold;
color: rgba(0,0,0,0.1);
}
.product-tag {
position: absolute;
top: 8px;
left: 8px;
font-size: 11px;
padding: 2px 8px;
border-radius: 8px;
}
.product-info {
padding: 0;
font-weight: 700;
color: rgba(0, 0, 0, 0.18);
}
.name {
margin: 12px 0 6px;
font-size: 14px;
font-weight: 500;
margin: 0 0 4px 0;
font-weight: 700;
color: #1f1f1f;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.product-meta {
font-size: 12px;
color: #999;
margin-bottom: 6px;
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
font-size: 12px;
color: #8b8b9a;
}
.duration {
background: #f0f0f0;
display: inline-flex;
align-items: center;
padding: 2px 8px;
border-radius: 10px;
border-radius: 999px;
background: #f4f6fb;
}
.stats {
@@ -532,10 +459,9 @@ onMounted(async () => {
gap: 8px;
}
.like-count,
.collect-count {
display: flex;
align-items: center;
.product-tags {
margin: 10px 0;
min-height: 26px;
}
.price-row {
@@ -545,51 +471,33 @@ onMounted(async () => {
}
.price {
color: #ff4d4f;
font-weight: bold;
margin: 0;
font-size: 16px;
font-size: 18px;
font-weight: 700;
color: #ff4d4f;
}
.product-tags {
margin: 8px 0;
display: flex;
flex-wrap: wrap;
}
.load-more {
padding: 20px;
text-align: center;
}
.empty-state {
padding: 60px 20px;
text-align: center;
color: #999;
font-size: 14px;
.empty-state,
.loading-state {
padding: 56px 0;
}
@media (min-width: 992px) {
.main-content {
min-height: calc(100vh - 60px);
height: auto;
max-width: var(--frontend-content-max-width);
margin: 0 auto;
width: 100%;
}
.category-sidebar {
width: 128px;
border-radius: 20px 0 0 20px;
}
.product-section {
padding: 24px;
}
.product-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
padding: 0;
}
}
@media (min-width: 1280px) {
.product-grid {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
File diff suppressed because it is too large Load Diff
+166 -137
View File
@@ -10,7 +10,7 @@
>
<div class="logo">
<h1 v-if="!collapsed">后台管理</h1>
<h1 v-else>管</h1>
<h1 v-else>后台</h1>
</div>
<a-menu
:selectedKeys="selectedKeys"
@@ -29,21 +29,36 @@
</a-menu-item>
</a-menu>
</a-layout-sider>
<a-layout>
<a-layout-header class="header">
<div class="header-shell">
<div class="header-left">
<MenuUnfoldOutlined
v-if="collapsed"
class="trigger"
@click="toggleCollapsed"
/>
<MenuFoldOutlined
v-else
class="trigger"
@click="toggleCollapsed"
/>
<MenuUnfoldOutlined v-if="collapsed" class="trigger" @click="toggleCollapsed" />
<MenuFoldOutlined v-else class="trigger" @click="toggleCollapsed" />
<div v-if="isBootstrapAdmin" class="shop-hint">
<span>当前暂无可用门店,请先前往店铺管理创建</span>
<a-button type="link" @click="router.push('/admin/shops')">去创建</a-button>
</div>
<div v-else-if="shopOptions.length > 1" class="shop-switcher">
<span class="shop-switcher-label">当前门店</span>
<a-select
v-model:value="selectedShopId"
class="shop-select"
:options="shopSelectOptions"
:loading="shopSwitchLoading"
@change="handleShopChange"
/>
</div>
<div v-else class="shop-pill">
<ShopOutlined />
<span>{{ currentShopName }}</span>
</div>
</div>
<div class="header-right">
<a-dropdown>
<a class="user-dropdown" @click.prevent>
@@ -53,11 +68,11 @@
</a>
<template #overlay>
<a-menu>
<a-menu-item key="profile" @click="goToProfile">
<a-menu-item key="home" @click="router.push('/admin')">
<template #icon>
<UserOutlined />
</template>
个人中心
工作台
</a-menu-item>
<a-menu-divider />
<a-menu-item key="logout" @click="handleLogout">
@@ -72,6 +87,7 @@
</div>
</div>
</a-layout-header>
<a-layout-content class="content">
<div class="content-shell">
<router-view />
@@ -83,26 +99,25 @@
</template>
<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
DashboardOutlined,
DownOutlined,
GiftOutlined,
HomeOutlined,
LogoutOutlined,
MenuFoldOutlined,
MenuUnfoldOutlined,
DashboardOutlined,
UserOutlined,
ShopOutlined,
HomeOutlined,
SafetyCertificateOutlined,
DownOutlined,
LogoutOutlined,
GiftOutlined,
TagOutlined,
ShopOutlined,
ShoppingOutlined,
TeamOutlined
TagOutlined,
TeamOutlined,
UserOutlined
} from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { userApi, type UserVO } from '@/api/admin'
import { authApi } from '@/api/auth'
import { adminAuthApi, type UserVO } from '@/api/admin'
import { DEFAULT_AVATAR } from '@/constants'
import { usePermission } from '@/utils/permission'
@@ -111,86 +126,52 @@ const route = useRoute()
const collapsed = ref(false)
const userInfo = ref<UserVO | null>(null)
const selectedKeys = ref<string[]>([route.path])
const selectedShopId = ref<string>()
const shopSwitchLoading = ref(false)
const { loadUserPermissions, hasPermission, clearPermissions, userPermissions } = usePermission()
const menuItems = [
{
key: '/admin',
icon: HomeOutlined,
label: '首页',
permissionCode: ''
},
{
key: '/admin/dashboard',
icon: DashboardOutlined,
label: '仪表盘',
permissionCode: 'dashboard:view'
},
{
key: '/admin/users',
icon: UserOutlined,
label: '用户管理',
permissionCode: 'user:view'
},
{
key: '/admin/products',
icon: ShopOutlined,
label: '作品管理',
permissionCode: 'product:view'
},
{
key: '/admin/coupons',
icon: GiftOutlined,
label: '优惠券管理',
permissionCode: 'coupon:view'
},
{
key: '/admin/shops',
icon: HomeOutlined,
label: '店铺管理',
permissionCode: 'shop:view'
},
{
key: '/admin/permissions',
icon: SafetyCertificateOutlined,
label: '权限管理',
permissionCode: 'permission:view'
},
{
key: '/admin/tags',
icon: TagOutlined,
label: '标签管理',
permissionCode: 'tag:view'
},
{
key: '/admin/orders',
icon: ShoppingOutlined,
label: '订单管理',
permissionCode: 'order:view'
},
{
key: '/admin/nail-artists',
icon: TeamOutlined,
label: '美甲师管理',
permissionCode: 'nail_artist:view'
}
{ key: '/admin', icon: HomeOutlined, label: '首页', permissionCode: '' },
{ key: '/admin/dashboard', icon: DashboardOutlined, label: '仪表盘', permissionCode: 'dashboard:view' },
{ key: '/admin/users', icon: UserOutlined, label: '用户管理', permissionCode: 'user:view' },
{ key: '/admin/products', icon: ShopOutlined, label: '作品管理', permissionCode: 'product:view' },
{ key: '/admin/coupons', icon: GiftOutlined, label: '优惠券管理', permissionCode: 'coupon:view' },
{ key: '/admin/shops', icon: HomeOutlined, label: '店铺管理', permissionCode: 'shop:view' },
{ key: '/admin/permissions', icon: SafetyCertificateOutlined, label: '权限管理', permissionCode: 'permission:view' },
{ key: '/admin/tags', icon: TagOutlined, label: '标签管理', permissionCode: 'tag:view' },
{ key: '/admin/orders', icon: ShoppingOutlined, label: '订单管理', permissionCode: 'order:view' },
{ key: '/admin/nail-artists', icon: TeamOutlined, label: '美甲师管理', permissionCode: 'nail_artist:view' }
]
const selectedKeys = ref<string[]>([route.path])
const isBootstrapAdmin = computed(() => userInfo.value?.type === 4 && !userInfo.value?.shopId)
const shopOptions = computed(() => {
const ids = userInfo.value?.shopIds || []
const names = userInfo.value?.shopNames || []
return ids.map((id, index) => ({
id: String(id),
name: names[index] || `门店 ${id}`
}))
})
const shopSelectOptions = computed(() => shopOptions.value.map(shop => ({ label: shop.name, value: shop.id })))
const currentShopName = computed(() => userInfo.value?.shopName || '未选择门店')
const filteredMenuItems = computed(() => {
// 访问 userPermissions 以建立依赖关系
userPermissions.value
// 所有用户类型都根据实际权限过滤菜单
return menuItems.filter(item => {
// 空权限码的菜单项(如首页)总是可见
if (!item.permissionCode) {
return true
}
return hasPermission(item.permissionCode)
})
let visibleItems = menuItems.filter(item => !item.permissionCode || hasPermission(item.permissionCode))
if (isBootstrapAdmin.value) {
visibleItems = visibleItems.filter(item => item.key === '/admin' || item.key === '/admin/shops')
}
return visibleItems
})
const persistAdminSession = (payload: any) => {
localStorage.setItem('adminAccessToken', payload.accessToken)
localStorage.setItem('adminRefreshToken', payload.refreshToken)
localStorage.setItem('adminUserInfo', JSON.stringify(payload.userInfo))
sessionStorage.setItem('adminAccessToken', payload.accessToken)
}
const toggleCollapsed = () => {
collapsed.value = !collapsed.value
}
@@ -199,20 +180,17 @@ const handleMenuClick = (info: any) => {
router.push(info.key)
}
const goToProfile = () => {
router.push('/profile')
}
const handleLogout = () => {
Modal.confirm({
title: '确认退出',
content: '确定要退出登录吗?',
title: '确认退出登录',
content: '退出后需要重新登录后台。',
okText: '确认',
cancelText: '取消',
onOk: async () => {
try {
// 尝试调用登出API
await authApi.logout()
await adminAuthApi.logout()
} catch (error) {
console.error('登出失败:', error)
console.error('退出失败:', error)
} finally {
localStorage.removeItem('adminAccessToken')
localStorage.removeItem('adminRefreshToken')
@@ -232,21 +210,51 @@ const handleLogout = () => {
const fetchUserInfo = async () => {
try {
const adminUserInfoStr = localStorage.getItem('adminUserInfo')
if (adminUserInfoStr) {
userInfo.value = JSON.parse(adminUserInfoStr)
} else {
const res = await userApi.getUserInfo()
userInfo.value = res as unknown as UserVO
const cache = localStorage.getItem('adminUserInfo')
if (cache) {
userInfo.value = JSON.parse(cache)
}
if (!userInfo.value) {
return
}
selectedShopId.value = userInfo.value.shopId ? String(userInfo.value.shopId) : undefined
} catch (error) {
console.error('获取用户信息失败:', error)
console.error('获取后台用户信息失败:', error)
}
}
watch(() => route.path, (newPath) => {
selectedKeys.value = [newPath]
}, { immediate: true })
const handleShopChange = async (shopId: unknown) => {
if (typeof shopId !== 'string' && typeof shopId !== 'number') {
return
}
const normalizedShopId = String(shopId)
if (!normalizedShopId || normalizedShopId === String(userInfo.value?.shopId || '')) {
return
}
shopSwitchLoading.value = true
try {
const response = await adminAuthApi.switchShop(normalizedShopId)
persistAdminSession(response as any)
await fetchUserInfo()
await loadUserPermissions()
message.success('门店上下文已切换')
window.location.reload()
} catch (error: any) {
console.error('切换门店失败:', error)
selectedShopId.value = userInfo.value?.shopId ? String(userInfo.value.shopId) : undefined
message.error(error?.message || '切换门店失败')
} finally {
shopSwitchLoading.value = false
}
}
watch(
() => route.path,
newPath => {
selectedKeys.value = [newPath]
},
{ immediate: true }
)
onMounted(async () => {
await fetchUserInfo()
@@ -275,51 +283,76 @@ onMounted(async () => {
display: flex;
align-items: center;
justify-content: center;
background: rgba(255, 255, 255, 0.1);
background: rgba(255, 255, 255, 0.08);
}
.logo h1 {
margin: 0;
color: white;
font-size: 18px;
margin: 0;
font-weight: 600;
}
:deep(.ant-menu) {
border-right: none;
font-weight: 700;
}
.header {
background: white;
padding: 0 24px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
position: sticky;
top: 0;
z-index: 100;
padding: 0 24px;
background: white;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}
.header-shell {
width: 100%;
max-width: var(--admin-content-max-width);
margin: 0 auto;
min-height: 64px;
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px;
}
.header-left {
display: flex;
align-items: center;
gap: 16px;
min-width: 0;
}
.trigger {
font-size: 18px;
cursor: pointer;
transition: color 0.3s;
}
.trigger:hover {
color: #1890ff;
.shop-hint,
.shop-switcher,
.shop-pill {
display: inline-flex;
align-items: center;
gap: 10px;
min-height: 40px;
padding: 0 14px;
border-radius: 999px;
background: #f5f7fb;
color: #334155;
}
.shop-hint {
flex-wrap: wrap;
}
.shop-switcher-label {
font-size: 13px;
color: #64748b;
}
.shop-select {
min-width: 220px;
}
.shop-pill {
font-weight: 600;
}
.header-right {
@@ -331,29 +364,25 @@ onMounted(async () => {
display: flex;
align-items: center;
gap: 12px;
cursor: pointer;
padding: 8px 12px;
border-radius: 8px;
transition: background 0.3s;
border-radius: 10px;
transition: background 0.2s ease;
}
.user-dropdown:hover {
background: #f5f5f5;
background: #f8fafc;
}
.username {
font-size: 14px;
color: #333;
color: #1f2937;
}
.content {
margin-left: 240px;
min-height: calc(100vh - 64px);
padding: 24px;
background: #f0f2f5;
min-height: calc(100vh - 64px);
transition: margin-left 0.2s;
position: relative;
z-index: 1;
}
.content-shell {
+112 -36
View File
@@ -15,11 +15,10 @@
@finish="handleLogin"
>
<a-alert
v-if="!shopLoading && !hasAvailableShops"
type="warning"
v-if="loginShopMessage"
:type="allowShoplessLogin || hasAvailableShops ? 'info' : 'warning'"
show-icon
message="当前暂无可选店铺"
description="如果你使用的是平台管理员账号,可以直接登录后台先创建第一家店铺;其他后台账号仍需先绑定店铺。"
:message="loginShopMessage"
style="margin-bottom: 16px"
/>
@@ -46,10 +45,10 @@
<a-select
v-model:value="formState.shopId"
size="large"
:placeholder="hasAvailableShops ? '请选择登录店铺' : '当前暂无可选店铺'"
:placeholder="shopPlaceholder"
:loading="shopLoading"
:options="shopOptions"
:disabled="shopLoading || !hasAvailableShops"
:disabled="shopLoading || (!hasAvailableShops && !allowShoplessLogin)"
show-search
:filter-option="filterShopOption"
/>
@@ -77,20 +76,21 @@
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
import { adminAuthApi } from '@/api/admin'
import { shopApi, type ShopSimpleVO } from '@/api/shop'
import { adminAuthApi, type LoginShopSelectionResponse } from '@/api/admin'
import { usePermission } from '@/utils/permission'
const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)
const shopLoading = ref(false)
const shops = ref<ShopSimpleVO[]>([])
const shops = ref<Array<{ id: number | string; shopName: string }>>([])
const allowShoplessLogin = ref(false)
const loginShopMessage = ref('')
const { loadUserPermissions } = usePermission()
const formState = reactive({
@@ -98,9 +98,10 @@ const formState = reactive({
password: '',
shopId: undefined as string | undefined
})
let loginShopTimer: number | undefined
const getShopIdValue = (shop: ShopSimpleVO) => String(shop.id ?? '')
const getShopLabel = (shop: ShopSimpleVO) => String(shop.shopName || shop.name || `店铺 ${shop.id}`)
const getShopIdValue = (shop: { id: number | string; shopName: string }) => String(shop.id ?? '')
const getShopLabel = (shop: { id: number | string; shopName: string }) => String(shop.shopName || `店铺 ${shop.id}`)
const shopOptions = computed(() =>
shops.value.map(shop => ({
@@ -109,6 +110,19 @@ const shopOptions = computed(() =>
}))
)
const hasAvailableShops = computed(() => shopOptions.value.length > 0)
const shouldRequireShop = computed(() => hasAvailableShops.value && !allowShoplessLogin.value)
const shopPlaceholder = computed(() => {
if (allowShoplessLogin.value) {
return '当前无需选择店铺'
}
if (shopLoading.value) {
return '正在加载可登录店铺'
}
if (hasAvailableShops.value) {
return '请选择登录店铺'
}
return '请先输入账号'
})
const formRules = {
account: [
@@ -118,7 +132,7 @@ const formRules = {
password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
shopId: [{
validator: async () => {
if (!hasAvailableShops.value || formState.shopId) {
if (!shouldRequireShop.value || formState.shopId) {
return Promise.resolve()
}
return Promise.reject(new Error('请选择登录店铺'))
@@ -130,6 +144,18 @@ const formRules = {
const filterShopOption = (input: string, option: { label?: string | number } | undefined) =>
String(option?.label ?? '').toLowerCase().includes(input.toLowerCase())
const isLoginShopPrefetchUnsupported = (error: unknown) => {
const status = (error as any)?.response?.status
return status === 404
}
const resetLoginShopTimer = () => {
if (loginShopTimer !== undefined) {
window.clearTimeout(loginShopTimer)
loginShopTimer = undefined
}
}
const restoreLoginShop = () => {
const cached = localStorage.getItem('adminUserInfo')
if (!cached) {
@@ -145,32 +171,63 @@ const restoreLoginShop = () => {
}
}
const loadShops = async () => {
const applyLoginShopSelection = (selection?: LoginShopSelectionResponse | null) => {
shops.value = selection?.shops || []
allowShoplessLogin.value = Boolean(selection?.allowShoplessLogin)
loginShopMessage.value = selection?.message || ''
if (allowShoplessLogin.value) {
formState.shopId = undefined
return
}
if (!shops.value.length) {
formState.shopId = undefined
return
}
const matchedShop = shops.value.find(shop => getShopIdValue(shop) === formState.shopId)
if (matchedShop) {
return
}
if (shops.value.length === 1) {
formState.shopId = getShopIdValue(shops.value[0]!)
return
}
formState.shopId = undefined
}
const loadLoginShops = async (account = formState.account) => {
const trimmedAccount = account.trim()
if (!trimmedAccount) {
applyLoginShopSelection(null)
return
}
shopLoading.value = true
try {
shops.value = await shopApi.getShopsSimple() as unknown as ShopSimpleVO[]
if (!shops.value.length) {
formState.shopId = undefined
return
const selection = await adminAuthApi.getLoginShops(trimmedAccount) as unknown as LoginShopSelectionResponse
if (formState.account.trim() === trimmedAccount) {
applyLoginShopSelection(selection)
}
const hasMatchedShop = shopOptions.value.some(option => option.value === formState.shopId)
if (hasMatchedShop) {
return
}
if (shops.value.length === 1) {
const [onlyShop] = shops.value
if (onlyShop) {
formState.shopId = getShopIdValue(onlyShop)
}
return
}
formState.shopId = undefined
} catch (error) {
console.error('获取登录店铺列表失败:', error)
message.error('店铺列表加载失败,请刷新后重试')
if (formState.account.trim() === trimmedAccount) {
if (isLoginShopPrefetchUnsupported(error)) {
applyLoginShopSelection({
allowShoplessLogin: true,
message: '当前环境暂未开放登录前店铺预加载,可直接登录。',
shops: []
})
} else {
applyLoginShopSelection(null)
loginShopMessage.value = '登录店铺加载失败,请稍后重试'
}
}
if (!isLoginShopPrefetchUnsupported(error)) {
console.error('获取登录店铺列表失败:', error)
}
} finally {
shopLoading.value = false
}
@@ -214,7 +271,26 @@ const handleLogin = async () => {
onMounted(() => {
restoreLoginShop()
loadShops()
})
watch(
() => formState.account,
value => {
resetLoginShopTimer()
const trimmedAccount = value.trim()
if (!trimmedAccount) {
applyLoginShopSelection(null)
return
}
loginShopTimer = window.setTimeout(() => {
loginShopTimer = undefined
void loadLoginShops(trimmedAccount)
}, 400)
}
)
onBeforeUnmount(() => {
resetLoginShopTimer()
})
const goToFrontend = () => {
+182 -102
View File
@@ -1,58 +1,44 @@
<template>
<div class="dashboard">
<a-page-header title="仪表盘" sub-title="欢迎使用后台管理系统" />
<a-row :gutter="16" class="stat-cards">
<a-col :span="6">
<a-page-header
title="仪表盘"
:sub-title="pageSubtitle"
/>
<a-row :gutter="[16, 16]" class="stat-cards">
<a-col :xs="24" :sm="12" :xl="6">
<a-card>
<a-statistic
title="总用户数"
:value="stats.totalUsers"
:value-style="{ color: '#3f8600' }"
:loading="loading"
>
<a-statistic title="用户数" :value="stats.totalUsers" :loading="loading">
<template #prefix>
<UserOutlined />
</template>
</a-statistic>
</a-card>
</a-col>
<a-col :span="6">
<a-col :xs="24" :sm="12" :xl="6">
<a-card>
<a-statistic
title="作品总数"
:value="stats.totalProducts"
:value-style="{ color: '#1890ff' }"
:loading="loading"
>
<a-statistic title="作品数" :value="stats.totalProducts" :loading="loading">
<template #prefix>
<ShopOutlined />
</template>
</a-statistic>
</a-card>
</a-col>
<a-col :span="6" v-if="isAdmin">
<a-col v-if="isAdmin" :xs="24" :sm="12" :xl="6">
<a-card>
<a-statistic
title="店铺数量"
:value="stats.totalShops"
:value-style="{ color: '#722ed1' }"
:loading="loading"
>
<a-statistic title="门店数" :value="stats.totalShops" :loading="loading">
<template #prefix>
<HomeOutlined />
</template>
</a-statistic>
</a-card>
</a-col>
<a-col :span="6">
<a-col :xs="24" :sm="12" :xl="6">
<a-card>
<a-statistic
title="今日订单"
:value="stats.todayOrders"
:value-style="{ color: '#cf1322' }"
:loading="loading"
>
<a-statistic title="今日订单" :value="stats.todayOrders" :loading="loading">
<template #prefix>
<ShoppingOutlined />
</template>
@@ -61,47 +47,50 @@
</a-col>
</a-row>
<a-row :gutter="16" class="charts-section">
<a-col :span="16">
<a-card title="订单趋势" :bordered="false" class="chart-card">
<div class="chart-placeholder">
<BarChartOutlined :style="{ fontSize: '64px', color: '#d9d9d9' }" />
<p>订单趋势图表</p>
</div>
<a-row :gutter="[16, 16]">
<a-col :xs="24" :xl="14">
<a-card title="经营提醒" class="insight-card">
<a-spin :spinning="loading">
<div class="insight-list">
<div v-for="item in insightItems" :key="item.title" class="insight-item">
<div class="insight-title">{{ item.title }}</div>
<div class="insight-description">{{ item.description }}</div>
</div>
</div>
</a-spin>
</a-card>
</a-col>
<a-col :span="8">
<a-card title="热门作品" :bordered="false" class="chart-card">
<a-col :xs="24" :xl="10">
<a-card title="热门作品" class="side-card">
<a-spin :spinning="loading">
<a-list :data-source="stats.hotProducts" size="small">
<template #renderItem="{ item }">
<a-list-item>
<a-list-item-meta>
<template #title>
<a href="#">{{ item.title }}</a>
</template>
<template #description>
点赞: {{ item.likeCount }} | 收藏: {{ item.collectCount || 0 }}
</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
<a-empty v-if="!stats.hotProducts.length" description="暂时还没有热门作品数据" />
<div v-else class="hot-list">
<div v-for="item in stats.hotProducts" :key="item.id" class="hot-item">
<div>
<div class="hot-name">{{ item.title }}</div>
<div class="hot-meta">点赞 {{ item.likeCount || 0 }} · 收藏 {{ item.collectCount || 0 }}</div>
</div>
<div class="hot-price">¥{{ Number(item.price || 0).toFixed(2) }}</div>
</div>
</div>
</a-spin>
</a-card>
</a-col>
</a-row>
<a-card title="最近活动" :bordered="false" class="activity-card">
<a-card title="最近动态" class="activity-card">
<a-spin :spinning="loading">
<a-timeline>
<a-timeline-item
v-for="activity in stats.recentActivities"
<a-empty v-if="!stats.recentActivities.length" description="暂时没有最近动态" />
<a-timeline v-else>
<a-timeline-item
v-for="activity in stats.recentActivities"
:key="activity.id"
:color="activity.color"
:color="activity.color || 'blue'"
>
<p>{{ activity.description }}</p>
<p style="font-size: 12px; color: #999;">{{ formatTime(activity.time) }}</p>
<p class="activity-title">{{ activity.title || '系统动态' }}</p>
<p class="activity-description">{{ activity.description }}</p>
<p class="activity-time">{{ formatTime(activity.time) }}</p>
</a-timeline-item>
</a-timeline>
</a-spin>
@@ -110,15 +99,9 @@
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import {
UserOutlined,
ShopOutlined,
HomeOutlined,
ShoppingOutlined,
BarChartOutlined
} from '@ant-design/icons-vue'
import { HomeOutlined, ShopOutlined, ShoppingOutlined, UserOutlined } from '@ant-design/icons-vue'
import { adminDashboardApi, type DashboardStats } from '@/api/admin'
const loading = ref(false)
@@ -131,24 +114,62 @@ const stats = reactive<DashboardStats>({
recentActivities: []
})
// 获取当前用户信息
const getCurrentUserInfo = () => {
try {
const userInfoStr = localStorage.getItem('adminUserInfo')
if (userInfoStr) {
const userInfo = JSON.parse(userInfoStr)
return userInfo
}
const cache = localStorage.getItem('adminUserInfo')
return cache ? JSON.parse(cache) : null
} catch (error) {
console.error('获取当前用户信息失败', error)
console.error('读取后台用户信息失败:', error)
return null
}
return null
}
// 判断是否为管理员
const isAdmin = computed(() => {
const userInfo = getCurrentUserInfo()
return userInfo?.type === 4
const currentUser = computed(() => getCurrentUserInfo())
const isAdmin = computed(() => currentUser.value?.type === 4)
const pageSubtitle = computed(() => {
if (isAdmin.value) {
return stats.totalShops > 0 ? '查看整体经营情况与各门店动态' : '当前还没有门店,先去店铺管理创建第一家门店'
}
return currentUser.value?.shopName ? `当前门店:${currentUser.value.shopName}` : '当前还没有选中门店'
})
const insightItems = computed(() => {
const items = []
if (isAdmin.value && stats.totalShops === 0) {
items.push({
title: '先创建门店',
description: '系统目前还没有门店,建议先在店铺管理里创建第一家门店,再继续配置作品、优惠券和员工。'
})
}
if (stats.totalProducts === 0) {
items.push({
title: '还没有可售作品',
description: '可以先补充几款基础作品,首页和前台作品页会更完整,也更方便测试完整下单流程。'
})
} else {
items.push({
title: '作品库已准备好',
description: `当前共有 ${stats.totalProducts} 个作品,建议继续关注热门作品的收藏和点赞表现。`
})
}
if (stats.todayOrders === 0) {
items.push({
title: '今日订单较安静',
description: '可以检查首页推荐、优惠券配置或门店营业时间是否完整,减少用户下单前的犹豫。'
})
} else {
items.push({
title: '今日已有订单流入',
description: `今天已产生 ${stats.todayOrders} 笔订单,建议优先关注订单状态推进和美甲师排期。`
})
}
if (stats.totalUsers > 0) {
items.push({
title: '用户池正在积累',
description: `当前共有 ${stats.totalUsers} 个用户,可继续结合收藏、优惠券和 VIP 规则提升复购。`
})
}
return items
})
const formatTime = (timeStr: string) => {
@@ -156,22 +177,21 @@ const formatTime = (timeStr: string) => {
const time = new Date(timeStr)
const now = new Date()
const diff = now.getTime() - time.getTime()
const minutes = Math.floor(diff / 60000)
const hours = Math.floor(diff / 3600000)
const days = Math.floor(diff / 86400000)
if (minutes < 1) return '刚刚'
if (minutes < 60) return `${minutes}分钟前`
if (hours < 24) return `${hours}小时前`
if (days < 7) return `${days}天前`
if (minutes < 60) return `${minutes} 分钟前`
if (hours < 24) return `${hours} 小时前`
if (days < 7) return `${days} 天前`
return time.toLocaleDateString('zh-CN')
}
const fetchStats = async () => {
loading.value = true
try {
loading.value = true
const data = await adminDashboardApi.getStats()
Object.assign(stats, data)
} catch (error) {
@@ -183,7 +203,7 @@ const fetchStats = async () => {
}
onMounted(() => {
fetchStats()
void fetchStats()
})
</script>
@@ -196,29 +216,89 @@ onMounted(() => {
margin-bottom: 24px;
}
.charts-section {
margin-bottom: 24px;
.insight-card,
.side-card,
.activity-card {
border-radius: 18px;
}
.chart-card {
height: 400px;
.insight-list {
display: grid;
gap: 14px;
}
.chart-placeholder {
.insight-item {
padding: 16px 18px;
border-radius: 14px;
background: linear-gradient(135deg, #f8fbff 0%, #f5f7ff 100%);
border: 1px solid #edf2ff;
}
.insight-title {
font-size: 15px;
font-weight: 700;
color: #1f2937;
}
.insight-description {
margin-top: 6px;
line-height: 1.7;
color: #64748b;
}
.hot-list {
display: grid;
gap: 12px;
}
.hot-item {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 300px;
color: #999;
justify-content: space-between;
gap: 12px;
padding: 14px 0;
border-bottom: 1px solid #f0f0f0;
}
.chart-placeholder p {
margin-top: 16px;
font-size: 14px;
.hot-item:last-child {
border-bottom: none;
padding-bottom: 0;
}
.hot-name {
font-weight: 700;
color: #1f2937;
}
.hot-meta,
.activity-description,
.activity-time {
color: #64748b;
}
.hot-meta,
.activity-time {
font-size: 12px;
}
.hot-price {
white-space: nowrap;
font-weight: 700;
color: #ff4d4f;
}
.activity-card {
margin-top: 24px;
}
.activity-title {
margin: 0 0 4px;
font-weight: 700;
color: #1f2937;
}
.activity-description,
.activity-time {
margin: 0;
line-height: 1.7;
}
</style>
+26
View File
@@ -64,6 +64,15 @@
<span v-if="getShopBannerImages(record).length === 0" class="no-banner">暂无Banner</span>
</div>
</template>
<template v-else-if="column.key === 'status'">
<a-switch
:checked="record.status !== 0"
:disabled="!hasPermission('shop:edit') || !isAdmin"
checked-children="启用"
un-checked-children="停用"
@change="(checked: any) => handleStatusChange(record, checked === true)"
/>
</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button v-if="hasPermission('shop:view')" type="link" size="small" @click="showViewModal(record)">
@@ -298,6 +307,7 @@ const viewFormState = reactive({
description: '',
address: '',
businessHours: '',
status: 1,
coverImageFileId: '',
imageFileIds: ''
})
@@ -316,6 +326,7 @@ const formState = reactive({
description: '',
address: '',
businessHours: '',
status: 1,
coverImageFileId: '',
imageFileIds: ''
})
@@ -345,6 +356,7 @@ const columns = [
{ title: '店铺描述', dataIndex: 'description', key: 'description' },
{ title: '店铺地址', dataIndex: 'address', key: 'address' },
{ title: '营业时间', dataIndex: 'businessHours', key: 'businessHours' },
{ title: '状态', key: 'status', width: 120 },
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
]
@@ -600,6 +612,7 @@ const showAddModal = () => {
description: '',
address: '',
businessHours: '',
status: 1,
coverImageFileId: '',
imageFileIds: ''
})
@@ -619,6 +632,7 @@ const showEditModal = async (record: Shop | Record<string, any>) => {
description: 'description' in record ? record.description : (record as any).description,
address: 'address' in record ? record.address : (record as any).address,
businessHours: 'businessHours' in record ? record.businessHours : (record as any).businessHours,
status: 'status' in record ? (record.status ?? 1) : ((record as any).status ?? 1),
coverImageFileId: 'coverImageFileId' in record ? record.coverImageFileId : (record as any).coverImageFileId,
imageFileIds: 'imageFileIds' in record ? record.imageFileIds : (record as any).imageFileIds
})
@@ -707,6 +721,7 @@ const showViewModal = async (record: Shop | Record<string, any>) => {
description: 'description' in record ? record.description : (record as any).description,
address: 'address' in record ? record.address : (record as any).address,
businessHours: 'businessHours' in record ? record.businessHours : (record as any).businessHours,
status: 'status' in record ? (record.status ?? 1) : ((record as any).status ?? 1),
coverImageFileId: 'coverImageFileId' in record ? record.coverImageFileId : (record as any).coverImageFileId,
imageFileIds: 'imageFileIds' in record ? record.imageFileIds : (record as any).imageFileIds
})
@@ -812,6 +827,17 @@ const handleDelete = async (record: Shop | Record<string, any>) => {
}
}
const handleStatusChange = async (record: Shop | Record<string, any>, enabled: boolean) => {
try {
const shopId = 'id' in record ? record.id : (record as any).id
await adminShopApi.updateShopStatus(shopId, enabled ? 1 : 0)
;(record as any).status = enabled ? 1 : 0
message.success(`店铺已${enabled ? '启用' : '停用'}`)
} catch (error) {
message.error('店铺状态更新失败')
}
}
onMounted(async () => {
await loadUserPermissions()
fetchShopList()
+68 -31
View File
@@ -34,7 +34,7 @@
</template>
<template v-else-if="column.key === 'shopName'">
{{ record.shopName || getShopNameById(record.shopId) || '-' }}
{{ getShopDisplay(record) || '-' }}
</template>
<template v-else-if="column.key === 'type'">
@@ -83,7 +83,7 @@
</a-button>
<a-popconfirm
v-if="hasPermission('user:delete') && record.type !== 4"
title="确定要删除这个用户吗?"
title="确定要将这个用户从当前店铺移除吗?"
@confirm="handleDelete(record)"
>
<a-button type="link" size="small" danger>
@@ -128,10 +128,11 @@
<a-form-item v-if="!isEdit" label="密码" name="password">
<a-input-password v-model:value="formState.password" placeholder="请输入密码" />
</a-form-item>
<a-form-item label="所属店铺" name="shopId">
<a-form-item label="所属店铺" name="shopIds">
<a-select
v-model:value="formState.shopId"
placeholder="请选择店铺"
v-model:value="formState.shopIds"
mode="multiple"
:placeholder="currentUserInfo?.type === 4 ? '请选择一个或多个店铺' : '请选择店铺'"
:loading="shopLoading"
:disabled="currentUserInfo?.type !== 4 && !!currentUserInfo?.shopId"
>
@@ -169,7 +170,7 @@
<a-descriptions-item label="账号">{{ viewRecord?.account || '-' }}</a-descriptions-item>
<a-descriptions-item label="昵称">{{ viewRecord?.nickname || '-' }}</a-descriptions-item>
<a-descriptions-item label="手机号">{{ viewRecord?.phone || '-' }}</a-descriptions-item>
<a-descriptions-item label="所属店铺">{{ viewRecord?.shopName || '-' }}</a-descriptions-item>
<a-descriptions-item label="所属店铺">{{ getShopDisplay(viewRecord) || '-' }}</a-descriptions-item>
<a-descriptions-item label="用户类型">{{ getUserTypeText(viewRecord?.type || 0) }}</a-descriptions-item>
<a-descriptions-item label="VIP 等级">{{ viewRecord?.level || '普通' }}</a-descriptions-item>
<a-descriptions-item label="状态">{{ viewRecord?.status === 1 ? '正常' : '禁用' }}</a-descriptions-item>
@@ -188,7 +189,7 @@
<div v-if="assetTargetUser" class="asset-modal">
<a-alert
:message="`${assetTargetUser.nickname}(${assetTargetUser.account})`"
:description="assetTargetUser.shopName ? `所属店铺:${assetTargetUser.shopName}` : '未绑定店铺'"
:description="getShopDisplay(assetTargetUser) ? `所属店铺:${getShopDisplay(assetTargetUser)}` : '未绑定店铺'"
type="info"
show-icon
style="margin-bottom: 16px"
@@ -423,7 +424,7 @@ const formState = reactive({
phone: '',
password: '',
type: 0,
shopId: undefined as string | undefined
shopIds: [] as string[]
})
const balanceForm = reactive<AdminUserBalanceChangeRequest>({
@@ -459,7 +460,15 @@ const formRules = {
}
],
password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
shopId: [{ required: true, message: '请选择店铺', trigger: 'change' }],
shopIds: [{
validator: async (_rule: unknown, value: string[]) => {
if (Array.isArray(value) && value.length > 0) {
return Promise.resolve()
}
return Promise.reject('请选择至少一个店铺')
},
trigger: 'change'
}],
type: [{ required: true, message: '请选择用户类型', trigger: 'change' }]
} as any
@@ -561,12 +570,41 @@ const getShopNameById = (shopId?: string | number | null) => {
return matchedShop?.shopName || ''
}
const resolveEditableShopId = (shopId?: string | number | null) => {
const targetShopId = normalizeShopId(shopId)
if (targetShopId && shopList.value.some(shop => getShopOptionValue(shop) === targetShopId)) {
return targetShopId
const getShopDisplay = (user?: Partial<UserVO> | Record<string, any> | null) => {
if (!user) {
return ''
}
return shopList.value.length === 1 ? getShopOptionValue(shopList.value[0]!) : undefined
const names = (user.shopNames || []).filter(Boolean)
if (names.length) {
return names.join('、')
}
if (user.shopName) {
return user.shopName
}
if (user.shopIds?.length) {
return (user.shopIds as Array<string | number>)
.map((id: string | number) => getShopNameById(id) || `店铺 ${id}`)
.join('、')
}
return getShopNameById(user.shopId) || ''
}
const resolveEditableShopIds = (user?: UserVO | null) => {
const sourceIds = user?.shopIds?.length
? user.shopIds
: (user?.shopId ? [user.shopId] : [])
const normalizedIds = sourceIds
.map(id => normalizeShopId(id))
.filter((id): id is string => Boolean(id))
.filter(id => shopList.value.some(shop => getShopOptionValue(shop) === id))
if (normalizedIds.length) {
return normalizedIds
}
return currentUserInfo?.type !== 4 && currentUserInfo?.shopId
? [normalizeShopId(currentUserInfo.shopId)!]
: []
}
const fetchShopList = async () => {
@@ -575,7 +613,7 @@ const fetchShopList = async () => {
const shops = await adminShopApi.listAllShops() as unknown as Shop[]
shopList.value = shops || []
if (currentUserInfo?.type !== 4 && currentUserInfo?.shopId) {
formState.shopId = normalizeShopId(currentUserInfo.shopId)
formState.shopIds = [normalizeShopId(currentUserInfo.shopId)!]
}
} catch (error) {
console.error('获取店铺列表失败:', error)
@@ -593,7 +631,7 @@ const fetchUserList = async () => {
keyword: searchText.value || undefined
}
if (currentUserInfo?.type !== 4 && currentUserInfo?.shopId) {
if (currentUserInfo?.shopId) {
params.shopId = currentUserInfo.shopId
}
@@ -616,9 +654,9 @@ const resetFormState = () => {
phone: '',
password: '',
type: 0,
shopId: currentUserInfo?.type !== 4 && currentUserInfo?.shopId
? normalizeShopId(currentUserInfo.shopId)
: undefined
shopIds: currentUserInfo?.type !== 4 && currentUserInfo?.shopId
? [normalizeShopId(currentUserInfo.shopId)!]
: []
})
}
@@ -649,7 +687,7 @@ const showEditModal = (record: any) => {
phone: record.phone || '',
password: '',
type: record.type,
shopId: resolveEditableShopId(record.shopId)
shopIds: resolveEditableShopIds(record)
})
modalVisible.value = true
}
@@ -713,15 +751,21 @@ const handleModalOk = async () => {
try {
await formRef.value?.validate()
modalLoading.value = true
const requestData = {
const requestData: Record<string, unknown> = {
account: formState.account.trim(),
nickname: formState.nickname.trim(),
phone: formState.phone.trim(),
type: formState.type,
shopId: formState.shopId || undefined,
shopIds: formState.shopIds,
shopId: formState.shopIds.length ? formState.shopIds[0] : undefined,
...(formState.password.trim() ? { password: formState.password.trim() } : {})
}
if (isEdit.value && currentUserInfo?.type !== 4) {
delete requestData.shopIds
delete requestData.shopId
}
if (isEdit.value && currentUser.value) {
await adminUserApi.updateUser(currentUser.value.id, requestData)
message.success('更新成功')
@@ -751,7 +795,7 @@ const handleStatusChange = async (record: any, checked: boolean) => {
try {
await adminUserApi.updateUserStatus(record.id, checked ? 1 : 0)
record.status = checked ? 1 : 0
message.success('状态更新成功')
message.success(`已${checked ? '启用' : '停用'}当前店铺下的用户访问`)
} catch (error) {
console.error('状态更新失败:', error)
message.error('状态更新失败')
@@ -780,15 +824,8 @@ const handleDelete = async (record: any) => {
message.warning('管理员账号无法被删除')
return
}
const timestamp = Date.now()
await adminUserApi.updateUser(record.id, {
account: `${record.account}_deleted_${timestamp}`,
phone: record.phone ? `${record.phone}_deleted_${timestamp}` : undefined
})
await adminUserApi.deleteUser(record.id)
message.success('删除成功')
message.success('已移除当前店铺下的用户绑定')
await fetchUserList()
} catch (error) {
console.error('删除用户失败:', error)