功能:更新消息中心和 YumiNail 模块

This commit is contained in:
xiaowang
2026-05-13 12:43:01 +08:00
parent 6b9eba5aca
commit 2074addc40
284 changed files with 21031 additions and 4533 deletions
-13
View File
@@ -1,13 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>frontend</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
-3427
View File
File diff suppressed because it is too large Load Diff
-33
View File
@@ -1,33 +0,0 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
"@element-plus/icons-vue": "^2.3.2",
"@iconify/vue": "^5.0.0",
"ant-design-vue": "^4.2.6",
"axios": "^1.13.5",
"element-plus": "^2.13.2",
"pinia": "^3.0.4",
"vue": "^3.5.25",
"vue-router": "^4.6.4"
},
"devDependencies": {
"@types/node": "^24.10.13",
"@vitejs/plugin-vue": "^6.0.2",
"@vue/tsconfig": "^0.8.1",
"less": "^4.5.1",
"sass": "^1.97.3",
"typescript": "~5.9.3",
"unplugin-auto-import": "^21.0.0",
"unplugin-vue-components": "^31.0.0",
"vite": "^7.3.1",
"vue-tsc": "^3.1.5"
}
}
-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

-143
View File
@@ -1,143 +0,0 @@
<template>
<el-config-provider>
<ConfigProvider :locale="antdLocale">
<div class="app-container">
<BottomNav v-if="!isHiddenNav" />
<div class="page-content" :class="{ 'no-nav-padding': isHiddenNav }">
<router-view v-slot="{ Component }">
<transition name="page-fade" mode="out-in">
<component :is="Component" :key="route.path" />
</transition>
</router-view>
</div>
</div>
</ConfigProvider>
</el-config-provider>
</template>
<script setup lang="ts">
import { computed, onMounted, provide, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ConfigProvider } from 'ant-design-vue'
import BottomNav from './components/BottomNav.vue'
import { cartApi } from './api/cart'
import antdLocale from './config/antdv-locale'
const route = useRoute()
const router = useRouter()
const routerReady = ref(false)
const isHiddenNav = computed(() => {
if (!routerReady.value) {
return true
}
if (route.path === '/' || route.path.startsWith('/admin')) {
return true
}
return route.matched.some(r => r.meta.hideNav) || route.matched.some(r => r.meta.isAdmin)
})
// 全局购物车数量状态
const cartCount = ref(0)
// 加载购物车数量
const loadCartCount = async () => {
try {
// 检查用户是否已登录
const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
if (!token) {
cartCount.value = 0
return
}
const response = await cartApi.getCartList() as any
const data = response || []
const cartList = Array.isArray(data) ? data : []
const totalQuantity = cartList.reduce((sum: number, item: any) => sum + (item.quantity || 0), 0)
cartCount.value = totalQuantity
} catch (error) {
cartCount.value = 0
}
}
// 提供更新购物车数量的方法
const updateCartCount = async () => {
await loadCartCount()
}
provide('updateCartCount', updateCartCount)
provide('cartCount', cartCount)
// 监听路由变化,更新购物车数量
watch(() => route.path, async () => {
// 检查当前是否是后台页面,如果是则不加载购物车数据
const isAdminPage = route.matched.some(r => r.meta.isAdmin)
if (!isAdminPage) {
await loadCartCount()
}
})
// 页面加载时获取购物车数量
loadCartCount()
onMounted(async () => {
await router.isReady()
routerReady.value = true
})
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #2c3e50;
}
.app-container {
min-height: 100vh;
display: flex;
flex-direction: column;
position: relative;
}
.page-content {
flex: 1;
padding-bottom: 60px;
position: relative;
z-index: 1;
}
/* 当导航栏隐藏时,移除底部 padding */
.page-content.no-nav-padding {
padding-bottom: 0;
}
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.2s ease;
}
.fade-enter-from {
opacity: 0;
}
.fade-leave-to {
opacity: 0;
}
.page-fade-enter-active,
.page-fade-leave-active {
transition: opacity 0.2s ease;
}
.page-fade-enter-from {
opacity: 0;
}
.page-fade-leave-to {
opacity: 0;
}
</style>
-668
View File
@@ -1,668 +0,0 @@
import axios, { AxiosError, type AxiosProgressEvent } from 'axios'
import router from '../router'
import { message } from 'ant-design-vue'
import { ADMIN_API_BASE_URL } from '../config/api'
import type { IdType } from '@/utils/id'
let lastErrorTime = 0
let lastErrorMessage = ''
const ERROR_DEBOUNCE_TIME = 1000
const adminApi = axios.create({
baseURL: ADMIN_API_BASE_URL,
timeout: 10000,
headers: {
'Content-Type': 'application/json'
}
})
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 => {
if (!isAuthFreePath(config.url)) {
let token = localStorage.getItem('adminAccessToken')
if (!token) {
token = sessionStorage.getItem('adminAccessToken')
}
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
}
return config
},
error => Promise.reject(error)
)
adminApi.interceptors.response.use(
response => {
const res = response.data
if (res.code !== 200) {
const errorMsg = res.message || '请求失败'
if (!errorMsg.includes('权限') && !errorMsg.includes('permission')) {
showError(errorMsg)
} else {
console.error('权限不足:', errorMsg)
}
return Promise.reject(new Error(errorMsg))
}
return res.data as any
},
async (error: AxiosError) => {
const originalRequest = error.config as any
if (error.response?.status === 401) {
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)
})
}
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
}
}
handleAdminTokenExpired()
} else if (error.response?.status !== 403) {
const errorMsg = (error.response?.data as any)?.message || error.message || '请求失败'
showError(errorMsg)
} else {
console.error('权限不足:', error)
}
if (error.response?.status === 403) {
const errorMsg = (error.response?.data as any)?.message || '权限不足'
console.error('Admin API Permission Error:', errorMsg)
return Promise.reject(new Error(errorMsg))
}
console.error('Admin API Error:', error)
return Promise.reject(error)
}
)
export interface AdminLoginRequest {
account: string
password: string
shopId?: IdType
}
export interface AdminLoginResponse {
accessToken: string
refreshToken: string
userInfo: any
}
export interface LoginShopSelectionResponse {
allowShoplessLogin: boolean
message: string
shops: Array<{
id: IdType
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?: IdType) => {
return adminApi.post<AdminLoginResponse>('/auth/switch-shop', { shopId })
},
refreshToken: (refreshToken: string) => {
return adminApi.post<{ accessToken: string; refreshToken: string }>('/auth/refresh', { refreshToken })
}
}
export interface ObjectStorageFileVO {
id: IdType
fileName: string
fileSize: number
contentType: string
createTime: string
}
export interface ChunkUploadInitRequest {
fileName: string
fileSize: number
contentType: string
fileFingerprint: string
scene: string
}
export interface ChunkUploadSessionVO {
uploadId: string
chunkSize: number
totalChunks: number
uploadedChunks: number[]
}
export const adminFileApi = {
uploadFile: (file: File) => {
const formData = new FormData()
formData.append('file', file)
return adminApi.post<ObjectStorageFileVO>('/object-storage-file/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
},
initChunkUpload: (data: ChunkUploadInitRequest) => {
return adminApi.post<ChunkUploadSessionVO>('/object-storage-file/upload/init', data) as unknown as Promise<ChunkUploadSessionVO>
},
uploadChunk: (
data: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob },
config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void }
) => {
const formData = new FormData()
formData.append('uploadId', data.uploadId)
formData.append('chunkIndex', String(data.chunkIndex))
formData.append('totalChunks', String(data.totalChunks))
formData.append('chunk', data.chunk)
return adminApi.post<boolean>('/object-storage-file/upload/chunk', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
signal: config?.signal,
onUploadProgress: config?.onUploadProgress
})
},
completeChunkUpload: (uploadId: string) => {
return adminApi.post<ObjectStorageFileVO>('/object-storage-file/upload/complete', { uploadId }) as unknown as Promise<ObjectStorageFileVO>
},
cancelChunkUpload: (uploadId: string) => {
return adminApi.delete<boolean>(`/object-storage-file/upload/${uploadId}`)
},
getSignedUrl: (id: IdType) => {
return adminApi.get<string>(`/object-storage-file/get-signed-url/${id}`)
}
}
export interface Tag {
id: IdType
tagName: string
textColor?: string
bgColor?: string
borderColor?: string
shopId?: IdType
shopName?: string
createTime: string
updateTime: string
}
export const adminTagApi = {
listAllTags: () => {
return adminApi.get<Tag[]>('/tag/list/all') as unknown as Promise<Tag[]>
},
listTagsByShopId: (shopId: IdType) => {
return adminApi.get<Tag[]>(`/tag/list/by-shop/${shopId}`) as unknown as Promise<Tag[]>
},
createTag: (data: { tagName: string; textColor?: string; bgColor?: string; borderColor?: string; shopId?: IdType }) => {
return adminApi.post<IdType>('/tag/create', data)
},
updateTag: (id: IdType, data: { tagName: string; textColor?: string; bgColor?: string; borderColor?: string; shopId?: IdType }) => {
return adminApi.put<boolean>(`/tag/update/${id}`, data)
},
deleteTag: (id: IdType) => {
return adminApi.delete<boolean>(`/tag/delete/${id}`)
}
}
export interface Artist {
id: IdType
nickname: string
account: string
avatar?: string
shopId?: IdType
shopName?: string
createTime: string
updateTime: string
}
export const adminArtistApi = {
listArtists: (shopId?: IdType) => {
const params: any = {}
if (shopId) {
params.shopId = shopId
}
return adminApi.get<Artist[]>('/user/list/artists', { params })
}
}
export interface Coupon {
id: IdType
couponCode?: string
couponName: string
couponType: number
couponTypeName?: string
discountValue?: string
minAmount?: number
reduceAmount?: string
totalCount?: number
usedCount?: number
remainingCount?: number
startTime: string
endTime: string
status?: number
statusName?: string
shopId?: IdType
shopName?: string
couponScene?: string
requiredVipLevel?: string
autoMatch?: number
availableTags?: Tag[]
unavailableTags?: Tag[]
createTime: string
updateTime: string
}
export const adminCouponApi = {
listAllCoupons: (shopId?: IdType) => {
const params = shopId ? { shopId } : {}
return adminApi.get<Coupon[]>('/coupon/list/all', { params }) as unknown as Promise<Coupon[]>
},
createCoupon: (data: any) => {
return adminApi.post<IdType>('/coupon/create', data)
},
updateCoupon: (id: IdType, data: any) => {
return adminApi.put<boolean>(`/coupon/update/${id}`, data)
},
deleteCoupon: (id: IdType) => {
return adminApi.delete<boolean>(`/coupon/delete/${id}`)
},
distributeCoupon: (data: any) => {
return adminApi.post<boolean>('/coupon/distribute', null, { params: data })
}
}
export interface Product {
id: IdType
shopId: IdType
shopName?: string
title: string
description: string
price: number
approximateDuration?: string
tags?: string
tagList?: string[]
tagInfos?: any[]
imageFileIds?: string
imageUrls?: string[]
bookableArtists?: string
availableCoupons?: string
likeCount?: number
collectCount?: number
createTime: string
updateTime: string
}
export const adminProductApi = {
listProducts: (params: { page: number; size: number; keyword?: string; shopId?: IdType }) => {
return adminApi.get<{ list: Product[]; total: number; page: number; size: number }>('/product/list', { params })
},
listAllProducts: () => {
return adminApi.get<Product[]>('/product/list/all')
},
createProduct: (data: any) => {
return adminApi.post<IdType>('/product/create', data)
},
updateProduct: (id: IdType, data: any) => {
return adminApi.put<boolean>(`/product/update/${id}`, data)
},
deleteProduct: (id: IdType) => {
return adminApi.delete<boolean>(`/product/delete/${id}`)
}
}
export interface Shop {
id: IdType
shopName: string
description: string
address: string
businessHours: string
status?: number
coverImageFileId?: string
coverImageUrls?: string[]
imageFileIds?: string
imageUrls?: string[]
createTime: string
updateTime: string
}
export interface ShopListResponse {
list: Shop[]
total: number
page: number
size: number
}
export interface CreateShopRequest {
shopName: string
description: string
address: string
businessHours: string
coverImageFileId?: string
imageFileIds?: string
status?: number
}
export const adminShopApi = {
listShops: (params: { page: number; size: number; keyword?: string; shopId?: IdType }) => {
return adminApi.get<ShopListResponse>('/shops/list', { params }) as unknown as Promise<ShopListResponse>
},
listAllShops: () => {
return adminApi.get<Shop[]>('/shops/list/all') as unknown as Promise<Shop[]>
},
createShop: (data: CreateShopRequest) => {
return adminApi.post<IdType>('/shops/create', data)
},
updateShop: (id: IdType, data: CreateShopRequest) => {
return adminApi.put<boolean>(`/shops/update/${id}`, data)
},
updateShopStatus: (id: IdType, status: number) => {
return adminApi.put<boolean>(`/shops/status/${id}`, { status })
},
deleteShop: (id: IdType) => {
return adminApi.delete<boolean>(`/shops/delete/${id}`)
}
}
export interface UserVO {
id: IdType
shopId?: IdType
shopName?: string
shopIds?: IdType[]
shopNames?: string[]
nickname: string
account: string
avatar: string
phone?: string
signature?: string
level?: string
type: number
vipId?: IdType
createTime: string
updateTime: string
status?: number
}
export interface PageResult<T> {
list: T[]
total: number
page: number
size: number
}
export const adminUserApi = {
listUsers: (params: { page: number; size: number; keyword?: string; type?: number; shopId?: IdType; status?: number }) => {
return adminApi.get<PageResult<UserVO>>('/user/list', { params }) as unknown as Promise<PageResult<UserVO>>
},
listAllUsers: () => {
return adminApi.get<UserVO[]>('/user/list/all') as unknown as Promise<UserVO[]>
},
createUser: (data: any) => {
return adminApi.post<IdType>('/user/create', data)
},
updateUser: (id: IdType, data: any) => {
return adminApi.put<boolean>(`/user/update/${id}`, data)
},
deleteUser: (id: IdType) => {
return adminApi.delete<boolean>(`/user/delete/${id}`)
},
unbindUser: (id: IdType) => {
return adminApi.put<boolean>(`/user/unbind/${id}`, {})
},
updateUserStatus: (id: IdType, status: number) => {
return adminApi.put<boolean>(`/user/status/${id}`, { status })
},
resetPassword: (id: IdType) => {
return adminApi.post<string>(`/user/reset-password/${id}`)
},
getUserInfo: () => {
return adminApi.get<UserVO>('/user/info') as unknown as Promise<UserVO>
},
getUserAsset: (id: IdType) => {
return adminApi.get<UserAssetVO>(`/user/${id}/asset`) as unknown as Promise<UserAssetVO>
},
getUserBalanceHistory: (id: IdType) => {
return adminApi.get<UserBalanceHistoryItem[]>(`/user/${id}/balance/history`) as unknown as Promise<UserBalanceHistoryItem[]>
},
changeUserBalance: (id: IdType, data: AdminUserBalanceChangeRequest) => {
return adminApi.post<UserAssetVO>(`/user/${id}/balance/change`, data) as unknown as Promise<UserAssetVO>
},
overrideUserVip: (id: IdType, data: AdminUserVipOverrideRequest) => {
return adminApi.post<UserAssetVO>(`/user/${id}/vip/override`, data) as unknown as Promise<UserAssetVO>
},
recalculateUserVip: (id: IdType) => {
return adminApi.post<UserAssetVO>(`/user/${id}/vip/recalculate`) as unknown as Promise<UserAssetVO>
}
}
export interface UserAssetVO {
userId: IdType
nickname: string
balance: number
totalRechargeAmount: number
lastRechargeTime?: string
vipInfoId?: IdType
vipLevel: string
benefitId?: IdType
benefitInfo?: string
manualOverride: boolean
vipStartTime?: string
vipExpireTime?: string
}
export interface UserBalanceHistoryItem {
id: IdType
userId: IdType
userNickname?: string
amount: number
type?: string
currentBalance?: number
beforeBalance?: number
afterBalance?: number
changeScene?: string
relatedOrderId?: IdType
relatedOrderNo?: string
externalOrderNo?: string
operatorId?: IdType
remark?: string
changeTime: string
}
export interface AdminUserBalanceChangeRequest {
amount: number
changeScene: string
relatedOrderId?: IdType
externalOrderNo?: string
remark?: string
}
export interface AdminUserVipOverrideRequest {
vipLevel: string
remark?: string
}
export const userApi = adminUserApi
export interface OrderVO {
id: IdType
orderNo: string
userId: IdType
userNickname?: string
shopId: IdType
shopName?: string
artistId?: IdType
artistName?: string
totalAmount: number
discountAmount: number
payAmount: number
status: number
statusText?: string
remark?: string
createTime: string
updateTime: string
}
export const adminOrderApi = {
listOrders: (params: { page: number; size: number; keyword?: string; status?: number; shopId?: IdType }) => {
return adminApi.get<PageResult<OrderVO>>('/order/list', { params })
},
updateOrderStatus: (id: IdType, status: number) => {
return adminApi.put<boolean>(`/order/update-status/${id}`, { status })
}
}
export interface HotProductVO {
id: IdType
title: string
price: number
likeCount: number
collectCount: number
}
export interface RecentActivityVO {
id: IdType
type: string
title?: string
description: string
time: string
color?: string
}
export interface DashboardStats {
totalUsers: number
totalProducts: number
totalShops: number
todayOrders: number
hotProducts: HotProductVO[]
recentActivities: RecentActivityVO[]
}
export const adminDashboardApi = {
getStats: () => {
return adminApi.get<DashboardStats>('/dashboard/stats')
}
}
export interface NailArtistInfoVO {
id: IdType
userId: IdType
identity: string
experience: number
skills: string
rating: number
status: number
portfolio: string
nickname: string
shopId: IdType
shopName: string
}
export const adminNailArtistApi = {
listNailArtists: () => {
return adminApi.get<NailArtistInfoVO[]>('/nail-artist/list')
},
getNailArtistInfo: (userId: IdType) => {
return adminApi.get<NailArtistInfoVO>(`/nail-artist/get/${userId}`)
},
saveNailArtistInfo: (data: any) => {
return adminApi.post<NailArtistInfoVO>('/nail-artist/save', data)
}
}
export { adminApi }
export default adminApi
-110
View File
@@ -1,110 +0,0 @@
import api from './index'
import type { IdType } from '@/utils/id'
export interface SendVerificationCodeRequest {
phone: string
}
export interface LoginRequest {
account: string
password: string
rememberMe?: boolean
shopId?: string | number
}
export interface PhoneLoginRequest {
phone: string
verificationCode: string
shopId?: string | number
}
export interface RegisterRequest {
account: string
password: string
nickname: string
shopId?: string | number
phone?: string
verificationCode?: string
}
export interface LoginResponse {
accessToken: string
refreshToken: string
userInfo: UserInfo
}
export interface UserInfo {
id: IdType
account: string
nickname: string
avatar?: string
signature?: string
type?: number
shopId?: IdType
shopName?: string
shopIds?: IdType[]
shopNames?: string[]
createTime: string
updateTime?: string
}
export interface RefreshTokenRequest {
refreshToken: string
}
export interface RefreshTokenResponse {
accessToken: string
refreshToken: string
}
export interface ResetPasswordRequest {
phone: string
verificationCode: string
newPassword: string
}
export interface SwitchShopRequest {
shopId?: string | number
}
export const authApi = {
sendVerificationCode: (data: SendVerificationCodeRequest) => {
return api.post('/user/send-verification-code', data)
},
login: (data: LoginRequest) => {
return api.post<LoginResponse>('/user/login', data)
},
phoneLogin: (data: PhoneLoginRequest) => {
return api.post<LoginResponse>('/user/phone-login', data)
},
adminLogin: (data: LoginRequest) => {
return api.post<LoginResponse>('/admin/auth/login', data)
},
register: (data: RegisterRequest) => {
return api.post('/user/register', data)
},
refreshToken: (data: RefreshTokenRequest) => {
return api.post<RefreshTokenResponse>('/user/refresh-token', data)
},
logout: () => {
return api.post('/user/logout')
},
switchShop: (data: SwitchShopRequest) => {
return api.post<LoginResponse>('/user/switch-shop', data)
},
getUserInfo: () => {
return api.get<UserInfo>('/user/info')
},
resetPasswordByPhone: (data: ResetPasswordRequest) => {
return api.post('/user/reset-password-by-phone', data)
}
}
-39
View File
@@ -1,39 +0,0 @@
import api from './index'
import type { IdType } from '@/utils/id'
interface CartItem {
productId: IdType
quantity: number
}
export const cartApi = {
// 添加作品到购物车
addToCart: (item: CartItem) => {
return api.post('/cart/add', item)
},
// 从购物车移除作品
removeFromCart: (productId: IdType) => {
return api.delete(`/cart/remove/${productId}`)
},
// 批量从购物车移除作品
batchRemoveFromCart: (cartItemIds: IdType[]) => {
return api.post('/cart/batch-remove', cartItemIds)
},
// 更新购物车作品数量
updateCartQuantity: (item: CartItem) => {
return api.put('/cart/update', item)
},
// 获取购物车列表
getCartList: () => {
return api.get('/cart/list')
},
// 清空购物车
clearCart: () => {
return api.delete('/cart/clear')
}
}
-156
View File
@@ -1,156 +0,0 @@
import request from './index'
import type { IdType } from '@/utils/id'
export interface Coupon {
id: IdType
couponCode: string
couponName: string
couponType: number
couponTypeName: string
discountValue?: number
minAmount?: number
reduceAmount?: number
totalCount: number
usedCount: number
remainingCount: number
startTime: string
endTime: string
status: number
statusName: string
shopId?: IdType
couponScene?: string
requiredVipLevel?: string
autoMatch?: number
availableTags: Tag[]
unavailableTags: Tag[]
}
export interface Tag {
id: IdType
tagName?: string
}
export interface UserCoupon {
id: IdType
couponId: IdType
couponName: string
couponType: number
couponTypeName: string
discountValue: string
minAmount: string
reduceAmount: string
startTime: string
endTime: string
status: number
statusName: string
obtainTime: string
useTime: string
sourceType?: string
requiredVipLevel?: string
autoMatched?: boolean
}
export interface CreateCouponRequest {
couponCode: string
couponName: string
couponType: number
discountValue?: number
minAmount?: number
reduceAmount?: number
totalCount: number
startTime: string
endTime: string
couponScene?: string
requiredVipLevel?: string
autoMatch?: number
availableTagIds: IdType[]
unavailableTagIds: IdType[]
}
export interface CouponListResponse {
list: Coupon[]
total: number
page: number
size: number
}
export const couponApi = {
// 创建优惠券
createCoupon: (data: CreateCouponRequest) => {
return request({
url: '/coupon/create',
method: 'post',
data
})
},
// 更新优惠券
updateCoupon: (id: IdType, data: CreateCouponRequest) => {
return request({
url: `/coupon/update/${id}`,
method: 'put',
data
})
},
// 删除优惠券
deleteCoupon: (id: IdType) => {
return request({
url: `/coupon/delete/${id}`,
method: 'delete'
})
},
// 获取优惠券详情
getCouponById: (id: IdType) => {
return request({
url: `/coupon/detail/${id}`,
method: 'get'
})
},
// 获取优惠券列表
listCoupons: (params: { page: number; size: number; shopId?: IdType }) => {
return request({
url: '/coupon/list',
method: 'get',
params
})
},
// 为用户分配优惠券
assignCouponToUser: (userId: IdType, couponId: IdType) => {
return request({
url: '/coupon/assign',
method: 'post',
params: { userId, couponId }
})
},
// 获取用户优惠券列表
listUserCoupons: async (status?: number): Promise<UserCoupon[]> => {
return await request({
url: '/coupon/user/list',
method: 'get',
params: { status }
}) as UserCoupon[]
},
// 使用优惠券
useCoupon: (userCouponId: IdType) => {
return request({
url: '/coupon/use',
method: 'post',
params: { userCouponId }
})
},
// 获取作品可用的优惠券
getAvailableCoupons: async (productTags: string, productPrice: number, shopId?: IdType): Promise<UserCoupon[]> => {
return await request({
url: '/coupon/available',
method: 'get',
params: { productTags, productPrice, shopId }
}) as UserCoupon[]
}
}
-62
View File
@@ -1,62 +0,0 @@
import type { AxiosProgressEvent } from 'axios'
import api from './index'
import type { IdType } from '@/utils/id'
export interface ChunkUploadInitRequest {
fileName: string
fileSize: number
contentType: string
fileFingerprint: string
scene: string
}
export interface ChunkUploadSessionVO {
uploadId: string
chunkSize: number
totalChunks: number
uploadedChunks: number[]
}
export const fileApi = {
uploadAvatar: (file: File) => {
const formData = new FormData()
formData.append('file', file)
return api.post<string>('/user/upload-avatar', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
},
initAvatarChunkUpload: (data: ChunkUploadInitRequest) => {
return api.post<ChunkUploadSessionVO>('/user/upload-avatar/init', data) as unknown as Promise<ChunkUploadSessionVO>
},
uploadAvatarChunk: (
data: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob },
config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void }
) => {
const formData = new FormData()
formData.append('uploadId', data.uploadId)
formData.append('chunkIndex', String(data.chunkIndex))
formData.append('totalChunks', String(data.totalChunks))
formData.append('chunk', data.chunk)
return api.post<boolean>('/user/upload-avatar/chunk', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
signal: config?.signal,
onUploadProgress: config?.onUploadProgress
})
},
completeAvatarChunkUpload: (uploadId: string) => {
return api.post<string>('/user/upload-avatar/complete', { uploadId }) as unknown as Promise<string>
},
cancelAvatarChunkUpload: (uploadId: string) => {
return api.delete<boolean>(`/user/upload-avatar/${uploadId}`)
},
getSignedUrl: (fileId: IdType, expiryTimeInMinutes?: number) => {
return api.get<string>(`/file/get-signed-url/${fileId}`, {
params: { expiryTimeInMinutes }
})
}
}
-236
View File
@@ -1,236 +0,0 @@
import axios, { AxiosError } from 'axios'
import { authApi } from './auth'
import { adminAuthApi } from './admin'
import { wishlistApi } from './wishlist'
import router from '../router'
import { message } from 'ant-design-vue'
import { API_BASE_URL } from '../config/api'
import type { IdType } from '@/utils/id'
// 防重复提示标志
let lastErrorTime = 0
let lastErrorMessage = ''
const ERROR_DEBOUNCE_TIME = 1000 // 1秒内不重复显示相同错误
const api = axios.create({
baseURL: API_BASE_URL,
timeout: 10000,
headers: {
'Content-Type': 'application/json'
}
})
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 handleTokenExpired = (isAdmin = false) => {
// 清理token和用户信息
if (isAdmin) {
// 清理后台管理的token
localStorage.removeItem('adminAccessToken')
localStorage.removeItem('adminRefreshToken')
localStorage.removeItem('adminUserInfo')
localStorage.removeItem('userPermissions')
sessionStorage.removeItem('adminAccessToken')
} else {
// 清理前台的token
localStorage.removeItem('accessToken')
localStorage.removeItem('refreshToken')
localStorage.removeItem('userInfo')
sessionStorage.removeItem('accessToken')
}
// 显示错误提示
if (Date.now() - lastErrorTime > ERROR_DEBOUNCE_TIME || lastErrorMessage !== '登录已过期,请重新登录') {
showError('登录已过期,请重新登录')
}
// 执行跳转,确保无论如何都会跳转
setTimeout(() => {
if (isAdmin) {
try {
router.push('/admin/login').catch(() => {
window.location.href = '/admin/login'
})
} catch {
window.location.href = '/admin/login'
}
} else {
try {
router.push('/').catch(() => {
window.location.href = '/'
})
} catch {
window.location.href = '/'
}
}
}, 500) // 延迟执行,确保错误提示先显示
}
api.interceptors.request.use(
config => {
let token = localStorage.getItem('accessToken')
if (!token) {
token = sessionStorage.getItem('accessToken')
}
// 检查是否是后台管理的API请求
if (!token && (config.url?.includes('/admin/') || config.url?.includes('/order/admin/'))) {
token = localStorage.getItem('adminAccessToken')
if (!token) {
token = sessionStorage.getItem('adminAccessToken')
}
}
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
},
error => {
return Promise.reject(error)
}
)
api.interceptors.response.use(
response => {
const res = response.data
if (res.code !== 200) {
const errorMsg = res.message || '请求失败'
if (!errorMsg.includes('权限') && !errorMsg.includes('permission')) {
showError(errorMsg)
}
return Promise.reject(new Error(errorMsg))
}
return res.data as any
},
async (error: AxiosError) => {
const originalRequest = error.config as any
const isWhitelistedPath = (url: string) => {
return url?.includes('/user/login') ||
url?.includes('/user/register') ||
url?.includes('/user/check/') ||
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')
}
if (error.response?.status === 401) {
// 检查是否是后台管理的API请求
const isAdminRequest = originalRequest.url?.includes('/admin/') || originalRequest.url?.includes('/order/admin/')
if (!originalRequest._retry && !isWhitelistedPath(originalRequest.url)) {
if (isRefreshing) {
return new Promise((resolve, reject) => {
failedQueue.push({ resolve, reject })
}).then(token => {
if (token) {
originalRequest.headers.Authorization = `Bearer ${token}`
}
return api(originalRequest)
}).catch(err => {
return Promise.reject(err)
})
}
originalRequest._retry = true
isRefreshing = true
try {
let refreshToken
if (isAdminRequest) {
refreshToken = localStorage.getItem('adminRefreshToken')
} else {
refreshToken = localStorage.getItem('refreshToken')
}
if (!refreshToken) {
throw new Error('No refresh token available')
}
// 这里需要根据是否是后台请求调用不同的refreshToken API
// 暂时使用同一个API,实际项目中可能需要分开
const response = isAdminRequest
? await adminAuthApi.refreshToken(refreshToken)
: await authApi.refreshToken({ refreshToken })
const newToken = (response as any).accessToken
const newRefreshToken = (response as any).refreshToken
if (isAdminRequest) {
localStorage.setItem('adminAccessToken', newToken)
localStorage.setItem('adminRefreshToken', newRefreshToken)
sessionStorage.setItem('adminAccessToken', newToken)
} else {
localStorage.setItem('accessToken', newToken)
localStorage.setItem('refreshToken', newRefreshToken)
sessionStorage.setItem('accessToken', newToken)
}
processQueue(null, newToken)
originalRequest.headers.Authorization = `Bearer ${newToken}`
return api(originalRequest)
} catch (refreshError) {
processQueue(refreshError, null)
handleTokenExpired(isAdminRequest)
return Promise.reject(refreshError)
} finally {
isRefreshing = false
}
} else {
handleTokenExpired(isAdminRequest)
return Promise.reject(error)
}
} else if (error.response?.status !== 403) { // 403权限不足不提示
const errorMsg = (error.response?.data as any)?.message || error.message || '请求失败'
showError(errorMsg)
}
return Promise.reject(error)
}
)
export const fileApi = {
getSignedUrl: (fileId: IdType, expiryTimeInMinutes?: number) => {
return api.get<string>(`/file/get-signed-url/${fileId}`, {
params: { expiryTimeInMinutes }
})
}
}
export { wishlistApi }
export default api
-58
View File
@@ -1,58 +0,0 @@
import api from './index'
import type { IdType } from '@/utils/id'
interface OrderItem {
productId: IdType
quantity: number
artistId?: IdType
appointmentTime?: string
}
interface CreateOrderRequest {
couponId?: IdType
couponSourceType?: string
items: OrderItem[]
}
export const orderApi = {
// 创建订单
createOrder: (data: CreateOrderRequest) => {
return api.post('/order/create', data)
},
// 获取订单列表
getOrderList: async (): Promise<any[]> => {
return await api.get<any[]>('/order/list') as unknown as any[]
},
// 获取订单详情
getOrderDetail: (orderId: IdType) => {
return api.get(`/order/detail/${orderId}`)
},
// 取消订单
cancelOrder: (orderId: IdType) => {
return api.put(`/order/cancel/${orderId}`)
},
// 后台获取所有订单
getAllOrders: () => {
return api.get('/order/admin/list')
},
// 后台处理订单
processOrder: (orderId: IdType, status: number) => {
return api.put(`/order/admin/process/${orderId}`, {}, {
params: { status }
})
},
// 美甲师查看自己的订单
getArtistOrders: () => {
return api.get('/order/artist/list')
},
completeArtistOrder: (orderId: IdType) => {
return api.put(`/order/artist/complete/${orderId}`)
}
}
-59
View File
@@ -1,59 +0,0 @@
import { adminApi } from './admin'
import type { IdType } from '@/utils/id'
export interface PermissionVO {
id: IdType
permissionCode: string
permissionName: string
permissionGroup: string
description: string
createTime: string
updateTime: string
}
export interface CreatePermissionRequest {
permissionCode: string
permissionName: string
permissionGroup: string
description: string
}
export interface UpdatePermissionRequest {
permissionCode?: string
permissionName?: string
permissionGroup?: string
description?: string
}
export const permissionApi = {
getUserPermissions: (userId?: IdType) => {
if (userId) {
return adminApi.get<PermissionVO[]>(`/permission/user/${userId}`)
}
return adminApi.get<PermissionVO[]>('/permission/user/current')
},
getAssignablePermissionIds: (userId: IdType) => {
return adminApi.get<IdType[]>(`/permission/assignable/${userId}`)
},
listAllPermissions: () => {
return adminApi.get<PermissionVO[]>('/permission/list/all')
},
createPermission: (data: CreatePermissionRequest) => {
return adminApi.post('/permission/create', data)
},
updatePermission: (id: IdType, data: UpdatePermissionRequest) => {
return adminApi.put(`/permission/update/${id}`, data)
},
deletePermission: (id: IdType) => {
return adminApi.delete(`/permission/delete/${id}`)
},
assignUserPermissions: (userId: IdType, permissionIds: IdType[]) => {
return adminApi.post(`/permission/assign/${userId}`, { permissionIds })
}
}
-96
View File
@@ -1,96 +0,0 @@
import api from './index'
import type { IdType } from '@/utils/id'
export interface ProductVO {
id: IdType
shopId: IdType | null
shopName?: string
name: string
title?: string
description: string
image: string
imageFileIds?: string
imageUrls?: string[]
price: number
estimatedTime: number
approximateDuration?: string
bookableArtists?: string
availableBookableArtistCount?: number
bookableArtistRestricted?: boolean
availableCoupons?: string
category: string
tags?: string
tagList?: string[]
tagInfos?: TagInfo[]
status: number
likeCount?: number
collectCount?: number
createTime: string
updateTime: string
}
export interface TagInfo {
id: IdType
tagName: string
textColor?: string
bgColor?: string
borderColor?: string
}
export interface ListProductsParams {
page: number
size: number
keyword?: string
}
export interface CreateProductRequest {
name: string
description: string
image: string
price: number
estimatedTime: number
category: string
status: number
shopId: IdType | null
}
export interface UpdateProductRequest {
name?: string
description?: string
image?: string
price?: number
estimatedTime?: number
category?: string
status?: number
shopId?: IdType | null
}
export const productApi = {
getAllProducts: async (): Promise<ProductVO[]> => {
return await api.get<ProductVO[]>('/product/list/all') as unknown as ProductVO[]
},
getProductById: async (id: IdType): Promise<ProductVO> => {
return await api.get<ProductVO>(`/product/get/${id}`) as unknown as ProductVO
},
getProductsByTag: async (tag: string): Promise<ProductVO[]> => {
return await api.get<ProductVO[]>(`/product/list/tag/${tag}`) as unknown as ProductVO[]
},
likeProduct: async (productId: IdType): Promise<boolean> => {
return await api.post<boolean>(`/product/like/${productId}`) as unknown as boolean
},
unlikeProduct: async (productId: IdType): Promise<boolean> => {
return await api.post<boolean>(`/product/unlike/${productId}`) as unknown as boolean
},
searchProducts: async (keyword: string): Promise<ProductVO[]> => {
return await api.get<ProductVO[]>('/product/list/search', {
params: {
keyword: keyword
}
}) as unknown as ProductVO[]
}
}
-28
View File
@@ -1,28 +0,0 @@
import api from './index'
import type { IdType } from '@/utils/id'
export const productLikeApi = {
/**
* 点赞作品
* @param productId 作品ID
*/
likeProduct: (productId: IdType) => {
return api.post<boolean>(`/product-like/like/${productId}`)
},
/**
* 取消点赞作品
* @param productId 作品ID
*/
unlikeProduct: (productId: IdType) => {
return api.post<boolean>(`/product-like/unlike/${productId}`)
},
/**
* 检查用户是否已点赞作品
* @param productId 作品ID
*/
checkLikeStatus: (productId: IdType) => {
return api.get<boolean>(`/product-like/check/${productId}`)
}
}
-67
View File
@@ -1,67 +0,0 @@
import api from './index'
import type { IdType } from '@/utils/id'
export interface ShopVO {
id: IdType
shopName: string
description: string
address: string
businessHours: string
status?: number
coverImageFileId?: string
coverImageUrls?: string[]
imageFileIds: string
imageUrls?: string[]
createTime: string
updateTime: string
}
export interface ShopSimpleVO {
id: string | number
shopName?: string
name?: string
}
export interface ListShopsParams {
page: number
size: number
keyword?: string
}
export interface CreateShopRequest {
name: string
description: string
image: string
phone: string
address: string
businessHours: string
status: number
}
export interface UpdateShopRequest {
name?: string
description?: string
image?: string
phone?: string
address?: string
businessHours?: string
status?: number
}
export const shopApi = {
getAllShops: async (): Promise<ShopVO[]> => {
return await api.get<ShopVO[]>('/shop/list/all') as unknown as ShopVO[]
},
getPublicShops: async (): Promise<ShopVO[]> => {
return await api.get<ShopVO[]>('/shop/list/public') as unknown as ShopVO[]
},
getShopsSimple: async (): Promise<ShopSimpleVO[]> => {
return await api.get<ShopSimpleVO[]>('/shop/list/simple') as unknown as ShopSimpleVO[]
},
getShopById: async (id: IdType): Promise<ShopVO> => {
return await api.get<ShopVO>(`/shop/get/${id}`) as unknown as ShopVO
}
}
-41
View File
@@ -1,41 +0,0 @@
import api from './index'
import type { IdType } from '@/utils/id'
export interface TagVO {
id: IdType
tagName: string
textColor: string
bgColor: string
borderColor: string
createTime: string
updateTime: string
}
export interface TagDTO {
tagName: string
textColor: string
bgColor: string
borderColor: string
}
export const tagApi = {
getAllTags: () => {
return api.get<TagVO[]>('/tag/list/all')
},
getTagById: (id: IdType) => {
return api.get<TagVO>(`/tag/get/${id}`)
},
createTag: (data: TagDTO) => {
return api.post<TagVO>('/tag/add', data)
},
updateTag: (id: IdType, data: TagDTO) => {
return api.put<TagVO>(`/tag/update/${id}`, data)
},
deleteTag: (id: IdType) => {
return api.delete(`/tag/delete/${id}`)
}
}
-139
View File
@@ -1,139 +0,0 @@
import api from './index'
import type { UserInfo } from './auth'
import type { IdType } from '@/utils/id'
export interface UserVO extends UserInfo {
id: IdType
shopId?: IdType
shopName?: string
shopIds?: IdType[]
shopNames?: string[]
nickname: string
account: string
avatar: string
signature?: string
level?: string
type: number
vipId?: IdType
createTime: string
updateTime: string
status: number
phone?: string
}
export interface UpdateUserInfoRequest {
nickname?: string
avatar?: string
signature?: string
}
export interface ListUsersParams {
page: number
size: number
keyword?: string
shopId?: IdType
status?: number
}
export interface CreateUserRequest {
account: string
nickname: string
phone: string
password: string
type: number
shopId?: IdType
shopIds?: IdType[]
}
export interface UpdateUserRequest {
account?: string
nickname?: string
phone?: string
type?: number
shopId?: IdType
shopIds?: IdType[]
}
export interface UpdatePasswordRequest {
password: string
verificationCode: string
}
export interface BindPhoneRequest {
phone: string
verificationCode: string
}
export interface AvailabilityCheckResponse {
available: boolean
message: string
}
export interface LoginAccountCheckResponse {
exists: boolean
nickname?: string
message: string
}
export interface LoginShopSelectionResponse {
allowShoplessLogin: boolean
message: string
shops: Array<{
id: IdType
shopName: string
}>
}
export interface UpdatePhoneRequest {
oldPhone: string
newPhone: string
verificationCode: string
}
export const userApi = {
getUserInfo: async (): Promise<UserVO> => {
return await api.get<UserVO>('/user/info') as unknown as UserVO
},
updateUserInfo: (data: UpdateUserInfoRequest) => {
return api.put('/user/update', data)
},
updatePassword: (data: UpdatePasswordRequest) => {
return api.put('/user/password', data)
},
bindPhone: (data: BindPhoneRequest) => {
return api.post('/user/bind-phone', data)
},
updatePhone: (data: UpdatePhoneRequest) => {
return api.put('/user/phone', data)
},
getUserByAccount: async (account: string): Promise<UserVO> => {
return await api.get<UserVO>(`/user/get/account/${account}`) as unknown as UserVO
},
checkAccountAvailability: async (account: string): Promise<AvailabilityCheckResponse> => {
return await api.get<AvailabilityCheckResponse>(`/user/check/account/${encodeURIComponent(account)}`) as unknown as AvailabilityCheckResponse
},
checkLoginAccountAvailability: async (account: string): Promise<LoginAccountCheckResponse> => {
return await api.get<LoginAccountCheckResponse>(`/user/check/login-account/${encodeURIComponent(account)}`) as unknown as LoginAccountCheckResponse
},
getLoginShopsByAccount: async (account: string): Promise<LoginShopSelectionResponse> => {
return await api.get<LoginShopSelectionResponse>(`/user/check/login-shops/account/${encodeURIComponent(account)}`) as unknown as LoginShopSelectionResponse
},
getLoginShopsByPhone: async (phone: string): Promise<LoginShopSelectionResponse> => {
return await api.get<LoginShopSelectionResponse>(`/user/check/login-shops/phone/${encodeURIComponent(phone)}`) as unknown as LoginShopSelectionResponse
},
checkPhoneAvailability: async (phone: string): Promise<AvailabilityCheckResponse> => {
return await api.get<AvailabilityCheckResponse>(`/user/check/phone/${encodeURIComponent(phone)}`) as unknown as AvailabilityCheckResponse
},
listUsersByType: async (type: number): Promise<UserVO[]> => {
return await api.get<UserVO[]>(`/user/list/type/${type}`) as unknown as UserVO[]
},
sendVerificationCode: (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')
}
}
-46
View File
@@ -1,46 +0,0 @@
import api from './index'
import type { IdType } from '@/utils/id'
export interface WishlistItem {
id: IdType
userId: IdType
productId: IdType
product: {
id: IdType
shopId: IdType | null
shopName?: string
title: string
description: string
imageFileIds?: string
imageUrls?: string[]
price: number
tags?: string
tagList?: string[]
tagInfos?: any[]
likeCount?: number
collectCount?: number
approximateDuration?: string
bookableArtists?: string
availableCoupons?: string
createTime: string
updateTime: string
}
}
export const wishlistApi = {
addToWishlist: async (productId: IdType): Promise<boolean> => {
return await api.post<boolean>('/wishlist/add', { productId }) as unknown as boolean
},
removeFromWishlist: async (productId: IdType): Promise<boolean> => {
return await api.post<boolean>('/wishlist/remove', { productId }) as unknown as boolean
},
checkWishlist: async (productId: IdType): Promise<boolean> => {
return await api.get<boolean>(`/wishlist/check?productId=${productId}`) as unknown as boolean
},
getWishlist: async (): Promise<WishlistItem[]> => {
return await api.get<WishlistItem[]>('/wishlist/list') as unknown as WishlistItem[]
}
}
-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>

