功能:更新消息中心和 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
+657
View File
@@ -0,0 +1,657 @@
import axios, { AxiosError, type AxiosProgressEvent } from 'axios'
import { message } from 'ant-design-vue'
import { ADMIN_API_BASE_URL } from '../config/api'
import type { IdType } from '@/utils/id'
import { clearAdminSessionStorage } from '@/utils/admin-session'
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 = () => {
clearAdminSessionStorage()
if (Date.now() - lastErrorTime > ERROR_DEBOUNCE_TIME || lastErrorMessage !== '登录已过期,请重新登录') {
showError('登录已过期,请重新登录')
}
setTimeout(() => {
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
@@ -0,0 +1,110 @@
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
@@ -0,0 +1,39 @@
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
@@ -0,0 +1,156 @@
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
@@ -0,0 +1,62 @@
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 }
})
}
}
+220
View File
@@ -0,0 +1,220 @@
import axios, { AxiosError } from 'axios'
import { authApi } from './auth'
import { adminAuthApi } from './admin'
import { wishlistApi } from './wishlist'
import { message } from 'ant-design-vue'
import { API_BASE_URL } from '../config/api'
import type { IdType } from '@/utils/id'
import { clearAdminSessionStorage } from '@/utils/admin-session'
// 防重复提示标志
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
clearAdminSessionStorage()
} 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) {
window.location.href = '/admin/login'
} else {
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
@@ -0,0 +1,58 @@
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
@@ -0,0 +1,59 @@
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
@@ -0,0 +1,96 @@
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
@@ -0,0 +1,28 @@
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
@@ -0,0 +1,67 @@
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
@@ -0,0 +1,41 @@
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
@@ -0,0 +1,139 @@
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
@@ -0,0 +1,46 @@
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[]
}
}