Files
JayuCloud/Frontend/src/api/admin.ts
T

669 lines
18 KiB
TypeScript
Raw Normal View History

2026-03-26 11:41:38 +08:00
import axios, { AxiosError, type AxiosProgressEvent } from 'axios'
2026-02-25 10:37:16 +08:00
import router from '../router'
import { message } from 'ant-design-vue'
2026-03-10 23:23:15 +08:00
import { ADMIN_API_BASE_URL } from '../config/api'
2026-03-27 14:55:41 +08:00
import type { IdType } from '@/utils/id'
2026-02-25 10:37:16 +08:00
2026-02-26 23:28:24 +08:00
let lastErrorTime = 0
let lastErrorMessage = ''
const ERROR_DEBOUNCE_TIME = 1000
2026-02-26 23:28:24 +08:00
2026-02-25 10:37:16 +08:00
const adminApi = axios.create({
2026-03-10 23:23:15 +08:00
baseURL: ADMIN_API_BASE_URL,
2026-02-25 10:37:16 +08:00
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)
}
2026-02-25 10:37:16 +08:00
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}`
}
2026-02-25 10:37:16 +08:00
}
return config
},
error => Promise.reject(error)
2026-02-25 10:37:16 +08:00
)
adminApi.interceptors.response.use(
response => {
const res = response.data
if (res.code !== 200) {
2026-02-26 23:28:24 +08:00
const errorMsg = res.message || '请求失败'
if (!errorMsg.includes('权限') && !errorMsg.includes('permission')) {
showError(errorMsg)
2026-02-26 23:28:24 +08:00
} else {
console.error('权限不足:', errorMsg)
}
return Promise.reject(new Error(errorMsg))
}
2026-03-02 10:13:20 +08:00
return res.data as any
2026-02-25 10:37:16 +08:00
},
async (error: AxiosError) => {
const originalRequest = error.config as any
2026-02-26 23:28:24 +08:00
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)
2026-02-26 23:28:24 +08:00
})
}
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
2026-02-26 23:28:24 +08:00
}
}
handleAdminTokenExpired()
} else if (error.response?.status !== 403) {
const errorMsg = (error.response?.data as any)?.message || error.message || '请求失败'
2026-02-26 23:28:24 +08:00
showError(errorMsg)
} else {
console.error('权限不足:', error)
2026-02-25 10:37:16 +08:00
}
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))
}
2026-02-25 10:37:16 +08:00
console.error('Admin API Error:', error)
return Promise.reject(error)
}
)
export interface AdminLoginRequest {
2026-02-25 11:08:02 +08:00
account: string
2026-02-25 10:37:16 +08:00
password: string
2026-03-27 14:55:41 +08:00
shopId?: IdType
2026-02-25 10:37:16 +08:00
}
export interface AdminLoginResponse {
accessToken: string
refreshToken: string
userInfo: any
}
export interface LoginShopSelectionResponse {
allowShoplessLogin: boolean
message: string
shops: Array<{
2026-03-27 14:55:41 +08:00
id: IdType
shopName: string
}>
}
2026-02-25 10:37:16 +08:00
export const adminAuthApi = {
login: (data: AdminLoginRequest) => {
2026-02-27 14:20:20 +08:00
return adminApi.post<AdminLoginResponse>('/auth/login', data)
2026-02-25 10:37:16 +08:00
},
getLoginShops: (account: string) => {
return adminApi.get<LoginShopSelectionResponse>(`/auth/login-shops/${encodeURIComponent(account)}`)
},
logout: () => {
return adminApi.post<boolean>('/auth/logout')
},
2026-03-27 14:55:41 +08:00
switchShop: (shopId?: IdType) => {
return adminApi.post<AdminLoginResponse>('/auth/switch-shop', { shopId })
},
refreshToken: (refreshToken: string) => {
return adminApi.post<{ accessToken: string; refreshToken: string }>('/auth/refresh', { refreshToken })
}
}
2026-02-25 10:37:16 +08:00
export interface ObjectStorageFileVO {
2026-03-27 14:55:41 +08:00
id: IdType
fileName: string
fileSize: number
contentType: string
createTime: string
}
2026-03-26 11:41:38 +08:00
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'
}
})
},
2026-03-26 11:41:38 +08:00
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}`)
},
2026-03-27 14:55:41 +08:00
getSignedUrl: (id: IdType) => {
return adminApi.get<string>(`/object-storage-file/get-signed-url/${id}`)
}
}
export interface Tag {
2026-03-27 14:55:41 +08:00
id: IdType
tagName: string
textColor?: string
bgColor?: string
borderColor?: string
2026-03-27 14:55:41 +08:00
shopId?: IdType
shopName?: string
createTime: string
updateTime: string
}
export const adminTagApi = {
listAllTags: () => {
return adminApi.get<Tag[]>('/tag/list/all') as unknown as Promise<Tag[]>
},
2026-03-27 14:55:41 +08:00
listTagsByShopId: (shopId: IdType) => {
return adminApi.get<Tag[]>(`/tag/list/by-shop/${shopId}`) as unknown as Promise<Tag[]>
},
2026-03-27 14:55:41 +08:00
createTag: (data: { tagName: string; textColor?: string; bgColor?: string; borderColor?: string; shopId?: IdType }) => {
return adminApi.post<IdType>('/tag/create', data)
},
2026-03-27 14:55:41 +08:00
updateTag: (id: IdType, data: { tagName: string; textColor?: string; bgColor?: string; borderColor?: string; shopId?: IdType }) => {
return adminApi.put<boolean>(`/tag/update/${id}`, data)
},
2026-03-27 14:55:41 +08:00
deleteTag: (id: IdType) => {
return adminApi.delete<boolean>(`/tag/delete/${id}`)
}
}
export interface Artist {
2026-03-27 14:55:41 +08:00
id: IdType
nickname: string
account: string
avatar?: string
2026-03-27 14:55:41 +08:00
shopId?: IdType
shopName?: string
createTime: string
updateTime: string
}
export const adminArtistApi = {
2026-03-27 14:55:41 +08:00
listArtists: (shopId?: IdType) => {
const params: any = {}
if (shopId) {
params.shopId = shopId
}
return adminApi.get<Artist[]>('/user/list/artists', { params })
}
}
export interface Coupon {
2026-03-27 14:55:41 +08:00
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
2026-03-27 14:55:41 +08:00
shopId?: IdType
shopName?: string
couponScene?: string
requiredVipLevel?: string
autoMatch?: number
availableTags?: Tag[]
unavailableTags?: Tag[]
createTime: string
updateTime: string
}
export const adminCouponApi = {
2026-03-27 14:55:41 +08:00
listAllCoupons: (shopId?: IdType) => {
const params = shopId ? { shopId } : {}
return adminApi.get<Coupon[]>('/coupon/list/all', { params }) as unknown as Promise<Coupon[]>
},
createCoupon: (data: any) => {
2026-03-27 14:55:41 +08:00
return adminApi.post<IdType>('/coupon/create', data)
},
2026-03-27 14:55:41 +08:00
updateCoupon: (id: IdType, data: any) => {
return adminApi.put<boolean>(`/coupon/update/${id}`, data)
},
2026-03-27 14:55:41 +08:00
deleteCoupon: (id: IdType) => {
return adminApi.delete<boolean>(`/coupon/delete/${id}`)
2026-03-10 23:23:15 +08:00
},
distributeCoupon: (data: any) => {
return adminApi.post<boolean>('/coupon/distribute', null, { params: data })
2026-02-25 10:37:16 +08:00
}
}
2026-02-25 14:32:34 +08:00
export interface Product {
2026-03-27 14:55:41 +08:00
id: IdType
shopId: IdType
shopName?: string
2026-02-25 14:32:34 +08:00
title: string
description: string
price: number
approximateDuration?: string
tags?: string
2026-02-25 14:32:34 +08:00
tagList?: string[]
tagInfos?: any[]
imageFileIds?: string
imageUrls?: string[]
bookableArtists?: string
availableCoupons?: string
likeCount?: number
collectCount?: number
2026-02-25 14:32:34 +08:00
createTime: string
updateTime: string
}
export const adminProductApi = {
2026-03-27 14:55:41 +08:00
listProducts: (params: { page: number; size: number; keyword?: string; shopId?: IdType }) => {
return adminApi.get<{ list: Product[]; total: number; page: number; size: number }>('/product/list', { params })
2026-02-25 14:32:34 +08:00
},
listAllProducts: () => {
return adminApi.get<Product[]>('/product/list/all')
},
createProduct: (data: any) => {
2026-03-27 14:55:41 +08:00
return adminApi.post<IdType>('/product/create', data)
2026-02-25 14:32:34 +08:00
},
2026-03-27 14:55:41 +08:00
updateProduct: (id: IdType, data: any) => {
2026-02-27 14:20:20 +08:00
return adminApi.put<boolean>(`/product/update/${id}`, data)
2026-02-25 14:32:34 +08:00
},
2026-03-27 14:55:41 +08:00
deleteProduct: (id: IdType) => {
2026-02-27 14:20:20 +08:00
return adminApi.delete<boolean>(`/product/delete/${id}`)
2026-02-25 14:32:34 +08:00
}
}
2026-02-25 14:44:50 +08:00
export interface Shop {
2026-03-27 14:55:41 +08:00
id: IdType
2026-02-25 14:44:50 +08:00
shopName: string
description: string
address: string
businessHours: string
status?: number
coverImageFileId?: string
coverImageUrls?: string[]
imageFileIds?: string
2026-02-26 14:20:35 +08:00
imageUrls?: string[]
2026-02-25 14:44:50 +08:00
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
2026-02-25 14:44:50 +08:00
}
export const adminShopApi = {
2026-03-27 14:55:41 +08:00
listShops: (params: { page: number; size: number; keyword?: string; shopId?: IdType }) => {
return adminApi.get<ShopListResponse>('/shops/list', { params }) as unknown as Promise<ShopListResponse>
2026-02-25 14:44:50 +08:00
},
listAllShops: () => {
return adminApi.get<Shop[]>('/shops/list/all') as unknown as Promise<Shop[]>
},
2026-02-25 14:44:50 +08:00
createShop: (data: CreateShopRequest) => {
2026-03-27 14:55:41 +08:00
return adminApi.post<IdType>('/shops/create', data)
2026-02-25 14:44:50 +08:00
},
2026-03-27 14:55:41 +08:00
updateShop: (id: IdType, data: CreateShopRequest) => {
2026-02-27 14:20:20 +08:00
return adminApi.put<boolean>(`/shops/update/${id}`, data)
2026-02-25 14:44:50 +08:00
},
2026-03-27 14:55:41 +08:00
updateShopStatus: (id: IdType, status: number) => {
return adminApi.put<boolean>(`/shops/status/${id}`, { status })
},
2026-03-27 14:55:41 +08:00
deleteShop: (id: IdType) => {
2026-02-27 14:20:20 +08:00
return adminApi.delete<boolean>(`/shops/delete/${id}`)
2026-02-25 14:44:50 +08:00
}
}
export interface UserVO {
2026-03-27 14:55:41 +08:00
id: IdType
shopId?: IdType
shopName?: string
2026-03-27 14:55:41 +08:00
shopIds?: IdType[]
shopNames?: string[]
nickname: string
account: string
avatar: string
phone?: string
signature?: string
level?: string
type: number
2026-03-27 14:55:41 +08:00
vipId?: IdType
createTime: string
updateTime: string
status?: number
}
export interface PageResult<T> {
list: T[]
total: number
page: number
size: number
}
export const adminUserApi = {
2026-03-27 14:55:41 +08:00
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) => {
2026-03-27 14:55:41 +08:00
return adminApi.post<IdType>('/user/create', data)
},
2026-03-27 14:55:41 +08:00
updateUser: (id: IdType, data: any) => {
2026-02-27 14:20:20 +08:00
return adminApi.put<boolean>(`/user/update/${id}`, data)
},
2026-03-27 14:55:41 +08:00
deleteUser: (id: IdType) => {
2026-02-27 14:20:20 +08:00
return adminApi.delete<boolean>(`/user/delete/${id}`)
},
2026-03-27 14:55:41 +08:00
unbindUser: (id: IdType) => {
return adminApi.put<boolean>(`/user/unbind/${id}`, {})
},
2026-03-27 14:55:41 +08:00
updateUserStatus: (id: IdType, status: number) => {
return adminApi.put<boolean>(`/user/status/${id}`, { status })
},
2026-03-27 14:55:41 +08:00
resetPassword: (id: IdType) => {
return adminApi.post<string>(`/user/reset-password/${id}`)
},
getUserInfo: () => {
return adminApi.get<UserVO>('/user/info') as unknown as Promise<UserVO>
},
2026-03-27 14:55:41 +08:00
getUserAsset: (id: IdType) => {
return adminApi.get<UserAssetVO>(`/user/${id}/asset`) as unknown as Promise<UserAssetVO>
},
2026-03-27 14:55:41 +08:00
getUserBalanceHistory: (id: IdType) => {
return adminApi.get<UserBalanceHistoryItem[]>(`/user/${id}/balance/history`) as unknown as Promise<UserBalanceHistoryItem[]>
},
2026-03-27 14:55:41 +08:00
changeUserBalance: (id: IdType, data: AdminUserBalanceChangeRequest) => {
return adminApi.post<UserAssetVO>(`/user/${id}/balance/change`, data) as unknown as Promise<UserAssetVO>
},
2026-03-27 14:55:41 +08:00
overrideUserVip: (id: IdType, data: AdminUserVipOverrideRequest) => {
return adminApi.post<UserAssetVO>(`/user/${id}/vip/override`, data) as unknown as Promise<UserAssetVO>
},
2026-03-27 14:55:41 +08:00
recalculateUserVip: (id: IdType) => {
return adminApi.post<UserAssetVO>(`/user/${id}/vip/recalculate`) as unknown as Promise<UserAssetVO>
}
}
export interface UserAssetVO {
2026-03-27 14:55:41 +08:00
userId: IdType
nickname: string
balance: number
totalRechargeAmount: number
lastRechargeTime?: string
2026-03-27 14:55:41 +08:00
vipInfoId?: IdType
vipLevel: string
2026-03-27 14:55:41 +08:00
benefitId?: IdType
benefitInfo?: string
manualOverride: boolean
vipStartTime?: string
vipExpireTime?: string
}
export interface UserBalanceHistoryItem {
2026-03-27 14:55:41 +08:00
id: IdType
userId: IdType
userNickname?: string
amount: number
type?: string
currentBalance?: number
beforeBalance?: number
afterBalance?: number
changeScene?: string
2026-03-27 14:55:41 +08:00
relatedOrderId?: IdType
relatedOrderNo?: string
externalOrderNo?: string
2026-03-27 14:55:41 +08:00
operatorId?: IdType
remark?: string
changeTime: string
}
export interface AdminUserBalanceChangeRequest {
amount: number
changeScene: string
2026-03-27 14:55:41 +08:00
relatedOrderId?: IdType
externalOrderNo?: string
remark?: string
}
export interface AdminUserVipOverrideRequest {
vipLevel: string
remark?: string
}
export const userApi = adminUserApi
export interface OrderVO {
2026-03-27 14:55:41 +08:00
id: IdType
orderNo: string
2026-03-27 14:55:41 +08:00
userId: IdType
userNickname?: string
2026-03-27 14:55:41 +08:00
shopId: IdType
shopName?: string
2026-03-27 14:55:41 +08:00
artistId?: IdType
artistName?: string
totalAmount: number
discountAmount: number
payAmount: number
status: number
statusText?: string
remark?: string
createTime: string
updateTime: string
}
export const adminOrderApi = {
2026-03-27 14:55:41 +08:00
listOrders: (params: { page: number; size: number; keyword?: string; status?: number; shopId?: IdType }) => {
return adminApi.get<PageResult<OrderVO>>('/order/list', { params })
},
2026-03-27 14:55:41 +08:00
updateOrderStatus: (id: IdType, status: number) => {
return adminApi.put<boolean>(`/order/update-status/${id}`, { status })
}
}
export interface HotProductVO {
2026-03-27 14:55:41 +08:00
id: IdType
title: string
price: number
likeCount: number
collectCount: number
}
export interface RecentActivityVO {
2026-03-27 14:55:41 +08:00
id: IdType
type: string
title?: string
2026-02-26 17:54:18 +08:00
description: string
time: string
2026-03-10 23:23:15 +08:00
color?: string
2026-02-26 17:54:18 +08:00
}
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')
}
}
2026-03-04 15:42:43 +08:00
export interface NailArtistInfoVO {
2026-03-27 14:55:41 +08:00
id: IdType
userId: IdType
2026-03-04 15:42:43 +08:00
identity: string
experience: number
skills: string
rating: number
status: number
portfolio: string
nickname: string
2026-03-27 14:55:41 +08:00
shopId: IdType
2026-03-04 15:42:43 +08:00
shopName: string
}
export const adminNailArtistApi = {
listNailArtists: () => {
return adminApi.get<NailArtistInfoVO[]>('/nail-artist/list')
},
2026-03-27 14:55:41 +08:00
getNailArtistInfo: (userId: IdType) => {
2026-03-04 15:42:43 +08:00
return adminApi.get<NailArtistInfoVO>(`/nail-artist/get/${userId}`)
},
saveNailArtistInfo: (data: any) => {
return adminApi.post<NailArtistInfoVO>('/nail-artist/save', data)
}
}
export { adminApi }
2026-02-27 11:05:15 +08:00
export default adminApi