Before

Width:  |  Height:  |  Size: 496 B

-90
View File
@@ -1,90 +0,0 @@
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// Generated by unplugin-auto-import
// biome-ignore lint: disable
export {}
declare global {
const EffectScope: typeof import('vue').EffectScope
const acceptHMRUpdate: typeof import('pinia').acceptHMRUpdate
const computed: typeof import('vue').computed
const createApp: typeof import('vue').createApp
const createPinia: typeof import('pinia').createPinia
const customRef: typeof import('vue').customRef
const defineAsyncComponent: typeof import('vue').defineAsyncComponent
const defineComponent: typeof import('vue').defineComponent
const defineStore: typeof import('pinia').defineStore
const effectScope: typeof import('vue').effectScope
const getActivePinia: typeof import('pinia').getActivePinia
const getCurrentInstance: typeof import('vue').getCurrentInstance
const getCurrentScope: typeof import('vue').getCurrentScope
const getCurrentWatcher: typeof import('vue').getCurrentWatcher
const h: typeof import('vue').h
const inject: typeof import('vue').inject
const isProxy: typeof import('vue').isProxy
const isReactive: typeof import('vue').isReactive
const isReadonly: typeof import('vue').isReadonly
const isRef: typeof import('vue').isRef
const isShallow: typeof import('vue').isShallow
const mapActions: typeof import('pinia').mapActions
const mapGetters: typeof import('pinia').mapGetters
const mapState: typeof import('pinia').mapState
const mapStores: typeof import('pinia').mapStores
const mapWritableState: typeof import('pinia').mapWritableState
const markRaw: typeof import('vue').markRaw
const nextTick: typeof import('vue').nextTick
const onActivated: typeof import('vue').onActivated
const onBeforeMount: typeof import('vue').onBeforeMount
const onBeforeRouteLeave: typeof import('vue-router').onBeforeRouteLeave
const onBeforeRouteUpdate: typeof import('vue-router').onBeforeRouteUpdate
const onBeforeUnmount: typeof import('vue').onBeforeUnmount
const onBeforeUpdate: typeof import('vue').onBeforeUpdate
const onDeactivated: typeof import('vue').onDeactivated
const onErrorCaptured: typeof import('vue').onErrorCaptured
const onMounted: typeof import('vue').onMounted
const onRenderTracked: typeof import('vue').onRenderTracked
const onRenderTriggered: typeof import('vue').onRenderTriggered
const onScopeDispose: typeof import('vue').onScopeDispose
const onServerPrefetch: typeof import('vue').onServerPrefetch
const onUnmounted: typeof import('vue').onUnmounted
const onUpdated: typeof import('vue').onUpdated
const onWatcherCleanup: typeof import('vue').onWatcherCleanup
const provide: typeof import('vue').provide
const reactive: typeof import('vue').reactive
const readonly: typeof import('vue').readonly
const ref: typeof import('vue').ref
const resolveComponent: typeof import('vue').resolveComponent
const setActivePinia: typeof import('pinia').setActivePinia
const setMapStoreSuffix: typeof import('pinia').setMapStoreSuffix
const shallowReactive: typeof import('vue').shallowReactive
const shallowReadonly: typeof import('vue').shallowReadonly
const shallowRef: typeof import('vue').shallowRef
const storeToRefs: typeof import('pinia').storeToRefs
const toRaw: typeof import('vue').toRaw
const toRef: typeof import('vue').toRef
const toRefs: typeof import('vue').toRefs
const toValue: typeof import('vue').toValue
const triggerRef: typeof import('vue').triggerRef
const unref: typeof import('vue').unref
const useAttrs: typeof import('vue').useAttrs
const useCssModule: typeof import('vue').useCssModule
const useCssVars: typeof import('vue').useCssVars
const useId: typeof import('vue').useId
const useLink: typeof import('vue-router').useLink
const useModel: typeof import('vue').useModel
const useRoute: typeof import('vue-router').useRoute
const useRouter: typeof import('vue-router').useRouter
const useSlots: typeof import('vue').useSlots
const useTemplateRef: typeof import('vue').useTemplateRef
const watch: typeof import('vue').watch
const watchEffect: typeof import('vue').watchEffect
const watchPostEffect: typeof import('vue').watchPostEffect
const watchSyncEffect: typeof import('vue').watchSyncEffect
}
// for type re-export
declare global {
// @ts-ignore
export type { Component, Slot, Slots, ComponentPublicInstance, ComputedRef, DirectiveBinding, ExtractDefaultPropTypes, ExtractPropTypes, ExtractPublicPropTypes, InjectionKey, PropType, Ref, ShallowRef, MaybeRef, MaybeRefOrGetter, VNode, WritableComputedRef } from 'vue'
import('vue')
}
-87
View File
@@ -1,87 +0,0 @@
/* eslint-disable */
// @ts-nocheck
// biome-ignore lint: disable
// oxlint-disable
// ------
// Generated by unplugin-vue-components
// Read more: https://github.com/vuejs/core/pull/3399
export {}
/* prettier-ignore */
declare module 'vue' {
export interface GlobalComponents {
AAlert: typeof import('ant-design-vue/es')['Alert']
AAvatar: typeof import('ant-design-vue/es')['Avatar']
ABadge: typeof import('ant-design-vue/es')['Badge']
AButton: typeof import('ant-design-vue/es')['Button']
ACard: typeof import('ant-design-vue/es')['Card']
ACarousel: typeof import('ant-design-vue/es')['Carousel']
ACheckbox: typeof import('ant-design-vue/es')['Checkbox']
ACheckboxGroup: typeof import('ant-design-vue/es')['CheckboxGroup']
ACol: typeof import('ant-design-vue/es')['Col']
ACollapse: typeof import('ant-design-vue/es')['Collapse']
ACollapsePanel: typeof import('ant-design-vue/es')['CollapsePanel']
ADatePicker: typeof import('ant-design-vue/es')['DatePicker']
ADescriptions: typeof import('ant-design-vue/es')['Descriptions']
ADescriptionsItem: typeof import('ant-design-vue/es')['DescriptionsItem']
ADivider: typeof import('ant-design-vue/es')['Divider']
ADropdown: typeof import('ant-design-vue/es')['Dropdown']
AEmpty: typeof import('ant-design-vue/es')['Empty']
AForm: typeof import('ant-design-vue/es')['Form']
AFormItem: typeof import('ant-design-vue/es')['FormItem']
AGrid: typeof import('ant-design-vue/es')['Grid']
AImage: typeof import('ant-design-vue/es')['Image']
AInput: typeof import('ant-design-vue/es')['Input']
AInputNumber: typeof import('ant-design-vue/es')['InputNumber']
AInputPassword: typeof import('ant-design-vue/es')['InputPassword']
AInputSearch: typeof import('ant-design-vue/es')['InputSearch']
ALayout: typeof import('ant-design-vue/es')['Layout']
ALayoutContent: typeof import('ant-design-vue/es')['LayoutContent']
ALayoutHeader: typeof import('ant-design-vue/es')['LayoutHeader']
ALayoutSider: typeof import('ant-design-vue/es')['LayoutSider']
AList: typeof import('ant-design-vue/es')['List']
AListItem: typeof import('ant-design-vue/es')['ListItem']
AListItemMeta: typeof import('ant-design-vue/es')['ListItemMeta']
AMenu: typeof import('ant-design-vue/es')['Menu']
AMenuDivider: typeof import('ant-design-vue/es')['MenuDivider']
AMenuItem: typeof import('ant-design-vue/es')['MenuItem']
AModal: typeof import('ant-design-vue/es')['Modal']
APageHeader: typeof import('ant-design-vue/es')['PageHeader']
APopconfirm: typeof import('ant-design-vue/es')['Popconfirm']
AProgress: typeof import('ant-design-vue/es')['Progress']
ARadio: typeof import('ant-design-vue/es')['Radio']
ARadioButton: typeof import('ant-design-vue/es')['RadioButton']
ARadioGroup: typeof import('ant-design-vue/es')['RadioGroup']
AResult: typeof import('ant-design-vue/es')['Result']
ARow: typeof import('ant-design-vue/es')['Row']
ASegmented: typeof import('ant-design-vue/es')['Segmented']
ASelect: typeof import('ant-design-vue/es')['Select']
ASelectOption: typeof import('ant-design-vue/es')['SelectOption']
ASkeleton: typeof import('ant-design-vue/es')['Skeleton']
ASpace: typeof import('ant-design-vue/es')['Space']
ASpin: typeof import('ant-design-vue/es')['Spin']
AStatistic: typeof import('ant-design-vue/es')['Statistic']
ASwitch: typeof import('ant-design-vue/es')['Switch']
ATable: typeof import('ant-design-vue/es')['Table']
ATabPane: typeof import('ant-design-vue/es')['TabPane']
ATabs: typeof import('ant-design-vue/es')['Tabs']
ATag: typeof import('ant-design-vue/es')['Tag']
ATextarea: typeof import('ant-design-vue/es')['Textarea']
ATimeline: typeof import('ant-design-vue/es')['Timeline']
ATimelineItem: typeof import('ant-design-vue/es')['TimelineItem']
ATooltip: typeof import('ant-design-vue/es')['Tooltip']
ATypographyText: typeof import('ant-design-vue/es')['TypographyText']
AUpload: typeof import('ant-design-vue/es')['Upload']
BottomNav: typeof import('./components/BottomNav.vue')['default']
DraftActions: typeof import('./components/DraftActions.vue')['default']
ElButton: typeof import('element-plus/es')['ElButton']
ElColorPicker: typeof import('element-plus/es')['ElColorPicker']
ElConfigProvider: typeof import('element-plus/es')['ElConfigProvider']
ElIcon: typeof import('element-plus/es')['ElIcon']
HelloWorld: typeof import('./components/HelloWorld.vue')['default']
RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView']
TableEllipsisText: typeof import('./components/TableEllipsisText.vue')['default']
}
}
-187
View File
@@ -1,187 +0,0 @@
<template>
<a-layout class="bottom-nav">
<a-layout-content class="nav-content">
<!-- 首页导航项 -->
<div class="nav-item" :class="{ active: currentRoute === 'home' }" @click="handleNavClick('home')">
<a-badge :count="0" :offset="[0, 0]">
<div class="nav-icon">
<HomeOutlined :style="{ fontSize: '24px' }" />
</div>
</a-badge>
<span class="nav-label">首页</span>
</div>
<!-- 作品导航项 -->
<div class="nav-item" :class="{ active: currentRoute === 'products' }" @click="handleNavClick('products')">
<a-badge :count="0" :offset="[0, 0]">
<div class="nav-icon">
<ShoppingOutlined :style="{ fontSize: '24px' }" />
</div>
</a-badge>
<span class="nav-label">作品</span>
</div>
<!-- 购物车导航项 -->
<div class="nav-item" :class="{ active: currentRoute === 'cart' }" @click="handleNavClick('cart')">
<a-badge :count="cartCount" :offset="[0, 0]">
<div class="nav-icon">
<ShoppingCartOutlined :style="{ fontSize: '24px' }" />
</div>
</a-badge>
<span class="nav-label">购物车</span>
</div>
<!-- 个人中心导航项 -->
<div class="nav-item" :class="{ active: currentRoute === 'profile' }" @click="handleNavClick('profile')">
<a-badge :dot="hasNotification" :offset="[0, 0]">
<div class="nav-icon">
<UserOutlined :style="{ fontSize: '24px' }" />
</div>
</a-badge>
<span class="nav-label">我的</span>
</div>
</a-layout-content>
</a-layout>
</template>
<script setup lang="ts">
import { computed, inject, onMounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { HomeOutlined, ShoppingOutlined, ShoppingCartOutlined, UserOutlined } from '@ant-design/icons-vue'
const router = useRouter()
const route = useRoute()
// 注入全局购物车数量状态
const cartCount = inject('cartCount', ref(0))
// 注入更新购物车数量的方法
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
// 是否有未读通知
const hasNotification = computed(() => true)
// 加载购物车数量
const loadCartCount = async () => {
// 这里我们不需要做任何事情,因为全局状态会自动更新
// 但我们仍然需要这个方法,因为 App.vue 会调用它
}
// 页面加载时获取购物车数量
onMounted(() => {
// 检查当前是否是后台页面,如果是则不加载购物车数据
const isAdminPage = window.location.pathname.startsWith('/admin')
if (!isAdminPage) {
// 调用全局更新方法
updateCartCount()
}
})
// 提供一个方法让其他组件调用更新购物车数量
defineExpose({
loadCartCount
})
// 根据当前路由判断激活的导航项
const currentRoute = computed(() => {
if (!route || !route.path) return 'home'
const path = route.path
if (path === '/') return 'home'
if (path === '/products') return 'products'
if (path === '/product') return 'products'
if (path === '/cart') return 'cart'
if (path === '/profile') return 'profile'
if (path === '/wishlist') return 'profile'
return 'home'
})
// 处理导航点击事件
const handleNavClick = (tab: string) => {
if (tab === 'home') {
router.push('/home')
} else if (tab === 'products') {
router.push('/products')
} else if (tab === 'cart') {
router.push('/cart')
} else if (tab === 'profile') {
router.push('/profile')
}
}
</script>
<style scoped>
.bottom-nav {
position: fixed;
bottom: 0;
left: 0;
right: 0;
width: 100%;
height: 60px;
background: white;
box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.08);
z-index: 1000;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
backface-visibility: hidden;
will-change: transform;
transform: translateZ(0);
transition: none !important;
}
.nav-content {
display: flex;
justify-content: space-around;
align-items: center;
height: 100%;
width: 100%;
max-width: 560px;
margin: 0 auto;
padding: 0 10px;
transition: none !important;
}
.nav-item {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 8px 12px;
cursor: pointer;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
border-radius: 12px;
min-width: 60px;
}
.nav-item:hover {
background: rgba(24, 144, 255, 0.05);
transform: translateY(-2px);
}
.nav-item.active {
color: #1890ff;
}
.nav-item.active .nav-icon {
transform: scale(1.1);
}
.nav-icon {
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 4px;
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.nav-label {
font-size: 11px;
font-weight: 500;
transition: all 0.3s ease;
}
.nav-item.active .nav-label {
font-weight: 600;
}
</style>
-62
View File
@@ -1,62 +0,0 @@
<template>
<div class="draft-actions">
<a-space wrap>
<a-button size="small" @click="$emit('save')" :disabled="disabled">
暂存
</a-button>
<a-button v-if="showClear" size="small" type="link" @click="$emit('clear')" :disabled="disabled">
清除暂存
</a-button>
<span v-if="savedAt" class="draft-saved-at">
上次暂存:{{ formattedSavedAt }}
</span>
<span v-else class="draft-saved-at">
暂存仅保存在当前浏览器中
</span>
</a-space>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
const props = withDefaults(defineProps<{
savedAt?: number | null
disabled?: boolean
showClear?: boolean
}>(), {
savedAt: null,
disabled: false,
showClear: true
})
defineEmits<{
(event: 'save'): void
(event: 'clear'): void
}>()
const formattedSavedAt = computed(() => {
if (!props.savedAt) {
return ''
}
const date = new Date(props.savedAt)
const year = date.getFullYear()
const month = `${date.getMonth() + 1}`.padStart(2, '0')
const day = `${date.getDate()}`.padStart(2, '0')
const hour = `${date.getHours()}`.padStart(2, '0')
const minute = `${date.getMinutes()}`.padStart(2, '0')
return `${year}-${month}-${day} ${hour}:${minute}`
})
</script>
<style scoped>
.draft-actions {
margin-bottom: 12px;
}
.draft-saved-at {
color: #8c8c8c;
font-size: 12px;
line-height: 24px;
}
</style>
-41
View File
@@ -1,41 +0,0 @@
<script setup lang="ts">
import { ref } from 'vue'
defineProps<{ msg: string }>()
const count = ref(0)
</script>
<template>
<h1>{{ msg }}</h1>
<div class="card">
<button type="button" @click="count++">count is {{ count }}</button>
<p>
Edit
<code>components/HelloWorld.vue</code> to test HMR
</p>
</div>
<p>
Check out
<a href="https://vuejs.org/guide/quick-start.html#local" target="_blank"
>create-vue</a
>, the official Vue + Vite starter
</p>
<p>
Learn more about IDE Support for Vue in the
<a
href="https://vuejs.org/guide/scaling-up/tooling.html#ide-support"
target="_blank"
>Vue Docs Scaling up Guide</a
>.
</p>
<p class="read-the-docs">Click on the Vite and Vue logos to learn more</p>
</template>
<style scoped>
.read-the-docs {
color: #888;
}
</style>
@@ -1,64 +0,0 @@
<template>
<span v-if="!displayText" class="empty-text">{{ emptyText }}</span>
<a-tooltip v-else :title="displayText" placement="topLeft">
<div class="ellipsis-text" :class="lineClass">
{{ displayText }}
</div>
</a-tooltip>
</template>
<script setup lang="ts">
import { computed } from 'vue'
const props = withDefaults(defineProps<{
text?: string | number | null
lines?: 1 | 2 | 3
emptyText?: string
}>(), {
lines: 1,
emptyText: '--'
})
const displayText = computed(() => {
if (props.text === undefined || props.text === null) {
return ''
}
const value = String(props.text).trim()
return value
})
const lineClass = computed(() => {
return props.lines > 1 ? `lines-${props.lines}` : ''
})
</script>
<style scoped>
.ellipsis-text {
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
word-break: break-all;
line-height: 1.5;
}
.lines-2,
.lines-3 {
display: -webkit-box;
-webkit-box-orient: vertical;
white-space: normal;
word-break: break-word;
}
.lines-2 {
-webkit-line-clamp: 2;
}
.lines-3 {
-webkit-line-clamp: 3;
}
.empty-text {
color: #bfbfbf;
}
</style>
-46
View File
@@ -1,46 +0,0 @@
import zhCN from 'ant-design-vue/es/locale/zh_CN'
const baseCalendar = (zhCN.Calendar || { lang: {} }) as any
const baseDatePicker = (zhCN.DatePicker || { lang: {}, timePickerLocale: {} }) as any
const baseTimePicker = (zhCN.TimePicker || {}) as any
const antdLocale: any = {
...zhCN,
Modal: {
...zhCN.Modal,
okText: '确认',
cancelText: zhCN.Modal?.cancelText || '取消',
justOkText: zhCN.Modal?.justOkText || '知道了'
},
Popconfirm: {
...zhCN.Popconfirm,
okText: '确认',
cancelText: zhCN.Popconfirm?.cancelText || '取消'
},
Calendar: {
...baseCalendar,
lang: {
...baseCalendar.lang,
ok: '确认',
now: '现在时间'
}
},
DatePicker: {
...baseDatePicker,
lang: {
...baseDatePicker.lang,
ok: '确认',
now: '现在时间'
},
timePickerLocale: {
...baseDatePicker.timePickerLocale,
now: '现在时间'
}
},
TimePicker: {
...baseTimePicker,
now: '现在时间'
}
}
export default antdLocale
-11
View File
@@ -1,11 +0,0 @@
// API配置文件
// 提取域名和端口,方便后续修改
export const API_CONFIG = {
domain: 'http://127.0.0.1',
port: '80',
basePath: '/api',
adminBasePath: '/admin/api'
}
export const API_BASE_URL = `${API_CONFIG.domain}:${API_CONFIG.port}${API_CONFIG.basePath}`
export const ADMIN_API_BASE_URL = `${API_CONFIG.domain}:${API_CONFIG.port}${API_CONFIG.adminBasePath}`
-3
View File
@@ -1,3 +0,0 @@
export const DEFAULT_AVATAR = 'https://api.dicebear.com/7.x/avataaars/svg?seed=default'
export const DEFAULT_PRODUCT_IMAGE = 'https://via.placeholder.com/200x200?text=Product'
export const DEFAULT_SHOP_IMAGE = 'https://via.placeholder.com/200x200?text=Shop'
-18
View File
@@ -1,18 +0,0 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/reset.css'
import App from './App.vue'
import router from './router'
const app = createApp(App)
const pinia = createPinia()
app.use(pinia)
app.use(router)
app.use(ElementPlus)
app.use(Antd)
app.mount('#app')
-294
View File
@@ -1,294 +0,0 @@
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'auth',
component: () => import('../views/AuthView.vue'),
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
},
{
path: '/home',
name: 'home',
component: () => import('../views/HomeView.vue'),
meta: { requiresAuth: false, isAdmin: false }
},
{
path: '/products',
name: 'products',
component: () => import('../views/ProductListView.vue'),
meta: { requiresAuth: false, isAdmin: false }
},
{
path: '/product/:id',
name: 'product-detail',
component: () => import('../views/ProductDetailView.vue'),
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
},
{
path: '/cart',
name: 'cart',
component: () => import('../views/CartView.vue'),
meta: { requiresAuth: true, isAdmin: false }
},
{
path: '/profile',
name: 'profile',
component: () => import('../views/ProfileView.vue'),
meta: { requiresAuth: true, isAdmin: false }
},
{
path: '/shop/:id',
name: 'shop-detail',
component: () => import('../views/ShopDetailView.vue'),
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
},
{
path: '/wishlist',
name: 'wishlist',
component: () => import('../views/WishlistView.vue'),
meta: { requiresAuth: true, isAdmin: false }
},
{
path: '/orders',
name: 'orders',
component: () => import('../views/OrderView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/artist-orders',
name: 'artist-orders',
component: () => import('../views/ArtistOrderView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false, permissionCode: 'order:view' }
},
{
path: '/settings',
name: 'settings',
component: () => import('../views/SettingsView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/settings/account',
name: 'account-settings',
component: () => import('../views/AccountSettingsView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/settings/password',
name: 'password-settings',
component: () => import('../views/PasswordSettingsView.vue'),
meta: { requiresAuth: true, hideNav: true, isAdmin: false }
},
{
path: '/coupons',
name: 'coupons',
component: () => import('../views/CouponView.vue'),
meta: { requiresAuth: true, isAdmin: false ,hideNav: true}
},
{
path: '/admin/login',
name: 'admin-login',
component: () => import('../views/admin/AdminLoginView.vue'),
meta: { requiresAuth: false, isAdmin: true, hideNav: true }
},
{
path: '/admin',
component: () => import('../views/admin/AdminLayout.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true },
children: [
{
path: '',
name: 'admin',
component: () => import('../views/admin/HomeView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true }
},
{
path: 'dashboard',
name: 'admin-dashboard',
component: () => import('../views/admin/DashboardView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'dashboard:view' }
},
{
path: 'users',
name: 'admin-users',
component: () => import('../views/admin/UsersView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'user:view' }
},
{
path: 'products',
name: 'admin-products',
component: () => import('../views/admin/ProductsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'product:view' }
},
{
path: 'coupons',
name: 'admin-coupons',
component: () => import('../views/admin/CouponsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'coupon:view' }
},
{
path: 'shops',
name: 'admin-shops',
component: () => import('../views/admin/ShopsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'shop:view' }
},
{
path: 'permissions',
name: 'admin-permissions',
component: () => import('../views/admin/PermissionsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'permission:view' }
},
{
path: 'orders',
name: 'admin-orders',
component: () => import('../views/admin/OrdersView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'order:view' }
},
{
path: 'tags',
name: 'admin-tags',
component: () => import('../views/admin/TagsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'tag:view' }
},
{
path: 'nail-artists',
name: 'admin-nail-artists',
component: () => import('../views/admin/NailArtistsView.vue'),
meta: { requiresAuth: true, isAdmin: true, hideNav: true, permissionCode: 'nail_artist:view' }
}
]
},
{
path: '/:pathMatch(.*)*',
name: 'not-found',
component: () => import('../views/NotFoundView.vue'),
meta: { requiresAuth: false, hideNav: true, isAdmin: false }
}
]
})
router.beforeEach((to, _from, next) => {
const isAdminRoute = to.meta.isAdmin as boolean
const requiresAuth = to.meta.requiresAuth as boolean
if (isAdminRoute) {
const adminToken = localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken')
const adminUserInfoStr = localStorage.getItem('adminUserInfo')
let adminUserInfo: any = null
let isBootstrapAdmin = false
if (adminUserInfoStr) {
try {
adminUserInfo = JSON.parse(adminUserInfoStr)
isBootstrapAdmin = adminUserInfo?.type === 4 && !adminUserInfo?.shopId
} catch (parseError) {
console.error('Failed to parse admin user info in guard:', parseError)
}
}
if (requiresAuth && (!adminToken || !adminUserInfoStr)) {
// 清除可能存在的过期信息
localStorage.removeItem('adminAccessToken')
localStorage.removeItem('adminRefreshToken')
localStorage.removeItem('adminUserInfo')
localStorage.removeItem('userPermissions')
sessionStorage.removeItem('adminAccessToken')
next('/admin/login')
} else if (to.path === '/admin/login' && adminToken && adminUserInfoStr) {
next(isBootstrapAdmin ? '/admin/shops' : '/admin/dashboard')
} else {
// 检查用户权限
const permissionCode = to.meta.permissionCode as string
if (permissionCode) {
const fallbackAdminPath = isBootstrapAdmin ? '/admin/shops' : '/admin'
// 获取用户信息
try {
const adminUserInfoStr = localStorage.getItem('adminUserInfo')
if (adminUserInfoStr) {
try {
JSON.parse(adminUserInfoStr)
// 获取用户权限
const userPermissionsStr = localStorage.getItem('userPermissions')
if (userPermissionsStr) {
try {
const userPermissions = JSON.parse(userPermissionsStr)
// 检查用户是否拥有该权限
if (userPermissions.includes(permissionCode)) {
next()
} else {
next(fallbackAdminPath)
}
} catch (parseError) {
console.error('Failed to parse user permissions:', parseError)
// 解析失败,允许访问首页临时,直到权限加载完成
if (to.path === '/admin') {
next()
} else {
next(fallbackAdminPath)
}
}
} else {
// 没有权限信息,允许访问首页临时,直到权限加载完成
if (to.path === '/admin') {
next()
} else {
next(fallbackAdminPath)
}
}
} catch (parseError) {
console.error('Failed to parse user info:', parseError)
// 解析失败,重定向到登录页
localStorage.removeItem('adminAccessToken')
localStorage.removeItem('adminRefreshToken')
localStorage.removeItem('adminUserInfo')
localStorage.removeItem('userPermissions')
sessionStorage.removeItem('adminAccessToken')
next('/admin/login')
}
} else {
// 没有用户信息,重定向到登录页
next('/admin/login')
}
} catch (error) {
console.error('解析用户信息失败:', error)
// 解析失败,重定向到登录页
localStorage.removeItem('adminAccessToken')
localStorage.removeItem('adminRefreshToken')
localStorage.removeItem('adminUserInfo')
localStorage.removeItem('userPermissions')
sessionStorage.removeItem('adminAccessToken')
next('/admin/login')
}
} else {
// 没有权限要求,直接通过
next()
}
}
} else {
const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
if (requiresAuth && !token) {
next('/')
} else if (to.path === '/' && token) {
next('/home')
} else {
// 对于需要认证的页面,验证token的有效性
if (requiresAuth && token) {
// 检查userInfo是否存在
const userInfo = localStorage.getItem('userInfo')
if (!userInfo) {
localStorage.removeItem('accessToken')
localStorage.removeItem('refreshToken')
sessionStorage.removeItem('accessToken')
next('/')
return
}
}
next()
}
}
})
export default router
-40
View File
@@ -1,40 +0,0 @@
:root {
--primary-color: #ff6600; /* 根据设计稿中的橙色色值调整 */
--bg-color: #ffffff;
--secondary-bg-color: #f5f5f5;
--text-primary: #333333;
--text-secondary: #999999;
--border-radius-base: 10px;
--border-radius-large: 30px;
--frontend-page-max-width: 1280px;
--frontend-content-max-width: 1120px;
--admin-content-max-width: 1440px;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: var(--secondary-bg-color);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
color: var(--text-primary);
}
.mobile-container {
width: 100%;
max-width: 100%;
margin: 0 auto;
min-height: 100vh;
background-color: var(--bg-color);
position: relative;
overflow-x: hidden;
}
@media (min-width: 992px) {
.mobile-container {
max-width: var(--frontend-page-max-width);
}
}
-12
View File
@@ -1,12 +0,0 @@
.bottom-nav {
position: fixed;
bottom: 0;
width: 100%;
height: 60px;
background: white;
display: flex;
justify-content: space-around;
align-items: center;
box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
z-index: 1000;
}
-6
View File
@@ -1,6 +0,0 @@
export const ACCOUNT_REGEX = /^[A-Za-z0-9]+$/
const ACCOUNT_SANITIZE_REGEX = /[^A-Za-z0-9]/g
export const ACCOUNT_RULE_MESSAGE = '账号只能包含字母和数字'
export const sanitizeAccountInput = (value: string) => (value || '').replace(ACCOUNT_SANITIZE_REGEX, '')
-161
View File
@@ -1,161 +0,0 @@
import type { AxiosProgressEvent } from 'axios'
export interface ChunkUploadSession {
uploadId: string
chunkSize: number
totalChunks: number
uploadedChunks: number[]
}
export interface ChunkUploadInitRequest {
fileName: string
fileSize: number
contentType: string
fileFingerprint: string
scene: string
}
export interface ChunkUploadApi<TResponse> {
initUpload: (payload: ChunkUploadInitRequest) => Promise<ChunkUploadSession>
uploadChunk: (
payload: { uploadId: string; chunkIndex: number; totalChunks: number; chunk: Blob },
config?: { signal?: AbortSignal; onUploadProgress?: (event: AxiosProgressEvent) => void }
) => Promise<unknown>
completeUpload: (uploadId: string) => Promise<TResponse>
cancelUpload?: (uploadId: string) => Promise<unknown>
}
export interface ChunkUploadOptions<TResponse> {
file: File
scene: string
api: ChunkUploadApi<TResponse>
preprocessFile?: (file: File) => Promise<File>
onProgress?: (percent: number) => void
}
export interface ChunkUploadResult<TResponse> {
response: TResponse
uploadId: string
processedFile: File
}
export interface ChunkUploadTask<TResponse> {
promise: Promise<ChunkUploadResult<TResponse>>
cancel: () => void
getUploadId: () => string
}
const computeFileFingerprint = async (file: File) => {
const fingerprintSeed = `${file.name}|${file.size}|${file.lastModified}|${file.type}`
if (!window.crypto?.subtle) {
return btoa(unescape(encodeURIComponent(fingerprintSeed)))
}
const buffer = new TextEncoder().encode(fingerprintSeed)
const hashBuffer = await window.crypto.subtle.digest('SHA-256', buffer)
const hashArray = Array.from(new Uint8Array(hashBuffer))
return hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('')
}
const getChunkSizeByIndex = (fileSize: number, chunkSize: number, chunkIndex: number) => {
const start = chunkIndex * chunkSize
const end = Math.min(start + chunkSize, fileSize)
return Math.max(end - start, 0)
}
const calculateUploadedBytes = (fileSize: number, chunkSize: number, uploadedChunks: number[]) => {
return uploadedChunks.reduce((total, chunkIndex) => total + getChunkSizeByIndex(fileSize, chunkSize, chunkIndex), 0)
}
export const createChunkUploadTask = <TResponse>(options: ChunkUploadOptions<TResponse>): ChunkUploadTask<TResponse> => {
const abortController = new AbortController()
let uploadId = ''
let cancelled = false
const cleanupCancelledSession = async () => {
if (uploadId && options.api.cancelUpload) {
await options.api.cancelUpload(uploadId).catch(() => undefined)
}
}
const promise = (async () => {
const processedFile = options.preprocessFile ? await options.preprocessFile(options.file) : options.file
const fileFingerprint = await computeFileFingerprint(processedFile)
const session = await options.api.initUpload({
fileName: processedFile.name,
fileSize: processedFile.size,
contentType: processedFile.type || 'application/octet-stream',
fileFingerprint,
scene: options.scene
})
uploadId = session.uploadId
if (cancelled) {
await cleanupCancelledSession()
throw new Error('上传已取消')
}
const uploadedChunkSet = new Set(session.uploadedChunks || [])
let uploadedBytes = calculateUploadedBytes(processedFile.size, session.chunkSize, Array.from(uploadedChunkSet))
options.onProgress?.(Math.min((uploadedBytes / Math.max(processedFile.size, 1)) * 100, 100))
for (let chunkIndex = 0; chunkIndex < session.totalChunks; chunkIndex++) {
if (cancelled) {
await cleanupCancelledSession()
throw new Error('上传已取消')
}
if (uploadedChunkSet.has(chunkIndex)) {
continue
}
const start = chunkIndex * session.chunkSize
const end = Math.min(start + session.chunkSize, processedFile.size)
const chunk = processedFile.slice(start, end)
const chunkBytes = end - start
await options.api.uploadChunk(
{
uploadId: session.uploadId,
chunkIndex,
totalChunks: session.totalChunks,
chunk
},
{
signal: abortController.signal,
onUploadProgress: (event) => {
const loaded = Math.min(event.loaded || 0, chunkBytes)
const percent = ((uploadedBytes + loaded) / Math.max(processedFile.size, 1)) * 100
options.onProgress?.(Math.min(percent, 99.9))
}
}
)
uploadedChunkSet.add(chunkIndex)
uploadedBytes += chunkBytes
options.onProgress?.(Math.min((uploadedBytes / Math.max(processedFile.size, 1)) * 100, 99.9))
}
if (cancelled) {
await cleanupCancelledSession()
throw new Error('上传已取消')
}
const response = await options.api.completeUpload(session.uploadId)
options.onProgress?.(100)
return {
response,
uploadId: session.uploadId,
processedFile
}
})()
return {
promise,
cancel: () => {
cancelled = true
abortController.abort()
if (uploadId && options.api.cancelUpload) {
void options.api.cancelUpload(uploadId).catch(() => undefined)
}
},
getUploadId: () => uploadId
}
}
-42
View File
@@ -1,42 +0,0 @@
export type DraftStorageMode = 'local' | 'session'
export interface DraftRecord<T> {
savedAt: number
payload: T
}
const getStorage = (mode: DraftStorageMode) => (mode === 'session' ? window.sessionStorage : window.localStorage)
export const buildDraftStorageKey = (...parts: Array<string | number | undefined | null>) => {
const normalizedParts = parts
.filter((part): part is string | number => part !== undefined && part !== null && String(part).trim().length > 0)
.map(part => String(part).trim())
return `yuminail:draft:${normalizedParts.join(':')}`
}
export const saveDraftRecord = <T>(key: string, payload: T, mode: DraftStorageMode = 'local') => {
const record: DraftRecord<T> = {
savedAt: Date.now(),
payload
}
getStorage(mode).setItem(key, JSON.stringify(record))
return record
}
export const loadDraftRecord = <T>(key: string, mode: DraftStorageMode = 'local') => {
const rawValue = getStorage(mode).getItem(key)
if (!rawValue) {
return null
}
try {
return JSON.parse(rawValue) as DraftRecord<T>
} catch {
getStorage(mode).removeItem(key)
return null
}
}
export const clearDraftRecord = (key: string, mode: DraftStorageMode = 'local') => {
getStorage(mode).removeItem(key)
}
-22
View File
@@ -1,22 +0,0 @@
export type IdType = string | number
export const isEmptyId = (value: unknown): value is undefined | null | '' => {
return value === undefined || value === null || `${value}`.trim() === ''
}
export const toIdString = (value: IdType) => String(value)
// 前端统一把雪花 ID 视为字符串语义处理,避免任何 Number 转换带来的精度污染。
export const toOptionalIdString = (value: unknown) => {
if (isEmptyId(value)) {
return undefined
}
return String(value).trim()
}
// 比较 ID 时统一做字符串归一化,兼容接口返回 string / number 两种情况。
export const sameId = (left: unknown, right: unknown) => {
const leftId = toOptionalIdString(left)
const rightId = toOptionalIdString(right)
return leftId !== undefined && leftId === rightId
}
-196
View File
@@ -1,196 +0,0 @@
const DEFAULT_MAX_IMAGE_SIZE = 5 * 1024 * 1024
const AUTO_COMPRESS_TYPES = new Set(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])
export interface ImageCompressionResult {
file: File
originalSize: number
finalSize: number
compressed: boolean
converted: boolean
skippedReason?: string
}
const QUALITY_STEPS = [0.92, 0.84, 0.76, 0.68, 0.6, 0.52]
const SCALE_STEPS = [1, 0.9, 0.8, 0.7, 0.6, 0.5]
const loadImageElement = (file: File) => {
return new Promise<HTMLImageElement>((resolve, reject) => {
const image = new Image()
const objectUrl = URL.createObjectURL(file)
image.onload = () => {
URL.revokeObjectURL(objectUrl)
resolve(image)
}
image.onerror = () => {
URL.revokeObjectURL(objectUrl)
reject(new Error('图片读取失败'))
}
image.src = objectUrl
})
}
const canvasToBlob = (canvas: HTMLCanvasElement, type: string, quality?: number) => {
return new Promise<Blob>((resolve, reject) => {
canvas.toBlob(
(blob) => {
if (!blob) {
reject(new Error('图片压缩失败'))
return
}
resolve(blob)
},
type,
quality
)
})
}
const getOutputExtension = (type: string) => {
if (type === 'image/png') {
return '.png'
}
if (type === 'image/webp') {
return '.webp'
}
return '.jpg'
}
const buildOutputName = (fileName: string, type: string) => {
const extension = getOutputExtension(type)
const dotIndex = fileName.lastIndexOf('.')
const baseName = dotIndex > -1 ? fileName.slice(0, dotIndex) : fileName
return `${baseName}${extension}`
}
const drawImageToCanvas = (image: HTMLImageElement, width: number, height: number, mimeType: string) => {
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
const context = canvas.getContext('2d')
if (!context) {
throw new Error('无法初始化图片压缩画布')
}
if (mimeType !== 'image/png') {
context.fillStyle = '#ffffff'
context.fillRect(0, 0, width, height)
}
context.drawImage(image, 0, 0, width, height)
return canvas
}
const toCompressedFile = (blob: Blob, sourceFile: File, mimeType: string) => {
return new File([blob], buildOutputName(sourceFile.name, mimeType), {
type: mimeType,
lastModified: sourceFile.lastModified
})
}
const getPreferredMimeTypes = (file: File) => {
if (file.type === 'image/png') {
return ['image/png', 'image/jpeg']
}
if (file.type === 'image/webp') {
return ['image/webp', 'image/jpeg']
}
return ['image/jpeg']
}
export const formatFileSize = (bytes: number) => {
if (bytes >= 1024 * 1024) {
return `${(bytes / 1024 / 1024).toFixed(2)}MB`
}
return `${(bytes / 1024).toFixed(0)}KB`
}
export const compressImageIfNeeded = async (
file: File,
maxSize = DEFAULT_MAX_IMAGE_SIZE
): Promise<ImageCompressionResult> => {
if (!file.type.startsWith('image/')) {
return {
file,
originalSize: file.size,
finalSize: file.size,
compressed: false,
converted: false,
skippedReason: '仅支持图片文件上传'
}
}
if (file.size <= maxSize) {
return {
file,
originalSize: file.size,
finalSize: file.size,
compressed: false,
converted: false
}
}
if (!AUTO_COMPRESS_TYPES.has(file.type)) {
return {
file,
originalSize: file.size,
finalSize: file.size,
compressed: false,
converted: false,
skippedReason: '当前图片格式暂不支持自动压缩,请手动处理后重试'
}
}
const image = await loadImageElement(file)
const preferredMimeTypes = getPreferredMimeTypes(file)
let bestBlob: Blob | null = null
let bestMimeType = file.type
for (const scale of SCALE_STEPS) {
const width = Math.max(1, Math.round(image.naturalWidth * scale))
const height = Math.max(1, Math.round(image.naturalHeight * scale))
for (const mimeType of preferredMimeTypes) {
const canvas = drawImageToCanvas(image, width, height, mimeType)
const qualitySteps = mimeType === 'image/png' ? [undefined] : QUALITY_STEPS
for (const quality of qualitySteps) {
const blob = await canvasToBlob(canvas, mimeType, quality)
if (!bestBlob || blob.size < bestBlob.size) {
bestBlob = blob
bestMimeType = mimeType
}
if (blob.size <= maxSize) {
const compressedFile = toCompressedFile(blob, file, mimeType)
return {
file: compressedFile,
originalSize: file.size,
finalSize: blob.size,
compressed: true,
converted: mimeType !== file.type
}
}
}
}
}
if (!bestBlob) {
throw new Error('图片压缩失败')
}
const compressedFile = toCompressedFile(bestBlob, file, bestMimeType)
return {
file: compressedFile,
originalSize: file.size,
finalSize: bestBlob.size,
compressed: true,
converted: bestMimeType !== file.type
}
}
export const MAX_IMAGE_UPLOAD_SIZE = DEFAULT_MAX_IMAGE_SIZE
-50
View File
@@ -1,50 +0,0 @@
import { permissionApi } from '@/api/permission'
import { ref, computed } from 'vue'
const userPermissions = ref<string[]>([])
const loadingPermissions = ref(false)
export const usePermission = () => {
const hasPermission = (permissionCode: string) => {
return userPermissions.value.includes(permissionCode)
}
const hasAnyPermission = (permissionCodes: string[]) => {
return permissionCodes.some(code => userPermissions.value.includes(code))
}
const hasAllPermissions = (permissionCodes: string[]) => {
return permissionCodes.every(code => userPermissions.value.includes(code))
}
const loadUserPermissions = async () => {
loadingPermissions.value = true
try {
const permissions = await permissionApi.getUserPermissions()
userPermissions.value = permissions && Array.isArray(permissions) ? permissions.map(p => p.permissionCode) : []
// 存储权限到本地存储,供路由守卫使用
localStorage.setItem('userPermissions', JSON.stringify(userPermissions.value))
} catch (error) {
console.error('加载用户权限失败:', error)
userPermissions.value = []
localStorage.setItem('userPermissions', JSON.stringify([]))
} finally {
loadingPermissions.value = false
}
}
const clearPermissions = () => {
userPermissions.value = []
localStorage.removeItem('userPermissions')
}
return {
userPermissions: computed(() => userPermissions.value),
loadingPermissions: computed(() => loadingPermissions.value),
hasPermission,
hasAnyPermission,
hasAllPermissions,
loadUserPermissions,
clearPermissions
}
}
-732
View File
@@ -1,732 +0,0 @@
<template>
<div class="mobile-container">
<!-- 头部区域 -->
<header class="header">
<a-button class="back-btn" type="text" @click="handleBackClick">
<LeftOutlined :style="{ fontSize: '20px' }" />
</a-button>
<h1>账号设置</h1>
<div class="empty"></div>
</header>
<!-- 账号设置内容 -->
<div class="account-settings">
<!-- 账号设置选项 -->
<a-card :bordered="false" class="settings-card">
<a-list :data-source="accountSettings" :split="false">
<template #renderItem="{ item }">
<a-list-item class="setting-item" @click="handleSettingClick(item.key)">
<template #actions>
<RightOutlined />
</template>
<a-list-item-meta>
<template #avatar>
<div class="setting-icon" :style="{ backgroundColor: item.bgColor }">
<component :is="item.icon" />
</div>
</template>
<template #title>
<span>{{ item.title }}</span>
</template>
<template #description v-if="item.desc">
<span>{{ item.desc }}</span>
</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
</a-card>
</div>
<!-- 绑定手机号弹窗 -->
<a-modal
v-model:visible="bindPhoneModalVisible"
title="绑定手机号"
@ok="handleBindPhoneSubmit"
@cancel="handleBindPhoneCancel"
:confirmLoading="bindPhoneLoading"
>
<DraftActions
:saved-at="bindPhoneDraftSavedAt"
@save="handleSaveBindPhoneDraft"
@clear="handleClearBindPhoneDraft"
/>
<a-form layout="vertical">
<a-form-item label="手机号" name="phone">
<a-input
v-model:value="bindPhoneForm.phone"
placeholder="请输入手机号"
:disabled="!!userInfo.phone"
/>
</a-form-item>
<a-form-item label="验证码" name="verificationCode">
<a-input
v-model:value="bindPhoneForm.verificationCode"
placeholder="请输入验证码"
>
<template #suffix>
<a-button
type="link"
:disabled="countdown > 0 || !bindPhoneForm.phone"
@click="handleSendVerificationCode"
>
{{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
</a-button>
</template>
</a-input>
</a-form-item>
</a-form>
</a-modal>
<!-- 修改手机号弹窗 -->
<a-modal
v-model:visible="changePhoneModalVisible"
title="修改手机号"
@ok="handleChangePhoneSubmit"
@cancel="handleChangePhoneCancel"
:confirmLoading="changePhoneLoading"
>
<DraftActions
:saved-at="changePhoneDraftSavedAt"
@save="handleSaveChangePhoneDraft"
@clear="handleClearChangePhoneDraft"
/>
<a-form layout="vertical">
<a-form-item label="旧手机号">
<a-input :value="userInfo.phone" disabled />
</a-form-item>
<a-form-item label="新手机号" name="newPhone">
<a-input
v-model:value="changePhoneForm.newPhone"
placeholder="请输入新手机号"
/>
</a-form-item>
<a-form-item label="验证码" name="verificationCode">
<a-input
v-model:value="changePhoneForm.verificationCode"
placeholder="请输入验证码"
>
<template #suffix>
<a-button
type="link"
:disabled="countdown > 0 || !changePhoneForm.newPhone"
@click="handleSendChangePhoneVerificationCode"
>
{{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
</a-button>
</template>
</a-input>
</a-form-item>
</a-form>
</a-modal>
<!-- 修改密码弹窗 -->
<a-modal
v-model:visible="changePasswordModalVisible"
title="修改密码"
@ok="handleChangePasswordSubmit"
@cancel="handleChangePasswordCancel"
:confirmLoading="changePasswordLoading"
>
<DraftActions
:saved-at="changePasswordDraftSavedAt"
@save="handleSaveChangePasswordDraft"
@clear="handleClearChangePasswordDraft"
/>
<a-form layout="vertical">
<a-form-item label="手机号">
<a-input :value="userInfo.phone" disabled />
</a-form-item>
<a-form-item label="验证码" name="verificationCode">
<a-input
v-model:value="changePasswordForm.verificationCode"
placeholder="请输入验证码"
>
<template #suffix>
<a-button
type="link"
:disabled="countdown > 0"
@click="handleSendChangePasswordVerificationCode"
>
{{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
</a-button>
</template>
</a-input>
</a-form-item>
<a-form-item label="新密码" name="password">
<a-input-password
v-model:value="changePasswordForm.password"
placeholder="请输入新密码"
/>
<div class="password-tip">
密码长度至少8位,包含字母和数字
</div>
</a-form-item>
<a-form-item label="确认密码" name="confirmPassword">
<a-input-password
v-model:value="changePasswordForm.confirmPassword"
placeholder="请再次输入新密码"
/>
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined, RightOutlined, LockOutlined, PhoneOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import DraftActions from '@/components/DraftActions.vue'
import { userApi } from '@/api/user'
import type { UserVO } from '@/api/user'
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
const router = useRouter()
// 用户信息
const userInfo = ref<UserVO>({
id: 0,
nickname: '',
account: '',
avatar: '',
type: 0,
status: 0,
createTime: '',
updateTime: ''
})
// 状态标识
const hasPassword = ref(false)
const hasPhone = ref(false)
// 绑定手机号表单
const bindPhoneModalVisible = ref(false)
const bindPhoneLoading = ref(false)
const bindPhoneDraftSavedAt = ref<number | null>(null)
const bindPhoneForm = reactive({
phone: '',
verificationCode: ''
})
// 修改手机号表单
const changePhoneModalVisible = ref(false)
const changePhoneLoading = ref(false)
const changePhoneDraftSavedAt = ref<number | null>(null)
const changePhoneForm = reactive({
newPhone: '',
verificationCode: ''
})
// 修改密码表单
const changePasswordModalVisible = ref(false)
const changePasswordLoading = ref(false)
const changePasswordDraftSavedAt = ref<number | null>(null)
const changePasswordForm = reactive({
verificationCode: '',
password: '',
confirmPassword: ''
})
const restoreSessionDraft = <T extends Record<string, any>>(key: string, target: T, savedAtRef: typeof bindPhoneDraftSavedAt) => {
const draft = loadDraftRecord<T>(key, 'session')
if (!draft) {
savedAtRef.value = null
return
}
Object.assign(target, draft.payload)
savedAtRef.value = draft.savedAt
message.success('已恢复暂存内容')
}
const saveSessionDraft = <T>(key: string, payload: T, savedAtRef: typeof bindPhoneDraftSavedAt, successMessage = '已暂存到当前会话') => {
const draft = saveDraftRecord(key, payload, 'session')
savedAtRef.value = draft.savedAt
message.success(successMessage)
}
const clearSessionDraft = (key: string, savedAtRef: typeof bindPhoneDraftSavedAt, showMessage = true) => {
clearDraftRecord(key, 'session')
savedAtRef.value = null
if (showMessage) {
message.success('已清除暂存')
}
}
const bindPhoneDraftKey = buildDraftStorageKey('account-settings', 'bind-phone')
const changePhoneDraftKey = buildDraftStorageKey('account-settings', 'change-phone')
const changePasswordDraftKey = buildDraftStorageKey('account-settings', 'change-password')
const handleSaveBindPhoneDraft = () => {
saveSessionDraft(bindPhoneDraftKey, { ...bindPhoneForm }, bindPhoneDraftSavedAt)
}
const handleClearBindPhoneDraft = (showMessage = true) => {
clearSessionDraft(bindPhoneDraftKey, bindPhoneDraftSavedAt, showMessage)
}
const handleSaveChangePhoneDraft = () => {
saveSessionDraft(changePhoneDraftKey, { ...changePhoneForm }, changePhoneDraftSavedAt)
}
const handleClearChangePhoneDraft = (showMessage = true) => {
clearSessionDraft(changePhoneDraftKey, changePhoneDraftSavedAt, showMessage)
}
const handleSaveChangePasswordDraft = () => {
saveSessionDraft(changePasswordDraftKey, { ...changePasswordForm }, changePasswordDraftSavedAt)
}
const handleClearChangePasswordDraft = (showMessage = true) => {
clearSessionDraft(changePasswordDraftKey, changePasswordDraftSavedAt, showMessage)
}
// 倒计时
const countdown = ref(0)
// 账号设置选项
const accountSettings = ref([
{
key: 'changePhone',
title: '修改手机号',
icon: PhoneOutlined,
bgColor: '#e6f7ff'
},
{
key: 'changePassword',
title: '修改密码',
icon: LockOutlined,
bgColor: '#f6ffed'
},
{
key: 'deactivateAccount',
title: '注销账号',
icon: LockOutlined,
bgColor: '#fff1f0'
}
])
// 根据用户状态动态更新账号设置选项
const updateAccountSettings = () => {
const settings = []
// 手机号相关
if (!hasPhone.value) {
settings.push({
key: 'bindPhone',
title: '绑定手机号',
icon: PhoneOutlined,
bgColor: '#e6f7ff'
})
} else {
settings.push({
key: 'changePhone',
title: '修改手机号',
icon: PhoneOutlined,
bgColor: '#e6f7ff'
})
}
// 密码相关
if (!hasPassword.value) {
settings.push({
key: 'setPassword',
title: '设置密码',
icon: LockOutlined,
bgColor: '#fff7e6'
})
} else {
settings.push({
key: 'changePassword',
title: '修改密码',
icon: LockOutlined,
bgColor: '#f6ffed'
})
}
// 注销账号
settings.push({
key: 'deactivateAccount',
title: '注销账号',
icon: LockOutlined,
bgColor: '#fff1f0'
})
accountSettings.value = settings
}
// 获取用户信息
const fetchUserInfo = async () => {
try {
const response = await userApi.getUserInfo() as any
userInfo.value = response
// 检查是否绑定手机号
hasPhone.value = !!userInfo.value.phone
// 检查是否设置密码(通过localStorage中的标识)
hasPassword.value = localStorage.getItem('needSetPassword') !== 'true'
// 更新账号设置选项
updateAccountSettings()
} catch (error) {
console.error('获取用户信息失败:', error)
message.error('获取用户信息失败')
}
}
// 处理返回
const handleBackClick = () => {
router.back()
}
// 处理设置项点击
const handleSettingClick = (key: string) => {
switch (key) {
case 'bindPhone':
restoreSessionDraft(bindPhoneDraftKey, bindPhoneForm, bindPhoneDraftSavedAt)
bindPhoneModalVisible.value = true
break
case 'changePhone':
restoreSessionDraft(changePhoneDraftKey, changePhoneForm, changePhoneDraftSavedAt)
changePhoneModalVisible.value = true
break
case 'setPassword':
handleSetPassword()
break
case 'changePassword':
restoreSessionDraft(changePasswordDraftKey, changePasswordForm, changePasswordDraftSavedAt)
changePasswordModalVisible.value = true
break
case 'deactivateAccount':
handleDeactivateAccount()
break
default:
break
}
}
// 处理设置密码
const handleSetPassword = () => {
router.push('/settings/password')
}
// 发送绑定手机号验证码
const handleSendVerificationCode = async () => {
if (!bindPhoneForm.phone) {
message.error('请输入手机号')
return
}
const phoneRegex = /^1[3-9]\d{9}$/
if (!phoneRegex.test(bindPhoneForm.phone)) {
message.error('手机号格式不正确')
return
}
try {
await userApi.sendVerificationCode({ phone: bindPhoneForm.phone })
message.success('验证码发送成功')
startCountdown()
} catch (error) {
console.error('发送验证码失败:', error)
message.error('发送验证码失败')
}
}
// 发送修改手机号验证码
const handleSendChangePhoneVerificationCode = async () => {
if (!changePhoneForm.newPhone) {
message.error('请输入新手机号')
return
}
const phoneRegex = /^1[3-9]\d{9}$/
if (!phoneRegex.test(changePhoneForm.newPhone)) {
message.error('手机号格式不正确')
return
}
try {
await userApi.sendVerificationCode({ phone: changePhoneForm.newPhone })
message.success('验证码发送成功')
startCountdown()
} catch (error) {
console.error('发送验证码失败:', error)
message.error('发送验证码失败')
}
}
// 发送修改密码验证码
const handleSendChangePasswordVerificationCode = async () => {
if (!userInfo.value.phone) {
message.error('请先绑定手机号')
return
}
const phoneRegex = /^1[3-9]\d{9}$/
if (!phoneRegex.test(userInfo.value.phone)) {
message.error('手机号格式不正确')
return
}
try {
await userApi.sendVerificationCode({ phone: userInfo.value.phone })
message.success('验证码发送成功')
startCountdown()
} catch (error) {
console.error('发送验证码失败:', error)
message.error('发送验证码失败')
}
}
// 开始倒计时
const startCountdown = () => {
countdown.value = 60
const timer = setInterval(() => {
countdown.value--
if (countdown.value <= 0) {
clearInterval(timer)
}
}, 1000)
}
// 处理绑定手机号提交
const handleBindPhoneSubmit = async () => {
if (!bindPhoneForm.phone || !bindPhoneForm.verificationCode) {
message.error('请填写完整信息')
return
}
bindPhoneLoading.value = true
try {
await userApi.bindPhone({
phone: bindPhoneForm.phone,
verificationCode: bindPhoneForm.verificationCode
})
message.success('手机号绑定成功')
handleClearBindPhoneDraft(false)
bindPhoneModalVisible.value = false
await fetchUserInfo()
} catch (error: any) {
console.error('绑定手机号失败:', error)
message.error(error.message || '绑定手机号失败')
} finally {
bindPhoneLoading.value = false
}
}
// 处理绑定手机号取消
const handleBindPhoneCancel = () => {
bindPhoneModalVisible.value = false
bindPhoneForm.phone = ''
bindPhoneForm.verificationCode = ''
}
// 处理修改手机号提交
const handleChangePhoneSubmit = async () => {
if (!changePhoneForm.newPhone || !changePhoneForm.verificationCode) {
message.error('请填写完整信息')
return
}
changePhoneLoading.value = true
try {
await userApi.updatePhone({
oldPhone: userInfo.value.phone!,
newPhone: changePhoneForm.newPhone,
verificationCode: changePhoneForm.verificationCode
})
message.success('手机号修改成功')
handleClearChangePhoneDraft(false)
changePhoneModalVisible.value = false
await fetchUserInfo()
} catch (error: any) {
console.error('修改手机号失败:', error)
message.error(error.message || '修改手机号失败')
} finally {
changePhoneLoading.value = false
}
}
// 处理修改手机号取消
const handleChangePhoneCancel = () => {
changePhoneModalVisible.value = false
changePhoneForm.newPhone = ''
changePhoneForm.verificationCode = ''
}
// 处理修改密码提交
const handleChangePasswordSubmit = async () => {
if (!changePasswordForm.verificationCode || !changePasswordForm.password || !changePasswordForm.confirmPassword) {
message.error('请填写完整信息')
return
}
if (changePasswordForm.password !== changePasswordForm.confirmPassword) {
message.error('两次输入的密码不一致')
return
}
changePasswordLoading.value = true
try {
await userApi.updatePassword({
password: changePasswordForm.password,
verificationCode: changePasswordForm.verificationCode
})
message.success('密码修改成功')
handleClearChangePasswordDraft(false)
changePasswordModalVisible.value = false
// 清除需要设置密码的标识
localStorage.removeItem('needSetPassword')
hasPassword.value = true
} catch (error: any) {
console.error('修改密码失败:', error)
message.error(error.message || '修改密码失败')
} finally {
changePasswordLoading.value = false
}
}
// 处理修改密码取消
const handleChangePasswordCancel = () => {
changePasswordModalVisible.value = false
changePasswordForm.verificationCode = ''
changePasswordForm.password = ''
changePasswordForm.confirmPassword = ''
}
// 处理注销账号
const handleDeactivateAccount = async () => {
Modal.confirm({
title: '确认注销账号',
content: '注销账号后,您的所有数据将被删除且无法恢复。确定要注销账号吗?',
okText: '确认注销',
okType: 'danger',
cancelText: '取消',
onOk: async () => {
try {
await userApi.deactivateAccount()
message.success('账号注销成功')
} catch (error) {
console.error('注销账号失败:', error)
message.error('注销账号失败')
} finally {
// 无论成功或失败,都清除本地存储的用户信息
localStorage.removeItem('accessToken')
localStorage.removeItem('refreshToken')
localStorage.removeItem('userInfo')
localStorage.removeItem('adminAccessToken')
localStorage.removeItem('adminRefreshToken')
localStorage.removeItem('adminUserInfo')
localStorage.removeItem('needSetPassword')
localStorage.removeItem('userPermissions')
sessionStorage.removeItem('accessToken')
sessionStorage.removeItem('adminAccessToken')
// 跳转到登录页
router.push('/')
}
}
})
}
// 生命周期
onMounted(() => {
fetchUserInfo()
})
</script>
<style scoped>
.mobile-container {
min-height: 100vh;
background: #f5f5f5;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 15px;
background: white;
border-bottom: 1px solid #f0f0f0;
}
.header h1 {
font-size: 18px;
font-weight: bold;
margin: 0;
}
.back-btn,
.empty {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
}
.account-settings {
padding: 15px;
}
.status-tips {
margin-bottom: 15px;
}
.settings-card {
border-radius: 16px;
overflow: hidden;
background: white;
}
.settings-card :deep(.ant-card-body) {
padding: 0;
}
.setting-item {
padding: 16px;
cursor: pointer;
transition: background 0.3s;
border-bottom: 1px solid #f0f0f0;
}
.setting-item:hover {
background: #fafafa;
}
.setting-item:last-child {
border-bottom: none;
}
.setting-item :deep(.ant-list-item-action) {
margin-left: 8px;
color: #ccc;
}
.setting-icon {
width: 40px;
height: 40px;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
color: white;
}
.setting-item :deep(.ant-list-item-meta-title) {
font-size: 15px;
font-weight: 500;
color: #333;
}
.setting-item :deep(.ant-list-item-meta-description) {
font-size: 12px;
color: #999;
}
.password-tip {
font-size: 12px;
color: #999;
margin-top: 8px;
}
</style>
-132
View File
@@ -1,132 +0,0 @@
<template>
<div class="page">
<header class="header">
<a-button type="text" @click="router.back()">
<LeftOutlined :style="{ fontSize: '20px' }" />
</a-button>
<h1>美甲师订单</h1>
<div class="placeholder" />
</header>
<main class="content">
<a-empty v-if="!orders.length" description="暂无订单">
<a-button type="primary" @click="loadOrders">刷新</a-button>
</a-empty>
<a-card v-for="order in orders" :key="order.id" class="order-card">
<div class="order-head">
<span>订单号:{{ order.orderNo }}</span>
<span class="status" :class="statusClass(order.status)">{{ order.statusText }}</span>
</div>
<div v-for="item in order.items" :key="item.id" class="item">
<div class="thumb">
<img v-if="item.productImage" :src="item.productImage" :alt="item.productTitle" />
<span v-else>{{ item.productTitle[0] }}</span>
</div>
<div class="main">
<div class="title">{{ item.productTitle }}</div>
<div class="line">¥{{ item.price.toFixed(2) }} x {{ item.quantity }}</div>
<div v-if="item.appointmentTime" class="line appointment">预约时间:{{ item.appointmentTime }}</div>
</div>
</div>
<div class="footer">
<span>当前项目合计:¥{{ order.actualAmount.toFixed(2) }}</span>
<a-button v-if="order.status === 1" size="small" type="primary" @click="completeOrder(order.id)">
完成服务
</a-button>
</div>
</a-card>
</main>
</div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { fileApi } from '../api/index'
import { orderApi } from '../api/order'
import type { IdType } from '@/utils/id'
const router = useRouter()
const orders = ref<any[]>([])
const imageIdCache = ref<Record<string, string>>({})
const statusClass = (status: number) => {
if (status === 1) return 'pending'
if (status === 2) return 'completed'
return 'cancelled'
}
const loadOrders = async () => {
try {
orders.value = (await orderApi.getArtistOrders() as unknown as any[]) || []
for (const order of orders.value) {
for (const item of order.items || []) {
const match = item.productImage?.replace(/<[^>]*>/g, '').match(/\/api\/file\/get\/(\d+)/)
if (!match?.[1]) continue
const imageId = match[1]
try {
if (!imageIdCache.value[imageId]) imageIdCache.value[imageId] = await fileApi.getSignedUrl(imageId) as any
item.productImage = imageIdCache.value[imageId]
} catch {
item.productImage = ''
}
}
}
} catch {
message.error('获取订单列表失败')
}
}
const completeOrder = (orderId: IdType) => {
Modal.confirm({
title: '确认完成服务',
content: '确定要完成这个订单吗?',
onOk: async () => {
try {
await orderApi.completeArtistOrder(orderId)
message.success('订单已完成')
await loadOrders()
} catch {
message.error('完成订单失败')
}
}
})
}
onMounted(loadOrders)
</script>
<style scoped>
.page { min-height: 100vh; padding-top: 60px; background: #f5f5f5; }
.header { position: fixed; top: 0; left: 0; right: 0; z-index: 10; display: flex; align-items: center; justify-content: space-between; padding: 10px 15px; background: #fff; border-bottom: 1px solid #f0f0f0; }
.header h1 { margin: 0; font-size: 18px; }
.placeholder { width: 40px; height: 40px; }
.content { padding: 15px; }
.order-card { margin-bottom: 12px; border-radius: 12px; }
.order-head, .footer { display: flex; align-items: center; justify-content: space-between; }
.order-head { margin-bottom: 12px; padding-bottom: 10px; border-bottom: 1px solid #f0f0f0; }
.status { padding: 4px 10px; border-radius: 999px; font-size: 12px; font-weight: 600; }
.pending { background: #fff7e6; color: #fa8c16; }
.completed { background: #f6ffed; color: #52c41a; }
.cancelled { background: #fff1f0; color: #ff4d4f; }
.item { display: flex; gap: 12px; margin-bottom: 12px; }
.thumb { width: 60px; height: 60px; border-radius: 8px; overflow: hidden; display: flex; align-items: center; justify-content: center; background: #eef3ff; }
.thumb img { width: 100%; height: 100%; object-fit: cover; }
.main { flex: 1; }
.title { font-weight: 600; }
.line { margin-top: 4px; color: #666; font-size: 13px; }
.appointment { color: #1890ff; }
@media (min-width: 992px) {
.content {
max-width: 980px;
margin: 0 auto;
padding: 24px;
}
}
</style>
File diff suppressed because it is too large Load Diff
-879
View File
@@ -1,879 +0,0 @@
<template>
<div class="page">
<header class="header">
<a-button type="text" @click="router.back()">
<LeftOutlined :style="{ fontSize: '20px' }" />
</a-button>
<h1>购物车</h1>
<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>
<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)">
<img v-if="item.productImage" :src="item.productImage" :alt="item.productTitle" />
<span v-else>{{ item.productTitle[0] }}</span>
</div>
<div class="item-main">
<div class="title" @click="openProduct(item)">{{ item.productTitle }}</div>
<div class="price">¥{{ Number(item.price || 0).toFixed(2) }}</div>
<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"
: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 ? '请选择预约时间' : '先选择美甲师') }}
</span>
<RightOutlined />
</div>
<div v-if="item.approximateDuration" class="duration">预计时长:{{ item.approximateDuration }}</div>
<div class="actions">
<div class="qty">
<a-button size="small" :disabled="item.quantity <= 1" @click="changeQuantity(item, -1)">-</a-button>
<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-button type="text" danger size="small">
<DeleteOutlined />
</a-button>
</a-popconfirm>
</div>
</div>
</div>
</a-card>
<a-card v-if="selectedCount && !editing" class="coupon-card" @click="openCouponModal">
<div class="coupon-row">
<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>
</a-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>
</a-card>
</main>
<footer v-if="cartItems.length" class="footer">
<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-radio-group v-model:value="couponSelectionKey" class="coupon-options">
<a-radio :value="NO_COUPON_KEY">不使用优惠</a-radio>
<a-radio v-for="coupon in availableCoupons" :key="getCouponKey(coupon)" :value="getCouponKey(coupon)">
{{ formatCouponDisplay(coupon) }}
</a-radio>
</a-radio-group>
<div class="coupon-tip">
系统只会默认预选最佳 VIP 自动券,普通用户券需要你手动选择后才会在下单时使用。
</div>
</a-modal>
<a-modal v-model:open="showBookingModal" :title="bookingTitle" @ok="confirmBooking" @cancel="closeBookingModal">
<div class="modal-section">
<div class="section-title">美甲师</div>
<div v-if="availableArtists.length" class="artist-list">
<button
v-for="artist in availableArtists"
:key="artist.id"
type="button"
class="artist-option"
:class="{ active: sameId(draftArtistId, artist.id) }"
@click="draftArtistId = artist.id"
>
<img v-if="artist.avatar" :src="artist.avatar" :alt="artist.name" />
<span>{{ artist.name }}</span>
</button>
</div>
<a-empty v-else description="暂无可预约美甲师" />
</div>
<div class="modal-section">
<div class="section-title">预约时间</div>
<a-date-picker
v-model:value="draftAppointmentTime"
class="time-picker"
style="width: 100%"
format="YYYY-MM-DD HH:mm:ss"
value-format="YYYY-MM-DD HH:mm:ss"
input-read-only
:disabled-date="disablePastAppointmentDate"
:disabled-time="disablePastAppointmentTime"
:show-time="{ minuteStep: 30, secondStep: 60, hideDisabledOptions: true }"
placeholder="请选择预约时间"
/>
<div class="helper">{{ bookingHelperText }}</div>
</div>
</a-modal>
</div>
</template>
<script setup lang="ts">
import { computed, inject, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { DeleteOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { cartApi } from '../api/cart'
import { couponApi, type UserCoupon } from '../api/coupon'
import { fileApi } from '../api/index'
import { orderApi } from '../api/order'
import { shopApi } from '../api/shop'
import type { IdType } from '@/utils/id'
import { sameId, toOptionalIdString } from '@/utils/id'
const router = useRouter()
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
const NO_COUPON_KEY = 'NONE'
interface ArtistOption {
id: IdType
name: string
avatar?: string
}
interface CartItem {
id: IdType
productId: IdType
shopId?: IdType
productTitle: string
productImage: string
originalProductImage?: string
price: number
quantity: number
totalPrice: number
tags: string
tagNames?: string
approximateDuration?: string
bookableArtists?: string
availableBookableArtistCount?: number
bookableArtistRestricted?: boolean
availableArtists?: ArtistOption[]
appointmentTime?: string
selected: boolean
artistId?: IdType
artist?: ArtistOption
}
interface CheckoutIssue {
key: string
message: string
itemId?: IdType
}
const cartItems = ref<CartItem[]>([])
const imageIdCache = ref<Record<string, string>>({})
const itemRefs = ref<Record<string, HTMLElement>>({})
const availableCoupons = ref<UserCoupon[]>([])
const selectedCoupon = ref<UserCoupon | null>(null)
const couponSelectionKey = ref(NO_COUPON_KEY)
const couponSelectionTouched = ref(false)
const showCouponModal = ref(false)
const showBookingModal = ref(false)
const currentItem = ref<CartItem | null>(null)
const availableArtists = ref<ArtistOption[]>([])
const draftArtistId = ref<IdType>()
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 + 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 bookingHelperText = computed(() => {
const texts: string[] = []
if (currentShopHours.value) texts.push(`门店营业时间:${currentShopHours.value}`)
if (currentItem.value?.approximateDuration) texts.push(`预计时长:${currentItem.value.approximateDuration}`)
return texts.join(' · ') || '请选择至少晚于当前 5 分钟的预约时间'
})
const getMinAppointmentDate = () => {
const date = new Date()
date.setSeconds(0, 0)
date.setMinutes(date.getMinutes() + 5)
return date
}
const getDayBoundary = (date: Date) => {
const boundary = new Date(date)
boundary.setHours(0, 0, 0, 0)
return boundary.getTime()
}
const getCouponKey = (coupon: UserCoupon) => `${coupon.sourceType || 'USER_COUPON'}:${coupon.id}`
const setItemRef = (itemId: IdType, element: unknown) => {
const refKey = toOptionalIdString(itemId)
if (!refKey) {
return
}
if (element && (element as any).$el) {
itemRefs.value[refKey] = (element as any).$el as HTMLElement
return
}
if (element instanceof HTMLElement) {
itemRefs.value[refKey] = element
return
}
delete itemRefs.value[refKey]
}
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)
return discountValue ? amount - amount * discountValue / 10 : 0
}
if (coupon.couponType === 2) {
return Number(coupon.reduceAmount || 0)
}
return 0
}
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 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 })
}
const selectedShopIds = new Set(
items
.map(item => toOptionalIdString(item.shopId))
.filter((shopId): shopId is string => Boolean(shopId))
)
if (selectedShopIds.size > 1) {
issues.push({ key: 'shop', message: '跨店铺项目请分开结算', itemId: items[0]?.id })
}
const selectedArtistIds = new Set(
items
.map(item => toOptionalIdString(item.artistId))
.filter((artistId): artistId is string => Boolean(artistId))
)
if (selectedArtistIds.size > 1) {
issues.push({ key: 'artist-mix', message: '不同美甲师的项目请分开结算', itemId: items[0]?.id })
}
return issues
})
const scrollToIssue = (issue?: CheckoutIssue) => {
const itemId = toOptionalIdString(issue?.itemId)
if (!itemId) {
return
}
const target = itemRefs.value[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 => ({
...item,
selected: true,
originalProductImage: item.productImage,
productImage: '',
appointmentTime: item.appointmentTime
}))
couponSelectionTouched.value = false
couponSelectionKey.value = NO_COUPON_KEY
selectedCoupon.value = null
editing.value = false
await Promise.all([loadProductImages(), loadAvailableCoupons()])
}
const loadProductImages = async () => {
for (const item of cartItems.value) {
if (!item.originalProductImage) continue
const match = item.originalProductImage.replace(/<[^>]*>/g, '').match(/\/api\/file\/get\/(\d+)/)
if (!match?.[1]) continue
const imageId = match[1]
try {
if (!imageIdCache.value[imageId]) {
imageIdCache.value[imageId] = await fileApi.getSignedUrl(imageId) as any
}
item.productImage = imageIdCache.value[imageId] || ''
} catch {
item.productImage = ''
}
}
}
const loadAvailableCoupons = async () => {
if (editing.value) {
return
}
const currentSelectedKey = selectedCoupon.value ? getCouponKey(selectedCoupon.value) : couponSelectionKey.value
const selectedShopId = selectedItems.value[0]?.shopId
if (!selectedItems.value.length || subtotal.value <= 0) {
availableCoupons.value = []
selectedCoupon.value = null
couponSelectionKey.value = NO_COUPON_KEY
return
}
try {
// 这里只做“最佳 VIP 自动券”兜底预选,普通用户券必须显式点选后才会消耗。
const tags = new Set<string>()
selectedItems.value.forEach(item => {
item.tagNames?.split(',').map(tag => tag.trim()).forEach(tag => {
if (tag) {
tags.add(tag)
}
})
})
const data = await couponApi.getAvailableCoupons(Array.from(tags).join(','), subtotal.value, selectedShopId) as unknown as UserCoupon[]
availableCoupons.value = Array.isArray(data) ? data : []
const matchedCoupon = availableCoupons.value.find(coupon => getCouponKey(coupon) === currentSelectedKey) || null
if (matchedCoupon) {
selectedCoupon.value = matchedCoupon
couponSelectionKey.value = getCouponKey(matchedCoupon)
return
}
if (couponSelectionTouched.value && currentSelectedKey === NO_COUPON_KEY) {
selectedCoupon.value = null
couponSelectionKey.value = NO_COUPON_KEY
return
}
couponSelectionTouched.value = false
const defaultVipCoupon = findBestSystemVipCoupon(availableCoupons.value)
if (defaultVipCoupon) {
selectedCoupon.value = defaultVipCoupon
couponSelectionKey.value = getCouponKey(defaultVipCoupon)
} else {
selectedCoupon.value = null
couponSelectionKey.value = NO_COUPON_KEY
}
} catch (error) {
console.error('获取可用优惠失败:', error)
availableCoupons.value = []
selectedCoupon.value = null
couponSelectionKey.value = NO_COUPON_KEY
}
}
const changeQuantity = async (item: CartItem, delta: number) => {
const next = item.quantity + delta
if (next < 1 || next > 99) return
item.quantity = next
try {
await cartApi.updateCartQuantity({ productId: item.productId, quantity: next })
await Promise.all([loadAvailableCoupons(), updateCartCount()])
} catch {
item.quantity -= delta
message.error('更新数量失败')
}
}
const removeItem = async (item: CartItem) => {
try {
await cartApi.removeFromCart(item.productId)
cartItems.value = cartItems.value.filter(current => !sameId(current.id, item.id))
await Promise.all([loadAvailableCoupons(), updateCartCount()])
message.success('作品已删除')
} catch {
message.error('删除作品失败')
}
}
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
draftAppointmentTime.value = item.appointmentTime || ''
showBookingModal.value = true
await Promise.all([loadArtists(item), loadShopHours(item.shopId)])
}
const loadArtists = async (item: CartItem) => {
// 购物车里保存的是后端已经按作品可约范围裁剪过的美甲师列表,这里只做前端展示和 ID 保真。
availableArtists.value = Array.isArray(item.availableArtists)
? item.availableArtists
.filter(artist => artist && artist.id !== undefined && artist.id !== null)
.map(artist => ({
id: artist.id,
name: artist.name,
avatar: artist.avatar
}))
: []
if (draftArtistId.value && !availableArtists.value.some(artist => sameId(artist.id, draftArtistId.value))) {
draftArtistId.value = undefined
}
}
const loadShopHours = async (shopId?: IdType) => {
currentShopHours.value = ''
if (!shopId) return
try {
const shop = await shopApi.getShopById(shopId) as any
currentShopHours.value = shop?.businessHours || ''
} catch {
currentShopHours.value = ''
}
}
const disablePastAppointmentDate = (current: any) => {
if (!current) return false
return current.valueOf() < getDayBoundary(new Date())
}
const disablePastAppointmentTime = (current: any) => {
if (!current || typeof current.format !== 'function') {
return {}
}
const minDate = getMinAppointmentDate()
const minDateText = [
minDate.getFullYear(),
String(minDate.getMonth() + 1).padStart(2, '0'),
String(minDate.getDate()).padStart(2, '0')
].join('-')
if (current.format('YYYY-MM-DD') !== minDateText) {
return {}
}
const minHour = minDate.getHours()
const minMinute = minDate.getMinutes()
return {
disabledHours: () => Array.from({ length: minHour }, (_, index) => index),
disabledMinutes: (selectedHour: number) => selectedHour === minHour
? Array.from({ length: minMinute }, (_, index) => index)
: [],
disabledSeconds: () => []
}
}
const closeBookingModal = () => {
showBookingModal.value = false
currentItem.value = null
draftArtistId.value = undefined
draftAppointmentTime.value = ''
availableArtists.value = []
currentShopHours.value = ''
}
const confirmBooking = () => {
if (!currentItem.value) return closeBookingModal()
if (!draftArtistId.value) return message.warning('请先选择美甲师')
if (!draftAppointmentTime.value) return message.warning('请选择预约时间')
if (isPastAppointment(draftAppointmentTime.value)) return message.warning('预约时间至少需要晚于当前 5 分钟')
currentItem.value.artistId = draftArtistId.value
currentItem.value.artist = availableArtists.value.find(artist => sameId(artist.id, draftArtistId.value))
currentItem.value.appointmentTime = draftAppointmentTime.value
closeBookingModal()
}
const openCouponModal = () => {
couponSelectionKey.value = selectedCoupon.value ? getCouponKey(selectedCoupon.value) : NO_COUPON_KEY
showCouponModal.value = true
}
const applyCouponSelection = () => {
couponSelectionTouched.value = true
if (couponSelectionKey.value === NO_COUPON_KEY) {
selectedCoupon.value = null
} else {
selectedCoupon.value = availableCoupons.value.find(coupon => getCouponKey(coupon) === couponSelectionKey.value) || null
}
showCouponModal.value = false
}
const checkout = async () => {
const items = selectedItems.value
if (!items.length) {
return message.warning('请先选择要结算的作品')
}
const firstIssue = checkoutIssues.value[0]
if (firstIssue) {
message.warning(firstIssue.message)
scrollToIssue(firstIssue)
return
}
try {
await orderApi.createOrder({
couponId: selectedCoupon.value?.id,
couponSourceType: selectedCoupon.value?.sourceType || (couponSelectionTouched.value && !selectedCoupon.value ? NO_COUPON_KEY : undefined),
items: items.map(item => ({
productId: item.productId,
quantity: item.quantity,
artistId: item.artistId,
appointmentTime: item.appointmentTime
}))
})
await Promise.all([loadCartItems(), updateCartCount()])
message.success('订单创建成功')
router.push('/orders')
} catch (error: any) {
console.error('创建订单失败:', error)
message.error(error?.message || '创建订单失败')
}
}
watch(
() => cartItems.value.map(item => `${item.id}-${item.selected}-${item.quantity}`).join('|'),
() => {
void loadAvailableCoupons()
}
)
onMounted(async () => {
try {
await loadCartItems()
} catch {
message.error('获取购物车数据失败')
}
})
</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;
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 {
padding: 15px 15px 140px;
}
}
</style>
-294
View File
@@ -1,294 +0,0 @@
<template>
<div class="mobile-container">
<header class="header">
<a-button type="text" class="back-btn" @click="router.back()">
<LeftOutlined />
</a-button>
<h1>我的优惠券</h1>
<div class="placeholder"></div>
</header>
<div class="coupon-section">
<a-card :bordered="false" class="filter-card">
<a-segmented
v-model:value="activeFilter"
:options="filterOptions"
class="filter-segmented"
/>
</a-card>
<a-card v-if="loading" :bordered="false" class="content-card">
<a-skeleton :paragraph="{ rows: 3 }" />
</a-card>
<a-card v-else-if="coupons.length === 0" :bordered="false" class="content-card">
<a-empty description="暂无优惠券">
<a-button type="primary">去领取</a-button>
</a-empty>
</a-card>
<div v-else class="coupon-list">
<a-card
v-for="coupon in filteredCoupons"
:key="coupon.id"
class="coupon-card"
:class="{ 'expired': coupon.status === 3 }"
>
<div class="coupon-content">
<div class="coupon-value">
{{ coupon.couponType === 1 ? `${coupon.discountValue}折` : `¥${coupon.reduceAmount}` }}
</div>
<div class="coupon-info">
<div class="coupon-name">{{ coupon.couponName }}</div>
<div class="coupon-condition" v-if="coupon.couponType === 2">
满{{ coupon.minAmount }}元可用
</div>
<div class="coupon-time">
{{ formatDate(coupon.startTime) }} 至 {{ formatDate(coupon.endTime) }}
</div>
<div :class="['coupon-status', getStatusClass(coupon.status)]">
{{ coupon.statusName }}
</div>
</div>
</div>
</a-card>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { couponApi } from '@/api/coupon'
const router = useRouter()
const loading = ref(false)
const coupons = ref<any[]>([])
const activeFilter = ref('all')
const filterOptions = [
{ label: '全部', value: 'all' },
{ label: '未使用', value: 'available' },
{ label: '已使用', value: 'used' },
{ label: '已过期', value: 'expired' }
]
const filteredCoupons = computed(() => {
if (activeFilter.value === 'all') {
return coupons.value
} else if (activeFilter.value === 'available') {
return coupons.value.filter(coupon => coupon.status === 1)
} else if (activeFilter.value === 'used') {
return coupons.value.filter(coupon => coupon.status === 2)
} else if (activeFilter.value === 'expired') {
return coupons.value.filter(coupon => coupon.status === 3)
}
return coupons.value
})
const loadCoupons = async () => {
loading.value = true
try {
const response = await couponApi.listUserCoupons() as any
coupons.value = response || []
} catch (error) {
console.error('获取优惠券列表失败:', error)
message.error('获取优惠券列表失败')
} finally {
loading.value = false
}
}
const getStatusClass = (status: number) => {
switch (status) {
case 1:
return 'available'
case 2:
return 'used'
case 3:
return 'expired'
default:
return ''
}
}
const formatDate = (dateString: string) => {
if (!dateString) return ''
const date = new Date(dateString)
return date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
})
}
onMounted(() => {
loadCoupons()
})
</script>
<style scoped>
.mobile-container {
padding-top: 60px;
min-height: 100vh;
background: #f5f5f5;
}
.header {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 100;
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 15px;
background: white;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}
.header h1 {
font-size: 18px;
font-weight: bold;
margin: 0;
color: #1a1a2e;
}
.back-btn {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
color: #1a1a2e;
}
.placeholder {
width: 40px;
}
.coupon-section {
padding: 15px;
}
.filter-card {
border-radius: 12px;
margin-bottom: 15px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}
.filter-segmented {
width: 100%;
}
.content-card {
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
padding: 40px 20px;
}
.coupon-list {
display: flex;
flex-direction: column;
gap: 15px;
}
.coupon-card {
border-radius: 12px;
overflow: hidden;
background: linear-gradient(135deg, #f5f7ff 0%, #e8ecff 100%);
transition: all 0.3s ease;
}
.coupon-card:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.15);
}
.coupon-card.expired {
opacity: 0.6;
background: linear-gradient(135deg, #f5f5f5 0%, #e8e8e8 100%);
}
.coupon-content {
display: flex;
align-items: center;
gap: 20px;
padding: 20px;
}
.coupon-value {
font-size: 24px;
font-weight: 700;
color: #667eea;
padding: 20px;
background: rgba(102, 126, 234, 0.1);
border-radius: 8px;
min-width: 100px;
text-align: center;
}
.coupon-card.expired .coupon-value {
color: #8b8b9a;
background: rgba(139, 139, 154, 0.1);
}
.coupon-info {
flex: 1;
display: flex;
flex-direction: column;
gap: 8px;
}
.coupon-name {
font-size: 16px;
font-weight: 600;
color: #1a1a2e;
}
.coupon-condition {
font-size: 12px;
color: #667eea;
}
.coupon-time {
font-size: 12px;
color: #8b8b9a;
}
.coupon-status {
font-size: 12px;
font-weight: 600;
padding: 2px 8px;
border-radius: 8px;
align-self: flex-start;
}
.coupon-status.available {
background: #f6ffed;
color: #52c41a;
}
.coupon-status.used {
background: #f5f5f5;
color: #8b8b9a;
}
.coupon-status.expired {
background: #fff1f0;
color: #ff4d4f;
}
@media (min-width: 992px) {
.coupon-section {
max-width: 960px;
margin: 0 auto;
padding: 24px;
}
}
</style>
-619
View File
@@ -1,619 +0,0 @@
<template>
<div class="mobile-container">
<header class="header">
<div class="user-info" @click="handleUserClick">
<a-avatar
:size="44"
:src="userInfo?.avatar || DEFAULT_AVATAR"
/>
<div class="welcome">
<p class="greeting">{{ greeting }}</p>
<p class="username">{{ displayName }}</p>
</div>
</div>
<a-button class="header-action" type="primary" ghost @click="handleUserClick">
{{ isLoggedIn ? '个人中心' : '去登录' }}
</a-button>
</header>
<div class="search-section">
<a-input-search
v-model:value="searchQuery"
size="large"
placeholder="搜索作品、风格或门店"
enter-button="搜索"
@search="handleSearch"
/>
</div>
<a-alert
v-if="!isLoggedIn"
class="guest-alert"
type="info"
show-icon
message="当前为游客模式"
description="先逛作品和门店,收藏、加购、下单时再登录即可。"
/>
<section class="section">
<div class="banner-container">
<div class="banner-carousel">
<a-carousel v-if="bannerImages.length" autoplay :autoplay-speed="3200" effect="fade">
<div
v-for="banner in bannerImages"
:key="banner.id"
class="banner-slide"
@click="openShopById(banner.shopId)"
>
<img :src="banner.url" :alt="banner.shopName" class="banner-img" />
<div class="banner-copy">
<a-tag color="blue">门店推荐</a-tag>
<h3>{{ banner.shopName }}</h3>
<p>{{ banner.businessHours || '欢迎到店体验' }}</p>
</div>
</div>
</a-carousel>
<div v-else class="banner-empty">
<h3>发现适合你的美甲风格</h3>
<p>先看看门店 Banner 和精选作品,再决定今天预约谁。</p>
<a-button type="primary" @click="router.push('/products')">浏览作品</a-button>
</div>
</div>
</div>
</section>
<section class="section">
<div class="section-header">
<h3>精选作品</h3>
<a class="see-all" @click="handleSeeAll('featured')">查看全部</a>
</div>
<div class="horizontal-scroll">
<a-card
v-for="item in featuredItems"
:key="item.id"
class="product-card"
:body-style="{ padding: '12px' }"
hoverable
@click="handleProductClick(item)"
>
<div class="product-img" :style="{ backgroundColor: item.bgColor }">
<img v-if="item.coverUrl" :src="item.coverUrl" :alt="item.name" class="product-cover" />
<span v-else>{{ item.name[0] }}</span>
</div>
<div class="product-info">
<p class="name">{{ item.name }}</p>
<p class="meta">{{ item.meta }}</p>
<p class="price">¥{{ item.price }}</p>
</div>
</a-card>
</div>
</section>
<section class="section popular-section">
<div class="section-header">
<h3>热门作品</h3>
<a class="see-all" @click="handleSeeAll('popular')">查看全部</a>
</div>
<div class="product-grid">
<a-card
v-for="item in popularItems"
:key="item.id"
class="product-card grid-item"
:body-style="{ padding: '12px' }"
hoverable
@click="handleProductClick(item)"
>
<div class="product-img" :style="{ backgroundColor: item.bgColor }">
<img v-if="item.coverUrl" :src="item.coverUrl" :alt="item.name" class="product-cover" />
<span v-else>{{ item.name[0] }}</span>
</div>
<div class="product-info">
<p class="name">{{ item.name }}</p>
<p class="meta">{{ item.meta }}</p>
<p class="price">¥{{ item.price }}</p>
</div>
</a-card>
</div>
<div v-if="loading" class="loading-more">
<a-spin size="small" />
<span>加载中...</span>
</div>
<div v-else-if="!hasMore && popularItems.length > 0" class="no-more">
没有更多热门推荐了
</div>
<div v-else-if="popularItems.length === 0 && !loading" class="no-products">
暂无热门作品
</div>
</section>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { userApi, type UserVO } from '../api/user'
import { productApi, type ProductVO } from '../api/product'
import { shopApi, type ShopVO } from '../api/shop'
import { fileApi } from '../api/file'
import { DEFAULT_AVATAR, DEFAULT_PRODUCT_IMAGE } from '@/constants'
import type { IdType } from '@/utils/id'
interface BannerImage {
id: string
shopId: IdType
shopName: string
businessHours?: string
url: string
}
interface ProductCardItem {
id: IdType
name: string
price: string
meta: string
coverUrl: string
bgColor: string
}
const router = useRouter()
const userInfo = ref<UserVO | null>(null)
const publicShops = ref<ShopVO[]>([])
const bannerImages = ref<BannerImage[]>([])
const featuredItems = ref<ProductCardItem[]>([])
const popularSource = ref<ProductCardItem[]>([])
const popularItems = ref<ProductCardItem[]>([])
const productImageCache = ref<Record<string, string>>({})
const searchQuery = ref('')
const loading = ref(false)
const hasMore = ref(true)
const page = ref(1)
const pageSize = 8
const isLoggedIn = computed(() => Boolean(localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')))
const greeting = computed(() => (isLoggedIn.value ? '欢迎回来' : '游客模式'))
const displayName = computed(() => userInfo.value?.nickname || (isLoggedIn.value ? '用户' : '先看看门店和作品'))
const getRandomColor = (): string => {
const colors = ['#ffe4d6', '#d6eaff', '#e2ffd6', '#fff2d6', '#d6ffe4', '#e4d6ff']
return colors[Math.floor(Math.random() * colors.length)] ?? '#ffe4d6'
}
const getProductCoverUrl = async (product: ProductVO): Promise<string> => {
const firstImageId = product.imageFileIds?.split(',').map(id => id.trim()).find(Boolean)
if (!firstImageId) {
return DEFAULT_PRODUCT_IMAGE
}
if (!productImageCache.value[firstImageId]) {
try {
productImageCache.value[firstImageId] = await fileApi.getSignedUrl(firstImageId) as unknown as string
} catch (error) {
console.error('获取首页作品封面失败:', error)
productImageCache.value[firstImageId] = DEFAULT_PRODUCT_IMAGE
}
}
return productImageCache.value[firstImageId] || DEFAULT_PRODUCT_IMAGE
}
const formatProductCards = async (products: ProductVO[]): Promise<ProductCardItem[]> =>
Promise.all(products.map(async item => ({
id: item.id,
name: item.title || item.name || '未命名作品',
price: Number(item.price || 0).toFixed(2),
meta: item.approximateDuration || item.shopName || '支持预约',
coverUrl: await getProductCoverUrl(item),
bgColor: getRandomColor()
})))
const appendPopularItems = (loadMore = false) => {
const nextItems = popularSource.value.slice(0, page.value * pageSize)
popularItems.value = nextItems
hasMore.value = nextItems.length < popularSource.value.length
if (!loadMore && nextItems.length === 0) {
hasMore.value = false
}
}
const loadUserInfo = async () => {
if (!isLoggedIn.value) {
userInfo.value = null
return
}
try {
const response = await userApi.getUserInfo()
userInfo.value = response || null
} catch (error) {
console.error('获取用户信息失败:', error)
userInfo.value = null
}
}
const loadPublicShops = async () => {
try {
const shops = await shopApi.getPublicShops()
publicShops.value = Array.isArray(shops) ? shops : []
await loadBannerImages()
} catch (error) {
console.error('获取门店列表失败:', error)
publicShops.value = []
bannerImages.value = []
}
}
const loadBannerImages = async () => {
const banners: BannerImage[] = []
for (const shop of publicShops.value) {
const coverIds = (shop.coverImageFileId || shop.imageFileIds || '')
.split(',')
.map(id => id.trim())
.filter(Boolean)
for (const id of coverIds) {
try {
const url = await fileApi.getSignedUrl(id) as unknown as string
if (url) {
banners.push({
id: `${shop.id}-${id}`,
shopId: shop.id,
shopName: shop.shopName,
businessHours: shop.businessHours,
url
})
}
} catch (error) {
console.error('获取门店轮播图失败:', error)
}
}
}
bannerImages.value = banners.slice(0, 8)
}
const loadFeaturedProducts = async () => {
try {
let products = await productApi.getProductsByTag('精选')
if (!Array.isArray(products) || products.length === 0) {
products = await productApi.getAllProducts()
}
featuredItems.value = await formatProductCards((products || []).slice(0, 6))
} catch (error) {
console.error('获取精选作品失败:', error)
featuredItems.value = []
}
}
const loadPopularProducts = async () => {
loading.value = true
try {
let products = await productApi.getProductsByTag('热门')
if (!Array.isArray(products) || products.length === 0) {
products = await productApi.getAllProducts()
}
popularSource.value = await formatProductCards(products || [])
page.value = 1
appendPopularItems()
} catch (error) {
console.error('获取热门作品失败:', error)
popularSource.value = []
popularItems.value = []
hasMore.value = false
} finally {
loading.value = false
}
}
const handleScroll = () => {
if (loading.value || !hasMore.value) {
return
}
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
const clientHeight = document.documentElement.clientHeight
if (scrollTop + clientHeight >= scrollHeight - 120) {
page.value += 1
appendPopularItems(true)
}
}
const handleUserClick = () => {
if (isLoggedIn.value) {
router.push('/profile')
return
}
message.info('登录后可查看个人中心、收藏和订单')
router.push('/')
}
const handleSearch = () => {
const keyword = searchQuery.value.trim()
router.push(keyword ? { path: '/products', query: { keyword } } : '/products')
}
const handleSeeAll = (type: 'featured' | 'popular') => {
router.push({
path: '/products',
query: type === 'featured' ? { tag: '精选' } : { tag: '热门' }
})
}
const handleProductClick = (item: ProductCardItem) => {
router.push(`/product/${item.id}`)
}
const openShopById = (shopId: IdType) => {
router.push(`/shop/${shopId}`)
}
onMounted(async () => {
await Promise.all([
loadUserInfo(),
loadPublicShops(),
loadFeaturedProducts(),
loadPopularProducts()
])
window.addEventListener('scroll', handleScroll)
})
onUnmounted(() => {
window.removeEventListener('scroll', handleScroll)
})
</script>
<style scoped>
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px 20px 8px;
}
.user-info {
display: flex;
align-items: center;
gap: 12px;
cursor: pointer;
}
.greeting {
font-size: 12px;
color: #8b8b9a;
margin: 0 0 2px;
}
.username {
font-size: 16px;
font-weight: 700;
margin: 0;
color: #1f1f1f;
}
.header-action {
border-radius: 999px;
}
.search-section {
padding: 8px 20px 0;
}
.guest-alert {
margin: 16px 20px 0;
border-radius: 16px;
}
.banner-container {
padding: 0 20px;
}
.banner-carousel {
width: 100%;
border-radius: 18px;
overflow: hidden;
min-height: 220px;
box-shadow: 0 12px 30px rgba(15, 23, 42, 0.12);
background: linear-gradient(135deg, #f4f7ff 0%, #eef4ff 100%);
}
.banner-slide {
position: relative;
width: 100%;
aspect-ratio: 16 / 9;
cursor: pointer;
}
.banner-img {
width: 100%;
height: 100%;
object-fit: cover;
}
.banner-copy {
position: absolute;
left: 24px;
bottom: 24px;
padding: 16px 18px;
border-radius: 16px;
background: rgba(255, 255, 255, 0.92);
backdrop-filter: blur(6px);
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
}
.banner-copy h3 {
margin: 10px 0 4px;
font-size: 22px;
color: #1f1f1f;
}
.banner-copy p {
margin: 0;
color: #666;
}
.banner-empty {
min-height: 220px;
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
gap: 12px;
padding: 28px;
}
.banner-empty h3 {
margin: 0;
font-size: 26px;
color: #1f1f1f;
}
.banner-empty p {
margin: 0;
max-width: 360px;
color: #666;
line-height: 1.7;
}
.section {
padding: 24px 0 0;
}
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 20px 14px;
}
.section-header h3 {
margin: 0;
font-size: 18px;
font-weight: 700;
}
.see-all {
color: #1677ff;
font-size: 13px;
}
.horizontal-scroll {
display: flex;
gap: 14px;
overflow-x: auto;
padding: 0 20px;
scrollbar-width: none;
}
.horizontal-scroll::-webkit-scrollbar {
display: none;
}
.product-card {
width: 152px;
flex-shrink: 0;
border-radius: 18px;
}
.product-card :deep(.ant-card-body) {
padding: 12px;
}
.product-img {
width: 100%;
aspect-ratio: 1;
border-radius: 14px;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 10px;
font-size: 40px;
font-weight: 700;
color: rgba(0, 0, 0, 0.15);
}
.product-cover {
width: 100%;
height: 100%;
object-fit: cover;
}
.name {
margin: 0 0 4px;
font-size: 14px;
font-weight: 600;
color: #1f1f1f;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.meta {
margin: 0 0 6px;
font-size: 12px;
color: #8b8b9a;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.price {
margin: 0;
font-size: 16px;
font-weight: 700;
color: #ff4d4f;
}
.product-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
padding: 0 20px;
}
.grid-item {
width: 100%;
}
.loading-more,
.no-more,
.no-products {
display: flex;
justify-content: center;
align-items: center;
gap: 8px;
padding: 24px 0 36px;
color: #8b8b9a;
}
@media (min-width: 992px) {
.header,
.search-section,
.section,
.guest-alert {
max-width: var(--frontend-content-max-width);
margin-left: auto;
margin-right: auto;
}
.banner-container {
padding: 0 24px;
}
.banner-carousel {
max-width: var(--frontend-content-max-width);
}
.horizontal-scroll {
overflow: visible;
flex-wrap: wrap;
}
.product-card {
flex: 1 1 calc(25% - 12px);
width: calc(25% - 12px);
min-width: 180px;
}
.product-grid {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
}
</style>
-138
View File
@@ -1,138 +0,0 @@
<template>
<div class="not-found-container">
<div class="not-found-content">
<div class="error-code">404</div>
<h1>页面不存在</h1>
<p>您访问的页面不存在或已被删除</p>
<p class="redirect-message">
将在 <span class="countdown">{{ countdown }}</span> 秒后自动跳转到首页...
</p>
<a-button type="primary" @click="redirectToHome">立即前往首页</a-button>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const countdown = ref(5)
let timer: number | null = null
const redirectToHome = () => {
if (timer) {
clearInterval(timer)
}
router.push('/home')
}
onMounted(() => {
timer = window.setInterval(() => {
if (countdown.value > 0) {
countdown.value--
} else {
if (timer) {
clearInterval(timer)
}
redirectToHome()
}
}, 1000)
})
onUnmounted(() => {
if (timer) {
clearInterval(timer)
}
})
</script>
<style scoped>
.not-found-container {
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 20px;
}
.not-found-content {
background: white;
border-radius: 20px;
padding: 60px 40px;
text-align: center;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
max-width: 500px;
width: 100%;
}
.error-code {
font-size: 120px;
font-weight: bold;
color: #667eea;
margin: 0 0 20px 0;
line-height: 1;
}
.not-found-content h1 {
font-size: 28px;
font-weight: 700;
color: #333;
margin: 0 0 16px 0;
}
.not-found-content p {
font-size: 16px;
color: #666;
margin: 0 0 24px 0;
line-height: 1.6;
}
.redirect-message {
margin: 20px 0 30px 0;
color: #999;
font-size: 14px;
}
.countdown {
color: #667eea;
font-weight: bold;
font-size: 18px;
margin: 0 4px;
}
:deep(.ant-btn-primary) {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: none;
padding: 12px 32px;
font-size: 16px;
font-weight: 600;
border-radius: 25px;
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
transition: all 0.3s ease;
}
:deep(.ant-btn-primary:hover) {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}
@media (max-width: 768px) {
.not-found-content {
padding: 40px 20px;
}
.error-code {
font-size: 80px;
}
.not-found-content h1 {
font-size: 24px;
}
.not-found-content p {
font-size: 14px;
}
}
</style>
-131
View File
@@ -1,131 +0,0 @@
<template>
<div class="page">
<header class="header">
<a-button type="text" @click="router.back()">
<LeftOutlined :style="{ fontSize: '20px' }" />
</a-button>
<h1>我的订单</h1>
<div class="placeholder" />
</header>
<main class="content">
<a-empty v-if="!orders.length" description="暂无订单">
<a-button type="primary" @click="router.push('/products')">去逛逛</a-button>
</a-empty>
<a-card v-for="order in orders" :key="order.id" class="order-card">
<div class="order-head">
<span>订单号:{{ order.orderNo }}</span>
<span class="status" :class="statusClass(order.status)">{{ order.statusText }}</span>
</div>
<div v-for="item in order.items" :key="item.id" class="item">
<div class="thumb">
<img v-if="item.productImage" :src="item.productImage" :alt="item.productTitle" />
<span v-else>{{ item.productTitle[0] }}</span>
</div>
<div class="main">
<div class="title">{{ item.productTitle }}</div>
<div class="line">¥{{ item.price.toFixed(2) }} x {{ item.quantity }}</div>
<div v-if="item.artistName" class="line">美甲师:{{ item.artistName }}</div>
<div v-if="item.appointmentTime" class="line appointment">预约时间:{{ item.appointmentTime }}</div>
</div>
</div>
<div class="footer">
<span>总计:¥{{ order.actualAmount.toFixed(2) }}</span>
<a-button v-if="order.status === 1" size="small" danger @click="cancelOrder(order.id)">取消订单</a-button>
</div>
</a-card>
</main>
</div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { fileApi } from '../api/index'
import { orderApi } from '../api/order'
import type { IdType } from '@/utils/id'
const router = useRouter()
const orders = ref<any[]>([])
const imageIdCache = ref<Record<string, string>>({})
const statusClass = (status: number) => {
if (status === 1) return 'pending'
if (status === 2) return 'completed'
return 'cancelled'
}
const loadOrders = async () => {
try {
orders.value = (await orderApi.getOrderList() as unknown as any[]) || []
for (const order of orders.value) {
for (const item of order.items || []) {
const match = item.productImage?.replace(/<[^>]*>/g, '').match(/\/api\/file\/get\/(\d+)/)
if (!match?.[1]) continue
const imageId = match[1]
try {
if (!imageIdCache.value[imageId]) imageIdCache.value[imageId] = await fileApi.getSignedUrl(imageId) as any
item.productImage = imageIdCache.value[imageId]
} catch {
item.productImage = ''
}
}
}
} catch {
message.error('获取订单列表失败')
}
}
const cancelOrder = (orderId: IdType) => {
Modal.confirm({
title: '确认取消订单',
content: '确定要取消这个订单吗?',
onOk: async () => {
try {
await orderApi.cancelOrder(orderId)
message.success('订单已取消')
await loadOrders()
} catch {
message.error('取消订单失败')
}
}
})
}
onMounted(loadOrders)
</script>
<style scoped>
.page { min-height: 100vh; padding-top: 60px; background: #f5f5f5; }
.header { position: fixed; top: 0; left: 0; right: 0; z-index: 10; display: flex; align-items: center; justify-content: space-between; padding: 10px 15px; background: #fff; border-bottom: 1px solid #f0f0f0; }
.header h1 { margin: 0; font-size: 18px; }
.placeholder { width: 40px; height: 40px; }
.content { padding: 15px; }
.order-card { margin-bottom: 12px; border-radius: 12px; }
.order-head, .footer { display: flex; align-items: center; justify-content: space-between; }
.order-head { margin-bottom: 12px; padding-bottom: 10px; border-bottom: 1px solid #f0f0f0; }
.status { padding: 4px 10px; border-radius: 999px; font-size: 12px; font-weight: 600; }
.pending { background: #fff7e6; color: #fa8c16; }
.completed { background: #f6ffed; color: #52c41a; }
.cancelled { background: #fff1f0; color: #ff4d4f; }
.item { display: flex; gap: 12px; margin-bottom: 12px; }
.thumb { width: 60px; height: 60px; border-radius: 8px; overflow: hidden; display: flex; align-items: center; justify-content: center; background: #eef3ff; }
.thumb img { width: 100%; height: 100%; object-fit: cover; }
.main { flex: 1; }
.title { font-weight: 600; }
.line { margin-top: 4px; color: #666; font-size: 13px; }
.appointment { color: #1890ff; }
@media (min-width: 992px) {
.content {
max-width: 980px;
margin: 0 auto;
padding: 24px;
}
}
</style>
-299
View File
@@ -1,299 +0,0 @@
<template>
<div class="mobile-container">
<header class="header">
<a-button class="back-btn" type="text" @click="handleBackClick">
<LeftOutlined :style="{ fontSize: '20px' }" />
</a-button>
<h1>设置密码</h1>
<div class="empty"></div>
</header>
<div class="password-form">
<a-card :bordered="false" class="form-card">
<DraftActions
:saved-at="draftSavedAt"
@save="handleSaveDraft"
@clear="handleClearDraft"
/>
<a-form
ref="formRef"
:model="formState"
:rules="formRules"
layout="vertical"
@finish="handleSubmit"
>
<a-form-item label="手机号">
<a-input :value="userPhone || '未绑定手机号'" disabled size="large" />
</a-form-item>
<a-form-item label="验证码" name="verificationCode">
<a-input
v-model:value="formState.verificationCode"
placeholder="请输入验证码"
size="large"
>
<template #suffix>
<a-button
type="link"
:disabled="countdown > 0 || !userPhone"
@click="handleSendVerificationCode"
>
{{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
</a-button>
</template>
</a-input>
</a-form-item>
<a-form-item label="新密码" name="password">
<a-input-password
v-model:value="formState.password"
placeholder="请输入新密码"
size="large"
@pressEnter="handleSubmit"
>
<template #prefix>
<LockOutlined style="color: #999" />
</template>
</a-input-password>
<div class="password-tip">
密码长度至少 8 位,且需包含字母和数字
</div>
</a-form-item>
<a-form-item label="确认密码" name="confirmPassword">
<a-input-password
v-model:value="formState.confirmPassword"
placeholder="请再次输入新密码"
size="large"
@pressEnter="handleSubmit"
>
<template #prefix>
<LockOutlined style="color: #999" />
</template>
</a-input-password>
</a-form-item>
<a-form-item>
<a-button
type="primary"
html-type="submit"
size="large"
block
:loading="loading"
>
确认设置
</a-button>
</a-form-item>
</a-form>
</a-card>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { LeftOutlined, LockOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import DraftActions from '@/components/DraftActions.vue'
import { userApi } from '@/api/user'
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)
const countdown = ref(0)
const userInfo = ref<{ phone?: string } | null>(null)
const draftSavedAt = ref<number | null>(null)
let countdownTimer: ReturnType<typeof setInterval> | null = null
const formState = reactive({
verificationCode: '',
password: '',
confirmPassword: ''
})
const draftKey = buildDraftStorageKey('password-settings', 'set-password')
const restoreDraft = () => {
const draft = loadDraftRecord<typeof formState>(draftKey, 'session')
if (!draft) {
draftSavedAt.value = null
return
}
Object.assign(formState, draft.payload)
draftSavedAt.value = draft.savedAt
message.success('已恢复暂存内容')
}
const handleSaveDraft = () => {
const draft = saveDraftRecord(draftKey, { ...formState }, 'session')
draftSavedAt.value = draft.savedAt
message.success('已暂存到当前会话')
}
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(draftKey, 'session')
draftSavedAt.value = null
if (showMessage) {
message.success('已清除暂存')
}
}
const userPhone = computed(() => userInfo.value?.phone || '')
const validateConfirmPassword = (_rule: any, value: string) => {
if (value !== formState.password) {
return Promise.reject(new Error('两次输入的密码不一致'))
}
return Promise.resolve()
}
const formRules: Record<string, Rule[]> = {
verificationCode: [
{ required: true, message: '请输入验证码', trigger: 'blur' },
{ pattern: /^\d{6}$/, message: '验证码必须是6位数字', trigger: 'blur' }
],
password: [
{ required: true, message: '请输入新密码', trigger: 'blur' },
{ min: 8, message: '密码长度至少8位', trigger: 'blur' },
{ pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,}$/, message: '密码必须包含字母和数字', trigger: 'blur' }
],
confirmPassword: [
{ required: true, message: '请确认新密码', trigger: 'blur' },
{ validator: validateConfirmPassword, trigger: 'blur' }
]
}
const startCountdown = () => {
countdown.value = 60
if (countdownTimer) {
clearInterval(countdownTimer)
}
countdownTimer = setInterval(() => {
countdown.value -= 1
if (countdown.value <= 0 && countdownTimer) {
clearInterval(countdownTimer)
countdownTimer = null
}
}, 1000)
}
const fetchUserInfo = async () => {
try {
const res = await userApi.getUserInfo()
userInfo.value = res as unknown as { phone?: string }
} catch (error: any) {
console.error('获取用户信息失败:', error)
message.error(error.message || '获取用户信息失败')
}
}
const handleSendVerificationCode = async () => {
if (!userPhone.value) {
message.error('请先绑定手机号')
return
}
try {
await userApi.sendVerificationCode({ phone: userPhone.value })
message.success('验证码发送成功')
startCountdown()
} catch (error: any) {
console.error('发送验证码失败:', error)
message.error(error.message || '发送验证码失败')
}
}
const handleSubmit = async () => {
if (!formRef.value) return
try {
await formRef.value.validate()
if (!userPhone.value) {
message.error('请先绑定手机号')
return
}
loading.value = true
await userApi.updatePassword({
password: formState.password,
verificationCode: formState.verificationCode
})
message.success('密码设置成功')
handleClearDraft(false)
localStorage.removeItem('needSetPassword')
router.push('/profile')
} catch (error: any) {
console.error('设置密码失败:', error)
message.error(error.message || '设置密码失败')
} finally {
loading.value = false
}
}
const handleBackClick = () => {
router.back()
}
onMounted(() => {
fetchUserInfo()
restoreDraft()
})
onUnmounted(() => {
if (countdownTimer) {
clearInterval(countdownTimer)
}
})
</script>
<style scoped>
.mobile-container {
min-height: 100vh;
background: #f5f5f5;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 15px;
background: white;
border-bottom: 1px solid #f0f0f0;
}
.header h1 {
font-size: 18px;
font-weight: bold;
margin: 0;
}
.back-btn,
.empty {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
}
.password-form {
padding: 15px;
}
.form-card {
border-radius: 16px;
overflow: hidden;
background: white;
}
.password-tip {
margin-top: 8px;
color: #999;
font-size: 12px;
}
</style>
-682
View File
@@ -1,682 +0,0 @@
<template>
<div class="mobile-container">
<header class="header">
<a-button type="text" @click="handleBackClick">
<LeftOutlined :style="{ fontSize: '20px' }" />
</a-button>
<h1>{{ product.title || product.name || '作品详情' }}</h1>
<a-button type="text" @click="handleFavoriteClick">
<component :is="isFavorite ? StarFilled : StarOutlined" :class="['header-star', { active: isFavorite }]" />
</a-button>
</header>
<main class="content">
<a-result
v-if="loadError"
status="warning"
title="暂时无法查看作品详情"
:sub-title="loadError"
>
<template #extra>
<a-button type="primary" @click="handleBackClick">返回上一页</a-button>
</template>
</a-result>
<template v-else>
<section class="hero-card">
<a-carousel v-if="productImages.length > 1" autoplay dots>
<div v-for="(image, index) in productImages" :key="index" class="carousel-slide">
<img :src="image" :alt="product.title || product.name" class="product-image" />
</div>
</a-carousel>
<div v-else class="single-image">
<img :src="productImages[0] || DEFAULT_PRODUCT_IMAGE" :alt="product.title || product.name" class="product-image" />
</div>
</section>
<section class="info-card">
<div class="info-header">
<div>
<h2 class="product-name">{{ product.title || product.name }}</h2>
<p class="product-price">¥{{ Number(product.price || 0).toFixed(2) }}</p>
</div>
<a-tag color="blue">{{ product.approximateDuration || '时长待确认' }}</a-tag>
</div>
<div class="metric-row">
<button class="metric-card" type="button" @click="openShopDetail" :disabled="!shopInfo?.id">
<ShopOutlined />
<div>
<span class="metric-label">所属门店</span>
<strong>{{ shopInfo?.shopName || '暂未绑定门店' }}</strong>
</div>
</button>
<div class="metric-card">
<TeamOutlined />
<div>
<span class="metric-label">可约美甲师</span>
<strong>{{ artistCountText }}</strong>
</div>
</div>
<div class="metric-card">
<CalendarOutlined />
<div>
<span class="metric-label">最早可约</span>
<strong>{{ earliestBookableText }}</strong>
</div>
</div>
</div>
<div v-if="shopInfo" class="shop-summary" @click="openShopDetail">
<div class="shop-summary-title">{{ shopInfo.shopName }}</div>
<div class="shop-summary-text">{{ shopInfo.address || '门店地址待完善' }}</div>
<div class="shop-summary-text">{{ shopInfo.businessHours || '营业时间待完善' }}</div>
</div>
<div class="stats-row">
<button type="button" class="stat-btn" @click="handleLikeClick">
<component :is="isLiked ? HeartFilled : HeartOutlined" :class="{ active: isLiked }" />
<span>{{ product.likeCount || 0 }} 点赞</span>
</button>
<button type="button" class="stat-btn" @click="handleFavoriteClick">
<component :is="isFavorite ? StarFilled : StarOutlined" :class="{ active: isFavorite }" />
<span>{{ product.collectCount || 0 }} 收藏</span>
</button>
<div class="stat-btn static">
<ClockCircleOutlined />
<span>{{ product.approximateDuration || '时长待定' }}</span>
</div>
</div>
<div class="tags">
<a-tag
v-for="tag in product.tagInfos || []"
:key="tag.id"
:style="{
color: tag.textColor || '#333',
backgroundColor: tag.bgColor || '#f0f0f0',
borderColor: tag.borderColor || '#f0f0f0'
}"
>
{{ tag.tagName }}
</a-tag>
<a-tag v-if="!product.tagInfos?.length" color="default">暂无标签</a-tag>
</div>
<div class="description-block">
<h3>作品介绍</h3>
<p>{{ product.description || '店家还没补充作品说明。' }}</p>
</div>
</section>
</template>
</main>
<footer v-if="!loadError" class="action-buttons">
<a-button class="add-cart-btn" size="large" @click="handleAddToCart">
<ShoppingCartOutlined />
加入购物车
</a-button>
<a-button class="buy-now-btn" type="primary" size="large" @click="handleBuyNow">
<ThunderboltOutlined />
立即预约
</a-button>
</footer>
</div>
</template>
<script setup lang="ts">
import { computed, inject, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
CalendarOutlined,
ClockCircleOutlined,
HeartFilled,
HeartOutlined,
LeftOutlined,
ShoppingCartOutlined,
ShopOutlined,
StarFilled,
StarOutlined,
TeamOutlined,
ThunderboltOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { cartApi } from '@/api/cart'
import { fileApi } from '@/api/file'
import { productApi, type ProductVO } from '@/api/product'
import { productLikeApi } from '@/api/productLike'
import { shopApi, type ShopVO } from '@/api/shop'
import { wishlistApi } from '@/api/wishlist'
import { DEFAULT_PRODUCT_IMAGE } from '@/constants'
import type { IdType } from '@/utils/id'
import { toOptionalIdString } from '@/utils/id'
const route = useRoute()
const router = useRouter()
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
const product = ref<ProductVO>({} as ProductVO)
const shopInfo = ref<ShopVO | null>(null)
const productImages = ref<string[]>([])
const imageIdCache = ref<Record<string, string>>({})
const isFavorite = ref(false)
const isLiked = ref(false)
const loadError = ref('')
const isLoggedIn = computed(() => Boolean(localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')))
const artistCount = computed(() => {
if (typeof product.value.availableBookableArtistCount === 'number') {
return product.value.availableBookableArtistCount
}
const rawValue = product.value.bookableArtists || ''
return rawValue
.split(',')
.map(id => id.trim())
.filter(Boolean).length
})
const artistCountText = computed(() => {
if (artistCount.value > 0) {
return `${artistCount.value} 位`
}
return product.value.bookableArtistRestricted ? '暂无' : '门店安排'
})
const earliestBookableText = computed(() => estimateEarliestBookable(shopInfo.value?.businessHours))
const parseTimeRange = (businessHours?: string): { start: string; end: string } | null => {
if (!businessHours) {
return null
}
const normalized = businessHours.replace(/\s+/g, '')
const matched = normalized.match(/(\d{1,2}:\d{2}).*?(\d{1,2}:\d{2})/)
if (!matched) {
return null
}
const [, start, end] = matched
if (!start || !end) {
return null
}
return { start, end }
}
const formatDateTime = (date: Date) => {
const month = `${date.getMonth() + 1}`.padStart(2, '0')
const day = `${date.getDate()}`.padStart(2, '0')
const hour = `${date.getHours()}`.padStart(2, '0')
const minute = `${date.getMinutes()}`.padStart(2, '0')
return `${month}-${day} ${hour}:${minute}`
}
const estimateEarliestBookable = (businessHours?: string) => {
const timeRange = parseTimeRange(businessHours)
if (!timeRange) {
return businessHours || '以门店安排为准'
}
const startParts = timeRange.start.split(':').map(Number)
const endParts = timeRange.end.split(':').map(Number)
const startHour = startParts[0]
const startMinute = startParts[1]
const endHour = endParts[0]
const endMinute = endParts[1]
if ([startHour, startMinute, endHour, endMinute].some(value => value === undefined || Number.isNaN(value))) {
return businessHours || '以门店安排为准'
}
const safeStartHour = startHour ?? 0
const safeStartMinute = startMinute ?? 0
const safeEndHour = endHour ?? 0
const safeEndMinute = endMinute ?? 0
const candidate = new Date(Date.now() + 30 * 60 * 1000)
const openTime = new Date(candidate)
openTime.setHours(safeStartHour, safeStartMinute, 0, 0)
const closeTime = new Date(candidate)
closeTime.setHours(safeEndHour, safeEndMinute, 0, 0)
if (candidate <= openTime) {
return `今天 ${timeRange.start}`
}
if (candidate >= closeTime) {
const nextOpen = new Date(openTime)
nextOpen.setDate(nextOpen.getDate() + 1)
return `明天 ${timeRange.start}`
}
return formatDateTime(candidate)
}
const requireLogin = (actionText: string) => {
if (isLoggedIn.value) {
return true
}
message.info(`${actionText}前请先登录`)
router.push('/')
return false
}
const loadProductImages = async () => {
const fileIds = product.value.imageFileIds?.split(',').map(id => id.trim()).filter(Boolean) || []
if (!fileIds.length) {
productImages.value = [DEFAULT_PRODUCT_IMAGE]
return
}
const urls: string[] = []
for (const id of fileIds) {
try {
if (!imageIdCache.value[id]) {
imageIdCache.value[id] = await fileApi.getSignedUrl(id) as unknown as string
}
if (imageIdCache.value[id]) {
urls.push(imageIdCache.value[id])
}
} catch (error) {
console.error('获取作品图片失败:', error)
}
}
productImages.value = urls.length ? urls : [DEFAULT_PRODUCT_IMAGE]
}
const loadShopInfo = async (shopId?: IdType | null) => {
if (!shopId) {
shopInfo.value = null
return
}
try {
const response = await shopApi.getShopById(shopId)
shopInfo.value = response || null
} catch (error) {
console.error('获取门店信息失败:', error)
shopInfo.value = null
}
}
const checkWishlistStatus = async () => {
if (!isLoggedIn.value || !product.value.id) {
isFavorite.value = false
return
}
try {
const status = await wishlistApi.checkWishlist(product.value.id)
isFavorite.value = Boolean(status)
} catch (error) {
console.error('获取收藏状态失败:', error)
isFavorite.value = false
}
}
const checkLikeStatus = async () => {
if (!isLoggedIn.value || !product.value.id) {
isLiked.value = false
return
}
try {
const status = await productLikeApi.checkLikeStatus(product.value.id)
isLiked.value = Boolean(status)
} catch (error) {
console.error('获取点赞状态失败:', error)
isLiked.value = false
}
}
const resolveLoadError = (error: any) => {
const status = error?.response?.status
if (status === 404) {
return '这件作品可能已下架或不存在。'
}
if (status === 401) {
return '作品详情暂时无法加载,请稍后重试。'
}
return error?.message || '网络有点忙,请稍后再试。'
}
const fetchProductDetail = async () => {
loadError.value = ''
try {
const productId = toOptionalIdString(route.params.id)
if (!productId) {
throw new Error('作品ID不存在')
}
const response = await productApi.getProductById(productId)
if (!response?.id) {
throw new Error('未找到对应作品')
}
product.value = response
await Promise.all([
loadProductImages(),
loadShopInfo(response.shopId),
checkWishlistStatus(),
checkLikeStatus()
])
} catch (error) {
console.error('获取作品详情失败:', error)
loadError.value = resolveLoadError(error)
}
}
const handleBackClick = () => {
router.back()
}
const openShopDetail = () => {
if (!shopInfo.value?.id) {
return
}
router.push(`/shop/${shopInfo.value.id}`)
}
const handleFavoriteClick = async () => {
if (!product.value.id || !requireLogin('收藏作品')) {
return
}
try {
if (isFavorite.value) {
await wishlistApi.removeFromWishlist(product.value.id)
product.value.collectCount = Math.max(0, Number(product.value.collectCount || 0) - 1)
message.success('已取消收藏')
} else {
await wishlistApi.addToWishlist(product.value.id)
product.value.collectCount = Number(product.value.collectCount || 0) + 1
message.success('已加入收藏')
}
isFavorite.value = !isFavorite.value
} catch (error) {
console.error('收藏操作失败:', error)
message.error('收藏操作失败,请稍后重试')
}
}
const handleLikeClick = async () => {
if (!product.value.id || !requireLogin('点赞作品')) {
return
}
try {
if (isLiked.value) {
await productLikeApi.unlikeProduct(product.value.id)
product.value.likeCount = Math.max(0, Number(product.value.likeCount || 0) - 1)
message.success('已取消点赞')
} else {
await productLikeApi.likeProduct(product.value.id)
product.value.likeCount = Number(product.value.likeCount || 0) + 1
message.success('已点赞')
}
isLiked.value = !isLiked.value
} catch (error) {
console.error('点赞操作失败:', error)
message.error('点赞操作失败,请稍后重试')
}
}
const handleAddToCart = async () => {
if (!product.value.id || !requireLogin('加入购物车')) {
return
}
try {
await cartApi.addToCart({ productId: product.value.id, quantity: 1 })
await updateCartCount()
message.success(`已将 ${product.value.title || product.value.name || '作品'} 加入购物车`)
} catch (error) {
console.error('加入购物车失败:', error)
message.error('加入购物车失败,请稍后重试')
}
}
const handleBuyNow = async () => {
if (!product.value.id || !requireLogin('预约下单')) {
return
}
try {
await cartApi.addToCart({ productId: product.value.id, quantity: 1 })
await updateCartCount()
router.push('/cart')
} catch (error) {
console.error('立即预约失败:', error)
message.error('操作失败,请稍后重试')
}
}
onMounted(() => {
void fetchProductDetail()
})
</script>
<style scoped>
.mobile-container {
min-height: 100vh;
background: #f5f5f5;
}
.header {
position: sticky;
top: 0;
z-index: 100;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 10px 16px;
background: rgba(255, 255, 255, 0.96);
backdrop-filter: blur(10px);
border-bottom: 1px solid #f0f0f0;
}
.header h1 {
flex: 1;
margin: 0;
font-size: 18px;
font-weight: 700;
text-align: center;
}
.header-star {
font-size: 20px;
color: #8b8b9a;
}
.header-star.active {
color: #f7b500;
}
.content {
padding: 16px 16px 108px;
}
.hero-card,
.info-card {
max-width: 1040px;
margin: 0 auto 16px;
border-radius: 20px;
overflow: hidden;
background: white;
box-shadow: 0 10px 30px rgba(15, 23, 42, 0.08);
}
.carousel-slide,
.single-image {
aspect-ratio: 16 / 11;
overflow: hidden;
}
.product-image {
width: 100%;
height: 100%;
object-fit: cover;
}
.info-card {
padding: 24px;
}
.info-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 16px;
}
.product-name {
margin: 0 0 8px;
font-size: 26px;
font-weight: 700;
color: #1f1f1f;
}
.product-price {
margin: 0;
font-size: 28px;
font-weight: 700;
color: #ff4d4f;
}
.metric-row {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 12px;
margin-top: 20px;
}
.metric-card {
display: flex;
align-items: center;
gap: 10px;
width: 100%;
padding: 14px;
border: 1px solid #edf0f5;
border-radius: 16px;
background: #fafcff;
text-align: left;
}
.metric-card:disabled {
cursor: default;
}
.metric-card :deep(svg) {
font-size: 18px;
color: #1677ff;
}
.metric-label {
display: block;
font-size: 12px;
color: #8b8b9a;
}
.metric-card strong {
font-size: 14px;
color: #1f1f1f;
}
.shop-summary {
margin-top: 18px;
padding: 16px 18px;
border-radius: 18px;
background: linear-gradient(135deg, #f8fbff 0%, #eef4ff 100%);
cursor: pointer;
}
.shop-summary-title {
font-size: 16px;
font-weight: 700;
color: #1f1f1f;
}
.shop-summary-text {
margin-top: 6px;
color: #666;
line-height: 1.6;
}
.stats-row {
display: flex;
gap: 12px;
margin-top: 20px;
}
.stat-btn {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 10px 14px;
border: 1px solid #edf0f5;
border-radius: 999px;
background: white;
color: #666;
}
.stat-btn :deep(svg) {
font-size: 16px;
}
.stat-btn :deep(.active),
.stat-btn :deep(svg.active) {
color: #ff4d4f;
}
.stat-btn .active {
color: #ff4d4f;
}
.stat-btn.static {
cursor: default;
}
.tags {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 20px;
}
.description-block {
margin-top: 24px;
}
.description-block h3 {
margin: 0 0 12px;
font-size: 18px;
font-weight: 700;
}
.description-block p {
margin: 0;
color: #666;
line-height: 1.8;
}
.action-buttons {
position: fixed;
left: 0;
right: 0;
bottom: 0;
z-index: 120;
display: flex;
gap: 12px;
padding: 16px;
background: rgba(255, 255, 255, 0.96);
backdrop-filter: blur(10px);
border-top: 1px solid #f0f0f0;
}
.action-buttons :deep(.ant-btn) {
flex: 1;
height: 48px;
border-radius: 999px;
font-size: 15px;
font-weight: 700;
}
@media (max-width: 767px) {
.metric-row {
grid-template-columns: 1fr;
}
.stats-row {
flex-wrap: wrap;
}
}
</style>
-505
View File
@@ -1,505 +0,0 @@
<template>
<div class="mobile-container">
<header class="header">
<a-button class="back-btn" type="text" @click="handleBackClick">
<LeftOutlined :style="{ fontSize: '20px' }" />
</a-button>
<h1 v-if="!showSearch">作品列表</h1>
<div v-else class="search-input-container">
<a-input-search
v-model:value="searchKeyword"
placeholder="搜索作品"
class="search-input"
enter-button
@search="handleSearch"
/>
</div>
<a-button class="search-btn" type="text" @click="toggleSearch">
<SearchOutlined :style="{ fontSize: '20px' }" />
</a-button>
</header>
<div class="main-content">
<div class="category-sidebar">
<div
v-for="category in categories"
:key="category"
class="category-item"
:class="{ active: selectedCategory === category }"
@click="handleCategoryClick(category)"
>
{{ category }}
</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"
:key="item.id"
class="product-card"
:body-style="{ padding: '12px' }"
hoverable
@click="handleProductClick(item)"
>
<div class="product-img">
<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)?.[0] || '作' }}</span>
</div>
</div>
<div class="product-info">
<p class="name">{{ item.title || item.name }}</p>
<div class="product-meta">
<span class="duration">{{ item.approximateDuration || '时长待定' }}</span>
<div class="stats">
<span>{{ item.likeCount || 0 }} 点赞</span>
<span>{{ item.collectCount || 0 }} 收藏</span>
</div>
</div>
<div class="product-tags">
<template v-if="item.tagInfos?.length">
<a-tag
v-for="tag in item.tagInfos"
:key="tag.id"
size="small"
:style="{
marginRight: '4px',
marginBottom: '4px',
color: tag.textColor || '#333',
backgroundColor: tag.bgColor || '#f0f0f0',
borderColor: tag.borderColor || '#f0f0f0'
}"
>
{{ tag.tagName }}
</a-tag>
</template>
<a-tag v-else size="small" color="default">暂无标签</a-tag>
</div>
<div class="price-row">
<p class="price">¥{{ Number(item.price || 0).toFixed(2) }}</p>
<a-button
type="primary"
size="small"
shape="circle"
@click.stop="handleAddToCart(item)"
>
<ShoppingCartOutlined />
</a-button>
</div>
</div>
</a-card>
</div>
<div v-if="products.length === 0 && !loading" class="empty-state">
<a-empty description="暂时没有匹配的作品">
<a-button type="primary" @click="resetFilters">查看全部作品</a-button>
</a-empty>
</div>
<div v-if="loading" class="loading-state">
<a-spin />
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
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 allTags = ref<TagVO[]>([])
const categories = ref<string[]>(['全部'])
const selectedCategory = ref('全部')
const products = ref<ProductVO[]>([])
const loading = ref(false)
const showSearch = ref(false)
const searchKeyword = ref('')
const imageIdCache = ref<Record<string, string>>({})
const imageUrls = ref<Record<string, string[]>>({})
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[String(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(id) as unknown as string
}
if (imageIdCache.value[id]) {
urls.push(imageIdCache.value[id])
}
} catch (error) {
console.error('获取作品图片失败:', error)
}
}
imageUrls.value[String(product.id)] = urls.length ? urls : [DEFAULT_PRODUCT_IMAGE]
}
}
const getProductImages = (product: ProductVO): string[] => imageUrls.value[String(product.id)] || [DEFAULT_PRODUCT_IMAGE]
const fetchTags = async () => {
try {
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 fetchProducts = async () => {
loading.value = true
try {
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)
}
products.value = Array.isArray(response) ? response : []
await loadImageUrls(products.value)
} catch (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('/home')
}
const handleCategoryClick = (category: string) => {
selectedCategory.value = category
searchKeyword.value = ''
showSearch.value = false
router.replace({
path: '/products',
query: category === '全部' ? {} : { tag: category }
})
}
const handleProductClick = (item: ProductVO) => {
router.push(`/product/${item.id}`)
}
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 || '作品'} 加入购物车`)
} catch (error) {
console.error('加入购物车失败:', error)
message.error('加入购物车失败,请稍后重试')
}
}
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 = ''
router.replace({ path: '/products', query: selectedCategory.value === '全部' ? {} : { tag: selectedCategory.value } })
}
}
const resetFilters = () => {
selectedCategory.value = '全部'
searchKeyword.value = ''
showSearch.value = false
router.replace('/products')
}
watch(
() => route.query,
async () => {
await syncRouteFilters()
},
{ deep: true }
)
onMounted(async () => {
await fetchTags()
await syncRouteFilters()
})
</script>
<style scoped>
.mobile-container {
padding-top: 60px;
min-height: 100vh;
background: #f5f5f5;
}
.header {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 100;
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 15px;
border-bottom: 1px solid #f0f0f0;
background: white;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
.header h1 {
margin: 0;
font-size: 18px;
font-weight: 700;
}
.back-btn,
.search-btn {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
}
.search-input-container {
flex: 1;
margin: 0 10px;
}
.main-content {
display: flex;
min-height: calc(100vh - 60px);
}
.category-sidebar {
width: 92px;
background: #fafafa;
border-right: 1px solid #ececec;
overflow-y: auto;
}
.category-item {
padding: 16px 12px;
font-size: 13px;
color: #666;
text-align: center;
cursor: pointer;
transition: all 0.2s ease;
border-left: 3px solid transparent;
}
.category-item.active {
color: #1677ff;
background: white;
border-left-color: #1677ff;
font-weight: 700;
}
.product-section {
flex: 1;
padding: 16px;
overflow-y: auto;
}
.page-banner {
margin-bottom: 16px;
border-radius: 14px;
}
.product-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
}
.product-card {
border-radius: 18px;
}
.product-img {
width: 100%;
aspect-ratio: 1;
overflow: hidden;
border-radius: 14px;
background: #eef3ff;
}
.product-image {
width: 100%;
height: 100%;
object-fit: cover;
}
.product-img-placeholder {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
font-size: 40px;
font-weight: 700;
color: rgba(0, 0, 0, 0.18);
}
.name {
margin: 12px 0 6px;
font-size: 14px;
font-weight: 700;
color: #1f1f1f;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.product-meta {
display: flex;
justify-content: space-between;
gap: 8px;
font-size: 12px;
color: #8b8b9a;
}
.duration {
display: inline-flex;
align-items: center;
padding: 2px 8px;
border-radius: 999px;
background: #f4f6fb;
}
.stats {
display: flex;
gap: 8px;
}
.product-tags {
margin: 10px 0;
min-height: 26px;
}
.price-row {
display: flex;
justify-content: space-between;
align-items: center;
}
.price {
margin: 0;
font-size: 18px;
font-weight: 700;
color: #ff4d4f;
}
.empty-state,
.loading-state {
padding: 56px 0;
}
@media (min-width: 992px) {
.main-content {
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(4, minmax(0, 1fr));
}
}
</style>
-872
View File
@@ -1,872 +0,0 @@
<template>
<div class="mobile-container">
<div class="header-bg"></div>
<header class="header">
<h1>个人中心</h1>
<a-button class="settings-btn" type="text" @click="handleSettingsClick">
<SettingOutlined :style="{ fontSize: '20px' }" />
</a-button>
</header>
<div class="profile-info">
<a-card :bordered="false" class="profile-card">
<div class="avatar-section">
<a-badge :dot="hasNotification" :offset="[-5, 5]">
<a-avatar :size="90" :src="userInfo.avatar || DEFAULT_AVATAR" class="user-avatar" />
</a-badge>
<div class="user-details">
<h2 class="username">{{ userInfo.nickname || '用户' }}</h2>
<p class="account">{{ userInfo.account }}</p>
<p class="signature" v-if="userInfo.signature">{{ userInfo.signature }}</p>
</div>
</div>
<div class="shop-card" @click="handleShopCardClick">
<div class="shop-icon-wrapper">
<ShopOutlined class="shop-icon" />
</div>
<div class="shop-content">
<p class="shop-label">当前登录门店</p>
<h3 class="shop-name">{{ currentShopName }}</h3>
<p class="shop-tip">{{ shopSwitchTip }}</p>
</div>
<div class="shop-arrow">
<RightOutlined />
</div>
</div>
<div v-if="needSetPassword" class="password-tip">
<a-alert
type="warning"
message="建议尽快设置密码"
description="你当前更适合使用手机号验证码登录,设置密码后账号会更方便也更安全。"
show-icon
>
<template #action>
<a-button size="small" type="primary" @click="handleSetPassword">去设置</a-button>
</template>
</a-alert>
</div>
<a-button type="primary" block @click="handleEditProfile" class="edit-btn">
编辑资料
</a-button>
</a-card>
</div>
<div class="stats-section">
<a-card :bordered="false" class="stats-card">
<a-row :gutter="16">
<a-col :span="8">
<div class="stat-item" @click="router.push('/orders')">
<div class="stat-icon orders">
<ShoppingOutlined />
</div>
<a-statistic title="订单" :value="orderCount" />
</div>
</a-col>
<a-col :span="8">
<div class="stat-item" @click="router.push('/wishlist')">
<div class="stat-icon wishlist">
<HeartOutlined />
</div>
<a-statistic title="收藏" :value="wishlistCount" />
</div>
</a-col>
<a-col :span="8">
<div class="stat-item" @click="router.push('/coupons')">
<div class="stat-icon coupons">
<CreditCardOutlined />
</div>
<a-statistic title="优惠券" :value="couponCount" />
</div>
</a-col>
</a-row>
</a-card>
</div>
<div class="menu-section">
<a-card :bordered="false" class="menu-card">
<a-list :data-source="menuItems" :split="false">
<template #renderItem="{ item }">
<a-list-item class="menu-item" @click="handleMenuClick(item.key)">
<template #actions>
<RightOutlined />
</template>
<a-list-item-meta>
<template #avatar>
<div class="menu-icon" :style="{ backgroundColor: item.bgColor }">
<component :is="item.icon" />
</div>
</template>
<template #title>
<span>{{ item.title }}</span>
</template>
<template #description v-if="item.desc">
<span>{{ item.desc }}</span>
</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
</a-card>
</div>
<div class="logout-section">
<a-button danger block @click="handleLogout">
退出登录
</a-button>
</div>
<a-modal
v-model:open="editModalVisible"
title="编辑资料"
@ok="handleSaveProfile"
@cancel="handleCancelEdit"
:confirmLoading="saving"
:ok-button-props="{ disabled: avatarUploadPending }"
>
<DraftActions
:saved-at="draftSavedAt"
:disabled="avatarUploadPending"
@save="handleSaveDraft"
@clear="handleClearDraft"
/>
<a-form layout="vertical">
<a-form-item label="头像">
<div class="avatar-upload-section">
<a-upload
name="file"
:show-upload-list="false"
:before-upload="beforeUploadAvatar"
:custom-request="handleAvatarUpload"
accept="image/*"
>
<a-avatar :size="80" :src="editForm.avatar || DEFAULT_AVATAR" />
<div class="upload-hint">点击更换头像</div>
</a-upload>
<a-progress
v-if="avatarUploadPending"
:percent="Math.round(avatarUploadProgress)"
size="small"
status="active"
class="avatar-upload-progress"
/>
<div v-if="avatarUploadPending" class="avatar-upload-status">头像上传中,上传完成前不可保存。</div>
<a-button v-if="editForm.avatar" type="text" danger size="small" @click="handleDeleteAvatar">
删除头像
</a-button>
</div>
</a-form-item>
<a-form-item label="昵称">
<a-input v-model:value="editForm.nickname" placeholder="请输入昵称" />
</a-form-item>
<a-form-item label="个性签名">
<a-textarea v-model:value="editForm.signature" placeholder="请输入个性签名" :rows="3" />
</a-form-item>
</a-form>
</a-modal>
<a-modal
v-model:open="shopSwitchVisible"
title="切换登录门店"
:confirm-loading="shopSwitchLoading"
@ok="handleConfirmSwitchShop"
>
<a-radio-group v-model:value="selectedShopId" class="shop-option-group">
<a-radio
v-for="shop in shopOptions"
:key="String(shop.id)"
:value="String(shop.id)"
class="shop-option"
>
<div class="shop-option-name">{{ shop.shopName }}</div>
</a-radio>
</a-radio-group>
<a-empty v-if="!shopOptions.length" description="当前账号没有可切换的门店" />
</a-modal>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import {
BellOutlined,
CreditCardOutlined,
HeartOutlined,
QuestionCircleOutlined,
RightOutlined,
SettingOutlined,
ShopOutlined,
ShoppingOutlined
} from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import type { UploadProps } from 'ant-design-vue'
import DraftActions from '@/components/DraftActions.vue'
import { authApi } from '@/api/auth'
import { couponApi } from '@/api/coupon'
import { fileApi } from '@/api/file'
import { orderApi } from '@/api/order'
import { userApi, type UserVO } from '@/api/user'
import { createChunkUploadTask, type ChunkUploadTask } from '@/utils/chunk-upload'
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
import { wishlistApi } from '@/api/wishlist'
import { DEFAULT_AVATAR } from '@/constants'
const router = useRouter()
const userInfo = ref<UserVO>({
id: 0,
nickname: '',
account: '',
avatar: '',
type: 0,
status: 0,
createTime: '',
updateTime: ''
})
const editModalVisible = ref(false)
const saving = ref(false)
const needSetPassword = ref(false)
const hasNotification = ref(false)
const orderCount = ref(0)
const couponCount = ref(0)
const wishlistCount = ref(0)
const shopSwitchVisible = ref(false)
const shopSwitchLoading = ref(false)
const selectedShopId = ref<string>()
const avatarUploadProgress = ref(0)
const avatarUploadPending = ref(false)
let avatarUploadTask: ChunkUploadTask<string> | null = null
const draftSavedAt = ref<number | null>(null)
const editForm = reactive({
nickname: '',
avatar: '',
signature: ''
})
const getDraftKey = () => buildDraftStorageKey('profile-edit')
const buildDraftPayload = () => ({
nickname: editForm.nickname,
avatar: editForm.avatar,
signature: editForm.signature
})
const restoreDraft = () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
if (!draft) {
draftSavedAt.value = null
return
}
Object.assign(editForm, draft.payload)
draftSavedAt.value = draft.savedAt
message.success('已恢复暂存内容')
}
const handleSaveDraft = () => {
if (avatarUploadPending.value) {
message.warning('头像上传完成后才能暂存')
return
}
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload())
draftSavedAt.value = draft.savedAt
message.success('已暂存到本地')
}
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey())
draftSavedAt.value = null
if (showMessage) {
message.success('已清除暂存')
}
}
const shopOptions = computed(() => {
const ids = userInfo.value.shopIds || []
const names = userInfo.value.shopNames || []
return ids.map((id, index) => ({
id,
shopName: names[index] || `门店 ${id}`
}))
})
const currentShopName = computed(() => userInfo.value.shopName || '暂未选择门店')
const shopSwitchTip = computed(() => {
if (shopOptions.value.length > 1) {
return `可切换 ${shopOptions.value.length} 家门店`
}
if (shopOptions.value.length === 1) {
return '点击查看当前门店详情'
}
return '当前账号暂无可切换门店'
})
const menuItems = [
{
key: 'orders',
title: '我的订单',
desc: '查看预约状态、取消订单',
icon: ShoppingOutlined,
bgColor: '#e6f7ff'
},
{
key: 'wishlist',
title: '我的收藏',
desc: '快速回到喜欢的作品',
icon: HeartOutlined,
bgColor: '#fff1f0'
},
{
key: 'coupons',
title: '我的优惠券',
desc: '查看可用优惠和 VIP 折扣',
icon: CreditCardOutlined,
bgColor: '#fff7e6'
},
{
key: 'notifications',
title: '消息通知',
desc: '消息中心功能开发中',
icon: BellOutlined,
bgColor: '#f9f0ff'
},
{
key: 'help',
title: '帮助与支持',
desc: '常见问题功能开发中',
icon: QuestionCircleOutlined,
bgColor: '#eef9ff'
}
]
const persistUserSession = (payload: any) => {
localStorage.setItem('accessToken', payload.accessToken)
localStorage.setItem('refreshToken', payload.refreshToken)
localStorage.setItem('userInfo', JSON.stringify(payload.userInfo))
sessionStorage.setItem('accessToken', payload.accessToken)
if (payload.needSetPassword) {
localStorage.setItem('needSetPassword', 'true')
} else {
localStorage.removeItem('needSetPassword')
}
}
const fetchUserInfo = async () => {
try {
const response = await userApi.getUserInfo()
userInfo.value = response
needSetPassword.value = localStorage.getItem('needSetPassword') === 'true'
selectedShopId.value = response.shopId ? String(response.shopId) : undefined
} catch (error) {
console.error('获取用户信息失败:', error)
message.error('获取用户信息失败')
}
}
const loadCounts = async () => {
try {
const [orders, coupons, wishlist] = await Promise.all([
orderApi.getOrderList(),
couponApi.listUserCoupons(),
wishlistApi.getWishlist()
])
orderCount.value = Array.isArray(orders) ? orders.length : 0
couponCount.value = Array.isArray(coupons) ? coupons.length : 0
wishlistCount.value = Array.isArray(wishlist) ? wishlist.length : 0
} catch (error) {
console.error('加载个人中心统计失败:', error)
}
}
const handleEditProfile = () => {
avatarUploadTask?.cancel()
avatarUploadTask = null
avatarUploadPending.value = false
avatarUploadProgress.value = 0
editForm.nickname = userInfo.value.nickname || ''
editForm.avatar = userInfo.value.avatar || ''
editForm.signature = userInfo.value.signature || ''
restoreDraft()
editModalVisible.value = true
}
const beforeUploadAvatar: UploadProps['beforeUpload'] = file => {
const isImage = file.type.startsWith('image/')
const isLt20M = file.size / 1024 / 1024 < 20
if (!isImage) {
message.error('只能上传图片文件')
}
if (!isLt20M) {
message.error('图片大小不能超过 20MB')
}
return isImage && isLt20M
}
const handleAvatarUpload = async (options: any) => {
const { file, onProgress, onSuccess, onError } = options
avatarUploadTask?.cancel()
avatarUploadProgress.value = 0
avatarUploadPending.value = true
const task = createChunkUploadTask({
file: file as File,
scene: 'profile-avatar',
api: {
initUpload: fileApi.initAvatarChunkUpload,
uploadChunk: fileApi.uploadAvatarChunk,
completeUpload: fileApi.completeAvatarChunkUpload,
cancelUpload: fileApi.cancelAvatarChunkUpload
},
onProgress: (percent) => {
avatarUploadProgress.value = percent
onProgress?.({ percent })
}
})
avatarUploadTask = task
try {
const { response } = await task.promise
editForm.avatar = response as unknown as string
avatarUploadProgress.value = 100
onSuccess?.({ url: response })
message.success('头像上传成功')
} catch (error) {
const errorMessage = (error as Error)?.message || '头像上传失败'
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
console.error('头像上传失败:', error)
message.error(errorMessage)
onError?.(error)
}
} finally {
if (avatarUploadTask === task) {
avatarUploadTask = null
avatarUploadPending.value = false
}
}
}
const handleDeleteAvatar = () => {
Modal.confirm({
title: '确认删除头像',
content: '删除后会恢复为默认头像。',
okText: '确认',
cancelText: '取消',
onOk: async () => {
editForm.avatar = ''
try {
await userApi.updateUserInfo({ avatar: '' })
userInfo.value.avatar = ''
message.success('头像删除成功')
} catch (error) {
console.error('删除头像失败:', error)
message.error('删除头像失败')
}
}
})
}
const handleSaveProfile = async () => {
if (!editForm.nickname.trim()) {
message.error('请输入昵称')
return
}
if (avatarUploadPending.value) {
message.warning('头像上传完成前不可保存')
return
}
saving.value = true
try {
await userApi.updateUserInfo({
nickname: editForm.nickname,
avatar: editForm.avatar,
signature: editForm.signature
})
message.success('资料更新成功')
handleClearDraft(false)
editModalVisible.value = false
await fetchUserInfo()
} catch (error) {
console.error('保存资料失败:', error)
message.error('保存资料失败')
} finally {
saving.value = false
}
}
const handleCancelEdit = () => {
avatarUploadTask?.cancel()
avatarUploadTask = null
avatarUploadPending.value = false
avatarUploadProgress.value = 0
editModalVisible.value = false
}
const handleShopCardClick = () => {
if (shopOptions.value.length > 1) {
shopSwitchVisible.value = true
return
}
if (userInfo.value.shopId) {
router.push(`/shop/${userInfo.value.shopId}`)
return
}
message.info('当前账号还没有可用门店')
}
const handleConfirmSwitchShop = async () => {
if (!selectedShopId.value) {
message.warning('请选择要切换的门店')
return
}
if (String(userInfo.value.shopId || '') === selectedShopId.value) {
shopSwitchVisible.value = false
return
}
shopSwitchLoading.value = true
try {
const response = await authApi.switchShop({ shopId: selectedShopId.value })
persistUserSession(response as any)
message.success('门店已切换')
shopSwitchVisible.value = false
await Promise.all([fetchUserInfo(), loadCounts()])
} catch (error: any) {
console.error('切换门店失败:', error)
message.error(error?.message || '切换门店失败')
} finally {
shopSwitchLoading.value = false
}
}
const handleMenuClick = (key: string) => {
if (key === 'orders') {
router.push('/orders')
} else if (key === 'wishlist') {
router.push('/wishlist')
} else if (key === 'coupons') {
router.push('/coupons')
} else if (key === 'notifications') {
message.info('消息通知功能开发中')
} else if (key === 'help') {
message.info('帮助中心功能开发中')
}
}
const handleLogout = () => {
Modal.confirm({
title: '确认退出登录',
content: '退出后需要重新登录才能继续下单和查看订单。',
okText: '确认',
cancelText: '取消',
onOk: async () => {
try {
await authApi.logout()
} catch (error) {
console.error('退出登录接口调用失败:', error)
} finally {
localStorage.removeItem('accessToken')
localStorage.removeItem('refreshToken')
localStorage.removeItem('userInfo')
localStorage.removeItem('needSetPassword')
sessionStorage.removeItem('accessToken')
message.success('已退出登录')
router.push('/')
}
}
})
}
const handleSettingsClick = () => {
router.push('/settings')
}
const handleSetPassword = () => {
router.push('/settings/password')
}
onMounted(async () => {
await Promise.all([fetchUserInfo(), loadCounts()])
})
</script>
<style scoped>
.mobile-container {
padding-top: 60px;
min-height: 100vh;
background: #f5f5f5;
position: relative;
}
.header-bg {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 200px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 45%, #f093fb 100%);
z-index: 0;
}
.header {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 100;
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 15px;
color: white;
}
.header h1 {
margin: 0;
font-size: 18px;
font-weight: 700;
}
.settings-btn {
color: white;
}
.profile-info,
.stats-section,
.menu-section,
.logout-section {
position: relative;
z-index: 1;
padding: 0 15px 15px;
}
.profile-info {
padding-top: 15px;
}
.profile-card,
.stats-card,
.menu-card {
border-radius: 22px;
box-shadow: 0 12px 30px rgba(15, 23, 42, 0.08);
}
.profile-card :deep(.ant-card-body) {
padding: 28px 24px 24px;
}
.avatar-section {
display: flex;
align-items: center;
gap: 18px;
}
.user-avatar {
border: 4px solid white;
}
.username {
margin: 0 0 6px;
font-size: 24px;
font-weight: 700;
color: #1a1a2e;
}
.account,
.signature {
margin: 0;
color: #7c7c8a;
line-height: 1.7;
}
.shop-card {
display: flex;
align-items: center;
gap: 14px;
margin-top: 24px;
padding: 18px;
border-radius: 18px;
background: linear-gradient(135deg, #f5f7ff 0%, #e8ecff 100%);
cursor: pointer;
}
.shop-icon-wrapper {
width: 52px;
height: 52px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 14px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.shop-icon {
font-size: 24px;
color: white;
}
.shop-content {
flex: 1;
}
.shop-label {
margin: 0 0 4px;
font-size: 12px;
color: #8b8b9a;
}
.shop-name {
margin: 0;
font-size: 18px;
font-weight: 700;
color: #1a1a2e;
}
.shop-tip {
margin: 6px 0 0;
color: #6b6b7a;
font-size: 13px;
}
.shop-arrow {
color: #c4c4d0;
}
.password-tip {
margin-top: 20px;
}
.edit-btn {
margin-top: 20px;
height: 48px;
border-radius: 14px;
font-size: 15px;
font-weight: 700;
}
.stats-card :deep(.ant-card-body) {
padding: 20px 16px;
}
.stat-item {
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
cursor: pointer;
}
.stat-icon {
width: 52px;
height: 52px;
border-radius: 16px;
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
color: white;
}
.stat-icon.orders {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.stat-icon.wishlist {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}
.stat-icon.coupons {
background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}
.menu-card :deep(.ant-card-body) {
padding: 0;
}
.menu-item {
padding: 18px 16px;
cursor: pointer;
border-bottom: 1px solid #f5f5f7;
}
.menu-item:last-child {
border-bottom: none;
}
.menu-icon {
width: 44px;
height: 44px;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
font-size: 20px;
color: white;
}
.logout-section :deep(.ant-btn-dangerous) {
height: 50px;
border-radius: 25px;
font-weight: 700;
font-size: 16px;
}
.avatar-upload-section {
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
}
.upload-hint {
font-size: 12px;
color: #667eea;
}
.avatar-upload-progress {
width: 220px;
margin-top: 4px;
}
.avatar-upload-status {
font-size: 12px;
color: #fa8c16;
}
.shop-option-group {
display: flex;
flex-direction: column;
gap: 12px;
}
.shop-option {
margin: 0;
padding: 12px 14px;
border: 1px solid #e8ecff;
border-radius: 14px;
}
.shop-option-name {
font-weight: 600;
}
@media (min-width: 992px) {
.profile-info,
.stats-section,
.menu-section,
.logout-section {
max-width: var(--frontend-content-max-width);
margin-left: auto;
margin-right: auto;
}
}
</style>
-274
View File
@@ -1,274 +0,0 @@
<template>
<div class="mobile-container">
<!-- 头部区域 -->
<header class="header">
<a-button class="back-btn" type="text" @click="handleBackClick">
<LeftOutlined :style="{ fontSize: '20px' }" />
</a-button>
<h1>设置</h1>
<div class="empty"></div>
</header>
<!-- 设置菜单 -->
<div class="settings-menu">
<a-card :bordered="false" class="settings-card">
<a-list :data-source="settingsSections" :split="false">
<template #renderItem="{ item }">
<!-- 分组标题 -->
<a-list-item class="section-title" v-if="item.type === 'title'">
<span>{{ item.title }}</span>
</a-list-item>
<!-- 设置项 -->
<a-list-item
v-else
class="setting-item"
@click="handleSettingClick(item.key)"
>
<template #actions>
<component :is="item.actionComponent" v-if="item.actionComponent" :props="item.actionProps" />
<RightOutlined v-else />
</template>
<a-list-item-meta>
<template #avatar>
<div class="setting-icon" :style="{ backgroundColor: item.bgColor }">
<component :is="item.icon" />
</div>
</template>
<template #title>
<span>{{ item.title }}</span>
</template>
<template #description v-if="item.desc">
<span>{{ item.desc }}</span>
</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
</a-card>
</div>
<!-- 版本信息 -->
<div class="version-info">
<a-typography-text type="secondary">版本 1.0.0</a-typography-text>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import {
LeftOutlined,
RightOutlined,
LockOutlined,
BellOutlined,
SoundOutlined,
MessageOutlined,
ClearOutlined,
SafetyOutlined,
InfoCircleOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
const router = useRouter()
// 设置项数据
const settingsSections = ref([
// 账户与安全
{
type: 'title',
title: '账户与安全'
},
{
key: 'account',
title: '账号设置',
desc: '修改密码、绑定手机',
icon: LockOutlined,
bgColor: '#e6f7ff'
},
// 通知设置
{
type: 'title',
title: '通知设置'
},
{
key: 'notifications',
title: '消息通知',
icon: BellOutlined,
bgColor: '#f6ffed'
},
{
key: 'message-push',
title: '消息推送',
icon: MessageOutlined,
bgColor: '#fffbe6'
},
// 外观设置
{
type: 'title',
title: '外观设置'
},
{
key: 'theme',
title: '主题设置',
desc: '跟随系统',
icon: SoundOutlined,
bgColor: '#f9f0ff'
},
// 其他设置
{
type: 'title',
title: '其他设置'
},
{
key: 'clear-cache',
title: '清除缓存',
desc: '12.5 MB',
icon: ClearOutlined,
bgColor: '#fff2e8'
},
{
key: 'privacy',
title: '隐私政策',
icon: SafetyOutlined,
bgColor: '#e6f7ff'
},
{
key: 'about',
title: '关于我们',
icon: InfoCircleOutlined,
bgColor: '#f6ffed'
}
])
// 处理返回按钮点击
const handleBackClick = () => {
router.back()
}
// 处理设置项点击
const handleSettingClick = (key: string) => {
switch (key) {
case 'account':
router.push('/settings/account')
break
case 'notifications':
message.info('消息通知功能开发中...')
break
case 'message-push':
message.info('消息推送功能开发中...')
break
case 'theme':
message.info('主题设置功能开发中...')
break
case 'clear-cache':
message.success('缓存已清除')
break
case 'privacy':
message.info('隐私政策功能开发中...')
break
case 'about':
message.info('关于我们功能开发中...')
break
default:
break
}
}
</script>
<style scoped>
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 15px;
border-bottom: 1px solid #f0f0f0;
}
.header h1 {
font-size: 18px;
font-weight: bold;
margin: 0;
}
.back-btn,
.empty {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
}
.settings-menu {
padding: 15px;
}
.settings-card {
border-radius: 16px;
overflow: hidden;
}
.settings-card :deep(.ant-card-body) {
padding: 0;
}
.section-title {
padding: 12px 16px;
font-size: 13px;
color: #999;
background: #fafafa;
}
.setting-item {
padding: 16px;
cursor: pointer;
transition: background 0.3s;
border-bottom: 1px solid #f0f0f0;
}
.setting-item:hover {
background: #fafafa;
}
.setting-item:last-child {
border-bottom: none;
}
.setting-item :deep(.ant-list-item-action) {
margin-left: 8px;
color: #ccc;
}
.setting-icon {
width: 40px;
height: 40px;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
}
.setting-item :deep(.ant-list-item-meta-title) {
font-size: 15px;
font-weight: 500;
color: #333;
}
.setting-item :deep(.ant-list-item-meta-description) {
font-size: 12px;
color: #999;
}
.version-info {
padding: 20px;
text-align: center;
}
</style>
-398
View File
@@ -1,398 +0,0 @@
<template>
<div class="shop-detail">
<div class="header-bg"></div>
<header class="header">
<a-button class="back-btn" type="text" @click="handleBackClick">
<LeftOutlined :style="{ fontSize: '20px' }" />
</a-button>
<h1>店铺详情</h1>
<div class="header-placeholder"></div>
</header>
<div class="shop-content">
<a-card :bordered="false" class="shop-card">
<div class="shop-info">
<div class="shop-header">
<div class="shop-icon-wrapper">
<ShopOutlined class="shop-icon" />
</div>
<div class="shop-header-content">
<h2 class="shop-name" @click="copyToClipboard(shopInfo.shopName, '店名')" style="cursor: pointer;">
{{ shopInfo.shopName }}
<span class="copy-icon">📋</span>
</h2>
<p class="shop-address" @click="copyToClipboard(shopInfo.address, '地址')" style="cursor: pointer;">
{{ shopInfo.address }}
<span class="copy-icon">📋</span>
</p>
</div>
</div>
<div class="shop-details">
<div class="detail-item">
<div class="detail-label">营业时间</div>
<div class="detail-value">{{ shopInfo.businessHours }}</div>
</div>
<div class="detail-item">
<div class="detail-label">店铺描述</div>
<div class="detail-value">{{ shopInfo.description }}</div>
</div>
</div>
<!-- 店铺环境图轮播 -->
<div class="shop-images" v-if="shopImages.length > 0">
<h3 class="section-title">店铺环境图</h3>
<div class="image-carousel">
<a-carousel autoplay :autoplay-speed="3000" dots>
<div v-for="(url, index) in shopImages" :key="index" class="carousel-item" @click="showImageModal(url)">
<img :src="url" :alt="`店铺环境图 ${index + 1}`" class="carousel-image" />
</div>
</a-carousel>
</div>
</div>
<!-- 图片查看模态框 -->
<a-modal
v-model:open="imageModalVisible"
title="店铺环境图"
:width="800"
@cancel="handleCancel"
>
<img :src="selectedImage" alt="店铺环境图" class="modal-image" />
</a-modal>
</div>
</a-card>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { LeftOutlined, ShopOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { shopApi, type ShopVO } from '@/api/shop'
import { fileApi } from '@/api/file'
import { toOptionalIdString } from '@/utils/id'
const router = useRouter()
const route = useRoute()
const shopInfo = ref<ShopVO>({
id: '',
shopName: '',
description: '',
address: '',
businessHours: '',
imageFileIds: '',
createTime: '',
updateTime: ''
})
const shopImages = ref<string[]>([])
// 图片模态框
const imageModalVisible = ref(false)
const selectedImage = ref('')
const handleBackClick = () => {
router.back()
}
// 显示图片模态框
const showImageModal = (imageUrl: string) => {
selectedImage.value = imageUrl
imageModalVisible.value = true
}
// 关闭图片模态框
const handleCancel = () => {
imageModalVisible.value = false
selectedImage.value = ''
}
// 复制到剪贴板
const copyToClipboard = async (text: string, type: string) => {
try {
await navigator.clipboard.writeText(text)
message.success(`${type}已复制到剪贴板`)
} catch (err) {
console.error('复制失败:', err)
message.error('复制失败,请手动复制')
}
}
const loadShopImages = async () => {
try {
const imageFileIds = shopInfo.value.imageFileIds
if (imageFileIds) {
const fileIds = imageFileIds.split(',').filter(id => id.trim())
const fileIdPromises = fileIds.map(idStr => {
const fileId = idStr.trim()
if (!fileId) {
return null
}
return fileApi.getSignedUrl(fileId).catch(() => {
return null
})
})
const results = await Promise.all(fileIdPromises)
const filteredResults = results
.filter((url): url is any => url !== null)
.map(url => {
const urlStr = typeof url === 'string' ? url : String(url)
return urlStr.replace(/[`]/g, '').trim()
})
shopImages.value = filteredResults
}
} catch (error) {
}
}
const fetchShopDetail = async () => {
try {
// 从路由参数或本地存储获取店铺ID
const shopId = toOptionalIdString(route.params.id || localStorage.getItem('userShopId'))
if (!shopId) {
message.error('店铺ID不存在')
router.back()
return
}
const response = await shopApi.getShopById(shopId) as any
shopInfo.value = response || {}
// 加载店铺图片
await loadShopImages()
} catch (error) {
message.error('获取店铺详情失败')
}
}
onMounted(() => {
fetchShopDetail()
})
</script>
<style scoped>
.shop-detail {
min-height: 100vh;
background: #f5f5f5;
position: relative;
}
.header-bg {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 120px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
z-index: 0;
}
.header {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 100;
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 15px;
background: transparent;
color: white;
}
.back-btn {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
color: white;
}
.header h1 {
font-size: 18px;
font-weight: bold;
margin: 0;
}
.header-placeholder {
width: 40px;
height: 40px;
}
.shop-content {
padding: 100px 15px 20px;
position: relative;
z-index: 1;
}
.shop-card {
border-radius: 20px;
overflow: hidden;
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
}
.shop-card :deep(.ant-card-body) {
padding: 24px;
}
.shop-info {
display: flex;
flex-direction: column;
gap: 20px;
}
.shop-header {
display: flex;
align-items: center;
gap: 16px;
}
.shop-icon-wrapper {
width: 80px;
height: 80px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 16px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.shop-icon {
font-size: 36px;
color: white;
}
.shop-header-content {
flex: 1;
}
.shop-name {
font-size: 22px;
font-weight: 700;
margin: 0 0 8px 0;
color: #1a1a2e;
}
.shop-address {
font-size: 14px;
color: #8b8b9a;
margin: 0;
}
.copy-icon {
font-size: 12px;
margin-left: 6px;
opacity: 0.6;
transition: opacity 0.2s ease;
}
.shop-name:hover .copy-icon,
.shop-address:hover .copy-icon {
opacity: 1;
color: #667eea;
}
.shop-details {
display: flex;
flex-direction: column;
gap: 16px;
}
.detail-item {
display: flex;
flex-direction: column;
gap: 6px;
}
.detail-label {
font-size: 13px;
color: #8b8b9a;
font-weight: 500;
}
.detail-value {
font-size: 16px;
color: #1a1a2e;
line-height: 1.5;
}
.section-title {
font-size: 16px;
font-weight: 600;
color: #1a1a2e;
margin: 0 0 12px 0;
}
.image-carousel {
margin: 12px 0;
border-radius: 12px;
overflow: hidden;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
width: 100%;
height: 200px;
}
.carousel-item {
width: 100%;
height: 200px;
cursor: pointer;
position: relative;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
}
.carousel-image {
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 0.3s ease;
}
.carousel-item:hover .carousel-image {
transform: scale(1.05);
}
/* 轮播指示器样式 */
.image-carousel :deep(.slick-dots) {
bottom: 10px;
}
.image-carousel :deep(.slick-dots li) {
margin: 0 4px;
}
.image-carousel :deep(.slick-dots li button) {
width: 8px;
height: 8px;
border-radius: 50%;
background: rgba(0, 0, 0, 0.4);
}
.image-carousel :deep(.slick-dots li.slick-active button) {
width: 20px;
border-radius: 4px;
background: #667eea;
}
.modal-image {
width: 100%;
max-height: 600px;
object-fit: contain;
border-radius: 8px;
}
@media (min-width: 992px) {
.shop-content {
max-width: 1040px;
margin: 0 auto;
padding: 100px 24px 24px;
}
}
</style>
-264
View File
@@ -1,264 +0,0 @@
<template>
<div class="mobile-container">
<!-- Header -->
<header class="header">
<div class="back-btn" @click="handleBackClick">
<el-icon><ArrowLeft /></el-icon>
</div>
<h1>我的收藏</h1>
<div class="empty"></div>
</header>
<!-- Wishlist Items -->
<div class="wishlist-items">
<div v-for="item in wishlistItems" :key="item.id" class="wishlist-item">
<div class="item-image" @click="handleProductClick(item.product.id)">
<img v-if="getProductImages(item.product) && getProductImages(item.product).length > 0"
:src="getProductImages(item.product)[0]"
:alt="item.product.title" />
<div v-else class="image-placeholder" :style="{ backgroundColor: getRandomColor() }">
<span>{{ item.product.title ? item.product.title[0] : '商' }}</span>
</div>
</div>
<div class="item-details">
<h3 class="item-name" @click="handleProductClick(item.product.id)">{{ item.product.title }}</h3>
<p class="item-price">¥{{ item.product.price }}</p>
<div class="item-actions">
<el-button size="small" type="primary" @click="handleAddToCart(item.product.id)">
添加到购物车
</el-button>
<el-icon class="delete-icon" @click="handleRemoveItem(item.product.id)"><Delete /></el-icon>
</div>
</div>
</div>
</div>
<!-- Empty Wishlist Message -->
<div v-if="wishlistItems.length === 0" class="empty-wishlist">
<el-icon :size="60" :style="{ color: '#fadb14' }"><StarFilled /></el-icon>
<p>收藏列表为空</p>
<el-button type="primary" @click="handleBrowseProducts">
浏览作品
</el-button>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, inject } from 'vue'
import { ArrowLeft, Delete, StarFilled } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { wishlistApi, type WishlistItem } from '@/api/wishlist'
import { cartApi } from '@/api/cart'
import { fileApi } from '@/api/file'
import type { IdType } from '@/utils/id'
import { sameId } from '@/utils/id'
const router = useRouter()
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
const wishlistItems = ref<WishlistItem[]>([])
const imageIdCache = ref<Record<string, string>>({})
const imageUrls = ref<Record<string, string[]>>({})
const DEFAULT_PRODUCT_IMAGE = 'data:image/svg+xml;base64,PHN2ZyB3aW0dPSJodHRwOi8vd3d3Lm9yZy8yMDAwL3N2ZyI+Pjwvc3ZnPg=='
const handleBackClick = () => {
router.back()
}
const fetchWishlist = async () => {
try {
const response = await wishlistApi.getWishlist()
wishlistItems.value = (response as unknown as WishlistItem[])
await loadImageUrls(response as unknown as WishlistItem[])
} catch (error) {
console.error('获取收藏列表失败:', error)
ElMessage.error('获取收藏列表失败')
}
}
const loadImageUrls = async (items: WishlistItem[]) => {
for (const item of items) {
if (item.product.imageFileIds) {
const ids = item.product.imageFileIds.split(',')
const urls: string[] = []
for (const id of ids) {
if (id) {
try {
if (!imageIdCache.value[id]) {
const response = await fileApi.getSignedUrl(id.trim()) 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[String(item.product.id)] = urls
} else {
imageUrls.value[String(item.product.id)] = [DEFAULT_PRODUCT_IMAGE]
}
}
}
const getProductImages = (product: any): string[] => {
return imageUrls.value[String(product.id)] || [DEFAULT_PRODUCT_IMAGE]
}
const handleAddToCart = async (productId: IdType) => {
try {
await cartApi.addToCart({ productId, quantity: 1 })
await updateCartCount()
ElMessage.success('已添加到购物车')
} catch (error) {
console.error('添加到购物车失败:', error)
ElMessage.error('添加到购物车失败')
}
}
const handleRemoveItem = async (productId: IdType) => {
try {
await wishlistApi.removeFromWishlist(productId)
wishlistItems.value = wishlistItems.value.filter(item => !sameId(item.productId, productId))
ElMessage.success('已从收藏中移除')
} catch (error) {
console.error('移除收藏失败:', error)
ElMessage.error('移除收藏失败')
}
}
const handleBrowseProducts = () => {
router.push('/products')
}
const handleProductClick = (productId: IdType) => {
router.push(`/product/${productId}`)
}
const getRandomColor = () => {
const colors = ['#ffe4d6', '#d6eaff', '#e2ffd6', '#fff2d6', '#d6ffe4', '#e4d6ff']
return colors[Math.floor(Math.random() * colors.length)]
}
onMounted(() => {
fetchWishlist()
})
</script>
<style scoped>
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 20px;
border-bottom: 1px solid #f0f0f0;
}
.back-btn {
width: 40px;
height: 40px;
display: flex;
align-items: center;
cursor: pointer;
}
.header h1 {
font-size: 18px;
font-weight: bold;
}
.empty {
width: 40px;
}
.wishlist-items {
padding: 20px;
padding-bottom: 20px;
}
.wishlist-item {
display: flex;
gap: 15px;
padding: 15px;
background: #f9f9f9;
border-radius: 15px;
margin-bottom: 15px;
}
.item-image {
width: 80px;
height: 80px;
border-radius: 10px;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
cursor: pointer;
}
.item-image img {
width: 100%;
height: 100%;
object-fit: cover;
}
.image-placeholder {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
font-size: 30px;
font-weight: bold;
color: rgba(0,0,0,0.1);
}
.item-details {
flex: 1;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.item-name {
font-size: 16px;
font-weight: bold;
margin: 0 0 5px 0;
}
.item-price {
color: var(--primary-color);
font-weight: bold;
margin: 0 0 10px 0;
}
.item-actions {
display: flex;
justify-content: space-between;
align-items: center;
}
.delete-icon {
color: #ff4757;
cursor: pointer;
font-size: 20px;
}
.empty-wishlist {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 60px 20px;
color: #999;
}
.empty-wishlist p {
margin: 20px 0;
font-size: 16px;
}
</style>
-397
View File
@@ -1,397 +0,0 @@
<template>
<div class="admin-layout">
<a-layout>
<a-layout-sider
v-model:collapsed="collapsed"
:trigger="null"
collapsible
class="sider"
width="240"
>
<div class="logo">
<h1 v-if="!collapsed">后台管理</h1>
<h1 v-else>后台</h1>
</div>
<a-menu
:selectedKeys="selectedKeys"
mode="inline"
theme="dark"
@click="handleMenuClick"
>
<a-menu-item
v-for="item in filteredMenuItems"
:key="item.key"
>
<template #icon>
<component :is="item.icon" />
</template>
<span>{{ item.label }}</span>
</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" />
<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>
<a-avatar :size="32" :src="userInfo?.avatar || DEFAULT_AVATAR" />
<span class="username">{{ userInfo?.nickname || '管理员' }}</span>
<DownOutlined />
</a>
<template #overlay>
<a-menu>
<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">
<template #icon>
<LogoutOutlined />
</template>
退出登录
</a-menu-item>
</a-menu>
</template>
</a-dropdown>
</div>
</div>
</a-layout-header>
<a-layout-content class="content">
<div class="content-shell">
<router-view />
</div>
</a-layout-content>
</a-layout>
</a-layout>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
DashboardOutlined,
DownOutlined,
GiftOutlined,
HomeOutlined,
LogoutOutlined,
MenuFoldOutlined,
MenuUnfoldOutlined,
SafetyCertificateOutlined,
ShopOutlined,
ShoppingOutlined,
TagOutlined,
TeamOutlined,
UserOutlined
} from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { adminAuthApi, type UserVO } from '@/api/admin'
import { DEFAULT_AVATAR } from '@/constants'
import { usePermission } from '@/utils/permission'
const router = useRouter()
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' }
]
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.value
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
}
const handleMenuClick = (info: any) => {
router.push(info.key)
}
const handleLogout = () => {
Modal.confirm({
title: '确认退出登录',
content: '退出后需要重新登录后台。',
okText: '确认',
cancelText: '取消',
onOk: async () => {
try {
await adminAuthApi.logout()
} catch (error) {
console.error('退出失败:', error)
} finally {
localStorage.removeItem('adminAccessToken')
localStorage.removeItem('adminRefreshToken')
localStorage.removeItem('adminUserInfo')
localStorage.removeItem('accessToken')
localStorage.removeItem('refreshToken')
localStorage.removeItem('userInfo')
sessionStorage.removeItem('adminAccessToken')
sessionStorage.removeItem('accessToken')
clearPermissions()
message.success('已退出登录')
window.location.href = '/admin/login'
}
}
})
}
const fetchUserInfo = async () => {
try {
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)
}
}
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()
await loadUserPermissions()
})
</script>
<style scoped>
.admin-layout {
height: 100vh;
}
.sider {
background: #001529;
overflow: auto;
height: 100vh;
position: fixed;
left: 0;
top: 0;
bottom: 0;
z-index: 1000;
}
.logo {
height: 64px;
display: flex;
align-items: center;
justify-content: center;
background: rgba(255, 255, 255, 0.08);
}
.logo h1 {
margin: 0;
color: white;
font-size: 18px;
font-weight: 700;
}
.header {
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;
}
.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 {
display: flex;
align-items: center;
}
.user-dropdown {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 12px;
border-radius: 10px;
transition: background 0.2s ease;
}
.user-dropdown:hover {
background: #f8fafc;
}
.username {
color: #1f2937;
}
.content {
margin-left: 240px;
min-height: calc(100vh - 64px);
padding: 24px;
background: #f0f2f5;
transition: margin-left 0.2s;
}
.content-shell {
width: 100%;
max-width: var(--admin-content-max-width);
margin: 0 auto;
}
.admin-layout :deep(.ant-layout-sider-collapsed) + .ant-layout .content {
margin-left: 80px;
}
</style>
-375
View File
@@ -1,375 +0,0 @@
<template>
<div class="admin-login">
<div class="login-container">
<div class="login-header">
<h1>后台管理系统</h1>
<p>欢迎回来,请登录您的账户</p>
</div>
<a-card class="login-card">
<a-form
ref="formRef"
:model="formState"
:rules="formRules"
layout="vertical"
@finish="handleLogin"
>
<a-alert
v-if="loginShopMessage"
:type="allowShoplessLogin || hasAvailableShops ? 'info' : 'warning'"
show-icon
:message="loginShopMessage"
style="margin-bottom: 16px"
/>
<a-form-item label="用户名" name="account">
<a-input
v-model:value="formState.account"
size="large"
placeholder="请输入用户名"
:prefix-icon="UserOutlined"
@input="handleAccountInput"
/>
</a-form-item>
<a-form-item label="密码" name="password">
<a-input-password
v-model:value="formState.password"
size="large"
placeholder="请输入密码"
:prefix-icon="LockOutlined"
@pressEnter="handleLogin"
/>
</a-form-item>
<a-form-item label="登录店铺" name="shopId">
<a-select
v-model:value="formState.shopId"
size="large"
:placeholder="shopPlaceholder"
:loading="shopLoading"
:options="shopOptions"
:disabled="shopLoading || (!hasAvailableShops && !allowShoplessLogin)"
show-search
:filter-option="filterShopOption"
/>
</a-form-item>
<a-form-item>
<a-button
type="primary"
size="large"
html-type="submit"
:loading="loading"
block
>
登录
</a-button>
</a-form-item>
</a-form>
<div class="login-footer">
<a @click="goToFrontend">返回前台</a>
</div>
</a-card>
</div>
</div>
</template>
<script setup lang="ts">
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, type LoginShopSelectionResponse } from '@/api/admin'
import { ACCOUNT_REGEX, ACCOUNT_RULE_MESSAGE, sanitizeAccountInput } from '@/utils/account'
import type { IdType } from '@/utils/id'
import { usePermission } from '@/utils/permission'
const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)
const shopLoading = ref(false)
const shops = ref<Array<{ id: IdType; shopName: string }>>([])
const allowShoplessLogin = ref(false)
const loginShopMessage = ref('')
const { loadUserPermissions } = usePermission()
const formState = reactive({
account: '',
password: '',
shopId: undefined as string | undefined
})
let loginShopTimer: number | undefined
const handleAccountInput = () => {
const normalized = sanitizeAccountInput(formState.account)
if (normalized !== formState.account) {
formState.account = normalized
}
}
const getShopIdValue = (shop: { id: IdType; shopName: string }) => String(shop.id ?? '')
const getShopLabel = (shop: { id: IdType; shopName: string }) => String(shop.shopName || `店铺 ${shop.id}`)
const shopOptions = computed(() =>
shops.value.map(shop => ({
label: getShopLabel(shop),
value: getShopIdValue(shop)
}))
)
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: [
{ required: true, message: '请输入用户名', trigger: 'blur' },
{ pattern: ACCOUNT_REGEX, message: ACCOUNT_RULE_MESSAGE, trigger: 'blur' }
],
password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
shopId: [{
validator: async () => {
if (!shouldRequireShop.value || formState.shopId) {
return Promise.resolve()
}
return Promise.reject(new Error('请选择登录店铺'))
},
trigger: 'change'
}]
} as any
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) {
return
}
try {
const parsed = JSON.parse(cached)
if (parsed?.shopId) {
formState.shopId = String(parsed.shopId)
}
} catch (error) {
console.error('恢复后台登录店铺失败:', error)
}
}
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 {
const selection = await adminAuthApi.getLoginShops(trimmedAccount) as unknown as LoginShopSelectionResponse
if (formState.account.trim() === trimmedAccount) {
applyLoginShopSelection(selection)
}
} catch (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
}
}
const handleLogin = async () => {
try {
await formRef.value?.validate()
loading.value = true
const res = await adminAuthApi.login({
account: formState.account,
password: formState.password,
shopId: formState.shopId
})
const { accessToken, refreshToken, userInfo } = res as any
localStorage.setItem('adminAccessToken', accessToken)
localStorage.setItem('adminRefreshToken', refreshToken)
localStorage.setItem('adminUserInfo', JSON.stringify(userInfo))
sessionStorage.setItem('adminAccessToken', accessToken)
message.success('登录成功')
await loadUserPermissions()
router.push('/admin').catch(err => {
console.error('跳转到首页失败:', err)
window.location.href = '/admin'
})
} catch (error: any) {
console.error('登录失败:', error)
message.error(error.message || '登录失败,请检查用户名和密码')
} finally {
loading.value = false
}
}
onMounted(() => {
restoreLoginShop()
})
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 = () => {
localStorage.removeItem('adminAccessToken')
localStorage.removeItem('adminRefreshToken')
localStorage.removeItem('adminUserInfo')
localStorage.removeItem('accessToken')
localStorage.removeItem('refreshToken')
localStorage.removeItem('userInfo')
localStorage.removeItem('userPermissions')
sessionStorage.removeItem('adminAccessToken')
sessionStorage.removeItem('accessToken')
setTimeout(() => {
window.location.href = '/'
}, 100)
}
</script>
<style scoped>
.admin-login {
min-height: 100vh;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
}
.login-container {
width: 100%;
max-width: 420px;
}
.login-header {
text-align: center;
margin-bottom: 32px;
color: white;
}
.login-header h1 {
font-size: 32px;
font-weight: 600;
margin: 0 0 8px 0;
}
.login-header p {
font-size: 14px;
opacity: 0.9;
margin: 0;
}
.login-card {
border-radius: 12px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}
.login-footer {
text-align: center;
margin-top: 16px;
}
.login-footer a {
color: #1890ff;
text-decoration: none;
font-size: 14px;
}
.login-footer a:hover {
text-decoration: underline;
}
</style>
-737
View File
@@ -1,737 +0,0 @@
<template>
<div class="coupons">
<a-page-header title="优惠券管理" sub-title="管理系统优惠券" />
<a-card :bordered="false">
<template #extra>
<a-space>
<a-input-search
v-model:value="searchText"
placeholder="搜索优惠券名称"
style="width: 260px"
@search="handleSearch"
/>
<a-button v-if="hasPermission('coupon:create')" type="primary" @click="showAddModal">
<template #icon>
<PlusOutlined />
</template>
新增优惠券
</a-button>
</a-space>
</template>
<a-table
:columns="columns"
:data-source="couponList"
:loading="loading"
:pagination="pagination"
row-key="id"
@change="handleTableChange"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'shop'">
{{ record.shopName || '未指定店铺' }}
</template>
<template v-else-if="column.key === 'couponType'">
<a-tag :color="record.couponType === 1 ? 'blue' : 'green'">
{{ record.couponTypeName || (record.couponType === 1 ? '折扣券' : '满减券') }}
</a-tag>
</template>
<template v-else-if="column.key === 'couponScene'">
<a-tag :color="record.couponScene === 'VIP_AUTO' ? 'gold' : 'default'">
{{ getCouponSceneText(record.couponScene) }}
</a-tag>
</template>
<template v-else-if="column.key === 'requiredVipLevel'">
{{ record.requiredVipLevel || '-' }}
</template>
<template v-else-if="column.key === 'value'">
<template v-if="record.couponType === 1">
{{ record.discountValue }} 折
</template>
<template v-else>
满 {{ record.minAmount }} 减 {{ record.reduceAmount }}
</template>
</template>
<template v-else-if="column.key === 'status'">
<a-tag :color="getStatusColor(record.status || 1)">
{{ record.statusName || '未知' }}
</a-tag>
</template>
<template v-else-if="column.key === 'actions'">
<a-space wrap>
<a-button v-if="hasPermission('coupon:view')" type="link" size="small" @click="showViewModal(record)">
查看
</a-button>
<a-button v-if="hasPermission('coupon:edit')" type="link" size="small" @click="showEditModal(record)">
编辑
</a-button>
<a-button
v-if="hasPermission('coupon:assign') && !isVipAutoCoupon(record) && record.status === 1"
type="link"
size="small"
@click="showDistributeModal(record)"
>
发放
</a-button>
<a-button
v-if="hasPermission('coupon:delete') && record.status !== 2"
type="link"
size="small"
danger
@click="handleDelete(record)"
>
删除
</a-button>
</a-space>
</template>
</template>
</a-table>
</a-card>
<a-modal
v-model:open="modalVisible"
:title="isEdit ? '编辑优惠券' : '新增优惠券'"
width="820px"
:confirm-loading="modalLoading"
@ok="handleModalOk"
@cancel="handleModalCancel"
>
<DraftActions
:saved-at="draftSavedAt"
@save="handleSaveDraft"
@clear="handleClearDraft"
/>
<a-form
ref="formRef"
:model="formState"
:rules="formRules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<a-form-item label="优惠券名称" name="couponName">
<a-input v-model:value="formState.couponName" placeholder="请输入优惠券名称" />
</a-form-item>
<a-form-item label="所属店铺" name="shopId">
<a-select
v-model:value="formState.shopId"
placeholder="请选择所属店铺"
:loading="loadingShops"
:disabled="currentUserInfo?.type === 2"
>
<a-select-option v-for="shop in shops" :key="shop.id" :value="shop.id">
{{ shop.shopName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="优惠券类型" name="couponType">
<a-select v-model:value="formState.couponType" placeholder="请选择优惠券类型">
<a-select-option :value="1">折扣券</a-select-option>
<a-select-option :value="2">满减券</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="优惠场景" name="couponScene">
<a-select v-model:value="formState.couponScene" placeholder="请选择优惠场景">
<a-select-option value="GENERAL">普通券</a-select-option>
<a-select-option value="VIP_AUTO">VIP 自动券</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="自动匹配">
<a-switch :checked="formState.autoMatch === 1" @change="(checked: any) => handleAutoMatchChange(checked === true)" />
</a-form-item>
<a-form-item v-if="isVipAutoForm" label="所需 VIP 等级" name="requiredVipLevel">
<a-select v-model:value="formState.requiredVipLevel" placeholder="请选择 VIP 等级">
<a-select-option value="青铜">青铜</a-select-option>
<a-select-option value="白银">白银</a-select-option>
<a-select-option value="黄金">黄金</a-select-option>
</a-select>
</a-form-item>
<a-form-item v-if="formState.couponType === 1" label="折扣值" name="discountValue">
<a-input-number v-model:value="formState.discountValue" :min="0.1" :max="9.9" :step="0.1" style="width: 100%" />
</a-form-item>
<a-form-item v-if="formState.couponType === 2" label="最低消费" name="minAmount">
<a-input-number v-model:value="formState.minAmount" :min="0" :step="0.01" style="width: 100%" />
</a-form-item>
<a-form-item v-if="formState.couponType === 2" label="减免金额" name="reduceAmount">
<a-input-number v-model:value="formState.reduceAmount" :min="0" :step="0.01" style="width: 100%" />
</a-form-item>
<a-form-item label="总数量" name="totalCount">
<a-input-number v-model:value="formState.totalCount" :min="1" style="width: 100%" />
</a-form-item>
<a-form-item label="开始时间" name="startTime">
<a-date-picker v-model:value="formState.startTime" show-time format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
</a-form-item>
<a-form-item label="结束时间" name="endTime">
<a-date-picker v-model:value="formState.endTime" show-time format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
</a-form-item>
<a-form-item label="可用标签" name="availableTagIds">
<a-select v-model:value="formState.availableTagIds" mode="multiple" placeholder="请选择可用标签">
<a-select-option v-for="tag in tagList" :key="tag.id" :value="tag.id">
{{ tag.tagName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="不可用标签" name="unavailableTagIds">
<a-select v-model:value="formState.unavailableTagIds" mode="multiple" placeholder="请选择不可用标签">
<a-select-option v-for="tag in tagList" :key="tag.id" :value="tag.id">
{{ tag.tagName }}
</a-select-option>
</a-select>
</a-form-item>
</a-form>
</a-modal>
<a-modal
v-model:open="viewModalVisible"
title="查看优惠券详情"
:footer="null"
width="760px"
@cancel="viewModalVisible = false"
>
<a-descriptions bordered :column="1" size="small">
<a-descriptions-item label="优惠券名称">{{ currentCoupon?.couponName || '-' }}</a-descriptions-item>
<a-descriptions-item label="所属店铺">{{ currentCoupon?.shopName || '-' }}</a-descriptions-item>
<a-descriptions-item label="优惠券类型">{{ currentCoupon?.couponType === 1 ? '折扣券' : '满减券' }}</a-descriptions-item>
<a-descriptions-item label="优惠场景">{{ getCouponSceneText(currentCoupon?.couponScene) }}</a-descriptions-item>
<a-descriptions-item label="所需 VIP 等级">{{ currentCoupon?.requiredVipLevel || '-' }}</a-descriptions-item>
<a-descriptions-item label="自动匹配">{{ currentCoupon?.autoMatch === 1 ? '是' : '否' }}</a-descriptions-item>
<a-descriptions-item label="优惠信息">{{ getCouponValueText(currentCoupon) }}</a-descriptions-item>
<a-descriptions-item label="总数量">{{ currentCoupon?.totalCount ?? '-' }}</a-descriptions-item>
<a-descriptions-item label="已使用">{{ currentCoupon?.usedCount ?? '-' }}</a-descriptions-item>
<a-descriptions-item label="开始时间">{{ currentCoupon?.startTime || '-' }}</a-descriptions-item>
<a-descriptions-item label="结束时间">{{ currentCoupon?.endTime || '-' }}</a-descriptions-item>
</a-descriptions>
</a-modal>
<a-modal
v-model:open="distributeModalVisible"
title="发放优惠券"
width="760px"
:confirm-loading="distributeLoading"
@ok="handleDistributeOk"
@cancel="handleDistributeCancel"
>
<a-form
ref="distributeFormRef"
:model="distributeFormState"
:rules="distributeFormRules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<a-form-item label="优惠券">
<a-input v-model:value="distributeFormState.couponName" disabled />
</a-form-item>
<a-form-item label="选择用户" name="userIds">
<a-select
v-model:value="distributeFormState.userIds"
mode="multiple"
placeholder="请选择要发放的用户"
>
<a-select-option v-for="user in userList" :key="user.id" :value="user.id">
{{ user.nickname }}({{ user.account }})
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="发放数量" name="quantity">
<a-input-number v-model:value="distributeFormState.quantity" :min="1" style="width: 100%" />
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { message, Modal } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import DraftActions from '@/components/DraftActions.vue'
import dayjs, { type Dayjs } from 'dayjs'
import {
adminCouponApi,
adminShopApi,
adminTagApi,
adminUserApi,
type Coupon,
type Shop,
type Tag,
type UserVO
} from '@/api/admin'
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
import { usePermission } from '@/utils/permission'
const { hasPermission, loadUserPermissions } = usePermission()
const currentUserInfo = (() => {
try {
const userInfoStr = localStorage.getItem('adminUserInfo')
return userInfoStr ? JSON.parse(userInfoStr) : null
} catch (error) {
console.error('获取当前用户信息失败', error)
return null
}
})()
interface CouponFormState {
couponCode: string
couponName: string
couponType: number
discountValue?: number
minAmount?: number
reduceAmount?: number
totalCount: number
startTime?: Dayjs
endTime?: Dayjs
availableTagIds: number[]
unavailableTagIds: number[]
shopId?: number
couponScene: string
requiredVipLevel?: string
autoMatch: number
}
const loading = ref(false)
const loadingShops = ref(false)
const modalVisible = ref(false)
const viewModalVisible = ref(false)
const modalLoading = ref(false)
const isEdit = ref(false)
const searchText = ref('')
const formRef = ref<FormInstance>()
const distributeFormRef = ref<FormInstance>()
const currentCoupon = ref<Coupon | null>(null)
const draftSavedAt = ref<number | null>(null)
const couponList = ref<Coupon[]>([])
const tagList = ref<Tag[]>([])
const userList = ref<UserVO[]>([])
const shops = ref<Shop[]>([])
const distributeModalVisible = ref(false)
const distributeLoading = ref(false)
const currentDistributeCoupon = ref<Coupon | null>(null)
const pagination = reactive({
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total: number) => `共 ${total} 条`
})
const formState = reactive<CouponFormState>({
couponCode: '',
couponName: '',
couponType: 1,
discountValue: 9.5,
minAmount: 100,
reduceAmount: 20,
totalCount: 100,
startTime: dayjs(),
endTime: dayjs().add(30, 'day'),
availableTagIds: [],
unavailableTagIds: [],
shopId: undefined,
couponScene: 'GENERAL',
requiredVipLevel: undefined,
autoMatch: 0
})
const distributeFormState = reactive({
couponName: '',
userIds: [] as number[],
quantity: 1
})
const formRules = {
couponName: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
couponType: [{ required: true, message: '请选择优惠券类型', trigger: 'change' }],
couponScene: [{ required: true, message: '请选择优惠场景', trigger: 'change' }],
requiredVipLevel: [{ required: true, message: '请选择所需 VIP 等级', trigger: 'change' }],
totalCount: [{ required: true, message: '请输入优惠券总数量', trigger: 'blur' }],
startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
shopId: [{ required: true, message: '请选择所属店铺', trigger: 'change' }]
} as any
const distributeFormRules = {
userIds: [{ required: true, message: '请选择要发放的用户', trigger: 'change' }],
quantity: [{ required: true, message: '请输入发放数量', trigger: 'blur' }]
} as any
const columns = [
{ title: '优惠券名称', dataIndex: 'couponName', key: 'couponName' },
{ title: '所属店铺', key: 'shop', width: 140 },
{ title: '类型', key: 'couponType', width: 100 },
{ title: '场景', key: 'couponScene', width: 120 },
{ title: '所需 VIP', key: 'requiredVipLevel', width: 110 },
{ title: '优惠信息', key: 'value', width: 170 },
{ title: '总数量', dataIndex: 'totalCount', key: 'totalCount', width: 90 },
{ title: '已使用', dataIndex: 'usedCount', key: 'usedCount', width: 90 },
{ title: '剩余', dataIndex: 'remainingCount', key: 'remainingCount', width: 90 },
{ title: '状态', key: 'status', width: 100 },
{ title: '操作', key: 'actions', width: 180, fixed: 'right' as const }
]
const isVipAutoForm = computed(() => formState.couponScene === 'VIP_AUTO' || formState.autoMatch === 1)
const getStatusColor = (status: number) => {
switch (status) {
case 1:
return 'green'
case 2:
return 'red'
case 3:
return 'orange'
default:
return 'default'
}
}
const getCouponSceneText = (scene?: string) => {
if (scene === 'VIP_AUTO') {
return 'VIP 自动券'
}
return '普通券'
}
const isVipAutoCoupon = (coupon: any) => coupon?.couponScene === 'VIP_AUTO' || coupon?.autoMatch === 1
const getCouponValueText = (coupon: Coupon | null) => {
if (!coupon) {
return '-'
}
return coupon.couponType === 1
? `${coupon.discountValue} 折`
: `满 ${coupon.minAmount} 减 ${coupon.reduceAmount}`
}
const resetFormState = () => {
Object.assign(formState, {
couponCode: '',
couponName: '',
couponType: 1,
discountValue: 9.5,
minAmount: 100,
reduceAmount: 20,
totalCount: 100,
startTime: dayjs(),
endTime: dayjs().add(30, 'day'),
availableTagIds: [],
unavailableTagIds: [],
shopId: currentUserInfo?.shopId || undefined,
couponScene: 'GENERAL',
requiredVipLevel: undefined,
autoMatch: 0
})
}
const getDraftKey = () => buildDraftStorageKey('admin-coupons', isEdit.value ? 'edit' : 'create', currentCoupon.value?.id ?? 'new')
const buildDraftPayload = () => ({
couponCode: formState.couponCode,
couponName: formState.couponName,
couponType: formState.couponType,
discountValue: formState.discountValue,
minAmount: formState.minAmount,
reduceAmount: formState.reduceAmount,
totalCount: formState.totalCount,
startTime: formState.startTime?.format('YYYY-MM-DD HH:mm:ss'),
endTime: formState.endTime?.format('YYYY-MM-DD HH:mm:ss'),
availableTagIds: [...formState.availableTagIds],
unavailableTagIds: [...formState.unavailableTagIds],
shopId: formState.shopId,
couponScene: formState.couponScene,
requiredVipLevel: formState.requiredVipLevel,
autoMatch: formState.autoMatch
})
const restoreDraft = () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
if (!draft) {
draftSavedAt.value = null
return
}
Object.assign(formState, {
...draft.payload,
startTime: draft.payload.startTime ? dayjs(draft.payload.startTime) : undefined,
endTime: draft.payload.endTime ? dayjs(draft.payload.endTime) : undefined
})
draftSavedAt.value = draft.savedAt
message.success('已恢复暂存内容')
}
const handleSaveDraft = () => {
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload())
draftSavedAt.value = draft.savedAt
message.success('已暂存到本地')
}
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey())
draftSavedAt.value = null
if (showMessage) {
message.success('已清除暂存')
}
}
watch(
() => formState.couponScene,
value => {
if (value === 'VIP_AUTO') {
formState.autoMatch = 1
if (!formState.requiredVipLevel) {
formState.requiredVipLevel = '青铜'
}
} else {
formState.autoMatch = 0
formState.requiredVipLevel = undefined
}
}
)
const handleAutoMatchChange = (checked: boolean) => {
formState.autoMatch = checked ? 1 : 0
formState.couponScene = checked ? 'VIP_AUTO' : 'GENERAL'
}
const fetchCoupons = async () => {
loading.value = true
try {
const shopId = currentUserInfo?.shopId || undefined
const coupons = await adminCouponApi.listAllCoupons(shopId) as unknown as Coupon[]
const list = Array.isArray(coupons) ? coupons : []
const keyword = searchText.value.trim()
couponList.value = keyword
? list.filter(item => (item.couponName || '').includes(keyword))
: list
pagination.total = couponList.value.length
} catch (error) {
console.error('获取优惠券列表失败:', error)
message.error('获取优惠券列表失败')
} finally {
loading.value = false
}
}
const fetchTags = async () => {
try {
const tags = await adminTagApi.listAllTags() as unknown as Tag[]
tagList.value = tags || []
} catch (error) {
console.error('获取标签列表失败:', error)
}
}
const fetchShops = async () => {
loadingShops.value = true
try {
const shopList = await adminShopApi.listAllShops() as unknown as Shop[]
shops.value = shopList || []
} catch (error) {
console.error('获取店铺列表失败:', error)
} finally {
loadingShops.value = false
}
}
const fetchUsers = async () => {
try {
const params: Record<string, unknown> = { page: 1, size: 200 }
if (currentUserInfo?.shopId) {
params.shopId = currentUserInfo.shopId
}
const result = await adminUserApi.listUsers(params as any)
userList.value = result.list || []
} catch (error) {
console.error('获取用户列表失败:', error)
userList.value = []
}
}
const handleSearch = () => {
pagination.current = 1
void fetchCoupons()
}
const handleTableChange = (pag: any) => {
pagination.current = pag.current || 1
pagination.pageSize = pag.pageSize || pagination.pageSize
}
const showAddModal = () => {
isEdit.value = false
currentCoupon.value = null
resetFormState()
restoreDraft()
modalVisible.value = true
}
const showEditModal = (record: any) => {
isEdit.value = true
currentCoupon.value = record
Object.assign(formState, {
couponCode: record.couponCode || '',
couponName: record.couponName || '',
couponType: record.couponType || 1,
discountValue: record.discountValue ? Number(record.discountValue) : 9.5,
minAmount: record.minAmount ? Number(record.minAmount) : 100,
reduceAmount: record.reduceAmount ? Number(record.reduceAmount) : 20,
totalCount: record.totalCount || 100,
startTime: record.startTime ? dayjs(record.startTime) : undefined,
endTime: record.endTime ? dayjs(record.endTime) : undefined,
availableTagIds: record.availableTags?.map((tag: Tag) => tag.id) || [],
unavailableTagIds: record.unavailableTags?.map((tag: Tag) => tag.id) || [],
shopId: record.shopId,
couponScene: record.couponScene || 'GENERAL',
requiredVipLevel: record.requiredVipLevel || undefined,
autoMatch: record.autoMatch || 0
})
restoreDraft()
modalVisible.value = true
}
const showViewModal = (record: any) => {
currentCoupon.value = record
viewModalVisible.value = true
}
const buildCouponPayload = () => ({
couponCode: formState.couponCode,
couponName: formState.couponName,
couponType: formState.couponType,
discountValue: formState.couponType === 1 ? formState.discountValue : undefined,
minAmount: formState.couponType === 2 ? formState.minAmount : undefined,
reduceAmount: formState.couponType === 2 ? formState.reduceAmount : undefined,
totalCount: formState.totalCount,
startTime: formState.startTime?.format('YYYY-MM-DD HH:mm:ss'),
endTime: formState.endTime?.format('YYYY-MM-DD HH:mm:ss'),
availableTagIds: formState.availableTagIds,
unavailableTagIds: formState.unavailableTagIds,
shopId: formState.shopId,
couponScene: formState.couponScene,
requiredVipLevel: isVipAutoForm.value ? formState.requiredVipLevel : undefined,
autoMatch: isVipAutoForm.value ? 1 : 0
})
const handleModalOk = async () => {
try {
await formRef.value?.validate()
modalLoading.value = true
const payload = buildCouponPayload()
if (isEdit.value && currentCoupon.value) {
await adminCouponApi.updateCoupon(currentCoupon.value.id, payload)
message.success('更新成功')
} else {
await adminCouponApi.createCoupon(payload)
message.success('创建成功')
}
handleClearDraft(false)
modalVisible.value = false
formRef.value?.resetFields()
await fetchCoupons()
} catch (error: any) {
console.error('保存优惠券失败:', error)
message.error(error.message || '操作失败')
} finally {
modalLoading.value = false
}
}
const handleModalCancel = () => {
modalVisible.value = false
formRef.value?.resetFields()
resetFormState()
}
const handleDelete = (record: any) => {
Modal.confirm({
title: '确认删除',
content: `确定要删除优惠券 ${record.couponName} 吗?`,
async onOk() {
try {
await adminCouponApi.deleteCoupon(record.id)
message.success('删除成功')
await fetchCoupons()
} catch (error) {
console.error('删除优惠券失败:', error)
message.error('删除失败')
}
}
})
}
const showDistributeModal = async (record: any) => {
currentDistributeCoupon.value = record
distributeFormState.couponName = record.couponName
distributeFormState.userIds = []
distributeFormState.quantity = 1
await fetchUsers()
distributeModalVisible.value = true
}
const handleDistributeOk = async () => {
if (!currentDistributeCoupon.value) {
return
}
if (isVipAutoCoupon(currentDistributeCoupon.value)) {
message.warning('VIP 自动券为系统模板券,不能手动发放')
return
}
try {
await distributeFormRef.value?.validate()
distributeLoading.value = true
await adminCouponApi.distributeCoupon({
couponId: currentDistributeCoupon.value.id,
userIds: distributeFormState.userIds,
quantity: distributeFormState.quantity
})
message.success('发放成功')
distributeModalVisible.value = false
} catch (error: any) {
console.error('发放优惠券失败:', error)
message.error(error.message || '发放失败')
} finally {
distributeLoading.value = false
}
}
const handleDistributeCancel = () => {
distributeModalVisible.value = false
distributeFormRef.value?.resetFields()
}
onMounted(async () => {
await loadUserPermissions()
await Promise.all([fetchTags(), fetchShops(), fetchCoupons()])
})
</script>
<style scoped>
.coupons {
padding: 0;
}
</style>
-304
View File
@@ -1,304 +0,0 @@
<template>
<div class="dashboard">
<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" :loading="loading">
<template #prefix>
<UserOutlined />
</template>
</a-statistic>
</a-card>
</a-col>
<a-col :xs="24" :sm="12" :xl="6">
<a-card>
<a-statistic title="作品数" :value="stats.totalProducts" :loading="loading">
<template #prefix>
<ShopOutlined />
</template>
</a-statistic>
</a-card>
</a-col>
<a-col v-if="isAdmin" :xs="24" :sm="12" :xl="6">
<a-card>
<a-statistic title="门店数" :value="stats.totalShops" :loading="loading">
<template #prefix>
<HomeOutlined />
</template>
</a-statistic>
</a-card>
</a-col>
<a-col :xs="24" :sm="12" :xl="6">
<a-card>
<a-statistic title="今日订单" :value="stats.todayOrders" :loading="loading">
<template #prefix>
<ShoppingOutlined />
</template>
</a-statistic>
</a-card>
</a-col>
</a-row>
<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 :xs="24" :xl="10">
<a-card title="热门作品" class="side-card">
<a-spin :spinning="loading">
<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="最近动态" class="activity-card">
<a-spin :spinning="loading">
<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 || 'blue'"
>
<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>
</a-card>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import { HomeOutlined, ShopOutlined, ShoppingOutlined, UserOutlined } from '@ant-design/icons-vue'
import { adminDashboardApi, type DashboardStats } from '@/api/admin'
const loading = ref(false)
const stats = reactive<DashboardStats>({
totalUsers: 0,
totalProducts: 0,
totalShops: 0,
todayOrders: 0,
hotProducts: [],
recentActivities: []
})
const getCurrentUserInfo = () => {
try {
const cache = localStorage.getItem('adminUserInfo')
return cache ? JSON.parse(cache) : null
} catch (error) {
console.error('读取后台用户信息失败:', error)
return null
}
}
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) => {
if (!timeStr) return ''
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} 天前`
return time.toLocaleDateString('zh-CN')
}
const fetchStats = async () => {
loading.value = true
try {
const data = await adminDashboardApi.getStats()
Object.assign(stats, data)
} catch (error) {
console.error('获取统计数据失败:', error)
message.error('获取统计数据失败')
} finally {
loading.value = false
}
}
onMounted(() => {
void fetchStats()
})
</script>
<style scoped>
.dashboard {
padding: 0;
}
.stat-cards {
margin-bottom: 24px;
}
.insight-card,
.side-card,
.activity-card {
border-radius: 18px;
}
.insight-list {
display: grid;
gap: 14px;
}
.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;
justify-content: space-between;
gap: 12px;
padding: 14px 0;
border-bottom: 1px solid #f0f0f0;
}
.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>
-334
View File
@@ -1,334 +0,0 @@
<template>
<div class="home">
<a-page-header title="欢迎使用后台管理系统" :sub-title="welcomeMessage" />
<a-alert
v-if="isBootstrapAdmin"
class="bootstrap-alert"
type="warning"
show-icon
message="当前处于建店引导态"
description="系统里还没有可用店铺。当前账号已允许登录后台先创建第一家店铺,其他后台模块会保持不可用,创建完成后请重新登录并选择店铺。"
/>
<a-card class="time-card">
<a-statistic title="当前时间" :value="currentTime" />
</a-card>
<a-card class="info-card">
<a-descriptions bordered>
<a-descriptions-item label="用户信息">
<div class="user-info">
<a-avatar :size="64" :src="userInfo?.avatar || DEFAULT_AVATAR" />
<div class="user-details">
<h3>{{ userInfo?.nickname || '管理员' }}</h3>
<p>{{ getUserTypeText(userInfo?.type) }}</p>
<p v-if="userInfo?.shopName">所属店铺: {{ userInfo?.shopName }}</p>
</div>
</div>
</a-descriptions-item>
</a-descriptions>
</a-card>
<a-card class="permissions-card">
<template #title>
<div class="card-title">
<SafetyCertificateOutlined class="title-icon" />
<span>我的权限</span>
</div>
</template>
<div class="permissions-content" v-if="userPermissions.length > 0">
<div v-for="(group, groupName) in groupedPermissions" :key="groupName" class="permission-group">
<div class="group-title">{{ groupName }}</div>
<div class="permission-tags">
<a-tag v-for="permission in group" :key="permission.id" color="blue" class="permission-tag">
{{ permission.permissionName }}
</a-tag>
</div>
</div>
</div>
<div class="no-permissions" v-else>
暂无权限信息
</div>
</a-card>
<a-card class="quick-actions">
<template #title>
快捷操作
</template>
<a-grid :columns="3" :colGap="16" :rowGap="16">
<a-grid-item v-for="item in quickActions" :key="item.key">
<a-card hoverable @click="navigateTo(item.path, item.permissionCode)">
<template #cover>
<div class="action-icon">
<component :is="item.icon" />
</div>
</template>
<template #title>
{{ item.title }}
</template>
</a-card>
</a-grid-item>
</a-grid>
</a-card>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { DashboardOutlined, UserOutlined, ShopOutlined, SafetyCertificateOutlined, HomeOutlined } from '@ant-design/icons-vue'
import { userApi, type UserVO } from '@/api/admin'
import { permissionApi, type PermissionVO } from '@/api/permission'
import { DEFAULT_AVATAR } from '@/constants'
import { message } from 'ant-design-vue'
const router = useRouter()
const currentTime = ref('')
const userInfo = ref<UserVO | null>(null)
const userPermissions = ref<PermissionVO[]>([])
const welcomeMessage = computed(() => {
const hour = new Date().getHours()
if (hour < 12) {
return '早上好!'
} else if (hour < 18) {
return '下午好!'
} else {
return '晚上好!'
}
})
const isBootstrapAdmin = computed(() => userInfo.value?.type === 4 && !userInfo.value?.shopId)
const groupedPermissions = computed(() => {
const groups: Record<string, PermissionVO[]> = {}
userPermissions.value.forEach(permission => {
const groupName = permission.permissionGroup
if (!groups[groupName]) {
groups[groupName] = []
}
groups[groupName]!.push(permission)
})
return groups
})
const quickActions = computed(() => {
const actions = [
{
key: 'dashboard',
title: '仪表盘',
path: '/admin/dashboard',
icon: DashboardOutlined,
permissionCode: 'dashboard:view'
},
{
key: 'users',
title: '用户管理',
path: '/admin/users',
icon: UserOutlined,
permissionCode: 'user:view'
},
{
key: 'products',
title: '作品管理',
path: '/admin/products',
icon: ShopOutlined,
permissionCode: 'product:view'
},
{
key: 'shops',
title: '店铺管理',
path: '/admin/shops',
icon: HomeOutlined,
permissionCode: 'shop:view'
},
{
key: 'permissions',
title: '权限管理',
path: '/admin/permissions',
icon: SafetyCertificateOutlined,
permissionCode: 'permission:view'
}
]
const grantedPermissions = new Set(userPermissions.value.map(permission => permission.permissionCode))
return actions.filter(item => grantedPermissions.has(item.permissionCode))
})
const getUserTypeText = (type: number | undefined) => {
switch (type) {
case 4:
return '管理员'
case 2:
return '店长'
case 3:
return '美甲师'
default:
return '普通用户'
}
}
const updateCurrentTime = () => {
const now = new Date()
currentTime.value = now.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
})
}
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
}
} catch (error) {
console.error('获取用户信息失败:', error)
}
}
const fetchUserPermissions = async () => {
try {
const res = await permissionApi.getUserPermissions()
userPermissions.value = res as unknown as PermissionVO[]
} catch (error) {
console.error('获取用户权限失败:', error)
}
}
const navigateTo = (path: string, permissionCode?: string) => {
// 检查是否需要权限
if (permissionCode) {
const hasPermission = userPermissions.value.some(p => p.permissionCode === permissionCode)
if (!hasPermission) {
message.warning('您没有该操作的权限')
return
}
}
router.push(path)
}
onMounted(() => {
updateCurrentTime()
setInterval(updateCurrentTime, 1000)
fetchUserInfo()
fetchUserPermissions()
})
</script>
<style scoped>
.home {
padding: 0;
}
.time-card {
margin-bottom: 24px;
}
.bootstrap-alert {
margin-bottom: 24px;
}
.info-card {
margin-bottom: 24px;
}
.permissions-card {
margin-bottom: 24px;
}
.user-info {
display: flex;
align-items: center;
gap: 16px;
}
.user-details {
flex: 1;
}
.user-details h3 {
margin: 0 0 8px 0;
font-size: 18px;
font-weight: 600;
}
.user-details p {
margin: 4px 0;
color: #666;
}
.card-title {
display: flex;
align-items: center;
gap: 8px;
font-size: 16px;
font-weight: 600;
color: #1a1a2e;
}
.title-icon {
font-size: 20px;
color: #667eea;
}
.permissions-content {
display: flex;
flex-direction: column;
gap: 16px;
}
.permission-group {
display: flex;
flex-direction: column;
gap: 10px;
}
.group-title {
font-size: 14px;
font-weight: 600;
color: #667eea;
margin-bottom: 4px;
}
.permission-tags {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.permission-tag {
font-size: 13px;
padding: 4px 12px;
border-radius: 12px;
margin: 0;
}
.no-permissions {
text-align: center;
padding: 20px;
color: #999;
}
.quick-actions {
margin-top: 24px;
}
.action-icon {
display: flex;
align-items: center;
justify-content: center;
height: 80px;
font-size: 32px;
color: #1890ff;
background: #f0f2f5;
}
</style>
@@ -1,495 +0,0 @@
<template>
<div class="nail-artists">
<a-page-header title="美甲师管理" sub-title="管理美甲师详细信息" />
<a-card :bordered="false">
<template #extra>
<a-space>
<a-input-search
v-model:value="searchText"
placeholder="搜索美甲师姓名"
style="width: 250px"
@search="handleSearch"
/>
</a-space>
</template>
<a-table
:columns="columns"
:data-source="nailArtistList"
:loading="loading"
:pagination="pagination"
@change="handleTableChange"
row-key="userId"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'status'">
<a-tag :color="getStatusColor(record.status)">
{{ getStatusText(record.status) }}
</a-tag>
</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button v-if="hasPermission('nail_artist:view')" type="link" size="small" @click="showViewModal(record)">
查看
</a-button>
<a-button v-if="hasPermission('nail_artist:edit')" type="link" size="small" @click="showEditModal(record)">
编辑
</a-button>
</a-space>
</template>
</template>
</a-table>
</a-card>
<!-- 编辑美甲师信息模态框 -->
<a-modal
v-model:open="modalVisible"
title="编辑美甲师信息"
@ok="handleModalOk"
@cancel="handleModalCancel"
:confirmLoading="modalLoading"
width="800px"
>
<DraftActions
:saved-at="draftSavedAt"
@save="handleSaveDraft"
@clear="handleClearDraft"
/>
<a-form
ref="formRef"
:model="formState"
:rules="formRules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<a-form-item label="美甲师姓名" name="nickname">
<a-input v-model:value="formState.nickname" :disabled="true" />
</a-form-item>
<a-form-item label="身份" name="identity">
<a-input
v-model:value="formState.identity"
placeholder="请输入身份"
:disabled="!isShopOwner"
/>
</a-form-item>
<a-form-item label="从业年限" name="experience">
<a-input-number
v-model:value="formState.experience"
:min="0"
placeholder="请输入从业年限"
:disabled="!isShopOwner"
/>
</a-form-item>
<a-form-item label="技能标签" name="skills">
<a-select
v-model:value="formState.skills"
mode="multiple"
placeholder="请选择技能标签"
:loading="tagLoading"
>
<a-select-option
v-for="tag in tagList"
:key="tag.id"
:value="tag.id.toString()"
>
{{ tag.tagName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="状态" name="status">
<a-select
v-model:value="formState.status"
placeholder="请选择状态"
:disabled="!isShopOwner"
>
<a-select-option :value="1">营业中</a-select-option>
<a-select-option :value="0">休息中</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="作品" name="portfolio">
<a-select
v-model:value="formState.portfolio"
mode="multiple"
placeholder="请选择作品作品"
:loading="productLoading"
>
<a-select-option
v-for="product in productList"
:key="product.id"
:value="product.id.toString()"
>
{{ product.title }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="评分">
<a-input v-model:value="formState.rating" :disabled="true" />
</a-form-item>
</a-form>
</a-modal>
<!-- 查看美甲师详情模态框 -->
<a-modal
v-model:open="viewModalVisible"
title="查看美甲师详情"
@cancel="handleViewModalCancel"
width="600px"
>
<a-form
:model="viewFormState"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<a-form-item label="美甲师姓名">
<a-input v-model:value="viewFormState.nickname" :disabled="true" />
</a-form-item>
<a-form-item label="所属店铺">
<a-input v-model:value="viewFormState.shopName" :disabled="true" />
</a-form-item>
<a-form-item label="身份">
<a-input v-model:value="viewFormState.identity" :disabled="true" />
</a-form-item>
<a-form-item label="从业年限">
<a-input v-model:value="viewFormState.experience" :disabled="true" />
</a-form-item>
<a-form-item label="技能标签">
<a-input v-model:value="viewFormState.skillsText" :disabled="true" />
</a-form-item>
<a-form-item label="状态">
<a-input v-model:value="viewFormState.statusText" :disabled="true" />
</a-form-item>
<a-form-item label="评分">
<a-input v-model:value="viewFormState.rating" :disabled="true" />
</a-form-item>
<a-form-item label="作品">
<a-input v-model:value="viewFormState.portfolioText" :disabled="true" />
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import DraftActions from '@/components/DraftActions.vue'
import { adminNailArtistApi, type NailArtistInfoVO } from '@/api/admin'
import { adminTagApi, type Tag } from '@/api/admin'
import { adminProductApi, type Product } from '@/api/admin'
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
import { usePermission } from '@/utils/permission'
const { hasPermission, loadUserPermissions } = usePermission()
const getCurrentUserInfo = () => {
try {
const userInfoStr = localStorage.getItem('adminUserInfo')
if (userInfoStr) {
const userInfo = JSON.parse(userInfoStr)
isAdmin.value = userInfo.type === 4
isShopOwner.value = userInfo.type === 2
return userInfo
}
} catch (error: any) {
console.error('获取当前用户信息失败', error)
}
return null
}
const loading = ref(false)
const tagLoading = ref(false)
const productLoading = ref(false)
const searchText = ref('')
const nailArtistList = ref<NailArtistInfoVO[]>([])
const tagList = ref<Tag[]>([])
const productList = ref<Product[]>([])
const modalVisible = ref(false)
const modalLoading = ref(false)
const viewModalVisible = ref(false)
const isAdmin = ref(false)
const isShopOwner = ref(false)
const formRef = ref<FormInstance>()
const currentNailArtist = ref<NailArtistInfoVO | null>(null)
const currentUserInfo = getCurrentUserInfo()
const draftSavedAt = ref<number | null>(null)
const viewFormState = reactive({
nickname: '',
shopName: '',
identity: '',
experience: '',
skillsText: '',
statusText: '',
rating: '',
portfolioText: ''
})
const pagination = reactive({
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total: number) => `共 ${total} 条`
})
const formState = reactive({
userId: 0,
identity: '',
experience: 0,
skills: [] as string[],
rating: 0,
status: 1,
portfolio: [] as string[],
nickname: ''
})
const getDraftKey = () => buildDraftStorageKey('admin-nail-artists', 'edit', currentNailArtist.value?.userId ?? formState.userId ?? 'unknown')
const buildDraftPayload = () => ({
identity: formState.identity,
experience: formState.experience,
skills: [...formState.skills],
status: formState.status,
portfolio: [...formState.portfolio]
})
const restoreDraft = () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
if (!draft) {
draftSavedAt.value = null
return
}
Object.assign(formState, {
identity: draft.payload.identity ?? formState.identity,
experience: typeof draft.payload.experience === 'number' ? draft.payload.experience : formState.experience,
skills: Array.isArray(draft.payload.skills) ? draft.payload.skills : formState.skills,
status: typeof draft.payload.status === 'number'
? (draft.payload.status === 0 ? 0 : 1)
: formState.status,
portfolio: Array.isArray(draft.payload.portfolio) ? draft.payload.portfolio : formState.portfolio
})
draftSavedAt.value = draft.savedAt
message.success('已恢复暂存内容')
}
const handleSaveDraft = () => {
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload())
draftSavedAt.value = draft.savedAt
message.success('已暂存到本地')
}
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey())
draftSavedAt.value = null
if (showMessage) {
message.success('已清除暂存')
}
}
const formRules = {
identity: [{ required: true, message: '请输入身份', trigger: 'blur' }],
experience: [{ required: true, message: '请输入从业年限', trigger: 'blur' }],
skills: [{ required: true, message: '请选择技能标签', trigger: 'change' }],
status: [{ required: true, message: '请选择状态', trigger: 'change' }],
portfolio: [{ required: true, message: '请选择作品作品', trigger: 'change' }]
} as any
const columns = [
{ title: '美甲师姓名', dataIndex: 'nickname', key: 'nickname' },
{ title: '所属店铺', dataIndex: 'shopName', key: 'shopName' },
{ title: '身份', dataIndex: 'identity', key: 'identity' },
{ title: '从业年限', dataIndex: 'experience', key: 'experience' },
{ title: '评分', dataIndex: 'rating', key: 'rating' },
{ title: '状态', key: 'status', width: 100 },
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
]
const getStatusText = (status: number) => {
return status === 1 ? '营业中' : '休息中'
}
const getStatusColor = (status: number) => {
return status === 1 ? 'green' : 'default'
}
const fetchTagList = async () => {
tagLoading.value = true
try {
const res = await adminTagApi.listAllTags() as unknown as Tag[]
tagList.value = res || []
} catch (error) {
console.error('获取标签列表失败:', error)
} finally {
tagLoading.value = false
}
}
const fetchProductList = async () => {
productLoading.value = true
try {
const params: any = {
page: 1,
size: 1000
}
if (currentUserInfo && currentUserInfo.type !== 4 && currentUserInfo.shopId) {
params.shopId = currentUserInfo.shopId
}
const res = await adminProductApi.listProducts(params) as unknown as { list: Product[] }
productList.value = res.list || []
} catch (error) {
console.error('获取作品列表失败:', error)
} finally {
productLoading.value = false
}
}
const fetchNailArtistList = async () => {
loading.value = true
try {
const res = await adminNailArtistApi.listNailArtists() as unknown as NailArtistInfoVO[]
let filteredList = res || []
// 按搜索词过滤
if (searchText.value) {
filteredList = filteredList.filter((item: NailArtistInfoVO) =>
item.nickname?.includes(searchText.value)
)
}
nailArtistList.value = filteredList
pagination.total = filteredList.length || 0
} catch (error) {
message.error('获取美甲师列表失败')
} finally {
loading.value = false
}
}
const handleSearch = () => {
pagination.current = 1
fetchNailArtistList()
}
const handleTableChange = (pag: any) => {
pagination.current = pag.current
pagination.pageSize = pag.pageSize
fetchNailArtistList()
}
const showEditModal = (record: Record<string, any>) => {
currentNailArtist.value = record as NailArtistInfoVO
const lockedFields = {
userId: record.userId,
rating: record.rating || 0,
nickname: record.nickname || ''
}
Object.assign(formState, {
identity: record.identity || '',
experience: record.experience || 0,
skills: record.skills ? record.skills.split(',').filter(Boolean) : [],
status: record.status || 1,
portfolio: record.portfolio ? record.portfolio.split(',').filter(Boolean) : [],
...lockedFields
})
restoreDraft()
Object.assign(formState, lockedFields)
modalVisible.value = true
}
const showViewModal = (record: Record<string, any>) => {
const nailArtist = record as NailArtistInfoVO
// 构建技能标签文本
const skillsArray = nailArtist.skills ? nailArtist.skills.split(',').filter(Boolean) : []
const skillsText = skillsArray.map(skillId => {
const tag = tagList.value.find(t => t.id.toString() === skillId)
return tag ? tag.tagName : skillId
}).join(', ')
// 构建作品文本
const portfolioArray = nailArtist.portfolio ? nailArtist.portfolio.split(',').filter(Boolean) : []
const portfolioText = portfolioArray.map(productId => {
const product = productList.value.find(p => p.id.toString() === productId)
return product ? product.title : productId
}).join(', ')
Object.assign(viewFormState, {
nickname: nailArtist.nickname || '',
shopName: nailArtist.shopName || '',
identity: nailArtist.identity || '',
experience: (nailArtist.experience || 0).toString(),
skillsText: skillsText,
statusText: getStatusText(nailArtist.status || 1),
rating: (nailArtist.rating || 0).toString(),
portfolioText: portfolioText
})
viewModalVisible.value = true
}
const handleViewModalCancel = () => {
viewModalVisible.value = false
}
const handleModalOk = async () => {
try {
await formRef.value?.validate()
const targetUserId = currentNailArtist.value?.userId ?? formState.userId
if (!targetUserId) {
message.error('未获取到当前美甲师信息,请关闭弹窗后重试')
return
}
modalLoading.value = true
// 准备提交数据
const submitData = {
userId: targetUserId,
identity: formState.identity,
experience: formState.experience,
rating: formState.rating,
status: formState.status,
skills: formState.skills.join(','),
portfolio: formState.portfolio.join(',')
}
await adminNailArtistApi.saveNailArtistInfo(submitData)
message.success('保存成功')
handleClearDraft(false)
modalVisible.value = false
fetchNailArtistList()
} catch (error) {
console.error(error)
const errorMessage = (error as Error)?.message
if (errorMessage) {
message.error(errorMessage)
return
}
message.error('操作失败')
} finally {
modalLoading.value = false
}
}
const handleModalCancel = () => {
modalVisible.value = false
currentNailArtist.value = null
formRef.value?.resetFields()
}
onMounted(async () => {
await loadUserPermissions()
fetchTagList()
fetchProductList()
fetchNailArtistList()
})
</script>
<style scoped>
.nail-artists {
padding: 0;
}
</style>
-160
View File
@@ -1,160 +0,0 @@
<template>
<div class="orders">
<a-page-header title="订单管理" sub-title="管理系统订单" />
<a-card :bordered="false">
<a-table :columns="columns" :data-source="orders" :loading="loading" row-key="id">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'status'">
<a-tag :color="statusColor(record.status)">{{ record.statusText }}</a-tag>
</template>
<template v-else-if="column.key === 'totalAmount'">
¥{{ record.totalAmount.toFixed(2) }}
</template>
<template v-else-if="column.key === 'actualAmount'">
¥{{ record.actualAmount.toFixed(2) }}
</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button type="link" size="small" @click="currentOrder = record">查看</a-button>
<a-button
v-if="record.status === 1 && canProcessOrders"
type="primary"
size="small"
@click="process(record.id, 2)"
>
确认完成
</a-button>
<a-button
v-if="record.status === 1 && canProcessOrders && !isArtist"
danger
size="small"
@click="process(record.id, 3)"
>
取消订单
</a-button>
</a-space>
</template>
</template>
</a-table>
</a-card>
<a-modal v-model:open="detailVisible" title="订单详情" width="860px" @cancel="currentOrder = null">
<template v-if="currentOrder">
<a-descriptions :column="2">
<a-descriptions-item label="订单编号">{{ currentOrder.orderNo }}</a-descriptions-item>
<a-descriptions-item label="用户ID">{{ currentOrder.userId }}</a-descriptions-item>
<a-descriptions-item label="订单总额">¥{{ currentOrder.totalAmount.toFixed(2) }}</a-descriptions-item>
<a-descriptions-item label="实付金额">¥{{ currentOrder.actualAmount.toFixed(2) }}</a-descriptions-item>
<a-descriptions-item label="优惠券">{{ currentOrder.couponName || '无' }}</a-descriptions-item>
<a-descriptions-item label="订单状态">{{ currentOrder.statusText }}</a-descriptions-item>
<a-descriptions-item label="创建时间" :span="2">{{ currentOrder.createTime }}</a-descriptions-item>
</a-descriptions>
<a-divider>订单项目</a-divider>
<a-table :columns="itemColumns" :data-source="currentOrder.items" row-key="id" :pagination="false">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'price'">¥{{ record.price.toFixed(2) }}</template>
<template v-else-if="column.key === 'totalPrice'">¥{{ (record.price * record.quantity).toFixed(2) }}</template>
</template>
</a-table>
</template>
</a-modal>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
import { orderApi } from '../../api/order'
import { usePermission } from '@/utils/permission'
import type { IdType } from '@/utils/id'
import { sameId } from '@/utils/id'
const orders = ref<any[]>([])
const loading = ref(false)
const currentOrder = ref<any | null>(null)
const currentUserType = ref<number | null>(null)
const { hasPermission, loadUserPermissions } = usePermission()
const detailVisible = computed({
get: () => !!currentOrder.value,
set: value => { if (!value) currentOrder.value = null }
})
const canProcessOrders = computed(() => hasPermission('order:process'))
const isArtist = computed(() => currentUserType.value === 3)
const columns = [
{ title: '订单编号', dataIndex: 'orderNo', key: 'orderNo' },
{ title: '用户ID', dataIndex: 'userId', key: 'userId', width: 100 },
{ title: '订单总额', key: 'totalAmount', width: 120 },
{ title: '实付金额', key: 'actualAmount', width: 120 },
{ title: '优惠券', dataIndex: 'couponName', key: 'couponName', width: 140 },
{ title: '状态', key: 'status', width: 100 },
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 180 },
{ title: '操作', key: 'actions', width: 180 }
]
const itemColumns = [
{ title: '商品ID', dataIndex: 'productId', key: 'productId', width: 100 },
{ title: '商品名称', dataIndex: 'productTitle', key: 'productTitle' },
{ title: '美甲师', dataIndex: 'artistName', key: 'artistName', width: 120 },
{ title: '预约时间', dataIndex: 'appointmentTime', key: 'appointmentTime', width: 180 },
{ title: '单价', key: 'price', width: 100 },
{ title: '数量', dataIndex: 'quantity', key: 'quantity', width: 80 },
{ title: '总价', key: 'totalPrice', width: 100 }
]
const statusColor = (status: number) => {
if (status === 1) return 'orange'
if (status === 2) return 'green'
if (status === 3) return 'red'
return 'default'
}
const resolveCurrentUserType = () => {
const cached = localStorage.getItem('adminUserInfo') || sessionStorage.getItem('adminUserInfo')
if (!cached) {
currentUserType.value = null
return
}
try {
currentUserType.value = JSON.parse(cached)?.type ?? null
} catch {
currentUserType.value = null
}
}
const loadOrders = async () => {
loading.value = true
try {
orders.value = await orderApi.getAllOrders() as unknown as any[]
} catch {
message.error('获取订单列表失败')
} finally {
loading.value = false
}
}
const process = async (orderId: IdType, status: number) => {
try {
await orderApi.processOrder(orderId, status)
message.success('操作成功')
await loadOrders()
if (sameId(currentOrder.value?.id, orderId)) {
currentOrder.value = orders.value.find(order => sameId(order.id, orderId)) || null
}
} catch {
message.error('操作失败')
}
}
onMounted(async () => {
resolveCurrentUserType()
await loadUserPermissions()
await loadOrders()
})
</script>
<style scoped>
.orders { padding: 0; }
</style>
@@ -1,565 +0,0 @@
<template>
<div class="permissions">
<a-page-header title="权限管理" sub-title="管理系统权限和用户权限分配" />
<a-card :bordered="false">
<a-tabs v-model:activeKey="activeTab">
<a-tab-pane key="permissions" tab="权限列表">
<div style="margin-bottom: 16px; text-align: right;">
<a-button v-if="hasPermission('permission:create')" type="primary" @click="showAddPermissionModal">
<template #icon>
<PlusOutlined />
</template>
新增权限
</a-button>
</div>
<a-table
:columns="permissionColumns"
:data-source="permissionList"
:loading="loading"
:pagination="permissionPagination"
:scroll="{ x: 1080 }"
@change="handlePermissionTableChange"
row-key="id"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'permissionGroup'">
<a-tag color="purple">{{ record.permissionGroup }}</a-tag>
</template>
<template v-else-if="column.key === 'permissionCode'">
<div style="max-width: 220px;">
<TableEllipsisText :text="record.permissionCode" />
</div>
</template>
<template v-else-if="column.key === 'permissionName'">
<div style="max-width: 180px;">
<TableEllipsisText :text="record.permissionName" />
</div>
</template>
<template v-else-if="column.key === 'description'">
<div style="max-width: 320px;">
<TableEllipsisText :text="record.description" :lines="2" />
</div>
</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button v-if="hasPermission('permission:edit')" type="link" size="small" @click="showEditPermissionModal(record)">
编辑
</a-button>
<a-popconfirm
v-if="hasPermission('permission:delete')"
title="确定要删除这个权限吗?"
@confirm="handleDeletePermission(record)"
>
<a-button type="link" size="small" danger>
删除
</a-button>
</a-popconfirm>
</a-space>
</template>
</template>
</a-table>
</a-tab-pane>
<a-tab-pane v-if="hasPermission('permission:assign')" key="user-permissions" tab="用户权限分配">
<a-row :gutter="16">
<a-col :span="8">
<a-card title="选择用户" :bordered="false">
<a-input-search
v-model:value="userSearchText"
placeholder="搜索用户"
style="margin-bottom: 16px"
@search="handleUserSearch"
/>
<a-list
:data-source="filteredUserList"
:loading="userLoading"
item-layout="horizontal"
size="small"
>
<template #renderItem="{ item }">
<a-list-item
:class="{ selected: sameId(selectedUser?.id, item.id) }"
style="cursor: pointer;"
@click="selectUser(item)"
>
<a-list-item-meta>
<template #avatar>
<a-avatar :src="item.avatar || DEFAULT_AVATAR" />
</template>
<template #title>{{ item.nickname }}</template>
<template #description>{{ item.account }} - {{ getUserTypeText(item.type) }}</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
</a-card>
</a-col>
<a-col :span="16">
<a-card
title="分配权限"
:bordered="false"
>
<template #extra>
<a-button v-if="selectedUser && hasPermission('permission:assign')" type="primary" @click="handleSaveUserPermissions">
保存权限
</a-button>
</template>
<template v-if="selectedUser">
<a-alert
:message="`当前用户: ${selectedUser.nickname}`"
:description="`用户类型: ${getUserTypeText(selectedUser.type)}`"
type="info"
show-icon
style="margin-bottom: 16px"
/>
<a-alert
v-if="disabledPermissionCount > 0"
:message="`有 ${disabledPermissionCount} 项权限不在该角色可分配范围内,已禁止选择`"
type="warning"
show-icon
style="margin-bottom: 16px"
/>
<a-spin :spinning="assignLoading">
<a-checkbox-group v-model:value="selectedPermissions">
<a-collapse v-model:activeKey="activeCollapseKeys">
<a-collapse-panel
v-for="(permissions, group) in groupedPermissions"
:key="group"
:header="group"
>
<a-space direction="vertical" style="width: 100%">
<a-checkbox
v-for="permission in permissions"
:key="permission.id"
:value="permission.id"
:disabled="isPermissionDisabled(permission)"
>
{{ permission.permissionName }}
<span style="color: #999; font-size: 12px; margin-left: 8px;">
({{ permission.permissionCode }})
</span>
<span
v-if="isPermissionDisabled(permission)"
style="color: #ff4d4f; font-size: 12px; margin-left: 8px;"
>
不可分配
</span>
</a-checkbox>
</a-space>
</a-collapse-panel>
</a-collapse>
</a-checkbox-group>
</a-spin>
</template>
<a-empty v-else description="请先选择一个用户" />
</a-card>
</a-col>
</a-row>
</a-tab-pane>
</a-tabs>
</a-card>
<a-modal
v-model:open="permissionModalVisible"
:title="isEditPermission ? '编辑权限' : '新增权限'"
@ok="handlePermissionModalOk"
@cancel="handlePermissionModalCancel"
:confirmLoading="permissionModalLoading"
>
<DraftActions
:saved-at="draftSavedAt"
@save="handleSaveDraft"
@clear="handleClearDraft"
/>
<a-form
ref="permissionFormRef"
:model="permissionFormState"
:rules="permissionFormRules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<a-form-item label="权限编码" name="permissionCode">
<a-input v-model:value="permissionFormState.permissionCode" placeholder="例如:product:add" />
</a-form-item>
<a-form-item label="权限名称" name="permissionName">
<a-input v-model:value="permissionFormState.permissionName" placeholder="例如:添加作品" />
</a-form-item>
<a-form-item label="权限分组" name="permissionGroup">
<a-select v-model:value="permissionFormState.permissionGroup" placeholder="请选择权限分组">
<a-select-option value="作品管理">作品管理</a-select-option>
<a-select-option value="店铺管理">店铺管理</a-select-option>
<a-select-option value="用户管理">用户管理</a-select-option>
<a-select-option value="权限管理">权限管理</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="权限描述" name="description">
<a-textarea
v-model:value="permissionFormState.description"
placeholder="请输入权限描述"
:rows="3"
/>
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import { PlusOutlined } from '@ant-design/icons-vue'
import DraftActions from '@/components/DraftActions.vue'
import TableEllipsisText from '@/components/TableEllipsisText.vue'
import { DEFAULT_AVATAR } from '@/constants'
import { userApi, type UserVO } from '@/api/admin'
import { permissionApi, type PermissionVO } from '@/api/permission'
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
import { usePermission } from '@/utils/permission'
import type { IdType } from '@/utils/id'
import { sameId } from '@/utils/id'
const { hasPermission, loadUserPermissions } = usePermission()
const activeTab = ref('permissions')
const loading = ref(false)
const permissionList = ref<PermissionVO[]>([])
const permissionModalVisible = ref(false)
const permissionModalLoading = ref(false)
const isEditPermission = ref(false)
const permissionFormRef = ref<FormInstance>()
const currentPermission = ref<PermissionVO | null>(null)
const draftSavedAt = ref<number | null>(null)
const permissionPagination = reactive({
current: 1,
pageSize: 20,
total: 0,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total: number) => `共 ${total} 条`
})
const permissionFormState = reactive({
permissionCode: '',
permissionName: '',
permissionGroup: '',
description: ''
})
const getDraftKey = () => buildDraftStorageKey('admin-permissions', isEditPermission.value ? 'edit' : 'create', currentPermission.value?.id ?? 'new')
const buildDraftPayload = () => ({
permissionCode: permissionFormState.permissionCode,
permissionName: permissionFormState.permissionName,
permissionGroup: permissionFormState.permissionGroup,
description: permissionFormState.description
})
const restoreDraft = () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
if (!draft) {
draftSavedAt.value = null
return
}
Object.assign(permissionFormState, draft.payload)
draftSavedAt.value = draft.savedAt
message.success('已恢复暂存内容')
}
const handleSaveDraft = () => {
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload())
draftSavedAt.value = draft.savedAt
message.success('已暂存到本地')
}
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey())
draftSavedAt.value = null
if (showMessage) {
message.success('已清除暂存')
}
}
const permissionFormRules: Record<string, Rule[]> = {
permissionCode: [{ required: true, message: '请输入权限编码', trigger: 'blur' }],
permissionName: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
permissionGroup: [{ required: true, message: '请选择权限分组', trigger: 'change' }],
description: [{ required: true, message: '请输入权限描述', trigger: 'blur' }]
}
const permissionColumns = [
{ title: '权限编码', dataIndex: 'permissionCode', key: 'permissionCode' },
{ title: '权限名称', dataIndex: 'permissionName', key: 'permissionName' },
{ title: '权限分组', key: 'permissionGroup', width: 120 },
{ title: '权限描述', dataIndex: 'description', key: 'description' },
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
]
const userLoading = ref(false)
const userSearchText = ref('')
const userList = ref<UserVO[]>([])
const selectedUser = ref<UserVO | null>(null)
const assignLoading = ref(false)
const selectedPermissions = ref<IdType[]>([])
const assignablePermissionIds = ref<IdType[]>([])
const activeCollapseKeys = ref<string[]>(['作品管理', '店铺管理', '用户管理', '权限管理'])
const currentLoginUser = ref<UserVO | null>(null)
// 权限 ID 同样可能以字符串形式返回,所以这里统一转成字符串集合做包含判断。
const assignablePermissionIdSet = computed(() => new Set(assignablePermissionIds.value.map(id => String(id))))
const disabledPermissionCount = computed(() =>
permissionList.value.filter(permission => !assignablePermissionIdSet.value.has(String(permission.id))).length
)
const groupedPermissions = computed(() => {
const groups: Record<string, PermissionVO[]> = {}
permissionList.value.forEach(p => {
const groupName = p.permissionGroup
if (!groups[groupName]) {
groups[groupName] = []
}
groups[groupName]!.push(p)
})
return groups
})
const getUserTypeText = (type: number) => {
const map: Record<number, string> = {
0: '用户',
2: '店长',
3: '美甲师',
4: '管理员'
}
return map[type] || '未知'
}
const filteredUserList = computed(() => {
if (!currentLoginUser.value) return []
const currentUserId = currentLoginUser.value.id
// 管理员可以看到所有用户(除了普通用户和自己)
if (currentLoginUser.value.type === 4) {
return userList.value.filter(user => user.type !== 0 && !sameId(user.id, currentUserId))
}
// 店长只能看到美甲师(除了自己)
if (currentLoginUser.value.type === 2) {
return userList.value.filter(user => user.type === 3 && !sameId(user.id, currentUserId))
}
// 其他用户类型(如美甲师)不能管理权限
return []
})
const isPermissionDisabled = (permission: PermissionVO) => {
if (!selectedUser.value) {
return true
}
return !assignablePermissionIdSet.value.has(String(permission.id))
}
const resolveRequestErrorMessage = (error: any, fallback: string) => {
return error?.response?.data?.message || error?.message || fallback
}
const fetchCurrentUser = async () => {
try {
// 尝试从API获取用户信息
try {
const res = await userApi.getUserInfo()
currentLoginUser.value = res as unknown as UserVO
} catch (apiError) {
// 如果API调用失败,尝试从本地存储获取
const userInfoStr = localStorage.getItem('adminUserInfo')
if (userInfoStr) {
try {
const userInfo = JSON.parse(userInfoStr)
currentLoginUser.value = userInfo as UserVO
} catch (parseError) {
console.error('解析本地存储的用户信息失败:', parseError)
}
} else {
console.error('获取当前用户信息失败,本地存储也没有用户信息')
}
}
} catch (error) {
console.error('获取当前用户信息失败:', error)
}
}
const fetchPermissionList = async () => {
loading.value = true
try {
const res = await permissionApi.listAllPermissions() as unknown as PermissionVO[]
permissionList.value = res || []
permissionPagination.total = res?.length || 0
} catch (error) {
message.error('获取权限列表失败')
} finally {
loading.value = false
}
}
const fetchUserList = async () => {
userLoading.value = true
try {
const params: any = {
page: 1,
size: 100,
keyword: userSearchText.value
}
// 如果当前用户不是管理员,只获取当前店铺的用户
if (currentLoginUser.value && currentLoginUser.value.type !== 4 && currentLoginUser.value.shopId) {
params.shopId = currentLoginUser.value.shopId
}
const res = await userApi.listUsers(params) as unknown as { list: UserVO[] }
userList.value = res.list || []
} catch (error) {
message.error('获取用户列表失败')
} finally {
userLoading.value = false
}
}
const handlePermissionTableChange = (pag: any) => {
permissionPagination.current = pag.current
permissionPagination.pageSize = pag.pageSize
fetchPermissionList()
}
const handleUserSearch = () => {
fetchUserList()
}
const selectUser = async (user: UserVO) => {
selectedUser.value = user
assignLoading.value = true
try {
// 已分配权限和“当前角色允许分配的权限”需要分开拿,前端只保留交集,避免保存时越权。
const [assignedPermissions, allowedIds] = await Promise.all([
permissionApi.getUserPermissions(user.id) as unknown as Promise<PermissionVO[]>,
permissionApi.getAssignablePermissionIds(user.id) as unknown as Promise<IdType[]>
])
assignablePermissionIds.value = allowedIds || []
const allowedIdSet = new Set(assignablePermissionIds.value.map(id => String(id)))
const assignedIds = (assignedPermissions || []).map((p: PermissionVO) => p.id)
selectedPermissions.value = assignedIds.filter(id => allowedIdSet.has(String(id)))
const trimmedCount = assignedIds.length - selectedPermissions.value.length
if (trimmedCount > 0) {
message.warning(`已自动排除 ${trimmedCount} 项超出当前角色允许范围的权限`)
}
} catch (error: any) {
message.error(resolveRequestErrorMessage(error, '获取用户权限失败'))
assignablePermissionIds.value = []
selectedPermissions.value = []
} finally {
assignLoading.value = false
}
}
const handleSaveUserPermissions = async () => {
if (!selectedUser.value) return
try {
await permissionApi.assignUserPermissions(selectedUser.value.id, selectedPermissions.value)
message.success('权限保存成功')
// 重新加载当前用户的权限
await loadUserPermissions()
} catch (error: any) {
message.error(resolveRequestErrorMessage(error, '权限保存失败'))
}
}
const showAddPermissionModal = () => {
isEditPermission.value = false
currentPermission.value = null
Object.assign(permissionFormState, {
permissionCode: '',
permissionName: '',
permissionGroup: '',
description: ''
})
restoreDraft()
permissionModalVisible.value = true
}
const showEditPermissionModal = (record: Record<string, any>) => {
isEditPermission.value = true
currentPermission.value = record as PermissionVO
Object.assign(permissionFormState, {
permissionCode: record.permissionCode,
permissionName: record.permissionName,
permissionGroup: record.permissionGroup,
description: record.description
})
restoreDraft()
permissionModalVisible.value = true
}
const handlePermissionModalOk = async () => {
try {
await permissionFormRef.value?.validate()
permissionModalLoading.value = true
if (isEditPermission.value && currentPermission.value) {
await permissionApi.updatePermission(currentPermission.value.id, permissionFormState)
message.success('更新成功')
} else {
await permissionApi.createPermission(permissionFormState)
message.success('创建成功')
}
handleClearDraft(false)
permissionModalVisible.value = false
fetchPermissionList()
} catch (error) {
console.error(error)
} finally {
permissionModalLoading.value = false
}
}
const handlePermissionModalCancel = () => {
permissionModalVisible.value = false
permissionFormRef.value?.resetFields()
}
const handleDeletePermission = async (record: Record<string, any>) => {
try {
await permissionApi.deletePermission((record as PermissionVO).id)
message.success('删除成功')
fetchPermissionList()
} catch (error) {
message.error('删除失败')
}
}
onMounted(async () => {
await fetchCurrentUser()
await loadUserPermissions()
fetchPermissionList()
// 确保在获取当前用户信息后再获取用户列表
setTimeout(() => {
fetchUserList()
}, 100)
})
</script>
<style scoped>
.permissions {
padding: 0;
}
.selected {
background: #e6f7ff !important;
border-left: 3px solid #1890ff;
}
</style>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-479
View File
@@ -1,479 +0,0 @@
<template>
<div class="tags">
<a-page-header title="标签管理" sub-title="管理系统标签" />
<a-card :bordered="false">
<template #extra>
<a-space>
<a-input-search
v-model:value="searchText"
placeholder="搜索标签名称"
style="width: 250px"
@search="handleSearch"
/>
<a-button v-if="hasPermission('tag:create')" type="primary" @click="showAddModal">
<template #icon>
<PlusOutlined />
</template>
新增标签
</a-button>
</a-space>
</template>
<a-table
:columns="columns"
:data-source="tagList"
:loading="loading"
:pagination="pagination"
@change="handleTableChange"
row-key="id"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'color'">
<span
class="tag-preview"
:style="{
backgroundColor: record.bgColor,
color: record.textColor,
borderColor: record.borderColor
}"
>
{{ record.tagName }}
</span>
</template>
<template v-else-if="column.key === 'shop'">
<span>{{ record.shopName || getShopName(record.shopId) }}</span>
</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button v-if="hasPermission('tag:view')" type="link" size="small" @click="showViewModal(record)">
查看
</a-button>
<a-button v-if="hasPermission('tag:edit')" type="link" size="small" @click="showEditModal(record)">
编辑
</a-button>
<a-button v-if="hasPermission('tag:delete')" type="link" size="small" danger @click="handleDelete(record)">
删除
</a-button>
</a-space>
</template>
</template>
</a-table>
</a-card>
<a-modal
v-model:open="modalVisible"
:title="isEdit ? '编辑标签' : '新增标签'"
@ok="handleModalOk"
@cancel="handleModalCancel"
:confirmLoading="modalLoading"
width="600px"
>
<DraftActions
:saved-at="draftSavedAt"
@save="handleSaveDraft"
@clear="handleClearDraft"
/>
<a-form
ref="formRef"
:model="formState"
:rules="formRules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<a-form-item label="标签名称" name="tagName">
<a-input v-model:value="formState.tagName" placeholder="请输入标签名称" />
</a-form-item>
<a-form-item label="所属店铺" name="shopId">
<a-select
v-model:value="formState.shopId"
placeholder="请选择所属店铺"
style="width: 100%"
:loading="loadingShops"
:disabled="getCurrentUserInfo()?.type === 2"
>
<a-select-option
v-if="shops.length === 0"
disabled
value=""
>
暂无店铺数据
</a-select-option>
<a-select-option
v-for="shop in shops"
:key="shop.id"
:value="shop.id"
>
{{ shop.shopName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="文字颜色" name="textColor">
<el-color-picker v-model="formState.textColor" />
</a-form-item>
<a-form-item label="背景颜色" name="bgColor">
<el-color-picker v-model="formState.bgColor" />
</a-form-item>
<a-form-item label="边框颜色" name="borderColor">
<el-color-picker v-model="formState.borderColor" />
</a-form-item>
<a-form-item label="预览">
<span
class="tag-preview"
:style="{
backgroundColor: formState.bgColor,
color: formState.textColor,
borderColor: formState.borderColor
}"
>
{{ formState.tagName }}
</span>
</a-form-item>
</a-form>
</a-modal>
<!-- 查看标签详情模态框 -->
<a-modal
v-model:open="viewModalVisible"
title="查看标签详情"
@cancel="handleViewModalCancel"
width="600px"
>
<a-form
:model="viewFormState"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<a-form-item label="标签名称">
<a-input v-model:value="viewFormState.tagName" :disabled="true" />
</a-form-item>
<a-form-item label="所属店铺">
<a-select v-model:value="viewFormState.shopId" :disabled="true">
<a-select-option
v-for="shop in shops"
:key="shop.id"
:value="shop.id"
>
{{ shop.shopName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="文字颜色">
<el-color-picker v-model="viewFormState.textColor" disabled />
</a-form-item>
<a-form-item label="背景颜色">
<el-color-picker v-model="viewFormState.bgColor" disabled />
</a-form-item>
<a-form-item label="边框颜色">
<el-color-picker v-model="viewFormState.borderColor" disabled />
</a-form-item>
<a-form-item label="预览">
<span
class="tag-preview"
:style="{
backgroundColor: viewFormState.bgColor,
color: viewFormState.textColor,
borderColor: viewFormState.borderColor
}"
>
{{ viewFormState.tagName }}
</span>
</a-form-item>
</a-form>
</a-modal>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import DraftActions from '@/components/DraftActions.vue'
import { adminTagApi, adminShopApi, type Shop } from '@/api/admin'
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
import type { IdType } from '@/utils/id'
import { usePermission } from '@/utils/permission'
const { hasPermission, loadUserPermissions } = usePermission()
const getCurrentUserInfo = () => {
try {
const userInfoStr = localStorage.getItem('adminUserInfo')
if (userInfoStr) {
const userInfo = JSON.parse(userInfoStr)
return userInfo
}
} catch (error) {
console.error('获取当前用户信息失败', error)
}
return null
}
const loading = ref(false)
const modalVisible = ref(false)
const viewModalVisible = ref(false)
const modalLoading = ref(false)
const isEdit = ref(false)
const searchText = ref('')
const formRef = ref<FormInstance>()
const currentTag = ref<any>(null)
const draftSavedAt = ref<number | null>(null)
// 查看标签相关状态
const viewFormState = reactive({
tagName: '',
shopId: undefined as number | undefined,
textColor: '#333333',
bgColor: '#FFFFFF',
borderColor: '#E5E5E5'
})
const tagList = ref<any[]>([])
const shops = ref<Shop[]>([])
const loadingShops = ref(false)
const pagination = reactive({
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total: number) => `共 ${total} 条`
})
const formState = reactive({
tagName: '',
shopId: undefined as number | undefined,
textColor: '#333333',
bgColor: '#FFFFFF',
borderColor: '#E5E5E5'
})
const getDraftKey = () => buildDraftStorageKey('admin-tags', isEdit.value ? 'edit' : 'create', currentTag.value?.id ?? 'new')
const buildDraftPayload = () => ({
tagName: formState.tagName,
shopId: formState.shopId,
textColor: formState.textColor,
bgColor: formState.bgColor,
borderColor: formState.borderColor
})
const restoreDraft = () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
if (!draft) {
draftSavedAt.value = null
return
}
Object.assign(formState, draft.payload)
draftSavedAt.value = draft.savedAt
message.success('已恢复暂存内容')
}
const handleSaveDraft = () => {
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload())
draftSavedAt.value = draft.savedAt
message.success('已暂存到本地')
}
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey())
draftSavedAt.value = null
if (showMessage) {
message.success('已清除暂存')
}
}
const formRules = {
tagName: [{ required: true, message: '请输入标签名称', trigger: 'blur' }],
shopId: [{ required: true, message: '请选择所属店铺', trigger: 'change' }]
} as any
const columns = [
{ title: '标签名称', dataIndex: 'tagName', key: 'tagName' },
{ title: '所属店铺', key: 'shop', width: 150 },
{ title: '预览', key: 'color', width: 150 },
{ title: '文字颜色', dataIndex: 'textColor', key: 'textColor', width: 120 },
{ title: '背景颜色', dataIndex: 'bgColor', key: 'bgColor', width: 120 },
{ title: '边框颜色', dataIndex: 'borderColor', key: 'borderColor', width: 120 },
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
]
const fetchTags = async () => {
loading.value = true
try {
const currentUser = getCurrentUserInfo()
const shopId = (currentUser && currentUser.shopId) ? currentUser.shopId : undefined
let tags
if (shopId) {
tags = await adminTagApi.listTagsByShopId(shopId) as unknown as any[]
} else {
tags = await adminTagApi.listAllTags() as unknown as any[]
}
tagList.value = tags || []
pagination.total = tagList.value.length
} catch (error) {
console.error('获取标签列表失败:', error)
message.error('获取标签列表失败')
} finally {
loading.value = false
}
}
const fetchShops = async () => {
loadingShops.value = true
try {
const res = await adminShopApi.listAllShops() as unknown as any[]
shops.value = res || []
} catch (error) {
console.error('获取店铺列表失败:', error)
} finally {
loadingShops.value = false
}
}
const normalizeShopIdValue = (value: string | number | undefined | null) => {
if (value === undefined || value === null || value === '') {
return ''
}
return String(value)
}
const getShopName = (shopId: IdType | undefined) => {
const normalizedShopId = normalizeShopIdValue(shopId)
const shop = shops.value.find(s => normalizeShopIdValue(s.id) === normalizedShopId)
return shop ? shop.shopName : '未知店铺'
}
const handleSearch = () => {
pagination.current = 1
fetchTags()
}
const handleTableChange = (pag: any) => {
pagination.current = pag.current
pagination.pageSize = pag.pageSize
fetchTags()
}
const showAddModal = () => {
isEdit.value = false
currentTag.value = null
const currentUser = getCurrentUserInfo()
const shopId = (currentUser && currentUser.shopId) ? currentUser.shopId : undefined
Object.assign(formState, {
tagName: '',
shopId: shopId,
textColor: '#333333',
bgColor: '#FFFFFF',
borderColor: '#E5E5E5'
})
restoreDraft()
modalVisible.value = true
}
const showEditModal = (record: any) => {
isEdit.value = true
currentTag.value = record
Object.assign(formState, {
tagName: record.tagName,
shopId: record.shopId,
textColor: record.textColor,
bgColor: record.bgColor,
borderColor: record.borderColor
})
restoreDraft()
modalVisible.value = true
}
const showViewModal = (record: any) => {
Object.assign(viewFormState, {
tagName: record.tagName,
shopId: record.shopId,
textColor: record.textColor,
bgColor: record.bgColor,
borderColor: record.borderColor
})
viewModalVisible.value = true
}
const handleViewModalCancel = () => {
viewModalVisible.value = false
}
const handleModalOk = async () => {
try {
await formRef.value?.validate()
modalLoading.value = true
const requestData = {
tagName: formState.tagName,
shopId: formState.shopId,
textColor: formState.textColor,
bgColor: formState.bgColor,
borderColor: formState.borderColor
}
if (isEdit.value && currentTag.value) {
await adminTagApi.updateTag(currentTag.value.id, requestData)
message.success('更新成功')
} else {
await adminTagApi.createTag(requestData)
message.success('创建成功')
}
handleClearDraft(false)
modalVisible.value = false
fetchTags()
} catch (error: any) {
console.error('Error:', error)
message.error(error?.message || (isEdit.value ? '更新失败' : '创建失败'))
} finally {
modalLoading.value = false
}
}
const handleModalCancel = () => {
modalVisible.value = false
formRef.value?.resetFields()
}
const handleDelete = (record: any) => {
Modal.confirm({
title: '确认删除',
content: `确定要删除标签 ${record.tagName} 吗?`,
onOk: async () => {
try {
await adminTagApi.deleteTag(record.id)
message.success('删除成功')
fetchTags()
} catch (error) {
message.error('删除失败')
}
}
})
}
onMounted(async () => {
await loadUserPermissions()
await fetchShops()
await fetchTags()
})
</script>
<style scoped>
.tags {
padding: 0;
}
.tag-preview {
display: inline-block;
padding: 4px 12px;
border-radius: 4px;
border: 1px solid;
font-size: 14px;
}
</style>
File diff suppressed because it is too large Load Diff
-20
View File
@@ -1,20 +0,0 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
},
"types": ["vite/client"],
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
}
-7
View File
@@ -1,7 +0,0 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
-26
View File
@@ -1,26 +0,0 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}
-60
View File
@@ -1,60 +0,0 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
// https://vite.dev/config/
export default defineConfig({
// 配置服务器中间件
plugins: [
vue(),
AutoImport({
resolvers: [ElementPlusResolver()],
imports: ['vue', 'vue-router', 'pinia'],
dts: 'src/auto-import.d.ts',
}),
Components({
resolvers: [ElementPlusResolver(), AntDesignVueResolver({ importStyle: 'less' })],
dts: 'src/components.d.ts',
}),
// 添加 IP 访问控制中间件
{
name: 'ip-access-control',
configureServer(server) {
// 暂时禁用 IP 访问控制,允许所有 IP 访问
// 生产环境应该重新启用并配置正确的 IP 列表
server.middlewares.use((_req, _res, next) => {
// 直接允许所有 IP 访问
next()
})
},
},
],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
server: {
port: 3000,
host: true,
proxy: {
'/api': {
target: 'http://wcy111.top:8088', // 代理到 Gateway
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
// 配置允许的主机名
allowedHosts: [
'localhost',
'127.0.0.1',
'2666.online', // 允许通过 2666.online 访问
'wcy111.top', // 允许通过 wcy111.top 访问
// 可以添加更多允许的域名
],
},
})